Skip to main content

ask/
storage.rs

1//! Project-local docs materialization + the `ask list` view. Rust port of
2//! `packages/cli/src/storage.ts`.
3//!
4//! `save_docs` writes (or links/refs) the fetched docs under
5//! `.ask/docs/<name>@<version>/`; `list_docs` joins `ask.json` (intent) with
6//! `.ask/resolved.json` (last materialization) for `ask list`.
7
8use std::path::{Path, PathBuf};
9
10pub use crate::ask_json::StoreMode;
11use crate::io::{empty_resolved, get_ask_dir, read_ask_json, read_resolved_json};
12use crate::resolved::{EntryFormat, Materialization};
13use crate::sources::DocFile;
14use crate::spec::library_name_from_spec;
15
16/// Options for [`save_docs`].
17#[derive(Debug, Clone, Default)]
18pub struct SaveDocsOptions {
19    pub store_mode: StoreMode,
20    pub store_path: Option<PathBuf>,
21    /// Relative docs subpath inside `store_path` (github `docsPath`). Link/ref
22    /// modes join this so the symlink/ref target is the docs dir, not the repo
23    /// root.
24    pub store_subpath: Option<String>,
25}
26
27pub fn get_docs_dir(project_dir: &Path) -> PathBuf {
28    get_ask_dir(project_dir).join("docs")
29}
30
31pub fn get_library_docs_dir(project_dir: &Path, name: &str, version: &str) -> PathBuf {
32    get_docs_dir(project_dir).join(format!("{name}@{version}"))
33}
34
35fn effective_store_path(store_path: &Path, store_subpath: Option<&str>) -> PathBuf {
36    match store_subpath.filter(|s| !s.is_empty()) {
37        Some(sub) => store_path.join(sub),
38        None => store_path.to_path_buf(),
39    }
40}
41
42/// Materialize docs into the project. Returns the path AGENTS.md should point at.
43pub fn save_docs(
44    project_dir: &Path,
45    name: &str,
46    version: &str,
47    files: &[DocFile],
48    options: &SaveDocsOptions,
49) -> anyhow::Result<PathBuf> {
50    let docs_dir = get_library_docs_dir(project_dir, name, version);
51
52    // ref mode: no project-local materialization.
53    if options.store_mode == StoreMode::Ref {
54        return Ok(match &options.store_path {
55            Some(sp) => effective_store_path(sp, options.store_subpath.as_deref()),
56            None => docs_dir,
57        });
58    }
59
60    // link mode: symlink project-local → store (docs subdir).
61    if options.store_mode == StoreMode::Link {
62        if let Some(sp) = &options.store_path {
63            let link_target = effective_store_path(sp, options.store_subpath.as_deref());
64            // Use symlink_metadata (examines the link itself), not exists (which
65            // follows it): a DANGLING symlink — left behind when `ask cache gc`
66            // deletes the store target — reports exists()==false, so the cleanup
67            // would be skipped and the following symlink_dir would fail EEXIST with
68            // a confusing "Failed to create symlink". remove_dir_all removes the
69            // link itself (verified for both live and dangling links), so the stale
70            // link is cleanly replaced.
71            if docs_dir.symlink_metadata().is_ok() {
72                std::fs::remove_dir_all(&docs_dir)?;
73            }
74            if let Some(parent) = docs_dir.parent() {
75                std::fs::create_dir_all(parent)?;
76            }
77            match symlink_dir(&link_target, &docs_dir) {
78                Ok(()) => return Ok(docs_dir),
79                Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => {
80                    // Clean up partial state, then fall through to copy.
81                    let _ = std::fs::remove_dir_all(&docs_dir);
82                    eprintln!(
83                        "  Symlink creation failed ({}), falling back to copy mode",
84                        e.kind()
85                    );
86                }
87                Err(e) => {
88                    let _ = std::fs::remove_dir_all(&docs_dir);
89                    anyhow::bail!("Failed to create symlink at {}: {e}", docs_dir.display());
90                }
91            }
92        }
93    }
94
95    // copy mode (default).
96    if docs_dir.exists() {
97        std::fs::remove_dir_all(&docs_dir)?;
98    }
99    std::fs::create_dir_all(&docs_dir)?;
100    for file in files {
101        let file_path = docs_dir.join(&file.path);
102        if let Some(parent) = file_path.parent() {
103            std::fs::create_dir_all(parent)?;
104        }
105        std::fs::write(&file_path, &file.content)?;
106    }
107    let index = files
108        .iter()
109        .map(|f| format!("- [{}](./{})", f.path, f.path))
110        .collect::<Vec<_>>()
111        .join("\n");
112    std::fs::write(
113        docs_dir.join("INDEX.md"),
114        format!("# {name}@{version} Documentation\n\n{index}\n"),
115    )?;
116
117    Ok(docs_dir)
118}
119
120#[cfg(unix)]
121fn symlink_dir(target: &Path, link: &Path) -> std::io::Result<()> {
122    std::os::unix::fs::symlink(target, link)
123}
124
125#[cfg(not(unix))]
126fn symlink_dir(target: &Path, link: &Path) -> std::io::Result<()> {
127    std::os::windows::fs::symlink_dir(target, link)
128}
129
130/// Remove project-local docs for `name` (all versions when `version` is `None`).
131pub fn remove_docs(project_dir: &Path, name: &str, version: Option<&str>) -> anyhow::Result<()> {
132    if let Some(version) = version {
133        let docs_dir = get_library_docs_dir(project_dir, name, version);
134        if docs_dir.exists() {
135            std::fs::remove_dir_all(&docs_dir)?;
136        }
137        return Ok(());
138    }
139    let base = get_docs_dir(project_dir);
140    if !base.exists() {
141        return Ok(());
142    }
143    let prefix = format!("{name}@");
144    for entry in std::fs::read_dir(&base)? {
145        let entry = entry?;
146        if entry.file_name().to_string_lossy().starts_with(&prefix) {
147            std::fs::remove_dir_all(entry.path())?;
148        }
149    }
150    Ok(())
151}
152
153/// Source classification for a list entry.
154#[derive(Debug, Clone, Copy, PartialEq, Eq)]
155pub enum ListSource {
156    PmDriven,
157    Github,
158    Unresolved,
159}
160
161/// One `ask list` row, joined from `ask.json` + `.ask/resolved.json`. Entries
162/// declared but never installed surface as `version: "unresolved"`.
163#[derive(Debug, Clone, PartialEq, Eq)]
164pub struct ListDocsEntry {
165    pub name: String,
166    pub version: String,
167    pub format: EntryFormat,
168    pub source: ListSource,
169    pub spec: String,
170    pub location: String,
171    pub file_count: u64,
172}
173
174pub fn list_docs(project_dir: &Path) -> Vec<ListDocsEntry> {
175    let Ok(Some(ask_json)) = read_ask_json(project_dir) else {
176        return Vec::new();
177    };
178    // `ask list` is a display-only, infallible lister (it already returns empty
179    // on an unreadable ask.json). It performs no rewrites, so masking a resolved
180    // read error here can't trigger the incorrect-rewrite bug the read_resolved_json
181    // change guards against — keep the infallible signature with an empty fallback.
182    let resolved = read_resolved_json(project_dir).unwrap_or_else(|_| empty_resolved());
183
184    let mut out = Vec::new();
185    for entry in &ask_json.libraries {
186        let spec = entry.spec().to_string();
187        let name = library_name_from_spec(&spec);
188        let source_kind = if spec.starts_with("github:") {
189            ListSource::Github
190        } else {
191            ListSource::PmDriven
192        };
193
194        let Some(cached) = resolved.entries.get(&name) else {
195            out.push(ListDocsEntry {
196                name,
197                version: "unresolved".into(),
198                format: EntryFormat::Docs,
199                source: ListSource::Unresolved,
200                spec,
201                location: "(not installed — run `ask install`)".into(),
202                file_count: 0,
203            });
204            continue;
205        };
206
207        // intent-skills format: docs live in node_modules; the skill listing is
208        // sourced from the AGENTS.md intent block (agents-intent, deferred).
209        if cached.format == Some(EntryFormat::IntentSkills) {
210            out.push(ListDocsEntry {
211                name,
212                version: cached.resolved_version.clone(),
213                format: EntryFormat::IntentSkills,
214                source: source_kind,
215                spec: spec.clone(),
216                location: format!("node_modules/{}", pkg_from_spec(&spec)),
217                file_count: 0,
218            });
219            continue;
220        }
221
222        if cached.materialization == Some(Materialization::InPlace) {
223            if let Some(in_place) = &cached.in_place_path {
224                out.push(ListDocsEntry {
225                    name,
226                    version: cached.resolved_version.clone(),
227                    format: EntryFormat::Docs,
228                    source: source_kind,
229                    spec,
230                    location: in_place.clone(),
231                    file_count: cached.file_count,
232                });
233                continue;
234            }
235        }
236
237        let docs_dir = get_library_docs_dir(project_dir, &name, &cached.resolved_version);
238        let file_count = if docs_dir.exists() {
239            count_files(&docs_dir)
240        } else {
241            cached.file_count
242        };
243        let location = pathdiff_relative(project_dir, &docs_dir)
244            .unwrap_or_else(|| docs_dir.to_string_lossy().into_owned());
245        out.push(ListDocsEntry {
246            name,
247            version: cached.resolved_version.clone(),
248            format: EntryFormat::Docs,
249            source: source_kind,
250            spec,
251            location,
252            file_count,
253        });
254    }
255    out.sort_by(|a, b| a.name.cmp(&b.name));
256    out
257}
258
259fn pkg_from_spec(spec: &str) -> &str {
260    match spec.find(':') {
261        Some(i) => &spec[i + 1..],
262        None => spec,
263    }
264}
265
266/// Path of `target` relative to `base` (forward-slash), or `None` when `target`
267/// is not under `base`.
268fn pathdiff_relative(base: &Path, target: &Path) -> Option<String> {
269    let rel = target.strip_prefix(base).ok()?;
270    if rel.as_os_str().is_empty() {
271        return None;
272    }
273    Some(
274        rel.components()
275            .map(|c| c.as_os_str().to_string_lossy())
276            .collect::<Vec<_>>()
277            .join("/"),
278    )
279}
280
281fn count_files(dir: &Path) -> u64 {
282    let mut count = 0;
283    let Ok(entries) = std::fs::read_dir(dir) else {
284        return 0;
285    };
286    for entry in entries.flatten() {
287        match entry.file_type() {
288            Ok(t) if t.is_dir() => count += count_files(&entry.path()),
289            Ok(_) => count += 1,
290            Err(_) => {}
291        }
292    }
293    count
294}
295
296#[cfg(test)]
297mod tests {
298    use super::*;
299
300    fn df(path: &str, content: &str) -> DocFile {
301        DocFile {
302            path: path.into(),
303            content: content.into(),
304        }
305    }
306
307    #[test]
308    fn save_copy_writes_files_and_index() {
309        let dir = tempfile::tempdir().unwrap();
310        let out = save_docs(
311            dir.path(),
312            "acme",
313            "1.0.0",
314            &[df("a.md", "A"), df("sub/b.md", "B")],
315            &SaveDocsOptions::default(),
316        )
317        .unwrap();
318        assert!(out.ends_with(".ask/docs/acme@1.0.0"));
319        assert_eq!(std::fs::read_to_string(out.join("a.md")).unwrap(), "A");
320        assert_eq!(std::fs::read_to_string(out.join("sub/b.md")).unwrap(), "B");
321        let index = std::fs::read_to_string(out.join("INDEX.md")).unwrap();
322        assert!(index.contains("# acme@1.0.0 Documentation"));
323        assert!(index.contains("- [a.md](./a.md)"));
324    }
325
326    #[test]
327    fn save_copy_replaces_existing() {
328        let dir = tempfile::tempdir().unwrap();
329        save_docs(
330            dir.path(),
331            "acme",
332            "1.0.0",
333            &[df("old.md", "x")],
334            &SaveDocsOptions::default(),
335        )
336        .unwrap();
337        let out = save_docs(
338            dir.path(),
339            "acme",
340            "1.0.0",
341            &[df("new.md", "y")],
342            &SaveDocsOptions::default(),
343        )
344        .unwrap();
345        assert!(!out.join("old.md").exists());
346        assert!(out.join("new.md").exists());
347    }
348
349    #[test]
350    fn ref_mode_returns_effective_store_path() {
351        let dir = tempfile::tempdir().unwrap();
352        let store = dir.path().join("store/github.com/o/r/v1");
353        let out = save_docs(
354            dir.path(),
355            "acme",
356            "1.0.0",
357            &[],
358            &SaveDocsOptions {
359                store_mode: StoreMode::Ref,
360                store_path: Some(store.clone()),
361                store_subpath: Some("docs".into()),
362            },
363        )
364        .unwrap();
365        assert_eq!(out, store.join("docs"));
366        // Nothing was materialized locally.
367        assert!(!get_library_docs_dir(dir.path(), "acme", "1.0.0").exists());
368    }
369
370    #[cfg(unix)]
371    #[test]
372    fn link_mode_creates_symlink_to_subpath() {
373        let dir = tempfile::tempdir().unwrap();
374        let store = dir.path().join("store");
375        std::fs::create_dir_all(store.join("docs")).unwrap();
376        std::fs::write(store.join("docs/guide.md"), "G").unwrap();
377        let out = save_docs(
378            dir.path(),
379            "acme",
380            "1.0.0",
381            &[],
382            &SaveDocsOptions {
383                store_mode: StoreMode::Link,
384                store_path: Some(store.clone()),
385                store_subpath: Some("docs".into()),
386            },
387        )
388        .unwrap();
389        assert!(out.symlink_metadata().unwrap().file_type().is_symlink());
390        assert_eq!(std::fs::read_to_string(out.join("guide.md")).unwrap(), "G");
391    }
392
393    #[test]
394    fn remove_docs_by_version_and_all() {
395        let dir = tempfile::tempdir().unwrap();
396        save_docs(
397            dir.path(),
398            "acme",
399            "1.0.0",
400            &[df("a.md", "A")],
401            &SaveDocsOptions::default(),
402        )
403        .unwrap();
404        save_docs(
405            dir.path(),
406            "acme",
407            "2.0.0",
408            &[df("a.md", "A")],
409            &SaveDocsOptions::default(),
410        )
411        .unwrap();
412        remove_docs(dir.path(), "acme", Some("1.0.0")).unwrap();
413        assert!(!get_library_docs_dir(dir.path(), "acme", "1.0.0").exists());
414        assert!(get_library_docs_dir(dir.path(), "acme", "2.0.0").exists());
415        remove_docs(dir.path(), "acme", None).unwrap();
416        assert!(!get_library_docs_dir(dir.path(), "acme", "2.0.0").exists());
417    }
418
419    #[test]
420    fn list_docs_empty_without_ask_json() {
421        let dir = tempfile::tempdir().unwrap();
422        assert!(list_docs(dir.path()).is_empty());
423    }
424
425    #[test]
426    fn list_docs_marks_unresolved_and_resolved() {
427        let dir = tempfile::tempdir().unwrap();
428        std::fs::create_dir_all(get_ask_dir(dir.path())).unwrap();
429        std::fs::write(
430            crate::io::get_ask_json_path(dir.path()),
431            r#"{"libraries":["npm:acme","github:o/other"]}"#,
432        )
433        .unwrap();
434        // Only acme is resolved.
435        std::fs::write(
436            crate::io::get_resolved_json_path(dir.path()),
437            r#"{"schemaVersion":1,"generatedAt":"2026-01-01T00:00:00Z","entries":{
438              "acme":{"spec":"npm:acme","resolvedVersion":"1.2.3",
439                "contentHash":"sha256-0000000000000000000000000000000000000000000000000000000000000000",
440                "fetchedAt":"2026-01-01T00:00:00Z","fileCount":3}}}"#,
441        )
442        .unwrap();
443
444        let entries = list_docs(dir.path());
445        assert_eq!(entries.len(), 2);
446        // Sorted by name: "acme" before "other".
447        assert_eq!(entries[0].name, "acme");
448        assert_eq!(entries[0].version, "1.2.3");
449        assert_eq!(entries[0].source, ListSource::PmDriven);
450        assert_eq!(entries[1].name, "other");
451        assert_eq!(entries[1].version, "unresolved");
452        assert_eq!(entries[1].source, ListSource::Unresolved);
453    }
454}