Skip to main content

subspace_core/
copilot_agent_tasks.rs

1//! Private subject-to-task references. Prompts and credentials are never stored.
2
3use std::collections::BTreeMap;
4use std::fs;
5use std::io;
6use std::path::PathBuf;
7use std::sync::{Mutex, PoisonError};
8
9use serde::{Deserialize, Serialize};
10
11use crate::{config, state};
12
13mod submission;
14pub use submission::{SUBMISSION_TIMEOUT, Submission, SubmissionTimeout};
15
16const MAX_SUBJECT_TASKS: usize = 50;
17const MAX_SUBJECT_ID_CHARS: usize = 200;
18const MAX_TASK_ID_CHARS: usize = 100;
19/// The current file version. Version 1 had no `monitor` flag.
20const FILE_VERSION: u32 = 2;
21/// The directory mode of the task file's directory: owner only.
22#[cfg(unix)]
23const OWNER_ONLY_DIR_MODE: u32 = 0o700;
24// Two dashboards share one file. Keep its read-modify-write operation atomic
25// within the process, including across separately constructed store handles.
26static WRITES: Mutex<()> = Mutex::new(());
27
28#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
29#[serde(rename_all = "camelCase")]
30pub struct TaskRef {
31    pub repo: String,
32    pub task_id: String,
33    pub created_at: String,
34    /// Whether a finished or stuck task raises an alert. Version 1 files have
35    /// no flag; they read as monitored, which only affects active tasks
36    /// because the watcher polls no others.
37    #[serde(default = "monitored_by_default")]
38    pub monitor: bool,
39}
40
41fn monitored_by_default() -> bool {
42    true
43}
44
45/// One subject's reference, for a caller that works across subjects.
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub struct SubjectTaskRef {
48    pub subject: String,
49    pub task: TaskRef,
50}
51
52#[derive(Serialize, Deserialize)]
53struct File {
54    version: u32,
55    subjects: BTreeMap<String, Vec<TaskRef>>,
56}
57
58impl Default for File {
59    fn default() -> Self {
60        Self {
61            version: FILE_VERSION,
62            subjects: BTreeMap::new(),
63        }
64    }
65}
66
67// qual:api
68#[derive(Clone)]
69pub struct TaskStore {
70    file: PathBuf,
71}
72
73impl TaskStore {
74    pub fn from_system() -> Option<Self> {
75        state::sibling("copilot-agent-tasks.json").map(Self::new)
76    }
77
78    pub fn new(file: PathBuf) -> Self {
79        Self { file }
80    }
81
82    fn read(&self) -> io::Result<File> {
83        let text = match fs::read_to_string(&self.file) {
84            Ok(text) => text,
85            Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(File::default()),
86            Err(error) => return Err(error),
87        };
88        let mut file: File = serde_json::from_str(&text).map_err(io::Error::other)?;
89        if file.version == 0 || file.version > FILE_VERSION {
90            return Err(io::Error::new(
91                io::ErrorKind::InvalidData,
92                "Unknown agent task file version.",
93            ));
94        }
95        file.version = FILE_VERSION;
96        file.subjects.retain(|subject, entries| {
97            entries.retain(valid_entry);
98            valid_subject(subject)
99        });
100        Ok(file)
101    }
102
103    pub fn tasks(&self, subject: &str) -> io::Result<Vec<TaskRef>> {
104        if !valid_subject(subject) {
105            return Err(io::Error::new(
106                io::ErrorKind::InvalidInput,
107                "Invalid agent subject.",
108            ));
109        }
110        let _guard = WRITES.lock().unwrap_or_else(PoisonError::into_inner);
111        let mut entries = self.read()?.subjects.remove(subject).unwrap_or_default();
112        entries.drain(..entries.len().saturating_sub(MAX_SUBJECT_TASKS));
113        Ok(entries)
114    }
115
116    pub fn record(&self, subject: &str, entry: TaskRef) -> io::Result<()> {
117        if !valid_subject(subject) || !valid_entry(&entry) {
118            return Err(io::Error::new(
119                io::ErrorKind::InvalidInput,
120                "Invalid agent task reference.",
121            ));
122        }
123        let _guard = WRITES.lock().unwrap_or_else(PoisonError::into_inner);
124        let mut file = self.read()?;
125        let entries = file.subjects.entry(subject.to_owned()).or_default();
126        entries.retain(|existing| {
127            existing.task_id != entry.task_id || !existing.repo.eq_ignore_ascii_case(&entry.repo)
128        });
129        entries.push(entry);
130        entries.drain(..entries.len().saturating_sub(MAX_SUBJECT_TASKS));
131        self.save(&file)
132    }
133
134    /// Every reference the file holds, with the subject that owns it.
135    pub fn all(&self) -> io::Result<Vec<SubjectTaskRef>> {
136        let _guard = WRITES.lock().unwrap_or_else(PoisonError::into_inner);
137        Ok(flatten(self.read()?.subjects))
138    }
139
140    /// Turns alerts on or off for every reference to `task_id`. `false` means
141    /// the file holds no such task.
142    // qual:api
143    pub fn set_monitor(&self, task_id: &str, monitor: bool) -> io::Result<bool> {
144        let _guard = WRITES.lock().unwrap_or_else(PoisonError::into_inner);
145        let mut file = self.read()?;
146        if !apply_monitor(&mut file.subjects, task_id, monitor) {
147            return Ok(false);
148        }
149        self.save(&file)?;
150        Ok(true)
151    }
152
153    fn save(&self, file: &File) -> io::Result<()> {
154        if let Some(dir) = self.file.parent() {
155            let mut builder = fs::DirBuilder::new();
156            builder.recursive(true);
157            #[cfg(unix)]
158            {
159                use std::os::unix::fs::DirBuilderExt as _;
160                builder.mode(OWNER_ONLY_DIR_MODE);
161            }
162            builder.create(dir)?;
163        }
164        let text = serde_json::to_string_pretty(file).map_err(io::Error::other)?;
165        state::write_atomic(&self.file, &text)
166    }
167}
168
169/// The references of every subject, each paired with its subject key.
170fn flatten(subjects: BTreeMap<String, Vec<TaskRef>>) -> Vec<SubjectTaskRef> {
171    subjects
172        .into_iter()
173        .flat_map(|(subject, entries)| {
174            entries.into_iter().map(move |task| SubjectTaskRef {
175                subject: subject.clone(),
176                task,
177            })
178        })
179        .collect()
180}
181
182/// Sets the monitor flag of every matching reference; `false` means none did.
183fn apply_monitor(
184    subjects: &mut BTreeMap<String, Vec<TaskRef>>,
185    task_id: &str,
186    monitor: bool,
187) -> bool {
188    let mut found = false;
189    for entry in subjects.values_mut().flatten() {
190        if entry.task_id == task_id {
191            entry.monitor = monitor;
192            found = true;
193        }
194    }
195    found
196}
197
198fn valid_subject(subject: &str) -> bool {
199    let Some((kind, id)) = subject.split_once(':') else {
200        return false;
201    };
202    matches!(kind, "chat" | "other")
203        && (1..=MAX_SUBJECT_ID_CHARS).contains(&id.len())
204        && id
205            .bytes()
206            .all(|byte| byte.is_ascii_alphanumeric() || b"._:/-".contains(&byte))
207}
208
209fn valid_entry(entry: &TaskRef) -> bool {
210    config::is_repo(&entry.repo)
211        && (1..=MAX_TASK_ID_CHARS).contains(&entry.task_id.len())
212        && entry
213            .task_id
214            .bytes()
215            .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
216}
217
218#[cfg(test)]
219mod tests {
220    use std::fs;
221    use std::sync::Arc;
222    use std::thread;
223
224    use super::{TaskRef, TaskStore};
225
226    fn entry(id: &str) -> TaskRef {
227        TaskRef {
228            repo: "o/r".into(),
229            task_id: id.into(),
230            created_at: "2026-10-03T00:00:00Z".into(),
231            monitor: true,
232        }
233    }
234
235    #[test]
236    fn references_are_deduplicated_capped_and_survive_reload() {
237        let dir = tempfile::tempdir().unwrap();
238        let file = dir.path().join("private").join("tasks.json");
239        let store = TaskStore::new(file.clone());
240        for id in 0..55 {
241            store.record("other:issue", entry(&id.to_string())).unwrap();
242        }
243        store.record("other:issue", entry("54")).unwrap();
244        let loaded = TaskStore::new(file.clone()).tasks("other:issue").unwrap();
245        assert_eq!(loaded.len(), 50);
246        assert_eq!(loaded[0].task_id, "5");
247        assert_eq!(loaded[49].task_id, "54");
248        #[cfg(unix)]
249        {
250            use std::os::unix::fs::PermissionsExt as _;
251            assert_eq!(
252                fs::metadata(&file).unwrap().permissions().mode() & 0o777,
253                0o600
254            );
255            assert_eq!(
256                fs::metadata(file.parent().unwrap())
257                    .unwrap()
258                    .permissions()
259                    .mode()
260                    & 0o777,
261                0o700
262            );
263        }
264    }
265
266    #[test]
267    fn separate_handles_do_not_lose_concurrent_records() {
268        let dir = tempfile::tempdir().unwrap();
269        let file = Arc::new(dir.path().join("tasks.json"));
270        thread::scope(|scope| {
271            for id in 0..20 {
272                let file = file.clone();
273                scope.spawn(move || {
274                    TaskStore::new((*file).clone())
275                        .record("other:risk", entry(&id.to_string()))
276                        .unwrap()
277                });
278            }
279        });
280        assert_eq!(
281            TaskStore::new((*file).clone())
282                .tasks("other:risk")
283                .unwrap()
284                .len(),
285            20
286        );
287    }
288
289    #[test]
290    fn broken_files_are_not_overwritten_and_invalid_references_are_rejected() {
291        let dir = tempfile::tempdir().unwrap();
292        let file = dir.path().join("tasks.json");
293        fs::write(&file, "{broken").unwrap();
294        let store = TaskStore::new(file.clone());
295        assert!(store.record("other:risk", entry("task")).is_err());
296        assert_eq!(fs::read_to_string(file).unwrap(), "{broken");
297        assert!(store.tasks("bad:subject").is_err());
298        assert!(store.record("other:risk", entry("../unsafe")).is_err());
299    }
300
301    #[test]
302    fn version_1_files_load_as_monitored_and_save_as_version_2() {
303        let dir = tempfile::tempdir().unwrap();
304        let file = dir.path().join("tasks.json");
305        fs::write(
306            &file,
307            r#"{"version":1,"subjects":{"chat:task-1":[{"repo":"o/r","taskId":"task-1","createdAt":"2026-10-03T00:00:00Z"}]}}"#,
308        )
309        .unwrap();
310        let store = TaskStore::new(file.clone());
311        let loaded = store.tasks("chat:task-1").unwrap();
312        assert_eq!(loaded.len(), 1);
313        assert!(loaded[0].monitor, "a version 1 reference is monitored");
314        assert!(super::monitored_by_default());
315        store.record("chat:task-1", entry("task-2")).unwrap();
316        assert!(
317            fs::read_to_string(&file)
318                .unwrap()
319                .contains("\"version\": 2")
320        );
321        fs::write(&file, r#"{"version":3,"subjects":{}}"#).unwrap();
322        assert!(store.tasks("chat:task-1").is_err());
323    }
324
325    #[test]
326    fn monitoring_toggles_by_task_id_and_every_subject_is_listed() {
327        let dir = tempfile::tempdir().unwrap();
328        let store = TaskStore::new(dir.path().join("tasks.json"));
329        store.record("chat:task-1", entry("task-1")).unwrap();
330        store.record("other:issue", entry("task-2")).unwrap();
331        assert!(store.set_monitor("task-1", false).unwrap());
332        assert!(!store.set_monitor("missing", false).unwrap());
333        let all = store.all().unwrap();
334        assert_eq!(all.len(), 2);
335        assert_eq!(all[0].subject, "chat:task-1");
336        assert!(!all[0].task.monitor);
337        assert_eq!(all[1].subject, "other:issue");
338        assert!(all[1].task.monitor);
339        assert!(store.set_monitor("task-1", true).unwrap());
340        assert!(store.tasks("chat:task-1").unwrap()[0].monitor);
341    }
342}