rhei-cli 0.1.0

Command-line driver for the Rhei agent runtime.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
    use super::*;
    use clap::CommandFactory;

    /// The top-level help is a hand-maintained `help_template` string, so a
    /// newly added subcommand is invisible in `rhei --help` until someone
    /// remembers to list it. `init` shipped that way. Fail loudly instead.
    #[test]
    fn every_subcommand_is_listed_in_the_top_level_help() {
        let command = cli_command();
        let help = command.clone().render_help().to_string();
        // Match a listing entry (`  <name>  <description>`), not a bare
        // substring: `list` and `run` also occur inside descriptions.
        let listed = |name: &str| {
            help.lines().any(|line| {
                line.starts_with("  ")
                    && line.trim_start().strip_prefix(name).is_some_and(|rest| {
                        rest.starts_with(char::is_whitespace) || rest.is_empty()
                    })
            })
        };
        let missing: Vec<&str> =
            command.get_subcommands().map(|sub| sub.get_name()).filter(|n| !listed(n)).collect();
        assert!(
            missing.is_empty(),
            "subcommands missing from the `help_template` in cli_declarations.rs: {missing:?}"
        );
    }

    #[test]
    fn parses_validate_command_with_input() {
        let cli = Cli::try_parse_from(["rhei", "validate", "docs/markdown-plan-compiler.md"])
            .expect("cli should parse");

        assert!(cli.state_machine.is_none());
        match cli.command {
            Commands::Validate { watch, input, .. } => {
                assert!(!watch);
                assert_eq!(input, Some(PathBuf::from("docs/markdown-plan-compiler.md")));
            }
            other => panic!("expected validate command, got {other:?}"),
        }
    }

    #[test]
    fn parses_validate_watch_command_with_input() {
        let cli =
            Cli::try_parse_from(["rhei", "validate", "--watch", "docs/markdown-plan-compiler.md"])
                .expect("cli should parse");

        assert!(cli.state_machine.is_none());
        match cli.command {
            Commands::Validate { watch, input, .. } => {
                assert!(watch);
                assert_eq!(input, Some(PathBuf::from("docs/markdown-plan-compiler.md")));
            }
            other => panic!("expected validate command, got {other:?}"),
        }
    }

    #[test]
    fn parses_render_json_pretty() {
        let cli = Cli::try_parse_from([
            "rhei",
            "render",
            "docs/markdown-plan-compiler.md",
            "--format",
            "json",
            "--pretty",
        ])
        .expect("cli should parse");

        match cli.command {
            Commands::Render { input, format, pretty, no_color, no_metadata, no_content, .. } => {
                assert_eq!(input, Some(PathBuf::from("docs/markdown-plan-compiler.md")));
                assert_eq!(format, RenderFormat::Json);
                assert!(pretty);
                assert!(!no_color);
                assert!(!no_metadata);
                assert!(!no_content);
            }
            other => panic!("expected render command, got {other:?}"),
        }
    }

    #[test]
    fn parses_render_github_toggles() {
        let cli = Cli::try_parse_from([
            "rhei",
            "render",
            "docs/markdown-plan-compiler.md",
            "--format",
            "github",
            "--no-metadata",
            "--no-content",
        ])
        .expect("cli should parse");

        match cli.command {
            Commands::Render { format, no_metadata, no_content, .. } => {
                assert_eq!(format, RenderFormat::Github);
                assert!(no_metadata);
                assert!(no_content);
            }
            other => panic!("expected render command, got {other:?}"),
        }
    }

    #[test]
    fn parses_render_progress_no_color() {
        let cli = Cli::try_parse_from([
            "rhei",
            "render",
            "docs/markdown-plan-compiler.md",
            "--format",
            "progress",
            "--no-color",
        ])
        .expect("cli should parse");

        match cli.command {
            Commands::Render { format, no_color, .. } => {
                assert_eq!(format, RenderFormat::Progress);
                assert!(no_color);
            }
            other => panic!("expected render command, got {other:?}"),
        }
    }

    #[test]
    fn parses_viz_command() {
        let cli = Cli::try_parse_from(["rhei", "viz", "plan.rhei.md", "-o", "out.html", "--open"])
            .expect("cli should parse");
        match cli.command {
            Commands::Viz { input, output, open, .. } => {
                assert_eq!(input, Some(PathBuf::from("plan.rhei.md")));
                assert_eq!(output, Some(PathBuf::from("out.html")));
                assert!(open);
            }
            other => panic!("expected viz command, got {other:?}"),
        }

        let cli = Cli::try_parse_from(["rhei", "viz", "workspace"]).expect("cli should parse");
        match cli.command {
            Commands::Viz { input, output, open, .. } => {
                assert_eq!(input, Some(PathBuf::from("workspace")));
                assert!(output.is_none());
                assert!(!open);
            }
            other => panic!("expected viz command, got {other:?}"),
        }
    }

    #[test]
    fn parses_states_command() {
        let cli = Cli::try_parse_from(["rhei", "states"]).expect("cli should parse");
        match cli.command {
            Commands::States { json, .. } => assert!(!json),
            other => panic!("expected states command, got {other:?}"),
        }

        let cli = Cli::try_parse_from(["rhei", "states", "--json"]).expect("cli should parse");
        match cli.command {
            Commands::States { json, .. } => assert!(json),
            other => panic!("expected states command, got {other:?}"),
        }
    }

    #[test]
    fn render_state_machine_text_includes_states_and_transitions() {
        let yaml = r#"
name: demo
version: 1
models:
  - gpt-5
  - claude-sonnet
states:
  draft:
    description: planning
    instructions: Wait until author promotes task.
    personality: Ask one sharp planning question first.
    initial: true
    visits: 3
    all_models:
      - gpt-5
      - claude-sonnet
  done:
    description: finished
    model: gpt-5
    final: true
transitions:
  - from: draft
    to: done
    on_enter: cli:record_done
"#;
        let machine = rhei_validator::StateMachine::from_yaml_str(yaml).expect("load");
        let rendered = render_state_machine_text(&machine);

        assert!(rendered.contains("State machine: demo"));
        assert!(rendered.contains("Models: gpt-5, claude-sonnet"));
        assert!(rendered.contains("draft"));
        assert!(rendered.contains("Visits: 3"));
        assert!(rendered.contains("Models: gpt-5, claude-sonnet"));
        assert!(rendered.contains("Personality: Ask one sharp planning question first."));
        assert!(rendered.contains("Wait until author promotes task."));
        assert!(rendered.contains("done [final]"));
        assert!(rendered.contains("Model: gpt-5"));
        assert!(rendered.contains("draft -> done (on_enter=cli:record_done)"));
    }

    #[test]
    fn render_state_machine_json_includes_state_personality() {
        let yaml = r#"
name: demo
version: 1
models:
  - gpt-5
states:
  draft:
    description: planning
    personality: Focus on planning risks.
    visits: 2
    all_models:
      - gpt-5
    initial: true
  done:
    description: done
    final: true
transitions: []
"#;
        let machine = rhei_validator::StateMachine::from_yaml_str(yaml).expect("load");
        let rendered = render_state_machine_json(&machine).expect("render JSON");
        let json: serde_json::Value = serde_json::from_str(&rendered).expect("parse JSON");

        assert_eq!(json["name"], "demo");
        assert_eq!(json["models"], serde_json::json!(["gpt-5"]));
        assert_eq!(json["states"][0]["personality"], "Focus on planning risks.");
        assert_eq!(json["states"][0]["visits"], 2);
        assert_eq!(json["states"][0]["all_models"], serde_json::json!(["gpt-5"]));
    }

    #[test]
    fn parses_run_command_with_separated_flag_groups() {
        let cli = Cli::try_parse_from([
            "rhei",
            "run",
            "plan.rhei.md",
            "--dry-run",
            "--no-callbacks",
            "--continue-on-error",
            "--parallel",
            "4",
            "--no-agent",
            "--agent",
            "codex",
            "--model",
            "o3",
        ])
        .expect("cli should parse");

        match cli.command {
            Commands::Run { input, standalone, agent, program, snapshot, .. } => {
                assert_eq!(input, Some(PathBuf::from("plan.rhei.md")));
                assert!(standalone.dry_run);
                assert!(standalone.no_callbacks);
                assert!(standalone.continue_on_error);
                assert_eq!(standalone.parallel, 4);
                assert!(agent.no_agent);
                assert_eq!(agent.agent.as_deref(), Some("codex"));
                assert_eq!(agent.model.as_deref(), Some("o3"));
                assert!(!program.no_program);
                assert_eq!(program.program_timeout.as_deref(), None);
                assert!(snapshot.from_snapshot.is_none());
                assert!(!snapshot.override_inherit);
                assert!(snapshot.snapshot_task.is_none());
                assert!(snapshot.snapshot_target.is_none());
            }
            other => panic!("expected run command, got {other:?}"),
        }
    }

    #[test]
    fn parses_run_command_with_snapshot_flags() {
        let cli = Cli::try_parse_from([
            "rhei",
            "run",
            "plan.rhei.md",
            "--from-snapshot",
            "1.2.3:implementation:pending@2:claude-code-anthropic-claude-opus-4-7/g3",
            "--override-inherit",
            "--task",
            "1.2.3",
            "--target",
            "claude-code-anthropic-claude-opus-4-7",
        ])
        .expect("cli should parse");

        match cli.command {
            Commands::Run { snapshot, .. } => {
                assert_eq!(
                    snapshot.from_snapshot.as_deref(),
                    Some("1.2.3:implementation:pending@2:claude-code-anthropic-claude-opus-4-7/g3")
                );
                assert!(snapshot.override_inherit);
                assert_eq!(snapshot.snapshot_task.as_deref(), Some("1.2.3"));
                assert_eq!(
                    snapshot.snapshot_target.as_deref(),
                    Some("claude-code-anthropic-claude-opus-4-7")
                );
            }
            other => panic!("expected run command, got {other:?}"),
        }
    }

    #[test]
    fn run_rejects_override_inherit_without_from_snapshot() {
        let err = Cli::try_parse_from(["rhei", "run", "plan.rhei.md", "--override-inherit"])
            .expect_err("clap should reject --override-inherit without --from-snapshot");
        let msg = err.to_string();
        assert!(
            msg.contains("--from-snapshot") || msg.contains("requires"),
            "unexpected clap error: {msg}"
        );
    }

    /// Dashboard startup follows the TUI/default and explicit override contract.
    /// §FS-rhei-run-tui.1.6 §FS-rhei-run
    #[test]
    fn dashboard_policy_follows_tui_default_and_explicit_flags() {
        let mut opts = default_run_options();

        assert!(opts.dashboard_enabled(true));
        assert!(!opts.dashboard_enabled(false));

        opts.standalone.no_dashboard = true;
        assert!(!opts.dashboard_enabled(true));
        assert!(!opts.dashboard_enabled(false));

        opts.standalone.no_dashboard = false;
        opts.standalone.dashboard = true;
        assert!(opts.dashboard_enabled(true));
        assert!(opts.dashboard_enabled(false));
    }

    /// Dry runs are planning-only and must not start live dashboard side effects.
    /// §FS-rhei-run.2
    #[test]
    fn dry_run_frontend_never_starts_dashboard() {
        let mut opts = default_run_options();
        opts.standalone.dry_run = true;
        opts.standalone.dashboard = true;

        let machines = ExecutionMachines {
            set: rhei_validator::MachineSet::single(
                rhei_validator::StateMachine::builtin_default(),
            ),
            default_callbacks: CallbackPaths {
                plan_path: PathBuf::from("missing-plan.rhei.md"),
                state_machine_path: None,
                working_dir: PathBuf::from("."),
            },
            per_rhei_callbacks: BTreeMap::new(),
        };
        let frontend = start_run_frontend(
            Path::new("."),
            Path::new("missing-plan.rhei.md"),
            &machines,
            &opts,
            1,
            0,
        );

        assert!(frontend.dashboard.is_none());
    }

    #[test]
    fn run_help_separates_standalone_and_agent_flags() {
        let mut command = Cli::command();
        let run = command.find_subcommand_mut("run").expect("run subcommand should exist");
        let mut buffer = Vec::new();
        run.write_long_help(&mut buffer).expect("help should render");
        let help = String::from_utf8(buffer).expect("help should be UTF-8");

        assert!(help.contains("Standalone Execution:"));
        assert!(help.contains("--dry-run"));
        assert!(help.contains("--parallel"));
        assert!(help.contains("Agent Execution:"));
        assert!(help.contains("--no-agent"));
        assert!(help.contains("--agent <AGENT>"));
        assert!(help.contains("--model <MODEL>"));
        assert!(help.contains("Program Execution:"));
        assert!(help.contains("--no-program"));
        assert!(help.contains("--program-timeout <DURATION>"));
        // §FS-rhei-run.2.3: Snapshots flag group.
        assert!(help.contains("Snapshots:"));
        assert!(help.contains("--from-snapshot <REF>"));
        assert!(help.contains("--override-inherit"));
        assert!(help.contains("--task <TASK_ID>"));
        assert!(help.contains("--target <SLUG>"));
    }

    #[test]
    fn parses_version_command() {
        let cli = Cli::try_parse_from(["rhei", "version"]).expect("cli should parse");

        match cli.command {
            Commands::Version => {}
            other => panic!("expected version command, got {other:?}"),
        }
    }

    #[test]
    fn parses_completions_command() {
        let cli = Cli::try_parse_from(["rhei", "completions", "fish"]).expect("cli should parse");

        match cli.command {
            Commands::Completions { shell, install, system, output, dry_run, .. } => {
                assert_eq!(shell, Some(CompletionShell::Fish));
                assert!(!install);
                assert!(!system);
                assert!(output.is_none());
                assert!(!dry_run);
            }
            other => panic!("expected completions command, got {other:?}"),
        }

        let cli =
            Cli::try_parse_from(["rhei", "completions", "powershell"]).expect("cli should parse");
        match cli.command {
            Commands::Completions { shell, .. } => {
                assert_eq!(shell, Some(CompletionShell::PowerShell))
            }
            other => panic!("expected completions command, got {other:?}"),
        }
    }

    /// §FS-rhei-completions.2
    #[test]
    fn parses_completions_without_shell() {
        let cli = Cli::try_parse_from(["rhei", "completions"]).expect("cli should parse");
        match cli.command {
            Commands::Completions { shell, .. } => assert_eq!(shell, None),
            other => panic!("expected completions command, got {other:?}"),
        }

        let cli = Cli::try_parse_from(["rhei", "completions", "--install", "--dry-run"])
            .expect("cli should parse");
        match cli.command {
            Commands::Completions { shell, install, dry_run, .. } => {
                assert_eq!(shell, None);
                assert!(install);
                assert!(dry_run);
            }
            other => panic!("expected completions command, got {other:?}"),
        }
    }

    /// §FS-rhei-completions.2
    #[test]
    fn detects_current_shell_from_shell_var() {
        let detected = |value: &str| detect_current_shell(Some(OsStr::new(value)));

        assert_eq!(detected("/bin/bash"), Some(CompletionShell::Bash));
        assert_eq!(detected("/usr/bin/zsh"), Some(CompletionShell::Zsh));
        assert_eq!(detected("fish"), Some(CompletionShell::Fish));
        assert_eq!(detected("/usr/local/bin/pwsh"), Some(CompletionShell::PowerShell));
        assert_eq!(detected("powershell"), Some(CompletionShell::PowerShell));
        assert_eq!(detected("/usr/bin/elvish"), Some(CompletionShell::Elvish));
        assert_eq!(detected("/bin/tcsh"), None);
        assert_eq!(detected(""), None);
        assert_eq!(detect_current_shell(None), None);
    }

    #[test]
    fn parses_completions_install_options() {
        let cli = Cli::try_parse_from([
            "rhei",
            "completions",
            "bash",
            "--install",
            "--system",
            "--dry-run",
        ])
        .expect("cli should parse");

        match cli.command {
            Commands::Completions { shell, install, system, dry_run, .. } => {
                assert_eq!(shell, Some(CompletionShell::Bash));
                assert!(install);
                assert!(system);
                assert!(dry_run);
            }
            other => panic!("expected completions command, got {other:?}"),
        }
    }

    #[test]
    fn root_help_lists_completions_command() {
        let mut command = Cli::command();
        let mut buffer = Vec::new();
        command.write_long_help(&mut buffer).expect("help should render");
        let help = String::from_utf8(buffer).expect("help should be UTF-8");

        assert!(help.contains("Setup:"));
        assert!(help.contains("completions"));
        assert!(help.contains("Generate shell completion scripts"));
    }

    #[test]
    fn render_rhei_json_smoke() {
        let rhei = rhei_core::parse(
            r#"# Rhei: Smoke

## Tasks

### Task 1: Alpha
**State:** pending
"#,
        )
        .expect("parse should succeed");

        let rendered = render_rhei(
            &rhei,
            BTreeSet::new(),
            false,
            Vec::new(),
            RenderFormat::Json,
            true,
            false,
            false,
            false,
        )
        .expect("render ok");

        assert!(rendered.contains("\"title\": \"Smoke\""));
        assert!(rendered.contains("\"tasks\""));
    }

    #[test]
    fn compose_agent_prompt_carries_domain_instructions_only() {
        let rhei = rhei_core::parse(
            r#"# Rhei: Prompt Smoke

## Tasks

### Task demo: Verify prompt wiring
**State:** review

Write findings and transition the task.
"#,
        )
        .expect("plan should parse");
        let machine = rhei_validator::StateMachine::from_yaml_str(
            r#"
name: prompt-smoke
version: 1
states:
  review:
    description: review
    instructions: Write findings to `{output.review-notes.path}`.
    initial: true
    outputs:
      - name: review-notes
        path: runtime/reviews/task-{task_id}.md
  fix:
    description: fix
    final: true
transitions:
  - from: review
    to: fix
"#,
        )
        .expect("machine should parse");
        let task = &rhei.tasks[0];
        let context = RuntimeTemplateContext {
            task_roots: None,
            workspace_root: Path::new("/tmp/workspace"),
            checkout_root: Path::new("/tmp/workspace"),
            plan_path: Path::new("/tmp/workspace"),
            state_machine_path: Some(Path::new("/tmp/workspace/states.yaml")),
            plan_title: &rhei.title,
            task,
            state_name: "review",
            current_state_raw: "review",
            machine: &machine,
            metadata: None,
            target: None,
            model: None,
            model_provider: None,
            model_name: None,
            agent: Some("codex"),
            agent_mode: None,
            tooling: None,
        };

        let prompt = compose_agent_prompt(&context).expect("prompt");

        // New Rhei Commands section replaces Workflow Notes.
        assert!(prompt.contains("## Rhei Commands"));
        assert!(prompt.contains("rhei-managed plan at `/tmp/workspace`"));
        assert!(prompt.contains("The active state machine is `/tmp/workspace/states.yaml`."));
        assert!(prompt.contains(
            "The `rhei run` process that spawned you is responsible for advancing the task"
        ));
        assert!(prompt.contains("Available transitions from `review`:"));

        // Completion is a property of the execution model, not the prompt — no
        // completion prose should appear.
        assert!(!prompt.contains("then stop"));
        assert!(!prompt.contains("create every required output artifact"));
        assert!(!prompt.contains("produce every required output artifact"));
        assert!(!prompt.contains("for caller context"));
        assert!(!prompt.contains("Workflow Notes"));
    }

    #[test]
    fn runtime_templates_use_resolved_model_provider_and_name() {
        let rhei = rhei_core::parse(
            "# Rhei: Prompt Smoke\n\n## Tasks\n\n### Task demo: Verify\n**State:** review\n\nDo work.\n",
        )
        .expect("plan should parse");
        let machine = rhei_validator::StateMachine::from_yaml_str(
            r#"
name: prompt-smoke
version: 1
states:
  review:
    description: review
    instructions: "{model} {model.provider} {model.name}"
  done:
    description: done
    final: true
"#,
        )
        .expect("machine should parse");
        let context = RuntimeTemplateContext {
            task_roots: None,
            workspace_root: Path::new("/tmp/workspace"),
            checkout_root: Path::new("/tmp/workspace"),
            plan_path: Path::new("/tmp/workspace"),
            state_machine_path: None,
            plan_title: &rhei.title,
            task: &rhei.tasks[0],
            state_name: "review",
            current_state_raw: "review",
            machine: &machine,
            metadata: None,
            target: None,
            model: Some("impl-fast"),
            model_provider: Some("anthropic"),
            model_name: Some("claude-sonnet-4-6"),
            agent: Some("codex"),
            agent_mode: None,
            tooling: None,
        };

        let rendered =
            resolve_runtime_template_text(state_instructions(&machine, "review").as_str(), &context);
        assert_eq!(rendered, "impl-fast anthropic claude-sonnet-4-6");
    }

    #[test]
    fn parse_diagnostic_includes_line_info_when_available() {
        let input = "first line\nbad line\nthird line";
        let err = rhei_core::parser::ParseError {
            message: "unexpected token".to_string(),
            line: Some(2),
            file: None,
        };

        let rendered = render_parse_diagnostic(Path::new("broken.md"), input, &err);

        assert!(rendered.contains("-- PARSE ERROR"));
        assert!(rendered.contains("broken.md"));
        assert!(rendered.contains("2| bad line"));
        assert!(rendered.contains("unexpected token"));
    }

    #[test]
    fn validation_failure_formatting_aggregates_multiple_errors() {
        let rendered = format_validation_errors(&[
            "Task 1 is missing mandatory **State:** metadata".to_string(),
            "Task 2 depends on missing Task 9".to_string(),
        ]);

        assert!(rendered.contains("I found 2 problems:"));
        assert!(rendered.contains("1. Task 1 is missing mandatory **State:** metadata"));
        assert!(rendered.contains("2. Task 2 depends on missing Task 9"));
    }

    #[test]
    fn path_matches_normalizes_paths() {
        let watched = canonical_watched_paths(
            Path::new("docs/markdown-plan-compiler.md"),
            Path::new("docs/states.yaml"),
        );

        assert!(path_matches(Path::new("./docs/markdown-plan-compiler.md"), &watched));
        assert!(path_matches(Path::new("docs/states.yaml"), &watched));
        assert!(!path_matches(Path::new("docs/plan-language-spec.md"), &watched));
    }

    #[test]
    fn panta_watch_excludes_runtime_at_any_depth() {
        // Absolute paths so `path_is_under` falls back to a component prefix
        // check without needing the directories to exist on disk.
        let targets = panta_watch_targets(Path::new("/proj"));

        // Manifest, single-file rheis, and workspace task files revalidate.
        assert!(path_matches(Path::new("/proj/index.panta.md"), &targets));
        assert!(path_matches(Path::new("/proj/auth.rhei.md"), &targets));
        assert!(path_matches(Path::new("/proj/billing/tasks/invoice.md"), &targets));

        // The project `runtime/` tree (where viz writes dashboard.html) never does...
        assert!(!path_matches(Path::new("/proj/runtime/dashboard.html"), &targets));
        // ...nor a per-rhei `runtime/` tree nested under a workspace rhei.
        assert!(!path_matches(Path::new("/proj/billing/runtime/results/billing.1.md"), &targets));

        // A similarly-named sibling that is not a `runtime` directory still matches.
        assert!(path_matches(Path::new("/proj/runtime-notes.rhei.md"), &targets));
    }

    /// A skill compiled into the binary but missing from the `--skills` default
    /// reaches only users who read the flag docs and type its name;
    /// `rhei-template-writer` shipped that way. §FS-rhei-install-skills.2
    #[test]
    fn default_skills_covers_every_builtin() {
        let command = cli_command();
        let install = command
            .get_subcommands()
            .find(|sub| sub.get_name() == "install-skills")
            .expect("install-skills subcommand");
        let arg = install
            .get_arguments()
            .find(|arg| arg.get_id() == "skills")
            .expect("--skills argument");

        let mut defaults: Vec<String> = arg
            .get_default_values()
            .iter()
            .flat_map(|value| {
                value
                    .to_string_lossy()
                    .split(',')
                    .map(ToOwned::to_owned)
                    .collect::<Vec<String>>()
            })
            .collect();
        defaults.sort();

        assert_eq!(
            defaults,
            builtin_skill_names(),
            "the --skills default in cli_declarations.rs and the skills embedded from \
             crates/rhei-cli/skills/ have drifted apart"
        );
    }

    /// Build a machine whose `implement` state writes a handoff at `path` and
    /// whose `review` state requires it.
    fn handoff_machine(
        models: &str,
        implement_state: &str,
        path: &str,
    ) -> rhei_validator::StateMachine {
        rhei_validator::StateMachine::from_yaml_str(&format!(
            r#"
name: handoff
version: 1
{models}
states:
  implement:
    description: implement
    initial: true
{implement_state}
    outputs:
      - name: implementation
        kind: handoff
        path: {path}
  review:
    description: review
    instructions: Review it.
    handoff:
      inherit:
        - from: transition.previous
          required: true
  done:
    description: done
    final: true
transitions:
  - from: implement
    to: review
  - from: review
    to: done
"#
        ))
        .expect("machine should parse")
    }

    fn handoff_plan() -> rhei_core::ast::Rhei {
        rhei_core::parse(
            r#"# Rhei: Handoff

## Tasks

### Task 1: Ship it
**State:** review
"#,
        )
        .expect("plan should parse")
    }

    fn handoff_context<'a>(
        workspace: &'a Path,
        rhei: &'a rhei_core::ast::Rhei,
        machine: &'a rhei_validator::StateMachine,
        model: Option<&'a str>,
    ) -> RuntimeTemplateContext<'a> {
        RuntimeTemplateContext {
            task_roots: None,
            workspace_root: workspace,
            checkout_root: workspace,
            plan_path: workspace,
            state_machine_path: None,
            plan_title: &rhei.title,
            task: &rhei.tasks[0],
            state_name: "review",
            current_state_raw: "review",
            machine,
            metadata: None,
            target: None,
            model,
            model_provider: None,
            model_name: None,
            agent: Some("codex"),
            agent_mode: None,
            tooling: None,
        }
    }

    fn record_transition(workspace: &Path, line: &str) {
        let runtime = workspace.join("runtime");
        std::fs::create_dir_all(&runtime).expect("mkdir runtime");
        std::fs::write(runtime.join("state-transitions.log"), format!("{line}\n"))
            .expect("write ledger");
    }

    /// A handoff path that templates the execution identity belongs to the
    /// state that *wrote* it. Resolving `{model}` with the successor's model
    /// looks for a file the producer never wrote. §FS-rhei-states.3.2
    #[test]
    fn state_handoff_resolves_under_the_source_states_model() {
        let rhei = handoff_plan();
        let machine = handoff_machine(
            "models:\n  - producer-model\n  - consumer-model",
            "    model: producer-model",
            "runtime/handoffs/{task_id}/{state}/{model}/impl.md",
        );

        let workspace = tempfile::tempdir().expect("tmpdir");
        record_transition(workspace.path(), "1 implement@review");
        let artifact =
            workspace.path().join("runtime/handoffs/1/implement/producer-model/impl.md");
        std::fs::create_dir_all(artifact.parent().expect("parent")).expect("mkdir");
        std::fs::write(&artifact, "Parser rewritten; tests green.\n").expect("write handoff");

        // The successor runs on a different model than the producer did.
        let context =
            handoff_context(workspace.path(), &rhei, &machine, Some("consumer-model"));
        let prompt = compose_agent_prompt(&context).expect("prompt");

        assert!(prompt.contains("## Handoff from implement"), "{prompt}");
        assert!(prompt.contains("Parser rewritten; tests green."), "{prompt}");
    }

    /// `outputs:` is an existence contract, so an agent can satisfy it with an
    /// empty file. A required handoff must not accept that as context.
    /// §FS-rhei-states.3.2
    #[test]
    fn required_state_handoff_rejects_an_empty_artifact() {
        let rhei = handoff_plan();
        let machine = handoff_machine("", "", "runtime/handoffs/{task_id}/{state}/impl.md");

        let workspace = tempfile::tempdir().expect("tmpdir");
        record_transition(workspace.path(), "1 implement@review");
        let artifact = workspace.path().join("runtime/handoffs/1/implement/impl.md");
        std::fs::create_dir_all(artifact.parent().expect("parent")).expect("mkdir");
        std::fs::write(&artifact, "   \n\n").expect("write empty handoff");

        let context = handoff_context(workspace.path(), &rhei, &machine, None);
        let err = compose_agent_prompt(&context).expect_err("empty handoff should fail");
        let message = format!("{err:?}");

        assert!(message.contains("no handoff artifact with content"), "{message}");
        assert!(message.contains("impl.md"), "error should name what it looked for: {message}");
    }

    /// `transition.previous` reads the central ledger, which is where state
    /// history lives. §FS-rhei-complete.3.1
    #[test]
    fn state_handoff_reads_the_source_state_from_the_transition_ledger() {
        let rhei = handoff_plan();
        let machine = handoff_machine("", "", "runtime/handoffs/{task_id}/{state}/impl.md");

        let workspace = tempfile::tempdir().expect("tmpdir");
        let artifact = workspace.path().join("runtime/handoffs/1/implement/impl.md");
        std::fs::create_dir_all(artifact.parent().expect("parent")).expect("mkdir");
        std::fs::write(&artifact, "notes\n").expect("write handoff");

        // No ledger entry yet: nothing records how the task reached `review`.
        let context = handoff_context(workspace.path(), &rhei, &machine, None);
        let err = compose_agent_prompt(&context).expect_err("no recorded transition");
        // Match a fragment short enough to survive miette's line wrapping.
        assert!(
            format!("{err:?}").contains("transition into this state was recorded"),
            "{err:?}"
        );

        // The last entry naming `review` as its destination picks the source.
        let runtime = workspace.path().join("runtime");
        std::fs::write(
            runtime.join("state-transitions.log"),
            "1 pending@implement\n1 implement@review\n",
        )
        .expect("write ledger");
        let prompt = compose_agent_prompt(&context).expect("prompt");
        assert!(prompt.contains("## Handoff from implement"), "{prompt}");
        assert!(prompt.contains("notes"), "{prompt}");
    }

    /// A consumed export reaches the agent as prompt context, and the exports
    /// this task publishes are named with the path the agent must write.
    /// §FS-rhei-agents.3.1
    #[test]
    fn compose_agent_prompt_carries_task_exports() {
        let rhei = rhei_core::parse(
            r#"# Rhei: Exports

## Tasks

### Task 1: Design the API
**State:** done
**Provides:** api-contract

### Task 2: Implement the client
**State:** review
**Prior:** Task 1
**Consumes:** 1:api-contract
**Provides:** client-notes
"#,
        )
        .expect("plan should parse");
        let machine = rhei_validator::StateMachine::from_yaml_str(
            r#"
name: exports
version: 1
states:
  review:
    description: review
    instructions: Implement it.
    initial: true
  done:
    description: done
    final: true
transitions:
  - from: review
    to: done
"#,
        )
        .expect("machine should parse");

        let workspace = tempfile::tempdir().expect("tmpdir");
        let export = workspace.path().join("runtime/exports/1/api-contract.md");
        std::fs::create_dir_all(export.parent().expect("parent")).expect("mkdir");
        std::fs::write(&export, "POST /v1/session returns a token.\n").expect("write export");

        let task = &rhei.tasks[1];
        let context = RuntimeTemplateContext {
            task_roots: None,
            workspace_root: workspace.path(),
            checkout_root: workspace.path(),
            plan_path: workspace.path(),
            state_machine_path: None,
            plan_title: &rhei.title,
            task,
            state_name: "review",
            current_state_raw: "review",
            machine: &machine,
            metadata: None,
            target: None,
            model: None,
            model_provider: None,
            model_name: None,
            agent: Some("codex"),
            agent_mode: None,
            tooling: None,
        };

        let prompt = compose_agent_prompt(&context).expect("prompt");

        assert!(prompt.contains("## Consumed Exports"), "{prompt}");
        assert!(prompt.contains("### api-contract from Task 1"), "{prompt}");
        assert!(prompt.contains("POST /v1/session returns a token."), "{prompt}");
        assert!(prompt.contains("## Exports to Publish"), "{prompt}");
        assert!(prompt.contains("`runtime/exports/2/client-notes.md`"), "{prompt}");
        // `review -> done` finishes the ticket, so the agent is told where the
        // result goes — it never calls `rhei complete` itself.
        // §FS-rhei-agents.3 §FS-rhei-states.3.3
        assert!(prompt.contains("## Result"), "{prompt}");
        assert!(prompt.contains("`runtime/results/2.md`"), "{prompt}");
    }

    /// The `## Result` section appears only where it applies: a state with no
    /// declared edge into a `final: true` state cannot finish the ticket, so
    /// naming the result path there would be noise.
    // §FS-rhei-agents.3
    #[test]
    fn compose_agent_prompt_omits_the_result_section_when_the_state_cannot_finish() {
        let rhei = rhei_core::parse(
            r#"# Rhei: Mid Flight

## Tasks

### Task 1: Implement
**State:** implement
"#,
        )
        .expect("plan should parse");
        let machine = rhei_validator::StateMachine::from_yaml_str(
            r#"
name: mid-flight
version: 1
states:
  implement:
    description: implement
    instructions: Implement it.
    initial: true
  review:
    description: review
  done:
    description: done
    final: true
transitions:
  - from: implement
    to: review
  - from: review
    to: done
"#,
        )
        .expect("machine should parse");

        let workspace = tempfile::tempdir().expect("tmpdir");
        let task = &rhei.tasks[0];
        let context = RuntimeTemplateContext {
            task_roots: None,
            workspace_root: workspace.path(),
            checkout_root: workspace.path(),
            plan_path: workspace.path(),
            state_machine_path: None,
            plan_title: &rhei.title,
            task,
            state_name: "implement",
            current_state_raw: "implement",
            machine: &machine,
            metadata: None,
            target: None,
            model: None,
            model_provider: None,
            model_name: None,
            agent: Some("codex"),
            agent_mode: None,
            tooling: None,
        };

        let prompt = compose_agent_prompt(&context).expect("prompt");
        assert!(!prompt.contains("## Result"), "{prompt}");
    }

    /// A wildcard escape hatch does not make a state one that can finish the
    /// ticket. Nearly every machine declares `* -> cancelled`, so counting it
    /// put the `## Result` section on the first state of every workflow — and an
    /// agent that writes a result three states early pre-satisfies the
    /// obligation at the real terminal edge with a stale message. The gate
    /// surfaces filter wildcards out of a gate's choices for the same reason.
    // §FS-rhei-agents.3 §FS-rhei-states.3.3
    #[test]
    fn compose_agent_prompt_omits_the_result_section_for_a_wildcard_terminal_edge() {
        let rhei = rhei_core::parse(
            r#"# Rhei: Wildcard Escape

## Tasks

### Task 1: Implement
**State:** implement
"#,
        )
        .expect("plan should parse");
        let machine = rhei_validator::StateMachine::from_yaml_str(
            r#"
name: wildcard-escape
version: 1
states:
  implement:
    description: implement
    instructions: Implement it.
    initial: true
  review:
    description: review
  done:
    description: done
    final: true
  cancelled:
    description: cancelled
    final: true
transitions:
  - from: implement
    to: review
  - from: review
    to: done
  - from: "*"
    to: cancelled
"#,
        )
        .expect("machine should parse");

        let workspace = tempfile::tempdir().expect("tmpdir");
        let task = &rhei.tasks[0];
        let mut context = RuntimeTemplateContext {
            task_roots: None,
            workspace_root: workspace.path(),
            checkout_root: workspace.path(),
            plan_path: workspace.path(),
            state_machine_path: None,
            plan_title: &rhei.title,
            task,
            state_name: "implement",
            current_state_raw: "implement",
            machine: &machine,
            metadata: None,
            target: None,
            model: None,
            model_provider: None,
            model_name: None,
            agent: Some("codex"),
            agent_mode: None,
            tooling: None,
        };

        let prompt = compose_agent_prompt(&context).expect("prompt");
        assert!(!prompt.contains("## Result"), "{prompt}");

        // The state that really can finish it still gets the section.
        context.state_name = "review";
        context.current_state_raw = "review";
        let prompt = compose_agent_prompt(&context).expect("prompt");
        assert!(prompt.contains("## Result"), "{prompt}");
        assert!(prompt.contains("`runtime/results/1.md`"), "{prompt}");
    }

    /// A fanned-out invocation is shown its own fragment, which is what its
    /// `RHEI_RESULT_PATH` holds: one shared path would let the last writer erase
    /// its siblings. §FS-rhei-agents.3 §FS-rhei-states.3.3
    #[test]
    fn compose_agent_prompt_names_the_per_invocation_result_fragment_under_fanout() {
        let rhei = rhei_core::parse(
            r#"# Rhei: Fanout Prompt

## Tasks

### Task 1: Review
**State:** review
"#,
        )
        .expect("plan should parse");
        let machine = rhei_validator::StateMachine::from_yaml_str(
            r#"
name: fanout-prompt
version: 1
models:
  - alpha
  - beta
states:
  review:
    description: review
    instructions: Review it.
    initial: true
    all_models:
      - alpha
      - beta
  done:
    description: done
    final: true
transitions:
  - from: review
    to: done
"#,
        )
        .expect("machine should parse");

        let workspace = tempfile::tempdir().expect("tmpdir");
        let task = &rhei.tasks[0];
        let context = RuntimeTemplateContext {
            task_roots: None,
            workspace_root: workspace.path(),
            checkout_root: workspace.path(),
            plan_path: workspace.path(),
            state_machine_path: None,
            plan_title: &rhei.title,
            task,
            state_name: "review",
            current_state_raw: "review",
            machine: &machine,
            metadata: None,
            target: None,
            model: Some("alpha"),
            model_provider: None,
            model_name: None,
            agent: Some("codex"),
            agent_mode: None,
            tooling: None,
        };

        let prompt = compose_agent_prompt(&context).expect("prompt");
        // State and visit key the fragment too, so a later fanned-out state
        // cannot be answered with this one's account. §FS-rhei-states.3.3
        assert!(prompt.contains("`runtime/results/1/review/1/alpha.md`"), "{prompt}");
        assert!(!prompt.contains("`runtime/results/1.md`"), "{prompt}");
    }

    /// An export a prior task never wrote is skipped, not raised: enforcement
    /// belongs to a validator, and a missing file must not block the spawn.
    #[test]
    fn compose_agent_prompt_skips_an_unwritten_export() {
        let rhei = rhei_core::parse(
            r#"# Rhei: Exports

## Tasks

### Task 1: Design the API
**State:** review
**Provides:** api-contract

### Task 2: Implement the client
**State:** review
**Prior:** Task 1
**Consumes:** 1:api-contract
"#,
        )
        .expect("plan should parse");
        let machine = rhei_validator::StateMachine::from_yaml_str(
            r#"
name: exports
version: 1
states:
  review:
    description: review
    instructions: Implement it.
    initial: true
  done:
    description: done
    final: true
transitions:
  - from: review
    to: done
"#,
        )
        .expect("machine should parse");

        let workspace = tempfile::tempdir().expect("tmpdir");
        let task = &rhei.tasks[1];
        let context = RuntimeTemplateContext {
            task_roots: None,
            workspace_root: workspace.path(),
            checkout_root: workspace.path(),
            plan_path: workspace.path(),
            state_machine_path: None,
            plan_title: &rhei.title,
            task,
            state_name: "review",
            current_state_raw: "review",
            machine: &machine,
            metadata: None,
            target: None,
            model: None,
            model_provider: None,
            model_name: None,
            agent: Some("codex"),
            agent_mode: None,
            tooling: None,
        };

        let prompt = compose_agent_prompt(&context).expect("prompt");

        assert!(!prompt.contains("## Consumed Exports"), "{prompt}");
    }