aprender-common 0.72.3

Shared utilities for the Batuta stack: formatting, system info, display helpers
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
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
//! Typed CLI argument roles (#3745 S1, PMAT-3749).
//!
//! A release cell can only be derived for an argument whose ROLE the gate can
//! see. Before these types, the role of an `apr` argument was knowable only
//! from its name: `apr run SOURCE`, `--prompt` and `-i FILE` were a `String`, a
//! `String` and a `PathBuf`, the same types as `--name`, `--tag` and
//! `--output`. Every release list was therefore typed by hand, and a verb, flag
//! or input shape missing from that list was invisible to the gate. That is how
//! `apr run --prompt P --chat` shipped double-templated (#3743) while
//! `-i file --chat` was covered.
//!
//! Each type here is a transparent newtype over `PathBuf` or `String` whose clap
//! value parser is the SAME parser clap uses for the raw type
//! (`PathBufValueParser` / `StringValueParser`), mapped into the newtype. So a
//! migrated argument accepts exactly the values it accepted before. The only
//! thing that changes is the parser's output TYPE, and that is what `apr surface`
//! reads, through `ValueParser::type_id()`, to decide the role. The role is
//! declared by how the argument is BUILT; its name never enters into it.
//!
//! The types live here rather than in `apr-cli` because a marker compared by
//! `TypeId` needs ONE defining crate, and some of `apr`'s surface is declared by
//! crates that do not depend on `apr-cli` (`apr pv …` from
//! `aprender-contracts-cli`, `apr rag …` from `aprender-rag-cli`).

use std::any::TypeId;
use std::ffi::OsStr;
use std::fmt;
use std::ops::Deref;
use std::path::{Path, PathBuf};

use clap::builder::{MapValueParser, PathBufValueParser, StringValueParser, TypedValueParser};

/// The role an argument plays in a release cell (#3745).
///
/// `Mode` and `Backend` are not listed in [`MARKERS`]. Mode is structural (a
/// flag action, or a finite value set), and backend is membership in the shared
/// `BackendArg` group; `apr surface` decides both.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Role {
    /// A model: a local file, or a reference `apr` resolves to one.
    Model,
    /// Text the model is prompted with.
    Prompt,
    /// A file the command consumes as input data (audio, text, a dataset).
    InputFile,
    /// The compute backend override.
    Backend,
    /// A generation sampling control: seed, temperature, top-k, top-p,
    /// repeat penalty (S1 v1.1, for S2.5's flag-effect sampling controls).
    Sampling,
    /// A flag, or a value drawn from a finite set.
    Mode,
    /// Declared, and none of the above: outputs, directories, configs, names.
    Other,
    /// A free-form value no role type declares. Only a foreign subtree may
    /// carry one; the marker guard is RED on it anywhere else.
    Unknown,
}

impl Role {
    /// The spelling used in the `apr-cli-surface` JSON.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Model => "model",
            Self::Prompt => "prompt",
            Self::InputFile => "input-file",
            Self::Backend => "backend",
            Self::Sampling => "sampling",
            Self::Mode => "mode",
            Self::Other => "other",
            Self::Unknown => "unknown",
        }
    }
}

/// What a marker's underlying value is: a filesystem path, or free text.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Carrier {
    /// Backed by `PathBuf`.
    Path,
    /// Backed by `String`.
    Text,
}

/// One role type: the `TypeId` its value parser yields, and what it declares.
#[derive(Debug, Clone, Copy)]
pub struct Marker {
    /// The type's name as written in code, e.g. `ModelPath`.
    pub name: &'static str,
    /// The role this type declares.
    pub role: Role,
    /// Path- or text-backed.
    pub carrier: Carrier,
    type_id: fn() -> TypeId,
}

impl Marker {
    /// The `TypeId` of the marker type, which is the `TypeId` its clap value
    /// parser reports.
    #[must_use]
    pub fn type_id(&self) -> TypeId {
        (self.type_id)()
    }
}

macro_rules! path_role {
    ($(#[$doc:meta])* $name:ident) => {
        $(#[$doc])*
        #[derive(Clone, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
        pub struct $name(PathBuf);

        // `Debug` is the inner value's, so `{:?}` of a migrated field prints
        // `"m.gguf"` exactly as the raw `PathBuf` did, never `ModelPath("m.gguf")`.
        impl fmt::Debug for $name {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                fmt::Debug::fmt(&self.0, f)
            }
        }

        impl $name {
            /// Wrap a path.
            #[must_use]
            pub fn new(path: impl Into<PathBuf>) -> Self {
                Self(path.into())
            }
            /// The path, borrowed.
            #[must_use]
            pub fn as_path(&self) -> &Path {
                &self.0
            }
            /// The path, owned.
            #[must_use]
            pub fn into_path_buf(self) -> PathBuf {
                self.0
            }
        }

        // `Path`, not `PathBuf`: the same target `PathBuf` derefs to, so
        // `Option<ModelPath>::as_deref()` is `Option<&Path>` exactly as
        // `Option<PathBuf>::as_deref()` was, and a migrated field reads the same.
        impl Deref for $name {
            type Target = Path;
            fn deref(&self) -> &Path {
                &self.0
            }
        }
        impl AsRef<Path> for $name {
            fn as_ref(&self) -> &Path {
                &self.0
            }
        }
        impl AsRef<OsStr> for $name {
            fn as_ref(&self) -> &OsStr {
                self.0.as_os_str()
            }
        }
        impl From<PathBuf> for $name {
            fn from(p: PathBuf) -> Self {
                Self(p)
            }
        }
        impl From<&Path> for $name {
            fn from(p: &Path) -> Self {
                Self(p.to_path_buf())
            }
        }
        impl From<&str> for $name {
            fn from(p: &str) -> Self {
                Self(PathBuf::from(p))
            }
        }
        impl From<String> for $name {
            fn from(p: String) -> Self {
                Self(PathBuf::from(p))
            }
        }
        impl From<$name> for PathBuf {
            fn from(p: $name) -> PathBuf {
                p.0
            }
        }
        impl PartialEq<PathBuf> for $name {
            fn eq(&self, other: &PathBuf) -> bool {
                &self.0 == other
            }
        }
        impl PartialEq<Path> for $name {
            fn eq(&self, other: &Path) -> bool {
                self.0 == other
            }
        }
        impl clap::builder::ValueParserFactory for $name {
            type Parser = MapValueParser<PathBufValueParser, fn(PathBuf) -> $name>;
            fn value_parser() -> Self::Parser {
                PathBufValueParser::new().map($name as fn(PathBuf) -> $name)
            }
        }
    };
}

macro_rules! text_role {
    ($(#[$doc:meta])* $name:ident) => {
        $(#[$doc])*
        #[derive(Clone, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
        pub struct $name(String);

        // `Debug` is the inner value's: `{:?}` prints `"text"`, as `String` did.
        impl fmt::Debug for $name {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                fmt::Debug::fmt(&self.0, f)
            }
        }

        impl $name {
            /// Wrap a string.
            #[must_use]
            pub fn new(s: impl Into<String>) -> Self {
                Self(s.into())
            }
            /// The text, borrowed.
            #[must_use]
            pub fn as_str(&self) -> &str {
                &self.0
            }
            /// The text as a `&String`, for callees that take one.
            #[must_use]
            pub fn as_string(&self) -> &String {
                &self.0
            }
            /// The text, owned.
            #[must_use]
            pub fn into_string(self) -> String {
                self.0
            }
        }

        // `str`, not `String`: the same target `String` derefs to, so
        // `Option<PromptText>::as_deref()` is `Option<&str>` exactly as
        // `Option<String>::as_deref()` was.
        impl Deref for $name {
            type Target = str;
            fn deref(&self) -> &str {
                &self.0
            }
        }
        impl AsRef<str> for $name {
            fn as_ref(&self) -> &str {
                &self.0
            }
        }
        impl AsRef<Path> for $name {
            fn as_ref(&self) -> &Path {
                Path::new(&self.0)
            }
        }
        impl AsRef<OsStr> for $name {
            fn as_ref(&self) -> &OsStr {
                OsStr::new(&self.0)
            }
        }
        impl fmt::Display for $name {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str(&self.0)
            }
        }
        impl From<String> for $name {
            fn from(s: String) -> Self {
                Self(s)
            }
        }
        impl From<&str> for $name {
            fn from(s: &str) -> Self {
                Self(s.to_string())
            }
        }
        impl From<$name> for String {
            fn from(s: $name) -> String {
                s.0
            }
        }
        impl PartialEq<str> for $name {
            fn eq(&self, other: &str) -> bool {
                self.0 == other
            }
        }
        impl PartialEq<&str> for $name {
            fn eq(&self, other: &&str) -> bool {
                self.0 == *other
            }
        }
        impl PartialEq<String> for $name {
            fn eq(&self, other: &String) -> bool {
                &self.0 == other
            }
        }
        impl clap::builder::ValueParserFactory for $name {
            type Parser = MapValueParser<StringValueParser, fn(String) -> $name>;
            fn value_parser() -> Self::Parser {
                StringValueParser::new().map($name as fn(String) -> $name)
            }
        }
    };
}

path_role!(
    /// A local model file (`.apr`, `.gguf`, `.safetensors`, …).
    ModelPath
);
path_role!(
    /// A file the command reads as input data, not as a model.
    InputFile
);
path_role!(
    /// A file the command writes.
    OutputPath
);
path_role!(
    /// A directory: a workspace, a cache, a corpus root, an output tree.
    DirPath
);
path_role!(
    /// A configuration, manifest, contract, schema or receipt the command
    /// reads to decide what to do, as distinct from the data it operates on.
    ConfigPath
);
text_role!(
    /// A model reference: a local path, `hf://org/repo`, a URL, or a cache
    /// name, which `apr` resolves to a model file.
    ModelRef
);
text_role!(
    /// Text the model is prompted with.
    PromptText
);
text_role!(
    /// Any other free text: a name, id, tag, URL, pattern or list.
    FreeText
);
text_role!(
    /// Text a model ENCODES or SCORES rather than generates from: `apr embed
    /// --text`, `apr rerank --query/--passage`, `apr eval --text` (perplexity).
    /// Role `other`, so the command does not read as a generator: `generates`
    /// drives the thinking × context-rung cells, which mean nothing for an
    /// encoder or a scorer (aprender-97 on #3745, v1.1).
    EncodeText
);

/// Command-level marker: this command GENERATES text from prompts that do not
/// arrive through a `PromptText` argument (#3745 S1, schema v1.1).
///
/// `apr serve run` takes its prompts over HTTP, `apr chat` reads them from
/// stdin, and `apr mcp` receives them as JSON-RPC tool calls. None of them has a
/// prompt ARGUMENT, so a rule that reads "generates" off the prompt role alone
/// would derive no prompt-shape cells for the very verb whose 0.69.0 leak
/// (#3571) started this. The marker is attached to the subcommand itself, with
/// no argument and no field:
///
/// ```ignore
/// #[command(group(batuta_common::cli_roles::ServesGeneration::group()))]
/// Run { /* … */ },
/// ```
///
/// `apr surface` reports `generates: true` for a command that has a
/// `PromptText` argument OR carries this group, and it matches the group by
/// [`ServesGeneration::ID`], never by the command's name.
#[derive(Debug, Clone, Copy)]
pub struct ServesGeneration;

impl ServesGeneration {
    /// The group id the marker is recognised by.
    pub const ID: &'static str = "batuta_common::cli_roles::ServesGeneration";

    /// The argument-less group that marks a command as a generator. It names
    /// no argument, so it changes neither parsing nor `--help`.
    #[must_use]
    pub fn group() -> clap::ArgGroup {
        clap::ArgGroup::new(Self::ID).multiple(true)
    }

    /// True iff `cmd` carries the marker.
    #[must_use]
    pub fn is_on(cmd: &clap::Command) -> bool {
        cmd.get_groups().any(|g| g.get_id() == Self::ID)
    }
}

/// Which generation sampling control an argument is (#3745 S1, v1.1). S2
/// derives its sampling cells per kind (sampled ≠ greedy, same seed twice is
/// byte-identical, seed A ≠ seed B, top-k 1 / T 0 is byte-greedy), so the kind
/// is declared, not read off the argument's name.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum SamplingKind {
    /// RNG seed of the sampler.
    Seed,
    /// Softmax temperature.
    Temperature,
    /// Top-k cut-off.
    TopK,
    /// Nucleus (top-p) threshold.
    TopP,
    /// Min-p threshold.
    MinP,
    /// Repetition penalty.
    RepeatPenalty,
    /// Window the repetition penalty looks back over.
    RepeatLastN,
}

impl SamplingKind {
    /// Every kind.
    pub const ALL: [SamplingKind; 7] = [
        Self::Seed,
        Self::Temperature,
        Self::TopK,
        Self::TopP,
        Self::MinP,
        Self::RepeatPenalty,
        Self::RepeatLastN,
    ];

    /// The spelling used in the `apr-cli-surface` JSON (`sampling_kind`).
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Seed => "seed",
            Self::Temperature => "temperature",
            Self::TopK => "top_k",
            Self::TopP => "top_p",
            Self::MinP => "min_p",
            Self::RepeatPenalty => "repeat_penalty",
            Self::RepeatLastN => "repeat_last_n",
        }
    }

    /// The group id an argument of this kind joins: `#[arg(group = SamplingKind::Temperature.id())]`.
    #[must_use]
    pub const fn id(self) -> &'static str {
        match self {
            Self::Seed => "batuta_common::cli_roles::SamplingArg::seed",
            Self::Temperature => "batuta_common::cli_roles::SamplingArg::temperature",
            Self::TopK => "batuta_common::cli_roles::SamplingArg::top_k",
            Self::TopP => "batuta_common::cli_roles::SamplingArg::top_p",
            Self::MinP => "batuta_common::cli_roles::SamplingArg::min_p",
            Self::RepeatPenalty => "batuta_common::cli_roles::SamplingArg::repeat_penalty",
            Self::RepeatLastN => "batuta_common::cli_roles::SamplingArg::repeat_last_n",
        }
    }
}

/// Argument-level marker for a generation SAMPLING control (#3745 S1, v1.1).
///
/// These are numbers, so a newtype would change every field's type and every
/// call site that reads it. Instead the argument joins the argument-less group
/// of its [`SamplingKind`], and the command declares those groups once, each
/// `multiple(true)`, so nothing about parsing changes:
///
/// ```ignore
/// #[command(groups(batuta_common::cli_roles::SamplingArg::groups()))]
/// Run {
///     #[arg(long, default_value = "0.0",
///           group = batuta_common::cli_roles::SamplingKind::Temperature.id())]
///     temperature: f32,
/// }
/// ```
///
/// `apr surface` reports role `sampling` and `sampling_kind` for a member of
/// one of these groups, matched by id, never by the argument's name.
#[derive(Debug, Clone, Copy)]
pub struct SamplingArg;

impl SamplingArg {
    /// One argument-less `multiple(true)` group per [`SamplingKind`], for
    /// `#[command(groups(SamplingArg::groups()))]`.
    #[must_use]
    pub fn groups() -> Vec<clap::ArgGroup> {
        SamplingKind::ALL
            .iter()
            .map(|k| clap::ArgGroup::new(k.id()).multiple(true))
            .collect()
    }

    /// The sampling kind of `arg` on `built`, if it has one. `built` must be a
    /// BUILT command: clap merges each argument's `group = …` into the
    /// command's groups only when the command is built.
    #[must_use]
    pub fn kind_of(built: &clap::Command, arg: &clap::Arg) -> Option<SamplingKind> {
        SamplingKind::ALL.into_iter().find(|k| {
            built
                .get_groups()
                .any(|g| g.get_id() == k.id() && g.get_args().any(|a| a == arg.get_id()))
        })
    }
}

/// Owned `String`s from a slice of text role values, for callees that take
/// `&[String]`.
#[must_use]
pub fn strings<T: AsRef<str>>(values: &[T]) -> Vec<String> {
    values.iter().map(|v| v.as_ref().to_string()).collect()
}

/// Owned `PathBuf`s from a slice of path role values, for callees that take
/// `&[PathBuf]`.
#[must_use]
pub fn path_bufs<T: AsRef<Path>>(values: &[T]) -> Vec<PathBuf> {
    values.iter().map(|v| v.as_ref().to_path_buf()).collect()
}

/// Every role type, in one table. `apr surface` reads roles through it, and the
/// marker guard refuses a free-form argument whose parser yields none of these.
pub const MARKERS: &[Marker] = &[
    Marker {
        name: "ModelPath",
        role: Role::Model,
        carrier: Carrier::Path,
        type_id: TypeId::of::<ModelPath>,
    },
    Marker {
        name: "ModelRef",
        role: Role::Model,
        carrier: Carrier::Text,
        type_id: TypeId::of::<ModelRef>,
    },
    Marker {
        name: "PromptText",
        role: Role::Prompt,
        carrier: Carrier::Text,
        type_id: TypeId::of::<PromptText>,
    },
    Marker {
        name: "InputFile",
        role: Role::InputFile,
        carrier: Carrier::Path,
        type_id: TypeId::of::<InputFile>,
    },
    Marker {
        name: "OutputPath",
        role: Role::Other,
        carrier: Carrier::Path,
        type_id: TypeId::of::<OutputPath>,
    },
    Marker {
        name: "DirPath",
        role: Role::Other,
        carrier: Carrier::Path,
        type_id: TypeId::of::<DirPath>,
    },
    Marker {
        name: "ConfigPath",
        role: Role::Other,
        carrier: Carrier::Path,
        type_id: TypeId::of::<ConfigPath>,
    },
    Marker {
        name: "FreeText",
        role: Role::Other,
        carrier: Carrier::Text,
        type_id: TypeId::of::<FreeText>,
    },
    Marker {
        name: "EncodeText",
        role: Role::Other,
        carrier: Carrier::Text,
        type_id: TypeId::of::<EncodeText>,
    },
];

/// The marker whose type a value parser yields, if any.
#[must_use]
pub fn marker_for(type_id: TypeId) -> Option<&'static Marker> {
    MARKERS.iter().find(|m| m.type_id() == type_id)
}

#[cfg(test)]
mod tests {
    use super::*;
    use clap::{Arg, Command};

    fn parser_type<T: clap::builder::ValueParserFactory>() -> TypeId
    where
        T::Parser: TypedValueParser + Send + Sync + 'static,
        <T::Parser as TypedValueParser>::Value: Send + Sync + Clone + 'static,
    {
        let vp: clap::builder::ValueParser = T::value_parser().into();
        let arg = Arg::new("x").value_parser(vp);
        // `AnyValueId` is clap's; it compares equal to a std `TypeId`.
        let id = arg.get_value_parser().type_id();
        MARKERS
            .iter()
            .map(Marker::type_id)
            .chain([TypeId::of::<PathBuf>(), TypeId::of::<String>()])
            .find(|t| id == *t)
            .expect("value parser yields a known type")
    }

    #[test]
    fn every_marker_parser_reports_its_own_type_id() {
        assert_eq!(parser_type::<ModelPath>(), TypeId::of::<ModelPath>());
        assert_eq!(parser_type::<ModelRef>(), TypeId::of::<ModelRef>());
        assert_eq!(parser_type::<PromptText>(), TypeId::of::<PromptText>());
        assert_eq!(parser_type::<InputFile>(), TypeId::of::<InputFile>());
        assert_eq!(parser_type::<OutputPath>(), TypeId::of::<OutputPath>());
        assert_eq!(parser_type::<DirPath>(), TypeId::of::<DirPath>());
        assert_eq!(parser_type::<ConfigPath>(), TypeId::of::<ConfigPath>());
        assert_eq!(parser_type::<FreeText>(), TypeId::of::<FreeText>());
        assert_eq!(parser_type::<EncodeText>(), TypeId::of::<EncodeText>());
    }

    #[test]
    fn marker_table_is_one_to_one_with_types() {
        let mut ids: Vec<TypeId> = MARKERS.iter().map(Marker::type_id).collect();
        ids.sort();
        ids.dedup();
        assert_eq!(ids.len(), MARKERS.len(), "two markers share a TypeId");
        assert!(
            marker_for(TypeId::of::<PathBuf>()).is_none(),
            "raw PathBuf must not be a marker"
        );
        assert!(
            marker_for(TypeId::of::<String>()).is_none(),
            "raw String must not be a marker"
        );
        assert_eq!(
            marker_for(TypeId::of::<ModelPath>()).map(|m| m.role),
            Some(Role::Model)
        );
        assert_eq!(
            marker_for(TypeId::of::<PromptText>()).map(|m| m.role),
            Some(Role::Prompt)
        );
    }

    /// A migrated argument must accept exactly what the raw type accepted: the
    /// marker parser is the raw parser, mapped. An empty path is refused by
    /// both, a normal value is accepted by both.
    #[test]
    fn marker_parsers_accept_what_the_raw_parsers_accept() {
        let raw = Command::new("t").arg(Arg::new("p").value_parser(clap::value_parser!(PathBuf)));
        let typed =
            Command::new("t").arg(Arg::new("p").value_parser(clap::value_parser!(ModelPath)));
        for argv in [vec!["t", "m.gguf"], vec!["t", ""], vec!["t", "-"]] {
            let a = raw.clone().try_get_matches_from(&argv).is_ok();
            let b = typed.clone().try_get_matches_from(&argv).is_ok();
            assert_eq!(a, b, "PathBuf vs ModelPath disagree on {argv:?}");
        }
        let m = typed.try_get_matches_from(["t", "m.gguf"]).expect("parses");
        assert_eq!(
            m.get_one::<ModelPath>("p").map(ModelPath::as_path),
            Some(Path::new("m.gguf"))
        );

        let raw = Command::new("t").arg(Arg::new("s").value_parser(clap::value_parser!(String)));
        let typed =
            Command::new("t").arg(Arg::new("s").value_parser(clap::value_parser!(PromptText)));
        for argv in [vec!["t", "What is 2+2?"], vec!["t", ""]] {
            let a = raw.clone().try_get_matches_from(&argv).is_ok();
            let b = typed.clone().try_get_matches_from(&argv).is_ok();
            assert_eq!(a, b, "String vs PromptText disagree on {argv:?}");
        }
    }

    /// The generation marker names no argument, so it changes neither what
    /// parses nor what `--help` prints, and it is found by id alone.
    #[test]
    fn serves_generation_marks_a_command_without_changing_it() {
        let plain = Command::new("t").arg(Arg::new("port").long("port"));
        let marked = plain.clone().group(ServesGeneration::group());
        assert!(!ServesGeneration::is_on(&plain));
        assert!(ServesGeneration::is_on(&marked));
        for argv in [vec!["t"], vec!["t", "--port", "8080"], vec!["t", "--nope"]] {
            let a = plain.clone().try_get_matches_from(&argv).is_ok();
            let b = marked.clone().try_get_matches_from(&argv).is_ok();
            assert_eq!(a, b, "the marker changed parsing of {argv:?}");
        }
        let help = |c: &Command| c.clone().render_long_help().to_string();
        assert_eq!(help(&plain), help(&marked), "the marker changed --help");
        // A look-alike group spelled with the type's short name is not the marker.
        let lookalike = plain.group(clap::ArgGroup::new("ServesGeneration").multiple(true));
        assert!(!ServesGeneration::is_on(&lookalike));
    }

    /// A migrated field must print the same under `{:?}` as the raw type did:
    /// error messages and tests format arguments that way.
    #[test]
    fn debug_output_is_the_raw_types() {
        assert_eq!(
            format!("{:?}", ModelPath::from("m.gguf")),
            format!("{:?}", PathBuf::from("m.gguf"))
        );
        assert_eq!(
            format!("{:?}", Some(OutputPath::from("o"))),
            format!("{:?}", Some(PathBuf::from("o")))
        );
        assert_eq!(
            format!("{:?}", PromptText::from("hi")),
            format!("{:?}", String::from("hi"))
        );
        assert_eq!(
            format!("{:?}", vec![FreeText::from("a")]),
            format!("{:?}", vec![String::from("a")])
        );
    }

    #[test]
    fn derive_picks_the_marker_parser_for_a_marker_field() {
        #[derive(clap::Parser)]
        struct T {
            model: ModelPath,
            #[arg(long)]
            prompt: Option<PromptText>,
            #[arg(long)]
            inputs: Vec<InputFile>,
        }
        use clap::{CommandFactory, Parser};
        let cmd = T::command();
        let id = |name: &str| {
            cmd.get_arguments()
                .find(|a| a.get_id() == name)
                .map(|a| a.get_value_parser().type_id())
                .expect("arg exists")
        };
        assert!(id("model") == TypeId::of::<ModelPath>());
        assert!(id("prompt") == TypeId::of::<PromptText>());
        assert!(id("inputs") == TypeId::of::<InputFile>());
        let t = T::try_parse_from(["t", "a.apr", "--prompt", "hi", "--inputs", "x.wav"])
            .expect("parses");
        assert_eq!(t.model.as_path(), Path::new("a.apr"));
        assert_eq!(t.prompt.as_deref(), Some("hi"));
        assert_eq!(t.inputs.len(), 1);
    }

    /// The spellings are the `apr-cli-surface` JSON contract: a renamed or
    /// blank spelling silently changes what `apr surface` reports.
    #[test]
    fn role_and_sampling_spellings_are_the_json_contract() {
        let roles = [
            (Role::Model, "model"),
            (Role::Prompt, "prompt"),
            (Role::InputFile, "input-file"),
            (Role::Backend, "backend"),
            (Role::Sampling, "sampling"),
            (Role::Mode, "mode"),
            (Role::Other, "other"),
            (Role::Unknown, "unknown"),
        ];
        for (role, s) in roles {
            assert_eq!(role.as_str(), s);
        }
        let kinds = [
            "seed",
            "temperature",
            "top_k",
            "top_p",
            "min_p",
            "repeat_penalty",
            "repeat_last_n",
        ];
        for (k, s) in SamplingKind::ALL.iter().zip(kinds) {
            assert_eq!(k.as_str(), s);
            assert_eq!(
                k.id(),
                format!("batuta_common::cli_roles::SamplingArg::{s}")
            );
        }
    }

    /// One `multiple(true)` group per kind, each named by that kind's id.
    #[test]
    fn sampling_groups_are_one_per_kind() {
        let groups = SamplingArg::groups();
        let ids: Vec<&str> = groups.iter().map(|g| g.get_id().as_str()).collect();
        let want: Vec<&str> = SamplingKind::ALL.iter().map(|k| k.id()).collect();
        assert_eq!(ids, want);
        assert!(groups.into_iter().all(|mut g| g.is_multiple()));
    }

    /// `kind_of` finds each argument's own kind, and none for an argument
    /// outside every sampling group, even when the groups are declared.
    #[test]
    fn kind_of_reads_the_group_an_argument_joined() {
        let mut cmd = Command::new("t").groups(SamplingArg::groups());
        for k in SamplingKind::ALL {
            cmd = cmd.arg(Arg::new(k.as_str()).long(k.as_str()).group(k.id()));
        }
        cmd = cmd.arg(Arg::new("port").long("port"));
        cmd.build();
        for k in SamplingKind::ALL {
            let arg = cmd
                .get_arguments()
                .find(|a| a.get_id() == k.as_str())
                .expect("arg exists");
            assert_eq!(SamplingArg::kind_of(&cmd, arg), Some(k), "{k:?}");
        }
        let port = cmd
            .get_arguments()
            .find(|a| a.get_id() == "port")
            .expect("arg exists");
        assert_eq!(SamplingArg::kind_of(&cmd, port), None);
    }

    #[test]
    fn strings_and_path_bufs_keep_every_value_in_order() {
        let texts = [FreeText::from("a"), FreeText::from("b")];
        assert_eq!(strings(&texts), vec!["a".to_string(), "b".to_string()]);
        assert!(strings::<FreeText>(&[]).is_empty());
        let paths = [InputFile::from("x.wav"), InputFile::from("y.wav")];
        assert_eq!(
            path_bufs(&paths),
            vec![PathBuf::from("x.wav"), PathBuf::from("y.wav")]
        );
    }
}