mecha10-cli 0.6.5

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
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
//! 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::{get_robot_id, push_configs};
use crate::handlers::upload::handle_upload;
use crate::paths;
use crate::services::build_platforms::{label_for_triple, BUILD_PLATFORMS};
use crate::services::credentials::CredentialsService;
use crate::services::publish_status::check_published_version;
use crate::services::rl_bundle;
use crate::templates::RustTemplates;
use crate::ui::prompts::is_interactive_terminal;
use anyhow::{Context, Result};
use dialoguer::{Confirm, Input};
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,
    /// Runs a trained RL policy in production (cloud/remote server, excludes the simulator)
    Rl,
}

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

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

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

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

/// 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,
        BuildCommand::Rl(args) => build_target(ctx, BuildTarget::Rl, args).await,
    }
}

/// Resolve which target triple(s) `mecha10 build` should actually build for (LAB-2152).
///
/// `--target` always wins and narrows to exactly that one triple, matching pre-LAB-2152
/// behavior, regardless of what `mecha10.json` configures. Otherwise, falls back to
/// `robot.targets`/`remote.targets`: empty/unset returns a single `None` entry - unchanged
/// behavior, build for the host machine's own architecture, no `--target` passed to cargo -
/// while a non-empty list returns every triple in it, so plain `mecha10 build robot` (with no
/// flag) builds all of them in one invocation.
fn resolve_build_targets(explicit_target: Option<&str>, configured_targets: Vec<String>) -> Vec<Option<String>> {
    if let Some(explicit) = explicit_target {
        return vec![Some(explicit.to_string())];
    }
    if configured_targets.is_empty() {
        return vec![None];
    }
    configured_targets.into_iter().map(Some).collect()
}

/// Show the platform-selection checklist (LAB-2152) and return the newly-selected triples.
///
/// Lists every [`BUILD_PLATFORMS`] entry by its human-readable label, pre-checked wherever
/// `configured` (the triples currently in `targets.<key>.platforms`) already has a match, and
/// lets the user toggle the selection. Reuses `crate::ui::prompts::multiselect` - the same
/// `dialoguer::MultiSelect` wrapper `handlers/add.rs` uses for its node/target checklists - so
/// this menu matches that theme/UX (including its "Select all" entry) rather than inventing a
/// separate one.
fn select_build_platforms(configured: &[String]) -> Result<Vec<String>> {
    let labels: Vec<&str> = BUILD_PLATFORMS.iter().map(|p| p.label).collect();
    let checked = platforms_checked(configured);

    let selected = crate::ui::prompts::multiselect("Select platform(s) to build for", &labels, &checked)?;

    Ok(selected
        .into_iter()
        .map(|i| BUILD_PLATFORMS[i].triple.to_string())
        .collect())
}

/// Which [`BUILD_PLATFORMS`] entries (by index) already have a matching triple in `configured` -
/// the pre-checked state [`select_build_platforms`]'s menu opens with. Split out from the
/// TTY-requiring `interact()` call above so it's unit-testable on plain data, matching this
/// file's existing split-out-the-pure-logic pattern (e.g. `needs_cross_compile_linker_config`,
/// `append_linker_section_if_missing`).
fn platforms_checked(configured: &[String]) -> Vec<bool> {
    BUILD_PLATFORMS
        .iter()
        .map(|p| configured.iter().any(|triple| triple == p.triple))
        .collect()
}

/// Write the newly-selected platform triples into `mecha10.json`'s `targets.<target_key>.platforms`
/// (LAB-2152). Patches the raw `serde_json::Value` in place - the same targeted approach
/// `update_version` already uses for the top-level `version` field - so nothing else in
/// `mecha10.json` (unrelated fields, key order, formatting) is touched.
///
/// An empty `platforms` list removes the key entirely rather than writing `"platforms": []`,
/// matching `TargetEntry::platforms`'s documented "empty/unset means build for the host
/// machine's own architecture" semantics (`targets.rs`).
async fn update_platforms(ctx: &CliContext, target_key: &str, platforms: &[String]) -> Result<()> {
    let config_path = ctx.working_dir.join(paths::PROJECT_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")?;

    if platforms.is_empty() {
        if let Some(entry) = config["targets"][target_key].as_object_mut() {
            entry.remove("platforms");
        }
    } else {
        config["targets"][target_key]["platforms"] = serde_json::json!(platforms);
    }

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

    let summary = if platforms.is_empty() {
        "host architecture".to_string()
    } else {
        platforms.join(", ")
    };
    println!(
        "📝 Updated mecha10.json: targets.{}.platforms → {}",
        target_key, summary
    );
    println!();

    Ok(())
}

/// Default node set for a scaffolded `targets.rl` entry - deliberately omits
/// `@mecha10/simulator` (see `BuildTarget::Rl`'s doc comment: training runs against the
/// simulator, running a trained policy in production should not - a target excludes a node
/// purely by not listing it, no special-cased exclusion mechanism exists or is needed).
const DEFAULT_RL_TARGET_NODES: &[&str] = &[
    "@mecha10/camera",
    "@mecha10/object-detector",
    "@mecha10/rl",
    "@mecha10/motor",
    "@mecha10/behavior-executor",
];

/// `mecha10 build rl`'s build/scaffold step: ensures `mecha10.json` has a `targets.rl` entry
/// (only writing the default node set the first time - never clobbering a project's own
/// customization) and switches the project's active behavior to `rl`, so `behavior-executor`
/// comes up already pointed at the bundled `rl` behavior with no manual step. This is the
/// concrete mechanism for "the rl target automatically puts the behaviour executor into rl
/// mode" - reusing the same raw-JSON-patch pattern `update_platforms`/`update_version` already
/// use, since `mecha10.json`'s `behaviors.active` is a single project-wide field, not per-target.
async fn ensure_rl_target_activated(ctx: &CliContext) -> Result<()> {
    let config_path = ctx.working_dir.join(paths::PROJECT_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")?;

    if config["targets"]["rl"].is_null() {
        config["targets"]["rl"]["nodes"] = serde_json::json!(DEFAULT_RL_TARGET_NODES);
        println!("📝 Updated mecha10.json: targets.rl.nodes → default rl node set");
    }

    if config["behaviors"]["active"].as_str() != Some("rl") {
        config["behaviors"]["active"] = serde_json::json!("rl");
        println!("📝 Updated mecha10.json: behaviors.active → \"rl\"");
    }
    println!();

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

    Ok(())
}

/// 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!();

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

    let project = ctx.project()?;
    let project_name = project.name()?;

    println!("Validating configs (mecha10.json + node configs)...");
    crate::config_validation::validate_config(None).context("Config validation failed")?;
    println!("✅ Config validation passed");
    println!();

    let mode = if args.dev { "dev" } else { "production" };
    update_env_mode(ctx, mode).await?;
    println!("Environment: {}", mode);

    let version_explicit = args.bump.is_some() || args.version.is_some();
    let mut 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 {
        let config = ctx.load_project_config().await?;
        println!("Version: {}", config.version);
        None
    };

    if !version_explicit {
        let current_version = ctx.load_project_config().await?.version;
        let interactive = is_interactive_terminal() && !args.non_interactive;
        match gate_on_already_published(ctx, &project_name, &current_version, target, interactive).await? {
            Some(resolved_version) => {
                if resolved_version != current_version {
                    version = Some(resolved_version);
                }
            }
            None => {
                println!();
                println!("Build cancelled.");
                return Ok(());
            }
        }
    }

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

    let configured_targets = if args.target.is_none() {
        let config = ctx.load_project_config().await?;
        let configured = match target {
            BuildTarget::Robot => config.targets.robot.and_then(|t| t.platforms).unwrap_or_default(),
            BuildTarget::Remote => config.targets.remote.and_then(|t| t.platforms).unwrap_or_default(),
            BuildTarget::Rl => config.targets.rl.and_then(|t| t.platforms).unwrap_or_default(),
        };

        let interactive = is_interactive_terminal() && !args.non_interactive;
        if interactive {
            let selected = select_build_platforms(&configured)?;
            if selected != configured {
                update_platforms(ctx, target.as_str(), &selected).await?;
            }
            if selected.is_empty() {
                println!("No platforms selected - building for the host machine's own architecture.");
                println!();
            }
            selected
        } else {
            configured
        }
    } else {
        Vec::new()
    };
    let build_targets = resolve_build_targets(args.target.as_deref(), configured_targets);

    if build_targets.len() > 1 {
        let labels: Vec<&str> = build_targets
            .iter()
            .map(|t| t.as_deref().map_or("host", label_for_triple))
            .collect();
        println!("Configured targets: {}", labels.join(", "));
    }
    println!();

    if matches!(target, BuildTarget::Rl) {
        ensure_rl_target_activated(ctx).await?;
    }

    regenerate_main_rs(ctx, &project_name).await?;
    ensure_core_messaging_feature(ctx).await?;
    update_core_dependency_lock(ctx).await?;

    for build_target_triple in &build_targets {
        if build_targets.len() > 1 {
            println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
            println!(
                "── {} ──",
                build_target_triple.as_deref().unwrap_or("host architecture")
            );
            println!();
        }

        let per_target_args = BuildTargetArgs {
            target: build_target_triple.clone(),
            ..args.clone()
        };

        if let Some(triple) = build_target_triple {
            ensure_cross_compile_linker_config(ctx, triple)?;
        }

        let result = build_with_cargo(ctx, target, &per_target_args).await;

        if let Some(v) = &version {
            if result.is_ok() {
                println!("📦 Built version: {}", v);
                println!();
            }
        }

        result?;
    }

    println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
    println!("📋 Pushing configs...");
    println!();
    // `push_configs` folds in `configs/simulation/{models,environments,images}` itself
    // (LAB-2937/LAB-2936: simulation assets live under `configs/` now, so config push covers
    // them - remote RL training pulls them through the same robot-config sync, via
    // `mecha10-launcher`'s config pull). No separate sim-asset push step needed for the `rl`
    // target any more.
    push_configs(ctx).await?;
    println!();

    // LAB-2768: additive to (never blocking/replacing) the production-inference binary build
    // this function otherwise performs for `BuildTarget::Rl` - packages+uploads the project's
    // `configs/rl/` + `configs/simulation/{models,environments}` as a single robot-scoped bundle
    // (LAB-2767), for `mecha10 run rl` on the trainer host to download before training starts. A
    // failure here is logged and swallowed rather than propagated, so it can never fail the
    // binary build/upload that follows.
    if matches!(target, BuildTarget::Rl) {
        println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
        println!("📦 Packaging & uploading RL project bundle...");
        println!();
        if let Err(e) = upload_rl_project_bundle(ctx, &project_name).await {
            println!("⚠️  Failed to upload RL project bundle: {e:#}");
            println!("   This does not block the production build below - re-run `mecha10 build rl`");
            println!("   once the issue is resolved to retry just the bundle upload.");
        }
        println!();
    }

    println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
    for build_target_triple in &build_targets {
        let binary_path = ctx
            .working_dir
            .join(paths::target_path_with_triple(
                build_target_triple.as_deref(),
                "release",
            ))
            .join(&project_name);
        let upload_args = UploadArgs {
            binary: Some(binary_path),
            config: None,
            registry_url: None,
            version: None,
            arch: None,
            target: Some(target.as_str().to_string()),
            dry_run: false,
        };
        handle_upload(ctx, &upload_args).await?;
    }

    Ok(())
}

/// Package the project's `configs/rl/` + `configs/simulation/{models,environments}` into a
/// single archive and upload it via LAB-2767's robot-scoped RL project bundle endpoint (LAB-2768).
///
/// Skips the upload entirely (not an error) when the project has neither directory populated -
/// see [`rl_bundle::build_rl_bundle_archive`]. Requires real credentials (unlike
/// `handlers::upload::handle_upload`'s anonymous-allowed binary upload): the bundle endpoint is
/// scoped/owned by robot ID, so there's no meaningful anonymous upload here.
async fn upload_rl_project_bundle(ctx: &mut CliContext, project_name: &str) -> Result<()> {
    let Some(archive_bytes) = rl_bundle::build_rl_bundle_archive(&ctx.working_dir)? else {
        println!("  No configs/rl/ or configs/simulation/{{models,environments}} found - skipping");
        return Ok(());
    };

    let robot_id = get_robot_id(ctx, None).await?;
    let project_config = ctx.load_project_config().await?;
    let control_plane_url = project_config.environments.control_plane_url();
    let tarball_name = rl_bundle::rl_bundle_tarball_name(project_name, &project_config.version);

    let credentials_service = CredentialsService::new();
    let credentials = if ctx.is_ci() {
        credentials_service.load()?
    } else {
        mecha10_auth::ensure_authenticated_interactive(&credentials_service)
            .await
            .ok()
    };
    let Some(credentials) = credentials else {
        anyhow::bail!("Not logged in. Run `mecha10 auth login` first.");
    };

    println!("  Robot ID: {}", robot_id);
    println!("  Bundle:   {}", tarball_name);

    rl_bundle::upload_rl_bundle(
        &control_plane_url,
        &robot_id,
        archive_bytes,
        &tarball_name,
        &credentials.api_key,
        &credentials.user_id,
    )
    .await?;

    println!("  ✅ Uploaded RL project bundle");

    Ok(())
}

/// Check whether `(project_name, version, target)` has already been published, and if so, either
/// gate the build behind a version bump (interactive) or just warn and proceed (non-interactive).
///
/// Returns `Ok(Some(version))` with the version to build - unchanged from `version`, or a newly
/// bumped one if the user chose to bump - or `Ok(None)` if the user declined to proceed with an
/// already-published version, in which case the caller must abort the build cleanly.
///
/// Never hard-fails the build: if the publish-status check itself errors (offline, no API key
/// configured, registry unreachable, etc.), this logs a warning and treats it exactly like
/// `exists: false` - `mecha10 build` must keep working without a control-plane connection.
async fn gate_on_already_published(
    ctx: &CliContext,
    project_name: &str,
    version: &str,
    target: BuildTarget,
    interactive: bool,
) -> Result<Option<String>> {
    let credentials_service = CredentialsService::new();
    let credentials = credentials_service.load().unwrap_or(None);
    let api_key = credentials.as_ref().map(|c| c.api_key.as_str());
    let user_id = credentials.as_ref().map(|c| c.user_id.as_str());

    let project_config = ctx.load_project_config().await?;
    let control_plane_url = project_config.environments.control_plane_url();

    let status = match check_published_version(
        &control_plane_url,
        project_name,
        version,
        target.as_str(),
        api_key,
        user_id,
    )
    .await
    {
        Ok(status) => status,
        Err(e) => {
            println!("⚠️  Could not check whether {} is already published: {e:#}", version);
            println!("   Continuing without the publish-status check.");
            println!();
            return Ok(Some(version.to_string()));
        }
    };

    if !status.exists {
        return Ok(Some(version.to_string()));
    }

    println!(
        "⚠️  Version {} has already been deployed for {}",
        version,
        target.as_str()
    );
    if !status.platforms.is_empty() {
        println!("   Already published for: {}", status.platforms.join(", "));
    }
    println!();

    if !interactive {
        println!(
            "Non-interactive mode: proceeding with the already-published version {}.",
            version
        );
        println!();
        return Ok(Some(version.to_string()));
    }

    let should_bump = Confirm::new()
        .with_prompt("Would you like to bump the version?")
        .default(false)
        .interact()
        .map_err(|e| anyhow::anyhow!("Failed to read confirmation: {e}"))?;

    if should_bump {
        let suggested = bump_semver(version, VersionBump::Patch)?;
        let new_version: String = Input::new()
            .with_prompt("New version")
            .with_initial_text(&suggested)
            .interact_text()
            .map_err(|e| anyhow::anyhow!("Failed to read new version: {e}"))?;

        validate_semver(&new_version)?;
        update_version(ctx, None, Some(new_version.clone())).await?;
        return Ok(Some(new_version));
    }

    let proceed = Confirm::new()
        .with_prompt("Proceed with build anyway?")
        .default(false)
        .interact()
        .map_err(|e| anyhow::anyhow!("Failed to read confirmation: {e}"))?;

    if proceed {
        Ok(Some(version.to_string()))
    } else {
        Ok(None)
    }
}

/// 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!();

    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!();

        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(())
}

/// Ensure `.cargo/config.toml` has a linker override for `triple`, when cross-compiling from
/// macOS to a Linux target - the one combination this repo's own cross-compile tooling needs
/// help with (see `scripts/release/targets.py`'s module doc: no cross-OS toolchain setup is
/// otherwise attempted).
///
/// Without this, `cargo build --target aarch64-unknown-linux-gnu` on macOS either fails
/// building `ring`/similar crates ("aarch64-linux-gnu-gcc: No such file or directory") if no
/// cross-gcc is on PATH at all, or - more confusingly - fails deep in the *linker* step with
/// "unknown options --as-needed -Bstatic -Bdynamic" if a `.cargo/config.toml` happens to set
/// `linker = "clang"` (e.g. copied from a Linux-native project): Apple's `ld64` (what `clang`
/// invokes on macOS) doesn't understand the GNU-linker-style flags rustc emits for `-gnu`
/// targets. The fix is a `.cargo/config.toml` pointing at the real cross-gcc instead.
///
/// Deliberately does NOT run when the host is Linux, even if it's natively targeting this same
/// triple - a `[target.<triple>]` section applies to a build for that triple whether it's an
/// explicit `--target` or the host's own implicit default, and a real Linux machine (or the
/// robot itself) almost never has a binary literally named `aarch64-unknown-linux-gnu-gcc` on
/// PATH (just plain `gcc`) - writing this section there would break native builds instead of
/// helping them.
///
/// Only ever adds a missing section - never overwrites an existing `[target.<triple>]` block,
/// so a project's own customization (a different linker, extra `rustflags`, etc.) is left
/// alone. Runs once per triple per build; there's no way to tell "we wrote this" apart from "the
/// user configured this themselves" after the fact, and that's fine - the second run is a cheap
/// no-op either way.
fn ensure_cross_compile_linker_config(ctx: &CliContext, triple: &str) -> Result<()> {
    if !needs_cross_compile_linker_config(std::env::consts::OS, triple) {
        return Ok(());
    }

    let config_path = ctx.working_dir.join(".cargo").join("config.toml");

    let existing = match std::fs::read_to_string(&config_path) {
        Ok(content) => content,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
        Err(e) => return Err(e).context("Failed to read .cargo/config.toml"),
    };

    let Some(updated) = append_linker_section_if_missing(&existing, triple) else {
        return Ok(());
    };

    let cross_gcc = cross_gcc_name(triple);
    if !is_on_path(&cross_gcc) {
        anyhow::bail!(
            "❌ Cross-compiling for {triple} from macOS needs `{cross_gcc}` on PATH.\n\n\
             Install the cross-toolchain:\n\
             \x20\x20brew tap messense/macos-cross-toolchains\n\
             \x20\x20brew install {triple}\n\
             \x20\x20rustup target add {triple}"
        );
    }

    if let Some(parent) = config_path.parent() {
        std::fs::create_dir_all(parent).context("Failed to create .cargo directory")?;
    }
    std::fs::write(&config_path, updated).context("Failed to write .cargo/config.toml")?;

    println!(
        "📝 Added [{}] linker override to .cargo/config.toml (cross-compiling from macOS)",
        triple
    );
    println!();

    Ok(())
}

/// Pure decision logic behind [`ensure_cross_compile_linker_config`]'s host-OS/target guard -
/// split out so it's unit-testable without actually running on macOS.
fn needs_cross_compile_linker_config(host_os: &str, triple: &str) -> bool {
    host_os == "macos" && triple.contains("-linux-")
}

/// The cross-gcc binary name expected on `PATH` for a given target triple (the
/// `messense/macos-cross-toolchains` Homebrew tap's naming convention).
fn cross_gcc_name(triple: &str) -> String {
    format!("{triple}-gcc")
}

/// Returns the new full `.cargo/config.toml` content with a `[target.<triple>]` linker section
/// appended, or `None` if `existing` already has one (in which case nothing should be written -
/// never overwrite a project's own customization). Split out from the filesystem-touching outer
/// function so this - the actual content-generation logic - is unit-testable on plain strings.
fn append_linker_section_if_missing(existing: &str, triple: &str) -> Option<String> {
    let section_header = format!("[target.{triple}]");
    if existing.contains(&section_header) {
        return None;
    }

    let mut updated = existing.to_string();
    if !updated.is_empty() && !updated.ends_with('\n') {
        updated.push('\n');
    }
    if !updated.is_empty() {
        updated.push('\n');
    }
    updated.push_str(&format!("{section_header}\nlinker = \"{}\"\n", cross_gcc_name(triple)));
    Some(updated)
}

/// Minimal `which`-style `PATH` lookup - not worth a whole crate dependency for one check.
fn is_on_path(binary: &str) -> bool {
    let Some(path_var) = std::env::var_os("PATH") else {
        return false;
    };
    std::env::split_paths(&path_var).any(|dir| dir.join(binary).is_file())
}

/// 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);

    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();

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

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

    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('-')
        .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
        ));
    }

    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);

    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} = {{ {}, features = [\"messaging\"] }}", inner.trim())
            } 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(())
}

/// Framework crates the generated project depends on directly with a loose `version = "*"`
/// requirement (see `Cargo.toml.prod.template`) -- both need their `Cargo.lock` entry refreshed
/// on every build, for the same reason (see `update_core_dependency_lock`'s doc comment).
const FRAMEWORK_DEPENDENCY_CRATES: &[&str] = &["mecha10-core", "mecha10-node-resolver"];

/// Refresh the project's framework dependencies' locked versions in Cargo.lock
///
/// `mecha10-core`/`mecha10-node-resolver` are pinned with `version = "*"` in the generated
/// Cargo.toml -- 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 or the
/// framework crate itself gains new API surface (e.g. `NodeResolver::spawn_and_wait`, which
/// `main.rs.template` calls). A project scaffolded before either was published to crates.io
/// stays permanently pinned to a stale version, with every subsequent `mecha10 build robot`
/// failing the exact same "unresolved import"/"method not found" 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() {
        return Ok(());
    }

    for crate_name in FRAMEWORK_DEPENDENCY_CRATES {
        let status = Command::new("cargo")
            .arg("update")
            .arg("-p")
            .arg(crate_name)
            .current_dir(&ctx.working_dir)
            .status()
            .with_context(|| format!("Failed to run cargo update -p {crate_name}"))?;

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

    Ok(())
}

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

    #[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");
    }

    #[test]
    fn resolve_build_targets_falls_back_to_host_arch_when_nothing_configured() {
        assert_eq!(resolve_build_targets(None, Vec::new()), vec![None]);
    }

    #[test]
    fn resolve_build_targets_builds_every_configured_triple_when_no_explicit_flag() {
        let configured = vec![
            "aarch64-unknown-linux-gnu".to_string(),
            "x86_64-unknown-linux-gnu".to_string(),
        ];
        assert_eq!(
            resolve_build_targets(None, configured),
            vec![
                Some("aarch64-unknown-linux-gnu".to_string()),
                Some("x86_64-unknown-linux-gnu".to_string())
            ]
        );
    }

    #[test]
    fn resolve_build_targets_explicit_flag_narrows_to_one_triple_ignoring_config() {
        let configured = vec![
            "aarch64-unknown-linux-gnu".to_string(),
            "x86_64-unknown-linux-gnu".to_string(),
        ];
        assert_eq!(
            resolve_build_targets(Some("aarch64-apple-darwin"), configured),
            vec![Some("aarch64-apple-darwin".to_string())]
        );
    }

    #[test]
    fn resolve_build_targets_explicit_flag_wins_even_with_no_config() {
        assert_eq!(
            resolve_build_targets(Some("x86_64-unknown-linux-gnu"), Vec::new()),
            vec![Some("x86_64-unknown-linux-gnu".to_string())]
        );
    }

    #[test]
    fn needs_cross_compile_linker_config_only_for_macos_targeting_linux() {
        assert!(needs_cross_compile_linker_config("macos", "aarch64-unknown-linux-gnu"));
        assert!(needs_cross_compile_linker_config("macos", "x86_64-unknown-linux-musl"));
    }

    #[test]
    fn needs_cross_compile_linker_config_false_on_non_macos_hosts() {
        assert!(!needs_cross_compile_linker_config("linux", "aarch64-unknown-linux-gnu"));
        assert!(!needs_cross_compile_linker_config(
            "windows",
            "aarch64-unknown-linux-gnu"
        ));
    }

    #[test]
    fn needs_cross_compile_linker_config_false_for_non_linux_targets() {
        assert!(!needs_cross_compile_linker_config("macos", "aarch64-apple-darwin"));
    }

    #[test]
    fn append_linker_section_if_missing_writes_a_new_section_to_an_empty_file() {
        let result = append_linker_section_if_missing("", "aarch64-unknown-linux-gnu");
        assert_eq!(
            result,
            Some("[target.aarch64-unknown-linux-gnu]\nlinker = \"aarch64-unknown-linux-gnu-gcc\"\n".to_string())
        );
    }

    #[test]
    fn append_linker_section_if_missing_appends_after_existing_unrelated_content() {
        let existing = "[target.x86_64-apple-darwin]\nlinker = \"clang\"\n";
        let result = append_linker_section_if_missing(existing, "aarch64-unknown-linux-gnu").unwrap();

        assert!(result.starts_with(existing));
        assert!(result.contains("[target.aarch64-unknown-linux-gnu]\nlinker = \"aarch64-unknown-linux-gnu-gcc\"\n"));
    }

    #[test]
    fn append_linker_section_if_missing_is_none_when_section_already_present() {
        let existing = "[target.aarch64-unknown-linux-gnu]\nlinker = \"some-other-linker\"\n";
        assert!(append_linker_section_if_missing(existing, "aarch64-unknown-linux-gnu").is_none());
    }

    #[test]
    fn cross_gcc_name_matches_the_macos_cross_toolchains_tap_convention() {
        assert_eq!(
            cross_gcc_name("aarch64-unknown-linux-gnu"),
            "aarch64-unknown-linux-gnu-gcc"
        );
    }

    #[tokio::test]
    async fn ensure_cross_compile_linker_config_is_a_noop_on_this_non_macos_test_host() {
        if std::env::consts::OS == "macos" {
            return;
        }

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

        ensure_cross_compile_linker_config(&ctx, "aarch64-unknown-linux-gnu").unwrap();

        assert!(!dir.path().join(".cargo").join("config.toml").exists());
    }

    #[test]
    fn is_interactive_terminal_does_not_panic() {
        let _ = is_interactive_terminal();
    }

    #[tokio::test]
    async fn gate_on_already_published_proceeds_when_publish_check_cannot_be_completed() {
        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))
            .build()
            .unwrap();

        let resolved = gate_on_already_published(&ctx, "proj", "1.0.0", BuildTarget::Robot, false)
            .await
            .unwrap();

        assert_eq!(resolved, Some("1.0.0".to_string()));
    }

    #[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());
    }

    #[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());
    }

    #[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");
        assert_eq!(
            std::fs::metadata(&env_path).unwrap().modified().unwrap(),
            original_modified
        );
    }

    #[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");

        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());
    }

    #[test]
    fn platforms_checked_matches_configured_triples() {
        let configured = vec![
            "x86_64-unknown-linux-gnu".to_string(),
            "aarch64-apple-darwin".to_string(),
        ];
        let checked = platforms_checked(&configured);

        let expected: Vec<bool> = BUILD_PLATFORMS
            .iter()
            .map(|p| p.triple == "x86_64-unknown-linux-gnu" || p.triple == "aarch64-apple-darwin")
            .collect();
        assert_eq!(checked, expected);
    }

    #[test]
    fn platforms_checked_is_all_false_when_nothing_configured() {
        assert_eq!(platforms_checked(&[]), vec![false; BUILD_PLATFORMS.len()]);
    }

    #[test]
    fn platforms_checked_ignores_a_triple_outside_build_platforms() {
        let configured = vec!["riscv64-unknown-linux-gnu".to_string()];
        assert_eq!(platforms_checked(&configured), vec![false; BUILD_PLATFORMS.len()]);
    }

    #[tokio::test]
    async fn update_platforms_writes_the_new_triples_into_the_target_entry() {
        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",
                "targets": {
                    "robot": { "nodes": ["@mecha10/motor"], "platforms": ["x86_64-unknown-linux-gnu"] }
                }
            })
            .to_string(),
        )
        .unwrap();

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

        update_platforms(&ctx, "robot", &["aarch64-unknown-linux-gnu".to_string()])
            .await
            .unwrap();

        let content = std::fs::read_to_string(&config_path).unwrap();
        let value: serde_json::Value = serde_json::from_str(&content).unwrap();
        assert_eq!(
            value["targets"]["robot"]["platforms"],
            serde_json::json!(["aarch64-unknown-linux-gnu"])
        );
        assert_eq!(
            value["targets"]["robot"]["nodes"],
            serde_json::json!(["@mecha10/motor"])
        );
    }

    #[tokio::test]
    async fn update_platforms_removes_the_key_when_deselected_to_empty() {
        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",
                "targets": {
                    "remote": { "nodes": ["@mecha10/object-detector"], "platforms": ["x86_64-unknown-linux-gnu"] }
                }
            })
            .to_string(),
        )
        .unwrap();

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

        update_platforms(&ctx, "remote", &[]).await.unwrap();

        let content = std::fs::read_to_string(&config_path).unwrap();
        let value: serde_json::Value = serde_json::from_str(&content).unwrap();
        assert!(
            value["targets"]["remote"].get("platforms").is_none(),
            "expected the platforms key to be removed entirely, got: {value}"
        );
        assert_eq!(
            value["targets"]["remote"]["nodes"],
            serde_json::json!(["@mecha10/object-detector"])
        );
    }

    #[tokio::test]
    async fn update_platforms_creates_the_target_entry_when_absent() {
        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"}).to_string(),
        )
        .unwrap();

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

        update_platforms(&ctx, "robot", &["aarch64-unknown-linux-gnu".to_string()])
            .await
            .unwrap();

        let content = std::fs::read_to_string(&config_path).unwrap();
        let value: serde_json::Value = serde_json::from_str(&content).unwrap();
        assert_eq!(
            value["targets"]["robot"]["platforms"],
            serde_json::json!(["aarch64-unknown-linux-gnu"])
        );
    }

    #[tokio::test]
    async fn ensure_rl_target_activated_writes_default_nodes_excluding_simulator() {
        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"}).to_string(),
        )
        .unwrap();

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

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

        let content = std::fs::read_to_string(&config_path).unwrap();
        let value: serde_json::Value = serde_json::from_str(&content).unwrap();
        let nodes = value["targets"]["rl"]["nodes"].as_array().unwrap();
        assert!(nodes.iter().any(|n| n == "@mecha10/rl"));
        assert!(
            !nodes.iter().any(|n| n == "@mecha10/simulator"),
            "the rl target must never include the simulator: {value}"
        );
        assert_eq!(value["behaviors"]["active"], serde_json::json!("rl"));
    }

    #[tokio::test]
    async fn ensure_rl_target_activated_never_clobbers_an_existing_rl_target_entry() {
        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",
                "targets": {
                    "rl": { "nodes": ["@mecha10/rl", "@mecha10/motor"], "platforms": ["aarch64-unknown-linux-gnu"] }
                }
            })
            .to_string(),
        )
        .unwrap();

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

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

        let content = std::fs::read_to_string(&config_path).unwrap();
        let value: serde_json::Value = serde_json::from_str(&content).unwrap();
        assert_eq!(
            value["targets"]["rl"]["nodes"],
            serde_json::json!(["@mecha10/rl", "@mecha10/motor"]),
            "an existing customized targets.rl entry must not be overwritten"
        );
        assert_eq!(
            value["targets"]["rl"]["platforms"],
            serde_json::json!(["aarch64-unknown-linux-gnu"])
        );
    }

    #[tokio::test]
    async fn ensure_rl_target_activated_is_idempotent_when_already_active() {
        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",
                "targets": {"rl": {"nodes": ["@mecha10/rl"]}},
                "behaviors": {"active": "rl"}
            })
            .to_string(),
        )
        .unwrap();

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

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

        let content = std::fs::read_to_string(&config_path).unwrap();
        let value: serde_json::Value = serde_json::from_str(&content).unwrap();
        assert_eq!(value["behaviors"]["active"], serde_json::json!("rl"));
        assert_eq!(value["targets"]["rl"]["nodes"], serde_json::json!(["@mecha10/rl"]));
    }

    #[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());
    }

    static CWD_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

    #[tokio::test]
    #[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();

        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,
            non_interactive: true,
        };

        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}"
        );
    }

    #[tokio::test]
    async fn upload_rl_project_bundle_skips_cleanly_when_nothing_to_package() {
        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 mut ctx = CliContextBuilder::new()
            .working_dir(dir.path().to_path_buf())
            .config_path(Some(config_path))
            .build()
            .unwrap();

        // No configs/rl/ or configs/simulation/{models,environments} exist under `dir` - this
        // must return Ok(()) without ever touching credentials/network (build_rl_bundle_archive
        // returns None before either is reached).
        upload_rl_project_bundle(&mut ctx, "proj").await.unwrap();
    }
}