zlayer-builder 0.13.0

Dockerfile parsing and buildah-based container image building
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
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
//! Windows (Chocolatey) package resolver — counterpart to `macos_image_resolver`.
//!
//! On Windows containers (WCOW), Linux package manager invocations
//! (`apt-get install`, `dnf install`, `apk add`) inside a Dockerfile cannot
//! run natively. This module resolves Linux package names against the
//! `RepoSources` Chocolatey shard files published at
//! `https://zachhandley.github.io/RepoSources/maps/choco/<distro>/<shard>.json`
//! and returns the equivalent Chocolatey package name so the builder can
//! emit `choco install <pkg>` lines in the WCOW lowered Dockerfile.
//!
//! The shard layout, on-disk cache, and HMAC cache-warming hint mirror the
//! macOS resolver in `macos_image_resolver.rs`. The Windows resolver lives in
//! a separate cache subdirectory (`package-maps-choco-v1`) so its TTL/version
//! is independent from the macOS resolver.

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

use serde::{Deserialize, Serialize};
use tracing::{debug, info, warn};
use zlayer_types::package_index::PackageIndexConfig;
use zlayer_types::ImageReference;

use crate::error::{BuildError, Result};

/// Registry namespace for prebuilt `ZLayer` Windows base + toolchain images.
///
/// Mirrors `ZLAYER_REGISTRY` in `macos_image_resolver.rs`. Used by
/// [`rewrite_image_for_windows`] to redirect generic Docker Hub references
/// (e.g. `golang:1.24`, `ubuntu:24.04`) to the equivalent Windows-native
/// prebuilts under this namespace.
const ZLAYER_REGISTRY: &str = "ghcr.io/blackleafdigital/zlayer";

/// Rewrite a generic image reference to the equivalent prebuilt `ZLayer`
/// Windows image under [`ZLAYER_REGISTRY`], parameterized by an LTSC line.
///
/// Counterpart to `macos_image_resolver::prebuilt_cache_ref`. Linux
/// container images cannot run on Windows containers directly, so the
/// builder rewrites known toolchain / base-distro references to prebuilt
/// `nanoserver`-based images tagged with the requested LTSC line
/// (`ltsc2022` or `ltsc2025`).
///
/// Returns `None` if:
/// * The reference is already inside [`ZLAYER_REGISTRY`] (already rewritten).
/// * The repository name doesn't map to a known base distro or toolchain.
///
/// # Examples
///
/// ```ignore
/// assert_eq!(
///     rewrite_image_for_windows("ubuntu:24.04", "ltsc2022"),
///     Some("ghcr.io/blackleafdigital/zlayer/base:windows-ltsc2022".to_string()),
/// );
/// assert_eq!(
///     rewrite_image_for_windows("golang:1.24", "ltsc2025"),
///     Some("ghcr.io/blackleafdigital/zlayer/golang:1.24-windows-ltsc2025".to_string()),
/// );
/// ```
#[must_use]
pub fn rewrite_image_for_windows(image_ref: &str, ltsc: &str) -> Option<String> {
    // Don't double-rewrite images already in our registry.
    if image_ref.starts_with(ZLAYER_REGISTRY) {
        return None;
    }

    // Strip the registry prefix (docker.io/library/, etc.).
    let stripped = strip_registry_prefix_for_windows(image_ref);

    // Split into name and tag using the canonical OCI parser (handles
    // host:port, digests, and missing tags correctly).
    let (name, tag) = match ImageReference::from_str(&stripped) {
        Ok(r) => (
            r.repository().to_string(),
            r.tag().unwrap_or("latest").to_string(),
        ),
        Err(_) => (stripped.clone(), "latest".to_string()),
    };
    let base_name = name.rsplit('/').next().unwrap_or(&name);

    // Base distro images → base:windows-<ltsc>
    if is_base_distro_for_windows(base_name) {
        return Some(format!("{ZLAYER_REGISTRY}/base:windows-{ltsc}"));
    }

    // Toolchain images → {zlayer_registry}/{canonical}:{version}-windows-<ltsc>
    let canonical = match base_name {
        "golang" | "go" => "golang",
        "node" => "node",
        "rust" => "rust",
        "python" | "python3" => "python",
        "deno" => "deno",
        "bun" => "bun",
        _ => return None,
    };

    let version = extract_version_from_tag_for_windows(&tag);
    Some(format!(
        "{ZLAYER_REGISTRY}/{canonical}:{version}-windows-{ltsc}"
    ))
}

/// Check whether the given base image name is a Linux distribution / base image
/// that has a prebuilt Windows counterpart at
/// `{ZLAYER_REGISTRY}/base:windows-<ltsc>`.
fn is_base_distro_for_windows(name: &str) -> bool {
    matches!(
        name,
        "ubuntu"
            | "debian"
            | "alpine"
            | "centos"
            | "fedora"
            | "rockylinux"
            | "almalinux"
            | "archlinux"
            | "amazonlinux"
            | "busybox"
    )
}

/// Strip common registry prefixes from an image reference.
///
/// Local copy of the macOS resolver's helper so this resolver compiles on
/// all platforms (the macOS one is `#[cfg(target_os = "macos")]`).
fn strip_registry_prefix_for_windows(image_ref: &str) -> String {
    let prefixes = [
        "docker.io/library/",
        "docker.io/",
        "index.docker.io/library/",
        "index.docker.io/",
    ];
    for prefix in &prefixes {
        if let Some(rest) = image_ref.strip_prefix(prefix) {
            return rest.to_string();
        }
    }
    image_ref.to_string()
}

/// Extract a version-like prefix from an image tag (e.g. `"20-slim"` → `"20"`).
///
/// Local copy of `macos_toolchain::extract_version_from_tag` so this
/// resolver compiles on all platforms.
fn extract_version_from_tag_for_windows(tag: &str) -> String {
    if tag == "latest" {
        return "latest".to_string();
    }

    // Try to extract a version-like prefix (digits and dots).
    let version_part: String = tag
        .chars()
        .take_while(|c| c.is_ascii_digit() || *c == '.')
        .collect();

    if version_part.is_empty() {
        "latest".to_string()
    } else {
        version_part.trim_end_matches('.').to_string()
    }
}

/// Base URL for Chocolatey package maps on the `RepoSources` `GitHub Pages` site.
const REPO_SOURCES_CHOCO_BASE: &str = "https://zachhandley.github.io/RepoSources/maps/choco";

/// Subdirectory (under the platform cache dir) where Chocolatey shard files
/// are stored. Distinct from the macOS Homebrew subdir so the two caches
/// never collide.
const PACKAGE_MAP_CACHE_SUBDIR: &str = "package-maps-choco-v1";

/// How long a cached Chocolatey shard is considered fresh (7 days).
const PACKAGE_MAP_CACHE_TTL_SECS: u64 = 7 * 24 * 3600;

/// HMAC secret compiled into the binary at build time.
///
/// Set at `cargo build` time via `ZLAYER_REPOSYNC_HMAC_SECRET=<hex>`. If unset
/// at build time, this evaluates to `None` and `fire_reposync_hint` silently
/// skips the POST — useful for dev builds where the cache-warm signal isn't
/// needed. Released binaries (built by CI with the Forgejo secret in scope)
/// carry the value forever. The signing *algorithm* is not re-derived here —
/// it lives once in [`zlayer_toolchain::package_index::sign`], and the hint
/// endpoint is derived from [`PackageIndexConfig`].
const REPOSYNC_HMAC_SECRET: Option<&str> = option_env!("ZLAYER_REPOSYNC_HMAC_SECRET");

/// Base of the `RepoSourceSyncer` (soon `ZPackageIndex` — same API) discovery
/// endpoint. `GET {base}/{name}?discover=true` returns a relocatable-artifact
/// descriptor (forge release / portable archive) when one is known for the
/// requested package. Mirrors the `?discover=true` path used by the macOS
/// resolver against `/formula/{name}`.
const REPOSYNC_DISCOVER_BASE: &str = "https://packages.zlayer.dev/choco";

/// Sentinel value placed in shard mappings to indicate that a Linux package
/// has no Chocolatey equivalent because it is Linux-only (e.g.
/// `linux-headers-generic`, `systemd`). The builder should silently skip
/// these.
const SKIP_SENTINEL: &str = "__skip__";

// ---------------------------------------------------------------------------
// Shard file types
// ---------------------------------------------------------------------------

/// JSON shape of a Chocolatey package-map shard file as published by
/// `RepoSources`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChocoMapShard {
    /// Header describing how/when the shard was generated.
    pub metadata: ChocoMapMetadata,
    /// Linux-package-name → Chocolatey-package-name (or `__skip__` sentinel).
    pub mappings: HashMap<String, String>,
}

/// Metadata header inside a Chocolatey shard JSON file.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChocoMapMetadata {
    /// ISO 8601 timestamp the shard was generated at.
    pub generated_at: String,
    /// Source description (e.g. `"chocolatey.org"`).
    pub source: String,
    /// Distro the shard maps from (e.g. `"debian-12"`).
    pub distro: String,
    /// Shard key (`a`..`z` or `_misc`).
    pub shard: String,
    /// Number of mappings in the shard.
    pub total_mappings: u64,
}

// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------

/// Resolve a single Linux package name to its Chocolatey equivalent.
///
/// * `Ok(Some(choco_pkg))` — the package resolved to a Chocolatey package.
/// * `Ok(None)` — the mapping exists but is marked `__skip__`, meaning the
///   package is Linux-only and the builder should silently omit it.
/// * `Err(_)` — network, cache, or parse failure, AND there's no stale cache
///   to fall back on.
///
/// A "miss" — i.e. the shard fetched cleanly but the package name is absent —
/// also returns `Err(BuildError::RegistryError { .. })` so the caller can
/// distinguish "no Chocolatey equivalent known" from "skipped on purpose".
///
/// # Errors
///
/// Returns `Err(BuildError::RegistryError)` if the shard cannot be fetched
/// (and no stale cache is available) or if the package is absent from the
/// fetched shard. Returns `Err(BuildError::CacheError)` if the platform
/// cache directory cannot be determined.
pub async fn resolve_chocolatey_package(
    linux_pkg: &str,
    source_distro: &str,
) -> Result<Option<String>> {
    let cache_dir = resolve_cache_dir()?;
    resolve_chocolatey_package_with_cache(linux_pkg, source_distro, &cache_dir).await
}

/// Bulk-resolve a list of Linux packages.
///
/// Returns one entry per input package, in the same order, as
/// `(linux_pkg, choco_pkg_or_none, skipped)`:
///
/// * `(name, Some(choco), false)` — resolved.
/// * `(name, None, true)` — mapping says `__skip__`.
/// * `(name, None, false)` — unresolved (no mapping and no error path
///   would still surface that as an error per shard; here we just degrade to
///   `None` for ergonomics so a single missing package doesn't fail the
///   whole batch). Callers that want strict resolution should inspect the
///   `Err` returned by [`resolve_chocolatey_package`] directly.
///
/// All shards needed by the batch are fetched once and reused across lookups.
///
/// # Errors
///
/// Returns `Err(BuildError::CacheError)` if the platform cache directory
/// cannot be determined. Individual shard fetch failures are tolerated:
/// packages mapping to a failed shard are returned with `None`/`false` and
/// a `debug!` line; this function only returns `Err` for unrecoverable
/// setup failures.
pub async fn resolve_chocolatey_packages(
    linux_pkgs: &[String],
    source_distro: &str,
) -> Result<Vec<(String, Option<String>, bool)>> {
    let cache_dir = resolve_cache_dir()?;
    let distro_cache_dir = cache_dir.join(PACKAGE_MAP_CACHE_SUBDIR).join(source_distro);

    // Pre-fetch every shard the batch needs so duplicate package names within
    // a single shard don't trigger duplicate HTTP requests.
    let mut shard_cache: HashMap<&'static str, HashMap<String, String>> = HashMap::new();
    for pkg in linux_pkgs {
        let shard = shard_key(pkg);
        if shard_cache.contains_key(shard) {
            continue;
        }
        match fetch_or_load_shard(source_distro, &distro_cache_dir, shard).await {
            Ok(map) => {
                shard_cache.insert(shard, map);
            }
            Err(e) => {
                debug!(
                    "shard {source_distro}/{shard} unavailable during bulk resolve: {e}; \
                     packages mapping to that shard will be marked unresolved"
                );
                shard_cache.insert(shard, HashMap::new());
            }
        }
    }

    let mut out = Vec::with_capacity(linux_pkgs.len());
    for pkg in linux_pkgs {
        let shard = shard_key(pkg);
        let shard_map = shard_cache.get(shard);
        match shard_map.and_then(|m| m.get(pkg)) {
            Some(val) if val == SKIP_SENTINEL => {
                out.push((pkg.clone(), None, true));
            }
            Some(val) => {
                out.push((pkg.clone(), Some(val.clone()), false));
            }
            None => {
                out.push((pkg.clone(), None, false));
            }
        }
    }
    Ok(out)
}

// ---------------------------------------------------------------------------
// Relocatable-artifact resolution (parity with macOS `ResolvedPackage`)
// ---------------------------------------------------------------------------

/// A resolved Windows package, after consulting both the relocatable-artifact
/// discovery endpoint and the Chocolatey shard map.
///
/// Counterpart to `macos_image_resolver::ResolvedPackage`. The Windows builder
/// prefers *relocatable* artifacts ([`DirectRelease`](Self::DirectRelease) /
/// [`RelocatableArchive`](Self::RelocatableArchive)) — these are downloaded and
/// extracted directly into the container rootfs layer, so the produced image
/// needs no Chocolatey in its base. [`ChocoFallback`](Self::ChocoFallback) is
/// only emitted when no relocatable artifact resolves; the apt→choco
/// translation still lowers those to `choco install`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ResolvedWindowsPackage {
    /// A direct download from a forge release (GitHub, GitLab, Codeberg,
    /// Forgejo) — typically a single `.exe` or a `.zip`/`.tar.*` bundle. The
    /// builder downloads `url`, extracts (or drops, for a bare binary) into a
    /// controlled prefix under the rootfs, and adds the bin dir to `PATH`.
    DirectRelease {
        /// Original Linux package name (preserved for diagnostics/PATH dir).
        name: String,
        /// HTTP(S) URL of the release asset.
        url: String,
        /// Trailing filename of `url`, used to pick the extractor.
        asset_name: String,
    },
    /// A portable/relocatable archive (zip or tarball) that extracts to a
    /// self-contained tree. Same install machinery as
    /// [`DirectRelease`](Self::DirectRelease); kept distinct so the discovery
    /// source ("portable:" / "archive:") is faithfully recorded.
    RelocatableArchive {
        /// Original Linux package name.
        name: String,
        /// HTTP(S) URL of the archive.
        url: String,
        /// Trailing filename of `url`, used to pick the extractor.
        asset_name: String,
    },
    /// No relocatable artifact resolved, but the shard map has a Chocolatey
    /// package name. The apt→choco translation keeps emitting
    /// `choco install -y <choco_name>` for these.
    ChocoFallback {
        /// Original Linux package name.
        name: String,
        /// Chocolatey package id to install.
        choco_name: String,
    },
    /// Linux-only package (`__skip__` sentinel) with no Windows equivalent —
    /// the builder silently omits it.
    Skip {
        /// Original Linux package name.
        name: String,
    },
}

impl ResolvedWindowsPackage {
    /// The original Linux package name this resolution is for.
    #[must_use]
    pub fn name(&self) -> &str {
        match self {
            Self::DirectRelease { name, .. }
            | Self::RelocatableArchive { name, .. }
            | Self::ChocoFallback { name, .. }
            | Self::Skip { name } => name,
        }
    }

    /// `true` when this package resolved to a relocatable artifact that the
    /// builder installs into the rootfs layer (so it must be elided from the
    /// `choco install` line).
    #[must_use]
    pub fn is_relocatable(&self) -> bool {
        matches!(
            self,
            Self::DirectRelease { .. } | Self::RelocatableArchive { .. }
        )
    }
}

/// Response from the `RepoSourceSyncer` / `ZPackageIndex` discovery endpoint.
///
/// Mirrors `macos_image_resolver::DiscoveryResponse`. The `source` tag
/// disambiguates the artifact kind:
/// * `github-release:` / `gitlab-release:` / `codeberg-release:` /
///   `forgejo-release:` → [`ResolvedWindowsPackage::DirectRelease`]
/// * `portable:` / `archive:` / `winget-portable:` →
///   [`ResolvedWindowsPackage::RelocatableArchive`]
#[derive(Debug, Deserialize)]
struct WindowsDiscoveryResponse {
    name: String,
    #[serde(default)]
    source: Option<String>,
    #[serde(default)]
    source_url: Option<String>,
}

/// Resolve a batch of Linux package names to [`ResolvedWindowsPackage`]s.
///
/// For each package, resolution order is:
/// 1. **Relocatable artifact** — `GET {discover}/{pkg}?discover=true`. A
///    forge-release source yields [`ResolvedWindowsPackage::DirectRelease`]; a
///    portable/archive source yields
///    [`ResolvedWindowsPackage::RelocatableArchive`]. This is preferred so the
///    produced image needs no Chocolatey.
/// 2. **Chocolatey fallback** — the existing shard map. A real choco name
///    yields [`ResolvedWindowsPackage::ChocoFallback`]; the `__skip__`
///    sentinel yields [`ResolvedWindowsPackage::Skip`].
/// 3. **Unresolved** — neither source knows the package: surfaced as
///    `Err(BuildError::ChocoResolutionFailed)` by the *caller* (the translator
///    decides whether an unresolved package is fatal). Here it is simply
///    omitted from the result vector so callers can detect the gap by name.
///
/// All shards needed by the batch are fetched once via
/// [`resolve_chocolatey_packages`] and reused. Discovery is a per-package
/// `GET`; failures (offline, 404) degrade silently to the choco fallback.
///
/// # Errors
///
/// Returns `Err(BuildError::CacheError)` if the platform cache directory
/// cannot be determined (the only unrecoverable setup failure). Per-package
/// discovery/network failures degrade to the Chocolatey fallback and never
/// abort the batch.
pub async fn resolve_windows_packages(
    linux_pkgs: &[String],
    source_distro: &str,
) -> Result<Vec<ResolvedWindowsPackage>> {
    // Pull the choco/skip mapping for the whole batch up front (one shard
    // fetch per letter) so the fallback path is cheap.
    let choco = resolve_chocolatey_packages(linux_pkgs, source_distro).await?;
    let mut choco_lookup: HashMap<&str, (Option<&str>, bool)> = HashMap::new();
    for (linux, c, skipped) in &choco {
        choco_lookup.insert(linux.as_str(), (c.as_deref(), *skipped));
    }

    let mut out = Vec::with_capacity(linux_pkgs.len());
    for pkg in linux_pkgs {
        // 1. Prefer a relocatable artifact.
        if let Some(reloc) = discover_relocatable_artifact(pkg).await {
            out.push(reloc);
            continue;
        }

        // 2. Chocolatey fallback (or skip).
        match choco_lookup.get(pkg.as_str()) {
            Some((_, true)) => out.push(ResolvedWindowsPackage::Skip { name: pkg.clone() }),
            Some((Some(choco_name), false)) => out.push(ResolvedWindowsPackage::ChocoFallback {
                name: pkg.clone(),
                choco_name: (*choco_name).to_string(),
            }),
            // 3. Unresolved — omit; the caller surfaces the diagnostic. This is
            //    a genuine MISS (no relocatable artifact AND no choco mapping),
            //    so fire a cheap fire-and-forget "unfulfilled request" to
            //    ZPackageIndex. The choco resolver maps a Debian source package
            //    to Windows, so the source manager is `apt`; distro normalized
            //    (`_` -> `-`, no-op when already `debian-12`).
            Some((None, false)) | None => {
                debug!(
                    "no relocatable artifact and no choco mapping for '{pkg}'; leaving unresolved"
                );
                crate::harvest::report_unfulfilled(
                    &source_distro.replacen('_', "-", 1),
                    "apt",
                    pkg,
                );
            }
        }
    }
    Ok(out)
}

/// Ask the discovery endpoint whether `pkg` has a relocatable Windows
/// artifact. Returns `None` on any failure (offline, 404, unrecognised
/// source) so the caller can fall back to Chocolatey.
///
/// Setting `ZLAYER_WINDOWS_DISCOVER_DISABLE=1` short-circuits the live `GET`
/// and always returns `None` — used by the hermetic translator unit tests
/// (which seed offline shard fixtures and must not touch the network) and by
/// operators who want a pure-Chocolatey lowering with no discovery round-trip.
async fn discover_relocatable_artifact(pkg: &str) -> Option<ResolvedWindowsPackage> {
    if std::env::var_os("ZLAYER_WINDOWS_DISCOVER_DISABLE").is_some_and(|v| !v.is_empty()) {
        debug!("ZLAYER_WINDOWS_DISCOVER_DISABLE set; skipping relocatable discovery for {pkg}");
        return None;
    }
    let url = format!("{REPOSYNC_DISCOVER_BASE}/{pkg}?discover=true");
    let resp = reqwest::get(&url).await.ok()?;
    if !resp.status().is_success() {
        return None;
    }
    let text = resp.text().await.ok()?;
    let discovery: WindowsDiscoveryResponse = serde_json::from_str(&text).ok()?;
    let source = discovery.source.as_deref()?;
    let src_url = discovery.source_url.clone().unwrap_or_default();
    if src_url.is_empty() {
        return None;
    }
    let asset_name = src_url.rsplit('/').next().unwrap_or(pkg).to_string();
    let name = if discovery.name.is_empty() {
        pkg.to_string()
    } else {
        discovery.name.clone()
    };

    if source.starts_with("github-release:")
        || source.starts_with("gitlab-release:")
        || source.starts_with("codeberg-release:")
        || source.starts_with("forgejo-release:")
    {
        info!("Discovered {pkg} as a direct forge release for Windows ({source})");
        return Some(ResolvedWindowsPackage::DirectRelease {
            name,
            url: src_url,
            asset_name,
        });
    }
    if source.starts_with("portable:")
        || source.starts_with("archive:")
        || source.starts_with("winget-portable:")
    {
        info!("Discovered {pkg} as a relocatable archive for Windows ({source})");
        return Some(ResolvedWindowsPackage::RelocatableArchive {
            name,
            url: src_url,
            asset_name,
        });
    }
    debug!("discovery for {pkg} returned unrecognised source '{source}'; falling back to choco");
    None
}

// ---------------------------------------------------------------------------
// Internals
// ---------------------------------------------------------------------------

/// Compute the shard key for a Linux package name.
///
/// Mirrors `macos_image_resolver::shard_key`: the lowercase first ASCII
/// letter (`a`..`z`) if alphabetic, otherwise `_misc`. Empty strings and
/// non-ASCII inputs also map to `_misc`.
fn shard_key(name: &str) -> &'static str {
    let first = name.chars().next().map(|c| c.to_ascii_lowercase());
    match first {
        Some(c) if c.is_ascii_lowercase() => match c {
            'a' => "a",
            'b' => "b",
            'c' => "c",
            'd' => "d",
            'e' => "e",
            'f' => "f",
            'g' => "g",
            'h' => "h",
            'i' => "i",
            'j' => "j",
            'k' => "k",
            'l' => "l",
            'm' => "m",
            'n' => "n",
            'o' => "o",
            'p' => "p",
            'q' => "q",
            'r' => "r",
            's' => "s",
            't' => "t",
            'u' => "u",
            'v' => "v",
            'w' => "w",
            'x' => "x",
            'y' => "y",
            'z' => "z",
            _ => "_misc",
        },
        _ => "_misc",
    }
}

/// Outcome of looking up a single package inside an already-parsed shard.
#[cfg(test)]
#[derive(Debug, PartialEq, Eq)]
enum ShardLookup {
    /// Mapping resolved to a Chocolatey package name.
    Found(String),
    /// Mapping is marked `__skip__` (Linux-only).
    Skip,
    /// Package name is absent from this shard.
    Absent,
}

/// Inspect a parsed shard for a given package name. Only used by unit tests
/// today; production code goes through [`fetch_or_load_shard`] +
/// [`resolve_chocolatey_package_with_cache`] which combine I/O and lookup.
#[cfg(test)]
fn resolve_in_shard(linux_pkg: &str, shard: &ChocoMapShard) -> ShardLookup {
    match shard.mappings.get(linux_pkg) {
        Some(v) if v == SKIP_SENTINEL => ShardLookup::Skip,
        Some(v) => ShardLookup::Found(v.clone()),
        None => ShardLookup::Absent,
    }
}

/// Returns the platform cache directory used for storing Chocolatey shards.
///
/// `ZLAYER_PACKAGE_MAP_CACHE_DIR`, when set to a non-empty path, overrides the
/// platform default on **every** OS. This is both an operator knob (relocate
/// the package-map cache) and what the test suite uses for a hermetic cache —
/// `dirs::cache_dir()` ignores `XDG_CACHE_HOME` on macOS and Windows, so an
/// env override is the only portable way to redirect it.
fn resolve_cache_dir() -> Result<PathBuf> {
    if let Some(dir) = std::env::var_os("ZLAYER_PACKAGE_MAP_CACHE_DIR") {
        let p = PathBuf::from(dir);
        if !p.as_os_str().is_empty() {
            return Ok(p);
        }
    }
    dirs::cache_dir().ok_or_else(|| {
        BuildError::cache_error("could not determine platform cache directory (dirs::cache_dir)")
    })
}

/// Single-package resolve with an explicit cache root. Used by
/// [`resolve_chocolatey_package`] and by unit tests that need a controlled
/// cache dir.
async fn resolve_chocolatey_package_with_cache(
    linux_pkg: &str,
    source_distro: &str,
    cache_dir: &Path,
) -> Result<Option<String>> {
    let distro_cache_dir = cache_dir.join(PACKAGE_MAP_CACHE_SUBDIR).join(source_distro);
    let shard = shard_key(linux_pkg);
    let map = fetch_or_load_shard(source_distro, &distro_cache_dir, shard).await?;

    match map.get(linux_pkg) {
        Some(val) if val == SKIP_SENTINEL => {
            debug!("chocolatey resolver skipping linux-only package: {linux_pkg}");
            Ok(None)
        }
        Some(val) => Ok(Some(val.clone())),
        None => Err(BuildError::registry_error(format!(
            "no Chocolatey mapping for '{linux_pkg}' in {source_distro}/{shard}.json"
        ))),
    }
}

/// Fetch one shard for `<distro>/<shard>.json`, with on-disk cache + stale
/// fallback.
///
/// Order of precedence:
/// 1. Fresh local cache (mtime within TTL) — read and return.
/// 2. Network fetch — write to cache, fire HMAC POST hint, return.
/// 3. Stale cache fallback — read and return with a `warn!`.
/// 4. Truly nothing available — propagate the HTTP error as `RegistryError`.
async fn fetch_or_load_shard(
    distro: &str,
    cache_dir: &Path,
    shard: &str,
) -> Result<HashMap<String, String>> {
    let cache_path = cache_dir.join(format!("{shard}.json"));

    // 1. Fresh local cache.
    if let Ok(meta) = tokio::fs::metadata(&cache_path).await {
        if let Ok(modified) = meta.modified() {
            let age = modified
                .elapsed()
                .unwrap_or(std::time::Duration::from_secs(u64::MAX));
            if age.as_secs() < PACKAGE_MAP_CACHE_TTL_SECS {
                if let Some(map) = read_cached_map(&cache_path).await {
                    debug!(
                        "Using cached choco package map for {distro}/{shard} ({} mappings, age {}s)",
                        map.len(),
                        age.as_secs()
                    );
                    return Ok(map);
                }
            }
        }
    }

    // 2. Network fetch.
    let url = format!("{REPO_SOURCES_CHOCO_BASE}/{distro}/{shard}.json");
    debug!("Fetching choco shard from {url}");
    match fetch_shard(&url).await {
        Ok(shard_file) => {
            info!(
                "Fetched {} choco mappings for {distro}/{shard} from RepoSources",
                shard_file.mappings.len()
            );
            if let Err(e) = write_cached_shard(cache_dir, &cache_path, &shard_file).await {
                warn!("Failed to cache choco shard {distro}/{shard}: {e}");
            }
            fire_reposync_hint(distro, shard);
            Ok(shard_file.mappings)
        }
        Err(e) => {
            debug!("Failed to fetch choco shard {distro}/{shard}: {e}");

            // 3. Stale cache fallback.
            if let Some(map) = read_cached_map(&cache_path).await {
                warn!(
                    "Using stale cached choco shard for {distro}/{shard} ({} mappings)",
                    map.len()
                );
                return Ok(map);
            }

            // 4. Nothing available.
            Err(BuildError::registry_error(format!(
                "failed to fetch choco shard {distro}/{shard}.json: {e}"
            )))
        }
    }
}

/// Fetch one shard JSON document from `url`.
async fn fetch_shard(url: &str) -> std::result::Result<ChocoMapShard, String> {
    let response = reqwest::get(url)
        .await
        .map_err(|e| format!("HTTP request failed: {e}"))?;

    if !response.status().is_success() {
        return Err(format!("HTTP {}", response.status()));
    }

    response
        .json::<ChocoMapShard>()
        .await
        .map_err(|e| format!("JSON parse failed: {e}"))
}

/// Read a cached shard from disk and return just the mappings.
async fn read_cached_map(path: &Path) -> Option<HashMap<String, String>> {
    let contents = tokio::fs::read_to_string(path).await.ok()?;
    let shard: ChocoMapShard = serde_json::from_str(&contents).ok()?;
    Some(shard.mappings)
}

/// Write a `ChocoMapShard` to disk, creating the directory if needed.
async fn write_cached_shard(
    map_dir: &Path,
    cache_path: &Path,
    shard: &ChocoMapShard,
) -> std::result::Result<(), String> {
    tokio::fs::create_dir_all(map_dir)
        .await
        .map_err(|e| format!("create dir: {e}"))?;
    let json = serde_json::to_string_pretty(shard).map_err(|e| format!("serialize: {e}"))?;
    tokio::fs::write(cache_path, json)
        .await
        .map_err(|e| format!("write: {e}"))
}

/// Fire-and-forget cache-warm hint POST to `RepoSourceSyncer`. No-op when
/// `ZLAYER_REPOSYNC_HMAC_SECRET` was unset at build time.
///
/// Reuses the single workspace HMAC signer
/// ([`zlayer_toolchain::package_index::sign`]) and derives the endpoint from
/// [`PackageIndexConfig`] (`{base}/choco-hint`) rather than re-deriving either.
fn fire_reposync_hint(distro: &str, shard: &str) {
    let Some(secret) = REPOSYNC_HMAC_SECRET.filter(|s| !s.is_empty()) else {
        debug!(
            "ZLAYER_REPOSYNC_HMAC_SECRET not baked into binary (or empty); skipping reposync cache warm for choco/{distro}/{shard}"
        );
        return;
    };
    let distro = distro.to_string();
    let shard = shard.to_string();
    let endpoint = PackageIndexConfig::from_env().choco_hint_url();
    tokio::spawn(async move {
        let payload = format!(r#"{{"scope":"choco","distro":"{distro}","shard":"{shard}"}}"#);
        let signature = zlayer_toolchain::package_index::sign(secret, payload.as_bytes());
        let _ = reqwest::Client::new()
            .post(&endpoint)
            .header("x-reposync-signature", signature)
            .header("content-type", "application/json")
            .body(payload)
            .send()
            .await;
    });
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    const FIXTURE_SHARD: &str = r#"{
        "metadata": {
            "generated_at": "2026-05-21T00:00:00Z",
            "source": "chocolatey.org",
            "distro": "debian-12",
            "shard": "c",
            "total_mappings": 2
        },
        "mappings": {
            "curl": "curl",
            "linux-headers-generic": "__skip__"
        }
    }"#;

    #[test]
    fn shard_key_alpha() {
        assert_eq!(shard_key("apache2"), "a");
        assert_eq!(shard_key("curl"), "c");
        assert_eq!(shard_key("Zoo"), "z");
    }

    #[test]
    fn shard_key_non_alpha() {
        assert_eq!(shard_key("7zip"), "_misc");
        assert_eq!(shard_key("_internal"), "_misc");
        assert_eq!(shard_key(""), "_misc");
    }

    #[test]
    fn parse_shard_json() {
        let shard: ChocoMapShard =
            serde_json::from_str(FIXTURE_SHARD).expect("fixture parses cleanly");
        assert_eq!(shard.metadata.distro, "debian-12");
        assert_eq!(shard.metadata.shard, "c");
        assert_eq!(shard.metadata.total_mappings, 2);

        // Normal mapping.
        assert_eq!(
            resolve_in_shard("curl", &shard),
            ShardLookup::Found("curl".to_string()),
        );

        // __skip__ sentinel.
        assert_eq!(
            resolve_in_shard("linux-headers-generic", &shard),
            ShardLookup::Skip,
        );

        // Absent from shard.
        assert_eq!(
            resolve_in_shard("not-in-shard", &shard),
            ShardLookup::Absent,
        );
    }

    #[tokio::test]
    async fn cache_ttl_respected() {
        let tmp = tempfile::tempdir().unwrap();
        let cache_dir = tmp.path().to_path_buf();
        let distro_dir = cache_dir.join(PACKAGE_MAP_CACHE_SUBDIR).join("debian-12");
        tokio::fs::create_dir_all(&distro_dir).await.unwrap();
        let shard_path = distro_dir.join("c.json");
        tokio::fs::write(&shard_path, FIXTURE_SHARD).await.unwrap();

        // Sanity check: with a fresh mtime, resolver reads from cache (no network).
        let fresh = resolve_chocolatey_package_with_cache("curl", "debian-12", &cache_dir)
            .await
            .expect("fresh cache hit should resolve");
        assert_eq!(fresh.as_deref(), Some("curl"));

        // Rewind mtime to 8 days ago — the loader must treat it as expired
        // and fall through to the network-fetch path. We then verify that
        // the same TTL predicate the production code uses (mtime elapsed >=
        // PACKAGE_MAP_CACHE_TTL_SECS) reports the file as stale.
        let eight_days_ago = std::time::SystemTime::now()
            .checked_sub(std::time::Duration::from_secs(8 * 24 * 3600))
            .unwrap();
        let file = std::fs::File::options()
            .write(true)
            .open(&shard_path)
            .unwrap();
        file.set_modified(eight_days_ago)
            .expect("backdate mtime via File::set_modified");
        drop(file);

        let meta = tokio::fs::metadata(&shard_path).await.unwrap();
        let modified = meta.modified().unwrap();
        let age = modified.elapsed().unwrap();
        assert!(
            age.as_secs() >= PACKAGE_MAP_CACHE_TTL_SECS,
            "expected backdated mtime to exceed TTL ({} >= {})",
            age.as_secs(),
            PACKAGE_MAP_CACHE_TTL_SECS
        );
    }

    #[test]
    fn rewrite_image_for_windows_skips_already_rewritten() {
        assert_eq!(
            rewrite_image_for_windows(
                "ghcr.io/blackleafdigital/zlayer/base:windows-ltsc2022",
                "ltsc2022",
            ),
            None,
        );
        assert_eq!(
            rewrite_image_for_windows(
                "ghcr.io/blackleafdigital/zlayer/golang:1.24-windows-ltsc2025",
                "ltsc2025",
            ),
            None,
        );
    }

    #[test]
    fn rewrite_image_for_windows_ubuntu_ltsc2022() {
        assert_eq!(
            rewrite_image_for_windows("ubuntu:24.04", "ltsc2022"),
            Some("ghcr.io/blackleafdigital/zlayer/base:windows-ltsc2022".to_string()),
        );
    }

    #[test]
    fn rewrite_image_for_windows_ubuntu_ltsc2025() {
        assert_eq!(
            rewrite_image_for_windows("ubuntu:24.04", "ltsc2025"),
            Some("ghcr.io/blackleafdigital/zlayer/base:windows-ltsc2025".to_string()),
        );
    }

    #[test]
    fn rewrite_image_for_windows_golang_ltsc2022() {
        assert_eq!(
            rewrite_image_for_windows("golang:1.24", "ltsc2022"),
            Some("ghcr.io/blackleafdigital/zlayer/golang:1.24-windows-ltsc2022".to_string()),
        );
    }

    #[test]
    fn rewrite_image_for_windows_node_ltsc2025() {
        assert_eq!(
            rewrite_image_for_windows("node:22", "ltsc2025"),
            Some("ghcr.io/blackleafdigital/zlayer/node:22-windows-ltsc2025".to_string()),
        );
    }

    #[test]
    fn rewrite_image_for_windows_unknown_returns_none() {
        assert_eq!(rewrite_image_for_windows("nginx:1.25", "ltsc2022"), None);
        assert_eq!(rewrite_image_for_windows("redis:7", "ltsc2025"), None);
    }

    #[test]
    fn rewrite_image_for_windows_strips_docker_io_prefix() {
        assert_eq!(
            rewrite_image_for_windows("docker.io/library/ubuntu:22.04", "ltsc2022"),
            Some("ghcr.io/blackleafdigital/zlayer/base:windows-ltsc2022".to_string()),
        );
    }

    #[test]
    fn rewrite_image_for_windows_python_alias() {
        assert_eq!(
            rewrite_image_for_windows("python3:3.12", "ltsc2022"),
            Some("ghcr.io/blackleafdigital/zlayer/python:3.12-windows-ltsc2022".to_string()),
        );
    }

    #[test]
    fn rewrite_image_for_windows_no_tag_defaults_to_latest() {
        assert_eq!(
            rewrite_image_for_windows("bun", "ltsc2025"),
            Some("ghcr.io/blackleafdigital/zlayer/bun:latest-windows-ltsc2025".to_string()),
        );
    }

    #[test]
    fn resolved_windows_package_accessors() {
        let dr = ResolvedWindowsPackage::DirectRelease {
            name: "jq".into(),
            url: "https://example.com/jq.exe".into(),
            asset_name: "jq.exe".into(),
        };
        assert_eq!(dr.name(), "jq");
        assert!(dr.is_relocatable());

        let ra = ResolvedWindowsPackage::RelocatableArchive {
            name: "ripgrep".into(),
            url: "https://example.com/rg.zip".into(),
            asset_name: "rg.zip".into(),
        };
        assert_eq!(ra.name(), "ripgrep");
        assert!(ra.is_relocatable());

        let cf = ResolvedWindowsPackage::ChocoFallback {
            name: "curl".into(),
            choco_name: "curl".into(),
        };
        assert_eq!(cf.name(), "curl");
        assert!(!cf.is_relocatable());

        let sk = ResolvedWindowsPackage::Skip {
            name: "linux-headers-generic".into(),
        };
        assert_eq!(sk.name(), "linux-headers-generic");
        assert!(!sk.is_relocatable());
    }

    #[tokio::test]
    async fn resolve_windows_packages_falls_back_to_choco_when_discovery_disabled() {
        // With discovery disabled and an offline shard fixture, every
        // package must resolve through the Chocolatey fallback path —
        // no network for either discovery or shard fetch.
        let tmp = tempfile::tempdir().unwrap();
        let cache_dir = tmp.path().to_path_buf();
        std::env::set_var("ZLAYER_PACKAGE_MAP_CACHE_DIR", &cache_dir);
        std::env::set_var("ZLAYER_WINDOWS_DISCOVER_DISABLE", "1");
        let distro_dir = cache_dir.join(PACKAGE_MAP_CACHE_SUBDIR).join("debian-12");
        tokio::fs::create_dir_all(&distro_dir).await.unwrap();
        tokio::fs::write(distro_dir.join("c.json"), FIXTURE_SHARD)
            .await
            .unwrap();
        // `linux-headers-generic` shards to `l`, so it needs its own shard
        // file carrying the `__skip__` sentinel.
        let l_shard = r#"{
            "metadata": {
                "generated_at": "2026-05-21T00:00:00Z",
                "source": "chocolatey.org",
                "distro": "debian-12",
                "shard": "l",
                "total_mappings": 1
            },
            "mappings": { "linux-headers-generic": "__skip__" }
        }"#;
        tokio::fs::write(distro_dir.join("l.json"), l_shard)
            .await
            .unwrap();

        let pkgs = vec!["curl".to_string(), "linux-headers-generic".to_string()];
        let resolved = resolve_windows_packages(&pkgs, "debian-12")
            .await
            .expect("resolve succeeds with offline fixture");

        std::env::remove_var("ZLAYER_PACKAGE_MAP_CACHE_DIR");
        std::env::remove_var("ZLAYER_WINDOWS_DISCOVER_DISABLE");

        assert_eq!(resolved.len(), 2);
        assert_eq!(
            resolved[0],
            ResolvedWindowsPackage::ChocoFallback {
                name: "curl".into(),
                choco_name: "curl".into(),
            }
        );
        assert_eq!(
            resolved[1],
            ResolvedWindowsPackage::Skip {
                name: "linux-headers-generic".into(),
            }
        );
    }

    #[tokio::test]
    #[ignore = "live network: hits zachhandley.github.io"]
    async fn live_resolve_curl_debian12() {
        let result = resolve_chocolatey_package("curl", "debian-12").await;
        let resolved = result.expect("live network resolve should succeed");
        assert!(
            resolved.is_some(),
            "curl should resolve to some chocolatey package, got None (__skip__)"
        );
    }
}