tambo 0.5.0

Install and prove the whole AI knowledge-tool kit
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
//! The one adapter for every data-declared stack member (aegis-1i5h1j C1).
//!
//! Install fetches the member's release asset for this host and accepts it only
//! if its SHA-256 equals the digest RECORDED in the reviewed manifest; it never
//! trusts a checksum file fetched at install time. It refuses to overwrite a
//! program of the same name that is not this member (A2). Verify runs the
//! manifest's steps in a hermetic temp HOME (A3), and the manifest schema
//! requires an absent-then-present marker pair (A4).

use std::{
    env,
    ffi::OsStr,
    fs,
    path::{Component, Path, PathBuf},
    process::Command,
};

use anyhow::{bail, Context, Result};

use super::{checked, download_https, managed_bin_dir, Adapter};
use crate::members::{Kind, Manifest, Program, ANY_TARGET};
use crate::model::ToolName;

pub(super) struct ManifestAdapter(pub(super) &'static Manifest);

/// The release target triple for this host, if the manifest records one.
pub(crate) fn release_target(manifest: &Manifest) -> Result<&'static str> {
    if manifest.kind == Kind::PythonWheel {
        // One pure-Python wheel serves every host; validate() guarantees the key.
        return Ok(ANY_TARGET);
    }
    let host = match (env::consts::ARCH, env::consts::OS) {
        ("x86_64", "linux") => "x86_64-unknown-linux-gnu",
        ("aarch64", "linux") => "aarch64-unknown-linux-gnu",
        ("x86_64", "macos") => "x86_64-apple-darwin",
        ("aarch64", "macos") => "aarch64-apple-darwin",
        (arch, os) => bail!("{}: no release target for {arch}-{os}", manifest.name),
    };
    if !manifest.sha256.contains_key(host) {
        bail!(
            "{} {} has no reviewed digest for {host}; this host cannot install it",
            manifest.name,
            manifest.version
        );
    }
    Ok(host)
}

/// Where install writes `program`. HOME or CARGO_HOME is required.
fn destination(program: &str) -> Result<PathBuf> {
    Ok(managed_bin_dir()
        .context("HOME is required for a stack member")?
        .join(program))
}

/// The first executable `program` on PATH, if any.
fn on_path(program: &str) -> Option<PathBuf> {
    use std::os::unix::fs::PermissionsExt;
    env::split_paths(&env::var_os("PATH")?)
        .map(|dir| dir.join(program))
        .find(|p| {
            p.is_file()
                && p.metadata()
                    .is_ok_and(|m| m.permissions().mode() & 0o111 != 0)
        })
}

fn same_file(a: &Path, b: &Path) -> bool {
    match (a.canonicalize(), b.canonicalize()) {
        (Ok(a), Ok(b)) => a == b,
        _ => false,
    }
}

/// Does the executable at `path` identify as this member's `program`?
/// Probes run in a throwaway HOME, so reading an identity never touches the
/// user's own config or store (wu, #46).
fn identify(path: &Path, program: &Program) -> Result<()> {
    identify_via(path, program, None)
}

/// `identify`, with the probe run through `wrapper` when one is given.
fn identify_via(path: &Path, program: &Program, wrapper: Option<&Path>) -> Result<()> {
    let root = tempfile::tempdir().context("create identity probe root")?;
    let out = hermetic_command(root.path(), wrapper, path)?
        .args(&program.identity_argv)
        .output()
        .with_context(|| format!("cannot run {} to read its identity", path.display()))?;
    let text = format!(
        "{}{}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr)
    );
    if !std::iter::once(&program.identity_contains)
        .chain(&program.identity_alternatives)
        .any(|identity| text.contains(identity))
    {
        bail!(
            "a different `{}` is at {} (its identity does not contain {:?})",
            program.name,
            path.display(),
            program.identity_contains
        );
    }
    Ok(())
}

/// Refuse to replace, or to be shadowed by, a program that is not this member
/// (A2). The DESTINATION is what install overwrites, so it is checked whether
/// or not its directory is on PATH (malcolm B1, wu F2); a foreign program
/// earlier on PATH would shadow the install, so it is refused too.
fn refuse_foreign_program(manifest: &Manifest) -> Result<()> {
    for program in &manifest.programs {
        let dest = destination(&program.name)?;
        if dest.exists() {
            if let Err(error) = identify(&dest, program) {
                match orphaned_own_launcher(manifest, &dest) {
                    Some(interpreter) => eprintln!(
                        "{}: replacing {}: it is this member's own console script, and its \
                         venv interpreter {} no longer exists",
                        manifest.name,
                        dest.display(),
                        interpreter.display()
                    ),
                    None => {
                        return Err(error).with_context(|| {
                            format!("refusing to overwrite it with {}", manifest.name)
                        })
                    }
                }
            }
        }
        if let Some(found) = on_path(&program.name).filter(|p| !same_file(p, &dest)) {
            identify(&found, program).with_context(|| {
                format!(
                    "it would shadow {} installed at {}",
                    manifest.name,
                    dest.display()
                )
            })?;
        }
    }
    Ok(())
}

/// A python-wheel member's console script whose venv is gone, so it cannot run
/// to prove its identity (aegis-z1u9s0). Seen on CI: a cache restored
/// `$CARGO_HOME/bin` but not the venvs under `~/.local/share`, and the A2 guard
/// then refused to overwrite caboodle's own launcher. Ownership is proved, not
/// assumed: the script's interpreter (a `#!` line, or pip's `/bin/sh`
/// trampoline for a long path) must lie inside this member's caboodle-owned
/// venv directory and must not exist. Anything else unrunnable stays refused.
/// Returns the missing interpreter.
fn orphaned_own_launcher(manifest: &Manifest, script: &Path) -> Option<PathBuf> {
    if manifest.kind != Kind::PythonWheel {
        return None;
    }
    let owned = venv_root(manifest).ok()?.parent()?.to_path_buf();
    let text = fs::read(script).ok()?;
    let text = String::from_utf8_lossy(&text[..text.len().min(4096)]);
    let mut lines = text.lines();
    let shebang = lines.next()?.strip_prefix("#!")?.trim();
    let interpreter = if shebang == "/bin/sh" {
        // pip: '''exec' /path/to/python "$0" "$@"
        lines
            .next()?
            .strip_prefix("'''exec' ")?
            .split_whitespace()
            .next()?
            .to_string()
    } else {
        shebang.split_whitespace().next()?.to_string()
    };
    let interpreter = PathBuf::from(interpreter);
    // strip_prefix is lexical, so `<owned>/../x` would pass it: a path that is
    // not plainly inside the members dir is not provably ours (malcolm, #66).
    let plain = interpreter.is_absolute()
        && interpreter
            .components()
            .all(|c| matches!(c, Component::RootDir | Component::Normal(_)));
    let inside = plain
        && interpreter
            .strip_prefix(&owned)
            .is_ok_and(|rest| !rest.as_os_str().is_empty());
    (inside && !interpreter.exists()).then_some(interpreter)
}

/// The executable version and verify must run: the managed install when it
/// exists, otherwise the first on PATH. Either way its identity is checked,
/// so a same-named foreign program is never read back or verified as this member.
fn resolve(program: &Program) -> Result<PathBuf> {
    let dest = destination(&program.name)?;
    let path = if dest.exists() {
        dest
    } else {
        on_path(&program.name).with_context(|| format!("`{}` is not installed", program.name))?
    };
    identify(&path, program)?;
    Ok(path)
}

/// Copy `source` over `dest` via a temp file in the same directory and a
/// rename, so an interrupted install never leaves a truncated binary and a
/// running program is never written in place (malcolm N1).
fn install_atomically(source: &Path, dest: &Path) -> Result<()> {
    use std::os::unix::fs::PermissionsExt;
    let dir = dest.parent().context("destination has no directory")?;
    let staged = tempfile::NamedTempFile::new_in(dir)
        .with_context(|| format!("stage in {}", dir.display()))?;
    fs::copy(source, staged.path()).with_context(|| format!("stage {}", dest.display()))?;
    fs::set_permissions(staged.path(), fs::Permissions::from_mode(0o755))?;
    staged.as_file().sync_all()?;
    staged
        .persist(dest)
        .map_err(|e| e.error)
        .with_context(|| format!("install {}", dest.display()))?;
    Ok(())
}

pub(super) fn sha256_file(path: &Path) -> Result<String> {
    use sha2::{Digest, Sha256};
    let mut file = fs::File::open(path).with_context(|| format!("open {}", path.display()))?;
    let mut hasher = Sha256::new();
    std::io::copy(&mut file, &mut hasher)?;
    Ok(format!("{:x}", hasher.finalize()))
}

/// Download `m`'s release asset for this host, accept it only on the RECORDED
/// digest, and materialize it. Returns the scratch dir (keep it alive while the
/// programs are used) and the directory holding the programs. A python-wheel
/// member materializes into its persistent per-version venv.
pub(crate) fn stage(m: &Manifest) -> Result<(tempfile::TempDir, PathBuf)> {
    let target = release_target(m)?;
    let asset = m.asset_for(target);

    let root =
        tempfile::tempdir().with_context(|| format!("create {} download directory", m.name))?;
    let archive = root.path().join(&asset);
    download_https(
        &format!(
            "https://github.com/{}/releases/download/{}/{asset}",
            m.repo,
            m.tag()
        ),
        &archive,
    )?;
    if sha256_file(&archive)? != m.sha256[target] {
        bail!(
            "{} {} release checksum mismatch for {target}",
            m.name,
            m.version
        );
    }
    let unpack = match m.kind {
        Kind::RustRelease => root.path().join("unpack"),
        // The venv outlives the install: its console scripts point into it.
        Kind::PythonWheel => venv_root(m)?,
    };
    let unpack = materialize(m, &archive, &unpack)?;
    Ok((root, unpack))
}

/// Stage the reviewed release and run its identity, version and functional
/// contract in temporary roots. This never installs a managed program.
pub(crate) fn verify_release_member(m: &Manifest) -> Result<()> {
    if m.kind != Kind::RustRelease {
        bail!("standalone release verification supports rust-release members only");
    }
    let (_root, unpack) = stage(m)?;
    verify_staged_member(m, &unpack)
}

fn verify_staged_member(m: &Manifest, unpack: &Path) -> Result<()> {
    let resolved = m
        .programs
        .iter()
        .map(|program| {
            let path = find_program(unpack, &program.name).context("release program missing")?;
            identify(&path, program)?;
            Ok((program.name.as_str(), path))
        })
        .collect::<Result<Vec<_>>>()?;
    let first = &resolved[0].1;
    let root = tempfile::tempdir()?;
    let mut argv = vec![first.to_string_lossy().into_owned()];
    argv.extend(m.version_argv.iter().cloned());
    let output = hermetic_via(root.path(), None, &argv, None)?;
    let reported = String::from_utf8_lossy(&output.stdout);
    if !reports_version(reported.trim(), &m.version) {
        bail!("{} release reports an unexpected version", m.name);
    }
    verify_resolved(m, &resolved)
}

impl Adapter for ManifestAdapter {
    fn name(&self) -> ToolName {
        ToolName::Member(self.0.name.as_str())
    }

    fn desired_version(&self) -> String {
        format!("{} {}", self.0.name, self.0.version)
    }

    fn package_adapter(&self) -> Result<Option<Box<dyn Adapter>>> {
        let resolved = self
            .0
            .programs
            .iter()
            .map(|program| {
                let path = on_path(&program.name).with_context(|| {
                    format!("package {} requires {} on PATH", self.0.name, program.name)
                })?;
                identify(&path, program)?;
                Ok((program.name.clone(), path))
            })
            .collect::<Result<Vec<_>>>()?;
        Ok(Some(Box::new(PackageManifestAdapter {
            manifest: self.0,
            resolved,
        })))
    }

    fn install(&self) -> Result<()> {
        let m = self.0;
        refuse_foreign_program(m)?;
        let (_root, unpack) = stage(m)?;
        let bin = managed_bin_dir().context("HOME is required to install a stack member")?;
        fs::create_dir_all(&bin).with_context(|| format!("create {}", bin.display()))?;
        for program in &m.programs {
            let source = find_program(&unpack, &program.name).with_context(|| {
                format!("{} release does not contain `{}`", m.name, program.name)
            })?;
            install_atomically(&source, &bin.join(&program.name))?;
        }
        Ok(())
    }

    fn version(&self) -> Result<String> {
        let m = self.0;
        let path = resolve(&m.programs[0])?;
        let out = checked(
            path.as_os_str(),
            m.version_argv.iter().map(String::as_str),
            None,
        )?;
        let version = String::from_utf8_lossy(&out.stdout).trim().to_owned();
        if version.is_empty() {
            bail!(
                "{} {} returned no version",
                m.name,
                m.version_argv.join(" ")
            );
        }
        Ok(version)
    }

    fn is_current(&self, installed: &str) -> bool {
        reports_version(installed, &self.0.version)
    }

    fn verify(&self) -> Result<()> {
        let m = self.0;
        // Verify the member, not whatever answers to its name (B1).
        let resolved = m
            .programs
            .iter()
            .map(|p| Ok((p.name.as_str(), resolve(p)?)))
            .collect::<Result<Vec<_>>>()?;
        verify_resolved(m, &resolved)
    }
}

/// Package read-back uses the exact PATH launchers selected after delivery.
/// Keep the launcher path (rather than its canonical target) for wrappers that
/// depend on argv[0] or their installation directory.
struct PackageManifestAdapter {
    manifest: &'static Manifest,
    resolved: Vec<(String, PathBuf)>,
}

impl Adapter for PackageManifestAdapter {
    fn name(&self) -> ToolName {
        ToolName::Member(self.manifest.name.as_str())
    }
    fn desired_version(&self) -> String {
        format!("{} {}", self.manifest.name, self.manifest.version)
    }
    fn install(&self) -> Result<()> {
        bail!("package installation belongs to the package manager")
    }
    fn version(&self) -> Result<String> {
        let out = checked(
            self.resolved[0].1.as_os_str(),
            self.manifest.version_argv.iter().map(String::as_str),
            None,
        )?;
        let version = String::from_utf8_lossy(&out.stdout).trim().to_owned();
        if version.is_empty() {
            bail!("{} returned no package version", self.manifest.name);
        }
        Ok(version)
    }
    fn is_current(&self, installed: &str) -> bool {
        reports_version(installed, &self.manifest.version)
    }
    fn verify(&self) -> Result<()> {
        let resolved = self
            .resolved
            .iter()
            .map(|(name, path)| (name.as_str(), path.clone()))
            .collect::<Vec<_>>();
        verify_resolved(self.manifest, &resolved)
    }
}

/// Verify a single-program member AT `path` (the copy PATH runs), after
/// confirming `path` identifies as the member.
pub(crate) fn verify_at(m: &Manifest, path: &Path) -> Result<()> {
    let program = single_program(m)?;
    identify_member(m, path)?;
    verify_resolved(m, &[(program.name.as_str(), path.to_path_buf())])
}

/// Refuse unless the program at `path` identifies as `m`'s single program, so
/// release tracking never replaces a same-named foreign program (A2).
pub(crate) fn identify_member(m: &Manifest, path: &Path) -> Result<()> {
    identify(path, single_program(m)?)
        .with_context(|| format!("refusing to update it as {}", m.name))
}

/// The one program of a member that release tracking can update in place.
pub(crate) fn single_program(m: &Manifest) -> Result<&Program> {
    match m.programs.as_slice() {
        [only] => Ok(only),
        _ => bail!(
            "{} has {} programs; update-release tracks single-program members only",
            m.name,
            m.programs.len()
        ),
    }
}

fn verify_resolved(m: &Manifest, resolved: &[(&str, PathBuf)]) -> Result<()> {
    {
        let root =
            tempfile::tempdir().with_context(|| format!("create {} verification root", m.name))?;
        let marker = format!(
            "caboodle-{}-{}",
            m.name,
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map_or(0, |d| d.as_nanos())
        );
        for (i, step) in m.verify.iter().enumerate() {
            let mut argv: Vec<String> = step
                .argv
                .iter()
                .map(|a| a.replace("{marker}", &marker))
                .collect();
            if let Some((_, path)) = resolved.iter().find(|(name, _)| *name == argv[0]) {
                argv[0] = path.to_string_lossy().into_owned();
            }
            let stdin = step.stdin.as_ref().map(|s| s.replace("{marker}", &marker));
            let out =
                hermetic_via(root.path(), None, &argv, stdin.as_deref()).with_context(|| {
                    format!("{} verify step {} ({})", m.name, i + 1, argv.join(" "))
                })?;
            let stdout = String::from_utf8_lossy(&out.stdout);
            if let Some(absent) = &step.absent {
                let needle = absent.replace("{marker}", &marker);
                if stdout.contains(&needle) {
                    bail!("{} verify step {}: control failed, {needle:?} present before it was created", m.name, i + 1);
                }
            }
            if let Some(present) = &step.present {
                let needle = present.replace("{marker}", &marker);
                if !stdout.contains(&needle) {
                    bail!(
                        "{} verify step {}: {needle:?} not present after it was created",
                        m.name,
                        i + 1
                    );
                }
            }
        }
        Ok(())
    }
}

/// Does a version line report `version`, as a whole word (`v` optional)?
fn reports_version(line: &str, version: &str) -> bool {
    line.split_whitespace()
        .any(|word| word.trim_start_matches('v') == version)
}

/// Prove a release asset IS `manifest` before its digest is recorded (malcolm
/// S1): unpack it, and require every program to answer its identity and the
/// first to report `manifest.version`. A release that dropped its identity text
/// would otherwise bump green and then fail every fleet version/verify with a
/// foreign-program refusal that points at the wrong cause.
///
/// This EXECUTES an unreviewed release. `wrapper`, when given, is run as
/// `<wrapper> <program> <args...>` for every such execution, so the caller can
/// confine it (the unattended bump cron uses a no-network, no-home sandbox,
/// aegis-uy26l7). caboodle itself stays platform-neutral.
pub(crate) fn prove_release(
    manifest: &Manifest,
    archive: &Path,
    wrapper: Option<&Path>,
) -> Result<()> {
    let scratch = tempfile::tempdir().context("create release proof directory")?;
    let unpack = materialize(manifest, archive, &scratch.path().join("unpack"))?;
    for program in &manifest.programs {
        let path = find_program(&unpack, &program.name).with_context(|| {
            format!(
                "{} release does not contain `{}`",
                manifest.name, program.name
            )
        })?;
        identify_via(&path, program, wrapper).with_context(|| {
            format!(
                "{} {} does not answer its manifest identity; fix identity_contains in review \
                 (it must still match the oldest installed release) before bumping",
                manifest.name, manifest.version
            )
        })?;
    }
    let first =
        find_program(&unpack, &manifest.programs[0].name).context("release program vanished")?;
    let mut argv = vec![first.to_string_lossy().into_owned()];
    argv.extend(manifest.version_argv.iter().cloned());
    let out =
        hermetic_via(scratch.path(), wrapper, &argv, None).context("read the release's version")?;
    let reported = String::from_utf8_lossy(&out.stdout).trim().to_owned();
    if !reports_version(&reported, &manifest.version) {
        bail!(
            "{} release tagged {} reports version {reported:?}; refusing to pin it",
            manifest.name,
            manifest.version
        );
    }
    Ok(())
}

/// Where a python-wheel member's venv goes: caboodle-owned and UNIQUE per
/// install (`<version>-<nanos>`), never reused. A venv cannot be moved (its
/// scripts and pyvenv.cfg hold absolute paths), so a reinstall builds beside the
/// live one and the swap is the atomic replacement of the console script. A
/// failed pip leaves the live venv, and the script pointing into it, untouched
/// (dearing, caboodle#59). Superseded venvs are left for rollback.
fn venv_root(manifest: &Manifest) -> Result<PathBuf> {
    let home = env::var_os("HOME").context("HOME is required for a python-wheel member")?;
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_or(0, |d| d.as_nanos());
    Ok(PathBuf::from(home)
        .join(".local/share/caboodle/members")
        .join(&manifest.name)
        .join(format!("{}-{nanos}", manifest.version)))
}

/// Pick an interpreter that satisfies the wheel's `Requires-Python`, BEFORE
/// anything is created. `python3` first, then versioned names newest first, so a
/// host whose `python3` is too old (macOS /usr/bin is 3.9) still works when a
/// newer one is installed, and is refused with the requirement named otherwise.
/// The wheel's METADATA is read by that interpreter's own zipfile module; a
/// specifier this check cannot evaluate is refused, never guessed.
fn select_python(archive: &Path) -> Result<String> {
    const CHECK: &str = r#"
import re, sys, zipfile
with zipfile.ZipFile(sys.argv[1]) as z:
    meta = next(n for n in z.namelist() if n.endswith(".dist-info/METADATA"))
    req = next((l.split(":", 1)[1].strip() for l in z.read(meta).decode().splitlines()
                if l.lower().startswith("requires-python:")), "")
have = sys.version_info[:3]
def ver(s):
    return tuple(int(x) for x in s.split(".")) + (0,) * (3 - len(s.split(".")))
ops = {">=": lambda a, b: a >= b, ">": lambda a, b: a > b, "<=": lambda a, b: a <= b,
       "<": lambda a, b: a < b, "==": lambda a, b: a == b, "!=": lambda a, b: a != b}
for clause in filter(None, (c.strip() for c in req.split(","))):
    m = re.fullmatch(r"(>=|<=|==|!=|>|<)\s*(\d+(?:\.\d+){0,2})", clause)
    if not m:
        print("UNEVALUABLE " + req); sys.exit(3)
    if not ops[m.group(1)](have, ver(m.group(2))):
        print("UNSATISFIED " + req); sys.exit(2)
print("OK " + req)
"#;
    let mut candidates = vec!["python3".to_owned()];
    candidates.extend((9..=14).rev().map(|minor| format!("python3.{minor}")));
    let mut requirement = String::new();
    for python in &candidates {
        let Ok(out) = Command::new(python)
            .args(["-c", CHECK])
            .arg(archive)
            .output()
        else {
            continue;
        };
        let text = String::from_utf8_lossy(&out.stdout).trim().to_owned();
        match out.status.code() {
            Some(0) => return Ok(python.clone()),
            Some(3) => bail!("cannot evaluate the wheel's Requires-Python ({text}); refusing"),
            _ => requirement = text,
        }
    }
    bail!(
        "no python on PATH satisfies the wheel's Requires-Python ({}); install one, then retry",
        requirement
            .strip_prefix("UNSATISFIED ")
            .unwrap_or("python3 not found")
    )
}

/// Turn a verified release asset into a directory holding its programs.
///
/// rust-release: unpack the tarball into `dest`. python-wheel: build a fresh
/// venv at `dest` (replacing one a previous install left) and pip-install the
/// wheel into it; the programs are its console scripts in `dest/bin`. Installing
/// a wheel runs none of its code, so the caller may still confine the first
/// EXECUTION of an unreviewed release with a probe wrapper.
fn materialize(manifest: &Manifest, archive: &Path, dest: &Path) -> Result<PathBuf> {
    match manifest.kind {
        Kind::RustRelease => {
            fs::create_dir_all(dest)?;
            checked(
                "tar",
                [
                    OsStr::new("-xzf"),
                    archive.as_os_str(),
                    OsStr::new("-C"),
                    dest.as_os_str(),
                ],
                None,
            )?;
            Ok(dest.to_path_buf())
        }
        Kind::PythonWheel => {
            // Refuse an unsatisfiable Requires-Python before creating anything.
            let python = select_python(archive)?;
            if dest.exists() {
                bail!(
                    "{} already exists; a venv is never rebuilt in place",
                    dest.display()
                );
            }
            if let Some(parent) = dest.parent() {
                fs::create_dir_all(parent)?;
            }
            let built = (|| -> Result<()> {
                checked(
                    &python,
                    [OsStr::new("-m"), OsStr::new("venv"), dest.as_os_str()],
                    None,
                )
                .with_context(|| format!("create the {} venv with {python}", manifest.name))?;
                checked(
                    dest.join("bin/python").as_os_str(),
                    [
                        OsStr::new("-m"),
                        OsStr::new("pip"),
                        OsStr::new("install"),
                        OsStr::new("--quiet"),
                        OsStr::new("--disable-pip-version-check"),
                        archive.as_os_str(),
                    ],
                    None,
                )
                .with_context(|| format!("pip install {}", manifest.name))?;
                Ok(())
            })();
            if let Err(error) = built {
                // Only the new, never-live directory is removed.
                let _ = fs::remove_dir_all(dest);
                return Err(error);
            }
            Ok(dest.join("bin"))
        }
    }
}

pub(crate) fn find_program(dir: &Path, name: &str) -> Option<std::path::PathBuf> {
    let direct = dir.join(name);
    if direct.is_file() {
        return Some(direct);
    }
    fs::read_dir(dir)
        .ok()?
        .filter_map(Result::ok)
        .find_map(|e| {
            let p = e.path();
            if p.is_dir() {
                find_program(&p, name)
            } else {
                None
            }
        })
}

/// Run one verify step in `root` with a CLEARED environment (A3): HOME and the
/// XDG dirs inside `root`, PATH and the locale passed through, nothing else. A
/// member that reads its store location from the environment would otherwise
/// write the verify marker into the user's live store (malcolm B2).
fn hermetic_via(
    root: &Path,
    wrapper: Option<&Path>,
    argv: &[String],
    stdin: Option<&str>,
) -> Result<std::process::Output> {
    use std::io::Write;
    use std::process::Stdio;
    let (program, args) = argv.split_first().context("empty verify step")?;
    let mut command = hermetic_command(root, wrapper, program)?;
    command
        .args(args)
        .stdin(if stdin.is_some() {
            Stdio::piped()
        } else {
            Stdio::null()
        })
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    let mut child = command.spawn().with_context(|| format!("run {program}"))?;
    if let Some(text) = stdin {
        // Dropped at the end of this statement, which closes the pipe (EOF).
        child
            .stdin
            .take()
            .context("stdin pipe")?
            .write_all(text.as_bytes())
            .with_context(|| format!("write stdin to {program}"))?;
    }
    let out = child
        .wait_with_output()
        .with_context(|| format!("run {program}"))?;
    if !out.status.success() {
        bail!(
            "exited {}: {}",
            out.status,
            String::from_utf8_lossy(&out.stderr).trim()
        );
    }
    Ok(out)
}

/// `program` with a CLEARED environment rooted at `root`: HOME and the XDG dirs
/// inside it, PATH and the locale passed through, nothing else.
fn hermetic_command(
    root: &Path,
    wrapper: Option<&Path>,
    program: impl AsRef<OsStr>,
) -> Result<Command> {
    let mut command = match wrapper {
        Some(wrapper) => {
            let mut c = Command::new(wrapper);
            c.arg(program);
            c
        }
        None => Command::new(program),
    };
    command.current_dir(root).env_clear();
    for var in ["PATH", "LANG", "LC_ALL", "TERM"] {
        if let Some(value) = env::var_os(var) {
            command.env(var, value);
        }
    }
    for (var, dir) in [
        ("HOME", "home"),
        ("XDG_CONFIG_HOME", "config"),
        ("XDG_DATA_HOME", "data"),
        ("XDG_STATE_HOME", "state"),
        ("XDG_CACHE_HOME", "cache"),
    ] {
        let path = root.join(dir);
        fs::create_dir_all(&path)?;
        command.env(var, path);
    }
    Ok(command)
}

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

    /// A minimal wheel whose METADATA declares `requires`.
    fn wheel(dir: &Path, requires: &str) -> PathBuf {
        let path = dir.join("demo-1.0.0-py3-none-any.whl");
        let line = if requires.is_empty() {
            String::new()
        } else {
            format!("Requires-Python: {requires}\\n")
        };
        let meta = format!("Metadata-Version: 2.1\\nName: demo\\nVersion: 1.0.0\\n{line}");
        let script = format!(
            "import sys, zipfile\nz = zipfile.ZipFile(sys.argv[1], 'w')\nz.writestr('demo-1.0.0.dist-info/METADATA', '{meta}')\nz.close()\n"
        );
        let status = Command::new("python3")
            .args(["-c", &script])
            .arg(&path)
            .status()
            .unwrap();
        assert!(status.success());
        path
    }

    #[test]
    fn a_satisfied_or_absent_requirement_selects_an_interpreter() {
        let dir = tempfile::tempdir().unwrap();
        assert!(select_python(&wheel(dir.path(), ">=3.0")).is_ok());
        let dir = tempfile::tempdir().unwrap();
        assert!(select_python(&wheel(dir.path(), "")).is_ok());
    }

    #[test]
    fn an_unsatisfiable_requirement_is_refused_and_named() {
        let dir = tempfile::tempdir().unwrap();
        let err = select_python(&wheel(dir.path(), ">=3.0,<3.1"))
            .unwrap_err()
            .to_string();
        assert!(
            err.contains("satisfies the wheel's Requires-Python (>=3.0,<3.1)"),
            "{err}"
        );
    }

    #[test]
    fn an_unevaluable_requirement_is_refused_not_guessed() {
        let dir = tempfile::tempdir().unwrap();
        let err = select_python(&wheel(dir.path(), "~=3.11"))
            .unwrap_err()
            .to_string();
        assert!(err.contains("cannot evaluate"), "{err}");
    }
}

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

    #[test]
    fn staged_member_requires_identity_version_and_functional_roundtrip() {
        let mut manifest = Manifest::parse(include_str!(
            "../../tests/fixtures/members/fixture-demo.toml"
        ))
        .unwrap();
        let root = tempfile::tempdir().unwrap();
        let archive = Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests/fixtures/releases/fixture-demo-v0.1.0-x86_64-unknown-linux-gnu.tar.gz");
        let unpack = materialize(&manifest, &archive, &root.path().join("unpack")).unwrap();
        verify_staged_member(&manifest, &unpack).unwrap();
        manifest.programs[0].identity_contains = "foreign identity".to_owned();
        assert!(verify_staged_member(&manifest, &unpack).is_err());
        manifest.programs[0].identity_contains =
            "fixture-demo is the caboodle fixture stack member".to_owned();
        manifest.version = "0.1.1".to_owned();
        assert!(verify_staged_member(&manifest, &unpack).is_err());
        manifest.version = "0.1.0".to_owned();
        manifest.verify[2].present = Some("missing-positive-control".to_owned());
        assert!(verify_staged_member(&manifest, &unpack).is_err());
    }
}

#[cfg(all(test, unix))]
mod seeds_identity_tests {
    use super::*;
    use std::os::unix::fs::PermissionsExt;

    #[test]
    fn seeds_identity_accepts_both_editions_and_refuses_foreign_sd() {
        let manifest = Manifest::parse(include_str!("../../members/seeds.toml")).unwrap();
        let program = &manifest.programs[0];
        let root = tempfile::tempdir().unwrap();
        let executable = root.path().join("sd");
        for (text, accepted) in [
            ("seeds is the beads-compatible tracker", true),
            ("seeds is the work-item tracker for the quipu stack", true),
            ("sd 1.0.0", false),
            ("sd is an intuitive find and replace CLI", false),
            ("seeds is a different program", false),
        ] {
            std::fs::write(&executable, format!("#!/bin/sh\nprintf '%s\\n' '{text}'\n")).unwrap();
            std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(0o755)).unwrap();
            assert_eq!(identify(&executable, program).is_ok(), accepted, "{text}");
        }
    }
}