bnto-engine 0.1.4

Shared engine — registry creation and pipeline convenience for all consumers
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
// Dependency checker — verifies that external tools required by processors
// are available on the host system. WASM has no shell, so this module is
// only useful in CLI/desktop contexts where ProcessContext is a NativeContext.

use bnto_core::{BntoError, Dependency, NodeRegistry, PipelineDefinition};
use std::collections::HashSet;

/// Result of checking a single dependency.
#[derive(Debug, Clone)]
pub struct DependencyStatus {
    pub dependency: Dependency,
    pub found: bool,
    /// Installed version string (if detected via `--version`).
    pub installed_version: Option<String>,
    /// Whether the installed version satisfies the constraint.
    /// `None` if no constraint was specified or version couldn't be determined.
    pub version_satisfied: Option<bool>,
}

/// Collect unique dependencies required by a pipeline definition.
///
/// Merges two sources: recipe-level deps (`definition.requires`) first,
/// then per-node processor deps (from `metadata().requires`). Deduplicates
/// by binary name — recipe-level deps take precedence when both declare
/// the same binary.
pub fn collect_pipeline_dependencies(
    definition: &PipelineDefinition,
    registry: &NodeRegistry,
) -> Vec<Dependency> {
    let mut seen = HashSet::new();
    let mut deps = Vec::new();

    // Recipe-level deps first — these take precedence.
    for dep in &definition.requires {
        if seen.insert(dep.binary.clone()) {
            deps.push(dep.clone());
        }
    }

    // Then per-node processor deps (existing logic).
    collect_from_nodes(&definition.nodes, registry, &mut seen, &mut deps);
    deps
}

fn collect_from_nodes(
    nodes: &[bnto_core::PipelineNode],
    registry: &NodeRegistry,
    seen: &mut HashSet<String>,
    deps: &mut Vec<Dependency>,
) {
    let empty_params = serde_json::Map::new();
    for node in nodes {
        if let Some(processor) = registry.resolve(&node.node_type, &empty_params) {
            for dep in &processor.metadata().requires {
                if seen.insert(dep.binary.clone()) {
                    deps.push(dep.clone());
                }
            }
        }
        // Recurse into container children.
        if let Some(children) = &node.children {
            collect_from_nodes(children, registry, seen, deps);
        }
    }
}

/// Collect unique dependencies from ALL registered processors in the registry.
pub fn collect_all_dependencies(registry: &NodeRegistry) -> Vec<Dependency> {
    let mut seen = HashSet::new();
    let mut deps = Vec::new();
    for metadata in registry.catalog() {
        for dep in metadata.requires {
            if seen.insert(dep.binary.clone()) {
                deps.push(dep);
            }
        }
    }
    deps
}

/// Check whether each dependency's binary is available on the system
/// and whether its version satisfies any declared constraint.
///
/// Uses `which <binary>` to probe the PATH. If the dependency has a
/// non-empty `version` constraint, runs `<binary> --version` and
/// validates the output against the constraint.
pub fn check_dependencies(
    deps: &[Dependency],
    ctx: &dyn bnto_core::ProcessContext,
) -> Vec<DependencyStatus> {
    deps.iter()
        .map(|dep| {
            let found = ctx.run_command("which", &[&dep.binary]).is_ok();

            // Only check version if the binary exists and has a constraint.
            let (installed_version, version_satisfied) = if found && !dep.version.is_empty() {
                match bnto_core::check_version(&dep.binary, &dep.version, ctx) {
                    bnto_core::VersionCheckResult::Checked {
                        installed,
                        satisfied,
                    } => (Some(installed), Some(satisfied)),
                    bnto_core::VersionCheckResult::Skipped => (None, None),
                }
            } else {
                (None, None)
            };

            DependencyStatus {
                dependency: dep.clone(),
                found,
                installed_version,
                version_satisfied,
            }
        })
        .collect()
}

/// Check dependencies for a pipeline definition and return an error if any are missing.
///
/// Intended as a pre-flight check before `run_pipeline()`. Returns `Ok(())`
/// when all dependencies are satisfied, or `Err(BntoError)` listing the
/// missing binaries with install hints.
pub fn check_pipeline_dependencies(
    definition: &PipelineDefinition,
    registry: &NodeRegistry,
    ctx: &dyn bnto_core::ProcessContext,
) -> Result<(), BntoError> {
    let deps = collect_pipeline_dependencies(definition, registry);
    if deps.is_empty() {
        return Ok(());
    }

    let statuses = check_dependencies(&deps, ctx);

    let mut messages: Vec<String> = Vec::new();

    for s in &statuses {
        if !s.found {
            let hint = &s.dependency.install_hint;
            messages.push(format!("  - {} (install: {})", s.dependency.binary, hint));
        } else if s.version_satisfied == Some(false) {
            let installed = s.installed_version.as_deref().unwrap_or("unknown");
            messages.push(format!(
                "  - {} (installed: {}, requires: {})",
                s.dependency.binary, installed, s.dependency.version
            ));
        }
    }

    if messages.is_empty() {
        return Ok(());
    }

    Err(BntoError::InvalidInput(format!(
        "Dependency requirements not met:\n{}",
        messages.join("\n")
    )))
}

/// Check that all required secrets declared by a pipeline are available.
///
/// Parallel to `check_pipeline_dependencies()` — this is the pre-flight
/// check for env vars. Returns `Ok(())` when all required secrets are
/// present, or `Err(BntoError)` listing the missing ones.
pub fn check_pipeline_secrets(
    definition: &PipelineDefinition,
    ctx: &dyn bnto_core::ProcessContext,
) -> Result<(), BntoError> {
    if definition.secrets.is_empty() {
        return Ok(());
    }

    let statuses = bnto_core::secrets::check_secrets(&definition.secrets, ctx);
    let missing = bnto_core::secrets::missing_required(&statuses);

    if missing.is_empty() {
        return Ok(());
    }

    Err(BntoError::InvalidInput(
        bnto_core::secrets::format_missing_error(&missing),
    ))
}

// =============================================================================
// Tests
// =============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use bnto_core::NodeProcessor;
    use bnto_core::NoopContext;
    use bnto_core::context::ProcessContext;
    use bnto_core::errors::BntoError;
    use bnto_core::metadata::{Dependency, InputCardinality, NodeCategory, NodeMetadata};
    use bnto_core::processor::{NodeInput, NodeOutput, OutputFile};
    use bnto_core::progress::ProgressReporter;
    use std::path::{Path, PathBuf};

    // --- Mock processor that declares dependencies ---

    struct FfmpegProcessor;

    impl NodeProcessor for FfmpegProcessor {
        fn name(&self) -> &str {
            "video-transcode"
        }

        fn process(
            &self,
            input: NodeInput,
            _progress: &ProgressReporter,
            _ctx: &dyn ProcessContext,
        ) -> Result<NodeOutput, BntoError> {
            Ok(NodeOutput {
                files: vec![OutputFile {
                    data: input.data,
                    filename: input.filename,
                    mime_type: "video/mp4".to_string(),
                    metadata: serde_json::Map::new(),
                }],
                metadata: serde_json::Map::new(),
            })
        }

        fn metadata(&self) -> NodeMetadata {
            NodeMetadata {
                node_type: "video-transcode".to_string(),
                name: "Transcode Video".to_string(),
                description: "Transcode video using ffmpeg.".to_string(),
                category: NodeCategory::Data,
                accepts: vec!["video/*".to_string()],
                platforms: vec!["cli".to_string()],
                parameters: vec![],
                input_cardinality: InputCardinality::PerFile,
                requires: vec![Dependency {
                    binary: "ffmpeg".to_string(),
                    version: ">=6.0".to_string(),
                    install_hint: "brew install ffmpeg".to_string(),
                    homepage: "https://ffmpeg.org".to_string(),
                }],
            }
        }
    }

    struct YtDlpProcessor;

    impl NodeProcessor for YtDlpProcessor {
        fn name(&self) -> &str {
            "video-download"
        }

        fn process(
            &self,
            input: NodeInput,
            _progress: &ProgressReporter,
            _ctx: &dyn ProcessContext,
        ) -> Result<NodeOutput, BntoError> {
            Ok(NodeOutput {
                files: vec![OutputFile {
                    data: input.data,
                    filename: input.filename,
                    mime_type: "video/mp4".to_string(),
                    metadata: serde_json::Map::new(),
                }],
                metadata: serde_json::Map::new(),
            })
        }

        fn metadata(&self) -> NodeMetadata {
            NodeMetadata {
                node_type: "video-download".to_string(),
                name: "Download Video".to_string(),
                description: "Download video using yt-dlp.".to_string(),
                category: NodeCategory::Data,
                accepts: vec![],
                platforms: vec!["cli".to_string()],
                parameters: vec![],
                input_cardinality: InputCardinality::PerFile,
                requires: vec![
                    Dependency {
                        binary: "yt-dlp".to_string(),
                        version: String::new(),
                        install_hint: "brew install yt-dlp".to_string(),
                        homepage: "https://github.com/yt-dlp/yt-dlp".to_string(),
                    },
                    Dependency {
                        binary: "ffmpeg".to_string(),
                        version: ">=6.0".to_string(),
                        install_hint: "brew install ffmpeg".to_string(),
                        homepage: "https://ffmpeg.org".to_string(),
                    },
                ],
            }
        }
    }

    /// A no-dep processor (like existing browser-only ones).
    struct NoDepsProcessor;

    impl NodeProcessor for NoDepsProcessor {
        fn name(&self) -> &str {
            "no-deps"
        }

        fn process(
            &self,
            input: NodeInput,
            _progress: &ProgressReporter,
            _ctx: &dyn ProcessContext,
        ) -> Result<NodeOutput, BntoError> {
            Ok(NodeOutput {
                files: vec![OutputFile {
                    data: input.data,
                    filename: input.filename,
                    mime_type: "application/octet-stream".to_string(),
                    metadata: serde_json::Map::new(),
                }],
                metadata: serde_json::Map::new(),
            })
        }
    }

    /// Mock context where `which` always fails (simulates missing deps).
    struct AllMissingContext;

    impl ProcessContext for AllMissingContext {
        fn run_command(&self, _cmd: &str, _args: &[&str]) -> Result<Vec<u8>, BntoError> {
            Err(BntoError::ProcessingFailed("not found".to_string()))
        }
        fn temp_file(&self, _suffix: &str) -> Result<PathBuf, BntoError> {
            Err(BntoError::ProcessingFailed("not available".to_string()))
        }
        fn env_var(&self, _key: &str) -> Option<String> {
            None
        }
        fn work_dir(&self) -> Result<&Path, BntoError> {
            Err(BntoError::ProcessingFailed("not available".to_string()))
        }
    }

    /// Mock context where `which` always succeeds.
    struct AllFoundContext;

    impl ProcessContext for AllFoundContext {
        fn run_command(&self, _cmd: &str, _args: &[&str]) -> Result<Vec<u8>, BntoError> {
            Ok(b"/usr/local/bin/found".to_vec())
        }
        fn temp_file(&self, _suffix: &str) -> Result<PathBuf, BntoError> {
            Err(BntoError::ProcessingFailed("not available".to_string()))
        }
        fn env_var(&self, _key: &str) -> Option<String> {
            None
        }
        fn work_dir(&self) -> Result<&Path, BntoError> {
            Err(BntoError::ProcessingFailed("not available".to_string()))
        }
    }

    fn make_definition(node_types: &[&str]) -> PipelineDefinition {
        let json = serde_json::json!({
            "nodes": node_types.iter().enumerate().map(|(i, t)| {
                serde_json::json!({ "id": format!("n{i}"), "type": t })
            }).collect::<Vec<_>>()
        });
        serde_json::from_value(json).unwrap()
    }

    /// Build a definition with recipe-level `requires` and the given nodes.
    fn make_definition_with_requires(
        node_types: &[&str],
        requires: Vec<Dependency>,
    ) -> PipelineDefinition {
        let mut def = make_definition(node_types);
        def.requires = requires;
        def
    }

    fn ytdlp_dep() -> Dependency {
        Dependency {
            binary: "yt-dlp".to_string(),
            version: String::new(),
            install_hint: "brew install yt-dlp".to_string(),
            homepage: String::new(),
        }
    }

    fn ffmpeg_dep() -> Dependency {
        Dependency {
            binary: "ffmpeg".to_string(),
            version: ">=6.0".to_string(),
            install_hint: "brew install ffmpeg".to_string(),
            homepage: "https://ffmpeg.org".to_string(),
        }
    }

    // --- collect_pipeline_dependencies ---

    #[test]
    fn test_collect_empty_pipeline_returns_no_deps() {
        let def = make_definition(&["input", "output"]);
        let registry = NodeRegistry::new();
        let deps = collect_pipeline_dependencies(&def, &registry);
        assert!(deps.is_empty());
    }

    #[test]
    fn test_collect_pipeline_with_no_dep_processor() {
        let mut registry = NodeRegistry::new();
        registry.register("no-deps", Box::new(NoDepsProcessor));
        let def = make_definition(&["input", "no-deps", "output"]);
        let deps = collect_pipeline_dependencies(&def, &registry);
        assert!(deps.is_empty());
    }

    #[test]
    fn test_collect_pipeline_with_ffmpeg_dep() {
        let mut registry = NodeRegistry::new();
        registry.register("video-transcode", Box::new(FfmpegProcessor));
        let def = make_definition(&["input", "video-transcode", "output"]);
        let deps = collect_pipeline_dependencies(&def, &registry);
        assert_eq!(deps.len(), 1);
        assert_eq!(deps[0].binary, "ffmpeg");
    }

    #[test]
    fn test_collect_deduplicates_shared_deps() {
        let mut registry = NodeRegistry::new();
        registry.register("video-transcode", Box::new(FfmpegProcessor));
        registry.register("video-download", Box::new(YtDlpProcessor));
        let def = make_definition(&["input", "video-transcode", "video-download", "output"]);
        let deps = collect_pipeline_dependencies(&def, &registry);
        // ffmpeg appears in both, but should be deduplicated
        assert_eq!(deps.len(), 2); // ffmpeg + yt-dlp
        let binaries: Vec<&str> = deps.iter().map(|d| d.binary.as_str()).collect();
        assert!(binaries.contains(&"ffmpeg"));
        assert!(binaries.contains(&"yt-dlp"));
    }

    // --- collect_pipeline_dependencies: recipe-level requires ---

    #[test]
    fn test_collect_recipe_only_deps() {
        // Recipe declares deps but no nodes have processor deps.
        let def = make_definition_with_requires(&["input", "output"], vec![ytdlp_dep()]);
        let registry = NodeRegistry::new();
        let deps = collect_pipeline_dependencies(&def, &registry);
        assert_eq!(deps.len(), 1);
        assert_eq!(deps[0].binary, "yt-dlp");
    }

    #[test]
    fn test_collect_node_only_deps_unchanged() {
        // Recipe has no requires but nodes have processor deps.
        // This is the existing behavior — must still work.
        let mut registry = NodeRegistry::new();
        registry.register("video-transcode", Box::new(FfmpegProcessor));
        let def = make_definition(&["input", "video-transcode", "output"]);
        let deps = collect_pipeline_dependencies(&def, &registry);
        assert_eq!(deps.len(), 1);
        assert_eq!(deps[0].binary, "ffmpeg");
    }

    #[test]
    fn test_collect_merged_recipe_and_node_deps() {
        // Recipe declares yt-dlp, node declares ffmpeg — both should appear.
        let mut registry = NodeRegistry::new();
        registry.register("video-transcode", Box::new(FfmpegProcessor));
        let def = make_definition_with_requires(
            &["input", "video-transcode", "output"],
            vec![ytdlp_dep()],
        );
        let deps = collect_pipeline_dependencies(&def, &registry);
        assert_eq!(deps.len(), 2);
        let binaries: Vec<&str> = deps.iter().map(|d| d.binary.as_str()).collect();
        assert!(binaries.contains(&"yt-dlp"));
        assert!(binaries.contains(&"ffmpeg"));
    }

    #[test]
    fn test_collect_recipe_deps_come_first() {
        // Recipe-level deps should appear before node-level deps in the list.
        let mut registry = NodeRegistry::new();
        registry.register("video-transcode", Box::new(FfmpegProcessor));
        let def = make_definition_with_requires(
            &["input", "video-transcode", "output"],
            vec![ytdlp_dep()],
        );
        let deps = collect_pipeline_dependencies(&def, &registry);
        assert_eq!(
            deps[0].binary, "yt-dlp",
            "Recipe-level dep should come first"
        );
        assert_eq!(
            deps[1].binary, "ffmpeg",
            "Node-level dep should come second"
        );
    }

    #[test]
    fn test_collect_deduplicated_recipe_and_node_deps() {
        // Both recipe and node declare ffmpeg — should appear only once.
        let mut registry = NodeRegistry::new();
        registry.register("video-transcode", Box::new(FfmpegProcessor));
        let def = make_definition_with_requires(
            &["input", "video-transcode", "output"],
            vec![ffmpeg_dep()],
        );
        let deps = collect_pipeline_dependencies(&def, &registry);
        assert_eq!(deps.len(), 1, "Duplicate ffmpeg should be deduplicated");
        assert_eq!(deps[0].binary, "ffmpeg");
    }

    #[test]
    fn test_collect_empty_recipe_requires() {
        // Recipe has explicit empty requires — should behave like no requires.
        let def = make_definition_with_requires(&["input", "output"], vec![]);
        let registry = NodeRegistry::new();
        let deps = collect_pipeline_dependencies(&def, &registry);
        assert!(deps.is_empty());
    }

    #[test]
    fn test_check_pipeline_dependencies_catches_recipe_deps() {
        // Pre-flight check should catch missing recipe-level deps too.
        let def = make_definition_with_requires(&["input", "output"], vec![ytdlp_dep()]);
        let registry = NodeRegistry::new();
        let result = check_pipeline_dependencies(&def, &registry, &AllMissingContext);
        assert!(result.is_err());
        let err_msg = result.unwrap_err().to_string();
        assert!(err_msg.contains("yt-dlp"));
        assert!(err_msg.contains("brew install yt-dlp"));
    }

    // --- collect_all_dependencies ---

    #[test]
    fn test_collect_all_from_empty_registry() {
        let registry = NodeRegistry::new();
        let deps = collect_all_dependencies(&registry);
        assert!(deps.is_empty());
    }

    #[test]
    fn test_collect_all_deduplicates() {
        let mut registry = NodeRegistry::new();
        registry.register("video-transcode", Box::new(FfmpegProcessor));
        registry.register("video-download", Box::new(YtDlpProcessor));
        registry.register("no-deps", Box::new(NoDepsProcessor));
        let deps = collect_all_dependencies(&registry);
        assert_eq!(deps.len(), 2); // ffmpeg + yt-dlp (deduplicated)
    }

    // --- check_dependencies ---

    #[test]
    fn test_check_all_missing() {
        let deps = vec![Dependency {
            binary: "ffmpeg".to_string(),
            version: String::new(),
            install_hint: "brew install ffmpeg".to_string(),
            homepage: String::new(),
        }];
        let statuses = check_dependencies(&deps, &AllMissingContext);
        assert_eq!(statuses.len(), 1);
        assert!(!statuses[0].found);
    }

    #[test]
    fn test_check_all_found() {
        let deps = vec![Dependency {
            binary: "ffmpeg".to_string(),
            version: String::new(),
            install_hint: "brew install ffmpeg".to_string(),
            homepage: String::new(),
        }];
        let statuses = check_dependencies(&deps, &AllFoundContext);
        assert_eq!(statuses.len(), 1);
        assert!(statuses[0].found);
    }

    #[test]
    fn test_check_empty_deps_returns_empty() {
        let statuses = check_dependencies(&[], &NoopContext);
        assert!(statuses.is_empty());
    }

    // --- check_pipeline_dependencies ---

    #[test]
    fn test_preflight_no_deps_ok() {
        let mut registry = NodeRegistry::new();
        registry.register("no-deps", Box::new(NoDepsProcessor));
        let def = make_definition(&["input", "no-deps", "output"]);
        let result = check_pipeline_dependencies(&def, &registry, &NoopContext);
        assert!(result.is_ok());
    }

    #[test]
    fn test_preflight_missing_dep_returns_error() {
        let mut registry = NodeRegistry::new();
        registry.register("video-transcode", Box::new(FfmpegProcessor));
        let def = make_definition(&["input", "video-transcode", "output"]);
        let result = check_pipeline_dependencies(&def, &registry, &AllMissingContext);
        assert!(result.is_err());
        let err_msg = result.unwrap_err().to_string();
        assert!(err_msg.contains("ffmpeg"));
        assert!(err_msg.contains("brew install ffmpeg"));
    }

    #[test]
    fn test_preflight_all_found_ok() {
        let mut registry = NodeRegistry::new();
        registry.register("video-transcode", Box::new(FfmpegProcessor));
        let def = make_definition(&["input", "video-transcode", "output"]);
        let result = check_pipeline_dependencies(&def, &registry, &AllFoundContext);
        assert!(result.is_ok());
    }

    #[test]
    fn test_preflight_error_lists_all_missing() {
        let mut registry = NodeRegistry::new();
        registry.register("video-download", Box::new(YtDlpProcessor));
        let def = make_definition(&["input", "video-download", "output"]);
        let result = check_pipeline_dependencies(&def, &registry, &AllMissingContext);
        assert!(result.is_err());
        let err_msg = result.unwrap_err().to_string();
        assert!(err_msg.contains("yt-dlp"));
        assert!(err_msg.contains("ffmpeg"));
    }

    // --- Version constraint integration ---

    /// Mock context that returns a path for `which` and version output
    /// for `<binary> --version`. Simulates a system with ffmpeg 6.1.1.
    struct VersionedContext {
        version_output: String,
    }

    impl VersionedContext {
        fn new(version_output: &str) -> Self {
            Self {
                version_output: version_output.to_string(),
            }
        }
    }

    impl ProcessContext for VersionedContext {
        fn run_command(&self, cmd: &str, _args: &[&str]) -> Result<Vec<u8>, BntoError> {
            if cmd == "which" {
                Ok(b"/usr/local/bin/found".to_vec())
            } else {
                Ok(self.version_output.as_bytes().to_vec())
            }
        }
        fn temp_file(&self, _suffix: &str) -> Result<PathBuf, BntoError> {
            Err(BntoError::ProcessingFailed("mock".to_string()))
        }
        fn env_var(&self, _key: &str) -> Option<String> {
            None
        }
        fn work_dir(&self) -> Result<&Path, BntoError> {
            Err(BntoError::ProcessingFailed("mock".to_string()))
        }
    }

    #[test]
    fn test_check_deps_version_satisfied() {
        let ctx = VersionedContext::new("ffmpeg version 6.1.1 Copyright");
        let deps = vec![ffmpeg_dep()]; // requires >=6.0
        let statuses = check_dependencies(&deps, &ctx);
        assert_eq!(statuses.len(), 1);
        assert!(statuses[0].found);
        assert_eq!(statuses[0].installed_version.as_deref(), Some("6.1.1"));
        assert_eq!(statuses[0].version_satisfied, Some(true));
    }

    #[test]
    fn test_check_deps_version_unsatisfied() {
        let ctx = VersionedContext::new("ffmpeg version 5.0.2 Copyright");
        let deps = vec![ffmpeg_dep()]; // requires >=6.0
        let statuses = check_dependencies(&deps, &ctx);
        assert_eq!(statuses.len(), 1);
        assert!(statuses[0].found);
        assert_eq!(statuses[0].installed_version.as_deref(), Some("5.0.2"));
        assert_eq!(statuses[0].version_satisfied, Some(false));
    }

    #[test]
    fn test_check_deps_no_version_constraint() {
        let ctx = VersionedContext::new("yt-dlp 2024.12.23");
        let deps = vec![ytdlp_dep()]; // no version constraint
        let statuses = check_dependencies(&deps, &ctx);
        assert_eq!(statuses.len(), 1);
        assert!(statuses[0].found);
        assert!(statuses[0].installed_version.is_none());
        assert!(statuses[0].version_satisfied.is_none());
    }

    #[test]
    fn test_preflight_version_mismatch_returns_error() {
        let ctx = VersionedContext::new("ffmpeg version 5.0.2 Copyright");
        let mut registry = NodeRegistry::new();
        registry.register("video-transcode", Box::new(FfmpegProcessor));
        let def = make_definition(&["input", "video-transcode", "output"]);
        let result = check_pipeline_dependencies(&def, &registry, &ctx);
        assert!(result.is_err());
        let err_msg = result.unwrap_err().to_string();
        assert!(err_msg.contains("ffmpeg"));
        assert!(err_msg.contains("5.0.2"));
        assert!(err_msg.contains(">=6.0"));
    }

    #[test]
    fn test_preflight_version_satisfied_passes() {
        let ctx = VersionedContext::new("ffmpeg version 6.1.1 Copyright");
        let mut registry = NodeRegistry::new();
        registry.register("video-transcode", Box::new(FfmpegProcessor));
        let def = make_definition(&["input", "video-transcode", "output"]);
        let result = check_pipeline_dependencies(&def, &registry, &ctx);
        assert!(result.is_ok());
    }

    // --- check_pipeline_secrets ---

    fn make_definition_with_secrets(secrets: Vec<bnto_core::SecretDef>) -> PipelineDefinition {
        let mut def = make_definition(&["input", "output"]);
        def.secrets = secrets;
        def
    }

    fn required_secret(key: &str) -> bnto_core::SecretDef {
        bnto_core::SecretDef {
            key: key.to_string(),
            description: String::new(),
            required: true,
        }
    }

    fn optional_secret(key: &str) -> bnto_core::SecretDef {
        bnto_core::SecretDef {
            key: key.to_string(),
            description: String::new(),
            required: false,
        }
    }

    /// Mock context that provides specific env vars.
    struct EnvContext {
        vars: std::collections::HashMap<String, String>,
    }

    impl EnvContext {
        fn new(pairs: &[(&str, &str)]) -> Self {
            Self {
                vars: pairs
                    .iter()
                    .map(|(k, v)| (k.to_string(), v.to_string()))
                    .collect(),
            }
        }
    }

    impl ProcessContext for EnvContext {
        fn run_command(&self, _cmd: &str, _args: &[&str]) -> Result<Vec<u8>, BntoError> {
            Err(BntoError::ProcessingFailed("mock".to_string()))
        }
        fn temp_file(&self, _suffix: &str) -> Result<PathBuf, BntoError> {
            Err(BntoError::ProcessingFailed("mock".to_string()))
        }
        fn env_var(&self, key: &str) -> Option<String> {
            self.vars.get(key).cloned()
        }
        fn work_dir(&self) -> Result<&Path, BntoError> {
            Err(BntoError::ProcessingFailed("mock".to_string()))
        }
    }

    #[test]
    fn test_secrets_preflight_no_secrets_ok() {
        let def = make_definition(&["input", "output"]);
        let result = check_pipeline_secrets(&def, &NoopContext);
        assert!(result.is_ok());
    }

    #[test]
    fn test_secrets_preflight_all_present_ok() {
        let def = make_definition_with_secrets(vec![required_secret("API_KEY")]);
        let ctx = EnvContext::new(&[("API_KEY", "sk-123")]);
        let result = check_pipeline_secrets(&def, &ctx);
        assert!(result.is_ok());
    }

    #[test]
    fn test_secrets_preflight_required_missing_fails() {
        let def = make_definition_with_secrets(vec![required_secret("API_KEY")]);
        let result = check_pipeline_secrets(&def, &NoopContext);
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        assert!(msg.contains("API_KEY"));
        assert!(msg.contains("~/.config/bnto/.env"));
    }

    #[test]
    fn test_secrets_preflight_optional_missing_ok() {
        let def = make_definition_with_secrets(vec![optional_secret("OPTIONAL_KEY")]);
        let result = check_pipeline_secrets(&def, &NoopContext);
        assert!(result.is_ok());
    }

    #[test]
    fn test_secrets_preflight_mixed_missing_only_required() {
        let def = make_definition_with_secrets(vec![
            required_secret("REQUIRED_KEY"),
            optional_secret("OPTIONAL_KEY"),
        ]);
        let result = check_pipeline_secrets(&def, &NoopContext);
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        assert!(msg.contains("REQUIRED_KEY"));
        assert!(!msg.contains("OPTIONAL_KEY"));
    }
}