leviath-package 0.1.1

Agent packaging, sharing, and installation for Leviath
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
//! Agent installation from bundle archives.

use flate2::read::GzDecoder;
use std::fs;
use std::io::Read;
use std::path::{Path, PathBuf};

/// Largest decompressed size a bundle may unpack to.
///
/// Bounds a decompression bomb: gzip reaches ratios well past 1000:1, so a
/// bundle small enough to look unremarkable could fill the disk. 256 MiB is far
/// above any real agent bundle (they are manifests, prompts, and a few `.rhai`
/// files) and far below "fills the disk".
const MAX_UNPACKED_BYTES: u64 = 256 * 1024 * 1024;

/// Refuse an unpacked bundle that contains symlinks.
///
/// tar-rs blocks entries that *extract* outside the destination, but a symlink
/// entry lands inside it perfectly legally - and then points wherever it likes.
/// Since the installed tree is later scanned for `.rhai` tool scripts and read
/// by the file tools, a link is a way to smuggle content in (or to have a later
/// write follow it out). Nothing in a legitimate agent bundle needs one.
/// What an entry is, as far as this check cares.
///
/// A three-way answer rather than a `FileType`, because `FileType` cannot be
/// constructed without a real file of that kind - and a real symlink is exactly
/// what a test cannot create on Windows without a privilege CI runners lack.
#[derive(Debug, Clone, Copy, PartialEq)]
enum Entry {
    Dir,
    File,
    /// A symlink, or an entry that could not be stat'd at all - the same
    /// refusal either way, since neither can be certified.
    Refused,
}

/// Classify a directory entry by its own metadata, not its target's.
///
/// `symlink_metadata` does not follow the link, which is the point.
fn classify(path: &Path) -> Entry {
    match fs::symlink_metadata(path).map(|m| m.file_type()).ok() {
        Some(t) if t.is_dir() => Entry::Dir,
        Some(t) if !t.is_symlink() => Entry::File,
        _ => Entry::Refused,
    }
}

/// Refuse a bundle containing any symlink, at any depth, with the entry
/// classifier injected.
///
/// A `fn` pointer (not `impl Fn`) so there is one monomorphization, matching the
/// seam idiom used elsewhere in the workspace. The seam exists because the
/// refusal cannot be reached otherwise on every platform: it needs a real
/// symlink on disk, and creating one on Windows requires a privilege CI runners
/// do not have. The `#[cfg(unix)]` tests still prove the real behaviour end to
/// end through a genuine symlink in a genuine archive.
fn reject_symlinks_with(dir: &Path, classify: fn(&Path) -> Entry) -> anyhow::Result<()> {
    // `into_iter().flatten().flatten()` rather than a `match` on `read_dir`: this
    // directory was created and unpacked into moments ago, so an unreadable one
    // has no reachable test - and it surfaces anyway on the manifest read that
    // follows. Collapsing it to "no entries" keeps the semantics with no branch
    // nothing can exercise.
    for entry in fs::read_dir(dir).into_iter().flatten().flatten() {
        let path = entry.path();
        match classify(&path) {
            Entry::Dir => reject_symlinks_with(&path, classify)?,
            Entry::File => {}
            Entry::Refused => anyhow::bail!(
                "Package contains a symlink or unreadable entry ('{}'), which is not \
                 permitted in an agent bundle",
                path.display()
            ),
        }
    }
    Ok(())
}

/// Information about an installed agent.
#[derive(Debug, Clone)]
pub struct InstalledAgent {
    /// Agent name
    pub name: String,
    /// Agent version
    pub version: String,
    /// Installation path
    pub path: PathBuf,
    /// Agent description
    pub description: String,
}

/// Installs agents from `.leviath-bundle` packages.
pub struct AgentInstaller {
    /// Installation directory (default ~/.leviath/agents/)
    install_dir: PathBuf,
}

impl AgentInstaller {
    /// Create a new installer using the default installation directory.
    ///
    /// The install root comes from the shared `LEVIATH_HOME`-aware resolver
    /// in [`leviath_core::paths`], so this crate installs into exactly the
    /// tree every other component reads.
    pub fn new() -> Self {
        // Panic (rather than silently falling back to ".") when no home
        // resolves: a system with no home directory is a misconfigured
        // environment, and failing loudly is better than installing into an
        // unexpected relative path.
        let install_dir =
            leviath_core::paths::agents_dir().expect("could not determine home directory");
        Self { install_dir }
    }

    /// Create an installer with a custom installation directory.
    pub fn with_install_dir(install_dir: PathBuf) -> Self {
        Self { install_dir }
    }

    /// Install an agent from a `.leviath-bundle` file.
    pub fn install(&self, package_path: &Path) -> anyhow::Result<InstalledAgent> {
        tracing::info!(path = %package_path.display(), "Installing agent from package");

        let data = fs::read(package_path).map_err(|e| {
            anyhow::anyhow!("Failed to read package '{}': {}", package_path.display(), e)
        })?;

        // Derive name from filename (strip .leviath-bundle extension)
        let name = package_path
            .file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or("unknown")
            .to_string();

        self.install_from_bytes(&name, &data)
    }

    /// Install an agent from in-memory bytes.
    ///
    /// `name` becomes a directory under the install dir, so it must be a single
    /// safe path component. `install` derives it from `file_stem()` (which
    /// already strips directories), but this is `pub` and any future caller
    /// passing a downloaded or user-supplied name would otherwise get a
    /// traversal for free - `Path::join` does not normalize, and an absolute
    /// name replaces the base entirely.
    pub fn install_from_bytes(&self, name: &str, data: &[u8]) -> anyhow::Result<InstalledAgent> {
        self.install_from_bytes_with(name, data, classify)
    }

    /// Core of [`install_from_bytes`](Self::install_from_bytes) with the entry
    /// classifier injected - see [`reject_symlinks_with`] for why the seam
    /// exists. A `fn` pointer, so there is one monomorphization.
    fn install_from_bytes_with(
        &self,
        name: &str,
        data: &[u8],
        classify: fn(&Path) -> Entry,
    ) -> anyhow::Result<InstalledAgent> {
        tracing::info!(name = %name, "Installing agent from bytes");

        if !leviath_core::is_safe_path_component(name) {
            anyhow::bail!(
                "invalid agent name '{name}': names may contain only letters, digits, \
                 '.', '_' and '-'"
            );
        }
        let agent_dir = self.install_dir.join(name);

        // Create installation directory
        fs::create_dir_all(&agent_dir).map_err(|e| {
            anyhow::anyhow!(
                "Failed to create install directory '{}': {}",
                agent_dir.display(),
                e
            )
        })?;

        // Extract tar.gz archive.
        //
        // `Read::take` bounds the *decompressed* stream. Without it a ~1 MB
        // bundle could expand to fill the disk - the classic decompression bomb -
        // and nothing downstream would notice until the write failed.
        //
        // `set_preserve_permissions(false)` and `set_unpack_xattrs(false)`:
        // otherwise an attacker-authored archive chooses the modes and extended
        // attributes of the files it drops into the user's home.
        //
        // tar-rs already rejects `..` components and validates every entry
        // against the destination (including hard links), so classic zip-slip is
        // covered by the dependency - which is a reason to keep `cargo audit`
        // watching it, not a reason to assume it always will.
        let decoder = GzDecoder::new(data).take(MAX_UNPACKED_BYTES);
        let mut archive = tar::Archive::new(decoder);
        archive.set_preserve_permissions(false);
        archive.set_unpack_xattrs(false);

        archive.unpack(&agent_dir).map_err(|e| {
            anyhow::anyhow!(
                "Failed to extract package: {}. (Bundles are limited to {} MiB \
                 uncompressed.)",
                e,
                MAX_UNPACKED_BYTES / (1024 * 1024)
            )
        })?;
        reject_symlinks_with(&agent_dir, classify)?;

        // Read agent.leviath to get metadata
        let manifest_path = agent_dir.join("agent.leviath");
        let (version, description) = if manifest_path.exists() {
            let content = fs::read_to_string(&manifest_path).unwrap_or_default();
            let parsed: toml::Value =
                toml::from_str(&content).unwrap_or(toml::Value::Table(toml::map::Map::new()));
            let version = parsed
                .get("agent")
                .and_then(|a| a.get("version"))
                .and_then(|v| v.as_str())
                .unwrap_or("0.0.0")
                .to_string();
            let description = parsed
                .get("agent")
                .and_then(|a| a.get("description"))
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .to_string();
            (version, description)
        } else {
            ("0.0.0".to_string(), String::new())
        };

        tracing::info!(
            name = %name,
            version = %version,
            path = %agent_dir.display(),
            "Agent installed successfully"
        );

        Ok(InstalledAgent {
            name: name.to_string(),
            version,
            path: agent_dir,
            description,
        })
    }

    /// Uninstall an agent by removing its directory.
    pub fn uninstall(&self, agent_name: &str) -> anyhow::Result<()> {
        let agent_dir = self.install_dir.join(agent_name);

        if !agent_dir.exists() {
            anyhow::bail!("Agent '{}' is not installed", agent_name);
        }

        fs::remove_dir_all(&agent_dir)
            .map_err(|e| anyhow::anyhow!("Failed to remove agent '{}': {}", agent_name, e))?;

        tracing::info!(name = %agent_name, "Agent uninstalled");
        Ok(())
    }

    /// List all installed agents.
    pub fn list_installed(&self) -> anyhow::Result<Vec<InstalledAgent>> {
        if !self.install_dir.exists() {
            return Ok(Vec::new());
        }

        let mut agents = Vec::new();

        for entry in
            fs::read_dir(&self.install_dir).expect("install_dir exists - read_dir should not fail")
        {
            let entry = entry.expect("read_dir entry should not fail");
            let path = entry.path();

            if path.is_dir() {
                let manifest_path = path.join("agent.leviath");
                if manifest_path.exists() {
                    let name = path
                        .file_name()
                        .and_then(|n| n.to_str())
                        .unwrap_or("unknown")
                        .to_string();

                    let content = fs::read_to_string(&manifest_path).unwrap_or_default();
                    let parsed: toml::Value = toml::from_str(&content)
                        .unwrap_or(toml::Value::Table(toml::map::Map::new()));

                    let version = parsed
                        .get("agent")
                        .and_then(|a| a.get("version"))
                        .and_then(|v| v.as_str())
                        .unwrap_or("0.0.0")
                        .to_string();
                    let description = parsed
                        .get("agent")
                        .and_then(|a| a.get("description"))
                        .and_then(|v| v.as_str())
                        .unwrap_or("")
                        .to_string();

                    agents.push(InstalledAgent {
                        name,
                        version,
                        path,
                        description,
                    });
                }
            }
        }

        Ok(agents)
    }

    /// Get information about a specific installed agent.
    pub fn get_installed(&self, name: &str) -> anyhow::Result<Option<InstalledAgent>> {
        let agent_dir = self.install_dir.join(name);

        if !agent_dir.exists() {
            return Ok(None);
        }

        let manifest_path = agent_dir.join("agent.leviath");
        if !manifest_path.exists() {
            return Ok(None);
        }

        let content = fs::read_to_string(&manifest_path).unwrap_or_default();
        let parsed: toml::Value =
            toml::from_str(&content).unwrap_or(toml::Value::Table(toml::map::Map::new()));

        let version = parsed
            .get("agent")
            .and_then(|a| a.get("version"))
            .and_then(|v| v.as_str())
            .unwrap_or("0.0.0")
            .to_string();
        let description = parsed
            .get("agent")
            .and_then(|a| a.get("description"))
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string();

        Ok(Some(InstalledAgent {
            name: name.to_string(),
            version,
            path: agent_dir,
            description,
        }))
    }
}

impl Default for AgentInstaller {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_support::with_tracing;
    use flate2::Compression;
    use flate2::write::GzEncoder;

    /// Create a minimal tar.gz bundle with an agent.leviath manifest.
    fn make_bundle(name: &str, version: &str, description: &str) -> Vec<u8> {
        let manifest = format!(
            r#"[agent]
name = "{}"
version = "{}"
description = "{}"
"#,
            name, version, description
        );

        let mut encoder = GzEncoder::new(Vec::new(), Compression::fast());
        {
            let mut archive = tar::Builder::new(&mut encoder);
            let manifest_bytes = manifest.as_bytes();
            let mut header = tar::Header::new_gnu();
            header.set_size(manifest_bytes.len() as u64);
            header.set_mode(0o644);
            header.set_cksum();
            archive
                .append_data(&mut header, "agent.leviath", manifest_bytes)
                .unwrap();
            archive.finish().unwrap();
        }
        encoder.finish().unwrap()
    }

    /// `install_from_bytes` is `pub` and joins `name` onto the install dir.
    /// `Path::join` does not normalize `..` and an absolute name replaces the
    /// base entirely, so an unvalidated name reached anywhere on the filesystem.
    #[test]
    fn install_from_bytes_rejects_traversing_names() {
        let dir = tempfile::tempdir().unwrap();
        let installer = AgentInstaller::with_install_dir(dir.path().to_path_buf());
        let bundle = make_bundle("x", "1.0.0", "d");
        for name in ["../escape", "../../tmp/escape", "/tmp/escape", "a/b", ".."] {
            let err = installer
                .install_from_bytes(name, &bundle)
                .expect_err("{name} must be refused");
            assert!(err.to_string().contains("invalid agent name"), "{err}");
        }
        assert!(
            !std::path::Path::new("/tmp/escape").exists(),
            "nothing may be created outside the install dir"
        );
    }

    /// A gzip bomb: a small archive that expands without bound. `Read::take`
    /// stops it mid-stream, so the unpack fails instead of filling the disk.
    #[test]
    fn install_from_bytes_refuses_a_decompression_bomb() {
        // 512 MiB of zeros, which gzip compresses to a few hundred KiB - past
        // the 256 MiB cap, so extraction must fail.
        let mut encoder = GzEncoder::new(Vec::new(), Compression::fast());
        {
            let mut archive = tar::Builder::new(&mut encoder);
            let size = 512 * 1024 * 1024u64;
            let mut header = tar::Header::new_gnu();
            header.set_size(size);
            header.set_mode(0o644);
            header.set_cksum();
            archive
                .append_data(&mut header, "big.bin", std::io::repeat(0).take(size))
                .unwrap();
            archive.finish().unwrap();
        }
        let bomb = encoder.finish().unwrap();
        // The length is bound first: a *call* inside `assert!`'s format
        // arguments is a region only the failing path reaches.
        let compressed = bomb.len();
        assert!(
            compressed < 5 * 1024 * 1024,
            "precondition: the bomb is small on disk"
        );

        let dir = tempfile::tempdir().unwrap();
        let installer = AgentInstaller::with_install_dir(dir.path().to_path_buf());
        let err = installer
            .install_from_bytes("bomb", &bomb)
            .expect_err("an oversized bundle must be refused");
        assert!(err.to_string().contains("Failed to extract"), "{err}");
    }

    /// A bundle with a `tools/` subdirectory - the realistic shape, and the one
    /// that exercises the recursive descent rather than only the flat case.
    #[test]
    fn install_from_bytes_accepts_a_nested_directory() {
        let mut encoder = GzEncoder::new(Vec::new(), Compression::fast());
        {
            let mut archive = tar::Builder::new(&mut encoder);
            for (path, body) in [
                (
                    "agent.leviath",
                    "[agent]\nname = \"n\"\nversion = \"1.0.0\"\n",
                ),
                ("tools/web_fetch.rhai", "// @tool web_fetch\n"),
            ] {
                let bytes = body.as_bytes();
                let mut header = tar::Header::new_gnu();
                header.set_size(bytes.len() as u64);
                header.set_mode(0o644);
                header.set_cksum();
                archive.append_data(&mut header, path, bytes).unwrap();
            }
            archive.finish().unwrap();
        }
        let bundle = encoder.finish().unwrap();

        let dir = tempfile::tempdir().unwrap();
        let installer = AgentInstaller::with_install_dir(dir.path().to_path_buf());
        let installed = installer.install_from_bytes("nested", &bundle).unwrap();
        assert!(installed.path.join("tools/web_fetch.rhai").exists());
    }

    /// A symlink hidden one directory down is refused too - the scan descends
    /// rather than checking only the top level, which is where a bundle would
    /// naturally put one (`tools/`).
    #[cfg(unix)]
    #[test]
    fn install_from_bytes_refuses_a_nested_symlink_entry() {
        let mut encoder = GzEncoder::new(Vec::new(), Compression::fast());
        {
            let mut archive = tar::Builder::new(&mut encoder);
            let manifest = "[agent]\nname = \"n\"\nversion = \"1.0.0\"\n";
            let bytes = manifest.as_bytes();
            let mut header = tar::Header::new_gnu();
            header.set_size(bytes.len() as u64);
            header.set_mode(0o644);
            header.set_cksum();
            archive
                .append_data(&mut header, "agent.leviath", bytes)
                .unwrap();

            let mut link = tar::Header::new_gnu();
            link.set_size(0);
            link.set_entry_type(tar::EntryType::Symlink);
            link.set_mode(0o777);
            archive
                .append_link(&mut link, "tools/escape", "/etc/passwd")
                .unwrap();
            archive.finish().unwrap();
        }
        let bundle = encoder.finish().unwrap();

        let dir = tempfile::tempdir().unwrap();
        let installer = AgentInstaller::with_install_dir(dir.path().to_path_buf());
        let err = installer
            .install_from_bytes("nested-link", &bundle)
            .expect_err("a nested symlink must be refused");
        assert!(err.to_string().contains("symlink"), "{err}");
    }

    /// tar-rs blocks entries that *extract* outside the destination, but a
    /// symlink entry lands inside it legally and then points wherever it likes.
    /// The installed tree is later scanned for `.rhai` tool scripts, so a link
    /// is a way to smuggle content in.
    /// The refusal itself, driven through the injected classifier so it runs on
    /// every platform. The `#[cfg(unix)]` tests below prove the same refusal
    /// against a genuine symlink in a genuine archive; this one proves the arm
    /// fires on Windows too, where a test cannot create one.
    #[test]
    fn reject_symlinks_refuses_an_entry_it_cannot_certify() {
        fn all_refused(_: &Path) -> Entry {
            Entry::Refused
        }
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("thing"), b"x").unwrap();

        let err = reject_symlinks_with(dir.path(), all_refused)
            .expect_err("an entry that cannot be certified is refused");
        assert!(err.to_string().contains("symlink or unreadable"), "{err}");
    }

    /// The refusal has to propagate out of a *nested* directory too - a bundle
    /// plants its `tools/` subdirectory, not its root.
    #[test]
    fn reject_symlinks_refuses_an_entry_nested_in_a_subdirectory() {
        /// Refuses only the leaf, so the recursion has to reach it.
        fn refuse_the_leaf(path: &Path) -> Entry {
            match path.file_name().and_then(|n| n.to_str()) {
                Some("web_fetch.rhai") => Entry::Refused,
                _ => classify(path),
            }
        }

        let dir = tempfile::tempdir().unwrap();
        let nested = dir.path().join("tools");
        std::fs::create_dir(&nested).unwrap();
        std::fs::write(nested.join("web_fetch.rhai"), b"x").unwrap();

        let err = reject_symlinks_with(dir.path(), refuse_the_leaf)
            .expect_err("a refused entry one level down is still refused");
        assert!(err.to_string().contains("web_fetch.rhai"), "{err}");
    }

    /// And the refusal fails the *install*, rather than being computed and
    /// discarded - the bundle must not be left in place.
    #[test]
    fn install_refuses_a_bundle_whose_entries_cannot_be_certified() {
        fn all_refused(_: &Path) -> Entry {
            Entry::Refused
        }

        let dir = tempfile::tempdir().unwrap();
        let installer = AgentInstaller::with_install_dir(dir.path().to_path_buf());
        let bundle = make_bundle("probe", "1.0.0", "a probe");

        let err = installer
            .install_from_bytes_with("probe", &bundle, all_refused)
            .expect_err("an uncertifiable bundle must not install");
        assert!(err.to_string().contains("symlink or unreadable"), "{err}");
    }

    /// Ordinary files and nested directories pass, so the test above is not
    /// passing merely because everything is refused.
    #[test]
    fn reject_symlinks_admits_ordinary_files_and_directories() {
        let dir = tempfile::tempdir().unwrap();
        let nested = dir.path().join("tools");
        std::fs::create_dir(&nested).unwrap();
        std::fs::write(nested.join("web_fetch.rhai"), b"x").unwrap();
        std::fs::write(dir.path().join("agent.leviath"), b"x").unwrap();

        reject_symlinks_with(dir.path(), classify).expect("an ordinary bundle passes");
        // And the classifier itself agrees about what it saw.
        assert_eq!(classify(&nested), Entry::Dir);
        assert_eq!(classify(&nested.join("web_fetch.rhai")), Entry::File);
        assert_eq!(classify(&dir.path().join("no-such-entry")), Entry::Refused);
    }

    #[cfg(unix)]
    #[test]
    fn install_from_bytes_refuses_a_symlink_entry() {
        let mut encoder = GzEncoder::new(Vec::new(), Compression::fast());
        {
            let mut archive = tar::Builder::new(&mut encoder);
            let mut header = tar::Header::new_gnu();
            header.set_size(0);
            header.set_entry_type(tar::EntryType::Symlink);
            header.set_mode(0o777);
            archive
                .append_link(&mut header, "escape", "/etc/passwd")
                .unwrap();
            archive.finish().unwrap();
        }
        let bundle = encoder.finish().unwrap();

        let dir = tempfile::tempdir().unwrap();
        let installer = AgentInstaller::with_install_dir(dir.path().to_path_buf());
        let err = installer
            .install_from_bytes("linky", &bundle)
            .expect_err("a symlink entry must be refused");
        assert!(err.to_string().contains("symlink"), "{err}");
    }

    #[test]
    fn with_install_dir_sets_dir() {
        let dir = PathBuf::from("/tmp/test-installer");
        let installer = AgentInstaller::with_install_dir(dir.clone());
        assert_eq!(installer.install_dir, dir);
    }

    #[test]
    fn install_from_bytes_creates_directory() {
        with_tracing(|| {
            let dir = tempfile::tempdir().unwrap();
            let installer = AgentInstaller::with_install_dir(dir.path().to_path_buf());

            let bundle = make_bundle("test-agent", "1.0.0", "A test agent");
            let result = installer.install_from_bytes("test-agent", &bundle).unwrap();

            assert_eq!(result.name, "test-agent");
            assert_eq!(result.version, "1.0.0");
            assert_eq!(result.description, "A test agent");
            assert!(result.path.exists());
            assert!(result.path.join("agent.leviath").exists());
        });
    }

    #[test]
    fn install_from_bytes_no_manifest_defaults() {
        let dir = tempfile::tempdir().unwrap();
        let installer = AgentInstaller::with_install_dir(dir.path().to_path_buf());

        // Create a bundle with no agent.leviath
        let mut encoder = GzEncoder::new(Vec::new(), Compression::fast());
        {
            let mut archive = tar::Builder::new(&mut encoder);
            let data = b"hello";
            let mut header = tar::Header::new_gnu();
            header.set_size(data.len() as u64);
            header.set_mode(0o644);
            header.set_cksum();
            archive
                .append_data(&mut header, "readme.txt", &data[..])
                .unwrap();
            archive.finish().unwrap();
        }
        let bundle = encoder.finish().unwrap();

        let result = installer
            .install_from_bytes("no-manifest", &bundle)
            .unwrap();
        assert_eq!(result.version, "0.0.0");
        assert_eq!(result.description, "");
    }

    #[test]
    fn uninstall_removes_directory() {
        with_tracing(|| {
            let dir = tempfile::tempdir().unwrap();
            let installer = AgentInstaller::with_install_dir(dir.path().to_path_buf());

            let bundle = make_bundle("to-remove", "1.0.0", "remove me");
            installer.install_from_bytes("to-remove", &bundle).unwrap();

            assert!(dir.path().join("to-remove").exists());
            installer.uninstall("to-remove").unwrap();
            assert!(!dir.path().join("to-remove").exists());
        });
    }

    #[test]
    fn uninstall_nonexistent_returns_error() {
        let dir = tempfile::tempdir().unwrap();
        let installer = AgentInstaller::with_install_dir(dir.path().to_path_buf());

        let err = installer.uninstall("no-such-agent").unwrap_err();
        assert!(err.to_string().contains("not installed"));
    }

    #[test]
    fn list_installed_empty_dir() {
        let dir = tempfile::tempdir().unwrap();
        let installer = AgentInstaller::with_install_dir(dir.path().to_path_buf());
        let agents = installer.list_installed().unwrap();
        assert!(agents.is_empty());
    }

    #[test]
    fn list_installed_nonexistent_dir() {
        let installer =
            AgentInstaller::with_install_dir(PathBuf::from("/tmp/nonexistent-leviath-test-dir"));
        let agents = installer.list_installed().unwrap();
        assert!(agents.is_empty());
    }

    #[test]
    fn list_installed_returns_installed_agents() {
        let dir = tempfile::tempdir().unwrap();
        let installer = AgentInstaller::with_install_dir(dir.path().to_path_buf());

        let bundle1 = make_bundle("agent-a", "1.0.0", "Agent A");
        let bundle2 = make_bundle("agent-b", "2.0.0", "Agent B");
        installer.install_from_bytes("agent-a", &bundle1).unwrap();
        installer.install_from_bytes("agent-b", &bundle2).unwrap();

        let agents = installer.list_installed().unwrap();
        assert_eq!(agents.len(), 2);
        let names: Vec<&str> = agents.iter().map(|a| a.name.as_str()).collect();
        assert!(names.contains(&"agent-a"));
        assert!(names.contains(&"agent-b"));
    }

    #[test]
    fn list_installed_skips_non_directory_entries() {
        let dir = tempfile::tempdir().unwrap();
        let installer = AgentInstaller::with_install_dir(dir.path().to_path_buf());

        // Install one real agent
        let bundle = make_bundle("good-agent", "1.0.0", "Good");
        installer.install_from_bytes("good-agent", &bundle).unwrap();

        // A regular file (not a dir) - covers the `if path.is_dir()` false branch
        fs::write(dir.path().join("not-an-agent.txt"), "hello").unwrap();

        // A dir without an agent.leviath manifest - covers the `if manifest_path.exists()` false branch
        fs::create_dir_all(dir.path().join("no-manifest-dir")).unwrap();

        let agents = installer.list_installed().unwrap();
        // Only the properly-installed agent is returned; file and bare dir are skipped
        assert_eq!(agents.len(), 1);
        assert_eq!(agents[0].name, "good-agent");
    }

    #[test]
    fn get_installed_found() {
        let dir = tempfile::tempdir().unwrap();
        let installer = AgentInstaller::with_install_dir(dir.path().to_path_buf());

        let bundle = make_bundle("findme", "3.2.1", "Find this agent");
        installer.install_from_bytes("findme", &bundle).unwrap();

        let agent = installer.get_installed("findme").unwrap().unwrap();
        assert_eq!(agent.name, "findme");
        assert_eq!(agent.version, "3.2.1");
        assert_eq!(agent.description, "Find this agent");
    }

    #[test]
    fn get_installed_not_found() {
        let dir = tempfile::tempdir().unwrap();
        let installer = AgentInstaller::with_install_dir(dir.path().to_path_buf());
        assert!(installer.get_installed("nope").unwrap().is_none());
    }

    #[test]
    fn get_installed_dir_exists_but_no_manifest() {
        let dir = tempfile::tempdir().unwrap();
        let installer = AgentInstaller::with_install_dir(dir.path().to_path_buf());

        // Create directory but no agent.leviath
        fs::create_dir_all(dir.path().join("empty-agent")).unwrap();
        assert!(installer.get_installed("empty-agent").unwrap().is_none());
    }

    // ─── AgentInstaller::new / Default ─────────────────────────────────

    #[test]
    fn new_derives_install_dir_from_home() {
        let installer = AgentInstaller::new();
        assert!(installer.install_dir.ends_with(".leviath/agents"));
    }

    #[test]
    fn default_matches_new() {
        let installer = AgentInstaller::default();
        assert!(installer.install_dir.ends_with(".leviath/agents"));
    }

    // ─── install() (file-based) ────────────────────────────────────────

    #[test]
    fn install_from_file_path_derives_name_from_filename() {
        with_tracing(|| {
            let dir = tempfile::tempdir().unwrap();
            let installer = AgentInstaller::with_install_dir(dir.path().join("agents"));

            let bundle = make_bundle("file-agent", "1.2.3", "Installed from a file");
            let package_path = dir.path().join("file-agent.leviath-bundle");
            fs::write(&package_path, &bundle).unwrap();

            let result = installer.install(&package_path).unwrap();
            assert_eq!(result.name, "file-agent");
            assert_eq!(result.version, "1.2.3");
            assert_eq!(result.description, "Installed from a file");
            assert!(result.path.exists());
        });
    }

    #[test]
    fn install_from_file_path_missing_file_returns_error() {
        let dir = tempfile::tempdir().unwrap();
        let installer = AgentInstaller::with_install_dir(dir.path().to_path_buf());

        let err = installer
            .install(&dir.path().join("does-not-exist.leviath-bundle"))
            .unwrap_err();
        assert!(err.to_string().contains("Failed to read package"));
    }

    // ─── install_from_bytes: create_dir_all failure ────────────────────

    #[test]
    fn install_from_bytes_create_dir_failure_returns_error() {
        let dir = tempfile::tempdir().unwrap();
        // Make a plain file where a directory needs to exist, so
        // create_dir_all(install_dir.join(name)) fails.
        let blocker = dir.path().join("blocker");
        fs::write(&blocker, b"not a directory").unwrap();

        let installer = AgentInstaller::with_install_dir(blocker.join("agents"));
        let bundle = make_bundle("blocked", "1.0.0", "desc");
        let err = installer
            .install_from_bytes("blocked", &bundle)
            .unwrap_err();
        assert!(
            err.to_string()
                .contains("Failed to create install directory")
        );
    }

    #[test]
    fn install_from_bytes_corrupt_tar_after_valid_gzip_returns_extract_error() {
        // Valid gzip framing wrapping bytes that are NOT a valid tar
        // archive - `GzDecoder` decompresses fine, but `Archive::unpack`
        // fails on the malformed header, exercising the "Failed to extract
        // package" error arm that every other test's well-formed bundle
        // never reaches.
        let dir = tempfile::tempdir().unwrap();
        let installer = AgentInstaller::with_install_dir(dir.path().to_path_buf());

        let mut encoder = GzEncoder::new(Vec::new(), Compression::fast());
        use std::io::Write;
        encoder
            .write_all(&[b'x'; 600]) // not a valid 512-byte tar header
            .unwrap();
        let bundle = encoder.finish().unwrap();

        let err = installer
            .install_from_bytes("corrupt-tar", &bundle)
            .unwrap_err();
        assert!(err.to_string().contains("Failed to extract package"));
    }

    #[test]
    fn uninstall_remove_dir_all_failure_returns_error() {
        // The installed "agent" entry is a regular file rather than a
        // directory: `exists()` passes the guard, but `remove_dir_all`
        // requires a directory and fails on every platform (NotADirectory),
        // exercising the "Failed to remove agent" error arm.
        let dir = tempfile::tempdir().unwrap();
        let installer = AgentInstaller::with_install_dir(dir.path().to_path_buf());
        let agent_path = dir.path().join("not-a-dir");
        fs::write(&agent_path, b"i am a file, not a directory").unwrap();

        let result = installer.uninstall("not-a-dir");

        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("Failed to remove agent")
        );
    }
}