aidaemon_core/project.rs
1//! The project a turn works in.
2
3use std::path::PathBuf;
4
5/// The project a turn works in: a unit of work the host keeps (an app's
6/// project, a bot placed in one), with the folder it lives in when it has
7/// one. Memory and tools key project-scoped state on [`ProjectRef::id`],
8/// which stays the same when the project is renamed or its folder moves.
9///
10/// The host resolves it from its own typed state (which project a
11/// conversation is placed in, which folder a turn is bound to), never from
12/// what a message says.
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub struct ProjectRef {
15 /// Stable id. Only ASCII letters, digits, `-` and `_` (see
16 /// [`ProjectRef::is_valid_id`]), so it is safe as a directory name.
17 pub id: String,
18 /// The name the owner gave it.
19 pub name: String,
20 /// The folder, absolute, when the project has one.
21 pub root: Option<PathBuf>,
22}
23
24impl ProjectRef {
25 /// A project, when `id` is a valid project id.
26 pub fn new(
27 id: impl Into<String>,
28 name: impl Into<String>,
29 root: Option<PathBuf>,
30 ) -> Option<Self> {
31 let id = id.into();
32 Self::is_valid_id(&id).then(|| Self {
33 id,
34 name: name.into(),
35 root,
36 })
37 }
38
39 /// 1–128 ASCII letters, digits, `-` or `_`, not starting with `-`: a
40 /// name that cannot leave the directory it is joined to.
41 pub fn is_valid_id(id: &str) -> bool {
42 !id.is_empty()
43 && id.len() <= 128
44 && !id.starts_with('-')
45 && id
46 .bytes()
47 .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
48 }
49}
50
51#[cfg(test)]
52mod tests {
53 use super::*;
54
55 #[test]
56 fn ids_cannot_leave_their_directory() {
57 assert!(ProjectRef::is_valid_id(
58 "project-0a1b2c3d-0000-4000-8000-000000000001"
59 ));
60 assert!(ProjectRef::is_valid_id("acme_site"));
61 for bad in [
62 "",
63 "..",
64 "../x",
65 "a/b",
66 "a\\b",
67 "-rf",
68 "a b",
69 "é",
70 &"x".repeat(129),
71 ] {
72 assert!(!ProjectRef::is_valid_id(bad), "{bad:?}");
73 }
74 assert!(ProjectRef::new("../etc", "x", None).is_none());
75 }
76}