Skip to main content

doiget_cli/commands/
capabilities.rs

1//! `doiget capabilities` — single-shot inventory JSON for LLM cold-boot
2//! (#214).
3//!
4//! Emits a single JSON value describing the **full surface** of this
5//! `doiget` binary: subcommands (walked from the live `clap::Command`
6//! tree so the inventory cannot drift from the parser), positional args
7//! and named flags per subcommand, global flags, the four
8//! [`super::output::OutputMode`] values, hand-maintained env-var + example tables, the
9//! `doiget_*` MCP tool list, compile-time features, and a `docs` map
10//! pointing at the canonical spec files.
11//!
12//! Design rationale: the existing `--help` output lists subcommand
13//! names but the rest of doiget's surface (env vars, MCP tools, JSON
14//! schemas, ADR refs) is scattered across `docs/`. An LLM cold-booted
15//! into doiget — no repo access, no follow-up doc reads — cannot
16//! discover those via `--help` alone. This subcommand closes that gap
17//! with one round-trip.
18//!
19//! # Output mode
20//!
21//! `doiget capabilities` is a **product-output** command per the
22//! ADR-0017 convention (`--mode` is informational; the JSON inventory
23//! is the artefact). `--mode quiet` is the one mode that suppresses
24//! stdout (#203 / CONFIG.md §5); every other mode emits the same JSON.
25//!
26//! # Wire-format stability (whole module)
27//!
28//! Every `pub` struct / enum below carries `#[non_exhaustive]`. Adding
29//! a field is non-breaking; renaming or removing one is a
30//! compile-time break for downstream Rust consumers and a
31//! `[BREAKING]`-class change for JSON consumers (CHANGELOG must call
32//! it out). The per-item `#[non_exhaustive]` attributes intentionally
33//! carry no inline comment; this module-doc says it once.
34
35use anyhow::{Context, Result};
36use serde::Serialize;
37
38/// Top-level capability inventory. Serialised to stdout as one JSON
39/// value. Field names are part of the public wire format: renaming
40/// any field is a semver minor with a CHANGELOG `\[BREAKING\]` callout
41/// (same discipline as `EntryInfo` / `MigrationReport` in #213).
42#[allow(missing_docs)] // Field names ARE the schema; documented externally in #214.
43#[non_exhaustive]
44#[derive(Debug, Serialize)]
45pub struct Capabilities {
46    /// `CARGO_PKG_VERSION` for this build.
47    pub version: &'static str,
48    /// Cargo features compiled into this binary. Contains `"oa-only"`
49    /// in stock release builds (the default feature). Empty only when
50    /// the crate was built with `--no-default-features` and **no
51    /// other features enabled**; a build like
52    /// `cargo build --no-default-features --features citation`
53    /// yields `["citation"]`, not `[]`.
54    pub features: Vec<&'static str>,
55    /// All four [`super::output::OutputMode`] values; the parser accepts these for
56    /// `--mode`. Mirrors `CONFIG.md` §5 (CLI flags).
57    pub modes: &'static [&'static str],
58    /// Global flags that apply to every subcommand.
59    pub global_flags: Vec<FlagSpec>,
60    /// One entry per CLI subcommand (clap-walked).
61    pub subcommands: Vec<SubcommandSpec>,
62    /// `DOIGET_*` env vars from CONFIG.md §4.
63    pub env_vars: &'static [EnvVar],
64    /// MCP tools exposed by `doiget serve` (hand-coded; the source of
65    /// truth is `docs/MCP_TOOLS.md` §1).
66    pub mcp_tools: &'static [McpTool],
67    /// Canonical doc paths an LLM can pull for deeper context.
68    pub docs: Docs,
69    /// Number of user-extension allowlist hosts loaded from
70    /// `<config_dir>/doiget/config.toml` per ADR-0028 D2. `0` if the
71    /// config file is missing, contains no `[[network.additional_hosts]]`,
72    /// or fails to parse — run `doiget config doctor` to diagnose parse
73    /// failures. Exposed so an LLM can confirm at cold-boot whether the
74    /// curated allowlist has been extended on this host.
75    pub user_extension_count: usize,
76}
77
78/// What kind of value (if any) a [`FlagSpec`] carries.
79///
80/// Typed (not `&'static str`) so a typo can't slip into the wire
81/// format and the `Enum`-implies-`values`-present invariant is
82/// expressible at the type layer (see #215 for the design pass). Serialises
83/// as the lowercased variant name: `"bool"`, `"enum"`, `"string"`.
84#[non_exhaustive]
85#[derive(Debug, Serialize)]
86#[serde(rename_all = "lowercase")]
87pub enum FlagKind {
88    /// Boolean switch (no value).
89    Bool,
90    /// Value-bounded flag — `values` carries the accepted set.
91    Enum,
92    /// Any non-`Bool`, non-`Enum` flag. Today every such flag emits
93    /// `"string"`; richer typing (`Path` / `Int` etc.) is intentionally
94    /// out of scope until a real consumer needs it — `#[non_exhaustive]`
95    /// reserves space without commitment.
96    String,
97}
98
99#[allow(missing_docs)] // Field names ARE the schema; documented externally in #214.
100#[non_exhaustive]
101#[derive(Debug, Serialize)]
102pub struct FlagSpec {
103    /// e.g. `--mode`, `--json`, `-q`.
104    pub name: String,
105    /// Boolean / enum / free-string discriminator. See [`FlagKind`].
106    pub kind: FlagKind,
107    /// `clap` `help` text.
108    pub help: Option<String>,
109    /// For `kind == FlagKind::Enum`: the accepted values, harvested
110    /// from clap's `PossibleValuesParser`. Owned (not `&'static`) so
111    /// the helper works for any future enum flag, not just `--mode`
112    /// (see #215).
113    #[serde(skip_serializing_if = "Option::is_none")]
114    pub values: Option<Vec<String>>,
115}
116
117#[allow(missing_docs)] // Field names ARE the schema; documented externally in #214.
118#[non_exhaustive]
119#[derive(Debug, Serialize)]
120pub struct SubcommandSpec {
121    pub name: String,
122    pub summary: Option<String>,
123    pub args: Vec<ArgSpec>,
124    pub flags: Vec<FlagSpec>,
125    /// Hand-maintained canonical invocations.
126    pub examples: &'static [&'static str],
127    /// How this command interacts with `--mode json`. See [`JsonMode`].
128    pub json_mode: JsonMode,
129    /// Cargo feature this subcommand is gated behind, if any.
130    #[serde(skip_serializing_if = "Option::is_none")]
131    pub feature_gated: Option<&'static str>,
132}
133
134/// What kind of positional argument an [`ArgSpec`] describes.
135///
136/// Currently every entry is `Positional`; the typed enum reserves
137/// space for future variants (e.g. `Stdin` markers) without breaking
138/// existing JSON consumers. Serialises as `"positional"`.
139#[non_exhaustive]
140#[derive(Debug, Serialize)]
141#[serde(rename_all = "lowercase")]
142pub enum ArgKind {
143    /// A required-or-optional positional argument on the subcommand.
144    Positional,
145}
146
147#[allow(missing_docs)] // Field names ARE the schema; documented externally in #214.
148#[non_exhaustive]
149#[derive(Debug, Serialize)]
150pub struct ArgSpec {
151    pub name: String,
152    /// Always [`ArgKind::Positional`] today. Kept as a discriminator
153    /// so the JSON shape can grow new arg kinds later without
154    /// renaming fields (see #215 for the design pass).
155    pub kind: ArgKind,
156    pub help: Option<String>,
157    /// `true` when the arg has no default and no `Option<T>` wrapper.
158    pub required: bool,
159}
160
161/// How a subcommand interacts with `--mode json`.
162///
163/// Wire shape: every variant serialises to an object with a `status`
164/// discriminant, so a consumer sees uniform `{"status":"…", …}`
165/// records (`#[serde(tag = "status")]`). Before #215 the previous
166/// mixed string/object representation forced consumers to handle two
167/// JSON shapes for sibling variants.
168///
169/// **Tuple variants not permitted.** `#[serde(tag = "status")]`
170/// requires the tag to live in the same flat object as variant
171/// fields; tuple variants are incompatible with internally-tagged
172/// representation. Future variants MUST use named fields.
173#[non_exhaustive] // Adding a future variant is non-breaking for JSON consumers.
174#[derive(Debug, Serialize)]
175#[serde(tag = "status", rename_all = "lowercase")]
176pub enum JsonMode {
177    /// The command's primary output IS the requested artifact, not
178    /// informational chatter. `--mode` is informational here; the
179    /// exact stdout shape (e.g. JSON for `csl` / `graph` /
180    /// `capabilities` and the JSON-RPC stream from `serve`; BibTeX
181    /// for `bib`; PDF-on-disk + stderr summary for `fetch`; a
182    /// `--dry-run` JSON plan in the dry-run variants) is fixed by
183    /// the subcommand and may vary across flags. **Consult
184    /// `examples` for the per-flag stdout form** rather than
185    /// assuming JSON.
186    Artifact,
187    /// Under `--mode json` the command emits a structured JSON body
188    /// on stdout; otherwise the human form (e.g. `info`,
189    /// `list-recent`, `audit-log`, `provenance migrate`, `batch`).
190    Supported,
191    // NOTE: a `Deferred { tracking: &'static str }` variant was
192    // sketched during #214's design phase but never instantiated by
193    // any subcommand. Removed in the #215 self-review pass to avoid
194    // shipping an unused wire shape; `#[non_exhaustive]` keeps the
195    // door open to add it back non-breakingly when a real consumer
196    // emerges.
197}
198
199#[allow(missing_docs)] // Field names ARE the schema; documented externally in #214.
200#[non_exhaustive]
201#[derive(Debug, Serialize)]
202pub struct EnvVar {
203    pub name: &'static str,
204    /// `(none)` when no built-in default.
205    pub default: &'static str,
206    pub help: &'static str,
207}
208
209#[allow(missing_docs)] // Field names ARE the schema; documented externally in #214.
210#[non_exhaustive]
211#[derive(Debug, Serialize)]
212pub struct McpTool {
213    pub name: &'static str,
214    /// Anchor-style reference into `docs/MCP_TOOLS.md`.
215    pub schema_ref: &'static str,
216}
217
218#[allow(missing_docs)] // Field names ARE the schema; documented externally in #214.
219#[non_exhaustive]
220#[derive(Debug, Serialize)]
221pub struct Docs {
222    pub config: &'static str,
223    pub errors: &'static str,
224    pub scope: &'static str,
225    pub mcp: &'static str,
226    pub sources: &'static str,
227    pub redirect_allowlist: &'static str,
228    pub provenance_log: &'static str,
229}
230
231// ---------------------------------------------------------------------------
232// Static tables
233// ---------------------------------------------------------------------------
234
235const MODES: &[&str] = &["human", "json", "quiet", "mcp"];
236
237const ENV_VARS: &[EnvVar] = &[
238    EnvVar {
239        name: "DOIGET_STORE_ROOT",
240        default: "$HOME/papers",
241        help: "Root of the on-disk paper store. CONFIG.md §4.",
242    },
243    EnvVar {
244        name: "DOIGET_CACHE_ROOT",
245        default: "$HOME/.cache/doiget",
246        help: "Root of the on-disk HTTP / metadata cache. CONFIG.md §4.",
247    },
248    EnvVar {
249        name: "DOIGET_LOG_PATH",
250        default: "<config_dir>/doiget/access.jsonl",
251        help: "JSON-Lines provenance log file path (PROVENANCE_LOG.md §3).",
252    },
253    EnvVar {
254        name: "DOIGET_LOG_RETENTION_DAYS",
255        default: "90",
256        help: "Rotated-segment retention window (0 disables pruning). #140 / PROVENANCE_LOG.md §6.",
257    },
258    EnvVar {
259        name: "DOIGET_MODE",
260        default: "(none)",
261        help: "Output mode (`human`/`json`/`quiet`/`mcp`). ADR-0017 ladder rung 3.",
262    },
263    EnvVar {
264        name: "DOIGET_CONTACT_EMAIL",
265        default: "(none)",
266        help: "Contact email for polite User-Agent header (CONFIG.md §4).",
267    },
268    EnvVar {
269        name: "DOIGET_UNPAYWALL_EMAIL",
270        default: "(falls back to DOIGET_CONTACT_EMAIL)",
271        help: "Unpaywall-specific contact email.",
272    },
273    EnvVar {
274        name: "DOIGET_USER_AGENT",
275        default: "(default polite UA)",
276        help: "Override the User-Agent header for all outbound requests.",
277    },
278    EnvVar {
279        name: "DOIGET_ENABLE_OPENALEX",
280        default: "(off)",
281        help: "Enable the OpenAlex citation graph source (graph subcommand prerequisite).",
282    },
283    EnvVar {
284        name: "DOIGET_ARXIV_BASE",
285        default: "https://export.arxiv.org/",
286        help: "arXiv API base URL — primarily for testing/wiremock override.",
287    },
288    EnvVar {
289        name: "DOIGET_CROSSREF_BASE",
290        default: "https://api.crossref.org/",
291        help: "Crossref API base URL.",
292    },
293    EnvVar {
294        name: "DOIGET_UNPAYWALL_BASE",
295        default: "https://api.unpaywall.org/",
296        help: "Unpaywall API base URL.",
297    },
298];
299
300const MCP_TOOLS: &[McpTool] = &[
301    McpTool {
302        name: "doiget_resolve_paper",
303        schema_ref: "docs/MCP_TOOLS.md#1-tool-list",
304    },
305    McpTool {
306        name: "doiget_fetch_paper",
307        schema_ref: "docs/MCP_TOOLS.md#1-tool-list",
308    },
309    McpTool {
310        name: "doiget_metadata_only",
311        schema_ref: "docs/MCP_TOOLS.md#11-doiget_metadata_only-normative",
312    },
313    McpTool {
314        name: "doiget_batch_fetch",
315        schema_ref: "docs/MCP_TOOLS.md#1-tool-list",
316    },
317    McpTool {
318        name: "doiget_info",
319        schema_ref: "docs/MCP_TOOLS.md#1-tool-list",
320    },
321    McpTool {
322        name: "doiget_search_local",
323        schema_ref: "docs/MCP_TOOLS.md#1-tool-list",
324    },
325    McpTool {
326        name: "doiget_list_recent",
327        schema_ref: "docs/MCP_TOOLS.md#1-tool-list",
328    },
329    McpTool {
330        name: "doiget_paper_pdf_path",
331        schema_ref: "docs/MCP_TOOLS.md#1-tool-list",
332    },
333    McpTool {
334        name: "doiget_capability_profile",
335        schema_ref: "docs/MCP_TOOLS.md#1-tool-list",
336    },
337    McpTool {
338        name: "doiget_health",
339        schema_ref: "docs/MCP_TOOLS.md#1-tool-list",
340    },
341    McpTool {
342        name: "doiget_expand_citation_graph",
343        schema_ref: "docs/MCP_TOOLS.md#1-tool-list",
344    },
345    McpTool {
346        name: "doiget_bibtex_export",
347        schema_ref: "docs/MCP_TOOLS.md#1-tool-list",
348    },
349    McpTool {
350        name: "doiget_csl_export",
351        schema_ref: "docs/MCP_TOOLS.md#1-tool-list",
352    },
353    McpTool {
354        // ADR-0030 D6: parse a CSL-JSON / (future) BibTeX file and
355        // fetch each resolvable entry; each result row carries the
356        // source bibliography's `entry_key` so a Zotero / Mendeley
357        // plugin can bridge the fetched PDF back to the originating
358        // reference.
359        name: "doiget_batch_from_bibliography",
360        schema_ref: "docs/MCP_TOOLS.md#1-tool-list",
361    },
362];
363
364const DOCS: Docs = Docs {
365    config: "docs/CONFIG.md",
366    errors: "docs/ERRORS.md",
367    scope: "docs/SCOPE.md",
368    mcp: "docs/MCP_TOOLS.md",
369    sources: "docs/SOURCES.md",
370    redirect_allowlist: "docs/REDIRECT_ALLOWLIST.md",
371    provenance_log: "docs/PROVENANCE_LOG.md",
372};
373
374/// Per-subcommand hand-maintained metadata. The clap walk provides
375/// name + summary + args + flags; this table adds examples,
376/// `json_mode` semantics, and feature-gating that clap doesn't
377/// expose. A regression unit test asserts every clap-visible
378/// subcommand has an entry here (otherwise the test fails loudly).
379///
380/// **Maintenance:** `feature_gated` MUST be kept in sync with the
381/// corresponding `#[cfg(feature = …)]` annotation in `main.rs`. There
382/// is no compile-time check; the `every_test_cli_subcommand_has_metadata`
383/// regression test does not cover feature-gating directly — it only
384/// asserts metadata exists. Add a CI matrix entry (`--features
385/// citation`) when introducing new gated subcommands so the e2e
386/// assertion list catches drift (see #215). Alternatively, add a
387/// unit test that asserts `metadata_for("graph").unwrap().feature_gated
388/// == Some("citation")` to lock the gate at the lib-test layer.
389struct SubcommandMeta {
390    examples: &'static [&'static str],
391    json_mode: JsonMode,
392    feature_gated: Option<&'static str>,
393}
394
395fn metadata_for(subcommand: &str) -> Option<SubcommandMeta> {
396    let m = match subcommand {
397        "fetch" => SubcommandMeta {
398            examples: &[
399                "doiget fetch 10.1234/foo",
400                "doiget fetch arxiv:2401.12345",
401                "doiget fetch 10.1234/foo --dry-run",
402            ],
403            // The success summary is on stderr (ADR-0001); the
404            // dry-run plan is JSON product output (ADR-0022).
405            json_mode: JsonMode::Artifact,
406            feature_gated: None,
407        },
408        "batch" => SubcommandMeta {
409            examples: &[
410                "doiget batch refs.txt",
411                "doiget batch refs.txt --dry-run",
412                "doiget batch refs.txt --json",
413            ],
414            // `--json` emits the ERRORS.md §3 JSONL per-ref shape (#205).
415            json_mode: JsonMode::Supported,
416            feature_gated: None,
417        },
418        "info" => SubcommandMeta {
419            examples: &[
420                "doiget info 10.1234/foo",
421                "doiget info arxiv:2401.12345 --json",
422            ],
423            json_mode: JsonMode::Supported,
424            feature_gated: None,
425        },
426        "list-recent" => SubcommandMeta {
427            examples: &[
428                "doiget list-recent",
429                "doiget list-recent 20",
430                "doiget list-recent --json",
431            ],
432            json_mode: JsonMode::Supported,
433            feature_gated: None,
434        },
435        "search" => SubcommandMeta {
436            examples: &[
437                "doiget search 'quantum entanglement'",
438                "doiget search renormalization --json",
439            ],
440            json_mode: JsonMode::Supported,
441            feature_gated: None,
442        },
443        "bib" => SubcommandMeta {
444            examples: &["doiget bib 10.1234/foo", "doiget bib arxiv:2401.12345"],
445            // BibTeX output is the product; `--mode` is informational.
446            json_mode: JsonMode::Artifact,
447            feature_gated: None,
448        },
449        "csl" => SubcommandMeta {
450            examples: &["doiget csl 10.1234/foo"],
451            json_mode: JsonMode::Artifact,
452            feature_gated: None,
453        },
454        "audit-log" => SubcommandMeta {
455            examples: &[
456                "doiget audit-log --verify",
457                "doiget audit-log --verify --json",
458                "doiget --quiet audit-log --verify   # exit code only",
459            ],
460            json_mode: JsonMode::Supported,
461            feature_gated: None,
462        },
463        "provenance" => SubcommandMeta {
464            examples: &[
465                "doiget provenance migrate --dry-run",
466                "doiget provenance migrate",
467                "doiget provenance migrate --dry-run --json",
468            ],
469            json_mode: JsonMode::Supported,
470            feature_gated: None,
471        },
472        "config" => SubcommandMeta {
473            examples: &[
474                "doiget config show",
475                "doiget config show --json",
476                "doiget config path",
477                "doiget config doctor",
478            ],
479            json_mode: JsonMode::Supported,
480            feature_gated: None,
481        },
482        "serve" => SubcommandMeta {
483            examples: &["doiget serve   # stdio MCP server (ADR-0001)"],
484            // serve always runs in mcp mode; the protocol output is
485            // JSON-RPC, which is product.
486            json_mode: JsonMode::Artifact,
487            feature_gated: None,
488        },
489        "graph" => SubcommandMeta {
490            examples: &[
491                "DOIGET_ENABLE_OPENALEX=1 doiget graph 10.1234/foo",
492                "DOIGET_ENABLE_OPENALEX=1 doiget graph 10.1234/foo --depth 2 --total 50",
493            ],
494            json_mode: JsonMode::Artifact,
495            feature_gated: Some("citation"),
496        },
497        "capabilities" => SubcommandMeta {
498            examples: &["doiget capabilities | jq ."],
499            // The whole point of capabilities IS JSON output.
500            json_mode: JsonMode::Artifact,
501            feature_gated: None,
502        },
503        // clap auto-adds `help`; we silently ignore it (it's not a
504        // domain subcommand).
505        "help" => return None,
506        _ => return None,
507    };
508    Some(m)
509}
510
511// ---------------------------------------------------------------------------
512// Build
513// ---------------------------------------------------------------------------
514
515/// Build the [`Capabilities`] inventory from `cli` (the clap parser
516/// for this binary, supplied by the caller because the `Cli` struct
517/// lives in `main.rs` and is not exposed in the library crate). The
518/// caller is `commands::main::run_dispatch` via `Cli::command()`.
519pub fn build_capabilities(cli: &clap::Command) -> Capabilities {
520    let global_flags = collect_global_flags(cli);
521    let subcommands = cli
522        .get_subcommands()
523        .filter_map(|sub| build_subcommand(sub, cli))
524        .collect::<Vec<_>>();
525    Capabilities {
526        version: env!("CARGO_PKG_VERSION"),
527        features: compile_time_features(),
528        modes: MODES,
529        global_flags,
530        subcommands,
531        env_vars: ENV_VARS,
532        mcp_tools: MCP_TOOLS,
533        docs: DOCS,
534        user_extension_count: user_extension_count(),
535    }
536}
537
538/// Count valid `[[network.additional_hosts]]` entries in
539/// `<config_dir>/doiget/config.toml` (ADR-0028 D2). Returns `0` on any
540/// failure — missing config, parse error, unresolvable config dir.
541/// Diagnose failures via `doiget config doctor`; here we only need a
542/// best-effort cold-boot signal for the inventory.
543fn user_extension_count() -> usize {
544    let cfg_dir = match super::fetch::config_dir_utf8() {
545        Ok(p) => p,
546        Err(_) => return 0,
547    };
548    let path = cfg_dir.join("doiget").join("config.toml");
549    match doiget_core::user_extension::load(&path) {
550        Ok(hosts) => hosts.len(),
551        Err(_) => 0,
552    }
553}
554
555fn compile_time_features() -> Vec<&'static str> {
556    let mut feats: Vec<&'static str> = Vec::new();
557    if cfg!(feature = "oa-only") {
558        feats.push("oa-only");
559    }
560    if cfg!(feature = "metadata") {
561        feats.push("metadata");
562    }
563    if cfg!(feature = "citation") {
564        feats.push("citation");
565    }
566    if cfg!(feature = "tdm-elsevier") {
567        feats.push("tdm-elsevier");
568    }
569    if cfg!(feature = "tdm-aps") {
570        feats.push("tdm-aps");
571    }
572    if cfg!(feature = "tdm-springer") {
573        feats.push("tdm-springer");
574    }
575    feats
576}
577
578fn collect_global_flags(cmd: &clap::Command) -> Vec<FlagSpec> {
579    cmd.get_arguments()
580        .filter(|a| a.is_global_set())
581        .map(arg_to_flag_spec)
582        .collect()
583}
584
585fn build_subcommand(sub: &clap::Command, root: &clap::Command) -> Option<SubcommandSpec> {
586    let name = sub.get_name();
587    let meta = metadata_for(name)?;
588    let (args, flags) = split_args_and_flags(sub, root);
589    Some(SubcommandSpec {
590        name: name.to_string(),
591        summary: sub.get_about().map(|s| s.to_string()),
592        args,
593        flags,
594        examples: meta.examples,
595        json_mode: meta.json_mode,
596        feature_gated: meta.feature_gated,
597    })
598}
599
600fn split_args_and_flags(
601    sub: &clap::Command,
602    root: &clap::Command,
603) -> (Vec<ArgSpec>, Vec<FlagSpec>) {
604    // The root's global args appear in every subcommand's iterator;
605    // suppress them from per-subcommand `flags` (they're already in
606    // `global_flags`).
607    let global_names: std::collections::HashSet<&str> = root
608        .get_arguments()
609        .filter(|a| a.is_global_set())
610        .map(|a| a.get_id().as_str())
611        .collect();
612    let mut args = Vec::new();
613    let mut flags = Vec::new();
614    for a in sub.get_arguments() {
615        if global_names.contains(a.get_id().as_str()) {
616            continue;
617        }
618        // Clap auto-adds `--help` (and `--version` on the root) to
619        // every subcommand. They're not positional and not
620        // `is_global_set()`, so they would otherwise leak into every
621        // subcommand's `flags[]` as `kind: "string"`. Filter on the
622        // action against the known built-in variants.
623        //
624        // **Maintenance:** `clap::ArgAction` is itself
625        // `#[non_exhaustive]` upstream. A future clap release that
626        // adds a new built-in action (e.g. a hypothetical
627        // `HelpMarkdown`) would fall through this `matches!` and
628        // reappear in `flags[]`. Re-audit this filter on every clap
629        // minor-version bump.
630        if matches!(
631            a.get_action(),
632            clap::ArgAction::Help
633                | clap::ArgAction::HelpShort
634                | clap::ArgAction::HelpLong
635                | clap::ArgAction::Version
636        ) {
637            continue;
638        }
639        if a.is_positional() {
640            args.push(ArgSpec {
641                name: a.get_id().to_string(),
642                kind: ArgKind::Positional,
643                help: a.get_help().map(|s| s.to_string()),
644                required: a.is_required_set(),
645            });
646        } else {
647            flags.push(arg_to_flag_spec(a));
648        }
649    }
650    (args, flags)
651}
652
653fn arg_to_flag_spec(a: &clap::Arg) -> FlagSpec {
654    let name = a
655        .get_long()
656        .map(|s| format!("--{s}"))
657        .or_else(|| a.get_short().map(|c| format!("-{c}")))
658        .unwrap_or_else(|| a.get_id().to_string());
659    // Boolean switches → `Bool`; value-enum flags → `Enum` with the
660    // accepted values harvested from clap directly; everything else
661    // → `String`. The `possible_values()` harvest covers any future
662    // enum flag without code change (see #215).
663    let possible: Option<Vec<String>> = a
664        .get_value_parser()
665        .possible_values()
666        .map(|it| it.map(|pv| pv.get_name().to_owned()).collect());
667    let (kind, values) = if matches!(
668        a.get_action(),
669        clap::ArgAction::SetTrue | clap::ArgAction::SetFalse
670    ) {
671        (FlagKind::Bool, None)
672    } else if let Some(vs) = possible {
673        (FlagKind::Enum, Some(vs))
674    } else {
675        (FlagKind::String, None)
676    };
677    FlagSpec {
678        name,
679        kind,
680        help: a.get_help().map(|s| s.to_string()),
681        values,
682    }
683}
684
685// ---------------------------------------------------------------------------
686// Entry point
687// ---------------------------------------------------------------------------
688
689/// Run the `doiget capabilities` subcommand.
690///
691/// `capabilities` is an **artifact** command per ADR-0017 Amendment 1:
692/// its stdout output IS the deliverable (the inventory JSON an LLM
693/// reads on cold-boot). It honors only **explicit** Quiet —
694/// `--quiet` / `-q` / `--mode quiet` / `DOIGET_MODE=quiet` — and emits
695/// the inventory on every other path. The `quiet_was_explicit`
696/// discriminator is what distinguishes the two cases:
697///
698/// | mode               | quiet_was_explicit | behaviour          |
699/// |--------------------|--------------------|--------------------|
700/// | non-`Quiet`        | -                  | emit               |
701/// | `Quiet` (explicit) | `true`             | suppress           |
702/// | `Quiet` (non-TTY)  | `false`            | **emit** (#219)    |
703///
704/// The non-TTY case is the one #219 / #220 report: an LLM tool
705/// executor captures stdout, so `stdout_is_tty()` is `false`, the
706/// resolver falls through to `Quiet`, but the caller wants the JSON
707/// inventory exactly because it's about to be machine-parsed. The
708/// table's bottom row is the fix.
709///
710/// The caller passes the live `clap::Command` so the clap walk
711/// operates on the binary's actual `Cli` tree (which the lib half of
712/// this crate can't reach directly — the `Cli` struct lives in
713/// `main.rs`).
714pub fn run(
715    cli: &clap::Command,
716    mode: super::output::OutputMode,
717    quiet_was_explicit: bool,
718) -> Result<()> {
719    // ADR-0017 Amendment 1: artifact command — suppress ONLY on
720    // explicit Quiet, never on the non-TTY implicit fallback.
721    if mode == super::output::OutputMode::Quiet && quiet_was_explicit {
722        return Ok(());
723    }
724    let caps = build_capabilities(cli);
725    let s = serde_json::to_string_pretty(&caps).context("serialise capabilities inventory")?;
726    // `print_stdout` workspace-deny; localised allow at the
727    // sanctioned product-output sink. See `commands/csl.rs`'s pattern.
728    #[allow(clippy::print_stdout)]
729    {
730        println!("{s}");
731    }
732    Ok(())
733}
734
735// ---------------------------------------------------------------------------
736// Tests
737// ---------------------------------------------------------------------------
738
739#[cfg(test)]
740#[allow(clippy::expect_used, clippy::unwrap_used, clippy::panic)]
741mod tests {
742    use super::*;
743
744    /// Mirrors the `Cli` struct in `main.rs` for lib-test reach.
745    /// `commands::capabilities` is library-level; the binary-only
746    /// `Cli` struct can't be reached from here, so we re-derive a
747    /// shadow whose subcommand list is identical. The
748    /// `cli_shadow_matches_main_cli` integration test in
749    /// `tests/capabilities_e2e.rs` runs the real binary and asserts
750    /// the wire output matches.
751    fn test_cli() -> clap::Command {
752        use clap::{Arg, ArgAction, Command};
753        let mode_values = ["human", "json", "quiet", "mcp"];
754        let cmd = Command::new("doiget")
755            .arg(
756                Arg::new("mode")
757                    .long("mode")
758                    .global(true)
759                    .value_parser(clap::builder::PossibleValuesParser::new(mode_values))
760                    .help("Output mode (human|json|quiet|mcp)."),
761            )
762            .arg(
763                Arg::new("json")
764                    .long("json")
765                    .global(true)
766                    .action(ArgAction::SetTrue)
767                    .help("Short for `--mode json`."),
768            )
769            .arg(
770                Arg::new("quiet")
771                    .long("quiet")
772                    .short('q')
773                    .global(true)
774                    .action(ArgAction::SetTrue)
775                    .help("Short for `--mode quiet`."),
776            )
777            .subcommand(
778                Command::new("fetch")
779                    .about("Fetch a single paper PDF")
780                    .arg(Arg::new("ref").required(true))
781                    .arg(
782                        Arg::new("dry-run")
783                            .long("dry-run")
784                            .action(ArgAction::SetTrue),
785                    ),
786            )
787            .subcommand(
788                Command::new("batch")
789                    .about("Fetch many refs")
790                    .arg(Arg::new("path").required(true))
791                    .arg(
792                        Arg::new("dry-run")
793                            .long("dry-run")
794                            .action(ArgAction::SetTrue),
795                    ),
796            )
797            .subcommand(
798                Command::new("info")
799                    .about("Show metadata")
800                    .arg(Arg::new("ref").required(true)),
801            )
802            .subcommand(Command::new("list-recent").about("List recent"))
803            .subcommand(
804                Command::new("search")
805                    .about("Search local")
806                    .arg(Arg::new("query").required(true)),
807            )
808            .subcommand(
809                Command::new("bib")
810                    .about("BibTeX export")
811                    .arg(Arg::new("ref").required(true)),
812            )
813            .subcommand(
814                Command::new("csl")
815                    .about("CSL export")
816                    .arg(Arg::new("ref").required(true)),
817            )
818            .subcommand(
819                Command::new("audit-log")
820                    .about("Audit log")
821                    .arg(Arg::new("verify").long("verify").action(ArgAction::SetTrue)),
822            )
823            .subcommand(Command::new("provenance").about("Provenance ops"))
824            .subcommand(
825                Command::new("config")
826                    .about("Config")
827                    .arg(Arg::new("action").required(true)),
828            )
829            .subcommand(Command::new("serve").about("MCP server"));
830        // `graph` is `#[cfg(feature = "citation")]` in main.rs; mirror
831        // the gate so the shadow CLI matches the production surface
832        // (see #215).
833        #[cfg(feature = "citation")]
834        let cmd = cmd.subcommand(
835            Command::new("graph")
836                .about("Citation graph")
837                .arg(Arg::new("ref").required(true)),
838        );
839        cmd.subcommand(Command::new("capabilities").about("Capabilities"))
840    }
841
842    fn caps() -> Capabilities {
843        build_capabilities(&test_cli())
844    }
845
846    #[test]
847    fn capabilities_serialises_to_valid_json() {
848        let s = serde_json::to_string_pretty(&caps()).expect("serialise");
849        let v: serde_json::Value = serde_json::from_str(&s).expect("parse round-trip");
850        for key in [
851            "version",
852            "features",
853            "modes",
854            "global_flags",
855            "subcommands",
856            "env_vars",
857            "mcp_tools",
858            "docs",
859            "user_extension_count",
860        ] {
861            assert!(
862                v.get(key).is_some(),
863                "top-level key `{key}` missing from capabilities JSON: {v}"
864            );
865        }
866    }
867
868    #[test]
869    fn modes_field_matches_output_mode_enum() {
870        // Tied to `OutputMode { Human, Json, Quiet, Mcp }`.
871        assert_eq!(caps().modes, &["human", "json", "quiet", "mcp"]);
872    }
873
874    #[test]
875    fn env_vars_all_use_doiget_prefix() {
876        for ev in ENV_VARS {
877            assert!(
878                ev.name.starts_with("DOIGET_"),
879                "env var name MUST use DOIGET_ prefix, got `{}`",
880                ev.name
881            );
882        }
883    }
884
885    #[test]
886    fn mcp_tools_all_use_doiget_prefix() {
887        for t in MCP_TOOLS {
888            assert!(
889                t.name.starts_with("doiget_"),
890                "MCP tool name MUST use doiget_ prefix, got `{}`",
891                t.name
892            );
893        }
894    }
895
896    #[test]
897    fn subcommand_examples_reference_the_subcommand_name() {
898        for sub in &caps().subcommands {
899            for ex in sub.examples {
900                // `graph` examples carry a `DOIGET_ENABLE_OPENALEX=1`
901                // env prefix before `doiget …`. Allow either form.
902                assert!(
903                    ex.starts_with("doiget ") || ex.contains(" doiget "),
904                    "example `{ex}` for `{}` must invoke `doiget` somewhere",
905                    sub.name
906                );
907                assert!(
908                    ex.contains(&sub.name),
909                    "example `{ex}` does not mention subcommand `{}`",
910                    sub.name
911                );
912            }
913        }
914    }
915
916    // Exact-set parity guard against drift between the static
917    // `ENV_VARS` table and the documented surface (#215). The expected set is the SOURCE OF TRUTH at test time;
918    // adding a new DOIGET_* env var requires updating both ENV_VARS
919    // and this list in lockstep. CHANGELOG records cross-PR changes.
920    #[test]
921    fn env_vars_exact_set_matches_expected() {
922        let actual: std::collections::BTreeSet<&str> = ENV_VARS.iter().map(|ev| ev.name).collect();
923        let expected: std::collections::BTreeSet<&str> = [
924            // CONFIG.md §4 documented:
925            "DOIGET_STORE_ROOT",
926            "DOIGET_CACHE_ROOT",
927            "DOIGET_LOG_PATH",
928            "DOIGET_LOG_RETENTION_DAYS",
929            "DOIGET_USER_AGENT",
930            "DOIGET_UNPAYWALL_EMAIL",
931            "DOIGET_MODE",
932            // Code-reachable but documented in code-level docs or
933            // CAPABILITY.md (not CONFIG.md §4):
934            "DOIGET_CONTACT_EMAIL",
935            "DOIGET_ENABLE_OPENALEX",
936            // Test/wiremock-override base URLs:
937            "DOIGET_ARXIV_BASE",
938            "DOIGET_CROSSREF_BASE",
939            "DOIGET_UNPAYWALL_BASE",
940        ]
941        .into_iter()
942        .collect();
943        assert_eq!(
944            actual, expected,
945            "ENV_VARS table drifted from the expected canonical set; \
946             update both `ENV_VARS` and this test together (and CONFIG.md §4 \
947             if the new var is user-documented)."
948        );
949    }
950
951    // Exact-set parity guard against drift between the static
952    // `MCP_TOOLS` table and `docs/MCP_TOOLS.md` §1 (#215).
953    #[test]
954    fn mcp_tools_exact_set_matches_expected() {
955        let actual: std::collections::BTreeSet<&str> = MCP_TOOLS.iter().map(|t| t.name).collect();
956        let expected: std::collections::BTreeSet<&str> = [
957            "doiget_resolve_paper",
958            "doiget_fetch_paper",
959            "doiget_metadata_only",
960            "doiget_batch_fetch",
961            "doiget_info",
962            "doiget_search_local",
963            "doiget_list_recent",
964            "doiget_paper_pdf_path",
965            "doiget_capability_profile",
966            "doiget_health",
967            "doiget_expand_citation_graph",
968            "doiget_bibtex_export",
969            "doiget_csl_export",
970            "doiget_batch_from_bibliography",
971        ]
972        .into_iter()
973        .collect();
974        assert_eq!(
975            actual, expected,
976            "MCP_TOOLS table drifted from the expected set; update both \
977             `MCP_TOOLS` and this test together (and docs/MCP_TOOLS.md §1)."
978        );
979    }
980
981    // Pin the `#[serde(tag = "status")]` wire shape: every variant
982    // serialises to a `{"status":"…", …}` object. Accidentally
983    // removing the `tag` attribute (or renaming the discriminant)
984    // would silently degrade the wire format; this test catches it
985    // (#215 N1).
986    #[test]
987    fn json_mode_serialises_with_status_discriminant() {
988        let s = serde_json::to_string(&JsonMode::Artifact).expect("serialise");
989        assert_eq!(
990            s, r#"{"status":"artifact"}"#,
991            "Artifact must emit a status-tagged object"
992        );
993        let s = serde_json::to_string(&JsonMode::Supported).expect("serialise");
994        assert_eq!(s, r#"{"status":"supported"}"#);
995    }
996
997    // `arg_to_flag_spec` was generalised in #215 to harvest the
998    // accepted values from clap's `PossibleValuesParser` instead of
999    // hard-coding `--mode`. Pin the contract: the `--mode` entry in
1000    // `global_flags` MUST report `kind: Enum` with all four mode
1001    // strings. A future regression that silently degrades `--mode`
1002    // to `kind: String, values: None` would otherwise pass every
1003    // existing test (#215 N3).
1004    #[test]
1005    fn mode_flag_carries_enum_kind_and_all_four_values() {
1006        let global = &caps().global_flags;
1007        let mode = global
1008            .iter()
1009            .find(|f| f.name == "--mode")
1010            .expect("--mode flag is in global_flags");
1011        assert!(
1012            matches!(mode.kind, FlagKind::Enum),
1013            "--mode kind MUST be Enum, got {:?}",
1014            mode.kind
1015        );
1016        let vs = mode.values.as_ref().expect("--mode carries values");
1017        let mut sorted = vs.clone();
1018        sorted.sort();
1019        assert_eq!(sorted, vec!["human", "json", "mcp", "quiet"]);
1020    }
1021
1022    // `compile_time_features()` pushes string literals that must
1023    // exactly match the Cargo feature names in `Cargo.toml`. A
1024    // typo in the literal (`"oa_only"` vs `"oa-only"`) would
1025    // silently invert the inventory's `features` field for every
1026    // consumer. The default build has `oa-only` active; assert
1027    // the literal round-trips (#215 A9).
1028    #[test]
1029    fn compile_time_features_contains_oa_only_under_default() {
1030        // `cfg!(feature = "oa-only")` is true in the default test
1031        // build; if a future maintainer disables the default feature
1032        // for the test target, this test becomes meaningless but
1033        // does not cause a false failure.
1034        if cfg!(feature = "oa-only") {
1035            let f = compile_time_features();
1036            assert!(
1037                f.contains(&"oa-only"),
1038                "oa-only feature was enabled at compile time but \
1039                 `compile_time_features()` did not list it: {f:?}"
1040            );
1041        }
1042    }
1043
1044    #[test]
1045    fn version_is_cargo_pkg_version() {
1046        assert_eq!(caps().version, env!("CARGO_PKG_VERSION"));
1047    }
1048
1049    /// ADR-0028 D2: `user_extension_count` must reflect the number of
1050    /// `[[network.additional_hosts]]` entries actually present in
1051    /// `<config_dir>/doiget/config.toml`. The test points every
1052    /// config-dir env var at a tempdir, writes a 2-host config, and
1053    /// asserts the inventory reports `2`. Drift here would silently
1054    /// hide user-curated allowlist hosts from the cold-boot JSON.
1055    #[test]
1056    #[serial_test::serial]
1057    fn user_extension_count_reflects_config_toml_entries() {
1058        let tmp = tempfile::TempDir::new().expect("tempdir");
1059        let cfg_root = camino::Utf8Path::from_path(tmp.path()).expect("utf8 tempdir");
1060        let doiget_dir = cfg_root.join("doiget");
1061        std::fs::create_dir_all(doiget_dir.as_std_path()).expect("mk dir");
1062        let config_toml = doiget_dir.join("config.toml");
1063        std::fs::write(
1064            config_toml.as_std_path(),
1065            "[[network.additional_hosts]]\n\
1066             host = \"example.org\"\n\
1067             \n\
1068             [[network.additional_hosts]]\n\
1069             host = \"*.example.net\"\n\
1070             note = \"university OA mirror\"\n",
1071        )
1072        .expect("write config.toml");
1073
1074        let _x = EnvGuard::set("XDG_CONFIG_HOME", cfg_root.as_str());
1075        let _a = EnvGuard::unset("APPDATA");
1076        let _h = EnvGuard::unset("HOME");
1077        let _u = EnvGuard::unset("USERPROFILE");
1078
1079        let cli = test_cli();
1080        let caps = build_capabilities(&cli);
1081        assert_eq!(
1082            caps.user_extension_count, 2,
1083            "expected 2 user-extension hosts, got {}",
1084            caps.user_extension_count
1085        );
1086    }
1087
1088    /// Companion: with no config file (and a resolvable config dir),
1089    /// the count is `0` — the curated allowlist is the entire surface.
1090    /// Confirms the `Ok(vec![])` not-found path in `user_extension::load`
1091    /// flows through unchanged.
1092    #[test]
1093    #[serial_test::serial]
1094    fn user_extension_count_is_zero_without_config_toml() {
1095        let tmp = tempfile::TempDir::new().expect("tempdir");
1096        let cfg_root = camino::Utf8Path::from_path(tmp.path()).expect("utf8 tempdir");
1097
1098        let _x = EnvGuard::set("XDG_CONFIG_HOME", cfg_root.as_str());
1099        let _a = EnvGuard::unset("APPDATA");
1100        let _h = EnvGuard::unset("HOME");
1101        let _u = EnvGuard::unset("USERPROFILE");
1102
1103        let caps = build_capabilities(&test_cli());
1104        assert_eq!(caps.user_extension_count, 0);
1105    }
1106
1107    /// Minimal env-guard local to this tests module; mirrors the
1108    /// pattern in `commands::config::tests` (each module keeps its
1109    /// own copy so they stay leaf-level cheap).
1110    struct EnvGuard {
1111        var: &'static str,
1112        prior: Option<std::ffi::OsString>,
1113    }
1114
1115    impl EnvGuard {
1116        fn set(var: &'static str, value: &str) -> Self {
1117            let prior = std::env::var_os(var);
1118            std::env::set_var(var, value);
1119            EnvGuard { var, prior }
1120        }
1121        fn unset(var: &'static str) -> Self {
1122            let prior = std::env::var_os(var);
1123            std::env::remove_var(var);
1124            EnvGuard { var, prior }
1125        }
1126    }
1127
1128    impl Drop for EnvGuard {
1129        fn drop(&mut self) {
1130            match &self.prior {
1131                Some(v) => std::env::set_var(self.var, v),
1132                None => std::env::remove_var(self.var),
1133            }
1134        }
1135    }
1136
1137    #[test]
1138    fn every_test_cli_subcommand_has_metadata() {
1139        // Regression at the lib layer: anything we add to the shadow
1140        // `test_cli` must also be in `metadata_for`. The real
1141        // `Cli::command()` is exercised by the e2e test in
1142        // `tests/capabilities_e2e.rs`.
1143        for sub in test_cli().get_subcommands() {
1144            let name = sub.get_name();
1145            if name == "help" {
1146                continue;
1147            }
1148            assert!(
1149                metadata_for(name).is_some(),
1150                "subcommand `{name}` lacks metadata in `metadata_for`"
1151            );
1152        }
1153    }
1154}