flagon-io/g1t

public

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

g1t/services/work/src/lifecycle.rs

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