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
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
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
//! Windows toolchain provisioning — "our apt" for the HCS sandbox.
//!
//! The Windows analogue of the macOS [`crate::source_build`] /
//! [`crate::prebuilt`] paths. The HCS sandbox has no package manager, so this
//! provisions a named tool into a self-contained, **relocatable** toolchain with the
//! same [`ToolchainManifest`] layout the macOS toolchains use, and the same on-disk cache
//! key (`<cache>/<tool>-<version>-<arch>/` + a `.ready` marker).
//!
//! # Strategy
//!
//! 1. **`git` → MinGit** ([`ensure_mingit`]). Git for Windows publishes
//!    **MinGit**, a fully self-contained, relocatable portable zip (no
//!    installer, no registry writes, no absolute-path baking) — exactly the
//!    Windows equivalent of a relocation-free toolchain. We resolve the latest release
//!    from the `git-for-windows/git` GitHub releases, fetch the right
//!    architecture's `MinGit-<ver>-{64-bit,arm64}.zip`, and extract it into the
//!    toolchain.
//! 2. **Everything else → Chocolatey.** The package is resolved through the
//!    ZLayer package index (`/choco/:name` → `.nupkg` URL + version), the
//!    `.nupkg` is downloaded (digest-verified when the index/lockfile carries
//!    one) and its `tools/chocolateyInstall.ps1` is parsed into an
//!    [`InstallPlan`] by [`crate::recipe_choco`]:
//!    - **Portable zip / web-file packages** — plans made only of
//!      [`InstallStep::StageResource`] / [`InstallStep::PrefixInstall`] /
//!      [`InstallStep::BinInstall`] — execute **leaf-side**: each resource is
//!      fetched (sha256-verified from the ps1's embedded checksums; an empty
//!      checksum — the weak-checksum case [`crate::recipe_choco`] documents —
//!      downloads unverified with a loud warning) and extracted/staged into
//!      the toolchain prefix. This is fetch + unzip, no arbitrary code — the
//!      same trust class as MinGit.
//!    - **exe/msi installer packages** (any other plan shape) run
//!      `choco install` inside a Windows container through the registered
//!      [`crate::executor::ContainerBuildExecutor`] with the network allowed
//!      loudly (grep `NET-FALLBACK`). When no executor is registered this
//!      fails with [`ToolchainError::ExecutorUnavailable`] — never a host
//!      subprocess, and never a wrong binary.
//!
//! This module is compiled on **all** hosts (it is pure HTTP + zip extraction +
//! manifest I/O; the executor call is platform-tagged *data*, not `cfg`'d code),
//! so the toolchain format, the MinGit resolver, and the choco chain are
//! unit-testable on a macOS build host even though the toolchains are only
//! *provisioned for* Windows containers.

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

use serde::Deserialize;

use crate::error::{Result, ToolchainError};
use crate::executor::{ContainerBuildExecutor, ContainerBuildRequest, NetPolicy};
use crate::manifest::{ToolchainManifest, ToolchainSource};
use crate::recipe::{InstallPlan, InstallStep};
use crate::registry::ToolchainArtifactId;
use crate::relocate::RelocationReport;

/// The platform token stored in a Windows artifact id / coverage record.
const WINDOWS_OS_TOKEN: &str = "windows";

/// Which install path produced a Windows toolchain, for coverage + publish
/// routing. Both carry the finalize [`RelocationReport`] (finalization always
/// relocates), but only the hermetic path is published.
#[derive(Debug)]
enum WinBuildKind {
    /// A leaf-executable choco plan or the MinGit extract: hermetic, publishable
    /// → coverage `Built`.
    Hermetic(RelocationReport),
    /// The loud full-network containerized `choco install` (`AllowLoud`) fallback
    /// → coverage `NetFallback` (not published).
    NetFallback(RelocationReport),
}

/// `git-for-windows/git` GitHub "latest release" API endpoint.
const GIT_FOR_WINDOWS_LATEST: &str =
    "https://api.github.com/repos/git-for-windows/git/releases/latest";

/// Offline fallback: the latest known Git for Windows release at the time of
/// writing (looked up from `git-for-windows/git` releases — NOT a stale guess).
/// Used only when the live release API is unreachable (offline / rate-limited),
/// so a per-machine cache can still be seeded deterministically.
const MINGIT_FALLBACK_VERSION: &str = "2.55.0";
/// Release tag matching [`MINGIT_FALLBACK_VERSION`].
const MINGIT_FALLBACK_TAG: &str = "v2.55.0.windows.1";

/// Architecture token used in toolchain cache keys + MinGit asset names
/// (`x86_64`/`arm64`).
#[must_use]
pub fn windows_arch_token() -> &'static str {
    if cfg!(target_arch = "aarch64") {
        "arm64"
    } else {
        "x86_64"
    }
}

/// Split a package request into `(formula, version_token)` — mirrors the macOS
/// `split_pkg`. The full `pkg` is always the formula/tool name.
fn split_pkg(pkg: &str) -> (&str, &str) {
    match pkg.split_once('@') {
        Some((_, ver)) if !ver.is_empty() => (pkg, ver),
        _ => (pkg, "latest"),
    }
}

/// Provision (or reuse) a Windows toolchain for `pkg`, returning the toolchain directory.
///
/// Dispatches: `git` lands as a relocatable MinGit toolchain; every other formula
/// resolves through the Chocolatey chain ([`ensure_choco_toolchain`]): portable
/// zip/web-file packages are fetched + extracted leaf-side, exe/msi installer
/// packages run `choco install` in a network-enabled Windows container via the
/// registered [`crate::executor::ContainerBuildExecutor`].
///
/// # Errors
///
/// Returns [`ToolchainError::ExecutorUnavailable`] for an installer-style
/// package when no container executor is registered, and propagates
/// resolution / download / extraction errors.
pub async fn ensure_windows_toolchain(
    pkg: &str,
    cache_dir: &Path,
    lockfile: Option<&crate::ToolchainLockfile>,
) -> Result<PathBuf> {
    let (formula, _version) = split_pkg(pkg);
    match formula {
        "git" => ensure_mingit(cache_dir, lockfile).await,
        other => ensure_choco_toolchain(other, cache_dir, lockfile).await,
    }
}

/// Resolve a Windows tool to `(version, url, published_sha256)` for the lockfile
/// resolver, without downloading. `git` resolves through the MinGit release
/// API; everything else resolves to its `.nupkg` coordinates through the
/// package index's Chocolatey route (the lock then pins the nupkg URL +
/// version, and the digest is computed by the caller's verifying download).
///
/// # Errors
///
/// Propagates package-index resolution failures for non-`git` formulae.
pub(crate) async fn resolve_locked_windows(
    formula: &str,
) -> Result<(String, String, Option<String>)> {
    match formula {
        "git" => Ok(resolve_mingit(windows_arch_token()).await),
        other => resolve_choco(other).await,
    }
}

// ---------------------------------------------------------------------------
// Chocolatey chain (every non-`git` tool)
// ---------------------------------------------------------------------------

/// Identity + provenance of a resolved Chocolatey package, threaded from
/// resolution through install into the manifest.
struct ChocoPkg {
    /// The tool / choco package id (e.g. `terraform`).
    tool: String,
    /// Resolved (or lock-pinned) package version — also the cache-key version.
    version: String,
    /// The `.nupkg` download URL (recorded as the manifest source URL).
    nupkg_url: String,
    /// The digest actually verified for the `.nupkg`, or empty when no
    /// index/lockfile digest existed (verification then comes from the ps1's
    /// embedded per-resource checksums on the leaf path).
    verified_sha256: String,
}

/// Resolve a non-`git` Windows tool through the package index's Chocolatey
/// route to `(version, nupkg_url, published_sha256)`.
///
/// [`ChocoData`](zlayer_types::package_index::ChocoData) carries `version`,
/// the `.nupkg` `url`, and an `Option<sha256>` that is usually `None` (choco
/// publishes no reliable package digest — the ps1's embedded checksums verify
/// the actual payloads instead).
async fn resolve_choco(formula: &str) -> Result<(String, String, Option<String>)> {
    let data = crate::package_index::PackageIndexClient::from_env()
        .get_choco(formula)
        .await?;
    let version = data.version.trim();
    if version.is_empty() {
        return Err(ToolchainError::RegistryError {
            message: format!("choco entry for {formula} carries no version"),
        });
    }
    let url = data.url.trim();
    if url.is_empty() {
        return Err(ToolchainError::RegistryError {
            message: format!("choco entry for {formula} carries no .nupkg URL"),
        });
    }
    let sha256 = data
        .sha256
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty());
    Ok((version.to_string(), url.to_string(), sha256))
}

/// Provision (or reuse) a Chocolatey-backed toolchain for `formula`.
///
/// Idempotent via the `<toolchain>/.ready` marker (written LAST, after the
/// manifest — mirroring [`ensure_mingit`]). A lockfile hit pins the exact
/// version + nupkg URL + digest (consume-only, exactly like MinGit's locked
/// path); a miss live-resolves through the package index.
async fn ensure_choco_toolchain(
    formula: &str,
    cache_dir: &Path,
    lockfile: Option<&crate::ToolchainLockfile>,
) -> Result<PathBuf> {
    let arch = windows_arch_token();

    // A lock hit pins the exact version + nupkg URL + digest (consume-only).
    let (version, url, expected_sha) = match lockfile.and_then(|l| {
        use crate::ToolchainLockfileExt;
        l.lookup(formula, "windows", arch)
    }) {
        Some(locked) => (
            locked.version.clone(),
            locked.url.clone(),
            Some(locked.sha256.clone()),
        ),
        None => resolve_choco(formula).await?,
    };

    let toolchain = cache_dir.join(format!("{formula}-{version}-{arch}"));
    let ready_marker = toolchain.join(".ready");
    // Local `.ready` wins FIRST (zero network).
    if tokio::fs::try_exists(&ready_marker).await.unwrap_or(false) {
        return Ok(toolchain);
    }

    // Identity known (version resolved) → pull-first, best-effort.
    let id = ToolchainArtifactId {
        tool: formula.to_string(),
        version: version.clone(),
        os: WINDOWS_OS_TOKEN.to_string(),
        arch: arch.to_string(),
    };
    if crate::pull_first(&id, &toolchain).await?.is_some() {
        return Ok(toolchain);
    }

    // Miss → install fresh, then record coverage + (hermetic) publish.
    match install_choco_fresh(formula, &version, &url, expected_sha.as_deref(), &toolchain).await {
        Ok(WinBuildKind::Hermetic(report)) => {
            crate::finish_built(&id, &toolchain, Some(&report), false).await;
            Ok(toolchain)
        }
        Ok(WinBuildKind::NetFallback(_report)) => {
            crate::record_net_fallback(&id).await;
            Ok(toolchain)
        }
        Err(e) => {
            crate::record_failed(&id, &e).await;
            Err(e)
        }
    }
}

/// Download the `.nupkg`, parse it, and install it into a freshly-cleared
/// `toolchain`, returning which path won ([`WinBuildKind`]). Split out of
/// [`ensure_choco_toolchain`] so the coverage/publish wrapper stays thin and any
/// error routes to a single `record_failed`.
async fn install_choco_fresh(
    formula: &str,
    version: &str,
    url: &str,
    expected_sha: Option<&str>,
    toolchain: &Path,
) -> Result<WinBuildKind> {
    // Fresh install — clear any partial toolchain.
    let _ = tokio::fs::remove_dir_all(toolchain).await;
    tokio::fs::create_dir_all(toolchain).await?;

    // Download the .nupkg (digest-verified when the index/lock pinned one;
    // otherwise the digest is computed only — real verification then comes
    // from the ps1's embedded per-resource checksums on the leaf path).
    tracing::info!(tool = formula, url = %url, "downloading Chocolatey .nupkg");
    let nupkg_path = toolchain.join(".pkg.nupkg");
    let verified = expected_sha.map(str::trim).filter(|s| !s.is_empty());
    let computed = crate::package_index::download_verified(url, &nupkg_path, verified).await?;
    let bytes = tokio::fs::read(&nupkg_path).await?;
    let _ = tokio::fs::remove_file(&nupkg_path).await;

    let recipe = crate::recipe_choco::parse_nupkg(&bytes, toolchain)?;
    let pkg = ChocoPkg {
        tool: formula.to_string(),
        version: version.to_string(),
        nupkg_url: url.to_string(),
        verified_sha256: if verified.is_some() {
            computed
        } else {
            String::new()
        },
    };

    let executor = crate::executor::container_executor();
    install_from_choco_recipe(&pkg, recipe.plan, toolchain, executor.as_deref()).await
}

/// Install a parsed choco plan into `toolchain` and finalize it (relocate +
/// manifest + `.ready`): leaf-side fetch + extract for a leaf-executable plan,
/// otherwise containerized `choco install` through `executor`. Returns whether
/// the hermetic leaf path or the loud-network container path won (so the caller
/// publishes only the former), carrying the finalize [`RelocationReport`].
///
/// The executor is a parameter (rather than resolved here) so tests can drive
/// the decision with a mock without touching the process-global slot.
async fn install_from_choco_recipe(
    pkg: &ChocoPkg,
    plan: InstallPlan,
    toolchain: &Path,
    executor: Option<&dyn ContainerBuildExecutor>,
) -> Result<WinBuildKind> {
    let scratch = toolchain.join(".build");
    tokio::fs::create_dir_all(&scratch).await?;

    let net_fallback = if plan_is_leaf_executable(&plan) {
        execute_choco_plan_leaf(&pkg.tool, &plan, toolchain).await?;
        false
    } else {
        let Some(executor) = executor else {
            return Err(ToolchainError::ExecutorUnavailable {
                tool: pkg.tool.clone(),
            });
        };
        run_choco_in_container(pkg, toolchain, executor).await?;
        true
    };

    // Finalize exactly like MinGit: scratch cleared, relocate, manifest written,
    // then `.ready` stamped LAST.
    let _ = tokio::fs::remove_dir_all(&scratch).await;
    let path_dirs = probe_windows_path_dirs(toolchain).await;
    let report = finalize_windows_toolchain(
        toolchain,
        &pkg.tool,
        &pkg.version,
        path_dirs,
        pkg.nupkg_url.clone(),
        pkg.verified_sha256.clone(),
    )
    .await?;
    Ok(if net_fallback {
        WinBuildKind::NetFallback(report)
    } else {
        WinBuildKind::Hermetic(report)
    })
}

/// `true` when an [`InstallStep::Unsupported`] construct is one of
/// [`crate::recipe_choco`]'s weak-checksum markers (`no checksum for <url>` /
/// `checksumType <t>` / `checksumType unknown for <url>`) rather than a real
/// inexecutable construct. Weak-checksum plans still execute leaf-side — the
/// download just proceeds unverified, loudly.
fn is_weak_checksum_marker(construct: &str) -> bool {
    construct.starts_with("no checksum for ") || construct.starts_with("checksumType ")
}

/// `true` when every step of the plan is leaf-executable fetch + unzip
/// ([`InstallStep::StageResource`] / [`InstallStep::PrefixInstall`] /
/// [`InstallStep::BinInstall`], plus informational weak-checksum markers).
/// Anything else (exe/msi installers, opaque PowerShell) routes to the
/// containerized choco path — bias to the container, never a wrong binary.
fn plan_is_leaf_executable(plan: &InstallPlan) -> bool {
    plan.steps.iter().all(|step| match step {
        InstallStep::StageResource { .. }
        | InstallStep::PrefixInstall { .. }
        | InstallStep::BinInstall { .. } => true,
        InstallStep::Unsupported { construct } => is_weak_checksum_marker(construct),
        _ => false,
    })
}

/// Execute a leaf-executable choco plan: download every resource
/// (sha256-verified when the ps1 embedded a digest; unverified-with-warning
/// for the weak-checksum case), then apply the staged steps into the prefix.
async fn execute_choco_plan_leaf(tool: &str, plan: &InstallPlan, toolchain: &Path) -> Result<()> {
    let resources_dir = toolchain.join(".build").join("resources");
    let mut staged: HashMap<String, PathBuf> = HashMap::new();
    for res in &plan.resources {
        let file = res
            .url
            .rsplit('/')
            .next()
            .filter(|s| !s.is_empty())
            .unwrap_or("resource.bin");
        let dest = resources_dir.join(&res.name).join(file);
        if res.sha256.trim().is_empty() {
            // The weak-checksum case recipe_choco documents: the ps1 carried no
            // usable sha256, so this download is UNVERIFIED. Proceed, loudly.
            tracing::warn!(
                tool,
                resource = %res.name,
                url = %res.url,
                "choco resource declares no sha256; downloading UNVERIFIED (weak checksum)"
            );
            crate::package_index::download_verified(&res.url, &dest, None).await?;
        } else {
            crate::package_index::download_verified(&res.url, &dest, Some(&res.sha256)).await?;
        }
        staged.insert(res.name.clone(), dest);
    }
    apply_choco_steps(plan, &staged, toolchain).await
}

/// Apply the steps of a leaf-executable choco plan against the prefix,
/// mirroring how [`crate::recipe_choco`] models the choco cmdlets:
///
/// - `Install-ChocolateyZipPackage` parses to a [`InstallStep::StageResource`]
///   plus an immediate `PrefixInstall { from: ".", to: None }` — the pair
///   means "extract the downloaded zip into the tools dir (our prefix)".
/// - `Get-ChocolateyWebFile` parses to a lone `StageResource` — the raw file
///   lands in the tools dir named after the package (the parser does not
///   retain `FileFullPath`, and the dominant idiom is
///   `Join-Path $toolsDir "$packageName.exe"`).
/// - `Install-BinFile` parses to a [`InstallStep::BinInstall`] — copy the
///   prefix-relative source into `<prefix>/bin`, optionally renamed.
async fn apply_choco_steps(
    plan: &InstallPlan,
    staged: &HashMap<String, PathBuf>,
    toolchain: &Path,
) -> Result<()> {
    let mut i = 0usize;
    while i < plan.steps.len() {
        match &plan.steps[i] {
            InstallStep::StageResource { name, dir } => {
                let src = staged
                    .get(name)
                    .ok_or_else(|| ToolchainError::RegistryError {
                        message: format!("choco plan stages undeclared resource '{name}'"),
                    })?;
                let dest_dir = dir
                    .as_deref()
                    .map_or_else(|| toolchain.to_path_buf(), |d| toolchain.join(d));
                let paired_extract = matches!(
                    plan.steps.get(i + 1),
                    Some(InstallStep::PrefixInstall { from, to: None }) if from == "."
                );
                if paired_extract {
                    extract_resource_zip(src, &dest_dir).await?;
                    i += 1; // the PrefixInstall is consumed by the extraction
                } else {
                    stage_web_file(name, src, &dest_dir).await?;
                }
            }
            InstallStep::BinInstall { from, to } => {
                apply_bin_install(toolchain, from, to.as_deref()).await?;
            }
            InstallStep::Unsupported { construct } if is_weak_checksum_marker(construct) => {
                // Informational only — the unverified download already warned.
            }
            other => {
                // Unreachable behind `plan_is_leaf_executable`, but never
                // guess: a step this executor does not model is an error.
                return Err(ToolchainError::RegistryError {
                    message: format!("choco plan step is not leaf-executable: {other:?}"),
                });
            }
        }
        i += 1;
    }
    Ok(())
}

/// Extract a staged zip resource into `dest_dir` (the prefix or a subdir).
async fn extract_resource_zip(src: &Path, dest_dir: &Path) -> Result<()> {
    let bytes = tokio::fs::read(src).await?;
    let dest = dest_dir.to_path_buf();
    tokio::task::spawn_blocking(move || extract_zip_to(&bytes, &dest))
        .await
        .map_err(|e| ToolchainError::RegistryError {
            message: format!("choco resource extraction task panicked: {e}"),
        })?
}

/// Land a raw (non-archive) web-file resource in `dest_dir` as
/// `<resource-name>.<source-extension>` — e.g. resource `jq` downloaded from
/// `.../jq-windows-amd64.exe` lands as `jq.exe`, matching choco's
/// `$toolsDir\$packageName.exe` idiom (never the mangled URL basename).
async fn stage_web_file(name: &str, src: &Path, dest_dir: &Path) -> Result<()> {
    let file_name = src
        .extension()
        .and_then(|e| e.to_str())
        .map_or_else(|| name.to_string(), |ext| format!("{name}.{ext}"));
    tokio::fs::create_dir_all(dest_dir).await?;
    tokio::fs::copy(src, dest_dir.join(file_name)).await?;
    Ok(())
}

/// `Install-BinFile` semantics: copy the prefix-relative `from` into
/// `<prefix>/bin/<to-or-basename>`. A rename without an extension carries the
/// source's extension so the landed binary stays runnable (`jq` → `jq.exe`).
async fn apply_bin_install(toolchain: &Path, from: &str, to: Option<&str>) -> Result<()> {
    let src = toolchain.join(from);
    let src_name = src
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or(from)
        .to_string();
    let mut dest_name = to.map_or_else(|| src_name.clone(), str::to_string);
    if !dest_name.contains('.') {
        if let Some(ext) = Path::new(&src_name).extension().and_then(|e| e.to_str()) {
            dest_name.push('.');
            dest_name.push_str(ext);
        }
    }
    let bin = toolchain.join("bin");
    tokio::fs::create_dir_all(&bin).await?;
    tokio::fs::copy(&src, bin.join(&dest_name))
        .await
        .map_err(|e| ToolchainError::RegistryError {
            message: format!("Install-BinFile source '{from}' could not be staged: {e}"),
        })?;
    Ok(())
}

/// Run `choco install <tool>` inside a network-enabled Windows container.
///
/// `choco` exists inside the runtime's choco-capable Windows base container —
/// this request depends on that image; the runtime executor (the agent's HCS
/// implementation) owns materializing it, and capture semantics (installed
/// payload → `prefix`) are runtime-side too.
async fn run_choco_in_container(
    pkg: &ChocoPkg,
    toolchain: &Path,
    executor: &dyn ContainerBuildExecutor,
) -> Result<()> {
    let req = choco_container_request(&pkg.tool, &pkg.version, toolchain);
    tracing::warn!(
        tool = %pkg.tool,
        version = %pkg.version,
        "NET-FALLBACK: choco plan is not leaf-executable (exe/msi installer); \
         running `choco install` in a network-enabled Windows container"
    );
    let report = executor.execute(&req).await?;
    tracing::warn!(
        tool = %pkg.tool,
        log_tail = %report.log_tail,
        "NET-FALLBACK: containerized choco install completed"
    );
    Ok(())
}

/// Assemble the containerized-choco [`ContainerBuildRequest`]: a single
/// `choco install` [`InstallStep::System`] step, Windows platform, network
/// allowed loudly (choco fetches its own installers), scratch at
/// `<prefix>/.build`.
fn choco_container_request(tool: &str, version: &str, toolchain: &Path) -> ContainerBuildRequest {
    let scratch = toolchain.join(".build");
    let argv = [
        "choco",
        "install",
        tool,
        "-y",
        "--no-progress",
        "--version",
        version,
    ]
    .iter()
    .map(ToString::to_string)
    .collect();
    ContainerBuildRequest {
        tool: tool.to_string(),
        platform: crate::ToolPlatform::Windows,
        plan: InstallPlan {
            steps: vec![InstallStep::System { argv }],
            resources: Vec::new(),
            patches: Vec::new(),
            env: HashMap::new(),
            deparallelize: false,
        },
        // No source tree for a choco install — the step runs in scratch.
        src_dir: scratch.clone(),
        prefix: toolchain.to_path_buf(),
        scratch_dir: scratch,
        dep_toolchains: Vec::new(),
        resources_dir: None,
        env: HashMap::new(),
        path_prefix: Vec::new(),
        net: NetPolicy::AllowLoud,
    }
}

/// Probe the provisioned layout for `PATH` directories: the toolchain root,
/// `bin/`, and `tools/` qualify when they directly contain a Windows
/// executable (`.exe` / `.bat` / `.cmd`).
async fn probe_windows_path_dirs(toolchain: &Path) -> Vec<String> {
    let mut dirs = Vec::new();
    for candidate in [
        toolchain.to_path_buf(),
        toolchain.join("bin"),
        toolchain.join("tools"),
    ] {
        if dir_has_windows_executable(&candidate).await {
            dirs.push(candidate.display().to_string());
        }
    }
    dirs
}

/// `true` when `dir` directly contains a `.exe` / `.bat` / `.cmd` entry.
async fn dir_has_windows_executable(dir: &Path) -> bool {
    let Ok(mut entries) = tokio::fs::read_dir(dir).await else {
        return false;
    };
    while let Ok(Some(entry)) = entries.next_entry().await {
        if let Some(name) = entry.file_name().to_str() {
            let is_executable = Path::new(name)
                .extension()
                .and_then(|e| e.to_str())
                .is_some_and(|ext| {
                    ["exe", "bat", "cmd"]
                        .iter()
                        .any(|want| ext.eq_ignore_ascii_case(want))
                });
            if is_executable {
                return true;
            }
        }
    }
    false
}

/// Finish a populated Windows toolchain the single canonical way (shared by
/// the MinGit and choco paths):
///
/// 1. [`make_relocatable`](crate::relocate::make_relocatable) the tree in place
///    (built prefix = the toolchain dir; no build deps). Windows toolchains hold
///    PE binaries, never Mach-O, so this invokes NO host tools — it only
///    residue-scans + text-placeholders — and returns the [`RelocationReport`]
///    the publish step consumes.
/// 2. write the [`ToolchainManifest`] (`platform: "windows"`, `source: Prebuilt`)
///    AFTER relocation (so its absolute `path_dirs` are not placeholdered), then
///    stamp `.ready` LAST.
async fn finalize_windows_toolchain(
    toolchain: &Path,
    tool: &str,
    version: &str,
    path_dirs: Vec<String>,
    url: String,
    sha256: String,
) -> Result<RelocationReport> {
    let report = crate::relocate::make_relocatable(toolchain, toolchain, &[]).await?;
    let manifest = ToolchainManifest {
        tool: tool.to_string(),
        version: version.to_string(),
        arch: windows_arch_token().to_string(),
        platform: "windows".to_string(),
        path_dirs,
        env: HashMap::new(),
        source: ToolchainSource::Prebuilt { url, sha256 },
        build_deps: Vec::new(),
        provisioned_at: chrono::Utc::now().to_rfc3339(),
    };
    manifest.write_to_toolchain(toolchain).await?;
    tokio::fs::write(toolchain.join(".ready"), b"").await?;
    Ok(report)
}

// ---------------------------------------------------------------------------
// MinGit (the `git` fast path)
// ---------------------------------------------------------------------------

/// A single asset attached to a GitHub release.
#[derive(Debug, Clone, Deserialize)]
struct GhAsset {
    name: String,
    #[serde(default)]
    browser_download_url: String,
}

/// The subset of the GitHub release JSON we consume.
#[derive(Debug, Clone, Deserialize)]
struct GhRelease {
    #[serde(default)]
    tag_name: String,
    #[serde(default)]
    assets: Vec<GhAsset>,
}

/// Resolve `<ver>` from a Git for Windows tag (`v2.55.0.windows.1` → `2.55.0`).
fn mingit_version_from_tag(tag: &str) -> String {
    tag.trim_start_matches('v')
        .split(".windows")
        .next()
        .unwrap_or(tag)
        .to_string()
}

/// The MinGit asset file name for `version` + `arch`.
///
/// Git for Windows names them `MinGit-<ver>-64-bit.zip` (x86_64) and
/// `MinGit-<ver>-arm64.zip` (arm64). The plain (non-`busybox`) variant is the
/// full MinGit with the real coreutils.
fn mingit_asset_name(version: &str, arch: &str) -> String {
    let suffix = if arch == "arm64" { "arm64" } else { "64-bit" };
    format!("MinGit-{version}-{suffix}.zip")
}

/// Pick the right MinGit asset from a release's assets for `arch`, preferring
/// the plain (non-`busybox`, non-`32-bit`) build. Returns the download URL.
fn pick_mingit_asset<'a>(assets: &'a [GhAsset], version: &str, arch: &str) -> Option<&'a GhAsset> {
    let want = mingit_asset_name(version, arch);
    assets
        .iter()
        .find(|a| a.name == want && !a.browser_download_url.is_empty())
}

/// Construct the canonical MinGit download URL for a `(tag, version, arch)` —
/// the offline fallback when the release API can't be queried.
fn mingit_download_url(tag: &str, version: &str, arch: &str) -> String {
    format!(
        "https://github.com/git-for-windows/git/releases/download/{tag}/{}",
        mingit_asset_name(version, arch)
    )
}

/// Resolve the MinGit `(version, download_url)` to fetch: query the live release
/// API, falling back to the canonical URL for the pinned fallback version when
/// the API is unreachable.
async fn resolve_mingit(arch: &str) -> (String, String, Option<String>) {
    match fetch_latest_release().await {
        Ok(rel) => {
            let version = mingit_version_from_tag(&rel.tag_name);
            if let Some(asset) = pick_mingit_asset(&rel.assets, &version, arch) {
                // Git for Windows sometimes ships a sibling `<asset>.sha256`.
                let sha = mingit_sibling_sha256(&rel.assets, &asset.name).await;
                return (version, asset.browser_download_url.clone(), sha);
            }
            // API reachable but the expected asset name wasn't found — construct
            // the canonical URL for the resolved tag/version.
            let url = mingit_download_url(&rel.tag_name, &version, arch);
            (version, url, None)
        }
        Err(_) => (
            MINGIT_FALLBACK_VERSION.to_string(),
            mingit_download_url(MINGIT_FALLBACK_TAG, MINGIT_FALLBACK_VERSION, arch),
            None,
        ),
    }
}

/// Best-effort: find a sibling `<asset>.sha256` checksum asset and return its hex
/// digest. Returns `None` when absent or unreadable (compute-on-download).
async fn mingit_sibling_sha256(assets: &[GhAsset], asset_name: &str) -> Option<String> {
    let want = format!("{asset_name}.sha256");
    let asset = assets
        .iter()
        .find(|a| a.name == want && !a.browser_download_url.is_empty())?;
    let text = reqwest::get(&asset.browser_download_url)
        .await
        .ok()?
        .text()
        .await
        .ok()?;
    let token = text.split_whitespace().next()?;
    (token.len() == 64 && token.chars().all(|c| c.is_ascii_hexdigit()))
        .then(|| token.to_ascii_lowercase())
}

/// Fetch + parse the latest `git-for-windows/git` release. GitHub requires a
/// `User-Agent`; we parse from text so no extra reqwest feature is needed.
async fn fetch_latest_release() -> Result<GhRelease> {
    let client = reqwest::Client::builder()
        .user_agent("zlayer-toolchain")
        .build()
        .map_err(|e| ToolchainError::RegistryError {
            message: format!("failed to build HTTP client: {e}"),
        })?;
    let text = client
        .get(GIT_FOR_WINDOWS_LATEST)
        .send()
        .await
        .map_err(|e| ToolchainError::RegistryError {
            message: format!("failed to query git-for-windows releases: {e}"),
        })?
        .text()
        .await
        .map_err(|e| ToolchainError::RegistryError {
            message: format!("failed to read git-for-windows release body: {e}"),
        })?;
    serde_json::from_str(&text).map_err(|e| ToolchainError::RegistryError {
        message: format!("failed to parse git-for-windows release JSON: {e}"),
    })
}

/// Provision the `git` toolchain from MinGit (a relocatable portable zip).
///
/// Idempotent via the `<toolchain>/.ready` marker written last. Extracts MinGit into
/// `<cache>/git-<ver>-<arch>/` and writes a [`ToolchainManifest`] whose `path_dirs`
/// are the in-toolchain MinGit binary directories (`cmd`, `mingw64\bin`, `usr\bin`).
///
/// # Errors
///
/// Propagates download/extraction failures.
pub async fn ensure_mingit(
    cache_dir: &Path,
    lockfile: Option<&crate::ToolchainLockfile>,
) -> Result<PathBuf> {
    let arch = windows_arch_token();

    // A lock hit pins the exact version + URL + digest (consume-only).
    let (version, url, expected_sha) = match lockfile.and_then(|l| {
        use crate::ToolchainLockfileExt;
        l.lookup("git", "windows", arch)
    }) {
        Some(locked) => (
            locked.version.clone(),
            locked.url.clone(),
            Some(locked.sha256.clone()),
        ),
        None => resolve_mingit(arch).await,
    };

    let toolchain = cache_dir.join(format!("git-{version}-{arch}"));
    let ready_marker = toolchain.join(".ready");
    // Local `.ready` wins FIRST (zero network).
    if tokio::fs::try_exists(&ready_marker).await.unwrap_or(false) {
        return Ok(toolchain);
    }

    // Identity known (version resolved) → pull-first, best-effort.
    let id = ToolchainArtifactId {
        tool: "git".to_string(),
        version: version.clone(),
        os: WINDOWS_OS_TOKEN.to_string(),
        arch: arch.to_string(),
    };
    if crate::pull_first(&id, &toolchain).await?.is_some() {
        return Ok(toolchain);
    }

    // Miss → extract fresh, then record coverage + publish (MinGit is always a
    // hermetic leaf extract — no net fallback).
    match install_mingit_fresh(&toolchain, &version, &url, expected_sha.as_deref()).await {
        Ok(report) => {
            crate::finish_built(&id, &toolchain, Some(&report), false).await;
            Ok(toolchain)
        }
        Err(e) => {
            crate::record_failed(&id, &e).await;
            Err(e)
        }
    }
}

/// Download + extract MinGit into a freshly-cleared `toolchain` and finalize it
/// (relocate + manifest + `.ready`), returning the [`RelocationReport`]. Split
/// out of [`ensure_mingit`] so the coverage/publish wrapper stays thin and any
/// error routes to a single `record_failed`.
async fn install_mingit_fresh(
    toolchain: &Path,
    version: &str,
    url: &str,
    expected_sha: Option<&str>,
) -> Result<RelocationReport> {
    // Fresh extract — clear any partial toolchain.
    let _ = tokio::fs::remove_dir_all(toolchain).await;
    tokio::fs::create_dir_all(toolchain).await?;

    tracing::info!(url = %url, "downloading MinGit for the Windows git toolchain");
    // Stream + verify (against a lockfile/published digest when available) into a
    // temp zip inside the toolchain, recording the computed digest in the manifest.
    let zip_path = toolchain.join(".mingit.zip");
    let computed_sha =
        crate::package_index::download_verified(url, &zip_path, expected_sha).await?;
    let bytes = tokio::fs::read(&zip_path).await?;

    let toolchain_clone = toolchain.to_path_buf();
    tokio::task::spawn_blocking(move || extract_zip_to(&bytes, &toolchain_clone))
        .await
        .map_err(|e| ToolchainError::RegistryError {
            message: format!("MinGit extraction task panicked: {e}"),
        })??;
    let _ = tokio::fs::remove_file(&zip_path).await;

    // MinGit's `git.exe` lives at `cmd\git.exe`; the POSIX helpers + dlls live
    // under `mingw64\bin` and `usr\bin`. All are relocatable (resolved relative
    // to the exe), so the manifest just prepends the in-toolchain dirs to PATH.
    let path_dirs = ["cmd", "mingw64\\bin", "usr\\bin"]
        .iter()
        .map(|sub| toolchain.join(sub).display().to_string())
        .collect::<Vec<_>>();

    finalize_windows_toolchain(
        toolchain,
        "git",
        version,
        path_dirs,
        url.to_string(),
        computed_sha,
    )
    .await
}

/// Extract a zip archive (in memory) into `dest`, preserving the archive's
/// internal directory structure. Synchronous (the `zip` crate is blocking) —
/// call under `spawn_blocking`. Shared by the MinGit and choco leaf paths.
fn extract_zip_to(bytes: &[u8], dest: &Path) -> Result<()> {
    let reader = std::io::Cursor::new(bytes);
    let mut archive = zip::ZipArchive::new(reader).map_err(|e| ToolchainError::RegistryError {
        message: format!("failed to open zip archive: {e}"),
    })?;
    for i in 0..archive.len() {
        let mut file = archive
            .by_index(i)
            .map_err(|e| ToolchainError::RegistryError {
                message: format!("failed to read zip entry {i}: {e}"),
            })?;
        // `enclosed_name` returns an owned `PathBuf` sanitized against path
        // traversal (`None` = the entry name escaped the archive root); it holds
        // no borrow on `file`, so the later `&mut file` for the copy is free.
        let Some(rel) = file.enclosed_name() else {
            continue; // skip unsafe (path-traversal) entries
        };
        let out_path = dest.join(&rel);
        if file.is_dir() {
            std::fs::create_dir_all(&out_path)?;
            continue;
        }
        if let Some(parent) = out_path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        let mut out = std::fs::File::create(&out_path)?;
        std::io::copy(&mut file, &mut out)?;
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::executor::ContainerBuildReport;
    use crate::{LockedTool, ToolchainLockfile, ToolchainLockfileExt};

    // -- shared fixture helpers ------------------------------------------------

    /// Build a tiny in-memory zip from `(name, bytes)` entries.
    fn build_zip(files: &[(&str, &[u8])]) -> Vec<u8> {
        use std::io::Write;
        let mut buf = Vec::new();
        {
            let mut zw = zip::ZipWriter::new(std::io::Cursor::new(&mut buf));
            let opts = zip::write::SimpleFileOptions::default();
            for (name, content) in files {
                zw.start_file(*name, opts).unwrap();
                zw.write_all(content).unwrap();
            }
            zw.finish().unwrap();
        }
        buf
    }

    /// Minimal-but-realistic nuspec XML for `id`/`version` (mirrors the
    /// `recipe_choco` test fixture).
    fn nuspec_xml(id: &str, version: &str) -> String {
        format!(
            r#"<?xml version="1.0" encoding="utf-8"?>
<package xmlns="http://schemas.microsoft.com/packaging/2011/08/nuspec.xsd">
  <metadata>
    <id>{id}</id>
    <version>{version}</version>
    <authors>test</authors>
  </metadata>
</package>"#
        )
    }

    /// Build an in-memory `.nupkg` (nuspec + install ps1) for `id`/`version`.
    fn build_nupkg(id: &str, version: &str, ps1: &str) -> Vec<u8> {
        let nuspec = nuspec_xml(id, version);
        build_zip(&[
            (&format!("{id}.nuspec"), nuspec.as_bytes()),
            ("tools/chocolateyInstall.ps1", ps1.as_bytes()),
        ])
    }

    /// sha256 (bare lowercase hex) of `bytes`.
    fn sha256_hex(bytes: &[u8]) -> String {
        use sha2::{Digest, Sha256};
        hex::encode(Sha256::digest(bytes))
    }

    /// Serve `bytes` over a loopback HTTP listener (every request gets the
    /// same 200 body). Returns the URL of `/{name}`. The accept loop lives on
    /// a detached task for the test's lifetime.
    async fn serve_bytes(bytes: Vec<u8>, name: &str) -> String {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(async move {
            loop {
                let Ok((mut sock, _)) = listener.accept().await else {
                    break;
                };
                let body = bytes.clone();
                tokio::spawn(async move {
                    use tokio::io::{AsyncReadExt, AsyncWriteExt};
                    let mut buf = [0u8; 2048];
                    let _ = sock.read(&mut buf).await; // consume the request head
                    let head = format!(
                        "HTTP/1.1 200 OK\r\ncontent-length: {}\r\nconnection: close\r\n\r\n",
                        body.len()
                    );
                    let _ = sock.write_all(head.as_bytes()).await;
                    let _ = sock.write_all(&body).await;
                    let _ = sock.shutdown().await;
                });
            }
        });
        format!("http://{addr}/{name}")
    }

    /// A [`ChocoPkg`] identity for fixture installs.
    fn pkg(tool: &str, version: &str) -> ChocoPkg {
        ChocoPkg {
            tool: tool.to_string(),
            version: version.to_string(),
            nupkg_url: format!("https://example/{tool}.{version}.nupkg"),
            verified_sha256: String::new(),
        }
    }

    /// Local mock executor passed DIRECTLY as `&dyn` (never through the
    /// process-global slot — that slot belongs to `executor.rs`'s single
    /// sequential test). Captures the request it served.
    struct CapturingExecutor {
        seen: std::sync::Mutex<Option<ContainerBuildRequest>>,
    }

    impl ContainerBuildExecutor for CapturingExecutor {
        fn execute<'a>(
            &'a self,
            req: &'a ContainerBuildRequest,
        ) -> std::pin::Pin<
            Box<dyn std::future::Future<Output = Result<ContainerBuildReport>> + Send + 'a>,
        > {
            Box::pin(async move {
                *self.seen.lock().unwrap() = Some(req.clone());
                Ok(ContainerBuildReport {
                    log_tail: "choco install ok".to_string(),
                })
            })
        }
    }

    // -- MinGit resolver (unchanged behavior) -----------------------------------

    #[test]
    fn version_parsed_from_tag() {
        assert_eq!(mingit_version_from_tag("v2.55.0.windows.1"), "2.55.0");
        assert_eq!(mingit_version_from_tag("v2.43.2.windows.2"), "2.43.2");
        assert_eq!(mingit_version_from_tag("2.40.0"), "2.40.0");
    }

    #[test]
    fn asset_name_per_arch() {
        assert_eq!(
            mingit_asset_name("2.55.0", "x86_64"),
            "MinGit-2.55.0-64-bit.zip"
        );
        assert_eq!(
            mingit_asset_name("2.55.0", "arm64"),
            "MinGit-2.55.0-arm64.zip"
        );
    }

    #[test]
    fn download_url_is_canonical() {
        let url = mingit_download_url("v2.55.0.windows.1", "2.55.0", "x86_64");
        assert_eq!(
            url,
            "https://github.com/git-for-windows/git/releases/download/\
             v2.55.0.windows.1/MinGit-2.55.0-64-bit.zip"
        );
    }

    #[test]
    fn picks_plain_mingit_not_busybox_or_32bit() {
        let assets = vec![
            GhAsset {
                name: "MinGit-2.55.0-32-bit.zip".to_string(),
                browser_download_url: "https://x/32".to_string(),
            },
            GhAsset {
                name: "MinGit-2.55.0-busybox-64-bit.zip".to_string(),
                browser_download_url: "https://x/bb".to_string(),
            },
            GhAsset {
                name: "MinGit-2.55.0-64-bit.zip".to_string(),
                browser_download_url: "https://x/64".to_string(),
            },
            GhAsset {
                name: "MinGit-2.55.0-arm64.zip".to_string(),
                browser_download_url: "https://x/arm".to_string(),
            },
        ];
        assert_eq!(
            pick_mingit_asset(&assets, "2.55.0", "x86_64")
                .unwrap()
                .browser_download_url,
            "https://x/64"
        );
        assert_eq!(
            pick_mingit_asset(&assets, "2.55.0", "arm64")
                .unwrap()
                .browser_download_url,
            "https://x/arm"
        );
    }

    #[test]
    fn pick_returns_none_when_asset_missing() {
        let assets = vec![GhAsset {
            name: "MinGit-2.55.0-32-bit.zip".to_string(),
            browser_download_url: "https://x/32".to_string(),
        }];
        assert!(pick_mingit_asset(&assets, "2.55.0", "x86_64").is_none());
    }

    #[test]
    fn release_json_parses() {
        let json = r#"{
            "tag_name": "v2.55.0.windows.1",
            "assets": [
                {"name": "MinGit-2.55.0-64-bit.zip", "browser_download_url": "https://x/64"}
            ]
        }"#;
        let rel: GhRelease = serde_json::from_str(json).unwrap();
        assert_eq!(mingit_version_from_tag(&rel.tag_name), "2.55.0");
        assert_eq!(rel.assets.len(), 1);
    }

    #[tokio::test]
    async fn extract_zip_roundtrips_nested_layout() {
        // Build a tiny in-memory zip mirroring MinGit's nested layout, extract
        // it, and assert the tree (and a file's bytes) materialize correctly.
        let buf = build_zip(&[
            ("cmd/git.exe", b"MZ-fake-exe"),
            ("mingw64/bin/git.exe", b"MZ-fake-exe-2"),
        ]);
        let tmp = tempfile::tempdir().unwrap();
        extract_zip_to(&buf, tmp.path()).unwrap();
        assert!(tmp.path().join("cmd/git.exe").is_file());
        assert!(tmp.path().join("mingw64/bin/git.exe").is_file());
        assert_eq!(
            std::fs::read(tmp.path().join("cmd/git.exe")).unwrap(),
            b"MZ-fake-exe"
        );
    }

    // -- choco chain: leaf execution ---------------------------------------------

    /// A fully-supported zip-package plan (the terraform-style splat idiom)
    /// executes LEAF-SIDE: resource verified + extracted into the prefix,
    /// manifest written in the MinGit shape, scratch cleaned, `.ready` LAST.
    #[tokio::test]
    async fn supported_choco_zip_plan_installs_leaf_side() {
        let payload = build_zip(&[("sample.exe", b"MZ-sample")]);
        let sha = sha256_hex(&payload);
        let url = serve_bytes(payload, "sample-1.0.0.zip").await;
        let ps1 = format!(
            "$toolsDir = \"$(Split-Path -Parent $MyInvocation.MyCommand.Definition)\"\n\
             Install-ChocolateyZipPackage -PackageName 'sample' -Url64bit '{url}' \
             -Checksum64 '{sha}' -ChecksumType64 'sha256' -UnzipLocation $toolsDir\n"
        );
        let tmp = tempfile::tempdir().unwrap();
        let toolchain = tmp
            .path()
            .join(format!("sample-1.0.0-{}", windows_arch_token()));
        tokio::fs::create_dir_all(&toolchain).await.unwrap();

        let nupkg = build_nupkg("sample", "1.0.0", &ps1);
        let recipe = crate::recipe_choco::parse_nupkg(&nupkg, &toolchain).unwrap();
        assert!(recipe.plan.is_fully_supported());
        assert!(plan_is_leaf_executable(&recipe.plan));

        let pkg = pkg("sample", "1.0.0");
        install_from_choco_recipe(&pkg, recipe.plan, &toolchain, None)
            .await
            .expect("leaf-executable plan must install without an executor");

        assert_eq!(
            tokio::fs::read(toolchain.join("sample.exe")).await.unwrap(),
            b"MZ-sample"
        );
        assert!(toolchain.join(".ready").is_file(), ".ready stamped last");
        assert!(!toolchain.join(".build").exists(), "scratch cleaned");

        let manifest = ToolchainManifest::read_from_toolchain(&toolchain)
            .await
            .unwrap()
            .expect("manifest written before .ready");
        assert_eq!(manifest.tool, "sample");
        assert_eq!(manifest.version, "1.0.0");
        assert_eq!(manifest.arch, windows_arch_token());
        assert_eq!(manifest.platform, "windows");
        assert_eq!(
            manifest.path_dirs,
            vec![toolchain.display().to_string()],
            "the prefix root holds sample.exe, so it is the probed PATH dir"
        );
        assert_eq!(
            manifest.source,
            ToolchainSource::Prebuilt {
                url: pkg.nupkg_url.clone(),
                sha256: String::new(),
            },
            "unverified nupkg records an EMPTY sha (payload was ps1-verified)"
        );
    }

    /// The weak-checksum case (md5 checksumType → empty sha256 + marker):
    /// still leaf-executable — the download proceeds UNVERIFIED (with a warn)
    /// and the install lands.
    #[tokio::test]
    async fn weak_checksum_choco_plan_warns_but_installs() {
        let payload = build_zip(&[("tool.exe", b"MZ-weak")]);
        let url = serve_bytes(payload, "weak-1.0.0.zip").await;
        let ps1 = format!(
            "Install-ChocolateyZipPackage -PackageName 'weak' -Url '{url}' \
             -Checksum 'd41d8cd98f00b204e9800998ecf8427e' -ChecksumType 'md5' \
             -UnzipLocation \"$(Split-Path -Parent $MyInvocation.MyCommand.Definition)\"\n"
        );
        let tmp = tempfile::tempdir().unwrap();
        let toolchain = tmp
            .path()
            .join(format!("weak-1.0.0-{}", windows_arch_token()));
        tokio::fs::create_dir_all(&toolchain).await.unwrap();

        let nupkg = build_nupkg("weak", "1.0.0", &ps1);
        let recipe = crate::recipe_choco::parse_nupkg(&nupkg, &toolchain).unwrap();
        assert!(
            !recipe.plan.is_fully_supported(),
            "weak checksum surfaces a marker"
        );
        assert!(
            plan_is_leaf_executable(&recipe.plan),
            "weak-checksum markers do NOT route to the container"
        );
        assert!(recipe.plan.resources[0].sha256.is_empty());

        install_from_choco_recipe(&pkg("weak", "1.0.0"), recipe.plan, &toolchain, None)
            .await
            .expect("weak-checksum plan proceeds unverified");
        assert_eq!(
            tokio::fs::read(toolchain.join("tool.exe")).await.unwrap(),
            b"MZ-weak"
        );
        assert!(toolchain.join(".ready").is_file());
    }

    /// A lone web-file stage lands the raw file in the prefix named after the
    /// package (never the mangled URL basename), and `Install-BinFile` copies
    /// it into `<prefix>/bin` carrying the extension.
    #[tokio::test]
    async fn web_file_and_bin_install_stage_into_prefix() {
        let body = b"MZ-jq-fake".to_vec();
        let sha = sha256_hex(&body);
        let url = serve_bytes(body, "jq-windows-amd64.exe").await;
        let tmp = tempfile::tempdir().unwrap();
        let toolchain = tmp
            .path()
            .join(format!("jq-1.8.1-{}", windows_arch_token()));
        tokio::fs::create_dir_all(&toolchain).await.unwrap();
        let prefix = toolchain.display().to_string();
        let ps1 = format!(
            "Get-ChocolateyWebFile -PackageName 'jq' -FileFullPath '{prefix}\\jq.exe' \
             -Url64bit '{url}' -Checksum64 '{sha}' -ChecksumType64 'sha256'\n\
             Install-BinFile -Name 'jq' -Path '{prefix}/jq.exe'\n"
        );

        let nupkg = build_nupkg("jq", "1.8.1", &ps1);
        let recipe = crate::recipe_choco::parse_nupkg(&nupkg, &toolchain).unwrap();
        assert!(plan_is_leaf_executable(&recipe.plan));

        install_from_choco_recipe(&pkg("jq", "1.8.1"), recipe.plan, &toolchain, None)
            .await
            .unwrap();

        assert_eq!(
            tokio::fs::read(toolchain.join("jq.exe")).await.unwrap(),
            b"MZ-jq-fake",
            "web file staged as <package>.exe in the prefix root"
        );
        assert_eq!(
            tokio::fs::read(toolchain.join("bin/jq.exe")).await.unwrap(),
            b"MZ-jq-fake",
            "Install-BinFile copies into <prefix>/bin carrying the extension"
        );
        let manifest = ToolchainManifest::read_from_toolchain(&toolchain)
            .await
            .unwrap()
            .unwrap();
        assert_eq!(
            manifest.path_dirs,
            vec![
                toolchain.display().to_string(),
                toolchain.join("bin").display().to_string(),
            ],
            "both the prefix root and bin/ carry executables"
        );
    }

    // -- choco chain: container fallback ------------------------------------------

    /// An exe-installer plan (not leaf-executable) WITHOUT a registered
    /// executor fails with `ExecutorUnavailable` — no network, no `.ready`.
    #[tokio::test]
    async fn exe_installer_without_executor_is_executor_unavailable() {
        let ps1 = "$packageArgs = @{\n\
                     packageName = 'sample'\n\
                     fileType    = 'exe'\n\
                     url         = 'https://example.com/sample-setup.exe'\n\
                     silentArgs  = '/S'\n\
                   }\n\
                   Install-ChocolateyPackage @packageArgs\n";
        let tmp = tempfile::tempdir().unwrap();
        let toolchain = tmp
            .path()
            .join(format!("sample-1.0.0-{}", windows_arch_token()));
        tokio::fs::create_dir_all(&toolchain).await.unwrap();

        let nupkg = build_nupkg("sample", "1.0.0", ps1);
        let recipe = crate::recipe_choco::parse_nupkg(&nupkg, &toolchain).unwrap();
        assert!(!plan_is_leaf_executable(&recipe.plan));

        let err = install_from_choco_recipe(&pkg("sample", "1.0.0"), recipe.plan, &toolchain, None)
            .await
            .unwrap_err();
        assert!(
            matches!(err, ToolchainError::ExecutorUnavailable { ref tool } if tool == "sample"),
            "{err}"
        );
        assert!(
            !toolchain.join(".ready").exists(),
            "no .ready without an install"
        );
    }

    /// With a (mock) executor, the exe-installer plan becomes ONE containerized
    /// `choco install` request: Windows platform, `AllowLoud` network, the choco
    /// argv, prefix/scratch wired — and finalization writes the manifest with
    /// the nupkg identity URL + empty sha, then `.ready`.
    #[tokio::test]
    async fn exe_installer_with_executor_runs_containerized_choco() {
        let ps1 = "Install-ChocolateyPackage -PackageName 'sample' -FileType 'exe' \
                   -Url 'https://example.com/sample-setup.exe' -SilentArgs '/S'\n";
        let tmp = tempfile::tempdir().unwrap();
        let toolchain = tmp
            .path()
            .join(format!("sample-2.5.0-{}", windows_arch_token()));
        tokio::fs::create_dir_all(&toolchain).await.unwrap();

        let nupkg = build_nupkg("sample", "2.5.0", ps1);
        let recipe = crate::recipe_choco::parse_nupkg(&nupkg, &toolchain).unwrap();
        let exec = CapturingExecutor {
            seen: std::sync::Mutex::new(None),
        };
        let pkg = pkg("sample", "2.5.0");
        install_from_choco_recipe(&pkg, recipe.plan, &toolchain, Some(&exec))
            .await
            .expect("mock containerized choco install should succeed");

        let req = exec
            .seen
            .lock()
            .unwrap()
            .take()
            .expect("executor must have been invoked");
        assert_eq!(req.tool, "sample");
        assert_eq!(req.platform, crate::ToolPlatform::Windows);
        assert_eq!(
            req.net,
            NetPolicy::AllowLoud,
            "choco fetches its own installer — network allowed LOUDLY"
        );
        assert_eq!(req.prefix, toolchain);
        assert_eq!(req.scratch_dir, toolchain.join(".build"));
        assert_eq!(
            req.plan.steps,
            vec![InstallStep::System {
                argv: [
                    "choco",
                    "install",
                    "sample",
                    "-y",
                    "--no-progress",
                    "--version",
                    "2.5.0",
                ]
                .iter()
                .map(ToString::to_string)
                .collect(),
            }]
        );

        let manifest = ToolchainManifest::read_from_toolchain(&toolchain)
            .await
            .unwrap()
            .expect("manifest written after the container run");
        assert_eq!(manifest.tool, "sample");
        assert_eq!(manifest.version, "2.5.0");
        assert_eq!(
            manifest.source,
            ToolchainSource::Prebuilt {
                url: pkg.nupkg_url.clone(),
                sha256: String::new(),
            },
            "container path records the choco pkg identity URL, empty sha"
        );
        assert!(toolchain.join(".ready").is_file());
    }

    // -- choco chain: lockfile pin -------------------------------------------------

    /// The lockfile pin round-trips through the FULL `ensure_windows_toolchain`
    /// chain offline: the pinned `(version, nupkg url, sha256)` is consumed
    /// (no live index resolve), the nupkg download is digest-verified, the
    /// leaf plan installs, and a second call short-circuits on `.ready`.
    #[tokio::test]
    async fn locked_choco_pin_round_trips_through_ensure() {
        let payload = build_zip(&[("pinned.exe", b"MZ-pinned")]);
        let payload_sha = sha256_hex(&payload);
        let res_url = serve_bytes(payload, "pinned-2.0.0.zip").await;
        let ps1 = format!(
            "Install-ChocolateyZipPackage -PackageName 'pinned' -Url64bit '{res_url}' \
             -Checksum64 '{payload_sha}' -ChecksumType64 'sha256' \
             -UnzipLocation \"$(Split-Path -Parent $MyInvocation.MyCommand.Definition)\"\n"
        );
        let nupkg = build_nupkg("pinned", "2.0.0", &ps1);
        let nupkg_sha = sha256_hex(&nupkg);
        let nupkg_url = serve_bytes(nupkg, "pinned.2.0.0.nupkg").await;

        let mut lock = ToolchainLockfile::new();
        lock.upsert(LockedTool {
            tool: "pinned".to_string(),
            platform: "windows".to_string(),
            arch: windows_arch_token().to_string(),
            version: "2.0.0".to_string(),
            url: nupkg_url.clone(),
            sha256: nupkg_sha.clone(),
            resolved_at: "2026-07-06T00:00:00Z".to_string(),
        });

        let tmp = tempfile::tempdir().unwrap();
        let toolchain = ensure_windows_toolchain("pinned", tmp.path(), Some(&lock))
            .await
            .expect("lock-pinned choco toolchain should provision offline");
        assert_eq!(
            toolchain,
            tmp.path()
                .join(format!("pinned-2.0.0-{}", windows_arch_token())),
            "cache key uses the LOCKED version"
        );
        assert_eq!(
            tokio::fs::read(toolchain.join("pinned.exe")).await.unwrap(),
            b"MZ-pinned"
        );
        let manifest = ToolchainManifest::read_from_toolchain(&toolchain)
            .await
            .unwrap()
            .unwrap();
        assert_eq!(
            manifest.source,
            ToolchainSource::Prebuilt {
                url: nupkg_url,
                sha256: nupkg_sha,
            },
            "lock-verified nupkg records the verified digest"
        );

        // Idempotent: the second call short-circuits on `.ready`.
        let again = ensure_windows_toolchain("pinned", tmp.path(), Some(&lock))
            .await
            .unwrap();
        assert_eq!(again, toolchain);
    }

    /// A lock-pinned nupkg whose bytes do NOT match the pinned digest is
    /// rejected (`DigestMismatch`) — the pin is consume-only and enforced.
    #[tokio::test]
    async fn locked_choco_pin_rejects_digest_mismatch() {
        let nupkg = build_nupkg("evil", "1.0.0", "Write-Host hi\n");
        let nupkg_url = serve_bytes(nupkg, "evil.1.0.0.nupkg").await;

        let mut lock = ToolchainLockfile::new();
        lock.upsert(LockedTool {
            tool: "evil".to_string(),
            platform: "windows".to_string(),
            arch: windows_arch_token().to_string(),
            version: "1.0.0".to_string(),
            url: nupkg_url,
            sha256: "a".repeat(64),
            resolved_at: "2026-07-06T00:00:00Z".to_string(),
        });

        let tmp = tempfile::tempdir().unwrap();
        let err = ensure_windows_toolchain("evil", tmp.path(), Some(&lock))
            .await
            .unwrap_err();
        assert!(
            matches!(err, ToolchainError::DigestMismatch { .. }),
            "{err}"
        );
    }
}