1use std::time::Duration;
6
7use aidaemon_tools::{ExecutionBackend, ExecutionRequest};
8
9use crate::goals::{HandoffArtifact, TaskAttempt, TaskWorkspace};
10use crate::stores::{TaskStore, WorkCoordinationStore};
11
12#[derive(Debug, Default)]
13pub struct WorkspaceEvidence {
14 pub artifacts: Vec<HandoffArtifact>,
15 pub verification: Vec<String>,
16}
17
18fn short_component(value: &str) -> String {
19 value
20 .chars()
21 .filter(|ch| ch.is_ascii_alphanumeric())
22 .take(12)
23 .collect()
24}
25
26fn safe_slug_component(value: &str) -> String {
27 let mut slug = String::new();
28 let mut previous_dash = false;
29 for ch in value.chars().flat_map(char::to_lowercase) {
30 if ch.is_ascii_alphanumeric() {
31 slug.push(ch);
32 previous_dash = false;
33 } else if !previous_dash && !slug.is_empty() {
34 slug.push('-');
35 previous_dash = true;
36 }
37 if slug.len() >= 48 {
38 break;
39 }
40 }
41 slug.trim_matches('-').to_string()
42}
43
44fn isolated_workspace_slug(description: &str, task_id: &str) -> String {
45 let lower = description.to_ascii_lowercase();
46 let words = lower
47 .split(|ch: char| !ch.is_ascii_alphanumeric())
48 .filter(|word| !word.is_empty())
49 .collect::<Vec<_>>();
50 let mut topic = Vec::new();
51 if let Some(index) = words.iter().position(|word| *word == "about") {
52 for word in words.iter().skip(index + 1).take(4) {
53 if matches!(*word, "and" | "then" | "with" | "in" | "under" | "for") {
54 break;
55 }
56 topic.push(*word);
57 }
58 }
59 let base = if topic.is_empty() {
60 "task".to_string()
61 } else {
62 let topic = safe_slug_component(&topic.join("-"));
63 if lower.contains("website") || lower.contains("web site") {
64 format!("{topic}-site")
65 } else {
66 topic
67 }
68 };
69 format!("{}-{}", base, short_component(task_id))
70}
71
72async fn git_output(
73 backend: &dyn ExecutionBackend,
74 cwd: &str,
75 args: Vec<String>,
76 timeout: Duration,
77) -> anyhow::Result<String> {
78 let mut full_args = vec!["-C".to_string(), cwd.to_string()];
79 full_args.extend(args);
80 let output = backend
81 .execute(ExecutionRequest::argv("git", full_args), timeout)
82 .await?;
83 anyhow::ensure!(
84 !output.timed_out,
85 "git command timed out while preparing task workspace"
86 );
87 anyhow::ensure!(
88 output.exit_code == 0,
89 "git command failed: {}",
90 output.stderr_lossy().trim()
91 );
92 Ok(output.stdout_lossy().trim().to_string())
93}
94
95pub async fn provision_task_workspace<S>(
98 backend: &dyn ExecutionBackend,
99 state: &S,
100 task_id: &str,
101 attempt: &TaskAttempt,
102 project_scope: Option<&str>,
103) -> anyhow::Result<TaskWorkspace>
104where
105 S: TaskStore + WorkCoordinationStore + ?Sized,
106{
107 if let Some(existing) = state.get_task_workspace(task_id).await?
108 && existing.attempt_id == attempt.id
109 && existing.status != "failed"
110 {
111 return Ok(existing);
112 }
113
114 let requested_policy = state.get_task_workspace_policy(task_id).await?;
115 let task_description = state
116 .get_task(task_id)
117 .await?
118 .map(|task| task.description)
119 .unwrap_or_default();
120 let now = chrono::Utc::now().to_rfc3339();
121 if matches!(requested_policy.as_str(), "shared" | "isolated") {
122 let requested_root = project_scope.unwrap_or_else(|| backend.workspace_root().as_str());
123 let requested_root = backend.resolve_path(requested_root).await?;
124 let workspace_container = backend.workspace_root();
125 let at_workspace_container = requested_root.as_str() == workspace_container.as_str();
126 let explicitly_shared = requested_policy == "shared"
131 && state.task_workspace_policy_is_explicit(task_id).await?;
132 let auto_isolate =
133 requested_policy == "isolated" || (at_workspace_container && !explicitly_shared);
134 let resolved_root = if auto_isolate && at_workspace_container {
135 workspace_container.join(isolated_workspace_slug(&task_description, task_id))
136 } else {
137 requested_root
138 };
139 backend.create_dir_all(&resolved_root).await?;
140 backend.canonicalize(&resolved_root).await?;
145 let root_path = resolved_root.to_string();
146 let workspace = TaskWorkspace {
147 id: uuid::Uuid::new_v4().to_string(),
148 task_id: task_id.to_string(),
149 attempt_id: attempt.id.clone(),
150 backend_id: backend.id().to_string(),
151 policy: if auto_isolate {
152 "isolated".to_string()
153 } else {
154 "shared".to_string()
155 },
156 root_path,
157 branch_name: None,
158 base_ref: None,
159 head_ref: None,
160 status: "active".to_string(),
161 created_at: now,
162 released_at: None,
163 };
164 state.create_task_workspace(&workspace).await?;
165 return Ok(workspace);
166 }
167
168 anyhow::ensure!(
169 requested_policy == "worktree",
170 "unsupported task workspace policy"
171 );
172 let scope = project_scope
173 .ok_or_else(|| anyhow::anyhow!("worktree policy requires an explicit project scope"))?;
174 let resolved_scope = backend.resolve_path(scope).await?;
175 let canonical_scope = backend.canonicalize(&resolved_scope).await?;
176 let git_root = git_output(
177 backend,
178 canonical_scope.as_str(),
179 vec!["rev-parse".to_string(), "--show-toplevel".to_string()],
180 Duration::from_secs(20),
181 )
182 .await?;
183 let base_ref = git_output(
184 backend,
185 &git_root,
186 vec!["rev-parse".to_string(), "HEAD".to_string()],
187 Duration::from_secs(20),
188 )
189 .await?;
190 let suffix = format!(
191 "{}-{}",
192 short_component(task_id),
193 short_component(&attempt.id)
194 );
195 let branch_name = format!("aidaemon/task-{suffix}");
196 let parent = backend.workspace_root().join(".aidaemon-workspaces");
197 backend.create_dir_all(&parent).await?;
198 let root = parent.join(&suffix);
199 let mut workspace = TaskWorkspace {
200 id: uuid::Uuid::new_v4().to_string(),
201 task_id: task_id.to_string(),
202 attempt_id: attempt.id.clone(),
203 backend_id: backend.id().to_string(),
204 policy: requested_policy,
205 root_path: root.as_str().to_string(),
206 branch_name: Some(branch_name.clone()),
207 base_ref: Some(base_ref.clone()),
208 head_ref: None,
209 status: "active".to_string(),
210 created_at: now,
211 released_at: None,
212 };
213 let create = git_output(
214 backend,
215 &git_root,
216 vec![
217 "worktree".to_string(),
218 "add".to_string(),
219 "-b".to_string(),
220 branch_name,
221 root.as_str().to_string(),
222 base_ref,
223 ],
224 Duration::from_secs(60),
225 )
226 .await;
227 if let Err(error) = create {
228 workspace.status = "failed".to_string();
229 state.create_task_workspace(&workspace).await?;
230 return Err(error);
231 }
232 state.create_task_workspace(&workspace).await?;
233 Ok(workspace)
234}
235
236pub async fn preserve_task_workspace<S>(
239 backend: &dyn ExecutionBackend,
240 state: &S,
241 task_id: &str,
242) -> anyhow::Result<WorkspaceEvidence>
243where
244 S: WorkCoordinationStore + ?Sized,
245{
246 let Some(mut workspace) = state.get_task_workspace(task_id).await? else {
247 return Ok(WorkspaceEvidence::default());
248 };
249 if workspace.status != "active" {
250 return Ok(WorkspaceEvidence::default());
251 }
252
253 let mut evidence = WorkspaceEvidence {
254 artifacts: vec![HandoffArtifact {
255 kind: "path".to_string(),
256 reference: workspace.root_path.clone(),
257 digest: None,
258 metadata: Some(format!("workspace_policy={}", workspace.policy)),
259 }],
260 verification: Vec::new(),
261 };
262 if workspace.policy == "worktree" {
263 match git_output(
264 backend,
265 &workspace.root_path,
266 vec!["rev-parse".to_string(), "HEAD".to_string()],
267 Duration::from_secs(20),
268 )
269 .await
270 {
271 Ok(head) => {
272 workspace.head_ref = Some(head.clone());
273 evidence.artifacts.push(HandoffArtifact {
274 kind: "commit".to_string(),
275 reference: head,
276 digest: None,
277 metadata: workspace.branch_name.clone(),
278 });
279 }
280 Err(error) => evidence
281 .verification
282 .push(format!("Could not read workspace HEAD: {error}")),
283 }
284 match git_output(
285 backend,
286 &workspace.root_path,
287 vec!["status".to_string(), "--porcelain".to_string()],
288 Duration::from_secs(20),
289 )
290 .await
291 {
292 Ok(status) if status.is_empty() => evidence
293 .verification
294 .push("Workspace has no uncommitted changes.".to_string()),
295 Ok(status) => evidence.verification.push(format!(
296 "Workspace preserved with {} uncommitted path(s).",
297 status.lines().count()
298 )),
299 Err(error) => evidence
300 .verification
301 .push(format!("Could not inspect workspace status: {error}")),
302 }
303 } else {
304 evidence
305 .verification
306 .push(format!("{} workspace path recorded.", workspace.policy));
307 }
308 workspace.status = "preserved".to_string();
309 state.update_task_workspace(&workspace).await?;
310 Ok(evidence)
311}
312
313#[cfg(test)]
314mod tests {
315 use super::{isolated_workspace_slug, short_component};
316
317 #[test]
318 fn workspace_components_are_bounded_and_safe() {
319 assert_eq!(short_component("abc-123_DEF!xyz"), "abc123DEFxyz");
320 assert_eq!(short_component("123456789012345"), "123456789012");
321 }
322
323 #[test]
324 fn new_project_workspace_gets_bounded_human_readable_slug() {
325 assert_eq!(
326 isolated_workspace_slug(
327 "Create a website about AI engineering and deploy it",
328 "43b2cf48-bc97"
329 ),
330 "ai-engineering-site-43b2cf48bc97"
331 );
332 }
333}