← Commit history
CHANGELOG.md+13
@@ -1,5 +1,18 @@ # Changelog +## 0.2.75 (2026-10-26)+**Reviews, pair routing, length tuning, thermal vias, a board report: eight new verbs (201).**+- New verb `altium_schematic_review`: every placed pin (from the sheet files, with its electrical type) against Altium's compiled netlist: power pins on no net and outputs together (errors), pins on no net, one-pin nets, undriven inputs and IC supplies with no decoupling capacitor (warnings; inductor nets taken as switch nodes). Bluetooth Sentinel: 15 sheets, 194 pins, 65 nets in 8 s.+- New verb `altium_pin_pad_check`: symbol pins against footprint pads per part, and parts on only one side.+- New verb `altium_route_pair`: a differential pair routed as a pair along one centreline, sized by `diffOhms` from the stack-up, the plan checked before it lands (crossing nets, a segment over another net's pad), with its own width rule. 90 ohm test pair: skew 0.042 mm, DRC clean.+- New verb `altium_length_tune`: a serpentine sized to the exact missing length (or another net's), clear of other copper. 23.231 to 30.000 mm, DRC clean.+- New verb `altium_thermal_vias`: a via grid in an exposed pad, sized by the board's via rule, clear of the vias already there (Sentinel U4: +8, DRC 0).+- New verb `altium_board_report`: every check on one board and a picture of it, as one self-contained dark HTML page.+- New verb `altium_placement_check`: courtyard overlaps, parts off or over the edge (judged by pads), pads near the edge (by their corners), parts on mounting holes.+- New verb `altium_auto_classes`: GND, Power, Clock and HighSpeed classes and differential pairs from the net names, proposed, then written with apply.+- `altium_set_design_rules {fab:"jlcpcb"}`: JLCPCB's limits for the board's layers and copper weight written as its rules, vias at the surcharge-free 0.5 / 0.3 mm unless `costlier`.+- Verb battery: all eight on the lane board.+ ## 0.2.74 (2026-10-26) **A JLCPCB order in one call, return-path fixes, bottom-side designators, declined prompts on record.** - New verb `altium_jlcpcb_order`: the JLCPCB fab check, the manufacturing outputs, the JLCPCB BOM and CPL and the assembly-tier check in one call, written to one folder: a Gerber zip with only the Gerber layers and the drill file, `bom-jlcpcb.csv`, `cpl-jlcpcb.csv` and `order.json`, with the order-form values and every issue in one list. Measured on the lane board in 21 s.
README.md+17−7
@@ -15,7 +15,7 @@ normal session. Ask in plain words and it: - makes the outputs: Gerbers, NC drill, pick and place, BOMs grouped by MPN (JLCPCB, Mouser, DigiKey files),   schematic PDF and STEP, checking that the outline and every copper layer reached the Gerbers -193 commands, tested on Altium Designer 26.11 and Altium Designer Develop. It runs in **Hydrogen**, Adom's free+201 commands, tested on Altium Designer 26.11 and Altium Designer Develop. It runs in **Hydrogen**, Adom's free desktop app, through Adom Bridge. You bring your own AI subscription and your own Altium licence.  ::youtube{id="dFecpcIzdSE" title="An AI designs a 12 V to 5 V buck converter in Altium Designer"}@@ -29,7 +29,7 @@ and the verb prefix `altium_`.  ## What it can do -Tested on Altium Designer 26.11.1 and Altium Designer Develop. 193 verbs; each row names the ones+Tested on Altium Designer 26.11.1 and Altium Designer Develop. 201 verbs; each row names the ones behind it (prefix `altium_`).  | Area | What the AI can do | Verbs |@@ -38,14 +38,14 @@ behind it (prefix `altium_`). | Parts in one step | Import a whole part (symbol, footprint, STEP, parameters) in one call; put an Adom wiki part on a sheet with the `altium-wiki-part` command (symbol, footprint, a 3D chip laser-etched with its part number, Mouser / DigiKey / LCSC numbers); import KiCad files | `import_part`, `install_library_bundle`, `add_symbol_art`, `import_kicad` | | Altium 365 | Search the workspace's components and place one on a sheet with its workspace link, parameters and footprint; GraphQL queries and library uploads with a workspace token | `workspace_search`, `workspace_place`, `a365_*` | | Schematics | Draw a schematic from a netlist, place library parts, wire pins (wire, net label or power port), move, rotate, rename and delete parts, swap a part for another without breaking its connections, annotate, fill the title block, cross-probe, hierarchical sheets (sheet symbols with entries, ports on the child), the compiled netlist checked net by net | `build_schematic`, `sch_place_part`, `sch_connect`, `sch_edit`, `sch_swap_part`, `annotate`, `doc_params`, `sch_zoom`, `sch_sheet_symbol`, `netlist` |-| Checks | Compile and ERC with the Messages panel read back, DRC with each violation's location, a 14-check design review, schematic-to-board cross-check | `compile`, `run_erc`, `run_drc`, `routing_drc`, `review_board`, `cross_check` |+| Checks | Compile and ERC with the Messages panel read back, DRC with each violation's location, a 14-check design review, schematic-to-board cross-check, a schematic review before Update PCB (unconnected pins, one-pin nets, missing decoupling), symbols against footprints, a placement review, one shareable HTML report per board | `compile`, `run_erc`, `run_drc`, `routing_drc`, `review_board`, `cross_check`, `schematic_review`, `pin_pad_check`, `placement_check`, `board_report` | | Schematic to board | Update PCB with the whole change order previewed row by row first, keeping board-only parts, net classes and rules | `update_pcb` |-| Board setup | Build a board from a netlist, shape the outline, edit the stack-up (add planes and inner layers, set copper, dielectrics and total thickness), write a fab's design rules, add scoped rules, net classes and differential pairs, length limits, matched-length groups, differential-pair width and gap, via styles, component classes with rooms | `build_board`, `set_outline`, `board_outline`, `layer_stack`, `set_design_rules`, `add_rule`, `net_classes`, `diff_pairs`, `component_classes` |+| Board setup | Build a board from a netlist, shape the outline, edit the stack-up (add planes and inner layers, set copper, dielectrics and total thickness), write a fab's design rules, add scoped rules, net classes and differential pairs, length limits, matched-length groups, differential-pair width and gap, via styles, component classes with rooms, net classes and pairs from the net names, a fab's rules (JLCPCB built in) | `auto_classes`, `build_board`, `set_outline`, `board_outline`, `layer_stack`, `set_design_rules`, `add_rule`, `net_classes`, `diff_pairs`, `component_classes` | | Signal and power | The trace width for a target impedance on every copper layer of the real stack-up (50 ohm single-ended, 90 or 100 ohm pairs with their gap), written as rules if asked; whether each power net's narrowest track and its vias carry its current (IPC-2221); signal tracks that run over a gap in the reference copper next to them (return paths), with a pour-patch plan to close each gap; copper balance per layer | `impedance`, `current_capacity`, `return_path`, `copper_balance` | | 3D and enclosure | Each part's height from its 3D bodies, the parts over an enclosure's height limit or under a lid feature, and bodies that collide or sit too close | `height_check` | | Board furniture | Mounting holes (at points or the corners), fiducials with a mask opening and no paste, a stitching-via grid that keeps clear of other nets, pads and parts, a via fence along RF tracks and the board edge | `board_features`, `via_fence` | | Placement | Move and rotate parts or shift them by an offset (read back to 0.001 mm), find free space for a part near another, suggest rotations that shorten connections, copy one channel's layout to the others, swap footprints, read or set the selection | `move_parts`, `find_space`, `check_orientation`, `replicate_layout`, `swap_footprint`, `selection` |-| Routing and copper | Route a net with waypoints and vias, run Altium's autorouter, rip up nets, resize routed tracks, pour polygons with keepouts, repour, place vias, clean up the silkscreen, add teardrops, measure routed length per net and the skew of each pair | `route_net`, `autoroute`, `ripup_nets`, `set_track_width`, `apply_pours`, `repour`, `place_vias`, `apply_silkscreen`, `teardrops`, `net_lengths` |+| Routing and copper | Route a net with waypoints and vias, run Altium's autorouter, rip up nets, resize routed tracks, pour polygons with keepouts, repour, place vias, clean up the silkscreen, add teardrops, measure routed length per net and the skew of each pair, route a differential pair as a pair at its impedance, tune a net's length with a serpentine, thermal vias in exposed pads | `route_pair`, `length_tune`, `thermal_vias`, `route_net`, `autoroute`, `ripup_nets`, `set_track_width`, `apply_pours`, `repour`, `place_vias`, `apply_silkscreen`, `teardrops`, `net_lengths` | | BOM | Bill of materials straight from Altium, grouped by MPN with a variant applied, JLCPCB / Mouser / DigiKey files, ordering gaps flagged; write parameters back to the sheets; assembly variants | `bom`, `sheet_params`, `variants` | | Manufacturing outputs | Gerbers, NC drill, pick and place, BOM, ODB++ and IPC-2581 in one call, checking that the outline and every copper layer reached the Gerbers; the board checked against a fab's limits before ordering (JLCPCB's built in), and against JLCPCB's Economic and Standard assembly tiers; a whole JLCPCB order folder (Gerber zip, BOM, CPL, order-form values, every issue) in one call; a step-and-repeat panel with rails, tooling holes and fiducials, separated by V-score lines or mouse-bite tabs drawn the way JLCPCB reads them, with JLCPCB's panel rules checked; any OutJob, and read an OutJob's containers and settings; the schematic as a PDF with assembly and fabrication drawings; STEP; silkscreen cleaned off the pads first with Altium's Silkscreen Preparation, and every designator placed clear of pads and other labels | `export_manufacturing`, `jlcpcb_order`, `fab_check`, `assembly_check`, `panelize`, `run_outjob`, `outjob_info`, `export_pdf`, `export_step`, `silkscreen_prep`, `silk_designators` | | Reading the design | The whole board as data in mm, schematic parts with pins, rules, layers, poured copper, silkscreen, every part parameter in the project; a .SchDoc read straight from the file without Altium | `read_board`, `routing_state`, `schematic_data`, `read_sheet_file`, `part_parameters`, `read_rules`, `pour_state`, `silk_state`, `pcb_report` |@@ -54,6 +54,8 @@ behind it (prefix `altium_`).  Current, heat and EMC analysis of an Altium board runs through [AI Flow](https://wiki.adom.inc/adom/adom-aiflow). +This bridge is the reference for the [EDA Bridge Standard](https://wiki.adom.inc/adom/eda-bridge-standard): its verbs and board model are the ones every Adom EDA bridge (KiCad, Fusion 360 and the next) is measured against.+ > ### Two things on this page: which one do you want? > > | | **Release ZIP** (`adom-bridge-altium-v*.zip`) | **Package** (`adom-wiki pkg install adom/altium-bridge`) |@@ -68,7 +70,7 @@ Current, heat and EMC analysis of an Altium board runs through [AI Flow](https:/  Altium Designer is the user's own **host app**. The bridge finds an installed Altium (`%ProgramFiles%\Altium\AD*\X2.EXE`, Designer or Develop), starts it in the background, runs a small-**DelphiScript agent** inside it, and gives the AI 193 `altium_*` verbs.+**DelphiScript agent** inside it, and gives the AI 201 `altium_*` verbs.  - **Page and docs:** https://wiki.adom.inc/adom/altium-bridge - **Bridge SDK:** https://wiki.adom.inc/adom/adom-bridge-sdk@@ -168,7 +170,7 @@ way to read it). A stopped engine is restarted with `altium_agent_recover`.  <!-- verbs:start (tools/readme_verbs.py writes this list) --> -All 193 verbs, by area (prefix `altium_`). `altium_describe` returns the live catalog with every input, output, hint and example.+All 201 verbs, by area (prefix `altium_`). `altium_describe` returns the live catalog with every input, output, hint and example.  ### Running Altium: launch, close, health, dialogs @@ -263,6 +265,14 @@ All 193 verbs, by area (prefix `altium_`). `altium_describe` returns the live ca - `altium_via_fence`: A via fence for EMC: a row of ground vias on both sides of RF or fast nets' tracks, and/or round the board edge, at a pitch from the frequency (lambda/20) or given; each via clear of other copper and pads, the same net's vias and the edge. - `altium_assembly_check`: Ready for JLCPCB assembly? The board against both JLCPCB PCBA tiers as published (Economic and Standard): board or panel size, thickness and layers, parts on one or both sides, the smallest package and the finest pin pitch, fiducials, and the parts with no LCSC number; answers the cheapest tier every rule allows. - `altium_jlcpcb_order`: A JLCPCB order in one call: the board checked against JLCPCB's fab limits, the Gerbers and drill zipped the way JLCPCB's order page takes them, the JLCPCB BOM and pick-and-place (CPL), the assembly-tier check, and the order-form values, in one folder with every issue in one list.+- `altium_schematic_review`: Review the schematic before Update PCB: every placed pin (read from the sheet files, with its electrical type) against Altium's compiled netlist.+- `altium_pin_pad_check`: Do the footprints fit their symbols? Part by part, the symbol's pin numbers (from the sheet files) against the footprint's pad names (from the board): pins with no pad, pads with no pin, and parts on only the sheets or only the board.+- `altium_route_pair`: Route a differential pair as a pair: one centreline from the source pads' midpoint through waypoints to the destination pads' midpoint, each net offset to its own side at width + gap with mitred corners and a short fan-out from each pad; width and gap given or solved from the stack-up for a target impedance; both lengths and the skew answered.+- `altium_thermal_vias`: A thermal via grid in a part's exposed pad (the ground or thermal pad under a QFN, DFN, PowerPAD or regulator): centred, inset from the pad's edge, sized by the board's Routing Via rule, on the pad's net.+- `altium_board_report`: One shareable page per board: every check run against the live board and its project (Altium's DRC, JLCPCB fab limits and assembly tiers, the schematic review, symbols against footprints, impedance widths, return paths, copper balance, 3D heights) with a picture of the board, written as a single HTML file.+- `altium_placement_check`: Review the placement before routing: parts whose courtyards (pads and body, grown by a margin) overlap on the same side, parts off the board or over its edge, pads too close to the edge for assembly and depanelling, and parts on a mounting hole.+- `altium_auto_classes`: Net classes from the nets' own names: GND, Power (VCC, VDD, 3V3, VBAT...), Clock, HighSpeed (USB, Ethernet, HDMI, PCIe, DDR, MIPI, LVDS, SATA...) and the differential pairs their _P/_N, +/-, DP/DN names spell; a proposal first, written as Altium net classes (Power with a width rule) and pairs with apply.+- `altium_length_tune`: Lengthen a routed net to a target length, or to match another net (a pair's skew, a DDR byte lane): a serpentine in its longest straight track that has room beside it, the bumps sized to add exactly the length missing, every bump clear of other copper and inside the board. - `altium_remove_items`: Delete specific free tracks and vias, given exactly as altium_routing_state returned them. - `altium_ripup_nets`: Delete every free track, arc and via on each named net. - `altium_apply_pours`: Add solid polygon pours from outlines and pour them, each with its own connect style (solid joints or thermal spokes), plus pour keepouts (polygon cutouts); answers each pour's real poured copper area.
bridge-rs/src/autoclass.rsadded+90
@@ -0,0 +1,90 @@+//! Net classes from the names a designer already gave the nets: ground, power, clocks, the fast interfaces (USB,+//! Ethernet, HDMI, PCIe, DDR, MIPI, LVDS, SATA), and the differential pairs their _P/_N (+/-, DP/DN) suffixes spell;+//! proposed first, written as Altium net classes and pairs when asked.+use serde_json::{json, Value};+use std::collections::BTreeMap;++/// The class a net's name puts it in, if any. Pure.+pub fn classify(net: &str) -> Option<&'static str> {+    let n = net.to_ascii_uppercase();+    let core = n.trim_start_matches(['+', '-', '/', '\\']);+    if crate::schreview::is_ground(&n) || core.starts_with("GND") { return Some("GND"); }+    let power = core.contains("VBUS") || core.starts_with("VCC") || core.starts_with("VDD") || core.starts_with("VBAT") || core.starts_with("VIN") || core.starts_with("VBUS")+        || core.starts_with("VSYS") || core.starts_with("VREF") || core.starts_with("PWR") || core.starts_with("VCORE") || core.starts_with("VOUT")+        || (core.starts_with('V') && core.len() > 1 && core.as_bytes()[1].is_ascii_digit())+        || core.chars().next().map(|c| c.is_ascii_digit()).unwrap_or(false) && (core.contains('V'));+    // a supply's name wins over what it feeds (VDD_XTAL is the crystal's supply, not a clock)+    if power { return Some("Power"); }+    let fast = ["USB", "ETH", "RGMII", "RMII", "SGMII", "HDMI", "PCIE", "DDR", "MIPI", "CSI", "DSI", "LVDS", "SATA", "SERDES", "QSPI", "SDIO", "EMMC"];+    if fast.iter().any(|f| core.contains(f)) { return Some("HighSpeed"); }+    if core.contains("CLK") || core.contains("XTAL") || core.contains("OSC") || core.ends_with("SCK") { return Some("Clock"); }+    None+}++/// Differential pairs by name: X_P/X_N, XP/XN, X+/X-, X_DP/X_DM. Pure.+pub fn pairs(nets: &[String]) -> Vec<(String, String, String)> {+    let set: BTreeMap<String, &String> = nets.iter().map(|n| (n.to_ascii_uppercase(), n)).collect();+    let mut out = Vec::new();+    for (u, orig) in &set {+        // longest suffixes first: USB_DP must pair as USB (DP/DN), not as USB_D (P/N)+        for (p, q) in [("_DP", "_DN"), ("_DP", "_DM"), ("DP", "DN"), ("DP", "DM"), ("_P", "_N"), ("+", "-"), ("P", "N")] {+            if let Some(stem) = u.strip_suffix(p) {+                if stem.is_empty() { continue; }+                if let Some(neg) = set.get(&format!("{stem}{q}")) {+                    let name = stem.trim_end_matches('_').to_string();+                    if !out.iter().any(|(n, _, _): &(String, String, String)| *n == name) { out.push((name, (*orig).clone(), (*neg).clone())); }+                    break;+                }+            }+        }+    }+    out+}++/// altium_auto_classes {filePath?, apply?, powerWidthMm?}+pub fn auto_classes(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 nets: Vec<String> = st["nets"].as_array().cloned().unwrap_or_default().iter().filter_map(|n| n.as_str().map(String::from)).collect();+    let mut classes: BTreeMap<&str, Vec<String>> = BTreeMap::new();+    for n in &nets { if let Some(c) = classify(n) { classes.entry(c).or_default().push(n.clone()); } }+    let prs = pairs(&nets);+    let proposal = json!({"classes": classes, "pairs": prs.iter().map(|(n, p, q)| json!({"name": n, "pos": p, "neg": q})).collect::<Vec<_>>(),+                          "unclassified": nets.iter().filter(|n| classify(n).is_none()).count()});+    if args.get("apply").and_then(|b| b.as_bool()) != Some(true) {+        return json!({"success": true, "applied": false, "proposal": proposal, "_hint": "A proposal from the net names. Check it, then call again with apply:true to write the classes (Power gets a width rule, powerWidthMm, default 0.5) and the pairs."});+    }+    let mut done = Vec::new();+    for (c, members) in &classes {+        let mut a = json!({"name": c, "nets": members});+        if *c == "Power" { a["width"] = json!(args.get("powerWidthMm").and_then(|v| v.as_f64()).unwrap_or(0.5)); }+        let r = crate::design::net_classes(&a);+        done.push(json!({"class": c, "nets": members.len(), "success": r.get("success").cloned().unwrap_or(json!(false)), "error": r.get("error").cloned().unwrap_or(Value::Null)}));+    }+    for (n, p, q) in &prs {+        let r = crate::design::diff_pairs(&json!({"name": n, "pos": p, "neg": q}));+        done.push(json!({"pair": n, "success": r.get("success").cloned().unwrap_or(json!(false)), "error": r.get("error").cloned().unwrap_or(Value::Null)}));+    }+    json!({"success": done.iter().all(|d| d["success"] == json!(true)), "applied": true, "proposal": proposal, "written": done,+        "_hint": "Scope rules to them: InNetClass('Power'), InNetClass('HighSpeed'), InDifferentialPair('<name>'). altium_impedance {apply} sizes the pairs; altium_current_capacity checks the power nets."})+}++#[cfg(test)]+mod tests {+    use super::*;++    #[test]+    fn names_sort_into_classes_and_pairs() {+        for (n, c) in [("GND", Some("GND")), ("AGND", Some("GND")), ("+3V3", Some("Power")), ("VDD_CORE", Some("Power")), ("5V", Some("Power")), ("VBUS", Some("Power")),+                       ("USB_DP", Some("HighSpeed")), ("ETH_TX_P", Some("HighSpeed")), ("MCLK", Some("Clock")), ("VDD_XTAL", Some("Power")), ("USB_VBUS", Some("Power")), ("XTAL_IN", Some("Clock")), ("SPI_SCK", Some("Clock")), ("N1", None), ("LED_RED", None)] {+            assert_eq!(classify(n), c, "{n}");+        }+        let nets: Vec<String> = ["USB_DP", "USB_DN", "ETH_TX_P", "ETH_TX_N", "LVDS0+", "LVDS0-", "SDA"].iter().map(|s| s.to_string()).collect();+        let p = pairs(&nets);+        assert_eq!(p.len(), 3);+        assert!(p.iter().any(|(n, a, b)| n == "USB" && a == "USB_DP" && b == "USB_DN"));+        assert!(p.iter().any(|(n, a, b)| n == "LVDS0" && a == "LVDS0+" && b == "LVDS0-"));+    }+}
bridge-rs/src/features.rs+68
@@ -181,6 +181,63 @@ pub fn via_style(rules: &[Value]) -> Option<(f64, f64)> {     Some((num(d, "PreferedWidth").or(num(d, "PreferredWidth"))?, num(d, "PreferredHoleWidth")?)) } +/// Thermal via grid points inside a pad (x, y, sx, sy, rotation mm): `pitch` apart, `inset` from the pad's edge plus+/// the via's radius, centred. Pure.+pub fn thermal_grid(x: f64, y: f64, sx: f64, sy: f64, rot: f64, pitch: f64, size: f64, inset: f64) -> Vec<(f64, f64)> {+    let (ux, uy) = (sx / 2.0 - inset - size / 2.0, sy / 2.0 - inset - size / 2.0);+    if ux < 0.0 || uy < 0.0 { return vec![]; }+    let (nx, ny) = ((2.0 * ux / pitch).floor() as i64 + 1, (2.0 * uy / pitch).floor() as i64 + 1);+    let (c, s) = (rot.to_radians().cos(), rot.to_radians().sin());+    let mut out = Vec::new();+    for i in 0..nx { for j in 0..ny {+        let (lx, ly) = ((i as f64 - (nx - 1) as f64 / 2.0) * pitch, (j as f64 - (ny - 1) as f64 / 2.0) * pitch);+        out.push((((x + lx * c - ly * s) * 1000.0).round() / 1000.0, ((y + lx * s + ly * c) * 1000.0).round() / 1000.0));+    } }+    out+}++/// altium_thermal_vias {filePath?, ref, pad?, pitchMm?, size?, drill?, insetMm?, dryRun?}+pub fn thermal_vias(args: &Value) -> Value {+    use crate::routing::{apply, guarded, raw, BOTTOM, TOP};+    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 = match guarded(args) { Ok(s) => s, Err(e) => return e };+    let Some(rf) = crate::support::s(args, "ref") else { return json!({"success": false, "errorCode": "bad_args", "error": "ref names the part (e.g. U3)"}) };+    let pads: Vec<Value> = st["pads"].as_array().cloned().unwrap_or_default().into_iter().filter(|p| p["ref"].as_str().map(|r| r.eq_ignore_ascii_case(&rf)).unwrap_or(false)).collect();+    if pads.is_empty() { return json!({"success": false, "errorCode": "no_such_part", "error": format!("{rf} has no pads on this board")}); }+    // the exposed pad: the one named, else the part's largest pad+    let pad = match crate::support::s(args, "pad") {+        Some(n) => pads.iter().find(|p| p["name"].as_str().map(|x| x.eq_ignore_ascii_case(&n)).unwrap_or(false)).cloned(),+        None => pads.iter().max_by(|a, b| (f(&a["sizeX"]) * f(&a["sizeY"])).partial_cmp(&(f(&b["sizeX"]) * f(&b["sizeY"]))).unwrap()).cloned(),+    };+    let Some(pad) = pad else { return json!({"success": false, "errorCode": "no_such_pad", "error": "that pad is not on the part", "pads": pads.iter().map(|p| p["name"].clone()).collect::<Vec<_>>()}) };+    let net = pad["net"].as_str().unwrap_or("").to_string();+    if net.is_empty() { return json!({"success": false, "errorCode": "pad_has_no_net", "error": format!("{rf}.{} is on no net: thermal vias would float", pad["name"].as_str().unwrap_or(""))}); }+    let rules = crate::agent::call("read_rules", &[], None, std::time::Duration::from_secs(60));+    let style = via_style(&rules.get("data").and_then(|d| d["rules"].as_array().cloned()).unwrap_or_default());+    let size = num(args, "size", style.map(|s| s.0).unwrap_or(0.6));+    let drill = num(args, "drill", style.map(|s| s.1).unwrap_or(0.3));+    let pitch = num(args, "pitchMm", (size + 0.5).max(1.0));+    let inset = num(args, "insetMm", 0.1);+    let grid = thermal_grid(f(&pad["x"]), f(&pad["y"]), f(&pad["sizeX"]), f(&pad["sizeY"]), f(&pad["rotation"]), pitch, size, inset);+    // keep clear of vias already there: the Bluetooth Sentinel's U4 pad had 8, and a grid laid over them broke Altium's+    // hole-to-hole rule 8 times (2026-10-26)+    let vias: Vec<(f64, f64, f64)> = st["vias"].as_array().cloned().unwrap_or_default().iter().map(|v| (f(&v["position"]["x"]), f(&v["position"]["y"]), f(&v["size"]))).collect();+    let inside = |x: f64, y: f64| (x - f(&pad["x"])).abs() <= f(&pad["sizeX"]).max(f(&pad["sizeY"])) / 2.0 && (y - f(&pad["y"])).abs() <= f(&pad["sizeX"]).max(f(&pad["sizeY"])) / 2.0;+    let existing = vias.iter().filter(|(x, y, _)| inside(*x, *y)).count();+    let pts: Vec<(f64, f64)> = grid.iter().cloned().filter(|(x, y)| vias.iter().all(|(vx, vy, vs)| ((x - vx).powi(2) + (y - vy).powi(2)).sqrt() >= size / 2.0 + vs / 2.0 + 0.2)).collect();+    let planned = json!({"part": rf, "pad": pad["name"], "net": net, "padMm": [pad["sizeX"], pad["sizeY"]], "vias": pts.len(), "existingVias": existing, "skippedNearExisting": grid.len() - pts.len(), "pitchMm": pitch, "via": {"sizeMm": size, "drillMm": drill},+                         "points": pts.iter().map(|(x, y)| json!([x, y])).collect::<Vec<_>>()});+    if pts.is_empty() {+        return json!({"success": existing > 0, "errorCode": if existing > 0 { "already_has_vias" } else { "pad_too_small" }, "error": if existing > 0 { "the pad's existing vias leave no room for more at this pitch" } else { "no via fits inside the pad at this size and inset" }, "planned": planned});+    }+    if args.get("dryRun").and_then(|b| b.as_bool()) == Some(true) { return json!({"success": true, "dryRun": true, "planned": planned}); }+    let ops: Vec<String> = pts.iter().map(|(x, y)| format!("V|{}|{}|{}|{}|{}|{}|{}", raw(*x), raw(*y), raw(size), raw(drill), TOP, BOTTOM, net)).collect();+    let r = apply(&ops, &st, "thermal_vias");+    json!({"success": r["success"], "applied": r["applied"], "failed": r["failed"], "planned": planned, "revision": r["revision"],+        "_hint": "Vias inside the pad carry its heat to the other layers' copper: pour the net on the far side (altium_apply_pours) so they have somewhere to go. Open vias in a pad wick solder: ask the fab to tent or plug them (JLCPCB: via covering), or use 0.3 mm or smaller drills. altium_routing_drc afterwards."})+}+ /// altium_via_fence {filePath?, nets?, edge?, viaNet, pitchMm?, freqGHz?, offsetMm?, size?, drill?, clearance?, dryRun?} pub fn via_fence(args: &Value) -> Value {     use crate::routing::{apply, guarded, raw, BOTTOM, TOP};@@ -410,4 +467,15 @@ mod tests {         let (s, d) = via_style(&mil).unwrap();         assert!((s - 0.6096).abs() < 1e-9 && (d - 0.3048).abs() < 1e-9);     }+    #[test]+    fn thermal_grid_fills_an_exposed_pad() {+        // a 3.3 mm QFN pad, 0.6 mm vias, 1.1 mm pitch: a 3 x 3 grid centred on the pad+        let g = thermal_grid(10.0, 10.0, 3.3, 3.3, 0.0, 1.1, 0.6, 0.1);+        assert_eq!(g.len(), 9);+        assert!(g.contains(&(10.0, 10.0)) && g.contains(&(8.9, 11.1)));+        assert!(thermal_grid(0.0, 0.0, 0.5, 0.5, 0.0, 1.0, 0.6, 0.1).is_empty());+        // turned 90 degrees, a long pad's grid turns with it+        let r = thermal_grid(0.0, 0.0, 4.0, 1.5, 90.0, 1.1, 0.6, 0.1);+        assert!(r.iter().all(|(x, _)| x.abs() < 0.5));+    } }
bridge-rs/src/lengthtune.rsadded+147
@@ -0,0 +1,147 @@+//! Length tuning: a serpentine in the net's longest straight track that has room beside it, its bumps sized to add+//! exactly the length a target (or another net's length) asks for, every bump clear of other copper and inside the+//! board, or a refusal that says why.+use serde_json::{json, Value};++fn f(v: &Value) -> f64 { v.as_f64().unwrap_or(0.0) }+fn r3(v: f64) -> f64 { (v * 1000.0).round() / 1000.0 }+type P = (f64, f64);++/// The serpentine's points replacing a track a->b: `n` rectangular bumps of height `amp` to the side `side` (+1 left,+/// -1 right), each `pitch` long along the track, centred on it. Pure.+pub fn meander(a: P, b: P, n: usize, amp: f64, pitch: f64, side: f64) -> Vec<P> {+    let len = ((b.0 - a.0).powi(2) + (b.1 - a.1).powi(2)).sqrt();+    let (ux, uy) = ((b.0 - a.0) / len, (b.1 - a.1) / len);+    let (nx, ny) = (-uy * side, ux * side);+    let at = |s: f64, h: f64| (a.0 + ux * s + nx * h, a.1 + uy * s + ny * h);+    let start = (len - n as f64 * pitch) / 2.0;+    let mut pts = vec![a];+    for k in 0..n {+        let s = start + k as f64 * pitch;+        pts.push(at(s, 0.0));+        pts.push(at(s, amp));+        pts.push(at(s + pitch / 2.0, amp));+        pts.push(at(s + pitch / 2.0, 0.0));+    }+    pts.push(b);+    pts.dedup_by(|p, q| (p.0 - q.0).abs() < 1e-9 && (p.1 - q.1).abs() < 1e-9);+    pts+}++fn seg_dist(p: P, a: P, b: P) -> f64 {+    let (dx, dy) = (b.0 - a.0, b.1 - a.1);+    let l2 = dx * dx + dy * dy;+    let t = if l2 > 0.0 { (((p.0 - a.0) * dx + (p.1 - a.1) * dy) / l2).clamp(0.0, 1.0) } else { 0.0 };+    ((a.0 + t * dx - p.0).powi(2) + (a.1 + t * dy - p.1).powi(2)).sqrt()+}++/// How many bumps and how tall, to add `extra` mm along a track `len` long: as few bumps as fit at `max_amp`, each+/// `pitch` long, leaving `margin` at both ends. None when it cannot fit. Pure.+pub fn sizing(extra: f64, len: f64, pitch: f64, max_amp: f64, margin: f64) -> Option<(usize, f64)> {+    if extra <= 0.0 { return None; }+    let room = ((len - 2.0 * margin) / pitch).floor() as usize;+    if room == 0 { return None; }+    let n = ((extra / (2.0 * max_amp)).ceil() as usize).max(1);+    if n > room { return None; }+    Some((n, extra / (2.0 * n as f64)))+}++/// altium_length_tune {filePath?, net, targetMm? | matchTo?, maxAmplitudeMm?, pitchMm?, clearance?, dryRun?, expectedRevision?}+pub fn length_tune(args: &Value) -> Value {+    use crate::routing::{apply, guarded, layer_id, raw};+    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 = match guarded(args) { Ok(s) => s, Err(e) => return e };+    let Some(net) = crate::support::s(args, "net") else { return json!({"success": false, "errorCode": "bad_args", "error": "net is the net to lengthen"}) };+    let lens = crate::lengths::lengths(&st);+    let len_of = |n: &str| lens.iter().find(|(k, _)| k.eq_ignore_ascii_case(n)).map(|(_, v)| f(&v["lengthMm"]));+    let Some(now) = len_of(&net) else { return json!({"success": false, "errorCode": "not_routed", "error": format!("{net} has no routed track")}) };+    let target = match (args.get("targetMm").and_then(|v| v.as_f64()), crate::support::s(args, "matchTo")) {+        (Some(t), _) => t,+        (None, Some(m)) => match len_of(&m) { Some(l) => l, None => return json!({"success": false, "errorCode": "not_routed", "error": format!("{m} has no routed track to match")}) },+        _ => return json!({"success": false, "errorCode": "bad_args", "error": "targetMm (mm) or matchTo (a net) says how long it should be"}),+    };+    let extra = target - now;+    if extra <= 0.01 { return json!({"success": true, "changed": false, "net": net, "lengthMm": r3(now), "targetMm": r3(target), "_hint": "Already at or past the target: tuning only lengthens. Shorten the other net, or route this one more directly."}); }+    let num = |k: &str, d: f64| args.get(k).and_then(|v| v.as_f64()).unwrap_or(d);+    let clearance = num("clearance", 0.2);+    // other copper on the board, per layer, as segments with half-widths (pads as their circumscribed circles)+    let mut other: Vec<(String, P, P, f64)> = Vec::new();+    for t in st["tracks"].as_array().cloned().unwrap_or_default() {+        if t["net"].as_str().map(|n| n.eq_ignore_ascii_case(&net)).unwrap_or(false) || !t["layer"].as_str().map(|l| l.ends_with(".Cu")).unwrap_or(false) { continue; }+        other.push((t["layer"].as_str().unwrap_or("").into(), (f(&t["start"]["x"]), f(&t["start"]["y"])), (f(&t["end"]["x"]), f(&t["end"]["y"])), f(&t["width"]) / 2.0));+    }+    for v in st["vias"].as_array().cloned().unwrap_or_default() {+        let p = (f(&v["position"]["x"]), f(&v["position"]["y"]));+        other.push(("*".into(), p, p, f(&v["size"]) / 2.0));+    }+    for p in st["pads"].as_array().cloned().unwrap_or_default() {+        if p["net"].as_str().map(|n| n.eq_ignore_ascii_case(&net)).unwrap_or(false) { continue; }+        let c = (f(&p["x"]), f(&p["y"]));+        other.push((p["layer"].as_str().unwrap_or("*.Cu").replace("*.Cu", "*"), c, c, (f(&p["sizeX"]).powi(2) + f(&p["sizeY"]).powi(2)).sqrt() / 2.0));+    }+    let ring = crate::coppermap::outline_ring(&st);+    let inside = |x: f64, y: f64| {+        let mut c = false;+        for k in 0..ring.len() { let (a, b) = (ring[k], ring[(k + 1) % ring.len()]); if (a.1 > y) != (b.1 > y) && x < (b.0 - a.0) * (y - a.1) / (b.1 - a.1) + a.0 { c = !c; } }+        c+    };+    // the net's tracks, longest first; for each, a side where the serpentine fits+    let mut tracks: Vec<Value> = st["tracks"].as_array().cloned().unwrap_or_default().into_iter().filter(|t| t["net"].as_str().map(|n| n.eq_ignore_ascii_case(&net)).unwrap_or(false)).collect();+    let tlen = |t: &Value| ((f(&t["end"]["x"]) - f(&t["start"]["x"])).powi(2) + (f(&t["end"]["y"]) - f(&t["start"]["y"])).powi(2)).sqrt();+    tracks.sort_by(|a, b| tlen(b).partial_cmp(&tlen(a)).unwrap());+    let mut why = Vec::new();+    for t in &tracks {+        let (a, b) = ((f(&t["start"]["x"]), f(&t["start"]["y"])), (f(&t["end"]["x"]), f(&t["end"]["y"])));+        let w = f(&t["width"]);+        let layer = t["layer"].as_str().unwrap_or("F.Cu").to_string();+        let pitch = num("pitchMm", (4.0 * w).max(4.0 * clearance + 2.0 * w));+        let max_amp = num("maxAmplitudeMm", 3.0);+        let Some((n, amp)) = sizing(extra, tlen(t), pitch, max_amp, 2.0 * w) else { why.push(json!({"track": [a, b], "why": "too short for the bumps this needs at this amplitude"})); continue };+        for side in [1.0, -1.0] {+            let pts = meander(a, b, n, amp, pitch, side);+            let clear = pts.windows(2).all(|s| other.iter().filter(|o| o.0 == layer || o.0 == "*").all(|o| {+                // segment to segment distance: endpoints against the other segment, and its endpoints against ours+                let d = seg_dist(s[0], o.1, o.2).min(seg_dist(s[1], o.1, o.2)).min(seg_dist(o.1, s[0], s[1])).min(seg_dist(o.2, s[0], s[1]));+                d >= o.3 + w / 2.0 + clearance+            })) && pts.iter().all(|p| inside(p.0, p.1));+            if !clear { continue; }+            let added: f64 = pts.windows(2).map(|s| ((s[1].0 - s[0].0).powi(2) + (s[1].1 - s[0].1).powi(2)).sqrt()).sum::<f64>() - tlen(t);+            let plan = json!({"net": net, "layer": layer, "replaces": [[r3(a.0), r3(a.1)], [r3(b.0), r3(b.1)]], "bumps": n, "amplitudeMm": r3(amp), "pitchMm": r3(pitch),+                              "side": if side > 0.0 { "left" } else { "right" }, "addsMm": r3(added), "points": pts.iter().map(|p| json!([r3(p.0), r3(p.1)])).collect::<Vec<_>>()});+            if args.get("dryRun").and_then(|b| b.as_bool()) == Some(true) {+                return json!({"success": true, "dryRun": true, "lengthMm": r3(now), "targetMm": r3(target), "plan": plan});+            }+            let lid = layer_id(&json!(layer)).unwrap_or(1);+            let mut ops = vec![format!("D|T|{}|{}|{}|{}|{lid}", raw(a.0), raw(a.1), raw(b.0), raw(b.1))];+            for s in pts.windows(2) { ops.push(format!("T|{}|{}|{}|{}|{}|{lid}|{net}", raw(s[0].0), raw(s[0].1), raw(s[1].0), raw(s[1].1), raw(w))); }+            let r = apply(&ops, &st, "length_tune");+            let after = crate::lengths::lengths(&crate::routing::routing_state(&json!({})));+            let got = after.iter().find(|(k, _)| k.eq_ignore_ascii_case(&net)).map(|(_, v)| f(&v["lengthMm"])).unwrap_or(0.0);+            return json!({"success": r["success"], "changed": true, "lengthBeforeMm": r3(now), "lengthMm": r3(got), "targetMm": r3(target), "errorMm": r3(got - target), "plan": plan, "revision": r["revision"],+                "_hint": "One serpentine, one undo step. altium_net_lengths shows the routed lengths; altium_routing_drc checks clearances (the plan kept clearance from every other net's copper)."});+        }+        why.push(json!({"track": [[r3(a.0), r3(a.1)], [r3(b.0), r3(b.1)]], "why": "no clear room on either side for the bumps"}));+    }+    json!({"success": false, "errorCode": "no_room", "error": format!("no track of {net} has room for {:.2} mm more", extra), "lengthMm": r3(now), "targetMm": r3(target), "tried": why,+           "_hint": "Lower maxAmplitudeMm for more, shorter bumps, raise it for fewer, or reroute the net with a longer straight run in open space."})+}++#[cfg(test)]+mod tests {+    use super::*;++    #[test]+    fn a_meander_adds_exactly_twice_its_height_per_bump() {+        let (n, amp) = sizing(6.0, 30.0, 1.2, 1.0, 0.4).unwrap();+        assert_eq!(n, 3);+        assert!((amp - 1.0).abs() < 1e-9);+        let pts = meander((0.0, 0.0), (30.0, 0.0), n, amp, 1.2, 1.0);+        let len: f64 = pts.windows(2).map(|s| ((s[1].0 - s[0].0).powi(2) + (s[1].1 - s[0].1).powi(2)).sqrt()).sum();+        assert!((len - 36.0).abs() < 1e-9, "{len}");+        assert!(pts.iter().all(|p| p.1 >= -1e-9 && p.1 <= 1.0 + 1e-9));+        // too much for the room: refused+        assert!(sizing(100.0, 5.0, 1.2, 1.0, 0.4).is_none());+        assert!(sizing(-1.0, 30.0, 1.2, 1.0, 0.4).is_none());+    }+}
bridge-rs/src/main.rs+7−1
@@ -5,11 +5,13 @@ mod a365; mod ab; mod agent; mod assembly;+mod autoclass; mod board; mod bodies; mod bom; mod sch; mod schdoc;+mod schreview; mod design; mod dialogs; mod health;@@ -23,7 +25,9 @@ mod current; mod impedance; mod inspect; mod lengths;+mod lengthtune; mod order;+mod pairroute; mod panel; mod instance; mod library;@@ -32,7 +36,9 @@ mod lifecycle; mod manufacturing; mod misc; mod outputs;+mod placement; mod progress;+mod report; mod review; mod route; mod routing;@@ -52,7 +58,7 @@ use tiny_http::{Header, Method, Response, Server}; /// Attached to every failed reply (see the /command handler). const REPORT_ISSUES: &str = "If this looks like an altium-bridge BUG (not a refusal you expected), report it: check for a duplicate with `adom-wiki issue list adom/altium-bridge`, then `adom-wiki issue create adom/altium-bridge --title \"<verb>: <one-line symptom>\" --category bug-report --body \"<what you ran, what you expected, what happened, the VERBATIM response JSON (and errorShot if present), bridgeVersion, the Altium version from altium_status, the OS>\"`. A relay, routing, toast or lifecycle problem belongs on adom/adom-bridge instead. Reports from real machines are how this bridge gets correct: three different Altium builds behaved three different ways in one weekend."; -pub const BRIDGE_VERSION: &str = "0.2.74";+pub const BRIDGE_VERSION: &str = "0.2.75";  fn json_response(status: u16, body: &serde_json::Value) -> Response<std::io::Cursor<Vec<u8>>> {     let data = serde_json::to_vec(body).unwrap_or_else(|_| b"{}".to_vec());
bridge-rs/src/pairroute.rsadded+218
@@ -0,0 +1,218 @@+//! A differential pair routed as a pair: one centreline from the midpoint of the source pads through waypoints to the+//! midpoint of the destination pads, each net offset half a pitch (width + gap) to its own side with mitred corners,+//! a short fan-out from each pad, and both lengths and the skew reported.+use serde_json::{json, Value};++fn r3(v: f64) -> f64 { (v * 1000.0).round() / 1000.0 }+type P = (f64, f64);++fn sub(a: P, b: P) -> P { (a.0 - b.0, a.1 - b.1) }+fn norm(a: P) -> P { let l = (a.0 * a.0 + a.1 * a.1).sqrt(); if l > 0.0 { (a.0 / l, a.1 / l) } else { (0.0, 0.0) } }+fn left(d: P) -> P { (-d.1, d.0) }++/// The polyline offset `d` to the left (negative: right), corners mitred. Pure.+pub fn offset(path: &[P], d: f64) -> Vec<P> {+    let n = path.len();+    (0..n).map(|i| {+        let din = if i > 0 { norm(sub(path[i], path[i - 1])) } else { norm(sub(path[1], path[0])) };+        let dout = if i + 1 < n { norm(sub(path[i + 1], path[i])) } else { din };+        let (n1, n2) = (left(din), left(dout));+        let m = norm((n1.0 + n2.0, n1.1 + n2.1));+        let k = (m.0 * n1.0 + m.1 * n1.1).max(0.2); // a hairpin would blow the mitre up: cap it at 5x+        (path[i].0 + m.0 * d / k, path[i].1 + m.1 * d / k)+    }).collect()+}++fn length(p: &[P]) -> f64 { p.windows(2).map(|w| ((w[1].0 - w[0].0).powi(2) + (w[1].1 - w[0].1).powi(2)).sqrt()).sum() }++/// Both nets' points from pad to pad: the centreline from the pad midpoints through `via`, each net on the side its+/// source pad is on, `fan` mm of fan-out at each end. Pure.+pub fn plan(pos: (P, P), neg: (P, P), via: &[P], width: f64, gap: f64, fan: f64) -> (Vec<P>, Vec<P>) {+    let s = ((pos.0 .0 + neg.0 .0) / 2.0, (pos.0 .1 + neg.0 .1) / 2.0);+    let e = ((pos.1 .0 + neg.1 .0) / 2.0, (pos.1 .1 + neg.1 .1) / 2.0);+    let mut centre = vec![s];+    centre.extend_from_slice(via);+    centre.push(e);+    // pull the ends in by the fan-out so each pad has room to reach its own side+    let d0 = norm(sub(centre[1], centre[0]));+    let k = centre.len();+    let d1 = norm(sub(centre[k - 1], centre[k - 2]));+    centre[0] = (s.0 + d0.0 * fan, s.1 + d0.1 * fan);+    centre[k - 1] = (e.0 - d1.0 * fan, e.1 - d1.1 * fan);+    let half = (width + gap) / 2.0;+    // the positive net goes on the side its source pad is on+    let side = { let v = sub(pos.0, s); let n = left(d0); if v.0 * n.0 + v.1 * n.1 >= 0.0 { 1.0 } else { -1.0 } };+    let mut p = vec![pos.0]; p.extend(offset(&centre, half * side)); p.push(pos.1);+    let mut n = vec![neg.0]; n.extend(offset(&centre, -half * side)); n.push(neg.1);+    (p, n)+}++fn seg_dist(p: P, a: P, b: P) -> f64 {+    let (dx, dy) = (b.0 - a.0, b.1 - a.1);+    let l2 = dx * dx + dy * dy;+    let t = if l2 > 0.0 { (((p.0 - a.0) * dx + (p.1 - a.1) * dy) / l2).clamp(0.0, 1.0) } else { 0.0 };+    ((a.0 + t * dx - p.0).powi(2) + (a.1 + t * dy - p.1).powi(2)).sqrt()+}++fn crosses(a: P, b: P, c: P, d: P) -> bool {+    let o = |p: P, q: P, r: P| (q.0 - p.0) * (r.1 - p.1) - (q.1 - p.1) * (r.0 - p.0);+    let (d1, d2, d3, d4) = (o(c, d, a), o(c, d, b), o(a, b, c), o(a, b, d));+    (d1 > 0.0) != (d2 > 0.0) && (d3 > 0.0) != (d4 > 0.0)+}++/// What is wrong with a planned pair before it touches the board: the two nets crossing each other (the pads swap+/// sides between the ends), or a segment passing over another net's pad on the layer. Pads are (ref.name, net, x, y,+/// radius). Pure.+/// A pad as a stadium: its long axis from a to b and half its short side (a round pad: a = b). Pure.+pub fn pad_shape(x: f64, y: f64, sx: f64, sy: f64, rot: f64) -> (P, P, f64) {+    let (long, short) = (sx.max(sy), sx.min(sy));+    let ang = rot.to_radians() + if sy > sx { std::f64::consts::FRAC_PI_2 } else { 0.0 };+    let h = (long - short) / 2.0;+    ((x - h * ang.cos(), y - h * ang.sin()), (x + h * ang.cos(), y + h * ang.sin()), short / 2.0)+}++fn seg_seg(a: P, b: P, c: P, d: P) -> f64 {+    if crosses(a, b, c, d) { return 0.0; }+    seg_dist(a, c, d).min(seg_dist(b, c, d)).min(seg_dist(c, a, b)).min(seg_dist(d, a, b))+}++pub fn check(p: &[P], n: &[P], pads: &[(String, String, P, P, f64)], nets: (&str, &str), width: f64, clearance: f64) -> Vec<Value> {+    let mut out = Vec::new();+    for i in 0..p.len().saturating_sub(1) {+        for j in 0..n.len().saturating_sub(1) {+            if crosses(p[i], p[i + 1], n[j], n[j + 1]) {+                out.push(json!({"problem": "pair_crosses", "at": [r3((p[i].0 + p[i + 1].0) / 2.0), r3((p[i].1 + p[i + 1].1) / 2.0)],+                                "fix": "the pads are on swapped sides at the two ends: route to a via pair and cross on another layer, or swap the pins"}));+                return out;+            }+        }+    }+    for (path, net) in [(p, nets.0), (n, nets.1)] {+        for w in path.windows(2) {+            if let Some(hit) = pads.iter().find(|(_, pn, a, b, r)| !pn.eq_ignore_ascii_case(net) && seg_seg(*a, *b, w[0], w[1]) < r + width / 2.0 + clearance - 1e-9) {+                out.push(json!({"problem": "over_a_pad", "net": net, "pad": hit.0, "padNet": hit.1, "fix": "add waypoints (via) that lead the pair out of the part before it turns"}));+                break;+            }+        }+    }+    out+}++/// altium_route_pair {pos, neg, from:{pos, neg}, to:{pos, neg}, via?, layer?, width?, gap?, diffOhms?, fanMm?}+pub fn route_pair(args: &Value) -> Value {+    if let Some(g) = crate::support::need_licensed() { return g; }+    let s = |k: &str| args.get(k).and_then(|v| v.as_str()).map(String::from);+    let (Some(pn), Some(nn)) = (s("pos"), s("neg")) else { return json!({"success": false, "errorCode": "bad_args", "error": "pos and neg are the pair's two nets"}) };+    let pad = |o: &str, k: &str| args.get(o).and_then(|v| v.get(k)).and_then(|v| v.as_str()).map(String::from);+    let (Some(pf), Some(nf), Some(pt), Some(nt)) = (pad("from", "pos"), pad("from", "neg"), pad("to", "pos"), pad("to", "neg")) else {+        return json!({"success": false, "errorCode": "bad_args", "error": "from:{pos:\"U1.3\", neg:\"U1.4\"} and to:{pos, neg} name the pads at each end"});+    };+    let st = crate::routing::routing_state(&json!({}));+    if st.get("success").and_then(|b| b.as_bool()) != Some(true) { return st; }+    let at = |key: &str| -> Option<P> {+        let (r, n) = key.split_once('.')?;+        st["pads"].as_array()?.iter().find(|p| p["ref"].as_str() == Some(r) && p["name"].as_str() == Some(n)).map(|p| (p["x"].as_f64().unwrap_or(0.0), p["y"].as_f64().unwrap_or(0.0)))+    };+    let (Some(a), Some(b), Some(c), Some(d)) = (at(&pf), at(&nf), at(&pt), at(&nt)) else {+        return json!({"success": false, "errorCode": "no_such_pad", "error": format!("one of {pf}, {nf}, {pt}, {nt} is not a pad on the board")});+    };+    let layer = args.get("layer").cloned().unwrap_or(json!("F.Cu"));+    let lname = layer.as_str().unwrap_or("F.Cu").to_string();+    // width and gap: given, or solved from the stack-up for diffOhms on this layer (gap = width)+    let mut sized = Value::Null;+    let (mut width, mut gap) = (args.get("width").and_then(|v| v.as_f64()), args.get("gap").and_then(|v| v.as_f64()));+    if let Some(z) = args.get("diffOhms").and_then(|v| v.as_f64()) {+        let stack = crate::agent::call("layer_stack", &[], None, std::time::Duration::from_secs(60));+        let geo = crate::impedance::geometry(&stack.get("data").cloned().unwrap_or(Value::Null));+        let names = crate::coppermap::stack_layers(&stack.get("data").cloned().unwrap_or(Value::Null));+        if let Some(i) = names.iter().position(|n| n.0 == lname) {+            let rows = crate::impedance::widths(&geo[i..=i], None, Some(z), gap);+            if let (Some(w), Some(g)) = (rows[0]["diffWidth"].as_f64(), rows[0]["diffGap"].as_f64()) { width = width.or(Some(w)); gap = gap.or(Some(g)); sized = rows[0].clone(); }+        }+    }+    let (Some(width), Some(gap)) = (width, gap) else { return json!({"success": false, "errorCode": "bad_args", "error": "give width and gap (mm), or diffOhms to solve them from the stack-up"}) };+    let via: Vec<P> = args.get("via").and_then(|v| v.as_array()).map(|a| a.iter().filter_map(|p| Some((p[0].as_f64()?, p[1].as_f64()?))).collect()).unwrap_or_default();+    let fan = args.get("fanMm").and_then(|v| v.as_f64()).unwrap_or(1.0);+    let (pp, np) = plan((a, c), (b, d), &via, width, gap, fan);+    // check it before anything lands: crossing nets, or a segment over another net's pad on this layer+    let on_layer = |l: &str| l == "*.Cu" || l == lname;+    let num = |q: &Value, k: &str| q[k].as_f64().unwrap_or(0.0);+    let pads: Vec<(String, String, P, P, f64)> = st["pads"].as_array().cloned().unwrap_or_default().iter()+        .filter(|q| on_layer(q["layer"].as_str().unwrap_or("")))+        .map(|q| { let (a, b, r) = pad_shape(num(q, "x"), num(q, "y"), num(q, "sizeX"), num(q, "sizeY"), num(q, "rotation"));+                   (format!("{}.{}", q["ref"].as_str().unwrap_or(""), q["name"].as_str().unwrap_or("")), q["net"].as_str().unwrap_or("").to_string(), a, b, r) }).collect();+    let clearance = args.get("clearance").and_then(|v| v.as_f64()).unwrap_or(0.15);+    let problems = check(&pp, &np, &pads, (&pn, &nn), width, clearance);+    if !problems.is_empty() && args.get("force").and_then(|b| b.as_bool()) != Some(true) {+        return json!({"success": false, "errorCode": "pair_plan_blocked", "error": "the planned pair would short", "problems": problems,+            "planned": {pn.clone(): pp.iter().map(|q| json!([r3(q.0), r3(q.1)])).collect::<Vec<_>>(), nn.clone(): np.iter().map(|q| json!([r3(q.0), r3(q.1)])).collect::<Vec<_>>()},+            "widthMm": r3(width), "gapMm": r3(gap), "_hint": "Nothing was placed. Fix the plan (waypoints that lead out of the parts, or a layer change where the pair must cross) and call again."});+    }+    let pts = |v: &[P], first: &str, last: &str| -> Value {+        let mut out = vec![json!({"pad": first})];+        for p in &v[1..v.len() - 1] { out.push(json!([r3(p.0), r3(p.1)])); }+        out.push(json!({"pad": last}));+        json!([out])+    };+    let rp = crate::routing::route_net(&json!({"net": pn, "width": width, "layer": layer, "paths": pts(&pp, &pf, &pt)}));+    if rp.get("success").and_then(|b| b.as_bool()) != Some(true) { return json!({"success": false, "errorCode": "route_failed", "error": format!("{pn} did not route"), "detail": rp}); }+    let rn = crate::routing::route_net(&json!({"net": nn, "width": width, "layer": layer, "paths": pts(&np, &nf, &nt)}));+    // the pair's own width rule (+/-10%): a board's default width rule caps tracks well under a 90 ohm pair's (the+    // test board's DRC flagged every segment of a 0.573 mm pair, 2026-10-26)+    let rule = if args.get("rule").and_then(|b| b.as_bool()) != Some(false) {+        let r = crate::routing::add_rule(&json!({"kind": "width", "name": format!("Pair {pn} {nn}"), "scope1": format!("InNet('{pn}') Or InNet('{nn}')"),+                                                 "min": r3(width * 0.9), "preferred": r3(width), "max": r3(width * 1.1)}));+        json!({"name": format!("Adom Pair {pn} {nn}"), "success": r.get("success").cloned().unwrap_or(json!(false)), "descriptor": r.get("descriptor").cloned().unwrap_or(Value::Null)})+    } else { Value::Null };+    let (lp, ln) = (length(&pp), length(&np));+    json!({"success": rn.get("success").and_then(|b| b.as_bool()) == Some(true), "widthMm": r3(width), "gapMm": r3(gap), "sizedFor": sized, "layer": lname, "widthRule": rule,+        "lengthsMm": {pn.clone(): r3(lp), nn.clone(): r3(ln)}, "skewMm": r3((lp - ln).abs()), "revision": rn["revision"], "detail": if rn.get("success").and_then(|b| b.as_bool()) == Some(true) { Value::Null } else { rn.clone() },+        "_hint": "Both nets are routed as one pair along the centreline. skewMm is the length difference from the fan-outs and corners: altium_net_lengths measures it routed, and altium_add_rule kind diffpair / matched keeps it in check. Run altium_routing_drc for clearances."})+}++#[cfg(test)]+mod tests {+    use super::*;++    #[test]+    fn offset_keeps_the_pitch_round_a_corner() {+        let path = vec![(0.0, 0.0), (10.0, 0.0), (10.0, 10.0)];+        let l = offset(&path, 0.5);+        assert!((l[0].1 - 0.5).abs() < 1e-9);+        // the inside corner of a left turn: 0.5 from both legs+        assert!((l[1].0 - 9.5).abs() < 1e-9 && (l[1].1 - 0.5).abs() < 1e-9);+        assert!((l[2].0 - 9.5).abs() < 1e-9);+    }++    #[test]+    fn plan_puts_each_net_on_its_pads_side() {+        // pads 1 mm apart across a straight 20 mm run, positive on the left (+y)+        let (p, n) = plan(((0.0, 0.5), (20.0, 0.5)), ((0.0, -0.5), (20.0, -0.5)), &[], 0.2, 0.15, 1.0);+        assert_eq!(p.first(), Some(&(0.0, 0.5)));+        assert!(p[1].1 > 0.0 && n[1].1 < 0.0);+        assert!((p[1].1 - n[1].1 - 0.35).abs() < 1e-9);+        assert!((length(&p) - length(&n)).abs() < 1e-9);+    }+    #[test]+    fn check_catches_a_crossing_and_a_pad_in_the_way() {+        // destination pads swapped: the nets cross+        let (p, n) = plan(((0.0, 0.5), (20.0, -0.5)), ((0.0, -0.5), (20.0, 0.5)), &[], 0.2, 0.15, 1.0);+        assert_eq!(check(&p, &n, &[], ("P", "N"), 0.2, 0.15)[0]["problem"], "pair_crosses");+        // a pad of another net on the straight run+        let (p, n) = plan(((0.0, 0.5), (20.0, 0.5)), ((0.0, -0.5), (20.0, -0.5)), &[], 0.2, 0.15, 1.0);+        let pads = vec![("U1.8".to_string(), "X".to_string(), (10.0, 0.175), (10.0, 0.175), 0.3)];+        assert_eq!(check(&p, &n, &pads, ("P", "N"), 0.2, 0.15)[0]["pad"], "U1.8");+        assert!(check(&p, &n, &[], ("P", "N"), 0.2, 0.15).is_empty());+    }+    #[test]+    fn a_trace_leaving_a_soic_pin_clears_the_next_pin() {+        // SOIC pins 1.5 x 0.6 at 1.27 pitch: a 0.3 mm trace leaving pin 2 straight out passes pin 1 at 0.97 - 0.3 - 0.15+        let pin1 = pad_shape(0.0, 0.0, 1.5, 0.6, 0.0);+        let pads = vec![("U1.1".to_string(), "A".to_string(), pin1.0, pin1.1, pin1.2)];+        let p = vec![(0.0, 1.27), (3.0, 1.27)];+        assert!(check(&p, &[(0.0, 5.0), (3.0, 5.0)], &pads, ("B", "C"), 0.3, 0.15).is_empty());+        // the same trace run straight across pin 1 is caught+        let q = vec![(-2.0, 0.1), (3.0, 0.1)];+        assert_eq!(check(&q, &[(0.0, 5.0), (3.0, 5.0)], &pads, ("B", "C"), 0.3, 0.15)[0]["pad"], "U1.1");+    }+}
bridge-rs/src/placement.rsadded+151
@@ -0,0 +1,151 @@+//! A placement review before routing: parts whose courtyards (pads and body, grown by a margin) overlap on the same+//! side, parts off the board or over its edge, pads too close to the edge for assembly and depanelling, and parts on a+//! mounting hole.+use serde_json::{json, Value};+use std::collections::BTreeMap;++fn f(v: &Value) -> f64 { v.as_f64().unwrap_or(0.0) }+fn r3(v: f64) -> f64 { (v * 1000.0).round() / 1000.0 }+type Rect = (f64, f64, f64, f64);++fn hit(a: Rect, b: Rect) -> bool { a.0 < b.2 && b.0 < a.2 && a.1 < b.3 && b.1 < a.3 }+fn grow(r: Rect, d: f64) -> Rect { (r.0 - d, r.1 - d, r.2 + d, r.3 + d) }++/// Each part's box (its pads, and its 3D body's box when it has one) and side. Pure.+pub fn part_boxes(st: &Value, bodies: &BTreeMap<String, Rect>) -> BTreeMap<String, (bool, Rect)> {+    let mut m: BTreeMap<String, (bool, Rect)> = BTreeMap::new();+    let side: BTreeMap<String, bool> = st["components"].as_array().cloned().unwrap_or_default().iter()+        .filter_map(|c| Some((c["ref"].as_str()?.to_string(), c["side"] == "bottom"))).collect();+    for p in st["pads"].as_array().cloned().unwrap_or_default() {+        let Some(r) = p["ref"].as_str().filter(|r| !r.is_empty()) else { continue };+        let (c, s) = (f(&p["rotation"]).to_radians().cos().abs(), f(&p["rotation"]).to_radians().sin().abs());+        let (hx, hy) = ((f(&p["sizeX"]) * c + f(&p["sizeY"]) * s) / 2.0, (f(&p["sizeX"]) * s + f(&p["sizeY"]) * c) / 2.0);+        let b = (f(&p["x"]) - hx, f(&p["y"]) - hy, f(&p["x"]) + hx, f(&p["y"]) + hy);+        let e = m.entry(r.to_string()).or_insert((side.get(r).copied().unwrap_or(false), b));+        e.1 = (e.1 .0.min(b.0), e.1 .1.min(b.1), e.1 .2.max(b.2), e.1 .3.max(b.3));+    }+    for (r, b) in bodies {+        if let Some(e) = m.get_mut(r) { e.1 = (e.1 .0.min(b.0), e.1 .1.min(b.1), e.1 .2.max(b.2), e.1 .3.max(b.3)); }+    }+    m+}++/// The review. `ring` is the outline (mm); holes are (x, y, radius) of the board's own drilled, part-less pads. Pure.+pub fn review(boxes: &BTreeMap<String, (bool, Rect)>, pads: &[Value], ring: &[(f64, f64)], holes: &[(f64, f64, f64)], margin: f64, edge: f64) -> Value {+    let (bx0, bx1) = ring.iter().fold((f64::MAX, f64::MIN), |a, p| (a.0.min(p.0), a.1.max(p.0)));+    let (by0, by1) = ring.iter().fold((f64::MAX, f64::MIN), |a, p| (a.0.min(p.1), a.1.max(p.1)));+    let inside = |x: f64, y: f64| {+        let mut c = false;+        for k in 0..ring.len() {+            let (a, b) = (ring[k], ring[(k + 1) % ring.len()]);+            if (a.1 > y) != (b.1 > y) && x < (b.0 - a.0) * (y - a.1) / (b.1 - a.1) + a.0 { c = !c; }+        }+        c+    };+    let dist = |x: f64, y: 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 (mut overlaps, mut off, mut near, mut on_holes) = (Vec::new(), Vec::new(), Vec::new(), Vec::new());+    let list: Vec<(&String, &(bool, Rect))> = boxes.iter().collect();+    for i in 0..list.len() {+        for j in i + 1..list.len() {+            let ((ra, (sa, a)), (rb, (sb, b))) = (list[i], list[j]);+            if sa == sb && hit(grow(*a, margin), grow(*b, margin)) {+                let ov = (a.2.min(b.2) - a.0.max(b.0)).min(a.3.min(b.3) - a.1.max(b.1));+                overlaps.push(json!({"parts": [ra, rb], "side": if *sa { "bottom" } else { "top" }, "overlapMm": r3(ov + 2.0 * margin)}));+            }+        }+    }+    // on or off the board by its pads' centres: a box's corners fall outside a round board's edge while the part sits+    // well inside it (the Bluetooth Sentinel's J1 read as off the board)+    let mut pad_in: BTreeMap<&str, (usize, usize)> = BTreeMap::new();+    for p in pads {+        let Some(r) = p["ref"].as_str().filter(|r| !r.is_empty()) else { continue };+        let e = pad_in.entry(r).or_insert((0, 0));+        e.0 += 1;+        if inside(f(&p["x"]), f(&p["y"])) { e.1 += 1; }+    }+    let _ = (bx0, bx1, by0, by1);+    for (r, (_, b)) in boxes {+        let (n, n_in) = pad_in.get(r.as_str()).copied().unwrap_or((0, 0));+        if n > 0 && n_in == 0 { off.push(json!({"ref": r, "where": "off the board"})); continue; }+        if n_in < n { off.push(json!({"ref": r, "where": "over the board edge"})); continue; }+        for (x, y, hr) in holes { if hit(*b, (x - hr, y - hr, x + hr, y + hr)) { on_holes.push(json!({"ref": r, "hole": [r3(*x), r3(*y)]})); } }+    }+    // pads near the edge: the closest pad of each part+    let mut closest: BTreeMap<String, f64> = BTreeMap::new();+    for p in pads {+        let Some(r) = p["ref"].as_str().filter(|r| !r.is_empty()) else { continue };+        // the pad's four corners, turned with it: inside the outline their distance counts, outside it is negative+        let (c, s) = (f(&p["rotation"]).to_radians().cos(), f(&p["rotation"]).to_radians().sin());+        let (hx, hy) = (f(&p["sizeX"]) / 2.0, f(&p["sizeY"]) / 2.0);+        let d = [(-hx, -hy), (hx, -hy), (hx, hy), (-hx, hy)].iter().map(|(u, v)| {+            let (x, y) = (f(&p["x"]) + u * c - v * s, f(&p["y"]) + u * s + v * c);+            if inside(x, y) { dist(x, y) } else { -dist(x, y) }+        }).fold(f64::MAX, f64::min);+        let e = closest.entry(r.to_string()).or_insert(f64::MAX);+        if d < *e { *e = d; }+    }+    for (r, d) in &closest {+        if *d < edge && !off.iter().any(|o| o["ref"] == json!(r)) { near.push(json!({"ref": r, "padToEdgeMm": r3(*d)})); }+    }+    let ok = overlaps.is_empty() && off.is_empty() && on_holes.is_empty();+    json!({"parts": boxes.len(), "ok": ok, "courtyardOverlaps": overlaps, "offOrOverEdge": off, "onMountingHoles": on_holes, "nearEdge": near, "marginMm": margin, "edgeMm": edge})+}++/// altium_placement_check {filePath?, marginMm?, edgeMm?}+pub fn placement_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 ring = crate::coppermap::outline_ring(&st);+    if ring.len() < 3 { return json!({"success": false, "errorCode": "no_outline", "error": "the board has no outline"}); }+    // the parts' 3D bodies (silk_state's 'body' box takes in the designator text and made every neighbour overlap)+    let rows = crate::agent::call("bodies", &[], None, std::time::Duration::from_secs(120));+    let mut bodies: BTreeMap<String, Rect> = BTreeMap::new();+    for b in crate::bodies::boxes(&rows.get("data").and_then(|d| d["bodies"].as_array().cloned()).unwrap_or_default()) {+        let e = bodies.entry(b.part.clone()).or_insert((b.x0, b.y0, b.x1, b.y1));+        *e = (e.0.min(b.x0), e.1.min(b.y0), e.2.max(b.x1), e.3.max(b.y1));+    }+    let boxes = part_boxes(&st, &bodies);+    let pads = st["pads"].as_array().cloned().unwrap_or_default();+    let holes: Vec<(f64, f64, f64)> = pads.iter().filter(|p| f(&p["drill"]) > 0.0 && p["ref"].as_str().map(|r| r.is_empty()).unwrap_or(true))+        .map(|p| (f(&p["x"]), f(&p["y"]), f(&p["sizeX"]).max(f(&p["drill"])) / 2.0)).collect();+    let num = |k: &str, d: f64| args.get(k).and_then(|v| v.as_f64()).unwrap_or(d);+    let mut out = review(&boxes, &pads, &ring, &holes, num("marginMm", 0.1), num("edgeMm", 0.5));+    out["success"] = json!(true);+    out["_hint"] = json!("courtyardOverlaps: parts closer than twice marginMm (their pads and bodies): move them apart (altium_move_parts, altium_find_space). offOrOverEdge parts must come onto the board; nearEdge pads risk the router or the V-cut (JLCPCB: 0.4 mm from a V-cut, 0.2 from a routed edge). onMountingHoles: a screw head lands on the part.");+    out+}++#[cfg(test)]+mod tests {+    use super::*;++    #[test]+    fn placement_review_finds_each_problem() {+        let ring = vec![(0.0, 0.0), (40.0, 0.0), (40.0, 20.0), (0.0, 20.0)];+        let mut boxes = BTreeMap::new();+        boxes.insert("U1".to_string(), (false, (5.0, 5.0, 10.0, 10.0)));+        boxes.insert("C1".to_string(), (false, (10.2, 5.0, 11.0, 6.0)));   // 0.2 mm from U1: inside 2 x 0.25+        boxes.insert("C2".to_string(), (true, (10.2, 5.0, 11.0, 6.0)));    // the same spot on the bottom: fine+        boxes.insert("J1".to_string(), (false, (38.0, 8.0, 42.0, 12.0)));  // over the edge+        boxes.insert("R9".to_string(), (false, (50.0, 5.0, 51.0, 6.0)));   // off the board+        boxes.insert("R2".to_string(), (false, (1.5, 15.5, 2.5, 16.5)));   // on the hole at (2, 16)+        let pad = |r: &str, x: f64, y: f64| json!({"ref": r, "x": x, "y": y, "sizeX": 0.6, "sizeY": 0.6});+        let pads = vec![pad("C1", 10.6, 5.5), pad("U1", 5.2, 0.6), pad("J1", 39.0, 10.0), pad("J1", 41.0, 10.0), pad("R9", 50.5, 5.5)];+        let r = review(&boxes, &pads, &ring, &[(2.0, 16.0, 1.6)], 0.25, 0.5);+        assert_eq!(r["courtyardOverlaps"].as_array().unwrap().len(), 1);+        assert_eq!(r["courtyardOverlaps"][0]["parts"], json!(["C1", "U1"]));+        let off: Vec<String> = r["offOrOverEdge"].as_array().unwrap().iter().map(|o| format!("{} {}", o["ref"].as_str().unwrap(), o["where"].as_str().unwrap())).collect();+        assert!(off.contains(&"J1 over the board edge".to_string()) && off.contains(&"R9 off the board".to_string()));+        assert_eq!(r["onMountingHoles"][0]["ref"], "R2");+        assert_eq!(r["nearEdge"][0]["ref"], "U1");+        assert_eq!(r["ok"], json!(false));+    }+}
bridge-rs/src/report.rsadded+173
@@ -0,0 +1,173 @@+//! One shareable page per board: every check the bridge has, run against the live board and its project, with a+//! picture of the board, written as a single self-contained HTML file beside the project.+use serde_json::{json, Value};++fn esc(s: &str) -> String { s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;") }+fn txt(v: &Value) -> String {+    match v {+        Value::String(s) => s.clone(),+        Value::Null => String::new(),+        // lists read as plain text, not JSON+        Value::Array(a) => a.iter().map(txt).filter(|s| !s.is_empty()).collect::<Vec<_>>().join(", "),+        other => other.to_string(),+    }+}++/// One section of the page: a title, a verdict (true, false, None = information) and rows of (label, value). Pure.+pub struct Section { pub title: String, pub ok: Option<bool>, pub summary: String, pub rows: Vec<(String, String)> }++/// The sections from the checks' replies (any may be an error reply: it shows as such). Pure.+pub fn sections(c: &Value) -> Vec<Section> {+    let mut out = Vec::new();+    let failed = |r: &Value| r.get("success").and_then(|b| b.as_bool()) == Some(false);+    let err = |title: &str, r: &Value| Section { title: title.into(), ok: None, summary: format!("not run: {}", txt(r.get("error").unwrap_or(&Value::Null))), rows: vec![] };+    // design rules+    let d = &c["drc"];+    out.push(if failed(d) { err("Design rules (Altium DRC)", d) } else {+        Section { title: "Design rules (Altium DRC)".into(), ok: Some(d["errors"].as_i64() == Some(0) && d["unconnected"].as_i64() == Some(0)),+            summary: format!("{} violations, {} unconnected", txt(&d["errors"]), txt(&d["unconnected"])),+            rows: d["violations"].as_array().cloned().unwrap_or_default().iter().take(30).map(|v| (txt(&v["rule"]), txt(&v["objects"]))).collect() } });+    let f = &c["fab"];+    out.push(if failed(f) { err("JLCPCB fab limits", f) } else {+        let mut rows: Vec<(String, String)> = f["outsideLimits"].as_array().cloned().unwrap_or_default().iter().map(|o| (txt(&o["limit"]), format!("board {} mm, limit {} mm", txt(&o["boardMm"]), txt(&o["limitMm"])))).collect();+        for k in ["track", "viaDrill", "padHole", "edgeClearance", "silkText", "boardSize"] { if let Some(m) = f["measured"].get(k) { rows.push((format!("measured {k}"), format!("{} mm", txt(&m["mm"])))); } }+        Section { title: "JLCPCB fab limits".into(), ok: f["fits"].as_bool(), summary: format!("{} outside JLCPCB's limits", f["outsideLimits"].as_array().map(|a| a.len()).unwrap_or(0)), rows } });+    let a = &c["assembly"];+    out.push(if failed(a) { err("JLCPCB assembly", a) } else {+        let rows = ["economic", "standard"].iter().flat_map(|t| a[*t]["rules"].as_array().cloned().unwrap_or_default().into_iter().filter(|r| r["ok"] == json!(false)).map(move |r| (format!("{t}: {}", txt(&r["rule"])), txt(&r["detail"])))).collect();+        Section { title: "JLCPCB assembly".into(), ok: Some(!a["service"].is_null()), summary: format!("tier: {}", if a["service"].is_null() { "none passes yet".to_string() } else { txt(&a["service"]) }), rows } });+    let s = &c["schematic"];+    out.push(if failed(s) { err("Schematic review", s) } else {+        let rows = s["errors"].as_array().cloned().unwrap_or_default().iter().chain(s["warnings"].as_array().cloned().unwrap_or_default().iter()).take(30)+            .map(|w| (txt(&w["check"]), [w.get("pin"), w.get("net"), w.get("ics")].iter().flatten().map(|v| txt(v)).collect::<Vec<_>>().join(" "))).collect();+        Section { title: "Schematic review".into(), ok: s["ok"].as_bool(), summary: format!("{} errors, {} warnings, {} pins on {} nets", s["errors"].as_array().map(|a| a.len()).unwrap_or(0), s["warnings"].as_array().map(|a| a.len()).unwrap_or(0), txt(&s["pins"]), txt(&s["nets"])), rows } });+    let p = &c["pinPad"];+    out.push(if failed(p) { err("Symbols against footprints", p) } else {+        Section { title: "Symbols against footprints".into(), ok: p["ok"].as_bool(), summary: format!("{} of {} parts match", txt(&p["matching"]), txt(&p["partsChecked"])),+            rows: p["mismatches"].as_array().cloned().unwrap_or_default().iter().map(|m| (txt(&m["ref"]), format!("pins without pad {} / pads without pin {}", txt(&m["pinsWithoutPad"]), txt(&m["padsWithoutPin"])))).collect() } });+    let i = &c["impedance"];+    out.push(if failed(i) { err("Controlled impedance", i) } else {+        Section { title: "Controlled impedance (50 ohm, 90 ohm pairs)".into(), ok: None, summary: "track widths from the stack-up".into(),+            rows: i["layers"].as_array().cloned().unwrap_or_default().iter().map(|l| (txt(&l["layer"]), format!("{}: 50 ohm {} mm; 90 ohm pair {} / {} mm", txt(&l["model"]), txt(&l["width"]), txt(&l["diffWidth"]), txt(&l["diffGap"])))).collect() } });+    let r = &c["returnPath"];+    out.push(if failed(r) { err("Return paths", r) } else {+        Section { title: "Return paths".into(), ok: r["ok"].as_bool(), summary: format!("{} net-layer runs over a gap in the reference copper", r["nets"].as_array().map(|a| a.len()).unwrap_or(0)),+            rows: r["nets"].as_array().cloned().unwrap_or_default().iter().take(20).map(|n| (format!("{} on {}", txt(&n["net"]), txt(&n["layer"])), format!("{} mm of {} mm ({}%)", txt(&n["unreferencedMm"]), txt(&n["lengthMm"]), txt(&n["percent"])))).collect() } });+    let b = &c["balance"];+    out.push(if failed(b) { err("Copper balance", b) } else {+        Section { title: "Copper balance".into(), ok: b["balanced"].as_bool(), summary: "copper share per layer; mirrored pairs within 20 points".into(),+            rows: b["layers"].as_array().cloned().unwrap_or_default().iter().map(|l| (txt(&l["layer"]), format!("{}% ({} mm2)", txt(&l["percent"]), txt(&l["copperMm2"])))).collect() } });+    let h = &c["heights"];+    out.push(if failed(h) { err("3D heights and clearance", h) } else {+        let mut rows: Vec<(String, String)> = h["heights"].as_array().cloned().unwrap_or_default().iter().take(8).map(|x| (txt(&x["ref"]), format!("{} mm, {}", txt(&x["heightMm"]), txt(&x["side"])))).collect();+        for col in h["collisions"].as_array().cloned().unwrap_or_default() { rows.push(("collision".into(), format!("{} by {} mm", txt(&col["parts"]), txt(&col["overlapMm"])))); }+        Section { title: "3D heights and clearance".into(), ok: Some(h["collisions"].as_array().map(|a| a.is_empty()).unwrap_or(true)), summary: format!("{} bodies; {} parts without a 3D body", txt(&h["bodies"]), h["noBody"].as_array().map(|a| a.len()).unwrap_or(0)), rows } });+    out+}++/// The page. Dark by default with a light scheme, tokens on :root. Pure.+pub fn page(board: &str, when: &str, version: &str, shot: Option<&str>, secs: &[Section]) -> String {+    let badge = |ok: Option<bool>| match ok { Some(true) => "<span class=\"b ok\">pass</span>", Some(false) => "<span class=\"b no\">needs work</span>", None => "<span class=\"b info\">info</span>" };+    let mut body = String::new();+    for s in secs {+        body.push_str(&format!("<section><h2>{} {}</h2><p class=\"sum\">{}</p>", esc(&s.title), badge(s.ok), esc(&s.summary)));+        if !s.rows.is_empty() {+            body.push_str("<table>");+            for (k, v) in &s.rows { body.push_str(&format!("<tr><th>{}</th><td>{}</td></tr>", esc(k), esc(v))); }+            body.push_str("</table>");+        }+        body.push_str("</section>");+    }+    let pass = secs.iter().filter(|s| s.ok == Some(true)).count();+    let work = secs.iter().filter(|s| s.ok == Some(false)).count();+    let img = shot.map(|b| format!("<img alt=\"the board in Altium\" src=\"data:image/png;base64,{b}\">")).unwrap_or_default();+    format!(r#"<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">+<meta name="color-scheme" content="dark"><title>Board report</title><style>+:root{{--bg:#101418;--panel:#182028;--ink:#e6edf3;--dim:#9aa7b4;--line:#2a3542;--ok:#3fb950;--no:#f0883e;--info:#58a6ff}}+body{{margin:0;background:var(--bg);color:var(--ink);font:15px/1.5 system-ui,-apple-system,Segoe UI,sans-serif}}+main{{max-width:960px;margin:0 auto;padding:24px 16px}} h1{{font-size:24px;margin:0 0 4px}} .meta{{color:var(--dim);margin:0 0 16px}}+img{{width:100%;border:1px solid var(--line);border-radius:8px;margin:8px 0 16px}}+section{{background:var(--panel);border:1px solid var(--line);border-radius:8px;padding:12px 16px;margin:12px 0}}+h2{{font-size:17px;margin:0;display:flex;gap:8px;align-items:center}} .sum{{color:var(--dim);margin:4px 0 8px}}+.b{{font-size:12px;border-radius:999px;padding:1px 8px;border:1px solid}} .ok{{color:var(--ok)}} .no{{color:var(--no)}} .info{{color:var(--info)}}+table{{width:100%;border-collapse:collapse;font-size:13px}} th,td{{text-align:left;padding:4px 6px;border-top:1px solid var(--line);vertical-align:top;overflow-wrap:anywhere}} th{{width:34%;color:var(--dim);font-weight:500}}+</style></head><body><main><h1>{}</h1><p class="meta">{} &middot; {} pass, {} need work &middot; altium-bridge {}</p>{}{}</main></body></html>"#,+        esc(board), esc(when), pass, work, esc(version), img, body)+}++/// "YYYY-MM-DD HH:MM UTC" now (civil-from-days, no date crate). Pure but for the clock.+fn utc_now() -> String {+    let secs = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0);+    let (days, rem) = (secs.div_euclid(86400), secs.rem_euclid(86400));+    let z = days + 719468;+    let era = z.div_euclid(146097);+    let doe = z - era * 146097;+    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;+    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);+    let mp = (5 * doy + 2) / 153;+    let d = doy - (153 * mp + 2) / 5 + 1;+    let m = if mp < 10 { mp + 3 } else { mp - 9 };+    let y = yoe + era * 400 + if m <= 2 { 1 } else { 0 };+    format!("{y:04}-{m:02}-{d:02} {:02}:{:02} UTC", rem / 3600, (rem % 3600) / 60)+}++/// altium_board_report {projectPath, pcbPath, out?}+pub fn board_report(args: &Value) -> Value {+    use crate::support::s;+    if let Some(g) = crate::support::need_licensed() { return g; }+    let (Some(prj), Some(pcb)) = (s(args, "projectPath"), s(args, "pcbPath")) else {+        return json!({"success": false, "errorCode": "bad_args", "error": "projectPath (.PrjPcb) and pcbPath (.PcbDoc) are required"});+    };+    let t0 = std::time::Instant::now();+    let mut c = json!({});+    c["schematic"] = crate::schreview::schematic_review(&json!({"projectPath": prj}));+    c["pinPad"] = crate::schreview::pin_pad_check(&json!({"projectPath": prj, "pcbPath": pcb}));+    c["fab"] = crate::fab::fab_check(&json!({"filePath": pcb, "fab": "jlcpcb"}));+    c["assembly"] = crate::assembly::assembly_check(&json!({"filePath": pcb, "projectPath": prj}));+    c["impedance"] = crate::impedance::impedance(&json!({"filePath": pcb, "z0": 50, "diff": 90}));+    c["returnPath"] = crate::coppermap::return_path(&json!({"filePath": pcb}));+    c["balance"] = crate::coppermap::copper_balance(&json!({"filePath": pcb}));+    c["heights"] = crate::bodies::height_check(&json!({"filePath": pcb}));+    c["drc"] = crate::routing::routing_drc(&json!({"full": true}));+    // the picture: the board framed in Altium's own window (no focus taken)+    let st = crate::routing::routing_state(&json!({}));+    let mut shot = None;+    if let Some((x0, y0, x1, y1)) = crate::fab::outline_bbox(&st) {+        let m = ((x1 - x0).max(y1 - y0)) * 0.05;+        crate::routing::zoom_to(&json!({"rect": [x0 - m, y0 - m, x1 + m, y1 + m]}));+        if let Some(h) = crate::instance::main_window().and_then(|w| w["hwnd"].as_i64()) {+            let r = crate::ab::call("desktop_screenshot_base64", json!({"hwnd": h}), &[], 20);+            shot = r.get("image").or_else(|| r.get("base64")).and_then(|i| i.as_str()).map(String::from);+        }+    }+    let secs = sections(&c);+    let name = std::path::Path::new(&pcb).file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_else(|| "board".into());+    let out = s(args, "out").unwrap_or_else(|| std::path::Path::new(&prj).parent().unwrap_or(std::path::Path::new(".")).join(format!("{name} report.html")).to_string_lossy().to_string());+    let when = utc_now();+    let html = page(&name, &when, crate::BRIDGE_VERSION, shot.as_deref(), &secs);+    if let Err(e) = std::fs::write(&out, html) { return json!({"success": false, "errorCode": "write_failed", "error": format!("{out}: {e}")}); }+    json!({"success": true, "report": out, "sections": secs.iter().map(|s| json!({"title": s.title, "ok": s.ok, "summary": s.summary})).collect::<Vec<_>>(),+        "pass": secs.iter().filter(|s| s.ok == Some(true)).count(), "needsWork": secs.iter().filter(|s| s.ok == Some(false)).count(), "picture": shot.is_some(), "elapsedSec": (t0.elapsed().as_secs_f64() * 10.0).round() / 10.0,+        "_hint": "report is a single HTML file (the board's picture embedded): open it in a browser or send it. Each section's verdict and rows come from the verb named in it: run that verb for the full reply."})+}++#[cfg(test)]+mod tests {+    use super::*;++    #[test]+    fn sections_read_every_check_and_the_page_escapes() {+        let c = json!({"drc": {"success": true, "errors": 0, "unconnected": 0, "violations": []},+                       "fab": {"success": true, "fits": false, "outsideLimits": [{"limit": "minTrack", "boardMm": 0.08, "limitMm": 0.1}], "measured": {"track": {"mm": 0.08}}},+                       "assembly": {"success": false, "error": "no project"},+                       "schematic": {"success": true, "ok": true, "errors": [], "warnings": [{"check": "single_pin_net", "net": "<X>"}], "pins": 10, "nets": 4}});+        let s = sections(&c);+        assert_eq!(s[0].ok, Some(true));+        assert_eq!(s[1].ok, Some(false));+        assert!(s[2].summary.starts_with("not run"));+        let html = page("lane", "2026-10-26", "0.2.75", None, &s);+        assert!(html.contains("&lt;X&gt;") && !html.contains("<X>"));+        assert!(html.contains("color-scheme\" content=\"dark"));+        assert_eq!(txt(&json!(["Pad U2-5", "Pad U3-4"])), "Pad U2-5, Pad U3-4");+    }+}
bridge-rs/src/routing.rs+22
@@ -957,6 +957,28 @@ pub fn set_outline(args: &Value) -> Value { /// hole:{min,max}, annularRing, holeToHole, edgeClearance} (mm). Each rule kind is written by its own agent call, /// so a property one Altium build lacks fails alone; the reply says which kinds landed. pub fn set_design_rules(args: &Value) -> Value {+    // fab:"jlcpcb" fills what the caller leaves out from JLCPCB's published limits for this board's layers and copper+    if let Some(fab) = args.get("fab").and_then(|v| v.as_str()) {+        if !fab.eq_ignore_ascii_case("jlcpcb") && !fab.eq_ignore_ascii_case("jlc") {+            return err("unknown_fab", format!("no built-in rules for {fab}: jlcpcb is built in; pass any other fab's numbers directly"), "");+        }+        let stack = agent::call("layer_stack", &[], None, Duration::from_secs(60));+        let layers = stack.get("data").and_then(|d| d["copperLayers"].as_i64()).unwrap_or(2);+        let oz = args.get("copperOz").and_then(|v| v.as_f64()).unwrap_or(stack.get("data").and_then(|d| d["layers"][0]["copperUm"].as_f64()).unwrap_or(35.0) / 35.0);+        let (l, _) = crate::fab::jlcpcb_limits(layers, oz);+        let n = |k: &str| l.get(k).and_then(|v| v.as_f64()).unwrap_or(0.0);+        // vias: a 0.3 mm drill is JLCPCB's size without the small-hole surcharge; costlier:true takes its 0.15/0.25 minimum+        let costlier = args.get("costlier").and_then(|b| b.as_bool()) == Some(true);+        let (vd, vh): (f64, f64) = if costlier { (0.25, 0.15) } else { (0.5, 0.3) };+        let mut full = json!({"clearance": n("minClearance"), "trackWidth": {"min": n("minTrack")},+            "via": {"diameter": {"min": vd, "preferred": vd.max(0.6)}, "drill": {"min": vh, "preferred": vh.max(0.3)}},+            "hole": {"min": n("minPadHole"), "max": n("maxDrill")}, "annularRing": n("minPadAnnularRing"), "holeToHole": n("minHoleToHoleVia"), "edgeClearance": n("minEdgeClearance")});+        for (k, v) in args.as_object().cloned().unwrap_or_default() { if !matches!(k.as_str(), "fab" | "costlier" | "copperOz") { full[k] = v; } }+        let mut r = set_design_rules(&full);+        r["fab"] = json!({"name": "JLCPCB", "layers": layers, "copperOz": (oz * 1000.0).round() / 1000.0, "source": "https://jlcpcb.com/capabilities/pcb-capabilities", "read": "2026-10-23",+            "written": full, "notes": ["via 0.5/0.3 mm is the bridge's choice of JLCPCB's surcharge-free via (costlier:true writes 0.25/0.15)", "hole to hole is the via value (0.2); JLCPCB wants 0.45 between pad holes", "edge clearance 0.2 suits routed edges; V-cut needs 0.4 (altium_panelize checks it)"]});+        return r;+    }     let mm_of = |v: Option<&Value>| v.and_then(|x| x.as_f64());     let g = |o: &str, k: &str| mm_of(args.get(o).and_then(|x| x.get(k)));     let mut plan: Vec<(&str, Vec<(&str, String)>)> = Vec::new();
bridge-rs/src/schreview.rsadded+214
@@ -0,0 +1,214 @@+//! A schematic review before Update PCB: every placed pin from the project's sheet files (with its electrical type)+//! against Altium's compiled netlist. Unconnected pins (power pins as errors), nets with one pin, outputs driving each+//! other, inputs nothing drives, and IC power pins with no decoupling capacitor to ground.+use serde_json::{json, Map, Value};+use std::collections::{BTreeMap, BTreeSet};++/// Altium's pin electrical types (the ELECTRICAL field).+pub fn electrical(n: i64) -> &'static str {+    match n { 0 => "input", 1 => "io", 2 => "output", 3 => "open_collector", 4 => "passive", 5 => "hiz", 6 => "open_emitter", 7 => "power", _ => "unknown" }+}++pub fn is_ground(net: &str) -> bool {+    let n = net.to_ascii_uppercase();+    n == "GND" || n == "0V" || n == "VSS" || n == "AGND" || n == "DGND" || n == "PGND" || n == "GNDA" || n == "GNDD" || n.starts_with("GND_") || n.ends_with("_GND")+}++fn prefix(des: &str) -> String { des.chars().take_while(|c| c.is_ascii_alphabetic()).collect::<String>().to_ascii_uppercase() }++/// The review, from the parts (read_sheet_file components: designator, pins with number/name/electrical) and the nets+/// ({net: ["U1.8", ...]}). Pure.+pub fn review(parts: &[Value], nets: &Map<String, Value>) -> Value {+    // pin -> net+    let mut net_of: BTreeMap<String, String> = BTreeMap::new();+    for (n, ps) in nets { for p in ps.as_array().cloned().unwrap_or_default() { if let Some(s) = p.as_str() { net_of.insert(s.to_ascii_uppercase(), n.clone()); } } }+    // every placed pin, once (a multi-part chip appears once per part on the sheets)+    let mut pins: BTreeMap<String, (String, String, String, String)> = BTreeMap::new(); // key -> (designator, number, name, type)+    for c in parts {+        let des = c["designator"].as_str().unwrap_or("").to_string();+        if des.is_empty() || des.contains('?') { continue; }+        for p in c["pins"].as_array().cloned().unwrap_or_default() {+            let num = p["number"].as_str().unwrap_or("").to_string();+            pins.entry(format!("{des}.{num}").to_ascii_uppercase()).or_insert((des.clone(), num, p["name"].as_str().unwrap_or("").to_string(), electrical(p["electrical"].as_i64().unwrap_or(-1)).to_string()));+        }+    }+    let nc = |name: &str| { let n = name.to_ascii_uppercase(); n == "NC" || n == "N/C" || n == "DNC" || n.starts_with("NC_") || n == "NO CONNECT" };+    let mut errors = Vec::new();+    let mut warnings = Vec::new();+    for (key, (des, num, name, ty)) in &pins {+        if net_of.contains_key(key) || nc(name) { continue; }+        let f = json!({"check": "unconnected_pin", "pin": format!("{des}.{num}"), "name": name, "type": ty});+        if ty == "power" { errors.push(f) } else { warnings.push(f) }+    }+    for (n, ps) in nets {+        let members = ps.as_array().map(|a| a.len()).unwrap_or(0);+        if members == 1 { warnings.push(json!({"check": "single_pin_net", "net": n, "pin": ps[0]})); }+        let kinds: Vec<&str> = ps.as_array().cloned().unwrap_or_default().iter().filter_map(|p| p.as_str()).filter_map(|p| pins.get(&p.to_ascii_uppercase())).map(|t| t.3.as_str()).collect();+        let outs = kinds.iter().filter(|k| **k == "output").count();+        if outs >= 2 { errors.push(json!({"check": "outputs_together", "net": n, "outputs": outs})); }+        let driven = kinds.iter().any(|k| matches!(*k, "output" | "io" | "power" | "passive" | "open_collector" | "open_emitter" | "hiz" | "unknown"));+        if !kinds.is_empty() && kinds.iter().all(|k| *k == "input") && !driven && members > 0 {+            warnings.push(json!({"check": "undriven_input", "net": n, "inputs": kinds.len()}));+        }+    }+    // decoupling: each IC power pin on a supply net (not ground) wants a capacitor between that net and a ground+    let caps_between: BTreeMap<String, Vec<String>> = {+        let mut m: BTreeMap<String, Vec<String>> = BTreeMap::new();+        let mut cap_nets: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();+        for (key, (des, ..)) in &pins {+            if prefix(des) == "C" { if let Some(n) = net_of.get(key) { cap_nets.entry(des.clone()).or_default().insert(n.clone()); } }+        }+        for (c, ns) in cap_nets {+            if ns.iter().any(|n| is_ground(n)) { for n in ns.iter().filter(|n| !is_ground(n)) { m.entry(n.clone()).or_default().push(c.clone()); } }+        }+        m+    };+    let mut supplies: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();+    for (key, (des, _, _, ty)) in &pins {+        if ty != "power" || !matches!(prefix(des).as_str(), "U" | "IC") { continue; }+        if let Some(n) = net_of.get(key).filter(|n| !is_ground(n)) { supplies.entry(n.clone()).or_default().insert(des.clone()); }+    }+    let mut decoupling = Vec::new();+    for (net, ics) in &supplies {+        let caps = caps_between.get(net).cloned().unwrap_or_default();+        // an inductor on a 'supply' pin's net makes it a switch node (a regulator's SW/LX pin): no capacitor belongs+        // there (the Bluetooth Sentinel's SMPS_LX read as missing decoupling)+        let switch = nets.get(net).and_then(|p| p.as_array()).map(|a| a.iter().filter_map(|p| p.as_str()).any(|p| prefix(p.split('.').next().unwrap_or("")) == "L")).unwrap_or(false);+        let row = json!({"net": net, "ics": ics, "capacitors": caps, "ok": !caps.is_empty() || switch, "switchNode": switch});+        if caps.is_empty() && !switch { warnings.push(json!({"check": "no_decoupling", "net": net, "ics": ics})); }+        decoupling.push(row);+    }+    json!({"pins": pins.len(), "nets": nets.len(), "errors": errors, "warnings": warnings, "decoupling": decoupling, "ok": errors.is_empty()})+}++/// altium_schematic_review {projectPath}+pub fn schematic_review(args: &Value) -> Value {+    if let Some(g) = crate::support::need_licensed() { return g; }+    let Some(prj) = crate::support::s(args, "projectPath") else { return json!({"success": false, "errorCode": "bad_args", "error": "projectPath (.PrjPcb) is required"}) };+    let text = std::fs::read(&prj).map(|b| String::from_utf8_lossy(&b).to_string()).unwrap_or_default();+    if text.is_empty() { return json!({"success": false, "errorCode": "project_not_found", "error": format!("{prj} could not be read")}); }+    let dir = std::path::Path::new(&prj).parent().map(|p| p.to_path_buf()).unwrap_or_default();+    let sheets: Vec<String> = crate::routing::listed_documents(&text, &dir).into_iter().map(|p| p.to_string_lossy().to_string()).filter(|p| p.to_lowercase().ends_with(".schdoc")).collect();+    let mut parts = Vec::new();+    let mut unread = Vec::new();+    for s in &sheets {+        let r = crate::schdoc::read_sheet_file(&json!({"path": s, "pins": true}));+        match r["components"].as_array() { Some(a) => parts.extend(a.iter().cloned()), None => unread.push(json!({"sheet": s, "error": r.get("error").cloned().unwrap_or(Value::Null)})) }+    }+    let n = crate::hier::netlist(&json!({"projectPath": prj}));+    if n.get("success").and_then(|b| b.as_bool()) != Some(true) { return n; }+    let nets = n["nets"].as_object().cloned().unwrap_or_default();+    let mut out = review(&parts, &nets);+    out["success"] = json!(true);+    out["sheets"] = json!(sheets);+    out["unreadSheets"] = json!(unread);+    out["compileErrors"] = n["compileErrors"].clone();+    out["_hint"] = json!("errors stop a board (a power pin on no net, two outputs on one net); warnings deserve a look (pins on no net, one-pin nets, inputs nothing drives, an IC supply with no capacitor to ground). Pin types come from the symbols: a passive pin is never 'undriven'. Fix on the sheets (altium_sch_connect, altium_sch_place_part), then altium_update_pcb.");+    out+}++/// Symbol pins against footprint pads, part by part: pins with no pad (a net that can never reach copper), pads with no+/// pin (copper no net reaches: fine for mounting and mechanical pads), and parts on only one side. Pure.+pub fn pin_pad(parts: &[Value], pads: &[Value], board_refs: &[String]) -> Value {+    let mut pins: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();+    for c in parts {+        let des = c["designator"].as_str().unwrap_or("").to_string();+        if des.is_empty() || des.contains('?') { continue; }+        let e = pins.entry(des).or_default();+        for p in c["pins"].as_array().cloned().unwrap_or_default() { if let Some(n) = p["number"].as_str() { e.insert(n.to_ascii_uppercase()); } }+    }+    let mut padset: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();+    for p in pads {+        let (Some(r), Some(n)) = (p["ref"].as_str().filter(|r| !r.is_empty()), p["name"].as_str()) else { continue };+        padset.entry(r.to_string()).or_default().insert(n.to_ascii_uppercase());+    }+    let mut mismatches = Vec::new();+    let mut ok = 0;+    for (des, ps) in &pins {+        let Some(pd) = padset.get(des) else { continue };+        let no_pad: Vec<&String> = ps.iter().filter(|n| !pd.contains(*n)).collect();+        // unnamed or '0' pads and mounting pads (MH*, EP*, SH*, MP*) carry no pin by design+        let no_pin: Vec<&String> = pd.iter().filter(|n| !ps.contains(*n) && !n.is_empty() && *n != "0" && !["MH", "MP", "SH", "EP", "PAD", "TAB"].iter().any(|m| n.starts_with(m))).collect();+        if no_pad.is_empty() && no_pin.is_empty() { ok += 1; continue; }+        mismatches.push(json!({"ref": des, "pinsWithoutPad": no_pad, "padsWithoutPin": no_pin, "pins": ps.len(), "pads": pd.len()}));+    }+    let on_board: BTreeSet<String> = board_refs.iter().cloned().collect();+    let sheet_only: Vec<&String> = pins.keys().filter(|d| !on_board.contains(*d) && !padset.contains_key(*d)).collect();+    let board_only: Vec<&String> = on_board.iter().filter(|d| !pins.contains_key(*d)).collect();+    json!({"partsChecked": ok + mismatches.len(), "matching": ok, "mismatches": mismatches, "onSheetsOnly": sheet_only, "onBoardOnly": board_only,+           "ok": mismatches.iter().all(|m| m["pinsWithoutPad"].as_array().map(|a| a.is_empty()).unwrap_or(true))})+}++/// altium_pin_pad_check {projectPath, pcbPath}+pub fn pin_pad_check(args: &Value) -> Value {+    if let Some(g) = crate::support::need_licensed() { return g; }+    let (Some(prj), Some(pcb)) = (crate::support::s(args, "projectPath"), crate::support::s(args, "pcbPath")) else {+        return json!({"success": false, "errorCode": "bad_args", "error": "projectPath (.PrjPcb) and pcbPath (.PcbDoc) are required"});+    };+    let text = std::fs::read(&prj).map(|b| String::from_utf8_lossy(&b).to_string()).unwrap_or_default();+    if text.is_empty() { return json!({"success": false, "errorCode": "project_not_found", "error": format!("{prj} could not be read")}); }+    let dir = std::path::Path::new(&prj).parent().map(|p| p.to_path_buf()).unwrap_or_default();+    let mut parts = Vec::new();+    for s in crate::routing::listed_documents(&text, &dir).into_iter().map(|p| p.to_string_lossy().to_string()).filter(|p| p.to_lowercase().ends_with(".schdoc")) {+        if let Some(a) = crate::schdoc::read_sheet_file(&json!({"path": s, "pins": true}))["components"].as_array() { parts.extend(a.iter().cloned()); }+    }+    if let Some(e) = crate::support::must_open(&pcb, 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 refs: Vec<String> = st["components"].as_array().cloned().unwrap_or_default().iter().filter_map(|c| c["ref"].as_str().map(String::from)).collect();+    let mut out = pin_pad(&parts, st["pads"].as_array().map(|a| a.as_slice()).unwrap_or(&[]), &refs);+    out["success"] = json!(true);+    out["_hint"] = json!("pinsWithoutPad is a part whose footprint cannot carry every pin's net (a wrong footprint or a pin numbering that does not match): fix the footprint or the symbol (altium_swap_footprint, altium_build_footprint) before routing. padsWithoutPin is copper no net reaches. onSheetsOnly / onBoardOnly differ until altium_update_pcb.");+    out+}++#[cfg(test)]+mod tests {+    use super::*;++    fn part(des: &str, pins: &[(&str, &str, i64)]) -> Value {+        json!({"designator": des, "pins": pins.iter().map(|(n, nm, e)| json!({"number": n, "name": nm, "electrical": e})).collect::<Vec<_>>()})+    }++    #[test]+    fn the_review_finds_each_kind_of_problem() {+        let parts = vec![+            part("U1", &[("1", "VCC", 7), ("2", "GND", 7), ("3", "OUT", 2), ("4", "NC", 0), ("5", "EN", 0)]),+            part("U2", &[("1", "VDD", 7), ("2", "GND", 7), ("3", "OUT", 2), ("4", "IN", 0)]),+            part("C1", &[("1", "", 4), ("2", "", 4)]),+            part("R1", &[("1", "", 4), ("2", "", 4)]),+            part("U3", &[("1", "SW", 7)]), part("L1", &[("1", "", 4), ("2", "", 4)]),+        ];+        let nets = json!({"3V3": ["U1.1", "C1.1"], "VDD": ["U2.1"], "LX": ["U3.1", "L1.1"], "GND": ["U1.2", "U2.2", "C1.2"], "BUS": ["U1.3", "U2.3"], "SENSE": ["U2.4"], "R": ["R1.1", "R1.2"]});+        let r = review(&parts, nets.as_object().unwrap());+        let checks = |k: &str| r[k].as_array().unwrap().iter().map(|f| f["check"].as_str().unwrap().to_string()).collect::<Vec<_>>();+        // U1.5 EN floats (input, warning); NC is skipped; two outputs share BUS (error)+        assert!(checks("errors").contains(&"outputs_together".to_string()));+        assert!(checks("warnings").contains(&"unconnected_pin".to_string()));+        assert!(!r["warnings"].as_array().unwrap().iter().any(|f| f["pin"] == "U1.4"));+        // VDD has one pin and no capacitor; SENSE is an input nothing drives+        assert!(checks("warnings").contains(&"single_pin_net".to_string()));+        assert!(checks("warnings").contains(&"no_decoupling".to_string()));+        assert!(checks("warnings").contains(&"undriven_input".to_string()));+        let dec = r["decoupling"].as_array().unwrap();+        assert!(dec.iter().any(|d| d["net"] == "3V3" && d["ok"] == json!(true)));+        assert!(dec.iter().any(|d| d["net"] == "VDD" && d["ok"] == json!(false)));+        // a regulator's switch pin on an inductor is not a missing capacitor+        assert!(dec.iter().any(|d| d["net"] == "LX" && d["switchNode"] == json!(true) && d["ok"] == json!(true)));+    }+    #[test]+    fn pin_pad_finds_footprints_that_do_not_fit_their_symbols() {+        let parts = vec![part("U1", &[("1", "A", 0), ("2", "B", 0), ("3", "C", 0)]), part("R1", &[("1", "", 4), ("2", "", 4)]), part("C9", &[("1", "", 4), ("2", "", 4)])];+        let pad = |r: &str, n: &str| json!({"ref": r, "name": n});+        let pads = vec![pad("U1", "1"), pad("U1", "2"), pad("U1", "4"), pad("U1", "EP"), pad("R1", "1"), pad("R1", "2"), pad("J9", "1")];+        let r = pin_pad(&parts, &pads, &["U1".into(), "R1".into(), "J9".into()]);+        assert_eq!(r["matching"], 1);+        let m = &r["mismatches"][0];+        assert_eq!(m["ref"], "U1");+        assert_eq!(m["pinsWithoutPad"], json!(["3"]));+        assert_eq!(m["padsWithoutPin"], json!(["4"]));+        assert_eq!(r["onSheetsOnly"], json!(["C9"]));+        assert_eq!(r["onBoardOnly"], json!(["J9"]));+        assert_eq!(r["ok"], json!(false));+    }+}
bridge-rs/src/verbs.rs+66−2
@@ -22,7 +22,7 @@ pub const KNOWN: &[&str] = &[     "list_nets", "net_connections", "layers", "copper_layers", "read_rules",     "set_layer_visibility", "footprint_primitives", "schematic_data", "layer_stack", "net_classes", "diff_pairs", "board_outline", "set_track_width", "find_space", "selection", "check_orientation", "replicate_layout", "outjob_info", "find_symbol", "part_parameters",     // the live-board lane AI Flow drives-    "routing_state", "route_net", "move_parts", "place_vias", "board_features", "sch_sheet_symbol", "netlist", "silkscreen_prep", "net_lengths", "teardrops", "component_classes", "read_sheet_file", "fab_check", "panelize", "impedance", "current_capacity", "height_check", "copper_balance", "return_path", "silk_designators", "via_fence", "assembly_check", "jlcpcb_order", "remove_items", "ripup_nets", "apply_pours", "pour_state", "remove_pours", "repour", "routing_drc", "build_board", "set_outline", "set_design_rules", "zoom_to", "add_rule", "build_schematic", "export_manufacturing", "select_net", "silk_state", "apply_silkscreen",+    "routing_state", "route_net", "move_parts", "place_vias", "board_features", "sch_sheet_symbol", "netlist", "silkscreen_prep", "net_lengths", "teardrops", "component_classes", "read_sheet_file", "fab_check", "panelize", "impedance", "current_capacity", "height_check", "copper_balance", "return_path", "silk_designators", "via_fence", "assembly_check", "jlcpcb_order", "schematic_review", "pin_pad_check", "route_pair", "thermal_vias", "board_report", "placement_check", "auto_classes", "length_tune", "remove_items", "ripup_nets", "apply_pours", "pour_state", "remove_pours", "repour", "routing_drc", "build_board", "set_outline", "set_design_rules", "zoom_to", "add_rule", "build_schematic", "export_manufacturing", "select_net", "silk_state", "apply_silkscreen",     // surfaces     "show_project", "show_schematic", "show_2d_board", "show_3d_board", "show_library",     "show_symbol", "show_footprint", "show_3d_chip", "list_library", "demo",@@ -458,7 +458,7 @@ fn describe() -> Value {             json!({"vertices": "int", "revision": "string", "outlineEdges": "[{kind: line|arc, ...}]"}), 120,             "Rounding corners: pass the same rectangle with cornerRadius (1 mm is a common default).", &["build_board", "routing_state", "repour"], &["Needs the board current."], json!({"outline": {"rect": [0, 0, 28, 20], "cornerRadius": 1}})),         verb_doc("set_design_rules", "Write a fab's design rules into the current board: clearance, track width, routing via style, hole size, annular ring, hole-to-hole and board-edge clearance (mm).",-            json!({"clearance": "mm", "trackWidth": "{min, preferred?, max?} mm", "via": "{diameter:{min, preferred?, max?}, drill:{min, preferred?, max?}} mm", "hole": "{min, max?} mm", "annularRing": "mm", "holeToHole": "mm", "edgeClearance": "mm - copper to the board edge (the rule it creates is scoped OnCopper; silkscreen keeps its own rules)", "polygonConnect": "the board's catch-all polygon connect style: direct|relief|none, or {style, reliefWidth: mm, reliefEntries: 2|4} (per-pour rules from apply_pours keep theirs)"}),+            json!({"fab": "jlcpcb - fill every value left out from JLCPCB's published limits for this board's layers and copper weight", "costlier": "with fab: allow JLCPCB's surcharged small vias (0.15/0.25 mm) instead of 0.3/0.5", "clearance": "mm", "trackWidth": "{min, preferred?, max?} mm", "via": "{diameter:{min, preferred?, max?}, drill:{min, preferred?, max?}} mm", "hole": "{min, max?} mm", "annularRing": "mm", "holeToHole": "mm", "edgeClearance": "mm - copper to the board edge (the rule it creates is scoped OnCopper; silkscreen keeps its own rules)", "polygonConnect": "the board's catch-all polygon connect style: direct|relief|none, or {style, reliefWidth: mm, reliefEntries: 2|4} (per-pour rules from apply_pours keep theirs)"}),             json!({"landed": "[{kind, rulesWritten}]", "failed": "[{kind, error}]", "rules": "the board's rules after"}), 300,             "AI Flow's `rules use` calls this with the fab pack's numbers (adom/pcb-design-rules). Each kind is written separately, so one this Altium build lacks fails alone.",             &["read_rules", "rules_by_kind", "build_board"], &["Needs the board current.", "Every existing rule of a kind gets the values; rule scopes are kept, except an Adom edge rule an earlier bridge scoped to All, which becomes OnCopper (#26)."], json!({"clearance": 0.15, "trackWidth": {"min": 0.15}, "via": {"diameter": {"min": 0.45}, "drill": {"min": 0.2}}, "hole": {"min": 0.2}, "edgeClearance": 0.3})),@@ -706,6 +706,62 @@ fn describe() -> Value {             &["workspace_search", "sch_place_part", "annotate", "sch_connect", "update_pcb"],             &["Takes 15-70 s. Uses real clicks (double-click the result, click the sheet): Altium comes to the front.", "The part lands near the view's lower-left corner first, then moves to x,y: wires do not follow, so connect it after."],             json!({"sheet": "C:/proj/Main.SchDoc", "query": "100nF 0402 50V", "x": 3000, "y": 2000})),+        verb_doc("pin_pad_check", "Do the footprints fit their symbols? Part by part, the symbol's pin numbers (from the sheet files) against the footprint's pad names (from the board): pins with no pad, pads with no pin, and parts on only the sheets or only the board.",+            json!({"projectPath": "the .PrjPcb", "pcbPath": "its .PcbDoc"}),+            json!({"ok": "bool - every pin has a pad", "matching": "int", "mismatches": "[{ref, pinsWithoutPad, padsWithoutPin, pins, pads}]", "onSheetsOnly": "[ref]", "onBoardOnly": "[ref]"}), 200,+            "A pin with no pad is a net that can never reach copper: change the footprint (altium_swap_footprint) or renumber the symbol's pins before routing.",+            &["schematic_review", "update_pcb", "swap_footprint", "component_pins"],+            &["Mounting and thermal pads (MH*, MP*, SH*, EP*, PAD*, TAB*, unnamed or 0) are expected to have no pin."],+            json!({"projectPath": "C:/proj/Board.PrjPcb", "pcbPath": "C:/proj/Board.PcbDoc"})),+        verb_doc("length_tune", "Lengthen a routed net to a target length, or to match another net (a pair's skew, a DDR byte lane): a serpentine in its longest straight track that has room beside it, the bumps sized to add exactly the length missing, every bump clear of other copper and inside the board.",+            json!({"filePath": "the .PcbDoc (opened first; else the current board)", "net": "the net to lengthen", "targetMm": "the length it should have", "matchTo": "or: a net whose length to match", "maxAmplitudeMm": "bump height limit, default 3", "pitchMm": "one bump's length along the track (default 4 x width, at least 4 x clearance + 2 x width)", "clearance": "to other copper, default 0.2", "dryRun": "bool - plan only", "expectedRevision": "optional"}),+            json!({"changed": "bool", "lengthBeforeMm": "number", "lengthMm": "number", "targetMm": "number", "errorMm": "number", "plan": "{layer, replaces, bumps, amplitudeMm, pitchMm, side, addsMm, points}"}), 120,+            "Then altium_net_lengths (the pair or group), altium_routing_drc. For a matched group, tune each short net to the longest (matchTo).",+            &["net_lengths", "route_pair", "add_rule", "routing_drc"],+            &["Only lengthens: a net already longer than its target is left alone.", "One serpentine per call, in one track; call again to add more elsewhere."],+            json!({"net": "DN", "matchTo": "DP"})),+        verb_doc("auto_classes", "Net classes from the nets' own names: GND, Power (VCC, VDD, 3V3, VBAT...), Clock, HighSpeed (USB, Ethernet, HDMI, PCIe, DDR, MIPI, LVDS, SATA...) and the differential pairs their _P/_N, +/-, DP/DN names spell; a proposal first, written as Altium net classes (Power with a width rule) and pairs with apply.",+            json!({"filePath": "the .PcbDoc (opened first; else the current board)", "apply": "bool - write the classes and pairs (default: propose only)", "powerWidthMm": "the Power class's width rule, default 0.5"}),+            json!({"proposal": "{classes:{GND, Power, Clock, HighSpeed}, pairs:[{name, pos, neg}], unclassified}", "applied": "bool", "written": "[{class|pair, success}]"}), 180,+            "Then scope rules to them (InNetClass('Power')), size the pairs with altium_impedance {apply}, and check power with altium_current_capacity.",+            &["net_classes", "diff_pairs", "impedance", "add_rule", "current_capacity"],+            &["Names only: a net called N1 stays unclassified. Read the proposal before apply."],+            json!({"apply": true, "powerWidthMm": 0.6})),+        verb_doc("placement_check", "Review the placement before routing: parts whose courtyards (pads and body, grown by a margin) overlap on the same side, parts off the board or over its edge, pads too close to the edge for assembly and depanelling, and parts on a mounting hole.",+            json!({"filePath": "the .PcbDoc (opened first; else the current board)", "marginMm": "courtyard margin round each part, default 0.1 (parts closer than 0.2 mm are flagged)", "edgeMm": "pad to board edge, default 0.5"}),+            json!({"ok": "bool", "courtyardOverlaps": "[{parts, side, overlapMm}]", "offOrOverEdge": "[{ref, where}]", "onMountingHoles": "[{ref, hole}]", "nearEdge": "[{ref, padToEdgeMm}]", "parts": "int"}), 180,+            "Move what it names (altium_move_parts, altium_find_space for a clear spot), then route.",+            &["move_parts", "find_space", "height_check", "board_features"],+            &["A part's box is its pads and its 3D body, so an L-shaped part reads as its bounding box; on or off the board is judged by its pads."],+            json!({"marginMm": 0.25})),+        verb_doc("board_report", "One shareable page per board: every check run against the live board and its project (Altium's DRC, JLCPCB fab limits and assembly tiers, the schematic review, symbols against footprints, impedance widths, return paths, copper balance, 3D heights) with a picture of the board, written as a single HTML file.",+            json!({"projectPath": "the .PrjPcb", "pcbPath": "its .PcbDoc", "out": "the .html to write (default '<board> report.html' beside the project)"}),+            json!({"report": "path", "sections": "[{title, ok (true|false|null = info), summary}]", "pass": "int", "needsWork": "int", "picture": "bool", "elapsedSec": "number"}), 900,+            "Open the file in a browser or send it; each section names the verb to run for its full detail.",+            &["fab_check", "assembly_check", "schematic_review", "pin_pad_check", "return_path", "copper_balance", "height_check", "routing_drc"],+            &["Runs Altium's full batch DRC and frames the board in Altium's window for the picture (no focus taken).", "Takes about a minute on a small board."],+            json!({"projectPath": "C:/proj/Board.PrjPcb", "pcbPath": "C:/proj/Board.PcbDoc"})),+        verb_doc("thermal_vias", "A thermal via grid in a part's exposed pad (the ground or thermal pad under a QFN, DFN, PowerPAD or regulator): centred, inset from the pad's edge, sized by the board's Routing Via rule, on the pad's net.",+            json!({"filePath": "the .PcbDoc (opened first; else the current board)", "ref": "the part (e.g. U3)", "pad": "the pad's name (default the part's largest pad)", "pitchMm": "default via size + 0.5, at least 1.0", "size": "via diameter mm (default the board's via rule)", "drill": "mm (default the board's via rule)", "insetMm": "from the pad's edge, default 0.1", "dryRun": "bool - plan only", "expectedRevision": "optional"}),+            json!({"planned": "{part, pad, net, padMm, vias, pitchMm, via, points}", "applied": "int", "failed": "int"}), 120,+            "Pour the pad's net on the far side (altium_apply_pours) so the heat has somewhere to go, ask the fab to tent or plug vias in pads, then altium_routing_drc. adom-fields solves the heat itself.",+            &["apply_pours", "board_features", "routing_drc", "current_capacity"],+            &["Open vias in a pad wick solder away from it during reflow: tent or plug them, or keep drills at 0.3 mm or smaller."],+            json!({"ref": "U3", "pitchMm": 1.1})),+        verb_doc("route_pair", "Route a differential pair as a pair: one centreline from the source pads' midpoint through waypoints to the destination pads' midpoint, each net offset to its own side at width + gap with mitred corners and a short fan-out from each pad; width and gap given or solved from the stack-up for a target impedance; both lengths and the skew answered.",+            json!({"pos": "the positive net", "neg": "the negative net", "from": "{pos: \"U1.3\", neg: \"U1.4\"} the source pads", "to": "{pos, neg} the destination pads", "via": "[[x,y]...] centreline waypoints mm (optional)", "layer": "F.Cu (default) | B.Cu | In<n>.Cu", "width": "mm", "gap": "mm", "diffOhms": "solve width (and gap = width unless given) for this differential impedance on the layer", "fanMm": "fan-out length at each end, default 1", "clearance": "to other nets' pads when checking the plan, default 0.15", "force": "bool - route even when the plan check finds problems", "rule": "bool, default true - add a width rule for the two nets (+/-10%) so the board's own width rule does not flag the pair"}),+            json!({"widthMm": "number", "gapMm": "number", "sizedFor": "the impedance row used | null", "lengthsMm": "{pos, neg}", "skewMm": "number", "revision": "string"}), 120,+            "Then altium_net_lengths for the routed skew, altium_add_rule {kind:\"diffpair\"} to hold width and gap, and altium_routing_drc.",+            &["route_net", "impedance", "diff_pairs", "net_lengths", "add_rule"],+            &["One layer per call; split a pair that changes layer into two calls at the via pair.", "The waypoints are the pair's centreline, so keep them clear of other copper by half the pair's width."],+            json!({"pos": "USB_DP", "neg": "USB_DN", "from": {"pos": "U1.14", "neg": "U1.15"}, "to": {"pos": "J1.3", "neg": "J1.2"}, "via": [[20, 10], [30, 10]], "diffOhms": 90})),+        verb_doc("schematic_review", "Review the schematic before Update PCB: every placed pin (read from the sheet files, with its electrical type) against Altium's compiled netlist. Errors: power pins on no net, outputs driving each other. Warnings: pins on no net, one-pin nets, inputs nothing drives, IC supplies with no decoupling capacitor to ground.",+            json!({"projectPath": "the .PrjPcb (its sheets are read from file; the netlist is Altium's compile)"}),+            json!({"ok": "bool - no errors", "errors": "[{check, pin|net, ...}]", "warnings": "[{check, ...}]", "decoupling": "[{net, ics, capacitors, ok}]", "pins": "int", "nets": "int", "sheets": "[path]"}), 300,+            "Fix on the sheets (altium_sch_connect, altium_sch_place_part for a missing capacitor), then altium_update_pcb. altium_run_erc is Altium's own ERC with its rules.",+            &["netlist", "read_sheet_file", "run_erc", "sch_connect", "update_pcb"],+            &["Pins named NC, N/C or DNC are expected to float.", "Ground nets are recognised by name (GND, AGND, DGND, PGND, VSS, 0V, *_GND)."],+            json!({"projectPath": "C:/proj/Board.PrjPcb"})),         verb_doc("jlcpcb_order", "A JLCPCB order in one call: the board checked against JLCPCB's fab limits, the Gerbers and drill zipped the way JLCPCB's order page takes them, the JLCPCB BOM and pick-and-place (CPL), the assembly-tier check, and the order-form values, in one folder with every issue in one list.",             json!({"projectPath": "the .PrjPcb", "pcbPath": "its .PcbDoc", "outputDir": "the order folder (default 'JLCPCB order <board>' beside the project; emptied first)", "variant": "an assembly variant for the BOM (optional)"}),             json!({"ready": "bool - fab fits, an assembly tier passes, no issues", "folder": "path", "gerberZip": "{path, files}", "bomFiles": "[..] incl. bom-jlcpcb.csv, cpl-jlcpcb.csv", "orderForm": "{layers, dimensionsMm, outerCopperOz, minTrackSpaceMm, minHoleMm}", "assemblyService": "economic | standard | null", "issues": "[{from, what, at?}]"}), 900,@@ -1771,6 +1827,14 @@ pub fn dispatch(command: &str, args: &Value, _forwarded: &[(String, String)]) ->         "via_fence" => crate::features::via_fence(args),         "assembly_check" => crate::assembly::assembly_check(args),         "jlcpcb_order" => crate::order::jlcpcb_order(args),+        "schematic_review" => crate::schreview::schematic_review(args),+        "pin_pad_check" => crate::schreview::pin_pad_check(args),+        "route_pair" => crate::pairroute::route_pair(args),+        "thermal_vias" => crate::features::thermal_vias(args),+        "board_report" => crate::report::board_report(args),+        "placement_check" => crate::placement::placement_check(args),+        "auto_classes" => crate::autoclass::auto_classes(args),+        "length_tune" => crate::lengthtune::length_tune(args),         "footprint_from_land_pattern" => crate::footprint::from_land_pattern(args),         "find_symbol" => crate::inspect::find_symbol(args),         "part_parameters" => crate::inspect::part_parameters(args),
dev-skills/altium-bridge-test/run_verb_tests.py+11
@@ -346,6 +346,17 @@ def matrix(w):     M["jlcpcb_order"] = dict(phase=3.5, timeout=950, **ok(projectPath=LP, pcbPath=LB),                              check=lambda d: ((d.get("gerberZip") or {}).get("files") or 0) >= 8 and any("cpl-jlcpcb" in str(f) for f in d.get("bomFiles") or [])                                              and isinstance(d.get("issues"), list) and (d.get("orderForm") or {}).get("layers") == 2)+    # 0.2.75: reviews, pair routing, thermal vias, the board report, placement, classes and length tuning on the lane+    M["schematic_review"] = dict(phase=3.5, timeout=340, **ok(projectPath=LP),+                                 check=lambda d: (d.get("pins") or 0) > 0 and isinstance(d.get("warnings"), list) and isinstance(d.get("decoupling"), list))+    M["pin_pad_check"] = dict(phase=3.5, timeout=220, **ok(projectPath=LP, pcbPath=LB), check=lambda d: (d.get("partsChecked") or 0) >= 1)+    M["placement_check"] = dict(phase=3.5, timeout=200, **ok(filePath=LB), check=lambda d: (d.get("parts") or 0) >= 1 and isinstance(d.get("offOrOverEdge"), list))+    M["auto_classes"] = dict(phase=3.5, timeout=200, **ok(filePath=LB), check=lambda d: d.get("applied") is False and "GND" in ((d.get("proposal") or {}).get("classes") or {}))+    M["length_tune"] = dict(phase=3.5, timeout=150, **anyo("N1 planned 2 mm longer, or no room named", filePath=LB, net="N1", targetMm=40, dryRun=True))+    M["thermal_vias"] = dict(phase=3.5, timeout=150, **anyo("U1 (SOIC) has no exposed pad: a plan or pad_too_small", filePath=LB, ref="U1", dryRun=True))+    M["route_pair"] = dict(phase=3.5, timeout=150, **anyo("no such pads on the lane: refused by name", pos="N1", neg="GND", **{"from": {"pos": "U9.1", "neg": "U9.2"}}, to={"pos": "U9.3", "neg": "U9.4"}, width=0.2, gap=0.2))+    M["board_report"] = dict(phase=3.5, timeout=950, **ok(projectPath=LP, pcbPath=LB),+                             check=lambda d: str(d.get("report", "")).endswith(".html") and len(d.get("sections") or []) >= 8)     # 0.2.60: a variant written into the project file and read back from Altium     M["variants"] = dict(phase=3.5, timeout=400, **ok(projectPath=LP, name="BatteryLite", notFitted=["U2"], timeout=380),                          check=lambda d: any(v.get("name") == "BatteryLite" for v in (d.get("altium") or {}).get("variants") or []))
package.json+13−2
@@ -1,6 +1,6 @@ {   "slug": "altium-bridge",-  "version": "0.2.74",+  "version": "0.2.75",   "type": "app",   "description": "Let an AI (Claude, ChatGPT, Codex or any agent) run Altium Designer for you: create symbols and footprints, place parts (also from Altium 365), wire and annotate schematics, Update PCB, set the stack-up and rules, route, pour copper, add mounting holes and stitching vias, run ERC and DRC, and make Gerbers, BOMs and STEP. Free in Hydrogen; bring your own AI and Altium licence.",   "tags": [@@ -193,7 +193,18 @@     "altium jlcpcb order files",     "export altium board for jlcpcb order",     "altium gerber zip for jlcpcb",-    "fix return path gap altium"+    "fix return path gap altium",+    "altium schematic review",+    "check altium schematic before update pcb",+    "altium footprint pin mismatch",+    "altium differential pair routing",+    "route usb pair in altium",+    "altium length matching serpentine",+    "altium thermal vias exposed pad",+    "altium placement check",+    "altium board report pdf",+    "altium net classes automatically",+    "altium jlcpcb design rules"   ],   "discovery_pitch": "An AI that runs Altium Designer in the user's own session: libraries, schematics, Update PCB, stack-up, routing, DRC, Gerbers and BOMs.",   "sample_prompts": [
page.json+13−2
@@ -4,7 +4,7 @@   "type": "app",   "title": "Altium Bridge: AI for Altium Designer",   "brief": "Let an AI (Claude, ChatGPT, Codex or any agent) run Altium Designer for you: create symbols and footprints, place parts (also from Altium 365), wire and annotate schematics, Update PCB, set the stack-up and rules, route, pour copper, add mounting holes and stitching vias, run ERC and DRC, and make Gerbers, BOMs and STEP. Free in Hydrogen; bring your own AI and Altium licence.",-  "version": "0.2.74",+  "version": "0.2.75",   "hero": {     "type": "image",     "path": "screenshots/hero.png"@@ -185,7 +185,18 @@     "altium jlcpcb order files",     "export altium board for jlcpcb order",     "altium gerber zip for jlcpcb",-    "fix return path gap altium"+    "fix return path gap altium",+    "altium schematic review",+    "check altium schematic before update pcb",+    "altium footprint pin mismatch",+    "altium differential pair routing",+    "route usb pair in altium",+    "altium length matching serpentine",+    "altium thermal vias exposed pad",+    "altium placement check",+    "altium board report pdf",+    "altium net classes automatically",+    "altium jlcpcb design rules"   ],   "discovery_pitch": "An AI that runs Altium Designer in the user's own session: libraries, schematics, Update PCB, stack-up, routing, DRC, Gerbers and BOMs.",   "metadata": {},
skills/altium-boards/SKILL.md+31−1
@@ -6,7 +6,7 @@ description: >-   readback, 3D heights and clearance, impedance, current capacity, copper balance, return paths, fab limits, panels   with V-score or mouse bites. Use when asked for an altium stack-up, net class, mounting holes, a 50 or 90 ohm trace   width, will a trace carry 3 A, does it fit the enclosure, copper balance, return path, place the designators, a-  via fence, or panelize a board.+  via fence, route a differential pair, tune a length, thermal vias, check the placement, or panelize a board. ---  Parent skill: **altium-bridge**@@ -370,6 +370,36 @@ altium_via_fence '{"nets":["ANT_RF"],"edge":true,"viaNet":"GND","freqGHz":2.4}'   reports them by their bounding box, so every verb that keeps clear of pads sees them (the Sentinel's coin cell   contacts read 0 x 0 mm before, and a via landed on one). +## Pairs, length tuning, thermal vias, placement and classes (0.2.75)++```bash+altium_route_pair '{"pos":"USB_DP","neg":"USB_DN","from":{"pos":"U1.14","neg":"U1.15"},"to":{"pos":"J1.3","neg":"J1.2"},"via":[[20,10]],"diffOhms":90}'+altium_length_tune '{"net":"DN","matchTo":"DP"}'                 # a serpentine sized to the exact length missing+altium_thermal_vias '{"ref":"U3"}'                              # a via grid in the exposed pad+altium_placement_check '{}'                                     # overlaps, off the board, near the edge, on holes+altium_auto_classes '{"apply":true}'                            # GND / Power / Clock / HighSpeed classes and pairs by name+```++- `route_pair` routes both nets of a pair along one centreline (from the source pads' midpoint through `via` waypoints to+  the destination pads'), each offset half of width + gap to its own side with mitred corners and a 1 mm fan-out at each+  pad. Width and gap are given or solved from the stack-up for `diffOhms` on the layer. Before anything lands the plan is+  checked: the nets crossing (the pads swap sides between the ends: needs a layer change) or a segment over another+  net's pad (pads as stadiums, so a trace leaving an SOIC pin clears its neighbour) refuses with `pair_plan_blocked` and+  the planned points. It adds a width rule for the two nets (+/-10%) so the board's default width rule does not flag a+  wide pair. Measured: a 90 ohm pair (0.573 / 0.573 mm) between two SOICs, skew 0.042 mm, full DRC clean.+- `length_tune` lengthens a net to `targetMm` or to `matchTo`'s length: rectangular bumps in its longest straight track+  with room beside it (either side), as few as fit at `maxAmplitudeMm` (3), sized to add exactly the missing length, each+  kept `clearance` from other copper and inside the board; `dryRun` plans. Measured: DP 23.231 to 30.000 mm with 2 bumps on+  the side away from DN, DRC clean.+- `thermal_vias` fills a part's exposed pad (the named pad, else its largest) with a via grid on the pad's net, sized by+  the board's Routing Via rule, inset from the edge, clear of vias already there. Measured on the Bluetooth Sentinel's U4:+  8 vias added round the 8 it had, full DRC 0 (laying the grid over them first broke hole-to-hole 8 times).+- `placement_check`: parts closer than 2 x `marginMm` (0.1) on the same side (pads and 3D body), parts off the board or over+  its edge (by their pads, so round boards read right), pads within `edgeMm` (0.5) of the edge (each pad's corners), parts+  on a mounting hole.+- `auto_classes` proposes classes from net names (GND; Power: VCC, VDD, VBAT, VBUS, 3V3...; Clock; HighSpeed: USB, ETH,+  HDMI, PCIe, DDR, MIPI, LVDS, SATA...) and pairs from _P/_N, +/-, DP/DN; `apply` writes them, Power with a width rule.+ ## Lengths, length rules, rooms and teardrops (0.2.68)  ```bash
skills/altium-outputs/SKILL.md+15
@@ -68,6 +68,21 @@ Altium need not be running. Run one container with `altium_run_outjob {outjobPat - OutJob→PDF was blocked in the predecessor bridge; on this one run it through   `altium_run_outjob` and verify the files[] like any medium. +## One page per board, and JLCPCB's rules in the board (0.2.75)++```bash+altium_board_report '{"projectPath":"C:\\work\\Board.PrjPcb","pcbPath":"C:\\work\\Board.PcbDoc"}'+altium_set_design_rules '{"fab":"jlcpcb"}'+```++- `board_report` runs Altium's full DRC, the JLCPCB fab and assembly checks, the schematic review, symbols against+  footprints, impedance widths, return paths, copper balance and 3D heights, frames the board in Altium for a picture, and+  writes one self-contained dark HTML page ('<board> report.html' beside the project) with a verdict per section. Measured+  on the lane project: 12 s, 9 sections.+- `set_design_rules {fab:"jlcpcb"}` writes JLCPCB's published limits for the board's layers and copper weight as its rules+  (clearance, track width, hole, annular ring, hole to hole, board edge), and vias at 0.5 / 0.3 mm, JLCPCB's size without+  the small-hole surcharge (`costlier:true` writes 0.25 / 0.15). Values passed with it win.+ ## A JLCPCB order in one call (0.2.74)  ```bash
skills/altium-schematic-edit/SKILL.md+15
@@ -102,6 +102,21 @@ Every sheet-editing verb (`sch_edit`, `sch_connect`, `sch_place_part`, `sch_swap carries `uniqueIdsReissued: [{sheet, lost, new}]` and a `uniqueIdWarning`. Then, before Update PCB, re-link the parts in Altium (Project > Component Links), or take the duplicate sheet out of the project and restore the copy. +## Review before Update PCB (0.2.75)++```bash+altium_schematic_review '{"projectPath":"C:\\work\\Board.PrjPcb"}'+altium_pin_pad_check '{"projectPath":"C:\\work\\Board.PrjPcb","pcbPath":"C:\\work\\Board.PcbDoc"}'+```++- `schematic_review` reads every placed pin from the sheet files (with its electrical type) and checks it against Altium's+  compiled netlist. Errors: a power pin on no net, two outputs on one net. Warnings: a pin on no net (NC, N/C, DNC+  expected), a one-pin net, an input nothing drives, an IC supply with no capacitor to a ground (a net with an inductor is+  taken as a switch node and skipped). Measured on the Bluetooth Sentinel project: 15 sheets, 194 pins, 65 nets in 8 s.+- `pin_pad_check`: per part, symbol pin numbers against footprint pad names (pins with no pad are nets that can never+  reach copper), and parts on only the sheets or only the board. Mounting and thermal pads (MH, MP, SH, EP, PAD, TAB, 0)+  are expected to have no pin.+ ## Read a sheet without Altium (0.2.71)  ```bash
src/BRIDGE_VERSION+1−1
@@ -1 +1 @@-0.2.74+0.2.75
src/bridge.json+17−1
@@ -2,7 +2,7 @@   "manifest_version": 1,   "name": "altium",   "displayName": "Altium Designer",-  "version": "0.2.74",+  "version": "0.2.75",   "description": "Drive Altium Designer from Adom: a resident DelphiScript agent (eval + the 1,100-command process launcher), the X2 -R command line, UIA over the VCL shell, dialogs by PID, screenshots of every Altium window, and Altium 365.",   "homepage": "https://wiki.adom.inc/adom/altium-bridge",   "docs": "https://wiki.adom.inc/adom/altium-bridge",@@ -106,6 +106,14 @@     "altium_via_fence",     "altium_assembly_check",     "altium_jlcpcb_order",+    "altium_schematic_review",+    "altium_pin_pad_check",+    "altium_route_pair",+    "altium_thermal_vias",+    "altium_board_report",+    "altium_placement_check",+    "altium_auto_classes",+    "altium_length_tune",     "altium_find_space",     "altium_find_symbol",     "altium_footprint_primitives",@@ -233,6 +241,14 @@       "via_fence": 240,       "assembly_check": 400,       "jlcpcb_order": 900,+      "schematic_review": 320,+      "pin_pad_check": 200,+      "route_pair": 120,+      "thermal_vias": 120,+      "board_report": 900,+      "placement_check": 180,+      "auto_classes": 180,+      "length_tune": 120,       "agent_start": 120,       "run_outjob": 600,       "silk_state": 180,