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
    fn parse_template_source_filter(value: &str) -> MietteResult<TemplateSourceFilter> {
        match value.trim().to_ascii_lowercase().as_str() {
            "project" => Ok(TemplateSourceFilter::Project),
            "user" => Ok(TemplateSourceFilter::User),
            "builtin" | "built-in" => Ok(TemplateSourceFilter::Builtin),
            "all" => Ok(TemplateSourceFilter::All),
            other => Err(miette!(
                help = "pass --source project, --source user, --source builtin, or \
                        --source all.",
                "invalid template source '{}'. Expected one of: project, user, builtin, all",
                other
            )),
        }
    }

    fn discover_templates(filter: TemplateSourceFilter) -> MietteResult<Vec<DiscoveredTemplate>> {
        let mut templates = Vec::new();
        let mut seen = HashSet::new();

        for (source, root) in template_search_roots(filter)? {
            if source == TemplateSource::Builtin {
                // Built-ins have no search root: they live in the binary and are
                // extracted only when one is actually instantiated. Listing them
                // reads the embedded manifest instead. §FS-rhei-templates.1
                for name in builtin_template_names() {
                    if seen.contains(&name) {
                        continue;
                    }
                    let Ok(extracted) = materialize_builtin_template(&name) else {
                        continue;
                    };
                    let Ok(manifest) = load_template_manifest(extracted.path()) else {
                        continue;
                    };
                    seen.insert(name.clone());
                    templates.push(DiscoveredTemplate {
                        manifest,
                        // A built-in has no stable on-disk location; the name is
                        // how it is referenced.
                        path: PathBuf::from(&name),
                        source,
                    });
                }
                continue;
            }
            if !root.is_dir() {
                continue;
            }

            let mut entries = fs::read_dir(&root)
                .map_err(|err| file_io_report(&root, "failed to read template directory", err))?
                .collect::<Result<Vec<_>, _>>()
                .map_err(|err| {
                    miette!(
                        help = "check that the templates directory is readable, then re-run: rhei templates",
                        "failed to read dir entry in '{}': {err}", root.display()
                    )
                })?;
            entries.sort_by_key(|entry| entry.file_name());

            for entry in entries {
                let path = entry.path();
                let name = entry.file_name().to_string_lossy().to_string();
                if name.starts_with('.') || !path.is_dir() || seen.contains(&name) {
                    continue;
                }

                let Ok(manifest) = load_template_manifest(&path) else {
                    continue;
                };

                seen.insert(name);
                templates.push(DiscoveredTemplate { manifest, path, source });
            }
        }

        Ok(templates)
    }

    fn template_search_roots(
        filter: TemplateSourceFilter,
    ) -> MietteResult<Vec<(TemplateSource, PathBuf)>> {
        let mut roots = Vec::new();

        if filter.includes(TemplateSource::Project) {
            roots.push((
                TemplateSource::Project,
                project_template_root()?,
            ));
        }
        if filter.includes(TemplateSource::User) {
            roots.push((
                TemplateSource::User,
                home_dir()?.join(".agents").join("rhei").join("templates"),
            ));
        }
        if filter.includes(TemplateSource::Builtin) {
            // Placeholder path: built-ins are embedded, so this root is never
            // read. It exists so the tier keeps its place in the search order
            // and can be named in the "searched" listing.
            roots.push((TemplateSource::Builtin, PathBuf::from("<compiled into the rhei binary>")));
        }

        Ok(roots)
    }

    fn project_template_root() -> MietteResult<PathBuf> {
        // §FS-rhei-templates.1: project-local templates live under the nearest
        // `.agents/rhei/templates`, even when an unrelated parent has VCS markers.
        if let Some(root) = nearest_project_template_root()? {
            return Ok(root);
        }
        Ok(find_project_root()?.join(".agents").join("rhei").join("templates"))
    }

    fn nearest_project_template_root() -> MietteResult<Option<PathBuf>> {
        let cwd = std::env::current_dir()
            .map_err(|e| miette!(
                help = cwd_help(),
                "failed to determine working directory: {e}"
            ))?;
        let mut dir = Some(cwd.as_path());
        while let Some(current) = dir {
            let candidate = current.join(".agents").join("rhei").join("templates");
            if candidate.is_dir() {
                return Ok(Some(candidate));
            }
            dir = current.parent();
        }
        Ok(None)
    }

    /// A template resolved to a directory the instantiation pipeline can read.
    ///
    /// A built-in is extracted from the binary into a temporary directory; the
    /// handle is carried here so the extraction lives exactly as long as the
    /// resolved template is in use.
    struct ResolvedTemplate {
        path: PathBuf,
        _extracted: Option<ExtractedTemplate>,
    }

    impl ResolvedTemplate {
        fn path(&self) -> &Path {
            &self.path
        }
    }

    fn resolve_template_reference(reference: &str) -> MietteResult<ResolvedTemplate> {
        if template_reference_is_path(reference) {
            let path = PathBuf::from(reference);
            if !path.is_dir() {
                return Err(miette!(
                    help = "a template reference containing '/' is treated as a path. Point it at \
                            the directory holding template.yaml, or drop the '/' to use a \
                            template by name: rhei templates",
                    "template directory '{}' does not exist",
                    path.display()
                ));
            }
            return Ok(ResolvedTemplate { path, _extracted: None });
        }

        for (source, root) in template_search_roots(TemplateSourceFilter::All)? {
            if source == TemplateSource::Builtin {
                // Lowest priority: a project or user template of the same name
                // has already won by the time the search reaches here.
                if builtin_template_exists(reference) {
                    let extracted = materialize_builtin_template(reference)?;
                    return Ok(ResolvedTemplate {
                        path: extracted.path().to_path_buf(),
                        _extracted: Some(extracted),
                    });
                }
                continue;
            }
            let candidate = root.join(reference);
            if candidate.is_dir() {
                return Ok(ResolvedTemplate { path: candidate, _extracted: None });
            }
        }

        let names = discover_templates(TemplateSourceFilter::All)?
            .into_iter()
            .map(|template| template.manifest.name)
            .collect::<Vec<_>>();

        // §FS-rhei-templates.6.1.2: named-template lookup reports a close discovered match.
        // §FS-rhei-errors.1.3: and when nothing is close, it says how to see the list.
        let hint = nearest_match(reference, &names)
            .map(|name| format!("Did you mean '{name}'? "))
            .unwrap_or_default();
        Err(miette!(
            help = format!("{hint}List the templates you can instantiate with: rhei templates"),
            "template '{}' not found among project, user, or built-in templates",
            reference
        ))
    }

    fn template_reference_is_path(reference: &str) -> bool {
        let path = Path::new(reference);
        path.is_absolute() || reference.contains('/') || reference.starts_with('.')
    }

    fn load_template_manifest(template_dir: &Path) -> MietteResult<TemplateManifest> {
        let manifest_path = template_dir.join("template.yaml");
        let raw = fs::read_to_string(&manifest_path).map_err(|err| {
            file_io_report(&manifest_path, "failed to read template manifest", err)
        })?;
        let manifest: TemplateManifest = serde_yaml::from_str(&raw)
            .map_err(|err| miette!(
                help = template_manifest_help(),
                "failed to parse '{}': {err}", manifest_path.display()
            ))?;
        validate_template_manifest(&manifest, template_dir)?;
        Ok(manifest)
    }

    fn validate_template_manifest(
        manifest: &TemplateManifest,
        template_dir: &Path,
    ) -> MietteResult<()> {
        let dir_name =
            template_dir.file_name().and_then(|name| name.to_str()).ok_or_else(|| {
                miette!(
                    help = template_manifest_help(),
                    "template path '{}' has no directory name", template_dir.display()
                )
            })?;
        let ident = Regex::new(r"^[A-Za-z][A-Za-z0-9_-]*$")
            .expect("template identifier regex should be valid");

        if manifest.name != dir_name {
            return Err(miette!(
                help = template_manifest_help(),
                "template manifest name '{}' does not match directory '{}'",
                manifest.name,
                dir_name
            ));
        }
        if !ident.is_match(&manifest.name) {
            return Err(miette!(
                help = template_manifest_help(),
                "template name '{}' is not a valid identifier", manifest.name
            ));
        }
        if manifest.description.trim().is_empty() {
            return Err(miette!(
                help = template_manifest_help(),
                "template '{}' must include a non-empty description",
                manifest.name
            ));
        }

        let cwd = std::env::current_dir()
            .map_err(|err| miette!(
                help = cwd_help(),
                "failed to determine working directory: {err}"
            ))?;
        let mut seen = HashSet::new();
        let mut positional_indexes = Vec::new();

        for input in &manifest.inputs {
            if !ident.is_match(&input.name) {
                return Err(miette!(
                    help = template_manifest_help(),
                    "template '{}' input '{}' is not a valid identifier",
                    manifest.name,
                    input.name
                ));
            }
            if !seen.insert(input.name.as_str()) {
                return Err(miette!(
                    help = template_manifest_help(),
                    "template '{}' declares duplicate input '{}'",
                    manifest.name,
                    input.name
                ));
            }
            if input.description.trim().is_empty() {
                return Err(miette!(
                    help = template_manifest_help(),
                    "template '{}' input '{}' must include a description",
                    manifest.name,
                    input.name
                ));
            }
            if let Some(index) = input.positional {
                if index == 0 {
                    return Err(miette!(
                        help = template_manifest_help(),
                        "template '{}' input '{}' positional index must be >= 1",
                        manifest.name,
                        input.name
                    ));
                }
                positional_indexes.push((index, input.name.as_str()));
            }
            if input.schema.required == Some(true) && input.schema.default.is_some() {
                return Err(miette!(
                    help = template_manifest_help(),
                    "template '{}' input '{}' cannot set both required: true and default",
                    manifest.name,
                    input.name
                ));
            }
            validate_template_value_schema(&manifest.name, &input.name, &input.schema)?;
            if let Some(default) = input.schema.default.as_ref() {
                let _ = coerce_template_input_value(input, default, &cwd, true)?;
            }
        }

        positional_indexes.sort_by_key(|(index, _)| *index);
        for (expected, (actual, name)) in positional_indexes.iter().enumerate() {
            let expected = expected + 1;
            if *actual != expected {
                return Err(miette!(
                    help = template_manifest_help(),
                    "template '{}' input '{}' declares positional {}, but positional indexes must be unique and contiguous starting at 1",
                    manifest.name,
                    name,
                    actual
                ));
            }
        }

        let _ = detect_template_layout(template_dir)?;

        Ok(())
    }

    fn validate_template_value_schema(
        template_name: &str,
        label: &str,
        schema: &TemplateValueSchema,
    ) -> MietteResult<()> {
        if let Some(pattern) = schema.validate.as_deref() {
            if matches!(schema.value_type, TemplateInputType::Array | TemplateInputType::Object) {
                return Err(miette!(
                    help = template_manifest_help(),
                    "template '{}' input '{}' cannot set validate on {} values",
                    template_name,
                    label,
                    schema.value_type.as_str()
                ));
            }
            let _ = compile_full_match_regex(pattern).map_err(|err| {
                miette!(
                    help = template_manifest_help(),
                    "template '{}' input '{}' has invalid validate regex: {err}",
                    template_name,
                    label
                )
            })?;
        }

        if let Some(format) = schema.format {
            if matches!(schema.value_type, TemplateInputType::Array | TemplateInputType::Object) {
                return Err(miette!(
                    help = format!(
                        "move `format: {}` onto the scalar it applies to — the array's `items` \
                         entry or the object property — instead of the {} itself.",
                        format.as_str(),
                        schema.value_type.as_str()
                    ),
                    "template '{}' input '{}' cannot set format on {} values",
                    template_name,
                    label,
                    schema.value_type.as_str()
                ));
            }
        }

        match schema.value_type {
            TemplateInputType::Array => {
                let Some(items) = schema.items.as_deref() else {
                    return Err(miette!(
                        help = template_manifest_help(),
                        "template '{}' input '{}' with type array must declare items",
                        template_name,
                        label
                    ));
                };
                if !schema.properties.is_empty() {
                    return Err(miette!(
                        help = template_manifest_help(),
                        "template '{}' input '{}' with type array cannot declare properties",
                        template_name,
                        label
                    ));
                }
                validate_template_value_schema(template_name, label, items)?;
            }
            TemplateInputType::Object => {
                if schema.items.is_some() {
                    return Err(miette!(
                        help = template_manifest_help(),
                        "template '{}' input '{}' with type object cannot declare items",
                        template_name,
                        label
                    ));
                }
                for (property, property_schema) in &schema.properties {
                    validate_template_value_schema(
                        template_name,
                        &format!("{label}.{property}"),
                        property_schema,
                    )?;
                }
            }
            _ => {
                if schema.items.is_some() {
                    return Err(miette!(
                        help = template_manifest_help(),
                        "template '{}' input '{}' with type {} cannot declare items",
                        template_name,
                        label,
                        schema.value_type.as_str()
                    ));
                }
                if !schema.properties.is_empty() {
                    return Err(miette!(
                        help = template_manifest_help(),
                        "template '{}' input '{}' with type {} cannot declare properties",
                        template_name,
                        label,
                        schema.value_type.as_str()
                    ));
                }
            }
        }

        Ok(())
    }

    fn detect_template_layout(template_dir: &Path) -> MietteResult<TemplateLayout> {
        let plan_path = template_dir.join("plan.rhei.md");
        let index_path = template_dir.join("index.rhei.md");
        let has_plan = plan_path.is_file();
        let has_index = index_path.is_file();

        match (has_plan, has_index) {
            (true, false) => Ok(TemplateLayout::SingleFile),
            (false, true) => {
                let tasks_dir = template_dir.join("tasks");
                if !tasks_dir.is_dir() {
                    return Err(miette!(
                        help = template_manifest_help(),
                        "template '{}' is a workspace template but is missing tasks/",
                        template_dir.display()
                    ));
                }
                Ok(TemplateLayout::Workspace)
            }
            (true, true) => Err(miette!(
                help = template_manifest_help(),
                "template '{}' contains both plan.rhei.md and index.rhei.md",
                template_dir.display()
            )),
            (false, false) => Err(miette!(
                help = template_manifest_help(),
                "template '{}' must contain either plan.rhei.md or index.rhei.md",
                template_dir.display()
            )),
        }
    }

    fn collect_template_inputs(
        manifest: &TemplateManifest,
        template_ref: &str,
        values_files: &[PathBuf],
        input_args: &[String],
        set_values: &[String],
        set_files: &[String],
    ) -> MietteResult<BTreeMap<String, serde_json::Value>> {
        let cwd = std::env::current_dir()
            .map_err(|err| miette!(
                help = cwd_help(),
                "failed to determine working directory: {err}"
            ))?;
        let mut raw_values: BTreeMap<String, YamlValue> = BTreeMap::new();

        for values_file in values_files {
            let loaded = load_template_values_file(values_file)?;
            for (key, value) in loaded {
                raw_values.insert(key, value);
            }
        }

        let parsed_input_args = parse_template_input_args(manifest, input_args)?;
        for (key, value) in parsed_input_args.positional_values {
            raw_values.insert(key, YamlValue::String(value));
        }
        for (key, value) in parsed_input_args.assignments {
            raw_values.insert(key, YamlValue::String(value));
        }

        for assignment in set_values {
            let (key, value) = parse_assignment(assignment, "--set")?;
            raw_values.insert(key, YamlValue::String(value));
        }

        for assignment in set_files {
            let (key, value_path) = parse_assignment(assignment, "--set-file")?;
            let path = PathBuf::from(value_path);
            let contents = fs::read_to_string(&path)
                .map_err(|err| file_io_report(&path, "failed to read --set-file input", err))?;
            raw_values.insert(key, YamlValue::String(contents));
        }

        let declared_inputs =
            manifest.inputs.iter().map(|input| input.name.clone()).collect::<Vec<_>>();
        for key in raw_values.keys() {
            if !declared_inputs.iter().any(|name| name == key) {
                // §FS-rhei-errors.1.3: name the near miss instead of leaving the
                // user to diff their spelling against `--list-inputs` output.
                return Err(miette!(
                    help = format!(
                        "{}List every input with: {}",
                        did_you_mean(key, &declared_inputs)
                            .map(|hint| format!("{hint} "))
                            .unwrap_or_default(),
                        list_inputs_command(template_ref)
                    ),
                    "template '{}' has no input named '{}'",
                    manifest.name,
                    key
                ));
            }
        }

        // Report every missing input at once: one at a time turns supplying
        // inputs into a guessing loop where each attempt buys exactly one more
        // field name. §FS-rhei-templates.6.1.1 §FS-rhei-errors.1.1
        let missing = manifest
            .inputs
            .iter()
            .filter(|input| {
                input.is_required()
                    && input.schema.default.is_none()
                    && !raw_values.contains_key(&input.name)
            })
            .collect::<Vec<_>>();
        if !missing.is_empty() {
            return Err(missing_template_inputs_report(
                manifest,
                template_ref,
                &missing,
                values_files,
                input_args,
                set_values,
                set_files,
            ));
        }

        // §FS-rhei-errors.1.1: a rejected value is the same failure class as a
        // missing one, so a three-input mistake costs one round trip, not three.
        let mut resolved = BTreeMap::new();
        let mut rejected = Vec::new();
        for input in &manifest.inputs {
            let value = if let Some(raw) = raw_values.get(&input.name) {
                coerce_template_input_value(input, raw, &cwd, false)
            } else if let Some(default) = input.schema.default.as_ref() {
                coerce_template_input_value(input, default, &cwd, true)
            } else {
                Ok(empty_template_value(&input.schema))
            };

            let value = match value {
                Ok(value) => value,
                Err(report) => {
                    rejected.push((input.name.clone(), report));
                    continue;
                }
            };

            if let Err(report) = validate_resolved_value(&input.name, &input.schema, &value) {
                rejected.push((input.name.clone(), report));
                continue;
            }

            resolved.insert(input.name.clone(), value);
        }
        if !rejected.is_empty() {
            return Err(rejected_template_inputs_report(rejected, template_ref));
        }

        Ok(resolved)
    }

    /// Fold the per-input rejections into one diagnostic, keeping each input's
    /// own message and its own remedy. §FS-rhei-errors.1.1
    fn rejected_template_inputs_report(
        rejected: Vec<(String, Report)>,
        template_ref: &str,
    ) -> Report {
        // One bad input is already a complete diagnostic; wrapping it would only
        // bury its remedy under a summary line.
        if rejected.len() == 1 {
            let (_, report) = rejected.into_iter().next().expect("exactly one rejection");
            return with_list_inputs_pointer(&report, template_ref);
        }

        let listed = rejected
            .iter()
            .map(|(_, report)| format!("  {report}"))
            .collect::<Vec<_>>()
            .join("\n");
        // Remedies go in the help block, not the message: miette re-indents a
        // wrapped help line and does not re-indent a wrapped message line, so a
        // remedy nested into the message loses its nesting on a narrow terminal.
        // Each is prefixed with the input it repairs, which is what pairs it
        // with its failure now that the two are no longer adjacent.
        let remedies = rejected
            .iter()
            .filter_map(|(name, report)| {
                report.help().map(|help| {
                    let text = help.to_string();
                    let joined =
                        text.lines().map(str::trim).collect::<Vec<_>>().join(" ");
                    format!("{name}: {joined}")
                })
            })
            .collect::<Vec<_>>()
            .join("\n");
        miette!(
            help = format!(
                "{remedies}\nSee what every input accepts: {}",
                list_inputs_command(template_ref)
            ),
            "{} inputs were rejected:\n{listed}",
            rejected.len()
        )
    }

    /// The same report with `--list-inputs` appended to its help. Added here,
    /// not by each check, so a batch prints it once. §FS-rhei-errors.1.2
    fn with_list_inputs_pointer(report: &Report, template_ref: &str) -> Report {
        let pointer =
            format!("See what every input accepts: {}", list_inputs_command(template_ref));
        let help = match report.help() {
            Some(help) => format!("{help}\n{pointer}"),
            None => pointer,
        };
        miette!(help = help, "{report}")
    }

    /// Check a resolved scalar against the named `format` its input declares,
    /// so the failure names the input the user typed. §FS-rhei-errors.3.1
    fn validate_template_input_format(
        label: &str,
        format: TemplateInputFormat,
        rendered: &str,
    ) -> MietteResult<()> {
        match format {
            TemplateInputFormat::ExecutionTarget => {
                rhei_validator::parse_execution_target(rendered).map_err(|err| {
                    // §FS-rhei-errors.1.2: the example is keyed to what the
                    // user can actually type, not to the label.
                    miette!(
                        help = format!(
                            "{err}.\n{}",
                            execution_target_repair_example(label, rendered)
                        ),
                        "input '{}' is not a valid execution target: '{}'",
                        label,
                        rendered
                    )
                })?;
                Ok(())
            }
        }
    }

    /// A corrected value for `label`, written the way the user would supply it:
    /// an assignment for a top-level input, and for a nested scalar the value
    /// alone, since `reviewers[0]=…` is not CLI syntax. §FS-rhei-errors.1.2
    fn execution_target_repair_example(label: &str, rendered: &str) -> String {
        let example = rhei_validator::execution_target_example(rendered);
        let nested = label.contains('[') || label.contains('.');
        if !nested {
            return format!("A corrected value for this input: {}", shell_assignment(label, &example));
        }
        let root = label.split(['[', '.']).next().unwrap_or(label);
        format!(
            "A corrected value for '{label}': {}. Supply it inside the whole '{root}' value, \
             which is written as one YAML or JSON literal.",
            shell_quote(&example)
        )
    }

    /// The command that lists a template's inputs, quoted for paste.
    fn list_inputs_command(template_ref: &str) -> String {
        shell_command(["rhei", "instantiate", template_ref, "--list-inputs"])
    }

    /// Build the "you are missing these inputs" diagnostic: every missing name
    /// with its description, and a runnable command that carries the arguments
    /// already supplied. §FS-rhei-errors.1
    #[allow(clippy::too_many_arguments)]
    fn missing_template_inputs_report(
        manifest: &TemplateManifest,
        template_ref: &str,
        missing: &[&TemplateInputDef],
        values_files: &[PathBuf],
        input_args: &[String],
        set_values: &[String],
        set_files: &[String],
    ) -> Report {
        let listed = missing
            .iter()
            .map(|input| {
                format!("  {} ({}) — {}", input.name, input.value_type().as_str(), input.description)
            })
            .collect::<Vec<_>>()
            .join("\n");

        let placeholders = missing
            .iter()
            .map(|input| format!("{}={}", input.name, template_input_placeholder(input)))
            .collect::<Vec<_>>();
        let command = format_template_instantiation_command(
            template_ref,
            input_args,
            set_values,
            set_files,
            values_files,
            None,
            &placeholders,
        );

        // Name the input most likely to hold prose, not merely the first string
        // one: suggesting `--set-file subject=<path>` for a one-word title while
        // the essay-length brief sits below it reads as noise.
        let long_value_hint = missing
            .iter()
            .filter(|input| matches!(input.value_type(), TemplateInputType::String))
            .max_by_key(|input| input.description.chars().count())
            .map(|input| {
                format!(
                    "\nFor a long value, read it from a file: --set-file {}=<path>",
                    input.name
                )
            })
            .unwrap_or_default();

        let noun = if missing.len() == 1 { "input" } else { "inputs" };
        miette!(
            help = format!(
                "replace each <…> and run:\n  {command}{long_value_hint}\nList every input \
                 with: {}",
                list_inputs_command(template_ref)
            ),
            "template '{}' is missing {} required {noun}:\n{listed}",
            manifest.name,
            missing.len()
        )
    }

    /// A placeholder that shows the shape of a value rather than the word
    /// "value" — arrays and objects are supplied as YAML/JSON snippets, and a
    /// user who is told `<value>` will guess wrong.
    fn template_input_placeholder(input: &TemplateInputDef) -> String {
        match input.value_type() {
            TemplateInputType::Number => "<number>".to_string(),
            TemplateInputType::Boolean => "<true|false>".to_string(),
            TemplateInputType::Path => "<path>".to_string(),
            TemplateInputType::Array => "<[item, item]>".to_string(),
            TemplateInputType::Object => "<{key: value}>".to_string(),
            TemplateInputType::String => "<value>".to_string(),
        }
    }

    /// Enforce each scalar `validate` pattern in `schema` against the matching
    /// scalar in the already-coerced `value`, recursing through array items and
    /// object properties. This is what makes `validate` declared on a nested
    /// `properties.<x>` or array `items` scalar take effect — not only on
    /// top-level inputs. Patterns are guaranteed valid here because
    /// `validate_template_value_schema` compiled them at manifest-load time.
    fn validate_resolved_value(
        label: &str,
        schema: &TemplateValueSchema,
        value: &serde_json::Value,
    ) -> MietteResult<()> {
        if let Some(pattern) = schema.validate.as_deref() {
            let regex = compile_full_match_regex(pattern).map_err(|err| {
                miette!(
                    help = internal_error_help(),
                    "input '{}' has invalid validate regex: {err}",
                    label
                )
            })?;
            let rendered = scalar_template_value_as_string(value).ok_or_else(|| {
                miette!(
                    help = internal_error_help(),
                    "input '{}' uses validate but did not resolve to a scalar string value",
                    label
                )
            })?;
            if !regex.is_match(&rendered) {
                return Err(miette!(
                    help = format!("'{rendered}' is rejected by the input's own pattern."),
                    "input '{}' does not match validation pattern '{}'",
                    label,
                    pattern
                ));
            }
        }

        // §FS-rhei-errors.3.1: a named format fails here, against the input the
        // user typed, instead of later against a rendered file they never wrote.
        if let Some(format) = schema.format {
            let rendered = scalar_template_value_as_string(value).ok_or_else(|| {
                miette!(
                    help = internal_error_help(),
                    "input '{}' uses format but did not resolve to a scalar value",
                    label
                )
            })?;
            validate_template_input_format(label, format, &rendered)?;
        }

        match schema.value_type {
            TemplateInputType::Array => {
                if let (Some(items), serde_json::Value::Array(elements)) =
                    (schema.items.as_deref(), value)
                {
                    for (idx, element) in elements.iter().enumerate() {
                        validate_resolved_value(
                            &format!("{label}[{idx}]"),
                            items,
                            element,
                        )?;
                    }
                }
            }
            TemplateInputType::Object => {
                if let serde_json::Value::Object(map) = value {
                    for (property, property_schema) in &schema.properties {
                        if let Some(element) = map.get(property) {
                            validate_resolved_value(
                                &format!("{label}.{property}"),
                                property_schema,
                                element,
                            )?;
                        }
                    }
                }
            }
            _ => {}
        }

        Ok(())
    }