← Commit history
AI Flow 0.2.103: PRs #149 and #150 (Drew Owens), #246, #248
Co-Authored-By: Claude Opus 5.5 <[email protected]>
12 files changed
+241−23
Cargo.lock+10−10Cargo.toml+1−1bin/adom-aiflowcrates/adom-aiflow/src/edge_overhang.rs+39−1crates/adom-aiflow/src/main.rs+20−3crates/adom-aiflow/src/placement_verify.rs+30crates/adom-aiflow/src/schematic_check.rs+42crates/aiflow-bridge/src/landing.rs+46−5crates/aiflow-bridge/src/lib.rs+33−1docs/release-0.2.103.md+18package.json+1−1page.json+1−1Cargo.lock+10−10@@ -4,7 +4,7 @@ version = 4 [[package]] name = "adom-aiflow"-version = "0.2.102"+version = "0.2.103" dependencies = [ "aiflow-analyze", "aiflow-board",@@ -25,7 +25,7 @@ dependencies = [ [[package]] name = "aiflow-analyze"-version = "0.2.102"+version = "0.2.103" dependencies = [ "aiflow-board", "serde",@@ -35,7 +35,7 @@ dependencies = [ [[package]] name = "aiflow-board"-version = "0.2.102"+version = "0.2.103" dependencies = [ "roxmltree", "serde",@@ -44,7 +44,7 @@ dependencies = [ [[package]] name = "aiflow-bridge"-version = "0.2.102"+version = "0.2.103" dependencies = [ "aiflow-board", "serde",@@ -53,7 +53,7 @@ dependencies = [ [[package]] name = "aiflow-copper"-version = "0.2.102"+version = "0.2.103" dependencies = [ "aiflow-board", "aiflow-grid",@@ -63,7 +63,7 @@ dependencies = [ [[package]] name = "aiflow-grid"-version = "0.2.102"+version = "0.2.103" dependencies = [ "aiflow-board", "serde",@@ -72,7 +72,7 @@ dependencies = [ [[package]] name = "aiflow-place"-version = "0.2.102"+version = "0.2.103" dependencies = [ "aiflow-board", "serde",@@ -81,7 +81,7 @@ dependencies = [ [[package]] name = "aiflow-pours"-version = "0.2.102"+version = "0.2.103" dependencies = [ "aiflow-board", "aiflow-copper",@@ -91,7 +91,7 @@ dependencies = [ [[package]] name = "aiflow-router"-version = "0.2.102"+version = "0.2.103" dependencies = [ "aiflow-board", "aiflow-grid",@@ -101,7 +101,7 @@ dependencies = [ [[package]] name = "aiflow-run"-version = "0.2.102"+version = "0.2.103" dependencies = [ "serde", "serde_json",
Cargo.toml+1−1@@ -14,7 +14,7 @@ members = [ ] [workspace.package]-version = "0.2.102"+version = "0.2.103" edition = "2021" license = "MIT" repository = "https://wiki.adom.inc/adom/adom-aiflow"
bin/adom-aiflow⋯ 1 unchanged line ⋯
crates/adom-aiflow/src/edge_overhang.rs+39−1@@ -21,7 +21,7 @@ pub fn allowed(spec: &Value, cli: &[String]) -> Result<Vec<(String, String)>, St } } for r in cli.iter().map(|r| r.trim()).filter(|r| !r.is_empty()) {- if !out.iter().any(|(x, _)| x == r) { out.push((r.to_string(), "--allow-outside on the command line".into())); }+ if !out.iter().any(|(x, _)| x == r) { out.push((r.to_string(), CLI_WHY.into())); } } Ok(out) }@@ -50,6 +50,44 @@ pub fn check_board(b: &Board, allowed: &[(String, String)]) -> Result<Vec<String Ok(allowed.iter().map(|(r, why)| format!("edge overhang allowed for {r} ({why}): its body may cross the outline, every pad and copper item is inside")).collect()) } +/// A part allowed past the outline only by `placement.edgeOverhang` (or `--allow-outside`) lands, but+/// `place verify` accepts a part outside the outline only with a `placement.edgeConnectors` entry+/// (docs/edge-connectors.md), and before this the offline steps never said so: the spec had to change in+/// the live phase. One line per such part whose courtyard crosses the outline on `b`, with the entry+/// drafted from the board: its footprint, the edge it crosses, the overhang rounded up to 0.05 mm, the+/// why. A part with castellated edge pads needs no entry (place verify accepts it as it is).+pub fn verify_notes(b: &Board, spec: &Value, allowed: &[(String, String)]) -> Vec<String> {+ let declared = spec["placement"]["edgeConnectors"].as_object();+ let boxes = aiflow_place::boxes(b);+ let (x0, y0, x1, y1) = b.bbox;+ let mut out = Vec::new();+ for (r, why) in allowed {+ if declared.is_some_and(|d| d.contains_key(r)) { continue; }+ if b.pads.iter().any(|p| &p.reference == r && b.castellated_on_edge(p)) { continue; }+ let (Some(fp), Some(c)) = (b.footprints.get(r), boxes.get(r)) else { continue };+ let past: Vec<(&str, f64)> = [("minX", x0 - c.0), ("minY", y0 - c.1), ("maxX", c.2 - x1), ("maxY", c.3 - y1)].into_iter().filter(|(_, d)| *d > 1e-6).collect();+ if past.is_empty() { continue; }+ let by = if why == CLI_WHY { "--allow-outside" } else { "placement.edgeOverhang" };+ let head = format!("{r} is allowed past the outline only by {by}, so `place verify` (live) will refuse it until the spec has placement.edgeConnectors.{r} (docs/edge-connectors.md)");+ if aiflow_place::courtyard_local(b, r).is_none() {+ out.push(format!("NOTE: {head}; that entry is judged by the courtyard, and {r}'s footprint has none"));+ continue;+ }+ if past.len() > 1 {+ out.push(format!("NOTE: {head}; that entry allows one straight edge, and {r}'s courtyard crosses {}", past.iter().map(|(e, d)| format!("{e} by {d:.2} mm")).collect::<Vec<_>>().join(" and ")));+ continue;+ }+ let (edge, d) = past[0];+ let bound = (((d - 1e-6) / 0.05).ceil() * 0.05 * 100.0).round() / 100.0;+ let reason = if why == CLI_WHY { "<what the overhang is for>" } else { why.as_str() };+ let entry = json!({ r.as_str(): {"footprint": fp.lib, "edge": edge, "maxCourtyardOverhangMm": bound, "reason": reason} });+ out.push(format!("NOTE: {head}; its courtyard crosses {edge} by {d:.2} mm. Add it now, before the live phase: \"edgeConnectors\": {entry}"));+ }+ out+}++const CLI_WHY: &str = "--allow-outside on the command line";+ /// The record for a run's outcome. pub fn record(allowed: &[(String, String)]) -> Value { Value::Array(allowed.iter().map(|(r, w)| json!({"ref": r, "why": w})).collect())
crates/adom-aiflow/src/main.rs+20−3@@ -5225,7 +5225,12 @@ fn main() { let on_sheet = schematic_check::sheet_symbols(&std::fs::read_to_string(&net).unwrap_or_default()).unwrap_or_else(|e| err(&format!("netlist: {e}"), &[])); let lib = r.data["outcomes"]["project-page"]["libName"].as_str().map(|l| format!("PCM_{l}")); let bom_refs: Vec<String> = r.data["outcomes"]["parts"]["parts"].as_array().cloned().unwrap_or_default().iter().flat_map(|p| p["refs"].as_array().cloned().unwrap_or_default()).filter_map(|v| v.as_str().map(str::to_string)).collect();- let missing: Vec<String> = bom_refs.iter().filter(|rf| !on_sheet.contains_key(*rf)).cloned().collect();+ // issue #248: a part the BOM marks off-board (a battery, a coil, a motor wired to the board) is drawn but+ // marked "exclude from board", which leaves it out of the netlist: it counts when the sheet draws it+ let off_board: Vec<String> = r.data["outcomes"]["sourcing"]["offBoard"].as_array().into_iter().flatten().filter_map(|v| v.as_str().map(str::to_string)).collect();+ let drawn = if off_board.is_empty() { Default::default() } else { schematic_check::drawn_refs(Path::new(sch)) };+ let missing: Vec<String> = bom_refs.iter().filter(|rf| !on_sheet.contains_key(*rf) && !(off_board.contains(rf) && drawn.contains(*rf)))+ .map(|rf| if off_board.contains(rf) { format!("{rf} (off-board in the BOM, and no symbol with that reference is drawn)") } else { rf.clone() }).collect(); let foreign: Vec<String> = match &lib { Some(l) => on_sheet.iter().filter(|(rf, (sl, fp))| bom_refs.contains(rf) && (sl != l || !fp.starts_with(&format!("{l}:")))).map(|(rf, (sl, fp))| format!("{rf} ({sl} / {fp})")).collect(), None => Vec::new() }; let extra: Vec<String> = on_sheet.keys().filter(|rf| !bom_refs.contains(rf)).cloned().collect(); // issue #39: symbol polarity drawings, active-device pin types and readability (schematic_symbols.rs)@@ -5445,7 +5450,9 @@ fn main() { let moved: Vec<String> = mv.keys().cloned().collect(); // issue #95: an edge connector may overhang the outline by design, never with copper let overhang = edge_overhang::allowed(&spec_of(&r), allow_outside).unwrap_or_else(|e| err(&e, &[]));- let overhang_lines = edge_overhang::check_board(&nb, &overhang).unwrap_or_else(|e| { note(&e, &[format!("Suggested: move the part inward until every pad is inside; the run's current board is unchanged ({}).", outp.display())]); Vec::new() });+ let mut overhang_lines = edge_overhang::check_board(&nb, &overhang).unwrap_or_else(|e| { note(&e, &[format!("Suggested: move the part inward until every pad is inside; the run's current board is unchanged ({}).", outp.display())]); Vec::new() });+ // AF115: a part only in edgeOverhang lands, but place verify (live) wants edgeConnectors: say it offline+ overhang_lines.extend(edge_overhang::verify_notes(&nb, &spec_of(&r), &overhang)); let problems = aiflow_place::check_allowing(&nb, &moved, 0.05, &edge_overhang::refs(&overhang)); // issue #140: every part outside the outline, moved or not (a part pack found no spot for is not in the moves) let outside = aiflow_place::parts_outside(&nb, &edge_overhang::refs(&overhang));@@ -5499,6 +5506,7 @@ fn main() { for l in edge_overhang::check_moves(&b, &mv, &overhang).unwrap_or_else(|e| err(&e, &["Nothing was landed. Move the part inward until every pad is inside.".into()])) { eprintln!("{l}"); } // issue #140: parts that will still be outside the outline once these moves land (named, then landed anyway) let landed_board = aiflow_place::moves_from_json(&mv).ok().and_then(|m| aiflow_place::move_in_text(&b, &m).ok()).and_then(|(t, _)| Board::from_text(&b.path, t).ok());+ for l in edge_overhang::verify_notes(landed_board.as_ref().unwrap_or(&b), &spec_of(&r), &overhang) { eprintln!("{l}"); } if let Some(after) = landed_board.as_ref() { land_moves::fill_rotations(&mut mv, after); // issue #142: a Fusion move must keep each part on its side; read from the live board, not the run's copy@@ -6018,11 +6026,20 @@ fn main() { } if let Some(i) = stopped { let rep = res.replies.last().cloned().unwrap_or(Value::Null);+ // issue #246: the board could not be read before the first trace: say that, not "trace 1"+ if res.read_failed {+ let t = rep["aiflowIpcTimeoutMs"].as_u64().map(|t| format!("{t} ms")).unwrap_or_else(|| "the bridge's default".into());+ let mac = br.target_os().is_some_and(|o| o.contains("mac") || o.contains("darwin"));+ err(&format!("live {what}: nothing landed, the live board could not be read (last limit {t}): {} {}", rep["errorCode"].as_str().unwrap_or("?"), rep["message"].as_str().or(rep["error"].as_str()).unwrap_or("")), &[+ "A big board's full read takes seconds; set AIFLOW_IPC_TIMEOUT_MS (milliseconds) higher and land again. A dialog open in the editor blocks every read: close it.".into(),+ if mac { "On a Mac an editor behind other windows is slowed by App Nap: bring KiCad forward once, or allow the screen (`capture screen allowed`), and land again.".into() } else { String::new() }]);+ } if rep["errorCode"] == "via_touches_other_net" || rep["errorCode"] == "via_hole_clash" {- err(&format!("live {what} refused before landing anything: trace {} of {traces}: {}", i + 1, rep["message"].as_str().unwrap_or("")), &["Move the via clear of that copper (spec thermalVias/stitchVias or the plan; an entry's \"size\" and \"drill\" set its via, and spec viaClearance or the project's .kicad_dru its clearance), run `pour` or `gate` again, then land. Nothing was landed by this command.".into()]);+ err(&format!("live {what} refused before landing anything: trace {} of {traces}: {}", i + 1, rep["message"].as_str().unwrap_or("")), &["Move the via clear of that copper (spec thermalVias/stitchVias or the plan; an entry's \"size\" and \"drill\" set its via, and spec viaClearance or the project's .kicad_dru its clearance to other nets' vias; vias of one net need only the hole-to-hole minimum and copper that does not overlap), run `pour` or `gate` again, then land. Nothing was landed by this command.".into()]); } err(&format!("live {what} stopped at trace {} of {}: {} {}", i + 1, traces, rep["errorCode"], rep["message"].as_str().unwrap_or("")), &["A drc_rejected means the live board differs from the gated copy; read kicad_routing_state and gate again.".into(), format!("Rerun `land {what}` once fixed: traces already on the live board are skipped. To resume at this trace: `adom-aiflow land {what}{} --from {}`. The log has every reply.", plan.as_ref().map(|p| format!(" --plan {p}")).unwrap_or_default(), i + 1)]); }+ if traces == 0 { ok(&format!("{what}: nothing to land, the plan {planp} has no traces; the live board was not read"), &[]); return; } let skipped_note = if res.skipped > 0 { format!(", {} already on the board skipped", res.skipped) } else { String::new() }; ok(&format!("{what} landed live: {accepted} trace(s) of {} net entries{skipped_note}, one at a time, one undo step each, {:.1} s", entries.len(), t0.elapsed().as_secs_f64()), &[if what == "route" { "Next: adom-aiflow pour, land vias, land pours.".into() } else { "Next: adom-aiflow land pours.".into() }]); }
crates/adom-aiflow/src/placement_verify.rs+30@@ -336,6 +336,36 @@ mod tests { let e=check_with_spec(&copper_outside,&state,&native,&state,"board",&spec).unwrap_err(); assert!(e.contains("pad J1.A1 reaches outside the outline"),"{e}"); }+ #[test]+ fn the_offline_steps_draft_the_edge_connector_entry_place_verify_accepts() {+ // a part only in edgeOverhang: place check and place land say, before the live phase, what place verify+ // will want, and the entry they draft is one place verify accepts+ let (_,mut state,mut native)=fixture();+ let board=Board::from_text("edge", "(kicad_pcb (gr_rect (start 0 0) (end 10 10) (layer \"Edge.Cuts\")) (footprint \"Test:EDGE_CONN\" (layer \"F.Cu\") (at 5 5 0) (property \"Reference\" \"J1\") (fp_rect (start -1 -1) (end 5.4 1) (layer \"F.CrtYd\")) (pad \"1\" smd rect (at 0 0) (size 1 1) (layers \"F.Cu\" \"F.Mask\"))))".into()).unwrap();+ state["footprints"][0]=json!({"ref":"J1","x":5,"y":5,"rotation":0,"side":"F.Cu","footprint":"Test:EDGE_CONN","insideOutline":false,"courtyardSource":"courtyard","courtyard":{"minX":4,"minY":4,"maxX":10.4,"maxY":6}});+ native["outsideOutline"]=json!(["J1"]);native["placed"]=json!(false);+ let only=json!({"placement":{"edgeOverhang":[{"ref":"J1","why":"connector mouth proud of the edge"}]}});+ assert!(check_with_spec(&board,&state,&native,&state,"board",&only).is_err());+ let allowed=crate::edge_overhang::allowed(&only,&[]).unwrap();+ let notes=crate::edge_overhang::verify_notes(&board,&only,&allowed);+ assert_eq!(notes.len(),1,"{notes:?}");+ assert!(notes[0].contains("placement.edgeConnectors.J1") && notes[0].contains("crosses maxX by 0.40 mm"),"{}",notes[0]);+ let drafted:Value=serde_json::from_str(notes[0].split("\"edgeConnectors\": ").nth(1).unwrap()).unwrap();+ assert_eq!(drafted["J1"],json!({"footprint":"Test:EDGE_CONN","edge":"maxX","maxCourtyardOverhangMm":0.4,"reason":"connector mouth proud of the edge"}));+ let mut both=only.clone();both["placement"]["edgeConnectors"]=drafted;+ assert_eq!(check_with_spec(&board,&state,&native,&state,"board",&both).unwrap().accepted,1);+ // declared: no note; inside the outline: no note; --allow-outside only: the note, with a reason to write+ assert!(crate::edge_overhang::verify_notes(&board,&both,&crate::edge_overhang::allowed(&both,&[]).unwrap()).is_empty());+ let inside=Board::from_text("edge",board.text.replace("(end 5.4 1)","(end 4.9 1)")).unwrap();+ assert!(crate::edge_overhang::verify_notes(&inside,&only,&allowed).is_empty());+ let cli=crate::edge_overhang::allowed(&json!({}),&["J1".into()]).unwrap();+ let n=crate::edge_overhang::verify_notes(&board,&json!({}),&cli);+ assert!(n.len()==1 && n[0].contains("only by --allow-outside") && n[0].contains("<what the overhang is for>"),"{n:?}");+ // a courtyard past two edges: place verify allows one straight edge, so no entry is drafted+ let corner=Board::from_text("edge",board.text.replace("(start -1 -1) (end 5.4 1)","(start -1 -1) (end 5.4 5.3)")).unwrap();+ let n=crate::edge_overhang::verify_notes(&corner,&only,&allowed);+ assert!(n.len()==1 && n[0].contains("maxX by 0.40 mm and maxY by 0.30 mm") && !n[0].contains("\"edgeConnectors\""),"{n:?}");+ } /// Two concentric copper-only rings (ring courtyards, no pads) and a resistor R1 inside the inner ring, /// as the live state and the bridge's box verdict report them. fn rings() -> (Board,Value,Value) {
crates/adom-aiflow/src/schematic_check.rs+42@@ -54,6 +54,33 @@ pub fn run_erc(cli: &str, sch: &str, report: &Path) -> Result<(Value, Vec<String }) } +/// Issue #248: the references drawn in a schematic and its sheets (every .kicad_sch beside it, one level of+/// sub-folders too): a symbol's Reference property and each hierarchical instance's reference. KiCad leaves a+/// symbol marked "exclude from board" (a battery, a coil, a motor wired to the board) out of the netlist, so+/// these are read from the files.+pub fn drawn_refs(sch: &Path) -> std::collections::BTreeSet<String> {+ let dir = sch.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or(Path::new("."));+ let mut files: Vec<std::path::PathBuf> = vec![sch.to_path_buf()];+ for d in std::iter::once(dir.to_path_buf()).chain(std::fs::read_dir(dir).into_iter().flatten().flatten().map(|e| e.path()).filter(|p| p.is_dir())) {+ for e in std::fs::read_dir(&d).into_iter().flatten().flatten() {+ let p = e.path();+ if p.extension().is_some_and(|x| x == "kicad_sch") && !files.contains(&p) { files.push(p); }+ }+ }+ let re = regex_lite::Regex::new(r#"\(property\s+"Reference"\s+"([^"]+)"|\(reference\s+"([^"]+)"\)"#).unwrap();+ let mut out = std::collections::BTreeSet::new();+ for f in files {+ let t = std::fs::read_to_string(&f).unwrap_or_default();+ for c in re.captures_iter(&t) {+ if let Some(m) = c.get(1).or_else(|| c.get(2)) {+ let r = m.as_str();+ if !r.starts_with('#') && !r.ends_with('?') { out.insert(r.to_string()); }+ }+ }+ }+ out+}+ #[cfg(test)] mod tests { use super::*;@@ -115,4 +142,19 @@ mod tests { assert!(e.contains("ERC did not run") && e.contains("only 'pcb drc'"), "{e}"); let _ = std::fs::remove_dir_all(&dir); }++ /// Issue #248: an exclude-from-board symbol (never in the netlist) is read from the sheet files, a sub-sheet's+ /// instance reference too; power symbols (#PWR) and unannotated ones (R?) are not parts.+ #[test]+ fn off_board_symbols_are_read_from_the_sheet_files() {+ let d = std::env::temp_dir().join(format!("aiflow-sch-{}", std::process::id()));+ std::fs::create_dir_all(d.join("sub")).unwrap();+ std::fs::write(d.join("root.kicad_sch"), r##"(kicad_sch (symbol (lib_id "Device:Battery") (exclude_from_board yes) (property "Reference" "BT1" (at 0 0 0)))+ (symbol (lib_id "power:GND") (property "Reference" "#PWR01" (at 0 0 0))) (symbol (lib_id "Device:R") (property "Reference" "R?" (at 0 0 0))))"##).unwrap();+ std::fs::write(d.join("sub").join("motor.kicad_sch"), r#"(kicad_sch (symbol (lib_id "Motor:Motor_DC") (instances (project "p" (path "/x" (reference "M1") (unit 1))))))"#).unwrap();+ let got = drawn_refs(&d.join("root.kicad_sch"));+ assert!(got.contains("BT1") && got.contains("M1"), "{got:?}");+ assert!(!got.contains("#PWR01") && !got.contains("R?"));+ let _ = std::fs::remove_dir_all(&d);+ } }
crates/aiflow-bridge/src/landing.rs+46−5@@ -186,9 +186,11 @@ pub fn plan_holes(plan: &Value, pads: &BTreeMap<String, (String, Pt)>) -> Vec<Ho } /// The first hole a planned via of `net` at `at` (copper `size`, `drill`) clashes with: drill edge-/// to drill edge under `h2h`, or, for another via of any net, copper edge to copper edge under-/// `clearance` (a same-net via on top of another is still a drill clash; issue #83). The same via-/// (same net, same point) is not a clash with itself.+/// to drill edge under `h2h`, or, for a via of another net, copper edge to copper edge under+/// `clearance`. A via of the same net needs no copper clearance (KiCad's DRC applies none between+/// items of one net, and the fab's rule for them is the hole-to-hole minimum), but one whose copper+/// overlaps another's is still refused: a via planned on top of an existing via (issue #83). The same+/// via (same net, same point) is not a clash with itself. pub fn via_hole_clash(net: &str, at: Pt, size: f64, drill: f64, holes: &[Hole], h2h: f64, clearance: f64) -> Option<String> { let eps = 1e-4; holes.iter().find_map(|h| {@@ -198,8 +200,16 @@ pub fn via_hole_clash(net: &str, at: Pt, size: f64, drill: f64, holes: &[Hole], if d + eps < drills { return Some(format!("{}: centres {d:.2} mm apart, under the {:.2} mm hole-to-hole minimum ({h2h} mm drill edge to drill edge)", h.what, drills)); }+ if !h.via { return None; }+ if h.net == net {+ let overlap = (size + h.size) / 2.0;+ if d + eps < overlap {+ return Some(format!("{}: centres {d:.2} mm apart, under the {overlap:.2} mm via-to-via spacing of one net (the two vias' copper overlaps)", h.what));+ }+ return None;+ } let copper = (size + h.size) / 2.0 + clearance;- if h.via && d + eps < copper {+ if d + eps < copper { return Some(format!("{}: centres {d:.2} mm apart, under the {:.2} mm via-to-via spacing ({clearance} mm copper clearance)", h.what, copper)); } None@@ -257,6 +267,8 @@ pub struct Landing { pub traces: usize, /// already on the live board: not landed again pub skipped: usize,+ /// issue #246: the live board could not be read before the first trace (the last reply says why)+ pub read_failed: bool, /// before --from pub before_from: usize, /// the reply was lost but the read-back shows the trace landed@@ -282,8 +294,10 @@ pub fn land_traces_with( mut progress: impl FnMut(usize, usize, &Value, &Value), ) -> Landing { let mut out = Landing { traces: traces.len(), ..Default::default() };+ // issue #246: nothing to land, nothing to read (a full read of a big board is seconds, a minute in App Nap)+ if traces.is_empty() { return out; } let (revision, state) = read();- let Some(mut rev) = revision else { out.replies.push(state); out.stopped = Some(0); return out };+ let Some(mut rev) = revision else { out.replies.push(state); out.stopped = Some(0); out.read_failed = true; return out }; let live = LiveCopper::from_state(&state); let mut todo: Vec<usize> = Vec::new(); for (i, e) in traces.iter().enumerate() {@@ -433,6 +447,24 @@ mod tests { assert!(via_hole_clash("GND", (120.5, 80.0), 0.6, 0.3, &plan_holes(&plan, &live.pads), 0.25, 0.2).is_some()); } + #[test]+ fn vias_of_one_net_need_the_hole_minimum_not_the_copper_clearance() {+ // two parallel VIN paths, each dropping through a 0.6/0.3 via, the vias 0.65 mm apart: drill edges+ // 0.35 mm apart and copper edges 0.05 mm apart. KiCad's DRC passes it (no clearance within one net).+ let plan = json!({"nets": [via_entry("VIN", 12.0, 13.35)]});+ let holes = plan_holes(&plan, &BTreeMap::new());+ assert!(via_hole_clash("VIN", (12.0, 14.0), 0.6, 0.3, &holes, 0.2, 0.2).is_none(), "same net, 0.65 mm apart, clear of the 0.2 mm hole minimum");+ // the hole-to-hole minimum still holds within one net+ let h = via_hole_clash("VIN", (12.0, 14.0), 0.6, 0.3, &holes, 0.4, 0.2).expect("drills 0.35 mm apart, minimum 0.4");+ assert!(h.contains("hole-to-hole minimum"), "{h}");+ // a via of another net at the same place keeps the copper clearance+ let other = via_hole_clash("GND", (12.0, 14.0), 0.6, 0.3, &holes, 0.2, 0.2).expect("another net 0.05 mm away");+ assert!(other.contains("0.80 mm via-to-via spacing (0.2 mm copper clearance)"), "{other}");+ // one net, copper overlapping: still a via on top of a via (issue #83)+ let over = via_hole_clash("VIN", (12.0, 13.9), 0.6, 0.3, &holes, 0.2, 0.2).expect("0.55 mm apart, the copper overlaps");+ assert!(over.contains("copper overlaps"), "{over}");+ }+ #[test] fn a_landed_via_on_another_net_is_named_with_both_nets() { let live = LiveCopper::from_state(&state("r", &[], &[json!({"position": {"x": 113.3, "y": 92.55}, "net_name": "/SW", "size": 0.6, "uuid": "vsw"})]));@@ -470,6 +502,15 @@ mod tests { (l, calls) } + /// Issue #246: an empty plan reads nothing (run() panics on an unexpected read); a first read that fails is marked.+ #[test]+ fn an_empty_plan_reads_nothing_and_a_failed_read_is_named() {+ let (l, calls) = run(&[], 1, vec![], vec![], false);+ assert!(calls.is_empty() && l.stopped.is_none() && !l.read_failed);+ let (l, _) = run(&[trace(5.0)], 1, vec![], vec![json!({"success": false, "errorCode": "ipc_timeout"})], false);+ assert_eq!((l.stopped, l.read_failed), (Some(0), true));+ }+ fn trace(x: f64) -> Value { json!({"net": "+5V", "width": 0.4, "points": [[x, 10.0], [x, 20.0]]}) }
crates/aiflow-bridge/src/lib.rs+33−1@@ -21,6 +21,16 @@ pub const PULL_ATTEMPTS: usize = 3; // Waiting cannot repair an explicit identity/configuration refusal. In particular, // never conceal the requested/open board identities behind a generic no_revision.+/// Issue #246: the IPC limits a live read tries in turn: the one set (else the bridge's default, None), then+/// 30 s, then 120 s. A slow board (a big one, or an editor macOS put in App Nap) gets longer; it is never read+/// twenty times at a limit it cannot meet.+pub fn ipc_timeouts(set: Option<u64>) -> std::vec::IntoIter<Option<u64>> {+ let first = set.filter(|t| *t > 0);+ let mut v = vec![first];+ for t in [30_000u64, 120_000] { if first.map_or(true, |f| t > f) { v.push(Some(t)); } }+ v.into_iter()+}+ fn retryable_read(reply: &Value) -> bool { !matches!(reply["errorCode"].as_str(), Some("board_mismatch" | "invalid_socket" | "invalid_path" | "api_server_off" | "unsupported_kicad" | "no_pcb_frame" | "permission_denied")) }@@ -489,14 +499,24 @@ impl Bridge { pub fn revision_with_reply(&self, board: &str) -> (Option<String>, Value) { let mut last = Value::Null;+ // issue #246: AIFLOW_IPC_TIMEOUT_MS when set (else the bridge's own default); an ipc_timeout is read again+ // with a longer limit (ipc_timeouts), never twenty times at the same one+ let mut steps = ipc_timeouts(std::env::var("AIFLOW_IPC_TIMEOUT_MS").ok().and_then(|v| v.parse::<u64>().ok()));+ let mut timeout = steps.next().flatten(); for attempt in 0..20 {- let r = self.call("kicad_routing_state", &json!({"filePath": board}));+ let mut args = json!({"filePath": board});+ if let Some(t) = timeout { args["ipcTimeoutMs"] = json!(t); }+ let r = self.call("kicad_routing_state", &args); if let Some(rev) = r.get("revision").and_then(|r| r.as_str()) { return (Some(rev.to_string()), r); } eprintln!("revision read {}: {} {}", attempt + 1, r["errorCode"].as_str().or(r["status"].as_str()).unwrap_or("?"), r["error"].as_str().or(r["message"].as_str()).unwrap_or("").chars().take(120).collect::<String>()); last = r;+ if let Some(o) = last.as_object_mut() { o.insert("aiflowIpcTimeoutMs".into(), json!(timeout)); } if !retryable_read(&last) { break; }+ if last["errorCode"] == "ipc_timeout" {+ match steps.next() { Some(t) => { timeout = t; continue; } None => break }+ } std::thread::sleep(std::time::Duration::from_secs(6)); } (None, last)@@ -1345,6 +1365,18 @@ mod pcb_editor_tests { } } +#[cfg(test)]+mod ipc_timeout_tests {+ /// Issue #246: the bridge's default (or the set limit), then 30 s, then 120 s; never the same limit twice.+ #[test]+ fn a_timed_out_read_gets_longer_limits_and_stops() {+ assert_eq!(super::ipc_timeouts(None).collect::<Vec<_>>(), vec![None, Some(30_000), Some(120_000)]);+ assert_eq!(super::ipc_timeouts(Some(60_000)).collect::<Vec<_>>(), vec![Some(60_000), Some(120_000)]);+ assert_eq!(super::ipc_timeouts(Some(200_000)).collect::<Vec<_>>(), vec![Some(200_000)]);+ assert_eq!(super::ipc_timeouts(Some(0)).collect::<Vec<_>>(), vec![None, Some(30_000), Some(120_000)]);+ }+}+ #[cfg(test)] mod live_socket_tests { use super::*;
docs/release-0.2.103.mdadded+18@@ -0,0 +1,18 @@+# AI Flow 0.2.103++- **Vias of one net** (Drew Owens, PR #149). `land route` refused two vias of the same net closer than the copper+ clearance, which KiCad's DRC and the fab accept: one net needs no copper clearance. Same-net vias now need the+ hole-to-hole minimum and are refused only when their copper overlaps (a via on a via, issue #83).+- **Edge connectors said offline** (Drew Owens, PR #150). A part allowed past the outline only by+ `placement.edgeOverhang` lands, but `place verify` wants a `placement.edgeConnectors` entry. `place check` and+ `place land` now say so before the live phase and draft the entry from the board.+- **Live reads** (#246, Drew Owens).+ - A plan with no traces is "nothing to land", with no read of the live board.+ - Live reads take `AIFLOW_IPC_TIMEOUT_MS` when set; a read that times out is tried again at 30 s, then 120 s,+ and stops, instead of twenty times at the same limit.+ - A landing whose first read fails says the live board could not be read and the last limit, with the setting+ to raise and, on a Mac, App Nap; not "trace 1 of 0" and a DRC hint.+- **Off-board parts on the schematic** (#248, Andy E). `schematic check` no longer reports a part the BOM marks+ off-board (a battery, a coil, a motor) as "not on the sheet" when the schematic draws it: KiCad leaves an+ "exclude from board" symbol out of the netlist, so these are read from the sheet files. An off-board part that is+ not drawn is still named.
package.json+1−1@@ -1,7 +1,7 @@ { "slug": "adom-aiflow", "type": "app",- "version": "0.2.102",+ "version": "0.2.103", "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.102",+ "version": "0.2.103", "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.",