← Commit history
CHANGELOG.md+11
@@ -13,6 +13,17 @@   planning is Rust, unit-tested (connectivity with Altium's rules: T joins, crossings only at a dot, same-name labels).   Tested on Altium Develop: wire pin pairs, a three-pin bus fan-out with entries and labels, split, delete, label   edits, a region moved and back with every pin still on its net.+- **Sheets as a whole** (7 more verbs, the rest of the standard's batch 1): `sch_page` (paper, orientation, title+  block), `sch_create` (a new sheet, alone or as a project's child with its sheet symbol and the next page number),+  `sch_hierarchy` (the sheet tree from the files, without Altium; renumber pages depth-first), `sch_sheet_pins` (list,+  add, edit, delete, import from the child's ports, validate), `sch_reset_fields` (designator and comment back where the+  library symbol puts them), `sch_update_from_library` (re-place symbols from their library, refusing to drop a+  connected pin), `render_schematic` (a PNG of a sheet without a window: Altium's print to PDF, rendered by Windows;+  pixel baselines with drift, the changed region in mm and a diff image).+- The offline .SchDoc/.SchLib reader names nested streams by their storage (a SchLib's symbols each have a "Data"+  stream; flat names made them overwrite each other) and reads Altium's binary pin records.+- `fixtures/`: the lane and pair boards with the bridge's saved replies and expected check results, for the EDA+  Bridge Standard's shared checks engine (`ADOM_EDA_FIXTURES`). - `altium_bodies` (new): every part's 3D bodies as boxes in mm, the standard's bodies model (`{ref, side, x0, y0,   x1, y1, z0, z1}`), plus the parts with no body. The data `height_check` already read, now its own verb, so the   shared checks engine and other tools can read it.
README.md+11−4
@@ -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 -216 commands, tested on Altium Designer 26.11 and Altium Designer Develop. It runs in **Hydrogen**, Adom's free+223 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. 216 verbs; each row names the ones+Tested on Altium Designer 26.11.1 and Altium Designer Develop. 223 verbs; each row names the ones behind it (prefix `altium_`).  | Area | What the AI can do | Verbs |@@ -70,7 +70,7 @@ This bridge is the reference for the [EDA Bridge Standard](https://wiki.adom.inc  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 216 `altium_*` verbs.+**DelphiScript agent** inside it, and gives the AI 223 `altium_*` verbs.  - **Page and docs:** https://wiki.adom.inc/adom/altium-bridge - **Bridge SDK:** https://wiki.adom.inc/adom/adom-bridge-sdk@@ -170,7 +170,7 @@ way to read it). A stopped engine is restarted with `altium_agent_recover`.  <!-- verbs:start (tools/readme_verbs.py writes this list) --> -All 216 verbs, by area (prefix `altium_`). `altium_describe` returns the live catalog with every input, output, hint and example.+All 223 verbs, by area (prefix `altium_`). `altium_describe` returns the live catalog with every input, output, hint and example.  ### Running Altium: launch, close, health, dialogs @@ -325,6 +325,13 @@ All 216 verbs, by area (prefix `altium_`). `altium_describe` returns the live ca - `altium_sch_swap_part`: Replace a placed part with another library part (a different value, package or symbol) at the same place, designator and rotation, keeping its connections: where a new pin ends elsewhere, a wire joins it to where the old pin ended. - `altium_sch_connect`: Connect pins of placed parts: a wire stub from each pin's outer end plus a net label (kind label), a power port (kind power: GND-like nets get a ground symbol) or the stub alone (kind wire); or mark a pin left open on purpose with a No ERC marker (kind noerc, no net). - `altium_sch_edit`: Change placed parts on a sheet: move (to x,y mil), moveBy (dx,dy), rotate (degrees), rename (designator), re-comment (comment), delete.+- `altium_render_schematic`: Render a sheet to an image without opening a window, through the tool's own plotter, and keep visual baselines: baseline set stores the image, baseline compare reports the pixel drift, the changed region and a diff image.+- `altium_sch_page`: Read or set a sheet's page: paper size, orientation and title block (title, date, revision, company, comment lines).+- `altium_sch_create`: Create an empty schematic sheet with a paper size and title block; optionally add it to a project as a child sheet of the root.+- `altium_sch_hierarchy`: The sheet tree of a design, recursively: each sheet's name, file, id, instance path, page number, position, size and pins.+- `altium_sch_sheet_pins`: A sheet symbol's pins: list, add, edit (rename, kind, move along an edge) or delete.+- `altium_sch_reset_fields`: Put parts' designator and value text (or the named fields) back where the library symbol places them, through each part's rotation and mirror.+- `altium_sch_update_from_library`: Update the placed symbols on a sheet from their libraries (all, or the listed ones) and report which changed, which already matched and which no library has. - `altium_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. - `altium_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. - `altium_sch_trace_point`: Everything electrically connected at a point on a sheet: the wires, labels, pins, junctions, sheet pins and no-connect markers there, and for each net they belong to the whole net with its name.
bridge-rs/src/main.rs+1
@@ -13,6 +13,7 @@ mod sch; mod schdoc; mod schreview; mod schwire;+mod schsheet; mod design; mod dialogs; mod health;
bridge-rs/src/schdoc.rs+17−1
@@ -45,11 +45,27 @@ pub fn cfb_streams(b: &[u8]) -> Result<BTreeMap<String, Vec<u8>>, String> {         v     };     let dir = read(dir1, u64::MAX);-    let ents: Vec<(String, u8, u32, u64)> = dir.chunks(128).filter(|e| e.len() == 128).map(|e| {+    let mut ents: Vec<(String, u8, u32, u64)> = dir.chunks(128).filter(|e| e.len() == 128).map(|e| {         let nl = u16_at(e, 64).unwrap_or(0) as usize;         let units: Vec<u16> = (0..nl.saturating_sub(2) / 2).filter_map(|i| u16_at(e, i * 2)).collect();         (String::from_utf16_lossy(&units), e[66], u32_at(e, 0x74).unwrap_or(END), u64_at(e, 0x78).unwrap_or(0))     }).collect();+    // a stream inside a storage is named storage/stream (a SchLib keeps one "Data" stream per symbol storage; flat+    // names made them overwrite each other); top-level streams keep their bare name+    let links: Vec<(u32, u32, u32)> = dir.chunks(128).filter(|e| e.len() == 128).map(|e| (u32_at(e, 0x44).unwrap_or(END), u32_at(e, 0x48).unwrap_or(END), u32_at(e, 0x4C).unwrap_or(END))).collect();+    let mut stack: Vec<(u32, String)> = links.first().map(|l| vec![(l.2, String::new())]).unwrap_or_default();+    let mut seen = vec![false; ents.len()];+    while let Some((i, prefix)) = stack.pop() {+        let i = i as usize;+        if i >= ents.len() || seen[i] { continue; }+        seen[i] = true;+        let (l, r, c) = links[i];+        stack.push((l, prefix.clone()));+        stack.push((r, prefix.clone()));+        let full = if prefix.is_empty() { ents[i].0.clone() } else { format!("{prefix}/{}", ents[i].0) };+        if ents[i].1 == 1 { stack.push((c, full.clone())); }+        ents[i].0 = full;+    }     let root = ents.first().ok_or("no root entry")?;     let mini = read(root.2, root.3);     let mut minifat: Vec<u32> = Vec::new();
bridge-rs/src/schsheet.rsadded+761
@@ -0,0 +1,761 @@+//! Sheets as a whole, the rest of the EDA Bridge Standard's schematic batch 1 on Altium: the page and title block, a+//! new sheet (alone or as a child of a project's root), the sheet tree read from the files, sheet symbol pins, part+//! fields back where the library put them, and placed symbols updated from their libraries. Millimetres, y up.+use crate::sch::{agent_data, clean, maybe_save, st};+use crate::schdoc::{cfb_streams, records};+use crate::schwire::{self, apply, bad, dry, id_of, load, pts_arg, Sheet};+use crate::{agent, support};+use serde_json::{json, Value};+use std::collections::BTreeMap;+use std::path::{Path, PathBuf};+use std::time::Duration;++type Rec = BTreeMap<String, String>;++/// Altium's sheet styles (TSheetStyle order) and their size in mil, landscape.+const PAGES: &[(&str, i64, i64, i64)] = &[+    ("A4", 0, 11500, 7600), ("A3", 1, 15500, 11100), ("A2", 2, 22300, 15700), ("A1", 3, 31500, 22300), ("A0", 4, 44600, 31500),+    ("A", 5, 9500, 7500), ("B", 6, 15000, 9500), ("C", 7, 20000, 15000), ("D", 8, 32000, 20000), ("E", 9, 42000, 32000),+    ("USLetter", 10, 11000, 8500), ("USLegal", 11, 14000, 8500), ("USLedger", 12, 17000, 11000),+];++fn r2(v: f64) -> f64 { (v * 100.0).round() / 100.0 }++/// The title block's standard names and the Altium document parameters behind them.+const TITLE: &[(&str, &str)] = &[("title", "Title"), ("date", "Date"), ("rev", "Revision"), ("company", "CompanyName")];++fn doc_params(set: &[String]) -> Result<Vec<Value>, Value> {+    let r = agent::call("doc_params", &[("params", set.join(";"))], None, Duration::from_secs(60));+    let d = agent_data(&r)?;+    Ok(d["params"].as_array().cloned().unwrap_or_default())+}++fn title_block(params: &[Value]) -> Value {+    let get = |n: &str| params.iter().find(|p| st(&p["name"]).eq_ignore_ascii_case(n)).map(|p| st(&p["value"])).unwrap_or_default();+    let mut tb = serde_json::Map::new();+    for (k, n) in TITLE { tb.insert(k.to_string(), json!(get(n))); }+    let mut comments = Vec::new();+    for i in 1..=9 { let c = get(&format!("Comment{i}")); if c.is_empty() { break; } comments.push(json!(c)); }+    tb.insert("comments".into(), json!(comments));+    Value::Object(tb)+}++/// The page as the standard reports it: paper, size in mm, orientation.+fn page_of(sh: &Sheet) -> Value {+    let pg = &sh.page;+    let portrait = pg["orientation"].as_i64() == Some(1);+    let (name, w, h) = if pg["custom"].as_bool() == Some(true) {+        ("custom".to_string(), sh.mm(pg["cx"].as_i64().unwrap_or(0)), sh.mm(pg["cy"].as_i64().unwrap_or(0)))+    } else {+        let s = pg["style"].as_i64().unwrap_or(-1);+        match PAGES.iter().find(|p| p.1 == s) { Some(p) => (p.0.to_string(), r2(p.2 as f64 * 0.0254), r2(p.3 as f64 * 0.0254)), None => (format!("altium style {s}"), 0.0, 0.0) }+    };+    let (w, h) = if portrait { (w.min(h), w.max(h)) } else { (w.max(h), w.min(h)) };+    json!({"paper": name, "widthMm": w, "heightMm": h, "orientation": if portrait { "portrait" } else { "landscape" }})+}++/// The page step (A|style|custom|cx|cy|orientation) and the title block's parameters for page/create arguments.+fn page_changes(sh: &Sheet, args: &Value) -> Result<(Option<String>, Vec<String>), Value> {+    let mut step = None;+    let paper = args.get("paper").and_then(|v| v.as_str());+    let orient = args.get("orientation").and_then(|v| v.as_str());+    if paper.is_some() || orient.is_some() {+        let o = match orient { Some("portrait") => "1", Some("landscape") => "0", Some(x) => return Err(bad(format!("orientation {x}: portrait or landscape"))), None => "" };+        let (style, custom, cx, cy) = match paper {+            None => (String::new(), String::new(), String::new(), String::new()),+            Some(p) if p.eq_ignore_ascii_case("custom") || p.eq_ignore_ascii_case("A5") => {+                let (w, h) = if p.eq_ignore_ascii_case("A5") { (210.0, 148.0) } else {+                    match (args.get("widthMm").and_then(|v| v.as_f64()), args.get("heightMm").and_then(|v| v.as_f64())) { (Some(w), Some(h)) => (w, h), _ => return Err(bad("custom paper needs widthMm and heightMm")) }+                };+                (String::new(), "1".into(), sh.raw(w.max(h)).to_string(), sh.raw(w.min(h)).to_string())+            }+            Some(p) => match PAGES.iter().find(|x| x.0.eq_ignore_ascii_case(p) || (p.eq_ignore_ascii_case("Letter") && x.0 == "USLetter") || (p.eq_ignore_ascii_case("Tabloid") && x.0 == "USLedger")) {+                Some(x) => (x.1.to_string(), "0".into(), String::new(), String::new()),+                None => return Err(bad(format!("paper {p}: A4 to A0, A5, A to E, USLetter, USLegal, USLedger or custom"))),+            },+        };+        step = Some(format!("A|{style}|{custom}|{cx}|{cy}|{o}"));+    }+    let mut params = Vec::new();+    for (k, n) in TITLE { if let Some(v) = args.get(*k).and_then(|v| v.as_str()) { params.push(format!("{n}={}", clean(v).replace(';', ","))); } }+    if let Some(cs) = args.get("comments").and_then(|v| v.as_array()) {+        for (i, c) in cs.iter().enumerate() { params.push(format!("Comment{}={}", i + 1, clean(&st(c)).replace(';', ","))); }+    }+    Ok((step, params))+}++/// altium_sch_page {sheet, paper?, orientation?, widthMm?, heightMm?, title?, date?, rev?, company?, comments?, dryRun, save}+pub fn page(args: &Value) -> Value {+    let (sheet, sh) = match load(args) { Ok(x) => x, Err(e) => return e };+    let (step, params) = match page_changes(&sh, args) { Ok(x) => x, Err(e) => return e };+    let changed = step.is_some() || !params.is_empty();+    if dry(args) { return json!({"success": true, "dryRun": true, "sheet": sheet, "now": page_of(&sh), "pageStep": step, "set": params}); }+    if let Some(s) = &step { if let Err(e) = apply(args, &[s.clone()]) { return e; } }+    let ps = match doc_params(&params) { Ok(p) => p, Err(e) => return e };+    let sh2 = if step.is_some() { match load(args) { Ok((_, s)) => s, Err(e) => return e } } else { sh };+    let mut out = page_of(&sh2);+    out["success"] = json!(true); out["sheet"] = json!(sheet); out["titleBlock"] = title_block(&ps); out["changed"] = json!(changed);+    out["saved"] = if changed { maybe_save(args, &sheet) } else { json!(false) };+    out["_hint"] = json!("Altium's title block shows Title, Date, Revision and CompanyName through its special strings; comments are kept as parameters Comment1, Comment2... (a template shows them only if it has =Comment1 strings). Shrinking the paper moves nothing.");+    out+}++// -- reading sheet files without Altium ------------------------------------------------------------------------------++fn file_records(path: &str) -> Result<Vec<Rec>, String> {+    let b = std::fs::read(path).map_err(|e| format!("{path}: {e}"))?;+    let s = cfb_streams(&b)?;+    let fh = s.get("FileHeader").ok_or("no FileHeader stream")?;+    let recs = records(fh);+    Ok(if recs.first().map(|r| r.contains_key("HEADER")).unwrap_or(false) { recs[1..].to_vec() } else { recs })+}++fn num(r: &Rec, k: &str) -> i64 { r.get(k).and_then(|v| v.parse::<i64>().ok()).unwrap_or(0) }+/// mil from a 10-mil value and its _FRAC (1/100000 of one)+fn mil(r: &Rec, k: &str) -> f64 { (num(r, k) as f64 + num(r, &format!("{k}_FRAC")) as f64 / 100_000.0) * 10.0 }+fn mm(v: f64) -> f64 { (v * 0.0254 * 10000.0).round() / 10000.0 }++#[derive(Debug, Clone, Default)]+pub struct SymRec { pub name: String, pub file: String, pub at: (f64, f64), pub size: (f64, f64), pub entries: Vec<(String, i64, f64, i64)> }++/// Sheet symbols of a sheet file (record 15) with their name (32), file (33) and entries (16); mil. Pure.+pub fn sheet_symbols(recs: &[Rec]) -> Vec<SymRec> {+    let mut out = Vec::new();+    for (i, r) in recs.iter().enumerate() {+        if r.get("RECORD").map(|v| v.as_str()) != Some("15") { continue; }+        let mut s = SymRec { at: (mil(r, "LOCATION.X"), mil(r, "LOCATION.Y")), size: (mil(r, "XSIZE"), mil(r, "YSIZE")), ..Default::default() };+        for c in recs.iter().filter(|c| c.get("OWNERINDEX").and_then(|v| v.parse::<usize>().ok()) == Some(i)) {+            match c.get("RECORD").map(|v| v.as_str()) {+                Some("32") => s.name = c.get("TEXT").cloned().unwrap_or_default(),+                Some("33") => s.file = c.get("TEXT").cloned().unwrap_or_default(),+                Some("16") => s.entries.push((c.get("NAME").cloned().unwrap_or_default(), num(c, "SIDE"), mil(c, "DISTANCEFROMTOP"), num(c, "IOTYPE"))),+                _ => {}+            }+        }+        out.push(s);+    }+    out+}++/// The sheet's own parameter (record 41 without an owner part), e.g. SheetNumber.+pub fn sheet_param(recs: &[Rec], name: &str) -> Option<String> {+    recs.iter().find(|r| r.get("RECORD").map(|v| v.as_str()) == Some("41") && r.get("NAME").map(|n| n.eq_ignore_ascii_case(name)).unwrap_or(false)+        && r.get("OWNERINDEX").map(|o| o.parse::<i64>().unwrap_or(-1) < 0).unwrap_or(true)).and_then(|r| r.get("TEXT").cloned())+}++/// The ports of a sheet file (record 18): name and Altium IOType.+pub fn ports(recs: &[Rec]) -> Vec<(String, i64)> {+    recs.iter().filter(|r| r.get("RECORD").map(|v| v.as_str()) == Some("18")).map(|r| (r.get("NAME").cloned().unwrap_or_default(), num(r, "IOTYPE"))).collect()+}++fn kind_of(io: i64) -> &'static str { match io { 1 => "output", 2 => "input", 3 => "bidirectional", _ => "passive" } }+fn io_of(kind: &str) -> i64 { match kind { "output" => 1, "input" => 2, "bidirectional" | "tri_state" => 3, _ => 0 } }+fn side_name(s: i64) -> &'static str { match s { 1 => "right", 2 => "top", 3 => "bottom", _ => "left" } }+fn side_of(s: &str) -> i64 { match s { "right" => 1, "top" => 2, "bottom" => 3, _ => 0 } }++fn resolve(dir: &Path, f: &str) -> PathBuf { let p = Path::new(f); if p.is_absolute() || f.contains(':') { p.to_path_buf() } else { dir.join(f.replace('\\', "/").replace('/', std::path::MAIN_SEPARATOR_STR)) } }++/// A project's sheets (DocumentPath entries ending .SchDoc), absolute.+fn project_sheets(prj: &str) -> Result<Vec<String>, Value> {+    let text = std::fs::read(prj).map(|b| String::from_utf8_lossy(&b).to_string()).map_err(|e| json!({"success": false, "errorCode": "project_not_found", "error": format!("{prj}: {e}")}))?;+    let dir = Path::new(prj).parent().unwrap_or(Path::new(".")).to_path_buf();+    Ok(text.lines().filter_map(|l| l.trim().strip_prefix("DocumentPath=")).filter(|d| d.to_lowercase().ends_with(".schdoc")).map(|d| resolve(&dir, d).to_string_lossy().to_string()).collect())+}++/// The root sheet of a project: the sheet no sheet symbol points to.+fn project_root(prj: &str) -> Result<String, Value> {+    let sheets = project_sheets(prj)?;+    let mut children = std::collections::BTreeSet::new();+    for s in &sheets {+        let dir = Path::new(s).parent().unwrap_or(Path::new(".")).to_path_buf();+        if let Ok(r) = file_records(s) { for sy in sheet_symbols(&r) { children.insert(resolve(&dir, &sy.file).to_string_lossy().to_lowercase()); } }+    }+    sheets.iter().find(|s| !children.contains(&s.to_lowercase())).cloned().ok_or_else(|| json!({"success": false, "errorCode": "no_root", "error": "every sheet of the project is somebody's child: no root"}))+}++fn tree(file: &str, name: &str, path: &str, ancestors: &mut Vec<String>, problems: &mut Vec<Value>, order: &mut Vec<(String, String, Option<i64>)>, sym: Option<&SymRec>) -> Value {+    let mut node = json!({"name": name, "file": file, "id": format!("sheet-{}", &crate::routing::fnv(path)[..10]), "path": path});+    if let Some(s) = sym {+        node["at"] = json!([mm(s.at.0), mm(s.at.1)]);+        node["sizeMm"] = json!([mm(s.size.0), mm(s.size.1)]);+        node["pins"] = json!(s.entries.iter().map(|(n, _, _, io)| json!({"name": n, "kind": kind_of(*io)})).collect::<Vec<_>>());+    }+    if ancestors.iter().any(|a| a.eq_ignore_ascii_case(file)) { problems.push(json!({"sheet": path, "problem": "recursive"})); return node; }+    let recs = match file_records(file) {+        Ok(r) => r,+        Err(e) => { problems.push(json!({"sheet": path, "problem": if Path::new(file).exists() { "unreadable" } else { "missing" }, "detail": e})); return node; }+    };+    let page = sheet_param(&recs, "SheetNumber").and_then(|v| v.trim().parse::<i64>().ok());+    node["page"] = json!(page);+    order.push((file.to_string(), path.to_string(), page));+    ancestors.push(file.to_string());+    let dir = Path::new(file).parent().unwrap_or(Path::new(".")).to_path_buf();+    let kids: Vec<Value> = sheet_symbols(&recs).iter().map(|s| {+        let f = resolve(&dir, &s.file).to_string_lossy().to_string();+        tree(&f, &s.name, &format!("{path}/{}", s.name), ancestors, problems, order, Some(s))+    }).collect();+    ancestors.pop();+    node["children"] = json!(kids);+    node+}++/// altium_sch_hierarchy {sheet | project, renumber?, dryRun?}+pub fn hierarchy(args: &Value) -> Value {+    let root = match (support::s(args, "sheet"), support::s(args, "project").or_else(|| support::s(args, "projectPath"))) {+        (Some(s), _) => s,+        (None, Some(p)) => match project_root(&p) { Ok(r) => r, Err(e) => return e },+        _ => return bad("give sheet (the root sheet) or project"),+    };+    let stem = Path::new(&root).file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_default();+    let (mut problems, mut order) = (vec![], vec![]);+    let t = tree(&root, &stem, &format!("/{stem}"), &mut vec![], &mut problems, &mut order, None);+    let mut seen: BTreeMap<i64, usize> = BTreeMap::new();+    for (_, _, p) in &order { if let Some(p) = p { *seen.entry(*p).or_default() += 1; } }+    let dups: Vec<i64> = seen.iter().filter(|(_, n)| **n > 1).map(|(p, _)| *p).collect();+    let mut out = json!({"success": true, "root": root, "tree": [t], "problems": problems, "duplicatePages": dups,+        "_hint": "Read from the saved files, without Altium. A file used by two sheet symbols appears twice (one instance each). renumber:true writes SheetNumber depth-first from the root."});+    if args.get("renumber").and_then(|v| v.as_bool()) == Some(true) {+        // depth-first numbers; a file used twice keeps its first number+        let mut done: Vec<String> = Vec::new();+        let mut plan = Vec::new();+        for (f, path, page) in &order {+            if done.iter().any(|d| d.eq_ignore_ascii_case(f)) { continue; }+            done.push(f.clone());+            let want = done.len() as i64;+            if *page != Some(want) { plan.push((f.clone(), path.clone(), *page, want)); }+        }+        let renum: Vec<Value> = plan.iter().map(|(_, p, from, to)| json!({"sheet": p, "from": from, "to": to})).collect();+        out["renumbered"] = json!(renum);+        if !dry(args) {+            if let Some(g) = support::need_licensed() { return g; }+            for (f, _, _, to) in &plan {+                if let Some(e) = support::must_open(f, 60) { return e; }+                if let Err(e) = doc_params(&[format!("SheetNumber={to}"), format!("SheetTotal={}", done.len())]) { return e; }+                let _ = maybe_save(args, f);+            }+        } else { out["dryRun"] = json!(true); }+    }+    out+}++// -- sheet symbol pins -------------------------------------------------------------------------------------------------++/// altium_sch_sheet_pins {sheet, sheetSymbol?, action: list|add|edit|delete, name, kind, side, at, newName, import, validate, dryRun, save}+pub fn sheet_pins(args: &Value) -> Value {+    let (sheet, sh) = match load(args) { Ok(x) => x, Err(e) => return e };+    let dir = Path::new(&sheet).parent().unwrap_or(Path::new(".")).to_path_buf();+    let syms: Vec<&schwire::Item> = sh.items.iter().filter(|it| it.t == 'S').collect();+    let want = args.get("sheetSymbol").and_then(|v| v.as_str());+    let picked: Vec<&schwire::Item> = match want {+        Some(w) => syms.iter().filter(|s| s.text.eq_ignore_ascii_case(w) || id_of(&s.key) == w).cloned().collect(),+        None => syms.clone(),+    };+    if picked.is_empty() { return json!({"success": false, "errorCode": "not_found", "error": if syms.is_empty() { "no sheet symbol on this sheet".to_string() } else { format!("no sheet symbol {}", want.unwrap_or("")) }}); }+    let list = |s: &schwire::Item| -> Vec<Value> { s.entries.iter().map(|(n, side, dist, io)| json!({"id": format!("{}/{n}", id_of(&s.key)), "name": n, "kind": kind_of(*io), "side": side_name(*side), "at": sh.pt(schwire::entry_point(s, *side, *dist))})).collect() };+    let action = args.get("action").and_then(|v| v.as_str()).unwrap_or("list");+    let child_ports = |s: &schwire::Item| -> Result<Vec<(String, i64)>, String> { let f = resolve(&dir, &s.file); file_records(&f.to_string_lossy()).map(|r| ports(&r)) };+    // validate: every symbol's pins against its child's ports+    if args.get("validate").and_then(|v| v.as_bool()) == Some(true) {+        let mut problems = Vec::new();+        for s in &picked {+            match child_ports(s) {+                Err(e) => problems.push(json!({"sheetSymbol": s.text, "problem": "child_unreadable", "detail": e})),+                Ok(ps) => {+                    for (n, _, _, io) in &s.entries {+                        match ps.iter().find(|(p, _)| p.eq_ignore_ascii_case(n)) {+                            None => problems.push(json!({"sheetSymbol": s.text, "pin": n, "problem": "no_port"})),+                            Some((_, pio)) if *pio != *io && *io != 0 && *pio != 0 => problems.push(json!({"sheetSymbol": s.text, "pin": n, "problem": "kind_mismatch", "pinKind": kind_of(*io), "portKind": kind_of(*pio)})),+                            _ => {}+                        }+                    }+                    for (p, _) in &ps { if !s.entries.iter().any(|(n, ..)| n.eq_ignore_ascii_case(p)) { problems.push(json!({"sheetSymbol": s.text, "pin": p, "problem": "no_pin"})); } }+                }+            }+        }+        return json!({"success": true, "sheet": sheet, "problems": problems, "pins": picked.iter().flat_map(|s| list(s)).collect::<Vec<_>>(),+            "_hint": "no_port: a pin with no port of that name inside the child; no_pin: a port with no pin on the symbol (import:true adds them)."});+    }+    let import = args.get("import").and_then(|v| v.as_bool()) == Some(true);+    if action == "list" && !import { return json!({"success": true, "sheet": sheet, "pins": picked.iter().flat_map(|s| list(s)).collect::<Vec<_>>()}); }+    if picked.len() != 1 { return bad("name the sheet symbol (sheetSymbol: its name or id) to change its pins"); }+    let s = picked[0];+    let step = sh.raw(2.54);+    // the first free slot on a side, 2.54 mm apart from 2.54 mm in+    let free_slot = |side: i64, taken: &[(i64, i64)]| -> i64 {+        let len = if side >= 2 { s.w } else { s.h };+        (1..).map(|k| k * step).find(|d| *d >= len || !taken.iter().any(|(sd, t)| *sd == side && (t - d).abs() < step / 2)).unwrap_or(step)+    };+    let mut taken: Vec<(i64, i64)> = s.entries.iter().map(|(_, sd, d, _)| (*sd, *d)).collect();+    let snap = |at: (f64, f64), side: Option<i64>| -> (i64, i64) {+        let p = (sh.raw(at.0), sh.raw(at.1));+        // the nearest edge unless a side is given; distance from the top (left/right) or the left (top/bottom)+        let d = [(0, (p.0 - s.at.0).abs()), (1, (p.0 - s.at.0 - s.w).abs()), (2, (p.1 - s.at.1).abs()), (3, (p.1 - s.at.1 + s.h).abs())];+        let sd = side.unwrap_or_else(|| d.iter().min_by_key(|x| x.1).unwrap().0);+        let dist = if sd >= 2 { p.0 - s.at.0 } else { s.at.1 - p.1 };+        (sd, (dist as f64 / step as f64).round() as i64 * step)+    };+    let mut ops = Vec::new();+    let mut added = Vec::new();+    if import {+        let ps = match child_ports(s) { Ok(p) => p, Err(e) => return json!({"success": false, "errorCode": "child_unreadable", "error": e}) };+        for (p, io) in ps.iter().filter(|(p, _)| !s.entries.iter().any(|(n, ..)| n.eq_ignore_ascii_case(p))) {+            let side = if *io == 2 { 0 } else { 1 };+            let d = free_slot(side, &taken);+            taken.push((side, d));+            ops.push(format!("Y|{}|{}|{side}|{d}|{io}", s.key, clean(p)));+            added.push(json!(p));+        }+    } else {+        let name = clean(&st(&args["name"]));+        if name.is_empty() { return bad("name (the pin) is required"); }+        let kind = args.get("kind").and_then(|v| v.as_str());+        let side_arg = args.get("side").and_then(|v| v.as_str()).map(side_of);+        let at = args.get("at").and_then(pts_arg);+        match action {+            "add" => {+                if s.entries.iter().any(|(n, ..)| n.eq_ignore_ascii_case(&name)) { return json!({"success": false, "errorCode": "exists", "error": format!("{name} is already a pin of {}", s.text)}); }+                let io = io_of(kind.unwrap_or("passive"));+                let (sd, d) = match at { Some(a) => snap(a, side_arg), None => { let sd = side_arg.unwrap_or(if io == 2 { 0 } else { 1 }); (sd, free_slot(sd, &taken)) } };+                ops.push(format!("Y|{}|{name}|{sd}|{d}|{io}", s.key));+                added.push(json!(name));+            }+            "edit" => {+                if !s.entries.iter().any(|(n, ..)| n.eq_ignore_ascii_case(&name)) { return json!({"success": false, "errorCode": "not_found", "error": format!("no pin {name}")}); }+                let nn = args.get("newName").and_then(|v| v.as_str()).map(clean).unwrap_or_default();+                let (sd, d) = match at { Some(a) => { let (a1, b1) = snap(a, side_arg); (a1.to_string(), b1.to_string()) } None => (side_arg.map(|x| x.to_string()).unwrap_or_default(), String::new()) };+                ops.push(format!("Q|{}|{name}|{nn}|{sd}|{d}|{}", s.key, kind.map(|k| io_of(k).to_string()).unwrap_or_default()));+            }+            "delete" => ops.push(format!("Z|{}|{name}", s.key)),+            o => return bad(format!("action {o}: list, add, edit or delete")),+        }+    }+    if ops.is_empty() { return json!({"success": true, "sheet": sheet, "added": [], "pins": list(s), "_hint": "Nothing to do: every port of the child already has a pin."}); }+    if dry(args) { return json!({"success": true, "dryRun": true, "sheet": sheet, "steps": ops.len(), "added": added}); }+    let res = match apply(args, &ops) { Ok(r) => r, Err(e) => return e };+    let after = match load(args) { Ok((_, s2)) => s2, Err(e) => return e };+    let ns = after.items.iter().find(|it| it.t == 'S' && it.text == s.text && it.at == s.at);+    let pins: Vec<Value> = ns.map(|n| n.entries.iter().map(|(nm, side, dist, io)| json!({"id": format!("{}/{nm}", id_of(&n.key)), "name": nm, "kind": kind_of(*io), "side": side_name(*side), "at": after.pt(schwire::entry_point(n, *side, *dist))})).collect()).unwrap_or_default();+    json!({"success": schwire::failed(&res).is_empty(), "sheet": sheet, "pins": pins, "added": added, "failed": schwire::failed(&res), "saved": maybe_save(args, &sheet),+        "_hint": "A pin joins the child's port of the same name: wire it on this sheet at its at. Renaming a pin does not rename the port inside the child: check with validate:true."})+}++// -- part fields back where the library put them ------------------------------------------------------------------------++/// The library's designator and comment offsets (mil, from the symbol's origin), orientation and justification for+/// one symbol of a SchLib file. Pure over the file's streams.+pub fn lib_fields(streams: &BTreeMap<String, Vec<u8>>, libref: &str) -> Option<[(f64, f64, i64, i64); 2]> {+    for (name, data) in streams {+        if !name.ends_with("Data") { continue; }+        let recs = records(data);+        let Some(c) = recs.iter().find(|r| r.get("RECORD").map(|v| v.as_str()) == Some("1")) else { continue };+        if !c.get("LIBREFERENCE").map(|l| l.eq_ignore_ascii_case(libref)).unwrap_or(false) { continue; }+        let f = |rec: Option<&Rec>| rec.map(|r| (mil(r, "LOCATION.X"), mil(r, "LOCATION.Y"), num(r, "ORIENTATION"), num(r, "JUSTIFICATION"))).unwrap_or((0.0, 0.0, 0, 0));+        let des = recs.iter().find(|r| r.get("RECORD").map(|v| v.as_str()) == Some("34"));+        let cmt = recs.iter().find(|r| r.get("RECORD").map(|v| v.as_str()) == Some("41") && r.get("NAME").map(|n| n.eq_ignore_ascii_case("Comment")).unwrap_or(false));+        return Some([f(des), f(cmt)]);+    }+    None+}++/// An offset in the symbol's frame turned into the sheet's: mirrored in x first, then rotated by quarter turns.+pub fn place_offset(off: (f64, f64), rot: i64, mirror: bool) -> (f64, f64) {+    let (mut x, y) = off;+    if mirror { x = -x; }+    match rot.rem_euclid(4) { 1 => (-y, x), 2 => (-x, -y), 3 => (y, -x), _ => (x, y) }+}++/// The libraries to look a symbol up in: its own library path when that is a file, else every .SchLib beside the+/// sheet (Altium writes "*", any library, for parts placed from an open library).+fn candidate_libs(lib_path: &str, sheet: &str) -> Vec<String> {+    if !lib_path.is_empty() && lib_path != "*" && Path::new(lib_path).is_file() { return vec![lib_path.to_string()]; }+    let dir = Path::new(sheet).parent().unwrap_or(Path::new(".")).to_path_buf();+    let mut v: Vec<String> = std::fs::read_dir(&dir).map(|rd| rd.filter_map(|e| e.ok()).map(|e| e.path()).filter(|p| p.extension().map(|x| x.eq_ignore_ascii_case("schlib")).unwrap_or(false)).map(|p| p.to_string_lossy().to_string()).collect()).unwrap_or_default();+    v.sort();+    v+}++fn find_in_libs<T>(libs: &mut BTreeMap<String, Option<BTreeMap<String, Vec<u8>>>>, cands: &[String], f: impl Fn(&BTreeMap<String, Vec<u8>>) -> Option<T>) -> Option<(String, T)> {+    for c in cands {+        let streams = libs.entry(c.clone()).or_insert_with(|| std::fs::read(c).ok().and_then(|b| cfb_streams(&b).ok()));+        if let Some(t) = streams.as_ref().and_then(|s| f(s)) { return Some((c.clone(), t)); }+    }+    None+}++/// altium_sch_reset_fields {sheet, references? | all, fields?, dryRun, save}+pub fn reset_fields(args: &Value) -> Value {+    let (sheet, sh) = match load(args) { Ok(x) => x, Err(e) => return e };+    let all = args.get("all").and_then(|v| v.as_bool()) == Some(true);+    let refs: Vec<String> = args.get("references").and_then(|v| v.as_array()).map(|a| a.iter().map(|x| st(x).to_uppercase()).collect()).unwrap_or_default();+    if !all && refs.is_empty() { return bad("give references or all:true"); }+    let fields: Vec<String> = args.get("fields").and_then(|v| v.as_array()).map(|a| a.iter().map(|x| st(x).to_lowercase()).collect()).unwrap_or(vec!["designator".into(), "value".into()]);+    let mut libs: BTreeMap<String, Option<BTreeMap<String, Vec<u8>>>> = BTreeMap::new();+    let (mut ops, mut reset, mut fails) = (vec![], vec![], vec![]);+    for c in sh.comps.iter().filter(|c| all || refs.contains(&c.r.to_uppercase())) {+        let cands = candidate_libs(&c.lib_path, &sheet);+        let Some((_, fs)) = find_in_libs(&mut libs, &cands, |st| lib_fields(st, &c.lib)) else {+            fails.push(json!({"ref": c.r, "error": format!("{} is in none of {:?} (an integrated or database library part has no .SchLib to read)", c.lib, cands)}));+            continue;+        };+        for (k, (field, f)) in [("designator", fs[0]), ("comment", fs[1])].iter().enumerate() {+            let asked = fields.iter().any(|x| x == field || (*field == "comment" && x == "value"));+            if !asked { continue; }+            let _ = k;+            let (dx, dy) = place_offset((f.0, f.1), c.rot, c.mirror);+            let (x, y) = (c.at.0 + sh.raw(dx * 0.0254), c.at.1 + sh.raw(dy * 0.0254));+            ops.push(format!("F|{}|{field}|{x}|{y}|{}|{}", c.r, (f.2 + c.rot).rem_euclid(4), f.3));+            reset.push(json!({"ref": c.r, "field": if *field == "comment" { "value" } else { "designator" }, "at": sh.pt((x, y))}));+        }+    }+    if ops.is_empty() { return json!({"success": false, "errorCode": "nothing_to_do", "error": "no field could be reset", "failed": fails}); }+    if dry(args) { return json!({"success": true, "dryRun": true, "sheet": sheet, "reset": reset, "failed": fails}); }+    let res = match apply(args, &ops) { Ok(r) => r, Err(e) => return e };+    json!({"success": fails.is_empty() && schwire::failed(&res).is_empty(), "sheet": sheet, "reset": reset, "failed": fails, "stepsFailed": schwire::failed(&res), "saved": maybe_save(args, &sheet),+        "_hint": "Positions come from the symbol's library file (the part's library path), turned and mirrored with the part. Font and visibility are untouched."})+}++// -- placed symbols updated from their libraries ------------------------------------------------------------------------++fn lib_pins(streams: &BTreeMap<String, Vec<u8>>, libref: &str) -> Option<Vec<String>> {+    for (name, data) in streams {+        if !name.ends_with("Data") { continue; }+        let recs = records(data);+        let Some(c) = recs.iter().find(|r| r.get("RECORD").map(|v| v.as_str()) == Some("1")) else { continue };+        if !c.get("LIBREFERENCE").map(|l| l.eq_ignore_ascii_case(libref)).unwrap_or(false) { continue; }+        let mut pins: Vec<String> = recs.iter().filter(|r| r.get("RECORD").map(|v| v.as_str()) == Some("2")).filter_map(|r| r.get("DESIGNATOR").cloned()).collect();+        pins.extend(binary_pins(data).into_iter().map(|p| p.1));+        pins.sort(); pins.dedup();+        return Some(pins);+    }+    None+}++/// The pins a SchLib stores as binary records (record type 1): (name, designator). The layout (record id 2, flags,+/// owner part, edges, description, types, length, location, colour, then name and designator as length-prefixed+/// strings) is Altium's binary pin record. Pure.+pub fn binary_pins(data: &[u8]) -> Vec<(String, String)> {+    let mut out = Vec::new();+    let mut i = 0;+    let pstr = |b: &[u8], at: &mut usize| -> Option<String> { let n = *b.get(*at)? as usize; let s = b.get(*at + 1..*at + 1 + n)?; *at += 1 + n; Some(s.iter().map(|&c| c as char).collect()) };+    while i + 4 <= data.len() {+        let n = u32::from_le_bytes([data[i], data[i + 1], data[i + 2], data[i + 3]]);+        let (len, typ) = ((n & 0x00FF_FFFF) as usize, n >> 24);+        i += 4;+        let body = &data[i..(i + len).min(data.len())];+        i += len;+        if typ != 1 || body.len() < 12 || u32::from_le_bytes([body[0], body[1], body[2], body[3]]) != 2 { continue; }+        // 4 id, 1 unknown, 2 owner part, 1 display mode, 4 symbol edges+        let mut at = 12;+        let Some(_desc) = pstr(body, &mut at) else { continue };+        at += 3 + 2 + 2 + 2 + 4; // formal type, electrical, conglomerate; length; x; y; colour+        let (Some(name), Some(des)) = (pstr(body, &mut at), pstr(body, &mut at)) else { continue };+        out.push((name, des));+    }+    out+}++/// altium_sch_update_from_library {sheet, symbols?, library?, force?, dryRun, save}+pub fn update_from_library(args: &Value) -> Value {+    let (sheet, sh) = match load(args) { Ok(x) => x, Err(e) => return e };+    let only: Option<Vec<String>> = args.get("symbols").and_then(|v| v.as_array()).map(|a| a.iter().map(|x| st(x).to_uppercase()).collect());+    let lib_arg = support::s(args, "library");+    let force = args.get("force").and_then(|v| v.as_bool()) == Some(true);+    let g = schwire::graph(&sh);+    let nets = schwire::nets(&sh, &g);+    let connected = |pin: &str| nets.iter().any(|n| n["pins"].as_array().map(|a| a.iter().any(|x| st(x) == pin) && (a.len() > 1 || !n["labels"].as_array().map(|l| l.is_empty()).unwrap_or(true))).unwrap_or(false));+    let (mut changed, mut unchanged, mut not_found, mut refused, mut todo) = (vec![], vec![], vec![], vec![], vec![]);+    let mut libs: BTreeMap<String, Option<BTreeMap<String, Vec<u8>>>> = BTreeMap::new();+    for c in &sh.comps {+        if let Some(o) = &only { if !o.contains(&c.lib.to_uppercase()) && !o.contains(&c.r.to_uppercase()) { continue; } }+        let cands = match &lib_arg { Some(l) => vec![l.clone()], None => candidate_libs(&c.lib_path, &sheet) };+        let Some((lp, lpins)) = find_in_libs(&mut libs, &cands, |st| lib_pins(st, &c.lib)) else { not_found.push(json!({"symbol": c.lib, "ref": c.r, "searched": cands})); continue; };+        let mut placed: Vec<String> = sh.pins.iter().filter(|p| p.r == c.r).map(|p| p.num.clone()).collect();+        placed.sort(); placed.dedup();+        let added: Vec<&String> = lpins.iter().filter(|p| !placed.contains(p)).collect();+        let removed: Vec<&String> = placed.iter().filter(|p| !lpins.contains(p)).collect();+        let dropped: Vec<&String> = removed.iter().filter(|p| connected(&format!("{}.{}", c.r, p))).cloned().collect();+        if !dropped.is_empty() && !force { refused.push(json!({"symbol": c.lib, "ref": c.r, "droppedPins": dropped})); continue; }+        if added.is_empty() && removed.is_empty() && only.is_none() && lib_arg.is_none() { unchanged.push(json!({"symbol": c.lib, "ref": c.r})); continue; }+        changed.push(json!({"symbol": c.lib, "ref": c.r, "pinsAdded": added, "pinsRemoved": removed}));+        todo.push((c.r.clone(), lp, c.lib.clone()));+    }+    if dry(args) { return json!({"success": true, "dryRun": true, "sheet": sheet, "changed": changed, "unchanged": unchanged, "notFound": not_found, "refused": refused}); }+    let mut fails = Vec::new();+    for (r, lp, sym) in &todo {+        let res = crate::sch::swap_part(&json!({"sheet": sheet, "designator": r, "library": lp, "symbol": sym, "keepComment": true, "save": false}));+        if res.get("success").and_then(|b| b.as_bool()) != Some(true) { fails.push(json!({"ref": r, "error": res})); }+    }+    json!({"success": fails.is_empty(), "sheet": sheet, "changed": changed, "unchanged": unchanged, "notFound": not_found, "refused": refused, "failed": fails, "saved": maybe_save(args, &sheet),+        "_hint": "unchanged: the library symbol has the same pins (Altium cannot compare graphics from the sheet; name the symbols, or give library, to re-place them anyway). A changed symbol is re-placed from its library where it stood, keeping its designator and comment, with a wire from each moved pin's old end. Check with altium_compile."})+}++#[cfg(test)]+mod tests {+    use super::*;++    fn rec(kv: &[(&str, &str)]) -> Rec { kv.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect() }++    #[test]+    fn sheet_symbols_carry_their_name_file_and_entries() {+        let recs = vec![+            rec(&[("RECORD", "1")]),+            rec(&[("RECORD", "15"), ("LOCATION.X", "1000"), ("LOCATION.Y", "600"), ("XSIZE", "140"), ("YSIZE", "40")]),+            rec(&[("RECORD", "32"), ("OWNERINDEX", "1"), ("TEXT", "Power")]),+            rec(&[("RECORD", "33"), ("OWNERINDEX", "1"), ("TEXT", "Power.SchDoc")]),+            rec(&[("RECORD", "16"), ("OWNERINDEX", "1"), ("NAME", "VIN"), ("SIDE", "0"), ("DISTANCEFROMTOP", "10"), ("IOTYPE", "2")]),+            rec(&[("RECORD", "41"), ("NAME", "SheetNumber"), ("TEXT", "3")]),+        ];+        let s = sheet_symbols(&recs);+        assert_eq!(s.len(), 1);+        assert_eq!((s[0].name.as_str(), s[0].file.as_str()), ("Power", "Power.SchDoc"));+        assert_eq!(s[0].at, (10000.0, 6000.0));+        assert_eq!(s[0].size, (1400.0, 400.0));+        assert_eq!(s[0].entries, vec![("VIN".to_string(), 0, 100.0, 2)]);+        assert_eq!(sheet_param(&recs, "SheetNumber").as_deref(), Some("3"));+    }++    #[test]+    fn field_offsets_turn_and_mirror_with_the_part() {+        assert_eq!(place_offset((100.0, 50.0), 0, false), (100.0, 50.0));+        assert_eq!(place_offset((100.0, 50.0), 1, false), (-50.0, 100.0));+        assert_eq!(place_offset((100.0, 50.0), 2, false), (-100.0, -50.0));+        assert_eq!(place_offset((100.0, 50.0), 0, true), (-100.0, 50.0));+    }++    #[test]+    fn a_schlib_lists_its_symbols() {+        // a real SchLib when ADOM_SCHLIB names one, else skipped+        let Ok(p) = std::env::var("ADOM_SCHLIB") else { return };+        let st = cfb_streams(&std::fs::read(p).unwrap()).unwrap();+        for (n, d) in &st { let r = records(d); eprintln!("{n}: {} recs, first {:?}, binary pins {:?}", r.len(), r.first().map(|x| (x.get("RECORD"), x.get("LIBREFERENCE"))), binary_pins(d)); }+    }++    #[test]+    fn binary_pin_records_give_name_and_designator() {+        let mut body = vec![2, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0];+        body.push(0); // description+        body.extend([4, 4, 0, 30, 0, 0, 0, 0, 0, 0, 0, 0, 0]); // types (3), length, x, y (2 each), colour (4)+        body.push(4); body.extend(b"OUT1");+        body.push(1); body.extend(b"1");+        let mut data = ((body.len() as u32) | (1 << 24)).to_le_bytes().to_vec();+        data.extend(&body);+        assert_eq!(binary_pins(&data), vec![("OUT1".to_string(), "1".to_string())]);+    }++    #[test]+    fn kinds_round_trip() {+        for k in ["input", "output", "bidirectional", "passive"] { assert_eq!(kind_of(io_of(k)), k); }+        assert_eq!(kind_of(io_of("tri_state")), "bidirectional");+    }+}++/// altium_sch_create {sheet, paper?, orientation?, widthMm?, heightMm?, title.., comments?, project?, sheetName?, at?, dryRun}+pub fn create(args: &Value) -> Value {+    let Some(path) = support::s(args, "sheet").filter(|p| p.to_lowercase().ends_with(".schdoc")) else { return bad("sheet (the .SchDoc path to create) is required") };+    if Path::new(&path).exists() { return json!({"success": false, "errorCode": "exists", "error": format!("{path} exists: sch_create never overwrites")}); }+    let prj = support::s(args, "project").or_else(|| support::s(args, "projectPath"));+    let root = match &prj { Some(p) => match project_root(p) { Ok(r) => Some(r), Err(e) => return e }, None => None };+    // the next page number: one past the project's highest+    let page_no = match &prj {+        Some(p) => project_sheets(p).unwrap_or_default().iter().filter_map(|s| file_records(s).ok().and_then(|r| sheet_param(&r, "SheetNumber")).and_then(|v| v.trim().parse::<i64>().ok())).max().unwrap_or(1) + 1,+        None => 1,+    };+    let name = support::s(args, "sheetName").unwrap_or_else(|| Path::new(&path).file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_default());+    if dry(args) { return json!({"success": true, "dryRun": true, "sheet": path, "page": page_no, "root": root, "sheetName": name}); }+    if let Some(g) = support::need_licensed() { return g; }+    let tpl = match support::altium_public_file(r"Templates\ANSI B Landscape.SchDot") { Ok(p) => p, Err(e) => return json!({"success": false, "errorCode": "template_missing", "error": e}) };+    if let Err(e) = std::fs::copy(&tpl, &path) { return json!({"success": false, "errorCode": "write_failed", "error": format!("could not create {path}: {e}")}); }+    // page, title block and page number on the new sheet+    let mut a = args.clone();+    a["sheet"] = json!(path);+    a["dryRun"] = json!(false);+    let pg = page(&a);+    if pg.get("success").and_then(|b| b.as_bool()) != Some(true) { return json!({"success": false, "errorCode": "page_failed", "sheet": path, "reply": pg}); }+    if let Err(e) = doc_params(&[format!("SheetNumber={page_no}")]) { return e; }+    let _ = maybe_save(&json!({}), &path);+    let mut sym = Value::Null;+    if let (Some(p), Some(r)) = (&prj, &root) {+        if let Err(e) = crate::hier::add_to_project(p, &path) { return e; }+        let at = args.get("at").and_then(pts_arg);+        let mut sa = json!({"sheet": r, "child": path, "name": name, "entries": [], "ports": false, "projectPath": p});+        if let Some((x, y)) = at { sa["x"] = json!((x / 0.0254).round() as i64); sa["y"] = json!((y / 0.0254).round() as i64); }+        let ss = crate::hier::sheet_symbol(&sa);+        if ss.get("success").and_then(|b| b.as_bool()) != Some(true) { return json!({"success": false, "errorCode": "sheet_symbol_failed", "sheet": path, "reply": ss}); }+        let (_, rsh) = match load(&json!({"sheet": r})) { Ok(x) => x, Err(e) => return e };+        sym = rsh.items.iter().filter(|it| it.t == 'S' && it.text == name).last().map(|it| json!({"id": id_of(&it.key), "name": it.text, "at": rsh.pt(it.at)})).unwrap_or(Value::Null);+    }+    json!({"success": true, "sheet": path, "created": true, "page": page_no, "paper": pg["paper"], "sizeMm": [pg["widthMm"], pg["heightMm"]], "titleBlock": pg["titleBlock"], "sheetSymbol": sym, "root": root,+        "_hint": "Made from Altium's ANSI B Landscape template, then resized. A child sheet's symbol has no pins yet: put ports inside the child (altium_sch_connect kind port), then altium_sch_sheet_pins {import:true}."})+}++// -- a sheet as an image, without a window ---------------------------------------------------------------------------++/// PowerShell: render page 1 of a PDF to a PNG with Windows' own PDF renderer (Windows.Data.Pdf), then optionally+/// compare it with a baseline PNG pixel by pixel. Prints one JSON line.+const RENDER_PS: &str = r#"param([string]$Pdf, [string]$Png, [int]$Width, [int]$PageIndex = 0, [string]$Baseline = "", [string]$Diff = "")+$ErrorActionPreference = 'Stop'+Add-Type -AssemblyName System.Runtime.WindowsRuntime+$m = [System.WindowsRuntimeSystemExtensions].GetMethods()+$asOp = ($m | Where-Object { $_.Name -eq 'AsTask' -and $_.GetParameters().Count -eq 1 -and $_.GetParameters()[0].ParameterType.Name -eq 'IAsyncOperation`1' })[0]+$asAct = ($m | Where-Object { $_.Name -eq 'AsTask' -and $_.GetParameters().Count -eq 1 -and $_.GetParameters()[0].ParameterType.Name -eq 'IAsyncAction' })[0]+function Await($op, $t) { $k = $asOp.MakeGenericMethod($t).Invoke($null, @($op)); $k.Wait(-1) | Out-Null; $k.Result }+function AwaitAct($op) { $k = $asAct.Invoke($null, @($op)); $k.Wait(-1) | Out-Null }+[Windows.Storage.StorageFile, Windows.Storage, ContentType = WindowsRuntime] | Out-Null+[Windows.Storage.StorageFolder, Windows.Storage, ContentType = WindowsRuntime] | Out-Null+[Windows.Data.Pdf.PdfDocument, Windows.Data.Pdf, ContentType = WindowsRuntime] | Out-Null+$f = Await ([Windows.Storage.StorageFile]::GetFileFromPathAsync($Pdf)) ([Windows.Storage.StorageFile])+$doc = Await ([Windows.Data.Pdf.PdfDocument]::LoadFromFileAsync($f)) ([Windows.Data.Pdf.PdfDocument])+$pg = $doc.GetPage([Math]::Min($PageIndex, $doc.PageCount - 1))+$dir = Await ([Windows.Storage.StorageFolder]::GetFolderFromPathAsync([IO.Path]::GetDirectoryName($Png))) ([Windows.Storage.StorageFolder])+$out = Await ($dir.CreateFileAsync([IO.Path]::GetFileName($Png), [Windows.Storage.CreationCollisionOption]::ReplaceExisting)) ([Windows.Storage.StorageFile])+Add-Type -AssemblyName System.Drawing+function Render([int]$w) {+  $s = Await ($out.OpenAsync([Windows.Storage.FileAccessMode]::ReadWrite)) ([Windows.Storage.Streams.IRandomAccessStream])+  $s.Size = 0+  $o = New-Object Windows.Data.Pdf.PdfPageRenderOptions+  $o.DestinationWidth = $w+  AwaitAct ($pg.RenderToStreamAsync($s, $o))+  $s.Dispose()+  $b = [System.Drawing.Image]::FromFile($Png); $got = $b.Width; $b.Dispose(); $got+}+# Windows scales the destination by the display's scale factor (3000 px for 2000 at 150%): ask again, corrected+$got = Render $Width+if ($got -ne $Width) { $got = Render ([int][Math]::Round($Width * $Width / $got)) }+$renderer = "Windows.Data.Pdf " + [Environment]::OSVersion.Version.ToString()+if ($Baseline -eq "") { $b = [System.Drawing.Image]::FromFile($Png); "{""width"":$($b.Width),""height"":$($b.Height),""renderer"":""$renderer""}"; $b.Dispose(); exit 0 }+Add-Type -ReferencedAssemblies System.Drawing -TypeDefinition @"+using System; using System.Drawing; using System.Drawing.Imaging; using System.Runtime.InteropServices;+public static class AdomPxDiff {+  static int[] Px(Bitmap b) { var r = new Rectangle(0, 0, b.Width, b.Height); var d = b.LockBits(r, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); var a = new int[b.Width * b.Height]; Marshal.Copy(d.Scan0, a, 0, a.Length); b.UnlockBits(d); return a; }+  public static string Run(string now, string was, string diff) {+    var A = new Bitmap(now); var B = new Bitmap(was);+    if (A.Width != B.Width || A.Height != B.Height) { string s = "{\"width\":" + A.Width + ",\"height\":" + A.Height + ",\"driftPercent\":100,\"sizeChanged\":true}"; A.Dispose(); B.Dispose(); return s; }+    int w = A.Width, h = A.Height; var pa = Px(A); var pb = Px(B); var po = new int[w * h]; var po2 = new int[w * h]; var gr = new int[w * h];+    long n = 0; int x0 = w, y0 = h, x1 = -1, y1 = -1;+    for (int i = 0; i < pa.Length; i++) {+      int a = pa[i], c = pb[i];+      int d = Math.Max(Math.Abs(((a >> 16) & 255) - ((c >> 16) & 255)), Math.Max(Math.Abs(((a >> 8) & 255) - ((c >> 8) & 255)), Math.Abs((a & 255) - (c & 255))));+      int g = (((a >> 16) & 255) + ((a >> 8) & 255) + (a & 255)) / 3; g = 160 + g * 95 / 255;+      po[i] = d > 64 ? 1 : 0;+      gr[i] = g;+    }+    // a changed pixel counts when at least 3 of its 8 neighbours changed too: lone specks are anti-aliasing noise+    for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) {+      int i = y * w + x; int g = gr[i]; bool hit = false;+      if (po[i] == 1) { int k = 0; for (int dy = -1; dy <= 1; dy++) for (int dx = -1; dx <= 1; dx++) { int xx = x + dx, yy = y + dy; if ((dx != 0 || dy != 0) && xx >= 0 && yy >= 0 && xx < w && yy < h && (po[yy * w + xx] & 1) == 1) k++; } hit = k >= 3; }+      if (hit) { n++; if (x < x0) x0 = x; if (y < y0) y0 = y; if (x > x1) x1 = x; if (y > y1) y1 = y; }+      po2[i] = hit ? unchecked((int)0xFFFF0000) : unchecked((int)0xFF000000) | (g << 16) | (g << 8) | g;+    }+    var o = new Bitmap(w, h, PixelFormat.Format32bppArgb); var od = o.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); Marshal.Copy(po2, 0, od.Scan0, po2.Length); o.UnlockBits(od); o.Save(diff, ImageFormat.Png);+    o.Dispose(); A.Dispose(); B.Dispose();+    return "{\"width\":" + w + ",\"height\":" + h + ",\"changed\":" + n + ",\"driftPercent\":" + (100.0 * n / pa.Length).ToString("0.####", System.Globalization.CultureInfo.InvariantCulture) + (n > 0 ? ",\"box\":[" + x0 + "," + y0 + "," + x1 + "," + y1 + "]" : "") + "}";+  }+}+"@+$r = [AdomPxDiff]::Run($Png, $Baseline, $Diff)+$r.TrimEnd('}') + ",""renderer"":""$renderer""}"+"#;++fn powershell(script: &Path, args: &[String]) -> Result<Value, String> {+    let mut cmd = std::process::Command::new("powershell");+    cmd.args(["-NoProfile", "-ExecutionPolicy", "Bypass", "-File"]).arg(script).args(args);+    #[cfg(windows)]+    { use std::os::windows::process::CommandExt; cmd.creation_flags(0x0800_0000); }+    let o = cmd.output().map_err(|e| format!("powershell failed to start: {e}"))?;+    let out = String::from_utf8_lossy(&o.stdout).to_string();+    let line = out.lines().rev().find(|l| l.trim_start().starts_with('{')).ok_or_else(|| format!("no result: {} {}", out.trim(), String::from_utf8_lossy(&o.stderr).trim()))?;+    serde_json::from_str(line.trim()).map_err(|e| format!("{e}: {line}"))+}++/// altium_render_schematic {sheet, width?, outputDir?, baseline?: set|compare, threshold?}+pub fn render_schematic(args: &Value) -> Value {+    let (sheet, sh) = match load(args) { Ok(x) => x, Err(e) => return e };+    let width = args.get("width").and_then(|v| v.as_i64()).unwrap_or(2000).clamp(200, 10000);+    let stem = Path::new(&sheet).file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or("sheet".into());+    let dir = support::s(args, "outputDir").map(PathBuf::from).unwrap_or_else(|| Path::new(&sheet).parent().unwrap_or(Path::new(".")).join("render"));+    if let Err(e) = std::fs::create_dir_all(dir.join("baselines")) { return json!({"success": false, "errorCode": "write_failed", "error": format!("{}: {e}", dir.display())}); }+    // printed by Altium's own schematic print: through the sheet's own project when one beside it lists it (its title+    // block's fields resolve there, and the page is the sheet's place in the project), else a one-sheet project+    let tmp = std::env::temp_dir().join("adom-altium-render").join(format!("{}", (support::now() * 1000.0) as u64));+    if let Err(e) = std::fs::create_dir_all(&tmp) { return json!({"success": false, "errorCode": "temp_write_failed", "error": e.to_string()}); }+    let sdir = Path::new(&sheet).parent().unwrap_or(Path::new(".")).to_path_buf();+    let own = std::fs::read_dir(&sdir).ok().into_iter().flatten().filter_map(|e| e.ok()).map(|e| e.path())+        .filter(|p| p.extension().map(|x| x.eq_ignore_ascii_case("prjpcb")).unwrap_or(false))+        .find_map(|p| { let t = std::fs::read(&p).ok().map(|b| String::from_utf8_lossy(&b).to_string())?; let pr = crate::bom::parse_project(&t, &sdir);+            pr.sheets.iter().position(|x| x.eq_ignore_ascii_case(&sheet)).map(|i| (p.to_string_lossy().to_string(), i)) });+    let (prj, page_ix, temp_prj) = match own {+        Some((p, i)) => (p, i, false),+        None => {+            let p = tmp.join("AdomRender.PrjPcb");+            if let Err(e) = std::fs::write(&p, format!("[Design]\r\nVersion=1.0\r\nHierarchyMode=0\r\n\r\n[Document1]\r\nDocumentPath={sheet}\r\nAnnotationEnabled=1\r\n\r\n")) {+                return json!({"success": false, "errorCode": "temp_write_failed", "error": e.to_string()});+            }+            (p.to_string_lossy().to_string(), 0, true)+        }+    };+    let pdf = dir.join(format!("{stem}.pdf"));+    let print = || -> Result<(), Value> {+        let ex = crate::sch::export_pdf(&json!({"projectPath": prj, "output": pdf.to_string_lossy()}));+        if ex.get("success").and_then(|b| b.as_bool()) != Some(true) { return Err(json!({"success": false, "errorCode": "print_failed", "error": "Altium's schematic print wrote no PDF", "reply": ex})); }+        Ok(())+    };+    if let Err(e) = print() { return e; }+    let script = tmp.join("render.ps1");+    if let Err(e) = std::fs::write(&script, RENDER_PS) { return json!({"success": false, "errorCode": "temp_write_failed", "error": e.to_string()}); }+    let png = dir.join(format!("{stem}.png"));+    let base = dir.join("baselines").join(format!("{stem}-{width}.png"));+    let base_meta = base.with_extension("json");+    let mode = args.get("baseline").and_then(|v| v.as_str());+    let mut ps_args = vec!["-Pdf".to_string(), pdf.to_string_lossy().to_string(), "-Png".into(), png.to_string_lossy().to_string(), "-Width".into(), width.to_string(), "-PageIndex".into(), page_ix.to_string()];+    let diff_png = dir.join(format!("{stem}-diff.png"));+    if mode == Some("compare") {+        if !base.exists() { return json!({"success": false, "errorCode": "no_baseline", "error": format!("no baseline for {stem} at {width} px: set one with baseline:\"set\" first"), "baseline": base.to_string_lossy()}); }+        ps_args.extend(["-Baseline".into(), base.to_string_lossy().to_string(), "-Diff".into(), diff_png.to_string_lossy().to_string()]);+    }+    let mut r = match powershell(&script, &ps_args) { Ok(r) => r, Err(e) => return json!({"success": false, "errorCode": "render_failed", "error": e}) };+    // Altium's print now and then leaves the title block's special strings (=Title, sheet numbers) unfilled, which+    // reads as drift: a failed comparison prints once more and keeps the closer image+    let threshold = args.get("threshold").and_then(|v| v.as_f64()).unwrap_or(0.5);+    let mut reprinted = false;+    if mode == Some("compare") && r["driftPercent"].as_f64().unwrap_or(100.0) > threshold && r["sizeChanged"].as_bool() != Some(true) {+        if print().is_ok() {+            if let Ok(r2) = powershell(&script, &ps_args) {+                reprinted = true;+                if r2["driftPercent"].as_f64().unwrap_or(100.0) < r["driftPercent"].as_f64().unwrap_or(100.0) { r = r2; }+            }+        }+    }+    if temp_prj { let _ = agent::call("close_document", &[("path", prj.clone())], None, Duration::from_secs(30)); }+    let _ = std::fs::remove_dir_all(&tmp);+    let mut out = json!({"success": true, "sheet": sheet, "png": png.to_string_lossy(), "pdf": pdf.to_string_lossy(), "width": r["width"], "height": r["height"], "windowEtiquette": "background",+        "_hint": "Printed by Altium's own schematic print to PDF (no window), then rendered by Windows' PDF renderer. baseline:\"set\" keeps this image; baseline:\"compare\" reports the drift against it."});+    match mode {+        Some("set") => {+            if let Err(e) = std::fs::copy(&png, &base).and_then(|_| std::fs::write(&base_meta, json!({"renderer": r["renderer"], "width": width}).to_string())) { return json!({"success": false, "errorCode": "write_failed", "error": e.to_string()}); }+            out["baseline"] = json!(base.to_string_lossy());+        }+        Some("compare") => {+            let drift = r["driftPercent"].as_f64().unwrap_or(100.0);+            out["reprinted"] = json!(reprinted);+            let was = std::fs::read_to_string(&base_meta).ok().and_then(|t| serde_json::from_str::<Value>(&t).ok()).map(|v| v["renderer"].clone()).unwrap_or(Value::Null);+            out["driftPercent"] = json!(drift);+            out["pass"] = json!(drift <= threshold);+            out["threshold"] = json!(threshold);+            out["rendererChanged"] = json!(was != r["renderer"]);+            if r["changed"].as_i64().unwrap_or(0) > 0 { out["diffPng"] = json!(diff_png.to_string_lossy()); }+            // the changed pixels' box in sheet mm (the print fills the page: approximate)+            if let (Some(b), Some(w), Some(h)) = (r["box"].as_array(), r["width"].as_f64(), r["height"].as_f64()) {+                let pg = page_of(&sh);+                let (sw, shh) = (pg["widthMm"].as_f64().unwrap_or(0.0), pg["heightMm"].as_f64().unwrap_or(0.0));+                if sw > 0.0 {+                    let f = |i: usize| b.get(i).and_then(|v| v.as_f64()).unwrap_or(0.0);+                    out["changedRegionMm"] = json!([r2(f(0) / w * sw), r2((h - f(3)) / h * shh), r2(f(2) / w * sw), r2((h - f(1)) / h * shh)]);+                }+            }+            if r["sizeChanged"].as_bool() == Some(true) { out["sizeChanged"] = json!(true); }+        }+        Some(o) => return bad(format!("baseline {o}: set or compare")),+        None => {}+    }+    out+}
bridge-rs/src/schwire.rs+12−10
@@ -32,7 +32,7 @@ pub struct Item { pub struct Pin { pub r: String, pub num: String, pub name: String, pub elec: i64, pub at: P, pub dir: i64, pub hidden: bool }  #[derive(Debug, Clone, Default)]-pub struct Comp { pub r: String, pub at: P, pub lib: String }+pub struct Comp { pub r: String, pub at: P, pub lib: String, pub lib_path: String, pub rot: i64, pub mirror: bool, pub des: [i64; 4], pub cmt: [i64; 4] }  #[derive(Debug, Clone, Default)] pub struct Sheet { pub k: f64, pub items: Vec<Item>, pub pins: Vec<Pin>, pub comps: Vec<Comp>, pub page: Value, pub document: String }@@ -63,7 +63,9 @@ pub fn parse(d: &Value) -> Sheet {     for it in d["items"].as_array().cloned().unwrap_or_default() {         let t = st(&it["t"]).chars().next().unwrap_or('?');         if t == 'C' {-            sh.comps.push(Comp { r: st(&it["ref"]), at: (i(&it["x"]), i(&it["y"])), lib: st(&it["lib"]) });+            let f4 = |v: &Value| { let mut a = [0i64; 4]; for (k, x) in a.iter_mut().enumerate() { *x = i(&v[k]); } a };+            sh.comps.push(Comp { r: st(&it["ref"]), at: (i(&it["x"]), i(&it["y"])), lib: st(&it["lib"]), lib_path: st(&it["libPath"]),+                rot: i(&it["rot"]), mirror: it["mirror"].as_bool() == Some(true), des: f4(&it["des"]), cmt: f4(&it["cmt"]) });             continue;         }         let pts: Vec<P> = it["pts"].as_array().cloned().unwrap_or_default().iter().map(|p| (i(&p[0]), i(&p[1]))).collect();@@ -198,7 +200,7 @@ pub fn nets(sh: &Sheet, g: &Graph) -> Vec<Value> {  // -- the agent round trips ------------------------------------------------------------------------------------------ -fn load(args: &Value) -> Result<(String, Sheet), Value> {+pub(crate) fn load(args: &Value) -> Result<(String, Sheet), Value> {     if let Some(g) = support::need_licensed() { return Err(g); }     let sheet = need_sheet(args)?;     if let Some(e) = support::must_open(&sheet, 60) { return Err(e); }@@ -207,31 +209,31 @@ fn load(args: &Value) -> Result<(String, Sheet), Value> {     Ok((sheet, parse(&d))) } -fn apply(args: &Value, ops: &[String]) -> Result<Vec<Value>, Value> {+pub(crate) fn apply(args: &Value, ops: &[String]) -> Result<Vec<Value>, Value> {     if ops.is_empty() { return Ok(vec![]); }     let r = agent::call("sch_ops", &[], Some(&ops.join("\n")), timeout_of(args, 120));     let d = agent_data(&r)?;     Ok(d["results"].as_array().cloned().unwrap_or_default()) } -fn dry(args: &Value) -> bool { args.get("dryRun").and_then(|v| v.as_bool()) == Some(true) }+pub(crate) fn dry(args: &Value) -> bool { args.get("dryRun").and_then(|v| v.as_bool()) == Some(true) } -fn pts_arg(v: &Value) -> Option<(f64, f64)> { Some((v.get(0)?.as_f64()?, v.get(1)?.as_f64()?)) }+pub(crate) fn pts_arg(v: &Value) -> Option<(f64, f64)> { Some((v.get(0)?.as_f64()?, v.get(1)?.as_f64()?)) }  fn raw_pts(_sh: &Sheet, pts: &[P]) -> String { pts.iter().map(|p| format!("{},{}", p.0, p.1)).collect::<Vec<_>>().join(",") } -fn bad(msg: impl Into<String>) -> Value { json!({"success": false, "errorCode": "bad_args", "error": msg.into()}) }+pub(crate) fn bad(msg: impl Into<String>) -> Value { json!({"success": false, "errorCode": "bad_args", "error": msg.into()}) }  fn kind_name(t: char) -> &'static str {     match t { 'W' => "wire", 'B' => "bus", 'E' => "busEntry", 'J' => "junction", 'X' => "noConnect", 'N' => "label", 'P' => "port", 'O' => "powerPort", 'T' => "text", 'S' => "sheet", _ => "item" } } -fn by_id<'a>(sh: &'a Sheet, id: &str) -> Option<(usize, &'a Item)> { sh.items.iter().enumerate().find(|(_, it)| id_of(&it.key) == id) }+pub(crate) fn by_id<'a>(sh: &'a Sheet, id: &str) -> Option<(usize, &'a Item)> { sh.items.iter().enumerate().find(|(_, it)| id_of(&it.key) == id) }  /// Ids of the items a step created or changed, from the agent's per-step keys.-fn new_ids(results: &[Value]) -> Vec<Value> { results.iter().filter_map(|r| r["key"].as_str().filter(|k| !k.is_empty()).map(|k| json!(id_of(k)))).collect() }+pub(crate) fn new_ids(results: &[Value]) -> Vec<Value> { results.iter().filter_map(|r| r["key"].as_str().filter(|k| !k.is_empty()).map(|k| json!(id_of(k)))).collect() } -fn failed(results: &[Value]) -> Vec<Value> { results.iter().filter(|r| r["result"] != json!("ok")).cloned().collect() }+pub(crate) fn failed(results: &[Value]) -> Vec<Value> { results.iter().filter(|r| r["result"] != json!("ok")).cloned().collect() }  // -- verbs ---------------------------------------------------------------------------------------------------------- 
bridge-rs/src/verbs.rs+36−1
@@ -28,7 +28,7 @@ pub const KNOWN: &[&str] = &[     "show_symbol", "show_footprint", "show_3d_chip", "list_library", "demo",     "animate_view", "foreground",     // outputs / project-    "compile", "run_erc", "run_drc", "run_outjob", "export_gerber", "export_bom", "export_step", "bom", "variants", "workspace_search", "workspace_place", "sheet_params", "sch_place_part", "sch_swap_part", "sch_connect", "sch_edit", "sch_items", "sch_pins", "sch_trace_point", "sch_junction", "sch_bus", "sch_bus_entry", "sch_split_wire", "sch_delete_wire", "sch_edit_label", "sch_text", "sch_connect_pins", "sch_connect_to_bus", "sch_move_region", "sch_fix_connectivity", "annotate", "doc_params", "update_pcb", "export_pdf", "sch_zoom", "autoroute",+    "compile", "run_erc", "run_drc", "run_outjob", "export_gerber", "export_bom", "export_step", "bom", "variants", "workspace_search", "workspace_place", "sheet_params", "sch_place_part", "sch_swap_part", "sch_connect", "sch_edit", "render_schematic", "sch_page", "sch_create", "sch_hierarchy", "sch_sheet_pins", "sch_reset_fields", "sch_update_from_library", "sch_items", "sch_pins", "sch_trace_point", "sch_junction", "sch_bus", "sch_bus_entry", "sch_split_wire", "sch_delete_wire", "sch_edit_label", "sch_text", "sch_connect_pins", "sch_connect_to_bus", "sch_move_region", "sch_fix_connectivity", "annotate", "doc_params", "update_pcb", "export_pdf", "sch_zoom", "autoroute",     "save", "test_board", "board_shape", "pcb_report", "import_kicad",     "install_extension", "extension_ping",     // library authoring@@ -700,6 +700,34 @@ fn describe() -> Value {             json!({"sheet": "path to the schematic sheet file (required)", "toleranceMm": "number, default 0.5", "dryRun": "bool, default TRUE", "save": "bool, default true: save the sheet after the edit"}),             json!({"moves": "[{wireId, from, to, onto: {kind, id}, diagonal: bool}]", "unresolved": "[[x, y]]: dangling ends with nothing close", "saved": "bool"}), 120,             "Only dangling wire ends move. Read the moves before applying them: diagonal:true means the snapped wire is no longer horizontal or vertical. Check with run_erc after.", &["sch_trace_point", "run_erc"], &["dryRun defaults to true: nothing changes until dryRun:false.", "A wide tolerance can snap onto the wrong pin: keep it under half the sheet's grid."], json!({"sheet": "C:/proj/Power.SchDoc", "toleranceMm": 0.5, "dryRun": false})),+        verb_doc("sch_page", "Read or set a sheet's page: paper size, orientation and title block (title, date, revision, company, comment lines). Millimetres, the sheet's frame (y up).",+            json!({"sheet": "path to the schematic sheet file (required)", "paper": "A5 to A0, A to E, USLetter, USLegal, USLedger or custom", "orientation": "portrait|landscape", "widthMm": "number (custom paper)", "heightMm": "number (custom paper)", "title": "string", "date": "string", "rev": "string", "company": "string", "comments": "[string]: comment lines in order", "dryRun": "bool, default false: answer the plan and change nothing", "save": "bool, default true: save the sheet after the edit"}),+            json!({"paper": "string", "widthMm": "number", "heightMm": "number", "orientation": "string", "titleBlock": "{title, date, rev, company, comments}", "changed": "bool", "saved": "bool"}), 300,+            "With no change arguments it only reads. An empty string removes a title-block field. Each sheet of a hierarchy has its own page.", &[], &["Shrinking the paper moves nothing: items outside the new frame stay where they are (render_schematic shows it).", "Altium's title block shows Title, Date, Revision and CompanyName; comments are kept as parameters Comment1, Comment2... A5 has no Altium sheet style and is set as a custom size."], json!({"sheet": "C:/proj/Main.SchDoc", "paper": "A3", "title": "Main board", "rev": "B"})),+        verb_doc("sch_create", "Create an empty schematic sheet with a paper size and title block; optionally add it to a project as a child sheet of the root. It places no parts or nets (build_schematic does). Millimetres, the sheet's frame (y up).",+            json!({"sheet": "path of the sheet to create (required)", "paper": "A4, A3 ... USLetter or custom", "orientation": "portrait|landscape", "widthMm": "number (custom)", "heightMm": "number (custom)", "title": "string", "date": "string", "rev": "string", "company": "string", "comments": "[string]", "project": "path: add the sheet to this project under its root sheet", "sheetName": "string: the sheet symbol's name in the root", "at": "[x, y] mm: where the sheet symbol goes on the root", "dryRun": "bool, default false: answer the plan and change nothing"}),+            json!({"sheet": "path", "page": "int", "sheetSymbol": "{id, name, at} or null", "created": "bool"}), 300,+            "Without project the sheet stands alone. With project it is linked from the root sheet as a child sheet with the next page number.", &[], &["Never overwrites: an existing file is refused.", "A new child sheet has no pins on its symbol: add hierarchical ports inside, then sch_sheet_pins {import:true}.", "Made from Altium's ANSI B Landscape template and resized; the page number is one past the project's highest."], json!({"sheet": "C:/proj/Power.SchDoc", "project": "C:/proj/Board.PrjPcb", "sheetName": "Power", "title": "Power"})),+        verb_doc("sch_hierarchy", "The sheet tree of a design, recursively: each sheet's name, file, id, instance path, page number, position, size and pins. renumber:true renumbers pages depth-first from the root. Millimetres, the sheet's frame (y up).",+            json!({"sheet": "path to the root sheet", "project": "path to the project (instead of sheet)", "renumber": "bool, default false", "dryRun": "bool, default false: answer the plan and change nothing"}),+            json!({"tree": "[{name, file, id, path, page, at, sizeMm, pins: [{name, kind}], children: [...]}]", "problems": "[{sheet, problem: missing|unreadable|recursive}]", "duplicatePages": "[int]", "renumbered": "[{sheet, from, to}]"}), 300,+            "Pass the root sheet or the project. renumber writes only the numbers that change.", &[], &["A sheet file used by two sheet symbols appears twice in the tree (one instance each) but is one file.", "Read from the saved files without Altium: save open sheets first."], json!({"project": "C:/proj/Board.PrjPcb", "renumber": true})),+        verb_doc("sch_sheet_pins", "A sheet symbol's pins: list, add, edit (rename, kind, move along an edge) or delete. import:true adds a pin for every hierarchical port inside the child sheet that the symbol lacks; validate:true reports ports without pins, pins without ports and kind mismatches. Millimetres, the sheet's frame (y up).",+            json!({"sheet": "path to the parent sheet (required)", "sheetSymbol": "the sheet symbol's name or id (default: validate checks every one)", "action": "list|add|edit|delete, default list", "name": "string: the pin", "kind": "input|output|bidirectional|tri_state|passive", "side": "left|right|top|bottom", "at": "[x, y] mm: snapped to the nearest edge point", "newName": "string (edit)", "import": "bool", "validate": "bool", "dryRun": "bool, default false: answer the plan and change nothing", "save": "bool, default true: save the sheet after the edit"}),+            json!({"pins": "[{id, name, kind, side, at}]", "added": "[name]", "problems": "[{sheetSymbol, pin, problem: no_port|no_pin|kind_mismatch}]", "saved": "bool"}), 300,+            "Inputs go on the left edge and outputs on the right by default, in the first free slot. A pin joins the child's hierarchical port of the same name; wire it on the parent side at its at.", &[], &["Renaming a pin does not rename the port inside the child sheet: validate afterwards.", "A pin moved or deleted leaves its parent-side wire dangling.", "Altium has no tri-state or passive sheet entry: tri_state is stored as bidirectional, passive as unspecified."], json!({"sheet": "C:/proj/Main.SchDoc", "sheetSymbol": "Power", "import": true})),+        verb_doc("sch_reset_fields", "Put parts' designator and value text (or the named fields) back where the library symbol places them, through each part's rotation and mirror. One undo step. Millimetres, the sheet's frame (y up).",+            json!({"sheet": "path to the schematic sheet file (required)", "references": "[\"R5\", \"C3\"]", "all": "bool: every part on the sheet", "fields": "[designator, value] by default; other field names as the tool names them", "dryRun": "bool, default false: answer the plan and change nothing", "save": "bool, default true: save the sheet after the edit"}),+            json!({"reset": "[{ref, field}]", "saved": "bool"}), 300,+            "Font and visibility stay as they are; only position, angle and justification move.", &[], &["The library's offsets are what the symbol's author drew; the tool's automatic field placement may put them elsewhere.", "Positions come from the part's library file (its library path); parts from integrated or database libraries have none and are reported."], json!({"sheet": "C:/proj/Main.SchDoc", "references": ["R5", "C3"]})),+        verb_doc("sch_update_from_library", "Update the placed symbols on a sheet from their libraries (all, or the listed ones) and report which changed, which already matched and which no library has. Millimetres, the sheet's frame (y up).",+            json!({"sheet": "path to the schematic sheet file (required)", "symbols": "[library symbol name or id, ...] (default all)", "library": "path to one library to take them all from (with symbols)", "force": "bool, default false: update even when a placed pin would be dropped", "dryRun": "bool, default false: answer the plan and change nothing", "save": "bool, default true: save the sheet after the edit"}),+            json!({"changed": "[{symbol, pinsAdded, pinsRemoved}]", "unchanged": "[symbol]", "notFound": "[symbol]", "refused": "[{symbol, droppedPins}]", "saved": "bool"}), 300,+            "Run with dryRun first. A symbol whose new version drops a placed pin is refused unless force:true. Check the sheet afterwards with run_erc.", &[], &["A pin that moved in the library moves off its wire: check with sch_pins or run_erc after an update that reports changes.", "Altium cannot compare graphics from the sheet: a symbol with the same pins is reported unchanged unless named in symbols or library is given, which re-places it anyway."], json!({"sheet": "C:/proj/Main.SchDoc", "dryRun": true})),+        verb_doc("render_schematic", "Render a sheet to an image without opening a window, through the tool's own plotter, and keep visual baselines: baseline set stores the image, baseline compare reports the pixel drift, the changed region and a diff image.",+            json!({"sheet": "path to the schematic sheet file (required)", "width": "int px, default 2000", "outputDir": "folder for the image (default beside the project)", "baseline": "set|compare", "threshold": "percent of pixels, default 0.5 (compare)", "drawingSheet": "bool, default true: include the frame and title block"}),+            json!({"png": "path", "width": "int", "height": "int", "driftPercent": "number (compare)", "pass": "bool (compare)", "changedRegionMm": "[x1, y1, x2, y2] (compare)", "diffPng": "path: the changed pixels in red (compare)", "rendererChanged": "bool: the tool's plotter changed since the baseline"}), 400,+            "A sub-sheet renders with its real designators. compare renders at the baseline's width and passes when driftPercent <= threshold. show_* verbs open a window; this one does not.", &["export_pdf", "show_schematic"], &["Anti-aliasing differs between tool versions: rendererChanged:true means drift may not be a design change.", "A baseline is per sheet and per width; a paper size change reads as 100 percent drift.", "Altium prints the sheet to PDF (through its project when one beside it lists the sheet) and Windows renders it.", "Altium's print now and then leaves the title block's special strings (=Title, sheet numbers) unfilled; a failed comparison prints once more and keeps the closer image (reprinted:true), so drift confined to the title block is usually that."], json!({"sheet": "C:/proj/Power.SchDoc", "baseline": "compare"})),         verb_doc("sch_connect", "Connect pins of placed parts: a wire stub from each pin's outer end plus a net label (kind label), a power port (kind power: GND-like nets get a ground symbol) or the stub alone (kind wire); or mark a pin left open on purpose with a No ERC marker (kind noerc, no net). One undo step.",             json!({"sheet": "path to the .SchDoc (required)", "connections": "[{designator, pin (number or name), net, kind: label|power|wire|noerc|port (default label), io?: input|output|bidirectional (port), stubMil (default 200)}] (required)", "save": "bool, default true"}),             json!({"connected": "int", "results": "[{designator, pin, net, kind, result, endMil}]", "failed": "[..]", "saved": "bool"}), 90,@@ -1855,6 +1883,13 @@ pub fn dispatch(command: &str, args: &Value, _forwarded: &[(String, String)]) ->         "sheet_params" => crate::bom::sheet_params(args),         "sch_place_part" => crate::sch::place_part(args),         "sch_connect" => crate::sch::connect(args),+        "render_schematic" => crate::schsheet::render_schematic(args),+        "sch_page" => crate::schsheet::page(args),+        "sch_create" => crate::schsheet::create(args),+        "sch_hierarchy" => crate::schsheet::hierarchy(args),+        "sch_sheet_pins" => crate::schsheet::sheet_pins(args),+        "sch_reset_fields" => crate::schsheet::reset_fields(args),+        "sch_update_from_library" => crate::schsheet::update_from_library(args),         "sch_items" => crate::schwire::items(args),         "sch_pins" => crate::schwire::pins(args),         "sch_trace_point" => crate::schwire::trace_point(args),
fixtures/README.mdadded+23
@@ -0,0 +1,23 @@+# Fixtures: Altium boards and the bridge's replies, for the shared checks engine++The EDA Bridge Standard's checks engine (`adom-eda-checks`) proves it matches each bridge by running on that bridge's+own saved replies. Point `ADOM_EDA_FIXTURES` at this folder; the layout is the engine's:+`<bridge>/<board>.<model>.json` and `<bridge>/expected/<board>.<check>.json`.++From Altium bridge 0.2.76 on Altium Designer Develop (DESKTOP-BAR6S0F), 2026-10-27.++| File | What it is |+|---|---|+| `altium/lane.PcbDoc` | the lane test board: 40 x 20 mm with four rounded corners (arcs in the outline), 2 layers, three SOIC-8 test parts (U1 to U3, no 3D bodies) and R90 (0402 with a body); U3 and R90 sit off the board on purpose; 2 unconnected |+| `altium/pair.PcbDoc` | the differential-pair test board (no replies saved yet) |+| `altium/lane.routing_state.json` | the board model (`schema/board.schema.json`), with `isolatedCopper` |+| `altium/lane.layer_stack.json`, `lane.pour_state.json`, `lane.bodies.json` | the stack-up, poured copper and 3D body boxes |+| `altium/lane.read_rules.json`, `lane.silk_state.json` | the design rules (for the clearance rule) and the silkscreen |+| `altium/expected/lane.<check>.json` | what the bridge answers today: `fab_check`, `assembly_check`, `copper_balance`, `return_path`, `height_check`, `placement_check` (default arguments) |++Replies are saved as the bridge returned them, minus timing keys. Lane's `placement_check` is not ok on purpose (two+parts off the board); its `return_path` finds gaps.++The Bluetooth Sentinel, Altium's own example design, was used too (custom-shape pads, hatched pours, 73 parts with+bodies), but it is Altium's to publish, so it is not here: the same files can be made from any Altium install's+`Examples/Bluetooth Sentinel` board with the verbs above.
fixtures/altium/expected/lane.assembly_check.jsonadded+104
@@ -0,0 +1,104 @@+{+ "_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).",+ "agentResident": {+  "autoStopSec": 15,+  "note": "The agent loop is still running inside Altium, and while it runs Altium ignores the user's clicks. It stops by itself 15 s after the last verb; when you hand Altium back to the user, call altium_agent_stop."+ },+ "board": {+  "bottomSideParts": [],+  "fiducials": 1,+  "finestPitch": {+   "mm": 1.27,+   "ref": "U1"+  },+  "parts": 4,+  "smallestChip": {+   "padCentresMm": 1.0,+   "ref": "R90"+  },+  "throughHoleParts": [],+  "tinyFootprints": []+ },+ "bridgeVersion": "0.2.76",+ "economic": {+  "ok": false,+  "rules": [+   {+    "detail": "40 x 20 mm",+    "ok": true,+    "rule": "board 10 x 10 to 470 x 500 mm"+   },+   {+    "detail": "0.391 mm",+    "ok": false,+    "rule": "board 0.8 to 1.6 mm thick"+   },+   {+    "detail": "2 layers",+    "ok": true,+    "rule": "2, 4 or 6 layers"+   },+   {+    "detail": "all on top",+    "ok": true,+    "rule": "parts on one side only"+   },+   {+    "detail": "smallest two-pad part R90 (pad centres 1 mm)",+    "ok": true,+    "rule": "smallest package 0402"+   },+   {+    "detail": "finest 1.27 mm on U1",+    "ok": true,+    "rule": "IC pin pitch 0.4 mm or more (BGA 0.5 mm)"+   },+   {+    "detail": "not checked: pass projectPath",+    "ok": null,+    "rule": "every purchased part has an LCSC number"+   }+  ],+  "tier": "economic"+ },+ "fab": {+  "name": "JLCPCB",+  "read": "2026-10-26",+  "source": "https://jlcpcb.com/capabilities/pcb-assembly-capabilities"+ },+ "linesWithoutLcsc": null,+ "service": null,+ "standard": {+  "ok": false,+  "rules": [+   {+    "detail": "40 x 20 mm: a panel (altium_panelize) can bring it to 70 x 70",+    "ok": false,+    "rule": "board 70 x 70 to 460 x 500 mm"+   },+   {+    "detail": "smallest two-pad part R90 (pad centres 1 mm)",+    "ok": true,+    "rule": "smallest package 01005"+   },+   {+    "detail": "finest 1.27 mm on U1",+    "ok": true,+    "rule": "IC pin pitch 0.35 mm or more (BGA 0.3 mm)"+   },+   {+    "detail": "1 fiducial(s) on the board: add 3 (altium_board_features fiducials) or ship it in a panel with rails",+    "ok": false,+    "rule": "fiducials and edge rails"+   },+   {+    "detail": "not checked: pass projectPath",+    "ok": null,+    "rule": "every purchased part has an LCSC number"+   }+  ],+  "tier": "standard"+ },+ "success": true,+ "windowEtiquette": "background"+}\ No newline at end of file
fixtures/altium/expected/lane.copper_balance.jsonadded+40
@@ -0,0 +1,40 @@+{+ "_hint": "Mirrored layers carry similar copper: the stack should stay flat through reflow.",+ "agentResident": {+  "autoStopSec": 15,+  "note": "The agent loop is still running inside Altium, and while it runs Altium ignores the user's clicks. It stops by itself 15 s after the last verb; when you hand Altium back to the user, call altium_agent_stop."+ },+ "balanced": true,+ "boardMm2": 799.3,+ "bridgeVersion": "0.2.76",+ "layers": [+  {+   "copperMm2": 38.7,+   "layer": "F.Cu",+   "percent": 4.8+  },+  {+   "copperMm2": 17.9,+   "layer": "B.Cu",+   "percent": 2.2+  }+ ],+ "pairs": [+  {+   "differencePoints": 2.6,+   "layers": [+    "F.Cu",+    "B.Cu"+   ],+   "ok": true,+   "percent": [+    4.8,+    2.2+   ]+  }+ ],+ "poursWithoutRegions": [],+ "resolutionMm": 0.1,+ "success": true,+ "windowEtiquette": "background"+}\ No newline at end of file
fixtures/altium/expected/lane.fab_check.jsonadded+150
@@ -0,0 +1,150 @@+{+ "_hint": "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.",+ "agentResident": {+  "autoStopSec": 15,+  "note": "The agent loop is still running inside Altium, and while it runs Altium ignores the user's clicks. It stops by itself 15 s after the last verb; when you hand Altium back to the user, call altium_agent_stop."+ },+ "bridgeVersion": "0.2.76",+ "costlierOrBelowRecommended": [],+ "fab": null,+ "fits": null,+ "limitsChecked": [],+ "measured": {+  "boardSize": {+   "mm": [+    40.0,+    20.0+   ]+  },+  "clearanceRule": {+   "mm": 0.2+  },+  "copperLayers": 2,+  "counts": {+   "drilledPads": 4,+   "pads": 31,+   "tracks": 13,+   "vias": 4+  },+  "edgeClearance": {+   "at": [+    2.0,+    18.0+   ],+   "mm": 1.0,+   "pad": "MH4"+  },+  "holeToHolePad": {+   "at": [+    {+     "at": [+      2.0,+      2.0+     ],+     "pad": ".MH1"+    },+    {+     "at": [+      7.5,+      2.5+     ],+     "via": "GND"+    }+   ],+   "mm": 4.373+  },+  "holeToHoleVia": {+   "at": [+    {+     "at": [+      7.5,+      2.5+     ],+     "via": "GND"+    },+    {+     "at": [+      12.5,+      2.5+     ],+     "via": "GND"+    }+   ],+   "mm": 4.7+  },+  "largestDrill": {+   "at": {+    "at": [+     2.0,+     2.0+    ],+    "pad": ".MH1"+   },+   "mm": 2.0+  },+  "padHole": {+   "at": {+    "at": [+     2.0,+     18.0+    ],+    "pad": ".MH4"+   },+   "mm": 2.0+  },+  "smdPad": {+   "at": {+    "at": [+     185.58,+     26.289+    ],+    "pad": "U3.5"+   },+   "mm": 0.6+  },+  "track": {+   "at": {+    "from": [+     7.5184,+     2.5184+    ],+    "layer": "F.Cu",+    "net": "GND"+   },+   "mm": 0.3+  },+  "viaAnnularRing": {+   "at": {+    "at": [+     22.5,+     2.5+    ],+    "net": "GND"+   },+   "mm": 0.15+  },+  "viaDiameter": {+   "at": {+    "at": [+     22.5,+     2.5+    ],+    "net": "GND"+   },+   "mm": 0.6+  },+  "viaDrill": {+   "at": {+    "at": [+     22.5,+     2.5+    ],+    "net": "GND"+   },+   "mm": 0.3+  }+ },+ "outsideLimits": [],+ "success": true,+ "windowEtiquette": "background"+}\ No newline at end of file
fixtures/altium/expected/lane.height_check.jsonadded+51
@@ -0,0 +1,51 @@+{+ "_hint": "Heights are each part's tallest body above the surface it sits on (bottom-side parts below the bottom). collisions and tooClose compare body boxes; Altium's Component Clearance DRC (altium_run_drc) checks the real shapes. ok covers the parts that have bodies; complete is false while noBody lists parts with no 3D body and so no height: give them one (altium_add_body) before trusting the check.",+ "agentResident": {+  "autoStopSec": 15,+  "note": "The agent loop is still running inside Altium, and while it runs Altium ignores the user's clicks. It stops by itself 15 s after the last verb; when you hand Altium back to the user, call altium_agent_stop."+ },+ "bodies": 1,+ "bridgeVersion": "0.2.76",+ "collisions": [],+ "complete": false,+ "heights": [+  {+   "heightMm": 0.4,+   "rect": [+    188.193,+    26.018,+    188.743,+    27.068+   ],+   "ref": "R90",+   "side": "top"+  }+ ],+ "minGapMm": 0.0,+ "noBody": [+  "U3",+  "U2",+  "U1"+ ],+ "ok": true,+ "overLimit": [],+ "parts": 1,+ "regionHits": [],+ "success": true,+ "tallest": {+  "bottom": null,+  "top": {+   "heightMm": 0.4,+   "rect": [+    188.193,+    26.018,+    188.743,+    27.068+   ],+   "ref": "R90",+   "side": "top"+  }+ },+ "tooClose": [],+ "windowEtiquette": "background"+}\ No newline at end of file
fixtures/altium/expected/lane.placement_check.jsonadded+27
@@ -0,0 +1,27 @@+{+ "_hint": "courtyardOverlaps: parts closer than twice marginMm (their pads and bodies): move them apart (altium_move_parts, altium_find_space). offOrOverEdge parts must come onto the board; nearEdge pads risk the router or the V-cut (JLCPCB: 0.4 mm from a V-cut, 0.2 from a routed edge). onMountingHoles: a screw head lands on the part.",+ "agentResident": {+  "autoStopSec": 15,+  "note": "The agent loop is still running inside Altium, and while it runs Altium ignores the user's clicks. It stops by itself 15 s after the last verb; when you hand Altium back to the user, call altium_agent_stop."+ },+ "bridgeVersion": "0.2.76",+ "courtyardOverlaps": [],+ "edgeMm": 0.5,+ "marginMm": 0.1,+ "nearEdge": [],+ "offOrOverEdge": [+  {+   "ref": "R90",+   "where": "off the board"+  },+  {+   "ref": "U3",+   "where": "off the board"+  }+ ],+ "ok": false,+ "onMountingHoles": [],+ "parts": 4,+ "success": true,+ "windowEtiquette": "background"+}\ No newline at end of file
fixtures/altium/expected/lane.return_path.jsonadded+81
@@ -0,0 +1,81 @@+{+ "_hint": "Each row is a net whose tracks on that layer run over no pour or plane on either neighbouring layer for unreferencedMm (from firstGapAt). Its return current detours around the gap: more loop area, more emission and crosstalk. Close the gap (extend the pour: altium_apply_pours), route the net over solid copper, or add stitching capacitors or vias where it changes reference.",+ "agentResident": {+  "autoStopSec": 15,+  "note": "The agent loop is still running inside Altium, and while it runs Altium ignores the user's clicks. It stops by itself 15 s after the last verb; when you hand Altium back to the user, call altium_agent_stop."+ },+ "bridgeVersion": "0.2.76",+ "fix": null,+ "layersWithNoReferenceCopper": [],+ "nets": [+  {+   "firstGapAt": [+    7.518,+    2.568+   ],+   "gapRuns": [+    [+     7.336,+     2.509,+     7.518,+     8.095+    ],+    [+     22.535,+     2.535,+     31.651,+     8.095+    ]+   ],+   "layer": "F.Cu",+   "lengthMm": 17.339,+   "net": "GND",+   "percent": 100.0,+   "unreferencedMm": 17.339+  },+  {+   "firstGapAt": [+    7.55,+    2.5+   ],+   "gapRuns": [+    [+     7.55,+     2.5,+     22.45,+     2.5+    ]+   ],+   "layer": "B.Cu",+   "lengthMm": 15.0,+   "net": "GND",+   "percent": 100.0,+   "unreferencedMm": 15.0+  },+  {+   "firstGapAt": [+    12.75,+    11.905+   ],+   "gapRuns": [+    [+     12.75,+     11.905,+     26.25,+     11.905+    ]+   ],+   "layer": "F.Cu",+   "lengthMm": 13.6,+   "net": "N1",+   "percent": 100.0,+   "unreferencedMm": 13.6+  }+ ],+ "note": "No net owns a pour or a plane on this board: there is no reference copper, so every signal is reported. Pour GND (altium_apply_pours) or name referenceNets.",+ "ok": false,+ "referenceNets": [],+ "resolutionMm": 0.1,+ "success": true,+ "windowEtiquette": "background"+}\ No newline at end of file
fixtures/altium/lane.PcbDocadded
⋯ 1 unchanged line ⋯
fixtures/altium/lane.bodies.jsonadded+30
@@ -0,0 +1,30 @@+{+ "_hint": "One box per 3D body: x0..x1, y0..y1 in the board frame (mm, as altium_routing_state), z0..z1 above the surface the part sits on (a bottom part measures down from the bottom). A part made of several bodies has several boxes. noBody lists parts with no 3D body: give them one with altium_add_body. altium_height_check answers fit and clash questions from these boxes.",+ "agentResident": {+  "autoStopSec": 15,+  "note": "The agent loop is still running inside Altium, and while it runs Altium ignores the user's clicks. It stops by itself 15 s after the last verb; when you hand Altium back to the user, call altium_agent_stop."+ },+ "bodies": [+  {+   "ref": "R90",+   "side": "top",+   "x0": 188.193,+   "x1": 188.743,+   "y0": 26.018,+   "y1": 27.068,+   "z0": 0.0,+   "z1": 0.4+  }+ ],+ "bridgeVersion": "0.2.76",+ "count": 1,+ "model": "eda-bridge-standard/bodies",+ "noBody": [+  "U3",+  "U2",+  "U1"+ ],+ "success": true,+ "units": "mm",+ "windowEtiquette": "background"+}\ No newline at end of file
fixtures/altium/lane.layer_stack.jsonadded+53
@@ -0,0 +1,53 @@+{+ "_timing": {+  "inboxWaitMs": 0,+  "parseRetries": 0,+  "postedAtMs": 1,+  "responseSeenAtMs": 11,+  "totalMs": 22+ },+ "agentPhases": {+  "detectTick": 1161664406,+  "directExcept": 0,+  "directMs": 0,+  "directTries": 1,+  "dispatchMs": 0,+  "hbDeleteMs": 0,+  "hbRenameMs": 0,+  "hbSaveExcept": 0,+  "hbSaveMs": 0,+  "hbSaveTries": 1,+  "readMs": 0,+  "sleepMs": 10+ },+ "agentResident": {+  "autoStopSec": 15,+  "note": "The agent loop is still running inside Altium, and while it runs Altium ignores the user's clicks. It stops by itself 15 s after the last verb; when you hand Altium back to the user, call altium_agent_stop."+ },+ "bridgeVersion": "0.2.76",+ "command": "layer_stack",+ "data": {+  "copperLayers": 2,+  "layers": [+   {+    "copperUm": 36,+    "dielectricUm": 320,+    "dk1000": 4800,+    "kind": "signal",+    "material": "FR-4",+    "name": "Top Layer"+   },+   {+    "copperUm": 36,+    "kind": "signal",+    "name": "Bottom Layer"+   }+  ],+  "ok": true,+  "totalUm": 391+ },+ "id": "72566a9bfd10",+ "roundtripMs": 22,+ "success": true,+ "windowEtiquette": "background"+}\ No newline at end of file
fixtures/altium/lane.pour_state.jsonadded+14
@@ -0,0 +1,14 @@+{+ "_hint": "filledMm2 is the copper Altium poured (regions minus holes), not the outline area. A zone with filled:false poured nothing: an island removed as dead copper, or no connection to its net.",+ "agentResident": {+  "autoStopSec": 15,+  "note": "The agent loop is still running inside Altium, and while it runs Altium ignores the user's clicks. It stops by itself 15 s after the last verb; when you hand Altium back to the user, call altium_agent_stop."+ },+ "bridgeVersion": "0.2.76",+ "file": "C:\\Users\\olive\\Documents\\Adom\\panel-test\\lane.PcbDoc",+ "filledAreaByLayerMm2": {},+ "success": true,+ "unfilled": [],+ "windowEtiquette": "background",+ "zones": []+}\ No newline at end of file
fixtures/altium/lane.read_rules.jsonadded+439
@@ -0,0 +1,439 @@+{+ "_timing": {+  "inboxWaitMs": 0,+  "parseRetries": 0,+  "postedAtMs": 0,+  "responseSeenAtMs": 83,+  "totalMs": 96+ },+ "agentPhases": {+  "detectTick": 1165621718,+  "directExcept": 0,+  "directMs": 0,+  "directTries": 1,+  "dispatchMs": 78,+  "hbDeleteMs": 0,+  "hbRenameMs": 0,+  "hbSaveExcept": 0,+  "hbSaveMs": 0,+  "hbSaveTries": 1,+  "readMs": 0,+  "sleepMs": 10+ },+ "agentResident": {+  "autoStopSec": 15,+  "note": "The agent loop is still running inside Altium, and while it runs Altium ignores the user's clicks. It stops by itself 15 s after the last verb; when you hand Altium back to the user, call altium_agent_stop."+ },+ "bridgeVersion": "0.2.76",+ "command": "read_rules",+ "data": {+  "count": 40,+  "ok": true,+  "rules": [+   {+    "comment": "",+    "descriptor": "Supply Net(s)(InNet('GND'))",+    "enabled": true,+    "kind": 41,+    "name": "Schematic Supply Nets",+    "priority": 1,+    "scope1": "InNet('GND')",+    "scope2": "All"+   },+   {+    "comment": "",+    "descriptor": "Room Adom room BatCh1 (Bounding Region = (215.313mil, 246.613mil, 572.088mil, 540.789mil) (InComponentClass('BatCh1'))",+    "enabled": true,+    "kind": 22,+    "name": "Adom room BatCh1",+    "priority": 1,+    "scope1": "InComponentClass('BatCh1')",+    "scope2": "False"+   },+   {+    "comment": "net class BatteryPwr",+    "descriptor": "Clearance Constraint (Gap=9.842mil) (InNetClass('BatteryPwr')),(All)",+    "enabled": true,+    "kind": 0,+    "name": "Adom BatteryPwr clearance",+    "priority": 1,+    "scope1": "InNetClass('BatteryPwr')",+    "scope2": "All"+   },+   {+    "comment": "net class BatteryPwr",+    "descriptor": "Width Constraint (Min=11.811mil) (Max=196.85mil) (Preferred=11.811mil) (InNetClass('BatteryPwr'))",+    "enabled": true,+    "kind": 2,+    "name": "Adom BatteryPwr width",+    "priority": 1,+    "scope1": "InNetClass('BatteryPwr')",+    "scope2": "All"+   },+   {+    "comment": "",+    "descriptor": "Clearance Constraint (Gap=11.811mil) (InNet('N1')),(All)",+    "enabled": true,+    "kind": 0,+    "name": "Adom Battery",+    "priority": 2,+    "scope1": "InNet('N1')",+    "scope2": "All"+   },+   {+    "comment": "",+    "descriptor": "Modified Polygon (Allow modified: No), (Allow shelved: No)",+    "enabled": true,+    "kind": 62,+    "name": "UnpouredPolygon",+    "priority": 1,+    "scope1": "All",+    "scope2": "All"+   },+   {+    "comment": "",+    "descriptor": "Net Antennae (Tolerance=0mil) (All)",+    "enabled": true,+    "kind": 56,+    "name": "NetAntennae",+    "priority": 1,+    "scope1": "All",+    "scope2": "All"+   },+   {+    "comment": "",+    "descriptor": "Silk primitive without silk layer",+    "enabled": true,+    "kind": 59,+    "name": "SilkToBoardRegionClearance",+    "priority": 1,+    "scope1": "All",+    "scope2": "All"+   },+   {+    "comment": "",+    "descriptor": "Silk to Silk (Clearance=10mil) (All),(All)",+    "enabled": true,+    "kind": 55,+    "name": "SilkToSilkClearance",+    "priority": 1,+    "scope1": "All",+    "scope2": "All"+   },+   {+    "comment": "",+    "descriptor": "Silk To Solder Mask (Clearance=10mil) (IsPad),(All)",+    "enabled": true,+    "kind": 54,+    "name": "SilkToSolderMaskClearance",+    "priority": 1,+    "scope1": "IsPad",+    "scope2": "All"+   },+   {+    "comment": "",+    "descriptor": "Minimum Solder Mask Sliver (Gap=10mil) (All),(All)",+    "enabled": true,+    "kind": 53,+    "name": "MinimumSolderMaskSliver",+    "priority": 1,+    "scope1": "All",+    "scope2": "All"+   },+   {+    "comment": "",+    "descriptor": "Hole To Hole Clearance (Gap=9.842mil) (All),(All)",+    "enabled": true,+    "kind": 52,+    "name": "HoleToHoleClearance",+    "priority": 1,+    "scope1": "All",+    "scope2": "All"+   },+   {+    "comment": "",+    "descriptor": "Differential Pairs Uncoupled Length using the Gap Constraints (Min=10mil) (Max=10mil) (Prefered=10mil)  and Width Constraints (Min=15mil) (Max=15mil) (Prefered=15mil) (All)",+    "enabled": true,+    "kind": 51,+    "name": "DiffPairsRouting",+    "priority": 1,+    "scope1": "All",+    "scope2": "All"+   },+   {+    "comment": "Fanout_BGA (Default Rule)",+    "descriptor": "Fanout Control Rule ( (IsBGA) )",+    "enabled": true,+    "kind": 49,+    "name": "Fanout_BGA",+    "priority": 1,+    "scope1": "IsBGA",+    "scope2": "All"+   },+   {+    "comment": "Fanout_LCC (Default Rule)",+    "descriptor": "Fanout Control Rule ( (IsLCC) )",+    "enabled": true,+    "kind": 49,+    "name": "Fanout_LCC",+    "priority": 2,+    "scope1": "IsLCC",+    "scope2": "All"+   },+   {+    "comment": "Fanout_SOIC (Default Rule)",+    "descriptor": "Fanout Control Rule ( (IsSOIC) )",+    "enabled": true,+    "kind": 49,+    "name": "Fanout_SOIC",+    "priority": 3,+    "scope1": "IsSOIC",+    "scope2": "All"+   },+   {+    "comment": "Fanout_Small (Default Rule)",+    "descriptor": "Fanout Control Rule ( ((CompPinCount < 5)) )",+    "enabled": true,+    "kind": 49,+    "name": "Fanout_Small",+    "priority": 4,+    "scope1": "(CompPinCount < 5)",+    "scope2": "All"+   },+   {+    "comment": "Fanout_Default (Default Rule)",+    "descriptor": "Fanout Control Rule ( (All) )",+    "enabled": true,+    "kind": 49,+    "name": "Fanout_Default",+    "priority": 5,+    "scope1": "All",+    "scope2": "All"+   },+   {+    "comment": "",+    "descriptor": "Hole Size Constraint (Min=1mil) (Max=100mil) (All)",+    "enabled": true,+    "kind": 42,+    "name": "HoleSize",+    "priority": 1,+    "scope1": "All",+    "scope2": "All"+   },+   {+    "comment": "",+    "descriptor": "Pads and Vias to follow the Drill pairs settings",+    "enabled": true,+    "kind": 48,+    "name": "LayerPairs",+    "priority": 1,+    "scope1": "All",+    "scope2": "All"+   },+   {+    "comment": "",+    "descriptor": "Height Constraint (Min=0mil) (Max=1000mil) (Prefered=500mil) (All)",+    "enabled": true,+    "kind": 50,+    "name": "Height",+    "priority": 1,+    "scope1": "All",+    "scope2": "All"+   },+   {+    "comment": "",+    "descriptor": "Component Clearance Constraint ( Horizontal Gap = 10mil, Vertical Gap = 10mil ) (All),(All) ",+    "enabled": true,+    "kind": 24,+    "name": "ComponentClearance",+    "priority": 1,+    "scope1": "All",+    "scope2": "All"+   },+   {+    "comment": "",+    "descriptor": "Assembly Testpoint Style (Under Component=Yes) (All)",+    "enabled": true,+    "kind": 57,+    "name": "AssemblyTestpoint",+    "priority": 1,+    "scope1": "All",+    "scope2": "All"+   },+   {+    "comment": "",+    "descriptor": "Assembly Testpoint Usage (Valid =One Required, Allow multiple per net=No) (All)",+    "enabled": true,+    "kind": 58,+    "name": "AssemblyTestPointUsage",+    "priority": 1,+    "scope1": "All",+    "scope2": "All"+   },+   {+    "comment": "",+    "descriptor": "Fabrication Testpoint Style (Under Component=Yes) (All)",+    "enabled": true,+    "kind": 43,+    "name": "FabricationTestpoint",+    "priority": 1,+    "scope1": "All",+    "scope2": "All"+   },+   {+    "comment": "",+    "descriptor": "Fabrication Testpoint Usage (Valid =One Required, Allow multiple per net=No) (All)",+    "enabled": true,+    "kind": 44,+    "name": "FabricationTestPointUsage",+    "priority": 1,+    "scope1": "All",+    "scope2": "All"+   },+   {+    "comment": "",+    "descriptor": "Routing Topology Rule(Topology=Shortest) (All)",+    "enabled": true,+    "kind": 7,+    "name": "RoutingTopology",+    "priority": 1,+    "scope1": "All",+    "scope2": "All"+   },+   {+    "comment": "",+    "descriptor": "Solder Mask Expansion (Expansion =0mil) (All)",+    "enabled": true,+    "kind": 13,+    "name": "SolderMaskExpansion",+    "priority": 1,+    "scope1": "All",+    "scope2": "All"+   },+   {+    "comment": "",+    "descriptor": "Paste Mask Expansion (Expansion =0mil) (All)",+    "enabled": true,+    "kind": 14,+    "name": "PasteMaskExpansion",+    "priority": 1,+    "scope1": "All",+    "scope2": "All"+   },+   {+    "comment": "",+    "descriptor": "Routing Via (MinHoleWidth=28mil) (MaxHoleWidth=28mil) (PreferredHoleWidth=28mil) (MinWidth=50mil) (MaxWidth=50mil) (PreferedWidth=50mil) (All)",+    "enabled": true,+    "kind": 11,+    "name": "RoutingVias",+    "priority": 1,+    "scope1": "All",+    "scope2": "All"+   },+   {+    "comment": "",+    "descriptor": "Routing Corners (Style=45-Degree) (Min Setback=100mil) (Max Setback=100mil) (All)",+    "enabled": true,+    "kind": 10,+    "name": "RoutingCorners",+    "priority": 1,+    "scope1": "All",+    "scope2": "All"+   },+   {+    "comment": "",+    "descriptor": "Routing Layers(All)",+    "enabled": true,+    "kind": 9,+    "name": "RoutingLayers",+    "priority": 1,+    "scope1": "All",+    "scope2": "All"+   },+   {+    "comment": "",+    "descriptor": "TRoutingPriorityRule(Priority=0) (All)",+    "enabled": true,+    "kind": 8,+    "name": "RoutingPriority",+    "priority": 1,+    "scope1": "All",+    "scope2": "All"+   },+   {+    "comment": "",+    "descriptor": "Width Constraint (Min=5.906mil) (Max=78.74mil) (Preferred=9.842mil) (All)",+    "enabled": true,+    "kind": 2,+    "name": "Width",+    "priority": 2,+    "scope1": "All",+    "scope2": "All"+   },+   {+    "comment": "",+    "descriptor": "Polygon Connect Rule(Relief Connect )(Conductor Width=10mil) (Relief Angle=90 Angle) (Entries=4) (Air Gap Width=10mil) (All),(All)",+    "enabled": true,+    "kind": 20,+    "name": "PolygonConnect",+    "priority": 1,+    "scope1": "All",+    "scope2": "All"+   },+   {+    "comment": "",+    "descriptor": "Power Plane Clearance (Clearance =20mil) (All)",+    "enabled": true,+    "kind": 12,+    "name": "PlaneClearance",+    "priority": 1,+    "scope1": "All",+    "scope2": "All"+   },+   {+    "comment": "",+    "descriptor": "Power Plane Connect Rule(Relief Connect )(Expansion=20mil) (Conductor Width=10mil) (Air Gap=10mil) (Entries=4) (All)",+    "enabled": true,+    "kind": 6,+    "name": "PlaneConnect",+    "priority": 1,+    "scope1": "All",+    "scope2": "All"+   },+   {+    "comment": "",+    "descriptor": "Clearance Constraint (Gap=7.874mil) (All),(All)",+    "enabled": true,+    "kind": 0,+    "name": "Clearance",+    "priority": 3,+    "scope1": "All",+    "scope2": "All"+   },+   {+    "comment": "",+    "descriptor": "Un-Routed Net Constraint ( (All) )",+    "enabled": true,+    "kind": 16,+    "name": "UnRoutedNet",+    "priority": 1,+    "scope1": "All",+    "scope2": "All"+   },+   {+    "comment": "",+    "descriptor": "Short-Circuit Constraint (Allowed=No) (All),(All)",+    "enabled": true,+    "kind": 15,+    "name": "ShortCircuit",+    "priority": 1,+    "scope1": "All",+    "scope2": "All"+   }+  ]+ },+ "id": "75efcd4a8020",+ "roundtripMs": 96,+ "success": true,+ "windowEtiquette": "background"+}\ No newline at end of file
fixtures/altium/lane.routing_state.jsonadded+964
@@ -0,0 +1,964 @@+{+ "_hint": "mm, KiCad layer names (F.Cu/B.Cu/In<n>.Cu, *.Cu = multi-layer pad). Pass revision as expectedRevision to the edit verbs; unconnected is computed from the copper (altiumRatsnest is Altium's own count); isolatedCopper lists pours that reach nothing else of their net, not counted.",+ "agentResident": {+  "autoStopSec": 15,+  "note": "The agent loop is still running inside Altium, and while it runs Altium ignores the user's clicks. It stops by itself 15 s after the last verb; when you hand Altium back to the user, call altium_agent_stop."+ },+ "altiumRatsnest": 2,+ "arcs": [+  {+   "center": {+    "x": 1.0,+    "y": 1.0+   },+   "endAngle": 270.0,+   "layer": "L57",+   "layerId": 57,+   "net": "",+   "radius": 1.0,+   "startAngle": 180.0,+   "width": 0.1+  },+  {+   "center": {+    "x": 1.0,+    "y": 19.0+   },+   "endAngle": 180.0,+   "layer": "L57",+   "layerId": 57,+   "net": "",+   "radius": 1.0,+   "startAngle": 90.0,+   "width": 0.1+  },+  {+   "center": {+    "x": 39.0,+    "y": 19.0+   },+   "endAngle": 90.0,+   "layer": "L57",+   "layerId": 57,+   "net": "",+   "radius": 1.0,+   "startAngle": 0.0,+   "width": 0.1+  },+  {+   "center": {+    "x": 39.0,+    "y": 1.0+   },+   "endAngle": 360.0,+   "layer": "L57",+   "layerId": 57,+   "net": "",+   "radius": 1.0,+   "startAngle": 270.0,+   "width": 0.1+  }+ ],+ "boardId": "C:\\Users\\olive\\Documents\\Adom\\panel-test\\lane.PcbDoc",+ "bridgeVersion": "0.2.76",+ "components": [+  {+   "bodies": 0,+   "has3d": false,+   "pattern": "TST_SOIC8",+   "ref": "U3",+   "rotation": 0.0,+   "side": "top",+   "x": 182.88,+   "y": 28.194+  },+  {+   "bodies": 1,+   "has3d": true,+   "pattern": "RESC1005X40X25ML05T05",+   "ref": "R90",+   "rotation": 90.0,+   "side": "top",+   "x": 188.468,+   "y": 26.543+  },+  {+   "bodies": 0,+   "has3d": false,+   "pattern": "TST_SOIC8",+   "ref": "U2",+   "rotation": 0.0,+   "side": "top",+   "x": 29.0,+   "y": 10.0+  },+  {+   "bodies": 0,+   "has3d": false,+   "pattern": "TST_SOIC8",+   "ref": "U1",+   "rotation": 0.0,+   "side": "top",+   "x": 10.0,+   "y": 10.0+  }+ ],+ "counts": {+  "arcs": 4,+  "components": 4,+  "nets": 2,+  "pads": 31,+  "polygons": 0,+  "tracks": 13,+  "vias": 4+ },+ "file": "C:\\Users\\olive\\Documents\\Adom\\panel-test\\lane.PcbDoc",+ "isolatedCopper": [],+ "nets": [+  "GND",+  "N1"+ ],+ "outline": [+  [+   1.0,+   0.0+  ],+  [+   39.0,+   0.0+  ],+  [+   40.0,+   1.0+  ],+  [+   40.0,+   19.0+  ],+  [+   39.0,+   20.0+  ],+  [+   1.0,+   20.0+  ],+  [+   0.0,+   19.0+  ],+  [+   0.0,+   1.0+  ]+ ],+ "outlineEdges": [+  {+   "end": [+    39.0,+    0.0+   ],+   "kind": "line",+   "start": [+    1.0,+    0.0+   ]+  },+  {+   "angle1": 270.0,+   "angle2": 360.0,+   "center": [+    39.0,+    1.0+   ],+   "end": [+    40.0,+    1.0+   ],+   "kind": "arc",+   "radius": 1.0,+   "start": [+    39.0,+    0.0+   ]+  },+  {+   "end": [+    40.0,+    19.0+   ],+   "kind": "line",+   "start": [+    40.0,+    1.0+   ]+  },+  {+   "angle1": 0.0,+   "angle2": 90.0,+   "center": [+    39.0,+    19.0+   ],+   "end": [+    39.0,+    20.0+   ],+   "kind": "arc",+   "radius": 1.0,+   "start": [+    40.0,+    19.0+   ]+  },+  {+   "end": [+    1.0,+    20.0+   ],+   "kind": "line",+   "start": [+    39.0,+    20.0+   ]+  },+  {+   "angle1": 90.0,+   "angle2": 180.0,+   "center": [+    1.0,+    19.0+   ],+   "end": [+    0.0,+    19.0+   ],+   "kind": "arc",+   "radius": 1.0,+   "start": [+    1.0,+    20.0+   ]+  },+  {+   "end": [+    0.0,+    1.0+   ],+   "kind": "line",+   "start": [+    0.0,+    19.0+   ]+  },+  {+   "angle1": 180.0,+   "angle2": 270.0,+   "center": [+    1.0,+    1.0+   ],+   "end": [+    1.0,+    0.0+   ],+   "kind": "arc",+   "radius": 1.0,+   "start": [+    0.0,+    1.0+   ]+  }+ ],+ "pads": [+  {+   "drill": 0.0,+   "layer": "F.Cu",+   "layerId": 1,+   "name": "1",+   "net": "",+   "ref": "R90",+   "rotation": 180.0,+   "shape": "rect",+   "sizeX": 0.65,+   "sizeY": 0.65,+   "x": 188.468,+   "y": 26.043+  },+  {+   "drill": 0.0,+   "layer": "F.Cu",+   "layerId": 1,+   "name": "2",+   "net": "",+   "ref": "R90",+   "rotation": 180.0,+   "shape": "rect",+   "sizeX": 0.65,+   "sizeY": 0.65,+   "x": 188.468,+   "y": 27.043+  },+  {+   "drill": 0.0,+   "layer": "F.Cu",+   "layerId": 1,+   "name": "5",+   "net": "",+   "ref": "U3",+   "rotation": 0.0,+   "shape": "other",+   "sizeX": 1.55,+   "sizeY": 0.6,+   "x": 185.58,+   "y": 26.289+  },+  {+   "drill": 0.0,+   "layer": "F.Cu",+   "layerId": 1,+   "name": "6",+   "net": "",+   "ref": "U3",+   "rotation": 0.0,+   "shape": "other",+   "sizeX": 1.55,+   "sizeY": 0.6,+   "x": 185.58,+   "y": 27.559+  },+  {+   "drill": 0.0,+   "layer": "F.Cu",+   "layerId": 1,+   "name": "7",+   "net": "",+   "ref": "U3",+   "rotation": 0.0,+   "shape": "other",+   "sizeX": 1.55,+   "sizeY": 0.6,+   "x": 185.58,+   "y": 28.829+  },+  {+   "drill": 0.0,+   "layer": "F.Cu",+   "layerId": 1,+   "name": "8",+   "net": "",+   "ref": "U3",+   "rotation": 0.0,+   "shape": "other",+   "sizeX": 1.55,+   "sizeY": 0.6,+   "x": 185.58,+   "y": 30.099+  },+  {+   "drill": 0.0,+   "layer": "F.Cu",+   "layerId": 1,+   "name": "4",+   "net": "GND",+   "ref": "U3",+   "rotation": 0.0,+   "shape": "other",+   "sizeX": 1.55,+   "sizeY": 0.6,+   "x": 180.18,+   "y": 26.289+  },+  {+   "drill": 0.0,+   "layer": "F.Cu",+   "layerId": 1,+   "name": "3",+   "net": "",+   "ref": "U3",+   "rotation": 0.0,+   "shape": "other",+   "sizeX": 1.55,+   "sizeY": 0.6,+   "x": 180.18,+   "y": 27.559+  },+  {+   "drill": 0.0,+   "layer": "F.Cu",+   "layerId": 1,+   "name": "2",+   "net": "",+   "ref": "U3",+   "rotation": 0.0,+   "shape": "other",+   "sizeX": 1.55,+   "sizeY": 0.6,+   "x": 180.18,+   "y": 28.829+  },+  {+   "drill": 0.0,+   "layer": "F.Cu",+   "layerId": 1,+   "name": "1",+   "net": "N1",+   "ref": "U3",+   "rotation": 0.0,+   "shape": "other",+   "sizeX": 1.55,+   "sizeY": 0.6,+   "x": 180.18,+   "y": 30.099+  },+  {+   "drill": 0.0,+   "layer": "F.Cu",+   "layerId": 1,+   "name": "FID1",+   "net": "",+   "ref": "",+   "rotation": 0.0,+   "shape": "round",+   "sizeX": 1.0,+   "sizeY": 1.0,+   "x": 20.0,+   "y": 17.0+  },+  {+   "drill": 0.0,+   "layer": "F.Cu",+   "layerId": 1,+   "name": "5",+   "net": "GND",+   "ref": "U2",+   "rotation": 0.0,+   "shape": "other",+   "sizeX": 1.55,+   "sizeY": 0.6,+   "x": 31.7,+   "y": 8.095+  },+  {+   "drill": 0.0,+   "layer": "F.Cu",+   "layerId": 1,+   "name": "6",+   "net": "",+   "ref": "U2",+   "rotation": 0.0,+   "shape": "other",+   "sizeX": 1.55,+   "sizeY": 0.6,+   "x": 31.7,+   "y": 9.365+  },+  {+   "drill": 0.0,+   "layer": "F.Cu",+   "layerId": 1,+   "name": "7",+   "net": "",+   "ref": "U2",+   "rotation": 0.0,+   "shape": "other",+   "sizeX": 1.55,+   "sizeY": 0.6,+   "x": 31.7,+   "y": 10.635+  },+  {+   "drill": 0.0,+   "layer": "F.Cu",+   "layerId": 1,+   "name": "8",+   "net": "",+   "ref": "U2",+   "rotation": 0.0,+   "shape": "other",+   "sizeX": 1.55,+   "sizeY": 0.6,+   "x": 31.7,+   "y": 11.905+  },+  {+   "drill": 0.0,+   "layer": "F.Cu",+   "layerId": 1,+   "name": "4",+   "net": "",+   "ref": "U2",+   "rotation": 0.0,+   "shape": "other",+   "sizeX": 1.55,+   "sizeY": 0.6,+   "x": 26.3,+   "y": 8.095+  },+  {+   "drill": 0.0,+   "layer": "F.Cu",+   "layerId": 1,+   "name": "3",+   "net": "",+   "ref": "U2",+   "rotation": 0.0,+   "shape": "other",+   "sizeX": 1.55,+   "sizeY": 0.6,+   "x": 26.3,+   "y": 9.365+  },+  {+   "drill": 0.0,+   "layer": "F.Cu",+   "layerId": 1,+   "name": "2",+   "net": "",+   "ref": "U2",+   "rotation": 0.0,+   "shape": "other",+   "sizeX": 1.55,+   "sizeY": 0.6,+   "x": 26.3,+   "y": 10.635+  },+  {+   "drill": 0.0,+   "layer": "F.Cu",+   "layerId": 1,+   "name": "1",+   "net": "N1",+   "ref": "U2",+   "rotation": 0.0,+   "shape": "other",+   "sizeX": 1.55,+   "sizeY": 0.6,+   "x": 26.3,+   "y": 11.905+  },+  {+   "drill": 0.0,+   "layer": "F.Cu",+   "layerId": 1,+   "name": "5",+   "net": "",+   "ref": "U1",+   "rotation": 0.0,+   "shape": "other",+   "sizeX": 1.55,+   "sizeY": 0.6,+   "x": 12.7,+   "y": 8.095+  },+  {+   "drill": 0.0,+   "layer": "F.Cu",+   "layerId": 1,+   "name": "6",+   "net": "",+   "ref": "U1",+   "rotation": 0.0,+   "shape": "other",+   "sizeX": 1.55,+   "sizeY": 0.6,+   "x": 12.7,+   "y": 9.365+  },+  {+   "drill": 0.0,+   "layer": "F.Cu",+   "layerId": 1,+   "name": "7",+   "net": "",+   "ref": "U1",+   "rotation": 0.0,+   "shape": "other",+   "sizeX": 1.55,+   "sizeY": 0.6,+   "x": 12.7,+   "y": 10.635+  },+  {+   "drill": 0.0,+   "layer": "F.Cu",+   "layerId": 1,+   "name": "8",+   "net": "N1",+   "ref": "U1",+   "rotation": 0.0,+   "shape": "other",+   "sizeX": 1.55,+   "sizeY": 0.6,+   "x": 12.7,+   "y": 11.905+  },+  {+   "drill": 0.0,+   "layer": "F.Cu",+   "layerId": 1,+   "name": "4",+   "net": "GND",+   "ref": "U1",+   "rotation": 0.0,+   "shape": "other",+   "sizeX": 1.55,+   "sizeY": 0.6,+   "x": 7.3,+   "y": 8.095+  },+  {+   "drill": 0.0,+   "layer": "F.Cu",+   "layerId": 1,+   "name": "3",+   "net": "",+   "ref": "U1",+   "rotation": 0.0,+   "shape": "other",+   "sizeX": 1.55,+   "sizeY": 0.6,+   "x": 7.3,+   "y": 9.365+  },+  {+   "drill": 0.0,+   "layer": "F.Cu",+   "layerId": 1,+   "name": "2",+   "net": "",+   "ref": "U1",+   "rotation": 0.0,+   "shape": "other",+   "sizeX": 1.55,+   "sizeY": 0.6,+   "x": 7.3,+   "y": 10.635+  },+  {+   "drill": 0.0,+   "layer": "F.Cu",+   "layerId": 1,+   "name": "1",+   "net": "",+   "ref": "U1",+   "rotation": 0.0,+   "shape": "other",+   "sizeX": 1.55,+   "sizeY": 0.6,+   "x": 7.3,+   "y": 11.905+  },+  {+   "drill": 2.0,+   "layer": "*.Cu",+   "layerId": 74,+   "name": "MH4",+   "net": "",+   "ref": "",+   "rotation": 0.0,+   "shape": "round",+   "sizeX": 2.0,+   "sizeY": 2.0,+   "x": 2.0,+   "y": 18.0+  },+  {+   "drill": 2.0,+   "layer": "*.Cu",+   "layerId": 74,+   "name": "MH3",+   "net": "",+   "ref": "",+   "rotation": 0.0,+   "shape": "round",+   "sizeX": 2.0,+   "sizeY": 2.0,+   "x": 38.0,+   "y": 18.0+  },+  {+   "drill": 2.0,+   "layer": "*.Cu",+   "layerId": 74,+   "name": "MH2",+   "net": "",+   "ref": "",+   "rotation": 0.0,+   "shape": "round",+   "sizeX": 2.0,+   "sizeY": 2.0,+   "x": 38.0,+   "y": 2.0+  },+  {+   "drill": 2.0,+   "layer": "*.Cu",+   "layerId": 74,+   "name": "MH1",+   "net": "",+   "ref": "",+   "rotation": 0.0,+   "shape": "round",+   "sizeX": 2.0,+   "sizeY": 2.0,+   "x": 2.0,+   "y": 2.0+  }+ ],+ "polygons": [],+ "revision": "1784449c0b309767",+ "roundtripMs": 67,+ "splitNets": [+  {+   "groups": 2,+   "net": "GND"+  },+  {+   "groups": 2,+   "net": "N1"+  }+ ],+ "success": true,+ "tracks": [+  {+   "end": {+    "x": 0.0,+    "y": 19.0+   },+   "layer": "L57",+   "layerId": 57,+   "net": "",+   "start": {+    "x": 0.0,+    "y": 1.0+   },+   "width": 0.1+  },+  {+   "end": {+    "x": 39.0,+    "y": 20.0+   },+   "layer": "L57",+   "layerId": 57,+   "net": "",+   "start": {+    "x": 1.0,+    "y": 20.0+   },+   "width": 0.1+  },+  {+   "end": {+    "x": 40.0,+    "y": 19.0+   },+   "layer": "L57",+   "layerId": 57,+   "net": "",+   "start": {+    "x": 40.0,+    "y": 1.0+   },+   "width": 0.1+  },+  {+   "end": {+    "x": 39.0,+    "y": 0.0+   },+   "layer": "L57",+   "layerId": 57,+   "net": "",+   "start": {+    "x": 1.0,+    "y": 0.0+   },+   "width": 0.1+  },+  {+   "end": {+    "x": 7.5184,+    "y": 8.095+   },+   "layer": "F.Cu",+   "layerId": 1,+   "net": "GND",+   "start": {+    "x": 7.5184,+    "y": 2.5184+   },+   "width": 0.3+  },+  {+   "end": {+    "x": 31.7,+    "y": 8.095+   },+   "layer": "F.Cu",+   "layerId": 1,+   "net": "GND",+   "start": {+    "x": 28.0949,+    "y": 8.095+   },+   "width": 0.3+  },+  {+   "end": {+    "x": 28.0949,+    "y": 8.095+   },+   "layer": "F.Cu",+   "layerId": 1,+   "net": "GND",+   "start": {+    "x": 22.5,+    "y": 2.5+   },+   "width": 0.3+  },+  {+   "end": {+    "x": 7.5184,+    "y": 2.5184+   },+   "layer": "F.Cu",+   "layerId": 1,+   "net": "GND",+   "start": {+    "x": 7.5,+    "y": 2.5+   },+   "width": 0.3+  },+  {+   "end": {+    "x": 7.5184,+    "y": 8.095+   },+   "layer": "F.Cu",+   "layerId": 1,+   "net": "GND",+   "start": {+    "x": 7.3,+    "y": 8.095+   },+   "width": 0.3+  },+  {+   "end": {+    "x": 26.3,+    "y": 11.905+   },+   "layer": "F.Cu",+   "layerId": 1,+   "net": "N1",+   "start": {+    "x": 12.7,+    "y": 11.905+   },+   "width": 0.3+  },+  {+   "end": {+    "x": 12.5,+    "y": 2.5+   },+   "layer": "B.Cu",+   "layerId": 32,+   "net": "GND",+   "start": {+    "x": 7.5,+    "y": 2.5+   },+   "width": 0.3+  },+  {+   "end": {+    "x": 17.5,+    "y": 2.5+   },+   "layer": "B.Cu",+   "layerId": 32,+   "net": "GND",+   "start": {+    "x": 12.5,+    "y": 2.5+   },+   "width": 0.3+  },+  {+   "end": {+    "x": 22.5,+    "y": 2.5+   },+   "layer": "B.Cu",+   "layerId": 32,+   "net": "GND",+   "start": {+    "x": 17.5,+    "y": 2.5+   },+   "width": 0.3+  }+ ],+ "unconnected": 2,+ "units": "mm",+ "vias": [+  {+   "drill": 0.3,+   "layers": [+    "F.Cu",+    "B.Cu"+   ],+   "net": "GND",+   "position": {+    "x": 22.5,+    "y": 2.5+   },+   "size": 0.6+  },+  {+   "drill": 0.3,+   "layers": [+    "F.Cu",+    "B.Cu"+   ],+   "net": "GND",+   "position": {+    "x": 17.5,+    "y": 2.5+   },+   "size": 0.6+  },+  {+   "drill": 0.3,+   "layers": [+    "F.Cu",+    "B.Cu"+   ],+   "net": "GND",+   "position": {+    "x": 12.5,+    "y": 2.5+   },+   "size": 0.6+  },+  {+   "drill": 0.3,+   "layers": [+    "F.Cu",+    "B.Cu"+   ],+   "net": "GND",+   "position": {+    "x": 7.5,+    "y": 2.5+   },+   "size": 0.6+  }+ ],+ "windowEtiquette": "background"+}\ No newline at end of file
fixtures/altium/lane.silk_state.jsonadded+203
@@ -0,0 +1,203 @@+{+ "_hint": "mm, Altium's frame (y up). A text's x,y is its own location (lower left of the text before rotation); box is what Altium measures. texts/lines are the free overlay items, not a part's own.",+ "agentResident": {+  "autoStopSec": 15,+  "note": "The agent loop is still running inside Altium, and while it runs Altium ignores the user's clicks. It stops by itself 15 s after the last verb; when you hand Altium back to the user, call altium_agent_stop."+ },+ "bridgeVersion": "0.2.76",+ "components": [+  {+   "body": [+    179.105,+    25.419,+    186.655,+    31.004+   ],+   "comment": {+    "box": [+     179.1081,+     22.8727,+     189.7728,+     24.9042+    ],+    "rotation": 0,+    "shown": false,+    "size": 1.524,+    "text": "BATTERY",+    "x": 179.3621,+    "y": 23.1267+   },+   "name": {+    "box": [+     179.1081,+     31.5087,+     182.1553,+     33.5402+    ],+    "rotation": 0,+    "shown": true,+    "size": 1.524,+    "text": "U3",+    "x": 179.3621,+    "y": 31.7627+   },+   "pattern": "TST_SOIC8",+   "ref": "U3",+   "rotation": 0,+   "side": "top",+   "x": 182.88,+   "y": 28.194+  },+  {+   "body": [+    187.893,+    25.468,+    189.043,+    27.618+   ],+   "comment": {+    "box": [+     187.8965,+     22.6695,+     232.5862,+     24.9549+    ],+    "rotation": 0,+    "shown": false,+    "size": 1.524,+    "text": "Resistor 10k +/-1% 0402 100 mW",+    "x": 188.1505,+    "y": 22.9235+   },+   "name": {+    "box": [+     187.8965,+     28.1305,+     192.4672,+     30.162+    ],+    "rotation": 0,+    "shown": true,+    "size": 1.524,+    "text": "R90",+    "x": 188.1505,+    "y": 28.3845+   },+   "pattern": "RESC1005X40X25ML05T05",+   "ref": "R90",+   "rotation": 90,+   "side": "top",+   "x": 188.468,+   "y": 26.543+  },+  {+   "body": [+    25.225,+    7.225,+    32.775,+    12.81+   ],+   "comment": {+    "box": [+     29.0,+     10.0,+     29.0,+     10.0+    ],+    "rotation": 0,+    "shown": false,+    "size": 1.524,+    "text": "",+    "x": 29.0,+    "y": 10.0+   },+   "name": {+    "box": [+     28.746,+     9.746,+     31.7932,+     11.7775+    ],+    "rotation": 0,+    "shown": false,+    "size": 1.524,+    "text": "U2",+    "x": 29.0,+    "y": 10.0+   },+   "pattern": "TST_SOIC8",+   "ref": "U2",+   "rotation": 0,+   "side": "top",+   "x": 29.0,+   "y": 10.0+  },+  {+   "body": [+    6.225,+    7.225,+    13.775,+    12.81+   ],+   "comment": {+    "box": [+     9.746,+     9.4921,+     23.2038,+     11.7775+    ],+    "rotation": 0,+    "shown": false,+    "size": 1.524,+    "text": "TST_SOIC8",+    "x": 10.0,+    "y": 10.0+   },+   "name": {+    "box": [+     9.746,+     9.746,+     12.2853,+     11.7775+    ],+    "rotation": 0,+    "shown": false,+    "size": 1.524,+    "text": "U1",+    "x": 10.0,+    "y": 10.0+   },+   "pattern": "TST_SOIC8",+   "ref": "U1",+   "rotation": 0,+   "side": "top",+   "x": 10.0,+   "y": 10.0+  }+ ],+ "lines": [],+ "success": true,+ "texts": [+  {+   "box": [+    19.8571,+    17.8571,+    26.8074,+    19.1425+   ],+   "mirror": false,+   "raw": {+    "layer": 33,+    "x": 7874016,+    "y": 7086614+   },+   "rotation": 0,+   "side": "top",+   "size": 1.0,+   "text": "BATTERY",+   "x": 20.0,+   "y": 18.0+  }+ ],+ "windowEtiquette": "background"+}\ No newline at end of file
fixtures/altium/pair.PcbDocadded
⋯ 1 unchanged line ⋯
package.json+5−1
@@ -211,7 +211,11 @@     "wire these pins together in altium",     "add a bus in an altium schematic",     "altium schematic junction dots and labels",-    "trace a net on an altium schematic sheet"+    "trace a net on an altium schematic sheet",+    "create a new schematic sheet in altium",+    "altium sheet hierarchy page numbers",+    "render an altium schematic to an image",+    "update altium symbols from library"   ],   "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+5−1
@@ -203,7 +203,11 @@     "wire these pins together in altium",     "add a bus in an altium schematic",     "altium schematic junction dots and labels",-    "trace a net on an altium schematic sheet"+    "trace a net on an altium schematic sheet",+    "create a new schematic sheet in altium",+    "altium sheet hierarchy page numbers",+    "render an altium schematic to an image",+    "update altium symbols from library"   ],   "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-schematic-edit/SKILL.md+8
@@ -75,6 +75,14 @@ of its geometry, valid until the item changes, and every edit answers the new id | Move everything in a box (wires crossing the edge stretch) | `altium_sch_move_region` | | Snap near-miss wire ends onto their pins (plan first, dryRun defaults to true) | `altium_sch_fix_connectivity` | +| Paper, orientation, title block (read, or set) | `altium_sch_page` |+| A new sheet, or a new child sheet of a project with its symbol and page number | `altium_sch_create` |+| The sheet tree from the files (no Altium needed); renumber pages | `altium_sch_hierarchy` |+| A sheet symbol's pins: list, add, edit, delete, import the child's ports, validate | `altium_sch_sheet_pins` |+| Designators and comments back where the library puts them | `altium_sch_reset_fields` |+| Re-place symbols from their library (refuses to drop a connected pin) | `altium_sch_update_from_library` |+| A PNG of a sheet without opening a window; visual baselines and drift | `altium_render_schematic` |+ Every edit takes `dryRun` (the plan, nothing changed) and saves unless `save:false`. Check the result with `altium_sch_pins` (connectedPins) or `altium_compile`. 
src/agent/AdomAgent.pas.tmpl+74−2
@@ -8837,7 +8837,9 @@ Begin             C.SchIterator_Destroy(PIt);             If S <> '' Then S := S + ',';             S := S + '{"t":"C","key":"","ref":"' + JsonEsc(C.Designator.Text) + '","x":' + I2S(C.Location.X) + ',"y":' + I2S(C.Location.Y) +-                ',"lib":"' + JsonEsc(C.LibReference) + '","part":' + I2S(C.CurrentPartID) + ',"rot":' + I2S(C.Orientation) + ',"mirror":' + JBool(C.IsMirrored) + '}';+                ',"lib":"' + JsonEsc(C.LibReference) + '","libPath":"' + JsonEsc(C.LibraryPath) + '","part":' + I2S(C.CurrentPartID) + ',"rot":' + I2S(C.Orientation) + ',"mirror":' + JBool(C.IsMirrored) ++                ',"des":[' + I2S(C.Designator.Location.X) + ',' + I2S(C.Designator.Location.Y) + ',' + I2S(C.Designator.Orientation) + ',' + I2S(C.Designator.Justification) + ']' ++                ',"cmt":[' + I2S(C.Comment.Location.X) + ',' + I2S(C.Comment.Location.Y) + ',' + I2S(C.Comment.Orientation) + ',' + I2S(C.Comment.Justification) + ']}';         End         Else         Begin@@ -8881,7 +8883,7 @@ Begin     End;     Doc.SchIterator_Destroy(It);     Result := '{' + JRaw('ok','true') + ',' + JStr('document', Doc.DocumentName) + ',' + JRaw('k', I2S(MilsToCoord(1000))) + ',' +-        JRaw('page', '{"style":' + I2S(Doc.SheetStyle) + ',"custom":' + JBool(Doc.UseCustomSheet) + ',"cx":' + I2S(Doc.CustomX) + ',"cy":' + I2S(Doc.CustomY) + '}') + ',' ++        JRaw('page', '{"style":' + I2S(Doc.SheetStyle) + ',"custom":' + JBool(Doc.UseCustomSheet) + ',"cx":' + I2S(Doc.CustomX) + ',"cy":' + I2S(Doc.CustomY) + ',"orientation":' + I2S(Doc.WorkspaceOrientation) + '}') + ',' +         JRaw('items', '[' + S + ']') + ',' + JRaw('pins', '[' + P + ']') + '}'; End; @@ -8938,6 +8940,8 @@ Var     CL   : TInterfaceList;     Obj  : ISch_GraphicalObject;     C    : ISch_Component;+    En   : ISch_SheetEntry;+    EIt  : ISch_Iterator;     Op, K, Res, NewKey, S : String;     I, J, NOk : Integer; Begin@@ -9006,6 +9010,74 @@ Begin             CL.Free;             NewKey := FieldP(Op, 2);         End+        Else If K = 'A' Then+        Begin+            { A|style|custom(1/0)|cx|cy|orientation: the page (empty keeps a field) }+            If FieldP(Op, 2) <> '' Then Doc.SheetStyle := AdomInt(FieldP(Op, 2));+            If FieldP(Op, 3) <> '' Then Doc.UseCustomSheet := FieldP(Op, 3) = '1';+            If FieldP(Op, 4) <> '' Then Doc.CustomX := AdomInt(FieldP(Op, 4));+            If FieldP(Op, 5) <> '' Then Doc.CustomY := AdomInt(FieldP(Op, 5));+            If FieldP(Op, 6) <> '' Then Doc.WorkspaceOrientation := AdomInt(FieldP(Op, 6));+        End+        Else If K = 'F' Then+        Begin+            { F|ref|designator or comment|x|y|orientation|justification: put a part's field text there }+            CL := SheetCompsOf(Doc, FieldP(Op, 2));+            If CL.Count = 0 Then Res := 'designator not on this sheet';+            For J := 0 To CL.Count - 1 Do+            Begin+                C := CL[J];+                SchServer.RobotManager.SendMessage(C.I_ObjectAddress, c_BroadCast, SCHM_BeginModify, c_NoEventData);+                If LowerCase(FieldP(Op, 3)) = 'comment' Then Obj := C.Comment Else Obj := C.Designator;+                Obj.Location := Point(AdomInt(FieldP(Op, 4)), AdomInt(FieldP(Op, 5)));+                Obj.Orientation := AdomInt(FieldP(Op, 6));+                Obj.Justification := AdomInt(FieldP(Op, 7));+                SchServer.RobotManager.SendMessage(C.I_ObjectAddress, c_BroadCast, SCHM_EndModify, c_NoEventData);+                C.GraphicallyInvalidate;+            End;+            CL.Free;+        End+        Else If (K = 'Y') Or (K = 'Z') Or (K = 'Q') Then+        Begin+            { sheet symbol pins. Y|symkey|name|side|dist|io adds one; Z|symkey|name deletes it;+              Q|symkey|name|newname|side|dist|io edits it (empty keeps a field) }+            Obj := SchFindByKey(Doc, FieldP(Op, 2));+            If Obj = Nil Then Res := 'not found: the sheet symbol changed since it was read'+            Else+            Begin+                SchServer.RobotManager.SendMessage(Obj.I_ObjectAddress, c_BroadCast, SCHM_BeginModify, c_NoEventData);+                If K = 'Y' Then+                Begin+                    En := SchServer.SchObjectFactory(eSheetEntry, eCreate_Default);+                    En.Name := FieldP(Op, 3);+                    En.Side := AdomInt(FieldP(Op, 4));+                    En.DistanceFromTop := AdomInt(FieldP(Op, 5));+                    En.IOType := AdomInt(FieldP(Op, 6));+                    Obj.AddSchObject(En);+                    SchServer.RobotManager.SendMessage(Obj.I_ObjectAddress, c_BroadCast, SCHM_PrimitiveRegistration, En.I_ObjectAddress);+                End+                Else+                Begin+                    EIt := Obj.SchIterator_Create;+                    EIt.AddFilter_ObjectSet(MkSet(eSheetEntry));+                    En := EIt.FirstSchObject;+                    While (En <> Nil) And (UpperCase(En.Name) <> UpperCase(FieldP(Op, 3))) Do En := EIt.NextSchObject;+                    Obj.SchIterator_Destroy(EIt);+                    If En = Nil Then Res := 'no pin ' + FieldP(Op, 3)+                    Else If K = 'Z' Then Obj.RemoveSchObject(En)+                    Else+                    Begin+                        If FieldP(Op, 4) <> '' Then En.Name := FieldP(Op, 4);+                        If FieldP(Op, 5) <> '' Then En.Side := AdomInt(FieldP(Op, 5));+                        If FieldP(Op, 6) <> '' Then En.DistanceFromTop := AdomInt(FieldP(Op, 6));+                        If FieldP(Op, 7) <> '' Then En.IOType := AdomInt(FieldP(Op, 7));+                    End;+                End;+                SchServer.RobotManager.SendMessage(Obj.I_ObjectAddress, c_BroadCast, SCHM_EndModify, c_NoEventData);+                Obj.GraphicallyInvalidate;+                NewKey := SchKey(Obj);+            End;+        End         Else If (K = 'D') Or (K = 'V') Or (K = 'G') Or (K = 'L') Then         Begin             Obj := SchFindByKey(Doc, FieldP(Op, 2));
src/bridge.json+15−1
@@ -156,6 +156,7 @@     "altium_remove_symbol",     "altium_rename_footprint",     "altium_rename_symbol",+    "altium_render_schematic",     "altium_replicate_layout",     "altium_repour",     "altium_return_path",@@ -177,20 +178,26 @@     "altium_sch_connect",     "altium_sch_connect_pins",     "altium_sch_connect_to_bus",+    "altium_sch_create",     "altium_sch_delete_wire",     "altium_sch_edit",     "altium_sch_edit_label",     "altium_sch_fix_connectivity",+    "altium_sch_hierarchy",     "altium_sch_items",     "altium_sch_junction",     "altium_sch_move_region",+    "altium_sch_page",     "altium_sch_pins",     "altium_sch_place_part",+    "altium_sch_reset_fields",+    "altium_sch_sheet_pins",     "altium_sch_sheet_symbol",     "altium_sch_split_wire",     "altium_sch_swap_part",     "altium_sch_text",     "altium_sch_trace_point",+    "altium_sch_update_from_library",     "altium_sch_zoom",     "altium_schematic_data",     "altium_schematic_review",@@ -405,7 +412,14 @@       "sch_connect_pins": 150,       "sch_connect_to_bus": 150,       "sch_move_region": 150,-      "sch_fix_connectivity": 150+      "sch_fix_connectivity": 150,+      "sch_page": 320,+      "sch_create": 320,+      "sch_hierarchy": 320,+      "sch_sheet_pins": 320,+      "sch_reset_fields": 320,+      "sch_update_from_library": 320,+      "render_schematic": 420     },     "prefixes": [       {