camel-cli 0.47.0

Command-line interface for Apache Camel in Rust
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
//! Embedded-document runtime for compiled artifacts (openspec changes
//! `cli-compile` Tasks 2.2/2.3 and `multidoc` Task 2.2).
//!
//! [`run_embedded_document`] takes a validated [`EmbeddedRequest`] — a
//! v1 single-document trailer or a v2 decoded
//! [`VirtualDocumentStore`](super::store::VirtualDocumentStore) plus
//! the parsed artifact arguments — and runs it through the EXISTING
//! lifecycles:
//!
//! - v1 route artifacts drive the shared `camel run` lifecycle
//!   (`crate::commands::run::drive_lifecycle`) with the default
//!   in-memory config, the embedded single-document discovery seam,
//!   and `watch = false`;
//! - v2 multi-document route artifacts call
//!   [`camel_dsl::discover_virtual_store`] BEFORE boot (the merged
//!   embedded configuration feeds the context), build the
//!   `CamelConfig` through the deployment-time `${env:}` seam, and
//!   drive the same lifecycle with the discovered routes;
//! - job artifacts drive the existing job report/outcome lifecycle:
//!   v1 with the embedded document as the sole inline route source,
//!   v2 consuming the embedded job/config/route entries (indexed
//!   route files or the inline `routes:` block) with no filesystem
//!   route discovery.
//!
//! No compile-time asset is resolved at runtime, nothing is extracted
//! to a temporary location, and the watcher never activates.
//! `${env:NAME}` resolves from the deployment environment through the
//! discovery and config seams. Declared job `args:` resolve at startup
//! through the same parser path as normal jobs with an EMPTY `--arg`
//! list (jobargs Task 3.2): embedded declaration defaults fill the
//! interpolated fields — typed
//! defaults coerced through the same rules (jobtyped) — and a required
//! declaration without a default exits 2 before boot.
//!
//! [`self_detect_artifact`] is the binary entry point (Task 2.3): the
//! `camel` main calls it BEFORE Clap parses anything, so a self-contained
//! artifact consumes its own argv surface (`--report`, `--help`,
//! `--version`, `--manifest`) while a trailer-free image falls through to
//! the normal CLI unchanged.
//!
//! Exit codes: 0 graceful completion / job Completed; 1 job pipeline
//! failure (route runs end either in graceful completion or a boot-class
//! failure, so 1 stays reserved for them); 2 argument misuse, store or
//! configuration validation, boot failure, or report-write failure.

use std::fmt;
use std::path::{Path, PathBuf};
use std::process::ExitCode;

use serde::Serialize;

use super::CompileError;
use super::manifest;
use super::trailer::{self, Trailer, TrailerKind};
use crate::commands::run::{Discover, LifecycleFailure, LifecycleSpec};

/// Exit code for argument misuse, boot failure, and report-write failure.
const EXIT_REJECTION: i32 = 2;

/// Idle log line while a route artifact runs (watch disabled).
const IDLE_NOTE: &str = "compiled artifact running (hot-reload disabled). Press Ctrl+C to stop.";

/// Parsed artifact argument surface.
///
/// The exclusive modes (`--help`, `--version`, `--manifest`) print and
/// exit 0 without booting; `--report <path>` pairs with a run. The
/// surface is deliberately narrow: job arguments (`--arg`) are
/// unsupported (rejected as unknown) — declared arguments resolve from
/// the embedded declarations alone (jobargs Task 3.2).
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ArtifactArgs {
    /// `--report <path>`: where the run writes its report.
    pub report: Option<PathBuf>,
    /// `--help`: print usage and exit 0.
    pub help: bool,
    /// `--version`: print the runtime version and exit 0.
    pub version: bool,
    /// `--manifest`: print the operational manifest and exit 0.
    pub manifest: bool,
}

impl ArtifactArgs {
    /// The flag already present, for exclusive-mode conflict naming.
    fn first_set(&self) -> Option<&'static str> {
        if self.report.is_some() {
            Some("--report")
        } else if self.help {
            Some("--help")
        } else if self.version {
            Some("--version")
        } else if self.manifest {
            Some("--manifest")
        } else {
            None
        }
    }
}

/// Artifact-argument rejection. Every variant names the rejected
/// argument; the caller prints the diagnostic and exits 2.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ArtifactArgError {
    /// The same flag appeared twice.
    Duplicate(&'static str),
    /// Two mutually exclusive flags appeared together.
    Exclusive(&'static str, &'static str),
    /// `--report` has no value (end of arguments, or the next token is
    /// another flag).
    MissingValue(&'static str),
    /// An unknown flag.
    Unknown(String),
    /// A positional argument.
    Positional(String),
}

impl fmt::Display for ArtifactArgError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Duplicate(flag) => write!(f, "duplicate argument '{flag}'"),
            Self::Exclusive(a, b) => {
                write!(f, "arguments '{a}' and '{b}' are mutually exclusive")
            }
            Self::MissingValue(flag) => {
                write!(f, "argument '{flag}' requires a value")
            }
            Self::Unknown(arg) => write!(f, "unknown argument '{arg}'"),
            Self::Positional(arg) => write!(f, "unexpected positional argument '{arg}'"),
        }
    }
}

impl std::error::Error for ArtifactArgError {}

impl ArtifactArgs {
    /// Parse the artifact argv (no program name). Accepts `--report
    /// <path>`, `--help`, `--version`, and `--manifest`; rejects
    /// duplicates, exclusive combinations, missing report values,
    /// unknown flags, and positional arguments.
    pub fn parse(args: &[String]) -> Result<Self, ArtifactArgError> {
        let mut parsed = Self::default();
        let mut idx = 0;
        while idx < args.len() {
            let arg = args[idx].as_str();
            match arg {
                "--report" => {
                    if let Some(prev) = parsed.first_set() {
                        return Err(if prev == "--report" {
                            ArtifactArgError::Duplicate(prev)
                        } else {
                            ArtifactArgError::Exclusive(prev, "--report")
                        });
                    }
                    let Some(value) = args.get(idx + 1) else {
                        return Err(ArtifactArgError::MissingValue("--report"));
                    };
                    if value.starts_with('-') {
                        return Err(ArtifactArgError::MissingValue("--report"));
                    }
                    parsed.report = Some(PathBuf::from(value));
                    idx += 2;
                }
                "--help" | "--version" | "--manifest" => {
                    let flag: &'static str = match arg {
                        "--help" => "--help",
                        "--version" => "--version",
                        _ => "--manifest",
                    };
                    if let Some(prev) = parsed.first_set() {
                        return Err(if prev == flag {
                            ArtifactArgError::Duplicate(flag)
                        } else {
                            ArtifactArgError::Exclusive(prev, flag)
                        });
                    }
                    match flag {
                        "--help" => parsed.help = true,
                        "--version" => parsed.version = true,
                        _ => parsed.manifest = true,
                    }
                    idx += 1;
                }
                other if other.starts_with('-') => {
                    return Err(ArtifactArgError::Unknown(other.to_string()));
                }
                other => {
                    return Err(ArtifactArgError::Positional(other.to_string()));
                }
            }
        }
        Ok(parsed)
    }
}

/// Route-artifact status report: the exact JSON object
/// `{"kind":"route","status":"completed"|"failed","error":string|null}`
/// written to `--report` after boot/runtime completion or failure.
#[derive(Debug, Serialize)]
pub struct RouteReport {
    kind: &'static str,
    status: &'static str,
    error: Option<String>,
}

impl RouteReport {
    /// A gracefully completed run.
    fn completed() -> Self {
        Self {
            kind: "route",
            status: "completed",
            error: None,
        }
    }

    /// A failed run (boot/discovery class carries the diagnostic).
    fn failed(error: String) -> Self {
        Self {
            kind: "route",
            status: "failed",
            error: Some(error),
        }
    }

    /// Compact JSON with the exact key order `kind`, `status`, `error`.
    pub fn to_json(&self) -> String {
        serde_json::to_string(self).expect("route report serialization cannot fail") // allow-unwrap
    }
}

/// One validated embedded run request: the decoded artifact plus the
/// parsed artifact arguments.
///
/// - v1 (`[`EmbeddedRequest::SingleDocument`]`, built by
///   [`EmbeddedRequest::from_trailer`]): the single-document trailer
///   payload runs through the single-document seams — default
///   in-memory config, embedded-text discovery. v1 artifacts keep this
///   path verbatim.
/// - v2 ([`EmbeddedRequest::VirtualStore`], built by
///   [`EmbeddedRequest::from_v2`]; multidoc Task 2.2): the decoded
///   multi-document store runs through the virtual-store runtime —
///   merged embedded configuration, ordered source-plan routes,
///   deployment-time `${env:}` resolution. Single-document v2 stores
///   take the same path.
#[derive(Debug, Clone)]
pub enum EmbeddedRequest {
    /// v1 single-document artifact.
    SingleDocument {
        /// Embedded artifact kind (route/job).
        kind: TrailerKind,
        /// Logical source name; the runtime source identity is
        /// `compiled://<source_name>`.
        source_name: String,
        /// Normalized document text (pre-interpolation authoring text).
        document: String,
        /// Canonical manifest JSON (printed verbatim by `--manifest`).
        manifest_json: String,
        /// Parsed artifact arguments.
        args: ArtifactArgs,
    },
    /// v2 multi-document virtual-store artifact (multidoc Task 2.2).
    VirtualStore {
        /// Embedded artifact kind (route/job).
        kind: TrailerKind,
        /// Decoded virtual-document store; the entry point is
        /// `store.index.entry_point` and every document is read through
        /// the store, never the filesystem.
        store: super::store::VirtualDocumentStore,
        /// Canonical manifest JSON (printed verbatim by `--manifest`).
        manifest_json: String,
        /// Parsed artifact arguments.
        args: ArtifactArgs,
    },
}

impl EmbeddedRequest {
    /// Build the request from a decoded v1 trailer and parsed
    /// arguments. Both payload and manifest are validated UTF-8 (the
    /// encoder normalized the document and serialized the manifest as
    /// canonical UTF-8 JSON); the manifest must carry its
    /// `source_name`.
    pub fn from_trailer(trailer: Trailer, args: ArtifactArgs) -> Result<Self, CompileError> {
        let document = String::from_utf8(trailer.payload).map_err(|_| CompileError::InvalidUtf8)?;
        let manifest_json =
            String::from_utf8(trailer.manifest).map_err(|_| CompileError::InvalidUtf8)?;
        let source_name = serde_json::from_str::<serde_json::Value>(&manifest_json)
            .ok()
            .and_then(|value| {
                value
                    .get("source_name")
                    .and_then(|name| name.as_str())
                    .map(str::to_string)
            })
            .ok_or_else(|| {
                CompileError::InvalidDocument("manifest carries no source_name".to_string())
            })?;
        Ok(Self::SingleDocument {
            kind: trailer.kind,
            source_name,
            document,
            manifest_json,
            args,
        })
    }

    /// Build the request from a decoded v2 multi-document trailer and
    /// parsed arguments (multidoc Task 2.2). `decode_artifact` already
    /// verified the checksums, the store index, the typed references,
    /// and the manifest/store agreement; the store decodes again here
    /// and the typed reference invariants re-check — defense in depth
    /// so a hand-routed `TrailerV2` fails by name too, before boot.
    pub fn from_v2(v2: trailer::TrailerV2, args: ArtifactArgs) -> Result<Self, CompileError> {
        let store = super::store::VirtualDocumentStore::decode(v2.content, &v2.index)
            .map_err(|e| CompileError::InvalidDocument(format!("invalid virtual store: {e}")))?;
        super::store::validate_typed_references(&store.index, v2.kind)
            .map_err(|e| CompileError::InvalidDocument(format!("invalid virtual store: {e}")))?;
        let manifest_json =
            String::from_utf8(v2.manifest).map_err(|_| CompileError::InvalidUtf8)?;
        Ok(Self::VirtualStore {
            kind: v2.kind,
            store,
            manifest_json,
            args,
        })
    }
}

/// Run one validated embedded request; the process termination seam for
/// the binary self-detect path (Task 2.3 wires this into `main`).
pub async fn run_embedded_document(request: EmbeddedRequest) -> ExitCode {
    ExitCode::from(run_embedded_document_code(request).await as u8)
}

/// Self-detect a compiled artifact before any CLI parsing (Task 2.3).
///
/// Probes `current_exe()` and decodes its trailer (version-aware:
/// [`trailer::decode_artifact`]):
///
/// - absent trailer (no exact terminal magic; also an unreadable or
///   missing executable image) → `None`: the caller falls through to the
///   normal Clap CLI unchanged, because absence is indistinguishable
///   from an ordinary executable;
/// - marked corruption (terminal magic present but fields, bounds, or
///   checksum invalid) → fail closed: an integrity diagnostic on stderr
///   and exit 2, never a fall-through;
/// - valid trailer → the artifact argv (`std::args` minus the program
///   name) is parsed with [`ArtifactArgs::parse`] (misuse exits 2 naming
///   the argument), the payload decodes into an [`EmbeddedRequest`], and
///   the request dispatches through [`run_embedded_document_code`]:
///   `--help`, `--version`, and `--manifest` print and exit 0 without
///   booting.
///
/// Version dispatch (multidoc Task 2.2): a v1 artifact feeds the
/// single-document runtime (default in-memory config, embedded-text
/// discovery); a v2 multi-document artifact feeds the virtual-store
/// runtime — `discover_virtual_store` assembles the merged embedded
/// configuration and the ordered source-plan routes before boot, with
/// the deployment environment as the `${env:}` lookup.
/// `decode_artifact` has already validated the store, its references,
/// and the manifest/store agreement before this point; the request
/// builder re-validates as defense in depth.
pub async fn self_detect_artifact() -> Option<i32> {
    // A missing or unreadable executable image carries no trailer
    // evidence: that is absence, not corruption, so fall through.
    let exe = std::env::current_exe().ok()?;
    let bytes = std::fs::read(exe).ok()?;
    let decoded = match trailer::decode_artifact(&bytes) {
        Ok(Some(decoded)) => decoded,
        Ok(None) => return None,
        Err(e) => {
            eprintln!("compiled artifact integrity error: {e}");
            return Some(EXIT_REJECTION);
        }
    };
    let argv: Vec<String> = std::env::args().skip(1).collect();
    let args = match ArtifactArgs::parse(&argv) {
        Ok(args) => args,
        Err(e) => {
            eprintln!("{e}");
            return Some(EXIT_REJECTION);
        }
    };
    let request = match decoded {
        trailer::DecodedArtifact::V1(v1) => EmbeddedRequest::from_trailer(v1, args),
        trailer::DecodedArtifact::V2(v2) => EmbeddedRequest::from_v2(v2, args),
    };
    match request {
        Ok(request) => Some(run_embedded_document_code(request).await),
        Err(e) => {
            eprintln!("compiled artifact integrity error: {e}");
            Some(EXIT_REJECTION)
        }
    }
}

/// Same dispatch returning the raw process code (0/1/2); the seam for
/// harness children that re-exit with [`std::process::exit`] (an
/// `ExitCode` cannot be read back out).
pub async fn run_embedded_document_code(request: EmbeddedRequest) -> i32 {
    // The exclusive print-and-exit modes are common to both artifact
    // versions and never boot.
    let (help, version, manifest, report) = match &request {
        EmbeddedRequest::SingleDocument { args, .. }
        | EmbeddedRequest::VirtualStore { args, .. } => {
            (args.help, args.version, args.manifest, args.report.clone())
        }
    };
    if help {
        print_artifact_usage();
        return 0;
    }
    if version {
        println!("camel {}", manifest::RUNTIME_VERSION);
        return 0;
    }
    if manifest {
        let manifest_json = match &request {
            EmbeddedRequest::SingleDocument { manifest_json, .. }
            | EmbeddedRequest::VirtualStore { manifest_json, .. } => manifest_json,
        };
        println!("{manifest_json}");
        return 0;
    }
    match request {
        EmbeddedRequest::SingleDocument {
            kind,
            source_name,
            document,
            ..
        } => match kind {
            TrailerKind::Route => {
                run_embedded_route(&source_name, &document, report.as_deref()).await
            }
            TrailerKind::Job => {
                crate::commands::job::run_embedded_job(&source_name, &document, report).await
            }
        },
        EmbeddedRequest::VirtualStore { kind, store, .. } => match kind {
            TrailerKind::Route => run_embedded_store_route(&store, report.as_deref()).await,
            TrailerKind::Job => crate::commands::job::run_embedded_job_store(store, report).await,
        },
    }
}

/// Artifact `--help` text (no boot).
fn print_artifact_usage() {
    println!("camel compiled artifact usage:");
    println!("  --report <path>  write the run report to <path>");
    println!("  --manifest       print the operational manifest and exit");
    println!("  --version        print the runtime version and exit");
    println!("  --help           print this usage and exit");
}

/// Route-artifact lifecycle: default in-memory config, embedded source,
/// `watch = false` — the same boot, route registration, context start,
/// signal, and shutdown path `camel run` drives. Writes the
/// [`RouteReport`] to `report` when given.
///
/// Exit codes: 0 graceful completion; 2 boot/discovery/report-write
/// failure. Pipeline failure (1) stays reserved: a signal-driven route
/// run ends either in graceful completion or a boot-class failure.
async fn run_embedded_route(source_name: &str, document: &str, report: Option<&Path>) -> i32 {
    let config = match crate::commands::run::in_memory_default_config() {
        Ok(config) => config,
        Err(e) => return fail_route(report, e.to_string()),
    };
    let project_root = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
    let spec = LifecycleSpec {
        config,
        project_root,
        discover: Discover::Embedded {
            text: document.to_string(),
            source_name: source_name.to_string(),
            kind: camel_dsl::EmbeddedDocumentKind::Route,
        },
        watch: None,
        trust_note: false,
        idle_note: IDLE_NOTE,
    };
    match crate::commands::run::drive_lifecycle(spec).await {
        Ok(()) => {
            if let Err(e) = write_route_report(report, &RouteReport::completed()) {
                eprintln!("failed to write route report: {e}");
                return EXIT_REJECTION;
            }
            0
        }
        Err(LifecycleFailure::Discovery(e)) => fail_route(report, e.to_string()),
        Err(LifecycleFailure::Boot(e)) => fail_route(report, e.to_string()),
    }
}

/// Pre-boot failure of the shared virtual-store resolution. The two
/// phases fail for disjoint reasons, and the job lifecycle reports them
/// under different labels, so the variant is preserved for the caller.
#[derive(Debug)]
pub(crate) enum VirtualStoreResolveError {
    /// Store validation or source-plan discovery failed.
    Discovery(camel_dsl::DiscoveryError),
    /// The merged configuration failed to deserialize into a
    /// `CamelConfig`.
    Config(config::ConfigError),
}

impl fmt::Display for VirtualStoreResolveError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Discovery(e) => e.fmt(f),
            Self::Config(e) => e.fmt(f),
        }
    }
}

impl std::error::Error for VirtualStoreResolveError {}

/// Shared pre-boot resolution for v2 virtual-store artifacts (multidoc
/// Task 2.2): discovery assembles the merged embedded configuration and
/// the ordered source-plan routes, then the merged TOML tree
/// deserializes into the deployment `CamelConfig` with `${env:}`
/// resolution through `env`. Both steps run strictly BEFORE boot; the
/// caller owns the error reporting and the lifecycle hand-off.
pub(crate) fn resolve_virtual_store(
    store: &super::store::VirtualDocumentStore,
    env: &dyn Fn(&str) -> Option<String>,
) -> Result<
    (
        camel_config::config::CamelConfig,
        Vec<camel_core::RouteDefinition>,
    ),
    VirtualStoreResolveError,
> {
    let discovery = camel_dsl::discover_virtual_store(store, env)
        .map_err(VirtualStoreResolveError::Discovery)?;
    let config = camel_config::config::CamelConfig::from_toml_value_with_env(discovery.config, env)
        .map_err(VirtualStoreResolveError::Config)?;
    Ok((config, discovery.routes))
}

/// Route-artifact lifecycle for a v2 virtual store (multidoc Task 2.2):
/// merged embedded configuration, ordered source-plan routes, `watch =
/// false` — the same boot, route registration, context start, signal,
/// and shutdown path `camel run` drives. Writes the [`RouteReport`] to
/// `report` when given.
///
/// Store validation, configuration assembly, and route discovery run
/// BEFORE boot ([`resolve_virtual_store`]): an unknown schema, invalid
/// reference, malformed range, kind mismatch, or malformed
/// configuration entry exits 2 with a named diagnostic and no boot.
/// Exit codes: 0 graceful completion; 2
/// validation/discovery/config/boot/report-write failure.
async fn run_embedded_store_route(
    store: &super::store::VirtualDocumentStore,
    report: Option<&Path>,
) -> i32 {
    let identity = store.index.entry_point.clone();
    let ambient = |name: &str| std::env::var(name).ok();
    let (config, routes) = match resolve_virtual_store(store, &ambient) {
        Ok(resolved) => resolved,
        Err(e) => {
            eprintln!("compiled://{identity}: {e}");
            return fail_route(report, e.to_string());
        }
    };
    let project_root = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
    let spec = LifecycleSpec {
        config,
        project_root,
        discover: Discover::VirtualStore { routes },
        watch: None,
        trust_note: false,
        idle_note: IDLE_NOTE,
    };
    match crate::commands::run::drive_lifecycle(spec).await {
        Ok(()) => {
            if let Err(e) = write_route_report(report, &RouteReport::completed()) {
                eprintln!("failed to write route report: {e}");
                return EXIT_REJECTION;
            }
            0
        }
        Err(LifecycleFailure::Discovery(e)) => fail_route(report, e.to_string()),
        Err(LifecycleFailure::Boot(e)) => fail_route(report, e.to_string()),
    }
}

/// Record a failed run: write the failed report (best effort) and return
/// the boot-failure exit code.
fn fail_route(report: Option<&Path>, error: String) -> i32 {
    if let Err(e) = write_route_report(report, &RouteReport::failed(error.clone())) {
        eprintln!("failed to write route report: {e}");
    }
    EXIT_REJECTION
}

/// Write the report JSON (with trailing newline) when a path was given.
fn write_route_report(report: Option<&Path>, value: &RouteReport) -> std::io::Result<()> {
    match report {
        Some(path) => std::fs::write(path, format!("{}\n", value.to_json())),
        None => Ok(()),
    }
}

#[cfg(test)]
mod tests {
    use super::{ArtifactArgError, ArtifactArgs, RouteReport, TrailerKind};

    fn argv(args: &[&str]) -> Vec<String> {
        args.iter().map(|s| s.to_string()).collect()
    }

    /// The four accepted forms parse into their flags.
    #[test]
    fn artifact_args_accept_the_documented_surface() {
        let args = ArtifactArgs::parse(&argv(&["--report", "out.json"])).expect("report parses");
        assert_eq!(args.report, Some(std::path::PathBuf::from("out.json")));
        assert!(ArtifactArgs::parse(&argv(&["--help"])).expect("help").help);
        assert!(
            ArtifactArgs::parse(&argv(&["--version"]))
                .expect("version")
                .version
        );
        assert!(
            ArtifactArgs::parse(&argv(&["--manifest"]))
                .expect("manifest")
                .manifest
        );
        assert!(
            ArtifactArgs::parse(&argv(&[]))
                .expect("bare run")
                .report
                .is_none()
        );
    }

    /// Duplicate, missing-value, exclusive, unknown, and positional forms
    /// are rejected with the argument named.
    #[test]
    fn artifact_args_reject_misuse() {
        assert_eq!(
            ArtifactArgs::parse(&argv(&["--report", "a", "--report", "b"])),
            Err(ArtifactArgError::Duplicate("--report"))
        );
        assert_eq!(
            ArtifactArgs::parse(&argv(&["--report"])),
            Err(ArtifactArgError::MissingValue("--report"))
        );
        assert_eq!(
            ArtifactArgs::parse(&argv(&["--report", "--manifest"])),
            Err(ArtifactArgError::MissingValue("--report"))
        );
        assert_eq!(
            ArtifactArgs::parse(&argv(&["--help", "--version"])),
            Err(ArtifactArgError::Exclusive("--help", "--version"))
        );
        assert_eq!(
            ArtifactArgs::parse(&argv(&["--report", "r", "--manifest"])),
            Err(ArtifactArgError::Exclusive("--report", "--manifest"))
        );
        assert_eq!(
            ArtifactArgs::parse(&argv(&["--watch"])),
            Err(ArtifactArgError::Unknown("--watch".to_string()))
        );
        assert_eq!(
            ArtifactArgs::parse(&argv(&["routes.yaml"])),
            Err(ArtifactArgError::Positional("routes.yaml".to_string()))
        );
    }

    /// The route report serializes to the exact documented JSON object.
    #[test]
    fn route_report_serializes_exact_json() {
        assert_eq!(
            RouteReport::completed().to_json(),
            r#"{"kind":"route","status":"completed","error":null}"#
        );
        assert_eq!(
            RouteReport::failed("boom".to_string()).to_json(),
            r#"{"kind":"route","status":"failed","error":"boom"}"#
        );
    }

    /// `from_v2` decodes the store and re-validates the typed reference
    /// invariants as defense in depth: a hand-constructed store whose
    /// entry point kind disagrees with the artifact kind fails by name
    /// (multidoc Task 2.2 — the runtime-level rejection is pinned by
    /// `compiled_runtime_rejects_invalid_store_before_boot`, which
    /// replaced the interim fail-closed bridge test).
    #[test]
    fn from_v2_rejects_kind_mismatched_stores() {
        use super::super::store::{StoreDocument, StoreEntryKind};

        let route_doc = |path: &str| StoreDocument {
            path: path.to_string(),
            kind: StoreEntryKind::Route,
            bytes: b"routes:\n  - id: demo\n".to_vec(),
        };
        let job_doc = |path: &str| StoreDocument {
            path: path.to_string(),
            kind: StoreEntryKind::Job,
            bytes: b"execute:\n  mode: one-shot\n".to_vec(),
        };
        let v2 = |store: &super::super::store::VirtualDocumentStore| {
            use super::super::trailer::TrailerV2;
            TrailerV2 {
                kind: TrailerKind::Route,
                content: store.content.clone(),
                index: store.index.encode_canonical().expect("canonical index"),
                manifest: br#"{"manifest_schema":2,"source_name":"app.yaml"}"#.to_vec(),
            }
        };

        // Kind agreement: a route artifact over a route entry point
        // builds the virtual-store request.
        let route_store = super::super::store::VirtualDocumentStore::build(
            "app.yaml",
            &[route_doc("app.yaml")],
            &[],
            &["app.yaml".to_string()],
        )
        .expect("route store builds");
        let request = super::EmbeddedRequest::from_v2(v2(&route_store), Default::default())
            .expect("kind-agreeing store builds a request");
        assert!(matches!(
            request,
            super::EmbeddedRequest::VirtualStore { .. }
        ));

        // Kind mismatch: a route artifact over a job entry point fails
        // by name before any boot.
        let job_store = super::super::store::VirtualDocumentStore::build(
            "ingest.job.yaml",
            &[job_doc("ingest.job.yaml")],
            &[],
            &["ingest.job.yaml".to_string()],
        )
        .expect("job store builds");
        let err = super::EmbeddedRequest::from_v2(v2(&job_store), Default::default())
            .expect_err("kind-mismatched store must fail closed");
        assert!(
            err.to_string().contains("expected route"),
            "the rejection must name the kind mismatch: {err}"
        );
    }
}