main
Colby Knox adom-aiflow-pcbway 0.1.3: a guide, never a gate (checks report findings; only could-not-run is an error) 80bd934
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
//! PCBWay quote workflow. MIT. CSV utility derived from adom-aiflow-jlcpcb.
mod csvio;
use clap::{Parser, Subcommand};
use serde_json::{json, Value};
use sha2::{Digest, Sha256};
use std::{
    collections::{BTreeMap, BTreeSet},
    fs,
    io::Write,
    path::{Path, PathBuf},
};
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;

// A dynamic skill (see adom-aiflow): checks report and suggest, never block. ERROR means only "I could not run"
// (a missing or unreadable input); everything a check finds is a finding printed after OK, with the command done.
static FINDINGS: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());
fn finding(msg: impl Into<String>) {
    let m = msg.into();
    if let Ok(mut f) = FINDINGS.lock() {
        if !f.contains(&m) {
            f.push(m);
        }
    }
}
fn findings() -> Vec<String> {
    FINDINGS.lock().map(|f| f.clone()).unwrap_or_default()
}
#[derive(Parser)]
#[command(
    version,
    about = "PCBWay RFQ workflow: exact MPN BOM, source centroid, evidence-bound quote and comparison. Never purchases."
)]
struct Cli {
    #[arg(long, global = true, default_value = ".")]
    project: PathBuf,
    #[arg(long, global = true)]
    ai_thread: Option<String>,
    #[command(subcommand)]
    command: Cmd,
}
#[derive(Subcommand)]
enum Cmd {
    Init {
        #[arg(long)]
        scope: PathBuf,
    },
    Next,
    /// Show PCBWay in Hydrogen webview by default; Pup is an explicit option.
    Show {
        #[arg(long, default_value="webview", value_parser=["webview", "pup"])]
        surface: String,
        #[arg(long, default_value="quote", value_parser=["quote", "account"])]
        page: String,
        #[arg(long)]
        target: Option<String>,
    },
    /// Record account progress without storing a password in the project or ledger.
    Account {
        #[arg(long)]
        email: String,
        #[arg(long, value_parser=["registration-pending", "captcha-required", "verification-required", "signed-in"])]
        status: String,
        #[arg(long)]
        evidence: PathBuf,
    },
    /// Prepare a PRICING ONLY package; does not grant manufacturing approval.
    Export,
    /// Record vendor receipt (not a local click or a submission attempt).
    Submitted {
        #[arg(long)]
        receipt: PathBuf,
    },
    /// Record PCBWay's actual price with all inclusions and evidence.
    Quote {
        #[arg(long)]
        facts: PathBuf,
    },
    /// Persist a concrete dependency; next still names the unfinished step.
    Blocked {
        #[arg(long)]
        reason: String,
        #[arg(long)]
        evidence: PathBuf,
    },
    Compare {
        #[arg(long)]
        baseline: PathBuf,
    },
    Report,
}
fn read(p: &Path) -> Result<Value> {
    Ok(serde_json::from_slice(&fs::read(p)?)?)
}
fn write(p: &Path, v: &Value) -> Result<()> {
    fs::write(p, serde_json::to_vec_pretty(v)?)?;
    Ok(())
}
fn hash(p: &Path) -> Result<String> {
    Ok(format!("{:x}", Sha256::digest(fs::read(p)?)))
}
/// A field that should be filled: a finding when it is not.
fn want(v: &Value, k: &str, what: &str) {
    if v[k].as_str().unwrap_or("").trim().is_empty() {
        finding(format!("{what} has no {k}"));
    }
}
fn nonempty(v: &Value, k: &str) -> Result<String> {
    let s = v[k].as_str().unwrap_or("");
    if s.trim().is_empty() {
        return Err(format!("missing {k}").into());
    }
    Ok(s.into())
}
fn file(v: &Value) -> Result<Value> {
    let p = PathBuf::from(v.as_str().ok_or("file path required")?).canonicalize()?;
    if fs::metadata(&p)?.len() == 0 {
        return Err("empty evidence/input".into());
    }
    Ok(json!({"path":p,"sha256":hash(&p)?}))
}
fn current(v: &Value) -> bool {
    v["path"]
        .as_str()
        .and_then(|p| hash(Path::new(p)).ok())
        .is_some_and(|h| v["sha256"].as_str() == Some(h.as_str()))
}
fn digest(v: &Value) -> String {
    format!("{:x}", Sha256::digest(serde_json::to_vec(v).unwrap()))
}
fn valid_scope(v: &Value) -> Result<()> {
    if v["quantity"].as_u64().unwrap_or(0) == 0 {
        return Err("quantity must be positive".into());
    }
    for k in [
        "assembly",
        "finish",
        "target",
        "account",
        "centroidConvention",
        "openChecks",
    ] {
        want(v, k, "the scope");
    }
    for k in ["widthMm", "heightMm", "thicknessMm", "copperOz"] {
        if v[k].as_f64().unwrap_or(0.) <= 0. {
            finding(format!("the scope has no {k}: PCBWay's quote form asks for it"));
        }
    }
    if v["layers"].as_u64().unwrap_or(0) < 1 {
        finding("the scope has no layers count: PCBWay's quote form asks for it");
    }
    if !v["exclusions"].is_array() {
        finding("the scope lists no exclusions: say what the quote leaves out (shipping, tax, parts you supply) so it compares like for like");
    }
    Ok(())
}
fn load(d: &Path) -> Result<Value> {
    let s = read(&d.join("state.json"))?;
    for v in s["inputs"].as_object().ok_or("inputs missing")?.values() {
        if !current(v) {
            finding("an input (board, BOM, centroid or Gerbers) changed since init: a quote recorded before describes the old files; init a new run in a fresh --project for the new ones");
        }
    }
    Ok(s)
}
/// Is the exported package current (same scope, files unchanged)?
fn package_current(d: &Path, s: &Value) -> bool {
    read(&d.join("package.json")).is_ok_and(|p| {
        p["scopeDigest"] == digest(s)
            && p["files"].as_array().is_some_and(|a| a.iter().all(current))
    })
}
/// The exported package; a stale one is a finding (the commands still run).
fn package(d: &Path, s: &Value) -> Result<Value> {
    let p = read(&d.join("package.json")).map_err(|_| "no package yet: run `export` first")?;
    if !package_current(d, s) {
        finding("the package is stale (the scope or an exported file changed since export): run `export` again and repeat the vendor review");
    }
    Ok(p)
}
fn step(d: &Path, s: &Value) -> String {
    if !package_current(d, s) {
        return "export: make the pricing-only BOM/centroid/Gerber package".into();
    }
    if let Ok(a) = read(&d.join("account.json")) {
        if a["status"] != "signed-in" || !current(&a["evidence"]) {
            return format!("account: {}; continue the visible registration/login flow; CAPTCHA and email confirmation require the user; never infer successful registration from a click",a["status"]);
        }
    }
    let p = read(&d.join("package.json")).unwrap();
    let stamp = digest(&p);
    let r = read(&d.join("submitted.json")).unwrap_or(Value::Null);
    if r["packageDigest"] != stamp || !current(&r["evidence"]) || r["receiptConfirmed"] != true {
        return "submit: use the visible Hydrogen webview (Pup optional), verify intended account, upload package for RFQ; record actual vendor receipt with submitted".into();
    }
    let q = read(&d.join("quote.json")).unwrap_or(Value::Null);
    if q["packageDigest"] != stamp || !current(&q["evidence"]) {
        return "await-quote: inspect PCBWay response; assembly calculator excludes boards and components; request itemized complete price".into();
    }
    if q["kind"] != "vendor-full" {
        return "await-quote: only partial/calculator pricing exists; obtain full PCB + components + assembly quotation".into();
    }
    "quote-complete: deliver comparison and exclusions; manufacturing approval and payment are separate and not authorized by a quote request".into()
}
fn export(d: &Path, s: &Value) -> Result<Value> {
    let bom = csvio::Table::read(Path::new(s["inputs"]["bom"]["path"].as_str().unwrap()))?;
    let cpl = csvio::Table::read(Path::new(s["inputs"]["centroid"]["path"].as_str().unwrap()))?;
    if bom.col("ref").is_none() {
        return Err("the BOM has no reference column (ref, Reference or Designator)".into());
    }
    for h in ["mpn", "manufacturer", "value"] {
        if bom.col(h).is_none() {
            finding(format!("the BOM has no {h} column"));
        }
    }
    for h in ["Designator", "Mid X", "Mid Y", "Layer", "Rotation"] {
        if cpl.col(h).is_none() {
            return Err(format!("the centroid has no {h} column (kicad-cli's Ref/PosX/PosY/Rot/Side also work)").into());
        }
    }
    let mut included = BTreeMap::new();
    let mut seen = BTreeSet::new();
    let mut excluded = Vec::new();
    let dnp = |r: &Vec<String>| {
        let fit = bom.get(r, "fit").to_lowercase();
        let d = bom.get(r, "dnp").to_lowercase();
        ["post", "dnp", "exclude"].contains(&fit.as_str()) || ["yes", "true", "1", "dnp"].contains(&d.as_str())
    };
    let (mut no_mpn, mut dupes) = (Vec::new(), Vec::new());
    for r in &bom.rows {
        // a row may name several references (AI Flow's BOM: "C2 C3 C4")
        let refs: Vec<String> = bom
            .get(r, "ref")
            .split([' ', ',', ';'])
            .filter(|x| !x.is_empty())
            .map(String::from)
            .collect();
        if refs.is_empty() {
            finding("a BOM row has no reference: left out");
            continue;
        }
        for reference in refs {
            if !seen.insert(reference.clone()) {
                dupes.push(reference);
                continue;
            }
            if dnp(r) {
                excluded.push(reference);
                continue;
            }
            if bom.get(r, "mpn").is_empty() || bom.get(r, "manufacturer").is_empty() {
                no_mpn.push(reference.clone());
            }
            included.insert(reference, r);
        }
    }
    if !dupes.is_empty() {
        finding(format!("references on more than one BOM row (the first row is used): {}", dupes.join(", ")));
    }
    if !no_mpn.is_empty() {
        finding(format!("no exact MPN and manufacturer for {}: PCBWay will pick a part or ask; add them to the BOM for a like-for-like quote", no_mpn.join(", ")));
    }
    let mut placements = BTreeSet::new();
    let mut xyz = vec![vec!["Designator", "Mid X", "Mid Y", "Layer", "Rotation"]
        .into_iter()
        .map(String::from)
        .collect()];
    let (mut not_in_bom, mut bad_place) = (Vec::new(), Vec::new());
    for r in &cpl.rows {
        let reference = cpl.get(r, "Designator");
        if excluded.iter().any(|e| e == reference) {
            continue;
        }
        if !included.contains_key(reference) {
            not_in_bom.push(reference.to_string());
            continue;
        }
        if !placements.insert(reference.to_string()) {
            finding(format!("{reference} is in the centroid twice: the first row is used"));
            continue;
        }
        let ok = ["Mid X", "Mid Y", "Rotation"].iter().all(|h| {
            cpl.get(r, h).trim_end_matches("mm").trim().parse::<f64>().is_ok_and(|n| n.is_finite())
        });
        if !ok {
            bad_place.push(reference.to_string());
        }
        // PCBWay's centroid says Top/Bottom; kicad-cli says top/bottom
        let layer = match cpl.get(r, "Layer").to_ascii_lowercase().as_str() {
            "top" | "t" | "f" | "front" | "f.cu" => "Top".to_string(),
            "bottom" | "b" | "back" | "b.cu" => "Bottom".to_string(),
            other => {
                finding(format!("{reference}: centroid layer {other:?} is not top or bottom"));
                other.to_string()
            }
        };
        xyz.push(vec![
            reference.to_string(),
            cpl.get(r, "Mid X").into(),
            cpl.get(r, "Mid Y").into(),
            layer,
            cpl.get(r, "Rotation").into(),
        ]);
    }
    if !not_in_bom.is_empty() {
        finding(format!("in the centroid but not in the BOM (left out): {}", not_in_bom.join(", ")));
    }
    if !bad_place.is_empty() {
        finding(format!("no numeric position or rotation for {}", bad_place.join(", ")));
    }
    let unplaced: Vec<&String> = included.keys().filter(|r| !placements.contains(*r)).collect();
    if !unplaced.is_empty() {
        finding(format!("in the BOM but not in the centroid (PCBWay cannot place them): {}", unplaced.iter().map(|s| s.as_str()).collect::<Vec<_>>().join(", ")));
    }
    let mut rows = vec![vec![
        "Item",
        "Designator",
        "Quantity per board",
        "Manufacturer",
        "Manufacturer Part Number",
        "Description",
    ]
    .into_iter()
    .map(String::from)
    .collect()];
    for (i, (reference, r)) in included.iter().enumerate() {
        rows.push(vec![
            (i + 1).to_string(),
            reference.clone(),
            "1".into(),
            bom.get(r, "manufacturer").into(),
            bom.get(r, "mpn").into(),
            bom.get(r, "value").into(),
        ]);
    }
    let out = d.join("upload");
    fs::create_dir_all(&out)?;
    fs::write(
        out.join("BOM-PRICING-ONLY.csv"),
        csvio::write(&rows, "\r\n"),
    )?;
    fs::write(
        out.join("CENTROID-UNAPPROVED.csv"),
        csvio::write(&xyz, "\r\n"),
    )?;
    fs::copy(
        s["inputs"]["gerbers"]["path"].as_str().unwrap(),
        out.join("GERBERS-PRICING-ONLY.zip"),
    )?;
    let note=format!("# Pricing only — NOT RELEASED FOR MANUFACTURE\n\nQuantity: {}\n\nScope: {}\n\nSize: {} x {} mm, {} layers, {} mm, {} oz, {}.\n\nCentroid convention: {}\n\nOpen checks: {}\n\nExcluded references: {}\n\nOther exclusions: {}\n\nDo not substitute parts without approval. Quote PCB, parts/attrition, setup/stencil, placement, manual work, shipping and tax separately. No production or payment authorized. Vendor must review orientation/land patterns; JLC rotation corrections do not apply to PCBWay.\n",s["scope"]["quantity"],s["scope"]["assembly"],s["scope"]["widthMm"],s["scope"]["heightMm"],s["scope"]["layers"],s["scope"]["thicknessMm"],s["scope"]["copperOz"],s["scope"]["finish"],s["scope"]["centroidConvention"],s["scope"]["openChecks"],excluded.join(", "),s["scope"]["exclusions"]);
    fs::write(out.join("ASSEMBLY-NOTES.md"), note)?;
    let files = [
        "BOM-PRICING-ONLY.csv",
        "CENTROID-UNAPPROVED.csv",
        "GERBERS-PRICING-ONLY.zip",
        "ASSEMBLY-NOTES.md",
    ]
    .iter()
    .map(|n| file(&json!(out.join(n))))
    .collect::<Result<Vec<_>>>()?;
    let p = json!({"scopeDigest":digest(s),"files":files,"placementsPerBoard":included.len(),"manufacturingApproved":false,"excludedRefs":excluded});
    write(&d.join("package.json"), &p)?;
    Ok(p)
}
/// A quote's facts. ERROR only when it cannot be read as a quote (kind, total, a cost that is not a number);
/// what is missing or does not add up is a finding: the quote is recorded and the human sees what is open.
fn quote_valid(v: &Value, qty: u64) -> Result<()> {
    if !["calculator-only", "vendor-partial", "vendor-full"]
        .contains(&v["kind"].as_str().unwrap_or(""))
    {
        return Err("kind must be calculator-only, vendor-partial or vendor-full".into());
    }
    for k in ["vendorReference", "currency", "checkedAt", "scopeNote"] {
        want(v, k, "the quote");
    }
    if v["quantity"].as_u64() != Some(qty) {
        finding(format!("the quote is for {} boards but the scope says {qty}", v["quantity"]));
    }
    let total = v["totalBeforeShippingTax"]
        .as_f64()
        .ok_or("totalBeforeShippingTax must be a number")?;
    if !total.is_finite() || total <= 0. {
        return Err("totalBeforeShippingTax must be a positive number".into());
    }
    if !v["exclusions"].is_array() {
        finding("the quote lists no exclusions (shipping, tax, parts not included)");
    }
    if v["kind"] == "vendor-full" {
        for k in ["pcb", "components", "assembly"] {
            if v["includes"][k] != true {
                finding(format!("a vendor-full quote that does not say it includes {k}: it may not compare like for like"));
            }
        }
    }
    match v["breakdown"].as_object() {
        None => finding("no itemized breakdown: ask PCBWay for PCB, parts, setup, assembly and shipping separately"),
        Some(items) => {
            let mut sum = 0.;
            for x in items.values() {
                let n = x.as_f64().ok_or("every breakdown cost must be a number")?;
                if !n.is_finite() || n < 0. {
                    finding(format!("a breakdown cost is {n}"));
                }
                sum += n;
            }
            if (sum - total).abs() > 0.011 {
                finding(format!("the breakdown sums to {sum:.2} but the total is {total:.2}"));
            }
        }
    }
    Ok(())
}
fn run(c: &Cli) -> Result<Value> {
    let d = c.project.join("pcbway-flow");
    let mutating = !matches!(c.command, Cmd::Next | Cmd::Compare { .. });
    if mutating && c.ai_thread.as_deref().unwrap_or("").trim().is_empty() {
        return Err("caller_identity_required: pass --ai-thread".into());
    }
    if let Cmd::Init { scope } = &c.command {
        if d.join("state.json").exists() {
            return Err("existing run: use a separate project for new scope".into());
        }
        let v = read(scope)?;
        valid_scope(&v)?;
        let mut inputs = serde_json::Map::new();
        for k in ["board", "bom", "centroid", "gerbers"] {
            inputs.insert(k.into(), file(&v[k])?);
        }
        fs::create_dir_all(&d)?;
        write(
            &d.join("state.json"),
            &json!({"schema":"adom/pcbway-flow@1","scope":v,"inputs":inputs}),
        )?;
    }
    let s = load(&d)?;
    let result = match &c.command {
        Cmd::Show {
            surface,
            page,
            target,
        } => {
            let url = if page == "account" {
                "https://www.pcbway.com/Member/Login/"
            } else {
                "https://www.pcbway.com/quotesmt.aspx"
            };
            let th = c.ai_thread.as_deref().unwrap();
            let output = if surface == "webview" {
                std::process::Command::new("adom-cli")
                    .args([
                        "hydrogen",
                        "webview",
                        "open-or-refresh",
                        "--name",
                        "PCBWay Quote",
                        "--url",
                        url,
                    ])
                    .output()?
            } else {
                let t=target.as_deref().ok_or("Pup requires --target; verify the intended desktop and reuse the task-owned session")?;
                std::process::Command::new("adom-bridge").args(["--target",t,"--ai-thread",th,"pup_open_window",&json!({"window":"aiflow-pcbway","url":url,"reason":"Show the user the PCBWay quotation workflow"}).to_string()]).output()?
            };
            if !output.status.success() {
                return Err(String::from_utf8_lossy(&output.stderr).into_owned().into());
            }
            let reply: Value = serde_json::from_slice(&output.stdout)?;
            if reply["ok"] == false || reply["success"] == false || reply["status"] == "error" {
                return Err(format!("surface failed: {reply}").into());
            }
            json!({"surface":surface,"url":url,"result":reply,"hint":"Verify rendered content. For blocked embedding use Hydrogen External Webview; never silently change to Pup. Leave the vendor result visible at the end."})
        }
        Cmd::Account {
            email,
            status,
            evidence,
        } => {
            if s["scope"]["account"] != email.as_str() {
                finding(format!("the account {email} is not the one the scope names ({}): check it is the account the human meant", s["scope"]["account"]));
            }
            let v = json!({"email":email,"status":status,"evidence":file(&json!(evidence))?});
            write(&d.join("account.json"), &v)?;
            v
        }
        Cmd::Init { .. } | Cmd::Next => json!({"next":step(&d,&s)}),
        Cmd::Export => export(&d, &s)?,
        Cmd::Submitted { receipt } => {
            let p = package(&d, &s)?;
            let mut v = read(receipt)?;
            nonempty(&v, "vendorReference")?;
            nonempty(&v, "submittedAt")?;
            if v["receiptConfirmed"] != true {
                finding("receiptConfirmed is not true: a click is not a receipt; `next` stays at submit until PCBWay confirms it received the RFQ");
            }
            v["evidence"] = file(&v["evidence"])?;
            v["packageDigest"] = json!(digest(&p));
            write(&d.join("submitted.json"), &v)?;
            v
        }
        Cmd::Quote { facts } => {
            let p = package(&d, &s)?;
            let mut v = read(facts)?;
            quote_valid(&v, s["scope"]["quantity"].as_u64().unwrap())?;
            v["evidence"] = file(&v["evidence"])?;
            v["packageDigest"] = json!(digest(&p));
            v["manufacturingApproved"] = json!(false);
            write(&d.join("quote.json"), &v)?;
            v
        }
        Cmd::Blocked { reason, evidence } => {
            if reason.trim().is_empty() {
                return Err("concrete dependency required".into());
            }
            let v = json!({"reason":reason,"evidence":file(&json!(evidence))?,"next":step(&d,&s)});
            write(&d.join("dependency.json"), &v)?;
            v
        }
        Cmd::Compare { baseline } => {
            let p = package(&d, &s)?;
            let q = read(&d.join("quote.json"))?;
            if q["packageDigest"] != digest(&p) || !current(&q["evidence"]) {
                finding("the quote is stale (the package or its evidence changed since it was recorded)");
            }
            let b = read(baseline)?;
            if q["kind"] != "vendor-full" {
                finding(format!("the PCBWay quote is {}, not a full quote: it does not compare like for like with a full JLCPCB assembly price", q["kind"]));
            }
            if q["quantity"] != b["quantity"] || q["currency"] != b["currency"] {
                finding(format!("quantity or currency differ: PCBWay {} {}, baseline {} {}", q["quantity"], q["currency"], b["quantity"], b["currency"]));
            }
            json!({"pcbway":q["totalBeforeShippingTax"],"baseline":b["totalBeforeShippingTax"],"difference":q["totalBeforeShippingTax"].as_f64().unwrap()-b["totalBeforeShippingTax"].as_f64().ok_or("baseline total missing")?,"scopeReviewRequired":true,"pcbwayExclusions":q["exclusions"],"baselineExclusions":b["excludes"]})
        }
        Cmd::Report => {
            let v = json!({"next":step(&d,&s),"scope":s["scope"],"quote":read(&d.join("quote.json")).unwrap_or(Value::Null),"dependency":read(&d.join("dependency.json")).unwrap_or(Value::Null),"manufacturingApproved":false});
            write(&d.join("report.json"), &v)?;
            v
        }
    };
    if mutating {
        let mut f = fs::OpenOptions::new()
            .append(true)
            .create(true)
            .open(d.join("run.jsonl"))?;
        writeln!(
            f,
            "{}",
            json!({"unixSeconds":std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_secs(),"aiThread":c.ai_thread,"command":std::env::args().collect::<Vec<_>>(),"result":result,"findings":findings()})
        )?;
    }
    Ok(result)
}
fn main() {
    let c = Cli::parse();
    match run(&c) {
        Ok(v) => {
            println!("OK: {}", serde_json::to_string_pretty(&v).unwrap());
            let f = findings();
            if !f.is_empty() {
                println!("FINDINGS (suggestions, nothing is blocked):");
                for x in f {
                    println!("  - {x}");
                }
                println!("Suggestion: fix what is real, or tell the human what is open; `next` suggests the step.");
            }
        }
        Err(e) => {
            eprintln!("ERROR (could not run): {e}\nHint: fix the input and run again; `next` suggests what to do.");
            std::process::exit(1)
        }
    }
}
#[cfg(test)]
mod tests {
    use super::*;
    fn q() -> Value {
        json!({"kind":"vendor-full","quantity":5,"currency":"USD","checkedAt":"2026-10-20","vendorReference":"test","scopeNote":"five boards","totalBeforeShippingTax":20.,"includes":{"pcb":true,"components":true,"assembly":true},"breakdown":{"pcb":5.,"parts":10.,"assembly":5.},"exclusions":["shipping","tax"]})
    }
    static SERIAL: std::sync::Mutex<()> = std::sync::Mutex::new(());
    fn found(v: &Value, qty: u64) -> Vec<String> {
        let _one_at_a_time = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); // FINDINGS is process-wide
        FINDINGS.lock().unwrap().clear();
        quote_valid(v, qty).unwrap();
        findings()
    }
    #[test]
    fn full_without_components_is_a_finding_not_a_stop() {
        let mut v = q();
        v["includes"]["components"] = json!(false);
        assert!(found(&v, 5).iter().any(|f| f.contains("components")));
    }
    #[test]
    fn quantity_drift_is_a_finding() {
        assert!(found(&q(), 10).iter().any(|f| f.contains("10")));
    }
    #[test]
    fn a_bad_sum_is_a_finding() {
        let mut v = q();
        v["totalBeforeShippingTax"] = json!(19);
        assert!(found(&v, 5).iter().any(|f| f.contains("sums to")));
    }
    #[test]
    fn full_price_has_no_findings() {
        assert!(found(&q(), 5).is_empty());
    }
    #[test]
    fn an_unreadable_quote_is_still_an_error() {
        let mut v = q();
        v["kind"] = json!("guess");
        assert!(quote_valid(&v, 5).is_err());
    }
    #[test]
    fn ai_flow_export_columns_read_as_they_are() {
        let t = csvio::Table { head: ["Reference", "Qty", "Value", "Footprint", "Manufacturer", "MPN", "DNP"].map(String::from).to_vec(), rows: vec![] };
        assert_eq!((t.col("ref"), t.col("value"), t.col("manufacturer"), t.col("mpn")), (Some(0), Some(2), Some(4), Some(5)));
        let c = csvio::Table { head: ["Ref", "Val", "Package", "PosX", "PosY", "Rot", "Side"].map(String::from).to_vec(), rows: vec![] };
        assert_eq!((c.col("Designator"), c.col("Mid X"), c.col("Mid Y"), c.col("Rotation"), c.col("Layer")), (Some(0), Some(3), Some(4), Some(5), Some(6)));
    }
}