Skip to main content

ask/
resolved.rs

1//! `.ask/resolved.json` schema — Rust port of `packages/schema/src/resolved.ts`.
2//!
3//! `resolved.json` is a pure cache that lets `ask install` short-circuit when
4//! nothing has changed. `key` (the map key) is the library slug — the same
5//! string used under `.ask/docs/<slug>@<ver>/` and as the skill dir name.
6//!
7//! This file is machine-generated (never hand-edited), so the datetime fields
8//! use a light RFC3339 shape check rather than a full date parser; the content
9//! hash, commit SHA, and structural refinements are validated faithfully.
10
11use std::collections::BTreeMap;
12
13use serde::{Deserialize, Serialize};
14
15/// How the docs were materialized. `in-place` references
16/// `node_modules/<pkg>/<docsPath>` directly; the others are global-store modes.
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
18#[serde(rename_all = "kebab-case")]
19pub enum Materialization {
20    Copy,
21    Link,
22    Ref,
23    InPlace,
24}
25
26/// Distinguishes materialized docs from intent-skills entries.
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
28#[serde(rename_all = "kebab-case")]
29pub enum EntryFormat {
30    Docs,
31    IntentSkills,
32}
33
34/// One row in `.ask/resolved.json`. Optional fields are omitted from the
35/// serialized JSON when absent (parity with the TS optional keys). Unknown
36/// fields are rejected (zod `.strict()`).
37#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
38#[serde(deny_unknown_fields, rename_all = "camelCase")]
39pub struct ResolvedEntry {
40    /// The exact spec from `ask.json` (so we can detect spec edits).
41    pub spec: String,
42    /// Resolved version (lockfile for PM-driven, `ref` for standalone).
43    pub resolved_version: String,
44    /// Hash of the materialized doc files (`sha256-<64 hex>`).
45    pub content_hash: String,
46    /// ISO timestamp of the most recent successful fetch.
47    pub fetched_at: String,
48    /// Number of files written under `.ask/docs/<slug>@<ver>/`.
49    pub file_count: u64,
50    #[serde(skip_serializing_if = "Option::is_none")]
51    pub format: Option<EntryFormat>,
52    #[serde(skip_serializing_if = "Option::is_none")]
53    pub store_path: Option<String>,
54    #[serde(skip_serializing_if = "Option::is_none")]
55    pub materialization: Option<Materialization>,
56    /// Project-relative docs path when `materialization == in-place`.
57    #[serde(skip_serializing_if = "Option::is_none")]
58    pub in_place_path: Option<String>,
59    /// Git commit SHA a `github` ref resolved to (40-char lowercase hex).
60    #[serde(skip_serializing_if = "Option::is_none")]
61    pub commit: Option<String>,
62    /// Relative subpath inside `store_path` holding the docs tree.
63    #[serde(skip_serializing_if = "Option::is_none")]
64    pub store_subpath: Option<String>,
65}
66
67/// The `.ask/resolved.json` document.
68#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
69#[serde(deny_unknown_fields, rename_all = "camelCase")]
70pub struct ResolvedJson {
71    pub schema_version: u32,
72    pub generated_at: String,
73    /// Slug → resolved entry. `BTreeMap` gives deterministic on-disk ordering
74    /// (the cache is regenerable, so sorted order is fine).
75    pub entries: BTreeMap<String, ResolvedEntry>,
76}
77
78/// Validation failure for a resolved-cache document.
79#[derive(Debug, thiserror::Error, PartialEq, Eq)]
80pub enum ResolvedError {
81    #[error("contentHash must be sha256-<64 hex chars>: {0:?}")]
82    ContentHash(String),
83    #[error("commit must be a 40-char lowercase hex SHA: {0:?}")]
84    Commit(String),
85    #[error("{field} must be an ISO-8601 datetime with offset: {value:?}")]
86    DateTime { field: &'static str, value: String },
87    #[error("inPlacePath is required when materialization is 'in-place' (entry {0:?})")]
88    MissingInPlacePath(String),
89    #[error("schemaVersion must be 1, got {0}")]
90    SchemaVersion(u32),
91    #[error("{0} must be a non-empty string")]
92    EmptyField(&'static str),
93}
94
95impl ResolvedEntry {
96    /// Enforce the field-shape refinements serde structural parsing cannot.
97    pub fn validate(&self) -> Result<(), ResolvedError> {
98        // TS: spec / resolvedVersion are `z.string().min(1)` — reject empties so
99        // `.ask/resolved.json` acceptance stays in parity with the TS validator.
100        if self.spec.is_empty() {
101            return Err(ResolvedError::EmptyField("spec"));
102        }
103        if self.resolved_version.is_empty() {
104            return Err(ResolvedError::EmptyField("resolvedVersion"));
105        }
106        if !is_content_hash(&self.content_hash) {
107            return Err(ResolvedError::ContentHash(self.content_hash.clone()));
108        }
109        if !is_iso_datetime_offset(&self.fetched_at) {
110            return Err(ResolvedError::DateTime {
111                field: "fetchedAt",
112                value: self.fetched_at.clone(),
113            });
114        }
115        if let Some(commit) = &self.commit {
116            if !is_git_sha(commit) {
117                return Err(ResolvedError::Commit(commit.clone()));
118            }
119        }
120        if self.materialization == Some(Materialization::InPlace) && self.in_place_path.is_none() {
121            return Err(ResolvedError::MissingInPlacePath(self.spec.clone()));
122        }
123        Ok(())
124    }
125}
126
127impl ResolvedJson {
128    /// Parse and validate a `resolved.json` document from a JSON string.
129    pub fn parse(json: &str) -> anyhow::Result<Self> {
130        let parsed: ResolvedJson = serde_json::from_str(json)?;
131        parsed.validate()?;
132        Ok(parsed)
133    }
134
135    /// Validate the literal schema version, timestamp, and every entry.
136    pub fn validate(&self) -> Result<(), ResolvedError> {
137        if self.schema_version != 1 {
138            return Err(ResolvedError::SchemaVersion(self.schema_version));
139        }
140        if !is_iso_datetime_offset(&self.generated_at) {
141            return Err(ResolvedError::DateTime {
142                field: "generatedAt",
143                value: self.generated_at.clone(),
144            });
145        }
146        for entry in self.entries.values() {
147            entry.validate()?;
148        }
149        Ok(())
150    }
151}
152
153/// `^sha256-[0-9a-f]{64}$`.
154fn is_content_hash(s: &str) -> bool {
155    match s.strip_prefix("sha256-") {
156        Some(hex) => {
157            hex.len() == 64
158                && hex
159                    .bytes()
160                    .all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
161        }
162        None => false,
163    }
164}
165
166/// `^[0-9a-f]{40}$`.
167fn is_git_sha(s: &str) -> bool {
168    s.len() == 40
169        && s.bytes()
170            .all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
171}
172
173/// Light RFC3339 shape check: `YYYY-MM-DDThh:mm:ss[.fff]` followed by `Z` or a
174/// `±hh:mm` offset. Faithful to zod's `.datetime({ offset: true })` intent
175/// (an offset is required) without pulling a date-parsing dependency; tightened
176/// later if a module needs true calendar validation.
177fn is_iso_datetime_offset(s: &str) -> bool {
178    let Some((date, rest)) = s.split_once('T') else {
179        return false;
180    };
181    // Date: YYYY-MM-DD
182    let d: Vec<&str> = date.split('-').collect();
183    if d.len() != 3 || d[0].len() != 4 || d[1].len() != 2 || d[2].len() != 2 {
184        return false;
185    }
186    if !d.iter().all(|p| p.bytes().all(|b| b.is_ascii_digit())) {
187        return false;
188    }
189    // Time + offset.
190    let (time, offset) = if let Some(stripped) = rest.strip_suffix('Z') {
191        (stripped, true)
192    } else if let Some(idx) = rest.rfind(['+', '-']) {
193        // Offset must be ±hh:mm.
194        let off = &rest[idx + 1..];
195        let ok = off.len() == 5
196            && off.as_bytes()[2] == b':'
197            && off[..2]
198                .bytes()
199                .chain(off[3..].bytes())
200                .all(|b| b.is_ascii_digit());
201        (&rest[..idx], ok)
202    } else {
203        (rest, false)
204    };
205    if !offset {
206        return false;
207    }
208    // Time: hh:mm:ss with optional .fraction.
209    let core = time.split('.').next().unwrap_or(time);
210    let t: Vec<&str> = core.split(':').collect();
211    t.len() == 3
212        && t[0].len() == 2
213        && t[1].len() == 2
214        && t[2].len() == 2
215        && t.iter().all(|p| p.bytes().all(|b| b.is_ascii_digit()))
216}
217
218#[cfg(test)]
219mod tests {
220    use super::*;
221
222    const HASH: &str = "sha256-0000000000000000000000000000000000000000000000000000000000000000";
223    const SHA: &str = "0123456789abcdef0123456789abcdef01234567";
224
225    fn base_entry_json(extra: &str) -> String {
226        format!(
227            r#"{{"spec":"npm:next","resolvedVersion":"15.0.0","contentHash":"{HASH}","fetchedAt":"2026-07-04T00:00:00Z","fileCount":3{extra}}}"#
228        )
229    }
230
231    fn doc(entry_json: &str) -> String {
232        format!(
233            r#"{{"schemaVersion":1,"generatedAt":"2026-07-04T00:00:00Z","entries":{{"next":{entry_json}}}}}"#
234        )
235    }
236
237    #[test]
238    fn parses_minimal_entry() {
239        let ask = ResolvedJson::parse(&doc(&base_entry_json(""))).unwrap();
240        let e = &ask.entries["next"];
241        assert_eq!(e.spec, "npm:next");
242        assert_eq!(e.file_count, 3);
243        assert_eq!(e.commit, None);
244    }
245
246    #[test]
247    fn optional_fields_omitted_when_none() {
248        let e = ResolvedJson::parse(&doc(&base_entry_json("")))
249            .unwrap()
250            .entries
251            .remove("next")
252            .unwrap();
253        let json = serde_json::to_string(&e).unwrap();
254        assert!(!json.contains("commit"));
255        assert!(!json.contains("storePath"));
256        assert!(!json.contains("format"));
257    }
258
259    #[test]
260    fn kebab_case_enums_roundtrip() {
261        let json = base_entry_json(
262            r#","materialization":"in-place","inPlacePath":"node_modules/next/dist/docs","format":"intent-skills""#,
263        );
264        let e: ResolvedEntry = serde_json::from_str(&json).unwrap();
265        assert_eq!(e.materialization, Some(Materialization::InPlace));
266        assert_eq!(e.format, Some(EntryFormat::IntentSkills));
267        // Re-serialize keeps the kebab-case wire form.
268        let out = serde_json::to_string(&e).unwrap();
269        assert!(out.contains(r#""materialization":"in-place""#));
270        assert!(out.contains(r#""format":"intent-skills""#));
271    }
272
273    #[test]
274    fn in_place_requires_in_place_path() {
275        let json = base_entry_json(r#","materialization":"in-place""#);
276        let err = ResolvedJson::parse(&doc(&json)).unwrap_err();
277        assert!(err.to_string().contains("inPlacePath is required"));
278    }
279
280    #[test]
281    fn rejects_bad_content_hash() {
282        let json = base_entry_json("").replace(HASH, "sha256-xyz");
283        assert!(ResolvedJson::parse(&doc(&json)).is_err());
284    }
285
286    #[test]
287    fn rejects_empty_spec_or_version() {
288        // TS: spec / resolvedVersion are z.string().min(1).
289        let empty_spec = base_entry_json("").replace(r#""spec":"npm:next""#, r#""spec":"""#);
290        assert!(ResolvedJson::parse(&doc(&empty_spec)).is_err());
291        let empty_ver =
292            base_entry_json("").replace(r#""resolvedVersion":"15.0.0""#, r#""resolvedVersion":"""#);
293        assert!(ResolvedJson::parse(&doc(&empty_ver)).is_err());
294    }
295
296    #[test]
297    fn rejects_bad_commit_sha() {
298        let json = base_entry_json(r#","commit":"NOTASHA""#);
299        assert!(ResolvedJson::parse(&doc(&json)).is_err());
300    }
301
302    #[test]
303    fn accepts_valid_commit_sha() {
304        let json = base_entry_json(&format!(r#","commit":"{SHA}""#));
305        let ask = ResolvedJson::parse(&doc(&json)).unwrap();
306        assert_eq!(ask.entries["next"].commit.as_deref(), Some(SHA));
307    }
308
309    #[test]
310    fn rejects_wrong_schema_version() {
311        let doc = doc(&base_entry_json("")).replace("\"schemaVersion\":1", "\"schemaVersion\":2");
312        assert!(ResolvedJson::parse(&doc).is_err());
313    }
314
315    #[test]
316    fn rejects_unknown_entry_field() {
317        let json = base_entry_json(r#","bogus":1"#);
318        assert!(ResolvedJson::parse(&doc(&json)).is_err());
319    }
320
321    #[test]
322    fn datetime_offset_shapes() {
323        assert!(is_iso_datetime_offset("2026-07-04T00:00:00Z"));
324        assert!(is_iso_datetime_offset("2026-07-04T12:30:59.123+09:00"));
325        assert!(is_iso_datetime_offset("2026-07-04T12:30:59-05:00"));
326        assert!(!is_iso_datetime_offset("2026-07-04T00:00:00")); // no offset
327        assert!(!is_iso_datetime_offset("2026-07-04 00:00:00Z")); // no T
328        assert!(!is_iso_datetime_offset("not-a-date"));
329    }
330}