orch-cli 0.86.2

Orch, the agent orchestration engine: runs coding agents on tasks and cron jobs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
//! Owner slash commands — parse, validate, and execute /commands in issue comments.
//!
//! Provides command parsing (`parse_command`), validation + execution
//! (`validate_and_run_command`), and the individual command implementations.
//! The scanning loop lives in `sync.rs` (`scan_comments`).

use crate::backends::{ExternalBackend, ExternalId, Status};
use crate::github::http::GhHttp;
use async_trait::async_trait;
use std::sync::Arc;

/// Minimal store interface required by command execution.
///
/// Exists so tests can inject a mock that simulates DB failures without
/// coupling the test harness to a real SQLite pool.
#[allow(clippy::double_must_use)] // async_trait marks its boxed futures must_use twice
#[async_trait]
pub trait CommandStoreOps: Send + Sync {
    async fn resolve_task_id(&self, repo: &str, task_id: &str) -> anyhow::Result<Option<i64>>;

    async fn set_block_reason(&self, id: i64, reason: Option<&str>) -> anyhow::Result<()>;

    /// Reset all per-attempt counters for a task. Fire-and-forget — failures are
    /// logged but not propagated (same semantics as `store::store_reset_counters`).
    async fn reset_counters(&self, id: i64) -> anyhow::Result<()>;
}

#[async_trait]
impl CommandStoreOps for crate::store::TaskStore {
    async fn resolve_task_id(&self, repo: &str, task_id: &str) -> anyhow::Result<Option<i64>> {
        self.resolve_task_id(repo, task_id).await
    }

    async fn set_block_reason(&self, id: i64, reason: Option<&str>) -> anyhow::Result<()> {
        self.set_block_reason(id, reason).await
    }

    async fn reset_counters(&self, id: i64) -> anyhow::Result<()> {
        self.reset_counters(id).await
    }
}

/// Parsed owner command from an issue comment.
#[derive(Debug, Clone, PartialEq)]
pub enum OwnerCommand {
    /// Reset to status:new, re-dispatch.
    Retry,
    /// Clear agent, re-route (optionally force agent).
    Reroute(Option<String>),
    /// Mark status:done, close issue.
    Close,
    /// Mark status:blocked with optional reason.
    Block(Option<String>),
    /// Mark status:new, re-dispatch.
    Unblock,
    /// Trigger review agent on current PR.
    Review,
}

impl std::fmt::Display for OwnerCommand {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Retry => write!(f, "/retry"),
            Self::Reroute(Some(a)) => write!(f, "/reroute {a}"),
            Self::Reroute(None) => write!(f, "/reroute"),
            Self::Close => write!(f, "/close"),
            Self::Block(Some(r)) => write!(f, "/block {r}"),
            Self::Block(None) => write!(f, "/block"),
            Self::Unblock => write!(f, "/unblock"),
            Self::Review => write!(f, "/review"),
        }
    }
}

/// Parse a slash command from a comment body.
///
/// Scans each line for a `/command` at the start, optionally prefixed by an
/// `@orch` or `@orchestrator` mention on the same line. Returns the first
/// valid command found. Unknown `/something` lines are skipped. Lines inside
/// markdown fenced code blocks (``` or ~~~) are ignored to prevent accidental
/// command execution from code examples. Per CommonMark, a backtick fence
/// closes only a backtick fence and a tilde fence closes only a tilde fence —
/// mismatched closers are ignored.
pub fn parse_command(body: &str) -> Option<OwnerCommand> {
    // Track the opening fence (character, length) so mismatched or shorter
    // closers are ignored. Per CommonMark: a backtick fence closes only a
    // backtick fence, a tilde fence closes only a tilde fence, and the closing
    // fence must be at least as long as the opening fence.
    let mut fence_state: Option<(char, usize)> = None;
    for line in body.lines() {
        let trimmed = line.trim();
        let fence_ch = if trimmed.starts_with("```") {
            Some('`')
        } else if trimmed.starts_with("~~~") {
            Some('~')
        } else {
            None
        };
        if let Some(ch) = fence_ch {
            let run_len = trimmed.chars().take_while(|&c| c == ch).count();
            match fence_state {
                None => fence_state = Some((ch, run_len)),
                Some((c, len)) if c == ch && run_len >= len => fence_state = None,
                Some(_) => {} // mismatched closer or shorter — ignore
            }
            continue;
        }
        if fence_state.is_some() {
            continue;
        }
        let command_text = trimmed
            .strip_prefix("@orchestrator")
            .or_else(|| trimmed.strip_prefix("@orch"))
            .map(str::trim_start)
            .unwrap_or(trimmed);

        if !command_text.starts_with('/') {
            continue;
        }
        let parts: Vec<&str> = command_text.splitn(2, char::is_whitespace).collect();
        let cmd = parts[0];
        let args = parts
            .get(1)
            .map(|s| s.trim())
            .filter(|s| !s.is_empty())
            .map(String::from);

        match cmd {
            "/retry" => return Some(OwnerCommand::Retry),
            "/reroute" => return Some(OwnerCommand::Reroute(args)),
            "/close" => return Some(OwnerCommand::Close),
            "/block" => return Some(OwnerCommand::Block(args)),
            "/unblock" => return Some(OwnerCommand::Unblock),
            "/review" => return Some(OwnerCommand::Review),
            _ => continue,
        }
    }
    None
}

/// Reset all attempt/failure counters for a task. Fire-and-forget — errors are
/// logged as warnings but not returned so `/retry` and `/reroute` still succeed.
async fn cmd_reset_counters(store: &Option<Arc<dyn CommandStoreOps>>, repo: &str, task_id: &str) {
    let Some(ref s) = store else { return };
    match s.resolve_task_id(repo, task_id).await {
        Ok(Some(id)) => {
            if let Err(e) = s.reset_counters(id).await {
                tracing::warn!(task_id, err = %e, "store reset_counters failed");
            }
        }
        Ok(None) => {} // task not in store — no-op is expected
        Err(e) => {
            tracing::warn!(task_id, err = %e, "resolve_task_id failed in store write helper");
        }
    }
}

/// Execute a single owner command against a task.
pub async fn execute_command(
    backend: &Arc<dyn ExternalBackend>,
    gh: &GhHttp,
    repo: &str,
    task_id: &ExternalId,
    command: &OwnerCommand,
    store: &Option<Arc<dyn CommandStoreOps>>,
    task_manager: &Arc<crate::engine::tasks::TaskManager>,
) -> anyhow::Result<String> {
    match command {
        OwnerCommand::Retry => {
            // Remove agent labels, reset attempts and all failure counters, reset to new
            let task = backend.get_task(task_id).await?;
            for label in &task.labels {
                if label.starts_with("agent:") {
                    backend.remove_label(task_id, label).await?;
                }
            }
            // Reset store state (attempts + all failure counters) so the task starts fresh
            cmd_reset_counters(store, repo, &task_id.0).await;
            task_manager
                .update_task_status(task_id, Status::New)
                .await?;
            Ok("`/retry` — reset attempts, cleared agent, reset to `status:new`".to_string())
        }

        OwnerCommand::Reroute(agent) => {
            // Remove existing agent labels and reset attempts and all failure counters
            let task = backend.get_task(task_id).await?;
            for label in &task.labels {
                if label.starts_with("agent:") {
                    backend.remove_label(task_id, label).await?;
                }
            }
            // Reset store state (attempts + all failure counters) so the task starts fresh
            cmd_reset_counters(store, repo, &task_id.0).await;
            // Optionally set new agent
            if let Some(agent_name) = agent {
                let label = format!("agent:{agent_name}");
                backend.set_labels(task_id, &[label]).await?;
            }
            task_manager
                .update_task_status(task_id, Status::New)
                .await?;
            match agent {
                Some(a) => Ok(format!(
                    "`/reroute {a}` — cleared agent, reset attempts, forced `agent:{a}`, reset to `status:new`"
                )),
                None => {
                    Ok("`/reroute` — cleared agent, reset attempts, reset to `status:new`, will re-route".into())
                }
            }
        }

        OwnerCommand::Close => {
            task_manager
                .update_task_status(task_id, Status::Done)
                .await?;
            gh.close_issue(repo, &task_id.0).await?;
            Ok("`/close` — marked `status:done` and closed issue".to_string())
        }

        OwnerCommand::Block(reason) => {
            if let Some(ref store) = store {
                let store_id = store.resolve_task_id(repo, &task_id.0).await?;
                if let Some(store_id) = store_id {
                    store.set_block_reason(store_id, reason.as_deref()).await?;
                }
            }
            task_manager
                .update_task_status(task_id, Status::Blocked)
                .await?;
            match reason {
                Some(r) => Ok(format!("`/block` — marked `status:blocked`: {r}")),
                None => Ok("`/block` — marked `status:blocked`".to_string()),
            }
        }

        OwnerCommand::Unblock => {
            if let Some(ref store) = store {
                let store_id = store.resolve_task_id(repo, &task_id.0).await?;
                if let Some(store_id) = store_id {
                    store.set_block_reason(store_id, None).await?;
                }
            }
            task_manager
                .update_task_status(task_id, Status::New)
                .await?;
            Ok("`/unblock` — marked `status:new`, will re-dispatch".to_string())
        }

        OwnerCommand::Review => {
            task_manager
                .update_task_status(task_id, Status::NeedsReview)
                .await?;
            Ok(
                "`/review` — set `status:needs_review`, review agent will pick up on next tick"
                    .to_string(),
            )
        }
    }
}

/// Result of attempting to validate and run a slash command.
///
/// Variants that successfully fetched issue data include `is_pr` so callers
/// don't need a second `get_issue` call.
pub enum CommandOutcome {
    /// Command executed successfully or failed — either way, it was handled.
    Executed { is_pr: bool },
    /// Issue/PR is not open — command was skipped.
    NotOpen { is_pr: bool },
    /// Author is not a collaborator — command was skipped.
    NotCollaborator { is_pr: bool },
    /// Failed to fetch issue state — should retry.
    FetchFailed,
    /// Failed to check collaborator status — should retry.
    CollaboratorCheckFailed,
}

/// Validate a slash command (issue open, author is collaborator) and execute it.
///
/// Shared by both `scan_commands` (issue comments) and `scan_mentions` (mention
/// handling). Posts a confirmation or error comment on the issue/PR.
#[allow(clippy::too_many_arguments)]
pub async fn validate_and_run_command(
    backend: &Arc<dyn ExternalBackend>,
    gh: &GhHttp,
    repo: &str,
    issue_number: &str,
    command: &OwnerCommand,
    author: &str,
    store: &Option<Arc<dyn CommandStoreOps>>,
    task_manager: &Arc<crate::engine::tasks::TaskManager>,
) -> CommandOutcome {
    // Check issue state
    let issue_data = match gh.get_issue(repo, issue_number).await {
        Ok(data) => data,
        Err(e) => {
            tracing::warn!(issue = %issue_number, err = %e, "failed to check issue state");
            return CommandOutcome::FetchFailed;
        }
    };

    let is_pr = issue_data.pull_request.is_some();

    if issue_data.state != "open" {
        tracing::debug!(issue = %issue_number, state = %issue_data.state, command = %command, "ignoring slash command on non-open issue");
        return CommandOutcome::NotOpen { is_pr };
    }

    // Check collaborator status
    match gh.is_collaborator(repo, author).await {
        Ok(true) => {}
        Ok(false) => {
            tracing::info!(author, command = %command, issue = %issue_number, "ignoring slash command from non-collaborator");
            return CommandOutcome::NotCollaborator { is_pr };
        }
        Err(e) => {
            tracing::warn!(author, err = %e, "failed to check collaborator status");
            return CommandOutcome::CollaboratorCheckFailed;
        }
    }

    // Execute and post result
    let task_id = ExternalId(issue_number.to_string());
    let now = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string();

    match execute_command(backend, gh, repo, &task_id, command, store, task_manager).await {
        Ok(msg) => {
            tracing::info!(issue = %issue_number, author, command = %command, "executed command");
            let confirmation = format!(
                "[{now}] {msg} — executed by @{author}{}",
                crate::engine::orch_footer()
            );
            if let Err(e) = backend.post_comment(&task_id, &confirmation).await {
                tracing::warn!(issue = %issue_number, err = %e, "failed to post confirmation");
            }
        }
        Err(e) => {
            tracing::warn!(issue = %issue_number, command = %command, err = %e, "failed to execute command");
            let error_msg = format!(
                "[{now}] Failed to execute `{command}`: {e}{}",
                crate::engine::orch_footer()
            );
            if let Err(e2) = backend.post_comment(&task_id, &error_msg).await {
                tracing::warn!(issue = %issue_number, err = %e2, "failed to post error comment");
            }
        }
    }

    CommandOutcome::Executed { is_pr }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::backends::{ExternalBackend, ExternalId, ExternalTask, Mention, Status};
    use crate::store::{NewTask, TaskStore};
    use async_trait::async_trait;
    use std::sync::Arc;

    struct MockBackend {
        task: ExternalTask,
        fail_remove_label: bool,
    }

    impl MockBackend {
        fn new(id: &str) -> Self {
            Self {
                task: ExternalTask {
                    id: ExternalId(id.to_string()),
                    title: "Task".to_string(),
                    body: "".to_string(),
                    state: "open".to_string(),
                    labels: vec![],
                    author: "bot".to_string(),
                    created_at: "2026-01-01T00:00:00Z".to_string(),
                    updated_at: "2026-01-01T00:00:00Z".to_string(),
                    url: "".to_string(),
                },
                fail_remove_label: false,
            }
        }

        fn with_labels(id: &str, labels: Vec<String>) -> Self {
            let mut b = Self::new(id);
            b.task.labels = labels;
            b
        }

        fn failing_remove_label(id: &str, labels: Vec<String>) -> Self {
            let mut b = Self::with_labels(id, labels);
            b.fail_remove_label = true;
            b
        }
    }

    #[async_trait]
    impl ExternalBackend for MockBackend {
        fn name(&self) -> &str {
            "mock"
        }

        async fn create_task(
            &self,
            _title: &str,
            _body: &str,
            _labels: &[String],
        ) -> anyhow::Result<ExternalId> {
            Ok(self.task.id.clone())
        }

        async fn get_task(&self, _id: &ExternalId) -> anyhow::Result<ExternalTask> {
            Ok(self.task.clone())
        }

        async fn list_by_status(&self, _status: Status) -> anyhow::Result<Vec<ExternalTask>> {
            Ok(vec![])
        }

        async fn list_routable(&self) -> anyhow::Result<Vec<ExternalTask>> {
            Ok(vec![])
        }

        async fn post_comment(&self, _id: &ExternalId, _body: &str) -> anyhow::Result<()> {
            Ok(())
        }

        async fn set_labels(&self, _id: &ExternalId, _labels: &[String]) -> anyhow::Result<()> {
            Ok(())
        }

        async fn remove_label(&self, _id: &ExternalId, label: &str) -> anyhow::Result<()> {
            if self.fail_remove_label {
                anyhow::bail!("simulated remove_label failure for {label}");
            }
            Ok(())
        }

        async fn get_sub_issues(&self, _id: &ExternalId) -> anyhow::Result<Vec<ExternalId>> {
            Ok(vec![])
        }

        async fn create_sub_task(
            &self,
            _parent: &ExternalId,
            _title: &str,
            _body: &str,
            _labels: &[String],
        ) -> anyhow::Result<ExternalId> {
            Ok(ExternalId("child".to_string()))
        }

        async fn ensure_status_label(&self, _label: &str) -> anyhow::Result<()> {
            Ok(())
        }

        async fn has_open_issue_with_title(
            &self,
            _title: &str,
            _label: &str,
        ) -> anyhow::Result<bool> {
            Ok(false)
        }

        async fn health_check(&self) -> anyhow::Result<()> {
            Ok(())
        }

        async fn is_pr_merged(&self, _branch: &str) -> anyhow::Result<bool> {
            Ok(false)
        }

        async fn get_authenticated_user(&self) -> anyhow::Result<Option<String>> {
            Ok(Some("testbot".to_string()))
        }

        async fn get_mentions(&self, _since: &str) -> anyhow::Result<Vec<Mention>> {
            Ok(vec![])
        }

        async fn update_status(&self, _id: &ExternalId, _status: Status) -> anyhow::Result<()> {
            Ok(())
        }
    }

    /// Mock store whose `resolve_task_id` always returns an error.
    struct FailingStore;

    #[async_trait]
    impl CommandStoreOps for FailingStore {
        async fn resolve_task_id(
            &self,
            _repo: &str,
            _task_id: &str,
        ) -> anyhow::Result<Option<i64>> {
            anyhow::bail!("simulated resolve_task_id DB failure")
        }

        async fn set_block_reason(&self, _id: i64, _reason: Option<&str>) -> anyhow::Result<()> {
            anyhow::bail!("simulated set_block_reason DB failure")
        }

        async fn reset_counters(&self, _id: i64) -> anyhow::Result<()> {
            Ok(())
        }
    }

    #[tokio::test]
    async fn block_command_persists_reason_and_unblock_clears_it() {
        let store = Arc::new(TaskStore::open_memory().await.unwrap());
        let store_id = store
            .create(&NewTask {
                external_id: Some("42".to_string()),
                repo: "owner/repo".to_string(),
                origin: "github".to_string(),
                title: "Task".to_string(),
                body: "".to_string(),
                source: "manual".to_string(),
                source_id: "".to_string(),
                author: "bot".to_string(),
                url: "".to_string(),
                labels: vec![],
                parent_id: None,
            })
            .await
            .unwrap();
        let backend: Arc<dyn ExternalBackend> = Arc::new(MockBackend::new("42"));
        let backend_for_call = backend.clone();
        let task_manager = Arc::new(crate::engine::tasks::TaskManager::with_store(
            backend,
            store.clone(),
            "owner/repo".to_string(),
        ));
        let gh = crate::github::http::GhHttp::new().unwrap();
        let task_id = ExternalId("42".to_string());

        execute_command(
            &backend_for_call,
            &gh,
            "owner/repo",
            &task_id,
            &OwnerCommand::Block(Some("waiting on upstream fix".to_string())),
            &Some(Arc::clone(&store) as Arc<dyn CommandStoreOps>),
            &task_manager,
        )
        .await
        .unwrap();

        let task = store.get(store_id).await.unwrap();
        assert_eq!(task.status, crate::store::TaskStatus::Blocked);
        assert_eq!(
            task.block_reason.as_deref(),
            Some("waiting on upstream fix")
        );

        execute_command(
            &backend_for_call,
            &gh,
            "owner/repo",
            &task_id,
            &OwnerCommand::Unblock,
            &Some(Arc::clone(&store) as Arc<dyn CommandStoreOps>),
            &task_manager,
        )
        .await
        .unwrap();

        let task = store.get(store_id).await.unwrap();
        assert_eq!(task.status, crate::store::TaskStatus::New);
        assert!(task.block_reason.is_none());
    }

    #[test]
    fn parse_retry() {
        assert_eq!(parse_command("/retry"), Some(OwnerCommand::Retry));
    }

    #[test]
    fn parse_retry_with_trailing_whitespace() {
        assert_eq!(parse_command("/retry   "), Some(OwnerCommand::Retry));
    }

    #[test]
    fn parse_close() {
        assert_eq!(parse_command("/close"), Some(OwnerCommand::Close));
    }

    #[test]
    fn parse_unblock() {
        assert_eq!(parse_command("/unblock"), Some(OwnerCommand::Unblock));
    }

    #[test]
    fn parse_review() {
        assert_eq!(parse_command("/review"), Some(OwnerCommand::Review));
    }

    #[test]
    fn parse_reroute_no_agent() {
        assert_eq!(parse_command("/reroute"), Some(OwnerCommand::Reroute(None)));
    }

    #[test]
    fn parse_reroute_with_agent() {
        assert_eq!(
            parse_command("/reroute codex"),
            Some(OwnerCommand::Reroute(Some("codex".into())))
        );
    }

    #[test]
    fn parse_block_no_reason() {
        assert_eq!(parse_command("/block"), Some(OwnerCommand::Block(None)));
    }

    #[test]
    fn parse_block_with_reason() {
        assert_eq!(
            parse_command("/block waiting on upstream fix"),
            Some(OwnerCommand::Block(Some("waiting on upstream fix".into())))
        );
    }

    #[test]
    fn parse_ignores_non_command_text() {
        assert_eq!(parse_command("This is a regular comment"), None);
    }

    #[test]
    fn parse_ignores_unknown_commands() {
        assert_eq!(parse_command("/unknown"), None);
    }

    #[test]
    fn parse_command_in_multiline_body() {
        let body = "Some context here\n\n/retry\n\nMore text";
        assert_eq!(parse_command(body), Some(OwnerCommand::Retry));
    }

    #[test]
    fn parse_first_valid_command_wins() {
        let body = "/retry\n/close";
        assert_eq!(parse_command(body), Some(OwnerCommand::Retry));
    }

    #[test]
    fn parse_skips_unknown_finds_valid() {
        let body = "/unknown\n/close";
        assert_eq!(parse_command(body), Some(OwnerCommand::Close));
    }

    #[test]
    fn parse_indented_command() {
        // Commands with leading whitespace should still be detected
        assert_eq!(parse_command("  /retry"), Some(OwnerCommand::Retry));
    }

    #[test]
    fn parse_mention_prefixed_command() {
        assert_eq!(parse_command("@orch /retry"), Some(OwnerCommand::Retry));
    }

    #[test]
    fn parse_legacy_mention_prefixed_command() {
        assert_eq!(
            parse_command("@orchestrator /close"),
            Some(OwnerCommand::Close)
        );
    }

    #[test]
    fn parse_ignores_non_command_after_mention() {
        assert_eq!(parse_command("@orch please retry this"), None);
    }

    #[test]
    fn parse_ignores_command_in_code_fence() {
        let body = "Some context\n```\n/retry\n```\nMore text";
        assert_eq!(parse_command(body), None);
    }

    #[test]
    fn parse_ignores_mention_prefixed_command_in_code_fence() {
        let body = "```\n@orch /retry\n```";
        assert_eq!(parse_command(body), None);
    }

    #[test]
    fn parse_ignores_command_in_tilde_fence() {
        let body = "Some context\n~~~\n/close\n~~~\nMore text";
        assert_eq!(parse_command(body), None);
    }

    #[test]
    fn parse_finds_command_after_code_fence() {
        let body = "```\n/retry\n```\n/close";
        assert_eq!(parse_command(body), Some(OwnerCommand::Close));
    }

    #[test]
    fn parse_ignores_command_in_code_fence_with_lang() {
        let body = "```markdown\n/retry\n```";
        assert_eq!(parse_command(body), None);
    }

    #[test]
    fn parse_mixed_fence_does_not_close_backtick_with_tilde() {
        // ~~~ should NOT close a ``` fence — /retry is still inside the fence
        let body = "```bash\n/retry\n~~~\n/retry\n```";
        assert_eq!(parse_command(body), None);
    }

    #[test]
    fn parse_mixed_fence_does_not_close_tilde_with_backtick() {
        // ``` should NOT close a ~~~ fence — /close is still inside the fence
        let body = "~~~\n/close\n```\n/close\n~~~";
        assert_eq!(parse_command(body), None);
    }

    #[test]
    fn parse_command_after_mixed_fence_properly_closed() {
        // Fence opened with ``` and closed with ``` (tilde in between is ignored)
        // Command after the real closing fence should be found
        let body = "```\n/retry\n~~~\n/retry\n```\n/close";
        assert_eq!(parse_command(body), Some(OwnerCommand::Close));
    }

    #[tokio::test]
    async fn retry_propagates_remove_label_error() {
        let backend: Arc<dyn ExternalBackend> = Arc::new(MockBackend::failing_remove_label(
            "42",
            vec!["agent:claude".to_string()],
        ));
        let store = Arc::new(TaskStore::open_memory().await.unwrap());
        let task_manager = Arc::new(crate::engine::tasks::TaskManager::with_store(
            backend.clone(),
            store.clone(),
            "owner/repo".to_string(),
        ));
        let gh = crate::github::http::GhHttp::new().unwrap();
        let task_id = ExternalId("42".to_string());

        let result = execute_command(
            &backend,
            &gh,
            "owner/repo",
            &task_id,
            &OwnerCommand::Retry,
            &Some(store as Arc<dyn CommandStoreOps>),
            &task_manager,
        )
        .await;

        assert!(result.is_err(), "/retry must fail when remove_label fails");
        assert!(
            result.unwrap_err().to_string().contains("remove_label"),
            "error must mention remove_label"
        );
    }

    #[tokio::test]
    async fn reroute_propagates_remove_label_error() {
        let backend: Arc<dyn ExternalBackend> = Arc::new(MockBackend::failing_remove_label(
            "42",
            vec!["agent:codex".to_string()],
        ));
        let store = Arc::new(TaskStore::open_memory().await.unwrap());
        let task_manager = Arc::new(crate::engine::tasks::TaskManager::with_store(
            backend.clone(),
            store.clone(),
            "owner/repo".to_string(),
        ));
        let gh = crate::github::http::GhHttp::new().unwrap();
        let task_id = ExternalId("42".to_string());

        let result = execute_command(
            &backend,
            &gh,
            "owner/repo",
            &task_id,
            &OwnerCommand::Reroute(None),
            &Some(store as Arc<dyn CommandStoreOps>),
            &task_manager,
        )
        .await;

        assert!(
            result.is_err(),
            "/reroute must fail when remove_label fails"
        );
        assert!(
            result.unwrap_err().to_string().contains("remove_label"),
            "error must mention remove_label"
        );
    }

    #[tokio::test]
    async fn block_propagates_resolve_task_id_error() {
        let backend: Arc<dyn ExternalBackend> = Arc::new(MockBackend::new("42"));
        let store = Arc::new(TaskStore::open_memory().await.unwrap());
        let task_manager = Arc::new(crate::engine::tasks::TaskManager::with_store(
            backend.clone(),
            store,
            "owner/repo".to_string(),
        ));
        let gh = crate::github::http::GhHttp::new().unwrap();
        let task_id = ExternalId("42".to_string());
        let failing_store: Arc<dyn CommandStoreOps> = Arc::new(FailingStore);

        let result = execute_command(
            &backend,
            &gh,
            "owner/repo",
            &task_id,
            &OwnerCommand::Block(Some("reason".to_string())),
            &Some(failing_store),
            &task_manager,
        )
        .await;

        assert!(
            result.is_err(),
            "/block must fail when resolve_task_id fails"
        );
        assert!(
            result.unwrap_err().to_string().contains("resolve_task_id"),
            "error must mention resolve_task_id"
        );
    }

    #[tokio::test]
    async fn unblock_propagates_resolve_task_id_error() {
        let backend: Arc<dyn ExternalBackend> = Arc::new(MockBackend::new("42"));
        let store = Arc::new(TaskStore::open_memory().await.unwrap());
        let task_manager = Arc::new(crate::engine::tasks::TaskManager::with_store(
            backend.clone(),
            store,
            "owner/repo".to_string(),
        ));
        let gh = crate::github::http::GhHttp::new().unwrap();
        let task_id = ExternalId("42".to_string());
        let failing_store: Arc<dyn CommandStoreOps> = Arc::new(FailingStore);

        let result = execute_command(
            &backend,
            &gh,
            "owner/repo",
            &task_id,
            &OwnerCommand::Unblock,
            &Some(failing_store),
            &task_manager,
        )
        .await;

        assert!(
            result.is_err(),
            "/unblock must fail when resolve_task_id fails"
        );
        assert!(
            result.unwrap_err().to_string().contains("resolve_task_id"),
            "error must mention resolve_task_id"
        );
    }

    #[test]
    fn parse_shorter_backtick_does_not_close_longer_backtick_fence() {
        // ```` opens a 4-backtick fence; ``` (3 backticks) must NOT close it
        let body = "````\n/retry\n```\n/retry\n````";
        assert_eq!(parse_command(body), None);
    }

    #[test]
    fn parse_longer_backtick_closes_shorter_backtick_fence() {
        // ``` opens a 3-backtick fence; ```` (4 backticks) IS allowed to close it
        let body = "```\n/retry\n````\n/close";
        assert_eq!(parse_command(body), Some(OwnerCommand::Close));
    }

    #[test]
    fn parse_shorter_tilde_does_not_close_longer_tilde_fence() {
        // ~~~~ opens a 4-tilde fence; ~~~ (3 tildes) must NOT close it
        let body = "~~~~\n/close\n~~~\n/close\n~~~~";
        assert_eq!(parse_command(body), None);
    }

    #[test]
    fn parse_longer_tilde_closes_shorter_tilde_fence() {
        // ~~~ opens a 3-tilde fence; ~~~~ (4 tildes) IS allowed to close it
        let body = "~~~\n/close\n~~~~\n/retry";
        assert_eq!(parse_command(body), Some(OwnerCommand::Retry));
    }

    #[test]
    fn parse_command_after_longer_backtick_fence_properly_closed() {
        // ```` fence closed with ```` — command after should be found
        let body = "````markdown\n/retry\n```\n/retry\n````\n/close";
        assert_eq!(parse_command(body), Some(OwnerCommand::Close));
    }

    #[test]
    fn display_commands() {
        assert_eq!(OwnerCommand::Retry.to_string(), "/retry");
        assert_eq!(
            OwnerCommand::Reroute(Some("codex".into())).to_string(),
            "/reroute codex"
        );
        assert_eq!(OwnerCommand::Reroute(None).to_string(), "/reroute");
        assert_eq!(OwnerCommand::Close.to_string(), "/close");
        assert_eq!(
            OwnerCommand::Block(Some("reason".into())).to_string(),
            "/block reason"
        );
        assert_eq!(OwnerCommand::Block(None).to_string(), "/block");
        assert_eq!(OwnerCommand::Unblock.to_string(), "/unblock");
        assert_eq!(OwnerCommand::Review.to_string(), "/review");
    }
}