Skip to main content

magi/
landing.rs

1//! Read-only landing evidence for change tasks.
2//!
3//! The housekeeping worker runs bounded passes ([`audit_pass`]) to cache a
4//! three-way verdict ([`State::Landed`], [`State::NotLanded`], [`State::Unknown`])
5//! on each completed change task without changing its status or activity
6//! timestamp, and promotes a task held for [`crate::queue::MachineHoldCause::AwaitingLanding`]
7//! once its exact retained run is confirmed landed on its target base.
8
9use std::path::Path;
10use std::process::{Output, Stdio};
11use std::time::Duration;
12
13use jiff::Timestamp;
14use serde::{Deserialize, Serialize};
15
16use crate::config::{MergeMode, MergeStyle};
17use crate::land::ExternalMerge;
18use crate::notices::{Link, Notice, Notices};
19use crate::queue::{CompletionActor, CompletionContext, Queue, Task, TaskStatus};
20use crate::run::{Liveness, RunState, RunStatus};
21
22/// What the audit could establish about landing on the run's target base.
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
24#[serde(rename_all = "snake_case")]
25pub enum State {
26    /// Confirmed landing on the run's target base.
27    Landed,
28    /// Confirmed absence of a landing.
29    NotLanded,
30    /// Evidence was unavailable or inconclusive.
31    Unknown,
32}
33
34/// Cached verdict for a task's most recent execution run.
35#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
36pub struct LandingNote {
37    /// The verdict.
38    pub state: State,
39    /// The evidence or the reason it was inconclusive.
40    pub reason: String,
41    /// The run ID this verdict describes.
42    pub run: String,
43    /// When the audit finished.
44    pub checked_at: Timestamp,
45}
46
47/// Summary of one bounded [`audit_pass`].
48#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
49pub struct Summary {
50    /// Tasks audited in this pass.
51    pub audited: usize,
52    /// Held awaiting-landing tasks promoted to `done` after confirmed landing.
53    pub promoted: usize,
54    /// Audited tasks with confirmed `NotLanded`.
55    pub not_landed: usize,
56}
57
58/// Timeouts for external landing probes and each audited task.
59#[derive(Debug, Clone, Copy)]
60pub struct Limits {
61    /// Timeout for a single `git` invocation.
62    pub git: Duration,
63    /// Timeout for a single `gh` invocation.
64    pub gh: Duration,
65    /// Total budget for auditing one task before recording `Unknown`.
66    pub per_item: Duration,
67}
68
69impl Default for Limits {
70    fn default() -> Self {
71        Self {
72            git: Duration::from_secs(15),
73            gh: Duration::from_secs(20),
74            per_item: Duration::from_secs(30),
75        }
76    }
77}
78
79/// Maximum tasks audited in one housekeeping pass.
80pub const MAX_PER_PASS: usize = 5;
81/// Minimum interval before re-auditing a `NotLanded` or `Unknown` note.
82pub const RECHECK_SECS: i64 = 30 * 60;
83const NOTICE_PREFIX: &str = "landing:";
84const PR_LIMIT: usize = 30;
85
86#[derive(Clone, Copy)]
87struct Head<'a> {
88    branch: &'a str,
89    sha: &'a str,
90}
91
92impl<'a> Head<'a> {
93    fn recorded(run: &'a RunState) -> Option<Self> {
94        let (branch, sha) = if let Some(sha) = run.pr_merged_head.as_deref() {
95            (run.pr_branch()?, sha)
96        } else if let Some(sha) = run.pr_pushed_head.as_deref() {
97            (run.pr_branch()?, sha)
98        } else {
99            (run.winner()?.branch.as_str(), run.gate_head.as_deref()?)
100        };
101        (!branch.is_empty() && full_oid(sha)).then_some(Self { branch, sha })
102    }
103}
104
105enum Branch {
106    Empty,
107    InBase(String),
108    /// Not in the base at the exact tracking-ref commit SHA that was tested.
109    OutsideBase(String),
110}
111
112enum Facts {
113    Recorded,
114    Unavailable(&'static str),
115    Empty,
116    InBase,
117    Compared {
118        git_error: Option<String>,
119        forge: Result<Option<ExternalMerge>, String>,
120    },
121}
122
123fn judge(base: &str, squash_without_pr: bool, facts: Facts) -> (State, String) {
124    match facts {
125        Facts::Recorded => (State::Landed, "the run recorded a confirmed landing".into()),
126        Facts::Unavailable(reason) => (State::Unknown, reason.into()),
127        Facts::Empty => (
128            State::NotLanded,
129            "the recorded head has the same tree as its recorded comparison base".into(),
130        ),
131        Facts::InBase => (
132            State::Landed,
133            format!("{base} contains the run's recorded head"),
134        ),
135        Facts::Compared { git_error, forge } => match (forge, git_error) {
136            (Ok(Some(pr)), _) => (State::Landed, format!("merged into {base}: {}", pr.url)),
137            (Ok(None), None) if squash_without_pr => (
138                State::Unknown,
139                "no exact landing evidence; a manual or local squash would not preserve the recorded head"
140                    .into(),
141            ),
142            (Ok(None), None) => (
143                State::NotLanded,
144                format!(
145                    "{base} does not contain the recorded head and no matching pull request merged there"
146                ),
147            ),
148            (Ok(None), Some(reason)) | (Err(reason), None) => (State::Unknown, reason),
149            (Err(forge_error), Some(git_error)) => {
150                (State::Unknown, format!("{git_error}; {forge_error}"))
151            }
152        },
153    }
154}
155
156fn full_oid(sha: &str) -> bool {
157    matches!(sha.len(), 40 | 64)
158        && !sha.bytes().all(|b| b == b'0')
159        && sha.bytes().all(|b| b.is_ascii_hexdigit())
160}
161
162fn remote(run: &RunState) -> &str {
163    run.fetched_base
164        .as_ref()
165        .map_or(&run.config.merge.remote, |base| &base.remote)
166}
167
168async fn probe(program: &str, args: &[&str], repo: &Path) -> Result<Output, String> {
169    tokio::process::Command::new(program)
170        .args(args)
171        .current_dir(repo)
172        .env_remove("GH_REPO")
173        .env_remove("GIT_DIR")
174        .env_remove("GIT_COMMON_DIR")
175        .env_remove("GIT_WORK_TREE")
176        .env_remove("GIT_NAMESPACE")
177        .env_remove("GIT_OBJECT_DIRECTORY")
178        .env_remove("GIT_ALTERNATE_OBJECT_DIRECTORIES")
179        .env_remove("GIT_INDEX_FILE")
180        .env("GH_PROMPT_DISABLED", "1")
181        .env("GIT_TERMINAL_PROMPT", "0")
182        .env("GIT_NO_LAZY_FETCH", "1")
183        .env("GIT_NO_REPLACE_OBJECTS", "1")
184        .env("GIT_OPTIONAL_LOCKS", "0")
185        .stdin(Stdio::null())
186        .kill_on_drop(true)
187        .output()
188        .await
189        .map_err(|e| format!("{program}: {e}"))
190}
191
192fn stdout(out: &Output) -> Result<&str, String> {
193    std::str::from_utf8(&out.stdout)
194        .map(str::trim)
195        .map_err(|e| format!("invalid UTF-8: {e}"))
196}
197
198fn git_failure(operation: &str, out: &Output) -> String {
199    format!("git {operation} failed ({})", out.status)
200}
201
202async fn git_predicate(repo: &Path, args: &[&str]) -> Result<bool, String> {
203    let out = probe("git", args, repo).await?;
204    match out.status.code() {
205        Some(0) => Ok(true),
206        Some(1) => Ok(false),
207        _ => Err(git_failure(args[0], &out)),
208    }
209}
210
211async fn ancestor(repo: &Path, earlier: &str, later: &str) -> Result<bool, String> {
212    git_predicate(repo, &["merge-base", "--is-ancestor", earlier, later]).await
213}
214
215async fn local_branch(run: &RunState, head: Head<'_>) -> Result<Branch, String> {
216    let repo = &run.repo;
217    let start = match &run.base_sync {
218        Some(sync) if sync.conflict.is_none() => &sync.tip,
219        Some(_) => return Err("the saved base synchronization did not finish".into()),
220        None => &run.base_commit,
221    };
222    let base_ref = format!("refs/remotes/{}/{}", remote(run), run.base_branch);
223    let resolved = probe(
224        "git",
225        &["show-ref", "--verify", "--hash", "--", &base_ref],
226        repo,
227    )
228    .await?;
229    if !resolved.status.success() {
230        return Err(git_failure("show-ref (remote base)", &resolved));
231    }
232    let tested_base = stdout(&resolved)?;
233    if !full_oid(tested_base) || !full_oid(start) {
234        return Err("the recorded comparison base or remote base is not a full commit ID".into());
235    }
236    // The public PR name can differ from the retained local winner branch.
237    let branch = run
238        .winner()
239        .map_or(head.branch, |winner| winner.branch.as_str());
240    let branch_ref = format!("refs/heads/{branch}");
241    let retained = probe(
242        "git",
243        &["show-ref", "--verify", "--hash", "--", &branch_ref],
244        repo,
245    )
246    .await?;
247    if !retained.status.success() {
248        return Err(git_failure("show-ref (retained branch)", &retained));
249    }
250    if !ancestor(repo, start, head.sha).await? {
251        return Err("the recorded head does not descend from its recorded comparison base".into());
252    }
253    // Check emptiness before ancestry: a rebased empty branch equal to base is NotLanded.
254    if git_predicate(
255        repo,
256        &[
257            "diff",
258            "--quiet",
259            "--no-ext-diff",
260            "--no-textconv",
261            "--ignore-submodules=none",
262            start,
263            head.sha,
264            "--",
265        ],
266    )
267    .await?
268    {
269        return Ok(Branch::Empty);
270    }
271    if ancestor(repo, head.sha, tested_base).await? {
272        return Ok(Branch::InBase(tested_base.to_owned()));
273    }
274    let shallow = probe("git", &["rev-parse", "--is-shallow-repository"], repo).await?;
275    if !shallow.status.success() || stdout(&shallow)? != "false" {
276        return Err("local history may be incomplete; ancestry is unconfirmed".into());
277    }
278    Ok(Branch::OutsideBase(tested_base.to_owned()))
279}
280
281fn repo_component(part: &str) -> bool {
282    !part.is_empty()
283        && part != "."
284        && part != ".."
285        && part
286            .bytes()
287            .all(|b| b.is_ascii_alphanumeric() || b"-_.".contains(&b))
288}
289
290fn remote_repository(url: &str) -> Option<String> {
291    let (authority, path) = if let Some(rest) = url
292        .strip_prefix("https://")
293        .or_else(|| url.strip_prefix("http://"))
294        .or_else(|| url.strip_prefix("ssh://"))
295    {
296        rest.split_once('/')?
297    } else {
298        let (user_host, path) = url.split_once(':')?;
299        if !user_host.contains('@') {
300            return None;
301        }
302        (user_host, path)
303    };
304    let host = authority.rsplit('@').next()?;
305    let (owner, repo) = path.trim_end_matches('/').split_once('/')?;
306    let repo = repo.strip_suffix(".git").unwrap_or(repo);
307    [host, owner, repo]
308        .into_iter()
309        .all(repo_component)
310        .then(|| format!("{host}/{owner}/{repo}"))
311}
312
313fn pr_repository(url: &str, number: u64) -> Option<&str> {
314    let (repository, pr) = url.strip_prefix("https://")?.rsplit_once("/pull/")?;
315    let (host, path) = repository.split_once('/')?;
316    let (owner, repo) = path.split_once('/')?;
317    (number != 0
318        && pr.bytes().all(|b| b.is_ascii_digit())
319        && pr.parse::<u64>().ok() == Some(number)
320        && [host, owner, repo].into_iter().all(repo_component))
321    .then_some(repository)
322}
323
324#[derive(Deserialize)]
325#[serde(rename_all = "camelCase")]
326struct MergedPr {
327    url: String,
328    number: u64,
329    state: String,
330    merged_at: Timestamp,
331    base_ref_name: String,
332    head_ref_name: String,
333    head_ref_oid: String,
334    is_cross_repository: bool,
335}
336
337fn merged_pr(
338    json: &str,
339    repository: &str,
340    base: &str,
341    since: Timestamp,
342    head: Head<'_>,
343) -> Result<Option<ExternalMerge>, String> {
344    let prs: Vec<MergedPr> =
345        serde_json::from_str(json).map_err(|e| format!("invalid forge response: {e}"))?;
346    if prs.len() >= PR_LIMIT {
347        return Err("the forge response reached the pull request limit".into());
348    }
349    let mut found = None;
350    for pr in prs {
351        if pr.state != "MERGED"
352            || pr.base_ref_name.is_empty()
353            || pr.head_ref_name != head.branch
354            || !full_oid(&pr.head_ref_oid)
355            || !pr_repository(&pr.url, pr.number)
356                .is_some_and(|r| r.eq_ignore_ascii_case(repository))
357        {
358            return Err("the forge returned incomplete or unexpected pull request evidence".into());
359        }
360        if pr.base_ref_name == base
361            && pr.merged_at >= since
362            && pr.head_ref_oid.eq_ignore_ascii_case(head.sha)
363            && !pr.is_cross_repository
364        {
365            if found.is_some() {
366                return Err("multiple pull requests match the run's head".into());
367            }
368            found = Some(ExternalMerge {
369                url: pr.url,
370                number: pr.number,
371            });
372        }
373    }
374    Ok(found)
375}
376
377async fn forge_merge(
378    run: &RunState,
379    head: Head<'_>,
380    limits: Limits,
381) -> Result<Option<ExternalMerge>, String> {
382    let out = tokio::time::timeout(
383        limits.git,
384        probe("git", &["remote", "get-url", "--", remote(run)], &run.repo),
385    )
386    .await
387    .map_err(|_| "git remote lookup timed out")??;
388    if !out.status.success() {
389        return Err(git_failure("remote get-url", &out));
390    }
391    let repository = remote_repository(stdout(&out)?)
392        .ok_or("the run's remote is not a known forge repository")?;
393    if let Some(pr) = &run.pr
394        && !pr_repository(&pr.url, pr.number).is_some_and(|r| r.eq_ignore_ascii_case(&repository))
395    {
396        return Err("the recorded pull request belongs to a different repository".into());
397    }
398    let limit = PR_LIMIT.to_string();
399    let args = [
400        "pr",
401        "list",
402        "--repo",
403        &repository,
404        "--head",
405        head.branch,
406        "--state",
407        "merged",
408        "--limit",
409        &limit,
410        "--json",
411        "url,number,state,mergedAt,baseRefName,headRefName,headRefOid,isCrossRepository",
412    ];
413    let out = tokio::time::timeout(limits.gh, probe("gh", &args, &run.repo))
414        .await
415        .map_err(|_| "forge lookup timed out")??;
416    if !out.status.success() || !out.stderr.is_empty() {
417        return Err(format!(
418            "gh pr list did not return a clean result ({})",
419            out.status
420        ));
421    }
422    merged_pr(
423        stdout(&out)?,
424        &repository,
425        &run.base_branch,
426        run.created_at,
427        head,
428    )
429}
430
431/// Did the run itself record a confirmed remote landing on its target base?
432///
433/// Local merges (`MergeMode::Local`) are deliberately excluded: a local merge
434/// does not prove the commits reached the remote base branch and must be
435/// verified against the remote tracking ref or forge.
436pub(crate) fn recorded_landing(run: &RunState) -> bool {
437    match run.status {
438        RunStatus::AlreadyInBase => run.base_sync.as_ref().is_some_and(|sync| {
439            sync.conflict.is_none()
440                && sync.already_in.as_ref().is_some_and(|evidence| {
441                    evidence.tip == sync.tip
442                        && full_oid(&evidence.tip)
443                        && evidence.commits.iter().all(|commit| full_oid(commit))
444                })
445        }),
446        RunStatus::Merged => run
447            .merge
448            .as_ref()
449            .is_some_and(|m| m.ok && !m.empty && m.mode == MergeMode::Pr),
450        _ => false,
451    }
452}
453
454/// Whether a `Ready` run already carries confirmed merge evidence during
455/// settlement (either a recorded remote landing or a merged PR record for its
456/// published head).
457pub(crate) fn run_landed_for_settle(run: &RunState) -> bool {
458    if recorded_landing(run) {
459        return true;
460    }
461    run.status == RunStatus::Ready
462        && !run.merge.as_ref().is_some_and(|m| m.empty)
463        && run.pr.as_ref().is_some_and(|pr| pr.state == "merged")
464        && run.pr_merged_head.as_deref().is_some_and(full_oid)
465}
466
467/// Compare the exact tracking-ref SHA that `local_branch` audited against the
468/// remote's live base tip. Never re-reads `refs/remotes/...`, so a concurrent
469/// `git fetch` cannot mask a stale ancestry check.
470async fn base_is_stale(run: &RunState, tested: &str, limits: Limits) -> Option<String> {
471    let remote = remote(run);
472    let reference = format!("refs/heads/{}", run.base_branch);
473    let live = tokio::time::timeout(
474        limits.git,
475        probe(
476            "git",
477            &["ls-remote", "--exit-code", "--", remote, &reference],
478            &run.repo,
479        ),
480    )
481    .await;
482    let live = match live {
483        Ok(Ok(out)) if out.status.success() => stdout(&out)
484            .ok()
485            .and_then(|text| text.split_whitespace().next())
486            .filter(|sha| full_oid(sha))
487            .map(str::to_owned),
488        _ => None,
489    };
490    let Some(live) = live else {
491        return Some("the remote base could not be read to confirm the tracking ref".into());
492    };
493    if tested.eq_ignore_ascii_case(&live) {
494        None
495    } else {
496        Some("the tracking ref of the base is stale; fetch it before judging".into())
497    }
498}
499
500async fn gather_facts(run: &RunState, limits: Limits) -> Facts {
501    if recorded_landing(run) {
502        return Facts::Recorded;
503    }
504    if run.merge.as_ref().is_some_and(|m| m.empty)
505        || run.winner().is_some_and(|winner| winner.empty)
506    {
507        return Facts::Empty;
508    }
509    let Some(head) = Head::recorded(run) else {
510        return Facts::Unavailable("the run did not record an exact head to audit");
511    };
512    if !run.repo.join(".git").exists() {
513        return Facts::Unavailable("the run's repository checkout is unavailable");
514    }
515    match tokio::time::timeout(limits.git, local_branch(run, head)).await {
516        Ok(Ok(Branch::Empty)) => Facts::Empty,
517        Ok(Ok(Branch::InBase(tested))) => match base_is_stale(run, &tested, limits).await {
518            None => Facts::InBase,
519            Some(git_error) => Facts::Compared {
520                git_error: Some(git_error),
521                forge: Ok(None),
522            },
523        },
524        Ok(Ok(Branch::OutsideBase(tested))) => {
525            // Query remote freshness and forge in parallel so `ls-remote` does
526            // not extend worst-case audit latency beyond the forge timeout.
527            let (git_error, forge) = tokio::join!(
528                base_is_stale(run, &tested, limits),
529                forge_merge(run, head, limits),
530            );
531            Facts::Compared { git_error, forge }
532        }
533        Ok(Err(e)) => Facts::Compared {
534            git_error: Some(e),
535            forge: forge_merge(run, head, limits).await,
536        },
537        Err(_) => Facts::Compared {
538            git_error: Some("local Git lookup timed out".into()),
539            forge: forge_merge(run, head, limits).await,
540        },
541    }
542}
543
544/// Evaluate landing state for `run` under `limits`.
545pub async fn verdict(run: &RunState, limits: Limits) -> (State, String) {
546    let squash_without_pr = matches!(run.config.merge.mode, MergeMode::None | MergeMode::Local)
547        && run.config.merge.style == MergeStyle::Squash;
548    judge(
549        &run.base_branch,
550        squash_without_pr,
551        gather_facts(run, limits).await,
552    )
553}
554
555/// The run audited for a completed change task, if any. A change task that
556/// completed without any execution run yields the empty run id, which can
557/// never be confirmed landed. Investigations and explicitly discarded tasks
558/// are exempt.
559pub(crate) fn audited_run(task: &Task) -> Option<&str> {
560    if task.status != TaskStatus::Done || task.investigation || task.completed_by_discard() {
561        return None;
562    }
563    Some(task.execution_runs().last().map_or("", String::as_str))
564}
565
566/// The retained run of a task held for awaiting landing, if it still matches
567/// the latest execution run in the current assignment.
568pub(crate) fn awaiting_landing_run(task: &Task) -> Option<&str> {
569    if task.status != TaskStatus::Held || task.investigation {
570        return None;
571    }
572    let run = task.awaiting_landing_run()?;
573    (task.execution_runs().last().map(String::as_str) == Some(run)).then_some(run)
574}
575
576fn target_run(task: &Task) -> Option<&str> {
577    audited_run(task).or_else(|| awaiting_landing_run(task))
578}
579
580/// Load `id` and verify that it belongs to `task`'s current repository
581/// assignment and current authored instruction generation.
582pub(crate) fn load_run(home: &Path, task: &Task, id: &str) -> anyhow::Result<RunState> {
583    anyhow::ensure!(crate::run::is_run_id(id), "invalid execution run ID");
584    let run = RunState::load_under(id, home)?;
585    let owner = run
586        .origin
587        .as_ref()
588        .and_then(|origin| origin.task.as_deref());
589    let same_repo = run.repo == task.repo
590        || run
591            .repo
592            .canonicalize()
593            .ok()
594            .zip(task.repo.canonicalize().ok())
595            .is_some_and(|(run, task)| run == task);
596    let implicit_repo = task.repo.as_os_str().is_empty() || task.repo == Path::new(".");
597    anyhow::ensure!(
598        run.id == id
599            && run.task_assignment == task.reassignments.len()
600            && owner.is_none_or(|owner| owner == task.id)
601            && (same_repo || (implicit_repo && owner == Some(task.id.as_str())))
602            && task.assignment_accepts(&run),
603        "the run does not belong to the task's current repository assignment"
604    );
605    anyhow::ensure!(
606        crate::daemon::compatible_run_instruction(&run, task),
607        "the run does not match the current task instruction"
608    );
609    Ok(run)
610}
611
612/// The cached verdict, if it still describes the task's current audited run.
613pub fn current_note(task: &Task) -> Option<&LandingNote> {
614    let run = audited_run(task)?;
615    task.landing.as_ref().filter(|n| n.run == run)
616}
617
618fn current_target_note(task: &Task) -> Option<&LandingNote> {
619    let run = target_run(task)?;
620    task.landing.as_ref().filter(|n| n.run == run)
621}
622
623/// One-line annotation for CLI/web listings; `None` when landing was confirmed
624/// or the task is exempt.
625pub fn annotation(task: &Task) -> Option<String> {
626    let note = current_note(task)?;
627    match note.state {
628        State::Landed => None,
629        State::NotLanded => Some(format!("NOT LANDED: {}", note.reason)),
630        State::Unknown => Some(format!("landing unconfirmed: {}", note.reason)),
631    }
632}
633
634fn due(task: &Task, now: Timestamp) -> bool {
635    target_run(task).is_some()
636        && current_target_note(task).is_none_or(|note| {
637            let confirmed_done = task.status == TaskStatus::Done && note.state == State::Landed;
638            !confirmed_done && now.as_second() - note.checked_at.as_second() >= RECHECK_SECS
639        })
640}
641
642fn try_promote_awaiting_landing(
643    home: &Path,
644    queue: &Queue,
645    observed: &Task,
646    run_id: &str,
647    run_state: &RunState,
648    reason: &str,
649) -> bool {
650    let Ok(_claim) = queue.claim(&observed.id) else {
651        return false;
652    };
653    let Ok(mut current) = queue.get(&observed.id) else {
654        return false;
655    };
656    if current.status != TaskStatus::Held
657        || current.investigation
658        || current.updated_at != observed.updated_at
659        || current.machine_hold_cause != observed.machine_hold_cause
660        || current.instruction != observed.instruction
661        || current.instruction_rev != observed.instruction_rev
662        || current.repo != observed.repo
663        || current.reassignments != observed.reassignments
664        || awaiting_landing_run(&current) != Some(run_id)
665    {
666        return false;
667    }
668    let Ok(_fix) = crate::graph::FixClaim::acquire(&home.join("runs").join(run_id)) else {
669        return false;
670    };
671    let Ok(_owner) = crate::pr_head::owner_lock(home, run_id) else {
672        return false;
673    };
674    let Ok(reloaded) = load_run(home, &current, run_id) else {
675        return false;
676    };
677    let claims = crate::daemon::is_working_on(home, run_id, Timestamp::now());
678    if reloaded.liveness_under(home, claims) != Liveness::Dead || !reloaded.active.is_empty() {
679        return false;
680    }
681    let Ok(_lease) = crate::driver::maintenance(home, run_id) else {
682        return false;
683    };
684    // The asynchronous observation predates these locks. Refuse any changed
685    // run snapshot, including head, base, pass and merge evidence.
686    match (
687        serde_json::to_value(run_state),
688        serde_json::to_value(&reloaded),
689    ) {
690        (Ok(observed), Ok(current)) if observed == current => {}
691        _ => return false,
692    }
693    let expected = current.clone();
694    current.succeed(CompletionContext::from_run(
695        CompletionActor::DaemonSettle,
696        Some(format!("Landing confirmed: {reason}")),
697        &current,
698        &reloaded,
699    ));
700    if let Err(e) = queue.commit_completion(&mut current, &expected) {
701        tracing::warn!("landing audit: promote {}: {e:#}", observed.id);
702        return false;
703    }
704    crate::daemon::supersede_prior_runs(&current, home);
705    true
706}
707
708/// Bounded housekeeping pass: audits at most `max` overdue tasks, saves each
709/// verdict without bumping `updated_at` (including timeouts as `Unknown` so no
710/// slow item starves later tasks), promotes awaiting-landing tasks once
711/// confirmed landed, and reconciles per-repository notices for confirmed
712/// non-landings on `done` tasks.
713pub async fn audit_pass(home: &Path, limits: Limits, max: usize) -> Summary {
714    let queue = Queue::at(home.join("queue"));
715    let now = Timestamp::now();
716    let mut todo: Vec<_> = queue.list().into_iter().filter(|t| due(t, now)).collect();
717    todo.sort_by(|a, b| {
718        current_target_note(a)
719            .map(|n| n.checked_at)
720            .cmp(&current_target_note(b).map(|n| n.checked_at))
721            .then_with(|| a.id.cmp(&b.id))
722    });
723    let mut summary = Summary::default();
724    for task in todo.into_iter().take(max) {
725        let Some(run) = target_run(&task) else {
726            continue;
727        };
728        let loaded = if run.is_empty() {
729            Err(anyhow::anyhow!(
730                "the task completed without an execution run, so no landing evidence exists"
731            ))
732        } else {
733            load_run(home, &task, run)
734        };
735        let (state, reason) = match &loaded {
736            Ok(run_state) => {
737                match tokio::time::timeout(limits.per_item, verdict(run_state, limits)).await {
738                    Ok(result) => result,
739                    Err(_) => (
740                        State::Unknown,
741                        format!(
742                            "landing audit timed out after {}s",
743                            limits.per_item.as_secs()
744                        ),
745                    ),
746                }
747            }
748            Err(e) => (State::Unknown, format!("run record unavailable: {e}")),
749        };
750        summary.audited += 1;
751        if state == State::NotLanded && task.status == TaskStatus::Done {
752            summary.not_landed += 1;
753        }
754        if task.status == TaskStatus::Held
755            && state == State::Landed
756            && let Ok(run_state) = &loaded
757            && try_promote_awaiting_landing(home, &queue, &task, run, run_state, &reason)
758        {
759            summary.promoted += 1;
760            continue;
761        }
762        let note = LandingNote {
763            state,
764            reason,
765            run: run.to_owned(),
766            checked_at: Timestamp::now(),
767        };
768        if let Err(e) = queue.cache_landing(&task, note) {
769            tracing::warn!("landing audit: save note for {}: {e:#}", task.id);
770        }
771    }
772    reconcile_notices(home, &queue.list());
773    summary
774}
775
776fn reconcile_notices(home: &Path, tasks: &[Task]) {
777    use std::collections::{BTreeMap, BTreeSet};
778    let mut by_repo = BTreeMap::<_, Vec<_>>::new();
779    for task in tasks {
780        if current_note(task).is_some_and(|n| n.state == State::NotLanded) {
781            by_repo
782                .entry(task.repo.to_string_lossy().replace('\\', "/"))
783                .or_default()
784                .push(task.id.as_str());
785        }
786    }
787    let store = Notices::at(home.join("notifications"));
788    let mut live = BTreeSet::new();
789    for (repo, mut ids) in by_repo {
790        ids.sort_unstable();
791        let key = format!("{NOTICE_PREFIX}{repo}");
792        let shown = &ids[..ids.len().min(5)];
793        let name = Path::new(&repo)
794            .file_name()
795            .and_then(|name| name.to_str())
796            .unwrap_or(&repo);
797        let mut message = format!(
798            "{} done task(s) in {name} have not landed on their base branch: {}",
799            ids.len(),
800            shown.join(", ")
801        );
802        if ids.len() > shown.len() {
803            message.push_str(&format!(" and {} more", ids.len() - shown.len()));
804        }
805        live.insert(crate::notices::id_of(&key));
806        crate::notices::raise_in(
807            home,
808            Notice::warn(&key, message)
809                .link(Link::Task {
810                    id: ids[0].to_owned(),
811                })
812                .about(ids.iter().map(|id| (*id).to_owned()))
813                .cause(crate::notices::id_of(&ids.join(","))),
814        );
815    }
816    for notice in store.list() {
817        if notice.key.starts_with(NOTICE_PREFIX)
818            && !live.contains(&notice.id)
819            && let Err(e) = store.dismiss(&notice.id)
820        {
821            tracing::warn!("landing audit: dismiss {}: {e:#}", notice.id);
822        }
823    }
824}
825
826#[cfg(test)]
827mod tests {
828    use super::*;
829    use crate::config::Config;
830    use crate::queue::{InvestigationResult, Source};
831    use crate::run::Origin;
832    use serde_json::{Value, json};
833    use std::path::PathBuf;
834    use std::process::Command;
835
836    const HEAD: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
837    const OTHER_HEAD: &str = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
838    const BRANCH: &str = "magi/test/A";
839    const REPOSITORY: &str = "github.com/owner/repo";
840
841    fn pr() -> Value {
842        json!({
843            "url": "https://github.com/Owner/Repo/pull/9", "number": 9,
844            "state": "MERGED", "mergedAt": "2026-09-20T10:00:00Z",
845            "baseRefName": "main", "headRefName": BRANCH,
846            "headRefOid": HEAD, "isCrossRepository": false,
847        })
848    }
849
850    fn parse_prs(prs: Value) -> Result<Option<ExternalMerge>, String> {
851        merged_pr(
852            &prs.to_string(),
853            REPOSITORY,
854            "main",
855            "2026-09-19T00:00:00Z".parse().unwrap(),
856            Head {
857                branch: BRANCH,
858                sha: HEAD,
859            },
860        )
861    }
862
863    #[test]
864    fn judge_lands_on_exact_forge_proof_even_when_git_is_unavailable() {
865        let found = parse_prs(json!([pr()])).unwrap().unwrap();
866        let facts = Facts::Compared {
867            git_error: Some("tracking base is missing".into()),
868            forge: Ok(Some(found)),
869        };
870        let (state, reason) = judge("main", true, facts);
871        assert_eq!(state, State::Landed);
872        assert!(reason.contains("/pull/9"));
873    }
874
875    #[test]
876    fn judge_requires_both_negative_probes_to_rule_out_landing() {
877        let neither = Facts::Compared {
878            git_error: None,
879            forge: Ok(None),
880        };
881        assert_eq!(judge("main", false, neither).0, State::NotLanded);
882        let manual_squash = Facts::Compared {
883            git_error: None,
884            forge: Ok(None),
885        };
886        assert_eq!(judge("main", true, manual_squash).0, State::Unknown);
887
888        let forge_only = Facts::Compared {
889            git_error: Some("tracking base is missing".into()),
890            forge: Ok(None),
891        };
892        assert_eq!(judge("main", false, forge_only).0, State::Unknown);
893
894        let git_only = Facts::Compared {
895            git_error: None,
896            forge: Err("forge timed out".into()),
897        };
898        assert_eq!(judge("main", false, git_only).0, State::Unknown);
899    }
900
901    #[test]
902    fn forge_requires_a_same_repository_merge_of_the_exact_head_into_the_original_base() {
903        assert_eq!(parse_prs(json!([pr()])).unwrap().unwrap().number, 9);
904        assert_eq!(parse_prs(json!([])).unwrap(), None);
905        for (field, value) in [
906            ("baseRefName", json!("release")),
907            ("headRefOid", json!(OTHER_HEAD)),
908            ("isCrossRepository", json!(true)),
909            ("mergedAt", json!("2026-09-18T10:00:00Z")),
910        ] {
911            let mut unrelated = pr();
912            unrelated[field] = value;
913            assert_eq!(parse_prs(json!([unrelated])).unwrap(), None, "{field}");
914        }
915        assert_eq!(
916            remote_repository("git@github.com:Owner/Repo.git").as_deref(),
917            Some("github.com/Owner/Repo")
918        );
919    }
920
921    #[test]
922    fn bad_or_bounded_forge_results_do_not_count_even_with_an_exact_match() {
923        for (field, value) in [
924            ("url", json!("https://github.com/Other/Repo/pull/9")),
925            (
926                "url",
927                json!("https://github.com/Owner/Repo/pull/not-a-number"),
928            ),
929            ("headRefName", json!("different-branch")),
930            ("headRefOid", json!("cafebabe")),
931            ("mergedAt", json!("no timestamp")),
932            ("isCrossRepository", Value::Null),
933            ("state", json!("OPEN")),
934            ("baseRefName", json!("")),
935        ] {
936            let mut invalid = pr();
937            invalid[field] = value;
938            assert!(parse_prs(json!([pr(), invalid])).is_err(), "{field}");
939        }
940        let mut incomplete = pr();
941        incomplete.as_object_mut().unwrap().remove("mergedAt");
942        assert!(parse_prs(json!([incomplete])).is_err());
943        assert!(parse_prs(Value::Array(vec![pr(); PR_LIMIT])).is_err());
944        assert!(parse_prs(json!([pr(), pr()])).is_err());
945    }
946
947    fn git(dir: &Path, args: &[&str]) -> String {
948        let out = Command::new("git")
949            .args([
950                "-c",
951                "user.name=Landing Test",
952                "-c",
953                "user.email=landing@example.invalid",
954            ])
955            .args(args)
956            .current_dir(dir)
957            .output()
958            .unwrap();
959        assert!(
960            out.status.success(),
961            "git {args:?}: {}",
962            String::from_utf8_lossy(&out.stderr)
963        );
964        stdout(&out).unwrap().to_owned()
965    }
966
967    struct Fixture {
968        _temp: tempfile::TempDir,
969        home: PathBuf,
970        repo: PathBuf,
971        base: String,
972    }
973
974    impl Fixture {
975        fn new() -> Self {
976            let temp = tempfile::tempdir().unwrap();
977            let repo = temp.path().join("repo");
978            let home = temp.path().join("home");
979            std::fs::create_dir(&repo).unwrap();
980            git(&repo, &["init", "-b", "main"]);
981            git(&repo, &["commit", "--allow-empty", "-m", "base"]);
982            let base = git(&repo, &["rev-parse", "HEAD"]);
983            git(&repo, &["update-ref", "refs/remotes/origin/main", &base]);
984            Self {
985                _temp: temp,
986                home,
987                repo,
988                base,
989            }
990        }
991
992        fn head(&self, empty: bool) -> String {
993            git(&self.repo, &["switch", "-c", BRANCH]);
994            if !empty {
995                std::fs::write(self.repo.join("work.txt"), "candidate work").unwrap();
996                git(&self.repo, &["add", "work.txt"]);
997            }
998            git(&self.repo, &["commit", "--allow-empty", "-m", "candidate"]);
999            let sha = git(&self.repo, &["rev-parse", "HEAD"]);
1000            git(&self.repo, &["switch", "main"]);
1001            sha
1002        }
1003
1004        fn publish_base(&self, sha: &str) {
1005            let remote = self._temp.path().join("origin.git");
1006            if !remote.exists() {
1007                git(
1008                    self._temp.path(),
1009                    &["init", "--bare", "-b", "main", "origin.git"],
1010                );
1011                git(
1012                    &self.repo,
1013                    &["remote", "add", "origin", remote.to_str().unwrap()],
1014                );
1015            }
1016            git(
1017                &self.repo,
1018                &["push", "origin", &format!("+{sha}:refs/heads/main")],
1019            );
1020        }
1021
1022        fn run(&self, head: &str) -> RunState {
1023            let mut run = RunState::new(
1024                self.repo.clone(),
1025                "main".into(),
1026                self.base.clone(),
1027                "work".into(),
1028                Config::default(),
1029            );
1030            run.status = RunStatus::Ready;
1031            run.pr_head = Some(BRANCH.into());
1032            run.pr_pushed_head = Some(head.into());
1033            run
1034        }
1035
1036        fn done_task(&self, queue: &Queue, mut run: RunState, investigation: bool) -> Task {
1037            let mut task = Task::new(
1038                "task".into(),
1039                "work".into(),
1040                self.repo.clone(),
1041                Source::Human,
1042            );
1043            task.investigation = investigation;
1044            if investigation {
1045                task.completion_result = Some(InvestigationResult {
1046                    text: "Finding recorded".into(),
1047                    instruction_rev: task.instruction_rev,
1048                    recorded_at: Timestamp::now(),
1049                });
1050            }
1051            task.link_run(&run.id);
1052            run.task_instruction = Some(task.instruction.clone());
1053            run.task_instruction_rev = Some(task.instruction_rev);
1054            if run.origin.is_none() {
1055                run.origin = Some(Origin::queue(&task.id));
1056            }
1057            run.save_under(&self.home).unwrap();
1058            task.succeed(CompletionContext::from_run(
1059                CompletionActor::DaemonSettle,
1060                None,
1061                &task,
1062                &run,
1063            ));
1064            queue.put(&mut task).unwrap();
1065            task
1066        }
1067    }
1068
1069    #[tokio::test]
1070    async fn ancestry_checks_the_pinned_head_instead_of_the_branch_name() {
1071        let f = Fixture::new();
1072        let sha = f.head(false);
1073        let mut run = f.run(&sha);
1074        f.publish_base(&sha);
1075        git(&f.repo, &["branch", "-f", BRANCH, &f.base]);
1076        assert_eq!(verdict(&run, Limits::default()).await.0, State::Landed);
1077
1078        // A remote rewrite can invalidate positive ancestry while the tracking
1079        // ref still contains the candidate.
1080        let remote = f._temp.path().join("origin.git");
1081        git(&remote, &["update-ref", "refs/heads/main", &f.base]);
1082        let (state, why) = verdict(&run, Limits::default()).await;
1083        assert_eq!(state, State::Unknown);
1084        assert!(why.contains("stale"), "{why}");
1085        f.publish_base(&sha);
1086
1087        git(&f.repo, &["branch", "-f", BRANCH, &sha]);
1088        run.pr_pushed_head = None;
1089        assert_eq!(verdict(&run, Limits::default()).await.0, State::Unknown);
1090
1091        run.pr_pushed_head = Some(OTHER_HEAD.into());
1092        let (state, why) = verdict(&run, Limits::default()).await;
1093        assert_eq!(state, State::Unknown);
1094        assert!(why.contains("git merge-base failed"), "{why}");
1095    }
1096
1097    #[tokio::test]
1098    async fn deleted_branch_with_retained_commit_is_unknown() {
1099        for empty in [true, false] {
1100            let f = Fixture::new();
1101            let sha = f.head(empty);
1102            f.publish_base(&f.base);
1103            let run = f.run(&sha);
1104            git(&f.repo, &["branch", "-D", BRANCH]);
1105            assert_eq!(git(&f.repo, &["rev-parse", &sha]), sha);
1106            let (state, why) = verdict(&run, Limits::default()).await;
1107            assert_eq!(state, State::Unknown, "{why}");
1108            assert!(why.contains("retained branch"), "{why}");
1109        }
1110    }
1111
1112    #[tokio::test]
1113    async fn local_merge_does_not_count_as_remote_landing_without_push() {
1114        let f = Fixture::new();
1115        let sha = f.head(false);
1116        let remote = f._temp.path().join("origin.git");
1117        git(
1118            f._temp.path(),
1119            &["init", "--bare", "-b", "main", "origin.git"],
1120        );
1121        git(
1122            &f.repo,
1123            &["remote", "add", "origin", remote.to_str().unwrap()],
1124        );
1125        git(
1126            &f.repo,
1127            &["push", "origin", &format!("{}:refs/heads/main", f.base)],
1128        );
1129        // Merge into local main without pushing to origin.
1130        git(&f.repo, &["merge", "--no-ff", BRANCH, "-m", "local merge"]);
1131        let mut run = f.run(&sha);
1132        run.status = RunStatus::Merged;
1133        run.config.merge.mode = MergeMode::Local;
1134        run.merge = Some(crate::run::MergeOutcome {
1135            mode: MergeMode::Local,
1136            ok: true,
1137            detail: "merged locally".into(),
1138            empty: false,
1139        });
1140        assert!(!recorded_landing(&run));
1141        // Remote tracking ref still points at base, not the local merge.
1142        assert_ne!(verdict(&run, Limits::default()).await.0, State::Landed);
1143        // Once pushed to origin/main, exact ancestry confirms Landed.
1144        let pushed = git(&f.repo, &["rev-parse", "HEAD"]);
1145        git(&f.repo, &["push", "origin", "main"]);
1146        git(
1147            &f.repo,
1148            &["update-ref", "refs/remotes/origin/main", &pushed],
1149        );
1150        assert_eq!(verdict(&run, Limits::default()).await.0, State::Landed);
1151    }
1152
1153    #[tokio::test]
1154    async fn a_squash_without_forge_evidence_is_unknown_and_does_not_write_git_objects() {
1155        let f = Fixture::new();
1156        let sha = f.head(false);
1157        git(&f.repo, &["merge", "--squash", BRANCH]);
1158        git(&f.repo, &["commit", "-m", "squashed"]);
1159        git(&f.repo, &["update-ref", "refs/remotes/origin/main", "HEAD"]);
1160        let objects = git(&f.repo, &["count-objects", "-v"]);
1161        assert_eq!(
1162            verdict(&f.run(&sha), Limits::default()).await.0,
1163            State::Unknown
1164        );
1165        assert_eq!(git(&f.repo, &["count-objects", "-v"]), objects);
1166    }
1167
1168    #[tokio::test]
1169    async fn a_rebased_head_equal_to_its_recorded_base_does_not_count_upstream_work() {
1170        let f = Fixture::new();
1171        let upstream = f.head(false);
1172        git(
1173            &f.repo,
1174            &["update-ref", "refs/remotes/origin/main", &upstream],
1175        );
1176        let remote = f._temp.path().join("origin.git");
1177        git(
1178            f._temp.path(),
1179            &["init", "--bare", "-b", "main", "origin.git"],
1180        );
1181        git(
1182            &f.repo,
1183            &["remote", "add", "origin", remote.to_str().unwrap()],
1184        );
1185        git(
1186            &f.repo,
1187            &["push", "origin", &format!("{upstream}:refs/heads/main")],
1188        );
1189        let mut run = f.run(&upstream);
1190        run.base_sync = Some(crate::run::BaseSync {
1191            tip: upstream,
1192            behind: 0,
1193            attempts: 1,
1194            conflict: None,
1195            already_in: None,
1196        });
1197        assert_eq!(verdict(&run, Limits::default()).await.0, State::NotLanded);
1198    }
1199
1200    #[tokio::test]
1201    async fn an_unreadable_or_stale_remote_base_is_unknown_not_a_non_landing() {
1202        let f = Fixture::new();
1203        let upstream = f.head(false);
1204        let remote = f._temp.path().join("origin.git");
1205        git(
1206            f._temp.path(),
1207            &["init", "--bare", "-b", "main", "origin.git"],
1208        );
1209        git(
1210            &f.repo,
1211            &["remote", "add", "origin", remote.to_str().unwrap()],
1212        );
1213        git(
1214            &f.repo,
1215            &["push", "origin", &format!("{upstream}:refs/heads/main")],
1216        );
1217        git(
1218            &f.repo,
1219            &["update-ref", "refs/remotes/origin/main", &f.base],
1220        );
1221        let run = f.run(&upstream);
1222        let (state, why) = verdict(&run, Limits::default()).await;
1223        assert_eq!(state, State::Unknown, "{why}");
1224        assert!(why.contains("stale"), "{why}");
1225    }
1226
1227    #[tokio::test]
1228    async fn concurrent_fetch_updating_tracking_ref_still_compares_against_the_tested_base() {
1229        let f = Fixture::new();
1230        let upstream = f.head(false);
1231        let remote = f._temp.path().join("origin.git");
1232        git(
1233            f._temp.path(),
1234            &["init", "--bare", "-b", "main", "origin.git"],
1235        );
1236        git(
1237            &f.repo,
1238            &["remote", "add", "origin", remote.to_str().unwrap()],
1239        );
1240        git(
1241            &f.repo,
1242            &["push", "origin", &format!("{upstream}:refs/heads/main")],
1243        );
1244        // Simulate local_branch having tested the old tracking ref (`f.base`),
1245        // then a concurrent fetch advancing `refs/remotes/origin/main` to `upstream`.
1246        git(
1247            &f.repo,
1248            &["update-ref", "refs/remotes/origin/main", &upstream],
1249        );
1250        let run = f.run(&upstream);
1251        let stale = base_is_stale(&run, &f.base, Limits::default()).await;
1252        assert!(
1253            stale.as_deref().is_some_and(|why| why.contains("stale")),
1254            "expected stale error comparing tested base against live remote, got {stale:?}"
1255        );
1256    }
1257
1258    #[tokio::test]
1259    async fn terminal_labels_without_recorded_evidence_are_not_landed() {
1260        let f = Fixture::new();
1261        let mut run = f.run(OTHER_HEAD);
1262        run.pr_pushed_head = None;
1263        run.status = RunStatus::AlreadyInBase;
1264        assert_eq!(verdict(&run, Limits::default()).await.0, State::Unknown);
1265        run.status = RunStatus::Merged;
1266        run.merge = Some(crate::run::MergeOutcome {
1267            mode: MergeMode::None,
1268            ok: true,
1269            detail: String::new(),
1270            empty: false,
1271        });
1272        assert_eq!(verdict(&run, Limits::default()).await.0, State::Unknown);
1273        run.merge.as_mut().unwrap().mode = MergeMode::Local;
1274        assert_eq!(verdict(&run, Limits::default()).await.0, State::Unknown);
1275        run.merge.as_mut().unwrap().mode = MergeMode::Pr;
1276        assert_eq!(verdict(&run, Limits::default()).await.0, State::Landed);
1277    }
1278
1279    #[test]
1280    fn an_audit_snapshot_cannot_change_a_reopened_task() {
1281        let f = Fixture::new();
1282        let queue = Queue::at(f.home.join("queue"));
1283        let snapshot = f.done_task(&queue, f.run(&f.base), false);
1284        let note = LandingNote {
1285            state: State::NotLanded,
1286            reason: "the test head had no change".into(),
1287            run: audited_run(&snapshot).unwrap().to_owned(),
1288            checked_at: Timestamp::now(),
1289        };
1290        queue
1291            .modify(&snapshot.id, |task| {
1292                task.release();
1293                true
1294            })
1295            .unwrap();
1296        queue.cache_landing(&snapshot, note).unwrap();
1297        let current = queue.get(&snapshot.id).unwrap();
1298        assert_eq!(current.status, TaskStatus::Queued);
1299        assert!(current.landing.is_none());
1300    }
1301
1302    #[tokio::test]
1303    async fn finite_passes_record_notices_only_for_confirmed_non_landings() {
1304        let f = Fixture::new();
1305        let sha = f.head(true);
1306        let queue = Queue::at(f.home.join("queue"));
1307        let empty = f.done_task(&queue, f.run(&sha), false);
1308        let investigation = f.done_task(&queue, f.run(&sha), true);
1309        let mut foreign = f.run(&sha);
1310        foreign.status = RunStatus::Merged;
1311        foreign.merge = Some(crate::run::MergeOutcome {
1312            mode: MergeMode::Pr,
1313            ok: true,
1314            detail: String::new(),
1315            empty: false,
1316        });
1317        foreign.origin = Some(Origin::queue("another-task"));
1318        let unrelated = f.done_task(&queue, foreign, false);
1319        let notices = Notices::at(f.home.join("notifications"));
1320
1321        audit_pass(&f.home, Limits::default(), 1).await;
1322        assert_eq!(
1323            queue
1324                .list()
1325                .iter()
1326                .filter(|task| current_note(task).is_some())
1327                .count(),
1328            1
1329        );
1330        audit_pass(&f.home, Limits::default(), 1).await;
1331        let read_empty = queue.get(&empty.id).unwrap();
1332        assert_eq!(
1333            read_empty.status,
1334            TaskStatus::Done,
1335            "audit never transitions a done task"
1336        );
1337        assert_eq!(read_empty.updated_at, empty.updated_at);
1338        assert!(annotation(&read_empty).unwrap().starts_with("NOT LANDED"));
1339        assert!(
1340            annotation(&queue.get(&unrelated.id).unwrap())
1341                .unwrap()
1342                .starts_with("landing unconfirmed")
1343        );
1344        assert!(current_note(&queue.get(&investigation.id).unwrap()).is_none());
1345
1346        let seen = notices.list();
1347        assert_eq!(seen.len(), 1);
1348        assert!(seen[0].message.contains(&empty.id));
1349        let generation = seen[0].generation;
1350        queue
1351            .modify(&empty.id, |task| {
1352                task.landing.as_mut().unwrap().checked_at = "2020-01-01T00:00:00Z".parse().unwrap();
1353                true
1354            })
1355            .unwrap();
1356        audit_pass(&f.home, Limits::default(), MAX_PER_PASS).await;
1357        assert_eq!(notices.list()[0].generation, generation);
1358
1359        queue
1360            .modify(&empty.id, |task| {
1361                task.investigation = true;
1362                true
1363            })
1364            .unwrap();
1365        audit_pass(&f.home, Limits::default(), MAX_PER_PASS).await;
1366        assert!(notices.list().is_empty());
1367    }
1368
1369    #[tokio::test]
1370    async fn repository_landing_notice_delivers_all_task_ids_to_one_chat() {
1371        let f = Fixture::new();
1372        let sha = f.head(true);
1373        let queue = Queue::at(f.home.join("queue"));
1374        let a = f.done_task(&queue, f.run(&sha), false);
1375        let b = f.done_task(&queue, f.run(&sha), false);
1376        audit_pass(&f.home, Limits::default(), MAX_PER_PASS).await;
1377        let notices = Notices::at(f.home.join("notifications"));
1378        let notice = notices.list().pop().unwrap();
1379        assert_eq!(notice.subjects.len(), 2);
1380        let talks = crate::talk::Talks::at(f.home.join("talks"));
1381        let id = format!("notice-{}", notice.id);
1382        let mut chat = crate::talk::seeded_for_test(&id, f.repo.clone());
1383        talks.put(&mut chat).unwrap();
1384
1385        crate::notice_delivery::sweep(&queue, &talks, &f.home, &f.repo);
1386        let saved = notices.get(&notice.id).unwrap();
1387        assert_eq!(saved.delivered, saved.generation);
1388        assert!(!saved.unread());
1389        let pending = talks.get(&id).unwrap().pending;
1390        assert!(pending.contains(&a.id));
1391        assert!(pending.contains(&b.id));
1392        assert!(queue.get(&a.id).unwrap().chat.is_none());
1393        assert!(queue.get(&b.id).unwrap().chat.is_none());
1394        crate::notice_delivery::sweep(&queue, &talks, &f.home, &f.repo);
1395        assert_eq!(talks.list().len(), 1);
1396        assert_eq!(talks.get(&id).unwrap().pending, pending);
1397    }
1398
1399    #[tokio::test]
1400    async fn audit_promotes_held_awaiting_landing_only_when_snapshot_is_unchanged() {
1401        let f = Fixture::new();
1402        let sha = f.head(false);
1403        let queue = Queue::at(f.home.join("queue"));
1404        let mut run = f.run(&sha);
1405        run.driver_exited = true;
1406        let mut task = Task::new(
1407            "awaiting".into(),
1408            "work".into(),
1409            f.repo.clone(),
1410            Source::Human,
1411        );
1412        task.link_run(&run.id);
1413        run.origin = Some(Origin::queue(&task.id));
1414        run.task_instruction = Some(task.instruction.clone());
1415        run.task_instruction_rev = Some(task.instruction_rev);
1416        run.save_under(&f.home).unwrap();
1417        task.hold_awaiting_landing(run.id.clone(), "Ready but not landed".into());
1418        queue.put(&mut task).unwrap();
1419
1420        // Landing on origin/main promotes the held awaiting-landing task to Done.
1421        f.publish_base(&sha);
1422        let mut changed = run.clone();
1423        changed.pr_pushed_head = Some(f.base.clone());
1424        changed.save_under(&f.home).unwrap();
1425        assert!(!try_promote_awaiting_landing(
1426            &f.home,
1427            &queue,
1428            &task,
1429            &run.id,
1430            &run,
1431            "old head landed",
1432        ));
1433        assert_eq!(queue.get(&task.id).unwrap().status, TaskStatus::Held);
1434        run.save_under(&f.home).unwrap();
1435        let summary = audit_pass(&f.home, Limits::default(), MAX_PER_PASS).await;
1436        assert_eq!(summary.promoted, 1);
1437        let promoted = queue.get(&task.id).unwrap();
1438        assert_eq!(promoted.status, TaskStatus::Done);
1439        assert!(promoted.machine_hold_cause.is_none());
1440
1441        // If the task instruction was edited after the run, landing does NOT promote it.
1442        let mut edited = Task::new(
1443            "edited".into(),
1444            "work".into(),
1445            f.repo.clone(),
1446            Source::Human,
1447        );
1448        let mut run2 = f.run(&sha);
1449        run2.driver_exited = true;
1450        edited.link_run(&run2.id);
1451        run2.origin = Some(Origin::queue(&edited.id));
1452        run2.task_instruction = Some(edited.instruction.clone());
1453        run2.task_instruction_rev = Some(edited.instruction_rev);
1454        run2.save_under(&f.home).unwrap();
1455        edited.hold_awaiting_landing(run2.id.clone(), "Ready but not landed".into());
1456        edited
1457            .edit("edited".into(), "different work".into())
1458            .unwrap();
1459        edited.edit("edited".into(), "work".into()).unwrap();
1460        assert!(load_run(&f.home, &edited, &run2.id).is_err());
1461        run2.task_instruction_rev = None;
1462        run2.save_under(&f.home).unwrap();
1463        assert!(load_run(&f.home, &edited, &run2.id).is_err());
1464        queue.put(&mut edited).unwrap();
1465
1466        let summary = audit_pass(&f.home, Limits::default(), MAX_PER_PASS).await;
1467        assert_eq!(summary.promoted, 0);
1468        assert_eq!(queue.get(&edited.id).unwrap().status, TaskStatus::Held);
1469    }
1470
1471    #[tokio::test]
1472    async fn timed_out_audit_item_records_unknown_and_does_not_starve_later_tasks() {
1473        let f = Fixture::new();
1474        let sha_empty = f.head(true);
1475        let queue = Queue::at(f.home.join("queue"));
1476        let mut a = f.done_task(&queue, f.run(&sha_empty), false);
1477        let mut b = f.done_task(&queue, f.run(&sha_empty), false);
1478        if a.id > b.id {
1479            std::mem::swap(&mut a, &mut b);
1480        }
1481
1482        let zero = Limits {
1483            git: Duration::from_secs(15),
1484            gh: Duration::from_secs(20),
1485            per_item: Duration::ZERO,
1486        };
1487        audit_pass(&f.home, zero, 1).await;
1488        let first_after = queue.get(&a.id).unwrap();
1489        let note = current_note(&first_after).expect("timeout still records a note");
1490        assert_eq!(note.state, State::Unknown);
1491        assert!(note.reason.contains("timed out"), "{}", note.reason);
1492
1493        // Next pass with limit 1 audits the second (never-audited) task instead of starving it.
1494        audit_pass(&f.home, Limits::default(), 1).await;
1495        let second_after = queue.get(&b.id).unwrap();
1496        assert_eq!(
1497            current_note(&second_after).map(|n| n.state),
1498            Some(State::NotLanded)
1499        );
1500    }
1501}