Skip to main content

proa_cli/
lifecycle.rs

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