Skip to main content

logicaffeine_cli/project/
build.rs

1//! Phase 37: Build Orchestration
2//!
3//! Coordinates the build process for LOGOS projects.
4//!
5//! This module handles the complete build pipeline:
6//! 1. Load the project manifest (`Largo.toml`)
7//! 2. Compile LOGOS source to Rust code
8//! 3. Set up a Cargo project with runtime dependencies
9//! 4. Invoke `cargo build` to produce the final binary
10//!
11//! # Build Directory Structure
12//!
13//! ```text
14//! target/
15//! ├── debug/
16//! │   └── build/           # Generated Cargo project (debug)
17//! │       ├── Cargo.toml
18//! │       ├── src/main.rs  # Generated Rust code
19//! │       └── target/      # Cargo's output
20//! └── release/
21//!     └── build/           # Generated Cargo project (release)
22//! ```
23
24use std::fmt::Write as FmtWrite;
25use std::fs;
26use std::path::{Path, PathBuf};
27use std::process::Command;
28
29use crate::compile::compile_project_with_deps;
30use logicaffeine_compile::compile::{copy_runtime_crates, CompileError, RuntimeCrateSource};
31
32use super::manifest::{Manifest, ManifestError};
33
34/// Configuration for a build operation.
35///
36/// Specifies the project location and build mode (debug/release).
37///
38/// # Example
39///
40/// ```no_run
41/// use std::path::PathBuf;
42/// use logicaffeine_cli::project::build::{BuildConfig, build};
43///
44/// let config = BuildConfig {
45///     project_dir: PathBuf::from("my_project"),
46///     release: false,
47///     lib_mode: false,
48///     target: None,
49/// };
50///
51/// let result = build(config)?;
52/// println!("Built: {}", result.binary_path.display());
53/// # Ok::<(), Box<dyn std::error::Error>>(())
54/// ```
55pub struct BuildConfig {
56    /// Root directory of the LOGOS project (contains `Largo.toml`).
57    pub project_dir: PathBuf,
58    /// If `true`, build with optimizations (`cargo build --release`).
59    pub release: bool,
60    /// If `true`, build as a library (cdylib) instead of a binary.
61    pub lib_mode: bool,
62    /// Target triple for cross-compilation (e.g., "wasm32-unknown-unknown").
63    /// "wasm" is expanded to "wasm32-unknown-unknown".
64    pub target: Option<String>,
65}
66
67/// Native executable backend selected by `largo build` / `largo run`.
68#[derive(Debug, Clone, Copy, PartialEq, Eq)]
69pub enum Backend {
70    /// The existing LOGOS → Rust → rustc pipeline.
71    Rust,
72    /// A LOGOS → C lowering compiled by the host C compiler.
73    C(super::build_c::CLowering),
74}
75
76impl Backend {
77    /// Parse a native C backend name accepted by `--emit`.
78    pub fn from_emit(emit: &str) -> Option<Self> {
79        match emit {
80            "c" => Some(Self::C(super::build_c::CLowering::Ast)),
81            "c-bytecode" => Some(Self::C(super::build_c::CLowering::Bytecode)),
82            _ => None,
83        }
84    }
85}
86
87/// Result of a successful build operation.
88///
89/// Contains paths to the build outputs, used by subsequent commands
90/// like [`run`] to execute the compiled binary.
91#[derive(Debug)]
92pub struct BuildResult {
93    /// Directory containing build artifacts (`target/debug` or `target/release`).
94    pub target_dir: PathBuf,
95    /// Path to the compiled executable.
96    pub binary_path: PathBuf,
97}
98
99/// Errors that can occur during the build process.
100#[derive(Debug)]
101pub enum BuildError {
102    /// Failed to load or parse the project manifest.
103    Manifest(ManifestError),
104    /// LOGOS-to-Rust compilation failed.
105    Compile(CompileError),
106    /// The program does not compile: the diagnostic, rendered at the author's `file:line:col`.
107    Diagnostic(String),
108    /// File system operation failed.
109    Io(String),
110    /// Cargo build command failed (classified; the raw output already
111    /// streamed to the user's terminal live).
112    Cargo(CargoFailure),
113    /// Cargo itself was not found on PATH (no Rust toolchain installed).
114    Toolchain(String),
115    /// The selected C compiler was not found.
116    CToolchain(String),
117    /// The selected C compiler rejected generated code.
118    CCompiler(String),
119    /// The selected backend does not support this build shape.
120    Unsupported(String),
121    /// A required file or directory was not found.
122    NotFound(String),
123}
124
125impl std::fmt::Display for BuildError {
126    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
127        match self {
128            BuildError::Manifest(e) => write!(f, "{}", e),
129            BuildError::Compile(e) => write!(f, "{}", e),
130            BuildError::Diagnostic(rendered) => write!(f, "{rendered}"),
131            BuildError::Io(e) => write!(f, "IO error: {}", e),
132            BuildError::Cargo(e) => write!(f, "{}", e),
133            BuildError::Toolchain(e) => write!(f, "{}", e),
134            BuildError::CToolchain(e) => write!(f, "{}", e),
135            BuildError::CCompiler(e) => write!(f, "{}", e),
136            BuildError::Unsupported(e) => write!(f, "{}", e),
137            BuildError::NotFound(e) => write!(f, "Not found: {}", e),
138        }
139    }
140}
141
142impl std::error::Error for BuildError {}
143
144/// What actually went wrong when `cargo build` failed, judged from its
145/// stderr tail.
146#[derive(Debug, Clone, Copy, PartialEq, Eq)]
147pub enum CargoFailureKind {
148    /// A dependency could not be resolved or fetched — a `## Requires`
149    /// problem (bad crate name/version, or no network), not a compiler bug.
150    DependencyResolution,
151    /// rustc rejected the generated code — a LOGOS compiler bug, never the
152    /// user's fault.
153    GeneratedCode,
154}
155
156/// A classified `cargo build` failure. The full output already streamed to
157/// the terminal; this carries the verdict plus the retained tail for
158/// programmatic callers.
159#[derive(Debug)]
160pub struct CargoFailure {
161    /// The classification verdict.
162    pub kind: CargoFailureKind,
163    /// The last portion of cargo's stderr (bounded).
164    pub tail: String,
165    /// The generated Cargo project the failure occurred in.
166    pub project_dir: PathBuf,
167}
168
169impl std::fmt::Display for CargoFailure {
170    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
171        match self.kind {
172            CargoFailureKind::DependencyResolution => write!(
173                f,
174                "a `## Requires` dependency could not be resolved (cargo's output above has the details)"
175            ),
176            CargoFailureKind::GeneratedCode => write!(
177                f,
178                "the generated Rust failed to compile — this is a LOGOS compiler bug, not an error in your program (generated project: {})",
179                self.project_dir.display()
180            ),
181        }
182    }
183}
184
185/// Whether a `## Requires` crate name / version / feature is safe to write
186/// into the generated Cargo.toml verbatim: strictly alphanumerics plus the
187/// characters cargo specs actually use. Anything else (quotes, newlines,
188/// brackets) could smuggle TOML structure into the manifest.
189pub fn requires_component_is_safe(s: &str) -> bool {
190    !s.is_empty()
191        && s.chars().all(|c| {
192            c.is_ascii_alphanumeric()
193                || matches!(
194                    c,
195                    '-' | '_' | '.' | '^' | '~' | '*' | '<' | '>' | '=' | '+' | ',' | ' '
196                )
197        })
198}
199
200/// Judge a failed `cargo build` from its stderr tail.
201///
202/// Dependency-resolution failures (unknown crate, impossible version
203/// requirement, index/network fetch trouble) are the user-actionable class;
204/// everything else — above all rustc errors in the generated code — is a
205/// compiler bug on our side and is framed that way.
206pub fn classify_cargo_failure(stderr_tail: &str) -> CargoFailureKind {
207    const DEPENDENCY_MARKERS: [&str; 6] = [
208        "no matching package",
209        "failed to select a version",
210        "failed to get ",
211        "failed to fetch",
212        "failed to load source for dependency",
213        "unable to get packages from source",
214    ];
215    if DEPENDENCY_MARKERS.iter().any(|m| stderr_tail.contains(m)) {
216        CargoFailureKind::DependencyResolution
217    } else {
218        CargoFailureKind::GeneratedCode
219    }
220}
221
222impl From<ManifestError> for BuildError {
223    fn from(e: ManifestError) -> Self {
224        BuildError::Manifest(e)
225    }
226}
227
228impl From<CompileError> for BuildError {
229    fn from(e: CompileError) -> Self {
230        BuildError::Compile(e)
231    }
232}
233
234/// Find the project root by walking up the directory tree.
235///
236/// Searches for a `Largo.toml` file starting from `start` and moving
237/// up through parent directories. Returns the directory containing
238/// the manifest, or `None` if no manifest is found.
239///
240/// # Arguments
241///
242/// * `start` - Starting path (can be a file or directory)
243///
244/// # Example
245///
246/// ```no_run
247/// use std::path::Path;
248/// use logicaffeine_cli::project::build::find_project_root;
249///
250/// // Find project root from a subdirectory
251/// let root = find_project_root(Path::new("/projects/myapp/src/lib.lg"));
252/// assert_eq!(root, Some("/projects/myapp".into()));
253/// ```
254pub fn find_project_root(start: &Path) -> Option<PathBuf> {
255    let mut current = if start.is_file() {
256        start.parent()?.to_path_buf()
257    } else {
258        start.to_path_buf()
259    };
260
261    loop {
262        if current.join("Largo.toml").exists() {
263            return Some(current);
264        }
265        if !current.pop() {
266            return None;
267        }
268    }
269}
270
271/// Plan the embedded site for a full-stack project, or `None` when this is not one — the
272/// project's own [`BuildPlan`](super::shape::BuildPlan), the same decision `largo serve` routes on.
273/// A broken page (or an unassemblable import) is a LOUD build error here, before cargo — never a
274/// silently-dropped asset.
275///
276/// The returned table is the whole site in the dev router's URL namespace, so a binary built from
277/// it serves BYTE-for-byte what `largo serve` serves from memory (dev ≡ prod by construction).
278fn plan_web_bundle(
279    project_dir: &Path,
280) -> Result<Option<Vec<crate::commands::web_bundle::Asset>>, BuildError> {
281    // An entry whose shape cannot be decided does not parse; the compile step below reports that
282    // at its line, so it is not reported twice here.
283    let embeds_site = super::shape::Project::load(project_dir)
284        .and_then(|project| project.shape())
285        .map(|shape| shape.build_plan() == super::shape::BuildPlan::Binary { embeds_site: true })
286        .unwrap_or(false);
287    if !embeds_site {
288        return Ok(None);
289    }
290    let assets = crate::commands::web_bundle::plan_site(
291        &project_dir.join("pages"),
292        &project_dir.join("static"),
293    )
294    .map_err(|e| BuildError::Io(e.to_string()))?;
295    Ok(Some(assets))
296}
297
298/// Build a LOGOS project.
299///
300/// Compiles the project specified in `config` through the full build pipeline:
301/// 1. Load and validate the manifest
302/// 2. Compile LOGOS source to Rust
303/// 3. Generate a Cargo project with runtime dependencies
304/// 4. Run `cargo build`
305///
306/// The entry point is determined from the manifest's `package.entry` field,
307/// with a `.md` extension fallback if the `.lg` file doesn't exist.
308///
309/// # Errors
310///
311/// Returns an error if:
312/// - The manifest cannot be loaded
313/// - The entry point file doesn't exist
314/// - LOGOS compilation fails
315/// - Cargo build fails
316pub fn build(config: BuildConfig) -> Result<BuildResult, BuildError> {
317    build_backend(config, Backend::Rust)
318}
319
320/// Build through an explicitly selected native executable backend.
321pub fn build_backend(config: BuildConfig, backend: Backend) -> Result<BuildResult, BuildError> {
322    // Load manifest
323    let manifest = Manifest::load(&config.project_dir)?;
324
325    // The entry program (`.lg`, else its `.md` sibling), confined to the project. A site has
326    // none to build: `largo build` exports it instead, and a binary of it is not a thing.
327    let entry_path = super::shape::entry_file(&config.project_dir, &manifest)
328        .map_err(|e| BuildError::NotFound(e.message))?
329        .ok_or_else(|| {
330            BuildError::NotFound(super::shape::site_without_entry(&config.project_dir).message)
331        })?;
332    match backend {
333        Backend::Rust => build_with_entry(&config, &manifest, &entry_path),
334        Backend::C(lowering) => {
335            super::build_c::build_c_with_entry(&config, &manifest, &entry_path, lowering)
336        }
337    }
338}
339
340fn build_with_entry(
341    config: &BuildConfig,
342    manifest: &Manifest,
343    entry_path: &Path,
344) -> Result<BuildResult, BuildError> {
345    let started = std::time::Instant::now();
346    crate::ui::phase(
347        "Compiling",
348        format!(
349            "{} v{} (LOGOS → Rust)",
350            manifest.package.name, manifest.package.version
351        ),
352    );
353
354    // Create target directory structure
355    let target_dir = config.project_dir.join("target");
356    let build_dir = if config.release {
357        target_dir.join("release")
358    } else {
359        target_dir.join("debug")
360    };
361    let rust_project_dir = build_dir.join("build");
362
363    // Clean and recreate build directory
364    if rust_project_dir.exists() {
365        fs::remove_dir_all(&rust_project_dir).map_err(|e| BuildError::Io(e.to_string()))?;
366    }
367    fs::create_dir_all(&rust_project_dir).map_err(|e| BuildError::Io(e.to_string()))?;
368
369    // B4 — full-stack embed. A web project (a `Serve` entry alongside `pages/`
370    // or `static/`) bundles its whole site INTO the binary: every page compiled
371    // to wasm/js/html and every static asset collected, planned into ONE table
372    // in the dev router's URL namespace. `None` for a plain program (or a
373    // library build — a cdylib does not serve), where the build stays exactly as
374    // before. A broken page fails the build LOUDLY here, before cargo.
375    let site_assets = if config.lib_mode {
376        None
377    } else {
378        plan_web_bundle(&config.project_dir)?
379    };
380
381    // Link the declared local (`path`/`git`) dependencies: their roots are
382    // admitted by the loader so a bare `Import <Dep>.` resolves outside the
383    // project, threaded identically to every other tier. A floating git rev or
384    // a missing path fails the build loudly here.
385    let dep_roots = manifest
386        .resolve_dependencies(&config.project_dir)
387        .map_err(|e| BuildError::Io(e.to_string()))?
388        .into_iter()
389        .map(|d| logicaffeine_compile::loader::DepRoot {
390            name: d.name,
391            root: d.root,
392        })
393        .collect::<Vec<_>>();
394
395    // Compile LOGOS to Rust using Phase 36 compile_project. For a web build the
396    // `Serve` closure must consult the embedded `logos_assets` table before the
397    // handler (assets-first, the dev router's precedence) — a thread-local
398    // codegen scope threads that in without touching the plain-program path.
399    let compiled = if site_assets.is_some() {
400        logicaffeine_compile::codegen::with_embed_assets(|| {
401            compile_project_with_deps(entry_path, dep_roots.clone())
402        })
403    } else {
404        compile_project_with_deps(entry_path, dep_roots.clone())
405    };
406    let output = compiled.map_err(|e| match e {
407        CompileError::Parse(_) => BuildError::Diagnostic(
408            crate::diagnostics::compile_error(&e, entry_path, &dep_roots).message,
409        ),
410        other => BuildError::Compile(other),
411    })?;
412
413    // Write generated Rust code
414    let src_dir = rust_project_dir.join("src");
415    fs::create_dir_all(&src_dir).map_err(|e| BuildError::Io(e.to_string()))?;
416
417    let rust_code = output.rust_code.clone();
418
419    if config.lib_mode {
420        // Library mode: strip fn main() wrapper, write to lib.rs
421        let lib_code = strip_main_wrapper(&rust_code);
422        fs::write(src_dir.join("lib.rs"), lib_code).map_err(|e| BuildError::Io(e.to_string()))?;
423    } else if let Some(ref assets) = site_assets {
424        // Emit the `logos_assets` module + stage each asset's bytes beside it in
425        // `src/`, and declare the module at the top of the generated program so
426        // its `Serve` closure's `logos_assets::lookup` resolves. The assets ride
427        // via `include_bytes!` — the binary is genuinely one self-contained file.
428        use crate::commands::web_bundle::{page_patterns, site_assets_module, staged_asset_files};
429        // The page patterns the binary must answer — read from the SAME `pages/` the assets were
430        // planned from, so the shipped table and the shipped documents cannot disagree.
431        let patterns = page_patterns(&config.project_dir.join("pages"));
432        fs::write(
433            src_dir.join("logos_assets.rs"),
434            site_assets_module(&config.project_dir.join("pages"), assets, &patterns),
435        )
436        .map_err(|e| BuildError::Io(e.to_string()))?;
437        for (name, bytes) in staged_asset_files(assets) {
438            fs::write(src_dir.join(&name), bytes).map_err(|e| BuildError::Io(e.to_string()))?;
439        }
440        let main_code = format!("mod logos_assets;\n{rust_code}");
441        fs::write(src_dir.join("main.rs"), main_code).map_err(|e| BuildError::Io(e.to_string()))?;
442    } else {
443        fs::write(src_dir.join("main.rs"), &rust_code)
444            .map_err(|e| BuildError::Io(e.to_string()))?;
445    }
446
447    // Universal ABI: Write C header alongside generated code if present
448    if let Some(ref c_header) = output.c_header {
449        let header_name = format!("{}.h", manifest.package.name);
450        fs::write(rust_project_dir.join(&header_name), c_header)
451            .map_err(|e| BuildError::Io(e.to_string()))?;
452    }
453
454    // Resolve target triple (expand "wasm" shorthand)
455    let resolved_target = config.target.as_deref().map(|t| {
456        if t.eq_ignore_ascii_case("wasm") {
457            "wasm32-unknown-unknown"
458        } else {
459            t
460        }
461    });
462
463    // Write Cargo.toml for the generated project. Its one target carries the project's
464    // [`artifact_identity`], never the bare package name: every project that shares a
465    // `CARGO_TARGET_DIR` writes into one directory, and two projects called `app` would otherwise
466    // be two builds of one file.
467    let identity = artifact_identity(&manifest.package.name, &config.project_dir);
468    let mut cargo_toml = format!(
469        r#"[package]
470name = "{}"
471version = "{}"
472edition = "2021"
473autobins = false
474"#,
475        manifest.package.name, manifest.package.version
476    );
477    if config.lib_mode {
478        let _ = writeln!(
479            cargo_toml,
480            "\n[lib]\nname = \"{}\"\npath = \"src/lib.rs\"\ncrate-type = [\"cdylib\"]",
481            identity.replace('-', "_")
482        );
483    } else {
484        let _ = writeln!(
485            cargo_toml,
486            "\n[[bin]]\nname = \"{identity}\"\npath = \"src/main.rs\""
487        );
488    }
489
490    // In a checkout we stage runtime sources and path-depend on them; an
491    // installed `largo` (no checkout) depends on the matching crates.io release.
492    let runtime_source = RuntimeCrateSource::detect();
493    let _ = writeln!(cargo_toml, "\n[dependencies]");
494    let _ = writeln!(cargo_toml, "{}", runtime_source.data_dep());
495    let _ = writeln!(
496        cargo_toml,
497        "{}",
498        runtime_source.system_dep(&["full", "http"])
499    );
500    let _ = writeln!(
501        cargo_toml,
502        "tokio = {{ version = \"1\", features = [\"rt-multi-thread\", \"macros\"] }}"
503    );
504
505    // Third-party crates the generated code names directly (rayon, memchr, serde) — the one list
506    // the staged checking manifest shares, so a program that checks is a program that builds.
507    for line in logicaffeine_compile::compile::implied_crate_deps(&rust_code, &output.dependencies)
508    {
509        let _ = writeln!(cargo_toml, "{line}");
510    }
511
512    // Auto-inject wasm-bindgen when targeting wasm32
513    let mut has_wasm_bindgen = false;
514    if let Some(target) = resolved_target {
515        if target.starts_with("wasm32") {
516            let _ = writeln!(cargo_toml, "wasm-bindgen = \"0.2\"");
517            has_wasm_bindgen = true;
518        }
519    }
520
521    // Append user-declared dependencies from ## Requires blocks — these must
522    // stay inside [dependencies], before any later section header, and every
523    // component must be manifest-safe (no TOML structure smuggled in).
524    for dep in &output.dependencies {
525        if dep.name == "wasm-bindgen" && has_wasm_bindgen {
526            continue; // Already injected
527        }
528        if !requires_component_is_safe(&dep.name)
529            || !requires_component_is_safe(&dep.version)
530            || dep.features.iter().any(|f| !requires_component_is_safe(f))
531        {
532            return Err(BuildError::Compile(CompileError::Io(format!(
533                "`## Requires` declaration for '{}' contains characters that are not valid in a Cargo manifest",
534                dep.name
535            ))));
536        }
537        if dep.features.is_empty() {
538            let _ = writeln!(cargo_toml, "{} = \"{}\"", dep.name, dep.version);
539        } else {
540            let feats = dep
541                .features
542                .iter()
543                .map(|f| format!("\"{}\"", f))
544                .collect::<Vec<_>>()
545                .join(", ");
546            let _ = writeln!(
547                cargo_toml,
548                "{} = {{ version = \"{}\", features = [{}] }}",
549                dep.name, dep.version, feats
550            );
551        }
552    }
553
554    let _ = write!(cargo_toml, "\n{}", runtime_source.linux_engine_section());
555
556    // Release profile: maximize optimization for compiled programs
557    let _ = writeln!(
558        cargo_toml,
559        "\n[profile.release]\nlto = true\nopt-level = 3\ncodegen-units = 1\npanic = \"{}\"\nstrip = true",
560        logicaffeine_compile::codegen::release_panic_strategy(&rust_code)
561    );
562
563    fs::write(rust_project_dir.join("Cargo.toml"), &cargo_toml)
564        .map_err(|e| BuildError::Io(e.to_string()))?;
565
566    // Emit .cargo/config.toml with target-cpu=native for release builds.
567    // Only when not cross-compiling (target-cpu=native refers to the host CPU).
568    if config.release && resolved_target.is_none() {
569        let cargo_config_dir = rust_project_dir.join(".cargo");
570        fs::create_dir_all(&cargo_config_dir).map_err(|e| BuildError::Io(e.to_string()))?;
571        fs::write(
572            cargo_config_dir.join("config.toml"),
573            "[build]\nrustflags = [\"-C\", \"target-cpu=native\"]\n",
574        )
575        .map_err(|e| BuildError::Io(e.to_string()))?;
576    }
577
578    // Stage runtime sources only inside a checkout; a standalone install pulls
579    // them from crates.io, so there is nothing to copy.
580    if runtime_source.is_workspace() {
581        copy_runtime_crates(&rust_project_dir)?;
582    }
583
584    // Run cargo build: stdout inherits, stderr streams through a tee so the
585    // user watches cargo's progress live while we retain a bounded tail for
586    // failure classification.
587    crate::ui::phase("Building", "generated Rust (cargo)");
588    let mut cmd = Command::new("cargo");
589    // `json-render-diagnostics`: cargo still renders every diagnostic and its progress to stderr
590    // for the author, and reports each file it produced as a JSON message on stdout — which is
591    // how this build learns the path of ITS artifact rather than assuming one.
592    cmd.arg("build")
593        .arg("--message-format=json-render-diagnostics")
594        .current_dir(&rust_project_dir);
595    if config.release {
596        cmd.arg("--release");
597    }
598    if let Some(target) = resolved_target {
599        cmd.arg("--target").arg(target);
600    }
601    // Cargo sees a pipe on stderr and would disable its own color; pass the
602    // resolved choice explicitly so cargo and largo agree.
603    let color_arg = match anstream::AutoStream::choice(&std::io::stderr()) {
604        anstream::ColorChoice::Never => "never",
605        _ => "always",
606    };
607    cmd.arg("--color").arg(color_arg);
608    if crate::ui::is_quiet() {
609        cmd.arg("--quiet");
610    } else if crate::ui::verbosity() > 0 {
611        cmd.arg("--verbose");
612    }
613    cmd.stdout(std::process::Stdio::piped());
614    cmd.stderr(std::process::Stdio::piped());
615
616    let mut child = cmd.spawn().map_err(|e| {
617        if e.kind() == std::io::ErrorKind::NotFound {
618            BuildError::Toolchain(
619                "cargo was not found on PATH — a Rust toolchain is required for `largo build`"
620                    .to_string(),
621            )
622        } else {
623            BuildError::Io(e.to_string())
624        }
625    })?;
626
627    // Tee thread: copy raw bytes (cargo redraws progress with `\r`, so no
628    // line buffering) to our stderr while retaining the last TAIL_CAP bytes.
629    const TAIL_CAP: usize = 64 * 1024;
630    let mut child_err = child.stderr.take().expect("stderr was piped");
631    let tee = std::thread::spawn(move || {
632        use std::io::{Read, Write};
633        let mut tail: Vec<u8> = Vec::new();
634        let mut buf = [0u8; 8192];
635        let mut err_out = std::io::stderr();
636        loop {
637            match child_err.read(&mut buf) {
638                Ok(0) | Err(_) => break,
639                Ok(n) => {
640                    let _ = err_out.write_all(&buf[..n]);
641                    let _ = err_out.flush();
642                    tail.extend_from_slice(&buf[..n]);
643                    if tail.len() > TAIL_CAP {
644                        let cut = tail.len() - TAIL_CAP;
645                        tail.drain(..cut);
646                    }
647                }
648            }
649        }
650        tail
651    });
652
653    let mut child_out = child.stdout.take().expect("stdout was piped");
654    let messages = std::thread::spawn(move || {
655        use std::io::Read;
656        let mut all = String::new();
657        let _ = child_out.read_to_string(&mut all);
658        all
659    });
660
661    let status = child.wait().map_err(|e| BuildError::Io(e.to_string()))?;
662    let tail_bytes = tee.join().unwrap_or_default();
663    let messages = messages.join().unwrap_or_default();
664
665    if !status.success() {
666        let tail = String::from_utf8_lossy(&tail_bytes).into_owned();
667        let kind = classify_cargo_failure(&tail);
668
669        // A generated-code error points at the emitted Rust; re-check with the
670        // source-mapped codegen and show the user WHERE in their LOGOS source it
671        // came from. Best-effort: on any failure to remap, the raw cargo output
672        // (already streamed above) stands alone.
673        if kind == CargoFailureKind::GeneratedCode {
674            if let Ok(assembled) = logicaffeine_compile::analysis::assemble_project(&entry_path) {
675                if let Ok(remapped) = logicaffeine_compile::compile::remap_project_errors(
676                    &assembled.source,
677                    &rust_project_dir,
678                    Some(&assembled.source_map),
679                ) {
680                    if !remapped.is_empty() {
681                        eprintln!("\n— in your LOGOS source —");
682                        for err in &remapped {
683                            eprintln!("{err}");
684                        }
685                    }
686                }
687            }
688        }
689
690        return Err(BuildError::Cargo(CargoFailure {
691            kind,
692            tail,
693            project_dir: rust_project_dir,
694        }));
695    }
696
697    crate::ui::phase(
698        "Finished",
699        format!(
700            "{} profile in {:.1}s",
701            if config.release { "release" } else { "dev" },
702            started.elapsed().as_secs_f64()
703        ),
704    );
705
706    // The file this build wrote, as cargo reports it — whatever `CARGO_TARGET_DIR`, `--target` or
707    // a cargo config moved it to — published at the project's stable `target/<mode>/`, which only
708    // this project writes. The published file is the one reported and the one `largo run` runs.
709    let built = built_artifact(&messages, &identity, config.lib_mode).ok_or_else(|| {
710        BuildError::Io(format!(
711            "cargo finished but reported no {} named `{identity}`; its output is in {}",
712            if config.lib_mode { "library" } else { "binary" },
713            rust_project_dir.display()
714        ))
715    })?;
716    let built_name = built
717        .file_name()
718        .map(|n| n.to_string_lossy().into_owned())
719        .unwrap_or_default();
720    let stable_name = if config.lib_mode {
721        built_name.replacen(
722            &identity.replace('-', "_"),
723            &manifest.package.name.replace('-', "_"),
724            1,
725        )
726    } else {
727        built_name.replacen(&identity, &manifest.package.name, 1)
728    };
729    let binary_path = build_dir.join(&stable_name);
730    // A failed publish fails the build: whatever sits at the stable path would be an EARLIER
731    // build's, and there is no correct thing to do with a half-published one.
732    fs::copy(&built, &binary_path).map_err(|e| {
733        BuildError::Io(format!(
734            "the build succeeded but its artifact could not be published to {}: {e}\n\
735             The freshly built file is at {}. Anything at the stable path is from an EARLIER \
736             build — do not ship it.",
737            binary_path.display(),
738            built.display()
739        ))
740    })?;
741
742    // Universal ABI: the C header rides beside the published library or binary.
743    if output.c_header.is_some() {
744        let header_name = format!("{}.h", manifest.package.name);
745        let src_header = rust_project_dir.join(&header_name);
746        if src_header.exists() {
747            let _ = fs::copy(&src_header, build_dir.join(&header_name));
748        }
749    }
750
751    // A web binary is self-contained — its whole site rides inside via `include_bytes!`, runtime
752    // deps resolve from version pins, and the LOGOS stdlib is embedded in the compiler — so it
753    // deploys by copying this ONE file.
754    if let Some(assets) = &site_assets {
755        crate::ui::phase(
756            "Bundled",
757            format!(
758                "{} embedded asset(s) — self-contained web server",
759                assets.len()
760            ),
761        );
762    }
763    if !config.lib_mode {
764        crate::ui::phase("Artifact", binary_path.display().to_string());
765    }
766
767    Ok(BuildResult {
768        target_dir: build_dir,
769        binary_path,
770    })
771}
772
773/// The name a project's cargo target builds under: its package name and a digest of its
774/// canonical directory, so two projects that share a name never share an output file in a shared
775/// `CARGO_TARGET_DIR`, and one project always rebuilds the same file.
776fn artifact_identity(name: &str, project_dir: &Path) -> String {
777    let dir = project_dir
778        .canonicalize()
779        .unwrap_or_else(|_| project_dir.to_path_buf());
780    let digest = crate::commands::web_bundle::content_hash(dir.to_string_lossy().as_bytes());
781    format!("{name}-{digest}")
782}
783
784/// The file cargo reports producing for the target named `identity`: a binary's `executable`, or
785/// a library's shared object — read from cargo's own `compiler-artifact` messages.
786fn built_artifact(messages: &str, identity: &str, lib: bool) -> Option<PathBuf> {
787    let lib_name = identity.replace('-', "_");
788    messages
789        .lines()
790        .filter_map(|line| serde_json::from_str::<serde_json::Value>(line).ok())
791        .filter(|m| m["reason"] == "compiler-artifact")
792        .filter(|m| {
793            let name = m["target"]["name"].as_str().unwrap_or("");
794            if lib {
795                name == lib_name
796            } else {
797                name == identity
798            }
799        })
800        .find_map(|m| {
801            if lib {
802                m["filenames"]
803                    .as_array()?
804                    .iter()
805                    .filter_map(|f| f.as_str())
806                    .find(|f| {
807                        let f = f.to_ascii_lowercase();
808                        f.ends_with(".so")
809                            || f.ends_with(".dylib")
810                            || f.ends_with(".dll")
811                            || f.ends_with(".wasm")
812                    })
813                    .map(PathBuf::from)
814            } else {
815                m["executable"].as_str().map(PathBuf::from)
816            }
817        })
818}
819
820/// Strip the `fn main() { ... }` wrapper from generated code for library mode.
821/// Keeps everything before `fn main()` (imports, types, functions) intact.
822fn strip_main_wrapper(code: &str) -> String {
823    // Find "fn main() {" and extract content before it
824    if let Some(main_pos) = code.find("fn main() {") {
825        let before_main = &code[..main_pos];
826        // Extract the body of main (between the opening { and closing })
827        let after_opening = &code[main_pos + "fn main() {".len()..];
828        if let Some(close_pos) = after_opening.rfind('}') {
829            let main_body = &after_opening[..close_pos];
830            // Dedent main body
831            let dedented: Vec<&str> = main_body
832                .lines()
833                .map(|line| line.strip_prefix("    ").unwrap_or(line))
834                .collect();
835            format!("{}\n{}", before_main.trim_end(), dedented.join("\n"))
836        } else {
837            before_main.to_string()
838        }
839    } else {
840        code.to_string()
841    }
842}
843
844/// Execute a built LOGOS project.
845///
846/// Spawns the compiled binary and waits for it to complete.
847/// Returns the process exit code.
848///
849/// # Arguments
850///
851/// * `build_result` - Result from a previous [`build`] call
852///
853/// # Returns
854///
855/// The exit code of the process (0 for success, non-zero for failure).
856///
857/// # Errors
858///
859/// Returns [`BuildError::Io`] if the process cannot be spawned.
860pub fn run(build_result: &BuildResult, args: &[String]) -> Result<i32, BuildError> {
861    let mut child = Command::new(&build_result.binary_path)
862        .args(args)
863        .spawn()
864        .map_err(|e| BuildError::Io(e.to_string()))?;
865
866    let status = child.wait().map_err(|e| BuildError::Io(e.to_string()))?;
867
868    Ok(status.code().unwrap_or(1))
869}
870
871#[cfg(test)]
872#[path = "../../../../crates/logicaffeine_tests/unit/logicaffeine_cli/project/build/tests.rs"]
873mod tests;