bake-agent-context 0.4.0

Install context files from Cargo dependencies for coding agents
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
// Released under the MIT License.
// Copyright, 2026, by Samuel Williams.

use super::package::Package;
use super::skill::SkillDefinition;
#[cfg(test)]
use super::test_filesystem as fs;
use bake::{Error, Result};
use serde::Deserialize;
use std::collections::{HashMap, HashSet};
use std::env;
use std::ffi::{OsStr, OsString};
#[cfg(not(test))]
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;

/// Resolved package metadata for a Cargo context provider.
#[derive(Clone, Debug)]
pub struct Specification {
    pub name: String,
    pub version: String,
    pub description: Option<String>,
    pub context_path: PathBuf,
    selector: String,
}

impl Specification {
    /// The name accepted by the task's `--package` option.
    pub fn selector(&self) -> &str {
        &self.selector
    }

    #[cfg(test)]
    pub(super) fn for_test(name: &str, version: &str, context_path: PathBuf) -> Self {
        Self {
            name: name.to_owned(),
            version: version.to_owned(),
            description: Some(format!("{name} documentation")),
            context_path,
            selector: format!("{name}@{version}"),
        }
    }
}

/// An ordinary file loaded from a provider's `context/` directory.
#[derive(Clone, Debug)]
pub struct FileDefinition {
    /// The path relative to the provider's `context/` directory.
    pub path: PathBuf,
    /// The source file path.
    pub source_path: PathBuf,
    pub(crate) document: Option<super::document::Document>,
}

/// One loaded context definition.
#[derive(Clone, Debug)]
pub enum Definition {
    File(FileDefinition),
    Skill(SkillDefinition),
}

impl Definition {
    /// The name shown by `agent:context:list`.
    pub fn display_name(&self) -> String {
        match self {
            Self::File(file) => file
                .path
                .to_string_lossy()
                .replace(std::path::MAIN_SEPARATOR, "/"),
            Self::Skill(skill) => format!(
                "{} (skill)",
                skill.path.file_stem().unwrap().to_string_lossy()
            ),
        }
    }

    /// The source path relative to the provider's context directory.
    pub fn path(&self) -> &Path {
        match self {
            Self::File(file) => &file.path,
            Self::Skill(skill) => &skill.path,
        }
    }

    /// Read the authored content of this definition.
    pub fn content(&self) -> Result<String> {
        match self {
            Self::File(file) => file.content(),
            Self::Skill(skill) => Ok(skill.content().to_owned()),
        }
    }

    /// Whether the definition installs as an Agent Skill.
    pub fn is_skill(&self) -> bool {
        matches!(self, Self::Skill(_))
    }
}

impl FileDefinition {
    /// Read the authored content of the file.
    pub fn content(&self) -> Result<String> {
        if let Some(document) = &self.document {
            return Ok(document.content.clone());
        }

        read_context_file(&self.source_path)
    }
}

/// The provider and skill names refreshed by an installation.
#[derive(Debug)]
pub struct Installation {
    pub context: Vec<String>,
    pub skills: Vec<String>,
}

/// Discovers, lists, reads, and installs context from resolved Cargo dependencies.
#[derive(Clone, Debug)]
pub struct Installer {
    root: PathBuf,
    context_path: PathBuf,
    specifications: Vec<Specification>,
}

impl Installer {
    /// Resolve the project's Cargo packages and find dependencies with `context/` directories.
    pub fn discover(root: impl Into<PathBuf>) -> Result<Self> {
        let root = root.into();
        let cargo = cargo_executable(env::var_os("CARGO"));
        Self::discover_with_cargo(root, cargo)
    }

    fn discover_with_cargo(root: PathBuf, cargo: OsString) -> Result<Self> {
        let manifest = root.join("Cargo.toml");
        let output = run_cargo_metadata(&root, &cargo)?;
        if !output.status.success() {
            return Err(cargo_metadata_failure(
                &manifest,
                output.status,
                &output.stderr,
            ));
        }

        let metadata = parse_metadata(&output.stdout)?;
        Self::discover_from_metadata(root, metadata)
    }

    #[cfg(test)]
    pub(super) fn for_test(root: &Path, specifications: Vec<Specification>) -> Self {
        Self {
            root: root.to_path_buf(),
            context_path: root.join(".agents/context"),
            specifications,
        }
    }

    fn discover_from_metadata(root: PathBuf, metadata: CargoMetadata) -> Result<Self> {
        let workspace_members: HashSet<_> = metadata.workspace_members.into_iter().collect();
        let resolved_packages: HashSet<_> = metadata
            .resolve
            .map(|resolve| {
                resolve
                    .nodes
                    .into_iter()
                    .map(|node| node.package_id)
                    .collect()
            })
            .unwrap_or_default();

        let mut candidates = Vec::new();
        for package in metadata.packages {
            if workspace_members.contains(&package.package_id)
                || (!resolved_packages.is_empty()
                    && !resolved_packages.contains(&package.package_id))
            {
                continue;
            }

            let Some(package_root) = package.manifest_path.parent() else {
                continue;
            };
            let context_path = package_root.join("context");
            match fs::symlink_metadata(&context_path) {
                Ok(metadata) if metadata.file_type().is_dir() => {}
                Ok(_) => continue,
                Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
                Err(error) => {
                    return Err(Error::new(format!(
                        "cannot inspect {}: {error}",
                        context_path.display()
                    )));
                }
            };
            candidates.push(Specification {
                name: package.name,
                version: package.version,
                description: package.description,
                context_path,
                selector: String::new(),
            });
        }

        let mut name_counts = HashMap::new();
        for specification in &candidates {
            *name_counts
                .entry(specification.name.clone())
                .or_insert(0usize) += 1;
        }
        for specification in &mut candidates {
            specification.selector = if name_counts[&specification.name] == 1 {
                specification.name.clone()
            } else {
                format!("{}@{}", specification.name, specification.version)
            };
        }
        candidates.sort_by(|left, right| {
            left.name
                .cmp(&right.name)
                .then_with(|| left.version.cmp(&right.version))
        });

        Ok(Self {
            context_path: root.join(".agents/context"),
            root,
            specifications: candidates,
        })
    }

    pub fn root(&self) -> &Path {
        &self.root
    }

    pub fn context_path(&self) -> &Path {
        &self.context_path
    }

    pub fn specifications(&self) -> &[Specification] {
        &self.specifications
    }

    pub fn find_specification(&self, selector: &str) -> Result<Option<Specification>> {
        let matches: Vec<_> = self
            .specifications
            .iter()
            .filter(|specification| {
                specification.selector == selector || specification.name == selector
            })
            .collect();

        match matches.as_slice() {
            [] => Ok(None),
            [specification] => Ok(Some((*specification).clone())),
            _ => {
                let selectors = matches
                    .iter()
                    .map(|specification| specification.selector.as_str())
                    .collect::<Vec<_>>()
                    .join(", ");
                Err(Error::new(format!(
                    "multiple versions of crate {selector:?} provide context; choose one of: {selectors}"
                )))
            }
        }
    }

    /// Load providers with context directories, including empty providers.
    pub fn providers(&self) -> Result<Vec<Package>> {
        self.specifications
            .iter()
            .cloned()
            .map(Package::load)
            .collect()
    }

    /// Load one provider by its package selector.
    pub fn find_provider(&self, selector: &str) -> Result<Option<Package>> {
        self.find_specification(selector)?
            .map(Package::load)
            .transpose()
    }

    /// Read the authored content of a selected definition.
    pub fn show_context_file(&self, selector: &str, file: &str) -> Result<Option<String>> {
        let Some(package) = self.find_provider(selector)? else {
            return Ok(None);
        };
        package
            .find_definition(file)?
            .map(Definition::content)
            .transpose()
    }

    /// Install context and skills from the same loaded provider documents.
    pub fn install(&self, selector: Option<&str>) -> Result<Installation> {
        // Resolve the requested scope and load each provider once:
        let loaded =
            if let Some(selector) = selector {
                vec![self.find_provider(selector)?.ok_or_else(|| {
                    Error::new(format!("no context found for crate {selector:?}"))
                })?]
            } else {
                self.providers()?
            };
        let definitions: Vec<_> = loaded
            .iter()
            .flat_map(|package| package.definitions.iter())
            .filter_map(|definition| match definition {
                Definition::Skill(skill) => Some(skill.clone()),
                Definition::File(_) => None,
            })
            .collect();
        let package = selector
            .and_then(|_| loaded.first())
            .map(|package| package.specification.name.as_str());

        // Apply skill installation rules, then write ordinary definitions:
        let skills = super::skill::install_definitions(&self.root, &definitions, package, true)?;
        let mut context_names = Vec::new();
        for package in loaded {
            if package.install_files(&self.context_path.join(package.specification.selector()))? {
                context_names.push(package.specification.selector().to_owned());
            }
        }
        Ok(Installation {
            context: context_names,
            skills,
        })
    }
}

fn run_cargo_metadata(root: &Path, cargo: &OsStr) -> Result<std::process::Output> {
    let manifest = root.join("Cargo.toml");
    let mut command = Command::new(cargo);
    command
        .args([
            "metadata",
            "--format-version",
            "1",
            "--locked",
            "--manifest-path",
        ])
        .arg(&manifest)
        .current_dir(root);

    command.output().map_err(|error| {
        Error::new(format!(
            "cannot run cargo metadata for {}: {error}",
            manifest.display()
        ))
    })
}

fn cargo_executable(cargo: Option<OsString>) -> OsString {
    cargo.unwrap_or_else(|| "cargo".into())
}

fn cargo_metadata_failure(manifest: &Path, status: impl std::fmt::Display, stderr: &[u8]) -> Error {
    let details = String::from_utf8_lossy(stderr).trim().to_owned();
    Error::new(format!(
        "cargo metadata failed for {} ({}): {}",
        manifest.display(),
        status,
        if details.is_empty() {
            "run cargo check to resolve and lock the project's dependencies".to_owned()
        } else {
            details
        }
    ))
}

fn parse_metadata(stdout: &[u8]) -> Result<CargoMetadata> {
    serde_json::from_slice(stdout)
        .map_err(|error| Error::new(format!("cannot parse cargo metadata: {error}")))
}

#[derive(Deserialize)]
struct CargoMetadata {
    workspace_members: Vec<String>,
    packages: Vec<CargoPackage>,
    resolve: Option<Resolve>,
}

#[derive(Deserialize)]
struct Resolve {
    nodes: Vec<ResolveNode>,
}

#[derive(Deserialize)]
struct ResolveNode {
    #[serde(rename = "id")]
    package_id: String,
}

#[derive(Deserialize)]
struct CargoPackage {
    #[serde(rename = "id")]
    package_id: String,
    name: String,
    version: String,
    description: Option<String>,
    manifest_path: PathBuf,
}

fn read_context_file(path: &Path) -> Result<String> {
    fs::read_to_string(path)
        .map_err(|error| Error::new(format!("cannot read {}: {error}", path.display())))
}

pub(crate) fn remove_existing(path: &Path) -> Result<()> {
    let metadata = match fs::symlink_metadata(path) {
        Ok(metadata) => metadata,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
        Err(error) => {
            return Err(Error::new(format!(
                "cannot inspect {}: {error}",
                path.display()
            )));
        }
    };
    let result = if metadata.file_type().is_dir() {
        fs::remove_dir_all(path)
    } else {
        fs::remove_file(path)
    };
    result.map_err(|error| Error::new(format!("cannot remove {}: {error}", path.display())))
}

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

    fn cargo_package(id: &str, name: &str, version: &str, manifest_path: PathBuf) -> CargoPackage {
        CargoPackage {
            package_id: id.to_owned(),
            name: name.to_owned(),
            version: version.to_owned(),
            description: Some(format!("{name} description")),
            manifest_path,
        }
    }

    #[test]
    fn reports_cargo_execution_status_and_json_errors() {
        let directory = tempdir().unwrap();
        let error = Installer::discover(directory.path()).err().unwrap();
        assert!(error.to_string().contains("cargo metadata failed"));

        let error = Installer::discover_with_cargo(
            directory.path().to_path_buf(),
            directory.path().join("missing-cargo").into_os_string(),
        )
        .unwrap_err();
        assert!(error.to_string().contains("cannot run cargo metadata"));

        assert_eq!(cargo_executable(None), OsString::from("cargo"));
        assert_eq!(
            cargo_executable(Some(OsString::from("custom-cargo"))),
            OsString::from("custom-cargo")
        );

        let error = cargo_metadata_failure(
            &directory.path().join("Cargo.toml"),
            "exit status: 1",
            b"  cargo stderr \n",
        );
        assert!(error.to_string().ends_with("cargo stderr"));
        let error = cargo_metadata_failure(&PathBuf::from("Cargo.toml"), "exit status: 1", b"\n");
        assert!(error.to_string().contains("run cargo check to resolve"));

        let error = parse_metadata(b"not JSON").err().unwrap();
        assert!(error.to_string().contains("cannot parse cargo metadata"));
    }

    #[cfg(unix)]
    #[test]
    fn reports_metadata_parse_errors_from_cargo() {
        let directory = tempdir().unwrap();
        let error =
            Installer::discover_with_cargo(directory.path().to_path_buf(), "/usr/bin/true".into())
                .unwrap_err();
        assert!(error.to_string().contains("cannot parse cargo metadata"));
    }

    #[test]
    fn discovers_only_resolved_non_workspace_context_packages_and_disambiguates_versions() {
        let directory = tempdir().unwrap();
        let root = directory.path();
        for path in [
            "workspace",
            "duplicate-v1",
            "duplicate-v2",
            "missing",
            "file",
        ] {
            fs::create_dir_all(root.join(path)).unwrap();
        }
        fs::create_dir(root.join("workspace/context")).unwrap();
        fs::create_dir(root.join("duplicate-v1/context")).unwrap();
        fs::create_dir(root.join("duplicate-v2/context")).unwrap();
        fs::write(root.join("file/context"), "not a directory").unwrap();

        let packages = vec![
            cargo_package(
                "root 0.1.0",
                "workspace",
                "0.1.0",
                root.join("workspace/Cargo.toml"),
            ),
            cargo_package(
                "dup 1.0.0",
                "duplicate",
                "1.0.0",
                root.join("duplicate-v1/Cargo.toml"),
            ),
            cargo_package(
                "dup 2.0.0",
                "duplicate",
                "2.0.0",
                root.join("duplicate-v2/Cargo.toml"),
            ),
            cargo_package(
                "unresolved 1.0.0",
                "unresolved",
                "1.0.0",
                root.join("missing/Cargo.toml"),
            ),
            cargo_package("file 1.0.0", "file", "1.0.0", root.join("file/Cargo.toml")),
        ];
        let metadata = CargoMetadata {
            workspace_members: vec!["root 0.1.0".to_owned()],
            packages,
            resolve: Some(Resolve {
                nodes: vec![
                    ResolveNode {
                        package_id: "root 0.1.0".to_owned(),
                    },
                    ResolveNode {
                        package_id: "dup 1.0.0".to_owned(),
                    },
                    ResolveNode {
                        package_id: "dup 2.0.0".to_owned(),
                    },
                    ResolveNode {
                        package_id: "file 1.0.0".to_owned(),
                    },
                ],
            }),
        };
        let installer = Installer::discover_from_metadata(root.to_path_buf(), metadata).unwrap();

        assert_eq!(installer.root(), root);
        assert_eq!(installer.context_path(), root.join(".agents/context"));
        assert_eq!(
            installer
                .specifications()
                .iter()
                .map(Specification::selector)
                .collect::<Vec<_>>(),
            ["duplicate@1.0.0", "duplicate@2.0.0"]
        );
        assert!(installer.find_specification("missing").unwrap().is_none());
        assert!(
            installer
                .find_specification("duplicate")
                .unwrap_err()
                .to_string()
                .contains("duplicate@1.0.0, duplicate@2.0.0")
        );
        assert_eq!(
            installer
                .find_specification("duplicate@2.0.0")
                .unwrap()
                .unwrap()
                .version,
            "2.0.0"
        );
    }

    #[test]
    fn supports_metadata_without_a_resolve_graph_and_skips_missing_or_malformed_paths() {
        let directory = tempdir().unwrap();
        let root = directory.path();
        fs::create_dir_all(root.join("valid/context")).unwrap();
        fs::create_dir(root.join("path-is-file")).unwrap();
        fs::write(root.join("path-is-file/context"), "not a directory").unwrap();

        let metadata = CargoMetadata {
            workspace_members: Vec::new(),
            packages: vec![
                cargo_package("valid", "valid", "1.0.0", root.join("valid/Cargo.toml")),
                cargo_package(
                    "missing",
                    "missing",
                    "1.0.0",
                    root.join("absent/Cargo.toml"),
                ),
                cargo_package(
                    "file",
                    "file",
                    "1.0.0",
                    root.join("path-is-file/Cargo.toml"),
                ),
                cargo_package("empty", "empty", "1.0.0", PathBuf::new()),
            ],
            resolve: None,
        };
        let installer = Installer::discover_from_metadata(root.to_path_buf(), metadata).unwrap();
        assert_eq!(installer.specifications().len(), 1);
        assert_eq!(installer.specifications()[0].selector(), "valid");
    }

    #[cfg(unix)]
    #[test]
    fn reports_context_provider_path_inspection_errors() {
        let directory = tempdir().unwrap();
        let root = directory.path();
        let blocker = root.join("blocker");
        fs::write(&blocker, "file").unwrap();
        let metadata = CargoMetadata {
            workspace_members: Vec::new(),
            packages: vec![cargo_package(
                "broken",
                "broken",
                "1.0.0",
                blocker.join("Cargo.toml"),
            )],
            resolve: None,
        };
        assert!(Installer::discover_from_metadata(root.to_path_buf(), metadata).is_err());
    }

    #[test]
    fn finds_loaded_source_paths_before_skill_names() {
        let directory = tempdir().unwrap();
        let context = directory.path().join("context");
        fs::create_dir_all(context.join("nested")).unwrap();
        fs::write(context.join("guide.md"), "guide").unwrap();
        let source =
            "---\nname: guide\nmetadata: {type: skill}\ndescription: Workflow.\n---\n# Workflow\n";
        fs::write(context.join("workflow.md"), source).unwrap();
        fs::write(context.join("nested/readme.MD"), "nested").unwrap();
        let specification = Specification::for_test("provider", "1.0.0", context.clone());
        let installer = Installer::for_test(directory.path(), vec![specification]);
        let package = installer.find_provider("provider").unwrap().unwrap();
        assert_eq!(
            package
                .find_definition("guide")
                .unwrap()
                .unwrap()
                .content()
                .unwrap(),
            "guide"
        );
        assert_eq!(
            package
                .find_definition("guide.md")
                .unwrap()
                .unwrap()
                .content()
                .unwrap(),
            "guide"
        );
        assert_eq!(
            package
                .find_definition("workflow")
                .unwrap()
                .unwrap()
                .content()
                .unwrap(),
            source
        );
        assert_eq!(
            package
                .find_definition("nested/readme.MD")
                .unwrap()
                .unwrap()
                .content()
                .unwrap(),
            "nested"
        );
        assert!(package.find_definition("not-found").unwrap().is_none());
        for path in ["", "/etc/passwd", "./guide.md", "nested/../guide.md"] {
            assert!(package.find_definition(path).is_err());
        }

        // Source lookup uses the loaded snapshot, with installed names as a fallback:
        fs::remove_file(context.join("guide.md")).unwrap();
        assert_eq!(
            package
                .find_definition("guide")
                .unwrap()
                .unwrap()
                .content()
                .unwrap(),
            "guide"
        );
        assert_eq!(
            installer
                .show_context_file("provider", "guide")
                .unwrap()
                .as_deref(),
            Some(source)
        );
        fs::write(context.join("guide"), "exact source").unwrap();
        fs::write(context.join("guide.md"), "markdown source").unwrap();
        assert_eq!(
            installer
                .show_context_file("provider", "guide")
                .unwrap()
                .as_deref(),
            Some("exact source")
        );
        assert!(installer.find_provider("missing").unwrap().is_none());
        assert!(read_context_file(&context).is_err());
    }

    #[cfg(unix)]
    #[test]
    fn reports_context_removal_errors() {
        use std::os::unix::fs::PermissionsExt;

        let directory = tempdir().unwrap();
        let parent = directory.path().join("context");
        fs::create_dir(&parent).unwrap();
        let destination = parent.join("installed");
        fs::write(&destination, "previous context").unwrap();
        fs::set_permissions(&parent, fs::Permissions::from_mode(0o555)).unwrap();

        let result = remove_existing(&destination);
        fs::set_permissions(&parent, fs::Permissions::from_mode(0o755)).unwrap();

        assert!(result.unwrap_err().to_string().contains("cannot remove"));
    }

    #[cfg(unix)]
    #[test]
    fn rejects_context_file_symlinks_that_escape_the_provider() {
        use std::os::unix::fs::symlink;

        let directory = tempdir().unwrap();
        let context = directory.path().join("context");
        fs::create_dir_all(&context).unwrap();
        let outside = directory.path().join("private.md");
        fs::write(&outside, "secret").unwrap();
        symlink(&outside, context.join("external.md")).unwrap();

        let package = Package::load(Specification::for_test("provider", "1.0.0", context)).unwrap();
        assert!(package.find_definition("external.md").unwrap().is_none());
    }

    #[cfg(unix)]
    #[test]
    fn reports_removal_errors_for_paths_beneath_files() {
        let directory = tempdir().unwrap();
        let blocker = directory.path().join("blocker");
        fs::write(&blocker, "file").unwrap();
        assert!(remove_existing(&blocker.join("child")).is_err());
    }
    #[test]
    fn coordinates_ordinary_files_skills_and_empty_providers() {
        let directory = tempdir().unwrap();
        let root = directory.path();
        let context = root.join("provider/context");
        fs::create_dir_all(&context).unwrap();
        fs::write(context.join("guide.md"), "# Guide\n").unwrap();
        fs::write(context.join("data.txt"), "Opaque resource").unwrap();
        fs::write(
            context.join("workflow.md"),
            "---\nmetadata: {type: skill}\ndescription: Workflow.\n---\n",
        )
        .unwrap();
        let package = Specification::for_test("provider", "1.0.0", context.clone());
        let installer = Installer::for_test(root, vec![package.clone()]);
        assert_eq!(
            installer
                .show_context_file("provider", "data.txt")
                .unwrap()
                .as_deref(),
            Some("Opaque resource")
        );
        assert!(
            installer
                .show_context_file("provider", "provider-workflow")
                .unwrap()
                .unwrap()
                .contains("Workflow.")
        );
        assert!(
            installer
                .install(Some("missing"))
                .unwrap_err()
                .to_string()
                .contains("no context found")
        );
        let ambiguous = Installer::for_test(root, vec![package.clone(), package]);
        assert!(ambiguous.install(Some("provider")).is_err());
        let loaded = installer.install(None).unwrap();
        assert_eq!(loaded.context, ["provider@1.0.0"]);
        assert_eq!(loaded.skills, ["provider-workflow"]);
        fs::remove_file(context.join("guide.md")).unwrap();
        fs::remove_file(context.join("data.txt")).unwrap();
        assert!(installer.install(None).unwrap().context.is_empty());
        assert!(installer.install(None).unwrap().context.is_empty());
        fs::write(context.join("broken.md"), "---\n[invalid\n---\n").unwrap();
        assert!(
            installer
                .show_context_file("provider", "provider-workflow")
                .is_err()
        );
        assert!(installer.install(Some("provider")).is_err());
    }

    #[test]
    fn reports_ordinary_context_write_failures_from_the_main_installation() {
        let directory = tempdir().unwrap();
        let root = directory.path();
        let context = root.join("provider/context");
        fs::create_dir_all(&context).unwrap();
        fs::write(context.join("guide.md"), "# Guide\n").unwrap();
        let package = Specification::for_test("provider", "1.0.0", context);
        let installer = Installer::for_test(root, vec![package]);
        let destination = root.join(".agents/context/provider@1.0.0/guide.md");
        let _failure = fs::fail_once(fs::Operation::Write, move |path| path == destination);
        assert!(
            installer
                .install(None)
                .unwrap_err()
                .to_string()
                .contains("cannot write")
        );
    }
}