concinnity-dev 0.19.119

The Concinnity dev tooling library: world authoring, the in-engine editor, the debug server, docs and packaging
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
// The command tree itself: every subcommand `concinnity` accepts and the
// arguments it takes. Parsing only -- what each command does lives behind
// `dispatch`.
use concinnity_engine::app::run::LaunchRequest;
use std::num::NonZeroU32;

use concinnity_core::gfx::view_modes::ShowFlags;

use super::value_enums::{
    BundleFormatArg, DlssPresetArg, QualityPresetArg, RtDynamicArg, ShowFlagArg,
};

#[derive(clap::Subcommand, Debug)]
pub(crate) enum Commands {
    /// Create a new app in the current directory
    #[command(name = "init")]
    Init,

    /// Create a new app in a new directory
    #[command(name = "new")]
    New(NewArgs),

    /// Build a world from worlds/ into binary blobs
    #[command(name = "build")]
    Build(BuildArgs),

    /// Run a compiled world
    //
    // Production path: no debug server and no command channel. A shipped run
    // is neither remotely inspectable nor remotely driven: use `cn debug` for
    // that.
    #[command(name = "run")]
    Run(RunArgs),

    /// Run interpreted directly from a world jsonl file
    //
    // Compiles the world in memory (no prior `cn build` needed) and stands
    // up the localhost debug server.
    // This is the development run, and the path the agentic loop / a host UI
    // use when they need to read or drive runtime state: the port it opens
    // serves MCP.
    #[command(name = "debug")]
    Debug(DebugArgs),

    /// Edit a world in-engine with a save-back HUD [default command]
    //
    // Compiles world.jsonl in memory (no prior `cn build` needed, and the blobs
    // one wrote are neither read nor refreshed here), overlays the editor HUD (a
    // SAVE button plus an add-asset button), and persists edits by writing
    // world.jsonl. No command channel unless --debug-port is given (which
    // stands up the same MCP debug server `cn debug` uses, so an agent can
    // drive an editor session).
    #[command(name = "editor")]
    Editor(EditorArgs),

    /// Add an asset to the active world
    //
    // TARGET can be:
    //   - A file path  (shaders/pbr.vert, models/scene.obj)
    //     Type is inferred from the file extension or the JSON `type` field.
    //   - A type name  (Logger, LLM, HttpServer, VulkanRenderer, ...)
    //     Asset is created with the type's registered default args.
    #[command(name = "add")]
    Add(AddArgs),

    /// Remove an asset from the active world by its id
    //
    // ID is the `$id` an entry declares in its args (e.g. "pbr_vert"), or the
    // `<Type>#<ordinal>` handle of an anonymous one (e.g. "Prop#3").
    #[command(name = "rm")]
    Rm(RmArgs),

    /// List all declared assets
    #[command(name = "list")]
    List(ListArgs),

    /// Print an asset's effective entry from the expanded world
    //
    // Prints the full JSONL line for ID as the build sees it, including
    // assets that only exist through build-time expansion or injection. The
    // output can be pasted into world.jsonl verbatim to override a default.
    #[command(name = "explain")]
    Explain(ExplainArgs),

    /// Regenerate the asset reference pages under docs/assets
    //
    // Renders the asset schema compiled into this build, rustdoc included, so
    // it needs no source tree.
    #[command(name = "docs")]
    Docs(DocsArgs),

    /// Validate a world without building
    #[command(name = "test")]
    Test(TestArgs),

    /// Package a built world into a distributable app
    #[command(name = "export")]
    Export(ExportArgs),

    /// Serve the debug protocol to an MCP client over stdio
    //
    // A child process an MCP client spawns, not a listener: it speaks JSON-RPC
    // over stdin/stdout and forwards each tool call to a running app's debug
    // port, which serves the same protocol to any client that posts to it.
    #[command(name = "mcp")]
    Mcp(McpArgs),

    /// Print the version
    #[command(name = "version")]
    Version,
}

// The argv face of the launch-time render knobs on the engine's `LaunchRequest`.
// Each is a diagnostic: omitting it leaves the shipping behavior, and none is
// persisted, so a probe run can force one without writing settings. Flattened
// into every command that launches a world (`run` / `debug` / `editor`).
#[derive(Debug, Default, clap::Args)]
pub(crate) struct RenderArgs {
    /// Force the master graphics-quality preset for this launch, unpersisted
    // Outranks the settings-menu choice in .concinnity/settings. Only the
    // `ultra` ceiling permits ray-traced reflections, so an RT probe that omits
    // this measures a frame with RT clamped off and no log line saying so.
    #[arg(long, value_enum)]
    pub(crate) quality_preset: Option<QualityPresetArg>,

    /// How the ray-tracing acceleration structure tracks moving props
    // Omitted = `auto`, the dirty-gated TLAS rebuild a shipped run uses.
    #[arg(long, value_enum)]
    pub(crate) rt_dynamic: Option<RtDynamicArg>,

    /// Whether skinned meshes join the ray-tracing acceleration structure
    // Omitted = in. `--rt-skinned-geometry false` leaves the BVH over static +
    // instanced geometry only, which isolates the skinned trace path.
    #[arg(long)]
    pub(crate) rt_skinned_geometry: Option<bool>,

    /// Force the DLSS render preset for this launch, unpersisted
    // Outranks the settings-menu choice, so a probe can run a preset without
    // writing settings. Ignored unless DLSS is the upscaler.
    #[arg(long, value_enum)]
    pub(crate) dlss_preset: Option<DlssPresetArg>,

    /// Step the frame clock by exactly 1/RATE seconds per frame, whatever the wall time
    // So a capture at frame N sees the same clock on every launch: anything
    // animated by the clock, a world Shader's vertex hook included, lands in
    // the same place, and a pixel A/B of it is not noise.
    #[arg(long, value_name = "RATE")]
    pub(crate) fixed_frame_rate: Option<NonZeroU32>,

    /// Start with a feature pass off, as the editor's View menu turns it off; repeatable
    // So a probe can hold a frame with one pass removed against the same frame
    // with it on, each captured at an exact frame of its own launch.
    #[arg(long, value_enum, value_name = "FLAG")]
    pub(crate) hide: Vec<ShowFlagArg>,
}

impl RenderArgs {
    // The launch request these flags make, with the command's own validation
    // flag and whether it runs a development session.
    pub(crate) fn launch(&self, validation: Option<bool>, dev_loop: bool) -> LaunchRequest {
        LaunchRequest {
            capture: false,
            dev_loop,
            validation,
            quality_preset: self.quality_preset.map(Into::into),
            rt_dynamic: self.rt_dynamic.map(Into::into),
            rt_skinned_geometry: self.rt_skinned_geometry,
            dlss_preset: self.dlss_preset.map(Into::into),
            fixed_frame_rate: self.fixed_frame_rate,
            show: self.hide.iter().fold(ShowFlags::all(), |show, &flag| {
                show.with(flag.into(), false)
            }),
        }
    }
}

// The `-f` world a command operates on. Flattened into every command that
// reads a world from disk; an absent flag discovers it, a named file that does
// not exist is an error.
#[derive(Debug, clap::Args)]
pub(crate) struct WorldArg {
    /// Path to a world JSONL file (default: discover from worlds/)
    #[arg(short = 'f', long)]
    file: Option<String>,
}

impl WorldArg {
    pub(crate) fn file(&self) -> Option<&str> {
        self.file.as_deref()
    }
}

#[derive(Debug, clap::Args)]
pub(crate) struct DebugArgs {
    #[command(flatten)]
    pub(crate) world: WorldArg,

    /// Port for the localhost runtime debug server
    #[arg(long, default_value_t = 8777)]
    pub(crate) debug_port: u16,

    /// Enable graphics API validation, overriding the build profile
    // Omitting the flag defers to the build profile. See `RunArgs::validation`.
    #[arg(long)]
    pub(crate) validation: Option<bool>,

    #[command(flatten)]
    pub(crate) render: RenderArgs,
}

#[derive(Debug, clap::Args)]
pub(crate) struct McpArgs {
    /// Port the runtime debug server is listening on
    #[arg(long, default_value_t = 8777)]
    pub(crate) debug_port: u16,
}

#[derive(Debug, clap::Args)]
pub(crate) struct EditorArgs {
    /// Path to a world JSONL file (default: discover from worlds/)
    #[arg(short = 'f', long)]
    pub(crate) file: Option<String>,

    /// Start the localhost debug server on this port alongside the editor
    // Absent leaves the editor without a command channel; present makes an
    // editor session inspectable and drivable by any MCP client.
    #[arg(long)]
    pub(crate) debug_port: Option<u16>,

    /// Enable graphics API validation, overriding the build profile
    // Omitting the flag defers to the build profile. See `RunArgs::validation`.
    #[arg(long)]
    pub(crate) validation: Option<bool>,

    #[command(flatten)]
    pub(crate) render: RenderArgs,
}

#[derive(Debug, clap::Args)]
pub(crate) struct RunArgs {
    /// Enable graphics API validation, overriding the build profile
    // The DirectX / Vulkan debug layers, or on macOS the Metal API-validation
    // layer (the process re-execs once with `MTL_DEBUG_LAYER` set, since Metal
    // cannot toggle it from inside a running process). Omitting the flag defers
    // to the build profile: on for debug builds, off for release. Pass
    // `--validation false` to force it off in a debug build. The heavier Metal
    // shader validation is not enabled by this flag; set `MTL_SHADER_VALIDATION=1`
    // in the environment for that.
    #[arg(long)]
    pub(crate) validation: Option<bool>,

    /// Step simulation and rendering serially on one thread instead of pipelining them
    // A/B comparison, escape hatch.
    #[arg(long)]
    pub(crate) serial: bool,

    /// Keep every system's internal work on the sim thread instead of the job pool
    // Determinism oracle, escape hatch.
    #[arg(long)]
    pub(crate) serial_schedule: bool,

    /// Capture the last presented frame to this PNG when the run stops
    #[arg(long)]
    pub(crate) screenshot: Option<String>,

    /// Stop after this many frames (overrides GraphicsConfig.max_frames)
    #[arg(long)]
    pub(crate) frames: Option<u64>,

    #[command(flatten)]
    pub(crate) render: RenderArgs,
}

#[derive(Debug, clap::Args)]
pub(crate) struct AddArgs {
    /// Path to an asset file, a type name, or an entry like '["Window", {}]'
    pub(crate) target: String,

    /// The `$id` written into the world
    // If omitted, a file target's id is derived from the filename, and a type
    // name or inline entry without one is added anonymous.
    #[arg(short, long)]
    pub(crate) id: Option<String>,

    /// Named scaffold preset used when bootstrapping a new world
    // Currently only "minimal-3d-world" (a camera, sun, room, and sky on top of
    // the base scaffold). Ignored when scaffolding doesn't fire.
    #[arg(short = 't', long)]
    pub(crate) template: Option<String>,
}

#[derive(Debug, clap::Args)]
pub(crate) struct RmArgs {
    /// The asset's `$id`, or the `<Type>#<ordinal>` of an anonymous one
    pub(crate) id: String,
}

#[derive(Debug, clap::Args)]
pub(crate) struct TestArgs {
    #[command(flatten)]
    pub(crate) world: WorldArg,
}

#[derive(Debug, clap::Args)]
pub(crate) struct ListArgs {
    #[command(flatten)]
    pub(crate) world: WorldArg,

    /// List the expanded world the build produces
    // build-time macros are expanded and injected defaults included,
    // each row tagged with its provenance (authored / injected / expanded).
    #[arg(long)]
    pub(crate) expanded: bool,

    /// List the systems this world runs, in order, each with the condition
    // that includes it. Builds the world and reports `World::system_manifest()`
    // -- the same gates the runtime runs at start -- so it cannot drift.
    #[arg(long)]
    pub(crate) systems: bool,
}

#[derive(Debug, clap::Args)]
pub(crate) struct ExplainArgs {
    /// The asset's `$id`, or the `<Type>#<ordinal>` of an anonymous one
    pub(crate) id: String,

    #[command(flatten)]
    pub(crate) world: WorldArg,
}

#[derive(Debug, clap::Args)]
pub(crate) struct DocsArgs {
    /// Directory to write the docs/assets pages under
    #[arg(long, default_value = ".")]
    pub(crate) root: Option<String>,
}

#[derive(Debug, clap::Args)]
pub(crate) struct NewArgs {
    /// Directory to create the project in
    pub(crate) path: String,
}

#[derive(Debug, clap::Args)]
pub(crate) struct BuildArgs {
    #[command(flatten)]
    pub(crate) world: WorldArg,

    /// Also show the build's informational messages, such as each imported mesh
    #[arg(short, long)]
    pub(crate) verbose: bool,
}

#[derive(Debug, clap::Args)]
pub(crate) struct ExportArgs {
    #[command(flatten)]
    pub(crate) world: WorldArg,

    /// Override the application name
    #[arg(short = 'n', long)]
    pub(crate) name: Option<String>,

    /// Override the application version
    #[arg(long)]
    pub(crate) version: Option<String>,

    /// EntityTarget platform
    #[arg(long)]
    pub(crate) platform: Option<String>,

    /// Output directory for the exported app
    #[arg(long, default_value = "dist")]
    pub(crate) out: String,

    /// Output format
    #[arg(long, value_enum, default_value = "zip")]
    pub(crate) format: BundleFormatArg,

    /// Also produce a .dmg wrapping the .app (macOS-only)
    #[arg(long)]
    pub(crate) dmg: bool,
}

// Argument-parsing tests. The engine-launching dispatch and the Metal re-exec
// are exercised by the `tests/cli.rs` integration tests, which run the built
// binary; these cover the clap surface -- the command tree, the per-subcommand
// defaults, and the value-enum parsing -- without a process.
#[cfg(test)]
mod tests {
    use super::*;
    use crate::cli::Cli;
    use clap::Parser;
    use concinnity_core::render::dlss::DlssPreset;
    use concinnity_core::render::rt_geom::RtDynamicMode;
    use concinnity_engine::gfx::quality_preset::QualityPreset;

    // Every world-launching command carries the render flags, and each one
    // defaults to absent (which the engine resolves to today's behavior).
    #[test]
    fn the_render_flags_default_to_absent_on_every_launch_command() {
        for argv in [
            vec!["concinnity", "run"],
            vec!["concinnity", "debug"],
            vec!["concinnity", "editor"],
        ] {
            let cli = Cli::try_parse_from(&argv).unwrap();
            let render = match cli.resolved_command() {
                Commands::Run(a) => &a.render,
                Commands::Debug(a) => &a.render,
                Commands::Editor(a) => &a.render,
                _ => panic!("expected a launch command for {argv:?}"),
            };
            assert!(render.quality_preset.is_none(), "{argv:?}");
            assert!(render.rt_dynamic.is_none(), "{argv:?}");
            assert!(render.rt_skinned_geometry.is_none(), "{argv:?}");
            assert!(render.dlss_preset.is_none(), "{argv:?}");
            assert!(render.fixed_frame_rate.is_none(), "{argv:?}");
            assert!(render.hide.is_empty(), "{argv:?}");
        }
    }

    #[test]
    fn the_render_flags_map_onto_the_launch_request() {
        let cli = Cli::try_parse_from([
            "concinnity",
            "run",
            "--quality-preset",
            "ultra",
            "--rt-dynamic",
            "rebuild",
            "--rt-skinned-geometry",
            "false",
            "--dlss-preset",
            "m",
            "--fixed-frame-rate",
            "60",
            "--hide",
            "reactive",
            "--hide",
            "fog",
            "--hide",
            "reactive",
        ])
        .unwrap();
        let Commands::Run(args) = cli.resolved_command() else {
            panic!("expected run");
        };
        assert_eq!(
            args.render.launch(Some(true), true),
            LaunchRequest {
                capture: false,
                dev_loop: true,
                validation: Some(true),
                quality_preset: Some(QualityPreset::Ultra),
                rt_dynamic: Some(RtDynamicMode::Rebuild),
                rt_skinned_geometry: Some(false),
                dlss_preset: Some(DlssPreset::M),
                fixed_frame_rate: NonZeroU32::new(60),
                show: ShowFlags::all()
                    .toggled(ShowFlags::REACTIVE)
                    .toggled(ShowFlags::FOG),
            }
        );
    }

    // A rate of 0 would stop the clock, so it is refused at the flag.
    #[test]
    fn a_zero_fixed_frame_rate_is_refused() {
        let parsed = Cli::try_parse_from(["concinnity", "run", "--fixed-frame-rate", "0"]);
        assert!(parsed.is_err());
    }

    #[test]
    fn the_render_flags_parse_on_every_launch_command() {
        for command in ["run", "debug", "editor"] {
            let cli = Cli::try_parse_from([
                "concinnity",
                command,
                "--quality-preset",
                "ultra",
                "--rt-dynamic",
                "rebuild",
                "--rt-skinned-geometry",
                "false",
                "--dlss-preset",
                "l",
                "--fixed-frame-rate",
                "30",
                "--hide",
                "reactive",
                "--hide",
                "fog",
            ])
            .unwrap();
            let render = match cli.resolved_command() {
                Commands::Run(a) => &a.render,
                Commands::Debug(a) => &a.render,
                Commands::Editor(a) => &a.render,
                _ => panic!("expected a launch command for {command}"),
            };
            assert!(
                matches!(render.quality_preset, Some(QualityPresetArg::Ultra)),
                "{command}"
            );
            assert!(
                matches!(render.rt_dynamic, Some(RtDynamicArg::Rebuild)),
                "{command}"
            );
            assert_eq!(render.rt_skinned_geometry, Some(false), "{command}");
            assert!(
                matches!(render.dlss_preset, Some(DlssPresetArg::L)),
                "{command}"
            );
            assert_eq!(render.fixed_frame_rate, NonZeroU32::new(30), "{command}");
            assert_eq!(
                render.launch(None, false).show,
                ShowFlags::all()
                    .with(ShowFlags::REACTIVE, false)
                    .with(ShowFlags::FOG, false),
                "{command}"
            );
        }
    }

    #[test]
    fn debug_starts_the_server_on_the_named_world() {
        let cli = Cli::try_parse_from(["concinnity", "debug", "-f", "world.jsonl"]).unwrap();
        let Commands::Debug(a) = cli.resolved_command() else {
            panic!("expected debug");
        };
        assert_eq!(a.world.file(), Some("world.jsonl"));
        assert_eq!(a.debug_port, 8777, "the same default cn mcp dials");
    }

    #[test]
    fn debug_takes_no_subcommand() {
        for argv in [
            ["concinnity", "debug", "send"],
            ["concinnity", "debug", "screenshot"],
            ["concinnity", "debug", "watch"],
        ] {
            assert!(Cli::try_parse_from(argv).is_err(), "{argv:?}");
        }
    }

    #[test]
    fn mcp_defaults_to_the_debug_port() {
        let cli = Cli::try_parse_from(["concinnity", "mcp"]).unwrap();
        let Commands::Mcp(a) = cli.resolved_command() else {
            panic!("expected mcp");
        };
        assert_eq!(a.debug_port, 8777);
        let cli = Cli::try_parse_from(["concinnity", "mcp", "--debug-port", "9001"]).unwrap();
        let Commands::Mcp(a) = cli.resolved_command() else {
            panic!("expected mcp");
        };
        assert_eq!(a.debug_port, 9001);
    }

    #[test]
    fn export_defaults() {
        let cli = Cli::try_parse_from(["concinnity", "export"]).unwrap();
        let Commands::Export(e) = cli.resolved_command() else {
            panic!("expected export");
        };
        assert_eq!(e.out, "dist");
        assert_eq!(e.format, BundleFormatArg::Zip);
        assert!(!e.dmg);
    }

    #[test]
    fn export_rejects_an_unknown_format() {
        let err = Cli::try_parse_from(["concinnity", "export", "--format", "tarball"]).unwrap_err();
        assert_eq!(err.kind(), clap::error::ErrorKind::InvalidValue);
    }

    #[test]
    fn add_requires_a_target() {
        assert!(Cli::try_parse_from(["concinnity", "add"]).is_err());
        let cli = Cli::try_parse_from(["concinnity", "add", "Logger", "--id", "log"]).unwrap();
        let Commands::Add(a) = cli.resolved_command() else {
            panic!("expected add");
        };
        assert_eq!(a.target, "Logger");
        assert_eq!(a.id.as_deref(), Some("log"));
    }

    #[test]
    fn init_takes_no_arguments() {
        let cli = Cli::try_parse_from(["concinnity", "init"]).unwrap();
        assert!(matches!(cli.resolved_command(), Commands::Init));
        assert!(Cli::try_parse_from(["concinnity", "init", "extra"]).is_err());
    }

    #[test]
    fn new_requires_a_path() {
        assert!(Cli::try_parse_from(["concinnity", "new"]).is_err());
        let cli = Cli::try_parse_from(["concinnity", "new", "my-app"]).unwrap();
        let Commands::New(a) = cli.resolved_command() else {
            panic!("expected new");
        };
        assert_eq!(a.path, "my-app");
    }

    // `build` and `test` share the same optional --file, defaulting to discovery.
    #[test]
    fn build_and_test_take_an_optional_world_file() {
        let cli = Cli::try_parse_from(["concinnity", "build"]).unwrap();
        let Commands::Build(a) = cli.resolved_command() else {
            panic!("expected build");
        };
        assert!(a.world.file().is_none());

        let cli = Cli::try_parse_from(["concinnity", "build", "-f", "w.jsonl"]).unwrap();
        let Commands::Build(a) = cli.resolved_command() else {
            panic!("expected build");
        };
        assert_eq!(a.world.file(), Some("w.jsonl"));

        let cli = Cli::try_parse_from(["concinnity", "test", "--file", "w.jsonl"]).unwrap();
        let Commands::Test(a) = cli.resolved_command() else {
            panic!("expected test");
        };
        assert_eq!(a.world.file(), Some("w.jsonl"));
    }

    #[test]
    fn list_flags_are_independent() {
        let cli = Cli::try_parse_from(["concinnity", "list"]).unwrap();
        let Commands::List(a) = cli.resolved_command() else {
            panic!("expected list");
        };
        assert!(!a.expanded);
        assert!(!a.systems);

        let cli = Cli::try_parse_from(["concinnity", "list", "--expanded", "--systems"]).unwrap();
        let Commands::List(a) = cli.resolved_command() else {
            panic!("expected list");
        };
        assert!(a.expanded);
        assert!(a.systems);
    }

    #[test]
    fn explain_requires_an_id() {
        assert!(Cli::try_parse_from(["concinnity", "explain"]).is_err());
        let cli = Cli::try_parse_from(["concinnity", "explain", "gfx", "-f", "w.jsonl"]).unwrap();
        let Commands::Explain(a) = cli.resolved_command() else {
            panic!("expected explain");
        };
        assert_eq!(a.id, "gfx");
        assert_eq!(a.world.file(), Some("w.jsonl"));
    }

    #[test]
    fn rm_requires_an_id() {
        assert!(Cli::try_parse_from(["concinnity", "rm"]).is_err());
        let cli = Cli::try_parse_from(["concinnity", "rm", "Prop#3"]).unwrap();
        let Commands::Rm(a) = cli.resolved_command() else {
            panic!("expected rm");
        };
        assert_eq!(a.id, "Prop#3");
    }

    #[test]
    fn add_takes_a_scaffold_template() {
        let cli = Cli::try_parse_from(["concinnity", "add", "scene.glb", "-t", "minimal-3d-world"])
            .unwrap();
        let Commands::Add(a) = cli.resolved_command() else {
            panic!("expected add");
        };
        assert_eq!(a.target, "scene.glb");
        assert_eq!(a.template.as_deref(), Some("minimal-3d-world"));
    }

    #[test]
    fn docs_root_defaults_to_the_current_directory() {
        let cli = Cli::try_parse_from(["concinnity", "docs"]).unwrap();
        let Commands::Docs(a) = cli.resolved_command() else {
            panic!("expected docs");
        };
        assert_eq!(a.root.as_deref(), Some("."));

        let cli = Cli::try_parse_from(["concinnity", "docs", "--root", "/engine"]).unwrap();
        let Commands::Docs(a) = cli.resolved_command() else {
            panic!("expected docs");
        };
        assert_eq!(a.root.as_deref(), Some("/engine"));
    }

    // Validation is tri-state: absent means "default for this build profile",
    // so an explicit `false` must survive parsing as a value rather than
    // collapsing into the absent case.
    #[test]
    fn run_validation_is_tri_state() {
        let cli = Cli::try_parse_from(["concinnity", "run"]).unwrap();
        let Commands::Run(a) = cli.resolved_command() else {
            panic!("expected run");
        };
        assert_eq!(a.validation, None);

        for (arg, expected) in [("true", true), ("false", false)] {
            let cli = Cli::try_parse_from(["concinnity", "run", "--validation", arg]).unwrap();
            let Commands::Run(a) = cli.resolved_command() else {
                panic!("expected run");
            };
            assert_eq!(a.validation, Some(expected));
        }
    }

    #[test]
    fn editor_takes_a_file_debug_port_and_validation() {
        let cli = Cli::try_parse_from(["concinnity", "editor"]).unwrap();
        let Commands::Editor(a) = cli.resolved_command() else {
            panic!("expected editor");
        };
        assert!(a.file.is_none());
        assert!(a.debug_port.is_none());
        assert!(a.validation.is_none());

        let cli = Cli::try_parse_from([
            "concinnity",
            "editor",
            "-f",
            "w.jsonl",
            "--debug-port",
            "9001",
            "--validation",
            "false",
        ])
        .unwrap();
        let Commands::Editor(a) = cli.resolved_command() else {
            panic!("expected editor");
        };
        assert_eq!(a.file.as_deref(), Some("w.jsonl"));
        assert_eq!(a.debug_port, Some(9001));
        assert_eq!(a.validation, Some(false));
    }

    #[test]
    fn export_flags_override_every_default() {
        let cli = Cli::try_parse_from([
            "concinnity",
            "export",
            "-f",
            "w.jsonl",
            "-n",
            "My Game",
            "--version",
            "2.0.0",
            "--platform",
            "macos",
            "--out",
            "build",
            "--format",
            "dir",
            "--dmg",
        ])
        .unwrap();
        let Commands::Export(e) = cli.resolved_command() else {
            panic!("expected export");
        };
        assert_eq!(e.world.file(), Some("w.jsonl"));
        assert_eq!(e.name.as_deref(), Some("My Game"));
        assert_eq!(e.version.as_deref(), Some("2.0.0"));
        assert_eq!(e.platform.as_deref(), Some("macos"));
        assert_eq!(e.out, "build");
        assert_eq!(e.format, BundleFormatArg::Dir);
        assert!(e.dmg);
    }

    #[test]
    fn debug_takes_a_port_and_validation_without_a_client() {
        let cli = Cli::try_parse_from([
            "concinnity",
            "debug",
            "--debug-port",
            "9100",
            "--validation",
            "true",
        ])
        .unwrap();
        let Commands::Debug(a) = cli.resolved_command() else {
            panic!("expected debug");
        };
        assert_eq!(a.debug_port, 9100);
        assert_eq!(a.validation, Some(true));
    }
}