Skip to main content

orch/engine/tasks/
commands.rs

1//! Owner slash commands — parse, validate, and execute /commands in issue comments.
2//!
3//! Provides command parsing (`parse_command`), validation + execution
4//! (`validate_and_run_command`), and the individual command implementations.
5//! The scanning loop lives in `sync.rs` (`scan_comments`).
6
7use crate::backends::{ExternalBackend, ExternalId, Status};
8
9use crate::engine;
10use crate::engine::tasks::TaskManager;
11use crate::github::http::GhHttp;
12use crate::github::types::GitHubIssue;
13use crate::store::TaskStatus;
14use crate::store::TaskStore;
15use async_trait::async_trait;
16use std::fmt;
17use std::fmt::Display;
18use std::fmt::Formatter;
19use std::sync::Arc;
20
21/// Minimal store interface required by command execution.
22///
23/// Exists so tests can inject a mock that simulates DB failures without
24/// coupling the test harness to a real SQLite pool.
25#[async_trait]
26pub trait CommandStoreOps: Send + Sync {
27    async fn resolve_task_id(&self, repo: &str, task_id: &str) -> anyhow::Result<Option<i64>>;
28
29    async fn set_block_reason(&self, id: i64, reason: Option<&str>) -> anyhow::Result<()>;
30
31    /// Reset all per-attempt counters for a task. Fire-and-forget — failures are
32    /// logged but not propagated (same semantics as `store::store_reset_counters`).
33    async fn reset_counters(&self, id: i64) -> anyhow::Result<()>;
34
35    /// Current status of a task, or `None` when the store has no such task.
36    async fn status(&self, repo: &str, task_id: &str) -> anyhow::Result<Option<TaskStatus>>;
37}
38
39#[async_trait]
40impl CommandStoreOps for TaskStore {
41    async fn resolve_task_id(&self, repo: &str, task_id: &str) -> anyhow::Result<Option<i64>> {
42        self.resolve_task_id(repo, task_id).await
43    }
44
45    async fn set_block_reason(&self, id: i64, reason: Option<&str>) -> anyhow::Result<()> {
46        self.set_block_reason(id, reason).await
47    }
48
49    async fn reset_counters(&self, id: i64) -> anyhow::Result<()> {
50        self.reset_counters(id).await
51    }
52
53    async fn status(&self, repo: &str, task_id: &str) -> anyhow::Result<Option<TaskStatus>> {
54        let Some(id) = self.resolve_task_id(repo, task_id).await? else {
55            return Ok(None);
56        };
57        Ok(Some(self.get(id).await?.status))
58    }
59}
60
61/// Minimal GitHub interface required by command validation and execution.
62///
63/// Exists so tests can inject a mock that simulates transient API failures
64/// without reaching the network.
65#[async_trait]
66pub trait CommandGh: Send + Sync {
67    async fn get_issue(&self, repo: &str, number: &str) -> anyhow::Result<GitHubIssue>;
68
69    async fn is_collaborator(&self, repo: &str, username: &str) -> anyhow::Result<bool>;
70
71    async fn close_issue(&self, repo: &str, number: &str) -> anyhow::Result<()>;
72}
73
74#[async_trait]
75impl CommandGh for GhHttp {
76    async fn get_issue(&self, repo: &str, number: &str) -> anyhow::Result<GitHubIssue> {
77        GhHttp::get_issue(self, repo, number).await
78    }
79
80    async fn is_collaborator(&self, repo: &str, username: &str) -> anyhow::Result<bool> {
81        GhHttp::is_collaborator(self, repo, username).await
82    }
83
84    async fn close_issue(&self, repo: &str, number: &str) -> anyhow::Result<()> {
85        GhHttp::close_issue(self, repo, number).await
86    }
87}
88
89/// Parsed owner command from an issue comment.
90#[derive(Debug, Clone, PartialEq)]
91pub enum OwnerCommand {
92    /// Reset to status:new, re-dispatch.
93    Retry,
94    /// Clear agent, re-route (optionally force agent).
95    Reroute(Option<String>),
96    /// Mark status:done, close issue.
97    Close,
98    /// Mark status:blocked with optional reason.
99    Block(Option<String>),
100    /// Mark status:new, re-dispatch.
101    Unblock,
102    /// Trigger review agent on current PR.
103    Review,
104}
105
106impl Display for OwnerCommand {
107    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
108        match self {
109            Self::Retry => write!(f, "/retry"),
110            Self::Reroute(Some(a)) => write!(f, "/reroute {a}"),
111            Self::Reroute(None) => write!(f, "/reroute"),
112            Self::Close => write!(f, "/close"),
113            Self::Block(Some(r)) => write!(f, "/block {r}"),
114            Self::Block(None) => write!(f, "/block"),
115            Self::Unblock => write!(f, "/unblock"),
116            Self::Review => write!(f, "/review"),
117        }
118    }
119}
120
121/// Parse a slash command from a comment body.
122///
123/// Scans each line for a `/command` at the start, optionally prefixed by an
124/// `@orch` or `@orchestrator` mention on the same line. Returns the first
125/// valid command found. Unknown `/something` lines are skipped. Lines inside
126/// markdown fenced code blocks (``` or ~~~) are ignored to prevent accidental
127/// command execution from code examples. Per CommonMark, a backtick fence
128/// closes only a backtick fence and a tilde fence closes only a tilde fence —
129/// mismatched closers are ignored.
130pub fn parse_command(body: &str) -> Option<OwnerCommand> {
131    // Track the opening fence (character, length) so mismatched or shorter
132    // closers are ignored. Per CommonMark: a backtick fence closes only a
133    // backtick fence, a tilde fence closes only a tilde fence, and the closing
134    // fence must be at least as long as the opening fence.
135    let mut fence_state: Option<(char, usize)> = None;
136    for line in body.lines() {
137        let trimmed = line.trim();
138        let fence_ch = if trimmed.starts_with("```") {
139            Some('`')
140        } else if trimmed.starts_with("~~~") {
141            Some('~')
142        } else {
143            None
144        };
145        if let Some(ch) = fence_ch {
146            let run_len = trimmed.chars().take_while(|&c| c == ch).count();
147            match fence_state {
148                None => fence_state = Some((ch, run_len)),
149                Some((c, len)) if c == ch && run_len >= len => fence_state = None,
150                Some(_) => {} // mismatched closer or shorter — ignore
151            }
152            continue;
153        }
154        if fence_state.is_some() {
155            continue;
156        }
157        let command_text = trimmed
158            .strip_prefix("@orchestrator")
159            .or_else(|| trimmed.strip_prefix("@orch"))
160            .map_or(trimmed, str::trim_start);
161
162        if !command_text.starts_with('/') {
163            continue;
164        }
165        let parts: Vec<&str> = command_text.splitn(2, char::is_whitespace).collect();
166        let cmd = parts[0];
167        let args = parts
168            .get(1)
169            .map(|s| s.trim())
170            .filter(|s| !s.is_empty())
171            .map(String::from);
172
173        match cmd {
174            "/retry" => return Some(OwnerCommand::Retry),
175            "/reroute" => return Some(OwnerCommand::Reroute(args)),
176            "/close" => return Some(OwnerCommand::Close),
177            "/block" => return Some(OwnerCommand::Block(args)),
178            "/unblock" => return Some(OwnerCommand::Unblock),
179            "/review" => return Some(OwnerCommand::Review),
180            _ => {}
181        }
182    }
183    None
184}
185
186/// Reset all attempt/failure counters for a task. Fire-and-forget — errors are
187/// logged as warnings but not returned so `/retry` and `/reroute` still succeed.
188async fn cmd_reset_counters(store: Option<&Arc<dyn CommandStoreOps>>, repo: &str, task_id: &str) {
189    let Some(s) = store else { return };
190    match s.resolve_task_id(repo, task_id).await {
191        Ok(Some(id)) => {
192            if let Err(e) = s.reset_counters(id).await {
193                tracing::warn!(task_id, err = %e, "store reset_counters failed");
194            }
195        }
196        Ok(None) => {} // task not in store — no-op is expected
197        Err(e) => {
198            tracing::warn!(task_id, err = %e, "resolve_task_id failed in store write helper");
199        }
200    }
201}
202
203/// Refuse a command that would move a done task back into the pipeline.
204///
205/// Done is terminal: a revived task re-runs the body it was created with, which
206/// may be months stale and duplicate work that already has its own task (#3780)
207async fn refuse_if_done(
208    store: Option<&Arc<dyn CommandStoreOps>>,
209    repo: &str,
210    task_id: &str,
211    command: &OwnerCommand,
212) -> anyhow::Result<()> {
213    let Some(s) = store else { return Ok(()) };
214    if s.status(repo, task_id).await? != Some(TaskStatus::Done) {
215        return Ok(());
216    }
217    anyhow::bail!(
218        "`{command}` — task is done and done is terminal; open a new issue for follow-up work"
219    )
220}
221
222async fn clear_agent_reset_to_new(
223    backend: &Arc<dyn ExternalBackend>,
224    store: Option<&Arc<dyn CommandStoreOps>>,
225    repo: &str,
226    task_id: &ExternalId,
227    task_manager: &Arc<TaskManager>,
228    forced_agent: Option<&str>,
229) -> anyhow::Result<()> {
230    let task = backend.get_task(task_id).await?;
231    for label in &task.labels {
232        if label.starts_with("agent:") {
233            backend.remove_label(task_id, label).await?;
234        }
235    }
236    cmd_reset_counters(store, repo, &task_id.0).await;
237    if let Some(agent_name) = forced_agent {
238        let label = format!("agent:{agent_name}");
239        backend.set_labels(task_id, &[label]).await?;
240    }
241    task_manager
242        .update_task_status(task_id, Status::New)
243        .await?;
244    Ok(())
245}
246
247async fn write_block_reason(
248    store: Option<&Arc<dyn CommandStoreOps>>,
249    repo: &str,
250    task_id: &str,
251    reason: Option<&str>,
252) -> anyhow::Result<()> {
253    if let Some(store) = store {
254        let store_id = store.resolve_task_id(repo, task_id).await?;
255        if let Some(store_id) = store_id {
256            store.set_block_reason(store_id, reason).await?;
257        }
258    }
259    Ok(())
260}
261
262/// Execute a single owner command against a task.
263pub async fn execute_command(
264    backend: &Arc<dyn ExternalBackend>,
265    gh: &dyn CommandGh,
266    repo: &str,
267    task_id: &ExternalId,
268    command: &OwnerCommand,
269    store: &Option<Arc<dyn CommandStoreOps>>,
270    task_manager: &Arc<TaskManager>,
271) -> anyhow::Result<String> {
272    match command {
273        OwnerCommand::Retry => {
274            refuse_if_done(store.as_ref(), repo, &task_id.0, command).await?;
275            clear_agent_reset_to_new(backend, store.as_ref(), repo, task_id, task_manager, None)
276                .await?;
277            Ok("`/retry` — reset attempts, cleared agent, reset to `status:new`".to_string())
278        }
279
280        OwnerCommand::Reroute(agent) => {
281            refuse_if_done(store.as_ref(), repo, &task_id.0, command).await?;
282            clear_agent_reset_to_new(
283                backend,
284                store.as_ref(),
285                repo,
286                task_id,
287                task_manager,
288                agent.as_deref(),
289            )
290            .await?;
291            match agent {
292                Some(a) => Ok(format!(
293                    "`/reroute {a}` — cleared agent, reset attempts, forced `agent:{a}`, reset to `status:new`"
294                )),
295                None => {
296                    Ok("`/reroute` — cleared agent, reset attempts, reset to `status:new`, will re-route".into())
297                }
298            }
299        }
300
301        OwnerCommand::Close => {
302            task_manager
303                .update_task_status(task_id, Status::Done)
304                .await?;
305            gh.close_issue(repo, &task_id.0).await?;
306            Ok("`/close` — marked `status:done` and closed issue".to_string())
307        }
308
309        OwnerCommand::Block(reason) => {
310            refuse_if_done(store.as_ref(), repo, &task_id.0, command).await?;
311            write_block_reason(store.as_ref(), repo, &task_id.0, reason.as_deref()).await?;
312            task_manager
313                .update_task_status(task_id, Status::Blocked)
314                .await?;
315            match reason {
316                Some(r) => Ok(format!("`/block` — marked `status:blocked`: {r}")),
317                None => Ok("`/block` — marked `status:blocked`".to_string()),
318            }
319        }
320
321        OwnerCommand::Unblock => {
322            refuse_if_done(store.as_ref(), repo, &task_id.0, command).await?;
323            write_block_reason(store.as_ref(), repo, &task_id.0, None).await?;
324            task_manager
325                .update_task_status(task_id, Status::New)
326                .await?;
327            Ok("`/unblock` — marked `status:new`, will re-dispatch".to_string())
328        }
329
330        OwnerCommand::Review => {
331            refuse_if_done(store.as_ref(), repo, &task_id.0, command).await?;
332            task_manager
333                .update_task_status(task_id, Status::NeedsReview)
334                .await?;
335            Ok(
336                "`/review` — set `status:needs_review`, review agent will pick up on next tick"
337                    .to_string(),
338            )
339        }
340    }
341}
342
343/// Result of attempting to validate and run a slash command.
344///
345/// Variants that successfully fetched issue data include `is_pr` so callers
346/// don't need a second `get_issue` call.
347#[derive(Debug)]
348pub enum CommandOutcome {
349    /// Command executed successfully or failed — either way, it was handled.
350    Executed { is_pr: bool },
351    /// Issue/PR is not open — command was skipped.
352    NotOpen { is_pr: bool },
353    /// Author is not a collaborator — command was skipped.
354    NotCollaborator { is_pr: bool },
355    /// Failed to fetch issue state — should retry.
356    FetchFailed,
357    /// Failed to check collaborator status — should retry.
358    CollaboratorCheckFailed,
359}
360
361/// Validate a slash command (issue open, author is collaborator) and execute it.
362///
363/// Shared by both `scan_commands` (issue comments) and `scan_mentions` (mention
364/// handling). Posts a confirmation or error comment on the issue/PR.
365#[expect(
366    clippy::too_many_arguments,
367    reason = "two scan paths pass their own context to one shared validator"
368)]
369pub async fn validate_and_run_command(
370    backend: &Arc<dyn ExternalBackend>,
371    gh: &dyn CommandGh,
372    repo: &str,
373    issue_number: &str,
374    command: &OwnerCommand,
375    author: &str,
376    store: &Option<Arc<dyn CommandStoreOps>>,
377    task_manager: &Arc<TaskManager>,
378) -> CommandOutcome {
379    // Check issue state
380    let issue_data = match gh.get_issue(repo, issue_number).await {
381        Ok(data) => data,
382        Err(e) => {
383            tracing::warn!(issue = %issue_number, err = %e, "failed to check issue state");
384            return CommandOutcome::FetchFailed;
385        }
386    };
387
388    let is_pr = issue_data.pull_request.is_some();
389
390    if issue_data.state != "open" {
391        tracing::debug!(issue = %issue_number, state = %issue_data.state, command = %command, "ignoring slash command on non-open issue");
392        return CommandOutcome::NotOpen { is_pr };
393    }
394
395    // Check collaborator status
396    match gh.is_collaborator(repo, author).await {
397        Ok(true) => {}
398        Ok(false) => {
399            tracing::info!(author, command = %command, issue = %issue_number, "ignoring slash command from non-collaborator");
400            return CommandOutcome::NotCollaborator { is_pr };
401        }
402        Err(e) => {
403            tracing::warn!(author, err = %e, "failed to check collaborator status");
404            return CommandOutcome::CollaboratorCheckFailed;
405        }
406    }
407
408    // Execute and post result
409    let task_id = ExternalId(issue_number.to_string());
410    let now = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string();
411
412    match execute_command(backend, gh, repo, &task_id, command, store, task_manager).await {
413        Ok(msg) => {
414            tracing::info!(issue = %issue_number, author, command = %command, "executed command");
415            let confirmation = format!(
416                "[{now}] {msg} — executed by @{author}{}",
417                engine::orch_footer()
418            );
419            if let Err(e) = backend.post_comment(&task_id, &confirmation).await {
420                tracing::warn!(issue = %issue_number, err = %e, "failed to post confirmation");
421            }
422        }
423        Err(e) => {
424            tracing::warn!(issue = %issue_number, command = %command, err = %e, "failed to execute command");
425            let error_msg = format!(
426                "[{now}] Failed to execute `{command}`: {e}{}",
427                engine::orch_footer()
428            );
429            if let Err(e2) = backend.post_comment(&task_id, &error_msg).await {
430                tracing::warn!(issue = %issue_number, err = %e2, "failed to post error comment");
431            }
432        }
433    }
434
435    CommandOutcome::Executed { is_pr }
436}
437
438#[cfg(test)]
439mod tests {
440    use super::*;
441    use crate::backends::{Conversation, MergeState, TaskReader, TaskWriter, Tracker};
442    use crate::backends::{ExternalBackend, ExternalId, ExternalTask, Mention, Status};
443    use crate::store::{NewTask, TaskStore};
444    use async_trait::async_trait;
445    use std::sync::Arc;
446    use std::sync::Mutex;
447
448    struct MockBackend {
449        task: ExternalTask,
450        fail_remove_label: bool,
451        removed_labels: Mutex<Vec<String>>,
452        set_label_calls: Mutex<Vec<Vec<String>>>,
453    }
454
455    impl MockBackend {
456        fn new(id: &str) -> Self {
457            Self {
458                task: ExternalTask {
459                    id: ExternalId(id.to_string()),
460                    title: "Task".to_string(),
461                    body: String::new(),
462                    state: "open".to_string(),
463                    labels: vec![],
464                    author: "bot".to_string(),
465                    created_at: "2026-01-01T00:00:00Z".to_string(),
466                    updated_at: "2026-01-01T00:00:00Z".to_string(),
467                    url: String::new(),
468                },
469                fail_remove_label: false,
470                removed_labels: Mutex::new(Vec::new()),
471                set_label_calls: Mutex::new(Vec::new()),
472            }
473        }
474
475        fn with_labels(id: &str, labels: Vec<String>) -> Self {
476            let mut b = Self::new(id);
477            b.task.labels = labels;
478            b
479        }
480
481        fn failing_remove_label(id: &str, labels: Vec<String>) -> Self {
482            let mut b = Self::with_labels(id, labels);
483            b.fail_remove_label = true;
484            b
485        }
486    }
487
488    #[async_trait]
489    impl TaskReader for MockBackend {
490        async fn get_task(&self, _id: &ExternalId) -> anyhow::Result<ExternalTask> {
491            Ok(self.task.clone())
492        }
493
494        async fn list_by_status(&self, _status: Status) -> anyhow::Result<Vec<ExternalTask>> {
495            Ok(vec![])
496        }
497
498        async fn list_routable(&self) -> anyhow::Result<Vec<ExternalTask>> {
499            Ok(vec![])
500        }
501
502        async fn has_open_issue_with_title(
503            &self,
504            _title: &str,
505            _label: &str,
506        ) -> anyhow::Result<bool> {
507            Ok(false)
508        }
509    }
510
511    #[async_trait]
512    impl TaskWriter for MockBackend {
513        async fn create_task(
514            &self,
515            _title: &str,
516            _body: &str,
517            _labels: &[String],
518        ) -> anyhow::Result<ExternalId> {
519            Ok(self.task.id.clone())
520        }
521
522        async fn set_labels(&self, _id: &ExternalId, labels: &[String]) -> anyhow::Result<()> {
523            self.set_label_calls.lock().unwrap().push(labels.to_vec());
524            Ok(())
525        }
526
527        async fn remove_label(&self, _id: &ExternalId, label: &str) -> anyhow::Result<()> {
528            if self.fail_remove_label {
529                anyhow::bail!("simulated remove_label failure for {label}");
530            }
531            self.removed_labels.lock().unwrap().push(label.to_string());
532            Ok(())
533        }
534
535        async fn get_sub_issues(&self, _id: &ExternalId) -> anyhow::Result<Vec<ExternalId>> {
536            Ok(vec![])
537        }
538
539        async fn create_sub_task(
540            &self,
541            _parent: &ExternalId,
542            _title: &str,
543            _body: &str,
544            _labels: &[String],
545        ) -> anyhow::Result<ExternalId> {
546            Ok(ExternalId("child".to_string()))
547        }
548
549        async fn ensure_status_label(&self, _label: &str) -> anyhow::Result<()> {
550            Ok(())
551        }
552
553        async fn update_status(&self, _id: &ExternalId, _status: Status) -> anyhow::Result<()> {
554            Ok(())
555        }
556    }
557
558    #[async_trait]
559    impl Conversation for MockBackend {
560        async fn post_comment(&self, _id: &ExternalId, _body: &str) -> anyhow::Result<()> {
561            Ok(())
562        }
563
564        async fn get_authenticated_user(&self) -> anyhow::Result<Option<String>> {
565            Ok(Some("testbot".to_string()))
566        }
567
568        async fn get_mentions(&self, _since: &str) -> anyhow::Result<Vec<Mention>> {
569            Ok(vec![])
570        }
571    }
572
573    #[async_trait]
574    impl MergeState for MockBackend {
575        async fn is_pr_merged(&self, _branch: &str) -> anyhow::Result<bool> {
576            Ok(false)
577        }
578    }
579
580    #[async_trait]
581    impl Tracker for MockBackend {
582        fn name(&self) -> &'static str {
583            "mock"
584        }
585
586        async fn health_check(&self) -> anyhow::Result<()> {
587            Ok(())
588        }
589    }
590
591    /// Mock store whose `resolve_task_id` always returns an error.
592    struct FailingStore;
593
594    #[async_trait]
595    impl CommandStoreOps for FailingStore {
596        async fn resolve_task_id(
597            &self,
598            _repo: &str,
599            _task_id: &str,
600        ) -> anyhow::Result<Option<i64>> {
601            anyhow::bail!("simulated resolve_task_id DB failure")
602        }
603
604        async fn set_block_reason(&self, _id: i64, _reason: Option<&str>) -> anyhow::Result<()> {
605            anyhow::bail!("simulated set_block_reason DB failure")
606        }
607
608        async fn reset_counters(&self, _id: i64) -> anyhow::Result<()> {
609            Ok(())
610        }
611
612        async fn status(&self, _repo: &str, _task_id: &str) -> anyhow::Result<Option<TaskStatus>> {
613            Ok(None)
614        }
615    }
616
617    async fn command_fixture(
618        id: &str,
619        labels: Vec<String>,
620    ) -> (
621        Arc<MockBackend>,
622        Arc<dyn ExternalBackend>,
623        Arc<TaskStore>,
624        i64,
625        Arc<TaskManager>,
626        GhHttp,
627        ExternalId,
628    ) {
629        let store = Arc::new(TaskStore::open_memory().await.unwrap());
630        let store_id = store
631            .create(&NewTask {
632                external_id: Some(id.to_string()),
633                repo: "owner/repo".to_string(),
634                origin: "github".to_string(),
635                title: "Task".to_string(),
636                body: String::new(),
637                source: "manual".to_string(),
638                source_id: String::new(),
639                author: "bot".to_string(),
640                url: String::new(),
641                labels: labels.clone(),
642                parent_id: None,
643            })
644            .await
645            .unwrap();
646        let mock = Arc::new(MockBackend::with_labels(id, labels));
647        let backend: Arc<dyn ExternalBackend> = Arc::<MockBackend>::clone(&mock);
648        let task_manager = Arc::new(TaskManager::with_store(
649            Arc::clone(&backend),
650            Arc::clone(&store),
651            "owner/repo".to_string(),
652        ));
653        (
654            mock,
655            backend,
656            store,
657            store_id,
658            task_manager,
659            GhHttp::new().unwrap(),
660            ExternalId(id.to_string()),
661        )
662    }
663
664    async fn run_command(
665        backend: &Arc<dyn ExternalBackend>,
666        gh: &GhHttp,
667        store: &Arc<TaskStore>,
668        task_manager: &Arc<TaskManager>,
669        task_id: &ExternalId,
670        command: OwnerCommand,
671    ) -> anyhow::Result<String> {
672        execute_command(
673            backend,
674            gh,
675            "owner/repo",
676            task_id,
677            &command,
678            &Some(Arc::clone(store) as Arc<dyn CommandStoreOps>),
679            task_manager,
680        )
681        .await
682    }
683
684    async fn assert_done_task_refuses(command: OwnerCommand) {
685        let (_mock, backend, store, store_id, task_manager, gh, task_id) =
686            command_fixture("58", vec![]).await;
687        store
688            .update_status(store_id, TaskStatus::Done)
689            .await
690            .unwrap();
691
692        let err = run_command(&backend, &gh, &store, &task_manager, &task_id, command)
693            .await
694            .expect_err("done task must not be revived");
695        assert!(err.to_string().contains("done is terminal"), "got: {err}");
696        let task = store.get(store_id).await.unwrap();
697        assert_eq!(task.status, TaskStatus::Done);
698        assert!(task.block_reason.is_none());
699    }
700
701    #[tokio::test]
702    async fn block_command_persists_reason_and_unblock_clears_it() {
703        let store = Arc::new(TaskStore::open_memory().await.unwrap());
704        let store_id = store
705            .create(&NewTask {
706                external_id: Some("42".to_string()),
707                repo: "owner/repo".to_string(),
708                origin: "github".to_string(),
709                title: "Task".to_string(),
710                body: String::new(),
711                source: "manual".to_string(),
712                source_id: String::new(),
713                author: "bot".to_string(),
714                url: String::new(),
715                labels: vec![],
716                parent_id: None,
717            })
718            .await
719            .unwrap();
720        let backend: Arc<dyn ExternalBackend> = Arc::new(MockBackend::new("42"));
721        let backend_for_call = Arc::clone(&backend);
722        let task_manager = Arc::new(TaskManager::with_store(
723            backend,
724            Arc::clone(&store),
725            "owner/repo".to_string(),
726        ));
727        let gh = GhHttp::new().unwrap();
728        let task_id = ExternalId("42".to_string());
729
730        execute_command(
731            &backend_for_call,
732            &gh,
733            "owner/repo",
734            &task_id,
735            &OwnerCommand::Block(Some("waiting on upstream fix".to_string())),
736            &Some(Arc::clone(&store) as Arc<dyn CommandStoreOps>),
737            &task_manager,
738        )
739        .await
740        .unwrap();
741
742        let task = store.get(store_id).await.unwrap();
743        assert_eq!(task.status, TaskStatus::Blocked);
744        assert_eq!(
745            task.block_reason.as_deref(),
746            Some("waiting on upstream fix")
747        );
748
749        execute_command(
750            &backend_for_call,
751            &gh,
752            "owner/repo",
753            &task_id,
754            &OwnerCommand::Unblock,
755            &Some(Arc::clone(&store) as Arc<dyn CommandStoreOps>),
756            &task_manager,
757        )
758        .await
759        .unwrap();
760
761        let task = store.get(store_id).await.unwrap();
762        assert_eq!(task.status, TaskStatus::New);
763        assert!(task.block_reason.is_none());
764    }
765
766    /// Done is terminal: `/retry`, `/reroute` and `/unblock` must refuse a done
767    /// task instead of sending its stale body back to an agent (#3780).
768    #[tokio::test]
769    async fn done_task_refuses_retry_reroute_and_unblock() {
770        let store = Arc::new(TaskStore::open_memory().await.unwrap());
771        let store_id = store
772            .create(&NewTask {
773                external_id: Some("58".to_string()),
774                repo: "owner/repo".to_string(),
775                origin: "github".to_string(),
776                title: "Task".to_string(),
777                body: String::new(),
778                source: "cron".to_string(),
779                source_id: "code-development".to_string(),
780                author: "bot".to_string(),
781                url: String::new(),
782                labels: vec![],
783                parent_id: None,
784            })
785            .await
786            .unwrap();
787        store
788            .update_status(store_id, TaskStatus::Done)
789            .await
790            .unwrap();
791
792        let backend: Arc<dyn ExternalBackend> = Arc::new(MockBackend::new("58"));
793        let task_manager = Arc::new(TaskManager::with_store(
794            Arc::clone(&backend),
795            Arc::clone(&store),
796            "owner/repo".to_string(),
797        ));
798        let gh = GhHttp::new().unwrap();
799        let task_id = ExternalId("58".to_string());
800
801        for command in [
802            OwnerCommand::Retry,
803            OwnerCommand::Reroute(None),
804            OwnerCommand::Unblock,
805        ] {
806            let err = execute_command(
807                &backend,
808                &gh,
809                "owner/repo",
810                &task_id,
811                &command,
812                &Some(Arc::clone(&store) as Arc<dyn CommandStoreOps>),
813                &task_manager,
814            )
815            .await
816            .expect_err("done task must not be revived");
817            assert!(err.to_string().contains("done is terminal"), "got: {err}");
818            assert_eq!(
819                store.get(store_id).await.unwrap().status,
820                TaskStatus::Done,
821                "{command} must leave a done task done"
822            );
823        }
824    }
825
826    #[tokio::test]
827    async fn done_task_refuses_block() {
828        assert_done_task_refuses(OwnerCommand::Block(Some(
829            "waiting on upstream fix".to_string(),
830        )))
831        .await;
832    }
833
834    #[tokio::test]
835    async fn done_task_refuses_review() {
836        assert_done_task_refuses(OwnerCommand::Review).await;
837    }
838
839    #[test]
840    fn parse_retry() {
841        assert_eq!(parse_command("/retry"), Some(OwnerCommand::Retry));
842    }
843
844    #[test]
845    fn parse_retry_with_trailing_whitespace() {
846        assert_eq!(parse_command("/retry   "), Some(OwnerCommand::Retry));
847    }
848
849    #[test]
850    fn parse_close() {
851        assert_eq!(parse_command("/close"), Some(OwnerCommand::Close));
852    }
853
854    #[test]
855    fn parse_unblock() {
856        assert_eq!(parse_command("/unblock"), Some(OwnerCommand::Unblock));
857    }
858
859    #[test]
860    fn parse_review() {
861        assert_eq!(parse_command("/review"), Some(OwnerCommand::Review));
862    }
863
864    #[test]
865    fn parse_reroute_no_agent() {
866        assert_eq!(parse_command("/reroute"), Some(OwnerCommand::Reroute(None)));
867    }
868
869    #[test]
870    fn parse_reroute_with_agent() {
871        assert_eq!(
872            parse_command("/reroute codex"),
873            Some(OwnerCommand::Reroute(Some("codex".into())))
874        );
875    }
876
877    #[test]
878    fn parse_block_no_reason() {
879        assert_eq!(parse_command("/block"), Some(OwnerCommand::Block(None)));
880    }
881
882    #[test]
883    fn parse_block_with_reason() {
884        assert_eq!(
885            parse_command("/block waiting on upstream fix"),
886            Some(OwnerCommand::Block(Some("waiting on upstream fix".into())))
887        );
888    }
889
890    #[test]
891    fn parse_ignores_non_command_text() {
892        assert_eq!(parse_command("This is a regular comment"), None);
893    }
894
895    #[test]
896    fn parse_ignores_unknown_commands() {
897        assert_eq!(parse_command("/unknown"), None);
898    }
899
900    #[test]
901    fn parse_command_in_multiline_body() {
902        let body = "Some context here\n\n/retry\n\nMore text";
903        assert_eq!(parse_command(body), Some(OwnerCommand::Retry));
904    }
905
906    #[test]
907    fn parse_first_valid_command_wins() {
908        let body = "/retry\n/close";
909        assert_eq!(parse_command(body), Some(OwnerCommand::Retry));
910    }
911
912    #[test]
913    fn parse_skips_unknown_finds_valid() {
914        let body = "/unknown\n/close";
915        assert_eq!(parse_command(body), Some(OwnerCommand::Close));
916    }
917
918    #[test]
919    fn parse_indented_command() {
920        // Commands with leading whitespace should still be detected
921        assert_eq!(parse_command("  /retry"), Some(OwnerCommand::Retry));
922    }
923
924    #[test]
925    fn parse_mention_prefixed_command() {
926        assert_eq!(parse_command("@orch /retry"), Some(OwnerCommand::Retry));
927    }
928
929    #[test]
930    fn parse_legacy_mention_prefixed_command() {
931        assert_eq!(
932            parse_command("@orchestrator /close"),
933            Some(OwnerCommand::Close)
934        );
935    }
936
937    #[test]
938    fn parse_ignores_non_command_after_mention() {
939        assert_eq!(parse_command("@orch please retry this"), None);
940    }
941
942    #[test]
943    fn parse_ignores_command_in_code_fence() {
944        let body = "Some context\n```\n/retry\n```\nMore text";
945        assert_eq!(parse_command(body), None);
946    }
947
948    #[test]
949    fn parse_ignores_mention_prefixed_command_in_code_fence() {
950        let body = "```\n@orch /retry\n```";
951        assert_eq!(parse_command(body), None);
952    }
953
954    #[test]
955    fn parse_ignores_command_in_tilde_fence() {
956        let body = "Some context\n~~~\n/close\n~~~\nMore text";
957        assert_eq!(parse_command(body), None);
958    }
959
960    #[test]
961    fn parse_finds_command_after_code_fence() {
962        let body = "```\n/retry\n```\n/close";
963        assert_eq!(parse_command(body), Some(OwnerCommand::Close));
964    }
965
966    #[test]
967    fn parse_ignores_command_in_code_fence_with_lang() {
968        let body = "```markdown\n/retry\n```";
969        assert_eq!(parse_command(body), None);
970    }
971
972    #[test]
973    fn parse_mixed_fence_does_not_close_backtick_with_tilde() {
974        // ~~~ should NOT close a ``` fence — /retry is still inside the fence
975        let body = "```bash\n/retry\n~~~\n/retry\n```";
976        assert_eq!(parse_command(body), None);
977    }
978
979    #[test]
980    fn parse_mixed_fence_does_not_close_tilde_with_backtick() {
981        // ``` should NOT close a ~~~ fence — /close is still inside the fence
982        let body = "~~~\n/close\n```\n/close\n~~~";
983        assert_eq!(parse_command(body), None);
984    }
985
986    #[test]
987    fn parse_command_after_mixed_fence_properly_closed() {
988        // Fence opened with ``` and closed with ``` (tilde in between is ignored)
989        // Command after the real closing fence should be found
990        let body = "```\n/retry\n~~~\n/retry\n```\n/close";
991        assert_eq!(parse_command(body), Some(OwnerCommand::Close));
992    }
993
994    #[tokio::test]
995    async fn retry_propagates_remove_label_error() {
996        let backend: Arc<dyn ExternalBackend> = Arc::new(MockBackend::failing_remove_label(
997            "42",
998            vec!["agent:claude".to_string()],
999        ));
1000        let store = Arc::new(TaskStore::open_memory().await.unwrap());
1001        let task_manager = Arc::new(TaskManager::with_store(
1002            Arc::clone(&backend),
1003            Arc::clone(&store),
1004            "owner/repo".to_string(),
1005        ));
1006        let gh = GhHttp::new().unwrap();
1007        let task_id = ExternalId("42".to_string());
1008
1009        let result = execute_command(
1010            &backend,
1011            &gh,
1012            "owner/repo",
1013            &task_id,
1014            &OwnerCommand::Retry,
1015            &Some(store as Arc<dyn CommandStoreOps>),
1016            &task_manager,
1017        )
1018        .await;
1019
1020        assert!(result.is_err(), "/retry must fail when remove_label fails");
1021        assert!(
1022            result.unwrap_err().to_string().contains("remove_label"),
1023            "error must mention remove_label"
1024        );
1025    }
1026
1027    #[tokio::test]
1028    async fn reroute_propagates_remove_label_error() {
1029        let backend: Arc<dyn ExternalBackend> = Arc::new(MockBackend::failing_remove_label(
1030            "42",
1031            vec!["agent:codex".to_string()],
1032        ));
1033        let store = Arc::new(TaskStore::open_memory().await.unwrap());
1034        let task_manager = Arc::new(TaskManager::with_store(
1035            Arc::clone(&backend),
1036            Arc::clone(&store),
1037            "owner/repo".to_string(),
1038        ));
1039        let gh = GhHttp::new().unwrap();
1040        let task_id = ExternalId("42".to_string());
1041
1042        let result = execute_command(
1043            &backend,
1044            &gh,
1045            "owner/repo",
1046            &task_id,
1047            &OwnerCommand::Reroute(None),
1048            &Some(store as Arc<dyn CommandStoreOps>),
1049            &task_manager,
1050        )
1051        .await;
1052
1053        assert!(
1054            result.is_err(),
1055            "/reroute must fail when remove_label fails"
1056        );
1057        assert!(
1058            result.unwrap_err().to_string().contains("remove_label"),
1059            "error must mention remove_label"
1060        );
1061    }
1062
1063    #[tokio::test]
1064    async fn block_propagates_resolve_task_id_error() {
1065        let backend: Arc<dyn ExternalBackend> = Arc::new(MockBackend::new("42"));
1066        let store = Arc::new(TaskStore::open_memory().await.unwrap());
1067        let task_manager = Arc::new(TaskManager::with_store(
1068            Arc::clone(&backend),
1069            store,
1070            "owner/repo".to_string(),
1071        ));
1072        let gh = GhHttp::new().unwrap();
1073        let task_id = ExternalId("42".to_string());
1074        let failing_store: Arc<dyn CommandStoreOps> = Arc::new(FailingStore);
1075
1076        let result = execute_command(
1077            &backend,
1078            &gh,
1079            "owner/repo",
1080            &task_id,
1081            &OwnerCommand::Block(Some("reason".to_string())),
1082            &Some(failing_store),
1083            &task_manager,
1084        )
1085        .await;
1086
1087        assert!(
1088            result.is_err(),
1089            "/block must fail when resolve_task_id fails"
1090        );
1091        assert!(
1092            result.unwrap_err().to_string().contains("resolve_task_id"),
1093            "error must mention resolve_task_id"
1094        );
1095    }
1096
1097    #[tokio::test]
1098    async fn unblock_propagates_resolve_task_id_error() {
1099        let backend: Arc<dyn ExternalBackend> = Arc::new(MockBackend::new("42"));
1100        let store = Arc::new(TaskStore::open_memory().await.unwrap());
1101        let task_manager = Arc::new(TaskManager::with_store(
1102            Arc::clone(&backend),
1103            store,
1104            "owner/repo".to_string(),
1105        ));
1106        let gh = GhHttp::new().unwrap();
1107        let task_id = ExternalId("42".to_string());
1108        let failing_store: Arc<dyn CommandStoreOps> = Arc::new(FailingStore);
1109
1110        let result = execute_command(
1111            &backend,
1112            &gh,
1113            "owner/repo",
1114            &task_id,
1115            &OwnerCommand::Unblock,
1116            &Some(failing_store),
1117            &task_manager,
1118        )
1119        .await;
1120
1121        assert!(
1122            result.is_err(),
1123            "/unblock must fail when resolve_task_id fails"
1124        );
1125        assert!(
1126            result.unwrap_err().to_string().contains("resolve_task_id"),
1127            "error must mention resolve_task_id"
1128        );
1129    }
1130
1131    #[test]
1132    fn parse_shorter_backtick_does_not_close_longer_backtick_fence() {
1133        // ```` opens a 4-backtick fence; ``` (3 backticks) must NOT close it
1134        let body = "````\n/retry\n```\n/retry\n````";
1135        assert_eq!(parse_command(body), None);
1136    }
1137
1138    #[test]
1139    fn parse_longer_backtick_closes_shorter_backtick_fence() {
1140        // ``` opens a 3-backtick fence; ```` (4 backticks) IS allowed to close it
1141        let body = "```\n/retry\n````\n/close";
1142        assert_eq!(parse_command(body), Some(OwnerCommand::Close));
1143    }
1144
1145    #[test]
1146    fn parse_shorter_tilde_does_not_close_longer_tilde_fence() {
1147        // ~~~~ opens a 4-tilde fence; ~~~ (3 tildes) must NOT close it
1148        let body = "~~~~\n/close\n~~~\n/close\n~~~~";
1149        assert_eq!(parse_command(body), None);
1150    }
1151
1152    #[test]
1153    fn parse_longer_tilde_closes_shorter_tilde_fence() {
1154        // ~~~ opens a 3-tilde fence; ~~~~ (4 tildes) IS allowed to close it
1155        let body = "~~~\n/close\n~~~~\n/retry";
1156        assert_eq!(parse_command(body), Some(OwnerCommand::Retry));
1157    }
1158
1159    #[test]
1160    fn parse_command_after_longer_backtick_fence_properly_closed() {
1161        // ```` fence closed with ```` — command after should be found
1162        let body = "````markdown\n/retry\n```\n/retry\n````\n/close";
1163        assert_eq!(parse_command(body), Some(OwnerCommand::Close));
1164    }
1165
1166    #[test]
1167    fn display_commands() {
1168        assert_eq!(OwnerCommand::Retry.to_string(), "/retry");
1169        assert_eq!(
1170            OwnerCommand::Reroute(Some("codex".into())).to_string(),
1171            "/reroute codex"
1172        );
1173        assert_eq!(OwnerCommand::Reroute(None).to_string(), "/reroute");
1174        assert_eq!(OwnerCommand::Close.to_string(), "/close");
1175        assert_eq!(
1176            OwnerCommand::Block(Some("reason".into())).to_string(),
1177            "/block reason"
1178        );
1179        assert_eq!(OwnerCommand::Block(None).to_string(), "/block");
1180        assert_eq!(OwnerCommand::Unblock.to_string(), "/unblock");
1181        assert_eq!(OwnerCommand::Review.to_string(), "/review");
1182    }
1183
1184    #[tokio::test]
1185    async fn retry_clears_agent_labels_resets_counters_and_returns_message() {
1186        let (mock, backend, store, store_id, task_manager, gh, task_id) =
1187            command_fixture("71", vec!["agent:claude".to_string(), "bug".to_string()]).await;
1188        store.increment(store_id, "attempts").await.unwrap();
1189        store.increment(store_id, "review_cycles").await.unwrap();
1190
1191        let msg = run_command(
1192            &backend,
1193            &gh,
1194            &store,
1195            &task_manager,
1196            &task_id,
1197            OwnerCommand::Retry,
1198        )
1199        .await
1200        .unwrap();
1201
1202        assert_eq!(
1203            msg,
1204            "`/retry` — reset attempts, cleared agent, reset to `status:new`"
1205        );
1206        let task = store.get(store_id).await.unwrap();
1207        assert_eq!(task.status, TaskStatus::New);
1208        assert_eq!(task.attempts, 0);
1209        assert_eq!(task.review_cycles, 0);
1210        assert_eq!(
1211            mock.removed_labels.lock().unwrap().as_slice(),
1212            ["agent:claude"]
1213        );
1214        assert!(mock.set_label_calls.lock().unwrap().is_empty());
1215    }
1216
1217    #[tokio::test]
1218    async fn reroute_without_agent_clears_labels_and_returns_message() {
1219        let (mock, backend, store, store_id, task_manager, gh, task_id) =
1220            command_fixture("72", vec!["agent:codex".to_string()]).await;
1221
1222        let msg = run_command(
1223            &backend,
1224            &gh,
1225            &store,
1226            &task_manager,
1227            &task_id,
1228            OwnerCommand::Reroute(None),
1229        )
1230        .await
1231        .unwrap();
1232
1233        assert_eq!(
1234            msg,
1235            "`/reroute` — cleared agent, reset attempts, reset to `status:new`, will re-route"
1236        );
1237        assert_eq!(store.get(store_id).await.unwrap().status, TaskStatus::New);
1238        assert_eq!(
1239            mock.removed_labels.lock().unwrap().as_slice(),
1240            ["agent:codex"]
1241        );
1242        assert!(mock.set_label_calls.lock().unwrap().is_empty());
1243    }
1244
1245    #[tokio::test]
1246    async fn reroute_with_agent_sets_forced_agent_label() {
1247        let (mock, backend, store, store_id, task_manager, gh, task_id) =
1248            command_fixture("73", vec!["agent:claude".to_string()]).await;
1249
1250        let msg = run_command(
1251            &backend,
1252            &gh,
1253            &store,
1254            &task_manager,
1255            &task_id,
1256            OwnerCommand::Reroute(Some("codex".into())),
1257        )
1258        .await
1259        .unwrap();
1260
1261        assert_eq!(
1262            msg,
1263            "`/reroute codex` — cleared agent, reset attempts, forced `agent:codex`, reset to `status:new`"
1264        );
1265        assert_eq!(store.get(store_id).await.unwrap().status, TaskStatus::New);
1266        assert_eq!(
1267            mock.removed_labels.lock().unwrap().as_slice(),
1268            ["agent:claude"]
1269        );
1270        assert_eq!(
1271            mock.set_label_calls.lock().unwrap().as_slice(),
1272            [vec!["agent:codex".to_string()]]
1273        );
1274    }
1275
1276    #[tokio::test]
1277    async fn review_sets_needs_review_and_returns_message() {
1278        let (_mock, backend, store, store_id, task_manager, gh, task_id) =
1279            command_fixture("74", vec![]).await;
1280
1281        let msg = run_command(
1282            &backend,
1283            &gh,
1284            &store,
1285            &task_manager,
1286            &task_id,
1287            OwnerCommand::Review,
1288        )
1289        .await
1290        .unwrap();
1291
1292        assert_eq!(
1293            msg,
1294            "`/review` — set `status:needs_review`, review agent will pick up on next tick"
1295        );
1296        assert_eq!(
1297            store.get(store_id).await.unwrap().status,
1298            TaskStatus::NeedsReview
1299        );
1300    }
1301
1302    #[tokio::test]
1303    async fn block_without_reason_returns_message() {
1304        let (_mock, backend, store, store_id, task_manager, gh, task_id) =
1305            command_fixture("75", vec![]).await;
1306
1307        let msg = run_command(
1308            &backend,
1309            &gh,
1310            &store,
1311            &task_manager,
1312            &task_id,
1313            OwnerCommand::Block(None),
1314        )
1315        .await
1316        .unwrap();
1317
1318        assert_eq!(msg, "`/block` — marked `status:blocked`");
1319        let task = store.get(store_id).await.unwrap();
1320        assert_eq!(task.status, TaskStatus::Blocked);
1321        assert!(task.block_reason.is_none());
1322    }
1323}