Skip to main content

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