forked from openai/codex
-
Notifications
You must be signed in to change notification settings - Fork 238
Expand file tree
/
Copy pathloader.rs
More file actions
399 lines (334 loc) · 12.4 KB
/
Copy pathloader.rs
File metadata and controls
399 lines (334 loc) · 12.4 KB
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
use crate::config::Config;
use crate::config::resolve_code_path_for_read;
use crate::git_info::resolve_root_git_project_for_trust;
use crate::skills::model::SkillError;
use crate::skills::model::SkillLoadOutcome;
use crate::skills::model::SkillMetadata;
use crate::skills::model::SkillScope;
use crate::skills::system::system_cache_root_dir;
use crate::skills::system::install_system_skills;
use dunce::canonicalize as normalize_path;
use serde::Deserialize;
use std::collections::HashSet;
use std::collections::VecDeque;
use std::error::Error;
use std::fmt;
use std::fs;
use std::path::Path;
use std::path::PathBuf;
use tracing::error;
#[derive(Debug, Deserialize)]
struct SkillFrontmatter {
name: String,
description: String,
}
const SKILLS_FILENAME: &str = "SKILL.md";
const SKILLS_DIR_NAME: &str = "skills";
const REPO_ROOT_CONFIG_DIR_NAME: &str = ".codex";
const MAX_NAME_LEN: usize = 64;
const MAX_DESCRIPTION_LEN: usize = 1024;
#[derive(Debug)]
enum SkillParseError {
Read(std::io::Error),
MissingFrontmatter,
InvalidYaml(serde_yaml::Error),
MissingField(&'static str),
InvalidField { field: &'static str, reason: String },
}
impl fmt::Display for SkillParseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
SkillParseError::Read(e) => write!(f, "failed to read file: {e}"),
SkillParseError::MissingFrontmatter => {
write!(f, "missing YAML frontmatter delimited by ---")
}
SkillParseError::InvalidYaml(e) => write!(f, "invalid YAML: {e}"),
SkillParseError::MissingField(field) => write!(f, "missing field `{field}`"),
SkillParseError::InvalidField { field, reason } => {
write!(f, "invalid {field}: {reason}")
}
}
}
}
impl Error for SkillParseError {}
pub fn load_skills(config: &Config) -> SkillLoadOutcome {
if let Err(err) = install_system_skills(&config.code_home) {
tracing::error!("failed to install system skills: {err}");
}
load_skills_from_roots(skill_roots(config))
}
pub(crate) struct SkillRoot {
pub(crate) path: PathBuf,
pub(crate) scope: SkillScope,
}
pub(crate) fn load_skills_from_roots<I>(roots: I) -> SkillLoadOutcome
where
I: IntoIterator<Item = SkillRoot>,
{
let mut outcome = SkillLoadOutcome::default();
for root in roots {
discover_skills_under_root(&root.path, root.scope, &mut outcome);
}
let mut seen: HashSet<String> = HashSet::new();
outcome
.skills
.retain(|skill| seen.insert(skill.name.clone()));
outcome
.skills
.sort_by(|a, b| a.name.cmp(&b.name).then_with(|| a.path.cmp(&b.path)));
outcome
}
pub(crate) fn user_skills_root(config: &Config) -> SkillRoot {
let root = resolve_code_path_for_read(&config.code_home, Path::new(SKILLS_DIR_NAME));
SkillRoot {
path: root,
scope: SkillScope::User,
}
}
pub(crate) fn system_skills_root(config: &Config) -> SkillRoot {
SkillRoot {
path: system_cache_root_dir(&config.code_home),
scope: SkillScope::System,
}
}
pub(crate) fn repo_skills_root(cwd: &Path) -> Option<SkillRoot> {
let base = if cwd.is_dir() { cwd } else { cwd.parent()? };
let base = normalize_path(base).unwrap_or_else(|_| base.to_path_buf());
let repo_root =
resolve_root_git_project_for_trust(&base).map(|root| normalize_path(&root).unwrap_or(root));
let scope = SkillScope::Repo;
if let Some(repo_root) = repo_root.as_deref() {
for dir in base.ancestors() {
let skills_root = dir.join(REPO_ROOT_CONFIG_DIR_NAME).join(SKILLS_DIR_NAME);
if skills_root.is_dir() {
return Some(SkillRoot {
path: skills_root,
scope,
});
}
if dir == repo_root {
break;
}
}
return None;
}
let skills_root = base.join(REPO_ROOT_CONFIG_DIR_NAME).join(SKILLS_DIR_NAME);
skills_root.is_dir().then_some(SkillRoot {
path: skills_root,
scope,
})
}
fn skill_roots(config: &Config) -> Vec<SkillRoot> {
let mut roots = Vec::new();
if let Some(repo_root) = repo_skills_root(&config.cwd) {
roots.push(repo_root);
}
// Load order matters: we dedupe by name, keeping the first occurrence.
// This makes repo/user skills win over system skills.
roots.push(user_skills_root(config));
roots.push(system_skills_root(config));
roots
}
fn discover_skills_under_root(root: &Path, scope: SkillScope, outcome: &mut SkillLoadOutcome) {
let Ok(root) = normalize_path(root) else {
return;
};
if !root.is_dir() {
return;
}
// Follow symlinked directories for user and repo skills.
// System skills are managed by the tool itself, so symlinks are not followed.
let follow_symlinks = matches!(scope, SkillScope::User | SkillScope::Repo);
// Track visited directories to prevent infinite loops from circular symlinks.
let mut visited: HashSet<PathBuf> = HashSet::new();
visited.insert(root.clone());
let mut queue: VecDeque<PathBuf> = VecDeque::from([root]);
while let Some(dir) = queue.pop_front() {
let entries = match fs::read_dir(&dir) {
Ok(entries) => entries,
Err(e) => {
error!("failed to read skills dir {}: {e:#}", dir.display());
continue;
}
};
for entry in entries.flatten() {
let path = entry.path();
let file_name = match path.file_name().and_then(|f| f.to_str()) {
Some(name) => name,
None => continue,
};
if file_name.starts_with('.') {
continue;
}
let Ok(file_type) = entry.file_type() else {
continue;
};
if file_type.is_symlink() {
if !follow_symlinks {
continue;
}
// Resolve the symlink to determine what it points to.
let metadata = match fs::metadata(&path) {
Ok(m) => m,
Err(e) => {
error!("failed to stat skills entry {} (symlink): {e:#}", path.display());
continue;
}
};
if metadata.is_dir() {
// Canonicalize to detect cycles.
if let Ok(resolved) = normalize_path(&path) {
if visited.insert(resolved.clone()) {
queue.push_back(resolved);
}
}
}
// Symlinked files are not followed - only symlinked directories.
continue;
}
if file_type.is_dir() {
if let Ok(resolved) = normalize_path(&path) {
if visited.insert(resolved.clone()) {
queue.push_back(resolved);
}
} else {
queue.push_back(path);
}
continue;
}
if file_type.is_file() && file_name == SKILLS_FILENAME {
match parse_skill_file(&path, scope) {
Ok(skill) => {
outcome.skills.push(skill);
}
Err(err) => {
if scope != SkillScope::System {
outcome.errors.push(SkillError {
path,
message: err.to_string(),
});
}
}
}
}
}
}
}
fn parse_skill_file(path: &Path, scope: SkillScope) -> Result<SkillMetadata, SkillParseError> {
let contents = fs::read_to_string(path).map_err(SkillParseError::Read)?;
let frontmatter = extract_frontmatter(&contents).ok_or(SkillParseError::MissingFrontmatter)?;
let parsed: SkillFrontmatter =
serde_yaml::from_str(&frontmatter).map_err(SkillParseError::InvalidYaml)?;
let name = sanitize_single_line(&parsed.name);
let description = sanitize_single_line(&parsed.description);
validate_field(&name, MAX_NAME_LEN, "name")?;
validate_field(&description, MAX_DESCRIPTION_LEN, "description")?;
let resolved_path = normalize_path(path).unwrap_or_else(|_| path.to_path_buf());
Ok(SkillMetadata {
name,
description,
path: resolved_path,
scope,
content: contents,
})
}
fn sanitize_single_line(raw: &str) -> String {
raw.split_whitespace().collect::<Vec<_>>().join(" ")
}
fn validate_field(
value: &str,
max_len: usize,
field_name: &'static str,
) -> Result<(), SkillParseError> {
if value.is_empty() {
return Err(SkillParseError::MissingField(field_name));
}
if value.chars().count() > max_len {
return Err(SkillParseError::InvalidField {
field: field_name,
reason: format!("exceeds maximum length of {max_len} characters"),
});
}
Ok(())
}
fn extract_frontmatter(contents: &str) -> Option<String> {
let mut lines = contents.lines();
if !matches!(lines.next(), Some(line) if line.trim() == "---") {
return None;
}
let mut frontmatter_lines: Vec<&str> = Vec::new();
let mut found_closing = false;
for line in lines.by_ref() {
if line.trim() == "---" {
found_closing = true;
break;
}
frontmatter_lines.push(line);
}
if frontmatter_lines.is_empty() || !found_closing {
return None;
}
Some(frontmatter_lines.join("\n"))
}
#[cfg(test)]
mod tests {
use super::*;
use std::os::unix::fs::symlink;
use tempfile::TempDir;
fn write_skill(dir: &Path, name: &str, description: &str) -> PathBuf {
let skill_dir = dir.join(name);
fs::create_dir_all(&skill_dir).unwrap();
let skill_file = skill_dir.join("SKILL.md");
fs::write(
&skill_file,
format!("---\nname: {name}\ndescription: {description}\n---\n\n# Body\n"),
)
.unwrap();
skill_file
}
#[test]
fn follows_symlinked_directory_for_user_scope() {
let temp = TempDir::new().unwrap();
let skills_root = temp.path().join("skills");
fs::create_dir_all(&skills_root).unwrap();
// Create a skill in a separate directory
let shared = TempDir::new().unwrap();
write_skill(shared.path(), "shared-skill", "A shared skill");
// Symlink the shared directory into skills root
symlink(shared.path(), skills_root.join("shared")).unwrap();
let mut outcome = SkillLoadOutcome::default();
discover_skills_under_root(&skills_root, SkillScope::User, &mut outcome);
assert_eq!(outcome.skills.len(), 1);
assert_eq!(outcome.skills[0].name, "shared-skill");
}
#[test]
fn ignores_symlinked_directory_for_system_scope() {
let temp = TempDir::new().unwrap();
let skills_root = temp.path().join("skills");
fs::create_dir_all(&skills_root).unwrap();
// Create a skill in a separate directory
let shared = TempDir::new().unwrap();
write_skill(shared.path(), "shared-skill", "A shared skill");
// Symlink the shared directory into skills root
symlink(shared.path(), skills_root.join("shared")).unwrap();
let mut outcome = SkillLoadOutcome::default();
discover_skills_under_root(&skills_root, SkillScope::System, &mut outcome);
assert_eq!(outcome.skills.len(), 0, "System scope should ignore symlinks");
}
#[test]
fn handles_circular_symlink_without_infinite_loop() {
let temp = TempDir::new().unwrap();
let skills_root = temp.path().join("skills");
let cycle_dir = skills_root.join("cycle");
fs::create_dir_all(&cycle_dir).unwrap();
// Create a circular symlink
symlink(&cycle_dir, cycle_dir.join("loop")).unwrap();
// Also add a real skill to verify we still find it
write_skill(&cycle_dir, "real-skill", "A real skill");
let mut outcome = SkillLoadOutcome::default();
discover_skills_under_root(&skills_root, SkillScope::User, &mut outcome);
// Should find the real skill and not infinite loop
assert_eq!(outcome.skills.len(), 1);
assert_eq!(outcome.skills[0].name, "real-skill");
}
}