← Commit history
CHANGELOG.md+23
@@ -1,5 +1,28 @@ # Changelog +## 0.2.123++- **Slots and unplated holes in footprints built from KiCad** (#45, #49). `tools/kicad2altium.py` reads an oval drill (`(drill oval 0.6 1.7)`) as a slot and a KiCad `np_thru_hole` as unplated. `altium_build_footprint` makes them: `Pad.HoleType` slot with its width, length and rotation, and `Plated` off.+  - The spec's PAD line gains `plated`, `slot` and `slotrot` (older specs read as before).+  - Tested with the USB4105 USB-C receptacle: the 4 shield slots come through as plated slots and the 2 locating pegs as unplated holes. The NC drill files carry them (`-SlotHoles.TXT`, `;TYPE=NON_PLATED`).+- **`altium_export_manufacturing` checks that the outline Gerbers hold the board's shape** (#46).+  - The check reads GM1 and GKO themselves, chains their draws into closed loops and compares each loop's size with the board's (within 0.1 mm).+  - Two mounting-hole circles on Mechanical 1 used to pass as an outline.+  - When the shape is missing, the bridge draws it on Mechanical 1 beside what the layer already holds and generates again.+  - Each file's `note` says what it found. If the shape is still missing, the reply is `success:false`, `errorCode: no_board_outline`.+- **Changing the board outline refits the Default Layer Stack Region** (#47). `altium_board_shape`, `altium_set_outline`, `altium_build_board` and `altium_test_board` now refit it to the new outline. The 3D view and the layer stack draw from that region, and it kept the old size.+  - A region that did not match the old outline is the user's own and is left alone.+  - The reply's `stackRegions` gives `found`, `refit` and `leftAlone`.+  - Tested: 20.64 x 18.08 mm to 40 x 30 mm.+- **`altium_eval` runs scripts up to 16 KB** (#48). A script over 1,000 bytes, which failed on Altium's command line (a script error at 3.4 KB), is now run by the agent. The reply's `lane` and `laneReason` say which ran it.+  - Past 16 KB the reply is `script_too_long` before anything runs, because 32 KB timed out in Altium's script engine.+- **Symbols with several display modes are wired once** (#50). A placed part carries the pins of every part and every display mode.+  - `altium_build_schematic`, `altium_sch_connect` and `altium_sch_place_part`'s pin count now read only the pins the part shows: its current part and display mode, plus the pins shared by all parts.+  - A symbol with an alternate mode used to get every net label twice, stacked on the same spot.+  - `altium_sch_items` gains `stacked`: objects lying exactly on top of each other.+  - Tested: a 9-pin symbol with two modes got 9 labels, nothing stacked, and its netlist matched.+- Tested on Altium Designer 26.11.1.+ ## 0.2.122  - **`altium_add_dimensions {replace: true}`** removes the footprint's existing dimensions first, so a rerun after a re-import no longer stacks duplicates. With `dimensions: []` it only removes them.
SKILL.md+1−1
@@ -168,7 +168,7 @@ adom-bridge --ai-thread "board review" altium_export_gerber '{"outjobPath":"C:/d ## DelphiScript facts you need for `altium_eval`  - `[Var …;] Begin … End;` — a `Var` block is allowed (verified on AD 26.11.1, both lanes, 2026-10-22). Single quotes only. Use `altium_run_script` with a `.PrjScr` for real units, only when the agent is stopped.-- While the resident agent runs, `altium_eval` hands the text to RunScriptText from inside the agent and Altium ignores the nested script (measured on AD 26.11.1: `success:true`, nothing ran). Stop the agent first, or use a structured verb.+- **Size (0.2.123, #48):** up to 1,000 bytes runs on Altium's command line when the agent is stopped; a longer script, or any script while the agent runs, goes through the agent (`lane`, `laneReason`), which runs up to 16 KB. Past 16 KB the reply is `script_too_long` before anything runs (32 KB timed out in Altium's script engine). Put bulk data in a file the script reads instead. - Single quotes for strings; no double quotes anywhere in the text. - Unknown identifiers fail at **runtime** with an `Error` modal and a halted engine → `altium_agent_recover`. - To get data OUT, write a file from the script and read it back; `altium_run_command` / the structured verbs already do this for the common cases.
bridge-rs/src/gerberoutline.rsadded+161
@@ -0,0 +1,161 @@+//! The board outline as a fab reads it from an outline Gerber (GM1, GKO): the draws chained into closed loops, each with+//! its size, so a check can ask whether one of them IS the board shape. Counting draws passed a GM1 that held only two+//! mounting-hole circles and no outline (#46).+use serde_json::{json, Value};++type P = (f64, f64);++/// One draw: a line, or an arc flattened into points; `ends` are its start and end.+#[derive(Debug, Clone)]+pub struct Draw { pub pts: Vec<P>, pub start: P, pub end: P }++/// The draws (D01) of a Gerber file, in mm. Format, units, G01/G02/G03 (multi-quadrant, I/J from the start point),+/// modal coordinates. Flashes (D03) are not edges and are counted apart.+pub fn draws(text: &str) -> (Vec<Draw>, usize) {+    let mut dec_x = 4u32; let mut dec_y = 4u32;+    let mut scale = 1.0; // mm per unit+    let mut cur: P = (0.0, 0.0);+    let mut mode = 1; // 1 line, 2 clockwise, 3 counter-clockwise+    let mut out = Vec::new();+    let mut flashes = 0;+    for raw in text.split('*') {+        // a block keeps the % and line breaks around it ("%\n%MOIN"): both go+        let b = raw.trim_matches(|c: char| c == '%' || c.is_whitespace());+        if b.is_empty() { continue; }+        if let Some(fs) = b.strip_prefix("FS") {+            // FSLAX46Y46: the second digit of each pair is the decimals+            if let Some(i) = fs.find('X') { dec_x = fs[i + 2..i + 3].parse().unwrap_or(4); }+            if let Some(i) = fs.find('Y') { dec_y = fs[i + 2..i + 3].parse().unwrap_or(4); }+            continue;+        }+        if b.starts_with("MOMM") { scale = 1.0; continue; }+        if b.starts_with("MOIN") { scale = 25.4; continue; }+        if b.starts_with('%') || b.starts_with("AD") || b.starts_with("AM") || b.starts_with("LP") || b.starts_with("TF") || b.starts_with("TA") || b.starts_with("TO") || b.starts_with("TD") { continue; }+        let mut s = b;+        // G codes at the start of the block set the mode+        while let Some(rest) = s.strip_prefix('G') {+            let n: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect();+            match n.as_str() { "01" | "1" => mode = 1, "02" | "2" => mode = 2, "03" | "3" => mode = 3, _ => {} }+            s = &rest[n.len()..];+        }+        if !(s.contains('X') || s.contains('Y') || s.contains('D')) { continue; }+        let field = |k: char| -> Option<f64> {+            let i = s.find(k)?;+            let v: String = s[i + 1..].chars().take_while(|c| c.is_ascii_digit() || *c == '-' || *c == '+').collect();+            v.parse::<f64>().ok()+        };+        let d: Option<u32> = s.find('D').and_then(|i| s[i + 1..].chars().take_while(|c| c.is_ascii_digit()).collect::<String>().parse().ok());+        let x = field('X').map(|v| v / 10f64.powi(dec_x as i32) * scale).unwrap_or(cur.0);+        let y = field('Y').map(|v| v / 10f64.powi(dec_y as i32) * scale).unwrap_or(cur.1);+        let to = (x, y);+        match d {+            Some(1) => {+                let pts = if mode == 1 { vec![cur, to] } else {+                    let i = field('I').map(|v| v / 10f64.powi(dec_x as i32) * scale).unwrap_or(0.0);+                    let j = field('J').map(|v| v / 10f64.powi(dec_y as i32) * scale).unwrap_or(0.0);+                    arc(cur, to, (cur.0 + i, cur.1 + j), mode == 3)+                };+                out.push(Draw { pts, start: cur, end: to });+                cur = to;+            }+            Some(2) => cur = to,+            Some(3) => { flashes += 1; cur = to; }+            _ => cur = to,+        }+    }+    (out, flashes)+}++/// An arc from `a` to `b` about `c`, counter-clockwise when `ccw`, as points within 1 um of the curve; a full circle+/// when a and b meet.+fn arc(a: P, b: P, c: P, ccw: bool) -> Vec<P> {+    let r = ((a.0 - c.0).powi(2) + (a.1 - c.1).powi(2)).sqrt();+    let a0 = (a.1 - c.1).atan2(a.0 - c.0);+    let a1 = (b.1 - c.1).atan2(b.0 - c.0);+    let tau = std::f64::consts::TAU;+    let mut sweep = if ccw { a1 - a0 } else { a0 - a1 };+    while sweep <= 1e-9 { sweep += tau; }+    let step = if r > 0.0 { 2.0 * (1.0 - 0.001 / r).clamp(-1.0, 1.0).acos() } else { tau };+    let n = ((sweep / step.max(0.01)).ceil() as usize).clamp(1, 720);+    (0..=n).map(|k| { let t = a0 + if ccw { 1.0 } else { -1.0 } * sweep * k as f64 / n as f64; (c.0 + r * t.cos(), c.1 + r * t.sin()) }).collect()+}++/// The closed loops the draws make (ends within `tol` mm chained; every corner of a loop shared by exactly two draws),+/// each as [width, height, draws] in mm, plus the draws that close nothing.+pub fn loops(ds: &[Draw], tol: f64) -> (Vec<(f64, f64, usize)>, usize) {+    let key = |p: P| ((p.0 / tol).round() as i64, (p.1 / tol).round() as i64);+    let near = |a: P, b: P| (a.0 - b.0).abs() <= tol && (a.1 - b.1).abs() <= tol;+    let n = ds.len();+    let mut parent: Vec<usize> = (0..n).collect();+    fn find(p: &mut Vec<usize>, x: usize) -> usize { let mut r = x; while p[r] != r { r = p[r]; } let mut y = x; while p[y] != r { let z = p[y]; p[y] = r; y = z; } r }+    for i in 0..n { for j in i + 1..n {+        let (a, b) = (&ds[i], &ds[j]);+        if near(a.start, b.start) || near(a.start, b.end) || near(a.end, b.start) || near(a.end, b.end) { let (x, y) = (find(&mut parent, i), find(&mut parent, j)); parent[x] = y; }+    } }+    let mut groups: std::collections::BTreeMap<usize, Vec<usize>> = Default::default();+    for i in 0..n { let r = find(&mut parent, i); groups.entry(r).or_default().push(i); }+    let mut out = Vec::new();+    let mut open = 0;+    for (_, g) in groups {+        let mut deg: std::collections::HashMap<(i64, i64), usize> = Default::default();+        for &i in &g { *deg.entry(key(ds[i].start)).or_default() += 1; *deg.entry(key(ds[i].end)).or_default() += 1; }+        let single_circle = g.len() == 1 && near(ds[g[0]].start, ds[g[0]].end) && ds[g[0]].pts.len() > 2;+        let closed = single_circle || (g.len() >= 2 && deg.values().all(|d| d % 2 == 0));+        if !closed { open += g.len(); continue; }+        let pts = g.iter().flat_map(|&i| ds[i].pts.iter().copied());+        let (mut x0, mut y0, mut x1, mut y1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);+        for p in pts { x0 = x0.min(p.0); y0 = y0.min(p.1); x1 = x1.max(p.0); y1 = y1.max(p.1); }+        out.push((x1 - x0, y1 - y0, g.len()));+    }+    (out, open)+}++/// What one outline Gerber holds, and whether a loop in it is the board shape (`board`: width, height in mm, within+/// `tol` mm).+pub fn read(text: &str, board: Option<(f64, f64)>, tol: f64) -> Value {+    let (ds, flashes) = draws(text);+    let (ls, open) = loops(&ds, 0.01);+    let r3 = |v: f64| (v * 1000.0).round() / 1000.0;+    let matches = board.map(|(w, h)| ls.iter().any(|l| (l.0 - w).abs() <= tol && (l.1 - h).abs() <= tol));+    json!({"draws": ds.len(), "flashes": flashes, "closedLoops": ls.iter().map(|l| json!({"widthMm": r3(l.0), "heightMm": r3(l.1), "draws": l.2})).collect::<Vec<_>>(),+        "openDraws": open, "boardShape": matches})+}++#[cfg(test)]+mod tests {+    use super::*;++    const HEAD: &str = "%FSLAX46Y46*%\n%MOMM*%\n%ADD10C,0.254*%\nD10*\n";++    #[test]+    fn a_rectangle_is_the_board_shape() {+        let t = format!("{HEAD}X0Y0D02*\nX50000000Y0D01*\nX50000000Y30000000D01*\nX0Y30000000D01*\nX0Y0D01*\nM02*\n");+        let r = read(&t, Some((50.0, 30.0)), 0.1);+        assert_eq!(r["draws"], 4);+        assert_eq!(r["closedLoops"][0]["widthMm"], json!(50.0));+        assert_eq!(r["boardShape"], json!(true));+        assert_eq!(read(&t, Some((60.0, 30.0)), 0.1)["boardShape"], json!(false), "another board's size");+    }++    #[test]+    fn two_hole_circles_are_not_an_outline() {+        // #46: Mechanical 1 held two mounting-hole circles and nothing else+        let t = format!("{HEAD}G75*\nX5000000Y3000000D02*\nG03X5000000Y3000000I-1600000J0D01*\nX45000000Y3000000D02*\nG03X45000000Y3000000I-1600000J0D01*\nM02*\n");+        let r = read(&t, Some((50.0, 30.0)), 0.1);+        assert_eq!(r["closedLoops"].as_array().unwrap().len(), 2, "{r}");+        assert!((r["closedLoops"][0]["widthMm"].as_f64().unwrap() - 3.2).abs() < 0.01, "{r}");+        assert_eq!(r["boardShape"], json!(false));+    }++    #[test]+    fn rounded_corners_and_inches() {+        // a 2 x 1 inch board with one rounded corner (arc), in inches with 5 decimals+        let t = "%FSLAX25Y25*%\n%MOIN*%\nG01*\nX0Y0D02*\nX190000Y0D01*\nG03X200000Y10000I0J10000D01*\nG01*\nX200000Y100000D01*\nX0Y100000D01*\nX0Y0D01*\nM02*\n";+        let r = read(t, Some((50.8, 25.4)), 0.1);+        assert_eq!(r["boardShape"], json!(true), "{r}");+        // an open line is no loop+        let o = format!("{HEAD}X0Y0D02*\nX50000000Y0D01*\nM02*\n");+        let ro = read(&o, Some((50.0, 30.0)), 0.1);+        assert_eq!((ro["openDraws"].as_u64(), ro["boardShape"].as_bool()), (Some(1), Some(false)));+    }+}
bridge-rs/src/main.rs+2−1
@@ -16,6 +16,7 @@ mod simmodel; mod simcopy; mod silkcheck; mod dimensions;+mod gerberoutline; mod autoclass; mod board; mod bodies;@@ -91,7 +92,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.122";+pub const BRIDGE_VERSION: &str = "0.2.123";  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/manufacturing.rs+44−10
@@ -220,14 +220,21 @@ pub fn export_manufacturing(args: &Value) -> Value {     // a fab house reads the board's outline from the Gerbers: a scripted board has its shape but nothing on any     // outline layer, and its GM1/GKO came out empty with no warning (2026-10-22). Draw it on Mechanical 1 and     // generate again, unless told not to.-    let mut outline = outline_check(&r);+    // the board shape's size: the outline Gerber must hold a closed loop of that size (#46)+    let board = if crate::support::must_open(&pcb, 60).is_none() {+        crate::agent::call("read_outline", &[], None, std::time::Duration::from_secs(60)).get("data")+            .and_then(|d| Some((d["widthMil"].as_f64()? * 0.0254, d["heightMil"].as_f64()? * 0.0254))).filter(|(w, h)| *w > 0.0 && *h > 0.0)+    } else { None };+    let mut outline = outline_check(&r, board);     if outline["present"] == json!(false) && args.get("addOutline").and_then(|v| v.as_bool()) != Some(false) {         if crate::support::must_open(&pcb, 60).is_none() {-            let d = crate::agent::call("outline_tracks", &[("op", "draw".into()), ("mech", "1".into())], None, std::time::Duration::from_secs(60));+            // the Gerbers proved the board shape missing, so it is drawn beside whatever the layer holds: two mounting-hole+            // circles on Mechanical 1 made the draw step skip, and the set shipped without an outline (#46)+            let d = crate::agent::call("outline_tracks", &[("op", "draw".into()), ("mech", "1".into()), ("replace", "1".into())], None, std::time::Duration::from_secs(60));             outline["added"] = d.get("data").cloned().unwrap_or(d);             let _ = crate::agent::call("close_document", &[("path", outjob.clone())], None, std::time::Duration::from_secs(60));             r = outputs::run_outjob(&a);-            let after = outline_check(&r);+            let after = outline_check(&r, board);             outline["present"] = after["present"].clone();             outline["layers"] = after["layers"].clone();         }@@ -258,13 +265,22 @@ pub fn export_manufacturing(args: &Value) -> Value {     r["_hint"] = json!(if ok_outline {         if outline.get("added").is_some() { "files[] are the manufacturing set under outputDir. The board had no outline on any Gerber layer: the bridge drew its shape on Mechanical 1 (in memory; altium_save keeps it) and generated again, so GM1 carries it." }         else { "files[] are the manufacturing set under outputDir (Gerber, NC Drill, Pick Place, Bill of Materials folders); pull them with ab's pull_file and check them against the board before handing them over." }-    } else { "NO BOARD OUTLINE in the Gerbers (GM1/GKO empty): a fab house will reject this set. altium_board_outline draws the board shape on a mechanical layer; then run this again." });+    } else { "NO BOARD OUTLINE in the Gerbers: no outline file (GM1/GKO) holds a closed loop the size of the board shape (fabChecks.outline.layers[].note says what each holds). A fab house would reject this set. altium_board_outline draws the board shape on a mechanical layer; then run this again." });+    // a set without the board outline is not a fab package: the files stay, the call fails by name (#46)+    if outline["present"] == json!(false) {+        r["success"] = json!(false);+        r["errorCode"] = json!("no_board_outline");+        r["error"] = json!(format!("no outline Gerber holds the board shape: {}", outline["layers"].as_array().cloned().unwrap_or_default().iter()+            .map(|l| format!("{}: {}", l["file"].as_str().unwrap_or(""), l["note"].as_str().unwrap_or(""))).collect::<Vec<_>>().join("; ")));+    }     if r["fabChecks"]["copperLayers"]["ok"] == json!(false) { r["_hint"] = json!("COPPER LAYERS MISSING from the Gerbers: fabChecks.copperLayers counts fewer copper files than the board has. Check the stack (altium_layer_stack) and report it."); }     r } -/// Does any outline Gerber (mechanical or keep-out) carry a draw? Reads the files run_outjob listed.-fn outline_check(r: &Value) -> Value {+/// Does an outline Gerber (mechanical or keep-out) carry the board's outline: a closed loop the size of the board shape+/// (`board`, mm)? Reads the files run_outjob listed. Counting draws passed a GM1 holding only two mounting-hole circles+/// (#46); each file now says what it holds. Without the board's size, any closed loop counts.+fn outline_check(r: &Value, board: Option<(f64, f64)>) -> Value {     let dir = r["outputDir"].as_str().unwrap_or("").to_string();     let mut layers = Vec::new();     let mut present = false;@@ -274,12 +290,30 @@ fn outline_check(r: &Value) -> Value {         // the board outline layers a fab reads: keep-out (GKO) and Mechanical 1 (GM1); GM13/GM15 carry component bodies         if ext == "GKO" || ext == "GM1" || ext == "GML" || ext == "GBR" && name.to_ascii_lowercase().contains("outline") {             let text = std::fs::read_to_string(std::path::Path::new(&dir).join(&name)).unwrap_or_default();-            let draws = text.matches("D01").count() + text.matches("D1*").count();-            if draws > 0 { present = true; }-            layers.push(json!({"file": name, "draws": draws}));+            let mut l = crate::gerberoutline::read(&text, board, 0.1);+            let is_board = match board { Some(_) => l["boardShape"] == json!(true), None => l["closedLoops"].as_array().is_some_and(|a| !a.is_empty()) };+            if is_board { present = true; }+            l["file"] = json!(name);+            l["note"] = json!(describe(&l, board));+            layers.push(l);         }     }-    json!({"present": if layers.is_empty() && dir.is_empty() { Value::Null } else { json!(present) }, "layers": layers})+    let mut out = json!({"present": if layers.is_empty() && dir.is_empty() { Value::Null } else { json!(present) }, "layers": layers});+    if let Some((w, h)) = board { out["boardMm"] = json!([(w * 1000.0).round() / 1000.0, (h * 1000.0).round() / 1000.0]); }+    out+}++/// What an outline file holds, in words: "2 closed loops (3.2 x 3.2, 3.2 x 3.2 mm), none the board shape (50 x 30 mm)".+fn describe(l: &Value, board: Option<(f64, f64)>) -> String {+    let loops = l["closedLoops"].as_array().cloned().unwrap_or_default();+    let sizes: Vec<String> = loops.iter().take(4).map(|x| format!("{} x {}", x["widthMm"], x["heightMm"])).collect();+    let open = l["openDraws"].as_u64().unwrap_or(0);+    let mut s = if loops.is_empty() { "no closed loop".to_string() } else { format!("{} closed loop{} ({} mm)", loops.len(), if loops.len() == 1 { "" } else { "s" }, sizes.join(", ")) };+    if open > 0 { s.push_str(&format!(", {open} draw{} that close nothing", if open == 1 { "" } else { "s" })); }+    if let Some((w, h)) = board {+        s.push_str(&if l["boardShape"] == json!(true) { format!(": one is the board shape ({w:.3} x {h:.3} mm)") } else { format!(", none the board shape ({w:.3} x {h:.3} mm)") });+    }+    s }  #[cfg(test)]
bridge-rs/src/routing.rs+2−1
@@ -1330,7 +1330,8 @@ pub fn set_outline(args: &Value) -> Value {     let r = agent::call("set_outline", &[], Some(&format!("O|{spec}")), Duration::from_secs(120));     let d = match r.get("data") { Some(d) if d.get("ok").and_then(|v| v.as_bool()) == Some(true) => d.clone(), _ => return r };     let after = routing_state(&json!({}));-    json!({"success": true, "vertices": d["vertices"], "revisionBefore": st["revision"], "revision": after["revision"], "outlineEdges": after["outlineEdges"],+    // #47: the layer-stack region that had the old shape is refitted to the new one (found / refit / leftAlone)+    json!({"success": true, "vertices": d["vertices"], "stackRegions": d["stackRegions"], "revisionBefore": st["revision"], "revision": after["revision"], "outlineEdges": after["outlineEdges"],            "_hint": "Copper keeps its edge clearance from the new outline: repour (altium_repour) when a pour followed the old one."}) } 
bridge-rs/src/schwire.rs+7−2
@@ -321,8 +321,13 @@ pub fn items(args: &Value) -> Value {         if on(k) { out.get_mut(k).unwrap().push(v); }     }     let counts: BTreeMap<&str, usize> = out.iter().map(|(k, v)| (*k, v.len())).collect();-    let mut r = json!({"success": true, "sheet": sheet, "units": "mm", "counts": counts,-        "_hint": "Ids are Altium items' kind plus a hash of their geometry: valid until the item changes; every edit verb answers the new ids. Altium's ports are listed as hierarchical labels (altium: port). Parts are in altium_schematic_data; pins in altium_sch_pins."});+    // objects stacked on one spot share an id (kind plus geometry): a net label over another one joins their nets+    // where nobody sees it (#50: 570 labels sat on the visible ones)+    let mut seen: BTreeMap<(String, String), usize> = BTreeMap::new();+    for (k, v) in &out { for it in v { if let Some(id) = it["id"].as_str() { *seen.entry((k.to_string(), id.to_string())).or_default() += 1; } } }+    let stacked: Vec<Value> = seen.into_iter().filter(|(_, n)| *n > 1).map(|((k, id), n)| json!({"kind": k, "id": id, "count": n})).collect();+    let mut r = json!({"success": true, "sheet": sheet, "units": "mm", "counts": counts, "stacked": stacked,+        "_hint": "Ids are Altium items' kind plus a hash of their geometry: valid until the item changes; every edit verb answers the new ids. stacked lists ids that more than one object shares (objects on top of each other: a label over a label joins nets unseen). Altium's ports are listed as hierarchical labels (altium: port). Parts are in altium_schematic_data; pins in altium_sch_pins."});     for (k, v) in out { if on(k) { r[k] = json!(v); } }     r }
bridge-rs/src/verbs.rs+19−4
@@ -85,7 +85,7 @@ fn describe() -> Value {             &["status"], &["Develop writes NO licence tail when it HOLDS the seat - blank licenceState there means licensed."], json!({})),         verb_doc("eval", "Run a DelphiScript snippet inside Altium (optional Var block, then Begin ... End;) on the CURRENT document, or on filePath opened first.", json!({"text": "string - [Var X : Integer;] Begin ... End;", "filePath": "optional: the document to make current first (a .PcbDoc for PCBServer.GetCurrentPCBBoard)", "timeout": "int seconds the reply waits (default 60, up to 600). Altium's window does not respond while the script runs; the bridge knows it is the script and leaves Altium alone."}),             json!({"success": "bool (false + errorShot when Altium raised an error box)", "errorCode": "script_error", "errorShot": "PNG of Altium's error box"}), 30,-            "Single quotes only (no double quotes). A Var block before Begin is allowed. Capture output by writing a file, not by returning a value. Pass filePath: after an export the OutJob is current and GetCurrentPCBBoard is Nil.",+            "Up to 16000 bytes (longer: script_too_long at once); a script over 1000 bytes runs in the agent, started for it (the command line lane fails past about 2 KB). Single quotes only (no double quotes). A Var block before Begin is allowed. Capture output by writing a file, not by returning a value. Pass filePath: after an export the OutJob is current and GetCurrentPCBBoard is Nil.",             &["run_command"], &["An undeclared identifier HALTS the engine with a modal that Try/Except cannot catch.", "ShowMessage blocks the loop behind a modal - never use it."], json!({"text": "Begin PCBServer.GetCurrentPCBBoard.ViewManager_FullUpdate; End;"})),         verb_doc("run_command", "Run an Altium process (Server:Command) through the agent, on the CURRENT document or on filePath opened first.", json!({"command": "string - e.g. PCB:Zoom", "params": "string or object", "filePath": "optional: the document to make current first (PCB: processes need a board current)"}),             json!({"success": "bool"}), 60, "Params are pipe-joined key=value pairs. altium_list_commands searches the catalog.", &["eval", "list_commands"], &["Some processes open a modal dialog and block the loop until it is answered."], json!({"command": "PCB:Zoom", "params": {"Action": "All"}})),@@ -829,7 +829,7 @@ fn describe() -> Value {             json!({"sheet": "C:/proj/Main.SchDoc", "library": "C:/proj/Lib.SchLib", "symbol": "TPS54202DDCR", "designator": "U2", "x": 3000, "y": 4000})),         verb_doc("sch_items", "List a sheet's wiring items with ids and coordinates: wires, buses, bus entries, net labels (local, global, hierarchical), power ports, junctions, no-connect markers, texts and sheet symbols. Read only. Coordinates are mm in the sheet's frame (Altium's own, y up), the EDA Bridge Standard's schematic frame.",             json!({"sheet": "path to the schematic sheet file (required)", "kinds": "[wires, buses, busEntries, labels, powerPorts, junctions, noConnects, texts, sheets] (default all)"}),-            json!({"wires": "[{id, from, to}]", "buses": "[{id, from, to}]", "busEntries": "[{id, at, end}]", "labels": "[{id, text, kind: local|global|hierarchical, at, rotation}]", "powerPorts": "[{id, net, at}]", "junctions": "[{id, at}]", "noConnects": "[{id, at}]", "texts": "[{id, text, at}]", "sheets": "[{id, name, file, at, sizeMm}]", "counts": "{kind: int}"}), 120,+            json!({"wires": "[{id, from, to}]", "buses": "[{id, from, to}]", "busEntries": "[{id, at, end}]", "labels": "[{id, text, kind: local|global|hierarchical, at, rotation}]", "powerPorts": "[{id, net, at}]", "junctions": "[{id, at}]", "noConnects": "[{id, at}]", "texts": "[{id, text, at}]", "sheets": "[{id, name, file, at, sizeMm}]", "counts": "{kind: int}", "stacked": "[{kind, id, count}]: ids more than one object shares (objects on top of each other; a net label over another joins their nets unseen)"}), 120,             "The ids feed sch_delete_wire, sch_edit_label, sch_junction and sch_edit. Parts are in schematic_data.", &["schematic_data", "sch_pins", "sch_delete_wire", "sch_edit_label"], &["A wire is one straight segment: a polyline drawn in the editor is several wires sharing ends.", "Altium items have no stable id: an id is the item's kind plus a hash of its geometry, valid until the item changes; every edit answers the new ids."], json!({"sheet": "C:/proj/Main.SchDoc", "kinds": ["wires", "labels"]})),         verb_doc("sch_pins", "Every pin of the named parts on a sheet: its absolute position (rotation and mirror applied), number, name, electrical type, the side it leaves the body, and the wires, labels and nets touching it. Read only. Coordinates are mm in the sheet's frame (Altium's own, y up), the EDA Bridge Standard's schematic frame.",             json!({"sheet": "path to the schematic sheet file (required)", "references": "[\"U1\", \"R5\"] (default every part)", "connections": "bool, default true: add what touches each pin"}),@@ -1707,6 +1707,11 @@ fn batch_or_one(args: &Value, list: &str, one: fn(&Value) -> Value) -> Value {  /// After an eval: did Altium raise a script error box? The reaper photographs and presses a lone-OK "Error"; /// a two-button "X2 ... Continue execution?" is answered OK here. Watches 3.5 s.+/// altium_eval's sizes (#48): the -R command line lane takes the text as one argument and failed at 3.4 KB (2 KB ran),+/// so a longer script goes to the agent, which ran 16 KB and timed out at 32 KB.+pub const EVAL_CLI_MAX_BYTES: usize = 1000;+pub const EVAL_MAX_BYTES: usize = 16_000;+ fn eval_error_since(since: u64, lane: &str) -> Option<Value> {     let t = std::time::Instant::now();     while t.elapsed() < Duration::from_millis(3500) {@@ -1952,8 +1957,17 @@ pub fn dispatch(command: &str, args: &Value, _forwarded: &[(String, String)]) ->                 Some(t) => t,                 None => return json!({"success": false, "error": "text is required (DelphiScript STATEMENTS: Begin ... End;)"}),             };-            if !agent::is_alive() {-                // not resident → the -R RunScriptText lane is available and simplest+            // #48, measured on AD 26.11 (2026-12-04): the -R command line lane runs 2 KB but fails at 3.4 KB (a script+            // error here, instance_busy after ~65 s on AD 26.3); the agent lane runs 16 KB and times out at 32 KB+            if text.len() > EVAL_MAX_BYTES {+                return json!({"success": false, "errorCode": "script_too_long", "bytes": text.len(), "limitBytes": EVAL_MAX_BYTES,+                    "error": format!("the script is {} bytes; altium_eval runs up to {EVAL_MAX_BYTES} (32 KB timed out in Altium's script engine)", text.len()),+                    "_hint": "Split the script, or keep it short and put the bulk data in a file it reads (TStringList.LoadFromFile, one CommaText row per line)."});+            }+            let long = text.len() > EVAL_CLI_MAX_BYTES;+            if !agent::is_alive() && !long {+                // not resident → the -R RunScriptText lane is available and simplest (short scripts only: a longer one+                // is run by the agent, started for it)                 let since = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0);                 let mut r = lifecycle::run_script_text_lane(&text, Duration::from_secs(timeout.max(30)));                 r["lane"] = json!("cli_run_script_text");@@ -1968,6 +1982,7 @@ pub fn dispatch(command: &str, args: &Value, _forwarded: &[(String, String)]) ->             let since = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0);             let mut r = agent::call("eval", &[], Some(&text), Duration::from_secs(timeout.max(30)));             r["lane"] = json!("agent");+            if long { r["laneReason"] = json!(format!("{} bytes: past the command line lane's limit ({EVAL_CLI_MAX_BYTES}), run by the agent", text.len())); }             // the agent hands the text to Altium's script engine and answers at once; an error box comes after,             // so the agent lane answered success:true for a script that halted the engine (2026-10-22)             if r.get("success").and_then(|b| b.as_bool()) == Some(true) {
package.json+1−1
@@ -1,6 +1,6 @@ {   "slug": "altium-bridge",-  "version": "0.2.122",+  "version": "0.2.123",   "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": [
page.json+1−1
@@ -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.122",+  "version": "0.2.123",   "hero": {     "type": "image",     "path": "screenshots/hero.png"
skills/altium-boards/SKILL.md+5
@@ -66,6 +66,11 @@ GROWS to keep the new parts inside the drawing frame (`sheetGrown:true`; it neve  ## Board shape +From 0.2.123 (#47) `altium_board_shape`, `altium_set_outline`, `altium_build_board` and `altium_test_board` also refit+Altium's Default Layer Stack Region to the new outline (the region the 3D view and the layer stack draw from, which+otherwise kept the old size). A region that did not match the old outline is a user's own and is left alone; the+reply's `stackRegions` gives `found`, `refit` and `leftAlone`.+ `altium_board_shape {x0Mm,y0Mm,wMm,hMm}` sets the outline's four vertices (PointCount + Segments[] + Rebuild, the pattern that renders on every build; `.Clear` HALTS the engine). 
skills/altium-libraries/SKILL.md+4
@@ -70,6 +70,10 @@ included. Save afterwards.   "Courtyard", User.9→Mechanical 9 renamed **"Adom.SolderBalls"** (hidden by default). An organisation's own   layers come from the layer map, below. - KiCad Y-down is flipped; filled discs are full arcs at r/2 with stroke r.+- **Slots and unplated holes (0.2.123, #45/#49)**: a PAD line is `PAD|des|x|y|w|h|shape|hole|layer|crpct|plated|slot|slotrot`.+  `plated` 0 makes an unplated hole (KiCad `np_thru_hole`); `slot` above 0 makes a slot `hole` wide and `slot` long,+  turned `slotrot` degrees. kicad2altium writes both from an oval `(drill oval w h)`, so a USB-C receptacle's+  shield slots and locating pegs come through, and the NC drill files carry them (SlotHoles, NON_PLATED). - Pads must carry a Layer or they are SILENTLY DROPPED (measured); `Bottom*/Mid*` pad size   properties do not exist in this engine (halt). 
skills/altium-outputs/SKILL.md+5
@@ -34,6 +34,11 @@ Parent skill: **altium-bridge**   had its shape on no layer, so those files were empty and a fab house would reject the set. The bridge now   draws the shape on Mechanical 1 (`altium_board_outline`, in memory: `altium_save` keeps it) and generates   again; `addOutline:false` skips that and just reports.+- From 0.2.123 (#46) the check reads the outline Gerbers themselves: their draws chained into closed loops, each+  with its size, and `present` is true only when one loop is the board's shape (within 0.1 mm). Two mounting-hole+  circles on Mechanical 1 used to pass as an outline. The board shape is drawn beside what the layer already holds,+  and each file's `note` says what it found ("3 closed loops (3.2 x 3.2, 3.2 x 3.2, 40.0 x 30.0 mm): one is the+  board shape"). Still missing after that, the export answers `success:false`, `errorCode: no_board_outline`. - `fabChecks.copperLayers`: one copper Gerber per copper layer. The board's planes and inner layers are added   to the Gerber plot set (Altium's template plotted top, mid 1-2 and bottom only). Measured: a 4-layer buck gave   GTL, GP1, GP2, GBL.
skills/altium-schematic-edit/SKILL.md+5−1
@@ -45,6 +45,10 @@ altium_update_pcb     '{"projectPath":"C:\\proj\\board.PrjPcb","execute":true,"t - `annotate` gives every `R?`, `C?`, `U?` the lowest free number for its prefix across all sheets,   top-left first. `dryRun:true` shows the plan. The parts of a multi-part symbol on one sheet share a   number (U4A + U4B, then U5A + U5B), grouped top-left first, never two of the same part in one group.+- **Symbols with several display modes (0.2.123, #50).** A placed part carries the pins of every part and every+  display mode; only the shown ones are wired. `build_schematic`, `sch_connect` and `sch_place_part`'s pin count+  read the pins of the part's current part and display mode (and the pins shared by all parts). Before this a+  symbol with an alternate mode got its labels twice, stacked on the same spot.  ## Parts from the Altium 365 workspace (the shared cloud library) @@ -69,7 +73,7 @@ of its geometry, valid until the item changes, and every edit answers the new id  | Job | Verb | |---|---|-| Every wire, bus, entry, label, port, power port, junction, No ERC, text and sheet symbol | `altium_sch_items` |+| Every wire, bus, entry, label, port, power port, junction, No ERC, text and sheet symbol (`stacked` lists objects lying exactly on top of each other, which share an id: a sign of a doubled placement) | `altium_sch_items` | | Every pin: outer end (where a wire must land), direction, type, what touches it, its net, the pins it reaches | `altium_sch_pins` | | Everything connected at a point, and the whole net | `altium_sch_trace_point` | | Wire pin to pin (an L route, junctions where it makes a T) | `altium_sch_connect_pins {pairs:[{from:"U1.1", to:"R5.2"}]}` |
src/BRIDGE_VERSION+1−1
@@ -1 +1 @@-0.2.122+0.2.123
src/agent/AdomAgent.pas.tmpl+142−10
@@ -3634,6 +3634,15 @@ Begin             R := StrToIntDef(FieldP(L, 10), 0);             If (Shape = 'roundrect') And (R > 0) Then                 Pad.SetState_StackCRPctOnLayer(eTopLayer, R);+            { #45: field 11 plated (0: a KiCad np_thru_hole peg, drilled but not plated), field 12 the slot's length (mm)+              when the drill is oval (the hole size is then its width), field 13 its angle from the pad's x axis }+            If FieldP(L, 11) = '0' Then Pad.Plated := False;+            If AdomFloat(FieldP(L, 12)) > 0 Then+            Begin+                Pad.HoleType := eSlotHole;+                Pad.HoleWidth := MmC(FieldP(L, 12));+                Pad.HoleRotation := AdomFloat(FieldP(L, 13));+            End;             Comp.AddPCBObject(Pad);             NPads := NPads + 1;         End@@ -4278,6 +4287,100 @@ Begin     AL.Free; End; +{ The board outline's box from its vertices (the cached BoundingRectangle can lag an edit), in L, B, R, T. }+Procedure OutlineBoxOf(Board : IPCB_Board; Var L, B, R, T : Integer);+Var+    K : Integer;+    Seg : TPolySegment;+Begin+    L := 0; B := 0; R := 0; T := 0;+    If Board.BoardOutline = Nil Then Exit;+    For K := 0 To Board.BoardOutline.PointCount - 1 Do+    Begin+        Seg := Board.BoardOutline.Segments[K];+        If (K = 0) Or (Seg.vx < L) Then L := Seg.vx;+        If (K = 0) Or (Seg.vy < B) Then B := Seg.vy;+        If (K = 0) Or (Seg.vx > R) Then R := Seg.vx;+        If (K = 0) Or (Seg.vy > T) Then T := Seg.vy;+    End;+End;++{ The board outline as a region contour: its vertices, and points along each arc segment (from the end nearest the+  vertex, so the contour runs the outline's way). }+Function OutlineContour(Board : IPCB_Board) : IPCB_Contour;+Var+    K, I, N : Integer;+    Seg : TPolySegment;+    A0, A1, Sweep, Ang, D0, D1, Rad, DX, DY : Double;+Begin+    Result := PCBServer.PCBContourFactory;+    Rad := 3.14159265358979 / 180;+    For K := 0 To Board.BoardOutline.PointCount - 1 Do+    Begin+        Seg := Board.BoardOutline.Segments[K];+        Result.AddPoint(Seg.vx, Seg.vy);+        If (Seg.Kind = ePolySegmentArc) And (Seg.Radius > 0) Then+        Begin+            A0 := Seg.Angle1; A1 := Seg.Angle2;+            If A1 <= A0 Then A1 := A1 + 360;+            Sweep := A1 - A0;+            { the arc is walked from the end the vertex sits on (no ArcTan2 in DelphiScript: the nearer end wins) }+            DX := Seg.cx + Seg.Radius * Cos(A0 * Rad) - Seg.vx; DY := Seg.cy + Seg.Radius * Sin(A0 * Rad) - Seg.vy;+            D0 := DX * DX + DY * DY;+            DX := Seg.cx + Seg.Radius * Cos(A1 * Rad) - Seg.vx; DY := Seg.cy + Seg.Radius * Sin(A1 * Rad) - Seg.vy;+            D1 := DX * DX + DY * DY;+            N := 24;+            For I := 1 To N - 1 Do+            Begin+                If D0 <= D1 Then Ang := A0 + Sweep * I / N Else Ang := A1 - Sweep * I / N;+                Result.AddPoint(Seg.cx + Round(Seg.Radius * Cos(Ang * Rad)), Seg.cy + Round(Seg.Radius * Sin(Ang * Rad)));+            End;+        End;+    End;+End;++{ #47: after a board-shape edit, the layer-stack region (board planning's Default Layer Stack Region: a multi-layer+  region of kind 3) that had the OLD outline's box is refitted to the new outline. A region of that kind that did not+  match the old outline (a cutout, one of several stack regions) is left alone and counted. Returns the reply's JSON. }+Function RefitStackRegions(Board : IPCB_Board; OL, OB, OR2, OT : Integer) : String;+Var+    BI : IPCB_BoardIterator;+    P : IPCB_Primitive;+    Rs : TInterfaceList;+    R : TCoordRect;+    I, Found, Refit, Kept, Tol : Integer;+Begin+    Tol := MilsToCoord(10);+    Found := 0; Refit := 0; Kept := 0;+    Rs := TInterfaceList.Create;+    BI := Board.BoardIterator_Create;+    BI.AddFilter_ObjectSet(MkSet(eRegionObject));+    BI.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers);+    BI.AddFilter_Method(eProcessAll);+    P := BI.FirstPCBObject;+    While P <> Nil Do+    Begin+        If (P.Layer = eMultiLayer) And (P.Kind = 3) Then Rs.Add(P);+        P := BI.NextPCBObject;+    End;+    Board.BoardIterator_Destroy(BI);+    For I := 0 To Rs.Count - 1 Do+    Begin+        P := Rs[I];+        Found := Found + 1;+        R := P.BoundingRectangle;+        If (Abs(R.Left - OL) <= Tol) And (Abs(R.Bottom - OB) <= Tol) And (Abs(R.Right - OR2) <= Tol) And (Abs(R.Top - OT) <= Tol) Then+        Begin+            P.BeginModify;+            P.SetOutlineContour(OutlineContour(Board));+            P.EndModify;+            Refit := Refit + 1;+        End+        Else Kept := Kept + 1;+    End;+    Result := '{' + JRaw('found', IntToStr(Found)) + ',' + JRaw('refit', IntToStr(Refit)) + ',' + JRaw('leftAlone', IntToStr(Kept)) + '}';+End;+ { New PcbDoc: FR4 rectangle wMm x hMm (origin at 0,0), the footprint placed at   the centre, pad 1 and pad 49 given nets with a stub track each.   Args: footprint, wMm, hMm, pcb=<save path>, assigns=<des=net;...>, stubs=<des=x,y;...> (mm from centre) }@@ -4302,7 +4405,7 @@ Var     ECmp  : IPCB_Component;     GIt2  : IPCB_GroupIterator;     MPrim : IPCB_Primitive;-    I, K, WC, HC, CX, CY, PX, PY, Found : Integer;+    I, K, WC, HC, CX, CY, PX, PY, Found, OL, OB, OR2, OT : Integer;     NExist, ExtR, Cur, FW, FL, FR, AnyF : Integer;     FpName, PcbPath, Des, NetName, Item, Missing : String;     Ok, Append : Boolean;@@ -4414,6 +4517,7 @@ Begin     BO.Invalidate;     { no Clear: IPCB_BoardOutline has no Clear in this engine (halt, measured);       PointCount + Segments[] + Rebuild is the working pattern }+    OutlineBoxOf(Board, OL, OB, OR2, OT);     BO.PointCount := 4;     Seg := BO.Segments[0]; Seg.vx := 0; Seg.vy := 0; Seg.Kind := ePolySegmentLine; BO.Segments[0] := Seg;     Seg := BO.Segments[1]; Seg.vx := WC; Seg.vy := 0; Seg.Kind := ePolySegmentLine; BO.Segments[1] := Seg;@@ -4421,6 +4525,7 @@ Begin     Seg := BO.Segments[3]; Seg.vx := 0; Seg.vy := HC; Seg.Kind := ePolySegmentLine; BO.Segments[3] := Seg;     BO.Rebuild;     BO.Validate;+    RefitStackRegions(Board, OL, OB, OR2, OT);     End;     CX := WC Div 2;     If Append Then Cur := ExtR + MMsToCoord(6)@@ -4602,7 +4707,8 @@ Var     Board : IPCB_Board;     BO    : IPCB_BoardOutline;     Seg   : TPolySegment;-    X0, Y0, X1, Y1, K, NTr : Integer;+    X0, Y0, X1, Y1, K, NTr, OL, OB, OR2, OT : Integer;+    Regions : String;     Trk : IPCB_Track; Begin     Board := PCBServer.GetCurrentPCBBoard;@@ -4627,6 +4733,7 @@ Begin             JStr('error','this document has no board outline object (a PcbLib internal board has none); open a .PcbDoc') + '}';         Exit;     End;+    OutlineBoxOf(Board, OL, OB, OR2, OT);     PCBServer.PreProcess;     BO.Invalidate;     BO.PointCount := 4;@@ -4656,9 +4763,10 @@ Begin             NTr := NTr + 1;         End;     End;+    Regions := RefitStackRegions(Board, OL, OB, OR2, OT);     PCBServer.PostProcess;     Board.ViewManager_FullUpdate;-    Result := '{' + JRaw('ok','true') + ',' + JRaw('outlineMil', OutlineMilFromVertices(BO)) + ',' ++    Result := '{' + JRaw('ok','true') + ',' + JRaw('stackRegions', Regions) + ',' + JRaw('outlineMil', OutlineMilFromVertices(BO)) + ',' +         JStr('outlineSource', 'vertices') + ',' + JRaw('mechOutlineTracks', IntToStr(NTr)) + '}'; End; @@ -8182,7 +8290,8 @@ Var     Inst  : IPCB_Component;     LibFp : IPCB_LibComponent;     Op, PcbPath, Missing, Outline, Refs : String;-    I, K, Placed, Wired, OutN : Integer;+    I, K, Placed, Wired, OutN, OL, OB, OR2, OT : Integer;+    Regions : String; Begin     PcbPath := Param(Lines, 'pcb');     PLib := PCBServer.GetCurrentPCBLibrary;@@ -8215,7 +8324,14 @@ Begin     Placed := 0; Wired := 0; OutN := 0; Refs := '';     gInputError := '';     PCBServer.PreProcess;-    If Outline <> '' Then OutN := SetOutlineFrom(Board, Outline);+    { a new board's layer-stack region has the default shape: refitted to the outline (#47) }+    Regions := '{}';+    If Outline <> '' Then+    Begin+        OutlineBoxOf(Board, OL, OB, OR2, OT);+        OutN := SetOutlineFrom(Board, Outline);+        If OutN >= 3 Then Regions := RefitStackRegions(Board, OL, OB, OR2, OT);+    End;     For I := 0 To Ops.Count - 1 Do     Begin         Op := Trim(Ops[I]);@@ -8250,7 +8366,7 @@ Begin     Ops.Free; Fps.Free;     Result := '{' + JRaw('ok','true') + ',' + JStr('pcb', PcbPath) + ',' + JRaw('placed', IntToStr(Placed)) + ',' + JRaw('padsWired', IntToStr(Wired)) + ',' +         JRaw('libOriginMil', '[' + IntToStr(Round(CoordToMils(PLib.Board.XOrigin))) + ',' + IntToStr(Round(CoordToMils(PLib.Board.YOrigin))) + ']') + ',' +-        JRaw('outlineVertices', IntToStr(OutN)) + ',' + JRaw('refs', '[' + Refs + ']') + ',' + JRaw('badNumber', JBool(gInputError <> '')) + '}';+        JRaw('outlineVertices', IntToStr(OutN)) + ',' + JRaw('stackRegions', Regions) + ',' + JRaw('refs', '[' + Refs + ']') + ',' + JRaw('badNumber', JBool(gInputError <> '')) + '}';     gInputError := ''; End; @@ -8259,16 +8375,20 @@ End; Function CmdSetOutline(Lines : TStringList; Payload : String) : String; Var     Board : IPCB_Board;-    N : Integer;+    N, OL, OB, OR2, OT : Integer;+    Regions : String; 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;+    OutlineBoxOf(Board, OL, OB, OR2, OT);     PCBServer.PreProcess;     N := SetOutlineFrom(Board, FieldP(Trim(Payload), 2));+    Regions := '{}';+    If N >= 3 Then Regions := RefitStackRegions(Board, OL, OB, OR2, OT);     PCBServer.PostProcess;     gInputError := '';     Board.ViewManager_FullUpdate;-    Result := '{' + JRaw('ok', JBool(N >= 3)) + ',' + JRaw('vertices', IntToStr(N)) + '}';+    Result := '{' + JRaw('ok', JBool(N >= 3)) + ',' + JRaw('vertices', IntToStr(N)) + ',' + JRaw('stackRegions', Regions) + '}'; End;  { set_rule: write ONE design rule kind on the current board. One kind per call, so a property this@@ -8557,6 +8677,14 @@ End; { ------------------------------------------------------------ schematic editing (0.2.57) --- }  { the placed parts of the current sheet with this designator (every part of a multi-part component) }+{ A placed part's pin as the sheet shows it: its own part (or the shared part 0) in its current display mode. A placed+  part carries every part's and every display mode's pins; wiring the others put net labels where another mode's pin+  sits and shorted nets (#50: a symbol with 10 modes got 570 extra labels). }+Function PinShownOn(C : ISch_Component; Pin : ISch_Pin) : Boolean;+Begin+    Result := ((Pin.OwnerPartId = C.CurrentPartID) Or (Pin.OwnerPartId = 0)) And (Pin.OwnerPartDisplayMode = C.DisplayMode);+End;+ Function SheetCompsOf(Doc : ISch_Document; Des : String) : TInterfaceList; Var     It : ISch_Iterator;@@ -9111,7 +9239,7 @@ Begin                 Pin := PIt.FirstSchObject;                 While Pin <> Nil Do                 Begin-                    If (Pin.OwnerPartId = C.CurrentPartID) Or (Pin.OwnerPartId = 0) Then+                    If PinShownOn(C, Pin) Then                         If (UpperCase(Pin.Designator) = UpperCase(PinKey)) Or ((Hit = Nil) And (UpperCase(Pin.Name) = UpperCase(PinKey))) Then                             If (Hit = Nil) Or (UpperCase(Pin.Designator) = UpperCase(PinKey)) Then Hit := Pin;                     Pin := PIt.NextSchObject;@@ -9335,7 +9463,7 @@ Begin         Prim := PIt.FirstSchObject;         While Prim <> Nil Do         Begin-            If (Prim.OwnerPartId = Part) Or (Prim.OwnerPartId = 0) Then NPins := NPins + 1;+            If ((Prim.OwnerPartId = Part) Or (Prim.OwnerPartId = 0)) And (Prim.OwnerPartDisplayMode = Inst.DisplayMode) Then NPins := NPins + 1;             Prim := PIt.NextSchObject;         End;         Inst.SchIterator_Destroy(PIt);@@ -9984,6 +10112,9 @@ Begin             Pin := PIt.FirstSchObject;             While Pin <> Nil Do             Begin+              { only the pins the sheet shows are wired (#50) }+              If PinShownOn(Inst, Pin) Then+              Begin                 Net := PinNet.Values[Refs[K] + '.' + Pin.Designator];                 Dir := Pin.Orientation;                 HX := Pin.Location.X; HY := Pin.Location.Y;@@ -10023,6 +10154,7 @@ Begin                     SchServer.RobotManager.SendMessage(Sheet.I_ObjectAddress, c_BroadCast, SCHM_PrimitiveRegistration, NL.I_ObjectAddress);                     NLabels := NLabels + 1;                 End;+              End;                 Pin := PIt.NextSchObject;             End;             Inst.SchIterator_Destroy(PIt);
src/bridge.json+1−1
@@ -2,7 +2,7 @@   "manifest_version": 1,   "name": "altium",   "displayName": "Altium Designer",-  "version": "0.2.122",+  "version": "0.2.123",   "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",
tools/kicad2altium.py+27−8
@@ -5,7 +5,10 @@ DelphiScript). Units: mm in, mm out; Y is flipped (KiCad Y-down -> Altium Y-up).  Spec lines (pipe-separated):   META|name|description-  PAD|designator|x|y|w|h|shape|hole|layer|crpct      shape: round|rect|oval|roundrect ; layer: top|multi+  PAD|designator|x|y|w|h|shape|hole|layer|crpct|plated|slot|slotrot+        shape: round|rect|oval|roundrect ; layer: top|multi ; plated 1|0 (0: a KiCad np_thru_hole peg)+        slot: the slot's length in mm when the drill is oval (hole is then its width), 0 for a round hole;+        slotrot: the slot's angle in degrees, from the pad's x axis   LINE|layer|x1|y1|x2|y2|width   ARC|layer|cx|cy|r|width|start|stop                   full circles: 0..360, width = stroke   DISC|layer|cx|cy|r                                   filled circle (drawn as arc with width=r)@@ -28,6 +31,20 @@ LAYER = {"F.SilkS": "overlay", "F.Fab": "fab", "F.CrtYd": "courtyard", "User.9":  def num(x): return float(x) +def drill_of(d, rot=0.0):+    """A pad's drill as (hole, slot, slot_rot): (drill D) is a round hole D; (drill oval W L) a slot W wide and L long+    along the pad's x axis when W > L, its y axis otherwise (#45: float('oval') aborted the conversion). A pad turned+    90 or 270 degrees has its sizes swapped (see the pad), and so has its drill. An offset sub-list is skipped."""+    if not d: return 0.0, 0.0, 0.0+    vals = [v for v in d[1:] if isinstance(v, str)]+    oval = bool(vals) and vals[0] == 'oval'+    nums = [num(v) for v in vals if v != 'oval']+    if not nums: return 0.0, 0.0, 0.0+    dx = nums[0]; dy = nums[1] if len(nums) > 1 else nums[0]+    if not oval or abs(dx - dy) < 1e-9: return dx, 0.0, 0.0+    if rot in (90.0, 270.0): dx, dy = dy, dx+    return min(dx, dy), max(dx, dy), (0.0 if dx > dy else 90.0)+ def parse_sexpr(s):     """Minimal s-expression parser -> nested lists (strings kept)."""     tokens = re.findall(r'\(|\)|"(?:[^"\\]|\\.)*"|[^\s()]+', s)@@ -64,7 +81,7 @@ def convert(path, name=None, description=""):     assert fp[0] in ('footprint', 'module'), fp[0]     name = name or fp[1]     out = [f"META|{name}|{description}"]-    stats = {"pads": 0, "th": 0, "lines": 0, "arcs": 0, "discs": 0, "polys": 0, "layers": set()}+    stats = {"pads": 0, "th": 0, "npth": 0, "slots": 0, "lines": 0, "arcs": 0, "discs": 0, "polys": 0, "layers": set()}     for n in fp[2:]:         if not isinstance(n, list): continue         k = n[0]@@ -75,10 +92,11 @@ def convert(path, name=None, description=""):             w, h = num(size[1]), num(size[2])             rot = num(at[3]) if len(at) > 3 else 0.0             if rot in (90.0, 270.0): w, h = h, w-            hole = 0.0-            d = first(n, 'drill')-            if d: hole = num(d[1])-            layer = 'multi' if kind == 'thru_hole' else 'top'+            hole, slot, slot_rot = drill_of(first(n, 'drill'), rot)+            # a through hole of either kind is drilled: np_thru_hole (a peg) is a multi-layer pad left unplated. Written+            # as a top-layer pad it was never drilled (#45).+            layer = 'multi' if kind in ('thru_hole', 'np_thru_hole') else 'top'+            plated = 0 if kind == 'np_thru_hole' else 1             crp = 0             if shape == 'roundrect':                 rr = first(n, 'roundrect_rratio')@@ -90,8 +108,9 @@ def convert(path, name=None, description=""):                 shape_a = 'oval'             else:                 shape_a = 'rect'-            out.append(f"PAD|{des}|{x:.4f}|{y:.4f}|{w:.4f}|{h:.4f}|{shape_a}|{hole:.3f}|{layer}|{crp}")-            stats['pads'] += 1; stats['th'] += (kind == 'thru_hole')+            out.append(f"PAD|{des}|{x:.4f}|{y:.4f}|{w:.4f}|{h:.4f}|{shape_a}|{hole:.3f}|{layer}|{crp}|{plated}|{slot:.3f}|{slot_rot:g}")+            stats['pads'] += 1; stats['th'] += (kind in ('thru_hole', 'np_thru_hole'))+            stats['npth'] += (kind == 'np_thru_hole'); stats['slots'] += (slot > 0)         elif k == 'fp_line':             lay = layer_of(n)             if not lay: continue