Skip to main content

magi/
base_sync_recovery.rs

1//! Durable bounded synchronization intervals and single-use owner recovery approvals.
2use anyhow::{Result, ensure};
3use jiff::Timestamp;
4use serde::{Deserialize, Serialize};
5
6use crate::run::{CommandOutcome, ReviewRound, RunState, RunStatus};
7
8#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
9#[serde(rename_all = "snake_case")]
10/// Why synchronization stopped. Only exhaustion admits a new recovery interval.
11pub enum StopKind {
12    /// The ordinary moving-base budget was spent.
13    Exhausted,
14    /// Replaying the retained changes failed.
15    Conflict,
16    /// A remote ownership or publication operation failed.
17    Publication,
18    /// The remote branch contains foreign work.
19    Divergence,
20    /// The change was integrated, but closing its PR failed and may be retried.
21    ClosingIntegratedPr,
22    /// Legacy or unexpected evidence cannot justify recovery.
23    Unknown,
24}
25
26#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
27/// Stable identity of a stopped synchronization.
28pub struct Stop {
29    /// Typed cause.
30    pub kind: StopKind,
31    /// Retained candidate commit.
32    pub head: String,
33    /// Base tip observed at the stop.
34    pub tip: String,
35    /// Cumulative attempts when stopped.
36    pub attempts: usize,
37    /// Original diagnostic, retained verbatim.
38    pub detail: String,
39    /// When this record was created.
40    pub at: Timestamp,
41    /// A synchronized HEAD had not reached its gate before the base advanced.
42    #[serde(default)]
43    pub unverified_sync: bool,
44}
45
46#[derive(Debug, Clone, Serialize, Deserialize)]
47/// One explicit owner request, consumed durably before rebasing.
48pub struct Authorization {
49    #[serde(default)]
50    pub scope: Option<Scope>,
51    /// Standing-control request key, absent for terminal recovery.
52    #[serde(default)]
53    pub request: Option<String>,
54    /// Owner decision retained by the exact queue transition.
55    #[serde(default)]
56    pub decision: Option<Timestamp>,
57    /// Exact routed decision, when recovery came from a typed owner choice.
58    #[serde(default)]
59    pub question: Option<String>,
60    /// Older approvals authorized one attempt only.
61    #[serde(default)]
62    pub interval: bool,
63    #[serde(default)]
64    pub invalidated: Option<String>,
65    /// Task whose claim admitted the request.
66    pub task: String,
67    /// Exact saved execution authorized to recover.
68    pub run: String,
69    /// Immutable stop authorized by this request.
70    pub stop: Stop,
71    /// When this record was created.
72    pub at: Timestamp,
73    /// Persisted before any Git mutation. An interrupted consumption grants no retry.
74    pub consumed: bool,
75    /// Queue approval generation, absent for an explicit recovery command.
76    #[serde(default)]
77    pub generation: Option<u64>,
78    /// Historical evidence stays attached to its original heads.
79    pub reviews: Vec<ReviewRound>,
80    /// Prior gate outcomes, never evidence for the recovered head.
81    pub gate: Vec<CommandOutcome>,
82    /// Head targeted by the archived gate.
83    pub gate_head: Option<String>,
84    /// Whether the archived gate was attempted.
85    pub gate_ran: bool,
86}
87
88impl Authorization {
89    /// Consume a refused approval without granting recovery, retaining the reason.
90    pub(crate) fn refuse(&mut self, reason: impl Into<String>) {
91        self.invalidated = Some(reason.into());
92        self.consumed = true;
93    }
94}
95
96/// A bounded active interval. Lifetime attempts remain in `BaseSync`.
97#[derive(Debug, Clone, Serialize, Deserialize)]
98pub struct Episode {
99    /// Monotonic interval identity.
100    pub id: usize,
101    /// Why this interval was opened.
102    pub reason: String,
103    /// Reservations, including interrupted operations.
104    pub used: usize,
105    /// Last successful synchronization or actually executed verification in this interval.
106    pub synced_head: Option<String>,
107    /// Last successful synchronization, distinct from verification progress.
108    #[serde(default)]
109    pub last_sync_head: Option<String>,
110    /// An interruption after progress; consumed at most once.
111    pub boundary: Option<Boundary>,
112    /// Earlier interruption evidence superseded by actual progress.
113    #[serde(default)]
114    pub prior_boundaries: Vec<Boundary>,
115}
116
117/// Durable interruption evidence, never inferred from elapsed time.
118#[derive(Debug, Clone, Serialize, Deserialize)]
119pub struct Boundary {
120    pub pass: usize,
121    pub at: Timestamp,
122    pub head: String,
123    pub consumed: bool,
124}
125
126/// Write-ahead reservation. A restart continues this exact operation.
127#[derive(Debug, Clone, Serialize, Deserialize)]
128pub struct Operation {
129    pub id: usize,
130    pub episode: usize,
131    pub head: String,
132    pub tip: String,
133    pub finished: bool,
134    /// Exact result accepted by the rebase validator, saved before scratch cleanup.
135    #[serde(default)]
136    pub validated_head: Option<String>,
137}
138
139/// Consumed owner approval for an infrastructure boundary.
140#[derive(Debug, Clone, Serialize, Deserialize)]
141pub struct Renewal {
142    pub task: String,
143    pub run: String,
144    pub generation: u64,
145    pub instruction: String,
146    pub episode: usize,
147    pub boundary_pass: usize,
148    pub head: String,
149    pub tip: String,
150}
151
152/// Approval scope additional to the immutable stop.
153#[derive(Debug, Clone, Serialize, Deserialize)]
154pub struct Scope {
155    pub tip: String,
156    pub instruction: String,
157    pub episode: usize,
158    #[serde(default, skip_serializing_if = "Option::is_none")]
159    pub preparation_digest: Option<String>,
160}
161
162#[derive(Debug, Clone, Default, Serialize, Deserialize)]
163/// Persistent stop and authorization history, additive for legacy runs.
164pub struct Recovery {
165    /// Append-only interval and operation evidence, absent in old records.
166    #[serde(default)]
167    pub episodes: Vec<Episode>,
168    #[serde(default)]
169    pub operations: Vec<Operation>,
170    /// Stops remain evidence after successful recovery.
171    #[serde(default)]
172    pub stops: Vec<Stop>,
173    #[serde(default)]
174    pub renewals: Vec<Renewal>,
175    /// Current stop, if any.
176    pub stop: Option<Stop>,
177    /// Requests and archived evidence in authorization order.
178    pub authorizations: Vec<Authorization>,
179}
180
181impl RunState {
182    /// Shared CLI, notice and web instruction, based on the typed checkpoint.
183    pub fn base_sync_next_action(&self) -> String {
184        let episode = self.base_sync_recovery.episodes.last().map_or(0, |e| e.id);
185        let lifetime = self.base_sync.as_ref().map_or(0, |s| s.attempts);
186        format!(
187            "{} ({}/{} in episode {}, {} lifetime synchronizations)",
188            self.base_sync_action(),
189            self.base_episode_used(),
190            crate::graph::BASE_SYNC_ROUNDS,
191            episode,
192            lifetime
193        )
194    }
195
196    fn base_sync_action(&self) -> String {
197        if let Some(reason) = self
198            .base_sync_recovery
199            .authorizations
200            .last()
201            .and_then(|a| a.invalidated.as_ref())
202        {
203            return format!("Approval invalidated: {reason}");
204        }
205        if crate::repair_budget::legacy::legacy_sequencer_head(self).is_some() {
206            return crate::repair_budget::legacy::LEGACY_EXEC_ACTION.into();
207        }
208        if self.resource_block.is_some() {
209            return "Restore the required resource, then explicitly resume the retained run; automatic retries retain the synchronization budget".into();
210        }
211        if self.base_sync_recovery.stop.is_none()
212            && let Some(op) = self.pending_base_operation()
213        {
214            return format!(
215                "Resume reserved synchronization {} against base {}; inspect retained Git state if reconciliation is refused",
216                op.id, op.tip
217            );
218        }
219        if self.base_sync_blocked()
220            && (self.base_sync_recovery.stop.is_none()
221                || self
222                    .rebase_fixes
223                    .iter()
224                    .any(|r| r.stop.is_none() && !r.finished))
225        {
226            let task = self
227                .origin
228                .as_ref()
229                .and_then(|o| o.task.as_deref())
230                .unwrap_or("<task>");
231            return format!(
232                "Inspect legacy or missing structured stop evidence with `magi task inspect-base-stop {task} --run {}`; diagnostic-only textual stops require explicit evidence-bound base-conflict authorization, not movement budget recovery",
233                self.id
234            );
235        }
236        match self.base_sync_recovery.stop.as_ref().map(|s| &s.kind) {
237            Some(StopKind::Exhausted) => {
238                let why = if self.base_sync_recovery.stop.as_ref().is_some_and(|s| s.unverified_sync) {
239                    "The synchronized HEAD never reached its gate before the base moved again. "
240                } else {
241                    ""
242                };
243                if self.base_recovery_pending() {
244                    format!("{why}Approval recorded; resume the retained run to open the approved bounded synchronization interval")
245                } else {
246                    format!("{why}Authorize a new bounded synchronization interval with `magi run --resume {} --recover-base`, or, from a standing chat, `magi task control recover-base {} --request <unique-id> --head {}`", self.id, self.id, self.base_sync_recovery.stop.as_ref().unwrap().head)
247                }
248            },
249            Some(StopKind::Conflict) => {
250                let stop = self.base_sync_recovery.stop.as_ref().unwrap();
251                let task = self.origin.as_ref().and_then(|origin| origin.task.as_deref()).unwrap_or("<task>");
252                format!("Authorize a narrow history-preserving repair with `magi task grant-repair {task} --run {} --kind base-conflict --rounds 1 --head {} --tip {} --expect-pass {} --request <unique-id> --reason <reason> --instruction <approved-resolution>`; retain the original review criteria. Base-budget recovery cannot resolve a textual conflict", self.id, stop.head, stop.tip, self.passes.last().map_or(0, |p| p.index))
253            },
254            Some(StopKind::Divergence) => "Reconcile foreign remote branch commits before resuming; do not overwrite them".into(),
255            Some(StopKind::Publication) => "Inspect the retained publication failure and remote lease before resuming".into(),
256            Some(StopKind::ClosingIntegratedPr) => "Resume to retry closing the already integrated pull request".into(),
257            Some(StopKind::Unknown) if self.base_recovery_pending() => "Preparation recovery approval recorded; resume the retained run using only its remaining synchronization budget".into(),
258            Some(StopKind::Unknown) => format!("Inspect the retained synchronization state with `magi task inspect-base-stop {} --run {}`. Only a recognized preparation failure with evidence and remaining budget permits recovery", self.origin.as_ref().and_then(|o| o.task.as_deref()).unwrap_or("<task>"), self.id),
259            None => "Continue verification on the current synchronized HEAD".into(),
260        }
261    }
262
263    pub(crate) fn ensure_base_episode(&mut self) {
264        if let Some(stop) = self.base_sync_recovery.stop.clone()
265            && !self.base_sync_recovery.stops.contains(&stop)
266        {
267            self.base_sync_recovery.stops.push(stop);
268        }
269        if self.base_sync_recovery.episodes.is_empty() {
270            let used = self.base_sync.as_ref().map_or(0, |s| s.attempts);
271            self.base_sync_recovery.episodes.push(Episode {
272                id: 0,
273                reason: "initial or conservative legacy migration".into(),
274                used,
275                synced_head: None,
276                last_sync_head: None,
277                boundary: None,
278                prior_boundaries: Vec::new(),
279            });
280        }
281    }
282
283    fn open_base_episode(&mut self, reason: &str) {
284        self.ensure_base_episode();
285        let id = self.base_sync_recovery.episodes.len();
286        self.base_sync_recovery.episodes.push(Episode {
287            id,
288            reason: reason.into(),
289            used: 0,
290            synced_head: None,
291            last_sync_head: None,
292            boundary: None,
293            prior_boundaries: Vec::new(),
294        });
295    }
296
297    pub(crate) fn base_episode_used(&self) -> usize {
298        self.base_sync_recovery.episodes.last().map_or_else(
299            || self.base_sync.as_ref().map_or(0, |s| s.attempts),
300            |e| e.used,
301        )
302    }
303
304    pub(crate) fn record_base_progress(&mut self, head: &str) {
305        self.ensure_base_episode();
306        let episode = self.base_sync_recovery.episodes.last_mut().unwrap();
307        if let Some(boundary) = episode.boundary.take() {
308            episode.prior_boundaries.push(boundary);
309        }
310        episode.synced_head = Some(head.into());
311    }
312
313    /// Called by the same atomic state save that retains the resource stop.
314    pub(crate) fn record_base_interruption(&mut self) {
315        let Some(block) = &self.resource_block else {
316            return;
317        };
318        if matches!(block.cause, crate::run::ResourceBlockCause::Unrecorded) {
319            return;
320        }
321        let Some(episode) = self.base_sync_recovery.episodes.last_mut() else {
322            return;
323        };
324        let Some(head) = episode.synced_head.clone() else {
325            return;
326        };
327        if episode.boundary.is_none() {
328            episode.boundary = Some(Boundary {
329                pass: self.passes.last().map_or(0, |p| p.index),
330                at: block.at,
331                head,
332                consumed: false,
333            });
334        }
335    }
336
337    pub(crate) fn renew_base_episode(
338        &mut self,
339        task: &str,
340        approval: &crate::queue::Resumption,
341        head: &str,
342        tip: &str,
343    ) -> bool {
344        if self
345            .base_sync_recovery
346            .renewals
347            .iter()
348            .any(|r| r.task == task && r.generation >= approval.generation)
349            || self
350                .base_sync_recovery
351                .authorizations
352                .iter()
353                .any(|a| a.task == task && a.generation.is_some_and(|g| g >= approval.generation))
354        {
355            return false;
356        }
357        let Some(e) = self.base_sync_recovery.episodes.last_mut() else {
358            return false;
359        };
360        let Some(b) = &mut e.boundary else {
361            return false;
362        };
363        if b.consumed || b.head != head || approval.at <= b.at {
364            return false;
365        }
366        b.consumed = true;
367        self.base_sync_recovery.renewals.push(Renewal {
368            task: task.into(),
369            run: self.id.clone(),
370            generation: approval.generation,
371            instruction: approval.instruction.clone(),
372            episode: e.id,
373            boundary_pass: b.pass,
374            head: head.into(),
375            tip: tip.into(),
376        });
377        self.open_base_episode("owner resumption after recorded infrastructure interruption");
378        true
379    }
380
381    pub(crate) fn pending_base_operation(&self) -> Option<&Operation> {
382        self.base_sync_recovery
383            .operations
384            .last()
385            .filter(|op| !op.finished)
386    }
387
388    /// Reserve once before Git; retrying an unfinished operation spends nothing more.
389    pub(crate) fn reserve_base_operation(&mut self, head: &str, tip: &str) {
390        self.ensure_base_episode();
391        if self.pending_base_operation().is_some() {
392            return;
393        }
394        let e = self.base_sync_recovery.episodes.last_mut().unwrap();
395        e.used += 1;
396        let id = self.base_sync_recovery.operations.len();
397        self.base_sync_recovery.operations.push(Operation {
398            id,
399            episode: e.id,
400            head: head.into(),
401            tip: tip.into(),
402            finished: false,
403            validated_head: None,
404        });
405        if let Some(sync) = &mut self.base_sync {
406            sync.attempts += 1;
407        }
408    }
409
410    pub(crate) fn finish_base_operation(&mut self, head: Option<&str>) {
411        if let Some(op) = self.base_sync_recovery.operations.last_mut() {
412            op.finished = true;
413        }
414        if let Some(head) = head {
415            let episode = self.base_sync_recovery.episodes.last_mut().unwrap();
416            if let Some(boundary) = episode.boundary.take() {
417                episode.prior_boundaries.push(boundary);
418            }
419            episode.synced_head = Some(head.into());
420            episode.last_sync_head = Some(head.into());
421            self.reconcile_verification_head(head);
422        }
423    }
424
425    pub(crate) fn base_sync_blocked(&self) -> bool {
426        self.base_sync
427            .as_ref()
428            .is_some_and(|s| s.conflict.is_some())
429    }
430
431    /// This checkpoint only rechecks integration and retries PR closure. It
432    /// never clears the conflict guard or grants an additional rebase.
433    pub(crate) fn base_sync_closure_pending(&self) -> bool {
434        let Some(detail) = self
435            .base_sync
436            .as_ref()
437            .and_then(|sync| sync.conflict.as_ref())
438        else {
439            return false;
440        };
441        let Some(winner) = self.winner() else {
442            return false;
443        };
444        // Also recognizes the diagnostic written before typed stops existed.
445        let prefix = format!(
446            "{} is already in {}/{}, but its pull request could not be closed (",
447            winner.branch, self.config.merge.remote, self.base_branch
448        );
449        detail.starts_with(&prefix) && detail.ends_with("); resume to retry")
450    }
451
452    /// Legacy exhaustion is recognized only by the exact message and budget.
453    /// Once recorded, its identity remains stable across no-progress passes.
454    pub(crate) fn record_base_sync_stop(&mut self, head: &str) {
455        self.record_base_sync_stop_as(head, None);
456    }
457
458    pub(crate) fn record_base_sync_stop_as(&mut self, head: &str, kind: Option<StopKind>) {
459        let Some(sync) = self.base_sync.as_ref() else {
460            return;
461        };
462        let Some(detail) = sync.conflict.clone() else {
463            return;
464        };
465        if self
466            .base_sync_recovery
467            .stop
468            .as_ref()
469            .is_some_and(|s| s.head == head && s.tip == sync.tip && s.detail == detail)
470        {
471            self.status = RunStatus::Blocked;
472            return;
473        }
474        let exhausted = self.winner().is_some_and(|w| {
475            [
476                ("rebase(s)", "rebasing"),
477                ("synchronization(s)", "synchronizing"),
478            ].iter().any(|(noun, verb)| detail == format!(
479                "{} moved {} commit(s) ahead of {} after {} {}; {} again would only race it",
480                self.base_branch, sync.behind, w.branch, crate::graph::BASE_SYNC_ROUNDS, noun, verb
481            ))
482        });
483        let inferred = || {
484            if self.base_sync_closure_pending() {
485                StopKind::ClosingIntegratedPr
486            } else if sync.attempts >= crate::graph::BASE_SYNC_ROUNDS && exhausted {
487                StopKind::Exhausted
488            } else if detail.contains("not rebasing over") {
489                StopKind::Divergence
490            } else if detail.contains("refused the push")
491                || detail.contains("could not push")
492                || detail.contains("could not be pushed")
493            {
494                StopKind::Publication
495            } else if detail.contains("conflicts with") && detail.contains("did not rebase") {
496                StopKind::Conflict
497            } else {
498                StopKind::Unknown
499            }
500        };
501        let kind = kind.unwrap_or_else(inferred);
502        let at = self
503            .events
504            .iter()
505            .rev()
506            .find(|event| event.node == "land" && event.message == detail)
507            .map_or(self.updated_at, |event| event.at);
508        let unverified_sync = sync.behind > 0
509            && self
510                .base_sync_recovery
511                .episodes
512                .last()
513                .is_some_and(|e| e.last_sync_head.as_deref() == Some(head))
514            && !(self.gate_ran && self.gate_head.as_deref() == Some(head));
515        let stop = Stop {
516            unverified_sync,
517            kind,
518            head: head.to_owned(),
519            tip: sync.tip.clone(),
520            attempts: sync.attempts,
521            detail,
522            at,
523        };
524        self.base_sync_recovery.stops.push(stop.clone());
525        self.base_sync_recovery.stop = Some(stop);
526        self.status = RunStatus::Blocked;
527    }
528
529    pub(crate) fn base_recovery_pending(&self) -> bool {
530        self.base_sync_recovery
531            .authorizations
532            .last()
533            .is_some_and(|a| {
534                !a.consumed
535                    && a.invalidated.is_none()
536                    && a.run == self.id
537                    && self.base_sync_recovery.stop.as_ref() == Some(&a.stop)
538            })
539    }
540
541    /// Recognize only the historical Windows scratch preparation failure.
542    /// No sequencer was started by this diagnostic.
543    pub(crate) fn unknown_preparation_stop(&self, head: &str) -> bool {
544        let Some(stop) = &self.base_sync_recovery.stop else {
545            return false;
546        };
547        let Some(sync) = &self.base_sync else {
548            return false;
549        };
550        let Some(winner) = self.winner() else {
551            return false;
552        };
553        let prefix = format!(
554            "could not rebase {} onto {}/{}: spawn git rev-parse --git-path magi-rebase-heads: ",
555            winner.branch, self.config.merge.remote, self.base_branch
556        );
557        stop.kind == StopKind::Unknown
558            && stop.head == head
559            && stop.tip == sync.tip
560            && stop.attempts == sync.attempts
561            && stop.attempts > 0
562            && self.base_sync_recovery.stops.contains(stop)
563            && self
564                .base_sync_recovery
565                .operations
566                .iter()
567                .all(|op| op.finished)
568            && self
569                .base_sync_recovery
570                .episodes
571                .iter()
572                .try_fold(0usize, |sum, e| sum.checked_add(e.used))
573                == Some(stop.attempts)
574            && sync.conflict.as_ref() == Some(&stop.detail)
575            && stop.detail.strip_prefix(&prefix).is_some_and(|suffix| {
576                suffix.ends_with(" (os error 267)") && !suffix.contains(['\r', '\n'])
577            })
578            && self
579                .events
580                .iter()
581                .any(|e| e.node == "land" && e.message == stop.detail && e.at == stop.at)
582            && self.base_episode_used() < crate::graph::BASE_SYNC_ROUNDS
583            && self.base_sync_recovery.operations.last().is_some_and(|op| {
584                op.finished
585                    && op.id == self.base_sync_recovery.operations.len() - 1
586                    && op.validated_head.is_none()
587                    && op.head == head
588                    && op.tip == stop.tip
589                    && self
590                        .base_sync_recovery
591                        .episodes
592                        .last()
593                        .is_some_and(|e| e.id == op.episode)
594            })
595            && self.rebase_fixes.is_empty()
596    }
597
598    pub(crate) fn preparation_digest(&self, head: &str) -> Option<String> {
599        use sha2::{Digest, Sha256};
600        self.unknown_preparation_stop(head).then(|| {
601            let evidence = serde_json::json!({
602                "run": self.id,
603                "assignment": self.task_assignment,
604                "stop": self.base_sync_recovery.stop,
605                "sync": self.base_sync,
606                "episodes": self.base_sync_recovery.episodes,
607                "operations": self.base_sync_recovery.operations,
608                "task": self.origin.as_ref().and_then(|o| o.task.as_ref()),
609                "branch": self.winner().map(|w| &w.branch),
610            });
611            Sha256::digest(evidence.to_string())
612                .iter()
613                .map(|byte| format!("{byte:02x}"))
614                .collect()
615        })
616    }
617
618    pub(crate) fn authorize_base_sync(&mut self, task: &str) -> Result<()> {
619        let stop = self
620            .base_sync_recovery
621            .stop
622            .clone()
623            .ok_or_else(|| anyhow::anyhow!("no recorded base-sync stop"))?;
624        ensure!(
625            stop.kind == StopKind::Exhausted || self.unknown_preparation_stop(&stop.head),
626            "only exhausted base movement or a proven scratch preparation stop permits recovery"
627        );
628        ensure!(
629            !self
630                .base_sync_recovery
631                .authorizations
632                .last()
633                .is_some_and(|a| !a.consumed && a.stop == stop),
634            "this stop already has a pending authorization; resume the existing request"
635        );
636        self.base_sync_recovery.authorizations.push(Authorization {
637            scope: None,
638            request: None,
639            decision: None,
640            question: None,
641            interval: true,
642            invalidated: None,
643            task: task.to_owned(),
644            run: self.id.clone(),
645            stop,
646            at: Timestamp::now(),
647            consumed: false,
648            generation: None,
649            reviews: Vec::new(),
650            gate: Vec::new(),
651            gate_head: None,
652            gate_ran: false,
653        });
654        Ok(())
655    }
656
657    pub(crate) fn authorize_base_sync_resumption(
658        &mut self,
659        task: &str,
660        approval: &crate::queue::Resumption,
661    ) -> Result<()> {
662        let stop = self
663            .base_sync_recovery
664            .stop
665            .as_ref()
666            .ok_or_else(|| anyhow::anyhow!("no recorded base-sync stop"))?;
667        ensure!(
668            approval.at > stop.at,
669            "approval predates the base-sync stop"
670        );
671        ensure!(
672            !self.base_sync_recovery.authorizations.iter().any(|a| {
673                a.task == task && a.generation.is_some_and(|g| g >= approval.generation)
674            }) && !self
675                .base_sync_recovery
676                .renewals
677                .iter()
678                .any(|r| r.task == task && r.generation >= approval.generation),
679            "operator resumption generation already used"
680        );
681        self.authorize_base_sync(task)?;
682        self.base_sync_recovery
683            .authorizations
684            .last_mut()
685            .unwrap()
686            .generation = Some(approval.generation);
687        Ok(())
688    }
689
690    /// Consume the approved recovery and detach old verification evidence atomically.
691    /// Preparation recovery keeps the same interval. Save before reserving Git work.
692    pub(crate) fn consume_base_recovery(&mut self, head: &str) -> bool {
693        if !self.base_recovery_pending() {
694            return false;
695        }
696        let preparation_valid = self
697            .base_sync_recovery
698            .authorizations
699            .last()
700            .is_some_and(|a| {
701                a.stop.kind != StopKind::Unknown
702                    || a.scope.as_ref().is_some_and(|scope| {
703                        scope.preparation_digest.is_some()
704                            && scope.preparation_digest == self.preparation_digest(head)
705                    })
706            });
707        let a = self.base_sync_recovery.authorizations.last_mut().unwrap();
708        a.consumed = true;
709        if !preparation_valid {
710            a.refuse("preparation stop evidence changed; inspect and authorize again");
711            return false;
712        }
713        if a.stop.head != head {
714            a.refuse(format!(
715                "retained HEAD changed from {} to {head}; inspect it and authorize again with --recover-base",
716                a.stop.head
717            ));
718            return false;
719        }
720        a.reviews = self.reviews.clone();
721        a.gate = std::mem::take(&mut self.gate);
722        a.gate_head = self.gate_head.take();
723        a.gate_ran = std::mem::replace(&mut self.gate_ran, false);
724        let interval = a.interval;
725        self.base_sync.as_mut().unwrap().conflict = None;
726        if a.stop.kind == StopKind::Unknown {
727            for review in &mut self.reviews {
728                review.verified_head = None;
729            }
730            for e2e in [self.head_e2e.take(), self.gate_repair_e2e.take()]
731                .into_iter()
732                .flatten()
733            {
734                self.verification_history
735                    .push(crate::run::VerificationEvidence {
736                        superseded_by: None,
737                        archived_at: Some(Timestamp::now()),
738                        fixes_spent: Some(self.gate_fixes.len()),
739                        gate_head: None,
740                        gate_ran: false,
741                        gate: Vec::new(),
742                        e2e: Some(e2e),
743                    });
744            }
745            self.pre_gate.clear();
746            self.pre_gate_commit = None;
747        } else {
748            self.open_base_episode("explicit exhausted-base recovery");
749            if !interval {
750                self.base_sync_recovery.episodes.last_mut().unwrap().used =
751                    crate::graph::BASE_SYNC_ROUNDS - 1;
752            }
753        }
754        self.base_sync_recovery.stop = None;
755        true
756    }
757}
758
759/// A generic task release cannot authorize a stopped base synchronization.
760/// Use the queue's own home, including isolated triage stores.
761pub(crate) fn held_task(queue: &crate::queue::Queue, task: &crate::queue::Task) -> bool {
762    held_run(queue, task).is_some()
763}
764
765pub(crate) fn held_run(queue: &crate::queue::Queue, task: &crate::queue::Task) -> Option<RunState> {
766    let home = queue.root().parent()?;
767    task.execution_runs()
768        .last()
769        .and_then(|id| RunState::load_under(id, home).ok())
770        .filter(|state| {
771            state.base_sync_blocked()
772                && !state.base_recovery_pending()
773                && !state.base_sync_closure_pending()
774        })
775}
776
777impl crate::queue::Task {
778    /// Keep a producer stop stable across generic releases and driver passes.
779    pub(crate) fn base_sync_notice(&mut self, state: &RunState) {
780        let Some(sync) = state
781            .base_sync
782            .as_ref()
783            .filter(|_| state.base_sync_blocked())
784        else {
785            return;
786        };
787        let stop = state.base_sync_recovery.stop.as_ref();
788        self.held_at = Some(stop.map_or(state.updated_at, |s| s.at));
789        self.notice_cause("base-sync-stop", Some(&state.id), None);
790        if let Some(cause) = &mut self.hold_notice_cause {
791            cause.target = Some(match stop {
792                Some(s) => format!("{}:{}:{}", s.head, s.tip, s.at),
793                None => format!("legacy:{}:{}", sync.tip, sync.attempts),
794            });
795        }
796    }
797}
798
799/// Refuse a generic release at a textual stop before changing queue state.
800pub fn ensure_generic_release(
801    queue: &crate::queue::Queue,
802    task: &crate::queue::Task,
803) -> Result<()> {
804    if let Some(state) = task
805        .execution_runs()
806        .last()
807        .and_then(|id| RunState::load_under(id, queue.root().parent()?).ok())
808        && let Some(reason) = crate::repair_budget::conflict_failure(task, &state)
809    {
810        anyhow::bail!(reason);
811    }
812    if let Some(state) = held_run(queue, task)
813        && state
814            .base_sync_recovery
815            .stop
816            .as_ref()
817            .is_some_and(|s| s.kind == StopKind::Conflict)
818        && !crate::repair_budget::conflict_pending(task, &state)
819    {
820        anyhow::bail!(
821            "generic release cannot authorize this stopped synchronization. {}",
822            state.base_sync_next_action()
823        );
824    }
825    if let Some(state) = crate::land_sync_recovery::held_run(queue, task) {
826        anyhow::bail!(
827            "generic release cannot authorize exhausted landing base synchronization. {}",
828            state.land_sync_next_action()
829        );
830    }
831    Ok(())
832}