nishikaze 0.3.0

Zephyr build system companion.
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
//! Project configuration discovery helpers.

use std::fmt;
use std::path::{Path, PathBuf};

use crate::config::schema::FileConfig;
use crate::core::cli::{Cli, Command};

/// Configuration discovery context.
#[derive(Debug, Clone)]
pub struct ConfigCtx {
    /// Resolved project root containing kaze.toml.
    pub project_dir: PathBuf,
    /// Current working directory at invocation time.
    pub cwd: PathBuf,
    /// Whether kaze was invoked from inside build/ directory.
    pub invoked_from_build: bool,
}

/// Errors from configuration discovery.
#[derive(Debug)]
pub enum ConfigError {
    /// I/O error during discovery.
    Io(std::io::Error),
    /// No kaze.toml found while searching upwards.
    NotFound {
        /// Directory where the upward search started.
        start: PathBuf,
    },
}

impl fmt::Display for ConfigError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            Self::Io(ref e) => write!(f, "config error: {e}"),
            Self::NotFound { ref start } => write!(f, "config not found in: {}", start.display()),
        }
    }
}

impl std::error::Error for ConfigError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match *self {
            Self::Io(ref e) => Some(e),
            Self::NotFound { .. } => None,
        }
    }
}

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

/**
 * Discovers project configuration context.
 *
 * # Errors
 * Returns `ConfigError::Io` for filesystem failures and
 * `ConfigError::NotFound` when kaze.toml cannot be located.
 */
pub fn discover(project_override: Option<&Path>, cli: &Cli) -> Result<ConfigCtx, ConfigError> {
    let cwd = std::env::current_dir()?;
    let start = project_override.unwrap_or(&cwd);

    // ignore missing config file for `init` and `boards` commands
    let command = &cli.command;
    let project_dir = match *command {
        Command::Init(_) | Command::Boards => cwd.clone(),
        _ => find_upwards(start, "kaze.toml").ok_or_else(|| ConfigError::NotFound {
            start: start.to_path_buf(),
        })?,
    };

    let invoked_from_build = cwd.starts_with(project_dir.join("build"));
    Ok(ConfigCtx {
        project_dir,
        cwd,
        invoked_from_build,
    })
}

/**
 * Walks upward from `start` looking for a marker file, returning the directory
 * that contains it.
 *
 * # Arguments
 * - `start`: Directory to begin the upward search from.
 * - `marker`: Marker filename to locate.
 *
 * # Returns
 * Directory containing the marker file, or `None` if not found.
 */
#[must_use]
fn find_upwards(start: &Path, marker: &str) -> Option<PathBuf> {
    let mut cur = start;
    loop {
        if cur.join(marker).is_file() {
            return Some(cur.to_path_buf());
        }
        cur = cur.parent()?;
    }
}

/// Resolved configuration values for a single profile.
#[derive(Debug, Clone)]
pub struct ResolvedConfig {
    /// Discovery context used to resolve paths.
    pub ctx: ConfigCtx,
    /// Selected profile name, if any.
    pub profile: Option<String>,
    /// Resolved board name.
    pub board: String,
    /// Resolved runner name.
    pub runner: Option<String>,

    /// Project build root path.
    pub build_root: PathBuf,
    /// Build directory for the resolved profile.
    pub build_dir: PathBuf,

    /// Whether the project uses sysbuild.
    pub sysbuild: bool,

    /// Zephyr workspace root, if detected.
    pub zephyr_ws: Option<PathBuf>,
    /// Zephyr base path, if detected.
    pub zephyr_base: Option<PathBuf>,
    /// Zephyr workspace manifest repository url if provided.
    pub zephyr_url: Option<String>,
    /// Zephyr workspace manifest file path if provided.
    pub zephyr_manifest: Option<PathBuf>,

    /// Whether the project requires `BoM` build
    pub bom_build: bool,
    /// SPDX `BoM` version
    pub bom_v: String,

    /// Extra args for the configure step.
    pub args_conf: Vec<String>,
    /// Extra args for the build step.
    pub args_build: Vec<String>,
    /// Extra args for the flash step.
    pub args_flash: Vec<String>,
    /// Extra args for the run step.
    pub args_run: Vec<String>,
}

/// Errors during configuration resolution.
#[derive(Debug)]
pub enum ResolveError {
    /// No board can be resolved.
    NoBoardResolved,
    /// Profile name does not exist.
    UnknownProfile(String),
}

impl fmt::Display for ResolveError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            Self::NoBoardResolved => write!(f, "no board resolved"),
            Self::UnknownProfile(ref profile) => write!(f, "unknown profile: {profile}"),
        }
    }
}

impl std::error::Error for ResolveError {}

/**
 * Resolves a single configuration profile.
 *
 * # Errors
 * Returns `ResolveError::UnknownProfile` when an explicit profile is unknown and
 * `ResolveError::NoBoardResolved` when no board can be determined.
 *
 * # Panics
 * Panics if profile metadata is inconsistent with selection results
 * (e.g. a selected profile is missing from the config).
 */
pub fn resolve_single(
    cli: &Cli,
    ctx: &ConfigCtx,
    cfg: &FileConfig,
) -> Result<ResolvedConfig, ResolveError> {
    let profile = select_profile(cli, cfg)?;

    // base values from global project config
    let mut board = cfg.project.board.clone();
    let mut runner = cfg.project.runner.clone();

    // apply profile overrides
    if let Some(ref p) = profile {
        let prof = cfg
            .profiles
            .get(p)
            .ok_or_else(|| ResolveError::UnknownProfile(p.clone()))?;
        if prof.board.is_some() {
            board.clone_from(&prof.board);
        }
        if prof.runner.is_some() {
            runner.clone_from(&prof.runner);
        }
    }

    // apply CLI overrides
    if cli.board.is_some() {
        board.clone_from(&cli.board);
    }
    if cli.runner.is_some() {
        runner.clone_from(&cli.runner);
    }

    // ignore board resolution for `init` and `boards` commands
    let command = &cli.command;
    let board_resolved = match *command {
        Command::Boards => String::default(),
        Command::Init(_) => board.unwrap_or_else(|| "nucleo_f767zi".to_owned()),
        _ => board.ok_or(ResolveError::NoBoardResolved)?,
    };

    // build dir resolution
    let build_root = ctx.project_dir.join(&cfg.build.root);
    let build_dir = profile
        .as_ref()
        .map_or_else(|| build_root.clone(), |p| build_root.join(p));

    // sysbuild detection
    let sysbuild = is_sysbuild(&ctx.project_dir);

    // zephyr workspace discovery
    let (zephyr_ws, zephyr_base) = discover_zephyr(&ctx.project_dir, cfg);
    let zephyr_url = cfg.zephyr.url.clone();
    let zephyr_manifest = cfg.zephyr.manifest.as_ref().map(PathBuf::from);

    // spdx bom config
    let bom_build = cfg.bom.build;
    let bom_v = cfg.bom.version.clone();

    // extra args
    let mut args_conf = cfg.project.args.conf.to_vec();
    let mut args_build = cfg.project.args.build.to_vec();
    let mut args_flash = cfg.project.args.flash.to_vec();
    let mut args_run = cfg.project.args.run.to_vec();

    if let Some(ref p) = profile {
        let prof = cfg.profiles.get(p).expect("checked above");
        args_conf.extend(prof.args.conf.to_vec());
        args_build.extend(prof.args.build.to_vec());
        args_flash.extend(prof.args.flash.to_vec());
        args_run.extend(prof.args.run.to_vec());
    }

    Ok(ResolvedConfig {
        ctx: ctx.clone(),
        profile,
        board: board_resolved,
        runner,
        build_root,
        build_dir,
        sysbuild,
        zephyr_ws,
        zephyr_base,
        zephyr_url,
        zephyr_manifest,
        bom_build,
        bom_v,
        args_conf,
        args_build,
        args_flash,
        args_run,
    })
}

/**
 * Resolves configuration for all profiles.
 *
 * # Returns
 * Vector of per-profile results in profile iteration order.
 */
#[must_use]
pub fn resolve_all(
    cli: &Cli,
    ctx: &ConfigCtx,
    cfg: &FileConfig,
) -> Vec<Result<ResolvedConfig, ResolveError>> {
    if cfg.profiles.is_empty() {
        return vec![resolve_single(cli, ctx, cfg)];
    }
    cfg.profiles
        .keys()
        .cloned()
        .map(|p| {
            let mut cli2 = cli.clone();
            cli2.profile = Some(p);
            cli2.all = false;
            resolve_single(&cli2, ctx, cfg)
        })
        .collect()
}

/**
 * Chooses the active profile based on CLI flags and available profiles.
 *
 * # Arguments
 * - `cli`: Parsed CLI options.
 * - `cfg`: Loaded configuration for profile lookup.
 *
 * # Returns
 * Selected profile name (or `None` when profiles are absent).
 *
 * # Errors
 * Returns `ResolveError::UnknownProfile` when a requested profile does not exist.
 */
fn select_profile(cli: &Cli, cfg: &FileConfig) -> Result<Option<String>, ResolveError> {
    if cfg.profiles.is_empty() {
        return Ok(None);
    }

    if cli.all {
        return Ok(Some(default_profile(cfg)));
    }

    if let Some(p) = cli.profile.as_deref() {
        if !cfg.profiles.contains_key(p) {
            return Err(ResolveError::UnknownProfile(p.to_owned()));
        }

        return Ok(Some(p.to_owned()));
    }

    Ok(Some(default_profile(cfg)))
}

/**
 * Picks the configured default profile, or falls back to the first entry.
 *
 * # Arguments
 * - `cfg`: Loaded configuration containing profiles.
 *
 * # Returns
 * Selected profile name.
 */
fn default_profile(cfg: &FileConfig) -> String {
    if let Some(p) = cfg.project.default_profile.as_deref() {
        if cfg.profiles.contains_key(p) {
            return p.to_owned();
        }
    }

    cfg.profiles.keys().next().expect("non-empty").clone()
}

/**
 * Returns true when sysbuild configuration files/directories are present.
 *
 * # Arguments
 * - `project_dir`: Project root directory.
 *
 * # Returns
 * `true` when sysbuild configuration is detected, `false` otherwise.
 */
fn is_sysbuild(project_dir: &Path) -> bool {
    project_dir.join("sysbuild.conf").is_file() || project_dir.join("sysbuild").is_dir()
}

/**
 * Resolves Zephyr workspace/base from config, environment, or workspace scan.
 *
 * # Arguments
 * - `project_dir`: Project root used for workspace discovery.
 * - `cfg`: Loaded configuration for explicit workspace/base overrides.
 *
 * # Returns
 * Tuple of `(workspace, base)` when detected, otherwise `(None, None)`.
 */
fn discover_zephyr(project_dir: &Path, cfg: &FileConfig) -> (Option<PathBuf>, Option<PathBuf>) {
    // 1) explicit config
    let mut ws = cfg.zephyr.workspace.as_ref().map(PathBuf::from);
    let mut base = cfg.zephyr.base.as_ref().map(PathBuf::from);

    ws = abs_canonical(ws, project_dir);
    base = abs_canonical(base, project_dir);

    if ws.is_some() || base.is_some() {
        return (
            ws.clone(),
            base.or_else(|| ws.as_ref().map(|w| w.join("zephyr"))),
        );
    }

    // 2) env vars
    if let Some(zb) = std::env::var_os("ZEPHYR_BASE") {
        let base_env = PathBuf::from(zb);
        let ws_env = base_env
            .parent()
            .and_then(|p| p.parent().map(std::path::Path::to_path_buf));

        return (ws_env, Some(base_env));
    }

    // 3) try finding workspace
    if let Some(ws_find) = find_zephyr_workspace(project_dir) {
        return (Some(ws_find.clone()), Some(ws_find.join("zephyr")));
    }

    (None, None)
}

/**
 * Canonicalizes a path and converts to an absolute one
 *
 * # Arguments
 * - `path`: Path to canonicalize.
 * - `project_dir`: Project directory.
 *
 * # Returns
 * Absolute canonicalized path or `None`, if none provided.
 */
fn abs_canonical(path: Option<PathBuf>, project_dir: &Path) -> Option<PathBuf> {
    if let Some(ref path) = path {
        if path.is_relative() {
            if let Ok(path_canonical) = path.canonicalize() {
                return Some(project_dir.join(path_canonical));
            }
        }
    }

    path
}

/**
 * Walks upward looking for a `.west` workspace root.
 *
 * # Arguments
 * - `start`: Directory to begin the upward search from.
 *
 * # Returns
 * Workspace root path if found, otherwise `None`.
 */
fn find_zephyr_workspace(start: &Path) -> Option<PathBuf> {
    let mut cur = start;
    loop {
        if cur.join(".west").is_dir() {
            return Some(cur.to_path_buf());
        }
        cur = cur.parent()?;
    }
}

#[cfg(test)]
mod tests {
    use std::error::Error;
    use std::path::Path;
    use std::sync::atomic::{AtomicUsize, Ordering};

    use clap::Parser;

    use super::*;
    use crate::config::schema::{
        ArgAtom, ArgList, BuildCfg, FileConfig, PhaseArgsCfg, ProfileCfg, ProjectCfg, ZephyrCfg,
    };
    use crate::core::cli::{InitArgs, PhaseArgs};

    fn make_temp_dir(label: &str) -> PathBuf {
        static COUNTER: AtomicUsize = AtomicUsize::new(0);
        let mut dir = std::env::temp_dir();
        dir.push(format!(
            "nishikaze-core-config-{}-{}",
            label,
            COUNTER.fetch_add(1, Ordering::Relaxed)
        ));
        if dir.exists() {
            std::fs::remove_dir_all(&dir).expect("clean temp dir");
        }
        std::fs::create_dir_all(&dir).expect("create temp dir");
        dir
    }

    fn base_cfg() -> FileConfig {
        FileConfig {
            project: ProjectCfg {
                board: Some("b1".into()),
                runner: Some("r1".into()),
                default_profile: Some("dev".into()),
                name: None,
                args: PhaseArgsCfg::default(),
            },
            build: BuildCfg {
                root: "build".into(),
                link_compile_commands: None,
            },
            zephyr: ZephyrCfg::default(),
            ..FileConfig::default()
        }
    }

    fn ctx() -> ConfigCtx {
        ConfigCtx {
            project_dir: PathBuf::from("/tmp/project"),
            cwd: PathBuf::from("/tmp/project"),
            invoked_from_build: false,
        }
    }

    fn cli_with_cmd(command: Command) -> Cli {
        let mut cli = Cli::try_parse_from(["kaze", "clean"]).expect("parse ok");
        cli.command = command;
        cli
    }

    #[test]
    fn discover_skips_config_for_init_and_boards() {
        let dir = make_temp_dir("discover-init");
        let old = std::env::current_dir().expect("cwd");
        std::env::set_current_dir(&dir).expect("set cwd");

        let cli_init = cli_with_cmd(Command::Init(InitArgs::default()));
        let ctx_init = discover(None, &cli_init).expect("discover init ok");
        assert_eq!(ctx_init.project_dir, dir);

        let cli_boards = cli_with_cmd(Command::Boards);
        let ctx_boards = discover(None, &cli_boards).expect("discover boards ok");
        assert_eq!(ctx_boards.project_dir, dir);

        std::env::set_current_dir(old).expect("restore cwd");
    }

    #[test]
    fn discover_errors_when_config_missing() {
        let dir = make_temp_dir("discover-missing");
        let cli = cli_with_cmd(Command::Clean);
        let err = discover(Some(&dir), &cli).expect_err("missing config");
        assert!(matches!(&err, ConfigError::NotFound { .. }));
        if let ConfigError::NotFound { start } = err {
            assert_eq!(start, dir);
        }
    }

    #[test]
    fn find_upwards_finds_marker_and_returns_none_when_absent() {
        let dir = make_temp_dir("find-upwards");
        std::fs::write(dir.join("kaze.toml"), "").expect("write marker");
        let nested = dir.join("a").join("b");
        std::fs::create_dir_all(&nested).expect("create nested");

        let found = find_upwards(&nested, "kaze.toml");
        assert_eq!(found, Some(dir));

        let missing = find_upwards(&nested, "not-here");
        assert_eq!(missing, None);
    }

    #[test]
    fn config_error_display_and_source() {
        let io_err = std::io::Error::other("boom");
        let err = ConfigError::from(io_err);
        assert!(err.to_string().contains("config error: boom"));
        assert!(err.source().is_some());

        let missing = ConfigError::NotFound {
            start: PathBuf::from("/tmp/missing"),
        };
        assert!(
            missing
                .to_string()
                .contains("config not found in: /tmp/missing")
        );
        assert!(missing.source().is_none());
    }

    #[test]
    fn resolve_error_display_formats() {
        let missing = ResolveError::NoBoardResolved;
        assert_eq!(missing.to_string(), "no board resolved");

        let unknown = ResolveError::UnknownProfile("dev".into());
        assert_eq!(unknown.to_string(), "unknown profile: dev");
    }

    #[test]
    fn select_profile_returns_none_when_no_profiles() {
        let cfg = base_cfg();
        let cli = cli_with_cmd(Command::Clean);
        let selected = select_profile(&cli, &cfg).expect("select ok");
        assert_eq!(selected, None);
    }

    #[test]
    fn select_profile_falls_back_when_default_missing() {
        let mut cfg = base_cfg();
        cfg.project.default_profile = Some("missing".into());
        cfg.profiles.insert("prod".into(), ProfileCfg::default());
        cfg.profiles.insert("dev".into(), ProfileCfg::default());

        let cli = cli_with_cmd(Command::Clean);
        let selected = select_profile(&cli, &cfg).expect("select ok");
        assert_eq!(selected.as_deref(), Some("prod"));
    }

    #[test]
    fn select_profile_unknown_returns_error() {
        let mut cfg = base_cfg();
        cfg.profiles.insert("dev".into(), ProfileCfg::default());
        let mut cli = Cli::try_parse_from(["kaze", "clean"]).expect("parse ok");
        cli.profile = Some("missing".into());
        let err = select_profile(&cli, &cfg).expect_err("unknown profile");
        assert!(matches!(err, ResolveError::UnknownProfile(_)));
    }

    #[test]
    fn select_profile_default_used_when_all_and_profiles_exist() {
        let mut cfg = base_cfg();
        cfg.profiles.insert("dev".into(), ProfileCfg::default());
        cfg.profiles.insert("prod".into(), ProfileCfg::default());

        let mut cli = Cli::try_parse_from(["kaze", "clean"]).expect("parse ok");
        cli.all = true;

        let selected = select_profile(&cli, &cfg).expect("select ok");
        assert_eq!(selected.as_deref(), Some("dev"));
    }

    #[test]
    fn resolve_single_errors_without_board() {
        let mut cfg = base_cfg();
        cfg.project.board = None;
        cfg.profiles.insert("dev".into(), ProfileCfg::default());

        let cli = Cli::try_parse_from(["kaze", "clean"]).expect("parse ok");
        let err = resolve_single(&cli, &ctx(), &cfg).expect_err("missing board");
        assert!(matches!(err, ResolveError::NoBoardResolved));
    }

    #[test]
    fn resolve_single_applies_profile_overrides() {
        let mut cfg = base_cfg();
        cfg.profiles.insert(
            "dev".into(),
            ProfileCfg {
                board: Some("b2".into()),
                runner: Some("r2".into()),
                args: PhaseArgsCfg::default(),
            },
        );

        let mut cli = Cli::try_parse_from(["kaze", "clean"]).expect("parse ok");
        cli.profile = Some("dev".into());

        let rc = resolve_single(&cli, &ctx(), &cfg).expect("resolve ok");
        assert_eq!(rc.board, "b2");
        assert_eq!(rc.runner.as_deref(), Some("r2"));
    }

    #[test]
    fn resolve_single_cli_overrides_profile() {
        let mut cfg = base_cfg();
        cfg.profiles.insert(
            "dev".into(),
            ProfileCfg {
                board: Some("b2".into()),
                runner: Some("r2".into()),
                args: PhaseArgsCfg::default(),
            },
        );

        let mut cli = Cli::try_parse_from(["kaze", "clean"]).expect("parse ok");
        cli.profile = Some("dev".into());
        cli.board = Some("b3".into());
        cli.runner = Some("r3".into());

        let rc = resolve_single(&cli, &ctx(), &cfg).expect("resolve ok");
        assert_eq!(rc.board, "b3");
        assert_eq!(rc.runner.as_deref(), Some("r3"));
    }

    #[test]
    fn resolve_single_allows_init_without_board() {
        let mut cfg = base_cfg();
        cfg.project.board = None;

        let cli = cli_with_cmd(Command::Init(InitArgs::default()));
        let rc = resolve_single(&cli, &ctx(), &cfg).expect("should not require board");
        assert_eq!(rc.board, "nucleo_f767zi");
    }

    #[test]
    fn resolve_single_allows_boards_without_board() {
        let mut cfg = base_cfg();
        cfg.project.board = None;

        let cli = cli_with_cmd(Command::Boards);
        let rc = resolve_single(&cli, &ctx(), &cfg).expect("boards should not require board");
        assert!(rc.board.is_empty());
    }

    #[test]
    fn resolve_single_merges_phase_args() {
        let mut cfg = base_cfg();
        cfg.project.args.conf = ArgList(vec![ArgAtom::One("-DCFG=1".into())]);
        cfg.project.args.build = ArgList(vec![ArgAtom::One("-DBUILD=1".into())]);
        cfg.project.args.flash = ArgList(vec![ArgAtom::One("-DFLASH=1".into())]);
        cfg.project.args.run = ArgList(vec![ArgAtom::One("-DRUN=1".into())]);

        cfg.profiles.insert(
            "dev".into(),
            ProfileCfg {
                board: None,
                runner: None,
                args: PhaseArgsCfg {
                    conf: ArgList(vec![ArgAtom::One("-DCFG=2".into())]),
                    build: ArgList(vec![ArgAtom::One("-DBUILD=2".into())]),
                    flash: ArgList(vec![ArgAtom::One("-DFLASH=2".into())]),
                    run: ArgList(vec![ArgAtom::One("-DRUN=2".into())]),
                },
            },
        );

        let mut cli = cli_with_cmd(Command::Build(PhaseArgs::default()));
        cli.profile = Some("dev".into());

        let rc = resolve_single(&cli, &ctx(), &cfg).expect("resolve ok");
        assert_eq!(rc.args_conf, vec!["-DCFG=1", "-DCFG=2"]);
        assert_eq!(rc.args_build, vec!["-DBUILD=1", "-DBUILD=2"]);
        assert_eq!(rc.args_flash, vec!["-DFLASH=1", "-DFLASH=2"]);
        assert_eq!(rc.args_run, vec!["-DRUN=1", "-DRUN=2"]);
    }

    #[test]
    fn resolve_single_propagates_bom_config() {
        let cfg: FileConfig = toml::from_str(
            r#"
[project]
board = "native_sim"
"#,
        )
        .expect("parse ok");
        let cli = cli_with_cmd(Command::Clean);
        let rc = resolve_single(&cli, &ctx(), &cfg).expect("resolve ok");
        assert!(!rc.bom_build);
        assert_eq!(rc.bom_v, "2.2");

        let cfg_overrides: FileConfig = toml::from_str(
            r#"
[project]
board = "native_sim"

[bom]
build = true
version = "3"
"#,
        )
        .expect("parse ok");
        let rc_overrides = resolve_single(&cli, &ctx(), &cfg_overrides).expect("resolve ok");
        assert!(rc_overrides.bom_build);
        assert_eq!(rc_overrides.bom_v, "3");
    }

    #[test]
    fn resolve_single_propagates_zephyr_workspace_config() {
        let cfg: FileConfig = toml::from_str(
            r#"
[project]
board = "native_sim"

[zephyr]
url = "https://example.com/zephyr"
manifest = "west.yml"
"#,
        )
        .expect("parse ok");

        let cli = cli_with_cmd(Command::Clean);
        let rc = resolve_single(&cli, &ctx(), &cfg).expect("resolve ok");
        assert_eq!(rc.zephyr_url.as_deref(), Some("https://example.com/zephyr"));
        assert_eq!(rc.zephyr_manifest.as_deref(), Some(Path::new("west.yml")));
    }

    #[test]
    fn resolve_all_resolves_each_profile() {
        let mut cfg = base_cfg();
        cfg.profiles.insert("dev".into(), ProfileCfg::default());
        cfg.profiles.insert(
            "prod".into(),
            ProfileCfg {
                board: Some("b2".into()),
                runner: None,
                args: PhaseArgsCfg::default(),
            },
        );

        let cli = Cli::try_parse_from(["kaze", "clean"]).expect("parse ok");
        let results = resolve_all(&cli, &ctx(), &cfg);
        assert_eq!(results.len(), 2);
        assert!(results.iter().all(Result::is_ok));
    }

    #[test]
    fn resolve_all_handles_no_profiles() {
        let cfg = base_cfg();
        let cli = cli_with_cmd(Command::Clean);
        let results = resolve_all(&cli, &ctx(), &cfg);
        assert_eq!(results.len(), 1);
        let first = results.into_iter().next().expect("one result");
        first.expect("resolve ok");
    }

    #[test]
    fn is_sysbuild_detects_conf_and_dir() {
        let dir = make_temp_dir("sysbuild-detect");
        assert!(!is_sysbuild(&dir));

        std::fs::write(dir.join("sysbuild.conf"), "").expect("write sysbuild.conf");
        assert!(is_sysbuild(&dir));

        std::fs::remove_file(dir.join("sysbuild.conf")).expect("remove sysbuild.conf");
        std::fs::create_dir_all(dir.join("sysbuild")).expect("mkdir sysbuild");
        assert!(is_sysbuild(&dir));
    }

    #[test]
    fn discover_zephyr_prefers_explicit_config() {
        let dir = make_temp_dir("zephyr-explicit");
        let mut cfg = base_cfg();
        cfg.zephyr.workspace = Some(dir.join("ws").to_string_lossy().into_owned());
        cfg.zephyr.base = Some(dir.join("zb").to_string_lossy().into_owned());

        let (ws, base) = discover_zephyr(&dir, &cfg);
        assert_eq!(ws, Some(dir.join("ws")));
        assert_eq!(base, Some(dir.join("zb")));
    }

    #[test]
    fn discover_zephyr_rel_workspace_uses_abs_canonical() {
        let dir = make_temp_dir("zephyr-rel");
        let ws = dir.join("ws");
        std::fs::create_dir_all(&ws).expect("mkdir ws");

        let mut cfg = base_cfg();
        cfg.zephyr.workspace = Some("ws".into());

        let old = std::env::current_dir().expect("get cwd");
        std::env::set_current_dir(&dir).expect("set cwd");
        let (found_ws, found_base) = discover_zephyr(&dir, &cfg);
        std::env::set_current_dir(old).expect("restore cwd");
        assert_eq!(found_ws, Some(dir.join("ws")));
        assert_eq!(found_base, Some(dir.join("ws/zephyr")));
    }

    #[test]
    fn discover_zephyr_uses_env_base() {
        let dir = make_temp_dir("zephyr-env");
        let base = dir.join("west").join("zephyr");
        std::fs::create_dir_all(&base).expect("mkdir zephyr base");

        let old = std::env::var_os("ZEPHYR_BASE");
        // SAFETY: Test controls process environment; no concurrent access here.
        unsafe {
            std::env::set_var("ZEPHYR_BASE", &base);
        }

        let cfg = base_cfg();
        let (ws, zb) = discover_zephyr(&dir, &cfg);
        assert_eq!(zb, Some(base.clone()));
        let expected_ws = base
            .parent()
            .expect("base has parent")
            .parent()
            .expect("base has grandparent")
            .to_path_buf();
        assert_eq!(ws, Some(expected_ws));

        if let Some(old) = old {
            // SAFETY: Restoring environment to prior state within this test.
            unsafe {
                std::env::set_var("ZEPHYR_BASE", old);
            }
        } else {
            // SAFETY: Removing test-scoped environment override.
            unsafe {
                std::env::remove_var("ZEPHYR_BASE");
            }
        }
    }

    #[test]
    fn discover_zephyr_restores_preexisting_env_base() {
        let dir = make_temp_dir("zephyr-env-preexisting");
        let base = dir.join("west").join("zephyr");
        std::fs::create_dir_all(&base).expect("mkdir zephyr base");

        let original = std::env::var_os("ZEPHYR_BASE");
        let old_value = PathBuf::from("/tmp/zephyr-preexisting-restore");
        // SAFETY: Test controls process environment; no concurrent access here.
        unsafe {
            std::env::set_var("ZEPHYR_BASE", &old_value);
        }

        let old = std::env::var_os("ZEPHYR_BASE");
        // SAFETY: Test controls process environment; no concurrent access here.
        unsafe {
            std::env::set_var("ZEPHYR_BASE", &base);
        }

        let cfg = base_cfg();
        let (_ws, zb) = discover_zephyr(&dir, &cfg);
        assert_eq!(zb, Some(base));

        if let Some(old) = old {
            // SAFETY: Restoring environment to prior state within this test.
            unsafe {
                std::env::set_var("ZEPHYR_BASE", old);
            }
        } else {
            // SAFETY: Removing test-scoped environment override.
            unsafe {
                std::env::remove_var("ZEPHYR_BASE");
            }
        }

        assert_eq!(
            std::env::var_os("ZEPHYR_BASE"),
            Some(old_value.into_os_string())
        );

        if let Some(val) = original {
            // SAFETY: Restoring environment to prior state within this test.
            unsafe {
                std::env::set_var("ZEPHYR_BASE", val);
            }
        } else {
            // SAFETY: Removing test-scoped environment override.
            unsafe {
                std::env::remove_var("ZEPHYR_BASE");
            }
        }
    }

    #[test]
    fn discover_zephyr_restores_existing_env_base() {
        let dir = make_temp_dir("zephyr-env-restore");
        let base = dir.join("west").join("zephyr");
        std::fs::create_dir_all(&base).expect("mkdir zephyr base");

        let original = std::env::var_os("ZEPHYR_BASE");
        let old_value = PathBuf::from("/tmp/zephyr-preexisting");
        // SAFETY: Test controls process environment; no concurrent access here.
        unsafe {
            std::env::set_var("ZEPHYR_BASE", &old_value);
        }

        let old = std::env::var_os("ZEPHYR_BASE");
        // SAFETY: Test controls process environment; no concurrent access here.
        unsafe {
            std::env::set_var("ZEPHYR_BASE", &base);
        }

        let cfg = base_cfg();
        let (_ws, zb) = discover_zephyr(&dir, &cfg);
        assert_eq!(zb, Some(base));

        if let Some(old) = old {
            // SAFETY: Restoring environment to prior state within this test.
            unsafe {
                std::env::set_var("ZEPHYR_BASE", old);
            }
        } else {
            // SAFETY: Removing test-scoped environment override.
            unsafe {
                std::env::remove_var("ZEPHYR_BASE");
            }
        }

        assert_eq!(
            std::env::var_os("ZEPHYR_BASE"),
            Some(old_value.into_os_string())
        );

        if let Some(val) = original {
            // SAFETY: Restoring environment to prior state within this test.
            unsafe {
                std::env::set_var("ZEPHYR_BASE", val);
            }
        } else {
            // SAFETY: Removing test-scoped environment override.
            unsafe {
                std::env::remove_var("ZEPHYR_BASE");
            }
        }
    }

    #[test]
    fn discover_zephyr_finds_workspace() {
        let dir = make_temp_dir("zephyr-workspace");
        let ws = dir.join("ws");
        std::fs::create_dir_all(ws.join(".west")).expect("mkdir .west");

        let cfg = base_cfg();
        let (found_ws, found_base) = discover_zephyr(&ws, &cfg);
        assert_eq!(found_ws, Some(ws.clone()));
        assert_eq!(found_base, Some(ws.join("zephyr")));
    }

    #[test]
    fn discover_zephyr_none_when_absent() {
        let dir = make_temp_dir("zephyr-none");
        let cfg = base_cfg();
        let (ws, base) = discover_zephyr(&dir, &cfg);
        assert_eq!(ws, None);
        assert_eq!(base, None);
    }
}