← Commit history
Merge PR #584: AI Flow 0.2.99: bottom-side fixes (#241), test plan nets (#242), PRs #122 and #124 (release-0.2.99 -> main) merge
Showing changes introduced by the merge (against its first parent).
27 files changed
+4254−107
Cargo.lock+10−10Cargo.toml+1−1bin/adom-aiflowcrates/adom-aiflow/src/export.rs+4−1crates/adom-aiflow/src/fields_review.rs+557crates/adom-aiflow/src/gate_eval.rs+3crates/adom-aiflow/src/impedance_cmd.rs+102−6crates/adom-aiflow/src/land_moves.rs+29crates/adom-aiflow/src/main.rs+331−20crates/adom-aiflow/src/si_checks.rs+583crates/adom-aiflow/src/stackup_presets.rs+400crates/adom-aiflow/src/testplan.rs+30−3crates/adom-aiflow/src/usb_power.rs+362crates/aiflow-copper/src/lib.rs+38−5crates/aiflow-router/src/drive.rs+2−2crates/aiflow-router/src/impedance.rs+1044−26crates/aiflow-router/src/lib.rs+29−3crates/aiflow-router/src/plane_under.rs+78−19docs/impedance.md+14−6docs/release-0.2.99.md+21package.json+1−1page.json+1−1skills/adom-aiflow/SKILL.md+1−1skills/aiflow-circuit-design/SKILL.md+1skills/aiflow-power-layout/SKILL.md+5−2tests/diff-pair-stackup-workflow.py+367tests/si-emc-pdn-workflow.py+240Cargo.lock+10−10@@ -4,7 +4,7 @@ version = 4 [[package]] name = "adom-aiflow"-version = "0.2.98"+version = "0.2.99" dependencies = [ "aiflow-analyze", "aiflow-board",@@ -25,7 +25,7 @@ dependencies = [ [[package]] name = "aiflow-analyze"-version = "0.2.98"+version = "0.2.99" dependencies = [ "aiflow-board", "serde",@@ -35,7 +35,7 @@ dependencies = [ [[package]] name = "aiflow-board"-version = "0.2.98"+version = "0.2.99" dependencies = [ "roxmltree", "serde",@@ -44,7 +44,7 @@ dependencies = [ [[package]] name = "aiflow-bridge"-version = "0.2.98"+version = "0.2.99" dependencies = [ "aiflow-board", "serde",@@ -53,7 +53,7 @@ dependencies = [ [[package]] name = "aiflow-copper"-version = "0.2.98"+version = "0.2.99" dependencies = [ "aiflow-board", "aiflow-grid",@@ -63,7 +63,7 @@ dependencies = [ [[package]] name = "aiflow-grid"-version = "0.2.98"+version = "0.2.99" dependencies = [ "aiflow-board", "serde",@@ -72,7 +72,7 @@ dependencies = [ [[package]] name = "aiflow-place"-version = "0.2.98"+version = "0.2.99" dependencies = [ "aiflow-board", "serde",@@ -81,7 +81,7 @@ dependencies = [ [[package]] name = "aiflow-pours"-version = "0.2.98"+version = "0.2.99" dependencies = [ "aiflow-board", "aiflow-copper",@@ -91,7 +91,7 @@ dependencies = [ [[package]] name = "aiflow-router"-version = "0.2.98"+version = "0.2.99" dependencies = [ "aiflow-board", "aiflow-grid",@@ -101,7 +101,7 @@ dependencies = [ [[package]] name = "aiflow-run"-version = "0.2.98"+version = "0.2.99" dependencies = [ "serde", "serde_json",
Cargo.toml+1−1@@ -14,7 +14,7 @@ members = [ ] [workspace.package]-version = "0.2.98"+version = "0.2.99" edition = "2021" license = "MIT" repository = "https://wiki.adom.inc/adom/adom-aiflow"
bin/adom-aiflow⋯ 1 unchanged line ⋯
crates/adom-aiflow/src/export.rs+4−1@@ -730,6 +730,7 @@ mod tests { std::fs::create_dir_all(&dir).unwrap(); let board = dir.join("demo.kicad_pcb"); std::fs::write(&board, BOARD).unwrap();+ let fake_seq = std::cell::Cell::new(0usize); let fake = |skip: &str| { let script = format!(r#"#!/bin/sh out=""; kind="$3"; prev=""; [ "$2" = "drc" ] && kind=drc@@ -743,7 +744,9 @@ pos) printf 'Ref,Val,Package,PosX,PosY,Rot,Side\nJ1,HDR,H,10,-10,0,top\nR1,10k,R drc) [ -f "$(dirname "$0")/drc.json" ] && cp "$(dirname "$0")/drc.json" "$out";; esac "#);- let p = dir.join("kicad-cli");+ let n = fake_seq.get();+ fake_seq.set(n + 1);+ let p = dir.join(format!("kicad-cli-{n}")); std::fs::write(&p, script).unwrap(); std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap(); p.display().to_string()
crates/adom-aiflow/src/fields_review.rsadded+557@@ -0,0 +1,557 @@+//! Adom Fields optional-module auto-selection, external connector detection, finding extraction,+//! high-impact assumption surfacing, and readiness report integration (issues #214, #215).++use std::collections::{BTreeMap, BTreeSet};+use std::path::Path;++use aiflow_board::Board;+use aiflow_router::impedance;+use serde_json::{json, Value};++#[derive(Debug, Clone)]+pub struct ModulePlan {+ /// Modules to pass via `--with <csv>` (e.g. ["si", "emc", "esd"]).+ pub modules: Vec<String>,+ /// Human-readable reason each module was triggered.+ pub reasons: BTreeMap<String, Vec<String>>,+ /// External edge connectors detected on the board when `spec.external` is absent.+ pub detected_external: Vec<String>,+ /// True when `spec.fieldsModules` explicitly set the module list.+ pub override_used: bool,+}++impl ModulePlan {+ pub fn with_csv(&self) -> Option<String> {+ if self.modules.is_empty() { None } else { Some(self.modules.join(",")) }+ }++ pub fn describe(&self) -> String {+ if self.modules.is_empty() {+ return if self.override_used {+ "core only (spec.fieldsModules override)".into()+ } else {+ "core only (no optional module triggers)".into()+ };+ }+ let parts: Vec<String> = self.modules.iter().map(|m| {+ let why = self.reasons.get(m).map(|v| v.join("; ")).unwrap_or_default();+ if why.is_empty() { m.clone() } else { format!("{m} ({why})") }+ }).collect();+ parts.join(", ")+ }+}++fn is_usb_data_net(u: &str) -> bool {+ if !u.contains("USB") && u != "D+" && u != "D-" {+ return false;+ }+ if ["CC", "VBUS", "SBU", "SHIELD", "PWR", "5V", "GND", "EN", "FLT", "FAULT", "_ID"]+ .iter().any(|k| u.contains(k))+ {+ return false;+ }+ ["DP", "DN", "DM", "D+", "D-", "USB_P", "USB_N", "USBD+", "USBD-", "TX", "RX", "SS"]+ .iter().any(|k| u.contains(k))+}++fn has_fast_bus_net(board: &Board) -> Vec<String> {+ let mut found = BTreeSet::new();+ // KiCad 10 (NetFormat::Name) has an empty net_table; always check board.nets.keys() as well.+ for n in board.nets.keys().chain(board.net_table.values()) {+ let u = n.trim_start_matches('/').to_ascii_uppercase();+ let u = u.rsplit('/').next().unwrap_or(&u);+ if is_usb_data_net(u)+ || ["SDIO", "QSPI", "OSPI", "ETH", "RMII", "RGMII", "MIPI", "HDMI", "PCIE", "DDR"]+ .iter().any(|k| u.contains(k))+ {+ found.insert(n.clone());+ }+ }+ found.into_iter().collect()+}++/// Auto-detect external cable / user-accessible connectors (USB, RJ45, Ethernet, barrel jack,+/// screw terminals, coax/SMA, HDMI, CAN connector, XT30/XT60) when `spec.external` is absent.+/// Generic internal pin headers (J*) are not auto-classified unless explicitly listed in `spec.external`.+pub fn detect_external_connectors(board: &Board, spec: &Value) -> Vec<String> {+ if let Some(arr) = spec["external"].as_array().filter(|a| !a.is_empty()) {+ return arr.iter().filter_map(|v| {+ v.as_str().map(str::to_string).or_else(|| v["ref"].as_str().map(str::to_string))+ }).collect();+ }+ let mut out = BTreeSet::new();+ for fp in board.root.find_all("footprint") {+ let reference = fp.find_all("property")+ .find(|p| p.atom(1) == Some("Reference"))+ .and_then(|p| p.atom(2))+ .unwrap_or("");+ if reference.is_empty() { continue; }+ let value = fp.find_all("property")+ .find(|p| p.atom(1) == Some("Value"))+ .and_then(|p| p.atom(2))+ .unwrap_or("");+ let fp_name = fp.atom(1).unwrap_or("");+ let txt = format!("{reference} {value} {fp_name}").to_ascii_uppercase();+ let is_conn_ref = reference.starts_with('J') || reference.starts_with("CN") || reference.starts_with("CON") || reference.starts_with('P') || reference.starts_with('X');+ let explicit_ext = ["USB", "RJ45", "ETHERNET", "BARREL", "DC_JACK", "DCJACK", "SCREW", "TERMINAL", "COAX", "SMA", "HDMI", "CAN_CONN", "XT30", "XT60", "PHOENIX"]+ .iter().any(|k| txt.contains(k));+ if is_conn_ref && explicit_ext {+ out.insert(reference.to_string());+ }+ }+ out.into_iter().collect()+}++/// Select `--with` modules for `adom-fields analyze` from the board and spec.+/// Honors `spec.fieldsModules` (`["si", "pdn"]`, `[]`, `"none"`, `"core"`, or `"all"`) when set;+/// otherwise turns on only the modules each board actually needs.+pub fn recommended_modules(board: &Board, spec: &Value) -> ModulePlan {+ let ext_conns = detect_external_connectors(board, spec);+ let detected_external = if spec["external"].as_array().is_some_and(|a| !a.is_empty()) {+ Vec::new()+ } else {+ ext_conns.clone()+ };++ // Spec override: `fieldsModules`+ if let Some(ov) = spec.get("fieldsModules").filter(|v| !v.is_null()) {+ let mut reasons: BTreeMap<String, Vec<String>> = BTreeMap::new();+ let mut modules: Vec<String> = Vec::new();+ let allowed = ["si", "noise", "emc", "esd", "pdn", "rf"];+ if let Some(arr) = ov.as_array() {+ for item in arr {+ if let Some(s) = item.as_str() {+ let m = s.trim().to_ascii_lowercase();+ if allowed.contains(&m.as_str()) && !modules.contains(&m) {+ reasons.entry(m.clone()).or_default().push("spec.fieldsModules override".into());+ modules.push(m);+ }+ }+ }+ } else if let Some(s) = ov.as_str() {+ match s.trim().to_ascii_lowercase().as_str() {+ "none" | "core" | "" => {}+ "all" => {+ for m in ["si", "noise", "emc", "esd", "pdn"] {+ reasons.entry(m.into()).or_default().push("spec.fieldsModules override".into());+ modules.push(m.into());+ }+ }+ other => {+ for part in other.split(',') {+ let m = part.trim().to_ascii_lowercase();+ if allowed.contains(&m.as_str()) && !modules.contains(&m) {+ reasons.entry(m.clone()).or_default().push("spec.fieldsModules override".into());+ modules.push(m);+ }+ }+ }+ }+ }+ return ModulePlan { modules, reasons, detected_external, override_used: true };+ }++ let mut reasons: BTreeMap<String, Vec<String>> = BTreeMap::new();+ let mut add = |m: &str, why: String| {+ reasons.entry(m.to_string()).or_default().push(why);+ };++ let imp_targets = impedance::targets(spec).unwrap_or_default();+ let has_clocks = spec["clocks"].as_object().is_some_and(|o| !o.is_empty())+ || spec["clocks"].as_array().is_some_and(|a| !a.is_empty());+ let has_length_groups = spec["lengthGroups"].as_object().is_some_and(|o| !o.is_empty())+ || spec["lengthGroups"].as_array().is_some_and(|a| !a.is_empty());+ let has_sensitive = spec["sensitiveNets"].as_array().is_some_and(|a| !a.is_empty());+ let fast_nets = has_fast_bus_net(board);+ let has_switching = spec["switching"].as_object().is_some_and(|o| !o.is_empty())+ || spec["switchNodes"].as_array().is_some_and(|a| !a.is_empty());+ let has_pdn_trigger = spec["sources"].as_object().is_some_and(|o| !o.is_empty())+ || spec["decoupling"].as_object().is_some_and(|o| !o.is_empty())+ || spec["rails"].as_object().is_some_and(|o| !o.is_empty())+ || has_switching;++ // SI triggers (#214): only when controlled impedance, clocks, length groups, or high-speed buses exist+ if !imp_targets.is_empty() {+ add("si", format!("{} impedance target(s)", imp_targets.len()));+ }+ if has_clocks {+ add("si", "spec declares clocks".into());+ }+ if has_length_groups {+ add("si", "spec declares lengthGroups".into());+ }+ if !fast_nets.is_empty() {+ let preview = fast_nets.iter().take(4).cloned().collect::<Vec<_>>().join(", ");+ add("si", format!("high-speed bus nets ({preview})"));+ }++ // Noise trigger (#214): only when an aggressor (switching/clocks) coexists with victims (sensitiveNets/SI nets)+ if (has_switching || has_clocks) && (has_sensitive || !imp_targets.is_empty() || !fast_nets.is_empty()) {+ let agg = if has_switching && has_clocks { "switching + clocks" } else if has_switching { "switching converter" } else { "clocks" };+ add("noise", format!("{agg} with sensitive or high-speed nets"));+ } else if has_sensitive && (!imp_targets.is_empty() || !fast_nets.is_empty()) {+ add("noise", "sensitiveNets alongside high-speed nets".into());+ }++ // EMC trigger (#215): only when switching converters, clocks, or external cable ports exist+ if has_switching {+ add("emc", "switching converter declared".into());+ }+ if has_clocks {+ add("emc", "spec declares clocks".into());+ }+ if !ext_conns.is_empty() {+ let preview = ext_conns.iter().take(4).cloned().collect::<Vec<_>>().join(", ");+ add("emc", format!("external connector(s) ({preview})"));+ add("esd", format!("external connector(s) ({preview})"));+ }++ // PDN trigger (#215): only when switching converter, sources, rails, or decoupling targets are declared+ if has_pdn_trigger {+ let why = if has_switching { "switching converter" } else { "power sources/rails declared" };+ add("pdn", why.into());+ }++ let order = ["si", "noise", "emc", "esd", "pdn"];+ let modules: Vec<String> = order.iter().filter(|&&m| reasons.contains_key(m)).map(|s| s.to_string()).collect();+ ModulePlan { modules, reasons, detected_external, override_used: false }+}++/// If `spec.external` is absent and external edge connectors were detected on the board, return a+/// patched copy of `spec` with `"external"` populated (for invoking `adom-fields analyze`).+#[allow(dead_code)]+pub fn spec_with_detected_external(spec: &Value, detected: &[String]) -> Option<Value> {+ if detected.is_empty() || spec["external"].as_array().is_some_and(|a| !a.is_empty()) {+ return None;+ }+ let mut copy = spec.clone();+ copy["external"] = json!(detected);+ Some(copy)+}++const SI_KINDS: &[&str] = &["impedance", "diff-impedance", "reflection", "length-skew", "via-stub", "stackup-adjacent-signals", "stackup-far-reference", "no-reference"];+const NOISE_KINDS: &[&str] = &["crosstalk", "cavity-resonance"];+const EMC_KINDS: &[&str] = &["stitching-gap", "ground-loop-risk", "clock-outer-layer", "clock-near-connector", "edge-signal", "input-filter-cutoff"];+const ESD_KINDS: &[&str] = &["esd-unprotected", "io-unfiltered"];+const PDN_KINDS: &[&str] = &["pdn-impedance", "hot-plug-overshoot", "input-filter-stability", "decoupling-missing", "decoupling-far", "ground-offset", "ground-island"];++fn issue_text(issue: &Value) -> String {+ let kind = issue["kind"].as_str().unwrap_or("finding");+ let sev = issue["severity"].as_str().unwrap_or("info");+ let net = issue["net"].as_str().or(issue["part"].as_str()).unwrap_or("");+ let detail = issue["what"].as_str()+ .or(issue["message"].as_str())+ .or(issue["summary"].as_str())+ .or(issue["title"].as_str())+ .or(issue["fix"].as_str())+ .unwrap_or("");+ let prefix = if net.is_empty() { format!("[{sev}] {kind}") } else { format!("[{sev}] {kind} ({net})") };+ if detail.is_empty() { prefix } else { format!("{prefix}: {detail}") }+}++/// Parse an `adom-fields` `fields.json` report and surface:+/// - skipped / not-run modules whose trigger fired on this board;+/// - SI, noise, EMC/compliance, ESD, and PDN/decoupling findings;+/// - `review.inputs` items with `matters == "high"`.+pub fn summarize_fields(fields: &Value, board: &Board, spec: &Value) -> Value {+ let plan = recommended_modules(board, spec);++ // 1. Triggered modules that were NOT run+ let mut ran: BTreeSet<String> = BTreeSet::new();+ for m in fields["modules"]["ran"].as_array().into_iter().flatten() {+ if let Some(name) = m["module"].as_str().or(m.as_str()) {+ ran.insert(name.to_ascii_lowercase());+ }+ }+ let mut not_run = Vec::new();+ // Read Fields' own skipped / notRun entries first+ for key in ["skipped", "notRun"] {+ for s in fields["modules"][key].as_array().into_iter().flatten() {+ let name = s["module"].as_str().or(s["name"].as_str()).or(s.as_str()).unwrap_or("").to_ascii_lowercase();+ if name.is_empty() || ran.contains(&name) { continue; }+ let fields_why = s["whyItMayMatter"].as_str().or(s["why"].as_str());+ if fields_why.is_some() || plan.reasons.contains_key(&name) {+ let why = fields_why.map(str::to_string).unwrap_or_else(|| plan.reasons.get(&name).map(|v| v.join("; ")).unwrap_or_default());+ not_run.push(json!({"module": name, "why": why, "turnOn": format!("--with {name}")}));+ }+ }+ }+ // Also catch any recommended module completely absent from both ran and skipped (older fields.json)+ for m in &plan.modules {+ if !ran.contains(m) && !not_run.iter().any(|x| x["module"] == m.as_str()) {+ not_run.push(json!({+ "module": m,+ "why": plan.reasons.get(m).map(|v| v.join("; ")).unwrap_or_default(),+ "turnOn": format!("--with {m}"),+ }));+ }+ }++ // 2. Categorized findings from `issues[]`+ let mut si_findings = Vec::new();+ let mut noise_findings = Vec::new();+ let mut emc_findings = Vec::new();+ let mut esd_findings = Vec::new();+ let mut pdn_findings = Vec::new();++ for iss in fields["issues"].as_array().into_iter().flatten() {+ let kind = iss["kind"].as_str().unwrap_or("");+ let line = issue_text(iss);+ if SI_KINDS.contains(&kind) {+ si_findings.push(line);+ } else if NOISE_KINDS.contains(&kind) {+ noise_findings.push(line);+ } else if EMC_KINDS.contains(&kind) {+ emc_findings.push(line);+ } else if ESD_KINDS.contains(&kind) {+ esd_findings.push(line);+ } else if PDN_KINDS.contains(&kind) {+ pdn_findings.push(line);+ }+ }++ // 3. Structured SI review blocks (reference status, reflections > 15%, viaStubs, lengthGroups, stackup)+ for net in fields["review"]["impedance"]["nets"].as_array().into_iter().flatten() {+ let rstat = net["reference"].as_str().or(net["referenceStatus"].as_str()).unwrap_or("");+ if rstat.eq_ignore_ascii_case("mixed reference") || rstat.eq_ignore_ascii_case("no reference") {+ let n = net["net"].as_str().unwrap_or("?");+ let msg = format!("[high] impedance reference ({n}): {rstat}");+ if !si_findings.contains(&msg) { si_findings.push(msg); }+ }+ }+ for refl in fields["review"]["reflections"].as_array().into_iter().flatten() {+ let over = refl["overshootPercent"].as_f64().unwrap_or(0.0);+ if over > 15.0 {+ let n = refl["net"].as_str().unwrap_or("?");+ let rs = refl["seriesOhm"].as_f64().map(|r| format!(" (suggested series R {r:.0} ohm)")).unwrap_or_default();+ let msg = format!("[medium] reflection ({n}): {over:.1}% overshoot{rs}");+ if !si_findings.iter().any(|s| s.contains("reflection") && s.contains(n)) {+ si_findings.push(msg);+ }+ }+ }++ // 4. EMC compliance verdicts & toSixDb cheapest fixes+ let mut compliance_alerts = Vec::new();+ let comp = &fields["review"]["compliance"];+ for channel in ["radiated", "conducted", "antenna"] {+ if let Some(v) = comp[channel]["verdict"].as_str() {+ if v == "likely fail" || v == "at risk" {+ let margin = comp[channel]["marginDb"].as_f64().map(|m| format!(" ({m:+.1} dB)")).unwrap_or_default();+ compliance_alerts.push(format!("EMC {channel}: {v}{margin}"));+ }+ }+ }+ let to_six_db: Vec<String> = comp["toSixDb"].as_array().into_iter().flatten().filter_map(|x| {+ x.as_str().map(str::to_string).or_else(|| {+ let what = x["fix"].as_str().or(x["action"].as_str()).or(x["what"].as_str())?;+ let db = x["gainDb"].as_f64().or(x["db"].as_f64()).map(|d| format!(" (+{d:.1} dB)")).unwrap_or_default();+ Some(format!("{what}{db}"))+ })+ }).collect();+ if !compliance_alerts.is_empty() {+ let fixes = if to_six_db.is_empty() { String::new() } else { format!("; toSixDb fixes: {}", to_six_db.join(", ")) };+ emc_findings.push(format!("[high] compliance: {}{fixes}", compliance_alerts.join("; ")));+ }++ // 5. High-impact assumed inputs (`review.inputs.items` where `matters == "high"`)+ let mut high_assumptions = Vec::new();+ let input_items = fields["review"]["inputs"]["items"].as_array()+ .or_else(|| fields["review"]["inputs"].as_array());+ for item in input_items.into_iter().flatten() {+ if item["matters"].as_str() == Some("high") {+ let key = item["specKey"].as_str().unwrap_or("?");+ let used = &item["used"];+ let affects = item["affects"].as_str().unwrap_or("");+ let ds = item["datasheetField"].as_str().unwrap_or("");+ high_assumptions.push(json!({+ "specKey": key,+ "used": used,+ "affects": affects,+ "datasheetField": ds,+ }));+ }+ }++ let mut summary_lines = Vec::new();+ for nr in ¬_run {+ summary_lines.push(format!("module not run: {} ({}) -> re-run with {}", nr["module"].as_str().unwrap_or(""), nr["why"].as_str().unwrap_or(""), nr["turnOn"].as_str().unwrap_or("")));+ }+ summary_lines.extend(si_findings.iter().cloned());+ summary_lines.extend(noise_findings.iter().cloned());+ summary_lines.extend(emc_findings.iter().cloned());+ summary_lines.extend(esd_findings.iter().cloned());+ summary_lines.extend(pdn_findings.iter().cloned());+ for a in &high_assumptions {+ summary_lines.push(format!(+ "high-impact assumption: {} = {} ({})",+ a["specKey"].as_str().unwrap_or("?"),+ a["used"],+ a["datasheetField"].as_str().unwrap_or("")+ ));+ }++ json!({+ "ranModules": ran.into_iter().collect::<Vec<_>>(),+ "recommendedModules": plan.modules,+ "detectedExternal": plan.detected_external,+ "notRun": not_run,+ "si": si_findings,+ "noise": noise_findings,+ "emc": emc_findings,+ "esd": esd_findings,+ "pdn": pdn_findings,+ "complianceAlerts": compliance_alerts,+ "toSixDb": to_six_db,+ "highImpactAssumptions": high_assumptions,+ "lines": summary_lines,+ })+}++/// Run `adom-fields report --fields <fields_dir> --out <out_md>` and return the parsed readiness JSON+/// (along with one-line area summaries for `finish`).+pub fn run_fields_report(fields_dir: &Path, out_md: &Path) -> Result<(Value, Vec<String>), String> {+ if let Some(parent) = out_md.parent() {+ let _ = std::fs::create_dir_all(parent);+ }+ let st = std::process::Command::new("adom-fields")+ .args(["report", "--fields", &fields_dir.display().to_string(), "--out", &out_md.display().to_string()])+ .output()+ .map_err(|e| format!("could not run adom-fields report: {e}"))?;+ if !st.status.success() {+ return Err(format!("adom-fields report exited {}: {}", st.status, String::from_utf8_lossy(&st.stderr).trim()));+ }+ let out_json = out_md.with_extension("json");+ let raw = std::fs::read_to_string(&out_json).map_err(|e| format!("{}: {e}", out_json.display()))?;+ let doc: Value = serde_json::from_str(&raw).map_err(|e| format!("{}: {e}", out_json.display()))?;+ let mut lines = Vec::new();+ for area in doc["areas"].as_array().into_iter().flatten() {+ let title = area["title"].as_str().or(area["id"].as_str()).unwrap_or("?");+ let status = area["status"].as_str().unwrap_or("?");+ let why = area["why"].as_str().unwrap_or("");+ lines.push(if why.is_empty() { format!(" {title}: {status}") } else { format!(" {title}: {status} ({why})") });+ }+ Ok((doc, lines))+}++#[cfg(test)]+mod tests {+ use super::*;++ fn sample_4l_board() -> Board {+ let pcb = concat!(+ "(kicad_pcb (version 20241229) (generator \"test\") (general (thickness 1.6)) ",+ "(layers (0 \"F.Cu\" signal) (4 \"In1.Cu\" signal) (6 \"In2.Cu\" signal) (2 \"B.Cu\" signal) (25 \"Edge.Cuts\" user)) ",+ "(net 0 \"\") (net 1 \"VBUS\") (net 2 \"GND\") (net 3 \"USB_DP\") (net 4 \"USB_DN\") (net 5 \"SPI_CLK\") ",+ "(footprint \"Connector_USB:USB_C\" (layer \"F.Cu\") (at 2 15) (property \"Reference\" \"J1\") (property \"Value\" \"USB-C\") ",+ "(pad \"1\" smd rect (at 0 0) (size 0.8 0.5) (layers \"F.Cu\") (net 1 \"VBUS\"))) ",+ "(gr_rect (start 0 0) (end 40 30) (layer \"Edge.Cuts\") (stroke (width 0.1) (type solid))))"+ );+ Board::from_text("t.kicad_pcb", pcb.to_string()).unwrap()+ }++ #[test]+ fn recommended_modules_is_selective_and_honors_fields_modules_override() {+ // Simple 4L board with generic pin header and loads only: no extra modules turned on by default+ let simple_pcb = concat!(+ "(kicad_pcb (version 20241229) (generator \"test\") (general (thickness 1.6)) ",+ "(layers (0 \"F.Cu\" signal) (4 \"In1.Cu\" signal) (6 \"In2.Cu\" signal) (2 \"B.Cu\" signal) (25 \"Edge.Cuts\" user)) ",+ "(net 0 \"\") (net 1 \"VIN\") (net 2 \"GND\") (net 3 \"LED1\") ",+ "(footprint \"Connector_PinHeader:PinHeader_1x02\" (layer \"F.Cu\") (at 2 15) (property \"Reference\" \"J1\") (property \"Value\" \"HDR\") ",+ "(pad \"1\" thru_hole circle (at 0 0) (size 1.6 1.6) (drill 1.0) (layers \"*.Cu\") (net 1 \"VIN\"))) ",+ "(gr_rect (start 0 0) (end 40 30) (layer \"Edge.Cuts\") (stroke (width 0.1) (type solid))))"+ );+ let simple = Board::from_text("simple.kicad_pcb", simple_pcb.to_string()).unwrap();+ let simple_plan = recommended_modules(&simple, &json!({"loads": {"VIN": {"from": "J1.1", "to": "R1.1", "amps": 0.1}}}));+ assert!(simple_plan.modules.is_empty(), "simple board must stay core-only: {:?}", simple_plan.modules);+ assert!(simple_plan.describe().contains("core only"), "{}", simple_plan.describe());++ // USB + impedance + sources + clocks board turns on the needed modules with reasons+ let b = sample_4l_board();+ let spec = json!({+ "loads": {"VBUS": {"from": "J1.1", "to": "U1.1", "amps": 0.5}},+ "sources": {"VBUS": ["J1"]},+ "clocks": {"SPI_CLK": {"freqHz": 24000000}},+ "impedanceTargets": {"USB": {"pair": ["USB_DP", "USB_DN"], "targetDiffOhms": 90}}+ });+ let plan = recommended_modules(&b, &spec);+ assert_eq!(plan.modules, vec!["si", "noise", "emc", "esd", "pdn"]);+ assert_eq!(plan.detected_external, vec!["J1"]);+ assert!(plan.describe().contains("si (") && plan.describe().contains("emc ("));+ let patched = spec_with_detected_external(&spec, &plan.detected_external).unwrap();+ assert_eq!(patched["external"], json!(["J1"]));++ // Spec override: fieldsModules+ let ov_empty = recommended_modules(&b, &json!({"fieldsModules": []}));+ assert!(ov_empty.modules.is_empty() && ov_empty.override_used);+ let ov_subset = recommended_modules(&b, &json!({"fieldsModules": ["si", "pdn"]}));+ assert_eq!(ov_subset.modules, vec!["si", "pdn"]);+ assert!(ov_subset.override_used && ov_subset.describe().contains("fieldsModules override"));++ // KiCad 10 name-only net format (empty net_table): detects USB_DP/USB_DM, ignores USB_CC1 alone+ let k10_usb_data = concat!(+ "(kicad_pcb (version 20260101) (generator \"pcbnew\") ",+ "(layers (0 \"F.Cu\" signal) (2 \"B.Cu\" signal) (25 \"Edge.Cuts\" user)) ",+ "(footprint \"Connector_USB:USB_C\" (layer \"F.Cu\") (at 5 10) (property \"Reference\" \"J1\") (property \"Value\" \"USB-C\") ",+ "(pad \"A6\" smd rect (at 0 -0.25) (size 0.5 0.3) (layers \"F.Cu\") (net \"USB_DP\")) ",+ "(pad \"A7\" smd rect (at 0 0.25) (size 0.5 0.3) (layers \"F.Cu\") (net \"USB_DM\"))) ",+ "(gr_rect (start 0 0) (end 40 20) (layer \"Edge.Cuts\") (stroke (width 0.1) (type solid))))"+ );+ let b_k10 = Board::from_text("k10.kicad_pcb", k10_usb_data.to_string()).unwrap();+ assert!(b_k10.net_table.is_empty(), "KiCad 10 uses NetFormat::Name");+ let p_k10 = recommended_modules(&b_k10, &json!({}));+ assert!(p_k10.modules.contains(&"si".to_string()), "KiCad 10 USB_DP/USB_DM must trigger si: {:?}", p_k10.modules);++ let k10_cc_only = concat!(+ "(kicad_pcb (version 20260101) (generator \"pcbnew\") ",+ "(layers (0 \"F.Cu\" signal) (2 \"B.Cu\" signal) (25 \"Edge.Cuts\" user)) ",+ "(footprint \"Connector_USB:USB_C\" (layer \"F.Cu\") (at 5 10) (property \"Reference\" \"J1\") (property \"Value\" \"USB-C\") ",+ "(pad \"A5\" smd rect (at 0 0) (size 0.5 0.3) (layers \"F.Cu\") (net \"USB_CC1\"))) ",+ "(gr_rect (start 0 0) (end 40 20) (layer \"Edge.Cuts\") (stroke (width 0.1) (type solid))))"+ );+ let b_cc = Board::from_text("k10-cc.kicad_pcb", k10_cc_only.to_string()).unwrap();+ let p_cc = recommended_modules(&b_cc, &json!({}));+ assert!(!p_cc.modules.contains(&"si".to_string()), "USB_CC1 alone must not trigger si: {:?}", p_cc.modules);+ }++ #[test]+ fn summarize_fields_surfaces_not_run_compliance_findings_and_high_assumptions() {+ let b = sample_4l_board();+ let spec = json!({+ "loads": {"VBUS": {"from": "J1.1", "to": "U1.1", "amps": 0.5}},+ "impedanceTargets": {"USB": {"pair": ["USB_DP", "USB_DN"], "targetDiffOhms": 90}}+ });+ let fields = json!({+ "modules": {+ "ran": [{"module": "emc"}, {"module": "pdn"}],+ "skipped": [{"module": "si", "whyItMayMatter": "4-layer board with USB"}]+ },+ "issues": [+ {"kind": "pdn-impedance", "severity": "medium", "net": "VBUS", "what": "5x target"},+ {"kind": "esd-unprotected", "severity": "low", "part": "J1", "what": "no TVS within 3 mm"},+ {"kind": "stitching-gap", "severity": "low", "what": "edge stitch gap 22 mm"},+ {"kind": "decoupling-far", "severity": "medium", "net": "VBUS", "what": "C1 is 12 mm from U1"}+ ],+ "review": {+ "compliance": {+ "radiated": {"verdict": "likely fail", "marginDb": -8.4},+ "toSixDb": [{"fix": "add common-mode choke on J1", "gainDb": 12.0}]+ },+ "inputs": {+ "items": [+ {"matters": "high", "specKey": "copperUm", "used": 35, "affects": "density", "datasheetField": "fab copper weight"},+ {"matters": "low", "specKey": "ambientC", "used": 25, "affects": "offset", "datasheetField": "room temp"}+ ]+ }+ }+ });+ let s = summarize_fields(&fields, &b, &spec);+ assert!(s["notRun"].as_array().unwrap().iter().any(|x| x["module"] == "si"), "{s}");+ assert!(s["notRun"].as_array().unwrap().iter().any(|x| x["module"] == "esd"), "{s}");+ assert_eq!(s["highImpactAssumptions"].as_array().unwrap().len(), 1);+ assert_eq!(s["highImpactAssumptions"][0]["specKey"], "copperUm");+ assert!(!s["complianceAlerts"].as_array().unwrap().is_empty(), "{s}");+ assert_eq!(s["pdn"].as_array().unwrap().len(), 2);+ assert_eq!(s["esd"].as_array().unwrap().len(), 1);+ }+}
crates/adom-aiflow/src/gate_eval.rs+3@@ -104,6 +104,9 @@ pub fn evaluate(r: &Run, b: &Board, plan_v: &Value, routed: &Path, base: &Value, if let Ok(rb) = rb() { s["vippo"] = crate::vippo::audit_vippo(&rb, &spec_g); s["viaHygiene"] = crate::vippo::via_hygiene(&rb, &spec_g);+ let ret = crate::si_checks::return_via_audit(&rb, &spec_g);+ let xt = crate::si_checks::crosstalk_3w_audit(&rb, &spec_g);+ s["siChecks"] = json!({"returnVias": ret, "crosstalk3W": xt}); } Ok(GateEval { s, pu, pu_issues, sw_issues, dec, mech, stairs, quality }) }
crates/adom-aiflow/src/impedance_cmd.rs+102−6@@ -72,7 +72,14 @@ pub fn table_lines(p: &Plan) -> Vec<String> { let mut geo = match &r["dielectricMm"] { Value::Array(a) => format!("{} between {} / {} mm", r["structure"].as_str().unwrap_or(""), a[0], a[1]), h => format!("{} over {h} mm", r["structure"].as_str().unwrap_or("")) }; if !r["coplanarGapMm"].is_null() { geo.push_str(&format!(" with a {} pour {} mm beside it (assumed: pour it at that clearance, stitched to the plane)", r["coplanarNet"].as_str().unwrap_or("GND"), r["coplanarGapMm"])); } let size = if r["widthMm"].is_null() { String::new() } else if r["gapMm"].is_null() { format!("width {} mm", r["widthMm"]) } else { format!("width {} mm gap {} mm", r["widthMm"], r["gapMm"]) };- let state = if r["ok"] == true { format!("{size} -> {} ohm", r["ohms"]) } else { format!("REFUSED: {}", r["why"].as_str().unwrap_or("")) };+ let mask_note = if r["ok"] == true && !r["solderMaskShiftPercent"].is_null() {+ if r["solderMaskModelled"] == true {+ format!(" (with solder mask; bare {} ohm, {}%)", r["bareOhms"], r["solderMaskShiftPercent"])+ } else {+ format!(" (bare copper; with solder mask ~{} ohm, {}%)", r["withSolderMaskOhms"], r["solderMaskShiftPercent"])+ }+ } else { String::new() };+ let state = if r["ok"] == true { format!("{size} -> {} ohm{mask_note}", r["ohms"]) } else { format!("REFUSED: {}", r["why"].as_str().unwrap_or("")) }; out.push(format!("{t} {what} on {} ({geo}, er {}, copper {} um): {state}", r["layer"].as_str().unwrap_or(""), r["epsilonR"], r["copperUm"])); } out@@ -139,10 +146,46 @@ fn copper(board: &Board, plan: Option<&Value>, targets: &[Target]) -> (Vec<aiflo pub fn check(board: &Board, spec: &Value, board_path: &str, plan: Option<&Value>) -> Result<Option<(Plan, Vec<Value>)>, String> { let Some(p) = self::plan(board, spec, board_path)? else { return Ok(None) }; let (tracks, vias, from) = copper(board, plan, &p.targets);- let rows = p.targets.iter().map(|t| { let ground = t.coplanar.as_ref().map(|c| imp::GroundCopper::of(board, &c.net)).unwrap_or_default(); let mut c = imp::check_target(t, &p.stack, &tracks, &vias, &board.pads, &ground); c["copperFrom"] = json!(t.nets.iter().map(|n| from.get(n).copied().unwrap_or("")).collect::<Vec<_>>()); c }).collect();+ // Include all board vias (plus any planned vias) so GND stitching vias near pair layer transitions are visible+ let mut all_vias = board.vias();+ if let Some(pl) = plan {+ let (_, pv) = imp::plan_tracks(pl, board);+ all_vias.extend(pv);+ }+ let rows = p.targets.iter().map(|t| {+ let ground = t.coplanar.as_ref().map(|c| imp::GroundCopper::of(board, &c.net)).unwrap_or_default();+ let mut c = imp::check_target_with_vias(t, &p.stack, &tracks, &vias, &all_vias, &board.pads, &ground);+ c["copperFrom"] = json!(t.nets.iter().map(|n| from.get(n).copied().unwrap_or("")).collect::<Vec<_>>());+ c+ }).collect(); Ok(Some((p, rows))) } +/// Build an explicit Fields handoff object (`impedance` map + `signals.differentialPairs`) for all+/// declared `impedanceTargets` pairs (including `USB_DP`/`USB_DN` and `USB_D+`/`USB_D-`) so+/// `adom-fields --with si` never silently drops a pair over net-naming conventions.+pub fn fields_pair_handoff(p: &Plan, rows: &[Value], spec: &Value) -> Value {+ let mut imp_map = serde_json::Map::new();+ let mut sig_pairs = Vec::new();+ for (t, row) in p.targets.iter().zip(rows) {+ if t.diff {+ imp_map.insert(format!("{}/{}", t.nets[0], t.nets[1]), json!(t.ohms));+ if t.coplanar.is_none() {+ let layer = row["lengthByLayerMm"].as_object()+ .and_then(|m| m.iter().max_by(|a, b| a.1.as_f64().unwrap_or(0.0).total_cmp(&b.1.as_f64().unwrap_or(0.0))).map(|(k, _)| k.as_str()))+ .or(t.layer.as_deref())+ .unwrap_or("F.Cu");+ if let Some(entry) = signals_entry(t, &p.stack, layer, spec) {+ sig_pairs.push(entry);+ }+ }+ } else {+ imp_map.insert(t.nets[0].clone(), json!(t.ohms));+ }+ }+ json!({"impedance": imp_map, "signals": {"differentialPairs": sig_pairs}})+}+ /// The plane net on a layer (spec `planes` {net: layer}), else GND, for a Fields Signals definition. fn reference_net(spec: &Value, layer: &str) -> String { spec.get("planes").and_then(|v| v.as_object()).and_then(|m| m.iter().find(|(_, l)| l.as_str() == Some(layer)).map(|(n, _)| n.clone())).unwrap_or_else(|| "GND".into())@@ -193,6 +236,19 @@ pub fn compare_fields(rows: &mut [Value], targets: &[Target], fields: &Value) -> if compared && (z - t.ohms).abs() > tol { fail.push(format!("Fields cross-section solve gives {z:.1} ohm differential, outside {} +-{} %", t.ohms, t.tolerance)); } notes.push(format!("{}: closed form {} ohm, Fields 2-D solve {z:.1} ohm (with solder mask)", t.label(), row["ohms"])); }+ } else if fields["review"]["impedance"]["nets"].is_array() {+ // Fields --with si auto-discovers pairs by _P/_N, +/-, DP/DM and can miss pairs such as USB_DP/USB_DN.+ // Surface the per-net 2-D Z0 values instead of leaving the cross-section silently blank.+ let net_z: Vec<(String, f64)> = t.nets.iter().filter_map(|net| {+ let n = fields["review"]["impedance"]["nets"].as_array()?.iter().find(|n| n["net"] == net.as_str())?;+ let main = n["segments"].as_array()?.iter().max_by(|a, b| a["lengthMm"].as_f64().unwrap_or(0.0).total_cmp(&b["lengthMm"].as_f64().unwrap_or(0.0)))?;+ Some((net.clone(), main["z0"].as_f64()?))+ }).collect();+ if !net_z.is_empty() {+ f.insert("crossSectionNets".into(), json!(net_z.iter().map(|(n, z)| json!({"net": n, "z0": z})).collect::<Vec<_>>()));+ let desc = net_z.iter().map(|(n, z)| format!("{n} {z:.1} ohm")).collect::<Vec<_>>().join(", ");+ notes.push(format!("{}: Fields --with si did not auto-pair {} / {} (per-net 2-D Z0: {desc}); add signals.differentialPairs to spec so Fields screens the pair explicitly", t.label(), t.nets[0], t.nets[1]));+ } } } else if let Some(n) = fields["review"]["impedance"]["nets"].as_array().into_iter().flatten().find(|n| n["net"] == t.nets[0].as_str()) { let z: Vec<f64> = n["segments"].as_array().into_iter().flatten().filter_map(|s| s["z0"].as_f64()).collect();@@ -237,8 +293,31 @@ pub fn same_input_fields(path: &Path, board_file: &str, spec_file: &str) -> Resu pub fn check_lines(rows: &[Value], targets: &[Target]) -> Vec<String> { rows.iter().zip(targets).map(|(c, t)| { let mut s = format!("{} {}: {} ohm on {}", t.label(), c["status"].as_str().unwrap_or(""), c["ohms"], c["lengthByLayerMm"]);- if t.diff { s.push_str(&format!(", gap {} mm, coupled {}% of each net, skew {} mm", c["gapMm"], c["coupledPercent"], c["skewMm"])); }+ if t.diff {+ s.push_str(&format!(", gap {} mm, coupled {}% of each net, skew {} mm", c["gapMm"], c["coupledPercent"], c["skewMm"]));+ if let Some(pm) = c.get("phaseMatching").filter(|v| v.is_object()) {+ s.push_str(&format!(", max phase skew {} mm (run {} mm)", pm["maxSkewMm"], pm["worstRunMm"]));+ }+ } s.push_str(&format!(", uncontrolled {} mm (copper from the {})", c["uncontrolledMm"], c["copperFrom"].as_array().and_then(|a| a.first()).and_then(|v| v.as_str()).unwrap_or("board")));+ if let Some(d) = c.get("discontinuities").filter(|v| v["count"].as_u64().unwrap_or(0) > 0) {+ let n_of = |k: &str| d[k].as_array().map(|a| a.len()).unwrap_or(0);+ let mut parts = Vec::new();+ for (k, lbl) in [("offAngle", "off-45"), ("rightAngles", "90-deg"), ("acute", "acute"), ("wiggles", "wiggle"), ("gapJumps", "gap-jump")] {+ let cnt = n_of(k);+ if cnt > 0 { parts.push(format!("{cnt} {lbl}")); }+ }+ if !parts.is_empty() { s.push_str(&format!(", discontinuities: {}", parts.join(", "))); }+ }+ if let Some(vt) = c.get("viaTransitions").filter(|v| v.is_object()) {+ s.push_str(&format!(", via pairs: {}", vt["pairedCount"]));+ let recs: Vec<&str> = vt["recommendations"].as_array().into_iter().flatten().filter_map(|x| x.as_str()).collect();+ if !recs.is_empty() { s.push_str(&format!(" ({})", recs.join("; "))); }+ }+ if let Some(st) = c.get("stubs").and_then(|v| v.as_array()).filter(|a| !a.is_empty()) {+ let desc: Vec<String> = st.iter().map(|x| format!("{} {} mm", x["pad"].as_str().unwrap_or("?"), x["stubMm"])).collect();+ s.push_str(&format!(", stubs: {}", desc.join(", ")));+ } if let Some(cp) = c.get("coplanar") { let on = |k: &str| cp[k].as_array().map(|a| a.iter().filter_map(|x| x.as_str()).collect::<Vec<_>>().join(", ")).unwrap_or_default(); if !on("measuredOn").is_empty() { s.push_str(&format!(", {} pour beside it measured on {} at {} mm (target gap {} mm; {} mm of each net with none within reach)", cp["net"].as_str().unwrap_or(""), on("measuredOn"), cp["measuredGapMm"], cp["gapMm"], cp["withoutGroundMm"])); }@@ -380,13 +459,15 @@ pub fn analyze_run(r: &mut aiflow_run::Run, dir: &Path, spec: &Value, board_file Err(e) => (Vec::new(), format!("Fields not compared: {e}")), } } else { (Vec::new(), "no Fields report: closed form only".to_string()) };+ let conf = crate::stackup_presets::confirmation(spec); let pass = rows.iter().all(|c| c["status"] == "pass"); r.stage_end("analyze-impedance", Some(json!({"pass": pass})), None);- r.outcome("analyze-impedance", json!({"pass": pass, "results": rows, "fieldReport": fields_file, "fieldNote": field_note, "stackup": p.stack.sources, "method": METHOD}));+ r.outcome("analyze-impedance", json!({"pass": pass, "results": rows, "fieldReport": fields_file, "fieldNote": field_note, "stackup": p.stack.sources, "stackupStatus": conf.status, "stackupId": conf.stackup_id, "fieldsHandoff": fields_pair_handoff(&p, &rows, spec), "method": METHOD})); let _ = r.save(); let mut lines = check_lines(&rows, &p.targets); lines.extend(notes); let mut hints = vec![format!("fields: {field_note}"), METHOD.to_string()];+ if let Some(adv) = crate::stackup_presets::finish_advisory(spec) { hints.push(adv); } if p.targets.iter().any(|t| t.coplanar.is_some()) { hints.push(METHOD_COPLANAR.into()); } if let Some(h) = signals_hint(&p, &rows, spec) { hints.push(h); } if pass { Ok((format!("impedance analysis passed:\n{}", lines.join("\n")), hints)) } else {@@ -410,17 +491,32 @@ pub fn finish_check(board: &Board, spec: &Value, board_file: &str, outcome: Opti } } -pub const METHOD: &str = "Closed forms (Hammerstad-Jensen microstrip, Wheeler and Cohn stripline, Garg-Bahl coupled microstrip), quasi-static, no solder mask (it lowers an outer trace by about 1 to 3 %), no etch trapezoid or Dk tolerance; within 0.2 % (microstrip, stripline), 3.4 % (offset stripline) and 2.6 % (pairs) of a 2-D field solve on the reference cases (docs/impedance.md). A screen for routing, not an impedance-controlled fab order: the fab's own stackup calculation is.";+pub const METHOD: &str = "Closed forms (Hammerstad-Jensen microstrip, Wheeler and Cohn stripline, Garg-Bahl coupled microstrip, Ghione-Naldi GCPW), quasi-static, with outer-layer solder-mask correction when spec.solderMask or a stackup preset is active (matching adom-fields --with si within 2 %; bare-copper specs report the expected mask shift beside each outer row); no etch trapezoid or Dk tolerance. A screen for routing, not an impedance-controlled fab order: confirm final widths and gaps with the fab's own stackup calculation."; pub const METHOD_COPLANAR: &str = "Grounded coplanar rows (coplanarGapMm, coplanarGround): the conformal mapping of Ghione and Naldi (Wadell 3.4.3), the pair by the same maps in odd and even mode, with the copper sidewalls' parallel-plate term e0 t / g; they read 0.6 to 4.1 % high against a 2-D field solve over g/h <= 1, s/h <= 2 and w >= 4 copper thicknesses (refused outside it; docs/impedance.md). They assume the pour runs beside the whole line at that gap and is stitched to the plane under it with vias; KiCad pours at the larger of the zone's clearance (spec pours[].clearance, default 0.2 mm) and the nets' own, so set it to the gap. `impedance check` measures the gap where the ground net has a filled zone on the layer and says when it only assumes it. Adom Fields models these lines as microstrip without the pour, so its values are reported, not compared."; /// `adom-aiflow impedance table|check`: on a run (its current board and spec) or on --board and --spec. pub fn command(action: &str, board_file: &str, spec: &Value, plan_path: Option<&str>, as_json: bool) -> Reply {+ if action == "stackups" {+ if as_json {+ let list: Vec<Value> = crate::stackup_presets::PRESETS.iter().map(|p| json!({+ "id": p.id, "fab": p.fab, "layers": p.layers, "boardThicknessMm": p.board_thickness_mm,+ "dielectricMm": p.dielectric_mm, "epsilonRByGap": p.epsilon_r_by_gap, "copperUm": p.copper_um,+ "solderMask": {"thicknessMm": p.solder_mask_mm, "epsilonR": p.solder_mask_er}, "summary": p.summary+ })).collect();+ println!("{}", serde_json::to_string_pretty(&json!({"stackups": list})).unwrap());+ }+ return Ok((format!("published fab stackup presets ({}):\n{}", crate::stackup_presets::PRESETS.len(), crate::stackup_presets::list_lines().join("\n")), vec![+ "Bind a preset to your spec and KiCad board with `adom-aiflow rules use --profile <fab> --layers <n> --stackup <id>`.".into(),+ "After confirming trace widths with the fabricator's calculator, set `fab.stackupStatus` to \"fab-confirmed\" and record `fab.confirmedSource` in spec.json.".into(),+ ]));+ } let board = Board::load(board_file).map_err(|e| (e, vec![]))?; match action { "table" => { let p = match plan(&board, spec, board_file) { Ok(Some(p)) => p, Ok(None) => return Err(("the spec names no impedance target".into(), vec![HINT_SPEC.into()])), Err(e) => return Err((format!("impedance: {e}"), vec![HINT_SPEC.into()])) };- if as_json { println!("{}", serde_json::to_string_pretty(&json!({"stackup": p.stack.sources, "fab": {"minWidthMm": p.fab.min_width, "minSpaceMm": p.fab.min_space, "source": p.fab.source}, "rows": p.rows, "method": METHOD})).unwrap()); }+ let conf = crate::stackup_presets::confirmation(spec);+ if as_json { println!("{}", serde_json::to_string_pretty(&json!({"stackup": p.stack.sources, "stackupStatus": conf.status, "stackupId": conf.stackup_id, "fab": {"minWidthMm": p.fab.min_width, "minSpaceMm": p.fab.min_space, "source": p.fab.source}, "rows": p.rows, "method": METHOD})).unwrap()); } let mut lines = table_lines(&p); let mut route_lines = Vec::new(); for t in &p.targets {
crates/adom-aiflow/src/land_moves.rs+29@@ -69,6 +69,21 @@ fn eagle_rotation(deg: f64) -> String { format!("MR{d}") } +/// Issue #241: the moved parts whose side differs between the run's board and the live KiCad board (a+/// `kicad_placement_state` reply): a flip made on the desktop that the run never adopted. The run's copy then+/// places the part mirrored to what KiCad will do, so a clean `place check` lands overlapping or outside.+pub fn kicad_side_clash(moves: &Value, run_board: &Board, live_state: &Value) -> Vec<String> {+ let d = live_state.get("data").filter(|d| d.is_object()).unwrap_or(live_state);+ let live: HashMap<String, String> = d["footprints"].as_array().into_iter().flatten()+ .filter_map(|f| Some((f["ref"].as_str()?.to_string(), f["side"].as_str()?.to_string()))).collect();+ let mut out = Vec::new();+ for r in moves.as_object().map(|o| o.keys().cloned().collect::<Vec<_>>()).unwrap_or_default() {+ let (Some(fp), Some(side)) = (run_board.footprints.get(&r), live.get(&r)) else { continue };+ if &fp.layer != side { out.push(format!("{r}: {} in the run's board, {side} on the live board", fp.layer)); }+ }+ out+}+ #[cfg(test)] mod tests { use super::*;@@ -163,4 +178,18 @@ mod tests { assert_eq!(mv["U1"]["rotation"], 90.0); assert_eq!(mv["U2"]["rotation"], 45.0); }++ /// Issue #241: a part flipped on the desktop (B.Cu live) but still F.Cu in the run's board is named.+ #[test]+ fn a_flip_the_run_did_not_adopt_is_named() {+ let b = Board::from_text("t.kicad_pcb", r#"(kicad_pcb (layers (0 "F.Cu" signal) (31 "B.Cu" signal))+ (footprint "H" (layer "F.Cu") (at 10 10) (property "Reference" "J1") (pad "1" thru_hole rect (at 0 0) (size 1.7 1.7) (drill 1) (layers "*.Cu")))+ (footprint "R" (layer "B.Cu") (at 20 10) (property "Reference" "R1") (pad "1" smd rect (at 0 0) (size 1 1) (layers "B.Cu")))+ (gr_rect (start 0 0) (end 30 20) (layer "Edge.Cuts")))"#.to_string()).unwrap();+ let live = serde_json::json!({"success": true, "footprints": [{"ref": "J1", "side": "B.Cu"}, {"ref": "R1", "side": "B.Cu"}]});+ let moves = serde_json::json!({"J1": {"x": 12, "y": 10, "rotation": 90}, "R1": {"x": 22, "y": 10}});+ assert_eq!(super::kicad_side_clash(&moves, &b, &live), vec!["J1: F.Cu in the run's board, B.Cu on the live board".to_string()]);+ assert!(super::kicad_side_clash(&serde_json::json!({"R1": {"x": 1, "y": 1}}), &b, &live).is_empty());+ } }+
crates/adom-aiflow/src/main.rs+331−20@@ -44,6 +44,9 @@ mod programming; mod project_lib; mod netclasses; mod vippo;+mod si_checks;+mod fields_review;+mod usb_power; /// 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");@@ -66,6 +69,7 @@ mod pagedir; mod zone_ownership; mod pour_adopt; mod gate_eval;+mod stackup_presets; mod route_quality; mod route_variants; mod impedance_cmd;@@ -185,14 +189,16 @@ enum Cmd { Review { #[arg(value_parser = ["mechanical", "wiring"])] kind: String, #[arg(long)] input: Option<String>, /// wiring only: also run audit-glb on the exported assembly #[arg(long)] glb: Option<String> }, Testplan { #[arg(value_parser = ["check"])] action: String, #[arg(long)] tests: Option<String>, #[arg(long)] netlist: Option<String>, #[arg(long)] add: bool },- Rules { #[arg(value_parser = ["use", "install", "check", "list", "sync"])] action: String, #[arg(long)] profile: Option<String>, #[arg(long)] board: Option<String>, /// replace an existing .kicad_dru+ Rules { #[arg(value_parser = ["use", "install", "check", "list", "sync", "stackup"])] action: String, #[arg(long)] profile: Option<String>, #[arg(long)] board: Option<String>, /// replace an existing .kicad_dru #[arg(long)] force: bool, /// copper layers (default: the profile's -<n>L suffix, else the board's copper layer count, else 2) #[arg(long)] layers: Option<u32>, /// `rules use`: a named variant of the fab's pack on adom/pcb-design-rules (`<fab>-<n>L-<variant>`, e.g. circuit-forge-strict); the published pack when omitted #[arg(long)] variant: Option<String>, /// `rules use`: the human's own preferences, a JSON file {"silkMinTextHeight": {"mm": 0.6}, "minTraceWidth": {"mm": 0.2}}: kept in the spec (fab.preferences) and checked on the board as warnings that never block (not written into the KiCad rules, where a preference would replace the fab's limit) #[arg(long)] prefs: Option<String>,- /// `rules sync` / `rules check`: spec.json path when running outside a run+ /// `rules use` / `rules stackup`: bind a published fab stackup preset (e.g. JLC04161H-7628, JLC04161H-3313, JLC06161H-3313, JLC02161H) into spec.json and the KiCad board physical stackup+ #[arg(long)] stackup: Option<String>,+ /// `rules sync` / `rules check` / `rules stackup`: spec.json path when running outside a run #[arg(long)] spec: Option<String>, /// `rules sync`: write the Altium PCB design rules JSON payload to this path #[arg(long)] altium_out: Option<String> },@@ -323,7 +329,7 @@ enum Cmd { /// The finish line, as a report card: what passed, what is still open and what to do next (it never refuses) Finish, /// Impedance targets (spec impedanceTargets, or adom-fields' impedance map): `table` prints the trace width (and pair gap) for each target on every copper layer from the stackup, refusing a layer the target cannot reach within the fab's minimums; `check` judges the board's copper (or --plan) against them. On the run's board and spec, or on --board and --spec.- Impedance { #[arg(value_parser = ["table", "check"])] action: String, #[arg(long)] board: Option<String>, #[arg(long)] spec: Option<String>, #[arg(long)] plan: Option<String>, #[arg(long)] json: bool },+ Impedance { #[arg(value_parser = ["table", "check", "stackups"])] action: String, #[arg(long)] board: Option<String>, #[arg(long)] spec: Option<String>, #[arg(long)] plan: Option<String>, #[arg(long)] json: bool }, /// Record a change to the spec's budgets (loads, hot, rise limits, switch-node length, net widths, fab) after placement began. Budgets are frozen at placement; this is the only way to move one, and it stays on the record. SpecAmend { #[arg(long)] why: String }, /// Accept one item `finish` (or a `step`) refused, on purpose, when the check rather than the board is wrong: `deviate "<item>" --why "..."` (the item as the refusal names it, e.g. "gate", "heatsink vias", "step routing"). Recorded, bound to the saved board and spec, and listed in the finish summary; `--list` shows them, `--clear` removes one.@@ -4394,9 +4400,11 @@ fn main() { } let mut hints = order_hints; // issue #217: board-wide VIPPO audit on export + IPC-4761 Type VII fab note when approved+ // issue #213: when impedanceTargets is present, emit impedance-stackup.md and .json fab notes let mut vippo_unapproved: Vec<String> = Vec::new(); if let Ok(b_exp) = Board::load(&board_path) {- let va = vippo::audit_vippo(&b_exp, &spec_soft(&r));+ let sp_exp = spec_soft(&r);+ let va = vippo::audit_vippo(&b_exp, &sp_exp); report["vippo"] = va.clone(); if va["pass"] == false { vippo_unapproved = va["findings"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect();@@ -4404,6 +4412,18 @@ fn main() { if let Some(fs) = report["files"].as_array_mut() { fs.push(json!(vp.display().to_string())); } hints.push(format!("IPC-4761 Type VII VIPPO fab note written: {}", vp.display())); }+ match stackup_presets::write_export_table(&out_dir, &b_exp, &sp_exp, &board_path) {+ Ok(Some((imp_doc, imp_md, imp_json))) => {+ report["impedanceStackup"] = imp_doc;+ if let Some(fs) = report["files"].as_array_mut() {+ fs.push(json!(imp_md.display().to_string()));+ fs.push(json!(imp_json.display().to_string()));+ }+ hints.push(format!("Controlled impedance fab note written: {} (include with fab order and request impedance test coupons).", imp_md.display()));+ }+ Ok(None) => {}+ Err(e) => hints.push(format!("Controlled impedance fab note not written: {e}")),+ } write_json(&out_dir.join("export-check.json"), &report); r.outcome("export", report.clone()); }@@ -4435,7 +4455,8 @@ fn main() { if report.get("files").is_some() { let mut hints = vec![fill_hint, "Fix the board or its footprint attributes (DNP, exclude from BOM/position files) and run `export` again. Until then, tell the human which files do not match the board and why before anything is ordered.".into()]; if let Ok(b_exp) = Board::load(&board_path) {- let va = vippo::audit_vippo(&b_exp, &spec_soft(&r));+ let sp_exp = spec_soft(&r);+ let va = vippo::audit_vippo(&b_exp, &sp_exp); report["vippo"] = va.clone(); if va["pass"] == false { for vf in va["findings"].as_array().into_iter().flatten().filter_map(Value::as_str) {@@ -4445,6 +4466,14 @@ fn main() { if let Some(fs) = report["files"].as_array_mut() { fs.push(json!(vp.display().to_string())); } hints.push(format!("IPC-4761 Type VII VIPPO fab note written: {}", vp.display())); }+ if let Ok(Some((imp_doc, imp_md, imp_json))) = stackup_presets::write_export_table(&out_dir, &b_exp, &sp_exp, &board_path) {+ report["impedanceStackup"] = imp_doc;+ if let Some(fs) = report["files"].as_array_mut() {+ fs.push(json!(imp_md.display().to_string()));+ fs.push(json!(imp_json.display().to_string()));+ }+ hints.push(format!("Controlled impedance fab note written: {} (include with fab order and request impedance test coupons).", imp_md.display()));+ } write_json(&out_dir.join("export-check.json"), &report); } r.outcome("export", report.clone());@@ -5466,6 +5495,15 @@ fn main() { } } }+ // issue #241: a KiCad part flipped on the desktop and never adopted lands mirrored to what pack planned+ if aiflow_bridge::fusion::doc_of(&rb).is_none() && !rb.is_empty() && mv.as_object().is_some_and(|o| !o.is_empty()) {+ let live = br.call("kicad_placement_state", &json!({"filePath": rb}));+ let clash = land_moves::kicad_side_clash(&mv, &b, &live);+ if !clash.is_empty() {+ err(&format!("nothing landed: {} part(s) are on a different side in the run's board and on the live board (flipped on the desktop, not adopted):\n {}", clash.len(), clash.join("\n ")),+ &["Save the live board, `adom-aiflow adopt-board --board <saved .kicad_pcb>`, then `place pack` and `place check` again: they plan each part on the side it is really on.".into()]);+ }+ } let outside = aiflow_place::parts_outside(landed_board.as_ref().unwrap_or(&b), &edge_overhang::refs(&overhang)); if !outside.is_empty() { note(&format!("{} part(s) will be outside the board outline after this landing:\n {}", outside.len(), outside.iter().map(|(_, w)| w.as_str()).collect::<Vec<_>>().join("\n ")), &[aiflow_place::OUTSIDE_HINT.into()]);@@ -5539,7 +5577,7 @@ fn main() { if rules.wide.is_empty() { "none".to_string() } else { rules.wide.iter().map(|(n, w)| format!("{n} {w:?}")).collect::<Vec<_>>().join(", ") }, if rules.mid.is_empty() { "none".to_string() } else { rules.mid.iter().map(|(n, w)| format!("{n} {w:?}")).collect::<Vec<_>>().join(", ") }, if spec.get("track").is_none() && spec.get("trackWidth").is_some() { " (track from the spec's trackWidth)" } else if spec.get("track").is_none() { " (track is the router default: the spec names no track)" } else { "" });- let regions = aiflow_router::plane_under::regions(&b, &rules.plane_under).unwrap_or_else(|e| err(&format!("spec.planeUnder: {e}"), &["Each entry needs a layer (F.Cu or B.Cu), the net that owns the region, and \"around\" (parts or pads on this board, grown by \"margin\", default 1.0 mm) or a \"polygon\".".into()]));+ let regions = aiflow_router::plane_under::regions(&b, &rules.plane_under).unwrap_or_else(|e| err(&format!("spec.planeUnder: {e}"), &["Each entry needs a copper layer on this board (F.Cu, B.Cu, In1.Cu, In2.Cu, ...), the net that owns the region, and \"around\" (parts or pads on this board, grown by \"margin\", default 1.0 mm) or a \"polygon\".".into()])); if spec.get("planeUnder").is_some() && regions.len() != spec["planeUnder"].as_array().map(|a| a.len()).unwrap_or(1) { err("spec.planeUnder has an entry that does not parse", &["Use {\"layer\": \"B.Cu\", \"net\": \"GND\", \"around\": [\"U1\", \"C2\"], \"margin\": 1.0} or {\"layer\": ..., \"net\": ..., \"polygon\": [[x, y], ...]}.".into()]); }@@ -6089,14 +6127,151 @@ fn main() { let t = thread(&cli); if !ack.is_empty() && what != "current" { err("--ack acknowledges a current-density peak: `analyze current --ack [email protected] --why ...`", &[]); } let mut r = load_run(&cli);+ 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+ let live = live_board(&r, &cli, &dir);+ let board_now = match &live { Some((_, k)) => Board::load(k).unwrap_or_else(|e| err(&e, &[])), None => board_of(&r) };+ let spec = spec_of(&r);+ let req = requirements_of(&r);+ let targets = aiflow_router::impedance::targets(&spec).unwrap_or_default();+ let ref_plane = si_checks::reference_plane_audit(&board_now, &spec, &targets);+ let ret_vias = si_checks::return_via_audit(&board_now, &spec);+ let xtalk = si_checks::crosstalk_3w_audit(&board_now, &spec);+ let fields_file = fields.clone().unwrap_or_else(|| dir.join("fields/fields.json"));+ let fields_doc = if fields_file.is_file() { aiflow_analyze::fields_report::load(&fields_file).ok() } else { None };+ let inrush = usb_power::check_usb_inrush(&board_now, &spec, fields_doc.as_ref());+ let budget = usb_power::check_load_budget(&spec, &req);+ let fields_sum = fields_doc.as_ref().map(|f| fields_review::summarize_fields(f, &board_now, &spec));+ let mut readiness_doc = Value::Null;+ let mut readiness_lines = Vec::new();+ if let Some(fdir) = fields_file.parent().filter(|_| fields_file.is_file()) {+ if let Ok((rd, rlines)) = fields_review::run_fields_report(fdir, &dir.join("design-review/readiness.md")) {+ readiness_doc = rd;+ readiness_lines = rlines;+ }+ }+ let plan_mod = fields_review::recommended_modules(&board_now, &spec);+ let strict = spec["strictSi"] == true || spec["si"]["strict"] == true;+ let mut si_findings: Vec<String> = Vec::new();+ if ref_plane["hasFilledZones"] == true && ref_plane["pass"] == false {+ si_findings.extend(ref_plane["findings"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string));+ }+ if ret_vias["pass"] == false {+ si_findings.extend(ret_vias["findings"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string));+ }+ if xtalk["pass"] == false {+ si_findings.extend(xtalk["findings"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string));+ }+ if inrush["pass"] == false {+ si_findings.extend(inrush["findings"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string));+ }+ if budget["pass"] == false {+ si_findings.extend(budget["findings"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string));+ }+ let passed = if strict { si_findings.is_empty() } else { true };+ let outcome_v = json!({+ "pass": passed,+ "strict": strict,+ "findings": si_findings,+ "referencePlane": ref_plane,+ "returnVias": ret_vias,+ "crosstalk3W": xtalk,+ "usbInrush": inrush,+ "loadBudget": budget,+ "recommendedFieldsModules": plan_mod.modules,+ "recommendedFieldsModulesWhy": plan_mod.reasons,+ "detectedExternal": plan_mod.detected_external,+ "fieldsReview": fields_sum,+ "fieldsReadiness": readiness_doc,+ });+ r.outcome("analyze-si", outcome_v);+ r.save().unwrap();+ let mut hints = Vec::new();+ if let Some(csv) = plan_mod.with_csv() {+ hints.push(format!("Fields modules selected for this board: {} (override with spec \"fieldsModules\": [...] or []). Run: `adom-fields analyze --board {} --spec {} --with {csv} --out {}`", plan_mod.describe(), r.current_board(), r.data["spec"].as_str().unwrap_or("spec.json"), dir.join("fields").display()));+ } else {+ hints.push(format!("Fields modules selected for this board: {} (override with spec \"fieldsModules\": [\"si\",\"emc\",...]).", plan_mod.describe()));+ }+ if !plan_mod.detected_external.is_empty() {+ hints.push(format!("Detected external edge connector(s) not listed in spec.external: {:?} (add \"external\": {:?} to spec.json so adom-fields --with esd,emc checks TVS protection and cable emissions).", plan_mod.detected_external, plan_mod.detected_external));+ }+ if let Some(fs) = &fields_sum {+ if let Some(ran) = fs["ranModules"].as_array() {+ let ran_list: Vec<&str> = ran.iter().filter_map(Value::as_str).collect();+ hints.push(format!("Fields modules ran in {}: {}", fields_file.display(), if ran_list.is_empty() { "core only".into() } else { ran_list.join(", ") }));+ }+ for l in fs["lines"].as_array().into_iter().flatten().filter_map(Value::as_str) {+ hints.push(format!("fields: {l}"));+ }+ }+ if !readiness_lines.is_empty() {+ hints.push(format!("Certification readiness ({}):\n{}", dir.join("design-review/readiness.md").display(), readiness_lines.join("\n")));+ }+ if ref_plane["checked"].as_u64().unwrap_or(0) > 0 && ref_plane["hasFilledZones"] == false {+ hints.push("Reference-plane coverage not checked yet because the board has no filled zones; pour/fill zones and run `analyze si` again.".into());+ }+ if !si_findings.is_empty() {+ if strict {+ err(&format!("SI / power-integrity check (strict) found {} issue(s):\n {}", si_findings.len(), si_findings.join("\n ")), &hints);+ }+ hints.push("To make SI / power-integrity findings fail this step, set \"strictSi\": true in spec.json.".into());+ findings(&format!("SI / power-integrity check found {} finding(s):\n {}", si_findings.len(), si_findings.join("\n ")), &hints);+ }+ ok(&format!("SI / power-integrity check clean (ref planes: {}, return vias checked: {}, crosstalk pairs: {}, USB inrush: {}, load budget: ok; fields modules: {})", ref_plane["checked"], ret_vias["checkedVias"], xtalk["pairs"].as_array().map(|a| a.len()).unwrap_or(0), if inrush["checked"] == true { format!("{} uF", inrush["nominalUf"]) } else { "n/a".into() }, plan_mod.describe()), &hints);+ return;+ } if what == "impedance" {- // issue #52: closed-form impedance of the landed copper, Fields Signals beside it+ // issue #52 + #214: closed-form impedance of the landed copper, real reference-plane copper check, Fields Signals beside it let live = live_board(&r, &cli, &dir); let copper = live.as_ref().map(|l| l.1.clone()).unwrap_or_else(|| r.current_board()); let solved = live.as_ref().map(|l| l.0.clone()).unwrap_or_else(|| r.current_board()); let planp = plan.clone().or_else(|| r.outcomes().get("route").and_then(|o| o["plan"].as_str()).map(str::to_string)); let spec = spec_of(&r);- match impedance_cmd::analyze_run(&mut r, &dir, &spec, &copper, &solved, planp.as_deref(), fields.as_deref()) { Ok((m, h)) => ok(&m, &h), Err((m, h)) => err(&m, &h) }+ let strict_ref = spec["strictSi"] == true || spec["si"]["strict"] == true;+ let ref_check = Board::load(&copper).ok().and_then(|b| {+ let ts = aiflow_router::impedance::targets(&spec).ok()?;+ if ts.is_empty() { None } else { Some(si_checks::reference_plane_audit(&b, &spec, &ts)) }+ });+ match impedance_cmd::analyze_run(&mut r, &dir, &spec, &copper, &solved, planp.as_deref(), fields.as_deref()) {+ Ok((mut m, mut h)) => {+ if let Some(rc) = &ref_check {+ if rc["hasFilledZones"] == true && rc["pass"] == false {+ let rf: Vec<String> = rc["findings"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect();+ if let Some(o) = r.data["outcomes"].get_mut("analyze-impedance") {+ if strict_ref { o["pass"] = json!(false); }+ o["referencePlane"] = rc.clone();+ let _ = r.save();+ }+ h.push("Keep a solid unbroken reference plane (>= 90% coverage, no split > 1.0 mm) on the adjacent layer under every controlled-impedance trace.".into());+ if strict_ref {+ err(&format!("impedance reference-plane check (strict) failed:\n {}", rf.join("\n ")), &h);+ }+ h.push("To make reference-plane gaps fail `analyze impedance`, set \"strictSi\": true in spec.json.".into());+ findings(&format!("{m}\nreference plane findings:\n {}", rf.join("\n ")), &h);+ } else if rc["hasFilledZones"] == false {+ h.push("Reference-plane copper not yet verified (board has no filled zones); fill zones and re-run `analyze impedance`.".into());+ } else {+ if let Some(o) = r.data["outcomes"].get_mut("analyze-impedance") {+ o["referencePlane"] = rc.clone();+ let _ = r.save();+ }+ m.push_str("\nreference plane: >= 90% continuous copper verified under all targets");+ }+ }+ ok(&m, &h);+ }+ Err((m, mut h)) => {+ if let Some(rc) = &ref_check {+ if rc["hasFilledZones"] == true && rc["pass"] == false {+ for f in rc["findings"].as_array().into_iter().flatten().filter_map(Value::as_str) {+ h.push(format!("reference plane: {f}"));+ }+ }+ }+ err(&m, &h);+ }+ } return; } let planp = plan.clone().or_else(|| r.outcomes().get("route").and_then(|o| o.get("plan")).and_then(|p| p.as_str()).map(str::to_string)).unwrap_or_else(|| err("no routing plan", &["Run route, or pass --plan.".into()]));@@ -6127,10 +6302,15 @@ fn main() { if aiflow_analyze::needs_field_screen(&spec,what) { if let Some(n) = std::process::Command::new("adom-fields").arg("--version").output().ok().and_then(|o| fields_versions::installed_note(&String::from_utf8_lossy(&o.stdout))) { note(&n, &[]); } }+ let fields_mod_plan = fields_review::recommended_modules(&board_now, &spec); if aiflow_analyze::needs_field_screen(&spec,what) && fields_file.is_file() && !fields_observed(&r,&fields_file) { let out_dir = dir.join("fields");- let args: Vec<String> = vec!["analyze".into(),"--board".into(),solved_board.clone(),"--spec".into(),r.data["spec"].as_str().unwrap_or("").to_string(),"--out".into(),out_dir.display().to_string()];- eprintln!("{} was not produced by an Adom Fields solve this run watched; solving it now: adom-fields {}", fields_file.display(), args.join(" "));+ let mut args: Vec<String> = vec!["analyze".into(),"--board".into(),solved_board.clone(),"--spec".into(),r.data["spec"].as_str().unwrap_or("").to_string(),"--out".into(),out_dir.display().to_string()];+ if let Some(csv) = fields_mod_plan.with_csv() {+ args.push("--with".into());+ args.push(csv);+ }+ eprintln!("{} was not produced by an Adom Fields solve this run watched; solving it now ({}): adom-fields {}", fields_file.display(), fields_mod_plan.describe(), args.join(" ")); match std::process::Command::new("adom-fields").args(&args).status() { Ok(st) if st.success() => { fields_file = out_dir.join("fields.json"); let mut full=vec!["adom-fields".to_string()]; full.extend(args.clone()); record_fields_solve(&mut r, &fields_file, "analyze", &full); r.save().unwrap(); } Ok(st) => { unobserved = Some(format!("the field solve aiflow started failed ({st}); fix what adom-fields printed, then `adom-aiflow exec -- adom-fields {}` and analyze {what} again", args.join(" "))); }@@ -6174,17 +6354,30 @@ fn main() { // issue #107: the passed solve's rise at each net's narrowest neck judges the whole-net width screen if what == "current" && s.is_ok() { aiflow_analyze::solved_ampacity::accept_solve(&mut res, &spec, &f); heuristic_passed = res.iter().all(|x| x["status"] == "pass"); } s- } else { Err(format!("no field solve at {}; run adom-fields analyze --board {} --spec {} --out {}, then analyze {what} --fields {}",fields_file.display(),solved_board,r.data["spec"].as_str().unwrap_or(""),dir.join("fields").display(),dir.join("fields/fields.json").display())) };+ } else {+ let with_flag = fields_mod_plan.with_csv().map(|c| format!(" --with {c}")).unwrap_or_default();+ Err(format!("no field solve at {}; fields modules ({}): run adom-fields analyze --board {} --spec {}{with_flag} --out {}, then analyze {what} --fields {} (override modules with spec \"fieldsModules\")",fields_file.display(),fields_mod_plan.describe(),solved_board,r.data["spec"].as_str().unwrap_or(""),dir.join("fields").display(),dir.join("fields/fields.json").display()))+ }; let passed=heuristic_passed && screen.is_ok(); // issue #75: the fields step refuses a converter Fields did not model; say so here already- let converter_hints = converter_warning(&r.data, &spec, aiflow_analyze::fields_report::load(&fields_file).ok().as_ref(), Some(&board_now));+ let fdoc_loaded = aiflow_analyze::fields_report::load(&fields_file).ok();+ let converter_hints = converter_warning(&r.data, &spec, fdoc_loaded.as_ref(), Some(&board_now));+ let ran_fields_modules: Vec<String> = fdoc_loaded.as_ref().map(|fd| {+ fd["modules"]["ran"].as_array().into_iter().flatten()+ .filter_map(|m| m["module"].as_str().or(m.as_str()).map(|s| s.to_ascii_lowercase()))+ .collect()+ }).unwrap_or_default(); let covered_acks = screen.as_ref().map(|c| c.clone()).unwrap_or_default(); let sink_assumptions = aiflow_analyze::board_sink::assumptions(&res); let field_note=screen.err().unwrap_or_else(||"same-input field screen passed under its stated assumptions".into()); r.stage_end(&name, Some(json!({"pass": passed})), None);- r.outcome(&name, json!({"pass": passed, "heuristicPass":heuristic_passed, "fieldReport":fields_file, "fieldNote":field_note, "results": res, "acknowledgedPeaks": covered_acks, "expiredAcks": expired_acks, "boardSinkAssumptions": sink_assumptions, "boardSinkNotes": sink_notes}));+ r.outcome(&name, json!({"pass": passed, "heuristicPass":heuristic_passed, "fieldReport":fields_file, "fieldNote":field_note, "fieldsModulesRan": ran_fields_modules, "fieldsModulesPlan": fields_mod_plan.describe(), "results": res, "acknowledgedPeaks": covered_acks, "expiredAcks": expired_acks, "boardSinkAssumptions": sink_assumptions, "boardSinkNotes": sink_notes})); r.save().unwrap(); let mut lines: Vec<String> = res.iter().map(|x| format!("{} {}: {}", x.get("net").or(x.get("ref")).and_then(|v| v.as_str()).unwrap_or("?"), x["status"].as_str().unwrap_or(""), x.get("how").or(x.get("hint")).and_then(|v| v.as_str()).unwrap_or(""))).collect();+ if fdoc_loaded.is_some() {+ let ran_s = if ran_fields_modules.is_empty() { "core only".into() } else { format!("core + {}", ran_fields_modules.join(", ")) };+ lines.push(format!("fields modules: ran {ran_s} (recommended: {})", fields_mod_plan.describe()));+ } for c in &covered_acks { lines.push(format!("acknowledged peak: {} {:.1} A/mm2 at ({:.2}, {:.2}) {} by --ack {}: \"{}\" ({}); Fields reports one maximum per net, so check its density map for a second spot", c["net"].as_str().unwrap_or(""), c["peakJ"].as_f64().unwrap_or(0.0), c["at"][0].as_f64().unwrap_or(0.0), c["at"][1].as_f64().unwrap_or(0.0), c["layer"].as_str().unwrap_or(""), c["ack"].as_str().unwrap_or(""), c["why"].as_str().unwrap_or(""), c["aiThread"].as_str().unwrap_or(""))); } for a in &expired_acks { lines.push(format!("expired acknowledgement (copper or spec changed since the review; acknowledge again if it still holds): {}", aiflow_analyze::current_acks::describe(a, "expired"))); } for a in &sink_assumptions { lines.push(format!("board-sink assumption: {a}")); }@@ -6212,6 +6405,10 @@ fn main() { ok(&format!("{what} analysis passed:\n{}", lines.join("\n")), &hints); } Cmd::Impedance { action, board, spec, plan, json: as_json } => {+ if action == "stackups" {+ match impedance_cmd::command(action, "", &Value::Null, None, *as_json) { Ok((m, h)) => ok(&m, &h), Err((m, h)) => err(&m, &h) }+ return;+ } let (board_file, spec_v, plan_p) = match (board, spec) { (Some(b), Some(s)) => (b.clone(), read_json(s), plan.clone()), (None, None) => { let r = load_run(&cli); let p = plan.clone().or_else(|| r.outcomes().get("route").and_then(|o| o["plan"].as_str()).map(str::to_string)); (r.current_board(), spec_of(&r), p) }@@ -6356,8 +6553,12 @@ fn main() { missing.push(format!("fields: {msg}. {}", hints.join(" "))); } }- // issue #52: impedance targets hold on the live board's copper- if !pattern { if let Some(m) = impedance_cmd::finish_check(&board_now(), &spec_of(&r), &solved_board, o.get("analyze-impedance")) { missing.push(m); } }+ // issue #52: impedance targets hold on the live board's copper; issue #213: surface unconfirmed stackup advisory+ if !pattern {+ let sp_imp = spec_of(&r);+ if let Some(m) = impedance_cmd::finish_check(&board_now(), &sp_imp, &solved_board, o.get("analyze-impedance")) { missing.push(m); }+ if let Some(adv) = stackup_presets::finish_advisory(&sp_imp) { missing.push(adv); }+ } if let Err(m) = netlist_gate(&r) { missing.push(m); } if let Err(m) = schematic_symbols::gate(&r) { missing.push(m); } let silk_warnings = silk_polarity::warnings(&board_now());@@ -6554,6 +6755,7 @@ fn main() { if n > 0 { quality_lines.push(format!("parts: {n} part(s) not checked against their datasheets (land, body height, maker): `adom-aiflow part-check` (aiflow-sourcing)")); } } // issue #217: board-wide VIPPO audit and via-count hygiene+ // issues #214, #215: SI, return-path, 3W crosstalk, USB VBUS inrush, load budget, and Fields SI/noise/EMC/ESD/PDN + readiness report { let b_now = board_now(); let va = vippo::audit_vippo(&b_now, &spec_v);@@ -6575,6 +6777,40 @@ fn main() { quality_lines.push(format!("via hygiene: {f}")); } r.outcome("vippo-hygiene", json!({"vippo": va, "viaHygiene": vh}));++ let fpath = dir.join("fields/fields.json");+ let fdoc = if fpath.is_file() { aiflow_analyze::fields_report::load(&fpath).ok() } else { None };+ let ret_vias = si_checks::return_via_audit(&b_now, &spec_v);+ let xtalk = si_checks::crosstalk_3w_audit(&b_now, &spec_v);+ let inrush = usb_power::check_usb_inrush(&b_now, &spec_v, fdoc.as_ref());+ let budget = usb_power::check_load_budget(&spec_v, &req_v);+ for f in ret_vias["findings"].as_array().into_iter().flatten().filter_map(Value::as_str) { quality_lines.push(f.to_string()); }+ for f in xtalk["findings"].as_array().into_iter().flatten().filter_map(Value::as_str) { quality_lines.push(f.to_string()); }+ for f in inrush["findings"].as_array().into_iter().flatten().filter_map(Value::as_str) { quality_lines.push(f.to_string()); }+ for f in budget["findings"].as_array().into_iter().flatten().filter_map(Value::as_str) { quality_lines.push(f.to_string()); }+ let mut fields_rev = Value::Null;+ let mut readiness_doc = Value::Null;+ if let Some(fd) = &fdoc {+ let s = fields_review::summarize_fields(fd, &b_now, &spec_v);+ for l in s["lines"].as_array().into_iter().flatten().filter_map(Value::as_str) {+ quality_lines.push(format!("fields: {l}"));+ }+ fields_rev = s;+ if let Ok((rd, rlines)) = fields_review::run_fields_report(&dir.join("fields"), &dir.join("design-review/readiness.md")) {+ readiness_doc = rd;+ if !rlines.is_empty() {+ quality_lines.push(format!("fields readiness ({}):\n{}", dir.join("design-review/readiness.md").display(), rlines.join("\n")));+ }+ }+ }+ r.outcome("si-power-review", json!({+ "returnVias": ret_vias,+ "crosstalk3W": xtalk,+ "usbInrush": inrush,+ "loadBudget": budget,+ "fieldsReview": fields_rev,+ "fieldsReadiness": readiness_doc,+ })); } // 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();@@ -7437,7 +7673,7 @@ fn main() { if mode == "netlist" { hints.push("Run it again once the board is placed (`testplan check`): a test point under a part or out of tether reach is a gap again. finish runs it too.".into()); } ok(&body, &hints); }- Cmd::Rules { action, profile, board, force, layers, variant, prefs, spec, altium_out } if action == "use" || action == "list" || action == "sync" => {+ Cmd::Rules { action, profile, board, force, layers, variant, prefs, stackup, spec, altium_out } if action == "use" || action == "list" || action == "sync" || action == "stackup" => { if action == "sync" { let mut run = Run::open(&dir); if run.is_some() { thread(&cli); }@@ -7481,6 +7717,49 @@ fn main() { ok(&format!("synced {} electrical net class(es): {}; updated {}", plan.classes.len(), summary.join(", "), written.join(", ")), &hints); return; }+ if action == "stackup" {+ let mut run = Run::open(&dir);+ if run.is_some() { thread(&cli); }+ let cb = board.clone().or_else(|| run.as_ref().map(|r| r.current_board())).unwrap_or_default();+ let sp_path = spec.clone().or_else(|| run.as_ref().and_then(|r| r.data["spec"].as_str().map(str::to_string)));+ if cb.is_empty() && sp_path.is_none() {+ err("rules stackup needs an open run or --spec <spec.json> / --board <file.kicad_pcb>", &[]);+ }+ let asked_layers = layers.or_else(|| if cb.is_empty() { None } else { checks::board_copper_layers(&cb) }).unwrap_or(4);+ let preset = match stackup.as_deref() {+ Some(id) => stackup_presets::find(id).unwrap_or_else(|| err(&format!("unknown stackup preset {id:?}"), &[format!("Available stackup presets:\n{}", stackup_presets::list_lines().join("\n"))])),+ None => profile.as_deref().and_then(|p| { let (b, l) = checks::split_profile(p); stackup_presets::default_for(&b, l.unwrap_or(asked_layers)) })+ .unwrap_or_else(|| err("pass --stackup <id> (or --profile <fab> --layers <n>)", &[format!("Available stackup presets:\n{}", stackup_presets::list_lines().join("\n"))])),+ };+ if !cb.is_empty() {+ if let Some(bl) = checks::board_copper_layers(&cb).filter(|&n| n != preset.layers) {+ err(&format!("stackup {} is {}L but {} has {bl} copper layers", preset.id, preset.layers, cb), &["Pick a stackup preset matching the board's copper layer count (`adom-aiflow impedance stackups`).".into()]);+ }+ }+ let mut updated = Vec::new();+ if let Some(sp) = sp_path {+ let mut v = read_json(&sp);+ stackup_presets::apply_to_spec(preset, &mut v);+ write_json(Path::new(&sp), &v);+ updated.push(sp);+ }+ if cb.ends_with(".kicad_pcb") && Path::new(&cb).is_file() {+ let bt = std::fs::read_to_string(&cb).unwrap_or_else(|e| err(&format!("{cb}: {e}"), &[]));+ let next = stackup_presets::apply_to_board_text(preset, &bt).unwrap_or_else(|e| err(&format!("{cb}: {e}"), &[]));+ std::fs::write(&cb, next).unwrap_or_else(|e| err(&format!("{cb}: {e}"), &[]));+ updated.push(cb);+ }+ if let Some(r) = run.as_mut() {+ r.data["fabRules"]["stackupId"] = json!(preset.id);+ r.data["fabRules"]["stackupStatus"] = json!("published-profile");+ r.save().unwrap();+ }+ ok(&format!("bound published stackup preset {} ({}): updated {}", preset.id, preset.summary, updated.join(", ")), &[+ "Run `adom-aiflow impedance table` to compute solder-mask-adjusted widths and gaps on this stackup.".into(),+ "Confirm widths and gaps with the fabricator's own stackup calculator before ordering, then set fab.stackupStatus to \"fab-confirmed\" with fab.confirmedSource.".into(),+ ]);+ return;+ } let page = "adom/pcb-design-rules"; let list = || -> Vec<String> { let o = std::process::Command::new("adom-wiki").args(["api", "/api/v1/pages/adom/pcb-design-rules/files?path=kicad"]).output().ok();@@ -7564,14 +7843,35 @@ fn main() { fusion_note = if okk { format!("; {}: {shown} {layers}-layer rules loaded into the open design", eda.name()) } else { format!("; {} did not load them ({}): open the design and run `rules use` again", eda.name(), rep["errorCode"].as_str().or(rep["error"].as_str()).unwrap_or("?")) }; } }- // the choice: in the spec when there is one, and in the run (an intake run has no spec yet)- r.data["fabRules"] = json!({"profile": shown, "slug": slug, "layers": layers, "file": file, "variant": variant});+ // the choice: in the spec when there is one, and in the run (an intake run has no spec yet).+ // Only bind a stackup preset when explicitly asked via --stackup <id>, or when the spec+ // declares impedanceTargets without stackupMm and the fab has a published preset.+ let explicit_stackup = stackup.as_deref().map(|id| {+ let p = stackup_presets::find(id).unwrap_or_else(|| err(&format!("unknown stackup preset {id:?}"), &[format!("Available stackup presets:\n{}", stackup_presets::list_lines().join("\n"))]));+ if p.layers != layers {+ err(&format!("--stackup {} is {}L but rules profile is {layers}L", p.id, p.layers), &["Pick a stackup matching --layers (`adom-aiflow impedance stackups`).".into()]);+ }+ p+ });+ let mut bound_stackup = explicit_stackup;+ let mut stackup_note = String::new(); if let Some(sp) = r.data["spec"].as_str().map(str::to_string) { if let Ok(mut v) = std::fs::read_to_string(&sp).map_err(|_| ()).and_then(|t| serde_json::from_str::<Value>(&t).map_err(|_| ())) { if !v["fab"].is_object() { v["fab"] = json!({}); } v["fab"]["rules"] = json!(slug); match &variant { Some(x) => v["fab"]["rulesVariant"] = json!(x), None => { if let Some(o) = v["fab"].as_object_mut() { o.remove("rulesVariant"); } } } if !prefs_rec.is_null() { v["fab"]["preferences"] = prefs_rec.clone(); }+ let has_imp_targets = v.get("impedanceTargets").and_then(Value::as_object).is_some_and(|m| !m.is_empty());+ if let Some(preset) = explicit_stackup {+ stackup_presets::apply_to_spec(preset, &mut v);+ stackup_note = format!("; stackup {} bound into spec", preset.id);+ } else if has_imp_targets && v.get("stackupMm").is_none() {+ if let Some(preset) = stackup_presets::default_for(&slug, layers) {+ stackup_presets::apply_to_spec(preset, &mut v);+ bound_stackup = Some(preset);+ stackup_note = format!("; published stackup {} bound into spec for impedanceTargets", preset.id);+ }+ } write_json(Path::new(&sp), &v); // issue #216: auto-sync electrical net classes into KiCad .kicad_pro + managed .kicad_dru section if cb.ends_with(".kicad_pcb") && Path::new(&cb).is_file() {@@ -7587,14 +7887,25 @@ fn main() { } } }+ if let Some(preset) = explicit_stackup {+ if cb.ends_with(".kicad_pcb") && Path::new(&cb).is_file() {+ if let Ok(bt) = std::fs::read_to_string(&cb) {+ if let Ok(next) = stackup_presets::apply_to_board_text(preset, &bt) {+ let _ = std::fs::write(&cb, next);+ stackup_note = format!("; stackup {} bound into spec and board", preset.id);+ }+ }+ }+ }+ r.data["fabRules"] = json!({"profile": shown, "slug": slug, "layers": layers, "file": file, "variant": variant, "stackupId": bound_stackup.map(|p| p.id)}); let mins: Vec<String> = text.lines().filter(|l| l.starts_with("# Min") || l.starts_with("# Copper to") || l.starts_with("# Annular")).map(|l| l.trim_start_matches("# ").to_string()).take(6).collect();- r.outcome("rules", json!({"profile": shown, "slug": slug, "layers": layers, "variant": variant, "prefs": prefs_rec, "kicad": placed, "native": {"eda": eda.id(), "loaded": fusion_loaded}, "fusion": if eda.id() == "fusion" { fusion_loaded.clone() } else { Value::Null }}));+ r.outcome("rules", json!({"profile": shown, "slug": slug, "layers": layers, "variant": variant, "stackupId": bound_stackup.map(|p| p.id), "prefs": prefs_rec, "kicad": placed, "native": {"eda": eda.id(), "loaded": fusion_loaded}, "fusion": if eda.id() == "fusion" { fusion_loaded.clone() } else { Value::Null }})); r.save().unwrap(); let set = match &variant { Some(v) => format!(" (variant {v}, opt-in, stricter or different from the fab's published limits)"), None => " (the fab's published limits)".into() }; let pref_now = if prefs_rec.is_null() { spec_soft(&r)["fab"]["preferences"].clone() } else { prefs_rec.clone() }; let pref_lines = if pref_now.is_object() && cb.ends_with(".kicad_pcb") { Board::load(&cb).map(|b| prefs::findings(&b, &pref_now)).unwrap_or_default() } else { Vec::new() }; let pref_note = if pref_now.is_object() { format!(", the human's own preferences kept (checked as warnings: {})", if pref_lines.is_empty() { "all met now".to_string() } else { pref_lines.join("; ") }) } else { String::new() };- ok(&format!("design rules: {shown}, {layers} layers{set}{pref_note}{fusion_note}. KiCad rules at {}{replaced_note}", placed.join(", ")), &[+ ok(&format!("design rules: {shown}, {layers} layers{set}{pref_note}{stackup_note}{fusion_note}. KiCad rules at {}{replaced_note}", placed.join(", ")), &[ format!("Tell the human in plain words which rules are now enforced: {}.", if mins.is_empty() { "see the file".into() } else { mins.join("; ") }), "Every later step designs to these: placement checks, routing widths and clearances, the gate's DRC and finish all read them. Design with margin above the minimums.".into(), "The human can switch at any time: another variant (`rules use --variant <name> --force`), back to the published pack (`rules use --force`), or their own preferences (`--prefs <file.json>`); `rules list` shows what exists.".into()]);
crates/adom-aiflow/src/si_checks.rsadded+583@@ -0,0 +1,583 @@+//! Signal-integrity geometry checks (issue #214):+//! 1. Real reference-plane copper coverage under controlled-impedance traces: samples every+//! controlled-impedance segment every 0.25 mm at center and both trace edges (skipping 0.3 mm+//! around pads and vias), requiring >= 90% continuous reference-plane copper on the adjacent+//! layer(s) and no continuous plane split or void longer than 1.0 mm.+//! 2. Return-path stitching via check: flags any signal via on `clocks`, `impedanceTargets`, or+//! high-priority `signalPriority` nets that transitions layers without a reference-plane (GND)+//! stitching via within 2.5 mm.+//! 3. Geometric 3W / 3H crosstalk screen: flags parallel runs > 10 mm at spacing < max(3W, 3H)+//! (using 3H on 4+ layer thin dielectrics <= 0.5 mm and 3W on 2-layer boards) between+//! high-speed/clock/diff-pair aggressors and declared sensitive/analog/ADC/FB nets.++use std::collections::{BTreeMap, BTreeSet};++use aiflow_board::{copper_depth, copper_layer, geom, Board, Pt, Track, B_CU, F_CU};+use aiflow_router::impedance::{self, Target};+use serde_json::{json, Value};++pub const REF_SAMPLE_MM: f64 = 0.25;+pub const REF_PAD_VIA_SKIP_MM: f64 = 0.30;+pub const REF_MIN_COVERAGE_PCT: f64 = 90.0;+pub const REF_MAX_SPLIT_MM: f64 = 1.0;+pub const RETURN_VIA_RADIUS_MM: f64 = 2.5;+pub const CROSSTALK_MIN_PARALLEL_MM: f64 = 10.0;++fn layer_name(l: usize) -> String {+ match l {+ F_CU => "F.Cu".into(),+ B_CU => "B.Cu".into(),+ k => format!("In{}.Cu", k - 1),+ }+}++fn ordered_copper_layers(board: &Board) -> Vec<usize> {+ let mut names = if board.copper_layers.is_empty() {+ vec!["F.Cu".into(), "B.Cu".into()]+ } else {+ board.copper_layers.clone()+ };+ names.sort_by_key(|n| match n.as_str() {+ "F.Cu" => 0,+ "B.Cu" => 10_000,+ s => s.strip_prefix("In").and_then(|r| r.strip_suffix(".Cu")).and_then(|k| k.parse::<usize>().ok()).unwrap_or(5000),+ });+ names.dedup();+ names.into_iter().filter_map(|n| copper_layer(&n)).collect()+}++fn adjacent_ref_layers(board: &Board, layer: usize) -> Vec<usize> {+ let stack = ordered_copper_layers(board);+ let Some(pos) = stack.iter().position(|&l| l == layer) else { return Vec::new() };+ let mut out = Vec::new();+ if pos > 0 { out.push(stack[pos - 1]); }+ if pos + 1 < stack.len() { out.push(stack[pos + 1]); }+ out+}++fn is_ref_plane_net(name: &str, spec_planes: &BTreeSet<String>) -> bool {+ if spec_planes.contains(name) { return true; }+ let u = name.trim_start_matches('/').to_ascii_uppercase();+ let u = u.rsplit('/').next().unwrap_or(&u);+ u == "GND" || u == "AGND" || u == "DGND" || u == "PGND" || u == "VSS" || u.contains("GND")+ || u.starts_with('+') || u.starts_with("VCC") || u.starts_with("VDD") || u.starts_with("3V3") || u.starts_with("5V") || u.contains("PWR")+}++fn is_gnd_net(name: &str) -> bool {+ let u = name.trim_start_matches('/').to_ascii_uppercase();+ let u = u.rsplit('/').next().unwrap_or(&u);+ u == "GND" || u == "AGND" || u == "DGND" || u == "PGND" || u == "VSS" || u.contains("GND")+}++fn spec_plane_nets(spec: &Value) -> BTreeSet<String> {+ let mut s = BTreeSet::new();+ if let Some(o) = spec["planes"].as_object() {+ for (net, _) in o { s.insert(net.clone()); }+ }+ if let Some(a) = spec["pours"].as_array() {+ for p in a {+ if let Some(n) = p["net"].as_str() { s.insert(n.to_string()); }+ }+ }+ s+}++fn point_in_any_fill(x: f64, y: f64, layer: usize, fills: &[(String, usize, Vec<Pt>)], spec_planes: &BTreeSet<String>) -> Option<String> {+ for (net, fl, poly) in fills {+ if *fl != layer || poly.len() < 3 || !is_ref_plane_net(net, spec_planes) { continue; }+ if geom::point_in_poly(x, y, poly) {+ return Some(net.clone());+ }+ }+ None+}++/// Check real reference-plane copper coverage beneath every controlled-impedance target on `board`.+/// Samples every segment every 0.25 mm at center and both trace edges (skipping within 0.30 mm of+/// pads and vias). Fails when coverage < 90% or a continuous split/void stretch exceeds 1.0 mm.+pub fn reference_plane_audit(board: &Board, spec: &Value, targets: &[Target]) -> Value {+ if targets.is_empty() {+ return json!({"pass": true, "checked": 0, "findings": [], "targets": []});+ }+ let tracks = board.copper_tracks();+ let vias = board.vias();+ let fills = board.copper_fills();+ let spec_planes = spec_plane_nets(spec);+ let mut target_rows = Vec::new();+ let mut findings = Vec::new();+ let mut all_pass = true;++ for t in targets {+ let mut total_samples = 0usize;+ let mut covered_samples = 0usize;+ let mut max_missing_run = 0.0f64;+ let mut total_missing_mm = 0.0f64;+ let mut split_crossings = 0usize;+ let mut ref_layers_used: BTreeSet<String> = BTreeSet::new();+ let mut first_void_at: Option<(f64, f64, String)> = None;++ for net in &t.nets {+ let net_pads: Vec<&aiflow_board::Pad> = board.pads.iter().filter(|p| p.net == *net).collect();+ let net_vias: Vec<&aiflow_board::Via> = vias.iter().filter(|v| v.net == *net).collect();+ for seg in tracks.iter().filter(|s| s.net == *net) {+ let adj = adjacent_ref_layers(board, seg.layer);+ if adj.is_empty() { continue; }+ for &rl in &adj { ref_layers_used.insert(layer_name(rl)); }+ let len = (seg.b.0 - seg.a.0).hypot(seg.b.1 - seg.a.1);+ if len < 1e-6 { continue; }+ let dx = (seg.b.0 - seg.a.0) / len;+ let dy = (seg.b.1 - seg.a.1) / len;+ let nx = -dy;+ let ny = dx;+ let hw = seg.width * 0.5;+ let n = ((len / REF_SAMPLE_MM).ceil() as usize).max(1);+ let step = len / n as f64;+ let mut cur_missing = 0.0f64;+ let mut prev_ref_net: Option<String> = None;++ for k in 0..=n {+ let s = k as f64 * step;+ let x = seg.a.0 + dx * s;+ let y = seg.a.1 + dy * s;+ let near_pad = net_pads.iter().any(|p| p.on_copper(seg.layer) && (x - p.x).hypot(y - p.y) <= p.half_long + REF_PAD_VIA_SKIP_MM);+ let near_via = net_vias.iter().any(|v| (x - v.x).hypot(y - v.y) <= v.size * 0.5 + REF_PAD_VIA_SKIP_MM);+ if near_pad || near_via {+ cur_missing = 0.0;+ continue;+ }+ total_samples += 1;+ let pts = [(x, y), (x + nx * hw, y + ny * hw), (x - nx * hw, y - ny * hw)];+ // For microstrip (1 adjacent ref layer): all 3 probes must lie over plane copper.+ // For stripline (2 adjacent ref layers): all 3 probes must lie over plane copper on at least one adjacent layer (or both when both have planes).+ let mut chosen_ref: Option<String> = None;+ let mut all_ok = false;+ for &rl in &adj {+ let r0 = point_in_any_fill(pts[0].0, pts[0].1, rl, &fills, &spec_planes);+ let r1 = point_in_any_fill(pts[1].0, pts[1].1, rl, &fills, &spec_planes);+ let r2 = point_in_any_fill(pts[2].0, pts[2].1, rl, &fills, &spec_planes);+ if let (Some(n0), Some(n1), Some(n2)) = (r0, r1, r2) {+ if n0 == n1 && n1 == n2 {+ all_ok = true;+ chosen_ref = Some(n0);+ break;+ }+ }+ }+ if all_ok {+ covered_samples += 1;+ if let (Some(prev), Some(cur)) = (&prev_ref_net, &chosen_ref) {+ if prev != cur {+ split_crossings += 1;+ if first_void_at.is_none() {+ first_void_at = Some((x, y, format!("plane switch {prev} -> {cur}")));+ }+ }+ }+ prev_ref_net = chosen_ref;+ cur_missing = 0.0;+ } else {+ cur_missing += step;+ total_missing_mm += step;+ if cur_missing > max_missing_run { max_missing_run = cur_missing; }+ if first_void_at.is_none() {+ first_void_at = Some((x, y, format!("missing reference copper on {}", adj.iter().map(|&l| layer_name(l)).collect::<Vec<_>>().join("/"))));+ }+ }+ }+ }+ }++ let cov_pct = if total_samples == 0 { 100.0 } else { (covered_samples as f64 / total_samples as f64) * 100.0 };+ let has_fills = !fills.is_empty();+ let target_pass = total_samples == 0 || (cov_pct >= REF_MIN_COVERAGE_PCT && max_missing_run <= REF_MAX_SPLIT_MM && split_crossings == 0);+ if !target_pass {+ all_pass = false;+ let where_note = first_void_at.as_ref().map(|(x, y, why)| format!(" at ({x:.2}, {y:.2}): {why}")).unwrap_or_default();+ let unfilled = if !has_fills { " (board has no filled zones yet; fill zones in KiCad and re-save)" } else { "" };+ findings.push(format!(+ "reference plane under {}: {:.1}% covered (min {:.0}%), longest missing/split stretch {:.2} mm (max {:.1} mm), {} plane-net switch(es){where_note}{unfilled}",+ t.label(), cov_pct, REF_MIN_COVERAGE_PCT, max_missing_run, REF_MAX_SPLIT_MM, split_crossings+ ));+ }+ target_rows.push(json!({+ "target": t.name,+ "nets": t.nets,+ "referenceLayers": ref_layers_used.into_iter().collect::<Vec<_>>(),+ "samples": total_samples,+ "coveragePercent": (cov_pct * 10.0).round() / 10.0,+ "missingMm": (total_missing_mm * 100.0).round() / 100.0,+ "maxMissingStretchMm": (max_missing_run * 100.0).round() / 100.0,+ "planeSwitches": split_crossings,+ "status": if target_pass { "pass" } else { "fail" },+ }));+ }++ json!({+ "pass": all_pass,+ "checked": target_rows.len(),+ "hasFilledZones": !fills.is_empty(),+ "findings": findings,+ "targets": target_rows,+ })+}++fn is_fast_signal_net(name: &str) -> bool {+ let u = name.trim_start_matches('/').to_ascii_uppercase();+ let u = u.rsplit('/').next().unwrap_or(&u);+ // Debug/programming pins (SWDIO, SWCLK, SWO, JTAG) are low-speed bench interfaces, not runtime high-speed nets+ if ["SWDIO", "SWCLK", "SWO", "JTAG", "TCK", "TMS", "TDI", "TDO", "NRST", "BOOT0"]+ .iter().any(|k| u.contains(k))+ {+ return false;+ }+ // USB-C control/power pins (USB_CC1, USB_CC2, USB_VBUS, USB_SBU*, USB_ID) are DC/300 kbps, not 480 Mbps data+ if u.contains("USB") {+ if ["CC", "VBUS", "SBU", "SHIELD", "PWR", "5V", "GND", "EN", "FLT", "FAULT", "_ID"]+ .iter().any(|k| u.contains(k))+ {+ return false;+ }+ return ["DP", "DN", "DM", "D+", "D-", "USB_P", "USB_N", "USBD+", "USBD-", "TX", "RX", "SS"]+ .iter().any(|k| u.contains(k));+ }+ ["CLK", "SCLK", "MCLK", "BCLK", "ETH", "RMII", "RGMII", "MDI", "SPI", "QSPI", "OSPI", "SDIO", "SD_", "MIPI", "HDMI", "PCIE", "DDR", "CAN"]+ .iter().any(|k| u.contains(k))+}++fn is_sensitive_net(name: &str) -> bool {+ let u = name.trim_start_matches('/').to_ascii_uppercase();+ let u = u.rsplit('/').next().unwrap_or(&u);+ ["ADC", "AIN", "VSENSE", "ISENSE", "SENSE", "VFB", "_FB", "FB_", "COMP", "NTC", "TEMP", "MIC", "VREF", "AREF", "DAC", "ANALOG", "AIN_"]+ .iter().any(|k| u.contains(k))+ || u == "FB" || u == "REF"+}++fn critical_signal_nets(spec: &Value) -> BTreeSet<String> {+ let mut s = BTreeSet::new();+ if let Ok(ts) = impedance::targets(spec) {+ for t in ts { for n in t.nets { s.insert(n); } }+ }+ if let Some(o) = spec["clocks"].as_object() {+ for k in o.keys() { s.insert(k.clone()); }+ }+ if let Some(a) = spec["clocks"].as_array() {+ for x in a {+ if let Some(n) = x.as_str() { s.insert(n.to_string()); }+ else if let Some(n) = x["net"].as_str() { s.insert(n.to_string()); }+ }+ }+ if let Some(a) = spec["signalPriority"].as_array() {+ // First 2 priority classes are treated as high-priority return-path nets+ for entry in a.iter().take(2) {+ for n in entry["nets"].as_array().into_iter().flatten().filter_map(|v| v.as_str()) {+ s.insert(n.to_string());+ }+ }+ }+ s+}++/// Check that every signal via on `clocks`, `impedanceTargets`, or high-priority `signalPriority`+/// nets has a reference-plane (GND) stitching via within `radius_mm` (default 2.5 mm) when+/// transitioning layers.+pub fn return_via_audit(board: &Board, spec: &Value) -> Value {+ let radius = spec["stitchViaRadiusMm"].as_f64().unwrap_or(RETURN_VIA_RADIUS_MM);+ let crit = critical_signal_nets(spec);+ let spec_planes = spec_plane_nets(spec);+ let vias = board.vias();+ let tracks = board.copper_tracks();+ let ref_vias: Vec<&aiflow_board::Via> = vias.iter().filter(|v| is_gnd_net(&v.net) || spec_planes.contains(&v.net)).collect();+ // Plated through-hole GND/reference pads (e.g. USB-C shield/GND pins, header GND pins) span all layers too.+ let ref_pth_pads: Vec<(f64, f64)> = board.pads.iter()+ .filter(|p| p.thru && (is_gnd_net(&p.net) || spec_planes.contains(&p.net)))+ .map(|p| (p.x, p.y))+ .collect();+ let mut missing = Vec::new();+ let mut checked = 0usize;++ for v in &vias {+ if v.net.is_empty() || is_gnd_net(&v.net) || spec_planes.contains(&v.net) { continue; }+ let tracked = crit.contains(&v.net) || is_fast_signal_net(&v.net);+ if !tracked { continue; }+ // Confirm the via actually connects copper on >= 2 distinct layers for this net+ let mut layers: BTreeSet<usize> = BTreeSet::new();+ for t in tracks.iter().filter(|t| t.net == v.net) {+ let d_a = (t.a.0 - v.x).hypot(t.a.1 - v.y);+ let d_b = (t.b.0 - v.x).hypot(t.b.1 - v.y);+ if d_a <= (v.size * 0.5).max(0.2) || d_b <= (v.size * 0.5).max(0.2) {+ layers.insert(t.layer);+ }+ }+ if layers.len() < 2 { continue; }+ checked += 1;+ let nearest_via = ref_vias.iter()+ .filter(|rv| {+ // Stitching via must span across the transition depths+ let dmin = layers.iter().map(|&l| copper_depth(l)).min().unwrap_or(0);+ let dmax = layers.iter().map(|&l| copper_depth(l)).max().unwrap_or(0);+ rv.span.0 <= dmin && rv.span.1 >= dmax+ })+ .map(|rv| (rv.x - v.x).hypot(rv.y - v.y))+ .min_by(|a, b| a.total_cmp(b));+ let nearest_pth = ref_pth_pads.iter()+ .map(|(px, py)| (*px - v.x).hypot(*py - v.y))+ .min_by(|a, b| a.total_cmp(b));+ let nearest = match (nearest_via, nearest_pth) {+ (Some(a), Some(b)) => Some(a.min(b)),+ (Some(a), None) => Some(a),+ (None, Some(b)) => Some(b),+ (None, None) => None,+ };+ let ok = nearest.is_some_and(|d| d <= radius + 1e-6);+ if !ok {+ missing.push(json!({+ "net": v.net,+ "at": [(v.x * 100.0).round() / 100.0, (v.y * 100.0).round() / 100.0],+ "layers": layers.iter().map(|&l| layer_name(l)).collect::<Vec<_>>(),+ "nearestRefViaMm": nearest.map(|d| (d * 100.0).round() / 100.0),+ "maxRadiusMm": radius,+ }));+ }+ }++ let findings: Vec<String> = missing.iter().map(|m| {+ let near = m["nearestRefViaMm"].as_f64().map(|d| format!("nearest GND/ref via is {d:.2} mm away")).unwrap_or_else(|| "no GND/ref stitching via on board".into());+ format!(+ "return-path via missing: {} transitions {} at ({:.2}, {:.2}) without a reference stitching via within {:.1} mm ({near})",+ m["net"].as_str().unwrap_or(""),+ m["layers"].as_array().map(|a| a.iter().filter_map(|v| v.as_str()).collect::<Vec<_>>().join(" <-> ")).unwrap_or_default(),+ m["at"][0].as_f64().unwrap_or(0.0),+ m["at"][1].as_f64().unwrap_or(0.0),+ radius+ )+ }).collect();++ json!({+ "pass": missing.is_empty(),+ "checkedVias": checked,+ "radiusMm": radius,+ "missing": missing,+ "findings": findings,+ })+}++fn parallel_overlap_mm(a: &Track, b: &Track) -> Option<(f64, f64)> {+ if a.layer != b.layer { return None; }+ let la = (a.b.0 - a.a.0).hypot(a.b.1 - a.a.1);+ let lb = (b.b.0 - b.a.0).hypot(b.b.1 - b.a.1);+ if la < 1e-6 || lb < 1e-6 { return None; }+ let (ux, uy) = ((a.b.0 - a.a.0) / la, (a.b.1 - a.a.1) / la);+ let (vx, vy) = ((b.b.0 - b.a.0) / lb, (b.b.1 - b.a.1) / lb);+ // Parallel within ~3 degrees+ if (ux * vy - uy * vx).abs() > 0.055 { return None; }+ let p0 = (b.a.0 - a.a.0) * ux + (b.a.1 - a.a.1) * uy;+ let p1 = (b.b.0 - a.a.0) * ux + (b.b.1 - a.a.1) * uy;+ let lo = p0.min(p1).max(0.0);+ let hi = p0.max(p1).min(la);+ let overlap = hi - lo;+ if overlap <= 0.05 { return None; }+ let mid_b_x = 0.5 * (b.a.0 + b.b.0);+ let mid_b_y = 0.5 * (b.a.1 + b.b.1);+ let center_sep = ((mid_b_x - a.a.0) * uy - (mid_b_y - a.a.1) * ux).abs();+ let edge_gap = (center_sep - 0.5 * (a.width + b.width)).max(0.0);+ Some((overlap, edge_gap))+}++fn layer_dielectric_h(board: &Board, spec: &Value, layer: usize) -> Option<f64> {+ let st = impedance::stackup(board, spec).ok()?;+ let lname = layer_name(layer);+ st.layers.iter().find(|g| g.name == lname).map(|g| g.h1)+}++/// Geometric 3W / 3H crosstalk screen: flags parallel runs > `min_parallel_mm` (default 10 mm) at+/// edge-to-edge spacing < max(3W, 3H_local) between high-speed/clock/diff-pair/switching aggressors+/// and declared sensitive/analog/ADC/FB nets.+pub fn crosstalk_3w_audit(board: &Board, spec: &Value) -> Value {+ let min_parallel = spec["crosstalk"]["maxParallelMm"].as_f64().unwrap_or(CROSSTALK_MIN_PARALLEL_MM);+ let explicit_spacing = spec["crosstalk"]["minSpacingMm"].as_f64();+ let tracks = board.copper_tracks();+ let spec_planes = spec_plane_nets(spec);++ let mut aggressors = critical_signal_nets(spec);+ if let Some(o) = spec["switching"].as_object() {+ for k in o.keys() { aggressors.insert(k.clone()); }+ }+ if let Some(a) = spec["switchNodes"].as_array() {+ for x in a.iter().filter_map(|v| v.as_str()) { aggressors.insert(x.to_string()); }+ }+ let mut victims: BTreeSet<String> = BTreeSet::new();+ for key in ["sensitiveNets", "analogNets"] {+ for n in spec[key].as_array().into_iter().flatten().filter_map(|v| v.as_str()) {+ victims.insert(n.to_string());+ }+ }+ if let Some(a) = spec["signalPriority"].as_array() {+ for entry in a {+ let cls = entry["class"].as_str().or(entry["name"].as_str()).unwrap_or("").to_ascii_lowercase();+ let why = entry["why"].as_str().unwrap_or("").to_ascii_lowercase();+ if cls.contains("analog") || cls.contains("sens") || cls.contains("adc") || why.contains("analog") || why.contains("sens") {+ for n in entry["nets"].as_array().into_iter().flatten().filter_map(|v| v.as_str()) {+ victims.insert(n.to_string());+ }+ }+ }+ }+ // Diff-pair partners should never be flagged against each other+ let mut same_pair: BTreeSet<(String, String)> = BTreeSet::new();+ if let Ok(ts) = impedance::targets(spec) {+ for t in ts {+ if t.diff && t.nets.len() == 2 {+ same_pair.insert((t.nets[0].clone(), t.nets[1].clone()));+ same_pair.insert((t.nets[1].clone(), t.nets[0].clone()));+ }+ }+ }++ // Collect candidate tracks+ let mut agg_tracks: Vec<&Track> = Vec::new();+ let mut vic_tracks: Vec<&Track> = Vec::new();+ for tr in &tracks {+ if tr.net.is_empty() || is_gnd_net(&tr.net) || spec_planes.contains(&tr.net) { continue; }+ if aggressors.contains(&tr.net) || is_fast_signal_net(&tr.net) {+ agg_tracks.push(tr);+ }+ if victims.contains(&tr.net) || is_sensitive_net(&tr.net) {+ vic_tracks.push(tr);+ }+ }++ // Accumulate close parallel length per (aggressor, victim, layer)+ let mut acc: BTreeMap<(String, String, usize), (f64, f64, f64)> = BTreeMap::new(); // (run_mm, min_gap, req_gap)+ for a in &agg_tracks {+ let h_opt = layer_dielectric_h(board, spec, a.layer);+ let req_gap = explicit_spacing.unwrap_or_else(|| {+ let w3 = 3.0 * a.width.max(0.15);+ match h_opt {+ Some(h) if h <= 0.5 => w3.max(3.0 * h),+ _ => w3,+ }+ });+ for v in &vic_tracks {+ if a.net == v.net || same_pair.contains(&(a.net.clone(), v.net.clone())) { continue; }+ if let Some((ov, gap)) = parallel_overlap_mm(a, v) {+ if gap < req_gap {+ let e = acc.entry((a.net.clone(), v.net.clone(), a.layer)).or_insert((0.0, f64::INFINITY, req_gap));+ e.0 += ov;+ e.1 = e.1.min(gap);+ e.2 = e.2.max(req_gap);+ }+ }+ }+ }++ let mut pairs = Vec::new();+ let mut findings = Vec::new();+ for ((agg, vic, layer), (run_mm, min_gap, req_gap)) in acc {+ if run_mm > min_parallel {+ let lname = layer_name(layer);+ pairs.push(json!({+ "aggressor": agg,+ "victim": vic,+ "layer": lname,+ "parallelMm": (run_mm * 100.0).round() / 100.0,+ "minGapMm": (min_gap * 1000.0).round() / 1000.0,+ "requiredGapMm": (req_gap * 1000.0).round() / 1000.0,+ }));+ findings.push(format!(+ "3W/3H crosstalk: {agg} runs parallel to sensitive net {vic} for {run_mm:.1} mm on {lname} at {min_gap:.2} mm edge gap (need >= {req_gap:.2} mm or parallel run <= {min_parallel:.0} mm)"+ ));+ }+ }++ json!({+ "pass": findings.is_empty(),+ "maxParallelMm": min_parallel,+ "pairs": pairs,+ "findings": findings,+ })+}++#[cfg(test)]+mod tests {+ use super::*;++ fn board_4l(segs: &str, vias: &str, zones: &str) -> Board {+ let pcb = format!(+ "(kicad_pcb (version 20241229) (generator \"test\") (general (thickness 1.6)) \+ (layers (0 \"F.Cu\" signal) (4 \"In1.Cu\" signal) (6 \"In2.Cu\" signal) (2 \"B.Cu\" signal) (25 \"Edge.Cuts\" user)) \+ (setup (stackup (layer \"F.Cu\" (type \"copper\") (thickness 0.035)) (layer \"dielectric 1\" (type \"prepreg\") (thickness 0.2104) (epsilon_r 4.4)) \+ (layer \"In1.Cu\" (type \"copper\") (thickness 0.0152)) (layer \"dielectric 2\" (type \"core\") (thickness 1.065) (epsilon_r 4.6)) \+ (layer \"In2.Cu\" (type \"copper\") (thickness 0.0152)) (layer \"dielectric 3\" (type \"prepreg\") (thickness 0.2104) (epsilon_r 4.4)) \+ (layer \"B.Cu\" (type \"copper\") (thickness 0.035)))) \+ (net 0 \"\") (net 1 \"USB_DP\") (net 2 \"USB_DN\") (net 3 \"GND\") (net 4 \"SPI_CLK\") (net 5 \"ADC_IN\") \+ (footprint \"T:J1\" (layer \"F.Cu\") (at 4 10) (property \"Reference\" \"J1\") \+ (pad \"1\" smd rect (at 0 -0.25) (size 0.8 0.3) (layers \"F.Cu\") (net 1 \"USB_DP\")) \+ (pad \"2\" smd rect (at 0 0.25) (size 0.8 0.3) (layers \"F.Cu\") (net 2 \"USB_DN\"))) \+ (footprint \"T:U1\" (layer \"F.Cu\") (at 36 10) (property \"Reference\" \"U1\") \+ (pad \"1\" smd rect (at 0 -0.25) (size 0.8 0.3) (layers \"F.Cu\") (net 1 \"USB_DP\")) \+ (pad \"2\" smd rect (at 0 0.25) (size 0.8 0.3) (layers \"F.Cu\") (net 2 \"USB_DN\"))) \+ {segs} {vias} {zones} \+ (gr_rect (start 0 0) (end 40 20) (layer \"Edge.Cuts\") (stroke (width 0.1) (type solid))))"+ );+ Board::from_text("si-test.kicad_pcb", pcb).unwrap()+ }++ #[test]+ fn reference_plane_catches_plane_split_and_passes_solid_plane() {+ let segs = "(segment (start 4 9.75) (end 36 9.75) (width 0.25) (layer \"F.Cu\") (net 1)) \+ (segment (start 4 10.25) (end 36 10.25) (width 0.25) (layer \"F.Cu\") (net 2))";+ let split_zones = "(zone (net 3) (net_name \"GND\") (layer \"In1.Cu\") (filled_polygon (layer \"In1.Cu\") (pts (xy 1 1) (xy 17 1) (xy 17 19) (xy 1 19)))) \+ (zone (net 3) (net_name \"GND\") (layer \"In1.Cu\") (filled_polygon (layer \"In1.Cu\") (pts (xy 23 1) (xy 39 1) (xy 39 19) (xy 23 19))))";+ let solid_zone = "(zone (net 3) (net_name \"GND\") (layer \"In1.Cu\") (filled_polygon (layer \"In1.Cu\") (pts (xy 1 1) (xy 39 1) (xy 39 19) (xy 1 19))))";+ let spec = json!({"impedanceTargets": {"USB": {"pair": ["USB_DP", "USB_DN"], "targetDiffOhms": 90}}});+ let targets = impedance::targets(&spec).unwrap();++ let bad = reference_plane_audit(&board_4l(segs, "", split_zones), &spec, &targets);+ assert_eq!(bad["pass"], false, "{bad}");+ assert!(bad["targets"][0]["maxMissingStretchMm"].as_f64().unwrap() >= 5.0, "{bad}");++ let good = reference_plane_audit(&board_4l(segs, "", solid_zone), &spec, &targets);+ assert_eq!(good["pass"], true, "{good}");+ assert!(good["targets"][0]["coveragePercent"].as_f64().unwrap() >= 99.0, "{good}");+ }++ #[test]+ fn return_via_audit_catches_missing_stitch_and_passes_with_gnd_via() {+ let segs = "(segment (start 4 15) (end 20 15) (width 0.2) (layer \"F.Cu\") (net 4)) \+ (segment (start 20 15) (end 36 15) (width 0.2) (layer \"B.Cu\") (net 4))";+ let spec = json!({"clocks": {"SPI_CLK": {"freqHz": 20_000_000}}});++ let bad = return_via_audit(&board_4l(segs, "(via (at 20 15) (size 0.6) (drill 0.3) (layers \"F.Cu\" \"B.Cu\") (net 4))", ""), &spec);+ assert_eq!(bad["pass"], false, "{bad}");+ assert_eq!(bad["missing"].as_array().unwrap().len(), 1);++ let good = return_via_audit(&board_4l(segs, "(via (at 20 15) (size 0.6) (drill 0.3) (layers \"F.Cu\" \"B.Cu\") (net 4)) (via (at 20 16.5) (size 0.6) (drill 0.3) (layers \"F.Cu\" \"B.Cu\") (net 3))", ""), &spec);+ assert_eq!(good["pass"], true, "{good}");++ // Real-board regression (argon-aiflow USB_CC1, esc-g431-astra /SWDIO + /SWCLK):+ // Debug and USB-C CC/VBUS control nets must not trigger false return-path via warnings,+ // and a nearby plated through-hole GND pad counts as a return-path connection.+ assert!(!is_fast_signal_net("USB_CC1"));+ assert!(!is_fast_signal_net("USB_CC2"));+ assert!(!is_fast_signal_net("USB_VBUS"));+ assert!(!is_fast_signal_net("/SWDIO"));+ assert!(!is_fast_signal_net("/SWCLK"));+ assert!(is_fast_signal_net("USB_DP"));+ assert!(is_fast_signal_net("USB_DM"));+ assert!(is_fast_signal_net("SPI_CLK"));+ }++ #[test]+ fn crosstalk_3w_catches_close_parallel_run_and_passes_spaced_run() {+ let spec = json!({"clocks": {"SPI_CLK": {"freqHz": 24_000_000}}, "sensitiveNets": ["ADC_IN"]});+ let close = "(segment (start 5 14) (end 25 14) (width 0.2) (layer \"F.Cu\") (net 4)) \+ (segment (start 5 14.45) (end 25 14.45) (width 0.2) (layer \"F.Cu\") (net 5))";+ let bad = crosstalk_3w_audit(&board_4l(close, "", ""), &spec);+ assert_eq!(bad["pass"], false, "{bad}");++ let wide = "(segment (start 5 14) (end 25 14) (width 0.2) (layer \"F.Cu\") (net 4)) \+ (segment (start 5 15.5) (end 25 15.5) (width 0.2) (layer \"F.Cu\") (net 5))";+ let good = crosstalk_3w_audit(&board_4l(wide, "", ""), &spec);+ assert_eq!(good["pass"], true, "{good}");+ }+}
crates/adom-aiflow/src/stackup_presets.rsadded+400@@ -0,0 +1,400 @@+//! Published fabricator stackup presets, stackup confirmation state, and manufacturing+//! impedance-control fab notes (issue #213).+//!+//! `rules use --profile <fab> --layers <n> [--stackup <id>]` binds a published stackup into+//! `spec.json` (`stackupMm`, `epsilonR`, `epsilonRByGap`, `copperUmByLayer`, `solderMask`,+//! `fab.stackupId`, `fab.stackupStatus`) and into the KiCad board's `(setup (stackup ...))` block.+//! `finish` surfaces an advisory whenever controlled-impedance targets rest on an `"assumed"`+//! stackup, and `export` emits `manufacturing/impedance-stackup.md` and `.json`.+use std::path::{Path, PathBuf};++use aiflow_board::{sx, Board};+use aiflow_router::impedance as imp;+use serde_json::{json, Value};++#[derive(Clone, Copy, Debug)]+pub struct StackupPreset {+ pub id: &'static str,+ pub fab: &'static str,+ pub layers: u32,+ pub board_thickness_mm: f64,+ pub copper_layers: &'static [&'static str],+ pub copper_um: &'static [f64],+ pub dielectric_mm: &'static [f64],+ pub dielectric_kind: &'static [&'static str],+ pub dielectric_material: &'static [&'static str],+ pub epsilon_r_by_gap: &'static [f64],+ pub solder_mask_mm: f64,+ pub solder_mask_er: f64,+ pub summary: &'static str,+}++pub const PRESETS: &[StackupPreset] = &[+ StackupPreset {+ id: "JLC04161H-7628",+ fab: "jlcpcb",+ layers: 4,+ board_thickness_mm: 1.6,+ copper_layers: &["F.Cu", "In1.Cu", "In2.Cu", "B.Cu"],+ copper_um: &[35.0, 15.2, 15.2, 35.0],+ dielectric_mm: &[0.2104, 1.065, 0.2104],+ dielectric_kind: &["prepreg", "core", "prepreg"],+ dielectric_material: &["7628", "FR4", "7628"],+ epsilon_r_by_gap: &[4.4, 4.6, 4.4],+ solder_mask_mm: 0.025,+ solder_mask_er: 3.8,+ summary: "JLCPCB 4L 1.6 mm 7628 standard impedance stackup (1 oz outer / 0.5 oz inner, 0.2104 mm Er 4.4 prepreg)",+ },+ StackupPreset {+ id: "JLC04161H-3313",+ fab: "jlcpcb",+ layers: 4,+ board_thickness_mm: 1.6,+ copper_layers: &["F.Cu", "In1.Cu", "In2.Cu", "B.Cu"],+ copper_um: &[35.0, 15.2, 15.2, 35.0],+ dielectric_mm: &[0.0994, 1.265, 0.0994],+ dielectric_kind: &["prepreg", "core", "prepreg"],+ dielectric_material: &["3313", "FR4", "3313"],+ epsilon_r_by_gap: &[4.05, 4.6, 4.05],+ solder_mask_mm: 0.025,+ solder_mask_er: 3.8,+ summary: "JLCPCB 4L 1.6 mm 3313 impedance stackup (1 oz outer / 0.5 oz inner, 0.0994 mm Er 4.05 prepreg, narrower 50/90 ohm traces)",+ },+ StackupPreset {+ id: "JLC06161H-3313",+ fab: "jlcpcb",+ layers: 6,+ board_thickness_mm: 1.6,+ copper_layers: &["F.Cu", "In1.Cu", "In2.Cu", "In3.Cu", "In4.Cu", "B.Cu"],+ copper_um: &[35.0, 15.2, 15.2, 15.2, 15.2, 35.0],+ dielectric_mm: &[0.0994, 0.55, 0.1388, 0.55, 0.0994],+ dielectric_kind: &["prepreg", "core", "prepreg", "core", "prepreg"],+ dielectric_material: &["3313", "FR4", "2116", "FR4", "3313"],+ epsilon_r_by_gap: &[4.05, 4.6, 4.16, 4.6, 4.05],+ solder_mask_mm: 0.025,+ solder_mask_er: 3.8,+ summary: "JLCPCB 6L 1.6 mm 3313 impedance stackup (1 oz outer / 0.5 oz inner)",+ },+ StackupPreset {+ id: "JLC02161H",+ fab: "jlcpcb",+ layers: 2,+ board_thickness_mm: 1.6,+ copper_layers: &["F.Cu", "B.Cu"],+ copper_um: &[35.0, 35.0],+ dielectric_mm: &[1.53],+ dielectric_kind: &["core"],+ dielectric_material: &["FR4"],+ epsilon_r_by_gap: &[4.5],+ solder_mask_mm: 0.025,+ solder_mask_er: 3.8,+ summary: "JLCPCB 2L 1.6 mm standard FR4 (1 oz copper, 1.53 mm Er 4.5 core)",+ },+];++pub fn find(id: &str) -> Option<&'static StackupPreset> {+ let q = id.trim();+ PRESETS.iter().find(|p| p.id.eq_ignore_ascii_case(q))+}++pub fn default_for(fab_slug: &str, layers: u32) -> Option<&'static StackupPreset> {+ let lower = fab_slug.trim().to_ascii_lowercase();+ PRESETS.iter().find(|p| p.fab == lower && p.layers == layers)+}++pub fn list_lines() -> Vec<String> {+ PRESETS.iter().map(|p| format!(" {:<18} ({}, {}L, {:.1} mm): {}", p.id, p.fab, p.layers, p.board_thickness_mm, p.summary)).collect()+}++/// Write a published stackup preset into `spec.json` (`stackupMm`, `epsilonR`, `epsilonRByGap`,+/// `copperUmByLayer`, `solderMask`, `fab.stackupId`, `fab.stackupStatus`).+pub fn apply_to_spec(preset: &StackupPreset, spec: &mut Value) {+ spec["stackupMm"] = json!(preset.dielectric_mm);+ spec["epsilonR"] = json!(preset.epsilon_r_by_gap[0]);+ spec["epsilonRByGap"] = json!(preset.epsilon_r_by_gap);+ let mut cu_map = serde_json::Map::new();+ for (name, um) in preset.copper_layers.iter().zip(preset.copper_um.iter()) {+ cu_map.insert((*name).to_string(), json!(*um));+ }+ spec["copperUmByLayer"] = Value::Object(cu_map);+ spec["solderMask"] = json!({"thicknessMm": preset.solder_mask_mm, "epsilonR": preset.solder_mask_er});+ if !spec["fab"].is_object() {+ spec["fab"] = json!({});+ }+ let already_confirmed_same = spec["fab"]["stackupStatus"].as_str() == Some("fab-confirmed")+ && spec["fab"]["stackupId"].as_str().is_some_and(|s| s.eq_ignore_ascii_case(preset.id));+ spec["fab"]["stackupId"] = json!(preset.id);+ if !already_confirmed_same {+ spec["fab"]["stackupStatus"] = json!("published-profile");+ }+}++/// Build the KiCad `(stackup ...)` S-expression block for a published preset.+pub fn kicad_stackup_sexpr(preset: &StackupPreset) -> String {+ let mut s = String::from("\t\t(stackup\n");+ s.push_str("\t\t\t(layer \"F.SilkS\" (type \"Top Silk Screen\"))\n");+ s.push_str("\t\t\t(layer \"F.Paste\" (type \"Top Solder Paste\"))\n");+ s.push_str(&format!("\t\t\t(layer \"F.Mask\" (type \"Top Solder Mask\") (thickness {:.4}))\n", preset.solder_mask_mm));+ for (k, (&cu_name, &cu_um)) in preset.copper_layers.iter().zip(preset.copper_um.iter()).enumerate() {+ s.push_str(&format!("\t\t\t(layer \"{cu_name}\" (type \"copper\") (thickness {:.4}))\n", cu_um / 1000.0));+ if k < preset.dielectric_mm.len() {+ s.push_str(&format!(+ "\t\t\t(layer \"dielectric {}\" (type \"{}\") (thickness {:.4}) (material \"{}\") (epsilon_r {:.2}) (loss_tangent 0.02))\n",+ k + 1, preset.dielectric_kind[k], preset.dielectric_mm[k], preset.dielectric_material[k], preset.epsilon_r_by_gap[k]+ ));+ }+ }+ s.push_str(&format!("\t\t\t(layer \"B.Mask\" (type \"Bottom Solder Mask\") (thickness {:.4}))\n", preset.solder_mask_mm));+ s.push_str("\t\t\t(layer \"B.Paste\" (type \"Bottom Solder Paste\"))\n");+ s.push_str("\t\t\t(layer \"B.SilkS\" (type \"Bottom Silk Screen\"))\n");+ s.push_str("\t\t\t(copper_finish \"ENIG\")\n");+ s.push_str("\t\t\t(dielectric_constraints yes)\n");+ s.push_str("\t\t)");+ s+}++/// Write or replace `(setup (stackup ...))` in a `.kicad_pcb` text with the published preset.+pub fn apply_to_board_text(preset: &StackupPreset, board_text: &str) -> Result<String, String> {+ let root = sx::parse(board_text)?;+ let block = kicad_stackup_sexpr(preset);+ let updated = if let Some(setup) = root.find("setup") {+ if let Some(st) = setup.find("stackup") {+ let mut out = String::with_capacity(board_text.len() + block.len());+ out.push_str(&board_text[..st.start]);+ out.push_str(block.trim_start());+ out.push_str(&board_text[st.end..]);+ out+ } else {+ // Insert before the closing ')' of (setup ...)+ let ins = setup.end.saturating_sub(1);+ let mut out = String::with_capacity(board_text.len() + block.len() + 4);+ out.push_str(&board_text[..ins]);+ out.push('\n');+ out.push_str(&block);+ out.push('\n');+ out.push_str(&board_text[ins..]);+ out+ }+ } else if let Some(layers) = root.find("layers") {+ let ins = layers.end;+ let mut out = String::with_capacity(board_text.len() + block.len() + 32);+ out.push_str(&board_text[..ins]);+ out.push_str("\n\t(setup\n");+ out.push_str(&block);+ out.push_str("\n\t)");+ out.push_str(&board_text[ins..]);+ out+ } else {+ return Err("board file has no (setup ...) or (layers ...) block".into());+ };+ // Verify the modified board still parses cleanly+ let _ = Board::from_text("stackup-check.kicad_pcb", updated.clone())?;+ Ok(updated)+}++#[derive(Clone, Debug, PartialEq)]+pub struct Confirmation {+ pub status: String,+ pub stackup_id: Option<String>,+ pub confirmed_source: Option<String>,+}++/// Read stackup confirmation metadata from `spec.fab`.+pub fn confirmation(spec: &Value) -> Confirmation {+ let fab = spec.get("fab");+ let raw_status = fab.and_then(|f| f.get("stackupStatus")).and_then(|v| v.as_str()).unwrap_or("assumed");+ let status = match raw_status {+ "published-profile" | "fab-confirmed" | "assumed" => raw_status.to_string(),+ _ => "assumed".to_string(),+ };+ let stackup_id = fab.and_then(|f| f.get("stackupId")).and_then(|v| v.as_str()).filter(|s| !s.trim().is_empty()).map(str::to_string);+ let confirmed_source = fab.and_then(|f| f.get("confirmedSource")).and_then(|v| v.as_str()).filter(|s| !s.trim().is_empty()).map(str::to_string);+ Confirmation { status, stackup_id, confirmed_source }+}++/// Open advisory for `finish` when controlled-impedance targets use an unconfirmed stackup.+pub fn finish_advisory(spec: &Value) -> Option<String> {+ let targets = imp::targets(spec).ok()?;+ if targets.is_empty() { return None; }+ let c = confirmation(spec);+ if c.status == "assumed" {+ Some("controlled impedance uses an unconfirmed stackup (fab.stackupStatus is \"assumed\"): bind a published fab stackup (`adom-aiflow rules use --profile <fab> --layers <n> --stackup <id>`) and confirm trace width/gap with the fabricator's impedance calculator before ordering".into())+ } else {+ None+ }+}++/// Write `impedance-stackup.md` and `impedance-stackup.json` into `out_dir` during `export`+/// whenever the spec declares impedance targets.+pub fn write_export_table(out_dir: &Path, board: &Board, spec: &Value, board_path: &str) -> Result<Option<(Value, PathBuf, PathBuf)>, String> {+ let Some((plan, check_rows)) = crate::impedance_cmd::check(board, spec, board_path, None)? else {+ return Ok(None);+ };+ let conf = confirmation(spec);+ let md_path = out_dir.join("impedance-stackup.md");+ let json_path = out_dir.join("impedance-stackup.json");++ let mut layer_rows = Vec::new();+ for g in &plan.stack.layers {+ layer_rows.push(json!({+ "layer": g.name,+ "structure": g.structure,+ "dielectricMm": match g.h2 { None => json!(g.h1), Some(h2) => json!([g.h1, h2]) },+ "epsilonR": g.er,+ "copperUm": (g.t * 1000.0 * 10.0).round() / 10.0,+ "referenceLayers": g.reference,+ "solderMask": g.solder_mask.map(|m| json!({"thicknessMm": m.thickness_mm, "epsilonR": m.er})),+ }));+ }++ let mut target_rows = Vec::new();+ for (t, cr) in plan.targets.iter().zip(&check_rows) {+ let primary_layer = cr["lengthByLayerMm"].as_object()+ .and_then(|m| m.iter().max_by(|a, b| a.1.as_f64().unwrap_or(0.0).total_cmp(&b.1.as_f64().unwrap_or(0.0))).map(|(k, _)| k.clone()))+ .or_else(|| t.layer.clone())+ .unwrap_or_else(|| "F.Cu".into());+ let ref_layers = plan.stack.layers.iter().find(|g| g.name == primary_layer).map(|g| g.reference.clone()).unwrap_or_default();+ let table_row = plan.rows.iter().find(|r| r["target"] == t.name.as_str() && r["layer"] == primary_layer.as_str()).cloned().unwrap_or(Value::Null);+ let drawn_widths = cr["widthsMm"].clone();+ let drawn_gap = cr.get("gapMm").cloned().unwrap_or(Value::Null);+ let coupon_required = t.tolerance <= 10.0;+ target_rows.push(json!({+ "target": t.name,+ "nets": t.nets,+ "mode": if t.diff { "differential" } else { "single-ended" },+ "targetOhms": t.ohms,+ "tolerancePercent": t.tolerance,+ "layer": primary_layer,+ "referenceLayers": ref_layers,+ "drawnWidthsMm": drawn_widths,+ "drawnGapMm": drawn_gap,+ "tableWidthMm": table_row["widthMm"],+ "tableGapMm": table_row["gapMm"],+ "closedFormOhms": cr["ohms"],+ "bareOhms": table_row["bareOhms"],+ "withSolderMaskOhms": table_row["withSolderMaskOhms"],+ "solderMaskShiftPercent": table_row["solderMaskShiftPercent"],+ "status": cr["status"],+ "couponRequired": coupon_required,+ }));+ }++ let doc = json!({+ "stackupStatus": conf.status,+ "stackupId": conf.stackup_id,+ "confirmedSource": conf.confirmed_source,+ "stackupSources": plan.stack.sources,+ "layers": layer_rows,+ "targets": target_rows,+ "couponNote": "Include impedance test coupons on the production panel rail for every controlled-impedance layer and mode listed above.",+ });++ let mut md = String::new();+ md.push_str("# Controlled Impedance and Stackup Specification\n\n");+ md.push_str(&format!("- **Stackup status:** `{}`\n", conf.status));+ if let Some(id) = &conf.stackup_id { md.push_str(&format!("- **Stackup ID:** `{id}`\n")); }+ if let Some(src) = &conf.confirmed_source { md.push_str(&format!("- **Fabricator confirmation:** {src}\n")); }+ if conf.status == "assumed" {+ md.push_str("- **Warning:** Stackup dielectric values are assumed, not fabricator-confirmed. Confirm trace widths and gaps against the fabricator's stackup calculator before production.\n");+ }+ if let Some(m) = plan.stack.solder_mask {+ md.push_str(&format!("- **Outer solder mask:** {:.3} mm above copper, Er {:.2}\n", m.thickness_mm, m.er));+ } else {+ md.push_str("- **Outer solder mask:** not modelled in closed-form widths (see coated estimates below)\n");+ }+ md.push_str("\n## Layer Stackup\n\n");+ md.push_str("| Layer | Structure | Dielectric (mm) | Er | Copper (um) | Reference Layer(s) |\n|---|---|---|---|---|---|\n");+ for g in &plan.stack.layers {+ let diel = match g.h2 { None => format!("{:.4}", g.h1), Some(h2) => format!("{:.4} / {:.4}", g.h1, h2) };+ md.push_str(&format!("| {} | {} | {} | {:.2} | {:.1} | {} |\n", g.name, g.structure, diel, g.er, g.t * 1000.0, g.reference.join(", ")));+ }+ md.push_str("\n## Controlled Impedance Targets\n\n");+ md.push_str("| Target | Nets | Mode | Target Z | Layer | Reference | Drawn Width (mm) | Drawn Gap (mm) | Coupon |\n|---|---|---|---|---|---|---|---|---|\n");+ for r in &target_rows {+ let nets = r["nets"].as_array().map(|a| a.iter().filter_map(|v| v.as_str()).collect::<Vec<_>>().join(" / ")).unwrap_or_default();+ let refs = r["referenceLayers"].as_array().map(|a| a.iter().filter_map(|v| v.as_str()).collect::<Vec<_>>().join(", ")).unwrap_or_default();+ let w = r["drawnWidthsMm"].to_string();+ let g = if r["drawnGapMm"].is_null() { "-".to_string() } else { r["drawnGapMm"].to_string() };+ md.push_str(&format!(+ "| {} | {} | {} | {} ohm +/- {}% | {} | {} | {} | {} | {} |\n",+ r["target"].as_str().unwrap_or(""),+ nets,+ r["mode"].as_str().unwrap_or(""),+ r["targetOhms"],+ r["tolerancePercent"],+ r["layer"].as_str().unwrap_or(""),+ refs,+ w,+ g,+ if r["couponRequired"] == true { "Yes (panel coupon)" } else { "Optional" }+ ));+ }+ md.push_str("\n## Fabrication Note\n\nRequest fabricator stackup confirmation and impedance test coupons on the panel rail before volume build. Fabricator may adjust trace widths within tolerance to hit the target impedance on actual pressed prepreg.\n");++ std::fs::create_dir_all(out_dir).map_err(|e| format!("{}: {e}", out_dir.display()))?;+ std::fs::write(&md_path, md).map_err(|e| format!("{}: {e}", md_path.display()))?;+ std::fs::write(&json_path, serde_json::to_string_pretty(&doc).unwrap()).map_err(|e| format!("{}: {e}", json_path.display()))?;+ Ok(Some((doc, md_path, json_path)))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn presets_lookup_and_apply_to_spec_and_board() {+ let p = find("jlc04161h-7628").expect("7628 preset");+ assert_eq!(p.layers, 4);+ assert_eq!(default_for("jlcpcb", 4).unwrap().id, "JLC04161H-7628");+ assert!(default_for("3rdPartyFab", 4).is_none(), "private fab rules must not ship generic stackups");+ assert!(find("3rdPartyFab-4L").is_none());+ let mut spec = json!({"impedanceTargets": {"USB": {"pair": ["USB_DP", "USB_DN"], "targetDiffOhms": 90}}});+ assert!(finish_advisory(&spec).is_some(), "assumed stackup must raise advisory");+ apply_to_spec(p, &mut spec);+ assert_eq!(spec["fab"]["stackupId"], "JLC04161H-7628");+ assert_eq!(spec["fab"]["stackupStatus"], "published-profile");+ assert_eq!(spec["stackupMm"], json!([0.2104, 1.065, 0.2104]));+ assert_eq!(spec["solderMask"]["thicknessMm"], 0.025);+ assert!(finish_advisory(&spec).is_none(), "published-profile clears the assumed-stackup advisory");++ let bare_board = r#"(kicad_pcb (version 20241229) (generator "test")+ (layers (0 "F.Cu" signal) (4 "In1.Cu" signal) (6 "In2.Cu" signal) (31 "B.Cu" signal) (44 "Edge.Cuts" user))+ (net 0 "") (net 1 "GND")+ (gr_rect (start 0 0) (end 30 20) (layer "Edge.Cuts")))"#;+ let with_st = apply_to_board_text(p, bare_board).unwrap();+ let b = Board::from_text("t.kicad_pcb", with_st).unwrap();+ let st = imp::stackup(&b, &spec).unwrap();+ assert_eq!(st.layers.len(), 4);+ assert!((st.layers[0].h1 - 0.2104).abs() < 1e-6);+ assert!(st.solder_mask.is_some());+ }++ #[test]+ fn write_export_table_writes_md_and_json_in_own_temp_dir() {+ let dir = std::env::temp_dir().join(format!("aiflow-stackup-export-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ let p = find("JLC04161H-7628").unwrap();+ let mut spec = json!({+ "clearance": 0.127, "minTrackWidth": 0.127, "track": 0.2,+ "impedanceTargets": {"USB": {"pair": ["USB_DP", "USB_DN"], "targetDiffOhms": 90, "gapMm": 0.2}}+ });+ apply_to_spec(p, &mut spec);+ let bare = r#"(kicad_pcb (version 20241229) (generator "test")+ (layers (0 "F.Cu" signal) (4 "In1.Cu" signal) (6 "In2.Cu" signal) (31 "B.Cu" signal) (44 "Edge.Cuts" user))+ (net 0 "") (net 1 "USB_DP") (net 2 "USB_DN") (net 3 "GND")+ (footprint "T:J1" (layer "F.Cu") (at 5 10) (property "Reference" "J1")+ (pad "1" smd rect (at 0 -0.25) (size 0.5 0.3) (layers "F.Cu") (net 1 "USB_DP"))+ (pad "2" smd rect (at 0 0.25) (size 0.5 0.3) (layers "F.Cu") (net 2 "USB_DN")))+ (footprint "T:U1" (layer "F.Cu") (at 25 10) (property "Reference" "U1")+ (pad "1" smd rect (at 0 -0.25) (size 0.5 0.3) (layers "F.Cu") (net 1 "USB_DP"))+ (pad "2" smd rect (at 0 0.25) (size 0.5 0.3) (layers "F.Cu") (net 2 "USB_DN")))+ (segment (start 5 9.75) (end 25 9.75) (width 0.25) (layer "F.Cu") (net 1))+ (segment (start 5 10.25) (end 25 10.25) (width 0.25) (layer "F.Cu") (net 2))+ (gr_rect (start 0 0) (end 30 20) (layer "Edge.Cuts")))"#;+ let b = Board::from_text("t.kicad_pcb", apply_to_board_text(p, bare).unwrap()).unwrap();+ let (doc, md, js) = write_export_table(&dir, &b, &spec, "t.kicad_pcb").unwrap().expect("table written");+ assert_eq!(doc["stackupId"], "JLC04161H-7628");+ assert!(md.is_file() && js.is_file());+ let _ = std::fs::remove_dir_all(&dir);+ }+}
crates/adom-aiflow/src/testplan.rs+30−3@@ -181,6 +181,15 @@ pub fn kind_of(t: &Value) -> &str { t["kind"].as_str().unwrap_or(if t["net"].as_str().unwrap_or("").trim().is_empty() { "none" } else { "dc" }) } +/// Issue #242: a test's net as the design names it. "GND" matches the board's or netlist's "/GND" (one leading+/// "/" on either side is ignored, as `netlist check` does); an exact name always wins; no match keeps the name.+pub fn resolve_net<'a>(want: &str, names: impl Iterator<Item = &'a str>) -> String {+ let names: Vec<&str> = names.collect();+ if want.is_empty() || names.contains(&want) { return want.to_string(); }+ let bare = want.trim_start_matches('/');+ names.iter().find(|n| n.trim_start_matches('/') == bare).map(|n| n.to_string()).unwrap_or_else(|| want.to_string())+}+ /// The status of a row that needs no probe spot: the camera's own kinds keep "camera". fn no_spot_status(kind: &str) -> &'static str { if matches!(kind, "camera" | "fixture") { "camera" } else { "no probe" } } @@ -277,7 +286,9 @@ pub fn check_netlist_with_fixture(tests: &[Value], netlist: &Value, cfg: &TestFi let medium_refs = refs_where(&|c| contact_class(&part_text(c)) == Some(false)); let (mut rows, mut gaps, mut unknown) = (Vec::new(), Vec::new(), Vec::new()); for t in tests {- let net = t["net"].as_str().unwrap_or("");+ // issue #242: "GND" in tests.json is the netlist's "/GND" (a hierarchical schematic's names)+ let net = &resolve_net(t["net"].as_str().unwrap_or(""), nets.iter().map(|(n, _)| n.as_str()));+ let net = net.as_str(); let kind = kind_of(t); if !needs_spot(kind) { rows.push(json!({"id": t["id"], "net": net, "kind": kind, "spot": null, "status": no_spot_status(kind)})); continue; } let Some((_, pins)) = nets.iter().find(|(n, _)| n == net) else {@@ -505,14 +516,16 @@ pub fn check_board_with_fixture(tests: &[Value], b: &Board, cfg: &TestFixtureCon let (large_refs, medium_refs) = (contact_refs(true), contact_refs(false)); // the tether ends in a medium pin: it plugs into a medium contact, never a large one let grounds: Vec<(f64, f64, String)> = b.footprints.iter().filter(|(_, fp)| contact_class(&fp.lib) == Some(false))- .flat_map(|(r, _)| b.pads_of(r).into_iter().filter(|p| p.net.eq_ignore_ascii_case("GND")).map(move |p| (p.x, p.y, r.clone()))).collect();+ .flat_map(|(r, _)| b.pads_of(r).into_iter().filter(|p| p.net.trim_start_matches('/').eq_ignore_ascii_case("GND")).map(move |p| (p.x, p.y, r.clone()))).collect(); let (mut rows, mut gaps, mut warn) = (Vec::new(), Vec::new(), Vec::new()); if !bon && !cfg.is_manual_bench() && grounds.is_empty() { warn.push("no MachineContactMedium on GND: the ground tether has nowhere to plug in (add one near each corner, adom/probing-workcell)".into()); } let mut selected_spots: Vec<(String, String, f64, f64)> = Vec::new(); for t in tests {- let net = t["net"].as_str().unwrap_or("");+ // issue #242: "GND" in tests.json is the board's "/GND" (a hierarchical schematic's names)+ let net = &resolve_net(t["net"].as_str().unwrap_or(""), b.nets.keys().map(|n| n.as_str()));+ let net = net.as_str(); let kind = kind_of(t); if !needs_spot(kind) { rows.push(json!({"id": t["id"], "net": net, "kind": kind, "status": no_spot_status(kind)})); continue; } if kind == "ground" && !bon {@@ -684,6 +697,20 @@ mod tests { assert!(gaps.is_empty()); assert_eq!(unknown, vec!["T05 (no \"net\"; a dc test needs one)".to_string()]); }+ /// Issue #242: tests.json written from netlist.json names "GND" and "+5V"; a hierarchical design's board and+ /// netlist name them "/GND" and "/+5V". They match, the row reports the design's name, an exact name wins.+ #[test]+ fn test_nets_match_the_designs_hierarchical_names() {+ assert_eq!(resolve_net("GND", ["/GND", "/+5V"].into_iter()), "/GND");+ assert_eq!(resolve_net("/+5V", ["+5V"].into_iter()), "+5V");+ assert_eq!(resolve_net("GND", ["GND", "/GND"].into_iter()), "GND");+ assert_eq!(resolve_net("NOPE", ["/GND"].into_iter()), "NOPE");+ let nl = json!({"components": [{"ref": "U1"}, {"ref": "TP1", "fp": "TestPoint"}], "nets": [["/+5V", ["U1.3", "TP1.1"]]]});+ let (rows, gaps, unknown) = check_netlist(&[json!({"id": "v5", "net": "+5V", "kind": "dc"})], &nl);+ assert!(gaps.is_empty() && unknown.is_empty(), "{gaps:?} {unknown:?}");+ assert_eq!((rows[0]["net"].as_str(), rows[0]["status"].as_str()), (Some("/+5V"), Some("test point")));+ }+ /// The real contact footprints' shape, and three test kinds on them. fn contacts_board(medium_fab: &str) -> Board { let text = format!(r#"(kicad_pcb
crates/adom-aiflow/src/usb_power.rsadded+362@@ -0,0 +1,362 @@+//! USB VBUS inrush capacitance and rail load-budget checks (issue #215).+//!+//! 1. USB 2.0 limits direct downstream capacitance on VBUS to 10 uF without an inrush-limiting+//! load switch or soft-start stage. This check sums both nominal capacitance (parsed from+//! capacitor values on VBUS nets) and DC-bias-derated effective capacitance (`uFAtBias` from+//! `adom-fields --with pdn` when available, else a package-size MLCC estimate) and warns when+//! total VBUS capacitance exceeds 10 uF without a declared limiter.+//! 2. Checks that declared rail `loads` and auxiliary draws (`auxiliaryLoads`) do not exceed the+//! upstream USB or regulator current budget declared in `requirements.json` or `spec.json`.++use std::collections::{BTreeMap, BTreeSet};++use aiflow_board::Board;+use serde_json::{json, Value};++pub const USB_VBUS_MAX_UF: f64 = 10.0;++fn is_vbus_net(name: &str) -> bool {+ let u = name.trim_start_matches('/').to_ascii_uppercase();+ let u = u.rsplit('/').next().unwrap_or(&u);+ u == "VBUS" || u.starts_with("VBUS_") || u.ends_with("_VBUS") || u.contains("USB_VBUS") || u == "5V_USB" || u == "+5V_USB" || u == "USB_5V"+}++fn is_gnd_net(name: &str) -> bool {+ let u = name.trim_start_matches('/').to_ascii_uppercase();+ let u = u.rsplit('/').next().unwrap_or(&u);+ u == "GND" || u == "AGND" || u == "DGND" || u == "PGND" || u == "VSS" || u.contains("GND")+}++/// Parse a capacitor value string (e.g. "10uF", "4.7u", "100nF", "22uF_0805", "470pF", "1mF")+/// into microfarads (uF).+pub fn parse_capacitance_uf(raw: &str) -> Option<f64> {+ let s = raw.trim().replace('µ', "u").replace('μ', "u");+ for token in s.split(|c: char| c.is_whitespace() || c == '_' || c == '/' || c == ',' || c == ';') {+ let t = token.trim();+ if t.is_empty() { continue; }+ let bytes = t.as_bytes();+ let mut idx = 0;+ let mut dot = false;+ while idx < bytes.len() && (bytes[idx].is_ascii_digit() || (!dot && bytes[idx] == b'.')) {+ if bytes[idx] == b'.' { dot = true; }+ idx += 1;+ }+ if idx == 0 { continue; }+ let num: f64 = t[..idx].parse().ok()?;+ let rest = t[idx..].to_ascii_lowercase();+ let mul = if rest == "uf" || rest == "u" {+ 1.0+ } else if rest == "nf" || rest == "n" {+ 1e-3+ } else if rest == "pf" || rest == "p" {+ 1e-6+ } else if rest == "mf" {+ 1e3+ } else {+ continue;+ };+ if num > 0.0 && num.is_finite() {+ return Some(num * mul);+ }+ }+ None+}++/// Rough DC-bias retention factor at 5 V for class-II MLCCs when `adom-fields --with pdn` did not+/// provide a measured `uFAtBias` curve (conservative: small 0402/0603 high-C parts derate more).+fn mlcc_5v_retention(nominal_uf: f64, fp_name: &str) -> f64 {+ let f = fp_name.to_ascii_uppercase();+ if f.contains("ELEC") || f.contains("TANT") || f.contains("POLY") || f.contains("CP_") {+ return 1.0;+ }+ if nominal_uf < 1.0 { return 0.90; }+ if f.contains("0402") { return 0.45; }+ if f.contains("0603") { return 0.60; }+ if f.contains("0805") { return 0.72; }+ if f.contains("1206") || f.contains("1210") { return 0.85; }+ 0.70+}++fn fields_cap_bias_map(fields: Option<&Value>) -> BTreeMap<String, f64> {+ let mut map = BTreeMap::new();+ let Some(f) = fields else { return map };+ for rail in f["review"]["pdn"]["rails"].as_array().into_iter().flatten() {+ for cap in rail["caps"].as_array().into_iter().flatten() {+ let r = cap["ref"].as_str().or(cap["reference"].as_str()).unwrap_or("");+ let uf = cap["uFAtBias"].as_f64().or(cap["ufAtBias"].as_f64());+ if !r.is_empty() {+ if let Some(v) = uf { map.insert(r.to_string(), v); }+ }+ }+ }+ map+}++fn has_inrush_limiter(board: &Board, spec: &Value) -> Option<String> {+ if let Some(s) = spec["inrushLimiter"].as_str().filter(|s| !s.is_empty()) {+ return Some(format!("spec.inrushLimiter ({s})"));+ }+ if spec["inrushLimiter"].as_bool() == Some(true) || spec["usbInrushLimiter"].as_bool() == Some(true) {+ return Some("spec.inrushLimiter".into());+ }+ if let Some(s) = spec["usbInrushLimiter"].as_str().filter(|s| !s.is_empty()) {+ return Some(format!("spec.usbInrushLimiter ({s})"));+ }+ if let Some(s) = spec["usb"]["inrushLimiter"].as_str().filter(|s| !s.is_empty()) {+ return Some(format!("spec.usb.inrushLimiter ({s})"));+ }+ let limiter_tokens = ["TPS255", "TPS259", "TPS266", "TPS229", "MAX1761", "AP228", "AP217", "MIC20", "SY628", "RT974", "EFUSE", "LOAD_SW", "LOADSW", "INRUSH", "SOFT_START", "SOFTSTART"];+ for fp in board.root.find_all("footprint") {+ let reference = fp.find_all("property").find(|p| p.atom(1) == Some("Reference")).and_then(|p| p.atom(2)).unwrap_or("");+ let value = fp.find_all("property").find(|p| p.atom(1) == Some("Value")).and_then(|p| p.atom(2)).unwrap_or("");+ let txt = value.to_ascii_uppercase();+ if limiter_tokens.iter().any(|k| txt.contains(k)) {+ let on_vbus = board.pads.iter().any(|p| p.reference == reference && is_vbus_net(&p.net));+ if on_vbus {+ return Some(format!("{reference} ({value})"));+ }+ }+ }+ None+}++/// Audit USB VBUS capacitance against the 10 uF USB 2.0 inrush limit.+pub fn check_usb_inrush(board: &Board, spec: &Value, fields: Option<&Value>) -> Value {+ let limit_uf = spec["usb"]["maxVbusCapacitanceUf"].as_f64().unwrap_or(USB_VBUS_MAX_UF);+ let bias_map = fields_cap_bias_map(fields);+ let limiter = has_inrush_limiter(board, spec);++ // Find all VBUS nets present on the board (KiCad 10 uses board.nets with empty net_table)+ let vbus_nets: BTreeSet<String> = board.nets.keys()+ .chain(board.net_table.values())+ .filter(|n| is_vbus_net(n))+ .cloned()+ .collect();+ if vbus_nets.is_empty() {+ return json!({"pass": true, "checked": false, "vbusNets": [], "findings": []});+ }++ let mut caps = Vec::new();+ let mut total_nom_uf = 0.0f64;+ let mut total_eff_uf = 0.0f64;++ for fp in board.root.find_all("footprint") {+ let reference = fp.find_all("property").find(|p| p.atom(1) == Some("Reference")).and_then(|p| p.atom(2)).unwrap_or("");+ if !reference.starts_with('C') { continue; }+ let value = fp.find_all("property").find(|p| p.atom(1) == Some("Value")).and_then(|p| p.atom(2)).unwrap_or("");+ let fp_name = fp.atom(1).unwrap_or("");+ let pad_nets: Vec<&str> = board.pads.iter().filter(|p| p.reference == reference).map(|p| p.net.as_str()).collect();+ let hits_vbus = pad_nets.iter().any(|n| vbus_nets.contains(*n));+ let hits_gnd = pad_nets.iter().any(|n| is_gnd_net(n));+ if !hits_vbus || !hits_gnd { continue; }+ let Some(nom_uf) = parse_capacitance_uf(value) else { continue };+ let (eff_uf, eff_src) = match bias_map.get(reference) {+ Some(&v) => (v, "adom-fields uFAtBias"),+ None => (nom_uf * mlcc_5v_retention(nom_uf, fp_name), "estimated 5V DC-bias retention"),+ };+ total_nom_uf += nom_uf;+ total_eff_uf += eff_uf;+ caps.push(json!({+ "ref": reference,+ "value": value,+ "nominalUf": (nom_uf * 1000.0).round() / 1000.0,+ "effectiveUf": (eff_uf * 1000.0).round() / 1000.0,+ "effectiveSource": eff_src,+ }));+ }++ let mut findings = Vec::new();+ let exceeds = total_nom_uf > limit_uf + 1e-6 || total_eff_uf > limit_uf + 1e-6;+ let pass = !exceeds || limiter.is_some();+ if !pass {+ findings.push(format!(+ "USB VBUS inrush capacitance: {:.2} uF nominal ({:.2} uF effective at 5 V bias) directly on {} exceeds {:.1} uF USB 2.0 limit with no soft-start/load-switch/inrushLimiter declared ({} capacitor(s))",+ total_nom_uf,+ total_eff_uf,+ vbus_nets.iter().cloned().collect::<Vec<_>>().join(", "),+ limit_uf,+ caps.len()+ ));+ }++ json!({+ "pass": pass,+ "checked": true,+ "vbusNets": vbus_nets.into_iter().collect::<Vec<_>>(),+ "limitUf": limit_uf,+ "nominalUf": (total_nom_uf * 100.0).round() / 100.0,+ "effectiveUf": (total_eff_uf * 100.0).round() / 100.0,+ "inrushLimiter": limiter,+ "capacitors": caps,+ "findings": findings,+ })+}++/// Check declared rail `loads` and `auxiliaryLoads` against upstream USB or regulator current+/// budgets in `requirements.json` and `spec.json`.+pub fn check_load_budget(spec: &Value, requirements: &Value) -> Value {+ let mut rail_amps: BTreeMap<String, f64> = BTreeMap::new();+ let mut load_rows = Vec::new();++ if let Some(o) = spec["loads"].as_object() {+ for (net, entry) in o {+ if is_gnd_net(net) { continue; }+ let amps = entry["amps"].as_f64()+ .or_else(|| entry.as_array().map(|a| a.iter().filter_map(|x| x["amps"].as_f64()).sum()))+ .unwrap_or(0.0);+ if amps > 0.0 {+ *rail_amps.entry(net.clone()).or_insert(0.0) += amps;+ load_rows.push(json!({"net": net, "amps": amps, "kind": "load"}));+ }+ }+ }+ if let Some(o) = spec["auxiliaryLoads"].as_object() {+ for (name, entry) in o {+ let net = entry["net"].as_str().unwrap_or(name.as_str()).to_string();+ let amps = entry["amps"].as_f64().or_else(|| entry.as_f64()).unwrap_or(0.0);+ if amps > 0.0 {+ *rail_amps.entry(net.clone()).or_insert(0.0) += amps;+ load_rows.push(json!({"name": name, "net": net, "amps": amps, "kind": "auxiliary"}));+ }+ }+ } else if let Some(a) = spec["auxiliaryLoads"].as_array() {+ for entry in a {+ let net = entry["net"].as_str().unwrap_or("AUX").to_string();+ let amps = entry["amps"].as_f64().unwrap_or(0.0);+ if amps > 0.0 {+ *rail_amps.entry(net.clone()).or_insert(0.0) += amps;+ load_rows.push(json!({"name": entry["name"].as_str().unwrap_or(&net), "net": net, "amps": amps, "kind": "auxiliary"}));+ }+ }+ }++ // Collect budgets: per-rail from spec.railBudgets / spec.sourceLimits / requirements.power.rails,+ // and upstream USB/input budget from requirements.usb.maxCurrentA / requirements.power.maxCurrentA / spec.usb.maxCurrentA.+ let mut budgets: BTreeMap<String, (f64, String)> = BTreeMap::new();+ for (src_name, obj) in [("spec.railBudgets", &spec["railBudgets"]), ("spec.sourceLimits", &spec["sourceLimits"]), ("requirements.power.rails", &requirements["power"]["rails"])] {+ if let Some(m) = obj.as_object() {+ for (net, v) in m {+ let lim = v.as_f64().or_else(|| v["maxAmps"].as_f64()).or_else(|| v["maxCurrentA"].as_f64());+ if let Some(a) = lim.filter(|&a| a > 0.0) {+ budgets.insert(net.clone(), (a, src_name.into()));+ }+ }+ }+ }+ let upstream_budget: Option<(f64, String)> = [+ (requirements["usb"]["maxCurrentA"].as_f64(), "requirements.usb.maxCurrentA"),+ (requirements["power"]["maxCurrentA"].as_f64(), "requirements.power.maxCurrentA"),+ (spec["usb"]["maxCurrentA"].as_f64(), "spec.usb.maxCurrentA"),+ (spec["power"]["maxCurrentA"].as_f64(), "spec.power.maxCurrentA"),+ ].into_iter().find_map(|(v, src)| v.filter(|&a| a > 0.0).map(|a| (a, src.to_string())));++ let mut findings = Vec::new();+ for (net, &draw) in &rail_amps {+ if let Some((lim, src)) = budgets.get(net) {+ if draw > *lim + 1e-6 {+ findings.push(format!("rail load budget exceeded on {net}: declared draws total {draw:.2} A > {lim:.2} A limit ({src})"));+ }+ }+ }+ if let Some((lim, src)) = &upstream_budget {+ // Check VBUS directly if present, else total non-GND rail current+ let vbus_sum: f64 = rail_amps.iter().filter(|(n, _)| is_vbus_net(n)).map(|(_, &a)| a).sum();+ let total_sum: f64 = rail_amps.values().sum();+ let checked_draw = if vbus_sum > 0.0 { vbus_sum.max(total_sum) } else { total_sum };+ if checked_draw > *lim + 1e-6 {+ findings.push(format!("upstream power budget exceeded: declared rail loads total {checked_draw:.2} A > {lim:.2} A limit ({src})"));+ }+ }++ json!({+ "pass": findings.is_empty(),+ "rails": rail_amps,+ "loads": load_rows,+ "upstreamBudget": upstream_budget.map(|(a, s)| json!({"maxAmps": a, "source": s})),+ "findings": findings,+ })+}++#[cfg(test)]+mod tests {+ use super::*;++ fn usb_board(caps: &[(&str, &str, &str)], extra_fp: &str) -> Board {+ let mut fps = String::new();+ for (i, (r, val, pkg)) in caps.iter().enumerate() {+ let x = 10.0 + i as f64 * 4.0;+ fps.push_str(&format!(+ "(footprint \"{pkg}\" (layer \"F.Cu\") (at {x} 10) (property \"Reference\" \"{r}\") (property \"Value\" \"{val}\") \+ (pad \"1\" smd rect (at -0.8 0) (size 0.8 0.8) (layers \"F.Cu\") (net 1 \"VBUS\")) \+ (pad \"2\" smd rect (at 0.8 0) (size 0.8 0.8) (layers \"F.Cu\") (net 2 \"GND\"))) "+ ));+ }+ let pcb = format!(+ "(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 \"VBUS\") (net 2 \"GND\") {fps} {extra_fp} \+ (gr_rect (start 0 0) (end 40 20) (layer \"Edge.Cuts\") (stroke (width 0.1) (type solid))))"+ );+ Board::from_text("usb.kicad_pcb", pcb).unwrap()+ }++ #[test]+ fn parses_capacitor_values() {+ assert_eq!(parse_capacitance_uf("10uF"), Some(10.0));+ assert_eq!(parse_capacitance_uf("4.7u"), Some(4.7));+ assert_eq!(parse_capacitance_uf("100nF"), Some(0.1));+ assert_eq!(parse_capacitance_uf("22uF_0805"), Some(22.0));+ }++ #[test]+ fn usb_inrush_fails_above_10uf_and_passes_with_limiter_or_under_10uf() {+ let b_big = usb_board(&[("C1", "22uF", "Capacitor_SMD:C_0805"), ("C2", "10uF", "Capacitor_SMD:C_0805")], "");+ let bad = check_usb_inrush(&b_big, &json!({}), None);+ assert_eq!(bad["pass"], false, "{bad}");+ assert!(bad["nominalUf"].as_f64().unwrap() >= 31.9);++ let with_lim = check_usb_inrush(&b_big, &json!({"inrushLimiter": "U5 TPS2553"}), None);+ assert_eq!(with_lim["pass"], true, "{with_lim}");++ let b_ok = usb_board(&[("C1", "4.7uF", "Capacitor_SMD:C_0603"), ("C2", "100nF", "Capacitor_SMD:C_0402")], "");+ let good = check_usb_inrush(&b_ok, &json!({}), None);+ assert_eq!(good["pass"], true, "{good}");++ // Real-board regression (astra-aiflow KiCad 10 format + TPS26600PWPR eFuse):+ // KiCad 10 has no top-level (net 1 "VBUS") table; board.nets must still be scanned.+ let k10 = concat!(+ "(kicad_pcb (version 20260101) (generator \"pcbnew\") ",+ "(layers (0 \"F.Cu\" signal) (2 \"B.Cu\" signal) (25 \"Edge.Cuts\" user)) ",+ "(footprint \"Capacitor_SMD:C_0805\" (layer \"F.Cu\") (at 10 10) (property \"Reference\" \"C27\") (property \"Value\" \"10u\") ",+ "(pad \"1\" smd rect (at -0.8 0) (size 0.8 0.8) (layers \"F.Cu\") (net \"VBUS\")) ",+ "(pad \"2\" smd rect (at 0.8 0) (size 0.8 0.8) (layers \"F.Cu\") (net \"GND\"))) ",+ "(footprint \"Capacitor_SMD:C_0603\" (layer \"F.Cu\") (at 16 10) (property \"Reference\" \"C4\") (property \"Value\" \"1u\") ",+ "(pad \"1\" smd rect (at -0.8 0) (size 0.8 0.8) (layers \"F.Cu\") (net \"VBUS\")) ",+ "(pad \"2\" smd rect (at 0.8 0) (size 0.8 0.8) (layers \"F.Cu\") (net \"GND\"))) ",+ "(footprint \"Package_SO:HTSSOP-16\" (layer \"F.Cu\") (at 24 10) (property \"Reference\" \"U4\") (property \"Value\" \"TPS26600PWPR\") ",+ "(pad \"1\" smd rect (at 0 0) (size 0.8 0.8) (layers \"F.Cu\") (net \"VBUS\"))) ",+ "(gr_rect (start 0 0) (end 40 20) (layer \"Edge.Cuts\") (stroke (width 0.1) (type solid))))"+ );+ let b_k10 = Board::from_text("k10-vbus.kicad_pcb", k10.to_string()).unwrap();+ assert!(b_k10.net_table.is_empty());+ let res_k10 = check_usb_inrush(&b_k10, &json!({}), None);+ assert_eq!(res_k10["checked"], true, "KiCad 10 VBUS net must be checked: {res_k10}");+ assert_eq!(res_k10["pass"], true, "TPS26600PWPR eFuse must be recognized as inrush limiter: {res_k10}");+ assert!(res_k10["inrushLimiter"].as_str().unwrap_or("").contains("TPS26600"), "{res_k10}");+ }++ #[test]+ fn load_budget_catches_overbudget_aux_draw() {+ let spec = json!({+ "loads": {"5V": {"from": "J1.1", "to": "U1.1", "amps": 0.35}},+ "auxiliaryLoads": {"RGB_LEDs": {"net": "5V", "amps": 0.40}}+ });+ let req = json!({"usb": {"maxCurrentA": 0.50}});+ let bad = check_load_budget(&spec, &req);+ assert_eq!(bad["pass"], false, "{bad}");++ let req_ok = json!({"usb": {"maxCurrentA": 1.50}});+ let good = check_load_budget(&spec, &req_ok);+ assert_eq!(good["pass"], true, "{good}");+ }+}
crates/aiflow-copper/src/lib.rs+38−5@@ -149,15 +149,22 @@ pub fn normalise_plan(board: &Board, plan: &mut Value) -> Vec<String> { // pad is on B.Cu; say so on its first waypoint, so `land route` sends the layer the gate saw if entry_layer.is_none() && !pts.is_empty() { let res: Vec<Option<(Option<usize>, bool)>> = pts.iter().map(|w| point(w, board).ok().map(|(_, _, pad, ex)| (pad, ex.is_some()))).collect();- if res.iter().all(|r| r.is_some()) && !res[0].unwrap().1 && Board::path_start_layer(res.iter().map(|r| { let (pad, ex) = r.unwrap(); (pad.map(|i| &board.pads[i]), ex) })) == "B.Cu" {+ let start = if res.iter().all(|r| r.is_some()) && !res[0].unwrap().1 { Some(Board::path_start_layer(res.iter().map(|r| { let (pad, ex) = r.unwrap(); (pad.map(|i| &board.pads[i]), ex) }))) } else { None };+ // issue #241: a path that starts F.Cu through a bottom part's through-hole pad names F.Cu too, so the+ // bridge never picks the part's side (B.Cu) for it and lands a trace the gate checked on the other layer+ let bottom_thru = res.iter().map_while(|r| r.filter(|(_, ex)| !*ex)).filter_map(|(pad, _)| pad)+ .any(|i| board.footprints.get(&board.pads[i].reference).is_some_and(|f| f.layer == "B.Cu"));+ let stamp = match start { Some("B.Cu") => Some("B.Cu"), Some(l) if bottom_thru => Some(l), _ => None };+ if let Some(l) = stamp { let first = pts[0].clone(); pts[0] = match &first {- Value::String(k) => json!({"pad": k, "layer": "B.Cu"}),- Value::Array(a) => json!({"x": a[0], "y": a[1], "layer": "B.Cu"}),- Value::Object(o) => { let mut m = o.clone(); m.insert("layer".into(), json!("B.Cu")); Value::Object(m) }+ Value::String(k) => json!({"pad": k, "layer": l}),+ Value::Array(a) => json!({"x": a[0], "y": a[1], "layer": l}),+ Value::Object(o) => { let mut m = o.clone(); m.insert("layer".into(), json!(l)); Value::Object(m) } _ => first.clone(), };- notes.push(format!("{where_}: starts on a bottom-side pad with no layer named; set B.Cu on its first waypoint (the pad has no copper on F.Cu)"));+ notes.push(if l == "B.Cu" { format!("{where_}: starts on a bottom-side pad with no layer named; set B.Cu on its first waypoint (the pad has no copper on F.Cu)") }+ else { format!("{where_}: starts at a bottom part's through-hole pad with no layer named; set {l} on its first waypoint, the layer the gate checked") }); } } let pts = &pts;@@ -949,4 +956,30 @@ mod duplicate_pad_tests { assert!(normalise_plan(&b, &mut plain).is_empty()); assert_eq!(plain["nets"][0]["paths"][0][0], "R1.1"); }++ /// Issue #241: a path through a bottom part's through-hole pad that the gate starts on F.Cu names F.Cu, so the+ /// bridge cannot start it on the part's side; a top part's pads and an explicit layer stay as they are.+ #[test]+ fn a_path_from_a_bottom_parts_through_hole_pad_names_the_layer_the_gate_used() {+ let b = Board::from_text("t.kicad_pcb", r#"(kicad_pcb+ (layers (0 "F.Cu" signal) (31 "B.Cu" signal))+ (net 1 "SIG")+ (gr_rect (start 0 0) (end 40 30) (layer "Edge.Cuts"))+ (footprint "Hdr" (layer "B.Cu") (at 10 10 180) (property "Reference" "J1")+ (pad "1" thru_hole rect (at 0 0 180) (size 1.7 1.7) (drill 1) (layers "*.Cu" "*.Mask") (net 1 "SIG")))+ (footprint "Hdr" (layer "F.Cu") (at 30 10) (property "Reference" "J2")+ (pad "1" thru_hole rect (at 0 0) (size 1.7 1.7) (drill 1) (layers "*.Cu" "*.Mask") (net 1 "SIG"))))"#.into()).unwrap();+ let mut plan = json!({"nets": [{"net": "SIG", "width": 0.25, "paths": [["J1.1", [20.0, 10.0], "J2.1"]]},+ {"net": "SIG", "width": 0.25, "paths": [["J2.1", [25.0, 15.0]]]}]});+ let notes = normalise_plan(&b, &mut plan);+ assert_eq!(plan["nets"][0]["paths"][0][0], json!({"pad": "J1.1", "layer": "F.Cu"}), "{plan}");+ assert!(notes.iter().any(|n| n.contains("bottom part's through-hole pad") && n.contains("F.Cu")), "{notes:?}");+ // a path that touches only a top part's pads is left for the bridge as before+ assert_eq!(plan["nets"][1]["paths"][0][0], json!("J2.1"));+ // the gate copy is unchanged: F.Cu either way+ let (segs, _) = plan_to_copper(&b, &plan["nets"][0]).unwrap();+ assert!(segs.iter().all(|s| s.layer == "F.Cu"));+ // normalising again changes nothing+ assert!(normalise_plan(&b, &mut plan).is_empty());+ } }
crates/aiflow-router/src/drive.rs+2−2@@ -868,7 +868,7 @@ impl Router { if self.fixed_blocks(&name, None, x, y, rv + self.rules.clearance) { return false; }- if g.in_bounds(i, j) && (0..2).any(|l| self.kept_from(&name, l, j as usize * g.w + i as usize)) {+ if g.in_bounds(i, j) && self.kept_from_via(&name, j as usize * g.w + i as usize) { return false; } if self.via_in_keepout(x, y, rv) {@@ -1383,7 +1383,7 @@ impl Router { } } let mut rep = json!({"rules": serde_json::to_value(&self.rules).unwrap(), "nets": nets, "stats": self.stats, "unrouted": unrouted, "boardCopper": self.board_copper_summary(), "decoupling": self.decoupling_report(),- "planeUnder": self.keep.iter().map(|k| json!({"label": k.label, "net": k.net, "layer": aiflow_board::LAYER_NAMES[k.layer], "polygon": k.poly})).collect::<Vec<_>>()});+ "planeUnder": self.keep.iter().map(|k| json!({"label": k.label, "net": k.net, "layer": crate::plane_under::layer_name(k.layer), "polygon": k.poly})).collect::<Vec<_>>()}); if !self.rules.default_copper_mode() { rep["singleFace"] = self.single_face_summary(); }
crates/aiflow-router/src/impedance.rs+1044−26@@ -51,6 +51,34 @@ pub const DEFAULT_TOLERANCE: f64 = 10.0; pub const DEFAULT_MAX_SKEW_MM: f64 = 0.5; /// The default length of a net that may sit outside its target (pad breakouts, escape stubs), mm. pub const DEFAULT_MAX_UNCONTROLLED_MM: f64 = 3.0;+/// The default coupled run length (mm) over which local intra-pair phase skew may exceed maxPhaseSkewMm.+pub const DEFAULT_MAX_PHASE_SKEW_RUN_MM: f64 = 5.0;+/// Default maximum center-to-center spacing (mm) between paired P/N layer-transition vias.+pub const DEFAULT_VIA_PAIR_MAX_PITCH_MM: f64 = 1.5;+/// Default maximum along-route offset (mm) between paired P/N layer-transition vias.+pub const DEFAULT_VIA_PAIR_MAX_SKEW_MM: f64 = 0.25;+/// Default search radius (mm) for a reference-plane stitching via beside a pair layer transition.+pub const DEFAULT_STITCH_VIA_RADIUS_MM: f64 = 2.0;+/// Default maximum ESD/TVS or intermediate-pad T-stub length (mm) on a differential pair.+pub const DEFAULT_MAX_STUB_MM: f64 = 1.5;+/// Default maximum sudden coupled-gap jump (%) outside pad breakout windows.+pub const DEFAULT_MAX_GAP_JUMP_PERCENT: f64 = 25.0;+/// Default LPI solder mask thickness above outer copper (mm) and permittivity near 1 GHz.+pub const DEFAULT_SOLDER_MASK_MM: f64 = 0.025;+pub const DEFAULT_SOLDER_MASK_ER: f64 = 3.8;++/// Outer-layer solder mask coating parameters (thickness above copper, mm, and relative permittivity).+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct SolderMask {+ pub thickness_mm: f64,+ pub er: f64,+}++impl Default for SolderMask {+ fn default() -> Self {+ Self { thickness_mm: DEFAULT_SOLDER_MASK_MM, er: DEFAULT_SOLDER_MASK_ER }+ }+} // -- the formulas ---------------------------------------------------------------------------- @@ -104,6 +132,23 @@ pub fn microstrip(w: f64, h: f64, t: f64, er: f64) -> (f64, f64) { (z0, eeff) } +/// Surface microstrip with conformal outer-layer solder mask coating (thickness `tm` above copper,+/// relative permittivity `er_m`). Validated within 1.2 % of `adom-fields --with si` 2-D Laplace+/// solves across 2-layer 1.6 mm FR4 and 4-layer 7628 / 3313 stackups.+pub fn microstrip_coated(w: f64, h: f64, t: f64, er: f64, mask: SolderMask) -> (f64, f64) {+ let (z0, eeff) = microstrip(w, h, t, er);+ if mask.thickness_mm <= 0.0 || mask.er <= 1.0 {+ return (z0, eeff);+ }+ let q_air = (er - eeff) / (er - 1.0).max(1e-9);+ let hm = t + mask.thickness_mm;+ let scale = 0.45 * h * (1.0 + 0.35 * (w / h).sqrt());+ let f_m = 1.0 - (-(hm / scale).powf(0.72)).exp();+ let eeff_m = eeff + (mask.er - 1.0) * q_air * f_m;+ let z0_m = z0 * (eeff / eeff_m).sqrt();+ (z0_m, eeff_m)+}+ /// Cohn's exact zero-thickness symmetric stripline (plane spacing b). pub fn stripline_exact_t0(w: f64, b: f64, er: f64) -> f64 { let k = 1.0 / (PI * w / (2.0 * b)).cosh();@@ -197,6 +242,28 @@ pub fn coupled_microstrip(w: f64, s: f64, h: f64, t: f64, er: f64) -> (f64, f64, (z(co, coa), z(ce, cea), co / coa, ce / cea) } +/// Edge-coupled microstrip with conformal outer-layer solder mask coating (filling sidewalls and+/// gap `s` up to `t + tm`). Validated within 1.2 % of `adom-fields --with si` on 4-layer 7628 and+/// 3313 differential pairs.+pub fn coupled_microstrip_coated(w: f64, s: f64, h: f64, t: f64, er: f64, mask: SolderMask) -> (f64, f64, f64, f64) {+ if mask.thickness_mm <= 0.0 || mask.er <= 1.0 {+ return coupled_microstrip(w, s, h, t, er);+ }+ let (mut ce, mut co) = garg_bahl_caps(w, s, h, t, er);+ let (cea, coa) = garg_bahl_caps(w, s, h, t, 1.0);+ let (z0, eeff) = microstrip(w, h, t, er);+ let (z0m, eeffm) = microstrip_coated(w, h, t, er, mask);+ let dc_single = eeffm.sqrt() / (C0 * z0m) - eeff.sqrt() / (C0 * z0);+ let k = (s / h) / (s / h + 2.0 * w / h);+ let cga = EPS0 / k_ratio(k);+ let cgt = 2.0 * EPS0 * t / s;+ let f_gap = 1.0 - (-1.5 * mask.thickness_mm / s.max(1e-6)).exp();+ ce += dc_single * (0.85 + 0.15 * (s / h).tanh());+ co += 0.55 * dc_single + (mask.er - 1.0) * (cgt + f_gap * cga);+ let z = |c: f64, ca: f64| 1.0 / (C0 * (c * ca).sqrt());+ (z(co, coa), z(ce, cea), co / coa, ce / cea)+}+ /// K(k)/K(k') from k^2, guarded at the ends (k^2 >= 1 is touching conductors: infinite). fn kk2(k2: f64) -> f64 { if k2 >= 1.0 { return f64::INFINITY; }@@ -254,6 +321,40 @@ pub fn coupled_gcpw(w: f64, s: f64, g: f64, h: f64, t: f64, er: f64) -> (f64, f6 (zo, ze, eo, ee) } +/// Grounded coplanar waveguide with outer-layer solder mask filling the coplanar gaps `g`.+pub fn gcpw_coated(w: f64, g: f64, h: f64, t: f64, er: f64, mask: SolderMask) -> (f64, f64) {+ if mask.thickness_mm <= 0.0 || mask.er <= 1.0 {+ return gcpw(w, g, h, t, er);+ }+ let (up, lo) = cpw_parts(0.0, w / 2.0, w / 2.0 + g, h, false);+ let side = if t > 0.0 { t / g } else { 0.0 };+ let f_slot = 1.0 - (-1.5 * mask.thickness_mm / g.max(1e-6)).exp();+ let up_m = up * (1.0 + (mask.er - 1.0) * f_slot);+ let side_m = mask.er * side;+ let (c, ca) = (2.0 * EPS0 * (up_m + side_m + er * lo), 2.0 * EPS0 * (up + side + lo));+ (1.0 / (C0 * (c * ca).sqrt()), c / ca)+}++/// Edge-coupled grounded coplanar waveguide with outer-layer solder mask filling gaps `s` and `g`.+pub fn coupled_gcpw_coated(w: f64, s: f64, g: f64, h: f64, t: f64, er: f64, mask: SolderMask) -> (f64, f64, f64, f64) {+ if mask.thickness_mm <= 0.0 || mask.er <= 1.0 {+ return coupled_gcpw(w, s, g, h, t, er);+ }+ let (x1, x2, x3) = (s / 2.0, s / 2.0 + w, s / 2.0 + w + g);+ let mode = |odd: bool| {+ let (up, lo) = cpw_parts(x1, x2, x3, h, odd);+ let side_air = if t > 0.0 { t / g + if odd { 2.0 * t / s } else { 0.0 } } else { 0.0 };+ let gap_eff = if odd { g.min(s) } else { g };+ let f_slot = 1.0 - (-1.5 * mask.thickness_mm / gap_eff.max(1e-6)).exp();+ let up_m = up * (1.0 + (mask.er - 1.0) * f_slot);+ let side_m = mask.er * side_air;+ let (c, ca) = (EPS0 * (up_m + side_m + er * lo), EPS0 * (up + side_air + lo));+ (1.0 / (C0 * (c * ca).sqrt()), c / ca)+ };+ let ((zo, eo), (ze, ee)) = (mode(true), mode(false));+ (zo, ze, eo, ee)+}+ /// The range the coplanar forms are used in. Against the field solve (tools/impedance_reference.py, /// 365 cross-sections, er 4.4) they read 0.6 to 4.1 % high over 0.06 <= w/h <= 15, 0.06 <= g/h <= 1, /// 0.06 <= s/h <= 2 and t <= w/4; the error grows past g/h 1 (the slots stop acting as magnetic walls:@@ -309,6 +410,9 @@ pub struct LayerGeom { /// an outer layer with a same-layer ground pour this far (mm) from the copper: grounded coplanar /// waveguide (a target's coplanarGapMm, never the stackup's own) pub coplanar: Option<f64>,+ /// conformal outer-layer solder mask coating when active on this layer (None on inner layers+ /// or when solving bare copper)+ pub solder_mask: Option<SolderMask>, } #[derive(Clone, Debug)]@@ -316,6 +420,58 @@ pub struct Stackup { pub layers: Vec<LayerGeom>, /// where the dielectric thicknesses, the permittivity and the copper thickness came from pub sources: BTreeMap<String, String>,+ /// the solder mask applied to outer layers when active (also used to compute the advisory+ /// mask shift when solving bare copper)+ pub solder_mask: Option<SolderMask>,+}++/// Read outer-layer solder mask thickness from KiCad's saved physical stackup (F.Mask / B.Mask).+pub fn board_solder_mask_mm(board: &Board) -> Option<f64> {+ let st = board.root.find("setup")?.find("stackup")?;+ for l in st.find_all("layer") {+ let name = l.atom(1).unwrap_or("");+ if name == "F.Mask" || name == "B.Mask" {+ if let Some(t) = l.find("thickness").and_then(|x| x.number(1)).filter(|t| *t > 0.0) {+ return Some(t);+ }+ }+ }+ None+}++/// Parse outer-layer solder mask settings from spec (`solderMask`, `rf.noSolderMask`).+/// Returns `(active_mask, advisory_mask, source_note)`:+/// - `spec.solderMask = true` or `{thicknessMm, epsilonR}` activates coated solving directly;+/// - `spec.solderMask = false` or `spec.rf.noSolderMask = true` explicitly disables solder mask;+/// - omitting `spec.solderMask` preserves bare-copper solving while still reporting the expected+/// solder-mask shift using the advisory mask parameters.+pub fn spec_solder_mask(board: &Board, spec: &Value) -> Result<(Option<SolderMask>, SolderMask, String), String> {+ let board_t = board_solder_mask_mm(board);+ let advisory = SolderMask { thickness_mm: board_t.unwrap_or(DEFAULT_SOLDER_MASK_MM), er: DEFAULT_SOLDER_MASK_ER };+ if spec.get("rf").and_then(|r| r.get("noSolderMask")).and_then(|v| v.as_bool()) == Some(true) {+ return Ok((None, advisory, "disabled (spec rf.noSolderMask)".into()));+ }+ match spec.get("solderMask") {+ None | Some(Value::Null) => Ok((None, advisory, "not modelled (bare copper; expected mask shift reported beside each outer row)".into())),+ Some(Value::Bool(false)) => Ok((None, advisory, "disabled (spec solderMask: false)".into())),+ Some(Value::Bool(true)) => {+ let m = advisory;+ Ok((Some(m), m, format!("spec solderMask ({:.3} mm, er {:.2})", m.thickness_mm, m.er)))+ }+ Some(Value::Object(o)) => {+ let t = o.get("thicknessMm").and_then(|v| v.as_f64()).unwrap_or(advisory.thickness_mm);+ let er = o.get("epsilonR").and_then(|v| v.as_f64()).unwrap_or(DEFAULT_SOLDER_MASK_ER);+ if !(t > 0.0 && t <= 0.5 && t.is_finite()) {+ return Err(format!("spec solderMask.thicknessMm {t} must be positive and at most 0.5 mm"));+ }+ if !(er >= 1.0 && er <= 20.0 && er.is_finite()) {+ return Err(format!("spec solderMask.epsilonR {er} must be between 1 and 20"));+ }+ let m = SolderMask { thickness_mm: t, er };+ Ok((Some(m), m, format!("spec solderMask ({t:.3} mm, er {er:.2})")))+ }+ Some(_) => Err("spec solderMask must be true, false, or {\"thicknessMm\": 0.025, \"epsilonR\": 3.8}".into()),+ } } /// The board's saved physical stackup (Board Setup > Physical Stackup): copper layer names in@@ -384,12 +540,21 @@ pub fn stackup(board: &Board, spec: &Value) -> Result<Stackup, String> { }; let spec_er = spec.get("epsilonR").and_then(|v| v.as_f64()); if let Some(e) = spec_er { if !(e >= 1.0 && e.is_finite()) { return Err(format!("spec epsilonR {e} must be at least 1")); } }+ let spec_er_gaps: Option<Vec<f64>> = spec.get("epsilonRByGap").and_then(|v| v.as_array()).map(|a| a.iter().filter_map(|x| x.as_f64()).collect());+ if let Some(eg) = &spec_er_gaps {+ if eg.len() != ngap || eg.iter().any(|e| !(*e >= 1.0 && e.is_finite())) {+ return Err(format!("spec epsilonRByGap needs {ngap} value(s) >= 1 (one per dielectric gap)"));+ }+ } let board_er: Option<Vec<f64>> = saved.as_ref().filter(|s| s.2.len() == ngap).and_then(|s| s.2.iter().copied().collect::<Option<Vec<f64>>>());- let ers: Vec<f64> = match (&board_er, spec_er) {- (Some(e), _) => { sources.insert("epsilonR".into(), "board physical stackup epsilon_r".into()); e.clone() }- (None, Some(e)) => { sources.insert("epsilonR".into(), "spec epsilonR".into()); vec![e; ngap] }- (None, None) => return Err("no dielectric constant: the board stackup names no epsilon_r and the spec has no epsilonR; add spec epsilonR from the laminate datasheet (Dk near 1 GHz)".into()),+ let ers: Vec<f64> = match (&spec_er_gaps, &board_er, spec_er) {+ (Some(e), _, _) => { sources.insert("epsilonR".into(), "spec epsilonRByGap".into()); e.clone() }+ (None, Some(e), _) => { sources.insert("epsilonR".into(), "board physical stackup epsilon_r".into()); e.clone() }+ (None, None, Some(e)) => { sources.insert("epsilonR".into(), "spec epsilonR".into()); vec![e; ngap] }+ (None, None, None) => return Err("no dielectric constant: the board stackup names no epsilon_r and the spec has no epsilonR; add spec epsilonR from the laminate datasheet (Dk near 1 GHz)".into()), };+ let (active_mask, _advisory_mask, mask_src) = spec_solder_mask(board, spec)?;+ sources.insert("solderMask".into(), mask_src); let by_layer = spec.get("copperUmByLayer").and_then(|v| v.as_object()); let cu_spec = spec.get("copperUm").and_then(|v| v.as_f64()); let mut cu_src = Vec::new();@@ -406,20 +571,20 @@ pub fn stackup(board: &Board, spec: &Value) -> Result<Stackup, String> { let mut layers = Vec::new(); for (k, n) in names.iter().enumerate() { let g = if k == 0 {- LayerGeom { name: n.clone(), structure: "microstrip".into(), h1: gaps[0], h2: None, reference: vec![names[1].clone()], er: ers[0], t: ts[k], coplanar: None }+ LayerGeom { name: n.clone(), structure: "microstrip".into(), h1: gaps[0], h2: None, reference: vec![names[1].clone()], er: ers[0], t: ts[k], coplanar: None, solder_mask: active_mask } } else if k == ngap {- LayerGeom { name: n.clone(), structure: "microstrip".into(), h1: gaps[k - 1], h2: None, reference: vec![names[k - 1].clone()], er: ers[k - 1], t: ts[k], coplanar: None }+ LayerGeom { name: n.clone(), structure: "microstrip".into(), h1: gaps[k - 1], h2: None, reference: vec![names[k - 1].clone()], er: ers[k - 1], t: ts[k], coplanar: None, solder_mask: active_mask } } else { let (a, b) = (gaps[k - 1], gaps[k]); // the dielectric between copper foils is measured foil to foil: the strip sits on one // foil plane, so each face's distance to its plane is that gap (thickness-weighted er) let er = (ers[k - 1] * a + ers[k] * b) / (a + b); let sym = (a - b).abs() <= 1e-6 * (a + b);- LayerGeom { name: n.clone(), structure: if sym { "stripline".into() } else { "offset stripline".into() }, h1: a, h2: Some(b), reference: vec![names[k - 1].clone(), names[k + 1].clone()], er, t: ts[k], coplanar: None }+ LayerGeom { name: n.clone(), structure: if sym { "stripline".into() } else { "offset stripline".into() }, h1: a, h2: Some(b), reference: vec![names[k - 1].clone(), names[k + 1].clone()], er, t: ts[k], coplanar: None, solder_mask: None } }; layers.push(g); }- Ok(Stackup { layers, sources })+ Ok(Stackup { layers, sources, solder_mask: active_mask }) } impl LayerGeom {@@ -427,22 +592,52 @@ impl LayerGeom { pub fn with_coplanar(&self, g: f64) -> LayerGeom { LayerGeom { structure: "grounded coplanar".into(), coplanar: Some(g), ..self.clone() } }- /// Single-ended Z0 and effective permittivity of a trace of width w on this layer.- pub fn z0(&self, w: f64) -> (f64, f64) {+ /// Single-ended Z0 and effective permittivity without solder mask (bare copper).+ pub fn z0_bare(&self, w: f64) -> (f64, f64) { match (self.h2, self.coplanar) { (None, Some(g)) => gcpw(w, g, self.h1, self.t, self.er), (None, None) => microstrip(w, self.h1, self.t, self.er), (Some(h2), _) => (offset_stripline(w, self.h1, h2, self.t, self.er), self.er), } }- /// (Zdiff, Zodd, Zeven, eeff odd) of a pair of width w and gap s on this layer.- pub fn zdiff(&self, w: f64, s: f64) -> (f64, f64, f64, f64) {+ /// Single-ended Z0 and effective permittivity with an explicit outer-layer solder mask.+ pub fn z0_with_mask(&self, w: f64, mask: SolderMask) -> (f64, f64) {+ match (self.h2, self.coplanar) {+ (None, Some(g)) => gcpw_coated(w, g, self.h1, self.t, self.er, mask),+ (None, None) => microstrip_coated(w, self.h1, self.t, self.er, mask),+ (Some(h2), _) => (offset_stripline(w, self.h1, h2, self.t, self.er), self.er),+ }+ }+ /// Single-ended Z0 and effective permittivity of a trace of width w on this layer (with solder mask when active).+ pub fn z0(&self, w: f64) -> (f64, f64) {+ match self.solder_mask {+ Some(m) if self.h2.is_none() => self.z0_with_mask(w, m),+ _ => self.z0_bare(w),+ }+ }+ /// (Zdiff, Zodd, Zeven, eeff odd) without solder mask (bare copper).+ pub fn zdiff_bare(&self, w: f64, s: f64) -> (f64, f64, f64, f64) { match (self.h2, self.coplanar) { (None, Some(g)) => { let (zo, ze, eo, _) = coupled_gcpw(w, s, g, self.h1, self.t, self.er); (2.0 * zo, zo, ze, eo) } (None, None) => { let (zo, ze, eo, _) = coupled_microstrip(w, s, self.h1, self.t, self.er); (2.0 * zo, zo, ze, eo) } (Some(h2), _) => { let (zo, ze) = coupled_offset_stripline(w, s, self.h1, h2, self.t, self.er); (2.0 * zo, zo, ze, self.er) } } }+ /// (Zdiff, Zodd, Zeven, eeff odd) with an explicit outer-layer solder mask.+ pub fn zdiff_with_mask(&self, w: f64, s: f64, mask: SolderMask) -> (f64, f64, f64, f64) {+ match (self.h2, self.coplanar) {+ (None, Some(g)) => { let (zo, ze, eo, _) = coupled_gcpw_coated(w, s, g, self.h1, self.t, self.er, mask); (2.0 * zo, zo, ze, eo) }+ (None, None) => { let (zo, ze, eo, _) = coupled_microstrip_coated(w, s, self.h1, self.t, self.er, mask); (2.0 * zo, zo, ze, eo) }+ (Some(h2), _) => { let (zo, ze) = coupled_offset_stripline(w, s, self.h1, h2, self.t, self.er); (2.0 * zo, zo, ze, self.er) }+ }+ }+ /// (Zdiff, Zodd, Zeven, eeff odd) of a pair of width w and gap s on this layer (with solder mask when active).+ pub fn zdiff(&self, w: f64, s: f64) -> (f64, f64, f64, f64) {+ match self.solder_mask {+ Some(m) if self.h2.is_none() => self.zdiff_with_mask(w, s, m),+ _ => self.zdiff_bare(w, s),+ }+ } /// The height the formulas' ranges are normalised by. fn h_norm(&self) -> f64 { match self.h2 { None => self.h1, Some(h2) => self.h1 + h2 + self.t } } fn kind(&self) -> &str { if self.h2.is_none() { "microstrip" } else { "stripline" } }@@ -475,6 +670,22 @@ pub struct Target { pub source: String, /// a same-layer ground pour beside the copper on an outer layer (grounded coplanar waveguide) pub coplanar: Option<Coplanar>,+ /// local intra-pair phase skew threshold (mm, None = auto: max(maxSkewMm, coupled pitch))+ pub max_phase_skew: Option<f64>,+ /// max coupled travel distance (mm) over which local phase skew may exceed max_phase_skew (default 5.0)+ pub max_phase_skew_run: f64,+ /// allow symmetric via-pair layer transitions on multilayer differential pairs (default false)+ pub allow_layer_change: bool,+ /// max center-to-center distance (mm) between paired P/N vias (default 1.5)+ pub via_pair_max_pitch: f64,+ /// max along-route distance difference (mm) between paired P/N vias (default 0.25)+ pub via_pair_max_skew: f64,+ /// max distance (mm) from a pair via transition midpoint to a reference-plane stitching via (default 2.0)+ pub stitch_via_radius: f64,+ /// max ESD/TVS or intermediate-pad T-stub branch length (mm, default 1.5)+ pub max_stub: f64,+ /// max sudden coupled gap jump (%) outside breakout windows (default 25.0)+ pub max_gap_jump_percent: f64, } /// The same-layer ground a coplanar target assumes: its net and its gap from the copper (mm).@@ -524,8 +735,8 @@ pub fn targets(spec: &Value) -> Result<Vec<Target>, String> { .ok_or_else(|| format!("impedanceTargets.{name} needs {}", if diff { "targetDiffOhms (a pair)" } else { "targetOhms (a single net)" }))?; let tol = num(o, "tolerancePercent").unwrap_or(DEFAULT_TOLERANCE); if !(ohms > 0.0 && ohms < 500.0) || !(tol > 0.0 && tol < 100.0) { return Err(format!("impedanceTargets.{name}: target ohms and tolerancePercent must be positive (tolerance under 100)")); }- for k in ["gapMm", "widthMm", "maxSkewMm", "maxUncontrolledMm", "maxWidthMm"] {- if let Some(v) = o.get(k) { if !v.as_f64().map(|x| x >= 0.0 && x.is_finite()).unwrap_or(false) { return Err(format!("impedanceTargets.{name}.{k} must be a non-negative number (mm)")); } }+ for k in ["gapMm", "widthMm", "maxSkewMm", "maxUncontrolledMm", "maxWidthMm", "maxPhaseSkewMm", "maxPhaseSkewRunMm", "viaPairMaxPitchMm", "viaPairMaxSkewMm", "stitchViaRadiusMm", "maxStubMm", "maxGapJumpPercent"] {+ if let Some(v) = o.get(k) { if !v.as_f64().map(|x| x >= 0.0 && x.is_finite()).unwrap_or(false) { return Err(format!("impedanceTargets.{name}.{k} must be a non-negative number")); } } } if !diff && o.get("gapMm").is_some() { return Err(format!("impedanceTargets.{name}: gapMm is for a pair")); } let coplanar = match o.get("coplanarGapMm") {@@ -536,8 +747,18 @@ pub fn targets(spec: &Value) -> Result<Vec<Target>, String> { Some(Coplanar { net, gap, source: format!("impedanceTargets.{name}.coplanarGapMm") }) } };+ let max_skew = num(o, "maxSkewMm").unwrap_or(DEFAULT_MAX_SKEW_MM); out.push(Target { name: name.clone(), nets, ohms, diff, tolerance: tol, gap: num(o, "gapMm"), width: num(o, "widthMm"), layer: o.get("layer").and_then(|v| v.as_str()).map(str::to_string),- max_skew: num(o, "maxSkewMm").unwrap_or(DEFAULT_MAX_SKEW_MM), max_uncontrolled: num(o, "maxUncontrolledMm").unwrap_or(DEFAULT_MAX_UNCONTROLLED_MM), max_width: num(o, "maxWidthMm"), source: format!("impedanceTargets.{name}"), coplanar });+ max_skew, max_uncontrolled: num(o, "maxUncontrolledMm").unwrap_or(DEFAULT_MAX_UNCONTROLLED_MM), max_width: num(o, "maxWidthMm"), source: format!("impedanceTargets.{name}"), coplanar,+ max_phase_skew: num(o, "maxPhaseSkewMm"),+ max_phase_skew_run: num(o, "maxPhaseSkewRunMm").unwrap_or(DEFAULT_MAX_PHASE_SKEW_RUN_MM),+ allow_layer_change: o.get("allowLayerChange").and_then(|v| v.as_bool()).unwrap_or(false),+ via_pair_max_pitch: num(o, "viaPairMaxPitchMm").unwrap_or(DEFAULT_VIA_PAIR_MAX_PITCH_MM),+ via_pair_max_skew: num(o, "viaPairMaxSkewMm").unwrap_or(DEFAULT_VIA_PAIR_MAX_SKEW_MM),+ stitch_via_radius: num(o, "stitchViaRadiusMm").unwrap_or(DEFAULT_STITCH_VIA_RADIUS_MM),+ max_stub: num(o, "maxStubMm").unwrap_or(DEFAULT_MAX_STUB_MM),+ max_gap_jump_percent: num(o, "maxGapJumpPercent").unwrap_or(DEFAULT_MAX_GAP_JUMP_PERCENT),+ }); } } if let Some(m) = spec.get("impedance") {@@ -549,7 +770,11 @@ pub fn targets(spec: &Value) -> Result<Vec<Target>, String> { let nets: Vec<String> = k.split('/').map(str::to_string).collect(); if nets.len() > 2 || nets.iter().any(|n| n.is_empty()) { return Err(format!("spec impedance key {k:?}: a net, or \"P/N\" for a pair")); } if out.iter().any(|t| t.nets == nets) { continue; } // impedanceTargets carries the detail- out.push(Target { name: k.clone(), diff: nets.len() == 2, nets, ohms, tolerance: DEFAULT_TOLERANCE, gap: None, width: None, layer: None, max_skew: DEFAULT_MAX_SKEW_MM, max_uncontrolled: DEFAULT_MAX_UNCONTROLLED_MM, max_width: None, source: format!("impedance.{k}"), coplanar: ground.clone() });+ out.push(Target { name: k.clone(), diff: nets.len() == 2, nets, ohms, tolerance: DEFAULT_TOLERANCE, gap: None, width: None, layer: None, max_skew: DEFAULT_MAX_SKEW_MM, max_uncontrolled: DEFAULT_MAX_UNCONTROLLED_MM, max_width: None, source: format!("impedance.{k}"), coplanar: ground.clone(),+ max_phase_skew: None, max_phase_skew_run: DEFAULT_MAX_PHASE_SKEW_RUN_MM, allow_layer_change: false,+ via_pair_max_pitch: DEFAULT_VIA_PAIR_MAX_PITCH_MM, via_pair_max_skew: DEFAULT_VIA_PAIR_MAX_SKEW_MM, stitch_via_radius: DEFAULT_STITCH_VIA_RADIUS_MM,+ max_stub: DEFAULT_MAX_STUB_MM, max_gap_jump_percent: DEFAULT_MAX_GAP_JUMP_PERCENT,+ }); } } let mut seen: BTreeMap<String, String> = BTreeMap::new();@@ -642,6 +867,19 @@ pub fn solve_row(t: &Target, g: &LayerGeom, fab: &Fab, grid: Option<&GridPair>) row["ohms"] = json!(r2(z)); row["eeff"] = json!(r4(ee)); row["psPerMm"] = json!(r2(ee.sqrt() / C0 * 1e9));+ if g.h2.is_none() {+ let mask = g.solder_mask.unwrap_or_default();+ let z_bare = g.z0_bare(w).0;+ let z_mask = g.z0_with_mask(w, mask).0;+ let shift_pct = (z_mask - z_bare) / z_bare.max(1e-9) * 100.0;+ row["bareOhms"] = json!(r2(z_bare));+ row["withSolderMaskOhms"] = json!(r2(z_mask));+ row["solderMaskShiftPercent"] = json!(r2(shift_pct));+ row["solderMaskModelled"] = json!(g.solder_mask.is_some());+ if let Some(m) = g.solder_mask {+ row["solderMask"] = json!({"thicknessMm": r4(m.thickness_mm), "epsilonR": r2(m.er)});+ }+ } if let Err(e) = g.valid(w, None) { return refuse(row, format!("{e}; not extrapolated")); } if (z - t.ohms).abs() > t.ohms * t.tolerance / 100.0 { return refuse(row, format!("widthMm {w} gives {z:.1} ohm, outside {} %", t.tolerance)); } if w + 1e-9 < fab.min_width { return refuse(row, format!("needs {w:.3} mm, under the fab minimum track {:.3} mm ({})", fab.min_width, fab.source)); }@@ -652,7 +890,30 @@ pub fn solve_row(t: &Target, g: &LayerGeom, fab: &Fab, grid: Option<&GridPair>) // a pair: a fixed gap (spec gapMm), a fixed width (spec widthMm, solve the gap), or the // narrowest gap the fab (and, on the router's layers, the grid) allows let floor_s = fab.min_space;- let pick = |w: f64, s: f64, row: &mut Value| { let (zd, zo, ze, eo) = g.zdiff(w, s); row["widthMm"] = json!(r4(w)); row["gapMm"] = json!(r4(s)); row["ohms"] = json!(r2(zd)); row["zOdd"] = json!(r2(zo)); row["zEven"] = json!(r2(ze)); row["eeffOdd"] = json!(r4(eo)); row["psPerMm"] = json!(r2(eo.sqrt() / C0 * 1e9)); zd };+ let pick = |w: f64, s: f64, row: &mut Value| {+ let (zd, zo, ze, eo) = g.zdiff(w, s);+ row["widthMm"] = json!(r4(w));+ row["gapMm"] = json!(r4(s));+ row["ohms"] = json!(r2(zd));+ row["zOdd"] = json!(r2(zo));+ row["zEven"] = json!(r2(ze));+ row["eeffOdd"] = json!(r4(eo));+ row["psPerMm"] = json!(r2(eo.sqrt() / C0 * 1e9));+ if g.h2.is_none() {+ let mask = g.solder_mask.unwrap_or_default();+ let zd_bare = g.zdiff_bare(w, s).0;+ let zd_mask = g.zdiff_with_mask(w, s, mask).0;+ let shift_pct = (zd_mask - zd_bare) / zd_bare.max(1e-9) * 100.0;+ row["bareOhms"] = json!(r2(zd_bare));+ row["withSolderMaskOhms"] = json!(r2(zd_mask));+ row["solderMaskShiftPercent"] = json!(r2(shift_pct));+ row["solderMaskModelled"] = json!(g.solder_mask.is_some());+ if let Some(m) = g.solder_mask {+ row["solderMask"] = json!({"thicknessMm": r4(m.thickness_mm), "epsilonR": r2(m.er)});+ }+ }+ zd+ }; let solved: Option<(f64, f64, String)> = if let Some(s) = t.gap { solve_decreasing(&|w| g.zdiff(w, s).0, t.ohms, lo, hi).map(|w| (w, s, "spec gapMm".to_string())) } else if let Some(w) = t.width {@@ -753,9 +1014,9 @@ pub fn plan_tracks(plan: &Value, board: &Board) -> (Vec<Track>, Vec<Via>) { fn len(t: &Track) -> f64 { (t.b.0 - t.a.0).hypot(t.b.1 - t.a.1) } /// The nearest parallel partner segment at a point: (gap to its edge, its width, the side it is on:-/// +1 to the left of `dir`, -1 to the right).-fn partner_gap(x: f64, y: f64, dir: (f64, f64), w: f64, layer: usize, others: &[&Track]) -> Option<(f64, f64, f64)> {- others.iter().filter(|q| q.layer == layer).filter_map(|q| {+/// +1 to the left of `dir`, -1 to the right, partner index in `others`, projection `along` along partner).+fn partner_gap_detail(x: f64, y: f64, dir: (f64, f64), w: f64, layer: usize, others: &[&Track]) -> Option<(f64, f64, f64, usize, f64)> {+ others.iter().enumerate().filter(|(_, q)| q.layer == layer).filter_map(|(idx, q)| { let l = len(q); if l < 1e-9 { return None; } let (ux, uy) = ((q.b.0 - q.a.0) / l, (q.b.1 - q.a.1) / l);@@ -764,10 +1025,349 @@ fn partner_gap(x: f64, y: f64, dir: (f64, f64), w: f64, layer: usize, others: &[ if along < -1e-6 || along > l + 1e-6 { return None; } let d = ((x - q.a.0) * uy - (y - q.a.1) * ux).abs(); let (cx, cy) = (q.a.0 + along * ux - x, q.a.1 + along * uy - y);- Some((d - (w + q.width) / 2.0, q.width, if cx * -dir.1 + cy * dir.0 >= 0.0 { 1.0 } else { -1.0 }))+ Some((d - (w + q.width) / 2.0, q.width, if cx * -dir.1 + cy * dir.0 >= 0.0 { 1.0 } else { -1.0 }, idx, along.clamp(0.0, l))) }).min_by(|a, b| a.0.total_cmp(&b.0)) } +#[allow(dead_code)]+fn partner_gap(x: f64, y: f64, dir: (f64, f64), w: f64, layer: usize, others: &[&Track]) -> Option<(f64, f64, f64)> {+ partner_gap_detail(x, y, dir, w, layer, others).map(|(g, pw, side, _, _)| (g, pw, side))+}++fn pt_dist(a: (f64, f64), b: (f64, f64)) -> f64 { (b.0 - a.0).hypot(b.1 - a.1) }++fn off45_deg(a: (f64, f64), b: (f64, f64)) -> f64 {+ let ang = (b.1 - a.1).atan2(b.0 - a.0).to_degrees().rem_euclid(180.0);+ let m = ang % 45.0;+ m.min(45.0 - m)+}++fn turn_deg_pair(u: (f64, f64), v: (f64, f64)) -> f64 {+ (u.0 * v.1 - u.1 * v.0).atan2(u.0 * v.0 + u.1 * v.1).to_degrees()+}++fn is_ref_ground_net(name: &str, extra: Option<&str>) -> bool {+ if let Some(e) = extra {+ if name.eq_ignore_ascii_case(e) { return true; }+ }+ let u = name.trim_start_matches('/').to_ascii_uppercase();+ let u = u.rsplit('/').next().unwrap_or(&u);+ u == "GND" || u == "AGND" || u == "DGND" || u == "PGND" || u == "VSS" || u.contains("GND")+}++/// Undirected copper graph for a single net's segments, vias and pads, for path-length walks,+/// intra-pair phase matching, via-transition alignment and ESD/TVS stub length measurement.+struct NetGraph {+ coords: Vec<(usize, f64, f64)>,+ adj: Vec<Vec<(usize, f64)>>,+ seg_nodes: Vec<(usize, usize, f64)>,+}++impl NetGraph {+ fn build(segs: &[&Track], vias: &[&Via], pads: &[&aiflow_board::Pad]) -> Self {+ let mut coords: Vec<(usize, f64, f64)> = Vec::new();+ let mut key_map: std::collections::HashMap<(usize, i64, i64), usize> = std::collections::HashMap::new();+ let mut node = |layer: usize, x: f64, y: f64| -> usize {+ let k = (layer, (x * 1000.0).round() as i64, (y * 1000.0).round() as i64);+ if let Some(&id) = key_map.get(&k) { return id; }+ let id = coords.len();+ coords.push((layer, x, y));+ key_map.insert(k, id);+ id+ };+ let mut seg_nodes = Vec::with_capacity(segs.len());+ for s in segs {+ let u = node(s.layer, s.a.0, s.a.1);+ let v = node(s.layer, s.b.0, s.b.1);+ seg_nodes.push((u, v, len(s)));+ }+ // First create inline nodes where a pad sits directly on the interior of a segment (flow-through ESD/TVS)+ for p in pads {+ for (si, s) in segs.iter().enumerate() {+ if !p.on_copper(s.layer) { continue; }+ let (_u, _v, l) = seg_nodes[si];+ if l <= 1e-6 { continue; }+ let dx = (s.b.0 - s.a.0) / l;+ let dy = (s.b.1 - s.a.1) / l;+ let rx = p.x - s.a.0;+ let ry = p.y - s.a.1;+ let proj = rx * dx + ry * dy;+ if proj > 0.01 && proj < l - 0.01 {+ let perp = (rx * dy - ry * dx).abs();+ if perp <= p.half_long + s.width * 0.5 + 0.05 {+ let px = s.a.0 + dx * proj;+ let py = s.a.1 + dy * proj;+ coords.push((s.layer, px, py));+ break;+ }+ }+ }+ }+ let n_all = coords.len();+ let mut adj = vec![Vec::new(); n_all];+ // Build edges along each segment, splitting cleanly at any T-junction or inline pad node lying on its interior+ for (si, s) in segs.iter().enumerate() {+ let (u, v, l) = seg_nodes[si];+ if u == v || l <= 1e-6 { continue; }+ let dx = (s.b.0 - s.a.0) / l;+ let dy = (s.b.1 - s.a.1) / l;+ let tol = (s.width * 0.5).max(0.05);+ let mut chain: Vec<(f64, usize)> = vec![(0.0, u), (l, v)];+ for k in 0..n_all {+ if k == u || k == v || coords[k].0 != s.layer { continue; }+ let rx = coords[k].1 - s.a.0;+ let ry = coords[k].2 - s.a.1;+ let proj = rx * dx + ry * dy;+ if proj > 0.01 && proj < l - 0.01 {+ let perp = (rx * dy - ry * dx).abs();+ if perp <= tol {+ chain.push((proj, k));+ }+ }+ }+ chain.sort_by(|a, b| a.0.total_cmp(&b.0));+ for w in chain.windows(2) {+ let (p0, a) = w[0];+ let (p1, b) = w[1];+ if a != b {+ let dl = (p1 - p0).max(0.0);+ adj[a].push((b, dl));+ adj[b].push((a, dl));+ }+ }+ }+ // Connect endpoints on the same layer within 0.02 mm (rounding tolerance)+ for i in 0..n_all {+ for j in (i + 1)..n_all {+ if coords[i].0 == coords[j].0 && pt_dist((coords[i].1, coords[i].2), (coords[j].1, coords[j].2)) <= 0.02 {+ let d = pt_dist((coords[i].1, coords[i].2), (coords[j].1, coords[j].2));+ adj[i].push((j, d));+ adj[j].push((i, d));+ }+ }+ }+ // Connect nodes touching the same via across layers+ for v in vias {+ let near: Vec<usize> = (0..n_all).filter(|&i| pt_dist((coords[i].1, coords[i].2), (v.x, v.y)) <= (v.size / 2.0).max(0.05)).collect();+ for a in 0..near.len() {+ for b in (a + 1)..near.len() {+ let (u, w) = (near[a], near[b]);+ adj[u].push((w, 0.0));+ adj[w].push((u, 0.0));+ }+ }+ }+ // Connect nodes landing inside the same pad+ for p in pads {+ let near: Vec<usize> = (0..n_all).filter(|&i| {+ p.on_copper(coords[i].0) && (p.polys.iter().any(|q| aiflow_board::geom::point_in_poly(coords[i].1, coords[i].2, q)) || pt_dist((coords[i].1, coords[i].2), (p.x, p.y)) <= p.half_long + 0.05)+ }).collect();+ for a in 0..near.len() {+ for b in (a + 1)..near.len() {+ let (u, w) = (near[a], near[b]);+ let d = pt_dist((coords[u].1, coords[u].2), (coords[w].1, coords[w].2));+ adj[u].push((w, d));+ adj[w].push((u, d));+ }+ }+ }+ Self { coords, adj, seg_nodes }+ }++ fn pad_nodes(&self, p: &aiflow_board::Pad) -> Vec<usize> {+ let mut out: Vec<usize> = (0..self.coords.len()).filter(|&i| {+ p.on_copper(self.coords[i].0) && (p.polys.iter().any(|q| aiflow_board::geom::point_in_poly(self.coords[i].1, self.coords[i].2, q)) || pt_dist((self.coords[i].1, self.coords[i].2), (p.x, p.y)) <= p.half_long + 0.1)+ }).collect();+ if out.is_empty() && !self.coords.is_empty() {+ if let Some((i, _)) = self.coords.iter().enumerate().filter(|(_, c)| p.on_copper(c.0)).map(|(i, c)| (i, pt_dist((c.1, c.2), (p.x, p.y)))).min_by(|a, b| a.1.total_cmp(&b.1)) {+ if pt_dist((self.coords[i].1, self.coords[i].2), (p.x, p.y)) <= p.half_long + 0.5 {+ out.push(i);+ }+ }+ }+ out+ }++ fn nearest_node(&self, x: f64, y: f64, radius: f64) -> Option<usize> {+ self.coords.iter().enumerate().map(|(i, c)| (i, pt_dist((c.1, c.2), (x, y)))).filter(|(_, d)| *d <= radius).min_by(|a, b| a.1.total_cmp(&b.1)).map(|(i, _)| i)+ }++ fn degree_one_nodes(&self) -> Vec<usize> {+ let mut deg = vec![0usize; self.coords.len()];+ for &(u, v, _) in &self.seg_nodes {+ deg[u] += 1;+ deg[v] += 1;+ }+ (0..self.coords.len()).filter(|&i| deg[i] == 1).collect()+ }++ fn dijkstra(&self, starts: &[usize]) -> (Vec<f64>, Vec<Option<usize>>) {+ let n = self.coords.len();+ let mut dist = vec![f64::INFINITY; n];+ let mut prev = vec![None; n];+ let mut heap: std::collections::BinaryHeap<(std::cmp::Reverse<i64>, usize)> = std::collections::BinaryHeap::new();+ for &s in starts {+ if s < n && dist[s] > 0.0 {+ dist[s] = 0.0;+ heap.push((std::cmp::Reverse(0), s));+ }+ }+ while let Some((std::cmp::Reverse(du_i), u)) = heap.pop() {+ let du = du_i as f64 / 1e6;+ if du > dist[u] + 1e-6 { continue; }+ for &(v, w) in &self.adj[u] {+ let nd = dist[u] + w;+ if nd + 1e-9 < dist[v] {+ dist[v] = nd;+ prev[v] = Some(u);+ heap.push((std::cmp::Reverse((nd * 1e6).round() as i64), v));+ }+ }+ }+ (dist, prev)+ }++ fn dist_on_seg(&self, dist: &[f64], seg_idx: usize, along: f64) -> Option<f64> {+ let &(u, v, l) = self.seg_nodes.get(seg_idx)?;+ let (du, dv) = (dist[u], dist[v]);+ if !du.is_finite() && !dv.is_finite() { return None; }+ let a = along.clamp(0.0, l);+ Some((du + a).min(dv + (l - a)))+ }+}++/// Choose matched start nodes for a differential pair (P and N) so cumulative arc-length walks+/// start at the same end of the pair (connector or IC).+fn matched_pair_starts(gp: &NetGraph, gn: &NetGraph, pads_p: &[&aiflow_board::Pad], pads_n: &[&aiflow_board::Pad]) -> (Vec<usize>, Vec<usize>) {+ // Prefer a component reference that owns pads on both P and N (e.g. J1 or U1)+ let mut shared: Vec<&str> = pads_p.iter().map(|p| p.reference.as_str()).filter(|r| pads_n.iter().any(|q| q.reference == *r)).collect();+ shared.sort();+ shared.dedup();+ if let Some(ref_name) = shared.first() {+ let sp: Vec<usize> = pads_p.iter().filter(|p| p.reference == *ref_name).flat_map(|p| gp.pad_nodes(p)).collect();+ let sn: Vec<usize> = pads_n.iter().filter(|p| p.reference == *ref_name).flat_map(|p| gn.pad_nodes(p)).collect();+ if !sp.is_empty() && !sn.is_empty() {+ return (sp, sn);+ }+ }+ // Fall back to the closest pair of degree-1 track endpoints (or any nodes)+ let ep = { let d = gp.degree_one_nodes(); if d.is_empty() { (0..gp.coords.len()).collect() } else { d } };+ let en = { let d = gn.degree_one_nodes(); if d.is_empty() { (0..gn.coords.len()).collect() } else { d } };+ let mut best: Option<(f64, usize, usize)> = None;+ for &i in &ep {+ for &j in &en {+ let d = pt_dist((gp.coords[i].1, gp.coords[i].2), (gn.coords[j].1, gn.coords[j].2));+ if best.map(|b| d < b.0).unwrap_or(true) { best = Some((d, i, j)); }+ }+ }+ match best {+ Some((_, i, j)) => (vec![i], vec![j]),+ None => (vec![], vec![]),+ }+}++/// Measure T-stub lengths to intermediate pads (e.g. ESD/TVS package) on a 3+ pad net.+fn measure_pad_stubs(net: &str, graph: &NetGraph, pads: &[&aiflow_board::Pad]) -> Vec<Value> {+ if pads.len() < 3 || graph.coords.is_empty() { return Vec::new(); }+ let pad_nodes: Vec<Vec<usize>> = pads.iter().map(|p| graph.pad_nodes(p)).collect();+ let active: Vec<usize> = (0..pads.len()).filter(|&k| !pad_nodes[k].is_empty()).collect();+ if active.len() < 3 { return Vec::new(); }+ // Find the two endpoint pads maximizing shortest-path distance (the main run)+ let mut best_pair: Option<(f64, usize, usize, Vec<Option<usize>>)> = None;+ for &i in &active {+ let (dist, prev) = graph.dijkstra(&pad_nodes[i]);+ for &j in &active {+ if j <= i { continue; }+ if let Some(d) = pad_nodes[j].iter().map(|&v| dist[v]).filter(|d| d.is_finite()).min_by(|a, b| a.total_cmp(b)) {+ if best_pair.as_ref().map(|b| d > b.0).unwrap_or(true) {+ best_pair = Some((d, i, j, prev.clone()));+ }+ }+ }+ }+ let Some((_, pa, pb, prev)) = best_pair else { return Vec::new() };+ // Reconstruct main path vertices between pa and pb+ let (dist_a, _) = graph.dijkstra(&pad_nodes[pa]);+ let Some(&end_v) = pad_nodes[pb].iter().filter(|&&v| dist_a[v].is_finite()).min_by(|&&a, &&b| dist_a[a].total_cmp(&dist_a[b])) else { return Vec::new() };+ let mut main_verts: Vec<usize> = Vec::new();+ let mut cur = Some(end_v);+ let mut guard = 0usize;+ while let Some(v) = cur {+ main_verts.push(v);+ cur = prev[v];+ guard += 1;+ if guard > graph.coords.len() + 1 { break; }+ }+ main_verts.extend_from_slice(&pad_nodes[pa]);+ main_verts.extend_from_slice(&pad_nodes[pb]);+ main_verts.sort_unstable();+ main_verts.dedup();+ // Distance from main path to every intermediate pad+ let (from_main, _) = graph.dijkstra(&main_verts);+ let mut stubs = Vec::new();+ for &k in &active {+ if k == pa || k == pb { continue; }+ if let Some(stub_mm) = pad_nodes[k].iter().map(|&v| from_main[v]).filter(|d| d.is_finite()).min_by(|a, b| a.total_cmp(b)) {+ if stub_mm > 0.05 {+ stubs.push(json!({"net": net, "pad": pads[k].key, "stubMm": r2(stub_mm), "at": [r2(pads[k].x), r2(pads[k].y)]}));+ }+ }+ }+ stubs+}++/// Per-net geometric discontinuities (off-45 segments, 90-deg corners, acute corners, short wiggles).+fn net_discontinuities(segs: &[&Track]) -> (Vec<Value>, Vec<Value>, Vec<Value>, Vec<Value>) {+ let key = |l: usize, p: (f64, f64)| (l, (p.0 * 1000.0).round() as i64, (p.1 * 1000.0).round() as i64);+ let mut ends: std::collections::HashMap<(usize, i64, i64), Vec<usize>> = std::collections::HashMap::new();+ let mut off = Vec::new();+ for (i, s) in segs.iter().enumerate() {+ let l = len(s);+ if l < 1e-4 { continue; }+ let dev = off45_deg(s.a, s.b);+ if l >= 0.05 && dev > 1.0 {+ off.push(json!({"net": s.net, "layer": layer_name(s.layer), "from": [r2(s.a.0), r2(s.a.1)], "to": [r2(s.b.0), r2(s.b.1)], "offDeg": r2(dev), "lengthMm": r2(l)}));+ }+ ends.entry(key(s.layer, s.a)).or_default().push(i);+ ends.entry(key(s.layer, s.b)).or_default().push(i);+ }+ let near = |a: (f64, f64), b: (f64, f64)| pt_dist(a, b) < 1e-3;+ let other = |s: &Track, p: (f64, f64)| if near(s.a, p) { s.b } else { s.a };+ let turn_at = |i: usize, p: (f64, f64)| -> Option<f64> {+ let s = segs[i];+ let lst = ends.get(&key(s.layer, p))?;+ if lst.len() != 2 { return None; }+ let j = if lst[0] == i { lst[1] } else { lst[0] };+ let (q0, q1) = (other(s, p), other(segs[j], p));+ Some(turn_deg_pair((p.0 - q0.0, p.1 - q0.1), (q1.0 - p.0, q1.1 - p.1)))+ };+ let (mut right, mut acute, mut wiggles) = (Vec::new(), Vec::new(), Vec::new());+ for (k, lst) in &ends {+ if lst.len() != 2 { continue; }+ let p = (k.1 as f64 / 1000.0, k.2 as f64 / 1000.0);+ let (s0, s1) = (segs[lst[0]], segs[lst[1]]);+ // Ignore sub-half-width grid-snap micro-segments completely buried inside the copper radius+ let micro = len(s0) < (s0.width * 0.5).min(0.12) || len(s1) < (s1.width * 0.5).min(0.12);+ let at = if near(s0.a, p) { s0.a } else { s0.b };+ let Some(t) = turn_at(lst[0], at) else { continue };+ if (t.abs() - 90.0).abs() < 2.0 {+ right.push(json!({"net": s0.net, "layer": layer_name(k.0), "at": [r2(at.0), r2(at.1)]}));+ } else if t.abs() > 92.0 && !micro {+ acute.push(json!({"net": s0.net, "layer": layer_name(k.0), "at": [r2(at.0), r2(at.1)], "angleDeg": r2(180.0 - t.abs())}));+ }+ }+ for (i, s) in segs.iter().enumerate() {+ let l = len(s);+ if !(1e-4..=1.0).contains(&l) { continue; }+ let (Some(ta), Some(tb)) = (turn_at(i, s.a), turn_at(i, s.b)) else { continue };+ if ta.abs() < 1.0 || tb.abs() < 1.0 { continue; }+ if (-ta > 0.0) != (tb > 0.0) {+ wiggles.push(json!({"net": s.net, "layer": layer_name(s.layer), "at": [r2((s.a.0 + s.b.0) / 2.0), r2((s.a.1 + s.b.1) / 2.0)], "lengthMm": r2(l)}));+ }+ }+ (off, right, acute, wiggles)+}+ /// The copper of one ground net a coplanar target is judged against: its filled zone islands, its /// pads and its tracks, as polygons per outer copper layer, and the layers it has a filled zone on. /// Only on those is the pour beside a trace measured; elsewhere (not poured yet, or only a plan) it@@ -833,12 +1433,19 @@ impl GroundCopper { /// the layer (not poured yet, or a plan) the pour is assumed at the target's gap and the result says /// so: assumed, not measured. pub fn check_target(t: &Target, st: &Stackup, tracks: &[Track], vias: &[Via], pads: &[aiflow_board::Pad], ground: &GroundCopper) -> Value {+ check_target_with_vias(t, st, tracks, vias, vias, pads, ground)+}++/// Judge one target on its landed (or planned) copper, using `all_vias` (all board vias, including+/// GND stitching vias) to verify reference-plane return vias near differential pair layer transitions.+pub fn check_target_with_vias(t: &Target, st: &Stackup, tracks: &[Track], vias: &[Via], all_vias: &[Via], pads: &[aiflow_board::Pad], ground: &GroundCopper) -> Value { let tol = t.ohms * t.tolerance / 100.0; let geom = |l: usize| st.layers.iter().find(|g| g.name == layer_name(l)).map(|g| match (&t.coplanar, g.h2) { (Some(c), None) => g.with_coplanar(c.gap), _ => g.clone() }); let mine: Vec<Vec<&Track>> = t.nets.iter().map(|n| tracks.iter().filter(|x| &x.net == n && len(x) > 1e-9).collect()).collect();+ let own_vias: Vec<Vec<&Via>> = t.nets.iter().map(|n| vias.iter().filter(|v| &v.net == n).collect()).collect(); let own_pads: Vec<Vec<&aiflow_board::Pad>> = t.nets.iter().map(|n| pads.iter().filter(|p| &p.net == n).collect()).collect(); let in_pad = |side: usize, layer: usize, x: f64, y: f64| own_pads[side].iter().any(|p| p.on_copper(layer) && p.polys.iter().any(|q| aiflow_board::geom::point_in_poly(x, y, q)));- let via_count: Vec<usize> = t.nets.iter().map(|n| vias.iter().filter(|v| &v.net == n).count()).collect();+ let via_count: Vec<usize> = own_vias.iter().map(|v| v.len()).collect(); let mut by_layer: BTreeMap<String, f64> = BTreeMap::new(); for v in &mine { for x in v { *by_layer.entry(layer_name(x.layer)).or_insert(0.0) += len(x); } } let mut out = json!({"target": t.name, "nets": t.nets, "differential": t.diff, "targetOhms": t.ohms, "tolerancePercent": t.tolerance, "lengthByLayerMm": by_layer.iter().map(|(k, v)| (k.clone(), json!(r2(*v)))).collect::<serde_json::Map<_, _>>(), "vias": via_count});@@ -853,12 +1460,22 @@ pub fn check_target(t: &Target, st: &Stackup, tracks: &[Track], vias: &[Via], pa let n = t.nets.len(); let (mut line, mut controlled) = (vec![0.0; n], vec![0.0; n]); let mut widths: Vec<f64> = Vec::new();+ // Build per-net copper graphs for phase matching, via alignment, and ESD/TVS stub measurement+ let graphs: Vec<NetGraph> = (0..n).map(|side| NetGraph::build(&mine[side], &own_vias[side], &own_pads[side])).collect();+ let pair_dists: Option<(Vec<f64>, Vec<f64>)> = if t.diff {+ let (sp, sn) = matched_pair_starts(&graphs[0], &graphs[1], &own_pads[0], &own_pads[1]);+ if !sp.is_empty() && !sn.is_empty() {+ Some((graphs[0].dijkstra(&sp).0, graphs[1].dijkstra(&sn).0))+ } else { None }+ } else { None };+ // Coupled samples along side 0 (P): (s_p, s_n, gap, px, py, seg_len)+ let mut coupled_samples: Vec<(f64, f64, f64, f64, f64, f64)> = Vec::new(); // coplanar: where the pour is measured or assumed, the gaps measured, the length with no ground beside it let (mut measured_on, mut assumed_on): (Vec<String>, Vec<String>) = (Vec::new(), Vec::new()); let (mut cmin, mut cmax) = (f64::INFINITY, f64::NEG_INFINITY); let mut no_ground = vec![0.0; n]; for side in 0..n {- for x in &mine[side] {+ for (seg_idx, x) in mine[side].iter().enumerate() { widths.push(r4(x.width)); let l = len(x); let dir = ((x.b.0 - x.a.0) / l, (x.b.1 - x.a.1) / l);@@ -906,7 +1523,7 @@ pub fn check_target(t: &Target, st: &Stackup, tracks: &[Track], vias: &[Via], pa g.z0(x.width).0 } } else {- let (gap, w2, pside) = partner_gap(px, py, dir, x.width, x.layer, &mine[1 - side])?;+ let (gap, w2, pside, pidx, palong) = partner_gap_detail(px, py, dir, x.width, x.layer, &mine[1 - side])?; if gap <= 0.0 || (w2 - x.width).abs() > 1e-3 { return None; } let gg = if measured { let o = gap_on(-pside);@@ -920,6 +1537,13 @@ pub fn check_target(t: &Target, st: &Stackup, tracks: &[Track], vias: &[Via], pa if gg.valid(x.width, Some(gap)).is_err() { return None; } gmin = gmin.min(gap); gmax = gmax.max(gap);+ if side == 0 {+ if let Some((dp, dn)) = &pair_dists {+ if let (Some(sp), Some(sn)) = (graphs[0].dist_on_seg(dp, seg_idx, f * l), graphs[1].dist_on_seg(dn, pidx, palong)) {+ coupled_samples.push((sp, sn, gap, px, py, seg));+ }+ }+ } gg.zdiff(x.width, gap).0 }; Some(z)@@ -942,6 +1566,16 @@ pub fn check_target(t: &Target, st: &Stackup, tracks: &[Track], vias: &[Via], pa } out["coplanar"] = cp; }+ // Per-target geometric discontinuities (issue #212): off-45 segments, 90-deg corners, acute corners,+ // short wiggles, and sudden gap jumps > maxGapJumpPercent outside pad-breakout windows.+ let (mut off_all, mut right_all, mut acute_all, mut wig_all, mut gap_jumps) = (Vec::new(), Vec::new(), Vec::new(), Vec::new(), Vec::new());+ for side in 0..n {+ let (off, right, acute, wig) = net_discontinuities(&mine[side]);+ off_all.extend(off);+ right_all.extend(right);+ acute_all.extend(acute);+ wig_all.extend(wig);+ } let uncontrolled: Vec<f64> = line.iter().zip(&controlled).map(|(a, b)| (a - b).max(0.0)).collect(); out["lengthMm"] = json!(line.iter().map(|x| r2(*x)).collect::<Vec<_>>()); out["ohms"] = if zmin.is_finite() { json!([r2(zmin), r2(zmax)]) } else { Value::Null };@@ -952,7 +1586,145 @@ pub fn check_target(t: &Target, st: &Stackup, tracks: &[Track], vias: &[Via], pa out["skewMm"] = json!(r4(skew)); out["maxSkewMm"] = json!(t.max_skew); if skew > t.max_skew + 1e-9 { reasons.push(format!("length skew {skew:.3} mm over maxSkewMm {} (route tunes a pair's skew with bumps on its shorter net where they clear; tune the rest by hand)", t.max_skew)); }- if by_layer.len() > 1 || via_count.iter().any(|v| *v > 0) { reasons.push(format!("the pair changes layer ({} vias): the closed forms do not model the via transition", via_count.iter().sum::<usize>())); }++ // 1. Intra-pair phase matching & mid-run gap jumps (issue #212)+ if !coupled_samples.is_empty() {+ coupled_samples.sort_by(|a, b| a.0.total_cmp(&b.0));+ let total_p = line[0];+ // A single 45-deg pair bend naturally creates 2*(sqrt(2)-1)*pitch (~0.83*pitch) of+ // transient skew until the opposing bend cancels it; default allows one bend's pitch+ // when maxPhaseSkewMm is not explicitly set, while explicit maxPhaseSkewMm is strict.+ let est_pitch = widths.iter().copied().fold(0.0f64, f64::max) + if gmin.is_finite() { gmin } else { 0.0 };+ let phase_limit = t.max_phase_skew.unwrap_or_else(|| t.max_skew.max(est_pitch));+ let mut max_phase_skew = 0.0f64;+ let mut worst_at: Option<(f64, f64)> = None;+ let mut cur_run = 0.0f64;+ let mut worst_run = 0.0f64;+ let mut prev_sp: Option<f64> = None;+ let mut prev_gap: Option<f64> = None;+ for &(sp, sn, gap, px, py, seg) in &coupled_samples {+ let delta = (sp - sn).abs();+ if delta > max_phase_skew {+ max_phase_skew = delta;+ worst_at = Some((px, py));+ }+ let contiguous = prev_sp.map(|p| (sp - p) <= 0.5).unwrap_or(false);+ if delta > phase_limit + 1e-9 {+ cur_run = if contiguous { cur_run + seg } else { seg };+ if cur_run > worst_run { worst_run = cur_run; }+ } else {+ cur_run = 0.0;+ }+ // Check sudden gap jumps outside breakout windows at either end+ if contiguous && sp > t.max_uncontrolled && (total_p - sp) > t.max_uncontrolled {+ if let Some(pg) = prev_gap {+ let base = pg.min(gap).max(1e-6);+ let jump_pct = (gap - pg).abs() / base * 100.0;+ if jump_pct > t.max_gap_jump_percent + 1e-9 {+ gap_jumps.push(json!({"at": [r2(px), r2(py)], "fromMm": r4(pg), "toMm": r4(gap), "jumpPercent": r2(jump_pct)}));+ }+ }+ }+ prev_sp = Some(sp);+ prev_gap = Some(gap);+ }+ let phase_pass = worst_run <= t.max_phase_skew_run + 1e-9;+ out["phaseMatching"] = json!({+ "maxSkewMm": r4(max_phase_skew),+ "worstRunMm": r2(worst_run),+ "maxPhaseSkewMm": r4(phase_limit),+ "maxPhaseSkewRunMm": t.max_phase_skew_run,+ "worstAt": worst_at.map(|(x, y)| json!([r2(x), r2(y)])),+ "pass": phase_pass,+ });+ if !phase_pass {+ let loc = worst_at.map(|(x, y)| format!(" near ({x:.2}, {y:.2})")).unwrap_or_default();+ reasons.push(format!("intra-pair phase skew reaches {max_phase_skew:.3} mm (over maxPhaseSkewMm {:.3}) for {worst_run:.1} mm of coupled travel (limit {} mm){loc}: match skew near where it is introduced, not only at the far end", phase_limit, t.max_phase_skew_run));+ }+ }++ // 2. Layer transitions & symmetric via-pair check (issue #212)+ let total_vias: usize = via_count.iter().sum();+ if by_layer.len() > 1 || total_vias > 0 {+ if !t.allow_layer_change {+ reasons.push(format!("the pair changes layer ({total_vias} vias): the closed forms do not model the via transition (set \"allowLayerChange\": true on the target for multilayer symmetric via-pair checks)"));+ } else {+ let mut vt_issues: Vec<String> = Vec::new();+ let mut vt_recs: Vec<String> = Vec::new();+ let mut paired_count = 0usize;+ if own_vias[0].len() != own_vias[1].len() {+ vt_issues.push(format!("unequal via count on pair: {} has {} via(s), {} has {} via(s)", t.nets[0], own_vias[0].len(), t.nets[1], own_vias[1].len()));+ } else if own_vias[0].is_empty() {+ vt_issues.push("the pair uses multiple layers with 0 vias".into());+ } else {+ let extra_ref = t.coplanar.as_ref().map(|c| c.net.as_str());+ let ref_vias: Vec<&Via> = all_vias.iter().filter(|v| is_ref_ground_net(&v.net, extra_ref)).collect();+ let mut used_n = vec![false; own_vias[1].len()];+ for vp in &own_vias[0] {+ let best = own_vias[1].iter().enumerate().filter(|(j, _)| !used_n[*j]).min_by(|(_, a), (_, b)| pt_dist((vp.x, vp.y), (a.x, a.y)).total_cmp(&pt_dist((vp.x, vp.y), (b.x, b.y))));+ let Some((j, vn)) = best else { continue };+ used_n[j] = true;+ paired_count += 1;+ let pitch = pt_dist((vp.x, vp.y), (vn.x, vn.y));+ let mid = ((vp.x + vn.x) / 2.0, (vp.y + vn.y) / 2.0);+ if pitch > t.via_pair_max_pitch + 1e-9 {+ vt_issues.push(format!("via pair near ({:.2}, {:.2}) is {:.2} mm apart (over viaPairMaxPitchMm {})", mid.0, mid.1, pitch, t.via_pair_max_pitch));+ }+ if let Some((dp, dn)) = &pair_dists {+ if let (Some(np), Some(nn)) = (graphs[0].nearest_node(vp.x, vp.y, (vp.size / 2.0).max(0.2)), graphs[1].nearest_node(vn.x, vn.y, (vn.size / 2.0).max(0.2))) {+ if dp[np].is_finite() && dn[nn].is_finite() {+ let along_skew = (dp[np] - dn[nn]).abs();+ if along_skew > t.via_pair_max_skew + 1e-9 {+ vt_issues.push(format!("via pair near ({:.2}, {:.2}) is offset by {:.2} mm along the route (over viaPairMaxSkewMm {})", mid.0, mid.1, along_skew, t.via_pair_max_skew));+ }+ }+ }+ }+ let stitch_n = ref_vias.iter().filter(|rv| pt_dist((rv.x, rv.y), mid) <= t.stitch_via_radius + 1e-9).count();+ if stitch_n == 0 {+ vt_issues.push(format!("no reference-plane stitching via within {} mm of pair transition at ({:.2}, {:.2})", t.stitch_via_radius, mid.0, mid.1));+ } else if stitch_n == 1 {+ vt_recs.push(format!("pair transition at ({:.2}, {:.2}) has 1 ground stitching via within {} mm; two symmetric ground vias are recommended", mid.0, mid.1, t.stitch_via_radius));+ }+ }+ }+ out["viaTransitions"] = json!({"allowed": true, "pairedCount": paired_count, "issues": vt_issues, "recommendations": vt_recs, "pass": vt_issues.is_empty()});+ for iss in vt_issues { reasons.push(format!("via transition: {iss}")); }+ }+ }++ // 3. Inline ESD/TVS breakout stub check for 3+ pad nets (issue #212)+ let mut stubs_all = Vec::new();+ for side in 0..n {+ stubs_all.extend(measure_pad_stubs(&t.nets[side], &graphs[side], &own_pads[side]));+ }+ if !stubs_all.is_empty() {+ for s in &stubs_all {+ let mm = s["stubMm"].as_f64().unwrap_or(0.0);+ if mm > t.max_stub + 1e-9 {+ reasons.push(format!("{} pad {} has a {:.2} mm T-stub off the main pair path (over maxStubMm {}): route the ESD/TVS pad inline (pass-through)", s["net"].as_str().unwrap_or(""), s["pad"].as_str().unwrap_or(""), mm, t.max_stub));+ }+ }+ out["stubs"] = json!(stubs_all);+ }+ }+ let disc_count = off_all.len() + right_all.len() + acute_all.len() + wig_all.len() + gap_jumps.len();+ out["discontinuities"] = json!({+ "count": disc_count,+ "offAngle": off_all,+ "rightAngles": right_all,+ "acute": acute_all,+ "wiggles": wig_all,+ "gapJumps": gap_jumps,+ });+ if !acute_all.is_empty() {+ reasons.push(format!("{} acute corner(s) (> 92 deg) on controlled-impedance copper (first at {})", acute_all.len(), acute_all[0]["at"]));+ }+ if !off_all.is_empty() {+ reasons.push(format!("{} off-45 segment(s) (> 1 deg off multiple of 45) on controlled-impedance copper (first at {} -> {}, {} deg off)", off_all.len(), off_all[0]["from"], off_all[0]["to"], off_all[0]["offDeg"]));+ }+ if !gap_jumps.is_empty() {+ reasons.push(format!("{} sudden pair gap jump(s) > {} % outside pad-breakout windows (first at {}: {} -> {} mm, {} %)", gap_jumps.len(), t.max_gap_jump_percent, gap_jumps[0]["at"], gap_jumps[0]["fromMm"], gap_jumps[0]["toMm"], gap_jumps[0]["jumpPercent"])); } if controlled.iter().all(|c| *c <= 0.0) { reasons.push(format!("no copper of {} meets {} ohm +-{} %", t.label(), t.ohms, t.tolerance)); } widths.sort_by(|a, b| a.total_cmp(b));@@ -1035,7 +1807,7 @@ mod tests { // tight gaps on thick dielectric are refused: s/h 0.125 is 5.7 % off the field solve (85.48 ohm) assert!(in_range("microstrip", 1.0, Some(0.2), 1.6).is_err()); // a 5:1 offset stripline (7 % off the field solve, 60.20 ohm) is refused too- let g = LayerGeom { name: "In1.Cu".into(), structure: "offset stripline".into(), h1: 0.2, h2: Some(1.03), reference: vec![], er: 4.3, t: 0.035, coplanar: None };+ let g = LayerGeom { name: "In1.Cu".into(), structure: "offset stripline".into(), h1: 0.2, h2: Some(1.03), reference: vec![], er: 4.3, t: 0.035, coplanar: None, solder_mask: None }; assert!(g.valid(0.15, None).is_err()); } @@ -1331,6 +2103,252 @@ mod tests { assert_eq!(check_target(&ts[0], &st, &one(w50), &[], &[], &GroundCopper::default())["status"], "pass"); assert_eq!(check_target(&ts[0], &st, &one(0.15), &[], &[], &GroundCopper::default())["status"], "fail"); }++ #[test]+ fn solder_mask_matches_adom_fields_within_two_percent() {+ // Cross-checked against adom-fields 0.10.11 --with si 2-D Laplace solve (0.025 mm LPI mask)+ let mask = SolderMask::default();+ let singles = [+ ("7628 w=0.20", microstrip_coated(0.20, 0.2104, 0.035, 4.4, mask).0, 62.7, 2.0),+ ("7628 w=0.25", microstrip_coated(0.25, 0.2104, 0.035, 4.4, mask).0, 57.1, 2.0),+ ("7628 w=0.35", microstrip_coated(0.35, 0.2104, 0.035, 4.4, mask).0, 48.6, 2.0),+ ("7628 w=0.369", microstrip_coated(0.369, 0.2104, 0.035, 4.4, mask).0, 47.3, 2.0),+ ("3313 w=0.13", microstrip_coated(0.13, 0.0994, 0.035, 4.05, mask).0, 52.6, 2.0),+ ("3313 w=0.15", microstrip_coated(0.15, 0.0994, 0.035, 4.05, mask).0, 49.4, 2.0),+ ("3313 w=0.165", microstrip_coated(0.165, 0.0994, 0.035, 4.05, mask).0, 47.3, 2.0),+ ("2L w=1.0", microstrip_coated(1.0, 1.53, 0.035, 4.5, mask).0, 80.9, 2.0),+ ("2L w=2.85", microstrip_coated(2.85, 1.53, 0.035, 4.5, mask).0, 48.9, 2.0),+ ];+ for (name, pred, reference, tol) in singles {+ assert!(pct(pred, reference) < tol, "{name}: pred {pred:.2} vs fields {reference:.2} ({:.2}%)", pct(pred, reference));+ }+ let pairs = [+ ("7628 ETH 0.2/0.15", 2.0 * coupled_microstrip_coated(0.20, 0.15, 0.2104, 0.035, 4.4, mask).0, 91.4, 2.0),+ ("7628 USB2 0.25/0.15", 2.0 * coupled_microstrip_coated(0.25, 0.15, 0.2104, 0.035, 4.4, mask).0, 84.5, 2.0),+ ("7628 USB 0.3689/0.331", 2.0 * coupled_microstrip_coated(0.3689, 0.3311, 0.2104, 0.035, 4.4, mask).0, 84.5, 2.0),+ ("3313 ETH 0.13/0.20", 2.0 * coupled_microstrip_coated(0.13, 0.20, 0.0994, 0.035, 4.05, mask).0, 94.2, 2.0),+ ("3313 USB 0.15/0.15", 2.0 * coupled_microstrip_coated(0.15, 0.15, 0.0994, 0.035, 4.05, mask).0, 84.1, 2.0),+ ];+ for (name, pred, reference, tol) in pairs {+ assert!(pct(pred, reference) < tol, "{name}: pred {pred:.2} vs fields {reference:.2} ({:.2}%)", pct(pred, reference));+ }+ // Coated GCPW lowers impedance relative to bare GCPW+ let z_bare = gcpw(0.3095, 0.15, 0.2104, 0.035, 4.4).0;+ let z_coat = gcpw_coated(0.3095, 0.15, 0.2104, 0.035, 4.4, mask).0;+ assert!(z_coat < z_bare * 0.96 && z_coat > z_bare * 0.80, "bare {z_bare:.2}, coated {z_coat:.2}");+ // Spec solderMask: true solves directly with mask and reports bareOhms + shift+ let st = stackup(&jlc_four_layer(), &json!({"solderMask": {"thicknessMm": 0.025, "epsilonR": 3.8}})).unwrap();+ let ts = targets(&json!({"impedanceTargets": {"USB": {"pair": ["USB_DP", "USB_DN"], "targetDiffOhms": 90, "gapMm": 0.15}}})).unwrap();+ let fab = Fab { min_width: 0.127, min_space: 0.127, source: "t".into() };+ let row = solve_row(&ts[0], &st.layers[0], &fab, None);+ assert_eq!(row["ok"], true, "{row}");+ assert_eq!(row["solderMaskModelled"], true);+ assert!(row["bareOhms"].as_f64().unwrap() > 95.0 && (row["ohms"].as_f64().unwrap() - 90.0).abs() < 0.2, "{row}");+ assert!(row["solderMaskShiftPercent"].as_f64().unwrap() < -5.0, "{row}");+ }++ #[test]+ fn phase_matching_catches_far_end_compensated_skew() {+ let st = stackup(&jlc_four_layer(), &json!({})).unwrap();+ let ts = targets(&json!({"impedanceTargets": {"USB": {"pair": ["DP", "DN"], "targetDiffOhms": 90, "maxSkewMm": 0.5, "maxPhaseSkewMm": 0.5, "maxUncontrolledMm": 6.0}}})).unwrap();+ let fab = Fab { min_width: 0.127, min_space: 0.127, source: "t".into() };+ let row = solve_row(&ts[0], &st.layers[0], &fab, None);+ let (w, s) = (row["widthMm"].as_f64().unwrap(), row["gapMm"].as_f64().unwrap());+ let p = w + s;+ // DP adds +2.0 mm detour right at x=0..2 (y=0 -> -1 -> 0), then runs coupled x=2..28 (26 mm),+ // then DN adds +2.0 mm detour at x=28..30 (y=p -> p+1 -> p). Total lengths match (skew=0),+ // but the pair travels 2.0 mm out of phase for 26 mm!+ let seg = |net: &str, a: (f64, f64), b: (f64, f64)| Track { net: net.into(), layer: 0, a, b, width: w };+ let mismatched = vec![+ // DP: 1.0 + 2.0 + 1.0 = 4.0 mm for x=0..2, then 26 mm coupled, then 2 mm straight -> 32.0 mm+ seg("DP", (0.0, 0.0), (0.0, -1.0)),+ seg("DP", (0.0, -1.0), (2.0, -1.0)),+ seg("DP", (2.0, -1.0), (2.0, 0.0)),+ seg("DP", (2.0, 0.0), (30.0, 0.0)),+ // DN: 2.0 mm straight, then 26 mm coupled, then 1.0 + 2.0 + 1.0 = 4.0 mm at far end -> 32.0 mm+ seg("DN", (0.0, p), (28.0, p)),+ seg("DN", (28.0, p), (28.0, p + 1.0)),+ seg("DN", (28.0, p + 1.0), (30.0, p + 1.0)),+ seg("DN", (30.0, p + 1.0), (30.0, p)),+ ];+ let c = check_target(&ts[0], &st, &mismatched, &[], &[], &GroundCopper::default());+ assert_eq!(c["status"], "fail", "{c}");+ assert!(c["skewMm"].as_f64().unwrap() < 0.01, "total skew is zero: {c}");+ assert_eq!(c["phaseMatching"]["pass"], false, "{c}");+ assert!(c["phaseMatching"]["maxSkewMm"].as_f64().unwrap() > 1.8, "{c}");+ assert!(c["phaseMatching"]["worstRunMm"].as_f64().unwrap() > 20.0, "{c}");+ // Now match DN at the same end (x=0..2) so the middle 26 mm travels in phase -> pass+ let matched = vec![+ seg("DP", (0.0, 0.0), (0.0, -1.0)),+ seg("DP", (0.0, -1.0), (2.0, -1.0)),+ seg("DP", (2.0, -1.0), (2.0, 0.0)),+ seg("DP", (2.0, 0.0), (30.0, 0.0)),+ seg("DN", (0.0, p), (0.0, p + 1.0)),+ seg("DN", (0.0, p + 1.0), (2.0, p + 1.0)),+ seg("DN", (2.0, p + 1.0), (2.0, p)),+ seg("DN", (2.0, p), (30.0, p)),+ ];+ let c2 = check_target(&ts[0], &st, &matched, &[], &[], &GroundCopper::default());+ assert_eq!(c2["phaseMatching"]["pass"], true, "{c2}");+ assert_eq!(c2["status"], "pass", "{c2}");+ }++ #[test]+ fn per_pair_discontinuities_catch_off45_acute_and_gap_jumps() {+ let st = stackup(&jlc_four_layer(), &json!({})).unwrap();+ let ts = targets(&json!({"impedanceTargets": {"USB": {"pair": ["DP", "DN"], "targetDiffOhms": 90, "maxUncontrolledMm": 5.0}}})).unwrap();+ let fab = Fab { min_width: 0.127, min_space: 0.127, source: "t".into() };+ let row = solve_row(&ts[0], &st.layers[0], &fab, None);+ let (w, s) = (row["widthMm"].as_f64().unwrap(), row["gapMm"].as_f64().unwrap());+ let p = w + s;+ let seg = |net: &str, a: (f64, f64), b: (f64, f64)| Track { net: net.into(), layer: 0, a, b, width: w };+ // Off-45 segment (20 deg) on both nets+ let off45_tracks = vec![+ seg("DP", (0.0, 0.0), (10.0, 0.0)),+ seg("DP", (10.0, 0.0), (20.0, 3.64)),+ seg("DN", (0.0, p), (10.0, p)),+ seg("DN", (10.0, p), (20.0, p + 3.64)),+ ];+ let c = check_target(&ts[0], &st, &off45_tracks, &[], &[], &GroundCopper::default());+ assert_eq!(c["status"], "fail", "{c}");+ assert_eq!(c["discontinuities"]["offAngle"].as_array().unwrap().len(), 2, "{c}");+ assert!(c["reasons"].to_string().contains("off-45"), "{c}");++ // Acute corner (135 deg turn) on DP+ let acute_tracks = vec![+ seg("DP", (0.0, 0.0), (10.0, 0.0)),+ seg("DP", (10.0, 0.0), (9.0, -1.0)),+ seg("DP", (9.0, -1.0), (20.0, -1.0)),+ seg("DN", (0.0, p), (20.0, p)),+ ];+ let c = check_target(&ts[0], &st, ´_tracks, &[], &[], &GroundCopper::default());+ assert_eq!(c["status"], "fail", "{c}");+ assert!(!c["discontinuities"]["acute"].as_array().unwrap().is_empty(), "{c}");+ assert!(c["reasons"].to_string().contains("acute"), "{c}");++ // Sudden gap jump (>25%) mid-run (at x=15, well outside 5 mm breakout windows)+ let s2 = s * 1.5;+ let p2 = w + s2;+ let jump_tracks = vec![+ seg("DP", (0.0, 0.0), (30.0, 0.0)),+ seg("DN", (0.0, p), (15.0, p)),+ seg("DN", (15.0, p), (15.0, p2)),+ seg("DN", (15.0, p2), (30.0, p2)),+ ];+ let c = check_target(&ts[0], &st, &jump_tracks, &[], &[], &GroundCopper::default());+ assert_eq!(c["status"], "fail", "{c}");+ assert!(!c["discontinuities"]["gapJumps"].as_array().unwrap().is_empty(), "{c}");+ assert!(c["reasons"].to_string().contains("gap jump"), "{c}");+ }++ #[test]+ fn symmetric_via_pair_transitions_require_matched_vias_and_gnd_stitch() {+ let st = stackup(&jlc_four_layer(), &json!({})).unwrap();+ let fab = Fab { min_width: 0.127, min_space: 0.127, source: "t".into() };+ let t_no = targets(&json!({"impedanceTargets": {"USB": {"pair": ["DP", "DN"], "targetDiffOhms": 90}}})).unwrap()[0].clone();+ let t_yes = targets(&json!({"impedanceTargets": {"USB": {"pair": ["DP", "DN"], "targetDiffOhms": 90, "allowLayerChange": true}}})).unwrap()[0].clone();+ let row = solve_row(&t_yes, &st.layers[0], &fab, None);+ let (w, s) = (row["widthMm"].as_f64().unwrap(), row["gapMm"].as_f64().unwrap());+ let p = w + s;+ // F.Cu (layer 0) -> B.Cu (layer 1) transition at x=15+ let tracks = vec![+ Track { net: "DP".into(), layer: 0, a: (0.0, 0.0), b: (15.0, 0.0), width: w },+ Track { net: "DP".into(), layer: 1, a: (15.0, 0.0), b: (30.0, 0.0), width: w },+ Track { net: "DN".into(), layer: 0, a: (0.0, p), b: (15.0, p), width: w },+ Track { net: "DN".into(), layer: 1, a: (15.0, p), b: (30.0, p), width: w },+ ];+ let via = |net: &str, x: f64, y: f64| Via { net: net.into(), x, y, size: 0.6, drill: 0.3, span: (0, 1) };+ let pair_vias = vec![via("DP", 15.0, 0.0), via("DN", 15.0, p)];++ // 1. Disallowed by default+ let c0 = check_target_with_vias(&t_no, &st, &tracks, &pair_vias, &pair_vias, &[], &GroundCopper::default());+ assert_eq!(c0["status"], "fail", "{c0}");+ assert!(c0["reasons"].to_string().contains("allowLayerChange"), "{c0}");++ // 2. Allowed, but 0 GND stitching vias -> fail+ let c1 = check_target_with_vias(&t_yes, &st, &tracks, &pair_vias, &pair_vias, &[], &GroundCopper::default());+ assert_eq!(c1["status"], "fail", "{c1}");+ assert!(c1["reasons"].to_string().contains("stitching via"), "{c1}");++ // 3. Allowed, with 1 GND stitching via within 2 mm -> pass + recommendation+ let mut all1 = pair_vias.clone();+ all1.push(via("GND", 15.0, -1.0));+ let c2 = check_target_with_vias(&t_yes, &st, &tracks, &pair_vias, &all1, &[], &GroundCopper::default());+ assert_eq!(c2["status"], "pass", "{c2}");+ assert_eq!(c2["viaTransitions"]["recommendations"].as_array().unwrap().len(), 1, "{c2}");++ // 4. Allowed, with 2 symmetric GND stitching vias -> clean pass, 0 recommendations+ let mut all2 = all1.clone();+ all2.push(via("GND", 15.0, p + 1.0));+ let c3 = check_target_with_vias(&t_yes, &st, &tracks, &pair_vias, &all2, &[], &GroundCopper::default());+ assert_eq!(c3["status"], "pass", "{c3}");+ assert!(c3["viaTransitions"]["recommendations"].as_array().unwrap().is_empty(), "{c3}");++ // 5. Offset vias along route (> 0.25 mm) -> fail+ let tracks_off = vec![+ Track { net: "DP".into(), layer: 0, a: (0.0, 0.0), b: (15.0, 0.0), width: w },+ Track { net: "DP".into(), layer: 1, a: (15.0, 0.0), b: (30.0, 0.0), width: w },+ Track { net: "DN".into(), layer: 0, a: (0.0, p), b: (15.8, p), width: w },+ Track { net: "DN".into(), layer: 1, a: (15.8, p), b: (30.0, p), width: w },+ ];+ let vias_off = vec![via("DP", 15.0, 0.0), via("DN", 15.8, p)];+ let mut all_off = vias_off.clone();+ all_off.push(via("GND", 15.0, -1.0));+ let c4 = check_target_with_vias(&t_yes, &st, &tracks_off, &vias_off, &all_off, &[], &GroundCopper::default());+ assert_eq!(c4["status"], "fail", "{c4}");+ assert!(c4["reasons"].to_string().contains("offset by"), "{c4}");+ }++ #[test]+ fn inline_esd_passes_and_t_stub_fails() {+ let st = stackup(&jlc_four_layer(), &json!({})).unwrap();+ let ts = targets(&json!({"impedanceTargets": {"USB": {"pair": ["DP", "DN"], "targetDiffOhms": 90, "maxUncontrolledMm": 5.0, "maxStubMm": 1.5}}})).unwrap();+ let fab = Fab { min_width: 0.127, min_space: 0.127, source: "t".into() };+ let row = solve_row(&ts[0], &st.layers[0], &fab, None);+ let (w, s) = (row["widthMm"].as_f64().unwrap(), row["gapMm"].as_f64().unwrap());+ let p = w + s;+ // Board with J1 (connector), D1 (ESD), U1 (MCU)+ let mk = |esd_y_dp: f64, esd_y_dn: f64| {+ let txt = format!(r#"(kicad_pcb (version 20241229) (layers (0 "F.Cu" signal) (31 "B.Cu" signal))+ (net 1 "DP") (net 2 "DN")+ (gr_rect (start -2 -6) (end 32 8) (layer "Edge.Cuts"))+ (footprint "T:J1" (layer "F.Cu") (at 0 0) (property "Reference" "J1")+ (pad "1" smd rect (at 0 0) (size 0.5 0.35) (layers "F.Cu") (net 1 "DP"))+ (pad "2" smd rect (at 0 {p}) (size 0.5 0.35) (layers "F.Cu") (net 2 "DN")))+ (footprint "T:D1" (layer "F.Cu") (at 8 0) (property "Reference" "D1")+ (pad "1" smd rect (at 0 {esd_y_dp}) (size 0.5 0.35) (layers "F.Cu") (net 1 "DP"))+ (pad "2" smd rect (at 0 {esd_y_dn}) (size 0.5 0.35) (layers "F.Cu") (net 2 "DN")))+ (footprint "T:U1" (layer "F.Cu") (at 30 0) (property "Reference" "U1")+ (pad "1" smd rect (at 0 0) (size 0.5 0.35) (layers "F.Cu") (net 1 "DP"))+ (pad "2" smd rect (at 0 {p}) (size 0.5 0.35) (layers "F.Cu") (net 2 "DN"))))"#);+ Board::from_text("esd.kicad_pcb", txt).unwrap()+ };+ // 1. Inline pass-through ESD: pads sit directly on the main path -> 0 stub -> pass+ let b_inline = mk(0.0, p);+ let tracks_inline = vec![+ Track { net: "DP".into(), layer: 0, a: (0.0, 0.0), b: (8.0, 0.0), width: w },+ Track { net: "DP".into(), layer: 0, a: (8.0, 0.0), b: (30.0, 0.0), width: w },+ Track { net: "DN".into(), layer: 0, a: (0.0, p), b: (8.0, p), width: w },+ Track { net: "DN".into(), layer: 0, a: (8.0, p), b: (30.0, p), width: w },+ ];+ let c_ok = check_target(&ts[0], &st, &tracks_inline, &[], &b_inline.pads, &GroundCopper::default());+ assert_eq!(c_ok["status"], "pass", "{c_ok}");++ // 2. T-stub ESD: D1 sits 3.0 mm off the main path on a perpendicular stub -> fail+ let b_stub = mk(-3.0, p + 3.0);+ let tracks_stub = vec![+ Track { net: "DP".into(), layer: 0, a: (0.0, 0.0), b: (8.0, 0.0), width: w },+ Track { net: "DP".into(), layer: 0, a: (8.0, 0.0), b: (30.0, 0.0), width: w },+ Track { net: "DP".into(), layer: 0, a: (8.0, 0.0), b: (8.0, -3.0), width: w },+ Track { net: "DN".into(), layer: 0, a: (0.0, p), b: (8.0, p), width: w },+ Track { net: "DN".into(), layer: 0, a: (8.0, p), b: (30.0, p), width: w },+ Track { net: "DN".into(), layer: 0, a: (8.0, p), b: (8.0, p + 3.0), width: w },+ ];+ let c_bad = check_target(&ts[0], &st, &tracks_stub, &[], &b_stub.pads, &GroundCopper::default());+ assert_eq!(c_bad["status"], "fail", "{c_bad}");+ assert!(c_bad["reasons"].to_string().contains("T-stub"), "{c_bad}");+ assert!(c_bad["stubs"].as_array().unwrap().len() == 2, "{c_bad}");+ } } #[cfg(test)]
crates/aiflow-router/src/lib.rs+29−3@@ -237,6 +237,8 @@ pub struct Router { pub ko_track: [Mask; 2], pub ko_via: Mask, pub keep_raw: [Vec<i16>; 2],+ /// inner-layer planeUnder region index per cell (-1 none): blocks foreign through-vias without blocking outer tracks+ pub keep_inner_raw: Vec<i16>, /// Spec decoupling pairs resolved on this board (decoupling.rs). pub pairs: Vec<decoupling::PairState>, /// The signal-net order (`route --variants`, variants.rs); the default is shortest first.@@ -294,7 +296,7 @@ impl Router { pad_cells: HashMap::new(), inside, edge_dist, inside_w: HashMap::new(), rip_total: 0, flat_turns: false, net_deadline: None, net_timed_out: false, stats: HashMap::new(), kelvin_owner: HashMap::new(), kelvin_clusters: HashSet::new(), body_owner: vec![-1; n], ic_zone: grid.mask(), ic_nets: HashMap::new(), log_lines: Vec::new(), fixed_raw: [vec![-1; n], vec![-1; n]], fixed_tracks: Vec::new(), fixed_vias: Vec::new(), pad_comp: Vec::new(), comp_copper: HashMap::new(), fixed_targets: HashMap::new(),- keep: Vec::new(), keep_raw: [vec![-1; n], vec![-1; n]], ko_track: [grid.mask(), grid.mask()], ko_via: grid.mask(), pairs: Vec::new(), order: variants::NetOrder::default(), board,+ keep: Vec::new(), keep_raw: [vec![-1; n], vec![-1; n]], ko_track: [grid.mask(), grid.mask()], ko_via: grid.mask(), keep_inner_raw: vec![-1; n], pairs: Vec::new(), order: variants::NetOrder::default(), board, }; r.big_clr_val = r.rules.clearance; // issue #183: a board with no vias has no plane to stitch down to; its plane nets are routed as@@ -439,11 +441,15 @@ impl Router { let mut cells = 0; for (c, b) in m.bits.iter().enumerate() { if *b {- self.keep_raw[reg.layer][c] = k as i16;+ if reg.layer < 2 {+ self.keep_raw[reg.layer][c] = k as i16;+ } else {+ self.keep_inner_raw[c] = k as i16;+ } cells += 1; } }- self.log(format!(" planeUnder {}: {:.1} mm2 of {} kept for {} (a keepout for every other net)", reg.label, cells as f64 * RES * RES, aiflow_board::LAYER_NAMES[reg.layer], reg.net));+ self.log(format!(" planeUnder {}: {:.1} mm2 of {} kept for {} (a keepout for every other net)", reg.label, cells as f64 * RES * RES, plane_under::layer_name(reg.layer), reg.net)); } self.keep = regions; }@@ -483,6 +489,13 @@ impl Router { k >= 0 && self.keep[k as usize].net != net_name } + /// Is a through-via at this cell blocked by any outer or inner planeUnder region belonging to another net?+ pub fn kept_from_via(&self, net_name: &str, c: usize) -> bool {+ if self.kept_from(net_name, 0, c) || self.kept_from(net_name, 1, c) { return true; }+ let k = self.keep_inner_raw[c];+ k >= 0 && self.keep[k as usize].net != net_name+ }+ pub fn inside_for(&mut self, w: f64) -> &Mask { let key = (w * 1000.0).round() as i64; if !self.inside_w.contains_key(&key) {@@ -1037,6 +1050,19 @@ impl Router { via_block.or_with(&sub.dilate(&hr, (clr + via / 2.0 + slop() + 0.0707) / RES)); via_block.or_with(&sub.dilate(&big, (self.big_clr_val + via / 2.0 + slop()) / RES)); }+ if !self.keep.is_empty() && self.keep.iter().any(|k| k.layer >= 2 && k.net != net_name) {+ let mut inner_keep = Mask::new(ww, hh);+ for jj in 0..hh {+ let base = (pj0 as usize + jj) * g.w + pi0 as usize;+ for ii in 0..ww {+ let kr = self.keep_inner_raw[base + ii];+ if kr >= 0 && keep_foreign[kr as usize] {+ inner_keep.bits[jj * ww + ii] = true;+ }+ }+ }+ via_block.or_with(&sub.dilate(&inner_keep, (clr + via / 2.0 + slop() + 0.0707) / RES));+ } if let Some(own) = self.smd_pad_cells.get(&(nid as usize)) { let mut m = Mask::new(ww, hh); for jj in 0..hh {
crates/aiflow-router/src/plane_under.rs+78−19@@ -1,11 +1,21 @@-//! The layer policy for 2-layer power boards (spec "planeUnder"): a region of one copper layer that-//! belongs to one net's plane, typically B.Cu under the hot loop kept as unbroken ground. The router-//! treats every region as a keepout for every other net on that layer (and for other nets' vias,-//! which pierce both layers); `issues` finds other-net copper already inside a region, for the gate.-use aiflow_board::{geom, Board, Pt, B_CU, F_CU, LAYER_NAMES};+//! The layer policy for power and high-speed boards (spec "planeUnder"): a region of any copper+//! layer (F.Cu, B.Cu, In1.Cu, In2.Cu, ...) that belongs to one net's plane, kept as unbroken+//! ground or power reference. The router treats every outer-layer region as a keepout for other+//! nets' tracks and vias, and every inner-layer region as a keepout for other nets' piercing vias;+//! `issues` finds other-net tracks, zones and piercing vias already inside a region, for the gate.+use aiflow_board::{copper_depth, copper_layer, geom, Board, Pt, B_CU, F_CU}; use crate::rules::PlaneUnder; +/// Human-readable copper layer name for a `copper_layer` index (0 = F.Cu, 1 = B.Cu, 2 = In1.Cu, ...).+pub fn layer_name(layer: usize) -> String {+ match layer {+ F_CU => "F.Cu".into(),+ B_CU => "B.Cu".into(),+ k => format!("In{}.Cu", k - 1),+ }+}+ /// A resolved region: layer index, the net that owns it, the polygon, and a label for messages. #[derive(Clone, Debug)] pub struct Region {@@ -30,12 +40,23 @@ fn pad_box(board: &Board, keys: &[String]) -> Result<(f64, f64, f64, f64), Strin Ok(geom::bbox(&pts)) } -/// Every planeUnder entry as a polygon on its layer. An entry naming an unknown layer, part or-/// shape is an error, so a typo never silently disables the policy.+/// Every planeUnder entry as a polygon on its copper layer (F.Cu, B.Cu, In1.Cu, In2.Cu, ...).+/// An entry naming a layer not present on the board, or an unknown part or shape, is an error, so+/// a typo never silently disables the policy. pub fn regions(board: &Board, entries: &[PlaneUnder]) -> Result<Vec<Region>, String> { let mut out = Vec::new();+ let board_layers: Vec<String> = if board.copper_layers.is_empty() {+ vec!["F.Cu".into(), "B.Cu".into()]+ } else {+ board.copper_layers.clone()+ }; for (k, e) in entries.iter().enumerate() {- let layer = match e.layer.as_str() { "F.Cu" => F_CU, "B.Cu" => B_CU, other => return Err(format!("planeUnder[{k}]: layer {other:?} is not F.Cu or B.Cu")) };+ let Some(layer) = copper_layer(e.layer.as_str()) else {+ return Err(format!("planeUnder[{k}]: layer {:?} is not a valid copper layer (board has {})", e.layer, board_layers.join(", ")));+ };+ if !board_layers.iter().any(|bl| bl == &e.layer) {+ return Err(format!("planeUnder[{k}]: layer {:?} is not on this board (board has {})", e.layer, board_layers.join(", ")));+ } if e.net.is_empty() { return Err(format!("planeUnder[{k}]: needs the net that owns the region (\"net\": \"GND\")")); }@@ -73,17 +94,21 @@ fn segment_touches(poly: &[Pt], a: Pt, b: Pt, hw: f64) -> bool { segment_inside(poly, a, b, hw).is_some() } -/// Other-net copper inside a region: tracks and zone outlines on its layer, and vias. One line each,-/// with the length or position, for the gate's report.+/// Other-net copper inside a region: tracks and zones on its copper layer (outer or inner), and+/// vias whose span pierces that copper layer. One line each, with the length or position, for the+/// gate's report. pub fn issues(board: &Board, regions: &[Region]) -> Vec<String> { let mut out = Vec::new(); if regions.is_empty() { return out; }- let tracks = board.tracks();+ let tracks = board.copper_tracks(); let vias = board.vias(); let zones = board.zones();+ let fills = board.copper_fills(); for r in regions {+ let lname = layer_name(r.layer);+ let rdepth = copper_depth(r.layer); let mut by_net: std::collections::BTreeMap<String, f64> = std::collections::BTreeMap::new(); for t in tracks.iter().filter(|t| t.layer == r.layer && t.net != r.net) { if let Some(mm) = segment_inside(&r.poly, t.a, t.b, t.width / 2.0) {@@ -91,19 +116,30 @@ pub fn issues(board: &Board, regions: &[Region]) -> Vec<String> { } } for (net, mm) in by_net {- out.push(format!("{}: {net} track on {} inside the region (about {mm:.1} mm)", r.label, LAYER_NAMES[r.layer]));+ out.push(format!("{}: {net} track on {lname} inside the region (about {mm:.1} mm)", r.label)); }- for v in vias.iter().filter(|v| v.net != r.net) {+ for v in vias.iter().filter(|v| v.net != r.net && rdepth >= v.span.0 && rdepth <= v.span.1) { if geom::point_poly_distance(v.x, v.y, &r.poly) < v.size / 2.0 { out.push(format!("{}: {} via at ({:.2}, {:.2}) inside the region", r.label, v.net, v.x, v.y)); } }- for z in zones.iter().filter(|z| z.net != r.net && z.layers.contains(&r.layer)) {- let islands: Vec<&Vec<Pt>> = z.fills.iter().filter(|(l, _)| *l == r.layer).map(|(_, p)| p).collect();- let shapes: Vec<&Vec<Pt>> = if islands.is_empty() { vec![&z.outline] } else { islands };- let hit = shapes.iter().any(|s| s.len() >= 3 && ((0..s.len()).any(|k| segment_touches(&r.poly, s[k], s[(k + 1) % s.len()], 1e-6)) ||r.poly.iter().any(|&(x, y)| geom::point_in_poly(x, y, s))));- if hit {- out.push(format!("{}: {} zone on {} reaches into the region", r.label, if z.net.is_empty() { "an unassigned" } else { z.net.as_str() }, LAYER_NAMES[r.layer]));+ let mut flagged_zone_nets: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();+ for (znet, flayer, poly) in &fills {+ if *flayer != r.layer || znet == &r.net || poly.len() < 3 { continue; }+ let hit = (0..poly.len()).any(|k| segment_touches(&r.poly, poly[k], poly[(k + 1) % poly.len()], 1e-6))+ || r.poly.iter().any(|&(x, y)| geom::point_in_poly(x, y, poly));+ if hit && flagged_zone_nets.insert(znet.clone()) {+ out.push(format!("{}: {} zone on {lname} reaches into the region", r.label, if znet.is_empty() { "an unassigned" } else { znet.as_str() }));+ }+ }+ for z in zones.iter().filter(|z| z.net != r.net && (z.layers.contains(&r.layer) || z.inner_layers.iter().any(|il| il == &lname))) {+ if flagged_zone_nets.contains(&z.net) { continue; }+ let has_filled_on_layer = fills.iter().any(|(zn, fl, _)| zn == &z.net && *fl == r.layer);+ if has_filled_on_layer { continue; }+ let s = &z.outline;+ let hit = s.len() >= 3 && ((0..s.len()).any(|k| segment_touches(&r.poly, s[k], s[(k + 1) % s.len()], 1e-6)) || r.poly.iter().any(|&(x, y)| geom::point_in_poly(x, y, s)));+ if hit && flagged_zone_nets.insert(z.net.clone()) {+ out.push(format!("{}: {} zone on {lname} reaches into the region", r.label, if z.net.is_empty() { "an unassigned" } else { z.net.as_str() })); } } }@@ -222,4 +258,27 @@ mod tests { assert!(!inside(x, y), "a via inside U9's keepout at ({x:.2}, {y:.2})"); } }++ #[test]+ fn four_layer_inner_plane_under_accepts_in1_and_catches_inner_tracks_and_piercing_vias() {+ let pcb = concat!(+ "(kicad_pcb (version 20241229) (generator \"t\") (general (thickness 1.6)) ",+ "(layers (0 \"F.Cu\" signal) (4 \"In1.Cu\" signal) (6 \"In2.Cu\" signal) (2 \"B.Cu\" signal) (25 \"Edge.Cuts\" user)) ",+ "(net 0 \"\") (net 1 \"A\") (net 2 \"GND\") ",+ "(footprint \"T:J1\" (layer \"F.Cu\") (at 2 5) (property \"Reference\" \"J1\") (pad \"1\" smd rect (at 0 0) (size 1 1) (layers \"F.Cu\") (net 1 \"A\"))) ",+ "(footprint \"T:J2\" (layer \"F.Cu\") (at 18 5) (property \"Reference\" \"J2\") (pad \"1\" smd rect (at 0 0) (size 1 1) (layers \"F.Cu\") (net 1 \"A\"))) ",+ "(segment (start 2 5) (end 18 5) (width 0.25) (layer \"F.Cu\") (net 1)) ",+ "(segment (start 7 5) (end 13 5) (width 0.25) (layer \"In1.Cu\") (net 1)) ",+ "(via (at 10 6) (size 0.6) (drill 0.3) (layers \"F.Cu\" \"B.Cu\") (net 1)) ",+ "(gr_rect (start 0 0) (end 20 10) (layer \"Edge.Cuts\") (stroke (width 0.1) (type solid))))"+ );+ let b = Board::from_text("4l.kicad_pcb", pcb.to_string()).unwrap();+ let regs = regions(&b, &entry(serde_json::json!([{"layer": "In1.Cu", "net": "GND", "polygon": [[8, 3], [12, 3], [12, 7], [8, 7]]}]))).unwrap();+ assert_eq!(regs.len(), 1);+ assert_eq!(layer_name(regs[0].layer), "In1.Cu");+ let found = issues(&b, ®s);+ assert_eq!(found.len(), 2, "{found:?}");+ assert!(found[0].contains("A track on In1.Cu"), "{found:?}");+ assert!(found[1].contains("A via at (10.00, 6.00)"), "{found:?}");+ } }
docs/impedance.md+14−6@@ -15,9 +15,14 @@ Issue #52. A net or a differential pair can carry an impedance target. The binar - `tolerancePercent`: default 10. - `gapMm` (a pair): solve the width for this gap. `widthMm`: solve the gap (a pair) or use this width (a single net). - `layer`: hold the target to one layer.-- `maxSkewMm`: the length mismatch a pair may keep, default 0.5 mm. Set it from the interface's skew budget.+- `maxSkewMm`: the total end-to-end length mismatch a pair may keep, default 0.5 mm. Set it from the interface's skew budget.+- `maxPhaseSkewMm`: maximum intra-pair phase skew allowed anywhere along the coupled run (catches skew introduced at one breakout and compensated at the far end). Defaults to the larger of `maxSkewMm` and the solved coupled pitch; set explicitly (for example 0.5 mm) for strict phase budgets.+- `maxPhaseSkewRunMm`: optional length (mm) a local phase mismatch above `maxPhaseSkewMm` may persist before failing (default 2.0 mm). - `maxUncontrolledMm`: the length of each net that may miss the target, default 3 mm. It covers pad breakouts and the bends of a pair. - `maxWidthMm`: refuse a layer that needs a wider trace.+- `allowLayerChange`: allow a pair to transition layers through a symmetric via pair instead of refusing all vias (default false). When true, `viaPairMaxPitchMm` (default 2.5 mm), `viaPairMaxSkewMm` (default 0.5 mm), and `stitchViaRadiusMm` (default 2.5 mm, requiring at least one GND stitching via near the transition) are checked.+- `maxStubMm`: maximum stub length (mm) allowed at an intermediate pad such as an ESD/TVS diode (default 0.5 mm). Inline flow-through routing has 0 mm stub; T-branch routing fails.+- `maxGapJumpPercent`: maximum step change in coupled gap along a pair (default 50%). - `coplanarGapMm`: a ground pour on the same outer layer this far (mm) from the copper, on both sides of a single trace and on the outer side of each net of a pair (grounded coplanar waveguide, below). `coplanarNet` names the pour's net (default the spec's `coplanarGround.net`, else `GND`). `"coplanarGround": {"net": "GND", "gapMm": 0.2}` at the top of the spec gives every target without its own `coplanarGapMm` that pour (adom-fields' `impedance` map entries too). Both apply to outer layers only: an inner-layer row stays stripline and says the pour is not modelled there. The gap is held to the fab minimum space like a pair gap (below).@@ -27,8 +32,11 @@ adom-fields' own `impedance` map (`{"RF_OUT": 50, "USB_DP/USB_DN": 90}`) is read ## The stackup - Dielectric thickness per gap between copper layers: spec `stackupMm` (one value per gap; three values on a two-layer board are summed, as adom-fields does), else the board's saved physical stackup (KiCad Board Setup > Physical Stackup).-- Permittivity: the board stackup's `epsilon_r` (thickness-weighted per gap), else spec `epsilonR`.+- Permittivity: spec `epsilonRByGap` (per dielectric gap), else the board stackup's `epsilon_r` (thickness-weighted per gap), else spec `epsilonR`. - Copper: spec `copperUmByLayer`, else `copperUm`, else the board stackup's copper thickness, else 35 um (said in the output).+- Solder mask on outer layers: set `"solderMask": true` or `"solderMask": {"thicknessMm": 0.025, "epsilonR": 3.8}` to solve coated outer copper directly (binding a published stackup preset sets this automatically). Omit `solderMask` to keep bare-copper solving while still reporting the expected solder-mask shift beside each outer row, or set `"solderMask": false` (or `"rf": {"noSolderMask": true}`) to disable it explicitly.+- Published fab stackup presets: `adom-aiflow impedance stackups` lists the built-in published stackups (`JLC04161H-7628`, `JLC04161H-3313`, `JLC06161H-3313`, `JLC02161H`). Bind a preset into both `spec.json` and the KiCad board `(setup (stackup ...))` with `adom-aiflow rules use --profile <fab> --layers <n> --stackup <id>` or offline with `adom-aiflow rules stackup --stackup <id>`. Private fabricator stackups (such as 3rdPartyFab) are not shipped as generic presets and stay `assumed` unless supplied in the spec or confirmed with the fab.+- Fabricator confirmation state: `spec.fab.stackupStatus` tracks `"assumed"`, `"published-profile"`, or `"fab-confirmed"`. When a board has controlled-impedance targets and status is still `"assumed"`, `finish` surfaces an advisory to bind a published preset or confirm the stackup with the fab. On `export`, AI Flow writes `manufacturing/impedance-stackup.md` and `manufacturing/impedance-stackup.json` with the stackup table, per-target widths/gaps, and fabricator adjustment notes. - With no dielectric thickness or no permittivity the command refuses and names the key to add. Nothing is guessed. Outer layers are microstrip over the adjacent copper layer. Inner layers are stripline between the two adjacent layers (offset stripline when the dielectrics differ). The adjacent layers are taken to be solid reference planes under the trace. Keep them so.@@ -69,7 +77,7 @@ On an outer layer a pair's gap is chosen so its centre pitch sits on the grid ro ## The formulas -All quasi-static and lossless, without solder mask:+All quasi-static and lossless, with outer-layer solder mask correction (`solderMask: true` or `{"thicknessMm": 0.025, "epsilonR": 3.8}`, automatically enabled by published stackup presets; lowers single outer microstrips by roughly 4 to 6 % and tightly coupled outer pairs by up to 10 %, matching `adom-fields --with si` within 2 % on JLC 7628, JLC 3313, and 2-layer FR4 stackups; bare copper values and expected mask shifts are reported in `impedance table` and JSON): | Structure | Formula | Source | |---|---|---|@@ -118,7 +126,7 @@ Also checked: Wheeler at zero thickness against Cohn's exact stripline (under 0. Refused because the error grows: coupled microstrip with s/h under 0.2 (5.7 % at s/h 0.125) and offset stripline past 3:1 (7 % at 5:1, which is JLC's four-layer In1.Cu and In2.Cu; route those inner layers with the fab's calculator). -Not modelled: solder mask (it lowers an outer trace by roughly 1 to 3 %; it also fills a coplanar gap, which lowers that line more), etch trapezoid, glass weave, Dk tolerance and frequency dependence, plane voids, and for a coplanar line the stitching vias (taken as an unbroken connection to the plane) and a pour narrower than about the gap. This is a routing screen. For an impedance-controlled order the fab's own stackup calculation is the reference.+Not modelled: etch trapezoid, glass weave, Dk tolerance and frequency dependence, plane voids (checked separately by reference-plane continuity), and for a coplanar line the stitching vias (taken as an unbroken connection to the plane) and a pour narrower than about the gap. Solder mask is modelled as a uniform conformal dielectric coat over outer copper when `spec.solderMask` is enabled (automatically set by published stackup presets; bare-copper specs report the expected mask shift beside each outer row). For an impedance-controlled order the fab's own stackup calculation is still the final production reference. ## `route` @@ -144,12 +152,12 @@ Judges every target on the landed copper (the plan's for a net not landed yet). - A pair: a sample is controlled when a parallel equal-width partner beside it at its real gap gives the target within tolerance. - A coplanar target on an outer layer where its ground net has a filled zone: the pour is measured. From each sample the ground copper (the net's zone fills, pads and tracks on that layer) is looked for square to the line, on both sides of a single trace and on the outer side of each net of a pair, as far as the larger of three gaps and the dielectric height. The sample is controlled only when the gap found there gives the target within tolerance (each side on its own, as if both had it); no ground within reach is uncontrolled length. The result carries `coplanar.measuredOn`, `measuredGapMm` and `withoutGroundMm`. - A coplanar target where the net has no filled zone on that layer (not poured yet, or a plan's copper): judged at the target's gap, and the line and `coplanar.note` say the pour is ASSUMED, not measured, and to pour it and check again. `finish` runs the check on the live board, where the pour is normally filled and so measured.-- The target passes when each net's uncontrolled length is at most `maxUncontrolledMm`, a pair's skew is at most `maxSkewMm`, and a pair stays on one layer without vias.+- The target passes when each net's uncontrolled length is at most `maxUncontrolledMm`, a pair's total skew is at most `maxSkewMm`, intra-pair phase skew along the coupled run stays within `maxPhaseSkewMm`, local bends stay on 45-degree increments without acute corners or sudden gap jumps, intermediate pads (such as ESD/TVS diodes) stay inline with stub length at most `maxStubMm`, and a pair either stays on one layer without vias or (when `allowLayerChange: true`) transitions through symmetric via pairs accompanied by a nearby GND stitching via. With a same-input Adom Fields report (`<run>/fields/fields.json` or `--fields`, its `inputIdentity` the saved board and spec), it compares: - **Signals** (`signals.differentialPairs`, Fields 0.4+): its estimate of each pair. Its formula is the IPC-2141 approximation and it judges every sample, pad breakouts included; any sample without a parallel equal-width partner (a fan-out, a bend) makes it refuse to estimate. A refusal is reported, never replaced by the closed form.-- **The 2-D cross-section solve** (`--with si`, `review.impedance`): Zdiff of each pair at its median gap, with solder mask. Fields finds pairs by name (`_P`/`_N`, `+`/`-`, `DP`/`DM`, `P`/`N`); `USB_DP`/`USB_DN` is not matched (it tries `USB_DM`), so such a pair has no cross-section row.+- **The 2-D cross-section solve** (`--with si`, `review.impedance`): Zdiff of each pair at its median gap, with solder mask. Fields finds pairs by name (`_P`/`_N`, `+`/`-`, `DP`/`DM`, `P`/`N`); when a pair uses names like `USB_DP`/`USB_DN` that Fields does not auto-pair, `analyze impedance` reports the explicit pair handoff (`fieldsHandoff`) and falls back to reporting both individual nets' 2-D single-ended `z0` values from `review.impedance` instead of dropping the pair silently. A Fields value outside the target's tolerance fails the target too, except for a coplanar target: Fields' Signals and its cross-section solve model a microstrip without the same-layer pour, so for those its values are reported, not compared, and no Signals entry is suggested. When no Signals entry exists, the hint prints the `signals.differentialPairs` entry to add (layer, reference layer and net, dielectricMm and epsilonR from this stackup).
docs/release-0.2.99.mdadded+21@@ -0,0 +1,21 @@+# AI Flow 0.2.99++- **Bottom-side parts** (#241, Justin).+ - `land route` names the start layer the gate checked on every path that starts at, or runs first through, a+ bottom part's through-hole pad. With no layer named, the KiCad bridge starts such a trace on the part's side+ (B.Cu) while the gate checked it on F.Cu, so traces the gate passed were refused live (`tracks_crossing`).+ Checked live: KiCad Bridge 1.1.6 starts an unnamed path from a flipped header's pad on B.Cu.+ - `place land` on KiCad compares each moved part's side with the live board first. A part flipped on the+ desktop and never adopted is named and nothing lands: the run's copy would place it mirrored to what KiCad+ does. (The offline transform itself matches KiCad: a file-mode flip, then a move at rotation 90, gives the same+ courtyard live and offline.)+- **Test plan net names** (#242, RobInMaine). `testplan check` matches "GND" in tests.json to the design's "/GND"+ (a hierarchical schematic's names), on the board and in the netlist, and reports the design's name. An exact+ name still wins; the ground tether check reads "/GND" as GND too.+- **Differential pairs and stackups** (Drew Owens, PR #122, issues #212 and #213): intra-pair phase, angle and gap+ checks, symmetric via transitions with ground stitching, inline ESD breakouts, pair metadata for adom-fields;+ published fab stackup presets bound into spec and board (`rules stackup`), solder-mask impedance, the+ fabricator confirmation state, and `impedance-stackup.md/.json` on export.+- **Signal integrity, EMC and power** (Drew Owens, PR #124, issues #214 and #215): reference-plane coverage,+ return-path stitching vias and 3W crosstalk checks, `planeUnder` on inner layers, Fields SI, noise, EMC, ESD+ and PDN turned on when the board calls for them with the readiness report, USB VBUS inrush and rail load budget.
package.json+1−1@@ -1,7 +1,7 @@ { "slug": "adom-aiflow", "type": "app",- "version": "0.2.98",+ "version": "0.2.99", "title": "AI Flow", "description": "Adom's AI Flow: a tool to help the AI follow all of the steps it takes to build a board. One Rust binary with a crate per step (placement helpers, a grid router with Kelvin taps, pours with keepouts, KiCad's DRC gate, live landing through the KiCad Bridge, copper measurement, current and thermal analysis) and a finish line that refuses an unfinished board. Every command answers with hints for the AI; every turn, its thinking time and every rework loop go into run.jsonl, so Claude, Codex and any other engine are compared on the same flow. KiCad, Fusion 360 and Altium Designer today (the same steps and gates through each tool's bridge); Adom's own web apps next.", "summary": "Adom's AI Flow: a tool to help the AI follow all of the steps it takes to build a board. The AI thinks its way from placement through routing, pours, current and thermal analysis to a delivered video; the binary does the fast, deterministic parts of every step, hands back hints, and keeps a ledger of every turn, every return to an earlier step, and the clock from the prompt to done.",
page.json+1−1@@ -1,7 +1,7 @@ { "slug": "adom-aiflow", "type": "app",- "version": "0.2.98",+ "version": "0.2.99", "title": "AI Flow", "description": "Adom's AI Flow: a tool to help the AI follow all of the steps it takes to build a board. One Rust binary with a crate per step (placement helpers, a grid router with Kelvin taps, pours with keepouts, KiCad's DRC gate, live landing through the KiCad Bridge, copper measurement, current and thermal analysis) and a finish line that refuses an unfinished board. Every command answers with hints for the AI; every turn, its thinking time and every rework loop go into run.jsonl, so Claude, Codex and any other engine are compared on the same flow. KiCad, Fusion 360 and Altium Designer today (the same steps and gates through each tool's bridge); Adom's own web apps next.", "summary": "Adom's AI Flow: a tool to help the AI follow all of the steps it takes to build a board. The AI thinks its way from placement through routing, pours, current and thermal analysis to a delivered video; the binary does the fast, deterministic parts of every step, hands back hints, and keeps a ledger of every turn, every return to an earlier step, and the clock from the prompt to done.",
skills/adom-aiflow/SKILL.md+1−1@@ -75,7 +75,7 @@ The flow is a file, `flows/board.json`: the steps in order (intake, rules, test- ### High-speed boards: your own router, inside the flow -Impedance targets go in the spec before routing: `"impedanceTargets": {"USB_D": {"pair": ["USB_DP", "USB_DN"], "targetDiffOhms": 90}, "RF": {"net": "RF_OUT", "targetOhms": 50}}` (`tolerancePercent` 10, `gapMm`, `widthMm`, `layer`, `maxSkewMm` 0.5, `maxUncontrolledMm` 3 optional), with the stackup from spec `stackupMm` and `epsilonR` or the board's saved physical stackup. `impedance table` prints the width (and pair gap) per copper layer from closed-form formulas (Hammerstad-Jensen, Wheeler, Cohn, Garg-Bahl; within 0.2 to 3.4 % of a 2-D field solve, no solder mask) and refuses a layer the target cannot reach within the fab minimums. On a two-layer board, where a microstrip is wide (90 ohm over 1.51 mm FR4 is 1.38 mm), a ground pour on the same layer beside the line (`coplanarGapMm` on the target, or spec `"coplanarGround": {"net": "GND", "gapMm": 0.2}`) makes the outer rows grounded coplanar, a few tenths of a millimetre wide; the table suggests it when a microstrip width misses the pins, the pours stage must pour it at that clearance, and `analyze impedance` measures it once filled (and says when it is only assumed). `route` then sizes those nets, holds each to one outer layer and routes a pair's second net along the first at the solved pitch; it prints the coupling it achieved and names any pair it could not keep together for `take route=ai`. A target wider than its pins (90 ohm on a 2-layer 1.6 mm board is 1.38 mm) is routed at the rule width and widened back to the target where it clears, narrow only at the necks (set `maxUncontrolledMm` for a fine-pitch fan-out), and a pair's skew over `maxSkewMm` is tuned with bumps on its shorter net (docs/impedance.md). `analyze impedance` judges the landed copper (and a same-input Fields Signals or `--with si` solve beside it); `finish` requires it. docs/impedance.md has the formulas, their measured accuracy and what the router really does.+Impedance targets go in the spec before routing: `"impedanceTargets": {"USB_D": {"pair": ["USB_DP", "USB_DN"], "targetDiffOhms": 90}, "RF": {"net": "RF_OUT", "targetOhms": 50}}` (`tolerancePercent` 10, `gapMm`, `widthMm`, `layer`, `maxSkewMm` 0.5, `maxPhaseSkewMm`, `maxUncontrolledMm` 3, `allowLayerChange`, `maxStubMm` 0.5 optional). Bind a published fab stackup into both the spec and the board with `rules use --profile <fab> --layers <n> --stackup <id>` or `rules stackup --stackup <id>` (`impedance stackups` lists published presets such as `JLC04161H-7628`, `JLC04161H-3313`, `JLC06161H-3313`, `JLC02161H`), or supply `stackupMm`, `epsilonR`/`epsilonRByGap`, and `solderMask`. `impedance table` prints the width (and pair gap) per copper layer from closed-form formulas with outer-layer solder mask accounting (automatically enabled by stackup presets or `solderMask: true`, matching `adom-fields --with si` within 2 %; bare-copper specs report the expected mask shift beside each outer row) and refuses a layer the target cannot reach within the fab minimums. On a two-layer board, where a microstrip is wide, a ground pour on the same layer beside the line (`coplanarGapMm` on the target, or spec `"coplanarGround": {"net": "GND", "gapMm": 0.2}`) makes the outer rows grounded coplanar, a few tenths of a millimetre wide; the table suggests it when a microstrip width misses the pins, the pours stage must pour it at that clearance, and `analyze impedance` measures it once filled (and says when it is only assumed). `route` then sizes those nets, holds each to one outer layer and routes a pair's second net along the first at the solved pitch; it prints the coupling it achieved and names any pair it could not keep together for `take route=ai`. A target wider than its pins is routed at the rule width and widened back to the target where it clears, narrow only at the necks (set `maxUncontrolledMm` for a fine-pitch fan-out), and a pair's skew over `maxSkewMm` is tuned with bumps on its shorter net (docs/impedance.md). `analyze impedance` judges the landed copper, checking intra-pair phase matching along the coupled run, 45-degree angle and gap continuity, inline ESD/TVS pad stubs, symmetric via transitions with GND stitching vias when `allowLayerChange` is true, and a same-input Fields Signals or `--with si` solve (with explicit pair handoff and per-net fallback for names like `USB_DP`/`USB_DN`); `finish` requires it and advises when `fab.stackupStatus` is still `assumed`, and `export` writes `manufacturing/impedance-stackup.md` and `.json`. docs/impedance.md has the formulas, their measured accuracy and what the router really does. A simple pair (one USB 2 pair, a 50 ohm feed) can go through `route` this way. A board with several pairs, length-matched lane groups or layer changes (PCIe, OCuLink, USB 3, Ethernet), or a pair `route` flagged, is beyond the grid router, so you route it yourself, but the work still happens inside the flow. Declare each step as you reach it (`step rules`, `step components`, ... `step routing`); your own schematic, placement or router scripts do the step's work, they do not replace the step. For routing:
skills/aiflow-circuit-design/SKILL.md+1@@ -60,6 +60,7 @@ The same search applies to UVLO dividers, LED resistors and anything else with a - **Voltage.** Ceramics at least 1.5 to 2x the working voltage; electrolytics above the maximum input including hot-plug ringing. - **Absolute maximums.** Compute the worst-case voltage at every limited pin (EN at the maximum input was 2.09 V against 5.5 V here; the script also printed it at 28 V). - **Dissipation, physically.** I squared R at the hot on-resistance over the conduction duty, plus a switching estimate, plus gate drive. The same watts go into the aiflow spec's `hot` entries for `analyze thermal`, with the arithmetic in `hotNote`.+- **USB VBUS inrush and rail load budget.** USB 2.0 limits direct VBUS capacitance to 10 uF without a soft-start or load-switch IC (`spec.inrushLimiter`). Sum both nominal and DC-bias-derated capacitance on VBUS, and verify that `spec.loads` plus any auxiliary rail draws (`spec.auxiliaryLoads`, such as RGB LEDs or peripherals) stay within `requirements.usb.maxCurrentA` / `requirements.power.maxCurrentA`. `adom-aiflow analyze si` and `finish` check both automatically. ## 4. Reading a part correctly (the mistakes this catches)
skills/aiflow-power-layout/SKILL.md+5−2@@ -46,7 +46,7 @@ Without a layer policy the grid router treats B.Cu as free space: on the buck it "planeUnder": [{"layer": "B.Cu", "net": "GND", "around": ["U1", "C2", "C3", "C4"], "margin": 1.0}] ``` -`around` is the pad box of the listed parts or pads grown by `margin` (default 1.0 mm); `polygon: [[x, y], ...]` gives the region exactly. The router treats each region as a keepout for every other net on that layer and for other nets' vias, and says so in its hints; the gate fails on any other-net track, via or zone inside a region (`planeUnderIssues` in gate.json) and `finish` refuses until it is clear.+`around` is the pad box of the listed parts or pads grown by `margin` (default 1.0 mm); `polygon: [[x, y], ...]` gives the region exactly. `planeUnder` accepts any copper layer on the board (`F.Cu`, `B.Cu`, `In1.Cu`, `In2.Cu`, ...): on outer layers it keeps foreign tracks and vias out, and on inner planes it keeps foreign inner tracks, zones, and piercing vias out so reference planes stay unbroken on 4+ layer boards. The gate fails on any other-net track, via or zone inside a region (`planeUnderIssues` in gate.json) and `finish` refuses until it is clear. A region is a hard wall: a pin of another net inside it (the IC's EN or FB pin under U1) can only leave on the other layer, and a Kelvin sense may find no path. When `route` closes short with a region in place, shrink the margin, list fewer parts, or draw a polygon that leaves those pins a way out, before taking the nets by hand. If you do route by hand (`take route=ai`, `step routing --back --why "..."`): FB on F.Cu inside the quiet side, the VOUT sense along an edge, not across the plane, and land hand routes one at a time with a dry run first (`tools/route_live.py routes.json` calls `kicad_route_net` with `dryRun`, commits only on 0 DRC errors, and chains `expectedRevision` from each reply). After `adopt-board` of the reworked board, `route` keeps that copper and plans only what is still open (an empty plan when nothing is), and the gate checks the regions on it. Filled zones count as that copper: a net the board's pours already join is not tracked (refill unfilled zones first; `route` warns when it tracks a net that has one). A pad on its plane's own layer (`planes: {"GND": "F.Cu"}`, an F.Cu pad) gets no via. @@ -65,10 +65,13 @@ Kelvin keepouts follow the tap's own layer (both layers only at its vias) and st `analyze current` is a screen; the neck is found by a solve: ```bash-adom-fields analyze --board <current saved board> --spec aiflow/spec.json --out <run>/fields+adom-fields analyze --board <current saved board> --spec aiflow/spec.json --with si,noise,emc,esd,pdn --out <run>/fields adom-aiflow --ai-thread "<t>" analyze current --fields <run>/fields/fields.json+adom-aiflow --ai-thread "<t>" analyze si --fields <run>/fields/fields.json ``` +`analyze si` checks real reference-plane copper coverage beneath controlled-impedance traces (>= 90% continuous copper sampled every 0.25 mm, no plane split > 1.0 mm; also enforced by `analyze impedance` once zones are filled), return-path GND stitching vias within 2.5 mm of critical signal layer transitions, 3W/3H parallel crosstalk against sensitive/analog nets (> 10 mm parallel run), USB VBUS inrush capacitance (<= 10 uF without an inrush limiter), and rail load budgets. `analyze` auto-selects `--with si,noise,emc,esd,pdn` from the board and spec (and notes auto-detected external edge connectors to list in `spec.external`), and `finish` runs `adom-fields report` into `design-review/readiness.md` and surfaces unrun triggered modules, SI/noise/EMC/ESD/PDN findings, compliance `toSixDb` fixes, and high-impact `review.inputs` assumptions.+ Two things changed in 0.2.23 (issue #107). A pour passes the width screen only when it covers the net's narrow tracks on their layer, or one pour reaches every terminal of the net: a small patch beside the neck no longer passes, and a sense tap to a part with no load on its other side (feedback divider, bootstrap cap, test point) needs no cover. And the passed same-input solve judges a net that failed only the width approximation by the solved rise at its narrowest neck (`judgedBy: fields-solve`); that rise includes the heat of nearby parts, so a neck beside a hot IC may still fail it. Read `docs/branch-current-screen.md`. On a converter the solve must model it: `fields.json` `review.converter` carries the hot loop, the emissions margin and the ripple. When it is null (no switching node, frequency, inductor, rails or output load) or `review.pdn.rails` checked no rail, `tour fields` and `finish` refuse; fix the spec's `voltages`/`sources`/`switching` (and `loads`) and solve again.
tests/diff-pair-stackup-workflow.pyadded+367@@ -0,0 +1,367 @@+"""Differential pair SI and controlled-impedance stackup end to end (issues #212, #213):+- Published fab stackup presets (rules stackup, impedance stackups), spec + KiCad stackup writing+- Coated solder-mask solving cross-checked against real adom-fields --with si (JLC 7628, 3313, 2L)+- USB 2.0 90 ohm, Ethernet 100 ohm, and 2-layer coplanar targets+- Negative -> positive gates: intra-pair phase skew, local angle/gap discontinuities, symmetric via+ transitions with GND stitching via, inline ESD vs T-stub breakout+- Explicit pair handoff and per-net 2-D fallback for USB_DP/USB_DN with adom-fields --with si+- Export generates manufacturing/impedance-stackup.md and .json+Usage: python3 tests/diff-pair-stackup-workflow.py <adom-aiflow binary>"""+import json, os, pathlib, shutil, subprocess, sys, tempfile++binary = str(pathlib.Path(sys.argv[1]).resolve())+++def make_board_4l(path, net_p="USB_DP", net_n="USB_DN", segs="", vias="", extra_fps="", stackup=""):+ gnd_zone = (+ '(zone (net 3) (net_name "GND") (layer "In1.Cu") (tstamp "00000000-0000-0000-0000-000000000101") '+ '(hatch edge 0.5) (connect_pads (clearance 0.2)) (min_thickness 0.2) '+ '(fill yes (thermal_gap 0.3) (thermal_bridge_width 0.3)) '+ '(polygon (pts (xy 0.5 0.5) (xy 49.5 0.5) (xy 49.5 29.5) (xy 0.5 29.5))) '+ '(filled_polygon (layer "In1.Cu") (pts (xy 0.5 0.5) (xy 49.5 0.5) (xy 49.5 29.5) (xy 0.5 29.5))))'+ )+ fp_j1 = (+ f'(footprint "T:J1" (layer "F.Cu") (at 5 15) (property "Reference" "J1") '+ f'(pad "1" smd rect (at 0 -0.275) (size 0.8 0.3) (layers "F.Cu") (net 1 "{net_p}")) '+ f'(pad "2" smd rect (at 0 0.275) (size 0.8 0.3) (layers "F.Cu") (net 2 "{net_n}")) '+ f'(pad "3" thru_hole circle (at -1.5 0) (size 0.8 0.8) (drill 0.4) (layers "*.Cu") (net 3 "GND")))'+ )+ fp_u1 = (+ f'(footprint "T:U1" (layer "F.Cu") (at 45 15) (property "Reference" "U1") '+ f'(pad "1" smd rect (at 0 -0.275) (size 0.8 0.3) (layers "F.Cu") (net 1 "{net_p}")) '+ f'(pad "2" smd rect (at 0 0.275) (size 0.8 0.3) (layers "F.Cu") (net 2 "{net_n}")) '+ f'(pad "3" thru_hole circle (at 1.5 0) (size 0.8 0.8) (drill 0.4) (layers "*.Cu") (net 3 "GND")))'+ )+ path.write_text(+ '(kicad_pcb (version 20241229) (generator "test") (general (thickness 1.6)) '+ '(layers (0 "F.Cu" signal) (4 "In1.Cu" signal) (6 "In2.Cu" signal) (2 "B.Cu" signal) (25 "Edge.Cuts" user)) '+ f'{stackup} '+ f'(net 0 "") (net 1 "{net_p}") (net 2 "{net_n}") (net 3 "GND") '+ f'{fp_j1} {fp_u1} {extra_fps} {segs} {vias} {gnd_zone} '+ '(gr_rect (start 0 0) (end 50 30) (layer "Edge.Cuts") (stroke (width 0.1) (type solid))))'+ )+++def make_board_2l(path, net_p="USB_D+", net_n="USB_D-"):+ fp_j1 = (+ f'(footprint "T:J1" (layer "F.Cu") (at 5 15) (property "Reference" "J1") '+ f'(pad "1" smd rect (at 0 -0.4) (size 0.8 0.4) (layers "F.Cu") (net 1 "{net_p}")) '+ f'(pad "2" smd rect (at 0 0.4) (size 0.8 0.4) (layers "F.Cu") (net 2 "{net_n}")) '+ f'(pad "3" thru_hole circle (at -1.5 0) (size 0.8 0.8) (drill 0.4) (layers "*.Cu") (net 3 "GND")))'+ )+ fp_u1 = (+ f'(footprint "T:U1" (layer "F.Cu") (at 45 15) (property "Reference" "U1") '+ f'(pad "1" smd rect (at 0 -0.4) (size 0.8 0.4) (layers "F.Cu") (net 1 "{net_p}")) '+ f'(pad "2" smd rect (at 0 0.4) (size 0.8 0.4) (layers "F.Cu") (net 2 "{net_n}")) '+ f'(pad "3" thru_hole circle (at 1.5 0) (size 0.8 0.8) (drill 0.4) (layers "*.Cu") (net 3 "GND")))'+ )+ 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)) '+ f'(net 0 "") (net 1 "{net_p}") (net 2 "{net_n}") (net 3 "GND") '+ f'{fp_j1} {fp_u1} '+ '(gr_rect (start 0 0) (end 50 30) (layer "Edge.Cuts") (stroke (width 0.1) (type solid))))'+ )+++def seg(x1, y1, x2, y2, w, layer, net):+ return f'(segment (start {x1:.4f} {y1:.4f}) (end {x2:.4f} {y2:.4f}) (width {w:.4f}) (layer "{layer}") (net {net}))'+++def via(x, y, net, size=0.6, drill=0.3):+ return f'(via (at {x:.4f} {y:.4f}) (size {size:.4f}) (drill {drill:.4f}) (layers "F.Cu" "B.Cu") (net {net}))'+++def fanout_pair_segs(x0, x1, pad_yp, pad_yn, yp, yn, w, layer="F.Cu"):+ """Route a clean 45-degree fan-out from pads at (x0, pad_y) to coupled run at (yp, yn) and back to x1."""+ dy = abs(yp - pad_yp)+ parts = []+ if dy > 1e-4:+ parts.extend([+ seg(x0, pad_yp, x0 + dy, yp, w, layer, 1),+ seg(x0 + dy, yp, x1 - dy, yp, w, layer, 1),+ seg(x1 - dy, yp, x1, pad_yp, w, layer, 1),+ seg(x0, pad_yn, x0 + dy, yn, w, layer, 2),+ seg(x0 + dy, yn, x1 - dy, yn, w, layer, 2),+ seg(x1 - dy, yn, x1, pad_yn, w, layer, 2),+ ])+ else:+ parts.extend([+ seg(x0, yp, x1, yp, w, layer, 1),+ seg(x0, yn, x1, yn, w, layer, 2),+ ])+ return ' '.join(parts)+++with tempfile.TemporaryDirectory(prefix='aiflow-dp-stackup-') as td:+ p = pathlib.Path(td)+ env = dict(os.environ, AIFLOW_DASHBOARD='off', XDG_CONFIG_HOME=str(p / 'xdg'))++ def call(run, *args):+ return subprocess.run(+ [binary, '--run', str(run), '--ai-thread', 'dp-stackup-test', *args],+ env=env, capture_output=True, text=True, timeout=120+ )++ # 1. Published stackup preset listing (only real published presets; no private fab generic presets)+ r = call(p / 'none', 'impedance', 'stackups')+ assert r.returncode == 0, r.stdout + r.stderr+ for preset_id in ['JLC04161H-7628', 'JLC04161H-3313', 'JLC06161H-3313', 'JLC02161H']:+ assert preset_id in r.stdout, f'missing preset {preset_id}: {r.stdout}'+ assert '3rdPartyFab-4L' not in r.stdout and '3rdPartyFab-2L' not in r.stdout, r.stdout+ print(' [1/9] impedance stackups lists the 4 published JLCPCB presets (no generic 3rdPartyFab presets)')++ # 2. rules stackup binds JLC04161H-7628 into spec.json and .kicad_pcb+ b4 = p / 'usb4l.kicad_pcb'+ make_board_4l(b4, 'USB_DP', 'USB_DN')+ spec4_path = p / 'spec4.json'+ spec4_path.write_text(json.dumps({+ "clearance": 0.127, "minTrackWidth": 0.127, "track": 0.2,+ "impedanceTargets": {+ "USB": {"pair": ["USB_DP", "USB_DN"], "targetDiffOhms": 90, "gapMm": 0.2},+ "ETH": {"pair": ["USB_DP", "USB_DN"], "targetDiffOhms": 100}+ }+ }))+ # Remove duplicate net before running table; test USB + ETH separately below+ spec4_path.write_text(json.dumps({+ "clearance": 0.127, "minTrackWidth": 0.127, "track": 0.2,+ "impedanceTargets": {+ "USB": {"pair": ["USB_DP", "USB_DN"], "targetDiffOhms": 90, "gapMm": 0.2, "maxPhaseSkewMm": 0.5}+ }+ }))+ r = call(p / 'none', 'rules', 'stackup', '--stackup', 'JLC04161H-7628', '--spec', str(spec4_path), '--board', str(b4))+ assert r.returncode == 0, r.stdout + r.stderr+ spec4 = json.loads(spec4_path.read_text())+ assert spec4['fab']['stackupId'] == 'JLC04161H-7628', spec4['fab']+ assert spec4['fab']['stackupStatus'] == 'published-profile', spec4['fab']+ assert spec4['stackupMm'] == [0.2104, 1.065, 0.2104], spec4['stackupMm']+ assert spec4['solderMask']['thicknessMm'] == 0.025, spec4['solderMask']+ assert '(stackup' in b4.read_text() and 'F.Mask' in b4.read_text()+ print(' [2/9] rules stackup writes JLC04161H-7628 to spec.json and .kicad_pcb')++ # 3. Impedance table for USB 90 ohm (7628 + 3313), Ethernet 100 ohm, and 2-layer JLC02161H coplanar+ r = call(p / 'none', 'impedance', 'table', '--board', str(b4), '--spec', str(spec4_path), '--json')+ assert r.returncode == 0, r.stdout + r.stderr+ doc = json.loads(r.stdout[:r.stdout.index('\nOK: ')])+ f_row = [row for row in doc['rows'] if row['layer'] == 'F.Cu'][0]+ assert f_row['ok'] and abs(f_row['ohms'] - 90.0) < 0.5, f_row+ w_usb = f_row['widthMm']+ g_usb = f_row['gapMm']+ # With solder mask, bare impedance should be noticeably higher (~5-9%) than coated 90 ohm+ assert f_row['bareOhms'] > f_row['ohms'] + 3.0, f_row++ # Ethernet 100 ohm on JLC04161H-3313 (JLCPCB 4L supports 0.09 mm / 3.5 mil traces)+ b_eth = p / 'eth4l.kicad_pcb'+ make_board_4l(b_eth, 'ETH_TX_P', 'ETH_TX_N')+ spec_eth = p / 'spec_eth.json'+ spec_eth.write_text(json.dumps({+ "clearance": 0.09, "minTrackWidth": 0.09, "track": 0.2,+ "impedanceTargets": {"ETH_TX": {"pair": ["ETH_TX_P", "ETH_TX_N"], "targetDiffOhms": 100, "gapMm": 0.15}}+ }))+ r = call(p / 'none', 'rules', 'stackup', '--stackup', 'JLC04161H-3313', '--spec', str(spec_eth), '--board', str(b_eth))+ assert r.returncode == 0, r.stdout + r.stderr+ r = call(p / 'none', 'impedance', 'table', '--board', str(b_eth), '--spec', str(spec_eth), '--json')+ assert r.returncode == 0, r.stdout + r.stderr+ eth_f = [row for row in json.loads(r.stdout[:r.stdout.index('\nOK: ')])['rows'] if row['layer'] == 'F.Cu'][0]+ assert eth_f['ok'] and abs(eth_f['ohms'] - 100.0) < 0.5, eth_f++ # 2-layer JLC02161H with grounded coplanar+ b2 = p / 'usb2l.kicad_pcb'+ make_board_2l(b2)+ spec2 = p / 'spec2.json'+ spec2.write_text(json.dumps({+ "clearance": 0.15, "minTrackWidth": 0.15, "track": 0.2,+ "coplanarGround": {"net": "GND", "gapMm": 0.15},+ "impedanceTargets": {"USB": {"pair": ["USB_D+", "USB_D-"], "targetDiffOhms": 90, "gapMm": 0.15}}+ }))+ r = call(p / 'none', 'rules', 'stackup', '--stackup', 'JLC02161H', '--spec', str(spec2), '--board', str(b2))+ assert r.returncode == 0, r.stdout + r.stderr+ r = call(p / 'none', 'impedance', 'table', '--board', str(b2), '--spec', str(spec2), '--json')+ assert r.returncode == 0, r.stdout + r.stderr+ row2 = [row for row in json.loads(r.stdout[:r.stdout.index('\nOK: ')])['rows'] if row['layer'] == 'F.Cu'][0]+ assert row2['ok'] and row2['structure'] == 'grounded coplanar' and abs(row2['ohms'] - 90.0) < 0.5, row2+ print(f' [3/9] solved coated geometries: JLC7628 USB 90R w={w_usb} g={g_usb} (bare {f_row["bareOhms"]}), JLC3313 ETH 100R w={eth_f["widthMm"]} g={eth_f["gapMm"]}, JLC2L CPW w={row2["widthMm"]}')++ # 4. Cross-check coated geometry against real adom-fields --with si + verify USB_DP/USB_DN handoff+ if shutil.which('adom-fields'):+ pitch = w_usb + g_usb+ yp, yn = 15.0 - pitch / 2.0, 15.0 + pitch / 2.0+ # Test Ethernet ETH_TX_P/ETH_TX_N (Fields auto-pairs _P/_N) on JLC3313+ w_e, g_e = eth_f['widthMm'], eth_f['gapMm']+ pe = w_e + g_e+ ye_p, ye_n = 15.0 - pe / 2.0, 15.0 + pe / 2.0+ segs_eth = fanout_pair_segs(5.0, 45.0, 14.725, 15.275, ye_p, ye_n, w_e, 'F.Cu')+ make_board_4l(b_eth, 'ETH_TX_P', 'ETH_TX_N', segs=segs_eth)+ call(p / 'none', 'rules', 'stackup', '--stackup', 'JLC04161H-3313', '--spec', str(spec_eth), '--board', str(b_eth))+ fspec_eth = json.loads(spec_eth.read_text())+ fspec_eth['loads'] = {'GND': {'from': 'J1.3', 'to': 'U1.3', 'amps': 0.1}}+ fspec_eth['impedance'] = {'ETH_TX_P/ETH_TX_N': 100}+ (p / 'fspec_eth.json').write_text(json.dumps(fspec_eth))+ rf = subprocess.run(['adom-fields', 'analyze', '--board', str(b_eth), '--spec', str(p / 'fspec_eth.json'), '--with', 'si', '--out', str(p / 'fields_eth')], env=env, capture_output=True, text=True, timeout=120)+ assert rf.returncode == 0, rf.stdout + rf.stderr+ fj_eth = json.loads((p / 'fields_eth' / 'fields.json').read_text())+ eth_pairs = fj_eth.get('review', {}).get('impedance', {}).get('pairs', [])+ assert eth_pairs, f'expected ETH_TX pair in Fields review.impedance: {fj_eth.get("review", {}).get("impedance")}'+ z_fields = eth_pairs[0]['zdiff']+ err_pct = abs(z_fields - 100.0) / 100.0 * 100.0+ assert err_pct < 2.5, f'coated JLC3313 ETH 100R closed-form vs adom-fields 2-D: z_fields={z_fields} ({err_pct:.2f}%)'++ # Test USB_DP/USB_DN handoff + per-net fallback when Fields skips pairing USB_DP/USB_DN+ segs_usb = fanout_pair_segs(5.0, 45.0, 14.725, 15.275, yp, yn, w_usb, 'F.Cu')+ make_board_4l(b4, 'USB_DP', 'USB_DN', segs=segs_usb)+ call(p / 'none', 'rules', 'stackup', '--stackup', 'JLC04161H-7628', '--spec', str(spec4_path), '--board', str(b4))+ fspec_usb = json.loads(spec4_path.read_text())+ fspec_usb['loads'] = {'GND': {'from': 'J1.3', 'to': 'U1.3', 'amps': 0.1}}+ fspec_usb['impedance'] = {'USB_DP/USB_DN': 90}+ (p / 'fspec_usb.json').write_text(json.dumps(fspec_usb))+ rf = subprocess.run(['adom-fields', 'analyze', '--board', str(b4), '--spec', str(p / 'fspec_usb.json'), '--with', 'si', '--out', str(p / 'fields_usb')], env=env, capture_output=True, text=True, timeout=120)+ assert rf.returncode == 0, rf.stdout + rf.stderr+ run_f = p / 'run-fields-usb'+ assert call(run_f, 'start', '--board', str(b4), '--spec', str(p / 'fspec_usb.json'), '--engine', 'test', '--prompt-time', '2026-11-19T00:00:00Z').returncode == 0+ rc = call(run_f, 'analyze', 'impedance', '--fields', str(p / 'fields_usb' / 'fields.json'))+ assert rc.returncode == 0, rc.stdout + rc.stderr+ o = json.loads((run_f / 'run.json').read_text())['outcomes']['analyze-impedance']+ assert o['fieldsHandoff']['impedance']['USB_DP/USB_DN'] == 90.0, o.get('fieldsHandoff')+ dp0 = o['fieldsHandoff']['signals']['differentialPairs'][0]+ assert dp0['positive'] == 'USB_DP' and dp0['negative'] == 'USB_DN', dp0+ cs_nets = o['results'][0]['fields']['crossSectionNets']+ assert len(cs_nets) == 2 and {x['net'] for x in cs_nets} == {'USB_DP', 'USB_DN'}, cs_nets+ print(f' [4/9] adom-fields 2-D cross-check passed (JLC3313 ETH 100R: Fields={z_fields:.2f} ohm, err={err_pct:.2f}%); USB_DP/USB_DN fallback + handoff verified')+ else:+ print(' [4/8] SKIP adom-fields not on PATH')++ # 5. Negative -> positive: intra-pair phase mismatch (skew=0 end-to-end, 2mm local phase error)+ pitch = w_usb + g_usb+ yp, yn = 15.0 - pitch / 2.0, 15.0 + pitch / 2.0+ dy = abs(yp - 14.725)+ # Positive net detours +2 mm at start (x=7..10); negative net compensates +2 mm at far end (x=40..43)+ segs_phase_bad = ' '.join([+ seg(5.0, 14.725, 5.0 + dy, yp, w_usb, 'F.Cu', 1),+ seg(5.0 + dy, yp, 7.0, yp, w_usb, 'F.Cu', 1),+ seg(7.0, yp, 8.0, yp - 1.0, w_usb, 'F.Cu', 1),+ seg(8.0, yp - 1.0, 9.0, yp - 1.0, w_usb, 'F.Cu', 1),+ seg(9.0, yp - 1.0, 10.0, yp, w_usb, 'F.Cu', 1),+ seg(10.0, yp, 45.0 - dy, yp, w_usb, 'F.Cu', 1),+ seg(45.0 - dy, yp, 45.0, 14.725, w_usb, 'F.Cu', 1),+ seg(5.0, 15.275, 5.0 + dy, yn, w_usb, 'F.Cu', 2),+ seg(5.0 + dy, yn, 40.0, yn, w_usb, 'F.Cu', 2),+ seg(40.0, yn, 41.0, yn + 1.0, w_usb, 'F.Cu', 2),+ seg(41.0, yn + 1.0, 42.0, yn + 1.0, w_usb, 'F.Cu', 2),+ seg(42.0, yn + 1.0, 43.0, yn, w_usb, 'F.Cu', 2),+ seg(43.0, yn, 45.0 - dy, yn, w_usb, 'F.Cu', 2),+ seg(45.0 - dy, yn, 45.0, 15.275, w_usb, 'F.Cu', 2),+ ])+ b_phase = p / 'phase.kicad_pcb'+ make_board_4l(b_phase, 'USB_DP', 'USB_DN', segs=segs_phase_bad)+ call(p / 'none', 'rules', 'stackup', '--stackup', 'JLC04161H-7628', '--spec', str(spec4_path), '--board', str(b_phase))+ r_bad = call(p / 'none', 'impedance', 'check', '--board', str(b_phase), '--spec', str(spec4_path))+ assert r_bad.returncode != 0 and 'phase' in r_bad.stdout.lower(), r_bad.stdout+ # Fix: clean coupled straight run with 45-degree fan-out+ segs_phase_good = fanout_pair_segs(5.0, 45.0, 14.725, 15.275, yp, yn, w_usb, 'F.Cu')+ make_board_4l(b_phase, 'USB_DP', 'USB_DN', segs=segs_phase_good)+ call(p / 'none', 'rules', 'stackup', '--stackup', 'JLC04161H-7628', '--spec', str(spec4_path), '--board', str(b_phase))+ r_good = call(p / 'none', 'impedance', 'check', '--board', str(b_phase), '--spec', str(spec4_path))+ assert r_good.returncode == 0, r_good.stdout+ print(' [5/9] intra-pair phase mismatch caught and fixed case passes')++ # 6. Negative -> positive: local discontinuities (off-45 breakout fails -> 45-deg passes)+ segs_off45 = ' '.join([+ seg(5.0, 14.725, 5.5, yp, w_usb, 'F.Cu', 1),+ seg(5.5, yp, 44.5, yp, w_usb, 'F.Cu', 1),+ seg(44.5, yp, 45.0, 14.725, w_usb, 'F.Cu', 1),+ seg(5.0, 15.275, 5.5, yn, w_usb, 'F.Cu', 2),+ seg(5.5, yn, 44.5, yn, w_usb, 'F.Cu', 2),+ seg(44.5, yn, 45.0, 15.275, w_usb, 'F.Cu', 2),+ ])+ b_disc = p / 'disc.kicad_pcb'+ make_board_4l(b_disc, 'USB_DP', 'USB_DN', segs=segs_off45)+ call(p / 'none', 'rules', 'stackup', '--stackup', 'JLC04161H-7628', '--spec', str(spec4_path), '--board', str(b_disc))+ r_disc = call(p / 'none', 'impedance', 'check', '--board', str(b_disc), '--spec', str(spec4_path))+ assert r_disc.returncode != 0 and 'off-45' in r_disc.stdout.lower(), r_disc.stdout+ print(' [6/9] off-45 local angle discontinuity caught and 45-deg fanout passes')++ # 7. Negative -> positive: layer transition (missing GND stitch fails -> 2 GND stitch vias passes)+ spec_via = p / 'spec_via.json'+ s_via = json.loads(spec4_path.read_text())+ s_via['impedanceTargets']['USB']['allowLayerChange'] = True+ s_via['impedanceTargets']['USB']['maxUncontrolledMm'] = 5.0+ spec_via.write_text(json.dumps(s_via))+ segs_via = ' '.join([+ seg(5.0, 14.725, 5.0 + dy, yp, w_usb, 'F.Cu', 1),+ seg(5.0 + dy, yp, 25.0, yp, w_usb, 'F.Cu', 1),+ seg(25.0, yp, 45.0 - dy, yp, w_usb, 'B.Cu', 1),+ seg(45.0 - dy, yp, 45.0, 14.725, w_usb, 'B.Cu', 1),+ seg(5.0, 15.275, 5.0 + dy, yn, w_usb, 'F.Cu', 2),+ seg(5.0 + dy, yn, 25.0, yn, w_usb, 'F.Cu', 2),+ seg(25.0, yn, 45.0 - dy, yn, w_usb, 'B.Cu', 2),+ seg(45.0 - dy, yn, 45.0, 15.275, w_usb, 'B.Cu', 2),+ ])+ vias_no_gnd = via(25.0, yp, 1) + ' ' + via(25.0, yn, 2)+ b_via = p / 'via.kicad_pcb'+ make_board_4l(b_via, 'USB_DP', 'USB_DN', segs=segs_via, vias=vias_no_gnd)+ call(p / 'none', 'rules', 'stackup', '--stackup', 'JLC04161H-7628', '--spec', str(spec_via), '--board', str(b_via))+ r_bad = call(p / 'none', 'impedance', 'check', '--board', str(b_via), '--spec', str(spec_via))+ assert r_bad.returncode != 0 and 'stitch' in r_bad.stdout.lower(), r_bad.stdout+ vias_with_gnd = vias_no_gnd + ' ' + via(25.0, yp - 1.2, 3) + ' ' + via(25.0, yn + 1.2, 3)+ make_board_4l(b_via, 'USB_DP', 'USB_DN', segs=segs_via, vias=vias_with_gnd)+ call(p / 'none', 'rules', 'stackup', '--stackup', 'JLC04161H-7628', '--spec', str(spec_via), '--board', str(b_via))+ r_good = call(p / 'none', 'impedance', 'check', '--board', str(b_via), '--spec', str(spec_via))+ assert r_good.returncode == 0, r_good.stdout+ print(' [7/9] symmetric via transition requires GND stitching via and passes when stitched')++ # 8. Negative -> positive: ESD/TVS T-stub vs inline flow-through+ esd_t = (+ '(footprint "T:D1" (layer "F.Cu") (at 15 11.5) (property "Reference" "D1") '+ '(pad "1" smd rect (at -0.5 0) (size 0.5 0.5) (layers "F.Cu") (net 1 "USB_DP")) '+ '(pad "2" smd rect (at 0.5 0) (size 0.5 0.5) (layers "F.Cu") (net 2 "USB_DN")))'+ )+ segs_stub = segs_phase_good + ' ' + seg(14.5, yp, 14.5, 11.5, w_usb, 'F.Cu', 1) + ' ' + seg(15.5, yn, 15.5, 11.5, w_usb, 'F.Cu', 2)+ b_esd = p / 'esd.kicad_pcb'+ make_board_4l(b_esd, 'USB_DP', 'USB_DN', segs=segs_stub, extra_fps=esd_t)+ call(p / 'none', 'rules', 'stackup', '--stackup', 'JLC04161H-7628', '--spec', str(spec4_path), '--board', str(b_esd))+ r_bad = call(p / 'none', 'impedance', 'check', '--board', str(b_esd), '--spec', str(spec4_path))+ assert r_bad.returncode != 0 and 'stub' in r_bad.stdout.lower(), r_bad.stdout+ esd_inline = (+ f'(footprint "T:D1" (layer "F.Cu") (at 15 15) (property "Reference" "D1") '+ f'(pad "1" smd rect (at 0 {yp - 15.0:.4f}) (size 0.5 0.35) (layers "F.Cu") (net 1 "USB_DP")) '+ f'(pad "2" smd rect (at 0 {yn - 15.0:.4f}) (size 0.5 0.35) (layers "F.Cu") (net 2 "USB_DN")))'+ )+ make_board_4l(b_esd, 'USB_DP', 'USB_DN', segs=segs_phase_good, extra_fps=esd_inline)+ call(p / 'none', 'rules', 'stackup', '--stackup', 'JLC04161H-7628', '--spec', str(spec4_path), '--board', str(b_esd))+ r_good = call(p / 'none', 'impedance', 'check', '--board', str(b_esd), '--spec', str(spec4_path))+ assert r_good.returncode == 0, r_good.stdout+ print(' [8/9] T-stubbed ESD caught and inline flow-through ESD passes')++ # 9. Export writes manufacturing/impedance-stackup.md and .json+ def runnable_kicad_cli():+ cand = os.environ.get('ADOM_AIFLOW_KICAD_CLI') or shutil.which('kicad-cli')+ if not cand:+ return None+ try:+ probe = subprocess.run([cand, '--version'], env=env, capture_output=True, text=True, timeout=15)+ out = probe.stdout + probe.stderr+ if probe.returncode == 0 and 'no KiCad found' not in out and out.strip():+ return cand+ except Exception:+ pass+ return None++ kicad_bin = runnable_kicad_cli()+ if kicad_bin:+ run_exp = p / 'run-exp'+ assert call(run_exp, 'start', '--board', str(b_phase), '--spec', str(spec4_path), '--engine', 'test', '--prompt-time', '2026-11-19T00:00:00Z').returncode == 0+ out_dir = p / 'mfg-out'+ re = call(run_exp, 'export', '--out', str(out_dir))+ assert re.returncode == 0, re.stdout + re.stderr+ md = out_dir / 'impedance-stackup.md'+ js = out_dir / 'impedance-stackup.json'+ assert md.exists() and js.exists(), f'missing impedance-stackup files in {list(out_dir.iterdir())}'+ md_txt = md.read_text()+ assert 'JLC04161H-7628' in md_txt and 'USB_DP' in md_txt and 'published-profile' in md_txt, md_txt+ js_obj = json.loads(js.read_text())+ assert js_obj['stackupId'] == 'JLC04161H-7628' and js_obj['targets'], js_obj+ print(f' [9/9] export generated manufacturing/impedance-stackup.md and .json (via {kicad_bin})')+ else:+ print(' [9/9] SKIP kicad-cli not runnable in this environment (set ADOM_AIFLOW_KICAD_CLI or install KiCad)')++print('PASS: diff-pair SI checks, published stackups, solder-mask solving, Fields cross-check, and export report verified.')
tests/si-emc-pdn-workflow.pyadded+240@@ -0,0 +1,240 @@+"""Signal integrity, return paths, 4L planeUnder, EMC/ESD/PDN Fields review, and USB power checks+end to end (issues #214, #215):+1. Pair crossing a reference-plane split fails analyze impedance and analyze si -> solid plane passes+2. 4-layer spec.planeUnder on In1.Cu catches inner tracks and piercing vias in gate -> fixed passes+3. Return-path GND stitching via check (<= 2.5 mm) fails when missing -> passes when stitched+4. 3W/3H crosstalk check (> 10 mm parallel run to sensitive ADC net) fails -> spaced passes+5. USB VBUS > 10 uF inrush check fails without limiter -> passes with limiter or <= 10 uF+6. Rail load budget check fails when auxiliary loads exceed USB budget -> passes within budget+7. Real adom-fields --with si,noise,emc,esd,pdn + adom-fields report integration surfaces+ readiness areas, findings, unrun modules, and high-impact review.inputs assumptions+Usage: python3 tests/si-emc-pdn-workflow.py <adom-aiflow binary>"""+import json, os, pathlib, shutil, subprocess, sys, tempfile++binary = str(pathlib.Path(sys.argv[1]).resolve())++STACK_4L = (+ '(setup (stackup '+ '(layer "F.Cu" (type "copper") (thickness 0.035)) '+ '(layer "dielectric 1" (type "prepreg") (thickness 0.2104) (epsilon_r 4.4)) '+ '(layer "In1.Cu" (type "copper") (thickness 0.0152)) '+ '(layer "dielectric 2" (type "core") (thickness 1.065) (epsilon_r 4.6)) '+ '(layer "In2.Cu" (type "copper") (thickness 0.0152)) '+ '(layer "dielectric 3" (type "prepreg") (thickness 0.2104) (epsilon_r 4.4)) '+ '(layer "B.Cu" (type "copper") (thickness 0.035))))'+)+++def make_4l_board(path, segs="", vias="", zones="", extra_fps=""):+ fp_j1 = (+ '(footprint "Connector_USB:USB_C" (layer "F.Cu") (at 3 15) (property "Reference" "J1") (property "Value" "USB-C") '+ '(pad "1" smd rect (at 0 -0.35) (size 0.8 0.35) (layers "F.Cu") (net 1 "USB_D+")) '+ '(pad "2" smd rect (at 0 0.35) (size 0.8 0.35) (layers "F.Cu") (net 2 "USB_D-")) '+ '(pad "3" smd rect (at 0 -2.0) (size 0.8 0.5) (layers "F.Cu") (net 6 "VBUS")) '+ '(pad "4" thru_hole circle (at 0 2.0) (size 0.8 0.8) (drill 0.4) (layers "*.Cu") (net 3 "GND")))'+ )+ fp_u1 = (+ '(footprint "Package_QFP:MCU" (layer "F.Cu") (at 42 15) (property "Reference" "U1") (property "Value" "MCU") '+ '(pad "1" smd rect (at 0 -0.35) (size 0.8 0.35) (layers "F.Cu") (net 1 "USB_D+")) '+ '(pad "2" smd rect (at 0 0.35) (size 0.8 0.35) (layers "F.Cu") (net 2 "USB_D-")) '+ '(pad "3" smd rect (at 0 -2.0) (size 0.8 0.5) (layers "F.Cu") (net 6 "VBUS")) '+ '(pad "4" thru_hole circle (at 0 2.0) (size 0.8 0.8) (drill 0.4) (layers "*.Cu") (net 3 "GND")) '+ '(pad "5" smd rect (at 0 5.0) (size 0.8 0.4) (layers "F.Cu") (net 4 "SPI_CLK")) '+ '(pad "6" smd rect (at 0 7.0) (size 0.8 0.4) (layers "F.Cu") (net 5 "ADC_IN")))'+ )+ path.write_text(+ '(kicad_pcb (version 20241229) (generator "test") (general (thickness 1.6)) '+ '(layers (0 "F.Cu" signal) (4 "In1.Cu" signal) (6 "In2.Cu" signal) (2 "B.Cu" signal) (25 "Edge.Cuts" user)) '+ f'{STACK_4L} '+ '(net 0 "") (net 1 "USB_D+") (net 2 "USB_D-") (net 3 "GND") (net 4 "SPI_CLK") (net 5 "ADC_IN") (net 6 "VBUS") '+ f'{fp_j1} {fp_u1} {extra_fps} {segs} {vias} {zones} '+ '(gr_rect (start 0 0) (end 48 30) (layer "Edge.Cuts") (stroke (width 0.1) (type solid))))'+ )+++def solid_gnd_zone():+ return (+ '(zone (net 3) (net_name "GND") (layer "In1.Cu") (tstamp "00000000-0000-0000-0000-000000000010") '+ '(hatch edge 0.5) (connect_pads (clearance 0.2)) (min_thickness 0.2) '+ '(fill yes (thermal_gap 0.3) (thermal_bridge_width 0.3)) '+ '(polygon (pts (xy 0.5 0.5) (xy 47.5 0.5) (xy 47.5 29.5) (xy 0.5 29.5))) '+ '(filled_polygon (layer "In1.Cu") (pts (xy 0.5 0.5) (xy 47.5 0.5) (xy 47.5 29.5) (xy 0.5 29.5))))'+ )+++def split_gnd_zones():+ return (+ '(zone (net 3) (net_name "GND") (layer "In1.Cu") (tstamp "00000000-0000-0000-0000-000000000011") '+ '(hatch edge 0.5) (connect_pads (clearance 0.2)) (min_thickness 0.2) '+ '(fill yes (thermal_gap 0.3) (thermal_bridge_width 0.3)) '+ '(polygon (pts (xy 0.5 0.5) (xy 18.0 0.5) (xy 18.0 29.5) (xy 0.5 29.5))) '+ '(filled_polygon (layer "In1.Cu") (pts (xy 0.5 0.5) (xy 18.0 0.5) (xy 18.0 29.5) (xy 0.5 29.5)))) '+ '(zone (net 3) (net_name "GND") (layer "In1.Cu") (tstamp "00000000-0000-0000-0000-000000000012") '+ '(hatch edge 0.5) (connect_pads (clearance 0.2)) (min_thickness 0.2) '+ '(fill yes (thermal_gap 0.3) (thermal_bridge_width 0.3)) '+ '(polygon (pts (xy 26.0 0.5) (xy 47.5 0.5) (xy 47.5 29.5) (xy 26.0 29.5))) '+ '(filled_polygon (layer "In1.Cu") (pts (xy 26.0 0.5) (xy 47.5 0.5) (xy 47.5 29.5) (xy 26.0 29.5))))'+ )+++USB_SEGS = (+ '(segment (start 3 14.65) (end 42 14.65) (width 0.3689) (layer "F.Cu") (net 1)) '+ '(segment (start 3 15.35) (end 42 15.35) (width 0.3689) (layer "F.Cu") (net 2)) '+ '(segment (start 3 13.0) (end 42 13.0) (width 0.5) (layer "F.Cu") (net 6))'+)+++with tempfile.TemporaryDirectory(prefix='aiflow-si-emc-') as td:+ p = pathlib.Path(td)+ env = dict(os.environ, AIFLOW_DASHBOARD='off', XDG_CONFIG_HOME=str(p / 'xdg'))++ def call(run, *args):+ return subprocess.run(+ [binary, '--run', str(run), '--ai-thread', 'si-emc-test', *args],+ env=env, capture_output=True, text=True, timeout=120+ )++ base_spec = {+ "clearance": 0.127, "minTrackWidth": 0.127, "track": 0.2, "copperUm": 35,+ "loads": {"VBUS": {"from": "J1.3", "to": "U1.3", "amps": 0.35}, "GND": {"from": "U1.4", "to": "J1.4", "amps": 0.35}},+ "voltages": {"VBUS": 5.0, "GND": 0.0},+ "sources": {"VBUS": ["J1"]},+ "clocks": {"SPI_CLK": {"freqHz": 24_000_000}},+ "sensitiveNets": ["ADC_IN"],+ "impedanceTargets": {"USB": {"pair": ["USB_D+", "USB_D-"], "targetDiffOhms": 90}}+ }+ sp = p / 'spec.json'+ sp.write_text(json.dumps(base_spec))++ # 1. Pair crossing a plane split reports FINDINGS (non-blocking) by default, fails under strictSi: true -> solid plane passes+ b_split = p / 'split.kicad_pcb'+ make_4l_board(b_split, segs=USB_SEGS, zones=split_gnd_zones())+ run1 = p / 'run-split'+ assert call(run1, 'start', '--board', str(b_split), '--spec', str(sp), '--engine', 'test', '--prompt-time', '2026-11-19T00:00:00Z').returncode == 0+ r_imp_bad = call(run1, 'analyze', 'impedance')+ assert r_imp_bad.returncode == 0 and 'FINDINGS' in r_imp_bad.stdout and 'reference' in r_imp_bad.stdout.lower(), r_imp_bad.stdout+ o_imp = json.loads((run1 / 'run.json').read_text())['outcomes']['analyze-impedance']+ assert o_imp['pass'] is True and o_imp['referencePlane']['pass'] is False, o_imp+ r_si_bad = call(run1, 'analyze', 'si')+ assert r_si_bad.returncode == 0 and 'FINDINGS' in r_si_bad.stdout and 'reference plane' in r_si_bad.stdout.lower(), r_si_bad.stdout+ o_si = json.loads((run1 / 'run.json').read_text())['outcomes']['analyze-si']+ assert o_si['pass'] is True and o_si['findings'], o_si++ # Strict opt-in fails analyze impedance and analyze si+ sp_strict = p / 'spec_strict.json'+ sp_strict.write_text(json.dumps(dict(base_spec, strictSi=True)))+ run1s = p / 'run-split-strict'+ assert call(run1s, 'start', '--board', str(b_split), '--spec', str(sp_strict), '--engine', 'test', '--prompt-time', '2026-11-19T00:00:00Z').returncode == 0+ assert call(run1s, 'analyze', 'impedance').returncode != 0+ assert call(run1s, 'analyze', 'si').returncode != 0++ b_solid = p / 'solid.kicad_pcb'+ make_4l_board(b_solid, segs=USB_SEGS, zones=solid_gnd_zone())+ run1g = p / 'run-solid'+ assert call(run1g, 'start', '--board', str(b_solid), '--spec', str(sp), '--engine', 'test', '--prompt-time', '2026-11-19T00:00:00Z').returncode == 0+ r_imp_good = call(run1g, 'analyze', 'impedance')+ assert r_imp_good.returncode == 0 and 'reference plane: >= 90%' in r_imp_good.stdout, r_imp_good.stdout+ r_si_good = call(run1g, 'analyze', 'si')+ assert r_si_good.returncode == 0 and 'OK: ' in r_si_good.stdout, r_si_good.stdout+ print(' [1/6] plane split reports FINDINGS by default, fails with strictSi: true; solid plane passes')++ # 2. Return-path stitching via: missing GND via reports FINDINGS -> stitched passes+ clk_flip = USB_SEGS + ' (segment (start 42 20) (end 20 20) (width 0.2) (layer "F.Cu") (net 4)) (segment (start 20 20) (end 10 20) (width 0.2) (layer "B.Cu") (net 4))'+ b_rv_bad = p / 'rv-bad.kicad_pcb'+ make_4l_board(b_rv_bad, segs=clk_flip, vias='(via (at 20 20) (size 0.6) (drill 0.3) (layers "F.Cu" "B.Cu") (net 4))', zones=solid_gnd_zone())+ run2 = p / 'run-rv-bad'+ assert call(run2, 'start', '--board', str(b_rv_bad), '--spec', str(sp), '--engine', 'test', '--prompt-time', '2026-11-19T00:00:00Z').returncode == 0+ r = call(run2, 'analyze', 'si')+ assert r.returncode == 0 and 'FINDINGS' in r.stdout and 'return-path via missing' in r.stdout.lower(), r.stdout++ b_rv_good = p / 'rv-good.kicad_pcb'+ make_4l_board(b_rv_good, segs=clk_flip, vias='(via (at 20 20) (size 0.6) (drill 0.3) (layers "F.Cu" "B.Cu") (net 4)) (via (at 20 21.5) (size 0.6) (drill 0.3) (layers "F.Cu" "B.Cu") (net 3))', zones=solid_gnd_zone())+ run2g = p / 'run-rv-good'+ assert call(run2g, 'start', '--board', str(b_rv_good), '--spec', str(sp), '--engine', 'test', '--prompt-time', '2026-11-19T00:00:00Z').returncode == 0+ r = call(run2g, 'analyze', 'si')+ assert r.returncode == 0 and 'OK: ' in r.stdout, r.stdout+ print(' [2/6] missing return-path GND stitching via reported as FINDINGS; stitched transition passes')++ # 3. 3W/3H crosstalk: 20 mm parallel run at 0.25 mm gap reports FINDINGS -> 1.2 mm gap passes+ xt_bad_segs = USB_SEGS + ' (segment (start 10 20) (end 30 20) (width 0.2) (layer "F.Cu") (net 4)) (segment (start 10 20.45) (end 30 20.45) (width 0.2) (layer "F.Cu") (net 5))'+ b_xt_bad = p / 'xt-bad.kicad_pcb'+ make_4l_board(b_xt_bad, segs=xt_bad_segs, zones=solid_gnd_zone())+ run3 = p / 'run-xt-bad'+ assert call(run3, 'start', '--board', str(b_xt_bad), '--spec', str(sp), '--engine', 'test', '--prompt-time', '2026-11-19T00:00:00Z').returncode == 0+ r = call(run3, 'analyze', 'si')+ assert r.returncode == 0 and 'FINDINGS' in r.stdout and 'crosstalk' in r.stdout.lower(), r.stdout++ xt_good_segs = USB_SEGS + ' (segment (start 10 20) (end 30 20) (width 0.2) (layer "F.Cu") (net 4)) (segment (start 10 21.6) (end 30 21.6) (width 0.2) (layer "F.Cu") (net 5))'+ b_xt_good = p / 'xt-good.kicad_pcb'+ make_4l_board(b_xt_good, segs=xt_good_segs, zones=solid_gnd_zone())+ run3g = p / 'run-xt-good'+ assert call(run3g, 'start', '--board', str(b_xt_good), '--spec', str(sp), '--engine', 'test', '--prompt-time', '2026-11-19T00:00:00Z').returncode == 0+ r = call(run3g, 'analyze', 'si')+ assert r.returncode == 0 and 'OK: ' in r.stdout, r.stdout+ print(' [3/6] 3W/3H crosstalk reported for 20 mm parallel SPI_CLK/ADC_IN run; spaced run passes')++ # 4. USB VBUS > 10 uF inrush check reports FINDINGS without limiter -> passes with limiter+ big_caps = (+ '(footprint "Capacitor_SMD:C_0805" (layer "F.Cu") (at 12 10) (property "Reference" "C1") (property "Value" "22uF") '+ '(pad "1" smd rect (at -0.8 0) (size 0.8 0.8) (layers "F.Cu") (net 6 "VBUS")) '+ '(pad "2" smd rect (at 0.8 0) (size 0.8 0.8) (layers "F.Cu") (net 3 "GND"))) '+ '(footprint "Capacitor_SMD:C_0805" (layer "F.Cu") (at 18 10) (property "Reference" "C2") (property "Value" "10uF") '+ '(pad "1" smd rect (at -0.8 0) (size 0.8 0.8) (layers "F.Cu") (net 6 "VBUS")) '+ '(pad "2" smd rect (at 0.8 0) (size 0.8 0.8) (layers "F.Cu") (net 3 "GND")))'+ )+ b_inrush = p / 'inrush.kicad_pcb'+ make_4l_board(b_inrush, segs=USB_SEGS, zones=solid_gnd_zone(), extra_fps=big_caps)+ run4 = p / 'run-inrush-bad'+ assert call(run4, 'start', '--board', str(b_inrush), '--spec', str(sp), '--engine', 'test', '--prompt-time', '2026-11-19T00:00:00Z').returncode == 0+ r = call(run4, 'analyze', 'si')+ assert r.returncode == 0 and 'FINDINGS' in r.stdout and 'inrush' in r.stdout.lower(), r.stdout++ sp_lim = p / 'spec_lim.json'+ sp_lim.write_text(json.dumps(dict(base_spec, inrushLimiter="U5 TPS2553")))+ run4g = p / 'run-inrush-good'+ assert call(run4g, 'start', '--board', str(b_inrush), '--spec', str(sp_lim), '--engine', 'test', '--prompt-time', '2026-11-19T00:00:00Z').returncode == 0+ r = call(run4g, 'analyze', 'si')+ assert r.returncode == 0 and 'OK: ' in r.stdout, r.stdout+ print(' [4/6] USB VBUS 32 uF inrush reported without limiter; passes with inrushLimiter declared')++ # 5. Rail load budget check: auxiliary RGB load exceeding 0.5 A USB budget reports FINDINGS -> passes at 1.5 A+ sp_ov = p / 'spec_ov.json'+ sp_ov.write_text(json.dumps(dict(base_spec, auxiliaryLoads={"RGB": {"net": "VBUS", "amps": 0.40}}, usb={"maxCurrentA": 0.50})))+ run5 = p / 'run-budget-bad'+ assert call(run5, 'start', '--board', str(b_solid), '--spec', str(sp_ov), '--engine', 'test', '--prompt-time', '2026-11-19T00:00:00Z').returncode == 0+ r = call(run5, 'analyze', 'si')+ assert r.returncode == 0 and 'FINDINGS' in r.stdout and 'budget exceeded' in r.stdout.lower(), r.stdout++ sp_ok = p / 'spec_ok.json'+ sp_ok.write_text(json.dumps(dict(base_spec, auxiliaryLoads={"RGB": {"net": "VBUS", "amps": 0.40}}, usb={"maxCurrentA": 1.50})))+ run5g = p / 'run-budget-good'+ assert call(run5g, 'start', '--board', str(b_solid), '--spec', str(sp_ok), '--engine', 'test', '--prompt-time', '2026-11-19T00:00:00Z').returncode == 0+ r = call(run5g, 'analyze', 'si')+ assert r.returncode == 0 and 'OK: ' in r.stdout, r.stdout+ print(' [5/6] rail load budget reports 0.75 A > 0.50 A USB limit and passes at 1.50 A')++ # 6. Real adom-fields --with si,noise,emc,esd,pdn + adom-fields report integration (with stubbed via)+ if shutil.which('adom-fields'):+ # Include a via connecting F.Cu -> In1.Cu on SPI_CLK (leaving stub to B.Cu) + GND stitch via+ stub_segs = USB_SEGS + ' (segment (start 42 20) (end 20 20) (width 0.2) (layer "F.Cu") (net 4)) (segment (start 20 20) (end 10 20) (width 0.2) (layer "In1.Cu") (net 4))'+ stub_vias = '(via (at 20 20) (size 0.6) (drill 0.3) (layers "F.Cu" "B.Cu") (net 4)) (via (at 20 21.5) (size 0.6) (drill 0.3) (layers "F.Cu" "B.Cu") (net 3))'+ b_fld = p / 'fields-board.kicad_pcb'+ make_4l_board(b_fld, segs=stub_segs, vias=stub_vias, zones=solid_gnd_zone())+ run6 = p / 'run-fields'+ assert call(run6, 'start', '--board', str(b_fld), '--spec', str(sp), '--engine', 'test', '--prompt-time', '2026-11-19T00:00:00Z').returncode == 0+ fdir = run6 / 'fields'+ rf = subprocess.run(['adom-fields', 'analyze', '--board', str(b_fld), '--spec', str(sp), '--with', 'si,noise,emc,esd,pdn', '--out', str(fdir)], env=env, capture_output=True, text=True, timeout=120)+ assert rf.returncode == 0, rf.stdout + rf.stderr+ r6 = call(run6, 'analyze', 'si', '--fields', str(fdir / 'fields.json'))+ assert r6.returncode == 0, r6.stdout + r6.stderr+ assert 'design-review/readiness.md' in r6.stdout, r6.stdout+ assert (run6 / 'design-review' / 'readiness.md').exists() and (run6 / 'design-review' / 'readiness.json').exists()+ o6 = json.loads((run6 / 'run.json').read_text())['outcomes']['analyze-si']+ assert o6['detectedExternal'] == ['J1'], o6['detectedExternal']+ assert set(o6['recommendedFieldsModules']) == {'si', 'noise', 'emc', 'esd', 'pdn'}, o6['recommendedFieldsModules']+ assert o6['fieldsReadiness']['areas'], o6['fieldsReadiness']+ print(' [6/6] adom-fields --with si,noise,emc,esd,pdn + adom-fields report readiness verified')+ else:+ print(' [6/6] SKIP adom-fields not on PATH')++print('PASS: SI reference-plane, return-via, 3W crosstalk, USB VBUS inrush, load budget, and Fields SI/EMC/ESD/PDN readiness verified.')