silcrow 0.2.1

Deterministic CLI for a citable, checkable graph of laws in a git tree.
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
use anyhow::Result;
use std::path::{Path, PathBuf};

const SKILL_PATH: &str = ".agents/skills/silcrow/SKILL.md";
/// Any of these marks a skill file as one a Silcrow binary wrote, an older one included.
const SKILL_OURS: [&str; 3] = [
    "delegate to silcrow skill",
    "thin pointer to the silcrow CLI",
    "\nname: silcrow\n",
];
/// Copies an older Silcrow left in native skill directories. Only `eject` reads them.
const NATIVE_SKILLS: [&str; 4] = [
    ".cursor/skills/silcrow/SKILL.md",
    ".claude/skills/silcrow/SKILL.md",
    ".codex/skills/silcrow/SKILL.md",
    ".opencode/skills/silcrow/SKILL.md",
];

fn skill_is_ours(text: &str) -> bool {
    SKILL_OURS.iter().any(|mark| text.contains(mark))
}

fn read_if_present(path: &Path) -> Result<Option<String>> {
    match std::fs::read_to_string(path) {
        Ok(text) => Ok(Some(text)),
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(None),
        Err(err) => Err(anyhow::Error::new(err).context(format!("read {}", path.display()))),
    }
}

/// Every copy of the skill under `root` that is ours, so `eject` may delete it.
pub fn skill_copies(root: &Path) -> Result<Vec<PathBuf>> {
    // § k3v7hb6mk.e@zdb6j
    let mut out = Vec::new();
    for rel in std::iter::once(SKILL_PATH).chain(NATIVE_SKILLS) {
        let path = root.join(rel);
        if read_if_present(&path)?.is_some_and(|text| skill_is_ours(&text)) {
            out.push(path);
        }
    }
    Ok(out)
}

/// Skills named `silcrow` in a home skill directory, which an agent may load before the repo pointer.
pub fn home_skills(home: &Path, ws_root: &Path) -> Vec<PathBuf> {
    let home_is_root = std::fs::canonicalize(home).ok() == std::fs::canonicalize(ws_root).ok();
    std::iter::once(SKILL_PATH)
        .filter(|_| !home_is_root)
        .chain(NATIVE_SKILLS)
        .filter_map(|rel| Path::new(rel).parent())
        .map(|dir| home.join(dir))
        .filter(|dir| dir.exists())
        .collect()
}

/// Writes the skill pointer, and leaves a file at its path that is not ours alone.
pub fn install_skill(root: &Path, dry_run: bool) -> Result<()> {
    // § k3v7hb6mk.b@tbdfd
    let path = root.join(SKILL_PATH);
    let old = read_if_present(&path)?;
    let body = crate::write::keep_line_endings(
        old.as_deref().unwrap_or_default(),
        &crate::skill::pointer(),
    );
    match old.as_deref() {
        Some(text) if text == body => Ok(()),
        Some(text) if !skill_is_ours(text) => {
            eprintln!(
                "left {} alone: it is not the Silcrow skill pointer",
                path.display()
            );
            Ok(())
        }
        old => write_file(root, &path, old.unwrap_or_default(), &body, dry_run),
    }
}

/// Writes one harness file, or in a dry run prints the diff of what it would write.
pub fn write_file(root: &Path, path: &Path, old: &str, body: &str, dry_run: bool) -> Result<()> {
    // § z50y8eyxx.a@c9qb3
    if dry_run {
        crate::write::print_diff(path.strip_prefix(root).unwrap_or(path), old, body);
        return Ok(());
    }
    crate::walk::forget();
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    std::fs::write(path, body)?;
    eprintln!("wrote {}", path.display());
    Ok(())
}

// § yymjgaqr0.a@t2k52
const OPEN_TAG: &str = "<silcrow";
const CLOSE_TAG: &str = "</silcrow>";
// § end yymjgaqr0.a

/// A component that differs from what this binary writes. Git versions the
/// `AGENTS.md` block and the skill pointer; hooks are local to one clone.
pub struct Drift {
    pub path: PathBuf,
    pub versioned: bool,
    /// The line to add to a hook another tool wrote, which `install` leaves.
    pub add: Option<String>,
    /// The main checkout whose `install` writes this hook, read from a linked worktree.
    pub install_in: Option<PathBuf>,
    /// What manages the hooks, where `install` writes none, with the line to add to this one.
    pub manager: Option<(String, String)>,
}

/// The `AGENTS.md` block of one project, when it differs. Reads and writes nothing else.
pub fn project_drift(project: &Path) -> Result<Option<Drift>> {
    // § fgbh1bkcj@d6tqr
    let Some(branch) = default_branch_attr(project) else {
        return Ok(Some(Drift {
            path: project.join("AGENTS.md"),
            versioned: true,
            add: None,
            install_in: None,
            manager: None,
        }));
    };
    Ok(agents_restore(project, &branch)?.map(|(path, _)| Drift {
        path,
        versioned: true,
        add: None,
        install_in: None,
        manager: None,
    }))
}

fn default_branch_attr(project: &Path) -> Option<String> {
    let text = std::fs::read_to_string(project.join("AGENTS.md")).ok()?;
    crate::scheme::attr_from_agents(&text, "default-branch")
}

/// How a drifted component reads: absent, or present and different.
pub fn drift_label(d: &Drift) -> String {
    // § fgbh1bkcj.e@77b4f
    if let Some(line) = &d.add {
        let root = d.path.parent().unwrap_or(&d.path);
        match crate::hook::foreign_origin(root, &d.path) {
            Some(origin) => format!(
                "{} is a hook Silcrow did not write, not installed, and `silcrow install` leaves it: {origin}, `{line}`",
                d.path.display()
            ),
            None => format!(
                "{} is a hook of another tool, not installed: Silcrow does not read it and `silcrow install` leaves it. To run Silcrow there, add `{line}` to it",
                d.path.display()
            ),
        }
    } else if d.path.exists() {
        format!("{} differs from this binary", d.path.display())
    } else {
        format!("{} is missing", d.path.display())
    }
}

/// A drifted component and what fixes it.
pub fn drift_text(d: &Drift) -> String {
    // § hqv22s05t.e@2wcdg
    if let Some((manager, line)) = &d.manager {
        // § hqv22s05t.f@zhtvz
        let state = match d.path.exists() {
            true => "runs no Silcrow script of its own",
            false => "is missing",
        };
        return format!(
            "{} {state}: {manager} manages this repository's git hooks, so `silcrow install` writes none. Add `{line}` to that hook where {manager} runs it.",
            d.path.display()
        );
    }
    match &d.install_in {
        Some(main) => format!(
            "{}. Run `silcrow install` in the main checkout {}, whose hooks this worktree runs.",
            drift_label(d),
            main.display()
        ),
        None => format!("{}. Run `silcrow install`.", drift_label(d)),
    }
}

/// The skill pointer and the hooks, which live once at the workspace root.
pub fn workspace_drift(ws_root: &Path) -> Result<Vec<Drift>> {
    // § ave4h4m3g.a@zv354
    let mut out = Vec::new();
    // § fgbh1bkcj.a@2k685
    let skill = ws_root.join(SKILL_PATH);
    if ws_root.join(".git").exists()
        && read_if_present(&skill)?.as_deref() != Some(crate::skill::pointer().as_str())
    {
        out.push(Drift {
            path: skill,
            versioned: true,
            add: None,
            install_in: None,
            manager: None,
        });
    }
    let hooks = crate::hook::drift(ws_root)?;
    let (install_in, manager) = match hooks.is_empty() {
        true => (None, None),
        false => (
            crate::hook::main_checkout(ws_root)?,
            crate::hook::hook_manager(ws_root)?,
        ),
    };
    for (path, add) in hooks {
        // § hqv22s05t.f@e29nt
        let event = path
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or_default();
        let manager = manager
            .clone()
            .map(|m| (m, crate::hook::call_line(ws_root, event)));
        out.push(Drift {
            path,
            versioned: false,
            add: add.filter(|_| manager.is_none()),
            install_in: install_in.clone(),
            manager,
        });
    }
    // § end fgbh1bkcj.a
    Ok(out)
}

/// What the probe of `check` reads of `workspace_drift`: not a hook another tool wrote, which
/// the user cannot clear, and not the hooks in a CI job, which has none, or in a workspace whose
/// git root is no project, whose hooks belong to the repository that holds its projects.
pub fn probe_drift(ws_root: &Path) -> Result<Vec<Drift>> {
    // § fgbh1bkcj.d@zdmb2
    let ci = std::env::var("CI").ok();
    // § fgbh1bkcj.f@zdbr2
    let own_hooks = crate::walk::is_project(ws_root);
    probe_drift_in(ws_root, crate::notice::ci_job(ci.as_deref()) || !own_hooks)
    // § end fgbh1bkcj.f
}

/// `workspace_drift` without a hook another tool wrote, and without the hooks when `no_hooks`.
fn probe_drift_in(ws_root: &Path, no_hooks: bool) -> Result<Vec<Drift>> {
    // § fgbh1bkcj.e@ae3sb
    let mut drift = workspace_drift(ws_root)?;
    drift.retain(|d| d.add.is_none() && (d.versioned || !no_hooks));
    Ok(drift)
}

/// Prints the drift of a command that is not `check`: the skill pointer and the `AGENTS.md`
/// block, never a git hook. The exit code is unchanged.
pub fn report_drift(ws_root: &Path, project: Option<&Path>) -> Result<()> {
    // § fgbh1bkcj.c@7pmn4
    let mut drift = probe_drift(ws_root)?;
    drift.retain(|d| d.versioned);
    if let Some(project) = project {
        drift.extend(project_drift(project)?);
    }
    if drift.is_empty() {
        return Ok(());
    }
    for d in &drift {
        eprintln!("{}", drift_label(d));
    }
    eprintln!("run `silcrow install` to write them");
    Ok(())
}

/// The `AGENTS.md` block and the git hooks, written by `silcrow install`.
pub fn install_block_and_hooks(ws_root: &Path, project: &Path, dry_run: bool) -> Result<()> {
    // § ave4h4m3g.b@4mt3v
    // § yymjgaqr0.c@jtgg5
    let branch = match default_branch_attr(project) {
        Some(branch) => branch,
        None => crate::published::default_branch(ws_root)?,
    };
    // § end yymjgaqr0.c
    ensure_agents(ws_root, project, &branch, dry_run)?;
    crate::hook::install(ws_root, dry_run)
}

/// The path and the text `AGENTS.md` should hold, when it differs.
fn agents_restore(root: &Path, branch: &str) -> Result<Option<(PathBuf, String)>> {
    // § yymjgaqr0.b@4g1z4
    let path = root.join("AGENTS.md");
    let notes = agents_notes(&path);
    let policy = match crate::policy::ProjectPolicy::from_root(root) {
        Ok(policy) => policy,
        Err(_) if path.is_file() => return Ok(None),
        Err(_) => crate::policy::ProjectPolicy::defaults(),
    };
    let canonical = canonical_block(&notes, branch, &policy);
    if !path.is_file() {
        return Ok(Some((path, format!("{canonical}\n"))));
    }
    let text = std::fs::read_to_string(&path)?;
    Ok(restore_agents_text(&text, &canonical).map(|restored| (path, restored)))
}

fn ensure_agents(ws_root: &Path, root: &Path, branch: &str, dry_run: bool) -> Result<()> {
    let Some((path, restored)) = agents_restore(root, branch)? else {
        return Ok(());
    };
    let old = read_if_present(&path)?.unwrap_or_default();
    let restored = crate::write::keep_line_endings(&old, &restored);
    if restored == old {
        return Ok(());
    }
    write_file(ws_root, &path, &old, &restored, dry_run)
}

/// The `notes` list the block at `path` writes, its words joined by one space, or the
/// default list when it writes none.
fn agents_notes(path: &Path) -> String {
    std::fs::read_to_string(path)
        .ok()
        .and_then(|text| crate::scheme::attr_from_agents(&text, "notes"))
        .map_or_else(
            || crate::walk::DEFAULT_NOTES.to_string(),
            |list| list.split_whitespace().collect::<Vec<_>>().join(" "),
        )
}

pub(crate) fn block_range(text: &str) -> Option<(usize, usize)> {
    let start = text.find(OPEN_TAG)?;
    let end = start + text[start..].find(CLOSE_TAG)? + CLOSE_TAG.len();
    Some((start, end))
}

/// `AGENTS.md` without its Silcrow block and the blank line `install` puts after it.
pub fn strip_block(text: &str) -> Option<String> {
    let (start, mut end) = block_range(text)?;
    for _ in 0..2 {
        if text[end..].starts_with("\r\n") {
            end += 2;
        } else if text[end..].starts_with('\n') {
            end += 1;
        }
    }
    Some(format!("{}{}", &text[..start], &text[end..]))
}

fn block_is_well_formed(text: &str, canonical: &str) -> bool {
    let Some((start, end)) = block_range(text) else {
        return false;
    };
    &text[start..end] == canonical
}

fn restore_agents_text(text: &str, canonical: &str) -> Option<String> {
    // § yymjgaqr0.f@64mgj
    if block_is_well_formed(text, canonical) {
        return None;
    }
    if let Some((start, end)) = block_range(text) {
        let mut out = String::new();
        out.push_str(&text[..start]);
        out.push_str(canonical);
        out.push_str(&text[end..]);
        return Some(out);
    }
    if text.trim().is_empty() {
        return Some(format!("{canonical}\n"));
    }
    Some(format!("{canonical}\n\n{text}"))
}

// § one yymjgaqr0.e@f8mhp
const PRINCIPLES: &str = "Engineering principles:\n\
    - Locality: keep behavior, data, and decisions close to where they are used, and fix a shared defect once at its source.\n\
    - Explicitness: make inputs, outputs, dependencies, and failure modes visible.\n\
    - Economy: use the smallest mechanism that completely solves the problem, reusing existing code before adding any, and finish every caller, test, and fixture it touches.\n\
    - Stability: preserve observable behavior, including error handling and validation, across refactors unless a law changes it.\n\
    - Decisions: state each law as a business decision, in plain and abstract words a person can reason about and steer behavior with, never as a restatement of the code, and leave out any value or detail with no reason behind it.\n\
    - Verifiability: prefer deterministic behavior that can be checked directly, leave a test for new non-trivial logic, and name what was skipped or left unchecked.\n\
    - Order: make it work, then make it right, then make it fast only when a measured need or a law demands it.\n";

/// The block for `policy`, with every attribute written: one the block omits at its default.
fn canonical_block(notes: &str, branch: &str, policy: &crate::policy::ProjectPolicy) -> String {
    // § yymjgaqr0.d@vxcj7
    let (tests, words) = (policy.tests_attr(), policy.note_words_attr());
    let duties: String = [
        ("code", policy.code_attr()),
        ("docs", policy.docs_attr()),
        ("tests", tests.as_str()),
        ("test-markers", policy.test_markers.attr()),
        ("note-words", words.as_str()),
    ]
    .into_iter()
    .map(|(attr, value)| format!(" {attr}=\"{value}\""))
    .collect();
    format!(
        "<silcrow notes=\"{notes}\" default-branch=\"{branch}\"{duties}>\n\
         This repo follows [Silcrow](https://github.com/zifeo/silcrow).\n\
         Decisions: `{notes}`. Usage: `silcrow help`.\n\
         {PRINCIPLES}</silcrow>"
    )
}

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

    #[test]
    fn restores_missing_agents_file() {
        let dir = tempfile::tempdir().unwrap();
        ensure_agents(dir.path(), dir.path(), "main", false).unwrap();
        let text = std::fs::read_to_string(dir.path().join("AGENTS.md")).unwrap();
        assert!(block_is_well_formed(
            &text,
            &canonical_block(
                crate::walk::DEFAULT_NOTES,
                "main",
                &crate::policy::ProjectPolicy::defaults(),
            )
        ));
        assert!(
            text.starts_with("<silcrow notes=\"docs/decisions/**/*.md\" default-branch=\"main\" code=\"**/*\" docs=\"\" tests=\"conventions\" test-markers=\"error\" note-words=\"error:3000\">"),
            "{text}"
        );
    }

    #[test]
    fn install_keeps_a_tests_list_the_block_writes() {
        let dir = tempfile::tempdir().unwrap();
        let block = "<silcrow notes=\"docs/decisions/**/*.md\" default-branch=\"main\" code=\"**/*\" docs=\"\" tests=\"spec/**\">\nx\n</silcrow>\n";
        std::fs::write(dir.path().join("AGENTS.md"), block).unwrap();
        let (_, text) = agents_restore(dir.path(), "main").unwrap().unwrap();
        assert!(
            text.contains(" docs=\"\" tests=\"spec/**\" test-markers=\"error\""),
            "{text}"
        );
        std::fs::write(dir.path().join("AGENTS.md"), &text).unwrap();
        assert_eq!(agents_restore(dir.path(), "main").unwrap(), None);
    }

    #[test]
    fn install_writes_the_default_of_each_attribute_a_block_omits() {
        let dir = tempfile::tempdir().unwrap();
        let block = "<silcrow notes=\"docs/decisions/**/*.md\" default-branch=\"main\" docs=\"\" test-markers=\"warn\">\nx\n</silcrow>\n";
        std::fs::write(dir.path().join("AGENTS.md"), block).unwrap();
        let (_, text) = agents_restore(dir.path(), "main").unwrap().unwrap();
        assert!(
            text.starts_with("<silcrow notes=\"docs/decisions/**/*.md\" default-branch=\"main\" code=\"**/*\" docs=\"\" tests=\"conventions\" test-markers=\"warn\" note-words=\"error:3000\">"),
            "{text}"
        );
        std::fs::write(dir.path().join("AGENTS.md"), &text).unwrap();
        assert_eq!(agents_restore(dir.path(), "main").unwrap(), None);
    }

    #[test]
    fn install_leaves_a_block_with_doc_or_pin_alone() {
        for original in [
            "<silcrow doc=\"optional\">\nx\n</silcrow>\n",
            "<silcrow notes=\"docs/decisions/**/*.md\" pin=\"optional\">\nx\n</silcrow>\n",
        ] {
            let dir = tempfile::tempdir().unwrap();
            std::fs::write(dir.path().join("AGENTS.md"), original).unwrap();
            assert_eq!(agents_restore(dir.path(), "main").unwrap(), None);
        }
    }

    #[test]
    fn a_custom_decisions_list_is_kept_with_its_words_joined() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("AGENTS.md"),
            "<silcrow notes=\"docs/**/*.md   !docs/archive/**\">\nx\n</silcrow>\n",
        )
        .unwrap();
        let (_, text) = agents_restore(dir.path(), "main").unwrap().unwrap();
        assert!(
            text.starts_with(
                "<silcrow notes=\"docs/**/*.md !docs/archive/**\" default-branch=\"main\""
            ),
            "{text}"
        );
        assert!(
            text.contains("Decisions: `docs/**/*.md !docs/archive/**`."),
            "{text}"
        );
    }

    #[test]
    fn restores_missing_block() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("AGENTS.md"), "# hi\n").unwrap();
        ensure_agents(dir.path(), dir.path(), "main", false).unwrap();
        let text = std::fs::read_to_string(dir.path().join("AGENTS.md")).unwrap();
        assert!(text.contains("notes=\"docs/decisions/**/*.md\""));
        assert!(text.contains("# hi"));
    }

    #[test]
    fn accepts_present_block() {
        let dir = tempfile::tempdir().unwrap();
        let block = canonical_block(
            crate::walk::DEFAULT_NOTES,
            "main",
            &crate::policy::ProjectPolicy::defaults(),
        );
        std::fs::write(dir.path().join("AGENTS.md"), format!("{block}\n")).unwrap();
        assert!(ensure_agents(dir.path(), dir.path(), "main", false).is_ok());
        let text = std::fs::read_to_string(dir.path().join("AGENTS.md")).unwrap();
        assert_eq!(text, format!("{block}\n"));
    }

    #[test]
    fn dry_run_does_not_write() {
        let dir = tempfile::tempdir().unwrap();
        assert!(!dir.path().join("AGENTS.md").exists());
        ensure_agents(dir.path(), dir.path(), "main", true).unwrap();
        assert!(!dir.path().join("AGENTS.md").exists());
    }

    #[test]
    fn leaves_unknown_policy_value_alone() {
        let dir = tempfile::tempdir().unwrap();
        let original = "<silcrow test-markers=\"maybe\">\nGraph: silcrow check.\n</silcrow>\n";
        std::fs::write(dir.path().join("AGENTS.md"), original).unwrap();
        ensure_agents(dir.path(), dir.path(), "main", false).unwrap();
        let text = std::fs::read_to_string(dir.path().join("AGENTS.md")).unwrap();
        assert_eq!(text, original);
    }

    #[test]
    fn install_skills_writes_only_agents() {
        // § k3v7hb6mk.b@kq8eg
        let dest = tempfile::tempdir().unwrap();
        install_skill(dest.path(), false).unwrap();
        let pointer = crate::skill::pointer();
        let text =
            std::fs::read_to_string(dest.path().join(".agents/skills/silcrow/SKILL.md")).unwrap();
        assert_eq!(text, pointer);
        for rel in [
            ".cursor/skills/silcrow/SKILL.md",
            ".claude/skills/silcrow/SKILL.md",
            ".codex/skills/silcrow/SKILL.md",
            ".opencode/skills/silcrow/SKILL.md",
        ] {
            assert!(!dest.path().join(rel).exists(), "{rel}");
        }
    }

    #[test]
    fn install_skills_leaves_unmanaged_files() {
        let dest = tempfile::tempdir().unwrap();
        let foreign = dest.path().join(".agents/skills/silcrow/SKILL.md");
        std::fs::create_dir_all(foreign.parent().unwrap()).unwrap();
        std::fs::write(&foreign, "# mine\n").unwrap();
        install_skill(dest.path(), false).unwrap();
        assert_eq!(std::fs::read_to_string(&foreign).unwrap(), "# mine\n");
        assert!(skill_copies(dest.path()).unwrap().is_empty());
    }

    #[test]
    fn pointer_frontmatter_is_its_name_and_description() {
        let pointer = crate::skill::pointer();
        let front = pointer
            .strip_prefix("---\n")
            .and_then(|rest| rest.split_once("\n---\n"))
            .map(|(front, _)| front)
            .unwrap();
        let keys: Vec<&str> = front
            .lines()
            .map(|line| line.split_once(':').unwrap().0)
            .collect();
        assert_eq!(keys, ["name", "description"]);
    }

    #[test]
    fn committed_pointer_matches_this_binary() {
        let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
        let text = std::fs::read_to_string(root.join(".agents/skills/silcrow/SKILL.md")).unwrap();
        assert_eq!(text, crate::skill::pointer());
    }

    #[test]
    fn install_skills_refreshes_stale_pointer() {
        let dest = tempfile::tempdir().unwrap();
        let path = dest.path().join(".agents/skills/silcrow/SKILL.md");
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(
            &path,
            "---\nname: silcrow\ndescription: old\n---\n\nThis skill is a thin pointer to the silcrow CLI.\n",
        )
        .unwrap();
        install_skill(dest.path(), false).unwrap();
        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            crate::skill::pointer()
        );
    }

    #[test]
    fn install_skill_dry_run_writes_nothing() {
        let dest = tempfile::tempdir().unwrap();
        install_skill(dest.path(), true).unwrap();
        assert!(!dest.path().join(SKILL_PATH).exists());
    }

    #[test]
    fn skill_copies_names_the_pointer_and_native_copies_of_ours() {
        let dest = tempfile::tempdir().unwrap();
        install_skill(dest.path(), false).unwrap();
        let native = dest.path().join(".claude/skills/silcrow/SKILL.md");
        std::fs::create_dir_all(native.parent().unwrap()).unwrap();
        std::fs::write(&native, "---\nname: silcrow\n---\n").unwrap();
        let foreign = dest.path().join(".cursor/skills/silcrow/SKILL.md");
        std::fs::create_dir_all(foreign.parent().unwrap()).unwrap();
        std::fs::write(&foreign, "# mine\n").unwrap();
        assert_eq!(
            skill_copies(dest.path()).unwrap(),
            vec![dest.path().join(SKILL_PATH), native]
        );
    }
}