Skip to main content

kiss_coding/workflows/
store.rs

1//! Saved workflows on disk.
2//!
3//! A saved workflow is a `.js` file whose `meta.name` becomes a slash command,
4//! following the same discovery rules as prompt templates in
5//! `crate::prompts`: the user's own directory always, and the project's only
6//! when the project is trusted.
7
8use kiss_workflow::Script;
9use std::path::{Path, PathBuf};
10
11/// A workflow found on disk.
12#[derive(Debug, Clone, PartialEq, Eq)]
13pub struct SavedWorkflow {
14    pub name: String,
15    pub description: String,
16    pub path: PathBuf,
17    /// True for a workflow in the project rather than the user's home.
18    pub from_project: bool,
19}
20
21/// Where a saved workflow can be written.
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum SaveLocation {
24    /// `.kiss/workflows/` in the project, shared with everyone who clones it.
25    Project,
26    /// `~/.kiss/agent/workflows/`, available in every project.
27    Personal,
28}
29
30pub fn user_workflow_dir() -> Option<PathBuf> {
31    kiss_ai::paths::agent_dir().map(|dir| dir.join("workflows"))
32}
33
34pub fn project_workflow_dir(cwd: &Path) -> PathBuf {
35    cwd.join(".kiss/workflows")
36}
37
38impl SaveLocation {
39    pub const ALL: [SaveLocation; 2] = [SaveLocation::Project, SaveLocation::Personal];
40
41    /// The folder as a user reads it, independent of the current project.
42    pub fn display_dir(self) -> &'static str {
43        match self {
44            SaveLocation::Project => ".kiss/workflows/",
45            SaveLocation::Personal => "~/.kiss/agent/workflows/",
46        }
47    }
48
49    pub fn directory(self, cwd: &Path) -> Option<PathBuf> {
50        match self {
51            SaveLocation::Project => Some(project_workflow_dir(cwd)),
52            SaveLocation::Personal => user_workflow_dir(),
53        }
54    }
55}
56
57fn scan(dir: &Path, from_project: bool, out: &mut Vec<SavedWorkflow>) {
58    let Ok(entries) = std::fs::read_dir(dir) else {
59        return;
60    };
61    for entry in entries.flatten() {
62        let path = entry.path();
63        if path.extension().and_then(|extension| extension.to_str()) != Some("js") {
64            continue;
65        }
66        let Ok(text) = std::fs::read_to_string(&path) else {
67            continue;
68        };
69        // A file that does not parse is skipped rather than reported: a broken
70        // file in the directory must not stop the others from loading, and the
71        // error surfaces when the user runs it.
72        let Ok(script) = Script::parse(&text) else {
73            continue;
74        };
75        out.push(SavedWorkflow {
76            name: script.meta().name.clone(),
77            description: script.meta().description.clone(),
78            path,
79            from_project,
80        });
81    }
82}
83
84/// Find every saved workflow, with the project's copy winning on a name clash.
85pub fn discover(cwd: &Path, project_trusted: bool) -> Vec<SavedWorkflow> {
86    let mut out = Vec::new();
87    if project_trusted {
88        scan(&project_workflow_dir(cwd), true, &mut out);
89    }
90    if let Some(dir) = user_workflow_dir() {
91        scan(&dir, false, &mut out);
92    }
93    out.sort_by(|left, right| left.name.cmp(&right.name));
94    let mut seen = std::collections::HashSet::new();
95    out.retain(|workflow| seen.insert(workflow.name.clone()));
96    out
97}
98
99/// Write a workflow script, refusing to follow a symbolic link.
100///
101/// Writing through a link would put the file somewhere the user did not choose,
102/// so each part of the path is checked first. The write goes through a
103/// temporary file in the same directory and is then renamed, so an interrupted
104/// save cannot leave a truncated script behind.
105pub fn save(
106    location: SaveLocation,
107    cwd: &Path,
108    name: &str,
109    source: &str,
110    overwrite: bool,
111) -> anyhow::Result<PathBuf> {
112    let name = name.trim();
113    if name.is_empty() || !name.bytes().all(is_name_byte) {
114        anyhow::bail!(
115            "a workflow name uses lower-case letters, digits, and dashes, for example \
116             `audit-routes`"
117        );
118    }
119    let directory = location
120        .directory(cwd)
121        .ok_or_else(|| anyhow::anyhow!("no home directory"))?;
122
123    // The project location has two directories of its own to check. The
124    // personal one is often managed by a dotfiles tool, so only the file itself
125    // is checked there.
126    if location == SaveLocation::Project {
127        for ancestor in [directory.parent(), Some(directory.as_path())]
128            .into_iter()
129            .flatten()
130        {
131            refuse_symlink(ancestor)?;
132        }
133    }
134
135    std::fs::create_dir_all(&directory)?;
136    let path = directory.join(format!("{name}.js"));
137    refuse_symlink(&path)?;
138    if path.exists() && !overwrite {
139        anyhow::bail!("{} already exists", path.display());
140    }
141
142    kiss_ai::config_file::write_atomic(&path, source.as_bytes())?;
143    Ok(path)
144}
145
146fn refuse_symlink(path: &Path) -> anyhow::Result<()> {
147    if std::fs::symlink_metadata(path).is_ok_and(|data| data.file_type().is_symlink()) {
148        anyhow::bail!(
149            "{} is a symbolic link. Saving there would write outside the location you chose",
150            path.display()
151        );
152    }
153    Ok(())
154}
155
156fn is_name_byte(byte: u8) -> bool {
157    byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-'
158}
159
160#[cfg(test)]
161mod tests {
162    use super::*;
163
164    const SCRIPT: &str =
165        "export const meta = { name: 'audit-routes', description: 'Audit routes' }\nreturn 1\n";
166
167    #[test]
168    fn a_saved_workflow_can_be_found_again_by_name() {
169        let dir = tempfile::tempdir().unwrap();
170        let path = save(
171            SaveLocation::Project,
172            dir.path(),
173            "audit-routes",
174            SCRIPT,
175            false,
176        )
177        .unwrap();
178        assert!(path.ends_with("audit-routes.js"));
179
180        let found = discover(dir.path(), true);
181        assert_eq!(found.len(), 1);
182        assert_eq!(found[0].name, "audit-routes");
183        assert_eq!(found[0].description, "Audit routes");
184        assert!(found[0].from_project);
185    }
186
187    #[test]
188    fn an_untrusted_project_contributes_no_workflows() {
189        let dir = tempfile::tempdir().unwrap();
190        save(
191            SaveLocation::Project,
192            dir.path(),
193            "audit-routes",
194            SCRIPT,
195            false,
196        )
197        .unwrap();
198        // The user's own directory may hold workflows on this machine, so the
199        // check is that the project's file is absent rather than that nothing
200        // was found.
201        assert!(
202            !discover(dir.path(), false)
203                .iter()
204                .any(|workflow| workflow.from_project)
205        );
206    }
207
208    #[test]
209    fn saving_twice_needs_permission_to_overwrite() {
210        let dir = tempfile::tempdir().unwrap();
211        save(SaveLocation::Project, dir.path(), "audit", SCRIPT, false).unwrap();
212        let error = save(SaveLocation::Project, dir.path(), "audit", SCRIPT, false).unwrap_err();
213        assert!(error.to_string().contains("already exists"));
214        assert!(save(SaveLocation::Project, dir.path(), "audit", SCRIPT, true).is_ok());
215    }
216
217    #[test]
218    fn a_bad_name_is_refused_with_an_example() {
219        let dir = tempfile::tempdir().unwrap();
220        for name in ["", "Audit Routes", "audit/routes", "../escape"] {
221            let error = save(SaveLocation::Project, dir.path(), name, SCRIPT, false)
222                .unwrap_err()
223                .to_string();
224            assert!(error.contains("audit-routes"), "{name}: {error}");
225        }
226    }
227
228    #[cfg(unix)]
229    #[test]
230    fn saving_refuses_to_write_through_a_symbolic_link() {
231        let dir = tempfile::tempdir().unwrap();
232        let elsewhere = tempfile::tempdir().unwrap();
233        std::fs::create_dir_all(dir.path().join(".kiss")).unwrap();
234        std::os::unix::fs::symlink(elsewhere.path(), dir.path().join(".kiss/workflows")).unwrap();
235
236        let error = save(SaveLocation::Project, dir.path(), "audit", SCRIPT, false)
237            .unwrap_err()
238            .to_string();
239        assert!(error.contains("symbolic link"), "{error}");
240        assert!(!elsewhere.path().join("audit.js").exists());
241    }
242
243    #[test]
244    fn a_file_that_does_not_parse_is_skipped_rather_than_breaking_discovery() {
245        let dir = tempfile::tempdir().unwrap();
246        let workflows = project_workflow_dir(dir.path());
247        std::fs::create_dir_all(&workflows).unwrap();
248        std::fs::write(workflows.join("broken.js"), "this is not a workflow").unwrap();
249        std::fs::write(workflows.join("good.js"), SCRIPT).unwrap();
250
251        let found: Vec<String> = discover(dir.path(), true)
252            .into_iter()
253            .filter(|workflow| workflow.from_project)
254            .map(|workflow| workflow.name)
255            .collect();
256        assert_eq!(found, ["audit-routes"]);
257    }
258
259    #[test]
260    fn the_name_comes_from_meta_not_from_the_file_name() {
261        let dir = tempfile::tempdir().unwrap();
262        let workflows = project_workflow_dir(dir.path());
263        std::fs::create_dir_all(&workflows).unwrap();
264        std::fs::write(workflows.join("whatever.js"), SCRIPT).unwrap();
265        let found = discover(dir.path(), true);
266        assert_eq!(found[0].name, "audit-routes");
267    }
268}