1use include_dir::Dir;
2use std::fs;
3use std::path::{Path, PathBuf};
4use thiserror::Error;
5use vtcode_commons::fs::{ensure_dir_exists_sync, read_file_with_context_sync, write_file_with_context_sync};
6use vtcode_commons::utils::calculate_sha256;
7
8const SYSTEM_SKILLS_DIR: Dir = include_dir::include_dir!("$CARGO_MANIFEST_DIR/src/skills/assets/samples");
9
10const SYSTEM_SKILLS_DIR_NAME: &str = ".system";
11const SKILLS_DIR_NAME: &str = "skills";
12const SYSTEM_SKILLS_MARKER_FILENAME: &str = ".codex-system-skills.marker";
13const SYSTEM_SKILLS_MARKER_SALT: &str = "v2";
16
17#[must_use]
22pub fn bundled_skill_names() -> &'static [&'static str] {
23 &["cmd-review", "skill-creator", "skill-installer"]
24}
25
26pub fn system_cache_root_dir(codex_home: &Path) -> PathBuf {
32 codex_home.join(SKILLS_DIR_NAME).join(SYSTEM_SKILLS_DIR_NAME)
33}
34
35pub fn bundled_skills_home() -> Result<PathBuf, SystemSkillsError> {
42 let paths = vtcode_commons::VtCodePaths::resolve()
43 .map_err(|source| SystemSkillsError::io("resolve the bundled skills home", anyhow_to_io(source)))?;
44 Ok(paths.data_dir().to_path_buf())
45}
46
47#[must_use]
52pub fn has_bundled_skills_cache(home: &Path) -> bool {
53 system_cache_root_dir(home).join(SYSTEM_SKILLS_MARKER_FILENAME).is_file()
54}
55
56#[must_use]
62pub fn legacy_bundled_skills_cache_present() -> bool {
63 let legacy_home = std::env::var_os("CODEX_HOME")
64 .filter(|value| !value.is_empty())
65 .map(PathBuf::from)
66 .or_else(|| dirs::home_dir().map(|home| home.join(".codex")));
67 legacy_home.is_some_and(|home| has_bundled_skills_cache(&home))
68}
69
70#[must_use]
75pub fn bundled_skills_grandfathered() -> bool {
76 bundled_skills_home().is_ok_and(|home| has_bundled_skills_cache(&home)) || legacy_bundled_skills_cache_present()
77}
78
79pub fn install_system_skills(codex_home: &Path) -> Result<(), SystemSkillsError> {
92 require_absolute_home(codex_home)?;
93 let skills_root_dir = codex_home.join(SKILLS_DIR_NAME);
94 ensure_dir_exists_sync(&skills_root_dir)
95 .map_err(|source| SystemSkillsError::io("create skills root dir", anyhow_to_io(source)))?;
96
97 let dest_system = system_cache_root_dir(codex_home);
98
99 let marker_path = dest_system.join(SYSTEM_SKILLS_MARKER_FILENAME);
100 let expected_fingerprint = embedded_system_skills_fingerprint();
101 if dest_system.is_dir() && read_marker(&marker_path).is_ok_and(|marker| marker == expected_fingerprint) {
102 return Ok(());
103 }
104
105 if dest_system.exists() {
106 fs::remove_dir_all(&dest_system)
107 .map_err(|source| SystemSkillsError::io("remove existing system skills dir", source))?;
108 }
109
110 write_embedded_dir(&SYSTEM_SKILLS_DIR, &dest_system)?;
111 write_file_with_context_sync(&marker_path, &format!("{expected_fingerprint}\n"), "system skills marker")
112 .map_err(|source| SystemSkillsError::io("write system skills marker", anyhow_to_io(source)))?;
113 Ok(())
114}
115
116pub fn uninstall_system_skills(codex_home: &Path) {
117 if require_absolute_home(codex_home).is_err() {
118 return;
119 }
120 let _ = fs::remove_dir_all(system_cache_root_dir(codex_home));
121}
122
123fn require_absolute_home(codex_home: &Path) -> Result<(), SystemSkillsError> {
124 if codex_home.is_absolute() {
125 Ok(())
126 } else {
127 Err(SystemSkillsError::NonAbsoluteHome { home: codex_home.to_path_buf() })
128 }
129}
130
131fn anyhow_to_io(err: anyhow::Error) -> std::io::Error {
132 std::io::Error::other(err.to_string())
133}
134
135fn read_marker(path: &Path) -> Result<String, SystemSkillsError> {
136 Ok(read_file_with_context_sync(path, "system skills marker")
137 .map_err(|source| SystemSkillsError::io("read system skills marker", anyhow_to_io(source)))?
138 .trim()
139 .to_string())
140}
141
142fn stable_manifest_fingerprint<'a, I>(salt: &str, items: I) -> String
143where
144 I: IntoIterator<Item = (&'a str, Option<&'a str>)>,
145{
146 let mut manifest = String::new();
147 manifest.push_str("salt\t");
148 manifest.push_str(salt);
149 manifest.push('\n');
150
151 for (path, contents_hash) in items {
152 manifest.push_str(path);
153 manifest.push('\t');
154 manifest.push_str(contents_hash.unwrap_or("<dir>"));
155 manifest.push('\n');
156 }
157
158 calculate_sha256(manifest.as_bytes())
159}
160
161fn embedded_system_skills_fingerprint() -> String {
162 let mut items: Vec<(String, Option<String>)> = SYSTEM_SKILLS_DIR
163 .entries()
164 .iter()
165 .map(|entry| match entry {
166 include_dir::DirEntry::Dir(dir) => (dir.path().to_string_lossy().to_string(), None),
167 include_dir::DirEntry::File(file) => {
168 (file.path().to_string_lossy().to_string(), Some(calculate_sha256(file.contents())))
169 }
170 })
171 .collect();
172 items.sort_unstable_by(|(a, _), (b, _)| a.cmp(b));
173
174 stable_manifest_fingerprint(
175 SYSTEM_SKILLS_MARKER_SALT,
176 items
177 .iter()
178 .map(|(path, contents_hash)| (path.as_str(), contents_hash.as_deref())),
179 )
180}
181
182fn write_embedded_dir(dir: &Dir<'_>, dest: &Path) -> Result<(), SystemSkillsError> {
186 ensure_dir_exists_sync(dest)
187 .map_err(|source| SystemSkillsError::io("create system skills dir", anyhow_to_io(source)))?;
188
189 for entry in dir.entries() {
190 match entry {
191 include_dir::DirEntry::Dir(subdir) => {
192 let subdir_dest = dest.join(subdir.path());
193 ensure_dir_exists_sync(&subdir_dest)
194 .map_err(|source| SystemSkillsError::io("create system skills subdir", anyhow_to_io(source)))?;
195 write_embedded_dir(subdir, dest)?;
196 }
197 include_dir::DirEntry::File(file) => {
198 let path = dest.join(file.path());
199 if let Some(parent) = path.parent() {
200 ensure_dir_exists_sync(parent).map_err(|source| {
201 SystemSkillsError::io("create system skills file parent", anyhow_to_io(source))
202 })?;
203 }
204 let contents = std::str::from_utf8(file.contents())
205 .map_err(|source| SystemSkillsError::Utf8 { path: file.path().to_path_buf(), source })?;
206 write_file_with_context_sync(&path, contents, "system skill file")
207 .map_err(|source| SystemSkillsError::io("write system skill file", anyhow_to_io(source)))?;
208 }
209 }
210 }
211
212 Ok(())
213}
214
215#[derive(Debug, Error)]
216pub enum SystemSkillsError {
217 #[error("refusing to manage system skills under relative home {}", home.display())]
218 NonAbsoluteHome { home: PathBuf },
219 #[error("io error while {action}: {source}")]
220 Io {
221 action: &'static str,
222 #[source]
223 source: std::io::Error,
224 },
225 #[error("embedded system skill {path} is not valid UTF-8: {source}")]
226 Utf8 {
227 path: PathBuf,
228 #[source]
229 source: std::str::Utf8Error,
230 },
231}
232
233impl SystemSkillsError {
234 fn io(action: &'static str, source: std::io::Error) -> Self {
235 Self::Io { action, source }
236 }
237}
238
239#[cfg(test)]
240mod tests {
241 use super::{
242 SYSTEM_SKILLS_DIR, SYSTEM_SKILLS_MARKER_SALT, bundled_skill_names, bundled_skills_grandfathered,
243 embedded_system_skills_fingerprint, has_bundled_skills_cache, install_system_skills,
244 legacy_bundled_skills_cache_present, stable_manifest_fingerprint, system_cache_root_dir,
245 uninstall_system_skills,
246 };
247 use serial_test::serial;
248
249 #[test]
250 fn bundled_skill_names_match_embedded_samples() {
251 let mut embedded: Vec<String> = SYSTEM_SKILLS_DIR
252 .entries()
253 .iter()
254 .filter_map(|entry| match entry {
255 include_dir::DirEntry::Dir(dir) => {
256 dir.path().file_name().and_then(|name| name.to_str()).map(str::to_string)
257 }
258 include_dir::DirEntry::File(_) => None,
259 })
260 .collect();
261 embedded.sort_unstable();
262 let mut named: Vec<String> = bundled_skill_names().iter().map(ToString::to_string).collect();
263 named.sort_unstable();
264 assert_eq!(named, embedded);
265 }
266
267 #[test]
268 fn install_and_uninstall_refuse_relative_homes() {
269 let relative = std::path::PathBuf::from("relative-skills-home");
270 let error = install_system_skills(&relative).expect_err("relative install must fail");
271 assert!(error.to_string().contains("relative home"), "error: {error}");
272 assert!(!system_cache_root_dir(&relative).exists(), "refused install must not create anything");
273 uninstall_system_skills(&relative);
275 uninstall_system_skills(std::path::Path::new(""));
276 }
277
278 #[test]
279 fn cache_presence_tracks_install_lifecycle() {
280 let home = tempfile::TempDir::new().expect("temp home");
281 assert!(!has_bundled_skills_cache(home.path()));
282 install_system_skills(home.path()).expect("install");
283 assert!(has_bundled_skills_cache(home.path()));
284 uninstall_system_skills(home.path());
285 assert!(!has_bundled_skills_cache(home.path()));
286 }
287
288 #[test]
289 #[serial]
290 fn grandfather_detects_legacy_codex_marker() {
291 let legacy = tempfile::TempDir::new().expect("legacy home");
292 let guard = vtcode_commons::env_lock::lock();
293 let previous = std::env::var_os("CODEX_HOME");
294 guard.set_var("CODEX_HOME", legacy.path());
295 let data = tempfile::TempDir::new().expect("data dir");
297 let previous_data = std::env::var_os("VTCODE_DATA");
298 guard.set_var("VTCODE_DATA", data.path());
299
300 assert!(!legacy_bundled_skills_cache_present());
301 assert!(!bundled_skills_grandfathered());
302 install_system_skills(legacy.path()).expect("legacy install");
303 assert!(legacy_bundled_skills_cache_present());
304 assert!(bundled_skills_grandfathered());
305
306 guard.restore_var("CODEX_HOME", previous.as_deref());
307 guard.restore_var("VTCODE_DATA", previous_data.as_deref());
308 }
309
310 #[test]
311 fn stable_manifest_fingerprint_matches_known_digest() {
312 let fingerprint = stable_manifest_fingerprint(
313 SYSTEM_SKILLS_MARKER_SALT,
314 [
315 ("alpha", None),
316 ("alpha/config.json", Some("77c7ce9a5d86bb386d443bb96390dcf0ecf6afb7b74f84a88d64e6d4e8dcb5e0")),
317 ("beta.md", Some("3f89f6a04a1a1f8cb46fc4b356f7b81b8d18102fdb8b795f5b2f89e7cfefb3af")),
318 ],
319 );
320
321 assert_eq!(fingerprint, "218ca69badb47208804e293074956e23ed68d6946dde5d36e6fe8d56df170170");
322 }
323
324 #[test]
325 fn embedded_system_skills_fingerprint_uses_full_sha256_digest() {
326 assert_eq!(embedded_system_skills_fingerprint().len(), 64);
327 }
328}