mecha10-cli 0.6.3

Mecha10 CLI tool
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
//! Build command handler
//!
//! Orchestrates project building using cargo with target-specific features.

use crate::commands::{BuildCommand, BuildTargetArgs, UploadArgs, VersionBump};
use crate::context::CliContext;
use crate::handlers::config::push_configs;
use crate::handlers::upload::handle_upload;
use crate::paths;
use crate::templates::RustTemplates;
use anyhow::{Context, Result};
use mecha10_core::enum_str_method;
use std::process::Command;

/// Build target type
#[derive(Debug, Clone, Copy)]
pub enum BuildTarget {
    /// Robot nodes (edge/on-robot)
    Robot,
    /// Remote nodes (cloud/remote server)
    Remote,
}

enum_str_method!(
    /// Get the cargo feature flags for this target
    fn features(BuildTarget) -> &'static str {
        Robot => "target-robot",
        Remote => "target-remote",
    }
);

enum_str_method!(
    /// Get display name for this target
    fn display_name(BuildTarget) -> &'static str {
        Robot => "Robot",
        Remote => "Remote",
    }
);

enum_str_method!(
    /// Get description for this target
    fn description(BuildTarget) -> &'static str {
        Robot => "edge/on-robot nodes",
        Remote => "cloud/remote server nodes",
    }
);

enum_str_method!(
    /// Get string representation for metadata
    fn as_str(BuildTarget) -> &'static str {
        Robot => "robot",
        Remote => "remote",
    }
);

/// Handle the build command
pub async fn handle_build(ctx: &mut CliContext, command: &BuildCommand) -> Result<()> {
    match command {
        BuildCommand::Robot(args) => build_target(ctx, BuildTarget::Robot, args).await,
        BuildCommand::Remote(args) => build_target(ctx, BuildTarget::Remote, args).await,
    }
}

/// Build for a specific target
async fn build_target(ctx: &mut CliContext, target: BuildTarget, args: &BuildTargetArgs) -> Result<()> {
    println!();
    println!("🔨 Building Mecha10 Project - {} Target", target.display_name());
    println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
    println!();

    // Verify we're in a project
    if !ctx.is_project_initialized() {
        println!("⚠️  Not in a Mecha10 project directory");
        println!();
        return Err(anyhow::anyhow!("Not in a Mecha10 project"));
    }

    // Detect project to ensure it's valid
    let project = ctx.project()?;
    let project_name = project.name()?;

    // Validate mecha10.json + every referenced node config before doing any
    // real build work -- same shared function `mecha10 config validate` and
    // `mecha10 lint` use, so there's no copy-pasted validation logic here.
    // Catching a broken config now avoids burning a cargo/Docker build (and
    // later pushing bad configs) on a project that was never going to work.
    println!("Validating configs (mecha10.json + node configs)...");
    crate::config_validation::validate_config(None).context("Config validation failed")?;
    println!("✅ Config validation passed");
    println!();

    // Set MECHA10_ENV in the project's .env file (production unless --dev flag). This is the
    // "which environment was this last built for" signal, routed through the .env +
    // MECHA10_ENV mechanism established by LAB-2039 rather than a mecha10.json field
    // (lifecycle.default_mode, removed in LAB-2040).
    let mode = if args.dev { "dev" } else { "production" };
    update_env_mode(ctx, mode).await?;
    println!("Environment: {}", mode);

    // Handle version update if requested
    let version = if let Some(bump) = &args.bump {
        let new_version = update_version(ctx, Some(*bump), None).await?;
        println!("Version: {} (bumped)", new_version);
        Some(new_version)
    } else if let Some(version) = &args.version {
        let new_version = update_version(ctx, None, Some(version.clone())).await?;
        println!("Version: {} (set)", new_version);
        Some(new_version)
    } else {
        // Read current version for display
        let config = ctx.load_project_config().await?;
        println!("Version: {}", config.version);
        None
    };

    println!("Project: {}", project_name);
    println!("Target:  {} ({})", target.display_name(), target.description());
    println!();

    // Regenerate main.rs from current CLI template
    // This ensures projects created with older CLI versions get the latest fixes
    regenerate_main_rs(ctx, &project_name).await?;
    ensure_core_messaging_feature(ctx).await?;
    update_core_dependency_lock(ctx).await?;

    // Build using native cargo
    let result = build_with_cargo(ctx, target, args).await;

    // Show version in success message if it was updated
    if let Some(v) = version {
        if result.is_ok() {
            println!("📦 Built version: {}", v);
            println!();
        }
    }

    // If build failed, propagate error without running post-build steps
    result?;

    // After any successful build, push configs (changed only) and upload binary.
    // `push_configs` itself regenerates `websocket-bridge`'s relay topic allowlist from other
    // nodes' own configs (LAB relay-topics-core-deriver) before gathering local files, so
    // what's uploaded here already reflects the current derived allowlist.
    println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
    println!("📋 Pushing configs...");
    println!();
    push_configs(ctx).await?;
    println!();

    println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
    let upload_args = UploadArgs {
        binary: None,
        config: None,
        registry_url: None,
        version: None,
        arch: None,
        target: None,
        dry_run: false,
    };
    handle_upload(ctx, &upload_args).await?;

    Ok(())
}

/// Build using native cargo
async fn build_with_cargo(ctx: &CliContext, target: BuildTarget, args: &BuildTargetArgs) -> Result<()> {
    println!("Feature: --features {}", target.features());

    println!("Mode:    Release (optimized)");

    if let Some(arch) = &args.target {
        println!("Arch:    {} (cross-compilation)", arch);
    } else {
        println!("Arch:    Host architecture");
    }
    println!();

    // Build using cargo
    println!("Running cargo build...");
    println!();

    let mut cmd = Command::new("cargo");
    cmd.arg("build")
        .arg("--no-default-features")
        .arg("--features")
        .arg(target.features())
        .current_dir(&ctx.working_dir);

    cmd.arg("--release");

    if let Some(target_arch) = &args.target {
        cmd.arg("--target").arg(target_arch);
    }

    let status = cmd.status()?;

    println!();

    if status.success() {
        println!("✅ Build completed successfully");
        println!();

        // Show output location
        let target_dir = paths::target_path_with_triple(args.target.as_deref(), "release");

        println!("Binaries location: {}", target_dir);
        println!();
    } else {
        println!("❌ Build failed");
        println!();
        return Err(anyhow::anyhow!("Build failed"));
    }

    Ok(())
}

/// Write/update `MECHA10_ENV=<mode>` in the project's `.env` file
///
/// Creates the file if it doesn't exist, updates the `MECHA10_ENV=` line in place if one is
/// already present (preserving every other line untouched), or appends the line if absent.
/// This is a no-op if the value is already up to date.
///
/// This determines which environment configuration is used at runtime (dev or production) —
/// see `mecha10 dev`/launcher-service, which both read `MECHA10_ENV`. Previously this wrote a
/// `lifecycle.default_mode` field in mecha10.json instead; that field was removed in LAB-2040
/// since it duplicated the `.env`-based mechanism LAB-2039 already established.
async fn update_env_mode(ctx: &CliContext, mode: &str) -> Result<()> {
    let env_path = ctx.working_dir.join(paths::env::FILE);

    let existing = match tokio::fs::read_to_string(&env_path).await {
        Ok(content) => content,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
        Err(e) => return Err(e).context("Failed to read .env"),
    };

    let new_line = format!("MECHA10_ENV={mode}");
    let mut previous_value: Option<String> = None;
    let mut lines: Vec<String> = existing
        .lines()
        .map(|line| {
            if let Some(value) = line.strip_prefix("MECHA10_ENV=") {
                previous_value = Some(value.to_string());
                new_line.clone()
            } else {
                line.to_string()
            }
        })
        .collect();

    let unchanged = previous_value.as_deref() == Some(mode);
    if previous_value.is_none() {
        lines.push(new_line);
    }

    if !unchanged {
        let mut updated_content = lines.join("\n");
        updated_content.push('\n');

        tokio::fs::write(&env_path, updated_content)
            .await
            .context("Failed to write .env")?;

        match previous_value {
            Some(prev) => println!("📝 Updated MECHA10_ENV in .env: {} → {}", prev, mode),
            None => println!("📝 Set MECHA10_ENV={} in .env", mode),
        }
    }

    Ok(())
}

/// Update version in mecha10.json
///
/// Either bumps the version (patch, minor, major) or sets a specific version.
async fn update_version(ctx: &CliContext, bump: Option<VersionBump>, set_version: Option<String>) -> Result<String> {
    let config_path = ctx.working_dir.join(paths::PROJECT_CONFIG);

    // Read current config
    let config_content = tokio::fs::read_to_string(&config_path)
        .await
        .context("Failed to read mecha10.json")?;

    let mut config: serde_json::Value =
        serde_json::from_str(&config_content).context("Failed to parse mecha10.json")?;

    let current_version = config["version"].as_str().unwrap_or("0.1.0").to_string();

    // Calculate new version
    let new_version = if let Some(bump_type) = bump {
        bump_semver(&current_version, bump_type)?
    } else if let Some(version) = set_version {
        // Validate version format
        validate_semver(&version)?;
        version
    } else {
        return Ok(current_version);
    };

    // Update config
    config["version"] = serde_json::json!(new_version);

    // Write back
    let updated_content = serde_json::to_string_pretty(&config)?;
    tokio::fs::write(&config_path, updated_content)
        .await
        .context("Failed to write mecha10.json")?;

    println!("📝 Updated mecha10.json: {} → {}", current_version, new_version);

    Ok(new_version)
}

/// Bump a semver version string
fn bump_semver(version: &str, bump: VersionBump) -> Result<String> {
    let parts: Vec<&str> = version.split('.').collect();

    if parts.len() < 3 {
        return Err(anyhow::anyhow!(
            "Invalid version format '{}'. Expected semver (e.g., 1.2.3)",
            version
        ));
    }

    let major: u32 = parts[0].parse().context("Invalid major version number")?;
    let minor: u32 = parts[1].parse().context("Invalid minor version number")?;
    let patch: u32 = parts[2]
        .split('-') // Handle pre-release versions like 1.2.3-beta
        .next()
        .unwrap_or("0")
        .parse()
        .context("Invalid patch version number")?;

    let (new_major, new_minor, new_patch) = match bump {
        VersionBump::Major => (major + 1, 0, 0),
        VersionBump::Minor => (major, minor + 1, 0),
        VersionBump::Patch => (major, minor, patch + 1),
    };

    Ok(format!("{}.{}.{}", new_major, new_minor, new_patch))
}

/// Validate a semver version string
fn validate_semver(version: &str) -> Result<()> {
    let parts: Vec<&str> = version.split('.').collect();

    if parts.len() < 3 {
        return Err(anyhow::anyhow!(
            "Invalid version format '{}'. Expected semver (e.g., 1.2.3)",
            version
        ));
    }

    // Validate each part is a number (allow pre-release suffix on patch)
    parts[0].parse::<u32>().context("Invalid major version number")?;
    parts[1].parse::<u32>().context("Invalid minor version number")?;
    parts[2]
        .split('-')
        .next()
        .unwrap_or("0")
        .parse::<u32>()
        .context("Invalid patch version number")?;

    Ok(())
}

/// Regenerate main.rs from current CLI template
///
/// This ensures projects created with older CLI versions get the latest
/// template fixes (e.g., lifetime fixes, API changes).
async fn regenerate_main_rs(ctx: &CliContext, project_name: &str) -> Result<()> {
    let main_rs_path = ctx.working_dir.join(paths::rust::MAIN_RS);

    // Only regenerate if main.rs exists (don't create for non-standard projects)
    if !main_rs_path.exists() {
        return Ok(());
    }

    println!("Updating src/main.rs from current template...");

    let rust_templates = RustTemplates::new();
    rust_templates
        .create_main_rs(&ctx.working_dir, project_name)
        .await
        .context("Failed to regenerate main.rs")?;

    println!("✅ src/main.rs updated");
    println!();

    Ok(())
}

/// Ensure the project's `mecha10-core` dependency has the `messaging` feature enabled
///
/// `regenerate_main_rs` keeps `src/main.rs` in sync with the current CLI template, but
/// `Cargo.toml` is otherwise left untouched. Projects scaffolded before LAB-2075 (which made
/// the generated `main.rs` import `mecha10_core::command_relay`, itself gated behind the
/// `messaging` feature) get their `main.rs` auto-upgraded on the next build with no matching
/// `Cargo.toml` update, and fail with a confusing "unresolved import" error. This patches just
/// the one dependency line in place -- the same targeted approach `update_env_mode` uses for
/// `.env` -- rather than regenerating the whole file and clobbering any custom dependencies the
/// user added.
async fn ensure_core_messaging_feature(ctx: &CliContext) -> Result<()> {
    let cargo_toml_path = ctx.working_dir.join(paths::rust::CARGO_TOML);

    let content = match tokio::fs::read_to_string(&cargo_toml_path).await {
        Ok(content) => content,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
        Err(e) => return Err(e).context("Failed to read Cargo.toml"),
    };

    let mut changed = false;
    let updated_lines: Vec<String> = content
        .lines()
        .map(|line| {
            let trimmed = line.trim_start();
            if !trimmed.starts_with("mecha10-core") || trimmed.contains("messaging") {
                return line.to_string();
            }
            let Some(eq_pos) = trimmed.find('=') else {
                return line.to_string();
            };
            let key = trimmed[..eq_pos].trim();
            let value = trimmed[eq_pos + 1..].trim();

            changed = true;
            if let Some(inner) = value.strip_prefix('{').and_then(|v| v.strip_suffix('}')) {
                format!("{key} = {{{inner}, features = [\"messaging\"] }}")
            } else {
                format!("{key} = {{ version = {value}, features = [\"messaging\"] }}")
            }
        })
        .collect();

    if changed {
        let mut updated_content = updated_lines.join("\n");
        if content.ends_with('\n') {
            updated_content.push('\n');
        }

        tokio::fs::write(&cargo_toml_path, updated_content)
            .await
            .context("Failed to write Cargo.toml")?;

        println!(
            "📝 Enabled \"messaging\" feature on mecha10-core in Cargo.toml (required for mecha10_core::command_relay)"
        );
        println!();
    }

    Ok(())
}

/// Refresh `mecha10-core`'s locked version in Cargo.lock
///
/// `mecha10-core = { version = "*" }` is a loose requirement, but once `Cargo.lock` exists Cargo
/// keeps reusing whatever version it locked at project-creation time -- it never jumps to a
/// newer crates.io release on its own, even after `ensure_core_messaging_feature` enables the
/// `messaging` feature. A project scaffolded before `mecha10_core::command_relay` existed (or
/// before it was actually published) can be left permanently pinned to a `mecha10-core` version
/// that predates it, with every subsequent `mecha10 build robot` failing the exact same
/// "unresolved import" no matter how many times main.rs/Cargo.toml get regenerated. `cargo
/// update -p` only touches that one dependency's resolution, so this doesn't risk perturbing
/// anything else the project has already locked.
async fn update_core_dependency_lock(ctx: &CliContext) -> Result<()> {
    if !ctx.working_dir.join("Cargo.lock").exists() {
        // No lockfile yet - the upcoming build will resolve mecha10-core fresh on its own.
        return Ok(());
    }

    let status = Command::new("cargo")
        .arg("update")
        .arg("-p")
        .arg("mecha10-core")
        .current_dir(&ctx.working_dir)
        .status()
        .context("Failed to run cargo update -p mecha10-core")?;

    if !status.success() {
        println!("⚠️  cargo update -p mecha10-core failed - continuing with the existing Cargo.lock entry");
        println!();
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::context::CliContextBuilder;
    use tempfile::tempdir;

    // ===== BuildTarget enum accessors =====

    #[test]
    fn build_target_robot_metadata() {
        let target = BuildTarget::Robot;
        assert_eq!(target.features(), "target-robot");
        assert_eq!(target.display_name(), "Robot");
        assert_eq!(target.description(), "edge/on-robot nodes");
        assert_eq!(target.as_str(), "robot");
    }

    #[test]
    fn build_target_remote_metadata() {
        let target = BuildTarget::Remote;
        assert_eq!(target.features(), "target-remote");
        assert_eq!(target.display_name(), "Remote");
        assert_eq!(target.description(), "cloud/remote server nodes");
        assert_eq!(target.as_str(), "remote");
    }

    // ===== bump_semver =====

    #[test]
    fn bump_semver_patch() {
        assert_eq!(bump_semver("1.2.3", VersionBump::Patch).unwrap(), "1.2.4");
    }

    #[test]
    fn bump_semver_minor_resets_patch() {
        assert_eq!(bump_semver("1.2.3", VersionBump::Minor).unwrap(), "1.3.0");
    }

    #[test]
    fn bump_semver_major_resets_minor_and_patch() {
        assert_eq!(bump_semver("1.2.3", VersionBump::Major).unwrap(), "2.0.0");
    }

    #[test]
    fn bump_semver_handles_prerelease_suffix() {
        assert_eq!(bump_semver("1.2.3-beta", VersionBump::Patch).unwrap(), "1.2.4");
    }

    #[test]
    fn bump_semver_rejects_malformed_version() {
        let err = bump_semver("1.2", VersionBump::Patch).unwrap_err();
        assert!(err.to_string().contains("Invalid version format"));
    }

    #[test]
    fn bump_semver_rejects_non_numeric_parts() {
        assert!(bump_semver("a.b.c", VersionBump::Patch).is_err());
    }

    // ===== validate_semver =====

    #[test]
    fn validate_semver_accepts_valid_version() {
        assert!(validate_semver("1.2.3").is_ok());
    }

    #[test]
    fn validate_semver_accepts_prerelease_suffix() {
        assert!(validate_semver("1.2.3-rc.1").is_ok());
    }

    #[test]
    fn validate_semver_rejects_too_few_parts() {
        let err = validate_semver("1.2").unwrap_err();
        assert!(err.to_string().contains("Invalid version format"));
    }

    #[test]
    fn validate_semver_rejects_non_numeric_major() {
        assert!(validate_semver("x.2.3").is_err());
    }

    // ===== update_env_mode =====

    #[tokio::test]
    async fn update_env_mode_creates_env_file_when_absent() {
        let dir = tempdir().unwrap();
        let env_path = dir.path().join(".env");

        let ctx = CliContextBuilder::new()
            .working_dir(dir.path().to_path_buf())
            .build()
            .unwrap();

        update_env_mode(&ctx, "production").await.unwrap();

        let content = std::fs::read_to_string(&env_path).unwrap();
        assert_eq!(content, "MECHA10_ENV=production\n");
    }

    #[tokio::test]
    async fn update_env_mode_updates_existing_line_in_place() {
        let dir = tempdir().unwrap();
        let env_path = dir.path().join(".env");
        std::fs::write(&env_path, "ROBOT_ID=robot-1\nMECHA10_ENV=dev\nLOG_LEVEL=info\n").unwrap();

        let ctx = CliContextBuilder::new()
            .working_dir(dir.path().to_path_buf())
            .build()
            .unwrap();

        update_env_mode(&ctx, "production").await.unwrap();

        let content = std::fs::read_to_string(&env_path).unwrap();
        assert_eq!(content, "ROBOT_ID=robot-1\nMECHA10_ENV=production\nLOG_LEVEL=info\n");
    }

    #[tokio::test]
    async fn update_env_mode_appends_line_when_env_file_has_no_existing_entry() {
        let dir = tempdir().unwrap();
        let env_path = dir.path().join(".env");
        std::fs::write(&env_path, "ROBOT_ID=robot-1\n# MECHA10_ENV=\n").unwrap();

        let ctx = CliContextBuilder::new()
            .working_dir(dir.path().to_path_buf())
            .build()
            .unwrap();

        update_env_mode(&ctx, "dev").await.unwrap();

        let content = std::fs::read_to_string(&env_path).unwrap();
        assert_eq!(content, "ROBOT_ID=robot-1\n# MECHA10_ENV=\nMECHA10_ENV=dev\n");
    }

    #[tokio::test]
    async fn update_env_mode_is_noop_when_unchanged() {
        let dir = tempdir().unwrap();
        let env_path = dir.path().join(".env");
        std::fs::write(&env_path, "MECHA10_ENV=production\n").unwrap();
        let original_modified = std::fs::metadata(&env_path).unwrap().modified().unwrap();

        let ctx = CliContextBuilder::new()
            .working_dir(dir.path().to_path_buf())
            .build()
            .unwrap();

        update_env_mode(&ctx, "production").await.unwrap();

        let content = std::fs::read_to_string(&env_path).unwrap();
        assert_eq!(content, "MECHA10_ENV=production\n");
        // File untouched — same mtime (best-effort signal the no-op path skipped the write).
        assert_eq!(
            std::fs::metadata(&env_path).unwrap().modified().unwrap(),
            original_modified
        );
    }

    // ===== update_version =====

    #[tokio::test]
    async fn update_version_bumps_when_requested() {
        let dir = tempdir().unwrap();
        let config_path = dir.path().join("mecha10.json");
        std::fs::write(
            &config_path,
            serde_json::json!({"name": "proj", "version": "1.0.0", "robot": {"id": "robot-1"}}).to_string(),
        )
        .unwrap();

        let ctx = CliContextBuilder::new()
            .working_dir(dir.path().to_path_buf())
            .config_path(Some(config_path.clone()))
            .build()
            .unwrap();

        let new_version = update_version(&ctx, Some(VersionBump::Minor), None).await.unwrap();
        assert_eq!(new_version, "1.1.0");

        let content = std::fs::read_to_string(&config_path).unwrap();
        let value: serde_json::Value = serde_json::from_str(&content).unwrap();
        assert_eq!(value["version"], "1.1.0");
    }

    #[tokio::test]
    async fn update_version_sets_explicit_version() {
        let dir = tempdir().unwrap();
        let config_path = dir.path().join("mecha10.json");
        std::fs::write(
            &config_path,
            serde_json::json!({"name": "proj", "version": "1.0.0", "robot": {"id": "robot-1"}}).to_string(),
        )
        .unwrap();

        let ctx = CliContextBuilder::new()
            .working_dir(dir.path().to_path_buf())
            .config_path(Some(config_path.clone()))
            .build()
            .unwrap();

        let new_version = update_version(&ctx, None, Some("2.5.9".to_string())).await.unwrap();
        assert_eq!(new_version, "2.5.9");
    }

    #[tokio::test]
    async fn update_version_returns_current_when_neither_requested() {
        let dir = tempdir().unwrap();
        let config_path = dir.path().join("mecha10.json");
        std::fs::write(
            &config_path,
            serde_json::json!({"name": "proj", "version": "1.0.0", "robot": {"id": "robot-1"}}).to_string(),
        )
        .unwrap();

        let ctx = CliContextBuilder::new()
            .working_dir(dir.path().to_path_buf())
            .config_path(Some(config_path.clone()))
            .build()
            .unwrap();

        let new_version = update_version(&ctx, None, None).await.unwrap();
        assert_eq!(new_version, "1.0.0");

        // File should be unmodified since neither bump nor explicit version was requested.
        let content = std::fs::read_to_string(&config_path).unwrap();
        let value: serde_json::Value = serde_json::from_str(&content).unwrap();
        assert_eq!(value["version"], "1.0.0");
    }

    #[tokio::test]
    async fn update_version_rejects_invalid_explicit_version() {
        let dir = tempdir().unwrap();
        let config_path = dir.path().join("mecha10.json");
        std::fs::write(
            &config_path,
            serde_json::json!({"name": "proj", "version": "1.0.0", "robot": {"id": "robot-1"}}).to_string(),
        )
        .unwrap();

        let ctx = CliContextBuilder::new()
            .working_dir(dir.path().to_path_buf())
            .config_path(Some(config_path.clone()))
            .build()
            .unwrap();

        assert!(update_version(&ctx, None, Some("not-a-version".to_string()))
            .await
            .is_err());
    }

    // ===== ensure_core_messaging_feature =====

    #[tokio::test]
    async fn ensure_core_messaging_feature_patches_simple_string_dependency() {
        let dir = tempdir().unwrap();
        std::fs::write(
            dir.path().join("Cargo.toml"),
            "[dependencies]\nmecha10-core = \"*\"\ntokio = \"1\"\n",
        )
        .unwrap();

        let ctx = CliContextBuilder::new()
            .working_dir(dir.path().to_path_buf())
            .build()
            .unwrap();

        ensure_core_messaging_feature(&ctx).await.unwrap();

        let content = std::fs::read_to_string(dir.path().join("Cargo.toml")).unwrap();
        assert!(content.contains("mecha10-core = { version = \"*\", features = [\"messaging\"] }"));
        assert!(content.contains("tokio = \"1\""));
    }

    #[tokio::test]
    async fn ensure_core_messaging_feature_patches_inline_table_dependency() {
        let dir = tempdir().unwrap();
        std::fs::write(
            dir.path().join("Cargo.toml"),
            "[dependencies]\nmecha10-core = { version = \"2.0\" }\n",
        )
        .unwrap();

        let ctx = CliContextBuilder::new()
            .working_dir(dir.path().to_path_buf())
            .build()
            .unwrap();

        ensure_core_messaging_feature(&ctx).await.unwrap();

        let content = std::fs::read_to_string(dir.path().join("Cargo.toml")).unwrap();
        assert!(content.contains("mecha10-core = { version = \"2.0\", features = [\"messaging\"] }"));
    }

    #[tokio::test]
    async fn ensure_core_messaging_feature_is_noop_when_already_present() {
        let dir = tempdir().unwrap();
        let original = "[dependencies]\nmecha10-core = { version = \"*\", features = [\"messaging\"] }\n";
        std::fs::write(dir.path().join("Cargo.toml"), original).unwrap();

        let ctx = CliContextBuilder::new()
            .working_dir(dir.path().to_path_buf())
            .build()
            .unwrap();

        ensure_core_messaging_feature(&ctx).await.unwrap();

        let content = std::fs::read_to_string(dir.path().join("Cargo.toml")).unwrap();
        assert_eq!(content, original);
    }

    #[tokio::test]
    async fn ensure_core_messaging_feature_is_noop_when_cargo_toml_missing() {
        let dir = tempdir().unwrap();

        let ctx = CliContextBuilder::new()
            .working_dir(dir.path().to_path_buf())
            .build()
            .unwrap();

        assert!(ensure_core_messaging_feature(&ctx).await.is_ok());
        assert!(!dir.path().join("Cargo.toml").exists());
    }

    // ===== build_target: config validation gate =====

    // `config_validation::validate_config(None)` (like `mecha10 lint`'s
    // config-validation step) resolves the project via the process's current
    // directory, not `ctx.working_dir` -- so this test has to chdir like
    // packages/cli/tests/test_config_service.rs's `resolve_and_validate`
    // tests already do. Guarded by a mutex so it can't interleave with
    // another test in this same bin crate that also depends on cwd.
    static CWD_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

    #[tokio::test]
    // The guard intentionally spans the `.await` below -- it's serializing
    // access to the process-global current directory for the lifetime of
    // this single-threaded chdir/build/chdir-back sequence, not guarding an
    // async resource, so there's no other task to block on.
    #[allow(clippy::await_holding_lock)]
    async fn build_target_fails_fast_on_invalid_config_before_building() {
        let _guard = CWD_LOCK.lock().unwrap();
        let original_cwd = std::env::current_dir().unwrap();
        let dir = tempdir().unwrap();

        // References a node config file that doesn't exist -- fails the
        // shared validator's recursion into referenced node configs
        // (`validate_referenced_node_configs`), the same check `mecha10
        // config validate` runs. `name`/`version` stay valid so
        // `ctx.project()`/`project.name()` succeed and the failure is
        // attributable to the new validation gate here, not something
        // earlier in `build_target`.
        std::fs::write(
            dir.path().join("mecha10.json"),
            serde_json::json!({
                "name": "test-robot",
                "version": "1.0.0",
                "nodes": {
                    "drivers": [
                        {"name": "camera", "path": "./drivers/camera", "config": "./config/missing.json"}
                    ]
                }
            })
            .to_string(),
        )
        .unwrap();

        std::env::set_current_dir(dir.path()).unwrap();
        let mut ctx = CliContextBuilder::new()
            .working_dir(dir.path().to_path_buf())
            .build()
            .unwrap();

        let args = BuildTargetArgs {
            target: None,
            bump: None,
            version: None,
            dev: false,
        };

        let result = build_target(&mut ctx, BuildTarget::Robot, &args).await;
        std::env::set_current_dir(&original_cwd).unwrap();

        let err = result.expect_err("expected build to fail fast on an invalid config");
        let err_chain = format!("{:#}", err);
        assert!(
            err_chain.contains("Config validation failed"),
            "expected the config-validation gate to fire before any build work, got: {err_chain}"
        );
    }
}