orch-cli 0.117.1

Orch, the agent orchestration engine: runs coding agents on tasks and cron jobs
Documentation
//! Acts on the one item a relay event names, through the steps the sync runs for that item. The
//! payload only says which item to read, every decision uses what GitHub returns for it

use super::{comments, ingest_external_tasks, ingest_issue, prefetch_review_tasks};
use crate::backends::ExternalBackend;
use crate::engine::EngineConfig;
use crate::engine::git::cleanup::{ReviewTaskSnapshot, check_merged_prs};
use crate::engine::review::poll::{GhReviewClient, review_open_prs};
use crate::engine::router::RouterConfig;
use crate::engine::service::relay::Event;
use crate::engine::tasks;
use crate::engine::tasks::TaskManager;
use crate::store::{TaskStatus, TaskStore};
use dashmap::{DashMap, DashSet};
use serde_json::Value;
use std::sync::{Arc, LazyLock};
use tokio::sync::Mutex;

// One lock per repository, so an event and the sync never work on the same project at once
static REPO_LOCKS: LazyLock<DashMap<String, Arc<Mutex<()>>>> = LazyLock::new(DashMap::new);

/// The item an event names
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum Target {
    Issue(String),
    Prs(Vec<i64>),
    /// The default branch moved, so open PRs may be behind it
    DefaultBranch,
    /// Mentions and slash commands
    Comments,
    /// The open issues of the repository, for an issue event with no number
    Issues,
    /// The full sync of that one repository
    Repo,
    /// Nothing to read, the tick runs the CI gate and merges
    Tick,
    /// A check or workflow that has not completed, nothing to read and no tick
    Ignore,
}

/// What the caller still has to run
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum Followup {
    None,
    SyncRepo,
}

/// The handles the sync passes to the steps for one item
pub(crate) struct ItemContext<'a> {
    pub backend: &'a Arc<dyn ExternalBackend>,
    pub repo: &'a str,
    pub config: &'a EngineConfig,
    pub task_manager: &'a Arc<TaskManager>,
    pub store: &'a Arc<TaskStore>,
    pub dispatching: &'a Arc<DashMap<String, String>>,
    pub auto_merge_in_flight: &'a Arc<DashSet<String>>,
    pub router_config: &'a RouterConfig,
    pub gh: &'a dyn GhReviewClient,
}

pub(crate) fn repo_lock(repo: &str) -> Arc<Mutex<()>> {
    Arc::clone(
        REPO_LOCKS
            .entry(repo.to_ascii_lowercase())
            .or_insert_with(|| Arc::new(Mutex::new(())))
            .value(),
    )
}

pub(crate) fn target(event: &Event) -> Target {
    if matches!(
        event.name.as_str(),
        "check_run" | "check_suite" | "workflow_run"
    ) && event.action != "completed"
    {
        return Target::Ignore;
    }

    let Some(payload) = event.payload.as_ref() else {
        return truncated_target(&event.name);
    };

    match event.name.as_str() {
        "issues" => match event.action.as_str() {
            // A close or removal also ends the task, which the sync of the repository owns
            "closed" | "deleted" | "transferred" => Target::Repo,
            _ => number_at(payload, "/issue/number")
                .map_or(Target::Issues, |n| Target::Issue(n.to_string())),
        },
        "issue_comment" => Target::Comments,
        "pull_request"
        | "pull_request_review"
        | "pull_request_review_comment"
        | "pull_request_review_thread" => number_at(payload, "/pull_request/number")
            .or_else(|| number_at(payload, "/number"))
            .map_or(Target::Repo, |n| Target::Prs(vec![n])),
        "check_run" | "check_suite" | "workflow_run" => {
            let pointer = format!("/{}/pull_requests", event.name);
            match payload.pointer(&pointer).and_then(Value::as_array) {
                Some(prs) if prs.is_empty() => Target::Tick,
                Some(prs) => Target::Prs(
                    prs.iter()
                        .filter_map(|pr| pr.get("number").and_then(Value::as_i64))
                        .collect(),
                ),
                None => Target::Repo,
            }
        }
        "push" => {
            let pushed = payload.get("ref").and_then(Value::as_str);
            let default = payload
                .pointer("/repository/default_branch")
                .and_then(Value::as_str);
            match (pushed, default) {
                (Some(pushed), Some(default))
                    if pushed.strip_prefix("refs/heads/") != Some(default) =>
                {
                    Target::Tick
                }
                _ => Target::DefaultBranch,
            }
        }
        _ => Target::Repo,
    }
}

// A payload over 1 MB arrives without a body, the event and repository still say where to look
fn truncated_target(event: &str) -> Target {
    match event {
        "issues" => Target::Issues,
        "issue_comment" => Target::Comments,
        "push" => Target::DefaultBranch,
        _ => Target::Repo,
    }
}

fn number_at(payload: &Value, pointer: &str) -> Option<i64> {
    payload.pointer(pointer).and_then(Value::as_i64)
}

/// Runs the sync's steps for the item. The caller holds `repo_lock` for the repository
pub(crate) async fn apply(ctx: &ItemContext<'_>, target: Target) -> anyhow::Result<Followup> {
    match target {
        Target::Issue(number) => {
            ingest_issue(ctx.backend, ctx.repo, ctx.store, &number).await?;
        }
        Target::Issues => ingest_external_tasks(ctx.backend, ctx.repo, ctx.store).await?,
        Target::Comments => {
            comments::scan_comments(
                ctx.backend,
                Some(ctx.store),
                ctx.repo,
                ctx.task_manager,
                None,
            )
            .await?;
        }
        Target::Prs(numbers) => {
            let mut snapshots = Vec::new();
            for number in numbers {
                let Ok(number) = i32::try_from(number) else {
                    continue;
                };
                let Some(id) = ctx.store.resolve_id_by_pr_number(ctx.repo, number).await? else {
                    tracing::debug!(
                        repo = ctx.repo,
                        pr = number,
                        "event names a PR no task owns"
                    );
                    continue;
                };
                let stored = ctx.store.get(id).await?;
                snapshots.push(ReviewTaskSnapshot {
                    external: tasks::store_task_to_external(&stored),
                    stored,
                });
            }
            review(ctx, snapshots).await?;
        }
        Target::DefaultBranch => {
            let (mut snapshots, needs_review, blocked) =
                prefetch_review_tasks(ctx.store, ctx.repo).await?;
            snapshots.extend(needs_review);
            snapshots.extend(blocked);
            review(ctx, snapshots).await?;
        }
        Target::Repo => return Ok(Followup::SyncRepo),
        Target::Tick | Target::Ignore => {}
    }

    Ok(Followup::None)
}

// The merge check and the review step of the sync, for these tasks only
async fn review(ctx: &ItemContext<'_>, snapshots: Vec<ReviewTaskSnapshot>) -> anyhow::Result<()> {
    let (in_review, waiting): (Vec<_>, Vec<_>) = snapshots
        .into_iter()
        .partition(|s| matches!(s.stored.status, TaskStatus::InReview | TaskStatus::Approved));
    let waiting: Vec<_> = waiting
        .into_iter()
        .filter(|s| match s.stored.status {
            TaskStatus::NeedsReview => true,
            TaskStatus::Blocked => s.stored.pr_number.is_some() || !s.stored.branch.is_empty(),
            _ => false,
        })
        .collect();

    if in_review.is_empty() && waiting.is_empty() {
        return Ok(());
    }

    check_merged_prs(
        ctx.backend,
        ctx.repo,
        ctx.store,
        ctx.task_manager,
        &in_review,
        &waiting,
    )
    .await?;

    Box::pin(review_open_prs(
        ctx.backend,
        ctx.repo,
        ctx.config,
        ctx.task_manager,
        ctx.store,
        ctx.dispatching,
        ctx.auto_merge_in_flight,
        &in_review,
        ctx.gh,
        ctx.router_config,
    ))
    .await
}