Skip to main content

fats/
cli.rs

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