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
//! Upload command handler
//!
//! Uploads robot binaries to the binary registry for deployment via launcher.

use crate::commands::UploadArgs;
use crate::context::CliContext;
use crate::services::credentials::CredentialsService;
use anyhow::{Context, Result};
use std::path::{Path, PathBuf};
use tempfile::TempDir;

/// Binary registry API path (appended to control plane URL)
const BINARY_REGISTRY_PATH: &str = "/api/builds";

/// Handle the upload command
pub async fn handle_upload(ctx: &mut CliContext, args: &UploadArgs) -> Result<()> {
    println!();
    println!("📦 Mecha10 Robot Binary Upload");
    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"));
    }

    // Load project config
    let project = ctx.project()?;
    let project_name = project.name()?;

    // Determine paths
    let binary_path = args
        .binary
        .clone()
        .unwrap_or_else(|| ctx.working_dir.join("dist").join(&project_name));

    let config_path = args
        .config
        .clone()
        .unwrap_or_else(|| ctx.working_dir.join("dist").join("mecha10.json"));

    // Validate binary exists
    if !binary_path.exists() {
        println!("❌ Binary not found: {}", binary_path.display());
        println!();
        println!("Build first with:");
        println!("  mecha10 build robot");
        println!();
        return Err(anyhow::anyhow!("Binary not found: {}", binary_path.display()));
    }

    // Validate config exists (needed for reading version/metadata, not bundled in tarball)
    if !config_path.exists() {
        println!("❌ Config not found: {}", config_path.display());
        println!();
        println!("The mecha10.json is needed for version metadata.");
        println!("Build first with:");
        println!("  mecha10 build robot");
        println!();
        return Err(anyhow::anyhow!("Config not found: {}", config_path.display()));
    }

    // Warn if binary may be stale (source files newer than binary)
    if let Some(warning) = detect_stale_binary(&binary_path, &ctx.working_dir) {
        println!("⚠️  {}", warning);
        println!("   Run `mecha10 build robot` to rebuild before uploading.");
        println!();
    }

    // Load project config from project root (for control plane URL)
    let project_config = ctx.load_project_config().await?;
    let control_plane_url = project_config.environments.control_plane_url();

    // Read dist config to get version and other metadata
    let dist_config_content = tokio::fs::read_to_string(&config_path).await?;
    let dist_config: serde_json::Value = serde_json::from_str(&dist_config_content)?;

    let config_name = dist_config["name"].as_str().unwrap_or(&project_name);
    let robot_id = project_config.robot.id.clone();
    let version = args
        .version
        .clone()
        .unwrap_or_else(|| dist_config["version"].as_str().unwrap_or("0.1.0").to_string());

    // Detect architecture from binary or use provided
    let arch = args.arch.clone().unwrap_or_else(|| detect_arch(&binary_path));
    let platform = "linux";

    // Detect target from dist config or use provided
    let target = args
        .target
        .clone()
        .unwrap_or_else(|| dist_config["build_target"].as_str().unwrap_or("robot").to_string());

    // Determine registry URL: CLI arg > env var > control plane URL from config
    let registry_url = args.registry_url.clone().unwrap_or_else(|| {
        std::env::var("MECHA10_REGISTRY_URL")
            .unwrap_or_else(|_| format!("{}{}", control_plane_url, BINARY_REGISTRY_PATH))
    });

    // Get binary filename
    let binary_filename = binary_path
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or(&project_name);

    // Load credentials for authentication and created_by field
    let credentials_service = CredentialsService::new();
    let credentials = credentials_service.load()?;
    let created_by = credentials.as_ref().map(|c| c.user_id.clone());
    let api_key = credentials.as_ref().map(|c| c.api_key.clone());

    println!("Project:      {}", config_name);
    println!("Robot ID:     {}", robot_id);
    println!("Version:      {}", version);
    println!("Platform:     {}", platform);
    println!("Architecture: {}", arch);
    println!("Target:       {}", target);
    println!("Binary:       {}", binary_path.display());
    println!("Config:       {}", config_path.display());
    println!("Registry:     {}", registry_url);
    println!("Uploaded by:  {}", created_by.as_deref().unwrap_or("anonymous"));
    println!();

    // Create tarball (binary only - configs managed via robot-config service)
    println!("Creating tarball...");
    let temp_dir = TempDir::new()?;
    let tarball_name = format!("{}-v{}-{}-{}.tar.gz", config_name, version, platform, arch);
    let tarball_path = temp_dir.path().join(&tarball_name);

    create_tarball(&binary_path, binary_filename, &tarball_path)?;

    println!("  Note: configs are managed via `mecha10 config push`");

    let tarball_size = std::fs::metadata(&tarball_path)?.len();

    println!();
    println!("Tarball:      {} ({} bytes)", tarball_name, tarball_size);
    println!();

    if args.dry_run {
        println!("🔍 DRY RUN - No changes will be made");
        println!();
        println!("Would upload:");
        println!("  POST {}", registry_url);
        println!("  - name: {}", config_name);
        println!("  - version: {}", version);
        println!("  - platform: {}", platform);
        println!("  - arch: {}", arch);
        println!("  - target: {}", target);
        println!("  - tags: robot,{}", robot_id);
        println!("  - robot_id: {}", robot_id);
        println!("  - created_by: {}", created_by.as_deref().unwrap_or("(none)"));
        println!("  - file: {}", tarball_name);
        println!();
        return Ok(());
    }

    // Upload to binary registry
    println!("Uploading tarball...");
    println!();

    let response = upload_to_registry(UploadParams {
        registry_url: &registry_url,
        name: config_name,
        version: &version,
        platform,
        arch: &arch,
        target: &target,
        robot_id: &robot_id,
        created_by: created_by.as_deref(),
        api_key: api_key.as_deref(),
        tarball_path: &tarball_path,
        tarball_name: &tarball_name,
    })
    .await?;

    // Parse response
    if let Some(binary_id) = response.get("id").and_then(|v| v.as_str()) {
        println!("✅ Upload successful!");
        println!();
        println!("Binary ID:    {}", binary_id);
        println!("Download URL: {}/{}/download", registry_url, binary_id);
        println!();
        println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
        println!("✅ Upload Complete");
        println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
        println!();
    } else {
        println!("❌ Upload failed!");
        println!();
        println!("Response: {}", serde_json::to_string_pretty(&response)?);
        return Err(anyhow::anyhow!("Upload failed"));
    }

    Ok(())
}

/// Detect architecture from ELF binary
fn detect_arch(binary_path: &Path) -> String {
    // Try to read ELF header to detect architecture
    if let Ok(bytes) = std::fs::read(binary_path) {
        if bytes.len() >= 20 && &bytes[0..4] == b"\x7fELF" {
            // ELF magic number confirmed
            // e_machine is at offset 18 (2 bytes)
            let e_machine = u16::from_le_bytes([bytes[18], bytes[19]]);
            match e_machine {
                0x3E => return "x86_64".to_string(),  // EM_X86_64
                0xB7 => return "aarch64".to_string(), // EM_AARCH64
                _ => {}
            }
        }
    }

    // Default to x86_64
    "x86_64".to_string()
}

/// Check if the binary is stale relative to source files.
///
/// Returns a warning message if any file in `src/` or `Cargo.toml` is newer
/// than the binary, suggesting a rebuild may be needed.
fn detect_stale_binary(binary_path: &Path, project_root: &Path) -> Option<String> {
    let binary_mtime = std::fs::metadata(binary_path).ok()?.modified().ok()?;

    let sources_to_check = [
        project_root.join("src"),
        project_root.join("Cargo.toml"),
        project_root.join("Cargo.lock"),
    ];

    for source in &sources_to_check {
        if !source.exists() {
            continue;
        }

        if source.is_file() {
            if let Ok(mtime) = std::fs::metadata(source).and_then(|m| m.modified()) {
                if mtime > binary_mtime {
                    return Some(format!(
                        "Binary may be stale ({} was modified after the binary was built)",
                        source.file_name().unwrap_or_default().to_string_lossy()
                    ));
                }
            }
        } else if source.is_dir() {
            // Walk src/ directory
            if let Ok(entries) = std::fs::read_dir(source) {
                for entry in entries.flatten() {
                    let path = entry.path();
                    if path.extension().is_some_and(|e| e == "rs") {
                        if let Ok(mtime) = std::fs::metadata(&path).and_then(|m| m.modified()) {
                            if mtime > binary_mtime {
                                return Some(format!(
                                    "Binary may be stale (src/{} was modified after the binary was built)",
                                    path.file_name().unwrap_or_default().to_string_lossy()
                                ));
                            }
                        }
                    }
                }
            }
        }
    }

    None
}

/// Create a tarball containing only the binary
///
/// Note: mecha10.json and configs/ are NOT included in the tarball.
/// They are managed separately via `mecha10 config push/pull` and the
/// robot-config service. The launcher pulls configs to the project root
/// on startup.
fn create_tarball(binary_path: &Path, binary_filename: &str, tarball_path: &Path) -> Result<()> {
    use flate2::write::GzEncoder;
    use flate2::Compression;
    use tar::Builder;

    let tarball_file = std::fs::File::create(tarball_path)?;
    let encoder = GzEncoder::new(tarball_file, Compression::default());
    let mut builder = Builder::new(encoder);

    // Add binary only - configs are managed via robot-config service
    builder
        .append_path_with_name(binary_path, binary_filename)
        .context("Failed to add binary to tarball")?;

    builder.finish()?;

    Ok(())
}

/// Parameters for uploading a binary to the registry
struct UploadParams<'a> {
    registry_url: &'a str,
    name: &'a str,
    version: &'a str,
    platform: &'a str,
    arch: &'a str,
    target: &'a str,
    robot_id: &'a str,
    created_by: Option<&'a str>,
    api_key: Option<&'a str>,
    tarball_path: &'a PathBuf,
    tarball_name: &'a str,
}

/// Upload tarball to binary registry
async fn upload_to_registry(params: UploadParams<'_>) -> Result<serde_json::Value> {
    let UploadParams {
        registry_url,
        name,
        version,
        platform,
        arch,
        target,
        robot_id,
        created_by,
        api_key,
        tarball_path,
        tarball_name,
    } = params;
    let client = reqwest::Client::new();

    // Read tarball
    let tarball_bytes = tokio::fs::read(tarball_path).await?;

    // Create multipart form
    let file_part = reqwest::multipart::Part::bytes(tarball_bytes)
        .file_name(tarball_name.to_string())
        .mime_str("application/gzip")?;

    let mut form = reqwest::multipart::Form::new()
        .text("name", name.to_string())
        .text("description", format!("Robot binary bundle for {}", name))
        .text("version", version.to_string())
        .text("platform", platform.to_string())
        .text("arch", arch.to_string())
        .text("target", target.to_string())
        .text("tags", format!("robot,{}", robot_id))
        .text("robot_id", robot_id.to_string())
        .part("file", file_part);

    // Add created_by if available
    if let Some(user) = created_by {
        form = form.text("created_by", user.to_string());
    }

    // Build request with authentication headers
    let mut request = client.post(registry_url).multipart(form);

    // Add authentication if credentials available
    if let (Some(key), Some(user_id)) = (api_key, created_by) {
        request = request
            .header("Authorization", format!("Bearer {}", key))
            .header("X-User-ID", user_id);
    }

    // Send request
    let response = request.send().await.context("Failed to send upload request")?;

    let status = response.status();
    let body = response.text().await?;

    if !status.is_success() {
        return Err(anyhow::anyhow!("Upload failed with status {}: {}", status, body));
    }

    // Parse JSON response
    let json: serde_json::Value = serde_json::from_str(&body).context("Failed to parse response JSON")?;

    Ok(json)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::commands::UploadArgs;
    use crate::context::CliContextBuilder;
    use std::time::{Duration, SystemTime};
    use tempfile::tempdir;

    fn no_op_upload_args() -> UploadArgs {
        UploadArgs {
            binary: None,
            config: None,
            registry_url: None,
            version: None,
            arch: None,
            target: None,
            dry_run: false,
        }
    }

    // ===== detect_arch =====

    #[test]
    fn detect_arch_identifies_x86_64_elf() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("bin");
        let mut bytes = vec![0u8; 20];
        bytes[0..4].copy_from_slice(b"\x7fELF");
        bytes[18..20].copy_from_slice(&0x3Eu16.to_le_bytes());
        std::fs::write(&path, &bytes).unwrap();

        assert_eq!(detect_arch(&path), "x86_64");
    }

    #[test]
    fn detect_arch_identifies_aarch64_elf() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("bin");
        let mut bytes = vec![0u8; 20];
        bytes[0..4].copy_from_slice(b"\x7fELF");
        bytes[18..20].copy_from_slice(&0xB7u16.to_le_bytes());
        std::fs::write(&path, &bytes).unwrap();

        assert_eq!(detect_arch(&path), "aarch64");
    }

    #[test]
    fn detect_arch_defaults_to_x86_64_for_non_elf() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("bin");
        std::fs::write(&path, b"not an elf file").unwrap();

        assert_eq!(detect_arch(&path), "x86_64");
    }

    #[test]
    fn detect_arch_defaults_to_x86_64_when_file_missing() {
        let path = std::path::PathBuf::from("/nonexistent/binary/path");
        assert_eq!(detect_arch(&path), "x86_64");
    }

    // ===== detect_stale_binary =====

    #[test]
    fn detect_stale_binary_none_when_binary_is_newer() {
        let dir = tempdir().unwrap();
        let src_dir = dir.path().join("src");
        std::fs::create_dir_all(&src_dir).unwrap();
        let source_file = src_dir.join("main.rs");
        std::fs::write(&source_file, "fn main() {}").unwrap();

        // Ensure the binary is written strictly after the source file.
        std::thread::sleep(Duration::from_millis(20));
        let binary_path = dir.path().join("bin");
        std::fs::write(&binary_path, b"binary").unwrap();

        assert!(detect_stale_binary(&binary_path, dir.path()).is_none());
    }

    #[test]
    fn detect_stale_binary_warns_when_source_is_newer() {
        let dir = tempdir().unwrap();
        let binary_path = dir.path().join("bin");
        std::fs::write(&binary_path, b"binary").unwrap();

        std::thread::sleep(Duration::from_millis(20));
        let src_dir = dir.path().join("src");
        std::fs::create_dir_all(&src_dir).unwrap();
        std::fs::write(src_dir.join("main.rs"), "fn main() {}").unwrap();

        let warning = detect_stale_binary(&binary_path, dir.path());
        assert!(warning.is_some());
        assert!(warning.unwrap().contains("may be stale"));
    }

    #[test]
    fn detect_stale_binary_none_when_binary_missing() {
        let dir = tempdir().unwrap();
        let binary_path = dir.path().join("missing-bin");
        assert!(detect_stale_binary(&binary_path, dir.path()).is_none());
    }

    #[test]
    fn detect_stale_binary_ignores_future_and_missing_sources() {
        let dir = tempdir().unwrap();
        let binary_path = dir.path().join("bin");
        std::fs::write(&binary_path, b"binary").unwrap();
        // No src/, Cargo.toml, or Cargo.lock present.
        assert!(detect_stale_binary(&binary_path, dir.path()).is_none());
        let _ = SystemTime::now();
    }

    // ===== create_tarball =====

    #[test]
    fn create_tarball_writes_gzip_archive() {
        let dir = tempdir().unwrap();
        let binary_path = dir.path().join("myapp");
        std::fs::write(&binary_path, b"fake binary contents").unwrap();
        let tarball_path = dir.path().join("out.tar.gz");

        create_tarball(&binary_path, "myapp", &tarball_path).unwrap();

        assert!(tarball_path.exists());
        assert!(std::fs::metadata(&tarball_path).unwrap().len() > 0);
    }

    #[test]
    fn create_tarball_errors_when_binary_missing() {
        let dir = tempdir().unwrap();
        let binary_path = dir.path().join("missing");
        let tarball_path = dir.path().join("out.tar.gz");

        assert!(create_tarball(&binary_path, "missing", &tarball_path).is_err());
    }

    // ===== handle_upload error paths =====

    #[tokio::test]
    async fn handle_upload_errors_when_not_a_project() {
        let dir = tempdir().unwrap();
        let mut ctx = CliContextBuilder::new()
            .working_dir(dir.path().to_path_buf())
            .config_path(Some(dir.path().join("mecha10.json")))
            .build()
            .unwrap();

        let err = handle_upload(&mut ctx, &no_op_upload_args()).await.unwrap_err();
        assert!(err.to_string().contains("Not in a Mecha10 project"));
    }

    #[tokio::test]
    async fn handle_upload_errors_when_binary_missing() {
        let dir = tempdir().unwrap();
        let config_path = dir.path().join("mecha10.json");
        std::fs::write(
            &config_path,
            serde_json::json!({"name": "proj", "version": "0.1.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();

        let err = handle_upload(&mut ctx, &no_op_upload_args()).await.unwrap_err();
        assert!(err.to_string().contains("Binary not found"));
    }

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

        // Binary exists so we get past that check, but dist/mecha10.json does not.
        let dist_dir = dir.path().join("dist");
        std::fs::create_dir_all(&dist_dir).unwrap();
        std::fs::write(dist_dir.join("proj"), b"binary").unwrap();

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

        let err = handle_upload(&mut ctx, &no_op_upload_args()).await.unwrap_err();
        assert!(err.to_string().contains("Config not found"));
    }
}