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::{
12        atomic::{AtomicBool, AtomicU64, Ordering},
13        Arc,
14    },
15    thread,
16    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
17};
18
19use anyhow::{bail, Context, Result};
20use rsjs_ir::{
21    abi::{AbiVersion, ProducerVersion, SemanticHash},
22    build::{
23        ArtifactRole, BuildToolchain, DeclaredEnvironmentInput, InvocationSpec, RequestedRootTarget,
24    },
25};
26use rsjs_transport::TRANSPORT_FORMAT_VERSION;
27use serde::Deserialize;
28use sha2::{Digest, Sha256};
29
30mod dev_ui;
31mod public_assets;
32mod readiness;
33mod reload;
34
35pub(crate) use public_assets::load_start_manifest;
36
37use reload::{ReloadEvent, ReloadServer};
38
39#[cfg(not(windows))]
40use crate::rsjs::final_compile::snapshot_wrapper_executable;
41use crate::{
42    commands::{db, script, task},
43    config::{
44        load_project_config, AssetConfig, ProjectConfig, DEFAULT_BUILD_COMMAND, DEFAULT_DEV_COMMAND,
45    },
46    diagnostic::Severity,
47    rsjs::build::{
48        DescriptorCargoRequest, DESCRIPTOR_TARGET_POLICY_VERSION,
49        DESCRIPTOR_UNIT_SIDECAR_SCHEMA_VERSION, TOOL_NAMESPACE_DIR,
50    },
51    rsjs::cache::DESCRIPTOR_CACHE_SCHEMA_VERSION,
52    rsjs::final_compile::{prune_final_artifact_snapshot, FinalSnapshotLease},
53    rsjs::pipeline::{
54        run_linked_cargo_cached, run_linked_cargo_cached_with_progress,
55        try_run_optimistic_empty_linked_cargo, DescriptorRootSelector, LinkedCargoOutput,
56        LinkedCargoRequest, LinkedCargoStage, OptimisticLinkedCargoOutcome,
57    },
58    scaffold,
59};
60
61static RSJS_BUILD_NONCE: AtomicU64 = AtomicU64::new(0);
62static TEST_INTERRUPTED: AtomicBool = AtomicBool::new(false);
63const RSJS_COMPILER_ABI: AbiVersion = AbiVersion::new(1, 1);
64const RSJS_RUNTIME_PROTOCOL: AbiVersion = AbiVersion::new(1, 0);
65const RSJS_COMPILER_PRODUCER: ProducerVersion = ProducerVersion::new(0, 2, 0);
66const RSJS_WRAPPER_EXECUTABLE_FINGERPRINT_DOMAIN: &[u8] = b"proa.rsjs.wrapper-executable.v1\0";
67const PERSISTENT_DESCRIPTOR_TARGET_LAYOUT_VERSION: u16 = 1;
68const DEV_WATCH_POLL: Duration = Duration::from_millis(50);
69/// Editors write in bursts (temp file, rename, mtime touch) and formatters
70/// rewrite whole trees, so the loop waits for one quiet window before paying
71/// for a Cargo cycle. Vite and webpack sit in the same 100-300ms range.
72pub const DEV_WATCH_DEBOUNCE: Duration = Duration::from_millis(100);
73/// Refuse debounce windows shorter than one poll interval: they would claim a
74/// precision the poller cannot deliver.
75const DEV_WATCH_MIN_DEBOUNCE: Duration = DEV_WATCH_POLL;
76/// How long startup and restart probes wait for the server. A startup timeout
77/// leaves the browser closed and a restart timeout reports a failed reload.
78const DEV_READY_TIMEOUT: Duration = Duration::from_secs(20);
79
80pub struct DevOptions {
81    pub root: Option<PathBuf>,
82    pub host: Option<String>,
83    pub port: Option<u16>,
84    pub watch: Vec<PathBuf>,
85    pub open: bool,
86    pub offline: bool,
87    pub no_assets: bool,
88    pub hot_static: bool,
89    pub no_restart: bool,
90    pub no_reload: bool,
91    pub no_css_hot_swap: bool,
92    pub reload_port: Option<u16>,
93    pub debounce_ms: Option<u64>,
94    pub verbose: bool,
95    pub command: Vec<String>,
96}
97
98pub struct BuildOptions {
99    pub root: Option<PathBuf>,
100    pub profile: Option<String>,
101    pub package: Option<String>,
102    pub bin: Option<String>,
103    pub example: 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    pub no_check: bool,
111    pub no_assets: bool,
112    pub artifact_out: Option<PathBuf>,
113    pub command: Vec<String>,
114}
115
116pub struct CheckOptions {
117    pub root: Option<PathBuf>,
118    pub profile: Option<String>,
119    pub package: Option<String>,
120    pub bin: Option<String>,
121    pub target: Option<String>,
122    pub features: Vec<String>,
123    pub all_features: bool,
124    pub no_default_features: bool,
125    pub locked: bool,
126    pub offline: bool,
127}
128
129pub struct RunOptions {
130    pub root: Option<PathBuf>,
131    pub profile: Option<String>,
132    pub package: Option<String>,
133    pub bin: Option<String>,
134    pub target: Option<String>,
135    pub features: Vec<String>,
136    pub all_features: bool,
137    pub no_default_features: bool,
138    pub locked: bool,
139    pub offline: bool,
140    pub arguments: Vec<String>,
141}
142
143#[derive(Clone)]
144pub struct TestOptions {
145    pub root: Option<PathBuf>,
146    pub profile: Option<String>,
147    pub package: Option<String>,
148    pub bin: Option<String>,
149    pub test: Option<String>,
150    pub target: Option<String>,
151    pub features: Vec<String>,
152    pub all_features: bool,
153    pub no_default_features: bool,
154    pub locked: bool,
155    pub offline: bool,
156    pub watch: bool,
157    pub watch_paths: Vec<PathBuf>,
158    pub keep_database: bool,
159    pub arguments: Vec<String>,
160}
161
162#[derive(Debug)]
163struct LinkedDevLaunch {
164    executable: PathBuf,
165    arguments: Vec<OsString>,
166    plan_id: String,
167    single_pass: bool,
168    descriptor_artifacts: usize,
169    reused_descriptor_artifacts: usize,
170    reused_final_artifacts: usize,
171    public_assets: Option<PathBuf>,
172    compiled_inputs: Option<BTreeSet<PathBuf>>,
173    /// Keeps `executable` from being pruned by another session while this
174    /// launch is current. Dropped before this session prunes it.
175    _snapshot_lease: Option<Arc<FinalSnapshotLease>>,
176}
177
178/// State that one `proa dev` watch session carries between rebuilds.
179///
180/// Tool versions are deliberately not cached: they run in parallel with
181/// `cargo metadata`, so caching saves no wall time, and a toolchain switch
182/// mid-session would otherwise key new artifacts under the old toolchain.
183#[derive(Debug, Default)]
184struct DevSessionCache {
185    allow_optimistic_empty: bool,
186    #[cfg(not(windows))]
187    wrapper_snapshot: Option<CachedWrapperSnapshot>,
188}
189
190#[cfg(not(windows))]
191#[derive(Debug, Clone)]
192struct CachedWrapperSnapshot {
193    source_path: PathBuf,
194    source_stamp: FileStamp,
195    snapshot_root: PathBuf,
196    snapshot_path: PathBuf,
197    fingerprint: String,
198}
199
200impl DevSessionCache {
201    fn for_dev_watch(root: &Path) -> Self {
202        Self {
203            allow_optimistic_empty: !project_mentions_rsjs_macros(root),
204            ..Self::default()
205        }
206    }
207}
208
209struct LinkedDevRebuild {
210    config: ProjectConfig,
211    snapshot: WatchSnapshot,
212    launch: LinkedDevLaunch,
213    hot_state: Option<crate::hot_static::HotState>,
214}
215
216pub fn dev(options: DevOptions) -> Result<()> {
217    // A one-shot run has no change cycles to summarize.
218    dev_ui::enable(options.verbose || options.no_restart);
219    let root = absolute_project_root(scaffold::resolve_root(options.root.clone())?)?;
220    let mut runner = crate::config::DevConfigRunner::default();
221    let mut config = crate::config::load_project_config_with_runner(&root, Some(&mut runner))?;
222    script::hint("dev", &config.scripts.dev, DEFAULT_DEV_COMMAND);
223    let listen = resolve_dev_address(options.host.as_deref(), options.port, |name| {
224        std::env::var(name).ok()
225    })?;
226    let address = (listen.host.as_str(), listen.port);
227    // Reject an impossible watch window before anything is built, bound, or
228    // spawned. A flag error should cost nothing to recover from.
229    let debounce = dev_watch_debounce(&options)?;
230    let command = dev_command(&options, &config);
231    install_dev_signal_handler();
232
233    dev_ui::header(&dev_url(address.0, address.1));
234    dev_ui::detail!("Proa dev root: {}", root.display());
235    for note in &listen.notes {
236        dev_ui::detail!("{note}");
237    }
238    dev_ui::detail!("Building your site. The first build downloads dependencies and compiles crates; this can take several minutes.");
239    if options.open {
240        dev_ui::detail!("The browser will open when the server is ready.");
241    }
242    task::run_lifecycle_tasks(&root, &config, &config.scripts.before.dev, &BTreeMap::new())?;
243
244    if options.no_restart {
245        if !options.no_assets {
246            build_assets(&root, &config)?;
247        }
248        let hot_state = hot_scan_or_rustc_diagnostics(
249            &root,
250            &config,
251            &command,
252            None,
253            options
254                .hot_static
255                .then(|| crate::hot_static::HotState::prepare(&root))
256                .transpose(),
257        )?;
258        let source = public_assets::configured_path(&config, !options.no_assets)?;
259        let launch =
260            run_linked_dev_cycle(&root, &config, &command, hot_state.as_ref(), source, None)?;
261        return run_linked_dev_foreground(&root, &launch, address.0, address.1, options.open);
262    }
263
264    // Live reload is a watch-mode feature. Without restarts there is nothing
265    // to announce, so a one-shot run never pays for the event server.
266    let reload = start_reload_server(address, &options);
267    let mut session = DevSessionCache::for_dev_watch(&root);
268
269    if !options.no_assets {
270        build_assets(&root, &config)?;
271    }
272    let mut watch_paths = dev_watch_paths(&config, &options)?;
273    let baseline = watch_snapshot(&root, &watch_paths)?;
274    let mut hot_state = hot_scan_or_rustc_diagnostics(
275        &root,
276        &config,
277        &command,
278        None,
279        options
280            .hot_static
281            .then(|| crate::hot_static::HotState::prepare(&root))
282            .transpose(),
283    )?;
284    let source = public_assets::configured_path(&config, !options.no_assets)?;
285    let mut launch = run_linked_dev_cycle(
286        &root,
287        &config,
288        &command,
289        hot_state.as_ref(),
290        source,
291        Some(&mut session),
292    )?;
293    let mut child = spawn_linked_dev(&root, &launch, address.0, address.1, reload.as_ref())?;
294    announce_dev_start(options.open, address.0, address.1, &mut child);
295
296    let clock = Instant::now();
297    let mut debouncer = DevWatchDebouncer::new(baseline, debounce);
298    let mut retry_catalog_at = Instant::now();
299    let mut last_build_failed = false;
300
301    loop {
302        if let Some(status) = child.process.try_wait().context("poll linked dev server")? {
303            clear_active_child_group();
304            return exit_status_to_result(status, "linked dev server");
305        }
306
307        thread::sleep(debouncer.next_poll_delay(clock.elapsed()));
308        let current = watch_snapshot(&root, &watch_paths)?;
309        // Observe only disappearance. Publishing atomically replaces the manifest,
310        // and neither that write nor ordinary Cargo activity should trigger a build.
311        let missing_catalog = launch
312            .public_assets
313            .as_ref()
314            .is_some_and(|output| !output.join(proa_assets::MANIFEST_FILE).is_file());
315        let trigger_snapshot = match debouncer.observe(clock.elapsed(), current) {
316            DevWatchDecision::Ready(changed) => changed,
317            // Disappearing output can trigger recovery on idle inputs, but a
318            // failed build already recorded those inputs. A later edit must
319            // take the normal debounced path before attempting another build.
320            DevWatchDecision::Idle
321                if missing_catalog && !last_build_failed && Instant::now() >= retry_catalog_at =>
322            {
323                retry_catalog_at = Instant::now() + Duration::from_secs(2);
324                if launch.executable.is_file() {
325                    let output = launch
326                        .public_assets
327                        .as_ref()
328                        .expect("missing active catalog");
329                    let source = public_assets::configured_path(&config, true)?;
330                    match public_assets::publish(&root, source, output) {
331                        Ok(Some(_)) => {
332                            dev_ui::detail!("restored the public asset catalog without Cargo");
333                            dev_ui::outcome("Public assets restored");
334                            // A recreated catalog has a new reader lock. Reopen it.
335                            child.restart(&root, &launch, address, None, reload.as_ref())?;
336                            retry_catalog_at = Instant::now();
337                            continue;
338                        }
339                        Ok(None) => {}
340                        Err(error) => {
341                            eprintln!("could not restore the public asset catalog: {error:#}");
342                            notify(reload.as_ref(), &ReloadEvent::Failed(format!("{error:#}")));
343                            continue;
344                        }
345                    }
346                }
347                // Rebuild when the executable or the default public directory vanished.
348                debouncer.committed.clone()
349            }
350            _ => continue,
351        };
352
353        notify(reload.as_ref(), &ReloadEvent::Building);
354        dev_ui::changed(&changed_paths(&debouncer.committed, &trigger_snapshot));
355        let mut failure_snapshot = trigger_snapshot;
356        // The cached runner rechecks rustc's recorded inputs and Cargo settings
357        // itself, so any edit that leaves them untouched skips the runner build.
358        let evaluated = crate::config::load_project_config_with_runner(&root, Some(&mut runner));
359        let inputs = evaluated.and_then(|next| {
360            prepare_dev_inputs_with_compiled_inputs(
361                &root,
362                next,
363                &options,
364                &debouncer.committed,
365                hot_state.as_ref(),
366                launch.compiled_inputs.as_ref(),
367                &mut failure_snapshot,
368                &mut watch_paths,
369                if last_build_failed {
370                    AssetState::Unknown
371                } else {
372                    AssetState::Current
373                },
374            )
375        });
376        let inputs = match inputs {
377            Ok(inputs) => inputs,
378            Err(error) => {
379                last_build_failed = true;
380                if dev_ui::pretty() {
381                    dev_ui::fail("Could not prepare the build", Some(&format!("{error:#}")));
382                } else {
383                    eprintln!(
384                        "dev preparation failed; keeping the last valid server running:\n{error:#}"
385                    );
386                }
387                notify(reload.as_ref(), &ReloadEvent::Failed(format!("{error:#}")));
388                debouncer.commit(failure_snapshot);
389                continue;
390            }
391        };
392        let PreparedDevInputs {
393            config: next_config,
394            snapshot,
395            css_only,
396            public_assets_only,
397            changed_asset_paths,
398            hot_update,
399            deferred_assets,
400        } = inputs;
401        if css_only && !missing_catalog {
402            dev_ui::detail!("stylesheet change stabilized; rebuilt assets without restarting");
403            dev_ui::outcome("Styles updated");
404            dev_ui::finish();
405            debouncer.commit(snapshot);
406            notify(reload.as_ref(), &ReloadEvent::Css);
407            continue;
408        }
409        if public_assets_only
410            && !last_build_failed
411            && serde_json::to_vec(&next_config).ok() == serde_json::to_vec(&config).ok()
412            && launch.executable.is_file()
413            && launch.compiled_inputs.as_ref().is_some_and(|inputs| {
414                changed_asset_paths
415                    .iter()
416                    .all(|path| !is_compiled_input(&root, inputs, path))
417            })
418        {
419            if let Some(output) = launch.public_assets.as_ref() {
420                let source = public_assets::configured_path(&next_config, !options.no_assets)?;
421                match public_assets::publish(&root, source, output) {
422                    Ok(Some(_)) => {
423                        let stylesheet_only = is_stylesheet_only_change(&changed_asset_paths);
424                        dev_ui::outcome(if stylesheet_only {
425                            "Styles updated"
426                        } else {
427                            "Assets updated"
428                        });
429                        // Only a server that registered as a live reader
430                        // follows this publication. One that loaded a fixed
431                        // catalog, was built against a framework release
432                        // without in-place reloading, has exited, or is still
433                        // starting would keep serving the previous files, so
434                        // it is restarted exactly as before.
435                        let can_hot_swap = !(stylesheet_only && options.no_css_hot_swap)
436                            && public_assets::has_live_reader(output);
437                        if can_hot_swap {
438                            dev_ui::detail!(
439                                "public assets changed; republished catalog in place without restarting"
440                            );
441                            dev_ui::finish();
442                            debouncer.commit(snapshot);
443                            notify(
444                                reload.as_ref(),
445                                if stylesheet_only {
446                                    &ReloadEvent::Css
447                                } else {
448                                    &ReloadEvent::Reload
449                                },
450                            );
451                        } else {
452                            dev_ui::detail!(
453                                "public assets changed; republished catalog without Cargo"
454                            );
455                            child.restart(&root, &launch, address, None, reload.as_ref())?;
456                            debouncer.commit(snapshot);
457                        }
458                        continue;
459                    }
460                    Ok(None) => {}
461                    Err(error) => {
462                        last_build_failed = true;
463                        if dev_ui::pretty() {
464                            dev_ui::fail(
465                                "Could not publish public assets",
466                                Some(&format!("{error:#}")),
467                            );
468                        } else {
469                            eprintln!(
470                                "could not republish the public asset catalog; keeping the last valid server running:\n{error:#}"
471                            );
472                        }
473                        notify(reload.as_ref(), &ReloadEvent::Failed(format!("{error:#}")));
474                        debouncer.commit(failure_snapshot);
475                        continue;
476                    }
477                }
478            }
479        }
480        if let Some(mut update) = hot_update.filter(|_| !missing_catalog) {
481            match update.activate() {
482                Ok(()) => {
483                    dev_ui::detail!(
484                        "static template change stabilized; published without Cargo or restart"
485                    );
486                    dev_ui::outcome("Updated");
487                    dev_ui::finish();
488                    hot_state = Some(update);
489                    debouncer.commit(snapshot);
490                    notify(reload.as_ref(), &ReloadEvent::Reload);
491                    continue;
492                }
493                Err(error) => {
494                    eprintln!("static publication failed; using the linked rebuild: {error:#}")
495                }
496            }
497        }
498        dev_ui::detail!("change stabilized; rebuilding linked RSJS dev server");
499        let rebuild = (|| -> Result<LinkedDevRebuild> {
500            let command = dev_command(&options, &next_config);
501            // Capture the exact source/config state handed to this cycle after
502            // asset generation. A change during Cargo will differ on the next
503            // poll and schedule another cycle rather than being swallowed.
504            let mut cycle_snapshot = watch_snapshot(&root, &watch_paths)?;
505            failure_snapshot = cycle_snapshot.clone();
506            // Stage after tasks/assets may have generated Rust sources,
507            // and after the committed snapshot. An edit during staging or
508            // Cargo must differ from that snapshot on the next poll.
509            let next_hot_state = hot_scan_or_rustc_diagnostics(
510                &root,
511                &next_config,
512                &command,
513                hot_state.as_ref(),
514                hot_state
515                    .as_ref()
516                    .map(|state| state.candidate(&root))
517                    .transpose(),
518            )?;
519            let source = public_assets::configured_path(&next_config, !options.no_assets)?;
520            let launch = run_linked_dev_cycle_with_assets(
521                &root,
522                &next_config,
523                &command,
524                next_hot_state.as_ref(),
525                source,
526                Some(&mut session),
527                deferred_assets.as_deref(),
528            );
529            if let (Some(_), Some(public)) = (&deferred_assets, source) {
530                // Advance generated public outputs (e.g. Tailwind's CSS)
531                // written while Cargo ran, whether or not Cargo succeeded, so
532                // the next poll does not schedule a cycle for output this one
533                // already produced.
534                match watch_snapshot(&root, &watch_paths) {
535                    Ok(post_assets) => {
536                        for output in declared_asset_outputs(&next_config) {
537                            if output.starts_with(public) {
538                                if let Some(stamp) = post_assets.get(&output) {
539                                    cycle_snapshot.insert(output.clone(), *stamp);
540                                    failure_snapshot.insert(output, *stamp);
541                                }
542                            }
543                        }
544                    }
545                    Err(error) if launch.is_ok() => return Err(error),
546                    Err(_) => {}
547                }
548            }
549            let launch = launch?;
550            Ok(LinkedDevRebuild {
551                config: next_config,
552                snapshot: cycle_snapshot,
553                launch,
554                hot_state: next_hot_state,
555            })
556        })();
557
558        match rebuild {
559            Ok(LinkedDevRebuild {
560                config: next_config,
561                snapshot: cycle_snapshot,
562                launch: next_launch,
563                hot_state: mut next_hot_state,
564            }) => {
565                dev_ui::detail!(
566                    "linked dev rebuild succeeded; gracefully stopping the previous server before activating plan {}",
567                    next_launch.plan_id
568                );
569                child.restart(
570                    &root,
571                    &next_launch,
572                    address,
573                    next_hot_state.as_mut(),
574                    reload.as_ref(),
575                )?;
576                // The previous server has exited. Release its snapshot lease,
577                // then remove that snapshot unless another command holds it,
578                // so repeated saves keep one dev executable on disk.
579                let previous = std::mem::replace(&mut launch, next_launch);
580                if previous.executable != launch.executable {
581                    let superseded = previous.executable.clone();
582                    drop(previous);
583                    prune_final_artifact_snapshot(&superseded);
584                }
585                config = next_config;
586                retry_catalog_at = Instant::now();
587                last_build_failed = false;
588                hot_state = next_hot_state;
589                debouncer = DevWatchDebouncer::new(cycle_snapshot, debounce);
590            }
591            Err(error) => {
592                last_build_failed = true;
593                if dev_ui::pretty() {
594                    // The compiler already printed its own diagnostics.
595                    let detail = format!("{error:#}");
596                    let compiler = detail.contains("Cargo compilation failed")
597                        || detail.contains("compiler diagnostic above");
598                    dev_ui::fail("Build failed", (!compiler).then_some(detail.as_str()));
599                } else {
600                    eprintln!(
601                        "linked dev rebuild failed; keeping the last valid server running:\n{error:#}"
602                    );
603                }
604                notify(reload.as_ref(), &ReloadEvent::Failed(format!("{error:#}")));
605                // Do not spin on unchanged broken input. The next source,
606                // feature, cfg, or configuration change schedules a new cycle.
607                debouncer.commit(failure_snapshot);
608            }
609        }
610    }
611}
612
613struct PreparedDevInputs {
614    config: ProjectConfig,
615    snapshot: WatchSnapshot,
616    css_only: bool,
617    public_assets_only: bool,
618    changed_asset_paths: Vec<PathBuf>,
619    hot_update: Option<crate::hot_static::HotState>,
620    deferred_assets: Option<Vec<PathBuf>>,
621}
622
623/// What is known about generated assets when a change cycle starts.
624#[derive(Clone, Copy, PartialEq, Eq)]
625enum AssetState {
626    /// The previous cycle ran to completion, asset commands included.
627    Current,
628    /// The previous cycle failed somewhere. An asset command may never have
629    /// produced output for the sources as they are now, so nothing is skipped.
630    Unknown,
631}
632
633#[cfg(test)]
634#[allow(clippy::too_many_arguments)]
635fn prepare_dev_inputs(
636    root: &Path,
637    config: ProjectConfig,
638    options: &DevOptions,
639    committed: &WatchSnapshot,
640    hot_state: Option<&crate::hot_static::HotState>,
641    failure_snapshot: &mut WatchSnapshot,
642    watch_paths: &mut Vec<PathBuf>,
643    assets: AssetState,
644) -> Result<PreparedDevInputs> {
645    prepare_dev_inputs_with_compiled_inputs(
646        root,
647        config,
648        options,
649        committed,
650        hot_state,
651        None,
652        failure_snapshot,
653        watch_paths,
654        assets,
655    )
656}
657
658#[allow(clippy::too_many_arguments)]
659fn prepare_dev_inputs_with_compiled_inputs(
660    root: &Path,
661    config: ProjectConfig,
662    options: &DevOptions,
663    committed: &WatchSnapshot,
664    hot_state: Option<&crate::hot_static::HotState>,
665    compiled_inputs: Option<&BTreeSet<PathBuf>>,
666    failure_snapshot: &mut WatchSnapshot,
667    watch_paths: &mut Vec<PathBuf>,
668    assets: AssetState,
669) -> Result<PreparedDevInputs> {
670    // Failure snapshots must use the same watch set as the next poll, even
671    // when a config edit changes watched paths and preparation then fails.
672    *watch_paths = dev_watch_paths(&config, options)?;
673    let tasks =
674        task::run_lifecycle_tasks(root, &config, &config.scripts.before.dev, &BTreeMap::new());
675    // Include generated writes from pre-dev tasks, even if a task fails. Capture
676    // before scanning/publishing templates or running asset commands so edits
677    // during those operations still schedule another cycle.
678    let mut snapshot = watch_snapshot(root, watch_paths)?;
679    *failure_snapshot = snapshot.clone();
680    tasks?;
681    let changed = changed_paths(committed, &snapshot);
682    let public = public_assets::configured_path(&config, !options.no_assets)?;
683    let managed_public = public.is_some_and(|path| {
684        path != Path::new(crate::config::DEFAULT_PUBLIC_DIRECTORY) || root.join(path).exists()
685    });
686    let mut css_only = !managed_public
687        && !options.no_css_hot_swap
688        && !options.no_assets
689        && is_stylesheet_only_change(&changed);
690    let mut hot_update = if css_only {
691        None
692    } else if let Some(state) = hot_state {
693        match state.prepare_update(root, &changed) {
694            Ok(update) => update,
695            Err(error) => {
696                eprintln!("static update rejected; using the linked rebuild: {error:#}");
697                None
698            }
699        }
700    } else {
701        None
702    };
703    let generated_public_before = if hot_update.is_some() {
704        public
705            .filter(|public| !changed.iter().any(|path| path.starts_with(public)))
706            .map(|public| snapshot_generated_public_outputs(root, &config, public, &snapshot))
707            .transpose()?
708    } else {
709        None
710    };
711    let defer_assets = !options.no_assets
712        && !css_only
713        && hot_update.is_none()
714        && assets == AssetState::Current
715        && can_defer_assets_for_parallel_cargo(root, &config, public, &changed, compiled_inputs);
716    if !options.no_assets && !defer_assets {
717        let skippable = public.filter(|_| assets == AssetState::Current);
718        build_assets_for_change(root, &config, skippable, &changed)?;
719    }
720    let mut public_assets_only = false;
721    let mut changed_asset_paths = Vec::new();
722    if let Some(public) = public {
723        if !defer_assets {
724            let post_assets = if managed_public || root.join(public).exists() {
725                Some(watch_snapshot(root, watch_paths)?)
726            } else {
727                None
728            };
729            let post_changed = post_assets
730                .as_ref()
731                .map(|post_assets| changed_paths(committed, post_assets));
732            let changed_public: Vec<&PathBuf> = post_changed
733                .as_deref()
734                .unwrap_or(&changed)
735                .iter()
736                .filter(|path| path.starts_with(public))
737                .collect();
738            let public_changed = if changed_public.is_empty() {
739                false
740            } else if let (Some(before), Some(post_assets)) =
741                (&generated_public_before, &post_assets)
742            {
743                if all_unchanged_generated_outputs(root, &changed_public, before, post_assets)? {
744                    // Declared asset outputs (such as Tailwind's stylesheet) may be
745                    // rewritten with identical bytes and a newer mtime. Advance only
746                    // those verified stamps so authored saves are never swallowed.
747                    for path in &changed_public {
748                        if let Some(stamp) = post_assets.get(*path) {
749                            snapshot.insert((*path).clone(), *stamp);
750                        }
751                    }
752                    false
753                } else {
754                    true
755                }
756            } else {
757                true
758            };
759            if public_changed {
760                // The running server holds a fixed public catalog. Restart it when
761                // inputs (including generated files) change. Keep the pre-command
762                // snapshot for authored files outside `public/` so concurrent edits
763                // still schedule another cycle.
764                hot_update = None;
765                css_only = false;
766                if managed_public
767                    && !changed.is_empty()
768                    && changed
769                        .iter()
770                        .all(|path| is_css_or_public_or_asset_input(path, public, &config))
771                    && post_changed
772                        .as_deref()
773                        .unwrap_or(&changed)
774                        .iter()
775                        .all(|path| is_css_or_public_or_asset_input(path, public, &config))
776                {
777                    public_assets_only = true;
778                    changed_asset_paths = changed.clone();
779                    if let Some(post_changed) = &post_changed {
780                        for path in post_changed {
781                            if !changed_asset_paths.contains(path) {
782                                changed_asset_paths.push(path.clone());
783                            }
784                        }
785                    }
786                    if let Some(post_assets) = &post_assets {
787                        for path in &changed_public {
788                            if let Some(stamp) = post_assets.get(*path) {
789                                snapshot.insert((*path).clone(), *stamp);
790                            } else {
791                                snapshot.remove(*path);
792                            }
793                        }
794                    }
795                }
796            }
797        }
798    }
799    Ok(PreparedDevInputs {
800        config,
801        snapshot,
802        css_only,
803        public_assets_only,
804        changed_asset_paths,
805        hot_update,
806        deferred_assets: defer_assets.then_some(changed),
807    })
808}
809
810fn declared_asset_outputs(config: &ProjectConfig) -> Vec<PathBuf> {
811    let mut outputs = Vec::new();
812    if let Some(output) = crate::config::css_script_output(config) {
813        outputs.push(output);
814    }
815    for asset in config.build.assets() {
816        if !outputs.contains(&asset.output) {
817            outputs.push(asset.output.clone());
818        }
819    }
820    outputs
821}
822
823/// Asset commands (like Tailwind CSS) can run concurrently with Cargo on Rust
824/// edits when the previous build's dep-info proved none of the declared asset
825/// outputs are compiled into the binary (e.g. via `include_str!`).
826fn can_defer_assets_for_parallel_cargo(
827    root: &Path,
828    config: &ProjectConfig,
829    public: Option<&Path>,
830    changed: &[PathBuf],
831    compiled_inputs: Option<&BTreeSet<PathBuf>>,
832) -> bool {
833    let Some(inputs) = compiled_inputs else {
834        return false;
835    };
836    let outputs = declared_asset_outputs(config);
837    if outputs.is_empty() || changed.is_empty() {
838        return false;
839    }
840    let has_non_asset_change = changed.iter().any(|path| {
841        public.map_or_else(
842            || {
843                !path
844                    .extension()
845                    .and_then(OsStr::to_str)
846                    .is_some_and(|ext| ext.eq_ignore_ascii_case("css"))
847            },
848            |public| !is_css_or_public_or_asset_input(path, public, config),
849        )
850    });
851    has_non_asset_change
852        && outputs
853            .iter()
854            .all(|output| !is_compiled_input(root, inputs, output))
855}
856
857/// Whether a finished build's recorded inputs prove it embeds no declared
858/// asset output. Unknown inputs prove nothing.
859fn build_excludes_asset_outputs(
860    root: &Path,
861    config: &ProjectConfig,
862    final_root_inputs: Option<&[PathBuf]>,
863) -> bool {
864    collect_compiled_source_inputs_from_paths(final_root_inputs).is_some_and(|inputs| {
865        declared_asset_outputs(config)
866            .iter()
867            .all(|output| !is_compiled_input(root, &inputs, output))
868    })
869}
870
871/// Fast scheduling hint for `proa dev` watch mode: returns true if any `.rs`
872/// file under `src/` mentions RSJS macro/attribute tokens. Soundness never
873/// depends on this scan because `rsjs_macros` fails closed on unmapped units.
874fn project_mentions_rsjs_macros(root: &Path) -> bool {
875    let src = root.join("src");
876    if !src.is_dir() {
877        return true;
878    }
879    for entry in walkdir::WalkDir::new(src).follow_links(false) {
880        let Ok(entry) = entry else {
881            return true;
882        };
883        if !entry.file_type().is_file() || entry.path().extension() != Some(OsStr::new("rs")) {
884            continue;
885        }
886        let Ok(content) = fs::read_to_string(entry.path()) else {
887            return true;
888        };
889        if content.contains("#[rsjs")
890            || content.contains("rsjs::")
891            || content.contains("SharedState")
892        {
893            return true;
894        }
895    }
896    false
897}
898
899fn start_reload_server(address: (&str, u16), options: &DevOptions) -> Option<ReloadServer> {
900    if options.no_reload {
901        dev_ui::detail!("Proa dev live reload: off");
902        dev_ui::reload("off");
903        return None;
904    }
905
906    // Zero asks the operating system for a free port. A fixed offset from the
907    // dev port would quietly claim the port the developer's next site wants,
908    // and that site would then fail to bind with an error naming neither live
909    // reload nor the process holding it. Tabs do not need the port to be
910    // stable: one whose stream endpoint has moved reloads itself and picks up
911    // the current one from the page.
912    let requested = options.reload_port.unwrap_or_default();
913    if requested != 0 && requested == address.1 {
914        eprintln!(
915            "Proa dev live reload: off (--reload-port {requested} is the port the site itself uses)"
916        );
917        dev_ui::reload("off");
918        return None;
919    }
920    match ReloadServer::bind(address.0, requested) {
921        Ok(server) => {
922            dev_ui::detail!("Proa dev live reload: on (port {})", server.port());
923            dev_ui::reload("on");
924            Some(server)
925        }
926        Err(error) => {
927            // A dev loop that still rebuilds is far more useful than one that
928            // refuses to start because a port was unavailable.
929            eprintln!("Proa dev live reload: off ({error:#})");
930            dev_ui::reload("off");
931            None
932        }
933    }
934}
935
936/// Where `proa dev` asks the server to listen, and why.
937#[derive(Debug, PartialEq, Eq)]
938struct DevAddress {
939    host: String,
940    port: u16,
941    /// What an environment variable decided, or why one was passed over.
942    notes: Vec<String>,
943}
944
945/// Flags win, then the environment, then `127.0.0.1:3000`.
946///
947/// `PROA_HOST` and `PORT` are the variables the server itself reads, so a
948/// shell, container, or process manager that exports them gets the same
949/// address from `proa dev` as from `proa start`. `HOST` is honored too, but
950/// only when it can be a listen address: shells and toolchains export it for
951/// their own purposes (a machine name, a compiler target triple), and binding
952/// the dev server to whatever that happens to resolve to would be a surprise.
953fn resolve_dev_address(
954    host_flag: Option<&str>,
955    port_flag: Option<u16>,
956    env: impl Fn(&str) -> Option<String>,
957) -> Result<DevAddress> {
958    let set = |name: &str| {
959        env(name)
960            .map(|value| value.trim().to_owned())
961            .filter(|value| !value.is_empty())
962    };
963    let mut notes = Vec::new();
964    let host = if let Some(host) = host_flag {
965        host.to_owned()
966    } else if let Some(host) = set("PROA_HOST") {
967        notes.push(format!("Proa dev host: {host} (from PROA_HOST)"));
968        host
969    } else {
970        match set("HOST") {
971            Some(raw) => match normalize_listen_address(&raw) {
972                Some(normalized) => {
973                    if normalized == raw {
974                        notes.push(format!("Proa dev host: {normalized} (from HOST)"));
975                    } else {
976                        notes.push(format!("Proa dev host: {normalized} (from HOST={raw})"));
977                    }
978                    normalized
979                }
980                None => {
981                    notes.push(format!(
982                        "Proa dev host: ignoring HOST=`{raw}` because it is not an IP address or `localhost`; set PROA_HOST or pass --host to listen on a DNS name"
983                    ));
984                    "127.0.0.1".to_owned()
985                }
986            },
987            None => "127.0.0.1".to_owned(),
988        }
989    };
990    let port = match (port_flag, set("PORT")) {
991        (Some(port), _) => port,
992        (None, Some(value)) => {
993            let port = value
994                .parse::<u16>()
995                .ok()
996                .filter(|port| *port != 0)
997                .with_context(|| {
998                    format!(
999                        "invalid PORT environment variable `{value}`: expected a TCP port number (1-65535); pass --port to override it"
1000                    )
1001                })?;
1002            notes.push(format!("Proa dev port: {port} (from PORT)"));
1003            port
1004        }
1005        (None, None) => 3000,
1006    };
1007    Ok(DevAddress { host, port, notes })
1008}
1009
1010/// Accept `HOST` values that name a listen address and normalize them to a
1011/// bare `IpAddr` string so generated servers (`PROA_HOST.parse::<IpAddr>()`)
1012/// can bind without failing on `localhost` or bracketed IPv6 literals.
1013fn normalize_listen_address(host: &str) -> Option<String> {
1014    if host.eq_ignore_ascii_case("localhost") {
1015        return Some("127.0.0.1".to_owned());
1016    }
1017    if let Some(inner) = host
1018        .strip_prefix('[')
1019        .and_then(|rest| rest.strip_suffix(']'))
1020    {
1021        return inner
1022            .parse::<std::net::Ipv6Addr>()
1023            .ok()
1024            .map(|ip| ip.to_string());
1025    }
1026    host.parse::<std::net::IpAddr>()
1027        .ok()
1028        .map(|ip| ip.to_string())
1029}
1030
1031fn dev_watch_debounce(options: &DevOptions) -> Result<Duration> {
1032    let Some(requested) = options.debounce_ms else {
1033        return Ok(DEV_WATCH_DEBOUNCE);
1034    };
1035    let requested = Duration::from_millis(requested);
1036    if requested < DEV_WATCH_MIN_DEBOUNCE {
1037        bail!(
1038            "`--debounce-ms {}` is below the {}ms file-watch poll interval; use {}ms or more",
1039            requested.as_millis(),
1040            DEV_WATCH_POLL.as_millis(),
1041            DEV_WATCH_MIN_DEBOUNCE.as_millis()
1042        );
1043    }
1044    Ok(requested)
1045}
1046
1047fn notify(reload: Option<&ReloadServer>, event: &ReloadEvent) {
1048    if let Some(reload) = reload {
1049        reload.broadcast(event);
1050    }
1051}
1052
1053fn dev_url(host: &str, port: u16) -> String {
1054    use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
1055
1056    match host.trim_matches(['[', ']']).parse::<IpAddr>() {
1057        Ok(IpAddr::V4(address)) => {
1058            let address = if address.is_unspecified() {
1059                Ipv4Addr::LOCALHOST
1060            } else {
1061                address
1062            };
1063            format!("http://{address}:{port}")
1064        }
1065        Ok(IpAddr::V6(address)) => {
1066            let address = if address.is_unspecified() {
1067                Ipv6Addr::LOCALHOST
1068            } else {
1069                address
1070            };
1071            format!("http://[{address}]:{port}")
1072        }
1073        Err(_) => format!("http://{host}:{port}"),
1074    }
1075}
1076
1077fn announce_dev_start(open: bool, host: &str, port: u16, child: &mut DevChild) {
1078    dev_ui::detail!("Waiting for the dev server to be ready...");
1079    if let Some(url) = child.ready_url(host, port) {
1080        dev_ui::detail!("Proa dev ready: {url}");
1081        dev_ui::ready(&url);
1082        if open {
1083            open_url(&url);
1084        }
1085    } else if let Ok(Some(status)) = child.process.try_wait() {
1086        if open || !status.success() {
1087            eprintln!("Proa dev server exited before accepting connections ({status}).");
1088        }
1089    } else {
1090        eprintln!("Proa dev server is still running and has not reported readiness within {}s (configured listener {host}:{port}).", DEV_READY_TIMEOUT.as_secs());
1091    }
1092}
1093
1094fn open_url(url: &str) {
1095    #[cfg(target_os = "macos")]
1096    let mut command = Command::new("open");
1097    #[cfg(target_os = "linux")]
1098    let mut command = Command::new("xdg-open");
1099    #[cfg(target_os = "windows")]
1100    let mut command = {
1101        let mut command = Command::new("rundll32.exe");
1102        command.arg("url.dll,FileProtocolHandler");
1103        command
1104    };
1105    if let Err(error) = command.arg(url).spawn() {
1106        eprintln!("Could not open the browser: {error}. Open {url} manually.");
1107    }
1108}
1109
1110/// Tell tabs to reload, preferably once the replacement server answers.
1111///
1112/// Reloading into a connection-refused error page is the failure mode that
1113/// makes naive live reload feel broken, so readiness is confirmed first.
1114fn announce_reload(reload: Option<&ReloadServer>, host: &str, port: u16, child: &mut DevChild) {
1115    if let Some(url) = child.ready_url(host, port) {
1116        dev_ui::detail!("Proa dev ready: {url}");
1117        dev_ui::ready(&url);
1118        notify(reload, &ReloadEvent::Reload);
1119        return;
1120    }
1121
1122    // A server that exits on boot is a result the developer needs to see.
1123    if let Ok(Some(status)) = child.process.try_wait() {
1124        let detail = format!("the rebuilt server exited with {status}");
1125        eprintln!("live reload: {detail}");
1126        notify(reload, &ReloadEvent::Failed(detail));
1127        return;
1128    }
1129
1130    let detail = format!("the rebuilt server has not reported readiness within {}s (configured listener {host}:{port})", DEV_READY_TIMEOUT.as_secs());
1131    eprintln!("live reload: {detail}");
1132    notify(reload, &ReloadEvent::Failed(detail));
1133}
1134
1135/// Paths whose stamp differs between two snapshots, including deletions.
1136fn changed_paths(before: &WatchSnapshot, after: &WatchSnapshot) -> Vec<PathBuf> {
1137    let mut changed: Vec<PathBuf> = after
1138        .iter()
1139        .filter(|(path, stamp)| before.get(*path) != Some(*stamp))
1140        .map(|(path, _)| path.clone())
1141        .collect();
1142    changed.extend(
1143        before
1144            .keys()
1145            .filter(|path| !after.contains_key(*path))
1146            .cloned(),
1147    );
1148    changed
1149}
1150
1151/// Whether a change set can be served by rebuilding assets alone.
1152///
1153/// Only stylesheets qualify. Anything else, including a Tailwind class edited
1154/// inside a Rust template, changes a compiled input and needs a real rebuild.
1155fn is_stylesheet_only_change(changed: &[PathBuf]) -> bool {
1156    !changed.is_empty()
1157        && changed.iter().all(|path| {
1158            path.extension()
1159                .and_then(OsStr::to_str)
1160                .is_some_and(|extension| extension.eq_ignore_ascii_case("css"))
1161        })
1162}
1163
1164fn is_css_or_public_or_asset_input(path: &Path, public: &Path, config: &ProjectConfig) -> bool {
1165    path.starts_with(public)
1166        || path
1167            .extension()
1168            .and_then(OsStr::to_str)
1169            .is_some_and(|extension| extension.eq_ignore_ascii_case("css"))
1170        || config.build.assets().iter().any(|asset| {
1171            path == asset.input || asset.config.as_deref().is_some_and(|cfg| path == cfg)
1172        })
1173}
1174
1175/// Collect the files and directories Cargo recorded as inputs of the final
1176/// dev executable, with links resolved.
1177///
1178/// Returns `None` when Cargo's dep-info is unavailable or a local build script
1179/// declares no inputs, so asset-only edits fall back to a full linked rebuild.
1180fn collect_compiled_source_inputs(output: &LinkedCargoOutput) -> Option<BTreeSet<PathBuf>> {
1181    collect_compiled_source_inputs_from_paths(output.final_root_inputs.as_deref())
1182}
1183
1184fn collect_compiled_source_inputs_from_paths(
1185    inputs: Option<&[PathBuf]>,
1186) -> Option<BTreeSet<PathBuf>> {
1187    Some(
1188        inputs?
1189            .iter()
1190            .map(|input| input.canonicalize().unwrap_or_else(|_| input.clone()))
1191            .collect(),
1192    )
1193}
1194
1195/// Whether a watched, root-relative path is (or is inside) a compiled input.
1196///
1197/// The watcher reports authored paths, and `public` may be a link to another
1198/// directory, so both sides are compared with links resolved. A path that no
1199/// longer resolves counts as an input.
1200fn is_compiled_input(root: &Path, inputs: &BTreeSet<PathBuf>, path: &Path) -> bool {
1201    let path = root.join(path);
1202    // A deleted file still resolves through its directory.
1203    let resolved = path.canonicalize().or_else(|_| {
1204        let parent = path.parent().unwrap_or(root).canonicalize()?;
1205        Ok::<_, io::Error>(parent.join(path.file_name().unwrap_or_default()))
1206    });
1207    match resolved {
1208        // A declared build-script input can be a directory.
1209        Ok(resolved) => inputs.iter().any(|input| resolved.starts_with(input)),
1210        Err(_) => true,
1211    }
1212}
1213
1214fn default_watch_paths() -> Vec<PathBuf> {
1215    // Cargo.lock can be rewritten by Cargo itself. Watching it restarts the
1216    // dev loop for a change caused by the build.
1217    [
1218        "src",
1219        "styles",
1220        "migrations",
1221        "Cargo.toml",
1222        "build.rs",
1223        crate::config::CONFIG_FILE,
1224        crate::config::LOCK_FILE,
1225    ]
1226    .into_iter()
1227    .map(PathBuf::from)
1228    .collect()
1229}
1230
1231fn dev_watch_paths(config: &ProjectConfig, options: &DevOptions) -> Result<Vec<PathBuf>> {
1232    let mut paths = default_watch_paths();
1233    for path in &options.watch {
1234        if !paths.contains(path) {
1235            paths.push(path.clone());
1236        }
1237    }
1238    if let Some(public) = public_assets::configured_path(config, !options.no_assets)? {
1239        if !paths.iter().any(|path| path == public) {
1240            paths.push(public.to_path_buf());
1241        }
1242    }
1243    Ok(paths)
1244}
1245
1246// The exact final server runs in its own process group so restarts can stop
1247// its whole subprocess tree. That also detaches it from the terminal's
1248// foreground group, so Ctrl-C / SIGTERM on `proa dev` must be forwarded to
1249// the child group by hand or the server would outlive the CLI and keep the
1250// port bound.
1251#[cfg(unix)]
1252static ACTIVE_CHILD_GROUP: std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(0);
1253
1254fn set_active_child_group(child: &Child) {
1255    #[cfg(unix)]
1256    ACTIVE_CHILD_GROUP.store(child.id() as i32, std::sync::atomic::Ordering::SeqCst);
1257    #[cfg(not(unix))]
1258    let _ = child;
1259}
1260
1261fn clear_active_child_group() {
1262    #[cfg(unix)]
1263    ACTIVE_CHILD_GROUP.store(0, std::sync::atomic::Ordering::SeqCst);
1264}
1265
1266#[cfg(unix)]
1267extern "C" fn dev_signal_handler(signal: libc::c_int) {
1268    let pgid = ACTIVE_CHILD_GROUP.load(std::sync::atomic::Ordering::SeqCst);
1269    if pgid > 0 {
1270        unsafe { libc::kill(-pgid, libc::SIGTERM) };
1271    }
1272    unsafe { libc::_exit(128 + signal) };
1273}
1274
1275fn install_dev_signal_handler() {
1276    #[cfg(unix)]
1277    unsafe {
1278        libc::signal(
1279            libc::SIGINT,
1280            dev_signal_handler as extern "C" fn(libc::c_int) as libc::sighandler_t,
1281        );
1282        libc::signal(
1283            libc::SIGTERM,
1284            dev_signal_handler as extern "C" fn(libc::c_int) as libc::sighandler_t,
1285        );
1286    }
1287}
1288
1289fn default_release_export_path(
1290    target_dir: &Path,
1291    target_name: &str,
1292    target_triple: Option<&str>,
1293) -> PathBuf {
1294    let mut filename = OsString::from(target_name);
1295    let suffix = match target_triple {
1296        Some(triple) => {
1297            if triple.contains("windows") {
1298                ".exe"
1299            } else {
1300                ""
1301            }
1302        }
1303        None => std::env::consts::EXE_SUFFIX,
1304    };
1305    if !suffix.is_empty() && !target_name.to_ascii_lowercase().ends_with(suffix) {
1306        filename.push(suffix);
1307    }
1308    match target_triple {
1309        Some(triple) => target_dir.join(triple).join("release").join(filename),
1310        None => target_dir.join("release").join(filename),
1311    }
1312}
1313
1314pub fn build(mut options: BuildOptions) -> Result<()> {
1315    let root = absolute_project_root(scaffold::resolve_root(options.root.clone())?)?;
1316    let config = load_project_config(&root)?;
1317    script::hint("build", &config.scripts.build, DEFAULT_BUILD_COMMAND);
1318    if options.command.is_empty()
1319        && options.package.is_none()
1320        && options.bin.is_none()
1321        && options.example.is_none()
1322    {
1323        options.bin = configured_binary(&config);
1324    }
1325    let command = build_command(&options);
1326    // Validate and resolve the exact Cargo root before running configured asset
1327    // commands. An unsupported deployment command must fail without partially
1328    // executing a build.
1329    let prepared = prepare_linked_cargo_with_environment(
1330        &root,
1331        &command,
1332        LinkedCargoAction::Build,
1333        &rsjs_minify_environment(config.build.minify_rsjs),
1334    )?;
1335    let public_source = public_assets::configured_path(&config, !options.no_assets)?;
1336    let artifact_destination = options
1337        .artifact_out
1338        .as_deref()
1339        .map(|destination| resolve_artifact_output(&root, destination));
1340    if let Some(destination) = artifact_destination.as_deref() {
1341        public_assets::check_bundle_destination(&root, public_source, destination)?;
1342        warn_if_artifact_output_enters_source_closure(
1343            destination,
1344            &prepared.package_source_root,
1345            &prepared.request.descriptor.source_exclusion_directory,
1346        );
1347    }
1348
1349    task::run_lifecycle_tasks(
1350        &root,
1351        &config,
1352        &config.scripts.before.build,
1353        &BTreeMap::new(),
1354    )?;
1355    if !options.no_check {
1356        run_project_check(&root, &config)?;
1357    }
1358    if !options.no_assets {
1359        build_assets(&root, &config)?;
1360    }
1361
1362    println!("running linked RSJS Cargo build: {}", shellish(&command));
1363    let output = run_linked_cargo_cached(&prepared.request, &prepared.descriptor_cache_directory)
1364        .context("linked RSJS build failed")?;
1365    print_linked_cache_reuse(LinkedCargoAction::Build, &output);
1366    print_linked_cargo_output(LinkedCargoAction::Build, &prepared.request, &output);
1367    // An explicit export carries its own catalog beside the executable, so
1368    // only a build without one publishes into the target directory. Cargo's
1369    // own output directory never gets a bundle: a plain `cargo run` would
1370    // pick it up after the public files had moved on.
1371    let published_public_assets = match artifact_destination {
1372        Some(_) => None,
1373        None => public_assets::publish(&root, public_source, &prepared.public_output_directory)?,
1374    };
1375    let target_dir = &prepared.request.descriptor.source_exclusion_directory;
1376    let target_triple = prepared.target_triple.as_deref();
1377    let default_release_destination = (artifact_destination.is_none()
1378        && prepared.profile == "release"
1379        && prepared.request.root.role == ArtifactRole::RootExecutable)
1380        .then(|| {
1381            default_release_export_path(
1382                target_dir,
1383                &prepared.request.root.target_name,
1384                target_triple,
1385            )
1386        });
1387    let export_destination = artifact_destination
1388        .as_deref()
1389        .or(default_release_destination.as_deref());
1390    if let Some(destination) = export_destination {
1391        let source =
1392            select_final_root_executable(&prepared.request, &output, LinkedCargoAction::Build)?;
1393        // The default export never bundles, but an explicit export to the
1394        // same path may have: that catalog must not outlive its executable.
1395        let bundle = if artifact_destination.is_some() {
1396            // Storing the modules is what lets a static host serve them. The
1397            // server prepares its own when they are not there, so a failed
1398            // export costs that option and not the build.
1399            let framework =
1400                public_assets::export_framework_assets(&source, target_triple.is_some())
1401                    .unwrap_or_else(|error| {
1402                        eprintln!(
1403                            "warning: {error:#}; the bundle is written without them and the server will prepare them at startup"
1404                        );
1405                        None
1406                    });
1407            public_assets::bundle(&root, public_source, destination, framework.as_ref())?
1408        } else {
1409            public_assets::clear_bundle(destination)?
1410        };
1411        copy_executable_atomically(&source, destination).with_context(|| {
1412            format!(
1413                "failed to export linked executable `{}` to `{}`",
1414                source.display(),
1415                destination.display()
1416            )
1417        })?;
1418        let bundled_public_assets = bundle.directory.clone();
1419        // Before anything else can fail: the new executable is in place.
1420        bundle.finish()?;
1421        println!(
1422            "exported linked RSJS executable to {}",
1423            destination.display()
1424        );
1425        public_assets::record_start_manifest(
1426            target_dir,
1427            &prepared.request.root.package_id,
1428            &prepared.request.root.target_name,
1429            &prepared.profile,
1430            target_triple,
1431            destination,
1432            bundled_public_assets
1433                .as_deref()
1434                .or(published_public_assets.as_deref()),
1435        )?;
1436    }
1437    Ok(())
1438}
1439
1440pub fn check(mut options: CheckOptions) -> Result<()> {
1441    let root = absolute_project_root(scaffold::resolve_root(options.root.clone())?)?;
1442    let config = load_project_config(&root)?;
1443    if options.bin.is_none() {
1444        options.bin = config
1445            .application
1446            .as_ref()
1447            .map(|application| application.binary.as_str())
1448            .filter(|value| !value.is_empty())
1449            .map(ToString::to_string);
1450    }
1451    let command = check_command(&options);
1452    let prepared = prepare_linked_cargo_with_environment(
1453        &root,
1454        &command,
1455        LinkedCargoAction::Check,
1456        &rsjs_minify_environment(config.build.minify_rsjs),
1457    )?;
1458
1459    println!("running linked RSJS Cargo check: {}", shellish(&command));
1460    let output = run_linked_cargo_cached(&prepared.request, &prepared.descriptor_cache_directory)
1461        .context("linked RSJS check failed")?;
1462    print_linked_cache_reuse(LinkedCargoAction::Check, &output);
1463    print_linked_cargo_output(LinkedCargoAction::Check, &prepared.request, &output);
1464    Ok(())
1465}
1466
1467pub fn run(mut options: RunOptions) -> Result<()> {
1468    let root = absolute_project_root(scaffold::resolve_root(options.root.clone())?)?;
1469    let config = load_project_config(&root)?;
1470    if options.package.is_none() && options.bin.is_none() {
1471        options.bin = configured_binary(&config);
1472    }
1473    let command = run_command(&options);
1474    run_linked_execute_with_environment(
1475        &root,
1476        &command,
1477        LinkedCargoAction::Run,
1478        &config,
1479        &BTreeMap::new(),
1480    )
1481}
1482
1483pub fn test(mut options: TestOptions) -> Result<()> {
1484    install_test_signal_handler();
1485    TEST_INTERRUPTED.store(false, Ordering::SeqCst);
1486    if options.bin.is_some() && options.test.is_some() {
1487        bail!(
1488            "`cargo proa test` requires exactly one target selector: use either `--bin <name>` or `--test <name>`"
1489        );
1490    }
1491    let root = absolute_project_root(scaffold::resolve_root(options.root.clone())?)?;
1492    let explicit_target = options.bin.is_some() || options.test.is_some();
1493    let config = load_project_config(&root)?;
1494    if options.bin.is_none() && options.test.is_none() {
1495        options.bin = config
1496            .application
1497            .as_ref()
1498            .map(|application| application.binary.as_str())
1499            .filter(|value| !value.is_empty())
1500            .map(ToString::to_string);
1501        if options.bin.is_none() {
1502            bail!(
1503                "`cargo proa test` requires exactly one target selector: use either `--bin <name>` or `--test <name>`"
1504            );
1505        }
1506    }
1507    let mut commands = vec![test_command(&options)];
1508    if !explicit_target {
1509        let prepared = prepare_linked_cargo(&root, &commands[0], LinkedCargoAction::Test)?;
1510        for test in discover_integration_test_targets(&prepared.package_source_root)? {
1511            let mut integration = options.clone();
1512            integration.bin = None;
1513            integration.test = Some(test);
1514            commands.push(test_command(&integration));
1515        }
1516    }
1517    if options.watch {
1518        run_watched_tests(
1519            &root,
1520            &config,
1521            &commands,
1522            options.keep_database,
1523            &options.watch_paths,
1524        )
1525    } else {
1526        run_test_session(&root, &config, &commands, options.keep_database)
1527    }
1528}
1529
1530fn discover_integration_test_targets(package_source_root: &Path) -> Result<Vec<String>> {
1531    let directory = package_source_root.join("tests");
1532    let entries = match fs::read_dir(&directory) {
1533        Ok(entries) => entries,
1534        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
1535        Err(error) => return Err(error).with_context(|| format!("read {}", directory.display())),
1536    };
1537    let mut targets = Vec::new();
1538    for entry in entries {
1539        let entry = entry?;
1540        let path = entry.path();
1541        let is_rust_file = path.is_file() && path.extension() == Some(OsStr::new("rs"));
1542        let is_directory_target = path.is_dir() && path.join("main.rs").is_file();
1543        if !is_rust_file && !is_directory_target {
1544            continue;
1545        }
1546        let name = path
1547            .file_stem()
1548            .and_then(OsStr::to_str)
1549            .context("integration-test target names must be UTF-8")?;
1550        targets.push(name.to_string());
1551    }
1552    targets.sort();
1553    Ok(targets)
1554}
1555
1556#[derive(Debug)]
1557struct IsolatedTestDatabase {
1558    run_directory: PathBuf,
1559    path: PathBuf,
1560}
1561
1562impl IsolatedTestDatabase {
1563    fn create(root: &Path) -> Result<Self> {
1564        let run_directory = root.join("target/proa-tests").join(fresh_build_nonce());
1565        fs::create_dir_all(&run_directory)
1566            .with_context(|| format!("create {}", run_directory.display()))?;
1567        let database = Self {
1568            path: run_directory.join("test.db"),
1569            run_directory,
1570        };
1571        if let Err(error) = db::prepare_test_database(root, &database.path) {
1572            let _ = db::remove_test_database(&database.path);
1573            let _ = fs::remove_dir(&database.run_directory);
1574            return Err(error).context("prepare isolated test database");
1575        }
1576        println!("Test database  {}", database.path.display());
1577        Ok(database)
1578    }
1579
1580    fn url(&self) -> OsString {
1581        OsString::from(format!("sqlite://{}", self.path.display()))
1582    }
1583
1584    fn reset(&self, root: &Path) -> Result<()> {
1585        db::remove_test_database(&self.path)?;
1586        db::prepare_test_database(root, &self.path)
1587    }
1588
1589    fn cleanup(&self) -> Result<()> {
1590        db::remove_test_database(&self.path)?;
1591        match fs::remove_dir(&self.run_directory) {
1592            Ok(()) => Ok(()),
1593            Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
1594            Err(error) => {
1595                Err(error).with_context(|| format!("remove {}", self.run_directory.display()))
1596            }
1597        }
1598    }
1599}
1600
1601fn project_uses_sqlite(config: &ProjectConfig) -> bool {
1602    config.database.as_ref().map(|database| database.driver)
1603        == Some(crate::config::DatabaseDriver::Sqlite)
1604}
1605
1606fn run_test_session(
1607    root: &Path,
1608    config: &ProjectConfig,
1609    commands: &[Vec<String>],
1610    keep_database: bool,
1611) -> Result<()> {
1612    let database = project_uses_sqlite(config)
1613        .then(|| IsolatedTestDatabase::create(root))
1614        .transpose()?;
1615    if database.is_none() && keep_database {
1616        eprintln!("No SQLite capability is configured; --keep-database is a no-op.");
1617    }
1618    let result = (|| {
1619        let environment = test_environment(root, database.as_ref())?;
1620        run_test_hooks(root, config, &environment)?;
1621        prepare_test_assets(root, config)?;
1622        run_test_targets(root, config, commands, &environment)
1623    })();
1624    finish_test_database(database.as_ref(), keep_database && result.is_err())?;
1625    result
1626}
1627
1628fn run_watched_tests(
1629    root: &Path,
1630    config: &ProjectConfig,
1631    commands: &[Vec<String>],
1632    keep_database: bool,
1633    watch_paths: &[PathBuf],
1634) -> Result<()> {
1635    let database = project_uses_sqlite(config)
1636        .then(|| IsolatedTestDatabase::create(root))
1637        .transpose()?;
1638    if database.is_none() && keep_database {
1639        eprintln!("No SQLite capability is configured; --keep-database is a no-op.");
1640    }
1641    let result = watched_test_loop(root, config, commands, database.as_ref(), watch_paths);
1642    let preserve = keep_database
1643        && match &result {
1644            Ok(last_failed) => *last_failed,
1645            Err(_) => true,
1646        };
1647    finish_test_database(database.as_ref(), preserve)?;
1648    result.map(|_| ())
1649}
1650
1651fn watched_test_loop(
1652    root: &Path,
1653    config: &ProjectConfig,
1654    commands: &[Vec<String>],
1655    database: Option<&IsolatedTestDatabase>,
1656    watch_paths: &[PathBuf],
1657) -> Result<bool> {
1658    let mut paths = default_watch_paths();
1659    paths.extend(["tests", ".env", ".env.test"].map(PathBuf::from));
1660    paths.extend(watch_paths.iter().cloned());
1661    if public_assets::configured_path(config, true)?.is_some() {
1662        paths.extend(config.paths.public.iter().cloned());
1663    }
1664    let migrations = config
1665        .database
1666        .as_ref()
1667        .and_then(|database| database.migrations.as_deref())
1668        .map(PathBuf::from)
1669        .unwrap_or_else(|| PathBuf::from("migrations"));
1670    paths.push(migrations.clone());
1671    paths.sort_unstable();
1672    paths.dedup();
1673    let hooks = &config.scripts.before.test;
1674    // Hook execution reports invalid task names or dependency cycles.
1675    let declared_hook_outputs = task::lifecycle_output_paths(config, hooks).unwrap_or_default();
1676    let mut successful_hook_outputs = declared_hook_outputs.clone();
1677    if !hooks.is_empty() {
1678        successful_hook_outputs.extend(config.paths.public.as_deref());
1679    }
1680    let css_output = crate::config::css_script_output(config);
1681    let asset_outputs: Vec<_> = config
1682        .paths
1683        .public
1684        .iter()
1685        .flat_map(|_| {
1686            config
1687                .build
1688                .assets()
1689                .iter()
1690                .map(|asset| asset.output.as_path())
1691                .chain(css_output.as_deref())
1692        })
1693        .collect();
1694    let mut baseline = watch_snapshot(root, &paths)?;
1695    let mut last_failed;
1696
1697    loop {
1698        let environment = test_environment(root, database)?;
1699        let mut prepared = run_test_hooks(root, config, &environment);
1700        let hook_outputs = if prepared.is_ok() {
1701            // Asset publication and tests will see the prepared public inputs.
1702            &successful_hook_outputs
1703        } else {
1704            // No tests run after a failed hook. Keep a concurrent fix to an
1705            // authored fixture pending so the watcher retries preparation.
1706            &declared_hook_outputs
1707        };
1708        refresh_test_watch_outputs(root, &paths, hook_outputs, &mut baseline)?;
1709        if prepared.is_ok() {
1710            prepared = prepare_test_assets(root, config);
1711            refresh_test_watch_outputs(root, &paths, &asset_outputs, &mut baseline)?;
1712        }
1713        match prepared.and_then(|()| run_test_targets(root, config, commands, &environment)) {
1714            Ok(()) => last_failed = false,
1715            Err(error) => {
1716                last_failed = true;
1717                eprintln!("test run failed; watching for changes:\n{error:#}");
1718            }
1719        }
1720        if TEST_INTERRUPTED.load(Ordering::SeqCst) {
1721            break;
1722        }
1723        println!("Watching for test input changes · press Ctrl-C to stop");
1724        let changed = loop {
1725            thread::sleep(Duration::from_millis(200));
1726            if TEST_INTERRUPTED.load(Ordering::SeqCst) {
1727                break Vec::new();
1728            }
1729            let snapshot = watch_snapshot(root, &paths)?;
1730            let changed = changed_paths(&baseline, &snapshot);
1731            if !changed.is_empty() {
1732                thread::sleep(DEV_WATCH_DEBOUNCE);
1733                baseline = watch_snapshot(root, &paths)?;
1734                break changed;
1735            }
1736        };
1737        if TEST_INTERRUPTED.load(Ordering::SeqCst) {
1738            break;
1739        }
1740        if changed.iter().any(|path| {
1741            path.strip_prefix(root)
1742                .unwrap_or(path)
1743                .starts_with(&migrations)
1744        }) {
1745            if let Some(database) = &database {
1746                database.reset(root)?;
1747                println!("Test database reset after migration change");
1748            }
1749        }
1750    }
1751    Ok(last_failed)
1752}
1753
1754fn refresh_test_watch_outputs(
1755    root: &Path,
1756    watch_paths: &[PathBuf],
1757    outputs: &[&Path],
1758    baseline: &mut WatchSnapshot,
1759) -> Result<()> {
1760    if outputs.is_empty() {
1761        return Ok(());
1762    }
1763    let prepared = watch_snapshot(root, watch_paths)?;
1764    // Consume preparation writes for these paths. The next test build sees
1765    // edits made after this snapshot.
1766    for output in outputs {
1767        if output.as_os_str().is_empty() {
1768            continue;
1769        }
1770        let output = root.join(output);
1771        let path = output.strip_prefix(root).unwrap_or(&output);
1772        baseline.retain(|file, _| !file.starts_with(path));
1773        baseline.extend(
1774            prepared
1775                .iter()
1776                .filter(|(file, _)| file.starts_with(path))
1777                .map(|(file, stamp)| (file.clone(), *stamp)),
1778        );
1779    }
1780    Ok(())
1781}
1782
1783fn run_test_hooks(
1784    root: &Path,
1785    config: &ProjectConfig,
1786    environment: &BTreeMap<OsString, OsString>,
1787) -> Result<()> {
1788    if TEST_INTERRUPTED.load(Ordering::SeqCst) {
1789        bail!("test interrupted");
1790    }
1791    task::run_lifecycle_tasks(root, config, &config.scripts.before.test, environment)
1792}
1793
1794fn prepare_test_assets(root: &Path, config: &ProjectConfig) -> Result<()> {
1795    if public_assets::configured_path(config, true)?.is_some() {
1796        build_assets(root, config)?;
1797    }
1798    Ok(())
1799}
1800
1801fn run_test_targets(
1802    root: &Path,
1803    config: &ProjectConfig,
1804    commands: &[Vec<String>],
1805    environment: &BTreeMap<OsString, OsString>,
1806) -> Result<()> {
1807    for command in commands {
1808        run_linked_execute_with_environment(
1809            root,
1810            command,
1811            LinkedCargoAction::Test,
1812            config,
1813            environment,
1814        )?;
1815    }
1816    Ok(())
1817}
1818
1819fn finish_test_database(database: Option<&IsolatedTestDatabase>, preserve: bool) -> Result<()> {
1820    let Some(database) = database else {
1821        return Ok(());
1822    };
1823    if preserve {
1824        println!(
1825            "Preserved failing test database at {}",
1826            database.path.display()
1827        );
1828        Ok(())
1829    } else {
1830        database.cleanup()
1831    }
1832}
1833
1834fn test_environment(
1835    root: &Path,
1836    database: Option<&IsolatedTestDatabase>,
1837) -> Result<BTreeMap<OsString, OsString>> {
1838    let mut loaded = BTreeMap::<String, String>::new();
1839    merge_test_env_file(&root.join(".env"), &mut loaded)?;
1840    merge_test_env_file(&root.join(".env.test"), &mut loaded)?;
1841    let mut environment = loaded
1842        .into_iter()
1843        .filter(|(name, _)| env::var_os(name).is_none())
1844        .map(|(name, value)| (OsString::from(name), OsString::from(value)))
1845        .collect::<BTreeMap<_, _>>();
1846    if let Some(database) = database {
1847        environment.insert(OsString::from("DATABASE_URL"), database.url());
1848    }
1849    Ok(environment)
1850}
1851
1852fn merge_test_env_file(path: &Path, values: &mut BTreeMap<String, String>) -> Result<()> {
1853    let source = match fs::read_to_string(path) {
1854        Ok(source) => source,
1855        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),
1856        Err(error) => return Err(error).with_context(|| format!("read {}", path.display())),
1857    };
1858    for (index, line) in source.lines().enumerate() {
1859        let line = line.trim();
1860        if line.is_empty() || line.starts_with('#') {
1861            continue;
1862        }
1863        let line = line.strip_prefix("export ").unwrap_or(line);
1864        let (name, value) = line.split_once('=').with_context(|| {
1865            format!("{}:{} is not a NAME=value entry", path.display(), index + 1)
1866        })?;
1867        let name = name.trim();
1868        if name.is_empty()
1869            || !name.bytes().enumerate().all(|(index, byte)| {
1870                byte == b'_' || byte.is_ascii_alphabetic() || index > 0 && byte.is_ascii_digit()
1871            })
1872        {
1873            bail!(
1874                "{}:{} has an invalid environment name",
1875                path.display(),
1876                index + 1
1877            );
1878        }
1879        values.insert(
1880            name.to_string(),
1881            value.trim().trim_matches(['\'', '"']).to_string(),
1882        );
1883    }
1884    Ok(())
1885}
1886
1887#[cfg(unix)]
1888extern "C" fn test_signal_handler(_signal: libc::c_int) {
1889    TEST_INTERRUPTED.store(true, Ordering::SeqCst);
1890}
1891
1892fn install_test_signal_handler() {
1893    #[cfg(unix)]
1894    unsafe {
1895        libc::signal(
1896            libc::SIGINT,
1897            test_signal_handler as extern "C" fn(libc::c_int) as libc::sighandler_t,
1898        );
1899        libc::signal(
1900            libc::SIGTERM,
1901            test_signal_handler as extern "C" fn(libc::c_int) as libc::sighandler_t,
1902        );
1903    }
1904}
1905
1906// Both Cargo phases observe the same setting. Rustc records option_env! as a
1907// dependency, so changing the flag rebuilds its consumers in the same target.
1908fn rsjs_minify_environment(enabled: bool) -> BTreeMap<OsString, OsString> {
1909    BTreeMap::from([(
1910        "PROA_RSJS_MINIFY".into(),
1911        if enabled { "1" } else { "0" }.into(),
1912    )])
1913}
1914
1915fn run_linked_execute_with_environment(
1916    root: &Path,
1917    command: &[String],
1918    action: LinkedCargoAction,
1919    config: &ProjectConfig,
1920    environment: &BTreeMap<OsString, OsString>,
1921) -> Result<()> {
1922    let mut compile_environment = environment.clone();
1923    compile_environment.extend(rsjs_minify_environment(config.build.minify_rsjs));
1924    let mut prepared =
1925        prepare_linked_cargo_with_environment(root, command, action, &compile_environment)?;
1926    let public_source = public_assets::configured_path(config, true)?;
1927    let defer_execution = action == LinkedCargoAction::Run || public_source.is_some();
1928    if defer_execution {
1929        public_assets::defer_execution(&mut prepared, action);
1930    }
1931    if action == LinkedCargoAction::Run && public_source.is_some() {
1932        task::run_lifecycle_tasks(root, config, &config.scripts.before.build, &BTreeMap::new())?;
1933        build_assets(root, config)?;
1934    }
1935    println!(
1936        "running linked RSJS Cargo {}: {}",
1937        action.command_name(),
1938        shellish(command)
1939    );
1940    let output = run_linked_cargo_cached(&prepared.request, &prepared.descriptor_cache_directory)
1941        .with_context(|| format!("linked RSJS {} failed", action.command_name()))?;
1942    print_linked_cache_reuse(action, &output);
1943    print_linked_cargo_output(action, &prepared.request, &output);
1944    if defer_execution {
1945        let executable = select_final_root_executable(&prepared.request, &output, action)?;
1946        let public_output =
1947            public_assets::publish(root, public_source, &prepared.public_output_directory)?;
1948        let mut command = Command::new(executable);
1949        let execution_root = if action == LinkedCargoAction::Test {
1950            &prepared.package_source_root
1951        } else {
1952            root
1953        };
1954        command
1955            .current_dir(execution_root)
1956            .args(&prepared.runtime_args)
1957            .envs(environment);
1958        public_assets::runtime_environment(&mut command, public_output.as_deref());
1959        let status = command
1960            .status()
1961            .with_context(|| format!("start final linked {}", action.command_name()))?;
1962        exit_status_to_result(status, action.command_name())?;
1963    }
1964    Ok(())
1965}
1966
1967fn print_linked_cache_reuse(action: LinkedCargoAction, output: &LinkedCargoOutput) {
1968    let descriptor_artifacts = output.descriptor.cargo_artifacts.len();
1969    let reused_descriptor_artifacts = output
1970        .descriptor
1971        .cargo_artifacts
1972        .iter()
1973        .filter(|artifact| artifact.fresh)
1974        .count();
1975    let final_artifacts = output.final_cargo.cargo_artifacts.len();
1976    let reused_final_artifacts = output
1977        .final_cargo
1978        .cargo_artifacts
1979        .iter()
1980        .filter(|artifact| artifact.fresh)
1981        .count();
1982    println!(
1983        "linked RSJS {} cache: descriptor {reused_descriptor_artifacts}/{descriptor_artifacts} Cargo artifacts reused; final {reused_final_artifacts}/{final_artifacts} reused",
1984        action.command_name(),
1985    );
1986}
1987
1988/// Hot-template scanning parses every source file with syn, whose syntax
1989/// errors are far less useful than rustc's. When the scan fails, run Cargo
1990/// with the active manifest anyway so a half-written file reports rustc's
1991/// diagnostics; the scan error surfaces only if Cargo accepted the source.
1992fn hot_scan_or_rustc_diagnostics<T>(
1993    root: &Path,
1994    config: &ProjectConfig,
1995    command: &[String],
1996    active: Option<&crate::hot_static::HotState>,
1997    scan: Result<T>,
1998) -> Result<T> {
1999    scan.or_else(|scan_error| {
2000        run_linked_dev_cycle(root, config, command, active, None, None)?;
2001        Err(scan_error)
2002    })
2003}
2004
2005enum DevCargoBuild {
2006    SinglePass(crate::rsjs::pipeline::OptimisticLinkedCargoOutput),
2007    Full(LinkedCargoOutput),
2008}
2009
2010impl DevCargoBuild {
2011    fn final_root_inputs(&self) -> Option<&[PathBuf]> {
2012        match self {
2013            Self::SinglePass(output) => output.final_root_inputs.as_deref(),
2014            Self::Full(output) => output.final_root_inputs.as_deref(),
2015        }
2016    }
2017
2018    fn executable(&self) -> Option<&Path> {
2019        match self {
2020            Self::SinglePass(output) => output.final_root_artifact.executable.as_deref(),
2021            Self::Full(output) => output.final_root_artifact.executable.as_deref(),
2022        }
2023    }
2024}
2025
2026/// Build the dev server, trying the single-pass empty-plan build first when
2027/// the session allows it and falling back to the full linked pipeline.
2028fn run_dev_cargo(
2029    prepared: &PreparedLinkedCargo,
2030    mut session: Option<&mut DevSessionCache>,
2031) -> Result<DevCargoBuild> {
2032    let try_optimistic = session
2033        .as_deref()
2034        .is_some_and(|cache| cache.allow_optimistic_empty);
2035    if try_optimistic {
2036        dev_ui::stage("Compiling");
2037        dev_ui::detail!("Building site: compiling Rust...");
2038        match try_run_optimistic_empty_linked_cargo(&prepared.request)
2039            .context("linked RSJS dev build failed")?
2040        {
2041            OptimisticLinkedCargoOutcome::Succeeded(output) => {
2042                return Ok(DevCargoBuild::SinglePass(output));
2043            }
2044            OptimisticLinkedCargoOutcome::NeedsFullLinkedPass => {
2045                if let Some(cache) = session.as_deref_mut() {
2046                    cache.allow_optimistic_empty = false;
2047                }
2048                dev_ui::detail!("Browser island detected; running full two-pass linked build...");
2049            }
2050        }
2051    }
2052    let output = run_linked_cargo_cached_with_progress(
2053        &prepared.request,
2054        &prepared.descriptor_cache_directory,
2055        |stage| match stage {
2056            LinkedCargoStage::Descriptor => {
2057                dev_ui::stage("Compiling");
2058                dev_ui::detail!("Building site (1/2): resolving dependencies and compiling Rust...")
2059            }
2060            LinkedCargoStage::Link => {
2061                dev_ui::stage("Linking");
2062                dev_ui::detail!("Linking browser components...")
2063            }
2064            LinkedCargoStage::Final => {
2065                dev_ui::stage("Finishing");
2066                dev_ui::detail!("Building site (2/2): compiling the final server...")
2067            }
2068        },
2069    )
2070    .context("linked RSJS dev build failed")?;
2071    if let Some(cache) = session {
2072        cache.allow_optimistic_empty = output.semantic.is_empty();
2073    }
2074    Ok(DevCargoBuild::Full(output))
2075}
2076
2077fn run_linked_dev_cycle(
2078    root: &Path,
2079    config: &ProjectConfig,
2080    command: &[String],
2081    hot: Option<&crate::hot_static::HotState>,
2082    public_source: Option<&Path>,
2083    session: Option<&mut DevSessionCache>,
2084) -> Result<LinkedDevLaunch> {
2085    run_linked_dev_cycle_with_assets(root, config, command, hot, public_source, session, None)
2086}
2087
2088fn run_linked_dev_cycle_with_assets(
2089    root: &Path,
2090    config: &ProjectConfig,
2091    command: &[String],
2092    hot: Option<&crate::hot_static::HotState>,
2093    public_source: Option<&Path>,
2094    mut session: Option<&mut DevSessionCache>,
2095    deferred_asset_changes: Option<&[PathBuf]>,
2096) -> Result<LinkedDevLaunch> {
2097    let _progress = DevBuildProgress::start();
2098    dev_ui::detail!("running linked RSJS Cargo dev build: {}", shellish(command));
2099    dev_ui::detail!("Preparing the Cargo project and build cache...");
2100    let mut environment = hot.map(|state| state.environment()).unwrap_or_default();
2101    environment.extend(rsjs_minify_environment(config.build.minify_rsjs));
2102
2103    let (prepared, build, assets) = thread::scope(|scope| {
2104        let assets = deferred_asset_changes.map(|changed| {
2105            scope.spawn(move || build_assets_for_change(root, config, public_source, changed))
2106        });
2107        let prepared = prepare_linked_cargo_with_environment_and_session(
2108            root,
2109            command,
2110            LinkedCargoAction::Dev,
2111            &environment,
2112            session.as_deref_mut(),
2113        );
2114        let build = prepared
2115            .as_ref()
2116            .ok()
2117            .map(|prepared| run_dev_cargo(prepared, session.as_deref_mut()));
2118        let assets = assets.map(|handle| {
2119            handle
2120                .join()
2121                .map_err(|_| anyhow::anyhow!("background asset build thread panicked"))
2122                .and_then(|result| result)
2123        });
2124        (prepared, build, assets)
2125    });
2126
2127    let prepared = prepared?;
2128    let mut build = build.expect("Cargo runs once preparation succeeds")?;
2129    if let Some(assets) = assets {
2130        assets?;
2131    }
2132    // The previous build proved no asset output was compiled in, but this edit
2133    // may have added an `include_str!` of one that Cargo read while the asset
2134    // command was still writing it. Cargo dates each compilation from its
2135    // start, so one more pass rebuilds exactly when that happened.
2136    if deferred_asset_changes.is_some()
2137        && !build_excludes_asset_outputs(root, config, build.final_root_inputs())
2138    {
2139        dev_ui::detail!("this build reads a generated asset; rebuilding now that assets are final");
2140        let first = std::mem::replace(
2141            &mut build,
2142            run_dev_cargo(&prepared, session.as_deref_mut())?,
2143        );
2144        let stale = first
2145            .executable()
2146            .filter(|path| Some(*path) != build.executable())
2147            .map(Path::to_path_buf);
2148        drop(first);
2149        if let Some(stale) = stale {
2150            prune_final_artifact_snapshot(&stale);
2151        }
2152    }
2153
2154    match build {
2155        DevCargoBuild::SinglePass(output) => {
2156            let executable = select_attested_root_executable(
2157                &prepared.request,
2158                output.final_cargo.plan_id,
2159                output.semantic.plan_id,
2160                &output.semantic_plan_path,
2161                &output.final_root_artifact,
2162                LinkedCargoAction::Dev,
2163            )?;
2164            let public_assets =
2165                public_assets::publish(root, public_source, &prepared.public_output_directory)?;
2166            let reused_final_artifacts = output
2167                .final_cargo
2168                .cargo_artifacts
2169                .iter()
2170                .filter(|artifact| artifact.fresh)
2171                .count();
2172            dev_ui::detail!(
2173                "linked RSJS dev plan {} (single-pass; final cache: {reused_final_artifacts}/{} reused)",
2174                output.semantic.plan_id,
2175                output.final_cargo.cargo_artifacts.len(),
2176            );
2177            let compiled_inputs =
2178                collect_compiled_source_inputs_from_paths(output.final_root_inputs.as_deref());
2179            Ok(LinkedDevLaunch {
2180                executable,
2181                arguments: prepared.runtime_args,
2182                plan_id: output.semantic.plan_id.to_string(),
2183                single_pass: true,
2184                descriptor_artifacts: 0,
2185                reused_descriptor_artifacts: 0,
2186                reused_final_artifacts,
2187                public_assets,
2188                compiled_inputs,
2189                _snapshot_lease: output.final_root_lease,
2190            })
2191        }
2192        DevCargoBuild::Full(output) => {
2193            let executable =
2194                select_final_root_executable(&prepared.request, &output, LinkedCargoAction::Dev)?;
2195            let public_assets =
2196                public_assets::publish(root, public_source, &prepared.public_output_directory)?;
2197            let descriptor_artifacts = output.descriptor.cargo_artifacts.len();
2198            let reused_descriptor_artifacts = output
2199                .descriptor
2200                .cargo_artifacts
2201                .iter()
2202                .filter(|artifact| artifact.fresh)
2203                .count();
2204            let reused_final_artifacts = output
2205                .final_cargo
2206                .cargo_artifacts
2207                .iter()
2208                .filter(|artifact| artifact.fresh)
2209                .count();
2210            dev_ui::detail!(
2211                "linked RSJS dev plan {} (descriptor cache: {reused_descriptor_artifacts}/{descriptor_artifacts} Cargo artifacts reused; final cache: {reused_final_artifacts}/{} reused)",
2212                output.semantic.plan_id,
2213                output.final_cargo.cargo_artifacts.len(),
2214            );
2215
2216            let compiled_inputs = collect_compiled_source_inputs(&output);
2217            Ok(LinkedDevLaunch {
2218                executable,
2219                arguments: prepared.runtime_args,
2220                plan_id: output.semantic.plan_id.to_string(),
2221                single_pass: false,
2222                descriptor_artifacts,
2223                reused_descriptor_artifacts,
2224                reused_final_artifacts,
2225                public_assets,
2226                compiled_inputs,
2227                _snapshot_lease: output.final_root_lease.clone(),
2228            })
2229        }
2230    }
2231}
2232
2233// Cargo can be quiet while downloading, linking, or validating cached build
2234// artifacts. Keep the dev terminal visibly active until the entire build ends.
2235struct DevBuildProgress {
2236    done: std::sync::mpsc::Sender<()>,
2237    thread: Option<thread::JoinHandle<()>>,
2238}
2239
2240impl DevBuildProgress {
2241    fn start() -> Self {
2242        use std::sync::mpsc::{self, RecvTimeoutError};
2243
2244        let (done, receiver) = mpsc::channel();
2245        let pretty = dev_ui::pretty();
2246        let interval = if pretty {
2247            dev_ui::SPIN_INTERVAL
2248        } else {
2249            Duration::from_secs(10)
2250        };
2251        let thread = thread::spawn(move || {
2252            let started = Instant::now();
2253            while matches!(
2254                receiver.recv_timeout(interval),
2255                Err(RecvTimeoutError::Timeout)
2256            ) {
2257                if pretty {
2258                    dev_ui::spin(started);
2259                } else {
2260                    eprintln!(
2261                        "Still building your site ({}s elapsed)...",
2262                        started.elapsed().as_secs()
2263                    );
2264                }
2265            }
2266            if pretty {
2267                dev_ui::clear_spinner();
2268            }
2269        });
2270        Self {
2271            done,
2272            thread: Some(thread),
2273        }
2274    }
2275}
2276
2277impl Drop for DevBuildProgress {
2278    fn drop(&mut self) {
2279        let _ = self.done.send(());
2280        if let Some(thread) = self.thread.take() {
2281            let _ = thread.join();
2282        }
2283    }
2284}
2285
2286fn select_final_root_executable(
2287    request: &LinkedCargoRequest,
2288    output: &LinkedCargoOutput,
2289    action: LinkedCargoAction,
2290) -> Result<PathBuf> {
2291    select_attested_root_executable(
2292        request,
2293        output.final_cargo.plan_id,
2294        output.semantic.plan_id,
2295        &output.semantic_plan_path,
2296        &output.final_root_artifact,
2297        action,
2298    )
2299}
2300
2301fn select_attested_root_executable(
2302    request: &LinkedCargoRequest,
2303    final_plan_id: rsjs_ir::abi::PlanId,
2304    semantic_plan_id: rsjs_ir::abi::PlanId,
2305    semantic_plan_path: &Path,
2306    artifact: &crate::rsjs::build::CargoCompilerArtifact,
2307    action: LinkedCargoAction,
2308) -> Result<PathBuf> {
2309    if final_plan_id != semantic_plan_id {
2310        bail!(
2311            "linked {} final Cargo consumed plan {}, but the semantic linker produced {}",
2312            action.command_name(),
2313            final_plan_id,
2314            semantic_plan_id
2315        );
2316    }
2317    if !semantic_plan_path.is_file() {
2318        bail!(
2319            "linked {} semantic plan disappeared before executable selection: `{}`",
2320            action.command_name(),
2321            semantic_plan_path.display()
2322        );
2323    }
2324
2325    if artifact.package_id != request.root.package_id
2326        || artifact.target.name != request.root.target_name
2327        || artifact.target.kind != request.root.target_kinds
2328    {
2329        bail!(
2330            "attested final root no longer matches linked {} package `{}` target `{}`",
2331            action.command_name(),
2332            request.root.package_id,
2333            request.root.target_name
2334        );
2335    }
2336    let executable = artifact.executable.clone().ok_or_else(|| {
2337        anyhow::anyhow!(
2338            "final linked Cargo build emitted no executable for package `{}` binary `{}`",
2339            request.root.package_id,
2340            request.root.target_name
2341        )
2342    })?;
2343    if !executable.is_absolute() || !executable.is_file() {
2344        bail!(
2345            "final linked Cargo executable is not an existing absolute file: `{}`",
2346            executable.display()
2347        );
2348    }
2349    Ok(executable)
2350}
2351
2352fn resolve_artifact_output(root: &Path, requested: &Path) -> PathBuf {
2353    if requested.is_absolute() {
2354        requested.to_path_buf()
2355    } else {
2356        root.join(requested)
2357    }
2358}
2359
2360fn warn_if_artifact_output_enters_source_closure(
2361    destination: &Path,
2362    package_source_root: &Path,
2363    source_exclusion: &Path,
2364) {
2365    if artifact_output_enters_source_closure(destination, package_source_root, source_exclusion) {
2366        eprintln!(
2367            "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",
2368            destination.display(),
2369            package_source_root.display()
2370        );
2371    }
2372}
2373
2374fn artifact_output_enters_source_closure(
2375    destination: &Path,
2376    package_source_root: &Path,
2377    source_exclusion: &Path,
2378) -> bool {
2379    let Some(destination) = normalize_absolute_lexical_path(destination) else {
2380        return destination.starts_with(package_source_root);
2381    };
2382    let Some(package_source_root) = normalize_absolute_lexical_path(package_source_root) else {
2383        return false;
2384    };
2385    let Some(source_exclusion) = normalize_absolute_lexical_path(source_exclusion) else {
2386        return false;
2387    };
2388    if !destination.starts_with(&package_source_root) || destination.starts_with(&source_exclusion)
2389    {
2390        return false;
2391    }
2392    let Ok(relative) = destination.strip_prefix(&package_source_root) else {
2393        return false;
2394    };
2395    let mut components = relative
2396        .components()
2397        .filter_map(|component| match component {
2398            std::path::Component::Normal(value) => Some(value),
2399            _ => None,
2400        });
2401    let Some(first) = components.next() else {
2402        return true;
2403    };
2404    if matches!(
2405        first.to_str(),
2406        Some(".git" | ".hg" | ".svn" | ".jj" | "target" | "node_modules")
2407    ) {
2408        return false;
2409    }
2410    !components.any(|component| component == OsStr::new("node_modules"))
2411}
2412
2413fn normalize_absolute_lexical_path(path: &Path) -> Option<PathBuf> {
2414    use std::path::Component;
2415
2416    if !path.is_absolute() {
2417        return None;
2418    }
2419    let mut normalized = PathBuf::new();
2420    for component in path.components() {
2421        match component {
2422            Component::Prefix(_) | Component::RootDir | Component::Normal(_) => {
2423                normalized.push(component.as_os_str());
2424            }
2425            Component::CurDir => {}
2426            Component::ParentDir => {
2427                if !normalized.pop() {
2428                    return None;
2429                }
2430            }
2431        }
2432    }
2433    Some(normalized)
2434}
2435
2436fn copy_executable_atomically(source: &Path, destination: &Path) -> io::Result<()> {
2437    if source == destination {
2438        return Ok(());
2439    }
2440    if destination.is_dir() {
2441        return Err(io::Error::new(
2442            io::ErrorKind::InvalidInput,
2443            format!(
2444                "artifact output must name a file, but `{}` is a directory",
2445                destination.display()
2446            ),
2447        ));
2448    }
2449
2450    let parent = destination.parent().ok_or_else(|| {
2451        io::Error::new(
2452            io::ErrorKind::InvalidInput,
2453            format!(
2454                "artifact output `{}` has no parent directory",
2455                destination.display()
2456            ),
2457        )
2458    })?;
2459    fs::create_dir_all(parent)?;
2460
2461    let file_name = destination.file_name().ok_or_else(|| {
2462        io::Error::new(
2463            io::ErrorKind::InvalidInput,
2464            format!(
2465                "artifact output `{}` does not name a file",
2466                destination.display()
2467            ),
2468        )
2469    })?;
2470    let (temporary, mut temporary_file) = loop {
2471        let nonce = RSJS_BUILD_NONCE.fetch_add(1, Ordering::Relaxed);
2472        let candidate = parent.join(format!(
2473            ".{}.proa-export-{}-{nonce}",
2474            file_name.to_string_lossy(),
2475            std::process::id()
2476        ));
2477        match fs::OpenOptions::new()
2478            .create_new(true)
2479            .write(true)
2480            .open(&candidate)
2481        {
2482            Ok(file) => break (candidate, file),
2483            Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
2484            Err(error) => return Err(error),
2485        }
2486    };
2487
2488    let copy_result = (|| {
2489        let mut source_file = fs::File::open(source)?;
2490        let source_permissions = source_file.metadata()?.permissions();
2491        io::copy(&mut source_file, &mut temporary_file)?;
2492        temporary_file.set_permissions(source_permissions)?;
2493        temporary_file.sync_all()?;
2494        drop(temporary_file);
2495        replace_file(&temporary, destination)
2496    })();
2497
2498    if copy_result.is_err() {
2499        let _ = fs::remove_file(&temporary);
2500    }
2501    copy_result
2502}
2503
2504#[cfg(not(windows))]
2505fn replace_file(source: &Path, destination: &Path) -> io::Result<()> {
2506    fs::rename(source, destination)
2507}
2508
2509#[cfg(windows)]
2510fn replace_file(source: &Path, destination: &Path) -> io::Result<()> {
2511    use std::os::windows::ffi::OsStrExt;
2512    use windows_sys::Win32::Storage::FileSystem::{
2513        MoveFileExW, MOVEFILE_REPLACE_EXISTING, MOVEFILE_WRITE_THROUGH,
2514    };
2515
2516    let source: Vec<u16> = source.as_os_str().encode_wide().chain(Some(0)).collect();
2517    let destination: Vec<u16> = destination
2518        .as_os_str()
2519        .encode_wide()
2520        .chain(Some(0))
2521        .collect();
2522    let moved = unsafe {
2523        MoveFileExW(
2524            source.as_ptr(),
2525            destination.as_ptr(),
2526            MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH,
2527        )
2528    };
2529    if moved == 0 {
2530        Err(io::Error::last_os_error())
2531    } else {
2532        Ok(())
2533    }
2534}
2535
2536fn configured_binary(config: &ProjectConfig) -> Option<String> {
2537    config
2538        .application
2539        .as_ref()
2540        .map(|application| application.binary.as_str())
2541        .filter(|value| !value.is_empty())
2542        .map(ToString::to_string)
2543}
2544
2545fn snapshot_generated_public_outputs(
2546    root: &Path,
2547    config: &ProjectConfig,
2548    public: &Path,
2549    snapshot: &WatchSnapshot,
2550) -> Result<BTreeMap<PathBuf, [u8; 32]>> {
2551    let mut digests = BTreeMap::new();
2552    let css_output = crate::config::css_script_output(config);
2553    for output in config
2554        .build
2555        .assets()
2556        .iter()
2557        .map(|asset| asset.output.as_path())
2558        .chain(css_output.as_deref())
2559    {
2560        if output.as_os_str().is_empty() || !output.starts_with(public) {
2561            continue;
2562        }
2563        let Some(&expected_stamp) = snapshot.get(output) else {
2564            continue;
2565        };
2566        let full = root.join(output);
2567        let Ok(metadata) = fs::symlink_metadata(&full) else {
2568            continue;
2569        };
2570        if !metadata.file_type().is_file() || FileStamp::from_metadata(&metadata) != expected_stamp
2571        {
2572            // File changed after `snapshot` was taken; do not consume it.
2573            continue;
2574        }
2575        let bytes = fs::read(&full).with_context(|| format!("read {}", full.display()))?;
2576        let post_read =
2577            fs::symlink_metadata(&full).with_context(|| format!("stat {}", full.display()))?;
2578        if !post_read.file_type().is_file()
2579            || FileStamp::from_metadata(&post_read) != expected_stamp
2580        {
2581            continue;
2582        }
2583        digests.insert(output.to_path_buf(), Sha256::digest(&bytes).into());
2584    }
2585    Ok(digests)
2586}
2587
2588fn all_unchanged_generated_outputs(
2589    root: &Path,
2590    changed_public: &[&PathBuf],
2591    before: &BTreeMap<PathBuf, [u8; 32]>,
2592    post_assets: &WatchSnapshot,
2593) -> Result<bool> {
2594    for path in changed_public {
2595        let Some(expected_digest) = before.get(*path) else {
2596            return Ok(false);
2597        };
2598        let Some(&expected_stamp) = post_assets.get(*path) else {
2599            return Ok(false);
2600        };
2601        let full = root.join(path);
2602        let Ok(metadata) = fs::symlink_metadata(&full) else {
2603            return Ok(false);
2604        };
2605        if !metadata.file_type().is_file() || FileStamp::from_metadata(&metadata) != expected_stamp
2606        {
2607            return Ok(false);
2608        }
2609        let bytes = fs::read(&full).with_context(|| format!("read {}", full.display()))?;
2610        let post_read =
2611            fs::symlink_metadata(&full).with_context(|| format!("stat {}", full.display()))?;
2612        if !post_read.file_type().is_file()
2613            || FileStamp::from_metadata(&post_read) != expected_stamp
2614            || Sha256::digest(&bytes).as_slice() != expected_digest
2615        {
2616            return Ok(false);
2617        }
2618    }
2619    Ok(true)
2620}
2621
2622fn dev_command(options: &DevOptions, config: &ProjectConfig) -> Vec<String> {
2623    let mut command = if options.command.is_empty() {
2624        let mut command = vec!["cargo".into(), "run".into()];
2625        if let Some(bin) = configured_binary(config) {
2626            command.push("--bin".into());
2627            command.push(bin);
2628        }
2629        command
2630    } else {
2631        options.command.clone()
2632    };
2633    if options.offline {
2634        let cargo_end = command
2635            .iter()
2636            .position(|arg| arg == "--")
2637            .unwrap_or(command.len());
2638        if !command[..cargo_end].iter().any(|arg| arg == "--offline") {
2639            command.insert(cargo_end, "--offline".into());
2640        }
2641    }
2642    command
2643}
2644
2645fn build_command(options: &BuildOptions) -> Vec<String> {
2646    let mut command = if !options.command.is_empty() {
2647        options.command.clone()
2648    } else if let Some(profile) = &options.profile {
2649        vec![
2650            "cargo".into(),
2651            "build".into(),
2652            "--profile".into(),
2653            profile.clone(),
2654        ]
2655    } else {
2656        vec!["cargo".into(), "build".into(), "--release".into()]
2657    };
2658
2659    if let Some(package) = &options.package {
2660        command.push("-p".into());
2661        command.push(package.clone());
2662    }
2663    if let Some(bin) = &options.bin {
2664        command.push("--bin".into());
2665        command.push(bin.clone());
2666    }
2667    if let Some(example) = &options.example {
2668        command.push("--example".into());
2669        command.push(example.clone());
2670    }
2671    if let Some(target) = &options.target {
2672        command.push("--target".into());
2673        command.push(target.clone());
2674    }
2675    if !options.features.is_empty() {
2676        command.push("--features".into());
2677        command.push(options.features.join(","));
2678    }
2679    if options.all_features {
2680        command.push("--all-features".into());
2681    }
2682    if options.no_default_features {
2683        command.push("--no-default-features".into());
2684    }
2685    if options.locked {
2686        command.push("--locked".into());
2687    }
2688    if options.offline {
2689        command.push("--offline".into());
2690    }
2691
2692    command
2693}
2694
2695fn check_command(options: &CheckOptions) -> Vec<String> {
2696    let mut command = vec!["cargo".into(), "check".into()];
2697    append_cargo_selection(
2698        &mut command,
2699        options.profile.as_deref(),
2700        options.package.as_deref(),
2701        options.bin.as_deref(),
2702        options.target.as_deref(),
2703        &options.features,
2704        options.all_features,
2705        options.no_default_features,
2706        options.locked,
2707        options.offline,
2708    );
2709    command
2710}
2711
2712fn run_command(options: &RunOptions) -> Vec<String> {
2713    let mut command = vec!["cargo".into(), "run".into()];
2714    append_cargo_selection(
2715        &mut command,
2716        options.profile.as_deref(),
2717        options.package.as_deref(),
2718        options.bin.as_deref(),
2719        options.target.as_deref(),
2720        &options.features,
2721        options.all_features,
2722        options.no_default_features,
2723        options.locked,
2724        options.offline,
2725    );
2726    append_runtime_arguments(&mut command, &options.arguments);
2727    command
2728}
2729
2730fn test_command(options: &TestOptions) -> Vec<String> {
2731    let mut command = vec!["cargo".into(), "test".into()];
2732    append_cargo_selection(
2733        &mut command,
2734        options.profile.as_deref(),
2735        options.package.as_deref(),
2736        options.bin.as_deref(),
2737        options.target.as_deref(),
2738        &options.features,
2739        options.all_features,
2740        options.no_default_features,
2741        options.locked,
2742        options.offline,
2743    );
2744    if let Some(test) = &options.test {
2745        command.push("--test".into());
2746        command.push(test.clone());
2747    }
2748    append_runtime_arguments(&mut command, &options.arguments);
2749    command
2750}
2751
2752fn append_runtime_arguments(command: &mut Vec<String>, arguments: &[String]) {
2753    if !arguments.is_empty() {
2754        command.push("--".into());
2755        command.extend(arguments.iter().cloned());
2756    }
2757}
2758
2759fn append_cargo_selection(
2760    command: &mut Vec<String>,
2761    profile: Option<&str>,
2762    package: Option<&str>,
2763    bin: Option<&str>,
2764    target: Option<&str>,
2765    features: &[String],
2766    all_features: bool,
2767    no_default_features: bool,
2768    locked: bool,
2769    offline: bool,
2770) {
2771    if let Some(profile) = profile {
2772        command.push("--profile".into());
2773        command.push(profile.into());
2774    }
2775    if let Some(package) = package {
2776        command.push("-p".into());
2777        command.push(package.into());
2778    }
2779    if let Some(bin) = bin {
2780        command.push("--bin".into());
2781        command.push(bin.into());
2782    }
2783    if let Some(target) = target {
2784        command.push("--target".into());
2785        command.push(target.into());
2786    }
2787    if !features.is_empty() {
2788        command.push("--features".into());
2789        command.push(features.join(","));
2790    }
2791    if all_features {
2792        command.push("--all-features".into());
2793    }
2794    if no_default_features {
2795        command.push("--no-default-features".into());
2796    }
2797    if locked {
2798        command.push("--locked".into());
2799    }
2800    if offline {
2801        command.push("--offline".into());
2802    }
2803}
2804
2805#[derive(Debug, Clone, PartialEq, Eq)]
2806struct ParsedCargoInvocation {
2807    cargo: OsString,
2808    cargo_args: Vec<OsString>,
2809    runtime_args: Vec<OsString>,
2810    package: Option<String>,
2811    bin: Option<String>,
2812    example: Option<String>,
2813    test: Option<String>,
2814    profile: String,
2815    target: Option<String>,
2816    features: BTreeSet<String>,
2817    locked: bool,
2818    offline: bool,
2819    metadata_flags: Vec<OsString>,
2820    selection_args: Vec<String>,
2821}
2822
2823#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2824enum LinkedCargoAction {
2825    Build,
2826    Check,
2827    Dev,
2828    Run,
2829    Test,
2830}
2831
2832impl LinkedCargoAction {
2833    const fn command_name(self) -> &'static str {
2834        match self {
2835            Self::Build => "build",
2836            Self::Check => "check",
2837            Self::Dev => "dev",
2838            Self::Run => "run",
2839            Self::Test => "test",
2840        }
2841    }
2842
2843    const fn subcommand(self) -> &'static str {
2844        match self {
2845            Self::Build => "build",
2846            Self::Check => "check",
2847            Self::Dev => "run",
2848            Self::Run => "run",
2849            Self::Test => "test",
2850        }
2851    }
2852
2853    const fn final_subcommand(self) -> &'static str {
2854        match self {
2855            Self::Build => "build",
2856            Self::Check => "check",
2857            Self::Dev => "build",
2858            Self::Run => "run",
2859            Self::Test => "test",
2860        }
2861    }
2862
2863    const fn descriptor_subcommand(self) -> &'static str {
2864        match self {
2865            Self::Test => "test",
2866            Self::Check => "check",
2867            Self::Build | Self::Dev | Self::Run => "build",
2868        }
2869    }
2870
2871    const fn permits_runtime_arguments(self) -> bool {
2872        matches!(self, Self::Dev | Self::Run | Self::Test)
2873    }
2874
2875    const fn final_cargo_executes(self) -> bool {
2876        matches!(self, Self::Run | Self::Test)
2877    }
2878
2879    const fn root_role(self) -> ArtifactRole {
2880        match self {
2881            Self::Test => ArtifactRole::RootTest,
2882            Self::Build | Self::Check | Self::Dev | Self::Run => ArtifactRole::RootExecutable,
2883        }
2884    }
2885
2886    const fn descriptor_identity_marker(self) -> &'static str {
2887        match self {
2888            Self::Test => "proa:descriptor-mode=test-no-run",
2889            Self::Check => "proa:descriptor-mode=check",
2890            Self::Build | Self::Dev | Self::Run => "proa:descriptor-mode=build",
2891        }
2892    }
2893}
2894
2895#[derive(Debug)]
2896struct PreparedLinkedCargo {
2897    request: LinkedCargoRequest,
2898    profile: String,
2899    target_triple: Option<String>,
2900    runtime_args: Vec<OsString>,
2901    descriptor_cache_directory: PathBuf,
2902    package_source_root: PathBuf,
2903    public_output_directory: PathBuf,
2904    // Windows cannot safely relocate arbitrary PE executables without a
2905    // complete delay-import contract. Hold a no-write/no-delete sharing lock
2906    // instead so the fingerprinted wrapper path cannot be replaced before
2907    // Cargo opens it. Other hosts execute a content-addressed snapshot.
2908    _wrapper_lock: Option<fs::File>,
2909}
2910
2911#[derive(Debug, Deserialize)]
2912struct CargoMetadata {
2913    packages: Vec<CargoMetadataPackage>,
2914    workspace_members: Vec<String>,
2915    #[serde(default)]
2916    workspace_default_members: Vec<String>,
2917    target_directory: PathBuf,
2918}
2919
2920#[derive(Debug, Deserialize)]
2921struct CargoMetadataPackage {
2922    id: String,
2923    name: String,
2924    version: String,
2925    manifest_path: PathBuf,
2926    targets: Vec<CargoMetadataTarget>,
2927}
2928
2929#[derive(Debug, Deserialize)]
2930struct CargoMetadataTarget {
2931    name: String,
2932    kind: Vec<String>,
2933}
2934
2935#[derive(Debug)]
2936struct ExactCargoRoot {
2937    package_id: String,
2938    package_name: String,
2939    package_source_root: PathBuf,
2940    target_name: String,
2941    target_kinds: BTreeSet<String>,
2942    requested_target_kind: String,
2943}
2944
2945fn prepare_linked_cargo(
2946    root: &Path,
2947    command: &[String],
2948    action: LinkedCargoAction,
2949) -> Result<PreparedLinkedCargo> {
2950    prepare_linked_cargo_with_environment(root, command, action, &BTreeMap::new())
2951}
2952
2953fn prepare_linked_cargo_with_environment(
2954    root: &Path,
2955    command: &[String],
2956    action: LinkedCargoAction,
2957    environment: &BTreeMap<OsString, OsString>,
2958) -> Result<PreparedLinkedCargo> {
2959    prepare_linked_cargo_with_environment_and_session(root, command, action, environment, None)
2960}
2961
2962fn prepare_linked_cargo_with_environment_and_session(
2963    root: &Path,
2964    command: &[String],
2965    action: LinkedCargoAction,
2966    environment: &BTreeMap<OsString, OsString>,
2967    session: Option<&mut DevSessionCache>,
2968) -> Result<PreparedLinkedCargo> {
2969    let wrapper =
2970        crate::util::current_executable().context("resolve the cargo-proa wrapper executable")?;
2971    prepare_linked_cargo_with_wrapper_and_environment_and_session(
2972        root,
2973        command,
2974        action,
2975        wrapper,
2976        environment,
2977        session,
2978    )
2979}
2980
2981#[cfg(test)]
2982fn prepare_linked_cargo_with_wrapper(
2983    root: &Path,
2984    command: &[String],
2985    action: LinkedCargoAction,
2986    wrapper: PathBuf,
2987) -> Result<PreparedLinkedCargo> {
2988    prepare_linked_cargo_with_wrapper_and_environment_and_session(
2989        root,
2990        command,
2991        action,
2992        wrapper,
2993        &BTreeMap::new(),
2994        None,
2995    )
2996}
2997
2998fn prepare_linked_cargo_with_wrapper_and_environment_and_session(
2999    root: &Path,
3000    command: &[String],
3001    action: LinkedCargoAction,
3002    wrapper: PathBuf,
3003    environment: &BTreeMap<OsString, OsString>,
3004    mut session: Option<&mut DevSessionCache>,
3005) -> Result<PreparedLinkedCargo> {
3006    if !wrapper.is_absolute() {
3007        bail!(
3008            "the cargo-proa wrapper executable is not absolute: `{}`",
3009            wrapper.display()
3010        );
3011    }
3012    let parsed = parse_cargo_command(command, action)?;
3013    let mut timer = crate::rsjs::timing::StageTimer::new();
3014    // Query every current tool and Cargo's authoritative metadata on each
3015    // cycle. They are independent subprocesses; overlapping them avoids
3016    // adding their startup costs together without caching mutable tool state.
3017    let (metadata, cargo_version, rustc_version) = thread::scope(|scope| {
3018        let cargo = scope.spawn(|| tool_version(&parsed.cargo, &["-Vv"], "Cargo", root));
3019        let rustc = scope.spawn(|| selected_rustc_version(root));
3020        let metadata = load_cargo_metadata(root, &parsed);
3021        let cargo = cargo
3022            .join()
3023            .map_err(|_| anyhow::anyhow!("Cargo version query thread panicked"))
3024            .and_then(|result| result);
3025        let rustc = rustc
3026            .join()
3027            .map_err(|_| anyhow::anyhow!("rustc version query thread panicked"))
3028            .and_then(|result| result);
3029        (metadata, cargo, rustc)
3030    });
3031    let metadata = metadata?;
3032    let cargo_version = cargo_version?;
3033    let rustc_version = rustc_version?;
3034    timer.mark("prepare Cargo metadata and tool versions");
3035    let selected_root = select_exact_cargo_root(&metadata, &parsed, action)?;
3036    let public_output_directory =
3037        public_assets::output_directory(&metadata.target_directory, &selected_root, &parsed)?;
3038    if !metadata.target_directory.is_absolute() {
3039        bail!(
3040            "Cargo metadata returned a relative target directory `{}`; the linked RSJS pipeline requires an exact absolute artifact namespace",
3041            metadata.target_directory.display()
3042        );
3043    }
3044    let wrapper_snapshot_root = metadata
3045        .target_directory
3046        .join("proa-rsjs")
3047        .join("wrapper-snapshots-v1");
3048    let (wrapper, wrapper_lock, wrapper_fingerprint) = prepare_wrapper_with_session(
3049        &metadata.target_directory,
3050        &wrapper_snapshot_root,
3051        &wrapper,
3052        session.as_deref_mut(),
3053    )?;
3054    timer.mark("prepare wrapper snapshot and fingerprint");
3055    let package_source_root = selected_root.package_source_root.clone();
3056    let cli_producer = cli_tool_producer_version()?;
3057    let mut selection_args = parsed.selection_args.clone();
3058    // A binary compiled as a test harness is a different Cargo/rustc unit from
3059    // the same binary compiled normally. Keep that mode in the pre-Cargo
3060    // identity so persistent descriptor targets and caches cannot alias.
3061    selection_args.push(action.descriptor_identity_marker().to_string());
3062    // Producer semver is insufficient during local development and rolling
3063    // upgrades: the same absolute executable path can be atomically replaced
3064    // with different wrapper behavior. Bind every persistent descriptor and
3065    // final Cargo namespace to the exact wrapper bytes that will be invoked.
3066    selection_args.push(format!(
3067        "proa:wrapper-executable-fingerprint={wrapper_fingerprint}"
3068    ));
3069    let shared_target_scope = shared_cargo_target_scope(
3070        &wrapper_fingerprint,
3071        &cargo_version,
3072        &rustc_version,
3073        cli_producer,
3074    );
3075    let invocation_spec = InvocationSpec {
3076        roots: BTreeSet::from([RequestedRootTarget {
3077            package: selected_root.package_id.clone(),
3078            target_kind: selected_root.requested_target_kind.clone(),
3079            target_name: Some(selected_root.target_name.clone()),
3080        }]),
3081        target_triple: parsed.target.clone(),
3082        features: parsed.features.clone(),
3083        profile: parsed.profile.clone(),
3084        cargo_config: BTreeMap::new(),
3085        locked: parsed.locked,
3086        offline: parsed.offline,
3087        selection_args,
3088        // Test fixture values are supplied identically to descriptor and final
3089        // Cargo below, but are not semantic target selectors. Cargo build
3090        // scripts and the wrapper's observed-environment sidecars still
3091        // invalidate units that actually consume one of these values.
3092        environment: declared_build_environment(),
3093        toolchain: BuildToolchain {
3094            cargo: cargo_version,
3095            rustc: rustc_version,
3096            proa: cli_producer,
3097            compiler_abi: RSJS_COMPILER_ABI,
3098            transport_version: TRANSPORT_FORMAT_VERSION,
3099        },
3100    };
3101    let invocation = invocation_spec
3102        .invocation_id()
3103        .context("derive the pre-descriptor RSJS invocation identity")?;
3104
3105    // Windows linkers and native build tools can still impose MAX_PATH even
3106    // when Rust accepts long paths. Keep full cache identities, but spend fewer
3107    // characters on descriptive directory labels before Cargo adds its tree.
3108    //
3109    // Cargo already isolates profiles, features, target triples, and bin/test
3110    // roots inside one `--target-dir`, and the descriptor cache keys every unit
3111    // and snapshot by its exact Cargo coordinate. Share one Cargo target and
3112    // content-addressed descriptor cache per wrapper+toolchain scope so `dev`,
3113    // `test` (across multiple integration tests), `check`, and `build` reuse
3114    // compiled dependencies instead of multiplying `target/` by every target.
3115    let namespace = metadata.target_directory.join(TOOL_NAMESPACE_DIR);
3116    let build_root = namespace.join(invocation.to_string());
3117    let shared_root = namespace
3118        .join(if cfg!(windows) { "s" } else { "shared" })
3119        .join(&shared_target_scope);
3120    let source_exclusion_directory = metadata.target_directory.clone();
3121    let nonce = fresh_build_nonce();
3122    let descriptor_staging = build_root
3123        .join(if cfg!(windows) {
3124            "s"
3125        } else {
3126            "descriptor-staging"
3127        })
3128        .join(&nonce);
3129    let descriptor_target = shared_root.join(if cfg!(windows) {
3130        format!("d{DESCRIPTOR_TARGET_POLICY_VERSION}-{DESCRIPTOR_UNIT_SIDECAR_SCHEMA_VERSION}-{PERSISTENT_DESCRIPTOR_TARGET_LAYOUT_VERSION}")
3131    } else {
3132        format!("descriptor-target-policy-v{DESCRIPTOR_TARGET_POLICY_VERSION}-sidecar-v{DESCRIPTOR_UNIT_SIDECAR_SCHEMA_VERSION}-persistent-v{PERSISTENT_DESCRIPTOR_TARGET_LAYOUT_VERSION}")
3133    });
3134    let descriptor_cache_directory = shared_root.join(if cfg!(windows) {
3135        format!("c{DESCRIPTOR_CACHE_SCHEMA_VERSION}")
3136    } else {
3137        format!("descriptor-cache-v{DESCRIPTOR_CACHE_SCHEMA_VERSION}")
3138    });
3139    let plan_directory = namespace.join(if cfg!(windows) { "p" } else { "plans" });
3140    let final_target_root = namespace
3141        .join(if cfg!(windows) { "f" } else { "final-target" })
3142        .join(&shared_target_scope);
3143    let mut descriptor_cargo_args = parsed.cargo_args.clone();
3144    // The wrapper adds one explicit object output even when Cargo selected
3145    // `check`, so linked checks can keep descriptor and final rustc unit
3146    // coordinates identical. Tests require their exact `cfg(test)`/harness
3147    // compilation, so both phases use `cargo test`. The descriptor harness
3148    // never runs. Managed tests launch the final harness after publication.
3149    descriptor_cargo_args[0] = OsString::from(action.descriptor_subcommand());
3150    if action == LinkedCargoAction::Test {
3151        descriptor_cargo_args.push("--no-run".into());
3152    }
3153    let mut final_cargo_args = parsed.cargo_args.clone();
3154    final_cargo_args[0] = OsString::from(action.final_subcommand());
3155    if action.final_cargo_executes() && !parsed.runtime_args.is_empty() {
3156        final_cargo_args.push("--".into());
3157        final_cargo_args.extend(parsed.runtime_args.iter().cloned());
3158    }
3159
3160    Ok(PreparedLinkedCargo {
3161        request: LinkedCargoRequest {
3162            descriptor: DescriptorCargoRequest {
3163                cargo: parsed.cargo,
3164                wrapper,
3165                working_directory: root.to_path_buf(),
3166                staging_directory: descriptor_staging,
3167                target_directory: descriptor_target,
3168                source_exclusion_directory,
3169                cargo_args: descriptor_cargo_args,
3170                environment: environment.clone(),
3171            },
3172            root: DescriptorRootSelector {
3173                package_id: selected_root.package_id,
3174                target_name: selected_root.target_name,
3175                target_kinds: selected_root.target_kinds,
3176                role: action.root_role(),
3177                artifact_path: None,
3178            },
3179            invocation,
3180            producer: RSJS_COMPILER_PRODUCER,
3181            runtime_protocol: RSJS_RUNTIME_PROTOCOL,
3182            plan_directory,
3183            final_target_root,
3184            final_cargo_args,
3185            final_environment: environment.clone(),
3186        },
3187        profile: parsed.profile,
3188        target_triple: parsed.target,
3189        runtime_args: parsed.runtime_args,
3190        descriptor_cache_directory,
3191        package_source_root,
3192        public_output_directory,
3193        _wrapper_lock: wrapper_lock,
3194    })
3195}
3196
3197fn shared_cargo_target_scope(
3198    wrapper_fingerprint: &str,
3199    cargo_version: &str,
3200    rustc_version: &str,
3201    cli_producer: ProducerVersion,
3202) -> String {
3203    let mut hash = Sha256::new();
3204    hash.update(b"proa.rsjs.shared-cargo-target-scope.v1\0");
3205    let producer = format!(
3206        "{}.{}.{}",
3207        cli_producer.major, cli_producer.minor, cli_producer.patch
3208    );
3209    let abi = format!("{}.{}", RSJS_COMPILER_ABI.major, RSJS_COMPILER_ABI.minor);
3210    let transport = TRANSPORT_FORMAT_VERSION.to_string();
3211    for field in [
3212        wrapper_fingerprint,
3213        cargo_version,
3214        rustc_version,
3215        &producer,
3216        &abi,
3217        &transport,
3218    ] {
3219        hash.update((field.len() as u64).to_le_bytes());
3220        hash.update(field.as_bytes());
3221    }
3222    let digest = hash.finalize();
3223    format!("{:x}", base16ct::HexDisplay(&digest[..8]))
3224}
3225
3226#[cfg(not(windows))]
3227fn prepare_wrapper_with_session(
3228    source_exclusion: &Path,
3229    snapshot_root: &Path,
3230    wrapper: &Path,
3231    session: Option<&mut DevSessionCache>,
3232) -> Result<(PathBuf, Option<fs::File>, String)> {
3233    let source_stamp = fs::metadata(wrapper)
3234        .ok()
3235        .map(|m| FileStamp::from_metadata(&m));
3236    if let (Some(cache), Some(stamp)) = (session.as_deref(), source_stamp) {
3237        if let Some(cached) = &cache.wrapper_snapshot {
3238            if cached.source_path == wrapper
3239                && cached.source_stamp == stamp
3240                && cached.snapshot_root == snapshot_root
3241                && cached.snapshot_path.is_file()
3242            {
3243                return Ok((
3244                    cached.snapshot_path.clone(),
3245                    None,
3246                    cached.fingerprint.clone(),
3247                ));
3248            }
3249        }
3250    }
3251    let (snapshot, lock) = prepare_wrapper_executable(source_exclusion, snapshot_root, wrapper)?;
3252    let fingerprint = wrapper_executable_fingerprint(&snapshot)?;
3253    if let (Some(cache), Some(stamp)) = (session, source_stamp) {
3254        cache.wrapper_snapshot = Some(CachedWrapperSnapshot {
3255            source_path: wrapper.to_path_buf(),
3256            source_stamp: stamp,
3257            snapshot_root: snapshot_root.to_path_buf(),
3258            snapshot_path: snapshot.clone(),
3259            fingerprint: fingerprint.clone(),
3260        });
3261    }
3262    Ok((snapshot, lock, fingerprint))
3263}
3264
3265#[cfg(windows)]
3266fn prepare_wrapper_with_session(
3267    source_exclusion: &Path,
3268    snapshot_root: &Path,
3269    wrapper: &Path,
3270    _session: Option<&mut DevSessionCache>,
3271) -> Result<(PathBuf, Option<fs::File>, String)> {
3272    let (resolved, lock) = prepare_wrapper_executable(source_exclusion, snapshot_root, wrapper)?;
3273    let fingerprint = wrapper_executable_fingerprint(&resolved)?;
3274    Ok((resolved, lock, fingerprint))
3275}
3276
3277#[cfg(not(windows))]
3278fn prepare_wrapper_executable(
3279    source_exclusion: &Path,
3280    snapshot_root: &Path,
3281    wrapper: &Path,
3282) -> Result<(PathBuf, Option<fs::File>)> {
3283    let snapshot = snapshot_wrapper_executable(source_exclusion, snapshot_root, wrapper)
3284        .context("publish the cargo-proa wrapper into its content-addressed snapshot")?;
3285    Ok((snapshot, None))
3286}
3287
3288#[cfg(windows)]
3289fn prepare_wrapper_executable(
3290    _source_exclusion: &Path,
3291    _snapshot_root: &Path,
3292    wrapper: &Path,
3293) -> Result<(PathBuf, Option<fs::File>)> {
3294    use std::os::windows::fs::OpenOptionsExt as _;
3295    use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_READ;
3296
3297    let wrapper = fs::canonicalize(wrapper)
3298        .with_context(|| format!("resolve cargo-proa wrapper `{}`", wrapper.display()))?;
3299    let lock = fs::OpenOptions::new()
3300        .read(true)
3301        .share_mode(FILE_SHARE_READ)
3302        .open(&wrapper)
3303        .with_context(|| {
3304            format!(
3305                "lock cargo-proa wrapper `{}` against replacement during linked compilation",
3306                wrapper.display()
3307            )
3308        })?;
3309    Ok((wrapper, Some(lock)))
3310}
3311
3312fn wrapper_executable_fingerprint(path: &Path) -> Result<String> {
3313    use std::fmt::Write as _;
3314    use std::io::Read as _;
3315
3316    let mut executable = fs::File::open(path)
3317        .with_context(|| format!("open cargo-proa wrapper executable `{}`", path.display()))?;
3318    let metadata = executable
3319        .metadata()
3320        .with_context(|| format!("inspect cargo-proa wrapper executable `{}`", path.display()))?;
3321    if !metadata.is_file() {
3322        bail!(
3323            "cargo-proa wrapper executable is not a regular file: `{}`",
3324            path.display()
3325        );
3326    }
3327
3328    let mut hasher = Sha256::new();
3329    hasher.update(RSJS_WRAPPER_EXECUTABLE_FINGERPRINT_DOMAIN);
3330    let mut buffer = [0_u8; 64 * 1024];
3331    loop {
3332        let read = executable
3333            .read(&mut buffer)
3334            .with_context(|| format!("hash cargo-proa wrapper executable `{}`", path.display()))?;
3335        if read == 0 {
3336            break;
3337        }
3338        hasher.update(&buffer[..read]);
3339    }
3340
3341    let digest: [u8; 32] = hasher.finalize().into();
3342    let mut encoded = String::with_capacity("sha256:".len() + digest.len() * 2);
3343    encoded.push_str("sha256:");
3344    for byte in digest {
3345        let _ = write!(encoded, "{byte:02x}");
3346    }
3347    Ok(encoded)
3348}
3349
3350#[cfg(test)]
3351fn parse_cargo_build_command(command: &[String]) -> Result<ParsedCargoInvocation> {
3352    parse_cargo_command(command, LinkedCargoAction::Build)
3353}
3354
3355fn parse_cargo_command(
3356    command: &[String],
3357    action: LinkedCargoAction,
3358) -> Result<ParsedCargoInvocation> {
3359    let Some((program, raw_args)) = command.split_first() else {
3360        bail!(
3361            "linked Cargo {} command cannot be empty",
3362            action.subcommand()
3363        );
3364    };
3365    if !is_cargo_program(program) {
3366        bail!(
3367            "`cargo proa {command}` requires a Cargo {cargo_action} command for the linked RSJS pipeline; found `{}`. Custom non-Cargo commands are not supported yet",
3368            shellish(command),
3369            command = action.command_name(),
3370            cargo_action = action.subcommand(),
3371        );
3372    }
3373    if raw_args.first().map(String::as_str) != Some(action.subcommand()) {
3374        bail!(
3375            "`cargo proa {command}` currently supports only `cargo {cargo_action}`; found `{}`. Other Cargo subcommands do not yet have linked-root semantics for this workflow",
3376            shellish(command),
3377            command = action.command_name(),
3378            cargo_action = action.subcommand(),
3379        );
3380    }
3381
3382    let mut package = None;
3383    let mut bin = None;
3384    let mut example = None;
3385    let mut test = None;
3386    let mut explicit_profile = None;
3387    let mut release = false;
3388    let mut target = None;
3389    let mut features = BTreeSet::new();
3390    let mut locked = false;
3391    let mut offline = false;
3392    let mut metadata_flags = Vec::new();
3393    let mut selection_args = Vec::new();
3394    let mut runtime_args = Vec::new();
3395    let mut cargo_arg_count = raw_args.len();
3396    let mut index = 1;
3397    while index < raw_args.len() {
3398        let argument = &raw_args[index];
3399        match argument.as_str() {
3400            "--message-format" | "--target-dir" => {
3401                let value = raw_args.get(index + 1).cloned();
3402                bail!(
3403                    "Cargo argument `{argument}{}` is reserved by the linked RSJS pipeline; remove it so cargo-proa can isolate descriptor and final artifacts",
3404                    value
3405                        .as_deref()
3406                        .map(|value| format!(" {value}"))
3407                        .unwrap_or_default()
3408                );
3409            }
3410            value
3411                if value.starts_with("--message-format=") || value.starts_with("--target-dir=") =>
3412            {
3413                bail!(
3414                    "Cargo argument `{value}` is reserved by the linked RSJS pipeline; remove it so cargo-proa can own Cargo messages and artifact namespaces"
3415                );
3416            }
3417            "--workspace" | "--all" | "--exclude" | "--bins" | "--examples" | "--tests"
3418            | "--benches" | "--all-targets" | "--lib" | "--bench" => {
3419                bail!(
3420                    "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"
3421                );
3422            }
3423            "--manifest-path" | "--config" | "--artifact-dir" => {
3424                bail!(
3425                    "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"
3426                );
3427            }
3428            value
3429                if value.starts_with("--manifest-path=")
3430                    || value.starts_with("--config=")
3431                    || value.starts_with("--artifact-dir=") =>
3432            {
3433                bail!(
3434                    "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"
3435                );
3436            }
3437            "--" => {
3438                if !action.permits_runtime_arguments() {
3439                    bail!(
3440                        "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"
3441                    );
3442                }
3443                cargo_arg_count = index;
3444                runtime_args.extend(raw_args[index + 1..].iter().map(OsString::from));
3445                break;
3446            }
3447            "-p" | "--package" => {
3448                let value = required_cargo_value(raw_args, &mut index, argument)?;
3449                set_once(&mut package, value, "Cargo package")?;
3450            }
3451            value if value.starts_with("--package=") => {
3452                set_once(
3453                    &mut package,
3454                    nonempty_option_value(value, "--package=")?,
3455                    "Cargo package",
3456                )?;
3457            }
3458            value if value.starts_with("-p") && value.len() > 2 => {
3459                set_once(&mut package, value[2..].to_string(), "Cargo package")?;
3460            }
3461            "--bin" => {
3462                let value = required_cargo_value(raw_args, &mut index, argument)?;
3463                set_once(&mut bin, value, "Cargo binary")?;
3464            }
3465            value if value.starts_with("--bin=") => {
3466                set_once(
3467                    &mut bin,
3468                    nonempty_option_value(value, "--bin=")?,
3469                    "Cargo binary",
3470                )?;
3471            }
3472            "--example" if action != LinkedCargoAction::Test => {
3473                let value = required_cargo_value(raw_args, &mut index, argument)?;
3474                set_once(&mut example, value, "Cargo example")?;
3475            }
3476            value if action != LinkedCargoAction::Test && value.starts_with("--example=") => {
3477                set_once(
3478                    &mut example,
3479                    nonempty_option_value(value, "--example=")?,
3480                    "Cargo example",
3481                )?;
3482            }
3483            "--example" => {
3484                bail!(
3485                    "Cargo target-selection argument `--example` is not supported by `cargo proa test`; use `--bin <name>` or `--test <name>`"
3486                );
3487            }
3488            value if value.starts_with("--example=") => {
3489                bail!(
3490                    "Cargo target-selection argument `{value}` is not supported by `cargo proa test`; use `--bin <name>` or `--test <name>`"
3491                );
3492            }
3493            "--test" if action == LinkedCargoAction::Test => {
3494                let value = required_cargo_value(raw_args, &mut index, argument)?;
3495                set_once(&mut test, value, "Cargo integration test")?;
3496            }
3497            value if action == LinkedCargoAction::Test && value.starts_with("--test=") => {
3498                set_once(
3499                    &mut test,
3500                    nonempty_option_value(value, "--test=")?,
3501                    "Cargo integration test",
3502                )?;
3503            }
3504            "--test" => {
3505                bail!(
3506                    "Cargo target-selection argument `--test` is valid only for `cargo proa test`"
3507                );
3508            }
3509            value if value.starts_with("--test=") => {
3510                bail!(
3511                    "Cargo target-selection argument `{value}` is valid only for `cargo proa test`"
3512                );
3513            }
3514            "--profile" => {
3515                let value = required_cargo_value(raw_args, &mut index, argument)?;
3516                set_once(&mut explicit_profile, value, "Cargo profile")?;
3517            }
3518            value if value.starts_with("--profile=") => {
3519                set_once(
3520                    &mut explicit_profile,
3521                    nonempty_option_value(value, "--profile=")?,
3522                    "Cargo profile",
3523                )?;
3524            }
3525            "--release" => {
3526                if release {
3527                    bail!("Cargo profile selector `--release` was supplied more than once");
3528                }
3529                release = true;
3530            }
3531            "--target" => {
3532                let value = required_cargo_value(raw_args, &mut index, argument)?;
3533                set_once(&mut target, value, "Cargo target")?;
3534            }
3535            value if value.starts_with("--target=") => {
3536                set_once(
3537                    &mut target,
3538                    nonempty_option_value(value, "--target=")?,
3539                    "Cargo target",
3540                )?;
3541            }
3542            "--features" | "-F" => {
3543                let value = required_cargo_value(raw_args, &mut index, argument)?;
3544                extend_features(&mut features, &value)?;
3545            }
3546            value if value.starts_with("--features=") => {
3547                extend_features(&mut features, &nonempty_option_value(value, "--features=")?)?;
3548            }
3549            value if value.starts_with("-F") && value.len() > 2 => {
3550                extend_features(&mut features, &value[2..])?;
3551            }
3552            "--all-features" | "--no-default-features" => {
3553                metadata_flags.push(argument.clone().into());
3554                selection_args.push(argument.clone());
3555            }
3556            "--locked" => {
3557                locked = true;
3558                metadata_flags.push(argument.clone().into());
3559            }
3560            "--offline" => {
3561                offline = true;
3562                metadata_flags.push(argument.clone().into());
3563            }
3564            "--frozen" => {
3565                locked = true;
3566                offline = true;
3567                metadata_flags.push(argument.clone().into());
3568            }
3569            "-q"
3570            | "--quiet"
3571            | "-v"
3572            | "-vv"
3573            | "--verbose"
3574            | "--keep-going"
3575            | "--future-incompat-report"
3576            | "--timings"
3577            | "--ignore-rust-version" => {
3578                selection_args.push(argument.clone());
3579            }
3580            "--jobs" | "-j" | "--color" => {
3581                let value = required_cargo_value(raw_args, &mut index, argument)?;
3582                selection_args.push(argument.clone());
3583                selection_args.push(value);
3584            }
3585            value
3586                if value.starts_with("--jobs=")
3587                    || value.starts_with("--color=")
3588                    || value.starts_with("--timings=")
3589                    || (value.starts_with("-j") && value.len() > 2) =>
3590            {
3591                selection_args.push(value.to_string());
3592            }
3593            other => {
3594                bail!(
3595                    "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",
3596                    action = action.subcommand(),
3597                );
3598            }
3599        }
3600        index += 1;
3601    }
3602
3603    if release && explicit_profile.is_some() {
3604        bail!("Cargo profile is ambiguous: use either `--release` or `--profile`, not both");
3605    }
3606    if bin.is_some() && example.is_some() {
3607        bail!(
3608            "linked Cargo target selection is ambiguous: use either `--bin <name>` or `--example <name>`, not both"
3609        );
3610    }
3611    if action == LinkedCargoAction::Test && bin.is_some() == test.is_some() {
3612        bail!(
3613            "linked Cargo test requires exactly one target selector: use either `--bin <name>` or `--test <name>`"
3614        );
3615    }
3616    let profile = explicit_profile.unwrap_or_else(|| {
3617        if release {
3618            "release".to_string()
3619        } else if action == LinkedCargoAction::Test {
3620            "test".to_string()
3621        } else {
3622            "dev".to_string()
3623        }
3624    });
3625
3626    Ok(ParsedCargoInvocation {
3627        cargo: OsString::from(program),
3628        cargo_args: raw_args[..cargo_arg_count]
3629            .iter()
3630            .map(OsString::from)
3631            .collect(),
3632        runtime_args,
3633        package,
3634        bin,
3635        example,
3636        test,
3637        profile,
3638        target,
3639        features,
3640        locked,
3641        offline,
3642        metadata_flags,
3643        selection_args,
3644    })
3645}
3646
3647fn required_cargo_value(arguments: &[String], index: &mut usize, option: &str) -> Result<String> {
3648    *index += 1;
3649    let Some(value) = arguments.get(*index) else {
3650        bail!("Cargo option `{option}` requires a value");
3651    };
3652    if value.is_empty() || value.starts_with('-') {
3653        bail!("Cargo option `{option}` requires a nonempty value");
3654    }
3655    Ok(value.clone())
3656}
3657
3658fn nonempty_option_value(argument: &str, prefix: &str) -> Result<String> {
3659    let value = &argument[prefix.len()..];
3660    if value.is_empty() {
3661        bail!(
3662            "Cargo option `{}` requires a nonempty value",
3663            &prefix[..prefix.len() - 1]
3664        );
3665    }
3666    Ok(value.to_string())
3667}
3668
3669fn set_once(slot: &mut Option<String>, value: String, label: &str) -> Result<()> {
3670    if let Some(previous) = slot {
3671        bail!(
3672            "{label} selection is ambiguous: both `{previous}` and `{value}` were supplied; select exactly one"
3673        );
3674    }
3675    *slot = Some(value);
3676    Ok(())
3677}
3678
3679fn extend_features(features: &mut BTreeSet<String>, value: &str) -> Result<()> {
3680    let parsed = value
3681        .split([',', ' '])
3682        .filter(|feature| !feature.is_empty())
3683        .collect::<Vec<_>>();
3684    if parsed.is_empty() {
3685        bail!("Cargo `--features` requires at least one feature name");
3686    }
3687    features.extend(parsed.into_iter().map(str::to_string));
3688    Ok(())
3689}
3690
3691fn is_cargo_program(program: &str) -> bool {
3692    Path::new(program)
3693        .file_name()
3694        .and_then(OsStr::to_str)
3695        .is_some_and(|name| matches!(name, "cargo" | "cargo.exe"))
3696}
3697
3698fn load_cargo_metadata(root: &Path, parsed: &ParsedCargoInvocation) -> Result<CargoMetadata> {
3699    let manifest = root.join("Cargo.toml");
3700    let mut command = Command::new(&parsed.cargo);
3701    command
3702        .current_dir(root)
3703        .args([
3704            OsStr::new("metadata"),
3705            OsStr::new("--format-version=1"),
3706            OsStr::new("--no-deps"),
3707            OsStr::new("--manifest-path"),
3708        ])
3709        .arg(&manifest)
3710        .args(&parsed.metadata_flags);
3711    let output = command.output().with_context(|| {
3712        format!(
3713            "run Cargo metadata with `{}` for exact RSJS root selection",
3714            Path::new(&parsed.cargo).display()
3715        )
3716    })?;
3717    if !output.status.success() {
3718        bail!(
3719            "Cargo metadata failed while selecting the exact RSJS root ({status}):\n{stderr}",
3720            status = output.status,
3721            stderr = String::from_utf8_lossy(&output.stderr).trim()
3722        );
3723    }
3724    serde_json::from_slice(&output.stdout).context("parse Cargo metadata for RSJS root selection")
3725}
3726
3727fn select_exact_cargo_root(
3728    metadata: &CargoMetadata,
3729    parsed: &ParsedCargoInvocation,
3730    action: LinkedCargoAction,
3731) -> Result<ExactCargoRoot> {
3732    let (requested_target_kind, requested_target_name) = match action {
3733        LinkedCargoAction::Test => match (&parsed.bin, &parsed.test) {
3734            (Some(name), None) => ("bin", name.as_str()),
3735            (None, Some(name)) => ("test", name.as_str()),
3736            _ => {
3737                bail!(
3738                    "linked Cargo test requires exactly one target selector: use either `--bin <name>` or `--test <name>`"
3739                )
3740            }
3741        },
3742        LinkedCargoAction::Build
3743        | LinkedCargoAction::Check
3744        | LinkedCargoAction::Dev
3745        | LinkedCargoAction::Run => match (&parsed.bin, &parsed.example) {
3746            (Some(name), None) => ("bin", name.as_str()),
3747            (None, Some(name)) => ("example", name.as_str()),
3748            (None, None) => ("bin", ""),
3749            (Some(_), Some(_)) => {
3750                bail!(
3751                    "linked Cargo target selection is ambiguous: use either `--bin <name>` or `--example <name>`, not both"
3752                )
3753            }
3754        },
3755    };
3756    let workspace_members = metadata
3757        .workspace_members
3758        .iter()
3759        .map(String::as_str)
3760        .collect::<BTreeSet<_>>();
3761    let default_members = metadata
3762        .workspace_default_members
3763        .iter()
3764        .map(String::as_str)
3765        .collect::<BTreeSet<_>>();
3766    if parsed.package.is_none() && default_members.len() != 1 {
3767        bail!(
3768            "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>`",
3769            default_members.len(),
3770        );
3771    }
3772    let mut packages = metadata
3773        .packages
3774        .iter()
3775        .filter(|package| workspace_members.contains(package.id.as_str()))
3776        .filter(|package| match &parsed.package {
3777            Some(selector) => cargo_package_matches(package, selector),
3778            None => default_members.contains(package.id.as_str()),
3779        })
3780        .collect::<Vec<_>>();
3781    packages.sort_by(|left, right| left.id.cmp(&right.id));
3782
3783    if packages.is_empty() {
3784        match &parsed.package {
3785            Some(package) => bail!(
3786                "Cargo metadata contains no exact workspace package matching `-p {package}`; package specs must resolve to one workspace package"
3787            ),
3788            None => bail!(
3789                "Cargo metadata has no default workspace member to use as an RSJS root; pass `-p <package>` plus an exact target"
3790            ),
3791        }
3792    }
3793    if parsed.package.is_some() && packages.len() != 1 {
3794        bail!(
3795            "Cargo package selector `{}` matches {} workspace packages; pass one unambiguous package ID and exact target",
3796            parsed.package.as_deref().unwrap_or_default(),
3797            packages.len()
3798        );
3799    }
3800
3801    let mut candidates = Vec::new();
3802    for package in packages {
3803        if !package.manifest_path.is_absolute() {
3804            bail!(
3805                "Cargo package `{}` has a relative manifest path `{}`; exact source-closure diagnostics require an absolute package root",
3806                package.name,
3807                package.manifest_path.display()
3808            );
3809        }
3810        let package_source_root = package.manifest_path.parent().ok_or_else(|| {
3811            anyhow::anyhow!(
3812                "Cargo package `{}` manifest path `{}` has no parent directory",
3813                package.name,
3814                package.manifest_path.display()
3815            )
3816        })?;
3817        for target in &package.targets {
3818            let kinds = target.kind.iter().cloned().collect::<BTreeSet<_>>();
3819            if !kinds.contains(requested_target_kind) {
3820                continue;
3821            }
3822            if !requested_target_name.is_empty() && requested_target_name != target.name {
3823                continue;
3824            }
3825            candidates.push(ExactCargoRoot {
3826                package_id: package.id.clone(),
3827                package_name: package.name.clone(),
3828                package_source_root: package_source_root.to_path_buf(),
3829                target_name: target.name.clone(),
3830                target_kinds: kinds,
3831                requested_target_kind: requested_target_kind.to_string(),
3832            });
3833        }
3834    }
3835    candidates.sort_by(|left, right| {
3836        (&left.package_id, &left.target_name).cmp(&(&right.package_id, &right.target_name))
3837    });
3838
3839    match candidates.len() {
3840        0 => {
3841            if !requested_target_name.is_empty() {
3842                bail!(
3843                    "Cargo metadata contains no `{requested_target_kind}` target named `{requested_target_name}` in the selected package set"
3844                );
3845            }
3846            bail!(
3847                "the selected Cargo package set has no `{requested_target_kind}` target; the linked RSJS pipeline requires one executable root"
3848            );
3849        }
3850        1 => Ok(candidates.remove(0)),
3851        count => {
3852            let rendered = candidates
3853                .iter()
3854                .map(|candidate| format!("{}::{}", candidate.package_name, candidate.target_name))
3855                .collect::<Vec<_>>()
3856                .join(", ");
3857            bail!(
3858                "Cargo selection resolves to {count} `{requested_target_kind}` roots ({rendered}); cargo-proa will not guess. Pass an exact package and target"
3859            );
3860        }
3861    }
3862}
3863
3864fn cargo_package_matches(package: &CargoMetadataPackage, selector: &str) -> bool {
3865    selector == package.id
3866        || selector == package.name
3867        || selector == format!("{}@{}", package.name, package.version)
3868        || selector == format!("{}:{}", package.name, package.version)
3869}
3870
3871fn parse_producer_version(version: &str) -> Result<ProducerVersion> {
3872    let core = version.split_once('-').map_or(version, |(core, _)| core);
3873    let mut parts = core.split('.');
3874    let major = parse_version_part(parts.next(), "major", version)?;
3875    let minor = parse_version_part(parts.next(), "minor", version)?;
3876    let patch = parse_version_part(parts.next(), "patch", version)?;
3877    if parts.next().is_some() {
3878        bail!("unsupported cargo-proa producer version `{version}`");
3879    }
3880    Ok(ProducerVersion::new(major, minor, patch))
3881}
3882
3883fn cli_tool_producer_version() -> Result<ProducerVersion> {
3884    parse_producer_version(env!("CARGO_PKG_VERSION"))
3885}
3886
3887fn parse_version_part(part: Option<&str>, name: &str, version: &str) -> Result<u16> {
3888    part.ok_or_else(|| anyhow::anyhow!("cargo-proa version `{version}` has no {name} component"))?
3889        .parse::<u16>()
3890        .with_context(|| format!("parse cargo-proa {name} version from `{version}`"))
3891}
3892
3893fn tool_version(
3894    program: &OsStr,
3895    args: &[&str],
3896    label: &str,
3897    working_directory: &Path,
3898) -> Result<String> {
3899    let output = Command::new(program)
3900        .args(args)
3901        .current_dir(working_directory)
3902        .output()
3903        .with_context(|| {
3904            format!(
3905                "query {label} version from `{}`",
3906                Path::new(program).display()
3907            )
3908        })?;
3909    if !output.status.success() {
3910        bail!(
3911            "{label} version query failed with {}: {}",
3912            output.status,
3913            String::from_utf8_lossy(&output.stderr).trim()
3914        );
3915    }
3916    let version = String::from_utf8(output.stdout)
3917        .with_context(|| format!("{label} version output is not UTF-8"))?
3918        .trim()
3919        .to_string();
3920    if version.is_empty() {
3921        bail!("{label} version query returned empty output");
3922    }
3923    Ok(version)
3924}
3925
3926fn selected_rustc_version(working_directory: &Path) -> Result<String> {
3927    let rustc = std::env::var_os("RUSTC").unwrap_or_else(|| OsString::from("rustc"));
3928    tool_version(&rustc, &["-vV"], "rustc", working_directory)
3929}
3930
3931fn declared_build_environment() -> BTreeMap<String, DeclaredEnvironmentInput> {
3932    [
3933        "RUSTC",
3934        "RUSTFLAGS",
3935        "CARGO_ENCODED_RUSTFLAGS",
3936        "CARGO_BUILD_TARGET",
3937        "RUSTUP_TOOLCHAIN",
3938    ]
3939    .into_iter()
3940    .map(|name| {
3941        let value = std::env::var_os(name).map(|value| os_value_bytes(&value));
3942        (
3943            name.to_string(),
3944            DeclaredEnvironmentInput {
3945                name: name.to_string(),
3946                value_hash: SemanticHash::derive(&value),
3947            },
3948        )
3949    })
3950    .collect()
3951}
3952
3953#[cfg(unix)]
3954fn os_value_bytes(value: &OsStr) -> Vec<u8> {
3955    use std::os::unix::ffi::OsStrExt;
3956    value.as_bytes().to_vec()
3957}
3958
3959#[cfg(windows)]
3960fn os_value_bytes(value: &OsStr) -> Vec<u8> {
3961    use std::os::windows::ffi::OsStrExt;
3962    value.encode_wide().flat_map(u16::to_le_bytes).collect()
3963}
3964
3965#[cfg(not(any(unix, windows)))]
3966fn os_value_bytes(value: &OsStr) -> Vec<u8> {
3967    value.to_string_lossy().into_owned().into_bytes()
3968}
3969
3970fn absolute_project_root(root: PathBuf) -> Result<PathBuf> {
3971    let root = if root.is_absolute() {
3972        root
3973    } else {
3974        std::env::current_dir()?.join(root)
3975    };
3976    fs::canonicalize(&root)
3977        .with_context(|| format!("resolve absolute Proa project root `{}`", root.display()))
3978}
3979
3980fn fresh_build_nonce() -> String {
3981    let elapsed = SystemTime::now()
3982        .duration_since(UNIX_EPOCH)
3983        .unwrap_or_default()
3984        .as_nanos();
3985    let sequence = RSJS_BUILD_NONCE.fetch_add(1, Ordering::Relaxed);
3986    format!("{}-{elapsed}-{sequence}", std::process::id())
3987}
3988
3989fn print_linked_cargo_output(
3990    action: LinkedCargoAction,
3991    request: &LinkedCargoRequest,
3992    output: &LinkedCargoOutput,
3993) {
3994    println!(
3995        "linked RSJS plan {} for package `{}` binary `{}`",
3996        output.semantic.plan_id, request.root.package_id, request.root.target_name
3997    );
3998    match action {
3999        LinkedCargoAction::Build => println!(
4000            "final Cargo artifacts: {}",
4001            output.final_cargo.target_directory.display()
4002        ),
4003        LinkedCargoAction::Check => println!(
4004            "final Cargo check artifacts: {}",
4005            output.final_cargo.target_directory.display()
4006        ),
4007        LinkedCargoAction::Dev => println!(
4008            "final Cargo dev artifacts: {}",
4009            output.final_cargo.target_directory.display()
4010        ),
4011        LinkedCargoAction::Run => println!(
4012            "final Cargo run artifacts: {}",
4013            output.final_cargo.target_directory.display()
4014        ),
4015        LinkedCargoAction::Test => println!(
4016            "final Cargo test artifacts: {}",
4017            output.final_cargo.target_directory.display()
4018        ),
4019    }
4020}
4021
4022fn run_project_check(root: &Path, config: &ProjectConfig) -> Result<()> {
4023    let report = scaffold::site_check_with_config(root.to_path_buf(), config)?;
4024    scaffold::print_site_check(&report, false)?;
4025    if !report.errors.is_empty() {
4026        bail!("Proa site check failed");
4027    }
4028
4029    let src = root.join("src");
4030    if src.exists() {
4031        let paths = vec![src];
4032        let format_summary = crate::fmt::format_paths_with_options(&paths, true, true)?;
4033        for diagnostic in &format_summary.diagnostics {
4034            eprint!("{diagnostic}");
4035        }
4036        if !format_summary.changed.is_empty() {
4037            for path in &format_summary.changed {
4038                eprintln!("{}: Proa macro formatting differs", path.display());
4039            }
4040            bail!("Proa formatting check failed");
4041        }
4042        if format_summary
4043            .diagnostics
4044            .iter()
4045            .any(|diag| diag.severity == Severity::Error)
4046        {
4047            bail!("Proa formatting failed");
4048        }
4049
4050        let diagnostics = crate::lint::lint_paths(&paths, crate::lint::LintOptions::default())?;
4051        for diagnostic in &diagnostics {
4052            if diagnostic.severity.rank() >= Severity::Warning.rank() {
4053                eprint!("{diagnostic}");
4054            }
4055        }
4056        if diagnostics
4057            .iter()
4058            .any(|diag| matches!(diag.severity, Severity::Error | Severity::Warning))
4059        {
4060            bail!("Proa check failed");
4061        }
4062    }
4063
4064    Ok(())
4065}
4066
4067pub fn build_assets_for_project(root: &Path) -> Result<()> {
4068    let config = load_project_config(root)?;
4069    build_assets(root, &config)
4070}
4071
4072fn build_assets(root: &Path, config: &ProjectConfig) -> Result<()> {
4073    build_assets_for_change(root, config, None, &[])
4074}
4075
4076fn build_assets_for_change(
4077    root: &Path,
4078    config: &ProjectConfig,
4079    public: Option<&Path>,
4080    changed: &[PathBuf],
4081) -> Result<()> {
4082    if let Some(output) = crate::config::css_script_output(config) {
4083        prepare_asset_output(root, &output)?;
4084        let status = script::command(root, "css", &config.scripts.css, &[])?
4085            .status()
4086            .context("run scripts.css")?;
4087        exit_status_to_result(status, "scripts.css")?;
4088    }
4089    for asset in config.build.assets() {
4090        if let Some(public) = public {
4091            if should_skip_managed_tailwind_asset(root, public, asset, changed) {
4092                continue;
4093            }
4094        }
4095        build_asset(root, asset)?;
4096    }
4097    Ok(())
4098}
4099
4100fn should_skip_managed_tailwind_asset(
4101    root: &Path,
4102    public: &Path,
4103    asset: &AssetConfig,
4104    changed: &[PathBuf],
4105) -> bool {
4106    // Only skip the built-in managed Tailwind invocation; custom asset commands
4107    // may read undeclared files anywhere in `public/`.
4108    if asset.kind != "tailwind" || !asset.command.is_empty() || changed.is_empty() {
4109        return false;
4110    }
4111    if !root.join(&asset.output).is_file() {
4112        return false;
4113    }
4114    changed
4115        .iter()
4116        .all(|path| path.starts_with(public) && is_opaque_to_tailwind(path))
4117}
4118
4119/// Whether Tailwind can be trusted never to read this file.
4120///
4121/// Tailwind scans every file it does not recognize as binary, whatever the
4122/// extension: JSON, SVG, plain text, and templates in any language can all
4123/// contribute class names, and stylesheets can be imported. Skipping it is
4124/// therefore safe only for formats on its own binary list. Anything else,
4125/// including a file with no extension, runs Tailwind as before.
4126fn is_opaque_to_tailwind(path: &Path) -> bool {
4127    path.extension().and_then(OsStr::to_str).is_some_and(|ext| {
4128        matches!(
4129            ext.to_ascii_lowercase().as_str(),
4130            "png"
4131                | "jpg"
4132                | "jpeg"
4133                | "gif"
4134                | "webp"
4135                | "avif"
4136                | "ico"
4137                | "bmp"
4138                | "tif"
4139                | "tiff"
4140                | "heic"
4141                | "woff"
4142                | "woff2"
4143                | "ttf"
4144                | "otf"
4145                | "eot"
4146                | "mp3"
4147                | "wav"
4148                | "ogg"
4149                | "flac"
4150                | "aac"
4151                | "m4a"
4152                | "mp4"
4153                | "m4v"
4154                | "mov"
4155                | "webm"
4156                | "avi"
4157                | "mkv"
4158                | "pdf"
4159                | "zip"
4160                | "gz"
4161                | "wasm"
4162        )
4163    })
4164}
4165
4166fn build_asset(root: &Path, asset: &AssetConfig) -> Result<()> {
4167    let command = asset_command(root, asset)?;
4168    if command.is_empty() {
4169        return Ok(());
4170    }
4171
4172    if asset.kind == "tailwind"
4173        && asset.command.is_empty()
4174        && command
4175            .first()
4176            .is_some_and(|program| program == "tailwindcss")
4177        && !program_available("tailwindcss")
4178    {
4179        if root.join(&asset.output).is_file() {
4180            eprintln!(
4181                "warning: managed Tailwind binary is not cached; preserving prebuilt {}",
4182                asset.output.display()
4183            );
4184            return Ok(());
4185        }
4186        bail!(
4187            "Tailwind output `{}` is missing and the managed compiler is unavailable",
4188            asset.output.display()
4189        );
4190    }
4191
4192    prepare_asset_output(root, &asset.output)?;
4193    run_command_status(root, &command, "asset command")
4194}
4195
4196fn prepare_asset_output(root: &Path, output: &Path) -> Result<()> {
4197    if let Some(output_parent) = output.parent() {
4198        let output_parent = root.join(output_parent);
4199        fs::create_dir_all(&output_parent)
4200            .with_context(|| format!("create {}", output_parent.display()))?;
4201    }
4202
4203    dev_ui::detail!("building asset: {}", output.display());
4204    Ok(())
4205}
4206
4207fn asset_command(root: &Path, asset: &AssetConfig) -> Result<Vec<String>> {
4208    if !asset.command.is_empty() {
4209        return Ok(asset.command.clone());
4210    }
4211
4212    match asset.kind.as_str() {
4213        "tailwind" => {
4214            if !root.join(&asset.input).exists() {
4215                eprintln!(
4216                    "warning: tailwind input `{}` not found; skipping asset build for `{}`",
4217                    asset.input.display(),
4218                    asset.output.display()
4219                );
4220                return Ok(Vec::new());
4221            }
4222
4223            let mut command = vec![
4224                "tailwindcss".into(),
4225                "-i".into(),
4226                asset.input.display().to_string(),
4227                "-o".into(),
4228                asset.output.display().to_string(),
4229            ];
4230            if let Some(config) = &asset.config {
4231                if root.join(config).exists() {
4232                    command.push("-c".into());
4233                    command.push(config.display().to_string());
4234                }
4235            }
4236            Ok(command)
4237        }
4238        "command" if asset.command.is_empty() => Ok(Vec::new()),
4239        other => bail!("unknown asset kind `{other}` in proa.config.rs"),
4240    }
4241}
4242
4243fn program_available(program: &str) -> bool {
4244    let Some(search_path) = env::var_os("PATH") else {
4245        return false;
4246    };
4247    env::split_paths(&search_path).any(|directory| {
4248        let candidate = directory.join(program);
4249        candidate.is_file() || cfg!(windows) && directory.join(format!("{program}.exe")).is_file()
4250    })
4251}
4252
4253fn run_linked_dev_foreground(
4254    root: &Path,
4255    launch: &LinkedDevLaunch,
4256    host: &str,
4257    port: u16,
4258    open: bool,
4259) -> Result<()> {
4260    let mut child = spawn_linked_dev(root, launch, host, port, None)?;
4261    announce_dev_start(open, host, port, &mut child);
4262    let status = child.process.wait().context("wait for linked dev server");
4263    clear_active_child_group();
4264    exit_status_to_result(status?, "linked dev server")
4265}
4266
4267struct DevChild {
4268    process: Child,
4269    readiness: Option<readiness::ReadyChannel>,
4270}
4271
4272impl DevChild {
4273    fn ready_url(&mut self, host: &str, port: u16) -> Option<String> {
4274        reload::wait_until_serving(
4275            host,
4276            port,
4277            DEV_READY_TIMEOUT,
4278            &mut || matches!(self.process.try_wait(), Ok(None)),
4279            self.readiness.as_mut(),
4280        )
4281    }
4282
4283    fn restart(
4284        &mut self,
4285        root: &Path,
4286        launch: &LinkedDevLaunch,
4287        address: (&str, u16),
4288        hot: Option<&mut crate::hot_static::HotState>,
4289        reload: Option<&ReloadServer>,
4290    ) -> Result<()> {
4291        stop_child(&mut self.process)?;
4292        clear_active_child_group();
4293        if let Some(hot) = hot {
4294            hot.activate()?;
4295        }
4296        *self = spawn_linked_dev(root, launch, address.0, address.1, reload)?;
4297        announce_reload(reload, address.0, address.1, self);
4298        Ok(())
4299    }
4300}
4301
4302fn spawn_linked_dev(
4303    root: &Path,
4304    launch: &LinkedDevLaunch,
4305    host: &str,
4306    port: u16,
4307    reload: Option<&ReloadServer>,
4308) -> Result<DevChild> {
4309    print_linked_dev_launch(launch);
4310    public_assets::cleanup(launch.public_assets.as_deref());
4311    let session = reload.map(|server| (server.port(), server.token().to_owned()));
4312    let mut cmd = linked_dev_command(root, launch, host, port, session.as_ref());
4313    cmd.env_remove("PROA_DEV_READY");
4314    let readiness = readiness::ReadyChannel::bind(&mut cmd, host, port)
4315        .map_err(|error| {
4316            eprintln!(
4317                "Dev URL reporting unavailable ({error}). Checking the configured TCP listener."
4318            );
4319        })
4320        .ok();
4321    // Put the dev command in its own process group so restarts can stop the
4322    // whole server tree and release its port before activating the next plan.
4323    #[cfg(unix)]
4324    {
4325        use std::os::unix::process::CommandExt;
4326        cmd.process_group(0);
4327    }
4328    let process = cmd.spawn().with_context(|| {
4329        format!(
4330            "spawn linked dev executable `{}`",
4331            launch.executable.display()
4332        )
4333    })?;
4334    set_active_child_group(&process);
4335    Ok(DevChild { process, readiness })
4336}
4337
4338fn linked_dev_command(
4339    root: &Path,
4340    launch: &LinkedDevLaunch,
4341    host: &str,
4342    port: u16,
4343    session: Option<&(u16, String)>,
4344) -> Command {
4345    let mut cmd = Command::new(&launch.executable);
4346    cmd.args(&launch.arguments);
4347    cmd.current_dir(root);
4348    cmd.env("HOST", host);
4349    cmd.env("PROA_HOST", host);
4350    cmd.env("PORT", port.to_string());
4351    public_assets::runtime_environment(&mut cmd, launch.public_assets.as_deref());
4352    // These two are the whole contract with `proa_framework_axum::serve`, which
4353    // injects the live-reload client only when both are present. A stale
4354    // value inherited from the environment must never survive into a run with
4355    // live reload switched off.
4356    match session {
4357        Some((reload_port, token)) => {
4358            cmd.env(reload::RELOAD_PORT_ENV, reload_port.to_string());
4359            cmd.env(reload::RELOAD_TOKEN_ENV, token);
4360        }
4361        None => {
4362            cmd.env_remove(reload::RELOAD_PORT_ENV);
4363            cmd.env_remove(reload::RELOAD_TOKEN_ENV);
4364        }
4365    }
4366    cmd
4367}
4368
4369fn print_linked_dev_launch(launch: &LinkedDevLaunch) {
4370    if launch.single_pass {
4371        dev_ui::detail!(
4372            "starting final linked server `{}` with plan {} (single-pass, final cache {} reused)",
4373            launch.executable.display(),
4374            launch.plan_id,
4375            launch.reused_final_artifacts,
4376        );
4377    } else {
4378        dev_ui::detail!(
4379            "starting final linked server `{}` with plan {} (descriptor cache {}/{}, final cache {} reused)",
4380            launch.executable.display(),
4381            launch.plan_id,
4382            launch.reused_descriptor_artifacts,
4383            launch.descriptor_artifacts,
4384            launch.reused_final_artifacts,
4385        );
4386    }
4387}
4388
4389fn run_command_status(root: &Path, command: &[String], label: &str) -> Result<()> {
4390    dev_ui::detail!("running {}", shellish(command));
4391    let mut base = command_base(root, command)?;
4392    // The interactive dev view shows a tool's own output only when it fails.
4393    let run = if dev_ui::pretty() {
4394        // `output()` would close stdin. A command may still prompt on it.
4395        base.stdin(std::process::Stdio::inherit())
4396            .output()
4397            .map(|output| {
4398                if !output.status.success() {
4399                    let _ = io::Write::write_all(&mut io::stderr(), &output.stdout);
4400                    let _ = io::Write::write_all(&mut io::stderr(), &output.stderr);
4401                }
4402                output.status
4403            })
4404    } else {
4405        base.status()
4406    };
4407    let status = match run {
4408        Ok(status) => status,
4409        // A missing program surfaces as a bare "No such file or directory",
4410        // which reads as a missing input file rather than a tool that was
4411        // never installed. Name the program and say how to get it.
4412        Err(error) if error.kind() == io::ErrorKind::NotFound => {
4413            let program = command.first().map(String::as_str).unwrap_or(label);
4414            bail!("{}", missing_program_message(program));
4415        }
4416        Err(error) => return Err(error).with_context(|| format!("run `{}`", shellish(command))),
4417    };
4418    exit_status_to_result(status, label)
4419}
4420
4421fn missing_program_message(program: &str) -> String {
4422    let hint = match program {
4423        "tailwindcss" => {
4424            if cfg!(windows) {
4425                "\n  Install the standalone Tailwind CSS CLI v4 for Windows as tailwindcss.exe\n  \
4426                 and add its directory to PATH, then reopen your terminal.\n  \
4427                 See https://proa.so/docs/cli/new-site#tailwind-prerequisite"
4428            } else {
4429                "\n  Install Tailwind CSS CLI v4 with the Proa installer:\n  \
4430                 curl -fsSL https://proa.so/install.sh | \
4431                 sh -s -- --tailwind-only\n  \
4432                 Or, on macOS or Linux with Homebrew: brew install tailwindcss"
4433            }
4434        }
4435        _ => "\n  Install it and make sure it is on PATH, or set an explicit `command` for this asset in proa.config.rs.",
4436    };
4437    format!("`{program}` was not found on PATH.{hint}")
4438}
4439
4440fn command_base(root: &Path, command: &[String]) -> Result<Command> {
4441    let Some((program, args)) = command.split_first() else {
4442        bail!("command cannot be empty")
4443    };
4444    let mut cmd = Command::new(program);
4445    cmd.args(args);
4446    cmd.current_dir(root);
4447    Ok(cmd)
4448}
4449
4450fn exit_status_to_result(status: ExitStatus, label: &str) -> Result<()> {
4451    if status.success() {
4452        Ok(())
4453    } else {
4454        bail!("{label} exited with {status}")
4455    }
4456}
4457
4458fn stop_child(child: &mut Child) -> Result<()> {
4459    if child.try_wait()?.is_some() {
4460        return Ok(());
4461    }
4462
4463    #[cfg(unix)]
4464    {
4465        // Signal the whole process group: TERM first so the server can shut
4466        // down gracefully and release its port, then KILL if it lingers.
4467        let group = -(child.id() as i32);
4468        unsafe { libc::kill(group, libc::SIGTERM) };
4469        let deadline = Instant::now() + Duration::from_secs(2);
4470        loop {
4471            if child.try_wait()?.is_some() {
4472                return Ok(());
4473            }
4474            if Instant::now() >= deadline {
4475                break;
4476            }
4477            // Most servers exit promptly on TERM. Observe that exit without
4478            // imposing a whole watch-poll interval before activating the build.
4479            thread::sleep(Duration::from_millis(5));
4480        }
4481        unsafe { libc::kill(group, libc::SIGKILL) };
4482        let _ = child.wait();
4483        Ok(())
4484    }
4485
4486    #[cfg(not(unix))]
4487    {
4488        child.kill().context("stop dev command")?;
4489        let _ = child.wait();
4490        Ok(())
4491    }
4492}
4493
4494type WatchSnapshot = BTreeMap<PathBuf, FileStamp>;
4495
4496#[derive(Debug, Clone, PartialEq, Eq)]
4497enum DevWatchDecision {
4498    Idle,
4499    Debouncing,
4500    Ready(WatchSnapshot),
4501}
4502
4503#[derive(Debug)]
4504struct DevWatchDebouncer {
4505    committed: WatchSnapshot,
4506    pending: Option<(WatchSnapshot, Duration)>,
4507    delay: Duration,
4508}
4509
4510impl DevWatchDebouncer {
4511    fn new(committed: WatchSnapshot, delay: Duration) -> Self {
4512        Self {
4513            committed,
4514            pending: None,
4515            delay,
4516        }
4517    }
4518
4519    fn next_poll_delay(&self, now: Duration) -> Duration {
4520        let Some((_, first_seen)) = self.pending.as_ref() else {
4521            return DEV_WATCH_POLL;
4522        };
4523        // Wake at the end of the quiet window instead of rounding it up to
4524        // another whole poll interval. A fresh snapshot still authorizes the
4525        // rebuild; changed bytes reset the full window in observe().
4526        self.delay
4527            .saturating_sub(now.saturating_sub(*first_seen))
4528            .clamp(Duration::from_millis(1), DEV_WATCH_POLL)
4529    }
4530
4531    fn observe(&mut self, now: Duration, snapshot: WatchSnapshot) -> DevWatchDecision {
4532        if snapshot == self.committed {
4533            self.pending = None;
4534            return DevWatchDecision::Idle;
4535        }
4536
4537        match &mut self.pending {
4538            Some((pending, first_seen)) if *pending == snapshot => {
4539                if now.saturating_sub(*first_seen) >= self.delay {
4540                    DevWatchDecision::Ready(snapshot)
4541                } else {
4542                    DevWatchDecision::Debouncing
4543                }
4544            }
4545            pending => {
4546                *pending = Some((snapshot, now));
4547                DevWatchDecision::Debouncing
4548            }
4549        }
4550    }
4551
4552    fn commit(&mut self, snapshot: WatchSnapshot) {
4553        self.committed = snapshot;
4554        self.pending = None;
4555    }
4556}
4557
4558fn watch_snapshot(root: &Path, paths: &[PathBuf]) -> Result<WatchSnapshot> {
4559    let mut snapshot = BTreeMap::new();
4560    for rel in paths {
4561        let path = root.join(rel);
4562        if path.exists() {
4563            collect_file_stamps(root, &path, &mut snapshot)?;
4564        }
4565    }
4566    Ok(snapshot)
4567}
4568
4569fn collect_file_stamps(
4570    root: &Path,
4571    path: &Path,
4572    snapshot: &mut BTreeMap<PathBuf, FileStamp>,
4573) -> Result<()> {
4574    let mut metadata = match fs::symlink_metadata(path) {
4575        Ok(metadata) => metadata,
4576        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),
4577        Err(error) => return Err(error).with_context(|| format!("stat {}", path.display())),
4578    };
4579    if metadata.file_type().is_symlink() {
4580        let Ok(target) = fs::canonicalize(path) else {
4581            // Observe a broken symlink's own stamp instead of aborting the
4582            // watcher. Publication can then reject invalid public inputs while
4583            // keeping the last valid server running.
4584            let rel = path.strip_prefix(root).unwrap_or(path).to_path_buf();
4585            snapshot.insert(rel, FileStamp::from_metadata(&metadata));
4586            return Ok(());
4587        };
4588        if path
4589            .ancestors()
4590            .skip(1)
4591            .any(|parent| fs::canonicalize(parent).is_ok_and(|parent| parent == target))
4592        {
4593            // Observe the cycle's link instead of traversing it. Publication
4594            // can then reject invalid public inputs without losing the server.
4595            let rel = path.strip_prefix(root).unwrap_or(path).to_path_buf();
4596            snapshot.insert(rel, FileStamp::from_metadata(&metadata));
4597            return Ok(());
4598        }
4599        // Preserve ordinary source-link watching. Only link traversal needs
4600        // canonicalization; regular source trees retain one metadata read.
4601        metadata = match fs::metadata(path) {
4602            Ok(metadata) => metadata,
4603            Err(_) => {
4604                let rel = path.strip_prefix(root).unwrap_or(path).to_path_buf();
4605                snapshot.insert(rel, FileStamp::from_metadata(&metadata));
4606                return Ok(());
4607            }
4608        };
4609    }
4610    if metadata.is_dir() {
4611        if should_ignore_dir(path) {
4612            return Ok(());
4613        }
4614        let entries = match fs::read_dir(path) {
4615            Ok(entries) => entries,
4616            Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),
4617            Err(error) => return Err(error).with_context(|| format!("read {}", path.display())),
4618        };
4619        for entry in entries {
4620            collect_file_stamps(root, &entry?.path(), snapshot)?;
4621        }
4622    } else if metadata.is_file() {
4623        let rel = path.strip_prefix(root).unwrap_or(path).to_path_buf();
4624        snapshot.insert(rel, FileStamp::from_metadata(&metadata));
4625    }
4626    Ok(())
4627}
4628
4629fn should_ignore_dir(path: &Path) -> bool {
4630    matches!(
4631        path.file_name().and_then(|name| name.to_str()),
4632        Some("target" | "node_modules" | ".git")
4633    )
4634}
4635
4636#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4637struct FileStamp {
4638    len: u64,
4639    modified_nanos: u128,
4640}
4641
4642impl FileStamp {
4643    fn from_metadata(metadata: &fs::Metadata) -> Self {
4644        let modified_nanos = metadata
4645            .modified()
4646            .ok()
4647            .and_then(|modified| modified.duration_since(UNIX_EPOCH).ok())
4648            .map(|duration| duration.as_nanos())
4649            .unwrap_or(0);
4650
4651        Self {
4652            len: metadata.len(),
4653            modified_nanos,
4654        }
4655    }
4656}
4657
4658fn shellish(command: &[String]) -> String {
4659    command.join(" ")
4660}
4661
4662#[cfg(test)]
4663mod tests;