Skip to main content

ask/skills/
lock.rs

1//! The `ask skills` install lock (`.ask/skills-lock.json`) — the source of
2//! truth for `skills remove`. Rust port of `skills/lock.ts`.
3//!
4//! Entries are keyed by spec-key. Unlike the TS build (insertion order), the
5//! Rust store keys entries in a `BTreeMap` for deterministic on-disk ordering,
6//! matching `resolved.json`'s convention. The differential harness normalizes
7//! the volatile `installedAt` timestamp before diffing.
8
9use std::collections::BTreeMap;
10use std::path::{Path, PathBuf};
11
12use serde::{Deserialize, Serialize};
13
14pub const LOCK_FILENAME: &str = ".ask/skills-lock.json";
15
16/// One installed skill: its name and the agents it was symlinked into.
17#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
18pub struct LockSkill {
19    /// Skill name — the basename of the source skill directory.
20    pub name: String,
21    /// Agents whose `<agent>/skills/<name>` symlinks were installed.
22    pub agents: Vec<String>,
23}
24
25/// One lock entry per installed spec. Field order matches the TS object literal
26/// so `serde_json::to_string_pretty` reproduces `JSON.stringify` byte-for-byte.
27#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
28#[serde(rename_all = "camelCase")]
29pub struct LockEntry {
30    /// Original user-facing spec, e.g. `npm:next@14.2.3`.
31    pub spec: String,
32    /// Filesystem-safe encoding (see `encode_spec_key`).
33    pub spec_key: String,
34    /// Skills installed for this entry.
35    pub skills: Vec<LockSkill>,
36    /// ISO timestamp of the last install.
37    pub installed_at: String,
38}
39
40/// The whole lock file: a fixed `version: 1` plus the spec-key → entry map.
41#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
42pub struct LockFile {
43    pub version: u8,
44    pub entries: BTreeMap<String, LockEntry>,
45}
46
47impl Default for LockFile {
48    fn default() -> Self {
49        LockFile {
50            version: 1,
51            entries: BTreeMap::new(),
52        }
53    }
54}
55
56pub fn lock_path(project_dir: &Path) -> PathBuf {
57    project_dir.join(LOCK_FILENAME)
58}
59
60/// Read the lock, returning an empty `version: 1` lock when the file is absent.
61/// Errors on a schema mismatch (non-object, or `version != 1`). Parity with
62/// `readLock`.
63pub fn read_lock(project_dir: &Path) -> anyhow::Result<LockFile> {
64    let p = lock_path(project_dir);
65    if !p.exists() {
66        return Ok(LockFile::default());
67    }
68    let raw = std::fs::read_to_string(&p)?;
69    let value: serde_json::Value = serde_json::from_str(&raw)?;
70    let ok = value.get("version").and_then(|v| v.as_u64()) == Some(1)
71        && value.get("entries").map(|e| e.is_object()).unwrap_or(false);
72    if !ok {
73        anyhow::bail!("{LOCK_FILENAME}: schema mismatch");
74    }
75    Ok(serde_json::from_value(value)?)
76}
77
78/// Return a new lock with `entry` inserted/overwritten under its spec-key.
79pub fn upsert_entry(lock: &LockFile, entry: LockEntry) -> LockFile {
80    let mut entries = lock.entries.clone();
81    entries.insert(entry.spec_key.clone(), entry);
82    LockFile {
83        version: 1,
84        entries,
85    }
86}
87
88/// Return a new lock with `spec_key` removed (or the lock unchanged if absent).
89pub fn remove_entry(lock: &LockFile, spec_key: &str) -> LockFile {
90    let mut entries = lock.entries.clone();
91    entries.remove(spec_key);
92    LockFile {
93        version: 1,
94        entries,
95    }
96}
97
98/// Serialize (`JSON.stringify(lock, null, 2)\n`) to a `.tmp` neighbour then
99/// rename into place. The `.ask/` parent is created on demand. Parity with
100/// `writeLockAtomic`.
101pub fn write_lock_atomic(project_dir: &Path, lock: &LockFile) -> anyhow::Result<()> {
102    let target = lock_path(project_dir);
103    if let Some(parent) = target.parent() {
104        std::fs::create_dir_all(parent)?;
105    }
106    let tmp = target.with_extension("json.tmp");
107    let body = format!("{}\n", serde_json::to_string_pretty(lock)?);
108    std::fs::write(&tmp, body)?;
109    std::fs::rename(&tmp, &target)?;
110    Ok(())
111}
112
113#[cfg(test)]
114mod tests {
115    use super::*;
116
117    fn entry(spec: &str, spec_key: &str) -> LockEntry {
118        LockEntry {
119            spec: spec.to_string(),
120            spec_key: spec_key.to_string(),
121            skills: vec![LockSkill {
122                name: "s".to_string(),
123                agents: vec!["claude".to_string()],
124            }],
125            installed_at: "2026-07-04T00:00:00.000Z".to_string(),
126        }
127    }
128
129    #[test]
130    fn missing_lock_is_empty() {
131        let dir = tempfile::tempdir().unwrap();
132        let lock = read_lock(dir.path()).unwrap();
133        assert_eq!(lock.version, 1);
134        assert!(lock.entries.is_empty());
135    }
136
137    #[test]
138    fn write_read_roundtrip_and_camelcase_keys() {
139        let dir = tempfile::tempdir().unwrap();
140        let lock = upsert_entry(
141            &LockFile::default(),
142            entry("npm:react@18", "npm__react__18"),
143        );
144        write_lock_atomic(dir.path(), &lock).unwrap();
145        let body = std::fs::read_to_string(dir.path().join(LOCK_FILENAME)).unwrap();
146        assert!(body.contains("\"specKey\""));
147        assert!(body.contains("\"installedAt\""));
148        assert!(body.ends_with("}\n"));
149        let back = read_lock(dir.path()).unwrap();
150        assert_eq!(back, lock);
151    }
152
153    #[test]
154    fn field_order_matches_ts_literal() {
155        let lock = upsert_entry(
156            &LockFile::default(),
157            entry("npm:react@18", "npm__react__18"),
158        );
159        let body = serde_json::to_string_pretty(&lock).unwrap();
160        let spec = body.find("\"spec\"").unwrap();
161        let spec_key = body.find("\"specKey\"").unwrap();
162        let skills = body.find("\"skills\"").unwrap();
163        let installed = body.find("\"installedAt\"").unwrap();
164        assert!(spec < spec_key && spec_key < skills && skills < installed);
165    }
166
167    #[test]
168    fn upsert_and_remove() {
169        let lock = upsert_entry(&LockFile::default(), entry("a", "ka"));
170        let lock = upsert_entry(&lock, entry("b", "kb"));
171        assert_eq!(lock.entries.len(), 2);
172        let lock = remove_entry(&lock, "ka");
173        assert_eq!(lock.entries.len(), 1);
174        assert!(lock.entries.contains_key("kb"));
175        // Removing an absent key is a no-op.
176        let same = remove_entry(&lock, "nope");
177        assert_eq!(same.entries.len(), 1);
178    }
179
180    #[test]
181    fn schema_mismatch_errors() {
182        let dir = tempfile::tempdir().unwrap();
183        std::fs::create_dir_all(dir.path().join(".ask")).unwrap();
184        std::fs::write(
185            dir.path().join(LOCK_FILENAME),
186            r#"{"version":2,"entries":{}}"#,
187        )
188        .unwrap();
189        assert!(read_lock(dir.path()).is_err());
190    }
191}