Skip to main content

spec_driven_docs/domain/
skill_record.rs

1//! The user-scope skill record: what this tool last wrote outside an instance.
2//!
3//! Skill destinations live under the invoking user's home, where no instance
4//! manifest reaches, so without a record the installer's only reference is
5//! the payload it currently carries. That makes a copy left by an older
6//! release indistinguishable from a file the user edited, and every release
7//! that touches a skill refuses on destinations nobody touched. This record
8//! closes that gap and nothing else: one digest per destination, written
9//! after a successful apply, read to answer one question — are these bytes
10//! ones we wrote?
11//!
12//! It is not an instance manifest and never becomes one. No verification
13//! reads it, a missing or unreadable record only costs the caller the
14//! benefit of the doubt, and `distribution:user-scope-files-stay-unrecorded`
15//! keeps these paths out of the manifest that does drive verification.
16
17use std::collections::BTreeMap;
18
19use camino::{Utf8Path, Utf8PathBuf};
20use serde::{Deserialize, Serialize};
21
22use crate::domain::ownership::Sha256;
23
24/// The record schema this binary reads and writes.
25pub const SCHEMA_VERSION: u32 = 1;
26
27/// Where the record sits, relative to the home directory.
28///
29/// Home-relative rather than `XDG_STATE_HOME`-relative on purpose: the
30/// destinations it describes are `$HOME/.agents` and `$HOME/.claude`, which
31/// no XDG variable moves. A record reachable under a different home than the
32/// roots it speaks for would be worse than no record at all.
33pub const RECORD_PATH: &str = ".local/state/spec-driven-docs/skills.json";
34
35/// The digests this tool last wrote to user-scope skill destinations.
36#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
37#[serde(deny_unknown_fields)]
38pub struct SkillRecord {
39    /// Always [`SCHEMA_VERSION`] once parsed.
40    pub schema_version: u32,
41    /// Absolute destination path to the digest written there.
42    pub written: BTreeMap<Utf8PathBuf, Sha256>,
43}
44
45impl Default for SkillRecord {
46    fn default() -> Self {
47        Self::new()
48    }
49}
50
51impl SkillRecord {
52    /// An empty record at the current schema.
53    #[must_use]
54    pub const fn new() -> Self {
55        Self {
56            schema_version: SCHEMA_VERSION,
57            written: BTreeMap::new(),
58        }
59    }
60
61    /// Read the record at `path`, or an empty one.
62    ///
63    /// Every failure resolves to an empty record: absent, unreadable,
64    /// malformed, and written by a schema this binary does not know all mean
65    /// the same thing to a caller — nothing here can vouch for a
66    /// destination. Refusing instead would let a corrupt state file block an
67    /// install that has a `--force` it does not need.
68    #[must_use]
69    pub fn load(path: &Utf8Path) -> Self {
70        std::fs::read_to_string(path)
71            .ok()
72            .and_then(|text| serde_json::from_str::<Self>(&text).ok())
73            .filter(|record| record.schema_version == SCHEMA_VERSION)
74            .unwrap_or_default()
75    }
76
77    /// Serialize as pretty JSON with a trailing newline.
78    #[must_use]
79    pub fn to_json(&self) -> String {
80        let mut text = serde_json::to_string_pretty(self)
81            .unwrap_or_else(|_| "{\"schema_version\":1,\"written\":{}}".to_string());
82        text.push('\n');
83        text
84    }
85
86    /// Whether `digest` is what this tool last wrote to `destination`.
87    #[must_use]
88    pub fn wrote(&self, destination: &Utf8Path, digest: &Sha256) -> bool {
89        self.written.get(destination) == Some(digest)
90    }
91}
92
93#[cfg(test)]
94mod tests {
95    // sdd: permanent a test panics as its failure signal, not as control flow
96    #![allow(clippy::unwrap_used)]
97
98    use super::*;
99
100    fn path(dir: &tempfile::TempDir, name: &str) -> Utf8PathBuf {
101        Utf8PathBuf::from(dir.path().to_str().unwrap()).join(name)
102    }
103
104    #[test]
105    fn a_round_trip_preserves_every_entry() {
106        let dir = tempfile::tempdir().unwrap();
107        let file = path(&dir, "skills.json");
108        let mut record = SkillRecord::new();
109        record.written.insert(
110            Utf8PathBuf::from("/home/<user>/.claude/skills/s/SKILL.md"),
111            Sha256::of(b"x"),
112        );
113        std::fs::write(&file, record.to_json()).unwrap();
114        assert_eq!(SkillRecord::load(&file), record);
115    }
116
117    #[test]
118    fn wrote_answers_only_for_the_exact_path_and_digest() {
119        let mut record = SkillRecord::new();
120        let destination = Utf8PathBuf::from("/home/<user>/SKILL.md");
121        record.written.insert(destination.clone(), Sha256::of(b"x"));
122        assert!(record.wrote(&destination, &Sha256::of(b"x")));
123        assert!(!record.wrote(&destination, &Sha256::of(b"y")));
124        assert!(!record.wrote(Utf8Path::new("/home/<other>/SKILL.md"), &Sha256::of(b"x")));
125    }
126
127    /// A caller that cannot read the record loses the benefit of the doubt
128    /// and nothing else, so every unreadable shape resolves the same way.
129    #[test]
130    fn an_unusable_record_reads_as_empty_rather_than_failing() {
131        let dir = tempfile::tempdir().unwrap();
132        assert_eq!(
133            SkillRecord::load(&path(&dir, "absent.json")),
134            SkillRecord::new()
135        );
136
137        let malformed = path(&dir, "malformed.json");
138        std::fs::write(&malformed, "{not json").unwrap();
139        assert_eq!(SkillRecord::load(&malformed), SkillRecord::new());
140
141        let future = path(&dir, "future.json");
142        std::fs::write(&future, "{\"schema_version\":99,\"written\":{}}").unwrap();
143        assert_eq!(SkillRecord::load(&future), SkillRecord::new());
144    }
145}