cli-engine 0.9.3

Rust CLI framework for consistent command modules
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
use std::sync::Arc;

use clap::Arg;
use cli_engine::{
    BuildInfo, Cli, CliConfig, CommandResult, CommandSpec, GroupSpec, HumanViewDef, Module,
    NextAction, RuntimeCommandSpec, RuntimeGroupSpec, TableColumn, Tier,
};
use schemars::JsonSchema;
use serde::Serialize;
use serde_json::{Value, json};

#[derive(Debug, Serialize, JsonSchema)]
struct Project {
    id: String,
    name: String,
    status: String,
}

fn platform_module() -> Module {
    Module::new("Platform Systems", |_context| {
        RuntimeGroupSpec::new(GroupSpec::new("project", "Manage projects"))
            .with_command(list_projects())
            .with_command(delete_project())
    })
}

fn list_projects() -> RuntimeCommandSpec {
    RuntimeCommandSpec::new(
        CommandSpec::new("list", "List projects")
            .with_system("projects-api")
            .with_default_fields("id,name,status")
            .with_json_schema::<Project>()
            // Inline view assigned directly to this command.
            .with_view(vec![
                TableColumn::new("id", "ID"),
                TableColumn::new("name", "Name"),
                TableColumn::new("status", "Status"),
            ])
            .with_arg(Arg::new("team").long("team").required(true))
            .no_auth(true),
        async |_credential, args| {
            let team = args.get("team").and_then(Value::as_str).unwrap_or_default();
            Ok(CommandResult::new(json!([
                {"id": "p1", "name": format!("{team}-api"), "status": "active"},
                {"id": "p2", "name": format!("{team}-web"), "status": "disabled"}
            ])))
        },
    )
}

fn delete_project() -> RuntimeCommandSpec {
    RuntimeCommandSpec::new(
        CommandSpec::new("delete", "Delete a project")
            .with_system("projects-api")
            .with_tier(Tier::Destructive)
            .with_arg(Arg::new("id").long("id").required(true))
            .no_auth(true),
        async |_credential, args| {
            Ok(CommandResult::new(json!({
                    "deleted": args.get("id").and_then(Value::as_str).unwrap_or_default()
            })))
        },
    )
}

fn consumer_cli() -> Cli {
    Cli::new(
        CliConfig::new("my-cli", "Team CLI", "my-cli")
            .with_build(BuildInfo::new("0.1.0"))
            .with_module(platform_module()),
    )
}

#[tokio::test]
async fn consumer_style_cli_supports_json_human_schema_search_and_dry_run() {
    let cli = consumer_cli();

    let list = cli
        .run([
            "my-cli",
            "project",
            "list",
            "--team",
            "platform",
            "--filter",
            "status == 'active'",
            "--fields",
            "id,name",
        ])
        .await;
    assert_eq!(list.exit_code, 0);
    assert_eq!(
        serde_json::from_str::<Value>(&list.rendered).expect("json"),
        json!({"data": [{"id": "p1", "name": "platform-api"}]})
    );

    let human = cli
        .run([
            "my-cli", "project", "list", "--team", "platform", "--output", "human",
        ])
        .await;
    assert_eq!(human.exit_code, 0);
    assert!(human.rendered.contains("NAME"), "{}", human.rendered);
    assert!(human.rendered.contains("STATUS"), "{}", human.rendered);
    assert!(
        human.rendered.contains("p1  platform-api  active"),
        "{}",
        human.rendered
    );

    let schema = cli
        .run(["my-cli", "project", "list", "--schema", "--output", "json"])
        .await;
    assert_eq!(schema.exit_code, 0);
    let schema_json = serde_json::from_str::<Value>(&schema.rendered).expect("schema json");
    assert_eq!(schema_json["data"]["command"], "project:list");
    assert_eq!(schema_json["data"]["schema"]["title"], "Project");

    let search = cli
        .run([
            "my-cli", "search", "projects", "--scope", "project", "--output", "json",
        ])
        .await;
    assert_eq!(search.exit_code, 0);
    assert!(search.rendered.contains("project list"));

    let dry_run = cli
        .run([
            "my-cli",
            "project",
            "delete",
            "--id",
            "p1",
            "--dry-run",
            "--output",
            "json",
        ])
        .await;
    assert_eq!(dry_run.exit_code, 0);
    assert_eq!(
        serde_json::from_str::<Value>(&dry_run.rendered).expect("dry-run json")["data"]["action"],
        "dry-run: would execute"
    );
}

#[tokio::test]
async fn consumer_style_cli_reports_invalid_args_and_output_separately() {
    let cli = consumer_cli();

    let missing = cli.run(["my-cli", "project", "list"]).await;
    assert_ne!(missing.exit_code, 0);
    assert!(missing.rendered.contains("required"));

    let invalid_output = cli
        .run([
            "my-cli", "project", "list", "--team", "platform", "--output", "yaml",
        ])
        .await;
    assert_ne!(invalid_output.exit_code, 0);
    assert!(invalid_output.rendered.contains("invalid output format"));
}

#[tokio::test]
async fn consumer_style_cli_rejects_unknown_fields_instead_of_rendering_empty_rows() {
    let cli = consumer_cli();

    let unknown = cli
        .run([
            "my-cli",
            "project",
            "list",
            "--team",
            "platform",
            "--fields",
            "ID,status",
        ])
        .await;
    assert_ne!(unknown.exit_code, 0);
    let message = serde_json::from_str::<Value>(&unknown.rendered)
        .expect("error envelope should be json")["error"]["message"]
        .as_str()
        .expect("message should be a string")
        .to_owned();
    assert_eq!(
        message,
        "fields: unknown field \"ID\" (did you mean \"id\"?); valid fields: id, name, status"
    );

    let known = cli
        .run([
            "my-cli",
            "project",
            "list",
            "--team",
            "platform",
            "--fields",
            "id,status",
        ])
        .await;
    assert_eq!(known.exit_code, 0);
    assert_eq!(
        serde_json::from_str::<Value>(&known.rendered).expect("json"),
        json!({"data": [
            {"id": "p1", "status": "active"},
            {"id": "p2", "status": "disabled"}
        ]})
    );
}

#[tokio::test]
async fn default_fields_are_projected_without_validation_against_the_response() {
    // A command's `default_fields` can list a field the backend simply
    // didn't populate for a given response (e.g. an optional column with no
    // value in this particular result set) — unlike a user-typed `--fields`
    // typo, that must still succeed rather than hard-error every caller of
    // this command until the author notices.
    let cli = Cli::new(
        CliConfig::new("my-cli", "Team CLI", "my-cli").with_module(Module::new(
            "Platform Systems",
            |_context| {
                RuntimeGroupSpec::new(GroupSpec::new("widget", "Manage widgets")).with_command(
                    RuntimeCommandSpec::new(
                        CommandSpec::new("list", "List widgets")
                            .with_default_fields("id,description")
                            .no_auth(true),
                        async |_credential, _args| Ok(CommandResult::new(json!([{"id": "w1"}]))),
                    ),
                )
            },
        )),
    );

    let output = cli
        .run(["my-cli", "widget", "list", "--output", "json"])
        .await;
    assert_eq!(output.exit_code, 0, "{}", output.rendered);
    assert_eq!(
        serde_json::from_str::<Value>(&output.rendered).expect("json"),
        json!({"data": [{"id": "w1"}]})
    );
}

#[tokio::test]
async fn explicit_empty_fields_keeps_everything_instead_of_falling_back_to_default_fields() {
    // Once a command has `default_fields` set, clap fills `--fields` with
    // that same non-empty string whether or not the user typed the flag —
    // so `self.fields.is_empty()` can't tell "user explicitly cleared
    // --fields" apart from "user never touched it" (`fields_explicit` can).
    // An explicit `--fields ""` means "keep everything," same as `all`/`*`,
    // and must not silently narrow to the command's own default instead.
    let cli = Cli::new(
        CliConfig::new("my-cli", "Team CLI", "my-cli").with_module(Module::new(
            "Platform Systems",
            |_context| {
                RuntimeGroupSpec::new(GroupSpec::new("widget", "Manage widgets")).with_command(
                    RuntimeCommandSpec::new(
                        CommandSpec::new("list", "List widgets")
                            .with_default_fields("id")
                            .no_auth(true),
                        async |_credential, _args| {
                            Ok(CommandResult::new(json!([{"id": "w1", "extra": true}])))
                        },
                    ),
                )
            },
        )),
    );

    let output = cli
        .run([
            "my-cli", "widget", "list", "--output", "json", "--fields", "",
        ])
        .await;
    assert_eq!(output.exit_code, 0, "{}", output.rendered);
    assert_eq!(
        serde_json::from_str::<Value>(&output.rendered).expect("json"),
        json!({"data": [{"id": "w1", "extra": true}]})
    );
}

#[tokio::test]
async fn human_view_rejects_an_unknown_explicit_field_instead_of_narrowing_to_nothing() {
    // With a registered human view, `apply_pipeline`'s field validation never
    // runs — the view narrows its own columns instead of projecting the data
    // (see the comment in `middleware.rs` above `human_view`'s validation
    // check). Column narrowing (`select_columns` in `human.rs`) silently
    // skips a name with no matching column, so an explicit `--fields` typo
    // here needs its own check against the view's column catalog.
    let cli = consumer_cli();

    let unknown = cli
        .run([
            "my-cli", "project", "list", "--team", "platform", "--output", "human", "--fields",
            "ID",
        ])
        .await;
    assert_ne!(unknown.exit_code, 0, "{}", unknown.rendered);
    assert!(
        unknown.rendered.contains("unknown field \"ID\""),
        "{}",
        unknown.rendered
    );
    assert!(
        unknown.rendered.contains("did you mean \"id\"?"),
        "{}",
        unknown.rendered
    );
    assert!(
        unknown.rendered.contains("valid fields: id, name, status"),
        "{}",
        unknown.rendered
    );

    let known = cli
        .run([
            "my-cli", "project", "list", "--team", "platform", "--output", "human", "--fields",
            "id",
        ])
        .await;
    assert_eq!(known.exit_code, 0, "{}", known.rendered);
    assert!(known.rendered.contains("ID"), "{}", known.rendered);
    assert!(!known.rendered.contains("STATUS"), "{}", known.rendered);
}

fn consumer_cli_with_root_actions() -> Cli {
    Cli::new(
        CliConfig::new("my-cli", "Team CLI", "my-cli")
            .with_build(BuildInfo::new("0.1.0"))
            .with_module(platform_module())
            .with_root_next_actions(Arc::new(|| {
                vec![
                    NextAction::new("my-cli project list", "List projects"),
                    NextAction::new("my-cli tree", "Display the full command tree"),
                ]
            })),
    )
}

#[tokio::test]
async fn bare_invocation_human_shows_help_with_next_actions() {
    let cli = consumer_cli_with_root_actions();

    // `--human` forces the interactive format (under `cargo test` stdout is not a
    // TTY, so the default would otherwise resolve to json).
    let bare = cli.run(["my-cli", "--human"]).await;
    assert_eq!(bare.exit_code, 0);
    // Long help is preserved (the command summary still lists `tree`).
    assert!(bare.rendered.contains("tree"), "{}", bare.rendered);
    // Cold-start guidance is appended.
    assert!(
        bare.rendered.contains("Suggested next actions:"),
        "{}",
        bare.rendered
    );
    assert!(
        bare.rendered.contains("my-cli project list"),
        "{}",
        bare.rendered
    );
    // It is human text, not a JSON envelope.
    assert!(
        serde_json::from_str::<Value>(&bare.rendered).is_err(),
        "{}",
        bare.rendered
    );
    // The root help template drops the global options wall.
    assert!(!bare.rendered.contains("--fields"), "{}", bare.rendered);
}

#[tokio::test]
async fn group_help_keeps_subcommands_but_drops_global_options() {
    let cli = consumer_cli();

    // `--human` forces the interactive format (under `cargo test` stdout is
    // not a TTY, so the default would otherwise resolve to json — see
    // `bare_group_discovery_defaults_to_json_tree_off_a_tty` below).
    let group = cli.run(["my-cli", "project", "--human"]).await;
    assert_eq!(group.exit_code, 0);
    // Group page lists its child commands...
    assert!(group.rendered.contains("Commands:"), "{}", group.rendered);
    assert!(group.rendered.contains("list"), "{}", group.rendered);
    assert!(group.rendered.contains("delete"), "{}", group.rendered);
    // ...but not the global options wall.
    assert!(!group.rendered.contains("--fields"), "{}", group.rendered);

    // Leaf commands keep their full flag set.
    let leaf = cli.run(["my-cli", "project", "list", "--help"]).await;
    assert!(leaf.rendered.contains("--fields"), "{}", leaf.rendered);
}

#[tokio::test]
async fn bare_group_discovery_defaults_to_json_tree_off_a_tty() {
    let cli = consumer_cli();

    // No explicit `--output`/`--human`/`--json`: under `cargo test` stdout is
    // not a TTY, so this resolves to the same JSON-tree discovery an agent
    // gets by default.
    let group = cli.run(["my-cli", "project"]).await;
    assert_eq!(group.exit_code, 0, "{}", group.rendered);
    let data =
        &serde_json::from_str::<Value>(&group.rendered).expect("expected a JSON envelope")["data"];
    assert_eq!(data["name"], "project");
    assert_eq!(data["path"], "my-cli project");
    let children = data["children"].as_array().expect("children array");
    assert!(
        children
            .iter()
            .any(|child| child["name"] == "list" && child["description"] == "List projects"),
        "{}",
        group.rendered
    );
    assert!(
        children.iter().any(|child| child["name"] == "delete"),
        "{}",
        group.rendered
    );
}

#[tokio::test]
async fn bare_group_discovery_explicit_json_matches_tty_default() {
    let cli = consumer_cli();

    let explicit = cli.run(["my-cli", "project", "--json"]).await;
    let default = cli.run(["my-cli", "project"]).await;
    assert_eq!(explicit.exit_code, 0, "{}", explicit.rendered);
    assert_eq!(explicit.rendered, default.rendered);
}

#[tokio::test]
async fn bare_invocation_emits_discovery_envelope_for_explicit_json() {
    let cli = consumer_cli_with_root_actions();

    let bare = cli.run(["my-cli", "--output", "json"]).await;
    assert_eq!(bare.exit_code, 0);
    let envelope = serde_json::from_str::<Value>(&bare.rendered).expect("discovery json");
    assert_eq!(envelope["data"]["description"], "Team CLI");
    assert_eq!(envelope["data"]["version"], "0.1.0");
    let actions = envelope["next_actions"]
        .as_array()
        .expect("next_actions array");
    assert_eq!(actions.len(), 2);
    assert_eq!(actions[0]["command"], "my-cli project list");
    // No env/auth/command_tree embedded — reachable via next_actions instead.
    assert!(envelope["data"].get("command_tree").is_none());

    // The `--json` shorthand is also an explicit machine-format request.
    let shorthand = cli.run(["my-cli", "--json"]).await;
    assert_eq!(shorthand.exit_code, 0);
    let shorthand_envelope =
        serde_json::from_str::<Value>(&shorthand.rendered).expect("shorthand discovery json");
    assert_eq!(shorthand_envelope["data"]["description"], "Team CLI");
    assert!(shorthand_envelope["next_actions"].is_array());
}

#[tokio::test]
async fn bare_invocation_rejects_invalid_output_format() {
    let cli = consumer_cli_with_root_actions();

    // An unrecognized explicit `--output` must error on the bare-root discovery
    // path just as it does for a normal command, rather than silently coercing
    // to JSON.
    let bare = cli.run(["my-cli", "--output", "yaml"]).await;
    assert_ne!(bare.exit_code, 0, "{}", bare.rendered);
    assert!(
        bare.rendered.contains("invalid output format"),
        "{}",
        bare.rendered
    );
}

#[tokio::test]
async fn bare_invocation_without_hook_falls_back_to_long_help() {
    let cli = consumer_cli();

    let bare = cli.run(["my-cli"]).await;
    assert_eq!(bare.exit_code, 0);
    assert!(
        !bare.rendered.contains("Suggested next actions:"),
        "{}",
        bare.rendered
    );

    // Even with explicit json, no hook means the unchanged long-help fallback.
    let bare_json = cli.run(["my-cli", "--output", "json"]).await;
    assert_eq!(bare_json.exit_code, 0);
    assert!(
        serde_json::from_str::<Value>(&bare_json.rendered).is_err(),
        "{}",
        bare_json.rendered
    );
}

// A command whose `default_fields` is a strict *subset* of its data keys, with
// no registered HumanViewDef (so the table auto-derives columns from the data).
// This makes the field projection directly observable in human output.
fn fields_demo_cli() -> Cli {
    Cli::new(
        CliConfig::new("my-cli", "Team CLI", "my-cli")
            .with_build(BuildInfo::new("0.1.0"))
            .with_module(Module::new("Demo", |_context| {
                RuntimeGroupSpec::new(GroupSpec::new("widget", "Manage widgets")).with_command(
                    RuntimeCommandSpec::new(
                        CommandSpec::new("list", "List widgets")
                            .with_system("widgets-api")
                            .with_default_fields("id,name")
                            .no_auth(true),
                        async |_credential, _args| {
                            Ok(CommandResult::new(json!([
                                {"id": "w1", "name": "alpha", "secret": "hidden"}
                            ])))
                        },
                    ),
                )
            })),
    )
}

#[tokio::test]
async fn human_output_projects_to_default_fields_when_no_fields_flag() {
    let cli = fields_demo_cli();
    let human = cli
        .run(["my-cli", "widget", "list", "--output", "human"])
        .await;
    assert_eq!(human.exit_code, 0, "{}", human.rendered);
    assert!(human.rendered.contains("NAME"), "{}", human.rendered);
    // `default_fields` is "id,name", so the `secret` column must be projected
    // out of the human table even though no `--fields` flag was passed.
    assert!(
        !human.rendered.contains("SECRET") && !human.rendered.contains("hidden"),
        "human output should honor default_fields and omit `secret`: {}",
        human.rendered
    );
}

#[tokio::test]
async fn human_output_with_fields_all_overrides_default_fields() {
    // The escape hatch: `--fields all` shows every column in human mode.
    let cli = fields_demo_cli();
    let human = cli
        .run([
            "my-cli", "widget", "list", "--output", "human", "--fields", "all",
        ])
        .await;
    assert_eq!(human.exit_code, 0, "{}", human.rendered);
    assert!(human.rendered.contains("hidden"), "{}", human.rendered);
}

#[tokio::test]
async fn schema_on_no_schema_command_reports_no_schema_when_required_arg_missing() {
    // `project delete` has a required `--id` and no registered schema. Asking for
    // `--schema` must short-circuit with the no-schema message through the public
    // `Cli::run` path, not let clap reject the missing `--id` first.
    let cli = consumer_cli();
    let out = cli
        .run([
            "my-cli", "project", "delete", "--schema", "--output", "json",
        ])
        .await;
    assert_eq!(out.exit_code, 0, "{}", out.rendered);
    let envelope: Value = serde_json::from_str(&out.rendered).expect("json envelope");
    assert_eq!(
        envelope["data"]["message"], "No output schema is registered for this command.",
        "{}",
        out.rendered
    );
    // Same `{command, fields}` shape as a real SchemaInfo response.
    assert_eq!(
        envelope["data"]["command"], "project:delete",
        "{}",
        out.rendered
    );
    assert_eq!(envelope["data"]["fields"], json!([]), "{}", out.rendered);
}

#[tokio::test]
async fn schema_on_unknown_command_still_reports_unknown_command() {
    // The no-schema short-circuit must only fire for a real leaf command. A
    // typo'd command with `--schema` should still surface an unknown-command
    // error, not a misleading "no schema registered" body.
    let cli = consumer_cli();
    let out = cli
        .run(["my-cli", "project", "bogus", "--schema", "--output", "json"])
        .await;
    assert_ne!(out.exit_code, 0, "{}", out.rendered);
    assert!(out.rendered.contains("unknown command"), "{}", out.rendered);
    assert!(
        !out.rendered.contains("No output schema is registered"),
        "{}",
        out.rendered
    );
}

// A command that registers a HumanViewDef under its *command path* while setting
// a separate `system` (the common case: many commands share one backend system).
// `default_fields` is a strict subset of the view's columns, so if the view is
// resolved, projection is skipped and the view's extra column survives.
fn viewed_widgets_cli() -> Cli {
    Cli::new(
        CliConfig::new("my-cli", "Team CLI", "my-cli")
            .with_build(BuildInfo::new("0.1.0"))
            .with_module(
                Module::new("Demo", |_context| {
                    RuntimeGroupSpec::new(GroupSpec::new("widget", "Manage widgets")).with_command(
                        RuntimeCommandSpec::new(
                            CommandSpec::new("list", "List widgets")
                                .with_system("widgets-api")
                                // Reference a shared view registered on the module.
                                .with_view_id("widget-table")
                                .no_auth(true),
                            async |_credential, _args| {
                                Ok(CommandResult::new(json!([
                                    {"id": "w1", "name": "alpha", "status": "active"}
                                ])))
                            },
                        ),
                    )
                })
                .with_view(HumanViewDef::new(
                    "widget-table",
                    vec![
                        TableColumn::new("name", "Name"),
                        TableColumn::new("status", "Status"),
                    ],
                )),
            ),
    )
}

#[tokio::test]
async fn human_output_resolves_shared_view_by_id() {
    // The command references the shared view `widget-table` via `with_view_id`,
    // while its `system` is `widgets-api`. With no field selection, the view
    // resolves by the declared id and renders all its columns.
    let cli = viewed_widgets_cli();
    let human = cli
        .run(["my-cli", "widget", "list", "--output", "human"])
        .await;
    assert_eq!(human.exit_code, 0, "{}", human.rendered);
    assert!(human.rendered.contains("STATUS"), "{}", human.rendered);
    assert!(human.rendered.contains("active"), "{}", human.rendered);
}

// A command that assigns its view inline with `with_view`.
fn inline_view_gadgets_cli() -> Cli {
    Cli::new(
        CliConfig::new("my-cli", "Team CLI", "my-cli")
            .with_build(BuildInfo::new("0.1.0"))
            .with_module(Module::new("Demo", |_context| {
                RuntimeGroupSpec::new(GroupSpec::new("gadget", "Manage gadgets")).with_command(
                    RuntimeCommandSpec::new(
                        CommandSpec::new("list", "List gadgets")
                            .with_view(vec![
                                TableColumn::new("name", "Name"),
                                TableColumn::new("status", "Status"),
                            ])
                            .no_auth(true),
                        async |_credential, _args| {
                            Ok(CommandResult::new(json!([
                                {"id": "g1", "name": "alpha", "status": "active"}
                            ])))
                        },
                    ),
                )
            })),
    )
}

#[tokio::test]
async fn human_output_resolves_inline_view() {
    // The command assigns its view inline with `with_view`. The engine registers
    // it under the command path at build, so it resolves and renders its columns.
    let cli = inline_view_gadgets_cli();
    let human = cli
        .run(["my-cli", "gadget", "list", "--output", "human"])
        .await;
    assert_eq!(human.exit_code, 0, "{}", human.rendered);
    assert!(human.rendered.contains("STATUS"), "{}", human.rendered);
    assert!(human.rendered.contains("active"), "{}", human.rendered);
}

// A command with a three-column view and `default_fields` that selects a subset
// of those columns — the default `--fields`. Used to verify that field
// selection narrows the view's columns rather than projecting the data.
fn curated_view_cli() -> Cli {
    Cli::new(
        CliConfig::new("my-cli", "Team CLI", "my-cli")
            .with_build(BuildInfo::new("0.1.0"))
            .with_module(Module::new("Demo", |_context| {
                RuntimeGroupSpec::new(GroupSpec::new("gizmo", "Manage gizmos")).with_command(
                    RuntimeCommandSpec::new(
                        CommandSpec::new("list", "List gizmos")
                            .with_default_fields("id,name")
                            .with_view(vec![
                                TableColumn::new("id", "ID"),
                                TableColumn::new("name", "Name"),
                                TableColumn::new("status", "Status"),
                            ])
                            .no_auth(true),
                        async |_credential, _args| {
                            Ok(CommandResult::new(json!([
                                {"id": "z1", "name": "alpha", "status": "active"}
                            ])))
                        },
                    ),
                )
            })),
    )
}

#[tokio::test]
async fn default_fields_narrows_view_columns() {
    // `default_fields="id,name"` is the default `--fields`, so by default only the
    // `id` and `name` view columns show — `status` is omitted even though the view
    // defines it and the data carries it.
    let cli = curated_view_cli();
    let human = cli
        .run(["my-cli", "gizmo", "list", "--output", "human"])
        .await;
    assert_eq!(human.exit_code, 0, "{}", human.rendered);
    assert!(human.rendered.contains("ID"), "{}", human.rendered);
    assert!(human.rendered.contains("NAME"), "{}", human.rendered);
    assert!(!human.rendered.contains("STATUS"), "{}", human.rendered);
    assert!(!human.rendered.contains("active"), "{}", human.rendered);
}

#[tokio::test]
async fn fields_all_shows_every_view_column() {
    // `--fields all` overrides `default_fields` and shows every view column.
    let cli = curated_view_cli();
    let human = cli
        .run([
            "my-cli", "gizmo", "list", "--output", "human", "--fields", "all",
        ])
        .await;
    assert_eq!(human.exit_code, 0, "{}", human.rendered);
    assert!(human.rendered.contains("STATUS"), "{}", human.rendered);
    assert!(human.rendered.contains("active"), "{}", human.rendered);
}

#[tokio::test]
async fn fields_flag_selects_view_columns() {
    // An explicit `--fields` selects which view columns show: `id,status` keeps
    // those two columns and drops `name`, reading values from the full payload.
    let cli = curated_view_cli();
    let human = cli
        .run([
            "my-cli",
            "gizmo",
            "list",
            "--output",
            "human",
            "--fields",
            "id,status",
        ])
        .await;
    assert_eq!(human.exit_code, 0, "{}", human.rendered);
    assert!(human.rendered.contains("ID"), "{}", human.rendered);
    assert!(human.rendered.contains("STATUS"), "{}", human.rendered);
    assert!(human.rendered.contains("active"), "{}", human.rendered);
    assert!(!human.rendered.contains("NAME"), "{}", human.rendered);
}

// A command that sets BOTH an inline view and a shared view id. `with_view_id`
// takes precedence, so the shared view renders and the inline columns are unused
// (and are not registered).
fn combo_view_cli() -> Cli {
    Cli::new(
        CliConfig::new("my-cli", "Team CLI", "my-cli")
            .with_build(BuildInfo::new("0.1.0"))
            .with_module(
                Module::new("Demo", |_context| {
                    RuntimeGroupSpec::new(GroupSpec::new("combo", "Manage combos")).with_command(
                        RuntimeCommandSpec::new(
                            CommandSpec::new("list", "List combos")
                                .with_view(vec![TableColumn::new("id", "ID")])
                                .with_view_id("combo-shared")
                                .no_auth(true),
                            async |_credential, _args| {
                                Ok(CommandResult::new(json!([
                                    {"id": "c1", "status": "active"}
                                ])))
                            },
                        ),
                    )
                })
                .with_view(HumanViewDef::new(
                    "combo-shared",
                    vec![TableColumn::new("status", "Status")],
                )),
            ),
    )
}

#[tokio::test]
async fn view_id_takes_precedence_over_inline_view() {
    // The command sets both `with_view([id])` and `with_view_id("combo-shared")`.
    // The shared view (a `status` column) wins; the inline `id` column is not used.
    let cli = combo_view_cli();
    let human = cli
        .run(["my-cli", "combo", "list", "--output", "human"])
        .await;
    assert_eq!(human.exit_code, 0, "{}", human.rendered);
    assert!(human.rendered.contains("STATUS"), "{}", human.rendered);
    assert!(human.rendered.contains("active"), "{}", human.rendered);
    assert!(!human.rendered.contains("ID"), "{}", human.rendered);
}

#[tokio::test]
async fn completion_print_bash_exits_zero_with_script() {
    let cli = consumer_cli();
    let out = cli.run(["my-cli", "completion", "bash"]).await;
    assert_eq!(out.exit_code, 0, "rendered: {}", out.rendered);
    assert!(
        out.rendered.contains("my-cli"),
        "script should reference binary name; got: {}",
        out.rendered
    );
    assert!(
        !out.rendered.is_empty(),
        "script should be non-empty; got empty string"
    );
}

#[tokio::test]
async fn completion_print_unknown_shell_exits_nonzero() {
    let cli = consumer_cli();
    let out = cli.run(["my-cli", "completion", "notashell"]).await;
    assert_ne!(out.exit_code, 0, "should fail for unknown shell");
    assert!(
        out.rendered.contains("notashell") || out.rendered.contains("unsupported"),
        "error should mention the bad shell; got: {}",
        out.rendered
    );
}

// A command returning an object whose "parameters" field wraps a list under
// `items` (the pagination/`Summary<T>`-style shape a consumer CLI might use)
// — a nested view column reaches through that wrapper via a dotted field path.
fn nested_view_operation_cli() -> Cli {
    Cli::new(
        CliConfig::new("my-cli", "Team CLI", "my-cli")
            .with_build(BuildInfo::new("0.1.0"))
            .with_module(Module::new("Demo", |_context| {
                RuntimeGroupSpec::new(GroupSpec::new("operation", "Inspect operations"))
                    .with_command(RuntimeCommandSpec::new(
                        CommandSpec::new("get", "Get an operation")
                            .with_view(vec![
                                TableColumn::new("name", "Name"),
                                TableColumn::new("parameters.items", "Parameters").nested(vec![
                                    TableColumn::new("name", "Name"),
                                    TableColumn::new("in", "In"),
                                ]),
                            ])
                            .no_auth(true),
                        async |_credential, _args| {
                            Ok(CommandResult::new(json!({
                                "name": "getPets",
                                "parameters": {
                                    "items": [
                                        {"name": "limit", "in": "query"},
                                        {"name": "id", "in": "path"},
                                    ],
                                    "total": 2,
                                },
                            })))
                        },
                    ))
            })),
    )
}

#[tokio::test]
async fn human_output_renders_nested_view_column_as_indented_child_table() {
    // Proves the full wiring, not just the human.rs-internal path: `with_view`
    // registration, `HumanViewRegistry` lookup by command path, and
    // `render_human_with_registry_selected` all carry the nested column
    // through to a rendered indented child table.
    let cli = nested_view_operation_cli();
    let human = cli
        .run(["my-cli", "operation", "get", "--output", "human"])
        .await;
    assert_eq!(human.exit_code, 0, "{}", human.rendered);
    assert!(
        human.rendered.contains("Name: getPets"),
        "{}",
        human.rendered
    );
    assert!(
        human.rendered.contains("Parameters:\n"),
        "{}",
        human.rendered
    );
    assert!(human.rendered.contains("  NAME"), "{}", human.rendered);
    assert!(human.rendered.contains("  limit"), "{}", human.rendered);
    assert!(
        !human.rendered.contains('{'),
        "no raw JSON should leak into human output: {}",
        human.rendered
    );
}

// Same shape as `nested_view_operation_cli`, except `parameters` also carries
// a `pagination` field — the same `PaginationMeta` shape (`total`/`offset`/
// `limit`/`count`/`has_more`) `Envelope::pagination` already uses at the top
// level — so the nested column's child table gets the same truncation footer
// a top-level paginated array gets (DEVEX-985).
fn nested_view_operation_with_truncated_parameters_cli() -> Cli {
    Cli::new(
        CliConfig::new("my-cli", "Team CLI", "my-cli")
            .with_build(BuildInfo::new("0.1.0"))
            .with_module(Module::new("Demo", |_context| {
                RuntimeGroupSpec::new(GroupSpec::new("operation", "Inspect operations"))
                    .with_command(RuntimeCommandSpec::new(
                        CommandSpec::new("get", "Get an operation")
                            .with_view(vec![
                                TableColumn::new("name", "Name"),
                                TableColumn::new("parameters.items", "Parameters").nested(vec![
                                    TableColumn::new("name", "Name"),
                                    TableColumn::new("in", "In"),
                                ]),
                            ])
                            .no_auth(true),
                        async |_credential, _args| {
                            Ok(CommandResult::new(json!({
                                "name": "getPets",
                                "parameters": {
                                    "items": [
                                        {"name": "limit", "in": "query"},
                                        {"name": "id", "in": "path"},
                                    ],
                                    "pagination": {
                                        "total": 26,
                                        "offset": 0,
                                        "limit": 2,
                                        "count": 2,
                                        "has_more": true,
                                    },
                                },
                            })))
                        },
                    ))
            })),
    )
}

#[tokio::test]
async fn human_output_renders_nested_view_column_truncation_footer_from_pagination_sibling() {
    let cli = nested_view_operation_with_truncated_parameters_cli();
    let human = cli
        .run(["my-cli", "operation", "get", "--output", "human"])
        .await;
    assert_eq!(human.exit_code, 0, "{}", human.rendered);
    assert!(
        human.rendered.contains("(2 of 26 rows, offset 0, limit 2)"),
        "{}",
        human.rendered
    );
}