← Commit history
feat(testplan): capture test-fixture mode at intake and enforce bottom bed-of-nails DFT rules (#218)
5 files changed
+685−37
crates/adom-aiflow/src/main.rs+40−17@@ -4223,10 +4223,18 @@ fn main() { record_usage(&mut r, "start"); r.save().unwrap(); let _ = TURN.set((dir.clone(), idx));- let profile = preboard::named_profile(&requirements_of(&r));+ let req_v = requirements_of(&r);+ let profile = preboard::named_profile(&req_v);+ let fixture_hint = testplan::intake_fixture_hint(&req_v);+ let fixture_cfg = testplan::TestFixtureConfig::from_sources(&json!({}), &req_v);+ if fixture_cfg.explicit {+ r.data["testFixture"] = fixture_cfg.to_json();+ r.save().unwrap();+ } ok(&format!("intake run started at {}; the clock started at the prompt, {prompt_time}; step intake is open and there is no board yet", dir.display()), &[ "Pre-board steps are steps like any other: `step sourcing`, `step design`, `step simulation`, `step schematic`; every command is a turn charged to the step you declared, and with --target each step before the board films the tool's own window when the step works in it, else Hydrogen with the run's dashboard, else your own terminal window (nothing meaningful on screen is a recorded skip): work in a visible window.".into(), match profile { Some(p) => format!("Sourcing profile {p} (from the requirements): `sourcing check --bom design/bom.csv` gates the BOM; finish requires it."), None => "No sourcing profile named yet: write requirements.json with fab.target `fab` (default) or `jlcpcb` (aiflow-intake), then `sourcing check --bom <csv> --requirements requirements.json`.".into() },+ fixture_hint, "Record the design record as it lands: `evidence add --kind calcs --file design/calcs.json`, `evidence add --kind simulation --file sim/<results>.json` (a failing simulation is refused), `evidence add --kind vendor-model --file <result>` for a vendor PSpice/LTspice run (adom/adom-spice-skillpack).".into(), "When the board exists: `start --board B.kicad_pcb --spec spec.json --engine <you> [--target <box> --remote-board <path>]` on this same --run attaches it; the clock stays at the prompt.".into(), if r.data["page"].is_null() { "Name the run's page once (`clips --page <owner/slug>` or `report --page ...`) so every clip lands on docs/clips.md as it stops.".into() } else { String::new() },@@ -6128,9 +6136,10 @@ fn main() { if copper_carry::silk_dropped(&r.data) { missing.push("silkscreen proof (adopt-board changed the board file; `silkscreen-audit --record` again)".into()); } // the test plan again, on the finished board: every measurement still has a landing if let Some(tp) = r.data["testPlan"].as_str().map(str::to_string) {- let list = testplan::tests_of(&read_json(&tp));- let (_, gaps, _) = testplan::check_board(&list, &board_now());- if !gaps.is_empty() { missing.push(format!("test plan: no probe landing on {} (`testplan check` says why)", gaps.join(", "))); }+ let req_v = requirements_of(&r);+ let (list, fixture_cfg) = testplan::tests_of_with_fixture(&read_json(&tp), &req_v);+ let (_, gaps, _) = testplan::check_board_with_fixture(&list, &board_now(), &fixture_cfg);+ if !gaps.is_empty() { missing.push(format!("test plan ({}): no probe landing or fixture check gap on {} (`testplan check` says why)", fixture_cfg.mode, gaps.join(", "))); } } let (qv, mut quality_lines) = route_quality::of_board(&board_now(), &spec_soft(&r)); // issues #129, #130: the report card says when the board was not ranked (a suggestion, not an open item)@@ -6900,42 +6909,56 @@ fn main() { let mut r = load_run(&cli); let tp = tests.clone().or_else(|| r.data["testPlan"].as_str().map(str::to_string)).unwrap_or_else(|| err("testplan check needs --tests tests.json the first time", &["Write tests.json: [{id, what, net, why, kind: dc|ripple|waveform|camera|ground, expect}], one per measurement you will take on the probing workcell (skill aiflow-test-plan).".into()])); let tv = read_json(&tp);- let list = testplan::tests_of(&tv);+ let req_v = requirements_of(&r);+ let (list, fixture_cfg) = testplan::tests_of_with_fixture(&tv, &req_v); if list.is_empty() { err(&format!("{tp} has no tests"), &["A board with nothing to measure has not been thought through: list the rails, the switch node, feedback, ripple, enable and every LED.".into()]); } let tp_abs = std::fs::canonicalize(&tp).map(|p| p.display().to_string()).unwrap_or(tp.clone()); r.data["testPlan"] = json!(tp_abs); let has_board = r.data["boards"].as_array().map(|a| !a.is_empty()).unwrap_or(false); let (rows, gaps, notes, added, mode) = if has_board {- let (rows, gaps, warn) = testplan::check_board(&list, &board_of(&r));+ let (rows, gaps, warn) = testplan::check_board_with_fixture(&list, &board_of(&r), &fixture_cfg); (rows, gaps, warn, Vec::new(), "board") } else { let np = netlist.clone().unwrap_or_else(|| err("before the board, testplan check needs --netlist <netlist.json>", &[])); let mut nl = read_json(&np);- let (mut rows, mut gaps, unknown) = testplan::check_netlist(&list, &nl);+ let (mut rows, mut gaps, unknown) = testplan::check_netlist_with_fixture(&list, &nl, &fixture_cfg); if !unknown.is_empty() { err(&format!("tests name nets the netlist does not have: {}", unknown.join(", ")), &["Use the netlist's own net names (or rename the net in the design so the measurement has a name).".into()]); }- let fixable = testplan::addable(&rows);+ let fixable = testplan::addable_for_fixture(&rows, &fixture_cfg); let added = if *add && !fixable.is_empty() {- let a = testplan::add_test_points(&mut nl, &fixable); write_json(Path::new(&np), &nl);+ let a = testplan::add_test_points_for_fixture(&mut nl, &fixable, &fixture_cfg); write_json(Path::new(&np), &nl); // issue #143: the footprint, symbol and 3D model come with the binary; the wiki page is private- match testplan::write_test_point_files(Path::new(&np).parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or(Path::new("."))) {- Ok(to) => eprintln!("test point footprint, symbol, Fusion library and 3D model: {}", to.display()),- Err(e) => eprintln!("WARNING the test point files could not be written: {e}"),+ if !fixture_cfg.is_bed_of_nails() {+ match testplan::write_test_point_files(Path::new(&np).parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or(Path::new("."))) {+ Ok(to) => eprintln!("test point footprint, symbol, Fusion library and 3D model: {}", to.display()),+ Err(e) => eprintln!("WARNING the test point files could not be written: {e}"),+ } } // the table and the gaps as the netlist now stands: only a ground test with no contact is left- let again = testplan::check_netlist(&list, &nl); rows = again.0; gaps = again.1;+ let again = testplan::check_netlist_with_fixture(&list, &nl, &fixture_cfg); rows = again.0; gaps = again.1; a } else { vec![] }; (rows, gaps, vec![], added, "netlist") }; let table: Vec<String> = rows.iter().map(|x| format!(" {:<10} {:<12} {:<9} {}", x["id"].as_str().unwrap_or(""), x["net"].as_str().unwrap_or(""), x["kind"].as_str().unwrap_or(""), match x["status"].as_str().unwrap_or("") { "gap" => format!("GAP: {}", x["why"].as_str().unwrap_or("no test point")), s => format!("{s} {}", x["spot"].as_object().map(|o| format!("{} at ({}, {})", o["pad"].as_str().unwrap_or(""), o["x"], o["y"])).or_else(|| x["spot"].as_str().map(str::to_string)).unwrap_or_default()) })).collect();- r.outcome("testplan", json!({"mode": mode, "tests": rows, "gaps": gaps, "added": added, "notes": notes, "file": tp_abs}));+ r.outcome("testplan", json!({"mode": mode, "fixture": fixture_cfg.to_json(), "tests": rows, "gaps": gaps, "added": added, "notes": notes, "file": tp_abs})); r.save().unwrap();- let head = format!("test plan ({mode}): {} measurements, {} probe-able, {} gap(s){}", rows.len(), rows.iter().filter(|x| x["status"] != "gap").count(), gaps.len(), if added.is_empty() { String::new() } else { format!("; added {}", added.join(", ")) });+ let head = format!("test plan ({mode}, fixture {}): {} measurements, {} probe-able, {} gap(s){}", fixture_cfg.mode, rows.len(), rows.iter().filter(|x| x["status"] != "gap").count(), gaps.len(), if added.is_empty() { String::new() } else { format!("; added {}", added.join(", ")) }); let body = format!("{head}\n{}", table.join("\n")); if !gaps.is_empty() { let tether_hint = "A ground test needs a free MachineContactMedium on that net for the tether's medium pin: add one to the design (a test point or a large contact cannot take it).".to_string();- if testplan::ground_gap(&rows) && testplan::addable(&rows).is_empty() { findings(&body, &[tether_hint]); }- err(&body, &[if mode == "board" { "Each gap needs a spot: move a part off the pad, add a test point on the net (adom/testpoint-pad-0-5mm, schematic first: `step schematic --back --why \"test point for <net>\"`), or widen the copper so a 0.5 mm landing fits. Then `testplan check` again.".into() } else { "Add a test point per gap: `testplan check --netlist <netlist.json> --add` writes TP<n> (0.5 mm round, adom/testpoint-pad-0-5mm) into the netlist.".into() }]);+ if !fixture_cfg.is_bed_of_nails() && testplan::ground_gap(&rows) && testplan::addable(&rows).is_empty() { findings(&body, &[tether_hint]); }+ let fix_hint = if fixture_cfg.is_bed_of_nails() {+ if mode == "board" {+ format!("Bottom bed-of-nails fixture checks require bottom-side test pads >= {:.2} mm, center-to-center pitch >= {:.2} mm, >= {:.2} mm keepout from bottom SMT bodies and THT leads, >= {:.2} mm from board edge, and >= {} unplated tooling holes >= {:.1} mm (or requirements.json testFixture.alignmentFeatures). Fix each gap and run `testplan check` again.", fixture_cfg.min_pad_mm, fixture_cfg.min_pitch_mm, fixture_cfg.keepout_mm, fixture_cfg.edge_mm, fixture_cfg.min_tooling_holes, fixture_cfg.min_tooling_hole_mm)+ } else {+ format!("Add a bottom-side test point per gap: `testplan check --netlist <netlist.json> --add` writes TP<n> ({:.1} mm bottom pad) into the netlist.", fixture_cfg.min_pad_mm)+ }+ } else if mode == "board" {+ "Each gap needs a spot: move a part off the pad, add a test point on the net (adom/testpoint-pad-0-5mm, schematic first: `step schematic --back --why \"test point for <net>\"`), or widen the copper so a 0.5 mm landing fits. Then `testplan check` again.".into()+ } else {+ "Add a test point per gap: `testplan check --netlist <netlist.json> --add` writes TP<n> (0.5 mm round, adom/testpoint-pad-0-5mm) into the netlist.".into()+ };+ err(&body, &[fix_hint]); } let mut hints = vec!["Read the table to the human: what you will measure on the workcell and where the probe lands. Every added test point goes into the library and the schematic like any part.".to_string()]; hints.extend(notes.iter().map(|n| format!("Note: {n}")));
crates/adom-aiflow/src/testplan.rs+464−20@@ -26,8 +26,154 @@ pub const LANDING_R: f64 = 0.25; pub const SHORT_GAP: f64 = 0.3; /// Ground tether reach from a ground contact (mm). pub const REACH: f64 = 50.0;+/// Hard floor for bed-of-nails test-pad diameter (mm).+pub const BED_OF_NAILS_MIN_PAD_FLOOR: f64 = 0.8;+/// Default bed-of-nails test-pad diameter (mm).+pub const BED_OF_NAILS_DEFAULT_PAD: f64 = 1.0;+/// Default minimum center-to-center pitch for bed-of-nails pogo pins (50 mil = 1.27 mm).+pub const BED_OF_NAILS_MIN_PITCH: f64 = 1.27;+/// Default preferred center-to-center pitch for bed-of-nails pogo pins (100 mil = 2.54 mm).+pub const BED_OF_NAILS_PREFERRED_PITCH: f64 = 2.54;+/// Default bottom-side keepout from SMT bodies and through-hole leads (mm).+pub const BED_OF_NAILS_KEEPOUT: f64 = 1.5;+/// Default clearance from the board edge for bed-of-nails test pads (mm).+pub const BED_OF_NAILS_EDGE: f64 = 2.0;+/// Default minimum unplated tooling hole count and diameter (mm).+pub const BED_OF_NAILS_MIN_TOOLING_HOLES: usize = 2;+pub const BED_OF_NAILS_MIN_TOOLING_HOLE_MM: f64 = 2.0; -pub fn needs_spot(kind: &str) -> bool { !matches!(kind, "camera") }+/// Test-fixture strategy captured in requirements.json (`testFixture`) or tests.json (`fixture`).+#[derive(Clone, Debug, PartialEq)]+pub struct TestFixtureConfig {+ pub mode: String,+ pub explicit: bool,+ pub min_pad_mm: f64,+ pub min_pitch_mm: f64,+ pub preferred_pitch_mm: f64,+ pub keepout_mm: f64,+ pub edge_mm: f64,+ pub min_tooling_holes: usize,+ pub min_tooling_hole_mm: f64,+ pub alignment_features: Vec<String>,+}++impl TestFixtureConfig {+ pub fn top_workcell() -> Self {+ Self {+ mode: "top-workcell".into(),+ explicit: false,+ min_pad_mm: LANDING_R * 2.0,+ min_pitch_mm: 1.5,+ preferred_pitch_mm: 3.0,+ keepout_mm: 0.0,+ edge_mm: 0.0,+ min_tooling_holes: 0,+ min_tooling_hole_mm: 0.0,+ alignment_features: Vec::new(),+ }+ }++ pub fn bed_of_nails() -> Self {+ Self {+ mode: "bottom-bed-of-nails".into(),+ explicit: true,+ min_pad_mm: BED_OF_NAILS_DEFAULT_PAD,+ min_pitch_mm: BED_OF_NAILS_MIN_PITCH,+ preferred_pitch_mm: BED_OF_NAILS_PREFERRED_PITCH,+ keepout_mm: BED_OF_NAILS_KEEPOUT,+ edge_mm: BED_OF_NAILS_EDGE,+ min_tooling_holes: BED_OF_NAILS_MIN_TOOLING_HOLES,+ min_tooling_hole_mm: BED_OF_NAILS_MIN_TOOLING_HOLE_MM,+ alignment_features: Vec::new(),+ }+ }++ pub fn is_bed_of_nails(&self) -> bool { self.mode == "bottom-bed-of-nails" }+ pub fn is_manual_bench(&self) -> bool { self.mode == "manual-bench" }++ fn normalize_mode(raw: &str) -> String {+ match raw.trim().to_ascii_lowercase().as_str() {+ "bottom-bed-of-nails" | "bed-of-nails" | "bed_of_nails" | "bottom-pogo" | "pogo" => "bottom-bed-of-nails".into(),+ "manual-bench" | "manual" | "bench" => "manual-bench".into(),+ _ => "top-workcell".into(),+ }+ }++ /// Resolve test-fixture settings from tests.json and requirements.json (`tests.json` overrides).+ pub fn from_sources(tv: &Value, req: &Value) -> Self {+ let req_tf = req.get("testFixture").filter(|v| !v.is_null());+ let tv_tf = tv.get("testFixture").filter(|v| !v.is_null());+ let tv_fix = tv.get("fixture").and_then(Value::as_str);++ let raw_mode = tv_fix+ .or_else(|| tv_tf.and_then(|o| o.as_str().or_else(|| o["mode"].as_str())))+ .or_else(|| req_tf.and_then(|o| o.as_str().or_else(|| o["mode"].as_str())));+ let explicit = raw_mode.is_some();+ let mode = raw_mode.map(Self::normalize_mode).unwrap_or_else(|| "top-workcell".into());++ let mut cfg = if mode == "bottom-bed-of-nails" {+ Self::bed_of_nails()+ } else {+ let mut c = Self::top_workcell();+ c.mode = mode;+ c+ };+ cfg.explicit = explicit;++ for obj in [req_tf, tv_tf].into_iter().flatten() {+ if let Some(v) = obj.get("minPadMm").and_then(Value::as_f64) {+ cfg.min_pad_mm = if cfg.is_bed_of_nails() { v.max(BED_OF_NAILS_MIN_PAD_FLOOR) } else { v.max(0.2) };+ }+ if let Some(v) = obj.get("minPitchMm").and_then(Value::as_f64) { cfg.min_pitch_mm = v.max(0.0); }+ if let Some(v) = obj.get("preferredPitchMm").and_then(Value::as_f64) { cfg.preferred_pitch_mm = v.max(cfg.min_pitch_mm); }+ if let Some(v) = obj.get("keepoutMm").and_then(Value::as_f64) { cfg.keepout_mm = v.max(0.0); }+ if let Some(v) = obj.get("edgeMm").and_then(Value::as_f64) { cfg.edge_mm = v.max(0.0); }+ if let Some(v) = obj.get("minToolingHoles").and_then(Value::as_u64) { cfg.min_tooling_holes = v as usize; }+ if let Some(v) = obj.get("minToolingHoleMm").and_then(Value::as_f64) { cfg.min_tooling_hole_mm = v.max(0.5); }+ if let Some(arr) = obj.get("alignmentFeatures").and_then(Value::as_array) {+ cfg.alignment_features = arr.iter().filter_map(|x| x.as_str().map(str::trim).filter(|s| !s.is_empty()).map(str::to_string)).collect();+ }+ }+ cfg+ }++ pub fn to_json(&self) -> Value {+ json!({+ "mode": self.mode,+ "explicit": self.explicit,+ "minPadMm": self.min_pad_mm,+ "minPitchMm": self.min_pitch_mm,+ "preferredPitchMm": self.preferred_pitch_mm,+ "keepoutMm": self.keepout_mm,+ "edgeMm": self.edge_mm,+ "minToolingHoles": self.min_tooling_holes,+ "minToolingHoleMm": self.min_tooling_hole_mm,+ "alignmentFeatures": self.alignment_features,+ })+ }+}++/// Human-facing intake readback line describing the resolved test-fixture mode.+pub fn intake_fixture_hint(req: &Value) -> String {+ let cfg = TestFixtureConfig::from_sources(&json!({}), req);+ let is_molecule = req["formFactor"]["kind"].as_str().map(|s| s.eq_ignore_ascii_case("molecule")).unwrap_or(false);+ if cfg.explicit {+ if cfg.is_bed_of_nails() {+ format!(+ "Test fixture: bottom-bed-of-nails (from requirements.json testFixture; testplan check will default to bottom-side landings, pad >= {:.2} mm, pitch >= {:.2} mm, keepout >= {:.2} mm from bottom bodies/THT leads, edge >= {:.2} mm, tooling holes >= {} x {:.1} mm).",+ cfg.min_pad_mm, cfg.min_pitch_mm, cfg.keepout_mm, cfg.edge_mm, cfg.min_tooling_holes, cfg.min_tooling_hole_mm+ )+ } else {+ format!("Test fixture: {} (from requirements.json testFixture).", cfg.mode)+ }+ } else if is_molecule {+ "Test fixture: top-workcell (default for Adom molecules; override via requirements.json testFixture.mode if needed).".into()+ } else {+ "Test fixture: top-workcell (default; for a non-molecule board using a bottom-side bed-of-nails pogo fixture or manual bench probing, set requirements.json testFixture.mode to \"bottom-bed-of-nails\" or \"manual-bench\" before schematic capture).".into()+ }+}++pub fn needs_spot(kind: &str) -> bool { !matches!(kind, "camera" | "fixture") } /// A machine contact by its name: Some(true) large, Some(false) medium (or a contact of no stated size). fn contact_class(name: &str) -> Option<bool> {@@ -39,10 +185,17 @@ fn no_tether_contact(net: &str) -> String { format!("no MachineContactMedium on {net}: the ground tether plugs into one, and a test point cannot take it") } -/// The nets `--add` can give a spot to: a `ground` test needs a contact, not a test point.+/// The nets `--add` can give a spot to: a `ground` test needs a contact, not a test point,+/// and `fixture` rows are board-level mechanical checks. pub fn addable(rows: &[Value]) -> Vec<String> {+ addable_for_fixture(rows, &TestFixtureConfig::top_workcell())+}++/// Fixture-aware addable nets: in `bottom-bed-of-nails` mode, `ground` tests can also receive a bottom test point.+pub fn addable_for_fixture(rows: &[Value], cfg: &TestFixtureConfig) -> Vec<String> {+ let bon = cfg.is_bed_of_nails(); let mut out: Vec<String> = Vec::new();- for r in rows.iter().filter(|r| r["status"] == "gap" && r["kind"] != "ground") {+ for r in rows.iter().filter(|r| r["status"] == "gap" && r["kind"] != "fixture" && (bon || r["kind"] != "ground")) { if let Some(n) = r["net"].as_str() { if !out.iter().any(|x| x == n) { out.push(n.to_string()); } } } out@@ -60,6 +213,21 @@ pub fn tests_of(v: &Value) -> Vec<Value> { list } +/// Resolve both tests and fixture config from tests.json and requirements.json.+/// In `bottom-bed-of-nails` mode, every test without an explicit face defaults to `"bottom"`.+pub fn tests_of_with_fixture(v: &Value, req: &Value) -> (Vec<Value>, TestFixtureConfig) {+ let mut list = tests_of(v);+ let cfg = TestFixtureConfig::from_sources(v, req);+ if cfg.is_bed_of_nails() {+ for t in list.iter_mut() {+ if t.get("face").is_none() {+ t["face"] = json!("bottom");+ }+ }+ }+ (list, cfg)+}+ /// The faces a test may be probed from: `face` "top" (the default: the workcell lands from the front), /// "bottom" (the board is probed from below, e.g. bottom-side test points on a crowded top face) or "both". pub fn faces_of(t: &Value) -> Vec<bool> {@@ -78,7 +246,14 @@ pub fn nets_of(netlist: &Value) -> Vec<(String, Vec<String>)> { /// Netlist mode: (rows, gaps, unknown nets). A gap is a measured net with no landing on it: no test point /// and no large machine contact, or for a `ground` test no medium contact.+#[allow(dead_code)] pub fn check_netlist(tests: &[Value], netlist: &Value) -> (Vec<Value>, Vec<String>, Vec<String>) {+ check_netlist_with_fixture(tests, netlist, &TestFixtureConfig::top_workcell())+}++/// Netlist mode with fixture awareness: in `bottom-bed-of-nails` mode, `ground` tests also accept a test point.+pub fn check_netlist_with_fixture(tests: &[Value], netlist: &Value, cfg: &TestFixtureConfig) -> (Vec<Value>, Vec<String>, Vec<String>) {+ let bon = cfg.is_bed_of_nails(); let nets = nets_of(netlist); let comps = netlist["components"].as_array().cloned().unwrap_or_default(); let refs_where = |keep: &dyn Fn(&Value) -> bool| -> Vec<String> { comps.iter().filter(|c| keep(c)).filter_map(|c| c["ref"].as_str().map(str::to_string)).collect() };@@ -94,7 +269,7 @@ pub fn check_netlist(tests: &[Value], netlist: &Value) -> (Vec<Value>, Vec<Strin rows.push(json!({"id": t["id"], "net": net, "kind": kind, "spot": null, "status": "unknown net"})); continue; }; let on = |refs: &[String]| pins.iter().find(|p| refs.iter().any(|r| p.split('.').next() == Some(r.as_str())));- if kind == "ground" {+ if kind == "ground" && !bon { match on(&medium_refs) { Some(pin) => rows.push(json!({"id": t["id"], "net": net, "kind": kind, "spot": pin, "status": "contact"})), None => {@@ -109,7 +284,7 @@ pub fn check_netlist(tests: &[Value], netlist: &Value) -> (Vec<Value>, Vec<Strin let status = if !needs_spot(kind) { "camera" } else if tp.is_some() { "test point" } else if large.is_some() { "contact" } else { "gap" }; if status == "gap" && !gaps.contains(&net.to_string()) { gaps.push(net.to_string()); } let mut row = json!({"id": t["id"], "net": net, "kind": kind, "spot": tp.or(large), "status": status});- if status == "gap" && on(&medium_refs).is_some() { row["why"] = json!("no test point, and a MachineContactMedium is not a landing (its ring is thinner than the 0.5 mm landing)"); }+ if status == "gap" && !bon && on(&medium_refs).is_some() { row["why"] = json!("no test point, and a MachineContactMedium is not a landing (its ring is thinner than the 0.5 mm landing)"); } rows.push(row); } (rows, gaps, unknown)@@ -148,13 +323,35 @@ pub fn write_test_point_files(dir: &std::path::Path) -> Result<std::path::PathBu } /// Add one test point per gap net to the netlist (TP<n>, from the wiki test point page).+#[allow(dead_code)] pub fn add_test_points(netlist: &mut Value, gaps: &[String]) -> Vec<String> {+ add_test_points_for_fixture(netlist, gaps, &TestFixtureConfig::top_workcell())+}++/// Add one test point per gap net sized and placed for the active test fixture.+/// In `bottom-bed-of-nails` mode, creates bottom-side test points sized to `cfg.min_pad_mm` (default 1.0 mm).+pub fn add_test_points_for_fixture(netlist: &mut Value, gaps: &[String], cfg: &TestFixtureConfig) -> Vec<String> { let mut used: Vec<u32> = netlist["components"].as_array().cloned().unwrap_or_default().iter().filter_map(|c| c["ref"].as_str()?.strip_prefix("TP")?.parse().ok()).collect(); let mut added = Vec::new();+ let bon = cfg.is_bed_of_nails(); for net in gaps { let n = (1..).find(|k| !used.contains(k)).unwrap(); used.push(n); let r = format!("TP{n}");- netlist["components"].as_array_mut().map(|a| a.push(json!({"ref": r, "value": TP_VALUE, "fp": "adom:Adom_TestPoint_D0.5mm", "page": TP_PAGE, "mpn": TP_MPN, "block": "test", "why": format!("probe spot for {net} (test plan)")})));+ let comp = if bon {+ let d = cfg.min_pad_mm;+ json!({+ "ref": r,+ "value": format!("TP_{d:.1}mm_Bottom"),+ "fp": format!("TestPoint:TestPoint_Pad_D{d:.1}mm"),+ "side": "bottom",+ "padDiameterMm": d,+ "block": "test",+ "why": format!("bottom bed-of-nails probe spot for {net} (test plan)")+ })+ } else {+ json!({"ref": r, "value": TP_VALUE, "fp": "adom:Adom_TestPoint_D0.5mm", "page": TP_PAGE, "mpn": TP_MPN, "block": "test", "why": format!("probe spot for {net} (test plan)")})+ };+ netlist["components"].as_array_mut().map(|a| a.push(comp)); // written back in the shape the file already uses if let Some(o) = netlist["nets"].as_object_mut() { o.get_mut(net.as_str()).and_then(|p| p.as_array_mut()).map(|p| p.push(json!(format!("{r}.1"))));@@ -216,8 +413,67 @@ pub fn sided_bodies(b: &Board) -> Vec<(String, bool, (f64, f64, f64, f64))> { fn in_box(p: (f64, f64), b: &(f64, f64, f64, f64), grow: f64) -> bool { p.0 > b.0 - grow && p.0 < b.2 + grow && p.1 > b.1 - grow && p.1 < b.3 + grow } +fn pt_seg_dist(p: (f64, f64), a: (f64, f64), b: (f64, f64)) -> f64 {+ let (dx, dy) = (b.0 - a.0, b.1 - a.1);+ let l2 = dx * dx + dy * dy;+ let t = if l2 < 1e-12 { 0.0 } else { ((p.0 - a.0) * dx + (p.1 - a.1) * dy) / l2 }.clamp(0.0, 1.0);+ (p.0 - (a.0 + t * dx)).hypot(p.1 - (a.1 + t * dy))+}++fn dist_to_board_edge(c: (f64, f64), b: &Board) -> f64 {+ if b.outline.len() >= 3 {+ let mut best = f64::MAX;+ for i in 0..b.outline.len() {+ let a = b.outline[i];+ let q = b.outline[(i + 1) % b.outline.len()];+ best = best.min(pt_seg_dist(c, a, q));+ }+ return best;+ }+ let (x0, y0, x1, y1) = b.bbox;+ if (x1 - x0) <= 0.0 || (y1 - y0) <= 0.0 {+ return f64::MAX;+ }+ (c.0 - x0).min(x1 - c.0).min(c.1 - y0).min(y1 - c.1)+}++/// Unplated tooling holes on the board meeting the minimum diameter (mm): `(x, y, diameter, label)`.+pub fn tooling_holes(b: &Board, min_diameter_mm: f64) -> Vec<(f64, f64, f64, String)> {+ let mut out: Vec<(f64, f64, f64, String)> = Vec::new();+ for h in &b.holes {+ if !h.plated {+ let d = h.size.0.min(h.size.1);+ if d >= min_diameter_mm - 1e-6 {+ out.push((h.x, h.y, d, h.reference.clone()));+ }+ }+ }+ for p in &b.pads {+ if p.thru && p.net.is_empty() {+ let d = p.drill.unwrap_or(0.0);+ if d >= min_diameter_mm - 1e-6 && (p.size.0.min(p.size.1) - d).abs() <= 0.15 {+ if !out.iter().any(|(x, y, _, _)| (x - p.x).hypot(y - p.y) < 0.05) {+ out.push((p.x, p.y, d, p.reference.clone()));+ }+ }+ }+ }+ out+}+ /// Board mode: for each measured net, the best landing (x, y, on which pad) or why there is none.+#[allow(dead_code)] pub fn check_board(tests: &[Value], b: &Board) -> (Vec<Value>, Vec<String>, Vec<String>) {+ check_board_with_fixture(tests, b, &TestFixtureConfig::top_workcell())+}++/// Board mode with fixture-specific geometric checks (`top-workcell`, `bottom-bed-of-nails`, `manual-bench`).+pub fn check_board_with_fixture(tests: &[Value], b: &Board, cfg: &TestFixtureConfig) -> (Vec<Value>, Vec<String>, Vec<String>) {+ let bon = cfg.is_bed_of_nails();+ let landing_r = if bon { cfg.min_pad_mm / 2.0 } else { LANDING_R };+ let short_gap = if bon { 0.15 } else { SHORT_GAP };+ let body_grow = if bon { landing_r + cfg.keepout_mm } else { landing_r };+ // a body covers a pad only on its own side (issue #46): front bodies for front probing, back bodies for // a test probed from below (`face`: "bottom") let sided = sided_bodies(b);@@ -229,12 +485,15 @@ pub fn check_board(tests: &[Value], b: &Board) -> (Vec<Value>, Vec<String>, Vec< let grounds: Vec<(f64, f64, String)> = b.footprints.iter().filter(|(_, fp)| contact_class(&fp.lib) == Some(false)) .flat_map(|(r, _)| b.pads_of(r).into_iter().filter(|p| p.net.eq_ignore_ascii_case("GND")).map(move |p| (p.x, p.y, r.clone()))).collect(); let (mut rows, mut gaps, mut warn) = (Vec::new(), Vec::new(), Vec::new());- if grounds.is_empty() { warn.push("no MachineContactMedium on GND: the ground tether has nowhere to plug in (add one near each corner, adom/probing-workcell)".into()); }+ if !bon && !cfg.is_manual_bench() && grounds.is_empty() {+ warn.push("no MachineContactMedium on GND: the ground tether has nowhere to plug in (add one near each corner, adom/probing-workcell)".into());+ }+ let mut selected_spots: Vec<(String, String, f64, f64)> = Vec::new(); for t in tests { let net = t["net"].as_str().unwrap_or(""); let kind = t["kind"].as_str().unwrap_or("dc"); if !needs_spot(kind) { rows.push(json!({"id": t["id"], "net": net, "kind": kind, "status": "camera"})); continue; }- if kind == "ground" {+ if kind == "ground" && !bon { let contact = b.pads.iter().find(|p| p.net == net && medium_refs.contains(&p.reference)); match contact { Some(p) => rows.push(json!({"id": t["id"], "net": net, "kind": kind, "status": "contact", "spot": {"pad": p.key, "x": (p.x * 100.0).round() / 100.0, "y": (p.y * 100.0).round() / 100.0}})),@@ -243,16 +502,27 @@ pub fn check_board(tests: &[Value], b: &Board) -> (Vec<Value>, Vec<String>, Vec< continue; } let mut best: Option<(f64, f64, String, f64, bool)> = None;- let mut why = "no exposed copper on this net".to_string();+ let mut why = if bon { "no exposed bottom-side copper on this net".to_string() } else { "no exposed copper on this net".to_string() }; let faces = faces_of(t); for &front in &faces { let bodies = if front { &front_bodies } else { &back_bodies }; for p in b.pads.iter().filter(|p| p.net == net && if front { p.on_f } else { p.on_b }) {- if medium_refs.contains(&p.reference) { why = format!("{} is a MachineContactMedium: its ring is thinner than the 0.5 mm landing", p.key); continue; }+ if !bon && medium_refs.contains(&p.reference) { why = format!("{} is a MachineContactMedium: its ring is thinner than the 0.5 mm landing", p.key); continue; }+ if bon && !front && p.thru {+ why = format!("{} is a through-hole pin pad: soldered leads poke through the bottom side and deflect bed-of-nails pogo tips", p.key);+ continue;+ } let large = large_refs.contains(&p.reference); // sample landing centres inside the pad, shrunk by the landing radius- let (hx, hy) = (p.size.0 / 2.0 - LANDING_R, p.size.1 / 2.0 - LANDING_R);- if hx < -1e-9 || hy < -1e-9 { why = format!("pads too small for a 0.5 mm landing (e.g. {} {:.2}x{:.2} mm)", p.key, p.size.0, p.size.1); continue; }+ let (hx, hy) = (p.size.0 / 2.0 - landing_r, p.size.1 / 2.0 - landing_r);+ if hx < -1e-9 || hy < -1e-9 {+ why = if bon {+ format!("pads too small for a {:.2} mm bed-of-nails landing (e.g. {} {:.2}x{:.2} mm)", cfg.min_pad_mm, p.key, p.size.0, p.size.1)+ } else {+ format!("pads too small for a 0.5 mm landing (e.g. {} {:.2}x{:.2} mm)", p.key, p.size.0, p.size.1)+ };+ continue;+ } let steps = 5; for i in 0..=steps { for j in 0..=steps { let lx = if steps > 0 { -hx + 2.0 * hx * i as f64 / steps as f64 } else { 0.0 };@@ -262,28 +532,90 @@ pub fn check_board(tests: &[Value], b: &Board) -> (Vec<Value>, Vec<String>, Vec< // a large contact is probed on its ring: clear of the hole and on the copper if large { let from_centre = dx.hypot(dy);- if from_centre - LANDING_R < p.drill.unwrap_or(0.0) / 2.0 - 1e-9 || from_centre + LANDING_R > p.size.0 / 2.0 + 1e-9 { continue; }+ if from_centre - landing_r < p.drill.unwrap_or(0.0) / 2.0 - 1e-9 || from_centre + landing_r > p.size.0 / 2.0 + 1e-9 { continue; } } // and its own fab outline is no body over its own pad- if let Some((r, _)) = bodies.iter().find(|(r, bb)| !(large && *r == p.reference) && in_box(c, bb, LANDING_R)) {- why = format!("every landing on {net} is under a part body (e.g. {} under {r})", p.key); continue;+ if let Some((r, _)) = bodies.iter().find(|(r, bb)| !(large && *r == p.reference) && in_box(c, bb, body_grow)) {+ why = if bon {+ format!("every landing on {net} is within {:.2} mm of bottom part body {r} (bed-of-nails keepout)", cfg.keepout_mm)+ } else {+ format!("every landing on {net} is under a part body (e.g. {} under {r})", p.key)+ };+ continue; }- if b.pads.iter().any(|q| q.net != net && (if front { q.on_f } else { q.on_b }) && (q.x - c.0).hypot(q.y - c.1) < q.half_long + LANDING_R + SHORT_GAP) {- why = format!("every landing on {net} is within {SHORT_GAP} mm of another net's pad (short risk)"); continue;+ if bon && !front {+ if let Some((q, dist)) = b.pads.iter().filter(|q| q.thru && q.reference != p.reference).find_map(|q| {+ let edge_d = (q.x - c.0).hypot(q.y - c.1) - q.half_long - landing_r;+ (edge_d < cfg.keepout_mm - 1e-6).then_some((q, edge_d.max(0.0)))+ }) {+ why = format!("every landing on {net} is {:.2} mm from through-hole lead {} (bed-of-nails keepout >= {:.2} mm)", dist, q.key, cfg.keepout_mm);+ continue;+ }+ let edge_d = dist_to_board_edge(c, b) - landing_r;+ if edge_d < cfg.edge_mm - 1e-6 {+ why = format!("every landing on {net} is {:.2} mm from the board edge (bed-of-nails requires >= {:.2} mm)", edge_d.max(0.0), cfg.edge_mm);+ continue;+ }+ }+ if b.pads.iter().any(|q| q.net != net && (if front { q.on_f } else { q.on_b }) && (q.x - c.0).hypot(q.y - c.1) < q.half_long + landing_r + short_gap) {+ why = format!("every landing on {net} is within {short_gap} mm of another net's pad (short risk)"); continue; } let reach = grounds.iter().map(|g| (g.0 - c.0).hypot(g.1 - c.1)).fold(f64::MAX, f64::min);- if !grounds.is_empty() && reach > REACH { why = format!("{net}'s landings are {reach:.0} mm from the nearest ground contact (tether reach {REACH} mm)"); continue; }+ if !bon && !cfg.is_manual_bench() && !grounds.is_empty() && reach > REACH { why = format!("{net}'s landings are {reach:.0} mm from the nearest ground contact (tether reach {REACH} mm)"); continue; } // prefer test points, then the landing nearest a ground contact- let score = if p.reference.starts_with("TP") { -1000.0 } else { 0.0 } + if reach.is_finite() { reach } else { 0.0 };+ let score = if p.reference.starts_with("TP") { -1000.0 } else { 0.0 } + if !bon && reach.is_finite() { reach } else { 0.0 }; if best.as_ref().map(|b| score < b.3).unwrap_or(true) { best = Some((c.0, c.1, p.key.clone(), score, front)); } } } } } match best {- Some((x, y, pad, _, front)) => rows.push(json!({"id": t["id"], "net": net, "kind": kind, "status": if pad.starts_with("TP") { "test point" } else if large_refs.iter().any(|r| pad.split('.').next() == Some(r.as_str())) { "contact" } else { "exposed pad" }, "face": if front { "top" } else { "bottom" }, "spot": {"pad": pad, "x": (x * 100.0).round() / 100.0, "y": (y * 100.0).round() / 100.0}})),+ Some((x, y, pad, _, front)) => {+ selected_spots.push((net.to_string(), pad.clone(), x, y));+ rows.push(json!({"id": t["id"], "net": net, "kind": kind, "status": if pad.starts_with("TP") { "test point" } else if large_refs.iter().any(|r| pad.split('.').next() == Some(r.as_str())) { "contact" } else { "exposed pad" }, "face": if front { "top" } else { "bottom" }, "spot": {"pad": pad, "x": (x * 100.0).round() / 100.0, "y": (y * 100.0).round() / 100.0}}));+ } None => { if !gaps.contains(&net.to_string()) { gaps.push(net.to_string()); } rows.push(json!({"id": t["id"], "net": net, "kind": kind, "status": "gap", "why": why})); } } }++ // Board-wide bed-of-nails fixture geometry checks: center-to-center pogo pitch and unplated tooling holes+ if bon {+ for i in 0..selected_spots.len() {+ for j in (i + 1)..selected_spots.len() {+ let (n1, p1, x1, y1) = &selected_spots[i];+ let (n2, p2, x2, y2) = &selected_spots[j];+ if p1 == p2 { continue; }+ let d = (x1 - x2).hypot(y1 - y2);+ if d < cfg.min_pitch_mm - 1e-6 {+ let why = format!("test pads {p1} ({n1}) and {p2} ({n2}) are {d:.2} mm center-to-center (bed-of-nails minimum {:.2} mm)", cfg.min_pitch_mm);+ let key = format!("fixture-pitch({p1},{p2})");+ if !gaps.contains(&key) { gaps.push(key); }+ rows.push(json!({"id": "fixture:pitch", "net": format!("{n1}/{n2}"), "kind": "fixture", "status": "gap", "why": why}));+ } else if d < cfg.preferred_pitch_mm - 1e-6 {+ warn.push(format!("test pads {p1} ({n1}) and {p2} ({n2}) are {d:.2} mm apart (below preferred {:.2} mm pogo pitch; 50-mil probes needed)", cfg.preferred_pitch_mm));+ }+ }+ }+ let holes = tooling_holes(b, cfg.min_tooling_hole_mm);+ if holes.len() < cfg.min_tooling_holes && cfg.alignment_features.is_empty() {+ let why = format!(+ "bed-of-nails fixture requires at least {} unplated tooling hole(s) >= {:.1} mm diameter (found {}); add NPTH tooling holes or declare requirements.json testFixture.alignmentFeatures",+ cfg.min_tooling_holes, cfg.min_tooling_hole_mm, holes.len()+ );+ gaps.push("fixture-tooling-holes".into());+ rows.push(json!({"id": "fixture:tooling", "net": "MECHANICAL", "kind": "fixture", "status": "gap", "why": why}));+ } else if holes.len() >= 2 {+ // Advisory: check if all tooling holes are point-symmetric about board center (allows 180-deg board reversal)+ let (x0, y0, x1, y1) = b.bbox;+ let (cx, cy) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0);+ let symmetric = holes.iter().all(|(hx, hy, _, _)| {+ let (mx, my) = (2.0 * cx - hx, 2.0 * cy - hy);+ holes.iter().any(|(ox, oy, _, _)| (ox - mx).hypot(oy - my) < 0.25)+ });+ if symmetric {+ warn.push("unplated tooling holes are 180-degree symmetric about board center; offset one hole asymmetrically to key the PCB orientation on the bed-of-nails fixture".into());+ }+ }+ } (rows, gaps, warn) } @@ -453,4 +785,116 @@ mod tests { // the list shape still reads the same nets assert_eq!(nets_of(&json!({"nets": [["SW", ["U1.2"]]]})), vec![("SW".to_string(), vec!["U1.2".to_string()])]); }++ #[test]+ fn fixture_config_defaults_overrides_and_intake_hint() {+ let req_default = json!({});+ let cfg = TestFixtureConfig::from_sources(&json!([]), &req_default);+ assert_eq!(cfg.mode, "top-workcell");+ assert!(!cfg.explicit);+ assert!(intake_fixture_hint(&req_default).contains("bottom-bed-of-nails"));++ let req_mol = json!({"formFactor": {"kind": "molecule"}});+ assert!(intake_fixture_hint(&req_mol).contains("default for Adom molecules"));++ let req_bon = json!({"testFixture": {"mode": "bottom-bed-of-nails", "minPadMm": 0.5, "minPitchMm": 1.27}});+ let (tests, cfg_bon) = tests_of_with_fixture(&json!([{"id": "v", "net": "VCC", "kind": "dc"}]), &req_bon);+ assert!(cfg_bon.is_bed_of_nails());+ assert!((cfg_bon.min_pad_mm - 0.8).abs() < 1e-6, "hard floor 0.8 mm: {}", cfg_bon.min_pad_mm);+ assert_eq!(tests[0]["face"], "bottom");+ assert!(intake_fixture_hint(&req_bon).contains("bottom-bed-of-nails"));++ // tests.json "fixture": "bed-of-nails" activates bed-of-nails even without requirements.json+ let (tests2, cfg2) = tests_of_with_fixture(&json!({"fixture": "bed-of-nails", "tests": [{"id": "v", "net": "VCC", "kind": "dc"}]}), &json!({}));+ assert!(cfg2.is_bed_of_nails());+ assert_eq!(tests2[0]["face"], "bottom");+ }++ #[test]+ fn bed_of_nails_add_test_points_writes_bottom_1mm_pads() {+ let mut nl = json!({"components": [{"ref": "U1"}], "nets": {"VIN": ["U1.1"]}});+ let cfg = TestFixtureConfig::bed_of_nails();+ let added = add_test_points_for_fixture(&mut nl, &["VIN".to_string()], &cfg);+ assert_eq!(added, vec!["TP1 on VIN"]);+ let tp = &nl["components"][1];+ assert_eq!(tp["side"], "bottom");+ assert_eq!(tp["padDiameterMm"], json!(1.0));+ assert_eq!(tp["value"], "TP_1.0mm_Bottom");+ }++ #[test]+ fn bed_of_nails_board_catches_all_geometry_failures_and_passes_fixed() {+ let bon_tests = |req: &Value| tests_of_with_fixture(+ &json!([{"id": "v1", "net": "V1", "kind": "dc"}, {"id": "v2", "net": "V2", "kind": "dc"}]),+ req,+ );+ let req = json!({"testFixture": {"mode": "bottom-bed-of-nails"}});+ let (tests, cfg) = bon_tests(&req);++ // 1. Small 0.5 mm bottom pad + missing tooling holes -> fails both+ let b_small = Board::from_text("small.kicad_pcb", r#"(kicad_pcb (version 20240108)+ (layers (0 "F.Cu" signal) (31 "B.Cu" signal)) (net 1 "V1") (net 2 "V2")+ (gr_rect (start 0 0) (end 40 30) (layer "Edge.Cuts"))+ (footprint "TestPoint:TP" (layer "B.Cu") (at 10 10) (property "Reference" "TP1")+ (pad "1" smd circle (at 0 0) (size 0.5 0.5) (layers "B.Cu") (net 1 "V1")))+ (footprint "TestPoint:TP" (layer "B.Cu") (at 20 10) (property "Reference" "TP2")+ (pad "1" smd circle (at 0 0) (size 1.0 1.0) (layers "B.Cu") (net 2 "V2"))))"#.into()).unwrap();+ let (rows, gaps, _) = check_board_with_fixture(&tests, &b_small, &cfg);+ assert!(gaps.contains(&"V1".to_string()), "{rows:?}");+ assert!(gaps.contains(&"fixture-tooling-holes".to_string()), "{gaps:?}");++ // 2. Pitch 1.20 mm (< 1.27 mm, passes copper clearance) -> caught as fixture-pitch+ let b_geom = Board::from_text("geom.kicad_pcb", r#"(kicad_pcb (version 20240108)+ (layers (0 "F.Cu" signal) (31 "B.Cu" signal)) (net 1 "V1") (net 2 "V2") (net 3 "GND")+ (gr_rect (start 0 0) (end 40 30) (layer "Edge.Cuts"))+ (footprint "MountingHole:MH" (layer "F.Cu") (at 4 4) (property "Reference" "H1")+ (pad "" np_thru_hole circle (at 0 0) (size 2.5 2.5) (drill 2.5) (layers "*.Mask")))+ (footprint "MountingHole:MH" (layer "F.Cu") (at 36 22) (property "Reference" "H2")+ (pad "" np_thru_hole circle (at 0 0) (size 2.5 2.5) (drill 2.5) (layers "*.Mask")))+ (footprint "TestPoint:TP" (layer "B.Cu") (at 15 15) (property "Reference" "TP1")+ (pad "1" smd circle (at 0 0) (size 1.0 1.0) (layers "B.Cu") (net 1 "V1")))+ (footprint "TestPoint:TP" (layer "B.Cu") (at 16.2 15) (property "Reference" "TP2")+ (pad "1" smd circle (at 0 0) (size 1.0 1.0) (layers "B.Cu") (net 2 "V2"))))"#.into()).unwrap();+ let (rows_p, gaps_p, _) = check_board_with_fixture(&tests, &b_geom, &cfg);+ assert!(gaps_p.iter().any(|g| g.starts_with("fixture-pitch")), "{rows_p:?} {gaps_p:?}");++ // 3. THT lead within 1.5 mm of V1 pad + V2 pad within 2.0 mm of board edge -> both caught+ let b_keepout = Board::from_text("keepout.kicad_pcb", r#"(kicad_pcb (version 20240108)+ (layers (0 "F.Cu" signal) (31 "B.Cu" signal)) (net 1 "V1") (net 2 "V2") (net 3 "GND")+ (gr_rect (start 0 0) (end 40 30) (layer "Edge.Cuts"))+ (footprint "MountingHole:MH" (layer "F.Cu") (at 4 4) (property "Reference" "H1")+ (pad "" np_thru_hole circle (at 0 0) (size 2.5 2.5) (drill 2.5) (layers "*.Mask")))+ (footprint "MountingHole:MH" (layer "F.Cu") (at 36 22) (property "Reference" "H2")+ (pad "" np_thru_hole circle (at 0 0) (size 2.5 2.5) (drill 2.5) (layers "*.Mask")))+ (footprint "Connector:PinHeader" (layer "F.Cu") (at 12 15) (property "Reference" "J1")+ (pad "1" thru_hole circle (at 0 0) (size 1.7 1.7) (drill 1.0) (layers "*.Cu" "*.Mask") (net 3 "GND")))+ (footprint "TestPoint:TP" (layer "B.Cu") (at 14.0 15) (property "Reference" "TP1")+ (pad "1" smd circle (at 0 0) (size 1.0 1.0) (layers "B.Cu") (net 1 "V1")))+ (footprint "TestPoint:TP" (layer "B.Cu") (at 1.5 15) (property "Reference" "TP2")+ (pad "1" smd circle (at 0 0) (size 1.0 1.0) (layers "B.Cu") (net 2 "V2"))))"#.into()).unwrap();+ let (rows_k, gaps_k, _) = check_board_with_fixture(&tests, &b_keepout, &cfg);+ assert_eq!(gaps_k, vec!["V1".to_string(), "V2".to_string()], "{rows_k:?}");+ assert!(rows_k[0]["why"].as_str().unwrap().contains("through-hole lead"), "{rows_k:?}");+ assert!(rows_k[1]["why"].as_str().unwrap().contains("board edge"), "{rows_k:?}");++ // 4. Fixed board: 1.0 mm bottom pads at 3.0 mm pitch, >= 2.0 mm from edge, clear of THT, 2 asymmetric NPTH 2.5 mm holes -> PASS+ let b_ok = Board::from_text("ok.kicad_pcb", r#"(kicad_pcb (version 20240108)+ (layers (0 "F.Cu" signal) (31 "B.Cu" signal)) (net 1 "V1") (net 2 "V2") (net 3 "GND")+ (gr_rect (start 0 0) (end 40 30) (layer "Edge.Cuts"))+ (footprint "MountingHole:MH" (layer "F.Cu") (at 4 4) (property "Reference" "H1")+ (pad "" np_thru_hole circle (at 0 0) (size 2.5 2.5) (drill 2.5) (layers "*.Mask")))+ (footprint "MountingHole:MH" (layer "F.Cu") (at 36 22) (property "Reference" "H2")+ (pad "" np_thru_hole circle (at 0 0) (size 2.5 2.5) (drill 2.5) (layers "*.Mask")))+ (footprint "Connector:PinHeader" (layer "F.Cu") (at 8 15) (property "Reference" "J1")+ (pad "1" thru_hole circle (at 0 0) (size 1.7 1.7) (drill 1.0) (layers "*.Cu" "*.Mask") (net 3 "GND")))+ (footprint "TestPoint:TP" (layer "B.Cu") (at 18 15) (property "Reference" "TP1")+ (pad "1" smd circle (at 0 0) (size 1.0 1.0) (layers "B.Cu") (net 1 "V1")))+ (footprint "TestPoint:TP" (layer "B.Cu") (at 21 15) (property "Reference" "TP2")+ (pad "1" smd circle (at 0 0) (size 1.0 1.0) (layers "B.Cu") (net 2 "V2"))))"#.into()).unwrap();+ let (rows_ok, gaps_ok, warn_ok) = check_board_with_fixture(&tests, &b_ok, &cfg);+ assert!(gaps_ok.is_empty(), "{rows_ok:?} {gaps_ok:?}");+ assert!(warn_ok.is_empty(), "{warn_ok:?}");+ assert_eq!(rows_ok[0]["face"], "bottom");+ assert_eq!(rows_ok[1]["face"], "bottom");+ } }
skills/aiflow-intake/SKILL.md+2@@ -87,6 +87,7 @@ One file beside the design. Minimum shape: "outputs": [{"name": "VOUT", "V": 5.0, "tol_pct": 3, "I_A": 1.0}], "interfaces": {"power": ["VIN", "GND", "VOUT"], "control": ["EN"], "monitor": ["VMON"], "probe": ["SW", "FB", "VOUT", "GND"]}, "formFactor": {"kind": "molecule", "pin": "MachinePinMediumShort", "grid_mm": 2},+ "testFixture": {"mode": "top-workcell"}, "fab": {"target": "fab", "layers": 2, "thickness_mm": 1.6, "design_copper_oz": 0.5}, "sourcing": {"profile": "fab"}, "deliverables": ["calcs", "ngspice loop + transient", "vendor-model check", "schematic", "board", "3D models", "molecule publish", "scaffold + probe plan", "video", "clips page"],@@ -96,6 +97,7 @@ One file beside the design. Minimum shape: ``` - **inputs / outputs**: every rail with nominal, range and current. A design range wider than the brief is fine; say why.+- **testFixture**: optional `{"mode": "top-workcell" | "bottom-bed-of-nails" | "manual-bench"}`. Defaults to `"top-workcell"` for Adom molecules; for non-molecule boards destined for a bottom-side bed-of-nails pogo fixture, set `"mode": "bottom-bed-of-nails"` (optional overrides: `minPadMm`, `minPitchMm`, `preferredPitchMm`, `keepoutMm`, `edgeMm`, `minToolingHoles`, `minToolingHoleMm`, `alignmentFeatures`). `intake` reads back the active mode or default so fixture access is settled before schematic capture. - **fab.target**: `fab` (default) or `jlcpcb`. It picks `sourcing.profile` and the DRC rules profile (aiflow-molecule). - **deliverables**: everything the human asked for, including the steps after `finish` (molecule publish, scaffold placement, probe plan, vendor simulation). A deliverable not listed here gets forgotten.
skills/aiflow-test-plan/SKILL.md+10@@ -71,3 +71,13 @@ moving a part, adding a test point (back to the schematic), or widening copper. - At least 1.5 mm centre to centre from every other test pad, so a probe lands on one pad only; DRC passing is not enough (two pads 0.86 mm apart pass DRC and still share a probe). - Out of the machine-contact columns and corner-pin zones: the contacts keep their grid positions and their silkscreen tags; the test pads move. - A net on a `MachineContactLarge` needs no test pad: its ring is about 1 mm wide, clear of the bore, so the landing fits. A net only on a `MachineContactMedium` or a corner pin keeps its test pad for now: a medium contact's ring is about 0.3 mm wide around the bore, thinner than the 0.5 mm landing, and the human crosshair check for pads that small is not built.++## Bottom bed-of-nails fixture mode++When `requirements.json` sets `"testFixture": {"mode": "bottom-bed-of-nails"}` (or `tests.json` sets `"fixture": "bed-of-nails"`), `testplan check` enforces bottom-side bed-of-nails DFT rules:++- **Default probe face**: every test without an explicit `face` defaults to `"bottom"`; `testplan check --add` inserts bottom-side test points sized to `minPadMm` (default `1.0 mm`).+- **Minimum pad diameter**: `1.0 mm` default (configurable via `minPadMm`, hard floor `0.8 mm`). Through-hole pin pads are rejected as bed-of-nails pogo landings because soldered leads poke through and deflect pogo tips.+- **Center-to-center pogo pitch**: at least `1.27 mm` (50 mil) between every pair of selected test landings; distances under `preferredPitchMm` (`2.54 mm` / 100 mil) raise an advisory note.+- **Bottom-side keepouts and board edge**: at least `1.5 mm` pad-edge clearance (`keepoutMm`) from bottom-side SMT part bodies and through-hole pin pads/leads, and at least `2.0 mm` (`edgeMm`) from the board outline.+- **Tooling holes**: at least 2 unplated NPTH tooling holes with diameter `>= 2.0 mm` (`minToolingHoles`, `minToolingHoleMm`), unless `alignmentFeatures` is explicitly declared in `testFixture`. Symmetric tooling-hole pairs raise a non-blocking keying note.
tests/test-fixture-dft-workflow.pyadded+169@@ -0,0 +1,169 @@+"""Test-fixture strategy at intake and bottom bed-of-nails DFT rules end to end (issue #218):+1. intake reads back testFixture.mode (and states the default/override for non-molecule boards)+2. testplan check --netlist --add in bottom-bed-of-nails mode adds bottom 1.0 mm test points+3. Negative board tests: top-only pad, 0.5 mm pad, 1.0 mm pitch (< 1.27 mm), THT lead clash (< 1.5 mm),+ edge clearance (< 2.0 mm), and missing unplated tooling holes all fail testplan check+4. Fixed bottom-side board (1.0 mm pads, >= 2.54 mm pitch, >= 1.5 mm from THT/bottom body, >= 2.0 mm from edge,+ 2 asymmetric 2.5 mm NPTH tooling holes) passes testplan check with 0 gaps and 0 notes+5. tests.json "fixture": "bed-of-nails" + alignmentFeatures override works without requirements.json+Usage: python3 tests/test-fixture-dft-workflow.py <adom-aiflow binary>"""+import json, os, pathlib, subprocess, sys, tempfile++binary = str(pathlib.Path(sys.argv[1]).resolve())+++def make_board(path, extra_fps=""):+ path.write_text(+ '(kicad_pcb (version 20241229) (generator "test") (general (thickness 1.6)) '+ '(layers (0 "F.Cu" signal) (31 "B.Cu" signal) (25 "Edge.Cuts" user)) '+ '(net 0 "") (net 1 "VIN") (net 2 "VOUT") (net 3 "GND") '+ f'{extra_fps} '+ '(gr_rect (start 0 0) (end 50 35) (layer "Edge.Cuts") (stroke (width 0.1) (type solid))))'+ )+++HOLE_PAIR = (+ '(footprint "MountingHole:MH_2.5mm" (layer "F.Cu") (at 4 4) (property "Reference" "H1") '+ '(pad "" np_thru_hole circle (at 0 0) (size 2.5 2.5) (drill 2.5) (layers "*.Mask"))) '+ '(footprint "MountingHole:MH_2.5mm" (layer "F.Cu") (at 45 28) (property "Reference" "H2") '+ '(pad "" np_thru_hole circle (at 0 0) (size 2.5 2.5) (drill 2.5) (layers "*.Mask"))) '+)++THT_HDR = (+ '(footprint "Connector_PinHeader:PinHeader_1x01" (layer "F.Cu") (at 10 18) (property "Reference" "J1") '+ '(pad "1" thru_hole circle (at 0 0) (size 1.7 1.7) (drill 1.0) (layers "*.Cu" "*.Mask") (net 3 "GND"))) '+)++BOTTOM_IC = (+ '(footprint "Package_SO:SOIC-8" (layer "B.Cu") (at 38 18) (property "Reference" "U2") '+ '(fp_rect (start -2 -2) (end 2 2) (layer "B.Fab")) '+ '(pad "1" smd rect (at -1 0) (size 0.6 0.6) (layers "B.Cu") (net 3 "GND"))) '+)+++def tp(ref, x, y, net_id, net_name, size=1.0, side="B.Cu"):+ return (+ f'(footprint "TestPoint:TP" (layer "{side}") (at {x} {y}) (property "Reference" "{ref}") '+ f'(pad "1" smd circle (at 0 0) (size {size} {size}) (layers "{side}") (net {net_id} "{net_name}"))) '+ )+++with tempfile.TemporaryDirectory(prefix='aiflow-dft-') as td:+ p = pathlib.Path(td)+ env = dict(os.environ, AIFLOW_DASHBOARD='off', XDG_CONFIG_HOME=str(p / 'xdg'))++ def call(run, *args):+ return subprocess.run(+ [binary, '--run', str(run), '--ai-thread', 'dft-test', *args],+ env=env, capture_output=True, text=True, timeout=120+ )++ # 1. intake readback: explicit bottom-bed-of-nails vs omitted non-molecule default+ req_bon = p / 'req-bon.json'+ req_bon.write_text(json.dumps({+ "fab": {"target": "jlcpcb"},+ "formFactor": {"kind": "custom"},+ "testFixture": {"mode": "bottom-bed-of-nails"},+ }))+ req_def = p / 'req-default.json'+ req_def.write_text(json.dumps({"fab": {"target": "jlcpcb"}, "formFactor": {"kind": "custom"}}))++ run_def = p / 'run-def'+ rd = call(run_def, 'intake', '--prompt-time', '2026-11-19T00:00:00Z', '--requirements', str(req_def))+ assert rd.returncode == 0 and 'Test fixture: top-workcell' in rd.stdout and 'bottom-bed-of-nails' in rd.stdout, rd.stdout + rd.stderr++ run1 = p / 'run-bon'+ ri = call(run1, 'intake', '--prompt-time', '2026-11-19T00:00:00Z', '--requirements', str(req_bon))+ assert ri.returncode == 0 and 'Test fixture: bottom-bed-of-nails' in ri.stdout, ri.stdout + ri.stderr+ print(' [1/5] intake reads back bottom-bed-of-nails and states default/override for non-molecule boards')++ # 2. Netlist mode --add creates bottom-side 1.0 mm test points (including GND)+ tests_f = p / 'tests.json'+ tests_f.write_text(json.dumps([+ {"id": "vin", "what": "input rail", "net": "VIN", "why": "supply", "kind": "dc"},+ {"id": "vout", "what": "output rail", "net": "VOUT", "why": "reg", "kind": "dc"},+ {"id": "gnd", "what": "ground ref", "net": "GND", "why": "ref", "kind": "ground"},+ ]))+ nl_f = p / 'netlist.json'+ nl_f.write_text(json.dumps({+ "components": [{"ref": "U1", "value": "REG"}],+ "nets": {"VIN": ["U1.1"], "VOUT": ["U1.2"], "GND": ["U1.3"]},+ }))+ rn = call(run1, 'testplan', 'check', '--tests', str(tests_f), '--netlist', str(nl_f), '--add')+ assert rn.returncode == 0 and 'fixture bottom-bed-of-nails' in rn.stdout, rn.stdout + rn.stderr+ nl_after = json.loads(nl_f.read_text())+ tps = [c for c in nl_after['components'] if c['ref'].startswith('TP')]+ assert len(tps) == 3 and all(c.get('side') == 'bottom' and c.get('padDiameterMm') == 1.0 for c in tps), tps+ print(' [2/5] testplan check --add created 3 bottom-side 1.0 mm test points (VIN, VOUT, GND)')++ # 3. Negative board tests on synthetic KiCad boards+ spec_f = p / 'spec.json'+ spec_f.write_text(json.dumps({"clearance": 0.15, "minTrackWidth": 0.127, "track": 0.25}))++ def check_board_case(name, extra_fps, req_path=req_bon, t_path=tests_f):+ b = p / f'{name}.kicad_pcb'+ make_board(b, extra_fps)+ run = p / f'run-{name}'+ if req_path is not None:+ assert call(run, 'intake', '--prompt-time', '2026-11-19T00:00:00Z', '--requirements', str(req_path)).returncode == 0+ assert call(run, 'start', '--board', str(b), '--spec', str(spec_f), '--engine', 'test', '--prompt-time', '2026-11-19T00:00:00Z').returncode == 0+ return call(run, 'testplan', 'check', '--tests', str(t_path)), json.loads((run / 'run.json').read_text())['outcomes']['testplan']++ # 3a. Top-only test pads fail bottom-bed-of-nails+ r_top, o_top = check_board_case('top-only', HOLE_PAIR + tp('TP1', 20, 15, 1, 'VIN', 1.0, 'F.Cu') + tp('TP2', 25, 15, 2, 'VOUT', 1.0, 'F.Cu') + tp('TP3', 30, 15, 3, 'GND', 1.0, 'F.Cu'))+ assert r_top.returncode != 0 and set(o_top['gaps']) >= {'VIN', 'VOUT', 'GND'}, o_top++ # 3b. 0.5 mm bottom pad + missing tooling holes fail+ r_sm, o_sm = check_board_case('small-no-holes', tp('TP1', 20, 15, 1, 'VIN', 0.5) + tp('TP2', 25, 15, 2, 'VOUT', 1.0) + tp('TP3', 30, 15, 3, 'GND', 1.0))+ assert r_sm.returncode != 0 and 'VIN' in o_sm['gaps'] and 'fixture-tooling-holes' in o_sm['gaps'], o_sm++ # 3c. Pitch 1.20 mm (< 1.27 mm, passes copper clearance) fails fixture-pitch+ r_pt, o_pt = check_board_case('bad-pitch', HOLE_PAIR + tp('TP1', 20.0, 15, 1, 'VIN', 1.0) + tp('TP2', 21.2, 15, 2, 'VOUT', 1.0) + tp('TP3', 30.0, 15, 3, 'GND', 1.0))+ assert r_pt.returncode != 0 and any(g.startswith('fixture-pitch') for g in o_pt['gaps']), o_pt++ # 3d. THT lead keepout (< 1.5 mm) + bottom SMT body keepout (< 1.5 mm) + edge (< 2.0 mm) all fail+ r_ko, o_ko = check_board_case(+ 'keepouts',+ HOLE_PAIR + THT_HDR + BOTTOM_IC+ + tp('TP1', 12.0, 18, 1, 'VIN', 1.0) # within 1.5 mm of J1 THT lead at (10, 18)+ + tp('TP2', 35.0, 18, 2, 'VOUT', 1.0) # within 1.5 mm of U2 B.Fab body [36..40, 16..20]+ + tp('TP3', 1.5, 10, 3, 'GND', 1.0), # edge clearance 1.0 mm < 2.0 mm+ )+ assert r_ko.returncode != 0 and set(o_ko['gaps']) == {'VIN', 'VOUT', 'GND'}, o_ko+ whys = {row['net']: row['why'] for row in o_ko['tests']}+ assert 'through-hole lead' in whys['VIN'] and 'bottom part body' in whys['VOUT'] and 'board edge' in whys['GND'], whys+ print(' [3/5] negative board checks caught top-only, 0.5 mm pad, 1.0 mm pitch, THT lead, bottom body, edge, and missing tooling holes')++ # 4. Fixed board passes cleanly with 0 gaps and 0 warnings+ r_ok, o_ok = check_board_case(+ 'fixed',+ HOLE_PAIR + THT_HDR + BOTTOM_IC+ + tp('TP1', 18.0, 18, 1, 'VIN', 1.0)+ + tp('TP2', 22.0, 18, 2, 'VOUT', 1.0)+ + tp('TP3', 26.0, 18, 3, 'GND', 1.0),+ )+ assert r_ok.returncode == 0 and r_ok.stdout.startswith('OK:'), r_ok.stdout + r_ok.stderr+ assert o_ok['gaps'] == [] and o_ok['notes'] == [], o_ok+ assert all(row['face'] == 'bottom' for row in o_ok['tests']), o_ok['tests']+ print(' [4/5] fixed bottom-side board passed with 0 gaps and 0 notes')++ # 5. tests.json "fixture": "bed-of-nails" + alignmentFeatures works without requirements.json+ tests_inline = p / 'tests-inline.json'+ tests_inline.write_text(json.dumps({+ "fixture": "bed-of-nails",+ "testFixture": {"alignmentFeatures": ["board edge notch + fiducials"]},+ "tests": [+ {"id": "vin", "what": "input rail", "net": "VIN", "kind": "dc"},+ {"id": "vout", "what": "output rail", "net": "VOUT", "kind": "dc"},+ ],+ }))+ r_in, o_in = check_board_case(+ 'inline-align',+ tp('TP1', 18.0, 18, 1, 'VIN', 1.0) + tp('TP2', 22.0, 18, 2, 'VOUT', 1.0),+ req_path=None,+ t_path=tests_inline,+ )+ assert r_in.returncode == 0 and o_in['gaps'] == [] and o_in['fixture']['mode'] == 'bottom-bed-of-nails', o_in+ print(' [5/5] tests.json fixture="bed-of-nails" with alignmentFeatures passes without requirements.json')++print('PASS: test-fixture intake readback and bottom bed-of-nails DFT rules verified.')