fairlead 0.20.1

Guardrails and a guided path for coding agents: rules enforced as the agent works, tests scoped to what a change can reach, capped project memory, and KPIs.
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
//! `skills sync`: each routed SKILL.md written in the format each agent
//! loads. Every file Fairlead writes carries a header line right after its
//! opening `---`, a YAML comment the front matter parser skips; the header
//! is how a later sync, `--check` and `--clean` tell Fairlead's files from
//! a person's, so a file without it is never overwritten or removed.

use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;

use fairlead_core::config::{SkillRoute, Skills};

use super::skill::{self, Skill};

/// The start of the header every generated file carries.
pub const MARK: &str = "# Generated by fairlead skills sync";

const CLAUDE_DIR: &str = ".claude/skills";
const AGENTS_DIR: &str = ".agents/skills";
const CURSOR_DIR: &str = ".cursor/rules";

/// One file sync owns: where it goes, what it holds, and the SKILL.md it's from.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Target {
    pub path: String,
    pub text: String,
    pub source: String,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum State {
    Missing,
    /// It has the header but not what sync would write: hand-edited, or its source moved on.
    Stale,
    Fresh,
    /// Something without the header is at the path, so it isn't Fairlead's to replace.
    Conflict,
}

#[derive(Debug, Default)]
pub struct Plan {
    pub files: Vec<(Target, State)>,
    /// Generated files no route asks for any more.
    pub orphans: Vec<String>,
    /// What stops a sync: a route that can't be read, a name that can't be a
    /// file name, two skills wanting one path.
    pub problems: Vec<String>,
    /// Files beside a copied SKILL.md that sync leaves where they are.
    pub not_copied: Vec<String>,
}

impl Plan {
    /// Every way the tree differs from what sync would leave, one line each.
    pub fn drift(&self) -> Vec<String> {
        let mut out = self.problems.clone();
        for (t, state) in &self.files {
            match state {
                State::Missing => out.push(format!("missing {}", t.path)),
                State::Stale => out.push(format!(
                    "stale {}: differs from what {} gives",
                    t.path, t.source
                )),
                State::Conflict => out.push(conflict(&t.path)),
                State::Fresh => {}
            }
        }
        for o in &self.orphans {
            out.push(format!("orphaned {o}: no route writes it"));
        }
        out
    }
}

pub fn conflict(path: &str) -> String {
    format!("conflict {path}: exists without the generated header; left alone")
}

fn header(source: &str, eol: &str) -> String {
    format!("{MARK} from {source}; edit that file, not this one.{eol}")
}

/// Whether `text` is a file sync wrote: its header follows the opening `---`.
pub fn is_generated(text: &str) -> bool {
    let mut lines = text.strip_prefix('\u{feff}').unwrap_or(text).lines();
    lines.next().map(str::trim_end) == Some("---")
        && lines.next().is_some_and(|l| l.starts_with(MARK))
}

/// Where the front matter's opening line ends and where the body starts,
/// as byte offsets; `None` when the text has no closed `---` block.
fn front_matter(text: &str) -> Option<(usize, usize)> {
    let bom = if text.starts_with('\u{feff}') { 3 } else { 0 };
    let rest = &text[bom..];
    let open = if rest.starts_with("---\n") {
        4
    } else if rest.starts_with("---\r\n") {
        5
    } else {
        return None;
    };
    let mut at = bom + open;
    for line in text[at..].split_inclusive('\n') {
        at += line.len();
        if line.trim_end() == "---" {
            return Some((bom + open, at));
        }
    }
    None
}

/// A SKILL.md copy: the source byte for byte with the header after its
/// opening `---`. A source without front matter gets one holding the header
/// and its name, since the open format reads the name from there.
pub fn copy(text: &str, source: &str, name: &str) -> String {
    match front_matter(text) {
        Some((open_end, _)) => {
            let eol = if text[..open_end].ends_with("\r\n") {
                "\r\n"
            } else {
                "\n"
            };
            format!(
                "{}{}{}",
                &text[..open_end],
                header(source, eol),
                &text[open_end..]
            )
        }
        None => format!("---\n{}name: {name}\n---\n{text}", header(source, "\n")),
    }
}

/// A Cursor rule: the description and globs Cursor reads to decide when to
/// attach it, then the SKILL.md's body. Globs are written unquoted and
/// comma-joined, the way Cursor's own editor writes them.
pub fn mdc(text: &str, source: &str, description: &str, globs: &[String], always: bool) -> String {
    let body = front_matter(text).map_or(text, |(_, start)| &text[start..]);
    let mut out = format!("---\n{}", header(source, "\n"));
    if !description.is_empty() {
        let quoted = serde_json::to_string(description).expect("a string serializes");
        out.push_str(&format!("description: {quoted}\n"));
    }
    if !always && !globs.is_empty() {
        out.push_str(&format!("globs: {}\n", globs.join(",")));
    }
    out.push_str(&format!("alwaysApply: {always}\n---\n{body}"));
    out
}

/// The globs a route covers: its `paths`, then each of its modules' roots;
/// a module that doesn't resolve adds nothing.
pub fn globs(route: &SkillRoute, module_roots: &dyn Fn(&str) -> Vec<String>) -> Vec<String> {
    let mut out = route.paths.clone();
    for m in &route.modules {
        for root in module_roots(m) {
            let glob = if root.is_empty() {
                "**".to_string()
            } else {
                format!("{root}/**")
            };
            if !out.contains(&glob) {
                out.push(glob);
            }
        }
    }
    out
}

/// A name that can be a directory or file name in every target as it is.
fn safe_name(name: &str) -> bool {
    !name.is_empty()
        && !name.starts_with('.')
        && name
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
}

/// The directory that holds the skill's own directory: `.claude/skills` for
/// `.claude/skills/forms/SKILL.md`.
fn home(source: &str) -> Option<&str> {
    let source = source.trim_start_matches("./");
    let (dir, _) = source.rsplit_once('/')?;
    dir.rsplit_once('/').map(|(home, _)| home)
}

/// Files and directories beside a SKILL.md, from the repository root.
fn siblings(root: &Path, source: &str) -> Vec<String> {
    let Some((dir, _)) = source.rsplit_once('/') else {
        return Vec::new();
    };
    let Ok(entries) = std::fs::read_dir(root.join(dir)) else {
        return Vec::new();
    };
    let mut out: Vec<String> = entries
        .filter_map(Result::ok)
        .filter(|e| e.file_name() != "SKILL.md")
        .map(|e| {
            let slash = if e.path().is_dir() { "/" } else { "" };
            format!("{dir}/{}{slash}", e.file_name().to_string_lossy())
        })
        .collect();
    out.sort();
    out
}

/// What each target wants for one skill, keyed by target path.
fn render(
    skill: &Skill,
    route: &SkillRoute,
    text: &str,
    targets: &[String],
    module_roots: &dyn Fn(&str) -> Vec<String>,
) -> Vec<Target> {
    let mut out = Vec::new();
    let source = &skill.path;
    for target in targets {
        let (dir, path, body) = match target.as_str() {
            "claude" => (
                CLAUDE_DIR,
                format!("{CLAUDE_DIR}/{}/SKILL.md", skill.name),
                copy(text, source, &skill.name),
            ),
            "agents" => (
                AGENTS_DIR,
                format!("{AGENTS_DIR}/{}/SKILL.md", skill.name),
                copy(text, source, &skill.name),
            ),
            "cursor" => (
                CURSOR_DIR,
                format!("{CURSOR_DIR}/{}.mdc", skill.name),
                mdc(
                    text,
                    source,
                    &skill.description,
                    &globs(route, module_roots),
                    route.always,
                ),
            ),
            _ => continue,
        };
        if home(source) == Some(dir) {
            continue;
        }
        out.push(Target {
            path,
            text: body,
            source: source.clone(),
        });
    }
    out
}

/// Every generated file in the places sync writes, whatever the config says,
/// so dropping a target or a route still finds what it left.
pub fn generated(root: &Path) -> Vec<String> {
    let mut candidates = Vec::new();
    for dir in [CLAUDE_DIR, AGENTS_DIR] {
        if let Ok(entries) = std::fs::read_dir(root.join(dir)) {
            for e in entries.filter_map(Result::ok) {
                let name = e.file_name().to_string_lossy().into_owned();
                candidates.push(format!("{dir}/{name}/SKILL.md"));
            }
        }
    }
    if let Ok(entries) = std::fs::read_dir(root.join(CURSOR_DIR)) {
        for e in entries.filter_map(Result::ok) {
            let name = e.file_name().to_string_lossy().into_owned();
            if name.ends_with(".mdc") {
                candidates.push(format!("{CURSOR_DIR}/{name}"));
            }
        }
    }
    let mut out: Vec<String> = candidates
        .into_iter()
        .filter(|p| std::fs::read_to_string(root.join(p)).is_ok_and(|t| is_generated(&t)))
        .collect();
    out.sort();
    out
}

/// What sync would write, keep and remove, compared with the tree as it is.
pub fn plan(root: &Path, skills: &Skills, module_roots: &dyn Fn(&str) -> Vec<String>) -> Plan {
    let mut plan = Plan::default();
    let (loaded, bad) = skill::load(root, skills);
    for b in bad {
        plan.problems
            .push(format!("bad-skill {}: {}", b.path, b.reason));
    }
    let targets = skills.targets.items();
    let mut wanted: BTreeMap<String, Target> = BTreeMap::new();
    let mut noted = BTreeSet::new();
    for s in &loaded {
        let Some(route) = skills.routes.items().iter().find(|r| r.skill == s.path) else {
            continue;
        };
        if !safe_name(&s.name) {
            plan.problems.push(format!(
                "bad-name {}: `{}` can't be a file name; use letters, digits, `-`, `_` and `.`",
                s.path, s.name
            ));
            continue;
        }
        let Ok(text) = std::fs::read_to_string(root.join(&s.path)) else {
            continue;
        };
        for t in render(s, route, &text, targets, module_roots) {
            if !t.path.ends_with(".mdc") && noted.insert(s.path.clone()) {
                plan.not_copied.extend(siblings(root, &s.path));
            }
            if let Some(other) = wanted.get(&t.path) {
                plan.problems.push(format!(
                    "clash {}: both {} and {} would write it; give one a different `name`",
                    t.path, other.source, t.source
                ));
                continue;
            }
            wanted.insert(t.path.clone(), t);
        }
    }
    for t in wanted.into_values() {
        let state = match std::fs::read_to_string(root.join(&t.path)) {
            Err(_) => State::Missing,
            Ok(have) if !is_generated(&have) => State::Conflict,
            Ok(have) if have == t.text => State::Fresh,
            Ok(_) => State::Stale,
        };
        plan.files.push((t, state));
    }
    plan.orphans = generated(root)
        .into_iter()
        .filter(|p| !plan.files.iter().any(|(t, _)| &t.path == p))
        .collect();
    plan
}

#[cfg(test)]
mod tests {
    use super::*;
    use fairlead_core::config::List;

    const SKILL: &str = "---\nname: forms\ndescription: How forms validate.\nallowed-tools: Read\n---\nUse the schema.\n";

    fn route(paths: &[&str], modules: &[&str], always: bool) -> SkillRoute {
        SkillRoute {
            skill: "skills/forms/SKILL.md".into(),
            paths: paths.iter().map(|s| s.to_string()).collect(),
            modules: modules.iter().map(|s| s.to_string()).collect(),
            always,
        }
    }

    fn no_modules(_: &str) -> Vec<String> {
        Vec::new()
    }

    #[test]
    fn a_copy_keeps_the_front_matter_and_body_and_puts_the_header_first_inside_it() {
        let out = copy(SKILL, "skills/forms/SKILL.md", "forms");
        let mut lines = out.lines();
        assert_eq!(lines.next(), Some("---"));
        assert_eq!(
            lines.next(),
            Some("# Generated by fairlead skills sync from skills/forms/SKILL.md; edit that file, not this one.")
        );
        let without: String = out
            .lines()
            .filter(|l| !l.starts_with(MARK))
            .map(|l| format!("{l}\n"))
            .collect();
        assert_eq!(without, SKILL, "byte for byte apart from the header");
        assert!(is_generated(&out));
        assert!(!is_generated(SKILL));
    }

    #[test]
    fn a_copy_keeps_crlf_line_ends_and_a_source_without_front_matter_gets_one() {
        let crlf = SKILL.replace('\n', "\r\n");
        let out = copy(&crlf, "s/SKILL.md", "forms");
        assert!(out.starts_with(&format!("---\r\n{MARK} from s/SKILL.md")));
        assert_eq!(out.replacen(&header("s/SKILL.md", "\r\n"), "", 1), crlf);
        assert!(is_generated(&out));

        let bare = copy("Just a body\n", "s/SKILL.md", "bare");
        assert!(bare.starts_with("---\n# Generated"), "{bare}");
        assert!(bare.ends_with("name: bare\n---\nJust a body\n"), "{bare}");
    }

    #[test]
    fn a_cursor_rule_has_the_description_the_route_globs_and_the_body() {
        let out = mdc(
            SKILL,
            "skills/forms/SKILL.md",
            "How forms validate.",
            &["src/forms/**".into(), "**/*.form.ts".into()],
            false,
        );
        assert_eq!(
            out,
            format!(
                "---\n{}description: \"How forms validate.\"\nglobs: src/forms/**,**/*.form.ts\nalwaysApply: false\n---\nUse the schema.\n",
                header("skills/forms/SKILL.md", "\n")
            )
        );
        assert!(is_generated(&out));
    }

    #[test]
    fn an_always_route_applies_always_and_a_route_with_no_globs_is_left_to_the_description() {
        let always = mdc(SKILL, "s", "d", &["src/**".into()], true);
        assert!(always.contains("alwaysApply: true\n"), "{always}");
        assert!(!always.contains("globs:"), "{always}");
        let unresolved = globs(&route(&[], &["core"], false), &no_modules);
        assert!(unresolved.is_empty());
        let requested = mdc(SKILL, "s", "d", &unresolved, false);
        assert!(!requested.contains("globs:"), "{requested}");
        assert!(requested.contains("alwaysApply: false\n"), "{requested}");
    }

    #[test]
    fn module_routes_glob_their_module_roots_after_the_paths() {
        let roots = |m: &str| match m {
            "core" => vec!["packages/core".to_string()],
            "top" => vec![String::new()],
            _ => Vec::new(),
        };
        assert_eq!(
            globs(
                &route(&["docs/**"], &["core", "top", "gone"], false),
                &roots
            ),
            ["docs/**", "packages/core/**", "**"]
        );
    }

    #[test]
    fn a_source_already_in_a_targets_place_is_not_copied_there() {
        let dir = std::env::temp_dir().join(format!("fairlead-sync-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(dir.join(".claude/skills/forms/scripts")).unwrap();
        std::fs::write(dir.join(".claude/skills/forms/SKILL.md"), SKILL).unwrap();
        let skills = Skills {
            routes: List::Items(vec![SkillRoute {
                skill: ".claude/skills/forms/SKILL.md".into(),
                ..route(&["src/forms/**"], &[], false)
            }]),
            ..Skills::default()
        };
        let plan = plan(&dir, &skills, &no_modules);
        let paths: Vec<&str> = plan.files.iter().map(|(t, _)| t.path.as_str()).collect();
        assert_eq!(
            paths,
            [".agents/skills/forms/SKILL.md", ".cursor/rules/forms.mdc"]
        );
        assert!(plan.files.iter().all(|(_, s)| *s == State::Missing));
        assert_eq!(plan.not_copied, [".claude/skills/forms/scripts/"]);
        assert!(plan.problems.is_empty(), "{:?}", plan.problems);
    }

    #[test]
    fn a_name_that_cant_be_a_file_name_is_a_problem() {
        assert!(safe_name("web-forms_2.x"));
        for bad in ["", "../up", "a/b", ".hidden", "with space"] {
            assert!(!safe_name(bad), "{bad}");
        }
    }
}