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            write_block_reason(store.as_ref(), repo, &task_id.0, reason.as_deref()).await?;
310            task_manager
311                .update_task_status(task_id, Status::Blocked)
312                .await?;
313            match reason {
314                Some(r) => Ok(format!("`/block` — marked `status:blocked`: {r}")),
315                None => Ok("`/block` — marked `status:blocked`".to_string()),
316            }
317        }
318
319        OwnerCommand::Unblock => {
320            refuse_if_done(store.as_ref(), repo, &task_id.0, command).await?;
321            write_block_reason(store.as_ref(), repo, &task_id.0, None).await?;
322            task_manager
323                .update_task_status(task_id, Status::New)
324                .await?;
325            Ok("`/unblock` — marked `status:new`, will re-dispatch".to_string())
326        }
327
328        OwnerCommand::Review => {
329            task_manager
330                .update_task_status(task_id, Status::NeedsReview)
331                .await?;
332            Ok(
333                "`/review` — set `status:needs_review`, review agent will pick up on next tick"
334                    .to_string(),
335            )
336        }
337    }
338}
339
340/// Result of attempting to validate and run a slash command.
341///
342/// Variants that successfully fetched issue data include `is_pr` so callers
343/// don't need a second `get_issue` call.
344#[derive(Debug)]
345pub enum CommandOutcome {
346    /// Command executed successfully or failed — either way, it was handled.
347    Executed { is_pr: bool },
348    /// Issue/PR is not open — command was skipped.
349    NotOpen { is_pr: bool },
350    /// Author is not a collaborator — command was skipped.
351    NotCollaborator { is_pr: bool },
352    /// Failed to fetch issue state — should retry.
353    FetchFailed,
354    /// Failed to check collaborator status — should retry.
355    CollaboratorCheckFailed,
356}
357
358/// Validate a slash command (issue open, author is collaborator) and execute it.
359///
360/// Shared by both `scan_commands` (issue comments) and `scan_mentions` (mention
361/// handling). Posts a confirmation or error comment on the issue/PR.
362#[expect(
363    clippy::too_many_arguments,
364    reason = "two scan paths pass their own context to one shared validator"
365)]
366pub async fn validate_and_run_command(
367    backend: &Arc<dyn ExternalBackend>,
368    gh: &dyn CommandGh,
369    repo: &str,
370    issue_number: &str,
371    command: &OwnerCommand,
372    author: &str,
373    store: &Option<Arc<dyn CommandStoreOps>>,
374    task_manager: &Arc<TaskManager>,
375) -> CommandOutcome {
376    // Check issue state
377    let issue_data = match gh.get_issue(repo, issue_number).await {
378        Ok(data) => data,
379        Err(e) => {
380            tracing::warn!(issue = %issue_number, err = %e, "failed to check issue state");
381            return CommandOutcome::FetchFailed;
382        }
383    };
384
385    let is_pr = issue_data.pull_request.is_some();
386
387    if issue_data.state != "open" {
388        tracing::debug!(issue = %issue_number, state = %issue_data.state, command = %command, "ignoring slash command on non-open issue");
389        return CommandOutcome::NotOpen { is_pr };
390    }
391
392    // Check collaborator status
393    match gh.is_collaborator(repo, author).await {
394        Ok(true) => {}
395        Ok(false) => {
396            tracing::info!(author, command = %command, issue = %issue_number, "ignoring slash command from non-collaborator");
397            return CommandOutcome::NotCollaborator { is_pr };
398        }
399        Err(e) => {
400            tracing::warn!(author, err = %e, "failed to check collaborator status");
401            return CommandOutcome::CollaboratorCheckFailed;
402        }
403    }
404
405    // Execute and post result
406    let task_id = ExternalId(issue_number.to_string());
407    let now = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string();
408
409    match execute_command(backend, gh, repo, &task_id, command, store, task_manager).await {
410        Ok(msg) => {
411            tracing::info!(issue = %issue_number, author, command = %command, "executed command");
412            let confirmation = format!(
413                "[{now}] {msg} — executed by @{author}{}",
414                engine::orch_footer()
415            );
416            if let Err(e) = backend.post_comment(&task_id, &confirmation).await {
417                tracing::warn!(issue = %issue_number, err = %e, "failed to post confirmation");
418            }
419        }
420        Err(e) => {
421            tracing::warn!(issue = %issue_number, command = %command, err = %e, "failed to execute command");
422            let error_msg = format!(
423                "[{now}] Failed to execute `{command}`: {e}{}",
424                engine::orch_footer()
425            );
426            if let Err(e2) = backend.post_comment(&task_id, &error_msg).await {
427                tracing::warn!(issue = %issue_number, err = %e2, "failed to post error comment");
428            }
429        }
430    }
431
432    CommandOutcome::Executed { is_pr }
433}
434
435#[cfg(test)]
436mod tests {
437    use super::*;
438    use crate::backends::{ExternalBackend, ExternalId, ExternalTask, Mention, Status};
439    use crate::store::{NewTask, TaskStore};
440    use async_trait::async_trait;
441    use std::sync::Arc;
442    use std::sync::Mutex;
443
444    struct MockBackend {
445        task: ExternalTask,
446        fail_remove_label: bool,
447        removed_labels: Mutex<Vec<String>>,
448        set_label_calls: Mutex<Vec<Vec<String>>>,
449    }
450
451    impl MockBackend {
452        fn new(id: &str) -> Self {
453            Self {
454                task: ExternalTask {
455                    id: ExternalId(id.to_string()),
456                    title: "Task".to_string(),
457                    body: String::new(),
458                    state: "open".to_string(),
459                    labels: vec![],
460                    author: "bot".to_string(),
461                    created_at: "2026-01-01T00:00:00Z".to_string(),
462                    updated_at: "2026-01-01T00:00:00Z".to_string(),
463                    url: String::new(),
464                },
465                fail_remove_label: false,
466                removed_labels: Mutex::new(Vec::new()),
467                set_label_calls: Mutex::new(Vec::new()),
468            }
469        }
470
471        fn with_labels(id: &str, labels: Vec<String>) -> Self {
472            let mut b = Self::new(id);
473            b.task.labels = labels;
474            b
475        }
476
477        fn failing_remove_label(id: &str, labels: Vec<String>) -> Self {
478            let mut b = Self::with_labels(id, labels);
479            b.fail_remove_label = true;
480            b
481        }
482    }
483
484    #[async_trait]
485    impl ExternalBackend for MockBackend {
486        fn name(&self) -> &'static str {
487            "mock"
488        }
489
490        async fn create_task(
491            &self,
492            _title: &str,
493            _body: &str,
494            _labels: &[String],
495        ) -> anyhow::Result<ExternalId> {
496            Ok(self.task.id.clone())
497        }
498
499        async fn get_task(&self, _id: &ExternalId) -> anyhow::Result<ExternalTask> {
500            Ok(self.task.clone())
501        }
502
503        async fn list_by_status(&self, _status: Status) -> anyhow::Result<Vec<ExternalTask>> {
504            Ok(vec![])
505        }
506
507        async fn list_routable(&self) -> anyhow::Result<Vec<ExternalTask>> {
508            Ok(vec![])
509        }
510
511        async fn post_comment(&self, _id: &ExternalId, _body: &str) -> anyhow::Result<()> {
512            Ok(())
513        }
514
515        async fn set_labels(&self, _id: &ExternalId, labels: &[String]) -> anyhow::Result<()> {
516            self.set_label_calls.lock().unwrap().push(labels.to_vec());
517            Ok(())
518        }
519
520        async fn remove_label(&self, _id: &ExternalId, label: &str) -> anyhow::Result<()> {
521            if self.fail_remove_label {
522                anyhow::bail!("simulated remove_label failure for {label}");
523            }
524            self.removed_labels.lock().unwrap().push(label.to_string());
525            Ok(())
526        }
527
528        async fn get_sub_issues(&self, _id: &ExternalId) -> anyhow::Result<Vec<ExternalId>> {
529            Ok(vec![])
530        }
531
532        async fn create_sub_task(
533            &self,
534            _parent: &ExternalId,
535            _title: &str,
536            _body: &str,
537            _labels: &[String],
538        ) -> anyhow::Result<ExternalId> {
539            Ok(ExternalId("child".to_string()))
540        }
541
542        async fn ensure_status_label(&self, _label: &str) -> anyhow::Result<()> {
543            Ok(())
544        }
545
546        async fn has_open_issue_with_title(
547            &self,
548            _title: &str,
549            _label: &str,
550        ) -> anyhow::Result<bool> {
551            Ok(false)
552        }
553
554        async fn health_check(&self) -> anyhow::Result<()> {
555            Ok(())
556        }
557
558        async fn is_pr_merged(&self, _branch: &str) -> anyhow::Result<bool> {
559            Ok(false)
560        }
561
562        async fn get_authenticated_user(&self) -> anyhow::Result<Option<String>> {
563            Ok(Some("testbot".to_string()))
564        }
565
566        async fn get_mentions(&self, _since: &str) -> anyhow::Result<Vec<Mention>> {
567            Ok(vec![])
568        }
569
570        async fn update_status(&self, _id: &ExternalId, _status: Status) -> anyhow::Result<()> {
571            Ok(())
572        }
573    }
574
575    /// Mock store whose `resolve_task_id` always returns an error.
576    struct FailingStore;
577
578    #[async_trait]
579    impl CommandStoreOps for FailingStore {
580        async fn resolve_task_id(
581            &self,
582            _repo: &str,
583            _task_id: &str,
584        ) -> anyhow::Result<Option<i64>> {
585            anyhow::bail!("simulated resolve_task_id DB failure")
586        }
587
588        async fn set_block_reason(&self, _id: i64, _reason: Option<&str>) -> anyhow::Result<()> {
589            anyhow::bail!("simulated set_block_reason DB failure")
590        }
591
592        async fn reset_counters(&self, _id: i64) -> anyhow::Result<()> {
593            Ok(())
594        }
595
596        async fn status(&self, _repo: &str, _task_id: &str) -> anyhow::Result<Option<TaskStatus>> {
597            Ok(None)
598        }
599    }
600
601    async fn command_fixture(
602        id: &str,
603        labels: Vec<String>,
604    ) -> (
605        Arc<MockBackend>,
606        Arc<dyn ExternalBackend>,
607        Arc<TaskStore>,
608        i64,
609        Arc<TaskManager>,
610        GhHttp,
611        ExternalId,
612    ) {
613        let store = Arc::new(TaskStore::open_memory().await.unwrap());
614        let store_id = store
615            .create(&NewTask {
616                external_id: Some(id.to_string()),
617                repo: "owner/repo".to_string(),
618                origin: "github".to_string(),
619                title: "Task".to_string(),
620                body: String::new(),
621                source: "manual".to_string(),
622                source_id: String::new(),
623                author: "bot".to_string(),
624                url: String::new(),
625                labels: labels.clone(),
626                parent_id: None,
627            })
628            .await
629            .unwrap();
630        let mock = Arc::new(MockBackend::with_labels(id, labels));
631        let backend: Arc<dyn ExternalBackend> = Arc::<MockBackend>::clone(&mock);
632        let task_manager = Arc::new(TaskManager::with_store(
633            Arc::clone(&backend),
634            Arc::clone(&store),
635            "owner/repo".to_string(),
636        ));
637        (
638            mock,
639            backend,
640            store,
641            store_id,
642            task_manager,
643            GhHttp::new().unwrap(),
644            ExternalId(id.to_string()),
645        )
646    }
647
648    async fn run_command(
649        backend: &Arc<dyn ExternalBackend>,
650        gh: &GhHttp,
651        store: &Arc<TaskStore>,
652        task_manager: &Arc<TaskManager>,
653        task_id: &ExternalId,
654        command: OwnerCommand,
655    ) -> anyhow::Result<String> {
656        execute_command(
657            backend,
658            gh,
659            "owner/repo",
660            task_id,
661            &command,
662            &Some(Arc::clone(store) as Arc<dyn CommandStoreOps>),
663            task_manager,
664        )
665        .await
666    }
667
668    #[tokio::test]
669    async fn block_command_persists_reason_and_unblock_clears_it() {
670        let store = Arc::new(TaskStore::open_memory().await.unwrap());
671        let store_id = store
672            .create(&NewTask {
673                external_id: Some("42".to_string()),
674                repo: "owner/repo".to_string(),
675                origin: "github".to_string(),
676                title: "Task".to_string(),
677                body: String::new(),
678                source: "manual".to_string(),
679                source_id: String::new(),
680                author: "bot".to_string(),
681                url: String::new(),
682                labels: vec![],
683                parent_id: None,
684            })
685            .await
686            .unwrap();
687        let backend: Arc<dyn ExternalBackend> = Arc::new(MockBackend::new("42"));
688        let backend_for_call = Arc::clone(&backend);
689        let task_manager = Arc::new(TaskManager::with_store(
690            backend,
691            Arc::clone(&store),
692            "owner/repo".to_string(),
693        ));
694        let gh = GhHttp::new().unwrap();
695        let task_id = ExternalId("42".to_string());
696
697        execute_command(
698            &backend_for_call,
699            &gh,
700            "owner/repo",
701            &task_id,
702            &OwnerCommand::Block(Some("waiting on upstream fix".to_string())),
703            &Some(Arc::clone(&store) as Arc<dyn CommandStoreOps>),
704            &task_manager,
705        )
706        .await
707        .unwrap();
708
709        let task = store.get(store_id).await.unwrap();
710        assert_eq!(task.status, TaskStatus::Blocked);
711        assert_eq!(
712            task.block_reason.as_deref(),
713            Some("waiting on upstream fix")
714        );
715
716        execute_command(
717            &backend_for_call,
718            &gh,
719            "owner/repo",
720            &task_id,
721            &OwnerCommand::Unblock,
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::New);
730        assert!(task.block_reason.is_none());
731    }
732
733    /// Done is terminal: `/retry`, `/reroute` and `/unblock` must refuse a done
734    /// task instead of sending its stale body back to an agent (#3780).
735    #[tokio::test]
736    async fn done_task_refuses_retry_reroute_and_unblock() {
737        let store = Arc::new(TaskStore::open_memory().await.unwrap());
738        let store_id = store
739            .create(&NewTask {
740                external_id: Some("58".to_string()),
741                repo: "owner/repo".to_string(),
742                origin: "github".to_string(),
743                title: "Task".to_string(),
744                body: String::new(),
745                source: "cron".to_string(),
746                source_id: "code-development".to_string(),
747                author: "bot".to_string(),
748                url: String::new(),
749                labels: vec![],
750                parent_id: None,
751            })
752            .await
753            .unwrap();
754        store
755            .update_status(store_id, TaskStatus::Done)
756            .await
757            .unwrap();
758
759        let backend: Arc<dyn ExternalBackend> = Arc::new(MockBackend::new("58"));
760        let task_manager = Arc::new(TaskManager::with_store(
761            Arc::clone(&backend),
762            Arc::clone(&store),
763            "owner/repo".to_string(),
764        ));
765        let gh = GhHttp::new().unwrap();
766        let task_id = ExternalId("58".to_string());
767
768        for command in [
769            OwnerCommand::Retry,
770            OwnerCommand::Reroute(None),
771            OwnerCommand::Unblock,
772        ] {
773            let err = execute_command(
774                &backend,
775                &gh,
776                "owner/repo",
777                &task_id,
778                &command,
779                &Some(Arc::clone(&store) as Arc<dyn CommandStoreOps>),
780                &task_manager,
781            )
782            .await
783            .expect_err("done task must not be revived");
784            assert!(err.to_string().contains("done is terminal"), "got: {err}");
785            assert_eq!(
786                store.get(store_id).await.unwrap().status,
787                TaskStatus::Done,
788                "{command} must leave a done task done"
789            );
790        }
791    }
792
793    #[test]
794    fn parse_retry() {
795        assert_eq!(parse_command("/retry"), Some(OwnerCommand::Retry));
796    }
797
798    #[test]
799    fn parse_retry_with_trailing_whitespace() {
800        assert_eq!(parse_command("/retry   "), Some(OwnerCommand::Retry));
801    }
802
803    #[test]
804    fn parse_close() {
805        assert_eq!(parse_command("/close"), Some(OwnerCommand::Close));
806    }
807
808    #[test]
809    fn parse_unblock() {
810        assert_eq!(parse_command("/unblock"), Some(OwnerCommand::Unblock));
811    }
812
813    #[test]
814    fn parse_review() {
815        assert_eq!(parse_command("/review"), Some(OwnerCommand::Review));
816    }
817
818    #[test]
819    fn parse_reroute_no_agent() {
820        assert_eq!(parse_command("/reroute"), Some(OwnerCommand::Reroute(None)));
821    }
822
823    #[test]
824    fn parse_reroute_with_agent() {
825        assert_eq!(
826            parse_command("/reroute codex"),
827            Some(OwnerCommand::Reroute(Some("codex".into())))
828        );
829    }
830
831    #[test]
832    fn parse_block_no_reason() {
833        assert_eq!(parse_command("/block"), Some(OwnerCommand::Block(None)));
834    }
835
836    #[test]
837    fn parse_block_with_reason() {
838        assert_eq!(
839            parse_command("/block waiting on upstream fix"),
840            Some(OwnerCommand::Block(Some("waiting on upstream fix".into())))
841        );
842    }
843
844    #[test]
845    fn parse_ignores_non_command_text() {
846        assert_eq!(parse_command("This is a regular comment"), None);
847    }
848
849    #[test]
850    fn parse_ignores_unknown_commands() {
851        assert_eq!(parse_command("/unknown"), None);
852    }
853
854    #[test]
855    fn parse_command_in_multiline_body() {
856        let body = "Some context here\n\n/retry\n\nMore text";
857        assert_eq!(parse_command(body), Some(OwnerCommand::Retry));
858    }
859
860    #[test]
861    fn parse_first_valid_command_wins() {
862        let body = "/retry\n/close";
863        assert_eq!(parse_command(body), Some(OwnerCommand::Retry));
864    }
865
866    #[test]
867    fn parse_skips_unknown_finds_valid() {
868        let body = "/unknown\n/close";
869        assert_eq!(parse_command(body), Some(OwnerCommand::Close));
870    }
871
872    #[test]
873    fn parse_indented_command() {
874        // Commands with leading whitespace should still be detected
875        assert_eq!(parse_command("  /retry"), Some(OwnerCommand::Retry));
876    }
877
878    #[test]
879    fn parse_mention_prefixed_command() {
880        assert_eq!(parse_command("@orch /retry"), Some(OwnerCommand::Retry));
881    }
882
883    #[test]
884    fn parse_legacy_mention_prefixed_command() {
885        assert_eq!(
886            parse_command("@orchestrator /close"),
887            Some(OwnerCommand::Close)
888        );
889    }
890
891    #[test]
892    fn parse_ignores_non_command_after_mention() {
893        assert_eq!(parse_command("@orch please retry this"), None);
894    }
895
896    #[test]
897    fn parse_ignores_command_in_code_fence() {
898        let body = "Some context\n```\n/retry\n```\nMore text";
899        assert_eq!(parse_command(body), None);
900    }
901
902    #[test]
903    fn parse_ignores_mention_prefixed_command_in_code_fence() {
904        let body = "```\n@orch /retry\n```";
905        assert_eq!(parse_command(body), None);
906    }
907
908    #[test]
909    fn parse_ignores_command_in_tilde_fence() {
910        let body = "Some context\n~~~\n/close\n~~~\nMore text";
911        assert_eq!(parse_command(body), None);
912    }
913
914    #[test]
915    fn parse_finds_command_after_code_fence() {
916        let body = "```\n/retry\n```\n/close";
917        assert_eq!(parse_command(body), Some(OwnerCommand::Close));
918    }
919
920    #[test]
921    fn parse_ignores_command_in_code_fence_with_lang() {
922        let body = "```markdown\n/retry\n```";
923        assert_eq!(parse_command(body), None);
924    }
925
926    #[test]
927    fn parse_mixed_fence_does_not_close_backtick_with_tilde() {
928        // ~~~ should NOT close a ``` fence — /retry is still inside the fence
929        let body = "```bash\n/retry\n~~~\n/retry\n```";
930        assert_eq!(parse_command(body), None);
931    }
932
933    #[test]
934    fn parse_mixed_fence_does_not_close_tilde_with_backtick() {
935        // ``` should NOT close a ~~~ fence — /close is still inside the fence
936        let body = "~~~\n/close\n```\n/close\n~~~";
937        assert_eq!(parse_command(body), None);
938    }
939
940    #[test]
941    fn parse_command_after_mixed_fence_properly_closed() {
942        // Fence opened with ``` and closed with ``` (tilde in between is ignored)
943        // Command after the real closing fence should be found
944        let body = "```\n/retry\n~~~\n/retry\n```\n/close";
945        assert_eq!(parse_command(body), Some(OwnerCommand::Close));
946    }
947
948    #[tokio::test]
949    async fn retry_propagates_remove_label_error() {
950        let backend: Arc<dyn ExternalBackend> = Arc::new(MockBackend::failing_remove_label(
951            "42",
952            vec!["agent:claude".to_string()],
953        ));
954        let store = Arc::new(TaskStore::open_memory().await.unwrap());
955        let task_manager = Arc::new(TaskManager::with_store(
956            Arc::clone(&backend),
957            Arc::clone(&store),
958            "owner/repo".to_string(),
959        ));
960        let gh = GhHttp::new().unwrap();
961        let task_id = ExternalId("42".to_string());
962
963        let result = execute_command(
964            &backend,
965            &gh,
966            "owner/repo",
967            &task_id,
968            &OwnerCommand::Retry,
969            &Some(store as Arc<dyn CommandStoreOps>),
970            &task_manager,
971        )
972        .await;
973
974        assert!(result.is_err(), "/retry must fail when remove_label fails");
975        assert!(
976            result.unwrap_err().to_string().contains("remove_label"),
977            "error must mention remove_label"
978        );
979    }
980
981    #[tokio::test]
982    async fn reroute_propagates_remove_label_error() {
983        let backend: Arc<dyn ExternalBackend> = Arc::new(MockBackend::failing_remove_label(
984            "42",
985            vec!["agent:codex".to_string()],
986        ));
987        let store = Arc::new(TaskStore::open_memory().await.unwrap());
988        let task_manager = Arc::new(TaskManager::with_store(
989            Arc::clone(&backend),
990            Arc::clone(&store),
991            "owner/repo".to_string(),
992        ));
993        let gh = GhHttp::new().unwrap();
994        let task_id = ExternalId("42".to_string());
995
996        let result = execute_command(
997            &backend,
998            &gh,
999            "owner/repo",
1000            &task_id,
1001            &OwnerCommand::Reroute(None),
1002            &Some(store as Arc<dyn CommandStoreOps>),
1003            &task_manager,
1004        )
1005        .await;
1006
1007        assert!(
1008            result.is_err(),
1009            "/reroute must fail when remove_label fails"
1010        );
1011        assert!(
1012            result.unwrap_err().to_string().contains("remove_label"),
1013            "error must mention remove_label"
1014        );
1015    }
1016
1017    #[tokio::test]
1018    async fn block_propagates_resolve_task_id_error() {
1019        let backend: Arc<dyn ExternalBackend> = Arc::new(MockBackend::new("42"));
1020        let store = Arc::new(TaskStore::open_memory().await.unwrap());
1021        let task_manager = Arc::new(TaskManager::with_store(
1022            Arc::clone(&backend),
1023            store,
1024            "owner/repo".to_string(),
1025        ));
1026        let gh = GhHttp::new().unwrap();
1027        let task_id = ExternalId("42".to_string());
1028        let failing_store: Arc<dyn CommandStoreOps> = Arc::new(FailingStore);
1029
1030        let result = execute_command(
1031            &backend,
1032            &gh,
1033            "owner/repo",
1034            &task_id,
1035            &OwnerCommand::Block(Some("reason".to_string())),
1036            &Some(failing_store),
1037            &task_manager,
1038        )
1039        .await;
1040
1041        assert!(
1042            result.is_err(),
1043            "/block must fail when resolve_task_id fails"
1044        );
1045        assert!(
1046            result.unwrap_err().to_string().contains("resolve_task_id"),
1047            "error must mention resolve_task_id"
1048        );
1049    }
1050
1051    #[tokio::test]
1052    async fn unblock_propagates_resolve_task_id_error() {
1053        let backend: Arc<dyn ExternalBackend> = Arc::new(MockBackend::new("42"));
1054        let store = Arc::new(TaskStore::open_memory().await.unwrap());
1055        let task_manager = Arc::new(TaskManager::with_store(
1056            Arc::clone(&backend),
1057            store,
1058            "owner/repo".to_string(),
1059        ));
1060        let gh = GhHttp::new().unwrap();
1061        let task_id = ExternalId("42".to_string());
1062        let failing_store: Arc<dyn CommandStoreOps> = Arc::new(FailingStore);
1063
1064        let result = execute_command(
1065            &backend,
1066            &gh,
1067            "owner/repo",
1068            &task_id,
1069            &OwnerCommand::Unblock,
1070            &Some(failing_store),
1071            &task_manager,
1072        )
1073        .await;
1074
1075        assert!(
1076            result.is_err(),
1077            "/unblock must fail when resolve_task_id fails"
1078        );
1079        assert!(
1080            result.unwrap_err().to_string().contains("resolve_task_id"),
1081            "error must mention resolve_task_id"
1082        );
1083    }
1084
1085    #[test]
1086    fn parse_shorter_backtick_does_not_close_longer_backtick_fence() {
1087        // ```` opens a 4-backtick fence; ``` (3 backticks) must NOT close it
1088        let body = "````\n/retry\n```\n/retry\n````";
1089        assert_eq!(parse_command(body), None);
1090    }
1091
1092    #[test]
1093    fn parse_longer_backtick_closes_shorter_backtick_fence() {
1094        // ``` opens a 3-backtick fence; ```` (4 backticks) IS allowed to close it
1095        let body = "```\n/retry\n````\n/close";
1096        assert_eq!(parse_command(body), Some(OwnerCommand::Close));
1097    }
1098
1099    #[test]
1100    fn parse_shorter_tilde_does_not_close_longer_tilde_fence() {
1101        // ~~~~ opens a 4-tilde fence; ~~~ (3 tildes) must NOT close it
1102        let body = "~~~~\n/close\n~~~\n/close\n~~~~";
1103        assert_eq!(parse_command(body), None);
1104    }
1105
1106    #[test]
1107    fn parse_longer_tilde_closes_shorter_tilde_fence() {
1108        // ~~~ opens a 3-tilde fence; ~~~~ (4 tildes) IS allowed to close it
1109        let body = "~~~\n/close\n~~~~\n/retry";
1110        assert_eq!(parse_command(body), Some(OwnerCommand::Retry));
1111    }
1112
1113    #[test]
1114    fn parse_command_after_longer_backtick_fence_properly_closed() {
1115        // ```` fence closed with ```` — command after should be found
1116        let body = "````markdown\n/retry\n```\n/retry\n````\n/close";
1117        assert_eq!(parse_command(body), Some(OwnerCommand::Close));
1118    }
1119
1120    #[test]
1121    fn display_commands() {
1122        assert_eq!(OwnerCommand::Retry.to_string(), "/retry");
1123        assert_eq!(
1124            OwnerCommand::Reroute(Some("codex".into())).to_string(),
1125            "/reroute codex"
1126        );
1127        assert_eq!(OwnerCommand::Reroute(None).to_string(), "/reroute");
1128        assert_eq!(OwnerCommand::Close.to_string(), "/close");
1129        assert_eq!(
1130            OwnerCommand::Block(Some("reason".into())).to_string(),
1131            "/block reason"
1132        );
1133        assert_eq!(OwnerCommand::Block(None).to_string(), "/block");
1134        assert_eq!(OwnerCommand::Unblock.to_string(), "/unblock");
1135        assert_eq!(OwnerCommand::Review.to_string(), "/review");
1136    }
1137
1138    #[tokio::test]
1139    async fn retry_clears_agent_labels_resets_counters_and_returns_message() {
1140        let (mock, backend, store, store_id, task_manager, gh, task_id) =
1141            command_fixture("71", vec!["agent:claude".to_string(), "bug".to_string()]).await;
1142        store.increment(store_id, "attempts").await.unwrap();
1143        store.increment(store_id, "review_cycles").await.unwrap();
1144
1145        let msg = run_command(
1146            &backend,
1147            &gh,
1148            &store,
1149            &task_manager,
1150            &task_id,
1151            OwnerCommand::Retry,
1152        )
1153        .await
1154        .unwrap();
1155
1156        assert_eq!(
1157            msg,
1158            "`/retry` — reset attempts, cleared agent, reset to `status:new`"
1159        );
1160        let task = store.get(store_id).await.unwrap();
1161        assert_eq!(task.status, TaskStatus::New);
1162        assert_eq!(task.attempts, 0);
1163        assert_eq!(task.review_cycles, 0);
1164        assert_eq!(
1165            mock.removed_labels.lock().unwrap().as_slice(),
1166            ["agent:claude"]
1167        );
1168        assert!(mock.set_label_calls.lock().unwrap().is_empty());
1169    }
1170
1171    #[tokio::test]
1172    async fn reroute_without_agent_clears_labels_and_returns_message() {
1173        let (mock, backend, store, store_id, task_manager, gh, task_id) =
1174            command_fixture("72", vec!["agent:codex".to_string()]).await;
1175
1176        let msg = run_command(
1177            &backend,
1178            &gh,
1179            &store,
1180            &task_manager,
1181            &task_id,
1182            OwnerCommand::Reroute(None),
1183        )
1184        .await
1185        .unwrap();
1186
1187        assert_eq!(
1188            msg,
1189            "`/reroute` — cleared agent, reset attempts, reset to `status:new`, will re-route"
1190        );
1191        assert_eq!(store.get(store_id).await.unwrap().status, TaskStatus::New);
1192        assert_eq!(
1193            mock.removed_labels.lock().unwrap().as_slice(),
1194            ["agent:codex"]
1195        );
1196        assert!(mock.set_label_calls.lock().unwrap().is_empty());
1197    }
1198
1199    #[tokio::test]
1200    async fn reroute_with_agent_sets_forced_agent_label() {
1201        let (mock, backend, store, store_id, task_manager, gh, task_id) =
1202            command_fixture("73", vec!["agent:claude".to_string()]).await;
1203
1204        let msg = run_command(
1205            &backend,
1206            &gh,
1207            &store,
1208            &task_manager,
1209            &task_id,
1210            OwnerCommand::Reroute(Some("codex".into())),
1211        )
1212        .await
1213        .unwrap();
1214
1215        assert_eq!(
1216            msg,
1217            "`/reroute codex` — cleared agent, reset attempts, forced `agent:codex`, reset to `status:new`"
1218        );
1219        assert_eq!(store.get(store_id).await.unwrap().status, TaskStatus::New);
1220        assert_eq!(
1221            mock.removed_labels.lock().unwrap().as_slice(),
1222            ["agent:claude"]
1223        );
1224        assert_eq!(
1225            mock.set_label_calls.lock().unwrap().as_slice(),
1226            [vec!["agent:codex".to_string()]]
1227        );
1228    }
1229
1230    #[tokio::test]
1231    async fn review_sets_needs_review_and_returns_message() {
1232        let (_mock, backend, store, store_id, task_manager, gh, task_id) =
1233            command_fixture("74", vec![]).await;
1234
1235        let msg = run_command(
1236            &backend,
1237            &gh,
1238            &store,
1239            &task_manager,
1240            &task_id,
1241            OwnerCommand::Review,
1242        )
1243        .await
1244        .unwrap();
1245
1246        assert_eq!(
1247            msg,
1248            "`/review` — set `status:needs_review`, review agent will pick up on next tick"
1249        );
1250        assert_eq!(
1251            store.get(store_id).await.unwrap().status,
1252            TaskStatus::NeedsReview
1253        );
1254    }
1255
1256    #[tokio::test]
1257    async fn block_without_reason_returns_message() {
1258        let (_mock, backend, store, store_id, task_manager, gh, task_id) =
1259            command_fixture("75", vec![]).await;
1260
1261        let msg = run_command(
1262            &backend,
1263            &gh,
1264            &store,
1265            &task_manager,
1266            &task_id,
1267            OwnerCommand::Block(None),
1268        )
1269        .await
1270        .unwrap();
1271
1272        assert_eq!(msg, "`/block` — marked `status:blocked`");
1273        let task = store.get(store_id).await.unwrap();
1274        assert_eq!(task.status, TaskStatus::Blocked);
1275        assert!(task.block_reason.is_none());
1276    }
1277}