orch-cli 0.88.4

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
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
//! GitHub Issues backend — native HTTP via `reqwest` with connection pooling.
//!
//! Auth is resolved once at startup using the centralized [`TokenResolver`]
//! (`GH_TOKEN` → `GITHUB_TOKEN` environment variables by default).

use super::{ExternalBackend, ExternalId, ExternalTask, Mention, Status};
use crate::github::http::{status_label_color, GhHttp};
use crate::github::projects::label_status::LabelSyncConfig;
use crate::github::projects::ProjectSync;
use async_trait::async_trait;
use chrono::{Duration, Utc};

/// Author associations that are allowed to create tasks.
/// Only repository OWNER or COLLABORATOR authors are considered trusted for
/// ingestion. Other associations (members, collaborators, first-time
/// contributors, etc.) are ignored per the new sync policy.
/// Available values: COLLABORATOR, CONTRIBUTOR, FIRST_TIMER, FIRST_TIME_CONTRIBUTOR, MANNEQUIN, MEMBER, NONE, OWNER
const ALLOWED_ASSOCIATIONS: &[&str] = &["OWNER", "COLLABORATOR"];

/// Check if an issue author is trusted
fn is_trusted_author(issue: &crate::github::types::GitHubIssue) -> bool {
    issue
        .author_association
        .as_deref()
        .map(|a| ALLOWED_ASSOCIATIONS.contains(&a))
        .unwrap_or(false) // missing field = untrusted
}

// Check if a comment's author is trusted. The
// GitHub REST comment payload includes an `author_association` field, so
// prefer that when present. Missing association is treated as untrusted.
fn is_trusted_comment_author(c: &crate::github::types::GitHubComment) -> bool {
    c.author_association
        .as_deref()
        .map(|a| ALLOWED_ASSOCIATIONS.contains(&a))
        .unwrap_or(false)
}

fn active_status_from_label(label: &str) -> Option<Status> {
    match label {
        "status:routed" => Some(Status::Routed),
        "status:in_progress" => Some(Status::InProgress),
        "status:needs_review" => Some(Status::NeedsReview),
        "status:in_review" => Some(Status::InReview),
        "status:blocked" => Some(Status::Blocked),
        _ => None,
    }
}

fn classify_active_open_issue(
    issue: crate::github::types::GitHubIssue,
) -> Option<(ExternalTask, Option<Status>)> {
    // Guard: open issues tagged as done should never be re-ingested as new.
    if issue.labels.iter().any(|l| l.name == "status:done") {
        return None;
    }

    let status = issue
        .labels
        .iter()
        .find_map(|l| active_status_from_label(&l.name));
    let task = ExternalTask {
        id: ExternalId(issue.number.to_string()),
        title: issue.title,
        body: issue.body.unwrap_or_default(),
        state: issue.state,
        labels: issue.labels.into_iter().map(|l| l.name).collect(),
        author: issue.user.login,
        created_at: issue.created_at,
        updated_at: issue.updated_at,
        url: issue.html_url,
    };
    Some((task, status))
}

pub struct GitHubBackend {
    repo: String,
    gh: GhHttp,
}

/// Returns `true` if `id` is a valid GitHub issue number (positive integer).
///
/// Internal tasks use IDs like `"internal:63857"` which are not valid GitHub
/// issue numbers. Backend methods that call the GitHub API must skip these IDs
/// to avoid spurious 404 errors.
fn is_github_issue_id(id: &ExternalId) -> bool {
    id.0.parse::<u64>().is_ok()
}

impl GitHubBackend {
    pub fn new(repo: String) -> anyhow::Result<Self> {
        Ok(Self {
            repo,
            gh: GhHttp::new()?,
        })
    }

    async fn sync_project_status(
        &self,
        project: &ProjectSync,
        node_id: &str,
        status: &Status,
    ) -> anyhow::Result<()> {
        if LabelSyncConfig::from_config()?.manages(&self.repo, project.project_id()) {
            // Preserve existing ingestion membership behavior. The reconciler
            // owns the field value and reads the current labels on the next sync.
            project.add_item(node_id).await?;
            Ok(())
        } else {
            project.sync_item_status(node_id, status).await
        }
    }
}

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

    async fn create_task(
        &self,
        title: &str,
        body: &str,
        labels: &[String],
    ) -> anyhow::Result<ExternalId> {
        let issue = self
            .gh
            .create_issue(&self.repo, title, body, labels)
            .await?;
        Ok(ExternalId(issue.number.to_string()))
    }

    async fn get_task(&self, id: &ExternalId) -> anyhow::Result<ExternalTask> {
        let issue = self.gh.get_issue(&self.repo, &id.0).await?;
        Ok(ExternalTask {
            id: id.clone(),
            title: issue.title,
            body: issue.body.unwrap_or_default(),
            state: issue.state,
            labels: issue.labels.into_iter().map(|l| l.name).collect(),
            author: issue.user.login,
            created_at: issue.created_at,
            updated_at: issue.updated_at,
            url: issue.html_url,
        })
    }

    // update_status uses the default trait implementation (retry loop with
    // get_task → remove_label → set_labels). Only ensure_status_label is
    // overridden to auto-create labels on the GitHub repo.

    async fn ensure_status_label(&self, label: &str) -> anyhow::Result<()> {
        let status_name = &label["status:".len()..];
        self.gh
            .ensure_label(
                &self.repo,
                label,
                status_label_color(label),
                &format!("Task status: {status_name}"),
            )
            .await
    }

    /// Sync a task to the GitHub Project board (if configured).
    ///
    /// Called when a task is first ingested to ensure it appears on the
    /// project board immediately, not just when status changes later.
    /// Returns `Some(node_id)` if the item was added to the project board.
    async fn sync_to_project(
        &self,
        id: &ExternalId,
        status: Status,
    ) -> anyhow::Result<Option<String>> {
        // Only sync if project integration is configured
        let project = match ProjectSync::from_config() {
            Some(p) => p,
            None => return Ok(None),
        };

        // Fetch the issue to get its node_id
        let issue = self.gh.get_issue(&self.repo, &id.0).await?;

        // Get the node_id (required for project board operations)
        let node_id = issue
            .node_id
            .as_deref()
            .ok_or_else(|| anyhow::anyhow!("issue missing node_id"))?
            .to_string();

        // Add to project board and set initial status
        self.sync_project_status(&project, &node_id, &status)
            .await
            .map_err(|e| anyhow::anyhow!("project board sync failed: {e}"))?;

        Ok(Some(node_id))
    }

    async fn reconcile_project_statuses(&self) -> anyhow::Result<()> {
        LabelSyncConfig::from_config()?
            .reconcile(&self.gh, &self.repo)
            .await
            .map(|_| ())
    }

    async fn sync_estimate_to_project(&self, id: &ExternalId, estimate: u8) -> anyhow::Result<()> {
        let project = match ProjectSync::from_config() {
            Some(p) => p,
            None => return Ok(()),
        };

        // If the estimate field ID is missing from config, try to discover it
        // automatically and persist it for future calls. This handles the case
        // where the service was set up before the estimate sync feature existed.
        let project = if project.estimate_field_id().is_none() {
            match ProjectSync::discover_fields(project.project_id()).await {
                Ok(discovered) => {
                    if discovered.estimate_field_id().is_some() {
                        if let Err(e) =
                            crate::github::projects::write_project_config(&discovered).await
                        {
                            tracing::warn!(
                                err = %e,
                                "failed to persist discovered estimate field ID to config"
                            );
                        } else {
                            tracing::info!(
                                "auto-discovered and persisted project_estimate_field_id to config"
                            );
                        }
                        discovered
                    } else {
                        tracing::debug!(
                            "project has no 'Estimate' number field — skipping estimate sync"
                        );
                        return Ok(());
                    }
                }
                Err(e) => {
                    tracing::debug!(
                        err = %e,
                        "estimate field auto-discovery failed — skipping estimate sync"
                    );
                    return Ok(());
                }
            }
        } else {
            project
        };

        // Fetch the issue to get its node_id.
        let issue = self.gh.get_issue(&self.repo, &id.0).await?;
        let node_id = issue
            .node_id
            .as_deref()
            .ok_or_else(|| anyhow::anyhow!("issue missing node_id"))?;

        project
            .sync_item_estimate(node_id, estimate)
            .await
            .map_err(|e| anyhow::anyhow!("project estimate sync failed: {e}"))?;

        Ok(())
    }

    async fn get_project_item_estimates(
        &self,
        issue_node_ids: &[String],
    ) -> anyhow::Result<std::collections::HashMap<String, u8>> {
        let project = match ProjectSync::from_config() {
            Some(p) => p,
            None => return Ok(std::collections::HashMap::new()),
        };

        if issue_node_ids.is_empty() {
            return Ok(std::collections::HashMap::new());
        }

        project
            .get_estimates_for_issues(issue_node_ids)
            .await
            .map_err(|e| anyhow::anyhow!("project estimate fetch failed: {e}"))
    }

    /// Override default update_status to add project board sync after label update.
    async fn update_status(&self, id: &ExternalId, status: Status) -> anyhow::Result<()> {
        // Internal tasks (e.g. "internal:63857") are not GitHub issues — skip silently.
        if !is_github_issue_id(id) {
            return Ok(());
        }

        // Run the standard label-based status update (default trait impl logic)
        let label = status.as_label();

        if let Err(e) = self.ensure_status_label(label).await {
            tracing::warn!(label, err = %e, "ensure_status_label failed, continuing");
        }

        const MAX_RETRIES: u32 = 3;
        let mut last_err =
            anyhow::anyhow!("update_status({label}) failed: all {MAX_RETRIES} attempts exhausted");

        let mut issue_node_id: Option<String> = None;

        for attempt in 0..MAX_RETRIES {
            if attempt > 0 {
                tokio::time::sleep(std::time::Duration::from_millis(500 * u64::from(attempt)))
                    .await;
                tracing::debug!(attempt, label, "retrying update_status");
            }

            let issue = match self.gh.get_issue(&self.repo, &id.0).await {
                Ok(i) => i,
                Err(e) => {
                    last_err = e;
                    continue;
                }
            };

            // Capture node_id for project sync
            if issue_node_id.is_none() {
                issue_node_id = issue.node_id.clone();
            }

            let labels: Vec<String> = issue.labels.iter().map(|l| l.name.clone()).collect();

            let mut remove_failed = false;
            for old in labels
                .iter()
                .filter(|l| l.starts_with("status:") && l.as_str() != label)
            {
                if let Err(e) = self.remove_label(id, old).await {
                    tracing::warn!(old_label = %old, err = %e, attempt, "remove_label failed");
                    last_err = e;
                    remove_failed = true;
                    break;
                }
            }
            if remove_failed {
                continue;
            }

            match self.set_labels(id, &[label.to_string()]).await {
                Ok(()) => {
                    // Label update succeeded — now sync project board (non-fatal)
                    if let Some(ref node_id) = issue_node_id {
                        if let Some(project) = ProjectSync::from_config() {
                            if let Err(e) =
                                self.sync_project_status(&project, node_id, &status).await
                            {
                                tracing::warn!(
                                    task_id = id.0,
                                    err = %e,
                                    "project board sync failed (non-fatal)"
                                );
                            }
                        }
                    }

                    // Auto-close issue when status → Done (if auto_close enabled)
                    if status == Status::Done {
                        let auto_close = crate::config::get("workflow.auto_close")
                            .map(|v| v == "true")
                            .unwrap_or(true);
                        if auto_close {
                            if let Err(e) = self.gh.close_issue(&self.repo, &id.0).await {
                                tracing::warn!(
                                    task_id = id.0,
                                    err = %e,
                                    "auto-close issue failed (non-fatal)"
                                );
                            }
                        }
                    }

                    return Ok(());
                }
                Err(e) => {
                    tracing::warn!(label, err = %e, attempt, "set_labels failed");
                    last_err = e;
                }
            }
        }

        Err(last_err.context(format!(
            "update_status({label}) failed after {MAX_RETRIES} attempts"
        )))
    }

    async fn list_by_status(&self, status: Status) -> anyhow::Result<Vec<ExternalTask>> {
        // Done issues are auto-closed by the engine, so we must query state=all
        // to find them. All other statuses only live on open issues.
        let state = if status == Status::Done {
            "all"
        } else {
            "open"
        };
        let issues = self
            .gh
            .list_issues_with_state(&self.repo, status.as_label(), state)
            .await?;
        Ok(issues
            .into_iter()
            .filter(|issue| issue.pull_request.is_none()) // Exclude PRs
            .filter(is_trusted_author) // Only trusted authors
            .map(|issue| ExternalTask {
                id: ExternalId(issue.number.to_string()),
                title: issue.title,
                body: issue.body.unwrap_or_default(),
                state: issue.state,
                labels: issue.labels.into_iter().map(|l| l.name).collect(),
                author: issue.user.login,
                created_at: issue.created_at,
                updated_at: issue.updated_at,
                url: issue.html_url,
            })
            .collect())
    }

    /// List all tasks (open and closed) in a single API call.
    ///
    /// This fetches all issues with state=all and filters by status labels locally.
    /// More efficient than making 7 separate calls to `list_by_status`.
    async fn list_all_tasks(&self) -> anyhow::Result<Vec<ExternalTask>> {
        let issues = self.gh.list_all_issues(&self.repo).await?;
        Ok(issues
            .into_iter()
            .filter(|issue| issue.pull_request.is_none()) // Exclude PRs
            .filter(is_trusted_author) // Only trusted authors
            .map(|issue| ExternalTask {
                id: ExternalId(issue.number.to_string()),
                title: issue.title,
                body: issue.body.unwrap_or_default(),
                state: issue.state,
                labels: issue.labels.into_iter().map(|l| l.name).collect(),
                author: issue.user.login,
                created_at: issue.created_at,
                updated_at: issue.updated_at,
                url: issue.html_url,
            })
            .collect())
    }

    async fn list_reconciliation_candidates(&self) -> anyhow::Result<Vec<ExternalTask>> {
        let since = (Utc::now() - Duration::days(30)).to_rfc3339();
        let closed = self.gh.list_closed_issues_since(&self.repo, &since).await?;

        Ok(closed
            .into_iter()
            .filter(|issue| issue.pull_request.is_none()) // Exclude PRs
            .filter(is_trusted_author) // Only trusted authors
            .map(|issue| ExternalTask {
                id: ExternalId(issue.number.to_string()),
                title: issue.title,
                body: issue.body.unwrap_or_default(),
                state: issue.state,
                labels: issue.labels.into_iter().map(|l| l.name).collect(),
                author: issue.user.login,
                created_at: issue.created_at,
                updated_at: issue.updated_at,
                url: issue.html_url,
            })
            .collect())
    }

    /// List open issues that have no `status:*` label (unprocessed) or have `status:new`.
    async fn list_routable(&self) -> anyhow::Result<Vec<ExternalTask>> {
        let issues = self.gh.list_all_open_issues(&self.repo, None).await?;
        Ok(issues
            .into_iter()
            .filter(|issue| issue.pull_request.is_none()) // Exclude PRs
            .filter(is_trusted_author) // Only trusted authors
            .filter(|issue| {
                let labels: Vec<&str> = issue.labels.iter().map(|l| l.name.as_str()).collect();
                // Include if: has status:new, OR has no status:* label at all
                let has_status = labels.iter().any(|l| l.starts_with("status:"));
                !has_status || labels.contains(&"status:new")
            })
            .map(|issue| ExternalTask {
                id: ExternalId(issue.number.to_string()),
                title: issue.title,
                body: issue.body.unwrap_or_default(),
                state: issue.state,
                labels: issue.labels.into_iter().map(|l| l.name).collect(),
                author: issue.user.login,
                created_at: issue.created_at,
                updated_at: issue.updated_at,
                url: issue.html_url,
            })
            .collect())
    }

    /// Single-call override: fetches all open issues once and partitions by status label locally,
    /// replacing the 1 (list_routable) + 5 (list_by_status per active status) fan-out with a
    /// single `list_all_open_issues` request.
    /// When `since` is `Some(ts)`, uses GitHub's `?since` filter for efficiency.
    async fn list_active_open_issues(
        &self,
        since: Option<&str>,
    ) -> anyhow::Result<Vec<(ExternalTask, Option<crate::backends::Status>)>> {
        let issues = self.gh.list_all_open_issues(&self.repo, since).await?;

        Ok(issues
            .into_iter()
            .filter(|issue| issue.pull_request.is_none()) // Exclude PRs
            .filter(is_trusted_author) // Only trusted authors
            .filter_map(classify_active_open_issue)
            .collect())
    }

    async fn post_comment(&self, id: &ExternalId, body: &str) -> anyhow::Result<()> {
        // Internal tasks (e.g. "internal:63857") are not GitHub issues — skip silently.
        if !is_github_issue_id(id) {
            return Ok(());
        }
        self.gh.add_comment(&self.repo, &id.0, body).await
    }

    /// Additive: uses POST (gh.add_labels), so existing labels like bug, priority:high are preserved.
    async fn set_labels(&self, id: &ExternalId, labels: &[String]) -> anyhow::Result<()> {
        // Internal tasks (e.g. "internal:63857") are not GitHub issues — skip silently.
        if !is_github_issue_id(id) {
            return Ok(());
        }
        self.gh.add_labels(&self.repo, &id.0, labels).await
    }

    async fn remove_label(&self, id: &ExternalId, label: &str) -> anyhow::Result<()> {
        // Internal tasks (e.g. "internal:63857") are not GitHub issues — skip silently.
        if !is_github_issue_id(id) {
            return Ok(());
        }
        self.gh.remove_label(&self.repo, &id.0, label).await
    }

    async fn get_sub_issues(&self, id: &ExternalId) -> anyhow::Result<Vec<ExternalId>> {
        let sub_issue_numbers = self.gh.get_sub_issues(&self.repo, &id.0).await?;
        Ok(sub_issue_numbers
            .into_iter()
            .map(|n| ExternalId(n.to_string()))
            .collect())
    }

    async fn create_sub_task(
        &self,
        parent_id: &ExternalId,
        title: &str,
        body: &str,
        labels: &[String],
    ) -> anyhow::Result<ExternalId> {
        // Add parent label for metadata
        let mut all_labels = labels.to_vec();
        all_labels.push(format!("parent:{}", parent_id.0));

        // Create the child issue
        let child_issue = self
            .gh
            .create_issue(&self.repo, title, body, &all_labels)
            .await?;

        let child_id = ExternalId(child_issue.number.to_string());

        // Try to establish native sub-issue relationship via GraphQL
        if let (Some(child_node_id), Ok(parent_issue)) = (
            child_issue.node_id,
            self.gh.get_issue(&self.repo, &parent_id.0).await,
        ) {
            if let Some(parent_node_id) = parent_issue.node_id {
                if let Err(e) = self.gh.add_sub_issue(&parent_node_id, &child_node_id).await {
                    tracing::warn!(
                        parent = parent_id.0,
                        child = child_id.0,
                        err = %e,
                        "failed to add native sub-issue link (parent label still set)"
                    );
                }
            }
        }

        Ok(child_id)
    }

    async fn has_open_issue_with_title(&self, title: &str, label: &str) -> anyhow::Result<bool> {
        // Check open issues first
        let open_issues = if label.is_empty() {
            self.gh.list_all_open_issues(&self.repo, None).await?
        } else {
            self.gh.list_issues(&self.repo, label).await?
        };
        if open_issues.iter().any(|i| i.title == title) {
            return Ok(true);
        }
        // Also check issues closed within the last 24h — prevents re-creating a bug
        // that was just fixed and merged (the PR close event removes the open issue).
        let since = (chrono::Utc::now() - chrono::Duration::hours(24))
            .format("%Y-%m-%dT%H:%M:%SZ")
            .to_string();
        let closed = if label.is_empty() {
            self.gh.list_closed_issues_since(&self.repo, &since).await?
        } else {
            self.gh
                .list_issues_closed_since(&self.repo, label, &since)
                .await?
        };
        Ok(closed.iter().any(|i| i.title == title))
    }

    async fn health_check(&self) -> anyhow::Result<()> {
        self.gh.auth_status().await
    }

    async fn is_pr_merged(&self, branch: &str) -> anyhow::Result<bool> {
        self.gh.is_pr_merged(&self.repo, branch).await
    }

    async fn batch_is_pr_merged(
        &self,
        branches: &[String],
    ) -> anyhow::Result<std::collections::HashMap<String, bool>> {
        self.gh
            .batch_is_pr_merged_by_branch(&self.repo, branches)
            .await
    }

    async fn get_authenticated_user(&self) -> anyhow::Result<Option<String>> {
        self.gh.get_whoami().await.map(Some)
    }

    async fn get_mentions(&self, since: &str) -> anyhow::Result<Vec<Mention>> {
        let comments = self.gh.get_mentions(&self.repo, since).await?;
        // Only include mentions authored by trusted associations. The GitHub
        // REST issue comment payload does not include author_association, so
        // we conservatively check the parent issue's author_association when
        // an issue_url is available. If we cannot resolve association, skip
        // the comment.
        let mut out = Vec::new();
        for c in comments.into_iter() {
            // Prefer the comment's own author_association when present. If the
            // comment payload doesn't include it (older endpoints), fall back to
            // inspecting the parent issue's association when an issue_url is
            // available. If neither yields a trusted association, skip the
            // comment.
            let trusted = if is_trusted_comment_author(&c) {
                true
            } else if let Some(ref issue_url) = c.issue_url {
                // extract issue number and fetch issue to inspect author_association
                if let Some(n) = issue_url.rsplit('/').next() {
                    if let Ok(issue) = self.gh.get_issue(&self.repo, n).await {
                        is_trusted_author(&issue)
                    } else {
                        tracing::warn!(
                            repo = %self.repo,
                            issue_url = %issue_url,
                            comment_id = c.id,
                            author = %c.user.login,
                            "get_mentions: failed to fetch parent issue to check author trust, treating as untrusted — mention may be silently dropped"
                        );
                        false
                    }
                } else {
                    false
                }
            } else {
                false
            };

            if !trusted {
                tracing::debug!(comment_id = c.id, author = %c.user.login, "ignoring mention from untrusted author");
                continue;
            }

            out.push(Mention {
                id: c.id.to_string(),
                body: c.body,
                author: c.user.login,
                created_at: c.created_at,
                issue_url: c.issue_url,
            });
        }

        Ok(out)
    }

    async fn list_issue_comments(&self, id: &ExternalId) -> anyhow::Result<Vec<Mention>> {
        let issue_number: u64 =
            id.0.parse()
                .map_err(|_| anyhow::anyhow!("invalid issue number: {}", id.0))?;
        let comments = self.gh.get_issue_comments(&self.repo, issue_number).await?;
        // Filter comments to only include those from trusted associations.
        let mut out = Vec::new();
        for c in comments.into_iter() {
            // Prefer the comment's own association when present.
            if is_trusted_comment_author(&c) {
                out.push(Mention {
                    id: c.id.to_string(),
                    body: c.body,
                    author: c.user.login,
                    created_at: c.created_at,
                    issue_url: c.issue_url,
                });
                continue;
            }

            // Fall back to parent issue association when necessary.
            if let Ok(issue) = self.gh.get_issue(&self.repo, &id.0).await {
                if is_trusted_author(&issue) {
                    out.push(Mention {
                        id: c.id.to_string(),
                        body: c.body,
                        author: c.user.login,
                        created_at: c.created_at,
                        issue_url: c.issue_url,
                    });
                    continue;
                } else {
                    tracing::debug!(comment_id = c.id, author = %c.user.login, "ignoring issue comment from untrusted author");
                    continue;
                }
            } else {
                // If we cannot fetch the issue, skip the comment conservatively
                tracing::debug!(
                    comment_id = c.id,
                    "failed to fetch parent issue, skipping comment"
                );
                continue;
            }
        }

        Ok(out)
    }

    async fn acknowledge_issue(&self, id: &ExternalId) -> anyhow::Result<()> {
        self.gh.add_reaction(&self.repo, &id.0, "eyes").await
    }

    async fn acknowledge_mention(&self, comment_id: &str) -> anyhow::Result<()> {
        self.gh
            .add_comment_reaction(&self.repo, comment_id, "eyes")
            .await
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::github::types::{GitHubIssue, GitHubUser};

    // --- is_github_issue_id guard ---

    #[test]
    fn is_github_issue_id_numeric() {
        assert!(is_github_issue_id(&ExternalId("42".to_string())));
        assert!(is_github_issue_id(&ExternalId("1".to_string())));
        assert!(is_github_issue_id(&ExternalId("99999".to_string())));
    }

    #[test]
    fn is_github_issue_id_rejects_internal_prefix() {
        assert!(!is_github_issue_id(&ExternalId(
            "internal:63857".to_string()
        )));
        assert!(!is_github_issue_id(&ExternalId("internal:1".to_string())));
    }

    #[test]
    fn is_github_issue_id_rejects_empty_and_non_numeric() {
        assert!(!is_github_issue_id(&ExternalId("".to_string())));
        assert!(!is_github_issue_id(&ExternalId("abc".to_string())));
        assert!(!is_github_issue_id(&ExternalId("1.0".to_string())));
    }

    // ---

    #[test]
    fn allowed_associations_are_owner_and_contributor() {
        assert_eq!(ALLOWED_ASSOCIATIONS, &["OWNER", "COLLABORATOR"]);
    }

    #[test]
    fn is_trusted_author_owner() {
        let issue = GitHubIssue {
            number: 1,
            title: "t".to_string(),
            body: None,
            state: "open".to_string(),
            labels: vec![],
            user: GitHubUser {
                login: "u".to_string(),
            },
            created_at: "".to_string(),
            updated_at: "".to_string(),
            html_url: "".to_string(),
            node_id: None,
            pull_request: None,
            author_association: Some("OWNER".to_string()),
        };
        assert!(is_trusted_author(&issue));
    }

    #[test]
    fn is_trusted_author_collaborator() {
        let issue = GitHubIssue {
            number: 1,
            title: "t".to_string(),
            body: None,
            state: "open".to_string(),
            labels: vec![],
            user: GitHubUser {
                login: "u".to_string(),
            },
            created_at: "".to_string(),
            updated_at: "".to_string(),
            html_url: "".to_string(),
            node_id: None,
            pull_request: None,
            author_association: Some("COLLABORATOR".to_string()),
        };
        assert!(is_trusted_author(&issue));
    }

    #[test]
    fn is_not_trusted_author_contributor() {
        let issue = GitHubIssue {
            number: 1,
            title: "t".to_string(),
            body: None,
            state: "open".to_string(),
            labels: vec![],
            user: GitHubUser {
                login: "u".to_string(),
            },
            created_at: "".to_string(),
            updated_at: "".to_string(),
            html_url: "".to_string(),
            node_id: None,
            pull_request: None,
            author_association: Some("CONTRIBUTOR".to_string()),
        };
        assert!(!is_trusted_author(&issue));
    }

    #[test]
    fn is_not_trusted_author_member() {
        let issue = GitHubIssue {
            number: 1,
            title: "t".to_string(),
            body: None,
            state: "open".to_string(),
            labels: vec![],
            user: GitHubUser {
                login: "u".to_string(),
            },
            created_at: "".to_string(),
            updated_at: "".to_string(),
            html_url: "".to_string(),
            node_id: None,
            pull_request: None,
            author_association: Some("MEMBER".to_string()),
        };
        assert!(!is_trusted_author(&issue));
    }

    #[test]
    fn is_trusted_comment_author_direct() {
        use crate::github::types::GitHubComment;
        let c = GitHubComment {
            id: 1,
            body: "hi".to_string(),
            user: crate::github::types::GitHubUser {
                login: "u".to_string(),
            },
            created_at: "".to_string(),
            updated_at: None,
            html_url: None,
            issue_url: None,
            author_association: Some("OWNER".to_string()),
        };
        assert!(is_trusted_comment_author(&c));
    }

    #[test]
    fn is_not_trusted_comment_author_direct() {
        use crate::github::types::GitHubComment;
        let c = GitHubComment {
            id: 1,
            body: "hi".to_string(),
            user: crate::github::types::GitHubUser {
                login: "u".to_string(),
            },
            created_at: "".to_string(),
            updated_at: None,
            html_url: None,
            issue_url: None,
            author_association: Some("MEMBER".to_string()),
        };
        assert!(!is_trusted_comment_author(&c));
    }

    fn make_test_issue(labels: &[&str]) -> GitHubIssue {
        GitHubIssue {
            number: 1,
            title: "t".to_string(),
            body: None,
            state: "open".to_string(),
            labels: labels
                .iter()
                .map(|label| crate::github::types::GitHubLabel {
                    name: (*label).to_string(),
                    color: None,
                })
                .collect(),
            user: GitHubUser {
                login: "u".to_string(),
            },
            created_at: "".to_string(),
            updated_at: "".to_string(),
            html_url: "".to_string(),
            node_id: None,
            pull_request: None,
            author_association: Some("OWNER".to_string()),
        }
    }

    /// Open issues carrying `status:done` must be excluded from active-open ingest.
    #[test]
    fn classify_active_open_issue_excludes_status_done() {
        assert!(classify_active_open_issue(make_test_issue(&["status:done"])).is_none());
        assert!(
            classify_active_open_issue(make_test_issue(&["status:routed", "status:done"]))
                .is_none()
        );
    }

    #[test]
    fn classify_active_open_issue_preserves_unlabeled_and_new_as_none_status() {
        let unlabeled = classify_active_open_issue(make_test_issue(&[]))
            .expect("unlabeled issue should still be ingested");
        assert_eq!(unlabeled.1, None);

        let status_new = classify_active_open_issue(make_test_issue(&["status:new"]))
            .expect("status:new issue should still be ingested");
        assert_eq!(status_new.1, None);
    }

    #[test]
    fn classify_active_open_issue_maps_active_status() {
        let routed = classify_active_open_issue(make_test_issue(&["status:routed"]))
            .expect("active status issue should be ingested");
        assert_eq!(routed.1, Some(Status::Routed));
    }
}