pr_01m47d24b0e6n91zwymwxg0vpx/services/work/src/lifecycle.rs

1,492 lines53,780 bytesCodeBlame
1//! Seeing a pull request through. Once a g1t agent has made a change, g1t
2//! takes each remaining step itself: the acceptance checks, a review by
3//! another agent, sending the author back to address what either found,
4//! and catching up when the branch it would land on has moved. It stops
5//! when the pull request is ready for a person to merge, or when it has
6//! tried and a person has to decide.
7//!
8//! This service decides what the next step is and claims it. The runner
9//! service asks, on every event that could change the answer, and carries
10//! the step out in a sandbox.
11
12use g1t_contracts::events::PullEvent;
13use g1t_contracts::repos::{GetByIdArgs, Repo, RepoPath};
14use g1t_contracts::time::rfc3339;
15use g1t_contracts::work::*;
16use g1t_contracts::{FailureCode, Membership, Outcome, Role, User, Viewer};
17use g1t_kit::now_ms;
18use std::collections::HashMap;
19
20use serde::Deserialize;
21use worker::Result;
22use worker::wasm_bindgen::JsValue;
23
24use crate::Work;
25use crate::reviews::{AGENT_ID, AGENT_NAME};
26use crate::statuses::{self, WorkflowFacts};
27use crate::rows::ValueRow;
28
29/// How long a claimed step is waited for before it may be taken again.
30const REVIEW_MINUTES: u64 = 20;
31const REVISION_MINUTES: u64 = 60;
32const CATCH_UP_MINUTES: u64 = 30;
33const MERGE_MINUTES: u64 = 2;
34/// Who a merge made by a repository's settings is attributed to. Not an
35/// account: `g1t` cannot be registered.
36const POLICY_ACTOR_ID: &str = "g1t_policy";
37const POLICY_ACTOR_NAME: &str = "g1t";
38/// How much of a failed check's output the author is shown.
39const MAX_CHECK_OUTPUT_CHARS: usize = 4_000;
40const MANAGED_PAGE: u32 = 200;
41
42/// The part of a pull request's row that tracks its lifecycle.
43#[derive(Deserialize)]
44struct Progress {
45 managed: u8,
46 revisions: u32,
47 revised_at: Option<String>,
48 working_on: Option<String>,
49 working_until: Option<String>,
50 stalled: Option<String>,
51}
52
53/// A merge asked for while the pull request was behind, as stored.
54#[derive(serde::Serialize, Deserialize)]
55#[serde(rename_all = "camelCase")]
56struct LandRequest {
57 actor: User,
58 keep_issue_open: bool,
59}
60
61#[derive(Deserialize)]
62struct LandRow {
63 land_requested: Option<String>,
64 land_requested_at: Option<String>,
65 stalled: Option<String>,
66}
67
68#[derive(Deserialize)]
69struct FinishedReview {
70 finished_at: String,
71 verdict: Option<Verdict>,
72}
73
74#[derive(Deserialize)]
75struct ReviewNote {
76 body: String,
77 path: Option<String>,
78 line: Option<u32>,
79}
80
81/// What the author is being sent back to address.
82pub(crate) enum Feedback {
83 FailedChecks,
84 /// Workflows that failed on its head.
85 FailedWorkflows,
86 /// The review that finished at this time.
87 Review(String),
88 /// What a person who asked for changes wrote since the last revision.
89 Person(PersonRequest),
90}
91
92/// A person's request for changes that still stands: their latest verdict,
93/// made after the agent last revised.
94#[derive(Clone, Debug, Deserialize)]
95pub(crate) struct PersonRequest {
96 author_id: String,
97 author_name: String,
98 created_at: String,
99}
100
101/// What should happen next, if it is g1t's turn.
102pub(crate) enum Next {
103 /// A step is under way, or it is a person's turn.
104 Wait,
105 Review,
106 Revise(Feedback),
107 CatchUp,
108 /// Land it, because the repository says ready pull requests land.
109 Merge,
110}
111
112/// Whether g1t made this pull request, and so sees it through.
113pub(crate) fn made_by_g1t(pull: &Pull) -> bool {
114 pull.runtime == Runtime::Hosted && pull.agent == AGENT_NAME && pull.fork.is_some()
115}
116
117fn at(stage: Stage, detail: impl Into<String>, revisions: u32) -> Lifecycle {
118 Lifecycle {
119 stage,
120 detail: detail.into(),
121 revisions,
122 }
123}
124
125fn times(count: u32) -> String {
126 match count {
127 1 => "once".to_owned(),
128 2 => "twice".to_owned(),
129 count => format!("{count} times"),
130 }
131}
132
133/// Everything the next step depends on.
134struct Facts {
135 /// Still being made: not yet marked ready for review.
136 draft: bool,
137 /// Why g1t stopped, if it has.
138 stalled: Option<String>,
139 /// The step under way, if one was claimed and is still being waited for.
140 working_on: Option<String>,
141 check_status: Option<CheckStatus>,
142 /// A review someone asked for is being written.
143 review_pending: bool,
144 /// Whether the issue has acceptance checks at all.
145 has_checks: bool,
146 revisions: u32,
147 /// The latest finished review of the change as it is now.
148 review: Option<FinishedReview>,
149 /// Whether the branch it would land on has moved without it.
150 behind: bool,
151 /// Whether the repository lands a ready pull request by itself.
152 auto_merge: bool,
153 /// Whether the repository refuses to merge one that is behind.
154 require_up_to_date: bool,
155 /// Whether a second agent reviews it without being asked.
156 agent_review: bool,
157 /// How many times the author may be sent back.
158 max_revisions: u32,
159 /// What the repository's approval rule still wants, if anything.
160 approvals_missing: Option<String>,
161 /// A person asked for changes since the agent last revised.
162 person_request: Option<PersonRequest>,
163 /// Its place in the merge queue, and what is ahead of it there.
164 queued: Option<(QueueState, Vec<u32>)>,
165 /// What the workflows run on its head say.
166 workflows: WorkflowFacts,
167}
168
169/// Where a pull request stands, and the step to take if it is g1t's turn.
170///
171/// The order is: nothing while a step is under way; a person asking for
172/// changes is answered first; the checks must pass; then a review must
173/// approve; then it must be up to date. A person's or an agent's request
174/// for changes, or a failed check, sends the author back, a limited number
175/// of times, after which a person is asked.
176fn decide(facts: Facts) -> (Lifecycle, Next) {
177 let revisions = facts.revisions;
178 let wait = |stage, detail: &str| (at(stage, detail, revisions), Next::Wait);
179 let exhausted = revisions >= facts.max_revisions;
180
181 if facts.draft {
182 return wait(Stage::Working, "A g1t agent is making the change.");
183 }
184 if let Some(reason) = &facts.stalled {
185 return wait(Stage::NeedsYou, reason);
186 }
187 if let Some((state, ahead)) = &facts.queued {
188 let named = ahead.iter().map(|n| format!("#{n}")).collect::<Vec<_>>().join(", ");
189 let detail = match (state, ahead.is_empty()) {
190 (QueueState::Testing, true) => "In the merge queue: being tested on the default branch as it is.".to_owned(),
191 (QueueState::Testing, false) => {
192 format!("In the merge queue: being tested together with {named}, ahead of it.")
193 }
194 (QueueState::Passed, true) => "Passed in the merge queue. Landing.".to_owned(),
195 (QueueState::Passed, false) => {
196 format!("Passed in the merge queue together with {named}. It lands once they have.")
197 }
198 _ => "In the merge queue, waiting for its turn to be tested.".to_owned(),
199 };
200 return wait(Stage::Queued, &detail);
201 }
202 match facts.working_on.as_deref() {
203 Some("revision") => {
204 return wait(
205 Stage::Revising,
206 "The agent is addressing what the checks or the review found.",
207 );
208 }
209 Some("catch_up") => {
210 return wait(
211 Stage::CatchingUp,
212 "The agent is merging in the branch this will land on, which has moved.",
213 );
214 }
215 Some("merge") => return wait(Stage::Ready, "Merging."),
216 Some(_) => return wait(Stage::Reviewing, "A g1t agent is reviewing the change."),
217 None => {}
218 }
219 if matches!(
220 facts.check_status,
221 Some(CheckStatus::Queued | CheckStatus::Running)
222 ) {
223 return wait(Stage::Checking, "The acceptance checks are running.");
224 }
225 if facts.review_pending {
226 return wait(Stage::Reviewing, "A g1t agent is reviewing the change.");
227 }
228 // A person asked for changes: the agent makes them, as it would for a
229 // review it asked for, before anything else.
230 if let Some(request) = &facts.person_request {
231 if exhausted {
232 return wait(
233 Stage::NeedsYou,
234 &format!(
235 "{} asked for changes, and the agent has already revised {}.",
236 request.author_name,
237 times(revisions)
238 ),
239 );
240 }
241 return (
242 at(
243 Stage::Revising,
244 format!(
245 "{} asked for changes. The agent is being sent back to make them.",
246 request.author_name
247 ),
248 revisions,
249 ),
250 Next::Revise(Feedback::Person(request.clone())),
251 );
252 }
253
254 if facts.has_checks {
255 match facts.check_status {
256 Some(CheckStatus::Passed) => {}
257 Some(CheckStatus::Failed) if exhausted => {
258 return wait(
259 Stage::NeedsYou,
260 &format!(
261 "The acceptance checks still fail after the agent revised {}.",
262 times(revisions)
263 ),
264 );
265 }
266 Some(CheckStatus::Failed) => {
267 return (
268 at(
269 Stage::Revising,
270 "The acceptance checks failed. The agent is being sent back to fix them.",
271 revisions,
272 ),
273 Next::Revise(Feedback::FailedChecks),
274 );
275 }
276 Some(CheckStatus::Errored) => {
277 return wait(Stage::NeedsYou, "The acceptance checks could not be run.");
278 }
279 _ => {
280 return wait(
281 Stage::Checking,
282 "Waiting for the acceptance checks to start.",
283 );
284 }
285 }
286 }
287
288 // Its workflows, like its checks, must pass.
289 if !facts.workflows.failed.is_empty() {
290 let failed = statuses::list(&facts.workflows.failed);
291 if exhausted {
292 return wait(
293 Stage::NeedsYou,
294 &format!("{failed} still fails after the agent revised {}.", times(revisions)),
295 );
296 }
297 return (
298 at(
299 Stage::Revising,
300 format!("{failed} failed. The agent is being sent back to fix it."),
301 revisions,
302 ),
303 Next::Revise(Feedback::FailedWorkflows),
304 );
305 }
306 if !facts.workflows.pending.is_empty() {
307 return wait(
308 Stage::Checking,
309 &format!("Waiting for {} to finish.", statuses::list(&facts.workflows.pending)),
310 );
311 }
312
313 // A second agent reviews it, unless the repository leaves review to people.
314 if facts.agent_review {
315 match facts.review {
316 None => {
317 return (
318 at(
319 Stage::Reviewing,
320 "A g1t agent is about to review the change.",
321 revisions,
322 ),
323 Next::Review,
324 );
325 }
326 Some(FinishedReview { verdict: None, .. }) => {
327 return wait(Stage::NeedsYou, "The review could not be completed.");
328 }
329 Some(FinishedReview {
330 verdict: Some(Verdict::RequestChanges),
331 ..
332 }) if exhausted => {
333 return wait(
334 Stage::NeedsYou,
335 &format!(
336 "The review still asks for changes after the agent revised {}.",
337 times(revisions)
338 ),
339 );
340 }
341 Some(FinishedReview {
342 verdict: Some(Verdict::RequestChanges),
343 finished_at,
344 }) => {
345 return (
346 at(
347 Stage::Revising,
348 "The review asked for changes. The agent is being sent back to make them.",
349 revisions,
350 ),
351 Next::Revise(Feedback::Review(finished_at)),
352 );
353 }
354 Some(FinishedReview {
355 verdict: Some(Verdict::Approve),
356 ..
357 }) => {}
358 }
359 }
360
361 // Only where the repository insists is catching up a step of its own,
362 // followed by the checks again. Elsewhere it happens as part of merging.
363 if facts.behind && facts.require_up_to_date {
364 return (
365 at(
366 Stage::CatchingUp,
367 "The branch it will land on has moved. The agent is catching up.",
368 revisions,
369 ),
370 Next::CatchUp,
371 );
372 }
373 // The repository wants approvals this does not have yet: people's turn,
374 // so it is shown as needing someone, not as g1t still working.
375 if let Some(missing) = &facts.approvals_missing {
376 return wait(Stage::NeedsYou, missing);
377 }
378 if facts.auto_merge {
379 return (
380 at(
381 Stage::Ready,
382 "Everything this repository asks for is met. Merging, as its settings say.",
383 revisions,
384 ),
385 Next::Merge,
386 );
387 }
388 wait(
389 Stage::Ready,
390 if facts.behind {
391 "Ready to merge. Merging brings it up to date with the default branch first."
392 } else {
393 "Everything this repository asks for is met. Ready to merge."
394 },
395 )
396}
397
398impl Work {
399 /// Where a pull request stands and what g1t does next, remembered so
400 /// lists can show it without working it out again. `None` for one g1t
401 /// is not seeing through.
402 pub(crate) async fn assess(
403 &self,
404 pull: &Pull,
405 issue: &Option<Issue>,
406 behind: bool,
407 ) -> Result<Option<(Lifecycle, Next)>> {
408 let assessed = self.assess_now(pull, issue, behind).await?;
409 if let Some((lifecycle, _)) = &assessed {
410 self.remember(&pull.id, lifecycle).await?;
411 }
412 Ok(assessed)
413 }
414
415 /// Saves where a pull request stands, for [`Self::remembered`].
416 pub(crate) async fn remember(&self, pull_id: &str, lifecycle: &Lifecycle) -> Result<()> {
417 let stage = serde_json::to_value(lifecycle.stage)?;
418 self.db
419 .prepare("UPDATE pulls SET stage = ?, stage_detail = ? WHERE id = ?")
420 .bind(&[
421 stage.as_str().unwrap_or_default().into(),
422 lifecycle.detail.as_str().into(),
423 pull_id.into(),
424 ])?
425 .run()
426 .await?;
427 Ok(())
428 }
429
430 async fn assess_now(
431 &self,
432 pull: &Pull,
433 issue: &Option<Issue>,
434 behind: bool,
435 ) -> Result<Option<(Lifecycle, Next)>> {
436 if !pull.status.is_active() {
437 return Ok(None);
438 }
439 let Some(progress) = self
440 .db
441 .prepare(
442 "SELECT managed, revisions, revised_at, working_on, working_until, stalled
443 FROM pulls WHERE id = ?",
444 )
445 .bind(&[pull.id.as_str().into()])?
446 .first::<Progress>(None)
447 .await?
448 .filter(|progress| progress.managed != 0)
449 else {
450 return Ok(None);
451 };
452 let now = rfc3339(now_ms());
453 let working_on = progress
454 .working_until
455 .as_deref()
456 .is_some_and(|until| until > now.as_str())
457 .then(|| progress.working_on.clone().unwrap_or_default());
458 let review = self
459 .db
460 .prepare(
461 "SELECT finished_at, verdict FROM review_runs
462 WHERE pull_id = ? AND finished_at IS NOT NULL ORDER BY id DESC LIMIT 1",
463 )
464 .bind(&[pull.id.as_str().into()])?
465 .first::<FinishedReview>(None)
466 .await?
467 // A review of what the change was before its last revision says
468 // nothing about what it is now.
469 .filter(|review| {
470 progress
471 .revised_at
472 .as_deref()
473 .is_none_or(|revised| review.finished_at.as_str() >= revised)
474 });
475 let settings = self.settings(&pull.repo_id).await?;
476 Ok(Some(decide(Facts {
477 draft: pull.status == PullStatus::Draft,
478 stalled: progress.stalled,
479 working_on,
480 check_status: pull.check_status,
481 review_pending: self.review_pending(&pull.id).await?,
482 has_checks: issue.as_ref().is_some_and(|issue| !issue.checks.is_empty()),
483 revisions: progress.revisions,
484 review,
485 behind,
486 auto_merge: settings.auto_merge,
487 require_up_to_date: settings.require_up_to_date,
488 agent_review: settings.agent_review,
489 max_revisions: settings.max_revisions,
490 approvals_missing: self.approvals_gap(&settings, pull).await?,
491 person_request: self
492 .person_request(pull, progress.revised_at.as_deref())
493 .await?,
494 queued: self.queued_entry(&pull.id).await?,
495 workflows: WorkflowFacts::of(&self.statuses(&pull.repo_id, pull.head_commit.as_deref()).await?),
496 })))
497 }
498
499 /// The latest request for changes by a person other than the author,
500 /// if it is that person's latest verdict and came after the last
501 /// revision.
502 async fn person_request(
503 &self,
504 pull: &Pull,
505 revised_at: Option<&str>,
506 ) -> Result<Option<PersonRequest>> {
507 #[derive(Deserialize)]
508 struct Verdicts {
509 author_id: String,
510 author_name: String,
511 verdict: Verdict,
512 created_at: String,
513 }
514 let rows = self
515 .db
516 .prepare(
517 "SELECT author_id, author_name, verdict, created_at FROM comments
518 WHERE repo_id = ? AND number = ? AND verdict IS NOT NULL
519 AND author_id != ? AND author_id != ?
520 ORDER BY id",
521 )
522 .bind(&[
523 pull.repo_id.as_str().into(),
524 pull.number.into(),
525 pull.author.id.as_str().into(),
526 AGENT_ID.into(),
527 ])?
528 .all()
529 .await?
530 .results::<Verdicts>()?;
531 // Each person's latest verdict is the one that stands.
532 let mut latest: HashMap<String, Verdicts> = HashMap::new();
533 for row in rows {
534 latest.insert(row.author_id.clone(), row);
535 }
536 Ok(latest
537 .into_values()
538 .filter(|row| row.verdict == Verdict::RequestChanges)
539 .filter(|row| revised_at.is_none_or(|revised| row.created_at.as_str() > revised))
540 .max_by(|a, b| a.created_at.cmp(&b.created_at))
541 .map(|row| PersonRequest {
542 author_id: row.author_id,
543 author_name: row.author_name,
544 created_at: row.created_at,
545 }))
546 }
547
548 /// Marks a pull request a g1t agent has just opened as one g1t sees
549 /// through.
550 pub(crate) async fn manage(&self, pull: &Pull) -> Result<()> {
551 if !made_by_g1t(pull) {
552 return Ok(());
553 }
554 self.db
555 .prepare("UPDATE pulls SET managed = 1 WHERE id = ?")
556 .bind(&[pull.id.as_str().into()])?
557 .run()
558 .await?;
559 Ok(())
560 }
561
562 /// Takes a step for a pull request, if nobody else has. One statement,
563 /// so that two callers cannot both take it.
564 async fn claim(&self, pull_id: &str, step: &str, minutes: u64, revising: bool) -> Result<bool> {
565 let now = now_ms();
566 let revision = if revising {
567 ", revisions = revisions + 1, revised_at = ?1"
568 } else {
569 ""
570 };
571 Ok(self
572 .db
573 .prepare(format!(
574 "UPDATE pulls SET working_on = ?2, working_until = ?3{revision}
575 WHERE id = ?4 AND status = 'open' AND stalled IS NULL
576 AND (working_until IS NULL OR working_until < ?1)
577 RETURNING id AS value"
578 ))
579 .bind(&[
580 rfc3339(now).into(),
581 step.into(),
582 rfc3339(now + minutes * 60 * 1000).into(),
583 pull_id.into(),
584 ])?
585 .first::<ValueRow>(None)
586 .await?
587 .is_some())
588 }
589
590 /// What the author is told when sent back: the checks that failed and
591 /// what they printed, or the review and its comments on lines.
592 async fn feedback(&self, pull: &Pull, feedback: &Feedback) -> Result<String> {
593 match feedback {
594 Feedback::FailedChecks => {
595 let failed: Vec<String> = self
596 .latest_checks(&pull.id)
597 .await?
598 .map(|run| run.results)
599 .unwrap_or_default()
600 .into_iter()
601 .filter(|result| !result.passed)
602 .map(|result| {
603 let length = result.output.chars().count();
604 let output: String = result
605 .output
606 .chars()
607 .skip(length.saturating_sub(MAX_CHECK_OUTPUT_CHARS))
608 .collect();
609 let exit = result
610 .exit_code
611 .map_or("it was stopped for taking too long".to_owned(), |code| {
612 format!("exit code {code}")
613 });
614 format!("`{}` failed ({exit}):\n\n{}", result.command, output.trim())
615 })
616 .collect();
617 Ok(format!(
618 "These acceptance checks were run against your change in a clean sandbox and failed.\n\n{}",
619 failed.join("\n\n")
620 ))
621 }
622 Feedback::FailedWorkflows => {
623 let statuses = self.statuses(&pull.repo_id, pull.head_commit.as_deref()).await?;
624 let failed: Vec<String> = statuses
625 .iter()
626 .filter(|s| s.state == "failure" || s.state == "error")
627 .map(|s| {
628 let run = s.target_url.as_deref().and_then(|url| url.rsplit('/').next()).unwrap_or_default();
629 format!(
630 "- {} ({}): run `{run}`",
631 s.context,
632 s.description.as_deref().unwrap_or("failed")
633 )
634 })
635 .collect();
636 Ok(format!(
637 "These GitHub Actions workflows failed on your latest commit:\n\n{}\n\n\
638 Read why with the `get_workflow_run` tool (this repository, and the run's id), \
639 then `get_job_logs` for the job that failed. Fix the cause in the code, not the workflow, \
640 unless the workflow itself is wrong.",
641 failed.join("\n")
642 ))
643 }
644 Feedback::Review(finished_at) => {
645 // Everything a review says is recorded at the moment it finished.
646 let notes = self
647 .db
648 .prepare(
649 "SELECT body, path, line FROM comments
650 WHERE repo_id = ? AND number = ? AND author_id = ? AND created_at = ?
651 ORDER BY id",
652 )
653 .bind(&[
654 pull.repo_id.as_str().into(),
655 pull.number.into(),
656 AGENT_ID.into(),
657 finished_at.as_str().into(),
658 ])?
659 .all()
660 .await?
661 .results::<ReviewNote>()?;
662 let mut on_lines = Vec::new();
663 let mut summary = String::new();
664 for note in notes {
665 match (note.path, note.line) {
666 (Some(path), Some(line)) => {
667 on_lines.push(format!("- `{path}` line {line}: {}", note.body));
668 }
669 (Some(path), None) => on_lines.push(format!("- `{path}`: {}", note.body)),
670 (None, _) => summary = note.body,
671 }
672 }
673 let mut text = format!(
674 "Another agent reviewed your change and asked for changes.\n\n{summary}"
675 );
676 if !on_lines.is_empty() {
677 text.push_str("\n\nIts comments on lines:\n");
678 text.push_str(&on_lines.join("\n"));
679 }
680 Ok(text)
681 }
682 Feedback::Person(request) => {
683 // What they wrote since the agent last revised, which their
684 // request for changes closes.
685 let revised: Option<String> = self
686 .db
687 .prepare("SELECT revised_at AS value FROM pulls WHERE id = ?")
688 .bind(&[pull.id.as_str().into()])?
689 .first::<Option<String>>(Some("value"))
690 .await?
691 .flatten();
692 let notes = self
693 .db
694 .prepare(
695 "SELECT body, path, line FROM comments
696 WHERE repo_id = ? AND number = ? AND author_id = ?
697 AND created_at > ? AND created_at <= ?
698 ORDER BY id",
699 )
700 .bind(&[
701 pull.repo_id.as_str().into(),
702 pull.number.into(),
703 request.author_id.as_str().into(),
704 revised.unwrap_or_default().into(),
705 request.created_at.as_str().into(),
706 ])?
707 .all()
708 .await?
709 .results::<ReviewNote>()?;
710 let mut on_lines = Vec::new();
711 let mut said = Vec::new();
712 for note in notes {
713 match (note.path, note.line) {
714 (Some(path), Some(line)) => {
715 on_lines.push(format!("- `{path}` line {line}: {}", note.body));
716 }
717 (Some(path), None) => on_lines.push(format!("- `{path}`: {}", note.body)),
718 (None, _) => said.push(note.body),
719 }
720 }
721 let mut text = format!(
722 "{} reviewed your change and asked for changes.\n\n{}",
723 request.author_name,
724 said.join("\n\n")
725 );
726 if !on_lines.is_empty() {
727 text.push_str("\n\nTheir comments on lines:\n");
728 text.push_str(&on_lines.join("\n"));
729 }
730 Ok(text)
731 }
732 }
733 }
734
735 pub(crate) async fn advance(&self, a: AdvanceArgs) -> Result<Advance> {
736 let Some(pull) = self.pull_by_id(&a.pull_id).await? else {
737 return Ok(Advance::None);
738 };
739 if pull.status != PullStatus::Open {
740 return Ok(Advance::None);
741 }
742 // Its author can read both the repository and the fork.
743 let viewer: Viewer = Some(pull.author.clone());
744 let repo: Outcome<Repo> = g1t_kit::call(
745 &self.repos,
746 "get_by_id",
747 &GetByIdArgs {
748 id: pull.repo_id.clone(),
749 viewer,
750 },
751 )
752 .await?;
753 let (Outcome::Ok(repo), Some(source)) = (repo, pull.fork.clone()) else {
754 return Ok(Advance::None);
755 };
756 let issue = match pull.issue {
757 Some(number) => self.issue(&pull.repo_id, number).await?,
758 None => None,
759 };
760 let behind = self.is_behind(&repo.id, &pull).await?;
761 let Some((lifecycle, next)) = self.assess(&pull, &issue, behind).await? else {
762 return Ok(Advance::None);
763 };
764
765 if matches!(next, Next::Merge) {
766 self.merge_by_policy(&repo, &pull).await?;
767 return Ok(Advance::None);
768 }
769 let (step, minutes) = match &next {
770 Next::Wait | Next::Merge => return Ok(Advance::None),
771 Next::Review => ("review", REVIEW_MINUTES),
772 Next::Revise(_) => ("revision", REVISION_MINUTES),
773 Next::CatchUp => ("catch_up", CATCH_UP_MINUTES),
774 };
775 let feedback = match &next {
776 Next::Revise(feedback) => self.feedback(&pull, feedback).await?,
777 _ => String::new(),
778 };
779 if !self
780 .claim(&pull.id, step, minutes, matches!(next, Next::Revise(_)))
781 .await?
782 {
783 return Ok(Advance::None);
784 }
785 // Said in the conversation, so nobody has to wonder why a review or
786 // a new commit appeared.
787 let told = match &next {
788 Next::Review => {
789 self.db
790 .prepare(
791 "UPDATE pulls SET reviewers = json_insert(reviewers, '$[#]', ?1)
792 WHERE id = ?2 AND NOT EXISTS (
793 SELECT 1 FROM json_each(pulls.reviewers) WHERE json_each.value = ?1)",
794 )
795 .bind(&[AGENT_NAME.into(), pull.id.as_str().into()])?
796 .run()
797 .await?;
798 "requested a review from g1t-agent".to_owned()
799 }
800 Next::Revise(Feedback::FailedChecks) => {
801 "sent g1t-agent back to fix the failed checks".to_owned()
802 }
803 Next::Revise(Feedback::FailedWorkflows) => {
804 "sent g1t-agent back to fix the failed workflows".to_owned()
805 }
806 Next::Revise(Feedback::Review(_)) => {
807 "sent g1t-agent back to address the review".to_owned()
808 }
809 _ => format!(
810 "asked g1t-agent to bring this up to date with {}",
811 repo.default_branch
812 ),
813 };
814 self.note(
815 &pull.repo_id,
816 pull.number,
817 (POLICY_ACTOR_ID, POLICY_ACTOR_NAME),
818 &told,
819 )
820 .await?;
821 let job = LifecycleJob {
822 pull_id: pull.id,
823 repo: RepoPath {
824 namespace: repo.namespace,
825 name: repo.name,
826 },
827 number: pull.number,
828 author: pull.author,
829 source,
830 branch: None,
831 default_branch: repo.default_branch,
832 title: pull.title,
833 description: pull.body.unwrap_or_default(),
834 issue,
835 feedback,
836 round: lifecycle.revisions + 1,
837 };
838 Ok(match next {
839 Next::Review => Advance::Review { job },
840 Next::Revise(_) => Advance::Revise { job },
841 Next::CatchUp => Advance::CatchUp { job },
842 Next::Wait | Next::Merge => Advance::None,
843 })
844 }
845
846 /// Lands a pull request that is ready, on the authority of the
847 /// repository's settings instead of a person's click.
848 async fn merge_by_policy(&self, repo: &Repo, pull: &Pull) -> Result<()> {
849 if !self.claim(&pull.id, "merge", MERGE_MINUTES, false).await? {
850 return Ok(());
851 }
852 // g1t acts for the workspace whose members turned this on.
853 let actor = User {
854 id: POLICY_ACTOR_ID.to_owned(),
855 username: POLICY_ACTOR_NAME.to_owned(),
856 verified: true,
857 workspaces: vec![Membership {
858 slug: repo.namespace.clone(),
859 role: Role::Member,
860 }],
861 ..User::default()
862 };
863 let merged = self
864 .merge_pull(PullActionArgs {
865 actor,
866 repo: RepoPath {
867 namespace: repo.namespace.clone(),
868 name: repo.name.clone(),
869 },
870 number: pull.number,
871 summary: String::new(),
872 keep_issue_open: false,
873 ignore_checks: false,
874 })
875 .await?;
876 match merged {
877 Outcome::Ok(_) => Ok(()),
878 // Most likely the branch moved in the moment between: let go, and
879 // the next look at it will catch up and try again.
880 Outcome::Fail(failure) if failure.code == FailureCode::Conflict => {
881 self.db
882 .prepare(
883 "UPDATE pulls SET working_on = NULL, working_until = NULL
884 WHERE id = ? AND working_on = 'merge'",
885 )
886 .bind(&[pull.id.as_str().into()])?
887 .run()
888 .await?;
889 Ok(())
890 }
891 Outcome::Fail(failure) => {
892 self.stall(StallArgs {
893 pull_id: pull.id.clone(),
894 reason: format!("g1t could not merge this: {}", failure.message),
895 })
896 .await?;
897 Ok(())
898 }
899 }
900 }
901
902 /// Records that a merge was asked for while the pull request was
903 /// behind, and announces it so that the runner brings it up to date.
904 pub(crate) async fn request_landing(
905 &self,
906 pull: &Pull,
907 actor: &User,
908 keep_issue_open: bool,
909 ) -> Result<()> {
910 let now = now_ms();
911 let request = serde_json::to_string(&LandRequest {
912 actor: actor.clone(),
913 keep_issue_open,
914 })?;
915 self.db
916 .prepare(
917 "UPDATE pulls
918 SET land_requested = ?, land_requested_at = ?, stalled = NULL,
919 working_on = 'catch_up', working_until = ?
920 WHERE id = ?",
921 )
922 .bind(&[
923 request.into(),
924 rfc3339(now).into(),
925 rfc3339(now + CATCH_UP_MINUTES * 60 * 1000).into(),
926 pull.id.as_str().into(),
927 ])?
928 .run()
929 .await?;
930 self.publish(
931 "pull.merge_requested",
932 &pull.repo_id,
933 actor,
934 PullEvent {
935 pull_id: pull.id.clone(),
936 repo_id: pull.repo_id.clone(),
937 number: pull.number,
938 issue: pull.issue,
939 ..PullEvent::default()
940 },
941 )
942 .await
943 }
944
945 /// The merge waiting on a pull request, if one was asked for recently
946 /// enough to still stand.
947 async fn land_request(&self, pull_id: &str) -> Result<Option<LandRequest>> {
948 let row = self
949 .db
950 .prepare("SELECT land_requested, land_requested_at, stalled FROM pulls WHERE id = ?")
951 .bind(&[pull_id.into()])?
952 .first::<LandRow>(None)
953 .await?;
954 let oldest = rfc3339(now_ms().saturating_sub(CATCH_UP_MINUTES * 60 * 1000));
955 Ok(row
956 .filter(|row| {
957 row.land_requested_at
958 .as_deref()
959 .is_some_and(|at| at >= oldest.as_str())
960 })
961 .and_then(|row| row.land_requested)
962 .and_then(|request| serde_json::from_str(&request).ok()))
963 }
964
965 /// Whether a merge is waiting on a pull request, and why g1t stopped
966 /// working on it if it did.
967 pub(crate) async fn landing_state(&self, pull_id: &str) -> Result<(bool, Option<String>)> {
968 let stalled = self
969 .db
970 .prepare("SELECT land_requested, land_requested_at, stalled FROM pulls WHERE id = ?")
971 .bind(&[pull_id.into()])?
972 .first::<LandRow>(None)
973 .await?
974 .and_then(|row| row.stalled);
975 Ok((self.land_request(pull_id).await?.is_some(), stalled))
976 }
977
978 async fn forget_landing(&self, pull_id: &str) -> Result<()> {
979 self.db
980 .prepare(
981 "UPDATE pulls SET land_requested = NULL, land_requested_at = NULL WHERE id = ?",
982 )
983 .bind(&[pull_id.into()])?
984 .run()
985 .await?;
986 Ok(())
987 }
988
989 /// Lands a pull request whose head has just moved, if a merge of it was
990 /// waiting for exactly that. What it was caught up to was already
991 /// checked and reviewed apart from the merge, so the checks are not
992 /// waited for again; a repository that wants them rerun turns on
993 /// "require up to date", and then nothing is landed this way.
994 pub(crate) async fn land_if_requested(&self, pull_id: &str) -> Result<()> {
995 let Some(request) = self.land_request(pull_id).await? else {
996 return Ok(());
997 };
998 self.forget_landing(pull_id).await?;
999 let Some(pull) = self.pull_by_id(pull_id).await? else {
1000 return Ok(());
1001 };
1002 let repo: Outcome<Repo> = g1t_kit::call(
1003 &self.repos,
1004 "get_by_id",
1005 &GetByIdArgs {
1006 id: pull.repo_id.clone(),
1007 viewer: Some(request.actor.clone()),
1008 },
1009 )
1010 .await?;
1011 let Outcome::Ok(repo) = repo else {
1012 return Ok(());
1013 };
1014 let merged = self
1015 .merge_pull(PullActionArgs {
1016 actor: request.actor,
1017 repo: RepoPath {
1018 namespace: repo.namespace,
1019 name: repo.name,
1020 },
1021 number: pull.number,
1022 summary: String::new(),
1023 keep_issue_open: request.keep_issue_open,
1024 ignore_checks: true,
1025 })
1026 .await?;
1027 if let Outcome::Fail(failure) = merged {
1028 self.stall(StallArgs {
1029 pull_id: pull.id,
1030 reason: format!(
1031 "It was brought up to date but could not be merged: {}",
1032 failure.message
1033 ),
1034 })
1035 .await?;
1036 }
1037 Ok(())
1038 }
1039
1040 /// What the runner needs to bring a pull request up to date for a merge
1041 /// that is waiting on it.
1042 pub(crate) async fn catch_up_job(&self, a: CatchUpJobArgs) -> Result<Option<LifecycleJob>> {
1043 if self.land_request(&a.pull_id).await?.is_none() {
1044 return Ok(None);
1045 }
1046 let Some(pull) = self.pull_by_id(&a.pull_id).await? else {
1047 return Ok(None);
1048 };
1049 // Its author can read both the repository and the pull request's source.
1050 let repo: Outcome<Repo> = g1t_kit::call(
1051 &self.repos,
1052 "get_by_id",
1053 &GetByIdArgs {
1054 id: pull.repo_id.clone(),
1055 viewer: Some(pull.author.clone()),
1056 },
1057 )
1058 .await?;
1059 let Outcome::Ok(repo) = repo else {
1060 return Ok(None);
1061 };
1062 let path = RepoPath {
1063 namespace: repo.namespace,
1064 name: repo.name,
1065 };
1066 let issue = match pull.issue {
1067 Some(number) => self.issue(&pull.repo_id, number).await?,
1068 None => None,
1069 };
1070 Ok(Some(LifecycleJob {
1071 pull_id: pull.id,
1072 source: pull.fork.unwrap_or_else(|| path.clone()),
1073 repo: path,
1074 number: pull.number,
1075 author: pull.author,
1076 branch: pull.branch,
1077 default_branch: repo.default_branch,
1078 title: pull.title,
1079 description: pull.body.unwrap_or_default(),
1080 issue,
1081 feedback: String::new(),
1082 round: 0,
1083 }))
1084 }
1085
1086 pub(crate) async fn stall(&self, a: StallArgs) -> Result<bool> {
1087 self.db
1088 .prepare(
1089 "UPDATE pulls
1090 SET stalled = ?, working_on = NULL, working_until = NULL,
1091 land_requested = NULL, land_requested_at = NULL
1092 WHERE id = ? AND status = 'open'",
1093 )
1094 .bind(&[a.reason.trim().into(), a.pull_id.as_str().into()])?
1095 .run()
1096 .await?;
1097 self.db
1098 .prepare("UPDATE pulls SET stage = 'needs_you', stage_detail = ? WHERE id = ?")
1099 .bind(&[a.reason.trim().into(), a.pull_id.into()])?
1100 .run()
1101 .await?;
1102 Ok(true)
1103 }
1104
1105 pub(crate) async fn managed_pulls(&self, a: ManagedPullsArgs) -> Result<Vec<String>> {
1106 let rows = self
1107 .db
1108 .prepare(
1109 "SELECT id AS value FROM pulls
1110 WHERE status = 'open' AND managed = 1 AND stalled IS NULL
1111 AND (?1 IS NULL OR repo_id = ?1)
1112 ORDER BY updated_at DESC LIMIT ?2",
1113 )
1114 .bind(&[
1115 a.repo_id.map_or(JsValue::NULL, JsValue::from),
1116 MANAGED_PAGE.into(),
1117 ])?
1118 .all()
1119 .await?
1120 .results::<ValueRow>()?;
1121 Ok(rows.into_iter().map(|row| row.value).collect())
1122 }
1123}
1124
1125#[cfg(test)]
1126mod tests {
1127 use super::*;
1128
1129 const MAX_REVISIONS: u32 = 2;
1130
1131 #[test]
1132 fn approvals_the_repository_wants_are_waited_for() {
1133 let short = || Facts {
1134 review: reviewed(Some(Verdict::Approve)),
1135 approvals_missing: Some("This repository requires 1 approving review.".to_owned()),
1136 ..facts()
1137 };
1138 let (lifecycle, next) = decide(short());
1139 assert_eq!(lifecycle.stage, Stage::NeedsYou);
1140 assert_eq!(
1141 lifecycle.detail,
1142 "This repository requires 1 approving review."
1143 );
1144 assert!(matches!(next, Next::Wait));
1145 // Not even a repository that merges by itself merges without them.
1146 let automatic = Facts {
1147 auto_merge: true,
1148 ..short()
1149 };
1150 assert_eq!(outcome(automatic), (Stage::NeedsYou, "wait"));
1151 }
1152
1153 #[test]
1154 fn a_repository_can_leave_review_to_people() {
1155 let unreviewed = Facts {
1156 agent_review: false,
1157 ..facts()
1158 };
1159 assert_eq!(outcome(unreviewed), (Stage::Ready, "wait"));
1160 let failing = Facts {
1161 agent_review: false,
1162 check_status: Some(CheckStatus::Failed),
1163 ..facts()
1164 };
1165 assert_eq!(outcome(failing), (Stage::Revising, "revise for checks"));
1166 }
1167
1168 #[test]
1169 fn a_repository_sets_how_often_the_author_is_sent_back() {
1170 let never = Facts {
1171 max_revisions: 0,
1172 check_status: Some(CheckStatus::Failed),
1173 ..facts()
1174 };
1175 assert_eq!(outcome(never), (Stage::NeedsYou, "wait"));
1176 }
1177
1178 /// A pull request that is ready for review, with checks that passed
1179 /// and nothing else yet.
1180 fn facts() -> Facts {
1181 Facts {
1182 draft: false,
1183 stalled: None,
1184 working_on: None,
1185 check_status: Some(CheckStatus::Passed),
1186 review_pending: false,
1187 has_checks: true,
1188 revisions: 0,
1189 review: None,
1190 behind: false,
1191 auto_merge: false,
1192 require_up_to_date: false,
1193 agent_review: true,
1194 max_revisions: MAX_REVISIONS,
1195 approvals_missing: None,
1196 person_request: None,
1197 queued: None,
1198 workflows: WorkflowFacts::default(),
1199 }
1200 }
1201
1202 #[test]
1203 fn failed_workflows_send_the_agent_back_and_running_ones_wait() {
1204 let failed = Facts {
1205 workflows: WorkflowFacts { pending: vec![], failed: vec!["CI / pull_request".into()] },
1206 ..facts()
1207 };
1208 let (lifecycle, next) = decide(failed);
1209 assert!(matches!(next, Next::Revise(Feedback::FailedWorkflows)));
1210 assert!(lifecycle.detail.contains("CI / pull_request failed"));
1211 let running = Facts {
1212 workflows: WorkflowFacts { pending: vec!["CI / pull_request".into()], failed: vec![] },
1213 ..facts()
1214 };
1215 let (lifecycle, next) = decide(running);
1216 assert!(matches!(next, Next::Wait));
1217 assert!(lifecycle.detail.contains("Waiting for CI / pull_request"));
1218 }
1219
1220 #[test]
1221 fn a_queued_pull_request_waits_in_the_queue() {
1222 let queued = Facts {
1223 review: reviewed(Some(Verdict::Approve)),
1224 queued: Some((QueueState::Testing, vec![12, 14])),
1225 auto_merge: true,
1226 ..facts()
1227 };
1228 let (lifecycle, next) = decide(queued);
1229 assert_eq!(lifecycle.stage, Stage::Queued);
1230 assert!(lifecycle.detail.contains("#12, #14"));
1231 assert!(matches!(next, Next::Wait));
1232 }
1233
1234 fn asked_by_a_person() -> Option<PersonRequest> {
1235 Some(PersonRequest {
1236 author_id: "usr_reviewer".to_owned(),
1237 author_name: "g1t-reviewer".to_owned(),
1238 created_at: "2026-10-02T11:00:00.000Z".to_owned(),
1239 })
1240 }
1241
1242 #[test]
1243 fn a_person_asking_for_changes_sends_the_agent_back() {
1244 let asked = Facts {
1245 review: reviewed(Some(Verdict::Approve)),
1246 approvals_missing: Some("A reviewer has asked for changes.".to_owned()),
1247 person_request: asked_by_a_person(),
1248 ..facts()
1249 };
1250 let (lifecycle, _) = decide(Facts {
1251 person_request: asked_by_a_person(),
1252 ..facts()
1253 });
1254 assert!(lifecycle.detail.starts_with("g1t-reviewer asked for changes"));
1255 assert_eq!(outcome(asked), (Stage::Revising, "revise for a person"));
1256 }
1257
1258 #[test]
1259 fn a_person_is_asked_once_the_revisions_run_out() {
1260 let exhausted = Facts {
1261 person_request: asked_by_a_person(),
1262 revisions: MAX_REVISIONS,
1263 ..facts()
1264 };
1265 assert_eq!(outcome(exhausted), (Stage::NeedsYou, "wait"));
1266 }
1267
1268 fn reviewed(verdict: Option<Verdict>) -> Option<FinishedReview> {
1269 Some(FinishedReview {
1270 finished_at: "2026-10-02T10:00:00.000Z".to_owned(),
1271 verdict,
1272 })
1273 }
1274
1275 /// The stage, and a word for the step to take.
1276 fn outcome(facts: Facts) -> (Stage, &'static str) {
1277 let (lifecycle, next) = decide(facts);
1278 let step = match next {
1279 Next::Wait => "wait",
1280 Next::Review => "review",
1281 Next::Revise(Feedback::FailedChecks) => "revise for checks",
1282 Next::Revise(Feedback::FailedWorkflows) => "revise for workflows",
1283 Next::Revise(Feedback::Review(_)) => "revise for review",
1284 Next::Revise(Feedback::Person(_)) => "revise for a person",
1285 Next::CatchUp => "catch up",
1286 Next::Merge => "merge",
1287 };
1288 (lifecycle.stage, step)
1289 }
1290
1291 #[test]
1292 fn nothing_is_started_while_the_agent_is_still_working() {
1293 let draft = Facts {
1294 draft: true,
1295 check_status: None,
1296 ..facts()
1297 };
1298 assert_eq!(outcome(draft), (Stage::Working, "wait"));
1299 }
1300
1301 #[test]
1302 fn checks_come_before_review() {
1303 let unchecked = Facts {
1304 check_status: None,
1305 ..facts()
1306 };
1307 assert_eq!(outcome(unchecked), (Stage::Checking, "wait"));
1308 let running = Facts {
1309 check_status: Some(CheckStatus::Running),
1310 ..facts()
1311 };
1312 assert_eq!(outcome(running), (Stage::Checking, "wait"));
1313 assert_eq!(outcome(facts()), (Stage::Reviewing, "review"));
1314 }
1315
1316 #[test]
1317 fn an_issue_without_checks_goes_straight_to_review() {
1318 let unchecked = Facts {
1319 has_checks: false,
1320 check_status: None,
1321 ..facts()
1322 };
1323 assert_eq!(outcome(unchecked), (Stage::Reviewing, "review"));
1324 }
1325
1326 #[test]
1327 fn failed_checks_send_the_author_back() {
1328 let failed = Facts {
1329 check_status: Some(CheckStatus::Failed),
1330 ..facts()
1331 };
1332 assert_eq!(outcome(failed), (Stage::Revising, "revise for checks"));
1333 }
1334
1335 #[test]
1336 fn checks_that_could_not_run_are_a_persons_problem() {
1337 let errored = Facts {
1338 check_status: Some(CheckStatus::Errored),
1339 ..facts()
1340 };
1341 assert_eq!(outcome(errored), (Stage::NeedsYou, "wait"));
1342 }
1343
1344 #[test]
1345 fn a_review_asking_for_changes_sends_the_author_back() {
1346 let changes = Facts {
1347 review: reviewed(Some(Verdict::RequestChanges)),
1348 ..facts()
1349 };
1350 assert_eq!(outcome(changes), (Stage::Revising, "revise for review"));
1351 }
1352
1353 #[test]
1354 fn the_author_is_sent_back_only_so_many_times() {
1355 let failing = Facts {
1356 check_status: Some(CheckStatus::Failed),
1357 revisions: MAX_REVISIONS,
1358 ..facts()
1359 };
1360 assert_eq!(outcome(failing), (Stage::NeedsYou, "wait"));
1361 let unconvinced = Facts {
1362 review: reviewed(Some(Verdict::RequestChanges)),
1363 revisions: MAX_REVISIONS,
1364 ..facts()
1365 };
1366 assert_eq!(outcome(unconvinced), (Stage::NeedsYou, "wait"));
1367 // One short of the limit still gets another go.
1368 let once = Facts {
1369 check_status: Some(CheckStatus::Failed),
1370 revisions: MAX_REVISIONS - 1,
1371 ..facts()
1372 };
1373 assert_eq!(outcome(once), (Stage::Revising, "revise for checks"));
1374 }
1375
1376 #[test]
1377 fn a_review_that_could_not_be_written_is_not_retried() {
1378 let broken = Facts {
1379 review: reviewed(None),
1380 ..facts()
1381 };
1382 assert_eq!(outcome(broken), (Stage::NeedsYou, "wait"));
1383 }
1384
1385 #[test]
1386 fn being_behind_only_holds_a_change_up_where_the_repository_says_so() {
1387 let behind = || Facts {
1388 review: reviewed(Some(Verdict::Approve)),
1389 behind: true,
1390 ..facts()
1391 };
1392 // By default it is ready as it is; merging brings it up to date.
1393 assert_eq!(outcome(behind()), (Stage::Ready, "wait"));
1394 let strict = Facts {
1395 require_up_to_date: true,
1396 ..behind()
1397 };
1398 assert_eq!(outcome(strict), (Stage::CatchingUp, "catch up"));
1399 let current = Facts {
1400 review: reviewed(Some(Verdict::Approve)),
1401 ..facts()
1402 };
1403 assert_eq!(outcome(current), (Stage::Ready, "wait"));
1404 }
1405
1406 #[test]
1407 fn a_ready_change_lands_by_itself_only_where_the_repository_says_so() {
1408 let ready = || Facts {
1409 review: reviewed(Some(Verdict::Approve)),
1410 ..facts()
1411 };
1412 assert_eq!(outcome(ready()), (Stage::Ready, "wait"));
1413 let automatic = Facts {
1414 auto_merge: true,
1415 ..ready()
1416 };
1417 assert_eq!(outcome(automatic), (Stage::Ready, "merge"));
1418 // One that is behind is merged too: merging brings it up to date.
1419 let behind = Facts {
1420 auto_merge: true,
1421 behind: true,
1422 ..ready()
1423 };
1424 assert_eq!(outcome(behind), (Stage::Ready, "merge"));
1425 // Unless the repository wants it caught up and checked again first.
1426 let strict = Facts {
1427 auto_merge: true,
1428 behind: true,
1429 require_up_to_date: true,
1430 ..ready()
1431 };
1432 assert_eq!(outcome(strict), (Stage::CatchingUp, "catch up"));
1433 // Nothing short of approved is merged, whatever the setting.
1434 let failing = Facts {
1435 auto_merge: true,
1436 check_status: Some(CheckStatus::Failed),
1437 ..ready()
1438 };
1439 assert_eq!(outcome(failing), (Stage::Revising, "revise for checks"));
1440 let unreviewed = Facts {
1441 auto_merge: true,
1442 ..facts()
1443 };
1444 assert_eq!(outcome(unreviewed), (Stage::Reviewing, "review"));
1445 }
1446
1447 #[test]
1448 fn catching_up_reruns_the_checks_but_not_the_review() {
1449 // The merge moved the head, so the checks are waited for again.
1450 let merged_in = Facts {
1451 review: reviewed(Some(Verdict::Approve)),
1452 check_status: None,
1453 ..facts()
1454 };
1455 assert_eq!(outcome(merged_in), (Stage::Checking, "wait"));
1456 }
1457
1458 #[test]
1459 fn a_step_under_way_is_not_started_again() {
1460 for (step, stage) in [
1461 ("review", Stage::Reviewing),
1462 ("revision", Stage::Revising),
1463 ("catch_up", Stage::CatchingUp),
1464 ] {
1465 let busy = Facts {
1466 working_on: Some(step.to_owned()),
1467 // Whatever else is true, the step in hand comes first.
1468 check_status: Some(CheckStatus::Failed),
1469 ..facts()
1470 };
1471 assert_eq!(outcome(busy), (stage, "wait"));
1472 }
1473 let asked = Facts {
1474 review_pending: true,
1475 ..facts()
1476 };
1477 assert_eq!(outcome(asked), (Stage::Reviewing, "wait"));
1478 }
1479
1480 #[test]
1481 fn once_stopped_it_stays_stopped() {
1482 let (lifecycle, next) = decide(Facts {
1483 stalled: Some("The agent could not catch up.".to_owned()),
1484 review: reviewed(Some(Verdict::Approve)),
1485 behind: true,
1486 ..facts()
1487 });
1488 assert_eq!(lifecycle.stage, Stage::NeedsYou);
1489 assert_eq!(lifecycle.detail, "The agent could not catch up.");
1490 assert!(matches!(next, Next::Wait));
1491 }
1492}