← Commit history
Merge PR #598: AI Flow 0.2.108: rules use keeps an Altium board's own tighter rules (#228) (release-0.2.108 -> main) merge
Showing changes introduced by the merge (against its first parent).
12 files changed
+161−22
Cargo.lock+10−10Cargo.toml+1−1bin/adom-aiflowcrates/adom-aiflow/src/main.rs+4−2crates/adom-aiflow/src/prefs.rs+4−2crates/aiflow-bridge/src/altium.rs+14−3crates/aiflow-bridge/src/altium_rules.rs+113crates/aiflow-bridge/src/eda.rs+2−2crates/aiflow-bridge/src/lib.rs+1docs/release-0.2.108.md+10package.json+1−1page.json+1−1Cargo.lock+10−10@@ -4,7 +4,7 @@ version = 4 [[package]] name = "adom-aiflow"-version = "0.2.107"+version = "0.2.108" dependencies = [ "aiflow-analyze", "aiflow-board",@@ -25,7 +25,7 @@ dependencies = [ [[package]] name = "aiflow-analyze"-version = "0.2.107"+version = "0.2.108" dependencies = [ "aiflow-board", "serde",@@ -35,7 +35,7 @@ dependencies = [ [[package]] name = "aiflow-board"-version = "0.2.107"+version = "0.2.108" dependencies = [ "roxmltree", "serde",@@ -44,7 +44,7 @@ dependencies = [ [[package]] name = "aiflow-bridge"-version = "0.2.107"+version = "0.2.108" dependencies = [ "aiflow-board", "serde",@@ -53,7 +53,7 @@ dependencies = [ [[package]] name = "aiflow-copper"-version = "0.2.107"+version = "0.2.108" dependencies = [ "aiflow-board", "aiflow-grid",@@ -63,7 +63,7 @@ dependencies = [ [[package]] name = "aiflow-grid"-version = "0.2.107"+version = "0.2.108" dependencies = [ "aiflow-board", "serde",@@ -72,7 +72,7 @@ dependencies = [ [[package]] name = "aiflow-place"-version = "0.2.107"+version = "0.2.108" dependencies = [ "aiflow-board", "serde",@@ -81,7 +81,7 @@ dependencies = [ [[package]] name = "aiflow-pours"-version = "0.2.107"+version = "0.2.108" dependencies = [ "aiflow-board", "aiflow-copper",@@ -91,7 +91,7 @@ dependencies = [ [[package]] name = "aiflow-router"-version = "0.2.107"+version = "0.2.108" dependencies = [ "aiflow-board", "aiflow-grid",@@ -102,7 +102,7 @@ dependencies = [ [[package]] name = "aiflow-run"-version = "0.2.107"+version = "0.2.108" dependencies = [ "serde", "serde_json",
Cargo.toml+1−1@@ -14,7 +14,7 @@ members = [ ] [workspace.package]-version = "0.2.107"+version = "0.2.108" edition = "2021" license = "MIT" repository = "https://wiki.adom.inc/adom/adom-aiflow"
bin/adom-aiflow⋯ 1 unchanged line ⋯
crates/adom-aiflow/src/main.rs+4−2@@ -196,7 +196,7 @@ enum Cmd { #[arg(long)] layers: Option<u32>, /// `rules use`: a named variant of the fab's pack on adom/pcb-design-rules (`<fab>-<n>L-<variant>`, e.g. circuit-forge-strict); the published pack when omitted #[arg(long)] variant: Option<String>,- /// `rules use`: the human's own preferences, a JSON file {"silkMinTextHeight": {"mm": 0.6}, "minTraceWidth": {"mm": 0.2}}: kept in the spec (fab.preferences) and checked on the board as warnings that never block (not written into the KiCad rules, where a preference would replace the fab's limit)+ /// `rules use`: the human's own preferences, a JSON file {"silkMinTextHeight": {"mm": 0.6}, "minTraceWidth": {"mm": 0.2}}: kept in the spec (fab.preferences) and checked on the board as warnings that never block (not written into the KiCad rules, where a preference would replace the fab's limit). On an Altium board, minClearance, minTraceWidth, minHole and minHoleToHole raise the floors written into its rules, and a board rule already at or above a floor is left as it is #[arg(long)] prefs: Option<String>, /// `rules use` / `rules stackup`: bind a published fab stackup preset (e.g. JLC04161H-7628, JLC04161H-3313, JLC06161H-3313, JLC02161H) into spec.json and the KiCad board physical stackup #[arg(long)] stackup: Option<String>,@@ -7918,7 +7918,9 @@ fn main() { let eda = aiflow_bridge::eda::active(); if let Some(target) = r.data["target"].as_str().map(str::to_string) { let br = Bridge { ai_thread: thread(&cli), target };- if let Some(rep) = eda.load_design_rules(&|v: &str, a: &Value| br.raw_call(v, a), &slug, layers, &text) {+ // issue #228: the human's preferences (this --prefs, else the spec's fab.preferences) raise the floors+ let prefs_now = if prefs_rec.is_null() { r.data["spec"].as_str().map(read_json).map(|v| v["fab"]["preferences"].clone()).unwrap_or(Value::Null) } else { prefs_rec.clone() };+ if let Some(rep) = eda.load_design_rules(&|v: &str, a: &Value| br.raw_call(v, a), &slug, layers, &text, &prefs_now) { let okk = Bridge::ok(&rep); fusion_loaded = json!(okk); fusion_note = if okk { format!("; {}: {shown} {layers}-layer rules loaded into the open design", eda.name()) } else { format!("; {} did not load them ({}): open the design and run `rules use` again", eda.name(), rep["errorCode"].as_str().or(rep["error"].as_str()).unwrap_or("?")) };
crates/adom-aiflow/src/prefs.rs+4−2@@ -7,7 +7,7 @@ use aiflow_board::{sx, Board}; use serde_json::Value; -pub const KEYS: [&str; 2] = ["silkMinTextHeight", "minTraceWidth"];+pub const KEYS: [&str; 5] = ["silkMinTextHeight", "minTraceWidth", "minClearance", "minHole", "minHoleToHole"]; /// Validate a preferences object; Err names the bad key. pub fn validate(p: &Value) -> Result<(), String> {@@ -82,7 +82,9 @@ mod tests { #[test] fn preferences_validate() { assert!(validate(&json!({"silkMinTextHeight": {"mm": 0.6}, "minTraceWidth": {"mm": 0.2}})).is_ok());- assert!(validate(&json!({"minClearance": {"mm": 0.2}})).unwrap_err().contains("unknown"));+ // issue #228: clearance, hole and hole-to-hole preferences raise the floors written into an Altium board+ assert!(validate(&json!({"minClearance": {"mm": 0.2}, "minHole": {"mm": 0.25}, "minHoleToHole": {"mm": 0.25}})).is_ok());+ assert!(validate(&json!({"minViaSize": {"mm": 0.2}})).unwrap_err().contains("unknown")); assert!(validate(&json!({"silkMinTextHeight": {"mm": 0}})).is_err()); assert!(validate(&json!([1])).is_err()); }
crates/aiflow-bridge/src/altium.rs+14−3@@ -326,12 +326,23 @@ impl Eda for AltiumEda { } /// The fab pack's floors as Altium design rules (altium_set_design_rules).- fn load_design_rules(&self, t: &dyn Transport, _fab: &str, _layers: u32, dru: &str) -> Option<Value> {+ fn load_design_rules(&self, t: &dyn Transport, _fab: &str, _layers: u32, dru: &str, prefs: &Value) -> Option<Value> { let mut a = crate::eda::fab_numbers(dru); if a.as_object().map(|o| o.is_empty()).unwrap_or(true) { return Some(json!({"success": false, "errorCode": "no_rules", "error": "the fab rule pack names no constraints Altium can load"})); }+ // issue #228: the human's preferences raise the floors; the board's own rules at or above a floor are not+ // written (the bridge writes a value into every rule of its kind, net-class rules included)+ crate::altium_rules::with_prefs(&mut a, prefs); let _ = t.send("altium_show_2d_board", &json!({"filePath": self.path}));- a["expectPath"] = json!(self.path);- Some(t.send("altium_set_design_rules", &a))+ let read = t.send("altium_read_rules", &json!({}));+ let rules: Vec<Value> = read["rules"].as_array().or(read["data"]["rules"].as_array()).cloned().unwrap_or_default();+ let (mut send, kept) = if rules.is_empty() { (a.clone(), Vec::new()) } else { crate::altium_rules::needed(&a, &crate::altium_rules::current_minimums(&rules)) };+ if send.as_object().is_some_and(|o| o.is_empty()) {+ return Some(json!({"success": true, "unchanged": true, "kept": kept, "note": "every board-wide rule is already at or above the fab's floors: nothing written"}));+ }+ send["expectPath"] = json!(self.path);+ let mut r = t.send("altium_set_design_rules", &send);+ if let Some(o) = r.as_object_mut() { o.insert("kept".into(), json!(kept)); }+ Some(r) } fn main_window(&self, t: &dyn Transport) -> Option<i64> {
crates/aiflow-bridge/src/altium_rules.rsadded+113@@ -0,0 +1,113 @@+//! Issue #228 (Jelle): `rules use` on an existing Altium board sent the fab pack's floors as they are, and the+//! bridge writes a value into every rule of its kind, so tighter values set by hand (0.15 mm clearance and width,+//! 0.25 mm holes) and the net-class width rules came back at the pack's minimums. Here, before anything is sent,+//! the board's own enabled board-wide rules (scope All) are read from `altium_read_rules`, and only a floor the+//! board is below is kept: a board at or above every floor gets nothing written.+use serde_json::{json, Map, Value};+use std::collections::BTreeMap;++fn mm(v: &str) -> Option<f64> {+ let v = v.trim();+ if let Some(m) = v.strip_suffix("mil") { return m.trim().parse::<f64>().ok().map(|x| x * 0.0254); }+ v.trim_end_matches("mm").trim().parse::<f64>().ok()+}++/// A field of an Altium rule descriptor, e.g. `Gap` in `Clearance Constraint (Gap=10mil) (All),(All)`.+fn field(d: &str, key: &str) -> Option<f64> {+ let i = d.find(&format!("({key}="))? + key.len() + 2;+ mm(d[i..].split(')').next()?)+}++fn board_wide(r: &Value) -> bool {+ if r["enabled"] == false { return false; }+ let d = r["descriptor"].as_str().unwrap_or("");+ r["scope1"].as_str().map_or_else(|| d.trim_end().ends_with("(All)") || d.contains("(All),(All)"), |s| s.eq_ignore_ascii_case("all"))+ && r["scope2"].as_str().is_none_or(|s| s.eq_ignore_ascii_case("all"))+}++/// The smallest value each kind's enabled board-wide rules hold now (mm): clearance, trackWidth, hole,+/// holeToHole, annularRing, viaDiameter, viaDrill.+pub fn current_minimums(rules: &[Value]) -> BTreeMap<&'static str, f64> {+ let mut out: BTreeMap<&'static str, f64> = BTreeMap::new();+ let mut put = |k: &'static str, v: Option<f64>| { if let Some(v) = v { let e = out.entry(k).or_insert(v); if v < *e { *e = v; } } };+ for r in rules.iter().filter(|r| board_wide(r)) {+ let d = r["descriptor"].as_str().unwrap_or("");+ if d.starts_with("Clearance Constraint") { put("clearance", field(d, "Gap")); }+ else if d.starts_with("Width Constraint") { put("trackWidth", field(d, "Min")); }+ else if d.starts_with("Hole Size") { put("hole", field(d, "Min")); }+ else if d.starts_with("Hole To Hole") { put("holeToHole", field(d, "Gap")); }+ else if d.starts_with("Minimum Annular Ring") { put("annularRing", field(d, "Minimum")); }+ else if d.starts_with("Routing Via") { put("viaDiameter", field(d, "MinWidth")); put("viaDrill", field(d, "MinHoleWidth")); }+ }+ out+}++/// The floors `nums` (the `altium_set_design_rules` payload) to send to a board whose rules hold `cur`: a kind+/// already at or above its floor is left out (and named in the second list). A kind the board has no board-wide+/// rule for is sent.+pub fn needed(nums: &Value, cur: &BTreeMap<&'static str, f64>) -> (Value, Vec<String>) {+ let ok = |k: &str, floor: Option<f64>| floor.is_some_and(|f| cur.get(k).is_some_and(|c| *c + 1e-6 >= f));+ let mut out = Map::new();+ let mut kept = Vec::new();+ for (k, v) in nums.as_object().cloned().unwrap_or_default() {+ let at_floor = match k.as_str() {+ "clearance" | "holeToHole" | "annularRing" => ok(&k, v.as_f64()),+ "trackWidth" | "hole" => ok(&k, v["min"].as_f64()),+ "via" => ok("viaDiameter", v["diameter"]["min"].as_f64()) && ok("viaDrill", v["drill"]["min"].as_f64()),+ "expectPath" | "edgeClearance" => false,+ _ => false,+ };+ if at_floor { kept.push(format!("{k} (the board's {})", match k.as_str() { "via" => format!("{:.3} / {:.3} mm", cur["viaDiameter"], cur["viaDrill"]), "trackWidth" | "hole" => format!("{:.3} mm", cur[k.as_str()]), _ => format!("{:.3} mm", cur[k.as_str()]) })); }+ else { out.insert(k, v); }+ }+ (Value::Object(out), kept)+}++/// The human's preferences (`rules use --prefs`, spec `fab.preferences`) raise the floors sent: a tighter fab+/// class than the pack's (`minClearance`, `minTraceWidth`, `minHole`, `minHoleToHole`, each `{"mm": n}`).+pub fn with_prefs(nums: &mut Value, prefs: &Value) {+ let p = |k: &str| prefs[k]["mm"].as_f64().filter(|v| *v > 0.0);+ let up = |slot: &mut Value, v: f64| { if slot.as_f64().map_or(true, |c| v > c) { *slot = json!(v); } };+ if let Some(v) = p("minClearance") { up(&mut nums["clearance"], v); }+ if let Some(v) = p("minHoleToHole") { up(&mut nums["holeToHole"], v); }+ if let Some(v) = p("minTraceWidth") { up(&mut nums["trackWidth"]["min"], v); }+ if let Some(v) = p("minHole") { up(&mut nums["hole"]["min"], v); }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn rules() -> Vec<Value> {+ vec![json!({"descriptor": "Clearance Constraint (Gap=0.15mm) (All),(All)", "enabled": true, "scope1": "All"}),+ json!({"descriptor": "Width Constraint (Min=0.15mm) (Max=5mm) (Preferred=0.25mm) (All)", "enabled": true, "scope1": "All"}),+ json!({"descriptor": "Width Constraint (Min=0.5mm) (Max=5mm) (Preferred=0.8mm) (InNetClass('Power'))", "enabled": true, "scope1": "InNetClass('Power')"}),+ json!({"descriptor": "Hole Size Constraint (Min=0.25mm) (Max=6.3mm) (All)", "enabled": true, "scope1": "All"}),+ json!({"descriptor": "Hole To Hole Clearance (Gap=0.25mm) (All),(All)", "enabled": true}),+ json!({"descriptor": "Clearance Constraint (Gap=2mil) (All),(All)", "enabled": false})]+ }++ /// Jelle's board: every board-wide rule tighter than the pack's 0.1 mm floors: nothing is sent.+ #[test]+ fn a_board_above_every_floor_gets_nothing_written() {+ let cur = current_minimums(&rules());+ assert_eq!((cur["clearance"], cur["trackWidth"], cur["hole"], cur["holeToHole"]), (0.15, 0.15, 0.25, 0.25), "the disabled 2 mil rule and the net-class rule do not count");+ let nums = json!({"clearance": 0.1, "trackWidth": {"min": 0.1}, "hole": {"min": 0.1}, "holeToHole": 0.2});+ let (send, kept) = needed(&nums, &cur);+ assert_eq!(send, json!({}));+ assert_eq!(kept.len(), 4);+ }++ #[test]+ fn only_a_floor_the_board_is_below_is_sent_and_prefs_raise_floors() {+ let cur = current_minimums(&rules());+ let mut nums = json!({"clearance": 0.2, "trackWidth": {"min": 0.1}, "via": {"diameter": {"min": 0.45}, "drill": {"min": 0.2}}});+ let (send, _) = needed(&nums, &cur);+ assert_eq!(send["clearance"], 0.2, "the board's 0.15 is below the 0.2 floor");+ assert!(send.get("trackWidth").is_none());+ assert!(send.get("via").is_some(), "no board-wide via rule: sent");+ with_prefs(&mut nums, &json!({"minTraceWidth": {"mm": 0.2}, "minClearance": {"mm": 0.18}}));+ assert_eq!((nums["trackWidth"]["min"].as_f64(), nums["clearance"].as_f64()), (Some(0.2), Some(0.2)), "prefs only raise");+ assert_eq!(field("Clearance Constraint (Gap=10mil) (All),(All)", "Gap"), Some(0.254));+ }+}
crates/aiflow-bridge/src/eda.rs+2−2@@ -124,7 +124,7 @@ pub trait Eda: Send + Sync { fn round_corners(&self, _t: &dyn Transport, _corners: &[(f64, f64)], _radius: f64) -> Value { self.unsupported("round_corners") } /// Load a fab's design rules into the open design (the plan board's .kicad_dru is written by the flow /// for every backend: the offline gate reads it). None when the tool has nothing to load them into.- fn load_design_rules(&self, _t: &dyn Transport, _fab: &str, _layers: u32, _dru: &str) -> Option<Value> { None }+ fn load_design_rules(&self, _t: &dyn Transport, _fab: &str, _layers: u32, _dru: &str, _prefs: &Value) -> Option<Value> { None } /// The window to film for a step, the board framed in it. `cached` is the last filmed window. fn camera_window(&self, t: &dyn Transport, _step: &str, _cached: Option<i64>) -> Option<i64> { let h = self.main_window(t);@@ -304,7 +304,7 @@ impl Eda for FusionEda { } json!({"success": done == corners.len(), "rounded": done}) }- fn load_design_rules(&self, t: &dyn Transport, fab: &str, layers: u32, _dru: &str) -> Option<Value> {+ fn load_design_rules(&self, t: &dyn Transport, fab: &str, layers: u32, _dru: &str, _prefs: &Value) -> Option<Value> { Some(t.send("fusion_set_design_rules", &json!({"fab": fab, "layers": layers}))) } fn camera_window(&self, t: &dyn Transport, _step: &str, _cached: Option<i64>) -> Option<i64> {
crates/aiflow-bridge/src/lib.rs+1@@ -8,6 +8,7 @@ use std::process::Command; use serde_json::{json, Value}; pub mod altium;+pub mod altium_rules; pub mod eda; pub mod fusion; pub mod focus;
docs/release-0.2.108.mdadded+10@@ -0,0 +1,10 @@+# AI Flow 0.2.108++- **`rules use` keeps an Altium board's own tighter rules** (#228, Jelle). On an existing Altium board, the fab+ pack's floors were sent as they are, and the Altium bridge writes a value into every rule of its kind: tighter+ values set by hand (0.15 mm clearance and width, 0.25 mm holes) and the net-class width rules came back at the+ pack's minimums. `rules use` now reads the board's enabled board-wide rules first and writes only a floor the board+ is below; a board at or above every floor gets nothing written ("unchanged", with each rule it kept).+- **Preferences for clearance and holes.** `--prefs` (spec `fab.preferences`) takes `minClearance`, `minHole` and+ `minHoleToHole` besides `minTraceWidth` and `silkMinTextHeight`. On an Altium board they raise the floors written,+ so a tighter fab class can be stated.
package.json+1−1@@ -1,7 +1,7 @@ { "slug": "adom-aiflow", "type": "app",- "version": "0.2.107",+ "version": "0.2.108", "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.107",+ "version": "0.2.108", "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.",