← Commit history
Merge PR #604: 0.2.111: Altium place verify and adopt-board (#229) (release-0.2.111 -> main) merge
Showing changes introduced by the merge (against its first parent).
12 files changed
+363−22
Cargo.lock+10−10Cargo.toml+1−1bin/adom-aiflowcrates/adom-aiflow/src/altium_placement.rs+190crates/adom-aiflow/src/main.rs+103−3crates/adom-aiflow/src/placement_verify.rs+11−1crates/aiflow-board/src/altium.rs+27−4crates/aiflow-bridge/src/altium.rs+4−1docs/release-0.2.111.md+13package.json+1−1page.json+1−1skills/adom-aiflow/SKILL.md+2Cargo.lock+10−10@@ -4,7 +4,7 @@ version = 4 [[package]] name = "adom-aiflow"-version = "0.2.110"+version = "0.2.111" dependencies = [ "aiflow-analyze", "aiflow-board",@@ -25,7 +25,7 @@ dependencies = [ [[package]] name = "aiflow-analyze"-version = "0.2.110"+version = "0.2.111" dependencies = [ "aiflow-board", "serde",@@ -35,7 +35,7 @@ dependencies = [ [[package]] name = "aiflow-board"-version = "0.2.110"+version = "0.2.111" dependencies = [ "roxmltree", "serde",@@ -44,7 +44,7 @@ dependencies = [ [[package]] name = "aiflow-bridge"-version = "0.2.110"+version = "0.2.111" dependencies = [ "aiflow-board", "serde",@@ -53,7 +53,7 @@ dependencies = [ [[package]] name = "aiflow-copper"-version = "0.2.110"+version = "0.2.111" dependencies = [ "aiflow-board", "aiflow-grid",@@ -63,7 +63,7 @@ dependencies = [ [[package]] name = "aiflow-grid"-version = "0.2.110"+version = "0.2.111" dependencies = [ "aiflow-board", "serde",@@ -72,7 +72,7 @@ dependencies = [ [[package]] name = "aiflow-place"-version = "0.2.110"+version = "0.2.111" dependencies = [ "aiflow-board", "serde",@@ -81,7 +81,7 @@ dependencies = [ [[package]] name = "aiflow-pours"-version = "0.2.110"+version = "0.2.111" dependencies = [ "aiflow-board", "aiflow-copper",@@ -91,7 +91,7 @@ dependencies = [ [[package]] name = "aiflow-router"-version = "0.2.110"+version = "0.2.111" dependencies = [ "aiflow-board", "aiflow-grid",@@ -102,7 +102,7 @@ dependencies = [ [[package]] name = "aiflow-run"-version = "0.2.110"+version = "0.2.111" dependencies = [ "serde", "serde_json",
Cargo.toml+1−1@@ -14,7 +14,7 @@ members = [ ] [workspace.package]-version = "0.2.110"+version = "0.2.111" edition = "2021" license = "MIT" repository = "https://wiki.adom.inc/adom/adom-aiflow"
bin/adom-aiflow⋯ 1 unchanged line ⋯
crates/adom-aiflow/src/altium_placement.rsadded+190@@ -0,0 +1,190 @@+//! Issue #229 (Jelle Jocque): `place verify` and `adopt-board` on an Altium run.+//!+//! Altium is the board of record and its bridge has no kicad_placement_state. The live read+//! (altium_routing_state, rendered as the plan board by aiflow_board::altium) stands in for it: the+//! same footprints, sides, rotations and courtyards every offline stage reads. aiflow's courtyard+//! boxes and outline stand in for kicad_placement_validate's box checks, and Altium's own batch DRC,+//! its placement rules, is the native placement DRC.+use aiflow_board::Board;+use serde_json::{json, Value};+use std::collections::BTreeMap;++/// Altium's placement rule kinds: a violation of one of these is a placement violation. Height is+/// Altium's warning (aiflow-bridge altium.rs WARNING_RULES) and never reaches the error list.+pub const PLACEMENT_RULES: [&str; 4] = ["ComponentClearance", "ComponentOrientations", "PermittedLayers", "RoomDefinition"];+/// A connection left for routing is not an adoption error (KiCad's adopt-board lets connectivity remain too).+const UNROUTED_RULES: [&str; 2] = ["UnRoutedNet", "UnroutedNet"];++fn refs_outside(plan: &Board) -> Vec<String> {+ aiflow_place::parts_outside(plan, &[]).into_iter().map(|(r, _)| r).collect()+}++/// kicad_placement_state's reply, from the plan board rendered from one live Altium read.+pub fn state(plan: &Board, revision: &str, remote: &str) -> Value {+ let boxes = aiflow_place::boxes(plan);+ let outside = refs_outside(plan);+ let parts: Vec<Value> = plan.footprints.iter().map(|(r, fp)| {+ let mut p = json!({"ref": r, "x": fp.x, "y": fp.y, "rotation": fp.rot, "side": fp.layer, "footprint": fp.lib, "insideOutline": !outside.contains(r)});+ if let Some(b) = boxes.get(r) {+ p["courtyard"] = json!({"minX": b.0, "minY": b.1, "maxX": b.2, "maxY": b.3});+ p["courtyardSource"] = json!(if aiflow_place::courtyard_local(plan, r).is_some() { "courtyard" } else { "pads" });+ }+ p+ }).collect();+ json!({"success": !revision.is_empty(), "source": "live-editor", "backend": "altium", "revision": revision, "stale": false,+ "boardPath": remote, "footprintCount": parts.len(), "footprints": parts})+}++/// Courtyard boxes that overlap on a side both parts occupy (a drilled part is on both). A footprint+/// with no courtyard (an Altium free pad) is reported in withoutCourtyard instead, as KiCad does.+fn overlaps(plan: &Board) -> Vec<Value> {+ let boxes: Vec<(String, (f64, f64, f64, f64))> = aiflow_place::boxes(plan).into_iter()+ .filter(|(r, _)| aiflow_place::courtyard_local(plan, r).is_some()).collect();+ let mut out = Vec::new();+ for (i, (a, ba)) in boxes.iter().enumerate() {+ for (b, bb) in &boxes[i + 1..] {+ let hit = ba.0 < bb.2 - 1e-6 && bb.0 < ba.2 - 1e-6 && ba.1 < bb.3 - 1e-6 && bb.1 < ba.3 - 1e-6;+ if !hit { continue; }+ let (sa, sb) = (aiflow_place::sides(plan, a), aiflow_place::sides(plan, b));+ let side = if sa.0 && sb.0 { Some("F.Cu") } else if sa.1 && sb.1 { Some("B.Cu") } else { None };+ if let Some(side) = side { out.push(json!({"a": a, "b": b, "side": side})); }+ }+ }+ out+}++/// The native placement check, kicad_placement_validate's `drc`: Altium's batch DRC placement rules (in it+/// only when the board's batch DRC setup enables them) and the bridge's read-only altium_placement_check+/// (parts whose 3D bodies or pads meet on one side, parts on a mounting hole). Edges are left to+/// outsideOutline, where placement.edgeConnectors applies; nearEdge and stacked are advisories.+pub fn placement_drc(full: &Value, check: &Value) -> Value {+ let all = full["violations"].as_array().cloned().unwrap_or_default();+ let mut placement: Vec<Value> = all.iter().filter(|v| PLACEMENT_RULES.contains(&v["type"].as_str().unwrap_or(""))).cloned().collect();+ for o in check["courtyardOverlaps"].as_array().into_iter().flatten() {+ placement.push(json!({"type": "BodyOrPadOverlap", "items": o["parts"], "source": "altium_placement_check", "detail": o}));+ }+ for o in check["onMountingHoles"].as_array().into_iter().flatten() {+ placement.push(json!({"type": "OnMountingHole", "items": [o], "source": "altium_placement_check"}));+ }+ let checked = check["success"] == true && check["courtyardOverlaps"].is_array();+ let available = full["success"] == true && full["violations"].is_array() && checked;+ // a reply that counts more errors than it lists was cut short: never call it complete+ let truncated = full["truncated"] == true || check["truncated"] == true || full["errors"].as_u64().is_some_and(|n| n as usize > all.len());+ json!({"available": available, "source": "live-editor-snapshot", "tool": "Altium batch DRC (placement rules) and altium_placement_check",+ "placementClean": available && placement.is_empty(), "placementViolationCount": placement.len(),+ "placementViolations": placement, "errors": placement.len(), "violationReportMayBeTruncated": truncated,+ "advisories": {"nearEdge": check["nearEdge"], "stacked": check["stacked"]}})+}++/// Of two batch DRC replies, the one that lists more: altium-bridge 0.2.108 can answer 0 straight after a+/// repour or an open, and a second call lists them (the Altium thread, 2026-11-25).+pub fn fuller(a: Value, b: Value) -> Value {+ let n = |v: &Value| if v["success"] == true { v["violations"].as_array().map(|x| x.len() as i64).unwrap_or(-1) } else { -1 };+ if n(&b) > n(&a) { b } else { a }+}++/// kicad_placement_validate's reply for the plan board of one live read.+pub fn validation(plan: &Board, revision: &str, full_drc: &Value, check: &Value) -> Value {+ let outside = refs_outside(plan);+ let overlaps = overlaps(plan);+ let without: Vec<&String> = plan.footprints.keys().filter(|r| aiflow_place::courtyard_local(plan, r).is_none()).collect();+ json!({"success": !revision.is_empty(), "source": "live-editor", "backend": "altium", "revision": revision, "currentRevision": revision, "stale": false,+ "placed": outside.is_empty() && overlaps.is_empty(), "outsideOutline": outside, "parked": [], "courtyardOverlaps": overlaps,+ "withoutCourtyard": without, "drc": placement_drc(full_drc, check)})+}++/// Errors per Altium rule in a full DRC reply, connections left for routing not counted.+pub fn error_counts(full: &Value) -> BTreeMap<String, u64> {+ let mut m = BTreeMap::new();+ for v in full["violations"].as_array().into_iter().flatten() {+ let k = v["type"].as_str().unwrap_or("?");+ if UNROUTED_RULES.contains(&k) { continue; }+ *m.entry(k.to_string()).or_insert(0) += 1;+ }+ m+}++/// adopt-board on Altium: the rules whose error count rose over the last adopted Altium DRC (`base`,+/// None on the run's first Altium adoption: it becomes the baseline).+pub fn new_errors(now: &BTreeMap<String, u64>, base: Option<&Value>) -> Vec<String> {+ let Some(base) = base else { return Vec::new() };+ now.iter().filter_map(|(k, n)| {+ let was = base[k].as_u64().unwrap_or(0);+ (*n > was).then(|| format!("{k}: {was} -> {n}"))+ }).collect()+}++/// The revision a saved Altium board read carries.+pub fn revision_of(read_text: &str) -> Option<String> {+ let v: Value = serde_json::from_str(read_text).ok()?;+ v["state"]["revision"].as_str().filter(|s| !s.is_empty()).map(str::to_string)+}++#[cfg(test)]+mod tests {+ use super::*;++ fn read(parts: Value, pads: Value) -> String {+ json!({"source": "altium-bridge", "state": {"success": true, "revision": "r7", "boardId": "C:/b.PcbDoc", "nets": ["A", "B"],+ "outlineEdges": [{"kind": "line", "start": [0.0, 0.0], "end": [20.0, 0.0]}, {"kind": "line", "start": [20.0, 0.0], "end": [20.0, 10.0]}, {"kind": "line", "start": [20.0, 10.0], "end": [0.0, 10.0]}, {"kind": "line", "start": [0.0, 10.0], "end": [0.0, 0.0]}], "components": parts, "pads": pads, "tracks": [], "vias": [], "polygons": []}}).to_string()+ }+ fn pad(r: &str, x: f64, y: f64) -> Value { json!({"ref": r, "name": "1", "x": x, "y": y, "sizeX": 1.0, "sizeY": 1.0, "rotation": 0, "net": "A", "layer": "F.Cu", "shape": "rect"}) }+ fn plan(text: &str) -> Board { Board::from_text("plan.kicad_pcb", aiflow_board::altium::render_plan_board(text).unwrap()).unwrap() }++ #[test]+ fn the_live_read_is_a_placement_state_the_verifier_accepts() {+ let t = read(json!([{"ref": "R1", "x": 5.0, "y": 5.0, "rotation": 90.0, "side": "top", "pattern": "R0603"},+ {"ref": "C1", "x": 15.0, "y": 5.0, "rotation": 30.0, "side": "bottom", "pattern": "C0603"}]),+ json!([pad("R1", 5.0, 5.0), pad("C1", 15.0, 5.0)]));+ let b = plan(&t);+ let s = state(&b, "r7", "altium:C:/b.PcbDoc");+ assert_eq!(s["footprintCount"], 2);+ let c1 = s["footprints"].as_array().unwrap().iter().find(|p| p["ref"] == "C1").unwrap();+ assert_eq!(c1["side"], "B.Cu", "{c1}");+ assert_eq!(c1["insideOutline"], true);+ assert_eq!(c1["courtyardSource"], "courtyard", "the renderer draws one round the pads");+ let full = json!({"success": true, "violations": [], "errors": 0});+ let check = json!({"success": true, "courtyardOverlaps": [], "onMountingHoles": []});+ assert_eq!(validation(&b, "r7", &full, &json!({"success": false}))["drc"]["available"], false, "no placement check, no complete native check");+ let v = validation(&b, "r7", &full, &check);+ assert_eq!(v["placed"], true, "{v}");+ let ok = crate::placement_verify::check_with_spec(&b, &s, &v, &s, "altium:C:/b.PcbDoc", &Value::Null);+ assert!(ok.is_ok(), "{ok:?}");+ }++ #[test]+ fn overlaps_outside_parts_and_placement_rules_are_named() {+ let t = read(json!([{"ref": "R1", "x": 5.0, "y": 5.0, "rotation": 0.0, "side": "top", "pattern": "R"},+ {"ref": "R2", "x": 5.5, "y": 5.0, "rotation": 0.0, "side": "top", "pattern": "R"},+ {"ref": "R3", "x": 5.0, "y": 5.0, "rotation": 0.0, "side": "bottom", "pattern": "R"},+ {"ref": "R4", "x": 30.0, "y": 5.0, "rotation": 0.0, "side": "top", "pattern": "R"}]),+ json!([pad("R1", 5.0, 5.0), pad("R2", 5.5, 5.0), {"ref": "R3", "name": "1", "x": 5.0, "y": 5.0, "sizeX": 1.0, "sizeY": 1.0, "rotation": 0, "net": "B", "layer": "B.Cu", "shape": "rect"}, pad("R4", 30.0, 5.0)]));+ let b = plan(&t);+ let full = json!({"success": true, "errors": 1, "violations": [{"type": "ComponentClearance", "items": ["R1 R2"]}]});+ let v = validation(&b, "r7", &full, &json!({"success": true, "courtyardOverlaps": [{"parts": ["R1", "R2"]}]}));+ let pairs: Vec<String> = v["courtyardOverlaps"].as_array().unwrap().iter().map(|o| format!("{}{}", o["a"].as_str().unwrap(), o["b"].as_str().unwrap())).collect();+ assert_eq!(pairs, vec!["R1R2".to_string()], "a part on the other side is no overlap: {v}");+ assert_eq!(v["outsideOutline"], json!(["R4"]));+ assert_eq!(v["placed"], false);+ assert_eq!(v["drc"]["placementViolationCount"], 2, "the DRC rule and the bridge's body overlap");+ assert_eq!(v["drc"]["placementClean"], false);+ let s = state(&b, "r7", "x");+ assert!(crate::placement_verify::check_with_spec(&b, &s, &v, &s, "x", &Value::Null).is_err());+ }++ #[test]+ fn a_short_drc_reply_is_never_complete_and_unrouted_is_not_an_error() {+ let full = json!({"success": true, "errors": 3, "violations": [{"type": "Clearance"}, {"type": "UnRoutedNet"}]});+ assert_eq!(placement_drc(&full, &json!({"success": true, "courtyardOverlaps": []}))["violationReportMayBeTruncated"], true);+ let zero = json!({"success": true, "violations": []});+ assert_eq!(fuller(zero.clone(), full.clone()), full, "a second call that lists more wins");+ assert_eq!(fuller(full.clone(), json!({"success": false})), full);+ let now = error_counts(&full);+ assert_eq!(now.get("Clearance"), Some(&1));+ assert!(now.get("UnRoutedNet").is_none());+ assert!(new_errors(&now, None).is_empty(), "the first adoption is the baseline");+ assert_eq!(new_errors(&now, Some(&json!({"Clearance": 1}))), Vec::<String>::new());+ assert_eq!(new_errors(&now, Some(&json!({}))), vec!["Clearance: 0 -> 1".to_string()]);+ assert_eq!(revision_of(r#"{"state":{"revision":"abc"}}"#).as_deref(), Some("abc"));+ }+}
crates/adom-aiflow/src/main.rs+103−3@@ -30,6 +30,7 @@ mod browser_access; mod schematic_identity; mod remote_binding; mod placement_verify;+mod altium_placement; mod assembly_contacts; mod provenance; mod spec_freeze;@@ -3435,6 +3436,88 @@ fn live_board(r: &Run, cli: &Cli, dir: &std::path::Path) -> Option<(String, Stri } } +/// Issue #229: one fresh read of the live Altium board (the plan board rendered from it, and the+/// read's revision).+fn altium_live_read(r: &Run, cli: &Cli, dir: &std::path::Path) -> (Board, String) {+ let (_, k) = live_board(r, cli, dir).unwrap_or_else(|| err("this run's board is not in Altium", &[]));+ let rev = std::fs::read_to_string(dir.join("board-live.altium.json")).ok().and_then(|t| altium_placement::revision_of(&t))+ .unwrap_or_else(|| err("the live Altium read carries no revision", &["Update altium-bridge (bridge_update altium) and read again.".into()]));+ (Board::load(&k).unwrap_or_else(|e| err(&e, &[])), rev)+}++/// Issue #229: read the live Altium board and make it the run's board when it differs from the+/// current one (a new board-N, the project rules carried, copper evidence invalidated as any new board+/// does). Returns the plan board of that read and its revision.+fn altium_read_as_board(r: &mut Run, cli: &Cli, dir: &std::path::Path, why: &str) -> (Board, String) {+ let (plan, rev) = altium_live_read(r, cli, dir);+ let cur = r.current_board();+ if std::fs::read_to_string(&cur).ok().as_deref() != Some(plan.text.as_str()) {+ let n = r.data["boards"].as_array().map(|a| a.len()).unwrap_or(1);+ let dest = dir.join(format!("board-{n}.kicad_pcb"));+ std::fs::write(&dest, &plan.text).unwrap_or_else(|e| err(&e.to_string(), &[]));+ if !cur.is_empty() { aiflow_copper::copy_project_rules(&cur, &dest.display().to_string()).unwrap_or_else(|e| err(&e, &[])); }+ let (carried, note) = copper_carry::adopt(r, &dest.display().to_string());+ r.log("altium-live-board", json!({"board": dest, "revision": rev, "for": why, "read": dir.join("board-live.altium.json"), "copperCarried": carried, "carry": note}));+ r.save().unwrap_or_else(|e| err(&e, &[]));+ eprintln!("{why}: the live Altium board (revision {rev}) is the run's board now ({})", dest.display());+ }+ (plan, rev)+}++/// Issue #229: adopt-board on an Altium run. Altium is the board of record, so what is adopted is the+/// live board, read fresh (`--board live`, the run's .PcbDoc, or a saved bridge read that is still the+/// live revision). Altium's batch DRC stands in for KiCad's: an error count that rose over the last+/// Altium adoption refuses (connections left for routing are not counted); the run's first is the baseline.+fn adopt_altium(r: &mut Run, cli: &Cli, dir: &std::path::Path, board: &str, evidence: &str) -> ! {+ let remote = r.data["remoteBoard"].as_str().unwrap_or("").to_string();+ let named_live = board == "live" || board.to_ascii_lowercase().ends_with(".pcbdoc") || placement_verify::same_board_path(board, &remote);+ let saved_rev = if named_live { None } else {+ let text = std::fs::read_to_string(board).unwrap_or_else(|e| err(&format!("{board}: {e}"), &[]));+ if !aiflow_board::altium::is_altium(&text) {+ err(&format!("{board} is not an Altium board read; on an Altium run adopt-board adopts the live board in Altium"), &["`adom-aiflow adopt-board --board live --evidence <what changed in Altium>` reads the open board fresh (altium_routing_state and altium_pour_state) and makes it the run's board.".into()]);+ }+ Some(altium_placement::revision_of(&text).unwrap_or_else(|| err(&format!("{board} carries no revision"), &["Adopt the live board instead: --board live.".into()])))+ };+ let (plan, rev) = altium_live_read(r, cli, dir);+ if let Some(sr) = saved_rev.filter(|sr| *sr != rev) {+ err(&format!("{board} is revision {sr}; the board in Altium is at revision {rev} now"), &["`--board live` adopts what is in Altium now (the saved read is older).".into()]);+ }+ let drc = altium_drc(&bridge_of(r, cli), &remote, "adopt-board");+ if drc["success"] != true { err(&format!("Altium's batch DRC did not run: {}", drc["error"]), &["Check the bridge (altium_readiness), then adopt again: a board is adopted with its native DRC.".into()]); }+ let counts = altium_placement::error_counts(&drc);+ let base = r.data["altiumDrc"].clone();+ let new = altium_placement::new_errors(&counts, base.is_object().then_some(&base));+ if !new.is_empty() {+ err(&format!("adopt-board adds Altium DRC errors: {}", new.join("; ")), &["Correct them in Altium (Tools > Design Rule Check names each one), then adopt again. Connections left for routing are not counted.".into()]);+ }+ let cur = r.current_board();+ let n = r.data["boards"].as_array().map(|a| a.len()).unwrap_or(1);+ let dest = dir.join(format!("board-{n}.kicad_pcb"));+ std::fs::write(&dest, &plan.text).unwrap_or_else(|e| err(&e.to_string(), &[]));+ if !cur.is_empty() { aiflow_copper::copy_project_rules(&cur, &dest.display().to_string()).unwrap_or_else(|e| err(&e, &[])); }+ let (carried, carry_note) = copper_carry::adopt(r, &dest.display().to_string());+ r.data["remoteBinding"] = Value::Null;+ let first = !base.is_object();+ r.data["altiumDrc"] = json!(counts);+ let layers = plan.copper_layers.len();+ r.log("adopt-board", json!({"source": "altium-live", "named": board, "revision": rev, "board": dest, "evidence": evidence, "altiumDrc": counts, "drcBaseline": first, "copperLayers": layers, "copperCarried": carried}));+ r.save().unwrap_or_else(|e| err(&e, &[]));+ let drc_line = if counts.is_empty() { "Altium DRC: no errors (connections left for routing not counted)".to_string() } else {+ format!("Altium DRC: {} ({})", counts.iter().map(|(k, v)| format!("{k} {v}")).collect::<Vec<_>>().join(", "), if first { "the run's baseline: a later adoption refuses a rise" } else { "none new" })+ };+ ok(&format!("the live Altium board (revision {rev}, {layers} copper layers, {} parts) adopted as {}; {carry_note}", plan.footprints.len(), dest.display()),+ &[drc_line, "`place verify` records the placement proof on it; route, gate, land and finish read Altium again as they run.".into()]);+ std::process::exit(0);+}++/// Altium's batch DRC through the run's backend, called twice and the fuller reply kept (altium-bridge+/// 0.2.108 can list nothing straight after a repour or an open).+fn altium_drc(br: &Bridge, remote: &str, why: &str) -> Value {+ let call = || br.call("kicad_run_drc", &json!({"filePath": remote, "reason": format!("{why}: Altium batch DRC")}));+ let first = call();+ altium_placement::fuller(first, call())+}+ /// Why a field-screen neck happens, from the board the solve ran on: a via whose copper ring is the /// narrowest copper of its net, or another net's track cutting a net's patch pour off from its pin. /// Each hint names the spec change that fixes it, so a refine pass is a decision, not a search.@@ -4812,6 +4895,7 @@ fn main() { Cmd::AdoptBoard { board, evidence } => { thread(&cli); let mut r=load_run(&cli); if evidence.trim().is_empty(){err("adopt-board needs --evidence describing native save/refill/read-back", &["Save and refill the board in its EDA, then pass --board <file> --evidence <review notes or report path>.".into()]);}+ if aiflow_bridge::eda::active().id()=="altium" { adopt_altium(&mut r,&cli,&dir,board,evidence); } Board::load(board).unwrap_or_else(|e|err(&e,&[])); let base=run_drc_for(&r, &r.current_board()).unwrap_or_else(|e|err(&e,&[])); let candidate=run_drc_for(&r, board).unwrap_or_else(|e|err(&e,&[]));@@ -5383,6 +5467,11 @@ fn main() { let b = board_of(&r); match what.as_str() { "verify" => {+ // issue #229: on an Altium run Altium is the board of record: verify what is in Altium now+ // (a fresh read becomes the run's board when the placement there changed)+ let altium=aiflow_bridge::eda::active().id()=="altium";+ let first_read=if altium { Some(altium_read_as_board(&mut r,&cli,&dir,"place verify")) } else { None };+ let b=if first_read.is_some() { board_of(&r) } else { b }; let board_path=r.current_board(); let spec_path=r.data["spec"].as_str().unwrap_or("").to_string(); let board_hash=placement_verify::digest(Path::new(&board_path)).unwrap_or_else(|e|err(&e,&[]));@@ -5395,9 +5484,20 @@ fn main() { for l in &intent_lines { eprintln!("{l}"); } let rb=r.data["remoteBoard"].as_str().filter(|s|!s.is_empty()).unwrap_or_else(||err("place verify requires the named native board",&[])).to_string(); let br=bridge_of(&r,&cli);- let before=br.call("kicad_placement_state",&json!({"filePath":rb,"detail":true}));- let validation=br.call("kicad_placement_validate",&json!({"filePath":rb}));- let after=br.call("kicad_placement_state",&json!({"filePath":rb,"detail":true}));+ let (before,validation,after)=if let Some((plan,rev))=first_read {+ // Altium: the live read rendered as the plan board is the placement state, aiflow's courtyards and+ // Altium's batch DRC (its placement rules) the validation, and a second read after the DRC the check+ let before=altium_placement::state(&plan,&rev,&rb);+ let drc=altium_drc(&br,&rb,"place verify");+ let check=br.raw_call("altium_placement_check",&json!({"marginMm":0.0}));+ let validation=altium_placement::validation(&plan,&rev,&drc,&check);+ let (plan2,rev2)=altium_live_read(&r,&cli,&dir);+ (before,validation,altium_placement::state(&plan2,&rev2,&rb))+ } else {(+ br.call("kicad_placement_state",&json!({"filePath":rb,"detail":true})),+ br.call("kicad_placement_validate",&json!({"filePath":rb})),+ br.call("kicad_placement_state",&json!({"filePath":rb,"detail":true})),+ )}; let report=dir.join("placement-verify.json"); write_json(&report,&json!({"before":before,"validation":validation,"after":after})); let checked=placement_verify::check_with_spec(&b,&before,&validation,&after,&rb,&spec_of(&r));
crates/adom-aiflow/src/placement_verify.rs+11−1@@ -157,9 +157,19 @@ pub fn check_with_spec(board: &Board, before: &Value, validation: &Value, after: && !crate::silk_policy::blocking(spec, &board.path); let native_clear = (drc["placementClean"]==true && drc["placementViolationCount"].as_u64()==Some(0) && drc["errors"].as_u64()==Some(0)) || silk_only; let reviewed_contacts_only = crate::assembly_contacts::native_contacts_only(&contacts, drc, spec, revision, remote);- if drc["available"]!=true || drc["source"]!="live-editor-snapshot" || (!native_clear && !reviewed_contacts_only) || drc["violationReportMayBeTruncated"]!=false {+ if drc["available"]!=true || drc["source"]!="live-editor-snapshot" || drc["violationReportMayBeTruncated"]!=false { return Err("complete native placement DRC is required".into()); }+ if !native_clear && !reviewed_contacts_only {+ // issue #229: a complete report with findings names them, not "required"+ let named: Vec<String> = drc["placementViolations"].as_array().into_iter().flatten().take(8).map(|v| {+ let kind = v["type"].as_str().or(v["rule"].as_str()).unwrap_or("violation");+ let items: Vec<String> = v["items"].as_array().into_iter().flatten().map(|i| i.as_str().map(str::to_string).unwrap_or_else(|| i["description"].as_str().unwrap_or("").to_string())).filter(|s| !s.is_empty()).collect();+ if items.is_empty() { kind.to_string() } else { format!("{kind} ({})", items.join(", ")) }+ }).collect();+ let n = drc["placementViolationCount"].as_u64().unwrap_or(named.len() as u64);+ return Err(format!("native placement DRC finds {n} placement violation(s){}", if named.is_empty() { format!(" ({} error(s))", drc["errors"]) } else { format!(": {}", named.join("; ")) }));+ } let outside=validation["outsideOutline"].as_array().ok_or("missing native outside-outline report")?; let parts=after["footprints"].as_array().ok_or("missing footprints")?; let reported:BTreeSet<_>=outside.iter().filter_map(Value::as_str).collect();
crates/aiflow-board/src/altium.rs+27−4@@ -97,7 +97,12 @@ fn fracture(outline: &[(f64, f64)], holes: &[Vec<(f64, f64)>]) -> Vec<(f64, f64) } /// Is this text an Altium bridge board read (`board-live.altium.json`)?-pub fn is_altium(text: &str) -> bool { text.trim_start().starts_with('{') && text.contains("\"source\":\"altium-bridge\"") }+pub fn is_altium(text: &str) -> bool {+ if !text.trim_start().starts_with('{') { return false; }+ // issue #229: a read saved by hand may be pretty-printed ("source": "altium-bridge")+ text.contains("\"source\":\"altium-bridge\"") || (text.contains("altium-bridge")+ && serde_json::from_str::<Value>(text).map(|v| v["source"] == "altium-bridge").unwrap_or(false))+} /// The plan board for an Altium board: the bridge's read (`{"source":"altium-bridge", "state": /// altium_routing_state, "pours": altium_pour_state}`) written as `.kicad_pcb` text, y negated.@@ -118,9 +123,12 @@ pub fn render_plan_board(src: &str) -> Result<String, String> { let net_pad = |s: &str| if s.is_empty() { String::new() } else { format!("(net {} {})", idx(s), q(s)) }; let net_id = |s: &str| format!("(net {})", idx(s)); - let mut inner: Vec<String> = Vec::new();+ // issue #229: the stack-up's inner layers (altium_layer_stack), empty or not: a board turned 4-layer in+ // Altium is 4-layer here before anything is drawn on In1/In2+ let mut inner: Vec<String> = d["stack"]["layers"].as_array().into_iter().flatten()+ .filter_map(|l| l["layer"].as_str().filter(|n| n.starts_with("In") && n.ends_with(".Cu")).map(str::to_string)).collect(); for k in ["tracks", "arcs"] { for o in arr(k) { if let Some(l) = o["layer"].as_str().filter(|l| l.starts_with("In")) { if !inner.contains(&l.to_string()) { inner.push(l.to_string()); } } } }- inner.sort();+ inner.sort_by_key(|l| l.trim_start_matches("In").trim_end_matches(".Cu").parse::<u32>().unwrap_or(99)); let mut o = String::new(); o.push_str("(kicad_pcb (version 20241229) (generator \"adom-aiflow-altium\") (generator_version \"1\")\n (general (thickness 1.6))\n (paper \"A4\")\n (layers (0 \"F.Cu\" signal)");@@ -214,7 +222,7 @@ pub fn render_plan_board(src: &str) -> Result<String, String> { let shape = if (sx - sy).abs() < 1e-6 && matches!(p["shape"].as_str(), Some("round") | Some("circle")) { "circle" } else { "rect" }; let pad = if drill > 0.0 { format!("(pad {} thru_hole {shape} (at 0 0 {}) (size {} {}) (drill {}) (layers \"*.Cu\" \"*.Mask\") {pn})", q(p["name"].as_str().unwrap_or("")), n(f(&p["rotation"])), n(sx), n(sy), n(drill)) } else { format!("(pad {} smd {shape} (at 0 0 {}) (size {} {}) (layers \"F.Cu\" \"F.Paste\" \"F.Mask\") {pn})", q(p["name"].as_str().unwrap_or("")), n(f(&p["rotation"])), n(sx), n(sy)) };- let _ = writeln!(o, " (footprint \"Altium:FreePad\" (layer F.Cu) (at {} {} 0)\n (property \"Reference\" {} (at 0 0 0) (layer \"F.SilkS\") (hide yes))\n (attr smd)\n {pad}\n )", n(f(&p["x"])), n(yy(f(&p["y"]))), q(&format!("FREE{}", k + 1)));+ let _ = writeln!(o, " (footprint \"Altium:FreePad\" (layer F.Cu) (at {} {} 0)\n (property \"Reference\" {} (at 0 0 0) (layer \"F.SilkS\") (hide yes))\n (attr smd allow_missing_courtyard)\n {pad}\n )", n(f(&p["x"])), n(yy(f(&p["y"]))), q(&format!("FREE{}", k + 1))); } // free silkscreen: texts at their box centre (a bottom text mirrored, as it prints), and lines@@ -354,4 +362,19 @@ mod tests { let p = fracture(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)], &[vec![(4.0, 4.0), (6.0, 4.0), (6.0, 6.0), (4.0, 6.0)]]); assert_eq!(p.len(), 4 + 4 + 2); }++ #[test]+ fn the_stack_ups_inner_layers_render_empty_and_a_pretty_read_is_altium() {+ // issue #229: a board turned 4-layer in Altium, nothing drawn inside yet+ let st = serde_json::json!({"success": true, "nets": [], "components": [], "pads": [], "outlineEdges": [+ {"kind": "line", "start": [0.0, 0.0], "end": [10.0, 0.0]}, {"kind": "line", "start": [10.0, 0.0], "end": [10.0, 5.0]},+ {"kind": "line", "start": [10.0, 5.0], "end": [0.0, 5.0]}, {"kind": "line", "start": [0.0, 5.0], "end": [0.0, 0.0]}]});+ let stack = serde_json::json!({"copperLayers": 4, "layers": [{"layer": "F.Cu"}, {"layer": "In1.Cu"}, {"layer": "In2.Cu"}, {"layer": "B.Cu"}]});+ let src = serde_json::json!({"source": "altium-bridge", "state": st, "stack": stack});+ let b = crate::Board::from_text("t.kicad_pcb", render_plan_board(&src.to_string()).unwrap()).unwrap();+ assert_eq!(b.copper_layers.len(), 4, "{:?}", b.copper_layers);+ let pretty = serde_json::to_string_pretty(&src).unwrap();+ assert!(is_altium(&pretty) && !is_altium("(kicad_pcb)") && !is_altium("{\"source\": \"kicad\"}"));+ }+ }
crates/aiflow-bridge/src/altium.rs+4−1@@ -373,7 +373,10 @@ impl Eda for AltiumEda { // plan board its courtyard and fab outline (the mechanical checks need them) let project = dir.join("altium"); let project = if project.join("project.json").is_file() { json!(std::fs::canonicalize(&project).unwrap_or(project).display().to_string()) } else { Value::Null };- let src = json!({"source": "altium-bridge", "state": st, "pours": if ok(&pours) { pours } else { Value::Null }, "silk": if ok(&silk) { silk } else { Value::Null }, "projectDir": project});+ // issue #229: the stack-up, so a board turned 4-layer is 4-layer here before anything is drawn inside+ let stack = t.send("altium_layer_stack", &json!({"expectPath": self.path}));+ let stack = if ok(&stack) { if stack["data"].is_object() { stack["data"].clone() } else { stack } } else { Value::Null };+ let src = json!({"source": "altium-bridge", "state": st, "pours": if ok(&pours) { pours } else { Value::Null }, "silk": if ok(&silk) { silk } else { Value::Null }, "stack": stack, "projectDir": project}); let native = dir.join("board-live.altium.json"); let kicad = dir.join("board-live.kicad_pcb"); let text = src.to_string();
docs/release-0.2.111.mdadded+13@@ -0,0 +1,13 @@+# adom-aiflow 0.2.111++## Altium runs: place verify and adopt-board (issue #229, Jelle Jocque)++On an Altium run, Altium is the board of record, and placement could only be recorded as a deviation.++- `place verify` works on Altium. It reads the open board first; when the placement there changed, that read becomes the run's board (evidence carried over when the copper is unchanged). It builds the live placement report from that read: positions, rotations, sides, courtyards. It then checks courtyard boxes and the board outline. The native check combines Altium's batch DRC placement rules (ComponentClearance and the others, when the board's DRC setup enables them) with the Altium bridge's read-only `altium_placement_check` (parts whose bodies or pads meet, parts on a mounting hole). A second read after the check must carry the same revision.+- `adopt-board --board live --evidence <what changed>` adopts the open Altium board. A saved bridge read (`{"source":"altium-bridge",...}`, pretty-printed or not) is accepted while it is still the live revision; an older one is refused and names both revisions. Altium's batch DRC runs twice and the fuller reply is kept. Errors are counted per rule, with connections left for routing not counted. The run's first Altium adoption is the baseline, and a later adoption that raises a rule's count is refused.+- The Altium board read now includes the stack-up (`altium_layer_stack`): a board turned 4-layer in Altium is 4-layer in the run before anything is drawn on the inner layers (Jelle saw "the board has 2 copper layers" after changing the stack-up to 4).+- Altium free pads are drawn with `allow_missing_courtyard`, so they are not reported as parts without a courtyard.+- `place verify` (KiCad and Altium): a complete native placement check that finds violations now names them, instead of "complete native placement DRC is required".++Tested live on Altium Designer 26.11.1 with altium-bridge 0.2.108: overlap refused and named, a bottom-side part turned 90 degrees verified, a stale saved read refused, the 2 to 4 layer change adopted as 4 copper layers.
package.json+1−1@@ -1,7 +1,7 @@ { "slug": "adom-aiflow", "type": "app",- "version": "0.2.110",+ "version": "0.2.111", "title": "AI Flow", "description": "Adom's AI Flow: a tool to help the AI follow all of the steps it takes to build a board. One Rust binary with a crate per step (placement helpers, a grid router with Kelvin taps, pours with keepouts, KiCad's DRC gate, live landing through the KiCad Bridge, copper measurement, current and thermal analysis) and a finish line that refuses an unfinished board. Every command answers with hints for the AI; every turn, its thinking time and every rework loop go into run.jsonl, so Claude, Codex and any other engine are compared on the same flow. KiCad, Fusion 360 and Altium Designer today (the same steps and gates through each tool's bridge); Adom's own web apps next.", "summary": "Adom's AI Flow: a tool to help the AI follow all of the steps it takes to build a board. The AI thinks its way from placement through routing, pours, current and thermal analysis to a delivered video; the binary does the fast, deterministic parts of every step, hands back hints, and keeps a ledger of every turn, every return to an earlier step, and the clock from the prompt to done.",
page.json+1−1@@ -1,7 +1,7 @@ { "slug": "adom-aiflow", "type": "app",- "version": "0.2.110",+ "version": "0.2.111", "title": "AI Flow", "description": "Adom's AI Flow: a tool to help the AI follow all of the steps it takes to build a board. One Rust binary with a crate per step (placement helpers, a grid router with Kelvin taps, pours with keepouts, KiCad's DRC gate, live landing through the KiCad Bridge, copper measurement, current and thermal analysis) and a finish line that refuses an unfinished board. Every command answers with hints for the AI; every turn, its thinking time and every rework loop go into run.jsonl, so Claude, Codex and any other engine are compared on the same flow. KiCad, Fusion 360 and Altium Designer today (the same steps and gates through each tool's bridge); Adom's own web apps next.", "summary": "Adom's AI Flow: a tool to help the AI follow all of the steps it takes to build a board. The AI thinks its way from placement through routing, pours, current and thermal analysis to a delivered video; the binary does the fast, deterministic parts of every step, hands back hints, and keeps a ledger of every turn, every return to an earlier step, and the clock from the prompt to done.",
skills/adom-aiflow/SKILL.md+2@@ -708,6 +708,8 @@ The plan needs provenance: the plan `pour` wrote (its hash is recorded in the ru ### Silk-only adoption keeps copper evidence +On an Altium run (issue #229) Altium is the board of record. `adopt-board --board live --evidence <what changed in Altium>` reads the open board fresh (altium_routing_state, altium_pour_state, altium_silk_state) and makes its plan board the run's board; a saved bridge read (`{"source":"altium-bridge",...}`) is accepted only while it is still the live revision. Altium's batch DRC runs twice (the fuller reply is kept) and its errors are counted per rule, connections left for routing not counted: the run's first Altium adoption is the baseline, and a later one refuses a rule whose count rose. `place verify` on an Altium run reads the live board first (a changed placement becomes a new board of the run, evidence carried when the copper is unchanged), builds the live placement state from that read (sides, rotations and courtyards as the plan board has them; a bottom part is drawn at angle 0 there), checks courtyard boxes and the outline itself, and takes the native placement check from Altium's batch DRC placement rules (ComponentClearance and the rest, when the board's DRC setup enables them) plus the bridge's read-only `altium_placement_check` (bodies or pads that meet, parts on a mounting hole). A second read after the check must carry the same revision. Altium free pads are drawn with `allow_missing_courtyard`.+ Before `adopt-board` on a board your own scripts built, declare the step whose work it carries (`step placement` for placed parts, `step routing` for routed copper, `step pours` for zones), so the adoption and the commands after it are charged to that step. `adopt-board` compares the copper fingerprint of the current and adopted boards: tracks, vias, zones with settings, pads with geometry, net and drill, footprint placement, outline, stackup, nets and project rules, but not silkscreen, fab, courtyard, text or 3D models. When it is unchanged, gate, land, measure, the analyses, place verify and the Fields report are kept, with a carry record holding both board hashes and the fingerprint. Every board-hash check accepts the older board only through that record, re-verified from both snapshot files. Any copper change, an unreadable rule file or a non-KiCad board invalidates the evidence as before. The silkscreen and export proofs are always dropped; record them again. ### Holes with no copper