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