Skip to main content

ask/
io.rs

1//! `ask.json` / `.ask/resolved.json` file I/O + hashing — Rust port of
2//! `packages/cli/src/io.ts`.
3//!
4//! `ask.json` is a root-level file (beside `package.json`); `.ask/` holds
5//! materialized, gitignored output (docs + the resolved cache).
6
7use std::collections::BTreeMap;
8use std::io::Write as _;
9use std::path::{Path, PathBuf};
10
11use serde::Serialize;
12use sha2::{Digest, Sha256};
13use time::format_description::well_known::Rfc3339;
14use time::OffsetDateTime;
15
16use crate::ask_json::{AskJson, LibraryEntry};
17use crate::resolved::{ResolvedEntry, ResolvedJson};
18use crate::spec::{library_name_from_spec, parse_spec, split_explicit_version, ParsedSpec};
19
20const ASK_DIR: &str = ".ask";
21const ASK_JSON_FILE: &str = "ask.json";
22const RESOLVED_FILE: &str = "resolved.json";
23
24/// Serialize a value to JSON with **recursively sorted keys**, 2-space indent,
25/// and a trailing newline. Two calls with semantically equivalent input always
26/// produce the same byte string (port of `sortedJSON`).
27///
28/// Routing through `serde_json::Value` normalizes key order: serde_json's `Map`
29/// is a `BTreeMap` by default (the `preserve_order` feature is off), so
30/// `to_value` yields sorted maps at every level and arrays keep their order —
31/// exactly the TS `sortKeys` contract.
32pub fn sorted_json<T: Serialize>(value: &T) -> String {
33    let normalized = serde_json::to_value(value).expect("serializable value");
34    let mut out = serde_json::to_string_pretty(&normalized).expect("serializable value");
35    out.push('\n');
36    out
37}
38
39/// A file participating in a content hash. Exactly one of `bytes`/`content` is
40/// used (bytes wins); an absent payload hashes as empty, matching the TS.
41pub struct HashableFile {
42    pub relpath: String,
43    pub bytes: Option<Vec<u8>>,
44    pub content: Option<String>,
45}
46
47impl HashableFile {
48    fn payload(&self) -> &[u8] {
49        if let Some(b) = &self.bytes {
50            b
51        } else if let Some(c) = &self.content {
52            c.as_bytes()
53        } else {
54            &[]
55        }
56    }
57}
58
59/// Deterministic content hash over a list of files. Files are sorted by relative
60/// path; each contributes `<relpath>\0<bytes>\0` to the stream. The NUL
61/// separators prevent `path + content` ambiguity (`"ab"+"cd"` vs `"a"+"bcd"`).
62/// Returns `sha256-<hex>` (port of `contentHash`).
63pub fn content_hash(files: &[HashableFile]) -> String {
64    let mut sorted: Vec<&HashableFile> = files.iter().collect();
65    sorted.sort_by(|a, b| a.relpath.cmp(&b.relpath));
66    let mut hash = Sha256::new();
67    for f in sorted {
68        hash.update(f.relpath.as_bytes());
69        hash.update([0u8]);
70        hash.update(f.payload());
71        hash.update([0u8]);
72    }
73    format!("sha256-{:x}", hash.finalize())
74}
75
76/// Crash-safe write: stage the bytes in a sibling temp file, fsync, then rename
77/// into place. `std::fs::write` truncates the target first, so a crash/kill/full
78/// disk mid-write leaves a truncated file — fatal for `ask.json` (the declarative
79/// source of truth, which has no self-heal path). The rename is atomic on the
80/// same filesystem, so a reader ever sees either the old file or the complete
81/// new one. Same final bytes as `fs::write`, so parity is unaffected.
82fn write_atomic(path: &Path, contents: &str) -> anyhow::Result<()> {
83    let dir = path.parent().unwrap_or_else(|| Path::new("."));
84    std::fs::create_dir_all(dir)?;
85    let mut tmp = tempfile::NamedTempFile::new_in(dir)?;
86    tmp.write_all(contents.as_bytes())?;
87    tmp.as_file().sync_all()?;
88    tmp.persist(path).map_err(|e| e.error)?;
89    Ok(())
90}
91
92pub fn get_ask_dir(project_dir: &Path) -> PathBuf {
93    project_dir.join(ASK_DIR)
94}
95
96/// `ask.json` sits at the project root, NOT inside `.ask/`.
97pub fn get_ask_json_path(project_dir: &Path) -> PathBuf {
98    project_dir.join(ASK_JSON_FILE)
99}
100
101pub fn get_resolved_json_path(project_dir: &Path) -> PathBuf {
102    get_ask_dir(project_dir).join(RESOLVED_FILE)
103}
104
105/// Locate a library entry in `ask.json` by user-supplied identifier. Matches in
106/// three steps (parity with `findEntry` / `ask remove`):
107///
108///   1. Exact spec string.
109///   2. Library name via `library_name_from_spec(split_explicit_version(...))`
110///      — so `next` matches both `npm:next` and `npm:next@14`.
111///   3. Raw npm package name — `next` → `npm:next`, `@scope/pkg` → `npm:@scope/pkg`.
112///
113/// Returns `None` when nothing matches so callers can fall through to defaults.
114pub fn find_entry<'a>(ask_json: &'a AskJson, target: &str) -> Option<&'a LibraryEntry> {
115    for entry in &ask_json.libraries {
116        let spec = entry.spec();
117        if spec == target {
118            return Some(entry);
119        }
120        let (body, _version) = split_explicit_version(spec);
121        if library_name_from_spec(body) == target {
122            return Some(entry);
123        }
124        if let ParsedSpec::Npm { pkg, .. } = parse_spec(body) {
125            if pkg == target {
126                return Some(entry);
127            }
128        }
129    }
130    None
131}
132
133/// Read and validate `ask.json`. Returns `Ok(None)` when the file does not
134/// exist (so the install orchestrator can bootstrap an empty file). Errors on
135/// invalid JSON or schema violations.
136pub fn read_ask_json(project_dir: &Path) -> anyhow::Result<Option<AskJson>> {
137    let file = get_ask_json_path(project_dir);
138    if !file.exists() {
139        return Ok(None);
140    }
141    let raw = std::fs::read_to_string(&file)?;
142    let ask = AskJson::parse(&raw)
143        .map_err(|e| anyhow::anyhow!("Failed to parse {}: {e}.", file.display()))?;
144    Ok(Some(ask))
145}
146
147/// Validate and write `ask.json`. Library entries are NOT reordered (users may
148/// care about declaration order; `ask add` appends). Only object *keys* within
149/// each entry are sorted, via `sorted_json`.
150pub fn write_ask_json(project_dir: &Path, ask_json: &AskJson) -> anyhow::Result<()> {
151    ask_json.validate()?;
152    let file = get_ask_json_path(project_dir);
153    write_atomic(&file, &sorted_json(ask_json))
154}
155
156/// Read and validate `.ask/resolved.json`. Returns the default empty cache when
157/// the file is MISSING or fails to parse/validate — the cache is rebuilt from
158/// scratch in that case, which is what makes `resolved.json` safe to delete by
159/// hand. A non-NotFound read error (e.g. permission denied) is NOT masked as an
160/// empty cache — it is surfaced, matching TS `readResolvedJson` where the
161/// `readFileSync` sits OUTSIDE the parse `try/catch` (only parse failures fall
162/// back to empty). Masking it would hide a real disk/permission fault behind a
163/// silent full re-resolve.
164pub fn read_resolved_json(project_dir: &Path) -> anyhow::Result<ResolvedJson> {
165    let file = get_resolved_json_path(project_dir);
166    let raw = match std::fs::read_to_string(&file) {
167        Ok(raw) => raw,
168        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(empty_resolved()),
169        Err(e) => {
170            return Err(anyhow::Error::new(e).context(format!("Failed to read {}", file.display())))
171        }
172    };
173    Ok(ResolvedJson::parse(&raw).unwrap_or_else(|_| empty_resolved()))
174}
175
176/// The default empty resolved cache.
177pub fn empty_resolved() -> ResolvedJson {
178    ResolvedJson {
179        schema_version: 1,
180        generated_at: "1970-01-01T00:00:00Z".to_string(),
181        entries: BTreeMap::new(),
182    }
183}
184
185/// Validate and write `.ask/resolved.json`.
186pub fn write_resolved_json(project_dir: &Path, resolved: &ResolvedJson) -> anyhow::Result<()> {
187    resolved.validate()?;
188    let file = get_resolved_json_path(project_dir);
189    write_atomic(&file, &sorted_json(resolved))
190}
191
192/// Upsert a single entry into `.ask/resolved.json`. Skips the rewrite when
193/// nothing changed (modulo `fetchedAt`) so file watchers stay quiet on no-op
194/// runs (parity with `upsertResolvedEntry`).
195pub fn upsert_resolved_entry(
196    project_dir: &Path,
197    key: &str,
198    entry: ResolvedEntry,
199) -> anyhow::Result<()> {
200    let mut resolved = read_resolved_json(project_dir)?;
201    let changed = match resolved.entries.get(key) {
202        None => true,
203        Some(previous) => !eq_ignoring_fetched_at(previous, &entry),
204    };
205    if !changed {
206        return Ok(());
207    }
208    resolved.entries.insert(key.to_string(), entry);
209    resolved.generated_at = now_iso();
210    write_resolved_json(project_dir, &resolved)
211}
212
213/// Remove one or more entries from `.ask/resolved.json` by key. No-op if the
214/// key set is empty (parity with `removeResolvedEntries`).
215pub fn remove_resolved_entries(project_dir: &Path, keys: &[String]) -> anyhow::Result<()> {
216    if keys.is_empty() {
217        return Ok(());
218    }
219    let mut resolved = read_resolved_json(project_dir)?;
220    for k in keys {
221        resolved.entries.remove(k);
222    }
223    resolved.generated_at = now_iso();
224    write_resolved_json(project_dir, &resolved)
225}
226
227/// Two entries are equal ignoring `fetched_at` (the TS `stripFetchedAt`
228/// comparison, done structurally instead of via JSON).
229fn eq_ignoring_fetched_at(a: &ResolvedEntry, b: &ResolvedEntry) -> bool {
230    let mut a = a.clone();
231    a.fetched_at = b.fetched_at.clone();
232    &a == b
233}
234
235/// Current UTC time as an RFC3339 string (`new Date().toISOString()` analog).
236fn now_iso() -> String {
237    OffsetDateTime::now_utc()
238        .format(&Rfc3339)
239        .expect("Rfc3339 formatting of now_utc is infallible")
240}
241
242#[cfg(test)]
243mod tests {
244    use super::*;
245    use crate::ask_json::entry_from_spec;
246
247    fn tmp() -> tempfile::TempDir {
248        tempfile::tempdir().unwrap()
249    }
250
251    #[test]
252    fn sorted_json_sorts_keys_recursively_with_trailing_newline() {
253        let value = serde_json::json!({ "b": 1, "a": { "d": 2, "c": 3 } });
254        let out = sorted_json(&value);
255        assert_eq!(
256            out,
257            "{\n  \"a\": {\n    \"c\": 3,\n    \"d\": 2\n  },\n  \"b\": 1\n}\n"
258        );
259    }
260
261    #[test]
262    fn content_hash_is_order_independent_and_nul_separated() {
263        let f = |p: &str, c: &str| HashableFile {
264            relpath: p.into(),
265            bytes: None,
266            content: Some(c.into()),
267        };
268        let a = content_hash(&[f("a.md", "x"), f("b.md", "y")]);
269        let b = content_hash(&[f("b.md", "y"), f("a.md", "x")]);
270        assert_eq!(a, b, "sorting by relpath makes order irrelevant");
271        assert!(a.starts_with("sha256-"));
272        assert_eq!(a.len(), "sha256-".len() + 64);
273        // NUL separation: ("ab","cd") must differ from ("a","bcd").
274        assert_ne!(
275            content_hash(&[f("ab", "cd")]),
276            content_hash(&[f("a", "bcd")])
277        );
278    }
279
280    #[test]
281    fn content_hash_matches_known_vector() {
282        // sha256 of "a.md\0hello\0" — pin the exact stream format.
283        let h = content_hash(&[HashableFile {
284            relpath: "a.md".into(),
285            bytes: None,
286            content: Some("hello".into()),
287        }]);
288        let mut hasher = Sha256::new();
289        hasher.update(b"a.md\0hello\0");
290        assert_eq!(h, format!("sha256-{:x}", hasher.finalize()));
291    }
292
293    #[test]
294    fn read_missing_ask_json_is_none() {
295        let dir = tmp();
296        assert!(read_ask_json(dir.path()).unwrap().is_none());
297    }
298
299    #[test]
300    fn write_then_read_ask_json_roundtrips() {
301        let dir = tmp();
302        let ask = AskJson {
303            libraries: vec![
304                LibraryEntry::Spec("npm:next".into()),
305                entry_from_spec("npm:zod", &["docs/API.md".to_string()]),
306            ],
307        };
308        write_ask_json(dir.path(), &ask).unwrap();
309        // ask.json is at the root, not under .ask/.
310        assert!(dir.path().join("ask.json").exists());
311        let back = read_ask_json(dir.path()).unwrap().unwrap();
312        assert_eq!(back, ask);
313    }
314
315    #[test]
316    fn find_entry_three_ways() {
317        let ask = AskJson {
318            libraries: vec![
319                LibraryEntry::Spec("npm:next".into()),
320                LibraryEntry::Spec("npm:@mastra/client-js".into()),
321                LibraryEntry::Spec("github:vercel/next.js@v14.2.3".into()),
322            ],
323        };
324        // 1. exact spec
325        assert_eq!(find_entry(&ask, "npm:next").unwrap().spec(), "npm:next");
326        // 2. library name (with version stripped)
327        assert_eq!(
328            find_entry(&ask, "next.js").unwrap().spec(),
329            "github:vercel/next.js@v14.2.3"
330        );
331        // 3. raw npm package name (scoped)
332        assert_eq!(
333            find_entry(&ask, "@mastra/client-js").unwrap().spec(),
334            "npm:@mastra/client-js"
335        );
336        assert!(find_entry(&ask, "nonexistent").is_none());
337    }
338
339    #[test]
340    fn read_missing_resolved_is_empty_default() {
341        let dir = tmp();
342        let r = read_resolved_json(dir.path()).unwrap();
343        assert_eq!(r.schema_version, 1);
344        assert!(r.entries.is_empty());
345    }
346
347    #[test]
348    fn corrupt_resolved_json_falls_back_to_empty() {
349        let dir = tmp();
350        let file = get_resolved_json_path(dir.path());
351        std::fs::create_dir_all(file.parent().unwrap()).unwrap();
352        std::fs::write(&file, "{ not valid json").unwrap();
353        assert!(read_resolved_json(dir.path()).unwrap().entries.is_empty());
354    }
355
356    fn sample_entry(spec: &str) -> ResolvedEntry {
357        ResolvedEntry {
358            spec: spec.into(),
359            resolved_version: "1.0.0".into(),
360            content_hash: format!("sha256-{}", "0".repeat(64)),
361            fetched_at: "2026-07-04T00:00:00Z".into(),
362            file_count: 1,
363            format: None,
364            store_path: None,
365            materialization: None,
366            in_place_path: None,
367            commit: None,
368            store_subpath: None,
369        }
370    }
371
372    #[test]
373    fn upsert_then_remove_resolved_entry() {
374        let dir = tmp();
375        upsert_resolved_entry(dir.path(), "next", sample_entry("npm:next")).unwrap();
376        let r = read_resolved_json(dir.path()).unwrap();
377        assert!(r.entries.contains_key("next"));
378        // generatedAt was stamped to a real time (not the 1970 default).
379        assert_ne!(r.generated_at, "1970-01-01T00:00:00Z");
380
381        remove_resolved_entries(dir.path(), &["next".to_string()]).unwrap();
382        assert!(!read_resolved_json(dir.path())
383            .unwrap()
384            .entries
385            .contains_key("next"));
386    }
387
388    #[test]
389    fn upsert_skips_rewrite_when_only_fetched_at_differs() {
390        let dir = tmp();
391        upsert_resolved_entry(dir.path(), "next", sample_entry("npm:next")).unwrap();
392        let first = read_resolved_json(dir.path()).unwrap().generated_at.clone();
393
394        // Same entry but a different fetched_at → treated as unchanged, no rewrite.
395        let mut again = sample_entry("npm:next");
396        again.fetched_at = "2099-01-01T00:00:00Z".into();
397        upsert_resolved_entry(dir.path(), "next", again).unwrap();
398        assert_eq!(read_resolved_json(dir.path()).unwrap().generated_at, first);
399
400        // A material change (version) → rewrite.
401        let mut changed = sample_entry("npm:next");
402        changed.resolved_version = "2.0.0".into();
403        upsert_resolved_entry(dir.path(), "next", changed).unwrap();
404        assert_eq!(
405            read_resolved_json(dir.path()).unwrap().entries["next"].resolved_version,
406            "2.0.0"
407        );
408    }
409}