Skip to main content

release_kit/commands/
skill.rs

1//! `rk skill`: the reader of the agent skills, and the removal of the
2//! copies an earlier release installed under the home.
3//!
4//! Every landing carries the skills, so `install` only names the landing.
5//! `uninstall` resolves the home, the roots the chosen agent implies, and
6//! the record that sits beside them, and renders what the installer
7//! reports, in both the human and the machine form.
8
9use camino::{Utf8Path, Utf8PathBuf};
10use serde::Serialize;
11
12use crate::cli::skill::{Agent, SkillAction, SkillArgs};
13use crate::error::RkError;
14use crate::output::Output;
15use crate::skills;
16use crate::skills::installer::{self, Action, Layout};
17use crate::skills::record::RECORD_PATH;
18use crate::skills::{AGENTS_ROOT, CLAUDE_ROOT, LEGACY_SHARED_ROOT, home};
19
20/// The machine form of an install or uninstall report.
21#[derive(Debug, Serialize)]
22struct Report<'a> {
23    /// The shape version of this document.
24    schema: &'static str,
25    /// `install` or `uninstall`.
26    command: &'static str,
27    /// `preview` or `apply`.
28    mode: &'static str,
29    /// Everything the run did, or would do.
30    actions: &'a [Action],
31    /// What plausibly follows.
32    next: &'a [String],
33}
34
35/// Dispatch the skill action.
36///
37/// # Errors
38///
39/// Returns [`RkError::NotFound`] for an unknown skill name,
40/// [`RkError::Refused`] when the home is unusable or a destination cannot be
41/// touched, and [`RkError::Io`] on filesystem failure.
42pub fn run(args: &SkillArgs) -> Result<(), RkError> {
43    match &args.action {
44        SkillAction::List => {
45            let out = Output::human();
46            for skill in skills::all()? {
47                out.result_line(&skill.name);
48            }
49            Ok(())
50        }
51        SkillAction::Show { name, file } => show(name, file.as_deref()),
52        SkillAction::Install { apply, json, .. } => retired_install(Output::new(*json), *apply),
53        SkillAction::Uninstall { agent, apply, json } => {
54            let layout = layout(*agent)?;
55            let actions = installer::uninstall(&layout, *apply)?;
56            render(Output::new(*json), "uninstall", *apply, &actions)
57        }
58    }
59}
60
61/// What `rk skill install` says now that every landing carries the skills.
62const RETIRED_INSTALL: &str = "rk lands its skills into each project through `rk init` and `rk upgrade`. To remove the copies that an earlier release wrote under your home, run `rk skill uninstall --apply`.";
63
64/// The retired install: the text and exit 0 for a preview, a refusal
65/// under `--apply`, and nothing written either way.
66///
67/// SATISFIES distribution:a-skill-has-one-owner
68fn retired_install(out: Output, apply: bool) -> Result<(), RkError> {
69    if apply {
70        return Err(RkError::Usage(RETIRED_INSTALL.to_owned()));
71    }
72    out.result_line(RETIRED_INSTALL);
73    let next = vec!["rk skill uninstall --apply".to_owned()];
74    out.next(&next);
75    out.emit(&Report {
76        schema: "rk.skill/1",
77        command: "install",
78        mode: "preview",
79        actions: &[],
80        next: &next,
81    })
82}
83
84/// Render what the installer reported: the human lines by default, the
85/// `rk.skill/1` object under `--json`.
86fn render(
87    out: Output,
88    command: &'static str,
89    apply: bool,
90    actions: &[Action],
91) -> Result<(), RkError> {
92    if apply {
93        for action in actions {
94            out.result_line(applied_line(command, action));
95        }
96    } else {
97        out.result_line(format!(
98            "DRY RUN: rk skill {command} {} these files; re-run with --apply",
99            if command == "install" {
100                "writes"
101            } else {
102                "removes"
103            }
104        ));
105        for action in actions {
106            out.result_line(planned_line(action));
107        }
108    }
109    let next = next_lines(command, apply);
110    out.next(&next);
111    out.emit(&Report {
112        schema: "rk.skill/1",
113        command,
114        mode: if apply { "apply" } else { "preview" },
115        actions,
116        next: &next,
117    })
118}
119
120/// The one human line for a planned action.
121fn planned_line(action: &Action) -> String {
122    match action {
123        Action::Write { destination } | Action::Remove { destination } => destination.to_string(),
124        Action::Sweep { destination } => {
125            format!("sweep (no longer carried by this binary) {destination}")
126        }
127        Action::KeptEdited { destination } => format!("keep (edited by you) {destination}"),
128        other => format!("{other:?}"),
129    }
130}
131
132/// The one human line for a performed action, byte-identical to what the
133/// installer printed before the boundary existed.
134fn applied_line(command: &str, action: &Action) -> String {
135    match action {
136        Action::Write { destination } => format!("wrote {destination}"),
137        Action::Unchanged { destination } => format!("unchanged {destination}"),
138        Action::Sweep { destination } => format!("swept {destination}"),
139        Action::SweepFailed { destination, error } => {
140            format!("could not sweep {destination}; remove it by hand: {error}")
141        }
142        Action::Remove { destination } => format!("removed {destination}"),
143        Action::KeptEdited { destination } => format!("kept (edited by you) {destination}"),
144        Action::KeptDirectory { directory } => format!("kept (not empty) {directory}"),
145        Action::RecordUnwritten { record } => {
146            if command == "install" {
147                format!(
148                    "note: could not record the installed digests at {record}; a later install may ask for --force"
149                )
150            } else {
151                format!(
152                    "note: could not update the record at {record}; a later install may ask for --force"
153                )
154            }
155        }
156    }
157}
158
159/// What plausibly follows each outcome.
160fn next_lines(command: &str, apply: bool) -> Vec<String> {
161    match (command, apply) {
162        (_, false) => vec![format!("rk skill {command} --apply")],
163        (_, true) => vec![
164            "rk init and rk upgrade land the skills into each project".to_owned(),
165            "rk doctor reports any user-scope copy that is left".to_owned(),
166        ],
167    }
168}
169
170/// Print one skill's `SKILL.md`, byte-identical to the authored file, or
171/// one file of its package, byte for byte.
172///
173/// SATISFIES distribution:a-skill-is-readable-before-a-landing
174fn show(name: &str, file: Option<&str>) -> Result<(), RkError> {
175    let out = Output::human();
176    if let Some(path) = file {
177        let package = skills::packages()?
178            .into_iter()
179            .find(|package| package.name == name)
180            .ok_or_else(|| RkError::NotFound {
181                kind: "skill",
182                name: name.to_owned(),
183            })?;
184        let found = package
185            .files
186            .iter()
187            .find(|candidate| candidate.path == path)
188            .ok_or_else(|| RkError::NotFound {
189                kind: "skill file",
190                name: format!("{name}/{path}"),
191            })?;
192        out.result_bytes(found.bytes);
193        return Ok(());
194    }
195    skills::all()?
196        .into_iter()
197        .find(|skill| skill.name == name)
198        .map_or_else(
199            || {
200                Err(RkError::NotFound {
201                    kind: "skill",
202                    name: name.to_owned(),
203                })
204            },
205            |skill| {
206                out.result_raw(skill.text);
207                Ok(())
208            },
209        )
210}
211
212/// The roots a run touches, and the record that vouches for them.
213fn layout(agent: Agent) -> Result<Layout, RkError> {
214    let home = home()?;
215    Ok(Layout {
216        roots: roots(&home, agent),
217        legacy_shared: matches!(agent, Agent::All).then(|| home.join(LEGACY_SHARED_ROOT)),
218        record: home.join(RECORD_PATH),
219    })
220}
221
222/// The skill roots under `home`, in the order an apply writes them.
223fn roots(home: &Utf8Path, agent: Agent) -> Vec<Utf8PathBuf> {
224    let mut roots = Vec::new();
225    if matches!(agent, Agent::Claude | Agent::All) {
226        roots.push(home.join(CLAUDE_ROOT));
227    }
228    if matches!(agent, Agent::Codex | Agent::All) {
229        roots.push(home.join(AGENTS_ROOT));
230    }
231    roots
232}
233
234#[cfg(test)]
235mod tests {
236    use camino::Utf8Path;
237
238    use super::roots;
239    use crate::cli::skill::Agent;
240    use crate::skills::installer::Action;
241
242    #[test]
243    fn each_agent_selects_its_own_roots() {
244        let home = Utf8Path::new("/home/<user>");
245        assert_eq!(roots(home, Agent::Claude), ["/home/<user>/.claude/skills"]);
246        assert_eq!(roots(home, Agent::Codex), ["/home/<user>/.agents/skills"]);
247        assert_eq!(
248            roots(home, Agent::All),
249            ["/home/<user>/.claude/skills", "/home/<user>/.agents/skills"]
250        );
251    }
252
253    /// The complete `rk.skill/1` report shape, held by snapshot.
254    #[test]
255    fn the_skill_report_schema_snapshot_holds() {
256        let actions = vec![Action::Write {
257            destination: "/home/<user>/.claude/skills/rk-setup/SKILL.md".into(),
258        }];
259        let next = vec!["rk skill list names the installed skills".to_owned()];
260        let report = super::Report {
261            schema: "rk.skill/1",
262            command: "install",
263            mode: "apply",
264            actions: &actions,
265            next: &next,
266        };
267        assert_eq!(
268            serde_json::to_string(&report).expect("a report serializes"),
269            r#"{"schema":"rk.skill/1","command":"install","mode":"apply","actions":[{"action":"write","destination":"/home/<user>/.claude/skills/rk-setup/SKILL.md"}],"next":["rk skill list names the installed skills"]}"#
270        );
271    }
272
273    /// The `rk.skill/1` action shape, held by snapshot across every
274    /// variant, so the whole tagged-union vocabulary is exact and a
275    /// rename in any one arm fails here first.
276    #[test]
277    fn the_skill_action_schema_snapshot_holds() {
278        let cases: Vec<(Action, &str)> = vec![
279            (
280                Action::Write {
281                    destination: "/h/SKILL.md".into(),
282                },
283                r#"{"action":"write","destination":"/h/SKILL.md"}"#,
284            ),
285            (
286                Action::Unchanged {
287                    destination: "/h/SKILL.md".into(),
288                },
289                r#"{"action":"unchanged","destination":"/h/SKILL.md"}"#,
290            ),
291            (
292                Action::Sweep {
293                    destination: "/h/SKILL.md".into(),
294                },
295                r#"{"action":"sweep","destination":"/h/SKILL.md"}"#,
296            ),
297            (
298                Action::SweepFailed {
299                    destination: "/h/SKILL.md".into(),
300                    error: "permission denied".into(),
301                },
302                r#"{"action":"sweep-failed","destination":"/h/SKILL.md","error":"permission denied"}"#,
303            ),
304            (
305                Action::Remove {
306                    destination: "/h/SKILL.md".into(),
307                },
308                r#"{"action":"remove","destination":"/h/SKILL.md"}"#,
309            ),
310            (
311                Action::KeptEdited {
312                    destination: "/h/SKILL.md".into(),
313                },
314                r#"{"action":"kept-edited","destination":"/h/SKILL.md"}"#,
315            ),
316            (
317                Action::KeptDirectory {
318                    directory: "/h/rk-setup".into(),
319                },
320                r#"{"action":"kept-directory","directory":"/h/rk-setup"}"#,
321            ),
322            (
323                Action::RecordUnwritten {
324                    record: "/h/skills.sha256".into(),
325                },
326                r#"{"action":"record-unwritten","record":"/h/skills.sha256"}"#,
327            ),
328        ];
329        for (action, expected) in cases {
330            assert_eq!(
331                serde_json::to_string(&action).expect("an action serializes"),
332                expected
333            );
334        }
335    }
336}