Skip to main content

trusty_code/agents/
skill_refs.rs

1//! Skill files a composed tcode agent body points at by absolute path (#7727).
2//!
3//! Why: the shared `BASE-AGENT.md` tells an agent to open a skill file with its
4//! read tool at `{{TM_SKILLS}}/<skill>/SKILL.md`. trusty-mpm resolves that
5//! placeholder to its own deployed skills tier; tcode has no such tier, and its
6//! `read_file` is confined to the run's project or scratch root, so a pointer
7//! into any other real directory is one the agent cannot open.
8//! What: [`REFERENCED_SKILL_FILES`] embeds every file a roster pointer names.
9//! Two resolutions exist:
10//! - The project roster deploy writes the files beneath
11//!   `<project>/.trusty-code/skill-refs` ([`project_skill_refs_dir`],
12//!   [`materialize_skill_refs`]); the pointers land inside the project root.
13//! - An in-process compose (embedded fallback, a disk agent carrying the
14//!   placeholder) resolves to [`user_skill_refs_dir`] with no disk I/O
15//!   ([`resolve_skill_refs`]). `read_file` built with
16//!   `ReadFileTool::with_skill_refs` serves exactly those paths from
17//!   [`embedded_skill_ref`], so the pointer opens in bound and projectless runs
18//!   alike and compose never depends on a writable home.
19//!
20//! Neither directory is a skill-discovery directory, so these copies never
21//! shadow the embedded skill catalog.
22//! Test: `agents::skill_refs::tests`, `tools::fs::read::tests::skill_ref_*`.
23
24use std::path::{Path, PathBuf};
25
26use trusty_agents_common::agents::skill_root::{SKILLS_ROOT_PLACEHOLDER, resolve_skills_root};
27
28use crate::paths::WriteTargetError;
29use crate::paths::write_dir::NativeWriteDir;
30
31/// Directory name, beneath a `.trusty-code` root, holding the referenced files.
32pub const SKILL_REFS_DIRNAME: &str = "skill-refs";
33
34/// `(path relative to the skills root, file content)` for every skill file a
35/// shared roster pointer names. Byte copies of trusty-mpm's bundled skills,
36/// pinned by `referenced_copies_match_trusty_mpm_skills`.
37pub const REFERENCED_SKILL_FILES: &[(&str, &str)] = &[
38    (
39        "condition-based-waiting/SKILL.md",
40        include_str!("../assets/skill-refs/condition-based-waiting/SKILL.md"),
41    ),
42    // #8010: BASE-AGENT's revert/bisect rule points here (#7628).
43    (
44        "git-workflow/SKILL.md",
45        include_str!("../assets/skill-refs/git-workflow/SKILL.md"),
46    ),
47    (
48        "self-improvement-loop/SKILL.md",
49        include_str!("../assets/skill-refs/self-improvement-loop/SKILL.md"),
50    ),
51    (
52        "verification-before-completion/SKILL.md",
53        include_str!("../assets/skill-refs/verification-before-completion/SKILL.md"),
54    ),
55];
56
57/// `<project>/.trusty-code/skill-refs` — the root the project roster deploy uses.
58pub fn project_skill_refs_dir(project_root: &Path) -> PathBuf {
59    crate::paths::native_child(project_root, SKILL_REFS_DIRNAME)
60}
61
62/// `~/.trusty-code/skill-refs` — the address in-process composes resolve to.
63///
64/// What: a path only; nothing is written there. `read_file` serves it.
65pub fn user_skill_refs_dir() -> PathBuf {
66    crate::paths::private_state::private_state_dir().join(SKILL_REFS_DIRNAME)
67}
68
69/// The embedded content for `relative`, a path beneath a skill-refs root.
70///
71/// What: component-wise equality, so `a/../b` never matches `b`.
72/// Test: `embedded_skill_ref_matches_exact_entries_only`.
73pub fn embedded_skill_ref(relative: &Path) -> Option<&'static str> {
74    REFERENCED_SKILL_FILES
75        .iter()
76        .find(|(entry, _)| Path::new(entry) == relative)
77        .map(|(_, content)| *content)
78}
79
80/// Write every [`REFERENCED_SKILL_FILES`] entry beneath a pinned `dir`.
81///
82/// Why: this is the write #7779 caught landing in a victim directory — the old
83/// signature took a PATH, so the `create_dir_all`/`atomic_write` pair re-walked
84/// `<project>/.trusty-code/skill-refs` long after `check_native_write_target`
85/// had approved it, and followed whatever had been swapped in since.
86/// What: every entry's `<skill>/` directory is opened as a pinned child of `dir`
87/// ([`NativeWriteDir::child`]) and the file is written `openat`-relative to that
88/// handle, so the kernel resolves it against the validated inode rather than the
89/// path. A file whose content already matches is left alone, so repeated deploys
90/// do no writes; the rewrite is atomic, so a concurrent reader never sees a
91/// partial file. Postcondition: every entry is readable at
92/// `dir.path()/<relative path>` with its embedded content.
93/// Test: `materialize_skill_refs_writes_readable_files`,
94/// `agents::deploy::deploy_tests::swapped_skill_refs_dir_never_reaches_the_victim`.
95pub fn materialize_skill_refs(dir: &NativeWriteDir) -> Result<(), WriteTargetError> {
96    for (relative, content) in REFERENCED_SKILL_FILES {
97        let path = Path::new(relative);
98        let (parent, name) = match (path.parent(), path.file_name().and_then(|n| n.to_str())) {
99            (Some(parent), Some(name)) => (parent, name),
100            _ => {
101                return Err(WriteTargetError::Unpinnable {
102                    path: dir.path().join(relative),
103                    detail: format!("`{relative}` is not a usable skill-ref path"),
104                });
105            }
106        };
107        let skill = dir.child(parent)?;
108        if skill
109            .read(name)?
110            .is_some_and(|current| current == content.as_bytes())
111        {
112            continue;
113        }
114        skill.atomic_write(name, content.as_bytes())?;
115    }
116    Ok(())
117}
118
119/// Resolve the skills-root placeholder in a composed body against `dir`.
120///
121/// Why: compose runs for every agent resolution, so a failure here must never
122/// remove an agent from the roster (#7727 review, HIGH 2).
123/// What: pure string work. A body with no placeholder is returned unchanged.
124/// Otherwise the placeholder becomes `dir`; an unresolvable `dir` (relative —
125/// the no-home fallback — or non-UTF-8) logs a warning naming it and returns
126/// the body unchanged, so the agent still loads with an unresolved pointer.
127/// Test: `resolve_skill_refs_substitutes_without_touching_disk`,
128/// `resolve_skill_refs_keeps_the_body_for_a_relative_dir`.
129pub fn resolve_skill_refs(composed: &str, dir: &Path) -> String {
130    if !composed.contains(SKILLS_ROOT_PLACEHOLDER) {
131        return composed.to_string();
132    }
133    match resolve_skills_root(composed, dir) {
134        Ok(resolved) => resolved,
135        Err(e) => {
136            tracing::warn!(
137                path = %dir.display(),
138                "skill pointers left unresolved in a composed agent: {e}"
139            );
140            composed.to_string()
141        }
142    }
143}
144
145#[cfg(test)]
146mod tests {
147    use super::*;
148
149    #[test]
150    fn resolve_skill_refs_substitutes_without_touching_disk() {
151        let tmp = tempfile::tempdir().unwrap();
152        let dir = tmp.path().join("skill-refs");
153        let body = format!("Read `{SKILLS_ROOT_PLACEHOLDER}/self-improvement-loop/SKILL.md`.");
154        let out = resolve_skill_refs(&body, &dir);
155        let path = dir.join("self-improvement-loop/SKILL.md");
156        assert_eq!(out, format!("Read `{}`.", path.display()));
157        assert!(!dir.exists(), "compose must not write the refs dir");
158    }
159
160    #[test]
161    fn resolve_skill_refs_keeps_the_body_for_a_relative_dir() {
162        let body = format!("{SKILLS_ROOT_PLACEHOLDER}/x");
163        assert_eq!(resolve_skill_refs(&body, Path::new("relative")), body);
164    }
165
166    #[test]
167    fn materialize_skill_refs_writes_readable_files() {
168        let tmp = tempfile::tempdir().unwrap();
169        let dir = NativeWriteDir::open(tmp.path(), Path::new(SKILL_REFS_DIRNAME)).unwrap();
170        materialize_skill_refs(&dir).unwrap();
171        materialize_skill_refs(&dir).unwrap();
172        for (relative, content) in REFERENCED_SKILL_FILES {
173            assert_eq!(
174                std::fs::read_to_string(dir.path().join(relative)).unwrap(),
175                *content
176            );
177        }
178    }
179
180    #[test]
181    fn embedded_skill_ref_matches_exact_entries_only() {
182        let hit = Path::new("self-improvement-loop/SKILL.md");
183        assert_eq!(embedded_skill_ref(hit), Some(REFERENCED_SKILL_FILES[2].1));
184        for miss in [
185            "self-improvement-loop",
186            "x/../self-improvement-loop/SKILL.md",
187            "/self-improvement-loop/SKILL.md",
188        ] {
189            assert_eq!(embedded_skill_ref(Path::new(miss)), None, "{miss}");
190        }
191    }
192
193    #[test]
194    fn referenced_copies_match_trusty_mpm_skills() {
195        // #9012: trusty-mpm's skills moved to the workspace content tree.
196        // #9298: the running checkout, not the one that built this binary.
197        let mpm_skills = trusty_common::test_harness::test_repo_root()
198            .expect("the running checkout's workspace root")
199            .join("content/skills");
200        for (relative, content) in REFERENCED_SKILL_FILES {
201            let skill = relative.trim_end_matches("/SKILL.md");
202            let source = std::fs::read_to_string(mpm_skills.join(format!("{skill}.md")))
203                .unwrap_or_else(|e| panic!("trusty-mpm skill `{skill}` must exist: {e}"));
204            assert_eq!(
205                *content, source,
206                "`assets/skill-refs/{relative}` drifted from trusty-mpm's `{skill}.md`"
207            );
208        }
209    }
210
211    #[test]
212    fn every_roster_pointer_names_an_embedded_file() {
213        let marker = format!("{SKILLS_ROOT_PLACEHOLDER}/");
214        // #9011: the shared texts are read from the checkout's content.
215        let root = trusty_common::test_harness::test_repo_root()
216            .expect("the running checkout's workspace root"); // #9298
217        let content =
218            trusty_agents_common::agent_content::checkout_content(&root).expect("repo content");
219        let roster =
220            trusty_agents_common::agent_content::AgentRoster::load(&content).expect("roster");
221        for (file_name, md) in crate::assets::tm_agent_sources(&roster).expect("catalog") {
222            for (at, _) in md.match_indices(&marker) {
223                let rest = &md[at + marker.len()..];
224                let relative = rest.split('`').next().unwrap_or(rest);
225                assert!(
226                    REFERENCED_SKILL_FILES.iter().any(|(r, _)| *r == relative),
227                    "{file_name} points at `{relative}`, which tcode does not embed"
228                );
229            }
230        }
231    }
232}