← Commit history

0.2.73 source (not yet released, needs signing): fab_check JLCPCB preset, assembly_check, silk_designators, via_fence; custom-shape pads by bounding box; unreadable startup Confirm answered No; close_document by file name; project check by folder; 192 verbs; batteries 191/0 on AD 26.11.1 and Altium Designer Develop

Colby Knox ·4bafcdb1d0 · ·parent c334de6
20 files changed +862−52
CHANGELOG.md+14
@@ -1,5 +1,19 @@ # Changelog +## 0.2.73 (2026-10-26)+**Ready for JLCPCB: its limits built in, assembly tiers, designators and via fences.**+- `altium_fab_check {fab:"jlcpcb"}`: JLCPCB's published standard capabilities for the board's layer count and copper weight (source page and date in the reply), with new measurements: copper to the real outline, hole to hole (via and pad), largest drill, silkscreen line width and text height, minimum board size. `costlierOrBelowRecommended` names what passes only on a costlier option. On the Bluetooth Sentinel example: 0.7 mm designators, 0.127 mm silk lines, a pour 0.148 mm from the edge.+- New verb `altium_assembly_check`: the board against JLCPCB's Economic and Standard PCBA tiers (size, thickness, layers, sides, smallest package, finest pitch, fiducials, LCSC numbers) and the cheapest tier that passes.+- New verb `altium_silk_designators`: every designator upright at one size beside its part, clear of pads, other bodies and other labels, checked afterwards with Altium's own text boxes. Sentinel: 41 of 60 moved, none left on a pad or another label (7 were on pads before).+- New verb `altium_via_fence`: ground vias along RF or fast nets and round the board edge at lambda/20, sized by the board's Routing Via rule, each clear of other copper; Altium's full DRC stayed at 0 on the Sentinel after 26 vias.+- Custom-shape pads (copper drawn as regions, no size in Altium's API) are reported by their bounding box: every verb that keeps clear of pads now sees them (the Sentinel's 5 mm coin cell contacts read 0 x 0 before).+- Stitching and fences no longer treat lines on mechanical layers or a hatched pour's net-less tracks as copper to avoid; outline arcs are sampled every 2 degrees (16 points per arc put copper outside a curved edge).+- AD 26's startup prompt "There are new versions of extensions available. Would like to review and install them?" stopped `agent_start` dead (its text is painted, so it read as an unknown Confirm). A Yes/No "Confirm" whose question UIA cannot read is now answered No by the standing reaper, photographed first: it declines whatever it offers, and installing updates stays the user's call. No verb presses Yes on a dialog.+- `altium_close_document` finds a document Altium made in memory and saved under a name afterwards (it was "not open" by path on Develop); `altium_panelize` closes its saved panel when it does not join a project, so later project edits no longer refuse an unlisted document.+- The project check before a sheet is added (`project_has_unlisted_documents`) counts only documents in the project's own folder: Altium names a document's project by file name, so a second `lane.PrjPcb` open from another folder lent its sheet to this one and a clean project was refused.+- `altium_silk_designators` reports parts that sit off the board as such, and answers its after-checks even when nothing could move.+- Verb battery: `fab_check` with the JLCPCB preset, `silk_designators`, `via_fence`, `assembly_check`.+ ## 0.2.72 (2026-10-23) **Panels the way JLCPCB reads them, 3D fit, copper balance and return paths.** - `altium_panelize {separation}`: `vscore` puts the boards edge to edge with a V-CUT line across the whole panel on Mechanical 1 (the outline layer the Gerbers carry) and "V-CUT" written at both ends, as JLCPCB asks, and checks JLCPCB's published V-cut rules (panel 70 to 475 mm, board 0.6 mm or thicker, copper 0.4 mm from a cut, at most 25 cuts, rail widths, no arcs on a cut). `tabs` draws mouse bites per JLCPCB's guide (five 0.6 mm holes a tab, two tabs an edge and one more each 55 mm, a third of a hole into the board, none on the rails) with the rout path; it refuses a board whose own outline on a mechanical layer would cut every copy free. The panel frame is now drawn on Mechanical 1 (the panel's Gerbers had the boards' outlines but no frame), copper outside the board is flagged, and `projectPath` adds the panel to the project for its Gerbers.
README.md+9−6
@@ -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 -189 commands, tested on Altium Designer 26.11 and Altium Designer Develop. It runs in **Hydrogen**, Adom's free+192 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. 189 verbs; each row names the ones+Tested on Altium Designer 26.11.1 and Altium Designer Develop. 192 verbs; each row names the ones behind it (prefix `altium_`).  | Area | What the AI can do | Verbs |@@ -43,11 +43,11 @@ behind it (prefix `altium_`). | 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` | | 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); 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 | `board_features` |+| 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` | | 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; 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 | `export_manufacturing`, `fab_check`, `panelize`, `run_outjob`, `outjob_info`, `export_pdf`, `export_step`, `silkscreen_prep` |+| 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 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`, `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` | | Seeing it | Open any surface with a screenshot, 2D and 3D board views, zoom to parts or nets, camera moves | `show_*`, `zoom_to`, `select_net`, `animate_view` | | Running Altium | Launch in the background, look after the licence seat, close nuisance dialogs, work with several Altiums at once, run any DelphiScript or Altium command, install Altium | `launch`, `close`, `ensure_licensed`, `instances`, `check_dialogs`, `eval`, `run_command`, `install` |@@ -68,7 +68,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 189 `altium_*` verbs.+**DelphiScript agent** inside it, and gives the AI 192 `altium_*` verbs.  - **Page and docs:** https://wiki.adom.inc/adom/altium-bridge - **Bridge SDK:** https://wiki.adom.inc/adom/adom-bridge-sdk@@ -168,7 +168,7 @@ way to read it). A stopped engine is restarted with `altium_agent_recover`.  <!-- verbs:start (tools/readme_verbs.py writes this list) --> -All 189 verbs, by area (prefix `altium_`). `altium_describe` returns the live catalog with every input, output, hint and example.+All 192 verbs, by area (prefix `altium_`). `altium_describe` returns the live catalog with every input, output, hint and example.  ### Running Altium: launch, close, health, dialogs @@ -259,6 +259,9 @@ All 189 verbs, by area (prefix `altium_`). `altium_describe` returns the live ca - `altium_height_check`: Will it fit the enclosure? Each part's height from its 3D bodies (top and bottom side), the parts over a height limit board-wide or under a lid feature in a region, and part bodies that collide or come closer than a gap. - `altium_copper_balance`: How much of each copper layer is copper (tracks, pads, vias and what Altium actually poured, inside the outline; a plane counts full), and how far apart each mirrored pair of layers is: the copper balance a fab asks about because an unbalanced stack bows and twists in reflow. - `altium_return_path`: Where signal tracks lose their reference: for every signal net, the length of track on each layer that runs over no pour or plane copper on either neighbouring layer (a split, a gap, a void), with where the first gap starts.+- `altium_silk_designators`: Place every reference designator the way assembly houses want: one size, upright, beside its own part, clear of every pad (JLCPCB: 0.15 mm), every other part's body and the other designators, inside the board; read back from Altium's own text boxes.+- `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_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/assembly.rsadded+140
@@ -0,0 +1,140 @@+//! Ready for JLCPCB assembly? The board against both of JLCPCB's PCBA tiers as published+//! (jlcpcb.com/capabilities/pcb-assembly-capabilities, read 2026-10-26): size, thickness and layers, one or two sides,+//! the smallest package and the finest pin pitch, fiducials, and which parts have no LCSC number. It answers the tier+//! the board can be ordered in.+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 }++/// What the board offers the assembly line, from routing_state. Pure.+pub fn facts(st: &Value) -> Value {+    let pads = st["pads"].as_array().cloned().unwrap_or_default();+    let comps = st["components"].as_array().cloned().unwrap_or_default();+    let mut by: BTreeMap<String, Vec<(f64, f64)>> = BTreeMap::new();+    for p in pads.iter().filter(|p| f(&p["drill"]) == 0.0) {+        if let Some(r) = p["ref"].as_str().filter(|r| !r.is_empty()) { by.entry(r.to_string()).or_default().push((f(&p["x"]), f(&p["y"]))); }+    }+    // the finest pitch: the closest pad centres within one part with 3 or more SMD pads (an IC, a BGA, a connector)+    let mut pitch: Option<(f64, String)> = None;+    // the smallest two-pad part: its pad centres (an 0402 is about 1.0 mm apart, an 0201 0.5, an 01005 0.35)+    let mut chip: Option<(f64, String)> = None;+    for (r, ps) in &by {+        let mut d = f64::MAX;+        for i in 0..ps.len() { for j in i + 1..ps.len() { d = d.min(((ps[i].0 - ps[j].0).powi(2) + (ps[i].1 - ps[j].1).powi(2)).sqrt()); } }+        if ps.len() >= 3 && pitch.as_ref().map(|p| d < p.0).unwrap_or(true) { pitch = Some((d, r.clone())); }+        if ps.len() == 2 && chip.as_ref().map(|p| d < p.0).unwrap_or(true) { chip = Some((d, r.clone())); }+    }+    let named = |c: &Value, pat: &[&str]| { let p = c["pattern"].as_str().unwrap_or("").to_ascii_uppercase(); pat.iter().any(|x| p.contains(x)) };+    let tiny: Vec<Value> = comps.iter().filter(|c| named(c, &["0201", "01005", "0603M", "0402M"])).map(|c| json!({"ref": c["ref"], "footprint": c["pattern"]})).collect();+    let fid = |s: &str| s.to_ascii_uppercase().starts_with("FID");+    let fiducials = comps.iter().filter(|c| c["ref"].as_str().map(fid).unwrap_or(false) || named(c, &["FIDUCIAL"])).count()+        + pads.iter().filter(|p| p["ref"].as_str().map(|r| r.is_empty()).unwrap_or(true) && p["name"].as_str().map(fid).unwrap_or(false)).count();+    let bottom: Vec<Value> = comps.iter().filter(|c| c["side"] == "bottom").map(|c| c["ref"].clone()).collect();+    let tht = pads.iter().filter(|p| f(&p["drill"]) > 0.0 && p["ref"].as_str().map(|r| !r.is_empty()).unwrap_or(false))+        .filter_map(|p| p["ref"].as_str().map(String::from)).collect::<std::collections::BTreeSet<_>>();+    json!({"parts": comps.len(), "bottomSideParts": bottom, "finestPitch": pitch.map(|(d, r)| json!({"mm": r3(d), "ref": r})),+           "smallestChip": chip.map(|(d, r)| json!({"padCentresMm": r3(d), "ref": r})), "tinyFootprints": tiny, "fiducials": fiducials,+           "throughHoleParts": tht.into_iter().collect::<Vec<_>>()})+}++fn rule(name: &str, ok: Option<bool>, detail: String) -> Value { json!({"rule": name, "ok": ok, "detail": detail}) }++/// The board against one tier ("economic" or "standard"). `size` is [w, h] mm (the board, or the panel it ships in),+/// `lcsc_missing` the purchased lines with no LCSC number (None: not checked). Pure.+pub fn tier(name: &str, fa: &Value, size: (f64, f64), thick: Option<f64>, layers: Option<i64>, lcsc_missing: Option<usize>, panel: bool) -> Value {+    let eco = name == "economic";+    let mut rs = Vec::new();+    let (w, h) = (size.0.min(size.1), size.0.max(size.1));+    let (lo, hi): ((f64, f64), (f64, f64)) = match (eco, panel) { (true, false) => ((10.0, 10.0), (470.0, 500.0)), (true, true) => ((10.0, 10.0), (250.0, 250.0)), (false, false) => ((70.0, 70.0), (460.0, 500.0)), (false, true) => ((70.0, 70.0), (250.0, 250.0)) };+    let ok = w >= lo.0 && h >= lo.1 && w <= hi.0.min(hi.1) && h <= hi.0.max(hi.1);+    rs.push(rule(&format!("{} {} x {} to {} x {} mm", if panel { "panel" } else { "board" }, lo.0, lo.1, hi.0, hi.1), Some(ok), format!("{} x {} mm{}", r3(size.0), r3(size.1), if !ok && !eco && !panel { ": a panel (altium_panelize) can bring it to 70 x 70" } else { "" })));+    if eco {+        rs.push(match thick { Some(t) => rule("board 0.8 to 1.6 mm thick", Some((0.8 - 1e-6..=1.6 + 1e-6).contains(&t)), format!("{} mm", r3(t))), None => rule("board 0.8 to 1.6 mm thick", None, "thickness not read".into()) });+        rs.push(match layers { Some(n) => rule("2, 4 or 6 layers", Some([2, 4, 6].contains(&n)), format!("{n} layers")), None => rule("2, 4 or 6 layers", None, "layers not read".into()) });+        let bot = fa["bottomSideParts"].as_array().map(|a| a.len()).unwrap_or(0);+        rs.push(rule("parts on one side only", Some(bot == 0), if bot == 0 { "all on top".into() } else { format!("{bot} part(s) on the bottom: {}", fa["bottomSideParts"]) }));+    }+    let (chip_min, pitch_min) = if eco { (0.8, 0.4) } else { (0.3, 0.35) };+    let tiny = fa["tinyFootprints"].as_array().map(|a| a.len()).unwrap_or(0);+    let chip = fa["smallestChip"]["padCentresMm"].as_f64();+    let chip_ok = (eco && tiny == 0 || !eco) && chip.map(|c| c >= chip_min).unwrap_or(true);+    rs.push(rule(if eco { "smallest package 0402" } else { "smallest package 01005" }, Some(chip_ok),+        format!("smallest two-pad part {} (pad centres {} mm){}", fa["smallestChip"]["ref"].as_str().unwrap_or("-"), chip.map(r3).unwrap_or(0.0), if tiny > 0 { format!("; footprints named under 0402: {}", fa["tinyFootprints"]) } else { String::new() })));+    let pitch = fa["finestPitch"]["mm"].as_f64();+    rs.push(rule(&format!("IC pin pitch {pitch_min} mm or more (BGA {} mm)", if eco { 0.5 } else { 0.3 }), Some(pitch.map(|p| p + 1e-6 >= pitch_min).unwrap_or(true)),+        format!("finest {} mm on {}", pitch.map(r3).unwrap_or(0.0), fa["finestPitch"]["ref"].as_str().unwrap_or("-"))));+    if !eco {+        let n = fa["fiducials"].as_u64().unwrap_or(0);+        rs.push(rule("fiducials and edge rails", Some(n >= 2 || panel), if panel { "on the panel rails (altium_panelize adds three)".into() } else { format!("{n} fiducial(s) on the board: add 3 (altium_board_features fiducials) or ship it in a panel with rails") }));+    }+    rs.push(match lcsc_missing { Some(0) => rule("every purchased part has an LCSC number", Some(true), "all lines".into()),+        Some(n) => rule("every purchased part has an LCSC number", Some(false), format!("{n} line(s) without one: find them (adom-parts-search, adom-jlcpcb) or consign them")),+        None => rule("every purchased part has an LCSC number", None, "not checked: pass projectPath".into()) });+    let ok = rs.iter().all(|r| r["ok"] != json!(false));+    json!({"tier": name, "ok": ok, "rules": rs})+}++/// altium_assembly_check {filePath?, projectPath?, panelMm?}+pub fn assembly_check(args: &Value) -> Value {+    if let Some(g) = crate::support::need_licensed() { return g; }+    let mut lcsc_missing = None;+    let mut lcsc_lines = Value::Null;+    if let Some(prj) = crate::support::s(args, "projectPath") {+        let b = crate::bom::bom(&json!({"projectPath": prj, "write": false}));+        if b.get("success").and_then(|v| v.as_bool()) == Some(true) {+            let l = b["checks"]["jlcpcb"]["linesWithoutLcsc"].clone();+            lcsc_missing = Some(l.as_array().map(|a| a.len()).unwrap_or(0));+            lcsc_lines = l;+        } else { lcsc_lines = json!({"bomError": b.get("error").cloned().unwrap_or(Value::Null)}); }+    }+    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 Some((x0, y0, x1, y1)) = crate::fab::outline_bbox(&st) else { return json!({"success": false, "errorCode": "no_outline", "error": "the board has no outline"}) };+    let panel = args.get("panelMm").and_then(|v| v.as_array()).map(|a| (f(&a[0]), f(&a[1])));+    let size = panel.unwrap_or((x1 - x0, y1 - y0));+    let stack = crate::agent::call("layer_stack", &[], None, std::time::Duration::from_secs(60));+    let thick = stack.get("data").and_then(|d| d["totalUm"].as_f64()).map(|u| u / 1000.0);+    let layers = stack.get("data").and_then(|d| d["copperLayers"].as_i64());+    let fa = facts(&st);+    let eco = tier("economic", &fa, size, thick, layers, lcsc_missing, panel.is_some());+    let std_ = tier("standard", &fa, size, thick, layers, lcsc_missing, panel.is_some());+    let service = if eco["ok"] == json!(true) { json!("economic") } else if std_["ok"] == json!(true) { json!("standard") } else { Value::Null };+    json!({"success": true, "fab": {"name": "JLCPCB", "source": "https://jlcpcb.com/capabilities/pcb-assembly-capabilities", "read": "2026-10-26"},+        "service": service, "economic": eco, "standard": std_, "board": fa, "linesWithoutLcsc": lcsc_lines,+        "_hint": "service is the cheapest JLCPCB assembly tier every rule allows (null: fix what the rules mark false). Rotation: JLCPCB's part orientation can differ from Altium's for some packages; check every part in JLCPCB's placement preview after uploading the BOM and pick-and-place (altium_export_manufacturing, altium_bom writes the JLCPCB BOM)."})+}++#[cfg(test)]+mod tests {+    use super::*;++    fn board() -> Value {+        json!({"components": [{"ref": "U1", "side": "top", "pattern": "QFN-20"}, {"ref": "C1", "side": "top", "pattern": "C0402"}, {"ref": "R9", "side": "bottom", "pattern": "R0603"}],+               "pads": [{"ref": "U1", "name": "1", "x": 0.0, "y": 0.0, "drill": 0.0}, {"ref": "U1", "name": "2", "x": 0.5, "y": 0.0, "drill": 0.0}, {"ref": "U1", "name": "3", "x": 1.0, "y": 0.0, "drill": 0.0},+                        {"ref": "C1", "name": "1", "x": 5.0, "y": 0.0, "drill": 0.0}, {"ref": "C1", "name": "2", "x": 6.0, "y": 0.0, "drill": 0.0},+                        {"ref": "R9", "name": "1", "x": 9.0, "y": 0.0, "drill": 0.0}, {"ref": "R9", "name": "2", "x": 10.5, "y": 0.0, "drill": 0.0}]})+    }++    #[test]+    fn facts_find_pitch_the_smallest_chip_and_the_bottom_side() {+        let fa = facts(&board());+        assert_eq!(fa["finestPitch"], json!({"mm": 0.5, "ref": "U1"}));+        assert_eq!(fa["smallestChip"], json!({"padCentresMm": 1.0, "ref": "C1"}));+        assert_eq!(fa["bottomSideParts"], json!(["R9"]));+    }++    #[test]+    fn a_small_two_sided_board_needs_standard_in_a_panel() {+        let fa = facts(&board());+        let eco = tier("economic", &fa, (40.0, 20.0), Some(1.6), Some(2), Some(0), false);+        assert_eq!(eco["ok"], json!(false)); // R9 on the bottom+        let std_ = tier("standard", &fa, (40.0, 20.0), Some(1.6), Some(2), Some(0), false);+        assert_eq!(std_["ok"], json!(false)); // under 70 x 70 and no fiducials+        let std_panel = tier("standard", &fa, (90.0, 80.0), Some(1.6), Some(2), Some(0), true);+        assert_eq!(std_panel["ok"], json!(true));+        assert_eq!(tier("economic", &fa, (40.0, 20.0), Some(0.4), Some(2), None, false)["rules"][1]["ok"], json!(false));+    }+}
bridge-rs/src/coppermap.rs+5−2
@@ -96,14 +96,17 @@ pub fn stack_layers(stack: &Value) -> Vec<(String, bool, String)> { }  /// The outline as a ring in mm (arc edges sampled).-fn outline_ring(st: &Value) -> Vec<(f64, f64)> {+pub(crate) fn outline_ring(st: &Value) -> Vec<(f64, f64)> {     let mut ring = Vec::new();     for e in st["outlineEdges"].as_array().cloned().unwrap_or_default() {         if e["kind"] == "arc" {             let (cx, cy, r) = (f(&e["center"][0]), f(&e["center"][1]), f(&e["radius"]));             let (a1, mut a2) = (f(&e["angle1"]), f(&e["angle2"]));             if a2 <= a1 { a2 += 360.0; }-            for k in 0..=16 { let t = (a1 + (a2 - a1) * k as f64 / 16.0).to_radians(); ring.push((cx + r * t.cos(), cy + r * t.sin())); }+            // every 2 degrees: a chord cuts inside the arc by r(1 - cos 1deg), 3 um on a 20 mm radius (16 points per+            // arc put a hatched pour's ends 0.04 mm outside the Bluetooth Sentinel example's edge)+            let k = (((a2 - a1) / 2.0).ceil() as usize).max(4);+            for q in 0..=k { let t = (a1 + (a2 - a1) * q as f64 / k as f64).to_radians(); ring.push((cx + r * t.cos(), cy + r * t.sin())); }         } else { ring.push((f(&e["start"][0]), f(&e["start"][1]))); }     }     if ring.is_empty() { ring = st["outline"].as_array().cloned().unwrap_or_default().iter().map(|p| (f(&p[0]), f(&p[1]))).collect(); }
bridge-rs/src/dialogs.rs+9
@@ -207,6 +207,15 @@ fn scan_impl(main_pid_only: bool, sel_pid: Option<u64>) -> Vec<Value> {             safe_action = Some("Cancel".into());             meaning = "A script hit a runtime error and Altium's debugger asks 'Continue execution?'. Cancel stops the script cleanly; the resident agent survives. Photograph it first: the error text is only in the picture.".into();         }+        if category == "unknown" && title.trim() == "Confirm" && body.trim().is_empty() && btns.len() == 2+            && btns.iter().any(|b| b.eq_ignore_ascii_case("yes")) && btns.iter().any(|b| b.eq_ignore_ascii_case("no")) {+            // a painted Yes/No question UIA cannot read: AD 26's startup "There are new versions of extensions+            // available. Would like to review and install them?" stopped agent_start dead (2026-10-26), and Altium's+            // save-over-a-file Confirm looks the same. No declines whatever it offers; save prompts are other dialogs.+            category = "unreadable_confirm".into();+            safe_action = Some("No".into());+            meaning = "A Yes/No 'Confirm' whose question Altium paints (unreadable by UIA): at startup it is AD 26's 'new versions of extensions available, review and install them?'. No declines it (updating is the user's call: Help > Extensions and Updates). Photograph it first when a verb of yours is waiting on it.".into();+        }         if category == "unknown" && title.to_lowercase().contains("renewal failed") {             category = "licence_seat_stranded".into();             safe_action = Some("OK".into());
bridge-rs/src/fab.rs+134−4
@@ -24,6 +24,34 @@ pub fn outline_bbox(state: &Value) -> Option<(f64, f64, f64, f64)> {     Some((x0, y0, x1, y1)) } +/// The nearest copper (track, arc, pad, via) to the real outline, edge of copper to the outline's line, mm. Pour+/// boundaries are left out: they are drawn on the edge and Altium pulls the poured copper back by its rules.+pub fn edge_distance(state: &Value) -> Option<(f64, Value)> {+    let ring = crate::coppermap::outline_ring(state);+    if ring.len() < 3 { return None; }+    let seg = |x: f64, y: f64| -> f64 {+        (0..ring.len()).map(|k| {+            let (a, b) = (ring[k], ring[(k + 1) % ring.len()]);+            let (dx, dy) = (b.0 - a.0, b.1 - a.1);+            let l2 = dx * dx + dy * dy;+            let t = if l2 > 0.0 { (((x - a.0) * dx + (y - a.1) * dy) / l2).clamp(0.0, 1.0) } else { 0.0 };+            ((a.0 + t * dx - x).powi(2) + (a.1 + t * dy - y).powi(2)).sqrt()+        }).fold(f64::MAX, f64::min)+    };+    let copper = |l: &Value| l.as_str().map(|s| s.ends_with(".Cu")).unwrap_or(false);+    let mut pts: Vec<(f64, f64, f64, Value)> = Vec::new();+    for t in state["tracks"].as_array().cloned().unwrap_or_default().iter().filter(|t| copper(&t["layer"])) {+        for p in [&t["start"], &t["end"]] { pts.push((f(&p["x"]), f(&p["y"]), f(&t["width"]) / 2.0, json!({"track": t["net"], "layer": t["layer"]}))); }+    }+    for v in state["vias"].as_array().cloned().unwrap_or_default() { pts.push((f(&v["position"]["x"]), f(&v["position"]["y"]), f(&v["size"]) / 2.0, json!({"via": v["net"]}))); }+    for p in state["pads"].as_array().cloned().unwrap_or_default() {+        let (rf, nm) = (p["ref"].as_str().unwrap_or(""), p["name"].as_str().unwrap_or(""));+        pts.push((f(&p["x"]), f(&p["y"]), f(&p["sizeX"]).max(f(&p["sizeY"])) / 2.0, json!({"pad": if rf.is_empty() { nm.to_string() } else { format!("{rf}.{nm}") }})));+    }+    pts.into_iter().map(|(x, y, half, mut what)| { what["at"] = json!([r3(x), r3(y)]); (r3(seg(x, y) - half), what) })+        .min_by(|a, b| a.0.partial_cmp(&b.0).unwrap())+}+ /// The smallest of each feature with where it is. Pure, for the tests. pub fn measure(state: &Value) -> Map<String, Value> {     let mut m = Map::new();@@ -48,7 +76,27 @@ pub fn measure(state: &Value) -> Map<String, Value> {     min_by("smdPad", pads.iter().filter(|p| f(&p["drill"]) == 0.0).map(|p| (f(&p["sizeX"]).min(f(&p["sizeY"])), label(p))).collect());     if let Some((x0, y0, x1, y1)) = outline_bbox(state) {         m.insert("boardSize".into(), json!({"mm": [r3(x1 - x0), r3(y1 - y0)]}));+        let _ = (x0, y0, x1, y1);+        if let Some((d, mut at)) = edge_distance(state) { at["mm"] = json!(d); m.insert("edgeClearance".into(), at); }     }+    // drilled holes: the largest, and the closest pair edge to edge (via to via, and any pair with a pad hole)+    let mut holes: Vec<(f64, f64, f64, bool, Value)> = vias.iter().map(|v| (f(&v["position"]["x"]), f(&v["position"]["y"]), f(&v["drill"]), false, json!({"via": v["net"], "at": [v["position"]["x"], v["position"]["y"]]}))).collect();+    holes.extend(drilled.iter().map(|p| (f(&p["x"]), f(&p["y"]), f(&p["drill"]), true, label(p))));+    if let Some(h) = holes.iter().max_by(|a, b| a.2.partial_cmp(&b.2).unwrap()) { m.insert("largestDrill".into(), json!({"mm": r3(h.2), "at": h.4})); }+    holes.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());+    let (mut vv, mut pp): (Option<(f64, Value)>, Option<(f64, Value)>) = (None, None);+    for i in 0..holes.len() {+        for j in i + 1..holes.len() {+            let (a, b) = (&holes[i], &holes[j]);+            if b.0 - a.0 > 10.0 { break; }+            let d = ((a.0 - b.0).powi(2) + (a.1 - b.1).powi(2)).sqrt() - (a.2 + b.2) / 2.0;+            if (a.0 - b.0).abs() < 1e-6 && (a.1 - b.1).abs() < 1e-6 { continue; } // a via in a pad+            let slot = if a.3 || b.3 { &mut pp } else { &mut vv };+            if slot.as_ref().map(|s| d < s.0).unwrap_or(true) { *slot = Some((d, json!([a.4.clone(), b.4.clone()]))); }+        }+    }+    if let Some((d, at)) = vv { m.insert("holeToHoleVia".into(), json!({"mm": r3(d), "at": at})); }+    if let Some((d, at)) = pp { m.insert("holeToHolePad".into(), json!({"mm": r3(d), "at": at})); }     m.insert("counts".into(), json!({"tracks": state["tracks"].as_array().map(|a| a.len()), "vias": vias.len(), "pads": pads.len(), "drilledPads": drilled.len()}));     m }@@ -58,7 +106,9 @@ pub fn compare(meas: &Map<String, Value>, limits: &Map<String, Value>, clearance     let mut out = Vec::new();     let got = |k: &str| meas.get(k).and_then(|v| v["mm"].as_f64());     for (limit, feature) in [("minTrack", "track"), ("minViaDrill", "viaDrill"), ("minViaDiameter", "viaDiameter"), ("minViaAnnularRing", "viaAnnularRing"),-                             ("minPadHole", "padHole"), ("minPadAnnularRing", "padAnnularRing"), ("minSmdPad", "smdPad")] {+                             ("minPadHole", "padHole"), ("minPadAnnularRing", "padAnnularRing"), ("minSmdPad", "smdPad"),+                             ("minEdgeClearance", "edgeClearance"), ("minHoleToHoleVia", "holeToHoleVia"), ("minHoleToHolePad", "holeToHolePad"),+                             ("minSilkLine", "silkLine"), ("minSilkText", "silkText")] {         if let (Some(l), Some(v)) = (limits.get(limit).and_then(|x| x.as_f64()), got(feature)) {             if v + 1e-9 < l { out.push(json!({"limit": limit, "limitMm": l, "boardMm": v, "at": meas[feature]["at"]})); }         }@@ -69,6 +119,14 @@ pub fn compare(meas: &Map<String, Value>, limits: &Map<String, Value>, clearance     if let (Some(l), Some(n)) = (limits.get("maxLayers").and_then(|x| x.as_i64()), layers) {         if n > l { out.push(json!({"limit": "maxLayers", "limit_": l, "board": n})); }     }+    if let (Some(l), Some(v)) = (limits.get("maxDrill").and_then(|x| x.as_f64()), got("largestDrill")) {+        if v > l + 1e-9 { out.push(json!({"limit": "maxDrill", "limitMm": l, "boardMm": v, "at": meas["largestDrill"]["at"], "note": "larger holes are milled (routed) instead"})); }+    }+    if let (Some(lim), Some(sz)) = (limits.get("minBoardMm").and_then(|x| x.as_array()), meas.get("boardSize").and_then(|b| b["mm"].as_array())) {+        let (lw, lh) = (lim.first().and_then(|x| x.as_f64()).unwrap_or(0.0), lim.get(1).and_then(|x| x.as_f64()).unwrap_or(0.0));+        let (w, h) = (sz[0].as_f64().unwrap_or(0.0), sz[1].as_f64().unwrap_or(0.0));+        if w.min(h) + 1e-9 < lw.min(lh) || w.max(h) + 1e-9 < lw.max(lh) { out.push(json!({"limit": "minBoardMm", "limitMm": [lw, lh], "boardMm": [w, h]})); }+    }     if let (Some(lim), Some(sz)) = (limits.get("maxBoardMm").and_then(|x| x.as_array()), meas.get("boardSize").and_then(|b| b["mm"].as_array())) {         let (lw, lh) = (lim.first().and_then(|x| x.as_f64()).unwrap_or(f64::MAX), lim.get(1).and_then(|x| x.as_f64()).unwrap_or(f64::MAX));         let (w, h) = (sz[0].as_f64().unwrap_or(0.0), sz[1].as_f64().unwrap_or(0.0));@@ -93,6 +151,25 @@ pub fn min_clearance(rules: &[Value]) -> Option<f64> { }  /// altium_fab_check {filePath?, limits?}+/// JLCPCB's standard rigid-board capabilities (jlcpcb.com/capabilities/pcb-capabilities, read 2026-10-23) for this many+/// copper layers and outer copper weight (oz), and the notes on what passes only on a costlier option. Pure.+pub fn jlcpcb_limits(layers: i64, oz: f64) -> (Map<String, Value>, Vec<&'static str>) {+    let multi = layers >= 4;+    let two_oz = oz >= 1.75;+    let track = match (multi, two_oz) { (false, false) => 0.10, (true, false) => 0.09, (false, true) => 0.16, (true, true) => 0.15 };+    let max_board = match layers { 1 => json!([606, 510]), 2 => json!([670, 600]), 4 => json!([663, 593]), _ => json!([656, 586]) };+    let l = json!({"minTrack": track, "minClearance": track, "minViaDrill": 0.15, "minViaDiameter": 0.25, "minPadHole": 0.15,+        "minPadAnnularRing": if two_oz { 0.254 } else if multi { 0.15 } else { 0.18 }, "maxDrill": 6.3, "minHoleToHoleVia": 0.2, "minHoleToHolePad": 0.45,+        "minEdgeClearance": 0.2, "minSilkLine": 0.15, "minSilkText": 1.0, "minBoardMm": [3, 3], "maxBoardMm": max_board});+    let notes = vec![+        "via holes of 0.15 mm (and the 0.2/0.25 mm options with small vias) cost more; 0.1 mm holes and 0.2 mm vias only on boards 1 mm thick or thinner with ENIG or OSP",+        "PTH annular ring: JLCPCB recommends 0.25 mm (1-2 layers) or 0.20 mm (multilayer); the limit checked is the absolute minimum",+        "V-cut panels need copper 0.4 mm from the cut (altium_panelize separation:vscore checks it); routed and mouse-bite edges 0.2 mm",+        "NPTH holes 0.5 mm or more with a 0.45 mm ring; silkscreen 0.15 mm from pads (altium_silkscreen_prep clears it)",+    ];+    (l.as_object().cloned().unwrap_or_default(), notes)+}+ pub fn fab_check(args: &Value) -> Value {     if let Some(g) = crate::support::need_licensed() { return g; }     if let Some(p) = crate::support::s(args, "filePath") { if let Some(e) = crate::support::must_open(&p, 60) { return e; } }@@ -106,10 +183,45 @@ pub fn fab_check(args: &Value) -> Value {     let stack = crate::agent::call("layer_stack", &[], None, std::time::Duration::from_secs(60));     let layers = stack.get("data").and_then(|d| d.get("copperLayers")).and_then(|v| v.as_i64());     if let Some(n) = layers { meas.insert("copperLayers".into(), json!(n)); }-    let limits = args.get("limits").and_then(|l| l.as_object()).cloned().unwrap_or_default();+    let mut limits = Map::new();+    let mut fab = Value::Null;+    if let Some(name) = crate::support::s(args, "fab") {+        if !name.eq_ignore_ascii_case("jlcpcb") && !name.eq_ignore_ascii_case("jlc") {+            return json!({"success": false, "errorCode": "unknown_fab", "error": format!("no built-in limits for {name}: jlcpcb is built in; pass any other fab's numbers as limits")});+        }+        // the outer copper weight from the stack (35 um = 1 oz)+        let outer_um = stack.get("data").and_then(|d| d["layers"][0]["copperUm"].as_f64()).unwrap_or(35.0);+        let oz = args.get("copperOz").and_then(|v| v.as_f64()).unwrap_or(outer_um / 35.0);+        let (l, notes) = jlcpcb_limits(layers.unwrap_or(2), oz);+        limits = l;+        fab = json!({"name": "JLCPCB", "service": "standard rigid PCB", "copperOz": r3(oz), "source": "https://jlcpcb.com/capabilities/pcb-capabilities", "read": "2026-10-23", "notes": notes});+    }+    for (k, v) in args.get("limits").and_then(|l| l.as_object()).cloned().unwrap_or_default() { limits.insert(k, v); }+    // silkscreen sizes, only when a limit asks (the read walks every text)+    if limits.contains_key("minSilkText") || limits.contains_key("minSilkLine") {+        let silk = crate::routing::silk_state(&json!({}));+        let mut texts: Vec<(f64, Value)> = silk["texts"].as_array().cloned().unwrap_or_default().iter().filter(|t| t["side"] != "other").map(|t| (f(&t["size"]), json!({"text": t["text"], "at": [t["x"], t["y"]]}))).collect();+        for c in silk["components"].as_array().cloned().unwrap_or_default() {+            for k in ["name", "comment"] { if c[k]["shown"].as_bool() == Some(true) { texts.push((f(&c[k]["size"]), json!({"ref": c["ref"], "text": c[k]["text"], "at": [c[k]["x"], c[k]["y"]]}))); } }+        }+        if let Some((v, at)) = texts.into_iter().filter(|t| t.0 > 0.0).min_by(|a, b| a.0.partial_cmp(&b.0).unwrap()) { meas.insert("silkText".into(), json!({"mm": r3(v), "at": at})); }+        if let Some(l) = silk["lines"].as_array().cloned().unwrap_or_default().iter().filter(|l| l["side"] != "other" && f(&l["width"]) > 0.0).min_by(|a, b| f(&a["width"]).partial_cmp(&f(&b["width"])).unwrap()) {+            meas.insert("silkLine".into(), json!({"mm": r3(f(&l["width"])), "at": [l["x1"], l["y1"]]}));+        }+    }     let fails = compare(&meas, &limits, clearance, layers);-    json!({"success": true, "measured": meas, "limitsChecked": limits.keys().collect::<Vec<_>>(), "outsideLimits": fails, "fits": if limits.is_empty() { Value::Null } else { json!(fails.is_empty()) },-        "_hint": if limits.is_empty() { "Measured only. Pass the fab's limits (from its capability page) as limits:{minTrack, minClearance, minViaDrill, minViaDiameter, minViaAnnularRing, minPadHole, minPadAnnularRing, minSmdPad, maxLayers, maxBoardMm:[w,h]} in mm to check them." }+    // passes, but on a costlier option or under the recommendation+    let mut costlier = Vec::new();+    if !fab.is_null() {+        if let Some(v) = meas.get("viaDrill").and_then(|v| v["mm"].as_f64()) { if v < 0.3 { costlier.push(json!({"feature": "viaDrill", "boardMm": v, "note": "via holes under 0.3 mm are JLCPCB's costlier via options: choose the via size when ordering"})); } }+        if let Some(v) = meas.get("padAnnularRing").and_then(|v| v["mm"].as_f64()) {+            let rec = if layers.unwrap_or(2) >= 4 { 0.20 } else { 0.25 };+            if v < rec { costlier.push(json!({"feature": "padAnnularRing", "boardMm": v, "note": format!("under JLCPCB's recommended {rec} mm ring (within its absolute minimum when outsideLimits is silent)")})); }+        }+    }+    json!({"success": true, "fab": fab, "measured": meas, "limitsChecked": limits.keys().collect::<Vec<_>>(), "outsideLimits": fails, "fits": if limits.is_empty() { Value::Null } else { json!(fails.is_empty()) },+        "costlierOrBelowRecommended": costlier,+        "_hint": if limits.is_empty() { "Measured only. Pass fab:\"jlcpcb\" for JLCPCB's published limits, or any fab's limits (from its capability page) as limits:{minTrack, minClearance, minViaDrill, minViaDiameter, minViaAnnularRing, minPadHole, minPadAnnularRing, minSmdPad, minEdgeClearance, minHoleToHoleVia, minHoleToHolePad, maxDrill, minSilkLine, minSilkText, maxLayers, minBoardMm:[w,h], maxBoardMm:[w,h]} in mm to check them." }                  else { "outsideLimits names each feature below the fab's limit and where it is. Fix them (altium_set_track_width, altium_add_rule, a footprint change) or choose the fab's advanced service; then run altium_run_drc." }}) } @@ -156,4 +268,22 @@ mod tests {                          json!({"kind": 0, "descriptor": "Clearance Constraint (Gap=0.05mm) (All),(All)", "enabled": false})];         assert_eq!(min_clearance(&rules), Some(0.15));     }+    #[test]+    fn jlcpcb_limits_follow_layers_and_copper() {+        let (two, _) = jlcpcb_limits(2, 1.0);+        assert_eq!(two["minTrack"], 0.1);+        assert_eq!(two["minPadAnnularRing"], 0.18);+        assert_eq!(two["maxBoardMm"], json!([670, 600]));+        let (four, _) = jlcpcb_limits(4, 1.0);+        assert_eq!(four["minTrack"], 0.09);+        assert_eq!(jlcpcb_limits(2, 2.0).0["minTrack"], 0.16);+        // a 0.3 mm track board passes, a 0.08 mm one does not, and holes 0.15 mm apart edge to edge fail the via rule+        let st = json!({"tracks": [{"width": 0.08, "net": "A", "layer": "F.Cu", "start": {"x": 1.0, "y": 1.0}}],+                        "vias": [{"drill": 0.3, "size": 0.6, "net": "A", "position": {"x": 0.0, "y": 0.0}}, {"drill": 0.3, "size": 0.6, "net": "B", "position": {"x": 0.45, "y": 0.0}}],+                        "outline": [[-5, -5], [5, -5], [5, 5], [-5, 5]]});+        let m = measure(&st);+        assert_eq!(m["holeToHoleVia"]["mm"], 0.15);+        let fails: Vec<String> = compare(&m, &two, None, Some(2)).iter().map(|f| f["limit"].as_str().unwrap().to_string()).collect();+        assert!(fails.contains(&"minTrack".to_string()) && fails.contains(&"minHoleToHoleVia".to_string()), "{fails:?}");+    } }
bridge-rs/src/features.rs+147−17
@@ -26,7 +26,14 @@ fn seg_dist(px: f64, py: f64, a: (f64, f64), b: (f64, f64)) -> f64 { enum Ob { Seg((f64, f64), (f64, f64), f64), Disc(f64, f64, f64) }  fn obstacles(state: &Value, net: &str) -> (Vec<Ob>, Vec<(f64, f64)>) {-    let other = |v: &Value| !v["net"].as_str().unwrap_or("").eq_ignore_ascii_case(net);+    // copper on another net. Lines on mechanical and overlay layers are not copper, and net-less copper tracks are a+    // hatched pour's pieces (Altium lists them with no net) that re-pour round a new via+    let other = |v: &Value| {+        let n = v["net"].as_str().unwrap_or("");+        let copper = v.get("layer").map(|l| l.as_str().map(|s| s.ends_with(".Cu")).unwrap_or(false)).unwrap_or(true);+        let piece = n.is_empty() && v.get("start").or(v.get("center")).is_some();+        copper && !piece && !n.eq_ignore_ascii_case(net)+    };     let mut ob = Vec::new();     let mut same_vias = Vec::new();     for t in state["tracks"].as_array().cloned().unwrap_or_default() {@@ -87,29 +94,132 @@ pub fn plan_stitching_with(state: &Value, net: &str, pitch: f64, size: f64, clea     }     let (x0, x1) = area.iter().fold((f64::MAX, f64::MIN), |a, p| (a.0.min(p.0), a.1.max(p.0)));     let (y0, y1) = area.iter().fold((f64::MAX, f64::MIN), |a, p| (a.0.min(p.1), a.1.max(p.1)));-    let r = size / 2.0;-    let mut out = Vec::new();+    let mut cands = Vec::new();     let mut y = y0 + pitch / 2.0;-    while y < y1 && out.len() < max {+    while y < y1 {         let mut x = x0 + pitch / 2.0;-        while x < x1 && out.len() < max {-            let ok = inside(&outline, x, y) && inside(&area, x, y)-                && (0..outline.len()).all(|k| seg_dist(x, y, outline[k], outline[(k + 1) % outline.len()]) >= edge + r)-                && ob.iter().all(|o| match o {-                    Ob::Seg(a, b, hw) => seg_dist(x, y, *a, *b) - hw - r >= clearance,-                    Ob::Disc(cx, cy, cr) => ((x - cx).powi(2) + (y - cy).powi(2)).sqrt() - cr - r >= clearance,-                })-                && same.iter().all(|(sx, sy)| ((x - sx).powi(2) + (y - sy).powi(2)).sqrt() >= pitch / 2.0)-                && boxes.values().all(|b| x + r + clearance <= b.0 || x - r - clearance >= b.2 || y + r + clearance <= b.1 || y - r - clearance >= b.3)-                && keepouts.iter().all(|k| x + r <= k.0 || x - r >= k.2 || y + r <= k.1 || y - r >= k.3);-            if ok { out.push(((x * 1000.0).round() / 1000.0, (y * 1000.0).round() / 1000.0)); }-            x += pitch;-        }+        while x < x1 { if inside(&area, x, y) { cands.push((x, y)); } x += pitch; }         y += pitch;     }+    keep_clear(state, &outline, &cands, pitch / 2.0, size, clearance, edge, max, &ob, &same, &boxes, keepouts)+}++/// The candidate via points that fit: inside the outline, `edge` from it, `clearance` from other copper (`ob`), out of+/// part boxes and keepouts, and `sep` from the net's vias and from each other. Pure.+#[allow(clippy::too_many_arguments)]+fn keep_clear(_state: &Value, outline: &[(f64, f64)], cands: &[(f64, f64)], sep: f64, size: f64, clearance: f64, edge: f64, max: usize, ob: &[Ob],+              same: &[(f64, f64)], boxes: &std::collections::BTreeMap<String, (f64, f64, f64, f64)>, keepouts: &[(f64, f64, f64, f64)]) -> Vec<(f64, f64)> {+    let r = size / 2.0;+    let mut out: Vec<(f64, f64)> = Vec::new();+    for &(x, y) in cands {+        if out.len() >= max { break; }+        let ok = inside(outline, x, y)+            && (0..outline.len()).all(|k| seg_dist(x, y, outline[k], outline[(k + 1) % outline.len()]) >= edge + r)+            && ob.iter().all(|o| match o {+                Ob::Seg(a, b, hw) => seg_dist(x, y, *a, *b) - hw - r >= clearance,+                Ob::Disc(cx, cy, cr) => ((x - cx).powi(2) + (y - cy).powi(2)).sqrt() - cr - r >= clearance,+            })+            && same.iter().chain(out.iter()).all(|(sx, sy)| ((x - sx).powi(2) + (y - sy).powi(2)).sqrt() >= sep)+            && boxes.values().all(|b| x + r + clearance <= b.0 || x - r - clearance >= b.2 || y + r + clearance <= b.1 || y - r - clearance >= b.3)+            && keepouts.iter().all(|k| x + r <= k.0 || x - r >= k.2 || y + r <= k.1 || y - r >= k.3);+        if ok { out.push(((x * 1000.0).round() / 1000.0, (y * 1000.0).round() / 1000.0)); }+    }     out } +/// Via fence candidates: both sides of every copper track of `nets`, `offset` from its centreline, every `pitch` along+/// it; and with `edge_inset`, along the outline that far inside it. Pure.+pub fn fence_points(state: &Value, nets: &[String], pitch: f64, offset: f64, edge_inset: Option<f64>) -> Vec<(f64, f64)> {+    let mut v = Vec::new();+    for t in state["tracks"].as_array().cloned().unwrap_or_default() {+        let n = t["net"].as_str().unwrap_or("");+        if !nets.iter().any(|x| x.eq_ignore_ascii_case(n)) || !t["layer"].as_str().map(|l| l.ends_with(".Cu")).unwrap_or(false) { continue; }+        let (a, b) = ((f(&t["start"]["x"]), f(&t["start"]["y"])), (f(&t["end"]["x"]), f(&t["end"]["y"])));+        let len = ((b.0 - a.0).powi(2) + (b.1 - a.1).powi(2)).sqrt();+        if len <= 0.0 { continue; }+        let (ux, uy) = ((b.0 - a.0) / len, (b.1 - a.1) / len);+        let k = (len / pitch).floor() as usize;+        for i in 0..=k {+            let s = if k == 0 { len / 2.0 } else { i as f64 * len / k as f64 };+            for side in [1.0, -1.0] { v.push((a.0 + ux * s - uy * offset * side, a.1 + uy * s + ux * offset * side)); }+        }+    }+    if let Some(inset) = edge_inset {+        let ring = crate::coppermap::outline_ring(state);+        let n = ring.len();+        // inward is left of each edge on a counterclockwise ring+        let area: f64 = (0..n).map(|k| ring[k].0 * ring[(k + 1) % n].1 - ring[(k + 1) % n].0 * ring[k].1).sum();+        let sgn = if area > 0.0 { 1.0 } else { -1.0 };+        let mut carry: f64 = 0.0;+        for k in 0..n {+            let (a, b) = (ring[k], ring[(k + 1) % n]);+            let len = ((b.0 - a.0).powi(2) + (b.1 - a.1).powi(2)).sqrt();+            if len <= 0.0 { continue; }+            let (ux, uy) = ((b.0 - a.0) / len, (b.1 - a.1) / len);+            // clear of the corners by the inset, where an inward step from one edge lands on the next+            let mut s = carry.max(inset);+            while s <= len - inset { v.push((a.0 + ux * s - uy * inset * sgn, a.1 + uy * s + ux * inset * sgn)); s += pitch; }+            carry = (s - len).max(0.0);+        }+    }+    v+}++/// The board's preferred via (diameter, drill) in mm from its Routing Via rule's descriptor, e.g. "Routing Via+/// (MinHoleWidth=0.3mm) ... (PreferredHoleWidth=0.3mm) ... (PreferedWidth=0.5mm) (All)" (Altium's own spelling). Pure.+pub fn via_style(rules: &[Value]) -> Option<(f64, f64)> {+    let num = |d: &str, key: &str| -> Option<f64> {+        let i = d.find(&format!("({key}="))? + key.len() + 2;+        let s = &d[i..d[i..].find(')')? + i];+        let (v, unit) = s.trim_end_matches(char::is_alphabetic).parse::<f64>().ok().map(|v| (v, &s[s.trim_end_matches(char::is_alphabetic).len()..]))?;+        Some(if unit.eq_ignore_ascii_case("mil") { v * 0.0254 } else { v })+    };+    let mut rs: Vec<&Value> = rules.iter().filter(|r| r["enabled"] != json!(false) && r["descriptor"].as_str().map(|d| d.starts_with("Routing Via")).unwrap_or(false)).collect();+    // the board-wide rule (scope All), highest priority first+    rs.sort_by_key(|r| (r["scope1"].as_str() != Some("All"), r["priority"].as_i64().unwrap_or(99)));+    let d = rs.first()?["descriptor"].as_str()?;+    Some((num(d, "PreferedWidth").or(num(d, "PreferredWidth"))?, num(d, "PreferredHoleWidth")?))+}++/// 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};+    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(via_net) = crate::support::s(args, "viaNet") else { return json!({"success": false, "errorCode": "bad_args", "error": "viaNet is the net the fence ties to, usually GND"}) };+    if !st["nets"].as_array().map(|a| a.iter().any(|n| n.as_str().map(|s| s.eq_ignore_ascii_case(&via_net)).unwrap_or(false))).unwrap_or(false) {+        return json!({"success": false, "errorCode": "no_such_net", "error": format!("{via_net} is not a net on this board"), "nets": st["nets"]});+    }+    let nets: Vec<String> = args.get("nets").and_then(|v| v.as_array()).map(|a| a.iter().filter_map(|v| v.as_str().map(String::from)).collect()).unwrap_or_default();+    let edge_on = args.get("edge").and_then(|b| b.as_bool()).unwrap_or(false);+    if nets.is_empty() && !edge_on { return json!({"success": false, "errorCode": "bad_args", "error": "name nets to fence (e.g. [\"ANT_RF\"]) and/or edge:true for a fence round the board edge"}); }+    // the via the board's own Routing Via rule prefers, so the fence passes its DRC (0.6/0.3 broke the Bluetooth+    // Sentinel example's 0.5/0.3 rule on every via)+    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 clearance = num(args, "clearance", 0.2);+    // lambda/20 in FR-4 (effective er about 3.4) at the highest frequency, else 2 mm+    let pitch = match args.get("freqGHz").and_then(|v| v.as_f64()) { Some(g) if g > 0.0 => (299.79 / g / 3.4f64.sqrt() / 20.0).min(num(args, "pitchMm", f64::MAX)), _ => num(args, "pitchMm", 2.0) };+    let widest = st["tracks"].as_array().cloned().unwrap_or_default().iter().filter(|t| nets.iter().any(|n| t["net"].as_str().map(|s| s.eq_ignore_ascii_case(n)).unwrap_or(false))).map(|t| f(&t["width"])).fold(0.0, f64::max);+    let offset = num(args, "offsetMm", widest / 2.0 + clearance + size / 2.0 + 0.1);+    let inset = if edge_on { Some(num(args, "edgeInsetMm", size / 2.0 + 0.5)) } else { None };+    let cands = fence_points(&st, &nets, pitch, offset, inset);+    let outline: Vec<(f64, f64)> = crate::coppermap::outline_ring(&st);+    let (ob, same) = obstacles(&st, &via_net);+    let pts = keep_clear(&st, &outline, &cands, pitch * 0.6, size, clearance, 0.3, 5000, &ob, &same, &Default::default(), &[]);+    let planned = json!({"vias": pts.len(), "candidates": cands.len(), "via": {"sizeMm": size, "drillMm": drill, "from": if args.get("size").is_some() { "size/drill" } else if style.is_some() { "the board's Routing Via rule" } else { "default 0.6/0.3" }}, "pitchMm": (pitch * 1000.0).round() / 1000.0, "offsetMm": (offset * 1000.0).round() / 1000.0, "points": pts.iter().take(200).map(|(x, y)| json!([x, y])).collect::<Vec<_>>()});+    if args.get("dryRun").and_then(|b| b.as_bool()) == Some(true) || pts.is_empty() {+        return json!({"success": !pts.is_empty(), "dryRun": true, "planned": planned, "_hint": if pts.is_empty() { "No candidate fits: lower clearance or size, change offsetMm, or check the nets have tracks." } else { "Pass without dryRun to place them." }});+    }+    let ops: Vec<String> = pts.iter().map(|(x, y)| format!("V|{}|{}|{}|{}|{}|{}|{}", raw(*x), raw(*y), raw(size), raw(drill), TOP, BOTTOM, via_net)).collect();+    let r = apply(&ops, &st, "via_fence");+    json!({"success": r["success"], "applied": r["applied"], "failed": r["failed"], "planned": planned, "revision": r["revision"],+        "_hint": "Fence vias placed as one undo step, each clear of other copper by clearance and of the board edge, sized by the board's Routing Via rule. Repour (altium_repour) so pours join them, then altium_routing_drc {full:true} (the quick read can show stale test-point messages after a repour). skipped = candidates - vias: spots where other copper, a pad or the edge was too close."})+}+ /// The four corner positions of the outline's bounding box, `inset` mm in. pub fn corners(state: &Value, inset: f64) -> Vec<(f64, f64)> {     let o: Vec<(f64, f64)> = state["outline"].as_array().cloned().unwrap_or_default().iter().map(pt).collect();@@ -280,4 +390,24 @@ mod tests {     fn corner_holes_sit_inset_from_the_outline() {         assert_eq!(corners(&board(), 3.0), vec![(3.0, 3.0), (17.0, 3.0), (17.0, 7.0), (3.0, 7.0)]);     }+    #[test]+    fn fence_points_line_both_sides_of_a_track_and_the_edge() {+        let st = json!({"tracks": [{"net": "RF", "layer": "F.Cu", "width": 0.4, "start": {"x": 0.0, "y": 5.0}, "end": {"x": 10.0, "y": 5.0}}],+                        "outline": [[-5, 0], [15, 0], [15, 10], [-5, 10]],+                        "outlineEdges": [{"kind": "line", "start": [-5.0, 0.0]}, {"kind": "line", "start": [15.0, 0.0]}, {"kind": "line", "start": [15.0, 10.0]}, {"kind": "line", "start": [-5.0, 10.0]}]});+        let p = fence_points(&st, &["RF".to_string()], 2.0, 1.0, None);+        assert_eq!(p.len(), 12);+        assert!(p.contains(&(0.0, 6.0)) && p.contains(&(10.0, 4.0)));+        let e = fence_points(&st, &[], 5.0, 1.0, Some(0.5));+        assert!(e.iter().all(|(x, y)| *x >= -4.5 - 1e-9 && *x <= 14.5 + 1e-9 && *y >= 0.5 - 1e-9 && *y <= 9.5 + 1e-9), "{e:?}");+        assert!(e.len() >= 10, "{e:?}");+    }+    #[test]+    fn via_style_reads_altiums_descriptor() {+        let rules = vec![json!({"enabled": true, "scope1": "All", "priority": 1, "descriptor": "Routing Via (MinHoleWidth=0.3mm) (MaxHoleWidth=0.3mm) (PreferredHoleWidth=0.3mm) (MinWidth=0.5mm) (MaxWidth=0.5mm) (PreferedWidth=0.5mm) (All)"})];+        assert_eq!(via_style(&rules), Some((0.5, 0.3)));+        let mil = vec![json!({"enabled": true, "scope1": "All", "priority": 1, "descriptor": "Routing Via (PreferredHoleWidth=12mil) (PreferedWidth=24mil) (All)"})];+        let (s, d) = via_style(&mil).unwrap();+        assert!((s - 0.6096).abs() < 1e-9 && (d - 0.3048).abs() < 1e-9);+    } }
bridge-rs/src/main.rs+3−1
@@ -4,6 +4,7 @@ mod a365; mod ab; mod agent;+mod assembly; mod board; mod bodies; mod bom;@@ -35,6 +36,7 @@ mod review; mod route; mod routing; mod shot;+mod silkplace; mod support; mod surfaces; mod taskbar;@@ -49,7 +51,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.72";+pub const BRIDGE_VERSION: &str = "0.2.73";  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/panel.rs+8−2
@@ -264,7 +264,7 @@ pub fn panelize(args: &Value) -> Value {         }         // a document with that path may be open twice (a run cut short leaves its unsaved panel behind)         for _ in 0..3 {-            let c = crate::agent::call("close_document", &[("path", panel.clone())], None, std::time::Duration::from_secs(30));+            let c = crate::agent::call("close_document", &[("path", panel.replace('/', "\\"))], None, std::time::Duration::from_secs(30));             if c.get("data").and_then(|d| d.get("ok")).and_then(|v| v.as_bool()) != Some(true) { break; }         }         if let Err(e) = std::fs::remove_file(&panel) { return json!({"success": false, "errorCode": "panel_locked", "error": format!("could not replace {panel}: {e}")}); }@@ -336,9 +336,15 @@ pub fn panelize(args: &Value) -> Value {     }     let saved = crate::surfaces::save(&json!({}));     let mut project = Value::Null;+    let joined = s(args, "projectPath").is_some();+    if !joined {+        // a saved panel left open outside any project makes Altium's project edits refuse it as an unlisted document+        // (altium_sch_sheet_symbol answered project_has_unlisted_documents after it, battery 2026-10-26)+        crate::agent::call("close_document", &[("path", panel.replace('/', "\\"))], None, std::time::Duration::from_secs(30));+    }     if let Some(prj) = s(args, "projectPath") {         // the saved panel is open outside the project, which add_to_project refuses (it would be lost on reload)-        crate::agent::call("close_document", &[("path", panel.clone())], None, std::time::Duration::from_secs(30));+        crate::agent::call("close_document", &[("path", panel.replace('/', "\\"))], None, std::time::Duration::from_secs(30));         project = match crate::hier::add_to_project(&prj, &panel) { Ok(added) => json!({"path": prj, "added": added}), Err(e) => e };     }     let mut warnings = Vec::new();
bridge-rs/src/routing.rs+6−1
@@ -841,7 +841,12 @@ pub(crate) fn project_members(prj: &std::path::Path) -> (Vec<String>, Vec<String     let open: Vec<String> = st.get("data").and_then(|d| d.get("documents")).and_then(|d| d.as_array()).cloned().unwrap_or_default()         .iter().filter(|d| d["project"].as_str().map(|p| p.eq_ignore_ascii_case(&name)).unwrap_or(false) && d["open"].as_bool() == Some(true))         .filter_map(|d| d["path"].as_str().map(str::to_string)).collect();-    let unlisted = open.iter().filter(|o| !listed.iter().any(|l| same_file_name(l, std::path::Path::new(o.as_str())))).cloned().collect();+    // Altium names a document's project by file name only: a second lane.PrjPcb open from another folder lent its sheet+    // to this one and the check refused a clean project (battery 2026-10-26). Only documents in this project's folder+    // count as its unlisted ones.+    let here = |o: &str| std::path::Path::new(&o.replace('\\', "/")).parent().map(|p| p.to_string_lossy().to_lowercase())+        == Some(dir.to_string_lossy().replace('\\', "/").to_lowercase());+    let unlisted = open.iter().filter(|o| here(o) && !listed.iter().any(|l| same_file_name(l, std::path::Path::new(o.as_str())))).cloned().collect();     (open, unlisted) } 
bridge-rs/src/silkplace.rsadded+240
@@ -0,0 +1,240 @@+//! Reference designators placed the way assembly houses want them: one size for all, upright, beside their own part,+//! clear of every pad (JLCPCB: silkscreen 0.15 mm from pads), every other part's body and every designator already+//! placed, and inside the board. Altium's own text boxes are read back afterwards to prove it.+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 Rect = (f64, f64, f64, f64);++fn rect_of(v: &Value) -> Option<Rect> {+    let a = v.as_array()?;+    if a.len() != 4 { return None; }+    let n: Vec<f64> = a.iter().map(f).collect();+    Some((n[0].min(n[2]), n[1].min(n[3]), n[0].max(n[2]), n[1].max(n[3])))+}+fn grow(r: Rect, d: f64) -> Rect { (r.0 - d, r.1 - d, r.2 + d, r.3 + d) }+fn hit(a: Rect, b: Rect) -> bool { a.0 < b.2 && b.0 < a.2 && a.1 < b.3 && b.1 < a.3 }+fn union(a: Rect, b: Rect) -> Rect { (a.0.min(b.0), a.1.min(b.1), a.2.max(b.2), a.3.max(b.3)) }++/// A pad's copper as a rectangle (its rotated extent).+fn pad_rect(p: &Value) -> Rect {+    let (c, s) = (f(&p["rotation"]).to_radians().cos().abs(), f(&p["rotation"]).to_radians().sin().abs());+    let (sx, sy) = (f(&p["sizeX"]), f(&p["sizeY"]));+    let (hx, hy) = ((sx * c + sy * s) / 2.0, (sx * s + sy * c) / 2.0);+    (f(&p["x"]) - hx, f(&p["y"]) - hy, f(&p["x"]) + hx, f(&p["y"]) + hy)+}++fn on_side(layer: &Value, bottom: bool) -> bool {+    match layer.as_str() { Some("*.Cu") => true, Some("B.Cu") => bottom, Some("F.Cu") => !bottom, _ => false }+}++/// Where each designator goes: [{ref, x, y, size, rotation, side, at}] (x, y the text's lower-left, its right on the+/// bottom side where Altium mirrors it) and the parts with no clear spot. Pure: silk_state's components, the board's+/// pads and outline bounding box, and the boxes of labels that stay put.+pub fn plan(comps: &[Value], pads: &[Value], board: Rect, size: f64, min_size: f64, gap: f64, pad_clear: f64, fixed: &[(bool, Rect)]) -> (Vec<Value>, Vec<Value>) {+    // labels that stay where they are (parts left out, or with no spot) are obstacles like the ones placed+    let mut placed: Vec<(bool, Rect)> = fixed.to_vec();+    let (mut out, mut unplaced) = (Vec::new(), Vec::new());+    // the part's own outline: its body box and its own pads+    let own = |c: &Value| -> Option<Rect> {+        let r = c["ref"].as_str().unwrap_or("");+        let mut b = rect_of(&c["body"]);+        for p in pads.iter().filter(|p| p["ref"].as_str() == Some(r)) { b = Some(b.map(|x| union(x, pad_rect(p))).unwrap_or(pad_rect(p))); }+        b+    };+    let bodies: Vec<(String, bool, Rect)> = comps.iter().filter_map(|c| own(c).map(|b| (c["ref"].as_str().unwrap_or("").to_string(), c["side"] == "bottom", b))).collect();+    // big parts first: they have the fewest places to put a label and the small ones fit round them+    let mut order: Vec<&Value> = comps.iter().filter(|c| c["name"]["shown"].as_bool() != Some(false)).collect();+    order.sort_by(|a, b| {+        let area = |c: &Value| own(c).map(|r| (r.2 - r.0) * (r.3 - r.1)).unwrap_or(0.0);+        area(b).partial_cmp(&area(a)).unwrap()+    });+    let inside = grow(board, -0.2);+    for c in order {+        let rf = c["ref"].as_str().unwrap_or("").to_string();+        let bottom = c["side"] == "bottom";+        let Some(b) = own(c) else { unplaced.push(json!({"ref": rf, "why": "no body or pads to place it by"})); continue };+        if b.2 < board.0 || b.0 > board.2 || b.3 < board.1 || b.1 > board.3 {+            unplaced.push(json!({"ref": rf, "why": "the part is off the board: place it first (altium_move_parts)"}));+            continue;+        }+        // the label's size at the new height, from Altium's own box at the old one+        // Altium's box is the text plus half its stroke all round (a 1.0 mm designator measures 1.285 mm tall on the+        // Bluetooth Sentinel example): plan the text, check the box+        let old = f(&c["name"]["size"]);+        let turned = (f(&c["name"]["rotation"]).rem_euclid(180.0) - 90.0).abs() < 1.0;+        let (m, w) = match rect_of(&c["name"]["box"]) {+            Some(r) if old > 0.0 && r.2 > r.0 => {+                let (bw, bh) = if turned { (r.3 - r.1, r.2 - r.0) } else { (r.2 - r.0, r.3 - r.1) };+                let m = ((bh - old) / 2.0).clamp(0.0, 0.3);+                (m, (bw - 2.0 * m).max(old * 0.5) * size / old)+            }+            _ => (0.15, rf.len() as f64 * size * 0.8),+        };+        let free = |text: Rect| -> bool {+            let r = grow(text, m);+            r.0 >= inside.0 && r.1 >= inside.1 && r.2 <= inside.2 && r.3 <= inside.3+                && !pads.iter().any(|p| on_side(&p["layer"], bottom) && hit(r, grow(pad_rect(p), pad_clear)))+                && !bodies.iter().any(|(o, side, ob)| *o != rf && *side == bottom && hit(r, *ob))+                && !placed.iter().any(|(side, pr)| *side == bottom && hit(r, grow(*pr, 0.1)))+        };+        // the sizes to try: `size`, then down in 0.1 mm steps to `min_size`+        let mut found = None;+        let mut s = size;+        while found.is_none() && s >= min_size - 1e-9 {+            found = spots(b, w * s / size, s, gap, bottom).into_iter().find(|(r, _, _)| free(*r)).map(|(r, rot, at)| (r, rot, at, s));+            s -= 0.1;+        }+        match found {+            Some((r, rot, at, s)) => {+                placed.push((bottom, grow(r, m)));+                // the text's anchor: lower left upright; turned 90 its letters lie left of the anchor (lower right of the+                // box); mirrored on the bottom it is the text's right end+                let (ax, ay) = if rot == 90 { (r.2, r.1) } else if bottom { (r.2, r.1) } else { (r.0, r.1) };+                out.push(json!({"ref": rf, "x": r3(ax), "y": r3(ay), "size": r3(s), "rotation": rot, "side": if bottom { "bottom" } else { "top" }, "at": at}));+            }+            None => unplaced.push(json!({"ref": rf, "why": "no clear spot beside the part", "triedSizes": [size, min_size]})),+        }+    }+    (out, unplaced)+}++/// Places a w x h label could go round the part box b, nearest first: centred on each side, then slid along it, at+/// `gap` and then 3 x `gap`; turned 90 degrees beside the left and right sides (top side only: Altium mirrors bottom+/// text). Each is (box, rotation, where).+fn spots(b: Rect, w: f64, h: f64, gap: f64, bottom: bool) -> Vec<(Rect, i64, String)> {+    let mut v = Vec::new();+    let (cx, cy) = ((b.0 + b.2) / 2.0, (b.1 + b.3) / 2.0);+    for g in [gap, 3.0 * gap] {+        // slide offsets along a side: centre first, then outwards both ways in 0.5 mm steps+        let slide = |len: f64| -> Vec<f64> {+            let mut o = vec![0.0];+            let mut k = 0.5;+            while k <= len / 2.0 + 0.5 { o.push(-k); o.push(k); k += 0.5; }+            o+        };+        for d in slide(b.2 - b.0) {+            v.push(((cx - w / 2.0 + d, b.3 + g, cx + w / 2.0 + d, b.3 + g + h), 0, "above".to_string()));+            v.push(((cx - w / 2.0 + d, b.1 - g - h, cx + w / 2.0 + d, b.1 - g), 0, "below".to_string()));+        }+        for d in slide(b.3 - b.1) {+            v.push(((b.2 + g, cy - h / 2.0 + d, b.2 + g + w, cy + h / 2.0 + d), 0, "right".to_string()));+            v.push(((b.0 - g - w, cy - h / 2.0 + d, b.0 - g, cy + h / 2.0 + d), 0, "left".to_string()));+            if !bottom {+                v.push(((b.2 + g, cy - w / 2.0 + d, b.2 + g + h, cy + w / 2.0 + d), 90, "right, turned".to_string()));+                v.push(((b.0 - g - h, cy - w / 2.0 + d, b.0 - g, cy + w / 2.0 + d), 90, "left, turned".to_string()));+            }+        }+    }+    v+}++/// Designators whose box (Altium's own) still touches a pad, closer than `pad_clear`. Pure.+pub fn on_pads(comps: &[Value], pads: &[Value], pad_clear: f64) -> Vec<Value> {+    comps.iter().filter(|c| c["name"]["shown"].as_bool() != Some(false)).filter_map(|c| {+        let r = rect_of(&c["name"]["box"])?;+        let bottom = c["side"] == "bottom";+        let p = pads.iter().find(|p| on_side(&p["layer"], bottom) && hit(r, grow(pad_rect(p), pad_clear - 0.01)))?;+        Some(json!({"ref": c["ref"], "pad": format!("{}.{}", p["ref"].as_str().unwrap_or(""), p["name"].as_str().unwrap_or(""))}))+    }).collect()+}++/// altium_silk_designators {filePath?, size?, gap?, padClearance?, refs?, dryRun?}+pub fn silk_designators(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 num = |k: &str, d: f64| args.get(k).and_then(|v| v.as_f64()).unwrap_or(d);+    let (size, gap, clear) = (num("size", 1.0), num("gap", 0.2), num("padClearance", 0.15));+    if size < 0.5 { return json!({"success": false, "errorCode": "bad_args", "error": "size is the text height in mm, 0.5 or more (JLCPCB reads 1.0 mm and up reliably)"}); }+    let st = crate::routing::routing_state(&json!({}));+    if st.get("success").and_then(|b| b.as_bool()) != Some(true) { return st; }+    let Some(bb) = crate::fab::outline_bbox(&st) else { return json!({"success": false, "errorCode": "no_outline", "error": "the board has no outline"}) };+    let silk = crate::routing::silk_state(&json!({}));+    if silk.get("success").and_then(|b| b.as_bool()) != Some(true) { return silk; }+    let mut comps = silk["components"].as_array().cloned().unwrap_or_default();+    if let Some(want) = args.get("refs").and_then(|v| v.as_array()) {+        let w: Vec<&str> = want.iter().filter_map(|v| v.as_str()).collect();+        comps.retain(|c| c["ref"].as_str().map(|r| w.iter().any(|x| x.eq_ignore_ascii_case(r))).unwrap_or(false));+    }+    let pads = st["pads"].as_array().cloned().unwrap_or_default();+    let before = on_pads(&comps, &pads, clear);+    let min_size = num("minSize", size).min(size);+    // the labels of parts left out stay put; so do the labels of parts with no spot, so plan again round those+    let label = |c: &Value| -> Option<(bool, Rect)> { if c["name"]["shown"].as_bool() == Some(false) { None } else { rect_of(&c["name"]["box"]).map(|r| (c["side"] == "bottom", r)) } };+    let all = silk["components"].as_array().cloned().unwrap_or_default();+    let mut fixed: Vec<(bool, Rect)> = all.iter().filter(|c| !comps.iter().any(|k| k["ref"] == c["ref"])).filter_map(label).collect();+    let mut moving = comps.clone();+    let (mut names, mut unplaced) = (Vec::new(), Vec::new());+    // every round pins at least one more label, so this ends; the last round leaves nothing unpinned+    for _ in 0..=comps.len() {+        let (n, u) = plan(&moving, &pads, bb, size, min_size, gap, clear, &fixed);+        names = n;+        if u.is_empty() { break; }+        let stuck: Vec<Value> = u.iter().map(|x| x["ref"].clone()).collect();+        fixed.extend(moving.iter().filter(|c| stuck.contains(&c["ref"])).filter_map(label));+        moving.retain(|c| !stuck.contains(&c["ref"]));+        unplaced.extend(u);+    }+    if args.get("dryRun").and_then(|b| b.as_bool()) == Some(true) {+        return json!({"success": true, "dryRun": true, "planned": names, "unplaced": unplaced, "onPadsBefore": before});+    }+    if names.is_empty() {+        return json!({"success": before.is_empty(), "placed": 0, "unplaced": unplaced, "onPadsBefore": before, "onPadsAfter": before, "labelOverlapsAfter": [], "sizeMm": size,+            "_hint": "No designator could move to a clear spot at this size: see unplaced (try minSize, or move the parts)."});+    }+    let r = crate::routing::apply_silkscreen(&json!({"names": names}));+    let after_comps: Vec<Value> = r["after"]["components"].as_array().cloned().unwrap_or_default().into_iter()+        .filter(|c| names.iter().any(|n| n["ref"] == c["ref"])).collect();+    let after = on_pads(&after_comps, &pads, clear);+    // and label over label, with Altium's own boxes, among every shown designator+    let all_after = r["after"]["components"].as_array().cloned().unwrap_or_default();+    let boxes: Vec<(String, bool, Rect)> = all_after.iter().filter_map(|c| label(c).map(|(b, r)| (c["ref"].as_str().unwrap_or("").to_string(), b, r))).collect();+    let mut overlaps = Vec::new();+    for i in 0..boxes.len() { for j in i + 1..boxes.len() {+        if boxes[i].1 == boxes[j].1 && hit(boxes[i].2, boxes[j].2) && (names.iter().any(|n| n["ref"] == boxes[i].0) || names.iter().any(|n| n["ref"] == boxes[j].0)) {+            overlaps.push(json!([boxes[i].0, boxes[j].0]));+        }+    } }+    json!({"success": r["success"].as_bool() == Some(true) && after.is_empty() && overlaps.is_empty(), "placed": names.len(), "labelOverlapsAfter": overlaps, "applied": r["applied"], "failed": r["failed"],+        "unplaced": unplaced, "onPadsBefore": before, "onPadsAfter": after, "sizeMm": size,+        "_hint": "Every designator placed is upright, one size, beside its own part, clear of pads by padClearance and of other bodies and labels; onPadsAfter re-checks with Altium's own text boxes. unplaced parts had no clear spot: try a smaller size for them (refs), move the part, or place the label by hand (altium_apply_silkscreen). Then altium_silkscreen_prep and the silk DRC."})+}++#[cfg(test)]+mod tests {+    use super::*;++    fn comp(r: &str, body: [f64; 4]) -> Value {+        json!({"ref": r, "side": "top", "body": body, "name": {"text": r, "size": 1.0, "shown": true, "box": [0.0, 0.0, 2.0, 1.0]}})+    }++    #[test]+    fn labels_go_beside_their_part_clear_of_pads_and_each_other() {+        // C1 sits just above U1, where U1's label would go+        let comps = vec![comp("U1", [10.0, 10.0, 16.0, 16.0]), comp("C1", [12.0, 16.4, 14.0, 17.4])];+        let pads = vec![json!({"ref": "C1", "name": "1", "x": 12.5, "y": 16.9, "sizeX": 0.8, "sizeY": 0.8, "rotation": 0, "layer": "F.Cu"}),+                        json!({"ref": "C1", "name": "2", "x": 13.5, "y": 16.9, "sizeX": 0.8, "sizeY": 0.8, "rotation": 0, "layer": "F.Cu"})];+        let (out, un) = plan(&comps, &pads, (0.0, 0.0, 40.0, 40.0), 1.0, 1.0, 0.2, 0.15, &[]);+        assert!(un.is_empty());+        // U1 above would land on C1's body and pads: it goes below+        assert_eq!(out[0]["ref"], "U1");+        assert_eq!(out[0]["at"], "below");+        assert_eq!(out[1]["ref"], "C1");+        assert_eq!(out[1]["at"], "above");+        assert_eq!(out[1]["y"], 17.6);+        assert_eq!(out[0]["y"], 8.8);+    }++    #[test]+    fn a_part_boxed_in_is_reported_not_forced() {+        let comps = vec![comp("R1", [1.0, 1.0, 3.0, 2.0])];+        let (out, un) = plan(&comps, &[], (0.0, 0.0, 4.0, 3.0), 1.0, 1.0, 0.2, 0.15, &[]);+        assert!(out.is_empty());+        assert_eq!(un[0]["ref"], "R1");+        let on = on_pads(&[json!({"ref": "R1", "side": "top", "name": {"shown": true, "box": [0.0, 0.0, 2.0, 1.0]}})],+                         &[json!({"ref": "R1", "name": "1", "x": 1.0, "y": 0.5, "sizeX": 0.5, "sizeY": 0.5, "rotation": 0, "layer": "F.Cu"})], 0.15);+        assert_eq!(on.len(), 1);+    }+}
bridge-rs/src/verbs.rs+30−6
@@ -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", "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", "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",@@ -706,6 +706,27 @@ 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("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.",+            json!({"filePath": "the .PcbDoc (opened first; else the current board)", "projectPath": "the .PrjPcb - checks every purchased BOM line has an LCSC number (altium_bom)", "panelMm": "[w, h] when it ships in a panel (altium_panelize's panelMm)"}),+            json!({"service": "economic | standard | null", "economic": "{ok, rules:[{rule, ok, detail}]}", "standard": "{ok, rules}", "board": "{parts, bottomSideParts, finestPitch, smallestChip, tinyFootprints, fiducials, throughHoleParts}", "linesWithoutLcsc": "[..]"}), 300,+            "Fix what the rules mark false: panelize a small board (altium_panelize, then panelMm), add fiducials (altium_board_features), find LCSC numbers (adom-parts-search). Then altium_bom (JLCPCB BOM) and altium_export_manufacturing (pick and place), and check every part's rotation in JLCPCB's preview.",+            &["bom", "export_manufacturing", "panelize", "board_features", "fab_check"],+            &["Pitch is the closest pad centres within one part of 3 or more SMD pads; package size is read from footprint names and two-pad parts' pad spacing.", "Rotations are not checked: JLCPCB's preview is the authority on orientation."],+            json!({"projectPath": "C:/proj/Board.PrjPcb", "filePath": "C:/proj/Board.PcbDoc"})),+        verb_doc("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.",+            json!({"filePath": "the .PcbDoc (opened first; else the current board)", "nets": "[net] - the tracks to fence (e.g. [ANT_RF])", "edge": "bool - a fence round the board edge too", "viaNet": "the net the vias tie to (usually GND), required", "freqGHz": "the highest frequency: pitch = lambda/20 in FR-4", "pitchMm": "pitch, default 2 (a cap when freqGHz is given)", "offsetMm": "track centreline to via centre (default half the widest track + clearance + via radius + 0.1)", "edgeInsetMm": "edge fence: distance in from the edge (default via radius + 0.5)", "size": "via diameter mm, default 0.6", "drill": "mm, default 0.3", "clearance": "to other copper, mm, default 0.2", "dryRun": "bool - plan only", "expectedRevision": "optional"}),+            json!({"planned": "{vias, candidates, pitchMm, offsetMm, points}", "applied": "int", "failed": "int"}), 180,+            "Then altium_repour so the pours join the vias, and altium_run_drc. altium_return_path shows where a net still runs over a gap.",+            &["return_path", "board_features", "repour", "run_drc", "apply_pours"],+            &["Vias go through (top to bottom); a pour on viaNet should exist on the layers they join.", "Spots too close to other copper, pads or the edge are skipped, not forced."],+            json!({"nets": ["ANT_RF"], "edge": true, "viaNet": "GND", "freqGHz": 2.4})),+        verb_doc("silk_designators", "Place every reference designator the way assembly houses want: one size, upright, beside its own part, clear of every pad (JLCPCB: 0.15 mm), every other part's body and the other designators, inside the board; read back from Altium's own text boxes. Parts with no clear spot are reported, not forced onto pads.",+            json!({"filePath": "the .PcbDoc (opened first; else the current board)", "size": "text height mm, default 1.0 (JLCPCB's minimum)", "minSize": "mm - parts with no spot at size step down by 0.1 to this (default: size, no shrinking)", "gap": "label to part, mm, default 0.2", "padClearance": "label to any pad, mm, default 0.15", "refs": "[ref] - only these (default every part)", "dryRun": "bool - plan only"}),+            json!({"placed": "int", "unplaced": "[{ref, why}]", "onPadsBefore": "[{ref, pad}]", "onPadsAfter": "[{ref, pad}] - must be empty", "planned": "dryRun: [{ref, x, y, size, rotation, side, at}]"}), 600,+            "Then altium_silkscreen_prep (it clips silk off the mask) and altium_fab_check {fab:\"jlcpcb\"} for text height and line width. For unplaced parts try refs with a smaller size, or move the part.",+            &["silk_state", "apply_silkscreen", "silkscreen_prep", "fab_check"],+            &["Labels are tried above, below, right, left and at the corners of the part's body and pads, big parts first.", "Bottom-side labels are mirrored by Altium; onPadsAfter checks them with Altium's own boxes."],+            json!({"size": 1.0})),         verb_doc("copper_balance", "How much of each copper layer is copper (tracks, pads, vias and what Altium actually poured, inside the outline; a plane counts full), and how far apart each mirrored pair of layers is: the copper balance a fab asks about because an unbalanced stack bows and twists in reflow.",             json!({"filePath": "the .PcbDoc (opened first; else the current board)", "resolutionMm": "raster cell, default 0.1"}),             json!({"boardMm2": "number", "layers": "[{layer, copperMm2, percent, plane?}]", "pairs": "[{layers, percent, differencePoints, ok}] - layer 1 with n, 2 with n-1...", "balanced": "bool", "poursWithoutRegions": "[{net, layer}] - pours not poured, or hatched from tracks (counted through their tracks)"}), 180,@@ -746,15 +767,15 @@ fn describe() -> Value {             json!({"panelPath": "path", "boardMm": "[w, h] of one board's outline", "panelMm": "[w, h]", "boardsAt": "[[x, y]] each board's outline corner from the panel's corner", "separation": "{kind, cutsX, cutsY | tabs, holes, routLines, applied, failed}", "jlcpcb": "{rules:[{rule, ok (true|false|null = a note), detail}], fits}", "nearestCopperToEdge": "{mm, at}", "warnings": "[{copperOutsideOutline}]", "project": "{path, added}", "saved": "bool"}), 240,             "Fix what jlcpcb.rules marks false (panel under 70 mm: more rows or wider rails; copper under 0.4 mm from a cut; rounded corners on a V-cut) and run it again with overwrite:true. Then altium_export_manufacturing {projectPath, pcbPath: the panel}.",             &["fab_check", "export_manufacturing", "board_features", "set_outline"],-            &["Opens the board, then creates and saves the panel: the panel ends as the current document.", "tabs refuses a board that draws its own outline on a mechanical layer: every copy brings it along closed and a router would cut each board free.", "JLCPCB's rules as published (V-cut standards and mouse-bite guide, read 2026-10-23): V-cut panels 70 to 475 mm, 0.6 mm boards or thicker, copper 0.4 mm (1.0 recommended) from a cut, at most 25 cuts a side; mouse bites 0.6 mm holes 5 to a set, gaps of 1.2 mm or more."],+            &["Opens the board, then creates and saves the panel; without projectPath the saved panel is closed (open it with altium_open_document).", "tabs refuses a board that draws its own outline on a mechanical layer: every copy brings it along closed and a router would cut each board free.", "JLCPCB's rules as published (V-cut standards and mouse-bite guide, read 2026-10-23): V-cut panels 70 to 475 mm, 0.6 mm boards or thicker, copper 0.4 mm (1.0 recommended) from a cut, at most 25 cuts a side; mouse bites 0.6 mm holes 5 to a set, gaps of 1.2 mm or more."],             json!({"pcbPath": "C:/proj/Board.PcbDoc", "panelPath": "C:/proj/Panel.PcbDoc", "rows": 3, "cols": 3, "separation": "vscore", "railMm": 5, "projectPath": "C:/proj/Board.PrjPcb"})),         verb_doc("fab_check", "Before ordering: the board's fab-relevant minimums measured from the live board (narrowest track, smallest via drill, diameter and annular ring, smallest pad hole and ring, smallest SMD pad, clearance rule, copper layers, board size), each with where it is; with a fab's limits, which ones fall short.",-            json!({"filePath": "the .PcbDoc (opened first)", "limits": "{minTrack, minClearance, minViaDrill, minViaDiameter, minViaAnnularRing, minPadHole, minPadAnnularRing, minSmdPad, maxLayers, maxBoardMm:[w,h]} in mm - from the fab's capability page; omit to measure only"}),-            json!({"measured": "{track, viaDrill, viaDiameter, viaAnnularRing, padHole, padAnnularRing, smdPad: {mm, at}, clearanceRule, copperLayers, boardSize, counts}", "outsideLimits": "[{limit, limitMm, boardMm, at}]", "fits": "bool | null"}), 180,+            json!({"filePath": "the .PcbDoc (opened first)", "fab": "jlcpcb - JLCPCB's published standard capabilities for this board's layer count and copper weight (source and date in the reply)", "copperOz": "outer copper weight for the preset (default: read from the stack)", "limits": "{minTrack, minClearance, minViaDrill, minViaDiameter, minViaAnnularRing, minPadHole, minPadAnnularRing, minSmdPad, minEdgeClearance, minHoleToHoleVia, minHoleToHolePad, maxDrill, minSilkLine, minSilkText, maxLayers, minBoardMm:[w,h], maxBoardMm:[w,h]} in mm - any fab's numbers; with fab, these override the preset"}),+            json!({"fab": "{name, service, copperOz, source, read, notes} | null", "measured": "{track, viaDrill, viaDiameter, viaAnnularRing, padHole, padAnnularRing, smdPad, edgeClearance, holeToHoleVia, holeToHolePad, largestDrill, silkText, silkLine: {mm, at}, clearanceRule, copperLayers, boardSize, counts}", "outsideLimits": "[{limit, limitMm, boardMm, at}]", "fits": "bool | null", "costlierOrBelowRecommended": "[{feature, boardMm, note}]"}), 180,             "Look up the fab's own limits (its capability page) and pass them: the bridge does not carry fab numbers, they change. The measured values are what a fab's order form asks for.",             &["routing_state", "read_rules", "layer_stack", "export_manufacturing", "run_drc"],             &["Measures the board as it is now, from the live document: routed copper, vias and pads.", "Board size is the outline's bounding box."],-            json!({"limits": {"minTrack": 0.127, "minClearance": 0.127, "minViaDrill": 0.3, "minViaDiameter": 0.5, "maxLayers": 2}})),+            json!({"fab": "jlcpcb"})),         verb_doc("read_sheet_file", "Read a schematic sheet straight from its .SchDoc file, without Altium (it need not be installed or running): every part with its designator, library reference, comment, UniqueID, part number, position, parameters and pins, in milliseconds.",             json!({"path": "the .SchDoc (alias filePath)", "pins": "bool, default true - each part's own pins plus the shared part 0", "params": "bool, default false - every parameter with its value"}),             json!({"components": "[{designator, libReference, comment, description, uniqueId, partId, partCount, xMil, yMil, orientation, sourceLibrary, params?, pins?}]", "count": "int", "format": "the file header", "elapsedMs": "int"}), 30,@@ -1533,7 +1554,7 @@ pub fn dispatch(command: &str, args: &Value, _forwarded: &[(String, String)]) ->             if let Some(g) = need_licensed() { return g; }             match s(args, "path") {                 None => json!({"success": false, "error": "path is required (absolute path of the open document to close; never saves - altium_save first if anything is worth keeping)"}),-                Some(p) => agent::call("close_document", &[("path", p)], None, Duration::from_secs(30)),+                Some(p) => agent::call("close_document", &[("path", p.replace('/', "\\"))], None, Duration::from_secs(30)),             }         }         "activate_document" => surfaces::activate_document(args),@@ -1739,6 +1760,9 @@ pub fn dispatch(command: &str, args: &Value, _forwarded: &[(String, String)]) ->         "height_check" => crate::bodies::height_check(args),         "copper_balance" => crate::coppermap::copper_balance(args),         "return_path" => crate::coppermap::return_path(args),+        "silk_designators" => crate::silkplace::silk_designators(args),+        "via_fence" => crate::features::via_fence(args),+        "assembly_check" => crate::assembly::assembly_check(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+13−2
@@ -310,8 +310,9 @@ def matrix(w):     # 0.2.71: the sheet read from its file (no Altium), the fab minimums, impedance and current from the stack-up, and     # a 1 x 2 panel of the lane board (overwrite: the panel of the last run is still there)     M["read_sheet_file"] = dict(phase=3.5, **ok(path=LS), check=lambda d: any(c.get("designator") == "U1" for c in d.get("components") or []))-    M["fab_check"] = dict(phase=3.5, timeout=200, **ok(filePath=LB, limits={"minTrack": 0.1, "maxLayers": 2}),-                          check=lambda d: ((d.get("measured") or {}).get("boardSize") or {}).get("mm") == [40.0, 20.0] and d.get("fits") is True)+    M["fab_check"] = dict(phase=3.5, timeout=300, **ok(filePath=LB, fab="jlcpcb"),+                          check=lambda d: ((d.get("measured") or {}).get("boardSize") or {}).get("mm") == [40.0, 20.0] and (d.get("fab") or {}).get("name") == "JLCPCB"+                                          and "minEdgeClearance" in (d.get("limitsChecked") or []) and isinstance(d.get("fits"), bool))     M["impedance"] = dict(phase=3.5, timeout=150, **ok(filePath=LB, z0=50, diff=90),                           check=lambda d: len(d.get("layers") or []) == 2 and 0.3 < ((d.get("layers") or [{}])[0].get("width") or 0) < 1.0                                           and abs(((d.get("layers") or [{}])[0].get("zdiff") or 0) - 90) < 1)@@ -333,6 +334,14 @@ def matrix(w):                                check=lambda d: len(d.get("layers") or []) == 2 and abs((d.get("boardMm2") or 0) - 799.1) < 3 and len(d.get("pairs") or []) == 1)     M["return_path"] = dict(phase=3.5, timeout=260, **ok(filePath=LB),                             check=lambda d: isinstance(d.get("nets"), list) and isinstance(d.get("layersWithNoReferenceCopper"), list))+    # 0.2.73: JLCPCB's limits built in; designators placed clear of pads, read back from Altium's own text boxes+    M["silk_designators"] = dict(phase=3.5, timeout=650, **ok(filePath=LB, minSize=0.8),+                                 check=lambda d: d.get("onPadsAfter") == [] and d.get("labelOverlapsAfter") == [] and (d.get("failed") or 0) == 0)+    M["via_fence"] = dict(phase=3.5, timeout=300, **ok(filePath=LB, nets=["N1"], edge=True, viaNet="GND", pitchMm=3, dryRun=True),+                          check=lambda d: ((d.get("planned") or {}).get("vias") or 0) > 0)+    M["assembly_check"] = dict(phase=3.5, timeout=450, **ok(filePath=LB, projectPath=LP),+                               check=lambda d: d.get("service") in (None, "economic", "standard") and len((d.get("economic") or {}).get("rules") or []) >= 6+                                               and len((d.get("standard") or {}).get("rules") or []) >= 5)     # 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 []))@@ -485,6 +494,8 @@ def main():         elif why:             outcome = "PASS" if spec["expect"] in ("refuse", "any") else "FAIL"             detail = ("refused: " if outcome == "PASS" else "unexpected failure: ") + str(why)[:150]+            if outcome == "FAIL" and d.get("error") and str(d.get("error")) not in detail:+                detail += " | " + str(d.get("error"))[:300]  # the names a refusal carries (which documents, which part)         else:             outcome, detail = "FAIL", "success:false with NO reason (no errorCode, no error text)"         # nothing may be left on the user's screen
package.json+10−2
@@ -1,6 +1,6 @@ {   "slug": "altium-bridge",-  "version": "0.2.72",+  "version": "0.2.73",   "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": [@@ -181,7 +181,15 @@     "altium 3d clearance check",     "altium copper balance",     "altium return path check",-    "signal crossing a split plane altium"+    "signal crossing a split plane altium",+    "jlcpcb design rule check altium",+    "check my altium board against jlcpcb capabilities",+    "jlcpcb assembly check",+    "is my board ready for jlcpcb assembly",+    "altium place reference designators",+    "designators overlapping pads altium",+    "altium via fence",+    "via stitching along rf trace"   ],   "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+10−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.72",+  "version": "0.2.73",   "hero": {     "type": "image",     "path": "screenshots/hero.png"@@ -173,7 +173,15 @@     "altium 3d clearance check",     "altium copper balance",     "altium return path check",-    "signal crossing a split plane altium"+    "signal crossing a split plane altium",+    "jlcpcb design rule check altium",+    "check my altium board against jlcpcb capabilities",+    "jlcpcb assembly check",+    "is my board ready for jlcpcb assembly",+    "altium place reference designators",+    "designators overlapping pads altium",+    "altium via fence",+    "via stitching along rf trace"   ],   "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+25−1
@@ -5,7 +5,8 @@ description: >-   diff pairs, track widths, mounting holes, fiducials, stitching vias, free space, footprint swaps,   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, or panelize a board.+  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. ---  Parent skill: **altium-bridge**@@ -339,6 +340,29 @@ altium_return_path '{"nets":["USB_DP","USB_DN","CLK"]}'  # signal track over no   neighbouring layer (pours, planes, the reference nets' copper), with where the first gap starts. On the Sentinel   example it found the antenna trace ANT_RF (no ground under it by design) and parts of VBAT over gaps. +## Designators placed for assembly, and via fences (0.2.73)++```bash+altium_silk_designators '{"size":1.0,"minSize":0.8}'                                   # every designator clear of pads+altium_via_fence '{"nets":["ANT_RF"],"edge":true,"viaNet":"GND","freqGHz":2.4}'          # ground vias along RF and the edge+```++- `silk_designators` puts every reference designator upright at one size beside its own part, clear of every pad by+  `padClearance` (0.15 mm, JLCPCB's silk-to-pad), every other part's body and every other label, inside the board.+  Big parts first; spots above, below, left and right (slid along each side, near then farther, turned 90 degrees on+  the sides); `minSize` lets the hard ones step down 0.1 mm at a time. Labels that find no spot stay where they were and+  are listed in `unplaced`, and the rest are planned round them. `onPadsAfter` and `labelOverlapsAfter` re-check with+  Altium's own text boxes (a box is the text plus half its stroke all round: a 1.0 mm label measures 1.285 mm).+  Measured on the Bluetooth Sentinel example: 41 of 60 moved, none on a pad or another label (7 sat on pads before).+- `via_fence` lines ground vias along both sides of the named nets' tracks (offset from the widest track) and, with+  `edge`, round the board edge, at lambda/20 of `freqGHz` in FR-4 (3.4 mm at 2.4 GHz) or `pitchMm`. The via is the board's+  own Routing Via rule's preferred size, and every via keeps `clearance` from other copper and pads, the board edge and+  the net's other vias; spots that do not fit are skipped. Repour, then `altium_routing_drc {full:true}`: on the+  Sentinel example 26 vias round VBAT and the edge left Altium's full DRC at 0 violations.+- Pads with a custom shape (copper drawn as regions in the footprint) have no size in Altium's API; routing_state now+  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).+ ## Lengths, length rules, rooms and teardrops (0.2.68)  ```bash
skills/altium-outputs/SKILL.md+19
@@ -68,6 +68,25 @@ 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. +## Ready for JLCPCB: fab limits and assembly (0.2.73)++```bash+altium_fab_check '{"fab":"jlcpcb"}'                                              # JLCPCB's published PCB limits+altium_assembly_check '{"projectPath":"C:\\work\\Board.PrjPcb"}'              # Economic or Standard PCBA?+```++- `fab_check {fab:"jlcpcb"}` checks the board against JLCPCB's standard rigid-board capabilities for its layer count and+  copper weight (read from the stack): track and space, via drill and diameter, PTH hole and ring, hole to hole (via 0.2,+  pad 0.45), copper to the board edge (0.2, measured to the real outline), largest drill (6.3), silkscreen line (0.15)+  and text height (1.0), board size. `costlierOrBelowRecommended` names what passes only on a costlier option (via holes+  under 0.3 mm) or under JLCPCB's recommended ring. The reply names the source page and the date it was read; `limits`+  still overrides any value or checks another fab. Measured: the lane board fits; the Bluetooth Sentinel example misses+  on 0.7 mm designators, 0.127 mm silk lines and a hatched pour 0.148 mm from its curved edge.+- `assembly_check` checks JLCPCB's PCBA tiers as published: Economic (board 10 x 10 to 470 x 500 mm, 0.8 to 1.6 mm thick,+  2/4/6 layers, one side, 0402 and 0.4 mm pitch) and Standard (70 x 70 mm, or a panel up to 250 x 250 mm, both sides, 01005+  and 0.35 mm pitch, fiducials and rails), plus every purchased BOM line's LCSC number (`projectPath`). `service` is the+  cheapest tier that passes. Part rotation is not guessed: check it in JLCPCB's placement preview.+ ## Assembly and fabrication drawings (0.2.70)  `altium_export_pdf {projectPath, assembly: true, fabrication: true}` adds Altium's own Assembly Drawings output (top and
src/BRIDGE_VERSION+1−1
@@ -1 +1 @@-0.2.72+0.2.73
src/agent/AdomAgent.pas.tmpl+32−4
@@ -470,7 +470,9 @@ End; Function CmdCloseDocument(Lines : TStringList) : String; Var     Path : String;-    Doc  : IServerDocument;+    Doc, D : IServerDocument;+    SM   : IServerModule;+    I, J : Integer; Begin     Path := Param(Lines, 'path');     Doc := Nil;@@ -478,6 +480,21 @@ Begin         Doc := Client.GetDocumentByPath(Path);     Except     End;+    { a document made in memory and saved under a name afterwards (altium_panelize's panel) is not found by path on+      Develop (2026-10-26): walk every server's documents by file name (the bridge sends backslashes) }+    If Doc = Nil Then+    Begin+        For I := 0 To Client.Count - 1 Do+        Begin+            SM := Client.ServerModule[I];+            If SM = Nil Then Continue;+            For J := 0 To SM.DocumentCount - 1 Do+            Begin+                D := SM.Documents[J];+                If (D <> Nil) And (UpperCase(D.FileName) = UpperCase(Path)) Then Doc := D;+            End;+        End;+    End;     If Doc = Nil Then     Begin         Result := '{' + JRaw('ok', 'true') + ',' + JRaw('closed', 'false') + ',' + JStr('note', 'not open: ' + Path) + '}';@@ -5866,6 +5883,8 @@ Var     LT, LA, LV, LP, LC, LG, LO : TStringList;     Own, Pts : String;     K, Unrouted : Integer;+    PR    : TCoordRect;+    PX, PY, PW, PH, PRot, PS : Integer; Begin     Board := PCBServer.GetCurrentPCBBoard;     If Board = Nil Then Begin Result := '{' + JRaw('ok','false') + ',' + JStr('error','no current PCB board (open a .PcbDoc first)') + '}'; Exit; End;@@ -5905,9 +5924,18 @@ Begin             Pad := Prim;             Own := '';             If Pad.Component <> Nil Then Own := Pad.Component.Name.Text;-            LP.Add('["' + JsonEsc(Own) + '","' + JsonEsc(Pad.Name) + '",' + IntToStr(Pad.x) + ',' + IntToStr(Pad.y) + ',' +-                IntToStr(Pad.TopXSize) + ',' + IntToStr(Pad.TopYSize) + ',' + IntToStr(Round(Pad.Rotation * 1000)) + ',' +-                IntToStr(Pad.Layer) + ',' + IntToStr(Pad.HoleSize) + ',' + NetOf(Pad) + ',' + IntToStr(Pad.TopShape) + ']');+            PX := Pad.x; PY := Pad.y; PW := Pad.TopXSize; PH := Pad.TopYSize; PRot := Round(Pad.Rotation * 1000); PS := Pad.TopShape;+            If (PW = 0) Or (PH = 0) Then+            Begin+                { a custom-shape pad has no size: its copper is its bounding rectangle (the Bluetooth Sentinel coin cell+                  holder's 5 mm contacts read 0 x 0, and a via fence put a via on one, 2026-10-23) }+                PR := Pad.BoundingRectangle;+                PX := (PR.Left + PR.Right) Div 2; PY := (PR.Bottom + PR.Top) Div 2;+                PW := PR.Right - PR.Left; PH := PR.Top - PR.Bottom; PRot := 0; PS := eRectangular;+            End;+            LP.Add('["' + JsonEsc(Own) + '","' + JsonEsc(Pad.Name) + '",' + IntToStr(PX) + ',' + IntToStr(PY) + ',' ++                IntToStr(PW) + ',' + IntToStr(PH) + ',' + IntToStr(PRot) + ',' ++                IntToStr(Pad.Layer) + ',' + IntToStr(Pad.HoleSize) + ',' + NetOf(Pad) + ',' + IntToStr(PS) + ']');         End         Else If Prim.ObjectId = eComponentObject Then         Begin
src/bridge.json+7−1
@@ -2,7 +2,7 @@   "manifest_version": 1,   "name": "altium",   "displayName": "Altium Designer",-  "version": "0.2.72",+  "version": "0.2.73",   "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",@@ -102,6 +102,9 @@     "altium_height_check",     "altium_copper_balance",     "altium_return_path",+    "altium_silk_designators",+    "altium_via_fence",+    "altium_assembly_check",     "altium_find_space",     "altium_find_symbol",     "altium_footprint_primitives",@@ -225,6 +228,9 @@       "height_check": 150,       "copper_balance": 240,       "return_path": 240,+      "silk_designators": 600,+      "via_fence": 240,+      "assembly_check": 400,       "agent_start": 120,       "run_outjob": 600,       "silk_state": 180,