Skip to main content

orch/backends/
github.rs

1//! GitHub Issues backend — native HTTP via `reqwest` with connection pooling.
2//!
3//! Auth is resolved once at startup using the centralized [`TokenResolver`]
4//! (`GH_TOKEN` → `GITHUB_TOKEN` environment variables by default).
5
6use std::collections::HashMap;
7use std::time as std_time;
8
9use super::{ExternalId, ExternalTask, Mention, Status};
10
11use super::{Conversation, MergeState, TaskReader, TaskWriter, Tracker};
12use crate::backends;
13use crate::backends::BlockedByFetch;
14use crate::backends::PullRequestCompletion;
15use crate::config;
16use crate::github::app;
17use crate::github::http::{GhHttp, has_status, status_label_color};
18use crate::github::projects::ProjectSync;
19use crate::github::projects::label_status::LabelSyncConfig;
20use crate::github::types::GitHubComment;
21use crate::github::types::GitHubIssue;
22use crate::github::types::GitHubReview;
23use async_trait::async_trait;
24use chrono::{Duration, Utc};
25use tokio::time;
26
27/// Author associations that are allowed to create tasks.
28/// Only repository OWNER or COLLABORATOR authors are considered trusted for
29/// ingestion. Other associations (members, collaborators, first-time
30/// contributors, etc.) are ignored per the new sync policy.
31/// Available values: COLLABORATOR, CONTRIBUTOR, FIRST_TIMER, FIRST_TIME_CONTRIBUTOR, MANNEQUIN, MEMBER, NONE, OWNER
32// MEMBER is a member of the organization that owns the repo, as the operator is after a
33// transfer to an org. Without it every new issue and comment there was dropped
34const ALLOWED_ASSOCIATIONS: &[&str] = &["OWNER", "MEMBER", "COLLABORATOR"];
35
36/// Check if an issue author is trusted
37fn is_trusted_author(issue: &GitHubIssue) -> bool {
38    issue
39        .author_association
40        .as_deref()
41        .is_some_and(|a| ALLOWED_ASSOCIATIONS.contains(&a)) // missing field = untrusted
42}
43
44fn is_trusted_comment_author(c: &GitHubComment) -> bool {
45    c.author_association
46        .as_deref()
47        .is_some_and(|a| ALLOWED_ASSOCIATIONS.contains(&a))
48}
49
50fn trusted_mentions(comments: impl IntoIterator<Item = GitHubComment>) -> Vec<Mention> {
51    comments
52        .into_iter()
53        .filter_map(|c| {
54            if !is_trusted_comment_author(&c) {
55                tracing::debug!(
56                    comment_id = c.id,
57                    author = %c.user.login,
58                    "ignoring comment from untrusted author"
59                );
60                return None;
61            }
62            Some(Mention {
63                id: c.id.to_string(),
64                body: c.body,
65                author: c.user.login,
66                created_at: c.created_at,
67                issue_url: c.issue_url,
68            })
69        })
70        .collect()
71}
72
73fn active_status_from_label(label: &str) -> Option<Status> {
74    match label {
75        "status:routed" => Some(Status::Routed),
76        "status:in_progress" => Some(Status::InProgress),
77        "status:needs_review" => Some(Status::NeedsReview),
78        "status:in_review" => Some(Status::InReview),
79        "status:approved" => Some(Status::Approved),
80        "status:blocked" => Some(Status::Blocked),
81        "status:waiting" => Some(Status::Waiting),
82        _ => None,
83    }
84}
85
86fn classify_active_open_issue(issue: GitHubIssue) -> Option<(ExternalTask, Option<Status>)> {
87    // Guard: open issues tagged as done should never be re-ingested as new.
88    if issue.labels.iter().any(|l| l.name == "status:done") {
89        return None;
90    }
91
92    let status = issue
93        .labels
94        .iter()
95        .find_map(|l| active_status_from_label(&l.name));
96    let task = ExternalTask {
97        id: ExternalId(issue.number.to_string()),
98        title: issue.title,
99        body: issue.body.unwrap_or_default(),
100        state: issue.state,
101        labels: issue.labels.into_iter().map(|l| l.name).collect(),
102        author: issue.user.login,
103        created_at: issue.created_at,
104        updated_at: issue.updated_at,
105        url: issue.html_url,
106    };
107    Some((task, status))
108}
109
110// The filters `list_active_open_issues` applies, plus the open state the list endpoint implies
111fn classify_single_open_issue(issue: GitHubIssue) -> Option<(ExternalTask, Option<Status>)> {
112    if issue.state != "open" || issue.pull_request.is_some() || !is_trusted_author(&issue) {
113        return None;
114    }
115
116    classify_active_open_issue(issue)
117}
118
119#[derive(Debug)]
120pub struct GitHubBackend {
121    repo: String,
122    gh: GhHttp,
123}
124
125/// Returns `true` if `id` is a valid GitHub issue number (positive integer).
126///
127/// Internal tasks use IDs like `"internal:63857"` which are not valid GitHub
128/// issue numbers. Backend methods that call the GitHub API must skip these IDs
129/// to avoid spurious 404 errors.
130fn is_github_issue_id(id: &ExternalId) -> bool {
131    id.0.parse::<u64>().is_ok()
132}
133
134impl GitHubBackend {
135    pub fn new(repo: String) -> anyhow::Result<Self> {
136        Ok(Self {
137            repo,
138            gh: GhHttp::new()?,
139        })
140    }
141
142    #[cfg(test)]
143    fn for_test(repo: impl Into<String>, gh: GhHttp) -> Self {
144        Self {
145            repo: repo.into(),
146            gh,
147        }
148    }
149
150    async fn sync_project_status(
151        &self,
152        project: &ProjectSync,
153        node_id: &str,
154        status: &Status,
155    ) -> anyhow::Result<()> {
156        project
157            .sync_status(&self.repo, node_id, status.board_column())
158            .await
159    }
160}
161
162#[async_trait]
163impl TaskReader for GitHubBackend {
164    async fn get_task(&self, id: &ExternalId) -> anyhow::Result<ExternalTask> {
165        let issue = self.gh.get_issue(&self.repo, &id.0).await?;
166        Ok(ExternalTask {
167            id: id.clone(),
168            title: issue.title,
169            body: issue.body.unwrap_or_default(),
170            state: issue.state,
171            labels: issue.labels.into_iter().map(|l| l.name).collect(),
172            author: issue.user.login,
173            created_at: issue.created_at,
174            updated_at: issue.updated_at,
175            url: issue.html_url,
176        })
177    }
178
179    async fn list_by_status(&self, status: Status) -> anyhow::Result<Vec<ExternalTask>> {
180        // Done issues are auto-closed by the engine, so we must query state=all
181        // to find them. All other statuses only live on open issues.
182        let state = if status == Status::Done {
183            "all"
184        } else {
185            "open"
186        };
187        let issues = self
188            .gh
189            .list_issues_with_state(&self.repo, status.as_label(), state)
190            .await?;
191        Ok(issues
192            .into_iter()
193            .filter(|issue| issue.pull_request.is_none()) // Exclude PRs
194            .filter(is_trusted_author) // Only trusted authors
195            .map(|issue| ExternalTask {
196                id: ExternalId(issue.number.to_string()),
197                title: issue.title,
198                body: issue.body.unwrap_or_default(),
199                state: issue.state,
200                labels: issue.labels.into_iter().map(|l| l.name).collect(),
201                author: issue.user.login,
202                created_at: issue.created_at,
203                updated_at: issue.updated_at,
204                url: issue.html_url,
205            })
206            .collect())
207    }
208
209    /// List all tasks (open and closed) in a single API call.
210    ///
211    /// This fetches all issues with state=all and filters by status labels locally.
212    /// More efficient than making 7 separate calls to `list_by_status`.
213    async fn list_all_tasks(&self) -> anyhow::Result<Vec<ExternalTask>> {
214        let issues = self.gh.list_all_issues(&self.repo).await?;
215        Ok(issues
216            .into_iter()
217            .filter(|issue| issue.pull_request.is_none()) // Exclude PRs
218            .filter(is_trusted_author) // Only trusted authors
219            .map(|issue| ExternalTask {
220                id: ExternalId(issue.number.to_string()),
221                title: issue.title,
222                body: issue.body.unwrap_or_default(),
223                state: issue.state,
224                labels: issue.labels.into_iter().map(|l| l.name).collect(),
225                author: issue.user.login,
226                created_at: issue.created_at,
227                updated_at: issue.updated_at,
228                url: issue.html_url,
229            })
230            .collect())
231    }
232
233    async fn list_reconciliation_candidates(&self) -> anyhow::Result<Vec<ExternalTask>> {
234        let since = (Utc::now() - Duration::days(30)).to_rfc3339();
235        let closed = self.gh.list_closed_issues_since(&self.repo, &since).await?;
236
237        Ok(closed
238            .into_iter()
239            .filter(|issue| issue.pull_request.is_none()) // Exclude PRs
240            .filter(is_trusted_author) // Only trusted authors
241            .map(|issue| ExternalTask {
242                id: ExternalId(issue.number.to_string()),
243                title: issue.title,
244                body: issue.body.unwrap_or_default(),
245                state: issue.state,
246                labels: issue.labels.into_iter().map(|l| l.name).collect(),
247                author: issue.user.login,
248                created_at: issue.created_at,
249                updated_at: issue.updated_at,
250                url: issue.html_url,
251            })
252            .collect())
253    }
254
255    /// List open issues that have no `status:*` label (unprocessed) or have `status:new`.
256    async fn list_routable(&self) -> anyhow::Result<Vec<ExternalTask>> {
257        let issues = self.gh.list_all_open_issues(&self.repo).await?;
258        Ok(issues
259            .into_iter()
260            .filter(|issue| issue.pull_request.is_none()) // Exclude PRs
261            .filter(is_trusted_author) // Only trusted authors
262            .filter(|issue| {
263                let labels: Vec<&str> = issue.labels.iter().map(|l| l.name.as_str()).collect();
264                // Include if: has status:new, OR has no status:* label at all
265                let has_status = labels.iter().any(|l| l.starts_with("status:"));
266                !has_status || labels.contains(&"status:new")
267            })
268            .map(|issue| ExternalTask {
269                id: ExternalId(issue.number.to_string()),
270                title: issue.title,
271                body: issue.body.unwrap_or_default(),
272                state: issue.state,
273                labels: issue.labels.into_iter().map(|l| l.name).collect(),
274                author: issue.user.login,
275                created_at: issue.created_at,
276                updated_at: issue.updated_at,
277                url: issue.html_url,
278            })
279            .collect())
280    }
281
282    /// Single-call override: fetches all open issues once and partitions by status label locally,
283    /// replacing the 1 (list_routable) + 5 (list_by_status per active status) fan-out with a
284    /// single `list_all_open_issues` request.
285    async fn list_active_open_issues(
286        &self,
287    ) -> anyhow::Result<Vec<(ExternalTask, Option<backends::Status>)>> {
288        let issues = self.gh.list_all_open_issues(&self.repo).await?;
289
290        Ok(issues
291            .into_iter()
292            .filter(|issue| issue.pull_request.is_none()) // Exclude PRs
293            .filter(is_trusted_author) // Only trusted authors
294            .filter_map(classify_active_open_issue)
295            .collect())
296    }
297
298    /// The single-issue endpoint, which is current when the list of open issues lags behind
299    async fn get_active_open_issue(
300        &self,
301        id: &ExternalId,
302    ) -> anyhow::Result<Option<(ExternalTask, Option<backends::Status>)>> {
303        if !is_github_issue_id(id) {
304            return Ok(None);
305        }
306
307        let issue = self.gh.get_issue(&self.repo, &id.0).await?;
308        Ok(classify_single_open_issue(issue))
309    }
310
311    async fn has_open_issue_with_title(&self, title: &str, label: &str) -> anyhow::Result<bool> {
312        // Check open issues first
313        let open_issues = if label.is_empty() {
314            self.gh.list_all_open_issues(&self.repo).await?
315        } else {
316            self.gh.list_issues(&self.repo, label).await?
317        };
318        if open_issues.iter().any(|i| i.title == title) {
319            return Ok(true);
320        }
321        // Also check issues closed within the last 24h — prevents re-creating a bug
322        // that was just fixed and merged (the PR close event removes the open issue).
323        let since = (chrono::Utc::now() - chrono::Duration::hours(24))
324            .format("%Y-%m-%dT%H:%M:%SZ")
325            .to_string();
326        let closed = if label.is_empty() {
327            self.gh.list_closed_issues_since(&self.repo, &since).await?
328        } else {
329            self.gh
330                .list_issues_closed_since(&self.repo, label, &since)
331                .await?
332        };
333        Ok(closed.iter().any(|i| i.title == title))
334    }
335}
336
337#[async_trait]
338impl TaskWriter for GitHubBackend {
339    async fn create_task(
340        &self,
341        title: &str,
342        body: &str,
343        labels: &[String],
344    ) -> anyhow::Result<ExternalId> {
345        let issue = self
346            .gh
347            .create_issue(&self.repo, title, body, labels)
348            .await?;
349        Ok(ExternalId(issue.number.to_string()))
350    }
351
352    async fn ensure_status_label(&self, label: &str) -> anyhow::Result<()> {
353        let status_name = &label["status:".len()..];
354        self.gh
355            .ensure_label(
356                &self.repo,
357                label,
358                status_label_color(label),
359                &format!("Task status: {status_name}"),
360            )
361            .await
362    }
363
364    /// Override default update_status to add project board sync after label update.
365    async fn update_status(&self, id: &ExternalId, status: Status) -> anyhow::Result<()> {
366        const MAX_RETRIES: u32 = 3;
367        // Internal tasks (e.g. "internal:63857") are not GitHub issues — skip silently.
368        if !is_github_issue_id(id) {
369            return Ok(());
370        }
371
372        // Run the standard label-based status update (default trait impl logic)
373        let label = status.as_label();
374
375        if let Err(e) = self.ensure_status_label(label).await {
376            tracing::warn!(label, err = %e, "ensure_status_label failed, continuing");
377        }
378
379        let mut last_err =
380            anyhow::anyhow!("update_status({label}) failed: all {MAX_RETRIES} attempts exhausted");
381
382        let mut issue_node_id: Option<String> = None;
383
384        for attempt in 0..MAX_RETRIES {
385            if attempt > 0 {
386                time::sleep(std_time::Duration::from_millis(500 * u64::from(attempt))).await;
387                tracing::debug!(attempt, label, "retrying update_status");
388            }
389
390            let issue = match self.gh.get_issue(&self.repo, &id.0).await {
391                Ok(i) => i,
392                Err(e) => {
393                    last_err = e;
394                    continue;
395                }
396            };
397
398            // Capture node_id for project sync
399            if issue_node_id.is_none() {
400                issue_node_id = issue.node_id.clone();
401            }
402
403            let labels: Vec<String> = issue.labels.iter().map(|l| l.name.clone()).collect();
404
405            let mut remove_failed = false;
406            for old in labels
407                .iter()
408                .filter(|l| l.starts_with("status:") && l.as_str() != label)
409            {
410                if let Err(e) = self.remove_label(id, old).await {
411                    tracing::warn!(old_label = %old, err = %e, attempt, "remove_label failed");
412                    last_err = e;
413                    remove_failed = true;
414                    break;
415                }
416            }
417            if remove_failed {
418                continue;
419            }
420
421            match self.set_labels(id, &[label.to_string()]).await {
422                Ok(()) => {
423                    // Label update succeeded — now sync project board (non-fatal)
424                    if let Some(ref node_id) = issue_node_id
425                        && let Some(project) = ProjectSync::from_config()
426                        && let Err(e) = self.sync_project_status(&project, node_id, &status).await
427                    {
428                        tracing::warn!(
429                            task_id = id.0,
430                            err = %e,
431                            "project board sync failed (non-fatal)"
432                        );
433                    }
434
435                    // Auto-close issue when status → Done (if auto_close enabled)
436                    if status == Status::Done {
437                        let auto_close =
438                            config::get("workflow.auto_close").map_or(true, |v| v == "true");
439                        if auto_close && let Err(e) = self.gh.close_issue(&self.repo, &id.0).await {
440                            tracing::warn!(
441                                task_id = id.0,
442                                err = %e,
443                                "auto-close issue failed (non-fatal)"
444                            );
445                        }
446                    }
447
448                    return Ok(());
449                }
450                Err(e) => {
451                    tracing::warn!(label, err = %e, attempt, "set_labels failed");
452                    last_err = e;
453                }
454            }
455        }
456
457        Err(last_err.context(format!(
458            "update_status({label}) failed after {MAX_RETRIES} attempts"
459        )))
460    }
461
462    /// Additive: uses POST (gh.add_labels), so existing labels like bug, priority:high are preserved.
463    async fn set_labels(&self, id: &ExternalId, labels: &[String]) -> anyhow::Result<()> {
464        // Internal tasks (e.g. "internal:63857") are not GitHub issues — skip silently.
465        if !is_github_issue_id(id) {
466            return Ok(());
467        }
468        self.gh.add_labels(&self.repo, &id.0, labels).await
469    }
470
471    async fn remove_label(&self, id: &ExternalId, label: &str) -> anyhow::Result<()> {
472        // Internal tasks (e.g. "internal:63857") are not GitHub issues — skip silently.
473        if !is_github_issue_id(id) {
474            return Ok(());
475        }
476        self.gh.remove_label(&self.repo, &id.0, label).await
477    }
478
479    async fn get_sub_issues(&self, id: &ExternalId) -> anyhow::Result<Vec<ExternalId>> {
480        let sub_issue_numbers = self.gh.get_sub_issues(&self.repo, &id.0).await?;
481        Ok(sub_issue_numbers
482            .into_iter()
483            .map(|n| ExternalId(n.to_string()))
484            .collect())
485    }
486
487    async fn create_sub_task(
488        &self,
489        parent_id: &ExternalId,
490        title: &str,
491        body: &str,
492        labels: &[String],
493    ) -> anyhow::Result<ExternalId> {
494        // Add parent label for metadata
495        let mut all_labels = labels.to_vec();
496        all_labels.push(format!("parent:{}", parent_id.0));
497
498        // Create the child issue
499        let child_issue = self
500            .gh
501            .create_issue(&self.repo, title, body, &all_labels)
502            .await?;
503
504        let child_id = ExternalId(child_issue.number.to_string());
505
506        // Try to establish native sub-issue relationship via GraphQL
507        if let (Some(child_node_id), Ok(parent_issue)) = (
508            child_issue.node_id,
509            self.gh.get_issue(&self.repo, &parent_id.0).await,
510        ) && let Some(parent_node_id) = parent_issue.node_id
511            && let Err(e) = self.gh.add_sub_issue(&parent_node_id, &child_node_id).await
512        {
513            tracing::warn!(
514                parent = parent_id.0,
515                child = child_id.0,
516                err = %e,
517                "failed to add native sub-issue link (parent label still set)"
518            );
519        }
520
521        Ok(child_id)
522    }
523}
524
525#[async_trait]
526impl Conversation for GitHubBackend {
527    async fn post_comment(&self, id: &ExternalId, body: &str) -> anyhow::Result<()> {
528        // Internal tasks (e.g. "internal:63857") are not GitHub issues — skip silently.
529        if !is_github_issue_id(id) {
530            return Ok(());
531        }
532        self.gh.add_comment(&self.repo, &id.0, body).await
533    }
534
535    async fn get_authenticated_user(&self) -> anyhow::Result<Option<String>> {
536        self.gh.get_whoami().await.map(Some)
537    }
538
539    async fn get_mentions(&self, since: &str) -> anyhow::Result<Vec<Mention>> {
540        let comments = self.gh.get_mentions(&self.repo, since).await?;
541        Ok(trusted_mentions(comments))
542    }
543
544    async fn list_issue_comments(&self, id: &ExternalId) -> anyhow::Result<Vec<Mention>> {
545        let issue_number: u64 =
546            id.0.parse()
547                .map_err(|_| anyhow::anyhow!("invalid issue number: {}", id.0))?;
548        let comments = self.gh.get_issue_comments(&self.repo, issue_number).await?;
549        Ok(trusted_mentions(comments))
550    }
551
552    async fn acknowledge_issue(&self, id: &ExternalId) -> anyhow::Result<()> {
553        self.gh.add_reaction(&self.repo, &id.0, "eyes").await
554    }
555
556    async fn acknowledge_mention(&self, comment_id: &str) -> anyhow::Result<()> {
557        self.gh
558            .add_comment_reaction(&self.repo, comment_id, "eyes")
559            .await
560    }
561
562    async fn post_comment_in_repo(
563        &self,
564        repo: &str,
565        id: &ExternalId,
566        body: &str,
567    ) -> anyhow::Result<()> {
568        if !is_github_issue_id(id) {
569            return Ok(());
570        }
571        self.gh.add_comment(repo, &id.0, body).await
572    }
573}
574
575#[async_trait]
576impl MergeState for GitHubBackend {
577    async fn is_pr_merged(&self, branch: &str) -> anyhow::Result<bool> {
578        self.gh.is_pr_merged(&self.repo, branch).await
579    }
580
581    async fn batch_is_pr_merged(
582        &self,
583        branches: &[String],
584    ) -> anyhow::Result<HashMap<String, bool>> {
585        self.gh
586            .batch_is_pr_merged_by_branch(&self.repo, branches)
587            .await
588    }
589
590    async fn blocked_by(&self, repo: &str, issue_number: i64) -> anyhow::Result<BlockedByFetch> {
591        if issue_number <= 0 {
592            return Ok(BlockedByFetch::Unavailable);
593        }
594        self.gh
595            .list_blocked_by(repo, issue_number.cast_unsigned())
596            .await
597    }
598
599    async fn issue_close_state(
600        &self,
601        repo: &str,
602        issue_number: i64,
603    ) -> anyhow::Result<Option<(String, Option<String>)>> {
604        if issue_number <= 0 {
605            return Ok(None);
606        }
607        match self.gh.get_issue(repo, &issue_number.to_string()).await {
608            Ok(issue) => Ok(Some((issue.state, issue.state_reason))),
609            Err(err) if is_missing_issue(&err) => Ok(None),
610            Err(err) => Err(err),
611        }
612    }
613
614    async fn pull_request_completion(
615        &self,
616        repo: &str,
617        pr_number: i64,
618    ) -> anyhow::Result<Option<PullRequestCompletion>> {
619        if pr_number <= 0 {
620            return Ok(None);
621        }
622        let pr = match self.gh.get_pr(repo, pr_number.cast_unsigned()).await {
623            Ok(pr) => pr,
624            Err(err) if is_missing_issue(&err) => return Ok(None),
625            Err(err) => return Err(err),
626        };
627        let default_branch = self.gh.get_default_branch(repo).await.unwrap_or_default();
628        let app_login = app::bot_login().await;
629        let reviews = match self
630            .gh
631            .get_pr_reviews(repo, pr_number.cast_unsigned())
632            .await
633        {
634            Ok(reviews) => app::reviews_for_gate(&reviews, &pr.head.sha, app_login.as_deref()),
635            Err(err) => {
636                tracing::warn!(repo, pr_number, err = %err, "pull request reviews unreadable");
637                Vec::new()
638            }
639        };
640        let comments = match self.gh.list_comments(repo, &pr_number.to_string()).await {
641            Ok(comments) => comments,
642            Err(err) => {
643                tracing::warn!(repo, pr_number, err = %err, "pull request comments unreadable");
644                Vec::new()
645            }
646        };
647        let reviewer = match self.gh.get_whoami().await {
648            Ok(login) => Some(login),
649            Err(err) => {
650                tracing::warn!(repo, pr_number, err = %err, "reviewer login unreadable");
651                None
652            }
653        };
654        let comment_refs: Vec<AutomatedReviewComment<'_>> = comments
655            .iter()
656            .map(|comment| AutomatedReviewComment {
657                login: &comment.user.login,
658                body: &comment.body,
659                created_at: &comment.created_at,
660            })
661            .collect();
662        let comment_approved = reviewer
663            .iter()
664            .chain(app_login.iter())
665            .any(|login| latest_automated_review_approves(&comment_refs, login));
666        // An App review on the head replaces the comment, as in review_poll, so a stale
667        // approving comment cannot outvote an App change request
668        let (comment_approved, _) = app::effective_comment_flags(
669            &reviews,
670            &pr.head.sha,
671            app_login.as_deref(),
672            comment_approved,
673            false,
674        );
675        let merged = pr.merged.unwrap_or(false);
676        Ok(Some(PullRequestCompletion {
677            merged,
678            base_ref: pr.base.ref_,
679            default_branch,
680            approved: latest_review_approves(&reviews) || comment_approved,
681            closed: pr.state.eq_ignore_ascii_case("closed"),
682        }))
683    }
684
685    async fn add_dependency(
686        &self,
687        issue_number: i64,
688        blocking_repo: &str,
689        blocking_number: i64,
690    ) -> anyhow::Result<()> {
691        let blocker = self
692            .gh
693            .get_issue(blocking_repo, &blocking_number.to_string())
694            .await?;
695        if blocker.id == 0 {
696            anyhow::bail!("blocking issue {blocking_repo}#{blocking_number} has no database id");
697        }
698        self.gh
699            .add_blocked_by(
700                &self.repo,
701                issue_number.cast_unsigned(),
702                blocker.id.cast_signed(),
703            )
704            .await
705    }
706}
707
708#[async_trait]
709impl Tracker for GitHubBackend {
710    fn name(&self) -> &'static str {
711        "github"
712    }
713
714    /// Sync a task to the GitHub Project board (if configured).
715    ///
716    /// Called when a task is first ingested to ensure it appears on the
717    /// project board immediately, not just when status changes later.
718    /// Returns `Some(node_id)` if the item was added to the project board.
719    async fn sync_to_project(
720        &self,
721        id: &ExternalId,
722        status: Status,
723    ) -> anyhow::Result<Option<String>> {
724        // Only sync if project integration is configured
725        let Some(project) = ProjectSync::from_config() else {
726            return Ok(None);
727        };
728
729        // Fetch the issue to get its node_id
730        let issue = self.gh.get_issue(&self.repo, &id.0).await?;
731
732        // Get the node_id (required for project board operations)
733        let node_id = issue
734            .node_id
735            .as_deref()
736            .ok_or_else(|| anyhow::anyhow!("issue missing node_id"))?
737            .to_string();
738
739        // Add to project board and set initial status
740        self.sync_project_status(&project, &node_id, &status)
741            .await
742            .map_err(|e| anyhow::anyhow!("project board sync failed: {e}"))?;
743
744        Ok(Some(node_id))
745    }
746
747    async fn reconcile_project_statuses(&self) -> anyhow::Result<()> {
748        // Projects V2 on a personal account is out of reach for an installation token
749        LabelSyncConfig::from_config()?
750            .reconcile(&GhHttp::owner()?, &self.repo)
751            .await
752            .map(|_| ())
753    }
754
755    async fn sync_estimate_to_project(&self, id: &ExternalId, estimate: u8) -> anyhow::Result<()> {
756        let Some(project) = ProjectSync::from_config() else {
757            return Ok(());
758        };
759
760        let Some(project) = project.with_estimate_field().await else {
761            return Ok(());
762        };
763
764        // Fetch the issue to get its node_id.
765        let issue = self.gh.get_issue(&self.repo, &id.0).await?;
766        let node_id = issue
767            .node_id
768            .as_deref()
769            .ok_or_else(|| anyhow::anyhow!("issue missing node_id"))?;
770
771        project
772            .sync_item_estimate(node_id, estimate)
773            .await
774            .map_err(|e| anyhow::anyhow!("project estimate sync failed: {e}"))?;
775
776        Ok(())
777    }
778
779    async fn get_project_item_estimates(
780        &self,
781        issue_node_ids: &[String],
782    ) -> anyhow::Result<HashMap<String, u8>> {
783        let Some(project) = ProjectSync::from_config() else {
784            return Ok(HashMap::new());
785        };
786
787        if issue_node_ids.is_empty() {
788            return Ok(HashMap::new());
789        }
790
791        project
792            .get_estimates_for_issues(issue_node_ids)
793            .await
794            .map_err(|e| anyhow::anyhow!("project estimate fetch failed: {e}"))
795    }
796
797    async fn health_check(&self) -> anyhow::Result<()> {
798        self.gh.auth_status().await
799    }
800}
801
802fn is_missing_issue(err: &anyhow::Error) -> bool {
803    let text = err.to_string();
804    has_status(&text, 404) || text.contains("not found")
805}
806
807/// Latest substantive review wins. Comments and dismissed reviews are ignored.
808///
809/// `CHANGES_REQUESTED` after `APPROVED` means the pull request is not approved
810pub(crate) fn latest_review_approves(reviews: &[GitHubReview]) -> bool {
811    let mut latest: Option<(&str, &str)> = None;
812    for review in reviews {
813        let state = review.state.as_str();
814        let substantive = state.eq_ignore_ascii_case("APPROVED")
815            || state.eq_ignore_ascii_case("CHANGES_REQUESTED");
816        if !substantive {
817            continue;
818        }
819        match latest {
820            Some((at, _)) if review.submitted_at.as_str() < at => {}
821            _ => latest = Some((review.submitted_at.as_str(), state)),
822        }
823    }
824    latest.is_some_and(|(_, state)| state.eq_ignore_ascii_case("APPROVED"))
825}
826
827/// One issue comment considered for automated review approval.
828pub(crate) struct AutomatedReviewComment<'a> {
829    pub login: &'a str,
830    pub body: &'a str,
831    pub created_at: &'a str,
832}
833
834/// First-line verdict of a `## Automated Review` comment.
835///
836/// Orch writes an em dash. The review gate also accepts a hyphen
837pub(crate) fn automated_review_verdict(body: &str) -> Option<&'static str> {
838    let first = body.lines().next().unwrap_or("").trim().replace('\r', "");
839    if !first.starts_with("## Automated Review") {
840        return None;
841    }
842    let normalized = first.replace(['\u{2014}', '\u{2013}'], "-");
843    if normalized.contains("Automated Review - Approve") {
844        Some("approve")
845    } else if normalized.contains("Automated Review - Changes Requested") {
846        Some("changes_requested")
847    } else {
848        None
849    }
850}
851
852/// Latest `## Automated Review` comment from `reviewer` wins.
853///
854/// An empty reviewer matches nothing. A later changes-requested comment
855/// clears an earlier approve
856pub(crate) fn latest_automated_review_approves(
857    comments: &[AutomatedReviewComment<'_>],
858    reviewer: &str,
859) -> bool {
860    if reviewer.is_empty() {
861        return false;
862    }
863    let mut newest: Option<&AutomatedReviewComment<'_>> = None;
864    for comment in comments {
865        if automated_review_verdict(comment.body).is_none() {
866            continue;
867        }
868        if !comment.login.eq_ignore_ascii_case(reviewer) {
869            continue;
870        }
871        match newest {
872            Some(prev) if comment.created_at <= prev.created_at => {}
873            _ => newest = Some(comment),
874        }
875    }
876    newest.is_some_and(|comment| automated_review_verdict(comment.body) == Some("approve"))
877}
878
879#[cfg(test)]
880mod tests {
881    use std::env;
882
883    use wiremock::Mock;
884    use wiremock::MockServer;
885    use wiremock::ResponseTemplate;
886    use wiremock::matchers::method;
887    use wiremock::matchers::path;
888
889    use super::*;
890    use crate::github::http::GhHttp;
891    use crate::github::token;
892    use crate::github::types::GitHubComment;
893    use crate::github::types::GitHubLabel;
894    use crate::github::types::{GitHubIssue, GitHubReview, GitHubUser};
895
896    fn review(state: &str, at: &str) -> GitHubReview {
897        GitHubReview {
898            id: 1,
899            user: GitHubUser {
900                login: "owner".into(),
901            },
902            body: None,
903            state: state.into(),
904            html_url: None,
905            submitted_at: at.into(),
906            commit_id: None,
907        }
908    }
909
910    #[test]
911    fn later_changes_requested_clears_an_earlier_approval() {
912        let reviews = vec![
913            review("APPROVED", "2026-01-01T00:00:00Z"),
914            review("COMMENTED", "2026-01-02T00:00:00Z"),
915            review("CHANGES_REQUESTED", "2026-01-03T00:00:00Z"),
916        ];
917        assert!(!latest_review_approves(&reviews));
918        let approved = vec![
919            review("CHANGES_REQUESTED", "2026-01-01T00:00:00Z"),
920            review("APPROVED", "2026-01-02T00:00:00Z"),
921        ];
922        assert!(latest_review_approves(&approved));
923    }
924
925    fn review_comment<'a>(
926        login: &'a str,
927        body: &'a str,
928        at: &'a str,
929    ) -> AutomatedReviewComment<'a> {
930        AutomatedReviewComment {
931            login,
932            body,
933            created_at: at,
934        }
935    }
936
937    #[test]
938    fn automated_review_comment_counts_as_approval_without_formal_reviews() {
939        assert!(!latest_review_approves(&[]));
940        let comments = [review_comment(
941            "orch-bot",
942            "## Automated Review \u{2014} Approve\n\nLooks good.",
943            "2026-01-02T00:00:00Z",
944        )];
945        assert!(latest_automated_review_approves(&comments, "orch-bot"));
946        assert!(latest_automated_review_approves(&comments, "Orch-Bot"));
947        assert!(!latest_automated_review_approves(&comments, "mallory"));
948        assert!(!latest_automated_review_approves(&comments, ""));
949        let hyphen = [review_comment(
950            "orch-bot",
951            "## Automated Review - Approve\n\nok",
952            "2026-01-02T00:00:00Z",
953        )];
954        assert!(latest_automated_review_approves(&hyphen, "orch-bot"));
955    }
956
957    #[test]
958    fn later_automated_changes_requested_clears_comment_approval() {
959        let comments = [
960            review_comment(
961                "orch-bot",
962                "## Automated Review \u{2014} Approve\n\nok",
963                "2026-01-01T00:00:00Z",
964            ),
965            review_comment(
966                "mallory",
967                "## Automated Review \u{2014} Changes Requested\n\nnope",
968                "2026-01-03T00:00:00Z",
969            ),
970            review_comment(
971                "orch-bot",
972                "## Automated Review \u{2014} Changes Requested\n\nfix",
973                "2026-01-02T00:00:00Z",
974            ),
975        ];
976        assert!(!latest_automated_review_approves(&comments, "orch-bot"));
977    }
978
979    // --- is_github_issue_id guard ---
980
981    #[test]
982    fn is_github_issue_id_numeric() {
983        assert!(is_github_issue_id(&ExternalId("42".to_string())));
984        assert!(is_github_issue_id(&ExternalId("1".to_string())));
985        assert!(is_github_issue_id(&ExternalId("99999".to_string())));
986    }
987
988    #[test]
989    fn is_github_issue_id_rejects_internal_prefix() {
990        assert!(!is_github_issue_id(&ExternalId(
991            "internal:63857".to_string()
992        )));
993        assert!(!is_github_issue_id(&ExternalId("internal:1".to_string())));
994    }
995
996    #[test]
997    fn is_github_issue_id_rejects_empty_and_non_numeric() {
998        assert!(!is_github_issue_id(&ExternalId(String::new())));
999        assert!(!is_github_issue_id(&ExternalId("abc".to_string())));
1000        assert!(!is_github_issue_id(&ExternalId("1.0".to_string())));
1001    }
1002
1003    // ---
1004
1005    #[test]
1006    fn allowed_associations_are_owner_member_and_collaborator() {
1007        assert_eq!(ALLOWED_ASSOCIATIONS, &["OWNER", "MEMBER", "COLLABORATOR"]);
1008    }
1009
1010    #[test]
1011    fn is_trusted_author_owner() {
1012        let issue = GitHubIssue {
1013            number: 1,
1014            id: 0,
1015            title: "t".to_string(),
1016            body: None,
1017            state: "open".to_string(),
1018            labels: vec![],
1019            user: GitHubUser {
1020                login: "u".to_string(),
1021            },
1022            created_at: String::new(),
1023            updated_at: String::new(),
1024            html_url: String::new(),
1025            node_id: None,
1026            pull_request: None,
1027            state_reason: None,
1028            author_association: Some("OWNER".to_string()),
1029        };
1030        assert!(is_trusted_author(&issue));
1031    }
1032
1033    #[test]
1034    fn is_trusted_author_collaborator() {
1035        let issue = GitHubIssue {
1036            number: 1,
1037            id: 0,
1038            title: "t".to_string(),
1039            body: None,
1040            state: "open".to_string(),
1041            labels: vec![],
1042            user: GitHubUser {
1043                login: "u".to_string(),
1044            },
1045            created_at: String::new(),
1046            updated_at: String::new(),
1047            html_url: String::new(),
1048            node_id: None,
1049            pull_request: None,
1050            state_reason: None,
1051            author_association: Some("COLLABORATOR".to_string()),
1052        };
1053        assert!(is_trusted_author(&issue));
1054    }
1055
1056    #[test]
1057    fn is_not_trusted_author_contributor() {
1058        let issue = GitHubIssue {
1059            number: 1,
1060            id: 0,
1061            title: "t".to_string(),
1062            body: None,
1063            state: "open".to_string(),
1064            labels: vec![],
1065            user: GitHubUser {
1066                login: "u".to_string(),
1067            },
1068            created_at: String::new(),
1069            updated_at: String::new(),
1070            html_url: String::new(),
1071            node_id: None,
1072            pull_request: None,
1073            state_reason: None,
1074            author_association: Some("CONTRIBUTOR".to_string()),
1075        };
1076        assert!(!is_trusted_author(&issue));
1077    }
1078
1079    #[test]
1080    fn is_trusted_author_member() {
1081        let issue = GitHubIssue {
1082            number: 1,
1083            id: 0,
1084            title: "t".to_string(),
1085            body: None,
1086            state: "open".to_string(),
1087            labels: vec![],
1088            user: GitHubUser {
1089                login: "u".to_string(),
1090            },
1091            created_at: String::new(),
1092            updated_at: String::new(),
1093            html_url: String::new(),
1094            node_id: None,
1095            pull_request: None,
1096            state_reason: None,
1097            author_association: Some("MEMBER".to_string()),
1098        };
1099        assert!(is_trusted_author(&issue));
1100    }
1101
1102    #[test]
1103    fn is_trusted_comment_author_direct() {
1104        let c = GitHubComment {
1105            id: 1,
1106            body: "hi".to_string(),
1107            user: GitHubUser {
1108                login: "u".to_string(),
1109            },
1110            created_at: String::new(),
1111            updated_at: None,
1112            html_url: None,
1113            issue_url: None,
1114            author_association: Some("OWNER".to_string()),
1115        };
1116        assert!(is_trusted_comment_author(&c));
1117    }
1118
1119    #[test]
1120    fn is_trusted_comment_author_member() {
1121        let c = GitHubComment {
1122            id: 1,
1123            body: "hi".to_string(),
1124            user: GitHubUser {
1125                login: "u".to_string(),
1126            },
1127            created_at: String::new(),
1128            updated_at: None,
1129            html_url: None,
1130            issue_url: None,
1131            author_association: Some("MEMBER".to_string()),
1132        };
1133        assert!(is_trusted_comment_author(&c));
1134    }
1135
1136    fn comment_json(id: u64, login: &str, association: &str) -> serde_json::Value {
1137        serde_json::json!({
1138            "id": id,
1139            "body": format!("from {login}"),
1140            "user": { "login": login },
1141            "created_at": "2026-01-01T00:00:00Z",
1142            "issue_url": "https://api.github.com/repos/o/r/issues/1",
1143            "author_association": association,
1144        })
1145    }
1146
1147    #[test]
1148    fn trusted_mentions_drops_contributor_on_owner_issue() {
1149        let comment = GitHubComment {
1150            id: 42,
1151            body: "@orch please look".to_string(),
1152            user: GitHubUser {
1153                login: "stranger".to_string(),
1154            },
1155            created_at: "2026-01-01T00:00:00Z".to_string(),
1156            updated_at: None,
1157            html_url: None,
1158            issue_url: Some("https://api.github.com/repos/o/r/issues/1".to_string()),
1159            author_association: Some("CONTRIBUTOR".to_string()),
1160        };
1161        let issue = GitHubIssue {
1162            number: 1,
1163            id: 0,
1164            title: "t".to_string(),
1165            body: None,
1166            state: "open".to_string(),
1167            labels: vec![],
1168            user: GitHubUser {
1169                login: "owner".to_string(),
1170            },
1171            created_at: String::new(),
1172            updated_at: String::new(),
1173            html_url: String::new(),
1174            node_id: None,
1175            pull_request: None,
1176            state_reason: None,
1177            author_association: Some("OWNER".to_string()),
1178        };
1179        assert!(is_trusted_author(&issue));
1180        assert!(!is_trusted_comment_author(&comment));
1181        let mentions = trusted_mentions([comment]);
1182        assert!(mentions.is_empty());
1183    }
1184
1185    #[expect(
1186        clippy::await_holding_lock,
1187        reason = "the env lock stays held across the awaits so tests do not race on GH_TOKEN"
1188    )]
1189    #[tokio::test]
1190    async fn get_mentions_and_list_issue_comments_exclude_contributor_on_owner_issue() {
1191        let _env = token::ENV_LOCK.lock().unwrap();
1192        let prev = env::var_os("GH_TOKEN");
1193        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
1194        unsafe { env::set_var("GH_TOKEN", "test_token") };
1195
1196        let server = MockServer::start().await;
1197        let comments = serde_json::json!([
1198            comment_json(42, "stranger", "CONTRIBUTOR"),
1199            comment_json(43, "owner", "OWNER"),
1200        ]);
1201        Mock::given(method("GET"))
1202            .and(path("/repos/o/r/issues/comments"))
1203            .respond_with(ResponseTemplate::new(200).set_body_json(comments.clone()))
1204            .expect(1)
1205            .mount(&server)
1206            .await;
1207        Mock::given(method("GET"))
1208            .and(path("/repos/o/r/issues/1/comments"))
1209            .respond_with(ResponseTemplate::new(200).set_body_json(comments))
1210            .expect(1)
1211            .mount(&server)
1212            .await;
1213        Mock::given(method("GET"))
1214            .and(path("/repos/o/r/issues/1"))
1215            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
1216                "number": 1,
1217                "id": 1,
1218                "title": "t",
1219                "state": "open",
1220                "labels": [],
1221                "user": { "login": "owner" },
1222                "created_at": "2026-01-01T00:00:00Z",
1223                "updated_at": "2026-01-01T00:00:00Z",
1224                "html_url": "https://github.com/o/r/issues/1",
1225                "author_association": "OWNER",
1226            })))
1227            .expect(0)
1228            .mount(&server)
1229            .await;
1230
1231        let backend = GitHubBackend::for_test("o/r", GhHttp::for_test(server.uri(), None));
1232        let mentions = backend
1233            .get_mentions("2026-01-01T00:00:00Z")
1234            .await
1235            .expect("get_mentions");
1236        let listed = backend
1237            .list_issue_comments(&ExternalId("1".to_string()))
1238            .await
1239            .expect("list_issue_comments");
1240
1241        match prev {
1242            // SAFETY: nextest runs each test in its own process, so no other test touches the environment
1243            Some(value) => unsafe { env::set_var("GH_TOKEN", value) },
1244            // SAFETY: nextest runs each test in its own process, so no other test touches the environment
1245            None => unsafe { env::remove_var("GH_TOKEN") },
1246        }
1247
1248        assert_eq!(mentions.len(), 1);
1249        assert_eq!(mentions[0].id, "43");
1250        assert_eq!(mentions[0].author, "owner");
1251        assert_eq!(listed.len(), 1);
1252        assert_eq!(listed[0].id, "43");
1253        assert_eq!(listed[0].author, "owner");
1254    }
1255
1256    fn make_test_issue(labels: &[&str]) -> GitHubIssue {
1257        GitHubIssue {
1258            number: 1,
1259            id: 0,
1260            title: "t".to_string(),
1261            body: None,
1262            state: "open".to_string(),
1263            labels: labels
1264                .iter()
1265                .map(|label| GitHubLabel {
1266                    name: (*label).to_string(),
1267                    color: None,
1268                })
1269                .collect(),
1270            user: GitHubUser {
1271                login: "u".to_string(),
1272            },
1273            created_at: String::new(),
1274            updated_at: String::new(),
1275            html_url: String::new(),
1276            node_id: None,
1277            pull_request: None,
1278            state_reason: None,
1279            author_association: Some("OWNER".to_string()),
1280        }
1281    }
1282
1283    #[test]
1284    fn a_single_issue_read_skips_what_the_open_list_skips() {
1285        assert!(classify_single_open_issue(make_test_issue(&[])).is_some());
1286
1287        let mut untrusted = make_test_issue(&[]);
1288        untrusted.author_association = Some("CONTRIBUTOR".to_string());
1289        assert!(classify_single_open_issue(untrusted).is_none());
1290
1291        let mut closed = make_test_issue(&[]);
1292        closed.state = "closed".to_string();
1293        assert!(classify_single_open_issue(closed).is_none());
1294
1295        assert!(classify_single_open_issue(make_test_issue(&["status:done"])).is_none());
1296    }
1297
1298    /// Open issues carrying `status:done` must be excluded from active-open ingest.
1299    #[test]
1300    fn classify_active_open_issue_excludes_status_done() {
1301        assert!(classify_active_open_issue(make_test_issue(&["status:done"])).is_none());
1302        assert!(
1303            classify_active_open_issue(make_test_issue(&["status:routed", "status:done"]))
1304                .is_none()
1305        );
1306    }
1307
1308    #[test]
1309    fn classify_active_open_issue_preserves_unlabeled_and_new_as_none_status() {
1310        let unlabeled = classify_active_open_issue(make_test_issue(&[]))
1311            .expect("unlabeled issue should still be ingested");
1312        assert_eq!(unlabeled.1, None);
1313
1314        let status_new = classify_active_open_issue(make_test_issue(&["status:new"]))
1315            .expect("status:new issue should still be ingested");
1316        assert_eq!(status_new.1, None);
1317    }
1318
1319    #[test]
1320    fn classify_active_open_issue_maps_active_status() {
1321        let routed = classify_active_open_issue(make_test_issue(&["status:routed"]))
1322            .expect("active status issue should be ingested");
1323        assert_eq!(routed.1, Some(Status::Routed));
1324    }
1325}