Skip to main content

proa_cli/
lifecycle.rs

1// Copyright Proa Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4use std::{
5    collections::{BTreeMap, BTreeSet},
6    env,
7    ffi::{OsStr, OsString},
8    fs, io,
9    path::{Path, PathBuf},
10    process::{Child, Command, ExitStatus},
11    sync::atomic::{AtomicBool, AtomicU64, Ordering},
12    thread,
13    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
14};
15
16use anyhow::{bail, Context, Result};
17use rsjs_ir::{
18    abi::{AbiVersion, ProducerVersion, SemanticHash},
19    build::{
20        ArtifactRole, BuildToolchain, DeclaredEnvironmentInput, InvocationSpec, RequestedRootTarget,
21    },
22};
23use rsjs_transport::TRANSPORT_FORMAT_VERSION;
24use serde::Deserialize;
25use sha2::{Digest, Sha256};
26
27mod reload;
28
29use reload::{ReloadEvent, ReloadServer};
30
31#[cfg(not(windows))]
32use crate::rsjs::final_compile::snapshot_wrapper_executable;
33use crate::{
34    commands::{db, task},
35    config::{load_project_config, AssetConfig, ProjectConfig},
36    diagnostic::Severity,
37    rsjs::build::{
38        DescriptorCargoRequest, DESCRIPTOR_TARGET_POLICY_VERSION,
39        DESCRIPTOR_UNIT_SIDECAR_SCHEMA_VERSION,
40    },
41    rsjs::cache::DESCRIPTOR_CACHE_SCHEMA_VERSION,
42    rsjs::pipeline::{
43        run_linked_cargo_cached, DescriptorRootSelector, LinkedCargoOutput, LinkedCargoRequest,
44    },
45    scaffold,
46};
47
48static RSJS_BUILD_NONCE: AtomicU64 = AtomicU64::new(0);
49static TEST_INTERRUPTED: AtomicBool = AtomicBool::new(false);
50const RSJS_COMPILER_ABI: AbiVersion = AbiVersion::new(1, 1);
51const RSJS_RUNTIME_PROTOCOL: AbiVersion = AbiVersion::new(1, 0);
52const RSJS_COMPILER_PRODUCER: ProducerVersion = ProducerVersion::new(0, 2, 0);
53const RSJS_WRAPPER_EXECUTABLE_FINGERPRINT_DOMAIN: &[u8] = b"proa.rsjs.wrapper-executable.v1\0";
54const PERSISTENT_DESCRIPTOR_TARGET_LAYOUT_VERSION: u16 = 1;
55const DEV_WATCH_POLL: Duration = Duration::from_millis(100);
56/// Editors write in bursts (temp file, rename, mtime touch) and formatters
57/// rewrite whole trees, so the loop waits for one quiet window before paying
58/// for a Cargo cycle. Vite and webpack sit in the same 100-300ms range.
59pub const DEV_WATCH_DEBOUNCE: Duration = Duration::from_millis(300);
60/// Refuse debounce windows shorter than one poll interval: they would claim a
61/// precision the poller cannot deliver.
62const DEV_WATCH_MIN_DEBOUNCE: Duration = DEV_WATCH_POLL;
63/// How long a restarted server gets to accept connections before tabs are
64/// told to reload anyway.
65const DEV_READY_TIMEOUT: Duration = Duration::from_secs(20);
66
67pub struct DevOptions {
68    pub root: Option<PathBuf>,
69    pub host: Option<String>,
70    pub port: Option<u16>,
71    pub offline: bool,
72    pub no_assets: bool,
73    pub no_restart: bool,
74    pub no_reload: bool,
75    pub no_css_hot_swap: bool,
76    pub reload_port: Option<u16>,
77    pub debounce_ms: Option<u64>,
78    pub command: Vec<String>,
79}
80
81pub struct BuildOptions {
82    pub root: Option<PathBuf>,
83    pub profile: Option<String>,
84    pub package: Option<String>,
85    pub bin: Option<String>,
86    pub example: Option<String>,
87    pub target: Option<String>,
88    pub features: Vec<String>,
89    pub all_features: bool,
90    pub no_default_features: bool,
91    pub locked: bool,
92    pub offline: bool,
93    pub no_check: bool,
94    pub no_assets: bool,
95    pub artifact_out: Option<PathBuf>,
96    pub command: Vec<String>,
97}
98
99pub struct CheckOptions {
100    pub root: Option<PathBuf>,
101    pub profile: Option<String>,
102    pub package: Option<String>,
103    pub bin: Option<String>,
104    pub target: Option<String>,
105    pub features: Vec<String>,
106    pub all_features: bool,
107    pub no_default_features: bool,
108    pub locked: bool,
109    pub offline: bool,
110}
111
112pub struct RunOptions {
113    pub root: Option<PathBuf>,
114    pub profile: Option<String>,
115    pub package: Option<String>,
116    pub bin: Option<String>,
117    pub target: Option<String>,
118    pub features: Vec<String>,
119    pub all_features: bool,
120    pub no_default_features: bool,
121    pub locked: bool,
122    pub offline: bool,
123    pub arguments: Vec<String>,
124}
125
126#[derive(Clone)]
127pub struct TestOptions {
128    pub root: Option<PathBuf>,
129    pub profile: Option<String>,
130    pub package: Option<String>,
131    pub bin: Option<String>,
132    pub test: Option<String>,
133    pub target: Option<String>,
134    pub features: Vec<String>,
135    pub all_features: bool,
136    pub no_default_features: bool,
137    pub locked: bool,
138    pub offline: bool,
139    pub watch: bool,
140    pub keep_database: bool,
141    pub arguments: Vec<String>,
142}
143
144#[derive(Debug)]
145struct LinkedDevLaunch {
146    executable: PathBuf,
147    arguments: Vec<OsString>,
148    plan_id: String,
149    descriptor_artifacts: usize,
150    reused_descriptor_artifacts: usize,
151    reused_final_artifacts: usize,
152}
153
154pub fn dev(options: DevOptions) -> Result<()> {
155    let root = absolute_project_root(scaffold::resolve_root(options.root.clone())?)?;
156    let config = load_dev_config(&root, &options)?;
157    // Reject an impossible watch window before anything is built, bound, or
158    // spawned. A flag error should cost nothing to recover from.
159    let debounce = dev_watch_debounce(&options)?;
160    install_dev_signal_handler();
161
162    println!("Proa dev root: {}", root.display());
163    println!(
164        "Proa dev URL: http://{}:{}",
165        config.dev.host, config.dev.port
166    );
167    task::run_lifecycle_tasks(&root, &config, &config.dev.before, &BTreeMap::new())?;
168
169    if options.no_restart {
170        if !options.no_assets {
171            build_assets(&root, &config)?;
172        }
173        let launch = run_linked_dev_cycle(&root, &config.dev.command)?;
174        return run_linked_dev_foreground(&root, &launch, &config.dev.host, config.dev.port, None);
175    }
176
177    // Live reload is a watch-mode feature. Without restarts there is nothing
178    // to announce, so a one-shot run never pays for the event server.
179    let reload = start_reload_server(&config, &options);
180    let session = reload
181        .as_ref()
182        .map(|server| (server.port(), server.token().to_string()));
183
184    if !options.no_assets {
185        build_assets(&root, &config)?;
186    }
187    let mut watch_paths = config.dev.watch.clone();
188    let baseline = watch_snapshot(&root, &watch_paths)?;
189    let launch = run_linked_dev_cycle(&root, &config.dev.command)?;
190    let mut child = spawn_linked_dev(
191        &root,
192        &launch,
193        &config.dev.host,
194        config.dev.port,
195        session.as_ref(),
196    )?;
197    set_active_child_group(&child);
198
199    let clock = Instant::now();
200    let mut debouncer = DevWatchDebouncer::new(baseline, debounce);
201
202    loop {
203        if let Some(status) = child.try_wait().context("poll linked dev server")? {
204            clear_active_child_group();
205            return exit_status_to_result(status, "linked dev server");
206        }
207
208        thread::sleep(DEV_WATCH_POLL);
209        let current = watch_snapshot(&root, &watch_paths)?;
210        let DevWatchDecision::Ready(trigger_snapshot) = debouncer.observe(clock.elapsed(), current)
211        else {
212            continue;
213        };
214
215        // A stylesheet edit changes no compiled input, so rebuilding assets
216        // and letting tabs re-fetch their stylesheets is both faster than a
217        // Cargo cycle and less destructive: scroll position, form state, and
218        // open dialogs all survive. This is Vite's CSS update path.
219        let changed = changed_paths(&debouncer.committed, &trigger_snapshot);
220        if !options.no_css_hot_swap && !options.no_assets && is_stylesheet_only_change(&changed) {
221            println!("stylesheet change stabilized; rebuilding assets without restarting");
222            notify(reload.as_ref(), &ReloadEvent::Building);
223            let assets = (|| -> Result<ProjectConfig> {
224                let next_config = load_dev_config(&root, &options)?;
225                task::run_lifecycle_tasks(
226                    &root,
227                    &next_config,
228                    &next_config.dev.before,
229                    &BTreeMap::new(),
230                )?;
231                build_assets(&root, &next_config)?;
232                Ok(next_config)
233            })();
234            match assets {
235                Ok(next_config) => {
236                    watch_paths = next_config.dev.watch.clone();
237                    // Commit the state that triggered this cycle, not one read
238                    // after the asset command finished. A stylesheet saved
239                    // while Tailwind was running would otherwise be folded in
240                    // as already handled and never rebuilt.
241                    debouncer.commit(trigger_snapshot);
242                    notify(reload.as_ref(), &ReloadEvent::Css);
243                }
244                Err(error) => {
245                    eprintln!("asset rebuild failed; keeping the last built assets:\n{error:#}");
246                    notify(reload.as_ref(), &ReloadEvent::Failed(format!("{error:#}")));
247                    debouncer.commit(trigger_snapshot);
248                }
249            }
250            continue;
251        }
252
253        println!("change stabilized; rebuilding linked RSJS dev server");
254        notify(reload.as_ref(), &ReloadEvent::Building);
255        let rebuild =
256            (|| -> Result<(ProjectConfig, Vec<PathBuf>, WatchSnapshot, LinkedDevLaunch)> {
257                let next_config = load_dev_config(&root, &options)?;
258                task::run_lifecycle_tasks(
259                    &root,
260                    &next_config,
261                    &next_config.dev.before,
262                    &BTreeMap::new(),
263                )?;
264                if !options.no_assets {
265                    build_assets(&root, &next_config)?;
266                }
267                let next_watch_paths = next_config.dev.watch.clone();
268                // Capture the exact source/config state handed to this cycle after
269                // asset generation. A change during Cargo will differ on the next
270                // poll and schedule another cycle rather than being swallowed.
271                let cycle_snapshot = watch_snapshot(&root, &next_watch_paths)?;
272                let launch = run_linked_dev_cycle(&root, &next_config.dev.command)?;
273                Ok((next_config, next_watch_paths, cycle_snapshot, launch))
274            })();
275
276        match rebuild {
277            Ok((next_config, next_watch_paths, cycle_snapshot, next_launch)) => {
278                println!(
279                    "linked dev rebuild succeeded; gracefully stopping the previous server before activating plan {}",
280                    next_launch.plan_id
281                );
282                stop_child(&mut child)?;
283                clear_active_child_group();
284                child = spawn_linked_dev(
285                    &root,
286                    &next_launch,
287                    &next_config.dev.host,
288                    next_config.dev.port,
289                    session.as_ref(),
290                )?;
291                set_active_child_group(&child);
292                watch_paths = next_watch_paths;
293                debouncer = DevWatchDebouncer::new(cycle_snapshot, debounce);
294                announce_reload(
295                    reload.as_ref(),
296                    &next_config.dev.host,
297                    next_config.dev.port,
298                    &mut child,
299                );
300            }
301            Err(error) => {
302                eprintln!(
303                    "linked dev rebuild failed; keeping the last valid server running:\n{error:#}"
304                );
305                notify(reload.as_ref(), &ReloadEvent::Failed(format!("{error:#}")));
306                // Do not spin on unchanged broken input. The next source,
307                // feature, cfg, or configuration change schedules a new cycle.
308                debouncer.commit(trigger_snapshot);
309            }
310        }
311    }
312}
313
314fn start_reload_server(config: &ProjectConfig, options: &DevOptions) -> Option<ReloadServer> {
315    if options.no_reload {
316        println!("Proa dev live reload: off");
317        return None;
318    }
319
320    // Zero asks the operating system for a free port. A fixed offset from the
321    // dev port would quietly claim the port the developer's next site wants,
322    // and that site would then fail to bind with an error naming neither live
323    // reload nor the process holding it. Tabs do not need the port to be
324    // stable: one whose stream endpoint has moved reloads itself and picks up
325    // the current one from the page.
326    let requested = options.reload_port.unwrap_or_default();
327    if requested != 0 && requested == config.dev.port {
328        eprintln!(
329            "Proa dev live reload: off (--reload-port {requested} is the port the site itself uses)"
330        );
331        return None;
332    }
333    match ReloadServer::bind(&config.dev.host, requested) {
334        Ok(server) => {
335            println!("Proa dev live reload: on (port {})", server.port());
336            Some(server)
337        }
338        Err(error) => {
339            // A dev loop that still rebuilds is far more useful than one that
340            // refuses to start because a port was unavailable.
341            eprintln!("Proa dev live reload: off ({error:#})");
342            None
343        }
344    }
345}
346
347fn dev_watch_debounce(options: &DevOptions) -> Result<Duration> {
348    let Some(requested) = options.debounce_ms else {
349        return Ok(DEV_WATCH_DEBOUNCE);
350    };
351    let requested = Duration::from_millis(requested);
352    if requested < DEV_WATCH_MIN_DEBOUNCE {
353        bail!(
354            "`--debounce-ms {}` is below the {}ms file-watch poll interval; use {}ms or more",
355            requested.as_millis(),
356            DEV_WATCH_POLL.as_millis(),
357            DEV_WATCH_MIN_DEBOUNCE.as_millis()
358        );
359    }
360    Ok(requested)
361}
362
363fn notify(reload: Option<&ReloadServer>, event: &ReloadEvent) {
364    if let Some(reload) = reload {
365        reload.broadcast(event);
366    }
367}
368
369/// Tell tabs to reload, preferably once the replacement server answers.
370///
371/// Reloading into a connection-refused error page is the failure mode that
372/// makes naive live reload feel broken, so readiness is confirmed first.
373fn announce_reload(reload: Option<&ReloadServer>, host: &str, port: u16, child: &mut Child) {
374    let Some(reload) = reload else { return };
375
376    let mut still_running = || !matches!(child.try_wait(), Ok(Some(_)));
377    if reload::wait_until_serving(host, port, DEV_READY_TIMEOUT, &mut still_running) {
378        reload.broadcast(&ReloadEvent::Reload);
379        return;
380    }
381
382    // A server that exits on boot is a result the developer needs to see.
383    if let Ok(Some(status)) = child.try_wait() {
384        let detail = format!("the rebuilt server exited with {status}");
385        eprintln!("live reload: {detail}");
386        reload.broadcast(&ReloadEvent::Failed(detail));
387        return;
388    }
389
390    // The process is alive but the probe never connected. The build did
391    // succeed, so this is far more likely to be a readiness check looking at
392    // the wrong address than a broken server, and refusing to reload would
393    // leave a stale page with no explanation. Reload and say what happened.
394    eprintln!(
395        "live reload: {host}:{port} did not accept a connection within {}s; reloading anyway",
396        DEV_READY_TIMEOUT.as_secs()
397    );
398    reload.broadcast(&ReloadEvent::Reload);
399}
400
401/// Paths whose stamp differs between two snapshots, including deletions.
402fn changed_paths(before: &WatchSnapshot, after: &WatchSnapshot) -> Vec<PathBuf> {
403    let mut changed: Vec<PathBuf> = after
404        .iter()
405        .filter(|(path, stamp)| before.get(*path) != Some(*stamp))
406        .map(|(path, _)| path.clone())
407        .collect();
408    changed.extend(
409        before
410            .keys()
411            .filter(|path| !after.contains_key(*path))
412            .cloned(),
413    );
414    changed
415}
416
417/// Whether a change set can be served by rebuilding assets alone.
418///
419/// Only stylesheets qualify. Anything else, including a Tailwind class edited
420/// inside a Rust template, changes a compiled input and needs a real rebuild.
421fn is_stylesheet_only_change(changed: &[PathBuf]) -> bool {
422    !changed.is_empty()
423        && changed.iter().all(|path| {
424            path.extension()
425                .and_then(OsStr::to_str)
426                .is_some_and(|extension| extension.eq_ignore_ascii_case("css"))
427        })
428}
429
430fn load_dev_config(root: &Path, options: &DevOptions) -> Result<ProjectConfig> {
431    let mut config = load_project_config(root)?;
432    apply_dev_overrides(&mut config, options);
433    Ok(config)
434}
435
436// The exact final server runs in its own process group so restarts can stop
437// its whole subprocess tree. That also detaches it from the terminal's
438// foreground group, so Ctrl-C / SIGTERM on `proa dev` must be forwarded to
439// the child group by hand or the server would outlive the CLI and keep the
440// port bound.
441#[cfg(unix)]
442static ACTIVE_CHILD_GROUP: std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(0);
443
444fn set_active_child_group(child: &Child) {
445    #[cfg(unix)]
446    ACTIVE_CHILD_GROUP.store(child.id() as i32, std::sync::atomic::Ordering::SeqCst);
447    #[cfg(not(unix))]
448    let _ = child;
449}
450
451fn clear_active_child_group() {
452    #[cfg(unix)]
453    ACTIVE_CHILD_GROUP.store(0, std::sync::atomic::Ordering::SeqCst);
454}
455
456#[cfg(unix)]
457extern "C" fn dev_signal_handler(signal: libc::c_int) {
458    let pgid = ACTIVE_CHILD_GROUP.load(std::sync::atomic::Ordering::SeqCst);
459    if pgid > 0 {
460        unsafe { libc::kill(-pgid, libc::SIGTERM) };
461    }
462    unsafe { libc::_exit(128 + signal) };
463}
464
465fn install_dev_signal_handler() {
466    #[cfg(unix)]
467    unsafe {
468        libc::signal(
469            libc::SIGINT,
470            dev_signal_handler as extern "C" fn(libc::c_int) as libc::sighandler_t,
471        );
472        libc::signal(
473            libc::SIGTERM,
474            dev_signal_handler as extern "C" fn(libc::c_int) as libc::sighandler_t,
475        );
476    }
477}
478
479pub fn build(options: BuildOptions) -> Result<()> {
480    let root = absolute_project_root(scaffold::resolve_root(options.root.clone())?)?;
481    let config = load_project_config(&root)?;
482    let command = build_command(&config, &options);
483    // Validate and resolve the exact Cargo root before running configured asset
484    // commands. An unsupported deployment command must fail without partially
485    // executing a build.
486    let prepared = prepare_linked_cargo(&root, &command, LinkedCargoAction::Build)?;
487    let artifact_destination = options
488        .artifact_out
489        .as_deref()
490        .map(|destination| resolve_artifact_output(&root, destination));
491    if let Some(destination) = artifact_destination.as_deref() {
492        warn_if_artifact_output_enters_source_closure(
493            destination,
494            &prepared.package_source_root,
495            &prepared.request.descriptor.source_exclusion_directory,
496        );
497    }
498
499    task::run_lifecycle_tasks(&root, &config, &config.build.before, &BTreeMap::new())?;
500    if !options.no_check {
501        run_project_check(&root)?;
502    }
503    if !options.no_assets {
504        build_assets(&root, &config)?;
505    }
506
507    println!("running linked RSJS Cargo build: {}", shellish(&command));
508    let output = run_linked_cargo_cached(&prepared.request, &prepared.descriptor_cache_directory)
509        .context("linked RSJS build failed")?;
510    print_linked_cache_reuse(LinkedCargoAction::Build, &output);
511    print_linked_cargo_output(LinkedCargoAction::Build, &prepared.request, &output);
512    if let Some(destination) = artifact_destination.as_deref() {
513        let source =
514            select_final_root_executable(&prepared.request, &output, LinkedCargoAction::Build)?;
515        copy_executable_atomically(&source, destination).with_context(|| {
516            format!(
517                "failed to export linked executable `{}` to `{}`",
518                source.display(),
519                destination.display()
520            )
521        })?;
522        println!(
523            "exported linked RSJS executable to {}",
524            destination.display()
525        );
526    }
527    Ok(())
528}
529
530pub fn check(mut options: CheckOptions) -> Result<()> {
531    let root = absolute_project_root(scaffold::resolve_root(options.root.clone())?)?;
532    if options.bin.is_none() {
533        let config = load_project_config(&root)?;
534        options.bin = config
535            .application
536            .as_ref()
537            .and_then(|application| application.get("binary"))
538            .and_then(serde_json::Value::as_str)
539            .map(ToString::to_string);
540    }
541    let command = check_command(&options);
542    let prepared = prepare_linked_cargo(&root, &command, LinkedCargoAction::Check)?;
543
544    println!("running linked RSJS Cargo check: {}", shellish(&command));
545    let output = run_linked_cargo_cached(&prepared.request, &prepared.descriptor_cache_directory)
546        .context("linked RSJS check failed")?;
547    print_linked_cache_reuse(LinkedCargoAction::Check, &output);
548    print_linked_cargo_output(LinkedCargoAction::Check, &prepared.request, &output);
549    Ok(())
550}
551
552pub fn run(options: RunOptions) -> Result<()> {
553    let root = absolute_project_root(scaffold::resolve_root(options.root.clone())?)?;
554    let command = run_command(&options);
555    run_linked_execute(&root, &command, LinkedCargoAction::Run)
556}
557
558pub fn test(mut options: TestOptions) -> Result<()> {
559    install_test_signal_handler();
560    TEST_INTERRUPTED.store(false, Ordering::SeqCst);
561    if options.bin.is_some() && options.test.is_some() {
562        bail!(
563            "`cargo proa test` requires exactly one target selector: use either `--bin <name>` or `--test <name>`"
564        );
565    }
566    let root = absolute_project_root(scaffold::resolve_root(options.root.clone())?)?;
567    let explicit_target = options.bin.is_some() || options.test.is_some();
568    if options.bin.is_none() && options.test.is_none() {
569        let config = load_project_config(&root)?;
570        options.bin = config
571            .application
572            .as_ref()
573            .and_then(|application| application.get("binary"))
574            .and_then(serde_json::Value::as_str)
575            .map(ToString::to_string);
576        if options.bin.is_none() {
577            bail!(
578                "`cargo proa test` requires exactly one target selector: use either `--bin <name>` or `--test <name>`"
579            );
580        }
581    }
582    let mut commands = vec![test_command(&options)];
583    if !explicit_target {
584        let prepared = prepare_linked_cargo(&root, &commands[0], LinkedCargoAction::Test)?;
585        for test in discover_integration_test_targets(&prepared.package_source_root)? {
586            let mut integration = options.clone();
587            integration.bin = None;
588            integration.test = Some(test);
589            commands.push(test_command(&integration));
590        }
591    }
592    let config = load_project_config(&root)?;
593    if options.watch {
594        run_watched_tests(&root, &config, &commands, options.keep_database)
595    } else {
596        run_test_session(&root, &config, &commands, options.keep_database)
597    }
598}
599
600fn discover_integration_test_targets(package_source_root: &Path) -> Result<Vec<String>> {
601    let directory = package_source_root.join("tests");
602    let entries = match fs::read_dir(&directory) {
603        Ok(entries) => entries,
604        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
605        Err(error) => return Err(error).with_context(|| format!("read {}", directory.display())),
606    };
607    let mut targets = Vec::new();
608    for entry in entries {
609        let entry = entry?;
610        let path = entry.path();
611        let is_rust_file = path.is_file() && path.extension() == Some(OsStr::new("rs"));
612        let is_directory_target = path.is_dir() && path.join("main.rs").is_file();
613        if !is_rust_file && !is_directory_target {
614            continue;
615        }
616        let name = path
617            .file_stem()
618            .and_then(OsStr::to_str)
619            .context("integration-test target names must be UTF-8")?;
620        targets.push(name.to_string());
621    }
622    targets.sort();
623    Ok(targets)
624}
625
626#[derive(Debug)]
627struct IsolatedTestDatabase {
628    run_directory: PathBuf,
629    path: PathBuf,
630}
631
632impl IsolatedTestDatabase {
633    fn create(root: &Path) -> Result<Self> {
634        let run_directory = root.join("target/proa-tests").join(fresh_build_nonce());
635        fs::create_dir_all(&run_directory)
636            .with_context(|| format!("create {}", run_directory.display()))?;
637        let database = Self {
638            path: run_directory.join("test.db"),
639            run_directory,
640        };
641        if let Err(error) = db::prepare_test_database(root, &database.path) {
642            let _ = db::remove_test_database(&database.path);
643            let _ = fs::remove_dir(&database.run_directory);
644            return Err(error).context("prepare isolated test database");
645        }
646        println!("Test database  {}", database.path.display());
647        Ok(database)
648    }
649
650    fn url(&self) -> OsString {
651        OsString::from(format!("sqlite://{}", self.path.display()))
652    }
653
654    fn reset(&self, root: &Path) -> Result<()> {
655        db::remove_test_database(&self.path)?;
656        db::prepare_test_database(root, &self.path)
657    }
658
659    fn cleanup(&self) -> Result<()> {
660        db::remove_test_database(&self.path)?;
661        match fs::remove_dir(&self.run_directory) {
662            Ok(()) => Ok(()),
663            Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
664            Err(error) => {
665                Err(error).with_context(|| format!("remove {}", self.run_directory.display()))
666            }
667        }
668    }
669}
670
671fn project_uses_sqlite(config: &ProjectConfig) -> bool {
672    config
673        .database
674        .as_ref()
675        .and_then(|database| database.get("driver"))
676        .and_then(serde_json::Value::as_str)
677        == Some("sqlite")
678}
679
680fn run_test_session(
681    root: &Path,
682    config: &ProjectConfig,
683    commands: &[Vec<String>],
684    keep_database: bool,
685) -> Result<()> {
686    let database = project_uses_sqlite(config)
687        .then(|| IsolatedTestDatabase::create(root))
688        .transpose()?;
689    if database.is_none() && keep_database {
690        eprintln!("No SQLite capability is configured; --keep-database is a no-op.");
691    }
692    let result = (|| {
693        let environment = test_environment(root, database.as_ref())?;
694        run_test_cycle(root, config, commands, &environment)
695    })();
696    finish_test_database(database.as_ref(), keep_database && result.is_err())?;
697    result
698}
699
700fn run_watched_tests(
701    root: &Path,
702    config: &ProjectConfig,
703    commands: &[Vec<String>],
704    keep_database: bool,
705) -> Result<()> {
706    let database = project_uses_sqlite(config)
707        .then(|| IsolatedTestDatabase::create(root))
708        .transpose()?;
709    if database.is_none() && keep_database {
710        eprintln!("No SQLite capability is configured; --keep-database is a no-op.");
711    }
712    let result = watched_test_loop(root, config, commands, database.as_ref());
713    let preserve = keep_database
714        && match &result {
715            Ok(last_failed) => *last_failed,
716            Err(_) => true,
717        };
718    finish_test_database(database.as_ref(), preserve)?;
719    result.map(|_| ())
720}
721
722fn watched_test_loop(
723    root: &Path,
724    config: &ProjectConfig,
725    commands: &[Vec<String>],
726    database: Option<&IsolatedTestDatabase>,
727) -> Result<bool> {
728    let mut paths = config.dev.watch.clone();
729    let migrations = config
730        .database
731        .as_ref()
732        .and_then(|database| database.get("migrations"))
733        .and_then(serde_json::Value::as_str)
734        .map(PathBuf::from)
735        .unwrap_or_else(|| PathBuf::from("migrations"));
736    if !paths.contains(&migrations) {
737        paths.push(migrations.clone());
738    }
739    for path in [PathBuf::from(".env"), PathBuf::from(".env.test")] {
740        if !paths.contains(&path) {
741            paths.push(path);
742        }
743    }
744    let mut baseline = watch_snapshot(root, &paths)?;
745    let mut last_failed;
746
747    loop {
748        let environment = test_environment(root, database)?;
749        match run_test_cycle(root, config, commands, &environment) {
750            Ok(()) => last_failed = false,
751            Err(error) => {
752                last_failed = true;
753                eprintln!("test run failed; watching for changes:\n{error:#}");
754            }
755        }
756        if TEST_INTERRUPTED.load(Ordering::SeqCst) {
757            break;
758        }
759        println!("Watching for test input changes · press Ctrl-C to stop");
760        let changed = loop {
761            thread::sleep(Duration::from_millis(200));
762            if TEST_INTERRUPTED.load(Ordering::SeqCst) {
763                break Vec::new();
764            }
765            let snapshot = watch_snapshot(root, &paths)?;
766            let changed = changed_paths(&baseline, &snapshot);
767            if !changed.is_empty() {
768                thread::sleep(DEV_WATCH_DEBOUNCE);
769                baseline = watch_snapshot(root, &paths)?;
770                break changed;
771            }
772        };
773        if TEST_INTERRUPTED.load(Ordering::SeqCst) {
774            break;
775        }
776        if changed.iter().any(|path| {
777            path.strip_prefix(root)
778                .unwrap_or(path)
779                .starts_with(&migrations)
780        }) {
781            if let Some(database) = &database {
782                database.reset(root)?;
783                println!("Test database reset after migration change");
784            }
785        }
786    }
787    Ok(last_failed)
788}
789
790fn run_test_cycle(
791    root: &Path,
792    config: &ProjectConfig,
793    commands: &[Vec<String>],
794    environment: &BTreeMap<OsString, OsString>,
795) -> Result<()> {
796    if TEST_INTERRUPTED.load(Ordering::SeqCst) {
797        bail!("test interrupted");
798    }
799    let before = config
800        .test
801        .as_ref()
802        .and_then(|test| test.get("before"))
803        .and_then(serde_json::Value::as_array)
804        .map(|tasks| {
805            tasks
806                .iter()
807                .map(|task| {
808                    task.as_str()
809                        .map(ToString::to_string)
810                        .context("test.before entries must be task names")
811                })
812                .collect::<Result<Vec<_>>>()
813        })
814        .transpose()?
815        .unwrap_or_default();
816    task::run_lifecycle_tasks(root, config, &before, environment)?;
817    for command in commands {
818        run_linked_execute_with_environment(root, command, LinkedCargoAction::Test, environment)?;
819    }
820    Ok(())
821}
822
823fn finish_test_database(database: Option<&IsolatedTestDatabase>, preserve: bool) -> Result<()> {
824    let Some(database) = database else {
825        return Ok(());
826    };
827    if preserve {
828        println!(
829            "Preserved failing test database at {}",
830            database.path.display()
831        );
832        Ok(())
833    } else {
834        database.cleanup()
835    }
836}
837
838fn test_environment(
839    root: &Path,
840    database: Option<&IsolatedTestDatabase>,
841) -> Result<BTreeMap<OsString, OsString>> {
842    let mut loaded = BTreeMap::<String, String>::new();
843    merge_test_env_file(&root.join(".env"), &mut loaded)?;
844    merge_test_env_file(&root.join(".env.test"), &mut loaded)?;
845    let mut environment = loaded
846        .into_iter()
847        .filter(|(name, _)| env::var_os(name).is_none())
848        .map(|(name, value)| (OsString::from(name), OsString::from(value)))
849        .collect::<BTreeMap<_, _>>();
850    if let Some(database) = database {
851        environment.insert(OsString::from("DATABASE_URL"), database.url());
852    }
853    Ok(environment)
854}
855
856fn merge_test_env_file(path: &Path, values: &mut BTreeMap<String, String>) -> Result<()> {
857    let source = match fs::read_to_string(path) {
858        Ok(source) => source,
859        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),
860        Err(error) => return Err(error).with_context(|| format!("read {}", path.display())),
861    };
862    for (index, line) in source.lines().enumerate() {
863        let line = line.trim();
864        if line.is_empty() || line.starts_with('#') {
865            continue;
866        }
867        let line = line.strip_prefix("export ").unwrap_or(line);
868        let (name, value) = line.split_once('=').with_context(|| {
869            format!("{}:{} is not a NAME=value entry", path.display(), index + 1)
870        })?;
871        let name = name.trim();
872        if name.is_empty()
873            || !name.bytes().enumerate().all(|(index, byte)| {
874                byte == b'_' || byte.is_ascii_alphabetic() || index > 0 && byte.is_ascii_digit()
875            })
876        {
877            bail!(
878                "{}:{} has an invalid environment name",
879                path.display(),
880                index + 1
881            );
882        }
883        values.insert(
884            name.to_string(),
885            value.trim().trim_matches(['\'', '"']).to_string(),
886        );
887    }
888    Ok(())
889}
890
891#[cfg(unix)]
892extern "C" fn test_signal_handler(_signal: libc::c_int) {
893    TEST_INTERRUPTED.store(true, Ordering::SeqCst);
894}
895
896fn install_test_signal_handler() {
897    #[cfg(unix)]
898    unsafe {
899        libc::signal(
900            libc::SIGINT,
901            test_signal_handler as extern "C" fn(libc::c_int) as libc::sighandler_t,
902        );
903        libc::signal(
904            libc::SIGTERM,
905            test_signal_handler as extern "C" fn(libc::c_int) as libc::sighandler_t,
906        );
907    }
908}
909
910fn run_linked_execute(root: &Path, command: &[String], action: LinkedCargoAction) -> Result<()> {
911    run_linked_execute_with_environment(root, command, action, &BTreeMap::new())
912}
913
914fn run_linked_execute_with_environment(
915    root: &Path,
916    command: &[String],
917    action: LinkedCargoAction,
918    environment: &BTreeMap<OsString, OsString>,
919) -> Result<()> {
920    let prepared = prepare_linked_cargo_with_environment(root, command, action, environment)?;
921    println!(
922        "running linked RSJS Cargo {}: {}",
923        action.command_name(),
924        shellish(command)
925    );
926    let output = run_linked_cargo_cached(&prepared.request, &prepared.descriptor_cache_directory)
927        .with_context(|| format!("linked RSJS {} failed", action.command_name()))?;
928    print_linked_cache_reuse(action, &output);
929    print_linked_cargo_output(action, &prepared.request, &output);
930    Ok(())
931}
932
933fn print_linked_cache_reuse(action: LinkedCargoAction, output: &LinkedCargoOutput) {
934    let descriptor_artifacts = output.descriptor.cargo_artifacts.len();
935    let reused_descriptor_artifacts = output
936        .descriptor
937        .cargo_artifacts
938        .iter()
939        .filter(|artifact| artifact.fresh)
940        .count();
941    let final_artifacts = output.final_cargo.cargo_artifacts.len();
942    let reused_final_artifacts = output
943        .final_cargo
944        .cargo_artifacts
945        .iter()
946        .filter(|artifact| artifact.fresh)
947        .count();
948    println!(
949        "linked RSJS {} cache: descriptor {reused_descriptor_artifacts}/{descriptor_artifacts} Cargo artifacts reused; final {reused_final_artifacts}/{final_artifacts} reused",
950        action.command_name(),
951    );
952}
953
954fn run_linked_dev_cycle(root: &Path, command: &[String]) -> Result<LinkedDevLaunch> {
955    let prepared = prepare_linked_cargo(root, command, LinkedCargoAction::Dev)?;
956    println!("running linked RSJS Cargo dev build: {}", shellish(command));
957    let output = run_linked_cargo_cached(&prepared.request, &prepared.descriptor_cache_directory)
958        .context("linked RSJS dev build failed")?;
959    let executable =
960        select_final_root_executable(&prepared.request, &output, LinkedCargoAction::Dev)?;
961    let descriptor_artifacts = output.descriptor.cargo_artifacts.len();
962    let reused_descriptor_artifacts = output
963        .descriptor
964        .cargo_artifacts
965        .iter()
966        .filter(|artifact| artifact.fresh)
967        .count();
968    let reused_final_artifacts = output
969        .final_cargo
970        .cargo_artifacts
971        .iter()
972        .filter(|artifact| artifact.fresh)
973        .count();
974    println!(
975        "linked RSJS dev plan {} (descriptor cache: {reused_descriptor_artifacts}/{descriptor_artifacts} Cargo artifacts reused; final cache: {reused_final_artifacts}/{} reused)",
976        output.semantic.plan_id,
977        output.final_cargo.cargo_artifacts.len(),
978    );
979
980    Ok(LinkedDevLaunch {
981        executable,
982        arguments: prepared.runtime_args,
983        plan_id: output.semantic.plan_id.to_string(),
984        descriptor_artifacts,
985        reused_descriptor_artifacts,
986        reused_final_artifacts,
987    })
988}
989
990fn select_final_root_executable(
991    request: &LinkedCargoRequest,
992    output: &LinkedCargoOutput,
993    action: LinkedCargoAction,
994) -> Result<PathBuf> {
995    if output.final_cargo.plan_id != output.semantic.plan_id {
996        bail!(
997            "linked {} final Cargo consumed plan {}, but the semantic linker produced {}",
998            action.command_name(),
999            output.final_cargo.plan_id,
1000            output.semantic.plan_id
1001        );
1002    }
1003    if !output.semantic_plan_path.is_file() {
1004        bail!(
1005            "linked {} semantic plan disappeared before executable selection: `{}`",
1006            action.command_name(),
1007            output.semantic_plan_path.display()
1008        );
1009    }
1010
1011    let artifact = &output.final_root_artifact;
1012    if artifact.package_id != request.root.package_id
1013        || artifact.target.name != request.root.target_name
1014        || artifact.target.kind != request.root.target_kinds
1015    {
1016        bail!(
1017            "attested final root no longer matches linked {} package `{}` target `{}`",
1018            action.command_name(),
1019            request.root.package_id,
1020            request.root.target_name
1021        );
1022    }
1023    let executable = artifact.executable.clone().ok_or_else(|| {
1024        anyhow::anyhow!(
1025            "final linked Cargo build emitted no executable for package `{}` binary `{}`",
1026            request.root.package_id,
1027            request.root.target_name
1028        )
1029    })?;
1030    if !executable.is_absolute() || !executable.is_file() {
1031        bail!(
1032            "final linked Cargo executable is not an existing absolute file: `{}`",
1033            executable.display()
1034        );
1035    }
1036    Ok(executable)
1037}
1038
1039fn resolve_artifact_output(root: &Path, requested: &Path) -> PathBuf {
1040    if requested.is_absolute() {
1041        requested.to_path_buf()
1042    } else {
1043        root.join(requested)
1044    }
1045}
1046
1047fn warn_if_artifact_output_enters_source_closure(
1048    destination: &Path,
1049    package_source_root: &Path,
1050    source_exclusion: &Path,
1051) {
1052    if artifact_output_enters_source_closure(destination, package_source_root, source_exclusion) {
1053        eprintln!(
1054            "warning[proa/artifact-out-source-closure]: artifact output `{}` is inside selected package `{}` and will participate in its next source-closure check; use the Cargo target directory or a path outside the package for warm rebuilds",
1055            destination.display(),
1056            package_source_root.display()
1057        );
1058    }
1059}
1060
1061fn artifact_output_enters_source_closure(
1062    destination: &Path,
1063    package_source_root: &Path,
1064    source_exclusion: &Path,
1065) -> bool {
1066    let Some(destination) = normalize_absolute_lexical_path(destination) else {
1067        return destination.starts_with(package_source_root);
1068    };
1069    let Some(package_source_root) = normalize_absolute_lexical_path(package_source_root) else {
1070        return false;
1071    };
1072    let Some(source_exclusion) = normalize_absolute_lexical_path(source_exclusion) else {
1073        return false;
1074    };
1075    if !destination.starts_with(&package_source_root) || destination.starts_with(&source_exclusion)
1076    {
1077        return false;
1078    }
1079    let Ok(relative) = destination.strip_prefix(&package_source_root) else {
1080        return false;
1081    };
1082    let mut components = relative
1083        .components()
1084        .filter_map(|component| match component {
1085            std::path::Component::Normal(value) => Some(value),
1086            _ => None,
1087        });
1088    let Some(first) = components.next() else {
1089        return true;
1090    };
1091    if matches!(
1092        first.to_str(),
1093        Some(".git" | ".hg" | ".svn" | ".jj" | "target" | "node_modules")
1094    ) {
1095        return false;
1096    }
1097    !components.any(|component| component == OsStr::new("node_modules"))
1098}
1099
1100fn normalize_absolute_lexical_path(path: &Path) -> Option<PathBuf> {
1101    use std::path::Component;
1102
1103    if !path.is_absolute() {
1104        return None;
1105    }
1106    let mut normalized = PathBuf::new();
1107    for component in path.components() {
1108        match component {
1109            Component::Prefix(_) | Component::RootDir | Component::Normal(_) => {
1110                normalized.push(component.as_os_str());
1111            }
1112            Component::CurDir => {}
1113            Component::ParentDir => {
1114                if !normalized.pop() {
1115                    return None;
1116                }
1117            }
1118        }
1119    }
1120    Some(normalized)
1121}
1122
1123fn copy_executable_atomically(source: &Path, destination: &Path) -> io::Result<()> {
1124    if source == destination {
1125        return Ok(());
1126    }
1127    if destination.is_dir() {
1128        return Err(io::Error::new(
1129            io::ErrorKind::InvalidInput,
1130            format!(
1131                "artifact output must name a file, but `{}` is a directory",
1132                destination.display()
1133            ),
1134        ));
1135    }
1136
1137    let parent = destination.parent().ok_or_else(|| {
1138        io::Error::new(
1139            io::ErrorKind::InvalidInput,
1140            format!(
1141                "artifact output `{}` has no parent directory",
1142                destination.display()
1143            ),
1144        )
1145    })?;
1146    fs::create_dir_all(parent)?;
1147
1148    let file_name = destination.file_name().ok_or_else(|| {
1149        io::Error::new(
1150            io::ErrorKind::InvalidInput,
1151            format!(
1152                "artifact output `{}` does not name a file",
1153                destination.display()
1154            ),
1155        )
1156    })?;
1157    let (temporary, mut temporary_file) = loop {
1158        let nonce = RSJS_BUILD_NONCE.fetch_add(1, Ordering::Relaxed);
1159        let candidate = parent.join(format!(
1160            ".{}.proa-export-{}-{nonce}",
1161            file_name.to_string_lossy(),
1162            std::process::id()
1163        ));
1164        match fs::OpenOptions::new()
1165            .create_new(true)
1166            .write(true)
1167            .open(&candidate)
1168        {
1169            Ok(file) => break (candidate, file),
1170            Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
1171            Err(error) => return Err(error),
1172        }
1173    };
1174
1175    let copy_result = (|| {
1176        let mut source_file = fs::File::open(source)?;
1177        let source_permissions = source_file.metadata()?.permissions();
1178        io::copy(&mut source_file, &mut temporary_file)?;
1179        temporary_file.set_permissions(source_permissions)?;
1180        temporary_file.sync_all()?;
1181        drop(temporary_file);
1182        replace_file(&temporary, destination)
1183    })();
1184
1185    if copy_result.is_err() {
1186        let _ = fs::remove_file(&temporary);
1187    }
1188    copy_result
1189}
1190
1191#[cfg(not(windows))]
1192fn replace_file(source: &Path, destination: &Path) -> io::Result<()> {
1193    fs::rename(source, destination)
1194}
1195
1196#[cfg(windows)]
1197fn replace_file(source: &Path, destination: &Path) -> io::Result<()> {
1198    use std::os::windows::ffi::OsStrExt;
1199    use windows_sys::Win32::Storage::FileSystem::{
1200        MoveFileExW, MOVEFILE_REPLACE_EXISTING, MOVEFILE_WRITE_THROUGH,
1201    };
1202
1203    let source: Vec<u16> = source.as_os_str().encode_wide().chain(Some(0)).collect();
1204    let destination: Vec<u16> = destination
1205        .as_os_str()
1206        .encode_wide()
1207        .chain(Some(0))
1208        .collect();
1209    let moved = unsafe {
1210        MoveFileExW(
1211            source.as_ptr(),
1212            destination.as_ptr(),
1213            MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH,
1214        )
1215    };
1216    if moved == 0 {
1217        Err(io::Error::last_os_error())
1218    } else {
1219        Ok(())
1220    }
1221}
1222
1223fn apply_dev_overrides(config: &mut ProjectConfig, options: &DevOptions) {
1224    if let Some(host) = &options.host {
1225        config.dev.host = host.clone();
1226    }
1227    if let Some(port) = options.port {
1228        config.dev.port = port;
1229    }
1230    if !options.command.is_empty() {
1231        config.dev.command = options.command.clone();
1232    }
1233    if options.offline && !config.dev.command.iter().any(|arg| arg == "--offline") {
1234        config.dev.command.push("--offline".to_string());
1235    }
1236}
1237
1238fn build_command(config: &ProjectConfig, options: &BuildOptions) -> Vec<String> {
1239    let mut command = if !options.command.is_empty() {
1240        options.command.clone()
1241    } else if let Some(profile) = &options.profile {
1242        vec![
1243            "cargo".into(),
1244            "build".into(),
1245            "--profile".into(),
1246            profile.clone(),
1247        ]
1248    } else {
1249        config.build.command.clone()
1250    };
1251
1252    if let Some(package) = &options.package {
1253        command.push("-p".into());
1254        command.push(package.clone());
1255    }
1256    if let Some(bin) = &options.bin {
1257        command.push("--bin".into());
1258        command.push(bin.clone());
1259    }
1260    if let Some(example) = &options.example {
1261        command.push("--example".into());
1262        command.push(example.clone());
1263    }
1264    if let Some(target) = &options.target {
1265        command.push("--target".into());
1266        command.push(target.clone());
1267    }
1268    if !options.features.is_empty() {
1269        command.push("--features".into());
1270        command.push(options.features.join(","));
1271    }
1272    if options.all_features {
1273        command.push("--all-features".into());
1274    }
1275    if options.no_default_features {
1276        command.push("--no-default-features".into());
1277    }
1278    if options.locked {
1279        command.push("--locked".into());
1280    }
1281    if options.offline {
1282        command.push("--offline".into());
1283    }
1284
1285    command
1286}
1287
1288fn check_command(options: &CheckOptions) -> Vec<String> {
1289    let mut command = vec!["cargo".into(), "check".into()];
1290    append_cargo_selection(
1291        &mut command,
1292        options.profile.as_deref(),
1293        options.package.as_deref(),
1294        options.bin.as_deref(),
1295        options.target.as_deref(),
1296        &options.features,
1297        options.all_features,
1298        options.no_default_features,
1299        options.locked,
1300        options.offline,
1301    );
1302    command
1303}
1304
1305fn run_command(options: &RunOptions) -> Vec<String> {
1306    let mut command = vec!["cargo".into(), "run".into()];
1307    append_cargo_selection(
1308        &mut command,
1309        options.profile.as_deref(),
1310        options.package.as_deref(),
1311        options.bin.as_deref(),
1312        options.target.as_deref(),
1313        &options.features,
1314        options.all_features,
1315        options.no_default_features,
1316        options.locked,
1317        options.offline,
1318    );
1319    append_runtime_arguments(&mut command, &options.arguments);
1320    command
1321}
1322
1323fn test_command(options: &TestOptions) -> Vec<String> {
1324    let mut command = vec!["cargo".into(), "test".into()];
1325    append_cargo_selection(
1326        &mut command,
1327        options.profile.as_deref(),
1328        options.package.as_deref(),
1329        options.bin.as_deref(),
1330        options.target.as_deref(),
1331        &options.features,
1332        options.all_features,
1333        options.no_default_features,
1334        options.locked,
1335        options.offline,
1336    );
1337    if let Some(test) = &options.test {
1338        command.push("--test".into());
1339        command.push(test.clone());
1340    }
1341    append_runtime_arguments(&mut command, &options.arguments);
1342    command
1343}
1344
1345fn append_runtime_arguments(command: &mut Vec<String>, arguments: &[String]) {
1346    if !arguments.is_empty() {
1347        command.push("--".into());
1348        command.extend(arguments.iter().cloned());
1349    }
1350}
1351
1352fn append_cargo_selection(
1353    command: &mut Vec<String>,
1354    profile: Option<&str>,
1355    package: Option<&str>,
1356    bin: Option<&str>,
1357    target: Option<&str>,
1358    features: &[String],
1359    all_features: bool,
1360    no_default_features: bool,
1361    locked: bool,
1362    offline: bool,
1363) {
1364    if let Some(profile) = profile {
1365        command.push("--profile".into());
1366        command.push(profile.into());
1367    }
1368    if let Some(package) = package {
1369        command.push("-p".into());
1370        command.push(package.into());
1371    }
1372    if let Some(bin) = bin {
1373        command.push("--bin".into());
1374        command.push(bin.into());
1375    }
1376    if let Some(target) = target {
1377        command.push("--target".into());
1378        command.push(target.into());
1379    }
1380    if !features.is_empty() {
1381        command.push("--features".into());
1382        command.push(features.join(","));
1383    }
1384    if all_features {
1385        command.push("--all-features".into());
1386    }
1387    if no_default_features {
1388        command.push("--no-default-features".into());
1389    }
1390    if locked {
1391        command.push("--locked".into());
1392    }
1393    if offline {
1394        command.push("--offline".into());
1395    }
1396}
1397
1398#[derive(Debug, Clone, PartialEq, Eq)]
1399struct ParsedCargoInvocation {
1400    cargo: OsString,
1401    cargo_args: Vec<OsString>,
1402    runtime_args: Vec<OsString>,
1403    package: Option<String>,
1404    bin: Option<String>,
1405    example: Option<String>,
1406    test: Option<String>,
1407    profile: String,
1408    target: Option<String>,
1409    features: BTreeSet<String>,
1410    locked: bool,
1411    offline: bool,
1412    metadata_flags: Vec<OsString>,
1413    selection_args: Vec<String>,
1414}
1415
1416#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1417enum LinkedCargoAction {
1418    Build,
1419    Check,
1420    Dev,
1421    Run,
1422    Test,
1423}
1424
1425impl LinkedCargoAction {
1426    const fn command_name(self) -> &'static str {
1427        match self {
1428            Self::Build => "build",
1429            Self::Check => "check",
1430            Self::Dev => "dev",
1431            Self::Run => "run",
1432            Self::Test => "test",
1433        }
1434    }
1435
1436    const fn subcommand(self) -> &'static str {
1437        match self {
1438            Self::Build => "build",
1439            Self::Check => "check",
1440            Self::Dev => "run",
1441            Self::Run => "run",
1442            Self::Test => "test",
1443        }
1444    }
1445
1446    const fn final_subcommand(self) -> &'static str {
1447        match self {
1448            Self::Build => "build",
1449            Self::Check => "check",
1450            Self::Dev => "build",
1451            Self::Run => "run",
1452            Self::Test => "test",
1453        }
1454    }
1455
1456    const fn descriptor_subcommand(self) -> &'static str {
1457        match self {
1458            Self::Test => "test",
1459            Self::Check => "check",
1460            Self::Build | Self::Dev | Self::Run => "build",
1461        }
1462    }
1463
1464    const fn permits_runtime_arguments(self) -> bool {
1465        matches!(self, Self::Dev | Self::Run | Self::Test)
1466    }
1467
1468    const fn final_cargo_executes(self) -> bool {
1469        matches!(self, Self::Run | Self::Test)
1470    }
1471
1472    const fn root_role(self) -> ArtifactRole {
1473        match self {
1474            Self::Test => ArtifactRole::RootTest,
1475            Self::Build | Self::Check | Self::Dev | Self::Run => ArtifactRole::RootExecutable,
1476        }
1477    }
1478
1479    const fn descriptor_identity_marker(self) -> &'static str {
1480        match self {
1481            Self::Test => "proa:descriptor-mode=test-no-run",
1482            Self::Check => "proa:descriptor-mode=check",
1483            Self::Build | Self::Dev | Self::Run => "proa:descriptor-mode=build",
1484        }
1485    }
1486}
1487
1488#[derive(Debug)]
1489struct PreparedLinkedCargo {
1490    request: LinkedCargoRequest,
1491    runtime_args: Vec<OsString>,
1492    descriptor_cache_directory: PathBuf,
1493    package_source_root: PathBuf,
1494    // Windows cannot safely relocate arbitrary PE executables without a
1495    // complete delay-import contract. Hold a no-write/no-delete sharing lock
1496    // instead so the fingerprinted wrapper path cannot be replaced before
1497    // Cargo opens it. Other hosts execute a content-addressed snapshot.
1498    _wrapper_lock: Option<fs::File>,
1499}
1500
1501#[derive(Debug, Deserialize)]
1502struct CargoMetadata {
1503    packages: Vec<CargoMetadataPackage>,
1504    workspace_members: Vec<String>,
1505    #[serde(default)]
1506    workspace_default_members: Vec<String>,
1507    target_directory: PathBuf,
1508}
1509
1510#[derive(Debug, Deserialize)]
1511struct CargoMetadataPackage {
1512    id: String,
1513    name: String,
1514    version: String,
1515    manifest_path: PathBuf,
1516    targets: Vec<CargoMetadataTarget>,
1517}
1518
1519#[derive(Debug, Deserialize)]
1520struct CargoMetadataTarget {
1521    name: String,
1522    kind: Vec<String>,
1523}
1524
1525#[derive(Debug)]
1526struct ExactCargoRoot {
1527    package_id: String,
1528    package_name: String,
1529    package_source_root: PathBuf,
1530    target_name: String,
1531    target_kinds: BTreeSet<String>,
1532    requested_target_kind: String,
1533}
1534
1535fn prepare_linked_cargo(
1536    root: &Path,
1537    command: &[String],
1538    action: LinkedCargoAction,
1539) -> Result<PreparedLinkedCargo> {
1540    prepare_linked_cargo_with_environment(root, command, action, &BTreeMap::new())
1541}
1542
1543fn prepare_linked_cargo_with_environment(
1544    root: &Path,
1545    command: &[String],
1546    action: LinkedCargoAction,
1547    environment: &BTreeMap<OsString, OsString>,
1548) -> Result<PreparedLinkedCargo> {
1549    let wrapper = std::env::current_exe().context("resolve the cargo-proa wrapper executable")?;
1550    prepare_linked_cargo_with_wrapper_and_environment(root, command, action, wrapper, environment)
1551}
1552
1553#[cfg(test)]
1554fn prepare_linked_cargo_with_wrapper(
1555    root: &Path,
1556    command: &[String],
1557    action: LinkedCargoAction,
1558    wrapper: PathBuf,
1559) -> Result<PreparedLinkedCargo> {
1560    prepare_linked_cargo_with_wrapper_and_environment(
1561        root,
1562        command,
1563        action,
1564        wrapper,
1565        &BTreeMap::new(),
1566    )
1567}
1568
1569fn prepare_linked_cargo_with_wrapper_and_environment(
1570    root: &Path,
1571    command: &[String],
1572    action: LinkedCargoAction,
1573    wrapper: PathBuf,
1574    environment: &BTreeMap<OsString, OsString>,
1575) -> Result<PreparedLinkedCargo> {
1576    if !wrapper.is_absolute() {
1577        bail!(
1578            "the cargo-proa wrapper executable is not absolute: `{}`",
1579            wrapper.display()
1580        );
1581    }
1582    let parsed = parse_cargo_command(command, action)?;
1583    let metadata = load_cargo_metadata(root, &parsed)?;
1584    let selected_root = select_exact_cargo_root(&metadata, &parsed, action)?;
1585    if !metadata.target_directory.is_absolute() {
1586        bail!(
1587            "Cargo metadata returned a relative target directory `{}`; the linked RSJS pipeline requires an exact absolute artifact namespace",
1588            metadata.target_directory.display()
1589        );
1590    }
1591    let wrapper_snapshot_root = metadata
1592        .target_directory
1593        .join("proa-rsjs")
1594        .join("wrapper-snapshots-v1");
1595    let (wrapper, wrapper_lock) =
1596        prepare_wrapper_executable(&metadata.target_directory, &wrapper_snapshot_root, &wrapper)?;
1597    let wrapper_fingerprint = wrapper_executable_fingerprint(&wrapper)?;
1598    let package_source_root = selected_root.package_source_root.clone();
1599    let cli_producer = cli_tool_producer_version()?;
1600    let mut selection_args = parsed.selection_args.clone();
1601    // A binary compiled as a test harness is a different Cargo/rustc unit from
1602    // the same binary compiled normally. Keep that mode in the pre-Cargo
1603    // identity so persistent descriptor targets and caches cannot alias.
1604    selection_args.push(action.descriptor_identity_marker().to_string());
1605    // Producer semver is insufficient during local development and rolling
1606    // upgrades: the same absolute executable path can be atomically replaced
1607    // with different wrapper behavior. Bind every persistent descriptor and
1608    // final Cargo namespace to the exact wrapper bytes that will be invoked.
1609    selection_args.push(format!(
1610        "proa:wrapper-executable-fingerprint={wrapper_fingerprint}"
1611    ));
1612    let invocation_spec = InvocationSpec {
1613        roots: BTreeSet::from([RequestedRootTarget {
1614            package: selected_root.package_id.clone(),
1615            target_kind: selected_root.requested_target_kind.clone(),
1616            target_name: Some(selected_root.target_name.clone()),
1617        }]),
1618        target_triple: parsed.target.clone(),
1619        features: parsed.features.clone(),
1620        profile: parsed.profile.clone(),
1621        cargo_config: BTreeMap::new(),
1622        locked: parsed.locked,
1623        offline: parsed.offline,
1624        selection_args,
1625        // Test fixture values are supplied identically to descriptor and final
1626        // Cargo below, but are not semantic target selectors. Cargo build
1627        // scripts and the wrapper's observed-environment sidecars still
1628        // invalidate units that actually consume one of these values.
1629        environment: declared_build_environment(),
1630        toolchain: BuildToolchain {
1631            cargo: tool_version(&parsed.cargo, &["-Vv"], "Cargo", root)?,
1632            rustc: selected_rustc_version(root)?,
1633            proa: cli_producer,
1634            compiler_abi: RSJS_COMPILER_ABI,
1635            transport_version: TRANSPORT_FORMAT_VERSION,
1636        },
1637    };
1638    let invocation = invocation_spec
1639        .invocation_id()
1640        .context("derive the pre-descriptor RSJS invocation identity")?;
1641
1642    let build_root = metadata
1643        .target_directory
1644        .join("proa-rsjs")
1645        .join(invocation.to_string());
1646    let source_exclusion_directory = metadata.target_directory.clone();
1647    let nonce = fresh_build_nonce();
1648    let descriptor_staging = build_root.join("descriptor-staging").join(&nonce);
1649    let descriptor_target = build_root.join(format!(
1650        "descriptor-target-policy-v{DESCRIPTOR_TARGET_POLICY_VERSION}-sidecar-v{DESCRIPTOR_UNIT_SIDECAR_SCHEMA_VERSION}-persistent-v{PERSISTENT_DESCRIPTOR_TARGET_LAYOUT_VERSION}"
1651    ));
1652    let descriptor_cache_directory = build_root.join(format!(
1653        "descriptor-cache-v{DESCRIPTOR_CACHE_SCHEMA_VERSION}"
1654    ));
1655    let plan_directory = metadata.target_directory.join("proa-rsjs").join("plans");
1656    let final_target_root = metadata
1657        .target_directory
1658        .join("proa-rsjs")
1659        .join("final-target");
1660    let mut descriptor_cargo_args = parsed.cargo_args.clone();
1661    // The wrapper adds one explicit object output even when Cargo selected
1662    // `check`, so linked checks can keep descriptor and final rustc unit
1663    // coordinates identical. Tests require their exact `cfg(test)`/harness
1664    // compilation, so both phases use `cargo test`; only the descriptor phase
1665    // adds `--no-run`.
1666    descriptor_cargo_args[0] = OsString::from(action.descriptor_subcommand());
1667    if action == LinkedCargoAction::Test {
1668        descriptor_cargo_args.push("--no-run".into());
1669    }
1670    let mut final_cargo_args = parsed.cargo_args.clone();
1671    final_cargo_args[0] = OsString::from(action.final_subcommand());
1672    if action.final_cargo_executes() && !parsed.runtime_args.is_empty() {
1673        final_cargo_args.push("--".into());
1674        final_cargo_args.extend(parsed.runtime_args.iter().cloned());
1675    }
1676
1677    Ok(PreparedLinkedCargo {
1678        request: LinkedCargoRequest {
1679            descriptor: DescriptorCargoRequest {
1680                cargo: parsed.cargo,
1681                wrapper,
1682                working_directory: root.to_path_buf(),
1683                staging_directory: descriptor_staging,
1684                target_directory: descriptor_target,
1685                source_exclusion_directory,
1686                cargo_args: descriptor_cargo_args,
1687                environment: environment.clone(),
1688            },
1689            root: DescriptorRootSelector {
1690                package_id: selected_root.package_id,
1691                target_name: selected_root.target_name,
1692                target_kinds: selected_root.target_kinds,
1693                role: action.root_role(),
1694                artifact_path: None,
1695            },
1696            invocation,
1697            producer: RSJS_COMPILER_PRODUCER,
1698            runtime_protocol: RSJS_RUNTIME_PROTOCOL,
1699            plan_directory,
1700            final_target_root,
1701            final_cargo_args,
1702            final_environment: environment.clone(),
1703        },
1704        runtime_args: parsed.runtime_args,
1705        descriptor_cache_directory,
1706        package_source_root,
1707        _wrapper_lock: wrapper_lock,
1708    })
1709}
1710
1711#[cfg(not(windows))]
1712fn prepare_wrapper_executable(
1713    source_exclusion: &Path,
1714    snapshot_root: &Path,
1715    wrapper: &Path,
1716) -> Result<(PathBuf, Option<fs::File>)> {
1717    let snapshot = snapshot_wrapper_executable(source_exclusion, snapshot_root, wrapper)
1718        .context("publish the cargo-proa wrapper into its content-addressed snapshot")?;
1719    Ok((snapshot, None))
1720}
1721
1722#[cfg(windows)]
1723fn prepare_wrapper_executable(
1724    _source_exclusion: &Path,
1725    _snapshot_root: &Path,
1726    wrapper: &Path,
1727) -> Result<(PathBuf, Option<fs::File>)> {
1728    use std::os::windows::fs::OpenOptionsExt as _;
1729    use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_READ;
1730
1731    let wrapper = fs::canonicalize(wrapper)
1732        .with_context(|| format!("resolve cargo-proa wrapper `{}`", wrapper.display()))?;
1733    let lock = fs::OpenOptions::new()
1734        .read(true)
1735        .share_mode(FILE_SHARE_READ)
1736        .open(&wrapper)
1737        .with_context(|| {
1738            format!(
1739                "lock cargo-proa wrapper `{}` against replacement during linked compilation",
1740                wrapper.display()
1741            )
1742        })?;
1743    Ok((wrapper, Some(lock)))
1744}
1745
1746fn wrapper_executable_fingerprint(path: &Path) -> Result<String> {
1747    use std::fmt::Write as _;
1748    use std::io::Read as _;
1749
1750    let mut executable = fs::File::open(path)
1751        .with_context(|| format!("open cargo-proa wrapper executable `{}`", path.display()))?;
1752    let metadata = executable
1753        .metadata()
1754        .with_context(|| format!("inspect cargo-proa wrapper executable `{}`", path.display()))?;
1755    if !metadata.is_file() {
1756        bail!(
1757            "cargo-proa wrapper executable is not a regular file: `{}`",
1758            path.display()
1759        );
1760    }
1761
1762    let mut hasher = Sha256::new();
1763    hasher.update(RSJS_WRAPPER_EXECUTABLE_FINGERPRINT_DOMAIN);
1764    let mut buffer = [0_u8; 64 * 1024];
1765    loop {
1766        let read = executable
1767            .read(&mut buffer)
1768            .with_context(|| format!("hash cargo-proa wrapper executable `{}`", path.display()))?;
1769        if read == 0 {
1770            break;
1771        }
1772        hasher.update(&buffer[..read]);
1773    }
1774
1775    let digest: [u8; 32] = hasher.finalize().into();
1776    let mut encoded = String::with_capacity("sha256:".len() + digest.len() * 2);
1777    encoded.push_str("sha256:");
1778    for byte in digest {
1779        let _ = write!(encoded, "{byte:02x}");
1780    }
1781    Ok(encoded)
1782}
1783
1784#[cfg(test)]
1785fn parse_cargo_build_command(command: &[String]) -> Result<ParsedCargoInvocation> {
1786    parse_cargo_command(command, LinkedCargoAction::Build)
1787}
1788
1789fn parse_cargo_command(
1790    command: &[String],
1791    action: LinkedCargoAction,
1792) -> Result<ParsedCargoInvocation> {
1793    let Some((program, raw_args)) = command.split_first() else {
1794        bail!(
1795            "linked Cargo {} command cannot be empty",
1796            action.subcommand()
1797        );
1798    };
1799    if !is_cargo_program(program) {
1800        bail!(
1801            "`cargo proa {command}` requires a Cargo {cargo_action} command for the linked RSJS pipeline; found `{}`. Custom non-Cargo commands are not supported yet",
1802            shellish(command),
1803            command = action.command_name(),
1804            cargo_action = action.subcommand(),
1805        );
1806    }
1807    if raw_args.first().map(String::as_str) != Some(action.subcommand()) {
1808        bail!(
1809            "`cargo proa {command}` currently supports only `cargo {cargo_action}`; found `{}`. Other Cargo subcommands do not yet have linked-root semantics for this workflow",
1810            shellish(command),
1811            command = action.command_name(),
1812            cargo_action = action.subcommand(),
1813        );
1814    }
1815
1816    let mut package = None;
1817    let mut bin = None;
1818    let mut example = None;
1819    let mut test = None;
1820    let mut explicit_profile = None;
1821    let mut release = false;
1822    let mut target = None;
1823    let mut features = BTreeSet::new();
1824    let mut locked = false;
1825    let mut offline = false;
1826    let mut metadata_flags = Vec::new();
1827    let mut selection_args = Vec::new();
1828    let mut runtime_args = Vec::new();
1829    let mut cargo_arg_count = raw_args.len();
1830    let mut index = 1;
1831    while index < raw_args.len() {
1832        let argument = &raw_args[index];
1833        match argument.as_str() {
1834            "--message-format" | "--target-dir" => {
1835                let value = raw_args.get(index + 1).cloned();
1836                bail!(
1837                    "Cargo argument `{argument}{}` is reserved by the linked RSJS pipeline; remove it so cargo-proa can isolate descriptor and final artifacts",
1838                    value
1839                        .as_deref()
1840                        .map(|value| format!(" {value}"))
1841                        .unwrap_or_default()
1842                );
1843            }
1844            value
1845                if value.starts_with("--message-format=") || value.starts_with("--target-dir=") =>
1846            {
1847                bail!(
1848                    "Cargo argument `{value}` is reserved by the linked RSJS pipeline; remove it so cargo-proa can own Cargo messages and artifact namespaces"
1849                );
1850            }
1851            "--workspace" | "--all" | "--exclude" | "--bins" | "--examples" | "--tests"
1852            | "--benches" | "--all-targets" | "--lib" | "--bench" => {
1853                bail!(
1854                    "Cargo target-selection argument `{argument}` can produce multiple or unsupported roots. The linked RSJS pipeline requires one exact package plus binary, example, or integration-test target"
1855                );
1856            }
1857            "--manifest-path" | "--config" | "--artifact-dir" => {
1858                bail!(
1859                    "Cargo argument `{argument}` is not supported by the first linked RSJS pipeline contract; select the project with `--root` and let cargo-proa own build configuration/output paths"
1860                );
1861            }
1862            value
1863                if value.starts_with("--manifest-path=")
1864                    || value.starts_with("--config=")
1865                    || value.starts_with("--artifact-dir=") =>
1866            {
1867                bail!(
1868                    "Cargo argument `{value}` is not supported by the first linked RSJS pipeline contract; select the project with `--root` and let cargo-proa own build configuration/output paths"
1869                );
1870            }
1871            "--" => {
1872                if !action.permits_runtime_arguments() {
1873                    bail!(
1874                        "arguments after `--` are supported only by `cargo proa dev`, `cargo proa run`, and `cargo proa test`; descriptor and final compiler inputs for this workflow must be derived by cargo-proa"
1875                    );
1876                }
1877                cargo_arg_count = index;
1878                runtime_args.extend(raw_args[index + 1..].iter().map(OsString::from));
1879                break;
1880            }
1881            "-p" | "--package" => {
1882                let value = required_cargo_value(raw_args, &mut index, argument)?;
1883                set_once(&mut package, value, "Cargo package")?;
1884            }
1885            value if value.starts_with("--package=") => {
1886                set_once(
1887                    &mut package,
1888                    nonempty_option_value(value, "--package=")?,
1889                    "Cargo package",
1890                )?;
1891            }
1892            value if value.starts_with("-p") && value.len() > 2 => {
1893                set_once(&mut package, value[2..].to_string(), "Cargo package")?;
1894            }
1895            "--bin" => {
1896                let value = required_cargo_value(raw_args, &mut index, argument)?;
1897                set_once(&mut bin, value, "Cargo binary")?;
1898            }
1899            value if value.starts_with("--bin=") => {
1900                set_once(
1901                    &mut bin,
1902                    nonempty_option_value(value, "--bin=")?,
1903                    "Cargo binary",
1904                )?;
1905            }
1906            "--example" if action != LinkedCargoAction::Test => {
1907                let value = required_cargo_value(raw_args, &mut index, argument)?;
1908                set_once(&mut example, value, "Cargo example")?;
1909            }
1910            value if action != LinkedCargoAction::Test && value.starts_with("--example=") => {
1911                set_once(
1912                    &mut example,
1913                    nonempty_option_value(value, "--example=")?,
1914                    "Cargo example",
1915                )?;
1916            }
1917            "--example" => {
1918                bail!(
1919                    "Cargo target-selection argument `--example` is not supported by `cargo proa test`; use `--bin <name>` or `--test <name>`"
1920                );
1921            }
1922            value if value.starts_with("--example=") => {
1923                bail!(
1924                    "Cargo target-selection argument `{value}` is not supported by `cargo proa test`; use `--bin <name>` or `--test <name>`"
1925                );
1926            }
1927            "--test" if action == LinkedCargoAction::Test => {
1928                let value = required_cargo_value(raw_args, &mut index, argument)?;
1929                set_once(&mut test, value, "Cargo integration test")?;
1930            }
1931            value if action == LinkedCargoAction::Test && value.starts_with("--test=") => {
1932                set_once(
1933                    &mut test,
1934                    nonempty_option_value(value, "--test=")?,
1935                    "Cargo integration test",
1936                )?;
1937            }
1938            "--test" => {
1939                bail!(
1940                    "Cargo target-selection argument `--test` is valid only for `cargo proa test`"
1941                );
1942            }
1943            value if value.starts_with("--test=") => {
1944                bail!(
1945                    "Cargo target-selection argument `{value}` is valid only for `cargo proa test`"
1946                );
1947            }
1948            "--profile" => {
1949                let value = required_cargo_value(raw_args, &mut index, argument)?;
1950                set_once(&mut explicit_profile, value, "Cargo profile")?;
1951            }
1952            value if value.starts_with("--profile=") => {
1953                set_once(
1954                    &mut explicit_profile,
1955                    nonempty_option_value(value, "--profile=")?,
1956                    "Cargo profile",
1957                )?;
1958            }
1959            "--release" => {
1960                if release {
1961                    bail!("Cargo profile selector `--release` was supplied more than once");
1962                }
1963                release = true;
1964            }
1965            "--target" => {
1966                let value = required_cargo_value(raw_args, &mut index, argument)?;
1967                set_once(&mut target, value, "Cargo target")?;
1968            }
1969            value if value.starts_with("--target=") => {
1970                set_once(
1971                    &mut target,
1972                    nonempty_option_value(value, "--target=")?,
1973                    "Cargo target",
1974                )?;
1975            }
1976            "--features" | "-F" => {
1977                let value = required_cargo_value(raw_args, &mut index, argument)?;
1978                extend_features(&mut features, &value)?;
1979            }
1980            value if value.starts_with("--features=") => {
1981                extend_features(&mut features, &nonempty_option_value(value, "--features=")?)?;
1982            }
1983            value if value.starts_with("-F") && value.len() > 2 => {
1984                extend_features(&mut features, &value[2..])?;
1985            }
1986            "--all-features" | "--no-default-features" => {
1987                metadata_flags.push(argument.clone().into());
1988                selection_args.push(argument.clone());
1989            }
1990            "--locked" => {
1991                locked = true;
1992                metadata_flags.push(argument.clone().into());
1993            }
1994            "--offline" => {
1995                offline = true;
1996                metadata_flags.push(argument.clone().into());
1997            }
1998            "--frozen" => {
1999                locked = true;
2000                offline = true;
2001                metadata_flags.push(argument.clone().into());
2002            }
2003            "-q"
2004            | "--quiet"
2005            | "-v"
2006            | "-vv"
2007            | "--verbose"
2008            | "--keep-going"
2009            | "--future-incompat-report"
2010            | "--timings"
2011            | "--ignore-rust-version" => {
2012                selection_args.push(argument.clone());
2013            }
2014            "--jobs" | "-j" | "--color" => {
2015                let value = required_cargo_value(raw_args, &mut index, argument)?;
2016                selection_args.push(argument.clone());
2017                selection_args.push(value);
2018            }
2019            value
2020                if value.starts_with("--jobs=")
2021                    || value.starts_with("--color=")
2022                    || value.starts_with("--timings=")
2023                    || (value.starts_with("-j") && value.len() > 2) =>
2024            {
2025                selection_args.push(value.to_string());
2026            }
2027            other => {
2028                bail!(
2029                    "Cargo {action} argument `{other}` is not yet classified by the linked RSJS pipeline. Remove it or use one of the supported package/bin/example/profile/feature/target/offline/locked/output flags",
2030                    action = action.subcommand(),
2031                );
2032            }
2033        }
2034        index += 1;
2035    }
2036
2037    if release && explicit_profile.is_some() {
2038        bail!("Cargo profile is ambiguous: use either `--release` or `--profile`, not both");
2039    }
2040    if bin.is_some() && example.is_some() {
2041        bail!(
2042            "linked Cargo target selection is ambiguous: use either `--bin <name>` or `--example <name>`, not both"
2043        );
2044    }
2045    if action == LinkedCargoAction::Test && bin.is_some() == test.is_some() {
2046        bail!(
2047            "linked Cargo test requires exactly one target selector: use either `--bin <name>` or `--test <name>`"
2048        );
2049    }
2050    let profile = explicit_profile.unwrap_or_else(|| {
2051        if release {
2052            "release".to_string()
2053        } else if action == LinkedCargoAction::Test {
2054            "test".to_string()
2055        } else {
2056            "dev".to_string()
2057        }
2058    });
2059
2060    Ok(ParsedCargoInvocation {
2061        cargo: OsString::from(program),
2062        cargo_args: raw_args[..cargo_arg_count]
2063            .iter()
2064            .map(OsString::from)
2065            .collect(),
2066        runtime_args,
2067        package,
2068        bin,
2069        example,
2070        test,
2071        profile,
2072        target,
2073        features,
2074        locked,
2075        offline,
2076        metadata_flags,
2077        selection_args,
2078    })
2079}
2080
2081fn required_cargo_value(arguments: &[String], index: &mut usize, option: &str) -> Result<String> {
2082    *index += 1;
2083    let Some(value) = arguments.get(*index) else {
2084        bail!("Cargo option `{option}` requires a value");
2085    };
2086    if value.is_empty() || value.starts_with('-') {
2087        bail!("Cargo option `{option}` requires a nonempty value");
2088    }
2089    Ok(value.clone())
2090}
2091
2092fn nonempty_option_value(argument: &str, prefix: &str) -> Result<String> {
2093    let value = &argument[prefix.len()..];
2094    if value.is_empty() {
2095        bail!(
2096            "Cargo option `{}` requires a nonempty value",
2097            &prefix[..prefix.len() - 1]
2098        );
2099    }
2100    Ok(value.to_string())
2101}
2102
2103fn set_once(slot: &mut Option<String>, value: String, label: &str) -> Result<()> {
2104    if let Some(previous) = slot {
2105        bail!(
2106            "{label} selection is ambiguous: both `{previous}` and `{value}` were supplied; select exactly one"
2107        );
2108    }
2109    *slot = Some(value);
2110    Ok(())
2111}
2112
2113fn extend_features(features: &mut BTreeSet<String>, value: &str) -> Result<()> {
2114    let parsed = value
2115        .split([',', ' '])
2116        .filter(|feature| !feature.is_empty())
2117        .collect::<Vec<_>>();
2118    if parsed.is_empty() {
2119        bail!("Cargo `--features` requires at least one feature name");
2120    }
2121    features.extend(parsed.into_iter().map(str::to_string));
2122    Ok(())
2123}
2124
2125fn is_cargo_program(program: &str) -> bool {
2126    Path::new(program)
2127        .file_name()
2128        .and_then(OsStr::to_str)
2129        .is_some_and(|name| matches!(name, "cargo" | "cargo.exe"))
2130}
2131
2132fn load_cargo_metadata(root: &Path, parsed: &ParsedCargoInvocation) -> Result<CargoMetadata> {
2133    let manifest = root.join("Cargo.toml");
2134    let mut command = Command::new(&parsed.cargo);
2135    command
2136        .current_dir(root)
2137        .args([
2138            OsStr::new("metadata"),
2139            OsStr::new("--format-version=1"),
2140            OsStr::new("--no-deps"),
2141            OsStr::new("--manifest-path"),
2142        ])
2143        .arg(&manifest)
2144        .args(&parsed.metadata_flags);
2145    let output = command.output().with_context(|| {
2146        format!(
2147            "run Cargo metadata with `{}` for exact RSJS root selection",
2148            Path::new(&parsed.cargo).display()
2149        )
2150    })?;
2151    if !output.status.success() {
2152        bail!(
2153            "Cargo metadata failed while selecting the exact RSJS root ({status}):\n{stderr}",
2154            status = output.status,
2155            stderr = String::from_utf8_lossy(&output.stderr).trim()
2156        );
2157    }
2158    serde_json::from_slice(&output.stdout).context("parse Cargo metadata for RSJS root selection")
2159}
2160
2161fn select_exact_cargo_root(
2162    metadata: &CargoMetadata,
2163    parsed: &ParsedCargoInvocation,
2164    action: LinkedCargoAction,
2165) -> Result<ExactCargoRoot> {
2166    let (requested_target_kind, requested_target_name) = match action {
2167        LinkedCargoAction::Test => match (&parsed.bin, &parsed.test) {
2168            (Some(name), None) => ("bin", name.as_str()),
2169            (None, Some(name)) => ("test", name.as_str()),
2170            _ => {
2171                bail!(
2172                    "linked Cargo test requires exactly one target selector: use either `--bin <name>` or `--test <name>`"
2173                )
2174            }
2175        },
2176        LinkedCargoAction::Build
2177        | LinkedCargoAction::Check
2178        | LinkedCargoAction::Dev
2179        | LinkedCargoAction::Run => match (&parsed.bin, &parsed.example) {
2180            (Some(name), None) => ("bin", name.as_str()),
2181            (None, Some(name)) => ("example", name.as_str()),
2182            (None, None) => ("bin", ""),
2183            (Some(_), Some(_)) => {
2184                bail!(
2185                    "linked Cargo target selection is ambiguous: use either `--bin <name>` or `--example <name>`, not both"
2186                )
2187            }
2188        },
2189    };
2190    let workspace_members = metadata
2191        .workspace_members
2192        .iter()
2193        .map(String::as_str)
2194        .collect::<BTreeSet<_>>();
2195    let default_members = metadata
2196        .workspace_default_members
2197        .iter()
2198        .map(String::as_str)
2199        .collect::<BTreeSet<_>>();
2200    if parsed.package.is_none() && default_members.len() != 1 {
2201        bail!(
2202            "Cargo defaults select {} workspace packages; the linked RSJS pipeline accepts one exact package and target. Pass `-p <package>` plus `--bin <name>`, `--example <name>`, or `--test <name>`",
2203            default_members.len(),
2204        );
2205    }
2206    let mut packages = metadata
2207        .packages
2208        .iter()
2209        .filter(|package| workspace_members.contains(package.id.as_str()))
2210        .filter(|package| match &parsed.package {
2211            Some(selector) => cargo_package_matches(package, selector),
2212            None => default_members.contains(package.id.as_str()),
2213        })
2214        .collect::<Vec<_>>();
2215    packages.sort_by(|left, right| left.id.cmp(&right.id));
2216
2217    if packages.is_empty() {
2218        match &parsed.package {
2219            Some(package) => bail!(
2220                "Cargo metadata contains no exact workspace package matching `-p {package}`; package specs must resolve to one workspace package"
2221            ),
2222            None => bail!(
2223                "Cargo metadata has no default workspace member to use as an RSJS root; pass `-p <package>` plus an exact target"
2224            ),
2225        }
2226    }
2227    if parsed.package.is_some() && packages.len() != 1 {
2228        bail!(
2229            "Cargo package selector `{}` matches {} workspace packages; pass one unambiguous package ID and exact target",
2230            parsed.package.as_deref().unwrap_or_default(),
2231            packages.len()
2232        );
2233    }
2234
2235    let mut candidates = Vec::new();
2236    for package in packages {
2237        if !package.manifest_path.is_absolute() {
2238            bail!(
2239                "Cargo package `{}` has a relative manifest path `{}`; exact source-closure diagnostics require an absolute package root",
2240                package.name,
2241                package.manifest_path.display()
2242            );
2243        }
2244        let package_source_root = package.manifest_path.parent().ok_or_else(|| {
2245            anyhow::anyhow!(
2246                "Cargo package `{}` manifest path `{}` has no parent directory",
2247                package.name,
2248                package.manifest_path.display()
2249            )
2250        })?;
2251        for target in &package.targets {
2252            let kinds = target.kind.iter().cloned().collect::<BTreeSet<_>>();
2253            if !kinds.contains(requested_target_kind) {
2254                continue;
2255            }
2256            if !requested_target_name.is_empty() && requested_target_name != target.name {
2257                continue;
2258            }
2259            candidates.push(ExactCargoRoot {
2260                package_id: package.id.clone(),
2261                package_name: package.name.clone(),
2262                package_source_root: package_source_root.to_path_buf(),
2263                target_name: target.name.clone(),
2264                target_kinds: kinds,
2265                requested_target_kind: requested_target_kind.to_string(),
2266            });
2267        }
2268    }
2269    candidates.sort_by(|left, right| {
2270        (&left.package_id, &left.target_name).cmp(&(&right.package_id, &right.target_name))
2271    });
2272
2273    match candidates.len() {
2274        0 => {
2275            if !requested_target_name.is_empty() {
2276                bail!(
2277                    "Cargo metadata contains no `{requested_target_kind}` target named `{requested_target_name}` in the selected package set"
2278                );
2279            }
2280            bail!(
2281                "the selected Cargo package set has no `{requested_target_kind}` target; the linked RSJS pipeline requires one executable root"
2282            );
2283        }
2284        1 => Ok(candidates.remove(0)),
2285        count => {
2286            let rendered = candidates
2287                .iter()
2288                .map(|candidate| format!("{}::{}", candidate.package_name, candidate.target_name))
2289                .collect::<Vec<_>>()
2290                .join(", ");
2291            bail!(
2292                "Cargo selection resolves to {count} `{requested_target_kind}` roots ({rendered}); cargo-proa will not guess. Pass an exact package and target"
2293            );
2294        }
2295    }
2296}
2297
2298fn cargo_package_matches(package: &CargoMetadataPackage, selector: &str) -> bool {
2299    selector == package.id
2300        || selector == package.name
2301        || selector == format!("{}@{}", package.name, package.version)
2302        || selector == format!("{}:{}", package.name, package.version)
2303}
2304
2305fn parse_producer_version(version: &str) -> Result<ProducerVersion> {
2306    let core = version.split_once('-').map_or(version, |(core, _)| core);
2307    let mut parts = core.split('.');
2308    let major = parse_version_part(parts.next(), "major", version)?;
2309    let minor = parse_version_part(parts.next(), "minor", version)?;
2310    let patch = parse_version_part(parts.next(), "patch", version)?;
2311    if parts.next().is_some() {
2312        bail!("unsupported cargo-proa producer version `{version}`");
2313    }
2314    Ok(ProducerVersion::new(major, minor, patch))
2315}
2316
2317fn cli_tool_producer_version() -> Result<ProducerVersion> {
2318    parse_producer_version(env!("CARGO_PKG_VERSION"))
2319}
2320
2321fn parse_version_part(part: Option<&str>, name: &str, version: &str) -> Result<u16> {
2322    part.ok_or_else(|| anyhow::anyhow!("cargo-proa version `{version}` has no {name} component"))?
2323        .parse::<u16>()
2324        .with_context(|| format!("parse cargo-proa {name} version from `{version}`"))
2325}
2326
2327fn tool_version(
2328    program: &OsStr,
2329    args: &[&str],
2330    label: &str,
2331    working_directory: &Path,
2332) -> Result<String> {
2333    let output = Command::new(program)
2334        .args(args)
2335        .current_dir(working_directory)
2336        .output()
2337        .with_context(|| {
2338            format!(
2339                "query {label} version from `{}`",
2340                Path::new(program).display()
2341            )
2342        })?;
2343    if !output.status.success() {
2344        bail!(
2345            "{label} version query failed with {}: {}",
2346            output.status,
2347            String::from_utf8_lossy(&output.stderr).trim()
2348        );
2349    }
2350    let version = String::from_utf8(output.stdout)
2351        .with_context(|| format!("{label} version output is not UTF-8"))?
2352        .trim()
2353        .to_string();
2354    if version.is_empty() {
2355        bail!("{label} version query returned empty output");
2356    }
2357    Ok(version)
2358}
2359
2360fn selected_rustc_version(working_directory: &Path) -> Result<String> {
2361    let rustc = std::env::var_os("RUSTC").unwrap_or_else(|| OsString::from("rustc"));
2362    tool_version(&rustc, &["-vV"], "rustc", working_directory)
2363}
2364
2365fn declared_build_environment() -> BTreeMap<String, DeclaredEnvironmentInput> {
2366    [
2367        "RUSTC",
2368        "RUSTFLAGS",
2369        "CARGO_ENCODED_RUSTFLAGS",
2370        "CARGO_BUILD_TARGET",
2371        "RUSTUP_TOOLCHAIN",
2372    ]
2373    .into_iter()
2374    .map(|name| {
2375        let value = std::env::var_os(name).map(|value| os_value_bytes(&value));
2376        (
2377            name.to_string(),
2378            DeclaredEnvironmentInput {
2379                name: name.to_string(),
2380                value_hash: SemanticHash::derive(&value),
2381            },
2382        )
2383    })
2384    .collect()
2385}
2386
2387#[cfg(unix)]
2388fn os_value_bytes(value: &OsStr) -> Vec<u8> {
2389    use std::os::unix::ffi::OsStrExt;
2390    value.as_bytes().to_vec()
2391}
2392
2393#[cfg(windows)]
2394fn os_value_bytes(value: &OsStr) -> Vec<u8> {
2395    use std::os::windows::ffi::OsStrExt;
2396    value.encode_wide().flat_map(u16::to_le_bytes).collect()
2397}
2398
2399#[cfg(not(any(unix, windows)))]
2400fn os_value_bytes(value: &OsStr) -> Vec<u8> {
2401    value.to_string_lossy().into_owned().into_bytes()
2402}
2403
2404fn absolute_project_root(root: PathBuf) -> Result<PathBuf> {
2405    let root = if root.is_absolute() {
2406        root
2407    } else {
2408        std::env::current_dir()?.join(root)
2409    };
2410    fs::canonicalize(&root)
2411        .with_context(|| format!("resolve absolute Proa project root `{}`", root.display()))
2412}
2413
2414fn fresh_build_nonce() -> String {
2415    let elapsed = SystemTime::now()
2416        .duration_since(UNIX_EPOCH)
2417        .unwrap_or_default()
2418        .as_nanos();
2419    let sequence = RSJS_BUILD_NONCE.fetch_add(1, Ordering::Relaxed);
2420    format!("{}-{elapsed}-{sequence}", std::process::id())
2421}
2422
2423fn print_linked_cargo_output(
2424    action: LinkedCargoAction,
2425    request: &LinkedCargoRequest,
2426    output: &LinkedCargoOutput,
2427) {
2428    println!(
2429        "linked RSJS plan {} for package `{}` binary `{}`",
2430        output.semantic.plan_id, request.root.package_id, request.root.target_name
2431    );
2432    match action {
2433        LinkedCargoAction::Build => println!(
2434            "final Cargo artifacts: {}",
2435            output.final_cargo.target_directory.display()
2436        ),
2437        LinkedCargoAction::Check => println!(
2438            "final Cargo check artifacts: {}",
2439            output.final_cargo.target_directory.display()
2440        ),
2441        LinkedCargoAction::Dev => println!(
2442            "final Cargo dev artifacts: {}",
2443            output.final_cargo.target_directory.display()
2444        ),
2445        LinkedCargoAction::Run => println!(
2446            "final Cargo run artifacts: {}",
2447            output.final_cargo.target_directory.display()
2448        ),
2449        LinkedCargoAction::Test => println!(
2450            "final Cargo test artifacts: {}",
2451            output.final_cargo.target_directory.display()
2452        ),
2453    }
2454}
2455
2456fn run_project_check(root: &Path) -> Result<()> {
2457    let report = scaffold::site_check(Some(root.to_path_buf()))?;
2458    scaffold::print_site_check(&report, false)?;
2459    if !report.errors.is_empty() {
2460        bail!("Proa site check failed");
2461    }
2462
2463    let src = root.join("src");
2464    if src.exists() {
2465        let paths = vec![src];
2466        let format_summary = crate::fmt::format_paths_with_options(&paths, true, true)?;
2467        for diagnostic in &format_summary.diagnostics {
2468            eprint!("{diagnostic}");
2469        }
2470        if !format_summary.changed.is_empty() {
2471            for path in &format_summary.changed {
2472                eprintln!("{}: Proa macro formatting differs", path.display());
2473            }
2474            bail!("Proa formatting check failed");
2475        }
2476        if format_summary
2477            .diagnostics
2478            .iter()
2479            .any(|diag| diag.severity == Severity::Error)
2480        {
2481            bail!("Proa formatting failed");
2482        }
2483
2484        let diagnostics = crate::lint::lint_paths(&paths, crate::lint::LintOptions::default())?;
2485        for diagnostic in &diagnostics {
2486            if diagnostic.severity.rank() >= Severity::Warning.rank() {
2487                eprint!("{diagnostic}");
2488            }
2489        }
2490        if diagnostics
2491            .iter()
2492            .any(|diag| matches!(diag.severity, Severity::Error | Severity::Warning))
2493        {
2494            bail!("Proa check failed");
2495        }
2496    }
2497
2498    Ok(())
2499}
2500
2501pub fn build_assets_for_project(root: &Path) -> Result<()> {
2502    let config = load_project_config(root)?;
2503    build_assets(root, &config)
2504}
2505
2506fn build_assets(root: &Path, config: &ProjectConfig) -> Result<()> {
2507    for asset in config.build.assets() {
2508        build_asset(root, asset)?;
2509    }
2510    Ok(())
2511}
2512
2513fn build_asset(root: &Path, asset: &AssetConfig) -> Result<()> {
2514    let command = asset_command(root, asset)?;
2515    if command.is_empty() {
2516        return Ok(());
2517    }
2518
2519    if asset.kind == "tailwind"
2520        && asset.command.is_empty()
2521        && command
2522            .first()
2523            .is_some_and(|program| program == "tailwindcss")
2524        && !program_available("tailwindcss")
2525    {
2526        if root.join(&asset.output).is_file() {
2527            eprintln!(
2528                "warning: managed Tailwind binary is not cached; preserving prebuilt {}",
2529                asset.output.display()
2530            );
2531            return Ok(());
2532        }
2533        bail!(
2534            "Tailwind output `{}` is missing and the managed compiler is unavailable",
2535            asset.output.display()
2536        );
2537    }
2538
2539    if let Some(output_parent) = asset.output.parent() {
2540        let output_parent = root.join(output_parent);
2541        fs::create_dir_all(&output_parent)
2542            .with_context(|| format!("create {}", output_parent.display()))?;
2543    }
2544
2545    println!("building asset: {}", asset.output.display());
2546    run_command_status(root, &command, "asset command")
2547}
2548
2549fn asset_command(root: &Path, asset: &AssetConfig) -> Result<Vec<String>> {
2550    if !asset.command.is_empty() {
2551        return Ok(asset.command.clone());
2552    }
2553
2554    match asset.kind.as_str() {
2555        "tailwind" => {
2556            if !root.join(&asset.input).exists() {
2557                eprintln!(
2558                    "warning: tailwind input `{}` not found; skipping asset build for `{}`",
2559                    asset.input.display(),
2560                    asset.output.display()
2561                );
2562                return Ok(Vec::new());
2563            }
2564
2565            let mut command = vec![
2566                "tailwindcss".into(),
2567                "-i".into(),
2568                asset.input.display().to_string(),
2569                "-o".into(),
2570                asset.output.display().to_string(),
2571            ];
2572            if let Some(config) = &asset.config {
2573                if root.join(config).exists() {
2574                    command.push("-c".into());
2575                    command.push(config.display().to_string());
2576                }
2577            }
2578            Ok(command)
2579        }
2580        "command" if asset.command.is_empty() => Ok(Vec::new()),
2581        other => bail!("unknown asset kind `{other}` in proa.config.json"),
2582    }
2583}
2584
2585fn program_available(program: &str) -> bool {
2586    let Some(search_path) = env::var_os("PATH") else {
2587        return false;
2588    };
2589    env::split_paths(&search_path).any(|directory| {
2590        let candidate = directory.join(program);
2591        candidate.is_file() || cfg!(windows) && directory.join(format!("{program}.exe")).is_file()
2592    })
2593}
2594
2595fn run_linked_dev_foreground(
2596    root: &Path,
2597    launch: &LinkedDevLaunch,
2598    host: &str,
2599    port: u16,
2600    session: Option<&(u16, String)>,
2601) -> Result<()> {
2602    print_linked_dev_launch(launch);
2603    let status = linked_dev_command(root, launch, host, port, session)
2604        .status()
2605        .with_context(|| {
2606            format!(
2607                "run linked dev executable `{}`",
2608                launch.executable.display()
2609            )
2610        })?;
2611    exit_status_to_result(status, "linked dev server")
2612}
2613
2614fn spawn_linked_dev(
2615    root: &Path,
2616    launch: &LinkedDevLaunch,
2617    host: &str,
2618    port: u16,
2619    session: Option<&(u16, String)>,
2620) -> Result<Child> {
2621    print_linked_dev_launch(launch);
2622    let mut cmd = linked_dev_command(root, launch, host, port, session);
2623    // Put the dev command in its own process group so restarts can stop the
2624    // whole server tree and release its port before activating the next plan.
2625    #[cfg(unix)]
2626    {
2627        use std::os::unix::process::CommandExt;
2628        cmd.process_group(0);
2629    }
2630    cmd.spawn().with_context(|| {
2631        format!(
2632            "spawn linked dev executable `{}`",
2633            launch.executable.display()
2634        )
2635    })
2636}
2637
2638fn linked_dev_command(
2639    root: &Path,
2640    launch: &LinkedDevLaunch,
2641    host: &str,
2642    port: u16,
2643    session: Option<&(u16, String)>,
2644) -> Command {
2645    let mut cmd = Command::new(&launch.executable);
2646    cmd.args(&launch.arguments);
2647    cmd.current_dir(root);
2648    cmd.env("HOST", host);
2649    cmd.env("PORT", port.to_string());
2650    // These two are the whole contract with `proa_framework_axum::serve`, which
2651    // injects the live-reload client only when both are present. A stale
2652    // value inherited from the environment must never survive into a run with
2653    // live reload switched off.
2654    match session {
2655        Some((reload_port, token)) => {
2656            cmd.env(reload::RELOAD_PORT_ENV, reload_port.to_string());
2657            cmd.env(reload::RELOAD_TOKEN_ENV, token);
2658        }
2659        None => {
2660            cmd.env_remove(reload::RELOAD_PORT_ENV);
2661            cmd.env_remove(reload::RELOAD_TOKEN_ENV);
2662        }
2663    }
2664    cmd
2665}
2666
2667fn print_linked_dev_launch(launch: &LinkedDevLaunch) {
2668    println!(
2669        "starting final linked server `{}` with plan {} (descriptor cache {}/{}, final cache {} reused)",
2670        launch.executable.display(),
2671        launch.plan_id,
2672        launch.reused_descriptor_artifacts,
2673        launch.descriptor_artifacts,
2674        launch.reused_final_artifacts,
2675    );
2676}
2677
2678fn run_command_status(root: &Path, command: &[String], label: &str) -> Result<()> {
2679    println!("running {}", shellish(command));
2680    let status = match command_base(root, command)?.status() {
2681        Ok(status) => status,
2682        // A missing program surfaces as a bare "No such file or directory",
2683        // which reads as a missing input file rather than a tool that was
2684        // never installed. Name the program and say how to get it.
2685        Err(error) if error.kind() == io::ErrorKind::NotFound => {
2686            let program = command.first().map(String::as_str).unwrap_or(label);
2687            bail!("{}", missing_program_message(program));
2688        }
2689        Err(error) => return Err(error).with_context(|| format!("run `{}`", shellish(command))),
2690    };
2691    exit_status_to_result(status, label)
2692}
2693
2694fn missing_program_message(program: &str) -> String {
2695    let hint = match program {
2696        "tailwindcss" => {
2697            "\n  Install Tailwind CSS CLI v4 with the Proa installer:\n  \
2698             curl -fsSL https://proa.so/install.sh | \
2699             sh -s -- --tailwind-only\n  \
2700             Or, on macOS or Linux with Homebrew: brew install tailwindcss"
2701        }
2702        _ => "\n  Install it and make sure it is on PATH, or set an explicit `command` for this asset in proa.config.json.",
2703    };
2704    format!("`{program}` was not found on PATH.{hint}")
2705}
2706
2707fn command_base(root: &Path, command: &[String]) -> Result<Command> {
2708    let Some((program, args)) = command.split_first() else {
2709        bail!("command cannot be empty")
2710    };
2711    let mut cmd = Command::new(program);
2712    cmd.args(args);
2713    cmd.current_dir(root);
2714    Ok(cmd)
2715}
2716
2717fn exit_status_to_result(status: ExitStatus, label: &str) -> Result<()> {
2718    if status.success() {
2719        Ok(())
2720    } else {
2721        bail!("{label} exited with {status}")
2722    }
2723}
2724
2725fn stop_child(child: &mut Child) -> Result<()> {
2726    if child.try_wait()?.is_some() {
2727        return Ok(());
2728    }
2729
2730    #[cfg(unix)]
2731    {
2732        // Signal the whole process group: TERM first so the server can shut
2733        // down gracefully and release its port, then KILL if it lingers.
2734        let group = -(child.id() as i32);
2735        unsafe { libc::kill(group, libc::SIGTERM) };
2736        for _ in 0..20 {
2737            if child.try_wait()?.is_some() {
2738                return Ok(());
2739            }
2740            thread::sleep(Duration::from_millis(100));
2741        }
2742        unsafe { libc::kill(group, libc::SIGKILL) };
2743        let _ = child.wait();
2744        Ok(())
2745    }
2746
2747    #[cfg(not(unix))]
2748    {
2749        child.kill().context("stop dev command")?;
2750        let _ = child.wait();
2751        Ok(())
2752    }
2753}
2754
2755type WatchSnapshot = BTreeMap<PathBuf, FileStamp>;
2756
2757#[derive(Debug, Clone, PartialEq, Eq)]
2758enum DevWatchDecision {
2759    Idle,
2760    Debouncing,
2761    Ready(WatchSnapshot),
2762}
2763
2764#[derive(Debug)]
2765struct DevWatchDebouncer {
2766    committed: WatchSnapshot,
2767    pending: Option<(WatchSnapshot, Duration)>,
2768    delay: Duration,
2769}
2770
2771impl DevWatchDebouncer {
2772    fn new(committed: WatchSnapshot, delay: Duration) -> Self {
2773        Self {
2774            committed,
2775            pending: None,
2776            delay,
2777        }
2778    }
2779
2780    fn observe(&mut self, now: Duration, snapshot: WatchSnapshot) -> DevWatchDecision {
2781        if snapshot == self.committed {
2782            self.pending = None;
2783            return DevWatchDecision::Idle;
2784        }
2785
2786        match &mut self.pending {
2787            Some((pending, first_seen)) if *pending == snapshot => {
2788                if now.saturating_sub(*first_seen) >= self.delay {
2789                    DevWatchDecision::Ready(snapshot)
2790                } else {
2791                    DevWatchDecision::Debouncing
2792                }
2793            }
2794            pending => {
2795                *pending = Some((snapshot, now));
2796                DevWatchDecision::Debouncing
2797            }
2798        }
2799    }
2800
2801    fn commit(&mut self, snapshot: WatchSnapshot) {
2802        self.committed = snapshot;
2803        self.pending = None;
2804    }
2805}
2806
2807fn watch_snapshot(root: &Path, paths: &[PathBuf]) -> Result<WatchSnapshot> {
2808    let mut snapshot = BTreeMap::new();
2809    for rel in paths {
2810        let path = root.join(rel);
2811        if path.exists() {
2812            collect_file_stamps(root, &path, &mut snapshot)?;
2813        }
2814    }
2815    Ok(snapshot)
2816}
2817
2818fn collect_file_stamps(
2819    root: &Path,
2820    path: &Path,
2821    snapshot: &mut BTreeMap<PathBuf, FileStamp>,
2822) -> Result<()> {
2823    let metadata = fs::metadata(path).with_context(|| format!("stat {}", path.display()))?;
2824    if metadata.is_dir() {
2825        if should_ignore_dir(path) {
2826            return Ok(());
2827        }
2828        for entry in fs::read_dir(path).with_context(|| format!("read {}", path.display()))? {
2829            collect_file_stamps(root, &entry?.path(), snapshot)?;
2830        }
2831    } else if metadata.is_file() {
2832        let rel = path.strip_prefix(root).unwrap_or(path).to_path_buf();
2833        snapshot.insert(rel, FileStamp::from_metadata(&metadata));
2834    }
2835    Ok(())
2836}
2837
2838fn should_ignore_dir(path: &Path) -> bool {
2839    matches!(
2840        path.file_name().and_then(|name| name.to_str()),
2841        Some("target" | "node_modules" | ".git")
2842    )
2843}
2844
2845#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2846struct FileStamp {
2847    len: u64,
2848    modified_nanos: u128,
2849}
2850
2851impl FileStamp {
2852    fn from_metadata(metadata: &fs::Metadata) -> Self {
2853        let modified_nanos = metadata
2854            .modified()
2855            .ok()
2856            .and_then(|modified| modified.duration_since(UNIX_EPOCH).ok())
2857            .map(|duration| duration.as_nanos())
2858            .unwrap_or(0);
2859
2860        Self {
2861            len: metadata.len(),
2862            modified_nanos,
2863        }
2864    }
2865}
2866
2867fn shellish(command: &[String]) -> String {
2868    command.join(" ")
2869}
2870
2871#[cfg(test)]
2872mod tests;