← Commit history

v2.1.9: `request-status` says when a part request is due, and what to do once it is late (Ray, PR #6; adom/adom-parts-search#15). LTST-C19HE1WT sat at queue position 1 for hours while `request-status` kept saying "about a minute".

Colby Knox ·f75beaf703 · ·parent 9f4f709
8 files changed +213−47
Cargo.lock+1−1
@@ -10,7 +10,7 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"  [[package]] name = "adom-parts-search"-version = "2.1.8"+version = "2.1.9" dependencies = [  "base64",  "clap",
Cargo.toml+1−1
@@ -1,6 +1,6 @@ [package] name = "adom-parts-search"-version = "2.1.8"+version = "2.1.9" edition = "2021" description = "Parts Search Electronics component search — CLI, backend HTTP service, and Hydrogen webview app" license = "MIT"
VERSION+1−1
@@ -1 +1 @@-2.1.8+2.1.9
install.sh

  
package.json+1−40
@@ -34,44 +34,5 @@     "SKILL.md",     "BUILD-SKILL.md",     "CHANGELOG.md"-  ],-  "changelog": "`request-status` says when a part request is due, and what to do once it is late (Ray, PR #6; adom/adom-parts-search#15). LTST-C19HE1WT sat at queue position 1 for hours while `request-status` kept saying \"about a minute\".",-  "discovery_triggers": [-    "parts search",-    "find part",-    "source component",-    "source part",-    "compare distributors",-    "compare vendors",-    "Mouser or DigiKey",-    "BOM sourcing",-    "price this part",-    "where can I get",-    "check stock",-    "parts availability",-    "fastest delivery",-    "cheapest part",-    "component search",-    "part lookup",-    "price breaks"-  ],-  "discovery_pitch": "Search Mouser, DigiKey and JLCPCB in parallel with product photos; Mouser-preferred best-source pick. Say 'with parts search' to your AI.",-  "sample_prompts": [-    {-      "label": "source an STM32F103RBT6",-      "prompt": "source an STM32F103RBT6"-    },-    {-      "label": "where can I get an ESP32-S3-WROOM cheape",-      "prompt": "where can I get an ESP32-S3-WROOM cheapest and fastest"-    },-    {-      "label": "compare Mouser, DigiKey and JLCPCB for a",-      "prompt": "compare Mouser, DigiKey and JLCPCB for an LM555"-    },-    {-      "label": "price this BOM across distributors",-      "prompt": "price this BOM across distributors"-    }   ]-}\ No newline at end of file+}
src/cli.rs+185−4
@@ -349,13 +349,194 @@ pub fn run_request(a: crate::RequestArgs) -> Result<(), String> {     Ok(()) } -/// `request-status <id|status link>`: where a request stands (GET /api/part-request/status/<id>).+/// `request-status <id|status link>`: where a request stands (GET /api/part-request/status/<id>), the time it is due,+/// and once that has passed, a Hint that the calling AI may build the part itself (adom/build-a-component-page). pub fn run_request_status(id: &str) -> Result<(), String> {     let id = id.trim_end_matches('/').rsplit('/').next().unwrap_or(id);-    let r = crate::wiki::request_status(id, None)?;+    let mut r = crate::wiki::request_status(id, None)?;     let req = r.get("request").cloned().unwrap_or(serde_json::Value::Null);-    crate::ok(format!("request {}: {}{}", id, req.get("state").and_then(|v| v.as_str()).unwrap_or("?"),-        req.get("public_reason").and_then(|v| v.as_str()).map(|x| format!(" ({})", x)).unwrap_or_default()));+    let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0);+    let due = deadline(&req, now);+    crate::ok(format!("request {}: {}{}{}", id, req.get("state").and_then(|v| v.as_str()).unwrap_or("?"),+        req.get("public_reason").or(req.get("reason")).and_then(|v| v.as_str()).map(|x| format!(" ({})", x)).unwrap_or_default(),+        due.as_ref().map(|d| format!("; {}", d.line())).unwrap_or_default()));+    let mut late_hint = None;+    if let Some(d) = &due {+        // CO's eta_text is not quoted when it contradicts the deadline (a retry hours away, or already late)+        if let Some(t) = d.eta_text.clone() { r["request"]["eta_text"] = serde_json::Value::String(t); }+        r["deadline"] = serde_json::json!({"at": fmt_utc(d.at), "source": d.source, "passed": d.passed});+        if d.passed {+            let slug = page_slug(&req);+            late_hint = Some(late_hint_text(&slug, &fmt_utc(d.at), &crate::wiki::page_state("adom", &slug, None)));+        }+    }     println!("{}", serde_json::to_string_pretty(&r).unwrap_or_default());+    if let Some(h) = late_hint { crate::hint(h); }     Ok(()) }++/// Service limits quoted when Component Ocean gives no retry time (component-factory#3: 20 minutes for an urgent part,+/// an hour for one in review); a `later` request is due within a day.+const LIMIT_NOW_SECS: i64 = 20 * 60;+const LIMIT_REVIEW_SECS: i64 = 60 * 60;+const LIMIT_LATER_SECS: i64 = 24 * 60 * 60;+const SKILL_BUILD_PAGE: &str = "build-a-component-page skill (https://wiki.adom.inc/adom/build-a-component-page)";++#[derive(Debug)]+pub struct Deadline { pub at: i64, pub source: String, pub passed: bool, pub eta_text: Option<String> }++impl Deadline {+    fn line(&self) -> String {+        if self.passed { format!("LATE: was due {} ({})", fmt_utc(self.at), self.source) }+        else { format!("due by {} ({})", fmt_utc(self.at), self.source) }+    }+}++/// When the request is due. Component Ocean's `not_before` (its next retry) plus `eta_seconds` when CO gives one,+/// otherwise `requested_at` plus the service limit. None once the request is built or finished.+pub fn deadline(req: &serde_json::Value, now: i64) -> Option<Deadline> {+    let state = req.get("state").and_then(|v| v.as_str()).unwrap_or("");+    if matches!(state, "built" | "done" | "published" | "public" | "cancelled" | "canceled" | "") { return None; }+    let eta = req.get("eta_seconds").and_then(|v| v.as_i64()).unwrap_or(0).max(0);+    let (at, source) = if let Some(nb) = req.get("not_before").and_then(epoch) {+        (nb + eta, format!("Component Ocean not_before: next retry {}{}", fmt_utc(nb),+            if eta > 0 { format!(", plus its {} s ETA", eta) } else { String::new() }))+    } else if let Some(t0) = req.get("requested_at").and_then(epoch) {+        let (lim, what) = if state == "review" { (LIMIT_REVIEW_SECS, "in review") }+            else if req.get("urgency").and_then(|v| v.as_str()) == Some("later") { (LIMIT_LATER_SECS, "a `later` request") }+            else { (LIMIT_NOW_SECS, "an urgent request") };+        (t0 + lim, format!("service limit: {} min for {} from requested_at", lim / 60, what))+    } else if eta > 0 {+        (now + eta, "Component Ocean eta_seconds".to_string())+    } else { return None; };+    let passed = now > at || matches!(state, "failed" | "error" | "rejected");+    let eta_text = if passed { Some(format!("late: was due {}", fmt_utc(at))) }+        else if at - now > eta + 120 || req.get("not_before").is_some() { Some(format!("due by {}", fmt_utc(at))) }+        else { None };+    Some(Deadline { at, source, passed, eta_text })+}++/// The Hint once the deadline has passed: use a verified page, finish an existing one, or build the part yourself.+pub fn late_hint_text(slug: &str, due: &str, page: &crate::wiki::PageState) -> String {+    use crate::wiki::PageState::*;+    let r = format!("adom/{}", slug);+    match page {+        Exists { verified: true } => format!("The factory is late (due {}), but {} already exists and is verified: use it \+            (https://wiki.adom.inc/{}). Do not build this part yourself and do not overwrite that page.", due, r, r),+        Exists { verified: false } => format!("The factory is late (due {}). {} already exists: finish that page with the {} \+            instead of creating a second one, and keep anything a person edited or verified on it.", due, r, SKILL_BUILD_PAGE),+        Missing | Unknown(_) => format!("The factory is late (due {}). You may build this part yourself with the {}, publishing \+            to {}.{} Never create a duplicate page and never overwrite a page that has a verification record or a person's edit; \+            if the factory finishes later, its build does not replace yours.", due, SKILL_BUILD_PAGE, r,+            if let Unknown(e) = page { format!(" Could not check whether {} exists ({}): check it before you publish.", r, e) }+            else { format!(" {} does not exist yet; check again right before you publish.", r) }),+    }+}++/// The page the request will fill: CO's page_url when set, else the MPN as a wiki slug (LTST-C19HE1WT -> ltst-c19he1wt).+pub fn page_slug(req: &serde_json::Value) -> String {+    if let Some(u) = req.get("page_url").and_then(|v| v.as_str()).filter(|u| !u.is_empty()) {+        return u.trim_end_matches('/').rsplit('/').next().unwrap_or(u).to_string();+    }+    let s: String = req.get("mpn").and_then(|v| v.as_str()).unwrap_or("").to_lowercase().chars()+        .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }).collect();+    s.trim_matches('-').to_string()+}++/// Seconds since the epoch, UTC: "2026-11-26 04:15:13" (CO's form), RFC 3339 with Z or an offset, or a number.+fn epoch(v: &serde_json::Value) -> Option<i64> {+    if let Some(n) = v.as_i64() { return Some(if n > 100_000_000_000 { n / 1000 } else { n }); }+    let s = v.as_str()?.trim();+    if let Ok(n) = s.parse::<i64>() { return epoch(&serde_json::json!(n)); }+    let n = |a: usize, b: usize| s.get(a..b).and_then(|x| x.parse::<i64>().ok());+    let t = days_from_civil(n(0, 4)?, n(5, 7)?, n(8, 10)?) * 86400 + n(11, 13)? * 3600 + n(14, 16)? * 60 + n(17, 19)?;+    let tail = s.get(19..).unwrap_or("").trim_start_matches(|c: char| c == '.' || c.is_ascii_digit());+    let off = match tail.as_bytes().first() {+        Some(b'+') | Some(b'-') => {+            let sign = if tail.starts_with('-') { -1 } else { 1 };+            let h = tail.get(1..3)?.parse::<i64>().ok()?;+            let m = tail.get(4..6).or(tail.get(3..5)).and_then(|x| x.parse::<i64>().ok()).unwrap_or(0);+            sign * (h * 3600 + m * 60)+        }+        _ => 0,+    };+    Some(t - off)+}++fn days_from_civil(y: i64, m: i64, d: i64) -> i64 {+    let y = if m <= 2 { y - 1 } else { y };+    let era = if y >= 0 { y } else { y - 399 } / 400;+    let yoe = y - era * 400;+    let doy = (153 * ((m + 9) % 12) + 2) / 5 + d - 1;+    era * 146097 + yoe * 365 + yoe / 4 - yoe / 100 + doy - 719468+}++pub fn fmt_utc(t: i64) -> String {+    let (days, secs) = (t.div_euclid(86400), t.rem_euclid(86400));+    let z = days + 719468;+    let era = if z >= 0 { z } else { z - 146096 } / 146097;+    let doe = z - era * 146097;+    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;+    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);+    let mp = (5 * doy + 2) / 153;+    let d = doy - (153 * mp + 2) / 5 + 1;+    let m = if mp < 10 { mp + 3 } else { mp - 9 };+    let y = yoe + era * 400 + if m <= 2 { 1 } else { 0 };+    format!("{:04}-{:02}-{:02} {:02}:{:02} UTC", y, m, d, secs / 3600, secs % 3600 / 60)+}++#[cfg(test)]+mod request_status_tests {+    use super::*;+    use crate::wiki::PageState;+    use serde_json::json;++    fn at(s: &str) -> i64 { epoch(&json!(s)).unwrap() }++    #[test]+    fn retry_hours_away_quotes_the_deadline_not_about_a_minute() {+        let now = at("2026-11-26 14:30:00");+        let req = json!({"mpn": "LTST-C19HE1WT", "state": "queued", "position": 1, "eta_seconds": 0,+            "eta_text": "about a minute", "urgency": "now", "requested_at": "2026-11-26 14:25:00",+            "not_before": "2026-11-26T18:00:00Z"});+        let d = deadline(&req, now).unwrap();+        assert_eq!(fmt_utc(d.at), "2026-11-26 18:00 UTC");+        assert!(!d.passed);+        assert!(d.source.contains("not_before"), "{}", d.source);+        assert!(d.line().contains("due by 2026-11-26 18:00 UTC"));+        let t = d.eta_text.unwrap();+        assert!(!t.contains("minute"), "{}", t);+    }++    #[test]+    fn deadline_passed_gives_the_build_it_yourself_hint() {+        // the LTST-C19HE1WT stall: queued at 04:15, eta 0 "about a minute", still there 10 hours later+        let req = json!({"mpn": "LTST-C19HE1WT", "state": "queued", "position": 1, "eta_seconds": 0,+            "eta_text": "about a minute", "urgency": "now", "requested_at": "2026-11-26 04:15:13"});+        let d = deadline(&req, at("2026-11-26 14:30:00")).unwrap();+        assert!(d.passed);+        assert_eq!(fmt_utc(d.at), "2026-11-26 04:35 UTC");+        assert!(d.source.starts_with("service limit"));+        assert!(!d.eta_text.as_deref().unwrap().contains("minute"));+        assert_eq!(page_slug(&req), "ltst-c19he1wt");+        let h = late_hint_text(&page_slug(&req), &fmt_utc(d.at), &PageState::Missing);+        assert!(h.contains("factory is late") && h.contains("build-a-component-page") && h.contains("adom/ltst-c19he1wt"), "{}", h);+        assert!(h.contains("duplicate") && h.contains("verification record"), "{}", h);+        // not yet due: no deadline passed+        assert!(!deadline(&req, at("2026-11-26 04:20:00")).unwrap().passed);+    }++    #[test]+    fn verified_page_exists_hint_says_use_it_do_not_build() {+        let h = late_hint_text("ltst-c19he1wt", "2026-11-26 04:35 UTC", &PageState::Exists { verified: true });+        assert!(h.contains("use it") && h.contains("Do not build") && h.contains("do not overwrite"), "{}", h);+        assert!(!h.contains("build-a-component-page"), "{}", h);+        assert!(crate::wiki::has_verification(&json!({"verification": {"entries": [{"status": "verified"}]}})));+        assert!(!crate::wiki::has_verification(&json!({"verification": {"entries": []}})));+    }++    #[test]+    fn built_request_has_no_deadline() {+        assert!(deadline(&json!({"state": "built", "requested_at": "2026-11-26 04:15:13"}), at("2026-11-27 00:00:00")).is_none());+    }+}
src/wiki.rs+24
@@ -257,6 +257,30 @@ pub fn request_status(id: &str, base: Option<&str>) -> Result<Value, String> {     get(base.unwrap_or(DEFAULT_WIKI), &format!("/api/part-request/status/{}", urlencode(id)), &token(), 20) } +/// Whether adom/<slug> exists and carries a verification record (checked before an AI builds a late part itself).+#[derive(Debug, Clone, PartialEq)]+pub enum PageState { Missing, Exists { verified: bool }, Unknown(String) }++pub fn page_state(owner: &str, slug: &str, base: Option<&str>) -> PageState {+    let base = base.unwrap_or(DEFAULT_WIKI);+    let tok = token();+    match get(base, &format!("/api/pages/{}/{}", owner, slug), &tok, 10) {+        Err(e) if e == "http 404" => PageState::Missing,+        Err(e) => PageState::Unknown(e),+        Ok(_) => {+            let ver = get(base, &format!("/api/pages/{}/{}/verification", owner, slug), &tok, 10).unwrap_or(Value::Null);+            PageState::Exists { verified: has_verification(&ver) }+        }+    }+}++/// A verification record that stands: an entry verified by someone (the parts factory's publish record counts) or current.+pub fn has_verification(ver: &Value) -> bool {+    ver.pointer("/verification/entries").and_then(|v| v.as_array()).map(|a| a.iter().any(|e|+        e.get("status").and_then(|s| s.as_str()) == Some("verified") || e.get("state").and_then(|s| s.as_str()) == Some("current")))+        .unwrap_or(false)+}+ /// What one page carries: CAD from component.parts, component.adom, lifecycle, and its verification state. pub fn hit_from(r: &Value, page: &Value, verification: &Value, base: &str, query: &str) -> WikiHit {     let owner = r.get("owner").and_then(|v| v.as_str()).unwrap_or("");
uninstall.sh