Skip to main content

fats/
lang.rs

1//! LANG: argv → command (parse + repair) and the ONLY place that writes to stdout.
2
3use chrono::Datelike;
4use std::io::IsTerminal;
5use std::path::Path;
6use std::sync::{LazyLock, OnceLock};
7
8/// The language's words (`src/data/words.json`).
9#[derive(serde::Deserialize)]
10#[serde(deny_unknown_fields, bound(deserialize = "'de: 'static"))]
11pub struct Words {
12    /// Command words: reserved only when the command holds no free text.
13    reserved: Vec<&'static str>,
14    /// Reserved only as the whole command (mods and `json` aside), as itself or as an alias: `fats u1 version`
15    /// filters the page for `version`, `fats login json` is `setup json`, `fats login page design` searches.
16    alone: Vec<&'static str>,
17    /// The lists of a page: next to a page id, the first word stays the list and the words after it filter it
18    /// (`fats u1 links inmueble`, `fats u1 cards 3 hab`).
19    pub lists: Vec<&'static str>,
20    /// Other spellings of a reserved word, and what people type for it (`login` → `setup`, `balance` →
21    /// `account`): reserved only without free text, like the word itself; `-V` by its case.
22    pub aliases: Vec<(&'static str, &'static str)>,
23    /// Words people type that name no command (`logout`, `install`): alone (mods aside) they get one `!` line
24    /// pointing to what fats has (`{b}` = the binary), never a paid search.
25    elsewhere: Vec<(&'static str, &'static str)>,
26    /// A leading verb is dropped (`read u2#3`); it also says the rest are words (`search stat`).
27    verbs: Vec<&'static str>,
28    /// Known mod keys (aliases resolve to these first), and those that take a boolean.
29    pub keys: Vec<&'static str>,
30    bools: Vec<&'static str>,
31    /// The commands a lone word may be a typo of. The reading words (`more`, `full`, `json`, `links`, `help`)
32    /// are left out: their neighbours are real searches (`mode`, `fuel`, `jason`, `yelp`).
33    pub commands: Vec<&'static str>,
34    /// More commands a first word led into a URL or id may be a typo of (`fetchh https://x`, `hlep u1`).
35    led: Vec<&'static str>,
36    /// Search-engine operators: an unknown key among them is a search word as typed (`filetype:pdf`), never `?`.
37    operators: Vec<&'static str>,
38    /// The IANA root zone (`tlds-alpha-by-domain.txt`, version 2026101900): a bare name is a host only when its
39    /// last label is one (`bare_tld`): `opencode.json`, `main.go` are words.
40    tlds: Vec<&'static str>,
41    /// What leads a path, never a key (`setup::masked`): `/etc/x`, `./file`, `~/x`.
42    pub path_lead: Vec<&'static str>,
43    /// The TLDs that are a file's extension too: a lone one-dot name ending in one (`main.rs`) is a file when it
44    /// exists, else it asks file or site (`parse`), never a guessed site.
45    file_tlds: Vec<&'static str>,
46    /// Key and credential file names (`.env.*` = a prefix), matched on the bare name: `cli::secret`.
47    pub secret_names: Vec<&'static str>,
48    /// Headers that carry a credential, the site's or ours: never kept with a page (`provider::header_lines`).
49    pub secret_headers: Vec<&'static str>,
50    /// A filter for only these words that finds nothing points to the page's media list (`search::grep`).
51    pub media: Vec<&'static str>,
52    /// Agent hosts by the env marker each sets for the commands it runs (`stats::host_of`): `CLAUDECODE` (Claude
53    /// Code's shell), `CODEX_THREAD_ID` (Codex's exec env), `PI_CODING_AGENT` (pi); the first set one wins.
54    pub hosts: Vec<(&'static str, &'static str)>,
55    /// The hosts `fats status` names and `fats setup mcp <host>` adds fats to: the files its `mcp add` writes
56    /// (`mcp::read`), that command (`{b}` = the server's command; none = fats writes the first file), the name a
57    /// person knows: Claude Code's user and local scopes in `~/.claude.json` (`$CLAUDE_CONFIG_DIR/.claude.json` while
58    /// that is set, code.claude.com/docs/en/claude-directory), its project scope in `./.mcp.json`
59    /// (code.claude.com/docs/en/mcp), Codex's `$CODEX_HOME/config.toml` (developers.openai.com/codex/mcp), Cursor's
60    /// global and project files (cursor.com/docs/context/mcp).
61    pub mcp_hosts: Vec<(&'static str, Vec<&'static str>, &'static str, &'static str)>,
62    /// What an SSH login sets (OpenSSH, ssh(1) ENVIRONMENT): `fats setup <p>` adds the key's SSH way only then.
63    pub ssh: Vec<&'static str>,
64    /// Words a filter never looks for (`search::terms_of`, the title query).
65    pub stop: Vec<&'static str>,
66}
67
68pub static WORDS: LazyLock<Words> = LazyLock::new(|| crate::settings::table("words"));
69
70pub const CARD: &str = "\
71fats <url|file.pdf>     fetch, outline           fats u3  u3#2  u3#2 l4  page  section  link
72fats u3#2 <words>       filter inside            fats <words>  web search → ids  site:ex.com  since:7d
73mods key:value  limit:20  match:exact|words  country:de  js:true  wait:30 (then pending)  provider:plain|bd|oxy|decodo  device:mobile
74more  up  all  full  json  fats = status  fats setup = keys  fats account = balance  j8.u3 = another session's id";
75
76/// `fats guide`: how to use fats well, the body the installed skill points at (`skills/fatsearch/SKILL.md`), so
77/// the guide always matches this binary.
78pub const GUIDE: &str = include_str!("data/guide.md");
79
80/// The line every first door ends with (`help`, `version`, the status, `setup`, a word that is no command): where
81/// the guide is and what reading it costs.
82pub fn to_guide() -> String {
83    format!("agents: {} guide = the manual (~{} tok)", bin(), ksize(crate::clean::tok(GUIDE)))
84}
85
86/// `--help` anywhere (an en or em dash for `--`: smart punctuation), or `-h`.
87const HELP_FLAGS: [&str; 4] = ["--help", "-h", "—help", "–help"];
88
89/// The human screens (`src/data/screens/`: text a human edits without Rust; `paint` fills the `{hole}`s).
90/// A `help-<topic>` row is `fats help <topic>`.
91pub const SCREENS: [(&str, &str); 11] = crate::settings::embed!("screens/", ".txt": "home", "ready", "yours",
92    "help", "help-mcp", "help-setup", "help-search", "tip-page", "tip-search", "setup", "telemetry");
93
94/// The styles a screen names (`{bold}` … `{/}`) and their ANSI SGR codes; none under `NO_COLOR` (no-color.org:
95/// set and not empty).
96const STYLES: [(&str, u8); 6] = [("bold", 1), ("dim", 2), ("green", 32), ("red", 31), ("cyan", 36), ("/", 0)];
97
98/// A screen with styles only.
99pub const NO_HOLES: [(&str, &str); 0] = [];
100
101pub fn screen(name: &str) -> &'static str {
102    SCREENS.iter().find(|s| s.0 == name).map_or("", |s| s.1)
103}
104
105/// THE hole filler (screens, `errors.json` fixes, table rows): each `{name}` of `holes`, in their order, becomes
106/// its value; any other `{` stays (JSON, a stray brace).
107pub fn draw(text: &str, holes: &[(&str, impl AsRef<str>)]) -> String {
108    holes.iter().fold(text.to_string(), |t, (name, value)| t.replace(&format!("{{{name}}}"), value.as_ref()))
109}
110
111/// A human screen: `text`'s holes, then its styles.
112pub fn paint(text: &str, holes: &[(&str, impl AsRef<str>)]) -> String {
113    let plain = std::env::var_os("NO_COLOR").is_some_and(|v| !v.is_empty());
114    #[cfg(test)]
115    let plain = tests::NO_COLOR.get().unwrap_or(plain);
116    draw(&draw(text, holes), &STYLES.map(|(k, n)| (k, if plain { String::new() } else { format!("\x1b[{n}m") })))
117}
118
119/// Whether a human reads this process's answers (`human`), set once by `cli::run`: a row built later (`fix`'s
120/// `no_key`) reads it without knowing the command; unset = an agent.
121pub static HUMAN: OnceLock<bool> = OnceLock::new();
122
123/// A human reads the answer: stdout is a terminal, or `FATS_HUMAN=1` (`0` = never); never `json`, MCP, a unit test.
124pub fn human(json: bool) -> bool {
125    let forced = std::env::var("FATS_HUMAN").ok().and_then(|v| crate::settings::boolean(&v));
126    let agent = json || cfg!(test) || crate::cli::FENCE.get().is_some();
127    !agent && forced.unwrap_or_else(|| std::io::stdout().is_terminal())
128}
129
130/// The help a human gets: `help` first (`fats help mcp` = its `help-<topic>` screen) or a help flag anywhere;
131/// None = no help asked (the agent's `--help` is the card, `parse`).
132pub fn help_screen(argv: &[String]) -> Option<String> {
133    let first = argv.first().is_some_and(|a| a.eq_ignore_ascii_case("help"));
134    let topic = argv.get(1).filter(|_| first).map(|t| screen(&format!("help-{}", t.to_lowercase())));
135    let text = topic.filter(|t| !t.is_empty()).unwrap_or(screen("help"));
136    (first || argv.iter().any(|a| HELP_FLAGS.contains(&a.as_str()))).then(|| paint(text, &NO_HOLES))
137}
138
139/// A human's keyless failure: a page the free fetch could not read, or a search, while no paid provider is keyed
140/// (and on) → the tip to add one (`tip-page`, `tip-search`) instead of the `! no_key` rows; None for anything else.
141pub fn tip(cmd: &Cmd, out: &Out, search: bool) -> Option<String> {
142    let paid = crate::fetch::keyed().iter().any(|t| t.spec().price > 0.0);
143    let keyless = !paid && out.rc != 0 && out.parts.is_empty() && out.lines.iter().any(|l| l.contains("! no_key "));
144    let page = |u: &String| paint(screen("tip-page"), &[("site", crate::fetch::site(u))]);
145    let tip = if search { Some(paint(screen("tip-search"), &NO_HOLES)) } else { cmd.urls.first().map(page) };
146    tip.filter(|_| keyless && cmd.urls.len() < 2 && cmd.verb.is_none() && !cmd.flag("dry"))
147}
148
149static BIN: OnceLock<String> = OnceLock::new();
150
151/// Hints echo argv[0]'s file name, so they run as printed; an `.exe` is dropped (on Windows argv[0] is often the
152/// file a launcher found, `fats.exe`, while `fats` is what a user types there too).
153pub fn bin() -> &'static str {
154    BIN.get_or_init(|| {
155        let p = std::path::PathBuf::from(std::env::args().next().unwrap_or_default());
156        let name = p.extension().filter(|e| e.eq_ignore_ascii_case("exe")).map_or(p.file_name(), |_| p.file_stem());
157        name.map(|f| f.to_string_lossy().into_owned()).filter(|s| !s.is_empty()).unwrap_or_else(|| "fats".into())
158    })
159}
160
161/// THE error table (`src/data/errors.json`): every `!` code → the one command that fixes it (a full fix command,
162/// never the same failing retry; a 404's site home is none). `{b}` = the binary, `{id}` `{url}` = the page,
163/// `{arg}` = a value only the caller knows (the cost wanted, the dir, the nearest command this build runs, the
164/// timed-out tier's move). A `*` key matches a code prefix. Walls go to Oxylabs with JavaScript; a PDF a provider
165/// sent as a page or cut short goes to Bright Data (its raw bytes are the exact file); transient codes retry the
166/// same call.
167pub static FIX: LazyLock<Vec<(&str, &str)>> = LazyLock::new(|| crate::settings::table("errors"));
168/// The fix for a code the table does not know (an old snapshot's): the transient retry.
169const RETRY: &str = "{b} {id} fresh:true";
170
171/// Where a `!` row points: the page id, its URL, the table's `{arg}`, and the tiers this run already tried or
172/// cannot use (`fetch::spent`).
173#[derive(Default)]
174pub struct At<'a> {
175    pub id: &'a str,
176    pub url: &'a str,
177    pub arg: &'a str,
178    pub done: &'a [&'a str],
179}
180
181/// The fix for a code; a code the table does not know (an old snapshot's) gets the transient retry. A fix that
182/// would send a tier in `At::done` (`provider:bd`; `js:true` = oxyjs) is the same failing call: the row says
183/// nothing is left instead.
184pub fn fix(code: &str, at: &At) -> String {
185    let hit = |k: &str| k.strip_suffix('*').map_or(k == code, |p| code.starts_with(p));
186    let t = FIX.iter().find(|r| hit(r.0)).map_or(RETRY, |r| r.1);
187    // a missing key the environment holds (`settings::env_key`, never sent) is copied in, never typed again
188    let env = code == "no_key" && crate::settings::env_key(at.arg).is_some();
189    let f = draw(t, &[("b", bin()), ("id", at.id), ("url", at.url), ("arg", if env { "import-env" } else { at.arg })]);
190    // a missing key's move: a human at a terminal runs its setup; an agent runs it itself and hands the user the
191    // numbered steps it prints (read as a command for the user, an agent asked a plain user to run it)
192    if code == "no_key" && !at.arg.is_empty() && !env && HUMAN.get() != Some(&true) {
193        return format!("run {f}, give the user its 3 lines");
194    }
195    // `js:true` = the table's first render rung (`Tier::renders`: oxyjs), the render it adds to bd's
196    let js = f.split(' ').any(|w| w == "js:true");
197    let js = js.then(|| crate::provider::Tier::ALL.into_iter().find(|t| t.renders())).flatten().map(|t| t.spec().short);
198    // the last `provider:` wins, as in `Cmd::get` (a search's `{id}` is its command, mods included)
199    let tier = js.or(f.split(' ').filter_map(|w| w.strip_prefix("provider:")).next_back());
200    // a mod already in force (`max_bytes:64m` at the ceiling) is the same failing call too
201    let sent = tier.is_some_and(|t| at.done.contains(&t));
202    let barred = sent || f.split(' ').any(|w| w.contains(':') && at.done.contains(&w));
203    // After a render that ran, a keyed paid tier this run did not call (one the site's wear skipped) is the
204    // move, never "nothing left"; after a provider's refusal too (it said nothing of the page: bd
205    // refused after oxy → oxyjs), never after a page's no-JS failure (`not_pdf`: a render brings no PDF)
206    if sent
207        && (js.is_some() || crate::provider::REFUSED.contains(&code))
208        && let Some((_, arrow)) = crate::fetch::left_ask(at.id, at.url, &crate::provider::Tier::ALL, at.done, |_| true)
209    {
210        return arrow;
211    }
212    if barred {
213        let open = if at.url.is_empty() { String::new() } else { format!(" · open {} in a browser", at.url) };
214        return format!("nothing left to try{open}");
215    }
216    // a mod the fix sets replaces the command's own (`provider:bd … provider:oxy` → `… provider:oxy`)
217    let toks: Vec<&str> = f.split(' ').filter(|w| !w.is_empty()).collect();
218    fn key(w: &str) -> Option<&str> {
219        w.split_once(':').map(|p| p.0).filter(|k| WORDS.keys.contains(k))
220    }
221    let later = |i: usize| key(toks[i]).is_some_and(|k| toks[i + 1..].iter().any(|w| key(w) == Some(k)));
222    let f = toks.iter().enumerate().filter(|&(i, _)| !later(i)).map(|p| *p.1).collect::<Vec<_>>().join(" ");
223    // the command is quoted (`priced`); a retry after a provider's unbilled error says so
224    let (cmd, rest) = f.split_once(", ").map_or((f.as_str(), ""), |(c, _)| (c, &f[c.len()..]));
225    let quoted = priced(cmd, at.url);
226    // a raised `cost:` that can buy nothing here (no paid tier keyed: `≤$0`) is a key's move, never a free retry
227    if code == "budget_hit" && quoted == cmd {
228        return fix("no_key", &At::default());
229    }
230    let free = quoted != cmd && crate::provider::REFUSED.contains(&code);
231    format!("{quoted}{}{rest}", if free { " · last try not charged" } else { "" })
232}
233
234/// THE price glyph. An arrow whose command can spend (`fresh:`, `js:`, `provider:`,
235/// `timeout:`) ends with the most it can, `≤$0.0030` = `dry:true`'s `up to` for it (`fetch::worst`).
236pub fn priced(cmd: &str, url: &str) -> String {
237    let c = crate::fetch::worst(cmd, url).map_or(0.0, |r| r.1);
238    if c > 0.0 { format!("{cmd} ≤${c:.4}") } else { cmd.into() }
239}
240
241/// A `!`: what is missing (`code`), its measure (`what`), the next command (`next`, "" = none). `row`: it also
242/// gets its own `{id} ! …` row, and the `=` line names only its code (`outline::flags`).
243#[derive(Default)]
244pub struct Flag {
245    pub code: String,
246    pub what: String,
247    pub next: String,
248    pub row: bool,
249}
250
251impl Flag {
252    /// THE `!` printer: `{subject} ! {code} {what} → {next}`, every `!` row (`body` = the `=` line's flags).
253    pub fn bang(&self, subject: &str) -> String {
254        format!("{subject} ! {}", self.body()).trim_start().to_string()
255    }
256
257    /// `{code} {what} → {next}`, one code of a `!` group.
258    pub fn body(&self) -> String {
259        let head = [&self.code, &self.what].iter().filter(|s| !s.is_empty()).map(|s| s.as_str()).collect::<Vec<_>>();
260        if self.next.is_empty() { head.join(" ") } else { format!("{} → {}", head.join(" "), self.next) }
261    }
262}
263
264/// A stored `! {code} {what} → {fix}{ · pages}` row (`fetch::skipped`) with the reader's arrow: the table's fix for
265/// its code and `cost:` arg, as `id`, priced for `url` (the writer's binary, id and price; another build's
266/// `fats-xyz setup`); the accounts' pages after it kept.
267pub fn restamp(row: &str, id: &str, url: &str) -> String {
268    let ((head, f), code) = (row.split_once(" → ").unwrap_or((row, "")), row.split(' ').nth(1).unwrap_or_default());
269    // `{arg}` read back: the stored arrow's `cost:`/`zone:` value, else, in a fix naming no page, the switch the
270    // row names (`! no_key oxy`, `! off free`), never the stored arrow's wording (a human's or an agent's)
271    let t = FIX.iter().find(|r| r.0 == code).map_or("", |r| r.1);
272    let named = row.split(' ').nth(2).filter(|_| t.contains("{arg}") && !t.contains("{id}"));
273    let arg =
274        f.split(' ').find_map(|w| w.strip_prefix("cost:").or(w.strip_prefix("zone:"))).or(named).unwrap_or_default();
275    format!("{head} → {}{}", fix(code, &At { id, url, arg, done: &[] }), f.find(" · ").map_or("", |i| &f[i..]))
276}
277
278/// A `!` row with the table's fix: `{subject} ! {code} {detail} → {fix}` (`Flag::bang`).
279pub fn bang(subject: &str, code: &str, detail: &str, at: &At) -> String {
280    Flag { code: code.into(), what: detail.into(), next: fix(code, at), row: true }.bang(subject)
281}
282
283/// The items of `it` whose `key` was not seen before, in order (distinct words, one row per account).
284pub fn uniq<T, K: PartialEq>(it: impl IntoIterator<Item = T>, key: impl Fn(&T) -> K) -> Vec<T> {
285    let mut out: Vec<T> = Vec::new();
286    for x in it {
287        if !out.iter().any(|o| key(o) == key(&x)) {
288            out.push(x);
289        }
290    }
291    out
292}
293
294/// First n chars.
295pub fn cut(s: &str, n: usize) -> &str {
296    s.char_indices().nth(n).map_or(s, |(i, _)| &s[..i])
297}
298
299pub fn ksize(n: usize) -> String {
300    match n {
301        0..1000 => n.to_string(),
302        1000..1_000_000 => format!("{:.1}k", n as f64 / 1e3),
303        _ => format!("{:.1}M", n as f64 / 1e6),
304    }
305}
306
307/// A byte size as people write caps: `16 MiB`, `512 KiB`.
308pub fn mib(n: u64) -> String {
309    if n >= 1 << 20 { format!("{:.0} MiB", n as f64 / (1u64 << 20) as f64) } else { format!("{} KiB", n >> 10) }
310}
311
312/// URL without scheme and `www.`, trimmed to n chars.
313pub fn short(url: &str, n: usize) -> String {
314    let s = url.strip_prefix("https://").or_else(|| url.strip_prefix("http://")).unwrap_or(url);
315    let s = if s != url { s.strip_prefix("www.").unwrap_or(s) } else { s };
316    if s.chars().count() <= n { s.to_string() } else { format!("{}…", cut(s, n - 1)) }
317}
318
319#[derive(Clone, Copy, PartialEq, Debug)]
320pub enum Match {
321    Exact,
322    Words,
323    Near,
324    Topic,
325}
326
327/// The `match:` values, in `Match` order.
328const MATCH: [&str; 4] = ["exact", "words", "near", "topic"];
329
330impl Match {
331    pub fn name(self) -> &'static str {
332        MATCH[self as usize]
333    }
334}
335
336#[derive(Clone, Copy, Debug, PartialEq, Default)]
337pub struct Id {
338    pub job: Option<usize>,
339    pub u: usize,
340    pub sec: Option<usize>,
341    pub part: usize,
342}
343
344impl Id {
345    fn parse(t: &str) -> Option<Id> {
346        let (job, rest) = match t.strip_prefix('j').and_then(|r| r.split_once('.')) {
347            Some((j, r)) => (Some(num(j)?), r),
348            None => (None, t),
349        };
350        let rest = rest.strip_prefix('u')?;
351        let (u, sec) = rest.split_once('#').map_or((rest, None), |(u, s)| (u, Some(s)));
352        let mut id = Id { job, u: num(u)?, ..Id::default() };
353        if let Some(s) = sec {
354            let d = s.trim_end_matches(|c: char| c.is_ascii_lowercase());
355            id.sec = Some(num(d)?);
356            id.part = part_of(&s[d.len()..])?;
357        }
358        Some(id)
359    }
360
361    /// The section part as typed: `#3`, `#3b`; empty for a page.
362    pub fn sec_tail(&self) -> String {
363        let part = if self.part > 0 { letters(self.part) } else { String::new() };
364        self.sec.map(|k| format!("#{k}{part}")).unwrap_or_default()
365    }
366
367    pub fn page(&self) -> String {
368        format!("{}u{}", self.job.map(|j| format!("j{j}.")).unwrap_or_default(), self.u)
369    }
370}
371
372/// Part suffix of a section id, bijective base 26: part 0 = `a` (or none) … 25 = `z`, 26 = `aa`, 27 = `ab` ….
373pub fn letters(part: usize) -> String {
374    let (mut n, mut out) = (part + 1, Vec::new());
375    while n > 0 {
376        n -= 1;
377        out.push(b'a' + (n % 26) as u8);
378        n /= 26;
379    }
380    out.iter().rev().map(|&b| b as char).collect()
381}
382
383/// Inverse of `letters`; "" = part 0. None = too long to be a real part.
384fn part_of(s: &str) -> Option<usize> {
385    Some(s.bytes().try_fold(0usize, |n, b| n.checked_mul(26)?.checked_add((b - b'a') as usize + 1))?.saturating_sub(1))
386}
387
388/// `since:` → the first day it admits (`YYYY-MM-DD`), counted back from `today` (days since 1970-01-01):
389/// `7d` `2w` `3m` (30 days) `1y`, or a date `2026` `2026-01` `2026-01-15`. None = not a `since:` value.
390pub fn since_date(v: &str, today: i64) -> Option<String> {
391    let unit =
392        v.chars().last().and_then(|u| [('d', 1), ('w', 7), ('m', 30), ('y', 365)].into_iter().find(|x| x.0 == u));
393    if let Some((_, days)) = unit {
394        let count = num(&v[..v.len() - 1])?.min(100_000) as i64;
395        let (year, month, day) = civil(today - count * days);
396        return Some(format!("{year:04}-{month:02}-{day:02}"));
397    }
398    let parts: Vec<&str> = v.split('-').collect();
399    let ok = |s: &&str, len: usize, hi: usize| s.len() == len && num(s).is_some_and(|n| (1..=hi).contains(&n));
400    let fine = parts.len() <= 3 && ok(&parts[0], 4, 9999) && parts.get(1).is_none_or(|m| ok(m, 2, 12));
401    (fine && parts.get(2).is_none_or(|d| ok(d, 2, 31)))
402        .then(|| format!("{}-{}-{}", parts[0], parts.get(1).unwrap_or(&"01"), parts.get(2).unwrap_or(&"01")))
403}
404
405/// Days since 1970-01-01 → (year, month, day), proleptic Gregorian (chrono's range is ±262,000 years).
406pub fn civil(z: i64) -> (i32, u32, u32) {
407    let d = chrono::DateTime::from_timestamp(z * 86_400, 0).unwrap_or_default().date_naive();
408    (d.year(), d.month(), d.day())
409}
410
411/// `20`, `1k`, `1.5k` → a count ≥ 1.
412fn count(s: &str) -> Option<usize> {
413    let (n, k) = s.strip_suffix(['k', 'K']).map_or((s, 1.0), |n| (n, 1000.0));
414    let x = n.parse::<f64>().ok().filter(|x| x.is_finite() && *x > 0.0)? * k;
415    (1.0..1e9).contains(&x).then_some(x as usize)
416}
417
418/// Whole seconds (`5`, `5s`) within `lo..=hi`.
419fn secs(s: &str, lo: u64, hi: u64) -> Option<u64> {
420    s.strip_suffix('s').unwrap_or(s).parse().ok().filter(|n| (lo..=hi).contains(n))
421}
422
423/// A byte size: `512k`, `32m` (binary units, `kb`/`mib` spellings too) or plain bytes.
424fn bytes(s: &str) -> Option<u64> {
425    let l = s.to_ascii_lowercase();
426    let n = l.trim_end_matches(['b', 'i']);
427    let kib = || n.strip_suffix('k').map_or((n, 0), |n| (n, 10));
428    let (n, shift) = n.strip_suffix('m').map_or_else(kib, |n| (n, 20));
429    n.parse::<u64>().ok()?.checked_mul(1 << shift)
430}
431
432fn num(s: &str) -> Option<usize> {
433    (!s.is_empty() && s.bytes().all(|b| b.is_ascii_digit())).then(|| s.parse().ok()).flatten()
434}
435
436#[derive(Default, Debug)]
437pub struct Cmd {
438    pub ids: Vec<Id>,
439    /// Bare job ids (`j3`): the job's command and pages.
440    pub jobs: Vec<usize>,
441    pub links: Vec<usize>,
442    /// Media rows of the page (`u3 m1`): the picture itself, fetched on demand (`cli::asset`).
443    pub media: Vec<usize>,
444    pub urls: Vec<String>,
445    pub files: Vec<String>,
446    pub reserved: Vec<&'static str>,
447    pub words: Vec<String>,
448    pub mods: Vec<(String, String)>,
449    /// A settings change's words (`setup free off`, `config set batch_parallel 8`): never a search (`stats::change`).
450    pub sub: Vec<String>,
451    /// The verb as typed (`search`), first among the non-mod tokens: printed first again, so a replay reads the
452    /// same (`search login` stays a search).
453    pub verb: Option<String>,
454    /// Nothing to act on, mods and `json` aside, or a `?` (`fats`, `fats search`, `fats -v`): the status, and no
455    /// arrow leads to it. A lone `site:` is a search, never idle.
456    pub idle: bool,
457    /// A usage problem: the `?` line to print (exit 2).
458    pub ask: Option<String>,
459    pub raw: String,
460}
461
462impl Cmd {
463    pub fn has(&self, r: &str) -> bool {
464        self.reserved.contains(&r)
465    }
466
467    pub fn get(&self, k: &str) -> Option<&str> {
468        self.mods.iter().rev().find(|(a, _)| a == k).map(|(_, v)| v.as_str())
469    }
470
471    pub fn flag(&self, k: &str) -> bool {
472        self.get(k) == Some("true")
473    }
474
475    /// Past the cache: `fresh:true`, or `js:true` (a render: what `! js_shell` and `! thin` ask for).
476    pub fn fresh(&self) -> bool {
477        self.flag("fresh") || self.flag("js")
478    }
479
480    /// A count mod (`limit:20`, `max:1k`); validated by the parser, so None = absent.
481    pub fn count(&self, k: &str) -> Option<usize> {
482        self.get(k).and_then(count)
483    }
484
485    /// Canonical form (what the repair table maps every input onto): ids, URLs, files, reserved words, the free
486    /// words as typed, then the mods (a fix arrow keeps the user's query in front, as typed).
487    pub fn canon(&self) -> String {
488        self.with_mod("", None)
489    }
490
491    /// The canonical command with mod `k` set to `v` (None = dropped): the `→` fix of a mod row.
492    pub fn with_mod(&self, k: &str, v: Option<&str>) -> String {
493        let mut p: Vec<String> = self.verb.iter().cloned().collect();
494        p.extend(self.ids.iter().map(|i| i.page() + &i.sec_tail()));
495        p.extend(self.jobs.iter().map(|j| format!("j{j}")));
496        p.extend(self.links.iter().map(|l| format!("l{l}")));
497        p.extend(self.media.iter().map(|m| format!("m{m}")));
498        p.extend(self.urls.iter().cloned());
499        p.extend(self.files.iter().cloned());
500        p.extend(self.reserved.iter().map(|r| r.to_string()));
501        p.extend(self.words.iter().cloned());
502        p.extend(self.mods.iter().filter(|(a, _)| a != k).map(|(k, v)| format!("{k}:{v}")));
503        p.extend(v.map(|v| format!("{k}:{v}")));
504        p.join(" ")
505    }
506}
507
508fn is_url(t: &str) -> bool {
509    let l = t.to_ascii_lowercase();
510    if let Some(r) = l.strip_prefix("https://").or_else(|| l.strip_prefix("http://")) {
511        return !r.is_empty();
512    }
513    // [a-z0-9-]+(\.[a-z0-9-]+)*\.[a-z]{2,}(/\S*)?
514    let host = l.split('/').next().unwrap_or("");
515    let labels: Vec<&str> = host.split('.').collect();
516    labels.len() >= 2
517        && labels.iter().all(|x| !x.is_empty() && x.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-'))
518        && labels.last().is_some_and(|x| x.len() >= 2 && x.bytes().all(|b| b.is_ascii_alphabetic()))
519}
520
521/// The last label of a bare name (no scheme, no `/`): it names a host only when it is a real TLD (`Words::tlds`:
522/// `opencode.json`, `main.go` are words) and the name stands where an address is typed (`as_words`). A scheme, a
523/// `/` or `site:` makes a host by its shape alone (`is_url`).
524fn bare_tld(low: &str) -> Option<&str> {
525    low.rsplit_once('.').filter(|_| !low.contains('/')).map(|(_, tld)| tld)
526}
527
528/// A URL's host by its name alone, no lookup (`dry:true` spends nothing, the network included): an IP address, or
529/// a name whose last label is a real TLD (`Words::tlds`) a resolver can ask for (`askable`). False = `no_host`:
530/// `dead.invalid`, `intranet`, `a..com`, `-a.com`, a 64-char label, none.
531pub fn real_host(url: &str) -> bool {
532    let host = crate::clean::host_of(url);
533    let tld = host.strip_suffix('.').unwrap_or(&host).rsplit('.').next().unwrap_or_default();
534    host.parse::<std::net::IpAddr>().is_ok() || (WORDS.tlds.contains(&tld) && askable(&host))
535}
536
537/// A name a resolver can ask for, by its shape alone (never its TLD: a test's `*.invalid` is one): every label
538/// 1–63 chars, no hyphen at either end (RFC 1035 §2.3.1, §2.3.4; one root dot may end the name). The real run's
539/// rule too: `provider::host_check` never looks the rest up.
540pub fn askable(host: &str) -> bool {
541    let label_ok = |l: &str| (1..=63).contains(&l.len()) && !l.starts_with('-') && !l.ends_with('-');
542    host.strip_suffix('.').unwrap_or(host).split('.').all(label_ok)
543}
544
545/// A path is a path only when it says so: `-`, a leading `/`, a `shaped` token (`class_of`), a document or secret
546/// extension or name (`page.html`, `a.pdf`, `id.pem`, `id_rsa`: `fetch::doc_kind`, `cli::secret`; alone, missing:
547/// `no_file`), or any name that is a file here (`README`; the fence first, then one stat). With an id in the command
548/// only explicit paths count (free text wins: `u1 price`). Beside search words only a `shaped` or extended path stays
549/// one whether it exists or not, and `-` must be the whole command (`as_words`). A missing one-dot name whose extension
550/// is a document's AND a real TLD (`notes.md`) is a file or a site: Err = the `?` that asks which (`file_or_site`), $0.
551fn is_file(t: &str, any_id: bool) -> Result<bool, String> {
552    if t == "-" || t.starts_with('/') {
553        return Ok(true);
554    }
555    let ext = Path::new(t).extension().map(|e| e.to_string_lossy().to_ascii_lowercase());
556    let doc = ext.as_ref().is_some_and(|e| crate::fetch::doc_kind(&format!(".{e}")).is_some());
557    let file = !any_id && !t.contains("://") && (doc || filed(Path::new(t)) || crate::cli::secret(Path::new(t)));
558    match file_or_site(t, &WORDS.tlds).filter(|_| file && doc) {
559        Some(q) => Err(q),
560        None => Ok(file),
561    }
562}
563
564/// A one-dot name (no `/`; a `\` is `shaped`) whose TLD is in `tlds` and that is no file here: the `?` that asks
565/// file or site, $0 (`is_file`; a lone `main.rs`, `parse`).
566fn file_or_site(t: &str, tlds: &[&str]) -> Option<String> {
567    let tld = bare_tld(&t.to_lowercase()).filter(|d| tlds.contains(d) && t.matches('.').count() == 1).is_some();
568    (tld && !filed(Path::new(t))).then(|| format!("? {t}: a missing file or a site · type ./{t} or https://{t}"))
569}
570
571/// A token shaped as a path whatever stands beside it: a `./ ../ file:` prefix, a dot-led name (`.env`, `.ssh`; `.NET`,
572/// `.io` lead a TLD: words; `.5` and `...` no name), a home (`~/`, `~name/`) or a variable (`$HOME/`, `${HOME}/`)
573/// leading a `/`, a `\` path's lead (`.\x`, `..\x`, `~\x`, `\\server\share`; a `\` elsewhere is a word's beside a page,
574/// `u1 price\|cost`, and a path's on a search, `parse`), a drive (`C:/x`, `C:\x`), a `/` path of ≥ 2 non-empty segments
575/// (`/etc/hosts`; `/DE/` is one: beside words a search word, `as_words`), or a bare one of ≥ 3 that no host leads
576/// (`internal/hr/salaries`; `TCP/IP` is a word, `docs.rs/a/b` a URL). A name of digits leads no home or variable:
577/// `~5/10`, `$5/mo` are words.
578fn shaped(t: &str) -> bool {
579    let (b, low) = (t.as_bytes(), t.to_ascii_lowercase());
580    let drive = b.len() > 2 && b[0].is_ascii_alphabetic() && b[1] == b':' && matches!(b[2], b'/' | b'\\');
581    let segments = t.split('/').filter(|s| !s.is_empty()).count();
582    let deep = if t.starts_with('/') { segments >= 2 } else { segments >= 3 && !is_url(t) && !t.contains(':') };
583    // the name after `~` `$` `.` up to a `/`: a letter, `_` or `{` first; after `.` no TLD (`.NET`, `.io`)
584    let name = |r: &str, dot: bool| {
585        let n = r.split('/').next().unwrap_or_default();
586        n.starts_with(|c: char| c.is_ascii_alphabetic() || "_{".contains(c)) && !(dot && WORDS.tlds.contains(&n))
587    };
588    let home = |s: char| low.strip_prefix(s).is_some_and(|r| r.contains('/') && name(r, false));
589    let dot = low.strip_prefix('.').is_some_and(|r| name(r, true));
590    let lead = ["./", "../", "~/", "file:", ".\\", "..\\", "~\\", "\\\\"].iter().any(|p| low.starts_with(p));
591    drive || deep || home('~') || home('$') || dot || lead
592}
593
594/// A local path as the shell would read it: `~/` is the home directory (`$HOME`; on Windows `%USERPROFILE%`, as
595/// Node's `os.homedir()` reads it for Claude Code and Cursor).
596pub fn local_path(f: &str) -> std::path::PathBuf {
597    f.strip_prefix("~/").map_or_else(|| f.into(), |r| std::env::home_dir().unwrap_or_default().join(r))
598}
599
600/// A file here, or a path the `fats mcp` fence refuses by its name alone (`cli::outside`): out there the disk is
601/// never looked at, and the path stays a path (`not_allowed`). A bare name never stands outside.
602fn filed(p: &Path) -> bool {
603    crate::cli::outside(p) || p.is_file()
604}
605
606/// Normalise one `key:value` (aliases, liberal booleans). Err = the `?` line.
607fn modifier(k: &str, v: &str) -> Result<(String, String), String> {
608    let (k, v) = alias(&k.to_ascii_lowercase(), v)?;
609    // a threshold for this command (`batch_parallel:8`, `settings::limit_of`)
610    if let Some(built) = crate::settings::LIMITS.get(k.as_str()) {
611        let fit = crate::settings::fits(&k, &v).map(|_| (k.clone(), v.clone()));
612        return fit.ok_or(format!("? {k}:{v} · a number like {k}:{built}"));
613    }
614    if !WORDS.keys.contains(&k.as_str()) {
615        return Err(format!("? {k}: unknown · keys {}", WORDS.keys.join(" ")));
616    }
617    value(&k, v).map(|v| (k, v))
618}
619
620/// A key that is no mod, alias or threshold and not one edit from a mod: a search word as typed (`og:image`,
621/// `schema:org`); a mistyped mod (`wiat:30`, `jsn:true`) asks.
622fn free_key(k: &str, v: &str) -> bool {
623    let k = k.to_ascii_lowercase();
624    let near = WORDS.keys.iter().any(|m| strsim::osa_distance(&k, m) < 2);
625    // an alias (`n:`, `geo:`) renames its key, or errs on its value (`loose:x`)
626    !near && alias(&k, v).is_ok_and(|a| a.0 == k) && !crate::settings::LIMITS.contains_key(k.as_str())
627}
628
629/// A key's other spellings (`n` `geo` `budget` `ua` `loose`) → (key, value).
630fn alias(k: &str, v: &str) -> Result<(String, String), String> {
631    let (k, v) = match k {
632        "n" => ("limit", v.to_string()),
633        "geo" | "loc" | "gl" | "country" => ("country", v.to_ascii_lowercase()),
634        "budget" => ("cost", v.to_string()),
635        "device" | "ua" => match v.to_ascii_lowercase().as_str() {
636            "mobile" | "phone" => ("device", "mobile".into()),
637            "desktop" | "pc" => ("device", "desktop".into()),
638            _ => return Err(format!("? device:{v} · use device:mobile|desktop (Oxylabs only)")),
639        },
640        "loose" => {
641            let n: u32 =
642                v.parse().map_err(|_| format!("? loose:{v} · loose takes 0..100 · or match:exact|words|near|topic"))?;
643            // 0 exact · 1-49 words · 50-79 near · 80+ topic (`MATCH` order)
644            ("match", MATCH[[1, 50, 80].iter().filter(|&&lo| n >= lo).count()].into())
645        }
646        _ => (k, v.to_string()),
647    };
648    Ok((k.to_string(), v))
649}
650
651/// A known key's value, checked and normalised (`js:1` → `true`, `hedge:5s` → `5`). Err = the `?` line.
652fn value(k: &str, v: String) -> Result<String, String> {
653    if WORDS.bools.contains(&k) {
654        let b = crate::settings::boolean(&v).ok_or_else(|| format!("? {k}:{v} · use {k}:true or {k}:false"))?;
655        return Ok(b.to_string());
656    }
657    let n = match k {
658        "hedge" => secs(&v, 0, 60).ok_or("hedge:{v} · seconds before the second provider, 0 to 60: hedge:0"),
659        "wait" => secs(&v, 0, 300).ok_or("wait:{v} · seconds before a fetch answers pending, 0 to 300: wait:30"),
660        "timeout" => secs(&v, 1, 300).ok_or("timeout:{v} · seconds for bd and oxyjs, 1 to 300: timeout:150"),
661        "max_bytes" => bytes(&v)
662            .filter(|n| (1 << 10..=crate::cli::MAX_BYTES_CEIL).contains(n))
663            .ok_or("max_bytes:{v} · 1k to 64m (KiB, MiB): max_bytes:32m"),
664        "fetch" => v.parse().ok().filter(|n| *n <= 50).ok_or("fetch:{v} · results to fetch ahead, 0 to 50: fetch:0"),
665        "limit" | "max" | "from" => count(&v).map(|n| n as u64).ok_or("{k}:{v} · {k} takes a count: {k}:20 · {k}:1k"),
666        _ => return text_value(k, v),
667    };
668    n.map(|n| n.to_string()).map_err(|q| format!("? {}", draw(q, &[("k", k), ("v", &v)])))
669}
670
671/// `value` for the keys whose value is a word: `match` `provider` `country` `since` `site` `cost`.
672fn text_value(k: &str, v: String) -> Result<String, String> {
673    let (ok, why) = match k {
674        "match" => (MATCH.contains(&v.as_str()), "use match:exact|words|near|topic"),
675        "country" => {
676            (v.len() == 2 && v.bytes().all(|b| b.is_ascii_alphabetic()), "two letters: country:de · country:us")
677        }
678        "zone" => (
679            v.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-'),
680            "a Bright Data zone name: zone:web_unlocker1",
681        ),
682        "since" => (since_date(&v, 0).is_some(), "an age or a date: since:7d · since:2w · since:2026-01"),
683        "cost" => {
684            (v.parse::<f64>().is_ok_and(|x| x.is_finite() && x >= 0.0), "cost takes US dollars per call: cost:0.5")
685        }
686        "provider" => {
687            // a JS rung is `provider:oxy js:true`, not a provider of its own (`Tier::renders`)
688            use crate::provider::Tier;
689            let t = Tier::parse(&v.to_ascii_lowercase()).filter(|t| !t.renders());
690            let p = t.map(|t| t.spec().short).or((v.eq_ignore_ascii_case("auto")).then_some("auto"));
691            let all: Vec<&str> = Tier::ALL.iter().filter(|t| !t.renders()).map(|t| t.spec().short).collect();
692            return p.map(String::from).ok_or(format!("? provider:{v} · use provider:auto|{}", all.join("|")));
693        }
694        "site" => {
695            let s = v.to_ascii_lowercase();
696            let s = s.strip_prefix("https://").or(s.strip_prefix("http://")).unwrap_or(&s).trim_end_matches('/');
697            let host = is_url(s).then(|| s.to_string());
698            return host.ok_or(format!("? site:{v} · a host: site:example.com · site:docs.rs/serde"));
699        }
700        _ => (true, ""),
701    };
702    if ok { Ok(v) } else { Err(format!("? {k}:{v} · {why}")) }
703}
704
705/// Token-level repairs. Pure; one canonical reading or a `?` line. Beside the tokens: the reserved words typed as a
706/// flag (`--cards` → `cards`), so a search never takes one as a word (`flag_word`).
707fn repair(argv: &[String]) -> (Vec<String>, Vec<String>) {
708    let s = argv.join(" ");
709    let s = s.trim().trim_matches('`').trim();
710    let s = s.strip_prefix("fats ").unwrap_or(s);
711    let (mut out, mut flagged): (Vec<String>, Vec<String>) = (Vec::new(), Vec::new());
712    let mut it = s.split_whitespace().map(|t| t.trim_matches(|c| matches!(c, '"' | '\'' | '`'))).peekable();
713    while let Some(t) = it.next() {
714        // a bare `--` ends options in a shell, it is no word (`fats -- rust` searches "rust")
715        if t.is_empty() || t == "--" {
716            continue;
717        }
718        let mut t = t.to_string();
719        // U2#3 → u2#3 · u2.3 → u2#3 · j8/u2 j8:u2 → j8.u2
720        if t.starts_with(['U', 'J']) && t[1..].starts_with(|c: char| c.is_ascii_digit()) {
721            t = t.to_lowercase();
722        }
723        let job =
724            t.split_once(['/', ':']).filter(|(a, b)| a.strip_prefix('j').and_then(num).is_some() && b.starts_with('u'));
725        if let Some((a, b)) = job {
726            t = format!("{a}.{b}");
727        }
728        let sec = t.strip_prefix('u').and_then(|r| r.split_once('.')).filter(|(a, b)| num(a).and(num(b)).is_some());
729        if let Some((a, b)) = sec {
730            t = format!("u{a}#{b}");
731        }
732        // the output switches -v → verbose:true, --json → json:true · --full → full · -n 20 / n=20 → limit:20 ·
733        // key=value → key:value; `--help` stays a flag
734        if let Some(on) = [("-v", "verbose:true"), ("--json", "json:true")].iter().find(|s| s.0 == t) {
735            t = on.1.into();
736        } else if let Some(r) = t.strip_prefix("--").filter(|r| *r != "help" && WORDS.reserved.contains(r)) {
737            t = r.to_string();
738            flagged.push(t.clone());
739        } else if t == "-n" && it.peek().is_some_and(|n| num(n).is_some()) {
740            t = format!("limit:{}", it.next().unwrap_or_default());
741        } else if let Some((k, v)) = t.split_once('=')
742            && !k.is_empty()
743            && k.bytes().all(|b| b.is_ascii_lowercase())
744            && !v.is_empty()
745        {
746            t = format!("{k}:{v}");
747        }
748        // l 4 → l4 · u2 #3 → u2#3
749        if t == "l" && it.peek().is_some_and(|n| num(n).is_some()) {
750            t = format!("l{}", it.next().unwrap_or_default());
751        }
752        if let (Some(r), Some(prev)) = (t.strip_prefix('#'), out.last_mut())
753            && num(r).is_some()
754            && Id::parse(prev).is_some_and(|i| i.sec.is_none())
755        {
756            prev.push_str(&t);
757            continue;
758        }
759        out.push(t);
760    }
761    (undecorate(out), flagged)
762}
763
764/// A pasted arrow's decorations are no words (`fats u1 js:true · bd, then oxyjs ≤$0.0030 ≈25s`, `u1#3 · 1.5k tok · $0`,
765/// `u2 · rendered`, `config · FATS_CACHE`): on a command led by an id, a job, a URL with its scheme or
766/// `setup`/`stats`/`config`, a `(…)` group (an older build's), a `≤$X` price (`$0` shell-expanded too), a `≈Ns` or
767/// `~Ns` time, and a `·` with the words after it up to the next `key:value` are dropped, wherever they stand. Any other
768/// command keeps them: `rust (programming language)` is a query.
769fn undecorate(toks: Vec<String>) -> Vec<String> {
770    let first = toks.first().map(|t| t.to_ascii_lowercase()).unwrap_or_default();
771    let job = first.strip_prefix('j').and_then(num).is_some();
772    let url = ["http://", "https://"].iter().any(|s| first.starts_with(s));
773    if !(Id::parse(&first).is_some() || job || url || ["setup", "stats", "config"].contains(&first.as_str())) {
774        return toks;
775    }
776    let (mut group, mut dot) = (false, false);
777    let mut keep = |t: &String| {
778        let inside = group || t.starts_with('(');
779        group = inside && !t.ends_with(')');
780        dot = (dot || t == "·") && key_value(t).is_none();
781        let time = t.strip_prefix(['~', '≈']).and_then(|r| r.strip_suffix('s')).is_some_and(|n| num(n).is_some());
782        // `≤` alone: an unquoted shell expands `$0` (`≤zsh.0030`)
783        !(inside || dot || t.starts_with('≤') || time)
784    };
785    toks.into_iter().filter(|t| keep(t)).collect()
786}
787
788/// A `key:value` by its shape (`limit:5`, `filetype:pdf`); a URL's scheme and a path are none.
789fn key_value(t: &str) -> Option<(&str, &str)> {
790    let (k, v) = t.split_once(':')?;
791    let key = !k.is_empty() && k.bytes().all(|b| b.is_ascii_alphabetic() || b == b'_');
792    let scheme = ["http", "https"].contains(&k.to_ascii_lowercase().as_str());
793    (key && !scheme && !v.is_empty() && !v.starts_with('/')).then_some((k, v))
794}
795
796/// The command a word is a typo of (edits = optimal string alignment: a letter changed, added, dropped, or two
797/// neighbours swapped). A lone word: one edit from `commands` (`stts` → `stats`). A first word led
798/// into a URL or id: up to two edits, fewer than half the command's length, from `commands` + `led`
799/// (`fetchh https://x` → `fetch`, `hlep u1` → `help`).
800fn typo(w: &str, led: bool) -> Option<&'static str> {
801    let w = w.to_lowercase();
802    if WORDS.reserved.contains(&w.as_str()) {
803        return None; // a command word itself (`stats` is not a typo of `status`)
804    }
805    let extra = if led { &WORDS.led[..] } else { &[] };
806    let max = |r: &str| if led { 2.min((r.len() - 1) / 2) } else { 1 };
807    WORDS.commands.iter().chain(extra).copied().find(|r| (1..=max(r)).contains(&strsim::osa_distance(&w, r)))
808}
809
810enum Class {
811    Id(Id),
812    Job(usize),
813    Link(usize),
814    Media(usize),
815    Url(String),
816    File(String),
817    Res(&'static str),
818    Mod(String, String),
819    Num(String),
820    Word,
821}
822
823pub fn parse(argv: &[String]) -> Cmd {
824    let (mut toks, flagged) = repair(argv);
825    let mut cmd = Cmd { raw: toks.join(" "), ..Cmd::default() };
826    // a verb is the first token, mods aside (`limit:5 search login`): the words after it are meant as words
827    let lead = toks.iter().position(|t| !matches!(class_of(t, false, false, true), Ok(Class::Mod(..))));
828    cmd.verb = lead.filter(|&i| WORDS.verbs.contains(&toks[i].to_lowercase().as_str())).map(|i| toks.remove(i));
829    if let Some(i) = lead.filter(|_| cmd.verb.is_none()) {
830        own_words(&mut cmd, &mut toks, i);
831    }
832    // `--help` or `-h` anywhere (an en or em dash for `--`: smart punctuation), or `help` first, is the card: never
833    // a paid search for the other words
834    let first_help = cmd.verb.is_none() && lead.is_some_and(|i| toks[i].eq_ignore_ascii_case("help"));
835    if first_help || toks.iter().any(|t| HELP_FLAGS.contains(&t.as_str())) {
836        toks = vec!["help".into()];
837    }
838    let has_id = toks.iter().any(|t| Id::parse(t).is_some());
839    let (mut cls, mut any_id) = (Vec::new(), false);
840    for t in &toks {
841        match class_of(t, has_id, any_id, cmd.verb.is_some()) {
842            // a directory here is no file and no search word (`/etc`, `./src`); outside the `fats mcp` fence the
843            // disk is never looked at: the run says `not_allowed`
844            Ok(Class::File(f)) if !crate::cli::outside(&local_path(&f)) && local_path(&f).is_dir() => {
845                cmd.ask.get_or_insert(format!("? {f} is a directory · name a file in it"));
846            }
847            Ok(c) => {
848                any_id |= matches!(c, Class::Id(_));
849                cls.push((t.clone(), c));
850            }
851            Err(q) => {
852                cmd.ask.get_or_insert(q);
853            }
854        }
855    }
856    as_words(&mut cls);
857    // free words that are all flags (`--login`, `-x`, `limit:5 -x`; an en or em dash for `--`, `–x`) are an option
858    // fats lacks, never a search; any other free word makes every word text, wherever the dash is (doctrine §1:
859    // `git rebase --onto`, `rust -tokio` excludes, `-5 degrees`), as does a verb, an id or a file: beside a page
860    // the words are a free filter (`u1 -n`); beside a URL they would be a paid `site:` search, so refused. The text
861    // keeps a dash as typed.
862    let search = cmd.verb.is_none() && !cls.iter().any(|p| matches!(p.1, Class::Id(_) | Class::File(_)));
863    let words: Vec<&String> = cls.iter().filter(|p| search && matches!(p.1, Class::Word)).map(|p| &p.0).collect();
864    if let Some(t) = words.first().filter(|_| words.iter().all(|t| is_flag(t))) {
865        let name = t.trim_start_matches(['-', '–', '—']);
866        let fix =
867            if WORDS.bools.contains(&name) { format!("mod: {name}:true") } else { format!("keys: {} setup", bin()) };
868        cmd.ask.get_or_insert(format!("! unknown flag {t} · {fix} · help: {} --help", bin()));
869    }
870    // mods and the output mod aside (one `alone` for both): a lone word, or a first word led into a URL or id,
871    // may be a command's typo or a word that names no command
872    let kinds: Vec<&(String, Class)> =
873        cls.iter().filter(|p| !matches!(p.1, Class::Mod(..) | Class::Res("json"))).collect();
874    let led = matches!(kinds[..], [(_, Class::Word), (_, Class::Url(_) | Class::Id(_)), ..]);
875    let (lone, none) = (matches!(kinds[..], [(_, Class::Word)]), kinds.is_empty());
876    // a lone one-dot name ending in a file's extension (`main.rs`) that is no file here is a file or a site: ask, $0
877    if let [(t, Class::Url(_))] = kinds[..]
878        && let Some(q) = file_or_site(t, &WORDS.file_tlds)
879    {
880        cmd.ask.get_or_insert(q);
881    }
882    sort_into(&mut cmd, kinds.len() == 1, cls, any_id);
883    // a `\` inside a word is a filter's beside a page (`u1 price\|cost`); on a search it is a local path's
884    // (`Documents\salaries`), and a path never reaches a search: `no_file`
885    if crate::cli::is_search(&cmd) {
886        (cmd.files, cmd.words) = std::mem::take(&mut cmd.words).into_iter().partition(|w| w.contains('\\'));
887    }
888    flag_word(&mut cmd, &flagged);
889    cmd.idle = none && cmd.get("site").is_none() || cmd.ask.is_some();
890    if cmd.verb.is_none() && (led || lone) {
891        ask_typo(&mut cmd, led);
892    }
893    // a `?`/`!` row is no search: a closing `json` stays its output mod (`whoami json`)
894    if cmd.ask.is_some() && cmd.words.last().is_some_and(|w| w.eq_ignore_ascii_case("json")) {
895        cmd.words.pop();
896        cmd.reserved.push("json");
897    }
898    cmd
899}
900
901/// A reserved word typed as a flag (`--cards`) that became a search word (no page in the command): a `?` with the
902/// two commands it meant, never a paid search for `… cards`.
903fn flag_word(cmd: &mut Cmd, flagged: &[String]) {
904    let page = !(cmd.ids.is_empty() && cmd.urls.is_empty() && cmd.files.is_empty() && cmd.jobs.is_empty());
905    let Some(f) = flagged.iter().find(|f| !page && cmd.words.contains(f)) else { return };
906    let rest = cmd.words.iter().filter(|w| *w != f).map(String::as_str).collect::<Vec<_>>().join(" ");
907    let (b, search) = (bin(), "is a mod, not a search word · search first:");
908    cmd.ask.get_or_insert(format!("? --{f} {search} {b} {rest} · then: {b} u1 {f}"));
909}
910
911/// What one token is. `has_id` = the command holds an id (only explicit paths are files then), `any_id` = an id
912/// came before this token (a URL-looking word after it is text), `verb` = a leading verb was dropped. Err = the `?`
913/// line.
914fn class_of(t: &str, has_id: bool, any_id: bool, verb: bool) -> Result<Class, String> {
915    let low = t.to_lowercase();
916    if let Some(id) = Id::parse(t) {
917        return Ok(Class::Id(id));
918    }
919    if let Some(n) = t.strip_prefix('j').and_then(num) {
920        return Ok(Class::Job(n));
921    }
922    if let Some(n) = t.strip_prefix('l').and_then(num) {
923        return Ok(Class::Link(n));
924    }
925    // `m1` names a picture only next to a page id; alone it is a word (`apple m1 review`)
926    if let Some(n) = t.strip_prefix('m').and_then(num).filter(|_| has_id) {
927        return Ok(Class::Media(n));
928    }
929    if let Some((a, w)) = t.split_once(':')
930        && Id::parse(a).is_some_and(|i| i.sec.is_some())
931        && w.split('-').all(|x| num(x).is_some())
932    {
933        // `u3#2:41-80`: a line window
934        return Err(format!("? {t}: line windows are not in v1 · read the section: {} {a}", bin()));
935    }
936    // a word people type for a command (`login`), never after a verb: `search login` searches it
937    let alias = WORDS.aliases.iter().find(|a| !verb && (a.0 == low || a.0 == t)).map(|a| a.1);
938    if let Some(r) = WORDS.reserved.iter().copied().find(|r| *r == low).or(alias) {
939        return Ok(Class::Res(r));
940    }
941    // beside a page a dot-led word with no path separator is the page's to read (`u5 .data.chains[0]`: a JSON path,
942    // else a filter)
943    if shaped(t) && !low.starts_with("file:") && !(has_id && t.starts_with('.') && !t.contains(['/', '\\'])) {
944        // a drive (`C:\x`) before any `key:value` reading: a path, never `? c: unknown`
945        return Ok(Class::File(t.to_string()));
946    }
947    if low.starts_with("file:") {
948        // a local file (`file:///a/b.pdf` → `/a/b.pdf`, percent-decoded), read like a path (and fenced the same
949        // way under `fats mcp`), never a search. A host is another machine on every OS (the URL parser reads
950        // `localhost` as none; url's `to_file_path` turns a host into a `\\host\share` path on Windows only)
951        let path = url::Url::parse(t).ok().filter(|u| u.scheme() == "file" && u.host().is_none());
952        let path = path.and_then(|u| u.to_file_path().ok()).map(|p| Class::File(p.to_string_lossy().into_owned()));
953        return path.ok_or(format!("? {t}: a file URL names a local path: {} /path/to/file", bin()));
954    }
955    if let Some((k, v)) = key_value(t) {
956        // a search engine's own query key (`filetype:pdf`) goes to the search as typed, a free key too (`og:image`);
957        // beside an id a key can only be a mod: an unknown one asks
958        if WORDS.operators.contains(&k.to_ascii_lowercase().as_str()) || !has_id && free_key(k, v) {
959            return Ok(Class::Word);
960        }
961        return modifier(k, v).map(|(k, v)| Class::Mod(k, v));
962    }
963    if is_file(t, has_id)? {
964        return Ok(Class::File(t.to_string()));
965    }
966    if !any_id && is_url(t) && bare_tld(&low).is_none_or(|tld| WORDS.tlds.contains(&tld)) {
967        return Ok(Class::Url(if low.starts_with("http") { t.to_string() } else { format!("https://{t}") }));
968    }
969    if num(t).is_some() {
970        return Ok(Class::Num(t.to_string()));
971    }
972    if t.len() > 1
973        && t.trim_start_matches(['u', 'j', 'l']).len() + 1 == t.len()
974        && t[1..].bytes().all(|b| b.is_ascii_digit())
975    {
976        // `l99999999999999999999`: an id past usize, not words to search
977        return Err(format!("? {t}: out of range"));
978    }
979    Ok(Class::Word)
980}
981
982/// A token that only looks like a place is a search word: a bare name (no scheme, no `/`, `bare_tld`) names a
983/// host unless the command holds a free word (not a host, not a URL: `example.com example.org` = two pages), and
984/// then still when it leads the way an address is typed, in lower case (`docs.rs tokio spawn`, mods and a verb
985/// aside); mid-query (`contact at acme.com phone`) or written as a name (`Booking.com hotels Lisbon`) it is a
986/// word, so no one-site search the agent never asked for.
987fn as_words(cls: &mut [(String, Class)]) {
988    let free = cls.iter().any(|(t, c)| matches!(c, Class::Word | Class::Num(_)) && !is_flag(t));
989    let lead = cls.iter().position(|(t, c)| !matches!(c, Class::Mod(..)) && !is_flag(t));
990    for (i, (t, c)) in cls.iter_mut().enumerate() {
991        let typed = Some(i) == lead && !t.bytes().any(|b| b.is_ascii_uppercase());
992        if matches!(c, Class::Url(_)) && bare_tld(&t.to_lowercase()).is_some() && free && !typed {
993            *c = Class::Word;
994        }
995    }
996    // a local path never reaches a search: a `shaped` one or one with an extension is a file wherever it stands
997    // (`no_file`, `not_allowed`); beside search words only a bare shape that is no file here is text (`CORP /DE/
998    // company`, `TCP/IP tuning` search), unless the `fats mcp` fence refuses it by name (`not_allowed`, the disk
999    // never looked at), and `-` (stdin) is the whole command
1000    if cls.iter().any(|p| matches!(p.1, Class::Word)) {
1001        for (t, c) in cls.iter_mut() {
1002            if let Class::File(p) = c
1003                && (p == "-" || !shaped(t) && Path::new(p).extension().is_none() && !filed(&local_path(p)))
1004            {
1005                *c = Class::Word;
1006            }
1007        }
1008    }
1009}
1010
1011/// A flag as typed: a dash (an en or em dash for `--`: smart punctuation) and a name.
1012fn is_flag(t: &str) -> bool {
1013    t.len() > 1 && t.starts_with(['-', '–', '—'])
1014}
1015
1016/// The classified tokens into `cmd`. Reserved words are reserved only when there is no free text, a list word
1017/// leading the words after a page id aside (`Words::lists`); a bare number with a page id has several readings, so it
1018/// asks. `alone` = one token, mods and `json` aside (`parse`); an alone-only word (`setup`) beside a page (an id, URL
1019/// or file) is text: `u1 setup` filters, `setup full` is setup.
1020fn sort_into(cmd: &mut Cmd, alone: bool, cls: Vec<(String, Class)>, any_id: bool) {
1021    let words = cls.iter().filter(|(_, c)| matches!(c, Class::Word)).count();
1022    let nums = cls.iter().filter(|(_, c)| matches!(c, Class::Num(_))).count();
1023    // a pinned `match:` says "this is a filter": a bare number is then text
1024    let pinned = cls.iter().any(|(_, c)| matches!(c, Class::Mod(k, _) if k == "match"));
1025    let free = words > 0 || nums > 1 || (nums > 0 && (!any_id || pinned));
1026    let page = cls.iter().any(|(_, c)| matches!(c, Class::Id(_) | Class::Url(_) | Class::File(_)));
1027    let lead = cls.iter().position(|(_, c)| matches!(c, Class::Res(_) | Class::Word | Class::Num(_)));
1028    // `stats` leading free words filters its rows (`fats stats rust all`: every reserved word a mod), never a search
1029    let index = lead.is_some_and(|i| matches!(cls[i].1, Class::Res("stats")));
1030    // `json` closing the words beside a page id or file is the output mod (`u1 price json`); on a search it is a
1031    // word like every reserved word there (`vite config json`, `example.com rust json`): JSON is `json:true`
1032    let read = index || cls.iter().any(|(_, c)| matches!(c, Class::Id(_) | Class::File(_)));
1033    let last = cls.iter().rposition(|(_, c)| !matches!(c, Class::Mod(..)));
1034    let list = |i, r: &str| index || Some(i) == lead && any_id && WORDS.lists.contains(&r);
1035    for (i, (t, c)) in cls.into_iter().enumerate() {
1036        match c {
1037            Class::Res(r) if r == "json" && Some(i) == last && read => cmd.reserved.push(r),
1038            Class::Id(i) => cmd.ids.push(i),
1039            Class::Job(j) => cmd.jobs.push(j),
1040            Class::Link(l) => cmd.links.push(l),
1041            Class::Media(m) => cmd.media.push(m),
1042            Class::Url(u) => cmd.urls.push(u),
1043            Class::File(f) => cmd.files.push(f),
1044            Class::Mod(k, v) => cmd.mods.push((k, v)),
1045            Class::Res(r) if !free && (alone || !page || !WORDS.alone.contains(&r)) || list(i, r) => {
1046                cmd.reserved.push(r)
1047            }
1048            Class::Num(n) if cmd.reserved.iter().any(|r| WORDS.lists.contains(r)) => cmd.words.push(n),
1049            Class::Num(n) if !free => {
1050                let q = number_ask(cmd, &n);
1051                cmd.ask.get_or_insert(q);
1052            }
1053            _ => cmd.words.push(t),
1054        }
1055    }
1056}
1057
1058/// `fats u2#3 4`: link, section or text? Every reading as a command.
1059fn number_ask(cmd: &Cmd, n: &str) -> String {
1060    let b = bin();
1061    match cmd.ids.last() {
1062        Some(i) => {
1063            let (full, page) = (cmd.canon(), i.page());
1064            format!("? {n}: link → {b} {full} l{n} · section → {b} {page}#{n} · text → {b} {full} {n} match:words")
1065        }
1066        None => format!("? {n}: link → {b} l{n} · text → {b} {n} match:words"),
1067    }
1068}
1069
1070/// `setup <name> [on|off|stop]`, `config set <name> <value>`, `config unset <name>`: the command's own words, from
1071/// `toks[i]` (`plain` = the free switch's other name). Nothing else follows `setup` but mods and command words: a
1072/// word there is a `?` (`? setup oxi → fats setup oxy`, a switch or on/off one edit away), never a paid search.
1073fn own_words(cmd: &mut Cmd, toks: &mut Vec<String>, i: usize) {
1074    let at = |k: usize| toks.get(i + k).map(|t| t.to_lowercase()).unwrap_or_default();
1075    let (verb, on, switches) =
1076        (toks[i].to_lowercase(), ["on", "off", "stop"].contains(&at(2).as_str()), crate::settings::SWITCHES);
1077    let own = |t: &String| {
1078        !HELP_FLAGS.contains(&t.as_str())
1079            && t != "json"
1080            && !matches!(class_of(t, false, false, true), Ok(Class::Mod(..)))
1081    };
1082    let n = match (verb.as_str(), at(1).as_str()) {
1083        ("setup", w) if switches.contains(&w) || w == "plain" => 1 + usize::from(on),
1084        // the level is checked by `settings::set`, which names the levels
1085        ("setup", "telemetry" | "mcp") => 1 + usize::from(toks.get(i + 2).is_some_and(own)),
1086        ("telemetry", "show") | ("setup", "import-env") => 1,
1087        // the value is every word up to the mods, whole (`~/Library/Application Support/x` is a cache dir)
1088        ("config", "set") => 3 + toks.iter().skip(i + 4).take_while(|t| own(t)).count(),
1089        ("config", "unset") => 2,
1090        _ => 0,
1091    };
1092    let sub = toks.drain(i + 1..(i + 1 + n).min(toks.len())).enumerate();
1093    let low =
1094        |(k, t): (usize, String)| if k > 1 { t } else { t.to_lowercase().replacen("plain", "free", (k == 0).into()) };
1095    cmd.sub = sub.map(low).collect();
1096    if cmd.sub.len() > 3 {
1097        let v = cmd.sub.split_off(2).join(" ");
1098        cmd.sub.push(v);
1099    }
1100    let word = |t: &&String| own(t) && matches!(class_of(t, false, false, true), Ok(Class::Word));
1101    let Some(w) = toks[i + 1..].iter().find(word).filter(|_| verb == "setup") else { return };
1102    let near =
1103        switches.into_iter().chain(["on", "off", "stop"]).find(|n| strsim::osa_distance(&w.to_lowercase(), n) == 1);
1104    let (raw, b, all) = (&cmd.raw, bin(), switches.join("|"));
1105    let fix = near.map_or(format!(" · {b} setup <{all}|plain> [on|off|stop] · zone:<name>"), |n| {
1106        format!(" → {b} {}", raw.replace(w.as_str(), n))
1107    });
1108    cmd.ask = Some(format!("? {raw}{fix}"));
1109}
1110
1111/// A command's typo asks (it is a paid search otherwise; a verb before it says "words"): `led` = a first word
1112/// led into a URL or id, else a lone word (mods aside: `yelp limit:5` searches).
1113fn ask_typo(cmd: &mut Cmd, led: bool) {
1114    let (Some(w), b) = (cmd.words.first().cloned(), bin()) else { return };
1115    if let Some((_, why)) = WORDS.elsewhere.iter().find(|e| !led && e.0.split(' ').any(|o| w.eq_ignore_ascii_case(o))) {
1116        cmd.ask.get_or_insert(format!("! {w}{} · {}", draw(why, &[("b", b)]), to_guide()));
1117    }
1118    if let Some(r) = typo(&w, led) {
1119        let fixed: Vec<&str> = cmd.raw.split(' ').map(|t| if t == w { r } else { t }).collect();
1120        let q = format!("? {w}: a command? {b} {} · a web search: {b} search {}", fixed.join(" "), cmd.raw);
1121        cmd.ask.get_or_insert(q);
1122    }
1123}
1124
1125/// One command's output. `rec` = the JSON record fields beyond what `emit` derives.
1126#[derive(Default)]
1127pub struct Out {
1128    pub lines: Vec<String>,
1129    pub rc: i32,
1130    /// Boxed: an `IndexMap` (key order kept) would make every `Result<_, Out>` large.
1131    pub rec: Box<serde_json::Map<String, serde_json::Value>>,
1132    /// One per input of a multi-input command: `json` prints these records, not the summary.
1133    pub parts: Vec<Out>,
1134}
1135
1136impl Out {
1137    pub fn new(lines: Vec<String>) -> Out {
1138        Out { lines, ..Out::default() }
1139    }
1140
1141    /// THE `?` printer: a usage row, exit 2; a key-shaped word in it (what was typed may be a key) as its tail.
1142    pub fn ask(line: &str) -> Out {
1143        Out { rc: 2, ..Out::new(vec![crate::setup::masked(line)]).with("error", "usage") }
1144    }
1145
1146    /// Whole-command failure (`= !` line + fix, exit 1).
1147    pub fn fail(code: &str, eq: String, hint: String) -> Out {
1148        Out { rc: 1, ..Out::new(vec![eq, hint.clone()]).with("error", code).with("hint", hint) }
1149    }
1150
1151    pub fn set(&mut self, k: &str, v: impl Into<serde_json::Value>) -> &mut Out {
1152        self.rec.insert(k.into(), v.into());
1153        self
1154    }
1155
1156    /// `set` on an answer being built: `Out::new(lines).with("id", id)`.
1157    pub fn with(mut self, k: &str, v: impl Into<serde_json::Value>) -> Out {
1158        self.set(k, v);
1159        self
1160    }
1161
1162    /// Rows that qualify the answer (`! bad_setting`, `! not_in_v1 country:de`): right after the `=` line, and
1163    /// as `warnings` in the record.
1164    pub fn warn(&mut self, rows: Vec<String>) {
1165        if rows.is_empty() {
1166            return;
1167        }
1168        // after the `=` line and the `!` rows already there: the cause first, then what else was skipped
1169        let bang = |l: &String| l.starts_with("! ") || l.split(' ').nth(1) == Some("!");
1170        let at = self.lines.len().min(1) + self.lines.iter().skip(1).take_while(|l| bang(l)).count();
1171        self.lines.splice(at..at, rows.iter().cloned());
1172        let mut all = self.rec.remove("warnings").and_then(|w| w.as_array().cloned()).unwrap_or_default();
1173        all.extend(rows.into_iter().map(Into::into));
1174        self.set("warnings", all);
1175    }
1176
1177    /// `max:N`: keep the `=` line and as many lines as fit in N tokens; the last row says what was cut.
1178    pub fn cap(&mut self, max: usize, fix: &str) {
1179        let mut used = 0;
1180        let Some(keep) = self.lines.iter().skip(1).position(|l| {
1181            used += crate::clean::tok(l);
1182            used > max
1183        }) else {
1184            return;
1185        };
1186        let cut: Vec<String> = self.lines.drain(keep + 1..).collect();
1187        let t: usize = cut.iter().map(|l| crate::clean::tok(l)).sum();
1188        self.lines.push(format!("… max:{max} cut {} lines ~{t}tok → {} {fix}", cut.len(), bin()));
1189        self.set("cut", cut.len());
1190    }
1191}
1192
1193/// The only printer: lines mode (agent path), or JSON Lines: one record, or one per input (the command's
1194/// warnings go on each). Every configured secret is masked in both (`redact`).
1195pub fn emit(o: &Out, json: bool) -> String {
1196    let text = match (json, o.parts.is_empty()) {
1197        (false, _) => o.lines.join("\n") + "\n",
1198        (true, true) => record(o, &[]),
1199        (true, false) => {
1200            let warn = o.rec.get("warnings").and_then(|w| w.as_array()).map_or(&[][..], |w| w.as_slice());
1201            o.parts.iter().map(|p| record(p, warn)).collect()
1202        }
1203    };
1204    redact(&text, &crate::settings::secrets())
1205}
1206
1207pub const MASK: &str = "***";
1208/// A run of this many characters of a secret is masked wherever it shows (a provider may echo part of a key).
1209const SECRET_RUN: usize = 12;
1210/// Shorter secrets are masked only whole; under this length a value is not a key and is left alone.
1211const SECRET_MIN: usize = 8;
1212
1213/// `text` with every `SECRET_RUN`-char run of a secret (a whole secret of `SECRET_MIN`.. chars) as `MASK`, matched
1214/// ASCII case-folded (a provider may echo a key upper-cased; folding keeps every byte offset).
1215pub fn redact(text: &str, secrets: &[String]) -> String {
1216    let (mut hide, low) = (vec![false; text.len()], text.to_ascii_lowercase());
1217    for s in secrets.iter().map(|s| s.to_ascii_lowercase()) {
1218        let at: Vec<usize> = s.char_indices().map(|c| c.0).chain([s.len()]).collect();
1219        let n = at.len() - 1;
1220        if n < SECRET_MIN {
1221            continue;
1222        }
1223        let w = n.min(SECRET_RUN);
1224        for i in 0..=n - w {
1225            let run = &s[at[i]..at[i + w]];
1226            for (j, _) in low.match_indices(run) {
1227                hide[j..j + run.len()].fill(true);
1228            }
1229        }
1230    }
1231    // a hidden run is whole chars (a secret's substring), so the byte before a char says whether its run goes on
1232    let mut out = String::with_capacity(text.len());
1233    for (i, c) in text.char_indices() {
1234        if !hide[i] {
1235            out.push(c);
1236        } else if i == 0 || !hide[i - 1] {
1237            out.push_str(MASK);
1238        }
1239    }
1240    out
1241}
1242
1243fn record(o: &Out, warn: &[serde_json::Value]) -> String {
1244    let mut r = o.rec.clone();
1245    if !warn.is_empty() {
1246        let mut all = warn.to_vec();
1247        if let Some(serde_json::Value::Array(own)) = r.remove("warnings") {
1248            all.extend(own);
1249        }
1250        r.insert("warnings".into(), all.into());
1251    }
1252    let text = o.lines.join("\n");
1253    for (k, v) in [
1254        ("provider", "local".into()),
1255        ("ms", 0.into()),
1256        ("cost", 0.0.into()),
1257        ("bytes_in", 0.into()),
1258        ("cache", false.into()),
1259        ("id", serde_json::Value::Null),
1260        ("url", serde_json::Value::Null),
1261    ] {
1262        r.entry(k).or_insert(v);
1263    }
1264    r.insert("bytes_out".into(), text.len().into());
1265    r.insert("lines".into(), o.lines.clone().into());
1266    r.sort_keys();
1267    serde_json::Value::Object(*r).to_string() + "\n"
1268}
1269
1270#[cfg(test)]
1271pub(crate) mod tests {
1272    use super::*;
1273
1274    thread_local! {
1275        /// `NO_COLOR` as this thread's `paint` reads it (Some = set or not), None = the environment's: a test sees
1276        /// both sides without touching the process environment.
1277        pub(crate) static NO_COLOR: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
1278    }
1279
1280    fn c(s: &str) -> Cmd {
1281        parse(&s.split(' ').map(String::from).collect::<Vec<_>>())
1282    }
1283
1284    /// One filler: a named hole becomes its value, any other brace stays; styles are only `paint`'s.
1285    #[test]
1286    fn draw_fills_named_holes_only() {
1287        assert_eq!(draw("{a}+{a} {c} {\"k\": 1} {", &[("a", "1"), ("b", "2")]), "1+1 {c} {\"k\": 1} {");
1288        assert_eq!(draw("{bold}x{/}", &NO_HOLES), "{bold}x{/}");
1289    }
1290
1291    /// Every screen, filled with the holes its owner fills (`stats::home`, `ready`, `tip`), leaves no hole: a
1292    /// typo in a data file (`{bodl}`) fails here, never on a user's terminal. Braces in a JSON line stay.
1293    #[test]
1294    fn every_screen_fills_every_hole() {
1295        let mut fills = vec!["ready", "yours", "pages", "id", "last", "spent", "site", "label", "text", "from"];
1296        fills.extend([
1297            "status", "name", "short", "mint", "signup", "step", "rank", "free", "cost", "b", "url", "env", "level",
1298            "life",
1299        ]);
1300        let holes: Vec<(&str, &str)> = fills.iter().map(|h| (*h, "X")).collect();
1301        for (name, text) in SCREENS {
1302            let out = paint(text, &holes);
1303            let left = out.split('{').skip(1).find(|r| r.split_once('}').is_some_and(|(h, _)| !h.contains(' ')));
1304            assert!(!text.is_empty() && left.is_none(), "{name}: {left:?}");
1305        }
1306        assert_eq!(screen("help-nope"), "");
1307        assert_eq!(help_screen(&["help".into(), "nope".into()]), Some(paint(screen("help"), &NO_HOLES)));
1308        assert_eq!(help_screen(&["rust".into(), "help".into()]), None, "a search for help");
1309    }
1310
1311    /// The repair table, one row per case: input → canonical command.
1312    const REPAIRS: &[(&str, &str)] = &[
1313        // a typed verb stays first in the canonical form (it replays the same reading)
1314        ("read u2#3", "read u2#3"),
1315        ("open u6", "open u6"),
1316        ("search cheap proxies", "search cheap proxies"),
1317        ("u2.3", "u2#3"),
1318        ("u2 #3", "u2#3"),
1319        ("\"u2#3\"", "u2#3"),
1320        ("U2#3", "u2#3"),
1321        ("`fats u2#3`", "u2#3"),
1322        ("u2#3 --full", "u2#3 full"),
1323        ("u2 -n 20", "u2 limit:20"),
1324        ("u2 n=20", "u2 limit:20"),
1325        ("u2#3 l 4", "u2#3 l4"),
1326        ("j8/u2", "j8.u2"),
1327        ("j8:u2", "j8.u2"),
1328        ("J8.U2#3b", "j8.u2#3b"),
1329        ("u3 loose:50", "u3 match:near"),
1330        ("u3 price js:1", "u3 price js:true"),
1331        ("u3 n:5 geo:FR budget:0.5", "u3 limit:5 country:fr cost:0.5"),
1332        ("ex.com ua:Phone", "https://ex.com device:mobile"),
1333        ("u3#2 full price", "u3#2 full price"),
1334        ("u3#2 links", "u3#2 links"),
1335        ("u1 links From:11", "u1 links from:11"),
1336        ("u1 iphone 15", "u1 iphone 15"),
1337        ("u1 15 match:words", "u1 15 match:words"),
1338        ("u1 -n", "u1 -n"),
1339        ("u1 -x -y", "u1 -x -y"),
1340        ("example.com", "https://example.com"),
1341        // a bare host needs a real TLD and stands alone or leads the command in lower case; mid-query or written
1342        // as a name it is a word; a scheme or a `/` makes a host anywhere
1343        ("opencode mcp config opencode.yaml", "opencode mcp config opencode.yaml"),
1344        ("pyproject.toml build backend options", "pyproject.toml build backend options"),
1345        ("nextjs next.config.mjs", "nextjs next.config.mjs"),
1346        ("main.go error", "main.go error"),
1347        ("logo.png size", "logo.png size"),
1348        ("cargo build main.rs", "cargo build main.rs"),
1349        ("build lib.so", "build lib.so"),
1350        ("rust x.ai", "rust x.ai"),
1351        ("contact at acme.com phone", "contact at acme.com phone"),
1352        ("Purchasing.NYC Lakewood New Jersey", "Purchasing.NYC Lakewood New Jersey"),
1353        ("Booking.com hotels Lisbon", "Booking.com hotels Lisbon"),
1354        ("Booking.com", "https://Booking.com"),
1355        ("fetch docs.rs tokio", "fetch https://docs.rs tokio"),
1356        ("docs.rs tokio spawn", "https://docs.rs tokio spawn"),
1357        ("limit:5 docs.rs tokio", "https://docs.rs tokio limit:5"),
1358        // bare hosts with no free word beside them are pages, a batch
1359        ("example.com example.org", "https://example.com https://example.org"),
1360        ("Example.com Example.org limit:5", "https://Example.com https://Example.org limit:5"),
1361        ("example.com example.org rust", "https://example.com example.org rust"),
1362        ("main.rs error handling", "https://main.rs error handling"),
1363        ("rust example.com", "rust example.com"),
1364        ("example.com rust", "https://example.com rust"),
1365        ("x.co", "https://x.co"),
1366        ("a.io", "https://a.io"),
1367        ("blog.rust-lang.org", "https://blog.rust-lang.org"),
1368        ("tokio docs.rs/tokio", "https://docs.rs/tokio tokio"),
1369        ("https://main.rs", "https://main.rs"),
1370        ("https://ex.com/a?b=1", "https://ex.com/a?b=1"),
1371        ("u1 v2.0", "u1 v2.0"),
1372        ("dry:yes u1#2", "u1#2 dry:true"),
1373        ("l4", "l4"),
1374        ("help", "help"),
1375        ("u1 max_bytes:32MiB", "u1 max_bytes:33554432"),
1376        ("-h", "help"),
1377        ("--help", "help"),
1378        ("how to get help", "how to get help"),
1379        ("u1 hedge:0", "u1 hedge:0"),
1380        ("u1 hedge:5s", "u1 hedge:5"),
1381        ("u1 timeout:300", "u1 timeout:300"),
1382        ("rust news site:HTTPS://Blog.Rust-Lang.org/ since:2w", "rust news site:blog.rust-lang.org since:2w"),
1383        ("serde site:docs.rs/serde", "serde site:docs.rs/serde"),
1384        // command words never search: status, version, ls; typos ask (below) unless a verb says "words"
1385        ("status", "status"),
1386        ("ls", "status"),
1387        ("--version", "version"),
1388        ("-V", "version"),
1389        ("rust status", "rust status"),
1390        ("u1 version", "u1 version"),
1391        ("status json:true", "status json:true"),
1392        ("search stat", "search stat"),
1393        ("search login", "search login"),
1394        ("stats", "stats"),
1395        ("ale", "ale"),
1396        // a real word one edit from a reading word searches
1397        ("yelp", "yelp"),
1398        ("fuel", "fuel"),
1399        ("jason", "jason"),
1400        ("mode", "mode"),
1401        // a word two edits from a command searches when lone or with mods; before a URL or id only from a long one
1402        ("acont", "acont"),
1403        ("acont limit:5", "acont limit:5"),
1404        ("yelp limit:5", "yelp limit:5"),
1405        ("go https://go.dev", "https://go.dev go"),
1406        ("rust u1", "u1 rust"),
1407        ("search fetchh https://x.com", "search https://x.com fetchh"),
1408        ("fetchh rust", "fetchh rust"),
1409        // a file URL decodes to this OS's path: Windows has no rootless `/tmp`, its paths start at a drive
1410        #[cfg(unix)]
1411        ("file:///tmp/a%20b.html", "/tmp/a b.html"),
1412        #[cfg(unix)]
1413        ("file://localhost/tmp/x", "/tmp/x"),
1414        #[cfg(windows)]
1415        ("file:///C:/tmp/a%20b.html", "C:\\tmp\\a b.html"),
1416        // a word people type for a command is that command, mods and `json` aside; with another word it is text
1417        ("login", "setup"),
1418        ("Sign-In", "setup"),
1419        ("usage", "account"),
1420        ("-v", "verbose:true"),
1421        ("rust --json", "rust json:true"),
1422        ("stat json", "stats json"),
1423        ("login limit:5", "setup limit:5"),
1424        ("keys json", "setup json"),
1425        ("login page design", "login page design"),
1426        ("u1 key", "u1 key"),
1427        ("u1 install", "u1 install"),
1428        // `--help` / `-h` anywhere, `help` first: the card
1429        ("rust --help", "help"),
1430        ("rust —help", "help"),
1431        ("–help", "help"),
1432        ("-- rust", "rust"),
1433        // a dash in the text is the text: only a flag reads it as `--`
1434        ("u1 Rust — the book", "u1 Rust — the book"),
1435        ("rust — tokio", "rust — tokio"),
1436        ("tokio —the runtime", "tokio —the runtime"),
1437        ("1990 – 2000 census", "1990 – 2000 census"),
1438        ("help login", "help"),
1439        // a flag beside two words, or after the verb, is text
1440        ("git rebase --onto", "git rebase --onto"),
1441        ("search -tokio rust", "search -tokio rust"),
1442        // a `-word` after a word is the engine's exclusion, not a flag
1443        ("rust -tokio", "rust -tokio"),
1444        // a search engine's query key is a search word as typed; a path beside words must exist, `-` be alone
1445        ("rust filetype:pdf before:2026-01", "rust filetype:pdf before:2026-01"),
1446        ("NORTHROP GRUMMAN CORP /DE/ company", "NORTHROP GRUMMAN CORP /DE/ company"),
1447        ("irs liaison committee - tei", "irs liaison committee - tei"),
1448        ("./nope.md summary", "./nope.md summary"),
1449        // a `/` path of 2+ segments or a drive is a path beside words too; `.rs` is no document: a host
1450        ("acme /etc/hosts", "/etc/hosts acme"),
1451        ("C:\\x acme", "C:\\x acme"),
1452        ("C:/x", "C:/x"),
1453        ("docs.rs tokio", "https://docs.rs tokio"),
1454        // a home, a variable, a `\` or a bare path of 3+ segments that no host leads is a path beside words too;
1455        // 2 segments are words unless they exist here, a host-led path is a URL, a name of digits leads nothing
1456        ("acme .\\secret\\plan", ".\\secret\\plan acme"),
1457        ("acme ~alice/secret", "~alice/secret acme"),
1458        ("acme ${HOME}/secret", "${HOME}/secret acme"),
1459        ("acme internal/hr/salaries", "internal/hr/salaries acme"),
1460        ("acme Documents/plan.key", "Documents/plan.key acme"),
1461        ("TCP/IP and/or AC/DC", "TCP/IP and/or AC/DC"),
1462        ("~5/10 $5/mo plan", "~5/10 $5/mo plan"),
1463        ("docs.rs/tokio/latest/tokio spawn", "https://docs.rs/tokio/latest/tokio spawn"),
1464        // a dot-led name is a path wherever it stands; one leading a TLD, a digit or no name is a word
1465        ("summary .env", ".env summary"),
1466        // a key that is no mod nor near one is a search word as typed
1467        ("discord embed og:image gif", "discord embed og:image gif"),
1468        ("x foo:1 schema:org", "x foo:1 schema:org"),
1469        (".ssh/config", ".ssh/config"),
1470        ("learn .NET core .io ... .5mm", "learn .NET core .io ... .5mm"),
1471    ];
1472
1473    /// Inputs that ask: input → the start of the `?` line.
1474    const ASKS: &[(&str, &str)] = &[
1475        ("u2#3 4", "? 4: link → "),
1476        // beside an id a key can only be a mod; in a search a mod one edit away is a typo
1477        ("u1 og:image", "? og: unknown · keys limit match"),
1478        ("x wiat:30", "? wiat: unknown · keys"),
1479        ("x jsn:true", "? jsn: unknown · keys"),
1480        ("rust countr:lt", "? countr: unknown · keys"),
1481        ("notes.md hello", "? notes.md: a missing file or a site · type ./notes.md or https://notes.md"),
1482        // a lone name ending in a file's extension that is no file here asks; beside words it leads a site search
1483        ("main.rs", "? main.rs: a missing file or a site · type ./main.rs or https://main.rs"),
1484        ("docs.rs limit:5", "? docs.rs: a missing file or a site"),
1485        // a directory is no file and no search word
1486        ("acme phone ./src", "? ./src is a directory · name a file in it"),
1487        ("u1 js:maybe", "? js:maybe · use js:true"),
1488        ("u1 match:fuzzy", "? match:fuzzy"),
1489        ("u1 max_bytes:65m", "? max_bytes:65m · 1k to 64m"),
1490        ("u1 max_bytes:lots", "? max_bytes:lots"),
1491        ("ex.com device:tablet", "? device:tablet · use device:mobile|desktop"),
1492        ("u1 hedge:61", "? hedge:61 · seconds before the second provider, 0 to 60"),
1493        ("u1 hedge:soon", "? hedge:soon"),
1494        ("u1 timeout:301", "? timeout:301 · seconds for bd and oxyjs, 1 to 300"),
1495        ("u1 timeout:99999999", "? timeout:99999999"),
1496        ("ex.com provider:oxyjs", "? provider:oxyjs · use provider:auto|plain|bd|oxy|decodo"),
1497        ("rust since:lately", "? since:lately · an age or a date"),
1498        ("rust since:2026-13", "? since:2026-13"),
1499        ("rust site:not_a_host", "? site:not_a_host · a host"),
1500        ("stts", "? stts: a command? "),
1501        ("acount", "? acount: a command? "),
1502        ("confg", "? confg: a command? "),
1503        ("cofnig", "? cofnig: a command? "),
1504        ("verison", "? verison: a command? "),
1505        ("versoin", "? versoin: a command? "),
1506        ("rotues", "? rotues: a command? "),
1507        ("fetchh", "? fetchh: a command? fats fetch · a web search: fats search fetchh"),
1508        ("fetchh https://x.com", "? fetchh: a command? fats fetch https://x.com · a web search: fats search fetchh"),
1509        ("fecth u1", "? fecth: a command? fats fetch u1 "),
1510        ("acont u1", "? acont: a command? fats account u1 "),
1511        ("hlep u1", "? hlep: a command? fats help u1 "),
1512        ("stts json:true", "? stts: a command? fats stats json:true "),
1513        // a file URL on another machine: fats reads local files only
1514        ("file://host/x", "? file://host/x: a file URL names a local path"),
1515        ("l99999999999999999999", "? l99999999999999999999: out of range"),
1516        ("u1 u99999999999999999999", "? u99999999999999999999: out of range"),
1517        ("--login", "! unknown flag --login · keys: fats setup · help: fats --help"),
1518        ("-x", "! unknown flag -x · "),
1519        ("limit:5 -x", "! unknown flag -x · "),
1520        ("–x", "! unknown flag –x · "),
1521        // every free word a flag, wherever it stands: nothing to search for
1522        ("-x -y", "! unknown flag -x · "),
1523        ("--login -x", "! unknown flag --login · "),
1524        ("—", "! unknown flag — · "),
1525        ("--dry ex.com", "! unknown flag --dry · mod: dry:true · "),
1526        // a mod typed as a flag after search words is no search word: the search, then the mod on a result
1527        ("fatsearch forum --cards", "? --cards is a mod, not a search word · search first: fats fatsearch forum · "),
1528        (
1529            "rust news --full",
1530            "? --full is a mod, not a search word · search first: fats rust news · then: fats u1 full",
1531        ),
1532        ("logout", "! logout is not a fats command · "),
1533        ("install json", "! install: see docs/installation.md"),
1534        ("stts json", "? stts: a command? "),
1535    ];
1536
1537    /// The root zone list is whole; `site:` and a `/` name a host by shape alone.
1538    #[test]
1539    fn tlds_and_host_shapes() {
1540        assert_eq!((WORDS.tlds.len(), WORDS.tlds[0], WORDS.tlds.last().copied()), (1437, "aaa", Some("zw")));
1541        // `site:` and a `/` name a host by shape alone, a TLD or not
1542        assert_eq!(
1543            (c("rust site:wiki.corp").get("site"), c("wiki.corp/a b").urls[0].as_str()),
1544            (Some("wiki.corp"), "https://wiki.corp/a")
1545        );
1546        // an engine's query key is never one of our keys or thresholds: it would stop being a search word
1547        let ours = |o: &&&str| WORDS.keys.contains(o) || crate::settings::LIMITS.contains_key(**o);
1548        assert_eq!(WORDS.operators.iter().find(ours), None);
1549    }
1550
1551    /// A name no resolver can ask for is `no_host` by its shape: a label over 63 chars, an empty label, a hyphen
1552    /// at a label's end (a 64-char label was looked up and blamed on the network).
1553    #[test]
1554    fn real_host_needs_askable_labels() {
1555        let (l63, l64) = ("a".repeat(63), "a".repeat(64));
1556        let good = [format!("https://{l63}.com/"), "https://a-b.example.com./x".into(), "http://[::1]/".into()];
1557        let good = good.into_iter().chain(["https://xn--bcher-kva.de/".into(), "https://93.184.215.14/a".into()]);
1558        for u in good {
1559            assert!(real_host(&u), "{u}");
1560        }
1561        let bad = [format!("https://{l64}.com/"), format!("https://x.{l64}.com/"), "https://a..com/".into()];
1562        let bad = bad
1563            .into_iter()
1564            .chain(["https://-a.com/", "https://a-.com/", "https://a.-com.com/", "https://.a.com/"].map(String::from));
1565        for u in bad.chain(["https://dead.invalid/a".into(), "https://a.com../".into()]) {
1566            assert!(!real_host(&u), "{u}");
1567        }
1568    }
1569
1570    /// A `\` makes a path only as a path's lead beside a page: grep alternation and a stray `\` are filter words
1571    /// there; on a search a `\` inside a word is a local path's, never sent.
1572    #[test]
1573    fn a_backslash_is_a_path_on_a_search() {
1574        let (path, word) = (c("u1 C:\\Users\\x"), c("u1 a\\b"));
1575        assert!(path.files == ["C:\\Users\\x"] && path.words.is_empty() && word.files.is_empty());
1576        assert_eq!((word.words, c("u1 price\\|cost").words), (vec!["a\\b".to_string()], vec!["price\\|cost".into()]));
1577        for q in ["Documents\\salaries 2026", "search a\\b rust", "2026 Documents\\salaries"] {
1578            let got = c(q);
1579            assert!(
1580                got.files.len() == 1 && got.files[0].contains('\\') && !crate::cli::is_search(&got),
1581                "{q}: {:?}",
1582                got.files
1583            );
1584        }
1585    }
1586
1587    /// The no-key move has one rule (`fix`): a bare `setup` without a provider; with one, an agent runs its setup
1588    /// and hands the user its steps; a stored row read again keeps its provider and the reader's wording.
1589    #[test]
1590    fn a_no_key_arrow_is_one_rule() {
1591        let (b, at) = (bin(), At::default());
1592        assert_eq!(bang("u3", "no_key", "bd", &at), format!("u3 ! no_key bd → {b} setup"));
1593        let bd = format!("u3 ! no_key bd → run {b} setup bd, give the user its 3 lines");
1594        assert_eq!(bang("u3", "no_key", "bd", &At { arg: "bd", ..at }), bd, "an agent runs the key's setup");
1595        assert_eq!(
1596            restamp(&format!("! no_key bd → {b} setup bd · https://x"), "u3", ""),
1597            bd[3..].to_string() + " · https://x"
1598        );
1599    }
1600
1601    #[test]
1602    fn repair_table() {
1603        for (i, want) in REPAIRS {
1604            let got = c(i);
1605            assert!(got.ask.is_none(), "{i} → {:?}", got.ask);
1606            assert_eq!(&got.canon(), want, "input: {i}");
1607        }
1608        for (i, _) in REPAIRS {
1609            let (once, twice) = (c(i).canon(), c(&c(i).canon()).canon());
1610            assert_eq!((c(&once).words, &twice), (c(i).words, &once), "{i}: the canonical form replays");
1611        }
1612        // every verb, a mod before or after it: the canonical form and a mod's arrow read the same command back
1613        let reading =
1614            |m: &Cmd| (m.verb.clone(), m.words.clone(), m.reserved.clone(), m.ids.iter().map(Id::page).collect());
1615        for (v, w) in WORDS.verbs.iter().flat_map(|v| ["login", "u1", "stat"].map(|w| (v, w))) {
1616            for i in [format!("limit:5 {v} {w}"), format!("{v} {w} limit:5"), format!("-v {v} {w}")] {
1617                let once = c(&i);
1618                let want: (_, _, _, Vec<String>) = reading(&once);
1619                assert!(once.verb.is_some() && once.ask.is_none(), "{i}: the verb is read");
1620                for line in [once.canon(), once.with_mod("limit", Some("3"))] {
1621                    assert_eq!(reading(&c(&line)), want, "{i} → {line}: the same reading");
1622                }
1623            }
1624        }
1625        for (i, want) in ASKS {
1626            let got = c(i).ask.unwrap_or_default().replace(bin(), "fats");
1627            assert!(got.starts_with(want), "{i} → {got}");
1628        }
1629        // a page's mod after a URL is the mod on that page, never a word or a `?` (`cli::run` reads it)
1630        for m in ["links", "cards", "all", "full", "media"] {
1631            let u = c(&format!("example.com/a {m}"));
1632            assert!(u.urls == ["https://example.com/a"] && u.reserved == [m] && u.words.is_empty() && u.ask.is_none());
1633        }
1634        // beside a page a mod typed as a flag is the mod
1635        assert!(c("u1 --cards").ask.is_none() && c("u1 --cards").reserved == ["cards"]);
1636        // `json` closing the words beside a page id or file is the output mod; on a search (a host's too) it is a
1637        // word, `json:true` the mod
1638        let searches = [
1639            ("rust news json", "rust news json"),
1640            ("json parser", "json parser"),
1641            ("example.com rust json", "rust json"),
1642        ];
1643        for (i, json, words) in searches.map(|(i, w)| (i, false, w)) {
1644            let got = c(i);
1645            assert_eq!((got.has("json"), got.words.join(" ").as_str()), (json, words), "{i}");
1646        }
1647        let mod_on = c("rust news json:true");
1648        assert!(mod_on.flag("json"));
1649        assert_eq!(mod_on.words, ["rust", "news"]);
1650        // a `?`/`!` row is no search: its closing `json` stays the switch
1651        for asked in ["whoami json", "stts json"] {
1652            assert!(c(asked).has("json") && !c(asked).words.contains(&"json".to_string()), "{asked}");
1653        }
1654        assert!(c("u1 price json").has("json") && c("u1 price json").words == ["price"]);
1655        // `stats` leading words filters its index, never a search; a closing `json` and `all` stay mods
1656        let st = c("stats rust http all json");
1657        assert!(st.has("stats") && st.has("all") && st.has("json") && st.words == ["rust", "http"], "{:?}", st.words);
1658        assert!(c("rust stats").words == ["rust", "stats"], "a search that names stats stays one");
1659        // two command words and no page are the command (`guide all` = the card), never a search for one of them;
1660        // beside a page, an alone-only word is text (`u1 setup` filters)
1661        for i in ["guide all", "setup full", "account more", "login all", "keys links"] {
1662            assert!(c(i).words.is_empty() && c(i).ask.is_none(), "{i}: {:?} {:?}", c(i).words, c(i).ask);
1663        }
1664        assert_eq!((c("u1 setup").words, c("https://a.b setup").words), (vec!["setup".into()], vec!["setup".into()]));
1665    }
1666
1667    /// A failed fetch's cause row stays first under the `=` line; skipped tiers and later warnings follow it.
1668    #[test]
1669    fn warnings_follow_the_cause() {
1670        let mut o = Out::new(vec!["= u1 ! js_shell T".into(), "u1 ! js_shell x → fix".into(), "[u1#1] # T".into()]);
1671        o.warn(vec!["u1 ! no_key oxy → fats setup".into()]);
1672        o.warn(vec!["u1 ! ignored device".into()]);
1673        let want =
1674            ["= u1 ! js_shell T", "u1 ! js_shell x → fix", "u1 ! no_key oxy → fats setup", "u1 ! ignored device"];
1675        assert_eq!(o.lines[..4], want);
1676        assert_eq!(o.rec["warnings"], serde_json::json!(want[2..]));
1677        // a search's rows have no subject: the cause (the default key) stays first all the same
1678        let mut o = Out::fail("no_key", "= ! no_key search".into(), "! no_key oxy".into());
1679        o.warn(vec!["! no_key bd".into()]);
1680        assert_eq!(o.lines, ["= ! no_key search", "! no_key oxy", "! no_key bd"]);
1681    }
1682
1683    /// Edits: a change, an addition, a drop, a swap of neighbours, each one; and the typo targets by position.
1684    #[test]
1685    fn near_words() {
1686        for (a, b, n) in [
1687            ("stat", "stats", 1),
1688            ("acount", "account", 1),
1689            ("confg", "config", 1),
1690            ("cofnig", "config", 1),
1691            ("sats", "stats", 1),
1692            ("fetchh", "fetch", 1),
1693            ("sta", "stats", 2),
1694            ("acont", "account", 2),
1695            ("cinfog", "config", 2),
1696            ("rust", "status", 5),
1697            ("ab", "ba x", 3),
1698        ] {
1699            assert_eq!((strsim::osa_distance(a, b), strsim::osa_distance(b, a)), (n, n), "{a} {b}");
1700        }
1701        assert_eq!((typo("stat", false), typo("ale", false), typo("us", false)), (Some("stats"), None, None));
1702        assert_eq!((typo("stats", false), typo("yelp", false), typo("fuel", false)), (None, None, None));
1703        assert_eq!(
1704            (typo("rotues", false), typo("fetchh", false), typo("acont", false)),
1705            (Some("routes"), Some("fetch"), None)
1706        );
1707        assert_eq!(
1708            (typo("acont", true), typo("hlep", true), typo("gh", true), typo("map", true)),
1709            (Some("account"), Some("help"), None, Some("mcp"))
1710        );
1711    }
1712
1713    /// Fuzz-ish: a table of hostile inputs never panics and always yields one reading or one `?`.
1714    #[test]
1715    fn hostile_inputs() {
1716        let junk = [
1717            "", " ", "#", "u", "u#", "u1#", "u1#a", "u99999999999999999999999", "j.u1", "j1.", "l", "l-1", "::", "a:",
1718            ":b", "http:", "https://", "--", "-n", "-n x", "n=", "=5", "``", "\"", "u1 #", "u1 # 3", "ü1#2", "u1#2zz",
1719            "\u{0}", "u1\u{a0}links", "🙂 u1", "j8/u", "file:///etc/passwd", "../", "~/", "u1 l 4 l 5", "all all",
1720        ];
1721        for j in junk {
1722            let cmd = c(j);
1723            cmd.canon();
1724            let usage = |q: &String| q.starts_with("? ") || q.starts_with("! unknown flag ");
1725            assert!(cmd.ask.as_ref().is_none_or(usage), "{j} → {:?}", cmd.ask);
1726        }
1727        for a in ['a', 'u', '#', '1', ':', '.', ' ', 'l', 'j', '/'] {
1728            for b in ['a', 'u', '#', '1', ':', '.', ' ', 'l', 'j', '/'] {
1729                c(&format!("u1{a}{b}2{a}")).canon();
1730            }
1731        }
1732    }
1733
1734    /// Every printed part id reads back (z → aa, never a shell symbol).
1735    #[test]
1736    fn part_ids_round_trip() {
1737        assert_eq!(
1738            [letters(0), letters(1), letters(25), letters(26), letters(27), letters(701), letters(702)],
1739            ["a", "b", "z", "aa", "ab", "zz", "aaa"]
1740        );
1741        for p in 0..20_000 {
1742            let id = Id::parse(&format!("j3.u2#7{}", letters(p))).unwrap_or_default();
1743            assert_eq!((id.job, id.u, id.sec, id.part), (Some(3), 2, Some(7), p));
1744        }
1745        assert_eq!(Id::parse("u2#7").map(|i| i.part), Some(0));
1746        assert!(Id::parse(&format!("u2#7{}", "z".repeat(40))).is_none());
1747    }
1748
1749    /// Every paid arrow is priced and parses (11 had no price, one offered `provider:oxyjs`): for every code
1750    /// of the table, every `{arg}` a failed copy gets (`fetch::fix_arg`, the search's longer time, a cap) and every
1751    /// spent tier set, an arrow whose command can spend parses and ends with `≤$X` = `dry:true`'s `up to` for it
1752    /// (in 0.1.7 its own worst case was the arrow checked against itself; a URL's arrow runs dry on the URL).
1753    #[test]
1754    fn every_paid_arrow_is_priced() {
1755        let args = ["", "js:true", "provider:bd", "provider:oxy js:true", "wait:30", "timeout:30", "0.0025"];
1756        let dones: [&[&str]; 4] = [&[], &["plain", "bd"], &["plain", "oxyjs"], &["plain", "oxy", "oxyjs"]];
1757        // a public IP: `dry:true` judges a host by its name alone (`real_host`), never a lookup; nothing is sent
1758        let cases = args
1759            .into_iter()
1760            .flat_map(|a| dones.map(|d| (a, d)))
1761            .flat_map(|c| [("https://93.184.215.14/a", c), ("", c)]);
1762        let (mut paid, b) = (0, bin());
1763        for (url, (arg, done)) in cases.collect::<Vec<_>>() {
1764            // `{arg}`: a timeout's mods (`fix_arg`), `budget_hit`'s cap in dollars, another code's its own word
1765            let fits = |r: &&(&str, &str)| match r.0 {
1766                "budget_hit" => arg == "0.0025",
1767                "provider_timeout" => arg != "0.0025",
1768                _ => arg.is_empty() || !r.1.contains("{arg}"),
1769            };
1770            for code in FIX.iter().filter(fits).map(|r| r.0.replace('*', "403")) {
1771                let f = fix(&code, &At { id: "u3", url, arg, done });
1772                let cmd = f.split(", ").next().unwrap_or_default().split(" ≤$").next().unwrap_or_default();
1773                let mods = ["fresh:", "js:", "provider:", "timeout:"];
1774                if !cmd.starts_with(b) || !cmd.split(' ').any(|w| mods.iter().any(|k| w.starts_with(k))) {
1775                    continue;
1776                }
1777                paid += 1;
1778                let words: Vec<String> = cmd.split(' ').skip(1).map(Into::into).collect();
1779                assert_eq!(parse(&words).ask, None, "{code} {arg}: {f}");
1780                let price = f.split(" ≤$").nth(1).and_then(|p| p.get(..6)).unwrap_or_default();
1781                let dry = words.iter().map(|w| if w == "u3" && !url.is_empty() { url } else { w.as_str() });
1782                let dry: Vec<String> = dry.map(Into::into).chain(["dry:true".into()]).collect();
1783                let c = crate::cache::Cache::at(crate::settings::get().cache.value.clone(), "t".into());
1784                let rows = crate::cli::plan(&parse(&dry), &c).lines.join("\n");
1785                let up = rows.split(" up to ").nth(1).and_then(|r| r.split([' ', '\n']).next()).unwrap_or("none");
1786                if !url.is_empty() {
1787                    assert_eq!(format!("${price}"), up, "{code} {arg}: {f}\n{rows}");
1788                }
1789                assert!(f.starts_with(&format!("{cmd} ≤$")), "{code} {arg}: {f}");
1790            }
1791        }
1792        assert!(paid > 500, "{paid}");
1793    }
1794
1795    /// Every keyed paid tier has its turn: with two providers spent, a third key's untried tier is the move
1796    #[test]
1797    fn a_third_key_is_the_move() {
1798        let at = At { id: "u3", done: &["plain", "oxy", "bd", "oxyjs"], ..Default::default() };
1799        assert_eq!(fix("captcha_wall", &at), format!("{} u3 fresh:true provider:decodo", bin()));
1800    }
1801
1802    /// One fix per code; every code a provider or the content check can return has a row (a new code without
1803    /// one fails here, not in front of an agent); the fix for a timeout is never the same failing retry.
1804    #[test]
1805    fn error_table() {
1806        let keys: Vec<&str> = FIX.iter().map(|r| r.0).collect();
1807        let mut uniq = keys.clone();
1808        uniq.sort_unstable();
1809        uniq.dedup();
1810        assert_eq!(uniq.len(), keys.len(), "a code with two fixes");
1811        let born = [include_str!("provider.rs"), include_str!("fetch.rs"), include_str!("stats.rs")].concat();
1812        let mut codes: Vec<&str> = born
1813            .split('"')
1814            .skip(1)
1815            .step_by(2)
1816            .filter(|w| w.contains('_') && w.bytes().all(|b| b.is_ascii_lowercase() || b == b'_' || b.is_ascii_digit()))
1817            .collect();
1818        codes.extend(crate::fetch::CHECK.rules.iter().map(|w| w.code).filter(|c| !c.is_empty()));
1819        codes.extend(["blocked_403", "http_502", "fetch_failed", "no_file", "not_allowed", "too_big", "offline"]);
1820        // literals in those files that are HTML or JSON names, not codes
1821        let names = ["b_algo", "result__a", "cf_chl_opt", "search_query", "status_code", "run_js", "max_results"];
1822        let names = [&names[..], &["brd_json", "dns_wait", "dns_fast_ms"]].concat();
1823        for c in codes.iter().filter(|c| !names.contains(c)) {
1824            let hit = keys.iter().any(|k| k.strip_suffix('*').map_or(k == c, |p| c.starts_with(p)));
1825            assert!(hit, "code {c} has no fix in FIX");
1826        }
1827        let at = At { id: "u3", url: "https://ex.com/a", arg: "0.0025", done: &[] };
1828        let b = bin();
1829        assert_eq!(
1830            fix("provider_timeout", &At { arg: "js:true", ..at }),
1831            format!("{b} u3 fresh:true js:true ≤$0.0030")
1832        );
1833        let at = At { id: "u3", url: "https://ex.com/a", arg: "0.0025", done: &[] };
1834        assert_eq!(
1835            fix("budget_hit", &at),
1836            format!("{b} u3 fresh:true cost:0.0025 ≤$0.0025"),
1837            "dry routes the cap: oxy no-JS + bd"
1838        );
1839        assert_eq!(fix("provider_timeout", &At { arg: "", ..at }), format!("{b} u3 fresh:true ≤$0.0040"), "one space");
1840        assert_eq!(fix("not_found", &at), format!("check the URL · search for it: {b} <words>"), "no home");
1841        let search = At { id: "provider:bd rules", url: "", ..at };
1842        assert_eq!(
1843            fix("provider_refused", &search),
1844            format!("{b} rules fresh:true provider:oxy ≤$0.0010 · last try not charged"),
1845            "one provider:, and bd's refusal is one of `provider::REFUSED`, unbilled"
1846        );
1847        let ceil = At { url: "big.html", done: &["max_bytes:64m"], ..at };
1848        assert_eq!(fix("too_big", &ceil), "nothing left to try · open big.html in a browser", "the cap in force");
1849        assert_eq!(fix("blocked_451", &at), format!("{b} u3 fresh:true provider:oxy js:true ≤$0.0015"));
1850        assert_eq!(fix("brightdata_refused", &at), format!("{b} u3 fresh:true ≤$0.0040"), "an old code: the retry");
1851        // the fence's bypass is the user's own choice: a hint an agent runs never carries it
1852        assert!(FIX.iter().all(|r| !r.1.contains("FATS_ALLOW_PRIVATE")), "a fix prints the private-address bypass");
1853        assert_eq!(fix("private_address", &at), format!("private address refused · see {b} config"));
1854        // a fix never names a tier that already ran (or cannot run: bd on a gov host)
1855        let done = At { done: &["plain", "oxy", "bd"], ..at };
1856        assert_eq!(fix("not_pdf", &done), "nothing left to try · open https://ex.com/a in a browser");
1857        let want = format!("{b} u3 fresh:true provider:oxy js:true ≤$0.0015");
1858        assert_eq!(fix("captcha_wall", &done), want, "oxyjs untried");
1859        assert_eq!(fix("provider_refused", &done), want, "a refusal's no-JS fix, oxyjs untried");
1860        let all = At { done: &["plain", "oxy", "bd", "oxyjs", "decodo", "decodojs"], url: "", ..at };
1861        assert_eq!(fix("captcha_wall", &all), "nothing left to try");
1862        // oxy no-JS skipped by the site's wear, the render captcha'd: oxy is the move
1863        let skipped = At { done: &["plain", "oxyjs", "bd"], ..at };
1864        assert_eq!(fix("captcha_wall", &skipped), format!("{b} u3 fresh:true provider:oxy ≤$0.0025"));
1865        let free = format!("{b} u3 fresh:true ≤$0.0040 · last try not charged");
1866        assert_eq!(fix("provider_error", &At { arg: "", ..all }), free, "a transient retry names no tier");
1867        let named = At { arg: "provider:oxy js:true", done: &["plain", "oxy", "bd"], ..all };
1868        assert_eq!(fix("provider_error", &named), format!("{want} · last try not charged"), "the tier left");
1869    }
1870
1871    /// `since:` ages count back from today; dates fill the missing month and day.
1872    #[test]
1873    fn since_dates() {
1874        let today = 20_738; // 2026-10-12
1875        assert_eq!(civil(today), (2026, 10, 12));
1876        assert_eq!(civil(0), (1970, 1, 1));
1877        for (v, want) in [
1878            ("7d", "2026-10-05"),
1879            ("2w", "2026-09-28"),
1880            ("1m", "2026-09-12"),
1881            ("1y", "2025-10-12"),
1882            ("0d", "2026-10-12"),
1883            ("2026", "2026-01-01"),
1884            ("2026-01", "2026-01-01"),
1885            ("2024-02-29", "2024-02-29"),
1886        ] {
1887            assert_eq!(since_date(v, today).as_deref(), Some(want), "{v}");
1888        }
1889        for v in ["", "d", "7", "7x", "26-01", "2026-1", "2026-00", "2026-01-32", "2026-01-01-01", "-7d", "é7d"] {
1890            assert_eq!(since_date(v, today), None, "{v}");
1891        }
1892    }
1893
1894    #[test]
1895    fn helpers() {
1896        assert_eq!(short("https://www.example.com/abc", 8), "example…");
1897        assert_eq!(ksize(999), "999");
1898        assert_eq!(ksize(1250), "1.2k");
1899        assert_eq!(cut("ąćę", 2), "ąć");
1900        let o = Out::new(vec!["= x".into()]);
1901        assert!(emit(&o, true).contains("\"bytes_out\":3"));
1902    }
1903
1904    /// A whole key, any 12-char run of it (an echo that cuts the key), and a short key whole are masked; text
1905    /// around them, multi-byte text and values too short to be keys are left alone.
1906    #[test]
1907    fn redactor_masks_keys_and_their_runs() {
1908        let key = &["Ab3dEf6hIj9lMn2pQr5t".to_string()];
1909        let s = |v: &[&str]| v.iter().map(|x| x.to_string()).collect::<Vec<_>>();
1910        assert_eq!(redact(&format!("Invalid api key: {}.", key[0]), key), "Invalid api key: ***.");
1911        assert_eq!(redact("echo dEf6hIj9lMn2 end", key), "echo *** end", "a 12-char run");
1912        assert_eq!(redact("dEf6hIj9lMn end", key), "dEf6hIj9lMn end", "11 chars: not a run");
1913        assert_eq!(redact("ąć Ab3dEf6hIj9lMn2pQr5t ąć", key), "ąć *** ąć");
1914        assert_eq!(redact("a sunflower b", &s(&["sunflower"])), "a *** b", "8-11 chars: whole value");
1915        assert_eq!(redact("x y xyz", &s(&["x", "xyz"])), "x y xyz", "too short to be a key");
1916        assert_eq!(redact("ąćęłńóśźż-ąćę", &s(&["ąćęłńóśźż-ąć"])), "***ę", "runs on char boundaries");
1917    }
1918}