dsp-cli 0.1.1

AI-agent-friendly command-line interface for the DaSCH Service Platform (DSP)
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
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
//! CLI parsing — layer 1 of ADR-0008.
//!
//! Produces typed argument structs from `argv`. The structs flow through the
//! action layer; no business logic lives here.

use clap::{Args, Parser, Subcommand};

use crate::diagnostic::Diagnostic;
use crate::render::{Format, HeaderMode, TableOptions};

// ── after_help column-doc strings ─────────────────────────────────────────────
//
// Each tabular leaf command carries a static `after_help` line that documents
// its column set.  These literals are derived from the per-noun column-set
// consts in `crate::render` (step 5, D9).  They are intentionally NOT built
// at runtime from the consts — clap requires `&'static str`.  A drift-guard
// unit test (`test_after_help_matches_consts`) asserts that each literal's
// column list exactly matches the joined `crate::render` const, so adding a
// column without updating the literal fails CI.

const AFTER_HELP_PROJECT_LIST: &str =
    "Columns (--columns): shortcode, shortname, longname, status, data_models, iri";

const AFTER_HELP_PROJECT_DESCRIBE: &str =
    "Columns (--columns): shortcode, shortname, longname, status, data_models, iri";

const AFTER_HELP_PROJECT_DUMP: &str = "Columns (--columns): path  (--delete mode: deleted)";

const AFTER_HELP_DATA_MODEL_LIST: &str =
    "Columns (--columns): name, iri, label, last_modified, is_builtin";

const AFTER_HELP_DATA_MODEL_DESCRIBE: &str =
    "Columns (--columns): name, iri, label, last_modified, resource_types";

const AFTER_HELP_DATA_MODEL_STRUCTURE: &str =
    "Columns (--columns): source, target, kind, field, target_data_model";

const AFTER_HELP_RESOURCE_TYPE_LIST: &str = "Columns (--columns): name, iri, label, is_builtin";

/// Full 8-column set for `resource-type describe` (one row per field).
/// `iri` is accessible via `--columns iri` (hidden from the default csv/tsv
/// output by the lean-default mechanism, but present in `all_columns`).
const AFTER_HELP_RESOURCE_TYPE_DESCRIBE: &str = "Columns (--columns): name, iri, value_type, link_target, cardinality, label, is_builtin, data_model";

const AFTER_HELP_RESOURCE_LIST: &str = "Columns (--columns): label, iri, ark_url, creation_date, last_modified, resource_type\n\n\
     Scan behaviour: a bare --resource-type name (no ://) scans all project data-models; \
     use --data-model or a full IRI to skip the scan. See also: `dsp docs concepts`\n\n\
     --order-by: field name (e.g. title) or full field IRI; sorts ascending; \
     targets project-defined fields (full IRI passed verbatim; bare name resolved to its field IRI)";

const AFTER_HELP_RESOURCE_DESCRIBE: &str = "Columns (--columns): label, iri, resource_type, ark_url, creation_date, last_modified, attached_project, owner, visibility, your_access\n\
     Columns (--columns) with --values: label, iri, field, field_label, value_type, value, comment\n\
     Default columns with --values: field, field_label, value_type, value\n\n\
     See also: `dsp docs concepts`";

const AFTER_HELP_AUTH_LOGIN: &str = "Columns (--columns): server, user, expires_at, state";

const AFTER_HELP_AUTH_STATUS: &str = "Columns (--columns): server, user, expires_at, state";

const AFTER_HELP_AUTH_LOGOUT: &str = "Columns (--columns): server, was_cached";

const AFTER_HELP_AUTH_SET_TOKEN: &str = "Columns (--columns): server, user, expires_at, state";

// ── output format ─────────────────────────────────────────────────────────────

/// Output format selection for vre data commands.
///
/// Flattened into each of the six vre leaf Args structs. Provides `--format`,
/// `-j`/`--json`, and `-l`/`--lines` as parallel selection paths.
///
/// Precedence (resolved by [`FormatArgs::resolve`]): `-j` > `-l` > `--format`.
/// No `conflicts_with` is used — clap treats `default_value_t` as "implicitly
/// set", which would make valid calls like `dsp vre project list -j` collide
/// with the prose default. The helper-method precedence is simpler and correct.
///
/// See [ADR-0003](../../docs/adr/0003-chaining-and-output.md) for the output
/// format specification and the design-decisions section of the 003 plan for
/// why this is per-leaf rather than global.
#[derive(Debug, Args)]
pub struct FormatArgs {
    /// Output format (default: prose).
    #[arg(
        long,
        value_enum,
        default_value_t = Format::Prose,
        value_name = "FORMAT"
    )]
    pub format: Format,

    /// Shortcut for --format=json.
    #[arg(short = 'j', long = "json")]
    pub json: bool,

    /// Shortcut for --format=lines.
    #[arg(short = 'l', long = "lines")]
    pub lines: bool,

    /// Output columns for tabular formats (csv, tsv, lines): comma-separated list
    /// that selects and reorders columns. Valid names are listed in the Columns
    /// line below. Duplicates are rejected.
    #[arg(long, value_name = "COLS")]
    pub columns: Option<String>,

    /// Omit the csv/tsv header row, e.g. appending rows to an existing file.
    #[arg(long, conflicts_with = "header_only")]
    pub no_header: bool,

    /// Emit only the csv/tsv header row, no data rows. Note: the command still
    /// contacts the server.
    #[arg(long)]
    pub header_only: bool,
}

impl FormatArgs {
    /// Resolve the effective format. Precedence: `-j` > `-l` > `--format`.
    pub fn resolve(&self) -> Format {
        if self.json {
            Format::Json
        } else if self.lines {
            Format::Lines
        } else {
            self.format
        }
    }

    /// Validate and resolve tabular options from the CLI flags.
    ///
    /// `format` must be the **resolved** format (call [`FormatArgs::resolve`]
    /// first — never pass `self.format`, which is always `Prose` when `-j`/`-l`
    /// are used).
    ///
    /// ## Validation rules
    ///
    /// - `--columns` is only valid with `csv`, `tsv`, or `lines` output.
    ///   Any other format → `Diagnostic::Usage`.
    /// - `--no-header` / `--header-only` are only valid with `csv` or `tsv`.
    ///   `lines` has no header concept. Any other format → `Diagnostic::Usage`.
    /// - `--columns` value: the string must be non-empty; each comma-separated
    ///   token must be non-blank (no `a,,b`); no duplicates allowed.
    ///   Unknown column names are validated later by the engine (which knows the
    ///   per-noun set).
    ///
    /// Returns a `TableOptions` whose `columns` field is guaranteed to be
    /// syntactically valid (non-empty `Some(Vec)` with no blank entries and no
    /// duplicates), or `None` if `--columns` was not supplied.
    pub fn table_options(&self, format: Format) -> Result<TableOptions, Diagnostic> {
        // Validate --columns scope.
        if self.columns.is_some() && !matches!(format, Format::Csv | Format::Tsv | Format::Lines) {
            return Err(Diagnostic::Usage(
                "--columns works with csv, tsv, and lines output".to_string(),
            ));
        }

        // Validate --no-header / --header-only scope.
        if (self.no_header || self.header_only) && !matches!(format, Format::Csv | Format::Tsv) {
            return Err(Diagnostic::Usage(
                "--no-header and --header-only work with csv and tsv output only (lines has no header concept)"
                    .to_string(),
            ));
        }

        // Parse --columns value.
        let columns = if let Some(ref raw) = self.columns {
            if raw.is_empty() {
                return Err(Diagnostic::Usage(
                    "--columns requires at least one column name".to_string(),
                ));
            }
            let parts: Vec<&str> = raw.split(',').collect();
            // Reject blank segments (e.g. "a,,b" or trailing comma).
            for part in &parts {
                if part.is_empty() {
                    return Err(Diagnostic::Usage(format!(
                        "--columns contains a blank segment in \"{raw}\"; \
                         use a comma-separated list with no empty entries"
                    )));
                }
            }
            // Reject duplicates.
            let mut seen = std::collections::HashSet::new();
            for part in &parts {
                if !seen.insert(*part) {
                    return Err(Diagnostic::Usage(format!(
                        "--columns contains duplicate column \"{part}\"; \
                         each column may appear at most once"
                    )));
                }
            }
            Some(parts.iter().map(|s| s.to_string()).collect())
        } else {
            None
        };

        let header = if self.header_only {
            HeaderMode::Only
        } else if self.no_header {
            HeaderMode::Off
        } else {
            HeaderMode::On
        };

        Ok(TableOptions { columns, header })
    }
}

/// `dsp` — AI-agent-friendly CLI for the DaSCH Service Platform.
#[derive(Debug, Parser)]
#[command(
    name = "dsp",
    version,
    about = "AI-agent-friendly CLI for the DaSCH Service Platform.",
    long_about = "AI-agent-friendly CLI for the DaSCH Service Platform (DSP).\n\
Run `dsp docs` to list available documentation topics.",
    max_term_width = 100
)]
pub struct Cli {
    /// Increase log verbosity (-v=info, -vv=debug, -vvv=trace). RUST_LOG overrides.
    #[arg(short = 'v', long = "verbose", action = clap::ArgAction::Count, global = true)]
    pub verbose: u8,

    #[command(subcommand)]
    pub command: TopLevel,
}

// Top-level command groups — areas (`vre`, `repo`) and meta-groups
// (`auth`, `docs`). See ADR-0006.
#[derive(Debug, Subcommand)]
pub enum TopLevel {
    /// Authentication management.
    Auth {
        #[command(subcommand)]
        cmd: AuthCmd,
    },

    /// Virtual Research Environment (VRE) operations.
    Vre {
        #[command(subcommand)]
        cmd: VreCmd,
    },

    /// Embedded end-user documentation; `dsp docs` lists topics.
    Docs(DocsArgs),
}

// ── auth ─────────────────────────────────────────────────────────────────────

/// Auth subcommands.
#[derive(Debug, Subcommand)]
pub enum AuthCmd {
    /// Log in to a DSP server and cache the session token.
    ///
    /// See also: dsp docs connecting
    Login(LoginArgs),

    /// Show authentication status for a DSP server.
    Status(StatusArgs),

    /// Log out from a DSP server and clear the cached session token.
    Logout(LogoutArgs),

    /// Cache a pre-issued bearer token read from stdin.
    ///
    /// Reads a JWT from stdin, verifies it against the server with a live
    /// probe, and — only if the probe succeeds — writes it into the auth
    /// cache. Subsequent commands then reuse the token until it expires.
    ///
    /// See also: dsp docs connecting
    #[command(name = "set-token")]
    SetToken(SetTokenArgs),

    /// Print the resolved bearer token to stdout, for piping.
    ///
    /// Prints a bearer credential to stdout — see the cautions in `dsp docs
    /// connecting`.
    ///
    /// See also: dsp docs connecting
    Token(TokenArgs),
}

/// Arguments for `dsp auth login`.
#[derive(Debug, Args)]
#[command(after_help = AFTER_HELP_AUTH_LOGIN)]
pub struct LoginArgs {
    /// DSP server URL or shortcut (e.g. `https://api.example.org` or `prod`).
    /// Can also be set via the `DSP_SERVER` environment variable or a `.env` file.
    #[arg(short = 's', long, env = "DSP_SERVER")]
    pub server: Option<String>,

    /// User identifier for authentication: an email address, a username, or a user IRI.
    /// Can also be set via the `DSP_USER` environment variable or a `.env` file.
    #[arg(short = 'u', long, env = "DSP_USER")]
    pub user: Option<String>,

    #[command(flatten)]
    pub format: FormatArgs,
}

/// Arguments for `dsp auth status`.
#[derive(Debug, Args)]
#[command(after_help = AFTER_HELP_AUTH_STATUS)]
pub struct StatusArgs {
    /// DSP server URL or shortcut (e.g. `https://api.example.org` or `prod`).
    /// Can also be set via the `DSP_SERVER` environment variable or a `.env` file.
    #[arg(short = 's', long, env = "DSP_SERVER")]
    pub server: Option<String>,

    #[command(flatten)]
    pub format: FormatArgs,
}

/// Arguments for `dsp auth logout`.
#[derive(Debug, Args)]
#[command(after_help = AFTER_HELP_AUTH_LOGOUT)]
pub struct LogoutArgs {
    /// DSP server URL or shortcut (e.g. `https://api.example.org` or `prod`).
    /// Can also be set via the `DSP_SERVER` environment variable or a `.env` file.
    #[arg(short = 's', long, env = "DSP_SERVER")]
    pub server: Option<String>,

    #[command(flatten)]
    pub format: FormatArgs,
}

/// Arguments for `dsp auth set-token`.
///
/// No `--token` flag: the token is read from stdin to avoid leaking it into
/// the shell history, `ps` output, or audit logs. See ADR-0007.
#[derive(Debug, Args)]
#[command(after_help = AFTER_HELP_AUTH_SET_TOKEN)]
pub struct SetTokenArgs {
    /// DSP server URL or shortcut (e.g. `https://api.example.org` or `prod`).
    /// Can also be set via the `DSP_SERVER` environment variable or a `.env` file.
    #[arg(short = 's', long, env = "DSP_SERVER")]
    pub server: Option<String>,

    #[command(flatten)]
    pub format: FormatArgs,
}

/// Arguments for `dsp auth token`.
///
/// No `--format`/`-j`/`-l`: the token is printed verbatim, bare, with no
/// envelope. No `after_help` columns line either — there is no tabular output.
#[derive(Debug, Args)]
pub struct TokenArgs {
    /// DSP server URL or shortcut (e.g. `https://api.example.org` or `prod`).
    /// Can also be set via the `DSP_SERVER` environment variable or a `.env` file.
    #[arg(short = 's', long, env = "DSP_SERVER")]
    pub server: Option<String>,
}

// ── vre ───────────────────────────────────────────────────────────────────────

/// VRE noun-group subcommands.
#[derive(Debug, Subcommand)]
pub enum VreCmd {
    /// Manage DSP projects.
    ///
    /// A project is the top-level container on DSP. Every data-model and
    /// resource belongs to exactly one project. See also: dsp docs concepts
    Project {
        #[command(subcommand)]
        cmd: ProjectCmd,
    },

    /// Manage data-models within a project.
    ///
    /// A data-model (called "ontology" in DSP-API) defines the schema for a
    /// project's resources: the resource-types, their fields, and value-types.
    // Explicit name is load-bearing — the CLI surface is stable (ADR-0002);
    // don't strip this as "redundant with default kebab-case."
    #[command(name = "data-model")]
    DataModel {
        #[command(subcommand)]
        cmd: DataModelCmd,
    },

    /// Manage resource-types within a data-model.
    ///
    /// A resource-type (called "class" in DSP-API) defines the structure of
    /// one kind of scholarly object: its fields, value-types, and cardinalities.
    // Explicit name is load-bearing — the CLI surface is stable (ADR-0002);
    // don't strip this as "redundant with default kebab-case."
    #[command(name = "resource-type")]
    ResourceType {
        #[command(subcommand)]
        cmd: ResourceTypeCmd,
    },

    /// List resource instances within a project.
    ///
    /// Fetches the actual data instances (scholarly objects) stored in the DSP
    /// server for a given resource-type, with optional pagination. See also:
    /// dsp docs concepts
    Resource {
        #[command(subcommand)]
        cmd: ResourceCmd,
    },
}

// ── vre project ───────────────────────────────────────────────────────────────

/// Project verb subcommands.
#[derive(Debug, Subcommand)]
pub enum ProjectCmd {
    /// List all projects on the DSP server.
    ///
    /// See also: dsp docs concepts
    List(ProjectListArgs),

    /// Describe a single DSP project.
    ///
    /// See also: dsp docs concepts
    Describe(ProjectDescribeArgs),

    /// Trigger and download a project dump (a server-produced bagit-zip archive).
    ///
    /// Connects to the DSP server, triggers a server-side dump of the specified
    /// project, polls until the dump is ready, and downloads the resulting
    /// bagit-zip archive to a local file. Binary assets (images, audio, video,
    /// etc.) are included by default; pass `--skip-assets` to download only
    /// the structured RDF data.
    ///
    /// **Requires a system-administrator token.** Obtain one via
    /// `dsp auth login --server <server>` or set the `DSP_TOKEN` environment
    /// variable.
    Dump(ProjectDumpArgs),
}

/// Arguments for `dsp vre project list`.
///
/// Lists all projects on the DSP server. Use `--filter` to narrow results by a
/// case-insensitive substring match over shortcode, shortname, and longname.
/// Authentication is optional: an anonymous caller sees all public projects; an
/// authenticated caller may see additional ones depending on server policy.
#[derive(Debug, Args)]
#[command(after_help = AFTER_HELP_PROJECT_LIST)]
pub struct ProjectListArgs {
    /// DSP server URL or shortcut (e.g. `https://api.example.org` or `prod`).
    /// Can also be set via the `DSP_SERVER` environment variable or a `.env` file.
    #[arg(short = 's', long, env = "DSP_SERVER")]
    pub server: Option<String>,

    /// Filter projects by case-insensitive substring over shortcode, shortname,
    /// and longname.
    #[arg(long)]
    pub filter: Option<String>,

    #[command(flatten)]
    pub format: FormatArgs,
}

/// Arguments for `dsp vre project describe`.
#[derive(Debug, Args)]
#[command(after_help = AFTER_HELP_PROJECT_DESCRIBE)]
pub struct ProjectDescribeArgs {
    /// DSP server URL or shortcut (e.g. `https://api.example.org` or `prod`).
    /// Can also be set via the `DSP_SERVER` environment variable or a `.env` file.
    #[arg(short = 's', long, env = "DSP_SERVER")]
    pub server: Option<String>,

    /// Shortcode, shortname, or IRI of the project to describe.
    #[arg(short = 'p', long)]
    pub project: Option<String>,

    #[command(flatten)]
    pub format: FormatArgs,
}

/// Arguments for `dsp vre project dump`.
///
/// Triggers a server-side project dump (a bagit-zip archive of the project's
/// data) and downloads it to a local file. Assets (images, audio, video, etc.)
/// are included by default; use `--skip-assets` to download only the
/// structured RDF data.
///
/// **Requires a system-administrator token.** Obtain one via
/// `dsp auth login --server <server>` or set the `DSP_TOKEN` environment
/// variable.
#[derive(Debug, Args)]
#[command(after_help = AFTER_HELP_PROJECT_DUMP)]
pub struct ProjectDumpArgs {
    /// DSP server URL or shortcut (e.g. `https://api.example.org` or `prod`).
    /// Can also be set via the `DSP_SERVER` environment variable or a `.env` file.
    #[arg(short = 's', long, env = "DSP_SERVER")]
    pub server: Option<String>,

    /// Shortcode, shortname, or IRI of the project to dump.
    #[arg(short = 'p', long)]
    pub project: Option<String>,

    /// Skip binary assets (images, audio, video, etc.); download only the
    /// project's structured RDF data. Assets are included by default.
    #[arg(long)]
    pub skip_assets: bool,

    /// Write the dump to this path instead of the default
    /// `./<shortcode>-<timestamp>.zip`.
    #[arg(short = 'o', long)]
    pub output: Option<std::path::PathBuf>,

    /// Overwrite an existing output file. Without this flag, the command
    /// refuses to overwrite an existing path.
    #[arg(long)]
    pub force: bool,

    /// Delete the server-side dump after a successful download.
    #[arg(long)]
    pub cleanup: bool,

    /// Abort if the dump has not completed within this many seconds
    /// (must be at least 1).
    #[arg(long, default_value_t = 3600, value_parser = clap::value_parser!(u64).range(1..))]
    pub timeout: u64,

    /// Discard this project's existing dump and create a fresh one. If the
    /// server's single dump slot is held by a **different** project, this refuses
    /// unless `--discard-other-project` is also given.
    #[arg(long, conflicts_with = "delete")]
    pub replace: bool,

    /// Remove this project's dump without downloading. If the slot is held by a
    /// different project, this is a no-op (it never removes another project's dump).
    #[arg(
        long,
        conflicts_with_all = ["replace", "output", "force", "skip_assets", "cleanup"]
    )]
    pub delete: bool,

    /// Only valid with `--replace`. The DSP-API holds one dump server-wide; if
    /// the slot is held by a **different** project, also discard *that* project's
    /// dump to make room. Without this, `--replace` refuses when the slot belongs
    /// to another project. (Distinct from `--force`, which only governs
    /// overwriting the local output file.)
    #[arg(long, requires = "replace", conflicts_with = "delete")]
    pub discard_other_project: bool,

    #[command(flatten)]
    pub format: FormatArgs,
}

// ── vre data-model ────────────────────────────────────────────────────────────

/// Data-model verb subcommands.
#[derive(Debug, Subcommand)]
pub enum DataModelCmd {
    /// List all data-models in a project.
    ///
    /// See also: dsp docs concepts
    List(DataModelListArgs),

    /// Describe a single data-model.
    ///
    /// See also: dsp docs concepts
    Describe(DataModelDescribeArgs),

    /// Show the relations (links + inheritance) between a data-model's resource-types.
    ///
    /// See also: dsp docs concepts
    Structure(DataModelStructureArgs),
}

/// Arguments for `dsp vre data-model list`.
#[derive(Debug, Args)]
#[command(after_help = AFTER_HELP_DATA_MODEL_LIST)]
pub struct DataModelListArgs {
    /// DSP server URL or shortcut (e.g. `https://api.example.org` or `prod`).
    /// Can also be set via the `DSP_SERVER` environment variable or a `.env` file.
    #[arg(short = 's', long, env = "DSP_SERVER")]
    pub server: Option<String>,

    /// Shortcode, shortname, or IRI of the project whose data-models to list.
    #[arg(short = 'p', long)]
    pub project: Option<String>,

    /// Filter data-models by case-insensitive substring over name and label.
    #[arg(long)]
    pub filter: Option<String>,

    /// Also list the platform built-in data-models (knora-api, standoff,
    /// salsah-gui) that every project inherits. Off by default.
    #[arg(long)]
    pub include_builtins: bool,

    #[command(flatten)]
    pub format: FormatArgs,
}

/// Arguments for `dsp vre data-model describe`.
#[derive(Debug, Args)]
#[command(after_help = AFTER_HELP_DATA_MODEL_DESCRIBE)]
pub struct DataModelDescribeArgs {
    /// DSP server URL or shortcut (e.g. `https://api.example.org` or `prod`).
    /// Can also be set via the `DSP_SERVER` environment variable or a `.env` file.
    #[arg(short = 's', long, env = "DSP_SERVER")]
    pub server: Option<String>,

    /// Shortcode, shortname, or IRI of the project containing the data-model.
    #[arg(short = 'p', long)]
    pub project: Option<String>,

    /// Name or IRI of the data-model to describe.
    #[arg(long = "data-model")]
    pub data_model: Option<String>,

    #[command(flatten)]
    pub format: FormatArgs,
}

/// Arguments for `dsp vre data-model structure`.
#[derive(Debug, Args)]
#[command(after_help = AFTER_HELP_DATA_MODEL_STRUCTURE)]
pub struct DataModelStructureArgs {
    /// DSP server URL or shortcut (e.g. `https://api.example.org` or `prod`).
    /// Can also be set via the `DSP_SERVER` environment variable or a `.env` file.
    #[arg(short = 's', long, env = "DSP_SERVER")]
    pub server: Option<String>,

    /// Shortcode, shortname, or IRI of the project containing the data-model.
    #[arg(short = 'p', long)]
    pub project: Option<String>,

    /// Name or IRI of the data-model whose structure to show.
    #[arg(long = "data-model")]
    pub data_model: Option<String>,

    /// Also show relations to/from the platform built-in resource-types
    /// (e.g. inherits edges to `Resource` or `StillImageRepresentation`).
    /// Off by default.
    #[arg(long)]
    pub include_builtins: bool,

    #[command(flatten)]
    pub format: FormatArgs,
}

// ── vre resource-type ─────────────────────────────────────────────────────────

/// Resource-type verb subcommands.
#[derive(Debug, Subcommand)]
pub enum ResourceTypeCmd {
    /// List all resource-types in a data-model.
    ///
    /// See also: dsp docs concepts
    List(ResourceTypeListArgs),

    /// Describe a single resource-type, including its fields and value-types.
    ///
    /// See also: dsp docs concepts
    Describe(ResourceTypeDescribeArgs),
}

/// Arguments for `dsp vre resource-type list`.
#[derive(Debug, Args)]
#[command(after_help = AFTER_HELP_RESOURCE_TYPE_LIST)]
pub struct ResourceTypeListArgs {
    /// DSP server URL or shortcut (e.g. `https://api.example.org` or `prod`).
    /// Can also be set via the `DSP_SERVER` environment variable or a `.env` file.
    #[arg(short = 's', long, env = "DSP_SERVER")]
    pub server: Option<String>,

    /// Shortcode, shortname, or IRI of the project.
    #[arg(short = 'p', long)]
    pub project: Option<String>,

    /// Name or IRI of the data-model containing the resource-types.
    #[arg(long = "data-model")]
    pub data_model: Option<String>,

    /// Filter resource-types by case-insensitive substring over name and label.
    #[arg(long)]
    pub filter: Option<String>,

    /// Also list the platform built-in resource-types a user can instantiate
    /// (Region, AudioSegment, VideoSegment, LinkObj) that every project inherits.
    /// Off by default.
    #[arg(long)]
    pub include_builtins: bool,

    #[command(flatten)]
    pub format: FormatArgs,
}

/// Arguments for `dsp vre resource-type describe`.
#[derive(Debug, Args)]
#[command(after_help = AFTER_HELP_RESOURCE_TYPE_DESCRIBE)]
pub struct ResourceTypeDescribeArgs {
    /// DSP server URL or shortcut (e.g. `https://api.example.org` or `prod`).
    /// Can also be set via the `DSP_SERVER` environment variable or a `.env` file.
    #[arg(short = 's', long, env = "DSP_SERVER")]
    pub server: Option<String>,

    /// Shortcode, shortname, or IRI of the project.
    #[arg(short = 'p', long)]
    pub project: Option<String>,

    /// Name or IRI of the data-model containing the resource-type.
    #[arg(long = "data-model")]
    pub data_model: Option<String>,

    /// Name or IRI of the resource-type to describe.
    #[arg(long = "resource-type")]
    pub resource_type: Option<String>,

    /// Also show the built-in (platform) fields every resource inherits
    /// (arkUrl, permissions, timestamps, …). Off by default.
    #[arg(long)]
    pub include_builtins: bool,

    #[command(flatten)]
    pub format: FormatArgs,
}

// ── vre resource ──────────────────────────────────────────────────────────────

/// Resource verb subcommands.
#[derive(Debug, Subcommand)]
pub enum ResourceCmd {
    /// List resource instances of a given type within a project.
    ///
    /// Fetches the actual data instances stored in DSP for a resource-type.
    /// Supports single-page (`--page N`) and all-pages (`--all`) modes.
    /// Authentication is optional; anonymous callers see only public resources.
    ///
    /// See also: dsp docs concepts
    List(ResourceListArgs),

    /// Fetch the envelope metadata of a single resource by its internal IRI.
    ///
    /// Returns the resource's label, resource-type, IRI, ARK URL, creation and
    /// last-modification dates, owning project, owner, visibility, and your
    /// access level. Field values (the actual data) are omitted by default;
    /// pass `--values` to include them.
    ///
    /// Use `--resource` with the resource's internal IRI. ARK addressing is not
    /// supported in v1 — use the internal IRI directly. Optionally, supply
    /// `--project` to guard that the resource belongs to the expected project.
    ///
    /// Authentication is optional; anonymous callers see only public resources.
    ///
    /// See also: dsp docs concepts
    Describe(ResourceDescribeArgs),
}

/// Arguments for `dsp vre resource list`.
#[derive(Debug, Args)]
#[command(after_help = AFTER_HELP_RESOURCE_LIST)]
pub struct ResourceListArgs {
    /// DSP server URL or shortcut (e.g. `https://api.example.org` or `prod`).
    /// Can also be set via the `DSP_SERVER` environment variable or a `.env` file.
    #[arg(short = 's', long, env = "DSP_SERVER")]
    pub server: Option<String>,

    /// Shortcode, shortname, or IRI of the project.
    #[arg(short = 'p', long)]
    pub project: Option<String>,

    /// Name or full IRI of the resource-type to list instances of.
    /// A bare name triggers a scan across all project data-models; use
    /// `--data-model` or a full IRI (`://` heuristic) to skip the scan.
    #[arg(long = "resource-type")]
    pub resource_type: Option<String>,

    /// Name or IRI of the data-model to scope the resource-type search.
    /// Optional; narrows the bare-name scan to one data-model.
    #[arg(long = "data-model")]
    pub data_model: Option<String>,

    /// Page number to fetch (zero-based). Cannot be combined with `--all`.
    /// Defaults to page 0 when neither `--page` nor `--all` is given.
    #[arg(long, value_parser = clap::value_parser!(u32), conflicts_with = "all")]
    pub page: Option<u32>,

    /// Fetch all pages until the server reports no more results.
    /// Cannot be combined with `--page`.
    #[arg(long)]
    pub all: bool,

    /// Filter resources by case-insensitive substring over the label.
    #[arg(long)]
    pub filter: Option<String>,

    /// Field name (e.g. `title`) or full field IRI to sort by (ascending).
    /// A bare field name is resolved to the resource-type's field IRI;
    /// a full IRI (contains `://`) is passed to the server verbatim.
    /// Targets project-defined fields; ascending order only.
    #[arg(long = "order-by")]
    pub order_by: Option<String>,

    #[command(flatten)]
    pub format: FormatArgs,
}

/// Arguments for `dsp vre resource describe`.
///
/// Fetches the envelope metadata of a single resource by its internal IRI.
/// Authentication is optional; anonymous callers see only publicly-visible
/// resources. Use `--project` to assert that the resource belongs to the
/// expected project (a cross-project guard — fails if the resource's
/// attached project does not match).
///
/// **ARK addressing is not supported in v1.** Use the resource's internal IRI
/// (e.g. `http://rdfh.ch/0803/AbCdEf`) as returned by `dsp vre resource list`.
#[derive(Debug, Args)]
#[command(after_help = AFTER_HELP_RESOURCE_DESCRIBE)]
pub struct ResourceDescribeArgs {
    /// DSP server URL or shortcut (e.g. `https://api.example.org` or `prod`).
    /// Can also be set via the `DSP_SERVER` environment variable or a `.env` file.
    #[arg(short = 's', long, env = "DSP_SERVER")]
    pub server: Option<String>,

    /// Internal IRI of the resource to describe (e.g. `http://rdfh.ch/0803/AbCdEf`).
    /// ARK addressing is not supported in v1 — use the internal IRI directly.
    /// Run `dsp vre resource list` to discover resource IRIs.
    #[arg(long)]
    pub resource: Option<String>,

    /// Shortcode, shortname, or IRI of the expected project. When given, the
    /// command fails with a usage error unless the resource's attached project
    /// matches this value. Omit to describe a resource regardless of project.
    #[arg(short = 'p', long)]
    pub project: Option<String>,

    /// Include the resource's field values in the output (off by default; metadata
    /// envelope only when omitted). In `prose` and `json` this adds a values
    /// section on top of the metadata; in tabular formats (`csv`, `tsv`, `lines`)
    /// the output becomes one row per value instead of the metadata row.
    /// Resolving field and list-item labels requires additional server requests.
    /// See also: `dsp docs concepts`
    #[arg(long)]
    pub values: bool,

    #[command(flatten)]
    pub format: FormatArgs,
}

// ── docs ──────────────────────────────────────────────────────────────────────

/// Arguments for `dsp docs [topic]`.
#[derive(Debug, Args)]
pub struct DocsArgs {
    /// Topic to display. Omit to list all topics. Topics: dsp-cli, dsp,
    /// concepts, identifiers, connecting, output, workflows, errors, dsp-tools.
    /// Run `dsp docs` for one-line descriptions.
    pub topic: Option<String>,

    /// Page the output through $PAGER (default `less`).
    #[arg(long, conflicts_with = "json")]
    pub pager: bool,

    /// Emit the topic index as machine-readable JSON. Cannot be combined with a
    /// topic name or --pager.
    #[arg(
        short = 'j',
        long = "json",
        conflicts_with_all = ["topic", "pager"]
    )]
    pub json: bool,
}

// ── Unit tests for FormatArgs::table_options and after_help drift guard ──────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::render::{
        AUTH_LOGIN_COLUMNS, AUTH_LOGOUT_COLUMNS, DATA_MODEL_DESCRIBE_COLUMNS,
        DATA_MODEL_STRUCTURE_COLUMNS, DATA_MODELS_COLUMNS, Format, HeaderMode,
        PROJECT_DUMP_COLUMNS, PROJECT_DUMP_DELETED_COLUMNS, PROJECTS_COLUMNS,
        RESOURCE_DESCRIBE_COLUMNS, RESOURCE_DESCRIBE_VALUES_COLUMNS,
        RESOURCE_DESCRIBE_VALUES_DEFAULT_COLUMNS, RESOURCE_LIST_COLUMNS,
        RESOURCE_TYPE_DESCRIBE_COLUMNS, RESOURCE_TYPES_COLUMNS,
    };
    use clap::CommandFactory;

    /// Helper: construct a minimal FormatArgs with only the given flags set;
    /// all others default to "unset / false / None".
    fn fmt_args(
        format: Format,
        json: bool,
        lines: bool,
        columns: Option<&str>,
        no_header: bool,
        header_only: bool,
    ) -> FormatArgs {
        FormatArgs {
            format,
            json,
            lines,
            columns: columns.map(|s| s.to_string()),
            no_header,
            header_only,
        }
    }

    // ── format-combination validation ─────────────────────────────────────────

    #[test]
    fn columns_with_prose_default_rejected() {
        // --columns with the default (prose) format → Usage error.
        let args = fmt_args(Format::Prose, false, false, Some("name"), false, false);
        let result = args.table_options(Format::Prose);
        assert!(
            matches!(result, Err(Diagnostic::Usage(_))),
            "expected Usage, got {result:?}"
        );
    }

    #[test]
    fn columns_with_json_rejected() {
        // --columns -j → resolved format is Json → Usage error.
        let args = fmt_args(Format::Prose, true, false, Some("name"), false, false);
        let resolved = args.resolve(); // Json
        let result = args.table_options(resolved);
        assert!(
            matches!(result, Err(Diagnostic::Usage(_))),
            "expected Usage, got {result:?}"
        );
    }

    #[test]
    fn columns_with_lines_accepted() {
        // --columns with -l (lines) → ok.
        let args = fmt_args(Format::Prose, false, true, Some("name"), false, false);
        let resolved = args.resolve(); // Lines
        let result = args.table_options(resolved);
        assert!(result.is_ok(), "expected Ok, got {result:?}");
        let opts = result.unwrap();
        assert_eq!(opts.columns, Some(vec!["name".to_string()]));
    }

    #[test]
    fn columns_with_format_lines_flag_accepted() {
        // --columns --format lines → resolved via the --format branch (not -l).
        let args = fmt_args(Format::Lines, false, false, Some("iri"), false, false);
        let resolved = args.resolve(); // Lines (via --format)
        let result = args.table_options(resolved);
        assert!(result.is_ok(), "expected Ok, got {result:?}");
        let opts = result.unwrap();
        assert_eq!(opts.columns, Some(vec!["iri".to_string()]));
    }

    #[test]
    fn columns_with_csv_accepted() {
        let args = fmt_args(
            Format::Csv,
            false,
            false,
            Some("shortcode,iri"),
            false,
            false,
        );
        let result = args.table_options(Format::Csv);
        assert!(result.is_ok(), "expected Ok, got {result:?}");
        let opts = result.unwrap();
        assert_eq!(
            opts.columns,
            Some(vec!["shortcode".to_string(), "iri".to_string()])
        );
    }

    // ── header-flag validation ────────────────────────────────────────────────

    #[test]
    fn no_header_with_prose_rejected() {
        // --no-header with the default prose format → Usage.
        let args = fmt_args(Format::Prose, false, false, None, true, false);
        let resolved = args.resolve(); // Prose
        let result = args.table_options(resolved);
        assert!(
            matches!(result, Err(Diagnostic::Usage(_))),
            "expected Usage for --no-header + prose, got {result:?}"
        );
    }

    #[test]
    fn header_only_with_prose_rejected() {
        // --header-only with the default prose format → Usage.
        let args = fmt_args(Format::Prose, false, false, None, false, true);
        let resolved = args.resolve(); // Prose
        let result = args.table_options(resolved);
        assert!(
            matches!(result, Err(Diagnostic::Usage(_))),
            "expected Usage for --header-only + prose, got {result:?}"
        );
    }

    #[test]
    fn no_header_with_lines_rejected() {
        // --no-header with lines → Usage (lines has no header concept).
        let args = fmt_args(Format::Prose, false, true, None, true, false);
        let resolved = args.resolve(); // Lines
        let result = args.table_options(resolved);
        assert!(
            matches!(result, Err(Diagnostic::Usage(_))),
            "expected Usage for --no-header + lines, got {result:?}"
        );
    }

    #[test]
    fn header_only_with_json_rejected() {
        // --header-only with -j → Usage.
        let args = fmt_args(Format::Prose, true, false, None, false, true);
        let resolved = args.resolve(); // Json
        let result = args.table_options(resolved);
        assert!(
            matches!(result, Err(Diagnostic::Usage(_))),
            "expected Usage for --header-only + json, got {result:?}"
        );
    }

    #[test]
    fn no_header_with_csv_accepted() {
        let args = fmt_args(Format::Csv, false, false, None, true, false);
        let opts = args.table_options(Format::Csv).unwrap();
        assert_eq!(opts.header, HeaderMode::Off);
    }

    #[test]
    fn header_only_with_tsv_accepted() {
        let args = fmt_args(Format::Tsv, false, false, None, false, true);
        let opts = args.table_options(Format::Tsv).unwrap();
        assert_eq!(opts.header, HeaderMode::Only);
    }

    #[test]
    fn default_gives_header_on() {
        let args = fmt_args(Format::Csv, false, false, None, false, false);
        let opts = args.table_options(Format::Csv).unwrap();
        assert_eq!(opts.header, HeaderMode::On);
    }

    // ── column syntax validation ──────────────────────────────────────────────

    #[test]
    fn empty_columns_value_rejected() {
        let args = fmt_args(Format::Csv, false, false, Some(""), false, false);
        let result = args.table_options(Format::Csv);
        assert!(
            matches!(result, Err(Diagnostic::Usage(_))),
            "expected Usage for empty --columns, got {result:?}"
        );
    }

    #[test]
    fn blank_segment_rejected() {
        // "a,,b" has an empty middle segment.
        let args = fmt_args(Format::Csv, false, false, Some("a,,b"), false, false);
        let result = args.table_options(Format::Csv);
        assert!(
            matches!(result, Err(Diagnostic::Usage(_))),
            "expected Usage for blank segment, got {result:?}"
        );
    }

    #[test]
    fn duplicate_rejected() {
        let args = fmt_args(Format::Csv, false, false, Some("iri,iri"), false, false);
        let result = args.table_options(Format::Csv);
        assert!(
            matches!(result, Err(Diagnostic::Usage(_))),
            "expected Usage for duplicate column, got {result:?}"
        );
    }

    #[test]
    fn single_column_accepted() {
        let args = fmt_args(Format::Lines, false, false, Some("iri"), false, false);
        let opts = args.table_options(Format::Lines).unwrap();
        assert_eq!(opts.columns, Some(vec!["iri".to_string()]));
    }

    #[test]
    fn multiple_columns_select_and_reorder() {
        // Columns come back in the user-supplied order (the engine honours it).
        let args = fmt_args(
            Format::Csv,
            false,
            false,
            Some("iri,shortcode,label"),
            false,
            false,
        );
        let opts = args.table_options(Format::Csv).unwrap();
        assert_eq!(
            opts.columns,
            Some(vec![
                "iri".to_string(),
                "shortcode".to_string(),
                "label".to_string()
            ])
        );
    }

    #[test]
    fn no_columns_gives_none() {
        let args = fmt_args(Format::Csv, false, false, None, false, false);
        let opts = args.table_options(Format::Csv).unwrap();
        assert_eq!(opts.columns, None);
    }

    // ── drift-guard: after_help column list must match per-noun consts ─────────
    //
    // Each assertion checks that the corresponding AFTER_HELP_* constant's column
    // list exactly matches `<CONST>.join(", ")`.  Adding a column to the const
    // without updating the literal (or vice versa) fails this test, preventing
    // silent drift between the runtime engine and the help text.
    //
    // RESOURCE_TYPE_DESCRIBE_DEFAULT_COLUMNS (and any other "lean default" consts)
    // are intentionally NOT listed here: they are internal engine defaults, not
    // user-facing column sets. The drift-guard covers all_columns consts only —
    // those are the valid names documented in each command's --help output.
    //
    // PROJECT_DUMP uses a bespoke two-mode literal rather than a join, so it is
    // tested separately against both component consts.

    /// Extract the column list from an after_help string of the form
    /// "Columns (--columns): col1, col2, ..."  or the dump variant
    /// "Columns (--columns): path (with --delete: deleted)".
    ///
    /// Returns everything after the ": " that follows "Columns (--columns)".
    fn extract_columns_part(after_help: &str) -> &str {
        after_help
            .strip_prefix("Columns (--columns): ")
            .expect("after_help must start with 'Columns (--columns): '")
    }

    #[test]
    fn after_help_matches_consts() {
        // Each pair: (after_help_const, column_const_as_joined_string).
        // Uses a Vec so a new pair is one line.
        let cases: &[(&str, &[&str])] = &[
            (AFTER_HELP_PROJECT_LIST, PROJECTS_COLUMNS),
            (AFTER_HELP_PROJECT_DESCRIBE, PROJECTS_COLUMNS),
            (AFTER_HELP_DATA_MODEL_LIST, DATA_MODELS_COLUMNS),
            (AFTER_HELP_DATA_MODEL_DESCRIBE, DATA_MODEL_DESCRIBE_COLUMNS),
            (
                AFTER_HELP_DATA_MODEL_STRUCTURE,
                DATA_MODEL_STRUCTURE_COLUMNS,
            ),
            (AFTER_HELP_RESOURCE_TYPE_LIST, RESOURCE_TYPES_COLUMNS),
            (
                AFTER_HELP_RESOURCE_TYPE_DESCRIBE,
                RESOURCE_TYPE_DESCRIBE_COLUMNS,
            ),
            (AFTER_HELP_AUTH_LOGIN, AUTH_LOGIN_COLUMNS),
            (AFTER_HELP_AUTH_STATUS, AUTH_LOGIN_COLUMNS),
            (AFTER_HELP_AUTH_LOGOUT, AUTH_LOGOUT_COLUMNS),
            (AFTER_HELP_AUTH_SET_TOKEN, AUTH_LOGIN_COLUMNS),
        ];

        for (help_str, const_cols) in cases {
            let extracted = extract_columns_part(help_str);
            let expected = const_cols.join(", ");
            assert_eq!(
                extracted, expected,
                "after_help drift for \"{help_str}\": \
                 help says \"{extracted}\" but const says \"{expected}\""
            );
        }

        // PROJECT_DUMP is bespoke (two-mode literal) — check it structurally.
        let dump_extracted = extract_columns_part(AFTER_HELP_PROJECT_DUMP);
        assert!(
            dump_extracted.starts_with(PROJECT_DUMP_COLUMNS[0]),
            "AFTER_HELP_PROJECT_DUMP must start with PROJECT_DUMP_COLUMNS[0] (\"path\"); \
             got \"{dump_extracted}\""
        );
        assert!(
            dump_extracted.contains(PROJECT_DUMP_DELETED_COLUMNS[0]),
            "AFTER_HELP_PROJECT_DUMP must contain PROJECT_DUMP_DELETED_COLUMNS[0] (\"deleted\"); \
             got \"{dump_extracted}\""
        );

        // RESOURCE_LIST has a multi-line after_help (columns line + scan-behaviour
        // summary). Check that the first line exactly matches the column const.
        let rl_extracted = extract_columns_part(AFTER_HELP_RESOURCE_LIST);
        let rl_first_line = rl_extracted
            .split('\n')
            .next()
            .expect("AFTER_HELP_RESOURCE_LIST must have at least one line");
        let rl_expected = RESOURCE_LIST_COLUMNS.join(", ");
        assert_eq!(
            rl_first_line, rl_expected,
            "AFTER_HELP_RESOURCE_LIST columns line must match RESOURCE_LIST_COLUMNS; \
             got \"{rl_first_line}\" but expected \"{rl_expected}\""
        );

        // RESOURCE_DESCRIBE also has a multi-line after_help (columns + "See also").
        // Check that the first line exactly matches the column const.
        let rd_extracted = extract_columns_part(AFTER_HELP_RESOURCE_DESCRIBE);
        let rd_first_line = rd_extracted
            .split('\n')
            .next()
            .expect("AFTER_HELP_RESOURCE_DESCRIBE must have at least one line");
        let rd_expected = RESOURCE_DESCRIBE_COLUMNS.join(", ");
        assert_eq!(
            rd_first_line, rd_expected,
            "AFTER_HELP_RESOURCE_DESCRIBE columns line must match RESOURCE_DESCRIBE_COLUMNS; \
             got \"{rd_first_line}\" but expected \"{rd_expected}\""
        );

        // RESOURCE_DESCRIBE also documents the --values column set (full + lean
        // default). Locate each sibling line by its distinct prefix and
        // exact-match the remainder — these prefixes don't collide with the
        // "Columns (--columns): " check above (that one anchors on the first
        // line of the whole string).
        let rd_values_prefix = "Columns (--columns) with --values: ";
        let rd_values_line = AFTER_HELP_RESOURCE_DESCRIBE
            .lines()
            .find(|l| l.starts_with(rd_values_prefix))
            .expect("AFTER_HELP_RESOURCE_DESCRIBE must have a --values columns line");
        let rd_values_extracted = rd_values_line
            .strip_prefix(rd_values_prefix)
            .expect("prefix already matched by find()");
        let rd_values_expected = RESOURCE_DESCRIBE_VALUES_COLUMNS.join(", ");
        assert_eq!(
            rd_values_extracted, rd_values_expected,
            "AFTER_HELP_RESOURCE_DESCRIBE --values columns line must match \
             RESOURCE_DESCRIBE_VALUES_COLUMNS; got \"{rd_values_extracted}\" but expected \
             \"{rd_values_expected}\""
        );

        let rd_values_default_prefix = "Default columns with --values: ";
        let rd_values_default_line = AFTER_HELP_RESOURCE_DESCRIBE
            .lines()
            .find(|l| l.starts_with(rd_values_default_prefix))
            .expect("AFTER_HELP_RESOURCE_DESCRIBE must have a default --values columns line");
        let rd_values_default_extracted = rd_values_default_line
            .strip_prefix(rd_values_default_prefix)
            .expect("prefix already matched by find()");
        let rd_values_default_expected = RESOURCE_DESCRIBE_VALUES_DEFAULT_COLUMNS.join(", ");
        assert_eq!(
            rd_values_default_extracted, rd_values_default_expected,
            "AFTER_HELP_RESOURCE_DESCRIBE default --values columns line must match \
             RESOURCE_DESCRIBE_VALUES_DEFAULT_COLUMNS; got \"{rd_values_default_extracted}\" \
             but expected \"{rd_values_default_expected}\""
        );
    }

    // ── drift-guard: skill/SKILL.md must document every clap long-flag ─────────

    /// Recursively collect every clap long-flag name (without the leading
    /// `--`) from `cmd` and all its subcommands into `out`. Excludes the
    /// auto-generated `help` and `version` flags, which `skill/SKILL.md`
    /// neither documents nor needs to.
    fn collect_long_flags(cmd: &clap::Command, out: &mut std::collections::BTreeSet<String>) {
        for arg in cmd.get_arguments() {
            if let Some(long) = arg.get_long()
                && long != "help"
                && long != "version"
            {
                out.insert(long.to_string());
            }
        }
        for sub in cmd.get_subcommands() {
            collect_long_flags(sub, out);
        }
    }

    #[test]
    fn skill_md_documents_every_long_flag() {
        // Every clap long-flag in the live command tree must appear literally
        // in skill/SKILL.md, so agents reading the skill never miss a flag
        // that ships. The flag set is derived from `Cli::command()` (not
        // hand-listed), so this guard cannot itself drift from the real
        // surface.
        const SKILL: &str = include_str!("../../skill/SKILL.md");

        let cmd = Cli::command();
        let mut flags = std::collections::BTreeSet::new();
        collect_long_flags(&cmd, &mut flags);

        // A flag `--foo` counts as present iff `--foo` occurs in the doc and
        // the next character is not `[A-Za-z0-9-]` (or end-of-string) — this
        // stops `--resource` from being spuriously satisfied by every
        // `--resource-type` occurrence.
        let mut missing = Vec::new();
        for flag in &flags {
            let needle = format!("--{flag}");
            let mut found = false;
            for (start, _) in SKILL.match_indices(&needle) {
                let after = start + needle.len();
                let next_char = SKILL[after..].chars().next();
                let boundary = match next_char {
                    None => true,
                    Some(c) => !(c.is_ascii_alphanumeric() || c == '-'),
                };
                if boundary {
                    found = true;
                    break;
                }
            }
            if !found {
                missing.push(needle);
            }
        }

        assert!(
            missing.is_empty(),
            "SKILL.md is missing these clap long-flags: {missing:?} — document them in \
             skill/SKILL.md or the CLI drifted from the skill"
        );
    }
}