1use std::sync::Arc;
6
7use aidaemon_channels::slash::{SlashCall, SlashCommand};
8use aidaemon_tools::semantics::UserRole;
9use async_trait::async_trait;
10
11use crate::goals::{TaskJournalEntry, WorkTaskSummary};
12use crate::stores::WorkCoordinationStore;
13
14pub struct WorkCommand {
16 state: Arc<dyn WorkCoordinationStore>,
17}
18
19impl WorkCommand {
20 pub fn new(state: Arc<dyn WorkCoordinationStore>) -> Self {
21 Self { state }
22 }
23}
24
25#[async_trait]
26impl SlashCommand for WorkCommand {
27 fn handles(&self, cmd: &str) -> bool {
28 cmd == "/work"
29 }
30
31 async fn run(&self, _cmd: &str, args: &str, call: &SlashCall<'_>) -> String {
32 self.handle_work(args, call.session_id, call.user_role)
33 .await
34 }
35}
36
37impl WorkCommand {
38 async fn handle_work(&self, args: &str, session_id: &str, user_role: UserRole) -> String {
39 if user_role != UserRole::Owner {
40 return "Only the owner can view or manage durable work.".to_string();
41 }
42
43 let mut parts = args.split_whitespace();
44 let action = parts.next().unwrap_or("overview").to_ascii_lowercase();
45 let project_id = match self.state.get_session_work_project(session_id).await {
46 Ok(project_id) => project_id,
47 Err(error) => return format!("Could not resolve the active project: {error}"),
48 };
49
50 match action.as_str() {
51 "overview" | "all" => self.render_work_overview(&project_id).await,
52 "waiting" | "ready" | "running" | "in_progress" | "blocked" | "attention"
53 | "needs_attention" | "done" => {
54 let lane = match action.as_str() {
55 "running" => "in_progress",
56 "attention" => "needs_attention",
57 value => value,
58 };
59 self.render_work_lane(&project_id, lane).await
60 }
61 "show" => {
62 let Some(reference) = parts.next() else {
63 return "Usage: /work show <task-id>".to_string();
64 };
65 let task = match self.resolve_work_task(&project_id, reference).await {
66 Ok(task) => task,
67 Err(message) => return message,
68 };
69 self.render_work_task(&task).await
70 }
71 "comment" | "unblock" => {
72 let Some(reference) = parts.next() else {
73 return format!("Usage: /work {action} <task-id> <message>");
74 };
75 let message = parts.collect::<Vec<_>>().join(" ");
76 if message.trim().is_empty() {
77 return format!("Usage: /work {action} <task-id> <message>");
78 }
79 let task = match self.resolve_work_task(&project_id, reference).await {
80 Ok(task) => task,
81 Err(message) => return message,
82 };
83 if action == "unblock" {
84 return match self
85 .state
86 .unblock_task(&task.task_id, &message, "owner", Some(session_id))
87 .await
88 {
89 Ok(true) => format!(
90 "Task {} was unblocked and returned to the ready queue.",
91 short_id(&task.task_id)
92 ),
93 Ok(false) => "That task is not currently blocked.".to_string(),
94 Err(error) => format!("Could not unblock task: {error}"),
95 };
96 }
97 let entry = TaskJournalEntry::new(
98 &task.project_id,
99 &task.goal_id,
100 &task.goal_run_id,
101 "comment",
102 "human",
103 "owner",
104 &message,
105 )
106 .with_task(Some(&task.task_id), None)
107 .with_source_channel(Some(session_id));
108 match self.state.append_task_journal(&entry).await {
109 Ok(()) => format!("Comment added to task {}.", short_id(&task.task_id)),
110 Err(error) => format!("Could not add comment: {error}"),
111 }
112 }
113 "retry" | "cancel" => {
114 let Some(reference) = parts.next() else {
115 return format!("Usage: /work {action} <task-id>");
116 };
117 let task = match self.resolve_work_task(&project_id, reference).await {
118 Ok(task) => task,
119 Err(message) => return message,
120 };
121 let result = if action == "retry" {
122 self.state
123 .retry_work_task(&task.task_id, "owner", Some(session_id))
124 .await
125 } else {
126 self.state
127 .cancel_work_task(&task.task_id, "owner", Some(session_id))
128 .await
129 };
130 match result {
131 Ok(true) if action == "retry" => {
132 format!("Task {} was queued for retry.", short_id(&task.task_id))
133 }
134 Ok(true) => format!("Task {} was cancelled.", short_id(&task.task_id)),
135 Ok(false) if action == "retry" => {
136 format!("Task {} cannot be retried.", short_id(&task.task_id))
137 }
138 Ok(false) => format!("Task {} cannot be cancelled.", short_id(&task.task_id)),
139 Err(error) => format!("Could not {action} task: {error}"),
140 }
141 }
142 "assign" => {
143 let (Some(reference), Some(profile_id)) = (parts.next(), parts.next()) else {
144 return "Usage: /work assign <task-id> <profile-id>".to_string();
145 };
146 let task = match self.resolve_work_task(&project_id, reference).await {
147 Ok(task) => task,
148 Err(message) => return message,
149 };
150 match self
151 .state
152 .assign_task_worker_profile(
153 &task.task_id,
154 profile_id,
155 "owner",
156 Some(session_id),
157 )
158 .await
159 {
160 Ok(true) => format!(
161 "Task {} assigned to profile {}.",
162 short_id(&task.task_id),
163 profile_id
164 ),
165 Ok(false) => "Task or worker profile was unavailable.".to_string(),
166 Err(error) => format!("Could not assign worker profile: {error}"),
167 }
168 }
169 "workspace" => {
170 let Some(reference) = parts.next() else {
171 return "Usage: /work workspace <task-id> [shared|isolated|worktree]"
172 .to_string();
173 };
174 let task = match self.resolve_work_task(&project_id, reference).await {
175 Ok(task) => task,
176 Err(message) => return message,
177 };
178 if let Some(policy) = parts.next() {
179 return match self
180 .state
181 .set_task_workspace_policy(&task.task_id, policy)
182 .await
183 {
184 Ok(true) => format!(
185 "Task {} workspace policy set to {}.",
186 short_id(&task.task_id),
187 policy
188 ),
189 Ok(false) => {
190 "Workspace policy can only change before execution.".to_string()
191 }
192 Err(error) => format!("Could not set workspace policy: {error}"),
193 };
194 }
195 match self.state.get_task_workspace(&task.task_id).await {
196 Ok(Some(workspace)) => format!(
197 "Task {} workspace\nPolicy: {}\nStatus: {}\nPath: {}\nBranch: {}",
198 short_id(&task.task_id),
199 workspace.policy,
200 workspace.status,
201 workspace.root_path,
202 workspace.branch_name.as_deref().unwrap_or("—")
203 ),
204 Ok(None) => match self.state.get_task_workspace_policy(&task.task_id).await {
205 Ok(policy) => format!(
206 "Task {} has policy {}; no workspace has been created yet.",
207 short_id(&task.task_id),
208 policy
209 ),
210 Err(error) => format!("Could not inspect workspace: {error}"),
211 },
212 Err(error) => format!("Could not inspect workspace: {error}"),
213 }
214 }
215 "profiles" => match self.state.list_worker_profiles(Some(&project_id)).await {
216 Ok(profiles) if profiles.is_empty() => "No enabled worker profiles.".to_string(),
217 Ok(profiles) => {
218 let lines = profiles
219 .into_iter()
220 .map(|profile| {
221 format!(
222 "• {} — {} (max {}, {})",
223 profile.id,
224 profile.name,
225 profile.max_concurrency,
226 profile.workspace_policy
227 )
228 })
229 .collect::<Vec<_>>();
230 format!("Worker profiles\n{}", lines.join("\n"))
231 }
232 Err(error) => format!("Could not list worker profiles: {error}"),
233 },
234 "projects" => match self.state.list_work_projects().await {
235 Ok(projects) => {
236 let lines = projects
237 .into_iter()
238 .map(|project| {
239 let marker = if project.id == project_id {
240 " (active)"
241 } else {
242 ""
243 };
244 format!("• {} — {}{}", project.id, project.name, marker)
245 })
246 .collect::<Vec<_>>();
247 format!("Projects\n{}", lines.join("\n"))
248 }
249 Err(error) => format!("Could not list projects: {error}"),
250 },
251 "project" => {
252 let Some(reference_head) = parts.next() else {
253 return format!("Active project: {project_id}\nUsage: /work project <id>");
254 };
255 if reference_head.eq_ignore_ascii_case("create") {
256 let name = parts.collect::<Vec<_>>().join(" ");
257 if name.trim().is_empty() {
258 return "Usage: /work project create <name>".to_string();
259 }
260 return match self.state.create_work_project(&name, None).await {
261 Ok(project) => match self
262 .state
263 .set_session_work_project(session_id, &project.id)
264 .await
265 {
266 Ok(true) => format!(
267 "Created and selected project {} ({})",
268 project.name, project.id
269 ),
270 Ok(false) => {
271 "Project was created but could not be selected.".to_string()
272 }
273 Err(error) => {
274 format!("Project was created but selection failed: {error}")
275 }
276 },
277 Err(error) => format!("Could not create project: {error}"),
278 };
279 }
280 let reference = std::iter::once(reference_head)
281 .chain(parts)
282 .collect::<Vec<_>>()
283 .join(" ");
284 let projects = match self.state.list_work_projects().await {
285 Ok(projects) => projects,
286 Err(error) => return format!("Could not list projects: {error}"),
287 };
288 let matches = projects
289 .into_iter()
290 .filter(|project| {
291 project.id == reference || project.name.eq_ignore_ascii_case(&reference)
292 })
293 .collect::<Vec<_>>();
294 let Some(project) = matches.first() else {
295 return "Project not found. Use /work projects to list choices.".to_string();
296 };
297 match self
298 .state
299 .set_session_work_project(session_id, &project.id)
300 .await
301 {
302 Ok(true) => format!("Active project set to {}.", project.name),
303 Ok(false) => "Project not found.".to_string(),
304 Err(error) => format!("Could not select project: {error}"),
305 }
306 }
307 _ => work_usage(),
308 }
309 }
310
311 async fn render_work_overview(&self, project_id: &str) -> String {
312 match self.state.list_work_goals(project_id, false, 25).await {
313 Ok(goals) if goals.is_empty() => {
314 format!("No active work in project {project_id}.")
315 }
316 Ok(goals) => {
317 let lines = goals
318 .into_iter()
319 .map(|goal| {
320 format!(
321 "• {} {} — ready {} · running {} · blocked {} · attention {} · done {}",
322 short_id(&goal.goal_id),
323 truncate_chars(&goal.description, 72),
324 goal.ready,
325 goal.in_progress,
326 goal.blocked,
327 goal.needs_attention,
328 goal.done
329 )
330 })
331 .collect::<Vec<_>>();
332 format!(
333 "Active work · project {project_id}\n{}\n\nUse /work ready, /work blocked, or /work show <task-id>.",
334 lines.join("\n")
335 )
336 }
337 Err(error) => format!("Could not load work: {error}"),
338 }
339 }
340
341 async fn render_work_lane(&self, project_id: &str, lane: &str) -> String {
342 match self.state.list_work_tasks(project_id, Some(lane), 50).await {
343 Ok(tasks) if tasks.is_empty() => format!("No tasks in the {lane} lane."),
344 Ok(tasks) => {
345 let lines = tasks
346 .into_iter()
347 .map(|task| {
348 let owner = task
349 .worker_profile
350 .as_deref()
351 .map(|profile| format!(" · {profile}"))
352 .unwrap_or_default();
353 format!(
354 "• {} [{}] {}{}",
355 short_id(&task.task_id),
356 task.priority,
357 truncate_chars(&task.description, 90),
358 owner
359 )
360 })
361 .collect::<Vec<_>>();
362 format!("{lane}\n{}", lines.join("\n"))
363 }
364 Err(error) => format!("Could not load work: {error}"),
365 }
366 }
367
368 async fn resolve_work_task(
369 &self,
370 project_id: &str,
371 reference: &str,
372 ) -> Result<WorkTaskSummary, String> {
373 let tasks = self
374 .state
375 .list_work_tasks(project_id, None, 500)
376 .await
377 .map_err(|error| format!("Could not load work: {error}"))?;
378 let mut matches = tasks
379 .into_iter()
380 .filter(|task| task.task_id == reference || task.task_id.starts_with(reference))
381 .collect::<Vec<_>>();
382 match matches.len() {
383 0 => Err("Task not found in the active project run.".to_string()),
384 1 => Ok(matches.remove(0)),
385 _ => Err("Task reference is ambiguous; provide more ID characters.".to_string()),
386 }
387 }
388
389 async fn render_work_task(&self, task: &WorkTaskSummary) -> String {
390 let journal = self
391 .state
392 .get_task_journal(&task.task_id, 8)
393 .await
394 .unwrap_or_default();
395 let handoff = self
396 .state
397 .get_latest_task_handoff(&task.task_id)
398 .await
399 .ok()
400 .flatten();
401 let workspace = self
402 .state
403 .get_task_workspace(&task.task_id)
404 .await
405 .ok()
406 .flatten();
407 let mut reply = format!(
408 "Task {}\n{}\nLane: {} · status: {} · priority: {}\nGoal: {}\nWorker: {}",
409 short_id(&task.task_id),
410 task.description,
411 task.lane,
412 task.status,
413 task.priority,
414 truncate_chars(&task.goal_description, 100),
415 task.worker_profile.as_deref().unwrap_or("unassigned")
416 );
417 if let Some(blocker) = &task.blocker {
418 reply.push_str(&format!("\nBlocker: {blocker}"));
419 }
420 if let Some(handoff) = handoff {
421 reply.push_str(&format!("\n\nLatest handoff: {}", handoff.summary));
422 if !handoff.verification.is_empty() {
423 reply.push_str(&format!("\nVerified: {}", handoff.verification.join("; ")));
424 }
425 if let Some(risk) = handoff.remaining_risk {
426 reply.push_str(&format!("\nRemaining risk: {risk}"));
427 }
428 if let Some(next) = handoff.next_step {
429 reply.push_str(&format!("\nNext step: {next}"));
430 }
431 }
432 if let Some(workspace) = workspace {
433 reply.push_str(&format!(
434 "\n\nWorkspace: {} ({})",
435 workspace.root_path, workspace.status
436 ));
437 }
438 if !journal.is_empty() {
439 let lines = journal
440 .into_iter()
441 .map(|entry| {
442 format!(
443 "• {} · {}: {}",
444 entry.created_at,
445 entry.entry_type,
446 truncate_chars(&entry.body, 120)
447 )
448 })
449 .collect::<Vec<_>>();
450 reply.push_str(&format!("\n\nRecent journal\n{}", lines.join("\n")));
451 }
452 reply
453 }
454}
455
456fn short_id(id: &str) -> &str {
457 let end = id
458 .char_indices()
459 .nth(8)
460 .map(|(index, _)| index)
461 .unwrap_or(id.len());
462 &id[..end]
463}
464
465use aidaemon_tools::text::truncate_ellipsis as truncate_chars;
466
467fn work_usage() -> String {
468 "Usage:\n\
469 /work — active overview\n\
470 /work ready|running|blocked|attention|done\n\
471 /work show <task-id>\n\
472 /work comment <task-id> <message>\n\
473 /work unblock <task-id> <resolution>\n\
474 /work retry|cancel <task-id>\n\
475 /work assign <task-id> <profile-id>\n\
476 /work workspace <task-id> [shared|isolated|worktree]\n\
477 /work profiles|projects\n\
478 /work project <id>\n\
479 /work project create <name>"
480 .to_string()
481}