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 "verify" => SubcommandMeta {
419 examples: &[
420 "doiget verify refs.bib",
421 "doiget verify library.bib --strict",
422 "doiget verify refs.txt --format refs",
423 ],
424 // Emits one JSON-Lines record per entry regardless of mode;
425 // the JSONL stream is the product output.
426 json_mode: JsonMode::Artifact,
427 feature_gated: None,
428 },
429 "info" => SubcommandMeta {
430 examples: &[
431 "doiget info 10.1234/foo",
432 "doiget info arxiv:2401.12345 --json",
433 ],
434 json_mode: JsonMode::Supported,
435 feature_gated: None,
436 },
437 "list-recent" => SubcommandMeta {
438 examples: &[
439 "doiget list-recent",
440 "doiget list-recent 20",
441 "doiget list-recent --json",
442 ],
443 json_mode: JsonMode::Supported,
444 feature_gated: None,
445 },
446 "search" => SubcommandMeta {
447 examples: &[
448 "doiget search 'quantum entanglement'",
449 "doiget search renormalization --json",
450 ],
451 json_mode: JsonMode::Supported,
452 feature_gated: None,
453 },
454 "bib" => SubcommandMeta {
455 examples: &["doiget bib 10.1234/foo", "doiget bib arxiv:2401.12345"],
456 // BibTeX output is the product; `--mode` is informational.
457 json_mode: JsonMode::Artifact,
458 feature_gated: None,
459 },
460 "cite" => SubcommandMeta {
461 examples: &["doiget cite 10.1234/foo", "doiget cite arxiv:2401.12345"],
462 // BibTeX output is the product (resolved live); `--mode` is
463 // informational, mirroring `bib`.
464 json_mode: JsonMode::Artifact,
465 feature_gated: None,
466 },
467 "csl" => SubcommandMeta {
468 examples: &["doiget csl 10.1234/foo"],
469 json_mode: JsonMode::Artifact,
470 feature_gated: None,
471 },
472 "audit-log" => SubcommandMeta {
473 examples: &[
474 "doiget audit-log --verify",
475 "doiget audit-log --verify --json",
476 "doiget --quiet audit-log --verify # exit code only",
477 ],
478 json_mode: JsonMode::Supported,
479 feature_gated: None,
480 },
481 "provenance" => SubcommandMeta {
482 examples: &[
483 "doiget provenance migrate --dry-run",
484 "doiget provenance migrate",
485 "doiget provenance migrate --dry-run --json",
486 ],
487 json_mode: JsonMode::Supported,
488 feature_gated: None,
489 },
490 "config" => SubcommandMeta {
491 examples: &[
492 "doiget config show",
493 "doiget config show --json",
494 "doiget config path",
495 "doiget config doctor",
496 ],
497 json_mode: JsonMode::Supported,
498 feature_gated: None,
499 },
500 "serve" => SubcommandMeta {
501 examples: &["doiget serve # stdio MCP server (ADR-0001)"],
502 // serve always runs in mcp mode; the protocol output is
503 // JSON-RPC, which is product.
504 json_mode: JsonMode::Artifact,
505 feature_gated: None,
506 },
507 "graph" => SubcommandMeta {
508 examples: &[
509 "DOIGET_ENABLE_OPENALEX=1 doiget graph 10.1234/foo",
510 "DOIGET_ENABLE_OPENALEX=1 doiget graph 10.1234/foo --depth 2 --total 50",
511 ],
512 json_mode: JsonMode::Artifact,
513 feature_gated: Some("citation"),
514 },
515 "version" => SubcommandMeta {
516 examples: &[
517 "doiget version",
518 "doiget version --check",
519 "doiget version --check --mode json",
520 ],
521 json_mode: JsonMode::Supported,
522 feature_gated: None,
523 },
524 "capabilities" => SubcommandMeta {
525 examples: &["doiget capabilities | jq ."],
526 // The whole point of capabilities IS JSON output.
527 json_mode: JsonMode::Artifact,
528 feature_gated: None,
529 },
530 // clap auto-adds `help`; we silently ignore it (it's not a
531 // domain subcommand).
532 "help" => return None,
533 _ => return None,
534 };
535 Some(m)
536}
537
538// ---------------------------------------------------------------------------
539// Build
540// ---------------------------------------------------------------------------
541
542/// Build the [`Capabilities`] inventory from `cli` (the clap parser
543/// for this binary, supplied by the caller because the `Cli` struct
544/// lives in `main.rs` and is not exposed in the library crate). The
545/// caller is `commands::main::run_dispatch` via `Cli::command()`.
546pub fn build_capabilities(cli: &clap::Command) -> Capabilities {
547 let global_flags = collect_global_flags(cli);
548 let subcommands = cli
549 .get_subcommands()
550 .filter_map(|sub| build_subcommand(sub, cli))
551 .collect::<Vec<_>>();
552 Capabilities {
553 version: env!("CARGO_PKG_VERSION"),
554 features: compile_time_features(),
555 modes: MODES,
556 global_flags,
557 subcommands,
558 env_vars: ENV_VARS,
559 mcp_tools: MCP_TOOLS,
560 docs: DOCS,
561 user_extension_count: user_extension_count(),
562 }
563}
564
565/// Count valid `[[network.additional_hosts]]` entries in
566/// `<config_dir>/doiget/config.toml` (ADR-0028 D2). Returns `0` on any
567/// failure — missing config, parse error, unresolvable config dir.
568/// Diagnose failures via `doiget config doctor`; here we only need a
569/// best-effort cold-boot signal for the inventory.
570fn user_extension_count() -> usize {
571 let cfg_dir = match super::fetch::config_dir_utf8() {
572 Ok(p) => p,
573 Err(_) => return 0,
574 };
575 let path = cfg_dir.join("doiget").join("config.toml");
576 match doiget_core::user_extension::load(&path) {
577 Ok(hosts) => hosts.len(),
578 Err(_) => 0,
579 }
580}
581
582fn compile_time_features() -> Vec<&'static str> {
583 let mut feats: Vec<&'static str> = Vec::new();
584 if cfg!(feature = "oa-only") {
585 feats.push("oa-only");
586 }
587 if cfg!(feature = "metadata") {
588 feats.push("metadata");
589 }
590 if cfg!(feature = "citation") {
591 feats.push("citation");
592 }
593 if cfg!(feature = "tdm-elsevier") {
594 feats.push("tdm-elsevier");
595 }
596 if cfg!(feature = "tdm-aps") {
597 feats.push("tdm-aps");
598 }
599 if cfg!(feature = "tdm-springer") {
600 feats.push("tdm-springer");
601 }
602 feats
603}
604
605fn collect_global_flags(cmd: &clap::Command) -> Vec<FlagSpec> {
606 cmd.get_arguments()
607 .filter(|a| a.is_global_set())
608 .map(arg_to_flag_spec)
609 .collect()
610}
611
612fn build_subcommand(sub: &clap::Command, root: &clap::Command) -> Option<SubcommandSpec> {
613 let name = sub.get_name();
614 let meta = metadata_for(name)?;
615 let (args, flags) = split_args_and_flags(sub, root);
616 Some(SubcommandSpec {
617 name: name.to_string(),
618 summary: sub.get_about().map(|s| s.to_string()),
619 args,
620 flags,
621 examples: meta.examples,
622 json_mode: meta.json_mode,
623 feature_gated: meta.feature_gated,
624 })
625}
626
627fn split_args_and_flags(
628 sub: &clap::Command,
629 root: &clap::Command,
630) -> (Vec<ArgSpec>, Vec<FlagSpec>) {
631 // The root's global args appear in every subcommand's iterator;
632 // suppress them from per-subcommand `flags` (they're already in
633 // `global_flags`).
634 let global_names: std::collections::HashSet<&str> = root
635 .get_arguments()
636 .filter(|a| a.is_global_set())
637 .map(|a| a.get_id().as_str())
638 .collect();
639 let mut args = Vec::new();
640 let mut flags = Vec::new();
641 for a in sub.get_arguments() {
642 if global_names.contains(a.get_id().as_str()) {
643 continue;
644 }
645 // Clap auto-adds `--help` (and `--version` on the root) to
646 // every subcommand. They're not positional and not
647 // `is_global_set()`, so they would otherwise leak into every
648 // subcommand's `flags[]` as `kind: "string"`. Filter on the
649 // action against the known built-in variants.
650 //
651 // **Maintenance:** `clap::ArgAction` is itself
652 // `#[non_exhaustive]` upstream. A future clap release that
653 // adds a new built-in action (e.g. a hypothetical
654 // `HelpMarkdown`) would fall through this `matches!` and
655 // reappear in `flags[]`. Re-audit this filter on every clap
656 // minor-version bump.
657 if matches!(
658 a.get_action(),
659 clap::ArgAction::Help
660 | clap::ArgAction::HelpShort
661 | clap::ArgAction::HelpLong
662 | clap::ArgAction::Version
663 ) {
664 continue;
665 }
666 if a.is_positional() {
667 args.push(ArgSpec {
668 name: a.get_id().to_string(),
669 kind: ArgKind::Positional,
670 help: a.get_help().map(|s| s.to_string()),
671 required: a.is_required_set(),
672 });
673 } else {
674 flags.push(arg_to_flag_spec(a));
675 }
676 }
677 (args, flags)
678}
679
680fn arg_to_flag_spec(a: &clap::Arg) -> FlagSpec {
681 let name = a
682 .get_long()
683 .map(|s| format!("--{s}"))
684 .or_else(|| a.get_short().map(|c| format!("-{c}")))
685 .unwrap_or_else(|| a.get_id().to_string());
686 // Boolean switches → `Bool`; value-enum flags → `Enum` with the
687 // accepted values harvested from clap directly; everything else
688 // → `String`. The `possible_values()` harvest covers any future
689 // enum flag without code change (see #215).
690 let possible: Option<Vec<String>> = a
691 .get_value_parser()
692 .possible_values()
693 .map(|it| it.map(|pv| pv.get_name().to_owned()).collect());
694 let (kind, values) = if matches!(
695 a.get_action(),
696 clap::ArgAction::SetTrue | clap::ArgAction::SetFalse
697 ) {
698 (FlagKind::Bool, None)
699 } else if let Some(vs) = possible {
700 (FlagKind::Enum, Some(vs))
701 } else {
702 (FlagKind::String, None)
703 };
704 FlagSpec {
705 name,
706 kind,
707 help: a.get_help().map(|s| s.to_string()),
708 values,
709 }
710}
711
712// ---------------------------------------------------------------------------
713// Entry point
714// ---------------------------------------------------------------------------
715
716/// Run the `doiget capabilities` subcommand.
717///
718/// `capabilities` is an **artifact** command per ADR-0017 Amendment 1:
719/// its stdout output IS the deliverable (the inventory JSON an LLM
720/// reads on cold-boot). It honors only **explicit** Quiet —
721/// `--quiet` / `-q` / `--mode quiet` / `DOIGET_MODE=quiet` — and emits
722/// the inventory on every other path. The `quiet_was_explicit`
723/// discriminator is what distinguishes the two cases:
724///
725/// | mode | quiet_was_explicit | behaviour |
726/// |--------------------|--------------------|--------------------|
727/// | non-`Quiet` | - | emit |
728/// | `Quiet` (explicit) | `true` | suppress |
729/// | `Quiet` (non-TTY) | `false` | **emit** (#219) |
730///
731/// The non-TTY case is the one #219 / #220 report: an LLM tool
732/// executor captures stdout, so `stdout_is_tty()` is `false`, the
733/// resolver falls through to `Quiet`, but the caller wants the JSON
734/// inventory exactly because it's about to be machine-parsed. The
735/// table's bottom row is the fix.
736///
737/// The caller passes the live `clap::Command` so the clap walk
738/// operates on the binary's actual `Cli` tree (which the lib half of
739/// this crate can't reach directly — the `Cli` struct lives in
740/// `main.rs`).
741pub fn run(
742 cli: &clap::Command,
743 mode: super::output::OutputMode,
744 quiet_was_explicit: bool,
745) -> Result<()> {
746 // ADR-0017 Amendment 1: artifact command — suppress ONLY on
747 // explicit Quiet, never on the non-TTY implicit fallback.
748 if mode == super::output::OutputMode::Quiet && quiet_was_explicit {
749 return Ok(());
750 }
751 let caps = build_capabilities(cli);
752 let s = serde_json::to_string_pretty(&caps).context("serialise capabilities inventory")?;
753 // `print_stdout` workspace-deny; localised allow at the
754 // sanctioned product-output sink. See `commands/csl.rs`'s pattern.
755 #[allow(clippy::print_stdout)]
756 {
757 println!("{s}");
758 }
759 Ok(())
760}
761
762// ---------------------------------------------------------------------------
763// Tests
764// ---------------------------------------------------------------------------
765
766#[cfg(test)]
767#[allow(clippy::expect_used, clippy::unwrap_used, clippy::panic)]
768mod tests {
769 use super::*;
770
771 /// Mirrors the `Cli` struct in `main.rs` for lib-test reach.
772 /// `commands::capabilities` is library-level; the binary-only
773 /// `Cli` struct can't be reached from here, so we re-derive a
774 /// shadow whose subcommand list is identical. The
775 /// `cli_shadow_matches_main_cli` integration test in
776 /// `tests/capabilities_e2e.rs` runs the real binary and asserts
777 /// the wire output matches.
778 fn test_cli() -> clap::Command {
779 use clap::{Arg, ArgAction, Command};
780 let mode_values = ["human", "json", "quiet", "mcp"];
781 let cmd = Command::new("doiget")
782 .arg(
783 Arg::new("mode")
784 .long("mode")
785 .global(true)
786 .value_parser(clap::builder::PossibleValuesParser::new(mode_values))
787 .help("Output mode (human|json|quiet|mcp)."),
788 )
789 .arg(
790 Arg::new("json")
791 .long("json")
792 .global(true)
793 .action(ArgAction::SetTrue)
794 .help("Short for `--mode json`."),
795 )
796 .arg(
797 Arg::new("quiet")
798 .long("quiet")
799 .short('q')
800 .global(true)
801 .action(ArgAction::SetTrue)
802 .help("Short for `--mode quiet`."),
803 )
804 .subcommand(
805 Command::new("fetch")
806 .about("Fetch a single paper PDF")
807 .arg(Arg::new("ref").required(true))
808 .arg(
809 Arg::new("dry-run")
810 .long("dry-run")
811 .action(ArgAction::SetTrue),
812 ),
813 )
814 .subcommand(
815 Command::new("batch")
816 .about("Fetch many refs")
817 .arg(Arg::new("path").required(true))
818 .arg(
819 Arg::new("dry-run")
820 .long("dry-run")
821 .action(ArgAction::SetTrue),
822 ),
823 )
824 .subcommand(
825 Command::new("info")
826 .about("Show metadata")
827 .arg(Arg::new("ref").required(true)),
828 )
829 .subcommand(Command::new("list-recent").about("List recent"))
830 .subcommand(
831 Command::new("search")
832 .about("Search local")
833 .arg(Arg::new("query").required(true)),
834 )
835 .subcommand(
836 Command::new("bib")
837 .about("BibTeX export")
838 .arg(Arg::new("ref").required(true)),
839 )
840 .subcommand(
841 Command::new("cite")
842 .about("Live BibTeX")
843 .arg(Arg::new("ref").required(true)),
844 )
845 .subcommand(
846 Command::new("csl")
847 .about("CSL export")
848 .arg(Arg::new("ref").required(true)),
849 )
850 .subcommand(
851 Command::new("audit-log")
852 .about("Audit log")
853 .arg(Arg::new("verify").long("verify").action(ArgAction::SetTrue)),
854 )
855 .subcommand(Command::new("provenance").about("Provenance ops"))
856 .subcommand(
857 Command::new("config")
858 .about("Config")
859 .arg(Arg::new("action").required(true)),
860 )
861 .subcommand(Command::new("serve").about("MCP server"));
862 // `graph` is `#[cfg(feature = "citation")]` in main.rs; mirror
863 // the gate so the shadow CLI matches the production surface
864 // (see #215).
865 #[cfg(feature = "citation")]
866 let cmd = cmd.subcommand(
867 Command::new("graph")
868 .about("Citation graph")
869 .arg(Arg::new("ref").required(true)),
870 );
871 cmd.subcommand(Command::new("capabilities").about("Capabilities"))
872 }
873
874 fn caps() -> Capabilities {
875 build_capabilities(&test_cli())
876 }
877
878 #[test]
879 fn capabilities_serialises_to_valid_json() {
880 let s = serde_json::to_string_pretty(&caps()).expect("serialise");
881 let v: serde_json::Value = serde_json::from_str(&s).expect("parse round-trip");
882 for key in [
883 "version",
884 "features",
885 "modes",
886 "global_flags",
887 "subcommands",
888 "env_vars",
889 "mcp_tools",
890 "docs",
891 "user_extension_count",
892 ] {
893 assert!(
894 v.get(key).is_some(),
895 "top-level key `{key}` missing from capabilities JSON: {v}"
896 );
897 }
898 }
899
900 #[test]
901 fn modes_field_matches_output_mode_enum() {
902 // Tied to `OutputMode { Human, Json, Quiet, Mcp }`.
903 assert_eq!(caps().modes, &["human", "json", "quiet", "mcp"]);
904 }
905
906 #[test]
907 fn env_vars_all_use_doiget_prefix() {
908 for ev in ENV_VARS {
909 assert!(
910 ev.name.starts_with("DOIGET_"),
911 "env var name MUST use DOIGET_ prefix, got `{}`",
912 ev.name
913 );
914 }
915 }
916
917 #[test]
918 fn mcp_tools_all_use_doiget_prefix() {
919 for t in MCP_TOOLS {
920 assert!(
921 t.name.starts_with("doiget_"),
922 "MCP tool name MUST use doiget_ prefix, got `{}`",
923 t.name
924 );
925 }
926 }
927
928 #[test]
929 fn subcommand_examples_reference_the_subcommand_name() {
930 for sub in &caps().subcommands {
931 for ex in sub.examples {
932 // `graph` examples carry a `DOIGET_ENABLE_OPENALEX=1`
933 // env prefix before `doiget …`. Allow either form.
934 assert!(
935 ex.starts_with("doiget ") || ex.contains(" doiget "),
936 "example `{ex}` for `{}` must invoke `doiget` somewhere",
937 sub.name
938 );
939 assert!(
940 ex.contains(&sub.name),
941 "example `{ex}` does not mention subcommand `{}`",
942 sub.name
943 );
944 }
945 }
946 }
947
948 // Exact-set parity guard against drift between the static
949 // `ENV_VARS` table and the documented surface (#215). The expected set is the SOURCE OF TRUTH at test time;
950 // adding a new DOIGET_* env var requires updating both ENV_VARS
951 // and this list in lockstep. CHANGELOG records cross-PR changes.
952 #[test]
953 fn env_vars_exact_set_matches_expected() {
954 let actual: std::collections::BTreeSet<&str> = ENV_VARS.iter().map(|ev| ev.name).collect();
955 let expected: std::collections::BTreeSet<&str> = [
956 // CONFIG.md §4 documented:
957 "DOIGET_STORE_ROOT",
958 "DOIGET_CACHE_ROOT",
959 "DOIGET_LOG_PATH",
960 "DOIGET_LOG_RETENTION_DAYS",
961 "DOIGET_USER_AGENT",
962 "DOIGET_UNPAYWALL_EMAIL",
963 "DOIGET_MODE",
964 // Code-reachable but documented in code-level docs or
965 // CAPABILITY.md (not CONFIG.md §4):
966 "DOIGET_CONTACT_EMAIL",
967 "DOIGET_ENABLE_OPENALEX",
968 // Test/wiremock-override base URLs:
969 "DOIGET_ARXIV_BASE",
970 "DOIGET_CROSSREF_BASE",
971 "DOIGET_UNPAYWALL_BASE",
972 ]
973 .into_iter()
974 .collect();
975 assert_eq!(
976 actual, expected,
977 "ENV_VARS table drifted from the expected canonical set; \
978 update both `ENV_VARS` and this test together (and CONFIG.md §4 \
979 if the new var is user-documented)."
980 );
981 }
982
983 // Exact-set parity guard against drift between the static
984 // `MCP_TOOLS` table and `docs/MCP_TOOLS.md` §1 (#215).
985 #[test]
986 fn mcp_tools_exact_set_matches_expected() {
987 let actual: std::collections::BTreeSet<&str> = MCP_TOOLS.iter().map(|t| t.name).collect();
988 let expected: std::collections::BTreeSet<&str> = [
989 "doiget_resolve_paper",
990 "doiget_fetch_paper",
991 "doiget_metadata_only",
992 "doiget_batch_fetch",
993 "doiget_info",
994 "doiget_search_local",
995 "doiget_list_recent",
996 "doiget_paper_pdf_path",
997 "doiget_capability_profile",
998 "doiget_health",
999 "doiget_expand_citation_graph",
1000 "doiget_bibtex_export",
1001 "doiget_csl_export",
1002 "doiget_batch_from_bibliography",
1003 ]
1004 .into_iter()
1005 .collect();
1006 assert_eq!(
1007 actual, expected,
1008 "MCP_TOOLS table drifted from the expected set; update both \
1009 `MCP_TOOLS` and this test together (and docs/MCP_TOOLS.md §1)."
1010 );
1011 }
1012
1013 // Pin the `#[serde(tag = "status")]` wire shape: every variant
1014 // serialises to a `{"status":"…", …}` object. Accidentally
1015 // removing the `tag` attribute (or renaming the discriminant)
1016 // would silently degrade the wire format; this test catches it
1017 // (#215 N1).
1018 #[test]
1019 fn json_mode_serialises_with_status_discriminant() {
1020 let s = serde_json::to_string(&JsonMode::Artifact).expect("serialise");
1021 assert_eq!(
1022 s, r#"{"status":"artifact"}"#,
1023 "Artifact must emit a status-tagged object"
1024 );
1025 let s = serde_json::to_string(&JsonMode::Supported).expect("serialise");
1026 assert_eq!(s, r#"{"status":"supported"}"#);
1027 }
1028
1029 // `arg_to_flag_spec` was generalised in #215 to harvest the
1030 // accepted values from clap's `PossibleValuesParser` instead of
1031 // hard-coding `--mode`. Pin the contract: the `--mode` entry in
1032 // `global_flags` MUST report `kind: Enum` with all four mode
1033 // strings. A future regression that silently degrades `--mode`
1034 // to `kind: String, values: None` would otherwise pass every
1035 // existing test (#215 N3).
1036 #[test]
1037 fn mode_flag_carries_enum_kind_and_all_four_values() {
1038 let global = &caps().global_flags;
1039 let mode = global
1040 .iter()
1041 .find(|f| f.name == "--mode")
1042 .expect("--mode flag is in global_flags");
1043 assert!(
1044 matches!(mode.kind, FlagKind::Enum),
1045 "--mode kind MUST be Enum, got {:?}",
1046 mode.kind
1047 );
1048 let vs = mode.values.as_ref().expect("--mode carries values");
1049 let mut sorted = vs.clone();
1050 sorted.sort();
1051 assert_eq!(sorted, vec!["human", "json", "mcp", "quiet"]);
1052 }
1053
1054 // `compile_time_features()` pushes string literals that must
1055 // exactly match the Cargo feature names in `Cargo.toml`. A
1056 // typo in the literal (`"oa_only"` vs `"oa-only"`) would
1057 // silently invert the inventory's `features` field for every
1058 // consumer. The default build has `oa-only` active; assert
1059 // the literal round-trips (#215 A9).
1060 #[test]
1061 fn compile_time_features_contains_oa_only_under_default() {
1062 // `cfg!(feature = "oa-only")` is true in the default test
1063 // build; if a future maintainer disables the default feature
1064 // for the test target, this test becomes meaningless but
1065 // does not cause a false failure.
1066 if cfg!(feature = "oa-only") {
1067 let f = compile_time_features();
1068 assert!(
1069 f.contains(&"oa-only"),
1070 "oa-only feature was enabled at compile time but \
1071 `compile_time_features()` did not list it: {f:?}"
1072 );
1073 }
1074 }
1075
1076 #[test]
1077 fn version_is_cargo_pkg_version() {
1078 assert_eq!(caps().version, env!("CARGO_PKG_VERSION"));
1079 }
1080
1081 /// ADR-0028 D2: `user_extension_count` must reflect the number of
1082 /// `[[network.additional_hosts]]` entries actually present in
1083 /// `<config_dir>/doiget/config.toml`. The test points every
1084 /// config-dir env var at a tempdir, writes a 2-host config, and
1085 /// asserts the inventory reports `2`. Drift here would silently
1086 /// hide user-curated allowlist hosts from the cold-boot JSON.
1087 #[test]
1088 #[serial_test::serial]
1089 fn user_extension_count_reflects_config_toml_entries() {
1090 let tmp = tempfile::TempDir::new().expect("tempdir");
1091 let cfg_root = camino::Utf8Path::from_path(tmp.path()).expect("utf8 tempdir");
1092 let doiget_dir = cfg_root.join("doiget");
1093 std::fs::create_dir_all(doiget_dir.as_std_path()).expect("mk dir");
1094 let config_toml = doiget_dir.join("config.toml");
1095 std::fs::write(
1096 config_toml.as_std_path(),
1097 "[[network.additional_hosts]]\n\
1098 host = \"example.org\"\n\
1099 \n\
1100 [[network.additional_hosts]]\n\
1101 host = \"*.example.net\"\n\
1102 note = \"university OA mirror\"\n",
1103 )
1104 .expect("write config.toml");
1105
1106 let _x = EnvGuard::set("XDG_CONFIG_HOME", cfg_root.as_str());
1107 let _a = EnvGuard::unset("APPDATA");
1108 let _h = EnvGuard::unset("HOME");
1109 let _u = EnvGuard::unset("USERPROFILE");
1110
1111 let cli = test_cli();
1112 let caps = build_capabilities(&cli);
1113 assert_eq!(
1114 caps.user_extension_count, 2,
1115 "expected 2 user-extension hosts, got {}",
1116 caps.user_extension_count
1117 );
1118 }
1119
1120 /// Companion: with no config file (and a resolvable config dir),
1121 /// the count is `0` — the curated allowlist is the entire surface.
1122 /// Confirms the `Ok(vec![])` not-found path in `user_extension::load`
1123 /// flows through unchanged.
1124 #[test]
1125 #[serial_test::serial]
1126 fn user_extension_count_is_zero_without_config_toml() {
1127 let tmp = tempfile::TempDir::new().expect("tempdir");
1128 let cfg_root = camino::Utf8Path::from_path(tmp.path()).expect("utf8 tempdir");
1129
1130 let _x = EnvGuard::set("XDG_CONFIG_HOME", cfg_root.as_str());
1131 let _a = EnvGuard::unset("APPDATA");
1132 let _h = EnvGuard::unset("HOME");
1133 let _u = EnvGuard::unset("USERPROFILE");
1134
1135 let caps = build_capabilities(&test_cli());
1136 assert_eq!(caps.user_extension_count, 0);
1137 }
1138
1139 /// Minimal env-guard local to this tests module; mirrors the
1140 /// pattern in `commands::config::tests` (each module keeps its
1141 /// own copy so they stay leaf-level cheap).
1142 struct EnvGuard {
1143 var: &'static str,
1144 prior: Option<std::ffi::OsString>,
1145 }
1146
1147 impl EnvGuard {
1148 fn set(var: &'static str, value: &str) -> Self {
1149 let prior = std::env::var_os(var);
1150 std::env::set_var(var, value);
1151 EnvGuard { var, prior }
1152 }
1153 fn unset(var: &'static str) -> Self {
1154 let prior = std::env::var_os(var);
1155 std::env::remove_var(var);
1156 EnvGuard { var, prior }
1157 }
1158 }
1159
1160 impl Drop for EnvGuard {
1161 fn drop(&mut self) {
1162 match &self.prior {
1163 Some(v) => std::env::set_var(self.var, v),
1164 None => std::env::remove_var(self.var),
1165 }
1166 }
1167 }
1168
1169 #[test]
1170 fn every_test_cli_subcommand_has_metadata() {
1171 // Regression at the lib layer: anything we add to the shadow
1172 // `test_cli` must also be in `metadata_for`. The real
1173 // `Cli::command()` is exercised by the e2e test in
1174 // `tests/capabilities_e2e.rs`.
1175 for sub in test_cli().get_subcommands() {
1176 let name = sub.get_name();
1177 if name == "help" {
1178 continue;
1179 }
1180 assert!(
1181 metadata_for(name).is_some(),
1182 "subcommand `{name}` lacks metadata in `metadata_for`"
1183 );
1184 }
1185 }
1186}