← Commit history
Merge PR #568: Circuit explorer on the project page (circuit-explorer-page -> main) merge
Showing changes introduced by the merge (against its first parent).
14 files changed
+3528−11
crates/adom-aiflow/src/main.rs+172−6install.sh+2skills/adom-aiflow/SKILL.md+2skills/aiflow-molecule/SKILL.md+1−1skills/aiflow-project-page/SKILL.md+63−2tests/page-build-workflow.py+103tests/project-page-check.py+6tools/page-build.py+2443tools/page-explorer/explorer.css+84tools/page-explorer/explorer.js+320tools/page-explorer/symbols.json+26tools/project-page-check.py+6−2tools/requirements-page.txt+3tools/test_page_build.py+297crates/adom-aiflow/src/main.rs+172−6@@ -228,8 +228,9 @@ enum Cmd { #[arg(long)] later: bool }, /// `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 { /// 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+ /// `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. After export, for every board (issues #131, #164): `project-page --molecule-bundle <folder>` builds the page itself into the folder it is published from: readme.html with the board and its contacts, the netlist-checked circuit explorer (a block flowchart, each block drawn the textbook way), the simulation, the components, manufacturing and the open items, plus docs/; `project-page check` checks that built page (findings, never a stop).+ ProjectPage { /// `check`: the built page (readme.html in the --molecule-bundle folder): every section present and filled, every figure made from the folder's board, the circuit explorer at 100 % coverage with 0 netlist differences and no auto-drawn block, a readable number of blocks, a BOM row for every bought part. Findings, never a stop.+ #[arg(value_parser = ["check"])] what: Option<String>, /// 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)@@ -238,7 +239,13 @@ enum Cmd { #[arg(long)] brief: Option<String>, #[arg(long)] replace_readme: bool, /// build locally and push nothing to the page (the wiki parts are still added to your private Cloud Library and exported from it); the steps the run leaves later are not pushed there either, until `project-page --sync` #[arg(long)] no_push: bool, /// no wiki call at all (implies --no-push): no Cloud Library create, add or export, so only the project-library parts are packaged and the wiki parts are named as left out (issue #157) #[arg(long)] local_only: bool, /// a folder of an EXISTING page (relative, like rig/boards/rig-carrier): the board's README and its PCM repository go there, the repository URLs carry it; implies --existing and never creates a page- #[arg(long)] page_dir: Option<String> },+ #[arg(long)] page_dir: Option<String>, /// build the page into this folder (molecule-publish's Stage 2 package folder, or any folder a board page is published from): readme.html, docs/, package.json readme_order ["html"]; an existing README.md is left as it is+ #[arg(long, alias = "bundle")] molecule_bundle: Option<String>, /// the design netlist with a `block` per component, the explorer's blocks (default: netlist.json beside the BOM or under design/)+ #[arg(long)] netlist: Option<String>, /// the circuit explorer's source folder: one drawing JSON per block, blocks.json (default: explorer/ beside the netlist)+ #[arg(long)] explorer: Option<String>, /// the BOM for the components table (default: the BOM the sourcing check passed)+ #[arg(long)] bom: Option<String>, /// a Fields rating sweep JSON ({"<amps>": {peakStill, peakMoving, parts}}); repeat for more (default: <run>/fields/rating-sweep.json)+ #[arg(long)] sweep: Vec<String>, /// no wiki reads while building (part pictures from 3D thumbnails or placeholders)+ #[arg(long)] offline: bool }, /// `pcm check`: the project page's PCM package is installed in the test box's KiCad (kicad_pcm_list), so the schematic can use every part. Install it first with kicad_pcm_add_repository + kicad_pcm_install (the URLs project-page printed). Pcm { #[arg(value_parser = ["check"])] what: String }, /// `schematic check --sch <file.kicad_sch>`: the from-scratch KiCad schematic, drawn in KiCad: kicad-cli ERC with no errors, every BOM reference on the sheet, every part from the project's PCM library (PCM_<lib>). Records the schematic for the netlist check that follows the board.@@ -2834,7 +2841,8 @@ fn latest_shot(dir: &Path, step: &str) -> Option<String> { /// molecule-publish --result <page>`); None for a plain board or once it is recorded. fn molecule_publish_hint(r: &Run) -> Option<String> { if !molecule_pins::wants_molecule(&spec_soft(r), &requirements_of(r)) || molecule_published(&r.data) { return None; }- Some("NEXT (molecule): publish it with molecule-publish, a separate package (`adom-wiki pkg install adom/molecule-publish`; skill molecule-publish). Its bundle is the STEP, the board, every schematic sheet, `<slug>-fab.zip` and `export.json` (both made with molecule-publish's scripts/fab_bundle.py create from the same saved board as the Gerbers `adom-aiflow export` wrote); check names first with its scripts/pin_names.py. Put the design review in the package too: `adom-aiflow project-page --results --out <package folder>` writes design-review/ (Fields numbers, analysis figures, contact table, parts table; issue #164) for it to carry and the README to link. The page is kind molecule: never push a GLB or footprint/symbol JSON and never bind component.parts.model_3d there; the wiki's model registry builds the model, footprint and symbol, and the publish is proven by `adom-wiki model status` showing the model built by the pipeline with metadataComplete true. Then record it: `adom-aiflow stage end molecule-publish --result <owner/slug>` (skill aiflow-molecule, section 5).".into())+ let page = if r.data["outcomes"]["page-build"].is_object() { "" } else { "Build its page into molecule-publish's Stage 2 package folder first: `adom-aiflow project-page --molecule-bundle <folder>` (readme.html with the board and contacts, the circuit explorer, the simulation and the components; docs/; package.json readme_order [\"html\"]), then `project-page check`. " };+ Some(format!("NEXT (molecule): {page}publish it with molecule-publish, a separate package (`adom-wiki pkg install adom/molecule-publish`; skill molecule-publish). Its bundle is the STEP, the board, every schematic sheet, `<slug>-fab.zip` and `export.json` (both made with molecule-publish's scripts/fab_bundle.py create from the same saved board as the Gerbers `adom-aiflow export` wrote); check names first with its scripts/pin_names.py. Put the design review in the package too: `adom-aiflow project-page --results --out <package folder>` writes design-review/ (Fields numbers, analysis figures, contact table, parts table; issue #164) for it to carry and the README to link. The page is kind molecule: never push a GLB or footprint/symbol JSON and never bind component.parts.model_3d there; the wiki's model registry builds the model, footprint and symbol, and the publish is proven by `adom-wiki model status` showing the model built by the pipeline with metadataComplete true. Then record it: `adom-aiflow stage end molecule-publish --result <owner/slug>` (skill aiflow-molecule, section 5).")) } /// Issue #137: what a molecule's project page is for (kind molecule) and what never goes on it.@@ -2884,6 +2892,151 @@ fn page_results_cmd(r: &mut Run, dir: &Path, page: &str, out: Option<&str>, page ok(&format!("design review written for {} ({}): {} file(s) under {}\n {}", Path::new(&board_path).file_name().and_then(|n| n.to_str()).unwrap_or(""), if built.sections.is_empty() { "no sections with data yet".to_string() } else { built.sections.join(", ") }, built.files.len(), root.display(), built.files.join("\n ")), &hints); } +/// The page build's options from the command line (`project-page --molecule-bundle <folder>` and `project-page check`).+struct PageOpts { page: Option<String>, bundle: Option<String>, title: Option<String>, brief: Option<String>, netlist: Option<String>, explorer: Option<String>, bom: Option<String>, sweeps: Vec<String>, offline: bool }++/// The design netlist with blocks (aiflow-schematic-to-board's netlist.json): the flag, else netlist.json beside+/// the BOM, under design/ beside the spec or requirements, or in the run's project folder.+fn design_netlist(r: &Run, flag: Option<&str>) -> Option<String> {+ if let Some(f) = flag { return Some(abs_path(f)); }+ let mut c: Vec<PathBuf> = Vec::new();+ for b in [r.data["outcomes"]["sourcing"]["bom"].as_str(), r.data["outcomes"]["parts"]["bom"].as_str()].into_iter().flatten() {+ if let Some(d) = Path::new(b).parent() { c.push(d.join("netlist.json")); }+ }+ for f in [r.data["spec"].as_str(), r.data["requirements"].as_str()].into_iter().flatten() {+ if let Some(d) = Path::new(f).parent() { c.push(d.join("design/netlist.json")); if let Some(u) = d.parent() { c.push(u.join("design/netlist.json")); } }+ }+ c.push(r.dir.join("../../design/netlist.json"));+ c.into_iter().find(|p| std::fs::read_to_string(p).ok().and_then(|t| serde_json::from_str::<Value>(&t).ok()).is_some_and(|v| v["components"].is_array()))+ .map(|p| std::fs::canonicalize(&p).unwrap_or(p).display().to_string())+}++fn abs_path(p: &str) -> String {+ let pb = PathBuf::from(p);+ let pb = if pb.is_absolute() { pb } else { std::env::current_dir().map(|d| d.join(&pb)).unwrap_or(pb) };+ std::fs::canonicalize(&pb).unwrap_or(pb).display().to_string()+}++/// The page builder: tools/page-build.py with the explorer's symbols, script and style in front of it.+fn run_page_build(cfg: &Value, dir: &Path) -> Value {+ let assets = json!({"symbols": include_str!("../../../tools/page-explorer/symbols.json"), "js": include_str!("../../../tools/page-explorer/explorer.js"), "css": include_str!("../../../tools/page-explorer/explorer.css")});+ let script = format!("PAGE_ASSETS = {}\n{}", serde_json::to_string(&assets).unwrap(), include_str!("../../../tools/page-build.py"));+ let cfgp = dir.join("project-page").join(format!("page-{}.json", cfg["mode"].as_str().unwrap_or("build")));+ let _ = std::fs::create_dir_all(cfgp.parent().unwrap());+ if let Err(e) = std::fs::write(&cfgp, serde_json::to_string_pretty(cfg).unwrap()) { return json!({"ok": false, "error": format!("{}: {e}", cfgp.display())}); }+ // written beside the config and run as a file: the script with its assets is longer than one argument may be+ let sp = dir.join("project-page").join("page-build.py");+ if let Err(e) = std::fs::write(&sp, &script) { return json!({"ok": false, "error": format!("{}: {e}", sp.display())}); }+ match std::process::Command::new(aiflow_python()).arg(&sp).arg(&cfgp).stdin(std::process::Stdio::null()).output() {+ Err(e) => json!({"ok": false, "error": format!("python3: {e}")}),+ Ok(o) => serde_json::from_slice(&o.stdout).unwrap_or_else(|_| json!({"ok": false, "error": aiflow_run::clip_text(&format!("{}{}", String::from_utf8_lossy(&o.stdout), String::from_utf8_lossy(&o.stderr)), 900)})),+ }+}++/// The config the page builder reads: the run, the folder, the page and every input it shows.+fn page_cfg(r: &Run, dir: &Path, mode: &str, o: &PageOpts) -> Value {+ let (spec, req) = (spec_soft(r), requirements_of(r));+ let rec = &r.data["outcomes"]["page-build"];+ let bundle = o.bundle.as_deref().map(abs_path).or_else(|| rec["bundle"].as_str().map(str::to_string));+ let page = o.page.clone().or_else(|| page_results::board_page(&r.data).map(|b| b.0)).or_else(|| rec["page"].as_str().map(str::to_string));+ // the build's own netlist first (a later build or check reads what the page was drawn from), then the default+ let netlist = o.netlist.as_deref().map(abs_path).or_else(|| rec["netlist"].as_str().map(str::to_string)).or_else(|| design_netlist(r, None));+ let explorer = o.explorer.as_deref().map(abs_path).or_else(|| rec["explorerDir"].as_str().map(str::to_string))+ .or_else(|| netlist.as_deref().and_then(|n| Path::new(n).parent().map(|d| d.join("explorer").display().to_string())))+ .unwrap_or_else(|| dir.join("explorer").display().to_string());+ let bom = o.bom.as_deref().map(abs_path).or_else(|| run_bom(r));+ let pkg: Value = bundle.as_deref().and_then(|b| std::fs::read_to_string(Path::new(b).join("package.json")).ok()).and_then(|t| serde_json::from_str(&t).ok()).unwrap_or(Value::Null);+ let title = o.title.clone().or_else(|| req["title"].as_str().map(str::to_string)).or_else(|| spec["title"].as_str().map(str::to_string)).or_else(|| pkg["title"].as_str().map(str::to_string)).unwrap_or_else(|| sequence::label(dir, &r.data));+ let brief = o.brief.as_deref().map(preboard::brief_text).or_else(|| pkg["description"].as_str().map(str::to_string)).or_else(|| req["summary"].as_str().or(req["description"].as_str()).map(str::to_string)).unwrap_or_default();+ let report = pagedir::run_page(&r.data).map(|(pg, d)| format!("https://wiki.adom.inc/{pg}/files/{}/README.md", pagedir::run_rel(d.as_deref(), &report_id(r))));+ let page_dir = if o.page.is_some() && o.page.as_deref() != r.data["projectPage"].as_str() { Value::Null } else { r.data["projectPageDir"].clone() };+ json!({"mode": mode, "run": dir.display().to_string(), "bundle": bundle, "page": page, "pageDir": page_dir, "title": title, "brief": brief,+ "molecule": molecule_pins::wants_molecule(&spec, &req), "spec": r.data["spec"], "requirements": r.data["requirements"], "board": r.current_board(),+ "netlist": netlist, "schematic": r.data["schematic"], "explorer": explorer, "bom": bom, "sweeps": o.sweeps.iter().map(|s| abs_path(s)).collect::<Vec<_>>(),+ "offline": o.offline, "runReport": report, "now": now(), "version": env!("CARGO_PKG_VERSION")})+}++/// `project-page --molecule-bundle <folder>` (build) and `project-page check` (issues #131, #164, #197, #198, #200).+fn page_command(r: &mut Run, dir: &Path, mode: &str, o: &PageOpts) {+ let cfg = page_cfg(r, dir, mode, o);+ if cfg["bundle"].is_null() {+ err("no page folder: `project-page --molecule-bundle <folder>` builds the page into the folder it is published from (molecule-publish's Stage 2 package folder for a molecule), and `project-page check` then checks it", &["Skill aiflow-project-page, section \"The page build\".".into()]);+ }+ let v = run_page_build(&cfg, dir);+ if v["ok"] != true {+ err(&format!("project page {mode}: {}", v["error"].as_str().unwrap_or("failed")), &["Read the error: a missing netlist (--netlist), a folder that is not there, or a tool the builder needs (kicad-cli via ADOM_AIFLOW_KICAD_CLI for the board pictures; python3 with Pillow and matplotlib for the figures).".into()]);+ }+ let strs = |x: &Value| -> Vec<String> { x.as_array().into_iter().flatten().filter_map(|s| s.as_str().map(str::to_string)).collect() };+ if mode == "check" {+ r.outcome("page-check", json!({"at": now(), "bundle": cfg["bundle"], "passed": v["passed"], "errors": v["errors"], "warnings": v["warnings"]}));+ r.save().unwrap_or_else(|e| err(&e, &[]));+ let warns: Vec<String> = strs(&v["warnings"]).into_iter().map(|s| format!("note: {s}")).collect();+ let ex = &v["explorer"];+ let line = format!("{} figure(s), {} BOM line(s), explorer {}% coverage, {} netlist difference(s) ({} drawn by hand, {} auto-drawn)", v["figures"], v["bomLines"], ex["coverage"], ex["diffs"], ex["hand"], ex["auto"]);+ let folder = cfg["bundle"].as_str().unwrap_or("<folder>");+ if v["passed"] == true {+ ok(&format!("project page check passed for {folder}: every section present, {line}"), &warns);+ return;+ }+ let errs = strs(&v["errors"]);+ findings(&format!("project page check: {} finding(s) in {folder} ({line}):\n {}", errs.len(), errs.join("\n ")),+ &[warns, vec![format!("Fix what each line says, then `project-page --molecule-bundle {folder}` and `project-page check` again (skill aiflow-project-page). finish lists these as open items; one you accept on purpose is `deviate \"circuit explorer\" --why ...` (or \"project page\").")]].concat());+ }+ let bundle = v["bundle"].as_str().unwrap_or("").to_string();+ r.outcome("page-build", json!({"at": now(), "bundle": bundle, "page": cfg["page"], "readme": v["readme"], "preview": v["preview"], "sections": v["sections"], "boardFingerprint": v["boardFingerprint"], "boardSha256": v["simulation"]["boardSha256"],+ "explorer": v["explorer"], "explorerDir": cfg["explorer"], "netlist": cfg["netlist"], "figures": v["figures"], "bomLines": v["bomLines"], "priced": v["priced"], "check": v["check"]}));+ r.save().unwrap_or_else(|e| err(&e, &[]));+ let ex = &v["explorer"];+ let mut hints: Vec<String> = strs(&v["notes"]).into_iter().map(|s| format!("note: {s}")).collect();+ let auto = strs(&v["autoBlocks"]);+ if !auto.is_empty() {+ hints.push(format!("{} block(s) are auto-drawn (every pin labelled with its net, no wires): {}. Draw each the textbook way as {}/<id>.json with \"block\": \"<block>\" (signal left to right, supplies up, ground down; start from auto/<block>.json), give each block a title and two sentences in blocks.json, then build again: the netlist check proves every drawing. Until then finish lists the explorer as an open item (skill aiflow-project-page, Circuit explorer).",+ auto.len(), auto.join(", "), cfg["explorer"].as_str().unwrap_or("explorer")));+ }+ if v["priced"].as_u64() == Some(0) && v["bomLines"].as_u64().unwrap_or(0) > 0 {+ hints.push(format!("No prices: the BOM ({}) has no unit price column and the sourcing check recorded none, so the page shows none and no board total. Add a unit_price column from a parts search (adom-parts-search) and build again; never type in a price you did not look up.", cfg["bom"].as_str().unwrap_or("?")));+ }+ let chk = &v["check"];+ if chk["passed"] != true { for e in strs(&chk["errors"]) { hints.push(format!("page check: {e}")); } }+ for w in strs(&chk["warnings"]) { hints.push(format!("page check note: {w}")); }+ if !Path::new(&bundle).join(page_results::FOLDER).join("README.md").is_file() {+ hints.push(format!("The Markdown design review (for README.md and search): `project-page --results --out {bundle}` writes {}/ there; build the page again and it links it.", page_results::FOLDER));+ }+ hints.push(format!("Look at it before you publish: {} (the page with local file links; on the wiki the same page links the published docs/).", v["preview"].as_str().unwrap_or("")));+ hints.push(if cfg["molecule"] == true {+ "Next (molecule): molecule-publish Stage 3 from this folder; readme.html, docs/ and package.json readme_order [\"html\"] ride along. Then `stage end molecule-publish --result <owner/slug>`; finish and deliver check this folder again.".into()+ } else { "Next: publish the folder to the board's page (adom-wiki pkg publish, or repo push of readme.html, README.md and docs/), with readme_order [\"html\"] in the page fields; finish and deliver check this folder again.".into() });+ let sections = strs(&v["sections"]);+ ok(&format!("page built in {bundle}: readme.html with {} sections ({}); explorer {} of {} parts drawn ({} by hand, {} auto-drawn), {} netlist difference(s); {} figure(s); {} BOM line(s), {} priced, pictures {} from wiki heroes, {} from 3D thumbnails, {} placeholders; page check {}",+ sections.len(), sections.join(", "), ex["parts"], ex["required"], ex["hand"], ex["auto"], ex["diffs"], v["figures"].as_array().map(|a| a.len()).unwrap_or(0), v["bomLines"], v["priced"],+ v["images"]["wiki"], v["images"]["thumbnail"], v["images"]["none"], if chk["passed"] == true { "passed".to_string() } else { format!("{} finding(s), listed below", chk["errors"].as_array().map(|a| a.len()).unwrap_or(0)) }), &hints);+}++/// finish and deliver: the built page's check as open-item lines (None when no page was built). An explorer+/// finding keeps its own name ("circuit explorer: ...") so `deviate "circuit explorer"` answers it; the rest+/// are "project page: ...".+fn page_check_lines(r: &Run, dir: &Path) -> Option<Vec<String>> {+ if !r.data["outcomes"]["page-build"].is_object() { return None; }+ let o = PageOpts { page: None, bundle: None, title: None, brief: None, netlist: None, explorer: None, bom: None, sweeps: vec![], offline: true };+ let v = run_page_build(&page_cfg(r, dir, "check", &o), dir);+ if v["ok"] != true { return Some(vec![format!("project page: the check did not run ({})", v["error"].as_str().unwrap_or("?"))]); }+ Some(v["errors"].as_array().into_iter().flatten().filter_map(|x| x.as_str()).map(page_line).collect())+}++fn page_line(s: &str) -> String {+ if s.starts_with("circuit explorer:") { s.to_string() } else { format!("project page: {s}") }+}++/// Issues #131, #164: after export, a run with a board page (or a molecule) whose page was never built: how to+/// build it, with the circuit explorer. A suggestion; empty otherwise.+fn page_build_hint(r: &Run) -> String {+ if r.data["outcomes"]["page-build"].is_object() || r.outcomes().get("export").is_none() { return String::new(); }+ let mol = molecule_pins::wants_molecule(&spec_soft(r), &requirements_of(r));+ if !mol && page_results::board_page(&r.data).is_none() { return String::new(); }+ format!("Suggested: build the page itself with the circuit explorer (the interactive schematic: a block flowchart, each block drawn the textbook way and checked against the netlist): `adom-aiflow project-page --molecule-bundle <{}>`, then `project-page check` (skill aiflow-project-page, The page build).",+ if mol { "molecule-publish package folder" } else { "the folder the page is published from" })+}+ /// The give-back hint: what the AI learned belongs to every Adom user. /// Colby (2026-11-11): at the end of a run, offer the human a tailored experience: their own skill or flow app, /// published on the wiki, that makes AI Flow work their way. An offer, once; never instead of giving a fix back.@@ -4849,11 +5002,18 @@ fn main() { } ok(&format!("assessment recorded for {} part(s) ({path}):\n{}", parts.len(), lines.join("\n")), &[hint]); }- Cmd::ProjectPage { page, results, out, sync, create, existing, private, title, brief, replace_readme, no_push, local_only, page_dir } => {+ Cmd::ProjectPage { what, page, results, out, sync, create, existing, private, title, brief, replace_readme, no_push, local_only, page_dir, molecule_bundle, netlist, explorer, bom, sweep, offline } => { let t = thread(&cli); let no_push = &(*no_push || *local_only); let mut r = load_run(&cli); if *results { page_results_cmd(&mut r, &dir, page, out.as_deref(), page_dir.as_deref()); return; }+ // issues #131, #164: the page itself (readme.html with the circuit explorer) built into its folder, and its check+ if what.is_some() || molecule_bundle.is_some() {+ let mode = if what.is_some() { "check" } else { "build" };+ let opts = PageOpts { page: Some(page.clone()).filter(|p| !p.is_empty()), bundle: molecule_bundle.clone(), title: title.clone(), brief: brief.clone(), netlist: netlist.clone(), explorer: explorer.clone(), bom: bom.clone(), sweeps: sweep.clone(), offline: *offline || *local_only };+ page_command(&mut r, &dir, mode, &opts);+ return;+ } if page.is_empty() { err("project-page needs --page <owner>/<slug> (only --results finds the run's page by itself)", &[]); } // a folder of an existing page (issue #85): implies --existing, never creates a page let page_dir_arg = page_dir.clone();@@ -6384,6 +6544,8 @@ fn main() { for f in o.get("part-check").and_then(|p| p["findings"].as_array()).into_iter().flatten().filter_map(Value::as_str) { missing.push(format!("part-check: {f}")); } // issue #199: a board page (or a molecule's) must show this board's design review, not an earlier one's if let Some(item) = page_results::page_item(&r.data, &sha256_file(&r.current_board()), molecule_pins::wants_molecule(&spec_soft(&r), &requirements_of(&r))) { missing.push(item); }+ // issues #164, #197, #200: the built page's check (an auto-drawn explorer block, a section with nothing to show, a part with no BOM row)+ if let Some(lines) = page_check_lines(&r, &dir) { missing.extend(lines); } // issue #193: a part with no page is reported with its requests, its assessment and the next command for m in o.get("parts").and_then(|p| p["missing"].as_array()).into_iter().flatten().filter_map(Value::as_str) { let (tries, a, ch) = (supply::attempts(&r.data, m), supply_assessed(&r, m), r.data["supplyChoices"].get(m).cloned());@@ -6458,7 +6620,7 @@ fn main() { if nothing_to_source { r.data["summary"]["notApplicable"].as_array_mut().unwrap().push(json!("sourcing check: not applicable (no footprint in the BOM)")); } r.log("finish", json!({"minutes": r.elapsed_minutes(), "steps": Value::Object(r.step_report())})); r.save().unwrap();- ok(&(format!("finished: {} from the prompt to a board {}, {:.1} min\npours: {}\n{}{}", r.data["engine"], match (open_items.len(), deviated.len()) { (0, 0) => "passing the configured screens".to_string(), (0, d) => format!("passing the configured screens except {d} recorded deviation(s), listed below"), (o, d) => format!("with {o} open item(s) still worth a look{} (listed above; finish again after any change)", if d > 0 { format!(" and {d} recorded deviation(s)") } else { String::new() }) }, r.elapsed_minutes(), pourverify::mode_label(r.outcomes().get("land-pours").unwrap_or(&Value::Null)), step_table(&r), if lib_parts.is_empty() { String::new() } else { format!("\nparts from a project library (no public component page): {}", lib_parts.join("; ")) }) + &na_text(&r.data["summary"]["notApplicable"]) + &flow_gaps::text(&gaps) + &if reviewed.is_empty() { String::new() } else { format!("\nreviewed exceptions and assumptions:\n {}", reviewed.join("\n ")) } + &if deviated.is_empty() { String::new() } else { format!("\nfinished with {} recorded deviation(s) (checks this board did not meet, accepted on purpose):\n {}", deviated.len(), deviated.iter().map(|d| format!("{}: {} (why: {})", d["item"].as_str().unwrap_or(""), d["line"].as_str().unwrap_or(""), d["why"].as_str().unwrap_or(""))).collect::<Vec<_>>().join("\n ")) } + &if quality_lines.is_empty() { String::new() } else { format!("\n{}", quality_lines.join("\n")) } + "\n" + &verified::message(&checked)), &[flow_gaps::hint(&gaps).unwrap_or_default(), "Tell the human exactly the verified list above; never call the board ready to fabricate unless every item says yes, and even then advise a human review.".into(), "The run is not delivered yet: cut the video, then `adom-aiflow deliver --video <mp4> --message \"<what you tell the human>\"`; the clock stops there, not here.".into(), "Add your token and dollar accounting to run.json under tokens and usd; the manifest is the row on the chart.".into(), results_hint(&r), molecule_publish_hint(&r).unwrap_or_default(), give_back_hint()]);+ ok(&(format!("finished: {} from the prompt to a board {}, {:.1} min\npours: {}\n{}{}", r.data["engine"], match (open_items.len(), deviated.len()) { (0, 0) => "passing the configured screens".to_string(), (0, d) => format!("passing the configured screens except {d} recorded deviation(s), listed below"), (o, d) => format!("with {o} open item(s) still worth a look{} (listed above; finish again after any change)", if d > 0 { format!(" and {d} recorded deviation(s)") } else { String::new() }) }, r.elapsed_minutes(), pourverify::mode_label(r.outcomes().get("land-pours").unwrap_or(&Value::Null)), step_table(&r), if lib_parts.is_empty() { String::new() } else { format!("\nparts from a project library (no public component page): {}", lib_parts.join("; ")) }) + &na_text(&r.data["summary"]["notApplicable"]) + &flow_gaps::text(&gaps) + &if reviewed.is_empty() { String::new() } else { format!("\nreviewed exceptions and assumptions:\n {}", reviewed.join("\n ")) } + &if deviated.is_empty() { String::new() } else { format!("\nfinished with {} recorded deviation(s) (checks this board did not meet, accepted on purpose):\n {}", deviated.len(), deviated.iter().map(|d| format!("{}: {} (why: {})", d["item"].as_str().unwrap_or(""), d["line"].as_str().unwrap_or(""), d["why"].as_str().unwrap_or(""))).collect::<Vec<_>>().join("\n ")) } + &if quality_lines.is_empty() { String::new() } else { format!("\n{}", quality_lines.join("\n")) } + "\n" + &verified::message(&checked)), &[flow_gaps::hint(&gaps).unwrap_or_default(), "Tell the human exactly the verified list above; never call the board ready to fabricate unless every item says yes, and even then advise a human review.".into(), "The run is not delivered yet: cut the video, then `adom-aiflow deliver --video <mp4> --message \"<what you tell the human>\"`; the clock stops there, not here.".into(), "Add your token and dollar accounting to run.json under tokens and usd; the manifest is the row on the chart.".into(), results_hint(&r), page_build_hint(&r), molecule_publish_hint(&r).unwrap_or_default(), give_back_hint()]); } Cmd::Capture { action, label, reason, off_page } => { let mut r = load_run(&cli);@@ -8299,6 +8461,10 @@ fn main() { media_drain(&mut r); // issue #199: say it when the page would go out with another board's design review if let Some(item) = page_results::page_item(&r.data, &sha256_file(&r.current_board()), molecule_pins::wants_molecule(&spec_soft(&r), &requirements_of(&r))) { note(&item, &["Delivering anyway is your call; tell the human the page does not show this board's results yet.".into()]); }+ // issues #164, #197: the built page is checked at delivery too (a note, never a stop)+ if let Some(l) = page_check_lines(&r, &run_dir(&cli)).filter(|l| !l.is_empty()) {+ note(&format!("the board's page has {} finding(s):\n {}", l.len(), l.join("\n ")), &["Fix them, `project-page --molecule-bundle <folder>` and `project-page check`, publish again, and tell the human what is still open.".into()]);+ } if let Some(target) = r.data["target"].as_str().map(str::to_string) { let (pulled, missing) = repull_failed_clips(&mut r, &Bridge { ai_thread: thread(&cli), target }, &dir); if pulled + missing > 0 { eprintln!("pulled {pulled} clip(s) that had not reached the run; {missing} still missing"); r.save().unwrap(); }
install.sh+2@@ -18,6 +18,8 @@ ln -sf "$HERE/tools/silkscreen-dashboard/server.py" "$HOME/.local/bin/adom-aiflo AIFLOW_PY_ENV="$HOME/.local/share/adom-aiflow/python" python3 -m venv --without-pip "$AIFLOW_PY_ENV" python3 -m pip --python "$AIFLOW_PY_ENV/bin/python3" install --disable-pip-version-check -r "$HERE/tools/requirements-silkscreen.txt"+# the project page build (project-page --molecule-bundle): board pictures, figures and part pictures+python3 -m pip --python "$AIFLOW_PY_ENV/bin/python3" install --disable-pip-version-check -r "$HERE/tools/requirements-page.txt" for helper in aiflow-widget library-tour; do chmod +x "$HERE/tools/$helper.py" done
skills/adom-aiflow/SKILL.md+2@@ -686,6 +686,8 @@ For a part cooled directly through its case and heatsink, read `docs/package-coo ## Project wiki presentation before delivery +**The page build, for every board after export (issues #131, #164).** `project-page --molecule-bundle <folder>` builds the page people read into the folder it is published from (molecule-publish's Stage 2 package folder for a molecule): readme.html with the board's pictures and contacts, the circuit explorer (a block flowchart from the netlist's `block` field; click a block for its circuit, drawn by you as a small JSON per block in `explorer/`, every drawing checked against the netlist), the simulation, the components (picture, MPN, maker, prices and buy links, board total), manufacturing and the open items. `project-page check` checks it; `finish` lists its findings as open items (an auto-drawn explorer block is one, under "circuit explorer") and `deliver` notes them. Skill aiflow-project-page, "The page build".+ Read `skills/aiflow-project-page/SKILL.md` and run `adom-aiflow project-page-check --project <root>` before delivering a wiki-backed project. Explicitly bind the assembled board hero and project datasheet, include 5–8 reviewed README screenshots, place the datasheet below the README and verify the actual published page. Automatic asset discovery and upload success are not acceptance. ### Board-edge connectors
skills/aiflow-molecule/SKILL.md+1−1@@ -133,7 +133,7 @@ Gate on the printed stats before publishing: The published board GLB is always the `--out` of `board-glb copper`, never the raw `step2glb convert` output. If `board-glb copper` refuses (quantized GLBs from step2glb are read as of 0.1.92), fix the cause and run it again; never publish the raw GLB to get past the gate. -The GLB above is for your own review and the run's pictures; it never goes on the molecule's page. Publish with molecule-publish 3.x, a separate package (`adom-wiki pkg install adom/molecule-publish`; it is a dependency of adom-aiflow). Its bundle is what the wiki's model registry builds from: the STEP, the board (`.kicad_pcb`), every schematic sheet (with the `.kicad_pro` and any project `.kicad_sym` / `.pretty` and `3d/` models, carried for APM), `<slug>-fab.zip` and `export.json`. Make the last two with its `scripts/fab_bundle.py create <folder> --slug <slug> --fab <a folder with only the Gerber and drill files> --tool kicad --tool-version <v> --exporter adom-aiflow --exporter-version <v> --source step=<slug>.step --source board_kicad_pcb=<design>.kicad_pcb`, from the same saved board as the Gerbers (`adom-aiflow export`), then run its Stage 1 checks (`bundle_check.py`, `pin_names.py check`, `fab_bundle.py check`). Never put a GLB, `*_footprint.json` or `*_symbol.json` in the bundle or bind `component.parts.model_3d`: the registry builds the model, footprint and symbol and refuses a pushed one (`REGISTRY_MODEL_FILE_REFUSED`). The page is kind `molecule` (`project-page` creates it so when the spec has `molecule`, or before `start` when requirements.json says `formFactor.kind: "molecule"` or names a MachinePin in `formFactor.pin`). Before Stage 3, put the design review in the package: `adom-aiflow project-page --results --out <package folder>` writes `design-review/` (Fields current and thermal numbers, your analysis figures, the contact table, the parts table with prices) for the package to carry; link it from the package README. The publish is proven by `adom-wiki model status` showing the model built by the pipeline with `metadataComplete: true`; record it with `adom-aiflow stage end molecule-publish --result <owner/slug>` (`export`, `finish`, `deliver` and `finish-guard` suggest it until then). Publishing is its own reviewed step: check the payload for anything confidential first, and say "the 3rd party fab" wherever the fab is named.+The GLB above is for your own review and the run's pictures; it never goes on the molecule's page. Publish with molecule-publish 3.x, a separate package (`adom-wiki pkg install adom/molecule-publish`; it is a dependency of adom-aiflow). Its bundle is what the wiki's model registry builds from: the STEP, the board (`.kicad_pcb`), every schematic sheet (with the `.kicad_pro` and any project `.kicad_sym` / `.pretty` and `3d/` models, carried for APM), `<slug>-fab.zip` and `export.json`. Make the last two with its `scripts/fab_bundle.py create <folder> --slug <slug> --fab <a folder with only the Gerber and drill files> --tool kicad --tool-version <v> --exporter adom-aiflow --exporter-version <v> --source step=<slug>.step --source board_kicad_pcb=<design>.kicad_pcb`, from the same saved board as the Gerbers (`adom-aiflow export`), then run its Stage 1 checks (`bundle_check.py`, `pin_names.py check`, `fab_bundle.py check`). Never put a GLB, `*_footprint.json` or `*_symbol.json` in the bundle or bind `component.parts.model_3d`: the registry builds the model, footprint and symbol and refuses a pushed one (`REGISTRY_MODEL_FILE_REFUSED`). The page is kind `molecule` (`project-page` creates it so when the spec has `molecule`, or before `start` when requirements.json says `formFactor.kind: "molecule"` or names a MachinePin in `formFactor.pin`). Before Stage 3, put the design review in the package: `adom-aiflow project-page --results --out <package folder>` writes `design-review/` (Fields current and thermal numbers, your analysis figures, the contact table, the parts table with prices) for the package to carry; link it from the package README. The publish is proven by `adom-wiki model status` showing the model built by the pipeline with `metadataComplete: true`; record it with `adom-aiflow stage end molecule-publish --result <owner/slug>` (`export`, `finish`, `deliver` and `finish-guard` suggest it until then). Publishing is its own reviewed step: check the payload for anything confidential first, and say "the 3rd party fab" wherever the fab is named. Before Stage 3, build the page into the package folder: `adom-aiflow project-page --molecule-bundle <package folder>` writes readme.html (board, contacts, circuit explorer, simulation, components) and docs/, and sets readme_order ["html"]; `project-page check` checks it (skill aiflow-project-page, "The page build"). ## Pads are real copper (John's rule)
skills/aiflow-project-page/SKILL.md+63−2@@ -1,13 +1,13 @@ --- name: aiflow-project-page-description: Publish and review a great AIFlow board project wiki page with an explicit assembled-board hero GLB, 5–8 meaningful screenshots, a real project datasheet at the bottom and verified live asset bindings (a molecule page gets no pushed GLB: the wiki registry builds its model). Use before final delivery or when a chip or blank datasheet appears on a board page.+description: Publish and review a great AIFlow board project wiki page with an explicit assembled-board hero GLB, 5–8 meaningful screenshots, a real project datasheet at the bottom and verified live asset bindings (a molecule page gets no pushed GLB: the wiki registry builds its model). After export, build every board's page with `project-page --molecule-bundle <folder>` (readme.html: board pictures and contacts, the netlist-checked circuit explorer, the simulation, the components with pictures, prices and buy links, manufacturing, open items) and check it with `project-page check`. Use before final delivery, when drawing the circuit explorer (the interactive schematic), or when a chip or blank datasheet appears on a board page. user-invocable: true --- # Deliver the project page ## Design review: `project-page --results` -Analysis results belong on the page people read, not only on the run report. After `analyze current`, `analyze thermal` or `tour fields` (they say so when the page's review is missing or older than the board, and `finish` says it again), run `adom-aiflow project-page --results`: it writes `design-review/README.md` for the current board (Fields current and thermal tables, the screens' verdicts, your `artifact --kind analysis-image` figures, a molecule's contact table, and the parts table with unit and line prices and buy links when the BOM has those columns) under `<run>/page-results/`, records which board it describes, and prints the `adom-wiki repo push`. Link it from the README as a sub-README card. For a molecule, `--out <molecule-publish package folder>` writes it into the package instead. Still by hand: chip images on the parts table and the interactive schematic (circuit explorer); the command lists them as open.+Analysis results belong on the page people read, not only on the run report. After `analyze current`, `analyze thermal` or `tour fields` (they say so when the page's review is missing or older than the board, and `finish` says it again), run `adom-aiflow project-page --results`: it writes `design-review/README.md` for the current board (Fields current and thermal tables, the screens' verdicts, your `artifact --kind analysis-image` figures, a molecule's contact table, and the parts table with unit and line prices and buy links when the BOM has those columns) under `<run>/page-results/`, records which board it describes, and prints the `adom-wiki repo push`. Link it from the README as a sub-README card. For a molecule, `--out <molecule-publish package folder>` writes it into the package instead. The interactive schematic (the circuit explorer) and the parts table with chip pictures are the page build below (`project-page --molecule-bundle`); its page links `design-review/` when the folder has one. ## Revision 1: `project-page` @@ -41,3 +41,64 @@ A board page (or a molecule's) must carry this board's design review: when the r What a page says about fabrication readiness comes from the run's `summary.verified` (issue #192): it always holds the newest check (`checkedBy` is finish, export or deliver, with `at`), `lines` reads each item as people should see it ("fills in Gerbers not known (not exported yet)"), and `verdict` is written for readers. Never publish an older snapshot after a later check, never print a raw state object, and never put an instruction meant for the AI on a page. Build or refresh the page after `export` (and after `deliver`), so it shows that check. Call this preflight and review before final delivery whenever the run publishes a project page. It supplements, never replaces, electrical, thermal, mechanical, fabrication or simulation gates. A draft may be published with explicit limitations; do not claim final delivery while page acceptance remains open.++## The page build: every board, after export (issues #131, #164, #197, #198, #200)++Revision 1 is a parts list, and `--results` is the Markdown design review. The page people read is built after export, for every board, molecule or not:++```+adom-aiflow project-page --molecule-bundle <folder> [--page <owner/slug>] [--netlist design/netlist.json] [--explorer design/explorer] [--bom design/bom.csv] [--sweep rating/sweep.json ...] [--offline]+adom-aiflow project-page check [--molecule-bundle <folder>]+```++`--molecule-bundle` (alias `--bundle`) is the folder the page is published from: molecule-publish's Stage 2 package folder for a molecule, any folder for a board page. The build writes into it:++- `readme.html`: a dark, self-contained page (the wiki's sandboxed frame; it posts `readme-height`), sections in this order, each `data-aiflow-section`:+ - **The board**: top and bottom pictures from kicad-cli's per-layer SVGs (`pcb export svg`, composed with cairosvg and Pillow: mask over copper, exposed pads gold, silkscreen white), and a facts table.+ - **Contacts** (when the board has MP<n> / MC<n>): net, class (large or medium, from the footprint), wire (14 AWG large, 24 AWG medium), position from MP1, use (the netlist note).+ - **Circuit explorer**: the `<aiflow-explorer>` web component, with the proof tags (parts drawn, pins drawn, netlist differences, hand-drawn against auto-drawn blocks).+ - **Simulation**: the Fields solve (copper loss, heat from the parts, worst A/mm² and where, peak rise in still and moving air against the budget, the `analyze current` and `analyze thermal` verdicts), the hottest parts, the worst necks, any rating sweep (the current at the rise budget, interpolated), the figures, layout revisions side by side once the run has solved more than one board, a link to `design-review/` when the folder has one, and a link to the run report.+ - **Components**: one row per BOM line with an MPN: the part's picture (its wiki page hero, cropped to the part; else a step2glb thumbnail of its STEP in the folder's 3d/; else a placeholder), MPN linked to its wiki page, maker, qty, refs, value, role, unit and line price, stock with its check date, a Mouser search by MPN, and the board total. Prices come only from a BOM price column (`unit_price`, `price`, ...) or the sourcing outcome; with none the page says so and shows no total. Never type in a price you did not look up.+ - **Manufacturing**: the files of export.json, the folder's CSVs, finish's verified list, and the fab notes (FAB-NOTES.md from the export).+ - **Open items**: finish's open items and deviations, plus the page's own (auto-drawn blocks, too many blocks, missing prices).+- `docs/`: `board/`, `review/`, `parts/`, `explorer/` (design.json, blocks.json and every drawing the page shows), `explorer-proof.json`, `figures.json` (each figure with the board fingerprint it shows), `bom.json`, `page-build.json`.+- `package.json` gets `readme_order: ["html"]` (the publish merges it into page.json). An existing README.md is left as it is; a missing one is written (search and excerpts read it). For the Markdown design review run `project-page --results --out <same folder>` and build again: the page then links it.++The build prints what it made and the check. Look at `<run>/project-page/preview/readme.html` (the same page with local file links) in a browser before publishing. Then a molecule goes to molecule-publish Stage 3 from that folder; a board page is published from it.++**`project-page check`** (also run by `finish`, as open items, and `deliver`, as a note, once a page was built; after export, `finish` suggests the build for a molecule or a run with a page that has none): every section present and filled, every figure made from the folder's board (the fingerprint in `docs/figures.json` against the board file now: sha256 with 3D model paths and Fab text left out, so molecule-publish's `3d/` rewrite and `silkscreen fab-tidy` keep it), the explorer proof recomputed from `docs/explorer/` (coverage 100 %, 0 netlist differences, the netlist unchanged since), a BOM row for every part with an MPN (a test pad, machine pin or contact the BOM lists as a board feature, with no part number, counts as listed: #200), `readme_order` `["html"]`, README.md present, no em-dash. Findings, never a stop:++- **An auto-drawn block is a finding (#197).** It passes the netlist check by construction (every pin labelled with its net) but is not readable as a circuit, so `finish` lists it as `circuit explorer: N of M block(s) auto-drawn ...` until you draw it, or record `deviate "circuit explorer" --why "..."` when an auto-drawn block is right on purpose. Other page findings are `project page: ...`.+- **Too many blocks is a warning (#198).** Past 15 blocks the flowchart stops being readable (aim for 6 to 15). Merge blocks in netlist.json's `block` field; a multi-channel board (four motor phases, five LED channels) gets one block per channel, with its functions as that block's drawings, which the explorer shows as tabs. A replicated channel can map one hand drawing onto the others by renaming references.++### Circuit explorer: blocks, drawings and the netlist check++Blocks are the netlist's `block` field (design/netlist.json, aiflow-schematic-to-board); without one, the board's sheets or reference hundreds. Signals between blocks are the nets that span blocks (ground nets left out), as arrows from the block with the driving pin (the schematic's pin types: power_out and output drive; a bidirectional pin drives only inputs; a contacts block drives what an input reads and a supply). Supplies run along the top, the signal chain below left to right, a contacts block that also receives nets is drawn again on the right as outputs. A click on a block shows its circuit; hovering a wire lights its net; a label jumps to the other block with that net.++The source folder (`--explorer`, default `explorer/` beside the netlist) holds:++- `blocks.json` (written once as a scaffold): `{"blocks": {"<block>": {"title": "...", "text": "one or two sentences"}}, "flow": {"nodes": {"<block>": [x, y]}, "edges": [{"from", "to", "label"}]}, "symbols": {"<ref, MPN or netlist part>": {"sym": "NMOS", "map": {"g": ["4"], "d": ["5"], "s": ["1", "2", "3"]}} | {"box": {...}}}}`.+- `<id>.json`, one per drawing, drawn by you, textbook style: signal left to right, supplies up, ground down, a half bridge as two stacked FETs with the phase node between them, a divider vertical, wires inside a block and labels only between blocks. Several drawings may share one block (they show as tabs); a block with a hand drawing must draw all its parts.+- `auto/<block>.json`: the fallback the build writes for every block with no drawing (each part with its symbol, each pin labelled with its net: correct by construction, not readable as a circuit). Start a drawing from it; never edit auto/ (it is rewritten).++A drawing (the AM/FM, motion-control and AM32 explorers' format, in JSON):++```json+{"block": "gvdd", "title": "10 V gate-drive supply", "text": "How it works, in two sentences.", "w": 680, "h": 270,+ "parts": [["U101", 310, 140, "", {"box": {"w": 120, "h": 80, "title": ["U101", "TPS7A4101"],+ "pins": [["IN", "L", 20, ["8"]], ["EN", "L", 60, ["5"]], ["OUT", "R", 20, ["1"]], ["FB", "R", 60, ["2"]], ["GND", "B", 60, ["4", "9"]]]}}],+ ["R101", 460, 150, "r90 ll"], ["C103", 160, 150, "r90 ll"]],+ "wires": [[[100, 120], "U101.IN"], ["C103.1", [160, 120]], ["U101.FB", [420, 160], "vh", [420, 180], [460, 180]]],+ "gnd": [["C103.2", "down", "RTN"], "U101.GND"],+ "rails": [["R101.1", "+10V", "up"]],+ "flags": [[[100, 120], "VBAT", "left"]],+ "notes": [[590, 230, "GVDD = V(FB) x (1 + R101 / R102)", "middle"]],+ "boxes": [[60, 40, 300, 200, "input filter"]]}+```++- Coordinates in px, y down. A part is `[ref, x, y, options, {object}]`; options: `r90 r180 r270` (clockwise), `mx my` (mirror first), `lt lb ll lr ln` (label top, bottom, left, right, none); the object may give `box` (pins `[name, L|R|T|B, offset, [part pin numbers]]`, `"auto"` for one from the schematic's pins), `sym` and `map`, `text`, `label: [dx, dy, anchor]`.+- Symbols (tools/page-explorer/symbols.json) and their pins: R C CP L FB F NT SW XTAL `1 2`; D DS DZ TVS LED `k a`; NMOS PMOS `g d s`; NPN PNP `b c e`; OPAMP `- + o`; TP MC MCL MP `p`. The symbol and pin map come from the reference letter and the schematic's pin names (G/D/S, B/C/E, K/A); ICs and anything else are boxes from the schematic symbol's pins.+- A wire is a list of pin references (`U101.OUT`) and `[x, y]` points; between two points `hv` (default) or `vh` says which way the corner goes. A point on another wire's segment joins it (a junction dot is drawn).+- `gnd`: `pin` or `[pin, dir, net]` (the net name when the ground is not GND, like RTN or AGND); `rails`: `[pin or point, net, up|down|left|right]`; `flags`: `[pin or point, net, dir]` (labels between blocks); `notes`: `[x, y, text, anchor]`; `boxes`: dashed regions with a title.++The check (in tools/page-build.py; the page only draws what it resolved): every wired group of pins, rails, flags and grounds carries exactly one net, and it is the netlist's (a short, a wrong label or a ground symbol on another net is a difference); no pin with a net left alone, no dangling wire end, no pin without a net wired; one net drawn in two pieces needs a label on each piece; every part of the netlist in some drawing (corner pins with no MPN and only ground are exempt) and every connected pin of a drawn part drawn. The proof is `docs/explorer-proof.json`; `project-page check` recomputes it and needs coverage 100 % and 0 differences. A hand-drawn SVG cannot be checked: draw in this JSON.
tests/page-build-workflow.pyadded+103@@ -0,0 +1,103 @@+"""Issues #164, #131, #197 and #158 through the CLI: `project-page --molecule-bundle <folder>` builds readme.html,+docs/ and readme_order ["html"] into a package folder and records the build; `project-page check` reports what the+page still lacks as findings (an auto-drawn explorer block among them); `project-page --results --out <folder>`+writes design-review/ beside it and the next build links it; `finish` lists the page's findings as open items, the+explorer's under its own name. adom-wiki is a fake on PATH that answers nothing (offline parts pictures). No CAD,+desktop or dashboard.++ python3 tests/page-build-workflow.py <adom-aiflow binary>+"""+import json, os, pathlib, subprocess, sys, tempfile+binary = str(pathlib.Path(sys.argv[1]).resolve())++FAKE_WIKI = '''#!/usr/bin/env python3+import json, os, sys+open(os.environ["FAKE_WIKI_LOG"], "a").write(json.dumps(sys.argv[1:]) + "\\n")+sys.exit(1)+'''+NETLIST = {"components": [+ {"ref": "U1", "block": "power", "value": "TLV70433", "mpn": "TLV70433DBVR", "mfr": "TI"},+ {"ref": "C1", "block": "power", "value": "1uF", "mpn": "CL05A105KA5NQNC", "mfr": "Samsung"},+ {"ref": "R1", "block": "led", "value": "1k", "mpn": "RC0402FR-071KL", "mfr": "Yageo"},+ {"ref": "D1", "block": "led", "value": "green", "mpn": "LTST-C191KGKT", "mfr": "Lite-On"},+ {"ref": "MC1", "block": "contacts", "value": "MachineContactMedium", "mpn": None}],+ "nets": {"VIN": ["U1.2", "C1.1", "MC1.1"], "+3V3": ["U1.3", "R1.1"], "LED_A": ["R1.2", "D1.2"], "GND": ["U1.1", "C1.2", "D1.1"]}}+# a minimal board to attach before finish (finish needs a board and a spec)+BOARD = """(kicad_pcb (version 20241229) (generator "test") (general (thickness 1.6))+ (layers (0 "F.Cu" signal) (2 "B.Cu" signal) (25 "Edge.Cuts" user) (37 "F.SilkS" user))+ (net 0 "") (net 1 "A") (net 2 "B")+ (gr_rect (start 0 0) (end 30 20) (layer "Edge.Cuts"))+ (footprint "TestPoint:TestPoint_Pad_D1.5mm" (layer "F.Cu") (at 5 10) (property "Reference" "TP1" (at 0 -2) (layer "F.SilkS"))+ (pad "1" smd circle (at 0 0) (size 1.5 1.5) (layers "F.Cu") (net 1 "A")))+ (footprint "TestPoint:TestPoint_Pad_D1.5mm" (layer "F.Cu") (at 25 10) (property "Reference" "TP2" (at 0 -2) (layer "F.SilkS"))+ (pad "1" smd circle (at 0 0) (size 1.5 1.5) (layers "F.Cu") (net 2 "B"))))+"""+BOM = "refs,qty,value,mpn,manufacturer\nMC1,1,contact,no part,Adom\nU1,1,TLV70433,TLV70433DBVR,TI\nC1,1,1uF,CL05A105KA5NQNC,Samsung\nR1,1,1k,RC0402FR-071KL,Yageo\nD1,1,green,LTST-C191KGKT,Lite-On\n"++with tempfile.TemporaryDirectory(prefix='aiflow-page-build-') as td:+ p = pathlib.Path(td)+ b = p / 'bin'; b.mkdir()+ (b / 'adom-wiki').write_text(FAKE_WIKI); (b / 'adom-wiki').chmod(0o755)+ log = p / 'wiki.jsonl'+ env = dict(os.environ, AIFLOW_DASHBOARD='off', PATH=f"{b}:{os.environ['PATH']}", FAKE_WIKI_LOG=str(log))+ env.pop('ADOM_AIFLOW_KICAD_CLI', None)++ def call(*args):+ return subprocess.run([binary, '--run', str(p / 'run'), '--ai-thread', 'page-build-test', *args], env=env, capture_output=True, text=True, timeout=300)++ def data():+ return json.loads((p / 'run' / 'run.json').read_text())++ (p / 'design').mkdir()+ (p / 'design' / 'netlist.json').write_text(json.dumps(NETLIST))+ (p / 'design' / 'bom.csv').write_text(BOM)+ # issue #158: no spec yet, requirements say molecule+ (p / 'requirements.json').write_text(json.dumps({"title": "Test molecule", "summary": "An LDO and an LED.", "formFactor": {"kind": "molecule", "pin": "MachinePinMediumShort"}}))+ r = call('intake', '--prompt-time', '2026-11-06T01:00:00Z', '--engine', 'test', '--requirements', str(p / 'requirements.json'))+ assert r.returncode == 0, r.stdout + r.stderr+ bundle = p / 'pkg'; bundle.mkdir()+ (bundle / 'package.json').write_text(json.dumps({"slug": "test-mol", "kind": "molecule", "title": "Test molecule", "description": "An LDO and an LED on a molecule."}))++ # no folder: refused with the way to give one+ r = call('project-page', 'check'); out = r.stdout + r.stderr+ assert r.returncode != 0 and '--molecule-bundle' in out, out++ r = call('project-page', '--molecule-bundle', str(bundle), '--netlist', str(p / 'design' / 'netlist.json'), '--bom', str(p / 'design' / 'bom.csv'), '--offline', '--page', 'adom/test-mol')+ out = r.stdout + r.stderr+ assert r.returncode == 0 and out.startswith('OK: page built in'), out+ html = (bundle / 'readme.html').read_text()+ for s in ('board', 'contacts', 'circuit-explorer', 'simulation', 'components', 'manufacturing', 'open-items'):+ assert f'data-aiflow-section="{s}"' in html, s+ assert json.loads((bundle / 'package.json').read_text())['readme_order'] == ['html']+ proof = json.loads((bundle / 'docs' / 'explorer-proof.json').read_text())+ assert proof['diffs'] == 0 and proof['coverage']['percent'] == 100.0, proof+ assert (p / 'design' / 'explorer' / 'blocks.json').is_file() and (p / 'design' / 'explorer' / 'auto' / 'power.json').is_file()+ rec = data()['outcomes']['page-build']+ assert rec['bundle'] == str(bundle.resolve()) and rec['explorer']['diffs'] == 0, rec+ assert 'auto-drawn' in out and 'No prices' in out and 'Next (molecule)' in out, out # the molecule note from requirements (#158)++ # the check: no board picture and no simulation yet are findings, never an error+ r = call('project-page', 'check'); out = r.stdout + r.stderr+ assert r.returncode == 0 and out.startswith('FINDINGS') and 'section board' in out and 'section simulation' in out, out+ assert data()['outcomes']['page-check']['passed'] is False++ assert 'circuit explorer:' in out and 'auto-drawn' in out, out # issue #197: a finding, not a quiet note++ # upstream's design review (`--results --out`) goes beside the page, and the next build links it+ r = call('project-page', '--results', '--out', str(bundle)); out = r.stdout + r.stderr+ assert r.returncode == 0 and (bundle / 'design-review' / 'README.md').is_file(), out+ readme_before = (bundle / 'README.md').read_text()+ r = call('project-page', '--molecule-bundle', str(bundle), '--offline'); out = r.stdout + r.stderr+ assert r.returncode == 0 and 'design-review/README.md' in (bundle / 'readme.html').read_text(), out+ assert (bundle / 'README.md').read_text() == readme_before # README.md is never rewritten++ # finish: the page's findings are open items, the explorer's under its own name (deviate "circuit explorer")+ (p / 'board.kicad_pcb').write_text(BOARD); (p / 'spec.json').write_text(json.dumps({"hot": {}, "hotNote": "test board"}))+ r = call('start', '--board', str(p / 'board.kicad_pcb'), '--spec', str(p / 'spec.json'), '--engine', 'test')+ assert r.returncode == 0, r.stdout + r.stderr+ r = call('finish'); out = r.stdout + r.stderr+ summ = data().get('summary') or {}+ opened = summ.get('open') or []+ assert any(o.startswith('circuit explorer:') and 'auto-drawn' in o for o in opened), (opened, out[-3000:])+ assert any(o.startswith('project page: section board') for o in opened), opened+print('PASS: project-page --molecule-bundle builds readme.html (seven sections), docs/ and readme_order ["html"] with a netlist-checked explorer (0 differences, 100 % coverage) and records the build; project-page check reports the missing board pictures, the simulation and the auto-drawn blocks as findings; --results --out puts design-review/ beside the page and the build links it without touching README.md; finish lists the page findings as open items; a requirements molecule is a molecule before a spec')
tests/project-page-check.py+6@@ -33,4 +33,10 @@ class PageChecks(unittest.TestCase): self.assertTrue(any('model_3d' in x for x in r['suggestions']),r) self.p['component']['parts']={'datasheet':'project.pdf'};r=self.run_check();self.assertTrue(r['passed'],r);self.assertEqual(r['suggestions'],[]) live=self.r/'live.json';live.write_text(json.dumps({'metadata':{'model_3d_path':'registry.glb','datasheet_path':'project.pdf'}}));self.assertTrue(m.check(self.r,live)['passed'])+ def test_a_built_html_page_points_at_its_own_check(self):+ # issue #164: readme.html with readme_order ["html"] is checked by `project-page check`, not the screenshot rule+ (self.r/'readme.html').write_text('<html></html>');(self.r/'README.md').write_text('# Board')+ self.assertFalse(self.run_check()['passed'])+ self.p['readme_order']=['html'];r=self.run_check();self.assertTrue(r['passed'],r)+ self.assertTrue(any('project-page check' in s for s in r['suggestions']),r) if __name__=='__main__':unittest.main()
tools/page-build.pyadded+2443@@ -0,0 +1,2443 @@+#!/usr/bin/env python3+"""The board's page, built for every board, molecule or not (issues #164, #131, #197, #198, #200): readme.html plus+docs/ in a package folder (the molecule-publish Stage 2 folder, or any folder a board page is published from).++ python3 tools/page-build.py <config.json> (the binary writes it beside the config with PAGE_ASSETS in front)++config: {"mode": "build" | "check", "run": <run dir>, "bundle": <folder>, "page": "owner/slug", "pageDir", "title",+"brief", "molecule": bool, "spec", "requirements", "board", "netlist", "schematic", "explorer", "bom", "sweeps": [...],+"fields", "offline": bool, "runReport": <url>, "now", "version"}++build readme.html (board renders and contacts, the circuit explorer, the simulation, the components, manufacturing,+ open items) and docs/ (board/, review/, parts/, explorer/, figures.json, bom.json, explorer-proof.json) into the+ bundle; package.json gets readme_order ["html"]. An existing README.md is left as it is (a missing one is+ written: the wiki needs it for search). The Markdown design review is `project-page --results --out <folder>`+ (design-review/README.md); the page links it when the folder has one.+check every section present and filled, every figure made from this board (the board fingerprint recorded beside it+ in docs/figures.json), the explorer proof recomputed from docs/explorer/ (coverage 100 %, 0 netlist+ differences, no auto-drawn block, a readable number of blocks), a BOM row for every bought part.++The circuit explorer: blocks come from netlist.json's `block` field; signals between blocks are the nets that span+blocks (ground nets left out), arrows from the block that drives the net (schematic pin types) to the others. Each+block's drawing is a small JSON in the explorer folder (<id>.json, "block": <netlist block>), drawn by the AI the+textbook way; a block with no drawing gets an auto-drawn one (every pin labelled with its net) in explorer/auto/.+Every drawing is checked against the netlist: each wired group of pins and labels must be one net, every connected+pin of a drawn part drawn, every part in some drawing. Prints one JSON object. Findings only: nothing here refuses."""+import csv, hashlib, html, io, json, math, os, re, shutil, subprocess, sys, tempfile, time, urllib.parse+from concurrent.futures import ThreadPoolExecutor++PROOF_SCHEMA = "aiflow.explorer-proof/1"+SECTION_IDS = ["board", "contacts", "circuit-explorer", "simulation", "components", "manufacturing", "open-items"]+WIKI = "https://wiki.adom.inc"+GAUGE = {"large": "14 AWG", "medium": "24 AWG"}+++def fail(msg, **extra):+ raise SystemExit(json.dumps(dict({"ok": False, "error": msg}, **extra)))+++def esc(s):+ return html.escape("" if s is None else str(s), quote=True)+++def sha_bytes(b):+ return hashlib.sha256(b).hexdigest()+++def sha(path):+ h = hashlib.sha256()+ with open(path, "rb") as f:+ for b in iter(lambda: f.read(1 << 20), b""):+ h.update(b)+ return h.hexdigest()+++def rjson(path, default=None):+ try:+ with open(path) as f:+ return json.load(f)+ except (OSError, ValueError, TypeError):+ return default+++def wjson(path, v):+ os.makedirs(os.path.dirname(path) or ".", exist_ok=True)+ with open(path, "w") as f:+ json.dump(v, f, indent=1, sort_keys=False)+ f.write("\n")+++def now():+ return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())+++def assets():+ """The explorer's symbols, script and style: PAGE_ASSETS when the binary runs this file, else the files beside it."""+ a = globals().get("PAGE_ASSETS")+ if a:+ return a+ here = os.path.join(os.path.dirname(os.path.abspath(__file__)), "page-explorer")+ return {"symbols": open(os.path.join(here, "symbols.json")).read(), "js": open(os.path.join(here, "explorer.js")).read(),+ "css": open(os.path.join(here, "explorer.css")).read()}+++def symbols():+ s = json.loads(assets()["symbols"])+ s.pop("_", None)+ return s+++# --------------------------------------------------------------------------- S-expressions (KiCad files)++_TOK = re.compile(r'\(|\)|"(?:[^"\\]|\\.)*"|[^\s()"]+')+++def sx(text):+ stack, cur = [], []+ for m in _TOK.finditer(text):+ t = m.group(0)+ if t == "(":+ stack.append(cur)+ cur = []+ elif t == ")":+ done = cur+ cur = stack.pop() if stack else []+ cur.append(done)+ elif t[0] == '"':+ cur.append(t[1:-1].replace('\\"', '"').replace("\\\\", "\\"))+ else:+ cur.append(t)+ return cur[0] if cur else []+++def kids(node, tag):+ return [x for x in node[1:] if isinstance(x, list) and x and x[0] == tag]+++def kid(node, tag):+ for x in node[1:]:+ if isinstance(x, list) and x and x[0] == tag:+ return x+ return None+++def prop(node, name):+ for p in kids(node, "property"):+ if len(p) > 2 and p[1] == name:+ return p[2]+ return None+++def num(v, d=0.0):+ try:+ return float(v)+ except (TypeError, ValueError):+ return d+++def board_fingerprint(path):+ """The board's identity for its pictures: sha256 of the file with 3D model paths and Fab-layer texts left out+ and whitespace collapsed (molecule-publish points the models at 3d/, `silkscreen fab-tidy` rewrites only Fab+ text: neither changes copper, parts or outline)."""+ try:+ t = open(path, encoding="utf-8", errors="replace").read()+ except OSError:+ return None+ t = re.sub(r'\(model\s+(?:"[^"]*"|[^\s()]+)', "(model", t)+ return sha_bytes(re.sub(r"\s+", " ", strip_fab_text(t)).encode())+++def strip_fab_text(t):+ """The board text without its Fab-layer texts (fp_text and property nodes on F.Fab or B.Fab): the Fab layer+ is the assembly drawing, not copper, parts or outline, so `silkscreen fab-tidy` after a Fields solve keeps the+ solve's pictures valid (adopt-board's copper fingerprint leaves Fab text out the same way)."""+ out, i, n = [], 0, len(t)+ starts = re.compile(r'\((?:fp_text|property)\b')+ while True:+ m = starts.search(t, i)+ if not m:+ out.append(t[i:]); break+ j, depth, k, q = m.start(), 0, m.start(), False+ while k < n:+ c = t[k]+ if q:+ if c == "\\": k += 1+ elif c == '"': q = False+ elif c == '"': q = True+ elif c == "(": depth += 1+ elif c == ")":+ depth -= 1+ if depth == 0: break+ k += 1+ node = t[j:k + 1]+ out.append(t[i:j])+ if not re.search(r'\(layer\s+"?[FB]\.Fab"?\s*\)', node):+ out.append(node)+ i = k + 1+ return "".join(out)+++def parse_board(path):+ """Footprints (ref, lib, value, x, y, side, pads {num: net}), the outline's box and the copper layers."""+ t = sx(open(path, encoding="utf-8", errors="replace").read())+ fps = []+ for fp in kids(t, "footprint"):+ ref = prop(fp, "Reference") or ""+ at = kid(fp, "at") or ["at", 0, 0]+ layer = (kid(fp, "layer") or ["layer", "F.Cu"])[1]+ pads = {}+ for p in kids(fp, "pad"):+ n = kid(p, "net")+ net = None+ if n and len(n) > 1 and isinstance(n[-1], str):+ # (net "NAME") in KiCad 10, (net 5 "NAME") before; a bare number names no net+ net = None if len(n) == 2 and re.fullmatch(r"\d+", n[-1]) else (n[-1] or None)+ if len(p) > 1 and isinstance(p[1], str) and p[1] != "":+ if p[1] not in pads or pads[p[1]] is None:+ pads[p[1]] = net+ fps.append({"ref": ref, "lib": fp[1] if len(fp) > 1 else "", "value": prop(fp, "Value") or "", "x": num(at[1]), "y": num(at[2]),+ "side": "bottom" if str(layer).startswith("B.") else "top", "pads": pads, "sheet": prop(fp, "Sheetname") or "",+ "mpn": prop(fp, "MPN") or prop(fp, "Manufacturer Part Number") or "", "mfr": prop(fp, "Manufacturer") or ""})+ xs, ys = [], []+ for tag in ("gr_line", "gr_arc", "gr_rect", "gr_circle", "gr_poly"):+ for g in kids(t, tag):+ if (kid(g, "layer") or ["", ""])[1] != "Edge.Cuts":+ continue+ for k in ("start", "end", "mid", "center"):+ q = kid(g, k)+ if q:+ xs.append(num(q[1])); ys.append(num(q[2]))+ pts = kid(g, "pts")+ for q in kids(pts, "xy") if pts else []:+ xs.append(num(q[1])); ys.append(num(q[2]))+ layers = [l[1] for l in (kid(t, "layers") or [])[1:] if isinstance(l, list) and len(l) > 2 and str(l[1]).endswith(".Cu")]+ box = [min(xs), min(ys), max(xs), max(ys)] if xs else None+ thick = None+ setup = kid(t, "general")+ if setup and kid(setup, "thickness"):+ thick = num(kid(setup, "thickness")[1])+ return {"footprints": fps, "outline": box, "copperLayers": layers, "thicknessMm": thick}+++def parse_schematics(path):+ """{ref: {"lib": lib_id, "pins": [{num, name, type, x, y}]}} from a root .kicad_sch and every sheet beside it."""+ if not path or not os.path.isfile(path):+ return {}+ folder = os.path.dirname(os.path.abspath(path))+ files = [os.path.join(folder, f) for f in sorted(os.listdir(folder)) if f.endswith(".kicad_sch")]+ libs, inst = {}, {}+ for f in files:+ try:+ t = sx(open(f, encoding="utf-8", errors="replace").read())+ except OSError:+ continue+ ls = kid(t, "lib_symbols")+ for s in kids(ls, "symbol") if ls else []:+ pins = []+ for sub in [s] + kids(s, "symbol"):+ for p in kids(sub, "pin"):+ at = kid(p, "at") or ["at", 0, 0]+ nm, nb = kid(p, "name"), kid(p, "number")+ if nb and len(nb) > 1:+ pins.append({"num": nb[1], "name": nm[1] if nm and len(nm) > 1 else "", "type": p[1] if len(p) > 1 else "",+ "x": num(at[1]), "y": num(at[2])})+ seen, uniq = set(), []+ for p in pins:+ if p["num"] not in seen:+ seen.add(p["num"]); uniq.append(p)+ libs[s[1]] = uniq+ for s in kids(t, "symbol"):+ lid = kid(s, "lib_id")+ ref = prop(s, "Reference")+ if lid and ref and not ref.startswith("#"):+ inst[ref] = lid[1]+ return {ref: {"lib": lid, "pins": libs.get(lid, [])} for ref, lid in inst.items()}+++# --------------------------------------------------------------------------- the design (netlist + schematic)++def norm_net(n):+ if n is None:+ return None+ n = str(n)+ return n[1:] if n.startswith("/") else n+++GROUND_RE = re.compile(r"^(A|D|P|S|C)?GND\w*$|^\w*_GND$|^RTN$|^VSS\w*$|^0V$|^EARTH$|^CHASSIS$", re.I)+++def is_ground(net, spec=None):+ if not net:+ return False+ extra = set()+ if isinstance(spec, dict):+ mol = spec.get("molecule") or {}+ if isinstance(mol, dict) and mol.get("cornerPinsNet"):+ extra.add(norm_net(mol["cornerPinsNet"]))+ for g in spec.get("groundNets") or []:+ extra.add(norm_net(g))+ return bool(GROUND_RE.match(net)) or net in extra+++def load_design(netlist_path, board, sch, spec):+ """{"parts": {ref: {...pins {num: net}...}}, "blocks": [ids in order], "source": ...}."""+ parts, order = {}, []+ src = None+ nl = rjson(netlist_path) if netlist_path else None+ if isinstance(nl, dict) and nl.get("components"):+ src = {"kind": "netlist.json", "path": os.path.abspath(netlist_path), "sha256": sha(netlist_path)}+ for c in nl["components"]:+ ref = c.get("ref")+ if not ref:+ continue+ b = c.get("block") or "board"+ parts[ref] = {"ref": ref, "value": c.get("value") or "", "mpn": c.get("mpn") or "", "mfr": c.get("mfr") or c.get("manufacturer") or "",+ "desc": c.get("desc") or "", "note": c.get("note") or "", "role": c.get("role") or "", "page": c.get("page") or "",+ "package": c.get("package") or "", "partKey": c.get("part") or "", "block": b, "pins": {}}+ if b not in order:+ order.append(b)+ nets = nl.get("nets") or {}+ items = nets.items() if isinstance(nets, dict) else [(n.get("name"), n.get("pins") or n.get("nodes") or []) for n in nets if isinstance(n, dict)]+ for net, pins in items:+ for pr in pins:+ ref, _, pin = str(pr).partition(".")+ if ref in parts and pin:+ parts[ref]["pins"][pin] = norm_net(net)+ elif board:+ src = {"kind": "board", "path": board.get("path"), "sha256": board.get("sha256")}+ sheets = {fp["sheet"] for fp in board["footprints"] if fp["sheet"]}+ for fp in board["footprints"]:+ if not fp["ref"] or fp["ref"].startswith("#") or fp["ref"].startswith("REF"):+ continue+ if len(sheets) > 1:+ b = fp["sheet"].strip("/") or "root"+ else:+ m = re.match(r"[A-Za-z]+(\d+)", fp["ref"])+ b = f"{int(m.group(1)) // 100}xx" if m and len(m.group(1)) >= 3 else "board"+ parts[fp["ref"]] = {"ref": fp["ref"], "value": fp["value"], "mpn": fp["mpn"], "mfr": fp["mfr"], "desc": "", "note": "", "role": "",+ "page": "", "package": fp["lib"].split(":")[-1], "block": b,+ "pins": {k: norm_net(v) for k, v in fp["pads"].items() if v}}+ if b not in order:+ order.append(b)+ else:+ return {"parts": {}, "blocks": [], "source": None}+ for ref, p in parts.items():+ s = sch.get(ref) or {}+ p["lib"] = s.get("lib") or ""+ p["schPins"] = s.get("pins") or []+ # board footprints carry the contact class (MachineContactLarge ...)+ for fp in (board or {}).get("footprints", []):+ if fp["ref"] in parts:+ parts[fp["ref"]]["footprint"] = fp["lib"]+ return {"parts": parts, "blocks": order, "source": src}+++# --------------------------------------------------------------------------- symbols for parts++# issue #172: an LED is named by its footprint or symbol name (after the colon, never the library nickname) or its+# value: a word starting with LED (LED_0603_1608Metric, LED-RGB, LED_Red) or a colour as a whole word in the value.+# A description ("clamp for the LED bar") or an MPN never makes a diode an LED.+LED_WORD = re.compile(r"(?<![A-Za-z])LED", re.I)+LED_COLOUR = re.compile(r"\b(green|red|blue|yellow|amber|white|orange|rgb|rgbw)\b", re.I)+++def is_led(dp):+ fp = (dp.get("footprint") or "").split(":")[-1]+ sym = (dp.get("lib") or "").split(":")[-1]+ v = dp.get("value") or ""+ return bool(LED_WORD.search(fp) or LED_WORD.search(sym) or LED_WORD.search(v) or LED_COLOUR.search(v))+++POLAR_RE = re.compile(r"electrolytic|polari[sz]ed|tantalum|alumin(i)?um|polymer", re.I)+++def pin_names(dp):+ return {p["num"]: (p["name"] or "").strip() for p in dp.get("schPins") or []}+++def all_pins(dp):+ nums = [p["num"] for p in dp.get("schPins") or []] or list(dp["pins"].keys())+ return sorted(set(nums) | set(dp["pins"].keys()), key=_numkey)+++def _numkey(n):+ m = re.match(r"(\D*)(\d+)(.*)", str(n))+ return (m.group(1), int(m.group(2)), m.group(3)) if m else (str(n), 0, "")+++def infer_symbol(dp):+ """(symbol name, {symbol pin: [part pins]}) or ("BOX", None) for a box drawn from the schematic's pins."""+ ref = dp["ref"]+ pre = (re.match(r"[A-Za-z]+", ref) or [""])[0].upper()+ pins = all_pins(dp)+ names = pin_names(dp)+ text = " ".join([dp.get("value", ""), dp.get("desc", ""), dp.get("mpn", ""), dp.get("lib", ""), dp.get("footprint", ""), dp.get("package", "")])+ by = lambda *ns: [p for p in pins if (names.get(p) or "").upper() in ns]+ if len(pins) == 1:+ p = {"p": pins}+ if pre == "TP" or re.search(r"test ?point|test pad|TestPoint|TP_", text, re.I):+ return "TP", p+ if pre == "MP" or re.search(r"MachinePin", text):+ return "MP", p+ if pre == "MC" or re.search(r"MachineContact", text):+ return ("MCL" if re.search(r"large", text, re.I) else "MC"), p+ return "TP", p+ if len(pins) == 2:+ a, b = pins+ two = {"1": [a], "2": [b]}+ if pre in ("R", "RS", "RSH"):+ return "R", two+ if pre == "C":+ return ("CP" if POLAR_RE.search(text) else "C"), two+ if pre == "L":+ return "L", two+ if pre in ("FB", "FL"):+ return "FB", two+ if pre == "F":+ return "F", two+ if pre in ("NT",):+ return "NT", two+ if pre in ("SW", "S", "BTN"):+ return "SW", two+ if pre in ("Y", "X"):+ return "XTAL", two+ if pre in ("D", "LED", "ZD", "TVS"):+ k, an = by("K", "CATHODE", "C"), by("A", "ANODE")+ m = {"k": k or [a], "a": an or [b]}+ if pre == "LED" or is_led(dp):+ return "LED", m+ if re.search(r"schottky", text, re.I):+ return "DS", m+ if pre == "TVS" or re.search(r"\btvs\b|esd", text, re.I):+ return "TVS", m+ if pre == "ZD" or re.search(r"zener", text, re.I):+ return "DZ", m+ return "D", m+ if pre == "Q" and pins:+ g, d, s = by("G", "GATE"), by("D", "DRAIN"), by("S", "SOURCE")+ if g and d and s and len(g) + len(d) + len(s) == len(pins):+ return ("PMOS" if re.search(r"p-?ch|pmos|p-channel", text, re.I) else "NMOS"), {"g": g, "d": d, "s": s}+ bb, c, e = by("B", "BASE"), by("C", "COLLECTOR"), by("E", "EMITTER")+ if bb and c and e and len(bb) + len(c) + len(e) == len(pins):+ return ("PNP" if re.search(r"pnp", text, re.I) else "NPN"), {"b": bb, "c": c, "e": e}+ return "BOX", None+++def auto_box(dp):+ """A box from the schematic symbol's pins (names and sides), pins of one name and net grouped; else numbers,+ half left and half right."""+ sp = dp.get("schPins") or []+ nets = dp["pins"]+ groups = []+ if sp:+ seen = {}+ for p in sp:+ name = p["name"] if p["name"] and p["name"] != "~" else p["num"]+ side = "L" if p["x"] < -0.01 else "R" if p["x"] > 0.01 else ("T" if p["y"] > 0 else "B")+ key = (name, nets.get(p["num"]), side)+ if key in seen:+ seen[key]["nums"].append(p["num"])+ continue+ g = {"name": name, "side": side, "nums": [p["num"]], "pos": (p["x"], p["y"])}+ seen[key] = g+ groups.append(g)+ else:+ ns = all_pins(dp)+ half = (len(ns) + 1) // 2+ for i, n in enumerate(ns):+ groups.append({"name": n, "side": "L" if i < half else "R", "nums": [n], "pos": (0, -i if i < half else -(i - half))})+ names_unique = {}+ for g in groups:+ names_unique.setdefault(g["name"], []).append(g)+ for nm, gs in names_unique.items():+ if len(gs) > 1: # one name on two nets or sides: tell them apart by number+ for g in gs:+ g["name"] = f"{nm}/{g['nums'][0]}"+ sides = {s: sorted([g for g in groups if g["side"] == s], key=lambda g: (-g["pos"][1]) if s in "LR" else g["pos"][0]) for s in "LRTB"}+ step = 20+ nlr = max(len(sides["L"]), len(sides["R"]), 1)+ ntb = max(len(sides["T"]), len(sides["B"]), 0)+ longest = lambda s: max([len(g["name"]) for g in sides[s]] or [0])+ w = max(60, (longest("L") + longest("R")) * 5.2 + 30, (ntb + 1) * step)+ w = int(math.ceil(w / 10.0) * 10)+ h = int(max(40, (nlr + 1) * step, ((longest("T") + longest("B")) * 5.2 + 30) if ntb else 0))+ h = int(math.ceil(h / 10.0) * 10)+ pins = []+ for s in "LRTB":+ for i, g in enumerate(sides[s]):+ pins.append([g["name"], s, (i + 1) * step, g["nums"]])+ return {"w": w, "h": h, "title": [dp["ref"], dp.get("value") or ""], "pins": pins}+++def box_sym(spec):+ pins, mp = {}, {}+ hw, hh = spec["w"] / 2.0, spec["h"] / 2.0+ for name, side, off, nums in spec["pins"]:+ if side == "L":+ p = [-hw - 10, -hh + off]+ elif side == "R":+ p = [hw + 10, -hh + off]+ elif side == "T":+ p = [-hw + off, -hh - 10]+ else:+ p = [-hw + off, hh + 10]+ pins[name] = p+ mp[name] = [str(n) for n in nums]+ return {"pins": pins, "bb": [-hw, -hh, hw, hh]}, mp+++def parse_opts(s, o):+ P = {"rot": 0, "mx": False, "my": False, "lab": None, "text": None, "box": None, "labxy": None, "sym": None, "map": None}+ for t in str(s or "").split():+ if re.fullmatch(r"r(0|90|180|270)", t):+ P["rot"] = int(t[1:])+ elif t == "mx":+ P["mx"] = True+ elif t == "my":+ P["my"] = True+ elif re.fullmatch(r"l[tblrn]", t):+ P["lab"] = t[1]+ else:+ raise ValueError("unknown part option " + t)+ if isinstance(o, dict):+ P["labxy"] = o.get("label")+ P["text"] = o.get("text")+ P["box"] = o.get("box")+ P["sym"] = o.get("sym")+ P["map"] = o.get("map")+ return P+++def xf(pt, P):+ x, y = pt+ if P["mx"]:+ x = -x+ if P["my"]:+ y = -y+ r = P["rot"]+ if r == 90:+ x, y = -y, x+ elif r == 180:+ x, y = -x, -y+ elif r == 270:+ x, y = y, -x+ return [P["x"] + x, P["y"] + y]+++def K(p):+ return f"{round(p[0] * 10) / 10:g},{round(p[1] * 10) / 10:g}"+++# --------------------------------------------------------------------------- the netlist check of one drawing++def resolve_symbol(dp, P, overrides, SYM):+ """(symbol name, symbol def, {symbol pin: [part pins]}, box spec or None)."""+ ov = overrides.get(dp["ref"]) or overrides.get(dp.get("mpn") or "\0") or {}+ box = P["box"] if P["box"] is not None else ov.get("box")+ if box is not None:+ spec = auto_box(dp) if box == "auto" else box+ s, m = box_sym(spec)+ return "BOX", s, m, spec+ name = P["sym"] or ov.get("sym")+ mp = P["map"] or ov.get("map")+ if not name:+ name, mp2 = infer_symbol(dp)+ mp = mp or mp2+ if name == "BOX" or name not in SYM:+ spec = auto_box(dp)+ s, m = box_sym(spec)+ return "BOX", s, m, spec+ if not mp:+ pins = all_pins(dp)+ sp = list(SYM[name]["pins"].keys())+ mp = {k: [pins[i]] for i, k in enumerate(sp) if i < len(pins)}+ return name, SYM[name], {k: [str(x) for x in (v if isinstance(v, list) else [v])] for k, v in mp.items()}, None+++def analyze(dr, design, overrides, SYM):+ """The sch.js analysis: place the parts, join wires, labels and pins into groups, each group one net."""+ did = dr.get("id") or dr.get("block") or "?"+ errors, warns = [], []+ err = lambda m: errors.append(f"{did}: {m}")+ parts, pin_at = [], {}+ for entry in dr.get("parts") or []:+ if not isinstance(entry, list) or len(entry) < 3:+ err(f"bad part entry {json.dumps(entry)[:60]}")+ continue+ key, x, y = entry[0], entry[1], entry[2]+ opt = entry[3] if len(entry) > 3 else ""+ obj = entry[4] if len(entry) > 4 else None+ if isinstance(opt, dict):+ opt, obj = "", opt+ dp = design["parts"].get(key)+ if not dp:+ err(f"unknown part {key} (not in the netlist)")+ continue+ try:+ P = parse_opts(opt, obj)+ except ValueError as e:+ err(f"{key}: {e}")+ continue+ P["x"], P["y"] = x, y+ name, sym, mp, spec = resolve_symbol(dp, P, overrides, SYM)+ part = {"key": key, "ref": key, "sym": name, "P": P, "box": spec, "pins": {}, "def": sym}+ for pn, lp in sym["pins"].items():+ nums = mp.get(pn)+ if not nums:+ err(f"{key}: symbol pin {pn} has no part pin (give a map)")+ continue+ missing = [n for n in nums if n not in all_pins(dp)]+ if missing:+ err(f"{key}.{pn}: the part has no pin {'/'.join(missing)}")+ nets = {dp["pins"].get(n) for n in nums}+ if len(nets) > 1:+ err(f"{key}.{pn}: pins {'/'.join(nums)} are on different nets {', '.join(sorted(str(n) for n in nets))}")+ pos = xf(lp, P)+ info = {"x": pos[0], "y": pos[1], "key": key, "pin": pn, "nums": nums, "net": dp["pins"].get(nums[0])}+ part["pins"][pn] = info+ pin_at[f"{key}.{pn}"] = info+ parts.append(part)++ def pt(item):+ if isinstance(item, list):+ if len(item) != 2 or not all(isinstance(v, (int, float)) for v in item):+ err(f"bad point {json.dumps(item)}")+ return None+ return [item[0], item[1]]+ p = pin_at.get(item)+ if not p:+ err(f"unknown pin {item}")+ return None+ return [p["x"], p["y"]]++ wires = []+ for w in dr.get("wires") or []:+ pts, route, good = [], "hv", True+ for item in w:+ if item in ("hv", "vh"):+ route = item+ continue+ q = pt(item)+ if q is None:+ good = False+ break+ if pts:+ p = pts[-1]+ if p[0] != q[0] and p[1] != q[1]:+ pts.append([q[0], p[1]] if route == "hv" else [p[0], q[1]])+ pts.append(q)+ route = "hv"+ if good and len(pts) >= 2:+ wires.append({"pts": pts})+ elif good:+ err(f"wire with one point: {json.dumps(w)}")++ anchors = []+ for g in dr.get("gnd") or []:+ if isinstance(g, list) and len(g) >= 2 and isinstance(g[1], str):+ at, d, nm = g[0], g[1], (g[2] if len(g) > 2 else "GND")+ else:+ at, d, nm = g, "down", "GND"+ p = pt(at)+ if p:+ anchors.append({"kind": "gnd", "name": norm_net(nm), "p": p, "dir": d or "down"})+ for kind, default in (("rails", "up"), ("flags", "right")):+ for a in dr.get(kind) or []:+ if not isinstance(a, list) or len(a) < 2:+ err(f"bad {kind[:-1]} {json.dumps(a)}")+ continue+ p = pt(a[0])+ if p:+ anchors.append({"kind": kind[:-1], "name": norm_net(a[1]), "p": p, "dir": a[2] if len(a) > 2 else default})++ parent = {}++ def find(a):+ while parent[a] != a:+ parent[a] = parent[parent[a]]+ a = parent[a]+ return a++ def add(a):+ parent.setdefault(a, a)++ def union(a, b):+ add(a); add(b)+ parent[find(a)] = find(b)++ segs = []+ for wi, w in enumerate(wires):+ for p in w["pts"]:+ add(K(p))+ for i in range(1, len(w["pts"])):+ union(K(w["pts"][i - 1]), K(w["pts"][i]))+ segs.append((w["pts"][i - 1], w["pts"][i], wi))+ key_pts = [p for w in wires for p in w["pts"]] + [[p["x"], p["y"]] for p in pin_at.values()] + [a["p"] for a in anchors]+ for p in key_pts:+ add(K(p))++ def on_seg(p, a, b):+ x, y = p+ if a[0] == b[0]:+ return x == a[0] and min(a[1], b[1]) < y < max(a[1], b[1])+ if a[1] == b[1]:+ return y == a[1] and min(a[0], b[0]) < x < max(a[0], b[0])+ return False++ tees = {}+ for a, b, _ in segs:+ for p in key_pts:+ if on_seg(p, a, b):+ union(K(p), K(a))+ tees[K(p)] = tees.get(K(p), 0) + 2+ for i in range(len(segs)):+ for j in range(i + 1, len(segs)):+ s, t = segs[i], segs[j]+ if s[2] == t[2]:+ continue+ vert = s[0][0] == s[1][0] and t[0][0] == t[1][0] and s[0][0] == t[0][0]+ hor = s[0][1] == s[1][1] and t[0][1] == t[1][1] and s[0][1] == t[0][1]+ if not vert and not hor:+ continue+ ix = 1 if vert else 0+ lo = max(min(s[0][ix], s[1][ix]), min(t[0][ix], t[1][ix]))+ hi = min(max(s[0][ix], s[1][ix]), max(t[0][ix], t[1][ix]))+ if hi > lo:+ union(K(s[0]), K(t[0]))+ warns.append(f"{did}: overlapping wires at {K(s[0])} / {K(t[0])}")++ groups = {}++ def G(k):+ return groups.setdefault(find(k), {"pins": [], "names": set(), "ends": 0})++ for p in pin_at.values():+ G(K([p["x"], p["y"]]))["pins"].append(p)+ for a in anchors:+ G(K(a["p"]))["names"].add(a["name"])+ degree = {}+ for w in wires:+ n = len(w["pts"])+ for i, p in enumerate(w["pts"]):+ G(K(p))["ends"] += 1+ degree[K(p)] = degree.get(K(p), 0) + (1 if i in (0, n - 1) else 2)+ for p in pin_at.values():+ degree[K([p["x"], p["y"]])] = degree.get(K([p["x"], p["y"]]), 0) + 1+ for a in anchors:+ degree[K(a["p"])] = degree.get(K(a["p"]), 0) + 1+ for k, n in tees.items():+ degree[k] = degree.get(k, 0) + n++ net_of = {}+ pieces = {}+ for root, g in groups.items():+ nets = {p["net"] for p in g["pins"]}+ real = {n for n in nets if n is not None} | g["names"]+ if None in nets and (len(g["pins"]) > 1 or g["ends"] or g["names"]):+ err("a pin with no net is wired: " + ", ".join(f"{p['key']}.{p['pin']}" for p in g["pins"] if p["net"] is None))+ if len(real) > 1:+ err("short: " + " + ".join(sorted(real)) + " joined at " + ", ".join([f"{p['key']}.{p['pin']}" for p in g["pins"]] + sorted(g["names"])))+ net_of[root] = sorted(real)[0] if real else None+ if len(g["pins"]) == 1 and not g["ends"] and not g["names"] and g["pins"][0]["net"] is not None:+ p0 = g["pins"][0]+ err(f"unconnected pin {p0['key']}.{p0['pin']} ({p0['net']})")+ if not g["pins"] and not g["names"] and g["ends"]:+ err(f"floating wire near {root}")+ if len(real) == 1:+ pieces.setdefault(next(iter(real)), []).append(g)+ for w in wires:+ for p in (w["pts"][0], w["pts"][-1]):+ if degree.get(K(p), 0) < 2:+ err(f"dangling wire end at {K(p)}")+ # one net drawn in pieces: each piece must carry its name (a label, rail or ground), or the drawing says two nets+ for net, gs in pieces.items():+ bare = [g for g in gs if not g["names"]]+ if len(gs) > 1 and bare:+ err(f"net {net} is drawn in {len(gs)} pieces and {len(bare)} of them carry no label: " ++ "; ".join(", ".join(f"{p['key']}.{p['pin']}" for p in g["pins"]) for g in bare))+ net_at = lambda p: net_of.get(find(K(p)))+ junctions = [[float(v) for v in k.split(",")] for k, n in degree.items() if n >= 3]+ return {"errors": errors, "warns": warns, "parts": parts, "wires": wires, "anchors": anchors, "junctions": junctions, "net_at": net_at}+++def short_value(v):+ """A value as a schematic prints it: 10nF 50V X7R 0402 -> 10nF 50V, 75k 1% -> 75k."""+ toks = v.split()+ if len(toks) >= 2 and re.fullmatch(r"\d+(\.\d+)?V", toks[1], re.I):+ return " ".join(toks[:2])+ return toks[0] if toks else v+++def render_model(dr, A, design):+ """What explorer.js draws: absolute positions and the net of every wire, label and junction."""+ parts = []+ for p in A["parts"]:+ P = p["P"]+ dp = design["parts"][p["ref"]]+ parts.append({"key": p["key"], "ref": p["ref"], "sym": p["sym"], "x": P["x"], "y": P["y"], "rot": P["rot"], "mx": P["mx"], "my": P["my"],+ "lab": P["lab"], "labxy": P["labxy"], "text": P["text"], "box": p["box"], "value": short_value(dp.get("value") or ""),+ "nets": sorted({i["net"] for i in p["pins"].values() if i["net"]})})+ nets = set()+ wires = []+ for w in A["wires"]:+ n = A["net_at"](w["pts"][0])+ nets.add(n)+ wires.append({"pts": w["pts"], "net": n})+ anchors = []+ for a in A["anchors"]:+ n = A["net_at"](a["p"]) or a["name"]+ nets.add(n)+ anchors.append({"kind": a["kind"], "name": a["name"], "p": a["p"], "dir": a["dir"], "net": n})+ for p in A["parts"]:+ for i in p["pins"].values():+ nets.add(i["net"])+ return {"id": dr["id"], "block": dr["block"], "title": dr.get("title") or "", "text": dr.get("text") or "", "w": dr.get("w", 600),+ "h": dr.get("h", 400), "auto": bool(dr.get("_auto")), "parts": parts, "wires": wires,+ "junctions": [[j[0], j[1], A["net_at"](j)] for j in A["junctions"]], "anchors": anchors,+ "notes": dr.get("notes") or [], "boxes": dr.get("boxes") or [], "nets": sorted(n for n in nets if n)}+++# --------------------------------------------------------------------------- auto-drawn blocks++def flag_w(name):+ return len(name) * 5.6 + 18+++def supply_like(net):+ """A supply rail by its name: +3V3, VBAT, GVDD, VCC_IO, 12V; not a feedback, sense or enable net beside one."""+ n = net or ""+ if re.search(r"FB|SENSE|SNS|_EN\b|_EN_|^EN|PGOOD|_PG\b|DIV|MON|_SW\b", n, re.I):+ return False+ return bool(re.match(r"^\+|^\d+V\d*$|^(G|A|D|P)?V(CC|DD|BAT|IN|BUS|SYS|MOT|REF|M|S)(_?\w{0,4})?$", n, re.I))+++def auto_drawing(block, refs, design, overrides, SYM, spec, title):+ """Every part of the block drawn with its symbol and every connected pin labelled with its net (a flag; a ground+ symbol for ground pins below the part; a supply symbol for supply pins above it). Correct by construction, not+ a textbook drawing."""+ items = []+ for ref in refs:+ dp = design["parts"][ref]+ P0 = {"rot": 0, "mx": False, "my": False, "lab": None, "text": None, "box": None, "labxy": None, "sym": None, "map": None, "x": 0, "y": 0}+ name, sym, mp, spec_box = resolve_symbol(dp, P0, overrides, SYM)+ rot = 90 if sym.get("two") else 0+ P0["rot"] = rot+ anchors = []+ lo = [0.0, 0.0, 0.0, 0.0] # extents left, top, right, bottom around the part origin+ bb = sym["bb"]+ c = [xf([bb[0], bb[1]], P0), xf([bb[2], bb[3]], P0)]+ lo = [min(c[0][0], c[1][0]) - 6, min(c[0][1], c[1][1]) - 6, max(c[0][0], c[1][0]) + 6, max(c[0][1], c[1][1]) + 6]+ for pn, lp in sym["pins"].items():+ nums = mp.get(pn) or []+ net = dp["pins"].get(nums[0]) if nums else None+ pos = xf(lp, P0)+ lo = [min(lo[0], pos[0]), min(lo[1], pos[1]), max(lo[2], pos[0]), max(lo[3], pos[1])]+ if not net:+ continue+ dx, dy = pos[0], pos[1]+ side = ("left" if dx < 0 else "right") if abs(dx) >= abs(dy) and abs(dx) > 0.1 else ("up" if dy < 0 else "down")+ if sym.get("tp"):+ side = "down"+ if is_ground(net, spec) and side == "down":+ anchors.append(["gnd", f"{ref}.{pn}", net, "down"])+ lo[3] = max(lo[3], pos[1] + 14)+ elif supply_like(net) and side == "up":+ anchors.append(["rail", f"{ref}.{pn}", net, "up"])+ lo[1] = min(lo[1], pos[1] - 18)+ lo[0] = min(lo[0], pos[0] - len(net) * 3)+ lo[2] = max(lo[2], pos[0] + len(net) * 3)+ else:+ anchors.append(["flag", f"{ref}.{pn}", net, side])+ fw = flag_w(net)+ if side == "left":+ lo[0] = min(lo[0], pos[0] - fw)+ elif side == "right":+ lo[2] = max(lo[2], pos[0] + fw)+ elif side == "up":+ lo[1] = min(lo[1], pos[1] - fw)+ else:+ lo[3] = max(lo[3], pos[1] + fw)+ if name == "BOX":+ lo[1] -= 26 # the title above the box+ else:+ lo[2] += 40 # reference and value to the right+ items.append({"ref": ref, "rot": rot, "box": spec_box, "anchors": anchors, "ext": lo, "big": name == "BOX"})+ items.sort(key=lambda it: (not it["big"], _numkey(it["ref"])))+ W, pad, gap = 760, 24, 26+ x, y, row_h, placed, width = pad, pad, 0, [], 0+ for it in items:+ e = it["ext"]+ w, h = e[2] - e[0], e[3] - e[1]+ if x > pad and x + w > W - pad:+ x, y, row_h = pad, y + row_h + gap, 0+ ox, oy = x - e[0], y - e[1]+ ox, oy = round(ox / 5) * 5, round(oy / 5) * 5+ placed.append((it, ox, oy))+ x += w + gap+ row_h = max(row_h, h)+ width = max(width, x)+ H = y + row_h + pad+ dr = {"id": f"auto-{block}", "block": block, "title": title, "_auto": True, "w": int(max(320, min(W, width + pad))), "h": int(H + 10),+ "text": "Auto-drawn: every pin labelled with its net. The textbook drawing of this block is still to be drawn (explorer/<id>.json).",+ "parts": [], "wires": [], "gnd": [], "rails": [], "flags": []}+ for it, ox, oy in placed:+ opt = ("r90" if it["rot"] == 90 else "") + (" lr" if not it["big"] else "")+ if it["box"]:+ dr["parts"].append([it["ref"], ox, oy, opt.strip(), {"box": it["box"]}])+ else:+ dr["parts"].append([it["ref"], ox, oy, opt.strip()])+ for kind, at, net, d in it["anchors"]:+ if kind == "gnd":+ dr["gnd"].append([at, d, net])+ elif kind == "rail":+ dr["rails"].append([at, net, d])+ else:+ dr["flags"].append([at, net, d])+ return dr+++# --------------------------------------------------------------------------- the explorer: drawings, proof, flow++def humanize(b):+ return b.upper() if len(b) <= 4 else b.replace("_", " ").replace("-", " ").capitalize()+++def furniture(dp, spec):+ """A part with no MPN whose pins all sit on one ground net (a corner machine pin): nothing to draw."""+ nets = set(dp["pins"].values())+ return not dp.get("mpn") and len(nets) == 1 and is_ground(next(iter(nets)), spec)+++def load_drawings(explorer_dir):+ out, errors = [], []+ if not explorer_dir or not os.path.isdir(explorer_dir):+ return out, errors+ for f in sorted(os.listdir(explorer_dir)):+ if not f.endswith(".json") or f in ("blocks.json", "symbols.json", "design.json"):+ continue+ p = os.path.join(explorer_dir, f)+ try:+ with open(p) as fh:+ d = json.load(fh)+ except ValueError as e:+ errors.append(f"{f}: not JSON ({e})")+ continue+ if not isinstance(d, dict) or not d.get("block"):+ errors.append(f"{f}: a drawing needs \"block\" (the netlist block it draws)")+ continue+ d.setdefault("id", f[:-5])+ d["_auto"] = bool(d.pop("auto", False))+ d["_file"] = f+ d["_sha256"] = sha(p)+ out.append(d)+ return out, errors+++def explorer_build(design, explorer_dir, spec, scaffold=True):+ """The drawings (hand-drawn, else auto), each checked; coverage; the flow chart. Returns (data, proof)."""+ SYM = symbols()+ cfg = rjson(os.path.join(explorer_dir, "blocks.json"), {}) if explorer_dir else {}+ cfg = cfg if isinstance(cfg, dict) else {}+ overrides = {}+ for k, v in (cfg.get("symbols") or {}).items():+ overrides[k] = v+ for ref, dp in design["parts"].items(): # a netlist "part" key (FET, R10K) names every part of that kind+ if k not in design["parts"] and dp.get("partKey") == k:+ overrides.setdefault(ref, v)+ blocks = design["blocks"]+ by_block = {b: [r for r, p in design["parts"].items() if p["block"] == b] for b in blocks}+ meta = cfg.get("blocks") or {}+ hand, load_errors = load_drawings(explorer_dir)+ have = {d["block"] for d in hand}+ hand_blocks = {d["block"] for d in hand if not d.get("_auto")}+ drawings = []+ for d in hand:+ if d["block"] not in by_block:+ load_errors.append(f"{d['_file']}: block {d['block']} is not a block of the netlist ({', '.join(blocks)})")+ continue+ drawings.append(d)+ auto = []+ for b in blocks:+ if b in have:+ continue+ refs = [r for r in by_block[b] if not furniture(design["parts"][r], spec)]+ if not refs:+ continue+ auto.append(auto_drawing(b, refs, design, overrides, SYM, spec, (meta.get(b) or {}).get("title") or humanize(b)))+ if explorer_dir and scaffold:+ os.makedirs(os.path.join(explorer_dir, "auto"), exist_ok=True)+ for f in os.listdir(os.path.join(explorer_dir, "auto")):+ if f.endswith(".json"):+ os.remove(os.path.join(explorer_dir, "auto", f))+ for d in auto:+ wjson(os.path.join(explorer_dir, "auto", d["block"] + ".json"), {k: v for k, v in d.items() if k != "_auto"})+ bp = os.path.join(explorer_dir, "blocks.json")+ if not os.path.isfile(bp):+ wjson(bp, {"_": "Circuit explorer source (adom-aiflow project-page). blocks: a title and one or two sentences per netlist block. flow: optional node positions {block: [x, y]} and edges [{from, to, label}] for the block flowchart. symbols: optional {ref or MPN: {sym, map} | {box}}. Drawings: <id>.json with \"block\"; auto/ holds the auto-drawn fallback, rewritten every build.",+ "blocks": {b: {"title": humanize(b), "text": ""} for b in blocks}, "flow": {}, "symbols": {}})+ drawings += auto+ models, all_errors, all_warns = [], list(load_errors), []+ drawn_parts, drawn_pins = set(), {}+ for d in drawings:+ A = analyze(d, design, overrides, SYM)+ all_errors += A["errors"]+ all_warns += A["warns"]+ m = render_model(d, A, design)+ m["file"] = d.get("_file") or f"auto/{d['block']}.json"+ m["sha256"] = d.get("_sha256") or sha_bytes(json.dumps(d, sort_keys=True).encode())+ m["errors"] = A["errors"]+ models.append(m)+ for p in A["parts"]:+ drawn_parts.add(p["ref"])+ for i in p["pins"].values():+ drawn_pins.setdefault(p["ref"], set()).update(i["nums"])+ required = [r for r, dp in design["parts"].items() if not furniture(dp, spec)]+ exempt = sorted(set(design["parts"]) - set(required), key=_numkey)+ missing = sorted([r for r in required if r not in drawn_parts], key=_numkey)+ pin_missing, pin_req, pin_drawn = [], 0, 0+ for r in required:+ if r not in drawn_parts:+ continue+ for n, net in design["parts"][r]["pins"].items():+ if net is None:+ continue+ pin_req += 1+ if n in drawn_pins.get(r, set()):+ pin_drawn += 1+ else:+ pin_missing.append(f"{r}.{n} ({net})")+ diffs = len(all_errors) + len(pin_missing)+ cov = 100.0 * (len(required) - len(missing)) / len(required) if required else 100.0+ proof = {"schema": PROOF_SCHEMA, "netlist": design["source"], "drawings": [{"id": m["id"], "block": m["block"], "file": m["file"], "sha256": m["sha256"],+ "auto": m["auto"], "parts": len(m["parts"]), "wires": len(m["wires"]), "errors": m["errors"]} for m in models],+ "coverage": {"percent": round(cov, 2), "parts": {"required": len(required), "drawn": len(required) - len(missing), "missing": missing,+ "exempt": exempt, "exemptWhy": "no MPN and every pin on one ground net (corner machine pins)"},+ "pins": {"required": pin_req, "drawn": pin_drawn, "missing": pin_missing}},+ "diffs": diffs, "differences": all_errors + [f"pin not drawn in any block: {p}" for p in pin_missing], "warnings": all_warns,+ "handDrawn": len([m for m in models if not m["auto"]]), "autoDrawn": len([m for m in models if m["auto"]]),+ "blocks": {b: {"drawings": [m["id"] for m in models if m["block"] == b], "auto": b not in hand_blocks} for b in blocks}}+ flow = flowchart(design, blocks, by_block, cfg.get("flow") or {}, meta, spec, models)+ parts_js = {r: {"value": p.get("value"), "mpn": p.get("mpn"), "mfr": p.get("mfr"), "desc": p.get("desc"), "note": p.get("note"),+ "page": p.get("page"), "block": p["block"]} for r, p in design["parts"].items()}+ data = {"parts": parts_js, "drawings": models, "flow": flow,+ "blocks": [{"id": b, "title": (meta.get(b) or {}).get("title") or humanize(b), "text": (meta.get(b) or {}).get("text") or "",+ "parts": sorted(by_block[b], key=_numkey), "drawings": [m["id"] for m in models if m["block"] == b],+ "auto": b not in hand_blocks} for b in blocks],+ "proof": {"coverage": proof["coverage"]["percent"], "diffs": diffs, "parts": len(required) - len(missing), "required": len(required),+ "pins": pin_drawn, "pinsRequired": pin_req, "hand": proof["handDrawn"], "auto": proof["autoDrawn"]}}+ return data, proof, drawings+++def compress_nets(nets):+ """GHA GHB GHC -> GH A/B/C; a short label for an edge."""+ groups = {}+ for n in sorted(nets):+ m = re.match(r"^(.*?)([A-Za-z0-9])$", n)+ stem = m.group(1) if m and len(n) > 2 else n+ groups.setdefault(stem, []).append(n)+ out = []+ for stem, ns in groups.items():+ if len(ns) > 1 and stem:+ out.append(stem.rstrip("_") + " " + "/".join(x[len(stem):] for x in ns))+ else:+ out.extend(ns)+ return out+++INTERFACE_RE = re.compile(r"^(MC|MP|J|P|CN|CON|X|H)\d+$")+++FLOW_MAX_BLOCKS = 15 # issue #198: past this a flowchart stops being readable+++def flowchart(design, blocks, by_block, fcfg, meta, spec, models):+ """Blocks as boxes, the nets between blocks as labelled arrows. Direction from the schematic's pin types: an+ output or power_out pin drives; a bidirectional pin drives only inputs; among passive pins the earlier block in+ the netlist wins, except a contacts block (connectors, machine contacts), which drives a net only when an input+ elsewhere reads it. A contacts block that also receives nets is drawn twice: inputs on the left, outputs on the+ right. Layered left to right (longest path, cycles broken in netlist order); explorer/blocks.json "flow"+ overrides positions ({block: [x, y]}) and edges ([{from, to, label}])."""+ order = {b: i for i, b in enumerate(blocks)}+ probe = {b for b in blocks if by_block[b] and all(re.match(r"TP\d", r) for r in by_block[b])}+ iface = {b for b in blocks if b not in probe and by_block[b] and all(INTERFACE_RE.match(r) or re.match(r"TP\d", r) for r in by_block[b])}+ net_pins = {}+ for r, p in design["parts"].items():+ if p["block"] in probe:+ continue+ types = {x["num"]: x["type"] for x in p.get("schPins") or []}+ for n, net in p["pins"].items():+ if net and not is_ground(net, spec):+ net_pins.setdefault(net, []).append((p["block"], types.get(n, "passive")))+ loads = {norm_net(k) for k, v in ((spec or {}).get("loads") or {}).items() if isinstance(v, dict) and (v.get("amps") or 0) > 0}+ pairs, strength = {}, {}+ for net, pins in net_pins.items():+ bl = sorted({b for b, _ in pins}, key=lambda b: order[b])+ if len(bl) < 2:+ continue+ reads = any(ty in ("input", "power_in", "bidirectional") for b, ty in pins if b not in iface)+ score = {}+ for b in bl:+ s = 0.0+ for bb, ty in pins:+ if bb != b:+ continue+ if ty in ("output", "power_out"):+ v = 4+ elif ty in ("bidirectional", "tri_state", "open_collector", "open_emitter"):+ others = [t2 for b2, t2 in pins if b2 != b]+ v = 2 if others and all(t2 in ("input", "power_in") for t2 in others) else 0.5+ elif ty in ("input", "power_in"):+ v = 0+ else:+ v = 1+ s = max(s, v)+ if b in iface and s <= 1:+ # a contact drives what the board reads, and a supply; a load net that is no supply leaves the board+ s = 0.9 if (not reads and net in loads and not supply_like(net)) else 1.5+ score[b] = s+ src = sorted(bl, key=lambda b: (-score[b], order[b]))[0]+ for b in bl:+ if b != src:+ pairs.setdefault((src, b), []).append(net)+ strength[(src, b)] = max(strength.get((src, b), 0), score[src])+ edges = [{"from": a, "to": b, "nets": sorted(ns)} for (a, b), ns in pairs.items()]+ if fcfg.get("edges"):+ given = []+ for e in fcfg["edges"]:+ if e.get("from") in order and e.get("to") in order:+ ns = e.get("nets") or pairs.get((e["from"], e["to"])) or pairs.get((e["to"], e["from"])) or []+ given.append({"from": e["from"], "to": e["to"], "nets": sorted(ns), "label": e.get("label")})+ edges = given+ for e in edges:+ if not e.get("label"):+ c = compress_nets(e["nets"])+ e["label"] = ", ".join(c[:3]) + (f" +{len(c) - 3}" if len(c) > 3 else "")+ # a contacts block that receives nets gets a second node on the right+ split = {b for b in iface if any(e["to"] == b for e in edges) and any(e["from"] == b for e in edges)}+ for e in edges:+ e["fromNode"] = e["from"]+ e["toNode"] = e["to"] + ":out" if e["to"] in split else e["to"]+ nodes_ids = list(blocks) + [b + ":out" for b in blocks if b in split]+ # two flows, as an engineer draws them: the supplies along the top (blocks whose only outputs are supply nets),+ # the signal chain below, left to right. Signal edges are layered by longest path, cycles broken at their+ # weakest edge (edges join strongest first, an output driving inputs before a passive divider feeding back).+ supply_net = {n for n, pins in net_pins.items() if supply_like(n) or any(ty == "power_out" for _, ty in pins)}+ for e in edges:+ e["supply"] = bool(e["nets"]) and all(n in supply_net for n in e["nets"])+ sig = [e for e in edges if not e["supply"]]+ touched = {e["fromNode"] for e in sig} | {e["toNode"] for e in sig}+ rail = [n for n in nodes_ids if n not in touched and n.split(":")[0] not in iface and n.split(":")[0] not in probe+ and any(e["fromNode"] == n or e["toNode"] == n for e in edges)]+ keep = set()++ def reaches(u, v, es):+ seen, stack = set(), [u]+ while stack:+ x = stack.pop()+ if x == v:+ return True+ if x in seen:+ continue+ seen.add(x)+ stack.extend(w for (y, w) in es if y == x)+ return False+ for e in sorted(sig, key=lambda e: (-strength.get((e["from"], e["to"]), 1), order[e["from"]], order[e["to"]])):+ u, v = e["fromNode"], e["toNode"]+ if u != v and not reaches(v, u, keep):+ keep.add((u, v))+ layer = {n: 0 for n in nodes_ids}+ for _ in range(len(nodes_ids) + 1):+ changed = False+ for u, v in keep:+ if layer[v] < layer[u] + 1:+ layer[v] = layer[u] + 1+ changed = True+ if not changed:+ break+ last = max([layer[n] for n in nodes_ids if n not in rail] or [0])+ for n in nodes_ids:+ if n.endswith(":out") or n.split(":")[0] in probe:+ layer[n] = max(last, 1)+ # the supply row: in supply order (a supply fed by another comes after it), from the second column+ sk = set()+ for e in edges:+ if e["supply"] and e["fromNode"] in rail and e["toNode"] in rail and not reaches(e["toNode"], e["fromNode"], sk):+ sk.add((e["fromNode"], e["toNode"]))+ depth = {n: 0 for n in rail}+ for _ in range(len(rail) + 1):+ for u, v in sk:+ depth[v] = max(depth[v], depth[u] + 1)+ rail.sort(key=lambda n: (depth[n], order[n.split(":")[0]]))+ NW, NH, CG, RG = 150, 58, 64, 26+ pos = {}+ for i, n in enumerate(rail):+ pos[n] = [20 + (i + (1 if len(rail) < max(last, 1) + 1 else 0)) * (NW + CG), 20]+ top = 20 + (NH + 46 if rail else 0)+ cols = {}+ for n in nodes_ids:+ if n not in rail:+ cols.setdefault(layer[n], []).append(n)+ for c in sorted(cols):+ ns = cols[c]+ def bary(n):+ ys = [pos[e["fromNode"]][1] for e in sig if e["toNode"] == n and e["fromNode"] in pos]+ return (sum(ys) / len(ys)) if ys else 1e9 + order[n.split(":")[0]]+ ns.sort(key=lambda n: (n.split(":")[0] in probe, bary(n), order[n.split(":")[0]]))+ for i, n in enumerate(ns):+ pos[n] = [20 + c * (NW + CG), top + i * (NH + RG)]+ for b, xy in (fcfg.get("nodes") or {}).items():+ if b in pos and isinstance(xy, list) and len(xy) >= 2:+ pos[b] = [xy[0], xy[1]]+ nodes = []+ for n in nodes_ids:+ b = n.split(":")[0]+ title = (meta.get(b) or {}).get("title") or humanize(b)+ k = len(by_block[b])+ hand = any(m["block"] == b and not m["auto"] for m in models)+ sub = f"{k} part{'s' if k != 1 else ''}" + ("" if hand else ", auto-drawn")+ if b in split:+ sub = ("outputs" if n.endswith(":out") else "inputs") + ", " + sub+ nodes.append({"id": n, "block": b, "x": pos[n][0], "y": pos[n][1], "w": NW, "h": NH, "title": title, "sub": sub, "probe": b in probe, "hand": hand})+ W = max(n["x"] + n["w"] for n in nodes) + 20 if nodes else 400+ H = max(n["y"] + n["h"] for n in nodes) + 46 if nodes else 200+ return {"w": W, "h": H, "nodes": nodes, "edges": edges}+++# --------------------------------------------------------------------------- board renders and contacts++def kicad_cli():+ return os.environ.get("ADOM_AIFLOW_KICAD_CLI") or shutil.which("kicad-cli")+++def board_renders(board_path, out_dir, work):+ """Top and bottom pictures from kicad-cli's per-layer SVGs, composed as the board looks: mask over copper,+ exposed pads gold, silkscreen white. Returns ({side: file}, note)."""+ kc = kicad_cli()+ if not kc:+ return {}, "no kicad-cli (set ADOM_AIFLOW_KICAD_CLI): board renders skipped"+ try:+ import cairosvg+ from PIL import Image, ImageChops, ImageDraw+ except ImportError as e:+ return {}, f"board renders need cairosvg and Pillow ({e})"+ svg = os.path.join(work, "svg")+ shutil.rmtree(svg, ignore_errors=True)+ os.makedirs(svg)+ src = os.path.join(work, "render-board.kicad_pcb")+ shutil.copy(board_path, src)+ p = subprocess.run([kc, "pcb", "export", "svg", "--mode-multi", "-o", svg, "-l", "F.Cu,B.Cu,F.Mask,B.Mask,F.Silkscreen,B.Silkscreen,Edge.Cuts",+ "--black-and-white", "--page-size-mode", "2", "--exclude-drawing-sheet", "--drill-shape-opt", "2", src],+ capture_output=True, text=True, stdin=subprocess.DEVNULL, timeout=600)+ files = os.listdir(svg) if os.path.isdir(svg) else []+ if p.returncode != 0 or not files:+ return {}, f"kicad-cli pcb export svg failed: {(p.stderr or p.stdout).strip()[:300]}"+ W = 1400++ def mask(layer):+ f = [x for x in files if x.endswith("-" + layer + ".svg")]+ if not f:+ return None+ png = cairosvg.svg2png(url=os.path.join(svg, f[0]), output_width=W, background_color="white")+ return ImageChops.invert(Image.open(io.BytesIO(png)).convert("L"))++ out = {}+ os.makedirs(out_dir, exist_ok=True)+ edge = mask("Edge_Cuts")+ if edge is None:+ return {}, "the board has no Edge.Cuts outline to render"+ pad = 24+ E = Image.new("L", (edge.size[0] + 2 * pad, edge.size[1] + 2 * pad), 0)+ E.paste(edge, (pad, pad))+ ImageDraw.floodfill(E, (1, 1), 128, thresh=60)+ board = E.point(lambda v: 0 if v == 128 else 255)+ for side, cu, mk, silk in (("top", "F_Cu", "F_Mask", "F_Silkscreen"), ("bottom", "B_Cu", "B_Mask", "B_Silkscreen")):+ def P(im):+ X = Image.new("L", board.size, 0)+ if im is not None:+ X.paste(im, (pad, pad))+ return X+ c, m, s = P(mask(cu)), P(mask(mk)), P(mask(silk))+ img = Image.new("RGBA", board.size, (0, 0, 0, 0))+ lay = lambda color, msk: img.paste(Image.new("RGBA", board.size, color), (0, 0), msk)+ lay((20, 60, 38, 255), board)+ lay((44, 110, 64, 255), ImageChops.multiply(c, board))+ lay((214, 176, 92, 255), ImageChops.multiply(c, m))+ lay((236, 240, 236, 255), ImageChops.multiply(s, board))+ if side == "bottom":+ img = img.transpose(Image.FLIP_LEFT_RIGHT)+ f = os.path.join(out_dir, f"{side}.png")+ img.save(f, optimize=True)+ out[side] = f+ return out, None+++def contacts(design, board, spec):+ """MP<n> / MC<n>: net, class (large or medium, from the footprint), wire gauge, position from MP1 (y up)."""+ fps = {fp["ref"]: fp for fp in board["footprints"]} if board else {}+ mp1 = fps.get("MP1")+ rows = []+ refs = sorted([r for r in set(fps) | set(design["parts"]) if re.fullmatch(r"M[CP]\d+", r)], key=_numkey)+ for r in refs:+ fp = fps.get(r) or {}+ dp = design["parts"].get(r) or {}+ lib = " ".join([fp.get("lib", ""), dp.get("footprint", ""), dp.get("value", ""), dp.get("package", "")])+ cls = "large" if re.search(r"large", lib, re.I) else "medium" if re.search(r"medium", lib, re.I) else ""+ if not cls and r.startswith("MP"):+ pin = str(((spec or {}).get("molecule") or {}).get("pin") or "")+ cls = "large" if "arge" in pin else "medium" if pin else ""+ nets = sorted({n for n in (fp.get("pads") or {}).values() if n} | {n for n in (dp.get("pins") or {}).values() if n})+ at = None+ if fp and mp1:+ at = [round(fp["x"] - mp1["x"], 2), round(mp1["y"] - fp["y"], 2)]+ rows.append({"ref": r, "kind": "pin" if r.startswith("MP") else "contact", "net": ", ".join(nets), "class": cls,+ "gauge": GAUGE.get(cls, ""), "at": at, "use": dp.get("note") or dp.get("desc") or ""})+ return rows+++# --------------------------------------------------------------------------- simulation (Fields, current, thermal)++SURF, INK, INK2, LINE = "#0d1117", "#e6edf3", "#8b949e", "#30363d"+++def fields_report(run, cfg):+ """(fields.json, detail, its folder, solved board path) of the run's latest Fields solve, or Nones."""+ cands = []+ if cfg.get("fields"):+ cands.append(cfg["fields"])+ o = run.get("outcomes") or {}+ for k in ("analyze-current", "analyze-thermal"):+ fr = (o.get(k) or {}).get("fieldReport")+ if fr:+ cands.append(fr if os.path.isabs(fr) else os.path.join(cfg["run"], fr))+ cands.append(fr)+ for s in reversed(run.get("fieldsSolves") or []):+ if s.get("file"):+ cands.append(s["file"])+ cands.append(os.path.join(cfg["run"], "fields", "fields.json"))+ for c in cands:+ if c and os.path.isfile(c):+ f = rjson(c)+ if isinstance(f, dict) and f.get("board"):+ b = (f.get("source") or {}).get("board")+ return f, os.path.dirname(os.path.abspath(c)), (b if b and os.path.isfile(b) else None), c+ return None, None, None, None+++def fields_figures(f, fdir, out_dir, spec):+ """fig_current.png (current density per copper layer, the screen as a dashed contour, the necks circled) and+ fig_temperature.png (rise over the board in still and moving air, the hot parts marked) from the solve's+ textures. Returns ([(file, shows)], note)."""+ try:+ import numpy as np+ from PIL import Image+ import matplotlib+ matplotlib.use("Agg")+ import matplotlib.pyplot as plt+ from matplotlib.colors import LinearSegmentedColormap+ except ImportError as e:+ return [], f"figures need numpy, Pillow and matplotlib ({e})"+ b = f["board"]+ ext = [b["x0"], b["x0"] + b["cols"] * b["cellMm"], b["y0"] + b["rows"] * b["cellMm"], b["y0"]]+ layers = [l for l in b.get("copperLayers") or ["F.Cu", "B.Cu"]]+ sc = f.get("scales") or {}+ tex = os.path.join(fdir, "tex")+ HEAT = LinearSegmentedColormap.from_list("heat", [SURF, "#4a1d0c", "#a8401a", "#eb6834", "#f6a37f", "#fde3d6"])+ CURR = LinearSegmentedColormap.from_list("curr", [SURF, "#0d366b", "#1c5cab", "#3987e5", "#86b6ef", "#cde2fb"])+ out = []+ os.makedirs(out_dir, exist_ok=True)++ def raw(kind, lay):+ p = os.path.join(tex, f"{kind}-{lay.replace('.', '_')}.raw.png")+ return np.array(Image.open(p)).astype(float) / 65535.0 if os.path.isfile(p) else None++ def style(ax):+ ax.set_facecolor(SURF)+ ax.set_xlim(ext[0], ext[1]); ax.set_ylim(ext[2], ext[3])+ ax.set_xticks([]); ax.set_yticks([])+ for s in ax.spines.values():+ s.set_color(LINE)++ def edges(ax, lay):+ p = os.path.join(tex, f"copper-{lay.replace('.', '_')}.png")+ if os.path.isfile(p):+ cu = np.array(Image.open(p).convert("L")).astype(float)+ ax.contour(np.linspace(ext[0], ext[1], cu.shape[1]), np.linspace(ext[3], ext[2], cu.shape[0]), cu, levels=[128], colors=LINE, linewidths=0.5)++ screen = 60.0+ for k in ("currentDensityScreen", "jScreen", "maxCurrentDensity"):+ if isinstance(spec, dict) and isinstance(spec.get(k), (int, float)):+ screen = float(spec[k])+ necks = [i for i in f.get("issues") or [] if i.get("kind") == "current-neck" and i.get("at")]+ maps = [(l, raw("J", l)) for l in layers]+ maps = [(l, m * float(sc.get("jHi") or sc.get("jMax") or 0)) for l, m in maps if m is not None]+ if maps:+ vmax = max(screen * 2.5, min(float(sc.get("jMax") or screen * 2), screen * 5))+ fig, axs = plt.subplots(1, len(maps), figsize=(5.2 * len(maps) + 1.2, 5.2), dpi=120, facecolor=SURF, squeeze=False)+ im = None+ for ax, (lay, J) in zip(axs[0], maps):+ style(ax)+ im = ax.imshow(np.clip(J, 0, vmax), cmap=CURR, vmin=0, vmax=vmax, extent=ext, interpolation="bilinear")+ if J.max() > screen:+ ax.contour(np.linspace(ext[0], ext[1], J.shape[1]), np.linspace(ext[3], ext[2], J.shape[0]), J, levels=[screen], colors=INK2, linewidths=0.6, linestyles="dashed")+ edges(ax, lay)+ for n in necks:+ if n.get("layer") == lay:+ x, y = n["at"]+ ax.plot(x, y, marker="o", ms=10, mfc="none", mec=INK, mew=1.3)+ ax.annotate(n.get("net") or "", (x, y), xytext=(7, -11), textcoords="offset points", color=INK, fontsize=9)+ ax.set_title(lay, color=INK, fontsize=10, pad=6)+ cb = fig.colorbar(im, ax=axs[0].tolist(), shrink=0.85, pad=0.015)+ cb.set_label(f"Current density, A/mm² (dashed: the {screen:g} A/mm² screen)", color=INK2)+ cb.ax.tick_params(colors=INK2); cb.outline.set_edgecolor(LINE)+ loads = sorted({round(n.get("amps") or 0, 2) for n in f.get("nets") or [] if (n.get("amps") or 0) >= 0.5})+ p = os.path.join(out_dir, "fig_current.png")+ fig.savefig(p, facecolor=SURF, bbox_inches="tight")+ plt.close(fig)+ out.append((p, "Fields current density"))+ tmaps = []+ for kind, label in (("T", "Still air"), ("Tm", "Moving air")):+ ms = [raw(kind, l) for l in layers]+ ms = [m for m in ms if m is not None]+ if ms:+ m = np.maximum.reduce(ms) * float(sc.get("tHi") or sc.get("tMax") or 0)+ tmaps.append((label, m))+ if tmaps:+ heat = f.get("heat") or {}+ hi = max(float(m.max()) for _, m in tmaps)+ fig, axs = plt.subplots(1, len(tmaps), figsize=(5.2 * len(tmaps) + 1.2, 5.2), dpi=120, facecolor=SURF, squeeze=False)+ im = None+ chips = sorted(f.get("chips") or [], key=lambda c: -(c.get("riseC") or 0))+ for ax, (label, m) in zip(axs[0], tmaps):+ style(ax)+ im = ax.imshow(m, cmap=HEAT, vmin=0, vmax=hi, extent=ext, interpolation="bilinear")+ edges(ax, layers[0])+ key = "riseC" if label == "Still air" else "riseMovingC"+ put = []+ for i, c in enumerate(chips):+ if c.get("x") is None:+ continue+ ax.plot(c["x"], c["y"], marker="s", ms=6, mfc="none", mec=INK2, mew=0.9)+ near = [q for q in put if abs(q[0] - c["x"]) < (ext[1] - ext[0]) * 0.22 and abs(q[1] - c["y"]) < (ext[2] - ext[3]) * 0.06]+ if i < 5 and not near:+ put.append((c["x"], c["y"]))+ ax.annotate(f"{c.get('reference')} +{(c.get(key) or 0):.0f} °C", (c["x"], c["y"]), xytext=(-4, 8), textcoords="offset points",+ color=INK, fontsize=8.5, ha="right" if c["x"] > (ext[0] + ext[1]) / 2 else "left",+ bbox=dict(boxstyle="round,pad=0.2", fc=SURF, ec="none", alpha=0.7))+ peak = heat.get("peakRiseC") if label == "Still air" else heat.get("peakRiseMovingC")+ coef = heat.get("stillAirWPerM2K") if label == "Still air" else heat.get("movingAirWPerM2K")+ ax.set_title(f"{label}" + (f" ({coef:g} W/m²K)" if coef else "") + (f", peak +{peak:.0f} °C" if peak is not None else ""), color=INK, fontsize=10, pad=6)+ cb = fig.colorbar(im, ax=axs[0].tolist(), shrink=0.85, pad=0.015)+ cb.set_label("Temperature rise over ambient, °C" + (f" (budget +{heat['budgetC']:g} °C)" if heat.get("budgetC") else ""), color=INK2)+ cb.ax.tick_params(colors=INK2); cb.outline.set_edgecolor(LINE)+ p = os.path.join(out_dir, "fig_temperature.png")+ fig.savefig(p, facecolor=SURF, bbox_inches="tight")+ plt.close(fig)+ out.append((p, "Fields temperature rise"))+ return out, None if out else "the Fields solve has no textures (tex/*.raw.png) to draw"+++def load_sweep(path):+ """A rating sweep: {"<amps>": {peakStill, peakMoving, parts: {ref: rise | [still, moving]}}}."""+ s = rjson(path)+ if not isinstance(s, dict):+ return None+ rows = []+ for k, v in s.items():+ try:+ a = float(k)+ except ValueError:+ continue+ if not isinstance(v, dict):+ continue+ parts = {}+ for r, x in (v.get("parts") or {}).items():+ parts[r] = x if isinstance(x, list) else [x, None]+ rows.append({"amps": a, "still": v.get("peakStill"), "moving": v.get("peakMoving"), "j": v.get("rtnPeakJ") or v.get("peakJ"), "parts": parts})+ rows.sort(key=lambda r: r["amps"])+ return rows or None+++def at_rise(rows, key, limit):+ """The current where the peak rise reaches the limit (linear between sweep points), or a bound."""+ pts = [(r["amps"], r[key]) for r in rows if isinstance(r.get(key), (int, float))]+ if not pts:+ return None+ for (a0, t0), (a1, t1) in zip(pts, pts[1:]):+ if t0 <= limit <= t1 and t1 != t0:+ return ("=", a0 + (limit - t0) * (a1 - a0) / (t1 - t0))+ if pts[0][1] > limit:+ return ("<", pts[0][0])+ return (">", pts[-1][0])+++def sweep_figure(rows, budget, out_dir):+ try:+ import matplotlib+ matplotlib.use("Agg")+ import matplotlib.pyplot as plt+ except ImportError:+ return None+ a = [r["amps"] for r in rows]+ fig, ax = plt.subplots(figsize=(7.5, 4.2), dpi=110, facecolor=SURF)+ ax.set_facecolor(SURF)+ for key, label, color in (("still", "Still air", "#eb6834"), ("moving", "Moving air", "#3987e5")):+ ys = [r[key] for r in rows]+ if any(isinstance(y, (int, float)) for y in ys):+ ax.plot(a, ys, marker="o", color=color, label=label, lw=1.8)+ if budget:+ ax.axhline(budget, color=INK2, ls="--", lw=0.9)+ ax.annotate(f"budget +{budget:g} °C", (a[0], budget), xytext=(2, 4), textcoords="offset points", color=INK2, fontsize=9)+ ax.set_xlabel("Load current, A", color=INK2); ax.set_ylabel("Peak rise, °C", color=INK2)+ ax.tick_params(colors=INK2)+ for s in ax.spines.values():+ s.set_color(LINE)+ ax.grid(color=LINE, lw=0.5)+ lg = ax.legend(facecolor=SURF, edgecolor=LINE)+ for t in lg.get_texts():+ t.set_color(INK)+ ax.set_title("Peak temperature rise against load current (Fields rating sweep)", color=INK, fontsize=11)+ p = os.path.join(out_dir, "fig_rating.png")+ fig.savefig(p, facecolor=SURF, bbox_inches="tight")+ plt.close(fig)+ return p+++def simulation_numbers(run, f, sweeps, budget_default):+ o = run.get("outcomes") or {}+ n = {"solved": bool(f)}+ if f:+ heat = f.get("heat") or {}+ nets = sorted(f.get("nets") or [], key=lambda x: -(x.get("peakJ") or 0))+ n.update({"solver": ((f.get("inputIdentity") or {}).get("solverVersion")), "boardSha256": (f.get("inputIdentity") or {}).get("board"),+ "jouleW": heat.get("jouleW"), "tabW": heat.get("tabW"), "peakRise": heat.get("peakRiseC"), "peakRiseMoving": heat.get("peakRiseMovingC"),+ "budget": heat.get("budgetC") or budget_default, "still": heat.get("stillAirWPerM2K"), "moving": heat.get("movingAirWPerM2K"),+ "jMax": nets[0].get("peakJ") if nets else (f.get("scales") or {}).get("jMax"), "jNet": nets[0].get("net") if nets else None,+ "jLayer": nets[0].get("peakLayer") if nets else None,+ "loads": [{"net": x.get("net"), "amps": x.get("amps"), "peakJ": x.get("peakJ"), "layer": x.get("peakLayer"), "jouleW": x.get("jouleW")}+ for x in nets if (x.get("amps") or 0) >= 0.5],+ "chips": [{"ref": c.get("reference"), "watts": c.get("watts"), "rise": c.get("riseC"), "riseMoving": c.get("riseMovingC"), "tab": c.get("tabNet")}+ for c in sorted(f.get("chips") or [], key=lambda c: -(c.get("riseC") or 0))],+ "necks": [{"net": i.get("net"), "layer": i.get("layer"), "at": i.get("at"), "what": i.get("what"), "severity": i.get("severity")}+ for i in f.get("issues") or [] if i.get("kind") == "current-neck"],+ "issues": len(f.get("issues") or []), "method": f.get("method")})+ for k, label in (("analyze-current", "current"), ("analyze-thermal", "thermal")):+ x = o.get(k)+ if x:+ n[label] = {"pass": x.get("pass"), "note": x.get("fieldNote"), "fails": [r.get("net") or r.get("ref") for r in x.get("results") or [] if r.get("status") == "fail"]}+ n["sweeps"] = []+ for p in sweeps:+ rows = load_sweep(p)+ if rows:+ b = n.get("budget") or budget_default+ n["sweeps"].append({"file": p, "rows": rows, "atBudgetStill": at_rise(rows, "still", b), "atBudgetMoving": at_rise(rows, "moving", b)})+ return n+++def fmt(v, nd=1, unit=""):+ if v is None:+ return "not solved"+ if isinstance(v, (int, float)):+ s = f"{v:.{nd}f}".rstrip("0").rstrip(".") if nd else f"{v:.0f}"+ return s + unit+ return str(v)+++# --------------------------------------------------------------------------- components (the cool BOM)++def read_bom(path):+ if not path or not os.path.isfile(path):+ return [], []+ with open(path, newline="", encoding="utf-8-sig") as fh:+ r = csv.DictReader(fh)+ rows = list(r)+ return rows, r.fieldnames or []+++def col(fields, *pats):+ for pat in pats:+ for f in fields:+ if re.fullmatch(pat, f.strip(), re.I):+ return f+ return None+++def money(v):+ if v is None:+ return None+ m = re.search(r"-?\d+(?:[.,]\d+)?", str(v).replace(",", ""))+ try:+ return float(m.group(0)) if m else None+ except ValueError:+ return None+++def bom_lines(bom_path, design, run):+ """One line per BOM row with an MPN: refs, qty, value, MPN, maker, wiki page, role, unit price (the BOM's or the+ sourcing outcome's; never guessed), stock and its date, source."""+ rows, fields = read_bom(bom_path)+ c_refs = col(fields, r"refs?", r"references?", r"designators?", r"reference designators?")+ c_qty = col(fields, r"qty", r"quantity", r"count")+ c_val = col(fields, r"value", r"val")+ c_mpn = col(fields, r"mpn", r"manufacturer part number", r"mfr ?part ?(number|no\.?|#)?", r"part ?number")+ c_mfr = col(fields, r"manufacturer", r"mfr", r"maker", r"vendor")+ c_wiki = col(fields, r"wiki", r"page", r"wiki ?page")+ c_role = col(fields, r"role", r"function", r"purpose", r"use")+ c_note = col(fields, r"notes?", r"comments?")+ c_price = col(fields, r"unit[ _-]?price.*", r"price[ _-]?(usd|each|1|unit)?", r"(mouser|digikey|lcsc)[ _-]?price.*", r"cost")+ c_stock = col(fields, r"stock.*", r".*stock.*")+ c_src = col(fields, r"source", r"supplier", r"distributor")+ stock_date = None+ if c_stock:+ m = re.search(r"\d{4}-\d{2}-\d{2}", c_stock)+ stock_date = m.group(0) if m else None+ prices = {}+ srec = (run.get("outcomes") or {}).get("sourcing") or {}+ for x in srec.get("rows") if isinstance(srec.get("rows"), list) else []:+ if isinstance(x, dict) and x.get("mpn") and money(x.get("unitPrice") or x.get("price")) is not None:+ prices[x["mpn"].upper()] = money(x.get("unitPrice") or x.get("price"))+ out = []+ for r in rows:+ mpn = (r.get(c_mpn) or "").strip() if c_mpn else ""+ refs = re.split(r"[\s,;]+", (r.get(c_refs) or "").strip()) if c_refs else []+ refs = [x for x in refs if x]+ if not mpn or re.fullmatch(r"(no part|n/?a|none|-|dnp|tbd)", mpn, re.I):+ out.append({"feature": True, "refs": refs, "value": r.get(c_val, "") if c_val else "", "mfr": r.get(c_mfr, "") if c_mfr else ""})+ continue+ qty = int(money(r.get(c_qty)) or len(refs) or 1) if c_qty else (len(refs) or 1)+ unit = money(r.get(c_price)) if c_price else None+ if unit is None:+ unit = prices.get(mpn.upper())+ dp = next((design["parts"][x] for x in refs if x in design["parts"]), {})+ role = (r.get(c_role) or "").strip() if c_role else ""+ if not role:+ role = dp.get("role") or ""+ if not role:+ notes = [design["parts"][x].get("note") for x in refs if x in design["parts"] and design["parts"][x].get("note")]+ role = notes[0] if notes else ((r.get(c_note) or "").strip() if c_note else "") or dp.get("desc") or ""+ role = re.split(r"(?<=[a-z0-9)])[.;] ", role)[0].strip()+ if len(role) > 90:+ role = role[:87].rsplit(" ", 1)[0] + "..."+ out.append({"feature": False, "refs": refs, "qty": qty, "value": (r.get(c_val) or "").strip() if c_val else dp.get("value", ""),+ "mpn": mpn, "mfr": ((r.get(c_mfr) or "").strip() if c_mfr else "") or dp.get("mfr", ""),+ "wiki": ((r.get(c_wiki) or "").strip() if c_wiki else "") or dp.get("page") or "", "role": role,+ "unit": unit, "line": round(unit * qty, 4) if unit is not None else None,+ "stock": (r.get(c_stock) or "").strip() if c_stock else "", "stockDate": stock_date,+ "source": (r.get(c_src) or "").strip() if c_src else "", "buy": "https://www.mouser.com/c/?q=" + urllib.parse.quote(mpn)})+ return out, {"priceColumn": c_price, "stockColumn": c_stock, "file": bom_path}+++def slugify(s):+ return re.sub(r"[^a-z0-9]+", "-", (s or "").lower()).strip("-")+++def _largest_region(small, thresh, blur):+ from PIL import Image, ImageChops, ImageFilter+ w, h = small.size+ px = small.load()+ border = [px[x, 0] for x in range(w)] + [px[x, h - 1] for x in range(w)] + [px[0, y] for y in range(h)] + [px[w - 1, y] for y in range(h)]+ bg = tuple(sorted(c[i] for c in border)[len(border) // 2] for i in range(3))+ src = small.filter(ImageFilter.GaussianBlur(blur)) if blur else small+ d = ImageChops.difference(src, Image.new("RGB", small.size, bg)).convert("L")+ m = d.point(lambda v: 255 if v > thresh else 0).filter(ImageFilter.MinFilter(5)).filter(ImageFilter.MaxFilter(3)).load()+ seen, best = set(), None+ for y in range(h):+ for x in range(w):+ if m[x, y] and (x, y) not in seen:+ stack, n, box = [(x, y)], 0, [x, y, x, y]+ seen.add((x, y))+ while stack:+ a, b = stack.pop()+ n += 1+ box = [min(box[0], a), min(box[1], b), max(box[2], a), max(box[3], b)]+ for q in ((a + 1, b), (a - 1, b), (a, b + 1), (a, b - 1)):+ if 0 <= q[0] < w and 0 <= q[1] < h and m[q] and q not in seen:+ seen.add(q)+ stack.append(q)+ if not best or n > best[0]:+ best = (n, box)+ if not best or best[0] < 0.01 * w * h:+ return None+ x0, y0, x1, y1 = best[1]+ if (x1 - x0) * (y1 - y0) > 0.75 * w * h:+ return None+ return best[1]+++def salient_crop(im):+ """The part in a hero picture: the largest region that differs from the border's colour, thin strokes (a+ billboard's text) eroded away, cropped square around it. A dark part on a dark billboard is looked for again,+ more finely, in the right part of the picture, where the hero studio puts the model. None when nothing stands+ out or it fills the frame."""+ im = im.convert("RGB")+ small = im.copy()+ small.thumbnail((240, 240))+ s = im.size[0] / float(small.size[0])+ box, off = _largest_region(small, 28, 0), 0+ if box is None and im.size[0] > 1.3 * im.size[1]:+ off = int(small.size[0] * 0.42)+ right = small.crop((off, 0, small.size[0], small.size[1]))+ box = _largest_region(right, 10, 1.5)+ if box is None:+ return None+ x0, y0, x1, y1 = box[0] + off, box[1], box[2] + off, box[3]+ side = min(max(x1 - x0, y1 - y0) * s * 1.25, min(im.size))+ cx = min(max((x0 + x1) / 2.0 * s, side / 2), im.size[0] - side / 2)+ cy = min(max((y0 + y1) / 2.0 * s, side / 2), im.size[1] - side / 2)+ return im.crop((int(cx - side / 2), int(cy - side / 2), int(cx + side / 2), int(cy + side / 2)))+++def part_image(line, cache, out_dir, bundle, offline):+ """docs/parts/<slug>.png: the part's wiki page hero, else a step2glb thumbnail of its STEP in the bundle's 3d/,+ else None (the page draws a placeholder). Returns (file, source)."""+ try:+ from PIL import Image+ except ImportError:+ return None, "none: Pillow missing"+ slug = slugify(line["mpn"])+ dst = os.path.join(out_dir, slug + ".png")+ os.makedirs(cache, exist_ok=True)++ def finish(src_png, how, crop=False):+ im = Image.open(src_png).convert("RGBA")+ if crop:+ c = salient_crop(im)+ im = c.convert("RGBA") if c is not None else im+ im.thumbnail((160, 160))+ canvas = Image.new("RGBA", (160, 160), (0, 0, 0, 0))+ canvas.paste(im, ((160 - im.size[0]) // 2, (160 - im.size[1]) // 2), im)+ canvas.save(dst, optimize=True)+ return dst, how++ page = line.get("wiki")+ if page and not offline:+ ck = os.path.join(cache, re.sub(r"[^A-Za-z0-9_.-]", "_", page) + ".hero")+ if not os.path.isfile(ck):+ pj = subprocess.run(["adom-wiki", "repo", "show", page, "page.json"], capture_output=True, text=True, stdin=subprocess.DEVNULL, timeout=90)+ hero = None+ try:+ hero = (json.loads(pj.stdout[pj.stdout.index("{"):]).get("hero") or {}) if pj.returncode == 0 else None+ except ValueError:+ hero = None+ path = (hero or {}).get("path") or (hero or {}).get("image")+ if path and re.search(r"\.(png|jpe?g|webp)$", path, re.I):+ subprocess.run(["adom-wiki", "repo", "show", page, path, "--out", ck], capture_output=True, stdin=subprocess.DEVNULL, timeout=120)+ if os.path.isfile(ck) and os.path.getsize(ck) > 0:+ try:+ return finish(ck, f"wiki hero of {page}", crop=True)+ except Exception:+ pass+ d3 = os.path.join(bundle, "3d")+ step = None+ if os.path.isdir(d3):+ want = {slugify(line["mpn"]), slugify((page or "").split("/")[-1])}+ for f in sorted(os.listdir(d3)):+ stem = slugify(re.sub(r"\.(step|stp)$", "", f, flags=re.I).replace("-etched", ""))+ if f.lower().endswith((".step", ".stp")) and stem in want:+ step = os.path.join(d3, f)+ break+ if step and shutil.which("step2glb") and not offline:+ ck = os.path.join(cache, slug + ".thumb.png")+ if not os.path.isfile(ck):+ subprocess.run(["step2glb", "thumbnail", step, "-o", ck, "--width", "320", "--height", "320", "--pose", "iso"],+ capture_output=True, stdin=subprocess.DEVNULL, timeout=240)+ if os.path.isfile(ck):+ try:+ return finish(ck, f"step2glb thumbnail of 3d/{os.path.basename(step)}")+ except Exception:+ pass+ return None, None+++# --------------------------------------------------------------------------- markdown (fab notes) to HTML++def md_inline(s):+ s = esc(s)+ s = re.sub(r"`([^`]+)`", r"<code>\1</code>", s)+ s = re.sub(r"\*\*([^*]+)\*\*", r"<strong>\1</strong>", s)+ s = re.sub(r"\[([^\]]+)\]\((https?://[^)\s]+)\)", r'<a href="\2" target="_blank" rel="noopener">\1</a>', s)+ return s+++def md_html(text, shift=1):+ out, para, lst = [], [], None++ def flush():+ nonlocal para, lst+ if para:+ out.append("<p>" + md_inline(" ".join(para)) + "</p>")+ para = []+ if lst:+ out.append("<ul>" + "".join(f"<li>{md_inline(i)}</li>" for i in lst) + "</ul>")+ lst = None++ for line in text.splitlines():+ m = re.match(r"^(#{1,6})\s+(.*)", line)+ if m:+ flush()+ lvl = min(6, len(m.group(1)) + shift)+ out.append(f"<h{lvl}>{md_inline(m.group(2))}</h{lvl}>")+ elif re.match(r"^\s*[-*]\s+", line):+ if para:+ flush()+ lst = (lst or []) + [re.sub(r"^\s*[-*]\s+", "", line)]+ elif re.match(r"^\s{2,}\S", line) and lst:+ lst[-1] += " " + line.strip()+ elif not line.strip():+ flush()+ else:+ if lst:+ flush()+ para.append(line.strip())+ flush()+ return "\n".join(out)+++# --------------------------------------------------------------------------- the page++PAGE_CSS = """+@font-face { font-family: 'Familjen Grotesk'; src: url(https://wiki.adom.inc/static/fonts/familjen-grotesk-700.woff2) format('woff2'); font-weight: 700; font-display: swap; }+@font-face { font-family: 'Familjen Grotesk'; src: url(https://wiki.adom.inc/static/fonts/familjen-grotesk-500.woff2) format('woff2'); font-weight: 500; font-display: swap; }+@font-face { font-family: 'JetBrains Mono'; src: url(https://wiki.adom.inc/static/fonts/jetbrains-mono-400.woff2) format('woff2'); font-weight: 400; font-display: swap; }+:root { color-scheme: dark; --bg: #0d1117; --bg-2: #161b22; --bg-3: #1c2128; --text: #e6edf3; --text-2: #8b949e; --accent: #00b8b1;+ --accent-bright: #00e6dc; --warn: #d29922; --bad: #f85149; --good: #3fb950; --border: #30363d; --radius: 6px;+ --font-display: 'Familjen Grotesk', -apple-system, 'Segoe UI', sans-serif; --font-body: 'Satoshi', -apple-system, 'Segoe UI', 'Noto Sans', sans-serif;+ --font-mono: 'JetBrains Mono', SFMono-Regular, Consolas, 'Liberation Mono', Menlo, monospace; }+* { box-sizing: border-box; }+html, body { margin: 0; background: var(--bg); color: var(--text); }+body { font: 14px/1.65 var(--font-body); -webkit-font-smoothing: antialiased; overflow-wrap: break-word; }+.doc { padding: 0 2px 24px; max-width: 1180px; }+h1, h2, h3 { font-family: var(--font-display); font-weight: 700; line-height: 1.3; text-wrap: balance; }+h1 { font-size: 2em; margin: 8px 0 12px; padding-bottom: 8px; border-bottom: 1px solid var(--border); }+h2 { font-size: 1.5em; margin: 30px 0 12px; padding-bottom: 6px; border-bottom: 1px solid var(--border); }+h3 { font-size: 1.15em; margin: 20px 0 8px; }+p { margin: 0 0 14px; }+a { color: var(--accent); text-decoration: none; } a:hover { color: var(--accent-bright); text-decoration: underline; }+table { width: 100%; border-collapse: collapse; margin: 0 0 16px; }+th, td { padding: 7px 10px; border: 1px solid var(--border); text-align: left; vertical-align: top; }+th { background: var(--bg-3); font-weight: 500; }+td.num, th.num { text-align: right; font-variant-numeric: tabular-nums; white-space: nowrap; }+code { font-family: var(--font-mono); font-size: .85em; background: var(--bg-3); padding: 1px 5px; border-radius: 4px; }+.lede { font-size: 1.08em; color: var(--text); }+.muted { color: var(--text-2); }+.scroll-x { overflow-x: auto; }+.facts td:first-child { width: 150px; color: var(--text-2); }+.pair { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; }+.pair figure, figure.fig { margin: 0 0 16px; }+figure img { display: block; width: 100%; max-width: 940px; height: auto; border: 1px solid var(--border); border-radius: var(--radius); background: var(--bg-2); }+figcaption { color: var(--text-2); font-size: .9em; margin-top: 6px; }+.tag { display: inline-block; font-size: .78em; padding: 0 7px; border-radius: 10px; border: 1px solid var(--border); color: var(--text-2); white-space: nowrap; }+.tag.good { color: var(--good); border-color: rgba(63,185,80,.4); } .tag.bad { color: var(--bad); border-color: rgba(248,81,73,.45); }+.tag.warn { color: var(--warn); border-color: rgba(210,153,34,.45); }+.bom td { vertical-align: middle; }+.bom .part { display: flex; gap: 10px; align-items: center; min-width: 210px; }+.bom .part img, .bom .part .ph { width: 56px; height: 56px; flex: none; border-radius: 6px; background: #f3f5f7; object-fit: contain; }+.bom .part .ph { display: flex; align-items: center; justify-content: center; color: #5b6b80; font: 10px var(--font-mono); text-align: center; background: #e9edf2; }+.bom .mpn { font-family: var(--font-mono); font-size: .92em; }+.bom .refs { font-family: var(--font-mono); font-size: .85em; color: var(--text-2); max-width: 220px; }+.total td { font-weight: 500; background: var(--bg-2); }+table.fit { width: auto; min-width: 420px; }+.proof { display: flex; flex-wrap: wrap; gap: 8px; margin: 0 0 12px; }+details.notes > summary { cursor: pointer; color: var(--accent); margin: 6px 0 10px; }+.foot { margin-top: 36px; color: var(--text-2); font-size: .85em; border-top: 1px solid var(--border); padding-top: 10px; }+aiflow-explorer { display: block; margin: 6px 0 24px; }+@media (max-width: 760px) { .pair { grid-template-columns: 1fr; } }+"""++READY = """(function(){var last=0;function report(){var h=Math.ceil(document.documentElement.scrollHeight)+2;if(Math.abs(h-last)>2){last=h;try{parent.postMessage({type:'readme-height',height:h},'*');}catch(e){}}}+window.addEventListener('load',report);if(window.ResizeObserver)new ResizeObserver(report).observe(document.documentElement);setInterval(report,1200);report();})();"""++LS_SHIM = """try { localStorage.length; } catch (e) { (function () { var m = {}; Object.defineProperty(window, "localStorage", { value: { getItem: function (k) { return k in m ? m[k] : null; }, setItem: function (k, v) { m[k] = String(v); }, removeItem: function (k) { delete m[k]; }, clear: function () { m = {}; } } }); })(); }"""+++def section(sid, title, body, state="ok", why=""):+ return (f'<section id="{sid}" data-aiflow-section="{sid}" data-state="{state}"' + (f' data-why="{esc(why)}"' if why else "") ++ f'>\n<h2>{esc(title)}</h2>\n{body}\n</section>\n')+++def table(head, rows, cls="", nums=()):+ th = "".join(f'<th class="num">{esc(h)}</th>' if i in nums else f"<th>{esc(h)}</th>" for i, h in enumerate(head))+ trs = "".join("<tr>" + "".join(f'<td class="num">{c}</td>' if i in nums else f"<td>{c}</td>" for i, c in enumerate(r)) + "</tr>" for r in rows)+ return f'<div class="scroll-x"><table class="{cls}"><thead><tr>{th}</tr></thead><tbody>{trs}</tbody></table></div>'+++def usd(v):+ return f"${v:,.2f}" if isinstance(v, (int, float)) else ""+++def build_page(ctx, url_of):+ """readme.html as text; url_of(bundle-relative path) gives each asset's URL (the wiki's render URL, or a local+ file URL for the preview)."""+ T, S = ctx["title"], ctx+ facts = []+ b = S["board"]+ if b.get("outline"):+ o = b["outline"]+ cu = S.get("copperUm")+ facts.append(("Board", f"{o[2] - o[0]:.1f} x {o[3] - o[1]:.1f} mm, {len(b.get('copperLayers') or [])} copper layers" ++ (f", {cu:g} µm ({cu / 35:.0f} oz) copper" if cu else "") + f", {len(S['design']['parts'])} parts on the netlist"))+ if S["molecule"]:+ mp = [c for c in S["contacts"] if c["kind"] == "pin"]+ mc = [c for c in S["contacts"] if c["kind"] == "contact"]+ cls = sorted({c["class"] for c in mp if c["class"]})+ facts.append(("Molecule", f"{'/'.join(cls) or 'machine'} corner pins {', '.join(c['ref'] for c in mp)}; {len(mc)} contacts "+ f"({len([c for c in mc if c['class'] == 'large'])} large, {len([c for c in mc if c['class'] == 'medium'])} medium)"))+ lines = [l for l in S["bom"] if not l["feature"]]+ facts.append(("Parts", f"{len(lines)} BOM lines, {sum(l['qty'] for l in lines)} parts" ++ (f"; {sum(len(l['refs']) for l in S['bom'] if l['feature'])} board features (machine pins, contacts, test pads) not bought" if any(l["feature"] for l in S["bom"]) else "")))+ n = S["sim"]+ if n.get("solved"):+ facts.append(("Simulation", f"peak rise +{fmt(n.get('peakRise'), 0)} °C in still air, +{fmt(n.get('peakRiseMoving'), 0)} °C in moving air "+ f"(budget +{fmt(n.get('budget'), 0)} °C); worst current density {fmt(n.get('jMax'), 0)} A/mm² on {n.get('jNet') or '?'}"))+ facts.append(("Status", S["status"]))+ out = [f"<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>{esc(T)}</title>",+ f"<script>{LS_SHIM}</script>", f"<style>@import url('https://api.fontshare.com/v2/css?f[]=satoshi@400,500&display=swap');{PAGE_CSS}</style>",+ "</head>\n<body>\n<main class=\"doc\">", f"<h1 id=\"top\">{esc(T)}</h1>", f"<p class=\"lede\">{esc(S['brief'])}</p>",+ table(["", ""], [[esc(k), esc(v)] for k, v in facts], cls="facts").replace("<thead><tr><th></th><th></th></tr></thead>", "")]+ # the board+ rend = S["renders"]+ if rend:+ figs = "".join(f'<figure><img src="{url_of(f"docs/board/{side}.png")}" alt="The board, {side} side, from its own KiCad file" loading="lazy">'+ f'<figcaption>{side.capitalize()} side{" (seen from below)" if side == "bottom" else ""}</figcaption></figure>' for side in ("top", "bottom") if side in rend)+ out.append(section("board", "The board", f'<div class="pair">{figs}</div>'))+ else:+ out.append(section("board", "The board", f"<p class=\"muted\">No board pictures: {esc(S['renderNote'] or 'no board file')}.</p>", "empty", S["renderNote"] or "no board renders"))+ # contacts+ if S["contacts"]:+ rows = [[f"<strong>{esc(c['ref'])}</strong>", esc(c["net"]), esc(c["class"] + (" pin" if c["kind"] == "pin" else " contact") if c["class"] else c["kind"]),+ esc(c["gauge"]), esc(f"{c['at'][0]:g}, {c['at'][1]:g}" if c["at"] else ""), esc(c["use"])] for c in S["contacts"]]+ body = table(["Contact", "Net", "Class", "Wire", "At (mm from MP1, y up)", "Use"], rows)+ body += "<p class=\"muted\">Large contacts take 14 AWG solid wire, medium ones 24 AWG. The Adom Electronics Prototyping Cloud Lab presses the machine pins and contacts in after assembly; they are not in the BOM.</p>"+ out.append(section("contacts", "Contacts", body))+ # explorer+ pr = S["explorer"]["proof"]+ tags = [f'<span class="tag {"good" if pr["coverage"] >= 100 else "bad"}">{pr["parts"]} of {pr["required"]} parts drawn</span>',+ f'<span class="tag {"good" if pr["pins"] >= pr["pinsRequired"] else "bad"}">{pr["pins"]} of {pr["pinsRequired"]} connected pins</span>',+ f'<span class="tag {"good" if pr["diffs"] == 0 else "bad"}">{pr["diffs"]} netlist difference{"s" if pr["diffs"] != 1 else ""}</span>',+ f'<span class="tag {"good" if pr["auto"] == 0 else "warn"}">{pr["hand"]} drawn by hand, {pr["auto"]} auto-drawn</span>']+ body = (f"<p>The board's blocks and the signals between them. Click a block for its circuit; hover a wire to trace its net, click a label to jump to "+ f"the block it goes to. Every drawing is checked against the design netlist ({esc((S['design']['source'] or {}).get('kind') or 'board')}): "+ f"each wire and label joins pins of one net, and every part and connected pin is drawn.</p><div class=\"proof\">{''.join(tags)}</div>"+ f"<aiflow-explorer></aiflow-explorer>")+ ok_ex = pr["coverage"] >= 100 and pr["diffs"] == 0+ out.append(section("circuit-explorer", "Circuit explorer", body, "ok" if ok_ex else "empty",+ "" if ok_ex else f"coverage {pr['coverage']} %, {pr['diffs']} differences"))+ # simulation+ out.append(sim_section(S, url_of))+ # components+ out.append(bom_section(S, url_of))+ # manufacturing+ out.append(mfg_section(S, url_of))+ # open items+ items = S["open"]+ body = ("<ul>" + "".join(f"<li>{esc(i)}</li>" for i in items) + "</ul>") if items else "<p>Nothing open.</p>"+ if S["finish"] is None:+ body = "<p class=\"muted\">finish has not run on this board yet: the open items appear here once it has.</p>" + body+ out.append(section("open-items", "Open items", body, "ok" if S["finish"] is not None else "empty", "" if S["finish"] is not None else "finish has not run"))+ out.append(f"<p class=\"foot\">Built by <code>adom-aiflow project-page --molecule-bundle</code> {esc(S['version'])} on {esc(S['now'])} from the run's board "+ f"(fingerprint <code>{esc((S['boardFingerprint'] or '')[:12])}</code>). The numbers are the run's own records; nothing on this page is typed in by hand.</p>")+ out.append("</main>")+ data = json.dumps(S["explorer"]["data"], separators=(",", ":")).replace("</", "<\\/")+ a = assets()+ out.append(f'<script type="application/json" id="aiflow-explorer-data">{data}</script>')+ out.append("<script>window.AIFLOW_EXPLORER_CSS = " + json.dumps(a["css"]).replace("</", "<\\/") + ";\nwindow.AIFLOW_SYMBOLS = " ++ json.dumps(symbols(), separators=(",", ":")) + ";\n" + a["js"].replace("</script", "<\\/script") + "</script>")+ out.append(f"<script>{READY}</script>\n</body>\n</html>\n")+ return "\n".join(out)+++def design_review_link(S):+ """`project-page --results --out <this folder>` writes design-review/README.md: the page links it."""+ if S.get("bundle") and os.path.isfile(os.path.join(S["bundle"], "design-review", "README.md")):+ return f'<p>The same results as a Markdown sub-page: <a href="{esc(S["filesUrl"]("design-review/README.md"))}" target="_blank" rel="noopener">the design review</a>.</p>'+ return ""+++def sim_section(S, url_of):+ n = S["sim"]+ figs = S["figures"]+ if not n.get("solved") and not n.get("current") and not n.get("thermal"):+ return section("simulation", "Simulation", "<p class=\"muted\">No Adom Fields solve, current or thermal analysis in this run yet. Solve it (`adom-fields analyze`), "+ "run `analyze current` and `analyze thermal`, then build the page again.</p>" + design_review_link(S), "empty", "no Fields, current or thermal results")+ parts = []+ if n.get("solved"):+ loads = ", ".join(f"{fmt(l['amps'], 2)} A on {l['net']}" for l in n.get("loads") or [])+ parts.append(f"<p>Current and heat solved with Adom Fields {esc(n.get('solver') or '')} on this board (<code>{esc((n.get('boardSha256') or '')[:12])}</code>) at the "+ f"spec's loads{(': ' + esc(loads)) if loads else ''}. Still air is {fmt(n.get('still'), 0)} W/m²K, moving air {fmt(n.get('moving'), 0)} W/m²K. "+ "These are DC screens with the spec's loss model: good for ranking layouts and finding necks, not a bench measurement.</p>")+ hist = S.get("history") or []+ cols = hist[-3:] if len(hist) > 1 else []+ heads = ["Result"] + ([f"Layout {i + 1}" + (" (this one)" if i == len(cols) - 1 else "") + f" {h['at'][:10]}" for i, h in enumerate(cols)] if cols else ["This layout"])+ def row(label, key, nd, unit):+ vals = [h["numbers"].get(key) for h in cols] if cols else [n.get(key)]+ return [esc(label)] + [esc(fmt(v, nd, unit)) for v in vals]+ rows = [row("Copper loss", "jouleW", 2, " W"), row("Heat from the parts", "tabW", 2, " W"),+ row("Worst current density", "jMax", 0, " A/mm²"),+ row("Peak rise, still air", "peakRise", 0, " °C"), row("Peak rise, moving air", "peakRiseMoving", 0, " °C")]+ for r_ in rows[3:]:+ r_[1:] = ["+" + c if c and c[0].isdigit() else c for c in r_[1:]]+ if n.get("jNet"):+ rows[2][-1] += f" <span class=\"muted\">({esc(n['jNet'])}, {esc(n.get('jLayer') or '')})</span>"+ b = n.get("budget")+ parts.append(table(heads, rows, cls="fit", nums=tuple(range(1, len(heads)))))+ scr = []+ for k in ("current", "thermal"):+ x = n.get(k)+ if x:+ tag = '<span class="tag good">pass</span>' if x.get("pass") else '<span class="tag bad">not passed</span>'+ scr.append(f"<li><code>analyze {k}</code> {tag} {esc(x.get('note') or '')}" + (f" <span class=\"muted\">(failing: {esc(', '.join(str(v) for v in x['fails'][:8]))})</span>" if x.get("fails") else "") + "</li>")+ if scr:+ parts.append("<ul>" + "".join(scr) + "</ul>")+ chips = n.get("chips") or []+ if chips:+ crow = []+ for c in chips[:10]:+ over = b is not None and (c.get("rise") or 0) > b+ crow.append([f"<strong>{esc(c['ref'])}</strong>", esc(fmt(c.get("watts"), 3, " W")),+ esc(fmt(c.get("rise"), 0, " °C")) + (' <span class="tag bad">over budget</span>' if over else ""),+ esc(fmt(c.get("riseMoving"), 0, " °C")), esc(c.get("tab") or "")])+ parts.append(f"<h3>Hottest parts</h3>" + table(["Part", "Dissipation", "Rise, still air", "Rise, moving air", "Tab net"], crow, cls="fit", nums=(1, 2, 3)) ++ (f"<p class=\"muted\">Budget +{fmt(b, 0)} °C over ambient (spec hotMaxRiseC).</p>" if b is not None else ""))+ necks = n.get("necks") or []+ if necks:+ parts.append("<h3>Worst necks</h3><ul>" + "".join(f"<li><strong>{esc(k.get('net'))}</strong> on {esc(k.get('layer'))}: {esc(k.get('what') or '')}</li>" for k in necks[:6]) + "</ul>")+ for sw in n.get("sweeps") or []:+ rows = []+ for r in sw["rows"]:+ hot = sorted(r["parts"].items(), key=lambda kv: -((kv[1] or [0])[0] or 0))+ rows.append([esc(fmt(r["amps"], 1, " A")), esc(fmt(r["still"], 0, " °C")), esc(fmt(r["moving"], 0, " °C")),+ esc(f"{hot[0][0]} +{hot[0][1][0]:.0f} °C" if hot and hot[0][1] and hot[0][1][0] is not None else "")])+ lim = []+ for key, label in (("atBudgetStill", "still air"), ("atBudgetMoving", "moving air")):+ v = sw.get(key)+ if v:+ lim.append(f"{label} {'about ' if v[0] == '=' else ('under ' if v[0] == '<' else 'over ')}{v[1]:.1f} A")+ parts.append(f"<h3>Rating sweep</h3>" + table(["Load", "Peak rise, still air", "Peak rise, moving air", "Hottest part (still air)"], rows, cls="fit", nums=(0, 1, 2)) ++ (f"<p>Current for the +{fmt(n.get('budget'), 0)} °C budget: {esc('; '.join(lim))} (from <code>{esc(os.path.basename(sw['file']))}</code>).</p>" if lim else ""))+ for f, shows in figs:+ rel = os.path.relpath(f, S["bundle"])+ cap = {"fig_current.png": "Current density on each copper layer at the spec's loads; the dashed line is the screen, the circles the worst necks.",+ "fig_temperature.png": "Temperature rise over the board in still and in moving air, the hot parts marked with their rise.",+ "fig_rating.png": "Peak rise against load current, from the rating sweep."}.get(os.path.basename(f), shows)+ small = ' style="max-width:720px"' if os.path.basename(f) == "fig_rating.png" else ""+ parts.append(f'<figure class="fig"><img src="{url_of(rel)}" alt="{esc(shows)}" loading="lazy"{small}><figcaption>{esc(cap)}</figcaption></figure>')+ if design_review_link(S):+ parts.append(design_review_link(S))+ if S.get("runReport"):+ parts.append(f'<p>The full run, step by step, with every analysis drawing: <a href="{esc(S["runReport"])}" target="_blank" rel="noopener">the AI Flow run report</a>.</p>')+ return section("simulation", "Simulation", "\n".join(parts))+++def bom_section(S, url_of):+ lines = [l for l in S["bom"] if not l["feature"]]+ if not lines:+ return section("components", "Components", "<p class=\"muted\">No BOM with part numbers in this run (sourcing check --bom, or --bom).</p>", "empty", "no BOM")+ priced = [l for l in lines if l["unit"] is not None]+ info = S["bomInfo"]+ rows = []+ for l in lines:+ img = l.get("image")+ pic = (f'<img src="{url_of(img)}" alt="{esc(l["mpn"])}" loading="lazy">' if img else f'<span class="ph">{esc((l["value"] or l["mpn"])[:14])}</span>')+ link = f'{WIKI}/{l["wiki"]}' if l.get("wiki") else None+ name = f'<a class="mpn" href="{esc(link)}" target="_blank" rel="noopener">{esc(l["mpn"])}</a>' if link else f'<span class="mpn">{esc(l["mpn"])}</span>'+ src = f'<br><span class="tag">{esc(l["source"])}</span>' if l.get("source") and not re.fullmatch(r"mouser", l["source"], re.I) else ""+ stock = esc(l["stock"]) if l.get("stock") else '<span class="muted">not recorded</span>'+ rows.append([f'<div class="part">{pic}<div>{name}<br><span class="muted">{esc(l["mfr"])}</span>{src}</div></div>', str(l["qty"]),+ f'<div class="refs">{esc(" ".join(l["refs"]))}</div>', esc(l["value"]), esc(l["role"]),+ usd(l["unit"]) if l["unit"] is not None else '<span class="muted">not recorded</span>',+ usd(l["line"]) if l["line"] is not None else '<span class="muted">not recorded</span>', stock,+ f'<a href="{esc(l["buy"])}" target="_blank" rel="noopener">Mouser</a>'])+ total = sum(l["line"] for l in priced)+ head = ["Part", "Qty", "Refs", "Value", "Role", "Unit", "Line", "Stock" + (f" ({lines[0]['stockDate']})" if lines[0].get("stockDate") else ""), "Buy"]+ tbl = table(head, rows, cls="bom", nums=(1, 5, 6, 7))+ if priced and len(priced) == len(lines):+ tbl = tbl.replace("</tbody>", f'<tr class="total"><td colspan="6">Board total, {sum(l["qty"] for l in lines)} parts</td><td class="num">{usd(total)}</td><td colspan="2"></td></tr></tbody>')+ lead = f"<p>Unit prices from the BOM's <code>{esc(info.get('priceColumn') or 'sourcing')}</code> column, at the quantity one board needs.</p>"+ elif priced:+ lead = (f"<p>Prices are recorded for {len(priced)} of {len(lines)} lines (the BOM's <code>{esc(info.get('priceColumn') or 'sourcing')}</code> column): "+ f"{usd(total)} for those lines. No board total: the other lines have no recorded price.</p>")+ else:+ lead = ("<p>No prices are recorded for this board: the BOM has no price column and the sourcing check recorded none, so this table shows none "+ "and no board total. Add a <code>unit_price</code> column from a parts search (adom-parts-search) and build the page again.</p>")+ feats = [l for l in S["bom"] if l["feature"]]+ tail = ""+ if feats:+ tail = "<p class=\"muted\">Board features, not bought parts: " + "; ".join(f"{esc(' '.join(l['refs']))} ({esc(l['value'])})" for l in feats) + ".</p>"+ tail += "<p class=\"muted\">Buy links search Mouser by the exact MPN. Pictures are each part's own wiki page hero.</p>"+ return section("components", "Components", lead + tbl + tail)+++ROLE_TEXT = {"step": "The assembled board in 3D (STEP)", "board_kicad_pcb": "The KiCad board", "schematic_kicad_sch": "The schematic",+ "schematic": "The schematic", "project": "The KiCad project", "fab_zip": "Gerbers and drill files", "export": "What the fabrication files were made from (export.json)",+ "bom": "Bill of materials", "cpl": "Pick and place"}+++def mfg_section(S, url_of):+ ex = S.get("exportJson") or {}+ rows = []+ for f in ex.get("files") or []:+ p = f.get("path")+ if not p:+ continue+ what = ROLE_TEXT.get(f.get("role"), f.get("role") or "")+ if f.get("role") == "fab_zip" and f.get("entries"):+ what += f" ({len(f['entries'])} files)"+ rows.append([f'<a href="{esc(S["filesUrl"](p))}" target="_blank" rel="noopener"><code>{esc(p)}</code></a>', esc(what), esc(f"{(f.get('bytes') or 0) / 1024:.0f} KB")])+ listed = {f.get("path") for f in ex.get("files") or []}+ for p in sorted(os.listdir(S["bundle"])):+ if p.lower().endswith((".csv",)) and p not in listed:+ rows.append([f'<a href="{esc(S["filesUrl"](p))}" target="_blank" rel="noopener"><code>{esc(p)}</code></a>',+ "Pick and place" if re.search(r"cpl|pos|place", p, re.I) else "Bill of materials" if re.search(r"bom", p, re.I) else "", ""])+ body = table(["File", "What", "Size"], rows, nums=(2,)) if rows else "<p class=\"muted\">No export.json in the folder: run `adom-aiflow export` and molecule-publish's fab_bundle.py first.</p>"+ ver = S.get("verified") or {}+ if ver.get("items"):+ body += "<p><strong>Checked by finish:</strong> " + ", ".join(f"{esc(k)} {'yes' if v == 'yes' else esc(v)}" for k, v in ver["items"].items()) + ".</p>"+ if ver.get("verdict"):+ body += f"<p class=\"muted\">{esc(ver['verdict'])}</p>"+ if S.get("fabNotes"):+ body += f"<details class=\"notes\" open><summary>Fabrication notes</summary>{md_html(S['fabNotes'], shift=2)}</details>"+ return section("manufacturing", "Manufacturing", body, "ok" if rows else "empty", "" if rows else "no export record")+++# --------------------------------------------------------------------------- build, check, results++def page_ref(cfg, bundle):+ page = cfg.get("page")+ if page and "/" in page:+ return page.split("/", 1)+ return None+++def url_maker(cfg, bundle, local=False):+ ref = page_ref(cfg, bundle)+ folder = (cfg.get("pageDir") or "").strip("/")++ def url_of(rel):+ p = os.path.join(bundle, rel)+ v = sha(p)[:8] if os.path.isfile(p) else ""+ if local or not ref:+ return ("file://" + urllib.parse.quote(os.path.abspath(p))) if local else rel+ return f"{WIKI}/{ref[0]}/{ref[1]}/render/{(folder + '/') if folder else ''}{rel}" + (f"?v={v}" if v else "")++ def files_url(rel):+ if not ref:+ return rel+ return f"{WIKI}/{ref[0]}/{ref[1]}/files/{(folder + '/') if folder else ''}{rel}"+ return url_of, files_url+++def bundle_board(bundle, cfg):+ """The board the page shows: the folder's (export.json role board*), else the run's current board."""+ ex = rjson(os.path.join(bundle, "export.json"), {}) or {}+ for f in ex.get("files") or []:+ if str(f.get("role", "")).startswith("board") and str(f.get("path", "")).endswith(".kicad_pcb"):+ p = os.path.join(bundle, f["path"])+ if os.path.isfile(p):+ return p+ for f in sorted(os.listdir(bundle)) if os.path.isdir(bundle) else []:+ if f.endswith(".kicad_pcb"):+ return os.path.join(bundle, f)+ b = cfg.get("board")+ return b if b and os.path.isfile(b) else None+++def find_schematic(cfg, bundle, run):+ if cfg.get("schematic") and os.path.isfile(cfg["schematic"]):+ return cfg["schematic"]+ for f in sorted(os.listdir(bundle)) if os.path.isdir(bundle) else []:+ if f.endswith(".kicad_sch") and os.path.isfile(os.path.join(bundle, f.replace(".kicad_sch", ".kicad_pro"))):+ return os.path.join(bundle, f)+ s = run.get("schematic") or ((run.get("outcomes") or {}).get("schematic") or {}).get("schematic")+ return s if isinstance(s, str) and os.path.isfile(s) else None+++def context(cfg):+ run_dir = cfg["run"]+ run = rjson(os.path.join(run_dir, "run.json"), {}) or {}+ bundle = os.path.abspath(cfg["bundle"])+ spec = rjson(cfg.get("spec") or run.get("spec") or "", {}) or {}+ board_path = bundle_board(bundle, cfg)+ board = parse_board(board_path) if board_path else None+ if board:+ board["path"], board["sha256"] = board_path, sha(board_path)+ sch = parse_schematics(find_schematic(cfg, bundle, run))+ design = load_design(cfg.get("netlist"), board, sch, spec)+ return run, bundle, spec, board_path, board, design+++def build(cfg):+ run, bundle, spec, board_path, board, design = context(cfg)+ if not os.path.isdir(bundle):+ fail(f"{bundle} is not a folder: give the molecule-publish package folder (Stage 2) or any folder the page is published from")+ if not design["parts"]:+ fail("no netlist: give --netlist <netlist.json> (components with a block, nets) or put the board (.kicad_pcb) in the folder")+ work = os.path.join(cfg["run"], "project-page", "page-build")+ os.makedirs(work, exist_ok=True)+ docs = os.path.join(bundle, "docs")+ for sub in ("board", "review", "parts", "explorer"):+ shutil.rmtree(os.path.join(docs, sub), ignore_errors=True)+ os.makedirs(docs, exist_ok=True)+ fp = board_fingerprint(board_path) if board_path else None+ notes = []+ renders, rnote = (board_renders(board_path, os.path.join(docs, "board"), work) if board_path else ({}, "no board file"))+ if rnote:+ notes.append(rnote)+ figures = [{"file": os.path.relpath(f, bundle), "shows": f"board {side}", "boardFingerprint": fp, "boardSha256": board["sha256"] if board else None,+ "source": board_path, "made": cfg.get("now") or now()} for side, f in renders.items()]+ # the explorer+ exdir = cfg.get("explorer")+ data, proof, drawings = explorer_build(design, exdir, spec, scaffold=bool(exdir))+ ed = os.path.join(docs, "explorer")+ os.makedirs(ed, exist_ok=True)+ wjson(os.path.join(ed, "design.json"), {"source": design["source"], "blocks": design["blocks"], "parts": design["parts"]})+ cfgb = rjson(os.path.join(exdir, "blocks.json"), {}) if exdir else {}+ wjson(os.path.join(ed, "blocks.json"), cfgb or {})+ for d in drawings:+ dd = {k: v for k, v in d.items() if not k.startswith("_")}+ if d.get("_auto"):+ dd["auto"] = True+ wjson(os.path.join(ed, f"{d.get('id')}.json"), dd)+ wjson(os.path.join(docs, "explorer-proof.json"), proof)+ # the simulation+ f, fdir, solved_board, fpath = fields_report(run, cfg)+ sweeps = [s for s in (cfg.get("sweeps") or []) if s and os.path.isfile(s)]+ auto_sweep = os.path.join(fdir or os.path.join(cfg["run"], "fields"), "rating-sweep.json")+ if not sweeps and os.path.isfile(auto_sweep):+ sweeps = [auto_sweep]+ budget = spec.get("hotMaxRiseC") if isinstance(spec.get("hotMaxRiseC"), (int, float)) else None+ sim = simulation_numbers(run, f, sweeps, budget)+ figs = []+ if f:+ figs, fnote = fields_figures(f, fdir, os.path.join(docs, "review"), spec)+ if fnote:+ notes.append(fnote)+ solved_fp = board_fingerprint(solved_board) if solved_board else None+ for p, shows in figs:+ figures.append({"file": os.path.relpath(p, bundle), "shows": shows, "boardFingerprint": solved_fp,+ "boardSha256": (f.get("inputIdentity") or {}).get("board"), "source": fpath, "made": cfg.get("now") or now()})+ if solved_fp and fp and solved_fp != fp:+ notes.append(f"the Fields solve is of another board ({os.path.basename(solved_board)}) than the one in the folder: solve this board and build again")+ for sw in sim.get("sweeps") or []:+ p = sweep_figure(sw["rows"], sim.get("budget"), os.path.join(docs, "review"))+ if p:+ figs.append((p, "Fields rating sweep"))+ figures.append({"file": os.path.relpath(p, bundle), "shows": "Fields rating sweep", "boardFingerprint": board_fingerprint(solved_board) if solved_board else None,+ "boardSha256": (f or {}).get("inputIdentity", {}).get("board"), "source": sw["file"], "made": cfg.get("now") or now()})+ # revision history: one entry per solved board+ hist_p = os.path.join(cfg["run"], "project-page", "review-history.json")+ hist = rjson(hist_p, []) or []+ if f:+ entry = {"boardSha256": sim.get("boardSha256"), "at": (cfg.get("now") or now()), "numbers": {k: sim.get(k) for k in ("jouleW", "tabW", "jMax", "peakRise", "peakRiseMoving")}}+ hist = [h for h in hist if h.get("boardSha256") != entry["boardSha256"]] + [entry]+ wjson(hist_p, hist[-6:])+ # components+ bom_path = cfg.get("bom") or ((run.get("outcomes") or {}).get("sourcing") or {}).get("bom") or ((run.get("outcomes") or {}).get("parts") or {}).get("bom")+ bom, binfo = bom_lines(bom_path, design, run)+ pdir = os.path.join(docs, "parts")+ os.makedirs(pdir, exist_ok=True)+ cache = os.path.join(cfg["run"], "project-page", "part-images")+ todo = [l for l in bom if not l["feature"]]+ with ThreadPoolExecutor(max_workers=6) as ex:+ res = list(ex.map(lambda l: part_image(l, cache, pdir, bundle, cfg.get("offline")), todo))+ for l, (img, how) in zip(todo, res):+ l["image"] = os.path.relpath(img, bundle) if img else None+ l["imageFrom"] = how+ if any(l.get("imageFrom") == "none: Pillow missing" for l in todo):+ notes.append("part pictures need Pillow (tools/requirements-page.txt; install.sh puts it in AI Flow's Python): placeholders shown")+ wjson(os.path.join(docs, "bom.json"), {"file": bom_path, "priceColumn": binfo.get("priceColumn"), "lines": bom})+ # manufacturing and open items+ export_dir = ((run.get("outcomes") or {}).get("export") or {}).get("dir")+ fab_notes = None+ for c in [os.path.join(bundle, "manufacturing", "FAB-NOTES.md"), os.path.join(bundle, "FAB-NOTES.md")] + ([os.path.join(export_dir, "FAB-NOTES.md")] if export_dir else []):+ if os.path.isfile(c):+ fab_notes = open(c, encoding="utf-8", errors="replace").read()+ break+ summ = run.get("summary") or {}+ finished = (run.get("clock") or {}).get("finishTime")+ open_items = list(summ.get("open") or []) if finished else []+ open_items += [f"deviation: {d.get('item') if isinstance(d, dict) else d}" for d in summ.get("deviations") or []] if finished else []+ if proof["autoDrawn"]:+ open_items.append(f"circuit explorer: {proof['autoDrawn']} block(s) auto-drawn (every pin labelled), still to be drawn the textbook way: " ++ ", ".join(b for b, v in proof["blocks"].items() if v["auto"] and v["drawings"]))+ nflow = len([b for b, v in proof["blocks"].items() if v.get("drawings") or v.get("auto") is not None])+ if nflow > FLOW_MAX_BLOCKS:+ open_items.append(f"circuit explorer: {nflow} blocks make an unreadable flowchart (aim for 6 to {FLOW_MAX_BLOCKS}): merge them in netlist.json's block field "+ "(a multi-channel board: one block per channel, its functions as drawing tabs)")+ if todo and not any(l["unit"] is not None for l in todo):+ open_items.append("components: no prices recorded in the BOM or the sourcing check")+ if proof["autoDrawn"] and finished and not summ.get("open"):+ summ = dict(summ, open=list(summ.get("open") or []) + ["circuit explorer not drawn"]) # never "passed its checks" over an undrawn explorer+ status = (f"finish ran with {len(summ.get('open') or [])} open item{'s' if len(summ.get('open') or []) != 1 else ''}; not cleared for fabrication"+ if finished and summ.get("open") else ("finish passed its checks; a human review is still advised before ordering" if finished else "finish has not run yet"))+ url_of, files_url = url_maker(cfg, bundle)+ ctx = {"title": cfg.get("title") or (rjson(os.path.join(bundle, "package.json"), {}) or {}).get("title") or os.path.basename(bundle),+ "brief": cfg.get("brief") or (rjson(os.path.join(bundle, "package.json"), {}) or {}).get("description") or "",+ "board": board or {}, "copperUm": spec.get("copperUm") or ((f or {}).get("board") or {}).get("copperUm"), "design": design,+ "molecule": bool(cfg.get("molecule")), "contacts": contacts(design, board, spec), "bom": bom, "bomInfo": binfo,+ "sim": sim, "figures": figs, "history": hist if f else [], "renders": renders, "renderNote": rnote, "explorer": {"data": data, "proof": data["proof"]},+ "open": open_items, "finish": finished, "status": status, "verified": summ.get("verified"), "fabNotes": fab_notes,+ "exportJson": rjson(os.path.join(bundle, "export.json"), {}), "bundle": bundle, "filesUrl": files_url,+ "runReport": cfg.get("runReport"), "boardFingerprint": fp, "version": cfg.get("version") or "", "now": cfg.get("now") or now()}+ wjson(os.path.join(docs, "figures.json"), {"boardFingerprint": fp, "figures": figures})+ page = build_page(ctx, url_of)+ with open(os.path.join(bundle, "readme.html"), "w") as fh:+ fh.write(page)+ lurl, _ = url_maker(cfg, bundle, local=True)+ prev = os.path.join(cfg["run"], "project-page", "preview")+ os.makedirs(prev, exist_ok=True)+ with open(os.path.join(prev, "readme.html"), "w") as fh:+ fh.write(build_page(ctx, lurl))+ sections = [s for s in SECTION_IDS if s != "contacts" or ctx["contacts"]]+ # package.json: the page shows the HTML (merged into page.json by the publish)+ pk = os.path.join(bundle, "package.json")+ pkg = rjson(pk)+ if isinstance(pkg, dict):+ pkg["readme_order"] = ["html"]+ wjson(pk, pkg)+ readme_note = write_readme_md(bundle, ctx)+ rec = {"schema": "aiflow.page-build/1", "at": ctx["now"], "bundle": bundle, "page": cfg.get("page"), "sections": sections,+ "boardFingerprint": fp, "board": board_path, "netlist": design["source"], "explorer": exdir, "version": ctx["version"]}+ wjson(os.path.join(docs, "page-build.json"), rec)+ result = check_bundle(bundle, cfg)+ return {"ok": True, "mode": "build", "bundle": bundle, "readme": os.path.join(bundle, "readme.html"), "preview": os.path.join(prev, "readme.html"),+ "sections": sections, "boardFingerprint": fp, "explorer": data["proof"], "explorerDir": exdir,+ "autoBlocks": [b for b, v in proof["blocks"].items() if v["auto"] and v["drawings"]],+ "figures": [x["file"] for x in figures], "bomLines": len(todo), "priced": len([l for l in todo if l["unit"] is not None]),+ "images": {"wiki": len([l for l in todo if (l.get("imageFrom") or "").startswith("wiki")]), "thumbnail": len([l for l in todo if (l.get("imageFrom") or "").startswith("step2glb")]),+ "none": len([l for l in todo if not l.get("image")])},+ "simulation": {k: sim.get(k) for k in ("solved", "peakRise", "peakRiseMoving", "jMax", "jNet", "budget", "boardSha256")}, "sweeps": [s["file"] for s in sim.get("sweeps") or []],+ "packageJson": isinstance(pkg, dict), "readmeMd": readme_note, "notes": notes, "check": result}+++def write_readme_md(bundle, ctx):+ """README.md is what search and excerpts read. An existing one is the author's (molecule-publish writes it, and+ `project-page --results --out` adds design-review/ for it to link): left as it is. A missing one is written."""+ p = os.path.join(bundle, "README.md")+ if os.path.isfile(p):+ return "README.md left as it is"+ lines = [l for l in ctx["bom"] if not l["feature"]]+ body = [f"# {ctx['title']}", "", ctx["brief"], "", "The page is readme.html: the board, its contacts, the circuit explorer, the simulation, the components, manufacturing and the open items.", "",+ f"Status: {ctx['status']}.", ""]+ if os.path.isfile(os.path.join(bundle, "design-review", "README.md")):+ body += ["[Design review](design-review/)", ""]+ body += ["## Components", "", "| MPN | Manufacturer | Qty | References |", "|---|---|---|---|"]+ body += [f"| {l['mpn']} | {l['mfr']} | {l['qty']} | {' '.join(l['refs'])} |" for l in lines]+ with open(p, "w") as fh:+ fh.write("\n".join(body) + "\n")+ return "README.md written"+++def check_bundle(bundle, cfg):+ """`project-page check`: every section present and filled, every figure from this board, the explorer proof+ recomputed (coverage 100 %, 0 differences), a BOM row for every part, readme_order ["html"]."""+ errors, warns = [], []+ rh = os.path.join(bundle, "readme.html")+ if not os.path.isfile(rh):+ return {"passed": False, "errors": [f"no readme.html in {bundle}: run `project-page --molecule-bundle {bundle}`"], "warnings": []}+ text = open(rh, encoding="utf-8").read()+ rec = rjson(os.path.join(bundle, "docs", "page-build.json"), {}) or {}+ found = {m.group(1): (m.group(2), m.group(3)) for m in re.finditer(r'data-aiflow-section="([^"]+)" data-state="([^"]+)"(?: data-why="([^"]*)")?', text)}+ want = rec.get("sections") or [s for s in SECTION_IDS if s != "contacts"]+ for s in want:+ if s not in found:+ errors.append(f"section {s} is missing from readme.html")+ elif found[s][0] != "ok":+ errors.append(f"section {s} has nothing to show: {html.unescape(found[s][1] or '')}")+ # figures: made from the board the folder carries now+ bp = bundle_board(bundle, cfg)+ fp_now = board_fingerprint(bp) if bp else None+ figs = rjson(os.path.join(bundle, "docs", "figures.json"), {}) or {}+ for f in figs.get("figures") or []:+ p = os.path.join(bundle, f.get("file", ""))+ if not os.path.isfile(p):+ errors.append(f"figure {f.get('file')} is listed but missing")+ elif fp_now and f.get("boardFingerprint") and f["boardFingerprint"] != fp_now:+ errors.append(f"figure {f.get('file')} ({f.get('shows')}) shows board {f['boardFingerprint'][:12]}, but the folder's board is {fp_now[:12]}: "+ "solve or render this board and build the page again")+ elif fp_now and not f.get("boardFingerprint"):+ warns.append(f"figure {f.get('file')} records no board fingerprint")+ if not figs.get("figures"):+ errors.append("no figures recorded (docs/figures.json): build the page")+ # the explorer, recomputed from what the page publishes+ ed = os.path.join(bundle, "docs", "explorer")+ dj = rjson(os.path.join(ed, "design.json"))+ spec = rjson(cfg.get("spec") or "", {}) or {}+ if not isinstance(dj, dict):+ errors.append("docs/explorer/design.json is missing: build the page")+ ex = None+ else:+ design = {"parts": dj.get("parts") or {}, "blocks": dj.get("blocks") or [], "source": dj.get("source")}+ _, ex, _ = explorer_build(design, ed, spec, scaffold=False)+ stored = rjson(os.path.join(bundle, "docs", "explorer-proof.json"), {}) or {}+ if ex["coverage"]["percent"] < 100:+ errors.append(f"explorer coverage {ex['coverage']['percent']} %: not drawn: " + ", ".join(ex["coverage"]["parts"]["missing"][:20]))+ if ex["diffs"]:+ errors.append(f"explorer: {ex['diffs']} netlist difference(s): " + "; ".join(ex["differences"][:8]))+ if stored.get("diffs") != ex["diffs"] or (stored.get("coverage") or {}).get("percent") != ex["coverage"]["percent"]:+ errors.append("docs/explorer-proof.json does not match the drawings it names: build the page again")+ src = (design.get("source") or {})+ if src.get("path") and os.path.isfile(src["path"]) and src.get("sha256") and sha(src["path"]) != src["sha256"]:+ errors.append(f"the netlist changed since the explorer was checked ({src['path']}): build the page again")+ auto = [b for b, v in ex["blocks"].items() if v["auto"] and v["drawings"]]+ if auto:+ # issue #197: an auto-drawn block (each pin labelled with its net, no wires) passes the netlist check by+ # construction but is not readable as a circuit; it is an open item until drawn or deviated+ errors.append(f"circuit explorer: {len(auto)} of {len(ex['blocks'])} block(s) auto-drawn (pins labelled, no wires), not readable as a "+ f"circuit: draw them the textbook way in the explorer folder (<id>.json, start from auto/<block>.json), "+ f"or `deviate \"circuit explorer\" --why ...`: " + ", ".join(auto[:12]) + (" ..." if len(auto) > 12 else ""))+ if len(ex["blocks"]) > FLOW_MAX_BLOCKS:+ # issue #198: more blocks than a flowchart can show+ warns.append(f"circuit explorer: {len(ex['blocks'])} blocks make an unreadable flowchart (aim for 6 to {FLOW_MAX_BLOCKS}): merge them in "+ "netlist.json's block field; a multi-channel board gets one block per channel with its functions as drawing tabs")+ # the BOM+ bj = rjson(os.path.join(bundle, "docs", "bom.json"), {}) or {}+ lines = [l for l in bj.get("lines") or [] if not l.get("feature")]+ rows_refs = {r for l in lines for r in l.get("refs") or []}+ if not lines:+ errors.append("components: no BOM lines on the page")+ else:+ if isinstance(dj, dict):+ parts = dj.get("parts") or {}+ # a board feature (bare test pad, machine pin, contact) is listed as a feature, not a bought row+ feat = {r for l in bj.get("lines") or [] if l.get("feature") for r in l.get("refs") or []}+ need = [r for r, p in parts.items() if p.get("mpn") and r not in feat]+ miss = sorted([r for r in need if r not in rows_refs], key=_numkey)+ if miss:+ errors.append("components: no BOM row for " + ", ".join(miss[:20]))+ rows_txt = text.count('<div class="part">')+ if rows_txt < len(lines):+ errors.append(f"components: the page shows {rows_txt} rows for {len(lines)} BOM lines")+ if not any(l.get("unit") is not None for l in lines):+ warns.append("components: no prices recorded (the page says so; add a unit_price column to show a board total)")+ pkg = rjson(os.path.join(bundle, "package.json"))+ if isinstance(pkg, dict):+ if pkg.get("readme_order") != ["html"]:+ errors.append('package.json readme_order is not ["html"]: the page would not show readme.html alone')+ else:+ warns.append("no package.json in the folder (molecule-publish Stage 2 writes it): set readme_order [\"html\"] in the page fields when you publish")+ if not os.path.isfile(os.path.join(bundle, "README.md")):+ errors.append("no README.md (the wiki still needs it for search and excerpts)")+ if re.search(r"—", text):+ errors.append("readme.html has an em-dash")+ return {"passed": not errors, "errors": errors, "warnings": warns, "bundle": bundle,+ "explorer": {"coverage": ex["coverage"]["percent"], "diffs": ex["diffs"], "auto": ex["autoDrawn"], "hand": ex["handDrawn"]} if ex else None,+ "figures": len(figs.get("figures") or []), "bomLines": len(lines)}+++def main():+ cfg = json.load(open(sys.argv[1]))+ cfg.setdefault("now", now())+ mode = cfg.get("mode") or "build"+ if mode == "build":+ out = build(cfg)+ elif mode == "check":+ b = cfg.get("bundle")+ if not b or not os.path.isdir(b):+ fail(f"no page folder to check ({b}): `project-page --molecule-bundle <folder>` builds one, `project-page check --bundle <folder>` checks it")+ out = dict(check_bundle(os.path.abspath(b), cfg), ok=True, mode="check")+ else:+ fail(f"mode {mode}: build or check (the Markdown design review is `adom-aiflow project-page --results`)")+ print(json.dumps(out))+++if __name__ == "__main__":+ main()
tools/page-explorer/explorer.cssadded+84@@ -0,0 +1,84 @@+/* <aiflow-explorer> (adom-aiflow project-page): the block flowchart and each block's circuit. Dark card, light paper+ for the schematics so a drawing reads like a textbook figure. */+:host { display: block; color: #e6edf3; font: 14px/1.5 'Satoshi', -apple-system, 'Segoe UI', sans-serif; }+* { box-sizing: border-box; }+.ex { border: 1px solid #30363d; border-radius: 8px; background: #161b22; overflow: hidden; }+.bar { display: flex; align-items: center; gap: 10px; padding: 8px 12px; border-bottom: 1px solid #30363d; background: #1c2128; flex-wrap: wrap; }+.bar .t { font: 700 15px 'Familjen Grotesk', -apple-system, sans-serif; }+.bar .hint { color: #8b949e; font-size: 12.5px; }+.flow-wrap { overflow-x: auto; padding: 6px 4px 2px; }+svg.flow { display: block; margin: 0 auto; width: 100%; height: auto; min-width: 640px; }+svg.flow .node rect { fill: #1c2128; stroke: #3d444d; stroke-width: 1.2; transition: stroke .15s, fill .15s; }+svg.flow .node.auto rect { stroke-dasharray: 5 3; }+svg.flow .node.probe rect { fill: #161b22; }+svg.flow .node:hover rect { stroke: #00b8b1; }+svg.flow .node.sel rect { stroke: #00e6dc; stroke-width: 2; fill: #0f2a2a; }+svg.flow .node { cursor: pointer; outline: none; }+svg.flow .node:focus-visible rect { stroke: #00e6dc; stroke-width: 2.4; }+svg.flow .node .nt { fill: #e6edf3; font: 700 13px 'Familjen Grotesk', -apple-system, sans-serif; }+svg.flow .node .ns { fill: #8b949e; font: 11px 'Satoshi', -apple-system, sans-serif; }+svg.flow .edge .ln { fill: none; stroke: #4c5560; stroke-width: 1.4; }+svg.flow .edge.pwr .ln { stroke: #8a6a3a; }+svg.flow .edge.on .ln { stroke: #00b8b1; stroke-width: 2; }+svg.flow .edge.off { opacity: .35; }+svg.flow .edge .lb rect { fill: #0d1117; stroke: #30363d; }+svg.flow .edge .lb text { fill: #b1bac4; font: 10.5px 'JetBrains Mono', ui-monospace, monospace; }+svg.flow .edge.on .lb text { fill: #e6edf3; }+svg.flow .edge .hit { stroke: transparent; stroke-width: 10; fill: none; }+.detail { border-top: 1px solid #30363d; padding: 12px 14px 14px; }+.dhead { display: flex; align-items: baseline; gap: 10px; flex-wrap: wrap; margin-bottom: 6px; }+.dhead h3 { margin: 0; font: 700 17px 'Familjen Grotesk', -apple-system, sans-serif; }+.tag { font-size: 11.5px; padding: 0 8px; border-radius: 10px; border: 1px solid #30363d; color: #8b949e; }+.tag.good { color: #3fb950; border-color: rgba(63,185,80,.45); }+.tag.warn { color: #d29922; border-color: rgba(210,153,34,.45); }+.tag.bad { color: #f85149; border-color: rgba(248,81,73,.45); }+.tabs { display: flex; gap: 6px; flex-wrap: wrap; margin: 4px 0 8px; }+.tabs button { background: #1c2128; color: #c9d1d9; border: 1px solid #30363d; border-radius: 6px; padding: 3px 10px; font: inherit; font-size: 12.5px; cursor: pointer; }+.tabs button.on { border-color: #00b8b1; color: #e6edf3; }+.dtext { color: #c9d1d9; margin: 0 0 10px; max-width: 900px; }+.paper { background: #fbfcfd; border-radius: 6px; border: 1px solid #30363d; overflow: auto; padding: 8px; }+.paper svg { display: block; margin: 0 auto; height: auto; }+.net { min-height: 22px; margin: 8px 0 4px; color: #8b949e; font-size: 12.5px; }+.net b { color: #e6edf3; font-family: 'JetBrains Mono', ui-monospace, monospace; font-weight: 500; }+.net a { color: #00b8b1; cursor: pointer; }+table.pl { width: 100%; border-collapse: collapse; margin-top: 8px; font-size: 12.5px; }+table.pl th, table.pl td { padding: 4px 8px; border: 1px solid #30363d; text-align: left; }+table.pl th { background: #1c2128; font-weight: 500; }+table.pl td.r { font-family: 'JetBrains Mono', ui-monospace, monospace; }+table.pl tr.hot td { background: rgba(224,117,11,.14); }+table.pl a { color: #00b8b1; text-decoration: none; }+details.pd > summary { cursor: pointer; color: #00b8b1; margin-top: 8px; font-size: 13px; }+/* the schematic */+svg.sch { --ink: #1d2a3a; --ink2: #5b6b80; --wire: #2f4a6b; --spaper: #fbfcfd; --val: #0c6f6b; --flag: #6c4fd6; --flagbg: rgba(108,79,214,.08);+ --tp: #0b8f88; --hl: #e0750b; --region: rgba(47,74,107,.35); overflow: visible; font-family: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }+svg.sch .sym path, svg.sch .sym .body { fill: none; stroke: var(--ink); stroke-width: 1.5; stroke-linejoin: round; stroke-linecap: round; }+svg.sch .sym path.fill, svg.sch .sym .dot { fill: var(--ink); stroke: none; }+svg.sch .part.tp .sym circle { stroke: var(--tp); fill: var(--spaper); }+svg.sch .part.tp .sym path, svg.sch .part.mc .sym path { stroke: var(--tp); }+svg.sch .part.mc .sym path.fill { fill: var(--tp); }+svg.sch .part.mc .sym circle { stroke: var(--tp); fill: none; stroke-width: 1.5; }+svg.sch .wire { fill: none; stroke: var(--wire); stroke-width: 1.4; stroke-linejoin: round; stroke-linecap: round; }+svg.sch .junction { fill: var(--wire); }+svg.sch .gnd, svg.sch .rail path { fill: none; stroke: var(--ink2); stroke-width: 1.4; stroke-linecap: round; }+svg.sch text { font-size: 9px; fill: var(--ink2); }+svg.sch .ref { fill: var(--ink2); font-size: 8.5px; }+svg.sch .val { fill: var(--val); font-size: 9px; font-weight: 600; }+svg.sch .pinname { font-size: 7.5px; fill: var(--ink2); }+svg.sch .inner { font-size: 7.5px; fill: var(--ink); font-weight: 600; }+svg.sch .tpl { fill: var(--tp); font-size: 8.5px; font-weight: 700; }+svg.sch .rail text { fill: var(--ink); font-size: 8.5px; font-weight: 600; }+svg.sch .gname { fill: var(--ink2); font-size: 7.5px; }+svg.sch .flag path { fill: var(--flagbg); stroke: var(--flag); stroke-width: 1.2; }+svg.sch .flag text { fill: var(--flag); font-size: 8.5px; font-weight: 600; }+svg.sch .note { fill: var(--ink2); font-size: 8.5px; font-style: italic; }+svg.sch .region { fill: none; stroke: var(--region); stroke-width: 1; stroke-dasharray: 4 3; }+svg.sch .region-t { fill: var(--ink2); font-size: 8.5px; font-weight: 600; }+svg.sch .boxbody { fill: #f1f4f8; stroke: var(--ink); stroke-width: 1.5; }+svg.sch .hit { fill: transparent; stroke: none; }+svg.sch .wire-hit { fill: none; stroke: transparent; stroke-width: 9; pointer-events: stroke; cursor: crosshair; }+svg.sch .part, svg.sch .flag { cursor: pointer; }+svg.sch .hl.wire, svg.sch .hl.gnd, svg.sch .rail.hl path { stroke: var(--hl); stroke-width: 2.4; }+svg.sch .hl.junction { fill: var(--hl); }+svg.sch .flag.hl path { stroke: var(--hl); stroke-width: 2; }+svg.sch .part.hot .sym path, svg.sch .part.hot .sym .body, svg.sch .part.hot .boxbody { stroke: var(--hl); }+svg.sch .part.hot .ref { fill: var(--hl); }
tools/page-explorer/explorer.jsadded+320@@ -0,0 +1,320 @@+/* <aiflow-explorer>: the board's circuit explorer (adom-aiflow project-page, issue #131). A block flowchart built from+ the netlist's blocks and the nets between them; click a block for its circuit, drawn from a small JSON per block and+ checked against the netlist by tools/page-build.py, which also resolves every position and net this script draws.+ Data: <script type="application/json" id="aiflow-explorer-data">, symbols in window.AIFLOW_SYMBOLS, style in+ window.AIFLOW_EXPLORER_CSS. No network, no storage: it runs in the wiki's sandboxed readme frame. */+(function () {+ 'use strict';+ if (!window.customElements || customElements.get('aiflow-explorer')) return;+ var esc = function (s) { return String(s == null ? '' : s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"'); };+ var CW = 5.6;++ function xf(pt, P) {+ var x = pt[0], y = pt[1];+ if (P.mx) x = -x;+ if (P.my) y = -y;+ if (P.rot === 90) { var t = x; x = -y; y = t; }+ else if (P.rot === 180) { x = -x; y = -y; }+ else if (P.rot === 270) { var u = x; x = y; y = -u; }+ return [P.x + x, P.y + y];+ }+ function bbox(bb, P) {+ var a = xf([bb[0], bb[1]], P), b = xf([bb[2], bb[3]], P);+ return [Math.min(a[0], b[0]), Math.min(a[1], b[1]), Math.max(a[0], b[0]), Math.max(a[1], b[1])];+ }++ function boxSym(spec) {+ var pins = {}, d = [], txt = [], hw = spec.w / 2, hh = spec.h / 2;+ spec.pins.forEach(function (pn) {+ var name = pn[0], side = pn[1], off = pn[2], p, q, t, an;+ if (side === 'L') { p = [-hw - 10, -hh + off]; q = [-hw, -hh + off]; t = [-hw + 4, -hh + off + 3]; an = 'start'; }+ else if (side === 'R') { p = [hw + 10, -hh + off]; q = [hw, -hh + off]; t = [hw - 4, -hh + off + 3]; an = 'end'; }+ else if (side === 'T') { p = [-hw + off, -hh - 10]; q = [-hw + off, -hh]; t = [-hw + off, -hh + 11]; an = 'middle'; }+ else { p = [-hw + off, hh + 10]; q = [-hw + off, hh]; t = [-hw + off, hh - 5]; an = 'middle'; }+ pins[name] = p;+ d.push('M' + p[0] + ',' + p[1] + 'L' + q[0] + ',' + q[1]);+ txt.push([t[0], t[1], name, an]);+ });+ return { pins: pins, d: d.join(''), bb: [-hw, -hh, hw, hh], boxText: txt, title: spec.title, w: spec.w, h: spec.h };+ }++ function partLabel(p, sym) {+ var P = p;+ if (P.lab === 'n') return '';+ var name = p.sym, ref = p.ref, val = sym.tp ? '' : p.value;+ var vertical = (P.rot === 90 || P.rot === 270), x, y, anchor, stack = true;+ if (P.labxy) { x = P.x + P.labxy[0]; y = P.y + P.labxy[1]; anchor = P.labxy[2] || 'start'; stack = P.labxy[3] !== 'line'; }+ else if (sym.tp) {+ var tip = xf([0, -19], P), dx = tip[0] - P.x, dy = tip[1] - P.y;+ x = tip[0]; y = tip[1] + (dy > 0 ? 8 : dy < 0 ? -1 : 3);+ anchor = dx > 0 ? 'start' : dx < 0 ? 'end' : 'middle';+ return '<text class="tpl" x="' + x + '" y="' + y + '" text-anchor="' + anchor + '">' + esc(sym.mc ? ref : ref) + '</text>';+ } else if (sym.two) {+ var side = P.lab || (vertical ? 'r' : 't');+ if (side === 't') { x = P.x; y = P.y - 11; anchor = 'middle'; stack = false; if (name === 'LED') y -= 6; }+ else if (side === 'b') { x = P.x; y = P.y + 18; anchor = 'middle'; stack = false; }+ else if (side === 'r') { x = P.x + 10; y = P.y - 1; anchor = 'start'; }+ else { x = P.x - 10; y = P.y - 1; anchor = 'end'; }+ } else if (sym.fet) {+ var s2 = P.lab || (P.mx !== (P.rot === 180) ? 'l' : 'r');+ if (s2 === 'l') { x = P.x - 17; anchor = 'end'; } else { x = P.x + 26; anchor = 'start'; }+ y = P.y - 2;+ if (s2 === 't') { x = P.x; y = P.y - 26; anchor = 'middle'; stack = false; }+ if (s2 === 'b') { x = P.x; y = P.y + 34; anchor = 'middle'; stack = false; }+ } else if (name === 'OPAMP') {+ return '<text class="ref" x="' + P.x + '" y="' + (P.lab === 'b' ? P.y + 34 : P.y - 27) + '" text-anchor="middle">' + esc(ref) + '</text>';+ } else if (name === 'BOX') { return ''; }+ else { x = P.x + 12; y = P.y; anchor = 'start'; }+ if (stack) {+ return '<text class="ref" x="' + x + '" y="' + y + '" text-anchor="' + anchor + '">' + esc(ref) + '</text>' ++ (val ? '<text class="val" x="' + x + '" y="' + (y + 10.5) + '" text-anchor="' + anchor + '">' + esc(val) + '</text>' : '');+ }+ return '<text x="' + x + '" y="' + y + '" text-anchor="' + anchor + '"><tspan class="ref">' + esc(ref) + '</tspan>' ++ (val ? ' <tspan class="val">' + esc(val) + '</tspan>' : '') + '</text>';+ }++ function drawPart(p, SYMS) {+ var sym = p.sym === 'BOX' ? boxSym(p.box) : SYMS[p.sym];+ if (!sym) return '';+ var tr = 'translate(' + p.x + ',' + p.y + ')' + (p.rot ? ' rotate(' + p.rot + ')' : '') + (p.mx || p.my ? ' scale(' + (p.mx ? -1 : 1) + ',' + (p.my ? -1 : 1) + ')' : '');+ var g = '<g class="sym" transform="' + tr + '">';+ if (p.sym === 'BOX') g += '<rect class="boxbody" x="' + (-sym.w / 2) + '" y="' + (-sym.h / 2) + '" width="' + sym.w + '" height="' + sym.h + '" rx="2"/>';+ if (sym.circle) g += '<circle class="body" cx="' + sym.circle[0] + '" cy="' + sym.circle[1] + '" r="' + sym.circle[2] + '"/>';+ g += '<path d="' + sym.d + '"/>';+ if (sym.f) g += '<path class="fill" d="' + sym.f + '"/>';+ (sym.dots || []).forEach(function (dt) { g += '<circle class="dot" cx="' + dt[0] + '" cy="' + dt[1] + '" r="2.2"/>'; });+ g += '</g>';+ if (sym.boxText) {+ sym.boxText.forEach(function (t) { var q = xf([t[0], t[1]], { x: p.x, y: p.y, rot: 0 }); g += '<text class="pinname" x="' + q[0] + '" y="' + q[1] + '" text-anchor="' + t[3] + '">' + esc(t[2]) + '</text>'; });+ var tl = Array.isArray(sym.title) ? sym.title : [sym.title || p.ref];+ tl.forEach(function (s, i) { g += '<text class="' + (i ? 'val' : 'ref') + '" x="' + p.x + '" y="' + (p.y + sym.bb[1] - 6 - (tl.length - 1 - i) * 11) + '" text-anchor="middle">' + esc(s) + '</text>'; });+ }+ if (p.text) g += '<text class="inner" x="' + p.x + '" y="' + (p.y + 3) + '" text-anchor="middle">' + esc(p.text) + '</text>';+ var b = bbox(sym.bb, p), pad = 4;+ g += '<rect class="hit" x="' + (b[0] - pad) + '" y="' + (b[1] - pad) + '" width="' + (b[2] - b[0] + 2 * pad) + '" height="' + (b[3] - b[1] + 2 * pad) + '"/>';+ var cls = 'part' + (sym.tp ? (sym.mc ? ' mc' : ' tp') : '');+ return '<g class="' + cls + '" data-ref="' + esc(p.ref) + '">' + g + partLabel(p, sym) + '</g>';+ }++ function drawAnchor(a) {+ var x = a.p[0], y = a.p[1], n = esc(a.net || a.name);+ if (a.kind === 'gnd') {+ var v = { down: [0, 1], up: [0, -1], left: [-1, 0], right: [1, 0] }[a.dir] || [0, 1];+ var px = function (s, t) { return [x + v[0] * s + v[1] * t, y + v[1] * s + v[0] * t]; };+ var L = function (s, t1, t2) { var p = px(s, t1), q = px(s, t2); return 'M' + p[0] + ',' + p[1] + 'L' + q[0] + ',' + q[1]; };+ var e = px(6, 0), lab = '';+ if (a.name && a.name !== 'GND') { var tp = px(19, 0); lab = '<text class="gname" x="' + tp[0] + '" y="' + (tp[1] + 2.5) + '" text-anchor="middle">' + esc(a.name) + '</text>'; }+ return '<g data-net="' + n + '"><path class="gnd" data-net="' + n + '" d="M' + x + ',' + y + 'L' + e[0] + ',' + e[1] + L(6, -7, 7) + L(9, -4.5, 4.5) + L(12, -2, 2) + '"/>' + lab + '</g>';+ }+ if (a.kind === 'rail') {+ var d, tx, ty, an;+ if (a.dir === 'up') { d = 'M' + x + ',' + y + 'V' + (y - 9) + 'M' + (x - 6) + ',' + (y - 9) + 'H' + (x + 6); tx = x; ty = y - 13; an = 'middle'; }+ else if (a.dir === 'down') { d = 'M' + x + ',' + y + 'V' + (y + 9) + 'M' + (x - 6) + ',' + (y + 9) + 'H' + (x + 6); tx = x; ty = y + 20; an = 'middle'; }+ else if (a.dir === 'right') { d = 'M' + x + ',' + y + 'H' + (x + 9) + 'M' + (x + 9) + ',' + (y - 6) + 'V' + (y + 6); tx = x + 13; ty = y + 3.5; an = 'start'; }+ else { d = 'M' + x + ',' + y + 'H' + (x - 9) + 'M' + (x - 9) + ',' + (y - 6) + 'V' + (y + 6); tx = x - 13; ty = y + 3.5; an = 'end'; }+ return '<g class="rail" data-net="' + n + '"><path d="' + d + '"/><text x="' + tx + '" y="' + ty + '" text-anchor="' + an + '">' + esc(a.name) + '</text></g>';+ }+ var tw = a.name.length * CW + 10, h = 7, pts, cx, cy;+ if (a.dir === 'right') { pts = [[x, y], [x + 6, y - h], [x + 6 + tw, y - h], [x + 6 + tw, y + h], [x + 6, y + h]]; cx = x + 6 + tw / 2; cy = y + 3.3; }+ else if (a.dir === 'left') { pts = [[x, y], [x - 6, y - h], [x - 6 - tw, y - h], [x - 6 - tw, y + h], [x - 6, y + h]]; cx = x - 6 - tw / 2; cy = y + 3.3; }+ else if (a.dir === 'up') { pts = [[x, y], [x + h, y - 6], [x + h, y - 6 - tw], [x - h, y - 6 - tw], [x - h, y - 6]]; cx = x; cy = y - 6 - tw / 2; }+ else { pts = [[x, y], [x + h, y + 6], [x + h, y + 6 + tw], [x - h, y + 6 + tw], [x - h, y + 6]]; cx = x; cy = y + 6 + tw / 2; }+ var vert = a.dir === 'up' || a.dir === 'down';+ return '<g class="flag" data-net="' + n + '" tabindex="0" role="button"><path d="M' + pts.map(function (p) { return p.join(','); }).join('L') + 'Z"/>' ++ '<text x="' + cx + '" y="' + cy + '" text-anchor="middle"' + (vert ? ' transform="rotate(-90 ' + cx + ' ' + cy + ')" dy="3.3"' : '') + '>' + esc(a.name) + '</text></g>';+ }++ function renderSch(dr, SYMS) {+ var o = ['<svg class="sch" viewBox="0 0 ' + dr.w + ' ' + dr.h + '" width="' + dr.w + '" height="' + dr.h + '" xmlns="http://www.w3.org/2000/svg">'];+ o.push('<g class="boxes">');+ (dr.boxes || []).forEach(function (b) {+ o.push('<rect class="region" x="' + b[0] + '" y="' + b[1] + '" width="' + b[2] + '" height="' + b[3] + '" rx="4"/>');+ if (b[4]) o.push('<text class="region-t" x="' + (b[0] + 4) + '" y="' + (b[1] - 4) + '">' + esc(b[4]) + '</text>');+ });+ o.push('</g><g class="wires">');+ dr.wires.forEach(function (w) {+ var d = 'M' + w.pts.map(function (p) { return p.join(','); }).join('L');+ o.push('<path class="wire" data-net="' + esc(w.net || '') + '" d="' + d + '"/><path class="wire-hit" data-net="' + esc(w.net || '') + '" d="' + d + '"/>');+ });+ dr.junctions.forEach(function (j) { o.push('<circle class="junction" data-net="' + esc(j[2] || '') + '" cx="' + j[0] + '" cy="' + j[1] + '" r="2.6"/>'); });+ o.push('</g><g class="anchors">');+ dr.anchors.forEach(function (a) { o.push(drawAnchor(a)); });+ o.push('</g><g class="parts">');+ dr.parts.forEach(function (p) { o.push(drawPart(p, SYMS)); });+ o.push('</g><g class="notes">');+ (dr.notes || []).forEach(function (n) {+ String(n[2]).split('\n').forEach(function (line, i) { o.push('<text class="note" x="' + n[0] + '" y="' + (n[1] + i * 11) + '" text-anchor="' + (n[3] || 'start') + '">' + esc(line) + '</text>'); });+ });+ o.push('</g></svg>');+ return o.join('');+ }++ // ------------------------------------------------------------------ the flowchart+ function renderFlow(F, sel) {+ var N = {}, o = [];+ F.nodes.forEach(function (n) { N[n.id] = n; });+ var outs = {}, ins = {};+ F.edges.forEach(function (e, i) { (outs[e.fromNode] = outs[e.fromNode] || []).push(i); (ins[e.toNode] = ins[e.toNode] || []).push(i); });+ // ports spread along the node's side, in the order of the other end's height, so arrows do not cross at the node+ Object.keys(outs).forEach(function (k) { outs[k].sort(function (p, q) { return N[F.edges[p].toNode].y - N[F.edges[q].toNode].y; }); });+ Object.keys(ins).forEach(function (k) { ins[k].sort(function (p, q) { return N[F.edges[p].fromNode].y - N[F.edges[q].fromNode].y; }); });+ var port = function (list, id, i, side) {+ var n = N[id], k = list[id].indexOf(i), m = list[id].length;+ return [side === 'out' ? n.x + n.w : n.x, n.y + 8 + (n.h - 16) * (k + 1) / (m + 1)];+ };+ o.push('<svg class="flow" viewBox="0 0 ' + F.w + ' ' + F.h + '" width="' + F.w + '" height="' + F.h + '" xmlns="http://www.w3.org/2000/svg">');+ o.push('<defs><marker id="ah" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse"><path d="M0,1L9,5L0,9Z" fill="#6e7681"/></marker>' ++ '<marker id="ahon" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0,1L9,5L0,9Z" fill="#00b8b1"/></marker></defs>');+ var labels = [], lines = [];+ F.edges.forEach(function (e, i) {+ var a = port(outs, e.fromNode, i, 'out'), b = port(ins, e.toNode, i, 'in'), d, lx, ly;+ var A = N[e.fromNode], B = N[e.toNode];+ var sameCol = Math.abs(A.x - B.x) < 10;+ if (sameCol) {+ var down = B.y > A.y, ax = A.x + A.w * (0.35 + 0.3 * ((i % 3) / 2)), bx = B.x + B.w * (0.35 + 0.3 * ((i % 3) / 2));+ var ay = down ? A.y + A.h : A.y, by = down ? B.y : B.y + B.h, k = down ? 1 : -1;+ d = 'M' + ax + ',' + ay + 'C' + ax + ',' + (ay + 18 * k) + ' ' + bx + ',' + (by - 18 * k) + ' ' + bx + ',' + by;+ lx = (ax + bx) / 2 + 30; ly = (ay + by) / 2;+ } else if (b[0] < a[0] - 20) {+ var lo2 = Math.max(A.y + A.h, B.y + B.h) + 18 + (i % 4) * 6, acx = A.x + A.w / 2, bcx = B.x + B.w / 2;+ d = 'M' + acx + ',' + (A.y + A.h) + 'C' + acx + ',' + lo2 + ' ' + acx + ',' + lo2 + ' ' + (acx - 30) + ',' + lo2 + 'L' + (bcx + 30) + ',' + lo2 + 'C' + bcx + ',' + lo2 + ' ' + bcx + ',' + lo2 + ' ' + bcx + ',' + (B.y + B.h);+ lx = (acx + bcx) / 2; ly = lo2;+ } else if (b[0] > a[0] + 20) {+ var mx = a[0] + Math.min(48, (b[0] - a[0]) / 2), mx2 = b[0] - Math.min(48, (b[0] - a[0]) / 2);+ d = 'M' + a[0] + ',' + a[1] + 'C' + mx + ',' + a[1] + ' ' + mx2 + ',' + b[1] + ' ' + b[0] + ',' + b[1];+ lx = (a[0] + b[0]) / 2; ly = (a[1] + b[1]) / 2;+ } else {+ var lo = Math.max(A.y + A.h, B.y + B.h) + 16;+ d = 'M' + a[0] + ',' + a[1] + 'C' + (a[0] + 40) + ',' + a[1] + ' ' + (a[0] + 40) + ',' + lo + ' ' + ((a[0] + b[0]) / 2) + ',' + lo + 'S' + (b[0] - 40) + ',' + b[1] + ' ' + b[0] + ',' + b[1];+ lx = (a[0] + b[0]) / 2; ly = lo;+ }+ var on = sel && (e.from === sel || e.to === sel), off = sel && !on;+ var pwr = (e.nets || []).some(function (n) { return /^\+|^V|VDD|VCC|VBAT/i.test(n); });+ var tip = e.from + ' to ' + e.to + ': ' + (e.nets || []).join(', ');+ lines.push({ on: on, s: '<g class="edge' + (on ? ' on' : '') + (off ? ' off' : '') + (pwr ? ' pwr' : '') + '"><title>' + esc(tip) + '</title>' ++ '<path class="hit" d="' + d + '"/><path class="ln" d="' + d + '" marker-end="url(#' + (on ? 'ahon' : 'ah') + ')"/></g>' });+ if (on || !sel) labels.push({ x: lx, y: ly, t: e.label, on: on, tip: tip });+ });+ lines.sort(function (p, q) { return (p.on ? 1 : 0) - (q.on ? 1 : 0); }).forEach(function (l) { o.push(l.s); });+ F.nodes.forEach(function (n) {+ o.push('<g class="node' + (n.hand ? '' : ' auto') + (n.probe ? ' probe' : '') + (n.block === sel ? ' sel' : '') + '" data-id="' + esc(n.block) + '" tabindex="0" role="button" aria-label="' + esc(n.title) + '">' ++ '<rect x="' + n.x + '" y="' + n.y + '" width="' + n.w + '" height="' + n.h + '" rx="8"/>' ++ '<text class="nt" x="' + (n.x + 11) + '" y="' + (n.y + 24) + '">' + esc(n.title) + '</text>' ++ '<text class="ns" x="' + (n.x + 11) + '" y="' + (n.y + 42) + '">' + esc(n.sub) + '</text></g>');+ });+ // labels on top, nudged apart so they do not sit on each other or on a block+ labels.sort(function (p, q) { return p.y - q.y; });+ var placed = [];+ labels.forEach(function (l) {+ var w = l.t.length * 6.2 + 12, h = 16, y = l.y, x = l.x;+ var clash = function (yy) {+ return placed.some(function (p) { return Math.abs(p.x - x) < (p.w + w) / 2 + 2 && Math.abs(p.y - yy) < h; }) ||+ F.nodes.some(function (n) { return x + w / 2 > n.x && x - w / 2 < n.x + n.w && yy + h / 2 > n.y && yy - h / 2 < n.y + n.h; });+ };+ for (var k = 0; k < 16 && clash(y); k++) y = l.y + (k % 2 ? -1 : 1) * h * Math.ceil((k + 1) / 2);+ placed.push({ x: x, y: y, w: w });+ o.push('<g class="edge lbl' + (l.on ? ' on' : '') + '"><title>' + esc(l.tip) + '</title><g class="lb"><rect x="' + (x - w / 2) + '" y="' + (y - 8) + '" width="' + w + '" height="' + h + '" rx="8"/>' ++ '<text x="' + x + '" y="' + (y + 3.5) + '" text-anchor="middle">' + esc(l.t) + '</text></g></g>');+ });+ o.push('</svg>');+ return o.join('');+ }++ class AiflowExplorer extends HTMLElement {+ connectedCallback() {+ if (this._done) return;+ this._done = true;+ var src = document.getElementById(this.getAttribute('data-src') || 'aiflow-explorer-data');+ try { this.D = JSON.parse(src.textContent); } catch (e) { this.textContent = 'Circuit explorer: no data.'; return; }+ this.SYMS = window.AIFLOW_SYMBOLS || {};+ this.byId = {};+ var self = this;+ this.D.drawings.forEach(function (d) { self.byId[d.id] = d; });+ this.root = this.attachShadow ? this.attachShadow({ mode: 'open' }) : this;+ this.root.innerHTML = '<style>' + (window.AIFLOW_EXPLORER_CSS || '') + '</style>' ++ '<div class="ex"><div class="bar"><span class="t">How the board works</span><span class="hint">Click a block for its circuit. Arrows carry the nets between blocks.</span></div>' ++ '<div class="flow-wrap"></div><div class="detail"></div></div>';+ this.flowEl = this.root.querySelector('.flow-wrap');+ this.detEl = this.root.querySelector('.detail');+ var first = this.D.blocks.filter(function (b) { return !b.auto && b.drawings.length; })[0] || this.D.blocks.filter(function (b) { return b.drawings.length; })[0];+ this.select(this.getAttribute('block') || (first && first.id), null);+ this.flowEl.addEventListener('click', function (ev) { var n = ev.target.closest('.node'); if (n) self.select(n.getAttribute('data-id'), null); });+ this.flowEl.addEventListener('keydown', function (ev) { var n = ev.target.closest('.node'); if (n && (ev.key === 'Enter' || ev.key === ' ')) { ev.preventDefault(); self.select(n.getAttribute('data-id'), null); } });+ }+ select(block, drawing, net) {+ var b = this.D.blocks.filter(function (x) { return x.id === block; })[0];+ if (!b) return;+ this.sel = block;+ this.flowEl.innerHTML = renderFlow(this.D.flow, block);+ var did = drawing && b.drawings.indexOf(drawing) >= 0 ? drawing : b.drawings[0];+ this.showDrawing(b, did, net);+ }+ showDrawing(b, did, net) {+ var self = this, dr = this.byId[did];+ var tags = dr ? (dr.auto ? '<span class="tag warn">auto-drawn: every pin labelled with its net</span>' : '<span class="tag good">drawn by hand, netlist-checked</span>') ++ (dr.errors && dr.errors.length ? '<span class="tag bad">' + dr.errors.length + ' difference(s) from the netlist</span>' : '<span class="tag good">0 differences</span>') : '<span class="tag">no drawing</span>';+ var tabs = b.drawings.length > 1 ? '<div class="tabs">' + b.drawings.map(function (id) { var d = self.byId[id]; return '<button data-d="' + esc(id) + '"' + (id === did ? ' class="on"' : '') + '>' + esc(d.title || id) + '</button>'; }).join('') + '</div>' : '';+ var text = (dr && dr.text) || b.text || '';+ var rows = b.parts.map(function (r) {+ var p = self.D.parts[r] || {};+ var mpn = p.mpn ? (p.page ? '<a href="https://wiki.adom.inc/' + esc(p.page) + '" target="_blank" rel="noopener">' + esc(p.mpn) + '</a>' : esc(p.mpn)) : '';+ return '<tr data-ref="' + esc(r) + '"><td class="r">' + esc(r) + '</td><td>' + esc(p.value) + '</td><td>' + mpn + '</td><td>' + esc(p.note || p.desc || '') + '</td></tr>';+ }).join('');+ this.detEl.innerHTML = '<div class="dhead"><h3>' + esc(b.title) + (dr && dr.title && dr.title !== b.title ? ': ' + esc(dr.title) : '') + '</h3>' + tags + '</div>' + tabs ++ (text ? '<p class="dtext">' + esc(text) + '</p>' : '') ++ (dr ? '<div class="paper">' + renderSch(dr, this.SYMS) + '</div>' : '') ++ '<div class="net">Hover a wire or a label to trace its net.</div>' ++ '<details class="pd"' + (b.parts.length <= 12 ? ' open' : '') + '><summary>' + b.parts.length + ' part' + (b.parts.length === 1 ? '' : 's') + ' in this block</summary>' ++ '<table class="pl"><thead><tr><th>Ref</th><th>Value</th><th>MPN</th><th>Role</th></tr></thead><tbody>' + rows + '</tbody></table></details>';+ var svg = this.detEl.querySelector('svg.sch');+ if (svg && dr) { svg.style.width = '100%'; svg.style.maxWidth = Math.round(dr.w * 1.5) + 'px'; svg.removeAttribute('height'); }+ this.detEl.querySelectorAll('.tabs button').forEach(function (bt) { bt.addEventListener('click', function () { self.showDrawing(b, bt.getAttribute('data-d')); }); });+ var netEl = this.detEl.querySelector('.net');+ var hl = function (n) {+ if (!svg) return;+ svg.querySelectorAll('.hl').forEach(function (x) { x.classList.remove('hl'); });+ if (!n) { netEl.innerHTML = 'Hover a wire or a label to trace its net.'; return; }+ svg.querySelectorAll('[data-net="' + CSS.escape(n) + '"]').forEach(function (x) { x.classList.add('hl'); });+ var others = self.D.drawings.filter(function (d) { return d.id !== did && d.nets.indexOf(n) >= 0; });+ netEl.innerHTML = 'Net <b>' + esc(n) + '</b>' + (others.length ? ': also in ' + others.map(function (d) { return '<a data-go="' + esc(d.id) + '">' + esc(self.titleOf(d)) + '</a>'; }).join(', ') : ': only in this block');+ netEl.querySelectorAll('a[data-go]').forEach(function (a) { a.addEventListener('click', function () { self.goDrawing(a.getAttribute('data-go'), n); }); });+ };+ if (svg) {+ svg.addEventListener('mouseover', function (ev) { var t = ev.target.closest('[data-net]'); if (t && t.getAttribute('data-net')) hl(t.getAttribute('data-net')); });+ svg.addEventListener('click', function (ev) {+ var f = ev.target.closest('.flag');+ if (f) {+ var n = f.getAttribute('data-net'), others = self.D.drawings.filter(function (d) { return d.id !== did && d.nets.indexOf(n) >= 0; });+ if (others.length) self.goDrawing(others[0].id, n);+ return;+ }+ var p = ev.target.closest('.part');+ if (p) {+ svg.querySelectorAll('.part.hot').forEach(function (x) { x.classList.remove('hot'); });+ p.classList.add('hot');+ var ref = p.getAttribute('data-ref');+ self.detEl.querySelectorAll('table.pl tr').forEach(function (tr) { tr.classList.toggle('hot', tr.getAttribute('data-ref') === ref); });+ var det = self.detEl.querySelector('details.pd'); if (det) det.open = true;+ var pp = self.D.parts[ref] || {};+ netEl.innerHTML = '<b>' + esc(ref) + '</b> ' + esc(pp.value || '') + (pp.mpn ? ', ' + esc(pp.mpn) : '') + (pp.mfr ? ' (' + esc(pp.mfr) + ')' : '') + (pp.note ? ': ' + esc(pp.note) : '');+ }+ });+ if (arguments.length > 2 && arguments[2]) hl(arguments[2]);+ }+ }+ titleOf(d) {+ var b = this.D.blocks.filter(function (x) { return x.id === d.block; })[0];+ return (b ? b.title : d.block) + (d.title && b && d.title !== b.title ? ': ' + d.title : '');+ }+ goDrawing(id, net) {+ var d = this.byId[id];+ if (!d) return;+ this.sel = d.block;+ this.flowEl.innerHTML = renderFlow(this.D.flow, d.block);+ var b = this.D.blocks.filter(function (x) { return x.id === d.block; })[0];+ this.showDrawing(b, id, net);+ this.detEl.scrollIntoView({ block: 'nearest', behavior: 'smooth' });+ }+ }+ customElements.define('aiflow-explorer', AiflowExplorer);+})();
tools/page-explorer/symbols.jsonadded+26@@ -0,0 +1,26 @@+{+ "_": "The circuit explorer's symbols (adom-aiflow project-page). One file for the netlist check (tools/page-build.py reads the pin positions) and the page (explorer.js draws the paths). Local coordinates in px, rotation 0, y down; pins are the wire ends. A symbol pin maps to part pins by name (R, C: 1 2; diodes: k a; MOSFET: g d s; BJT: b c e; test points and machine parts: p).",+ "R": {"pins": {"1": [-20, 0], "2": [20, 0]}, "d": "M-20,0H-12l2,-5l4,10l4,-10l4,10l4,-10l4,10l2,-5H20", "bb": [-13, -6, 13, 6], "two": true},+ "C": {"pins": {"1": [-20, 0], "2": [20, 0]}, "d": "M-20,0H-3M-3,-8V8M3,-8V8M3,0H20", "bb": [-4, -9, 4, 9], "two": true},+ "CP": {"pins": {"1": [-20, 0], "2": [20, 0]}, "d": "M-20,0H-3M-3,-8V8M3,0H20M6,-8Q2,0 6,8M-10,-10h5M-7.5,-12.5v5", "bb": [-11, -13, 7, 9], "two": true},+ "L": {"pins": {"1": [-20, 0], "2": [20, 0]}, "d": "M-20,0H-14a3.5,3.5 0 0 1 7,0a3.5,3.5 0 0 1 7,0a3.5,3.5 0 0 1 7,0a3.5,3.5 0 0 1 7,0H20", "bb": [-14, -5, 14, 2], "two": true},+ "FB": {"pins": {"1": [-20, 0], "2": [20, 0]}, "d": "M-20,0H-10M10,0H20", "f": "M-10,-4.5h20v9h-20z", "bb": [-10, -5, 10, 5], "two": true},+ "F": {"pins": {"1": [-20, 0], "2": [20, 0]}, "d": "M-20,0H20M-10,-4.5h20v9h-20z", "bb": [-10, -5, 10, 5], "two": true},+ "NT": {"pins": {"1": [-20, 0], "2": [20, 0]}, "d": "M-20,0H-5M5,0H20", "f": "M-5,-2.5h10v5h-10z", "bb": [-6, -4, 6, 4], "two": true},+ "SW": {"pins": {"1": [-20, 0], "2": [20, 0]}, "d": "M-20,0H-10M10,0H20M-12,-8H12M0,-8V-15M-6,-15H6", "dots": [[-8, 0], [8, 0]], "bb": [-12, -15, 12, 3], "two": true},+ "XTAL": {"pins": {"1": [-20, 0], "2": [20, 0]}, "d": "M-20,0H-8M-8,-7V7M8,-7V7M8,0H20M-4,-9h8v18h-8z", "bb": [-9, -10, 9, 10], "two": true},+ "D": {"pins": {"k": [-20, 0], "a": [20, 0]}, "d": "M-20,0H-6M6,0H20M-6,-6V6", "f": "M6,-6L6,6L-6,0Z", "bb": [-7, -7, 7, 7], "two": true},+ "DS": {"pins": {"k": [-20, 0], "a": [20, 0]}, "d": "M-20,0H-6M6,0H20M-3,-4V-6H-6V6H-9V4", "f": "M6,-6L6,6L-6,0Z", "bb": [-9, -7, 7, 7], "two": true},+ "DZ": {"pins": {"k": [-20, 0], "a": [20, 0]}, "d": "M-20,0H-6M6,0H20M-9,-8L-6,-6V6L-3,8", "f": "M6,-6L6,6L-6,0Z", "bb": [-9, -8, 7, 8], "two": true},+ "TVS": {"pins": {"k": [-20, 0], "a": [20, 0]}, "d": "M-20,0H-6M6,0H20M-6,-6V6M-6,-6L-10,-9M-6,6L-2,9", "f": "M6,-6L6,6L-6,0Z", "bb": [-10, -9, 7, 9], "two": true},+ "LED": {"pins": {"k": [-20, 0], "a": [20, 0]}, "d": "M-20,0H-6M6,0H20M-6,-6V6M-1,-8L3,-13M4,-8L8,-13", "f": "M6,-6L6,6L-6,0ZM4.5,-15l-0.5,4l-2.6,-2zM9.5,-15l-0.5,4l-2.6,-2z", "bb": [-7, -15, 10, 7], "two": true},+ "NPN": {"pins": {"b": [-20, 0], "c": [10, -20], "e": [10, 20]}, "d": "M-20,0H-6M-6,-10V10M-6,-4L10,-14V-20M-6,4L10,14V20", "f": "M7.6,12.5L2,12L4.7,7.7Z", "circle": [2, 0, 15], "bb": [-13, -15, 17, 15], "fet": true},+ "PNP": {"pins": {"b": [-20, 0], "c": [10, -20], "e": [10, 20]}, "d": "M-20,0H-6M-6,-10V10M-6,-4L10,-14V-20M-6,4L10,14V20", "f": "M-1.2,7L4.3,7.3L1.7,11.6Z", "circle": [2, 0, 15], "bb": [-13, -15, 17, 15], "fet": true},+ "NMOS": {"pins": {"g": [-20, 0], "d": [10, -20], "s": [10, 20]}, "d": "M-20,0H-7M-7,-9V9M-2,-11V-5M-2,-3V3M-2,5V11M-2,-8H10V-20M-2,8H10V20M-2,0H10V8M10,-8H17V-3M17,3V8H10M14,-3H20", "f": "M-1,0L4,-3L4,3ZM14,3L20,3L17,-3Z", "bb": [-8, -12, 21, 12], "fet": true},+ "PMOS": {"pins": {"g": [-20, 0], "d": [10, 20], "s": [10, -20]}, "d": "M-20,0H-7M-7,-9V9M-2,-11V-5M-2,-3V3M-2,5V11M-2,-8H10V-20M-2,8H10V20M-2,0H10V-8M10,-8H17V-3M17,3V8H10M14,-3H20", "f": "M9,0L4,-3L4,3ZM14,3L20,3L17,-3Z", "bb": [-8, -12, 21, 12], "fet": true},+ "OPAMP": {"pins": {"-": [-30, -10], "+": [-30, 10], "o": [30, 0]}, "d": "M-20,-22L-20,22L22,0ZM-30,-10H-20M-30,10H-20M22,0H30M-17,-10H-11M-17,10H-11M-14,7V13", "bb": [-20, -22, 22, 22]},+ "TP": {"pins": {"p": [0, 0]}, "d": "M0,0V-6", "circle": [0, -10, 4], "bb": [-5, -15, 5, 0], "tp": true},+ "MC": {"pins": {"p": [0, 0]}, "d": "M0,0V-6", "f": "M-4,-14h8v8h-8z", "bb": [-5, -15, 5, 0], "tp": true, "mc": true},+ "MCL": {"pins": {"p": [0, 0]}, "d": "M0,0V-6", "f": "M-6,-18h12v12h-12z", "bb": [-7, -19, 7, 0], "tp": true, "mc": true},+ "MP": {"pins": {"p": [0, 0]}, "d": "M0,0V-5M-3,-12h6", "circle": [0, -12, 7], "bb": [-8, -20, 8, 0], "tp": true, "mc": true}+}
tools/project-page-check.py+6−2@@ -35,9 +35,13 @@ def check(root, live=None): sections=page.get('sections',[]) if 'readme' not in sections or 'viewers' not in sections or sections.index('readme')>sections.index('viewers'):fail('Place README before viewers so datasheet appears below it') readme=(root/'README.md').read_text()- if (root/'readme.html').exists() or (root/'readme.public.html').exists():fail('HTML shadows README.md: review rendered source explicitly before using this Markdown preflight')+ # issue #164: a built page (readme.html, readme_order ["html"]) has its own check+ pkg=json.loads((root/'package.json').read_text()) if (root/'package.json').is_file() else {}+ html_page=(root/'readme.html').exists() and (page.get('readme_order') or pkg.get('readme_order'))==['html']+ if html_page:suggestions.append('readme.html is the page (readme_order ["html"]): `adom-aiflow project-page check --molecule-bundle '+str(root)+'` checks its sections, figures, circuit explorer and components')+ elif (root/'readme.html').exists() or (root/'readme.public.html').exists():fail('HTML shadows README.md: review rendered source explicitly before using this Markdown preflight') shots=re.findall(r'!\[[^\]]+\]\(([^ )]+)\)',readme)- if not 5<=len(set(shots))<=8:fail('README needs 5–8 distinct captioned project screenshots')+ if not html_page and not 5<=len(set(shots))<=8:fail('README needs 5–8 distinct captioned project screenshots') for s in shots: try:local(s) except Exception as e:fail(str(e))
tools/requirements-page.txtadded+3@@ -0,0 +1,3 @@+Pillow==10.2.0+matplotlib==3.11.2+cairosvg==2.9.1
tools/test_page_build.pyadded+297@@ -0,0 +1,297 @@+"""Tests for tools/page-build.py (issues #131, #164, #172, #197, #198, #200): the explorer's netlist check, the+auto-drawn fallback, the flowchart's directions, the LED rule, the components table, a whole build into a folder+and its check. No KiCad, no wiki (offline), no network: python3 tools/test_page_build.py"""+import importlib.util, json, os, shutil, tempfile, unittest, warnings+from pathlib import Path++_spec = importlib.util.spec_from_file_location('page_build', Path(__file__).with_name('page-build.py'))+pb = importlib.util.module_from_spec(_spec); _spec.loader.exec_module(pb)++# a 3.3 V LDO feeding an LED: two blocks, a supply net between them+NETLIST = {+ "components": [+ {"ref": "U1", "block": "power", "value": "TLV70433", "mpn": "TLV70433DBVR", "mfr": "TI", "page": "adom/tlv70433dbvr"},+ {"ref": "C1", "block": "power", "value": "1uF 25V", "mpn": "CL05A105KA5NQNC", "mfr": "Samsung"},+ {"ref": "C2", "block": "power", "value": "1uF 25V", "mpn": "CL05A105KA5NQNC", "mfr": "Samsung"},+ {"ref": "R1", "block": "led", "value": "1k", "mpn": "RC0402FR-071KL", "mfr": "Yageo"},+ {"ref": "D1", "block": "led", "value": "green", "mpn": "LTST-C191KGKT", "mfr": "Lite-On", "note": "power LED"},+ {"ref": "MP1", "block": "contacts", "value": "MachinePinMediumShort", "mpn": None},+ {"ref": "MC1", "block": "contacts", "value": "MachineContactMedium", "mpn": None},+ ],+ "nets": {"VIN": ["U1.2", "C1.1", "MC1.1"], "+3V3": ["U1.3", "C2.1", "R1.1"], "LED_A": ["R1.2", "D1.2"],+ "GND": ["U1.1", "C1.2", "C2.2", "D1.1", "MP1.1"]},+}+SCH = {"U1": {"lib": "x:TLV70433", "pins": [{"num": "1", "name": "GND", "type": "power_in", "x": 0, "y": -5}, {"num": "2", "name": "IN", "type": "power_in", "x": -7, "y": 2},+ {"num": "3", "name": "OUT", "type": "power_out", "x": 7, "y": 2}]},+ "D1": {"lib": "x:LED", "pins": [{"num": "1", "name": "K", "type": "passive", "x": -3, "y": 0}, {"num": "2", "name": "A", "type": "passive", "x": 3, "y": 0}]}}++# the LED block drawn by hand: +3V3 rail, R1 down to D1 (anode up), ground+LED_DRAWING = {"block": "led", "id": "led", "title": "Power LED", "w": 300, "h": 200,+ "parts": [["R1", 100, 80, "r90"], ["D1", 100, 140, "r270"]],+ "wires": [["R1.2", "D1.a"]], "rails": [["R1.1", "+3V3", "up"]], "gnd": [["D1.k", "down"]]}+++def design(tmp):+ p = os.path.join(tmp, "netlist.json")+ json.dump(NETLIST, open(p, "w"))+ return pb.load_design(p, None, SCH, {})+++class Explorer(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.mkdtemp(prefix="pb-test-")+ self.d = design(self.tmp)+ self.SYM = pb.symbols()++ def tearDown(self):+ shutil.rmtree(self.tmp, ignore_errors=True)++ def test_fingerprint_ignores_fab_text_model_paths_and_whitespace(self):+ # silkscreen fab-tidy after a Fields solve keeps the solve's figures valid+ a = '(kicad_pcb (footprint "R" (property "Reference" "R1" (at 0 0) (layer "F.Fab")) (property "Value" "10k" (at 1 0) (layer "F.Fab"))\n\t(fp_line (start 0 0) (end 1 1) (layer "F.SilkS")) (model "/x/r.step")))'+ b = '(kicad_pcb (footprint "R" (property "Reference" "R1" (at 0.5 0.2 90) (layer "F.Fab") (effects (font (size 0.3 0.3)))) (property "Value" "10k" (at 1 0) (layer "F.Fab") (hide yes))\n\t\t(fp_line (start 0 0) (end 1 1) (layer "F.SilkS")) (model "${KIPRJMOD}/3d/r.step")))'+ c = b.replace('(end 1 1) (layer "F.SilkS")', '(end 1 2) (layer "F.SilkS")')+ import tempfile, os+ d = tempfile.mkdtemp(); fs = []+ for i, s in enumerate((a, b, c)):+ f = os.path.join(d, f"{i}.kicad_pcb"); open(f, "w").write(s); fs.append(f)+ self.assertEqual(pb.board_fingerprint(fs[0]), pb.board_fingerprint(fs[1]))+ self.assertNotEqual(pb.board_fingerprint(fs[1]), pb.board_fingerprint(fs[2]))++ def test_symbols_from_reference_and_pin_names(self):+ self.assertEqual(pb.infer_symbol(self.d["parts"]["R1"])[0], "R")+ name, mp = pb.infer_symbol(self.d["parts"]["D1"])+ self.assertEqual((name, mp), ("LED", {"k": ["1"], "a": ["2"]}))+ self.assertEqual(pb.infer_symbol(self.d["parts"]["U1"])[0], "BOX")+ q = {"ref": "Q1", "value": "", "desc": "N-MOSFET", "pins": {"1": "S", "4": "G", "5": "D"},+ "schPins": [{"num": n, "name": nm, "type": "passive", "x": 0, "y": 0} for n, nm in (("1", "S"), ("2", "S"), ("4", "G"), ("5", "D"))]}+ name, mp = pb.infer_symbol(q)+ self.assertEqual(name, "NMOS")+ self.assertEqual(mp, {"g": ["4"], "d": ["5"], "s": ["1", "2"]})+ box = pb.auto_box(self.d["parts"]["U1"])+ self.assertEqual({p[0]: p[1] for p in box["pins"]}, {"IN": "L", "OUT": "R", "GND": "B"})++ def test_a_correct_drawing_has_no_differences(self):+ A = pb.analyze(dict(LED_DRAWING), self.d, {}, self.SYM)+ self.assertEqual(A["errors"], [])++ def test_a_wrong_pin_is_a_short(self):+ dr = json.loads(json.dumps(LED_DRAWING))+ dr["wires"] = [["R1.2", "D1.k"]] # anode and cathode swapped+ dr["gnd"] = [["D1.a", "down"]]+ errs = pb.analyze(dr, self.d, {}, self.SYM)["errors"]+ self.assertTrue(any("short" in e and "LED_A" in e and "GND" in e for e in errs), errs)++ def test_an_unwired_pin_and_a_dangling_wire(self):+ dr = json.loads(json.dumps(LED_DRAWING))+ dr["wires"] = [["R1.2", [140, 110]]]+ errs = pb.analyze(dr, self.d, {}, self.SYM)["errors"]+ self.assertTrue(any("unconnected pin D1.a" in e for e in errs), errs)+ self.assertTrue(any("dangling" in e for e in errs), errs)++ def test_one_net_in_two_unlabelled_pieces(self):+ dr = {"block": "power", "id": "p", "w": 400, "h": 200, "parts": [["C1", 100, 100, "r90"], ["C2", 200, 100, "r90"]],+ "wires": [["C1.2", [100, 150]], ["C2.2", [200, 150]]], "flags": [["C1.1", "VIN", "up"], ["C2.1", "+3V3", "up"]],+ "gnd": [[[200, 150], "down"]]}+ errs = pb.analyze(dr, self.d, {}, self.SYM)["errors"]+ self.assertTrue(any("net GND is drawn in 2 pieces" in e for e in errs), errs)++ def test_auto_drawing_is_correct_by_construction(self):+ for b in ("power", "led"):+ refs = [r for r, p in self.d["parts"].items() if p["block"] == b]+ dr = pb.auto_drawing(b, refs, self.d, {}, self.SYM, {}, b)+ self.assertEqual(pb.analyze(dr, self.d, {}, self.SYM)["errors"], [], b)++ def test_coverage_and_the_flow(self):+ ex = os.path.join(self.tmp, "explorer")+ os.makedirs(ex)+ json.dump(LED_DRAWING, open(os.path.join(ex, "led.json"), "w"))+ data, proof, _ = pb.explorer_build(self.d, ex, {}, scaffold=True)+ self.assertEqual(proof["diffs"], 0, proof["differences"])+ self.assertEqual(proof["coverage"]["percent"], 100.0)+ self.assertEqual(proof["handDrawn"], 1)+ self.assertIn("MP1", proof["coverage"]["parts"]["exempt"]) # a ground-only corner pin+ self.assertTrue(os.path.isfile(os.path.join(ex, "blocks.json")) and os.path.isfile(os.path.join(ex, "auto", "power.json")))+ edges = {(e["from"], e["to"]): e for e in data["flow"]["edges"]}+ self.assertIn(("power", "led"), edges) # the LDO's power_out drives +3V3+ self.assertTrue(edges[("power", "led")]["supply"])+ self.assertIn(("contacts", "power"), edges) # a contact drives VIN, which U1 reads+ # a hand drawing that leaves a part out: coverage below 100 % names it+ dr = json.loads(json.dumps(LED_DRAWING))+ dr["parts"] = dr["parts"][:1]+ dr["wires"], dr["gnd"] = [], []+ dr["flags"] = [["R1.2", "LED_A", "down"]]+ json.dump(dr, open(os.path.join(ex, "led.json"), "w"))+ _, proof, _ = pb.explorer_build(self.d, ex, {}, scaffold=False)+ self.assertEqual(proof["coverage"]["parts"]["missing"], ["D1"])+++BOM = """refs,qty,value,mpn,manufacturer,wiki,note,stock_checked_2026-11-05+MP1 MC1,2,machine,no part,Adom,adom/machinepin,+U1,1,TLV70433,TLV70433DBVR,TI,adom/tlv70433dbvr,3.3 V LDO; thin stock,19+C1 C2,2,1uF 25V,CL05A105KA5NQNC,Samsung,,,224917+R1,1,1k,RC0402FR-071KL,Yageo,,,7854699+D1,1,green,LTST-C191KGKT,Lite-On,,,2250462+"""+++class Build(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.mkdtemp(prefix="pb-build-")+ t = Path(self.tmp)+ (t / "run").mkdir()+ (t / "bundle").mkdir()+ json.dump(NETLIST, open(t / "netlist.json", "w"))+ (t / "bom.csv").write_text(BOM)+ json.dump({"slug": "x", "title": "Test molecule", "kind": "molecule", "description": "A test molecule with an LDO and an LED."}, open(t / "bundle" / "package.json", "w"))+ run = {"spec": None, "clock": {"finishTime": "2026-11-06T00:00:00Z"}, "summary": {"open": ["gate: 1 new DRC error"]}, "outcomes": {}}+ json.dump(run, open(t / "run" / "run.json", "w"))+ self.cfg = {"mode": "build", "run": str(t / "run"), "bundle": str(t / "bundle"), "page": "adom/x", "title": "Test molecule", "brief": "LDO and LED.",+ "molecule": True, "netlist": str(t / "netlist.json"), "explorer": str(t / "explorer"), "bom": str(t / "bom.csv"), "offline": True, "version": "test"}+ self.t = t++ def tearDown(self):+ shutil.rmtree(self.tmp, ignore_errors=True)++ def test_build_writes_the_page_and_check_names_what_is_missing(self):+ out = pb.build(self.cfg)+ html = (self.t / "bundle" / "readme.html").read_text()+ for s in ("board", "contacts", "circuit-explorer", "simulation", "components", "manufacturing", "open-items"):+ self.assertIn(f'data-aiflow-section="{s}"', html)+ self.assertIn("<aiflow-explorer>", html)+ self.assertIn("customElements.define('aiflow-explorer'", html)+ self.assertIn("readme-height", html)+ self.assertNotIn("—", html)+ self.assertEqual(json.load(open(self.t / "bundle" / "package.json"))["readme_order"], ["html"])+ self.assertTrue((self.t / "bundle" / "README.md").is_file())+ bom = json.load(open(self.t / "bundle" / "docs" / "bom.json"))+ lines = [l for l in bom["lines"] if not l["feature"]]+ self.assertEqual(len(lines), 4)+ self.assertTrue(all(l["unit"] is None for l in lines)) # no price column: none invented+ self.assertIn("No prices are recorded", html)+ self.assertIn("https://www.mouser.com/c/?q=TLV70433DBVR", html)+ self.assertIn("finish ran with 1 open item; not cleared for fabrication", html)+ self.assertEqual(out["explorer"]["diffs"], 0)+ self.assertEqual(out["explorer"]["coverage"], 100.0)+ # no board, no Fields solve: the check says which sections have nothing to show+ chk = out["check"]+ self.assertFalse(chk["passed"])+ self.assertTrue(any("section board" in e for e in chk["errors"]), chk)+ self.assertTrue(any("section simulation" in e for e in chk["errors"]), chk)+ # issue #197: no hand drawing yet, so every block is auto-drawn: a finding, not a quiet warning+ auto = [e for e in chk["errors"] if e.startswith("circuit explorer:") and "auto-drawn" in e]+ self.assertEqual(len(auto), 1, chk)+ self.assertIn("led", auto[0])+ self.assertFalse(any("netlist difference" in e or "coverage" in e for e in chk["errors"]), chk)++ def test_a_hand_drawn_block_leaves_the_auto_drawn_finding(self):+ # issue #197: the finding names only the blocks still auto-drawn+ ex = self.t / "explorer"; ex.mkdir()+ json.dump(LED_DRAWING, open(ex / "led.json", "w"))+ chk = pb.build(self.cfg)["check"]+ auto = [e for e in chk["errors"] if e.startswith("circuit explorer:") and "auto-drawn" in e]+ self.assertEqual(len(auto), 1, chk)+ self.assertNotIn("led", auto[0].split(": ")[-1].split(", "))+ self.assertIn("power", auto[0])++ def test_too_many_blocks_is_a_warning_and_an_open_item(self):+ # issue #198: past FLOW_MAX_BLOCKS the flowchart stops being readable+ n = pb.FLOW_MAX_BLOCKS + 2+ comps = [{"ref": f"R{i}", "block": f"b{i}", "value": "1k", "mpn": "RC0402FR-071KL", "mfr": "Yageo"} for i in range(1, n + 1)]+ nets = {f"N{i}": [f"R{i}.2", f"R{i + 1}.1"] for i in range(1, n)}+ nets["GND"] = ["R1.1", f"R{n}.2"]+ json.dump({"components": comps, "nets": nets}, open(self.t / "netlist.json", "w"))+ (self.t / "bom.csv").write_text("refs,qty,value,mpn,manufacturer\n" + " ".join(c["ref"] for c in comps) + f",{n},1k,RC0402FR-071KL,Yageo\n")+ out = pb.build(self.cfg)+ self.assertTrue(any("unreadable flowchart" in w for w in out["check"]["warnings"]), out["check"])+ html = (self.t / "bundle" / "readme.html").read_text()+ self.assertIn("unreadable flowchart", html) # the page's own open items say it too++ def test_board_features_in_the_bom_cover_their_test_pads(self):+ # issue #200: a bare test pad the BOM lists as a board feature (no part) is not a missing BOM row+ n = json.loads(json.dumps(NETLIST))+ n["components"].append({"ref": "TP1", "block": "power", "value": "TP", "mpn": "Adom_TestPoint_D0.5mm"})+ n["nets"]["+3V3"].append("TP1.1")+ json.dump(n, open(self.t / "netlist.json", "w"))+ chk = pb.build(self.cfg)["check"]+ self.assertTrue(any("no BOM row for TP1" in e for e in chk["errors"]), chk)+ (self.t / "bom.csv").write_text(BOM + "TP1,1,test pad,no part,Adom,,,\n")+ chk = pb.build(self.cfg)["check"]+ self.assertFalse(any("no BOM row" in e for e in chk["errors"]), chk)++ def test_an_existing_readme_is_left_as_it_is(self):+ # the Markdown design review is `project-page --results --out` (design-review/); the build never rewrites README.md+ (self.t / "bundle" / "README.md").write_text("# Mine\n\nWritten by molecule-publish.\n")+ out = pb.build(self.cfg)+ self.assertEqual((self.t / "bundle" / "README.md").read_text(), "# Mine\n\nWritten by molecule-publish.\n")+ self.assertEqual(out["readmeMd"], "README.md left as it is")+ # a design review sub-page in the folder is linked from the Simulation section+ (self.t / "bundle" / "design-review").mkdir()+ (self.t / "bundle" / "design-review" / "README.md").write_text("# Design review\n")+ pb.build(self.cfg)+ self.assertIn("design-review/README.md", (self.t / "bundle" / "readme.html").read_text())++ def test_a_price_column_gives_a_board_total(self):+ (self.t / "bom.csv").write_text(BOM.replace("stock_checked_2026-11-05", "stock_checked_2026-11-05,unit_price").replace("\n", ",0.50\n").replace("refs,qty,value,mpn,manufacturer,wiki,note,stock_checked_2026-11-05,unit_price,0.50", "refs,qty,value,mpn,manufacturer,wiki,note,stock_checked_2026-11-05,unit_price"))+ pb.build(self.cfg)+ html = (self.t / "bundle" / "readme.html").read_text()+ self.assertIn("Board total, 5 parts", html)+ self.assertIn("$2.50", html)++ def test_explorer_tampering_and_a_changed_netlist_fail_the_check(self):+ pb.build(self.cfg)+ ex = self.t / "bundle" / "docs" / "explorer"+ f = next(p for p in ex.glob("*.json") if p.name not in ("design.json", "blocks.json") and json.load(open(p)).get("block") == "led")+ d = json.load(open(f))+ d["flags"] = [[a[0], "GND" if a[1] == "LED_A" else a[1], a[2]] for a in d.get("flags") or []]+ json.dump(d, open(f, "w"))+ chk = pb.check_bundle(str(self.t / "bundle"), self.cfg)+ self.assertTrue(any("netlist difference" in e for e in chk["errors"]), chk)+ pb.build(self.cfg)+ n = json.load(open(self.t / "netlist.json"))+ n["nets"]["LED_A"].append("C1.1")+ json.dump(n, open(self.t / "netlist.json", "w"))+ chk = pb.check_bundle(str(self.t / "bundle"), self.cfg)+ self.assertTrue(any("the netlist changed" in e for e in chk["errors"]), chk)++ def test_figures_from_another_board_fail_the_check(self):+ pb.build(self.cfg)+ board = self.t / "bundle" / "x.kicad_pcb"+ board.write_text('(kicad_pcb (version 20240108) (generator "t"))\n')+ figs = json.load(open(self.t / "bundle" / "docs" / "figures.json"))+ figs["figures"] = [{"file": "docs/bom.json", "shows": "a figure", "boardFingerprint": "0" * 64}]+ json.dump(figs, open(self.t / "bundle" / "docs" / "figures.json", "w"))+ chk = pb.check_bundle(str(self.t / "bundle"), self.cfg)+ self.assertTrue(any("shows board 000000000000" in e for e in chk["errors"]), chk)+ # a model path change (molecule-publish's 3d/) keeps the fingerprint+ a = '(kicad_pcb (footprint "R" (model "${KIPRJMOD}/lib/r.step")))'+ b = '(kicad_pcb (footprint "R" (model "${KIPRJMOD}/3d/r.step")))'+ (self.t / "a.kicad_pcb").write_text(a); (self.t / "b.kicad_pcb").write_text(b)+ self.assertEqual(pb.board_fingerprint(str(self.t / "a.kicad_pcb")), pb.board_fingerprint(str(self.t / "b.kicad_pcb")))+++class Review(unittest.TestCase):+ def test_an_led_is_named_by_its_footprint_symbol_or_value(self):+ # issue #172: a description ("clamp for the LED bar") or an MPN never makes a diode an LED+ clamp = {"ref": "D7", "value": "PMEG6010CEJ", "desc": "Schottky clamp for the LED bar", "mpn": "PMEG6010CEJ,115", "lib": "led-driver:PMEG6010CEJ",+ "footprint": "led-driver:SOD-323F", "pins": {"1": "K", "2": "A"}}+ self.assertFalse(pb.is_led(clamp))+ self.assertEqual(pb.infer_symbol(clamp)[0], "DS")+ reduced = dict(clamp, desc="reduced leakage, required by the ordered spec")+ self.assertFalse(pb.is_led(reduced))+ self.assertTrue(pb.is_led(dict(clamp, footprint="LED_SMD:LED_0603_1608Metric")))+ self.assertTrue(pb.is_led(dict(clamp, lib="Device:LED")))+ self.assertTrue(pb.is_led(dict(clamp, value="green")))+ self.assertFalse(pb.is_led(dict(clamp, footprint="x:SEALED_SOLDERED")))++ def test_rise_limit_interpolation(self):+ rows = [{"amps": 6, "still": 67, "moving": 51}, {"amps": 10, "still": 91, "moving": 59}, {"amps": 12, "still": 106, "moving": 65}]+ self.assertEqual(pb.at_rise(rows, "still", 60), ("<", 6))+ k, a = pb.at_rise(rows, "moving", 60)+ self.assertEqual(k, "=")+ self.assertAlmostEqual(a, 10 + 2 * (1 / 6), places=3)+++if __name__ == "__main__":+ warnings.simplefilter("ignore", ResourceWarning)+ unittest.main(warnings="ignore")