← Commit history

Merge PR #548: Sync canonical electrical net classes into KiCad .kicad_pro/.kicad_dru and Altium DRC (#216) (feat/native-drc-netclasses -> main) merge

Colby Knox ·dc67aab200 · ·parents 0e7ba67, 24ae1f7

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

6 files changed +1038−9
crates/adom-aiflow/src/gate_eval.rs+1
@@ -100,6 +100,7 @@ pub fn evaluate(r: &Run, b: &Board, plan_v: &Value, routed: &Path, base: &Value,     s["staircases"] = json!(stairs);     let quality = rb().map(|rb| crate::route_quality::of_board(&rb, &spec_g)).unwrap_or_else(|e| (json!({"error": e}), Vec::new()));     s["routeQuality"] = crate::route_quality::outcome(&quality.0, "route-quality.json");+    s["netClasses"] = crate::netclasses::verify_kicad(&r.current_board(), rb().ok().as_ref(), &spec_g);     Ok(GateEval { s, pu, pu_issues, sw_issues, dec, mech, stairs, quality }) } 
crates/adom-aiflow/src/main.rs+79−8
@@ -41,6 +41,7 @@ mod silk_policy; mod led_states; mod programming; mod project_lib;+mod netclasses;  /// 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");@@ -181,13 +182,17 @@ 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"])] 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"])] 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> },+    #[arg(long)] prefs: Option<String>,+    /// `rules sync` / `rules check`: 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> },     /// Start the clock at the prompt before any board exists: the run opens with the `intake` step and no board; `start --board` attaches it later on the same clock.     Intake { #[arg(long)] prompt_time: String, /// the brief (a file: the human's message, a transcript, a spec); a requirements JSON is recorded as the requirements too     #[arg(long)] brief: Option<String>, /// requirements.json (aiflow-intake): fab.target picks the sourcing profile@@ -6874,7 +6879,48 @@ 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 } if action == "use" || action == "list" => {+        Cmd::Rules { action, profile, board, force, layers, variant, prefs, spec, altium_out } if action == "use" || action == "list" || action == "sync" => {+            if action == "sync" {+                let mut run = Run::open(&dir);+                if run.is_some() { thread(&cli); }+                let board_path = board.clone().or_else(|| run.as_ref().map(|r| r.current_board())).unwrap_or_default();+                let spec_v = match spec.as_deref() {+                    Some(s) => read_json(s),+                    None => run.as_ref().map(spec_of).unwrap_or_else(|| err("rules sync needs an open run or --spec <spec.json>", &[])),+                };+                let loaded_board = if board_path.ends_with(".kicad_pcb") && Path::new(&board_path).is_file() { Board::load(&board_path).ok() } else { None };+                let plan = netclasses::derive(loaded_board.as_ref(), &spec_v);+                if plan.classes.is_empty() {+                    ok("rules sync: spec defines no electrical net classes (no wideNets, midNets, impedanceTargets, HV voltages, or sensitiveNets)", &[]);+                    return;+                }+                let mut written = Vec::new();+                if !board_path.is_empty() && board_path.ends_with(".kicad_pcb") {+                    let (pro_p, dru_p) = netclasses::sync_kicad(&board_path, &plan).unwrap_or_else(|e| err(&e, &[]));+                    written.push(pro_p.display().to_string());+                    written.push(dru_p.display().to_string());+                }+                let alt_payload = netclasses::altium_rules_payload(&plan);+                let alt_req = aiflow_bridge::altium::design_rules_request(&board_path, &alt_payload);+                let alt_path = altium_out.as_ref().map(PathBuf::from)+                    .or_else(|| run.as_ref().map(|_| dir.join("altium-design-rules.json")));+                if let Some(ap) = alt_path {+                    write_json(&ap, &alt_req);+                    written.push(ap.display().to_string());+                }+                if let Some(r) = run.as_mut() {+                    r.outcome("rules-netclasses", json!({+                        "classes": plan.classes.iter().map(|c| json!({"name": c.name, "kind": c.kind, "nets": c.nets, "minWidthMm": c.min_width_mm, "clearanceMm": c.clearance_mm, "diffPairGapMm": c.diff_pair_gap_mm})).collect::<Vec<_>>(),+                        "written": written,+                    }));+                    r.save().unwrap();+                }+                let summary: Vec<String> = plan.classes.iter().map(|c| format!("{} ({} net(s))", c.name, c.nets.len())).collect();+                let mut hints = plan.notes;+                hints.push("Run `adom-aiflow rules check` or `adom-aiflow gate` to verify native DRC enforces these net classes.".into());+                ok(&format!("synced {} electrical net class(es): {}; updated {}", plan.classes.len(), summary.join(", "), written.join(", ")), &hints);+                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();@@ -6967,6 +7013,18 @@ fn main() {                     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(); }                     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() {+                        let b_opt = Board::load(&cb).ok();+                        let nc_plan = netclasses::derive(b_opt.as_ref(), &v);+                        if !nc_plan.classes.is_empty() {+                            if let Ok((pro_p, _)) = netclasses::sync_kicad(&cb, &nc_plan) {+                                placed.push(pro_p.display().to_string());+                            }+                            let alt_req = aiflow_bridge::altium::design_rules_request(&cb, &netclasses::altium_rules_payload(&nc_plan));+                            write_json(&dir.join("altium-design-rules.json"), &alt_req);+                        }+                    }                 }             }             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();@@ -6981,7 +7039,7 @@ fn main() {                 "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()]);         }-        Cmd::Rules { action, profile, board, force, layers, .. } => {+        Cmd::Rules { action, profile, board, force, layers, spec, .. } => {             let run = Run::open(&dir);             if run.is_some() { thread(&cli); }             let board_path = board.clone().or_else(|| run.as_ref().map(|r| r.current_board())).unwrap_or_else(|| err("rules needs --board <file.kicad_pcb> outside a run", &[]));@@ -7033,6 +7091,11 @@ fn main() {                 _ => {                     let fallback_layers = layers.or(recorded_layers);                     let result = checks::rules_check_layers(&profile, &board_path, fallback_layers);+                    let spec_nc = spec.as_deref().map(read_json).or_else(|| run.as_ref().map(spec_soft));+                    let nc_check = spec_nc.as_ref().map(|sv| {+                        let b_opt = Board::load(&board_path).ok();+                        netclasses::verify_kicad(&board_path, b_opt.as_ref(), sv)+                    });                     // A read-only check of this run's selected project rules is proof too.                     // Do not rewrite custom rules, or qualify a different board/profile.                     if let Some(mut r) = run {@@ -7047,21 +7110,29 @@ fn main() {                             .zip(std::fs::canonicalize(&selected_dru).ok())                             .is_some_and(|(a, b)| a == b);                         if same_board && same_profile && same_rules {+                            let nc_ok = nc_check.as_ref().map(|v| v["pass"] != false).unwrap_or(true);                             r.outcome("rules", json!({-                                "pass": result.is_ok(), "profile": profile,+                                "pass": result.is_ok() && nc_ok, "profile": profile,                                 "method": "existing-project-check", "board": board_path,                                 "boardSha256": sha256_file(&board_path),                                 "file": dru.display().to_string(),                                 "rulesSha256": sha256_file(&dru.display().to_string()),+                                "netClasses": nc_check,                                 "note": result.as_ref().map(|m| m.as_str())                                     .unwrap_or_else(|e| e.as_str())                             }));                             r.save().unwrap_or_else(|e| err(&e.to_string(), &[]));                         }                     }-                    match result {-                        Ok(m) => ok(&m, &[]),-                        Err(e) => findings(&e, &[checks::rules_hint_layers(&profile, checks::effective_layers(&profile, &board_path, fallback_layers))]),+                    let nc_findings: Vec<String> = nc_check.as_ref()+                        .filter(|v| v["pass"] == false)+                        .and_then(|v| v["findings"].as_array())+                        .into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect();+                    match (result, nc_findings.is_empty()) {+                        (Ok(m), true) => ok(&m, &[]),+                        (Ok(m), false) => findings(&format!("{m}; native net classes out of sync:\n  {}", nc_findings.join("\n  ")), &["Run `adom-aiflow rules sync` to write derived net classes into .kicad_pro and .kicad_dru so native DRC enforces them.".into()]),+                        (Err(e), true) => findings(&e, &[checks::rules_hint_layers(&profile, checks::effective_layers(&profile, &board_path, fallback_layers))]),+                        (Err(e), false) => findings(&format!("{e}\n  {}", nc_findings.join("\n  ")), &[checks::rules_hint_layers(&profile, checks::effective_layers(&profile, &board_path, fallback_layers)), "Run `adom-aiflow rules sync` to write derived net classes into .kicad_pro and .kicad_dru.".into()]),                     }                 }             }
crates/adom-aiflow/src/netclasses.rsadded+810
@@ -0,0 +1,810 @@+//! Canonical electrical net classes and native EDA DRC rule sync (issue #216).+//!+//! Derives electrical net classes from `spec.json` (`wideNets`, `midNets`, `loads`,+//! `impedanceTargets`, `voltages > 30 V` / `clearances`, `sensitiveNets` / `signalPriority`,+//! `clocks` / `switching`), writes them into:+//! - KiCad `<project>.kicad_pro` (`net_settings.classes` + `netclass_patterns`) and a managed+//!   `# BEGIN/END adom-aiflow netclasses` section of `<project>.kicad_dru` (validated by+//!   `checks::dru_syntax` without clobbering user custom rules);+//! - Altium PCB Design Rules payload JSON (Width per net class, Electrical Clearance matrix,+//!   Differential Pairs Routing width/gap/max uncoupled length, Matched Net Lengths).+//!+//! `verify_kicad` checks that every `impedanceTargets` pair/net and `wideNets` entry is assigned+//! to a matching non-`Default` native net class and rule set (used by `rules check` and `gate`).++use std::collections::{BTreeMap, BTreeSet};+use std::path::{Path, PathBuf};++use aiflow_board::Board;+use aiflow_router::impedance;+use serde_json::{json, Value};++pub const DRU_BEGIN: &str = "# BEGIN adom-aiflow netclasses";+pub const DRU_END: &str = "# END adom-aiflow netclasses";++#[derive(Debug, Clone)]+pub struct NetClassSpec {+    pub name: String,+    pub kind: String,+    pub nets: Vec<String>,+    pub min_width_mm: f64,+    pub opt_width_mm: Option<f64>,+    pub max_width_mm: Option<f64>,+    pub clearance_mm: f64,+    pub via_diameter_mm: Option<f64>,+    pub via_drill_mm: Option<f64>,+    pub diff_pair_gap_mm: Option<f64>,+    pub diff_pair_gap_min_mm: Option<f64>,+    pub diff_pair_gap_max_mm: Option<f64>,+    pub diff_pair_uncoupled_mm: Option<f64>,+    pub max_skew_mm: Option<f64>,+    pub is_diff_pair: bool,+}++#[derive(Debug, Clone)]+pub struct ClearancePair {+    pub class_a: String,+    pub class_b: String,+    pub min_mm: f64,+    pub why: String,+}++#[derive(Debug, Clone)]+pub struct NetClassPlan {+    pub base_clearance_mm: f64,+    pub base_track_mm: f64,+    pub classes: Vec<NetClassSpec>,+    pub inter_class_clearances: Vec<ClearancePair>,+    pub notes: Vec<String>,+}++fn r4(v: f64) -> f64 { (v * 10_000.0).round() / 10_000.0 }+fn r3(v: f64) -> f64 { (v * 1_000.0).round() / 1_000.0 }++fn clean_class_token(raw: &str) -> String {+    let s: String = raw.chars().map(|c| if c.is_ascii_alphanumeric() { c.to_ascii_uppercase() } else { '_' }).collect();+    let trimmed = s.trim_matches('_');+    if trimmed.is_empty() { "NET".into() } else { trimmed.to_string() }+}++fn ipc2221_b2_coated_clearance(volts: f64) -> f64 {+    let v = volts.abs();+    if v <= 30.0 { 0.13 }+    else if v <= 50.0 { 0.40 }+    else if v <= 100.0 { 0.60 }+    else if v <= 170.0 { 1.25 }+    else if v <= 300.0 { 2.00 }+    else { 3.20 }+}++fn is_gnd(name: &str) -> bool {+    let u = name.trim_start_matches('/').to_ascii_uppercase();+    let u = u.rsplit('/').next().unwrap_or(&u);+    u == "GND" || u == "AGND" || u == "DGND" || u == "PGND" || u == "VSS" || u.contains("GND")+}++/// Derive canonical electrical net classes from `spec.json` (and `board` stackup when available).+pub fn derive(board: Option<&Board>, spec: &Value) -> NetClassPlan {+    let base_clearance = spec["clearance"].as_f64().unwrap_or(0.2);+    let base_track = spec["track"].as_f64().unwrap_or(0.2);+    let min_track = spec["minTrackWidth"].as_f64().unwrap_or(0.127);+    let mut classes: Vec<NetClassSpec> = Vec::new();+    let mut inter_clearances: Vec<ClearancePair> = Vec::new();+    let mut notes: Vec<String> = Vec::new();+    let mut assigned: BTreeSet<String> = BTreeSet::new();++    // 1. Controlled-impedance and differential-pair classes (highest precedence)+    let imp_targets = impedance::targets(spec).unwrap_or_default();+    let solved_plan = board.and_then(|b| crate::impedance_cmd::plan(b, spec, "").ok().flatten());+    for t in &imp_targets {+        let solved_row = solved_plan.as_ref().and_then(|p| {+            let pref = t.layer.as_deref().unwrap_or("F.Cu");+            p.rows.iter().find(|r| r["target"] == t.name.as_str() && r["layer"] == pref && r["ok"] == true)+                .or_else(|| p.rows.iter().find(|r| r["target"] == t.name.as_str() && r["ok"] == true))+        });+        let w = solved_row.and_then(|r| r["widthMm"].as_f64())+            .or(t.width)+            .unwrap_or_else(|| {+                notes.push(format!("impedance target {}: no board stackup solved width; using fallback {:.3} mm", t.name, base_track.max(0.2)));+                base_track.max(0.2)+            });+        let g = solved_row.and_then(|r| r["gapMm"].as_f64()).or(t.gap);+        let tok = clean_class_token(&t.name);+        if t.diff {+            let gap = g.unwrap_or(base_clearance.max(0.15));+            let gap_tol = (gap * (t.tolerance / 100.0)).clamp(0.02, 0.08);+            let w_tol = (w * (t.tolerance / 100.0)).clamp(0.015, 0.06);+            let clr = t.coplanar.as_ref().map(|c| c.gap).unwrap_or_else(|| base_clearance.max(gap));+            for n in &t.nets { assigned.insert(n.clone()); }+            classes.push(NetClassSpec {+                name: format!("DIFF_{tok}"),+                kind: "diff-pair".into(),+                nets: t.nets.clone(),+                min_width_mm: r4((w - w_tol).max(min_track)),+                opt_width_mm: Some(r4(w)),+                max_width_mm: Some(r4(w + w_tol)),+                clearance_mm: r4(clr),+                via_diameter_mm: Some(0.6),+                via_drill_mm: Some(0.3),+                diff_pair_gap_mm: Some(r4(gap)),+                diff_pair_gap_min_mm: Some(r4((gap - gap_tol).max(min_track))),+                diff_pair_gap_max_mm: Some(r4(gap + gap_tol)),+                diff_pair_uncoupled_mm: Some(r3(t.max_uncontrolled)),+                max_skew_mm: Some(r3(t.max_skew)),+                is_diff_pair: true,+            });+        } else {+            let w_tol = (w * (t.tolerance / 100.0)).clamp(0.015, 0.06);+            let clr = t.coplanar.as_ref().map(|c| c.gap).unwrap_or(base_clearance);+            for n in &t.nets { assigned.insert(n.clone()); }+            classes.push(NetClassSpec {+                name: format!("IMP_{tok}"),+                kind: "impedance".into(),+                nets: t.nets.clone(),+                min_width_mm: r4((w - w_tol).max(min_track)),+                opt_width_mm: Some(r4(w)),+                max_width_mm: Some(r4(w + w_tol)),+                clearance_mm: r4(clr),+                via_diameter_mm: Some(0.6),+                via_drill_mm: Some(0.3),+                diff_pair_gap_mm: None,+                diff_pair_gap_min_mm: None,+                diff_pair_gap_max_mm: None,+                diff_pair_uncoupled_mm: None,+                max_skew_mm: None,+                is_diff_pair: false,+            });+        }+    }++    // 2. High-voltage / isolation clearance classes (voltages > 30 V)+    let mut hv_by_clr: BTreeMap<i64, Vec<String>> = BTreeMap::new();+    if let Some(volts) = spec["voltages"].as_object() {+        for (net, v) in volts {+            if let Some(vv) = v.as_f64() {+                if vv.abs() > 30.0 {+                    let clr = ipc2221_b2_coated_clearance(vv).max(base_clearance);+                    hv_by_clr.entry((clr * 1000.0).round() as i64).or_default().push(net.clone());+                }+            }+        }+    }+    for (clr_um, mut nets) in hv_by_clr {+        nets.sort();+        let clr = clr_um as f64 / 1000.0;+        let suffix = if clr_um == 400 { "50V" } else if clr_um == 600 { "100V" } else { "HV" };+        let name = if classes.iter().any(|c| c.name == format!("HV_{suffix}")) {+            format!("HV_{clr_um}UM")+        } else {+            format!("HV_{suffix}")+        };+        let mut width = base_track.max(0.3);+        if let Some(wn) = spec["wideNets"].as_object() {+            for n in &nets {+                if let Some(w) = wn.get(n).and_then(|x| x.as_f64()) { width = width.max(w); }+            }+        }+        for n in &nets { assigned.insert(n.clone()); }+        classes.push(NetClassSpec {+            name,+            kind: "high-voltage".into(),+            nets,+            min_width_mm: r4(width),+            opt_width_mm: Some(r4(width)),+            max_width_mm: None,+            clearance_mm: r4(clr),+            via_diameter_mm: Some(0.8),+            via_drill_mm: Some(0.4),+            diff_pair_gap_mm: None,+            diff_pair_gap_min_mm: None,+            diff_pair_gap_max_mm: None,+            diff_pair_uncoupled_mm: None,+            max_skew_mm: None,+            is_diff_pair: false,+        });+    }++    // 3. Power classes from wideNets / midNets / loads+    let mut wide_groups: BTreeMap<i64, Vec<String>> = BTreeMap::new();+    if let Some(o) = spec["wideNets"].as_object() {+        for (net, v) in o {+            if assigned.contains(net) { continue; }+            let w = v.as_f64().unwrap_or(0.5).max(min_track);+            wide_groups.entry((w * 1000.0).round() as i64).or_default().push(net.clone());+        }+    } else if let Some(a) = spec["wideNets"].as_array() {+        let def_w = spec["wideTrack"].as_f64().unwrap_or(0.5).max(min_track);+        for n in a.iter().filter_map(|v| v.as_str()) {+            if assigned.contains(n) { continue; }+            wide_groups.entry((def_w * 1000.0).round() as i64).or_default().push(n.to_string());+        }+    }+    let multi_wide = wide_groups.len() > 1;+    for (w_um, mut nets) in wide_groups {+        nets.sort();+        let w = w_um as f64 / 1000.0;+        let name = if multi_wide { format!("POWER_{w_um}UM") } else { "POWER_WIDE".into() };+        let clr = nets.iter()+            .filter_map(|n| spec["netClearance"][n].as_f64())+            .fold(base_clearance, f64::max);+        for n in &nets { assigned.insert(n.clone()); }+        classes.push(NetClassSpec {+            name,+            kind: "power".into(),+            nets,+            min_width_mm: r4(w),+            opt_width_mm: Some(r4(w)),+            max_width_mm: None,+            clearance_mm: r4(clr),+            via_diameter_mm: Some(0.8),+            via_drill_mm: Some(0.4),+            diff_pair_gap_mm: None,+            diff_pair_gap_min_mm: None,+            diff_pair_gap_max_mm: None,+            diff_pair_uncoupled_mm: None,+            max_skew_mm: None,+            is_diff_pair: false,+        });+    }++    let mut mid_nets: Vec<String> = Vec::new();+    let mut mid_w = spec["midTrack"].as_f64().unwrap_or(0.35);+    if let Some(o) = spec["midNets"].as_object() {+        for (net, v) in o {+            if assigned.contains(net) { continue; }+            if let Some(w) = v.as_f64() { mid_w = mid_w.max(w); }+            mid_nets.push(net.clone());+        }+    } else if let Some(a) = spec["midNets"].as_array() {+        for n in a.iter().filter_map(|v| v.as_str()) {+            if assigned.contains(n) { continue; }+            mid_nets.push(n.to_string());+        }+    }+    if !mid_nets.is_empty() {+        mid_nets.sort();+        for n in &mid_nets { assigned.insert(n.clone()); }+        classes.push(NetClassSpec {+            name: "POWER_MID".into(),+            kind: "power-mid".into(),+            nets: mid_nets,+            min_width_mm: r4(mid_w.max(min_track)),+            opt_width_mm: Some(r4(mid_w.max(min_track))),+            max_width_mm: None,+            clearance_mm: r4(base_clearance),+            via_diameter_mm: Some(0.7),+            via_drill_mm: Some(0.35),+            diff_pair_gap_mm: None,+            diff_pair_gap_min_mm: None,+            diff_pair_gap_max_mm: None,+            diff_pair_uncoupled_mm: None,+            max_skew_mm: None,+            is_diff_pair: false,+        });+    }++    // High-current loads not already in wideNets/midNets (>= 1.0 A)+    let mut load_nets: Vec<String> = Vec::new();+    if let Some(loads) = spec["loads"].as_object() {+        for (net, entry) in loads {+            if is_gnd(net) || assigned.contains(net) { continue; }+            let amps = entry["amps"].as_f64().unwrap_or(0.0);+            if amps >= 1.0 {+                load_nets.push(net.clone());+            }+        }+    }+    if !load_nets.is_empty() {+        load_nets.sort();+        for n in &load_nets { assigned.insert(n.clone()); }+        classes.push(NetClassSpec {+            name: "POWER_LOAD".into(),+            kind: "power-load".into(),+            nets: load_nets,+            min_width_mm: r4(0.5_f64.max(base_track)),+            opt_width_mm: Some(r4(0.5_f64.max(base_track))),+            max_width_mm: None,+            clearance_mm: r4(base_clearance),+            via_diameter_mm: Some(0.8),+            via_drill_mm: Some(0.4),+            diff_pair_gap_mm: None,+            diff_pair_gap_min_mm: None,+            diff_pair_gap_max_mm: None,+            diff_pair_uncoupled_mm: None,+            max_skew_mm: None,+            is_diff_pair: false,+        });+    }++    // 4. Sensitive / analog and switching / clock classes+    let mut sensitive: 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()) {+            if !assigned.contains(n) { sensitive.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()) {+                    if !assigned.contains(n) { sensitive.insert(n.to_string()); }+                }+            }+        }+    }+    if !sensitive.is_empty() {+        let nets: Vec<String> = sensitive.into_iter().collect();+        for n in &nets { assigned.insert(n.clone()); }+        classes.push(NetClassSpec {+            name: "SENSITIVE_ANALOG".into(),+            kind: "sensitive".into(),+            nets,+            min_width_mm: r4(base_track),+            opt_width_mm: Some(r4(base_track)),+            max_width_mm: None,+            clearance_mm: r4((base_clearance * 1.5).max(0.3)),+            via_diameter_mm: Some(0.6),+            via_drill_mm: Some(0.3),+            diff_pair_gap_mm: None,+            diff_pair_gap_min_mm: None,+            diff_pair_gap_max_mm: None,+            diff_pair_uncoupled_mm: None,+            max_skew_mm: None,+            is_diff_pair: false,+        });+    }++    let mut sw_clk: BTreeSet<String> = BTreeSet::new();+    if let Some(o) = spec["switching"].as_object() {+        for k in o.keys() { if !assigned.contains(k) { sw_clk.insert(k.clone()); } }+    }+    for n in spec["switchNodes"].as_array().into_iter().flatten().filter_map(|v| v.as_str()) {+        if !assigned.contains(n) { sw_clk.insert(n.to_string()); }+    }+    if let Some(o) = spec["clocks"].as_object() {+        for k in o.keys() { if !assigned.contains(k) { sw_clk.insert(k.clone()); } }+    }+    if !sw_clk.is_empty() {+        let nets: Vec<String> = sw_clk.into_iter().collect();+        classes.push(NetClassSpec {+            name: "SWITCH_CLK".into(),+            kind: "aggressor".into(),+            nets,+            min_width_mm: r4(base_track),+            opt_width_mm: Some(r4(base_track)),+            max_width_mm: None,+            clearance_mm: r4(base_clearance),+            via_diameter_mm: Some(0.6),+            via_drill_mm: Some(0.3),+            diff_pair_gap_mm: None,+            diff_pair_gap_min_mm: None,+            diff_pair_gap_max_mm: None,+            diff_pair_uncoupled_mm: None,+            max_skew_mm: None,+            is_diff_pair: false,+        });+    }++    // Inter-class clearance: sensitive vs switching/clock, plus explicit `spec.clearances`+    if classes.iter().any(|c| c.name == "SENSITIVE_ANALOG") && classes.iter().any(|c| c.name == "SWITCH_CLK") {+        inter_clearances.push(ClearancePair {+            class_a: "SENSITIVE_ANALOG".into(),+            class_b: "SWITCH_CLK".into(),+            min_mm: r4((base_clearance * 2.0).max(0.4)),+            why: "keep switching/clock aggressors away from sensitive analog nets".into(),+        });+    }+    if let Some(clrs) = spec["clearances"].as_array() {+        for c in clrs {+            if let (Some(a), Some(b), Some(mm)) = (c["classA"].as_str(), c["classB"].as_str(), c["minMm"].as_f64()) {+                if mm > 0.0 {+                    inter_clearances.push(ClearancePair {+                        class_a: a.to_string(),+                        class_b: b.to_string(),+                        min_mm: r4(mm),+                        why: c["why"].as_str().unwrap_or("spec.clearances").to_string(),+                    });+                }+            }+        }+    }++    NetClassPlan {+        base_clearance_mm: base_clearance,+        base_track_mm: base_track,+        classes,+        inter_class_clearances: inter_clearances,+        notes,+    }+}++/// Render the managed `.kicad_dru` block for `plan` (validated by `checks::dru_syntax`).+pub fn render_kicad_dru_block(plan: &NetClassPlan) -> String {+    let mut s = String::new();+    s.push_str(DRU_BEGIN);+    s.push('\n');+    for c in &plan.classes {+        let rbase = clean_class_token(&c.name).to_ascii_lowercase();+        let cond = format!("A.NetClass == '{}'", c.name);+        if c.is_diff_pair {+            let opt = c.opt_width_mm.unwrap_or(c.min_width_mm);+            let max_w = c.max_width_mm.unwrap_or(opt * 1.15);+            s.push_str(&format!(+                "(rule \"aiflow_nc_{rbase}_width\"\n  (condition \"{cond}\")\n  (constraint track_width (min {:.4}mm) (opt {:.4}mm) (max {:.4}mm))\n)\n",+                c.min_width_mm, opt, max_w+            ));+            if let (Some(gmin), Some(gopt), Some(gmax)) = (c.diff_pair_gap_min_mm, c.diff_pair_gap_mm, c.diff_pair_gap_max_mm) {+                s.push_str(&format!(+                    "(rule \"aiflow_nc_{rbase}_gap\"\n  (condition \"{cond}\")\n  (constraint diff_pair_gap (min {:.4}mm) (opt {:.4}mm) (max {:.4}mm))\n)\n",+                    gmin, gopt, gmax+                ));+            }+            if let Some(unc) = c.diff_pair_uncoupled_mm {+                s.push_str(&format!(+                    "(rule \"aiflow_nc_{rbase}_uncoupled\"\n  (condition \"{cond}\")\n  (constraint diff_pair_uncoupled (max {:.3}mm))\n)\n",+                    unc+                ));+            }+            if let Some(sk) = c.max_skew_mm {+                s.push_str(&format!(+                    "(rule \"aiflow_nc_{rbase}_skew\"\n  (condition \"{cond}\")\n  (constraint skew (max {:.3}mm))\n)\n",+                    sk+                ));+            }+        } else {+            s.push_str(&format!(+                "(rule \"aiflow_nc_{rbase}_width\"\n  (condition \"{cond}\")\n  (constraint track_width (min {:.4}mm))\n)\n",+                c.min_width_mm+            ));+        }+        if c.clearance_mm > plan.base_clearance_mm + 1e-6 {+            s.push_str(&format!(+                "(rule \"aiflow_nc_{rbase}_clearance\"\n  (condition \"{cond}\")\n  (constraint clearance (min {:.4}mm))\n)\n",+                c.clearance_mm+            ));+        }+    }+    for (i, ic) in plan.inter_class_clearances.iter().enumerate() {+        let a = clean_class_token(&ic.class_a).to_ascii_lowercase();+        let b = clean_class_token(&ic.class_b).to_ascii_lowercase();+        s.push_str(&format!(+            "(rule \"aiflow_nc_clr_{i}_{a}_{b}\"\n  (condition \"A.NetClass == '{}' && B.NetClass == '{}'\")\n  (constraint clearance (min {:.4}mm))\n)\n",+            ic.class_a, ic.class_b, ic.min_mm+        ));+    }+    s.push_str(DRU_END);+    s.push('\n');+    s+}++/// Replace or append the managed netclasses block in `.kicad_dru` text without touching any user+/// or fab rules outside `# BEGIN/END adom-aiflow netclasses`.+pub fn merge_kicad_dru_text(existing: Option<&str>, plan: &NetClassPlan) -> Result<String, String> {+    let block = render_kicad_dru_block(plan);+    let base = match existing {+        Some(t) if !t.trim().is_empty() => t.to_string(),+        _ => "(version 1)\n".to_string(),+    };+    let merged = if let (Some(b_idx), Some(e_idx)) = (base.find(DRU_BEGIN), base.find(DRU_END)) {+        if e_idx >= b_idx {+            let after_end = base[e_idx..].find('\n').map(|o| e_idx + o + 1).unwrap_or(base.len());+            format!("{}{}{}", &base[..b_idx], block, &base[after_end..])+        } else {+            format!("{}\n{}", base.trim_end(), block)+        }+    } else {+        format!("{}\n\n{}", base.trim_end(), block)+    };+    crate::checks::dru_syntax(&merged)?;+    Ok(merged)+}++/// Merge derived net classes into `<project>.kicad_pro` JSON (preserving `"Default"` and any+/// non-managed user classes and patterns).+pub fn merge_kicad_pro_json(existing: Option<Value>, pro_filename: &str, plan: &NetClassPlan) -> Value {+    let mut pro = match existing {+        Some(Value::Object(o)) => Value::Object(o),+        _ => json!({"meta": {"filename": pro_filename, "version": 1}}),+    };+    if !pro["net_settings"].is_object() {+        pro["net_settings"] = json!({});+    }+    let managed_names: BTreeSet<String> = plan.classes.iter().map(|c| c.name.clone()).collect();+    let managed_nets: BTreeSet<String> = plan.classes.iter().flat_map(|c| c.nets.iter().cloned()).collect();++    // Preserve Default and user-defined classes+    let mut classes: Vec<Value> = pro["net_settings"]["classes"].as_array().cloned().unwrap_or_default()+        .into_iter()+        .filter(|c| c["name"].as_str().map(|n| !managed_names.contains(n)).unwrap_or(true))+        .collect();+    if !classes.iter().any(|c| c["name"] == "Default") {+        classes.insert(0, json!({+            "name": "Default",+            "clearance": plan.base_clearance_mm,+            "track_width": plan.base_track_mm,+            "via_diameter": 0.6,+            "via_drill": 0.3,+        }));+    }+    for c in &plan.classes {+        let mut obj = serde_json::Map::new();+        obj.insert("name".into(), json!(c.name));+        obj.insert("clearance".into(), json!(c.clearance_mm));+        obj.insert("track_width".into(), json!(c.opt_width_mm.unwrap_or(c.min_width_mm)));+        obj.insert("via_diameter".into(), json!(c.via_diameter_mm.unwrap_or(0.6)));+        obj.insert("via_drill".into(), json!(c.via_drill_mm.unwrap_or(0.3)));+        if c.is_diff_pair {+            obj.insert("diff_pair_width".into(), json!(c.opt_width_mm.unwrap_or(c.min_width_mm)));+            if let Some(g) = c.diff_pair_gap_mm {+                obj.insert("diff_pair_gap".into(), json!(g));+            }+        }+        classes.push(Value::Object(obj));+    }+    pro["net_settings"]["classes"] = Value::Array(classes);++    // Preserve user patterns not naming our managed classes or nets+    let mut patterns: Vec<Value> = pro["net_settings"]["netclass_patterns"].as_array().cloned().unwrap_or_default()+        .into_iter()+        .filter(|p| {+            let nc = p["netclass"].as_str().unwrap_or("");+            let pat = p["pattern"].as_str().unwrap_or("");+            !managed_names.contains(nc) && !managed_nets.contains(pat)+        })+        .collect();+    for c in &plan.classes {+        for net in &c.nets {+            patterns.push(json!({"netclass": c.name, "pattern": net}));+        }+    }+    pro["net_settings"]["netclass_patterns"] = Value::Array(patterns);+    pro+}++/// Write both `<board>.kicad_pro` and `<board>.kicad_dru` managed net classes.+pub fn sync_kicad(board_path: &str, plan: &NetClassPlan) -> Result<(PathBuf, PathBuf), String> {+    let bp = Path::new(board_path);+    let pro_path = bp.with_extension("kicad_pro");+    let dru_path = bp.with_extension("kicad_dru");+    let existing_pro = std::fs::read_to_string(&pro_path).ok().and_then(|t| serde_json::from_str::<Value>(&t).ok());+    let pro_name = pro_path.file_name().and_then(|s| s.to_str()).unwrap_or("board.kicad_pro");+    let next_pro = merge_kicad_pro_json(existing_pro, pro_name, plan);+    let pro_text = serde_json::to_string_pretty(&next_pro).map_err(|e| e.to_string())?;+    std::fs::write(&pro_path, pro_text).map_err(|e| format!("{}: {e}", pro_path.display()))?;++    let existing_dru = std::fs::read_to_string(&dru_path).ok();+    let next_dru = merge_kicad_dru_text(existing_dru.as_deref(), plan)?;+    std::fs::write(&dru_path, next_dru).map_err(|e| format!("{}: {e}", dru_path.display()))?;+    Ok((pro_path, dru_path))+}++/// Build the Altium PCB Design Rules payload (Width per net class, Electrical Clearance matrix,+/// Differential Pairs Routing width/gap/max uncoupled length, Matched Net Lengths).+pub fn altium_rules_payload(plan: &NetClassPlan) -> Value {+    let mut net_classes = Vec::new();+    let mut width_rules = Vec::new();+    let mut clearance_matrix = Vec::new();+    let mut diff_pair_rules = Vec::new();+    let mut matched_length_rules = Vec::new();++    for c in &plan.classes {+        net_classes.push(json!({"name": c.name, "kind": c.kind, "nets": c.nets}));+        width_rules.push(json!({+            "name": format!("Width_{}", c.name),+            "scope": format!("InNetClass('{}')", c.name),+            "minMm": c.min_width_mm,+            "preferredMm": c.opt_width_mm.unwrap_or(c.min_width_mm),+            "maxMm": c.max_width_mm.unwrap_or((c.opt_width_mm.unwrap_or(c.min_width_mm) * 2.0).max(2.0)),+        }));+        if c.clearance_mm > plan.base_clearance_mm + 1e-6 {+            clearance_matrix.push(json!({+                "name": format!("Clearance_{}", c.name),+                "scopeA": format!("InNetClass('{}')", c.name),+                "scopeB": "All",+                "minMm": c.clearance_mm,+            }));+        }+        if c.is_diff_pair {+            diff_pair_rules.push(json!({+                "name": format!("DiffPair_{}", c.name),+                "scope": format!("InDifferentialPairClass('{}')", c.name),+                "nets": c.nets,+                "minWidthMm": c.min_width_mm,+                "preferredWidthMm": c.opt_width_mm.unwrap_or(c.min_width_mm),+                "maxWidthMm": c.max_width_mm.unwrap_or(c.min_width_mm),+                "minGapMm": c.diff_pair_gap_min_mm,+                "preferredGapMm": c.diff_pair_gap_mm,+                "maxGapMm": c.diff_pair_gap_max_mm,+                "maxUncoupledLengthMm": c.diff_pair_uncoupled_mm,+            }));+            if let Some(sk) = c.max_skew_mm {+                matched_length_rules.push(json!({+                    "name": format!("MatchedLength_{}", c.name),+                    "scope": format!("InDifferentialPairClass('{}')", c.name),+                    "toleranceMm": sk,+                }));+            }+        }+    }+    for ic in &plan.inter_class_clearances {+        clearance_matrix.push(json!({+            "name": format!("Clearance_{}_{}", ic.class_a, ic.class_b),+            "scopeA": format!("InNetClass('{}')", ic.class_a),+            "scopeB": format!("InNetClass('{}')", ic.class_b),+            "minMm": ic.min_mm,+            "why": ic.why,+        }));+    }++    json!({+        "schema": "aiflow-altium-rules/v1",+        "netClasses": net_classes,+        "routingWidthRules": width_rules,+        "clearanceMatrix": clearance_matrix,+        "diffPairRules": diff_pair_rules,+        "matchedLengthRules": matched_length_rules,+    })+}++/// Verify that every `impedanceTargets` pair/net and `wideNets` entry in `spec` has a matching+/// non-`Default` native net class in `<board>.kicad_pro` and matching rules in `<board>.kicad_dru`.+pub fn verify_kicad(board_path: &str, board: Option<&Board>, spec: &Value) -> Value {+    let plan = derive(board, spec);+    let required: Vec<&NetClassSpec> = plan.classes.iter().filter(|c| c.kind == "diff-pair" || c.kind == "impedance" || c.kind == "power" || c.kind == "high-voltage").collect();+    if required.is_empty() {+        return json!({"pass": true, "checked": 0, "findings": []});+    }++    let bp = Path::new(board_path);+    let pro_path = bp.with_extension("kicad_pro");+    let dru_path = bp.with_extension("kicad_dru");+    let mut findings = Vec::new();++    let pro = std::fs::read_to_string(&pro_path).ok().and_then(|t| serde_json::from_str::<Value>(&t).ok());+    let dru = std::fs::read_to_string(&dru_path).ok();++    if pro.is_none() {+        findings.push(format!("missing {}: native KiCad net classes are not synced (every net falls back to Default); run `adom-aiflow rules sync`", pro_path.display()));+    } else if let Some(p) = &pro {+        let classes: BTreeMap<String, &Value> = p["net_settings"]["classes"].as_array().into_iter().flatten()+            .filter_map(|c| Some((c["name"].as_str()?.to_string(), c)))+            .collect();+        let mut net_to_class: BTreeMap<String, String> = BTreeMap::new();+        for pat in p["net_settings"]["netclass_patterns"].as_array().into_iter().flatten() {+            if let (Some(nc), Some(pat_s)) = (pat["netclass"].as_str(), pat["pattern"].as_str()) {+                net_to_class.insert(pat_s.to_string(), nc.to_string());+            }+        }+        for req in &required {+            for net in &req.nets {+                match net_to_class.get(net) {+                    None => findings.push(format!("net {net} (expected class {}) has no native net class assignment in {} (falls back to Default)", req.name, pro_path.display())),+                    Some(nc) if nc == "Default" => findings.push(format!("net {net} is assigned to Default in {} instead of a {} net class", pro_path.display(), req.kind)),+                    Some(nc) => {+                        match classes.get(nc) {+                            None => findings.push(format!("net {net} references missing net class {nc:?} in {}", pro_path.display())),+                            Some(cls_obj) => {+                                let actual_w = cls_obj["track_width"].as_f64().unwrap_or(0.0);+                                let exp_w = req.opt_width_mm.unwrap_or(req.min_width_mm);+                                if req.kind == "power" && actual_w + 1e-4 < req.min_width_mm {+                                    findings.push(format!("net class {nc} for {net} has track_width {actual_w:.3} mm < spec minimum {:.3} mm (drifted)", req.min_width_mm));+                                } else if req.is_diff_pair && (actual_w - exp_w).abs() > (exp_w * 0.15).max(0.05) {+                                    findings.push(format!("diff-pair net class {nc} for {net} has track_width {actual_w:.3} mm vs spec target {exp_w:.3} mm (drifted)"));+                                }+                                if let Some(exp_g) = req.diff_pair_gap_mm {+                                    let actual_g = cls_obj["diff_pair_gap"].as_f64().unwrap_or(0.0);+                                    if (actual_g - exp_g).abs() > (exp_g * 0.20).max(0.04) {+                                        findings.push(format!("diff-pair net class {nc} for {net} has diff_pair_gap {actual_g:.3} mm vs spec target {exp_g:.3} mm (drifted)"));+                                    }+                                }+                            }+                        }+                    }+                }+            }+        }+    }++    if let Some(d) = &dru {+        if let Err(e) = crate::checks::dru_syntax(d) {+            findings.push(format!("{} syntax error: {e}", dru_path.display()));+        } else {+            for req in &required {+                let needle = format!("A.NetClass == '{}'", req.name);+                if !d.contains(&needle) {+                    findings.push(format!("{} has no custom rule for net class {} (run `adom-aiflow rules sync`)", dru_path.display(), req.name));+                }+            }+        }+    } else {+        findings.push(format!("missing {}: class-scoped KiCad DRC rules are not synced (run `adom-aiflow rules sync`)", dru_path.display()));+    }++    json!({+        "pass": findings.is_empty(),+        "checked": required.len(),+        "classes": plan.classes.iter().map(|c| json!({"name": c.name, "kind": c.kind, "nets": c.nets, "minWidthMm": c.min_width_mm, "clearanceMm": c.clearance_mm, "diffPairGapMm": c.diff_pair_gap_mm})).collect::<Vec<_>>(),+        "findings": findings,+    })+}++#[cfg(test)]+mod tests {+    use super::*;++    #[test]+    fn derives_power_diffpair_hv_and_sensitive_classes_and_syncs_kicad_and_altium() {+        let spec = json!({+            "clearance": 0.15,+            "minTrackWidth": 0.127,+            "track": 0.2,+            "wideNets": {"VIN": 0.8, "VOUT": 0.8},+            "midNets": ["GATE"],+            "voltages": {"HV_BUS": 60.0, "VIN": 12.0},+            "sensitiveNets": ["ADC_IN"],+            "clocks": {"SPI_CLK": {"freqHz": 24_000_000}},+            "impedanceTargets": {+                "USB": {"pair": ["USB_D+", "USB_D-"], "targetDiffOhms": 90, "widthMm": 0.35, "gapMm": 0.20, "maxSkewMm": 0.5, "maxUncontrolledMm": 3.0}+            }+        });+        let plan = derive(None, &spec);+        let names: Vec<&str> = plan.classes.iter().map(|c| c.name.as_str()).collect();+        assert!(names.contains(&"DIFF_USB"), "{names:?}");+        assert!(names.contains(&"POWER_WIDE"), "{names:?}");+        assert!(names.contains(&"POWER_MID"), "{names:?}");+        assert!(names.contains(&"HV_100V"), "{names:?}");+        assert!(names.contains(&"SENSITIVE_ANALOG"), "{names:?}");+        assert!(names.contains(&"SWITCH_CLK"), "{names:?}");+        assert_eq!(plan.inter_class_clearances.len(), 1);++        // Merge into existing DRU preserving user custom rules+        let user_dru = "(version 1)\n(rule \"user_custom\" (constraint clearance (min 0.15mm)))\n";+        let merged = merge_kicad_dru_text(Some(user_dru), &plan).unwrap();+        assert!(merged.contains("user_custom"));+        assert!(merged.contains("aiflow_nc_diff_usb_gap"));+        assert!(merged.contains("aiflow_nc_power_wide_width"));+        // Re-syncing is idempotent and does not duplicate the managed section+        let merged2 = merge_kicad_dru_text(Some(&merged), &plan).unwrap();+        assert_eq!(merged, merged2);++        // Altium rules payload carries width, clearance matrix, diff pair, and matched length+        let alt = altium_rules_payload(&plan);+        assert!(!alt["routingWidthRules"].as_array().unwrap().is_empty());+        assert!(!alt["clearanceMatrix"].as_array().unwrap().is_empty());+        assert_eq!(alt["diffPairRules"].as_array().unwrap().len(), 1);+        assert_eq!(alt["matchedLengthRules"].as_array().unwrap().len(), 1);+    }++    #[test]+    fn verify_kicad_catches_missing_and_drifted_netclasses_then_passes_after_sync() {+        let td = std::env::temp_dir().join(format!("aiflow-nc-test-{}", std::process::id()));+        let _ = std::fs::create_dir_all(&td);+        let bp = td.join("board.kicad_pcb");+        std::fs::write(&bp, "(kicad_pcb)").unwrap();+        let spec = json!({+            "clearance": 0.15, "minTrackWidth": 0.127, "track": 0.2,+            "wideNets": {"VIN": 0.8},+            "impedanceTargets": {"USB": {"pair": ["USB_D+", "USB_D-"], "targetDiffOhms": 90, "widthMm": 0.35, "gapMm": 0.20}}+        });+        let bad = verify_kicad(bp.to_str().unwrap(), None, &spec);+        assert_eq!(bad["pass"], false, "{bad}");++        let plan = derive(None, &spec);+        sync_kicad(bp.to_str().unwrap(), &plan).unwrap();+        let good = verify_kicad(bp.to_str().unwrap(), None, &spec);+        assert_eq!(good["pass"], true, "{good}");++        // Drift track_width in .kicad_pro -> verify_kicad must catch it+        let pro_p = bp.with_extension("kicad_pro");+        let mut pro: Value = serde_json::from_str(&std::fs::read_to_string(&pro_p).unwrap()).unwrap();+        for c in pro["net_settings"]["classes"].as_array_mut().unwrap() {+            if c["name"] == "POWER_WIDE" { c["track_width"] = json!(0.2); }+        }+        std::fs::write(&pro_p, serde_json::to_string_pretty(&pro).unwrap()).unwrap();+        let drifted = verify_kicad(bp.to_str().unwrap(), None, &spec);+        assert_eq!(drifted["pass"], false, "{drifted}");+        let _ = std::fs::remove_dir_all(&td);+    }+}
crates/aiflow-bridge/src/altium.rs+14
@@ -58,6 +58,20 @@ pub fn to_kicad_state(a: &Value) -> Value {            "unconnected": a["unconnected"], "elements": elements, "source": "altium"}) } +/// Build the `altium_set_design_rules` bridge payload combining board targeting with the canonical+/// net-class, width, clearance matrix, differential-pair, and matched-length rules (issue #216).+pub fn design_rules_request(board_path: &str, rules_payload: &Value) -> Value {+    json!({+        "expectPath": board_path,+        "schema": rules_payload["schema"],+        "netClasses": rules_payload["netClasses"],+        "routingWidthRules": rules_payload["routingWidthRules"],+        "clearanceMatrix": rules_payload["clearanceMatrix"],+        "diffPairRules": rules_payload["diffPairRules"],+        "matchedLengthRules": rules_payload["matchedLengthRules"],+    })+}+ impl AltiumEda {     fn read(&self, t: &dyn Transport) -> Value {         let r = t.send("altium_routing_state", &json!({"expectPath": self.path}));
skills/aiflow-schematic-to-board/SKILL.md+1−1
@@ -70,7 +70,7 @@ It creates the nets, loads each footprint (`pcbnew.FootprintLoad(dir, name)`, pr  - `GetFieldByName` is gone. `fp.SetField(name, value)` to set; iterate `fp.GetFields()` and match `f.GetName()` to hide or restyle. - Model paths changed through `fp.Models()` (`m.m_Filename = ...`) did not persist in the saved board. Rewrite the `(model ...)` entries in the saved file instead (`kicad/tools/set_models.py`: path, offset, and the -90 degree X rotation for Y-up models). Do this only in the build, before the board is opened in KiCad: KiCad Bridge has no model-binding verb yet (kicad-bridge#101), and a saved-file rewrite is not a live edit. Prove the result with `kicad_model_check` (its `modelBindings`) and a 3D frame; a body hidden by a viewer class is a `kicad_3d_viewer_settings` matter, never a reason to change BOM, position-file or DNP flags.-- The netclass API moves between versions: wrap it in try/except and let the `.kicad_dru` carry the limits.+- Native DRC net classes: run `adom-aiflow rules sync` (also auto-run by `rules use` when `spec.json` defines `wideNets`, `midNets`, `impedanceTargets`, voltages > 30 V, or sensitive/clock nets) to write canonical net classes into `<project>.kicad_pro` (`net_settings.classes` + `netclass_patterns`), emit class-scoped rules into a managed section of `<project>.kicad_dru` without clobbering user custom rules, and generate the Altium design-rules payload (`altium-design-rules.json`). `rules check` and `gate` verify that power and impedance nets stay assigned to matching native net classes rather than falling back to `Default`. - **One IPC socket.** KiCad's IPC API server belongs to the first KiCad process that opened it. A second editor (another board, another user's session) answers IPC for the wrong board or not at all; `capture open` reports `board_mismatch`. Save and close only your own conflicting editors, reopen the intended board first, and never close someone else's work. - **Footprint fields are refused over IPC** in 10.0.5 (`native_field_update_unsupported`): references, values and their text size or position cannot be edited live. Do them in build_board.py, or offline: close the clean editor, edit the saved board, reopen, then refresh both 2D and 3D views. 
tests/netclasses-drc-workflow.pyadded+133
@@ -0,0 +1,133 @@+"""Native DRC net-class sync end to end (issue #216):+- rules sync derives POWER, DIFF_*, HV_*, SENSITIVE_ANALOG, SWITCH_CLK classes from spec.json+- Writes .kicad_pro (net_settings.classes + netclass_patterns), managed .kicad_dru section+  (preserving user custom rules), and Altium design rules JSON payload+- rules check catches missing and drifted native net classes -> passes after rules sync+- Real kicad-cli pcb drc catches narrow power traces and wrong diff-pair gaps once synced,+  and clears them once the copper is fixed+Usage: python3 tests/netclasses-drc-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_board(path, vin_w, usb_w, usb_gap):+    yp = 14.0 - (usb_w + usb_gap) / 2.0+    yn = 14.0 + (usb_w + usb_gap) / 2.0+    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 "VIN") (net 2 "USB_D+") (net 3 "USB_D-") (net 4 "HV_BUS") (net 5 "ADC_IN") (net 6 "SPI_CLK") '+        '(footprint "T:J1" (layer "F.Cu") (at 5 10) (property "Reference" "J1") '+        f'(pad "1" smd rect (at 0 -2) (size 1.2 1.0) (layers "F.Cu") (net 1 "VIN")) '+        f'(pad "2" smd rect (at 0 {yp - 10:.4f}) (size 0.8 0.35) (layers "F.Cu") (net 2 "USB_D+")) '+        f'(pad "3" smd rect (at 0 {yn - 10:.4f}) (size 0.8 0.35) (layers "F.Cu") (net 3 "USB_D-"))) '+        '(footprint "T:U1" (layer "F.Cu") (at 35 10) (property "Reference" "U1") '+        f'(pad "1" smd rect (at 0 -2) (size 1.2 1.0) (layers "F.Cu") (net 1 "VIN")) '+        f'(pad "2" smd rect (at 0 {yp - 10:.4f}) (size 0.8 0.35) (layers "F.Cu") (net 2 "USB_D+")) '+        f'(pad "3" smd rect (at 0 {yn - 10:.4f}) (size 0.8 0.35) (layers "F.Cu") (net 3 "USB_D-"))) '+        f'(segment (start 5 8) (end 35 8) (width {vin_w:.4f}) (layer "F.Cu") (net 1)) '+        f'(segment (start 5 {yp:.4f}) (end 35 {yp:.4f}) (width {usb_w:.4f}) (layer "F.Cu") (net 2)) '+        f'(segment (start 5 {yn:.4f}) (end 35 {yn:.4f}) (width {usb_w:.4f}) (layer "F.Cu") (net 3)) '+        '(gr_rect (start 0 0) (end 40 20) (layer "Edge.Cuts") (stroke (width 0.1) (type solid))))'+    )+++with tempfile.TemporaryDirectory(prefix='aiflow-netclasses-') 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', 'netclasses-test', *args],+            env=env, capture_output=True, text=True, timeout=120+        )++    b = p / 'board.kicad_pcb'+    # Broken copper: VIN is only 0.2 mm (needs >= 0.8 mm), USB pair gap is 0.60 mm (target is 0.20 mm)+    make_board(b, vin_w=0.20, usb_w=0.35, usb_gap=0.60)+    # Seed a fab .kicad_dru with a user custom rule+    dru_path = b.with_suffix('.kicad_dru')+    dru_path.write_text(+        '(version 1)\n'+        '# adom-aiflow rules: jlcpcb 4L (from test)\n'+        '(rule "user_custom_keep" (constraint clearance (min 0.127mm)))\n'+    )+    spec = {+        "clearance": 0.127, "minTrackWidth": 0.127, "track": 0.2, "copperUm": 35,+        "fab": {"rules": "jlcpcb-4L"},+        "wideNets": {"VIN": 0.8},+        "voltages": {"HV_BUS": 60.0, "VIN": 12.0},+        "sensitiveNets": ["ADC_IN"],+        "clocks": {"SPI_CLK": {"freqHz": 24_000_000}},+        "impedanceTargets": {+            "USB": {"pair": ["USB_D+", "USB_D-"], "targetDiffOhms": 90, "gapMm": 0.20, "maxSkewMm": 0.5, "maxUncontrolledMm": 3.0}+        }+    }+    sp = p / 'spec.json'+    sp.write_text(json.dumps(spec))++    # 1. Before rules sync: rules check flags missing native net classes+    r_pre = call(p / 'none', 'rules', 'check', '--profile', 'jlcpcb-4L', '--board', str(b), '--spec', str(sp))+    assert 'native net classes out of sync' in r_pre.stdout, r_pre.stdout+    print('  [1/5] rules check catches missing native net classes before sync')++    # 2. rules sync writes .kicad_pro, managed .kicad_dru block (preserving user rule), and Altium rules JSON+    alt_out = p / 'altium-rules.json'+    r_sync = call(p / 'none', 'rules', 'sync', '--board', str(b), '--spec', str(sp), '--altium-out', str(alt_out))+    assert r_sync.returncode == 0, r_sync.stdout + r_sync.stderr+    pro = json.loads(b.with_suffix('.kicad_pro').read_text())+    cls_names = {c['name']: c for c in pro['net_settings']['classes']}+    assert {'Default', 'POWER_WIDE', 'DIFF_USB', 'HV_100V', 'SENSITIVE_ANALOG', 'SWITCH_CLK'} <= set(cls_names), cls_names.keys()+    dru_txt = dru_path.read_text()+    assert 'user_custom_keep' in dru_txt and '# BEGIN adom-aiflow netclasses' in dru_txt and 'aiflow_nc_diff_usb_gap' in dru_txt, dru_txt+    alt = json.loads(alt_out.read_text())+    assert alt['schema'] == 'aiflow-altium-rules/v1' and alt['diffPairRules'] and alt['matchedLengthRules'] and alt['clearanceMatrix'], alt+    print('  [2/5] rules sync wrote .kicad_pro, managed .kicad_dru preserving user rules, and Altium rules payload')++    # 3. rules check passes after sync+    r_post = call(p / 'none', 'rules', 'check', '--profile', 'jlcpcb-4L', '--board', str(b), '--spec', str(sp))+    assert r_post.returncode == 0 and r_post.stdout.startswith('OK:'), r_post.stdout+    print('  [3/5] rules check passes once native net classes are synced')++    # 4. Real kicad-cli pcb drc catches narrow VIN and wide USB gap -> fixed board clears both+    if shutil.which('kicad-cli'):+        drc_bad = p / 'drc-bad.json'+        subprocess.run(['kicad-cli', 'pcb', 'drc', '--format', 'json', '--output', str(drc_bad), str(b)], env=env, check=True, capture_output=True)+        v_bad = [v['type'] for v in json.loads(drc_bad.read_text()).get('violations', [])]+        assert 'track_width' in v_bad and 'diff_pair_gap_out_of_range' in v_bad, v_bad++        # Fix copper using the synced class optimal width and gap+        usb_w = cls_names['DIFF_USB']['diff_pair_width']+        usb_g = cls_names['DIFF_USB']['diff_pair_gap']+        make_board(b, vin_w=0.85, usb_w=usb_w, usb_gap=usb_g)+        drc_good = p / 'drc-good.json'+        subprocess.run(['kicad-cli', 'pcb', 'drc', '--format', 'json', '--output', str(drc_good), str(b)], env=env, check=True, capture_output=True)+        v_good = [v['type'] for v in json.loads(drc_good.read_text()).get('violations', [])]+        assert 'track_width' not in v_good and 'diff_pair_gap_out_of_range' not in v_good, v_good+        print('  [4/5] real kicad-cli pcb drc caught narrow VIN + wrong USB gap, and cleared both when fixed')+    else:+        print('  [4/5] SKIP kicad-cli not on PATH')++    # 5. Drift in .kicad_pro is caught by rules check+    for c in pro['net_settings']['classes']:+        if c['name'] == 'POWER_WIDE':+            c['track_width'] = 0.2+    b.with_suffix('.kicad_pro').write_text(json.dumps(pro, indent=2))+    r_drift = call(p / 'none', 'rules', 'check', '--profile', 'jlcpcb-4L', '--board', str(b), '--spec', str(sp))+    assert 'drifted' in r_drift.stdout.lower(), r_drift.stdout+    print('  [5/5] rules check catches drifted native net class track_width')++print('PASS: native DRC net classes (.kicad_pro, managed .kicad_dru, Altium rules payload, and live kicad-cli DRC) verified.')