mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
//! Self-description: the surface the product publishes about itself.
//!
//! These commands reach no server, so they answer on a host with no
//! destination configured at all.

use super::contract;
use crate::cli::{meta::MetaCommand, Cli};
use crate::error::{ExitNumber, Failure, Result};
use crate::output::Envelope;
use clap::CommandFactory;
use serde_json::{json, Value};

/// Serves one discovery command.
///
/// # Errors
///
/// Returns an absence failure when a contract is asked for a command that does
/// not exist.
pub fn execute(command: &MetaCommand, cli: &Cli) -> Result<Envelope> {
    match command {
        MetaCommand::Commands(args) => Ok(commands(args.with_globals)),
        MetaCommand::Schema(args) => schema(args.command.as_deref(), args.types),
        MetaCommand::Version => Ok(version()),
        // `--output` on this command and the global `--output` are one and the
        // same argument: both carry the identifier `output`, so `clap` matches
        // them once and hands the value to both. Writing the file here as well
        // would write the destination twice, the second time with the account
        // of the first write. So the destination is left to the one place that
        // serves it for every command, and the page travels in the envelope.
        MetaCommand::Manual(_) => Ok(manual()),
        MetaCommand::Completions(args) => completions(args.shell),
    }
    .map(|envelope| annotate(envelope, cli))
}

/// Leaves the envelope as produced; kept as the single place a future
/// invocation-wide annotation would attach.
const fn annotate(envelope: Envelope, _cli: &Cli) -> Envelope {
    envelope
}

/// The whole command tree, with the state of each command.
///
/// The state travels with the command so the published surface never claims
/// more than the build serves.
fn commands(with_globals: bool) -> Envelope {
    let root = Cli::command();
    let mut rows = Vec::new();
    collect(&root, &mut Vec::new(), &mut rows);
    rows.sort_by(|left, right| left["name"].as_str().cmp(&right["name"].as_str()));

    let mut data = json!({ "rows": rows });
    if with_globals {
        data["globals"] = global_flags(&root);
    }
    Envelope::new("meta commands", data)
}

/// Walks the tree and records every leaf command.
fn collect(command: &clap::Command, path: &mut Vec<String>, rows: &mut Vec<Value>) {
    for sub in command.get_subcommands() {
        path.push(sub.get_name().to_owned());
        if sub.get_subcommands().next().is_some() {
            collect(sub, path, rows);
        } else {
            let name = path.join(" ");
            let served = is_served(&name);
            rows.push(json!({
                "name": name,
                "about": sub.get_about().map(ToString::to_string).unwrap_or_default(),
                "state": if served { "served" } else { "planned" },
            }));
        }
        path.pop();
    }
}

/// Whether this build actually serves the named command.
///
/// The answer comes from the single list of served leaves, so the state
/// published here is the reach the build really has and not a guess drawn from
/// the shape of the name. A command that is published but not served fails
/// with a usage number and a hint, rather than pretending to work.
#[must_use]
pub fn is_served(name: &str) -> bool {
    super::SERVED_LEAVES.contains(&name)
}

/// The global flags, as published.
fn global_flags(root: &clap::Command) -> Value {
    let mut flags: Vec<Value> = root
        .get_arguments()
        .filter(|arg| arg.is_global_set())
        .map(|arg| {
            json!({
                "name": arg.get_long().unwrap_or_else(|| arg.get_id().as_str()),
                "about": arg.get_help().map(ToString::to_string).unwrap_or_default(),
            })
        })
        .collect();
    flags.sort_by(|left, right| left["name"].as_str().cmp(&right["name"].as_str()));
    Value::Array(flags)
}

/// The output contract of one command, or the type map.
fn schema(command: Option<&str>, types: bool) -> Result<Envelope> {
    if types {
        return Ok(Envelope::new("meta schema", type_map()));
    }

    let Some(wanted) = command else {
        let root = Cli::command();
        let mut rows = Vec::new();
        collect(&root, &mut Vec::new(), &mut rows);
        let names: Vec<Value> = rows.into_iter().map(|row| row["name"].clone()).collect();
        return Ok(Envelope::new("meta schema", json!({ "rows": names })));
    };

    let root = Cli::command();
    let mut rows = Vec::new();
    collect(&root, &mut Vec::new(), &mut rows);

    // A command that carries actions of its own is published under each of
    // them and never under the group, so a lookup by the group name has to
    // resolve to the group rather than be read as an unknown leaf. The actions
    // travel with the answer, because that is what a caller who asked about the
    // group has to know next.
    let carried = actions_under(wanted, &rows);
    if !carried.is_empty() {
        return Ok(Envelope::new(
            "meta schema",
            json!({
                "command": wanted,
                "state": if carried.iter().all(|leaf| is_served(leaf)) { "served" } else { "planned" },
                "actions": carried,
                "failures": contract::failure_shape(),
                "envelope": contract::envelope_shape(),
            }),
        ));
    }

    if !rows.iter().any(|row| row["name"] == wanted) {
        return Err(Failure::absence(
            "schema.unknown_command",
            format!("`{wanted}` is not a command of this product"),
        )
        .with_detail("detail", wanted)
        .with_hint("run `meta commands` to see the published tree"));
    }

    let mut data = json!({
        "command": wanted,
        "state": if is_served(wanted) { "served" } else { "planned" },
        "inputs": contract::inputs_of(&root, wanted),
        "effect": contract::effect_of(wanted),
        "data": contract::data_shape_of(wanted),
        "failures": contract::failure_shape(),
        "envelope": contract::envelope_shape(),
    });
    let marked = contract::marks_absence(wanted);
    if !marked.is_empty() {
        data["absent_when_missing"] = json!(marked);
    }
    Ok(Envelope::new("meta schema", data))
}

/// The published leaves a group carries, in the order the tree lists them.
///
/// A name is a group when the tree publishes leaves beneath it, so the answer
/// is read from the tree itself and can never name an action the build does not
/// carry.
fn actions_under(wanted: &str, rows: &[Value]) -> Vec<String> {
    let prefix = format!("{wanted} ");
    rows.iter()
        .filter_map(|row| row["name"].as_str())
        .filter(|name| name.starts_with(&prefix))
        .map(ToOwned::to_owned)
        .collect()
}

/// The fixed conversion from each server type family to its emitted form.
///
/// The rows are read from the one table the converter itself obeys, so the map
/// a caller reads can never name fewer families than the build converts. The
/// table is not configurable: a configurable conversion makes the same value
/// arrive in different shapes on different hosts.
fn type_map() -> Value {
    let rows: Vec<Value> = crate::types::map::published()
        .iter()
        .map(|entry| {
            json!({
                "family": entry.family.as_str(),
                "emitted": entry.shape.as_str(),
                "reason": entry.note,
            })
        })
        .collect();
    json!({ "rows": rows, "notes": TYPE_MAP_NOTES })
}

/// What a caller has to know about the map that no single row of it says.
///
/// These are conditions of the server and of its protocol rather than choices
/// of this build, so they are published beside the table instead of being left
/// for a caller to discover by being surprised. None of them changes a family
/// already published, which is what the amendment they come from requires.
const TYPE_MAP_NOTES: &[&str] = &[
    "The family of a stored value comes from the type the catalogue declares \
     for the column it lives in, never from the packet it arrived in: the \
     result packet of this server does not tell a universal identifier or a \
     network address apart from ordinary text.",
    "A result column the server declares no stored origin for was produced \
     rather than read, so there is no catalogue type to ask about it and its \
     family comes from the packet.",
    "The structured document of this server is text the server itself \
     validates, and not a binary type of its own.",
    "A text column with no validation declared for it is never turned into a \
     structure by guessing.",
];

/// The identity of the product and what this build can do.
fn version() -> Envelope {
    Envelope::new(
        "meta version",
        json!({
            "name": env!("CARGO_PKG_NAME"),
            "version": env!("CARGO_PKG_VERSION"),
            "encrypted_channel_available": crate::ENCRYPTED_CHANNEL_AVAILABLE,
            // Which cryptography this binary carries, and whether it has been
            // formally audited. Published rather than inferred, so a caller
            // deciding whether to trust this build never has to guess.
            "crypto_provider": crate::conn::provider::PROVIDER_NAME,
            "crypto_provider_audited": crate::conn::provider::PROVIDER_IS_AUDITED,
            "envelope_schema_version": crate::output::SCHEMA_VERSION,
        }),
    )
}

/// The manual of this build, as a manual page.
///
/// The page is generated from the very tree `clap` publishes, so it can never
/// describe a flag this build does not accept nor omit one it does. What the
/// generator cannot know — the command list with its state, the exit numbers
/// and the standing notes — is appended from the same tables the product obeys
/// elsewhere, never from prose written a second time.
///
/// The page travels inside the envelope, like every other answer, so the
/// primary channel carries one parseable document whatever was asked for.
///
/// A caller that wants the page on disk points `--output` at a file, and gets
/// the roff source rather than the envelope: the answer declares which of its
/// fields is a document in its own right, and the one place that writes to a
/// file writes that field. Writing the envelope, as this once did, produced a
/// `.1` file a manual reader could not open and whose name lied about what was
/// inside it.
fn manual() -> Envelope {
    Envelope::new(
        "meta manual",
        json!({ "format": "roff", "page": manual_page() }),
    )
    // The page is a document a manual reader opens, not data about one, so a
    // caller pointing `--output` at a file gets the page and not the envelope
    // with the page inside it. The primary channel is unchanged.
    .with_raw_field("page")
}

/// The manual page source, in the format a manual reader already understands.
fn manual_page() -> String {
    use clap_mangen::roff::{bold, roman, Roff};

    let root = Cli::command();
    let mut page = Vec::new();
    // Writing into memory cannot fail, and the generator only ever fails on the
    // write, so there is no failure here to hand back to a caller.
    let _ = clap_mangen::Man::new(root.clone())
        .title(env!("CARGO_PKG_NAME").to_uppercase())
        .section("1")
        .source(concat!(
            env!("CARGO_PKG_NAME"),
            " ",
            env!("CARGO_PKG_VERSION")
        ))
        // Read from the catalogue rather than written here. This was the one
        // Portuguese literal left in the product's source, so the page announced
        // itself in Portuguese to a reader who had asked for English, and the
        // code carried a language the rest of it does not use.
        .manual(crate::i18n::report::prose(
            crate::i18n::report::MANUAL_SECTION,
            &[],
        ))
        .render(&mut page);

    let mut extra = Roff::new();

    let mut rows = Vec::new();
    collect(&root, &mut Vec::new(), &mut rows);
    rows.sort_by(|left, right| left["name"].as_str().cmp(&right["name"].as_str()));
    extra.control("SH", ["COMMANDS"]);
    extra.text([roman(
        "Every command this build publishes, with the state it is in. A command \
         marked planned is on the surface but not served by this build, and \
         answers with the usage number rather than pretending to work.",
    )]);
    for row in &rows {
        let name = row["name"].as_str().unwrap_or_default();
        let state = row["state"].as_str().unwrap_or_default();
        let about = row["about"].as_str().unwrap_or_default();
        extra.control("TP", []);
        extra.text([bold(name), roman(format!(" ({state})"))]);
        extra.text([roman(about)]);
    }

    extra.control("SH", ["EXIT NUMBERS"]);
    extra.text([roman(
        "The list is closed. A number outside it does not exist in the product.",
    )]);
    for (number, meaning) in EXIT_MEANINGS {
        extra.control("TP", []);
        extra.text([bold(number.code().to_string())]);
        extra.text([roman(*meaning)]);
    }

    extra.control("SH", ["NOTES"]);
    for (heading, text) in MANUAL_NOTES {
        extra.control("TP", []);
        extra.text([bold(*heading)]);
        extra.text([roman(*text)]);
    }

    String::from_utf8_lossy(&page).into_owned() + &extra.render()
}

/// The published exit numbers, in the order the contract tabulates them.
///
/// The sentence beside each one is written here, because explaining a number to
/// a reader is this file's job and that prose exists nowhere else in the build.
/// The NUMBER is not written here: it is carried by the variant and read back
/// through `code()`.
///
/// It used to be written, as the strings `"0"`, `"2"` … `"141"`, and the comment
/// in its place said that was deliberate. It conflated two things. The prose
/// does have to live here; the digits never did, and holding them as text meant
/// the manual could disagree with the enumeration that actually decides what the
/// process returns — a variant could be renumbered and this table would go on
/// publishing the old number with the whole suite green.
const EXIT_MEANINGS: &[(ExitNumber, &str)] = {
    // Named individually inside the block that uses them, so each row fits on
    // one line. The alternative was thirty-six lines of wrapping for fourteen
    // rows, which pushed this file past the ceiling `source_shape` enforces.
    use ExitNumber::{
        Absence, Authentication, BrokenPipe, Config, Conflict, Interrupted, Limit, Network,
        Permission, Server, Success, Timeout, Usage, Validation,
    };
    &[
        (Success, "Success."),
        (Usage, "Incorrect use of this tool."),
        (Validation, "Analysis refused the statement before sending."),
        (Config, "Configuration missing or invalid."),
        (Network, "The server could not be reached."),
        (Authentication, "The credential was refused."),
        (Permission, "The credential may not do what was asked."),
        (Absence, "The requested object does not exist."),
        (Conflict, "Lock conflict, deadlock or constraint."),
        (Limit, "A size, row or packet ceiling was reached."),
        (Server, "The server returned an error of its own."),
        (Timeout, "Some phase exceeded its time budget."),
        (Interrupted, "Interrupted by a signal from the caller."),
        (BrokenPipe, "The output channel was closed by the reader."),
    ]
};

/// What a reader has to know about this tool that no flag says on its own.
const MANUAL_NOTES: &[(&str, &str)] = &[
    (
        "Channels",
        "The primary channel carries data only, in the published shape. \
         Diagnostics, progress and warnings go to the auxiliary channel and \
         never mix with data.",
    ),
    (
        "One shot",
        "The process is born, does its work and dies within a single \
         invocation. There is no daemon, no connection reused across \
         invocations and no state that survives the process.",
    ),
    (
        "Defence against unintended change",
        "Statements travel as prepared statements, so the server refuses more \
         than one per call. Classification reads the syntax tree, never the \
         first word. A credential restricted on the server is the only defence \
         that does not depend on this tool behaving correctly.",
    ),
    (
        "Configuration",
        "Every setting is written and read through the config commands. No \
         setting is ever read from the process environment.",
    ),
    (
        "Encrypted channel",
        "The default build carries a cryptography provider written entirely in \
         Rust, so it installs on a host with no C toolchain. Run meta version \
         to see which provider this build carries and whether it is audited.",
    ),
    (
        "Cutting an answer down",
        "Two ceilings cut, and they cut different things. --truncate-cell \
         shortens one value; --max-output-bytes bounds the whole envelope. \
         There is deliberately no --truncate-content between them: it would \
         name no third thing to cut and would need an order against both. \
         Whatever a cut leaves out is reported under applied, so an answer that \
         was shortened never reads as a complete one.",
    ),
    (
        "Reading an input",
        "limits.max_input_bytes bounds what one invocation will read from a \
         file or the standard input, before any of it is judged. It is not \
         limits.max_statement_bytes, which bounds how large one statement may \
         be: a script of many small statements is legitimate and its total is \
         not a statement. Raising conn.max_packet_bytes without raising this \
         one leaves the higher packet ceiling unreachable through a file, \
         because the reading stops first.",
    ),
];

/// Completion support for one shell.
///
/// # Errors
///
/// Returns a usage failure when no shell was named. The argument layer lets the
/// shell be absent so that publishing the contract costs nothing, which makes
/// this the place the requirement is really enforced.
fn completions(shell: Option<crate::cli::meta::Shell>) -> Result<Envelope> {
    let Some(shell) = shell else {
        return Err(Failure::usage(
            "meta.shell_missing",
            "completion support is generated for a shell, and none was named",
        )
        .with_hint(
            "name one of bash, zsh, fish, elvish or powershell, \
             as in `meta completions bash`",
        ));
    };

    let mut root = Cli::command();
    let mut script = Vec::new();
    clap_complete::generate(
        clap_complete::Shell::from(shell),
        &mut root,
        env!("CARGO_PKG_NAME"),
        &mut script,
    );
    Ok(Envelope::new(
        "meta completions",
        json!({
            "shell": format!("{shell:?}").to_lowercase(),
            "script": String::from_utf8_lossy(&script),
        }),
    ))
}

#[cfg(test)]
mod tests {
    use super::*;

    fn rows_of(envelope: &Envelope) -> &Vec<Value> {
        envelope.data["rows"].as_array().expect("array payload")
    }

    #[test]
    fn the_tree_publishes_every_command_with_its_state() {
        let envelope = commands(false);
        let rows = rows_of(&envelope);
        assert!(rows.len() >= 59, "the whole tree must be published");
        for row in rows {
            let state = row["state"].as_str().expect("state present");
            assert!(
                matches!(state, "served" | "planned"),
                "unexpected state {state}"
            );
        }
    }

    #[test]
    fn the_tree_is_ordered_so_the_same_run_gives_the_same_bytes() {
        let first = serde_json::to_string(&commands(false)).expect("serialises");
        let second = serde_json::to_string(&commands(false)).expect("serialises");
        assert_eq!(first, second);
    }

    #[test]
    fn asking_a_contract_for_an_unknown_command_is_an_absence() {
        let failure = schema(Some("query nonexistent"), false).expect_err("must refuse");
        assert_eq!(failure.category(), crate::error::Category::Absence);
        assert_eq!(failure.exit_number().code(), 8);
    }

    #[test]
    fn a_published_command_always_has_a_contract() {
        let envelope = schema(Some("query run"), false).expect("published command");
        assert_eq!(envelope.data["command"], "query run");
    }

    #[test]
    fn the_type_map_covers_every_family_the_contract_names() {
        let envelope = schema(None, true).expect("type map");
        let published = crate::types::map::published();
        assert_eq!(rows_of(&envelope).len(), published.len());
        for (row, entry) in rows_of(&envelope).iter().zip(published) {
            assert_eq!(row["family"], entry.family.as_str());
            assert_eq!(row["emitted"], entry.shape.as_str());
        }
    }

    /// Holds the published tree and the list of served leaves to each other, so
    /// neither can gain or lose a command without the other being told.
    #[test]
    fn the_served_list_and_the_published_tree_name_the_same_commands() {
        let root = Cli::command();
        let mut rows = Vec::new();
        collect(&root, &mut Vec::new(), &mut rows);
        let published: Vec<&str> = rows
            .iter()
            .map(|row| row["name"].as_str().expect("name present"))
            .collect();

        for leaf in published {
            let times = super::super::SERVED_LEAVES
                .iter()
                .filter(|served| **served == leaf)
                .count();
            assert_eq!(times, 1, "`{leaf}` must be listed exactly once");
        }
        for served in super::super::SERVED_LEAVES {
            assert!(
                rows.iter().any(|row| row["name"] == served),
                "`{served}` is listed but not published"
            );
        }
    }

    /// The manual has to describe the surface this build really carries, so it
    /// is generated from the tree rather than written a second time by hand.
    #[test]
    fn the_manual_describes_the_surface_this_build_carries() {
        let envelope = manual();
        // The page source escapes the characters roff would otherwise read as
        // its own, so the comparison is made over the text a reader sees.
        let page = envelope.data["page"]
            .as_str()
            .expect("a page is carried")
            .replace('\\', "");

        assert_eq!(envelope.data["format"], "roff");
        assert!(
            page.contains(env!("CARGO_PKG_NAME")),
            "the product names itself"
        );
        for leaf in super::super::SERVED_LEAVES {
            assert!(page.contains(leaf), "`{leaf}` is missing from the manual");
        }
        for (number, _) in EXIT_MEANINGS {
            let published = number.code().to_string();
            assert!(
                page.contains(&published),
                "exit number {published} is missing"
            );
        }
    }

    /// Every number the product can return is a number the manual explains.
    ///
    /// The test above walks the table and asks whether the page shows each
    /// entry. That guards the table against the page. Nothing guarded the table
    /// against the PRODUCT: a category could be added, start ending processes
    /// with a number of its own, and never appear here, because the only list
    /// being walked was this file's own.
    ///
    /// So the walk starts from `Category::ALL`, which is the set the product
    /// actually maps outcomes onto, and demands the table already explain each
    /// one. `Success` is added separately because no failing category maps to
    /// it — it is the number an invocation returns by not failing at all.
    #[test]
    fn every_exit_number_the_product_can_return_is_explained() {
        let explained: Vec<u8> = EXIT_MEANINGS
            .iter()
            .map(|(number, _)| number.code())
            .collect();

        assert!(
            explained.contains(&ExitNumber::Success.code()),
            "the manual does not explain the number a successful invocation returns"
        );

        for category in crate::error::Category::ALL {
            let number = category.exit_number().code();
            assert!(
                explained.contains(&number),
                "`{category:?}` ends a process with {number} and the manual \
                 explains no such number, so a reader meeting it has nowhere to \
                 look it up"
            );
        }
    }

    /// The page is a manual page and not a list of sentences, so a reader
    /// already equipped to read one can read this without a new tool.
    #[test]
    fn the_manual_carries_the_sections_a_manual_page_has() {
        let page = manual().data["page"]
            .as_str()
            .expect("a page is carried")
            .to_owned();

        for section in [".TH", "SYNOPSIS", "COMMANDS", "EXIT NUMBERS", "NOTES"] {
            assert!(
                page.contains(section),
                "`{section}` is missing from the page"
            );
        }
    }

    /// Publishing the contract must cost nothing, so the shell is optional to
    /// the argument layer. That moves the requirement here, where asking for
    /// completion support without saying for which shell has to be refused with
    /// a code and shown the shells this build writes support for.
    #[test]
    fn completion_support_without_a_shell_is_refused_with_a_code() {
        let failure = completions(None).expect_err("must refuse");

        assert_eq!(failure.code(), "meta.shell_missing");
        assert_eq!(failure.exit_number().code(), 2);
        assert!(failure.hint().is_some_and(|hint| hint.contains("bash")));
    }

    /// A command carrying actions of its own is published under each action and
    /// never under the group, so asking for the contract of the group has to
    /// answer for the group instead of reading it as a command that does not
    /// exist.
    #[test]
    fn a_command_that_carries_actions_answers_for_the_group() {
        let envelope = schema(Some("query named"), false).expect("a group is not an absence");

        assert_eq!(envelope.data["command"], "query named");
        let actions = envelope.data["actions"]
            .as_array()
            .expect("the actions travel with the answer");
        assert!(
            actions.iter().any(|action| action == "query named list"),
            "the actions are read from the published tree: {actions:?}"
        );
        assert!(envelope.data["envelope"]["command"].is_string());
    }

    #[test]
    fn the_build_reports_its_own_encryption_capability() {
        let envelope = version();
        assert_eq!(
            envelope.data["encrypted_channel_available"],
            crate::ENCRYPTED_CHANNEL_AVAILABLE
        );
    }

    /// A build that carries encryption must name the cryptography behind it.
    /// Reporting the capability without the provider would let two binaries
    /// with very different trust look identical from the outside.
    #[test]
    fn the_build_names_the_cryptography_it_carries() {
        let envelope = version();
        let named = envelope.data["crypto_provider"]
            .as_str()
            .expect("the provider is always named");

        assert_eq!(named == "none", !crate::ENCRYPTED_CHANNEL_AVAILABLE);
        assert_eq!(
            envelope.data["crypto_provider_audited"],
            crate::conn::provider::PROVIDER_IS_AUDITED
        );
    }
}