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` / TOML `disable_retry` / `max_retries=0`. 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        Ok(c) => c,
236        Err(e) => {
237            return Ok(emit_error(
238                &cli,
239                &e,
240                Locale::En,
241                stdout,
242                stderr,
243                stdout_is_terminal,
244            ));
245        }
246    };
247    if let Err(e) = apply_cli_overrides(&cli, &mut cfg) {
248        return Ok(emit_error(
249            &cli,
250            &e,
251            Locale::En,
252            stdout,
253            stderr,
254            stdout_is_terminal,
255        ));
256    }
257
258    // Fail-closed on explicit/config/env lang before any network work.
259    let locale = match Locale::resolve(cli.lang.as_deref().or(cfg.lang.as_deref())) {
260        Ok(l) => l,
261        Err(e) => {
262            return Ok(emit_error(
263                &cli,
264                &e,
265                Locale::En,
266                stdout,
267                stderr,
268                stdout_is_terminal,
269            ));
270        }
271    };
272    let start = Instant::now();
273    let wants_json = cli.wants_json(stdout_is_terminal);
274    let dry_run = cli.dry_run;
275    let wall = Duration::from_secs(cfg.timeout_secs.max(1));
276    let cancel = CancelFlag::new();
277    // Rules Rust: first Ctrl-C is cooperative; second within 5s force-exits 130.
278    let force_on_second = spawn_double_interrupt_force_exit();
279
280    let cli_ref = &cli;
281    let cfg_ref = &cfg;
282    let result = race_op_with_cancel_and_deadline(wall, cancel.clone(), async {
283        dispatch(
284            cli_ref, cfg_ref, locale, dry_run, wants_json, start, cancel, stdout, stderr,
285        )
286        .await
287    })
288    .await;
289
290    force_on_second.abort();
291
292    match result {
293        Ok(code) => Ok(code),
294        Err(e) if e.kind() == ErrorKind::BrokenPipe => Ok(ExitCode::from(141)),
295        Err(e) => Ok(emit_error(
296            &cli,
297            &e,
298            locale,
299            stdout,
300            stderr,
301            stdout_is_terminal,
302        )),
303    }
304}
305
306fn apply_cli_overrides(cli: &Cli, cfg: &mut Config) -> AppResult<()> {
307    if let Some(t) = cli.timeout {
308        if t == 0 {
309            return Err(AppError::new(
310                ErrorKind::InvalidInput,
311                "timeout must be >= 1 second (got 0)",
312            ));
313        }
314        cfg.timeout_secs = t;
315    }
316    if let Some(t) = cli.connect_timeout {
317        if t == 0 {
318            return Err(AppError::new(
319                ErrorKind::InvalidInput,
320                "connect_timeout must be >= 1 second (got 0)",
321            ));
322        }
323        cfg.connect_timeout_secs = t;
324    }
325    if let Some(ref ua) = cli.user_agent {
326        cfg.user_agent.clone_from(ua);
327    }
328    if let Some(b) = cli.max_body_bytes {
329        cfg.max_body_bytes = b;
330    }
331    if let Some(b) = cli.max_output_bytes {
332        cfg.max_output_bytes = b;
333    }
334    if let Some(d) = cli.rate_limit_delay_ms {
335        cfg.rate_limit_delay_ms = d;
336    }
337    if let Some(n) = cli.max_concurrency {
338        cfg.max_concurrency = n;
339    }
340    if let Some(r) = cli.max_retries {
341        cfg.max_retries = r;
342    }
343    if let Some(ms) = cli.retry_base_ms {
344        cfg.retry_base_ms = ms;
345    }
346    if let Some(ms) = cli.retry_max_delay_ms {
347        cfg.retry_max_delay_ms = ms;
348    }
349    if cli.disable_retry {
350        cfg.disable_retry = true;
351    }
352    if let Some(ref l) = cli.lang {
353        match &mut cfg.lang {
354            Some(dst) => dst.clone_from(l),
355            None => cfg.lang = Some(l.clone()),
356        }
357    }
358    if cli.no_cache {
359        cfg.no_cache = true;
360    }
361    if let Some(ttl) = cli.cache_ttl_secs {
362        cfg.cache_ttl_secs = ttl;
363    }
364    if let Some(max) = cli.max_cache_bytes {
365        cfg.max_cache_bytes = max;
366    }
367    if let Some(ref dir) = cli.cache_dir {
368        cfg.cache_dir = Some(dir.clone());
369    }
370    // After all CLI mutations: hard ceiling (cannot elevate above HARD_MAX_*).
371    cfg.clamp_resource_limits();
372    Ok(())
373}
374
375/// Rank nearby symbols for `--suggest` (exact → prefix → substring → edit distance).
376///
377/// Single in-memory pass over an all.html catalog (one prior HTTP fetch).
378fn rank_suggestions(leaf: &str, hits: &[docs_rs::SearchInCrateHit], limit: usize) -> Vec<String> {
379    use crate::domain::MatchMode;
380    let needle = leaf.trim();
381    if needle.is_empty() || limit == 0 {
382        return Vec::new();
383    }
384    let mut scored: Vec<(u8, &docs_rs::SearchInCrateHit)> = Vec::new();
385    for h in hits {
386        if let Some(s) = MatchMode::Exact.score(&h.name, needle) {
387            scored.push((s, h));
388            continue;
389        }
390        if let Some(s) = MatchMode::Prefix.score(&h.name, needle) {
391            scored.push((s.saturating_add(10), h));
392            continue;
393        }
394        if let Some(s) = MatchMode::Substring.score(&h.name, needle) {
395            scored.push((s.saturating_add(20), h));
396            continue;
397        }
398        let leaf_hit = h.name.rsplit("::").next().unwrap_or(h.name.as_str());
399        if let Some(d) = edit_distance_u8(needle, leaf_hit, 2) {
400            scored.push((30 + d, h));
401        }
402    }
403    scored.sort_by_key(|(s, h)| (*s, h.name.clone()));
404    let mut out = Vec::new();
405    let mut seen = std::collections::HashSet::new();
406    for (_, h) in scored {
407        let label = format!("{} ({})", h.name, h.kind);
408        if seen.insert(h.name.clone()) {
409            out.push(label);
410            if out.len() >= limit {
411                break;
412            }
413        }
414    }
415    out
416}
417
418/// Bounded Levenshtein distance; returns `None` when distance would exceed `max`.
419fn edit_distance_u8(a: &str, b: &str, max: u8) -> Option<u8> {
420    let a = a.to_ascii_lowercase();
421    let b = b.to_ascii_lowercase();
422    let (a, b) = (a.as_bytes(), b.as_bytes());
423    let (n, m) = (a.len(), b.len());
424    if n.abs_diff(m) > max as usize {
425        return None;
426    }
427    let max_u = max as usize;
428    let mut prev: Vec<usize> = (0..=m).collect();
429    let mut cur = vec![0usize; m + 1];
430    for i in 1..=n {
431        cur[0] = i;
432        let mut row_min = cur[0];
433        for j in 1..=m {
434            let cost = usize::from(a[i - 1] != b[j - 1]);
435            cur[j] = (prev[j] + 1).min(cur[j - 1] + 1).min(prev[j - 1] + cost);
436            row_min = row_min.min(cur[j]);
437        }
438        if row_min > max_u {
439            return None;
440        }
441        std::mem::swap(&mut prev, &mut cur);
442    }
443    let d = prev[m];
444    if d <= max_u { Some(d as u8) } else { None }
445}
446
447#[allow(clippy::too_many_arguments)]
448async fn dispatch<Out: Write, ErrW: Write>(
449    cli: &Cli,
450    cfg: &Config,
451    locale: Locale,
452    dry_run: bool,
453    wants_json: bool,
454    start: Instant,
455    cancel: CancelFlag,
456    stdout: &mut Out,
457    _stderr: &mut ErrW,
458) -> AppResult<ExitCode> {
459    match &cli.command {
460        Commands::Version => {
461            if wants_json {
462                let data = VersionData {
463                    name: APP_NAME,
464                    version: APP_VERSION,
465                    msrv: MSRV,
466                    os: std::env::consts::OS,
467                    arch: std::env::consts::ARCH,
468                };
469                write_json(
470                    stdout,
471                    &success_envelope("version", &data, duration_ms(start), None),
472                )?;
473            } else {
474                writeln!(stdout, "{APP_NAME} {APP_VERSION}").map_err(map_stdout_err)?;
475            }
476            Ok(ExitCode::SUCCESS)
477        }
478        Commands::Doctor { online } => doctor(cfg, *online, wants_json, start, locale, stdout),
479        Commands::Commands => commands_cmd(wants_json, start, stdout),
480        Commands::Schema { cmd } => schema_cmd(cmd, wants_json, cli.format, start, stdout),
481        Commands::Completions { shell } => {
482            // Completions emit shell script by default (even on non-TTY). JSON only if --json/--format json.
483            let explicit_json =
484                cli.json || matches!(cli.format, Some(crate::cli::OutputFormat::Json));
485            completions_cmd(*shell, explicit_json, start, stdout)
486        }
487        Commands::Cache { action } => cache_cmd(cfg, action, wants_json, start, stdout),
488        Commands::Config { action } => config_cmd(cli, cfg, action, wants_json, start, stdout),
489        Commands::SearchCrates {
490            query,
491            per_page,
492            sort,
493            page,
494            page_token,
495        } => {
496            // Full `meta.next_page` tokens already embed `q=…`; allow empty positional query then.
497            let token_carries_query = page_token.as_deref().is_some_and(|t| {
498                let qs = t.trim().trim_start_matches('?');
499                qs.contains('=')
500            });
501            let query = SearchQuery::parse(query, token_carries_query)?;
502            let sort_s = sort.as_api_str();
503            let (per_page, page) = crates_io::clamp_search_pagination(*per_page, *page);
504            let url = if let Some(token) = page_token.as_deref() {
505                crates_io::planned_url_with_page_token(
506                    &cfg.crates_io_origin,
507                    query.as_str(),
508                    per_page,
509                    sort_s,
510                    token,
511                )?
512            } else {
513                crates_io::planned_url_on_host(
514                    &cfg.crates_io_origin,
515                    query.as_str(),
516                    per_page,
517                    sort_s,
518                    page,
519                )?
520            };
521            // Single source of truth: echo params from the effective URL (GAP-001).
522            let fallback = crates_io::SearchEcho::from_cli(query.as_str(), page, per_page, sort_s);
523            let echo = crates_io::echo_params_from_url(&url, &fallback);
524            if dry_run {
525                return emit_dry_run(
526                    "search-crates",
527                    url.as_str(),
528                    SearchCratesDryParams {
529                        q: &echo.query,
530                        per_page: echo.per_page,
531                        sort: &echo.sort,
532                        page: echo.page,
533                        page_token: page_token.as_deref(),
534                    },
535                    wants_json,
536                    start,
537                    stdout,
538                );
539            }
540            let progress = ProgressGuard::start(
541                cli.quiet,
542                Duration::from_secs(2),
543                locale.progress_fetching("crates.io"),
544            );
545            let http = HttpClient::new(cfg.clone(), cancel)?;
546            let data = crates_io::search_crates_at(
547                &http,
548                &url,
549                &echo.query,
550                echo.per_page,
551                &echo.sort,
552                echo.page,
553            )
554            .await;
555            progress.finish();
556            let data = data?;
557            if wants_json {
558                write_json(
559                    stdout,
560                    &success_envelope(
561                        "search-crates",
562                        &data,
563                        duration_ms(start),
564                        Some(url.as_str()),
565                    ),
566                )?;
567            } else {
568                let md = render_search_markdown(&data);
569                let (out, _) = render::truncate_output(&md, cfg.max_output_bytes);
570                write!(stdout, "{out}").map_err(map_stdout_err)?;
571            }
572            Ok(ExitCode::SUCCESS)
573        }
574        Commands::Readme {
575            crate_name,
576            crate_version,
577        } => {
578            let crate_name = CrateName::parse(crate_name)?;
579            let version = VersionArg::parse_opt(crate_version.as_deref())?;
580            let origin = docs_origin_for_crate(cfg, crate_name.as_str());
581            let url =
582                docs_rs::readme_url_on_origin(&origin, crate_name.as_str(), version.as_str())?;
583            if dry_run {
584                return emit_dry_run(
585                    "readme",
586                    url.as_str(),
587                    ReadmeDryParams {
588                        crate_name: crate_name.as_str(),
589                        version: version.as_str(),
590                    },
591                    wants_json,
592                    start,
593                    stdout,
594                );
595            }
596            let progress = ProgressGuard::start(
597                cli.quiet,
598                Duration::from_secs(2),
599                locale.progress_fetching(crate_name.as_str()),
600            );
601            let http = HttpClient::new(cfg.clone(), cancel)?;
602            let data = docs_rs::fetch_readme_on_origin(
603                &http,
604                &origin,
605                crate_name.as_str(),
606                version.as_str(),
607            )
608            .await;
609            progress.finish();
610            let data = apply_truncation_to_readme(data?, cfg);
611            if wants_json {
612                write_json(
613                    stdout,
614                    &success_envelope("readme", &data, duration_ms(start), Some(&data.source_url)),
615                )?;
616            } else {
617                write!(stdout, "{}", render_readme_markdown(&data)).map_err(map_stdout_err)?;
618            }
619            Ok(ExitCode::SUCCESS)
620        }
621        Commands::GetItem {
622            crate_name,
623            item_type,
624            item_path,
625            crate_version,
626            suggest,
627        } => {
628            let crate_name = CrateName::parse(crate_name)?;
629            let kind = ItemKind::parse(item_type)?;
630            let item_path = ItemPath::parse(item_path)?;
631            let segs = item_path.segments();
632            if let Some(first) = segs.first() {
633                let rustc = item_kind::rustc_crate_name(crate_name.as_str());
634                if first.as_str() != crate_name.as_str()
635                    && first.as_str() != rustc.as_str()
636                    && (first.contains('-') || first.contains('_'))
637                {
638                    tracing::warn!(
639                        path_crate = %first,
640                        expected = %crate_name,
641                        "item_path crate prefix differs from crate_name"
642                    );
643                }
644            }
645            let version = VersionArg::parse_opt(crate_version.as_deref())?;
646            let origin = docs_origin_for_crate(cfg, crate_name.as_str());
647            let url = docs_rs::get_item_url_on_origin(
648                &origin,
649                crate_name.as_str(),
650                version.as_str(),
651                kind,
652                segs,
653            )?;
654            if dry_run {
655                return emit_dry_run(
656                    "get-item",
657                    url.as_str(),
658                    GetItemDryParams {
659                        crate_name: crate_name.as_str(),
660                        item_type: kind.as_str(),
661                        item_path: item_path.as_str(),
662                        version: version.as_str(),
663                    },
664                    wants_json,
665                    start,
666                    stdout,
667                );
668            }
669            let progress = ProgressGuard::start(
670                cli.quiet,
671                Duration::from_secs(2),
672                locale.progress_fetching(item_path.as_str()),
673            );
674            let http = HttpClient::new(cfg.clone(), cancel)?;
675            let data = docs_rs::fetch_item_on_origin(
676                &http,
677                &origin,
678                crate_name.as_str(),
679                version.as_str(),
680                kind,
681                segs,
682            )
683            .await;
684            progress.finish();
685            let data = match data {
686                Ok(d) => apply_truncation_to_item(d, cfg),
687                Err(e) if *suggest && e.kind() == ErrorKind::NotFound => {
688                    // Opt-in recovery: one all.html fetch, then cascade rank (GAP-005).
689                    let all_url = docs_rs::all_html_url_on_origin(
690                        &origin,
691                        crate_name.as_str(),
692                        version.as_str(),
693                    )?;
694                    let leaf = segs
695                        .last()
696                        .map(|s| s.as_str())
697                        .unwrap_or(item_path.as_str());
698                    if let Ok(catalog) = docs_rs::search_in_crate_at(
699                        &http,
700                        crate_name.as_str(),
701                        version.as_str(),
702                        "",
703                        None,
704                        1000,
705                        crate::domain::MatchMode::Prefix,
706                        &all_url,
707                    )
708                    .await
709                    {
710                        let names = rank_suggestions(leaf, &catalog.hits, 5);
711                        return Err(AppError::new(
712                            ErrorKind::NotFound,
713                            format!(
714                                "{}; suggestions: {}",
715                                e.message(),
716                                if names.is_empty() {
717                                    "(none)".into()
718                                } else {
719                                    names.join(", ")
720                                }
721                            ),
722                        ));
723                    }
724                    return Err(e);
725                }
726                Err(e) => return Err(e),
727            };
728            if wants_json {
729                write_json(
730                    stdout,
731                    &success_envelope(
732                        "get-item",
733                        &data,
734                        duration_ms(start),
735                        Some(&data.source_url),
736                    ),
737                )?;
738            } else {
739                write!(stdout, "{}", render_item_markdown(&data)).map_err(map_stdout_err)?;
740            }
741            Ok(ExitCode::SUCCESS)
742        }
743        Commands::SearchInCrate {
744            crate_name,
745            query,
746            crate_version,
747            item_type,
748            limit,
749            r#match,
750        } => {
751            let crate_name = CrateName::parse(crate_name)?;
752            let query = SearchQuery::parse(query, true)?;
753            let kind_filter = match item_type {
754                Some(t) if !t.is_empty() => Some(ItemKind::parse(t)?),
755                _ => None,
756            };
757            let match_mode = crate::domain::MatchMode::parse(r#match)?;
758            let version = VersionArg::parse_opt(crate_version.as_deref())?;
759            let origin = docs_origin_for_crate(cfg, crate_name.as_str());
760            let url =
761                docs_rs::all_html_url_on_origin(&origin, crate_name.as_str(), version.as_str())?;
762            let limit = (*limit).min(crate::config::MAX_SEARCH_IN_CRATE_LIMIT);
763            if dry_run {
764                return emit_dry_run(
765                    "search-in-crate",
766                    url.as_str(),
767                    SearchInCrateDryParams {
768                        crate_name: crate_name.as_str(),
769                        query: query.as_str(),
770                        version: version.as_str(),
771                        item_type: kind_filter.map(|k| k.as_str()),
772                        match_mode: Some(match_mode.as_str()),
773                        limit,
774                    },
775                    wants_json,
776                    start,
777                    stdout,
778                );
779            }
780            let progress = ProgressGuard::start(
781                cli.quiet,
782                Duration::from_secs(2),
783                locale.progress_fetching(&format!("{} all.html", crate_name.as_str())),
784            );
785            let http = HttpClient::new(cfg.clone(), cancel)?;
786            let data = docs_rs::search_in_crate_on_origin(
787                &http,
788                &origin,
789                crate_name.as_str(),
790                version.as_str(),
791                query.as_str(),
792                kind_filter,
793                limit,
794                match_mode,
795            )
796            .await;
797            progress.finish();
798            let data = data?;
799            if wants_json {
800                write_json(
801                    stdout,
802                    &success_envelope(
803                        "search-in-crate",
804                        &data,
805                        duration_ms(start),
806                        Some(&data.source_url),
807                    ),
808                )?;
809            } else {
810                let md = render_search_in_crate_markdown(&data);
811                let (out, _) = render::truncate_output(&md, cfg.max_output_bytes);
812                write!(stdout, "{out}").map_err(map_stdout_err)?;
813            }
814            Ok(ExitCode::SUCCESS)
815        }
816    }
817}
818
819fn doctor<Out: Write>(
820    cfg: &Config,
821    online: bool,
822    wants_json: bool,
823    start: Instant,
824    locale: Locale,
825    stdout: &mut Out,
826) -> AppResult<ExitCode> {
827    let mut checks = Vec::new();
828
829    checks.push(DoctorCheck {
830        name: "platform",
831        ok: true,
832        detail: crate::platform::platform_detail(),
833    });
834    checks.push(DoctorCheck {
835        name: "rustls_client",
836        ok: true,
837        detail: "reqwest built with rustls-tls".into(),
838    });
839    checks.push(DoctorCheck {
840        name: "user_agent",
841        ok: !cfg.user_agent.is_empty() && cfg.user_agent.contains(APP_NAME),
842        detail: cfg.user_agent.clone(),
843    });
844
845    let (config_ok, config_detail) = match &cfg.config_dir {
846        Some(p) => dir_ready_check(p),
847        None => (false, "default-not-resolved".into()),
848    };
849    checks.push(DoctorCheck {
850        name: "config_dir",
851        ok: config_ok,
852        detail: config_detail,
853    });
854
855    // XDG storage layer diagnostics (no .env runtime; no secret layers).
856    checks.push(DoctorCheck {
857        name: "config_source",
858        ok: cfg.config_path_source != crate::config::PathSource::Unresolved,
859        detail: cfg.config_path_source.as_str().into(),
860    });
861    let (cfg_file_ok, cfg_file_detail) = match cfg.config_file_path() {
862        Some(p) => {
863            if p.is_file() {
864                (
865                    true,
866                    format!(
867                        "present loaded={} path={}",
868                        cfg.config_toml_loaded,
869                        p.display()
870                    ),
871                )
872            } else {
873                (
874                    true,
875                    format!("absent (optional; run config init) path={}", p.display()),
876                )
877            }
878        }
879        None => (false, "config file path unresolved".into()),
880    };
881    checks.push(DoctorCheck {
882        name: "config_file",
883        ok: cfg_file_ok,
884        detail: cfg_file_detail,
885    });
886    checks.push(DoctorCheck {
887        name: "cache_source",
888        ok: cfg.no_cache || cfg.cache_path_source != crate::config::PathSource::Unresolved,
889        detail: if cfg.no_cache {
890            "n/a (--no-cache)".into()
891        } else {
892            cfg.cache_path_source.as_str().into()
893        },
894    });
895    checks.push(DoctorCheck {
896        name: "dotenv_runtime",
897        ok: true,
898        detail: "disabled (XDG + env allowlist only; no .env required after install)".into(),
899    });
900    checks.push(DoctorCheck {
901        name: "secrets_layers",
902        ok: true,
903        detail: "none (public HTTP only; keyring/cloud secret managers out of scope)".into(),
904    });
905
906    // Runtime clamps both to min 1s (`Config::timeout` / `connect_timeout`); report effective values.
907    let eff_timeout = cfg.timeout_secs.max(1);
908    let eff_connect = cfg.connect_timeout_secs.max(1);
909    checks.push(DoctorCheck {
910        name: "timeouts",
911        ok: true,
912        detail: format!("timeout={eff_timeout}s connect={eff_connect}s"),
913    });
914
915    let resolved_conc = crate::concurrency::resolve_max_concurrency(cfg.max_concurrency);
916    let workers = crate::concurrency::runtime_worker_threads();
917    checks.push(DoctorCheck {
918        name: "concurrency",
919        ok: true,
920        detail: format!(
921            "max_concurrency={} (configured={}; 0=auto) runtime_workers≈{} formula=min(cpus,free_ram/2/{}MiB) cap={}",
922            resolved_conc,
923            cfg.max_concurrency,
924            workers,
925            crate::concurrency::RAM_PER_TASK_MIB,
926            crate::concurrency::MAX_AUTO_CONCURRENCY
927        ),
928    });
929
930    let retry = crate::retry::RetryConfig::from_config(cfg);
931    checks.push(DoctorCheck {
932        name: "retry_policy",
933        ok: true,
934        detail: format!(
935            "enabled={} max_retries={} base_ms={} max_delay_ms={} max_attempts={} formula=full_jitter(min(base*2^n,max_delay)) kill_switch=--disable-retry",
936            retry.enabled,
937            retry.max_retries,
938            retry.base_ms,
939            retry.max_delay_ms,
940            retry.max_attempts()
941        ),
942    });
943
944    let (cache_ok, cache_detail) = if cfg.no_cache {
945        (true, "disabled (--no-cache)".to_string())
946    } else {
947        match &cfg.cache_dir {
948            Some(p) => {
949                let (ready, ready_detail) = dir_ready_check(p);
950                if !ready {
951                    (false, ready_detail)
952                } else {
953                    let stats =
954                        DiskCache::new(p.clone(), cfg.cache_ttl(), cfg.max_cache_bytes).stats();
955                    let budget = if cfg.max_cache_bytes == 0 {
956                        "unlimited".to_string()
957                    } else {
958                        format!("{}B", cfg.max_cache_bytes)
959                    };
960                    (
961                        true,
962                        format!(
963                            "enabled dir={} ttl={}s max={} entries={} used={}B parser={}",
964                            p.display(),
965                            cfg.cache_ttl_secs,
966                            budget,
967                            stats.entries,
968                            stats.total_bytes,
969                            crate::cache::CACHE_PARSER_VERSION
970                        ),
971                    )
972                }
973            }
974            None => (false, "no cache dir resolved".to_string()),
975        }
976    };
977    checks.push(DoctorCheck {
978        name: "disk_cache",
979        ok: cache_ok,
980        detail: cache_detail,
981    });
982
983    // Cross-process rate-limit lock+stamp directory (same root as disk cache).
984    let (rl_ok, rl_detail) = if cfg.no_cache {
985        (
986            true,
987            "n/a (--no-cache; in-process rate limit only)".to_string(),
988        )
989    } else {
990        match &cfg.cache_dir {
991            Some(p) => {
992                let rl = p.join("rate-limit");
993                dir_ready_check(&rl)
994            }
995            None => (
996                false,
997                "no cache dir resolved (cross-process rate limit unavailable)".to_string(),
998            ),
999        }
1000    };
1001    checks.push(DoctorCheck {
1002        name: "rate_limit_dir",
1003        ok: rl_ok,
1004        detail: rl_detail,
1005    });
1006
1007    // Resolved human locale for stderr prose (JSON messages stay English).
1008    checks.push(DoctorCheck {
1009        name: "lang",
1010        ok: true,
1011        detail: locale.as_bcp47().into(),
1012    });
1013
1014    // Contact URL should not be the historical placeholder host.
1015    let ua_contact_ok = !cfg.user_agent.contains("github.com/docsrs-cli/docsrs-cli");
1016    checks.push(DoctorCheck {
1017        name: "user_agent_contact",
1018        ok: ua_contact_ok,
1019        detail: if ua_contact_ok {
1020            "contact is not the placeholder docsrs-cli org".into()
1021        } else {
1022            "placeholder contact host github.com/docsrs-cli/docsrs-cli is invalid".into()
1023        },
1024    });
1025
1026    if online {
1027        // Sync DNS/TCP probe (no async runtime needed inside doctor).
1028        for (name, host) in [
1029            ("online_crates_io", "crates.io"),
1030            ("online_docs_rs", "docs.rs"),
1031        ] {
1032            let ok_probe = std::net::ToSocketAddrs::to_socket_addrs(&format!("{host}:443"))
1033                .map(|mut it| it.next().is_some())
1034                .unwrap_or(false);
1035            checks.push(DoctorCheck {
1036                name,
1037                ok: ok_probe,
1038                detail: if ok_probe {
1039                    format!("{host}:443 resolves")
1040                } else {
1041                    format!("{host}:443 DNS/resolve failed")
1042                },
1043            });
1044        }
1045    }
1046
1047    let ok = checks.iter().all(|c| c.ok);
1048    let data = DoctorData { ok, checks };
1049    if wants_json {
1050        // Agent-first: top-level `ok` mirrors `data.ok` (GAP-004). Exit 78 when unhealthy.
1051        write_json(
1052            stdout,
1053            &render::success_envelope_with_ok("doctor", &data, duration_ms(start), None, data.ok),
1054        )?;
1055    } else {
1056        writeln!(stdout, "{}", locale.doctor_ok(ok)).map_err(map_stdout_err)?;
1057        for c in &data.checks {
1058            writeln!(
1059                stdout,
1060                "- {} [{}] {}",
1061                c.name,
1062                if c.ok { "ok" } else { "fail" },
1063                c.detail
1064            )
1065            .map_err(map_stdout_err)?;
1066        }
1067    }
1068    Ok(if ok {
1069        ExitCode::SUCCESS
1070    } else {
1071        ExitCode::from(78)
1072    })
1073}
1074
1075/// Check that `path` is an existing writable directory, or can be created under a
1076/// writable ancestor. Does not leave directories behind when only probing parents.
1077fn dir_ready_check(path: &Path) -> (bool, String) {
1078    if path.is_dir() {
1079        let probe = path.join(".docsrs-cli-doctor-write-probe");
1080        return match std::fs::OpenOptions::new()
1081            .write(true)
1082            .create(true)
1083            .truncate(true)
1084            .open(&probe)
1085        {
1086            Ok(_) => {
1087                let _ = std::fs::remove_file(&probe);
1088                (true, path.display().to_string())
1089            }
1090            Err(e) => (false, format!("{} (not writable: {e})", path.display())),
1091        };
1092    }
1093    if path.exists() {
1094        return (
1095            false,
1096            format!("{} (exists but is not a directory)", path.display()),
1097        );
1098    }
1099    let mut ancestor = path.parent();
1100    while let Some(a) = ancestor {
1101        if a.as_os_str().is_empty() {
1102            break;
1103        }
1104        if a.is_dir() {
1105            let probe = a.join(".docsrs-cli-doctor-write-probe");
1106            return match std::fs::OpenOptions::new()
1107                .write(true)
1108                .create(true)
1109                .truncate(true)
1110                .open(&probe)
1111            {
1112                Ok(_) => {
1113                    let _ = std::fs::remove_file(&probe);
1114                    (
1115                        true,
1116                        format!("{} (creatable under {})", path.display(), a.display()),
1117                    )
1118                }
1119                Err(e) => (
1120                    false,
1121                    format!("{} (ancestor not writable: {e})", path.display()),
1122                ),
1123            };
1124        }
1125        if a.exists() {
1126            return (
1127                false,
1128                format!("{} (ancestor is not a directory)", path.display()),
1129            );
1130        }
1131        ancestor = a.parent();
1132    }
1133    (
1134        false,
1135        format!("{} (missing; no writable ancestor)", path.display()),
1136    )
1137}
1138
1139fn cache_cmd<Out: Write>(
1140    cfg: &Config,
1141    action: &CacheAction,
1142    wants_json: bool,
1143    start: Instant,
1144    stdout: &mut Out,
1145) -> AppResult<ExitCode> {
1146    let root = cfg.cache_dir.clone().ok_or_else(|| {
1147        AppError::new(
1148            ErrorKind::Config,
1149            "cache directory could not be resolved (set --cache-dir or DOCSRS_CLI_CACHE_DIR)",
1150        )
1151    })?;
1152    let cache = DiskCache::new(root, cfg.cache_ttl(), cfg.max_cache_bytes);
1153    match action {
1154        CacheAction::Clear => {
1155            let result = cache.clear()?;
1156            if wants_json {
1157                write_json(
1158                    stdout,
1159                    &success_envelope("cache-clear", &result, duration_ms(start), None),
1160                )?;
1161            } else {
1162                writeln!(
1163                    stdout,
1164                    "cache cleared: {} entries, {} bytes freed ({})",
1165                    result.removed_entries, result.freed_bytes, result.root
1166                )
1167                .map_err(map_stdout_err)?;
1168            }
1169        }
1170        CacheAction::Stats => {
1171            let stats = cache.stats();
1172            if wants_json {
1173                write_json(
1174                    stdout,
1175                    &success_envelope("cache-stats", &stats, duration_ms(start), None),
1176                )?;
1177            } else {
1178                let budget = if stats.max_bytes == 0 {
1179                    "unlimited".to_string()
1180                } else {
1181                    format!("{}B", stats.max_bytes)
1182                };
1183                writeln!(
1184                    stdout,
1185                    "cache root={} layout={} entries={} used={}B max={} ttl={}s parser={}",
1186                    stats.root,
1187                    stats.layout,
1188                    stats.entries,
1189                    stats.total_bytes,
1190                    budget,
1191                    stats.ttl_secs,
1192                    stats.parser_version
1193                )
1194                .map_err(map_stdout_err)?;
1195            }
1196        }
1197    }
1198    Ok(ExitCode::SUCCESS)
1199}
1200
1201/// XDG config lifecycle: path inventory, effective show, init template.
1202fn config_cmd<Out: Write>(
1203    cli: &Cli,
1204    cfg: &Config,
1205    action: &ConfigAction,
1206    wants_json: bool,
1207    start: Instant,
1208    stdout: &mut Out,
1209) -> AppResult<ExitCode> {
1210    match action {
1211        ConfigAction::Path => {
1212            let data = config_path_data(cfg);
1213            if wants_json {
1214                write_json(
1215                    stdout,
1216                    &success_envelope("config-path", &data, duration_ms(start), None),
1217                )?;
1218            } else {
1219                writeln!(
1220                    stdout,
1221                    "config_dir={} source={}",
1222                    data.config_dir.as_deref().unwrap_or("<unresolved>"),
1223                    data.config_source.as_str()
1224                )
1225                .map_err(map_stdout_err)?;
1226                writeln!(
1227                    stdout,
1228                    "config_file={} exists={} loaded={}",
1229                    data.config_file.as_deref().unwrap_or("<unresolved>"),
1230                    data.config_file_exists,
1231                    data.config_toml_loaded
1232                )
1233                .map_err(map_stdout_err)?;
1234                writeln!(
1235                    stdout,
1236                    "cache_dir={} source={}",
1237                    data.cache_dir.as_deref().unwrap_or("<unresolved>"),
1238                    data.cache_source.as_str()
1239                )
1240                .map_err(map_stdout_err)?;
1241                writeln!(
1242                    stdout,
1243                    "dotenv_runtime={} secrets={}",
1244                    data.dotenv_runtime, data.secrets_layers
1245                )
1246                .map_err(map_stdout_err)?;
1247            }
1248        }
1249        ConfigAction::Show => {
1250            if wants_json {
1251                write_json(
1252                    stdout,
1253                    &success_envelope("config-show", cfg, duration_ms(start), None),
1254                )?;
1255            } else {
1256                let pretty = serde_json::to_string_pretty(cfg).map_err(|e| {
1257                    AppError::with_source(ErrorKind::Internal, "failed to serialize config", e)
1258                })?;
1259                writeln!(stdout, "{pretty}").map_err(map_stdout_err)?;
1260            }
1261        }
1262        ConfigAction::Init { force } => {
1263            let result = init_config_toml(cli.config_dir.clone(), *force)?;
1264            if wants_json {
1265                write_json(
1266                    stdout,
1267                    &success_envelope("config-init", &result, duration_ms(start), None),
1268                )?;
1269            } else {
1270                let verb = if result.overwritten {
1271                    "overwrote"
1272                } else {
1273                    "created"
1274                };
1275                writeln!(
1276                    stdout,
1277                    "config init: {verb} {} (source={})",
1278                    result.path,
1279                    result.source.as_str()
1280                )
1281                .map_err(map_stdout_err)?;
1282            }
1283        }
1284    }
1285    Ok(ExitCode::SUCCESS)
1286}
1287
1288/// Emit the full command tree for agent discovery (`commands` subcommand).
1289fn commands_cmd<Out: Write>(
1290    wants_json: bool,
1291    start: Instant,
1292    stdout: &mut Out,
1293) -> AppResult<ExitCode> {
1294    let data = command_tree_data();
1295    if wants_json {
1296        write_json(
1297            stdout,
1298            &success_envelope("commands", &data, duration_ms(start), None),
1299        )?;
1300    } else {
1301        writeln!(stdout, "{} {} — command tree", data.name, data.version)
1302            .map_err(map_stdout_err)?;
1303        for c in data.commands {
1304            writeln!(stdout, "- {}: {}", c.name, c.about).map_err(map_stdout_err)?;
1305            for s in c.subcommands {
1306                writeln!(stdout, "  - {} {}: {}", c.name, s.name, s.about)
1307                    .map_err(map_stdout_err)?;
1308            }
1309        }
1310    }
1311    Ok(ExitCode::SUCCESS)
1312}
1313
1314/// Typed `version` success data (matches `docs/schemas/version.schema.json`).
1315#[derive(Debug, Serialize)]
1316struct VersionData {
1317    name: &'static str,
1318    version: &'static str,
1319    msrv: &'static str,
1320    os: &'static str,
1321    arch: &'static str,
1322}
1323
1324/// One doctor health check row.
1325#[derive(Debug, Serialize)]
1326struct DoctorCheck {
1327    name: &'static str,
1328    ok: bool,
1329    detail: String,
1330}
1331
1332/// Typed `doctor` success data (matches `docs/schemas/doctor.schema.json`).
1333#[derive(Debug, Serialize)]
1334struct DoctorData {
1335    ok: bool,
1336    checks: Vec<DoctorCheck>,
1337}
1338
1339/// Agent notes embedded in the `commands` tree.
1340#[derive(Debug, Serialize)]
1341struct AgentNotes {
1342    stdout: &'static str,
1343    stderr: &'static str,
1344    json_auto: &'static str,
1345    lifecycle: &'static str,
1346}
1347
1348/// One nested subcommand entry under `cache`.
1349#[derive(Debug, Serialize)]
1350struct SubCommandNode {
1351    name: &'static str,
1352    about: &'static str,
1353}
1354
1355/// One top-level command entry in the discovery tree.
1356#[derive(Debug, Serialize)]
1357struct CommandNode {
1358    name: &'static str,
1359    about: &'static str,
1360    args: &'static [&'static str],
1361    subcommands: &'static [SubCommandNode],
1362}
1363
1364/// Stable, ordered command tree for agents (no HashMap iteration).
1365#[derive(Debug, Serialize)]
1366struct CommandTree {
1367    name: &'static str,
1368    version: &'static str,
1369    msrv: &'static str,
1370    schema_version: u32,
1371    agent_notes: AgentNotes,
1372    commands: &'static [CommandNode],
1373}
1374
1375/// Schema command payload (`schema` stays `Value` — embedded JSON Schema document).
1376#[derive(Debug, Serialize)]
1377struct SchemaData<'a> {
1378    command: &'a str,
1379    schema: serde_json::Value,
1380    schema_version: u32,
1381}
1382
1383/// Completions command payload.
1384#[derive(Debug, Serialize)]
1385struct CompletionsData {
1386    shell: &'static str,
1387    script: String,
1388}
1389
1390/// Stable, ordered command tree for agents (no HashMap iteration).
1391fn command_tree_data() -> CommandTree {
1392    CommandTree {
1393        name: APP_NAME,
1394        version: APP_VERSION,
1395        msrv: MSRV,
1396        schema_version: SCHEMA_VERSION,
1397        agent_notes: AgentNotes {
1398            stdout: "data only (JSON envelope or markdown)",
1399            stderr: "diagnostics only",
1400            json_auto: "JSON is selected automatically when stdout is not a TTY unless --format markdown|text",
1401            lifecycle: "BORN → EXECUTE → FINALIZE → DIE (one-shot, no daemon)",
1402        },
1403        commands: &[
1404            CommandNode {
1405                name: "search-crates",
1406                about: "Search crates on crates.io",
1407                args: &["query", "--per-page", "--sort", "--page", "--page-token"],
1408                subcommands: &[],
1409            },
1410            CommandNode {
1411                name: "readme",
1412                about: "Fetch crate overview docblock from docs.rs (not git README)",
1413                args: &["crate_name", "--crate-version"],
1414                subcommands: &[],
1415            },
1416            CommandNode {
1417                name: "get-item",
1418                about: "Fetch documentation for a typed item",
1419                args: &[
1420                    "crate_name",
1421                    "item_type",
1422                    "item_path",
1423                    "--crate-version",
1424                    "--suggest",
1425                ],
1426                subcommands: &[],
1427            },
1428            CommandNode {
1429                name: "search-in-crate",
1430                about: "Search symbols in crate all.html index",
1431                args: &[
1432                    "crate_name",
1433                    "query",
1434                    "--crate-version",
1435                    "--item-type",
1436                    "--limit",
1437                    "--match",
1438                ],
1439                subcommands: &[],
1440            },
1441            CommandNode {
1442                name: "version",
1443                about: "Print binary version",
1444                args: &[],
1445                subcommands: &[],
1446            },
1447            CommandNode {
1448                name: "doctor",
1449                about: "Validate local TLS/config readiness",
1450                args: &["--online"],
1451                subcommands: &[],
1452            },
1453            CommandNode {
1454                name: "commands",
1455                about: "List the full command tree for agent discovery",
1456                args: &[],
1457                subcommands: &[],
1458            },
1459            CommandNode {
1460                name: "schema",
1461                about: "Emit JSON Schema for a command",
1462                args: &["--cmd"],
1463                subcommands: &[],
1464            },
1465            CommandNode {
1466                name: "completions",
1467                about: "Generate shell completions",
1468                args: &["shell"],
1469                subcommands: &[],
1470            },
1471            CommandNode {
1472                name: "cache",
1473                about: "Inspect or clear the XDG HTTP disk cache",
1474                args: &[],
1475                subcommands: &[
1476                    SubCommandNode {
1477                        name: "clear",
1478                        about: "Delete all cached HTTP bodies under the cache dir",
1479                    },
1480                    SubCommandNode {
1481                        name: "stats",
1482                        about: "Report entry count, total bytes, and budget",
1483                    },
1484                ],
1485            },
1486            CommandNode {
1487                name: "config",
1488                about: "Manage XDG config paths and optional config.toml (no secrets / no .env)",
1489                args: &[],
1490                subcommands: &[
1491                    SubCommandNode {
1492                        name: "path",
1493                        about: "Print resolved config/cache directories and which layer won",
1494                    },
1495                    SubCommandNode {
1496                        name: "show",
1497                        about: "Print effective runtime configuration",
1498                    },
1499                    SubCommandNode {
1500                        name: "init",
1501                        about: "Create default config.toml under the resolved config directory",
1502                    },
1503                ],
1504            },
1505        ],
1506    }
1507}
1508
1509fn schema_cmd<Out: Write>(
1510    cmd: &str,
1511    wants_json: bool,
1512    format: Option<crate::cli::OutputFormat>,
1513    start: Instant,
1514    stdout: &mut Out,
1515) -> AppResult<ExitCode> {
1516    let schema = match cmd {
1517        "search-crates" => include_str!("../docs/schemas/search-crates.schema.json"),
1518        "readme" => include_str!("../docs/schemas/readme.schema.json"),
1519        "get-item" => include_str!("../docs/schemas/get-item.schema.json"),
1520        "search-in-crate" => include_str!("../docs/schemas/search-in-crate.schema.json"),
1521        "version" => include_str!("../docs/schemas/version.schema.json"),
1522        "doctor" => include_str!("../docs/schemas/doctor.schema.json"),
1523        "commands" => include_str!("../docs/schemas/commands.schema.json"),
1524        "schema" => include_str!("../docs/schemas/schema.schema.json"),
1525        "completions" => include_str!("../docs/schemas/completions.schema.json"),
1526        "error" => include_str!("../docs/schemas/error.schema.json"),
1527        "dry-run" => include_str!("../docs/schemas/dry-run.schema.json"),
1528        "cache" | "cache-clear" | "cache-stats" => {
1529            include_str!("../docs/schemas/cache.schema.json")
1530        }
1531        "config" | "config-path" | "config-show" | "config-init" => {
1532            include_str!("../docs/schemas/config.schema.json")
1533        }
1534        other => {
1535            return Err(AppError::new(
1536                ErrorKind::Usage,
1537                format!("unknown schema command '{other}'"),
1538            ));
1539        }
1540    };
1541    let schema_val: serde_json::Value = serde_json::from_str(schema).map_err(|e| {
1542        AppError::with_source(ErrorKind::Internal, "embedded schema is invalid JSON", e)
1543    })?;
1544    // Branch first so JSON path can move `schema_val` into the envelope (no clone).
1545    if wants_json {
1546        let data = SchemaData {
1547            command: cmd,
1548            schema: schema_val,
1549            schema_version: SCHEMA_VERSION,
1550        };
1551        write_json(
1552            stdout,
1553            &success_envelope("schema", &data, duration_ms(start), None),
1554        )?;
1555    } else if matches!(format, Some(crate::cli::OutputFormat::Markdown)) {
1556        let md = render::render_schema_markdown(cmd, &schema_val);
1557        write!(stdout, "{md}").map_err(map_stdout_err)?;
1558    } else {
1559        writeln!(
1560            stdout,
1561            "{}",
1562            serde_json::to_string_pretty(&schema_val).unwrap_or_default()
1563        )
1564        .map_err(map_stdout_err)?;
1565    }
1566    Ok(ExitCode::SUCCESS)
1567}
1568
1569fn completions_cmd<Out: Write>(
1570    shell: crate::cli::Shell,
1571    wants_json: bool,
1572    start: Instant,
1573    stdout: &mut Out,
1574) -> AppResult<ExitCode> {
1575    let mut buf = Vec::new();
1576    let mut cmd = Cli::command();
1577    clap_complete::generate(shell.to_clap_shell(), &mut cmd, APP_NAME, &mut buf);
1578    let script = String::from_utf8_lossy(&buf).into_owned();
1579    if wants_json {
1580        let data = CompletionsData {
1581            shell: shell.as_str(),
1582            script,
1583        };
1584        write_json(
1585            stdout,
1586            &success_envelope("completions", &data, duration_ms(start), None),
1587        )?;
1588    } else {
1589        write!(stdout, "{script}").map_err(map_stdout_err)?;
1590        let _ = stdout.flush();
1591    }
1592    Ok(ExitCode::SUCCESS)
1593}
1594
1595/// Typed dry-run params for `search-crates` (keys match crates.io query string).
1596#[derive(Debug, Serialize)]
1597struct SearchCratesDryParams<'a> {
1598    q: &'a str,
1599    per_page: u32,
1600    sort: &'a str,
1601    page: u32,
1602    #[serde(skip_serializing_if = "Option::is_none")]
1603    page_token: Option<&'a str>,
1604}
1605
1606/// Typed dry-run params for `readme`.
1607#[derive(Debug, Serialize)]
1608struct ReadmeDryParams<'a> {
1609    crate_name: &'a str,
1610    version: &'a str,
1611}
1612
1613/// Typed dry-run params for `get-item`.
1614#[derive(Debug, Serialize)]
1615struct GetItemDryParams<'a> {
1616    crate_name: &'a str,
1617    item_type: &'a str,
1618    item_path: &'a str,
1619    version: &'a str,
1620}
1621
1622/// Typed dry-run params for `search-in-crate`.
1623#[derive(Debug, Serialize)]
1624struct SearchInCrateDryParams<'a> {
1625    crate_name: &'a str,
1626    query: &'a str,
1627    version: &'a str,
1628    #[serde(skip_serializing_if = "Option::is_none")]
1629    item_type: Option<&'a str>,
1630    #[serde(skip_serializing_if = "Option::is_none")]
1631    match_mode: Option<&'a str>,
1632    limit: u32,
1633}
1634
1635fn emit_dry_run<Out: Write, P: Serialize>(
1636    command: &str,
1637    planned_url: &str,
1638    planned_params: P,
1639    wants_json: bool,
1640    start: Instant,
1641    stdout: &mut Out,
1642) -> AppResult<ExitCode> {
1643    if wants_json {
1644        write_json(
1645            stdout,
1646            &dry_run_envelope(command, planned_url, &planned_params, duration_ms(start)),
1647        )?;
1648    } else {
1649        writeln!(stdout, "dry-run {command}").map_err(map_stdout_err)?;
1650        writeln!(stdout, "planned_url: {planned_url}").map_err(map_stdout_err)?;
1651        writeln!(
1652            stdout,
1653            "planned_params: {}",
1654            serde_json::to_string_pretty(&planned_params).unwrap_or_default()
1655        )
1656        .map_err(map_stdout_err)?;
1657    }
1658    Ok(ExitCode::SUCCESS)
1659}
1660
1661fn map_stdout_err(e: io::Error) -> AppError {
1662    if e.kind() == io::ErrorKind::BrokenPipe {
1663        AppError::broken_pipe()
1664    } else {
1665        AppError::with_source(ErrorKind::Internal, "stdout write", e)
1666    }
1667}
1668
1669/// Serialize one RFC 8259 JSON object (compact, single line) + trailing `\n`.
1670///
1671/// Product stdout is a single JSON document per invocation (not NDJSON streams).
1672/// Optional fields are omitted when `None` (`skip_serializing_if`), never `NaN`/`Infinity`.
1673///
1674/// Serialize to an intermediate buffer first so broken-pipe on write is mapped to
1675/// exit 141 without conflating pure serde failures with I/O.
1676fn write_json<Out: Write, T: Serialize>(stdout: &mut Out, v: &T) -> AppResult<()> {
1677    let mut buf = Vec::with_capacity(256);
1678    serde_json::to_writer(&mut buf, v)
1679        .map_err(|e| AppError::with_source(ErrorKind::Internal, "json serialize failed", e))?;
1680    buf.push(b'\n');
1681    stdout.write_all(&buf).map_err(map_stdout_err)?;
1682    let _ = stdout.flush();
1683    Ok(())
1684}
1685
1686fn emit_error<Out: Write, ErrW: Write>(
1687    cli: &Cli,
1688    err: &AppError,
1689    locale: Locale,
1690    stdout: &mut Out,
1691    stderr: &mut ErrW,
1692    stdout_is_terminal: bool,
1693) -> ExitCode {
1694    if cli.wants_json(stdout_is_terminal) {
1695        // Best-effort: preserve the original error exit code even if stdout is gone.
1696        let _ = write_json(stdout, &error_envelope(err));
1697    } else {
1698        // Human path: error on stderr; stdout stays empty.
1699        // Force with --format text|markdown even when stdout is a pipe.
1700        let _ = writeln!(stderr, "{}", locale.format_error(err.message()));
1701        let _ = stderr.flush();
1702    }
1703    flush_stdio();
1704    err.exit_code()
1705}