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