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