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    comment_issue(
434        gh,
435        repo,
436        task_id,
437        &format!(
438            "Default-branch checks failed after the CI bootstrap merge ({details}). Later tasks stay waiting until those checks pass."
439        ),
440    )
441    .await;
442
443    let max = ci::MAX_CI_MERGE_FAILURES;
444    let id = ExternalId(task_id.to_string());
445    if failures >= max {
446        tracing::error!(
447            task_id,
448            failures,
449            details,
450            "CI bootstrap default-branch checks failed, CI failure limit reached"
451        );
452        let fields = [(
453            "block_reason",
454            serde_json::json!(format!(
455                "CI failure limit ({max}) reached after the CI bootstrap merge"
456            )),
457        )];
458        if let Err(e) = task_manager
459            .update_task_status_and_result(&id, Status::Blocked, &fields)
460            .await
461        {
462            tracing::error!(
463                task_id,
464                err = %e,
465                "failed to block CI bootstrap after failed default-branch checks"
466            );
467        }
468    } else {
469        tracing::warn!(
470            task_id,
471            failures,
472            details,
473            "CI bootstrap default-branch checks failed, routing back to the task agent"
474        );
475        let fields = [
476            (
477                "last_error",
478                serde_json::json!(format!(
479                    "CI failed on the default branch after the CI bootstrap merge: {details}. Fix the failing checks"
480                )),
481            ),
482            (
483                "route_reason",
484                serde_json::json!("re-dispatch after CI bootstrap default-branch checks failed"),
485            ),
486        ];
487        if let Err(e) = task_manager
488            .update_task_status_and_result(&id, Status::Routed, &fields)
489            .await
490        {
491            tracing::error!(
492                task_id,
493                err = %e,
494                "failed to re-route CI bootstrap after failed default-branch checks"
495            );
496        }
497    }
498    Ok(())
499}
500
501async fn comment_never_run_once(
502    gh: &GhHttp,
503    store: &Arc<TaskStore>,
504    repo: &str,
505    task_id: &str,
506    err: &str,
507) {
508    let key = never_run_comment_key(repo, task_id);
509    match store.kv_get(&key).await {
510        Ok(Some(_)) => return,
511        Ok(None) => {}
512        Err(e) => {
513            tracing::warn!(
514                task_id,
515                err = %e,
516                "failed to read CI bootstrap never-run comment key"
517            );
518            return;
519        }
520    }
521    comment_issue(
522        gh,
523        repo,
524        task_id,
525        &format!(
526            "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."
527        ),
528    )
529    .await;
530    if let Err(e) = store.kv_set(&key, "1").await {
531        tracing::warn!(
532            task_id,
533            err = %e,
534            "failed to record CI bootstrap never-run comment"
535        );
536    }
537}
538
539async fn comment_refused(gh: &GhHttp, repo: &str, task_id: &str, err: &str) {
540    comment_issue(
541        gh,
542        repo,
543        task_id,
544        &format!(
545            "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."
546        ),
547    )
548    .await;
549}
550
551async fn comment_issue(gh: &GhHttp, repo: &str, task_id: &str, message: &str) {
552    let body = format!("{message}{}", engine::orch_footer());
553    if let Err(e) = gh.add_comment(repo, task_id, &body).await {
554        tracing::warn!(
555            task_id,
556            err = %e,
557            "failed to comment on CI bootstrap issue"
558        );
559    }
560}
561
562#[cfg(test)]
563mod tests {
564    use super::*;
565    use crate::backends::ExternalBackend;
566    use crate::backends::test_helpers::NoopBackend;
567    use crate::github::http::{REQUIRED_CHECK_RULESET_NAME, classify_ruleset_create_error};
568    use crate::github::types::GitHubApp;
569    use crate::plan::{CI_BOOTSTRAP_MARKER, ci_bootstrap_task, issue_body};
570    use crate::store::TaskStatus;
571    use crate::store::UpsertExternal;
572    use std::env;
573    use std::ffi::OsString;
574    use wiremock::matchers::{body_partial_json, method, path};
575    use wiremock::{Mock, MockServer, ResponseTemplate};
576
577    struct EnvVarGuard {
578        key: &'static str,
579        previous: Option<OsString>,
580    }
581
582    impl EnvVarGuard {
583        fn set(key: &'static str, value: &str) -> Self {
584            let previous = env::var_os(key);
585            // SAFETY: nextest runs each test in its own process
586            unsafe { env::set_var(key, value) };
587            Self { key, previous }
588        }
589    }
590
591    impl Drop for EnvVarGuard {
592        fn drop(&mut self) {
593            match self.previous.take() {
594                // SAFETY: nextest runs each test in its own process
595                Some(value) => unsafe { env::set_var(self.key, value) },
596                // SAFETY: nextest runs each test in its own process
597                None => unsafe { env::remove_var(self.key) },
598            }
599        }
600    }
601
602    fn run(
603        name: &str,
604        status: &str,
605        conclusion: Option<&str>,
606        app_id: Option<i64>,
607    ) -> GitHubCheckRun {
608        GitHubCheckRun {
609            id: 1,
610            name: name.to_string(),
611            status: status.to_string(),
612            conclusion: conclusion.map(String::from),
613            app: app_id.map(|id| GitHubApp { id }),
614        }
615    }
616
617    fn bootstrap_body() -> String {
618        issue_body(
619            &ci_bootstrap_task(false),
620            "acme/app",
621            "main",
622            "docs/ROADMAP.md",
623        )
624    }
625
626    async fn pending_store() -> (Arc<TaskStore>, Arc<TaskManager>, i64) {
627        let store = Arc::new(TaskStore::open_memory().await.unwrap());
628        let backend: Arc<dyn ExternalBackend> = Arc::new(NoopBackend);
629        let task_manager = Arc::new(TaskManager::with_store(
630            backend,
631            Arc::clone(&store),
632            "o/r".to_string(),
633        ));
634        let id = store
635            .upsert_external(&UpsertExternal {
636                repo: "o/r",
637                ext_id: "12",
638                title: "CI-01 Set up CI and tests",
639                body: &bootstrap_body(),
640                author: "u",
641                url: "",
642                labels: &[],
643                origin: "github",
644            })
645            .await
646            .unwrap();
647        store.update_status(id, TaskStatus::Approved).await.unwrap();
648        store
649            .kv_set(&kv_key("o/r", "12"), KV_PENDING)
650            .await
651            .unwrap();
652        (store, task_manager, id)
653    }
654
655    async fn mock_unprotected_main(server: &MockServer, sha: &str) {
656        Mock::given(method("GET"))
657            .and(path("/repos/o/r"))
658            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
659                "default_branch": "main"
660            })))
661            .mount(server)
662            .await;
663        Mock::given(method("GET"))
664            .and(path("/repos/o/r/branches/main/protection"))
665            .respond_with(
666                ResponseTemplate::new(404)
667                    .set_body_string("{\"message\":\"Branch not protected\"}"),
668            )
669            .mount(server)
670            .await;
671        Mock::given(method("GET"))
672            .and(path("/repos/o/r/rules/branches/main"))
673            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([])))
674            .mount(server)
675            .await;
676        Mock::given(method("GET"))
677            .and(path("/repos/o/r/branches/main"))
678            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
679                "commit": { "sha": sha }
680            })))
681            .mount(server)
682            .await;
683    }
684
685    async fn mock_classic_required(server: &MockServer, context: &str, sha: &str) {
686        Mock::given(method("GET"))
687            .and(path("/repos/o/r"))
688            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
689                "default_branch": "main"
690            })))
691            .mount(server)
692            .await;
693        Mock::given(method("GET"))
694            .and(path("/repos/o/r/branches/main/protection"))
695            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
696                "required_status_checks": {
697                    "checks": [{ "context": context, "app_id": 15368 }]
698                }
699            })))
700            .mount(server)
701            .await;
702        Mock::given(method("GET"))
703            .and(path("/repos/o/r/rules/branches/main"))
704            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([])))
705            .mount(server)
706            .await;
707        Mock::given(method("GET"))
708            .and(path("/repos/o/r/branches/main"))
709            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
710                "commit": { "sha": sha }
711            })))
712            .mount(server)
713            .await;
714    }
715
716    async fn mock_name_taken_ruleset(server: &MockServer, ruleset_checks: serde_json::Value) {
717        Mock::given(method("POST"))
718            .and(path("/repos/o/r/rulesets"))
719            .respond_with(ResponseTemplate::new(422).set_body_json(serde_json::json!({
720                "message": "Name has already been taken"
721            })))
722            .expect(1)
723            .mount(server)
724            .await;
725        Mock::given(method("GET"))
726            .and(path("/repos/o/r/rulesets"))
727            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([
728                { "id": 9, "name": REQUIRED_CHECK_RULESET_NAME }
729            ])))
730            .mount(server)
731            .await;
732        Mock::given(method("GET"))
733            .and(path("/repos/o/r/rulesets/9"))
734            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
735                "id": 9,
736                "name": REQUIRED_CHECK_RULESET_NAME,
737                "rules": [{
738                    "type": "required_status_checks",
739                    "parameters": {
740                        "required_status_checks": ruleset_checks
741                    }
742                }]
743            })))
744            .mount(server)
745            .await;
746    }
747
748    async fn mock_runs_and_empty_status(
749        server: &MockServer,
750        sha: &str,
751        check_runs: serde_json::Value,
752    ) {
753        Mock::given(method("GET"))
754            .and(path(format!("/repos/o/r/commits/{sha}/check-runs")))
755            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
756                "total_count": 1,
757                "check_runs": check_runs
758            })))
759            .mount(server)
760            .await;
761        Mock::given(method("GET"))
762            .and(path(format!("/repos/o/r/commits/{sha}/status")))
763            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
764                "state": "pending",
765                "total_count": 0,
766                "statuses": []
767            })))
768            .mount(server)
769            .await;
770    }
771
772    async fn mock_issue_comment(server: &MockServer, expected: u64) {
773        Mock::given(method("POST"))
774            .and(path("/repos/o/r/issues/12/comments"))
775            .respond_with(ResponseTemplate::new(201).set_body_json(serde_json::json!({
776                "id": 1
777            })))
778            .expect(expected)
779            .mount(server)
780            .await;
781    }
782
783    #[test]
784    fn ruleset_write_keeps_429_transport_and_422_with_401_digits_pending() {
785        for err in [
786            "GitHub API POST /rulesets failed (429 Too Many Requests): {\"message\":\"API rate limit exceeded\"}",
787            "HTTP request failed to send (transport error): connection reset by peer",
788            "failed (422 Unprocessable Entity): {\"message\":\"Ruleset validation failed for rule 401\"}",
789        ] {
790            assert!(
791                !matches!(
792                    classify_ruleset_create_error(err),
793                    RulesetCreateKind::Refused
794                ),
795                "{err}"
796            );
797        }
798    }
799
800    #[test]
801    fn is_ci_bootstrap_task_reads_the_body_marker() {
802        assert!(is_ci_bootstrap_task(&bootstrap_body()));
803        assert!(is_ci_bootstrap_task(&format!("{CI_BOOTSTRAP_MARKER}\n")));
804        assert!(is_ci_bootstrap_task("goal\n<!-- orch-plan: CI-01 -->"));
805        assert!(!is_ci_bootstrap_task(""));
806        assert!(!is_ci_bootstrap_task("goal"));
807    }
808
809    #[test]
810    fn checks_ready_for_ruleset_splits_pending_failed_and_empty() {
811        assert_eq!(checks_ready_for_ruleset(&[], &[]), ChecksReady::Empty);
812        assert_eq!(
813            checks_ready_for_ruleset(&[run("test", "in_progress", None, None)], &[]),
814            ChecksReady::Pending
815        );
816        assert_eq!(
817            checks_ready_for_ruleset(&[run("test", "completed", Some("failure"), None)], &[]),
818            ChecksReady::Failed(vec![FailedCheck {
819                name: "test".to_string(),
820                conclusion: "failure".to_string(),
821            }])
822        );
823        assert_eq!(
824            checks_ready_for_ruleset(
825                &[run("deploy", "completed", Some("action_required"), None)],
826                &[]
827            ),
828            ChecksReady::Pending
829        );
830        assert_eq!(
831            checks_ready_for_ruleset(
832                &[
833                    run("test", "completed", Some("success"), None),
834                    run("deploy", "completed", Some("action_required"), None),
835                ],
836                &[]
837            ),
838            ChecksReady::Pending
839        );
840        assert_eq!(
841            checks_ready_for_ruleset(&[run("test", "completed", Some("cancelled"), None)], &[]),
842            ChecksReady::Failed(vec![FailedCheck {
843                name: "test".to_string(),
844                conclusion: "cancelled".to_string(),
845            }])
846        );
847        assert_eq!(
848            checks_ready_for_ruleset(&[], &[("ci/test".to_string(), "failure".to_string())]),
849            ChecksReady::Failed(vec![FailedCheck {
850                name: "ci/test".to_string(),
851                conclusion: "failure".to_string(),
852            }])
853        );
854        assert_eq!(
855            checks_ready_for_ruleset(&[run("test", "completed", Some("skipped"), None)], &[]),
856            ChecksReady::Empty
857        );
858        assert_eq!(
859            checks_ready_for_ruleset(
860                &[run("orch/review", "completed", Some("success"), None)],
861                &[]
862            ),
863            ChecksReady::Empty
864        );
865        assert_eq!(
866            checks_ready_for_ruleset(
867                &[
868                    run("test", "completed", Some("failure"), None),
869                    run("lint", "in_progress", None, None),
870                ],
871                &[]
872            ),
873            ChecksReady::Failed(vec![FailedCheck {
874                name: "test".to_string(),
875                conclusion: "failure".to_string(),
876            }])
877        );
878        let ChecksReady::Ready(ready) = checks_ready_for_ruleset(
879            &[
880                run("test", "completed", Some("success"), Some(15368)),
881                run("review-gate", "completed", Some("success"), None),
882            ],
883            &[],
884        ) else {
885            panic!("expected ready checks");
886        };
887        assert_eq!(
888            ready,
889            vec![RequiredStatusCheck {
890                context: "test".to_string(),
891                integration_id: Some(15368),
892            }]
893        );
894    }
895
896    #[test]
897    fn required_contexts_cover_matches_by_context_name() {
898        let required = vec![RequiredStatusCheck {
899            context: "cla/check".to_string(),
900            integration_id: None,
901        }];
902        let needed = vec![RequiredStatusCheck {
903            context: "test".to_string(),
904            integration_id: Some(15368),
905        }];
906        assert!(!required_contexts_cover(&required, &needed));
907        let required = vec![
908            RequiredStatusCheck {
909                context: "cla/check".to_string(),
910                integration_id: None,
911            },
912            RequiredStatusCheck {
913                context: "test".to_string(),
914                integration_id: None,
915            },
916        ];
917        assert!(required_contexts_cover(&required, &needed));
918    }
919
920    #[test]
921    fn merge_missing_checks_appends_contexts_the_ruleset_lacks() {
922        let existing = vec![RequiredStatusCheck {
923            context: "cla/check".to_string(),
924            integration_id: None,
925        }];
926        let needed = vec![
927            RequiredStatusCheck {
928                context: "cla/check".to_string(),
929                integration_id: Some(1),
930            },
931            RequiredStatusCheck {
932                context: "test".to_string(),
933                integration_id: Some(15368),
934            },
935        ];
936        assert_eq!(
937            merge_missing_checks(existing, &needed),
938            vec![
939                RequiredStatusCheck {
940                    context: "cla/check".to_string(),
941                    integration_id: None,
942                },
943                RequiredStatusCheck {
944                    context: "test".to_string(),
945                    integration_id: Some(15368),
946                },
947            ]
948        );
949    }
950
951    #[tokio::test]
952    async fn hold_after_merge_records_pending_for_a_bootstrap_task() {
953        let store = Arc::new(TaskStore::open_memory().await.unwrap());
954        let task = ExternalTask {
955            id: ExternalId("12".to_string()),
956            title: "CI-01 Set up CI and tests".to_string(),
957            body: bootstrap_body(),
958            state: "open".to_string(),
959            labels: vec![],
960            author: String::new(),
961            created_at: String::new(),
962            updated_at: String::new(),
963            url: String::new(),
964        };
965        assert!(hold_after_merge(&task, &store, "o/r").await);
966        assert_eq!(
967            store.kv_get(&kv_key("o/r", "12")).await.unwrap().as_deref(),
968            Some(KV_PENDING)
969        );
970        store
971            .kv_set(&kv_key("o/r", "12"), KV_APPLIED)
972            .await
973            .unwrap();
974        assert!(!hold_after_merge(&task, &store, "o/r").await);
975    }
976
977    #[tokio::test]
978    async fn hold_after_merge_skips_a_title_without_a_plan_marker() {
979        let store = Arc::new(TaskStore::open_memory().await.unwrap());
980        let task = ExternalTask {
981            id: ExternalId("12".to_string()),
982            title: "CI-01 Set up CI and tests".to_string(),
983            body: "ordinary issue".to_string(),
984            state: "open".to_string(),
985            labels: vec![],
986            author: String::new(),
987            created_at: String::new(),
988            updated_at: String::new(),
989            url: String::new(),
990        };
991        assert!(!hold_after_merge(&task, &store, "o/r").await);
992        assert!(store.kv_get(&kv_key("o/r", "12")).await.unwrap().is_none());
993    }
994
995    #[tokio::test]
996    async fn apply_pending_dones_when_required_checks_already_cover_default_branch_checks() {
997        let _token = EnvVarGuard::set("GH_TOKEN", "test_token");
998        let server = MockServer::start().await;
999        mock_classic_required(&server, "test", "deadbeef").await;
1000        mock_runs_and_empty_status(
1001            &server,
1002            "deadbeef",
1003            serde_json::json!([{
1004                "id": 1,
1005                "name": "test",
1006                "status": "completed",
1007                "conclusion": "success",
1008                "app": { "id": 15368 }
1009            }]),
1010        )
1011        .await;
1012        Mock::given(method("POST"))
1013            .and(path("/repos/o/r/rulesets"))
1014            .respond_with(ResponseTemplate::new(201).set_body_json(serde_json::json!({
1015                "id": 9
1016            })))
1017            .expect(0)
1018            .mount(&server)
1019            .await;
1020
1021        let (store, task_manager, id) = pending_store().await;
1022        let gh = GhHttp::for_test(server.uri(), None);
1023        apply_pending_with(&gh, &store, &task_manager, "o/r")
1024            .await
1025            .unwrap();
1026
1027        let stored = store.get(id).await.unwrap();
1028        assert_eq!(stored.status, TaskStatus::Done);
1029        assert_eq!(
1030            store.kv_get(&kv_key("o/r", "12")).await.unwrap().as_deref(),
1031            Some(KV_APPLIED)
1032        );
1033    }
1034
1035    #[tokio::test]
1036    async fn apply_pending_creates_a_ruleset_when_an_unrelated_required_check_exists() {
1037        let _token = EnvVarGuard::set("GH_TOKEN", "test_token");
1038        let server = MockServer::start().await;
1039        mock_classic_required(&server, "cla/check", "deadbeef").await;
1040        mock_runs_and_empty_status(
1041            &server,
1042            "deadbeef",
1043            serde_json::json!([{
1044                "id": 1,
1045                "name": "test",
1046                "status": "completed",
1047                "conclusion": "success",
1048                "app": { "id": 15368 }
1049            }]),
1050        )
1051        .await;
1052        Mock::given(method("POST"))
1053            .and(path("/repos/o/r/rulesets"))
1054            .respond_with(ResponseTemplate::new(201).set_body_json(serde_json::json!({
1055                "id": 9,
1056                "name": REQUIRED_CHECK_RULESET_NAME
1057            })))
1058            .expect(1)
1059            .mount(&server)
1060            .await;
1061
1062        let (store, task_manager, id) = pending_store().await;
1063        let gh = GhHttp::for_test(server.uri(), None);
1064        apply_pending_with(&gh, &store, &task_manager, "o/r")
1065            .await
1066            .unwrap();
1067
1068        let stored = store.get(id).await.unwrap();
1069        assert_eq!(stored.status, TaskStatus::Done);
1070        assert_eq!(
1071            store.kv_get(&kv_key("o/r", "12")).await.unwrap().as_deref(),
1072            Some(KV_APPLIED)
1073        );
1074    }
1075
1076    #[tokio::test]
1077    async fn apply_pending_holds_when_an_unrelated_required_check_exists_and_checks_are_pending() {
1078        let _token = EnvVarGuard::set("GH_TOKEN", "test_token");
1079        let server = MockServer::start().await;
1080        mock_classic_required(&server, "cla/check", "deadbeef").await;
1081        mock_runs_and_empty_status(
1082            &server,
1083            "deadbeef",
1084            serde_json::json!([{
1085                "id": 1,
1086                "name": "test",
1087                "status": "in_progress",
1088                "conclusion": null,
1089                "app": { "id": 15368 }
1090            }]),
1091        )
1092        .await;
1093        Mock::given(method("POST"))
1094            .and(path("/repos/o/r/rulesets"))
1095            .respond_with(ResponseTemplate::new(201).set_body_json(serde_json::json!({
1096                "id": 9
1097            })))
1098            .expect(0)
1099            .mount(&server)
1100            .await;
1101
1102        let (store, task_manager, id) = pending_store().await;
1103        let gh = GhHttp::for_test(server.uri(), None);
1104        apply_pending_with(&gh, &store, &task_manager, "o/r")
1105            .await
1106            .unwrap();
1107
1108        let stored = store.get(id).await.unwrap();
1109        assert_eq!(stored.status, TaskStatus::Approved);
1110        assert_eq!(
1111            store.kv_get(&kv_key("o/r", "12")).await.unwrap().as_deref(),
1112            Some(KV_PENDING)
1113        );
1114    }
1115
1116    #[tokio::test]
1117    async fn apply_pending_dones_when_name_taken_and_orch_ruleset_lists_the_checks() {
1118        let _token = EnvVarGuard::set("GH_TOKEN", "test_token");
1119        let server = MockServer::start().await;
1120        mock_unprotected_main(&server, "deadbeef").await;
1121        mock_runs_and_empty_status(
1122            &server,
1123            "deadbeef",
1124            serde_json::json!([{
1125                "id": 1,
1126                "name": "test",
1127                "status": "completed",
1128                "conclusion": "success",
1129                "app": { "id": 15368 }
1130            }]),
1131        )
1132        .await;
1133        mock_name_taken_ruleset(
1134            &server,
1135            serde_json::json!([{ "context": "test", "integration_id": 15368 }]),
1136        )
1137        .await;
1138        Mock::given(method("PUT"))
1139            .and(path("/repos/o/r/rulesets/9"))
1140            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
1141                "id": 9
1142            })))
1143            .expect(0)
1144            .mount(&server)
1145            .await;
1146
1147        let (store, task_manager, id) = pending_store().await;
1148        let gh = GhHttp::for_test(server.uri(), None);
1149        apply_pending_with(&gh, &store, &task_manager, "o/r")
1150            .await
1151            .unwrap();
1152
1153        let stored = store.get(id).await.unwrap();
1154        assert_eq!(stored.status, TaskStatus::Done);
1155        assert_eq!(
1156            store.kv_get(&kv_key("o/r", "12")).await.unwrap().as_deref(),
1157            Some(KV_APPLIED)
1158        );
1159    }
1160
1161    #[tokio::test]
1162    async fn apply_pending_updates_the_orch_ruleset_when_name_taken_and_checks_are_missing() {
1163        let _token = EnvVarGuard::set("GH_TOKEN", "test_token");
1164        let server = MockServer::start().await;
1165        mock_unprotected_main(&server, "deadbeef").await;
1166        mock_runs_and_empty_status(
1167            &server,
1168            "deadbeef",
1169            serde_json::json!([{
1170                "id": 1,
1171                "name": "test",
1172                "status": "completed",
1173                "conclusion": "success",
1174                "app": { "id": 15368 }
1175            }]),
1176        )
1177        .await;
1178        mock_name_taken_ruleset(&server, serde_json::json!([{ "context": "cla/check" }])).await;
1179        Mock::given(method("PUT"))
1180            .and(path("/repos/o/r/rulesets/9"))
1181            .and(body_partial_json(serde_json::json!({
1182                "name": REQUIRED_CHECK_RULESET_NAME,
1183                "rules": [{
1184                    "type": "required_status_checks",
1185                    "parameters": {
1186                        "required_status_checks": [
1187                            { "context": "cla/check" },
1188                            { "context": "test", "integration_id": 15368 }
1189                        ]
1190                    }
1191                }]
1192            })))
1193            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
1194                "id": 9,
1195                "name": REQUIRED_CHECK_RULESET_NAME
1196            })))
1197            .expect(1)
1198            .mount(&server)
1199            .await;
1200
1201        let (store, task_manager, id) = pending_store().await;
1202        let gh = GhHttp::for_test(server.uri(), None);
1203        apply_pending_with(&gh, &store, &task_manager, "o/r")
1204            .await
1205            .unwrap();
1206
1207        let stored = store.get(id).await.unwrap();
1208        assert_eq!(stored.status, TaskStatus::Done);
1209        assert_eq!(
1210            store.kv_get(&kv_key("o/r", "12")).await.unwrap().as_deref(),
1211            Some(KV_APPLIED)
1212        );
1213    }
1214
1215    #[tokio::test]
1216    async fn apply_pending_creates_a_ruleset_when_default_branch_checks_pass() {
1217        let _token = EnvVarGuard::set("GH_TOKEN", "test_token");
1218        let server = MockServer::start().await;
1219        Mock::given(method("GET"))
1220            .and(path("/repos/o/r"))
1221            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
1222                "default_branch": "main"
1223            })))
1224            .mount(&server)
1225            .await;
1226        Mock::given(method("GET"))
1227            .and(path("/repos/o/r/branches/main/protection"))
1228            .respond_with(
1229                ResponseTemplate::new(404)
1230                    .set_body_string("{\"message\":\"Branch not protected\"}"),
1231            )
1232            .mount(&server)
1233            .await;
1234        Mock::given(method("GET"))
1235            .and(path("/repos/o/r/rules/branches/main"))
1236            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([])))
1237            .mount(&server)
1238            .await;
1239        Mock::given(method("GET"))
1240            .and(path("/repos/o/r/branches/main"))
1241            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
1242                "commit": { "sha": "deadbeef" }
1243            })))
1244            .mount(&server)
1245            .await;
1246        Mock::given(method("GET"))
1247            .and(path("/repos/o/r/commits/deadbeef/check-runs"))
1248            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
1249                "total_count": 1,
1250                "check_runs": [{
1251                    "id": 1,
1252                    "name": "test",
1253                    "status": "completed",
1254                    "conclusion": "success",
1255                    "app": { "id": 15368 }
1256                }]
1257            })))
1258            .mount(&server)
1259            .await;
1260        Mock::given(method("GET"))
1261            .and(path("/repos/o/r/commits/deadbeef/status"))
1262            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
1263                "state": "success",
1264                "total_count": 0,
1265                "statuses": []
1266            })))
1267            .mount(&server)
1268            .await;
1269        Mock::given(method("POST"))
1270            .and(path("/repos/o/r/rulesets"))
1271            .respond_with(ResponseTemplate::new(201).set_body_json(serde_json::json!({
1272                "id": 9,
1273                "name": "orch required checks"
1274            })))
1275            .expect(1)
1276            .mount(&server)
1277            .await;
1278
1279        let store = Arc::new(TaskStore::open_memory().await.unwrap());
1280        let backend: Arc<dyn ExternalBackend> = Arc::new(NoopBackend);
1281        let task_manager = Arc::new(TaskManager::with_store(
1282            backend,
1283            Arc::clone(&store),
1284            "o/r".to_string(),
1285        ));
1286        let id = store
1287            .upsert_external(&UpsertExternal {
1288                repo: "o/r",
1289                ext_id: "12",
1290                title: "CI-01 Set up CI and tests",
1291                body: &bootstrap_body(),
1292                author: "u",
1293                url: "",
1294                labels: &[],
1295                origin: "github",
1296            })
1297            .await
1298            .unwrap();
1299        store.update_status(id, TaskStatus::Approved).await.unwrap();
1300        store
1301            .kv_set(&kv_key("o/r", "12"), KV_PENDING)
1302            .await
1303            .unwrap();
1304
1305        let gh = GhHttp::for_test(server.uri(), None);
1306        apply_pending_with(&gh, &store, &task_manager, "o/r")
1307            .await
1308            .unwrap();
1309
1310        let stored = store.get(id).await.unwrap();
1311        assert_eq!(stored.status, TaskStatus::Done);
1312        assert_eq!(
1313            store.kv_get(&kv_key("o/r", "12")).await.unwrap().as_deref(),
1314            Some(KV_APPLIED)
1315        );
1316    }
1317
1318    #[tokio::test]
1319    async fn apply_pending_comments_and_holds_when_github_refuses_the_ruleset() {
1320        let _token = EnvVarGuard::set("GH_TOKEN", "test_token");
1321        let server = MockServer::start().await;
1322        Mock::given(method("GET"))
1323            .and(path("/repos/o/r"))
1324            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
1325                "default_branch": "main"
1326            })))
1327            .mount(&server)
1328            .await;
1329        Mock::given(method("GET"))
1330            .and(path("/repos/o/r/branches/main/protection"))
1331            .respond_with(
1332                ResponseTemplate::new(404)
1333                    .set_body_string("{\"message\":\"Branch not protected\"}"),
1334            )
1335            .mount(&server)
1336            .await;
1337        Mock::given(method("GET"))
1338            .and(path("/repos/o/r/rules/branches/main"))
1339            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([])))
1340            .mount(&server)
1341            .await;
1342        Mock::given(method("GET"))
1343            .and(path("/repos/o/r/branches/main"))
1344            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
1345                "commit": { "sha": "deadbeef" }
1346            })))
1347            .mount(&server)
1348            .await;
1349        Mock::given(method("GET"))
1350            .and(path("/repos/o/r/commits/deadbeef/check-runs"))
1351            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
1352                "total_count": 1,
1353                "check_runs": [{
1354                    "id": 1,
1355                    "name": "test",
1356                    "status": "completed",
1357                    "conclusion": "success",
1358                    "app": { "id": 15368 }
1359                }]
1360            })))
1361            .mount(&server)
1362            .await;
1363        Mock::given(method("GET"))
1364            .and(path("/repos/o/r/commits/deadbeef/status"))
1365            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
1366                "state": "success",
1367                "total_count": 0,
1368                "statuses": []
1369            })))
1370            .mount(&server)
1371            .await;
1372        Mock::given(method("POST"))
1373            .and(path("/repos/o/r/rulesets"))
1374            .respond_with(ResponseTemplate::new(403).set_body_json(serde_json::json!({
1375                "message": "Upgrade to GitHub Pro or make this repository public to enable this feature."
1376            })))
1377            .mount(&server)
1378            .await;
1379        Mock::given(method("POST"))
1380            .and(path("/repos/o/r/issues/12/comments"))
1381            .respond_with(ResponseTemplate::new(201).set_body_json(serde_json::json!({
1382                "id": 1
1383            })))
1384            .expect(1)
1385            .mount(&server)
1386            .await;
1387
1388        let store = Arc::new(TaskStore::open_memory().await.unwrap());
1389        let backend: Arc<dyn ExternalBackend> = Arc::new(NoopBackend);
1390        let task_manager = Arc::new(TaskManager::with_store(
1391            backend,
1392            Arc::clone(&store),
1393            "o/r".to_string(),
1394        ));
1395        let id = store
1396            .upsert_external(&UpsertExternal {
1397                repo: "o/r",
1398                ext_id: "12",
1399                title: "CI-01 Set up CI and tests",
1400                body: &bootstrap_body(),
1401                author: "u",
1402                url: "",
1403                labels: &[],
1404                origin: "github",
1405            })
1406            .await
1407            .unwrap();
1408        store.update_status(id, TaskStatus::Approved).await.unwrap();
1409        store
1410            .kv_set(&kv_key("o/r", "12"), KV_PENDING)
1411            .await
1412            .unwrap();
1413
1414        let gh = GhHttp::for_test(server.uri(), None);
1415        apply_pending_with(&gh, &store, &task_manager, "o/r")
1416            .await
1417            .unwrap();
1418
1419        let stored = store.get(id).await.unwrap();
1420        assert_eq!(stored.status, TaskStatus::Approved);
1421        assert_eq!(
1422            store.kv_get(&kv_key("o/r", "12")).await.unwrap().as_deref(),
1423            Some(KV_REFUSED)
1424        );
1425    }
1426
1427    #[tokio::test]
1428    async fn apply_pending_holds_when_ruleset_create_is_unrecognized_even_with_401_digits() {
1429        let _token = EnvVarGuard::set("GH_TOKEN", "test_token");
1430        let server = MockServer::start().await;
1431        mock_unprotected_main(&server, "deadbeef").await;
1432        mock_runs_and_empty_status(
1433            &server,
1434            "deadbeef",
1435            serde_json::json!([{
1436                "id": 1,
1437                "name": "test",
1438                "status": "completed",
1439                "conclusion": "success",
1440                "app": { "id": 15368 }
1441            }]),
1442        )
1443        .await;
1444        Mock::given(method("POST"))
1445            .and(path("/repos/o/r/rulesets"))
1446            .respond_with(ResponseTemplate::new(422).set_body_json(serde_json::json!({
1447                "message": "Ruleset validation failed for rule 401"
1448            })))
1449            .mount(&server)
1450            .await;
1451        mock_issue_comment(&server, 0).await;
1452
1453        let (store, task_manager, id) = pending_store().await;
1454        let gh = GhHttp::for_test(server.uri(), None);
1455        apply_pending_with(&gh, &store, &task_manager, "o/r")
1456            .await
1457            .unwrap();
1458        apply_pending_with(&gh, &store, &task_manager, "o/r")
1459            .await
1460            .unwrap();
1461
1462        let stored = store.get(id).await.unwrap();
1463        assert_eq!(stored.status, TaskStatus::Approved);
1464        assert_eq!(
1465            store.kv_get(&kv_key("o/r", "12")).await.unwrap().as_deref(),
1466            Some(KV_PENDING)
1467        );
1468    }
1469
1470    #[tokio::test]
1471    async fn apply_pending_reopens_a_closed_issue_and_creates_the_ruleset() {
1472        let _token = EnvVarGuard::set("GH_TOKEN", "test_token");
1473        let server = MockServer::start().await;
1474        Mock::given(method("GET"))
1475            .and(path("/repos/o/r"))
1476            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
1477                "default_branch": "main"
1478            })))
1479            .mount(&server)
1480            .await;
1481        Mock::given(method("GET"))
1482            .and(path("/repos/o/r/branches/main/protection"))
1483            .respond_with(
1484                ResponseTemplate::new(404)
1485                    .set_body_string("{\"message\":\"Branch not protected\"}"),
1486            )
1487            .mount(&server)
1488            .await;
1489        Mock::given(method("GET"))
1490            .and(path("/repos/o/r/rules/branches/main"))
1491            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([])))
1492            .mount(&server)
1493            .await;
1494        Mock::given(method("GET"))
1495            .and(path("/repos/o/r/issues/12"))
1496            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
1497                "number": 12,
1498                "id": 120,
1499                "title": "CI-01 Set up CI and tests",
1500                "body": "",
1501                "state": "closed",
1502                "labels": [],
1503                "user": { "login": "u" },
1504                "created_at": "",
1505                "updated_at": "",
1506                "html_url": ""
1507            })))
1508            .mount(&server)
1509            .await;
1510        Mock::given(method("PATCH"))
1511            .and(path("/repos/o/r/issues/12"))
1512            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
1513                "number": 12,
1514                "id": 120,
1515                "title": "CI-01 Set up CI and tests",
1516                "body": "",
1517                "state": "open",
1518                "labels": [],
1519                "user": { "login": "u" },
1520                "created_at": "",
1521                "updated_at": "",
1522                "html_url": ""
1523            })))
1524            .expect(1)
1525            .mount(&server)
1526            .await;
1527        Mock::given(method("GET"))
1528            .and(path("/repos/o/r/branches/main"))
1529            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
1530                "commit": { "sha": "deadbeef" }
1531            })))
1532            .mount(&server)
1533            .await;
1534        Mock::given(method("GET"))
1535            .and(path("/repos/o/r/commits/deadbeef/check-runs"))
1536            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
1537                "total_count": 1,
1538                "check_runs": [{
1539                    "id": 1,
1540                    "name": "test",
1541                    "status": "completed",
1542                    "conclusion": "success",
1543                    "app": { "id": 15368 }
1544                }]
1545            })))
1546            .mount(&server)
1547            .await;
1548        Mock::given(method("GET"))
1549            .and(path("/repos/o/r/commits/deadbeef/status"))
1550            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
1551                "state": "success",
1552                "total_count": 0,
1553                "statuses": []
1554            })))
1555            .mount(&server)
1556            .await;
1557        Mock::given(method("POST"))
1558            .and(path("/repos/o/r/rulesets"))
1559            .respond_with(ResponseTemplate::new(201).set_body_json(serde_json::json!({
1560                "id": 9,
1561                "name": "orch required checks"
1562            })))
1563            .expect(1)
1564            .mount(&server)
1565            .await;
1566
1567        let store = Arc::new(TaskStore::open_memory().await.unwrap());
1568        let backend: Arc<dyn ExternalBackend> = Arc::new(NoopBackend);
1569        let task_manager = Arc::new(TaskManager::with_store(
1570            backend,
1571            Arc::clone(&store),
1572            "o/r".to_string(),
1573        ));
1574        let id = store
1575            .upsert_external(&UpsertExternal {
1576                repo: "o/r",
1577                ext_id: "12",
1578                title: "CI-01 Set up CI and tests",
1579                body: &bootstrap_body(),
1580                author: "u",
1581                url: "",
1582                labels: &[],
1583                origin: "github",
1584            })
1585            .await
1586            .unwrap();
1587        store.update_status(id, TaskStatus::Done).await.unwrap();
1588        store
1589            .kv_set(&kv_key("o/r", "12"), KV_PENDING)
1590            .await
1591            .unwrap();
1592
1593        let gh = GhHttp::for_test(server.uri(), None);
1594        apply_pending_with(&gh, &store, &task_manager, "o/r")
1595            .await
1596            .unwrap();
1597
1598        let stored = store.get(id).await.unwrap();
1599        assert_eq!(stored.status, TaskStatus::Done);
1600        assert_eq!(
1601            store.kv_get(&kv_key("o/r", "12")).await.unwrap().as_deref(),
1602            Some(KV_APPLIED)
1603        );
1604    }
1605
1606    #[tokio::test]
1607    async fn apply_pending_logs_and_holds_while_default_branch_checks_run() {
1608        let _token = EnvVarGuard::set("GH_TOKEN", "test_token");
1609        let server = MockServer::start().await;
1610        mock_unprotected_main(&server, "deadbeef").await;
1611        mock_runs_and_empty_status(
1612            &server,
1613            "deadbeef",
1614            serde_json::json!([{
1615                "id": 1,
1616                "name": "test",
1617                "status": "in_progress",
1618                "conclusion": null,
1619                "app": { "id": 15368 }
1620            }]),
1621        )
1622        .await;
1623        mock_issue_comment(&server, 0).await;
1624        Mock::given(method("POST"))
1625            .and(path("/repos/o/r/rulesets"))
1626            .respond_with(ResponseTemplate::new(201).set_body_json(serde_json::json!({
1627                "id": 9
1628            })))
1629            .expect(0)
1630            .mount(&server)
1631            .await;
1632
1633        let (store, task_manager, id) = pending_store().await;
1634        let gh = GhHttp::for_test(server.uri(), None);
1635        apply_pending_with(&gh, &store, &task_manager, "o/r")
1636            .await
1637            .unwrap();
1638
1639        let stored = store.get(id).await.unwrap();
1640        assert_eq!(stored.status, TaskStatus::Approved);
1641        assert_eq!(
1642            store.kv_get(&kv_key("o/r", "12")).await.unwrap().as_deref(),
1643            Some(KV_PENDING)
1644        );
1645    }
1646
1647    #[tokio::test]
1648    async fn apply_pending_comments_and_routes_when_default_branch_checks_fail() {
1649        let _token = EnvVarGuard::set("GH_TOKEN", "test_token");
1650        let server = MockServer::start().await;
1651        mock_unprotected_main(&server, "deadbeef").await;
1652        mock_runs_and_empty_status(
1653            &server,
1654            "deadbeef",
1655            serde_json::json!([{
1656                "id": 1,
1657                "name": "test",
1658                "status": "completed",
1659                "conclusion": "failure",
1660                "app": { "id": 15368 }
1661            }]),
1662        )
1663        .await;
1664        mock_issue_comment(&server, 1).await;
1665
1666        let (store, task_manager, id) = pending_store().await;
1667        let gh = GhHttp::for_test(server.uri(), None);
1668        apply_pending_with(&gh, &store, &task_manager, "o/r")
1669            .await
1670            .unwrap();
1671
1672        let stored = store.get(id).await.unwrap();
1673        assert_eq!(stored.status, TaskStatus::Routed);
1674        assert_eq!(stored.ci_merge_failures, 1);
1675        assert!(stored.last_error.contains("test: failure"));
1676        assert_eq!(
1677            store.kv_get(&kv_key("o/r", "12")).await.unwrap().as_deref(),
1678            Some(KV_PENDING)
1679        );
1680
1681        apply_pending_with(&gh, &store, &task_manager, "o/r")
1682            .await
1683            .unwrap();
1684        let stored = store.get(id).await.unwrap();
1685        assert_eq!(stored.status, TaskStatus::Routed);
1686        assert_eq!(stored.ci_merge_failures, 1);
1687    }
1688
1689    #[tokio::test]
1690    async fn apply_pending_blocks_after_max_failed_default_branch_heads() {
1691        let _token = EnvVarGuard::set("GH_TOKEN", "test_token");
1692        let server = MockServer::start().await;
1693        mock_unprotected_main(&server, "deadbeef").await;
1694        mock_runs_and_empty_status(
1695            &server,
1696            "deadbeef",
1697            serde_json::json!([{
1698                "id": 1,
1699                "name": "test",
1700                "status": "completed",
1701                "conclusion": "cancelled",
1702                "app": { "id": 15368 }
1703            }]),
1704        )
1705        .await;
1706        mock_issue_comment(&server, 1).await;
1707
1708        let (store, task_manager, id) = pending_store().await;
1709        store.increment(id, "ci_merge_failures").await.unwrap();
1710        store.increment(id, "ci_merge_failures").await.unwrap();
1711        let gh = GhHttp::for_test(server.uri(), None);
1712        apply_pending_with(&gh, &store, &task_manager, "o/r")
1713            .await
1714            .unwrap();
1715
1716        let stored = store.get(id).await.unwrap();
1717        assert_eq!(stored.status, TaskStatus::Blocked);
1718        assert_eq!(
1719            stored.ci_merge_failures,
1720            i32::try_from(ci::MAX_CI_MERGE_FAILURES).unwrap()
1721        );
1722        assert!(
1723            stored
1724                .block_reason
1725                .as_deref()
1726                .unwrap_or("")
1727                .contains("CI failure limit")
1728        );
1729    }
1730
1731    #[tokio::test]
1732    async fn apply_pending_waits_before_commenting_when_no_check_starts() {
1733        let _token = EnvVarGuard::set("GH_TOKEN", "test_token");
1734        let server = MockServer::start().await;
1735        mock_unprotected_main(&server, "deadbeef").await;
1736        mock_runs_and_empty_status(&server, "deadbeef", serde_json::json!([])).await;
1737        mock_issue_comment(&server, 0).await;
1738
1739        let (store, task_manager, id) = pending_store().await;
1740        let gh = GhHttp::for_test(server.uri(), None);
1741        apply_pending_with(&gh, &store, &task_manager, "o/r")
1742            .await
1743            .unwrap();
1744
1745        let stored = store.get(id).await.unwrap();
1746        assert_eq!(stored.status, TaskStatus::Approved);
1747        assert!(
1748            store
1749                .kv_get("ci_bootstrap_wait_since:o/r#12#deadbeef")
1750                .await
1751                .unwrap()
1752                .is_some()
1753        );
1754        assert!(
1755            store
1756                .kv_get(&no_checks_comment_key("o/r", "12", "deadbeef"))
1757                .await
1758                .unwrap()
1759                .is_none()
1760        );
1761    }
1762
1763    #[tokio::test]
1764    async fn apply_pending_comments_once_when_no_check_starts_after_the_wait() {
1765        let _token = EnvVarGuard::set("GH_TOKEN", "test_token");
1766        let server = MockServer::start().await;
1767        mock_unprotected_main(&server, "deadbeef").await;
1768        mock_runs_and_empty_status(&server, "deadbeef", serde_json::json!([])).await;
1769        mock_issue_comment(&server, 1).await;
1770
1771        let (store, task_manager, id) = pending_store().await;
1772        let started = chrono::Utc::now().timestamp() - gate::NO_CHECKS_WAIT_SECS - 1;
1773        store
1774            .kv_set(
1775                "ci_bootstrap_wait_since:o/r#12#deadbeef",
1776                &started.to_string(),
1777            )
1778            .await
1779            .unwrap();
1780        let gh = GhHttp::for_test(server.uri(), None);
1781        apply_pending_with(&gh, &store, &task_manager, "o/r")
1782            .await
1783            .unwrap();
1784
1785        let stored = store.get(id).await.unwrap();
1786        assert_eq!(stored.status, TaskStatus::Approved);
1787        assert_eq!(
1788            store
1789                .kv_get(&no_checks_comment_key("o/r", "12", "deadbeef"))
1790                .await
1791                .unwrap()
1792                .as_deref(),
1793            Some("1")
1794        );
1795
1796        apply_pending_with(&gh, &store, &task_manager, "o/r")
1797            .await
1798            .unwrap();
1799        assert_eq!(store.get(id).await.unwrap().status, TaskStatus::Approved);
1800    }
1801
1802    #[tokio::test]
1803    async fn apply_pending_comments_once_when_github_says_the_check_never_ran() {
1804        let _token = EnvVarGuard::set("GH_TOKEN", "test_token");
1805        let server = MockServer::start().await;
1806        mock_unprotected_main(&server, "deadbeef").await;
1807        mock_runs_and_empty_status(
1808            &server,
1809            "deadbeef",
1810            serde_json::json!([{
1811                "id": 1,
1812                "name": "test",
1813                "status": "completed",
1814                "conclusion": "success",
1815                "app": { "id": 15368 }
1816            }]),
1817        )
1818        .await;
1819        Mock::given(method("POST"))
1820            .and(path("/repos/o/r/rulesets"))
1821            .respond_with(ResponseTemplate::new(422).set_body_json(serde_json::json!({
1822                "message": "test was not a valid check"
1823            })))
1824            .mount(&server)
1825            .await;
1826        mock_issue_comment(&server, 1).await;
1827
1828        let (store, task_manager, id) = pending_store().await;
1829        let gh = GhHttp::for_test(server.uri(), None);
1830        apply_pending_with(&gh, &store, &task_manager, "o/r")
1831            .await
1832            .unwrap();
1833        apply_pending_with(&gh, &store, &task_manager, "o/r")
1834            .await
1835            .unwrap();
1836
1837        let stored = store.get(id).await.unwrap();
1838        assert_eq!(stored.status, TaskStatus::Approved);
1839        assert_eq!(
1840            store.kv_get(&kv_key("o/r", "12")).await.unwrap().as_deref(),
1841            Some(KV_PENDING)
1842        );
1843        assert_eq!(
1844            store
1845                .kv_get(&never_run_comment_key("o/r", "12"))
1846                .await
1847                .unwrap()
1848                .as_deref(),
1849            Some("1")
1850        );
1851    }
1852}