zlayer-toolchain 0.14.3

Runtime toolchain provisioning (macOS Homebrew bottle resolver/installer) for ZLayer
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
//! `zlayer-toolchain` — reusable runtime toolchain provisioning.
//!
//! This is a **leaf** crate: it depends only on other leaf crates
//! (`zlayer-paths`, `zlayer-registry`, `zlayer-types`) and external crates. It
//! depends on neither `zlayer-agent` nor `zlayer-builder`. It exists to break
//! the `zlayer-builder` -> `zlayer-agent` build cycle: the macOS sandboxes
//! (Seatbelt / HCS) have no package manager, so this crate is "our apt-get" —
//! it provisions a named tool into a self-contained, absolute-prefix **toolchain** and
//! returns a [`ToolchainHandle`] describing how to run it.
//!
//! # Provisioning strategy (macOS)
//!
//! A toolchain is produced one of two ways, both relocation-free (no `@@HOMEBREW@@`):
//! - **Source build** ([`source_build`]): fetch the Homebrew formula's
//!   `urls.stable.url` source tarball and build it at an absolute toolchain prefix
//!   with the host Command Line Tools (the homebrew-core C-tool population:
//!   git, jq, cmake, ...).
//! - **Prebuilt fetch** ([`prebuilt`]): land a self-contained vendor archive
//!   for the language toolchains (go/node/rust/...).
//!
//! Every toolchain carries a [`manifest::ToolchainManifest`] (`toolchain.json`) describing
//! its `path_dirs` + `env`, so the resolver is generic — no tool is special-
//! cased on the handle path.
//!
//! # Surface
//!
//! - [`ensure_toolchain`] — provision a named tool and return a
//!   [`ToolchainHandle`].
//! - [`probe_ready_toolchain`] — non-blocking, filesystem-only `.ready` probe
//!   that reconstructs a handle from an already-provisioned toolchain.
//!
//! The old Homebrew **bottle** resolver/installer (download a prebuilt bottle
//! and rewrite its `@@HOMEBREW@@` install-name placeholders) has been removed
//! entirely — see the module docs on [`source_build`] for why that path was a
//! dead end under Seatbelt.

use std::collections::HashMap;
use std::path::{Path, PathBuf};

pub mod brew_emulate;
pub mod coverage;
pub mod error;
pub mod executor;
pub mod formula;
pub mod lockfile;
pub mod manifest;
pub mod package_index;
pub mod prebuilt;
pub mod recipe;
pub mod recipe_choco;
pub mod registry;
pub mod relocate;
pub mod source_build;
pub mod windows;

pub use error::{Result, ToolchainError};
pub use lockfile::{LockedTool, ToolchainLockfile, ToolchainLockfileExt, LOCKFILE_NAME};

use crate::coverage::{CoverageRecord, CoverageStatus};
use crate::registry::{PublishedToolchain, PulledToolchain, ToolchainArtifactId};
use crate::relocate::RelocationReport;

/// Target platform for a toolchain provisioning request.
///
/// Both platforms provision into the same toolchain format. macOS goes through
/// source-build / prebuilt-fetch / brew-emulate ([`ensure_macos_toolchain`]); Windows
/// goes through MinGit for `git` and the Chocolatey chain for everything else
/// ([`windows`]): portable zip/web-file packages are fetched + extracted
/// leaf-side, while exe/msi installer packages run `choco install` inside a
/// Windows container via the registered [`executor::ContainerBuildExecutor`]
/// (failing with [`ToolchainError::ExecutorUnavailable`] when none is
/// registered — never a host subprocess).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ToolPlatform {
    /// macOS host — provision via source build / prebuilt fetch into a toolchain.
    MacOS,
    /// Windows host — provision via MinGit / portable artifact into a toolchain.
    Windows,
}

/// A provisioned toolchain: where it lives and how to run it.
///
/// `path_dirs` are absolute directories to prepend to `PATH`; `env` are extra
/// environment variables the caller should set so the tool resolves its own
/// libraries / exec helpers out of the toolchain instead of the host. Both are a
/// direct projection of the toolchain's [`manifest::ToolchainManifest`].
#[derive(Debug, Clone)]
pub struct ToolchainHandle {
    /// Root directory of the provisioned toolchain (the cache key dir).
    pub install_dir: PathBuf,
    /// Absolute directories to prepend to `PATH`.
    pub path_dirs: Vec<String>,
    /// Extra environment variables for running the tool.
    pub env: HashMap<String, String>,
}

/// Host architecture token used in cache keys (`arm64` / `x86_64`).
fn arch_token() -> &'static str {
    match std::env::consts::ARCH {
        "aarch64" => "arm64",
        other => other,
    }
}

/// Split a package request into `(formula, version_token)`.
///
/// `git` -> `("git", "latest")`; `openssl@3` -> `("openssl@3", "3")`. The full
/// `pkg` is always the brew formula name (brew versioned formulae keep their
/// `@major` suffix); the version token only feeds the cache key.
fn split_pkg(pkg: &str) -> (&str, &str) {
    match pkg.split_once('@') {
        Some((_, ver)) if !ver.is_empty() => (pkg, ver),
        _ => (pkg, "latest"),
    }
}

/// Ensure a runtime tool is provisioned and return a handle describing how to
/// run it.
///
/// The install is idempotent: the toolchain lives at
/// `{cache_dir}/{formula}-{version}-{arch}` and is guarded by a `.ready` marker
/// (written after the [`manifest::ToolchainManifest`]), so a populated cache
/// short-circuits without any network or build work.
///
/// # Errors
///
/// Returns [`ToolchainError::ExecutorUnavailable`] for a Windows formula whose
/// Chocolatey install plan needs the containerized `choco` path (exe/msi
/// installers) when no runtime container executor is registered.
/// Propagates formula-resolution, download, dependency and build errors.
/// When `lockfile` is `Some`, a lock hit for `(pkg, platform, arch)` pins the
/// exact version + URL and the download is verified against the pinned sha256
/// ("consume-only": this crate never *writes* the lock — the CLI does). A lock
/// miss live-resolves and records the resolved digest in the toolchain manifest.
pub async fn ensure_toolchain(
    pkg: &str,
    platform: ToolPlatform,
    cache_dir: &Path,
    lockfile: Option<&ToolchainLockfile>,
) -> Result<ToolchainHandle> {
    match platform {
        ToolPlatform::Windows => {
            let toolchain = windows::ensure_windows_toolchain(pkg, cache_dir, lockfile).await?;
            build_handle_from_toolchain(toolchain).await
        }
        ToolPlatform::MacOS => {
            let toolchain = ensure_macos_toolchain(pkg, cache_dir, lockfile).await?;
            build_handle_from_toolchain(toolchain).await
        }
    }
}

/// Provision (or reuse) a macOS toolchain for `pkg`, returning the toolchain directory.
///
/// Dispatches generically: language toolchains land via the relocation-free
/// prebuilt fetcher; everything else is built from source. Both write a
/// [`manifest::ToolchainManifest`] and converge on the same cache + toolchain layout. This
/// is the crate-internal entry point that [`source_build`] also re-enters to
/// resolve build dependencies recursively.
pub(crate) async fn ensure_macos_toolchain(
    pkg: &str,
    cache_dir: &Path,
    lockfile: Option<&ToolchainLockfile>,
) -> Result<PathBuf> {
    let (formula, _version) = split_pkg(pkg);
    if prebuilt::is_prebuilt_formula(formula) {
        // Language toolchains (go/node/rust/...) land as relocation-free
        // self-contained vendor archives.
        prebuilt::ensure_prebuilt(formula, cache_dir, lockfile).await
    } else {
        // The homebrew-core C-tool population (git/jq/cmake/...) is built from
        // source at an absolute toolchain prefix.
        source_build::ensure_from_source(formula, cache_dir, lockfile).await
    }
}

/// Map a toolchain arch token (`arm64` / `x86_64`) to the vendor-download arch token
/// (`arm64` / `amd64`) the prebuilt resolvers expect.
fn vendor_arch(arch: &str) -> &str {
    if arch == "x86_64" {
        "amd64"
    } else {
        arch
    }
}

/// The lowercase platform token stored in a manifest / lock entry.
fn platform_token(platform: ToolPlatform) -> &'static str {
    match platform {
        ToolPlatform::MacOS => "macos",
        ToolPlatform::Windows => "windows",
    }
}

/// Sanitize a tool token for use inside a temp-file name.
fn sanitize(tool: &str) -> String {
    tool.chars()
        .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
        .collect()
}

/// Resolve a tool to a fully-pinned [`LockedTool`] by live-resolving its exact
/// version + download URL, streaming the artifact to a temp file, and hashing
/// the bytes (verifying against the upstream-published digest when one exists).
///
/// This is the resolution path the CLI's `zlayer toolchains lock` reuses, so the
/// lock writer never duplicates resolver logic. `arch` is the toolchain arch token
/// (`arm64` / `x86_64`); the vendor-arch mapping is internal.
///
/// # Errors
///
/// Propagates resolution / download / digest-verification failures.
pub async fn resolve_locked_tool(
    tool: &str,
    platform: ToolPlatform,
    arch: &str,
) -> Result<LockedTool> {
    let (formula, _version) = split_pkg(tool);
    let (version, url, expected): (String, String, Option<String>) = match platform {
        ToolPlatform::MacOS => {
            if prebuilt::is_prebuilt_formula(formula) {
                let r = prebuilt::resolve_prebuilt(formula, vendor_arch(arch)).await?;
                (r.version, r.url, r.sha256)
            } else {
                let spec = source_build::resolve_source_spec(formula).await?;
                let sha = (!spec.sha256.is_empty()).then_some(spec.sha256);
                (spec.version, spec.tarball_url, sha)
            }
        }
        ToolPlatform::Windows => windows::resolve_locked_windows(formula).await?,
    };

    // Stream to a temp file to compute (and, when published, verify) the digest.
    let tmp = std::env::temp_dir().join(format!(
        "zlayer-lock-{}-{arch}-{}",
        sanitize(tool),
        std::process::id()
    ));
    let sha256 = package_index::download_verified(&url, &tmp, expected.as_deref()).await?;
    let _ = tokio::fs::remove_file(&tmp).await;

    Ok(LockedTool {
        tool: tool.to_string(),
        platform: platform_token(platform).to_string(),
        arch: arch.to_string(),
        version,
        url,
        sha256,
        resolved_at: chrono::Utc::now().to_rfc3339(),
    })
}

/// Reconstruct a [`ToolchainHandle`] from a provisioned toolchain by reading (or, for
/// a pre-manifest toolchain, synthesizing) its [`manifest::ToolchainManifest`].
async fn build_handle_from_toolchain(toolchain: PathBuf) -> Result<ToolchainHandle> {
    let manifest = manifest::ToolchainManifest::load_or_synthesize(&toolchain).await?;
    Ok(ToolchainHandle {
        install_dir: toolchain,
        path_dirs: manifest.path_dirs,
        env: manifest.env,
    })
}

/// Non-blocking, filesystem-only probe for an already-provisioned toolchain.
///
/// Returns `Some(handle)` iff a `.ready`-stamped toolchain for `(pkg, platform,
/// cache_dir)` exists on disk; otherwise `None`. Does **no** network I/O, no
/// build, and no mutation — it reconstructs the [`ToolchainHandle`] from the
/// toolchain's manifest exactly as the fast path of [`ensure_toolchain`] does.
///
/// It exists so a caller that provisions in the background (and therefore can't
/// `await` the cold install on its hot path) can still inject a toolchain already on
/// disk — e.g. from a previous daemon process. Returns `None` for any non-macOS
/// platform or when no ready toolchain is present.
pub async fn probe_ready_toolchain(
    pkg: &str,
    _platform: ToolPlatform,
    cache_dir: &Path,
) -> Option<ToolchainHandle> {
    // The toolchain layout + cache key are platform-agnostic, so the probe is too: it
    // just looks for a `.ready`-stamped `<formula>-<ver>-<arch>` toolchain on disk.
    let (formula, _version) = split_pkg(pkg);
    let toolchain = newest_ready_toolchain(formula, cache_dir).await?;
    build_handle_from_toolchain(toolchain).await.ok()
}

/// Find the newest `{formula}-<ver>-<arch>` toolchain under `cache_dir` that is
/// stamped `.ready` (mtime-ordered). Returns `None` for a cold/partial cache.
async fn newest_ready_toolchain(formula: &str, cache_dir: &Path) -> Option<PathBuf> {
    let prefix = format!("{formula}-");
    let arch_suffix = format!("-{}", arch_token());
    let mut entries = tokio::fs::read_dir(cache_dir).await.ok()?;
    let mut best: Option<(std::time::SystemTime, PathBuf)> = None;
    while let Ok(Some(entry)) = entries.next_entry().await {
        let name = entry.file_name();
        let Some(name) = name.to_str() else { continue };
        if !name.starts_with(&prefix) || !name.ends_with(&arch_suffix) {
            continue;
        }
        let toolchain = entry.path();
        if !tokio::fs::try_exists(toolchain.join(".ready"))
            .await
            .unwrap_or(false)
        {
            continue;
        }
        let mtime = entry
            .metadata()
            .await
            .ok()
            .and_then(|m| m.modified().ok())
            .unwrap_or(std::time::UNIX_EPOCH);
        if best.as_ref().is_none_or(|(t, _)| mtime >= *t) {
            best = Some((mtime, toolchain));
        }
    }
    best.map(|(_, toolchain)| toolchain)
}

// ---------------------------------------------------------------------------
// Toolchain-registry pull-first + build-coverage wiring (shared by the three
// resolve entry points: macOS source-build, Windows, and prebuilt).
//
// Every resolve is: local `.ready` wins (zero network) → else pull-first from
// the registry → else build → (non-prebuilt) relocate + publish → record
// coverage exactly once. Registry pulls/publishes AND coverage writes are all
// best-effort: a registry error never fails a resolve, and `coverage::record`
// returns `()`. A cold offline machine resolves exactly as before, plus two
// quiet, failed best-effort network attempts (a pull, then a publish).
// ---------------------------------------------------------------------------

/// Max bytes of an error `Display` kept in a coverage `error_tail` (~2 KiB) —
/// enough to triage a build failure without bloating the coverage row.
const ERROR_TAIL_MAX: usize = 2048;

/// Try the toolchain registry before building `id` into `toolchain`.
///
/// - `Ok(Some(()))` — a published artifact was pulled: [`registry::try_pull_toolchain`]
///   already unpacked + relocated it and wrote its manifest (`source = Registry`);
///   this then stamps `.ready` (WITHOUT rewriting that manifest — see
///   [`stamp_ready`]) and records coverage `Built`. The caller returns the
///   toolchain with NO build.
/// - `Ok(None)` — a miss (nothing published, or the registry unreachable-as-
///   not-found): the caller builds.
///
/// A registry transport error is swallowed to `Ok(None)` (logged `warn`): the
/// registry must NEVER block a resolve. The only propagated error is a local
/// `.ready` write failure after a successful pull (a genuine local-FS fault).
pub(crate) async fn pull_first(id: &ToolchainArtifactId, toolchain: &Path) -> Result<Option<()>> {
    match registry::try_pull_toolchain(id, toolchain).await {
        Ok(Some(pulled)) => {
            stamp_ready(toolchain).await?;
            record_pull_built(id, &pulled).await;
            Ok(Some(()))
        }
        Ok(None) => Ok(None),
        Err(e) => {
            tracing::warn!(
                tool = %id.tool,
                error = %e,
                "toolchain registry pull failed (non-fatal); building instead"
            );
            Ok(None)
        }
    }
}

/// Stamp the `.ready` marker on an already-materialized toolchain dir WITHOUT
/// touching `toolchain.json`.
///
/// Used after a registry pull, which already wrote the manifest with
/// `source = Registry` and deliberately left `.ready` to the caller. The
/// source-build / Windows finalize path would REWRITE the manifest (clobbering
/// the Registry provenance with `SourceBuild`/`Prebuilt`), so it must not be
/// reused here — a bare marker write is exactly what the pull contract expects.
pub(crate) async fn stamp_ready(toolchain: &Path) -> Result<()> {
    tokio::fs::write(toolchain.join(".ready"), b"").await?;
    Ok(())
}

/// Finish a successful LOCAL build: (non-prebuilt) best-effort publish, then
/// record coverage `Built`.
///
/// `report` is the [`RelocationReport`] the build's finalize produced (present
/// for the relocatable source-build / Windows paths, `None` for prebuilt).
/// Publish runs only when [`should_publish`] — language prebuilts are already
/// relocation-free vendor archives (and large: the OCI client buffers blobs in
/// memory), so they are pull-first + coverage-only, never relocated or
/// published. A publish failure (the common anonymous / no-token case) is a
/// `warn`, and coverage is still recorded `Built`, just without a registry ref.
pub(crate) async fn finish_built(
    id: &ToolchainArtifactId,
    toolchain: &Path,
    report: Option<&RelocationReport>,
    is_prebuilt: bool,
) {
    let published = if should_publish(is_prebuilt) {
        match report {
            Some(report) => try_publish(id, toolchain, report).await,
            None => None,
        }
    } else {
        None
    };
    coverage::record(&build_coverage(
        id,
        CoverageStatus::Built,
        published.as_ref(),
        None,
    ))
    .await;
}

/// Record a net-fallback resolve (the loud full-network brew/choco route won):
/// coverage `NetFallback`, no registry ref (net-fallback artifacts are not
/// hermetic, so they are not published from here).
pub(crate) async fn record_net_fallback(id: &ToolchainArtifactId) {
    coverage::record(&build_coverage(id, CoverageStatus::NetFallback, None, None)).await;
}

/// Record a failed resolve: coverage `Failed` with the error's `Display` as the
/// (truncated) `error_tail`. Best-effort — the caller still propagates `err`.
pub(crate) async fn record_failed(id: &ToolchainArtifactId, err: &ToolchainError) {
    let tail = err.to_string();
    coverage::record(&build_coverage(
        id,
        CoverageStatus::Failed,
        None,
        Some(&tail),
    ))
    .await;
}

/// Record a registry pull-hit as coverage `Built`, carrying the pulled
/// artifact's reference + digest (a pull is, for coverage, the same
/// `(registry_ref, digest)` coordinate a publish would record).
async fn record_pull_built(id: &ToolchainArtifactId, pulled: &PulledToolchain) {
    let published = PublishedToolchain {
        reference: pulled.reference.clone(),
        digest: pulled.digest.clone(),
    };
    coverage::record(&build_coverage(
        id,
        CoverageStatus::Built,
        Some(&published),
        None,
    ))
    .await;
}

/// Best-effort publish of a freshly-built toolchain: read its just-written
/// manifest, then [`registry::publish_toolchain`] it (built prefix = the
/// toolchain dir itself). `None` on any failure (missing manifest, or a push
/// denied for anonymous / no-token — the common case), which is logged `warn`
/// and leaves the toolchain built-locally-only.
async fn try_publish(
    id: &ToolchainArtifactId,
    toolchain: &Path,
    report: &RelocationReport,
) -> Option<PublishedToolchain> {
    let manifest = match manifest::ToolchainManifest::read_from_toolchain(toolchain).await {
        Ok(Some(manifest)) => manifest,
        Ok(None) => {
            tracing::warn!(tool = %id.tool, "no manifest present to publish; skipping publish");
            return None;
        }
        Err(e) => {
            tracing::warn!(tool = %id.tool, error = %e, "reading manifest for publish failed; skipping publish");
            return None;
        }
    };
    match registry::publish_toolchain(toolchain, &manifest, report, toolchain, id).await {
        Ok(published) => Some(published),
        Err(e) => {
            tracing::warn!(
                tool = %id.tool,
                error = %e,
                "toolchain publish failed (non-fatal; an anonymous / no-token push is expected)"
            );
            None
        }
    }
}

/// Whether a freshly-built toolchain of this kind is relocated + published.
///
/// Language prebuilts are excluded: they are already relocation-free vendor
/// archives and large enough that publishing (the OCI client buffers blobs in
/// memory) is not worth it. Everything else (source builds, Windows toolchains)
/// is published so the next machine skips the build.
fn should_publish(is_prebuilt: bool) -> bool {
    !is_prebuilt
}

/// Assemble a [`CoverageRecord`] from a resolve outcome. Pure (no I/O): the
/// status / registry-ref / error-tail wiring is unit-testable without a network
/// or a real build. `platform` / `arch` come straight off the artifact id (the
/// crate's `"macos"` / `"windows"` + `"arm64"` / `"x86_64"` tokens); a present
/// `published` fills `registry_ref` / `registry_digest`; a present `err` fills a
/// truncated `error_tail`.
fn build_coverage(
    id: &ToolchainArtifactId,
    status: CoverageStatus,
    published: Option<&PublishedToolchain>,
    err: Option<&str>,
) -> CoverageRecord {
    CoverageRecord {
        tool: id.tool.clone(),
        platform: id.os.clone(),
        arch: id.arch.clone(),
        status,
        version: id.version.clone(),
        registry_ref: published.map(|p| p.reference.clone()).unwrap_or_default(),
        registry_digest: published.map(|p| p.digest.clone()).unwrap_or_default(),
        error_tail: err.map(truncate_error_tail).unwrap_or_default(),
        recorded_at: coverage::now_rfc3339(),
    }
}

/// Truncate an error `Display` to [`ERROR_TAIL_MAX`] bytes for a coverage
/// `error_tail`, on a char boundary so the result stays valid UTF-8.
fn truncate_error_tail(err: &str) -> String {
    if err.len() <= ERROR_TAIL_MAX {
        return err.to_string();
    }
    let mut end = ERROR_TAIL_MAX;
    while end > 0 && !err.is_char_boundary(end) {
        end -= 1;
    }
    err[..end].to_string()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::manifest::{ToolchainManifest, ToolchainSource};

    #[test]
    fn split_pkg_plain_defaults_to_latest() {
        assert_eq!(split_pkg("git"), ("git", "latest"));
    }

    #[test]
    fn split_pkg_versioned_keeps_full_formula() {
        assert_eq!(split_pkg("openssl@3"), ("openssl@3", "3"));
    }

    #[test]
    fn split_pkg_trailing_at_is_latest() {
        assert_eq!(split_pkg("weird@"), ("weird@", "latest"));
    }

    // -- E2: coverage-record assembly + pull-first / publish gating ------------

    fn sample_id() -> ToolchainArtifactId {
        ToolchainArtifactId {
            tool: "jq".to_string(),
            version: "1.8.1".to_string(),
            os: "macos".to_string(),
            arch: "arm64".to_string(),
        }
    }

    /// A normal build records `Built` carrying the published ref + digest.
    #[test]
    fn build_coverage_built_carries_registry_ref_and_digest() {
        let id = sample_id();
        let published = PublishedToolchain {
            reference: "ghcr.io/blackleafdigital/zlayer/toolchains:jq-1.8.1-macos-arm64"
                .to_string(),
            digest: "sha256:abc".to_string(),
        };
        let rec = build_coverage(&id, CoverageStatus::Built, Some(&published), None);
        assert_eq!(rec.tool, "jq");
        assert_eq!(rec.platform, "macos");
        assert_eq!(rec.arch, "arm64");
        assert_eq!(rec.version, "1.8.1");
        assert_eq!(rec.status, CoverageStatus::Built);
        assert_eq!(rec.registry_ref, published.reference);
        assert_eq!(rec.registry_digest, "sha256:abc");
        assert!(rec.error_tail.is_empty());
        assert!(!rec.recorded_at.is_empty(), "recorded_at is stamped");
    }

    /// A prebuilt / publish-skipped `Built` still has status `Built` but no
    /// registry ref (published is `None`).
    #[test]
    fn build_coverage_built_without_publish_has_no_ref() {
        let rec = build_coverage(&sample_id(), CoverageStatus::Built, None, None);
        assert_eq!(rec.status, CoverageStatus::Built);
        assert!(rec.registry_ref.is_empty());
        assert!(rec.registry_digest.is_empty());
        assert!(rec.error_tail.is_empty());
    }

    /// A build-fail path records `Failed` with the error's Display as `error_tail`.
    #[test]
    fn build_coverage_failed_carries_error_tail() {
        let err = "Registry error: generic source build blew up".to_string();
        let rec = build_coverage(&sample_id(), CoverageStatus::Failed, None, Some(&err));
        assert_eq!(rec.status, CoverageStatus::Failed);
        assert_eq!(rec.error_tail, err);
        assert!(rec.registry_ref.is_empty());
        assert!(rec.registry_digest.is_empty());
    }

    /// A net-fallback path records `NetFallback` (no ref, no error tail).
    #[test]
    fn build_coverage_net_fallback_status() {
        let rec = build_coverage(&sample_id(), CoverageStatus::NetFallback, None, None);
        assert_eq!(rec.status, CoverageStatus::NetFallback);
        assert!(rec.registry_ref.is_empty());
        assert!(rec.error_tail.is_empty());
    }

    /// `error_tail` is capped at ~2 KiB on a char boundary (valid UTF-8).
    #[test]
    fn error_tail_truncates_to_cap_on_char_boundary() {
        let short = "small error";
        assert_eq!(truncate_error_tail(short), short);

        // 4000 × 2-byte chars = 8000 bytes → truncated to <= ERROR_TAIL_MAX.
        let long = "é".repeat(4000);
        let cut = truncate_error_tail(&long);
        assert!(cut.len() <= ERROR_TAIL_MAX);
        assert!(cut.len() > ERROR_TAIL_MAX - 4, "cut near the cap, not tiny");
        assert!(
            long.starts_with(&cut),
            "a valid-UTF-8 prefix of the original"
        );
    }

    /// The publish gate: source-build / Windows toolchains publish; language
    /// prebuilts never do (excluded from relocate + publish).
    #[test]
    fn should_publish_excludes_prebuilt() {
        assert!(
            should_publish(false),
            "source-build / Windows toolchains publish"
        );
        assert!(
            !should_publish(true),
            "language prebuilts are never published"
        );
    }

    /// The pull-hit short-circuit's stamp step: `stamp_ready` adds `.ready` to a
    /// materialized dir WITHOUT clobbering the pull's `source = Registry`
    /// manifest (the finalize path would rewrite it). Together with registry.rs's
    /// `pull_round_trip_from_local_registry_rehomes_and_stamps_source` (which
    /// proves the pull unpacks + relocates + writes the Registry manifest and
    /// leaves `.ready` to the caller) this covers the pull-hit branch end-to-end
    /// without a live registry — `try_pull_toolchain` cannot be injected without
    /// touching registry.rs, so the branch is split at this stamp seam.
    #[tokio::test]
    async fn stamp_ready_writes_marker_without_clobbering_registry_manifest() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path();
        let mut env = HashMap::new();
        env.insert("K".to_string(), format!("{}/lib", dir.display()));
        let manifest = ToolchainManifest {
            tool: "jq".to_string(),
            version: "1.8.1".to_string(),
            arch: "arm64".to_string(),
            platform: "macos".to_string(),
            path_dirs: vec![format!("{}/bin", dir.display())],
            env,
            source: ToolchainSource::Registry {
                reference: "ghcr.io/x/toolchains:jq-1.8.1-macos-arm64".to_string(),
                digest: "sha256:deadbeef".to_string(),
            },
            build_deps: vec![],
            provisioned_at: "2026-07-06T00:00:00Z".to_string(),
        };
        manifest.write_to_toolchain(dir).await.unwrap();
        assert!(
            !dir.join(".ready").exists(),
            "pull leaves .ready to the caller"
        );

        stamp_ready(dir).await.unwrap();

        assert!(dir.join(".ready").is_file(), ".ready stamped");
        let reread = ToolchainManifest::read_from_toolchain(dir)
            .await
            .unwrap()
            .unwrap();
        match reread.source {
            ToolchainSource::Registry { reference, digest } => {
                assert_eq!(reference, "ghcr.io/x/toolchains:jq-1.8.1-macos-arm64");
                assert_eq!(digest, "sha256:deadbeef");
            }
            other => panic!("stamp_ready must NOT rewrite the Registry manifest; got {other:?}"),
        }
    }

    /// A Windows formula whose choco plan is an exe installer (7zip's
    /// `chocolateyInstall.ps1` is `Install-ChocolateyPackage`) requires the
    /// runtime container executor; with none registered the chain fails with
    /// `ExecutorUnavailable`. Live because the chain resolves + downloads the
    /// `.nupkg` through the package index BEFORE the executor decision — the
    /// offline decision-fn coverage lives in the `windows` module's own tests.
    #[tokio::test]
    #[ignore = "live: resolves + downloads a Chocolatey package through the package index"]
    async fn windows_exe_installer_without_executor_is_executor_unavailable() {
        let tmp = tempfile::tempdir().unwrap();
        let err = ensure_toolchain("7zip", ToolPlatform::Windows, tmp.path(), None)
            .await
            .unwrap_err();
        assert!(
            matches!(err, ToolchainError::ExecutorUnavailable { .. }),
            "{err}"
        );
    }

    /// Lay down a source-built `git` toolchain WITHOUT a manifest (the pre-manifest
    /// layout) so the offline tests exercise the backward-compatible synthesis
    /// path of [`build_handle_from_toolchain`].
    async fn seed_legacy_git_toolchain(cache_dir: &Path, version: &str) -> PathBuf {
        let toolchain = cache_dir.join(format!("git-{version}-{}", arch_token()));
        tokio::fs::create_dir_all(toolchain.join("bin"))
            .await
            .unwrap();
        tokio::fs::create_dir_all(toolchain.join("libexec/git-core"))
            .await
            .unwrap();
        tokio::fs::create_dir_all(toolchain.join("etc"))
            .await
            .unwrap();
        tokio::fs::write(toolchain.join("etc/gitconfig"), b"")
            .await
            .unwrap();
        tokio::fs::write(toolchain.join(".ready"), b"")
            .await
            .unwrap();
        toolchain
    }

    /// Lay down a toolchain WITH a `toolchain.json` manifest so the resolver's generic
    /// (non-synthesized) path is covered.
    async fn seed_toolchain_with_manifest(cache_dir: &Path, tool: &str, version: &str) -> PathBuf {
        let toolchain = cache_dir.join(format!("{tool}-{version}-{}", arch_token()));
        let bin = toolchain.join("bin");
        tokio::fs::create_dir_all(&bin).await.unwrap();
        let mut env = HashMap::new();
        env.insert("FOO".to_string(), "bar".to_string());
        let manifest = ToolchainManifest {
            tool: tool.to_string(),
            version: version.to_string(),
            arch: arch_token().to_string(),
            platform: "macos".to_string(),
            path_dirs: vec![bin.display().to_string()],
            env,
            source: ToolchainSource::SourceBuild {
                url: String::new(),
                sha256: String::new(),
            },
            build_deps: vec![],
            provisioned_at: "2026-06-30T00:00:00Z".to_string(),
        };
        manifest.write_to_toolchain(&toolchain).await.unwrap();
        tokio::fs::write(toolchain.join(".ready"), b"")
            .await
            .unwrap();
        toolchain
    }

    /// A pre-manifest `git` toolchain synthesizes a handle whose env is ONLY
    /// `GIT_EXEC_PATH` (→ `<toolchain>/libexec/git-core`), with NO
    /// `DYLD_FALLBACK_LIBRARY_PATH` and NO `GIT_CONFIG_SYSTEM`.
    #[tokio::test]
    async fn handle_synthesized_for_legacy_git_toolchain_drops_dyld() {
        let tmp = tempfile::tempdir().unwrap();
        let toolchain = seed_legacy_git_toolchain(tmp.path(), "2.55.0").await;

        let handle = build_handle_from_toolchain(toolchain.clone())
            .await
            .unwrap();

        assert_eq!(handle.install_dir, toolchain);
        assert_eq!(
            handle.path_dirs,
            vec![toolchain.join("bin").display().to_string()]
        );
        assert_eq!(
            handle.env.get("GIT_EXEC_PATH"),
            Some(&toolchain.join("libexec/git-core").display().to_string())
        );
        assert!(!handle.env.contains_key("DYLD_FALLBACK_LIBRARY_PATH"));
        assert!(!handle.env.contains_key("GIT_CONFIG_SYSTEM"));
    }

    /// A toolchain WITH a manifest projects the manifest's `path_dirs` + `env`
    /// verbatim onto the handle.
    #[tokio::test]
    async fn handle_reads_manifest_when_present() {
        let tmp = tempfile::tempdir().unwrap();
        let toolchain = seed_toolchain_with_manifest(tmp.path(), "jq", "1.8.2").await;

        let handle = build_handle_from_toolchain(toolchain.clone())
            .await
            .unwrap();
        assert_eq!(handle.install_dir, toolchain);
        assert_eq!(
            handle.path_dirs,
            vec![toolchain.join("bin").display().to_string()]
        );
        assert_eq!(handle.env.get("FOO"), Some(&"bar".to_string()));
    }

    /// The on-disk fallback the runtime relies on: a `.ready` toolchain is probed
    /// (no install) and reconstructs the SAME handle as the fast path.
    #[tokio::test]
    async fn probe_ready_returns_handle_for_ready_toolchain() {
        let tmp = tempfile::tempdir().unwrap();
        let toolchain = seed_legacy_git_toolchain(tmp.path(), "2.55.0").await;

        let handle = probe_ready_toolchain("git", ToolPlatform::MacOS, tmp.path())
            .await
            .expect("ready toolchain should be probed without install");

        assert_eq!(handle.install_dir, toolchain);
        assert_eq!(
            handle.env.get("GIT_EXEC_PATH"),
            Some(&toolchain.join("libexec/git-core").display().to_string())
        );
    }

    /// Probing a different tool's toolchain works generically (not git-special).
    #[tokio::test]
    async fn probe_ready_is_generic_across_tools() {
        let tmp = tempfile::tempdir().unwrap();
        let toolchain = seed_toolchain_with_manifest(tmp.path(), "jq", "1.8.2").await;

        let handle = probe_ready_toolchain("jq", ToolPlatform::MacOS, tmp.path())
            .await
            .expect("ready jq toolchain should be probed");
        assert_eq!(handle.install_dir, toolchain);
        assert_eq!(handle.env.get("FOO"), Some(&"bar".to_string()));
    }

    /// A toolchain dir that exists but is NOT stamped `.ready` (mid-build) must probe
    /// to `None` — never inject a partial toolchain.
    #[tokio::test]
    async fn probe_ready_returns_none_without_ready_marker() {
        let tmp = tempfile::tempdir().unwrap();
        let toolchain = tmp.path().join(format!("git-2.55.0-{}", arch_token()));
        tokio::fs::create_dir_all(toolchain.join("bin"))
            .await
            .unwrap();

        assert!(
            probe_ready_toolchain("git", ToolPlatform::MacOS, tmp.path())
                .await
                .is_none(),
            "an unstamped toolchain must not be injected"
        );
    }

    /// Cold cache, an absent tool, and non-macOS requests all probe to `None`.
    #[tokio::test]
    async fn probe_ready_returns_none_for_cold_or_unsupported() {
        let tmp = tempfile::tempdir().unwrap();
        assert!(
            probe_ready_toolchain("git", ToolPlatform::MacOS, tmp.path())
                .await
                .is_none(),
            "cold cache should probe None"
        );
        assert!(
            probe_ready_toolchain("jq", ToolPlatform::MacOS, tmp.path())
                .await
                .is_none(),
            "absent tool should probe None"
        );
        assert!(
            probe_ready_toolchain("git", ToolPlatform::Windows, tmp.path())
                .await
                .is_none(),
            "cold cache probes None on every platform"
        );
    }

    /// Full end-to-end provision of BOTH verification targets: build `git` and
    /// `jq` FROM SOURCE and run them. Asserts each built binary carries NO
    /// `@@HOMEBREW@@` placeholder (the bottle-relocation failure mode) and that
    /// a manifest was written. `#[ignore]` because it hits the network + the
    /// compiler and only works on macOS with CLT; run with:
    ///   `cargo test -p zlayer-toolchain -- --ignored`.
    #[tokio::test]
    #[ignore = "live build test; fetches + compiles git and jq from source (macOS + CLT only)"]
    async fn ensure_git_and_jq_build_from_source_and_run() {
        let tmp = tempfile::tempdir().unwrap();

        for (tool, version_needle) in [("git", "git version"), ("jq", "jq-")] {
            let handle = ensure_toolchain(tool, ToolPlatform::MacOS, tmp.path(), None)
                .await
                .unwrap_or_else(|e| panic!("{tool} toolchain should build from source: {e}"));

            let bin = handle.install_dir.join("bin").join(tool);
            assert!(
                bin.exists(),
                "{tool} binary should exist at <toolchain>/bin/{tool}"
            );

            // The toolchain must carry a manifest.
            let manifest = ToolchainManifest::read_from_toolchain(&handle.install_dir)
                .await
                .unwrap()
                .unwrap_or_else(|| panic!("{tool} toolchain must have a manifest"));
            assert_eq!(manifest.tool, tool);

            // No @@HOMEBREW@@ anywhere in the built binary.
            let bytes = tokio::fs::read(&bin).await.expect("read binary");
            assert!(
                !contains_subslice_bytes(&bytes, b"@@HOMEBREW"),
                "source-built {tool} must contain NO @@HOMEBREW@@ references"
            );

            let mut cmd = tokio::process::Command::new(&bin);
            for (k, v) in &handle.env {
                cmd.env(k, v);
            }
            let out = cmd.arg("--version").output().await.expect("run --version");
            assert!(out.status.success(), "{tool} --version should succeed");
            assert!(
                String::from_utf8_lossy(&out.stdout).contains(version_needle)
                    || String::from_utf8_lossy(&out.stderr).contains(version_needle),
                "{tool} --version output should contain '{version_needle}'"
            );
        }
    }

    /// Tiny byte-substring helper for the binary placeholder scan above.
    fn contains_subslice_bytes(haystack: &[u8], needle: &[u8]) -> bool {
        if needle.is_empty() || haystack.len() < needle.len() {
            return false;
        }
        haystack
            .windows(needle.len())
            .any(|window| window == needle)
    }
}