rayengine-cli 0.0.3

Project tools for rayengine games
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
//! Project scaffolding and Cargo tooling with structured agent-readable results.

use clap::{Parser, Subcommand, ValueEnum};
use rayengine_core::manifest::{ProjectManifest, ResolvedManifest};
use serde_json::{Value, json};
use std::{
    fs,
    path::{Path, PathBuf},
    process::{Command, ExitCode},
};

mod lifecycle;
mod package;
mod plugins;
mod watch;

#[derive(Parser)]
#[command(version, about = "Small Rust game projects over raylib")]
struct Cli {
    /// Emit one versioned JSON result; Cargo diagnostics are embedded in it.
    #[arg(long, global = true)]
    json: bool,
    #[command(subcommand)]
    command: Action,
}

#[derive(Subcommand)]
enum Action {
    /// Create a playable starter in a new directory.
    New {
        path: PathBuf,
        #[arg(long, value_enum, default_value = "2d")]
        kind: Kind,
        /// Named starter; supersedes --kind (which remains a compatibility alias).
        #[arg(long, value_enum, conflicts_with = "kind")]
        template: Option<Kind>,
        /// Override the package name (default: directory name).
        #[arg(long)]
        name: Option<String>,
        /// Use a local SDK crate instead of the published SDK version.
        #[arg(long)]
        sdk_path: Option<PathBuf>,
    },
    /// Create an optional Cargo plugin library in a new directory.
    NewPlugin {
        path: PathBuf,
        /// Override the package name (default: directory name).
        #[arg(long)]
        name: Option<String>,
        /// Use a local SDK crate instead of the published SDK version.
        #[arg(long)]
        sdk_path: Option<PathBuf>,
    },
    /// Inspect project packages without compiling.
    Info {
        #[arg(default_value = ".")]
        path: PathBuf,
        /// Select a named rayengine.toml profile.
        #[arg(long)]
        profile: Option<String>,
    },
    /// Type-check a game project.
    Check {
        #[arg(default_value = ".")]
        path: PathBuf,
        /// Select a named rayengine.toml profile.
        #[arg(long)]
        profile: Option<String>,
    },
    /// Build a game project.
    Build {
        #[arg(default_value = ".")]
        path: PathBuf,
        #[arg(long)]
        release: bool,
        /// Select a named rayengine.toml profile (independent of Cargo --release).
        #[arg(long)]
        profile: Option<String>,
    },
    /// Run a game; remaining arguments are passed to its binary.
    Run {
        #[arg(default_value = ".")]
        path: PathBuf,
        #[arg(long)]
        release: bool,
        /// Select a named rayengine.toml profile (independent of Cargo --release).
        #[arg(long)]
        profile: Option<String>,
        /// Override project.executable with a Cargo binary target.
        #[arg(long)]
        bin: Option<String>,
        #[arg(last = true)]
        args: Vec<String>,
    },
    /// Check Linux native build prerequisites without modifying the system.
    Doctor {
        /// Print distro-specific install commands without running them.
        #[arg(long)]
        fix_hints: bool,
    },
    /// List available playable starters.
    Templates,
    /// Build a release executable, relocatable Linux folder and .tar.gz archive.
    #[command(alias = "bundle")]
    Package {
        #[arg(default_value = ".")]
        path: PathBuf,
        #[arg(long)]
        profile: Option<String>,
        #[arg(long)]
        bin: Option<String>,
        /// Parent directory for bundles (default: project bundles/).
        #[arg(long)]
        output: Option<PathBuf>,
        /// Enable Cargo features required by the selected executable.
        #[arg(long, value_delimiter = ',')]
        features: Vec<String>,
    },
    /// Add a first-party Cargo dependency and its manifest namespace.
    Add {
        plugin: String,
        #[arg(default_value = ".")]
        path: PathBuf,
        /// Local plugin crate; otherwise infer from a local SDK or match its version.
        #[arg(long)]
        plugin_path: Option<PathBuf>,
        /// Enable optional plugin features, comma separated.
        #[arg(long, value_delimiter = ',')]
        features: Vec<String>,
    },
    /// Remove a first-party dependency and its base/profile namespaces.
    Remove {
        plugin: String,
        #[arg(default_value = ".")]
        path: PathBuf,
    },
    /// Rebuild and restart on source, asset and manifest changes; Ctrl-C stops.
    Watch {
        #[arg(default_value = ".")]
        path: PathBuf,
        #[arg(long)]
        release: bool,
        #[arg(long)]
        profile: Option<String>,
        #[arg(long)]
        bin: Option<String>,
        #[arg(long, default_value = "200", value_parser = clap::value_parser!(u64).range(1..))]
        debounce_ms: u64,
        /// Enable Cargo features required by the selected executable.
        #[arg(long, value_delimiter = ',')]
        features: Vec<String>,
        /// Stop after this many rebuild cycles (includes the initial build).
        #[arg(long, value_parser = clap::value_parser!(u32).range(1..))]
        cycles: Option<u32>,
        /// Stop after this many milliseconds, including builds (for automation).
        #[arg(long, value_parser = clap::value_parser!(u64).range(1..))]
        timeout_ms: Option<u64>,
        #[arg(last = true)]
        args: Vec<String>,
    },
    /// Remove Cargo build outputs and CLI-generated bundles.
    Clean {
        #[arg(default_value = ".")]
        path: PathBuf,
        /// Also clean bundles generated in this custom output directory.
        #[arg(long)]
        output: Option<PathBuf>,
    },
}

#[derive(Clone, Copy, ValueEnum)]
enum Kind {
    #[value(name = "2d")]
    TwoD,
    #[value(name = "3d")]
    ThreeD,
    Topdown,
    Platformer,
}

struct Failure {
    code: &'static str,
    message: String,
    details: Value,
}
impl Failure {
    fn new(code: &'static str, message: impl Into<String>) -> Self {
        Self {
            code,
            message: message.into(),
            details: Value::Null,
        }
    }
}
type Result<T> = std::result::Result<T, Failure>;

fn main() -> ExitCode {
    let args: Vec<_> = std::env::args_os().collect();
    let json_requested = args
        .iter()
        .take_while(|arg| *arg != "--")
        .any(|arg| arg == "--json");
    let cli = match Cli::try_parse_from(args) {
        Ok(cli) => cli,
        Err(error) => {
            if matches!(
                error.kind(),
                clap::error::ErrorKind::DisplayHelp | clap::error::ErrorKind::DisplayVersion
            ) {
                let _ = error.print();
                return ExitCode::SUCCESS;
            }
            if json_requested {
                println!(
                    "{}",
                    json!({ "schema_version": 1, "ok": false, "command": null,
                    "error": { "code": "invalid_arguments", "message": error.to_string(), "details": null } })
                );
            } else {
                let _ = error.print();
            }
            return ExitCode::from(2);
        }
    };
    let command = match &cli.command {
        Action::New { .. } => "new",
        Action::NewPlugin { .. } => "new-plugin",
        Action::Info { .. } => "info",
        Action::Check { .. } => "check",
        Action::Build { .. } => "build",
        Action::Run { .. } => "run",
        Action::Doctor { .. } => "doctor",
        Action::Templates => "templates",
        Action::Package { .. } => "package",
        Action::Add { .. } => "add",
        Action::Remove { .. } => "remove",
        Action::Watch { .. } => "watch",
        Action::Clean { .. } => "clean",
    };
    match execute(cli.command, cli.json) {
        Ok(data) => {
            if cli.json {
                println!(
                    "{}",
                    json!({ "schema_version": 1, "ok": true, "command": command, "data": data })
                );
            } else {
                print_success(command, &data);
            }
            ExitCode::SUCCESS
        }
        Err(error) => {
            if cli.json {
                println!(
                    "{}",
                    json!({ "schema_version": 1, "ok": false, "command": command,
                "error": { "code": error.code, "message": error.message, "details": error.details } })
                );
            } else {
                eprintln!("rayengine: {}", error.message);
                if command == "doctor"
                    && let Some(hints) = error.details["fix_hints"].as_array()
                {
                    for hint in hints {
                        eprintln!("Hint (not executed): {}", hint.as_str().unwrap_or(""));
                    }
                }
                if let Some(stderr) = error.details.get("stderr").and_then(Value::as_str) {
                    eprint!("{stderr}");
                }
            }
            ExitCode::FAILURE
        }
    }
}

fn execute(action: Action, json_mode: bool) -> Result<Value> {
    match action {
        Action::New {
            path,
            kind,
            template,
            name,
            sdk_path,
        } => create_project(&path, template.unwrap_or(kind), name, sdk_path),
        Action::NewPlugin {
            path,
            name,
            sdk_path,
        } => create_package(&path, Template::Plugin, name, sdk_path),
        Action::Info { path, profile } => {
            let manifest = manifest(&path)?;
            let (project, profiles) = project_manifest(&path, profile.as_deref())?;
            let output = Command::new("cargo")
                .args([
                    "metadata",
                    "--no-deps",
                    "--format-version",
                    "1",
                    "--manifest-path",
                ])
                .arg(&manifest)
                .output()
                .map_err(process_error)?;
            if !output.status.success() {
                return Err(cargo_failure(output, "metadata failed"));
            }
            let metadata: Value = serde_json::from_slice(&output.stdout)
                .map_err(|e| Failure::new("invalid_metadata", e.to_string()))?;
            Ok(
                json!({ "engine_version": env!("CARGO_PKG_VERSION"), "manifest": manifest,
                "workspace_root": metadata["workspace_root"], "packages": metadata["packages"],
                "project_manifest": project, "profiles": profiles }),
            )
        }
        Action::Check { path, profile } => cargo_task(
            "check",
            &path,
            false,
            profile.as_deref(),
            None,
            &[],
            json_mode,
        ),
        Action::Build {
            path,
            release,
            profile,
        } => cargo_task(
            "build",
            &path,
            release,
            profile.as_deref(),
            None,
            &[],
            json_mode,
        ),
        Action::Run {
            path,
            release,
            profile,
            bin,
            args,
        } => cargo_task(
            "run",
            &path,
            release,
            profile.as_deref(),
            bin.as_deref(),
            &args,
            json_mode,
        ),
        Action::Doctor { fix_hints } => doctor(fix_hints),
        Action::Templates => Ok(json!({ "templates": [
            {"name": "2d", "description": "Platform physics with primitive drawing", "plugins": []},
            {"name": "3d", "description": "First-person 3D movement", "plugins": []},
            {"name": "topdown", "description": "Top-down tilemap movement and collision", "plugins": ["tilemap"]},
            {"name": "platformer", "description": "Tilemap platform physics and jumping", "plugins": ["tilemap"]}
        ] })),
        Action::Package {
            path,
            profile,
            bin,
            output,
            features,
        } => package::package(
            &path,
            profile.as_deref(),
            bin.as_deref(),
            output.as_deref(),
            &features,
        ),
        Action::Add {
            plugin,
            path,
            plugin_path,
            features,
        } => plugins::edit(&path, &plugin, true, plugin_path.as_deref(), &features),
        Action::Remove { plugin, path } => plugins::edit(&path, &plugin, false, None, &[]),
        Action::Clean { path, output } => lifecycle::clean(&path, output.as_deref()),
        Action::Watch {
            path,
            release,
            profile,
            bin,
            debounce_ms,
            features,
            cycles,
            timeout_ms,
            args,
        } => watch::watch(watch::Options {
            path,
            release,
            profile,
            bin,
            debounce_ms,
            features,
            cycles,
            timeout_ms,
            args,
            json_mode,
        }),
    }
}

fn manifest(path: &Path) -> Result<PathBuf> {
    let manifest = if path
        .file_name()
        .is_some_and(|name| name == "rayengine.toml")
    {
        path.canonicalize().map_err(|e| {
            Failure::new(
                "invalid_project_manifest",
                format!("{}: {e}", path.display()),
            )
        })?;
        path.with_file_name("Cargo.toml")
    } else if path.is_file() {
        path.to_path_buf()
    } else {
        path.join("Cargo.toml")
    };
    manifest
        .canonicalize()
        .map_err(|e| Failure::new("missing_manifest", format!("{}: {e}", manifest.display())))
}

fn project_manifest(
    path: &Path,
    profile: Option<&str>,
) -> Result<(Option<ResolvedManifest>, Vec<String>)> {
    let manifest = ProjectManifest::load_optional(path)
        .map_err(|e| Failure::new("invalid_project_manifest", e.to_string()))?;
    match manifest {
        Some(manifest) => {
            let profiles = manifest.profiles().map(str::to_owned).collect();
            let project = manifest
                .resolve(profile)
                .map_err(|e| Failure::new("invalid_project_manifest", e.to_string()))?;
            Ok((Some(project), profiles))
        }
        None if profile.is_some() => Err(Failure::new(
            "invalid_project_manifest",
            "a profile requires rayengine.toml",
        )),
        None => Ok((None, vec![])),
    }
}

fn create_project(
    path: &Path,
    kind: Kind,
    name: Option<String>,
    sdk_path: Option<PathBuf>,
) -> Result<Value> {
    create_package(path, Template::Game(kind), name, sdk_path)
}

#[derive(Clone, Copy)]
enum Template {
    Game(Kind),
    Plugin,
}

fn create_package(
    path: &Path,
    template: Template,
    name: Option<String>,
    sdk_path: Option<PathBuf>,
) -> Result<Value> {
    let name = name
        .or_else(|| {
            path.file_name()
                .and_then(|s| s.to_str())
                .map(str::to_string)
        })
        .ok_or_else(|| Failure::new("invalid_name", "specify a package name with --name"))?;
    validate_name(&name)?;
    let sdk = sdk_path
        .map(|path| {
            let sdk = path.canonicalize().map_err(|_| {
                Failure::new(
                    "missing_sdk",
                    "--sdk-path must point to the rayengine SDK crate",
                )
            })?;
            let sdk_manifest = fs::read_to_string(sdk.join("Cargo.toml"))
                .map_err(|e| Failure::new("missing_sdk", e.to_string()))?;
            if !sdk_manifest
                .lines()
                .map(str::trim)
                .skip_while(|line| *line != "[package]")
                .skip(1)
                .take_while(|line| !line.starts_with('['))
                .any(|line| line == "name = \"rayengine\"")
            {
                return Err(Failure::new(
                    "invalid_sdk",
                    "--sdk-path must point to crates/rayengine, not the workspace root",
                ));
            }
            if sdk.to_str().is_none() {
                return Err(Failure::new("invalid_sdk", "SDK path must be UTF-8"));
            }
            Ok(sdk)
        })
        .transpose()?;
    let dependency = match &sdk {
        Some(path) => format!(
            "{{ path = {} }}",
            serde_json::to_string(path.to_str().expect("validated UTF-8"))
                .expect("string serialization")
        ),
        None => format!("\"{}\"", env!("CARGO_PKG_VERSION")),
    };
    if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
        fs::create_dir_all(parent).map_err(io_error)?;
    }
    // Atomic: rejects existing directories, files and symlinks.
    fs::create_dir(path).map_err(|e| {
        Failure::new(
            "destination_exists_or_unwritable",
            format!("{}: {e}", path.display()),
        )
    })?;
    let mut destination = NewDirectory {
        path: path.to_path_buf(),
        committed: false,
    };
    fs::create_dir(path.join("src")).map_err(io_error)?;
    // Nested standalone plugins are explicit dependencies, not automatically
    // adopted members of a generated game's workspace.
    let workspace = match template {
        Template::Game(_) => "[workspace]\nexclude = [\"plugins\"]\n",
        Template::Plugin => "[workspace]\n",
    };
    let cargo = format!(
        "[package]\nname = {}\nversion = \"0.1.0\"\nedition = \"2024\"\nrust-version = \"1.89\"\n\n[dependencies]\nrayengine = {dependency}\n\n{workspace}",
        serde_json::to_string(&name).expect("string serialization")
    );
    fs::write(path.join("Cargo.toml"), cargo).map_err(io_error)?;
    let (source_path, source, kind) = match template {
        Template::Game(Kind::TwoD) => ("src/main.rs", include_str!("templates/2d.rs"), "2d"),
        Template::Game(Kind::ThreeD) => ("src/main.rs", include_str!("templates/3d.rs"), "3d"),
        Template::Game(Kind::Topdown) => (
            "src/main.rs",
            include_str!("templates/topdown.rs"),
            "topdown",
        ),
        Template::Game(Kind::Platformer) => (
            "src/main.rs",
            include_str!("templates/platformer.rs"),
            "platformer",
        ),
        Template::Plugin => ("src/lib.rs", include_str!("templates/plugin.rs"), "plugin"),
    };
    fs::write(path.join(source_path), source).map_err(io_error)?;
    fs::write(
        path.join(".gitignore"),
        "/target/\n/artifacts/\n/bundles/\n",
    )
    .map_err(io_error)?;
    let readme = match template {
        Template::Game(_) => format!(
            "# {name}\n\nA rayengine game.\n\n```sh\ncargo run\ncargo check\ncargo run -- --frames 60 --screenshot artifacts/frame.png\n```\n\nrayengine.toml describes runtime defaults and asset discovery; Cargo.toml
still describes the Rust build. Inspect with `rayengine info . --profile dev`.
Run with `rayengine run . --profile dev -- --frames 60`. Direct `cargo run`
loads the base manifest; set RAYENGINE_PROFILE=dev to select a profile.
Paths are relative to the manifest, even when invoked from another directory.

The SDK dependency can be changed in Cargo.toml. Keep game state in\nordinary Rust components; fixed_update handles simulation and draw handles\ninterpolated rendering. See rayengine's rustdoc guides for the API.\n"
        ),
        Template::Plugin => format!(
            "# {name}\n\nAn optional rayengine Cargo plugin.\n\n```sh\ncargo check\ncargo test\ncargo doc --no-deps\n```\n\nAdd this library as a path dependency in the consuming game's Cargo.toml.\nStore MyPlugin and PluginState in your game, then call its Plugin hooks\nexplicitly from Game. The engine does not register or invoke plugins.\nConfigure action IDs in the game; keep GPU work on the render thread.\nThe SDK dependency must match the SDK source/version used by the game.\nIf nested in an existing workspace, exclude this path in its root workspace\nor remove this library's [workspace] and add it to the root members.\nGenerated rayengine games already exclude plugins.\nSee rayengine's plugins rustdoc guide for composition, ownership, and cleanup.\n"
        ),
    };
    fs::write(path.join("README.md"), readme).map_err(io_error)?;
    let mut files = vec!["Cargo.toml", source_path, ".gitignore", "README.md"];
    if matches!(template, Template::Game(_)) {
        let project_manifest = include_str!("templates/rayengine.toml").replace("{{name}}", &name);
        fs::write(path.join("rayengine.toml"), project_manifest).map_err(io_error)?;
        fs::create_dir(path.join("assets")).map_err(io_error)?;
        fs::write(path.join("assets/.gitkeep"), "").map_err(io_error)?;
        files.extend(["rayengine.toml", "assets/.gitkeep"]);
        if matches!(template, Template::Game(Kind::Topdown | Kind::Platformer)) {
            plugins::edit(path, "tilemap", true, None, &[])?;
            let level = if kind == "topdown" {
                include_str!("templates/topdown.toml")
            } else {
                include_str!("templates/platformer.toml")
            };
            fs::write(path.join("assets/level.toml"), level).map_err(io_error)?;
            files.push("assets/level.toml");
        }
    }
    let project = path.canonicalize().map_err(io_error)?;
    destination.committed = true;
    Ok(json!({ "path": project, "name": name, "kind": kind,
        "sdk_path": sdk, "files": files }))
}

struct NewDirectory {
    path: PathBuf,
    committed: bool,
}
impl Drop for NewDirectory {
    fn drop(&mut self) {
        if !self.committed {
            let _ = fs::remove_dir_all(&self.path);
        }
    }
}

fn validate_name(name: &str) -> Result<()> {
    if name.is_empty()
        || !name.as_bytes()[0].is_ascii_alphabetic()
        || !name
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
        || ["rayengine", "rayengine-core", "rayengine-cli"].contains(&name)
    {
        Err(Failure::new(
            "invalid_name",
            "package name must start with an ASCII letter and contain letters, digits, '-' or '_' (engine package names are reserved)",
        ))
    } else {
        Ok(())
    }
}

fn cargo_task(
    task: &str,
    path: &Path,
    release: bool,
    profile: Option<&str>,
    bin: Option<&str>,
    args: &[String],
    json_mode: bool,
) -> Result<Value> {
    let manifest = manifest(path)?;
    let (project, _) = project_manifest(path, profile)?;
    let mut command = Command::new("cargo");
    command
        .arg(task)
        .arg("--manifest-path")
        .arg(&manifest)
        .current_dir(manifest.parent().expect("manifest has parent"));
    if release {
        command.arg("--release");
    }
    if json_mode {
        command.arg("--message-format=json");
    }
    if task == "run" {
        if let Some(target) = bin.or_else(|| {
            project
                .as_ref()
                .and_then(|p| p.settings.project.executable.as_deref())
        }) {
            command.arg("--bin").arg(target);
        }
        // Pass an explicit file/profile to opt-in runtimes, independent of cwd.
        command
            .env_remove("RAYENGINE_MANIFEST")
            .env_remove("RAYENGINE_PROFILE");
        if let Some(project) = &project {
            command.env("RAYENGINE_MANIFEST", &project.path);
            if let Some(profile) = &project.profile {
                command.env("RAYENGINE_PROFILE", profile);
            }
        }
        command.arg("--").args(args);
    }
    if !json_mode {
        let status = command.status().map_err(process_error)?;
        if !status.success() {
            return Err(Failure::new(
                "cargo_failed",
                format!("cargo {task} exited with {status}"),
            ));
        }
        return Ok(
            json!({ "manifest": manifest, "release": release, "project_manifest": project }),
        );
    }
    let output = command.output().map_err(process_error)?;
    if !output.status.success() {
        return Err(cargo_failure(output, &format!("cargo {task} failed")));
    }
    let stdout = String::from_utf8_lossy(&output.stdout);
    let mut diagnostics = Vec::new();
    let mut game_output = Vec::new();
    for line in stdout.lines() {
        match serde_json::from_str::<Value>(line) {
            Ok(value) if value.get("reason").is_some() => diagnostics.push(value),
            _ => game_output.push(line),
        }
    }
    Ok(
        json!({ "manifest": manifest, "release": release, "project_manifest": project, "diagnostics": diagnostics,
        "stdout": game_output.join("\n"), "stderr": String::from_utf8_lossy(&output.stderr) }),
    )
}

fn doctor(fix_hints: bool) -> Result<Value> {
    let mut checks = Vec::new();
    for (name, args) in [
        ("rustc", &["--version"][..]),
        ("cargo", &["--version"]),
        ("cmake", &["--version"]),
        ("clang", &["--version"]),
    ] {
        let output = Command::new(name).args(args).output();
        let (ok, detail) = match output {
            Ok(out) => (
                out.status.success(),
                String::from_utf8_lossy(&out.stdout)
                    .lines()
                    .next()
                    .unwrap_or("")
                    .to_string(),
            ),
            Err(e) => (false, e.to_string()),
        };
        checks.push(json!({ "name": name, "required": true, "ok": ok, "detail": detail }));
    }
    if cfg!(target_os = "linux") {
        for (name, required, packages) in [
            (
                "X11/OpenGL/audio headers",
                true,
                &["x11", "xrandr", "xinerama", "xcursor", "xi", "gl", "alsa"][..],
            ),
            ("Wayland headers", false, &["wayland-client", "xkbcommon"]),
        ] {
            let ok = Command::new("pkg-config")
                .arg("--exists")
                .args(packages)
                .output()
                .is_ok_and(|out| out.status.success());
            checks.push(json!({ "name": name, "required": required, "ok": ok, "detail": packages.join(", ") }));
        }
    }
    let hints = if fix_hints {
        lifecycle::fix_hints()
    } else {
        vec![]
    };
    let data = json!({ "engine_version": env!("CARGO_PKG_VERSION"), "platform": std::env::consts::OS, "checks": checks, "fix_hints": hints });
    if checks
        .iter()
        .any(|c| c["required"] == true && c["ok"] == false)
    {
        Err(Failure {
            code: "missing_prerequisites",
            message: "native build prerequisites are missing; see installation guide".into(),
            details: data,
        })
    } else {
        Ok(data)
    }
}

fn cargo_failure(output: std::process::Output, message: &str) -> Failure {
    Failure {
        code: "cargo_failed",
        message: message.into(),
        details: json!({
            "exit_code": output.status.code(), "stdout": String::from_utf8_lossy(&output.stdout),
            "stderr": String::from_utf8_lossy(&output.stderr),
            "diagnostics": String::from_utf8_lossy(&output.stdout).lines().filter_map(|line| serde_json::from_str::<Value>(line).ok()).collect::<Vec<_>>()
        }),
    }
}
fn io_error(error: std::io::Error) -> Failure {
    Failure::new("io_failed", error.to_string())
}
fn process_error(error: std::io::Error) -> Failure {
    Failure::new("process_failed", error.to_string())
}

fn print_success(command: &str, data: &Value) {
    match command {
        "new" | "new-plugin" => println!(
            "Created {} at {}\nCheck it with: cargo check --manifest-path {}/Cargo.toml",
            data["name"].as_str().unwrap_or("game"),
            data["path"].as_str().unwrap_or(""),
            data["path"].as_str().unwrap_or("")
        ),
        "doctor" => {
            println!(
                "rayengine {} / {}",
                env!("CARGO_PKG_VERSION"),
                std::env::consts::OS
            );
            if let Some(checks) = data["checks"].as_array() {
                for check in checks {
                    println!(
                        "{} {}: {}",
                        if check["ok"] == true {
                            "ok"
                        } else {
                            "optional/missing"
                        },
                        check["name"].as_str().unwrap_or(""),
                        check["detail"].as_str().unwrap_or("")
                    );
                }
            }
            if let Some(hints) = data["fix_hints"].as_array() {
                for hint in hints {
                    println!("Hint (not executed): {}", hint.as_str().unwrap_or(""));
                }
            }
        }
        "info" => println!(
            "{}",
            serde_json::to_string_pretty(data).expect("JSON value")
        ),
        "check" | "build" | "run" => println!("cargo {command} completed"),
        _ => println!(
            "{}",
            serde_json::to_string_pretty(data).expect("JSON value")
        ),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn unsafe_or_ambiguous_package_names_are_rejected() {
        for name in [
            "",
            "../game",
            "3game",
            "has space",
            "rayengine",
            "line\nbreak",
        ] {
            assert!(validate_name(name).is_err());
        }
        assert!(validate_name("my-game_2").is_ok());
    }

    #[test]
    fn creation_never_overwrites_an_existing_project() {
        let path = std::env::temp_dir().join(format!("rayengine-cli-test-{}", std::process::id()));
        fs::create_dir(&path).unwrap();
        fs::write(path.join("keep.txt"), "existing user data").unwrap();
        let error = create_project(&path, Kind::TwoD, Some("test-game".into()), None).unwrap_err();
        assert_eq!(error.code, "destination_exists_or_unwritable");
        assert_eq!(
            fs::read_to_string(path.join("keep.txt")).unwrap(),
            "existing user data"
        );
        fs::remove_file(path.join("keep.txt")).unwrap();
        fs::remove_dir(path).unwrap();
    }
}