release_kit/skills/record.rs
1//! The user-scope skill record: what an earlier release last wrote outside a
2//! project. `rk skill uninstall` reads it to remove only those copies.
3//!
4//! Those destinations live under the invoking user's home, where no target
5//! repository reaches, so without a record the installer's only reference is
6//! the skills it currently carries. That makes a copy an older release wrote
7//! indistinguishable from a file the user edited, and every release touching a
8//! skill then refuses on destinations nobody touched. The record closes that
9//! gap and nothing else: one digest per destination, written after a
10//! successful apply, read to answer one question — are these bytes ones we
11//! wrote?
12//!
13//! It is state, not a manifest. Nothing verifies against it, and every
14//! unreadable shape resolves to an empty record, so a lost one costs only the
15//! benefit of the doubt. The format is the one `sha256sum` prints, under a
16//! version line: a file that cheap to lose earns no parser that can fail in
17//! more than one way.
18
19use std::collections::BTreeMap;
20use std::fmt::Write as _;
21
22use camino::{Utf8Path, Utf8PathBuf};
23
24use crate::skills::Digest;
25
26/// Where the record sits, relative to the home directory.
27///
28/// Home-relative rather than `XDG_STATE_HOME`-relative on purpose: the
29/// destinations it speaks for are `$HOME/.claude` and `$HOME/.agents`, which
30/// no XDG variable moves. A record reachable under a different home than the
31/// roots it vouches for would be worse than no record at all.
32pub const RECORD_PATH: &str = ".local/state/release-kit/skills.sha256";
33
34/// The first line of a record this binary understands.
35const HEADER: &str = "# release-kit skill record v1";
36
37/// The separator `sha256sum` writes between a digest and its path.
38const SEPARATOR: &str = " ";
39
40/// The digests this tool last wrote to user-scope skill destinations.
41#[derive(Debug, Default, Clone, PartialEq, Eq)]
42pub struct Record {
43 /// Destination path to the digest written there.
44 pub written: BTreeMap<Utf8PathBuf, Digest>,
45}
46
47impl Record {
48 /// Read the record at `path`, or an empty one.
49 ///
50 /// Every failure resolves to an empty record: absent, unreadable,
51 /// malformed, and written under a header this binary does not know all
52 /// mean the same thing to a caller — nothing here can vouch for a
53 /// destination. Refusing instead would let a corrupt state file block an
54 /// install that has a `--force` it does not need.
55 #[must_use]
56 pub fn load(path: &Utf8Path) -> Self {
57 std::fs::read_to_string(path)
58 .ok()
59 .and_then(|text| Self::parse(&text))
60 .unwrap_or_default()
61 }
62
63 /// Parse a record body, or reject it whole.
64 fn parse(text: &str) -> Option<Self> {
65 let mut lines = text.lines();
66 if lines.next()? != HEADER {
67 return None;
68 }
69 let mut written = BTreeMap::new();
70 for line in lines.filter(|line| !line.is_empty()) {
71 // Split at the digest's fixed width rather than on the first
72 // separator, so a destination path holding two spaces still
73 // round-trips.
74 let (digest, rest) = line.split_at_checked(64)?;
75 let path = rest.strip_prefix(SEPARATOR)?;
76 written.insert(Utf8PathBuf::from(path), Digest::parse(digest)?);
77 }
78 Some(Self { written })
79 }
80
81 /// Whether this record says it wrote `digest` at `destination`.
82 #[must_use]
83 pub fn wrote(&self, destination: &Utf8Path, digest: &Digest) -> bool {
84 self.written.get(destination) == Some(digest)
85 }
86
87 /// Serialize in the `sha256sum` shape, under the version header.
88 #[must_use]
89 pub fn to_text(&self) -> String {
90 let mut text = format!("{HEADER}\n");
91 for (destination, digest) in &self.written {
92 // Writing into a String cannot fail; the result is discarded so
93 // no caller has to handle an error that cannot happen.
94 let _ = writeln!(text, "{digest}{SEPARATOR}{destination}");
95 }
96 text
97 }
98}
99
100#[cfg(test)]
101mod tests {
102 use camino::Utf8PathBuf;
103
104 use super::{HEADER, Record};
105 use crate::skills::Digest;
106
107 fn record() -> Record {
108 let mut record = Record::default();
109 record.written.insert(
110 Utf8PathBuf::from("/home/<user>/.claude/skills/rk-setup/SKILL.md"),
111 Digest::of(b"one"),
112 );
113 record.written.insert(
114 // Two spaces in the path: the separator must not decide the split.
115 Utf8PathBuf::from("/home/<user>/two spaces/SKILL.md"),
116 Digest::of(b"two"),
117 );
118 record
119 }
120
121 #[test]
122 fn a_record_round_trips_through_its_text_form() {
123 let original = record();
124 let parsed = Record::parse(&original.to_text()).expect("the record parses");
125 assert_eq!(parsed, original);
126 }
127
128 #[test]
129 fn a_record_vouches_only_for_the_digest_it_holds() {
130 let record = record();
131 let destination = Utf8PathBuf::from("/home/<user>/.claude/skills/rk-setup/SKILL.md");
132 assert!(record.wrote(&destination, &Digest::of(b"one")));
133 assert!(!record.wrote(&destination, &Digest::of(b"edited")));
134 assert!(!record.wrote(
135 Utf8PathBuf::from("/elsewhere").as_path(),
136 &Digest::of(b"one")
137 ));
138 }
139
140 #[test]
141 fn every_unreadable_shape_resolves_to_an_empty_record() {
142 let good = record().to_text();
143 for text in [
144 String::new(),
145 "not a header\n".to_string(),
146 "# release-kit skill record v2\n".to_string(),
147 good.replace(HEADER, "# release-kit skill record v0"),
148 // A truncated digest, and a line missing its separator.
149 format!("{HEADER}\nabc /path\n"),
150 format!("{HEADER}\n{} /path\n", Digest::of(b"one")),
151 ] {
152 assert_eq!(
153 Record::parse(&text),
154 None,
155 "'{text}' parsed as a valid record"
156 );
157 }
158 }
159
160 #[test]
161 fn a_missing_record_loads_empty() {
162 assert_eq!(
163 Record::load(Utf8PathBuf::from("/no/such/record").as_path()),
164 Record::default()
165 );
166 }
167}