main
Colby Knox 0.2.73 source (not yet released, needs signing): fab_check JLCPCB preset, assembly_check, silk_designators, via_fence;… 4bafcdb
//! The board's fab-relevant minimums, measured from the live board, and how they compare with a fab's limits: the
//! numbers a fab's order form and capability page ask about, so the AI can check a board before ordering.
use serde_json::{json, Map, Value};

fn f(v: &Value) -> f64 { v.as_f64().unwrap_or(0.0) }
fn r3(v: f64) -> f64 { (v * 1000.0).round() / 1000.0 }

/// The outline's bounding box (x0, y0, x1, y1) in mm, arc edges included.
pub fn outline_bbox(state: &Value) -> Option<(f64, f64, f64, f64)> {
    let mut o: Vec<(f64, f64)> = state["outline"].as_array().cloned().unwrap_or_default().iter().map(|p| (f(&p[0]), f(&p[1]))).collect();
    // an arc edge bulges past its end points: sample it (the Bluetooth Sentinel example measured 80 x 4.5 mm by its
    // vertices alone)
    for e in state["outlineEdges"].as_array().cloned().unwrap_or_default() {
        if e["kind"].as_str() != Some("arc") { continue; }
        let (cx, cy, r) = (f(&e["center"][0]), f(&e["center"][1]), f(&e["radius"]));
        let (a1, mut a2) = (f(&e["angle1"]), f(&e["angle2"]));
        if a2 <= a1 { a2 += 360.0; }
        let mut a = a1;
        while a <= a2 + 1e-9 { o.push((cx + r * a.to_radians().cos(), cy + r * a.to_radians().sin())); a += 2.0; }
    }
    if o.is_empty() { return None; }
    let (x0, x1) = o.iter().fold((f64::MAX, f64::MIN), |a, p| (a.0.min(p.0), a.1.max(p.0)));
    let (y0, y1) = o.iter().fold((f64::MAX, f64::MIN), |a, p| (a.0.min(p.1), a.1.max(p.1)));
    Some((x0, y0, x1, y1))
}

/// The nearest copper (track, arc, pad, via) to the real outline, edge of copper to the outline's line, mm. Pour
/// boundaries are left out: they are drawn on the edge and Altium pulls the poured copper back by its rules.
pub fn edge_distance(state: &Value) -> Option<(f64, Value)> {
    let ring = crate::coppermap::outline_ring(state);
    if ring.len() < 3 { return None; }
    let seg = |x: f64, y: f64| -> f64 {
        (0..ring.len()).map(|k| {
            let (a, b) = (ring[k], ring[(k + 1) % ring.len()]);
            let (dx, dy) = (b.0 - a.0, b.1 - a.1);
            let l2 = dx * dx + dy * dy;
            let t = if l2 > 0.0 { (((x - a.0) * dx + (y - a.1) * dy) / l2).clamp(0.0, 1.0) } else { 0.0 };
            ((a.0 + t * dx - x).powi(2) + (a.1 + t * dy - y).powi(2)).sqrt()
        }).fold(f64::MAX, f64::min)
    };
    let copper = |l: &Value| l.as_str().map(|s| s.ends_with(".Cu")).unwrap_or(false);
    let mut pts: Vec<(f64, f64, f64, Value)> = Vec::new();
    for t in state["tracks"].as_array().cloned().unwrap_or_default().iter().filter(|t| copper(&t["layer"])) {
        for p in [&t["start"], &t["end"]] { pts.push((f(&p["x"]), f(&p["y"]), f(&t["width"]) / 2.0, json!({"track": t["net"], "layer": t["layer"]}))); }
    }
    for v in state["vias"].as_array().cloned().unwrap_or_default() { pts.push((f(&v["position"]["x"]), f(&v["position"]["y"]), f(&v["size"]) / 2.0, json!({"via": v["net"]}))); }
    for p in state["pads"].as_array().cloned().unwrap_or_default() {
        let (rf, nm) = (p["ref"].as_str().unwrap_or(""), p["name"].as_str().unwrap_or(""));
        pts.push((f(&p["x"]), f(&p["y"]), f(&p["sizeX"]).max(f(&p["sizeY"])) / 2.0, json!({"pad": if rf.is_empty() { nm.to_string() } else { format!("{rf}.{nm}") }})));
    }
    pts.into_iter().map(|(x, y, half, mut what)| { what["at"] = json!([r3(x), r3(y)]); (r3(seg(x, y) - half), what) })
        .min_by(|a, b| a.0.partial_cmp(&b.0).unwrap())
}

/// The smallest of each feature with where it is. Pure, for the tests.
pub fn measure(state: &Value) -> Map<String, Value> {
    let mut m = Map::new();
    let mut min_by = |key: &str, items: Vec<(f64, Value)>| {
        if let Some((v, at)) = items.into_iter().filter(|(v, _)| *v > 0.0).min_by(|a, b| a.0.partial_cmp(&b.0).unwrap()) {
            m.insert(key.into(), json!({"mm": r3(v), "at": at}));
        }
    };
    // copper only: outline and drawing lines on mechanical layers (L57...) are not tracks a fab etches
    let copper = |l: &Value| l.as_str().map(|s| s == "F.Cu" || s == "B.Cu" || (s.starts_with("In") && s.ends_with(".Cu"))).unwrap_or(false);
    min_by("track", state["tracks"].as_array().cloned().unwrap_or_default().iter().filter(|t| copper(&t["layer"])).map(|t| (f(&t["width"]), json!({"net": t["net"], "layer": t["layer"], "from": [t["start"]["x"], t["start"]["y"]]}))).collect());
    let vias = state["vias"].as_array().cloned().unwrap_or_default();
    min_by("viaDrill", vias.iter().map(|v| (f(&v["drill"]), json!({"net": v["net"], "at": [v["position"]["x"], v["position"]["y"]]}))).collect());
    min_by("viaDiameter", vias.iter().map(|v| (f(&v["size"]), json!({"net": v["net"], "at": [v["position"]["x"], v["position"]["y"]]}))).collect());
    min_by("viaAnnularRing", vias.iter().map(|v| ((f(&v["size"]) - f(&v["drill"])) / 2.0, json!({"net": v["net"], "at": [v["position"]["x"], v["position"]["y"]]}))).collect());
    let pads = state["pads"].as_array().cloned().unwrap_or_default();
    let drilled: Vec<&Value> = pads.iter().filter(|p| f(&p["drill"]) > 0.0).collect();
    let label = |p: &Value| json!({"pad": format!("{}.{}", p["ref"].as_str().unwrap_or(""), p["name"].as_str().unwrap_or("")), "at": [p["x"], p["y"]]});
    min_by("padHole", drilled.iter().map(|p| (f(&p["drill"]), label(p))).collect());
    // a pad's ring on its narrow side (a round hole in an oblong pad)
    min_by("padAnnularRing", drilled.iter().filter(|p| f(&p["sizeX"]) > f(&p["drill"])).map(|p| ((f(&p["sizeX"]).min(f(&p["sizeY"])) - f(&p["drill"])) / 2.0, label(p))).collect());
    min_by("smdPad", pads.iter().filter(|p| f(&p["drill"]) == 0.0).map(|p| (f(&p["sizeX"]).min(f(&p["sizeY"])), label(p))).collect());
    if let Some((x0, y0, x1, y1)) = outline_bbox(state) {
        m.insert("boardSize".into(), json!({"mm": [r3(x1 - x0), r3(y1 - y0)]}));
        let _ = (x0, y0, x1, y1);
        if let Some((d, mut at)) = edge_distance(state) { at["mm"] = json!(d); m.insert("edgeClearance".into(), at); }
    }
    // drilled holes: the largest, and the closest pair edge to edge (via to via, and any pair with a pad hole)
    let mut holes: Vec<(f64, f64, f64, bool, Value)> = vias.iter().map(|v| (f(&v["position"]["x"]), f(&v["position"]["y"]), f(&v["drill"]), false, json!({"via": v["net"], "at": [v["position"]["x"], v["position"]["y"]]}))).collect();
    holes.extend(drilled.iter().map(|p| (f(&p["x"]), f(&p["y"]), f(&p["drill"]), true, label(p))));
    if let Some(h) = holes.iter().max_by(|a, b| a.2.partial_cmp(&b.2).unwrap()) { m.insert("largestDrill".into(), json!({"mm": r3(h.2), "at": h.4})); }
    holes.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());
    let (mut vv, mut pp): (Option<(f64, Value)>, Option<(f64, Value)>) = (None, None);
    for i in 0..holes.len() {
        for j in i + 1..holes.len() {
            let (a, b) = (&holes[i], &holes[j]);
            if b.0 - a.0 > 10.0 { break; }
            let d = ((a.0 - b.0).powi(2) + (a.1 - b.1).powi(2)).sqrt() - (a.2 + b.2) / 2.0;
            if (a.0 - b.0).abs() < 1e-6 && (a.1 - b.1).abs() < 1e-6 { continue; } // a via in a pad
            let slot = if a.3 || b.3 { &mut pp } else { &mut vv };
            if slot.as_ref().map(|s| d < s.0).unwrap_or(true) { *slot = Some((d, json!([a.4.clone(), b.4.clone()]))); }
        }
    }
    if let Some((d, at)) = vv { m.insert("holeToHoleVia".into(), json!({"mm": r3(d), "at": at})); }
    if let Some((d, at)) = pp { m.insert("holeToHolePad".into(), json!({"mm": r3(d), "at": at})); }
    m.insert("counts".into(), json!({"tracks": state["tracks"].as_array().map(|a| a.len()), "vias": vias.len(), "pads": pads.len(), "drilledPads": drilled.len()}));
    m
}

/// The measured values against the caller's limits; each limit names its feature (min*, or max for board and layers).
pub fn compare(meas: &Map<String, Value>, limits: &Map<String, Value>, clearance: Option<f64>, layers: Option<i64>) -> Vec<Value> {
    let mut out = Vec::new();
    let got = |k: &str| meas.get(k).and_then(|v| v["mm"].as_f64());
    for (limit, feature) in [("minTrack", "track"), ("minViaDrill", "viaDrill"), ("minViaDiameter", "viaDiameter"), ("minViaAnnularRing", "viaAnnularRing"),
                             ("minPadHole", "padHole"), ("minPadAnnularRing", "padAnnularRing"), ("minSmdPad", "smdPad"),
                             ("minEdgeClearance", "edgeClearance"), ("minHoleToHoleVia", "holeToHoleVia"), ("minHoleToHolePad", "holeToHolePad"),
                             ("minSilkLine", "silkLine"), ("minSilkText", "silkText")] {
        if let (Some(l), Some(v)) = (limits.get(limit).and_then(|x| x.as_f64()), got(feature)) {
            if v + 1e-9 < l { out.push(json!({"limit": limit, "limitMm": l, "boardMm": v, "at": meas[feature]["at"]})); }
        }
    }
    if let (Some(l), Some(c)) = (limits.get("minClearance").and_then(|x| x.as_f64()), clearance) {
        if c + 1e-9 < l { out.push(json!({"limit": "minClearance", "limitMm": l, "boardMm": c, "at": "the board's clearance rule"})); }
    }
    if let (Some(l), Some(n)) = (limits.get("maxLayers").and_then(|x| x.as_i64()), layers) {
        if n > l { out.push(json!({"limit": "maxLayers", "limit_": l, "board": n})); }
    }
    if let (Some(l), Some(v)) = (limits.get("maxDrill").and_then(|x| x.as_f64()), got("largestDrill")) {
        if v > l + 1e-9 { out.push(json!({"limit": "maxDrill", "limitMm": l, "boardMm": v, "at": meas["largestDrill"]["at"], "note": "larger holes are milled (routed) instead"})); }
    }
    if let (Some(lim), Some(sz)) = (limits.get("minBoardMm").and_then(|x| x.as_array()), meas.get("boardSize").and_then(|b| b["mm"].as_array())) {
        let (lw, lh) = (lim.first().and_then(|x| x.as_f64()).unwrap_or(0.0), lim.get(1).and_then(|x| x.as_f64()).unwrap_or(0.0));
        let (w, h) = (sz[0].as_f64().unwrap_or(0.0), sz[1].as_f64().unwrap_or(0.0));
        if w.min(h) + 1e-9 < lw.min(lh) || w.max(h) + 1e-9 < lw.max(lh) { out.push(json!({"limit": "minBoardMm", "limitMm": [lw, lh], "boardMm": [w, h]})); }
    }
    if let (Some(lim), Some(sz)) = (limits.get("maxBoardMm").and_then(|x| x.as_array()), meas.get("boardSize").and_then(|b| b["mm"].as_array())) {
        let (lw, lh) = (lim.first().and_then(|x| x.as_f64()).unwrap_or(f64::MAX), lim.get(1).and_then(|x| x.as_f64()).unwrap_or(f64::MAX));
        let (w, h) = (sz[0].as_f64().unwrap_or(0.0), sz[1].as_f64().unwrap_or(0.0));
        // either orientation fits
        if !((w <= lw && h <= lh) || (w <= lh && h <= lw)) { out.push(json!({"limit": "maxBoardMm", "limitMm": [lw, lh], "boardMm": [w, h]})); }
    }
    out
}

/// The smallest clearance gap among the board's clearance rules, from their descriptors ("Gap=10mil" / "Gap=0.2mm").
pub fn min_clearance(rules: &[Value]) -> Option<f64> {
    rules.iter().filter(|r| r["kind"].as_i64() == Some(0) || r["kindName"].as_str() == Some("Clearance") || r["name"].as_str().map(|n| n.to_lowercase().contains("clearance")).unwrap_or(false))
        .filter(|r| r["enabled"].as_bool() != Some(false))
        .filter_map(|r| {
            let d = r["descriptor"].as_str()?;
            let i = d.find("Gap=")? + 4;
            let num: String = d[i..].chars().take_while(|c| c.is_ascii_digit() || *c == '.').collect();
            let v: f64 = num.parse().ok()?;
            let unit = &d[i + num.len()..];
            Some(if unit.starts_with("mil") { v * 0.0254 } else { v })
        }).reduce(f64::min).map(r3)
}

/// altium_fab_check {filePath?, limits?}
/// JLCPCB's standard rigid-board capabilities (jlcpcb.com/capabilities/pcb-capabilities, read 2026-10-23) for this many
/// copper layers and outer copper weight (oz), and the notes on what passes only on a costlier option. Pure.
pub fn jlcpcb_limits(layers: i64, oz: f64) -> (Map<String, Value>, Vec<&'static str>) {
    let multi = layers >= 4;
    let two_oz = oz >= 1.75;
    let track = match (multi, two_oz) { (false, false) => 0.10, (true, false) => 0.09, (false, true) => 0.16, (true, true) => 0.15 };
    let max_board = match layers { 1 => json!([606, 510]), 2 => json!([670, 600]), 4 => json!([663, 593]), _ => json!([656, 586]) };
    let l = json!({"minTrack": track, "minClearance": track, "minViaDrill": 0.15, "minViaDiameter": 0.25, "minPadHole": 0.15,
        "minPadAnnularRing": if two_oz { 0.254 } else if multi { 0.15 } else { 0.18 }, "maxDrill": 6.3, "minHoleToHoleVia": 0.2, "minHoleToHolePad": 0.45,
        "minEdgeClearance": 0.2, "minSilkLine": 0.15, "minSilkText": 1.0, "minBoardMm": [3, 3], "maxBoardMm": max_board});
    let notes = vec![
        "via holes of 0.15 mm (and the 0.2/0.25 mm options with small vias) cost more; 0.1 mm holes and 0.2 mm vias only on boards 1 mm thick or thinner with ENIG or OSP",
        "PTH annular ring: JLCPCB recommends 0.25 mm (1-2 layers) or 0.20 mm (multilayer); the limit checked is the absolute minimum",
        "V-cut panels need copper 0.4 mm from the cut (altium_panelize separation:vscore checks it); routed and mouse-bite edges 0.2 mm",
        "NPTH holes 0.5 mm or more with a 0.45 mm ring; silkscreen 0.15 mm from pads (altium_silkscreen_prep clears it)",
    ];
    (l.as_object().cloned().unwrap_or_default(), notes)
}

pub fn fab_check(args: &Value) -> Value {
    if let Some(g) = crate::support::need_licensed() { return g; }
    if let Some(p) = crate::support::s(args, "filePath") { if let Some(e) = crate::support::must_open(&p, 60) { return e; } }
    let st = crate::routing::routing_state(&json!({}));
    if st.get("success").and_then(|b| b.as_bool()) != Some(true) { return st; }
    let mut meas = measure(&st);
    let rules = crate::agent::call("read_rules", &[], None, std::time::Duration::from_secs(60));
    let rule_list = rules.get("data").and_then(|d| d.get("rules")).and_then(|r| r.as_array()).cloned().unwrap_or_default();
    let clearance = min_clearance(&rule_list);
    if let Some(c) = clearance { meas.insert("clearanceRule".into(), json!({"mm": c})); }
    let stack = crate::agent::call("layer_stack", &[], None, std::time::Duration::from_secs(60));
    let layers = stack.get("data").and_then(|d| d.get("copperLayers")).and_then(|v| v.as_i64());
    if let Some(n) = layers { meas.insert("copperLayers".into(), json!(n)); }
    let mut limits = Map::new();
    let mut fab = Value::Null;
    if let Some(name) = crate::support::s(args, "fab") {
        if !name.eq_ignore_ascii_case("jlcpcb") && !name.eq_ignore_ascii_case("jlc") {
            return json!({"success": false, "errorCode": "unknown_fab", "error": format!("no built-in limits for {name}: jlcpcb is built in; pass any other fab's numbers as limits")});
        }
        // the outer copper weight from the stack (35 um = 1 oz)
        let outer_um = stack.get("data").and_then(|d| d["layers"][0]["copperUm"].as_f64()).unwrap_or(35.0);
        let oz = args.get("copperOz").and_then(|v| v.as_f64()).unwrap_or(outer_um / 35.0);
        let (l, notes) = jlcpcb_limits(layers.unwrap_or(2), oz);
        limits = l;
        fab = json!({"name": "JLCPCB", "service": "standard rigid PCB", "copperOz": r3(oz), "source": "https://jlcpcb.com/capabilities/pcb-capabilities", "read": "2026-10-23", "notes": notes});
    }
    for (k, v) in args.get("limits").and_then(|l| l.as_object()).cloned().unwrap_or_default() { limits.insert(k, v); }
    // silkscreen sizes, only when a limit asks (the read walks every text)
    if limits.contains_key("minSilkText") || limits.contains_key("minSilkLine") {
        let silk = crate::routing::silk_state(&json!({}));
        let mut texts: Vec<(f64, Value)> = silk["texts"].as_array().cloned().unwrap_or_default().iter().filter(|t| t["side"] != "other").map(|t| (f(&t["size"]), json!({"text": t["text"], "at": [t["x"], t["y"]]}))).collect();
        for c in silk["components"].as_array().cloned().unwrap_or_default() {
            for k in ["name", "comment"] { if c[k]["shown"].as_bool() == Some(true) { texts.push((f(&c[k]["size"]), json!({"ref": c["ref"], "text": c[k]["text"], "at": [c[k]["x"], c[k]["y"]]}))); } }
        }
        if let Some((v, at)) = texts.into_iter().filter(|t| t.0 > 0.0).min_by(|a, b| a.0.partial_cmp(&b.0).unwrap()) { meas.insert("silkText".into(), json!({"mm": r3(v), "at": at})); }
        if let Some(l) = silk["lines"].as_array().cloned().unwrap_or_default().iter().filter(|l| l["side"] != "other" && f(&l["width"]) > 0.0).min_by(|a, b| f(&a["width"]).partial_cmp(&f(&b["width"])).unwrap()) {
            meas.insert("silkLine".into(), json!({"mm": r3(f(&l["width"])), "at": [l["x1"], l["y1"]]}));
        }
    }
    let fails = compare(&meas, &limits, clearance, layers);
    // passes, but on a costlier option or under the recommendation
    let mut costlier = Vec::new();
    if !fab.is_null() {
        if let Some(v) = meas.get("viaDrill").and_then(|v| v["mm"].as_f64()) { if v < 0.3 { costlier.push(json!({"feature": "viaDrill", "boardMm": v, "note": "via holes under 0.3 mm are JLCPCB's costlier via options: choose the via size when ordering"})); } }
        if let Some(v) = meas.get("padAnnularRing").and_then(|v| v["mm"].as_f64()) {
            let rec = if layers.unwrap_or(2) >= 4 { 0.20 } else { 0.25 };
            if v < rec { costlier.push(json!({"feature": "padAnnularRing", "boardMm": v, "note": format!("under JLCPCB's recommended {rec} mm ring (within its absolute minimum when outsideLimits is silent)")})); }
        }
    }
    json!({"success": true, "fab": fab, "measured": meas, "limitsChecked": limits.keys().collect::<Vec<_>>(), "outsideLimits": fails, "fits": if limits.is_empty() { Value::Null } else { json!(fails.is_empty()) },
        "costlierOrBelowRecommended": costlier,
        "_hint": if limits.is_empty() { "Measured only. Pass fab:\"jlcpcb\" for JLCPCB's published limits, or any fab's limits (from its capability page) as limits:{minTrack, minClearance, minViaDrill, minViaDiameter, minViaAnnularRing, minPadHole, minPadAnnularRing, minSmdPad, minEdgeClearance, minHoleToHoleVia, minHoleToHolePad, maxDrill, minSilkLine, minSilkText, maxLayers, minBoardMm:[w,h], maxBoardMm:[w,h]} in mm to check them." }
                 else { "outsideLimits names each feature below the fab's limit and where it is. Fix them (altium_set_track_width, altium_add_rule, a footprint change) or choose the fab's advanced service; then run altium_run_drc." }})
}

#[cfg(test)]
mod tests {
    use super::*;

    fn board() -> Value {
        json!({"tracks": [{"width": 0.25, "net": "A", "layer": "F.Cu", "start": {"x": 0.0, "y": 0.0}}, {"width": 0.1, "net": "B", "layer": "B.Cu", "start": {"x": 5.0, "y": 5.0}}, {"width": 0.05, "net": "", "layer": "L57", "start": {"x": 0.0, "y": 0.0}}],
               "vias": [{"size": 0.6, "drill": 0.3, "net": "GND", "position": {"x": 1.0, "y": 1.0}}, {"size": 0.45, "drill": 0.25, "net": "B", "position": {"x": 2.0, "y": 2.0}}],
               "pads": [{"ref": "J1", "name": "1", "x": 0.0, "y": 0.0, "sizeX": 1.7, "sizeY": 1.7, "drill": 1.0}, {"ref": "U1", "name": "3", "x": 3.0, "y": 0.0, "sizeX": 0.3, "sizeY": 1.0, "drill": 0.0}],
               "outline": [[0, 0], [50, 0], [50, 30], [0, 30]]})
    }

    #[test]
    fn the_smallest_features_are_found_with_where_they_are() {
        let m = measure(&board());
        assert_eq!(m["track"]["mm"], json!(0.1));
        assert_eq!(m["track"]["at"]["net"], json!("B"));
        assert_eq!((m["viaDrill"]["mm"].clone(), m["viaDiameter"]["mm"].clone(), m["viaAnnularRing"]["mm"].clone()), (json!(0.25), json!(0.45), json!(0.1)));
        assert_eq!((m["padHole"]["mm"].clone(), m["padAnnularRing"]["mm"].clone(), m["smdPad"]["mm"].clone()), (json!(1.0), json!(0.35), json!(0.3)));
        assert_eq!(m["boardSize"]["mm"], json!([50.0, 30.0]));
    }

    #[test]
    fn arc_edges_count_toward_the_board_size() {
        let b = json!({"outline": [[0, 0], [10, 0]], "outlineEdges": [{"kind": "arc", "center": [5.0, 0.0], "radius": 5.0, "angle1": 0.0, "angle2": 180.0}]});
        assert_eq!(measure(&b)["boardSize"]["mm"], json!([10.0, 5.0]));
    }

    #[test]
    fn limits_name_what_falls_short_and_a_board_fits_either_way_round() {
        let m = measure(&board());
        let lim = json!({"minTrack": 0.127, "minViaDrill": 0.3, "maxBoardMm": [30, 60], "maxLayers": 2, "minClearance": 0.127});
        let f = compare(&m, lim.as_object().unwrap(), Some(0.1), Some(2));
        let names: Vec<&str> = f.iter().map(|x| x["limit"].as_str().unwrap()).collect();
        assert_eq!(names, vec!["minTrack", "minViaDrill", "minClearance"]);
    }

    #[test]
    fn clearance_is_read_from_rule_descriptors_in_mil_or_mm() {
        let rules = vec![json!({"kind": 0, "descriptor": "Clearance Constraint (Gap=10mil) (All),(All)", "enabled": true}),
                         json!({"kind": 0, "descriptor": "Clearance Constraint (Gap=0.15mm) (InNet('SW')),(All)", "enabled": true}),
                         json!({"kind": 0, "descriptor": "Clearance Constraint (Gap=0.05mm) (All),(All)", "enabled": false})];
        assert_eq!(min_clearance(&rules), Some(0.15));
    }
    #[test]
    fn jlcpcb_limits_follow_layers_and_copper() {
        let (two, _) = jlcpcb_limits(2, 1.0);
        assert_eq!(two["minTrack"], 0.1);
        assert_eq!(two["minPadAnnularRing"], 0.18);
        assert_eq!(two["maxBoardMm"], json!([670, 600]));
        let (four, _) = jlcpcb_limits(4, 1.0);
        assert_eq!(four["minTrack"], 0.09);
        assert_eq!(jlcpcb_limits(2, 2.0).0["minTrack"], 0.16);
        // a 0.3 mm track board passes, a 0.08 mm one does not, and holes 0.15 mm apart edge to edge fail the via rule
        let st = json!({"tracks": [{"width": 0.08, "net": "A", "layer": "F.Cu", "start": {"x": 1.0, "y": 1.0}}],
                        "vias": [{"drill": 0.3, "size": 0.6, "net": "A", "position": {"x": 0.0, "y": 0.0}}, {"drill": 0.3, "size": 0.6, "net": "B", "position": {"x": 0.45, "y": 0.0}}],
                        "outline": [[-5, -5], [5, -5], [5, 5], [-5, 5]]});
        let m = measure(&st);
        assert_eq!(m["holeToHoleVia"]["mm"], 0.15);
        let fails: Vec<String> = compare(&m, &two, None, Some(2)).iter().map(|f| f["limit"].as_str().unwrap().to_string()).collect();
        assert!(fails.contains(&"minTrack".to_string()) && fails.contains(&"minHoleToHoleVia".to_string()), "{fails:?}");
    }
}