Skip to main content

orch/engine/ci/
bootstrap.rs

1//! After a CI bootstrap task merges, require its default-branch checks
2
3use crate::engine::ci;
4use crate::github::http::RulesetApply;
5#[cfg(test)]
6use crate::github::types::merge_missing_checks;
7use crate::github::types::required_contexts_cover;
8
9use crate::backends::{ExternalId, ExternalTask, Status};
10use crate::engine;
11use crate::engine::ci::gate;
12use crate::engine::tasks::TaskManager;
13use crate::github::http::{GhHttp, RulesetCreateKind};
14use crate::github::types::{GitHubCheckRun, RequiredStatusCheck};
15use crate::plan;
16use crate::store;
17use crate::store::TaskStore;
18use std::sync::Arc;
19
20const KV_PENDING: &str = "pending";
21const KV_APPLIED: &str = "applied";
22const KV_REFUSED: &str = "refused";
23
24#[derive(Debug, PartialEq)]
25pub(crate) enum ChecksReady {
26    Ready(Vec<RequiredStatusCheck>),
27    /// A real check is still queued, in progress, or waiting on a person
28    Pending,
29    /// A real check finished as failure, error, cancelled, or timed out
30    Failed(Vec<FailedCheck>),
31    /// No real check has started
32    Empty,
33}
34
35#[derive(Debug, PartialEq)]
36pub(crate) struct FailedCheck {
37    name: String,
38    conclusion: String,
39}
40
41pub(crate) fn is_ci_bootstrap_task(body: &str) -> bool {
42    plan::is_ci_bootstrap_body(body)
43        || plan::marker_id(body).is_some_and(|id| plan::is_ci_bootstrap_id(&id))
44}
45
46pub(crate) fn kv_key(repo: &str, task_id: &str) -> String {
47    format!("ci-bootstrap:{repo}:{task_id}")
48}
49
50/// True when this merged CI bootstrap task must stay approved until a ruleset exists
51pub(crate) async fn hold_after_merge(
52    task: &ExternalTask,
53    store: &Arc<TaskStore>,
54    repo: &str,
55) -> bool {
56    if !is_ci_bootstrap_task(&task.body) {
57        return false;
58    }
59    let key = kv_key(repo, &task.id.0);
60    match store.kv_get(&key).await {
61        Ok(Some(state)) if state == KV_APPLIED => false,
62        Ok(Some(_)) => true,
63        Ok(None) => {
64            if let Err(e) = store.kv_set(&key, KV_PENDING).await {
65                tracing::warn!(
66                    task_id = %task.id.0,
67                    err = %e,
68                    "failed to record CI bootstrap pending"
69                );
70            }
71            true
72        }
73        Err(e) => {
74            tracing::warn!(
75                task_id = %task.id.0,
76                err = %e,
77                "failed to read CI bootstrap state"
78            );
79            true
80        }
81    }
82}
83
84pub(crate) async fn apply_pending(
85    store: &Arc<TaskStore>,
86    task_manager: &Arc<TaskManager>,
87    repo: &str,
88) -> anyhow::Result<()> {
89    let gh = GhHttp::owner()?;
90    apply_pending_with(&gh, store, task_manager, repo).await
91}
92
93pub(crate) async fn apply_pending_with(
94    gh: &GhHttp,
95    store: &Arc<TaskStore>,
96    task_manager: &Arc<TaskManager>,
97    repo: &str,
98) -> anyhow::Result<()> {
99    let prefix = format!("ci-bootstrap:{repo}:");
100    let entries = store.kv_list_prefix(&prefix).await?;
101    for (key, state) in entries {
102        if state == KV_APPLIED {
103            continue;
104        }
105        let Some(task_id) = key.strip_prefix(&prefix) else {
106            continue;
107        };
108        if let Err(e) = apply_one(gh, store, task_manager, repo, task_id, &state).await {
109            tracing::warn!(task_id, err = %e, "CI bootstrap ruleset apply failed");
110        }
111    }
112    Ok(())
113}
114
115pub(crate) fn checks_ready_for_ruleset(
116    runs: &[GitHubCheckRun],
117    statuses: &[(String, String)],
118) -> ChecksReady {
119    let mut ready: Vec<RequiredStatusCheck> = Vec::new();
120    let mut pending = false;
121    let mut failed: Vec<FailedCheck> = Vec::new();
122
123    for run in runs {
124        if gate::is_own_check(&run.name) {
125            continue;
126        }
127        if !run.is_finished() {
128            pending = true;
129            continue;
130        }
131        match run.conclusion.as_deref() {
132            Some("success") => {
133                let integration_id = run.app.as_ref().map(|app| app.id).filter(|&id| id > 0);
134                if !ready.iter().any(|check| check.context == run.name) {
135                    ready.push(RequiredStatusCheck {
136                        context: run.name.clone(),
137                        integration_id,
138                    });
139                }
140            }
141            Some("skipped" | "neutral") => {}
142            Some(conclusion) => failed.push(FailedCheck {
143                name: run.name.clone(),
144                conclusion: conclusion.to_string(),
145            }),
146            None => pending = true,
147        }
148    }
149
150    for (context, state) in statuses {
151        if gate::is_own_check(context) {
152            continue;
153        }
154        match state.as_str() {
155            "pending" => pending = true,
156            "success" => {
157                if !ready.iter().any(|check| &check.context == context) {
158                    ready.push(RequiredStatusCheck {
159                        context: context.clone(),
160                        integration_id: None,
161                    });
162                }
163            }
164            "failure" | "error" => failed.push(FailedCheck {
165                name: context.clone(),
166                conclusion: state.clone(),
167            }),
168            _ => {}
169        }
170    }
171
172    if !failed.is_empty() {
173        ChecksReady::Failed(failed)
174    } else if pending {
175        ChecksReady::Pending
176    } else if ready.is_empty() {
177        ChecksReady::Empty
178    } else {
179        ChecksReady::Ready(ready)
180    }
181}
182
183async fn apply_one(
184    gh: &GhHttp,
185    store: &Arc<TaskStore>,
186    task_manager: &Arc<TaskManager>,
187    repo: &str,
188    task_id: &str,
189    state: &str,
190) -> anyhow::Result<()> {
191    if store::opt_store_get_task(&Some(Arc::clone(store)), repo, task_id)
192        .await
193        .is_none()
194    {
195        return Ok(());
196    }
197
198    let branch = gh.get_default_branch(repo).await?;
199    let required = gh.get_required_status_check_contexts(repo, &branch).await?;
200    let sha = gh.get_branch_sha(repo, &branch).await?;
201    let runs = gh.get_check_runs(repo, &sha).await?;
202    let statuses = gh.get_commit_status_contexts(repo, &sha).await?;
203    let checks = match checks_ready_for_ruleset(&runs, &statuses) {
204        ChecksReady::Pending => {
205            tracing::info!(
206                task_id,
207                sha = %sha,
208                "CI bootstrap waiting for default-branch checks"
209            );
210            reopen_if_closed(gh, repo, task_id).await;
211            clear_wait(store, repo, task_id).await;
212            return Ok(());
213        }
214        ChecksReady::Empty => {
215            reopen_if_closed(gh, repo, task_id).await;
216            return wait_for_checks(gh, store, repo, task_id, &sha).await;
217        }
218        ChecksReady::Failed(failed) => {
219            reopen_if_closed(gh, repo, task_id).await;
220            clear_wait(store, repo, task_id).await;
221            return handle_failed_checks(gh, store, task_manager, repo, task_id, &sha, &failed)
222                .await;
223        }
224        ChecksReady::Ready(checks) => {
225            clear_wait(store, repo, task_id).await;
226            checks
227        }
228    };
229
230    if required_contexts_cover(&required, &checks) {
231        return finish_applied(store, task_manager, task_id, repo).await;
232    }
233
234    // GitHub may have closed the issue via Closes on the PR, keep it open until the ruleset exists
235    reopen_if_closed(gh, repo, task_id).await;
236    if state == KV_REFUSED {
237        return Ok(());
238    }
239
240    match gh.apply_required_check_ruleset(repo, &checks).await? {
241        RulesetApply::Applied => finish_applied(store, task_manager, task_id, repo).await,
242        RulesetApply::NameTakenNotFound => {
243            tracing::info!(
244                task_id,
245                "CI bootstrap ruleset name taken, existing ruleset not found"
246            );
247            Ok(())
248        }
249        RulesetApply::Failed { err, kind } => {
250            handle_ruleset_write_error(gh, store, repo, task_id, &err, kind).await
251        }
252    }
253}
254
255async fn handle_ruleset_write_error(
256    gh: &GhHttp,
257    store: &Arc<TaskStore>,
258    repo: &str,
259    task_id: &str,
260    err: &str,
261    kind: RulesetCreateKind,
262) -> anyhow::Result<()> {
263    match kind {
264        RulesetCreateKind::NameTaken | RulesetCreateKind::Retryable | RulesetCreateKind::Other => {
265            tracing::info!(
266                task_id,
267                err = %err,
268                "CI bootstrap ruleset create retrying"
269            );
270            Ok(())
271        }
272        RulesetCreateKind::CheckNeverRun => {
273            tracing::info!(
274                task_id,
275                err = %err,
276                "CI bootstrap ruleset create waiting, check has not run"
277            );
278            comment_never_run_once(gh, store, repo, task_id, err).await;
279            Ok(())
280        }
281        RulesetCreateKind::Refused => {
282            comment_refused(gh, repo, task_id, err).await;
283            store.kv_set(&kv_key(repo, task_id), KV_REFUSED).await?;
284            Ok(())
285        }
286    }
287}
288
289async fn finish_applied(
290    store: &Arc<TaskStore>,
291    task_manager: &Arc<TaskManager>,
292    task_id: &str,
293    repo: &str,
294) -> anyhow::Result<()> {
295    store.kv_set(&kv_key(repo, task_id), KV_APPLIED).await?;
296    task_manager
297        .update_task_status(&ExternalId(task_id.to_string()), Status::Done)
298        .await?;
299    Ok(())
300}
301
302async fn reopen_if_closed(gh: &GhHttp, repo: &str, task_id: &str) {
303    match gh.get_issue(repo, task_id).await {
304        Ok(issue) if issue.state.eq_ignore_ascii_case("closed") => {
305            if let Err(e) = gh.reopen_issue(repo, task_id).await {
306                tracing::warn!(
307                    task_id,
308                    err = %e,
309                    "failed to reopen CI bootstrap issue"
310                );
311            }
312        }
313        Ok(_) => {}
314        Err(e) => {
315            tracing::warn!(
316                task_id,
317                err = %e,
318                "failed to read CI bootstrap issue"
319            );
320        }
321    }
322}
323
324fn wait_prefix(repo: &str, task_id: &str) -> String {
325    format!("ci_bootstrap_wait_since:{repo}#{task_id}#")
326}
327
328fn no_checks_comment_key(repo: &str, task_id: &str, sha: &str) -> String {
329    format!("ci_bootstrap_no_checks_comment:{repo}#{task_id}#{sha}")
330}
331
332fn never_run_comment_key(repo: &str, task_id: &str) -> String {
333    format!("ci_bootstrap_never_run_comment:{repo}#{task_id}")
334}
335
336fn format_failed(failed: &[FailedCheck]) -> String {
337    failed
338        .iter()
339        .map(|check| format!("{}: {}", check.name, check.conclusion))
340        .collect::<Vec<_>>()
341        .join(", ")
342}
343
344async fn clear_wait(store: &Arc<TaskStore>, repo: &str, task_id: &str) {
345    let prefix = wait_prefix(repo, task_id);
346    let keys = match store.kv_list_prefix(&prefix).await {
347        Ok(entries) => entries,
348        Err(e) => {
349            tracing::warn!(task_id, err = %e, "failed to list CI bootstrap wait keys");
350            return;
351        }
352    };
353    for (key, _) in keys {
354        if let Err(e) = store.kv_delete(&key).await {
355            tracing::warn!(task_id, err = %e, "failed to clear CI bootstrap wait key");
356        }
357    }
358}
359
360async fn wait_for_checks(
361    gh: &GhHttp,
362    store: &Arc<TaskStore>,
363    repo: &str,
364    task_id: &str,
365    sha: &str,
366) -> anyhow::Result<()> {
367    let prefix = wait_prefix(repo, task_id);
368    let key = format!("{prefix}{sha}");
369    let now = chrono::Utc::now().timestamp();
370    let since = gate::wait_since(store, &prefix, &key, now).await?;
371    if now - since < gate::NO_CHECKS_WAIT_SECS {
372        tracing::info!(
373            task_id,
374            sha = %sha,
375            "CI bootstrap waiting for a default-branch check to start"
376        );
377        return Ok(());
378    }
379    let wait_mins = gate::NO_CHECKS_WAIT_SECS / 60;
380    tracing::warn!(
381        task_id,
382        sha = %sha,
383        wait_mins,
384        "CI bootstrap has no default-branch check after the wait"
385    );
386    let comment_key = no_checks_comment_key(repo, task_id, sha);
387    if store.kv_get(&comment_key).await?.is_none() {
388        comment_issue(
389            gh,
390            repo,
391            task_id,
392            &format!(
393                "No default-branch check has started {wait_mins} minutes after the CI bootstrap merge. Later tasks stay waiting until a check runs."
394            ),
395        )
396        .await;
397        store.kv_set(&comment_key, "1").await?;
398    }
399    Ok(())
400}
401
402async fn handle_failed_checks(
403    gh: &GhHttp,
404    store: &Arc<TaskStore>,
405    task_manager: &Arc<TaskManager>,
406    repo: &str,
407    task_id: &str,
408    sha: &str,
409    failed: &[FailedCheck],
410) -> anyhow::Result<()> {
411    let details = format_failed(failed);
412    let failures = match ci::count_ci_failure_for_head(store, repo, task_id, sha).await {
413        Ok(Some(v)) => v,
414        Ok(None) => {
415            tracing::info!(
416                task_id,
417                sha = %sha,
418                details,
419                "CI bootstrap default-branch checks still failed on the same head"
420            );
421            return Ok(());
422        }
423        Err(e) => {
424            tracing::warn!(
425                task_id,
426                err = %e,
427                "failed to increment ci_merge_failures for CI bootstrap"
428            );
429            return Ok(());
430        }
431    };
432
433    let max = ci::MAX_CI_MERGE_FAILURES;
434    let id = ExternalId(task_id.to_string());
435    let (status, fields) = if failures >= max {
436        tracing::error!(
437            task_id,
438            failures,
439            details,
440            "CI bootstrap default-branch checks failed, CI failure limit reached"
441        );
442        (
443            Status::Blocked,
444            vec![(
445                "block_reason",
446                serde_json::json!(format!(
447                    "CI failure limit ({max}) reached after the CI bootstrap merge"
448                )),
449            )],
450        )
451    } else {
452        tracing::warn!(
453            task_id,
454            failures,
455            details,
456            "CI bootstrap default-branch checks failed, routing back to the task agent"
457        );
458        (
459            Status::Routed,
460            vec![
461                (
462                    "last_error",
463                    serde_json::json!(format!(
464                        "CI failed on the default branch after the CI bootstrap merge: {details}. Fix the failing checks"
465                    )),
466                ),
467                (
468                    "route_reason",
469                    serde_json::json!(
470                        "re-dispatch after CI bootstrap default-branch checks failed"
471                    ),
472                ),
473            ],
474        )
475    };
476    if let Err(e) =
477        ci::apply_ci_failure_status(store, task_manager, repo, &id, sha, status, &fields).await
478    {
479        tracing::error!(
480            task_id,
481            err = %e,
482            "failed to apply CI bootstrap status after failed default-branch checks"
483        );
484        return Ok(());
485    }
486    comment_issue(
487        gh,
488        repo,
489        task_id,
490        &format!(
491            "Default-branch checks failed after the CI bootstrap merge ({details}). Later tasks stay waiting until those checks pass."
492        ),
493    )
494    .await;
495    Ok(())
496}
497
498async fn comment_never_run_once(
499    gh: &GhHttp,
500    store: &Arc<TaskStore>,
501    repo: &str,
502    task_id: &str,
503    err: &str,
504) {
505    let key = never_run_comment_key(repo, task_id);
506    match store.kv_get(&key).await {
507        Ok(Some(_)) => return,
508        Ok(None) => {}
509        Err(e) => {
510            tracing::warn!(
511                task_id,
512                err = %e,
513                "failed to read CI bootstrap never-run comment key"
514            );
515            return;
516        }
517    }
518    comment_issue(
519        gh,
520        repo,
521        task_id,
522        &format!(
523            "GitHub does not treat the default-branch checks as valid required checks ({err}). Later tasks stay waiting until a required-checks ruleset can be created."
524        ),
525    )
526    .await;
527    if let Err(e) = store.kv_set(&key, "1").await {
528        tracing::warn!(
529            task_id,
530            err = %e,
531            "failed to record CI bootstrap never-run comment"
532        );
533    }
534}
535
536async fn comment_refused(gh: &GhHttp, repo: &str, task_id: &str, err: &str) {
537    comment_issue(
538        gh,
539        repo,
540        task_id,
541        &format!(
542            "GitHub refused a required-checks ruleset on the default branch ({err}). Turn branch protection on for this repository. Later tasks stay waiting until that happens."
543        ),
544    )
545    .await;
546}
547
548async fn comment_issue(gh: &GhHttp, repo: &str, task_id: &str, message: &str) {
549    let body = format!("{message}{}", engine::orch_footer());
550    if let Err(e) = gh.add_comment(repo, task_id, &body).await {
551        tracing::warn!(
552            task_id,
553            err = %e,
554            "failed to comment on CI bootstrap issue"
555        );
556    }
557}
558
559#[cfg(test)]
560mod tests {
561    use super::*;
562    use crate::backends::ExternalBackend;
563    use crate::backends::test_helpers::NoopBackend;
564    use crate::github::http::{REQUIRED_CHECK_RULESET_NAME, classify_ruleset_create_error};
565    use crate::github::types::GitHubApp;
566    use crate::plan::{CI_BOOTSTRAP_MARKER, ci_bootstrap_task, issue_body};
567    use crate::store::TaskStatus;
568    use crate::store::UpsertExternal;
569    use std::env;
570    use std::ffi::OsString;
571    use wiremock::matchers::{body_partial_json, method, path};
572    use wiremock::{Mock, MockServer, ResponseTemplate};
573
574    struct EnvVarGuard {
575        key: &'static str,
576        previous: Option<OsString>,
577    }
578
579    impl EnvVarGuard {
580        fn set(key: &'static str, value: &str) -> Self {
581            let previous = env::var_os(key);
582            // SAFETY: nextest runs each test in its own process
583            unsafe { env::set_var(key, value) };
584            Self { key, previous }
585        }
586    }
587
588    impl Drop for EnvVarGuard {
589        fn drop(&mut self) {
590            match self.previous.take() {
591                // SAFETY: nextest runs each test in its own process
592                Some(value) => unsafe { env::set_var(self.key, value) },
593                // SAFETY: nextest runs each test in its own process
594                None => unsafe { env::remove_var(self.key) },
595            }
596        }
597    }
598
599    fn run(
600        name: &str,
601        status: &str,
602        conclusion: Option<&str>,
603        app_id: Option<i64>,
604    ) -> GitHubCheckRun {
605        GitHubCheckRun {
606            id: 1,
607            name: name.to_string(),
608            status: status.to_string(),
609            conclusion: conclusion.map(String::from),
610            app: app_id.map(|id| GitHubApp { id }),
611        }
612    }
613
614    fn bootstrap_body() -> String {
615        issue_body(
616            &ci_bootstrap_task(false),
617            "acme/app",
618            "main",
619            "docs/ROADMAP.md",
620        )
621    }
622
623    async fn pending_store() -> (Arc<TaskStore>, Arc<TaskManager>, i64) {
624        let store = Arc::new(TaskStore::open_memory().await.unwrap());
625        let backend: Arc<dyn ExternalBackend> = Arc::new(NoopBackend);
626        let task_manager = Arc::new(TaskManager::with_store(
627            backend,
628            Arc::clone(&store),
629            "o/r".to_string(),
630        ));
631        let id = store
632            .upsert_external(&UpsertExternal {
633                repo: "o/r",
634                ext_id: "12",
635                title: "CI-01 Set up CI and tests",
636                body: &bootstrap_body(),
637                author: "u",
638                url: "",
639                labels: &[],
640                origin: "github",
641            })
642            .await
643            .unwrap();
644        store.update_status(id, TaskStatus::Approved).await.unwrap();
645        store
646            .kv_set(&kv_key("o/r", "12"), KV_PENDING)
647            .await
648            .unwrap();
649        (store, task_manager, id)
650    }
651
652    async fn mock_unprotected_main(server: &MockServer, sha: &str) {
653        Mock::given(method("GET"))
654            .and(path("/repos/o/r"))
655            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
656                "default_branch": "main"
657            })))
658            .mount(server)
659            .await;
660        Mock::given(method("GET"))
661            .and(path("/repos/o/r/branches/main/protection"))
662            .respond_with(
663                ResponseTemplate::new(404)
664                    .set_body_string("{\"message\":\"Branch not protected\"}"),
665            )
666            .mount(server)
667            .await;
668        Mock::given(method("GET"))
669            .and(path("/repos/o/r/rules/branches/main"))
670            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([])))
671            .mount(server)
672            .await;
673        Mock::given(method("GET"))
674            .and(path("/repos/o/r/branches/main"))
675            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
676                "commit": { "sha": sha }
677            })))
678            .mount(server)
679            .await;
680    }
681
682    async fn mock_classic_required(server: &MockServer, context: &str, sha: &str) {
683        Mock::given(method("GET"))
684            .and(path("/repos/o/r"))
685            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
686                "default_branch": "main"
687            })))
688            .mount(server)
689            .await;
690        Mock::given(method("GET"))
691            .and(path("/repos/o/r/branches/main/protection"))
692            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
693                "required_status_checks": {
694                    "checks": [{ "context": context, "app_id": 15368 }]
695                }
696            })))
697            .mount(server)
698            .await;
699        Mock::given(method("GET"))
700            .and(path("/repos/o/r/rules/branches/main"))
701            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([])))
702            .mount(server)
703            .await;
704        Mock::given(method("GET"))
705            .and(path("/repos/o/r/branches/main"))
706            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
707                "commit": { "sha": sha }
708            })))
709            .mount(server)
710            .await;
711    }
712
713    async fn mock_name_taken_ruleset(server: &MockServer, ruleset_checks: serde_json::Value) {
714        Mock::given(method("POST"))
715            .and(path("/repos/o/r/rulesets"))
716            .respond_with(ResponseTemplate::new(422).set_body_json(serde_json::json!({
717                "message": "Name has already been taken"
718            })))
719            .expect(1)
720            .mount(server)
721            .await;
722        Mock::given(method("GET"))
723            .and(path("/repos/o/r/rulesets"))
724            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([
725                { "id": 9, "name": REQUIRED_CHECK_RULESET_NAME }
726            ])))
727            .mount(server)
728            .await;
729        Mock::given(method("GET"))
730            .and(path("/repos/o/r/rulesets/9"))
731            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
732                "id": 9,
733                "name": REQUIRED_CHECK_RULESET_NAME,
734                "rules": [{
735                    "type": "required_status_checks",
736                    "parameters": {
737                        "required_status_checks": ruleset_checks
738                    }
739                }]
740            })))
741            .mount(server)
742            .await;
743    }
744
745    async fn mock_runs_and_empty_status(
746        server: &MockServer,
747        sha: &str,
748        check_runs: serde_json::Value,
749    ) {
750        Mock::given(method("GET"))
751            .and(path(format!("/repos/o/r/commits/{sha}/check-runs")))
752            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
753                "total_count": 1,
754                "check_runs": check_runs
755            })))
756            .mount(server)
757            .await;
758        Mock::given(method("GET"))
759            .and(path(format!("/repos/o/r/commits/{sha}/status")))
760            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
761                "state": "pending",
762                "total_count": 0,
763                "statuses": []
764            })))
765            .mount(server)
766            .await;
767    }
768
769    async fn mock_issue_comment(server: &MockServer, expected: u64) {
770        Mock::given(method("POST"))
771            .and(path("/repos/o/r/issues/12/comments"))
772            .respond_with(ResponseTemplate::new(201).set_body_json(serde_json::json!({
773                "id": 1
774            })))
775            .expect(expected)
776            .mount(server)
777            .await;
778    }
779
780    #[test]
781    fn ruleset_write_keeps_429_transport_and_422_with_401_digits_pending() {
782        for err in [
783            "GitHub API POST /rulesets failed (429 Too Many Requests): {\"message\":\"API rate limit exceeded\"}",
784            "HTTP request failed to send (transport error): connection reset by peer",
785            "failed (422 Unprocessable Entity): {\"message\":\"Ruleset validation failed for rule 401\"}",
786        ] {
787            assert!(
788                !matches!(
789                    classify_ruleset_create_error(err),
790                    RulesetCreateKind::Refused
791                ),
792                "{err}"
793            );
794        }
795    }
796
797    #[test]
798    fn is_ci_bootstrap_task_reads_the_body_marker() {
799        assert!(is_ci_bootstrap_task(&bootstrap_body()));
800        assert!(is_ci_bootstrap_task(&format!("{CI_BOOTSTRAP_MARKER}\n")));
801        assert!(is_ci_bootstrap_task("goal\n<!-- orch-plan: CI-01 -->"));
802        assert!(!is_ci_bootstrap_task(""));
803        assert!(!is_ci_bootstrap_task("goal"));
804    }
805
806    #[test]
807    fn checks_ready_for_ruleset_splits_pending_failed_and_empty() {
808        assert_eq!(checks_ready_for_ruleset(&[], &[]), ChecksReady::Empty);
809        assert_eq!(
810            checks_ready_for_ruleset(&[run("test", "in_progress", None, None)], &[]),
811            ChecksReady::Pending
812        );
813        assert_eq!(
814            checks_ready_for_ruleset(&[run("test", "completed", Some("failure"), None)], &[]),
815            ChecksReady::Failed(vec![FailedCheck {
816                name: "test".to_string(),
817                conclusion: "failure".to_string(),
818            }])
819        );
820        assert_eq!(
821            checks_ready_for_ruleset(
822                &[run("deploy", "completed", Some("action_required"), None)],
823                &[]
824            ),
825            ChecksReady::Pending
826        );
827        assert_eq!(
828            checks_ready_for_ruleset(
829                &[
830                    run("test", "completed", Some("success"), None),
831                    run("deploy", "completed", Some("action_required"), None),
832                ],
833                &[]
834            ),
835            ChecksReady::Pending
836        );
837        assert_eq!(
838            checks_ready_for_ruleset(&[run("test", "completed", Some("cancelled"), None)], &[]),
839            ChecksReady::Failed(vec![FailedCheck {
840                name: "test".to_string(),
841                conclusion: "cancelled".to_string(),
842            }])
843        );
844        assert_eq!(
845            checks_ready_for_ruleset(&[], &[("ci/test".to_string(), "failure".to_string())]),
846            ChecksReady::Failed(vec![FailedCheck {
847                name: "ci/test".to_string(),
848                conclusion: "failure".to_string(),
849            }])
850        );
851        assert_eq!(
852            checks_ready_for_ruleset(&[run("test", "completed", Some("skipped"), None)], &[]),
853            ChecksReady::Empty
854        );
855        assert_eq!(
856            checks_ready_for_ruleset(
857                &[run("orch/review", "completed", Some("success"), None)],
858                &[]
859            ),
860            ChecksReady::Empty
861        );
862        assert_eq!(
863            checks_ready_for_ruleset(
864                &[
865                    run("test", "completed", Some("failure"), None),
866                    run("lint", "in_progress", None, None),
867                ],
868                &[]
869            ),
870            ChecksReady::Failed(vec![FailedCheck {
871                name: "test".to_string(),
872                conclusion: "failure".to_string(),
873            }])
874        );
875        let ChecksReady::Ready(ready) = checks_ready_for_ruleset(
876            &[
877                run("test", "completed", Some("success"), Some(15368)),
878                run("review-gate", "completed", Some("success"), None),
879            ],
880            &[],
881        ) else {
882            panic!("expected ready checks");
883        };
884        assert_eq!(
885            ready,
886            vec![RequiredStatusCheck {
887                context: "test".to_string(),
888                integration_id: Some(15368),
889            }]
890        );
891    }
892
893    #[test]
894    fn required_contexts_cover_matches_by_context_name() {
895        let required = vec![RequiredStatusCheck {
896            context: "cla/check".to_string(),
897            integration_id: None,
898        }];
899        let needed = vec![RequiredStatusCheck {
900            context: "test".to_string(),
901            integration_id: Some(15368),
902        }];
903        assert!(!required_contexts_cover(&required, &needed));
904        let required = vec![
905            RequiredStatusCheck {
906                context: "cla/check".to_string(),
907                integration_id: None,
908            },
909            RequiredStatusCheck {
910                context: "test".to_string(),
911                integration_id: None,
912            },
913        ];
914        assert!(required_contexts_cover(&required, &needed));
915    }
916
917    #[test]
918    fn merge_missing_checks_appends_contexts_the_ruleset_lacks() {
919        let existing = vec![RequiredStatusCheck {
920            context: "cla/check".to_string(),
921            integration_id: None,
922        }];
923        let needed = vec![
924            RequiredStatusCheck {
925                context: "cla/check".to_string(),
926                integration_id: Some(1),
927            },
928            RequiredStatusCheck {
929                context: "test".to_string(),
930                integration_id: Some(15368),
931            },
932        ];
933        assert_eq!(
934            merge_missing_checks(existing, &needed),
935            vec![
936                RequiredStatusCheck {
937                    context: "cla/check".to_string(),
938                    integration_id: None,
939                },
940                RequiredStatusCheck {
941                    context: "test".to_string(),
942                    integration_id: Some(15368),
943                },
944            ]
945        );
946    }
947
948    #[tokio::test]
949    async fn hold_after_merge_records_pending_for_a_bootstrap_task() {
950        let store = Arc::new(TaskStore::open_memory().await.unwrap());
951        let task = ExternalTask {
952            id: ExternalId("12".to_string()),
953            title: "CI-01 Set up CI and tests".to_string(),
954            body: bootstrap_body(),
955            state: "open".to_string(),
956            labels: vec![],
957            author: String::new(),
958            created_at: String::new(),
959            updated_at: String::new(),
960            url: String::new(),
961        };
962        assert!(hold_after_merge(&task, &store, "o/r").await);
963        assert_eq!(
964            store.kv_get(&kv_key("o/r", "12")).await.unwrap().as_deref(),
965            Some(KV_PENDING)
966        );
967        store
968            .kv_set(&kv_key("o/r", "12"), KV_APPLIED)
969            .await
970            .unwrap();
971        assert!(!hold_after_merge(&task, &store, "o/r").await);
972    }
973
974    #[tokio::test]
975    async fn hold_after_merge_skips_a_title_without_a_plan_marker() {
976        let store = Arc::new(TaskStore::open_memory().await.unwrap());
977        let task = ExternalTask {
978            id: ExternalId("12".to_string()),
979            title: "CI-01 Set up CI and tests".to_string(),
980            body: "ordinary issue".to_string(),
981            state: "open".to_string(),
982            labels: vec![],
983            author: String::new(),
984            created_at: String::new(),
985            updated_at: String::new(),
986            url: String::new(),
987        };
988        assert!(!hold_after_merge(&task, &store, "o/r").await);
989        assert!(store.kv_get(&kv_key("o/r", "12")).await.unwrap().is_none());
990    }
991
992    #[tokio::test]
993    async fn apply_pending_dones_when_required_checks_already_cover_default_branch_checks() {
994        let _token = EnvVarGuard::set("GH_TOKEN", "test_token");
995        let server = MockServer::start().await;
996        mock_classic_required(&server, "test", "deadbeef").await;
997        mock_runs_and_empty_status(
998            &server,
999            "deadbeef",
1000            serde_json::json!([{
1001                "id": 1,
1002                "name": "test",
1003                "status": "completed",
1004                "conclusion": "success",
1005                "app": { "id": 15368 }
1006            }]),
1007        )
1008        .await;
1009        Mock::given(method("POST"))
1010            .and(path("/repos/o/r/rulesets"))
1011            .respond_with(ResponseTemplate::new(201).set_body_json(serde_json::json!({
1012                "id": 9
1013            })))
1014            .expect(0)
1015            .mount(&server)
1016            .await;
1017
1018        let (store, task_manager, id) = pending_store().await;
1019        let gh = GhHttp::for_test(server.uri(), None);
1020        apply_pending_with(&gh, &store, &task_manager, "o/r")
1021            .await
1022            .unwrap();
1023
1024        let stored = store.get(id).await.unwrap();
1025        assert_eq!(stored.status, TaskStatus::Done);
1026        assert_eq!(
1027            store.kv_get(&kv_key("o/r", "12")).await.unwrap().as_deref(),
1028            Some(KV_APPLIED)
1029        );
1030    }
1031
1032    #[tokio::test]
1033    async fn apply_pending_creates_a_ruleset_when_an_unrelated_required_check_exists() {
1034        let _token = EnvVarGuard::set("GH_TOKEN", "test_token");
1035        let server = MockServer::start().await;
1036        mock_classic_required(&server, "cla/check", "deadbeef").await;
1037        mock_runs_and_empty_status(
1038            &server,
1039            "deadbeef",
1040            serde_json::json!([{
1041                "id": 1,
1042                "name": "test",
1043                "status": "completed",
1044                "conclusion": "success",
1045                "app": { "id": 15368 }
1046            }]),
1047        )
1048        .await;
1049        Mock::given(method("POST"))
1050            .and(path("/repos/o/r/rulesets"))
1051            .respond_with(ResponseTemplate::new(201).set_body_json(serde_json::json!({
1052                "id": 9,
1053                "name": REQUIRED_CHECK_RULESET_NAME
1054            })))
1055            .expect(1)
1056            .mount(&server)
1057            .await;
1058
1059        let (store, task_manager, id) = pending_store().await;
1060        let gh = GhHttp::for_test(server.uri(), None);
1061        apply_pending_with(&gh, &store, &task_manager, "o/r")
1062            .await
1063            .unwrap();
1064
1065        let stored = store.get(id).await.unwrap();
1066        assert_eq!(stored.status, TaskStatus::Done);
1067        assert_eq!(
1068            store.kv_get(&kv_key("o/r", "12")).await.unwrap().as_deref(),
1069            Some(KV_APPLIED)
1070        );
1071    }
1072
1073    #[tokio::test]
1074    async fn apply_pending_holds_when_an_unrelated_required_check_exists_and_checks_are_pending() {
1075        let _token = EnvVarGuard::set("GH_TOKEN", "test_token");
1076        let server = MockServer::start().await;
1077        mock_classic_required(&server, "cla/check", "deadbeef").await;
1078        mock_runs_and_empty_status(
1079            &server,
1080            "deadbeef",
1081            serde_json::json!([{
1082                "id": 1,
1083                "name": "test",
1084                "status": "in_progress",
1085                "conclusion": null,
1086                "app": { "id": 15368 }
1087            }]),
1088        )
1089        .await;
1090        Mock::given(method("POST"))
1091            .and(path("/repos/o/r/rulesets"))
1092            .respond_with(ResponseTemplate::new(201).set_body_json(serde_json::json!({
1093                "id": 9
1094            })))
1095            .expect(0)
1096            .mount(&server)
1097            .await;
1098
1099        let (store, task_manager, id) = pending_store().await;
1100        let gh = GhHttp::for_test(server.uri(), None);
1101        apply_pending_with(&gh, &store, &task_manager, "o/r")
1102            .await
1103            .unwrap();
1104
1105        let stored = store.get(id).await.unwrap();
1106        assert_eq!(stored.status, TaskStatus::Approved);
1107        assert_eq!(
1108            store.kv_get(&kv_key("o/r", "12")).await.unwrap().as_deref(),
1109            Some(KV_PENDING)
1110        );
1111    }
1112
1113    #[tokio::test]
1114    async fn apply_pending_dones_when_name_taken_and_orch_ruleset_lists_the_checks() {
1115        let _token = EnvVarGuard::set("GH_TOKEN", "test_token");
1116        let server = MockServer::start().await;
1117        mock_unprotected_main(&server, "deadbeef").await;
1118        mock_runs_and_empty_status(
1119            &server,
1120            "deadbeef",
1121            serde_json::json!([{
1122                "id": 1,
1123                "name": "test",
1124                "status": "completed",
1125                "conclusion": "success",
1126                "app": { "id": 15368 }
1127            }]),
1128        )
1129        .await;
1130        mock_name_taken_ruleset(
1131            &server,
1132            serde_json::json!([{ "context": "test", "integration_id": 15368 }]),
1133        )
1134        .await;
1135        Mock::given(method("PUT"))
1136            .and(path("/repos/o/r/rulesets/9"))
1137            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
1138                "id": 9
1139            })))
1140            .expect(0)
1141            .mount(&server)
1142            .await;
1143
1144        let (store, task_manager, id) = pending_store().await;
1145        let gh = GhHttp::for_test(server.uri(), None);
1146        apply_pending_with(&gh, &store, &task_manager, "o/r")
1147            .await
1148            .unwrap();
1149
1150        let stored = store.get(id).await.unwrap();
1151        assert_eq!(stored.status, TaskStatus::Done);
1152        assert_eq!(
1153            store.kv_get(&kv_key("o/r", "12")).await.unwrap().as_deref(),
1154            Some(KV_APPLIED)
1155        );
1156    }
1157
1158    #[tokio::test]
1159    async fn apply_pending_updates_the_orch_ruleset_when_name_taken_and_checks_are_missing() {
1160        let _token = EnvVarGuard::set("GH_TOKEN", "test_token");
1161        let server = MockServer::start().await;
1162        mock_unprotected_main(&server, "deadbeef").await;
1163        mock_runs_and_empty_status(
1164            &server,
1165            "deadbeef",
1166            serde_json::json!([{
1167                "id": 1,
1168                "name": "test",
1169                "status": "completed",
1170                "conclusion": "success",
1171                "app": { "id": 15368 }
1172            }]),
1173        )
1174        .await;
1175        mock_name_taken_ruleset(&server, serde_json::json!([{ "context": "cla/check" }])).await;
1176        Mock::given(method("PUT"))
1177            .and(path("/repos/o/r/rulesets/9"))
1178            .and(body_partial_json(serde_json::json!({
1179                "name": REQUIRED_CHECK_RULESET_NAME,
1180                "rules": [{
1181                    "type": "required_status_checks",
1182                    "parameters": {
1183                        "required_status_checks": [
1184                            { "context": "cla/check" },
1185                            { "context": "test", "integration_id": 15368 }
1186                        ]
1187                    }
1188                }]
1189            })))
1190            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
1191                "id": 9,
1192                "name": REQUIRED_CHECK_RULESET_NAME
1193            })))
1194            .expect(1)
1195            .mount(&server)
1196            .await;
1197
1198        let (store, task_manager, id) = pending_store().await;
1199        let gh = GhHttp::for_test(server.uri(), None);
1200        apply_pending_with(&gh, &store, &task_manager, "o/r")
1201            .await
1202            .unwrap();
1203
1204        let stored = store.get(id).await.unwrap();
1205        assert_eq!(stored.status, TaskStatus::Done);
1206        assert_eq!(
1207            store.kv_get(&kv_key("o/r", "12")).await.unwrap().as_deref(),
1208            Some(KV_APPLIED)
1209        );
1210    }
1211
1212    #[tokio::test]
1213    async fn apply_pending_creates_a_ruleset_when_default_branch_checks_pass() {
1214        let _token = EnvVarGuard::set("GH_TOKEN", "test_token");
1215        let server = MockServer::start().await;
1216        Mock::given(method("GET"))
1217            .and(path("/repos/o/r"))
1218            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
1219                "default_branch": "main"
1220            })))
1221            .mount(&server)
1222            .await;
1223        Mock::given(method("GET"))
1224            .and(path("/repos/o/r/branches/main/protection"))
1225            .respond_with(
1226                ResponseTemplate::new(404)
1227                    .set_body_string("{\"message\":\"Branch not protected\"}"),
1228            )
1229            .mount(&server)
1230            .await;
1231        Mock::given(method("GET"))
1232            .and(path("/repos/o/r/rules/branches/main"))
1233            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([])))
1234            .mount(&server)
1235            .await;
1236        Mock::given(method("GET"))
1237            .and(path("/repos/o/r/branches/main"))
1238            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
1239                "commit": { "sha": "deadbeef" }
1240            })))
1241            .mount(&server)
1242            .await;
1243        Mock::given(method("GET"))
1244            .and(path("/repos/o/r/commits/deadbeef/check-runs"))
1245            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
1246                "total_count": 1,
1247                "check_runs": [{
1248                    "id": 1,
1249                    "name": "test",
1250                    "status": "completed",
1251                    "conclusion": "success",
1252                    "app": { "id": 15368 }
1253                }]
1254            })))
1255            .mount(&server)
1256            .await;
1257        Mock::given(method("GET"))
1258            .and(path("/repos/o/r/commits/deadbeef/status"))
1259            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
1260                "state": "success",
1261                "total_count": 0,
1262                "statuses": []
1263            })))
1264            .mount(&server)
1265            .await;
1266        Mock::given(method("POST"))
1267            .and(path("/repos/o/r/rulesets"))
1268            .respond_with(ResponseTemplate::new(201).set_body_json(serde_json::json!({
1269                "id": 9,
1270                "name": "orch required checks"
1271            })))
1272            .expect(1)
1273            .mount(&server)
1274            .await;
1275
1276        let store = Arc::new(TaskStore::open_memory().await.unwrap());
1277        let backend: Arc<dyn ExternalBackend> = Arc::new(NoopBackend);
1278        let task_manager = Arc::new(TaskManager::with_store(
1279            backend,
1280            Arc::clone(&store),
1281            "o/r".to_string(),
1282        ));
1283        let id = store
1284            .upsert_external(&UpsertExternal {
1285                repo: "o/r",
1286                ext_id: "12",
1287                title: "CI-01 Set up CI and tests",
1288                body: &bootstrap_body(),
1289                author: "u",
1290                url: "",
1291                labels: &[],
1292                origin: "github",
1293            })
1294            .await
1295            .unwrap();
1296        store.update_status(id, TaskStatus::Approved).await.unwrap();
1297        store
1298            .kv_set(&kv_key("o/r", "12"), KV_PENDING)
1299            .await
1300            .unwrap();
1301
1302        let gh = GhHttp::for_test(server.uri(), None);
1303        apply_pending_with(&gh, &store, &task_manager, "o/r")
1304            .await
1305            .unwrap();
1306
1307        let stored = store.get(id).await.unwrap();
1308        assert_eq!(stored.status, TaskStatus::Done);
1309        assert_eq!(
1310            store.kv_get(&kv_key("o/r", "12")).await.unwrap().as_deref(),
1311            Some(KV_APPLIED)
1312        );
1313    }
1314
1315    #[tokio::test]
1316    async fn apply_pending_comments_and_holds_when_github_refuses_the_ruleset() {
1317        let _token = EnvVarGuard::set("GH_TOKEN", "test_token");
1318        let server = MockServer::start().await;
1319        Mock::given(method("GET"))
1320            .and(path("/repos/o/r"))
1321            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
1322                "default_branch": "main"
1323            })))
1324            .mount(&server)
1325            .await;
1326        Mock::given(method("GET"))
1327            .and(path("/repos/o/r/branches/main/protection"))
1328            .respond_with(
1329                ResponseTemplate::new(404)
1330                    .set_body_string("{\"message\":\"Branch not protected\"}"),
1331            )
1332            .mount(&server)
1333            .await;
1334        Mock::given(method("GET"))
1335            .and(path("/repos/o/r/rules/branches/main"))
1336            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([])))
1337            .mount(&server)
1338            .await;
1339        Mock::given(method("GET"))
1340            .and(path("/repos/o/r/branches/main"))
1341            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
1342                "commit": { "sha": "deadbeef" }
1343            })))
1344            .mount(&server)
1345            .await;
1346        Mock::given(method("GET"))
1347            .and(path("/repos/o/r/commits/deadbeef/check-runs"))
1348            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
1349                "total_count": 1,
1350                "check_runs": [{
1351                    "id": 1,
1352                    "name": "test",
1353                    "status": "completed",
1354                    "conclusion": "success",
1355                    "app": { "id": 15368 }
1356                }]
1357            })))
1358            .mount(&server)
1359            .await;
1360        Mock::given(method("GET"))
1361            .and(path("/repos/o/r/commits/deadbeef/status"))
1362            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
1363                "state": "success",
1364                "total_count": 0,
1365                "statuses": []
1366            })))
1367            .mount(&server)
1368            .await;
1369        Mock::given(method("POST"))
1370            .and(path("/repos/o/r/rulesets"))
1371            .respond_with(ResponseTemplate::new(403).set_body_json(serde_json::json!({
1372                "message": "Upgrade to GitHub Pro or make this repository public to enable this feature."
1373            })))
1374            .mount(&server)
1375            .await;
1376        Mock::given(method("POST"))
1377            .and(path("/repos/o/r/issues/12/comments"))
1378            .respond_with(ResponseTemplate::new(201).set_body_json(serde_json::json!({
1379                "id": 1
1380            })))
1381            .expect(1)
1382            .mount(&server)
1383            .await;
1384
1385        let store = Arc::new(TaskStore::open_memory().await.unwrap());
1386        let backend: Arc<dyn ExternalBackend> = Arc::new(NoopBackend);
1387        let task_manager = Arc::new(TaskManager::with_store(
1388            backend,
1389            Arc::clone(&store),
1390            "o/r".to_string(),
1391        ));
1392        let id = store
1393            .upsert_external(&UpsertExternal {
1394                repo: "o/r",
1395                ext_id: "12",
1396                title: "CI-01 Set up CI and tests",
1397                body: &bootstrap_body(),
1398                author: "u",
1399                url: "",
1400                labels: &[],
1401                origin: "github",
1402            })
1403            .await
1404            .unwrap();
1405        store.update_status(id, TaskStatus::Approved).await.unwrap();
1406        store
1407            .kv_set(&kv_key("o/r", "12"), KV_PENDING)
1408            .await
1409            .unwrap();
1410
1411        let gh = GhHttp::for_test(server.uri(), None);
1412        apply_pending_with(&gh, &store, &task_manager, "o/r")
1413            .await
1414            .unwrap();
1415
1416        let stored = store.get(id).await.unwrap();
1417        assert_eq!(stored.status, TaskStatus::Approved);
1418        assert_eq!(
1419            store.kv_get(&kv_key("o/r", "12")).await.unwrap().as_deref(),
1420            Some(KV_REFUSED)
1421        );
1422    }
1423
1424    #[tokio::test]
1425    async fn apply_pending_holds_when_ruleset_create_is_unrecognized_even_with_401_digits() {
1426        let _token = EnvVarGuard::set("GH_TOKEN", "test_token");
1427        let server = MockServer::start().await;
1428        mock_unprotected_main(&server, "deadbeef").await;
1429        mock_runs_and_empty_status(
1430            &server,
1431            "deadbeef",
1432            serde_json::json!([{
1433                "id": 1,
1434                "name": "test",
1435                "status": "completed",
1436                "conclusion": "success",
1437                "app": { "id": 15368 }
1438            }]),
1439        )
1440        .await;
1441        Mock::given(method("POST"))
1442            .and(path("/repos/o/r/rulesets"))
1443            .respond_with(ResponseTemplate::new(422).set_body_json(serde_json::json!({
1444                "message": "Ruleset validation failed for rule 401"
1445            })))
1446            .mount(&server)
1447            .await;
1448        mock_issue_comment(&server, 0).await;
1449
1450        let (store, task_manager, id) = pending_store().await;
1451        let gh = GhHttp::for_test(server.uri(), None);
1452        apply_pending_with(&gh, &store, &task_manager, "o/r")
1453            .await
1454            .unwrap();
1455        apply_pending_with(&gh, &store, &task_manager, "o/r")
1456            .await
1457            .unwrap();
1458
1459        let stored = store.get(id).await.unwrap();
1460        assert_eq!(stored.status, TaskStatus::Approved);
1461        assert_eq!(
1462            store.kv_get(&kv_key("o/r", "12")).await.unwrap().as_deref(),
1463            Some(KV_PENDING)
1464        );
1465    }
1466
1467    #[tokio::test]
1468    async fn apply_pending_reopens_a_closed_issue_and_creates_the_ruleset() {
1469        let _token = EnvVarGuard::set("GH_TOKEN", "test_token");
1470        let server = MockServer::start().await;
1471        Mock::given(method("GET"))
1472            .and(path("/repos/o/r"))
1473            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
1474                "default_branch": "main"
1475            })))
1476            .mount(&server)
1477            .await;
1478        Mock::given(method("GET"))
1479            .and(path("/repos/o/r/branches/main/protection"))
1480            .respond_with(
1481                ResponseTemplate::new(404)
1482                    .set_body_string("{\"message\":\"Branch not protected\"}"),
1483            )
1484            .mount(&server)
1485            .await;
1486        Mock::given(method("GET"))
1487            .and(path("/repos/o/r/rules/branches/main"))
1488            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([])))
1489            .mount(&server)
1490            .await;
1491        Mock::given(method("GET"))
1492            .and(path("/repos/o/r/issues/12"))
1493            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
1494                "number": 12,
1495                "id": 120,
1496                "title": "CI-01 Set up CI and tests",
1497                "body": "",
1498                "state": "closed",
1499                "labels": [],
1500                "user": { "login": "u" },
1501                "created_at": "",
1502                "updated_at": "",
1503                "html_url": ""
1504            })))
1505            .mount(&server)
1506            .await;
1507        Mock::given(method("PATCH"))
1508            .and(path("/repos/o/r/issues/12"))
1509            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
1510                "number": 12,
1511                "id": 120,
1512                "title": "CI-01 Set up CI and tests",
1513                "body": "",
1514                "state": "open",
1515                "labels": [],
1516                "user": { "login": "u" },
1517                "created_at": "",
1518                "updated_at": "",
1519                "html_url": ""
1520            })))
1521            .expect(1)
1522            .mount(&server)
1523            .await;
1524        Mock::given(method("GET"))
1525            .and(path("/repos/o/r/branches/main"))
1526            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
1527                "commit": { "sha": "deadbeef" }
1528            })))
1529            .mount(&server)
1530            .await;
1531        Mock::given(method("GET"))
1532            .and(path("/repos/o/r/commits/deadbeef/check-runs"))
1533            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
1534                "total_count": 1,
1535                "check_runs": [{
1536                    "id": 1,
1537                    "name": "test",
1538                    "status": "completed",
1539                    "conclusion": "success",
1540                    "app": { "id": 15368 }
1541                }]
1542            })))
1543            .mount(&server)
1544            .await;
1545        Mock::given(method("GET"))
1546            .and(path("/repos/o/r/commits/deadbeef/status"))
1547            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
1548                "state": "success",
1549                "total_count": 0,
1550                "statuses": []
1551            })))
1552            .mount(&server)
1553            .await;
1554        Mock::given(method("POST"))
1555            .and(path("/repos/o/r/rulesets"))
1556            .respond_with(ResponseTemplate::new(201).set_body_json(serde_json::json!({
1557                "id": 9,
1558                "name": "orch required checks"
1559            })))
1560            .expect(1)
1561            .mount(&server)
1562            .await;
1563
1564        let store = Arc::new(TaskStore::open_memory().await.unwrap());
1565        let backend: Arc<dyn ExternalBackend> = Arc::new(NoopBackend);
1566        let task_manager = Arc::new(TaskManager::with_store(
1567            backend,
1568            Arc::clone(&store),
1569            "o/r".to_string(),
1570        ));
1571        let id = store
1572            .upsert_external(&UpsertExternal {
1573                repo: "o/r",
1574                ext_id: "12",
1575                title: "CI-01 Set up CI and tests",
1576                body: &bootstrap_body(),
1577                author: "u",
1578                url: "",
1579                labels: &[],
1580                origin: "github",
1581            })
1582            .await
1583            .unwrap();
1584        store.update_status(id, TaskStatus::Done).await.unwrap();
1585        store
1586            .kv_set(&kv_key("o/r", "12"), KV_PENDING)
1587            .await
1588            .unwrap();
1589
1590        let gh = GhHttp::for_test(server.uri(), None);
1591        apply_pending_with(&gh, &store, &task_manager, "o/r")
1592            .await
1593            .unwrap();
1594
1595        let stored = store.get(id).await.unwrap();
1596        assert_eq!(stored.status, TaskStatus::Done);
1597        assert_eq!(
1598            store.kv_get(&kv_key("o/r", "12")).await.unwrap().as_deref(),
1599            Some(KV_APPLIED)
1600        );
1601    }
1602
1603    #[tokio::test]
1604    async fn apply_pending_logs_and_holds_while_default_branch_checks_run() {
1605        let _token = EnvVarGuard::set("GH_TOKEN", "test_token");
1606        let server = MockServer::start().await;
1607        mock_unprotected_main(&server, "deadbeef").await;
1608        mock_runs_and_empty_status(
1609            &server,
1610            "deadbeef",
1611            serde_json::json!([{
1612                "id": 1,
1613                "name": "test",
1614                "status": "in_progress",
1615                "conclusion": null,
1616                "app": { "id": 15368 }
1617            }]),
1618        )
1619        .await;
1620        mock_issue_comment(&server, 0).await;
1621        Mock::given(method("POST"))
1622            .and(path("/repos/o/r/rulesets"))
1623            .respond_with(ResponseTemplate::new(201).set_body_json(serde_json::json!({
1624                "id": 9
1625            })))
1626            .expect(0)
1627            .mount(&server)
1628            .await;
1629
1630        let (store, task_manager, id) = pending_store().await;
1631        let gh = GhHttp::for_test(server.uri(), None);
1632        apply_pending_with(&gh, &store, &task_manager, "o/r")
1633            .await
1634            .unwrap();
1635
1636        let stored = store.get(id).await.unwrap();
1637        assert_eq!(stored.status, TaskStatus::Approved);
1638        assert_eq!(
1639            store.kv_get(&kv_key("o/r", "12")).await.unwrap().as_deref(),
1640            Some(KV_PENDING)
1641        );
1642    }
1643
1644    #[tokio::test]
1645    async fn apply_pending_comments_and_routes_when_default_branch_checks_fail() {
1646        let _token = EnvVarGuard::set("GH_TOKEN", "test_token");
1647        let server = MockServer::start().await;
1648        mock_unprotected_main(&server, "deadbeef").await;
1649        mock_runs_and_empty_status(
1650            &server,
1651            "deadbeef",
1652            serde_json::json!([{
1653                "id": 1,
1654                "name": "test",
1655                "status": "completed",
1656                "conclusion": "failure",
1657                "app": { "id": 15368 }
1658            }]),
1659        )
1660        .await;
1661        mock_issue_comment(&server, 1).await;
1662
1663        let (store, task_manager, id) = pending_store().await;
1664        let gh = GhHttp::for_test(server.uri(), None);
1665        apply_pending_with(&gh, &store, &task_manager, "o/r")
1666            .await
1667            .unwrap();
1668
1669        let stored = store.get(id).await.unwrap();
1670        assert_eq!(stored.status, TaskStatus::Routed);
1671        assert_eq!(stored.ci_merge_failures, 1);
1672        assert!(stored.last_error.contains("test: failure"));
1673        assert_eq!(
1674            store.kv_get(&kv_key("o/r", "12")).await.unwrap().as_deref(),
1675            Some(KV_PENDING)
1676        );
1677
1678        apply_pending_with(&gh, &store, &task_manager, "o/r")
1679            .await
1680            .unwrap();
1681        let stored = store.get(id).await.unwrap();
1682        assert_eq!(stored.status, TaskStatus::Routed);
1683        assert_eq!(stored.ci_merge_failures, 1);
1684    }
1685
1686    #[tokio::test]
1687    async fn apply_pending_blocks_after_max_failed_default_branch_heads() {
1688        let _token = EnvVarGuard::set("GH_TOKEN", "test_token");
1689        let server = MockServer::start().await;
1690        mock_unprotected_main(&server, "deadbeef").await;
1691        mock_runs_and_empty_status(
1692            &server,
1693            "deadbeef",
1694            serde_json::json!([{
1695                "id": 1,
1696                "name": "test",
1697                "status": "completed",
1698                "conclusion": "cancelled",
1699                "app": { "id": 15368 }
1700            }]),
1701        )
1702        .await;
1703        mock_issue_comment(&server, 1).await;
1704
1705        let (store, task_manager, id) = pending_store().await;
1706        store.increment(id, "ci_merge_failures").await.unwrap();
1707        store.increment(id, "ci_merge_failures").await.unwrap();
1708        let gh = GhHttp::for_test(server.uri(), None);
1709        apply_pending_with(&gh, &store, &task_manager, "o/r")
1710            .await
1711            .unwrap();
1712
1713        let stored = store.get(id).await.unwrap();
1714        assert_eq!(stored.status, TaskStatus::Blocked);
1715        assert_eq!(
1716            stored.ci_merge_failures,
1717            i32::try_from(ci::MAX_CI_MERGE_FAILURES).unwrap()
1718        );
1719        assert!(
1720            stored
1721                .block_reason
1722                .as_deref()
1723                .unwrap_or("")
1724                .contains("CI failure limit")
1725        );
1726    }
1727
1728    #[tokio::test]
1729    async fn apply_pending_waits_before_commenting_when_no_check_starts() {
1730        let _token = EnvVarGuard::set("GH_TOKEN", "test_token");
1731        let server = MockServer::start().await;
1732        mock_unprotected_main(&server, "deadbeef").await;
1733        mock_runs_and_empty_status(&server, "deadbeef", serde_json::json!([])).await;
1734        mock_issue_comment(&server, 0).await;
1735
1736        let (store, task_manager, id) = pending_store().await;
1737        let gh = GhHttp::for_test(server.uri(), None);
1738        apply_pending_with(&gh, &store, &task_manager, "o/r")
1739            .await
1740            .unwrap();
1741
1742        let stored = store.get(id).await.unwrap();
1743        assert_eq!(stored.status, TaskStatus::Approved);
1744        assert!(
1745            store
1746                .kv_get("ci_bootstrap_wait_since:o/r#12#deadbeef")
1747                .await
1748                .unwrap()
1749                .is_some()
1750        );
1751        assert!(
1752            store
1753                .kv_get(&no_checks_comment_key("o/r", "12", "deadbeef"))
1754                .await
1755                .unwrap()
1756                .is_none()
1757        );
1758    }
1759
1760    #[tokio::test]
1761    async fn apply_pending_comments_once_when_no_check_starts_after_the_wait() {
1762        let _token = EnvVarGuard::set("GH_TOKEN", "test_token");
1763        let server = MockServer::start().await;
1764        mock_unprotected_main(&server, "deadbeef").await;
1765        mock_runs_and_empty_status(&server, "deadbeef", serde_json::json!([])).await;
1766        mock_issue_comment(&server, 1).await;
1767
1768        let (store, task_manager, id) = pending_store().await;
1769        let started = chrono::Utc::now().timestamp() - gate::NO_CHECKS_WAIT_SECS - 1;
1770        store
1771            .kv_set(
1772                "ci_bootstrap_wait_since:o/r#12#deadbeef",
1773                &started.to_string(),
1774            )
1775            .await
1776            .unwrap();
1777        let gh = GhHttp::for_test(server.uri(), None);
1778        apply_pending_with(&gh, &store, &task_manager, "o/r")
1779            .await
1780            .unwrap();
1781
1782        let stored = store.get(id).await.unwrap();
1783        assert_eq!(stored.status, TaskStatus::Approved);
1784        assert_eq!(
1785            store
1786                .kv_get(&no_checks_comment_key("o/r", "12", "deadbeef"))
1787                .await
1788                .unwrap()
1789                .as_deref(),
1790            Some("1")
1791        );
1792
1793        apply_pending_with(&gh, &store, &task_manager, "o/r")
1794            .await
1795            .unwrap();
1796        assert_eq!(store.get(id).await.unwrap().status, TaskStatus::Approved);
1797    }
1798
1799    #[tokio::test]
1800    async fn apply_pending_comments_once_when_github_says_the_check_never_ran() {
1801        let _token = EnvVarGuard::set("GH_TOKEN", "test_token");
1802        let server = MockServer::start().await;
1803        mock_unprotected_main(&server, "deadbeef").await;
1804        mock_runs_and_empty_status(
1805            &server,
1806            "deadbeef",
1807            serde_json::json!([{
1808                "id": 1,
1809                "name": "test",
1810                "status": "completed",
1811                "conclusion": "success",
1812                "app": { "id": 15368 }
1813            }]),
1814        )
1815        .await;
1816        Mock::given(method("POST"))
1817            .and(path("/repos/o/r/rulesets"))
1818            .respond_with(ResponseTemplate::new(422).set_body_json(serde_json::json!({
1819                "message": "test was not a valid check"
1820            })))
1821            .mount(&server)
1822            .await;
1823        mock_issue_comment(&server, 1).await;
1824
1825        let (store, task_manager, id) = pending_store().await;
1826        let gh = GhHttp::for_test(server.uri(), None);
1827        apply_pending_with(&gh, &store, &task_manager, "o/r")
1828            .await
1829            .unwrap();
1830        apply_pending_with(&gh, &store, &task_manager, "o/r")
1831            .await
1832            .unwrap();
1833
1834        let stored = store.get(id).await.unwrap();
1835        assert_eq!(stored.status, TaskStatus::Approved);
1836        assert_eq!(
1837            store.kv_get(&kv_key("o/r", "12")).await.unwrap().as_deref(),
1838            Some(KV_PENDING)
1839        );
1840        assert_eq!(
1841            store
1842                .kv_get(&never_run_comment_key("o/r", "12"))
1843                .await
1844                .unwrap()
1845                .as_deref(),
1846            Some("1")
1847        );
1848    }
1849}