← Commit history
Cargo.lock+11−11
@@ -4,7 +4,7 @@ version = 4  [[package]] name = "adom-aiflow"-version = "0.2.148"+version = "0.2.149" dependencies = [  "aiflow-analyze",  "aiflow-board",@@ -28,7 +28,7 @@ dependencies = [  [[package]] name = "aiflow-analyze"-version = "0.2.148"+version = "0.2.149" dependencies = [  "aiflow-board",  "aiflow-sys",@@ -39,7 +39,7 @@ dependencies = [  [[package]] name = "aiflow-board"-version = "0.2.148"+version = "0.2.149" dependencies = [  "aiflow-sys",  "roxmltree",@@ -49,7 +49,7 @@ dependencies = [  [[package]] name = "aiflow-bridge"-version = "0.2.148"+version = "0.2.149" dependencies = [  "aiflow-board",  "aiflow-sys",@@ -59,7 +59,7 @@ dependencies = [  [[package]] name = "aiflow-copper"-version = "0.2.148"+version = "0.2.149" dependencies = [  "aiflow-board",  "aiflow-grid",@@ -70,7 +70,7 @@ dependencies = [  [[package]] name = "aiflow-grid"-version = "0.2.148"+version = "0.2.149" dependencies = [  "aiflow-board",  "serde",@@ -79,7 +79,7 @@ dependencies = [  [[package]] name = "aiflow-place"-version = "0.2.148"+version = "0.2.149" dependencies = [  "aiflow-board",  "aiflow-sys",@@ -89,7 +89,7 @@ dependencies = [  [[package]] name = "aiflow-pours"-version = "0.2.148"+version = "0.2.149" dependencies = [  "aiflow-board",  "aiflow-copper",@@ -100,7 +100,7 @@ dependencies = [  [[package]] name = "aiflow-router"-version = "0.2.148"+version = "0.2.149" dependencies = [  "aiflow-board",  "aiflow-grid",@@ -111,7 +111,7 @@ dependencies = [  [[package]] name = "aiflow-run"-version = "0.2.148"+version = "0.2.149" dependencies = [  "aiflow-sys",  "serde",@@ -120,7 +120,7 @@ dependencies = [  [[package]] name = "aiflow-sys"-version = "0.2.148"+version = "0.2.149" dependencies = [  "serde_json", ]
Cargo.toml+1−1
@@ -15,7 +15,7 @@ members = [ ]  [workspace.package]-version = "0.2.148"+version = "0.2.149" edition = "2021" license = "MIT" repository = "https://wiki.adom.inc/adom/adom-aiflow"
crates/adom-aiflow/src/main.rs+72−16
@@ -1,6 +1,7 @@ //! adom-aiflow: the board loop as one command, with the clock, the negotiation and the finish line. //! Every reply starts with OK: or ERROR: and carries Hint: lines that depend on this board and run. mod bare_lands;+mod part_follow; mod connector_mating; mod continuation; mod model_fit;@@ -242,10 +243,16 @@ enum Cmd {     /// `parts [--bom <csv>] [--show] [--dwell 4]`: the from-scratch board's parts on the wiki. Every BOM row with an MPN (default: the BOM the sourcing check passed) is matched to its Adom wiki component page (a `wiki` column, owner/slug, names it directly; else the MPN's slug forms, then a page whose component.mpn is the MPN); --show walks a Hydrogen tab through each page so the viewer sees the parts being chosen. A part with no page fails: make it (wiki-component skill) and run again, or give it from the board's own project library (--project-lib).     Parts { #[arg(long)] bom: Option<String>, #[arg(long)] show: bool, #[arg(long, default_value_t = 4)] dwell: u64, /// a project library folder for parts with no public component page: KiCad .kicad_sym, .pretty footprints, STEP models and a provenance.json naming each MPN's source (default: the spec's or requirements' "projectLib"). Each listed MPN needs a symbol, a footprint, a model and provenance; project-page packages them, finish reports them.     #[arg(long)] project_lib: Option<String> },-    /// `part-request <MPN> [--as <orderable MPN>] [--datasheet <link>] [--manufacturer <maker>]`: ask Adom's part factory for the page of a BOM part with none (issue #193), and keep the attempt in the run. The same inputs are never sent twice: one retry changes at least one (the orderable number from `adom-wiki part candidates`, the maker's product page, package drawing or CAD link, the manufacturer). `--refresh` reads the factory's answers for every pending attempt. After a refused retry, assess the part (`supply-risk`).+    /// `part-request <MPN> [--as <orderable MPN>] [--datasheet <link>] [--manufacturer <maker>]`: ask Adom's part factory for the page of a BOM part with none (issue #193), and keep the attempt in the run. The same inputs are never sent twice: one retry changes at least one (the orderable number from `adom-wiki part candidates`, the maker's product page, package drawing or CAD link, the manufacturer). `--refresh` reads the factory's answers for every pending attempt. After a refused retry, assess the part (`supply-risk`). The answers come back to this thread, not by email to the human (the wiki, 2026-12-04): `--missing` sends every part `parts` found with no page as one batch named for the board, and `--follow`, under the Monitor tool, prints one line per change while you keep working; a request past its deadline (20 minutes unless `--deadline`) is planned for as a refusal.     PartRequest { mpn: Option<String>, /// the part number to send, when the BOM's is not the orderable one (a packaging or reel suffix)     #[arg(long = "as")] as_mpn: Option<String>, #[arg(long)] datasheet: Option<String>, #[arg(long)] manufacturer: Option<String>, #[arg(long)] refresh: bool, /// later, the factory's batch wave (default: now)-    #[arg(long)] later: bool },+    #[arg(long)] later: bool, /// send every part `parts` found with no page and no request yet, as one batch for this board+    #[arg(long)] missing: bool, /// the batch's name: the board (default: the run's board file name)+    #[arg(long = "ref")] batch_ref: Option<String>, /// wait on the run's open requests and print one line per change (run it under the Monitor tool, never in the foreground); ends when every one is built, refused or past its deadline+    #[arg(long)] follow: bool, /// with --follow: stop following after this many minutes+    #[arg(long, default_value_t = 25)] minutes: u64, /// how long the run waits for the factory before planning without it, in minutes (1 to 1440; the wiki's default is 20)+    #[arg(long)] deadline: Option<u32>, /// email the human how it ends as well (only when they asked for email)+    #[arg(long)] email: 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. 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).@@ -4280,13 +4287,14 @@ fn main() {     // All engines share the same default. Server/write children must never open tabs recursively.     // `status` reads a run, often another thread's (an audit, a director): it opens no tab, records no     // turn and leaves the run's clips alone, so the run's own files are byte for byte what they were.-    if !matches!(cli.cmd, Cmd::Timeline { .. } | Cmd::Demo { .. } | Cmd::Status) && !matches!(&cli.cmd, Cmd::Dfa { board: Some(_), .. }) {+    let background = matches!(&cli.cmd, Cmd::PartRequest { follow: true, .. });+    if !background && !matches!(cli.cmd, Cmd::Timeline { .. } | Cmd::Demo { .. } | Cmd::Status) && !matches!(&cli.cmd, Cmd::Dfa { board: Some(_), .. }) {         let ai_thread = cli.ai_thread.clone().or_else(|| Run::open(&dir).and_then(|r|r.data["aiThread"].as_str().map(str::to_owned))).unwrap_or_else(|| "adom-aiflow".into());         let _ = DASHBOARD.set((dir.clone(), ai_thread.clone()));         ensure_dashboard(&dir, &ai_thread, matches!(cli.cmd, Cmd::Prompt { .. }));     }     // every command is a turn in the run's ledger; the gap before it is the AI's thinking time-    if !matches!(cli.cmd, Cmd::Start { .. } | Cmd::Intake { .. } | Cmd::Demo { .. } | Cmd::Status) && !matches!(&cli.cmd, Cmd::Dfa { board: Some(_), .. }) && !matches!(&cli.cmd, Cmd::Timeline { action, .. } if action == "serve" || action == "list" || action == "close") {+    if !background && !matches!(cli.cmd, Cmd::Start { .. } | Cmd::Intake { .. } | Cmd::Demo { .. } | Cmd::Status) && !matches!(&cli.cmd, Cmd::Dfa { board: Some(_), .. }) && !matches!(&cli.cmd, Cmd::Timeline { action, .. } if action == "serve" || action == "list" || action == "close") {         if let Some(mut r) = Run::open(&dir) {             let idx = r.turn_begin(&command_line());             // the thread that last drove the run: the dashboard header and the tab registry name it@@ -5105,7 +5113,7 @@ fn main() {                 // AI Flow never refuses (0.2.48): the parts record is saved; the missing parts are findings with the ways on                 let lead: Vec<String> = decisions.iter().map(|d| format!("  {}\n    next: {}", d["decision"].as_str().unwrap_or(""), d["next"].as_str().unwrap_or(""))).collect();                 findings(&format!("{} of {} parts have no Adom wiki component page{} yet; the decision each needs:\n{}\n{}{}", missing.len(), rows.len(), if plib.is_some() { " and no complete project-library entry" } else { "" }, lead.join("\n"), list.join("\n"), if gaps.is_empty() { String::new() } else { format!("\n{}", gaps.join("\n")) }),-                    &["For each part with no page: `part-request <MPN>` asks the factory; a refusal gets one retry with a changed input; a part still without a page gets a supply assessment and up to three alternatives (`supply-risk`), and the human chooses (aiflow-sourcing skill, \"When a part cannot get a page\"). The project page and the KiCad library are built from these pages.".into(), "A part whose page cannot be public yet: `parts --project-lib <dir>` with its symbol, footprint, STEP model and a provenance.json entry (aiflow-sourcing skill).".into()]);+                    &["The parts with no page: `part-request --missing` asks the factory for all of them as one batch for this board; keep working while it builds and follow it with `part-request --follow` under the Monitor tool (the answers come back to this thread, not by email); a refusal or a passed deadline gets one retry with a changed input; a part still without a page gets a supply assessment and up to three alternatives (`supply-risk`), and the human chooses (aiflow-sourcing skill, \"When a part cannot get a page\"). The project page and the KiCad library are built from these pages.".into(), "A part whose page cannot be public yet: `parts --project-lib <dir>` with its symbol, footprint, STEP model and a provenance.json entry (aiflow-sourcing skill).".into()]);             }             // issue #157: a page matched by MPN is not yet a page checked against the datasheet             note("a page matched by MPN is not proof its footprint and model match the datasheet: write what each datasheet says in design/part-checks.json and run `adom-aiflow part-check` (aiflow-sourcing, \"Check each part against its datasheet\")", &[]);@@ -5201,9 +5209,47 @@ fn main() {             if !lines.is_empty() { findings(&format!("{} part(s) checked against their datasheets; what disagrees:\n  {}{tail}", results.len(), lines.join("\n  ")), &hints); }             ok(&format!("{} part(s) checked against their datasheets: footprints, models and makers agree{tail}", results.len()), &[]);         }-        Cmd::PartRequest { mpn, as_mpn, datasheet, manufacturer, refresh, later } => {+        Cmd::PartRequest { mpn, as_mpn, datasheet, manufacturer, refresh, later, missing, batch_ref, follow, minutes, deadline, email } => {+            if *follow {+                // read-only on run.json (the run's other commands write it meanwhile); changes go to stdout and the ledger+                let r = Run::open(&run_dir(&cli)).unwrap_or_else(|| err(&format!("no run at {}", run_dir(&cli).display()), &[]));+                let open = part_follow::targets(&r.data);+                if open.is_empty() {+                    println!("OK: no part request is waiting on the factory (every one is built, refused or past its deadline): `part-request --refresh`, then `parts`");+                    return;+                }+                println!("following {} part request(s): {}", open.len(), open.iter().map(|x| x.mpn.as_str()).collect::<Vec<_>>().join(", "));+                let (seen, still) = part_follow::follow(&r.data, *minutes, |m| match m {+                    Ok(c) => { println!("{}", c.line()); r.log("part-request-update", json!({"mpn": c.mpn, "attempt": c.attempt, "from": c.from, "to": c.to, "deadlinePassed": c.late, "page": c.page, "reason": c.reason})); }+                    Err(e) => println!("{e}"),+                });+                println!("OK: {} change(s); {}. Next: `adom-aiflow part-request --refresh` records the answers, then `parts`", seen.len(),+                    if still == 0 { "every followed request is built, refused or past its deadline".to_string() } else { format!("{still} still open after {minutes} minutes (follow again, or `--refresh` later)") });+                return;+            }             let t = thread(&cli);             let mut r = load_run(&cli);+            let follow_hint = "Keep working on the board; follow the answers in the background: `adom-aiflow part-request --follow` under the Monitor tool (one line per change, ends when every request is final or past its deadline), then `part-request --refresh`. They come back to this thread, not by email to the human.".to_string();+            if *missing {+                let sent = part_follow::unrequested(&r.data);+                if sent.is_empty() {+                    let m = r.data["outcomes"]["parts"]["missing"].as_array().map(|a| a.len()).unwrap_or(0);+                    ok(&format!("nothing to send: {}", if r.data["outcomes"]["parts"].is_null() { "run `parts` first; it lists the parts with no page".to_string() } else if m == 0 { "every part has a page".to_string() } else { format!("each of the {m} part(s) with no page has a request already (a retry goes one by one: `part-request <MPN> --as ...`)") }), &[]);+                    return;+                }+                let bref = batch_ref.clone().unwrap_or_else(|| r.data["board"].as_str().and_then(|b| Path::new(b).file_stem().map(|s| s.to_string_lossy().to_string())).unwrap_or_else(|| r.data["id"].as_str().unwrap_or("board").to_string()));+                let mut body = json!({"mpns": sent, "urgency": if *later { "later" } else { "now" }, "ref": bref, "source": "bom"});+                part_follow::thread_opts(&mut body, *deadline, *email);+                let ans = part_follow::api("/api/part-request/batch", "POST", Some(&body)).unwrap_or_else(|e| err(&format!("the batch was not taken: {e}"), &[]));+                let (id, lines) = part_follow::record_batch(&mut r.data, &sent, &ans, &bref, &t, &now());+                part_follow::refresh_by_status_api(&mut r.data);+                r.log("part-request-batch", json!({"batch": id, "ref": bref, "mpns": sent.iter().map(|s| s["mpn"].clone()).collect::<Vec<_>>(), "notify": ans["notify"], "deadlineAt": ans["deadline_at"]}));+                r.save().unwrap();+                let how = match ans["notify"].as_str() { Some("email") => "the human is emailed how it ends".to_string(), _ => format!("answers come back to this thread{}", ans["deadline_at"].as_str().map(|d| format!(", deadline {d}")).unwrap_or_default()) };+                ok(&format!("batch {id} for {bref}: {} part(s) sent ({how})+{}", sent.len(), lines.join("\n")), &[follow_hint]);+                return;+            }             if *refresh {                 let o = aiflow_sys::process::Command::new("adom-wiki").args(["part", "status", "--json"]).stdin(aiflow_sys::process::Stdio::null()).output()                     .unwrap_or_else(|e| err(&format!("could not run adom-wiki part status: {e}"), &[]));@@ -5211,7 +5257,7 @@ fn main() {                 let Some(list) = v["data"]["requests"].as_array().cloned() else {                     err(&format!("could not read the factory's answers (adom-wiki part status --json): {}", String::from_utf8_lossy(&o.stderr).trim()), &[])                 };-                let n = supply::refresh(&mut r.data, &list);+                let n = supply::refresh(&mut r.data, &list) + part_follow::refresh_by_status_api(&mut r.data);                 r.log("part-request-refresh", json!({"changed": n}));                 r.save().unwrap();                 let lines: Vec<String> = r.data["partRequests"].as_object().into_iter().flatten().map(|(m, a)| {@@ -5229,30 +5275,40 @@ fn main() {                     &[supply::next(&mpn, &supply::attempts(&r.data, &mpn), None, None)]);             }             let prior = supply::attempts(&r.data, &mpn);-            if prior.iter().filter(|a| supply::refused(a)).count() >= 2 {-                note(&format!("{mpn} has had its retry ({} refused attempts): one bounded retry, then the supply assessment, is the way (issue #193)", prior.iter().filter(|a| supply::refused(a)).count()), &[supply::next(&mpn, &prior, None, None)]);+            if prior.iter().filter(|a| supply::failed(a)).count() >= 2 {+                note(&format!("{mpn} has had its retry ({} refused or late attempts): one bounded retry, then the supply assessment, is the way (issue #193)", prior.iter().filter(|a| supply::failed(a)).count()), &[supply::next(&mpn, &prior, None, None)]);             }-            if let Some((i, _)) = prior.iter().enumerate().rev().find(|(_, a)| supply::pending(a)) {-                note(&format!("attempt {} for {mpn} is still in the factory's queue; `part-request --refresh` reads its answer", i + 1), &[]);+            if let Some((i, _)) = prior.iter().enumerate().rev().find(|(_, a)| supply::waiting(a)) {+                note(&format!("attempt {} for {mpn} is still in the factory's queue; `part-request --follow` (under the Monitor tool) or `--refresh` reads its answer", i + 1), &[]);             }             let changed = prior.last().map(|a| supply::changed(&a["inputs"], &inp)).unwrap_or_default();             let mut args: Vec<String> = vec!["part".into(), "request".into(), sent.clone(), "--json".into(), if *later { "--later" } else { "--now" }.into(), "--source".into(), "bom".into()];             if let Some(m) = manufacturer { args.extend(["--manufacturer".into(), m.clone()]); }             if let Some(d) = datasheet { args.extend(["--datasheet".into(), d.clone()]); }-            let o = aiflow_sys::process::Command::new("adom-wiki").args(&args).stdin(aiflow_sys::process::Stdio::null()).output()-                .unwrap_or_else(|e| err(&format!("could not run adom-wiki part request: {e}"), &[]));-            let v: Value = serde_json::from_slice(&o.stdout).unwrap_or(Value::Null);+            // --deadline and --email: the API takes them today (deadline_minutes, notify); the CLI flags come later+            let (v, raw): (Value, String) = if deadline.is_some() || *email {+                let mut body = json!({"mpn": sent, "urgency": if *later { "later" } else { "now" }});+                if let Some(m) = manufacturer { body["manufacturer"] = json!(m); }+                if let Some(d) = datasheet { body["datasheet_url"] = json!(d); }+                part_follow::thread_opts(&mut body, *deadline, *email);+                (part_follow::api("/api/part-request", "POST", Some(&body)).unwrap_or_else(|e| err(&format!("the part request was not taken: {e}"), &[])), String::new())+            } else {+                let o = aiflow_sys::process::Command::new("adom-wiki").args(&args).stdin(aiflow_sys::process::Stdio::null()).output()+                    .unwrap_or_else(|e| err(&format!("could not run adom-wiki part request: {e}"), &[]));+                (serde_json::from_slice(&o.stdout).unwrap_or(Value::Null), format!("{}{}", String::from_utf8_lossy(&o.stdout).trim(), String::from_utf8_lossy(&o.stderr).trim()))+            };             let ans = supply::answer(&v);             if ans.is_null() && v["status"] != "ok" {-                err(&format!("the part request was not taken: {}", v["error"]["message"].as_str().or(v["error"].as_str()).map(str::to_string).unwrap_or_else(|| format!("{}{}", String::from_utf8_lossy(&o.stdout).trim(), String::from_utf8_lossy(&o.stderr).trim()))), &[]);+                err(&format!("the part request was not taken: {}", v["error"]["message"].as_str().or(v["error"].as_str()).map(str::to_string).unwrap_or(raw)), &[]);             }             let mut a = json!({"at": now(), "aiThread": t, "inputs": inp, "changed": changed, "state": "sent"});-            supply::absorb(&mut a, &ans);+            supply::absorb_answer(&mut a, &v);             let n = supply::record(&mut r.data, &mpn, a.clone());             r.log("part-request", json!({"mpn": mpn, "attempt": n, "request": a}));             r.save().unwrap();             let tries = supply::attempts(&r.data, &mpn);             let next = if supply::built(&a) { "`parts` again: the page is used for this BOM line".to_string() } else { supply::next(&mpn, &tries, None, None) };+            let next = if supply::waiting(&a) && a["notify"] != "email" { format!("{next}. The answer comes back to this thread{}, not by email to the human", a["deadlineAt"].as_str().map(|d| format!(" (deadline {d})")).unwrap_or_default()) } else { next };             ok(&format!("attempt {n} for {mpn}{}{}: {}{}", if sent != mpn { format!(" (sent as {sent})") } else { String::new() }, if changed.is_empty() { String::new() } else { format!(", changed: {}", changed.join(", ")) },                 a["state"].as_str().unwrap_or("sent"), a["reason"].as_str().map(|x| format!(" ({x})")).unwrap_or_default()), &[next]);         }
crates/adom-aiflow/src/part_follow.rsadded+303
@@ -0,0 +1,303 @@+//! Part requests answer the thread that asked (the wiki, 2026-12-04): a request made with a token is+//! `notify: "thread"`, with no email to the human, a deadline (20 minutes by default) and a `status_api` that+//! holds a read until the state changes (`?wait=<s>`, at most 55). The run never blocks on the factory:+//!+//! - `part-request --missing` sends every part `parts` found with no page, and no attempt yet, as ONE batch named+//!   for the board (`--ref`), so five boards on five Mesh boxes each follow only their own batch;+//! - `part-request --follow` (under the Monitor tool) waits on the run's open requests and prints one line per+//!   change, ending when every one is built, refused or past its deadline. It only reads run.json (another+//!   command may be writing it) and appends to the ledger; `part-request --refresh` records the answers.+use serde_json::{json, Value};+use std::sync::mpsc;+use std::time::{Duration, Instant};++use crate::supply;++/// At most 8 waits at once per caller on the wiki; more than this many open requests poll instead.+const MAX_WAITERS: usize = 6;+const WAIT_S: u64 = 50;++/// A raw `adom-wiki api` call: the server's body, or why it failed.+pub fn api(path: &str, method: &str, body: Option<&Value>) -> Result<Value, String> {+    let mut c = aiflow_sys::process::Command::new("adom-wiki");+    c.arg("api").arg(path);+    if method != "GET" { c.args(["-X", method]); }+    let b = body.map(|b| b.to_string());+    if let Some(b) = &b { c.args(["--body", b]); }+    let o = c.stdin(aiflow_sys::process::Stdio::null()).output().map_err(|e| format!("could not run adom-wiki api: {e}"))?;+    let v: Value = serde_json::from_slice(&o.stdout).map_err(|_| format!("adom-wiki api {path}: {}{}", String::from_utf8_lossy(&o.stdout).trim(), String::from_utf8_lossy(&o.stderr).trim()))?;+    if let Some(s) = v["http_status"].as_u64() {+        let why = v["response"]["error"].as_str().or(v["response"]["message"].as_str()).unwrap_or("");+        return Err(format!("{path}: HTTP {s}{}", if why.is_empty() { String::new() } else { format!(": {why}") }));+    }+    if v["status"] == "error" { return Err(format!("{path}: {}", v["data"]["response"]["error"].as_str().unwrap_or("error"))); }+    Ok(v)+}++/// The body for `POST /api/part-request` or `/batch`: who hears how it ends and how long the run waits.+pub fn thread_opts(body: &mut Value, deadline: Option<u32>, email: bool) {+    if let Some(m) = deadline { body["deadline_minutes"] = json!(m.clamp(1, 1440)); }+    if email { body["notify"] = json!("email"); }+}++/// One BOM row as the batch takes it: the MPN, and the maker and datasheet link when the BOM has them.+pub fn batch_entry(row: &Value) -> Value {+    let mpn = row["mpn"].as_str().unwrap_or("").trim();+    let pick = |ks: &[&str]| ks.iter().find_map(|k| row[*k].as_str().map(str::trim).filter(|s| !s.is_empty()).map(str::to_string));+    let mut e = json!({"mpn": mpn});+    if let Some(m) = pick(&["manufacturer", "maker", "mfr"]) { e["manufacturer"] = json!(m); }+    if let Some(d) = pick(&["datasheet", "datasheetUrl", "datasheet_url"]).filter(|d| d.starts_with("http")) { e["datasheet_url"] = json!(d); }+    e+}++/// The parts `parts` found with no page that have never been requested: the ones a batch sends. A part with an+/// attempt already gets its retry one by one (`part-request <MPN> --as ...`), never the same inputs again.+pub fn unrequested(data: &Value) -> Vec<Value> {+    let p = &data["outcomes"]["parts"];+    let missing: Vec<String> = p["missing"].as_array().into_iter().flatten().filter_map(|m| m.as_str().map(str::to_string)).collect();+    let rows = p["parts"].as_array().cloned().unwrap_or_default();+    missing.iter().filter(|m| supply::attempts(data, m).is_empty()).map(|m| {+        rows.iter().find(|x| x["mpn"].as_str() == Some(m.as_str())).map(batch_entry).unwrap_or_else(|| json!({"mpn": m}))+    }).collect()+}++/// Record a batch answer: one attempt per part (with its status API), and the batch itself in `partBatches`.+/// Returns (batch id, one line per part).+pub fn record_batch(data: &mut Value, sent: &[Value], ans: &Value, batch_ref: &str, thread: &str, at: &str) -> (String, Vec<String>) {+    let id = ans["batch"]["id"].as_str().map(str::to_string).or_else(|| ans["batch_id"].as_str().map(str::to_string)).or_else(|| ans["batch_id"].as_u64().map(|n| n.to_string())).unwrap_or_default();+    let items = ans["items"].as_array().cloned().unwrap_or_default();+    let mut lines = Vec::new();+    for s in sent {+        let mpn = s["mpn"].as_str().unwrap_or("");+        let it = items.iter().find(|i| supply::item_mpn(i).map(|m| m.eq_ignore_ascii_case(mpn)).unwrap_or(false)).cloned().unwrap_or(Value::Null);+        let mut a = json!({"at": at, "aiThread": thread, "inputs": supply::inputs(mpn, s["manufacturer"].as_str(), s["datasheet_url"].as_str()), "changed": [], "state": "sent", "batchId": id, "batchRef": batch_ref});+        supply::absorb(&mut a, &it);+        for (from, to) in [("notify", "notify"), ("deadline_at", "deadlineAt")] {+            if a[to].is_null() && !ans[from].is_null() { a[to] = ans[from].clone(); }+        }+        if let Some(m) = it["message"].as_str().filter(|m| !m.is_empty()) { if supply::refused(&a) && a["reason"].is_null() { a["reason"] = json!(m); } }+        lines.push(format!("  {mpn:<24} {}{}", a["state"].as_str().unwrap_or("sent"), a["reason"].as_str().map(|r| format!(" ({r})")).unwrap_or_default()));+        supply::record(data, mpn, a);+    }+    if !data["partBatches"].is_array() { data["partBatches"] = json!([]); }+    data["partBatches"].as_array_mut().unwrap().push(json!({"id": id, "ref": batch_ref, "at": at, "aiThread": thread, "mpns": sent.iter().map(|s| s["mpn"].clone()).collect::<Vec<_>>(),+        "notify": ans["notify"], "deadlineAt": ans["deadline_at"], "url": ans["batch"]["url"]}));+    (id, lines)+}++/// Read each open attempt's own status (no wait) into the run: the deadline, and the state when the list+/// `part status` gave has not caught up; and the page of a built one the batch answer named without it.+/// Returns how many changed.+pub fn refresh_by_status_api(data: &mut Value) -> usize {+    let mut n = 0;+    let Some(all) = data["partRequests"].as_object_mut() else { return 0 };+    for list in all.values_mut() {+        for a in list.as_array_mut().into_iter().flatten().filter(|a| supply::pending(a) || (supply::built(a) && a["pageUrl"].is_null())) {+            let Some(path) = a["statusApi"].as_str().map(str::to_string) else { continue };+            let Ok(v) = api(&path, "GET", None) else { continue };+            let before = (a["state"].clone(), a["deadlinePassed"] == true);+            supply::absorb_answer(a, &v);+            if (a["state"].clone(), a["deadlinePassed"] == true) != before { n += 1; }+        }+    }+    n+}++/// An open request to follow.+#[derive(Clone, Debug)]+pub struct Target { pub mpn: String, pub attempt: usize, pub status_api: Option<String>, pub state: String }++/// The run's requests still inside their deadline.+pub fn targets(data: &Value) -> Vec<Target> {+    let mut out = Vec::new();+    for (m, list) in data["partRequests"].as_object().into_iter().flatten() {+        for (i, a) in list.as_array().into_iter().flatten().enumerate().filter(|(_, a)| supply::waiting(a)) {+            out.push(Target { mpn: m.clone(), attempt: i + 1, status_api: a["statusApi"].as_str().map(str::to_string), state: a["state"].as_str().unwrap_or("sent").to_string() });+        }+    }+    out+}++/// One change seen while following.+#[derive(Clone, Debug, PartialEq)]+pub struct Change { pub mpn: String, pub attempt: usize, pub from: String, pub to: String, pub late: bool, pub page: Option<String>, pub reason: Option<String>, pub done: bool }++impl Change {+    pub fn line(&self) -> String {+        let what = if self.late && self.to != "built" { format!("{} (deadline passed: plan as for a refusal; the factory keeps going)", self.to) } else { self.to.clone() };+        format!("{} (attempt {}): {} -> {what}{}{}", self.mpn, self.attempt, self.from, self.page.as_deref().map(|p| format!(" {p}")).unwrap_or_default(), self.reason.as_deref().map(|r| format!(" ({r})")).unwrap_or_default())+    }+}++/// Compare one status answer with what was known: the change to report, if any.+pub fn change_of(t: &Target, was_late: bool, v: &Value) -> Option<Change> {+    let r = supply::answer(v);+    let to = r["state"].as_str()?.to_string();+    let late = r["deadline_passed"] == true;+    if to == t.state && late == was_late { return None; }+    let probe = json!({"state": to});+    let done = supply::built(&probe) || supply::refused(&probe) || late;+    Some(Change { mpn: t.mpn.clone(), attempt: t.attempt, from: t.state.clone(), to, late, page: r["page_url"].as_str().map(str::to_string), reason: r["reason"].as_str().map(str::to_string), done })+}++fn wait_on(t: Target, path: String, wait: u64, stop: Instant, tx: mpsc::Sender<Result<Change, String>>) {+    let (mut t, mut late, mut errors) = (t, false, 0);+    while Instant::now() < stop {+        let since: String = t.state.chars().filter(|c| c.is_ascii_alphanumeric() || *c == '_').collect();+        let q = if wait > 0 { format!("{path}?wait={wait}&since={since}") } else { path.clone() };+        let asked = Instant::now();+        match api(&q, "GET", None) {+            Ok(v) => {+                errors = 0;+                if let Some(c) = change_of(&t, late, &v) {+                    let done = c.done;+                    t.state = c.to.clone();+                    late = c.late;+                    let _ = tx.send(Ok(c));+                    if done { return; }+                } else if wait == 0 {+                    std::thread::sleep(Duration::from_secs(30));+                } else if asked.elapsed() < Duration::from_secs(5) {+                    // the wiki answered at once with nothing new (a server without the wait): never ask in a tight loop+                    std::thread::sleep(Duration::from_secs(10));+                }+            }+            Err(e) => {+                errors += 1;+                if errors >= 5 { let _ = tx.send(Err(format!("{} (attempt {}): could not read its status ({e}); `part-request --refresh` reads it later", t.mpn, t.attempt))); return; }+                std::thread::sleep(Duration::from_secs(20));+            }+        }+    }+}++/// Requests with no status API (a wiki older than 2026-12-04): poll `part status --json` and compare.+fn poll_list(ts: Vec<Target>, data: Value, stop: Instant, tx: mpsc::Sender<Result<Change, String>>) {+    let mut data = data;+    let mut open = ts;+    while !open.is_empty() && Instant::now() < stop {+        std::thread::sleep(Duration::from_secs(45));+        let o = aiflow_sys::process::Command::new("adom-wiki").args(["part", "status", "--json"]).stdin(aiflow_sys::process::Stdio::null()).output();+        let Some(list) = o.ok().and_then(|o| serde_json::from_slice::<Value>(&o.stdout).ok()).and_then(|v| v["data"]["requests"].as_array().cloned()) else { continue };+        supply::refresh(&mut data, &list);+        open.retain_mut(|t| {+            let a = &data["partRequests"][&t.mpn][t.attempt - 1];+            let now = a["state"].as_str().unwrap_or("").to_string();+            if now.is_empty() || now == t.state { return true; }+            let done = !supply::pending(a);+            let _ = tx.send(Ok(Change { mpn: t.mpn.clone(), attempt: t.attempt, from: t.state.clone(), to: now.clone(), late: false, page: a["pageUrl"].as_str().map(str::to_string), reason: a["reason"].as_str().map(str::to_string), done }));+            t.state = now;+            !done+        });+    }+}++/// Follow every open request until each is final or past its deadline, or `minutes` run out. Calls `each` per+/// change (or failure to read) as it comes. Returns (changes, how many were still open at the end).+pub fn follow(data: &Value, minutes: u64, mut each: impl FnMut(&Result<Change, String>)) -> (Vec<Change>, usize) {+    let ts = targets(data);+    let stop = Instant::now() + Duration::from_secs(minutes.max(1) * 60);+    let (tx, rx) = mpsc::channel();+    let (with_api, without): (Vec<Target>, Vec<Target>) = ts.iter().cloned().partition(|t| t.status_api.is_some());+    let wait = if with_api.len() <= MAX_WAITERS { WAIT_S } else { 0 };+    for t in with_api {+        let (tx, path) = (tx.clone(), t.status_api.clone().unwrap());+        std::thread::spawn(move || wait_on(t, path, wait, stop, tx));+    }+    if !without.is_empty() {+        let (tx, d) = (tx.clone(), data.clone());+        std::thread::spawn(move || poll_list(without, d, stop, tx));+    }+    drop(tx);+    let mut seen = Vec::new();+    let mut finished: std::collections::BTreeSet<(String, usize)> = Default::default();+    for m in rx {+        each(&m);+        if let Ok(c) = &m {+            if c.done { finished.insert((c.mpn.clone(), c.attempt)); }+            seen.push(c.clone());+        }+    }+    let open = ts.iter().filter(|t| !finished.contains(&(t.mpn.clone(), t.attempt))).count();+    (seen, open)+}++#[cfg(test)]+mod tests {+    use super::*;++    #[test]+    fn a_thread_request_keeps_where_to_wait_and_its_deadline() {+        // the wiki's answer to a token request: the record, and beside it notify, status_api, deadline_at+        let v = json!({"status": "ok", "data": {"request": {"id": 9700, "mpn": "ZZPT100A", "state": "queued", "status_url": "/part-request/abc"},+            "notify": "thread", "status_api": "/api/part-request/status/tok123", "deadline_at": "2026-12-04T17:20:00.000Z"}});+        let mut a = json!({"state": "sent"});+        supply::absorb_answer(&mut a, &v);+        assert_eq!((a["state"].as_str(), a["statusApi"].as_str(), a["deadlineAt"].as_str(), a["notify"].as_str(), a["requestId"].as_u64()),+            (Some("queued"), Some("/api/part-request/status/tok123"), Some("2026-12-04T17:20:00.000Z"), Some("thread"), Some(9700)));+        assert!(supply::waiting(&a));+        // past the deadline, still building: planned for as a refusal, still followed by refresh+        supply::absorb_answer(&mut a, &json!({"request": {"state": "building", "deadline_passed": true}}));+        assert!(supply::late(&a) && supply::failed(&a) && supply::pending(&a) && !supply::waiting(&a));+        let next = supply::next("ZZPT100A", &[a.clone()], None, None);+        assert!(next.contains("deadline") && next.contains("build-a-component-page") && next.contains("--as"), "{next}");+        assert!(supply::decision("ZZPT100A", &[], &[a.clone()], None, None).contains("deadline passed"));+        // built after its deadline: no longer late+        supply::absorb_answer(&mut a, &json!({"request": {"state": "built", "deadline_passed": false, "page_url": "/adom/zzpt100a"}}));+        assert!(supply::built(&a) && !supply::late(&a));+    }++    #[test]+    fn an_open_request_says_follow_it_and_keep_working() {+        let a = json!({"inputs": supply::inputs("U7", None, None), "state": "queued", "statusApi": "/api/part-request/status/t"});+        let next = supply::next("U7", &[a], None, None);+        assert!(next.contains("--follow") && next.contains("Monitor") && next.contains("keep working"), "{next}");+    }++    #[test]+    fn a_board_batch_records_each_part_and_the_batch() {+        let mut d = json!({"outcomes": {"parts": {"missing": ["U7", "Q2", "J9"], "parts": [+            {"mpn": "U7", "manufacturer": "Acme", "datasheet": "https://acme/u7.pdf"}, {"mpn": "Q2"}, {"mpn": "J9"}]}},+            "partRequests": {"J9": [{"inputs": supply::inputs("J9", None, None), "state": "cannot_build"}]}});+        let sent = unrequested(&d);+        assert_eq!(sent, vec![json!({"mpn": "U7", "manufacturer": "Acme", "datasheet_url": "https://acme/u7.pdf"}), json!({"mpn": "Q2"})], "J9 had its attempt: a retry goes one by one");+        let ans = json!({"notify": "thread", "deadline_at": "2026-12-04T17:20:00Z", "batch": {"id": "b_x1", "url": "/part-requests/batch/b_x1"}, "items": [+            {"mpn_input": "U7", "request_id": 11, "state": "queued", "status_api": "/api/part-request/status/t11"},+            {"mpn_input": "Q2", "request_id": 12, "state": "unknown", "message": "not a part number the factory knows"}]});+        let (id, lines) = record_batch(&mut d, &sent, &ans, "power-board", "AI Flow", "2026-12-04T17:00:00Z");+        assert_eq!(id, "b_x1");+        assert_eq!(lines.len(), 2);+        let u7 = &d["partRequests"]["U7"][0];+        assert_eq!((u7["statusApi"].as_str(), u7["batchId"].as_str(), u7["deadlineAt"].as_str(), u7["notify"].as_str(), u7["requestId"].as_u64()),+            (Some("/api/part-request/status/t11"), Some("b_x1"), Some("2026-12-04T17:20:00Z"), Some("thread"), Some(11)));+        assert!(supply::refused(&d["partRequests"]["Q2"][0]), "an unknown number is a refusal");+        assert_eq!(d["partRequests"]["Q2"][0]["reason"], "not a part number the factory knows");+        assert_eq!(d["partBatches"][0]["ref"], "power-board");+        assert!(unrequested(&d).is_empty(), "sent once");+        let ts = targets(&d);+        assert_eq!(ts.len(), 1);+        assert_eq!((ts[0].mpn.as_str(), ts[0].status_api.as_deref()), ("U7", Some("/api/part-request/status/t11")));+    }++    #[test]+    fn a_status_answer_is_a_change_only_when_it_moved() {+        let t = Target { mpn: "U7".into(), attempt: 1, status_api: Some("/s".into()), state: "queued".into() };+        assert_eq!(change_of(&t, false, &json!({"request": {"state": "queued"}})), None);+        let c = change_of(&t, false, &json!({"request": {"state": "building"}})).unwrap();+        assert!(!c.done);+        let late = change_of(&t, false, &json!({"request": {"state": "queued", "deadline_passed": true}})).unwrap();+        assert!(late.done && late.line().contains("deadline passed"), "{}", late.line());+        let built = change_of(&t, false, &json!({"request": {"state": "built", "page_url": "/adom/u7"}})).unwrap();+        assert!(built.done && built.line().contains("/adom/u7"));+    }++    #[test]+    fn the_thread_options_go_in_the_body() {+        let mut b = json!({"mpn": "U7"});+        thread_opts(&mut b, Some(45), true);+        assert_eq!(b, json!({"mpn": "U7", "deadline_minutes": 45, "notify": "email"}));+        let mut c = json!({});+        thread_opts(&mut c, Some(5000), false);+        assert_eq!(c, json!({"deadline_minutes": 1440}));+    }+}
crates/adom-aiflow/src/supply.rs+65−14
@@ -15,8 +15,9 @@ use serde_json::{json, Value}; pub const DEFAULT_FILE: &str = "design/supply-risk.json"; pub const MAX_ALTERNATIVES: usize = 3; const RISKS: [&str; 3] = ["high", "medium", "low"];-/// The factory states that mean "no page from this attempt".-const REFUSED: [&str; 5] = ["cannot_build", "review", "failed", "rejected", "error"];+/// The factory states that mean "no page from this attempt" (a batch also answers "unknown" for a number the factory+/// does not recognize, and "gave_up").+const REFUSED: [&str; 7] = ["cannot_build", "review", "failed", "rejected", "error", "unknown", "gave_up"];  /// What one request sent: the part number asked for, the manufacturer, the datasheet (or land-pattern) link. pub fn inputs(requested: &str, manufacturer: Option<&str>, datasheet: Option<&str>) -> Value {@@ -46,25 +47,61 @@ pub fn duplicate(data: &Value, mpn: &str, inp: &Value) -> Option<(usize, Value)> pub fn refused(a: &Value) -> bool { a["state"].as_str().map(|s| REFUSED.contains(&s)).unwrap_or(false) } pub fn built(a: &Value) -> bool { a["state"] == "built" } pub fn pending(a: &Value) -> bool { !refused(a) && !built(a) }+/// Still building past the deadline the request was given (`deadline_passed`): planned for as a refusal, while the+/// factory keeps going and a page that lands later is still used.+pub fn late(a: &Value) -> bool { pending(a) && a["deadlinePassed"] == true }+/// No page from this attempt to plan on: refused, or past its deadline.+pub fn failed(a: &Value) -> bool { refused(a) || late(a) }+/// Pending and still inside its deadline: follow it in the background and keep working.+pub fn waiting(a: &Value) -> bool { pending(a) && !late(a) }  /// The request record inside whatever envelope `adom-wiki part request --json` or `part status --json` answers.+/// The record with a `state` wins over an envelope that only carries `status_url` beside it: the wiki answers a+/// single request as `{request: {state, ...}, status_url, status_api, ...}` (before 0.2.149 every such attempt was+/// recorded as "sent", whatever the factory said). pub fn answer(v: &Value) -> Value {-    fn find(v: &Value) -> Option<Value> {+    fn find(v: &Value, key: &str) -> Option<Value> {         match v {-            Value::Object(m) if m.contains_key("state") || m.contains_key("status_url") => Some(v.clone()),-            Value::Object(m) => m.values().find_map(find),-            Value::Array(a) => a.iter().find_map(find),+            Value::Object(m) if m.contains_key(key) => Some(v.clone()),+            Value::Object(m) => m.values().find_map(|x| find(x, key)),+            Value::Array(a) => a.iter().find_map(|x| find(x, key)),             _ => None,         }     }-    find(&v["data"]).or_else(|| find(v)).unwrap_or(Value::Null)+    let root = if v["data"].is_null() { v } else { &v["data"] };+    let Some(mut rec) = find(root, "state").or_else(|| find(root, "status_url")) else { return Value::Null };+    // the envelope's status link sits beside the record+    if rec["status_url"].is_null() && !root["status_url"].is_null() { rec["status_url"] = root["status_url"].clone(); }+    rec } -/// Fold a factory answer into an attempt.+/// Fold a factory answer into an attempt. A request made from a thread (the wiki, 2026-12-04) also says where to wait+/// on it (`status_api`), when to stop waiting (`deadline_at`, `deadline_passed`) and who hears how it ends (`notify`). pub fn absorb(attempt: &mut Value, ans: &Value) {-    for (from, to) in [("state", "state"), ("reason", "reason"), ("page_url", "pageUrl"), ("status_url", "statusUrl"), ("updated_at", "updatedAt"), ("requested_at", "requestedAt")] {+    for (from, to) in [("state", "state"), ("reason", "reason"), ("page_url", "pageUrl"), ("status_url", "statusUrl"), ("updated_at", "updatedAt"), ("requested_at", "requestedAt"),+                       ("status_api", "statusApi"), ("deadline_at", "deadlineAt"), ("deadline_passed", "deadlinePassed"), ("notify", "notify"), ("request_id", "requestId")] {         if !ans[from].is_null() { attempt[to] = ans[from].clone(); }     }+    // a batch item names its state "status" and its part "mpn_input"; a single request's record carries its id+    if ans["state"].is_null() { if let Some(s) = ans["status"].as_str() { attempt["state"] = json!(s); } }+    if attempt["requestId"].is_null() && ans["id"].is_number() { attempt["requestId"] = ans["id"].clone(); }+    // a request's answer gives the page as a full URL, the status list as a path: keep the path+    if let Some(u) = attempt["pageUrl"].as_str().and_then(|u| u.strip_prefix("https://wiki.adom.inc")).map(str::to_string) { attempt["pageUrl"] = json!(u); }+}++/// Fold a whole `part request` or status answer: the request record, then the thread fields the envelope carries+/// beside it (`{request: {...}, notify, status_api, deadline_at}`).+pub fn absorb_answer(attempt: &mut Value, v: &Value) {+    absorb(attempt, &answer(v));+    let top = if v["data"].is_object() { &v["data"] } else { v };+    for (from, to) in [("status_api", "statusApi"), ("deadline_at", "deadlineAt"), ("notify", "notify")] {+        if !top[from].is_null() { attempt[to] = top[from].clone(); }+    }+}++/// The part number a batch item was sent as.+pub fn item_mpn(it: &Value) -> Option<&str> {+    it["mpn_input"].as_str().filter(|s| !s.trim().is_empty()).or(it["mpn"].as_str()).map(str::trim) }  pub fn record(data: &mut Value, mpn: &str, attempt: Value) -> usize {@@ -153,12 +190,14 @@ pub fn decision(mpn: &str, refs: &[String], tries: &[Value], assessed: Option<&V     let mut parts = Vec::new();     let refused_n = tries.iter().filter(|a| refused(a)).count();     if tries.is_empty() { parts.push("no page request yet".to_string()); }+    if let Some(a) = tries.iter().rev().find(|a| built(a)) { parts.push(format!("page built{}", a["pageUrl"].as_str().map(|u| format!(": {}", u.trim_start_matches('/'))).unwrap_or_default())); }     if refused_n > 0 {         let mut why: Vec<String> = tries.iter().filter(|a| refused(a)).filter_map(|a| a["reason"].as_str().map(|s| s.trim_end_matches('.').to_string())).collect();         why.dedup();         parts.push(format!("refused {}{}", times(refused_n), if why.is_empty() { String::new() } else { format!(" ({})", why.join("; ")) }));     }-    if tries.iter().any(pending) { parts.push("a request is still in the factory's queue".into()); }+    if tries.iter().any(waiting) { parts.push("a request is still in the factory's queue".into()); }+    if tries.iter().any(late) { parts.push("the factory's deadline passed with no page (it keeps building; a page that lands later is used)".into()); }     if let Some(a) = assessed {         let dist = a["distributors"].as_array().map(|d| d.len()).unwrap_or(0);         let life = a["lifecycle"]["value"].as_str().or(a["lifecycle"].as_str()).unwrap_or("?");@@ -190,17 +229,22 @@ pub fn next(mpn: &str, tries: &[Value], assessed: Option<&Value>, choice: Option         return format!("ask the human which way to go for {mpn} (an alternative or keep it), then `supply-risk --choose {mpn} --pick <alternative|keep> --why \"...\"`; nothing is substituted without their choice");     }     if tries.is_empty() {-        return format!("`part-request {mpn} [--datasheet <link>]` asks the factory for its page (or give it from the project library)");+        return format!("`part-request --missing` asks the factory for every part with no page as one batch for this board (`part-request {mpn} [--datasheet <link>]` for this one alone), or give it from the project library");+    }+    if tries.last().map(waiting).unwrap_or(false) {+        return format!("keep working on the board: follow {mpn} in the background with `adom-aiflow part-request --follow` under the Monitor tool (one line per change; it ends when every request is final or past its deadline), then `part-request --refresh` records the answers");     }-    if tries.last().map(pending).unwrap_or(false) {-        return "`part-request --refresh` once the factory has answered".into();+    // the wiki, 2026-12-04: a passed deadline is planned for as a refusal; the factory keeps going+    if tries.last().map(late).unwrap_or(false) {+        let retry = if tries.len() == 1 { format!(", or retry once with a changed input (`part-request {mpn} --as <orderable MPN>`, `--datasheet <link>`, `--manufacturer <maker>`)") } else { String::new() };+        return format!("the factory's deadline for {mpn} passed with no page: plan as for a refusal. Build its page yourself (build-a-component-page skill){retry}, or assess its supply (write {DEFAULT_FILE}, then `supply-risk`); a page that lands later is still picked up by `parts`");     }     // issue #259 (Max Jenkinson): a refusal for want of a land pattern the factory can read (connectors publish it as     // a dimensioned drawing, not text) fails the same way on every retry, and the part's supply is not the problem     if refused_n >= 1 && tries.iter().filter(|a| refused(a)).any(land_pattern_refusal) {         return format!("the factory cannot read {mpn}'s land pattern (a drawing, not text; usual for connectors), so another datasheet will refuse the same way: give it from the project library (`parts --project-lib <dir>`: symbol, footprint, STEP and provenance). Take the footprint from a source that already has it: KiCad's own libraries (Connector_USB, Connector_JST, ... hold many receptacles by MPN), the assembly house's library for a part it stocks, or the maker's CAD download; check its pads against the datasheet's drawing and record where it came from in provenance");     }-    if refused_n == 1 && tries.len() == 1 {+    if tries.iter().filter(|a| failed(a)).count() == 1 && tries.len() == 1 {         return format!("retry once with a changed input: `part-request {mpn} --as <orderable MPN>` (`adom-wiki part candidates {mpn}`), `--datasheet <the maker's product page, package drawing or CAD link>`, or `--manufacturer <maker>`");     }     format!("assess {mpn}'s supply: write {DEFAULT_FILE} (lifecycle, stock per distributor, lead time, second sources, package, datasheet and land pattern published, up to three alternatives; each figure with source and date), then `supply-risk`")@@ -272,6 +316,13 @@ mod tests {         assert_eq!(built_page(&d, "U7X"), Some((1, "adom/u7x-tr".to_string(), "U7X-TR".to_string())));         assert!(refused(&d["partRequests"]["U9"][0]));         assert_eq!(answer(&json!({"status": "ok", "data": {"request": {"state": "queued", "status_url": "/x"}}}))["status_url"], "/x");+        // the live single-request answer (2026-12-04): the state is in `request`, the status link beside it+        let live = json!({"status": "ok", "data": {"request": {"id": 1412, "state": "built", "page_url": "https://wiki.adom.inc/adom/ptv09a-4020f-b104"},+            "already": "built", "status_url": "/part-request/K", "status_api": "/api/part-request/status/K", "notify": "email", "deadline_at": null}});+        let mut a = json!({"state": "sent"});+        absorb_answer(&mut a, &live);+        assert_eq!((a["state"].as_str(), a["pageUrl"].as_str(), a["statusUrl"].as_str(), a["statusApi"].as_str()),+            (Some("built"), Some("/adom/ptv09a-4020f-b104"), Some("/part-request/K"), Some("/api/part-request/status/K")));     }      #[test]
docs/release-0.2.149.mdadded+12
@@ -0,0 +1,12 @@+# adom-aiflow 0.2.149++Part requests answer the thread that asked (the wiki, 2026-12-04). A request AI Flow sends carries the thread's token, so the wiki emails the human nothing about it (an inbox item still records how it ended), gives it a deadline (20 minutes by default), and says where to wait on it. John is building five boards on several Adom Mesh boxes; each thread now hears its own parts' answers instead of the human's inbox.++- **One batch per board.** `part-request --missing [--ref "<board>"]` sends every part `parts` found with no page, and no request yet, as one batch named for the board (default: the board's file name). Each part is kept in `partRequests` with its batch, and the batch in `partBatches`. A retry still goes one part at a time with a changed input.+- **Never block on the factory.** `part-request --follow`, run under the Monitor tool, waits on the run's open requests (the wiki holds each read until the state changes), prints one line per change and ends when every request is built, refused or past its deadline. It only reads run.json, records no turn, and logs each change to the ledger; `part-request --refresh` records the answers. `parts`, `part-request` and the sourcing skill say to keep working on the board meanwhile.+- **Each attempt keeps** `statusApi`, `deadlineAt`, `deadlinePassed`, `notify` and the request id, beside `statusUrl`. `--refresh` also reads each open request's own status, so a passed deadline shows.+- **A passed deadline is planned for as a refusal**: the next step is a retry with a changed input, building the page yourself (build-a-component-page), or the supply assessment. The factory keeps going, and a page that lands later is still used by `parts`.+- **`--deadline <minutes>`** (1 to 1440) and **`--email`** (only when the human asked to be emailed) go to the wiki's API for one part or a batch.+- **Fixed: a single request's state.** The wiki answers one part with the record inside `request` and the status link beside it; AI Flow took the outer object and recorded every such attempt as "sent", whatever the factory said. A part already built now reads built at once, with its page as a path (the answer gives a full URL).+- A batch's `unknown` (a number the factory does not recognize) and `gave_up` count as refusals.+- Skills: aiflow-sourcing ("When a part cannot get a page", step 1) and adom-aiflow (the parts step).
package.json+1−1
@@ -1,7 +1,7 @@ {   "slug": "adom-aiflow",   "type": "app",-  "version": "0.2.148",+  "version": "0.2.149",   "title": "AI Flow",   "description": "Adom's AI Flow: a tool to help the AI follow all of the steps it takes to build a board. One Rust binary with a crate per step (placement helpers, a grid router with Kelvin taps, pours with keepouts, KiCad's DRC gate, live landing through the KiCad Bridge, copper measurement, current and thermal analysis) and a finish line that refuses an unfinished board. Every command answers with hints for the AI; every turn, its thinking time and every rework loop go into run.jsonl, so Claude, Codex and any other engine are compared on the same flow. KiCad, Fusion 360 and Altium Designer today (the same steps and gates through each tool's bridge); Adom's own web apps next.",   "summary": "Adom's AI Flow: a tool to help the AI follow all of the steps it takes to build a board. The AI thinks its way from placement through routing, pours, current and thermal analysis to a delivered video; the binary does the fast, deterministic parts of every step, hands back hints, and keeps a ledger of every turn, every return to an earlier step, and the clock from the prompt to done.",
page.json+1−1
@@ -1,7 +1,7 @@ {   "slug": "adom-aiflow",   "type": "app",-  "version": "0.2.148",+  "version": "0.2.149",   "title": "AI Flow",   "description": "Adom's AI Flow: a tool to help the AI follow all of the steps it takes to build a board. One Rust binary with a crate per step (placement helpers, a grid router with Kelvin taps, pours with keepouts, KiCad's DRC gate, live landing through the KiCad Bridge, copper measurement, current and thermal analysis) and a finish line that refuses an unfinished board. Every command answers with hints for the AI; every turn, its thinking time and every rework loop go into run.jsonl, so Claude, Codex and any other engine are compared on the same flow. KiCad, Fusion 360 and Altium Designer today (the same steps and gates through each tool's bridge); Adom's own web apps next.",   "summary": "Adom's AI Flow: a tool to help the AI follow all of the steps it takes to build a board. The AI thinks its way from placement through routing, pours, current and thermal analysis to a delivered video; the binary does the fast, deterministic parts of every step, hands back hints, and keeps a ledger of every turn, every return to an earlier step, and the clock from the prompt to done.",
skills/adom-aiflow/SKILL.md+1−1
@@ -364,7 +364,7 @@ The clock starts at the prompt even when there is no board yet. A KiCad run that starts with no board (`intake` with no `start --board`) follows the `kicad-new` sequence: intake, rules, design, test-plan, sourcing, **parts**, **project-page**, **library**, **schematic**, simulation, then components, models and the board steps as usual. Hydrogen is the stage for the steps without KiCad (the step dashboard comes up at every new phase), KiCad's window for the rest.  1. **`sourcing check --bom design/bom.csv`** as above.-2. **`step parts`, `parts --show`**: every BOM row with an MPN is matched to its Adom wiki component page; one Hydrogen tab ("Parts · <run>") steps through the pages so the viewer sees the parts picked. A part with no page: `part-request <MPN>` asks Adom's part factory for it (or make it with the wiki-component skill: datasheet symbol, footprint, STEP; verified), run `parts --show` again. A refused request gets one retry with a changed input (`--as <orderable MPN>`, `--datasheet <the maker's drawing>`); a part still without a page gets a supply assessment and up to three alternatives (`supply-risk`), and the human chooses (`supply-risk --choose`): aiflow-sourcing, "When a part cannot get a page". Never swap in a similar part to dodge a missing page, and never without the human's choice.+2. **`step parts`, `parts --show`**: every BOM row with an MPN is matched to its Adom wiki component page; one Hydrogen tab ("Parts · <run>") steps through the pages so the viewer sees the parts picked. Parts with no page: `part-request --missing` asks Adom's part factory for all of them as one batch for this board (or make one with the wiki-component skill: datasheet symbol, footprint, STEP; verified). The answers come back to this thread, not by email to the human: keep working and follow them with `part-request --follow` under the Monitor tool, then `part-request --refresh` and `parts --show` again; a request past its deadline (20 minutes) is planned for as a refusal. A refused request gets one retry with a changed input (`--as <orderable MPN>`, `--datasheet <the maker's drawing>`); a part still without a page gets a supply assessment and up to three alternatives (`supply-risk`), and the human chooses (`supply-risk --choose`): aiflow-sourcing, "When a part cannot get a page". Never swap in a similar part to dodge a missing page, and never without the human's choice. 3. **`step project-page`, `project-page --page <owner>/<slug> --create`**: revision 1 of the board's one project page before any EDA work: a README saying what the board is, the component table (references, value, MPN, manufacturer, each part's wiki page) and a KiCad PCM repository of every part (an Adom Cloud Library of the parts, exported and repackaged for KiCad's Plugin and Content Manager, served from the page at `/api/pages/<owner>/<slug>/files/pcm/repository.json`). A new board always gets a new, standalone page (a new slug, `--create`); `project-page` refuses an existing page unless `--existing` says it is this same board's own page. Later revisions update this same page (aiflow-project-page skill); never a second page for the board. 4. **`step library`**: install the parts in KiCad on the test box: `kicad_pcm_add_repository {"url": <repositoryUrl>}`, `kicad_pcm_install {"repositoryUrl": ..., "identifier": ...}` (both printed by `project-page`), restart KiCad, then **`pcm check`** (the package is in `kicad_pcm_list`). The library is `PCM_<slug>`. 5. **`step schematic`**: draw the schematic in KiCad's schematic editor, on camera: `kicad_open_schematic`, `kicad_sch_place_symbol` (symbols from `PCM_<slug>`), `kicad_sch_wire`, `kicad_sch_label`, `kicad_sch_set_property`; save; **`schematic check --sch <project>.kicad_sch`** passes when kicad-cli ERC ran and has no errors (no ERC report is a failure, never a clean ERC), every BOM reference is on the sheet and every part comes from the project library. An existing project that keeps its own native libraries need not move to `PCM_<slug>`: a part with a complete project-library entry passes when its provenance.json entry binds each reference to the exact native symbol library and footprint the schematic uses, `"nativeSourceBindings": [{"ref": "U1", "symbolLibrary": "MyLib", "footprint": "MyLib:QFN-48"}]` (issue #266); any other reference, library or footprint still fails, and ERC and the symbol checks are unchanged. Never write the `.kicad_sch` with a script of your own: the viewer is meant to see it drawn.
skills/aiflow-sourcing/SKILL.md+9−1
@@ -165,7 +165,15 @@ Verified example, 2026-10-08: Pup showed Mouser Access Denied for MF40200V1-1000  `parts` names every BOM part with no component page and the next command for each. Before you call a part a failure, do three things in order (issue #193): -1. **Ask the factory, then retry once with better inputs.** `adom-aiflow part-request <MPN> [--datasheet <link>]` sends `adom-wiki part request` and keeps the attempt in the run (`partRequests`); `part-request --refresh` reads the answers of queued ones. A refusal (`cannot_build`, `review`) gets exactly one retry that changes at least one input. AI Flow does not send the same inputs twice. Pick the change from the refusal:+1. **Ask the factory, then retry once with better inputs.** Ask for the board's parts together: `adom-aiflow part-request --missing [--ref "<board>"]` sends every part `parts` found with no page as one batch named for the board (default: the board's file name), and keeps each attempt in the run (`partRequests`, the batch in `partBatches`). One part on its own: `adom-aiflow part-request <MPN> [--datasheet <link>]`. A refusal (`cannot_build`, `review`, `unknown`) gets exactly one retry, one part at a time, that changes at least one input. AI Flow does not send the same inputs twice. Pick the change from the refusal (the list below).++   **The answer comes back to this thread, not to the human's inbox.** A request from AI Flow carries the thread's token, so the wiki sends the human no email about it (an inbox item still records how it ended) and gives it a deadline, 20 minutes by default. Never block the run on the factory:+   - after asking, keep working on the rest of the board, and start `adom-aiflow part-request --follow` under the Monitor tool. It waits on the run's open requests (each one's `statusApi`, a read the wiki holds until the state changes), prints one line per change and ends when every request is built, refused or past its deadline. It only reads run.json; then run `part-request --refresh` to record the answers and `parts` to use the new pages. Without Monitor: `adom-wiki api "<statusApi>?wait=50"` answers as soon as the state changes;+   - a request past its deadline (`deadlinePassed`, the `PART_REQUEST_DEADLINE_PASSED` hint) is planned for as a refusal: retry once with a changed input, build the page yourself (build-a-component-page skill), or go on to step 2. The factory keeps going, and a page that lands later is still picked up by `parts`;+   - `--deadline <minutes>` (1 to 1440) when the run can wait longer or must move sooner; `--email` only when the human asked to be emailed;+   - five boards on several Mesh boxes: each thread requests its own board's batch and follows only its own run's requests.++   Pick the retry's change from the refusal:    - no distributor sells the number, or a packaging/reel suffix: `--as <orderable MPN>` (from `adom-wiki part candidates <MPN>`); the BOM line keeps its MPN, and the page built under the other number is used for it;    - no datasheet, or no land-pattern drawing: `--datasheet` with the maker's product page, its separate package drawing or its CAD download (section 5's order), or the distributor PDF when the maker's page failed;    - land-pattern readings disagreed: `--datasheet` with the maker's own footprint or package drawing, which settles it;