Skip to main content

fats/
telemetry.rs

1//! TELEMETRY: the one-time notice, the daily update check (L1) and the weekly counts (L2); what each sends is
2//! printed by `fats telemetry show` and listed in docs/telemetry.md. The foreground run only makes small files, one
3//! `create_new` each, so ten agents that start at once still ping once a day; the one process that made today's
4//! stamp goes on detached (`fats --continue telemetry`, `cli::detach`) and makes the call there. A process that
5//! started before the notice was shown sends nothing. Off under a CI marker (telemetry.json `ci_env`),
6//! `DO_NOT_TRACK`, `FATS_TELEMETRY=0` or `FATS_OFFLINE` (`settings::Settings::telemetry`): nothing written, nothing
7//! sent. Never sent: an id, a URL, a search, a path, a key.
8
9use crate::lang::{Out, bin, draw, screen};
10use crate::provider::{Api, block, ours};
11use crate::settings::{self, limit};
12use serde_json::{Value, json};
13use std::io::{Read, Seek, Write};
14use std::path::{Path, PathBuf};
15use std::sync::LazyLock;
16use std::time::{Duration, SystemTime};
17
18const VERSION: &str = env!("CARGO_PKG_VERSION");
19
20/// What is sent: `full` = L1 + L2, `minimal` = L1 only, `off` = nothing (no update hint either).
21#[derive(Clone, Copy, PartialEq, Eq)]
22pub enum Level {
23    Off,
24    Minimal,
25    Full,
26}
27
28impl Level {
29    /// `full` · `minimal` · `off`, or a boolean (`FATS_TELEMETRY=0` = off, `1` = full).
30    pub fn parse(v: &str) -> Option<Level> {
31        match v.to_ascii_lowercase().as_str() {
32            "full" => Some(Level::Full),
33            "minimal" => Some(Level::Minimal),
34            v => settings::boolean(v).map(|on| if on { Level::Full } else { Level::Off }),
35        }
36    }
37
38    pub fn name(self) -> &'static str {
39        ["off", "minimal", "full"][self as usize]
40    }
41}
42
43impl std::fmt::Debug for Level {
44    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45        f.write_str(self.name())
46    }
47}
48
49/// `env CI` … `env DO_NOT_TRACK`: the switches that turn it off whatever is set, as `config` names them.
50static OFF: LazyLock<Vec<String>> =
51    LazyLock::new(|| TABLE.ci_env.iter().chain(&["DO_NOT_TRACK".into()]).map(|k| format!("env {k}")).collect());
52
53/// Off whatever is set, and why: a robot is no user (a CI marker), the user said no to every tool (`DO_NOT_TRACK`),
54/// no network is allowed (`FATS_OFFLINE`). A switch is set by any value but an empty one or a no (`0`, `false`,
55/// `no`, `off`). `env` = the settings reader's (empty = unset).
56pub fn quiet(env: &dyn Fn(&str) -> Option<String>, offline: bool) -> Option<settings::Set<Level>> {
57    let on = |k: &str| env(k).is_some_and(|v| settings::boolean(&v) != Some(false));
58    let robot = OFF.iter().find(|k| on(k.trim_start_matches("env "))).map(String::as_str);
59    robot.or(offline.then_some("offline (FATS_OFFLINE)")).map(|src| settings::Set { value: Level::Off, src })
60}
61
62/// The level in effect (`settings::Settings::telemetry`).
63pub fn level() -> Level {
64    settings::get().telemetry.value
65}
66
67/// `src/data/telemetry.json`: the upgrade command of each install package (`via`), the env markers of a CI run.
68#[derive(serde::Deserialize)]
69#[serde(deny_unknown_fields)]
70struct Table {
71    upgrade: std::collections::BTreeMap<String, String>,
72    ci_env: Vec<String>,
73}
74static TABLE: LazyLock<Table> = LazyLock::new(|| settings::table("telemetry"));
75
76/// `<cache>/telemetry/<name>`: `ping/` the day and week stamps, `days/` the day marks (`d7`), `week/` the weekly
77/// tally (`cache::bump`), `latest.json` the last reply, `sent.jsonl`, notes to tell, the detached run's log.
78pub fn at(name: &str) -> PathBuf {
79    settings::get().cache.value.join("telemetry").join(name)
80}
81
82/// When this process started, in whole seconds (forced by `stats::hook`, the binary's first step): a notice made in
83/// an earlier second was shown by an earlier process.
84pub static STARTED: LazyLock<u64> = LazyLock::new(|| secs(SystemTime::now()));
85
86fn secs(t: SystemTime) -> u64 {
87    t.duration_since(SystemTime::UNIX_EPOCH).map_or(0, |d| d.as_secs())
88}
89
90/// Tries of a day's check (or a week's counts) that may go unanswered, and the wait after each.
91const TRIES: u32 = 3;
92const RETRY_S: u64 = 3600;
93
94/// `<key dir>/telemetry-notice`: made when the notice was shown, holding the month of the first run (`first`);
95/// beside the keys, so a wiped cache neither shows it again nor starts a new cohort.
96fn notice_file() -> PathBuf {
97    settings::get().key_dir.value.join("telemetry-notice")
98}
99
100/// This month (`2026-10`): the first run's, once this run's notice is claimed.
101fn month() -> String {
102    date(today()).format("%Y-%m").to_string()
103}
104
105fn today() -> i64 {
106    (crate::cache::now() / 86_400.0).floor() as i64
107}
108
109/// Days since 1970-01-01 → the UTC date.
110fn date(days: i64) -> chrono::NaiveDate {
111    chrono::DateTime::from_timestamp(days * 86_400, 0).unwrap_or_default().date_naive()
112}
113
114/// Today's update check stamp, per version: the first run after an upgrade checks at once (its notes).
115fn stamp() -> String {
116    format!("{}-{VERSION}", date(today()))
117}
118
119fn week_stamp() -> String {
120    format!("l2-{}", crate::cache::week_of(crate::cache::now()))
121}
122
123/// The CPU as the endpoints take it: `arm64`, `x86_64` (Rust says `aarch64`).
124pub fn arch() -> &'static str {
125    match std::env::consts::ARCH {
126        "aarch64" => "arm64",
127        a => a,
128    }
129}
130
131/// Make `path` holding `text`: true for the one process that made it (`create_new`), its folder made first. A text
132/// that fails to write reads as none (`first` = this month, a stamp = no retry).
133fn claim(path: &Path, text: &str) -> bool {
134    let make = || std::fs::File::options().write(true).create_new(true).open(path);
135    let made = make().or_else(|e| match (e.kind(), path.parent()) {
136        (std::io::ErrorKind::NotFound, Some(d)) => std::fs::create_dir_all(d).and_then(|()| make()),
137        _ => Err(e),
138    });
139    made.map(|mut f| f.write_all(text.as_bytes()).is_ok()).is_ok()
140}
141
142/// Whether this process makes the call `stamp` stands for. The stamp holds the tries not answered yet (a running
143/// one counts), `0` once one went through: the process that makes it tries first; after a failure, the one that
144/// takes its lock (never a wait) and finds it ≥ `RETRY_S` old with fewer than `TRIES` tries, its write the new
145/// mtime.
146fn due(stamp: &Path) -> bool {
147    if claim(stamp, "1") {
148        return true;
149    }
150    let Ok(mut f) = std::fs::File::options().read(true).write(true).open(stamp) else { return false };
151    let mut tries = String::new();
152    let held = f.try_lock().is_ok() && f.read_to_string(&mut tries).is_ok();
153    let age = f.metadata().and_then(|m| m.modified()).map_or(0, |t| secs(SystemTime::now()).saturating_sub(secs(t)));
154    let Some(n) = tries.trim().parse::<u32>().ok().filter(|n| held && age >= RETRY_S && (1..TRIES).contains(n)) else {
155        return false;
156    };
157    f.set_len(0).and_then(|()| f.rewind()).and_then(|()| write!(f, "{}", n + 1)).is_ok()
158}
159
160/// One call to our endpoint: the 200's body, or what failed (the HTTP status, else the code). A test build answers
161/// `FATS_FAKE_TELEMETRY=<status>` instead, without the network.
162fn call(to: Api, req: Value) -> Result<Vec<u8>, String> {
163    #[cfg(feature = "fake")]
164    if let Ok(status) = std::env::var("FATS_FAKE_TELEMETRY") {
165        return Err(status);
166    }
167    block(ours(to, req, Duration::from_secs(limit("telemetry_wait_s")))).unwrap_or_else(|| Err("net_error".into()))
168}
169
170/// After every command `cmd` (`main`, each MCP call), after its answer: the cache sweep (`cache::sweep`); then, but
171/// for a command about telemetry itself (`fats telemetry`, `fats setup telemetry …`: it may change the level now),
172/// the notice once (`shown`), today's day mark, notes the last check left (`tell`), and the update check: detached,
173/// by the one process that takes today's stamp (`due`); `FATS_TELEMETRY_DEBUG=1` prints it on stderr instead.
174pub fn tick(cmd: &[String]) {
175    crate::cache::sweep();
176    let s = settings::get();
177    let words: Vec<&str> = cmd.iter().flat_map(|a| a.split_whitespace()).collect();
178    let own = matches!(words[..], ["telemetry", ..] | ["setup", "telemetry", ..]);
179    if s.telemetry.value == Level::Off || own || !shown() {
180        return;
181    }
182    claim(&at(&format!("days/{}", date(today()))), "");
183    let mine = at(&format!("tell-{}", std::process::id()));
184    if std::fs::rename(at("tell"), &mine).is_ok() {
185        eprint!("{}", std::fs::read_to_string(&mine).unwrap_or_default());
186        std::fs::remove_file(&mine).ok();
187    }
188    if s.telemetry_debug.value {
189        eprintln!("[telemetry] GET {}", Api::Telemetry.url(&query()));
190        send_l2();
191    } else if due(&at(&format!("ping/{}", stamp()))) {
192        crate::cli::detach("telemetry".into(), &at("ping.log"), None).ok();
193    }
194}
195
196/// Whether this process may send: the notice was made in a second before this process started (by an earlier
197/// one). Else nothing goes, and the process that makes the notice's file shows it (stderr); one that cannot make it
198/// sends nothing either.
199fn shown() -> bool {
200    let file = notice_file();
201    if let Ok(t) = std::fs::metadata(&file).and_then(|m| m.modified()) {
202        return secs(t) < *STARTED;
203    }
204    if claim(&file, &month()) {
205        eprintln!("{}", page("notice").trim_end());
206    }
207    false
208}
209
210/// The update check's fields (docs/telemetry.md): schema, version, the version before an upgrade (`from`, until a
211/// check went through), OS, CPU, install package, month of the first run, days used of the last 7 (today too), level.
212fn query() -> Value {
213    let day = today();
214    let d7 = 1 + (1..7).filter(|k| at(&format!("days/{}", date(day - k))).exists()).count(); // today: this run
215    // before the first run's notice is claimed (after its command: `tick`), the month it will claim; a value not
216    // shaped YYYY-MM is never sent
217    let first = std::fs::read_to_string(notice_file()).ok().filter(|f| !f.trim().is_empty()).unwrap_or_else(month);
218    let digits: String = first.trim().chars().map(|c| if c.is_ascii_digit() { '9' } else { c }).collect();
219    let mut q = json!({"s": "1", "v": VERSION, "os": std::env::consts::OS, "arch": arch(), "via": via(),
220        "first": first.trim(), "d7": d7.to_string(), "t": level().name()});
221    if digits != "9999-99" {
222        q.as_object_mut().into_iter().for_each(|o| drop(o.remove("first")));
223    }
224    if let Some(from) = reply()["v"].as_str().filter(|v| *v != VERSION) {
225        q["from"] = from.into();
226    }
227    q
228}
229
230/// The last update check's reply (`latest`, `notes`, `skill`, the `l2` and `warn` switches) and the version that
231/// sent it (`v`), `checked`; Null before the first.
232fn reply() -> Value {
233    let mut r = crate::cache::jload(&at("latest.json")).unwrap_or_default();
234    checked(&mut r);
235    r
236}
237
238/// A reply as kept and told: `latest` only as `1.2.3`; `notes` and `warn` as their first line, control characters
239/// dropped, at most 200 chars (the user's terminal prints them).
240fn checked(r: &mut Value) {
241    let Some(o) = r.as_object_mut() else { return };
242    let digits = |n: &str| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit());
243    o.retain(|k, v| k != "latest" || v.as_str().is_some_and(|v| v.split('.').map(digits).eq([true; 3])));
244    for k in ["notes", "warn"] {
245        let line = o.get(k).and_then(Value::as_str).and_then(|t| t.lines().next()).unwrap_or_default();
246        let line: String = line.chars().filter(|c| !c.is_control()).take(200).collect();
247        o.insert(k.into(), Some(line).filter(|l| !l.trim().is_empty()).into());
248    }
249}
250
251/// The install package, by where this binary is: npm (its package's `node_modules`), Homebrew (`Cellar`), the
252/// shell installer (`$CARGO_HOME/bin` with the installer's receipt), cargo (`$CARGO_HOME/bin` without it), else
253/// unknown. Every answer has an upgrade command in the table.
254fn via() -> &'static str {
255    let exe = std::env::current_exe().and_then(std::fs::canonicalize).unwrap_or_default();
256    let has = |part: &str| exe.components().any(|c| c.as_os_str() == part);
257    let var = |k: &str| std::env::var_os(k).filter(|v| !v.is_empty()).map(PathBuf::from);
258    let cargo = var("CARGO_HOME").or_else(|| std::env::home_dir().map(|h| h.join(".cargo"))).unwrap_or_default();
259    let in_cargo = std::fs::canonicalize(cargo.join("bin")).is_ok_and(|b| exe.parent() == Some(b.as_path()));
260    // where the shell installer writes it: `$XDG_CONFIG_HOME`, else `~/.config`
261    let conf = var("XDG_CONFIG_HOME").or_else(|| std::env::home_dir().map(|h| h.join(".config"))).unwrap_or_default();
262    let receipt = conf.join("fatsearch").join("fatsearch-receipt.json").is_file();
263    match () {
264        _ if has("node_modules") => "npm",
265        _ if has("Cellar") => "brew",
266        _ if in_cargo && receipt => "sh",
267        _ if in_cargo => "cargo",
268        _ => "unknown",
269    }
270}
271
272/// The detached half (`fats --continue telemetry`): today's update check; its reply kept, what to tell the user
273/// left for the next run (`tick`), what was sent logged, a failed one too. A failed check keeps its stamp's count
274/// (`due`: a later run retries after an hour, three tries a day); never an error row, never a retry here. Exit code.
275pub fn send() -> i32 {
276    let (q, old) = (query(), reply());
277    if level() == Level::Off {
278        return 1;
279    }
280    let url = Api::Telemetry.url(&q);
281    let json = |b: Vec<u8>| serde_json::from_slice(&b).ok().filter(Value::is_object).ok_or_else(|| "not_json".into());
282    let got = call(Api::Telemetry, q.clone()).and_then(json);
283    log("l1", url.into(), got.as_ref().err());
284    let Ok(mut r) = got else { return 1 };
285    std::fs::write(at(&format!("ping/{}", stamp())), "0").ok();
286    checked(&mut r);
287    let mut tell = Vec::new();
288    if q.get("from").is_some() {
289        let notes = r["notes"].as_str().filter(|n| r["latest"] == VERSION && !n.is_empty());
290        tell.push(format!("~ {} updated to {VERSION}{}", bin(), notes.map(|n| format!(": {n}")).unwrap_or_default()));
291        tell.extend((r["skill"] == true).then(|| "~ new skill tips too: npx skills update fatsearch".to_string()));
292    }
293    tell.extend(r["warn"].as_str().filter(|w| old["warn"] != *w).map(|w| format!("~ {w}")));
294    let mut file = std::fs::File::options().append(true).create(true).open(at("tell"));
295    tell.iter().for_each(|t| drop(file.as_mut().map(|f| writeln!(f, "{t}"))));
296    r["v"] = VERSION.into();
297    std::fs::write(at("latest.json"), r.to_string()).ok();
298    prune();
299    send_l2();
300    0
301}
302
303/// Stamps of past days, weeks and versions, and day marks older than 7 days (`d7` counts the last 7).
304fn prune() {
305    let names =
306        |d: &str| std::fs::read_dir(at(d)).into_iter().flatten().flatten().map(|e| e.path()).collect::<Vec<_>>();
307    let (keep, oldest) = ([stamp(), week_stamp()], date(today() - 6).to_string());
308    let name = |p: &Path| p.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
309    let gone = names("ping").into_iter().filter(|p| !keep.contains(&name(p)));
310    for p in gone.chain(names("days").into_iter().filter(|p| name(p) < oldest)) {
311        std::fs::remove_file(p).ok();
312    }
313}
314
315/// The weekly counts (`stats::weekly`, last week's): level full only, by the one process that takes this week's
316/// stamp (`ping/l2-<week>`, `due`: three tries an hour apart), never while the last reply paused them (`"l2":
317/// false`), over `telemetry_l2_bytes` (the endpoint takes no more) or for a week with no command;
318/// `FATS_TELEMETRY_DEBUG=1` prints them instead.
319pub fn send_l2() {
320    let payload = weekly();
321    let Some(body) = l2_body(&payload) else { return };
322    if settings::get().telemetry_debug.value {
323        return eprintln!("[telemetry] POST {} {body}", Api::TelemetryL2.row().url);
324    }
325    let stamp = at(&format!("ping/{}", week_stamp()));
326    if !due(&stamp) {
327        return; // sent this week already, or tried within the hour, or another process sends it now
328    }
329    let sent = call(Api::TelemetryL2, payload.clone()).inspect(|_| drop(std::fs::write(&stamp, "0")));
330    log("l2", payload, sent.as_ref().err());
331}
332
333/// Last week's usage summary (`stats::weekly_of`): the payload the weekly send posts and `fats telemetry show` prints.
334fn weekly() -> Value {
335    crate::stats::weekly_of(
336        &settings::get().cache.value,
337        &crate::cache::week_of(crate::cache::now() - crate::cache::WEEK_S),
338    )
339}
340
341/// The weekly counts as they would go, or None: not full, paused, too big or empty.
342fn l2_body(payload: &Value) -> Option<String> {
343    let body = payload.to_string();
344    let used = payload["cmd"].as_object().is_some_and(|c| !c.is_empty());
345    let paused = reply()["l2"] == false || body.len() > limit::<usize>("telemetry_l2_bytes");
346    (level() == Level::Full && used && !paused).then_some(body)
347}
348
349/// One payload sent as `key` (`l1` its URL, `l2` its body) into `sent.jsonl` with its time and what failed; the
350/// last `telemetry_sent_keep` kept.
351fn log(key: &str, sent: Value, failed: Option<&String>) {
352    let p = at("sent.jsonl");
353    let at = chrono::DateTime::from_timestamp(crate::cache::now() as i64, 0).map(|t| t.format("%Y-%m-%dT%H:%M:%SZ"));
354    let mut row = json!({ "at": at.map(|t| t.to_string()) });
355    row[key] = sent;
356    failed.into_iter().for_each(|f| row["failed"] = f.as_str().into());
357    let mut rows: Vec<String> = std::fs::read_to_string(&p).unwrap_or_default().lines().map(String::from).collect();
358    rows.push(row.to_string());
359    let skip = rows.len().saturating_sub(limit("telemetry_sent_keep"));
360    std::fs::write(&p, rows[skip..].join("\n") + "\n").ok();
361}
362
363/// Part `name` of `src/data/screens/telemetry.txt` (the notice, the setup row).
364fn page(name: &str) -> &'static str {
365    screen("telemetry").split("§ ").find_map(|s| s.strip_prefix(name)?.strip_prefix('\n')).unwrap_or_default()
366}
367
368/// The `telemetry` row of `fats setup` (what is sent and never sent, how to change it).
369pub fn row() -> Vec<String> {
370    let level = format!("{:<6}", level().name());
371    draw(page("row"), &[("level", level.as_str()), ("b", bin())]).lines().map(String::from).collect()
372}
373
374/// The `telemetry` line of `fats status` and `fats telemetry`: the level and its source, and a newer version
375/// with its upgrade command (the last check's reply; none when off).
376pub fn status() -> String {
377    let (set, b) = (&settings::get().telemetry, bin());
378    let semver = |v: &str| v.split('.').map(|p| p.parse::<u64>().unwrap_or(0)).collect::<Vec<_>>();
379    let latest = reply()["latest"].as_str().map(String::from);
380    let newer = latest.filter(|l| set.value != Level::Off && semver(l) > semver(VERSION));
381    let how = TABLE.upgrade.get(via()).map_or("", String::as_str);
382    let hint = newer.map(|l| format!(" · {b} {l} available → {how}")).unwrap_or_default();
383    let (level, src) = (set.value.name(), set.src);
384    format!("telemetry {level} ({src}){hint} · what is sent: {b} telemetry show · {b} setup telemetry full|minimal|off")
385}
386
387/// `fats telemetry show`: the next update check exactly as it would go, the weekly counts, then the last ones sent
388/// (a failed one with its status) and, after a failed check, when the next may go.
389pub fn show() -> Out {
390    let (lvl, l2) = (level(), Api::TelemetryL2.row().url);
391    let mut lines = vec![format!("= {} · nothing sent now", status())];
392    lines.push(match lvl {
393        Level::Off => "next: nothing (off)".into(),
394        _ => format!("next daily: GET {}", Api::Telemetry.url(&query())),
395    });
396    lines.push(match (lvl, l2_body(&weekly())) {
397        (Level::Full, Some(body)) => format!("next weekly: POST {l2} {body}"),
398        (Level::Full, None) => "next weekly: nothing (no command last week, or paused by the server)".into(),
399        _ => "next weekly: nothing (full only)".into(),
400    });
401    let (p, keep) = (at("sent.jsonl"), |l: &str| serde_json::from_str::<Value>(l).ok());
402    let rows: Vec<Value> = std::fs::read_to_string(&p).unwrap_or_default().lines().filter_map(keep).collect();
403    let last = rows.iter().rev().find(|r| r["l1"].is_string()).filter(|r| r["failed"].is_string());
404    let tries = std::fs::read_to_string(at(&format!("ping/{}", stamp()))).unwrap_or_default();
405    let next = if tries.trim().parse().is_ok_and(|n: u32| n >= TRIES) { "tomorrow" } else { "after 1 h" };
406    lines.extend(last.map(|r| {
407        let day = r["at"].as_str().unwrap_or_default().split('T').next().unwrap_or_default();
408        format!("last check: {day} failed {} · next {next}", r["failed"].as_str().unwrap_or_default())
409    }));
410    lines.push(format!("sent: {} kept in {}", rows.len(), p.display()));
411    lines.extend(rows.iter().rev().map(|r| {
412        let at = r["at"].as_str().unwrap_or_default();
413        let failed = r["failed"].as_str().map(|f| format!(" · failed {f}")).unwrap_or_default();
414        match r["l1"].as_str() {
415            Some(u) => format!("{at} GET {u}{failed}"),
416            None => format!("{at} POST {l2} {}{failed}", r["l2"]),
417        }
418    }));
419    Out::new(lines)
420}
421
422#[cfg(test)]
423mod tests {
424    use super::*;
425
426    #[test]
427    fn levels_parse() {
428        let all = ["full", "MINIMAL", "off", "0", "1", "no", "maybe"].map(Level::parse);
429        let want = [Some(Level::Full), Some(Level::Minimal), Some(Level::Off), Some(Level::Off), Some(Level::Full)];
430        assert_eq!(all[..5], want);
431        assert_eq!((all[5], all[6]), (Some(Level::Off), None));
432        assert_eq!(format!("{:?}", Level::Minimal), "minimal", "a refused value's `using` names the level");
433        assert_eq!(page("notice"), "~ anonymous usage stats on · what's sent: fats telemetry show · off: fats setup\n");
434        assert_eq!(row().len(), 5, "the setup row: the level line and four more");
435        let via = ["npm", "brew", "sh", "cargo", "unknown"];
436        assert!(
437            via.iter().all(|v| TABLE.upgrade.contains_key(*v)) && TABLE.upgrade.len() == via.len(),
438            "what via names"
439        );
440    }
441
442    /// A reply as kept: `latest` only as `1.2.3`; `notes` and `warn` one printable line of at most 200 chars.
443    #[test]
444    fn replies_are_checked() {
445        let kept = |latest: &str, warn: &str| {
446            let mut r = json!({"latest": latest, "notes": "fixed\nsecond line", "warn": warn, "l2": false});
447            checked(&mut r);
448            r
449        };
450        assert_eq!(kept("1.2.3", "ok")["latest"], "1.2.3");
451        for bad in ["1.2", "1.2.3.4", "1.2.x", "1..3", "v1.2.3", "1.2.3-rc1", "1.2.3\u{1b}[2J"] {
452            assert_eq!(kept(bad, "")["latest"], Value::Null, "{bad}");
453        }
454        let r = kept("1.2.3", &format!("\u{1b}[31mred\u{7}{}", "é".repeat(300)));
455        assert_eq!((r["notes"].as_str(), r["l2"].as_bool()), (Some("fixed"), Some(false)));
456        let warn = r["warn"].as_str().unwrap_or_default();
457        assert!(warn.starts_with("[31mred") && warn.chars().count() == 200 && !warn.contains(char::is_control));
458        assert_eq!(kept("1.2.3", " \t\n")["warn"], Value::Null, "nothing printable: no note");
459        let mut odd = json!([1]);
460        checked(&mut odd);
461        assert_eq!(odd, json!([1]), "a reply that is no object stays what it is: read as none");
462    }
463}