← Commit history
Merge PR #559: Housecleaning: thirteen small fixes from three board runs (fix/housecleaning-round-2 -> main) merge
Showing changes introduced by the merge (against its first parent).
9 files changed
+396−23
crates/adom-aiflow/src/export.rs+43−7crates/adom-aiflow/src/main.rs+129−10crates/adom-aiflow/src/preboard.rs+11−4crates/adom-aiflow/src/sequence.rs+11crates/adom-aiflow/src/silkproof.rs+8crates/aiflow-analyze/src/lib.rs+17−1crates/aiflow-place/src/lib.rs+27skills/aiflow-silkscreen/SKILL.md+1−1tests/housecleaning-workflow.py+149crates/adom-aiflow/src/export.rs+43−7@@ -17,6 +17,8 @@ pub struct Part { pub footprint: String, pub mpn: String, pub manufacturer: String,+ /// AF54: the distributor part numbers the footprint carries (Mouser, DigiKey, LCSC), in that order; empty when not given+ pub distributors: [String; 3], pub bottom: bool, pub rot: f64, pub dnp: bool,@@ -58,6 +60,13 @@ mod prop_tests { } } +/// AF54: the footprint fields that carry a distributor's own part number, per distributor (any spelling).+const MOUSER_FIELDS: &[&str] = &["Mouser", "Mouser Part Number", "Mouser_PN", "Mouser PN", "Mouser No"];+const DIGIKEY_FIELDS: &[&str] = &["DigiKey", "Digi-Key", "DigiKey Part Number", "Digi-Key Part Number", "DigiKey_PN", "Digi-Key_PN", "DigiKey PN"];+const LCSC_FIELDS: &[&str] = &["LCSC", "LCSC Part #", "LCSC Part Number", "LCSC_PN", "LCSC PN"];+/// The distributor columns the review BOM adds when any part carries one of them.+pub const DISTRIBUTOR_COLUMNS: [&str; 3] = ["Mouser", "DigiKey", "LCSC"];+ /// A footprint flag in either spelling: an atom of `(attr ...)` or its own `(flag yes)` node. fn flag(fp: &sx::Node, name: &str) -> bool { let in_attr = fp.find("attr").map(|a| a.items.iter().any(|it| matches!(it, sx::Item::Atom { text, .. } if text == name))).unwrap_or(false);@@ -85,6 +94,7 @@ pub fn inventory(b: &Board) -> Inventory { footprint: fp.value().unwrap_or("").to_string(), mpn: prop(fp, &["MPN", "Manufacturer_Part_Number", "Manufacturer Part Number", "MFR_PN", "PartNumber", "Part Number"]), manufacturer: prop(fp, &["Manufacturer", "MFR", "Manufacturer_Name"]),+ distributors: [prop(fp, MOUSER_FIELDS), prop(fp, DIGIKEY_FIELDS), prop(fp, LCSC_FIELDS)], bottom: fp.find("layer").and_then(|l| l.value()) == Some("B.Cu"), rot: at.and_then(|a| a.number(3)).unwrap_or(0.0), dnp: flag(fp, "dnp"),@@ -156,21 +166,29 @@ pub const OFF_BOARD_DNP: &str = "off-board (not assembled)"; /// write_bom, plus one do-not-place line per off-board part after the board's own lines. pub fn write_bom_with(inv: &Inventory, off: &[OffBoard]) -> String {- let mut groups: BTreeMap<(String, String, String, String, bool), Vec<String>> = BTreeMap::new();+ // AF54: the distributor part numbers the footprints carry go into the review BOM (columns only when any part has one)+ let dist = inv.parts.values().any(|p| p.in_bom && p.distributors.iter().any(|d| !d.is_empty()));+ let mut groups: BTreeMap<(String, String, String, String, bool, [String; 3]), Vec<String>> = BTreeMap::new(); for (r, p) in inv.parts.iter().filter(|(_, p)| p.in_bom) {- groups.entry((p.value.clone(), p.footprint.clone(), p.manufacturer.clone(), p.mpn.clone(), p.dnp)).or_default().push(r.clone());+ groups.entry((p.value.clone(), p.footprint.clone(), p.manufacturer.clone(), p.mpn.clone(), p.dnp, p.distributors.clone())).or_default().push(r.clone()); }- let mut lines: Vec<(Vec<String>, String)> = groups.into_iter().map(|((v, fp, m, mpn, dnp), mut refs)| {+ let mut lines: Vec<(Vec<String>, String)> = groups.into_iter().map(|((v, fp, m, mpn, dnp, d), mut refs)| { refs.sort_by_key(|a| natural(a));- let line = [refs.join(" "), refs.len().to_string(), v, fp, m, mpn, if dnp { "DNP".into() } else { String::new() }].iter().map(|s| csv_field(s)).collect::<Vec<_>>().join(",");+ let mut cells = vec![refs.join(" "), refs.len().to_string(), v, fp, m, mpn, if dnp { "DNP".into() } else { String::new() }];+ if dist { cells.extend(d); }+ let line = cells.iter().map(|s| csv_field(s)).collect::<Vec<_>>().join(","); (refs, line) }).collect(); lines.sort_by_key(|(refs, _)| natural(&refs[0]));- let mut out = String::from("Reference,Qty,Value,Footprint,Manufacturer,MPN,DNP\n");+ let mut out = String::from("Reference,Qty,Value,Footprint,Manufacturer,MPN,DNP");+ if dist { for c in DISTRIBUTOR_COLUMNS { out.push(','); out.push_str(c); } }+ out.push('\n'); for (_, l) in lines { out.push_str(&l); out.push('\n'); } for o in off.iter().filter(|o| !inv.parts.contains_key(&o.reference)) { let fp = if o.connects_to.is_empty() { "off-board".to_string() } else { format!("off-board, plugs into {}", o.connects_to) };- let line = [o.reference.clone(), o.qty.to_string(), o.value.clone(), fp, o.manufacturer.clone(), o.mpn.clone(), OFF_BOARD_DNP.to_string()].iter().map(|s| csv_field(s)).collect::<Vec<_>>().join(",");+ let mut cells = vec![o.reference.clone(), o.qty.to_string(), o.value.clone(), fp, o.manufacturer.clone(), o.mpn.clone(), OFF_BOARD_DNP.to_string()];+ if dist { cells.extend([String::new(), String::new(), String::new()]); }+ let line = cells.iter().map(|s| csv_field(s)).collect::<Vec<_>>().join(","); out.push_str(&line); out.push('\n'); } out@@ -511,7 +529,7 @@ pub fn export_with(board_path: &str, out: &Path, cli: &str, off: &[OffBoard]) -> let report = json!({ "pass": problems.is_empty(), "dir": out.display().to_string(), "board": board_path, "boardSha256": crate::sha256_file(board_path), "kicadCli": cli,- "gerbers": g, "drill": d, "cpl": c, "bom": b, "fillsSaved": saved_fill, "fillsGerbers": gerber_fill, "fillsCurrent": fills_current, "bomSource": if off.is_empty() { "the board's footprints (Value, footprint, MPN and Manufacturer properties, DNP and exclude-from-BOM attributes)".to_string() } else { format!("the board's footprints (Value, footprint, MPN and Manufacturer properties, DNP and exclude-from-BOM attributes), plus {} off-board part(s) from the spec as do-not-place lines", off.len()) },+ "gerbers": g, "drill": d, "cpl": c, "bom": b, "fillsSaved": saved_fill, "fillsGerbers": gerber_fill, "fillsCurrent": fills_current, "bomSource": if off.is_empty() { "the board's footprints (Value, footprint, MPN and Manufacturer properties, Mouser, DigiKey and LCSC numbers when given, DNP and exclude-from-BOM attributes)".to_string() } else { format!("the board's footprints (Value, footprint, MPN and Manufacturer properties, Mouser, DigiKey and LCSC numbers when given, DNP and exclude-from-BOM attributes), plus {} off-board part(s) from the spec as do-not-place lines", off.len()) }, "files": files, "notes": notes, "problems": problems, }); if problems.is_empty() { Ok(report) } else { Err((report, problems)) }@@ -620,6 +638,24 @@ mod tests { assert!(p.contains("marks MP1 fitted"), "{p}"); } + /// AF54: a footprint's distributor numbers reach the review BOM, so a cart needs no second lookup+ #[test]+ fn distributor_numbers_are_carried_into_the_review_bom() {+ let with = BOARD.replace(r#"(property "MPN" "RC0603FR-0710KL") (attr smd)+ (pad "1" smd rect (at -0.8 0) (size 0.8 0.9) (layers "F.Cu" "F.Paste" "F.Mask")))"#, r#"(property "MPN" "RC0603FR-0710KL") (property "Mouser" "603-RC0603FR-0710KL") (property "LCSC Part #" "C98220") (attr smd)+ (pad "1" smd rect (at -0.8 0) (size 0.8 0.9) (layers "F.Cu" "F.Paste" "F.Mask")))"#);+ assert_ne!(with, BOARD);+ let i = inventory(&Board::from_text("t.kicad_pcb", with).unwrap());+ assert_eq!(i.parts["R1"].distributors, ["603-RC0603FR-0710KL".to_string(), String::new(), "C98220".to_string()]);+ let text = write_bom(&i);+ assert!(text.starts_with("Reference,Qty,Value,Footprint,Manufacturer,MPN,DNP,Mouser,DigiKey,LCSC\n"), "{text}");+ assert!(text.contains(",RC0603FR-0710KL,,603-RC0603FR-0710KL,,C98220\n"), "{text}");+ let (_, p) = check_bom(&text, &i);+ assert!(p.is_empty(), "{p:?}\n{text}");+ // no distributor field anywhere: the columns stay as they were+ assert!(write_bom(&inv()).starts_with("Reference,Qty,Value,Footprint,Manufacturer,MPN,DNP\n"));+ }+ #[test] fn off_board_parts_go_in_the_bom_as_do_not_place_lines() { let i = inv();
crates/adom-aiflow/src/main.rs+129−10@@ -123,7 +123,8 @@ enum Cmd { SilkscreenDashboard { action: String, #[arg(long, default_value="auto")] port: String, #[arg(long, default_value="wv")] surface: String, #[arg(long)] url: Option<String>, #[arg(long)] target: Option<String>, #[arg(long)] json: Option<String>, #[arg(long)] reason: Option<String> }, /// Whole-board silkscreen obstacle audit (fail-closed). With --record, a pass whose inventory covers the board (every footprint reference, a via/hole item per via) and whose labels meet finish's per-footprint minimum records the `silkscreen` step proof; a failed audit records nothing. SilkscreenAudit { /// a hand-built inventory; without it the input is built from --board (or the run's current board) and written beside --out- #[arg(long)] input: Option<PathBuf>, #[arg(long)] out: PathBuf, /// record the silkscreen step proof when the audit passes and covers the board+ #[arg(long)] input: Option<PathBuf>, /// the audit result (default: <run>/silkscreen/silkscreen-audit.json); its folder is made when missing+ #[arg(long)] out: Option<PathBuf>, /// record the silkscreen step proof when the audit passes and covers the board #[arg(long)] record: bool, /// the board the inventory covers (default: the run's current board) #[arg(long)] board: Option<String> }, /// `silkscreen fab-check|fab-tidy [--board B] [--out O] [--size MM]`: the Fab layer standard (issue #163). fab-check reports Fab texts off their parts, values shown and mixed reference sizes; fab-tidy writes a copy of the board with each reference centred on its body, upright along its long axis, one size (shrunk only to fit, floor 0.3 mm), values hidden. Only Fab texts change.@@ -215,7 +216,9 @@ enum Cmd { /// Verify and bind the current snapshot to an exact saved native KiCad file. BindRemoteBoard { #[arg(long)] remote_board: String }, /// Adopt a native-saved board after AI-owned edits, preserving project rules and checking baseline DRC.- AdoptBoard { #[arg(long)] board: String, #[arg(long)] evidence: String },+ AdoptBoard { /// the native-saved board to adopt+ #[arg(long)] board: String, /// required: how the board was saved and checked in its EDA (review notes, or a report's path), recorded with the adoption+ #[arg(long)] evidence: String }, /// `parts [--bom <csv>] [--show] [--dwell 4]`: the from-scratch board's parts on the wiki. Every BOM row with an MPN (default: the BOM the sourcing check passed) is matched to its Adom wiki component page (a `wiki` column, owner/slug, names it directly; else the MPN's slug forms, then a page whose component.mpn is the MPN); --show walks a Hydrogen tab through each page so the viewer sees the parts being chosen. A part with no page fails: make it (wiki-component skill) and run again, or give it from the board's own project library (--project-lib). Parts { #[arg(long)] bom: Option<String>, #[arg(long)] show: bool, #[arg(long, default_value_t = 4)] dwell: u64, /// a project library folder for parts with no public component page: KiCad .kicad_sym, .pretty footprints, STEP models and a provenance.json naming each MPN's source (default: the spec's or requirements' "projectLib"). Each listed MPN needs a symbol, a footprint, a model and provenance; project-page packages them, finish reports them. #[arg(long)] project_lib: Option<String> },@@ -226,7 +229,8 @@ enum Cmd { /// `supply-risk [--file design/supply-risk.json]`: record your assessment of the parts that could not get a page (issue #193): per part the risk (high, medium, low), lifecycle, distributors with stock, lead time, second sources, package, whether a datasheet and land pattern are published, and up to three alternatives with what each changes on the board; every figure with its source and date. What the file leaves out is reported, never refused. `--choose <MPN> --pick <alternative|keep> --why "..."` records the human's choice (only after they made it). SupplyRisk { #[arg(long, default_value = supply::DEFAULT_FILE)] file: String, #[arg(long)] choose: Option<String>, #[arg(long)] pick: Option<String>, #[arg(long)] why: Option<String> }, /// `project-page --page <owner/slug> [--create]`: revision 1 of the board's project page before any EDA work: a README that says what the board is with the component table, and a KiCad PCM repository of every part (an Adom Cloud Library, exported and repackaged for KiCad's Plugin and Content Manager). Opens the page in Hydrogen.- ProjectPage { #[arg(long, default_value = "")] page: String, /// write the design review (design-review/README.md: Fields current and thermal numbers, your analysis figures, a molecule's contact table, the parts table with prices) for the current board into the page's staging folder, or into --out (a molecule-publish package folder); prints the push (issues #147, #164)+ ProjectPage { /// the page, owner/slug. The parts come from the `parts` record: project-library parts are the ones `parts --project-lib <dir>` (or spec/requirements "projectLib") resolved, so run `parts` with it first; project-page itself takes no --project-lib+ #[arg(long, default_value = "")] page: String, /// write the design review (design-review/README.md: Fields current and thermal numbers, your analysis figures, a molecule's contact table, the parts table with prices) for the current board into the page's staging folder, or into --out (a molecule-publish package folder); prints the push (issues #147, #164) #[arg(long)] results: bool, /// with --results: the folder to write design-review/ into (a molecule-publish package folder) instead of <run>/page-results #[arg(long)] out: Option<String>, /// push every visited step's sub-readme and the README's "How this board was built" section now (each step's is also pushed in the background when the run leaves it) #[arg(long)] sync: bool, #[arg(long)] create: bool, /// the page already exists and is this same board's own page (an earlier run of it); refused otherwise@@ -3559,6 +3563,62 @@ fn wiki_page_json(page: &str) -> Option<Value> { serde_json::from_str(t.get(t.find('{')?..=t.rfind('}')?)?).ok() } +/// AF31: the references of a component register whose review is still open: no review status, or+/// "pending" or "stale" (a status the AI wrote, like "pass" or "reference-only", is a recorded review).+fn components_review_open(report: &Value) -> Vec<String> {+ report["components"].as_array().into_iter().flatten()+ .filter(|e| matches!(e["review"]["status"].as_str().map(|s| s.trim().to_ascii_lowercase()).as_deref(), None | Some("") | Some("pending") | Some("stale")))+ .filter_map(|e| e["reference"].as_str().map(str::to_string)).collect()+}++/// The register's review state in one clause: which references still wait for the AI review.+fn components_review_line(open: &[String]) -> String {+ if open.is_empty() { return "every reference has a recorded review (none pending or stale)".into(); }+ let shown = if open.len() > 12 { format!("{} and {} more", open[..12].join(", "), open.len() - 12) } else { open.join(", ") };+ format!("AI review is pending for {} reference(s): {shown}", open.len())+}++/// N4: the dangling tracks and vias a KiCad DRC report names (`track_dangling`, `via_dangling`), as+/// "track with an open end on NET at (x, y)" / "via on NET at (x, y)": KiCad's position of the item.+fn dangling_copper(drc: &Value) -> Vec<String> {+ drc["violations"].as_array().into_iter().flatten().filter_map(|v| {+ let what = match v["type"].as_str()? { "track_dangling" => "track with an open end", "via_dangling" => "via", _ => return None };+ let item = &v["items"][0];+ let at = item["pos"]["x"].as_f64().zip(item["pos"]["y"].as_f64()).map(|(x, y)| format!(" at ({x:.2}, {y:.2})")).unwrap_or_default();+ let net = item["description"].as_str().and_then(|d| d.split('[').nth(1)).and_then(|d| d.split(']').next()).map(|n| format!(" on {n}")).unwrap_or_default();+ Some(format!("{what}{net}{at}"))+ }).collect()+}++/// AF112: the pads (REF.PAD) and vias whose teardrops are enabled (`(teardrops ... (enabled yes))`): KiCad's+/// refill makes a teardrop zone on each, copper the plan never named.+fn teardrop_items(b: &Board) -> Vec<String> {+ let on = |n: &aiflow_board::sx::Node| n.find("teardrops").and_then(|t| t.find("enabled")).and_then(|e| e.value()) == Some("yes");+ let mut out = Vec::new();+ for fp in b.root.find_all("footprint") {+ let reference = aiflow_board::reference_of(fp).unwrap_or_default();+ for p in fp.find_all("pad").filter(|p| on(p)) { out.push(format!("{reference}.{}", p.value().unwrap_or(""))); }+ }+ for v in b.root.find_all("via").filter(|v| on(v)) {+ let at = v.find("at");+ out.push(format!("via at ({:.2}, {:.2})", at.and_then(|a| a.number(1)).unwrap_or(0.0), at.and_then(|a| a.number(2)).unwrap_or(0.0)));+ }+ out+}++/// AF24: is package `id` installed by a kicad_pcm_list answer? Only a package row (an object whose+/// `identifier` is `id`) counts, and not one whose `onDisk` is false (KiCad lists it, its files are gone).+fn pcm_installed(list: &Value, id: &str) -> bool {+ match list {+ Value::Object(o) => {+ if o.get("identifier").and_then(Value::as_str) == Some(id) && o.get("onDisk").and_then(Value::as_bool) != Some(false) { return true; }+ o.values().any(|v| pcm_installed(v, id))+ }+ Value::Array(a) => a.iter().any(|v| pcm_installed(v, id)),+ _ => false,+ }+}+ /// The installed version of package `id` in a kicad_pcm_list answer (any object whose identifier is `id`). fn pcm_installed_version(list: &Value, id: &str) -> Option<String> { match list {@@ -3579,6 +3639,43 @@ mod pcm_installed_version_tests { assert_eq!(super::pcm_installed_version(&list, "inc.adom.wiki.x.y").as_deref(), Some("1.0.0")); assert_eq!(super::pcm_installed_version(&list, "nope"), None); }++ /// AF24: the shape a Windows KiCad 10 bridge answers (packages[] rows with identifier, version, onDisk;+ /// repositories[] with name and url). Text that merely quotes the identifier is no installed package.+ #[test]+ fn installed_only_by_a_package_row() {+ let id = "inc.adom.wiki.owner.board";+ let row = serde_json::json!({"success": true, "count": 1, "packages": [{"identifier": id, "version": "1.0.0", "onDisk": true, "type": "library"}], "repositories": [{"name": "Board (Adom wiki)", "url": "https://example.invalid/pcm/repository.json"}]});+ assert!(super::pcm_installed(&row, id));+ let quoted = serde_json::json!({"success": false, "error": format!("package {id} is not installed"), "packages": []});+ assert!(serde_json::to_string("ed).unwrap().contains(id) && !super::pcm_installed("ed, id));+ let hinted = serde_json::json!({"success": true, "count": 0, "packages": [], "_hint": format!("install {id} with kicad_pcm_install")});+ assert!(!super::pcm_installed(&hinted, id));+ let gone = serde_json::json!({"packages": [{"identifier": id, "version": "1.0.0", "onDisk": false}]});+ assert!(!super::pcm_installed(&gone, id));+ let other = serde_json::json!({"packages": [{"identifier": format!("{id}.extra"), "version": "1.0.0"}]});+ assert!(!super::pcm_installed(&other, id));+ }+}++#[cfg(test)]+mod components_review_tests {+ /// AF31: the reply names the references still waiting for review, from the register itself+ #[test]+ fn pending_only_for_references_whose_review_is_open() {+ let reg = serde_json::json!({"components": [+ {"reference": "R1", "review": {"status": "pending"}},+ {"reference": "U1", "review": {"status": "pass"}},+ {"reference": "C1", "review": {"status": "stale"}},+ {"reference": "J1", "review": {"status": "reference-only"}}]});+ let open = super::components_review_open(®);+ assert_eq!(open, vec!["R1", "C1"]);+ assert_eq!(super::components_review_line(&open), "AI review is pending for 2 reference(s): R1, C1");+ let done = serde_json::json!({"components": [{"reference": "U1", "review": {"status": "pass"}}, {"reference": "R1", "review": {"status": "needs-work"}}]});+ let open = super::components_review_open(&done);+ assert!(open.is_empty());+ assert!(!super::components_review_line(&open).contains("pending for"), "{}", super::components_review_line(&open));+ } } /// The page the background step pages go to when the run leaves a step: the project page, unless@@ -3916,6 +4013,13 @@ fn main() { thread(&cli); // a plain audit of a named board needs no run; --record (and the default board) do let run = if *record || board.is_none() { Some(load_run(&cli)) } else { Run::open(&run_dir(&cli)) };+ // N25, N29: --out may be left out (the run's silkscreen folder), and a folder that does not exist yet is+ // made, so `--out audit/result.json` no longer fails on the input file it writes beside it+ let out_path: PathBuf = out.clone().unwrap_or_else(|| run.as_ref().map(|r| r.dir.join("silkscreen").join("silkscreen-audit.json")).unwrap_or_else(|| PathBuf::from("silkscreen-audit.json")));+ if let Some(parent) = out_path.parent().filter(|p| !p.as_os_str().is_empty()) {+ std::fs::create_dir_all(parent).unwrap_or_else(|e| err(&format!("{}: {e}", parent.display()), &[]));+ }+ let out = &out_path; // issue #153: with no --input, the input is built from the saved board (same geometry for every engine) let built = input.is_none(); let input = input.clone().unwrap_or_else(|| {@@ -4464,10 +4568,17 @@ fn main() { aiflow_copper::copy_project_rules(board,&dest.display().to_string()).unwrap_or_else(|e|err(&e,&[])); let (carried, carry_note) = copper_carry::adopt(&mut r, &dest.display().to_string()); r.data["remoteBinding"]=Value::Null;- r.log("adopt-board",json!({"source":board,"board":dest,"evidence":evidence,"drc":summary,"copperCarried":carried}));+ // N4: dangling tracks and vias (KiCad's own DRC warnings) are named, not left for the human to find;+ // AF112: pads and vias that ask KiCad for teardrops are named (a refill adds teardrop zones there)+ let dangling = dangling_copper(&candidate);+ let teardrops = teardrop_items(&Board::load(board).unwrap_or_else(|e| err(&e, &[])));+ r.log("adopt-board",json!({"source":board,"board":dest,"evidence":evidence,"drc":summary,"copperCarried":carried,"dangling":dangling,"teardropItems":teardrops})); r.save().unwrap();- if carried { ok(&format!("native-saved board adopted; historical snapshots preserved; {carry_note}"), &["Silkscreen changed: record the silkscreen proof again (`silkscreen-audit --record`) and export again; finish reruns the full native DRC. Bind the desktop board again (bind-remote-board) before live commands.".into()]); }- else { ok(&format!("native-saved board adopted; historical snapshots preserved; {carry_note}"), &["Run plan, then route: it keeps the board's own tracks and vias and plans only the connections they leave open (a fully routed board gets an empty plan that gate, land route and finish accept). Re-solve Fields before finish.".into()]); }+ let mut extra: Vec<String> = Vec::new();+ if !dangling.is_empty() { extra.push(format!("dangling copper on the adopted board (KiCad DRC warnings, not blocking): {}{}. They stay in the Gerbers: remove them in KiCad (Edit > Cleanup Tracks and Vias, or delete them), save, and adopt again.", dangling.iter().take(10).cloned().collect::<Vec<_>>().join("; "), if dangling.len() > 10 { format!("; and {} more (run.jsonl adopt-board)", dangling.len() - 10) } else { String::new() })); }+ if !teardrops.is_empty() { extra.push(format!("{} pad(s) or via(s) ask KiCad for teardrops ({}): a KiCad refill adds a small teardrop zone on each (priority 30000, attr teardrop). They are KiCad's own copper, not pours; check that the footprints mean them.", teardrops.len(), teardrops.iter().take(12).cloned().collect::<Vec<_>>().join(", "))); }+ if carried { ok(&format!("native-saved board adopted; historical snapshots preserved; {carry_note}"), &[extra.clone(), vec!["Silkscreen changed: record the silkscreen proof again (`silkscreen-audit --record`) and export again; finish reruns the full native DRC. Bind the desktop board again (bind-remote-board) before live commands.".into()]].concat()); }+ else { ok(&format!("native-saved board adopted; historical snapshots preserved; {carry_note}"), &[extra, vec!["Run plan, then route: it keeps the board's own tracks and vias and plans only the connections they leave open (a fully routed board gets an empty plan that gate, land route and finish accept). Re-solve Fields before finish.".into()]].concat()); } } Cmd::Parts { bom, show, dwell, project_lib } => { let t = thread(&cli);@@ -4834,8 +4945,9 @@ fn main() { let Some(id) = pp["identifier"].as_str().map(str::to_string) else { err("no project page yet: `project-page --page <owner/slug> --create` first", &[]) }; let br = bridge_of(&r, &cli); let list = br.raw_call("kicad_pcm_list", &json!({}));- let text = list.to_string();- let installed = text.contains(&id);+ // AF24: installed means a package row of the reply names the identifier (and its files are on+ // disk), not that the reply's text quotes it somewhere (an error, a hint, a repository name)+ let installed = pcm_installed(&list, &id); // issue #169: an installed package older than the page's build still has the old parts let built = pp["pcmVersion"].as_str().unwrap_or("").to_string(); let have = pcm_installed_version(&list, &id);@@ -4919,13 +5031,15 @@ fn main() { let report = json!({"schemaVersion": 1, "board": b.path, "mpnMarking": preference, "components": entries, "qualityGate": "AI review required; this inventory does not certify identities, geometry, redistribution rights or native rendering"}); std::fs::write(&path, serde_json::to_string_pretty(&report).unwrap()).unwrap_or_else(|e| err(&format!("write component register: {e}"), &[]));- r.data["components"] = json!({"register": path, "mpnMarking": preference, "reviewStatus": "pending"});+ // AF31: the references whose review is still open, from the register itself (not a fixed "pending")+ let open = components_review_open(&report);+ r.data["components"] = json!({"register": path, "mpnMarking": preference, "reviewStatus": if open.is_empty() { "recorded" } else { "pending" }, "reviewOpen": open.len()}); r.save().unwrap_or_else(|e| err(&e, &[])); let flow: Value = serde_json::from_str(include_str!("../../../flows/board.json")).unwrap(); let step = flow["steps"].as_array().unwrap().iter().find(|s| s["name"] == "components").unwrap(); let mut hints: Vec<String> = step["workflow"].as_array().unwrap().iter().filter_map(Value::as_str).map(str::to_owned).collect(); hints.push(format!("MPN marking preference: {preference} (default on: every IC's model carries its laser-etched MPN, and finish checks it). Mark a model with `adom-aiflow-etch --in <model.step> --mpn <MPN> --out <model-etched.step> --footprint <part.kicad_mod>`: the mark planner places it (along the longest usable dimension, between the terminations, as large as fits, upright with pin 1 lower left), the shared service writes it with the model's colours, and the legibility gate must say PASS; look at <etched>.check.png before you report (Marking checklist in the adom-aiflow skill). 'off' keeps plain models; 'ask' offers the option. Existing review notes are preserved on rerun; re-review when source properties or geometry changes."));- ok(&format!("component register: {} ({} references); AI review is pending", path.display(), report["components"].as_array().unwrap().len()), &hints);+ ok(&format!("component register: {} ({} references); {}", path.display(), report["components"].as_array().unwrap().len(), components_review_line(&open)), &hints); } Cmd::Plan => { let mut r = load_run(&cli);@@ -5194,9 +5308,14 @@ fn main() { let b = board_of(&r); // issue #140: a part outside the outline cannot be routed; name it before routing (the router reports its nets as unrouted) let outside = aiflow_place::parts_outside(&b, &edge_overhang::allowed(&spec, &[]).map(|o| edge_overhang::refs(&o)).unwrap_or_default());+ // AF69: a courtyard that alone crosses the edge leaves its pads inside: the router routes them+ let (outside, courtyard_only) = aiflow_place::split_courtyard_only(&b, outside); if !outside.is_empty() { note(&format!("{} part(s) outside the board outline; their connections are left unrouted:\n {}", outside.len(), outside.iter().map(|(_, w)| w.as_str()).collect::<Vec<_>>().join("\n ")), &[aiflow_place::OUTSIDE_HINT.into()]); }+ if !courtyard_only.is_empty() {+ note(&format!("{} part(s) whose courtyard alone crosses the board edge; their pads are inside and are routed:\n {}", courtyard_only.len(), courtyard_only.iter().map(|(_, w)| w.as_str()).collect::<Vec<_>>().join("\n ")), &[aiflow_place::COURTYARD_ONLY_HINT.into()]);+ } let missing=aiflow_pours::missing_planes(&b,&spec); if !missing.is_empty(){err(&format!("declared reference planes do not exist: {}",missing.join(", ")), &["Create the listed net/layer zones through the EDA bridge, fill and save them, then `adom-aiflow adopt-board --board <saved.kicad_pcb> --evidence <native review notes>` before route. A spec.planes declaration alone is not copper.".into()]);} let mut rules = aiflow_router::Rules::from_spec(&spec);
crates/adom-aiflow/src/preboard.rs+11−4@@ -128,7 +128,7 @@ pub fn sourcing_check(bom: &str, board: Option<&(BTreeSet<String>, BTreeSet<Stri if !errors.is_empty() { return json!({"pass": false, "errors": errors, "warnings": warnings, "rows": rows.len().saturating_sub(1)}); } let get = |row: &Vec<String>, c: Option<usize>| c.and_then(|i| row.get(i)).map(|s| s.trim().to_string()).unwrap_or_default(); let mut bom_refs: BTreeMap<String, usize> = BTreeMap::new();- let mut per_mpn: BTreeMap<String, (u64, Option<u64>, String)> = BTreeMap::new(); // mpn -> (refs, stock, first ref)+ let mut per_mpn: BTreeMap<String, (u64, Option<u64>, String, bool)> = BTreeMap::new(); // mpn -> (refs, stock, first ref, an Adom stock row) let (mut no_part_rows, mut adom_rows, mut distributor_rows, mut lcsc_rows) = (0usize, 0usize, 0usize, 0usize); let mut dates: BTreeSet<String> = header_date.iter().cloned().collect(); let mut adom_no_qty: Vec<String> = Vec::new();@@ -177,7 +177,7 @@ pub fn sourcing_check(bom: &str, board: Option<&(BTreeSet<String>, BTreeSet<Stri if header_date.is_none() && c_stock_date.map(|c| get(row, Some(c)).is_empty()).unwrap_or(true) && !stock_text.is_empty() { errors.push(format!("{label} ({mpn}): the stock check has no date")); }- let e = per_mpn.entry(mpn.clone()).or_insert((0, None, label.clone()));+ let e = per_mpn.entry(mpn.clone()).or_insert((0, None, label.clone(), adom)); e.0 += refs.len() as u64; if e.1.is_none() { e.1 = stock; } }@@ -192,10 +192,12 @@ pub fn sourcing_check(bom: &str, board: Option<&(BTreeSet<String>, BTreeSet<Stri warnings.push(consigned_warning.clone()); } if !adom_no_qty.is_empty() { warnings.push(format!("{} Adom stock row(s) with no quantity recorded ({}): `pnp-inventory bulk-check --bom <csv>` fills it", adom_no_qty.len(), adom_no_qty.join(", "))); }- for (mpn, (n, stock, label)) in &per_mpn {+ for (mpn, (n, stock, label, adom)) in &per_mpn { if let Some(s) = stock { let need = n * qty.max(1);- if *s < 2 * need { warnings.push(format!("{label} ({mpn}): thin stock, {s} on hand for {need} needed ({n} per board x {qty}); under 2x the build: order early or pick a second source")); }+ // AF58: an Adom stock row's count is Adom's own reels; say so, so a distributor's 0 copied into it is seen for what it is+ let whose = if *adom { "; an Adom stock row: its count must be Adom's own reels (`pnp-inventory bulk-check --bom <csv>` reads them), not a distributor's stock" } else { "" };+ if *s < 2 * need { warnings.push(format!("{label} ({mpn}): thin stock, {s} on hand for {need} needed ({n} per board x {qty}); under 2x the build: order early or pick a second source{whose}")); } } } let (mut missing, mut extra) = (Vec::new(), Vec::new());@@ -801,6 +803,11 @@ mod tests { let out = sourcing_check("ref,mpn,source,stock,stock_date\nU1,TPS,Mouser,15,2026-09-29\n", None, "fab", 10); assert_eq!(out["pass"], true, "{out}"); assert!(out["warnings"].to_string().contains("thin stock"));+ assert!(!out["warnings"].to_string().contains("Adom stock row"));+ // AF58: an Adom stock row with a distributor's 0 copied into it: the warning says whose count it must be+ let out = sourcing_check("ref,mpn,source,stock,stock_date\nC1,CL21A226MPQNNNE,\"Adom stock (basic part, also Mouser)\",0,2026-11-10\n", None, "fab", 10);+ let w = out["warnings"].to_string();+ assert!(w.contains("thin stock, 0 on hand") && w.contains("an Adom stock row: its count must be Adom's own reels") && w.contains("pnp-inventory bulk-check"), "{w}"); } #[test]
crates/adom-aiflow/src/sequence.rs+11@@ -383,6 +383,9 @@ pub fn overdue_warning(data: &Value, flow: &Value, seq: &[String], now_secs: u64 if !data["clock"]["deliveredTime"].is_null() { return None; } let current = data["currentStep"].as_str()?; let at = last_visit(data, current).and_then(|t| aiflow_run::parse(&t))?;+ // N32: `finish` has run on this visit: the commands after it (a silkscreen pass, an audit of a+ // finished or copied run) are not a step left undeclared+ if current == "finish" && data["clock"]["finishTime"].as_str().and_then(aiflow_run::parse).is_some_and(|f| f >= at) { return None; } let min = now_secs.saturating_sub(at) / 60; let expected = expected_minutes(flow, current); if min <= expected * 2 { return None; }@@ -606,6 +609,14 @@ mod tests { let mut done = d.clone(); done["clock"]["deliveredTime"] = json!("2026-01-01T01:00:00Z"); assert!(overdue_warning(&done, &flow, &seq, t0 + 999 * 60).is_none());+ // N32: still in finish hours after it ran (a later silkscreen pass on a finished run): no nag+ let mut fin = json!({"currentStep": "finish", "clock": {"deliveredTime": null, "finishTime": null}, "steps": {"finish": {"visits": [{"at": "2026-01-01T00:00:00Z"}]}}});+ assert!(overdue_warning(&fin, &flow, &seq, t0 + 383 * 60).is_some(), "finish not run yet: the nag stays");+ fin["clock"]["finishTime"] = json!("2026-01-01T00:20:00Z");+ assert!(overdue_warning(&fin, &flow, &seq, t0 + 383 * 60).is_none());+ // a finish from an earlier visit does not cover a new one+ fin["steps"]["finish"]["visits"] = json!([{"at": "2026-01-01T00:00:00Z"}, {"at": "2026-01-01T02:00:00Z"}]);+ assert!(overdue_warning(&fin, &flow, &seq, t0 + 383 * 60).is_some()); } }
crates/adom-aiflow/src/silkproof.rs+8@@ -173,6 +173,11 @@ pub fn mark_gaps(input: &Value, board: &Board) -> Vec<String> { for m in &marks { let boxes = mark_boxes(m); if boxes.is_empty() { continue; }+ // AF50: a leader line or a frame draws no text, so it is never judged against a footprint's text by its+ // id (`C17:leader` read as C17's reference box): the comment above says so, and now the code does+ let id_text = m["id"].as_str().unwrap_or("");+ let draws_no_text = |s: &str| matches!(s.trim().to_ascii_lowercase().as_str(), "leader" | "frame" | "line" | "arrow");+ if m["text"].is_null() && (m["kind"].as_str().is_some_and(draws_no_text) || id_text.rsplit([':', '-']).next().is_some_and(draws_no_text)) { continue; } let u = boxes.iter().fold((f64::MAX, f64::MAX, f64::MIN, f64::MIN), |a, b| (a.0.min(b.0), a.1.min(b.1), a.2.max(b.2), a.3.max(b.3))); let layer = m["layer"].as_str(); let id = m["id"].as_str().unwrap_or("");@@ -329,6 +334,9 @@ mod tests { let named = with(json!([{"id": "lbl", "text": "10k", "layer": "F.SilkS", "box": [0.0, 0.0, 0.5, 0.5]}, {"id": "frame", "layer": "F.SilkS", "box": [8.0, 8.0, 8.2, 8.2]}])); let why = geometry_gaps(&named, &b).join("; "); assert!(why.contains("1 label") && why.contains("\"10k\""), "{why}");+ // AF50: a leader line (no text) beside its part is not a label box: never judged against the reference+ let leaders = with(json!([{"id": "R1:leader", "layer": "F.SilkS", "box": [1.9, 1.3, 2.1, 3.0]}, {"id": "C1-frame", "layer": "F.SilkS", "box": [5.0, 2.0, 5.1, 2.1]}, {"id": "x", "kind": "leader", "layer": "F.SilkS", "box": [1.7, 0.7, 1.8, 1.3]}]));+ assert!(geometry_gaps(&leaders, &b).is_empty(), "{:?}", geometry_gaps(&leaders, &b)); // rotation: a 90 degree text needs a tall box let rot = BOARD.replace("(property \"Reference\" \"R1\" (at 0 -1)", "(property \"Reference\" \"R1\" (at 0 -1 90)"); let b90 = Board::from_text("t.kicad_pcb", rot).unwrap();
crates/aiflow-analyze/src/lib.rs+17−1@@ -245,6 +245,7 @@ fn thermal_with_vias(plan: &Value, spec: &Value, zone_state: Option<&Value>, boa let limit = theta_limit.unwrap_or(if rise_limit.is_some() { f64::INFINITY } else { 60.0 }); let rise = theta * watts; let mut r = json!({"ref": reference, "watts": watts, "tabNet": net, "pourLayers": layers, "pourFilledMm2": area, "viasOnNet": vias, "thetaEstimateCPerW": (theta * 10.0).round() / 10.0, "limitCPerW": theta_limit, "riseEstimateC": (rise * 10.0).round() / 10.0, "riseLimitC": rise_limit});+ if theta_limit.is_none() && rise_limit.is_none() { r["defaultLimitCPerW"] = json!(60.0); } if zs.is_empty() { r["status"] = json!("fail"); r["hint"] = json!(if net.is_empty() { format!("{reference} dissipates {watts:.2} W but names no tabNet: give the net of its exposed tab, or, for a part with no tab (an LED, an inductor, a small leaded IC), declare \"cooling\": \"leads\" so the Fields solve judges it through its leads") } else { format!("{reference} dissipates {watts:.1} W into {net} but {net} has no pour: pour the tab net on the outer layers with a solid connection and thermal vias in the tab") });@@ -252,7 +253,9 @@ fn thermal_with_vias(plan: &Value, spec: &Value, zone_state: Option<&Value>, boa } else if theta > limit { r["status"] = json!("fail"); if theta_limit.is_none() { r["estimateFailed"] = json!(true); }- r["hint"] = json!(format!("{reference}: {area:.0} mm2 of copper on {net} gives about {theta:.0} C/W (limit {limit:.0}): widen the pour or add the other outer layer with vias"));+ // AF41: a part with no budget of its own is judged against AI Flow's default: say so+ let whose = if theta_limit.is_none() && rise_limit.is_none() { format!(", AI Flow's default: {reference} has no maxThetaCPerW or maxRiseC and the spec no hotMaxRiseC; give the part's real budget in spec.hot") } else { String::new() };+ r["hint"] = json!(format!("{reference}: {area:.0} mm2 of copper on {net} gives about {theta:.0} C/W (limit {limit:.0}{whose}): widen the pour or add the other outer layer with vias")); ok = false; } else if rise_limit.is_some_and(|l| rise > l) { r["status"] = json!("fail");@@ -288,6 +291,19 @@ mod tests { #[cfg(test)] mod regression_tests { use super::*;+ /// AF41: a hot part with no budget is judged against 60 C/W, and the finding says that is AI Flow's default+ #[test] fn the_default_thermal_budget_is_named() {+ let plan=json!({"nets":[]});+ let zs=json!({"zones":[{"type":"copper","net":"GND","layers":["F.Cu"],"fills":[{"areaMm2":5.0}]}]});+ let (pass,r)=analyze_thermal(&plan,&json!({"hot":{"U4":{"watts":0.041,"tabNet":"GND"}}}),Some(&zs));+ assert!(!pass);+ let h=r[0]["hint"].as_str().unwrap();+ assert!(h.contains("limit 60, AI Flow's default") && h.contains("give the part's real budget"), "{h}");+ assert_eq!(r[0]["defaultLimitCPerW"], 60.0);+ // a stated budget is the part's own: no default named+ let (_,r)=analyze_thermal(&plan,&json!({"hot":{"U4":{"watts":0.041,"tabNet":"GND","maxThetaCPerW":100}}}),Some(&zs));+ assert!(!r[0]["hint"].as_str().unwrap_or("").contains("default") && r[0].get("defaultLimitCPerW").is_none(), "{}", r[0]);+ } #[test] fn thermal_counts_vias_landed_after_routing() { // run 2026-10-15: SW poured on both layers, two vias landed after routing; the plan had none let plan=json!({"nets":[{"net":"SW","width":0.8,"paths":[[{"x":1.0,"y":1.0},{"x":2.0,"y":1.0}]]}]});
crates/aiflow-place/src/lib.rs+27@@ -571,6 +571,16 @@ pub fn parts_outside(board: &Board, overhang: &[String]) -> Vec<(String, String) } /// The suggestion that goes with `parts_outside` findings.+/// AF69: split `parts_outside` into the parts whose pads (or whole body) are outside, whose connections the+/// router sets aside, and the parts whose courtyard alone crosses the edge: their pads are inside and are routed.+pub fn split_courtyard_only(board: &Board, outside: Vec<(String, String)>) -> (Vec<(String, String)>, Vec<(String, String)>) {+ let whole = board.parts_outside();+ outside.into_iter().partition(|(r, _)| whole.contains(r) || board.pads.iter().any(|p| &p.reference == r && p.polys.iter().flatten().any(|q| board.point_outside(q.0, q.1))))+}++/// AF69: the hint for a part whose courtyard alone crosses the edge.+pub const COURTYARD_ONLY_HINT: &str = "A part meant to reach the edge (a connector mouth, a snap post, a cable exit): name it in spec placement.edgeOverhang [{\"ref\", \"why\"}] and this note goes. Otherwise move it inside with a wish and `place pack`.";+ pub const OUTSIDE_HINT: &str = "Move each part named above inside the outline: give it a wish in the wishes file (or a wider radius) and run `place pack` again (a pack that reports N-1 of N parts placed left the missing part where it was), then `place check` and `place land`. An edge connector meant to overhang: name it in spec placement.edgeOverhang [{\"ref\", \"why\"}]."; /// Courtyard overlaps and outside-the-outline parts among the moved refs on a board.@@ -639,6 +649,23 @@ mod tests { use super::*; use serde_json::json; + /// AF69: a part whose courtyard alone crosses the edge keeps its pads inside and is routed; a part with a pad+ /// past the edge is not. Only the second is "outside" for the router.+ #[test]+ fn a_courtyard_only_crossing_is_told_apart() {+ let t = "(kicad_pcb (version 20260206) (layers (0 \"F.Cu\" signal) (2 \"B.Cu\" signal) (25 \"Edge.Cuts\" user)) (gr_rect (start 0 0) (end 30 20) (layer \"Edge.Cuts\"))\n\+ (footprint \"J\" (layer \"F.Cu\") (at 2 10) (property \"Reference\" \"J1\") (fp_rect (start -2.5 -2) (end 2 2) (layer \"F.CrtYd\")) (pad \"1\" smd rect (at 0 0) (size 1 1) (layers \"F.Cu\") (net \"A\")))\n\+ (footprint \"J\" (layer \"F.Cu\") (at 29.8 10) (property \"Reference\" \"J2\") (fp_rect (start -1 -1) (end 1 1) (layer \"F.CrtYd\")) (pad \"1\" smd rect (at 0 0) (size 1 1) (layers \"F.Cu\") (net \"A\")))\n\+ (footprint \"R\" (layer \"F.Cu\") (at 15 10) (property \"Reference\" \"R1\") (fp_rect (start -1 -1) (end 1 1) (layer \"F.CrtYd\")) (pad \"1\" smd rect (at 0 0) (size 1 1) (layers \"F.Cu\") (net \"A\"))))";+ let b = Board::from_text("t", t.to_string()).unwrap();+ let outside = parts_outside(&b, &[]);+ let names: Vec<&str> = outside.iter().map(|(r, _)| r.as_str()).collect();+ assert_eq!(names, vec!["J1", "J2"], "{outside:?}");+ let (pads_out, courtyard_only) = split_courtyard_only(&b, outside);+ assert_eq!(pads_out.iter().map(|(r, _)| r.as_str()).collect::<Vec<_>>(), vec!["J2"], "{pads_out:?}");+ assert_eq!(courtyard_only.iter().map(|(r, _)| r.as_str()).collect::<Vec<_>>(), vec!["J1"], "{courtyard_only:?}");+ }+ /// A 30 x 20 mm board with two-pad parts: (reference, pad 1 net, pad 2 net, x, y); pads 1 mm apart on x. fn board(parts: &[(&str, &str, &str, f64, f64)]) -> Board { let mut t = String::from("(kicad_pcb\n\t(version 20260206)\n\t(generator \"test\")\n\t(layers\n\t\t(0 \"F.Cu\" signal)\n\t\t(2 \"B.Cu\" signal)\n\t\t(25 \"Edge.Cuts\" user)\n\t)\n");
skills/aiflow-silkscreen/SKILL.md+1−1@@ -138,7 +138,7 @@ When using native SVG as a 3D silkscreen texture, export with `--drill-shape-opt Every silkscreen command reads a JSON file you write; lengths are mm in board coordinates, boxes are `[x0, y0, x1, y1]`. -- `silkscreen-audit --board <board> --out result.json [--record]` (issue #153): leave out `--input` and the audit builds its input from the saved board (default the run's current board) and writes it beside `--out` as `silkscreen-audit-input.json`, so every engine audits the same geometry. The audit is a rectangle check (each label box against each obstacle box), so the builder gives shapes, not bounding boxes: each label is its turned text rectangle (KiCad stroke font estimate), each pad its outline (round pads as circles) plus 0.05 mm, each body its F.Fab hull (else courtyard), silk artwork its strokes, all cut into 0.1 mm strips; vias are their full square. A 45 degree label or a round test point is then not a false collision. Collisions are findings (exit 0, no proof recorded); an unreadable input is an error.+- `silkscreen-audit --board <board> --out result.json [--record]` (issue #153): leave out `--input` and the audit builds its input from the saved board (default the run's current board) and writes it beside `--out` as `silkscreen-audit-input.json`, so every engine audits the same geometry. `--out` may be left out (`<run>/silkscreen/silkscreen-audit.json`), and a folder it names that does not exist yet is made. The audit is a rectangle check (each label box against each obstacle box), so the builder gives shapes, not bounding boxes: each label is its turned text rectangle (KiCad stroke font estimate), each pad its outline (round pads as circles) plus 0.05 mm, each body its F.Fab hull (else courtyard), silk artwork its strokes, all cut into 0.1 mm strips; vias are their full square. A 45 degree label or a round test point is then not a false collision. Collisions are findings (exit 0, no proof recorded); an unreadable input is an error. - `silkscreen-audit --input audit.json --out result.json [--record]` (a hand-built input; one box per item reports collisions in the empty corners of turned labels and round pads): `{"obstacles": [{"id", "kind", "layer", "box" | "boxes": [[...]]}], "inventory": [{"id", "kind", "layers": ["F.SilkS", ...]}], "marks": [{"id", "layer", "box" | "boxes"}]}`. The inventory is independent of the obstacles and covers the whole board: every footprint by its reference (`R1`, `R1:body`, `R1:pad:1`) and a via or hole item per via. Every inventory item needs an obstacle with the same `id`, `kind` and `layer`; every mark is checked against every obstacle on its layer. `--record` also checks the boxes against the saved board (each pad inside one of its footprint's boxes, each via inside a via box as large as the via). Source: `tools/silkscreen-obstacle-check.py` in the package. - `silkscreen-layout --input candidates.json --out layout.json [--events ...]`: `{"bounds": [x0, y0, x1, y1], "obstacles": [{"box"}], "clearance": 0.12, "labels": [{"id", "anchor": [x, y], "maxDistance", "orderGroup", "order", "requiredRoles", "candidates": [{"position": [x, y], "box", "boxes", "font", "children": [{"role", "size"}], "qualityPenalty"}]}]}`. Source: `tools/silkscreen-layout.py`. - `silkscreen-sections`, `silkscreen-preflight` (`{"placements": [{"index", "box", "polygon"}], "obstacles": [...], "requiredIndices": [...]}`), `silkscreen-contact-policy` (`--geometry` carries the board `outline`) and `silkscreen-mask --board <file.kicad_pcb>`: see the scripts of the same names under `tools/` in the package for every key.
tests/housecleaning-workflow.pyadded+149@@ -0,0 +1,149 @@+"""Small fixes, end to end with the real binary, no CAD and no desktop (fake kicad-cli and adom-bridge):++- components (AF31): the reply names the references whose review is still open, not a fixed "AI review is pending";+- silkscreen-audit (N25, N29): --out may be left out, and a folder it names that does not exist yet is made;+- route (AF69): a part whose courtyard alone crosses the edge is not reported as left unrouted;+- adopt-board (N4, AF112): dangling tracks and vias from KiCad's DRC, and pads that ask KiCad for teardrops, are named;+- pcm check (AF24): a reply that only quotes the identifier is not an installed package;+- the over-budget warning (N32) is not printed once finish has run on this visit.++Usage: python3 tests/housecleaning-workflow.py <adom-aiflow binary>"""+import json, os, pathlib, subprocess, sys, tempfile++binary = str(pathlib.Path(sys.argv[1]).resolve())++FAKE_BRIDGE = r'''#!/usr/bin/env python3+import json, sys+if "kicad_pcm_list" in sys.argv:+ # the package is NOT installed; the reply only quotes its identifier in a hint+ print(json.dumps({"success": True, "status": "ok", "count": 0, "packages": [], "repositories": [],+ "_hint": "nothing installed; install inc.adom.wiki.test.board with kicad_pcm_install"}))+else:+ print(json.dumps({"success": True, "status": "ok", "revision": "r1"}))+'''+# DRC: a board carrying the STUB net has a dangling track and a dangling via (KiCad's warnings)+FAKE_CLI = r'''#!/usr/bin/env python3+import sys, json+a = sys.argv[1:]+if "--help" in a: print("--refill-zones --schematic-parity"); sys.exit(0)+if "version" in a or "--version" in a: print("10.0.8"); sys.exit(0)+out = a[a.index("--output") + 1]+text = open(a[-1]).read()+v = []+if '"STUB"' in text:+ v.append({"type": "track_dangling", "severity": "warning", "description": "Track has unconnected end", "items": [{"description": "Track [STUB] on F.Cu, length 3.0000 mm", "pos": {"x": 17.0, "y": 4.0}}]})+ v.append({"type": "via_dangling", "severity": "warning", "description": "Via is not connected or connected on only one layer", "items": [{"description": "Via [STUB] on F.Cu - B.Cu", "pos": {"x": 20.0, "y": 4.0}}]})+json.dump({"kicad_version": "10.0.8", "violations": v, "unconnected_items": []}, open(out, "w"))+'''+++def board(extra=''):+ return f'''(kicad_pcb (version 20240108) (generator "pcbnew")+ (layers (0 "F.Cu" signal) (31 "B.Cu" signal) (37 "F.SilkS" user) (44 "Edge.Cuts" user) (47 "F.CrtYd" user))+ (net 0 "") (net 1 "A") (net 2 "STUB")+ (gr_rect (start 0 0) (end 30 20) (layer "Edge.Cuts"))+ (footprint "T:J" (layer "F.Cu") (at 2 10) (property "Reference" "J1" (at 0 -3) (layer "F.SilkS") (effects (font (size 1 1) (thickness 0.15))))+ (fp_rect (start -2.5 -2) (end 2 2) (layer "F.CrtYd"))+ (pad "1" smd rect (at 0 0) (size 1 1) (layers "F.Cu") (net 1 "A")))+ (footprint "T:R" (layer "F.Cu") (at 15 10) (property "Reference" "R1" (at 0 -3) (layer "F.SilkS") (effects (font (size 1 1) (thickness 0.15))))+ (fp_rect (start -1 -1) (end 1 1) (layer "F.CrtYd"))+ (pad "1" smd rect (at 0 0) (size 1 1) (layers "F.Cu") (net 1 "A"){extra}))+)+'''+++TEARDROPS = ' (teardrops (best_length_ratio 0.5) (max_length 1) (best_width_ratio 1) (max_width 2) (curved_edges no) (filter_ratio 0.9) (enabled yes) (allow_two_segments yes) (prefer_zone_connections yes))'+passed = 0+failed = []+++def check(cond, what, out=''):+ """Each item is its own fix: a failure is listed and the next item still runs."""+ global passed+ if not cond:+ failed.append(what)+ print(f'FAIL: {what}\n{out[-1500:]}\n', file=sys.stderr)+ return+ passed += 1+++with tempfile.TemporaryDirectory(prefix='aiflow-housecleaning-') as td:+ p = pathlib.Path(td)+ bindir = p / 'bin'; bindir.mkdir()+ (bindir / 'adom-bridge').write_text(FAKE_BRIDGE); (bindir / 'adom-bridge').chmod(0o755)+ (bindir / 'kicad-cli').write_text(FAKE_CLI); (bindir / 'kicad-cli').chmod(0o755)+ env = dict(os.environ, AIFLOW_DASHBOARD='off', AIFLOW_NO_PART_SEARCH='1', AIFLOW_NO_PART_LOOKUP='1', AIFLOW_AUTO_CAPTURE='off',+ ADOM_AIFLOW_KICAD_CLI=str(bindir / 'kicad-cli'), PATH=f"{bindir}:{os.environ['PATH']}")+ env.pop('KICAD_REMOTE_TARGET', None)++ def call(run, *args):+ r = subprocess.run([binary, '--run', str(run), '--ai-thread', 'housecleaning-test', *args], env=env, capture_output=True, text=True, timeout=600)+ return r, r.stdout + r.stderr++ (p / 'b.kicad_pcb').write_text(board())+ (p / 'spec.json').write_text(json.dumps({"board": "housecleaning", "clearance": 0.2}))+ run = p / 'run'+ r, out = call(run, 'start', '--board', str(p / 'b.kicad_pcb'), '--spec', str(p / 'spec.json'), '--engine', 'test', '--target', 'fakebox', '--remote-board', 'C:/boards/b.kicad_pcb')+ check(r.returncode == 0, 'start', out)++ # ---- AF31: components+ r, out = call(run, 'components', '--etch', 'off')+ check(r.returncode == 0 and 'AI review is pending for 2 reference(s): J1, R1' in out, 'components names the two open reviews', out)+ reg = json.loads((run / 'components.json').read_text())+ for e in reg['components']:+ e['review']['status'] = 'pass'+ (run / 'components.json').write_text(json.dumps(reg))+ r, out = call(run, 'components', '--etch', 'off')+ check(r.returncode == 0 and 'every reference has a recorded review' in out and 'AI review is pending' not in out, 'components after every review is recorded', out)++ # ---- N29, N25: silkscreen-audit --out into a new folder, and with no --out+ target = p / 'audit' / 'new' / 'result.json'+ r, out = call(run, 'silkscreen-audit', '--board', str(p / 'b.kicad_pcb'), '--out', str(target))+ check('No such file' not in out and (target.parent / 'silkscreen-audit-input.json').is_file(), 'silkscreen-audit makes the --out folder', out)+ r, out = call(run, 'silkscreen-audit')+ check('--out' not in out.split('\n')[0] and (run / 'silkscreen' / 'silkscreen-audit-input.json').is_file(), 'silkscreen-audit with no --out writes into the run', out)++ # ---- AF69: route with J1's courtyard over the left edge (its pad is inside)+ (p / 'plan.json').write_text(json.dumps({"nets": []}))+ r, out = call(run, 'route', '--passes', '1')+ check('courtyard alone crosses the board edge' in out and 'left unrouted' not in out, 'route tells a courtyard-only crossing apart', out)++ # ---- N4, AF112: adopt-board on a board with a dangling track and via, and a pad that asks for teardrops+ cand = board(TEARDROPS).replace('\n)\n', '\n (segment (start 14 4) (end 17 4) (width 0.2) (layer "F.Cu") (net 2))\n (via (at 20 4) (size 0.6) (drill 0.3) (layers "F.Cu" "B.Cu") (net 2))\n)\n')+ check('(segment' in cand and TEARDROPS in cand, 'candidate board built')+ (p / 'cand.kicad_pcb').write_text(cand)+ r, out = call(run, 'adopt-board', '--board', str(p / 'cand.kicad_pcb'), '--evidence', 'test: saved and refilled in KiCad')+ check(r.returncode == 0, 'adopt-board runs', out)+ check('dangling copper on the adopted board' in out and 'track with an open end on STUB at (17.00, 4.00)' in out and 'via on STUB at (20.00, 4.00)' in out, 'adopt-board names the dangling copper', out)+ check('ask KiCad for teardrops (R1.1)' in out, 'adopt-board names the teardrop pads', out)++ # ---- AF56, N25: the help says where project-library parts come from, and what --evidence is+ r, out = call(run, 'project-page', '--help')+ check('parts --project-lib' in out, 'project-page --help names the project library source', out)+ r, out = call(run, 'adopt-board', '--help')+ check('how the board was saved and checked' in out, 'adopt-board --help describes --evidence', out)++ # ---- AF24: pcm check against a reply that only quotes the identifier+ d = json.loads((run / 'run.json').read_text())+ d.setdefault('outcomes', {})['project-page'] = {"identifier": "inc.adom.wiki.test.board", "pcmVersion": "1.0.0", "libName": "test-board", "repositoryUrl": "https://example.invalid/pcm/repository.json"}+ (run / 'run.json').write_text(json.dumps(d))+ r, out = call(run, 'pcm', 'check')+ check('is not installed' in out and 'is installed in KiCad' not in out, 'pcm check needs a package row', out)++ # ---- N32: still in finish hours after finish ran: no over-budget warning+ d = json.loads((run / 'run.json').read_text())+ d['currentStep'] = 'finish'+ d.setdefault('steps', {}).setdefault('finish', {})['visits'] = [{"at": "2026-01-01T00:00:00Z"}]+ d['clock']['finishTime'] = "2026-01-01T00:20:00Z"+ d['clock']['deliveredTime'] = None+ (run / 'run.json').write_text(json.dumps(d))+ r, out = call(run, 'silkscreen', 'fab-check', '--board', str(p / 'b.kicad_pcb'))+ check('still in finish after' not in out, 'no over-budget warning after finish ran', out)+ d['clock']['finishTime'] = None+ (run / 'run.json').write_text(json.dumps(d))+ r, out = call(run, 'silkscreen', 'fab-check', '--board', str(p / 'b.kicad_pcb'))+ check('still in finish after' in out, 'the warning stays while finish has not run', out)++if failed:+ sys.exit(f'FAILED housecleaning-workflow: {len(failed)} check(s): ' + '; '.join(failed))+print(f'OK housecleaning-workflow: {passed} checks passed')