bock-build 1.0.0

Build pipeline for Bock projects, coordinating parse, check, codegen, and target compilation
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
//! Toolchain detection and invocation for target compilation.
//!
//! After code generation produces target-language source files, this module
//! detects installed toolchains (node, rustc, go, python3, tsc) and invokes
//! the appropriate build/validation commands per target profile.

use std::collections::HashMap;
use std::fmt;
use std::path::{Path, PathBuf};
use std::process::Command;

/// Information about a target's toolchain requirements.
#[derive(Debug, Clone)]
pub struct ToolchainSpec {
    /// Target profile ID (e.g., "js", "rust", "go").
    pub target_id: String,
    /// Display name for error messages (e.g., "Node.js", "Rust compiler").
    pub display_name: String,
    /// Primary binary name to locate on PATH (e.g., "node", "rustc").
    pub binary_name: String,
    /// Arguments to get the toolchain version (e.g., ["--version"]).
    pub version_args: Vec<String>,
    /// Command and arguments used to validate/compile generated source.
    /// The source file path is appended as the last argument.
    pub compile_command: String,
    /// Arguments for the compile command (source path appended unless
    /// [`ToolchainSpec::validate_per_project`] is set).
    pub compile_args: Vec<String>,
    /// Whether the compile/validation command operates on the **whole emitted
    /// project directory** rather than one source file at a time.
    ///
    /// `false` (the default for interpreted/single-file targets) means the
    /// build driver runs `compile_command compile_args <file>` once per emitted
    /// source file (e.g. `node --check main.js`). `true` (rust/go, whose
    /// per-module output is a real Cargo crate / Go module — S3) means it runs
    /// `compile_command compile_args` **once** with the output directory as the
    /// working directory and **no** appended file path (e.g. `cargo check` /
    /// `go build` in `build/<target>/`); a per-file `src/<module>.rs` references
    /// `crate::…` paths and does not type-check in isolation.
    pub validate_per_project: bool,
    /// The plan for executing a built program and capturing its stdout.
    ///
    /// Distinct from [`ToolchainSpec::compile_command`]/[`ToolchainSpec::compile_args`],
    /// which only *validate* generated source (e.g. `node --check`, `tsc --noEmit`).
    /// Execution may require multiple ordered steps (e.g. Rust compiles then runs
    /// the produced binary); see [`RunPlan`].
    pub run_plan: RunPlan,
    /// Human-readable install instructions shown when toolchain is missing.
    pub install_hint: String,
}

/// How a [`RunStep`]'s `command` should be resolved when spawned.
///
/// This distinguishes "invoke a toolchain on PATH" from "execute a file the
/// previous step produced in the working directory". The distinction is what
/// makes execution cross-platform: a produced artifact is *not* on PATH and on
/// Windows carries an `.exe` suffix, so it must be spawned by its workdir path
/// (with [`std::env::consts::EXE_SUFFIX`] appended) rather than looked up like
/// a toolchain binary.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StepKind {
    /// `command` is a toolchain binary resolved on PATH (e.g. `node`, `rustc`,
    /// `python3`, `go`, `tsc`). Spawned by name; a spawn `NotFound` means the
    /// toolchain is missing.
    Toolchain,
    /// `command` is the base name of an artifact a prior step produced in the
    /// working directory (e.g. `main_bin`). It is spawned as
    /// `<workdir>/<command><EXE_SUFFIX>` — never resolved on PATH — so it runs
    /// portably on Windows (`main_bin.exe`) and Unix (`main_bin`) alike.
    Artifact,
}

/// A single command in a target's execution plan.
///
/// Steps run in order from the program's working directory. The entrypoint
/// file is always named `main.<ext>` (matching `bock build`'s emitted entry
/// module), so steps reference it by literal name rather than an interpolated
/// path. The *last* step's captured stdout is the program's output.
#[derive(Debug, Clone)]
pub struct RunStep {
    /// The program to invoke. Resolution depends on [`RunStep::kind`]:
    /// a [`StepKind::Toolchain`] command is looked up on PATH (e.g. `node`,
    /// `python3`); a [`StepKind::Artifact`] command is the base name of a
    /// produced binary spawned by its workdir path with the platform exe
    /// suffix appended.
    pub command: String,
    /// Literal arguments passed to `command`, in order.
    pub args: Vec<String>,
    /// Whether `command` is a PATH-resolved toolchain or a produced artifact.
    pub kind: StepKind,
}

impl RunStep {
    /// Construct a PATH-resolved toolchain step from a command name and string
    /// arguments (e.g. `node main.js`, `rustc … main.rs -o main_bin`).
    pub fn new(command: impl Into<String>, args: &[&str]) -> Self {
        Self {
            command: command.into(),
            args: args.iter().map(|a| (*a).to_string()).collect(),
            kind: StepKind::Toolchain,
        }
    }

    /// Construct a step that executes a produced artifact in the working
    /// directory. `name` is the artifact's base name (no exe suffix, no `./`):
    /// the platform [`EXE_SUFFIX`](std::env::consts::EXE_SUFFIX) is appended and
    /// the file is spawned by its workdir path, so it never goes through PATH /
    /// toolchain detection. Used for compiled targets such as Rust whose
    /// compile step writes `main_bin` (`main_bin.exe` on Windows).
    pub fn artifact(name: impl Into<String>) -> Self {
        Self {
            command: name.into(),
            args: Vec::new(),
            kind: StepKind::Artifact,
        }
    }
}

/// The ordered sequence of commands that compiles (if needed) and runs a
/// generated program, capturing the final step's stdout.
///
/// Single-step targets (interpreted languages) have one entry; compiled targets
/// such as Rust have a compile step followed by a run step. Every step must
/// exit zero or [`ToolchainRegistry::run`] reports the failing step.
#[derive(Debug, Clone)]
pub struct RunPlan {
    /// The steps to execute, in order. Must be non-empty.
    pub steps: Vec<RunStep>,
}

/// Result of successfully detecting a toolchain.
#[derive(Debug, Clone)]
pub struct DetectedToolchain {
    /// Target profile ID.
    pub target_id: String,
    /// Full path to the binary, or just the binary name if resolved via PATH.
    pub binary_path: PathBuf,
    /// Version string if detection succeeded.
    pub version: Option<String>,
}

/// Result of invoking a target compilation.
#[derive(Debug)]
pub struct CompilationResult {
    /// Target profile ID.
    pub target_id: String,
    /// The command that was executed.
    pub command: String,
    /// Standard output from the command.
    pub stdout: String,
    /// Standard error from the command.
    pub stderr: String,
    /// Whether the compilation succeeded.
    pub success: bool,
}

/// Result of executing a generated program and capturing its output.
///
/// Returned by [`ToolchainRegistry::run`]. Unlike [`CompilationResult`], a
/// non-zero `exit` is *not* an error at this layer — callers (e.g. the
/// conformance execution harness) decide whether a given exit code or stdout
/// constitutes a test failure.
#[derive(Debug, Clone)]
pub struct RunOutput {
    /// Target profile ID the program was run under (e.g. "js", "rust").
    pub target_id: String,
    /// The full command pipeline that was executed, joined with `&&` for display.
    pub command: String,
    /// Captured standard output of the final step.
    pub stdout: String,
    /// Captured standard error of the final step.
    pub stderr: String,
    /// Process exit code of the final step, if the process exited normally.
    pub exit: Option<i32>,
}

/// Errors that can occur during toolchain operations.
#[derive(Debug)]
pub enum ToolchainError {
    /// The required toolchain binary was not found on PATH.
    NotFound {
        /// Target profile ID.
        target_id: String,
        /// Binary that was looked for.
        binary_name: String,
        /// Human-readable install instructions.
        install_hint: String,
    },
    /// The toolchain was found but the compilation/validation command failed.
    InvocationFailed {
        /// Target profile ID.
        target_id: String,
        /// The full command that was run.
        command: String,
        /// Standard output (some compilers like tsc write errors here).
        stdout: String,
        /// Standard error output.
        stderr: String,
        /// Process exit code, if available.
        exit_code: Option<i32>,
    },
    /// An I/O error occurred while invoking the toolchain.
    Io(std::io::Error),
}

impl fmt::Display for ToolchainError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ToolchainError::NotFound {
                target_id,
                binary_name,
                install_hint,
            } => {
                write!(
                    f,
                    "Toolchain not found for target '{target_id}': \
                     '{binary_name}' is not installed or not on PATH.\n\
                     To install: {install_hint}"
                )
            }
            ToolchainError::InvocationFailed {
                target_id,
                command,
                stdout,
                stderr,
                exit_code,
            } => {
                let diagnostic = if !stderr.is_empty() { stderr } else { stdout };
                write!(
                    f,
                    "Compilation failed for target '{target_id}'.\n\
                     Command: {command}\n\
                     Exit code: {}\n\
                     output:\n{diagnostic}",
                    exit_code
                        .map(|c| c.to_string())
                        .unwrap_or_else(|| "signal".to_string())
                )
            }
            ToolchainError::Io(err) => write!(f, "I/O error during toolchain invocation: {err}"),
        }
    }
}

impl std::error::Error for ToolchainError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            ToolchainError::Io(err) => Some(err),
            _ => None,
        }
    }
}

impl From<std::io::Error> for ToolchainError {
    fn from(err: std::io::Error) -> Self {
        ToolchainError::Io(err)
    }
}

/// Registry of known toolchain specifications for all supported targets.
#[derive(Debug)]
pub struct ToolchainRegistry {
    specs: HashMap<String, ToolchainSpec>,
}

impl ToolchainRegistry {
    /// Creates a new empty registry.
    #[must_use]
    pub fn new() -> Self {
        Self {
            specs: HashMap::new(),
        }
    }

    /// Creates a registry pre-populated with all built-in target toolchains.
    #[must_use]
    pub fn with_builtins() -> Self {
        let mut registry = Self::new();
        registry.register(builtin_javascript_spec());
        registry.register(builtin_typescript_spec());
        registry.register(builtin_python_spec());
        registry.register(builtin_rust_spec());
        registry.register(builtin_go_spec());
        registry
    }

    /// Register a toolchain spec for a target.
    pub fn register(&mut self, spec: ToolchainSpec) {
        self.specs.insert(spec.target_id.clone(), spec);
    }

    /// Look up the toolchain spec for a target ID.
    #[must_use]
    pub fn get(&self, target_id: &str) -> Option<&ToolchainSpec> {
        self.specs.get(target_id)
    }

    /// Returns all registered target IDs.
    #[must_use]
    pub fn target_ids(&self) -> Vec<&str> {
        self.specs.keys().map(|s| s.as_str()).collect()
    }

    /// Detect whether a target's toolchain is installed.
    ///
    /// Checks for the binary on PATH and attempts to read its version.
    pub fn detect(&self, target_id: &str) -> Result<DetectedToolchain, ToolchainError> {
        let spec = self
            .specs
            .get(target_id)
            .ok_or_else(|| ToolchainError::NotFound {
                target_id: target_id.to_string(),
                binary_name: target_id.to_string(),
                install_hint: format!("No toolchain registered for target '{target_id}'"),
            })?;

        detect_toolchain(spec)
    }

    /// Detect all registered toolchains, returning found and missing.
    #[must_use]
    pub fn detect_all(&self) -> ToolchainReport {
        let mut found = Vec::new();
        let mut missing = Vec::new();

        for (target_id, spec) in &self.specs {
            match detect_toolchain(spec) {
                Ok(detected) => found.push(detected),
                Err(err) => missing.push((target_id.clone(), err)),
            }
        }

        ToolchainReport { found, missing }
    }

    /// Invoke the compilation/validation command for a target.
    ///
    /// If `source_only` is true, skips compilation and returns immediately.
    pub fn invoke(
        &self,
        target_id: &str,
        source_path: &Path,
        source_only: bool,
    ) -> Result<CompilationResult, ToolchainError> {
        if source_only {
            return Ok(CompilationResult {
                target_id: target_id.to_string(),
                command: "(source-only, compilation skipped)".to_string(),
                stdout: String::new(),
                stderr: String::new(),
                success: true,
            });
        }

        let spec = self
            .specs
            .get(target_id)
            .ok_or_else(|| ToolchainError::NotFound {
                target_id: target_id.to_string(),
                binary_name: target_id.to_string(),
                install_hint: format!("No toolchain registered for target '{target_id}'"),
            })?;

        // First ensure the toolchain is installed
        detect_toolchain(spec)?;

        // Invoke the compile command
        invoke_compile(spec, source_path)
    }

    /// Whether `target_id`'s validation runs once over the whole emitted project
    /// directory (`cargo check` / `go build` for the per-module rust/go trees)
    /// rather than once per source file. See
    /// [`ToolchainSpec::validate_per_project`].
    #[must_use]
    pub fn validates_per_project(&self, target_id: &str) -> bool {
        self.specs
            .get(target_id)
            .is_some_and(|s| s.validate_per_project)
    }

    /// Validate a whole emitted project directory at once (for targets whose
    /// per-module output is a real project — rust's Cargo crate, go's module).
    ///
    /// Runs `compile_command compile_args` with `project_dir` as the working
    /// directory and **no** appended file path. Used in place of the per-file
    /// [`ToolchainRegistry::invoke`] loop for [`ToolchainSpec::validate_per_project`]
    /// targets, where a lone `src/<module>.rs` does not type-check in isolation.
    ///
    /// If `source_only` is true, skips validation and returns success.
    pub fn invoke_project(
        &self,
        target_id: &str,
        project_dir: &Path,
        source_only: bool,
    ) -> Result<CompilationResult, ToolchainError> {
        if source_only {
            return Ok(CompilationResult {
                target_id: target_id.to_string(),
                command: "(source-only, compilation skipped)".to_string(),
                stdout: String::new(),
                stderr: String::new(),
                success: true,
            });
        }
        let spec = self
            .specs
            .get(target_id)
            .ok_or_else(|| ToolchainError::NotFound {
                target_id: target_id.to_string(),
                binary_name: target_id.to_string(),
                install_hint: format!("No toolchain registered for target '{target_id}'"),
            })?;
        detect_toolchain(spec)?;
        invoke_compile_in_dir(spec, project_dir)
    }

    /// Compile (if the target requires it) and execute a generated program,
    /// capturing the final step's stdout/stderr/exit.
    ///
    /// `workdir` must contain the emitted entrypoint named `main.<ext>` (as
    /// produced by `bock build` into `build/<target>/`). Each step in the
    /// target's [`RunPlan`] runs with `workdir` as its current directory.
    ///
    /// # Errors
    ///
    /// * [`ToolchainError::NotFound`] if the toolchain binary is absent.
    /// * [`ToolchainError::InvocationFailed`] if a non-final (compile) step
    ///   exits non-zero — the generated program never produced output. A
    ///   non-zero exit of the *final* step is **not** an error here; it is
    ///   surfaced via [`RunOutput::exit`] for the caller to judge.
    /// * [`ToolchainError::Io`] for other spawn failures.
    pub fn run(&self, target_id: &str, workdir: &Path) -> Result<RunOutput, ToolchainError> {
        let spec = self
            .specs
            .get(target_id)
            .ok_or_else(|| ToolchainError::NotFound {
                target_id: target_id.to_string(),
                binary_name: target_id.to_string(),
                install_hint: format!("No toolchain registered for target '{target_id}'"),
            })?;

        // Ensure the primary toolchain is installed before attempting to run.
        detect_toolchain(spec)?;

        run_program(spec, workdir)
    }
}

impl Default for ToolchainRegistry {
    fn default() -> Self {
        Self::with_builtins()
    }
}

/// Report of toolchain detection across all targets.
#[derive(Debug)]
pub struct ToolchainReport {
    /// Successfully detected toolchains.
    pub found: Vec<DetectedToolchain>,
    /// Targets whose toolchain was not found, with the error.
    pub missing: Vec<(String, ToolchainError)>,
}

impl ToolchainReport {
    /// Returns true if all registered toolchains were found.
    #[must_use]
    pub fn all_found(&self) -> bool {
        self.missing.is_empty()
    }
}

// ---------------------------------------------------------------------------
// Built-in toolchain specs
// ---------------------------------------------------------------------------

fn builtin_javascript_spec() -> ToolchainSpec {
    ToolchainSpec {
        target_id: "js".to_string(),
        display_name: "Node.js".to_string(),
        binary_name: "node".to_string(),
        version_args: vec!["--version".to_string()],
        compile_command: "node".to_string(),
        compile_args: vec!["--check".to_string()],
        validate_per_project: false,
        // Run the emitted ESM/CJS entry directly with Node.
        run_plan: RunPlan {
            steps: vec![RunStep::new("node", &["main.js"])],
        },
        install_hint: "Install Node.js from https://nodejs.org/ or via your package manager \
                        (e.g., `brew install node`, `apt install nodejs`)"
            .to_string(),
    }
}

fn builtin_typescript_spec() -> ToolchainSpec {
    ToolchainSpec {
        target_id: "ts".to_string(),
        display_name: "TypeScript compiler".to_string(),
        binary_name: "tsc".to_string(),
        version_args: vec!["--version".to_string()],
        compile_command: "tsc".to_string(),
        // Validate the whole project via its `tsconfig.json` (`tsc --noEmit -p .`)
        // rather than per file. The emitted tree imports sibling modules via `.ts`
        // specifiers (so it runs under `node --experimental-strip-types`); a
        // single-file `tsc --noEmit <file>` ignores the tsconfig, so it would
        // reject the `.ts` specifier (TS5097). `validate_per_project` runs `tsc`
        // once in `build/ts/`, where `rewriteRelativeImportExtensions` (from the
        // scaffolded `tsconfig.json`) accepts the `.ts` extension.
        compile_args: vec!["--noEmit".to_string(), "-p".to_string(), ".".to_string()],
        validate_per_project: true,
        // Compile the whole project via its `tsconfig.json` (`tsc -p .`), then
        // run the emitted ESM entry with Node. Project mode (§20.6.2) always
        // scaffolds a `tsconfig.json`; with it present in the run workdir, the
        // old single-file `tsc main.ts` fails (TS5112: "tsconfig.json is present
        // but will not be loaded if files are specified on commandline").
        // Building by project resolves the config *and* compiles the whole
        // per-module `.ts` tree (S6b). `rewriteRelativeImportExtensions` rewrites
        // the `.ts` import specifiers to `.js` on emit so `node main.js` runs.
        run_plan: RunPlan {
            steps: vec![
                RunStep::new("tsc", &["-p", "."]),
                RunStep::new("node", &["main.js"]),
            ],
        },
        install_hint: "Install TypeScript via npm: `npm install -g typescript`".to_string(),
    }
}

fn builtin_python_spec() -> ToolchainSpec {
    ToolchainSpec {
        target_id: "python".to_string(),
        display_name: "Python 3".to_string(),
        binary_name: "python3".to_string(),
        version_args: vec!["--version".to_string()],
        compile_command: "python3".to_string(),
        compile_args: vec!["-m".to_string(), "py_compile".to_string()],
        validate_per_project: false,
        // Run the emitted module directly with the Python 3 interpreter.
        run_plan: RunPlan {
            steps: vec![RunStep::new("python3", &["main.py"])],
        },
        install_hint: "Install Python 3 from https://python.org/ or via your package manager \
                        (e.g., `brew install python3`, `apt install python3`)"
            .to_string(),
    }
}

fn builtin_rust_spec() -> ToolchainSpec {
    ToolchainSpec {
        target_id: "rust".to_string(),
        display_name: "Rust toolchain (cargo)".to_string(),
        binary_name: "cargo".to_string(),
        version_args: vec!["--version".to_string()],
        // Per the per-module native tree (S3, §20.6.1 / DQ19), the rust build
        // output under `build/rust/` is a real Cargo crate, so validation is at
        // the *crate* level (`cargo check` in the output dir) rather than
        // per-file `rustc` — a `src/<module>.rs` file references `crate::…`
        // paths and does not type-check in isolation. `validate_per_project`
        // makes the build driver invoke this once in the output dir.
        compile_command: "cargo".to_string(),
        compile_args: vec!["check".to_string(), "--quiet".to_string()],
        validate_per_project: true,
        // `cargo run` from the crate root compiles the whole module tree and
        // runs the `bock_app` binary. `--quiet` keeps cargo's build progress off
        // stdout (the program's own stdout is what the harness captures); a debug
        // build keeps it fast. This replaces the single-file `rustc main.rs`.
        run_plan: RunPlan {
            steps: vec![RunStep::new("cargo", &["run", "--quiet"])],
        },
        install_hint: "Install Rust via rustup: https://rustup.rs/".to_string(),
    }
}

fn builtin_go_spec() -> ToolchainSpec {
    ToolchainSpec {
        target_id: "go".to_string(),
        display_name: "Go compiler".to_string(),
        binary_name: "go".to_string(),
        version_args: vec!["version".to_string()],
        // Per the per-module native tree (S3), the go output under `build/go/`
        // is a real Go module (`go.mod` + the per-module `.go` files in one
        // `package main`), so it `go build`s as a *package* in the output dir
        // rather than `go vet`-ing one file. `validate_per_project` makes the
        // build driver invoke this once in the output dir.
        compile_command: "go".to_string(),
        compile_args: vec!["build".to_string(), "-o".to_string(), os_devnull()],
        validate_per_project: true,
        // `go run .` compiles and executes the whole package in the dir in one
        // step — replacing the single-file `go run main.go`.
        run_plan: RunPlan {
            steps: vec![RunStep::new("go", &["run", "."])],
        },
        install_hint: "Install Go from https://go.dev/dl/ or via your package manager \
                        (e.g., `brew install go`, `apt install golang`)"
            .to_string(),
    }
}

/// The platform null device (`/dev/null` on Unix, `NUL` on Windows). Used as
/// `go build -o` so crate-level validation discards the produced binary instead
/// of leaving an artifact in the output dir.
fn os_devnull() -> String {
    if cfg!(windows) { "NUL" } else { "/dev/null" }.to_string()
}

// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------

/// Check if a binary exists on PATH and get its version.
fn detect_toolchain(spec: &ToolchainSpec) -> Result<DetectedToolchain, ToolchainError> {
    // Try to find the binary using `which` equivalent — run the version command
    let mut cmd = Command::new(&spec.binary_name);
    for arg in &spec.version_args {
        cmd.arg(arg);
    }

    let output = cmd.output().map_err(|e| {
        // Both NotFound and PermissionDenied indicate the binary isn't usable
        if e.kind() == std::io::ErrorKind::NotFound
            || e.kind() == std::io::ErrorKind::PermissionDenied
        {
            ToolchainError::NotFound {
                target_id: spec.target_id.clone(),
                binary_name: spec.binary_name.clone(),
                install_hint: spec.install_hint.clone(),
            }
        } else {
            ToolchainError::Io(e)
        }
    })?;

    let version = if output.status.success() {
        let v = String::from_utf8_lossy(&output.stdout).trim().to_string();
        if v.is_empty() {
            None
        } else {
            Some(v)
        }
    } else {
        None
    };

    Ok(DetectedToolchain {
        target_id: spec.target_id.clone(),
        binary_path: PathBuf::from(&spec.binary_name),
        version,
    })
}

/// Invoke the compile/validation command for a generated source file.
fn invoke_compile(
    spec: &ToolchainSpec,
    source_path: &Path,
) -> Result<CompilationResult, ToolchainError> {
    let mut cmd = Command::new(&spec.compile_command);
    for arg in &spec.compile_args {
        cmd.arg(arg);
    }
    cmd.arg(source_path);

    let full_command = format!(
        "{} {} {}",
        spec.compile_command,
        spec.compile_args.join(" "),
        source_path.display()
    );

    let output = cmd.output().map_err(|e| {
        if e.kind() == std::io::ErrorKind::NotFound
            || e.kind() == std::io::ErrorKind::PermissionDenied
        {
            ToolchainError::NotFound {
                target_id: spec.target_id.clone(),
                binary_name: spec.compile_command.clone(),
                install_hint: spec.install_hint.clone(),
            }
        } else {
            ToolchainError::Io(e)
        }
    })?;

    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
    let stderr = String::from_utf8_lossy(&output.stderr).to_string();
    let success = output.status.success();

    if !success {
        return Err(ToolchainError::InvocationFailed {
            target_id: spec.target_id.clone(),
            command: full_command,
            stdout: stdout.clone(),
            stderr: stderr.clone(),
            exit_code: output.status.code(),
        });
    }

    Ok(CompilationResult {
        target_id: spec.target_id.clone(),
        command: full_command,
        stdout,
        stderr,
        success,
    })
}

/// Validate a whole emitted project directory at once: run
/// `compile_command compile_args` with `project_dir` as the working directory
/// and **no** appended file path (e.g. `cargo check` / `go build` in
/// `build/<target>/`). Used for [`ToolchainSpec::validate_per_project`] targets
/// (rust/go), whose per-module output is a real Cargo crate / Go module.
fn invoke_compile_in_dir(
    spec: &ToolchainSpec,
    project_dir: &Path,
) -> Result<CompilationResult, ToolchainError> {
    let mut cmd = Command::new(&spec.compile_command);
    for arg in &spec.compile_args {
        cmd.arg(arg);
    }
    cmd.current_dir(project_dir);

    let full_command = format!(
        "{} {} (in {})",
        spec.compile_command,
        spec.compile_args.join(" "),
        project_dir.display()
    );

    let output = cmd.output().map_err(|e| {
        if e.kind() == std::io::ErrorKind::NotFound
            || e.kind() == std::io::ErrorKind::PermissionDenied
        {
            ToolchainError::NotFound {
                target_id: spec.target_id.clone(),
                binary_name: spec.compile_command.clone(),
                install_hint: spec.install_hint.clone(),
            }
        } else {
            ToolchainError::Io(e)
        }
    })?;

    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
    let stderr = String::from_utf8_lossy(&output.stderr).to_string();
    let success = output.status.success();

    if !success {
        return Err(ToolchainError::InvocationFailed {
            target_id: spec.target_id.clone(),
            command: full_command,
            stdout: stdout.clone(),
            stderr: stderr.clone(),
            exit_code: output.status.code(),
        });
    }

    Ok(CompilationResult {
        target_id: spec.target_id.clone(),
        command: full_command,
        stdout,
        stderr,
        success,
    })
}

/// Execute a target's [`RunPlan`] from `workdir`, returning the final step's output.
///
/// Compile/setup steps (every step except the last) must exit zero, or this
/// returns [`ToolchainError::InvocationFailed`] for the failing step. The final
/// step's output is captured and returned regardless of its exit code.
fn run_program(spec: &ToolchainSpec, workdir: &Path) -> Result<RunOutput, ToolchainError> {
    let steps = &spec.run_plan.steps;
    debug_assert!(!steps.is_empty(), "run plan must have at least one step");

    let display = steps
        .iter()
        .map(|step| {
            format!("{} {}", step.command, step.args.join(" "))
                .trim()
                .to_string()
        })
        .collect::<Vec<_>>()
        .join(" && ");

    let last_idx = steps.len().saturating_sub(1);
    let mut final_stdout = String::new();
    let mut final_stderr = String::new();
    let mut final_exit: Option<i32> = None;

    for (idx, step) in steps.iter().enumerate() {
        // Resolve the program to spawn. A toolchain step is looked up on PATH
        // by name; a produced-artifact step is spawned by its workdir path with
        // the platform exe suffix appended, so it never goes through PATH /
        // toolchain detection (which is what broke Rust execution on Windows).
        let program = match step.kind {
            StepKind::Toolchain => PathBuf::from(&step.command),
            StepKind::Artifact => {
                workdir.join(format!("{}{}", step.command, std::env::consts::EXE_SUFFIX))
            }
        };

        let mut cmd = Command::new(&program);
        cmd.args(&step.args);
        cmd.current_dir(workdir);

        let output = cmd.output().map_err(|e| {
            if e.kind() == std::io::ErrorKind::NotFound
                || e.kind() == std::io::ErrorKind::PermissionDenied
            {
                ToolchainError::NotFound {
                    target_id: spec.target_id.clone(),
                    binary_name: step.command.clone(),
                    install_hint: spec.install_hint.clone(),
                }
            } else {
                ToolchainError::Io(e)
            }
        })?;

        let stdout = String::from_utf8_lossy(&output.stdout).to_string();
        let stderr = String::from_utf8_lossy(&output.stderr).to_string();

        if idx != last_idx && !output.status.success() {
            // A compile/setup step failed: the program never ran.
            return Err(ToolchainError::InvocationFailed {
                target_id: spec.target_id.clone(),
                command: format!("{} {}", step.command, step.args.join(" "))
                    .trim()
                    .to_string(),
                stdout,
                stderr,
                exit_code: output.status.code(),
            });
        }

        final_stdout = stdout;
        final_stderr = stderr;
        final_exit = output.status.code();
    }

    Ok(RunOutput {
        target_id: spec.target_id.clone(),
        command: display,
        stdout: final_stdout,
        stderr: final_stderr,
        exit: final_exit,
    })
}

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

    #[test]
    fn registry_with_builtins_has_all_targets() {
        let registry = ToolchainRegistry::with_builtins();
        assert!(registry.get("js").is_some());
        assert!(registry.get("ts").is_some());
        assert!(registry.get("python").is_some());
        assert!(registry.get("rust").is_some());
        assert!(registry.get("go").is_some());
        assert_eq!(registry.target_ids().len(), 5);
    }

    #[test]
    fn registry_default_equals_builtins() {
        let registry = ToolchainRegistry::default();
        assert_eq!(registry.target_ids().len(), 5);
    }

    #[test]
    fn registry_custom_spec() {
        let mut registry = ToolchainRegistry::new();
        assert!(registry.get("custom").is_none());

        registry.register(ToolchainSpec {
            target_id: "custom".to_string(),
            display_name: "Custom Lang".to_string(),
            binary_name: "customc".to_string(),
            version_args: vec!["--version".to_string()],
            compile_command: "customc".to_string(),
            compile_args: vec!["--check".to_string()],
            validate_per_project: false,
            run_plan: RunPlan {
                steps: vec![RunStep::new("customc", &["main.custom"])],
            },
            install_hint: "Install custom-lang from example.com".to_string(),
        });

        assert!(registry.get("custom").is_some());
        assert_eq!(registry.get("custom").unwrap().display_name, "Custom Lang");
    }

    #[test]
    fn unknown_target_returns_not_found() {
        let registry = ToolchainRegistry::with_builtins();
        let result = registry.detect("unknown_target_xyz");
        assert!(result.is_err());
        match result.unwrap_err() {
            ToolchainError::NotFound { target_id, .. } => {
                assert_eq!(target_id, "unknown_target_xyz");
            }
            other => panic!("Expected NotFound, got: {other}"),
        }
    }

    #[test]
    fn missing_binary_returns_not_found_error() {
        let spec = ToolchainSpec {
            target_id: "fake".to_string(),
            display_name: "Fake".to_string(),
            binary_name: "definitely_not_a_real_binary_xyz_123".to_string(),
            version_args: vec!["--version".to_string()],
            compile_command: "definitely_not_a_real_binary_xyz_123".to_string(),
            compile_args: vec![],
            validate_per_project: false,
            run_plan: RunPlan {
                steps: vec![RunStep::new("definitely_not_a_real_binary_xyz_123", &[])],
            },
            install_hint: "This is a test".to_string(),
        };

        let result = detect_toolchain(&spec);
        assert!(result.is_err());
        match result.unwrap_err() {
            ToolchainError::NotFound {
                target_id,
                binary_name,
                install_hint,
            } => {
                assert_eq!(target_id, "fake");
                assert_eq!(binary_name, "definitely_not_a_real_binary_xyz_123");
                assert_eq!(install_hint, "This is a test");
            }
            other => panic!("Expected NotFound, got: {other}"),
        }
    }

    #[test]
    fn not_found_error_display_includes_install_hint() {
        let err = ToolchainError::NotFound {
            target_id: "rust".to_string(),
            binary_name: "rustc".to_string(),
            install_hint: "Install via rustup".to_string(),
        };
        let msg = err.to_string();
        assert!(msg.contains("rust"));
        assert!(msg.contains("rustc"));
        assert!(msg.contains("Install via rustup"));
    }

    #[test]
    fn invocation_failed_error_display() {
        let err = ToolchainError::InvocationFailed {
            target_id: "js".to_string(),
            command: "node --check test.js".to_string(),
            stdout: String::new(),
            stderr: "SyntaxError: unexpected token".to_string(),
            exit_code: Some(1),
        };
        let msg = err.to_string();
        assert!(msg.contains("js"));
        assert!(msg.contains("node --check test.js"));
        assert!(msg.contains("SyntaxError"));
        assert!(msg.contains("1"));
    }

    #[test]
    fn invocation_failed_prefers_stderr_over_stdout() {
        let err = ToolchainError::InvocationFailed {
            target_id: "rust".to_string(),
            command: "rustc test.rs".to_string(),
            stdout: "ignored stdout".to_string(),
            stderr: "real error on stderr".to_string(),
            exit_code: Some(1),
        };
        let msg = err.to_string();
        assert!(msg.contains("real error on stderr"));
        assert!(!msg.contains("ignored stdout"));
    }

    #[test]
    fn invocation_failed_falls_back_to_stdout() {
        let err = ToolchainError::InvocationFailed {
            target_id: "ts".to_string(),
            command: "tsc --noEmit test.ts".to_string(),
            stdout: "test.ts(1,1): error TS2304: Cannot find name 'x'.".to_string(),
            stderr: String::new(),
            exit_code: Some(2),
        };
        let msg = err.to_string();
        assert!(msg.contains("error TS2304"));
        assert!(msg.contains("Cannot find name"));
    }

    #[test]
    fn source_only_skips_compilation() {
        let registry = ToolchainRegistry::with_builtins();
        let result = registry
            .invoke("js", Path::new("test.js"), true)
            .expect("source_only should always succeed");

        assert!(result.success);
        assert!(result.command.contains("source-only"));
        assert_eq!(result.target_id, "js");
    }

    #[test]
    fn source_only_works_for_any_target() {
        let registry = ToolchainRegistry::with_builtins();

        for target in &["js", "ts", "python", "rust", "go"] {
            let result = registry
                .invoke(target, Path::new("test.src"), true)
                .expect("source_only should succeed for all targets");
            assert!(result.success);
            assert_eq!(result.target_id, *target);
        }
    }

    #[test]
    fn invoke_unknown_target_returns_error() {
        let registry = ToolchainRegistry::with_builtins();
        let result = registry.invoke("unknown_xyz", Path::new("test.src"), false);
        assert!(result.is_err());
    }

    #[test]
    fn builtin_specs_have_correct_binaries() {
        let js = builtin_javascript_spec();
        assert_eq!(js.binary_name, "node");
        assert_eq!(js.compile_command, "node");

        let ts = builtin_typescript_spec();
        assert_eq!(ts.binary_name, "tsc");

        let py = builtin_python_spec();
        assert_eq!(py.binary_name, "python3");

        // Rust/Go emit a real project (Cargo crate / Go module — S3), so they
        // build and validate via the project toolchain (`cargo` / `go`) at the
        // crate/module level rather than per-file `rustc`/`go vet`.
        let rs = builtin_rust_spec();
        assert_eq!(rs.binary_name, "cargo");
        assert!(rs.compile_args.contains(&"check".to_string()));
        assert!(rs.validate_per_project);

        let go = builtin_go_spec();
        assert_eq!(go.binary_name, "go");
        assert!(go.compile_args.contains(&"build".to_string()));
        assert!(go.validate_per_project);
    }

    #[test]
    fn detect_all_returns_report() {
        let registry = ToolchainRegistry::with_builtins();
        let report = registry.detect_all();
        // Total should match number of builtins
        assert_eq!(report.found.len() + report.missing.len(), 5);
    }

    #[test]
    fn toolchain_report_all_found() {
        // With an empty registry, all_found should be true (no missing)
        let registry = ToolchainRegistry::new();
        let report = registry.detect_all();
        assert!(report.all_found());
    }

    #[test]
    fn detect_missing_binary_via_registry() {
        let mut registry = ToolchainRegistry::new();
        registry.register(ToolchainSpec {
            target_id: "fake".to_string(),
            display_name: "Fake".to_string(),
            binary_name: "not_a_real_binary_abc_999".to_string(),
            version_args: vec!["--version".to_string()],
            compile_command: "not_a_real_binary_abc_999".to_string(),
            compile_args: vec![],
            validate_per_project: false,
            run_plan: RunPlan {
                steps: vec![RunStep::new("not_a_real_binary_abc_999", &[])],
            },
            install_hint: "Cannot install fake toolchain".to_string(),
        });

        let report = registry.detect_all();
        assert!(!report.all_found());
        assert_eq!(report.missing.len(), 1);
        assert_eq!(report.missing[0].0, "fake");
    }

    #[test]
    fn invoke_with_missing_toolchain_gives_clear_error() {
        let mut registry = ToolchainRegistry::new();
        registry.register(ToolchainSpec {
            target_id: "fake".to_string(),
            display_name: "Fake Lang".to_string(),
            binary_name: "not_a_real_binary_zzz".to_string(),
            version_args: vec!["--version".to_string()],
            compile_command: "not_a_real_binary_zzz".to_string(),
            compile_args: vec!["--check".to_string()],
            validate_per_project: false,
            run_plan: RunPlan {
                steps: vec![RunStep::new("not_a_real_binary_zzz", &[])],
            },
            install_hint: "Install from example.com".to_string(),
        });

        let result = registry.invoke("fake", Path::new("test.src"), false);
        assert!(result.is_err());
        let err = result.unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("not installed"));
        assert!(msg.contains("Install from example.com"));
    }

    #[test]
    fn builtin_specs_have_run_plans() {
        let registry = ToolchainRegistry::with_builtins();
        for target in &["js", "ts", "python", "rust", "go"] {
            let spec = registry.get(target).expect("builtin spec present");
            assert!(
                !spec.run_plan.steps.is_empty(),
                "{target} run plan must be non-empty"
            );
        }
    }

    #[test]
    fn rust_run_plan_is_cargo_run() {
        // Per the per-module native tree (S3), rust output is a Cargo crate run
        // via a single `cargo run` step from the build dir — replacing the old
        // two-step `rustc main.rs` + produced-artifact plan.
        let spec = builtin_rust_spec();
        assert_eq!(spec.binary_name, "cargo");
        assert_eq!(spec.run_plan.steps.len(), 1, "rust runs via `cargo run`");
        assert_eq!(spec.run_plan.steps[0].command, "cargo");
        assert_eq!(spec.run_plan.steps[0].kind, StepKind::Toolchain);
        assert!(spec.run_plan.steps[0].args.contains(&"run".to_string()));
    }

    #[test]
    fn go_run_plan_is_go_run_dir() {
        // Per the per-module native tree (S3), go output is a Go module run via
        // `go run .` over the whole package dir — replacing `go run main.go`.
        let spec = builtin_go_spec();
        assert_eq!(spec.run_plan.steps.len(), 1, "go runs via `go run .`");
        assert_eq!(spec.run_plan.steps[0].command, "go");
        assert_eq!(
            spec.run_plan.steps[0].args,
            vec!["run".to_string(), ".".to_string()]
        );
    }

    #[test]
    fn ts_run_plan_is_tsc_project_then_node() {
        // TS builds by project (`tsc -p .`) so the scaffolded `tsconfig.json`
        // (always present in project mode, §20.6.2 / S6b) is honored rather than
        // colliding with a single-file `tsc main.ts` (TS5112).
        let spec = builtin_typescript_spec();
        assert_eq!(spec.run_plan.steps.len(), 2, "ts emits then runs");
        assert_eq!(spec.run_plan.steps[0].command, "tsc");
        assert_eq!(
            spec.run_plan.steps[0].args,
            vec!["-p".to_string(), ".".to_string()]
        );
        assert_eq!(spec.run_plan.steps[1].command, "node");
        assert_eq!(spec.run_plan.steps[1].args, vec!["main.js".to_string()]);
    }

    #[test]
    fn single_step_targets_run_one_command() {
        // js/python run their entry directly; rust/go run their emitted project
        // via a single `cargo run` / `go run .` step (S3).
        for spec in [
            builtin_javascript_spec(),
            builtin_python_spec(),
            builtin_rust_spec(),
            builtin_go_spec(),
        ] {
            assert_eq!(
                spec.run_plan.steps.len(),
                1,
                "{} should be a single run step",
                spec.target_id
            );
        }
    }

    #[test]
    fn run_unknown_target_returns_not_found() {
        let registry = ToolchainRegistry::with_builtins();
        let result = registry.run("unknown_xyz", Path::new("."));
        assert!(result.is_err());
        match result.unwrap_err() {
            ToolchainError::NotFound { target_id, .. } => {
                assert_eq!(target_id, "unknown_xyz");
            }
            other => panic!("Expected NotFound, got: {other}"),
        }
    }

    #[test]
    fn run_with_missing_toolchain_gives_not_found() {
        let mut registry = ToolchainRegistry::new();
        registry.register(ToolchainSpec {
            target_id: "fake".to_string(),
            display_name: "Fake Lang".to_string(),
            binary_name: "not_a_real_binary_run_xyz".to_string(),
            version_args: vec!["--version".to_string()],
            compile_command: "not_a_real_binary_run_xyz".to_string(),
            compile_args: vec![],
            validate_per_project: false,
            run_plan: RunPlan {
                steps: vec![RunStep::new("not_a_real_binary_run_xyz", &[])],
            },
            install_hint: "Install from example.com".to_string(),
        });

        let result = registry.run("fake", Path::new("."));
        assert!(matches!(result, Err(ToolchainError::NotFound { .. })));
    }

    #[test]
    fn run_captures_stdout_of_final_step() {
        // Use a portable program (`true`-like) to exercise the plumbing without
        // depending on a language toolchain. We register a custom spec whose
        // single step is a command guaranteed present on the test host.
        if Command::new("printf").arg("").output().is_err() {
            // `printf` not available on this host; skip rather than fail.
            return;
        }
        let mut registry = ToolchainRegistry::new();
        registry.register(ToolchainSpec {
            target_id: "printer".to_string(),
            display_name: "Printer".to_string(),
            binary_name: "printf".to_string(),
            version_args: vec!["%s".to_string(), "probe".to_string()],
            compile_command: "printf".to_string(),
            compile_args: vec![],
            validate_per_project: false,
            run_plan: RunPlan {
                steps: vec![RunStep::new("printf", &["%s", "captured-output"])],
            },
            install_hint: "coreutils".to_string(),
        });

        let out = registry.run("printer", Path::new(".")).expect("run ok");
        assert_eq!(out.target_id, "printer");
        assert_eq!(out.stdout.trim(), "captured-output");
        assert_eq!(out.exit, Some(0));
    }

    #[test]
    fn run_reports_failing_compile_step() {
        // A two-step plan whose first (compile) step exits non-zero must surface
        // InvocationFailed, not reach the second step.
        if Command::new("false").output().is_err() {
            return;
        }
        let mut registry = ToolchainRegistry::new();
        registry.register(ToolchainSpec {
            target_id: "twostep".to_string(),
            display_name: "Two Step".to_string(),
            binary_name: "false".to_string(),
            version_args: vec![],
            compile_command: "false".to_string(),
            compile_args: vec![],
            validate_per_project: false,
            run_plan: RunPlan {
                steps: vec![
                    RunStep::new("false", &[]),
                    RunStep::new("echo", &["unreached"]),
                ],
            },
            install_hint: "coreutils".to_string(),
        });

        let result = registry.run("twostep", Path::new("."));
        match result {
            Err(ToolchainError::InvocationFailed { target_id, .. }) => {
                assert_eq!(target_id, "twostep");
            }
            other => panic!("expected InvocationFailed, got {other:?}"),
        }
    }
}