Skip to main content

docsrs_cli/
lib.rs

1//! One-shot library and CLI for crates.io search and docs.rs documentation.
2//!
3//! `docsrs-cli` is agent-first: structured data on stdout, diagnostics on stderr,
4//! deterministic exit codes, and a BORN → EXECUTE → FINALIZE → DIE lifecycle with
5//! no daemon or sticky session state.
6//!
7//! This crate **consumes** published documentation from crates.io and docs.rs
8//! (and stdlib pages on `doc.rust-lang.org`). It does **not** replace docs.rs
9//! or re-implement `cargo doc` as a proprietary host.
10//!
11//! # Concurrency model (Rules Rust — parallelism)
12//!
13//! Workload is **mixed I/O + CPU** (see binary `main`, [`concurrency`], [`http::HttpClient`]):
14//! multi-thread Tokio for HTTPS, `spawn_blocking` under
15//! [`concurrency::ConcurrencyBudget`] for HTML parse, and `rayon` for large
16//! `all.html` hit scans. Bound via `--max-concurrency` / auto CPU+RAM formula.
17//! Fixed auxiliary tasks (double-interrupt, [`shutdown::ProgressGuard`]) still
18//! abort-on-drop. Shared cancel uses `Arc<AtomicU8>`, not `Mutex` across `.await`.
19//!
20//! # HTTP retry (Rules Rust — retry/backoff)
21//!
22//! Product GETs use [`retry::RetryConfig`]: exponential full-jitter backoff,
23//! `Retry-After` delta-seconds on 429/503, no retry on permanent 4xx/parse.
24//! Kill switch: `--disable-retry` / `DOCSRS_CLI_DISABLE_RETRY`. Policy is
25//! single-layer inside [`http::HttpClient`] only.
26//!
27//! # Features
28//!
29//! This package has no Cargo feature flags. All product capabilities ship in the
30//! default build. Optional network live tests are gated by environment variables
31//! (`DOCSRS_CLI_NETWORK_TESTS`, `DOCSRS_CLI_STDLIB_NETWORK_TESTS`), not features.
32//!
33//! # Safety
34//!
35//! - Product code in `src/` contains no `unsafe` blocks.
36//! - docs.rs builds enable `doc_cfg` via `#![cfg_attr(docsrs, feature(doc_cfg))]`
37//!   (post-2025 merge of `doc_auto_cfg` into `doc_cfg`). Local `cargo +stable doc`
38//!   does not require the nightly feature gate.
39//! - TLS is rustls-only; HTTP product methods are GET-only against an allowlist.
40//! - Mermaid diagrams for the agent lifecycle live on [`run`] via `aquamarine`
41//!   (attribute macros apply to items, not the crate root).
42//!
43//! # Examples
44//!
45//! Parse a crate name at the domain boundary:
46//!
47//! ```
48//! use docsrs_cli::domain::CrateName;
49//!
50//! let name = CrateName::parse("serde").expect("valid crate name");
51//! assert_eq!(name.as_str(), "serde");
52//! ```
53//!
54//! Map error kinds to process exit codes:
55//!
56//! ```
57//! use docsrs_cli::error::ErrorKind;
58//!
59//! assert_eq!(ErrorKind::NotFound.exit_code(), 66);
60//! assert!(ErrorKind::Timeout.retryable());
61//! ```
62
63#![warn(missing_docs)]
64#![warn(rustdoc::missing_crate_level_docs)]
65#![warn(rustdoc::broken_intra_doc_links)]
66#![warn(rustdoc::private_intra_doc_links)]
67#![deny(rustdoc::invalid_html_tags)]
68#![deny(rustdoc::invalid_rust_codeblocks)]
69#![deny(rustdoc::bare_urls)]
70#![warn(rustdoc::redundant_explicit_links)]
71#![cfg_attr(docsrs, feature(doc_cfg))]
72
73pub mod cache;
74pub mod cli;
75pub mod concurrency;
76pub mod config;
77pub mod crates_io;
78pub mod docs_rs;
79pub mod domain;
80pub mod error;
81pub mod http;
82pub mod i18n;
83pub mod item_kind;
84pub mod platform;
85pub mod render;
86pub mod retry;
87pub mod shutdown;
88pub mod telemetry;
89
90use std::io::{self, IsTerminal, Write};
91use std::path::Path;
92use std::process::ExitCode;
93use std::time::Duration;
94
95use clap::{CommandFactory, Parser};
96use serde::Serialize;
97use tokio::time::Instant;
98
99use crate::cache::DiskCache;
100use crate::cli::{CacheAction, Cli, Commands, ConfigAction};
101use crate::config::{
102    APP_NAME, APP_VERSION, Config, MSRV, SCHEMA_VERSION, config_path_data, docs_origin_for_crate,
103    init_config_toml,
104};
105use crate::domain::{CrateName, ItemPath, SearchQuery, VersionArg};
106use crate::error::{AppError, AppResult, ErrorKind};
107use crate::http::HttpClient;
108use crate::i18n::Locale;
109use crate::item_kind::ItemKind;
110use crate::render::{
111    apply_truncation_to_item, apply_truncation_to_readme, dry_run_envelope, error_envelope,
112    render_item_markdown, render_readme_markdown, render_search_in_crate_markdown,
113    render_search_markdown, success_envelope,
114};
115use crate::shutdown::{
116    CancelFlag, ProgressGuard, duration_ms, flush_stdio, race_op_with_cancel_and_deadline,
117    spawn_double_interrupt_force_exit,
118};
119use crate::telemetry::init_tracing;
120
121/// Parse argv and execute one command. Returns process exit code.
122///
123/// This is the binary entrypoint wrapper (stdin/stdout/stderr are process defaults).
124/// Agent-first: when stdout is not a TTY, JSON is auto-selected unless `--format` forces human.
125///
126/// # Lifecycle
127///
128/// ```mermaid
129/// sequenceDiagram
130///   participant A as Agent
131///   participant C as docsrs-cli
132///   participant N as crates.io / docs.rs
133///   A->>C: BORN spawn
134///   C->>N: EXECUTE GET
135///   N-->>C: body
136///   C-->>A: stdout envelope
137///   C->>C: FINALIZE flush
138///   C->>C: DIE exit code
139/// ```
140#[cfg_attr(doc, aquamarine::aquamarine)]
141pub async fn run<I, T>(args: I) -> ExitCode
142where
143    I: IntoIterator<Item = T>,
144    T: Into<std::ffi::OsString> + Clone,
145{
146    let stdout_is_terminal = io::stdout().is_terminal();
147    run_with_io(
148        args,
149        io::stdin(),
150        io::stdout(),
151        io::stderr(),
152        stdout_is_terminal,
153    )
154    .await
155}
156
157/// Injectable IO entrypoint for tests (`run(args, stdin, stdout, stderr, stdout_is_terminal)`).
158///
159/// `stdin` is reserved for future payload flows and is unused by current ops.
160/// Pass `stdout_is_terminal = true` to keep human markdown default in unit tests;
161/// the binary path passes the real `IsTerminal` of process stdout.
162pub async fn run_with_io<I, T, In, Out, ErrW>(
163    args: I,
164    _stdin: In,
165    mut stdout: Out,
166    mut stderr: ErrW,
167    stdout_is_terminal: bool,
168) -> ExitCode
169where
170    I: IntoIterator<Item = T>,
171    T: Into<std::ffi::OsString> + Clone,
172    In: io::Read,
173    Out: Write,
174    ErrW: Write,
175{
176    let cli = match Cli::try_parse_from(args) {
177        Ok(c) => c,
178        Err(e) => {
179            // clap prints help/usage itself to its preferred stream
180            let _ = e.print();
181            flush_stdio();
182            return if e.use_stderr() {
183                ExitCode::from(2)
184            } else {
185                ExitCode::SUCCESS
186            };
187        }
188    };
189
190    let code = match run_cli(cli, &mut stdout, &mut stderr, stdout_is_terminal).await {
191        Ok(code) => code,
192        Err(err) if err.kind() == ErrorKind::BrokenPipe => ExitCode::from(141),
193        Err(err) => {
194            // Domain errors should already have been turned into ExitCode via
195            // `emit_error` inside `run_cli`. This path is a last-resort safety net
196            // (preserves kind exit code; never hardcodes 70).
197            tracing::error!(
198                target: "docsrs_cli::telemetry",
199                error = %err,
200                kind = ?err.kind(),
201                "error escaped structured emit path"
202            );
203            let _ = writeln!(stderr, "error: {}", err.message());
204            err.exit_code()
205        }
206    };
207    flush_stdio();
208    let _ = stdout.flush();
209    let _ = stderr.flush();
210    code
211}
212
213async fn run_cli<Out: Write, ErrW: Write>(
214    cli: Cli,
215    stdout: &mut Out,
216    stderr: &mut ErrW,
217    stdout_is_terminal: bool,
218) -> Result<ExitCode, AppError> {
219    if let Err(e) = cli.validate_format_conflict() {
220        return Ok(emit_error(
221            &cli,
222            &e,
223            Locale::En,
224            stdout,
225            stderr,
226            stdout_is_terminal,
227        ));
228    }
229
230    init_tracing(&cli);
231
232    // Config load must go through `emit_error` so exit 78 / JSON envelope are correct.
233    // A bare `?` would bubble to `run_with_io` and historically forced exit 70.
234    let mut cfg = match Config::load_with_cache_dir(cli.config_dir.clone(), cli.cache_dir.clone())
235    {
236        Ok(c) => c,
237        Err(e) => {
238            return Ok(emit_error(
239                &cli,
240                &e,
241                Locale::En,
242                stdout,
243                stderr,
244                stdout_is_terminal,
245            ));
246        }
247    };
248    apply_cli_overrides(&cli, &mut cfg);
249
250    // Fail-closed on explicit/config/env lang before any network work.
251    let locale = match Locale::resolve(cli.lang.as_deref().or(cfg.lang.as_deref())) {
252        Ok(l) => l,
253        Err(e) => {
254            return Ok(emit_error(
255                &cli,
256                &e,
257                Locale::En,
258                stdout,
259                stderr,
260                stdout_is_terminal,
261            ));
262        }
263    };
264    let start = Instant::now();
265    let wants_json = cli.wants_json(stdout_is_terminal);
266    let dry_run = cli.dry_run;
267    let wall = Duration::from_secs(cfg.timeout_secs.max(1));
268    let cancel = CancelFlag::new();
269    // Rules Rust: first Ctrl-C is cooperative; second within 5s force-exits 130.
270    let force_on_second = spawn_double_interrupt_force_exit();
271
272    let cli_ref = &cli;
273    let cfg_ref = &cfg;
274    let result = race_op_with_cancel_and_deadline(wall, cancel.clone(), async {
275        dispatch(
276            cli_ref, cfg_ref, locale, dry_run, wants_json, start, cancel, stdout, stderr,
277        )
278        .await
279    })
280    .await;
281
282    force_on_second.abort();
283
284    match result {
285        Ok(code) => Ok(code),
286        Err(e) if e.kind() == ErrorKind::BrokenPipe => Ok(ExitCode::from(141)),
287        Err(e) => Ok(emit_error(
288            &cli,
289            &e,
290            locale,
291            stdout,
292            stderr,
293            stdout_is_terminal,
294        )),
295    }
296}
297
298fn apply_cli_overrides(cli: &Cli, cfg: &mut Config) {
299    if let Some(t) = cli.timeout {
300        cfg.timeout_secs = t;
301    }
302    if let Some(t) = cli.connect_timeout {
303        cfg.connect_timeout_secs = t;
304    }
305    if let Some(ref ua) = cli.user_agent {
306        cfg.user_agent.clone_from(ua);
307    }
308    if let Some(b) = cli.max_body_bytes {
309        cfg.max_body_bytes = b;
310    }
311    if let Some(b) = cli.max_output_bytes {
312        cfg.max_output_bytes = b;
313    }
314    if let Some(d) = cli.rate_limit_delay_ms {
315        cfg.rate_limit_delay_ms = d;
316    }
317    if let Some(n) = cli.max_concurrency {
318        cfg.max_concurrency = n;
319    }
320    if let Some(r) = cli.max_retries {
321        cfg.max_retries = r;
322    }
323    if let Some(ms) = cli.retry_base_ms {
324        cfg.retry_base_ms = ms;
325    }
326    if let Some(ms) = cli.retry_max_delay_ms {
327        cfg.retry_max_delay_ms = ms;
328    }
329    if cli.disable_retry {
330        cfg.disable_retry = true;
331    }
332    if let Some(ref l) = cli.lang {
333        match &mut cfg.lang {
334            Some(dst) => dst.clone_from(l),
335            None => cfg.lang = Some(l.clone()),
336        }
337    }
338    if cli.no_cache {
339        cfg.no_cache = true;
340    }
341    if let Some(ttl) = cli.cache_ttl_secs {
342        cfg.cache_ttl_secs = ttl;
343    }
344    if let Some(max) = cli.max_cache_bytes {
345        cfg.max_cache_bytes = max;
346    }
347    if let Some(ref dir) = cli.cache_dir {
348        cfg.cache_dir = Some(dir.clone());
349    }
350    // After all CLI mutations: hard ceiling (cannot elevate above HARD_MAX_*).
351    cfg.clamp_resource_limits();
352}
353
354#[allow(clippy::too_many_arguments)]
355async fn dispatch<Out: Write, ErrW: Write>(
356    cli: &Cli,
357    cfg: &Config,
358    locale: Locale,
359    dry_run: bool,
360    wants_json: bool,
361    start: Instant,
362    cancel: CancelFlag,
363    stdout: &mut Out,
364    _stderr: &mut ErrW,
365) -> AppResult<ExitCode> {
366    match &cli.command {
367        Commands::Version => {
368            if wants_json {
369                let data = VersionData {
370                    name: APP_NAME,
371                    version: APP_VERSION,
372                    msrv: MSRV,
373                    os: std::env::consts::OS,
374                    arch: std::env::consts::ARCH,
375                };
376                write_json(
377                    stdout,
378                    &success_envelope("version", &data, duration_ms(start), None),
379                )?;
380            } else {
381                writeln!(stdout, "{APP_NAME} {APP_VERSION}").map_err(map_stdout_err)?;
382            }
383            Ok(ExitCode::SUCCESS)
384        }
385        Commands::Doctor => doctor(cfg, wants_json, start, locale, stdout),
386        Commands::Commands => commands_cmd(wants_json, start, stdout),
387        Commands::Schema { cmd } => schema_cmd(cmd, wants_json, cli.format, start, stdout),
388        Commands::Completions { shell } => completions_cmd(*shell, wants_json, start, stdout),
389        Commands::Cache { action } => cache_cmd(cfg, action, wants_json, start, stdout),
390        Commands::Config { action } => config_cmd(cli, cfg, action, wants_json, start, stdout),
391        Commands::SearchCrates {
392            query,
393            per_page,
394            sort,
395            page,
396        } => {
397            let query = SearchQuery::parse(query, false)?;
398            let sort_s = sort.as_api_str();
399            // Clamp once so dry-run planned_params matches the URL and live request.
400            let (per_page, page) = crates_io::clamp_search_pagination(*per_page, *page);
401            let url = crates_io::planned_url_on_host(
402                &cfg.crates_io_origin,
403                query.as_str(),
404                per_page,
405                sort_s,
406                page,
407            )?;
408            if dry_run {
409                return emit_dry_run(
410                    "search-crates",
411                    url.as_str(),
412                    SearchCratesDryParams {
413                        q: query.as_str(),
414                        per_page,
415                        sort: sort_s,
416                        page,
417                    },
418                    wants_json,
419                    start,
420                    stdout,
421                );
422            }
423            let progress = ProgressGuard::start(
424                cli.quiet,
425                Duration::from_secs(2),
426                locale.progress_fetching("crates.io"),
427            );
428            let http = HttpClient::new(cfg.clone(), cancel)?;
429            let data = crates_io::search_crates_on_origin(
430                &http,
431                &cfg.crates_io_origin,
432                query.as_str(),
433                per_page,
434                sort_s,
435                page,
436            )
437            .await;
438            progress.finish();
439            let data = data?;
440            if wants_json {
441                write_json(
442                    stdout,
443                    &success_envelope(
444                        "search-crates",
445                        &data,
446                        duration_ms(start),
447                        Some(url.as_str()),
448                    ),
449                )?;
450            } else {
451                let md = render_search_markdown(&data);
452                let (out, _) = render::truncate_output(&md, cfg.max_output_bytes);
453                write!(stdout, "{out}").map_err(map_stdout_err)?;
454            }
455            Ok(ExitCode::SUCCESS)
456        }
457        Commands::Readme {
458            crate_name,
459            crate_version,
460        } => {
461            let crate_name = CrateName::parse(crate_name)?;
462            let version = VersionArg::parse_opt(crate_version.as_deref())?;
463            let origin = docs_origin_for_crate(cfg, crate_name.as_str());
464            let url =
465                docs_rs::readme_url_on_origin(&origin, crate_name.as_str(), version.as_str())?;
466            if dry_run {
467                return emit_dry_run(
468                    "readme",
469                    url.as_str(),
470                    ReadmeDryParams {
471                        crate_name: crate_name.as_str(),
472                        version: version.as_str(),
473                    },
474                    wants_json,
475                    start,
476                    stdout,
477                );
478            }
479            let progress = ProgressGuard::start(
480                cli.quiet,
481                Duration::from_secs(2),
482                locale.progress_fetching(crate_name.as_str()),
483            );
484            let http = HttpClient::new(cfg.clone(), cancel)?;
485            let data = docs_rs::fetch_readme_on_origin(
486                &http,
487                &origin,
488                crate_name.as_str(),
489                version.as_str(),
490            )
491            .await;
492            progress.finish();
493            let data = apply_truncation_to_readme(data?, cfg);
494            if wants_json {
495                write_json(
496                    stdout,
497                    &success_envelope("readme", &data, duration_ms(start), Some(&data.source_url)),
498                )?;
499            } else {
500                write!(stdout, "{}", render_readme_markdown(&data)).map_err(map_stdout_err)?;
501            }
502            Ok(ExitCode::SUCCESS)
503        }
504        Commands::GetItem {
505            crate_name,
506            item_type,
507            item_path,
508            crate_version,
509        } => {
510            let crate_name = CrateName::parse(crate_name)?;
511            let kind = ItemKind::parse(item_type)?;
512            let item_path = ItemPath::parse(item_path)?;
513            let segs = item_path.segments();
514            if let Some(first) = segs.first() {
515                let rustc = item_kind::rustc_crate_name(crate_name.as_str());
516                if first.as_str() != crate_name.as_str()
517                    && first.as_str() != rustc.as_str()
518                    && (first.contains('-') || first.contains('_'))
519                {
520                    tracing::warn!(
521                        path_crate = %first,
522                        expected = %crate_name,
523                        "item_path crate prefix differs from crate_name"
524                    );
525                }
526            }
527            let version = VersionArg::parse_opt(crate_version.as_deref())?;
528            let origin = docs_origin_for_crate(cfg, crate_name.as_str());
529            let url = docs_rs::get_item_url_on_origin(
530                &origin,
531                crate_name.as_str(),
532                version.as_str(),
533                kind,
534                segs,
535            )?;
536            if dry_run {
537                return emit_dry_run(
538                    "get-item",
539                    url.as_str(),
540                    GetItemDryParams {
541                        crate_name: crate_name.as_str(),
542                        item_type: kind.as_str(),
543                        item_path: item_path.as_str(),
544                        version: version.as_str(),
545                    },
546                    wants_json,
547                    start,
548                    stdout,
549                );
550            }
551            let progress = ProgressGuard::start(
552                cli.quiet,
553                Duration::from_secs(2),
554                locale.progress_fetching(item_path.as_str()),
555            );
556            let http = HttpClient::new(cfg.clone(), cancel)?;
557            let data = docs_rs::fetch_item_on_origin(
558                &http,
559                &origin,
560                crate_name.as_str(),
561                version.as_str(),
562                kind,
563                segs,
564            )
565            .await;
566            progress.finish();
567            let data = apply_truncation_to_item(data?, cfg);
568            if wants_json {
569                write_json(
570                    stdout,
571                    &success_envelope(
572                        "get-item",
573                        &data,
574                        duration_ms(start),
575                        Some(&data.source_url),
576                    ),
577                )?;
578            } else {
579                write!(stdout, "{}", render_item_markdown(&data)).map_err(map_stdout_err)?;
580            }
581            Ok(ExitCode::SUCCESS)
582        }
583        Commands::SearchInCrate {
584            crate_name,
585            query,
586            crate_version,
587            item_type,
588            limit,
589        } => {
590            let crate_name = CrateName::parse(crate_name)?;
591            let query = SearchQuery::parse(query, true)?;
592            let kind_filter = match item_type {
593                Some(t) if !t.is_empty() => Some(ItemKind::parse(t)?),
594                _ => None,
595            };
596            let version = VersionArg::parse_opt(crate_version.as_deref())?;
597            let origin = docs_origin_for_crate(cfg, crate_name.as_str());
598            let url =
599                docs_rs::all_html_url_on_origin(&origin, crate_name.as_str(), version.as_str())?;
600            if dry_run {
601                return emit_dry_run(
602                    "search-in-crate",
603                    url.as_str(),
604                    SearchInCrateDryParams {
605                        crate_name: crate_name.as_str(),
606                        query: query.as_str(),
607                        version: version.as_str(),
608                        item_type: kind_filter.map(|k| k.as_str()),
609                        limit: *limit,
610                    },
611                    wants_json,
612                    start,
613                    stdout,
614                );
615            }
616            let progress = ProgressGuard::start(
617                cli.quiet,
618                Duration::from_secs(2),
619                locale.progress_fetching(&format!("{} all.html", crate_name.as_str())),
620            );
621            let http = HttpClient::new(cfg.clone(), cancel)?;
622            let data = docs_rs::search_in_crate_on_origin(
623                &http,
624                &origin,
625                crate_name.as_str(),
626                version.as_str(),
627                query.as_str(),
628                kind_filter,
629                *limit,
630            )
631            .await;
632            progress.finish();
633            let data = data?;
634            if wants_json {
635                write_json(
636                    stdout,
637                    &success_envelope(
638                        "search-in-crate",
639                        &data,
640                        duration_ms(start),
641                        Some(&data.source_url),
642                    ),
643                )?;
644            } else {
645                let md = render_search_in_crate_markdown(&data);
646                let (out, _) = render::truncate_output(&md, cfg.max_output_bytes);
647                write!(stdout, "{out}").map_err(map_stdout_err)?;
648            }
649            Ok(ExitCode::SUCCESS)
650        }
651    }
652}
653
654fn doctor<Out: Write>(
655    cfg: &Config,
656    wants_json: bool,
657    start: Instant,
658    locale: Locale,
659    stdout: &mut Out,
660) -> AppResult<ExitCode> {
661    let mut checks = Vec::new();
662
663    checks.push(DoctorCheck {
664        name: "platform",
665        ok: true,
666        detail: crate::platform::platform_detail(),
667    });
668    checks.push(DoctorCheck {
669        name: "rustls_client",
670        ok: true,
671        detail: "reqwest built with rustls-tls".into(),
672    });
673    checks.push(DoctorCheck {
674        name: "user_agent",
675        ok: !cfg.user_agent.is_empty() && cfg.user_agent.contains(APP_NAME),
676        detail: cfg.user_agent.clone(),
677    });
678
679    let (config_ok, config_detail) = match &cfg.config_dir {
680        Some(p) => dir_ready_check(p),
681        None => (false, "default-not-resolved".into()),
682    };
683    checks.push(DoctorCheck {
684        name: "config_dir",
685        ok: config_ok,
686        detail: config_detail,
687    });
688
689    // XDG storage layer diagnostics (no .env runtime; no secret layers).
690    checks.push(DoctorCheck {
691        name: "config_source",
692        ok: cfg.config_path_source != crate::config::PathSource::Unresolved,
693        detail: cfg.config_path_source.as_str().into(),
694    });
695    let (cfg_file_ok, cfg_file_detail) = match cfg.config_file_path() {
696        Some(p) => {
697            if p.is_file() {
698                (
699                    true,
700                    format!(
701                        "present loaded={} path={}",
702                        cfg.config_toml_loaded,
703                        p.display()
704                    ),
705                )
706            } else {
707                (
708                    true,
709                    format!(
710                        "absent (optional; run config init) path={}",
711                        p.display()
712                    ),
713                )
714            }
715        }
716        None => (false, "config file path unresolved".into()),
717    };
718    checks.push(DoctorCheck {
719        name: "config_file",
720        ok: cfg_file_ok,
721        detail: cfg_file_detail,
722    });
723    checks.push(DoctorCheck {
724        name: "cache_source",
725        ok: cfg.no_cache || cfg.cache_path_source != crate::config::PathSource::Unresolved,
726        detail: if cfg.no_cache {
727            "n/a (--no-cache)".into()
728        } else {
729            cfg.cache_path_source.as_str().into()
730        },
731    });
732    checks.push(DoctorCheck {
733        name: "dotenv_runtime",
734        ok: true,
735        detail: "disabled (XDG + env allowlist only; no .env required after install)".into(),
736    });
737    checks.push(DoctorCheck {
738        name: "secrets_layers",
739        ok: true,
740        detail: "none (public HTTP only; keyring/cloud secret managers out of scope)".into(),
741    });
742
743    // Runtime clamps both to min 1s (`Config::timeout` / `connect_timeout`); report effective values.
744    let eff_timeout = cfg.timeout_secs.max(1);
745    let eff_connect = cfg.connect_timeout_secs.max(1);
746    checks.push(DoctorCheck {
747        name: "timeouts",
748        ok: true,
749        detail: format!("timeout={eff_timeout}s connect={eff_connect}s"),
750    });
751
752    let resolved_conc = crate::concurrency::resolve_max_concurrency(cfg.max_concurrency);
753    let workers = crate::concurrency::runtime_worker_threads();
754    checks.push(DoctorCheck {
755        name: "concurrency",
756        ok: true,
757        detail: format!(
758            "max_concurrency={} (configured={}; 0=auto) runtime_workers≈{} formula=min(cpus,free_ram/2/{}MiB) cap={}",
759            resolved_conc,
760            cfg.max_concurrency,
761            workers,
762            crate::concurrency::RAM_PER_TASK_MIB,
763            crate::concurrency::MAX_AUTO_CONCURRENCY
764        ),
765    });
766
767    let retry = crate::retry::RetryConfig::from_config(cfg);
768    checks.push(DoctorCheck {
769        name: "retry_policy",
770        ok: true,
771        detail: format!(
772            "enabled={} max_retries={} base_ms={} max_delay_ms={} max_attempts={} formula=full_jitter(min(base*2^n,max_delay)) kill_switch=--disable-retry",
773            retry.enabled,
774            retry.max_retries,
775            retry.base_ms,
776            retry.max_delay_ms,
777            retry.max_attempts()
778        ),
779    });
780
781    let (cache_ok, cache_detail) = if cfg.no_cache {
782        (true, "disabled (--no-cache)".to_string())
783    } else {
784        match &cfg.cache_dir {
785            Some(p) => {
786                let (ready, ready_detail) = dir_ready_check(p);
787                if !ready {
788                    (false, ready_detail)
789                } else {
790                    let stats =
791                        DiskCache::new(p.clone(), cfg.cache_ttl(), cfg.max_cache_bytes).stats();
792                    let budget = if cfg.max_cache_bytes == 0 {
793                        "unlimited".to_string()
794                    } else {
795                        format!("{}B", cfg.max_cache_bytes)
796                    };
797                    (
798                        true,
799                        format!(
800                            "enabled dir={} ttl={}s max={} entries={} used={}B parser={}",
801                            p.display(),
802                            cfg.cache_ttl_secs,
803                            budget,
804                            stats.entries,
805                            stats.total_bytes,
806                            crate::cache::CACHE_PARSER_VERSION
807                        ),
808                    )
809                }
810            }
811            None => (false, "no cache dir resolved".to_string()),
812        }
813    };
814    checks.push(DoctorCheck {
815        name: "disk_cache",
816        ok: cache_ok,
817        detail: cache_detail,
818    });
819
820    // Cross-process rate-limit lock+stamp directory (same root as disk cache).
821    let (rl_ok, rl_detail) = if cfg.no_cache {
822        (
823            true,
824            "n/a (--no-cache; in-process rate limit only)".to_string(),
825        )
826    } else {
827        match &cfg.cache_dir {
828            Some(p) => {
829                let rl = p.join("rate-limit");
830                dir_ready_check(&rl)
831            }
832            None => (
833                false,
834                "no cache dir resolved (cross-process rate limit unavailable)".to_string(),
835            ),
836        }
837    };
838    checks.push(DoctorCheck {
839        name: "rate_limit_dir",
840        ok: rl_ok,
841        detail: rl_detail,
842    });
843
844    // Resolved human locale for stderr prose (JSON messages stay English).
845    checks.push(DoctorCheck {
846        name: "lang",
847        ok: true,
848        detail: locale.as_bcp47().into(),
849    });
850
851    let ok = checks.iter().all(|c| c.ok);
852    let data = DoctorData { ok, checks };
853    if wants_json {
854        write_json(
855            stdout,
856            &success_envelope("doctor", &data, duration_ms(start), None),
857        )?;
858    } else {
859        writeln!(stdout, "{}", locale.doctor_ok(ok)).map_err(map_stdout_err)?;
860        for c in &data.checks {
861            writeln!(
862                stdout,
863                "- {} [{}] {}",
864                c.name,
865                if c.ok { "ok" } else { "fail" },
866                c.detail
867            )
868            .map_err(map_stdout_err)?;
869        }
870    }
871    Ok(if ok {
872        ExitCode::SUCCESS
873    } else {
874        ExitCode::from(78)
875    })
876}
877
878/// Check that `path` is an existing writable directory, or can be created under a
879/// writable ancestor. Does not leave directories behind when only probing parents.
880fn dir_ready_check(path: &Path) -> (bool, String) {
881    if path.is_dir() {
882        let probe = path.join(".docsrs-cli-doctor-write-probe");
883        return match std::fs::OpenOptions::new()
884            .write(true)
885            .create(true)
886            .truncate(true)
887            .open(&probe)
888        {
889            Ok(_) => {
890                let _ = std::fs::remove_file(&probe);
891                (true, path.display().to_string())
892            }
893            Err(e) => (false, format!("{} (not writable: {e})", path.display())),
894        };
895    }
896    if path.exists() {
897        return (
898            false,
899            format!("{} (exists but is not a directory)", path.display()),
900        );
901    }
902    let mut ancestor = path.parent();
903    while let Some(a) = ancestor {
904        if a.as_os_str().is_empty() {
905            break;
906        }
907        if a.is_dir() {
908            let probe = a.join(".docsrs-cli-doctor-write-probe");
909            return match std::fs::OpenOptions::new()
910                .write(true)
911                .create(true)
912                .truncate(true)
913                .open(&probe)
914            {
915                Ok(_) => {
916                    let _ = std::fs::remove_file(&probe);
917                    (
918                        true,
919                        format!("{} (creatable under {})", path.display(), a.display()),
920                    )
921                }
922                Err(e) => (
923                    false,
924                    format!("{} (ancestor not writable: {e})", path.display()),
925                ),
926            };
927        }
928        if a.exists() {
929            return (
930                false,
931                format!("{} (ancestor is not a directory)", path.display()),
932            );
933        }
934        ancestor = a.parent();
935    }
936    (
937        false,
938        format!("{} (missing; no writable ancestor)", path.display()),
939    )
940}
941
942fn cache_cmd<Out: Write>(
943    cfg: &Config,
944    action: &CacheAction,
945    wants_json: bool,
946    start: Instant,
947    stdout: &mut Out,
948) -> AppResult<ExitCode> {
949    let root = cfg.cache_dir.clone().ok_or_else(|| {
950        AppError::new(
951            ErrorKind::Config,
952            "cache directory could not be resolved (set --cache-dir or DOCSRS_CLI_CACHE_DIR)",
953        )
954    })?;
955    let cache = DiskCache::new(root, cfg.cache_ttl(), cfg.max_cache_bytes);
956    match action {
957        CacheAction::Clear => {
958            let result = cache.clear()?;
959            if wants_json {
960                write_json(
961                    stdout,
962                    &success_envelope("cache-clear", &result, duration_ms(start), None),
963                )?;
964            } else {
965                writeln!(
966                    stdout,
967                    "cache cleared: {} entries, {} bytes freed ({})",
968                    result.removed_entries, result.freed_bytes, result.root
969                )
970                .map_err(map_stdout_err)?;
971            }
972        }
973        CacheAction::Stats => {
974            let stats = cache.stats();
975            if wants_json {
976                write_json(
977                    stdout,
978                    &success_envelope("cache-stats", &stats, duration_ms(start), None),
979                )?;
980            } else {
981                let budget = if stats.max_bytes == 0 {
982                    "unlimited".to_string()
983                } else {
984                    format!("{}B", stats.max_bytes)
985                };
986                writeln!(
987                    stdout,
988                    "cache root={} layout={} entries={} used={}B max={} ttl={}s parser={}",
989                    stats.root,
990                    stats.layout,
991                    stats.entries,
992                    stats.total_bytes,
993                    budget,
994                    stats.ttl_secs,
995                    stats.parser_version
996                )
997                .map_err(map_stdout_err)?;
998            }
999        }
1000    }
1001    Ok(ExitCode::SUCCESS)
1002}
1003
1004/// XDG config lifecycle: path inventory, effective show, init template.
1005fn config_cmd<Out: Write>(
1006    cli: &Cli,
1007    cfg: &Config,
1008    action: &ConfigAction,
1009    wants_json: bool,
1010    start: Instant,
1011    stdout: &mut Out,
1012) -> AppResult<ExitCode> {
1013    match action {
1014        ConfigAction::Path => {
1015            let data = config_path_data(cfg);
1016            if wants_json {
1017                write_json(
1018                    stdout,
1019                    &success_envelope("config-path", &data, duration_ms(start), None),
1020                )?;
1021            } else {
1022                writeln!(
1023                    stdout,
1024                    "config_dir={} source={}",
1025                    data.config_dir.as_deref().unwrap_or("<unresolved>"),
1026                    data.config_source.as_str()
1027                )
1028                .map_err(map_stdout_err)?;
1029                writeln!(
1030                    stdout,
1031                    "config_file={} exists={} loaded={}",
1032                    data.config_file.as_deref().unwrap_or("<unresolved>"),
1033                    data.config_file_exists,
1034                    data.config_toml_loaded
1035                )
1036                .map_err(map_stdout_err)?;
1037                writeln!(
1038                    stdout,
1039                    "cache_dir={} source={}",
1040                    data.cache_dir.as_deref().unwrap_or("<unresolved>"),
1041                    data.cache_source.as_str()
1042                )
1043                .map_err(map_stdout_err)?;
1044                writeln!(
1045                    stdout,
1046                    "dotenv_runtime={} secrets={}",
1047                    data.dotenv_runtime, data.secrets_layers
1048                )
1049                .map_err(map_stdout_err)?;
1050            }
1051        }
1052        ConfigAction::Show => {
1053            if wants_json {
1054                write_json(
1055                    stdout,
1056                    &success_envelope("config-show", cfg, duration_ms(start), None),
1057                )?;
1058            } else {
1059                let pretty = serde_json::to_string_pretty(cfg).map_err(|e| {
1060                    AppError::with_source(ErrorKind::Internal, "failed to serialize config", e)
1061                })?;
1062                writeln!(stdout, "{pretty}").map_err(map_stdout_err)?;
1063            }
1064        }
1065        ConfigAction::Init { force } => {
1066            let result = init_config_toml(cli.config_dir.clone(), *force)?;
1067            if wants_json {
1068                write_json(
1069                    stdout,
1070                    &success_envelope("config-init", &result, duration_ms(start), None),
1071                )?;
1072            } else {
1073                let verb = if result.overwritten {
1074                    "overwrote"
1075                } else {
1076                    "created"
1077                };
1078                writeln!(
1079                    stdout,
1080                    "config init: {verb} {} (source={})",
1081                    result.path,
1082                    result.source.as_str()
1083                )
1084                .map_err(map_stdout_err)?;
1085            }
1086        }
1087    }
1088    Ok(ExitCode::SUCCESS)
1089}
1090
1091/// Emit the full command tree for agent discovery (`commands` subcommand).
1092fn commands_cmd<Out: Write>(
1093    wants_json: bool,
1094    start: Instant,
1095    stdout: &mut Out,
1096) -> AppResult<ExitCode> {
1097    let data = command_tree_data();
1098    if wants_json {
1099        write_json(
1100            stdout,
1101            &success_envelope("commands", &data, duration_ms(start), None),
1102        )?;
1103    } else {
1104        writeln!(
1105            stdout,
1106            "{} {} — command tree",
1107            data.name, data.version
1108        )
1109        .map_err(map_stdout_err)?;
1110        for c in data.commands {
1111            writeln!(stdout, "- {}: {}", c.name, c.about).map_err(map_stdout_err)?;
1112            for s in c.subcommands {
1113                writeln!(stdout, "  - {} {}: {}", c.name, s.name, s.about)
1114                    .map_err(map_stdout_err)?;
1115            }
1116        }
1117    }
1118    Ok(ExitCode::SUCCESS)
1119}
1120
1121/// Typed `version` success data (matches `docs/schemas/version.schema.json`).
1122#[derive(Debug, Serialize)]
1123struct VersionData {
1124    name: &'static str,
1125    version: &'static str,
1126    msrv: &'static str,
1127    os: &'static str,
1128    arch: &'static str,
1129}
1130
1131/// One doctor health check row.
1132#[derive(Debug, Serialize)]
1133struct DoctorCheck {
1134    name: &'static str,
1135    ok: bool,
1136    detail: String,
1137}
1138
1139/// Typed `doctor` success data (matches `docs/schemas/doctor.schema.json`).
1140#[derive(Debug, Serialize)]
1141struct DoctorData {
1142    ok: bool,
1143    checks: Vec<DoctorCheck>,
1144}
1145
1146/// Agent notes embedded in the `commands` tree.
1147#[derive(Debug, Serialize)]
1148struct AgentNotes {
1149    stdout: &'static str,
1150    stderr: &'static str,
1151    json_auto: &'static str,
1152    lifecycle: &'static str,
1153}
1154
1155/// One nested subcommand entry under `cache`.
1156#[derive(Debug, Serialize)]
1157struct SubCommandNode {
1158    name: &'static str,
1159    about: &'static str,
1160}
1161
1162/// One top-level command entry in the discovery tree.
1163#[derive(Debug, Serialize)]
1164struct CommandNode {
1165    name: &'static str,
1166    about: &'static str,
1167    args: &'static [&'static str],
1168    subcommands: &'static [SubCommandNode],
1169}
1170
1171/// Stable, ordered command tree for agents (no HashMap iteration).
1172#[derive(Debug, Serialize)]
1173struct CommandTree {
1174    name: &'static str,
1175    version: &'static str,
1176    msrv: &'static str,
1177    schema_version: u32,
1178    agent_notes: AgentNotes,
1179    commands: &'static [CommandNode],
1180}
1181
1182/// Schema command payload (`schema` stays `Value` — embedded JSON Schema document).
1183#[derive(Debug, Serialize)]
1184struct SchemaData<'a> {
1185    command: &'a str,
1186    schema: serde_json::Value,
1187    schema_version: u32,
1188}
1189
1190/// Completions command payload.
1191#[derive(Debug, Serialize)]
1192struct CompletionsData {
1193    shell: &'static str,
1194    script: String,
1195}
1196
1197/// Stable, ordered command tree for agents (no HashMap iteration).
1198fn command_tree_data() -> CommandTree {
1199    CommandTree {
1200        name: APP_NAME,
1201        version: APP_VERSION,
1202        msrv: MSRV,
1203        schema_version: SCHEMA_VERSION,
1204        agent_notes: AgentNotes {
1205            stdout: "data only (JSON envelope or markdown)",
1206            stderr: "diagnostics only",
1207            json_auto: "JSON is selected automatically when stdout is not a TTY unless --format markdown|text",
1208            lifecycle: "BORN → EXECUTE → FINALIZE → DIE (one-shot, no daemon)",
1209        },
1210        commands: &[
1211            CommandNode {
1212                name: "search-crates",
1213                about: "Search crates on crates.io",
1214                args: &["query", "--per-page", "--sort", "--page"],
1215                subcommands: &[],
1216            },
1217            CommandNode {
1218                name: "readme",
1219                about: "Fetch crate overview docblock from docs.rs (not git README)",
1220                args: &["crate_name", "--crate-version"],
1221                subcommands: &[],
1222            },
1223            CommandNode {
1224                name: "get-item",
1225                about: "Fetch documentation for a typed item",
1226                args: &["crate_name", "item_type", "item_path", "--crate-version"],
1227                subcommands: &[],
1228            },
1229            CommandNode {
1230                name: "search-in-crate",
1231                about: "Search symbols in crate all.html index",
1232                args: &["crate_name", "query", "--crate-version", "--item-type", "--limit"],
1233                subcommands: &[],
1234            },
1235            CommandNode {
1236                name: "version",
1237                about: "Print binary version",
1238                args: &[],
1239                subcommands: &[],
1240            },
1241            CommandNode {
1242                name: "doctor",
1243                about: "Validate local TLS/config readiness",
1244                args: &[],
1245                subcommands: &[],
1246            },
1247            CommandNode {
1248                name: "commands",
1249                about: "List the full command tree for agent discovery",
1250                args: &[],
1251                subcommands: &[],
1252            },
1253            CommandNode {
1254                name: "schema",
1255                about: "Emit JSON Schema for a command",
1256                args: &["--cmd"],
1257                subcommands: &[],
1258            },
1259            CommandNode {
1260                name: "completions",
1261                about: "Generate shell completions",
1262                args: &["shell"],
1263                subcommands: &[],
1264            },
1265            CommandNode {
1266                name: "cache",
1267                about: "Inspect or clear the XDG HTTP disk cache",
1268                args: &[],
1269                subcommands: &[
1270                    SubCommandNode {
1271                        name: "clear",
1272                        about: "Delete all cached HTTP bodies under the cache dir",
1273                    },
1274                    SubCommandNode {
1275                        name: "stats",
1276                        about: "Report entry count, total bytes, and budget",
1277                    },
1278                ],
1279            },
1280            CommandNode {
1281                name: "config",
1282                about: "Manage XDG config paths and optional config.toml (no secrets / no .env)",
1283                args: &[],
1284                subcommands: &[
1285                    SubCommandNode {
1286                        name: "path",
1287                        about: "Print resolved config/cache directories and which layer won",
1288                    },
1289                    SubCommandNode {
1290                        name: "show",
1291                        about: "Print effective runtime configuration",
1292                    },
1293                    SubCommandNode {
1294                        name: "init",
1295                        about: "Create default config.toml under the resolved config directory",
1296                    },
1297                ],
1298            },
1299        ],
1300    }
1301}
1302
1303fn schema_cmd<Out: Write>(
1304    cmd: &str,
1305    wants_json: bool,
1306    format: Option<crate::cli::OutputFormat>,
1307    start: Instant,
1308    stdout: &mut Out,
1309) -> AppResult<ExitCode> {
1310    let schema = match cmd {
1311        "search-crates" => include_str!("../docs/schemas/search-crates.schema.json"),
1312        "readme" => include_str!("../docs/schemas/readme.schema.json"),
1313        "get-item" => include_str!("../docs/schemas/get-item.schema.json"),
1314        "search-in-crate" => include_str!("../docs/schemas/search-in-crate.schema.json"),
1315        "version" => include_str!("../docs/schemas/version.schema.json"),
1316        "doctor" => include_str!("../docs/schemas/doctor.schema.json"),
1317        "commands" => include_str!("../docs/schemas/commands.schema.json"),
1318        "cache" | "cache-clear" | "cache-stats" => {
1319            include_str!("../docs/schemas/cache.schema.json")
1320        }
1321        "config" | "config-path" | "config-show" | "config-init" => {
1322            include_str!("../docs/schemas/config.schema.json")
1323        }
1324        other => {
1325            return Err(AppError::new(
1326                ErrorKind::Usage,
1327                format!("unknown schema command '{other}'"),
1328            ));
1329        }
1330    };
1331    let schema_val: serde_json::Value = serde_json::from_str(schema).map_err(|e| {
1332        AppError::with_source(ErrorKind::Internal, "embedded schema is invalid JSON", e)
1333    })?;
1334    // Branch first so JSON path can move `schema_val` into the envelope (no clone).
1335    if wants_json {
1336        let data = SchemaData {
1337            command: cmd,
1338            schema: schema_val,
1339            schema_version: SCHEMA_VERSION,
1340        };
1341        write_json(
1342            stdout,
1343            &success_envelope("schema", &data, duration_ms(start), None),
1344        )?;
1345    } else if matches!(format, Some(crate::cli::OutputFormat::Markdown)) {
1346        let md = render::render_schema_markdown(cmd, &schema_val);
1347        write!(stdout, "{md}").map_err(map_stdout_err)?;
1348    } else {
1349        writeln!(
1350            stdout,
1351            "{}",
1352            serde_json::to_string_pretty(&schema_val).unwrap_or_default()
1353        )
1354        .map_err(map_stdout_err)?;
1355    }
1356    Ok(ExitCode::SUCCESS)
1357}
1358
1359fn completions_cmd<Out: Write>(
1360    shell: crate::cli::Shell,
1361    wants_json: bool,
1362    start: Instant,
1363    stdout: &mut Out,
1364) -> AppResult<ExitCode> {
1365    let mut buf = Vec::new();
1366    let mut cmd = Cli::command();
1367    clap_complete::generate(shell.to_clap_shell(), &mut cmd, APP_NAME, &mut buf);
1368    let script = String::from_utf8_lossy(&buf).into_owned();
1369    if wants_json {
1370        let data = CompletionsData {
1371            shell: shell.as_str(),
1372            script,
1373        };
1374        write_json(
1375            stdout,
1376            &success_envelope("completions", &data, duration_ms(start), None),
1377        )?;
1378    } else {
1379        write!(stdout, "{script}").map_err(map_stdout_err)?;
1380        let _ = stdout.flush();
1381    }
1382    Ok(ExitCode::SUCCESS)
1383}
1384
1385/// Typed dry-run params for `search-crates` (keys match crates.io query string).
1386#[derive(Debug, Serialize)]
1387struct SearchCratesDryParams<'a> {
1388    q: &'a str,
1389    per_page: u32,
1390    sort: &'a str,
1391    page: u32,
1392}
1393
1394/// Typed dry-run params for `readme`.
1395#[derive(Debug, Serialize)]
1396struct ReadmeDryParams<'a> {
1397    #[serde(rename = "crate")]
1398    crate_name: &'a str,
1399    version: &'a str,
1400}
1401
1402/// Typed dry-run params for `get-item`.
1403#[derive(Debug, Serialize)]
1404struct GetItemDryParams<'a> {
1405    #[serde(rename = "crate")]
1406    crate_name: &'a str,
1407    item_type: &'a str,
1408    item_path: &'a str,
1409    version: &'a str,
1410}
1411
1412/// Typed dry-run params for `search-in-crate`.
1413#[derive(Debug, Serialize)]
1414struct SearchInCrateDryParams<'a> {
1415    #[serde(rename = "crate")]
1416    crate_name: &'a str,
1417    query: &'a str,
1418    version: &'a str,
1419    #[serde(skip_serializing_if = "Option::is_none")]
1420    item_type: Option<&'a str>,
1421    limit: u32,
1422}
1423
1424fn emit_dry_run<Out: Write, P: Serialize>(
1425    command: &str,
1426    planned_url: &str,
1427    planned_params: P,
1428    wants_json: bool,
1429    start: Instant,
1430    stdout: &mut Out,
1431) -> AppResult<ExitCode> {
1432    if wants_json {
1433        write_json(
1434            stdout,
1435            &dry_run_envelope(command, planned_url, &planned_params, duration_ms(start)),
1436        )?;
1437    } else {
1438        writeln!(stdout, "dry-run {command}").map_err(map_stdout_err)?;
1439        writeln!(stdout, "planned_url: {planned_url}").map_err(map_stdout_err)?;
1440        writeln!(
1441            stdout,
1442            "planned_params: {}",
1443            serde_json::to_string_pretty(&planned_params).unwrap_or_default()
1444        )
1445        .map_err(map_stdout_err)?;
1446    }
1447    Ok(ExitCode::SUCCESS)
1448}
1449
1450fn map_stdout_err(e: io::Error) -> AppError {
1451    if e.kind() == io::ErrorKind::BrokenPipe {
1452        AppError::broken_pipe()
1453    } else {
1454        AppError::with_source(ErrorKind::Internal, "stdout write", e)
1455    }
1456}
1457
1458/// Serialize one RFC 8259 JSON object (compact, single line) + trailing `\n`.
1459///
1460/// Product stdout is a single JSON document per invocation (not NDJSON streams).
1461/// Optional fields are omitted when `None` (`skip_serializing_if`), never `NaN`/`Infinity`.
1462///
1463/// Serialize to an intermediate buffer first so broken-pipe on write is mapped to
1464/// exit 141 without conflating pure serde failures with I/O.
1465fn write_json<Out: Write, T: Serialize>(stdout: &mut Out, v: &T) -> AppResult<()> {
1466    let mut buf = Vec::with_capacity(256);
1467    serde_json::to_writer(&mut buf, v)
1468        .map_err(|e| AppError::with_source(ErrorKind::Internal, "json serialize failed", e))?;
1469    buf.push(b'\n');
1470    stdout.write_all(&buf).map_err(map_stdout_err)?;
1471    let _ = stdout.flush();
1472    Ok(())
1473}
1474
1475fn emit_error<Out: Write, ErrW: Write>(
1476    cli: &Cli,
1477    err: &AppError,
1478    locale: Locale,
1479    stdout: &mut Out,
1480    stderr: &mut ErrW,
1481    stdout_is_terminal: bool,
1482) -> ExitCode {
1483    if cli.wants_json(stdout_is_terminal) {
1484        // Best-effort: preserve the original error exit code even if stdout is gone.
1485        let _ = write_json(stdout, &error_envelope(err));
1486    } else {
1487        // Human path: error on stderr; stdout stays empty.
1488        // Force with --format text|markdown even when stdout is a pipe.
1489        let _ = writeln!(stderr, "{}", locale.format_error(err.message()));
1490        let _ = stderr.flush();
1491    }
1492    flush_stdio();
1493    err.exit_code()
1494}