oxdock-cli 0.48.0-alpha

CLI tooling for executing OxDock's Dockerfile-inspired DSL on native platforms.
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
//! CLI user-facing errors behind single constructors with stable keys.
//!
//! This module owns every CLI template and key (`cli.*`). It builds on
//! the generic [`oxdock_diagnostics::Diagnostic`] transport but owns its
//! wording: changing CLI text happens here, never in the leaf crate.
//! DSL diagnostics stay owned by the DSL crates.

pub use oxdock_diagnostics::Diagnostic;
use oxdock_diagnostics::flatten_chain;
use oxdock_macros::oxdock_embed;

// CLI usage bodies, one file per Cargo feature variant: statically
// compiled assets cannot branch on Cargo features, so the script
// renders both variants (version line included, through inherited
// Cargo metadata) and Rust `#[cfg]` picks the live one.
oxdock_embed! {
    name: UsageAssets,
    script: {
        INHERIT_ENV [CARGO_PKG_VERSION, CARGO_PKG_DESCRIPTION]
        FUNC EMIT_BODY($is_net: BOOL): VOID {
            LET $net_flags: STRING = """
              --offline          open no sockets (endpoint flags require the `net` feature)
            """

            LET $tail: STRING = """
            Endpoint flags (--listen/-p) require the `net` feature (rebuild with --features net).
            """

            IF $is_net {
                $net_flags = """
                  --listen <addr>    expose a logical service port ([host:]port, repeatable)
                  -p <[host:]outer:inner>  map outer port to an inner service port or name (repeatable; outer 0 is ephemeral; bare outer binds loopback, prefix 0.0.0.0: for all interfaces)
                  --offline          open no sockets (conflicts with --listen/-p)
                  --remote TARGET=CMD    bind a REMOTE target to a stdio transport command (repeatable)
                """
                $tail = "Scripts declare logical endpoints (a port like 2251); the flags above map them to interfaces."
            }

            ECHO """
            oxdock {{ env:CARGO_PKG_VERSION }} — {{ env:CARGO_PKG_DESCRIPTION }}

            Usage: oxdock [OPTIONS] [--] [SCRIPT] [-- script-args...]
              SCRIPT             script file path (same as `--script <file>`); `-` reads stdin
              --script <file|->  script file (relative resolves under the OxDock workspace root), or `-` for stdin
              --shell            run the script, then drop into an interactive shell (requires a TTY)
              --dry-run          print the transitive import closure (file:line CMD) instead of running
              --mcp              serve EXPORTed FUNCs as MCP tools over stdio (requires the `mcp` feature)
            {{ $net_flags }}
              --help, -h         print this help and exit
              --version, -V, -v   print the version and exit

            With no script given, reads the script from stdin (must be piped unless `--shell`).
            Everything after SCRIPT is a verbatim script arg (read via `STD::ARGV()`); one leading `--` there is a separator and dropped, so `--dry-run` after the script stays data.
            {{ $tail }}
            """
        }

        LET $p: PIPE
        WITH_IO [stdout=$p] {
            EMIT_BODY(true)
        }
        WITH_IO [stdin=$p] WRITE dist/usage-net.txt
        WITH_IO [stdout=$p] {
            EMIT_BODY(false)
        }
        WITH_IO [stdin=$p] WRITE dist/usage-lean.txt
    },
    out_dir: "usage-prebuilt",
}

/// Human-readable CLI usage, printed for `--help`/`-h`. The full
/// text, version line included, is rendered once at compile time by
/// the `UsageAssets` script above. Feature selection stays in Rust
/// `#[cfg]`: the DSL has no feature namespace, so each variant lives
/// in its own asset file.
pub fn usage() -> String {
    #[cfg(feature = "net")]
    let asset = "dist/usage-net.txt";
    #[cfg(not(feature = "net"))]
    let asset = "dist/usage-lean.txt";
    let file = UsageAssets::get(asset).expect("usage must be embedded");
    str::from_utf8(file.data.as_ref())
        .expect("usage is UTF-8")
        .to_string()
}

/// `--help`/`-h`: not a failure, but surfaces through the parse
/// result so `run()` can print usage and exit 0 without the parser
/// exiting the process itself (public library API). Message is the
/// full usage text byte for byte.
pub fn help_requested() -> Diagnostic {
    Diagnostic::new("cli.help_requested", usage(), Diagnostic::make_fields(&[]))
}

/// `--version`/`-V`/`-v`: same contract as `--help`. Message is the
/// version line byte for byte.
pub fn version_requested() -> Diagnostic {
    Diagnostic::new(
        "cli.version_requested",
        super::version(),
        Diagnostic::make_fields(&[]),
    )
}

/// A flag needing a Cargo feature this build lacks. Takes the flag and
/// the feature that would provide it; both ride as structured fields.
pub fn feature_required(flag: &str, feature: &str) -> Diagnostic {
    let message =
        format!("{flag} requires the `{feature}` feature (rebuild with --features {feature})");
    Diagnostic::new(
        "cli.feature_required",
        message,
        Diagnostic::make_fields(&[("flag", flag), ("feature", feature)]),
    )
}

/// `--offline` combined with socket flags.
pub fn offline_conflict() -> Diagnostic {
    Diagnostic::new(
        "cli.offline_conflict",
        "--offline conflicts with --listen/-p (offline runs open no sockets)".to_string(),
        Diagnostic::make_fields(&[]),
    )
}

/// Same virtual endpoint mapped twice.
pub fn endpoint_duplicate_inner(endpoint: &str) -> Diagnostic {
    let message = format!("virtual endpoint '{endpoint}' is mapped twice");
    Diagnostic::new(
        "cli.endpoint_duplicate_inner",
        message,
        Diagnostic::make_fields(&[("endpoint", endpoint)]),
    )
}

/// Same outer socket address mapped twice.
pub fn endpoint_duplicate_outer(addr: &str) -> Diagnostic {
    let message = format!("outer socket address {addr} is mapped twice");
    Diagnostic::new(
        "cli.endpoint_duplicate_outer",
        message,
        Diagnostic::make_fields(&[("address", addr)]),
    )
}

/// `--listen` without a value: an address is required.
pub fn listen_requires_address() -> Diagnostic {
    Diagnostic::new(
        "cli.listen_requires_address",
        "--listen requires an address ([host:]port)".to_string(),
        Diagnostic::make_fields(&[("flag", "--listen")]),
    )
}

/// `--listen` with a non-numeric bare port.
pub fn listen_port_numeric(raw: &str) -> Diagnostic {
    let message = format!("--listen port must be numeric 1-65535, got {raw:?}");
    Diagnostic::new(
        "cli.listen_port_numeric",
        message,
        Diagnostic::make_fields(&[("flag", "--listen"), ("got", raw)]),
    )
}

/// `--listen` port `0`: an exposed ephemeral port has no stable
/// service key (that shape belongs to `-p 0:<endpoint>`).
pub fn listen_port_zero() -> Diagnostic {
    Diagnostic::new(
        "cli.listen_port_zero",
        "--listen port 0 has no stable service key (use -p 0:<endpoint> for an ephemeral outer port)"
            .to_string(),
        Diagnostic::make_fields(&[("flag", "--listen")]),
    )
}

/// `--listen` with an unparsable socket address.
pub fn listen_address_invalid(raw: &str) -> Diagnostic {
    let message = format!("--listen address must be [host:]port (try 0.0.0.0:2251), got {raw:?}");
    Diagnostic::new(
        "cli.listen_address_invalid",
        message,
        Diagnostic::make_fields(&[("flag", "--listen"), ("got", raw)]),
    )
}

/// `-p` without the `outer:inner` shape, or with an empty inner.
pub fn publish_requires_shape(raw: &str) -> Diagnostic {
    let message = format!(
        "-p requires [host:]outer:inner (try -p 2222:2251 or -p 127.0.0.1:1234:ssh-server), got {raw:?}"
    );
    Diagnostic::new(
        "cli.publish_requires_shape",
        message,
        Diagnostic::make_fields(&[("flag", "-p"), ("got", raw)]),
    )
}

/// `-p` with an unparsable outer address.
pub fn publish_outer_invalid(raw: &str) -> Diagnostic {
    let message = format!(
        "-p outer address invalid in {raw:?} (expected a port 0-65535 or a [host:]port address)"
    );
    Diagnostic::new(
        "cli.publish_outer_invalid",
        message,
        Diagnostic::make_fields(&[("flag", "-p"), ("got", raw)]),
    )
}

/// `-p` inner endpoint rejected by the endpoint grammar. Takes the
/// underlying `Diagnostic` and inlines its `flatten_chain` text so
/// call sites stay `format!`-free. The inner is a leaf parse-surface
/// failure (sourceless inline), so rendering the bare `Diagnostic`
/// matches the retired anyhow-chain bytes exactly. Net-only: lean
/// builds store the raw inner text and reject later with the feature
/// error.
#[cfg(feature = "net")]
pub fn publish_inner_invalid(raw: &str, reason: Diagnostic) -> Diagnostic {
    let reason_text = flatten_chain(&reason);
    let message = format!("-p inner endpoint invalid in {raw:?}: {reason_text}");
    Diagnostic::new(
        "cli.publish_inner_invalid",
        message,
        Diagnostic::make_fields(&[("flag", "-p"), ("got", raw), ("reason", &reason_text)]),
    )
}

/// Script imports a module the CLI knows but this build did not link.
/// Takes the module name and the Cargo feature that would link it.
pub fn module_unlinked(module: &str, feature: &str) -> Diagnostic {
    let message =
        format!("module `{module}` is known but not linked (rebuild with --features {feature})");
    Diagnostic::new(
        "cli.module_unlinked",
        message,
        Diagnostic::make_fields(&[("module", module), ("feature", feature)]),
    )
}

/// Unknown `--long` / `-s` flag. Takes the bare name plus whether it
/// was long (`--name`) or short (`-n`); the template owns the dashes.
pub fn unexpected_flag(name: &str, long: bool) -> Diagnostic {
    let prefix = if long { "--" } else { "-" };
    let message = format!("unexpected flag: {prefix}{name}");
    Diagnostic::new(
        "cli.unexpected_flag",
        message,
        Diagnostic::make_fields(&[("flag", name)]),
    )
}

/// `--script` without a value.
pub fn script_flag_needs_path() -> Diagnostic {
    Diagnostic::new(
        "cli.script_flag_needs_path",
        "--script requires a path".to_string(),
        Diagnostic::make_fields(&[("flag", "--script")]),
    )
}

/// SCRIPT positional that is a URL, not a workspace path.
pub fn script_not_local(text: &str) -> Diagnostic {
    let message = format!("not a local path: {text:?} (pass a workspace path or `-` for stdin)");
    Diagnostic::new(
        "cli.script_not_local",
        message,
        Diagnostic::make_fields(&[("got", text)]),
    )
}

/// OS argument that is not valid UTF-8.
pub fn arg_not_utf8() -> Diagnostic {
    Diagnostic::new(
        "cli.arg_not_utf8",
        "argument must be UTF-8".to_string(),
        Diagnostic::make_fields(&[]),
    )
}

/// lexopt plumbing failure. Takes the underlying failure;
/// `{reason:#}` formatting lives here so call sites stay
/// `format!`-free.
pub fn arg_lex_error(reason: &lexopt::Error) -> Diagnostic {
    let reason_text = format!("{reason:#}");
    Diagnostic::new(
        "cli.arg_lex_error",
        reason_text.clone(),
        Diagnostic::make_fields(&[("reason", &reason_text)]),
    )
}

/// `--remote` without a value.
pub fn remote_requires_value() -> Diagnostic {
    Diagnostic::new(
        "cli.remote_requires_value",
        "--remote requires <target>=\"<command>\"".to_string(),
        Diagnostic::make_fields(&[("flag", "--remote")]),
    )
}

/// `--remote` without the `<target>="<command>"` shape (lean pure
/// validator, kept live so the flag stays diagnosed without `net`).
#[cfg(not(feature = "net"))]
pub fn remote_requires_shape(raw: &str) -> Diagnostic {
    let message = format!("invalid --remote {raw:?}: expected <target>=\"<command>\"");
    Diagnostic::new(
        "cli.remote_requires_shape",
        message,
        Diagnostic::make_fields(&[("flag", "--remote"), ("got", raw)]),
    )
}

/// No piped script on stdin and no `--shell` to justify emptiness.
pub fn script_stdin_missing() -> Diagnostic {
    Diagnostic::new(
        "cli.script_stdin_missing",
        "no stdin detected; pass --script <file> or pipe a script into stdin (use --script - if explicit)"
            .to_string(),
        Diagnostic::make_fields(&[]),
    )
}

/// Workspace root discovery failed. Takes the underlying failure;
/// the outer text matches the retired bare context byte for byte.
pub fn guard_workspace_root(reason: &Diagnostic) -> Diagnostic {
    let reason_text = flatten_chain(reason);
    let message = format!("guard workspace root: {reason_text}");
    Diagnostic::new(
        "cli.guard_workspace_root",
        message,
        Diagnostic::make_fields(&[("reason", &reason_text)]),
    )
}

/// Script path rejected by the workspace guard. Takes the path and
/// the underlying failure; shared by both parse sites (one key).
pub fn guard_script_path(path: &str, reason: &Diagnostic) -> Diagnostic {
    let reason_text = flatten_chain(reason);
    let message = format!("guard script path {path}: {reason_text}");
    Diagnostic::new(
        "cli.guard_script_path",
        message,
        Diagnostic::make_fields(&[("path", path), ("reason", &reason_text)]),
    )
}

/// Script file unreadable. Takes the display path and the underlying
/// failure; the outer text matches the retired bare context byte
/// for byte.
pub fn read_script_at(path: &str, reason: &Diagnostic) -> Diagnostic {
    let reason_text = flatten_chain(reason);
    let message = format!("failed to read script at {path}: {reason_text}");
    Diagnostic::new(
        "cli.read_script_at",
        message,
        Diagnostic::make_fields(&[("path", path), ("reason", &reason_text)]),
    )
}

/// Piped script unreadable from stdin. Takes the underlying I/O
/// failure; the text is inlined, so no source rides along. Shared
/// by both read sites (one key).
pub fn read_script_stdin(reason: &std::io::Error) -> Diagnostic {
    let reason_text = format!("{reason:#}");
    let message = format!("failed to read script from stdin: {reason_text}");
    Diagnostic::new(
        "cli.read_script_stdin",
        message,
        Diagnostic::make_fields(&[("reason", &reason_text)]),
    )
}

/// Shell snapshot directory failed to materialize. Takes the
/// underlying failure; shared by both snapshot arms (one key).
pub fn create_shell_temp_dir(reason: &Diagnostic) -> Diagnostic {
    let reason_text = flatten_chain(reason);
    let message = format!("failed to create shell temp dir: {reason_text}");
    Diagnostic::new(
        "cli.create_shell_temp_dir",
        message,
        Diagnostic::make_fields(&[("reason", &reason_text)]),
    )
}

/// `--shell` without a controlling terminal.
pub fn shell_needs_tty() -> Diagnostic {
    Diagnostic::new(
        "cli.shell_needs_tty",
        "--shell requires a tty (no controlling tty available)".to_string(),
        Diagnostic::make_fields(&[("flag", "--shell")]),
    )
}

/// `--shell` through `execute_with_result`, which never supports it
/// (embedder API misuse, not user input).
pub fn shell_unsupported_in_result() -> Diagnostic {
    Diagnostic::new(
        "cli.shell_unsupported_in_result",
        "execute_with_result does not support --shell".to_string(),
        Diagnostic::make_fields(&[]),
    )
}

/// Windows shell re-exec staging hit a temp path without a parent
/// (internal invariant, not user input).
#[cfg(windows)]
pub fn shell_temp_missing_parent() -> Diagnostic {
    Diagnostic::new(
        "cli.shell_temp_missing_parent",
        "temp path unexpectedly missing parent".to_string(),
        Diagnostic::make_fields(&[]),
    )
}

/// Windows shell re-exec could not locate the running executable.
/// Takes the underlying I/O failure; the text is inlined, so no
/// source rides along.
#[cfg(windows)]
pub fn determine_current_exe(reason: &std::io::Error) -> Diagnostic {
    let reason_text = format!("{reason:#}");
    let message = format!("determine current executable: {reason_text}");
    Diagnostic::new(
        "cli.determine_current_exe",
        message,
        Diagnostic::make_fields(&[("reason", &reason_text)]),
    )
}

/// Windows shell re-exec could not guard the system temp dir.
/// Takes the underlying failure.
#[cfg(windows)]
pub fn guard_system_temp_dir(reason: &Diagnostic) -> Diagnostic {
    let reason_text = flatten_chain(reason);
    let message = format!("guard system temp dir: {reason_text}");
    Diagnostic::new(
        "cli.guard_system_temp_dir",
        message,
        Diagnostic::make_fields(&[("reason", &reason_text)]),
    )
}

/// Windows shell re-exec could not build the temp shell path.
/// Takes the underlying failure.
#[cfg(windows)]
pub fn construct_temp_shell_path(reason: &Diagnostic) -> Diagnostic {
    let reason_text = flatten_chain(reason);
    let message = format!("construct temp shell path: {reason_text}");
    Diagnostic::new(
        "cli.construct_temp_shell_path",
        message,
        Diagnostic::make_fields(&[("reason", &reason_text)]),
    )
}

/// Windows shell re-exec could not copy the runner binary. Takes
/// the destination display path and the underlying failure.
#[cfg(windows)]
pub fn copy_shell_runner(dest: &str, reason: &Diagnostic) -> Diagnostic {
    let reason_text = flatten_chain(reason);
    let message = format!("failed to copy shell runner to {dest}: {reason_text}");
    Diagnostic::new(
        "cli.copy_shell_runner",
        message,
        Diagnostic::make_fields(&[("dest", dest), ("reason", &reason_text)]),
    )
}

/// Windows shell re-exec could not spawn the staged runner. Takes
/// the destination display path and the spawn failure, which rides
/// `Diagnostic` natively (spawn is `DiagnosticResult`).
#[cfg(windows)]
pub fn spawn_shell_from(dest: &str, reason: &Diagnostic) -> Diagnostic {
    let reason_text = flatten_chain(reason);
    let message = format!("failed to spawn shell from {dest}: {reason_text}");
    Diagnostic::new(
        "cli.spawn_shell_from",
        message,
        Diagnostic::make_fields(&[("dest", dest), ("reason", &reason_text)]),
    )
}

/// `--remote-serve` combined with script/shell/remote inputs.
#[cfg(feature = "net")]
pub fn remote_serve_runs_alone() -> Diagnostic {
    Diagnostic::new(
        "cli.remote_serve_runs_alone",
        "--remote-serve runs alone (no --script, --shell, --remote, or script args)".to_string(),
        Diagnostic::make_fields(&[("flag", "--remote-serve")]),
    )
}

/// `--remote-serve` without piped stdio.
#[cfg(feature = "net")]
pub fn remote_serve_needs_stdio() -> Diagnostic {
    Diagnostic::new(
        "cli.remote_serve_needs_stdio",
        "--remote-serve requires piped stdio (no TTY)".to_string(),
        Diagnostic::make_fields(&[("flag", "--remote-serve")]),
    )
}

/// Fetch tar arrived with no staging section (guest protocol
/// invariant, not user input).
#[cfg(feature = "net")]
pub fn fetch_tar_no_stage() -> Diagnostic {
    Diagnostic::new(
        "cli.serve_fetch_tar_no_stage",
        "serve fetch tar arrived with no stage".to_string(),
        Diagnostic::make_fields(&[]),
    )
}

/// Fetch tar dir member escapes staging. Takes the member path and the
/// underlying failure; `flatten_chain` rendering lives here so call
/// sites stay `format!`-free.
#[cfg(feature = "net")]
pub fn fetch_dir_escapes(path: &str, reason: &Diagnostic) -> Diagnostic {
    let reason_text = flatten_chain(reason);
    let message = format!("fetch dir {path:?} escapes staging: {reason_text}");
    Diagnostic::new(
        "cli.serve_fetch_dir_escapes",
        message,
        Diagnostic::make_fields(&[("path", path), ("reason", &reason_text)]),
    )
}

/// Fetch tar file member escapes staging.
#[cfg(feature = "net")]
pub fn fetch_file_escapes(path: &str, reason: &Diagnostic) -> Diagnostic {
    let reason_text = flatten_chain(reason);
    let message = format!("fetch file {path:?} escapes staging: {reason_text}");
    Diagnostic::new(
        "cli.serve_fetch_file_escapes",
        message,
        Diagnostic::make_fields(&[("path", path), ("reason", &reason_text)]),
    )
}

/// Fetch tar parent directory escapes staging.
#[cfg(feature = "net")]
pub fn fetch_parent_escapes(path: &str, reason: &Diagnostic) -> Diagnostic {
    let reason_text = flatten_chain(reason);
    let message = format!("fetch parent {path:?} escapes staging: {reason_text}");
    Diagnostic::new(
        "cli.serve_fetch_parent_escapes",
        message,
        Diagnostic::make_fields(&[("path", path), ("reason", &reason_text)]),
    )
}

/// Fetch tar symlink member refused (content arrives resolved
/// host-side; symlinks are never served).
#[cfg(feature = "net")]
pub fn fetch_symlink_refused(path: &str, target: &str) -> Diagnostic {
    let message = format!("fetch symlink {path:?} -> {target:?} refused: fetch entries are files");
    Diagnostic::new(
        "cli.serve_fetch_symlink_refused",
        message,
        Diagnostic::make_fields(&[("path", path), ("target", target)]),
    )
}

/// Fetch spill write failure. Takes the underlying I/O failure; the
/// text is inlined, so no source rides along. Sibling of
/// `eval_remote_rewind_failed` for the serve feed loop (fetch tarball
/// bytes into the spill stage).
#[cfg(feature = "net")]
pub fn serve_fetch_spill_write_failed(reason: &std::io::Error) -> Diagnostic {
    let reason_text = format!("{reason:#}");
    let message = format!("serve fetch spill write failed: {reason_text}");
    Diagnostic::new(
        "cli.serve_fetch_spill_write_failed",
        message,
        Diagnostic::make_fields(&[("reason", &reason_text)]),
    )
}

/// Fetch member streaming I/O failure. Takes the member path and the
/// underlying I/O failure; the text is inlined, so no source rides
/// along. Shared by the prepare-staging member read/write sites (one
/// key, one mode), mirroring `eval_unarchive_member_failed`.
#[cfg(feature = "net")]
pub fn serve_fetch_member_failed(path: &str, reason: &std::io::Error) -> Diagnostic {
    let reason_text = format!("{reason:#}");
    let message = format!("fetch member {path:?} failed: {reason_text}");
    Diagnostic::new(
        "cli.serve_fetch_member_failed",
        message,
        Diagnostic::make_fields(&[("path", path), ("reason", &reason_text)]),
    )
}

/// Serve engine worker thread panicked (internal invariant).
#[cfg(feature = "net")]
pub fn serve_engine_panicked() -> Diagnostic {
    Diagnostic::new(
        "cli.serve_engine_panicked",
        "serve engine thread panicked".to_string(),
        Diagnostic::make_fields(&[]),
    )
}

/// Serve stream-handler registration failed. Takes the method name and
/// the foreign endpoint failure; the text is inlined, so no source
/// rides along. Sibling of the other serve I/O ctors (net module
/// convention: cause text inlined without `with_source`).
#[cfg(feature = "net")]
pub fn serve_handler_register_failed(
    method: &str,
    reason: &muxio_rpc_service_endpoint::error::RpcServiceEndpointError,
) -> Diagnostic {
    let reason_text = format!("{reason:#}");
    let message = format!("serve handler registration for {method} failed: {reason_text}");
    Diagnostic::new(
        "cli.serve_handler_register_failed",
        message,
        Diagnostic::make_fields(&[("method", method), ("reason", &reason_text)]),
    )
}

/// Transfer staging tempdir failed. Takes the wrapped failure;
/// `flatten_chain` rendering lives here.
#[cfg(feature = "net")]
pub fn serve_transfer_tempdir_failed(reason: &Diagnostic) -> Diagnostic {
    let reason_text = flatten_chain(reason);
    let message = format!("serve transfer tempdir failed: {reason_text}");
    Diagnostic::new(
        "cli.serve_transfer_tempdir_failed",
        message,
        Diagnostic::make_fields(&[("reason", &reason_text)]),
    )
}

/// Fetch descriptor decode failed. Takes the concrete serialization
/// failure; rendering lives here.
#[cfg(feature = "net")]
pub fn serve_fetch_descriptor_decode_failed(reason: &serde_json::Error) -> Diagnostic {
    let reason_text = reason.to_string();
    let message = format!("serve fetch descriptor decode failed: {reason_text}");
    Diagnostic::new(
        "cli.serve_fetch_descriptor_decode_failed",
        message,
        Diagnostic::make_fields(&[("reason", &reason_text)]),
    )
}

/// Unpack staging tempdir failed. Takes the wrapped failure;
/// `flatten_chain` rendering lives here.
#[cfg(feature = "net")]
pub fn serve_staging_tempdir_failed(reason: &Diagnostic) -> Diagnostic {
    let reason_text = flatten_chain(reason);
    let message = format!("serve staging tempdir failed: {reason_text}");
    Diagnostic::new(
        "cli.serve_staging_tempdir_failed",
        message,
        Diagnostic::make_fields(&[("reason", &reason_text)]),
    )
}

/// Push staging tempdir failed. Takes the wrapped failure;
/// `flatten_chain` rendering lives here.
#[cfg(feature = "net")]
pub fn serve_push_tempdir_failed(reason: &Diagnostic) -> Diagnostic {
    let reason_text = flatten_chain(reason);
    let message = format!("serve push tempdir failed: {reason_text}");
    Diagnostic::new(
        "cli.serve_push_tempdir_failed",
        message,
        Diagnostic::make_fields(&[("reason", &reason_text)]),
    )
}

/// Push spill flush failure. Takes the underlying I/O failure; the
/// text is inlined, so no source rides along. Covers the packed-tar
/// flush into the push spill before the hash pass.
#[cfg(feature = "net")]
pub fn serve_push_spill_flush_failed(reason: &std::io::Error) -> Diagnostic {
    let reason_text = format!("{reason:#}");
    let message = format!("serve push spill flush failed: {reason_text}");
    Diagnostic::new(
        "cli.serve_push_spill_flush_failed",
        message,
        Diagnostic::make_fields(&[("reason", &reason_text)]),
    )
}

/// Push spill hash failure. Takes the underlying I/O failure; the
/// text is inlined, so no source rides along. Covers the re-read
/// hash pass over the push spill.
#[cfg(feature = "net")]
pub fn serve_push_spill_hash_failed(reason: &std::io::Error) -> Diagnostic {
    let reason_text = format!("{reason:#}");
    let message = format!("serve push spill hash failed: {reason_text}");
    Diagnostic::new(
        "cli.serve_push_spill_hash_failed",
        message,
        Diagnostic::make_fields(&[("reason", &reason_text)]),
    )
}

/// Guest push source escapes staging. Takes the underlying failure;
/// `flatten_chain` rendering lives here.
#[cfg(feature = "net")]
pub fn push_source_escapes(guest_src: &str, reason: &Diagnostic) -> Diagnostic {
    let reason_text = flatten_chain(reason);
    let message = format!("guest push source {guest_src:?} escapes staging: {reason_text}");
    Diagnostic::new(
        "cli.serve_push_source_escapes",
        message,
        Diagnostic::make_fields(&[("source", guest_src), ("reason", &reason_text)]),
    )
}

/// Guest push source unreadable. Takes the underlying failure;
/// `flatten_chain` rendering lives here.
#[cfg(feature = "net")]
pub fn push_source_unreadable(path: &str, reason: &Diagnostic) -> Diagnostic {
    let reason_text = flatten_chain(reason);
    let message = format!("guest push source {path:?} unreadable: {reason_text}");
    Diagnostic::new(
        "cli.serve_push_source_unreadable",
        message,
        Diagnostic::make_fields(&[("source", path), ("reason", &reason_text)]),
    )
}

/// Guest push source missing from staging.
#[cfg(feature = "net")]
pub fn push_source_missing(guest_src: &str, reason: &Diagnostic) -> Diagnostic {
    let reason_text = flatten_chain(reason);
    let message = format!("guest push source {guest_src:?} missing: {reason_text}");
    Diagnostic::new(
        "cli.serve_push_source_missing",
        message,
        Diagnostic::make_fields(&[("source", guest_src), ("reason", &reason_text)]),
    )
}

/// `--mcp` without piped stdio.
#[cfg(feature = "mcp")]
pub fn mcp_needs_stdio() -> Diagnostic {
    Diagnostic::new(
        "cli.mcp_needs_stdio",
        "--mcp requires piped stdio transport".to_string(),
        Diagnostic::make_fields(&[("flag", "--mcp")]),
    )
}

/// `--mcp` reading the script from stdin (stdin carries JSON-RPC).
#[cfg(feature = "mcp")]
pub fn mcp_needs_script_file() -> Diagnostic {
    Diagnostic::new(
        "cli.mcp_needs_script_file",
        "--mcp requires a script file (stdin carries the JSON-RPC stream)".to_string(),
        Diagnostic::make_fields(&[("flag", "--mcp")]),
    )
}

/// `--mcp` combined with other run inputs. Takes the conflicting
/// inputs as structured items; joining lives here.
#[cfg(feature = "mcp")]
pub fn mcp_runs_alone(conflicts: &[&str]) -> Diagnostic {
    let joined = conflicts.join(", ");
    let message = format!("--mcp runs alone (no {joined})");
    Diagnostic::new(
        "cli.mcp_runs_alone",
        message,
        Diagnostic::make_fields(&[("flag", "--mcp"), ("conflicts", &joined)]),
    )
}

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

    #[cfg(feature = "net")]
    fn serde_err() -> serde_json::Error {
        serde_json::from_slice::<serde_json::Value>(b"{bad}").unwrap_err()
    }

    /// Sample keyed reason for serve-ctor tests: the ctors take
    /// `&Diagnostic` and inline its `flatten_chain` text, so a keyed
    /// sample pins the same bytes the old `anyhow!("...")` literals did.
    fn sample_reason(text: &str) -> Diagnostic {
        Diagnostic::new("t.reason", text.to_string(), Diagnostic::make_fields(&[]))
    }

    /// Sample I/O failure for the spill/hash/member/stdin ctors:
    /// test-only `std::io::Error` construction (never `anyhow!`), so
    /// the `{reason:#}` inline text pins to `"boom"`.
    fn io_err() -> std::io::Error {
        std::io::Error::new(std::io::ErrorKind::BrokenPipe, "boom")
    }

    #[test]
    fn feature_message_shared_across_sites() {
        for (flag, feature) in [
            ("--listen", "net"),
            ("-p", "net"),
            ("script module", "net"),
            ("--remote-serve", "net"),
            ("--mcp", "mcp"),
        ] {
            let diag = feature_required(flag, feature);
            assert_eq!(diag.key(), "cli.feature_required");
            assert!(diag.message().contains(flag), "{diag}");
            assert!(diag.message().contains(feature), "{diag}");
        }
    }

    #[test]
    fn mcp_feature_gate_names_mcp_not_net() {
        let diag = feature_required("--mcp", "mcp");
        let text = diag.message();
        assert!(text.contains("`mcp`"), "{diag}");
        assert!(text.contains("--features mcp"), "{diag}");
        assert!(!text.contains("net"), "{diag}");
    }

    #[test]
    fn endpoint_duplicates_name_the_key() {
        let inner = endpoint_duplicate_inner("2251");
        assert_eq!(inner.key(), "cli.endpoint_duplicate_inner");

        let outer = endpoint_duplicate_outer("127.0.0.1:2222");
        assert_eq!(outer.key(), "cli.endpoint_duplicate_outer");
    }

    #[test]
    fn untrusted_input_cannot_crash_cli_errors() {
        let evil = "bad\u{1f}flag".to_string();
        let diag = feature_required(&evil, "net");
        assert!(!diag.message().contains('\u{1f}'));
    }

    #[test]
    fn net_shape_errors_carry_stable_keys() {
        let cases: &[(&str, anyhow::Error)] = &[
            (
                "cli.listen_requires_address",
                anyhow::Error::from(listen_requires_address()),
            ),
            (
                "cli.listen_port_numeric",
                anyhow::Error::from(listen_port_numeric("abc")),
            ),
            (
                "cli.listen_port_zero",
                anyhow::Error::from(listen_port_zero()),
            ),
            (
                "cli.listen_address_invalid",
                anyhow::Error::from(listen_address_invalid("0.0.0.0:99999")),
            ),
            (
                "cli.publish_requires_shape",
                anyhow::Error::from(publish_requires_shape("2251")),
            ),
            (
                "cli.publish_outer_invalid",
                anyhow::Error::from(publish_outer_invalid("abc:2251")),
            ),
            // Net-only: lean builds store the raw inner and reject with
            // the feature error instead.
            #[cfg(feature = "net")]
            (
                "cli.publish_inner_invalid",
                anyhow::Error::from(publish_inner_invalid(
                    "2222:0",
                    Diagnostic::new(
                        "t.reason",
                        "bad endpoint".to_string(),
                        Diagnostic::make_fields(&[]),
                    ),
                )),
            ),
            (
                "cli.module_unlinked",
                anyhow::Error::from(module_unlinked("NET", "net")),
            ),
            (
                "cli.unexpected_flag",
                anyhow::Error::from(unexpected_flag("frobnicate", true)),
            ),
            (
                "cli.script_flag_needs_path",
                anyhow::Error::from(script_flag_needs_path()),
            ),
            (
                "cli.script_not_local",
                anyhow::Error::from(script_not_local("https://x")),
            ),
            ("cli.arg_not_utf8", anyhow::Error::from(arg_not_utf8())),
            (
                "cli.arg_lex_error",
                anyhow::Error::from(arg_lex_error(&lexopt::Error::UnexpectedOption(
                    "--nope".to_string(),
                ))),
            ),
            (
                "cli.remote_requires_value",
                anyhow::Error::from(remote_requires_value()),
            ),
            #[cfg(not(feature = "net"))]
            (
                "cli.remote_requires_shape",
                anyhow::Error::from(remote_requires_shape("prod")),
            ),
            (
                "cli.script_stdin_missing",
                anyhow::Error::from(script_stdin_missing()),
            ),
            (
                "cli.shell_needs_tty",
                anyhow::Error::from(shell_needs_tty()),
            ),
            (
                "cli.shell_unsupported_in_result",
                anyhow::Error::from(shell_unsupported_in_result()),
            ),
            #[cfg(windows)]
            (
                "cli.shell_temp_missing_parent",
                anyhow::Error::from(shell_temp_missing_parent()),
            ),
            #[cfg(feature = "net")]
            (
                "cli.remote_serve_runs_alone",
                anyhow::Error::from(remote_serve_runs_alone()),
            ),
            #[cfg(feature = "net")]
            (
                "cli.remote_serve_needs_stdio",
                anyhow::Error::from(remote_serve_needs_stdio()),
            ),
            #[cfg(feature = "net")]
            (
                "cli.serve_fetch_tar_no_stage",
                anyhow::Error::from(fetch_tar_no_stage()),
            ),
            #[cfg(feature = "net")]
            (
                "cli.serve_fetch_dir_escapes",
                anyhow::Error::from(fetch_dir_escapes("a", &sample_reason("root"))),
            ),
            #[cfg(feature = "net")]
            (
                "cli.serve_fetch_file_escapes",
                anyhow::Error::from(fetch_file_escapes("a", &sample_reason("root"))),
            ),
            #[cfg(feature = "net")]
            (
                "cli.serve_fetch_parent_escapes",
                anyhow::Error::from(fetch_parent_escapes("a", &sample_reason("root"))),
            ),
            #[cfg(feature = "net")]
            (
                "cli.serve_fetch_symlink_refused",
                anyhow::Error::from(fetch_symlink_refused("a", "b")),
            ),
            #[cfg(feature = "net")]
            (
                "cli.serve_fetch_spill_write_failed",
                anyhow::Error::from(serve_fetch_spill_write_failed(&io_err())),
            ),
            #[cfg(feature = "net")]
            (
                "cli.serve_fetch_member_failed",
                anyhow::Error::from(serve_fetch_member_failed("a", &io_err())),
            ),
            #[cfg(feature = "net")]
            (
                "cli.serve_engine_panicked",
                anyhow::Error::from(serve_engine_panicked()),
            ),
            #[cfg(feature = "net")]
            (
                "cli.serve_handler_register_failed",
                anyhow::Error::from(serve_handler_register_failed(
                    "exec",
                    &muxio_rpc_service_endpoint::error::RpcServiceEndpointError::Handler(Box::new(
                        io_err(),
                    )),
                )),
            ),
            #[cfg(feature = "net")]
            (
                "cli.serve_transfer_tempdir_failed",
                anyhow::Error::from(serve_transfer_tempdir_failed(&sample_reason("boom"))),
            ),
            #[cfg(feature = "net")]
            (
                "cli.serve_fetch_descriptor_decode_failed",
                anyhow::Error::from(serve_fetch_descriptor_decode_failed(&serde_err())),
            ),
            #[cfg(feature = "net")]
            (
                "cli.serve_staging_tempdir_failed",
                anyhow::Error::from(serve_staging_tempdir_failed(&sample_reason("boom"))),
            ),
            #[cfg(feature = "net")]
            (
                "cli.serve_push_tempdir_failed",
                anyhow::Error::from(serve_push_tempdir_failed(&sample_reason("boom"))),
            ),
            #[cfg(feature = "net")]
            (
                "cli.serve_push_spill_flush_failed",
                anyhow::Error::from(serve_push_spill_flush_failed(&io_err())),
            ),
            #[cfg(feature = "net")]
            (
                "cli.serve_push_spill_hash_failed",
                anyhow::Error::from(serve_push_spill_hash_failed(&io_err())),
            ),
            #[cfg(feature = "net")]
            (
                "cli.serve_push_source_escapes",
                anyhow::Error::from(push_source_escapes("a", &sample_reason("root"))),
            ),
            #[cfg(feature = "net")]
            (
                "cli.serve_push_source_unreadable",
                anyhow::Error::from(push_source_unreadable("a", &sample_reason("root"))),
            ),
            #[cfg(feature = "net")]
            (
                "cli.serve_push_source_missing",
                anyhow::Error::from(push_source_missing("a", &sample_reason("root"))),
            ),
            #[cfg(feature = "mcp")]
            (
                "cli.mcp_needs_stdio",
                anyhow::Error::from(mcp_needs_stdio()),
            ),
            #[cfg(feature = "mcp")]
            (
                "cli.mcp_needs_script_file",
                anyhow::Error::from(mcp_needs_script_file()),
            ),
            #[cfg(feature = "mcp")]
            (
                "cli.mcp_runs_alone",
                anyhow::Error::from(mcp_runs_alone(&["--shell"])),
            ),
            (
                "cli.guard_workspace_root",
                anyhow::Error::from(guard_workspace_root(&sample_reason("boom"))),
            ),
            (
                "cli.guard_script_path",
                anyhow::Error::from(guard_script_path("s.ox", &sample_reason("boom"))),
            ),
            (
                "cli.read_script_at",
                anyhow::Error::from(read_script_at("s.ox", &sample_reason("boom"))),
            ),
            (
                "cli.read_script_stdin",
                anyhow::Error::from(read_script_stdin(&io_err())),
            ),
            (
                "cli.create_shell_temp_dir",
                anyhow::Error::from(create_shell_temp_dir(&sample_reason("boom"))),
            ),
            #[cfg(windows)]
            (
                "cli.determine_current_exe",
                anyhow::Error::from(determine_current_exe(&io_err())),
            ),
            #[cfg(windows)]
            (
                "cli.guard_system_temp_dir",
                anyhow::Error::from(guard_system_temp_dir(&sample_reason("boom"))),
            ),
            #[cfg(windows)]
            (
                "cli.construct_temp_shell_path",
                anyhow::Error::from(construct_temp_shell_path(&sample_reason("boom"))),
            ),
            #[cfg(windows)]
            (
                "cli.copy_shell_runner",
                anyhow::Error::from(copy_shell_runner("d.exe", &sample_reason("boom"))),
            ),
            #[cfg(windows)]
            (
                "cli.spawn_shell_from",
                anyhow::Error::from(spawn_shell_from("d.exe", &sample_reason("boom"))),
            ),
            ("cli.help_requested", anyhow::Error::from(help_requested())),
            (
                "cli.version_requested",
                anyhow::Error::from(version_requested()),
            ),
        ];
        let mut seen = std::collections::HashSet::new();
        for (key, err) in cases {
            let diag = err
                .downcast_ref::<Diagnostic>()
                .expect("CLI errors stay typed");
            assert_eq!(&diag.key(), key, "{diag}");
            assert!(seen.insert(*key), "duplicate key {key}");
        }
    }

    #[test]
    fn flag_shape_messages_name_the_flag() {
        assert_eq!(
            unexpected_flag("frobnicate", true).message(),
            "unexpected flag: --frobnicate"
        );
        assert_eq!(unexpected_flag("z", false).message(), "unexpected flag: -z");
        assert_eq!(
            script_flag_needs_path().message(),
            "--script requires a path"
        );
        assert!(
            script_not_local("https://x/y")
                .to_string()
                .contains("\"https://x/y\"")
        );
        assert!(
            arg_lex_error(&lexopt::Error::UnexpectedOption("--nope".to_string()))
                .to_string()
                .contains("--nope")
        );
        assert_eq!(
            remote_requires_value().message(),
            "--remote requires <target>=\"<command>\""
        );
        #[cfg(feature = "mcp")]
        assert_eq!(
            mcp_runs_alone(&["--shell", "--remote"]).message(),
            "--mcp runs alone (no --shell, --remote)"
        );
    }

    #[test]
    fn startup_context_messages_carry_outer_text() {
        assert_eq!(
            guard_workspace_root(&sample_reason("boom")).message(),
            "guard workspace root: boom"
        );
        assert_eq!(
            guard_script_path("s.ox", &sample_reason("boom")).message(),
            "guard script path s.ox: boom"
        );
        assert_eq!(
            read_script_at("s.ox", &sample_reason("denied")).message(),
            "failed to read script at s.ox: denied"
        );
        assert_eq!(
            read_script_stdin(&io_err()).message(),
            "failed to read script from stdin: boom"
        );
        assert_eq!(
            create_shell_temp_dir(&sample_reason("boom")).message(),
            "failed to create shell temp dir: boom"
        );
    }

    #[cfg(windows)]
    #[test]
    fn windows_reexec_messages_carry_outer_text() {
        assert_eq!(
            determine_current_exe(&io_err()).message(),
            "determine current executable: boom"
        );
        assert_eq!(
            guard_system_temp_dir(&sample_reason("boom")).message(),
            "guard system temp dir: boom"
        );
        assert_eq!(
            construct_temp_shell_path(&sample_reason("boom")).message(),
            "construct temp shell path: boom"
        );
        assert_eq!(
            copy_shell_runner("d.exe", &sample_reason("boom")).message(),
            "failed to copy shell runner to d.exe: boom"
        );
        assert_eq!(
            spawn_shell_from("d.exe", &sample_reason("boom")).message(),
            "failed to spawn shell from d.exe: boom"
        );
    }

    #[cfg(feature = "mcp")]
    #[test]
    fn mcp_gate_messages() {
        assert_eq!(
            mcp_needs_stdio().message(),
            "--mcp requires piped stdio transport"
        );
        assert_eq!(
            mcp_needs_script_file().message(),
            "--mcp requires a script file (stdin carries the JSON-RPC stream)"
        );
    }

    #[cfg(feature = "net")]
    #[test]
    fn serve_staging_messages_name_the_member() {
        let err = fetch_dir_escapes("a", &sample_reason("root"));
        assert!(err.to_string().contains("\"a\""), "{err}");
        assert!(err.to_string().contains("root"), "{err}");
        let err = fetch_symlink_refused("a", "b");
        assert_eq!(
            err.message(),
            "fetch symlink \"a\" -> \"b\" refused: fetch entries are files"
        );
        let err = push_source_unreadable("a", &sample_reason("denied"));
        assert!(err.to_string().contains("denied"), "{err}");
        assert_eq!(
            serve_transfer_tempdir_failed(&sample_reason("boom")).message(),
            "serve transfer tempdir failed: boom"
        );
        assert_eq!(
            serve_fetch_descriptor_decode_failed(&serde_err()).message(),
            "serve fetch descriptor decode failed: key must be a string at line 1 column 2"
        );
        assert_eq!(
            serve_staging_tempdir_failed(&sample_reason("boom")).message(),
            "serve staging tempdir failed: boom"
        );
        assert_eq!(
            serve_push_tempdir_failed(&sample_reason("boom")).message(),
            "serve push tempdir failed: boom"
        );
        assert_eq!(
            serve_fetch_spill_write_failed(&io_err()).message(),
            "serve fetch spill write failed: boom"
        );
        assert_eq!(
            serve_fetch_member_failed("a", &io_err()).message(),
            "fetch member \"a\" failed: boom"
        );
        assert_eq!(
            serve_push_spill_flush_failed(&io_err()).message(),
            "serve push spill flush failed: boom"
        );
        assert_eq!(
            serve_push_spill_hash_failed(&io_err()).message(),
            "serve push spill hash failed: boom"
        );
    }

    #[test]
    fn net_shape_messages_name_the_flag_and_value() {
        assert_eq!(
            listen_requires_address().message(),
            "--listen requires an address ([host:]port)"
        );
        assert!(
            publish_requires_shape("2251")
                .to_string()
                .contains("\"2251\"")
        );
        #[cfg(feature = "net")]
        {
            let err = publish_inner_invalid(
                "2222:0",
                Diagnostic::new(
                    "t.reason",
                    "bad endpoint".to_string(),
                    Diagnostic::make_fields(&[]),
                ),
            );
            let text = err.to_string();
            assert!(text.contains("\"2222:0\""), "{text}");
            assert!(text.contains("bad endpoint"), "{text}");
        }
        assert_eq!(
            module_unlinked("NET", "net").message(),
            "module `NET` is known but not linked (rebuild with --features net)"
        );
    }
}