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