Skip to main content

magi/
land_sync_recovery.rs

1//! Explicit, bounded same-run recovery for exhausted landing base synchronization.
2//!
3//! Landing base synchronization (`land.rs::rebase_landing_worktree`) uses its own
4//! `land_sync_attempts` counter against `config.graph.land_rounds`, separate from
5//! pre-publication `base_sync_recovery`. Recovery grants at most one extra landing
6//! sync attempt per explicit owner approval, capped over the run's lifetime, without
7//! resetting `land_sync_attempts` or bypassing fresh head-bound verification or merge
8//! approval.
9use std::path::Path;
10
11use anyhow::Result;
12use jiff::Timestamp;
13use serde::{Deserialize, Serialize};
14
15use crate::{
16    git,
17    queue::{Queue, Task, TaskStatus},
18    run::{
19        CommandOutcome, GateRepairE2e, MergeRepairPhase, RunState, RunStatus, VerificationEvidence,
20    },
21};
22
23/// Single-attempt allowance granted per explicit owner recovery approval.
24pub const GRANT_ATTEMPTS: usize = 1;
25
26/// Maximum lifetime extra landing base-sync attempts granted to one run.
27pub const MAX_GRANTS: usize = 4;
28
29/// Canonical diagnostic written when landing base synchronization exhausts its budget.
30pub const EXHAUSTED_DETAIL: &str = "landing base synchronization budget exhausted";
31
32/// Immutable snapshot of a landing base-sync exhaustion stop.
33#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
34pub struct Stop {
35    /// Cumulative `land_sync_attempts` when stopped.
36    pub attempts: usize,
37    /// Effective landing base-sync limit (`land_rounds + extra_attempts`) when stopped.
38    pub limit: usize,
39    /// Retained winner worktree and branch HEAD at the stop.
40    pub head: String,
41    /// Published PR HEAD observed and recorded at the stop.
42    pub pr_head: String,
43    /// Existing pull request URL.
44    pub pr_url: String,
45    /// Existing pull request number.
46    pub pr_number: u64,
47    /// Fetched base tip observed at the stop (or verified at legacy admission).
48    pub tip: String,
49    /// Canonical diagnostic detail.
50    pub detail: String,
51    /// Stable timestamp of the stop.
52    pub at: Timestamp,
53}
54
55/// Admission bindings revalidated at dispatch and execution time.
56#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
57pub struct Scope {
58    /// Fetched base tip observed at owner authorization; ordinary fast-forward is allowed.
59    pub tip: String,
60    /// Owning task instruction at authorization time.
61    pub instruction: String,
62    /// Owning task assignment count (`reassignments.len()`) at authorization time.
63    pub assignment: usize,
64    /// Open PR HEAD observed at authorization time.
65    pub pr_head: String,
66    /// Pull request URL at authorization time.
67    pub pr_url: String,
68    /// Pull request number at authorization time.
69    pub pr_number: u64,
70    /// Monotonic count of prior consumed grants (`extra_attempts`) at admission.
71    pub grant_index: usize,
72}
73
74/// Prior verification evidence detached and preserved before running recovered landing sync.
75#[derive(Debug, Clone, Serialize, Deserialize)]
76pub struct ArchivedVerification {
77    /// When the prior verification evidence was archived.
78    pub archived_at: Timestamp,
79    /// Head that previously held the archived verification evidence.
80    pub head: String,
81    /// Previous `gate_head`.
82    pub gate_head: Option<String>,
83    /// Previous `gate_ran`.
84    pub gate_ran: bool,
85    /// Previous gate command outcomes.
86    pub gate: Vec<CommandOutcome>,
87    /// Previous pre-gate command outcomes.
88    #[serde(default)]
89    pub pre_gate: Vec<CommandOutcome>,
90    /// Previous commit made by a pre-gate pass.
91    #[serde(default)]
92    pub pre_gate_commit: Option<String>,
93    /// Previous current-head E2E record.
94    pub head_e2e: Option<GateRepairE2e>,
95    /// Previous post-repair E2E record.
96    pub gate_repair_e2e: Option<GateRepairE2e>,
97    /// Previous `(round, verified_head)` pairs detached from review rounds.
98    #[serde(default)]
99    pub review_verified_heads: Vec<(usize, Option<String>)>,
100}
101
102/// One explicit owner recovery authorization, consumed durably before any Git mutation.
103#[derive(Debug, Clone, Serialize, Deserialize)]
104pub struct Authorization {
105    /// Durable request key (`<actor>/<request>`).
106    pub request: String,
107    /// Owning task id.
108    pub task: String,
109    /// Exact saved run id authorized to recover.
110    pub run: String,
111    /// Immutable stop snapshot authorized by this request.
112    pub stop: Stop,
113    /// Verified admission scope rechecked on dispatch and execution.
114    pub scope: Scope,
115    /// Owner decision timestamp committed on the owning task.
116    #[serde(default)]
117    pub decision: Option<Timestamp>,
118    /// Queue resumption generation committed on the owning task, if any.
119    #[serde(default)]
120    pub generation: Option<u64>,
121    /// Extra landing sync attempts granted upon consumption (always `GRANT_ATTEMPTS`).
122    pub granted_attempts: usize,
123    /// When this authorization was recorded.
124    pub at: Timestamp,
125    /// Persisted `true` before any Git mutation or budget increment.
126    pub consumed: bool,
127    /// When consumed or refused.
128    #[serde(default)]
129    pub consumed_at: Option<Timestamp>,
130    /// Refusal reason when invalidated before execution; `consumed` is also set `true`.
131    #[serde(default)]
132    pub invalidated: Option<String>,
133    /// Prior verification evidence archived when this authorization was consumed.
134    #[serde(default)]
135    pub archived_verification: Option<ArchivedVerification>,
136}
137
138impl Authorization {
139    /// Consume a refused approval without granting recovery, retaining the reason.
140    pub(crate) fn refuse(&mut self, reason: impl Into<String>) {
141        self.invalidated = Some(reason.into());
142        self.consumed = true;
143        if self.consumed_at.is_none() {
144            self.consumed_at = Some(Timestamp::now());
145        }
146    }
147}
148
149/// Persistent landing base-sync exhaustion stop and authorization history.
150#[derive(Debug, Clone, Default, Serialize, Deserialize)]
151pub struct Recovery {
152    /// Total extra landing sync attempts granted by consumed authorizations.
153    #[serde(default)]
154    pub extra_attempts: usize,
155    /// Append-only history of landing sync exhaustion stops.
156    #[serde(default)]
157    pub stops: Vec<Stop>,
158    /// Active exhaustion stop awaiting explicit owner recovery, if any.
159    #[serde(default)]
160    pub stop: Option<Stop>,
161    /// Append-only history of explicit owner recovery authorizations.
162    #[serde(default)]
163    pub authorizations: Vec<Authorization>,
164}
165
166/// Minimal live pull request metadata verified at admission, dispatch, and execution.
167#[derive(Debug, Clone, PartialEq, Eq)]
168pub struct ObservedPr {
169    /// Pull request URL.
170    pub url: String,
171    /// Pull request number.
172    pub number: u64,
173    /// Whether the pull request is currently open.
174    pub open: bool,
175    /// Current pull request head SHA reported by the forge.
176    pub head: String,
177    /// Pull request base branch reported by the forge, when readable.
178    pub base_branch: Option<String>,
179}
180
181/// Injectable forge observer for pull request head and lifecycle verification.
182pub trait PrObserver {
183    /// Observe the current pull request state and head SHA.
184    fn observe_pr(
185        &self,
186        repo: &Path,
187        pr_url: &str,
188    ) -> impl std::future::Future<Output = Result<ObservedPr>> + Send;
189}
190
191/// Production forge observer backed by `gh pr view`.
192#[derive(Debug, Default, Clone, Copy)]
193pub struct GhPrObserver;
194
195impl PrObserver for GhPrObserver {
196    async fn observe_pr(&self, repo: &Path, pr_url: &str) -> Result<ObservedPr> {
197        crate::land::observe_pr_summary(repo, pr_url).await
198    }
199}
200
201fn matches_exhausted_detail(detail: &str) -> bool {
202    let trimmed = detail.trim();
203    trimmed == EXHAUSTED_DETAIL
204        || trimmed == format!("could not synchronize landing base: {EXHAUSTED_DETAIL}")
205}
206
207fn matches_exhausted_event(message: &str) -> bool {
208    let trimmed = message.trim();
209    trimmed == format!("stopped: could not synchronize landing base: {EXHAUSTED_DETAIL}")
210        || trimmed == format!("stopped: {EXHAUSTED_DETAIL}")
211        || trimmed == format!("gave up: {EXHAUSTED_DETAIL}")
212        || trimmed == format!("gave up: could not synchronize landing base: {EXHAUSTED_DETAIL}")
213}
214
215fn legacy_exhausted_diagnostic(state: &RunState) -> bool {
216    if let Some(last_land) = state.events.iter().rev().find(|e| e.node == "land") {
217        matches_exhausted_event(&last_land.message)
218    } else {
219        state
220            .merge
221            .as_ref()
222            .is_some_and(|m| !m.ok && matches_exhausted_detail(&m.detail))
223    }
224}
225
226fn exhausted_stop_timestamp(state: &RunState) -> Timestamp {
227    state
228        .events
229        .iter()
230        .rev()
231        .find(|e| e.node == "land" && matches_exhausted_event(&e.message))
232        .map_or(state.updated_at, |e| e.at)
233}
234
235impl RunState {
236    /// Effective landing base-sync attempt limit including consumed recovery grants.
237    pub fn land_sync_budget(&self) -> usize {
238        self.config
239            .graph
240            .land_rounds
241            .saturating_add(self.land_sync_recovery.extra_attempts)
242            .saturating_sub(
243                self.land_sync_recovery
244                    .authorizations
245                    .iter()
246                    .filter(|a| a.invalidated.is_some() && a.archived_verification.is_some())
247                    .count(),
248            )
249    }
250
251    /// Remaining lifetime recovery grants available for this run.
252    pub fn land_sync_grants_remaining(&self) -> usize {
253        MAX_GRANTS.saturating_sub(self.land_sync_recovery.extra_attempts)
254    }
255
256    /// Centralized predicate recognizing both structured and legacy landing
257    /// base-sync exhaustion stops.
258    pub fn land_sync_exhausted(&self) -> bool {
259        if self.status != RunStatus::Blocked {
260            return false;
261        }
262        if self.released_to.is_some()
263            || self.retired_to.is_some()
264            || self.pr_taken_over_by.is_some()
265        {
266            return false;
267        }
268        if !crate::handover::landing_checkpoint(self)
269            || self.base_sync_blocked()
270            || self.pr_publication_pending
271        {
272            return false;
273        }
274        if self.merge_decision.is_some()
275            || self.resource_block.is_some()
276            || self.sequencer_stop.is_some()
277            || self.land_rebase_from.is_some()
278            || self.land_sync_target.is_some()
279        {
280            return false;
281        }
282        if self.merge_repairs.last().is_some_and(|r| {
283            matches!(
284                r.phase,
285                MergeRepairPhase::Requested
286                    | MergeRepairPhase::Fixing
287                    | MergeRepairPhase::Reviewing
288            )
289        }) || self
290            .repair_grants
291            .last()
292            .is_some_and(|g| g.phase != crate::repair_budget::Phase::Complete)
293            || self
294                .rebase_fixes
295                .iter()
296                .any(|r| r.stop.is_none() && !r.finished)
297        {
298            return false;
299        }
300        if !self.land_sync_pending
301            || self.land_sync_attempts == 0
302            || self.land_sync_attempts < self.land_sync_budget()
303        {
304            return false;
305        }
306        if let Some(stop) = &self.land_sync_recovery.stop {
307            stop.detail == EXHAUSTED_DETAIL
308                && stop.attempts == self.land_sync_attempts
309                && stop.limit == self.land_sync_budget()
310                && self
311                    .pr
312                    .as_ref()
313                    .is_some_and(|pr| pr.url == stop.pr_url && pr.number == stop.pr_number)
314                && self.land_sync_recovery.stops.contains(stop)
315        } else {
316            self.land_sync_recovery
317                .authorizations
318                .last()
319                .is_some_and(|a| {
320                    a.invalidated.is_some()
321                        && a.archived_verification.is_some()
322                        && a.stop.attempts == self.land_sync_attempts
323                })
324                || (self.land_sync_recovery.stops.is_empty()
325                    && self.land_sync_recovery.authorizations.is_empty()
326                    && legacy_exhausted_diagnostic(self))
327        }
328    }
329
330    /// Whether any landing sync recovery authorization is still unconsumed.
331    pub fn has_unconsumed_land_sync_authorization(&self) -> bool {
332        self.land_sync_recovery
333            .authorizations
334            .iter()
335            .any(|a| !a.consumed && a.invalidated.is_none())
336    }
337
338    /// Whether the active landing exhaustion stop has a matching unconsumed authorization.
339    pub fn land_sync_recovery_pending(&self) -> bool {
340        self.land_sync_exhausted()
341            && self
342                .land_sync_recovery
343                .authorizations
344                .last()
345                .is_some_and(|a| {
346                    !a.consumed
347                        && a.invalidated.is_none()
348                        && a.run == self.id
349                        && a.granted_attempts == GRANT_ATTEMPTS
350                        && a.scope.grant_index == self.land_sync_recovery.extra_attempts
351                        && self.land_sync_recovery.stop.as_ref() == Some(&a.stop)
352                })
353    }
354
355    /// A grant was saved but its synchronization attempt has not been charged.
356    /// A refused grant no longer contributes to the effective attempt budget.
357    pub(crate) fn land_sync_unstarted_grant(&self) -> bool {
358        self.status.resumable()
359            && self
360                .land_sync_recovery
361                .authorizations
362                .last()
363                .is_some_and(|a| {
364                    a.consumed
365                        && a.invalidated.is_none()
366                        && a.archived_verification.is_some()
367                        && self.land_sync_attempts == a.stop.attempts
368                        && self.land_sync_recovery.extra_attempts
369                            == a.scope.grant_index.saturating_add(GRANT_ATTEMPTS)
370                })
371    }
372
373    /// Single-line actionable guidance for CLI, notices, and reports.
374    pub fn land_sync_next_action(&self) -> String {
375        let attempts = self.land_sync_attempts;
376        let limit = self.land_sync_budget();
377        let grants = self.land_sync_recovery.extra_attempts;
378        let head = self
379            .land_sync_recovery
380            .stop
381            .as_ref()
382            .map(|s| s.head.as_str())
383            .or(self.pr_pushed_head.as_deref())
384            .unwrap_or("<full-head-sha>");
385        if let Some(reason) = self
386            .land_sync_recovery
387            .authorizations
388            .last()
389            .and_then(|a| a.invalidated.as_ref())
390            && !self.land_sync_recovery_pending()
391        {
392            if self.land_sync_grants_remaining() == 0 {
393                return format!(
394                    "Landing base-sync recovery approval invalidated: {reason}; lifetime grant limit reached ({grants}/{MAX_GRANTS})"
395                );
396            }
397            return format!(
398                "Landing base-sync recovery approval invalidated: {reason}. Authorize a new bounded attempt with `magi task control recover-land-sync {} --request <unique-id> --head {head}` ({attempts}/{limit} attempts, {grants}/{MAX_GRANTS} grants used)",
399                self.id
400            );
401        }
402        if self.land_sync_recovery_pending() || self.land_sync_unstarted_grant() {
403            return format!(
404                "Landing base-sync recovery approval recorded; resume the retained run to spend {GRANT_ATTEMPTS} approved synchronization attempt ({attempts}/{limit} attempts, {grants}/{MAX_GRANTS} recovery grants used)"
405            );
406        }
407        if self.land_sync_grants_remaining() == 0 {
408            return format!(
409                "Lifetime landing base-sync recovery limit reached ({grants}/{MAX_GRANTS} grants used, {attempts}/{limit} attempts); inspect the retained branch and PR before manual intervention"
410            );
411        }
412        format!(
413            "Authorize {GRANT_ATTEMPTS} bounded landing base-sync attempt with `magi task control recover-land-sync {} --request <unique-id> --head {head}` ({attempts}/{limit} attempts, {grants}/{MAX_GRANTS} recovery grants used)",
414            self.id
415        )
416    }
417
418    /// Persist a stable structured stop snapshot on landing sync exhaustion.
419    pub(crate) fn record_land_sync_exhausted_stop(&mut self, head: &str, pr_head: &str, tip: &str) {
420        let Some(pr) = self.pr.as_ref() else {
421            return;
422        };
423        let limit = self.land_sync_budget();
424        if self.land_sync_recovery.stop.as_ref().is_some_and(|s| {
425            s.attempts == self.land_sync_attempts
426                && s.limit == limit
427                && s.head.eq_ignore_ascii_case(head)
428                && s.pr_head.eq_ignore_ascii_case(pr_head)
429                && s.pr_url == pr.url
430                && s.pr_number == pr.number
431                && s.detail == EXHAUSTED_DETAIL
432        }) {
433            return;
434        }
435        let at = exhausted_stop_timestamp(self);
436        let stop = Stop {
437            attempts: self.land_sync_attempts,
438            limit,
439            head: head.to_ascii_lowercase(),
440            pr_head: pr_head.to_ascii_lowercase(),
441            pr_url: pr.url.clone(),
442            pr_number: pr.number,
443            tip: tip.to_ascii_lowercase(),
444            detail: EXHAUSTED_DETAIL.to_owned(),
445            at,
446        };
447        if !self.land_sync_recovery.stops.contains(&stop) {
448            self.land_sync_recovery.stops.push(stop.clone());
449        }
450        self.land_sync_recovery.stop = Some(stop);
451    }
452
453    /// Atomically consume a validated pending authorization, add its bounded
454    /// extra attempt, archive prior verification evidence, and require fresh
455    /// head-bound E2E and gate before publication.
456    ///
457    /// Callers MUST save `RunState` immediately before running any Git mutation.
458    pub(crate) fn consume_land_sync_recovery(
459        &mut self,
460        head: &str,
461        pr_head: &str,
462    ) -> std::result::Result<(), String> {
463        if !self.land_sync_recovery_pending() {
464            return Err("no matching pending landing base-sync recovery authorization".into());
465        }
466        let now = Timestamp::now();
467        let granted = self
468            .land_sync_recovery
469            .authorizations
470            .last()
471            .map(|a| a.granted_attempts)
472            .unwrap_or(0);
473        let Some(next_extra) = self.land_sync_recovery.extra_attempts.checked_add(granted) else {
474            return Err("landing base-sync grant counter overflow".into());
475        };
476        if granted != GRANT_ATTEMPTS || next_extra > MAX_GRANTS {
477            if let Some(auth) = self.land_sync_recovery.authorizations.last_mut() {
478                auth.refuse(format!(
479                    "lifetime landing base-sync recovery limit reached ({}/{MAX_GRANTS})",
480                    self.land_sync_recovery.extra_attempts
481                ));
482            }
483            return Err("lifetime landing base-sync recovery limit reached".into());
484        }
485        let head_mismatch = self
486            .land_sync_recovery
487            .authorizations
488            .last()
489            .is_some_and(|a| {
490                !a.stop.head.eq_ignore_ascii_case(head)
491                    || !a.stop.pr_head.eq_ignore_ascii_case(pr_head)
492            });
493        if head_mismatch {
494            if let Some(auth) = self.land_sync_recovery.authorizations.last_mut() {
495                auth.refuse(format!(
496                    "retained/published HEAD changed from {}/{} to {head}/{pr_head}",
497                    auth.stop.head, auth.stop.pr_head
498                ));
499            }
500            return Err("retained or published HEAD changed before consumption".into());
501        }
502
503        // Detach and preserve all prior verification evidence so fresh gate and
504        // current-head E2E MUST run even if HEAD stays unchanged.
505        let gate = std::mem::take(&mut self.gate);
506        let gate_head = self.gate_head.take();
507        let gate_ran = std::mem::replace(&mut self.gate_ran, false);
508        let head_e2e = self.head_e2e.take();
509        let gate_repair_e2e = self.gate_repair_e2e.take();
510        let pre_gate = std::mem::take(&mut self.pre_gate);
511        let pre_gate_commit = self.pre_gate_commit.take();
512
513        let mut review_verified_heads = Vec::with_capacity(self.reviews.len());
514        for review in &mut self.reviews {
515            review_verified_heads.push((review.round, review.verified_head.take()));
516        }
517
518        if gate_ran || !gate.is_empty() || head_e2e.is_some() {
519            self.verification_history.push(VerificationEvidence {
520                superseded_by: None,
521                archived_at: Some(now),
522                fixes_spent: Some(self.gate_fixes.len()),
523                gate_head: gate_head.clone(),
524                gate_ran,
525                gate: gate.clone(),
526                e2e: head_e2e.clone(),
527            });
528        }
529        if let Some(repair_e2e) = &gate_repair_e2e {
530            self.verification_history.push(VerificationEvidence {
531                superseded_by: None,
532                archived_at: Some(now),
533                fixes_spent: Some(self.gate_fixes.len()),
534                gate_head: None,
535                gate_ran: false,
536                gate: Vec::new(),
537                e2e: Some(repair_e2e.clone()),
538            });
539        }
540
541        let archived = ArchivedVerification {
542            archived_at: now,
543            head: head.to_ascii_lowercase(),
544            gate_head,
545            gate_ran,
546            gate,
547            pre_gate,
548            pre_gate_commit,
549            head_e2e,
550            gate_repair_e2e,
551            review_verified_heads,
552        };
553
554        let auth = self
555            .land_sync_recovery
556            .authorizations
557            .last_mut()
558            .expect("pending authorization exists");
559        auth.consumed = true;
560        auth.consumed_at = Some(now);
561        auth.archived_verification = Some(archived);
562
563        self.land_sync_recovery.extra_attempts = next_extra;
564        self.land_sync_recovery.stop = None;
565        Ok(())
566    }
567}
568
569/// Retry an observation failure without changing the accepted owner generation.
570pub(crate) fn queue_existing_authorization(queue: &Queue, task: &mut Task, run: &str) -> bool {
571    let Some(state) = latest_exhausted_run(queue, task) else {
572        return false;
573    };
574    if state.id != run || !(state.land_sync_recovery_pending() || state.land_sync_unstarted_grant())
575    {
576        return false;
577    }
578    let Some(auth) = state.land_sync_recovery.authorizations.last() else {
579        return false;
580    };
581    if task.id != auth.task
582        || !task.assignment_accepts(&state)
583        || task.instruction != auth.scope.instruction
584        || task.operator_decided_at != auth.decision
585        || auth
586            .generation
587            .is_some_and(|g| task.resumption.as_ref().map(|r| r.generation) != Some(g))
588        || !task.land_sync_recovery_requests.contains(&auth.request)
589        || task.fresh_start
590        || task.review_branch.is_some()
591        || task.pr_recovery.is_some()
592        || matches!(task.status, TaskStatus::Running | TaskStatus::Done)
593    {
594        return false;
595    }
596    task.status = TaskStatus::Queued;
597    task.hold_source = None;
598    task.hold_reason = None;
599    task.held_at = None;
600    true
601}
602
603/// Whether `task`'s latest run is held by landing base-sync exhaustion without
604/// an active pending recovery authorization.
605pub(crate) fn held_task(queue: &Queue, task: &Task) -> bool {
606    held_run(queue, task).is_some()
607}
608
609/// Load `task`'s latest run when it is blocked on landing base-sync exhaustion
610/// without an active pending recovery authorization.
611pub(crate) fn held_run(queue: &Queue, task: &Task) -> Option<RunState> {
612    latest_exhausted_run(queue, task).filter(|state| !state.land_sync_recovery_pending())
613}
614
615/// Load `task`'s latest run whenever it is currently in landing base-sync exhaustion
616/// (with or without a pending recovery authorization).
617pub(crate) fn latest_exhausted_run(queue: &Queue, task: &Task) -> Option<RunState> {
618    let home = queue.root().parent()?;
619    task.execution_runs()
620        .last()
621        .and_then(|id| RunState::load_under(id, home).ok())
622        .filter(|state| {
623            state.land_sync_exhausted()
624                || state.has_unconsumed_land_sync_authorization()
625                || state.land_sync_unstarted_grant()
626        })
627}
628
629/// Revalidate all ownership, task, HEAD, open-PR, and base-lineage invariants
630/// for a pending landing sync recovery authorization.
631///
632/// Used both at daemon dispatch time (`task_override = Some(task)`) and after
633/// acquiring the execution lease inside `land_with` (`task_override = None`,
634/// `observed_override = Some(&observed_pr)`).
635#[derive(Debug)]
636pub(crate) struct ValidationFailure {
637    pub reason: String,
638    pub observation_failed: bool,
639}
640
641impl ValidationFailure {
642    fn observation(reason: String) -> Self {
643        Self {
644            reason,
645            observation_failed: true,
646        }
647    }
648}
649
650impl From<String> for ValidationFailure {
651    fn from(reason: String) -> Self {
652        Self {
653            reason,
654            observation_failed: false,
655        }
656    }
657}
658
659impl From<&str> for ValidationFailure {
660    fn from(reason: &str) -> Self {
661        reason.to_owned().into()
662    }
663}
664
665pub(crate) async fn validate_pending_authorization<O: PrObserver>(
666    home: &Path,
667    state: &RunState,
668    task_override: Option<&Task>,
669    observed_override: Option<&ObservedPr>,
670    observer: &O,
671) -> std::result::Result<(String, String), ValidationFailure> {
672    let unstarted = state.land_sync_unstarted_grant();
673    if !state.land_sync_recovery_pending() && !unstarted {
674        return Err("landing base-sync stop or pending authorization state changed".into());
675    }
676    if let Err(error) = crate::pr_head::ensure_owner(state) {
677        return Err(format!("run ownership check failed: {error:#}").into());
678    }
679    let auth = state
680        .land_sync_recovery
681        .authorizations
682        .last()
683        .ok_or_else(|| "missing pending landing base-sync authorization".to_owned())?;
684    if auth.invalidated.is_some() {
685        return Err("landing base-sync recovery authorization was invalidated".into());
686    }
687    if auth.granted_attempts != GRANT_ATTEMPTS
688        || (!unstarted && state.land_sync_grants_remaining() < auth.granted_attempts)
689    {
690        return Err(format!(
691            "lifetime landing base-sync recovery limit reached ({}/{MAX_GRANTS})",
692            state.land_sync_recovery.extra_attempts
693        )
694        .into());
695    }
696
697    if !auth.task.is_empty() {
698        let loaded_task;
699        let task = match task_override {
700            Some(task) => task,
701            None => {
702                loaded_task = Queue::at(home.join("queue")).get(&auth.task).map_err(|e| {
703                    ValidationFailure::observation(format!(
704                        "owning task {} unreadable: {e:#}",
705                        auth.task
706                    ))
707                })?;
708                &loaded_task
709            }
710        };
711        if task.id != auth.task {
712            return Err("authorization targets a different task".into());
713        }
714        if state
715            .origin
716            .as_ref()
717            .and_then(|o| o.task.as_deref())
718            .is_some_and(|owner| owner != task.id)
719        {
720            return Err("run belongs to another task".into());
721        }
722        if task.execution_runs().last().map(String::as_str) != Some(state.id.as_str()) {
723            return Err("run is no longer the task's latest execution".into());
724        }
725        if !task.assignment_accepts(state) || task.reassignments.len() != auth.scope.assignment {
726            return Err("task repository assignment changed since authorization".into());
727        }
728        if task.status == TaskStatus::Done
729            || task.fresh_start
730            || task.review_branch.is_some()
731            || task.pr_recovery.is_some()
732        {
733            return Err("task queue state changed since authorization".into());
734        }
735        if task.instruction != auth.scope.instruction
736            || !crate::daemon::compatible_run_instruction(state, task)
737        {
738            return Err("task instruction changed since authorization".into());
739        }
740        if task.operator_decided_at != auth.decision {
741            return Err("a newer owner decision superseded this recovery authorization".into());
742        }
743        if let Some(generation) = auth.generation
744            && task.resumption.as_ref().map(|r| r.generation) != Some(generation)
745        {
746            return Err("task resumption generation changed since authorization".into());
747        }
748        if task_override.is_some()
749            && !task
750                .resume_override
751                .as_ref()
752                .is_some_and(|pin| pin.pinned_run.as_deref() == Some(state.id.as_str()))
753            && !(task.resume_override.is_none()
754                && task.land_sync_recovery_requests.contains(&auth.request))
755        {
756            return Err("task exact-run pin is missing or targets another run".into());
757        }
758    }
759
760    let winner = state
761        .winner()
762        .ok_or_else(|| "run has no retained winner".to_owned())?;
763    let clean = git::is_clean(&winner.worktree).await.map_err(|e| {
764        ValidationFailure::observation(format!(
765            "could not inspect retained worktree cleanliness: {e:#}"
766        ))
767    })?;
768    if !clean {
769        return Err("retained worktree has uncommitted changes".into());
770    }
771    let scratch = home.join("runs").join(&state.id).join("rebase");
772    let rebase_in_progress = git::checked_rebase_in_progress(&scratch)
773        .await
774        .map_err(|e| {
775            ValidationFailure::observation(format!("could not inspect scratch rebase state: {e:#}"))
776        })?;
777    if rebase_in_progress {
778        return Err("landing rebase is already in progress in scratch worktree".into());
779    }
780    let local_head = git::rev_parse(&winner.worktree, "HEAD")
781        .await
782        .map_err(|e| {
783            ValidationFailure::observation(format!("could not read retained worktree HEAD: {e:#}"))
784        })?;
785    let branch_head = git::rev_parse(&state.repo, &format!("refs/heads/{}", winner.branch))
786        .await
787        .map_err(|e| {
788            ValidationFailure::observation(format!("could not read winner branch ref: {e:#}"))
789        })?;
790    if local_head != branch_head {
791        return Err("retained worktree HEAD does not match the winner branch ref".into());
792    }
793    if !local_head.eq_ignore_ascii_case(&auth.stop.head) {
794        return Err(format!(
795            "retained HEAD changed from {} to {local_head}",
796            auth.stop.head
797        )
798        .into());
799    }
800    if !state
801        .pr_pushed_head
802        .as_deref()
803        .is_some_and(|h| h.eq_ignore_ascii_case(&local_head))
804    {
805        return Err("saved pr_pushed_head no longer matches the retained HEAD".into());
806    }
807    if !auth.stop.pr_head.eq_ignore_ascii_case(&local_head)
808        || !auth.scope.pr_head.eq_ignore_ascii_case(&local_head)
809    {
810        return Err("authorized PR head does not match the retained HEAD".into());
811    }
812    if !state.pr.as_ref().is_some_and(|pr| {
813        pr.state == "open" && pr.url == auth.scope.pr_url && pr.number == auth.scope.pr_number
814    }) {
815        return Err("recorded pull request metadata changed since authorization".into());
816    }
817
818    let fetched_pr;
819    let observed = match observed_override {
820        Some(observed) => observed,
821        None => {
822            fetched_pr = observer
823                .observe_pr(&state.repo, &auth.scope.pr_url)
824                .await
825                .map_err(|e| {
826                    ValidationFailure::observation(format!(
827                        "could not verify open pull request state: {e:#}"
828                    ))
829                })?;
830            &fetched_pr
831        }
832    };
833    if !observed.open {
834        return Err("pull request is no longer open".into());
835    }
836    if observed.url != auth.scope.pr_url || observed.number != auth.scope.pr_number {
837        return Err("observed pull request does not match authorized pull request".into());
838    }
839    if observed.head.len() != 40 || !observed.head.bytes().all(|b| b.is_ascii_hexdigit()) {
840        return Err(ValidationFailure::observation(
841            "observed pull request head is unreadable".into(),
842        ));
843    }
844    if !observed.head.eq_ignore_ascii_case(&local_head) {
845        return Err(format!(
846            "published PR head changed from {} to {}",
847            auth.scope.pr_head, observed.head
848        )
849        .into());
850    }
851    if observed
852        .base_branch
853        .as_deref()
854        .is_some_and(|b| !b.is_empty() && b != state.base_branch)
855    {
856        return Err("pull request base branch changed since authorization".into());
857    }
858
859    let fetched = git::fetch(&state.repo, &state.config.merge.remote, &state.base_branch)
860        .await
861        .map_err(|e| {
862            ValidationFailure::observation(format!(
863                "could not fetch base branch for revalidation: {e:#}"
864            ))
865        })?;
866    if !fetched.ok() {
867        return Err(ValidationFailure::observation(format!(
868            "could not fetch base branch for revalidation: {}",
869            fetched.stderr
870        )));
871    }
872    let onto = format!("{}/{}", state.config.merge.remote, state.base_branch);
873    let current_tip = git::rev_parse(&state.repo, &onto).await.map_err(|e| {
874        ValidationFailure::observation(format!("could not resolve fetched base tip: {e:#}"))
875    })?;
876    let descends_scope = git::ancestry(&state.repo, &auth.scope.tip, &current_tip)
877        .await
878        .map_err(|e| {
879            ValidationFailure::observation(format!(
880                "could not verify base tip lineage against authorized tip: {e:#}"
881            ))
882        })?;
883    if !descends_scope {
884        return Err(format!(
885            "fetched base tip {current_tip} does not fast-forward from authorized tip {}",
886            auth.scope.tip
887        )
888        .into());
889    }
890    let descends_stop = git::ancestry(&state.repo, &auth.stop.tip, &current_tip)
891        .await
892        .map_err(|e| {
893            ValidationFailure::observation(format!(
894                "could not verify base tip lineage against stopped tip: {e:#}"
895            ))
896        })?;
897    if !descends_stop {
898        return Err(format!(
899            "fetched base tip {current_tip} does not fast-forward from stopped tip {}",
900            auth.stop.tip
901        )
902        .into());
903    }
904
905    Ok((local_head, observed.head.clone()))
906}
907
908/// Result of dispatch-time revalidation for a landing base-sync exhaustion stop.
909pub(crate) enum DispatchDecision {
910    /// Proceed with ordinary execution or validated landing sync recovery.
911    Proceed,
912    /// Hold the task without spending an attempt or starting a replacement run.
913    Hold {
914        reason: String,
915        state: Box<RunState>,
916    },
917}
918
919/// Dispatch-time gate using `gh pr view` to revalidate pending recovery approvals.
920pub(crate) async fn dispatch_check(queue: &Queue, home: &Path, task: &Task) -> DispatchDecision {
921    dispatch_check_with(queue, home, task, &GhPrObserver).await
922}
923
924/// Injectable dispatch-time gate for unit and integration testing.
925pub(crate) async fn dispatch_check_with<O: PrObserver>(
926    queue: &Queue,
927    home: &Path,
928    task: &Task,
929    observer: &O,
930) -> DispatchDecision {
931    let Some(state) = latest_exhausted_run(queue, task) else {
932        return DispatchDecision::Proceed;
933    };
934    // Explicit exact-run resume may observe an externally closed PR without
935    // authorizing any branch synchronization.
936    if task
937        .resume_override
938        .as_ref()
939        .is_some_and(|pin| pin.pinned_run.as_deref() == Some(state.id.as_str()))
940        && let Some(pr) = &state.pr
941        && let Ok(observed) = observer.observe_pr(&state.repo, &pr.url).await
942        && !observed.open
943        && observed.url == pr.url
944        && observed.number == pr.number
945    {
946        return DispatchDecision::Proceed;
947    }
948    if !state.has_unconsumed_land_sync_authorization() && !state.land_sync_unstarted_grant() {
949        return DispatchDecision::Hold {
950            reason: format!(
951                "Landing base synchronization remains stopped. {} Ordinary resume or release grants no additional synchronization budget and starts no replacement competition.",
952                state.land_sync_next_action()
953            ),
954            state: Box::new(state),
955        };
956    }
957    match validate_pending_authorization(home, &state, Some(task), None, observer).await {
958        Ok(_) => DispatchDecision::Proceed,
959        Err(failure) => {
960            let reason = failure.reason;
961            let mut updated = state;
962            if !failure.observation_failed
963                && let Ok(_owner) = crate::pr_head::owner_lock(home, &updated.id)
964                && let Ok(mut reloaded) = RunState::load_under(&updated.id, home)
965                && let Ok(claimed) =
966                    crate::daemon::is_working_on_other(home, &reloaded.id, Timestamp::now())
967                && reloaded.liveness_under(home, claimed) == crate::run::Liveness::Dead
968                && let Ok(_exec) = crate::driver::maintenance(home, &reloaded.id)
969                && (reloaded.land_sync_recovery_pending() || reloaded.land_sync_unstarted_grant())
970                && let Some(auth) = reloaded.land_sync_recovery.authorizations.last_mut()
971                && auth.invalidated.is_none()
972                && updated
973                    .land_sync_recovery
974                    .authorizations
975                    .last()
976                    .is_some_and(|prior| prior.request == auth.request)
977            {
978                auth.refuse(&reason);
979                reloaded.event(
980                    "land-sync-recovery",
981                    format!("dispatch revalidation refused: {reason}"),
982                );
983                let _ = reloaded.save_under(home);
984                updated = reloaded;
985            }
986            DispatchDecision::Hold {
987                reason: format!(
988                    "Landing base-sync recovery refused at dispatch: {reason}. {}",
989                    updated.land_sync_next_action()
990                ),
991                state: Box::new(updated),
992            }
993        }
994    }
995}
996
997impl Task {
998    /// Anchor a landing base-sync exhaustion hold stably across driver passes.
999    pub(crate) fn land_sync_notice(&mut self, state: &RunState) {
1000        if !state.land_sync_exhausted() {
1001            return;
1002        }
1003        let stop = state.land_sync_recovery.stop.as_ref();
1004        self.held_at = Some(stop.map_or_else(|| exhausted_stop_timestamp(state), |s| s.at));
1005        self.notice_cause("land-sync-exhausted", Some(&state.id), None);
1006        if let Some(cause) = &mut self.hold_notice_cause {
1007            cause.target = Some(match stop {
1008                Some(s) => format!("{}:{}:{}:{}", s.head, s.attempts, s.limit, s.at),
1009                None => format!(
1010                    "legacy:{}:{}:{}",
1011                    state.pr_pushed_head.as_deref().unwrap_or("unknown"),
1012                    state.land_sync_attempts,
1013                    state.land_sync_budget()
1014                ),
1015            });
1016        }
1017    }
1018}