Skip to main content

fats/
cli.rs

1//! CLI: command → action → Out. Pages come from the cache, local files or the fetch router (fetch.rs);
2//! `FATS_OFFLINE=1` keeps every command off the network.
3
4use crate::cache::{Asset, Cache, Cursor, Detached, Done, Entry, HopRow, Meta, NoDoc, Snap, State, jload, now};
5use crate::clean::{Doc, host_of};
6use crate::fetch::{self, Hop, Plan};
7use crate::lang::{
8    At, CARD, Cmd, Flag, GUIDE, Id, Match, Out, WORDS, bang, bin, emit, fix, ksize, mib, parse, short, to_guide,
9};
10use crate::outline::{self, Page, Shown};
11use crate::provider::{self, Ask, Hit, Tier};
12use crate::{search, settings, stats};
13use std::io::Read;
14use std::path::{Path, PathBuf};
15use std::sync::OnceLock;
16use std::time::{Duration, Instant};
17
18/// Input cap per page, raised per command with `max_bytes:` up to the ceiling. Cleaning costs ~15× the input in
19/// memory (a 16 MB page peaked at 239 MB, a 53 MB one at 743 MB), so the default keeps a page near 250 MB
20/// (`fats config` shows both).
21pub const MAX_BYTES: u64 = 16 << 20;
22pub const MAX_BYTES_CEIL: u64 = 64 << 20;
23
24/// The command's input cap (`max_bytes:`, validated by the parser).
25fn cap_of(cmd: &Cmd) -> u64 {
26    cmd.get("max_bytes").and_then(|v| v.parse().ok()).unwrap_or(MAX_BYTES)
27}
28
29/// Directories local files may come from. Unset in the shell (it reads what its user can); `fats mcp` sets
30/// the working directory + the cache, because there the model picks the path.
31pub static FENCE: OnceLock<Vec<PathBuf>> = OnceLock::new();
32
33pub fn fence(dirs: Vec<PathBuf>) {
34    FENCE.set(dirs).ok(); // the first fence holds
35}
36
37/// Outside the fence by its name alone (`..` folded, the disk never read), so under `fats mcp` no answer tells
38/// whether a path out there exists: `/x/y words` searches and `/x/y` is refused either way.
39pub fn outside(path: &Path) -> bool {
40    let Some(dirs) = FENCE.get() else { return false };
41    let mut p = PathBuf::new();
42    for c in std::env::current_dir().unwrap_or_default().join(path).components() {
43        match c {
44            std::path::Component::ParentDir => {
45                p.pop();
46            }
47            c => p.push(c),
48        }
49    }
50    !dirs.iter().any(|d| p.starts_with(d) || d.canonicalize().is_ok_and(|d| p.starts_with(d)))
51}
52
53/// A key or credential file by its bare name, in any directory: a `Words::secret_names` name (`.env.*` = a
54/// prefix) or a secret extension (`Sites::doc_ext` kind `secret`: `.pem`). Never read, stored or searched
55/// (`fenced`: `secret_file`; missing, `no_file`).
56pub fn secret(p: &Path) -> bool {
57    let name = p.file_name().map(|n| n.to_string_lossy().to_lowercase()).unwrap_or_default();
58    let named = |s: &&str| s.strip_suffix('*').map_or(name == *s, |pre| name.starts_with(pre));
59    crate::lang::WORDS.secret_names.iter().any(named) || crate::fetch::doc_kind(&name) == Some("secret")
60}
61
62/// The path a local read opens: the canonical one the fence judged, by name first, then with symlinks resolved
63/// (so a link swapped in after the check never reaches outside: the open never resolves it again). Err = why the
64/// fence refuses it (`not_allowed`), or a key or credential file that exists, by its name or its target's
65/// (`secret_file`, `secret`: never opened); `Ok(Err)` = a path that does not resolve, its error the `no_file`
66/// answer.
67fn fenced(f: &str, path: &Path) -> Result<std::io::Result<PathBuf>, (&'static str, &'static str)> {
68    if f == "-" && FENCE.get().is_some() {
69        return Err(("not_allowed", "stdin carries the MCP protocol"));
70    }
71    let real = path.canonicalize();
72    // symlinks resolved only inside: ./link → /etc/hosts is outside
73    if outside(path) || real.as_ref().is_ok_and(|p| outside(p)) {
74        return Err(("not_allowed", "outside the working directory and the cache"));
75    }
76    if real.as_ref().is_ok_and(|p| secret(p) || secret(path)) {
77        return Err(("secret_file", "a key or credential file is not read · $0"));
78    }
79    Ok(real)
80}
81
82/// The output is JSON Lines: `json`, `json:true` or `FATS_JSON`.
83fn json_of(cmd: &Cmd) -> bool {
84    cmd.has("json") || cmd.flag("json") || settings::get().json.value
85}
86
87/// Run one invocation: (stdout text, exit code, the picture it asked for: `fats mcp` attaches it). Never panics
88/// on user input.
89pub fn run(argv: &[String]) -> (String, i32, Option<String>) {
90    let cmd = parse(argv);
91    if let Some(o) = crate::setup::key_in_argv(&cmd, argv) {
92        return (emit(&o, json_of(&cmd)), o.rc, None);
93    }
94    settings::mods(&cmd.mods);
95    let set = settings::get();
96    let json = json_of(&cmd);
97    let mut c = Cache::open();
98    // a human on a terminal: `fats` alone = the home screen, help = the help screens (the agent's: status, the card)
99    let human = crate::lang::human(json);
100    let screen = || if argv.is_empty() { Some(stats::home(&c)) } else { crate::lang::help_screen(argv) };
101    if let Some(s) = human.then(screen).flatten() {
102        return (s, 0, None);
103    }
104    let mut out = if let Some(q) = &cmd.ask {
105        Out::ask(q)
106    } else if cmd.flag("dry") {
107        plan(&cmd, &c)
108    } else {
109        let t0 = Instant::now();
110        let mut o = dispatch(&cmd, &mut c);
111        o.rec.entry("ms").or_insert((t0.elapsed().as_millis() as u64).into());
112        if let Err(e) = c.save() {
113            o = cache_write(e);
114        }
115        o
116    };
117    if let Some(m) = cmd.count("max") {
118        out.cap(m, &cmd.with_mod("max", Some(&(m * 2).to_string())));
119    }
120    if let Some(i) = cmd.ids.first() {
121        out.rec.entry("id").or_insert(i.page().into());
122    }
123    if let Some(u) = cmd.urls.first().or(cmd.files.first()) {
124        out.rec.entry("url").or_insert(u.as_str().into());
125    }
126    let mut rows = set.rejects.clone();
127    rows.extend(ignored(&cmd));
128    out.warn(rows);
129    let image = out.rec.get("image").and_then(|v| v.as_str()).map(String::from);
130    stats::tally_run(&c.root, &cmd, &out);
131    let tail = footer(&c, &out.lines, !json && FENCE.get().is_none());
132    if let Some(t) = human.then(|| crate::lang::tip(&cmd, &out, is_search(&cmd))).flatten() {
133        return (t, out.rc, image);
134    }
135    (emit(&out, json) + &tail, out.rc, image)
136}
137
138/// The CLI's background line (`show`: never MCP, never `json`): `~ u7 done · u9 pending 12s`, this session's
139/// detached runs not named on the answer's `=` lines (a batch's every input); a finished one once
140/// (`Detached::told`: shown, or named).
141fn footer(c: &Cache, lines: &[String], show: bool) -> String {
142    let named = |n| lines.iter().any(|h| h.starts_with('=') && h.split([' ', '.']).any(|w| w == format!("u{n}")));
143    let (mut over, mut on) = (Vec::new(), Vec::new());
144    for (n, r, alive) in c.runs().into_iter().filter(|r| !r.1.told) {
145        let id = if is_prefetch(&r) { format!("prefetch u{n}") } else { format!("u{n}") };
146        if alive && r.done.is_none() {
147            on.extend((!named(n)).then_some((id, n, r)));
148            continue;
149        }
150        // a failed run says why (its code) and what it cost: its own bill (`provider::charged`), the calls it cut
151        // from its stored copy (`upto`), as `stats` prints them
152        let m: Meta = c.st.u.get(n - 1).and_then(|e| jload(&c.dir(e)?.join("meta.json"))).unwrap_or_default();
153        let fail = |d: Done| format!("failed · {}{}", d.code, provider::spent(" · ", d.cost, m.upto()));
154        let end = r.done.map_or("! abandoned".into(), |d| if d.ok { "done".into() } else { fail(d) });
155        over.extend((!named(n)).then(|| format!("{id} {end}")));
156        if show || named(n) {
157            c.run_tell(n);
158        }
159    }
160    // `prefetch u1, u11 pending 31s · next: …`: one word for a search's runs, after the others; the first run's age
161    // and next move (`ready`): a bare read of a pending id answers at once, `wait:` waits
162    on.sort_by_key(|o| o.0.starts_with("prefetch"));
163    let ids = on.iter().map(|o| o.0.as_str()).collect::<Vec<_>>().join(", ").replace(", prefetch u", ", u");
164    over.extend(
165        on.first().map(|(_, n, r)| format!("{ids} pending {:.0}s · next: {}", now() - r.t, ready(c, *n, r, &[]))),
166    );
167    if over.is_empty() || !show { String::new() } else { format!("~ {}\n", over.join(" · ")) }
168}
169
170/// Every accepted mod is honoured or named here: a `!` row, never silently dropped. Honoured: match, dry, json,
171/// fresh, limit, max, cost, provider, js, country, timeout, wait; site and since by a web search; from by a list.
172/// `more` beside a list (the old hint `u1 links more`) is named too: lists page by `from:K`.
173fn ignored(cmd: &Cmd) -> Vec<String> {
174    let search = is_search(cmd);
175    let lists = WORDS.lists.iter().copied().chain(["media", "comments"]);
176    let (list, at) = (lists.into_iter().find(|w| cmd.has(w)), cmd.ids.first().map(|i| i.page() + " "));
177    let fix = |w| format!("! ignored more · lists page by from:K → {} {}{w} from:K", bin(), at.unwrap_or_default());
178    let more = list.filter(|_| cmd.has("more")).map(fix);
179    let row = |(k, v): &(String, String)| {
180        let (code, why) = match k.as_str() {
181            "verbose" if v == "true" => ("not_in_v1", "no diagnostics in this build"),
182            "fetch" if !search => ("ignored", "only a web search prefetches"),
183            "site" | "since" if !search || is_gh(cmd) => ("ignored", "only a web search uses it"),
184            "country" if is_gh(cmd) => ("ignored", "only a web search or a page fetch uses it"),
185            "zone" if !cmd.has("setup") => ("ignored", "only setup uses it"),
186            "from" if list.is_none() => ("ignored", "only a links, cards, media or comments list pages"),
187            _ => return None,
188        };
189        // the arrow only to a command that does something without the mod (`fats u1`, never a bare `fats open`)
190        let rest = Some(cmd.with_mod(k, None)).filter(|r| !parse(std::slice::from_ref(r)).idle);
191        Some(format!("! {code} {k}:{v} · {why}{}", rest.map_or(String::new(), |r| format!(" → {} {r}", bin()))))
192    };
193    cmd.mods.iter().filter_map(row).chain(more).collect()
194}
195
196/// Free words (or `site:` alone) without a page id, a local file or a page URL: a web search (`fats <words>`,
197/// `fats <host> <words>`, `fats site:x.com/news since:1d`).
198pub fn is_search(cmd: &Cmd) -> bool {
199    let any = !cmd.words.is_empty() || cmd.get("site").is_some();
200    any && cmd.ids.is_empty() && cmd.files.is_empty() && page_url(cmd).is_none()
201}
202
203/// `fats gh <words>`: a GitHub repository search (`github`), not a web search.
204pub fn is_gh(cmd: &Cmd) -> bool {
205    cmd.words.len() > 1 && cmd.words[0] == "gh" && cmd.urls.is_empty()
206}
207
208/// The one URL of the command when it names a page (a path past the host, or a query); a bare host is a site.
209fn page_url(cmd: &Cmd) -> Option<&str> {
210    let page = |u: &&String| url::Url::parse(u).is_ok_and(|p| p.path() != "/" || p.query().is_some());
211    cmd.urls.first().filter(page).filter(|_| cmd.urls.len() == 1).map(String::as_str)
212}
213
214/// One search as the command asks for it.
215struct Search {
216    /// The query sent: `site:` first, the `since:` hint last.
217    q: String,
218    /// The host of `site:`: results off it are dropped (the engine may ignore `site:` on common words).
219    site: Option<String>,
220    limit: usize,
221    country: Option<String>,
222    /// `fats gh <words>`: GitHub, not the web (`q` = the words after `gh`, up to `GH_MAX` results).
223    gh: bool,
224    /// The router's plan: oxy, bd beside it after the hedge; `provider:` `cost:` `timeout:` `hedge:`.
225    plan: Plan,
226}
227
228/// The command → a search, or the `?` line. `site:` (or the host of `fats <host> <words>`) goes in front of the
229/// words; `since:` becomes `after:YYYY-MM-DD` at the end: neither provider has a date parameter (Oxylabs
230/// `/v1/search` takes query, max_results, location only), so it is a hint to the engine, not a filter.
231fn search_of(cmd: &Cmd) -> Result<Search, Out> {
232    let b = bin();
233    if let Some(l) = cmd.links.first() {
234        return Err(Out::ask(&format!("? l{l} needs a page: {b} u1 l{l} · search: {b} {}", cmd.words.join(" "))));
235    }
236    if cmd.urls.len() > 1 {
237        let (site, words) = (short(&cmd.urls[0], 60), cmd.words.join(" "));
238        return Err(Out::ask(&format!("? one site per search: {b} {site} {words}")));
239    }
240    let gh = is_gh(cmd);
241    let site =
242        cmd.get("site").map(String::from).or(cmd.urls.first().map(|u| short(u, 2048).trim_end_matches('/').into()));
243    let site = site.filter(|_| !gh);
244    let after = cmd.get("since").filter(|_| !gh).and_then(|v| crate::lang::since_date(v, (now() / 86_400.0) as i64));
245    let words = cmd.words[usize::from(gh)..].iter().cloned();
246    let q = site.iter().map(|s| format!("site:{s}")).chain(words).chain(after.map(|d| format!("after:{d}")));
247    let q = q.collect::<Vec<_>>().join(" ");
248    // the redactor masks what is printed; a key in the words would still be sent to the provider
249    if crate::lang::redact(&q, &settings::secrets()) != q {
250        let what = "search · the words hold a configured key · not sent · $0";
251        return Err(refused("key_in_query", "", what, &At::default()));
252    }
253    if q.chars().count() > 2048 {
254        return Err(Out::ask(&format!("? query is {} chars · a search takes 2048 at most", q.chars().count())));
255    }
256    if let Some(p) = cmd.get("provider").filter(|p| !gh && !matches!(*p, "oxy" | "bd" | "auto")) {
257        return Err(Out::ask(&format!("? provider:{p} cannot search · provider:oxy|bd|auto")));
258    }
259    let max = if gh { settings::limit("gh_max") } else { provider::SEARCH_MAX };
260    let (p, asked) = (plan_of(cmd, None), wait_of(cmd));
261    // a lead slower than `wait:` runs detached (`searching`): no `wait:`, one call (`one_call`), so `dry` routes that
262    let wait = Some(p.search_wait(asked)).filter(|w| *w <= asked);
263    Ok(Search {
264        q,
265        site: site.map(|s| s.split('/').next().unwrap_or_default().to_ascii_lowercase()),
266        limit: cmd.count("limit").unwrap_or(10).min(max),
267        country: cmd.get("country").filter(|_| !gh).map(str::to_uppercase),
268        gh,
269        plan: Plan { wait, ..p },
270    })
271}
272
273/// `fats <words>`: one web search. Each result becomes an id holding its URL and no body; `fats u7` fetches it
274/// through the tiers into the same id. Oxylabs first, Bright Data when Oxylabs has no key or fails. The search
275/// record (provider, ms, cost, hits) is stored as `j<N>` for `stats`, health and `more`.
276fn web(cmd: &Cmd, c: &mut Cache) -> Result<Out, Out> {
277    let s = search_of(cmd)?;
278    let what = format!("search \"{}\"", s.q);
279    if settings::get().offline.value {
280        return Ok(offline(&what));
281    }
282    let t0 = Instant::now();
283    if s.gh {
284        return github(cmd, c, &s, t0);
285    }
286    // a search past `wait:` detaches; the detached run (`resume` named its job) is that one call, run to its end
287    if s.plan.wait.is_none() && c.job.is_none() {
288        return searching(c, cmd);
289    }
290    let mut run = fetch::run_search(&s.plan, &s.q, s.limit, s.country.as_deref());
291    let mut found = run.iter_mut().find(|h| h.ok).map(|h| (h.tier, std::mem::take(&mut h.hits)));
292    let mut rows = match (&mut found, &s.site) {
293        (None, _) => fetch::skipped(&s.plan, &run, "", &cmd.canon(), ""),
294        (Some((_, hits)), Some(host)) => on_site(hits, host),
295        _ => Vec::new(),
296    };
297    // no arrow: the rows shown are all a search returns; `limit:20` would only buy them again
298    if s.limit < cmd.count("limit").unwrap_or(0) {
299        rows.push(format!("! ignored limit · a search returns {} at most", s.limit));
300    }
301    if run.is_empty() {
302        return Ok(nothing_searched(&s, &what, rows));
303    }
304    let job = c.job_of(&cmd.raw).map_err(cache_write)?;
305    let served = found.as_ref().map_or("", |f| f.0.spec().name);
306    let meta = search_meta(&s, run.iter().map(Hop::row).collect(), served, t0);
307    let o = match found {
308        Some((_, hits)) => listed(c, job, meta, &hits)?,
309        // every provider failed: the record is kept (`j<N>`, the error answers in `error.txt`), then its row
310        None => c
311            .serp_put(job, &meta, fetch::error_text(&run).as_deref())
312            .map_err(cache_write)
313            .and_then(|()| search_out(c, cmd, job, &meta))?,
314    };
315    let mut o = prefetched(c, cmd, job, o);
316    o.warn(rows);
317    Ok(o)
318}
319
320/// A detached search's patience (`resume`): twice the search timeout (one call at the retry's time).
321const PATIENCE: Duration = provider::SEARCH_TIMEOUT.saturating_mul(2);
322
323/// A search whose lead provider answers slower than `wait:` (`Plan::search_wait`, bd) runs detached like a fetch
324/// : `fats --continue j<J>` searches with that patience and keeps the record `j<J>`; this call answers by
325/// `wait:` (from the command's start, `Cache::born`, as `wait_for`) with the list, the failure, or `pending` →
326/// `fats j<J>` (the list once stored, $0 more).
327fn searching(c: &mut Cache, cmd: &Cmd) -> Result<Out, Out> {
328    let job = c.job_of(&cmd.raw).map_err(cache_write)?;
329    detach(format!("j{job}"), &c.root.join(&c.session).join(format!("run/j{job}.log")), None).map_err(cache_write)?;
330    poll_until(c.born, wait_of(cmd), || c.serp(job).is_some(), || "search running".into());
331    match c.serp(job) {
332        Some(m) if m.ok => Ok(serp_list(c, job, 0, true)),
333        Some(m) => search_out(c, cmd, job, &m),
334        None => Ok(search_pending(c, job).unwrap_or_default()),
335    }
336}
337
338/// A search job not stored yet and younger than its detached patience (`resume`): `pending` → `fats j<J> wait:30`.
339fn search_pending(c: &Cache, job: usize) -> Option<Out> {
340    let j = c.job(job)?;
341    let q = Some(parse(std::slice::from_ref(&j.cmd))).filter(is_search).and_then(|cmd| search_of(&cmd).ok())?.q;
342    let age = (now() - j.t).max(0.0);
343    let row = format!("= j{job} pending {age:.0}s search \"{q}\" → {}", poll_next(&format!("j{job}"), 0));
344    (c.serp(job).is_none() && age < PATIENCE.as_secs_f64()).then(|| waiting(row, format!("j{job}")))
345}
346
347/// `fats gh <words>`: GitHub repositories by stars (`provider::gh_repos`), listed and opened like web results
348/// (each through the ladder), prefetched the same way. Free; the record `j<N>` holds a `gh` hop a call.
349fn github(cmd: &Cmd, c: &mut Cache, s: &Search, t0: Instant) -> Result<Out, Out> {
350    let wait = wait_of(cmd);
351    let got = provider::all_within(vec![provider::gh_repos(s.q.clone(), s.limit)], wait).pop().flatten();
352    let got = got.unwrap_or_else(|| Err(provider::late(wait)));
353    let job = c.job_of(&cmd.raw).map_err(cache_write)?;
354    // one hop a call: the search, and the account call beside it, so `stats` counts both
355    let calls = got.as_ref().map_or_else(|f| vec![(f.code, f.why.clone())], |(_, calls)| calls.clone());
356    let gh = HopRow { provider: "gh".into(), ms: t0.elapsed().as_millis() as u64, ..Default::default() };
357    let hops = calls.into_iter().map(|(code, why)| HopRow { code: code.into(), why, ..gh.clone() });
358    let meta = search_meta(s, hops.collect(), if got.is_ok() { "github" } else { "" }, t0);
359    let fail = match got {
360        Ok((hits, _)) => return listed(c, job, meta, &hits).map(|o| prefetched(c, cmd, job, o)),
361        Err(fail) => fail,
362    };
363    c.serp_put(job, &meta, Some(&fail.body)).map_err(cache_write)?;
364    search_out(c, cmd, job, &meta).and_then(Err) // one answer, now and on `fats jN`
365}
366
367/// `fetch:N` (default 1): search `job`'s top N results not fetched yet start fetching detached into their own ids,
368/// so `fats u1` a moment later is usually a cache hit. Free: plain only (`Plan::prefetch`), so `cost:` never
369/// stops one. A `prefetching u1 u2 free, plain only` row above the list's last line names the ids started.
370fn prefetched(c: &mut Cache, cmd: &Cmd, job: usize, mut o: Out) -> Out {
371    let open =
372        |(i, e): (usize, &Entry)| (e.job == Some(job) && e.serp && e.dir.is_empty()).then(|| (i + 1, e.url.clone()));
373    let top: Vec<(usize, String)> = c.st.u.iter().enumerate().filter_map(open).take(prefetch_n(cmd)).collect();
374    let mut queued = Vec::new();
375    for (n, url) in &top {
376        // a stored page opens on demand (no alias id); a running one, a private host, offline: `at_once` says no
377        let want = Want { url, slot: Some(*n), ..Want::default() };
378        let free = c.lookup(url).is_none() && at_once(c, want, cmd).is_none();
379        queued.extend(free.then(|| reserve(c, Entry::default(), want, cmd).ok()).flatten().map(|n| (n, want)));
380    }
381    // THE placement a batch's runs get: `fetch:20` starts 4 processes, not 20
382    let ids: Vec<String> = queued.iter().map(|q| format!("u{}", q.0)).collect();
383    if !ids.is_empty() && launch(c, &queued, cmd).is_ok() {
384        let row =
385            format!("prefetching {} free, plain only (detached; fetch:0 = none) · status: {}", ids.join(" "), bin());
386        o.lines.insert(o.lines.len() - 1, row);
387        o.set("prefetch", ids);
388    }
389    o
390}
391
392/// How many results a search fetches detached (`fetch:N`).
393pub const PREFETCH: usize = 1;
394
395/// `fetch:N`, none while the free fetch is off: a prefetch is plain only (`Plan::prefetch`), so it would only store
396/// a failure, never a page.
397fn prefetch_n(cmd: &Cmd) -> usize {
398    let n = cmd.get("fetch").and_then(|v| v.parse().ok()).unwrap_or(PREFETCH);
399    if Tier::Plain.key().is_some() { n } else { 0 }
400}
401
402/// Drop the hits off `host` (not it, not under it): Google may ignore `site:` when the words are common (5 of 10
403/// off-site, live 2026-10-13). The `! dropped` row, or none.
404fn on_site(hits: &mut Vec<Hit>, host: &str) -> Vec<String> {
405    let n = hits.len();
406    // `.docs.ex.com` ends with `.ex.com`: the host or a subdomain of it
407    hits.retain(|h| format!(".{}", host_of(&h.url)).ends_with(&format!(".{host}")));
408    let gone = n - hits.len();
409    (gone > 0).then(|| format!("! dropped {gone} off-site · not on {host}")).into_iter().collect()
410}
411
412/// A detached run a search's `fetch:N` started (its command is the search), not a page command.
413fn is_prefetch(r: &Detached) -> bool {
414    is_search(&parse(std::slice::from_ref(&r.cmd)))
415}
416
417/// No search provider could run (no key, or the cost cap): the first skipped row is the cause; none (cannot
418/// happen today) = the code's own fix.
419fn nothing_searched(s: &Search, what: &str, mut rows: Vec<String>) -> Out {
420    let code = if s.plan.keys.is_empty() { "no_key" } else { "budget_hit" };
421    let eq = format!("= ! {code} {what} · no search provider can run · 0ms");
422    let first = if rows.is_empty() { bang("", code, "", &At::default()) } else { rows.remove(0) };
423    let mut o = Out::fail(code, eq, first);
424    o.warn(rows);
425    o
426}
427
428/// A search's record (`j<N>/meta.json`): who served it (`served`, "" = every provider failed), its hops, their
429/// cost. A web search's hops are its tiers' (`Hop::row`); `fats gh` has a `gh` hop a call (search, account).
430fn search_meta(s: &Search, hops: Vec<HopRow>, served: &str, t0: Instant) -> Meta {
431    Meta {
432        url: format!("search:{}", s.q),
433        provider: served.into(),
434        ms: t0.elapsed().as_millis() as u64,
435        cost: provider::spend(hops.iter().map(|h| h.cost)),
436        ok: !served.is_empty(),
437        code: hops.last().map(|h| h.code.clone()).unwrap_or_default(),
438        t: now(),
439        kind: "serp".into(),
440        hops,
441        country: s.country.clone().unwrap_or_default(),
442        ..Default::default()
443    }
444}
445
446/// A failed search's answer from its record.
447fn search_out(c: &Cache, cmd: &Cmd, job: usize, m: &Meta) -> Result<Out, Out> {
448    let q = m.url.strip_prefix("search:").unwrap_or(&m.url);
449    let detail = format!("· tried {} · {}ms{}", m.tried(), m.ms, provider::spent(" ", m.cost, m.upto()));
450    // a slow provider gets more time (cut at `wait:`, or past its own timeout), never a time its call already had
451    // (a detached bd search ran 30 s, `one_call`); `fresh:true` changes nothing
452    let last = m.hops.last();
453    let arg = match m.code.as_str() {
454        "provider_timeout" if last.is_some_and(|h| h.why.starts_with("wait:")) => "wait:30",
455        "provider_timeout" if last.is_some_and(|h| h.ms < 30_000) => "timeout:30",
456        _ => "",
457    };
458    let (id, done) = (cmd.canon(), fetch::spent(m, &[], &fetch::keyed()));
459    let at = At { id: &id, arg, done: &done, ..At::default() };
460    let (who, owners) = fetch::fail_detail(m, "");
461    // The same failure on this query again = a count, never the call that failed twice
462    let n = fetch::fail_count(m, c.serps().iter().filter(|s| s.0 != job).map(|s| &s.1), Some(arg));
463    let next = if n.is_some() { String::new() } else { fix(&m.code, &at) };
464    let what = format!("{who}{}", n.unwrap_or_default()).trim_start().into();
465    let row = Flag { code: m.code.clone(), what, next, row: true }.bang("") + &provider::pages(&m.code, owners);
466    Ok(Out::fail(&m.code, format!("= ! {} j{job} search \"{q}\" {detail}", m.code), row))
467}
468
469/// A search's hits → one unfetched id each (url, no body) + the record `j<job>` → the first page of the list.
470fn listed(c: &mut Cache, job: usize, mut m: Meta, hits: &[Hit]) -> Result<Out, Out> {
471    let es: Vec<Entry> =
472        hits.iter().map(|h| Entry { url: h.url.clone(), job: Some(job), serp: true, ..Entry::default() }).collect();
473    let first = c.alloc(es, None).map_err(cache_write)?;
474    m.extra.insert("first".into(), first.into());
475    m.extra.insert("hits".into(), serde_json::to_value(hits).unwrap_or_default());
476    c.serp_put(job, &m, None).map_err(cache_write)?;
477    Ok(serp_list(c, job, 0, true))
478}
479
480/// A fresh search's part of its `=` line: provider, country, the tiers tried before it, its time and bill.
481fn searched(rec: &Meta) -> String {
482    let cc = if rec.country.is_empty() { String::new() } else { format!(" {}", rec.country) };
483    // gh's two calls run side by side, never one `after` the other: the account call's note (`github`), and
484    // GitHub's limit without a token, said here, never in the record's `provider`
485    let gh = rec.provider == "github";
486    let tried = if rec.hops.len() > 1 && !gh { format!(" after {}", rec.tried()) } else { String::new() };
487    let mut note: String = rec.hops.iter().filter(|h| gh && h.code != "ok").map(|h| h.why.as_str()).collect();
488    note += if gh && settings::key("gh").is_none() { " · no token: 10 searches/min" } else { "" };
489    let usd = provider::spent(" · ", rec.cost, rec.upto());
490    format!("{}{cc}{tried}{note} · {:.1}s{usd}", rec.provider, rec.ms as f64 / 1e3)
491}
492
493/// Search `job`'s results from hit `off`, up to the read cap; the cursor remembers where `more` goes on. `new` =
494/// this command ran the search (its cost and time on the `=` line), else the record's age.
495fn serp_list(c: &mut Cache, job: usize, off: usize, new: bool) -> Out {
496    let b = bin();
497    let Some(rec) = c.serp(job) else { return Out::ask(&format!("? j{job} has no search record · {b} <words>")) };
498    let hits: Vec<Hit> = rec.extra.get("hits").and_then(|v| serde_json::from_value(v.clone()).ok()).unwrap_or_default();
499    let first = rec.extra.get("first").and_then(|v| v.as_u64()).unwrap_or(1) as usize;
500    let query = rec.url.strip_prefix("search:").unwrap_or(&rec.url);
501    let (mut parts, mut rows) = (Vec::new(), Vec::new());
502    for (i, hit) in hits.iter().enumerate().skip(off) {
503        let n = first + i;
504        let snip = if hit.snippet.is_empty() { String::new() } else { format!(" — \"{}\"", short(&hit.snippet, 90)) };
505        let row = match rec.provider.as_str() {
506            // `★12.4k owner/repo · description · pushed 2026-10-01`: the title names the repo, the URL adds nothing
507            "github" => format!("u{n}  {} · {}", hit.title, hit.snippet),
508            _ => format!("u{n}  {}  {}{snip}", short(&hit.url, 40), short(&hit.title, 60)),
509        };
510        // a URL already in the cache opens from it (`cached`); a failed plain-only prefetch says nothing of the paid
511        // tiers, so its row names no render (`fats uN` walks the whole ladder, `dispatch_one`)
512        let row = if c.lookup(&hit.url).is_some() { format!("{row} · cached $0") } else { row };
513        let billed = new && i == off;
514        let mut part = Out::new(vec![row.clone()]);
515        part.set("i", i).set("id", format!("u{n}")).set("url", hit.url.clone()).set("cache", !new);
516        part.set("title", hit.title.clone()).set("snippet", hit.snippet.clone()).set("position", i + 1);
517        part.set("query", query).set("job", format!("j{job}")).set("provider", rec.provider.clone());
518        part.set("cost", if billed { rec.cost } else { 0.0 }).set("ms", if billed { rec.ms } else { 0 });
519        parts.push(part);
520        rows.push(row);
521    }
522    // every row within a read's token cap (`more` goes on), a search's own `limit:N` at most N of them (20 at most).
523    // A cut by tokens under `limit:` says so: `14 shown u1-u14 of limit:20 (1000 tok cap)`
524    let n = c.job(job).and_then(|j| parse(&[j.cmd]).count("limit")).map(|n| n.min(provider::SEARCH_MAX));
525    let (mut lines, cap) = (Vec::new(), settings::limit::<usize>("read_cap"));
526    let next = off + outline::cap_rows(&mut lines, &rows, 0, (cap, 1, n));
527    let cut = n.filter(|&n| lines.len() < n && next < hits.len());
528    let cut = cut.map_or(String::new(), |n| format!(" of limit:{n} ({cap} tok cap)"));
529    let total = hits.len();
530    let how = if new { searched(&rec) } else { format!("cache {}", outline::fmt_age((now() - rec.t).max(0.0))) };
531    let shown = match (off, lines.len()) {
532        (0, count) if count == total => String::new(),
533        (_, 0) => " · all shown".into(),
534        // the rows this answer printed, counted: `5 results` above 4 rows read as one lost (docs-3)
535        (_, count) => format!(" · {count} shown u{}-u{}{cut}", first + off, first + off + count - 1),
536    };
537    let mut head = vec![format!("= j{job} search \"{query}\" · {total} results{shown} · {how}")];
538    head.append(&mut lines);
539    let at = first + off.min(total.saturating_sub(1));
540    head.push(match (total, next < total) {
541        (0, _) if query.starts_with("site:") => format!("no on-site results · try without site: → {b} <words>"),
542        (0, _) => format!("no results · fewer words: {b} <words>"),
543        (_, true) => format!("open one: {b} u{at} · filter: {b} u{at} <words> · more: {b} more"),
544        (_, false) => format!("open one: {b} u{at} · filter: {b} u{at} <words>"),
545    });
546    if total > 0 {
547        c.st.cursor = Some(Cursor { u: at, serp: Some((job, next)), ..Cursor::default() });
548    }
549    let mut o = Out::new(head);
550    o.set("id", format!("j{job}")).set("provider", rec.provider.clone()).set("query", query).set("results", total);
551    o.set("cost", if new { rec.cost } else { 0.0 }).set("ms", if new { rec.ms } else { 0 }).set("cache", !new);
552    o.parts = parts;
553    o
554}
555
556/// `dry:true` of a search: the providers in order, the ids it would add, the most it can cost.
557fn search_dry(cmd: &Cmd, c: &Cache) -> Result<Out, Out> {
558    let search = search_of(cmd)?;
559    let (runs, max) = fetch::route(&search.plan);
560    let cc = search.country.as_ref().map(|cc| format!(" · country:{cc}")).unwrap_or_default();
561    let off = settings::get().offline.value;
562    let (q, lim, nokey) = (&search.q, search.limit, nokey_row(&search.plan));
563    let (via, wait) = (path_of(&runs), wait_of(cmd).as_secs());
564    let new = format!("new u{}-u{}", c.st.u.len() + 1, c.st.u.len() + lim);
565    let line = match (runs.is_empty(), off) {
566        (_, true) => format!("search \"{q}\" · $0 · ! offline → {}", fix("offline", &At::default())),
567        _ if search.gh => format!("search github \"{q}\" by stars · limit:{lim} → {new} · $0"),
568        (true, _) => format!("search \"{q}\" · nothing can search · $0{nokey}"),
569        _ => format!("search \"{q}\" via {via} · limit:{lim}{cc} · wait:{wait}s → {new} · up to ${max:.4}{nokey}"),
570    };
571    let n = prefetch_n(cmd).min(search.limit);
572    let pre = format!("then fetch:{n} prefetches the top {n} detached · free, plain only");
573    let mut o = Out::new(vec![
574        format!("= dry {} · spends nothing now", cmd.canon()),
575        line,
576        fetch::hedges(cmd.get("hedge")),
577        format!("run it: {} {}", bin(), cmd.with_mod("dry", None)),
578    ]);
579    if n > 0 && !runs.is_empty() && !off {
580        o.lines.insert(2, pre);
581    }
582    o.set("cost", 0.0).set("dry", true);
583    Ok(o)
584}
585
586/// ` · ! no_key oxy · would try … → fats setup oxy` for the plan's tiers without a key (`fetch::no_key`)
587/// while no paid tier has one, else for the provider `provider:` names only (a failed run names the rest).
588fn nokey_row(p: &Plan) -> String {
589    let paid = p.keys.iter().any(|t| *t != Tier::Plain);
590    let asked = |t: &Tier| matches!(p.mode, fetch::Mode::Only(o) if o.owner() == t.owner());
591    let left: Vec<Tier> = p.ladder(&[]).into_iter().filter(|t| !paid || asked(t)).collect();
592    fetch::no_key(p, &left, "", false).iter().map(|r| format!(" · {r}")).collect()
593}
594
595/// The router plan for one URL (None = the command's web search) from the command's mods.
596fn plan_of(cmd: &Cmd, url: Option<&str>) -> Plan {
597    let mut p = Plan::of(cmd, url);
598    p.prefetch = url.is_some() && is_search(cmd);
599    if settings::get().offline.value {
600        p.keys.clear();
601    }
602    p
603}
604
605/// A route as `dry:true` prints it: `plain → bd ∥ oxyjs after 5s`, a tier's second rung `bd retry`. A race
606/// (two providers' renders) keeps the no-JS rung after plain only after its captcha: `→ oxy (after a captcha)`
607/// (`fetch::route` simulates that wall, so the `up to` holds it).
608pub fn path_of(route: &[(Tier, Option<Duration>)]) -> String {
609    let gate = route.iter().any(|r| r.1.is_some()) && route.first().is_some_and(|r| r.0 == Tier::Plain);
610    let step = |(i, (t, hedge)): (usize, &(Tier, Option<Duration>))| match (i, hedge) {
611        (0, _) => t.spec().short.to_string(),
612        (_, Some(d)) => format!(" ∥ {} after {}s", t.spec().short, d.as_secs_f64()),
613        (_, None) if route[..i].iter().any(|r| r.0 == *t) => format!(" → {} retry", t.spec().short),
614        // a paid no-JS rung before a hedged render runs after plain's captcha only (`Plan::ladder`)
615        (_, None) => format!(" → {}{}", t.spec().short, if !t.can("js") && gate { " (after a captcha)" } else { "" }),
616    };
617    route.iter().enumerate().map(step).collect()
618}
619
620/// `dry:true`: what the command would read, add and spend; writes and spends nothing.
621pub fn plan(cmd: &Cmd, c: &Cache) -> Out {
622    if cmd.has("account") {
623        return stats::account_dry(c, cmd.flag("fresh"));
624    }
625    if let Some(out) = setup_move(cmd, true) {
626        return out;
627    }
628    if is_search(cmd) {
629        return merged(search_dry(cmd, c));
630    }
631    let mut dry = Dry { cmd, c, next: c.st.u.len(), refused: 0, total: 0.0 };
632    let mut lines = vec![format!("= dry {} · spends nothing now", cmd.canon())];
633    // a file: the run's own verdict on its path (`fenced`), refused or missing as the run would say, else its size
634    for f in &cmd.files {
635        let size = match fenced(f, &crate::lang::local_path(f)) {
636            Err((code, _)) => Err(code),
637            Ok(_) if f == "-" => Ok(0),
638            Ok(real) => real.and_then(std::fs::metadata).map(|m| m.len()).map_err(|_| "no_file"),
639        };
640        dry.refused += usize::from(size.is_err());
641        lines.push(match size {
642            Ok(n) => format!("{f} {}B local → clean → outline → {} · $0", ksize(n as usize), dry.to(None)),
643            Err(code) => format!("! {code} {f} · $0"),
644        });
645    }
646    for (i, u) in cmd.urls.iter().enumerate() {
647        // a URL named twice: one run, as `fetch_all` runs it
648        let twice = cmd.urls[..i].contains(u).then(|| format!("{} (same as above) · $0", short(u, 60)));
649        lines.push(twice.unwrap_or_else(|| dry.would(&short(u, 60), u, None)));
650    }
651    // a batch's runs share one `cost:` pool (`fetch::pooled`): its rows' total against it
652    if cmd.urls.len() > 1 {
653        let cap = plan_of(cmd, None).cap;
654        lines.push(format!("batch up to ${:.4} · cap ${cap:.4}", dry.total.min(cap)));
655    }
656    let cur = c.st.cursor.clone().unwrap_or_default();
657    let ids = match (&cmd.ids[..], cur.u) {
658        ([], u) if u > 0 && cmd.urls.is_empty() && cmd.files.is_empty() => vec![Id { u, ..Id::default() }],
659        (ids, _) => ids.to_vec(),
660    };
661    // an id this session does not hold: the run's own `?`, rc 2
662    if let Some(id) = ids.iter().find(|i| load(c, i).is_none()) {
663        return unknown(c, id);
664    }
665    for id in &ids {
666        lines.push(dry.id_row(id));
667    }
668    // every row refused: there is nothing to run, and the plan is a failure
669    let none = dry.refused > 0 && dry.refused == lines.len() - 1;
670    if !none {
671        lines.push(fetch::hedges(cmd.get("hedge")));
672        lines.push(format!("run it: {} {}", bin(), cmd.with_mod("dry", None)));
673    }
674    let mut o = Out::new(lines);
675    o.rc = i32::from(none);
676    o.set("cost", 0.0).set("dry", true);
677    o
678}
679
680/// One `dry:true` run: the rows it prints come from here.
681struct Dry<'a> {
682    cmd: &'a Cmd,
683    c: &'a Cache,
684    /// The u number the last new id took.
685    next: usize,
686    /// Rows the fence refuses: nothing would run for them.
687    refused: usize,
688    /// The `up to` of every fetch row.
689    total: f64,
690}
691
692impl Dry<'_> {
693    /// The id a fetch would store into: the unfetched search result `slot`, else a new one.
694    fn to(&mut self, slot: Option<usize>) -> String {
695        self.next += usize::from(slot.is_none());
696        slot.map_or_else(|| format!("new u{}", self.next), |n| format!("fills u{n}"))
697    }
698
699    /// What a fetch of `u` would do: a cache hit, a refusal, or the route it would take and its worst cost.
700    fn would(&mut self, what: &str, u: &str, slot: Option<usize>) -> String {
701        if let Some(n) = render_of(self.c, u, self.cmd) {
702            return format!("{what} = u{n} (rendered, cache) · $0");
703        }
704        if let Some((_, age)) = self.c.lookup(u).filter(|_| !self.cmd.fresh()) {
705            return format!("{what} cache hit, cache {} → {} · $0", outline::fmt_age(age), self.to(slot));
706        }
707        // the run already fetching it is waited for (`id_of`), never a second one
708        if let Some(n) = running(self.c, u) {
709            return format!("{what} = u{n} (running) · waits up to {}s for it · $0", wait_of(self.cmd).as_secs());
710        }
711        if provider::private_host(u) {
712            self.refused += 1;
713            return format!("{what} ! private_address → {}", fix("private_address", &At { url: u, ..At::default() }));
714        }
715        let mut p = plan_of(self.cmd, Some(u));
716        fetch::route_of(self.c, u, &mut p);
717        let (tiers, cost) = fetch::route(&p);
718        if settings::get().offline.value {
719            return format!("{what} not cached → ! offline (FATS_OFFLINE) · $0");
720        }
721        // dry spends nothing, the network included: the host by its name alone, never a lookup (`lang::real_host`:
722        // no real TLD = `no_host`; a private literal or `localhost` was refused above); a lookup's verdicts
723        // (`dns_timeout`, `dns_failed`, a name with a private address) are the real run's (`provider::host_check`)
724        if !crate::lang::real_host(u) {
725            self.refused += 1;
726            // the run stores its failure in an id all the same
727            let (host, to, id) = (host_of(u), fix("no_host", &At { id: u, url: u, ..At::default() }), self.to(slot));
728            return format!("{what} ! no_host {host} · {id} · $0 → {to}");
729        }
730        let nokey = nokey_row(&p);
731        if tiers.is_empty() {
732            // js:true or provider: left only tiers without a key
733            return format!("{what} not cached · nothing can fetch it · {} · $0{nokey}", self.to(slot));
734        }
735        let to = self.to(slot);
736        let mods = dry_mods(self.cmd, u, &tiers);
737        // a paid ask runs one provider at a time (`Plan::hedged`)
738        let off = if p.hedged() { "" } else { " · hedge:off, one provider at a time" };
739        let quote = if p.js { format!(" · {}", fetch::JS_QUOTE) } else { String::new() };
740        self.total += cost;
741        format!("{what} fetch {} → {to} · up to ${cost:.4}{quote}{off}{mods}{nokey}", path_of(&tiers))
742    }
743
744    /// What reading id `i` would do: follow a link, fetch a search result, else read the snapshot.
745    fn id_row(&mut self, i: &Id) -> String {
746        let (cmd, c, page) = (self.cmd, self.c, i.page());
747        if let Some(&li) = cmd.links.first() {
748            let link = load(c, i).and_then(|l| l.doc.ok()).and_then(|d| d.links.get(li.wrapping_sub(1)).cloned());
749            return match link {
750                Some(u) => self.would(&format!("{page}{} l{li} {}", i.sec_tail(), short(&u, 60)), &u, None),
751                None => format!("{page}{} l{li} unknown · $0", i.sec_tail()),
752            };
753        }
754        // a refetch (`fresh:true`, `js:true`) of a fetched page is a new id (`fetch_again`); a search result fills
755        // its own id
756        let again = cmd.fresh().then(|| load(c, i)).flatten().map(|l| l.meta.url).filter(|u| u.starts_with("http"));
757        // an id whose run has not ended reads it (`pending`, `! abandoned`), the way `dispatch_one` does
758        let ran = pending(c, i.u, &[]).is_some_and(|o| o.rc == 0 || !cmd.fresh());
759        match c.st.result(i.u).filter(|e| i.job.is_none() && !ran && (e.dir.is_empty() || cmd.fresh())) {
760            Some(e) => self.would(&format!("{page} {} (search result)", short(&e.url, 60)), &e.url, Some(i.u)),
761            None if let Some(u) = again => self.would(&format!("{page} {}", short(&u, 60)), &u, None),
762            None => format!("{page} local read · $0"),
763        }
764    }
765}
766
767/// The `country:` and `device:` a fetch would send, as `dry:true` prints them (`provider::sent`).
768fn dry_mods(cmd: &Cmd, u: &str, tiers: &[(Tier, Option<Duration>)]) -> String {
769    let ask = Ask { url: u.into(), country: cmd.get("country").map(String::from), ..Ask::default() };
770    let paid = tiers.iter().any(|t| t.0 != Tier::Plain);
771    let from = if cmd.get("country").is_none() { " (from the domain)" } else { "" };
772    let country = provider::sent(&ask, Tier::Bd).filter(|_| paid).map(|cc| format!(" · country:{cc}{from}"));
773    let device = match cmd.get("device") {
774        Some("mobile") => " · device:mobile (oxy, decodo; bd serves desktop)",
775        _ => "",
776    };
777    country.unwrap_or_default() + device
778}
779
780/// `fats j<N>`: a search's list, its failure (its `!` row and tried path, as when it ran) or `pending`; a search
781/// still running is waited for within `wait:`, as a page (`wait_for`), then the read lists the ids its run stored.
782fn job_read(cmd: &Cmd, c: &mut Cache, j: usize) -> Out {
783    poll_until(c.born, wait_of(cmd), || search_pending(c, j).is_none(), || "search running".into());
784    c.reload();
785    let failed = c.serp(j).filter(|m| !m.ok).zip(c.job(j)).map(|(m, x)| search_out(c, &parse(&[x.cmd]), j, &m));
786    let mut o = failed.map(merged).or_else(|| search_pending(c, j)).unwrap_or_else(|| job_view(c, j));
787    if !cmd.words.is_empty() {
788        let q = cmd.words.join(" ");
789        o.warn(vec![format!("j{j} ! not_in_v1 multi-page filter → {} j{j}.u1 {q}", bin())]);
790    }
791    o
792}
793
794/// No page, no URL, no words: what to type; a list word alone names the page it needs (the current one, else u1).
795fn nothing_to_do(cmd: &Cmd, u: usize) -> Out {
796    let (b, list) = (bin(), WORDS.lists.iter().chain(&["media", "comments"]).find(|w| cmd.has(w)));
797    let page = list.map(|w| format!("? {w} needs a page: {b} u{} {w}", u.max(1)));
798    Out::ask(&page.unwrap_or(format!("? nothing to do · {b} <url> · {b} u1#2 · {b} u1 <words>")))
799}
800
801fn dispatch(cmd: &Cmd, c: &mut Cache) -> Out {
802    let b = bin();
803    if let Some(o) = command(cmd, c) {
804        return o;
805    }
806    if let Some(&j) = cmd.jobs.first()
807        && cmd.ids.is_empty()
808        && cmd.urls.is_empty()
809        && cmd.files.is_empty()
810    {
811        return job_read(cmd, c, j);
812    }
813    let one = match (cmd.files.as_slice(), page_url(cmd), cmd.words.is_empty()) {
814        ([f], None, false) if cmd.urls.is_empty() => Some(local(c, f, cmd)),
815        ([], Some(u), false) => Some(fetch(c, Want { url: u, ..Want::default() }, cmd)),
816        _ => None,
817    };
818    if let Some(o) = one {
819        // a document + words: read it, then filter it like `fats u3 <words>`; still running → its `pending`
820        let o = merged(o);
821        return match (o.rc, c.st.cursor.clone(), o.rec.contains_key("pending")) {
822            (0, Some(cur), false) => dispatch_one(cmd, c, &cur, Id { u: cur.u, ..Id::default() }, true),
823            _ => o,
824        };
825    }
826    if is_search(cmd) {
827        // free words alone = the omnibox search, not a filter of the last page; a URL + words = within that site
828        return merged(web(cmd, c));
829    }
830    if !cmd.files.is_empty() || !cmd.urls.is_empty() {
831        return fetch_all(cmd, c);
832    }
833    let cur = c.st.cursor.clone().unwrap_or_default();
834    let mut ids = cmd.ids.clone();
835    if ids.is_empty() && (!cmd.links.is_empty() || cmd.has("more") || cmd.has("up")) {
836        if cur.u == 0 {
837            return Out::ask(&format!("? no current page · {b} <url> first"));
838        }
839        // a bare `more` goes on with a search list, else with the current page (`read`)
840        if let Some((j, off)) = cur.serp.filter(|_| cmd.links.is_empty() && cmd.has("more")) {
841            return serp_list(c, j, off, false);
842        }
843        ids.push(Id { u: cur.u, ..Id::default() });
844    }
845    let Some(id) = ids.first().cloned() else { return nothing_to_do(cmd, cur.u) };
846    // one page per command in v1: name the others instead of dropping them (the cross-page filter comes later)
847    let q = cmd.words.join(" ");
848    let what = if q.is_empty() { "read" } else { "filter" };
849    let row = |p: String| format!("{p} ! not_in_v1 multi-page {what} → {}", format!("{b} {p} {q}").trim_end());
850    let rest: Vec<String> = ids[1..].iter().map(|i| row(i.page())).collect();
851    let mut out = dispatch_one(cmd, c, &cur, id, false);
852    out.warn(rest);
853    out
854}
855
856/// A `setup` / `config` command's move, run or `dry` (`dry:true`, `FATS_OFFLINE`: the check spends and saves
857/// nothing): a switch or a setting changed (`stats::change`), else `fats setup [zone:<name>] [import-env]`'s check
858/// (`import-env` copies the environment's keys in). None = neither.
859fn setup_move(cmd: &Cmd, dry: bool) -> Option<Out> {
860    let import = cmd.sub == ["import-env"];
861    if !cmd.sub.is_empty() && cmd.get("zone").is_none() && !import {
862        return Some(stats::change(cmd));
863    }
864    cmd.has("setup").then(|| stats::setup(cmd.get("zone"), import, dry, wait_of(cmd)))
865}
866
867/// The commands that read no page: status (also `fats` alone), version, stats, config, account, setup, telemetry,
868/// help (the card), guide (`lang::GUIDE`);
869/// `routes` (gone) a `?`, `install` a `!` with the install page.
870fn command(cmd: &Cmd, c: &mut Cache) -> Option<Out> {
871    let b = bin();
872    Some(match () {
873        _ if cmd.idle || cmd.has("status") => stats::status(c),
874        _ if cmd.has("version") => {
875            Out::new(vec![format!("= {b} {} · status: {b} · {}", env!("CARGO_PKG_VERSION"), to_guide())])
876        }
877        _ if cmd.has("stats") => stats::stats(c, cmd, json_of(cmd)),
878        _ if cmd.has("telemetry") => crate::telemetry::show(),
879        _ if cmd.has("setup") && cmd.sub == ["telemetry"] => Out::new(crate::telemetry::row()),
880        _ if let Some(out) = crate::setup::piped(cmd) => out,
881        _ if let Some(out) = setup_move(cmd, settings::get().offline.value) => out,
882        _ if cmd.has("config") => stats::config(),
883        _ if cmd.has("account") => stats::account(c, cmd.flag("fresh"), wait_of(cmd)),
884        // gone with the learned start: a `?`, never a paid web search
885        _ if cmd.has("routes") => {
886            Out::ask(&format!("? routes: gone (no learned starts) · a page's route: {b} <url> dry:true · {b} config"))
887        }
888        _ if cmd.has("help") => Out::new(CARD.lines().map(String::from).chain([to_guide()]).collect()),
889        _ if cmd.has("guide") => Out::new(GUIDE.lines().map(String::from).collect()),
890        _ => return None,
891    })
892}
893
894/// One page id + mods. `new` = this command just stored the page (no `· cache` age on it).
895fn dispatch_one(cmd: &Cmd, c: &mut Cache, cur: &Cursor, id: Id, new: bool) -> Out {
896    let mine = id.job.is_none_or(|j| c.job(j).is_some_and(|x| x.session == c.session));
897    // a fetch still running is waited for like a fetch: its page the moment it ends within `wait:` (default
898    // `WAIT`), else `pending` (`wait:0` = at once); a run that ended while waited for is this read's fresh copy,
899    // `fresh:true` starts only an abandoned one again
900    let live = mine && c.run(id.u).is_some_and(|(r, alive)| alive && r.done.is_none());
901    let ended = live && wait_for(c, id.u, wait_of(cmd)).is_some();
902    if ended {
903        c.reload();
904    }
905    let refetch = cmd.fresh() && cmd.links.is_empty() && cmd.media.is_empty() && !new && !ended;
906    if let Some(o) = pending(c, id.u, &cmd.words).filter(|o| mine && (o.rc == 0 || !refetch)) {
907        return o;
908    }
909    // a failed prefetch (plain only) goes up the whole ladder only when named (`fats u3`), never on a bare read word
910    // (`more`, `up`)
911    let missed = || c.run(id.u).is_some_and(|(r, _)| r.done.as_ref().is_some_and(|d| !d.ok) && is_prefetch(&r));
912    let again = refetch || (!cmd.ids.is_empty() && missed());
913    if let Some(url) = c.st.result(id.u).filter(|e| mine && (e.dir.is_empty() || again)).map(|e| e.url.clone()) {
914        return open_result(cmd, c, cur, id, &url);
915    }
916    if refetch {
917        return fetch_again(cmd, c, &id);
918    }
919    if let Some(&li) = cmd.links.first() {
920        return open_link(cmd, c, &id, li);
921    }
922    if let Some(&k) = cmd.media.first() { asset(c, &id, k, cmd.fresh()) } else { read(cmd, c, cur, &id, new) }
923}
924
925/// Pictures fetched on demand (`asset`): plain only, never a paid tier; an `image/*` answer of at most
926/// `ASSET_MAX` bytes within `ASSET_WAIT` (`fats config`).
927pub const ASSET_MAX: u64 = 10_000_000;
928pub const ASSET_WAIT: Duration = Duration::from_secs(15);
929
930/// `fats u3 m1`: picture m1 of the page (`fats u3 media` order), fetched plain into `<page>/assets/` once; a
931/// re-run reads it there. The `=` line says what viewing it costs (`outline::viewed`) before any pixel is sent:
932/// the shell's own reader opens the path; `fats mcp` attaches the pixels (`image` in the record). `fresh` (`fats u3
933/// m1 fresh:true`) downloads it again, never the page. A file too big for this path: the `max_bytes:` retry is no
934/// use (`At::done`), it opens in a browser.
935fn asset(c: &Cache, id: &Id, k: usize, fresh: bool) -> Out {
936    let Some(page) = load(c, id) else { return unknown(c, id) };
937    let media = page.doc.as_ref().map_or(&[][..], |d| &d.media[..]);
938    let (pic, rec) = (media.get(k.wrapping_sub(1)), page.dir.join("assets").join(format!("m{k}.json")));
939    let src = pic.map_or("", |p| p.src.as_str());
940    let ok = |a: &Asset| a.src == src && a.ext.bytes().all(|b| b.is_ascii_alphanumeric()); // the record names no path
941    let kept = jload::<Asset>(&rec).filter(|a| !fresh && ok(a) && rec.with_extension(&a.ext).is_file());
942    let (new, got) = match (pic, kept) {
943        (None, _) => (true, Err(("no_media".into(), format!("· the page lists {}", media.len())))),
944        (_, Some(a)) => (false, Ok(a)),
945        _ => (true, download(&rec, src)),
946    };
947    let subject = format!("{} m{k}", page.eq);
948    let a = match got {
949        Ok(a) => a,
950        Err((code, what)) => {
951            let at = At { id: &page.pid, url: src, arg: &format!("m{k}"), done: &["max_bytes:64m"] };
952            let row = bang(&format!("{} m{k}", page.pid), &code, &what, &at);
953            return Out::fail(&code, format!("= {subject} ! {code} {what}"), row);
954        }
955    };
956    let (kind, path) = (if pic.is_some_and(|p| p.video) { "poster" } else { "photo" }, rec.with_extension(&a.ext));
957    let (ext, bytes, path) = (&a.ext, ksize(a.bytes as usize), path.display());
958    // what viewing it costs: low = the standard tier `fats mcp` sends, high = unscaled on Claude 4.7+ (`~1.5–4.7k`)
959    let [lo, hi] = [outline::STD, outline::HI_RES].map(|t| ksize(outline::viewed(a.w, a.h, t).1 as usize));
960    let lo = if lo == hi { String::new() } else { lo.replace('k', "") + "–" };
961    let view = if a.w == 0 { "size unread, view cost unknown".into() } else { format!("~{lo}{hi} tok if viewed") };
962    let how = if new { format!("plain {}ms $0", a.ms) } else { format!("cache {}", outline::fmt_age(now() - a.t)) };
963    let mut o =
964        Out::new(vec![format!("= {subject} {kind} {}x{} {ext} {bytes}B · saved {path} · {view} · {how}", a.w, a.h)]);
965    o.set("id", page.eq).set("image", path.to_string()).set("cost", 0.0).set("cache", !new);
966    o
967}
968
969/// Picture `src` fetched plain: the file, then its record `rec`. Err = (code, what). A 403/410 is a signed link of
970/// the cached page that has expired (the page fetched again carries a fresh one) or a host that refuses
971/// downloads from elsewhere (hotlink protection): which one is not known.
972fn download(rec: &Path, src: &str) -> Result<Asset, (String, String)> {
973    let err = |code: &str, what: String| (code.to_string(), what);
974    if settings::get().offline.value {
975        return Err(err("offline", "FATS_OFFLINE is on".into()));
976    }
977    let (_turn, t0) = (provider::pace(src), Instant::now());
978    let ask = Ask { url: src.into(), timeout: Some(ASSET_WAIT), max_bytes: ASSET_MAX, html: true, ..Ask::default() };
979    let got = provider::block(provider::get(Tier::Plain, &ask, "")).map_or(Err("net_error".into()), |g| g.0);
980    let raw = got.map_err(|f| match f.code {
981        "too_big" => err(f.code, format!("{} (>{}B)", f.why, ksize(ASSET_MAX as usize)).trim_start().into()),
982        code => err(code, f.why),
983    })?;
984    let ctype = raw.ctype.split(';').next().unwrap_or_default().trim().to_string();
985    match raw.status {
986        200..300 if ctype.starts_with("image/") => {}
987        200..300 => return Err(err("not_image", if ctype.is_empty() { "no content-type".into() } else { ctype })),
988        s @ (403 | 410) => return Err(err(&format!("http_{s}"), "· signed link expired or hotlink-blocked".into())),
989        s => return Err(err(&format!("http_{s}"), String::new())),
990    }
991    let reader = image::ImageReader::new(std::io::Cursor::new(&raw.body)).with_guessed_format().ok();
992    let (w, h) = reader.and_then(|r| r.into_dimensions().ok()).unwrap_or_default();
993    let ext = image::ImageFormat::from_mime_type(&ctype).map_or("img", |f| f.extensions_str()[0]);
994    let file = rec.with_extension(ext);
995    let write = |e: std::io::Error| err("cache_write", format!("{}: {e}", file.display()));
996    std::fs::create_dir_all(rec.parent().unwrap_or(rec)).map_err(write)?;
997    std::fs::write(&file, &raw.body).map_err(write)?;
998    let (bytes, ms) = (raw.body.len() as u64, t0.elapsed().as_millis() as u64);
999    let a = Asset { src: src.into(), ext: ext.into(), bytes, ms, t: now(), w, h };
1000    crate::cache::jsave(rec, &a).map_err(|e| err("cache_write", e))?;
1001    Ok(a)
1002}
1003
1004fn open_result(cmd: &Cmd, c: &mut Cache, cur: &Cursor, id: Id, url: &str) -> Out {
1005    let o = merged(fetch(c, Want { url, slot: Some(id.u), ..Want::default() }, cmd));
1006    let open = cmd.words.is_empty() && cmd.links.is_empty() && cmd.media.is_empty() && cmd.reserved.is_empty();
1007    let open = open && id.sec.is_none();
1008    if o.rc != 0 || open || c.st.result(id.u).is_some_and(|e| e.dir.is_empty()) {
1009        return o;
1010    }
1011    let mut out = dispatch_one(cmd, c, cur, id, true);
1012    let warn = o.rec.get("warnings").and_then(|w| w.as_array()).into_iter().flatten();
1013    out.warn(warn.filter_map(|w| w.as_str().map(String::from)).collect());
1014    out
1015}
1016
1017/// A new id of `url` that a stored page points at (`u3 fresh`, `u3 l4`): its label says where it came from.
1018fn refetch(c: &mut Cache, cmd: &Cmd, url: &str, from: &str) -> Out {
1019    merged(fetch(c, Want { url, prov: Some(from), slot: None }, cmd))
1020}
1021
1022/// `fresh:true` on a stored page: a refetch is a new id; the old snapshot stays readable.
1023fn fetch_again(cmd: &Cmd, c: &mut Cache, id: &Id) -> Out {
1024    let Some(l) = load(c, id) else { return unknown(c, id) };
1025    match l.meta.url.strip_prefix("file://") {
1026        Some(f) => merged(local(c, f, cmd)),
1027        None if l.meta.url == "stdin:" => {
1028            Out::ask(&format!("? {} came from stdin · pipe it again: … | {} -", l.pid, bin()))
1029        }
1030        None if l.meta.url.is_empty() => no_doc(&l.pid, &l.eq, &l.meta, &[], &NoDoc::Missing, None), // forgotten
1031        None => refetch(c, cmd, &l.meta.url, &format!("{} fresh", l.pid)),
1032    }
1033}
1034
1035/// `u3 l4`: fetch the page's link 4 as a new id.
1036fn open_link(cmd: &Cmd, c: &mut Cache, id: &Id, li: usize) -> Out {
1037    let Some(l) = load(c, id) else { return unknown(c, id) };
1038    let doc = match &l.doc {
1039        Ok(d) => d,
1040        Err(why) => return no_doc(&l.pid, &l.eq, &l.meta, &[], why, None),
1041    };
1042    let sec = id.sec_tail();
1043    match li.checked_sub(1).and_then(|i| doc.links.get(i)) {
1044        Some(u) => refetch(c, cmd, u, &format!("{}{sec} l{li}", l.pid)),
1045        None => {
1046            let n = doc.links.len();
1047            let have = if n == 0 { "no links".into() } else { format!("have l1-l{n}") };
1048            Out::ask(&format!("? l{li} unknown on {} · {have} · {} {} links", l.pid, bin(), l.pid))
1049        }
1050    }
1051}
1052
1053/// Read a stored page: links, a filter, `all`, `full`, a section (part), `more`, else the outline.
1054fn read(cmd: &Cmd, c: &mut Cache, cur: &Cursor, id: &Id, new: bool) -> Out {
1055    let named = |m: &Match| cmd.get("match") == Some(m.name());
1056    let rung = [Match::Exact, Match::Near, Match::Topic].into_iter().find(named).unwrap_or(Match::Words);
1057    let pinned = cmd.get("match").is_some();
1058    let more = cmd.has("more") && cur.u == id.u && id.job.is_none();
1059    let (from, limit) = (cmd.count("from").map_or(0, |n| n.saturating_sub(1)), cmd.count("limit"));
1060    page_cmd(c, id, new, |p| {
1061        Ok(if let Some(kind) = WORDS.lists.iter().find(|w| cmd.has(w)) {
1062            outline::list(p, from, limit, &cmd.words, kind)
1063        } else if !cmd.words.is_empty() {
1064            search::grep(p, &cmd.words, (rung, pinned), id.sec, limit)?
1065        } else if cmd.has("all") {
1066            outline::outline_all(p)
1067        } else if cmd.has("media") {
1068            outline::media(p, from, limit)
1069        } else if cmd.has("comments") {
1070            outline::comments(p, id.sec, from, limit)
1071        } else if cmd.has("full") && (1..=p.doc.sections.len()).contains(&id.sec.unwrap_or(1)) || more && cur.full {
1072            outline::read_full(p, id.sec.or(cur.k.filter(|_| more)), if more && cur.full { cur.part + 1 } else { 0 })
1073        } else if let Some(k) = id.sec.or(cur.k.filter(|_| more)) {
1074            outline::read_sec(p, k, if more && cur.k == Some(k) { cur.part + 1 } else { id.part })?
1075        } else if cmd.has("more") {
1076            outline::outline_all(p)
1077        } else {
1078            outline::outline(p, None)
1079        })
1080    })
1081    .unwrap_or_else(|| unknown(c, id))
1082}
1083
1084/// A whole-command refusal: the `= ! {code} {what}` line and the `!` row (`{subject} ! {code} → fix`), with no
1085/// provider page (the codes here are never about a provider's key or money).
1086fn refused(code: &str, subject: &str, what: &str, at: &At) -> Out {
1087    Out::fail(code, format!("= ! {code} {what}"), bang(subject, code, "", at))
1088}
1089
1090/// The cache dir refused a write: say which file and where the dir is set.
1091fn cache_write(e: impl std::fmt::Display) -> Out {
1092    refused("cache_write", "", &e.to_string(), &At::default())
1093}
1094
1095/// Both arms are an `Out`: a failure (a bad cache write, a fenced read) is itself the answer, carried by `?`.
1096fn merged(r: Result<Out, Out>) -> Out {
1097    r.unwrap_or_else(|o| o)
1098}
1099
1100/// A URL whose own host is loopback, private or link-local: refused before any tier sees it.
1101fn private(url: &str) -> Out {
1102    let what = format!("{} · loopback, private and link-local hosts are not fetched · 0ms", short(url, 60));
1103    refused("private_address", &short(url, 60), &what, &At { url, ..At::default() })
1104}
1105
1106fn offline(what: &str) -> Out {
1107    let detail = format!("{what} · not cached · FATS_OFFLINE is on: cache and local files only · 0ms");
1108    refused("offline", what, &detail, &At::default())
1109}
1110
1111/// `fats j3`: the job's command, when it ran, and its pages (each as a typed-back id).
1112fn job_view(c: &Cache, j: usize) -> Out {
1113    let b = bin();
1114    let (Some(job), Some((st, _))) = (c.job(j), ids_of(c, Some(j))) else {
1115        return unknown(c, &Id { job: Some(j), u: 1, ..Id::default() });
1116    };
1117    if job.cmd.is_empty() {
1118        return refused("expired", "", &format!("j{j} · its command and pages went after an hour"), &At::default());
1119    }
1120    // the page's `stats` row (`stats::page_row`: a result's cached / not fetched, THE liveness rule), in this job
1121    let mine = st.u.iter().enumerate().filter(|(_, e)| e.job == Some(j));
1122    let rows: Vec<_> = mine.map(|(i, e)| stats::page_row(c, i + 1, e, &format!("j{j}.")).lean).collect();
1123    let age = outline::fmt_age((now() - job.t).max(0.0));
1124    // a search's rows are results, fetched or not (`9 pages` for 9 unfetched results)
1125    let what = if st.u.iter().any(|e| e.job == Some(j) && e.serp) { "results" } else { "pages" };
1126    let mut lines = vec![format!("= j{j} {} {what} · {age} ago · s:{} · {b} {}", rows.len(), job.session, job.cmd)];
1127    let next = match rows.len() {
1128        0 => format!("no pages stored · rerun: {b} {}", job.cmd),
1129        _ => format!("open: {b} j{j}.u{}", st.u.iter().position(|e| e.job == Some(j)).map_or(1, |p| p + 1)),
1130    };
1131    lines.extend(rows);
1132    lines.push(next);
1133    Out::new(lines).with("id", format!("j{j}"))
1134}
1135
1136fn unknown(c: &Cache, id: &Id) -> Out {
1137    let b = bin();
1138    let last = Some(c.job_count()).filter(|&n| n > 0).map(|n| format!("last job j{n}"));
1139    let Some((st, _)) = ids_of(c, id.job) else {
1140        let last = last.unwrap_or("no jobs yet".into());
1141        return Out::ask(&format!("? j{} unknown · {last} · {b} <url>", id.job.unwrap_or_default()));
1142    };
1143    let have = if st.u.is_empty() { "none".into() } else { format!("u1-u{}", st.u.len()) };
1144    Out::ask(&format!("? {} unknown · have {have} · {}", id.page(), last.unwrap_or(format!("{b} <url>"))))
1145}
1146
1147struct Loaded {
1148    pid: String,
1149    eq: String,
1150    meta: Meta,
1151    doc: Result<Doc, NoDoc>,
1152    dir: std::path::PathBuf,
1153    other: bool,
1154}
1155
1156/// The ids job `j` sees (None = this session's): (its session's state, true when that is another session).
1157/// None = an unknown job.
1158fn ids_of(c: &Cache, j: Option<usize>) -> Option<(State, bool)> {
1159    let Some(j) = j else { return Some((c.st.clone(), false)) };
1160    let s = c.job(j)?.session;
1161    // another session's state, read-only, from inside the cache (`Cache::dir`)
1162    let other = || c.dir(&Entry { dir: s.clone(), ..Entry::default() }).and_then(|d| jload(&d.join("state.json")));
1163    Some(if s == c.session { (c.st.clone(), false) } else { (other().unwrap_or_default(), true) })
1164}
1165
1166/// Resolve an id (`u3`, `j8.u3`) to its snapshot. None = unknown id.
1167fn load(c: &Cache, id: &Id) -> Option<Loaded> {
1168    let (st, other) = ids_of(c, id.job)?;
1169    let e = st.u.get(id.u.checked_sub(1)?)?.clone();
1170    let (meta, doc) = c.page(&e);
1171    let pid = if other { id.page() } else { format!("u{}", id.u) };
1172    let eq = if other { pid.clone() } else { e.eq(id.u) };
1173    Some(Loaded { pid, eq, meta, doc, dir: c.dir(&e).unwrap_or_default(), other })
1174}
1175
1176/// The other stored copies of page `n`'s URL in this session: the newest id a render (`rendered`, the auto ladder's
1177/// too) or a paid ask (`js:true`, `provider:`: its meta says `hedge:off`) served with other text than `doc`'s
1178/// (`u2 · rendered`), else, when `doc` shows none of the page's own words, a copy's part that does
1179/// (`u1#3fy · page content`), else, when it holds no record of its own either, a copy's unread page record
1180/// (`u1#2fv · page record · 995 tok · $0`, never the error page as "the best copy" beside it); for a copy the cap
1181/// stopped (`fetch::budget_row`) the newest later copy that served, first (`u4`: its fix ran, the move at $0, never the
1182/// same `cost:` arrow again); and whether one of two copies with the same served text was a paid ask (the paid hint
1183/// bought that copy back already); and the first newer copy asked another way (country, provider: a geo fix that ran),
1184/// whether the run that fetched this one named `country:`.
1185type Copies = (Option<String>, bool, (Option<String>, bool));
1186pub(crate) fn copies(c: &Cache, n: usize, (meta, doc): (&Meta, &Doc), log: &[String]) -> Copies {
1187    let text = |d: &Doc| d.sections[..d.served()].iter().flat_map(|s| s.lines.clone()).collect::<Vec<_>>();
1188    // a paid ask (`js:true`, `provider:`: one provider at a time)
1189    let me = &c.st.u[n - 1];
1190    let paid = |m: &Meta| m.hedge == "off";
1191    let owner = |m: &Meta| Tier::parse(&m.provider).map(Tier::owner);
1192    let runs = c.st.u.iter().enumerate().filter(|(_, e)| e.dir == me.dir).filter_map(|(i, _)| c.run(i + 1));
1193    let asked = runs.into_iter().any(|(r, _)| parse(std::slice::from_ref(&r.cmd)).get("country").is_some());
1194    let mut found = (None, false, (None, asked));
1195    // A copy with neither the page's own words nor a record of its own (a 536 B error page)
1196    let bare = outline::shown(doc, meta).is_none() && outline::record_in(doc, meta, &[]).is_none();
1197    // a starved copy (its row reads the pool file): once, not once a copy
1198    let starved = fetch::budget_row(meta, "", &[]).is_some();
1199    for (i, o) in c.st.u.iter().enumerate().filter(|(_, o)| o.url == me.url && !o.dir.is_empty() && o.dir != me.dir) {
1200        let (m, Ok(d)) = c.page(o) else { continue };
1201        let other = m.ok && (m.country != meta.country || owner(&m) != owner(meta));
1202        found.2.0 = found.2.0.or((i >= n && other).then(|| format!("u{}", i + 1)));
1203        let same = text(&d) == text(doc);
1204        found.1 |= same && (paid(&m) || paid(meta));
1205        // a render or a paid ask with other text, else (this copy without the page's own words) a copy's part
1206        // holding them
1207        let held = outline::shown(&d, &m).filter(|_| outline::shown(doc, meta).is_none());
1208        let rec = || outline::record_in(&d, &m, log).filter(|_| bare).map(|r| format!("u{}{r}", i + 1));
1209        found.0 = match held {
1210            _ if i >= n && m.ok && starved => Some(format!("u{}", i + 1)),
1211            _ if !same && (rendered(&m) || m.ok && paid(&m)) => Some(format!("u{} · rendered", i + 1)),
1212            Some(tail) => Some(format!("u{}{tail} · page content", i + 1)),
1213            None => found.0.or_else(rec),
1214        };
1215    }
1216    found
1217}
1218
1219/// Run `f` on a page. None = unknown id. Moves the cursor only in this session. `new` = this command made the
1220/// snapshot; every other read names its age (`· cache 15h`) so a stale page is never shown as current.
1221fn page_cmd(c: &mut Cache, id: &Id, new: bool, f: impl FnOnce(&Page) -> Result<Shown, String>) -> Option<Out> {
1222    let Loaded { pid, eq, meta, doc, dir, other } = load(c, id)?;
1223    let (before, others) = c.st.u.get(id.u - 1).filter(|_| !other).map(|me| seen(c, me)).unwrap_or_default();
1224    // A copy with no doc gets the URL's other copies too (its newer served copy is its move)
1225    let blank = Doc::default();
1226    let (render, again, fixed) = if other {
1227        (None, false, (None, false))
1228    } else {
1229        copies(c, id.u, (&meta, doc.as_ref().unwrap_or(&blank)), &before)
1230    };
1231    let doc = match doc {
1232        Ok(d) => d,
1233        Err(why) => return Some(no_doc(&pid, &eq, &meta, &others, &why, render)),
1234    };
1235    let age = (!new).then(|| (now() - meta.t).max(0.0));
1236    // The part read now is read before the next move is computed (never `→` this part)
1237    let key = id.sec.and_then(|k| outline::part_key(&doc, k, id.part));
1238    let read = std::iter::once(id.sec_tail()).chain(key.clone()).chain(before).collect();
1239    let p = Page { id: pid, eq, doc: &doc, meta: &meta, age, at: (read, render, again, fixed, others) };
1240    let (mut lines, cursor) = match f(&p) {
1241        Ok(s) => s,
1242        Err(q) => return Some(Out::ask(&q)),
1243    };
1244    // every read's `=` line: a stored page's age, then the page's flags as the last group (`outline::flags`)
1245    if let Some(l) = lines.first_mut().filter(|l| l.starts_with("= ")) {
1246        if let Some(a) = age {
1247            // once: a head line names it already (`· cache 2m`, `· og cache 2m`)
1248            let age = format!("cache {}", outline::fmt_age(a));
1249            let age = if l.contains(&format!(" {age}")) { String::new() } else { format!(" · {age}") };
1250            l.push_str(&(age + &stale(c, id)));
1251        }
1252        l.push_str(&outline::flags(&p));
1253    }
1254    let mut o = Out::new(lines);
1255    record(&mut o, &p, &dir.to_string_lossy(), new);
1256    if id.sec.is_some() {
1257        o.set("id", format!("{}{}", p.eq, id.sec_tail())); // the section read, as named
1258    }
1259    if id.sec.is_some()
1260        && !other
1261        && let Err(e) = c.read_mark(id.u, &[id.sec_tail()].into_iter().chain(key).collect::<Vec<_>>())
1262    {
1263        o = cache_write(e);
1264    }
1265    if let Some(mut cur) = cursor
1266        && !other
1267    {
1268        cur.u = id.u;
1269        c.st.cursor = Some(cur);
1270    }
1271    Some(o)
1272}
1273
1274/// What the session read of entry `me`'s page: its parts under any id of its folder (a cache hit is a new id of the
1275/// same folder) and the text of parts read under any copy of its URL (`outline::part_key`); and
1276/// the URL's other copies (their cuts bound the timeout fix: `fetch::fix_arg`; their failures count).
1277fn seen(c: &Cache, me: &Entry) -> (Vec<String>, Vec<Meta>) {
1278    let copies = c.st.u.iter().filter(|e| !e.dir.is_empty() && (e.url == me.url || e.dir == me.dir));
1279    let read = copies.clone().flat_map(|e| e.read.iter().filter(|r| e.dir == me.dir || r.starts_with('=')).cloned());
1280    let others = copies.filter(|e| e.dir != me.dir).filter_map(|e| c.meta(&e.dir));
1281    (read.collect(), others.collect())
1282}
1283
1284/// ` (3 jobs ago; newest j8)` after a bare `uN` whose page came from an older job than the session's newest
1285/// ids (a fetch or a search's results): one session per user means `u1` may be another task's page, or not the
1286/// first result of the search just run. `j5.u1` names its job: no tail.
1287fn stale(c: &Cache, id: &Id) -> String {
1288    let Some(j) = c.st.u.get(id.u.wrapping_sub(1)).and_then(|e| e.job).filter(|_| id.job.is_none()) else {
1289        return String::new();
1290    };
1291    let newer: std::collections::BTreeSet<usize> = c.st.u.iter().filter_map(|e| e.job).filter(|&k| k > j).collect();
1292    let s = if newer.len() == 1 { "" } else { "s" };
1293    newer.last().map_or(String::new(), |n| format!(" ({} job{s} ago; newest j{n})", newer.len()))
1294}
1295
1296fn record(o: &mut Out, p: &Page, path: &str, new: bool) {
1297    let m = p.meta;
1298    o.set("id", p.eq.clone())
1299        .set("url", p.doc.final_url.clone())
1300        .set("provider", m.provider.clone())
1301        .set("cost", if new { m.cost } else { 0.0 })
1302        .set("upto", if new { m.upto() } else { 0.0 })
1303        .set("bytes_in", if new { m.bytes } else { 0 })
1304        .set("cache", !new)
1305        .set("age", (now() - m.t).max(0.0) as u64)
1306        .set("path", path.to_string())
1307        .set("mode", p.doc.mode.clone());
1308    if let Some((_, m)) = o.lines.first().and_then(|l| l.split_once("match:")) {
1309        o.set("match", m.to_string());
1310    }
1311}
1312
1313/// The move that works today for a zip (docx, xlsx) this build cannot read: pipe its XML through stdin.
1314fn text_of_zip(path: &str) -> String {
1315    format!("unzip -p {path} '*.xml' | {} -", bin())
1316}
1317
1318/// A snapshot without a doc: a body this build cannot read, a failed fetch, or a converter crash. One shape:
1319/// `= {eq} ! {code} {what}`, then the `!` row with the table fix (`lang::bang`) and, for a key code, the provider's
1320/// page.
1321pub(crate) fn no_doc(id: &str, eq: &str, m: &Meta, others: &[Meta], why: &NoDoc, served: Option<String>) -> Out {
1322    let url = short(&m.url, 60);
1323    let mut at = At { id, url: &m.url, ..At::default() };
1324    let (mut owners, mut next, newer) = (Vec::new(), None, served.is_some());
1325    let zip = if let NoDoc::Zip(path) = why { text_of_zip(&path.to_string_lossy()) } else { String::new() };
1326    let (code, what, detail) = match why {
1327        NoDoc::Zip(_) => {
1328            at.arg = &zip;
1329            let what =
1330                format!("zip (docx/xlsx) · {url} · {}B cached, no zip text in this build", ksize(m.bytes as usize));
1331            ("not_in_v1", what, format!("zip {url}"))
1332        }
1333        NoDoc::Parse(e) => ("parse_failed", format!("· {url} · {e}"), url.clone()),
1334        NoDoc::Missing if !m.ok => {
1335            let code = if m.code.is_empty() || m.code == "ok" { "fetch_failed" } else { &m.code };
1336            let spent = provider::spent(" ", m.cost, m.upto());
1337            let what = format!("· {} · tried {} · {}ms{spent}", host_of(&m.url), m.tried(), m.ms);
1338            // A newer copy that served is the move (`copies`), no count beside it
1339            let (detail, again, fix, named) = fetch::fail_row(m, others, &url, id, served.is_some());
1340            (owners, next) = (named, Some(served.map(|s| format!("{} {s}", bin())).or(fix).unwrap_or_default()));
1341            (code, what, detail + &again)
1342        }
1343        NoDoc::Missing if m.url.is_empty() => ("expired", "· its page and URL went after an hour".into(), "".into()),
1344        NoDoc::Missing => ("snapshot_missing", format!("· {url} · the cached body is gone"), url.clone()),
1345    };
1346    // a failed fetch's move (`fail_row`: none = a COUNT), else the table's fix
1347    let next = next.unwrap_or_else(|| fix(code, &at));
1348    let row = Flag { code: code.into(), what: detail, next, row: true }.bang(id) + &provider::pages(code, owners);
1349    // a copy the cap stopped: its `budget_hit` row (`fetch::skipped`) is its row, the arrow its own, unless a newer
1350    // copy served (the row points there)
1351    let budget = fetch::budget_row(m, id, others).filter(|_| !newer);
1352    let row = budget.map_or(row, |r| format!("{id} {r}"));
1353    let mut o = Out::fail(code, format!("= {eq} ! {code} {what}"), row);
1354    if let NoDoc::Zip(path) = why {
1355        o.set("kind", "zip").set("path", path.to_string_lossy().into_owned());
1356    }
1357    o
1358}
1359
1360/// Local files, then URLs (cache or network); every URL's id is reserved in input order (`dry:true` names the same
1361/// ones), then every run is placed before any is waited for (`launch`: at most `batch_parallel` processes), all
1362/// under the one `wait:`; they share the `cost:` cap (`fetch::pooled`). A URL named twice is one run, its second row
1363/// `(same as above)`. Several inputs = one job: a `=` summary line, then each input's block; `json` = one record per
1364/// input, carrying `i`. Exit 0 when any input succeeded (the failures are `!` rows), else the worst code.
1365fn fetch_all(cmd: &Cmd, c: &mut Cache) -> Out {
1366    let t0 = Instant::now();
1367    let want = |url| Want { url, ..Want::default() };
1368    let mut started: Vec<_> = cmd.files.iter().map(|f| Some(local(c, f, cmd).map(Err))).collect();
1369    let mut queued = Vec::new();
1370    for (i, u) in cmd.urls.iter().enumerate() {
1371        if cmd.urls[..i].contains(u) {
1372            started.push(None);
1373            continue;
1374        }
1375        let now = at_once(c, want(u), cmd).map(Err);
1376        let id = now.unwrap_or_else(|| id_of(c, want(u), cmd).map(Ok));
1377        if let Ok(Ok((n, true))) = id {
1378            queued.push((n, want(u)));
1379        }
1380        started.push(Some(id.map(|r| r.map(|(n, _)| n))));
1381    }
1382    // a cache that takes no run file fails every input alike
1383    if let Err(e) = launch(c, &queued, cmd) {
1384        return cache_write(e);
1385    }
1386    let mut parts: Vec<Out> = Vec::new();
1387    for (i, (f, s)) in cmd.files.iter().chain(&cmd.urls).zip(started).enumerate() {
1388        // a URL named before: its first row's (`same`)
1389        let first = cmd.urls.iter().position(|u| u == f).and_then(|j| parts.get(cmd.files.len() + j));
1390        let mut o = match s {
1391            Some(s) => merged(s.and_then(|s| s.map_or_else(Ok, |n| finish(c, n, want(f), cmd)))),
1392            None => first.map_or_else(Out::default, same),
1393        };
1394        o.rec.entry("url").or_insert(f.as_str().into());
1395        o.rec.entry("ms").or_insert((t0.elapsed().as_millis() as u64).into());
1396        o.set("i", i);
1397        parts.push(o);
1398    }
1399    if parts.len() == 1 {
1400        return parts.pop().unwrap_or_default();
1401    }
1402    // the counts are the rows below: a `pending` row is no page in context yet (not `3 ok` over 2 pending)
1403    let pending = parts.iter().filter(|p| p.rec.contains_key("pending")).count();
1404    // a page is ok without an `error`: a capped one exits 0 and still counts as `! budget_hit`
1405    let failed = |p: &&Out| p.rc != 0 || p.rec.contains_key("error");
1406    let ok = parts.iter().filter(|p| !failed(p)).count() - pending;
1407    let mut fails = indexmap::IndexMap::<&str, usize>::new(); // first-seen order
1408    let errs = parts.iter().filter(failed).map(|p| p.rec.get("error").and_then(|v| v.as_str()).unwrap_or("failed"));
1409    errs.for_each(|e| *fails.entry(e).or_default() += 1);
1410    let pend = if pending > 0 { format!(" · {pending} pending") } else { String::new() };
1411    let fails: String = pend + &fails.iter().map(|(e, n)| format!(" · {n} ! {e}")).collect::<String>();
1412    let sum = |k: &str| parts.iter().filter_map(|p| p.rec.get(k).and_then(|v| v.as_f64())).fold(0.0, |a, b| a + b);
1413    let (job, ms) = (c.job.map(|j| format!("j{j} ")).unwrap_or_default(), t0.elapsed().as_millis());
1414    let spent = provider::spent(" ", sum("cost"), sum("upto"));
1415    let mut all = Out::new(vec![format!("= {job}{} inputs · {ok} ok{fails} · {ms}ms{spent}", parts.len())]);
1416    all.rc = if ok + pending > 0 { 0 } else { parts.iter().map(|p| p.rc).max().unwrap_or(1) };
1417    all.lines.extend(parts.iter().flat_map(|p| p.lines.iter().cloned()));
1418    all.set("id", c.job.map(|j| format!("j{j}")));
1419    all.parts = parts;
1420    all
1421}
1422
1423/// A URL the batch named before: the first row's record and code under one line, never its cost again.
1424fn same(first: &Out) -> Out {
1425    let eq = first.lines.first().and_then(|l| l.split(' ').nth(1)).unwrap_or_default();
1426    let rec = Box::new(first.rec.iter().filter(|(k, _)| *k != "cost").map(|(k, v)| (k.clone(), v.clone())).collect());
1427    Out { lines: vec![format!("= {eq} (same as above)")], rc: first.rc, rec, parts: vec![] }
1428}
1429
1430/// What a fetch asks for: the URL, the label of where it came from (`u3 fresh`, `u3 l4`), and the unfetched search
1431/// result id it fills (`slot`).
1432#[derive(Clone, Copy, Default)]
1433struct Want<'a> {
1434    url: &'a str,
1435    prov: Option<&'a str>,
1436    slot: Option<usize>,
1437}
1438
1439/// A URL → a new id (or the unfetched search result `slot`): the cached snapshot (unless `fresh:true`), else the
1440/// router in a detached run (`resume`) that this call waits for up to `wait:`. A run still going
1441/// then answers `pending` and fills the id later; a failed fetch is stored too (meta and the best copy), so its id
1442/// explains what was tried.
1443fn fetch(c: &mut Cache, want: Want, cmd: &Cmd) -> Result<Out, Out> {
1444    let new = |c: &mut Cache| {
1445        let (n, start) = id_of(c, want, cmd)?;
1446        if start {
1447            launch(c, &[(n, want)], cmd).map_err(cache_write)?;
1448        }
1449        finish(c, n, want, cmd)
1450    };
1451    at_once(c, want, cmd).map_or_else(|| new(c), Ok)
1452}
1453
1454/// The id a URL's fetch waits for (`finish`): the live run already fetching it in this session, else a new one
1455/// reserved (`true`: to launch). One fetch per URL in flight, and the same ask again = `fats uN` on that run: its
1456/// page the moment it lands within `wait:` (a re-ask that answered `pending` at once cost a weak model 6.3 calls
1457/// where the id form cost 2.0).
1458fn id_of(c: &mut Cache, want: Want, cmd: &Cmd) -> Result<(usize, bool), Out> {
1459    if let Some(n) = running(c, want.url) {
1460        return Ok((n, false));
1461    }
1462    reserve(c, Entry::default(), want, cmd).map(|n| (n, true)).map_err(cache_write)
1463}
1464
1465/// Reserve `want`'s id now (a search result's own `slot`) as `entry` (its url and job set here), so it prints
1466/// while the run goes on. Its job: the search's for a result it fills, else this command's.
1467fn reserve(c: &mut Cache, entry: Entry, want: Want, cmd: &Cmd) -> Result<usize, String> {
1468    let job = want.slot.and_then(|n| c.st.result(n)).and_then(|e| e.job).map_or_else(|| c.job_of(&cmd.raw), Ok)?;
1469    c.alloc(vec![Entry { url: want.url.into(), job: Some(job), ..entry }], want.slot)
1470}
1471
1472/// A URL's answer that needs no network and no wait: the cache, a private host, offline.
1473fn at_once(c: &mut Cache, want: Want, cmd: &Cmd) -> Option<Out> {
1474    let url = want.url;
1475    let out = cached(c, url, want, cmd);
1476    let out = out.or_else(|| provider::private_host(url).then(|| private(url)));
1477    out.or_else(|| settings::get().offline.value.then(|| offline(&short(url, 60))))
1478}
1479
1480/// Run `n`'s answer: its page once it ended within `wait:`, else `pending`.
1481fn finish(c: &mut Cache, n: usize, want: Want, cmd: &Cmd) -> Result<Out, Out> {
1482    let Some(done) = wait_for(c, n, wait_of(cmd)) else {
1483        return Ok(pending(c, n, &cmd.words).unwrap_or_default());
1484    };
1485    if let Some(e) = done.fail {
1486        return Err(cache_write(e));
1487    }
1488    c.reload();
1489    let mut out = outlined(c, n, true, want.prov);
1490    out.warn(done.warn);
1491    if !done.ok && out.rc == 0 {
1492        // the best copy is shown, but the fetch failed: scripts and agents see it in `error`, and in rc unless the
1493        // command's own cap stopped it (`budget_hit`: it ran as asked, its row carries the paid move)
1494        out.rc = i32::from(done.code != "budget_hit");
1495        out.set("error", done.code);
1496    }
1497    Ok(out)
1498}
1499
1500/// How long a command waits for the network before it answers (`wait:` 0–300): a fetch then says `pending`,
1501/// a search, `gh`, `account`, `setup` give up the calls still running. 30 s: agents read `pending` as a failure
1502/// (polled 1-2×, then quit); 14/27 walled runs ended within 30 s, 24/27 within it + one `wait:30` poll.
1503pub const WAIT: u64 = 30;
1504
1505pub fn wait_of(cmd: &Cmd) -> Duration {
1506    Duration::from_secs(cmd.get("wait").and_then(|v| v.parse().ok()).unwrap_or(WAIT))
1507}
1508/// How often the waiting call reads the run file.
1509pub const POLL: Duration = Duration::from_millis(20);
1510
1511/// THE placement, a batch's and a search's prefetch alike: the reserved runs, in input order, dealt round-robin onto
1512/// at most `batch_parallel` lanes, a RAM guard (50 URLs ran 50 processes at once, 608 MB; 8 lanes peak at ~230 MB),
1513/// ONE process a lane, `fats --continue j<J>.u<N>` on its first run (`detach`), which runs the others queued behind
1514/// it after (`Detached::by`, `resume`). No host rule: renders leave through the providers' own exits, and one lane a
1515/// host made 3 walled pages of one site take 107 s, not 50.
1516/// A run = its reserved id, what it asks; two or more share one `cost:` pool, its first run's file.
1517fn launch(c: &Cache, runs: &[(usize, Want)], cmd: &Cmd) -> Result<(), String> {
1518    let (cap, pool) =
1519        (settings::limit::<usize>("batch_parallel").max(1), runs.get(1).map(|_| c.run_file(runs[0].0, "pool.json")));
1520    if let Some(at) = &pool {
1521        fetch::seed(at, runs.iter().map(|(n, w)| (*n, plan_of(cmd, Some(w.url)))), plan_of(cmd, None).cap)?;
1522    }
1523    for (head, &(n, ..)) in runs.iter().enumerate().take(cap) {
1524        let job = c.st.u.get(n - 1).and_then(|e| e.job).unwrap_or_default();
1525        // the lane's lock before its run files: no reader sees one without it (`Cache::run`)
1526        let lock = c.run_claim(n).ok_or_else(|| format!("{}: not locked", c.run_file(n, "lock").display()))?;
1527        for (k, &(id, w)) in runs.iter().skip(head).step_by(cap).enumerate() {
1528            let (by, status) = if k == 0 { (0, String::new()) } else { (n, format!("queued after u{n}")) };
1529            let (url, line, prov, pool) = (w.url.into(), cmd.raw.clone(), w.prov.map(String::from), pool.clone());
1530            c.run_put(id, &Detached { url, cmd: line, prov, job, pool, by, status, t: now(), ..<_>::default() })?;
1531        }
1532        detach(format!("j{job}.u{n}"), &c.run_file(n, "log"), Some(lock))?;
1533    }
1534    Ok(())
1535}
1536
1537/// `fats --continue <id>` in its own process (own process group, stdio to `log`, `lock` held while it lives: its stdin
1538/// on Unix, kept here and taken again by the run on Windows); in-process on a thread holding `lock` when a test's fake
1539/// transport answers.
1540pub(crate) fn detach(id: String, log: &std::path::Path, lock: Option<std::fs::File>) -> Result<(), String> {
1541    // and its folder: a search may be the session's first command (a fetch's `run_put` made it)
1542    let made = log.parent().map_or(Ok(()), std::fs::create_dir_all).and_then(|()| std::fs::File::create(log));
1543    let log = made.map_err(|e| e.to_string())?;
1544    if provider::in_process() {
1545        std::thread::spawn(move || (resume(&id), lock));
1546        return Ok(());
1547    }
1548    let mut p = std::process::Command::new(std::env::current_exe().map_err(|e| e.to_string())?);
1549    // Unix: the lock goes as the run's stdin (a flock is the open file's, the child's too). Windows: a lock is the
1550    // process's that took it, never a child's that inherits the handle (LockFileEx, learn.microsoft.com), and goes
1551    // when it closes the handle: this process keeps it until the run or this process ends, the run takes its own
1552    // (`hold_lane`), granted when this one lets go
1553    let (stdin, keep) = if cfg!(windows) { (None, lock) } else { (lock, None) };
1554    p.args(["--continue", &id]).stdin(stdin.map_or_else(std::process::Stdio::null, std::process::Stdio::from));
1555    p.stdout(log.try_clone().map_err(|e| e.to_string())?).stderr(log);
1556    #[cfg(unix)]
1557    std::os::unix::process::CommandExt::process_group(&mut p, 0);
1558    #[cfg(windows)] // CREATE_NO_WINDOW: no console window flashes up for the detached run (learn.microsoft.com)
1559    std::os::windows::process::CommandExt::creation_flags(&mut p, 0x0800_0000);
1560    let mut child = p.spawn().map_err(|e| format!("fats --continue {id}: {e}"))?;
1561    // reaped when it ends while this process still runs (`fats mcp`); else the system reaps the orphan
1562    std::thread::spawn(move || (child.wait().ok(), keep));
1563    Ok(())
1564}
1565
1566/// Windows: a detached run takes its lane's lock (`detach`) on a thread that waits while the launcher holds it,
1567/// then keeps it while this process lives (the lock is a run's sign of life, `cache::run_at`).
1568fn hold_lane(c: &Cache, n: usize) {
1569    if let Ok(f) = std::fs::File::open(c.run_file(n, "lock")) {
1570        std::thread::spawn(move || {
1571            // held until the process exits (`main` exits with this thread parked); a spurious wake parks again
1572            if f.lock().is_ok() {
1573                loop {
1574                    std::thread::park();
1575                }
1576            }
1577        });
1578    }
1579}
1580
1581/// Run `n` as it ended, waiting while it lives (its lock held: a run that has not started yet answers `starting`)
1582/// until `wait` after the COMMAND started (`Cache::born`), never `wait` per input: three walled URLs waited
1583/// 3 × 30 s, past an MCP host's 60 s call limit. None = no such run, still running, or abandoned.
1584fn wait_for(c: &Cache, n: usize, wait: Duration) -> Option<Done> {
1585    let doing = || c.run(n).map(|r| on_now(&r.0.status)).unwrap_or_default();
1586    poll_until(c.born, wait, || c.run(n).is_none_or(|(r, alive)| r.done.is_some() || !alive), doing);
1587    c.run(n)?.0.done
1588}
1589
1590/// The tiers a run's status says are running, `bd, oxyjs running` (`plain:blocked_403✗ · bd running · oxyjs
1591/// running`); `starting` before its first call (an empty status), `next tier` between two tiers (a tier ended,
1592/// the next not yet called: `plain:blocked_403✗ · oxy:thin✗`).
1593fn on_now(status: &str) -> String {
1594    let on: Vec<&str> = status.split(" · ").filter_map(|t| t.strip_suffix(" running")).collect();
1595    if status.is_empty() {
1596        return "starting".into();
1597    }
1598    if on.is_empty() { "next tier".into() } else { format!("{} running", on.join(", ")) }
1599}
1600
1601/// How often a wait says it still works: the still-working line (`poll_until`), the MCP progress (`mcp::ticking`).
1602pub const TICK: Duration = Duration::from_secs(5);
1603
1604/// Sleep until `done` says so or `wait` after the command started (`born`): every wait of a command is one deadline.
1605/// A human at a terminal sees it work: at 5 s and every 5 s, `~ still working · bd, oxyjs running · 10 s` (`doing`)
1606/// on stderr, and only when stderr is a terminal and not `fats mcp`: a pipe (an agent's shell) gets no byte, as the
1607/// agent reads stderr only after the call, merged with its answer.
1608fn poll_until(born: Instant, wait: Duration, done: impl Fn() -> bool, doing: impl Fn() -> String) {
1609    let human = std::io::IsTerminal::is_terminal(&std::io::stderr()) && FENCE.get().is_none();
1610    let mut said = 0;
1611    while !done() && born.elapsed() < wait {
1612        let s = born.elapsed().as_secs() / TICK.as_secs() * TICK.as_secs();
1613        if human && s > said {
1614            said = s;
1615            eprintln!("~ still working · {} · {s} s", doing());
1616        }
1617        std::thread::sleep(POLL);
1618    }
1619}
1620
1621/// A pending run's next move, `fats u3 wait:30 · free, usually ready in ≈11s`: the median time of this session's
1622/// calls on its route (its host, the tiers it waits for: `bd running`) from the newest one's start, never past the
1623/// running calls' own deadline (`Plan::timeout_of` as they started: `timeout:1s`), less the time now, rounded
1624/// once; from < 3 such calls or past it no number, `· free, check again in 30 s`: a wrong number is worse than none
1625/// (one constant promised 42 s for a 0.6 s plain prefetch; any host's bd calls promised 28 s, it took 60.5 s).
1626fn ready(c: &Cache, n: usize, run: &Detached, words: &[String]) -> String {
1627    let words = words.iter().map(|w| format!(" {w}")).collect::<String>();
1628    // a tier the run waits for (`bd running · oxyjs running`): `oxy running` is no part of `oxyjs running`
1629    let on = |h: &HopRow| run.status.contains(&format!("{} running", provider::short(&h.provider)));
1630    let metas = c.st.u.iter().filter(|e| !e.alias && host_of(&e.url) == host_of(&run.url));
1631    let mut ms: Vec<u64> = metas.filter_map(|e| c.meta(&e.dir)).flat_map(|m| m.hops).filter(on).map(|h| h.ms).collect();
1632    ms.sort_unstable();
1633    let end = ms.get(ms.len() / 2).filter(|_| ms.len() >= 3).map(|p| (run.since + *p as f64 / 1e3).min(run.until));
1634    let left = end.map_or(0.0, |e| (e - now()).round().max(0.0)) as u64;
1635    poll_next(&format!("u{n}{words}"), left)
1636}
1637
1638/// THE pending move, a page's and a search's alike: `fats u3 wait:30 · free, usually ready in ≈11s`, or
1639/// `· free, check again in 30 s` with no time to promise (`left` 0).
1640fn poll_next(id: &str, left: u64) -> String {
1641    let poll = settings::limit::<u64>("poll_wait");
1642    let eta = if left == 0 { format!("check again in {poll} s") } else { format!("usually ready in ≈{left}s") };
1643    format!("{} {id} wait:{poll} · free, {eta}", bin())
1644}
1645
1646/// An id whose detached run has not ended, as the answer: `= j5.u3 pending 31s ex.com · bd running → fats u3 <words>
1647/// wait:30 · free, usually ready in ≈11s`, or, when its process died, its failed copy (`Detached::cut`, `! abandoned`,
1648/// the read the sweep's stored copy gives). None = no such run, or it ended (the page is stored).
1649fn pending(c: &Cache, n: usize, words: &[String]) -> Option<Out> {
1650    let (run, alive) = c.run(n).filter(|x| x.0.done.is_none())?;
1651    let (id, age, host) = (format!("u{n}"), (now() - run.t).max(0.0).round() as u64, host_of(&run.url));
1652    let eq = format!("j{}.u{n}", run.job);
1653    if alive {
1654        let status = if run.status.is_empty() { "starting" } else { &run.status };
1655        return Some(waiting(format!("= {eq} pending {age}s {host} · {status} → {}", ready(c, n, &run, words)), id));
1656    }
1657    Some(no_doc(&id, &eq, &run.cut(), &[], &NoDoc::Missing, None))
1658}
1659
1660/// THE pending answer, a page's and a search's: its one row, its id, `pending` in the record.
1661fn waiting(row: String, id: String) -> Out {
1662    Out::new(vec![row]).with("id", id).with("pending", true)
1663}
1664
1665/// The live run already fetching `url` in this session (not ended, its lock held): its id. A search's prefetch is
1666/// none: plain only, its failure would answer an ask that walks the whole ladder (`fats uN` walks it after one).
1667fn running(c: &Cache, url: &str) -> Option<usize> {
1668    let live = |r: &(usize, Detached, bool)| r.1.url == url && r.1.done.is_none() && r.2 && !is_prefetch(&r.1);
1669    c.runs().into_iter().find(live).map(|r| r.0)
1670}
1671
1672/// `fats --continue j5.u3`: the detached half of a fetch. Runs the router for the run `fetch` reserved and stores
1673/// the page in that id, whether or not the call that started it still waits. Exit code for `main`.
1674pub fn resume(id: &str) -> i32 {
1675    if let Some(p) = id.strip_prefix("setup-") {
1676        return crate::setup::serve(p);
1677    }
1678    if id == "telemetry" {
1679        return crate::telemetry::send();
1680    }
1681    let (mut c, cmd) = (Cache::open(), parse(&[id.to_string()]));
1682    // a detached search (`searching`): its own command, past every lead's `search_s` (`wait:0`): no `wait:`, so
1683    // `search_of` plans the one call at the retry's time (`one_call`), never cut
1684    if let (Some(&j), None) = (cmd.jobs.first(), cmd.ids.first()) {
1685        let Some(job) = c.job(j) else { return 2 };
1686        c.job = Some(j);
1687        let rc = web(&parse(&[format!("{} wait:0", job.cmd)]), &mut c).map_or(1, |o| o.rc);
1688        return rc.max(i32::from(c.save().is_err()));
1689    }
1690    let Some(n) = cmd.ids.first().map(|i| i.u) else { return 2 };
1691    if cfg!(windows) && !provider::in_process() {
1692        hold_lane(&c, n);
1693    }
1694    // its lane: this run, then the ones queued behind it (`launch`), one after another; the worst exit code
1695    c.runs().into_iter().filter(|r| r.0 == n || r.1.by == n).map(|r| run_one(&mut c, r.0)).max().unwrap_or(1)
1696}
1697
1698/// Run `n` of a lane, its result in its run file. Exit code.
1699fn run_one(c: &mut Cache, n: usize) -> i32 {
1700    // one run per id: its launcher's lock is this process's stdin; a run another process claimed (pid) stops
1701    let Some((mut r, _)) = c.run(n).filter(|x| x.0.done.is_none() && x.0.pid == 0) else { return 1 };
1702    r.pid = std::process::id();
1703    if c.run_put(n, &r).is_err() {
1704        return 1;
1705    }
1706    let w = Cache::at(c.root.clone(), c.session.clone());
1707    let seen = |(status, since, until)| {
1708        w.run_put(n, &Detached { status, since, until, ..r.clone() }).ok(); // progress only: the run goes on
1709    };
1710    let done = routed(c, &r, n, &seen);
1711    r.done = Some(done);
1712    i32::from(w.run_put(n, &r).is_err())
1713}
1714
1715/// The router for run `n`, its page stored in `u<n>`: how it ended.
1716fn routed(c: &mut Cache, run: &Detached, n: usize, seen: fetch::Seen) -> Done {
1717    let (cmd, url) = (parse(std::slice::from_ref(&run.cmd)), run.url.as_str());
1718    settings::mods(&cmd.mods);
1719    let mut p = Plan { pool: run.pool.clone().map(|f| (f, n)), ..plan_of(&cmd, Some(url)) };
1720    fetch::route_of(c, url, &mut p);
1721    p.prior = c.lookup(url).and_then(|(dir, _)| c.dir(&Entry { dir, ..Entry::default() }));
1722    let t0 = Instant::now();
1723    let ask = Ask {
1724        url: url.into(),
1725        country: cmd.get("country").map(String::from),
1726        mobile: cmd.get("device") == Some("mobile"),
1727        max_bytes: cap_of(&cmd),
1728        ..Ask::default()
1729    };
1730    let mut hops = fetch::run(&p, &ask, seen);
1731    let mut got = fetch::outcome(url, &mut hops, t0.elapsed().as_millis() as u64);
1732    let served = Tier::parse(&got.meta.provider);
1733    got.meta.country = served.and_then(|t| provider::sent(&ask, t)).unwrap_or_default();
1734    // a paid ask ran one provider at a time: `stats` and the `=` line say `hedge:off` (`Meta::how`)
1735    got.meta.hedge = if p.hedged() { "" } else { "off" }.into();
1736    let (ok, cost, id) = (got.meta.ok, got.meta.cost, format!("u{n}"));
1737    let skipped = fetch::skipped(&p, &hops, "", &id, url);
1738    // a page the cap left without a paid try failed on the budget, not the site (`budget_hit` on its `=` line and in
1739    // `stats`); one that bought a rung failed on what the rung met
1740    let starved = !hops.iter().any(|h| h.tier.spec().price > 0.0) && skipped.iter().any(|r| r.contains("budget_hit"));
1741    got.meta.code = if starved { "budget_hit".into() } else { got.meta.code };
1742    let code = got.meta.code.clone();
1743    got.meta.extra.insert("skipped".into(), skipped.into());
1744    // who spent a batch's pool is read at each print (`fetch::budget_row`)
1745    got.meta.extra.extend(p.pool.as_ref().map(|(at, _)| ("pool".into(), at.to_string_lossy().into())));
1746    let file = got.file.as_ref().map(|(name, body)| (name.as_str(), body.as_slice()));
1747    let (index, error, doc) = (ok.then_some(url), got.error.as_deref(), got.doc.as_ref());
1748    let snap = Snap { file, error, doc, meta: got.meta, index, slot: Some(n) };
1749    if let Err(e) = c.ingest(snap, run.job, t0) {
1750        return Done { ok, code, cost, fail: Some(e), ..Done::default() };
1751    }
1752    Done { ok, code, cost, warn: fetch::ignored(&ask, &hops, &id).into_iter().collect(), fail: None }
1753}
1754/// The snapshot indexed under `key` (unless `fresh:true`) as a new id of `url` that points at it: no second
1755/// copy, no cost. None = not cached.
1756fn cached(c: &mut Cache, key: &str, want: Want, cmd: &Cmd) -> Option<Out> {
1757    if let Some(n) = render_of(c, key, cmd) {
1758        return Some(outlined(c, n, false, None));
1759    }
1760    let (dir, _) = c.lookup(key).filter(|_| !cmd.fresh())?;
1761    let n = reserve(c, Entry { dir, alias: true, ..Entry::default() }, want, cmd);
1762    Some(n.map_or_else(cache_write, |n| outlined(c, n, false, want.prov)))
1763}
1764
1765/// THE stored-render rule: `js:true` without `fresh:true` on a URL whose session holds a served render (any id,
1766/// any provider: `rendered`) = that copy, the newest, $0; `dry:true` says so (`Dry::would`). A second render
1767/// of it came back with the same page (4.4k vs 4.2k tok, 16 photos each) for $0.0015 more.
1768fn render_of(c: &Cache, url: &str, cmd: &Cmd) -> Option<usize> {
1769    let has = |e: &Entry| e.url == url && !e.dir.is_empty() && c.meta(&e.dir).is_some_and(|m| rendered(&m));
1770    (cmd.flag("js") && !cmd.flag("fresh")).then(|| c.st.u.iter().rposition(has)).flatten().map(|i| i + 1)
1771}
1772
1773/// A copy a render served: a tier that renders (`Tier::can("js")`: bd, oxyjs, decodojs), ok, never a shell's og
1774/// card (`fetch::og_card`).
1775fn rendered(m: &Meta) -> bool {
1776    m.ok && m.kind != "og" && Tier::parse(&m.provider).is_some_and(|t| t.can("js"))
1777}
1778
1779/// A canonical path as a user writes it: Windows' canonical form is verbatim (`\\?\C:\x`, `\\?\UNC\host\share`),
1780/// a prefix no one types; a path without one is unchanged.
1781fn shown(p: &Path) -> String {
1782    let p = p.to_string_lossy();
1783    p.strip_prefix(r"\\?\UNC\").map_or_else(|| p.strip_prefix(r"\\?\").unwrap_or(&p).into(), |s| format!(r"\\{s}"))
1784}
1785
1786/// A local file (or stdin, `-`) → a new id: the stored snapshot when the same bytes came from the same place
1787/// before, else converted and stored.
1788fn local(c: &mut Cache, f: &str, cmd: &Cmd) -> Result<Out, Out> {
1789    let t0 = Instant::now();
1790    let path = crate::lang::local_path(f);
1791    let real = fenced(f, &path).map_err(|(code, why)| refused(code, f, &format!("{f} · {why}"), &At::default()))?;
1792    let bytes = read_local(f, real, &path, cap_of(cmd))?;
1793    let file = || format!("file://{}", shown(&std::fs::canonicalize(&path).unwrap_or(path)));
1794    let url = if f == "-" { "stdin:".to_string() } else { file() };
1795    // the same bytes from the same place again: the stored snapshot (read without a second parse)
1796    let key = blake3::Hasher::new().update(url.as_bytes()).update(&[0]).update(&bytes).finalize();
1797    let key = format!("blake3:{}", key.to_hex());
1798    if let Some(out) = cached(c, &key, Want { url: &url, ..Want::default() }, cmd) {
1799        return Ok(out);
1800    }
1801    let (bytes, charset) = provider::decode_body(bytes, None);
1802    let kind = crate::clean::kind_of("", &bytes);
1803    if kind == "zip" {
1804        let next = text_of_zip(f);
1805        let eq = format!("= ! not_in_v1 zip text: {f} · not in this build (pages, files, cache) → {next}");
1806        let o = Out::new(vec![eq]).with("error", "not_in_v1").with("hint", next).with("what", "zip");
1807        return Ok(Out { rc: 1, ..o });
1808    }
1809    // provider `local`, one free hop, never a render
1810    let meta = Meta {
1811        url,
1812        provider: "local".into(),
1813        ok: true,
1814        code: "ok".into(),
1815        t: now(),
1816        bytes: bytes.len() as u64,
1817        kind: kind.into(),
1818        render: Some(false),
1819        charset: charset.into(),
1820        hops: vec![HopRow { provider: "local".into(), code: "ok".into(), ..Default::default() }],
1821        ..Meta::default()
1822    };
1823    // a converter crash is the answer here (nothing stored, no job spent)
1824    let doc = crate::cache::build(&bytes, &meta.url, &meta.url, meta.render == Some(true), kind)
1825        .map_err(|e| no_doc(f, f, &meta, &[], &NoDoc::Parse(e), None))?;
1826    let job = c.job_of(&cmd.raw).map_err(cache_write)?;
1827    let name = crate::cache::raw_name(kind);
1828    let snap = Snap { file: Some((&name, &bytes)), error: None, doc: Some(&doc), meta, index: Some(&key), slot: None };
1829    let n = c.ingest(snap, job, t0).map_err(cache_write)?;
1830    Ok(outlined(c, n, true, None))
1831}
1832
1833/// A page just stored as `u<n>`, as its outline (`new` = fetched by this command, else a cache hit).
1834fn outlined(c: &mut Cache, n: usize, new: bool, prov: Option<&str>) -> Out {
1835    page_cmd(c, &Id { u: n, ..Id::default() }, new, |p| Ok(outline::outline(p, prov))).unwrap_or_default()
1836}
1837
1838/// A local file's (or stdin's) bytes, up to `cap`, opened at `real` (the fence's canonical path, `fenced`), never
1839/// at `path` again. Err = the answer: unreadable, or over the cap.
1840fn read_local(f: &str, real: std::io::Result<PathBuf>, path: &Path, cap: u64) -> Result<Vec<u8>, Out> {
1841    let mut v = Vec::new();
1842    let read = match f {
1843        "-" => std::io::stdin().take(cap + 1).read_to_end(&mut v),
1844        _ => real.and_then(std::fs::File::open).and_then(|h| h.take(cap + 1).read_to_end(&mut v)),
1845    };
1846    if let Err(e) = read {
1847        let dir = path.parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new("."));
1848        let at = At { arg: &dir.to_string_lossy(), ..At::default() };
1849        return Err(refused("no_file", f, &format!("{f} · {e}"), &at));
1850    }
1851    if v.len() as u64 > cap {
1852        let what = format!("over the {} input cap (ceiling {}) · nothing stored", mib(cap), mib(MAX_BYTES_CEIL));
1853        let at = At { url: f, done: &["max_bytes:64m"][..usize::from(cap >= MAX_BYTES_CEIL)], ..At::default() };
1854        return Err(refused("too_big", f, &format!("{f} · {what}"), &at));
1855    }
1856    Ok(v)
1857}
1858
1859#[cfg(test)]
1860mod tests {
1861    use super::*;
1862    use crate::scratch::Scratch;
1863
1864    fn cmd(s: &str) -> Cmd {
1865        parse(&s.split(' ').map(String::from).collect::<Vec<_>>())
1866    }
1867
1868    /// The still-working line names the tiers a run's status has running, an `oxy running` never inside `oxyjs`;
1869    /// `starting` only before the first call, never between tiers.
1870    #[test]
1871    fn the_still_working_line_names_the_running_tiers() {
1872        assert_eq!(on_now("plain:blocked_403✗ · bd running · oxyjs running"), "bd, oxyjs running");
1873        assert_eq!(on_now("plain:blocked_403✗ · oxy:thin✗"), "next tier");
1874        assert_eq!(on_now(""), "starting");
1875    }
1876
1877    /// A local page's URL holds the path a user types: no Windows verbatim prefix; other paths as they are.
1878    #[test]
1879    fn a_path_is_shown_as_typed() {
1880        let p = |s: &str| shown(Path::new(s));
1881        assert_eq!(
1882            (p(r"\\?\C:\a\b.html"), p(r"\\?\UNC\host\share\b.html")),
1883            (r"C:\a\b.html".into(), r"\\host\share\b.html".into())
1884        );
1885        assert_eq!((p("/tmp/a b.html"), p(r"C:\a.html")), ("/tmp/a b.html".into(), r"C:\a.html".into()));
1886    }
1887
1888    /// A local read opens the canonical path the fence judged (TOCTOU): a link swapped to another file after the
1889    /// check is never read (`read_local` opening the link again reads the swapped file); a path that does not
1890    /// resolve is its own error.
1891    #[test]
1892    #[cfg(unix)]
1893    fn a_local_read_opens_the_path_it_checked() {
1894        let root = Scratch::new("fenced");
1895        let [a, b, link] = ["a.txt", "b.txt", "l.txt"].map(|n| root.join(n));
1896        std::fs::write(&a, "checked").ok();
1897        std::fs::write(&b, "swapped").ok();
1898        std::os::unix::fs::symlink(&a, &link).ok();
1899        let real = fenced("l.txt", &link);
1900        assert_eq!(real.as_ref().ok().and_then(|r| r.as_ref().ok()), a.canonicalize().ok().as_ref());
1901        std::fs::remove_file(&link).ok();
1902        std::os::unix::fs::symlink(&b, &link).ok();
1903        let Ok(real) = real else { panic!("inside the fence") };
1904        let read = read_local("l.txt", real, &link, 64).ok();
1905        assert_eq!(read.as_deref(), Some(&b"checked"[..]), "the link's new target is never opened");
1906        assert!(fenced("x", &root.join("none")).is_ok_and(|r| r.is_err()), "a missing file falls to no_file");
1907    }
1908
1909    /// `more` beside a list (the old hint syntax) is named, never a silent page 1.
1910    #[test]
1911    fn more_beside_a_list_is_named() {
1912        let b = bin();
1913        let row = |w: &str| format!("! ignored more · lists page by from:K → {b} {w} from:K");
1914        assert_eq!(ignored(&cmd("u1 links more")), [row("u1 links")]);
1915        assert_eq!(ignored(&cmd("u2#3 media more")), [row("u2 media")]);
1916        assert_eq!(ignored(&cmd("links more")), [row("links")]);
1917        assert!(ignored(&cmd("u1 more")).is_empty() && ignored(&cmd("u1 links from:3")).is_empty());
1918    }
1919
1920    /// A timed-out search's fix gives its call more time than it had, never the same paid cut again.
1921    #[test]
1922    fn a_search_timeout_fix_adds_time() {
1923        let row = |why: &str, ms: u64| {
1924            let hops = vec![HopRow {
1925                provider: "brightdata".into(),
1926                code: "provider_timeout".into(),
1927                ms,
1928                why: why.into(),
1929                ..Default::default()
1930            }];
1931            let m = Meta { url: "search:rust".into(), code: "provider_timeout".into(), hops, ..Meta::default() };
1932            let out = search_out(&Cache::at(PathBuf::new(), "t".into()), &parse(&["rust".into()]), 1, &m)
1933                .unwrap_or_else(|o| o);
1934            out.lines.join("\n")
1935        };
1936        let b = bin();
1937        let row15 = row("", 15_000);
1938        assert!(row15.ends_with(&format!("! provider_timeout → {b} rust fresh:true timeout:30 ≤$0.0025")), "{row15}");
1939        assert!(row("", 30_000).ends_with(&format!("! provider_timeout → {b} rust fresh:true ≤$0.0025")), "ran 30 s");
1940        let wait = row("wait:5s", 5_000);
1941        assert!(
1942            wait.ends_with(&format!("! provider_timeout bd wait:5s → {b} rust fresh:true wait:30 ≤$0.0025")),
1943            "{wait}"
1944        );
1945    }
1946
1947    /// The four answers for a snapshot without a doc, each `= {eq} ! {code} …` + the `!` row with the table fix
1948    /// (and the provider's page for a key code): a zip body, a converter crash, a failed fetch with no body kept,
1949    /// a body that is gone.
1950    #[test]
1951    fn no_doc_answers() {
1952        let b = bin();
1953        let hop = |code: &str| HopRow { provider: "oxylabs".into(), code: code.into(), ..Default::default() };
1954        let m = Meta { url: "https://ex.com/a".into(), ok: true, bytes: 2048, ..Meta::default() };
1955        let lines = |why: &NoDoc, m: &Meta| no_doc("u3", "j2.u3", m, &[], why, None).lines.join("\n");
1956        let zip = lines(&NoDoc::Zip("/c/u3/raw.zip".into()), &m);
1957        assert_eq!(
1958            zip,
1959            format!(
1960                "= j2.u3 ! not_in_v1 zip (docx/xlsx) · ex.com/a · 2.0kB cached, no zip text in this build\n\
1961                 u3 ! not_in_v1 zip ex.com/a → unzip -p /c/u3/raw.zip '*.xml' | {b} -"
1962            )
1963        );
1964        let o = no_doc("u3", "u3", &m, &[], &NoDoc::Zip("/c/u3/raw.zip".into()), None);
1965        assert_eq!((o.rc, o.rec["kind"].as_str(), o.rec["path"].as_str()), (1, Some("zip"), Some("/c/u3/raw.zip")));
1966        assert_eq!(
1967            lines(&NoDoc::Parse("pdf: bad xref".into()), &m),
1968            format!(
1969                "= j2.u3 ! parse_failed · ex.com/a · pdf: bad xref\nu3 ! parse_failed ex.com/a → {b} config · report the URL"
1970            )
1971        );
1972        assert_eq!(
1973            lines(&NoDoc::Missing, &m),
1974            format!(
1975                "= j2.u3 ! snapshot_missing · ex.com/a · the cached body is gone\nu3 ! snapshot_missing ex.com/a → {}",
1976                crate::lang::priced(&format!("{b} https://ex.com/a fresh:true"), "https://ex.com/a")
1977            )
1978        );
1979        const K: &str = " · oxy https://dashboard.oxylabs.io (a Web API instance's key)";
1980        let failed =
1981            Meta { ok: false, code: "bad_key".into(), ms: 700, cost: 0.001, hops: vec![hop("bad_key")], ..m.clone() };
1982        assert_eq!(
1983            lines(&NoDoc::Missing, &failed),
1984            format!(
1985                "= j2.u3 ! bad_key · ex.com · tried oxy:bad_key✗ · 700ms spent $0.0010\nu3 ! bad_key oxy → {b} setup{K}"
1986            )
1987        );
1988        let timed = Meta { code: "provider_timeout".into(), hops: vec![hop("provider_timeout")], ..failed.clone() };
1989        let t = lines(&NoDoc::Missing, &timed);
1990        assert!(t.ends_with(&format!("\nu3 ! provider_timeout ex.com/a → {b} u3 fresh:true js:true ≤$0.0030")), "{t}");
1991        let gone = Meta { code: String::new(), hops: vec![], ..failed };
1992        assert!(lines(&NoDoc::Missing, &gone).starts_with("= j2.u3 ! fetch_failed · ex.com · tried - · "));
1993    }
1994
1995    /// THE liveness rule (`Cache::run`): a run lives while its lock is held, the launcher's before the process
1996    /// starts, however long that takes (a 2 s window printed `! abandoned` under load); `pending`, status and
1997    /// `fats jN` read the same verdict.
1998    #[test]
1999    fn a_run_lives_while_its_lock_is_held() {
2000        let root = Scratch::new("start");
2001        let mut c = Cache::at(root.to_path_buf(), "t".into());
2002        let job = c.job_of("https://ex.com/a").expect("job");
2003        c.alloc(vec![Entry { url: "https://ex.com/a".into(), job: Some(job), ..Entry::default() }], None).expect("id");
2004        let lock = c.run_claim(1).expect("the launcher's lock");
2005        c.run_put(1, &Detached { url: "https://ex.com/a".into(), job: 1, t: now() - 60.0, ..Detached::default() })
2006            .expect("run file");
2007        let read = || (c.run(1).map(|r| r.1), pending(&c, 1, &[]).expect("a run").lines.join("\n"));
2008        let (alive, out) = read();
2009        assert!(alive == Some(true) && out.contains(" pending 60s ex.com · starting → "), "pid 0 at 60 s: {out}");
2010        let row = |c: &Cache| job_view(c, job).lines.get(1).cloned().unwrap_or_default();
2011        assert!(row(&c).starts_with("j1.u1 ex.com/a · pending → "), "{}", row(&c));
2012        drop(lock);
2013        let (alive, out) = read();
2014        assert!(alive == Some(false) && out.contains(" ! abandoned ex.com"), "no lock: {out}");
2015        assert!(row(&c).starts_with("j1.u1 ex.com · ! abandoned ex.com/a · "), "{}", row(&c));
2016    }
2017
2018    /// A session holding one plain id, then a saved Oxylabs answer listed as a search: (cache, its root, the hits,
2019    /// the search record, the listed output). No network: the provider call is the only part not run.
2020    fn listed_session(tag: &str) -> (Cache, Scratch, Vec<Hit>, Meta, Out) {
2021        let root = Scratch::new(&format!("serp-{tag}"));
2022        let mut cache = Cache::at(root.to_path_buf(), "t".into());
2023        let old = Entry { url: "https://ex.com/".into(), dir: "t/u1".into(), ..Entry::default() };
2024        assert_eq!(cache.alloc(vec![old], None), Ok(1));
2025        let body = include_bytes!("../tests/fixtures/oxy-search.json");
2026        let hits = provider::hits(Tier::Oxy, body, 10).expect("fixture");
2027        let job = cache.job_of("heidelberg university").expect("job");
2028        let meta = Meta {
2029            url: "search:heidelberg university".into(),
2030            provider: "oxylabs".into(),
2031            ms: 1630,
2032            cost: 0.001,
2033            kind: "serp".into(),
2034            t: now(),
2035            ..Default::default()
2036        };
2037        let out = merged(listed(&mut cache, job, meta.clone(), &hits));
2038        (cache, root, hits, meta, out)
2039    }
2040
2041    /// The list shape, one unfetched id per result after the ids already in the session, and `u<N> dry:true`
2042    /// resolving the result's URL.
2043    #[test]
2044    fn search_results_become_ids() {
2045        let (cache, _root, _, _, out) = listed_session("ids");
2046        let b = bin();
2047        // every row within the read cap, 1000 real tokens (`clean::tok`): all five, no `more`
2048        let first = "= j1 search \"heidelberg university\" · 5 results · oxylabs · 1.6s · spent $0.0010";
2049        assert_eq!(out.lines[0], first);
2050        assert_eq!(
2051            out.lines[1],
2052            "u2  uni-heidelberg.de/en  Heidelberg University — \"Heidelberg University – the oldest in Germany, recognized globally. \
2053             A leader in science, …\""
2054        );
2055        let wiki = "u4  en.wikipedia.org/wiki/Heidelberg_Univer…  Heidelberg University - Wikipedia";
2056        assert!(out.lines[3].starts_with(wiki));
2057        let last = format!("open one: {b} u2 · filter: {b} u2 <words>");
2058        assert_eq!(out.lines.last().map(String::as_str), Some(&*last));
2059        assert_eq!((out.lines.len(), out.parts.len(), out.rc), (7, 5, 0));
2060        assert_eq!(out.parts[0].rec["url"], "https://www.uni-heidelberg.de/en");
2061        assert_eq!((out.parts[0].rec["cost"].as_f64(), out.parts[1].rec["cost"].as_f64()), (Some(0.001), Some(0.0)));
2062        let unfetched = |n| cache.st.result(n).filter(|e| e.dir.is_empty()).cloned();
2063        let entry = unfetched(2).expect("u2 is a search result");
2064        assert_eq!((entry.url.as_str(), entry.job), ("https://www.uni-heidelberg.de/en", cache.job));
2065        assert!(unfetched(1).is_none() && unfetched(7).is_none());
2066        let dry = plan(&cmd("u2 dry:true"), &cache).lines.join("\n");
2067        assert!(dry.contains("u2 uni-heidelberg.de/en (search result)") && !dry.contains("local read"), "{dry}");
2068    }
2069
2070    /// 20 results: the list stops at the cap, `more` goes on from the cursor, `more` at the end says so.
2071    #[test]
2072    fn more_lists_past_the_cap() {
2073        let (mut cache, _root, hits, meta, _) = listed_session("more");
2074        let b = bin();
2075        let many: Vec<Hit> = (0..4).flat_map(|_| hits.clone()).collect();
2076        let job = cache.job_of("again").expect("job");
2077        let out = merged(listed(&mut cache, job, meta, &many));
2078        let rows = out.lines.iter().filter(|l| l.starts_with('u')).count();
2079        assert!((3..20).contains(&rows), "{:?}", out.lines);
2080        assert!(out.lines.last().is_some_and(|l| l.ends_with(&format!("more: {b} more"))));
2081        assert_eq!(cache.st.cursor.as_ref().and_then(|k| k.serp), Some((job, rows)));
2082        let more = dispatch(&cmd("more"), &mut cache);
2083        assert!(more.lines[0].starts_with(&format!("= j{job} search ")), "{:?}", more.lines);
2084        assert!(more.lines[0].contains(&format!(" shown u{}-", 7 + rows)), "{:?}", more.lines);
2085        assert!(more.lines[1].starts_with(&format!("u{}  ", 7 + rows)), "{:?}", more.lines);
2086    }
2087}