← Commit history
SKILL.md+5
@@ -270,6 +270,11 @@ The clock starts at the prompt even when there is no board yet. - Opt in to blocking for a fab that wants silk clearance enforced: `"fab": {"silkBlocking": true}` in the spec, or a comment line `# adom-aiflow: silkBlocking` in the board's `.kicad_dru` rules profile. Then they block as before 0.2.19 (an explicit `"silkBlocking": false` in the spec wins over the rules file). - KiCad's STEP export keeps the whole ink. So `board-glb copper` lays the exposed copper over the ink inside every mask opening, the way the fab prints it, and `board-glb check` fails a GLB whose silkscreen is not clipped where copper is exposed. +**Copper balance and layer-pair symmetry are reported, not blocking by default.** `pour`, `gate`, `finish`, `export` and `analyze balance` measure per-layer copper area percentage inside `Edge.Cuts` (filled zones, tracks, arcs, pads, vias and copper graphics, without double-counting overlaps), mirrored layer-pair deltas (`F.Cu/B.Cu`, `In1.Cu/In2.Cu` on 4L, `In1.Cu/In4.Cu` and `In2.Cu/In3.Cu` on 6L), and a four-quadrant view (`TL/TR/BL/BR`).+- Thresholds: warns when any mirrored pair differs by more than `20` percentage points (configurable via `"fab": {"maxCopperImbalancePct": 15}` or `.kicad_dru` comment `# adom-aiflow: maxCopperImbalancePct 15`), or when an outer layer (`F.Cu` or `B.Cu`) sits below `15%` copper (`"fab": {"minOuterCopperPct": 15}`, set `0` to disable).+- Hints name the lighter layer and suggest rebalancing pours, adding a hatched fill, or placing non-functional copper thieving (keeping thieving at least `1.5 mm` from high-speed traces).+- Never blocks a finished board by default. Opt in to blocking with `"fab": {"copperBalanceBlocking": true}` in the spec or `# adom-aiflow: copperBalanceBlocking` in the board's `.kicad_dru` rules profile (an explicit `"copperBalanceBlocking": false` in the spec wins over the rules file). Results are recorded in `gate.json`, `run.json` (`pour`, `gate`, `copper-balance`, `summary.copperBalance`) and `export-check.json`.+ ## The fields step (adom-fields)  After the pours and the analyses: `adom-fields analyze --board <the current board> --spec <spec> --out fields` (about two minutes; `adom-wiki pkg install adom/adom-fields` if it is missing), `adom-fields serve --fields fields --port 8874 &`, then `step fields` and `tour fields`: the binary opens the app in a pup window on the test box, films that window while `adom-fields tour` walks the board gently (the app paces itself: slow eased moves about nine seconds long, the board drifting a few degrees through every held beat, one copper pour isolated at a time, a quick turn-over to the bottom layer, because the flow plays this clip back at ten times speed, where a snap reads as frenetic) (each net lit, the hot parts, the issues flown to; the app's toasts are the captions), and records the issues in the run. When the Fields URL is a localhost proxy (an Adom Hydrogen desktop container's `VSCODE_PROXY_URI` is `http://{{port}}.localhost:<port>/`, reachable only on the machine hosting the container), the window opens on the user's primary machine (`adom-bridge targets` names it) instead of the test box, and the answer says so; `--on <box>` overrides. The issues (a current neck, a tab over its rise budget, a chip missing its thermal vias) are yours to answer before delivery; the app's screenshots are drawings you can register with `artifact`.
crates/adom-aiflow/src/gate_eval.rs+1
@@ -107,6 +107,7 @@ pub fn evaluate(r: &Run, b: &Board, plan_v: &Value, routed: &Path, base: &Value,         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});+        s["copperBalance"] = aiflow_analyze::copper_balance::audit(&rb, &spec_g, &r.current_board());     }     Ok(GateEval { s, pu, pu_issues, sw_issues, dec, mech, stairs, quality }) }
crates/adom-aiflow/src/main.rs+88−5
@@ -4602,6 +4602,7 @@ fn main() {                         let sp_exp = spec_soft(&r);                         let va = vippo::audit_vippo(&b_exp, &sp_exp);                         report["vippo"] = va.clone();+                        report["copperBalance"] = aiflow_analyze::copper_balance::audit(&b_exp, &sp_exp, &board_path);                         if va["pass"] == false {                             vippo_unapproved = va["findings"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect();                         } else if let Ok(Some(vp)) = vippo::write_vippo_fab_note(&out_dir, &va) {@@ -4654,6 +4655,7 @@ fn main() {                             let sp_exp = spec_soft(&r);                             let va = vippo::audit_vippo(&b_exp, &sp_exp);                             report["vippo"] = va.clone();+                            report["copperBalance"] = aiflow_analyze::copper_balance::audit(&b_exp, &sp_exp, &board_path);                             if va["pass"] == false {                                 for vf in va["findings"].as_array().into_iter().flatten().filter_map(Value::as_str) {                                     hints.push(format!("VIPPO: {vf}"));@@ -5946,11 +5948,24 @@ fn main() {             write_json(&zp, &json!({"zones": zones}));             pourverify::record_plan(&mut r.data, &zp, "pour").unwrap_or_else(|e| err(&e, &[]));             write_json(&vp, &json!({"engine": "adom-aiflow pour plan (thermal and stitching vias)", "nets": vias}));-            r.stage_end("pour", Some(json!({"zones": zones.len(), "keepouts": keepouts, "vias": vias.len()})), None);-            r.outcome("pour", json!({"pours": zp.display().to_string(), "vias": vp.display().to_string(), "zones": zones.len(), "keepouts": keepouts, "viaCount": vias.len()}));+            let resolved_zones = aiflow_pours::resolve_outline(&b, &zones);+            let cb = aiflow_analyze::copper_balance::audit_with_planned_zones(&b, &spec, &r.current_board(), &resolved_zones);+            r.stage_end("pour", Some(json!({"zones": zones.len(), "keepouts": keepouts, "vias": vias.len(), "maxPairImbalancePoints": cb["maxPairImbalancePoints"]})), None);+            r.outcome("pour", json!({"pours": zp.display().to_string(), "vias": vp.display().to_string(), "zones": zones.len(), "keepouts": keepouts, "viaCount": vias.len(), "copperBalance": cb}));             r.save().unwrap();             let lines: Vec<String> = zones.iter().map(aiflow_pours::describe).collect();-            ok(&format!("pours planned: {} zones ({keepouts} keepouts), {} vias\n{}", zones.len(), vias.len(), lines.join("\n")), &["Pours are filled and DRC-checked by kicad_add_zone's preflight when landed (the headless DRC does not refill zones). `land vias` then `land pours`.".into()]);+            let cb_lines = aiflow_analyze::copper_balance::format_summary(&cb);+            let mut pour_hints = vec!["Pours are filled and DRC-checked by kicad_add_zone's preflight when landed (the headless DRC does not refill zones). `land vias` then `land pours`.".into()];+            for w in cb["warnings"].as_array().into_iter().flatten().filter_map(Value::as_str) {+                eprintln!("Warning (copper balance): {w}");+            }+            if !cb["warnings"].as_array().map(|a| a.is_empty()).unwrap_or(true) {+                for h in cb["hints"].as_array().into_iter().flatten().filter_map(Value::as_str) {+                    pour_hints.push(h.to_string());+                }+            }+            let cb_block = if cb_lines.is_empty() { String::new() } else { format!("\n{}", cb_lines.join("\n")) };+            ok(&format!("pours planned: {} zones ({keepouts} keepouts), {} vias\n{}{cb_block}", zones.len(), vias.len(), lines.join("\n")), &pour_hints);         }         Cmd::Fusion { args, target } => {             // the Fusion steps run in Python beside the bridge calls; the run gives them their folder,@@ -6039,7 +6054,7 @@ fn main() {             let (newe, unc, inh) = (s["newErrors"].as_u64().unwrap_or(1), s["unconnected"].as_u64().unwrap_or(1), s["inheritedErrors"].as_u64().unwrap_or(0));             let npu = pu_issues.len() as u64;             r.stage_end("gate", Some(json!({"newErrors": newe, "unconnected": unc, "inheritedErrors": inh, "planeUnderIssues": npu})), None);-            r.outcome("gate", json!({"report": dir.join("gate.json").display().to_string(), "newErrors": newe, "unconnected": unc, "planeUnderIssues": npu, "courtyardsOk": mech.as_ref().map(|m| m.courtyards_ok()), "bodiesOk": mech.as_ref().map(|m| m.bodies_ok()), "staircases": stairs.len(), "routeQuality": s["routeQuality"], "silkAdvisories": s["silkAdvisories"], "silkBlocking": s["silkBlocking"], "routedBoard": routed.display().to_string(), "plan": planp, "planNormalised": plan_notes}));+            r.outcome("gate", json!({"report": dir.join("gate.json").display().to_string(), "newErrors": newe, "unconnected": unc, "planeUnderIssues": npu, "courtyardsOk": mech.as_ref().map(|m| m.courtyards_ok()), "bodiesOk": mech.as_ref().map(|m| m.bodies_ok()), "staircases": stairs.len(), "routeQuality": s["routeQuality"], "silkAdvisories": s["silkAdvisories"], "silkBlocking": s["silkBlocking"], "copperBalance": {"balanced": s["copperBalance"]["balanced"], "blocking": s["copperBalance"]["blocking"], "maxPairImbalancePoints": s["copperBalance"]["maxPairImbalancePoints"], "thresholdPoints": s["copperBalance"]["thresholdPoints"]}, "routedBoard": routed.display().to_string(), "plan": planp, "planNormalised": plan_notes}));             if !mol_errors.is_empty() { r.data["outcomes"]["gate"]["moleculeErrors"] = json!(mol_errors); }             if !mode.is_default() { r.data["outcomes"]["gate"]["singleFaceIssues"] = json!(sf_issues.len()); }             r.data["lastGate"] = json!({"at": r.data["outcomeAt"]["gate"], "board": r.current_board(), "boardRevision": r.data["boards"].as_array().map(|a| a.len()).unwrap_or(1), "newErrors": newe, "unconnected": unc, "inheritedErrors": inh, "planeUnderIssues": npu, "plan": planp});@@ -6093,6 +6108,23 @@ fn main() {             for hf in s["viaHygiene"]["findings"].as_array().into_iter().flatten().filter_map(Value::as_str) {                 eprintln!("Warning (via hygiene): {hf}");             }+            if s["copperBalance"].is_object() {+                let cb = &s["copperBalance"];+                let cb_unfilled = cb["unfilledZones"].as_array().map(|a| !a.is_empty()).unwrap_or(false);+                if cb["blocking"] == true && cb["pass"] == false && !cb_unfilled {+                    let cf: Vec<String> = cb["findings"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect();+                    let ch: Vec<String> = cb["hints"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect();+                    findings(&format!("gate failed: copper balance (blocking because copperBalanceBlocking is on):\n  {}", cf.join("\n  ")), &ch);+                }+                for w in cb["warnings"].as_array().into_iter().flatten().filter_map(Value::as_str) {+                    eprintln!("Warning (copper balance): {w}");+                }+                if !cb["warnings"].as_array().map(|a| a.is_empty()).unwrap_or(true) {+                    for h in cb["hints"].as_array().into_iter().flatten().filter_map(Value::as_str) {+                        eprintln!("Hint: {h}");+                    }+                }+            }             let silk_n = s["silkAdvisories"].as_u64().unwrap_or(0) as usize;             if silk_n > 0 { eprintln!("Warning: {}", silk_policy::advisory_line(silk_n, &s["silkAdvisoryList"].as_array().cloned().unwrap_or_default().iter().filter_map(|v| v.as_str().map(str::to_string)).collect::<Vec<_>>())); }             if !stairs.is_empty() { eprintln!("Warning: {} staircase run(s) left in the copper (tiny alternating 0/90 degree steps; redraw as one 45 degree segment):\n  {}", stairs.len(), stairs.iter().take(8).cloned().collect::<Vec<_>>().join("\n  ")); }@@ -6413,6 +6445,31 @@ 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 == "balance" || what == "copper-balance" {+                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 board_path = live.as_ref().map(|l| l.1.clone()).unwrap_or_else(|| r.current_board());+                let spec = spec_of(&r);+                r.stage_start("analyze-balance", Some("binary"), None);+                let cb = aiflow_analyze::copper_balance::audit(&board_now, &spec, &board_path);+                r.stage_end("analyze-balance", Some(json!({"balanced": cb["balanced"], "maxPairImbalancePoints": cb["maxPairImbalancePoints"], "blocking": cb["blocking"]})), None);+                r.outcome("analyze-balance", cb.clone());+                r.save().unwrap();+                if let Some(e) = cb["error"].as_str() {+                    let hints: Vec<String> = cb["hints"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect();+                    err(&format!("copper balance check could not run: {e}"), &hints);+                }+                let mut lines = aiflow_analyze::copper_balance::format_summary(&cb);+                for w in cb["warnings"].as_array().into_iter().flatten().filter_map(Value::as_str) {+                    lines.push(format!("  WARN: {w}"));+                }+                let hints: Vec<String> = cb["hints"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect();+                if cb["blocking"] == true && cb["pass"] == false {+                    err(&format!("copper balance check (blocking) failed:\n{}", lines.join("\n")), &hints);+                }+                ok(&lines.join("\n"), &hints);+                return;+            }             if what == "si" {                 // issues #214, #215: reference-plane copper coverage, return-path stitching vias,                 // 3W/3H crosstalk, USB VBUS inrush capacitance, rail load budgets, and Fields SI/noise/EMC/ESD/PDN review@@ -6580,7 +6637,7 @@ fn main() {             };             let name = format!("analyze-{what}");             r.stage_start(&name, Some("binary"), None);-            let (mut heuristic_passed, mut res) = match what.as_str() { "current" => aiflow_analyze::analyze_current_on_board(&plan_v, &spec, zs.as_ref(), Some(&pad_layers_of(&board_now)), &board_now), "thermal" => aiflow_analyze::analyze_thermal_on_board(&plan_v, &spec, zs.as_ref(), &board_now), other => err(&format!("analyze {other}: use current, thermal or impedance"), &[]) };+            let (mut heuristic_passed, mut res) = match what.as_str() { "current" => aiflow_analyze::analyze_current_on_board(&plan_v, &spec, zs.as_ref(), Some(&pad_layers_of(&board_now)), &board_now), "thermal" => aiflow_analyze::analyze_thermal_on_board(&plan_v, &spec, zs.as_ref(), &board_now), other => err(&format!("analyze {other}: use current, thermal, impedance, si or balance"), &[]) };             let mut fields_file=fields.clone().unwrap_or_else(||dir.join("fields/fields.json"));             // provenance: a fields.json is evidence only when it is the output of a solve aiflow ran or watched;             // any other file (copied, edited, or written to look like one) is solved again here, same inputs@@ -7130,6 +7187,29 @@ fn main() {                     "fieldsReview": fields_rev,                     "fieldsReadiness": readiness_doc,                 }));++                // Per-layer copper balance, mirrored layer-pair symmetry, and quadrant view+                // (advisory by default; spec.fab.copperBalanceBlocking or .kicad_dru marker opts into blocking)+                let cb = aiflow_analyze::copper_balance::audit(&b_now, &spec_v, &solved_board);+                for l in aiflow_analyze::copper_balance::format_summary(&cb) {+                    quality_lines.push(l);+                }+                if cb["blocking"] == true && cb["pass"] == false {+                    let cb_hint = cb["hints"].as_array().and_then(|a| a.first()).and_then(Value::as_str).unwrap_or("rebalance pours or add copper thieving on the lighter layer");+                    for f in cb["findings"].as_array().into_iter().flatten().filter_map(Value::as_str) {+                        missing.push(format!("copper balance (blocking because copperBalanceBlocking is on): {f} ({cb_hint})"));+                    }+                } else {+                    for w in cb["warnings"].as_array().into_iter().flatten().filter_map(Value::as_str) {+                        quality_lines.push(format!("copper balance warning (not blocking): {w}"));+                    }+                    if !cb["warnings"].as_array().map(|a| a.is_empty()).unwrap_or(true) {+                        for h in cb["hints"].as_array().into_iter().flatten().filter_map(Value::as_str) {+                            quality_lines.push(format!("  hint: {h}"));+                        }+                    }+                }+                r.outcome("copper-balance", cb);             }             // 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();@@ -7222,6 +7302,9 @@ fn main() {             let qp = dir.join("finish-route-quality.json");             write_json(&qp, &qv);             r.data["summary"]["routeQuality"] = route_quality::outcome(&qv, &qp.display().to_string());+            if let Some(cb) = r.outcomes().get("copper-balance").cloned() {+                r.data["summary"]["copperBalance"] = cb;+            }             r.data["summary"]["priorities"] = json!({"signalRanked": sig_ranked, "placementRanked": place_ranked, "classes": qv["classes"]});             if nothing_to_source { r.data["summary"]["notApplicable"].as_array_mut().unwrap().push(json!("sourcing check: not applicable (no footprint in the BOM)")); }             r.log("finish", json!({"minutes": r.elapsed_minutes(), "steps": Value::Object(r.step_report())}));
crates/aiflow-analyze/src/copper_balance.rsadded+1135
@@ -0,0 +1,1135 @@+//! Per-layer copper balance, mirrored layer-pair symmetry, and quadrant distribution audit.+//!+//! Computes true non-overlapping copper area per layer inside the board outline (minus cutouts)+//! using a boolean rasterizer adapted from `adom-eda-checks` (`copper_balance`):+//! - filled copper zones (`filled_polygon`, including KiCad fractured fills with internal holes+//!   and KiCad 10 arc vertices, plus legacy `fill_segments`)+//! - tracks and arcs (`segment` and `arc` capsules)+//! - copper pads (real transformed pad polygons, skipping non-plated holes with no copper annulus)+//! - vias (discs on each copper layer in the via's span, respecting blind/buried vias)+//! - board-level copper graphics (`gr_poly`, `gr_rect`, `gr_circle`, `gr_line`, `gr_arc` on `.Cu`)+//!+//! Mirrored layer pairs (`F.Cu/B.Cu`, `In1.Cu/In2.Cu` on 4L, `In1.Cu/In4.Cu` and `In2.Cu/In3.Cu`+//! on 6L, and so on about the core) are compared against a configurable threshold (default 20 pp).+//! Findings are advisory warnings by default and never block a finished board unless the spec or+//! fab rules profile opts in:+//! - spec: `"fab": {"maxCopperImbalancePct": 15, "minOuterCopperPct": 15, "copperBalanceBlocking": true}`+//!   (or `"copperBalance": {"maxImbalancePct": 15, "minOuterCopperPct": 15, "blocking": true}`)+//! - fab rules file (`<board>.kicad_dru`): comment lines `# adom-aiflow: copperBalanceBlocking`+//!   and `# adom-aiflow: maxCopperImbalancePct 15`. An explicit spec value wins over the rules file.++use std::collections::{BTreeMap, BTreeSet};+use std::path::Path;++use aiflow_board::{copper_layer, geom, sx::Node, Board, Pt};+use serde_json::{json, Value};++/// Default maximum allowed copper percentage-point difference between mirrored copper layers.+pub const DEFAULT_MAX_IMBALANCE_PCT: f64 = 20.0;+/// Default minimum outer-layer copper coverage percentage before advising thieving or hatched fill.+pub const DEFAULT_MIN_OUTER_PCT: f64 = 15.0;+/// Default raster cell size in mm (matches `adom-eda-checks`).+pub const DEFAULT_RESOLUTION_MM: f64 = 0.1;+/// Soft cap on raster cells per layer so very large panels stay fast and bounded in memory.+const MAX_RASTER_CELLS: f64 = 4_000_000.0;+/// Marker in `<board>.kicad_dru` comments that opts into blocking on copper imbalance.+pub const DRU_BLOCKING_MARKER: &str = "adom-aiflow: copperBalanceBlocking";+/// Marker prefix in `<board>.kicad_dru` comments that sets a fab-profile imbalance threshold.+pub const DRU_MAX_IMBALANCE_MARKER: &str = "adom-aiflow: maxCopperImbalancePct";++fn r1(v: f64) -> f64 {+    (v * 10.0).round() / 10.0+}++fn r2(v: f64) -> f64 {+    (v * 100.0).round() / 100.0+}++/// Configurable copper-balance policy resolved from spec and optional `.kicad_dru` profile.+#[derive(Debug, Clone, PartialEq)]+pub struct Policy {+    pub max_imbalance_pct: f64,+    pub min_outer_pct: f64,+    pub blocking: bool,+    pub resolution_mm: f64,+    pub source: String,+}++impl Default for Policy {+    fn default() -> Self {+        Self {+            max_imbalance_pct: DEFAULT_MAX_IMBALANCE_PCT,+            min_outer_pct: DEFAULT_MIN_OUTER_PCT,+            blocking: false,+            resolution_mm: DEFAULT_RESOLUTION_MM,+            source: "default".into(),+        }+    }+}++/// Parse `# adom-aiflow: copperBalanceBlocking` from a `.kicad_dru` file.+pub fn dru_declares_blocking(text: &str) -> bool {+    text.lines().any(|l| {+        let l = l.trim_start();+        l.starts_with('#') && l.contains(DRU_BLOCKING_MARKER)+    })+}++/// Parse `# adom-aiflow: maxCopperImbalancePct <N>` from a `.kicad_dru` file.+pub fn dru_max_imbalance_pct(text: &str) -> Option<f64> {+    for l in text.lines() {+        let l = l.trim_start();+        if !l.starts_with('#') {+            continue;+        }+        if let Some(idx) = l.find(DRU_MAX_IMBALANCE_MARKER) {+            let rest = l[idx + DRU_MAX_IMBALANCE_MARKER.len()..].trim_start_matches([':', '=', ' ', '\t']);+            let tok: String = rest+                .chars()+                .take_while(|c| c.is_ascii_digit() || *c == '.')+                .collect();+            if let Ok(v) = tok.parse::<f64>() {+                if v.is_finite() && v > 0.0 && v <= 100.0 {+                    return Some(v);+                }+            }+        }+    }+    None+}++/// Resolve copper-balance thresholds and opt-in blocking from `spec` and `<board>.kicad_dru`.+/// Spec settings take precedence over `.kicad_dru` comments, which take precedence over defaults.+pub fn policy(spec: &Value, board_path: &str) -> Policy {+    let dru_text = if board_path.is_empty() {+        None+    } else {+        std::fs::read_to_string(Path::new(board_path).with_extension("kicad_dru")).ok()+    };+    policy_with_dru(spec, dru_text.as_deref())+}++pub fn policy_with_dru(spec: &Value, dru_text: Option<&str>) -> Policy {+    let mut sources: Vec<&str> = Vec::new();++    let spec_max = spec["fab"]["maxCopperImbalancePct"]+        .as_f64()+        .or_else(|| spec["copperBalance"]["maxImbalancePct"].as_f64())+        .filter(|v| v.is_finite() && *v > 0.0 && *v <= 100.0);+    let dru_max = dru_text.and_then(dru_max_imbalance_pct);+    let max_imbalance_pct = if let Some(v) = spec_max {+        sources.push("spec");+        v+    } else if let Some(v) = dru_max {+        sources.push("dru");+        v+    } else {+        DEFAULT_MAX_IMBALANCE_PCT+    };++    let min_outer_pct = spec["fab"]["minOuterCopperPct"]+        .as_f64()+        .or_else(|| spec["copperBalance"]["minOuterCopperPct"].as_f64())+        .filter(|v| v.is_finite() && *v >= 0.0 && *v <= 100.0)+        .unwrap_or(DEFAULT_MIN_OUTER_PCT);++    let spec_block = spec["fab"]["copperBalanceBlocking"]+        .as_bool()+        .or_else(|| spec["copperBalance"]["blocking"].as_bool());+    let blocking = if let Some(b) = spec_block {+        if !sources.contains(&"spec") {+            sources.push("spec");+        }+        b+    } else if dru_text.is_some_and(dru_declares_blocking) {+        if !sources.contains(&"dru") {+            sources.push("dru");+        }+        true+    } else {+        false+    };++    let resolution_mm = spec["copperBalance"]["resolutionMm"]+        .as_f64()+        .filter(|v| v.is_finite())+        .map(|v| v.clamp(0.05, 1.0))+        .unwrap_or(DEFAULT_RESOLUTION_MM);++    Policy {+        max_imbalance_pct,+        min_outer_pct,+        blocking,+        resolution_mm,+        source: if sources.is_empty() {+            "default".into()+        } else {+            sources.join("+")+        },+    }+}++/// Boolean copper raster inside a bounding box at resolution `res` mm per cell.+/// Adapted from `adom-eda-checks` (`coppermap::Raster`).+#[derive(Clone)]+pub struct Raster {+    pub x0: f64,+    pub y0: f64,+    pub res: f64,+    pub w: usize,+    pub h: usize,+    pub cells: Vec<bool>,+}++impl Raster {+    pub fn new(x0: f64, y0: f64, x1: f64, y1: f64, res: f64) -> Self {+        let w = (((x1 - x0) / res).ceil() as usize).max(1);+        let h = (((y1 - y0) / res).ceil() as usize).max(1);+        Self {+            x0,+            y0,+            res,+            w,+            h,+            cells: vec![false; w * h],+        }+    }++    #[inline]+    fn centre(&self, i: usize, j: usize) -> (f64, f64) {+        (+            self.x0 + (i as f64 + 0.5) * self.res,+            self.y0 + (j as f64 + 0.5) * self.res,+        )+    }++    /// Exact index bounds `[i0, i1)` x `[j0, j1)` of cells whose centres lie in `[x0, x1]` x `[y0, y1]`.+    #[inline]+    fn span(&self, x0: f64, y0: f64, x1: f64, y1: f64) -> (usize, usize, usize, usize) {+        let lo = |v: f64, o: f64, n: usize| (((v - o) / self.res - 0.5).ceil().max(0.0) as usize).min(n);+        let hi = |v: f64, o: f64, n: usize| (((v - o) / self.res + 0.5).floor().max(0.0) as usize).min(n);+        let (i0, i1) = (lo(x0, self.x0, self.w), hi(x1, self.x0, self.w));+        let (j0, j1) = (lo(y0, self.y0, self.h), hi(y1, self.y0, self.h));+        (i0, j0, i1.max(i0), j1.max(j0))+    }++    /// Rasterize a segment of width `w` with round end caps (track, arc chord, via disc).+    pub fn capsule(&mut self, ax: f64, ay: f64, bx: f64, by: f64, w: f64) {+        if w <= 0.0 {+            return;+        }+        let r = w * 0.5;+        let r2 = r * r;+        let (i0, j0, i1, j1) = self.span(+            ax.min(bx) - r,+            ay.min(by) - r,+            ax.max(bx) + r,+            ay.max(by) + r,+        );+        let (dx, dy) = (bx - ax, by - ay);+        let l2 = dx * dx + dy * dy;+        for j in j0..j1 {+            let row = j * self.w;+            for i in i0..i1 {+                if self.cells[row + i] {+                    continue;+                }+                let (x, y) = self.centre(i, j);+                let t = if l2 > 0.0 {+                    (((x - ax) * dx + (y - ay) * dy) / l2).clamp(0.0, 1.0)+                } else {+                    0.0+                };+                let (px, py) = (ax + t * dx - x, ay + t * dy - y);+                if px * px + py * py <= r2 {+                    self.cells[row + i] = true;+                }+            }+        }+    }++    /// Scanline even-odd polygon fill. For a single KiCad fractured `filled_polygon` ring,+    /// holes joined by zero-width bridges stay empty while solid copper sets cells to `on`.+    pub fn poly(&mut self, ring: &[Pt], on: bool) {+        if ring.len() < 3 {+            return;+        }+        let mut lo_y = f64::INFINITY;+        let mut hi_y = f64::NEG_INFINITY;+        for &(_, y) in ring {+            if y < lo_y {+                lo_y = y;+            }+            if y > hi_y {+                hi_y = y;+            }+        }+        let (_, j0, _, j1) = self.span(self.x0, lo_y, self.x0, hi_y);+        let n = ring.len();+        let mut xs: Vec<f64> = Vec::with_capacity(16);+        for j in j0..j1 {+            let y = self.y0 + (j as f64 + 0.5) * self.res;+            xs.clear();+            for k in 0..n {+                let (a, b) = (ring[k], ring[(k + 1) % n]);+                if (a.1 <= y) != (b.1 <= y) {+                    xs.push(a.0 + (y - a.1) / (b.1 - a.1) * (b.0 - a.0));+                }+            }+            if xs.len() < 2 {+                continue;+            }+            xs.sort_by(|a, b| a.total_cmp(b));+            let row = j * self.w;+            for pair in xs.chunks_exact(2) {+                let (i0, _, i1, _) = self.span(pair[0], y, pair[1], y);+                for i in i0..i1 {+                    self.cells[row + i] = on;+                }+            }+        }+    }++    pub fn and_mask(&mut self, mask: &Raster) {+        for (c, m) in self.cells.iter_mut().zip(&mask.cells) {+            *c = *c && *m;+        }+    }++    pub fn count(&self) -> usize {+        self.cells.iter().filter(|&&c| c).count()+    }++    /// Count active cells in each quadrant split at `(mx, my)` in KiCad coordinates (Y down):+    /// `[TL, TR, BL, BR]`.+    pub fn quadrant_counts(&self, mx: f64, my: f64) -> [usize; 4] {+        let mut q = [0usize; 4];+        for j in 0..self.h {+            let y = self.y0 + (j as f64 + 0.5) * self.res;+            let row_off = if y < my { 0 } else { 2 };+            let row = j * self.w;+            for i in 0..self.w {+                if self.cells[row + i] {+                    let x = self.x0 + (i as f64 + 0.5) * self.res;+                    let col_off = if x < mx { 0 } else { 1 };+                    q[row_off + col_off] += 1;+                }+            }+        }+        q+    }+}++/// Ordered physical stackup copper layer names (`F.Cu`, `In1.Cu`, ..., `B.Cu`).+pub fn ordered_copper_layers(board: &Board) -> Vec<String> {+    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" => 0usize,+        "B.Cu" => 10_000usize,+        s => s+            .strip_prefix("In")+            .and_then(|r| r.strip_suffix(".Cu"))+            .and_then(|k| k.parse::<usize>().ok())+            .unwrap_or(5_000),+    });+    names.dedup();+    names+}++/// Extract polygon vertices from a KiCad `(pts ...)` node, sampling KiCad 10 `(arc ...)` children.+fn pts_of_node(parent: &Node) -> Vec<Pt> {+    let Some(pts) = parent.find("pts") else {+        return Vec::new();+    };+    let at = |n: &Node, tag: &str| n.find(tag).and_then(|p| Some((p.number(1)?, p.number(2)?)));+    let mut out = Vec::new();+    for c in pts.nodes() {+        match c.tag.as_str() {+            "xy" => {+                if let (Some(x), Some(y)) = (c.number(1), c.number(2)) {+                    out.push((x, y));+                }+            }+            "arc" => {+                if let (Some(a), Some(m), Some(b)) = (at(c, "start"), at(c, "mid"), at(c, "end")) {+                    for pt in geom::arc_points(a, m, b, 0.25) {+                        if out.last() != Some(&pt) {+                            out.push(pt);+                        }+                    }+                }+            }+            _ => {}+        }+    }+    out+}++fn zone_layers(z: &Node, board_layers: &[String]) -> Vec<String> {+    let mut raw: Vec<String> = Vec::new();+    if let Some(l) = z.find("layer").and_then(Node::value) {+        raw.push(l.to_string());+    }+    if let Some(ls) = z.find("layers") {+        for i in 1.. {+            match ls.atom(i) {+                Some(a) => raw.push(a.to_string()),+                None => break,+            }+        }+    }+    let mut out = Vec::new();+    for n in raw {+        let expanded: Vec<String> = match n.as_str() {+            "*.Cu" => board_layers.to_vec(),+            "F&B.Cu" => vec!["F.Cu".into(), "B.Cu".into()],+            s if s.ends_with(".Cu") => vec![s.to_string()],+            _ => vec![],+        };+        for l in expanded {+            if board_layers.iter().any(|b| b == &l) && !out.contains(&l) {+                out.push(l);+            }+        }+    }+    out+}++fn rasterize_board_copper_graphics(board: &Board, maps: &mut BTreeMap<String, Raster>) {+    let p2 = |n: Option<&Node>| -> Option<Pt> {+        let n = n?;+        Some((n.number(1)?, n.number(2)?))+    };+    for node in board.root.nodes() {+        if !node.tag.starts_with("gr_") {+            continue;+        }+        let Some(layer) = node.find("layer").and_then(Node::value) else {+            continue;+        };+        let Some(r) = maps.get_mut(layer) else {+            continue;+        };+        let stroke_w = node+            .find("stroke")+            .and_then(|s| s.find("width"))+            .and_then(|w| w.number(1))+            .or_else(|| node.find("width").and_then(|w| w.number(1)))+            .unwrap_or(0.15);+        let filled = node+            .find("fill")+            .and_then(Node::value)+            .map(|v| v == "solid" || v == "yes")+            .unwrap_or(node.tag == "gr_poly");+        match node.tag.as_str() {+            "gr_poly" => {+                let poly = pts_of_node(node);+                if poly.len() >= 3 {+                    if filled {+                        r.poly(&poly, true);+                    } else if stroke_w > 0.0 {+                        for k in 0..poly.len() {+                            let (a, b) = (poly[k], poly[(k + 1) % poly.len()]);+                            r.capsule(a.0, a.1, b.0, b.1, stroke_w);+                        }+                    }+                }+            }+            "gr_rect" => {+                if let (Some(a), Some(b)) = (p2(node.find("start")), p2(node.find("end"))) {+                    let poly = vec![a, (b.0, a.1), b, (a.0, b.1)];+                    if filled {+                        r.poly(&poly, true);+                    } else if stroke_w > 0.0 {+                        for k in 0..4 {+                            r.capsule(poly[k].0, poly[k].1, poly[(k + 1) % 4].0, poly[(k + 1) % 4].1, stroke_w);+                        }+                    }+                }+            }+            "gr_circle" => {+                if let (Some(c), Some(e)) = (p2(node.find("center")), p2(node.find("end"))) {+                    let rad = (e.0 - c.0).hypot(e.1 - c.1);+                    if filled {+                        r.capsule(c.0, c.1, c.0, c.1, rad * 2.0);+                    } else if stroke_w > 0.0 {+                        let ring = geom::circle_poly(c.0, c.1, rad, 32);+                        for k in 0..ring.len() {+                            let (a, b) = (ring[k], ring[(k + 1) % ring.len()]);+                            r.capsule(a.0, a.1, b.0, b.1, stroke_w);+                        }+                    }+                }+            }+            "gr_line" => {+                if let (Some(a), Some(b)) = (p2(node.find("start")), p2(node.find("end"))) {+                    r.capsule(a.0, a.1, b.0, b.1, stroke_w);+                }+            }+            "gr_arc" => {+                if let (Some(a), Some(m), Some(b)) = (p2(node.find("start")), p2(node.find("mid")), p2(node.find("end"))) {+                    let pts = geom::arc_points(a, m, b, 0.2);+                    for w in pts.windows(2) {+                        r.capsule(w[0].0, w[0].1, w[1].0, w[1].1, stroke_w);+                    }+                }+            }+            _ => {}+        }+    }+}++/// Audit copper balance on `board` using the resolved policy for `spec` and `board_path`.+pub fn audit(board: &Board, spec: &Value, board_path: &str) -> Value {+    let pol = policy(spec, board_path);+    audit_with_policy(board, &pol, None)+}++/// Audit copper balance on `board` while previewing planned zones (used by `pour` before zones are+/// landed and filled in KiCad). Planned copper zones are rasterized from their outlines only on+/// layers that do not already have saved `filled_polygon`s for that net.+pub fn audit_with_planned_zones(board: &Board, spec: &Value, board_path: &str, planned_zones: &[Value]) -> Value {+    let pol = policy(spec, board_path);+    audit_with_policy(board, &pol, Some(planned_zones))+}++/// Pure offline copper-balance audit with explicit `Policy` and optional planned zone preview.+pub fn audit_with_policy(board: &Board, pol: &Policy, planned_zones: Option<&[Value]>) -> Value {+    let layers = ordered_copper_layers(board);+    if board.outline.len() < 3 {+        return json!({+            "pass": true,+            "balanced": true,+            "blocking": pol.blocking,+            "error": "no closed Edge.Cuts outline",+            "layers": [],+            "pairs": [],+            "warnings": [],+            "findings": [],+            "hints": ["Add a closed Edge.Cuts board outline before auditing copper balance."],+        });+    }++    let (x0, y0, x1, y1) = board.bbox;+    let bw = (x1 - x0).max(0.1);+    let bh = (y1 - y0).max(0.1);+    let mut res = pol.resolution_mm.clamp(0.05, 1.0);+    if (bw / res) * (bh / res) > MAX_RASTER_CELLS {+        let scaled = ((bw * bh) / MAX_RASTER_CELLS).sqrt();+        res = ((scaled / 0.05).ceil() * 0.05).max(res);+    }++    let mut board_mask = Raster::new(x0, y0, x1, y1, res);+    board_mask.poly(&board.outline, true);+    for cutout in &board.outline_cutouts {+        board_mask.poly(cutout, false);+    }+    let total_cells = board_mask.count();+    if total_cells == 0 {+        return json!({+            "pass": true,+            "balanced": true,+            "blocking": pol.blocking,+            "error": "board outline has zero area",+            "layers": [],+            "pairs": [],+            "warnings": [],+            "findings": [],+            "hints": [],+        });+    }++    let cell_area = res * res;+    let board_area_mm2 = total_cells as f64 * cell_area;+    let (mx, my) = ((x0 + x1) * 0.5, (y0 + y1) * 0.5);+    let board_quads = board_mask.quadrant_counts(mx, my);++    let mut maps: BTreeMap<String, Raster> = BTreeMap::new();+    for l in &layers {+        maps.insert(l.clone(), Raster::new(x0, y0, x1, y1, res));+    }++    // 1. Filled zones on every copper layer + track unfilled zones+    let mut layer_has_fill: BTreeSet<String> = BTreeSet::new();+    let mut filled_net_layers: BTreeSet<(String, String)> = BTreeSet::new();+    let mut unfilled_zones: Vec<Value> = Vec::new();+    for z in board.root.find_all("zone") {+        if z.find("keepout").is_some() {+            continue;+        }+        let net = z+            .find("net_name")+            .and_then(Node::value)+            .map(str::to_string)+            .unwrap_or_else(|| board.item_net(z));+        let zname = z.find("name").and_then(Node::value).unwrap_or("").to_string();+        let zlayers = zone_layers(z, &layers);+        let outline_pts = z.find("polygon").map(pts_of_node).unwrap_or_default();+        let has_outline = outline_pts.len() >= 3 && geom::polygon_area(&outline_pts).abs() > 1e-6;++        let mut filled_on_this_zone: BTreeSet<String> = BTreeSet::new();+        for fp in z.find_all("filled_polygon") {+            let Some(layer) = fp.find("layer").and_then(Node::value) else {+                continue;+            };+            let Some(r) = maps.get_mut(layer) else {+                continue;+            };+            let poly = pts_of_node(fp);+            if poly.len() >= 3 {+                r.poly(&poly, true);+                filled_on_this_zone.insert(layer.to_string());+                layer_has_fill.insert(layer.to_string());+                filled_net_layers.insert((net.clone(), layer.to_string()));+            }+        }+        // Legacy hatched zone fill segments (when present)+        for fs in z.find_all("fill_segments") {+            let Some(layer) = fs.find("layer").and_then(Node::value) else {+                continue;+            };+            let Some(r) = maps.get_mut(layer) else {+                continue;+            };+            let pts = pts_of_node(fs);+            for pair in pts.chunks_exact(2) {+                r.capsule(pair[0].0, pair[0].1, pair[1].0, pair[1].1, 0.2);+                filled_on_this_zone.insert(layer.to_string());+                layer_has_fill.insert(layer.to_string());+                filled_net_layers.insert((net.clone(), layer.to_string()));+            }+        }+        if has_outline {+            for l in &zlayers {+                if !filled_on_this_zone.contains(l) {+                    unfilled_zones.push(json!({"net": net, "layer": l, "name": zname}));+                }+            }+        }+    }++    // Optional planned zone preview (for `pour` stage before KiCad fills them)+    let mut planned_outlines_used = false;+    if let Some(pzones) = planned_zones {+        // First apply planned copper zone outlines where not already filled+        for pz in pzones {+            if pz.get("keepout").is_some() || pz["type"].as_str() == Some("keepout") {+                continue;+            }+            let net = pz["net"].as_str().unwrap_or("").to_string();+            let pts: Vec<Pt> = pz["polygon"]+                .as_array()+                .map(|a| {+                    a.iter()+                        .filter_map(|q| Some((q[0].as_f64()?, q[1].as_f64()?)))+                        .collect()+                })+                .unwrap_or_default();+            if pts.len() < 3 {+                continue;+            }+            for l in pz["layers"].as_array().into_iter().flatten().filter_map(Value::as_str) {+                if filled_net_layers.contains(&(net.clone(), l.to_string())) {+                    continue;+                }+                if let Some(r) = maps.get_mut(l) {+                    r.poly(&pts, true);+                    planned_outlines_used = true;+                }+            }+        }+        // Punch planned pour keepouts out of the planned preview+        if planned_outlines_used {+            for pz in pzones {+                let is_pour_keepout = pz["keepout"]["copperPour"] == true+                    || pz["keepout"]["pours"] == true;+                if !is_pour_keepout {+                    continue;+                }+                let pts: Vec<Pt> = pz["polygon"]+                    .as_array()+                    .map(|a| {+                        a.iter()+                            .filter_map(|q| Some((q[0].as_f64()?, q[1].as_f64()?)))+                            .collect()+                    })+                    .unwrap_or_default();+                if pts.len() < 3 {+                    continue;+                }+                for l in pz["layers"].as_array().into_iter().flatten().filter_map(Value::as_str) {+                    if let Some(r) = maps.get_mut(l) {+                        r.poly(&pts, false);+                    }+                }+            }+        }+    }++    // 2. Tracks and arcs on every copper layer+    for tr in board.copper_tracks() {+        let lname = match tr.layer {+            aiflow_board::F_CU => "F.Cu".to_string(),+            aiflow_board::B_CU => "B.Cu".to_string(),+            k => format!("In{}.Cu", k - 1),+        };+        if let Some(r) = maps.get_mut(&lname) {+            r.capsule(tr.a.0, tr.a.1, tr.b.0, tr.b.1, tr.width);+        }+    }++    // 3. Copper pads (skipping unplated mounting holes whose drill covers the full pad size)+    for pad in &board.pads {+        let zero_annulus_npth = pad.drill.is_some_and(|d| d >= pad.size.0.min(pad.size.1) - 1e-4);+        if zero_annulus_npth {+            continue;+        }+        for l in &layers {+            let Some(cl) = copper_layer(l) else {+                continue;+            };+            if !pad.on_copper(cl) {+                continue;+            }+            if let Some(r) = maps.get_mut(l) {+                for poly in &pad.polys {+                    r.poly(poly, true);+                }+            }+        }+    }++    // 4. Vias (respecting blind/buried layer spans)+    for v in board.vias() {+        for l in &layers {+            let Some(cl) = copper_layer(l) else {+                continue;+            };+            if !v.on_copper(cl) {+                continue;+            }+            if let Some(r) = maps.get_mut(l) {+                r.capsule(v.x, v.y, v.x, v.y, v.size);+            }+        }+    }++    // 5. Board-level copper graphic items (logos, manual copper thieving shapes)+    rasterize_board_copper_graphics(board, &mut maps);++    // 6. Clip every layer to board outline (minus cutouts) and compute percentages and quadrants+    let mut layer_pct: BTreeMap<String, f64> = BTreeMap::new();+    let mut layer_quad_pct: BTreeMap<String, [f64; 4]> = BTreeMap::new();+    let mut layer_rows: Vec<Value> = Vec::new();+    let mut sparse_outer_warnings: Vec<String> = Vec::new();+    let mut sparse_outer_layers: Vec<(String, f64)> = Vec::new();++    for l in &layers {+        let r = maps.get_mut(l).unwrap();+        r.and_mask(&board_mask);+        let cu_cells = r.count();+        let cu_mm2 = cu_cells as f64 * cell_area;+        let pct = 100.0 * cu_cells as f64 / total_cells as f64;+        let q_cu = r.quadrant_counts(mx, my);+        let mut q_pct = [0.0f64; 4];+        let mut valid_q: Vec<f64> = Vec::new();+        for idx in 0..4 {+            if board_quads[idx] > 0 {+                q_pct[idx] = 100.0 * q_cu[idx] as f64 / board_quads[idx] as f64;+                if (board_quads[idx] as f64 / total_cells as f64) >= 0.05 {+                    valid_q.push(q_pct[idx]);+                }+            }+        }+        let q_spread = if valid_q.len() >= 2 {+            let lo = valid_q.iter().copied().fold(f64::INFINITY, f64::min);+            let hi = valid_q.iter().copied().fold(f64::NEG_INFINITY, f64::max);+            hi - lo+        } else {+            0.0+        };+        let is_outer = l == "F.Cu" || l == "B.Cu";+        let sparse_outer = is_outer && layers.len() >= 2 && pol.min_outer_pct > 0.0 && pct < pol.min_outer_pct;+        if sparse_outer {+            sparse_outer_warnings.push(format!(+                "sparse outer layer {l}: {:.1}% copper (below {:.0}% plating-uniformity guideline)",+                pct, pol.min_outer_pct+            ));+            sparse_outer_layers.push((l.clone(), pct));+        }++        layer_pct.insert(l.clone(), pct);+        layer_quad_pct.insert(l.clone(), q_pct);+        layer_rows.push(json!({+            "layer": l,+            "copperMm2": r1(cu_mm2),+            "percent": r1(pct),+            "hasFilledZones": layer_has_fill.contains(l),+            "quadrants": {+                "TL": r1(q_pct[0]),+                "TR": r1(q_pct[1]),+                "BL": r1(q_pct[2]),+                "BR": r1(q_pct[3]),+            },+            "quadrantSpreadPoints": r1(q_spread),+            "sparseOuter": sparse_outer,+        }));+    }++    // 7. Mirrored layer pairs about the core: (0, k-1), (1, k-2), ...+    let k = layers.len();+    let mut pair_rows: Vec<Value> = Vec::new();+    let mut pair_findings: Vec<String> = Vec::new();+    let mut max_imbalance = 0.0f64;+    let mut hints: Vec<String> = Vec::new();++    for i in 0..(k / 2) {+        let top = &layers[i];+        let bot = &layers[k - 1 - i];+        let p_top = layer_pct[top];+        let p_bot = layer_pct[bot];+        let diff = (p_top - p_bot).abs();+        if diff > max_imbalance {+            max_imbalance = diff;+        }+        let q_top = layer_quad_pct[top];+        let q_bot = layer_quad_pct[bot];+        let q_diffs = [+            (q_top[0] - q_bot[0]).abs(),+            (q_top[1] - q_bot[1]).abs(),+            (q_top[2] - q_bot[2]).abs(),+            (q_top[3] - q_bot[3]).abs(),+        ];+        let max_q_diff = q_diffs.iter().copied().fold(0.0f64, f64::max);+        let pair_ok = diff <= pol.max_imbalance_pct + 1e-6;+        let (lighter, lighter_pct, heavier, heavier_pct) = if p_top <= p_bot {+            (top.as_str(), p_top, bot.as_str(), p_bot)+        } else {+            (bot.as_str(), p_bot, top.as_str(), p_top)+        };+        if !pair_ok {+            pair_findings.push(format!(+                "copper imbalance on {top}/{bot}: {top} {:.1}% vs {bot} {:.1}% (delta {:.1} pp > {:.0} pp limit; lighter layer is {lighter})",+                p_top, p_bot, diff, pol.max_imbalance_pct+            ));+            hints.push(format!(+                "Rebalance {top}/{bot} ({:.1} pp delta): pour a ground/power plane, add hatched fill, or place non-functional copper thieving on {lighter} ({:.1}%), or trim excess pour on {heavier} ({:.1}%). Keep thieving >= 1.5 mm from controlled-impedance and high-speed traces.",+                diff, lighter_pct, heavier_pct+            ));+        }+        pair_rows.push(json!({+            "layers": [top, bot],+            "percent": [r1(p_top), r1(p_bot)],+            "differencePoints": r1(diff),+            "lighterLayer": lighter,+            "heavierLayer": heavier,+            "quadrantDiffs": {+                "TL": r1(q_diffs[0]),+                "TR": r1(q_diffs[1]),+                "BL": r1(q_diffs[2]),+                "BR": r1(q_diffs[3]),+            },+            "maxQuadrantDiffPoints": r1(max_q_diff),+            "ok": pair_ok,+        }));+    }++    for (l, pct) in &sparse_outer_layers {+        hints.push(format!(+            "Outer layer {l} is sparse ({:.1}% copper): add a GND pour, hatched fill, or copper thieving on {l} to improve electroplating uniformity and reduce bow/twist risk.",+            pct+        ));+    }++    if !unfilled_zones.is_empty() && !planned_outlines_used {+        hints.push(format!(+            "{} copper zone(s) have no saved fill in the board file: refill zones in KiCad (Edit > Fill All Zones) and re-save before trusting copper balance.",+            unfilled_zones.len()+        ));+    }++    let balanced = pair_findings.is_empty();+    let mut warnings = pair_findings.clone();+    warnings.extend(sparse_outer_warnings.clone());++    if warnings.is_empty() && unfilled_zones.is_empty() {+        hints.push(format!(+            "Mirrored layers stay within {:.0} pp of each other (max delta {:.1} pp): copper balance looks good for lamination and reflow.",+            pol.max_imbalance_pct, max_imbalance+        ));+    } else if !pol.blocking && !pair_findings.is_empty() {+        hints.push(format!(+            "Copper balance warnings are advisory by default. Adjust threshold with spec.fab.maxCopperImbalancePct (currently {:.0} pp) or opt into blocking with spec.fab.copperBalanceBlocking: true (or `# {DRU_BLOCKING_MARKER}` in .kicad_dru).",+            pol.max_imbalance_pct+        ));+    }++    json!({+        "pass": balanced,+        "balanced": balanced,+        "blocking": pol.blocking,+        "policySource": pol.source,+        "thresholdPoints": r1(pol.max_imbalance_pct),+        "minOuterCopperPercent": r1(pol.min_outer_pct),+        "boardMm2": r1(board_area_mm2),+        "resolutionMm": r2(res),+        "hasFilledZones": !layer_has_fill.is_empty(),+        "estimatedFromPlannedZones": planned_outlines_used,+        "maxPairImbalancePoints": r1(max_imbalance),+        "layers": layer_rows,+        "pairs": pair_rows,+        "unfilledZones": unfilled_zones,+        "findings": pair_findings,+        "sparseOuterWarnings": sparse_outer_warnings,+        "warnings": warnings,+        "hints": hints,+    })+}++/// Compact multi-line human summary for CLI output (`pour`, `gate`, `finish`, `analyze balance`).+pub fn format_summary(report: &Value) -> Vec<String> {+    let layers = report["layers"].as_array().cloned().unwrap_or_default();+    if layers.is_empty() {+        return Vec::new();+    }+    let layer_str: Vec<String> = layers+        .iter()+        .map(|l| {+            format!(+                "{} {:.1}%",+                l["layer"].as_str().unwrap_or("?"),+                l["percent"].as_f64().unwrap_or(0.0)+            )+        })+        .collect();+    let est = if report["estimatedFromPlannedZones"] == true {+        ", planned outlines preview"+    } else {+        ""+    };+    let mut lines = vec![format!(+        "copper balance: {} (board {:.1} mm2, res {:.2} mm{est})",+        layer_str.join(", "),+        report["boardMm2"].as_f64().unwrap_or(0.0),+        report["resolutionMm"].as_f64().unwrap_or(DEFAULT_RESOLUTION_MM)+    )];++    let pairs = report["pairs"].as_array().cloned().unwrap_or_default();+    if !pairs.is_empty() {+        let thresh = report["thresholdPoints"].as_f64().unwrap_or(DEFAULT_MAX_IMBALANCE_PCT);+        let pair_str: Vec<String> = pairs+            .iter()+            .map(|p| {+                let a = p["layers"][0].as_str().unwrap_or("?");+                let b = p["layers"][1].as_str().unwrap_or("?");+                let d = p["differencePoints"].as_f64().unwrap_or(0.0);+                let tag = if p["ok"] == true {+                    "ok".to_string()+                } else {+                    format!("WARN > {thresh:.0} pp")+                };+                format!("{a}/{b} {d:.1} pp ({tag})")+            })+            .collect();+        lines.push(format!("  mirrored pairs: {}", pair_str.join(", ")));+    }++    let quad_str: Vec<String> = layers+        .iter()+        .map(|l| {+            let q = &l["quadrants"];+            format!(+                "{} {:.0}/{:.0}/{:.0}/{:.0}%",+                l["layer"].as_str().unwrap_or("?"),+                q["TL"].as_f64().unwrap_or(0.0),+                q["TR"].as_f64().unwrap_or(0.0),+                q["BL"].as_f64().unwrap_or(0.0),+                q["BR"].as_f64().unwrap_or(0.0),+            )+        })+        .collect();+    lines.push(format!("  quadrants (TL/TR/BL/BR): {}", quad_str.join(", ")));+    lines+}++#[cfg(test)]+mod tests {+    use super::*;++    fn board_4l(zones: &str, segs: &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)) \+             (net 0 \"\") (net 1 \"GND\") (net 2 \"VCC\") \+             (gr_rect (start 0 0) (end 40 20) (layer \"Edge.Cuts\") (stroke (width 0.1) (type solid))) \+             {segs} {zones})"+        );+        Board::from_text("cb-test.kicad_pcb", pcb).unwrap()+    }++    fn full_zone(layer: &str, net_id: i32, net_name: &str, x0: f64, y0: f64, x1: f64, y1: f64) -> String {+        format!(+            "(zone (net {net_id}) (net_name \"{net_name}\") (layer \"{layer}\") \+             (polygon (pts (xy {x0} {y0}) (xy {x1} {y0}) (xy {x1} {y1}) (xy {x0} {y1}))) \+             (filled_polygon (layer \"{layer}\") (pts (xy {x0} {y0}) (xy {x1} {y0}) (xy {x1} {y1}) (xy {x0} {y1}))))"+        )+    }++    #[test]+    fn balanced_4l_board_passes_clean_with_accurate_quadrants() {+        let zones = [+            full_zone("F.Cu", 1, "GND", 1.0, 1.0, 39.0, 19.0),+            full_zone("In1.Cu", 1, "GND", 1.0, 1.0, 39.0, 19.0),+            full_zone("In2.Cu", 2, "VCC", 1.0, 1.0, 39.0, 19.0),+            full_zone("B.Cu", 1, "GND", 1.0, 1.0, 39.0, 19.0),+        ]+        .join(" ");+        let b = board_4l(&zones, "");+        let rep = audit(&b, &json!({}), "");+        assert_eq!(rep["pass"], true, "{rep}");+        assert_eq!(rep["balanced"], true, "{rep}");+        assert_eq!(rep["blocking"], false);+        assert!(rep["maxPairImbalancePoints"].as_f64().unwrap() < 0.5, "{rep}");+        // 38*18 / 40*20 = 684 / 800 = 85.5%+        let f_pct = rep["layers"][0]["percent"].as_f64().unwrap();+        assert!((f_pct - 85.5).abs() < 1.0, "expected ~85.5%, got {f_pct}");+        for q in ["TL", "TR", "BL", "BR"] {+            let qp = rep["layers"][0]["quadrants"][q].as_f64().unwrap();+            assert!((qp - 85.5).abs() < 1.5, "quad {q}: {qp}");+        }+        assert!(rep["warnings"].as_array().unwrap().is_empty(), "{rep}");+    }++    #[test]+    fn imbalanced_4l_inner_pair_flags_and_names_lighter_layer_with_fix_hint() {+        // In1.Cu ~90% filled, In2.Cu ~20% filled (left strip only) -> 70 pp delta+        let zones = [+            full_zone("F.Cu", 1, "GND", 2.0, 1.0, 38.0, 19.0),+            full_zone("In1.Cu", 1, "GND", 1.0, 0.5, 39.0, 19.5),+            full_zone("In2.Cu", 2, "VCC", 1.0, 0.5, 9.5, 19.5),+            full_zone("B.Cu", 1, "GND", 2.0, 1.0, 38.0, 19.0),+        ]+        .join(" ");+        let b = board_4l(&zones, "");+        let rep = audit(&b, &json!({}), "");+        assert_eq!(rep["pass"], false, "{rep}");+        assert_eq!(rep["balanced"], false);+        assert_eq!(rep["blocking"], false);+        let inner = &rep["pairs"][1];+        assert_eq!(inner["layers"], json!(["In1.Cu", "In2.Cu"]));+        assert_eq!(inner["ok"], false);+        assert_eq!(inner["lighterLayer"], "In2.Cu");+        let diff = inner["differencePoints"].as_f64().unwrap();+        assert!((diff - 70.0).abs() < 3.0, "expected ~70 pp, got {diff}");+        // Left quadrants of In2.Cu should carry copper while right quadrants are ~0%+        assert!(rep["layers"][2]["quadrants"]["TL"].as_f64().unwrap() > 35.0, "{rep}");+        assert!(rep["layers"][2]["quadrants"]["TR"].as_f64().unwrap() < 1.0, "{rep}");+        let hints = rep["hints"].as_array().unwrap();+        assert!(+            hints.iter().any(|h| {+                let s = h.as_str().unwrap_or("");+                s.contains("In2.Cu") && s.contains("thieving") && s.contains("hatched")+            }),+            "{hints:?}"+        );+    }++    #[test]+    fn six_layer_mirrored_pairs_match_about_core() {+        let pcb = r#"(kicad_pcb (version 20241229) (generator "test")+          (layers (0 "F.Cu" signal) (4 "In1.Cu" signal) (6 "In2.Cu" signal) (8 "In3.Cu" signal) (10 "In4.Cu" signal) (2 "B.Cu" signal) (25 "Edge.Cuts" user))+          (net 0 "") (net 1 "GND")+          (gr_rect (start 0 0) (end 20 20) (layer "Edge.Cuts"))+          (zone (net 1) (net_name "GND") (layer "In1.Cu") (polygon (pts (xy 0 0) (xy 20 0) (xy 20 20) (xy 0 20))) (filled_polygon (layer "In1.Cu") (pts (xy 0 0) (xy 20 0) (xy 20 20) (xy 0 20))))+        )"#;+        let b = Board::from_text("6l.kicad_pcb", pcb.to_string()).unwrap();+        let rep = audit(&b, &json!({}), "");+        let pairs: Vec<(&str, &str)> = rep["pairs"]+            .as_array()+            .unwrap()+            .iter()+            .map(|p| (p["layers"][0].as_str().unwrap(), p["layers"][1].as_str().unwrap()))+            .collect();+        assert_eq!(pairs, vec![("F.Cu", "B.Cu"), ("In1.Cu", "In4.Cu"), ("In2.Cu", "In3.Cu")]);+        assert_eq!(rep["pairs"][0]["ok"], true);+        assert_eq!(rep["pairs"][1]["ok"], false);+        assert_eq!(rep["pairs"][2]["ok"], true);+    }++    #[test]+    fn fractured_kicad_fill_and_overlapping_tracks_do_not_double_count() {+        // 10x10 mm board (100 mm^2), 8x8 fill (64 mm^2) with a 4x4 fractured hole (16 mm^2) -> 48 mm^2 = 48%.+        // Plus two identical overlapping tracks lying completely inside the solid fill: area must stay ~48%.+        let pcb = r#"(kicad_pcb (version 20241229) (generator "test")+          (layers (0 "F.Cu" signal) (2 "B.Cu" signal) (25 "Edge.Cuts" user))+          (net 0 "") (net 1 "GND")+          (gr_rect (start 0 0) (end 10 10) (layer "Edge.Cuts"))+          (zone (net 1) (net_name "GND") (layer "F.Cu")+            (polygon (pts (xy 1 1) (xy 9 1) (xy 9 9) (xy 1 9)))+            (filled_polygon (layer "F.Cu") (pts (xy 1 1) (xy 9 1) (xy 9 9) (xy 1 9) (xy 1 3) (xy 3 3) (xy 3 7) (xy 7 7) (xy 7 3) (xy 3 3) (xy 1 3))))+          (segment (start 1.5 2) (end 8.5 2) (width 1.0) (layer "F.Cu") (net 1))+          (segment (start 1.5 2) (end 8.5 2) (width 1.0) (layer "F.Cu") (net 1))+          (footprint "MountingHole:MH" (layer "F.Cu") (at 5 5) (property "Reference" "H1")+            (pad "" np_thru_hole circle (at 0 0) (size 3.0 3.0) (drill 3.0) (layers "*.Cu" "*.Mask")))+        )"#;+        let b = Board::from_text("frac.kicad_pcb", pcb.to_string()).unwrap();+        let rep = audit(&b, &json!({}), "");+        let f_pct = rep["layers"][0]["percent"].as_f64().unwrap();+        let b_pct = rep["layers"][1]["percent"].as_f64().unwrap();+        assert!((f_pct - 48.0).abs() < 1.5, "expected ~48%, got {f_pct} ({rep})");+        assert!(b_pct < 0.5, "NPTH mounting hole must not count as copper on B.Cu: {b_pct}");+    }++    #[test]+    fn spec_and_dru_knobs_control_threshold_and_blocking() {+        let dru = "(version 1)\n# adom-aiflow: copperBalanceBlocking\n# adom-aiflow: maxCopperImbalancePct 12\n";+        let p_dru = policy_with_dru(&json!({}), Some(dru));+        assert!(p_dru.blocking);+        assert_eq!(p_dru.max_imbalance_pct, 12.0);+        // Explicit spec false and threshold win over .kicad_dru+        let p_spec = policy_with_dru(+            &json!({"fab": {"copperBalanceBlocking": false, "maxCopperImbalancePct": 15}}),+            Some(dru),+        );+        assert!(!p_spec.blocking);+        assert_eq!(p_spec.max_imbalance_pct, 15.0);+        // Comment marker inside a rule string does not count+        let p_rule = policy_with_dru(&json!({}), Some("(rule \"adom-aiflow: copperBalanceBlocking\")"));+        assert!(!p_rule.blocking);+        assert_eq!(p_rule.max_imbalance_pct, DEFAULT_MAX_IMBALANCE_PCT);+    }++    #[test]+    fn scanline_span_has_no_one_cell_inflation_bias() {+        // 20 thin vertical bars of width 0.4 mm each across a 20x10 mm board:+        // true copper area = 20 * 0.4 * 10 = 80 mm^2 = 40.0%.+        // A 1-cell left-edge bias at 0.1 mm resolution would inflate this to 50.0%!+        let mut r = Raster::new(0.0, 0.0, 20.0, 10.0, 0.1);+        for k in 0..20 {+            let x0 = k as f64 + 0.2;+            let x1 = x0 + 0.4;+            r.poly(&[(x0, 0.0), (x1, 0.0), (x1, 10.0), (x0, 10.0)], true);+        }+        let area = r.count() as f64 * 0.01;+        assert!((area - 80.0).abs() < 0.5, "expected 80.0 mm^2 without edge bias, got {area}");+    }++    #[test]+    fn planned_zones_preview_catches_lopsided_pour_plan_before_fill() {+        let b = board_4l("", "");+        let planned = vec![json!({+            "net": "GND",+            "layers": ["In1.Cu"],+            "polygon": [[1.0, 1.0], [39.0, 1.0], [39.0, 19.0], [1.0, 19.0]]+        })];+        let rep = audit_with_planned_zones(&b, &json!({}), "", &planned);+        assert_eq!(rep["estimatedFromPlannedZones"], true, "{rep}");+        assert_eq!(rep["balanced"], false, "{rep}");+        assert_eq!(rep["pairs"][1]["lighterLayer"], "In2.Cu");+        assert!(rep["pairs"][1]["differencePoints"].as_f64().unwrap() > 80.0);+    }+}
crates/aiflow-analyze/src/lib.rs+1
@@ -6,6 +6,7 @@ //! the fix. 0.2 computes cross-sections through the filled polygons and IR drop per net. pub mod board_sink; pub mod branches;+pub mod copper_balance; pub mod current_acks; pub mod fields_report; pub mod lead_cooling;
skills/adom-aiflow/SKILL.md+5
@@ -341,6 +341,11 @@ The clock starts at the prompt even when there is no board yet. - Opt in to blocking for a fab that wants silk clearance enforced: `"fab": {"silkBlocking": true}` in the spec, or a comment line `# adom-aiflow: silkBlocking` in the board's `.kicad_dru` rules profile. Then they block as before 0.2.19 (an explicit `"silkBlocking": false` in the spec wins over the rules file). - KiCad's STEP export keeps the whole ink. So `board-glb copper` lays the exposed copper over the ink inside every mask opening, the way the fab prints it, and `board-glb check` fails a GLB whose silkscreen is not clipped where copper is exposed. +**Copper balance and layer-pair symmetry are reported, not blocking by default.** `pour`, `gate`, `finish`, `export` and `analyze balance` measure per-layer copper area percentage inside `Edge.Cuts` (filled zones, tracks, arcs, pads, vias and copper graphics, without double-counting overlaps), mirrored layer-pair deltas (`F.Cu/B.Cu`, `In1.Cu/In2.Cu` on 4L, `In1.Cu/In4.Cu` and `In2.Cu/In3.Cu` on 6L), and a four-quadrant view (`TL/TR/BL/BR`).+- Thresholds: warns when any mirrored pair differs by more than `20` percentage points (configurable via `"fab": {"maxCopperImbalancePct": 15}` or `.kicad_dru` comment `# adom-aiflow: maxCopperImbalancePct 15`), or when an outer layer (`F.Cu` or `B.Cu`) sits below `15%` copper (`"fab": {"minOuterCopperPct": 15}`, set `0` to disable).+- Hints name the lighter layer and suggest rebalancing pours, adding a hatched fill, or placing non-functional copper thieving (keeping thieving at least `1.5 mm` from high-speed traces).+- Never blocks a finished board by default. Opt in to blocking with `"fab": {"copperBalanceBlocking": true}` in the spec or `# adom-aiflow: copperBalanceBlocking` in the board's `.kicad_dru` rules profile (an explicit `"copperBalanceBlocking": false` in the spec wins over the rules file). Results are recorded in `gate.json`, `run.json` (`pour`, `gate`, `copper-balance`, `summary.copperBalance`) and `export-check.json`.+ ## A KiCad board from scratch (0.2.0)  A KiCad run that starts with no board (`intake` with no `start --board`) follows the `kicad-new` sequence: intake, rules, design, test-plan, sourcing, **parts**, **project-page**, **library**, **schematic**, simulation, then components, models and the board steps as usual. Hydrogen is the stage for the steps without KiCad (the step dashboard comes up at every new phase), KiCad's window for the rest.
skills/aiflow-power-layout/SKILL.md+1
@@ -59,6 +59,7 @@ Kelvin keepouts follow the tap's own layer (both layers only at its vias) and st - **Thermal vias beside small pins.** A SOT-23 or 0603 pad is too small for a via; an open via in it wicks solder. Put 0.6/0.3 mm vias in the solid pour just outside the pad, clear of other nets (`pour` now does this and says how many of `count` fit). `aiflow-router` keeps `allowViaInPad` off by default, and `gate`, `finish`, and `export` run a board-wide VIPPO audit separating large thermal EPADs (>= 4 mm2) from standard SMD pads; standard SMD via-in-pad requires `"fab": {"viaInPad": "filled-capped", "viaInPadWhy": "..."}` on a VIPPO-capable fab (emitting an IPC-4761 Type VII note on `export`). `gate` and `finish` also classify board vias (`signal-routing`, `power-fanout`, `thermal`, `stitching`), flag dense plane-perforating clusters (> 4 non-thermal vias within 3 mm) and high signal-via ratios (> 1.0/net or > 2 on a non-bus net), and `route` runs a post-route via-elimination pass. - **Count the vias a pad already has.** `pour` counts the pad's existing vias (an exposed pad's datasheet in-pad pattern too) toward `thermalVias[].count` and keeps planned vias clear of them; `land vias` refuses a via within the hole-to-hole minimum or via-to-via clearance of any via or hole before anything lands. - **Check every landed via's net.** A planned GND via whose pad touched the SW trace landed as SW and DRC passed. After `land vias`, read each via's net on the live board against the plan.+- **Keep mirrored layers balanced.** `pour` previews planned zone balance, and `gate`, `finish`, `export` and `analyze balance` measure per-layer copper percentage (filled zones, tracks, pads, vias), mirrored layer-pair deltas (`F.Cu/B.Cu`, `In1.Cu/In2.Cu`, `In1.Cu/In4.Cu`), and quadrants (`TL/TR/BL/BR`). By default it warns above 20 pp pair imbalance (or < 15% outer-layer copper) without blocking, suggesting a pour rebalance, hatched fill, or copper thieving on the lighter layer. Tune with `spec.fab.maxCopperImbalancePct` or opt into blocking with `spec.fab.copperBalanceBlocking: true` (or `# adom-aiflow: copperBalanceBlocking` in `.kicad_dru`).  ## 5. Current density: iterate with Fields 
tests/copper-balance-workflow.pyadded+234
@@ -0,0 +1,234 @@+"""Per-layer copper balance, mirrored layer-pair symmetry, and quadrant view end to end:+1. Balanced 4L board passes analyze balance and gate cleanly with per-layer %, pairs, and quadrants+2. Imbalanced 4L board (In1 ~90% vs In2 ~20%) warns in analyze balance, gate, and finish without blocking by default+3. Spec opt-in (fab.copperBalanceBlocking + maxCopperImbalancePct) enforces blocking in analyze balance, gate, and finish+4. Fab profile (.kicad_dru comment markers) sets threshold and blocking, and explicit spec false overrides .kicad_dru+5. pour stage previews planned-zone imbalance before landing and clears once pours are rebalanced+6. export writes copperBalance into export-check.json when kicad-cli is runnable+Usage: python3 tests/copper-balance-workflow.py <adom-aiflow binary>"""+import json+import os+import pathlib+import shutil+import subprocess+import sys+import tempfile++binary = str(pathlib.Path(sys.argv[1]).resolve())+++def zone_sexpr(layer, net_id, net_name, x0, y0, x1, y1):+    return (+        f'(zone (net {net_id}) (net_name "{net_name}") (layer "{layer}") '+        f'(polygon (pts (xy {x0} {y0}) (xy {x1} {y0}) (xy {x1} {y1}) (xy {x0} {y1}))) '+        f'(filled_polygon (layer "{layer}") (pts (xy {x0} {y0}) (xy {x1} {y0}) (xy {x1} {y1}) (xy {x0} {y1}))))'+    )+++def make_4l_board(path, zones=""):+    segs = (+        '(segment (start 7.2 10) (end 7.2 7.5) (width 0.25) (layer "F.Cu") (net 1)) '+        '(segment (start 7.2 7.5) (end 31.2 7.5) (width 0.25) (layer "F.Cu") (net 1)) '+        '(segment (start 31.2 7.5) (end 31.2 10) (width 0.25) (layer "F.Cu") (net 1)) '+        '(segment (start 8.8 10) (end 8.8 13.5) (width 0.25) (layer "F.Cu") (net 2)) '+        '(segment (start 8.8 13.5) (end 32.8 13.5) (width 0.25) (layer "F.Cu") (net 2)) '+        '(segment (start 32.8 13.5) (end 32.8 10) (width 0.25) (layer "F.Cu") (net 2))'+    )+    path.write_text(+        '(kicad_pcb (version 20241229) (generator "test") (general (thickness 1.6)) '+        '(layers (0 "F.Cu" signal) (4 "In1.Cu" signal) (6 "In2.Cu" signal) (2 "B.Cu" signal) (25 "Edge.Cuts" user)) '+        '(net 0 "") (net 1 "SIG") (net 2 "GND") (net 3 "VCC") '+        '(footprint "Resistor_SMD:R_0603" (layer "F.Cu") (at 8 10) (property "Reference" "R1") (property "Value" "10k") '+        '(fp_rect (start -1.5 -0.7) (end 1.5 0.7) (layer "F.CrtYd") (stroke (width 0.05) (type solid))) '+        '(pad "1" smd rect (at -0.8 0) (size 0.8 0.9) (layers "F.Cu") (net 1 "SIG")) '+        '(pad "2" smd rect (at 0.8 0) (size 0.8 0.9) (layers "F.Cu") (net 2 "GND"))) '+        '(footprint "Resistor_SMD:R_0603" (layer "F.Cu") (at 32 10) (property "Reference" "R2") (property "Value" "10k") '+        '(fp_rect (start -1.5 -0.7) (end 1.5 0.7) (layer "F.CrtYd") (stroke (width 0.05) (type solid))) '+        '(pad "1" smd rect (at -0.8 0) (size 0.8 0.9) (layers "F.Cu") (net 1 "SIG")) '+        '(pad "2" smd rect (at 0.8 0) (size 0.8 0.9) (layers "F.Cu") (net 2 "GND"))) '+        f'{segs} {zones} '+        '(gr_rect (start 0 0) (end 40 20) (layer "Edge.Cuts") (stroke (width 0.1) (type solid))))'+    )+++def runnable_kicad_cli(env):+    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+++with tempfile.TemporaryDirectory(prefix='aiflow-copper-balance-') 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', 'balance-test', *args],+            env=env, capture_output=True, text=True, timeout=120+        )++    base_dru = '(version 1)\n# adom-aiflow rules: jlcpcb 4L (from test)\n(rule "c" (constraint clearance (min 0.127mm)))\n'+    spec_default = p / 'spec_default.json'+    spec_default.write_text(json.dumps({+        "clearance": 0.15, "minTrackWidth": 0.127, "track": 0.25,+        "fab": {"rules": "jlcpcb-4L"}+    }))++    # 1. Balanced 4L board passes analyze balance and gate cleanly+    bal_zones = " ".join([+        zone_sexpr("F.Cu", 2, "GND", 1.0, 1.0, 39.0, 19.0),+        zone_sexpr("In1.Cu", 2, "GND", 1.0, 1.0, 39.0, 19.0),+        zone_sexpr("In2.Cu", 3, "VCC", 1.0, 1.0, 39.0, 19.0),+        zone_sexpr("B.Cu", 2, "GND", 1.0, 1.0, 39.0, 19.0),+    ])+    b_bal = p / 'balanced.kicad_pcb'+    make_4l_board(b_bal, zones=bal_zones)+    b_bal.with_suffix('.kicad_dru').write_text(base_dru)++    run1 = p / 'run-balanced'+    assert call(run1, 'start', '--board', str(b_bal), '--spec', str(spec_default), '--engine', 'test', '--prompt-time', '2026-12-02T00:00:00Z').returncode == 0+    rb1 = call(run1, 'analyze', 'balance')+    assert rb1.returncode == 0 and rb1.stdout.startswith('OK:'), rb1.stdout + rb1.stderr+    assert 'quadrants (TL/TR/BL/BR):' in rb1.stdout, rb1.stdout+    rj1 = json.loads((run1 / 'run.json').read_text())+    cb1 = rj1['outcomes']['analyze-balance']+    assert cb1['balanced'] is True and cb1['maxPairImbalancePoints'] <= 2.0, cb1+    rg1 = call(run1, 'gate')+    assert rg1.returncode == 0 and rg1.stdout.startswith('OK:'), rg1.stdout + rg1.stderr+    g1 = json.loads((run1 / 'gate.json').read_text())+    assert g1['copperBalance']['balanced'] is True, g1['copperBalance']+    print('  [1/6] balanced 4L board passed analyze balance and gate cleanly')++    # 2. Imbalanced 4L board warns without blocking by default across analyze balance, gate, and finish+    imb_zones = " ".join([+        zone_sexpr("F.Cu", 2, "GND", 1.0, 1.0, 39.0, 19.0),+        zone_sexpr("In1.Cu", 2, "GND", 1.0, 0.5, 39.0, 19.5),+        zone_sexpr("In2.Cu", 3, "VCC", 1.0, 0.5, 9.5, 19.5),+        zone_sexpr("B.Cu", 2, "GND", 1.0, 1.0, 39.0, 19.0),+    ])+    b_imb = p / 'imbalanced.kicad_pcb'+    make_4l_board(b_imb, zones=imb_zones)+    b_imb.with_suffix('.kicad_dru').write_text(base_dru)++    run2 = p / 'run-imbalanced'+    assert call(run2, 'start', '--board', str(b_imb), '--spec', str(spec_default), '--engine', 'test', '--prompt-time', '2026-12-02T00:00:00Z').returncode == 0+    rb2 = call(run2, 'analyze', 'balance')+    assert rb2.returncode == 0 and rb2.stdout.startswith('OK:'), rb2.stdout + rb2.stderr+    assert 'WARN:' in rb2.stdout and 'In2.Cu' in rb2.stdout and 'thieving' in rb2.stdout, rb2.stdout+    rg2 = call(run2, 'gate')+    assert rg2.returncode == 0 and rg2.stdout.startswith('OK:'), rg2.stdout + rg2.stderr+    assert 'Warning (copper balance):' in rg2.stderr, rg2.stderr+    g2 = json.loads((run2 / 'gate.json').read_text())+    assert g2['copperBalance']['balanced'] is False and g2['copperBalance']['blocking'] is False, g2['copperBalance']+    assert g2['copperBalance']['maxPairImbalancePoints'] > 60.0, g2['copperBalance']+    rf2 = call(run2, 'finish')+    assert rf2.returncode == 0, rf2.stdout + rf2.stderr+    rj2 = json.loads((run2 / 'run.json').read_text())+    assert rj2['summary']['copperBalance']['balanced'] is False, rj2['summary']['copperBalance']+    assert not any('copper balance' in item.lower() for item in rj2['summary']['open']), rj2['summary']['open']+    print('  [2/6] imbalanced 4L board warned in analyze balance, gate, and finish without blocking by default')++    # 3. Spec opt-in blocking enforces failure in analyze balance, gate, and finish open items+    spec_block = p / 'spec_block.json'+    spec_block.write_text(json.dumps({+        "clearance": 0.15, "minTrackWidth": 0.127, "track": 0.25,+        "fab": {"rules": "jlcpcb-4L", "maxCopperImbalancePct": 15, "copperBalanceBlocking": True}+    }))+    run3 = p / 'run-blocking-spec'+    assert call(run3, 'start', '--board', str(b_imb), '--spec', str(spec_block), '--engine', 'test', '--prompt-time', '2026-12-02T00:00:00Z').returncode == 0+    rb3 = call(run3, 'analyze', 'balance')+    assert rb3.returncode == 2 and rb3.stdout.startswith('ERROR:'), rb3.stdout + rb3.stderr+    rg3 = call(run3, 'gate')+    assert 'copper balance (blocking because copperBalanceBlocking is on)' in rg3.stdout, rg3.stdout + rg3.stderr+    rf3 = call(run3, 'finish')+    rj3 = json.loads((run3 / 'run.json').read_text())+    assert any('copper balance' in item.lower() for item in rj3['summary']['open']), rj3['summary']['open']+    print('  [3/6] spec fab.copperBalanceBlocking enforced blocking in analyze balance, gate, and finish')++    # 4. .kicad_dru comment markers set threshold & blocking; explicit spec false overrides+    b_dru = p / 'dru-optin.kicad_pcb'+    make_4l_board(b_dru, zones=imb_zones)+    b_dru.with_suffix('.kicad_dru').write_text(+        '(version 1)\n# adom-aiflow rules: jlcpcb 4L (from test)\n'+        '# adom-aiflow: copperBalanceBlocking\n'+        '# adom-aiflow: maxCopperImbalancePct 12\n'+        '(rule "c" (constraint clearance (min 0.127mm)))\n'+    )+    run4 = p / 'run-dru-block'+    assert call(run4, 'start', '--board', str(b_dru), '--spec', str(spec_default), '--engine', 'test', '--prompt-time', '2026-12-02T00:00:00Z').returncode == 0+    rb4 = call(run4, 'analyze', 'balance')+    assert rb4.returncode == 2 and rb4.stdout.startswith('ERROR:'), rb4.stdout + rb4.stderr+    cb4 = json.loads((run4 / 'run.json').read_text())['outcomes']['analyze-balance']+    assert cb4['blocking'] is True and cb4['thresholdPoints'] == 12.0, cb4++    spec_override = p / 'spec_override.json'+    spec_override.write_text(json.dumps({+        "clearance": 0.15, "minTrackWidth": 0.127, "track": 0.25,+        "fab": {"rules": "jlcpcb-4L", "copperBalanceBlocking": False}+    }))+    run4b = p / 'run-dru-override'+    assert call(run4b, 'start', '--board', str(b_dru), '--spec', str(spec_override), '--engine', 'test', '--prompt-time', '2026-12-02T00:00:00Z').returncode == 0+    rb4b = call(run4b, 'analyze', 'balance')+    assert rb4b.returncode == 0 and rb4b.stdout.startswith('OK:'), rb4b.stdout + rb4b.stderr+    print('  [4/6] .kicad_dru markers opted into blocking and threshold, and spec false overrode .kicad_dru')++    # 5. pour stage previews planned-zone imbalance before landing, and clears when balanced+    b_unpoured = p / 'unpoured.kicad_pcb'+    make_4l_board(b_unpoured, zones="")+    b_unpoured.with_suffix('.kicad_dru').write_text(base_dru)++    spec_pour_imb = p / 'spec_pour_imb.json'+    spec_pour_imb.write_text(json.dumps({+        "clearance": 0.15, "minTrackWidth": 0.127, "track": 0.25,+        "fab": {"rules": "jlcpcb-4L"},+        "pours": [+            {"net": "GND", "layers": ["In1.Cu"], "outline": True, "inset": 0.5}+        ]+    }))+    run5a = p / 'run-pour-imb'+    assert call(run5a, 'start', '--board', str(b_unpoured), '--spec', str(spec_pour_imb), '--engine', 'test', '--prompt-time', '2026-12-02T00:00:00Z').returncode == 0+    rp5a = call(run5a, 'pour')+    assert rp5a.returncode == 0 and rp5a.stdout.startswith('OK:'), rp5a.stdout + rp5a.stderr+    assert 'Warning (copper balance):' in rp5a.stderr and 'In2.Cu' in rp5a.stdout, rp5a.stdout + rp5a.stderr+    cb5a = json.loads((run5a / 'run.json').read_text())['outcomes']['pour']['copperBalance']+    assert cb5a['estimatedFromPlannedZones'] is True and cb5a['balanced'] is False, cb5a++    spec_pour_bal = p / 'spec_pour_bal.json'+    spec_pour_bal.write_text(json.dumps({+        "clearance": 0.15, "minTrackWidth": 0.127, "track": 0.25,+        "fab": {"rules": "jlcpcb-4L"},+        "pours": [+            {"net": "GND", "layers": ["In1.Cu"], "outline": True, "inset": 0.5},+            {"net": "GND", "layers": ["In2.Cu"], "outline": True, "inset": 0.5},+        ]+    }))+    run5b = p / 'run-pour-bal'+    assert call(run5b, 'start', '--board', str(b_unpoured), '--spec', str(spec_pour_bal), '--engine', 'test', '--prompt-time', '2026-12-02T00:00:00Z').returncode == 0+    rp5b = call(run5b, 'pour')+    assert rp5b.returncode == 0 and rp5b.stdout.startswith('OK:'), rp5b.stdout + rp5b.stderr+    cb5b = json.loads((run5b / 'run.json').read_text())['outcomes']['pour']['copperBalance']+    assert cb5b['balanced'] is True and cb5b['maxPairImbalancePoints'] < 10.0, cb5b+    print('  [5/6] pour stage previewed planned-zone imbalance and passed when In1/In2 were balanced')++    # 6. export writes copperBalance into export-check.json when kicad-cli is runnable+    kicad_bin = runnable_kicad_cli(env)+    if kicad_bin:+        out_dir = p / 'mfg-balance'+        re = call(run2, 'export', '--out', str(out_dir))+        check_json = out_dir / 'export-check.json'+        assert check_json.exists(), re.stdout + re.stderr+        ec = json.loads(check_json.read_text())+        assert 'copperBalance' in ec and ec['copperBalance']['balanced'] is False, ec.get('copperBalance')+        print(f'  [6/6] export wrote copperBalance into export-check.json (via {kicad_bin})')+    else:+        print('  [6/6] SKIP kicad-cli not runnable in this environment')++print('PASS: copper balance audit verified across pour, gate, finish, analyze balance, export, spec knobs, and .kicad_dru profile.')