Skip to main content

rap_steering_server/
lib.rs

1use std::collections::HashSet;
2use std::path::{Path, PathBuf};
3
4use serde::Deserialize;
5use tokio::fs;
6
7/// Single-file steering locations (relative to project root).
8const SINGLE_FILES: &[&str] = &[
9    "INFINITY.md",
10    "CLAUDE.md",
11    ".claude/settings.json",
12    "AGENTS.md",
13    ".cursorrules",
14    ".github/copilot-instructions.md",
15    ".windsurfrules",
16    "CONVENTIONS.md",
17];
18
19/// Directory steering locations — all files recursively.
20const DIRECTORIES: &[&str] = &[
21    ".kiro/steering",
22    ".cursor/rules",
23    ".ai/rules",
24    ".claude/skills",
25];
26
27#[derive(Debug, Deserialize)]
28pub struct ListSteeringArgs {
29    pub root: String,
30}
31
32#[derive(Debug, Deserialize)]
33pub struct LoadSteeringArgs {
34    pub root: String,
35    pub path: String,
36}
37
38/// Recursively collect all files under `dir`, returning paths relative to `root`.
39async fn collect_files_recursive(root: &Path, dir: &Path) -> Vec<PathBuf> {
40    let mut result = Vec::new();
41    let mut stack = vec![dir.to_path_buf()];
42    while let Some(current) = stack.pop() {
43        let Ok(mut entries) = fs::read_dir(&current).await else {
44            continue;
45        };
46        while let Ok(Some(entry)) = entries.next_entry().await {
47            let path = entry.path();
48            if path.is_dir() {
49                stack.push(path);
50            } else if let Ok(rel) = path.strip_prefix(root) {
51                result.push(rel.to_path_buf());
52            }
53        }
54    }
55    result
56}
57
58/// Collect steering candidates from a base directory, returning paths relative to that base.
59async fn collect_candidates(base: &Path) -> Vec<PathBuf> {
60    let mut candidates = Vec::new();
61    for f in SINGLE_FILES {
62        candidates.push(PathBuf::from(f));
63    }
64    for dir in DIRECTORIES {
65        let dir_path = base.join(dir);
66        if dir_path.is_dir() {
67            candidates.extend(collect_files_recursive(base, &dir_path).await);
68        }
69    }
70    candidates
71}
72
73/// Discover all steering files under `root` and the user's home directory,
74/// canonicalize to dedup symlinks, and return sorted relative paths.
75/// Home directory files are prefixed with `~/`.
76pub async fn list_steering_files(root: &Path) -> Result<Vec<String>, String> {
77    let canon_root = fs::canonicalize(root)
78        .await
79        .map_err(|e| format!("cannot canonicalize root: {e}"))?;
80
81    let mut seen_canonical = HashSet::new();
82    let mut results = Vec::new();
83
84    // Scan project root
85    for rel in collect_candidates(root).await {
86        let abs = root.join(&rel);
87        if !abs.exists() {
88            continue;
89        }
90        let Ok(canonical) = fs::canonicalize(&abs).await else {
91            continue;
92        };
93        // Verify it's under root (safety check)
94        if !canonical.starts_with(&canon_root) {
95            continue;
96        }
97        if seen_canonical.insert(canonical) {
98            results.push(rel.to_string_lossy().into_owned());
99        }
100    }
101
102    // Scan home directory
103    if let Some(home) = home_dir()
104        && let Ok(canon_home) = fs::canonicalize(&home).await
105        && canon_home != canon_root
106    {
107        for rel in collect_candidates(&home).await {
108            let abs = home.join(&rel);
109            if !abs.exists() {
110                continue;
111            }
112            let Ok(canonical) = fs::canonicalize(&abs).await else {
113                continue;
114            };
115            if !canonical.starts_with(&canon_home) {
116                continue;
117            }
118            if seen_canonical.insert(canonical) {
119                results.push(format!("~/{}", rel.to_string_lossy()));
120            }
121        }
122    }
123
124    results.sort();
125    Ok(results)
126}
127
128fn home_dir() -> Option<PathBuf> {
129    std::env::var_os("HOME").map(PathBuf::from)
130}
131
132/// Check that `rel` is under a known steering location.
133fn is_known_steering_location(rel: &str) -> bool {
134    let rel_path = Path::new(rel);
135    SINGLE_FILES.contains(&rel) || DIRECTORIES.iter().any(|d| rel_path.starts_with(d))
136}
137
138/// Load a steering file, with path traversal prevention.
139/// Paths prefixed with `~/` are resolved relative to the home directory.
140pub async fn load_steering_file(root: &Path, rel_path: &str) -> Result<String, String> {
141    let (base, rel) = if let Some(stripped) = rel_path.strip_prefix("~/") {
142        let home = home_dir().ok_or_else(|| "HOME not set".to_owned())?;
143        (home, stripped)
144    } else {
145        (root.to_path_buf(), rel_path)
146    };
147
148    if !is_known_steering_location(rel) {
149        return Err("not a steering file location".to_owned());
150    }
151
152    let canon_base = fs::canonicalize(&base)
153        .await
154        .map_err(|e| format!("cannot canonicalize base: {e}"))?;
155
156    let abs = base.join(rel);
157    let canonical = fs::canonicalize(&abs)
158        .await
159        .map_err(|e| format!("file not found: {e}"))?;
160
161    if !canonical.starts_with(&canon_base) {
162        return Err("path traversal denied".to_owned());
163    }
164
165    fs::read_to_string(&canonical)
166        .await
167        .map_err(|e| format!("failed to read file: {e}"))
168}