← Commit history

Merge PR #594: AI Flow 0.2.104: a pour split per layer is the same pour (#245) (release-0.2.104 -> main) merge

Colby Knox ·0c35880aa6 · ·parents 1fbc3dd, 172ca6e

Showing changes introduced by the merge (against its first parent).

8 files changed +179−16
Cargo.lock+10−10
@@ -4,7 +4,7 @@ version = 4  [[package]] name = "adom-aiflow"-version = "0.2.103"+version = "0.2.104" dependencies = [  "aiflow-analyze",  "aiflow-board",@@ -25,7 +25,7 @@ dependencies = [  [[package]] name = "aiflow-analyze"-version = "0.2.103"+version = "0.2.104" dependencies = [  "aiflow-board",  "serde",@@ -35,7 +35,7 @@ dependencies = [  [[package]] name = "aiflow-board"-version = "0.2.103"+version = "0.2.104" dependencies = [  "roxmltree",  "serde",@@ -44,7 +44,7 @@ dependencies = [  [[package]] name = "aiflow-bridge"-version = "0.2.103"+version = "0.2.104" dependencies = [  "aiflow-board",  "serde",@@ -53,7 +53,7 @@ dependencies = [  [[package]] name = "aiflow-copper"-version = "0.2.103"+version = "0.2.104" dependencies = [  "aiflow-board",  "aiflow-grid",@@ -63,7 +63,7 @@ dependencies = [  [[package]] name = "aiflow-grid"-version = "0.2.103"+version = "0.2.104" dependencies = [  "aiflow-board",  "serde",@@ -72,7 +72,7 @@ dependencies = [  [[package]] name = "aiflow-place"-version = "0.2.103"+version = "0.2.104" dependencies = [  "aiflow-board",  "serde",@@ -81,7 +81,7 @@ dependencies = [  [[package]] name = "aiflow-pours"-version = "0.2.103"+version = "0.2.104" dependencies = [  "aiflow-board",  "aiflow-copper",@@ -91,7 +91,7 @@ dependencies = [  [[package]] name = "aiflow-router"-version = "0.2.103"+version = "0.2.104" dependencies = [  "aiflow-board",  "aiflow-grid",@@ -101,7 +101,7 @@ dependencies = [  [[package]] name = "aiflow-run"-version = "0.2.103"+version = "0.2.104" dependencies = [  "serde",  "serde_json",
Cargo.toml+1−1
@@ -14,7 +14,7 @@ members = [ ]  [workspace.package]-version = "0.2.103"+version = "0.2.104" edition = "2021" license = "MIT" repository = "https://wiki.adom.inc/adom/adom-aiflow"
bin/adom-aiflow
⋯ 1 unchanged line ⋯
crates/adom-aiflow/src/pour_adopt.rs+104
@@ -51,6 +51,68 @@ fn refuse(code: &str, zone: &str, message: String, extra: Value) -> Value {     v } +/// What a plan zone's several same-name board zones are (issue #245).+enum Split {+    /// one identical one-layer zone per plan layer: the records to adopt or keep+    Adopt(Vec<Value>),+    /// every zone the run's own and the set differs from the plan: the bridge replaces them, as for one zone+    Replace,+    /// one-layer zones that do not make up the plan zone, and why+    Not(String),+    /// not one-layer zones at all: the old refusal+    NotSplit,+}++fn layers_of(node: &sx::Node) -> Vec<String> {+    let mut v: Vec<String> = node.find("layer").and_then(|l| l.value()).map(|l| vec![l.to_string()]).unwrap_or_default();+    if let Some(ls) = node.find("layers") {+        v.extend(ls.items.iter().filter_map(|it| if let sx::Item::Atom { text, .. } = it { Some(text.clone()) } else { None }).filter(|t| t != "layers"));+    }+    v+}++fn split_set(board: &Board, z: &Value, same: &[&&Value], defs: &BTreeMap<&str, &str>, owned: &[String]) -> Result<Split, Value> {+    let name = z["name"].as_str().unwrap_or("");+    let want: Vec<String> = z["layers"].as_array().into_iter().flatten().filter_map(|l| l.as_str().map(str::to_string)).collect();+    let mut by_layer: BTreeMap<String, Vec<(&str, &str)>> = BTreeMap::new();+    for r in same {+        let (Some(id), Some(def)) = (r["id"].as_str(), r["id"].as_str().and_then(|i| defs.get(i).copied())) else { return Ok(Split::NotSplit) };+        let node = sx::parse(def).map_err(|e| refuse("zone_adoption_refused", name, format!("the live definition of zone {id} does not parse: {e}"), json!({"boardZoneId": id})))?;+        let ls = layers_of(&node);+        if ls.len() != 1 { return Ok(Split::NotSplit); }+        by_layer.entry(ls[0].clone()).or_default().push((id, def));+    }+    let all_owned = same.iter().all(|r| r["id"].as_str().is_some_and(|id| owned.iter().any(|o| o == id)));+    let twice: Vec<&String> = by_layer.iter().filter(|(_, v)| v.len() > 1).map(|(l, _)| l).collect();+    let missing: Vec<&String> = want.iter().filter(|l| !by_layer.contains_key(*l)).collect();+    let extra: Vec<&String> = by_layer.keys().filter(|l| !want.contains(l)).collect();+    if !twice.is_empty() || !missing.is_empty() || !extra.is_empty() {+        if all_owned { return Ok(Split::Replace); }+        let mut why = Vec::new();+        if !twice.is_empty() { why.push(format!("more than one on {}", twice.iter().map(|s| s.as_str()).collect::<Vec<_>>().join(", "))); }+        if !missing.is_empty() { why.push(format!("none on {}", missing.iter().map(|s| s.as_str()).collect::<Vec<_>>().join(", "))); }+        if !extra.is_empty() { why.push(format!("one on {}, which the plan zone does not cover", extra.iter().map(|s| s.as_str()).collect::<Vec<_>>().join(", "))); }+        return Ok(Split::Not(format!("they are one-layer zones, but not one per plan layer ({}): adoption needs one zone, or one per layer", why.join("; "))));+    }+    let mut recs = Vec::new();+    let mut diffs_all = Vec::new();+    for l in &want {+        let (id, def) = by_layer[l][0];+        let mut zl = z.clone();+        zl["layers"] = json!([l]);+        let node = sx::parse(def).map_err(|e| refuse("zone_adoption_refused", name, format!("the live definition of zone {id} does not parse: {e}"), json!({"boardZoneId": id})))?;+        let (diffs, outline) = pourverify::adoption_differences(board, &zl, &node).map_err(|e| refuse("zone_adoption_refused", name, e, json!({"boardZoneId": id})))?;+        if !diffs.is_empty() { diffs_all.push(format!("{l} (zone {id}): {}", pourverify::adoption_line(&diffs))); continue; }+        recs.push(json!({"name": name, "id": id, "net": z["net"], "layers": [l], "splitOf": z["layers"], "ownedBefore": owned.iter().any(|o| o == id),+            "fieldsCompared": pourverify::ADOPT_FIELDS, "outline": outline, "definitionSha256": format!("{:x}", Sha256::digest(def.as_bytes()))}));+    }+    if !diffs_all.is_empty() {+        if all_owned { return Ok(Split::Replace); }+        return Ok(Split::Not(format!("they are one zone per plan layer, but not identical to the plan: {}", diffs_all.join("; "))));+    }+    Ok(Split::Adopt(recs))+}+ /// Decide, per plan zone, adopt / keep / send / refuse against a settled `kicad_zone_state` reply /// (`live`, with its `zones` rows and `definitions`). Err is a refusal reply (nothing was landed). pub fn plan(board: &Board, zones: &[Value], live: &Value, owned: &[String]) -> Result<Adoption, Value> {@@ -72,6 +134,19 @@ pub fn plan(board: &Board, zones: &[Value], live: &Value, owned: &[String]) -> R         }         let ids: Vec<&str> = same.iter().filter_map(|r| r["id"].as_str()).collect();         if same.len() > 1 {+            // issue #245: the plan zone split into one one-layer zone per layer, each identical on its layer+            match split_set(board, z, &same, &defs, owned)? {+                Split::Adopt(recs) => {+                    for rec in recs {+                        if let Some(id) = rec["id"].as_str() { not_sent.insert(id.to_string()); }+                        if rec["ownedBefore"] == true { out.kept.push(rec) } else { out.adopted.push(rec) }+                    }+                    continue;+                }+                Split::Replace => { out.send_zones.push(z.clone()); continue; }+                Split::Not(why) => return Err(refuse("zone_adoption_ambiguous", name, format!("planned zone {name:?} matches {} board zones of that name ({}); {why}", same.len(), ids.join(", ")), json!({"boardZoneIds": ids}))),+                Split::NotSplit => {}+            }             return Err(refuse("zone_adoption_ambiguous", name, format!("planned zone {name:?} matches {} board zones of that name ({}); adoption needs exactly one", same.len(), ids.join(", ")), json!({"boardZoneIds": ids})));         }         let Some(id) = ids.first().copied() else {@@ -227,6 +302,35 @@ mod tests {         assert_eq!(r["errorCode"], "zone_adoption_ambiguous");     } +    /// Issue #245: a two-layer plan zone on the board as one one-layer zone per layer, each identical on its layer,+    /// is adopted as a set; a set that misses a layer or differs is refused with the reason.+    #[test]+    fn a_two_layer_zone_split_per_layer_is_adopted_as_a_set() {+        let mut two = plan_zone();+        two["layers"] = json!(["F.Cu", "B.Cu"]);+        let f = staged_def("VLED pour", BODY, PTS);+        let b = f.replace("(layer \"F.Cu\")", "(layer \"B.Cu\")");+        let a = plan(&board(), &[two.clone()], &live(&[("z-f", "VLED pour", f.clone()), ("z-b", "VLED pour", b.clone())]), &[]).unwrap();+        assert_eq!(a.adopted.len(), 2, "{:?}", a.adopted);+        assert!(a.send_zones.is_empty());+        assert_eq!(a.adopted.iter().map(|r| r["layers"][0].as_str().unwrap()).collect::<Vec<_>>(), vec!["F.Cu", "B.Cu"]);+        // both owned and identical: kept+        let k = plan(&board(), &[two.clone()], &live(&[("z-f", "VLED pour", f.clone()), ("z-b", "VLED pour", b.clone())]), &["z-f".into(), "z-b".into()]).unwrap();+        assert_eq!((k.kept.len(), k.send_zones.len()), (2, 0));+        // two on F.Cu, none on B.Cu: refused, and the reason says so+        let r = plan(&board(), &[two.clone()], &live(&[("z-f", "VLED pour", f.clone()), ("z-g", "VLED pour", f.clone())]), &[]).unwrap_err();+        let m = r["message"].as_str().unwrap();+        assert!(m.contains("more than one on F.Cu") && m.contains("none on B.Cu"), "{m}");+        // the B.Cu half differs (another priority): refused naming the layer+        let bp = b.replace("(priority 1)", "(priority 2)");+        let r = plan(&board(), &[two.clone()], &live(&[("z-f", "VLED pour", f.clone()), ("z-b", "VLED pour", bp.clone())]), &[]).unwrap_err();+        assert!(r["message"].as_str().unwrap().contains("B.Cu (zone z-b)"), "{r}");+        // the same, owned by the run: the bridge replaces them with the plan zone+        let s = plan(&board(), &[two], &live(&[("z-f", "VLED pour", f), ("z-b", "VLED pour", bp)]), &["z-f".into(), "z-b".into()]).unwrap();+        assert_eq!(s.send_zones.len(), 1);+        assert_eq!(s.send_owned.len(), 2);+    }+     #[test]     fn owned_zones_are_kept_when_identical_and_sent_when_they_differ() {         let same = plan(&board(), &[plan_zone()], &live(&[("z-1", "VLED pour", staged_def("VLED pour", BODY, PTS))]), &["z-1".into(), "z-9".into()]).unwrap();
crates/adom-aiflow/src/pourverify.rs+52−3
@@ -268,6 +268,24 @@ fn expected_zone(board: &Board, z: &Value, loops: &[Value]) -> Result<Node, Stri  /// `keepouts_landed`: the tool lands keepout zones (KiCad), so each must match a saved zone; otherwise /// each is checked clear of pour copper (`keepout_clear`).+/// Issue #245: a multi-layer plan zone the board carries as one one-layer zone per layer (a generator or a+/// staging script writes it that way): for each plan layer, the plan zone on that layer alone must match exactly+/// one unused board zone. Some(the matches with their expected signatures) when every layer finds one, else None.+fn split_targets(board: &Board, z: &Value, loops: &[Value], actual: &[&Node], signatures: &[Value], used: &std::collections::BTreeSet<usize>) -> Result<Option<Vec<(usize, Value)>>, String> {+    let layers: Vec<Value> = z["layers"].as_array().cloned().unwrap_or_default();+    if layers.len() < 2 || z.get("boardZoneUuid").is_some() { return Ok(None); }+    let mut picked: Vec<(usize, Value)> = Vec::new();+    for l in layers {+        let mut zl = z.clone();+        zl["layers"] = json!([l]);+        let sig = signature(board, &expected_zone(board, &zl, loops)?);+        let m: Vec<usize> = (0..actual.len()).filter(|i| !used.contains(i) && !picked.iter().any(|p| p.0 == *i) && !is_teardrop(actual[*i]) && signatures[*i] == sig).collect();+        if m.len() != 1 { return Ok(None); }+        picked.push((m[0], sig));+    }+    Ok(Some(picked))+}+ pub fn check_with(board: &Board, plan: &Value, keepouts_landed: bool) -> Result<Value, String> {     let zones = plan["zones"]         .as_array()@@ -354,7 +372,12 @@ pub fn check_with(board: &Board, plan: &Value, keepouts_landed: bool) -> Result<             .filter(|i| !used.contains(i) && !is_teardrop(actual[*i]) && signatures[*i] == wanted                 && z.get("boardZoneUuid").is_none_or(|id| zone_id(actual[*i]).as_deref() == id.as_str()))             .collect();-        if matches.len() != 1 {+        // issue #245: one exact match, or (a multi-layer plan zone with none) the same zone split per layer: one+        // identical one-layer board zone for each of its layers, each layer once+        let targets: Vec<(usize, Value)> = if matches.len() == 1 { vec![(matches[0], wanted.clone())] }+            else if matches.is_empty() { split_targets(board, z, &loops, &actual, &signatures, &used)?.unwrap_or_default() }+            else { Vec::new() };+        if targets.is_empty() {             // name the closest unused board zone and every field where it differs             let closest = (0..actual.len())                 .filter(|i| !used.contains(i) && !is_teardrop(actual[*i]))@@ -382,7 +405,8 @@ pub fn check_with(board: &Board, plan: &Value, keepouts_landed: bool) -> Result<             report.push(entry);             continue;         }-        let i = matches[0];+        let split = targets.len() > 1;+        for (i, wanted) in targets {         let n = actual[i];         used.insert(i);         let supported = [@@ -441,7 +465,10 @@ pub fn check_with(board: &Board, plan: &Value, keepouts_landed: bool) -> Result<                 }             }         }-        groups.push(json!({"name":label,"boardZoneIndex":i,"boardZoneUuid":zone_id(n),"ok":true}));+        let mut g = json!({"name":label,"boardZoneIndex":i,"boardZoneUuid":zone_id(n),"ok":true});+        if split { g["splitLayer"] = wanted["layers"][0].clone(); }+        groups.push(g);+        }     }     // No hidden extra copper: every saved copper zone needs an explicit plan entry. A keepout rule area the     // plan does not own (issue #189: drawn by the human to keep copper off a spot) is theirs: it adds no copper,@@ -1029,6 +1056,28 @@ mod tests {         q["zones"][1]["boardZoneUuid"]=json!("");         assert!(check(&board,&q).is_err());     }+    /// Issue #245: a two-layer plan zone saved as one one-layer zone per layer (each filled) verifies, one group per+    /// layer; one layer missing does not.+    #[test]+    fn a_two_layer_zone_split_per_layer_verifies() {+        let p = json!({"zones":[{"net":"GND","layers":["F.Cu","B.Cu"],"polygon":[[0,0],[5,0],[5,5]],"connection":"solid"}]});+        let prefix = r#"(kicad_pcb (version 20260101) (layers (0 "F.Cu" signal) (31 "B.Cu" signal)) (gr_rect (start 0 0) (end 10 10) (layer "Edge.Cuts"))"#;+        let b0 = Board::from_text("test", format!("{prefix})")).unwrap();+        let one = |layer: &str, id: &str| {+            let mut zl = p["zones"][0].clone(); zl["layers"] = json!([layer]);+            let z = aiflow_pours::zone_sexpr(&b0, &zl).unwrap();+            let z = z.trim();+            let z = format!(r#"{} (uuid "{id}") (filled_polygon (layer "{layer}") (pts (xy 0 0) (xy 5 0) (xy 5 5))))"#, &z[..z.len() - 1]);+            z+        };+        let both = Board::from_text("test", format!("{prefix} {} {})", one("F.Cu", "zf"), one("B.Cu", "zb"))).unwrap();+        let r = check(&both, &p).unwrap();+        assert_eq!(r["pass"], true, "{r}");+        assert_eq!(r["groups"].as_array().unwrap().iter().map(|g| g["splitLayer"].as_str().unwrap_or("")).collect::<Vec<_>>(), vec!["F.Cu", "B.Cu"]);+        let half = Board::from_text("test", format!("{prefix} {})", one("F.Cu", "zf"))).unwrap();+        assert_eq!(check(&half, &p).unwrap()["pass"], false);+    }+     #[test]     fn a_human_keepout_outside_the_plan_is_recorded_not_failed() {         // issue #189: a rule area (no copper) the human drew to keep copper off a spot
docs/release-0.2.104.mdadded+10
@@ -0,0 +1,10 @@+# AI Flow 0.2.104++- **A pour split per layer is the same pour** (#245, Drew Owens). A board generator or a staging script often+  writes a two-layer pour as one one-layer zone per layer, with the same name, net, outline and settings.+  - `land pours` adopts (or, when the run owns them, keeps) such a set when it is one zone per plan layer, each+    identical to the plan zone on its layer, with one adoption record per zone. A set that misses a layer, has a+    layer twice or differs is refused with the reason (the layer, or the layer and the field). A set the run owns+    that no longer matches is replaced by the plan zone, as one owned zone is.+  - `verify-pours` accepts the same set: one exact one-layer match per plan layer, each with its saved fill,+    reported as one group per layer (`splitLayer`).
package.json+1−1
@@ -1,7 +1,7 @@ {   "slug": "adom-aiflow",   "type": "app",-  "version": "0.2.103",+  "version": "0.2.104",   "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.103",+  "version": "0.2.104",   "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.",