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