1use 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")]
10pub enum StopKind {
12 Exhausted,
14 Conflict,
16 Publication,
18 Divergence,
20 ClosingIntegratedPr,
22 Unknown,
24}
25
26#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
27pub struct Stop {
29 pub kind: StopKind,
31 pub head: String,
33 pub tip: String,
35 pub attempts: usize,
37 pub detail: String,
39 pub at: Timestamp,
41 #[serde(default)]
43 pub unverified_sync: bool,
44}
45
46#[derive(Debug, Clone, Serialize, Deserialize)]
47pub struct Authorization {
49 #[serde(default)]
50 pub scope: Option<Scope>,
51 #[serde(default)]
53 pub request: Option<String>,
54 #[serde(default)]
56 pub decision: Option<Timestamp>,
57 #[serde(default)]
59 pub question: Option<String>,
60 #[serde(default)]
62 pub interval: bool,
63 #[serde(default)]
64 pub invalidated: Option<String>,
65 pub task: String,
67 pub run: String,
69 pub stop: Stop,
71 pub at: Timestamp,
73 pub consumed: bool,
75 #[serde(default)]
77 pub generation: Option<u64>,
78 pub reviews: Vec<ReviewRound>,
80 pub gate: Vec<CommandOutcome>,
82 pub gate_head: Option<String>,
84 pub gate_ran: bool,
86}
87
88impl Authorization {
89 pub(crate) fn refuse(&mut self, reason: impl Into<String>) {
91 self.invalidated = Some(reason.into());
92 self.consumed = true;
93 }
94}
95
96#[derive(Debug, Clone, Serialize, Deserialize)]
98pub struct Episode {
99 pub id: usize,
101 pub reason: String,
103 pub used: usize,
105 pub synced_head: Option<String>,
107 #[serde(default)]
109 pub last_sync_head: Option<String>,
110 pub boundary: Option<Boundary>,
112 #[serde(default)]
114 pub prior_boundaries: Vec<Boundary>,
115}
116
117#[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#[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 #[serde(default)]
136 pub validated_head: Option<String>,
137}
138
139#[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#[derive(Debug, Clone, Serialize, Deserialize)]
154pub struct Scope {
155 pub tip: String,
156 pub instruction: String,
157 pub episode: usize,
158}
159
160#[derive(Debug, Clone, Default, Serialize, Deserialize)]
161pub struct Recovery {
163 #[serde(default)]
165 pub episodes: Vec<Episode>,
166 #[serde(default)]
167 pub operations: Vec<Operation>,
168 #[serde(default)]
170 pub stops: Vec<Stop>,
171 #[serde(default)]
172 pub renewals: Vec<Renewal>,
173 pub stop: Option<Stop>,
175 pub authorizations: Vec<Authorization>,
177}
178
179impl RunState {
180 pub fn base_sync_next_action(&self) -> String {
182 let episode = self.base_sync_recovery.episodes.last().map_or(0, |e| e.id);
183 let lifetime = self.base_sync.as_ref().map_or(0, |s| s.attempts);
184 format!(
185 "{} ({}/{} in episode {}, {} lifetime synchronizations)",
186 self.base_sync_action(),
187 self.base_episode_used(),
188 crate::graph::BASE_SYNC_ROUNDS,
189 episode,
190 lifetime
191 )
192 }
193
194 fn base_sync_action(&self) -> String {
195 if let Some(reason) = self
196 .base_sync_recovery
197 .authorizations
198 .last()
199 .and_then(|a| a.invalidated.as_ref())
200 {
201 return format!("Approval invalidated: {reason}");
202 }
203 if crate::repair_budget::legacy::legacy_sequencer_head(self).is_some() {
204 return crate::repair_budget::legacy::LEGACY_EXEC_ACTION.into();
205 }
206 if self.resource_block.is_some() {
207 return "Restore the required resource, then explicitly resume the retained run; automatic retries retain the synchronization budget".into();
208 }
209 if self.base_sync_recovery.stop.is_none()
210 && let Some(op) = self.pending_base_operation()
211 {
212 return format!(
213 "Resume reserved synchronization {} against base {}; inspect retained Git state if reconciliation is refused",
214 op.id, op.tip
215 );
216 }
217 if self.base_sync_blocked()
218 && (self.base_sync_recovery.stop.is_none()
219 || self
220 .rebase_fixes
221 .iter()
222 .any(|r| r.stop.is_none() && !r.finished))
223 {
224 let task = self
225 .origin
226 .as_ref()
227 .and_then(|o| o.task.as_deref())
228 .unwrap_or("<task>");
229 return format!(
230 "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",
231 self.id
232 );
233 }
234 match self.base_sync_recovery.stop.as_ref().map(|s| &s.kind) {
235 Some(StopKind::Exhausted) => {
236 let why = if self.base_sync_recovery.stop.as_ref().is_some_and(|s| s.unverified_sync) {
237 "The synchronized HEAD never reached its gate before the base moved again. "
238 } else {
239 ""
240 };
241 if self.base_recovery_pending() {
242 format!("{why}Approval recorded; resume the retained run to open the approved bounded synchronization interval")
243 } else {
244 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)
245 }
246 },
247 Some(StopKind::Conflict) => {
248 let stop = self.base_sync_recovery.stop.as_ref().unwrap();
249 let task = self.origin.as_ref().and_then(|origin| origin.task.as_deref()).unwrap_or("<task>");
250 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))
251 },
252 Some(StopKind::Divergence) => "Reconcile foreign remote branch commits before resuming; do not overwrite them".into(),
253 Some(StopKind::Publication) => "Inspect the retained publication failure and remote lease before resuming".into(),
254 Some(StopKind::ClosingIntegratedPr) => "Resume to retry closing the already integrated pull request".into(),
255 Some(StopKind::Unknown) => "Inspect the retained synchronization state before resuming; unknown evidence grants no new budget".into(),
256 None => "Continue verification on the current synchronized HEAD".into(),
257 }
258 }
259
260 pub(crate) fn ensure_base_episode(&mut self) {
261 if let Some(stop) = self.base_sync_recovery.stop.clone()
262 && !self.base_sync_recovery.stops.contains(&stop)
263 {
264 self.base_sync_recovery.stops.push(stop);
265 }
266 if self.base_sync_recovery.episodes.is_empty() {
267 let used = self.base_sync.as_ref().map_or(0, |s| s.attempts);
268 self.base_sync_recovery.episodes.push(Episode {
269 id: 0,
270 reason: "initial or conservative legacy migration".into(),
271 used,
272 synced_head: None,
273 last_sync_head: None,
274 boundary: None,
275 prior_boundaries: Vec::new(),
276 });
277 }
278 }
279
280 fn open_base_episode(&mut self, reason: &str) {
281 self.ensure_base_episode();
282 let id = self.base_sync_recovery.episodes.len();
283 self.base_sync_recovery.episodes.push(Episode {
284 id,
285 reason: reason.into(),
286 used: 0,
287 synced_head: None,
288 last_sync_head: None,
289 boundary: None,
290 prior_boundaries: Vec::new(),
291 });
292 }
293
294 pub(crate) fn base_episode_used(&self) -> usize {
295 self.base_sync_recovery.episodes.last().map_or_else(
296 || self.base_sync.as_ref().map_or(0, |s| s.attempts),
297 |e| e.used,
298 )
299 }
300
301 pub(crate) fn record_base_progress(&mut self, head: &str) {
302 self.ensure_base_episode();
303 let episode = self.base_sync_recovery.episodes.last_mut().unwrap();
304 if let Some(boundary) = episode.boundary.take() {
305 episode.prior_boundaries.push(boundary);
306 }
307 episode.synced_head = Some(head.into());
308 }
309
310 pub(crate) fn record_base_interruption(&mut self) {
312 let Some(block) = &self.resource_block else {
313 return;
314 };
315 if matches!(block.cause, crate::run::ResourceBlockCause::Unrecorded) {
316 return;
317 }
318 let Some(episode) = self.base_sync_recovery.episodes.last_mut() else {
319 return;
320 };
321 let Some(head) = episode.synced_head.clone() else {
322 return;
323 };
324 if episode.boundary.is_none() {
325 episode.boundary = Some(Boundary {
326 pass: self.passes.last().map_or(0, |p| p.index),
327 at: block.at,
328 head,
329 consumed: false,
330 });
331 }
332 }
333
334 pub(crate) fn renew_base_episode(
335 &mut self,
336 task: &str,
337 approval: &crate::queue::Resumption,
338 head: &str,
339 tip: &str,
340 ) -> bool {
341 if self
342 .base_sync_recovery
343 .renewals
344 .iter()
345 .any(|r| r.task == task && r.generation >= approval.generation)
346 || self
347 .base_sync_recovery
348 .authorizations
349 .iter()
350 .any(|a| a.task == task && a.generation.is_some_and(|g| g >= approval.generation))
351 {
352 return false;
353 }
354 let Some(e) = self.base_sync_recovery.episodes.last_mut() else {
355 return false;
356 };
357 let Some(b) = &mut e.boundary else {
358 return false;
359 };
360 if b.consumed || b.head != head || approval.at <= b.at {
361 return false;
362 }
363 b.consumed = true;
364 self.base_sync_recovery.renewals.push(Renewal {
365 task: task.into(),
366 run: self.id.clone(),
367 generation: approval.generation,
368 instruction: approval.instruction.clone(),
369 episode: e.id,
370 boundary_pass: b.pass,
371 head: head.into(),
372 tip: tip.into(),
373 });
374 self.open_base_episode("owner resumption after recorded infrastructure interruption");
375 true
376 }
377
378 pub(crate) fn pending_base_operation(&self) -> Option<&Operation> {
379 self.base_sync_recovery
380 .operations
381 .last()
382 .filter(|op| !op.finished)
383 }
384
385 pub(crate) fn reserve_base_operation(&mut self, head: &str, tip: &str) {
387 self.ensure_base_episode();
388 if self.pending_base_operation().is_some() {
389 return;
390 }
391 let e = self.base_sync_recovery.episodes.last_mut().unwrap();
392 e.used += 1;
393 let id = self.base_sync_recovery.operations.len();
394 self.base_sync_recovery.operations.push(Operation {
395 id,
396 episode: e.id,
397 head: head.into(),
398 tip: tip.into(),
399 finished: false,
400 validated_head: None,
401 });
402 if let Some(sync) = &mut self.base_sync {
403 sync.attempts += 1;
404 }
405 }
406
407 pub(crate) fn finish_base_operation(&mut self, head: Option<&str>) {
408 if let Some(op) = self.base_sync_recovery.operations.last_mut() {
409 op.finished = true;
410 }
411 if let Some(head) = head {
412 let episode = self.base_sync_recovery.episodes.last_mut().unwrap();
413 if let Some(boundary) = episode.boundary.take() {
414 episode.prior_boundaries.push(boundary);
415 }
416 episode.synced_head = Some(head.into());
417 episode.last_sync_head = Some(head.into());
418 self.reconcile_verification_head(head);
419 }
420 }
421
422 pub(crate) fn base_sync_blocked(&self) -> bool {
423 self.base_sync
424 .as_ref()
425 .is_some_and(|s| s.conflict.is_some())
426 }
427
428 pub(crate) fn base_sync_closure_pending(&self) -> bool {
431 let Some(detail) = self
432 .base_sync
433 .as_ref()
434 .and_then(|sync| sync.conflict.as_ref())
435 else {
436 return false;
437 };
438 let Some(winner) = self.winner() else {
439 return false;
440 };
441 let prefix = format!(
443 "{} is already in {}/{}, but its pull request could not be closed (",
444 winner.branch, self.config.merge.remote, self.base_branch
445 );
446 detail.starts_with(&prefix) && detail.ends_with("); resume to retry")
447 }
448
449 pub(crate) fn record_base_sync_stop(&mut self, head: &str) {
452 self.record_base_sync_stop_as(head, None);
453 }
454
455 pub(crate) fn record_base_sync_stop_as(&mut self, head: &str, kind: Option<StopKind>) {
456 let Some(sync) = self.base_sync.as_ref() else {
457 return;
458 };
459 let Some(detail) = sync.conflict.clone() else {
460 return;
461 };
462 if self
463 .base_sync_recovery
464 .stop
465 .as_ref()
466 .is_some_and(|s| s.head == head && s.tip == sync.tip && s.detail == detail)
467 {
468 self.status = RunStatus::Blocked;
469 return;
470 }
471 let exhausted = self.winner().is_some_and(|w| {
472 [
473 ("rebase(s)", "rebasing"),
474 ("synchronization(s)", "synchronizing"),
475 ].iter().any(|(noun, verb)| detail == format!(
476 "{} moved {} commit(s) ahead of {} after {} {}; {} again would only race it",
477 self.base_branch, sync.behind, w.branch, crate::graph::BASE_SYNC_ROUNDS, noun, verb
478 ))
479 });
480 let inferred = || {
481 if self.base_sync_closure_pending() {
482 StopKind::ClosingIntegratedPr
483 } else if sync.attempts >= crate::graph::BASE_SYNC_ROUNDS && exhausted {
484 StopKind::Exhausted
485 } else if detail.contains("not rebasing over") {
486 StopKind::Divergence
487 } else if detail.contains("refused the push")
488 || detail.contains("could not push")
489 || detail.contains("could not be pushed")
490 {
491 StopKind::Publication
492 } else if detail.contains("conflicts with") && detail.contains("did not rebase") {
493 StopKind::Conflict
494 } else {
495 StopKind::Unknown
496 }
497 };
498 let kind = kind.unwrap_or_else(inferred);
499 let at = self
500 .events
501 .iter()
502 .rev()
503 .find(|event| event.node == "land" && event.message == detail)
504 .map_or(self.updated_at, |event| event.at);
505 let unverified_sync = sync.behind > 0
506 && self
507 .base_sync_recovery
508 .episodes
509 .last()
510 .is_some_and(|e| e.last_sync_head.as_deref() == Some(head))
511 && !(self.gate_ran && self.gate_head.as_deref() == Some(head));
512 let stop = Stop {
513 unverified_sync,
514 kind,
515 head: head.to_owned(),
516 tip: sync.tip.clone(),
517 attempts: sync.attempts,
518 detail,
519 at,
520 };
521 self.base_sync_recovery.stops.push(stop.clone());
522 self.base_sync_recovery.stop = Some(stop);
523 self.status = RunStatus::Blocked;
524 }
525
526 pub(crate) fn base_recovery_pending(&self) -> bool {
527 self.base_sync_recovery
528 .authorizations
529 .last()
530 .is_some_and(|a| {
531 !a.consumed
532 && a.invalidated.is_none()
533 && a.run == self.id
534 && self.base_sync_recovery.stop.as_ref() == Some(&a.stop)
535 })
536 }
537
538 pub(crate) fn authorize_base_sync(&mut self, task: &str) -> Result<()> {
539 let stop = self
540 .base_sync_recovery
541 .stop
542 .clone()
543 .ok_or_else(|| anyhow::anyhow!("no recorded base-sync stop"))?;
544 ensure!(
545 stop.kind == StopKind::Exhausted,
546 "only exhausted base movement permits recovery"
547 );
548 ensure!(
549 !self
550 .base_sync_recovery
551 .authorizations
552 .last()
553 .is_some_and(|a| !a.consumed && a.stop == stop),
554 "this stop already has a pending authorization; resume the existing request"
555 );
556 self.base_sync_recovery.authorizations.push(Authorization {
557 scope: None,
558 request: None,
559 decision: None,
560 question: None,
561 interval: true,
562 invalidated: None,
563 task: task.to_owned(),
564 run: self.id.clone(),
565 stop,
566 at: Timestamp::now(),
567 consumed: false,
568 generation: None,
569 reviews: Vec::new(),
570 gate: Vec::new(),
571 gate_head: None,
572 gate_ran: false,
573 });
574 Ok(())
575 }
576
577 pub(crate) fn authorize_base_sync_resumption(
578 &mut self,
579 task: &str,
580 approval: &crate::queue::Resumption,
581 ) -> Result<()> {
582 let stop = self
583 .base_sync_recovery
584 .stop
585 .as_ref()
586 .ok_or_else(|| anyhow::anyhow!("no recorded base-sync stop"))?;
587 ensure!(
588 approval.at > stop.at,
589 "approval predates the base-sync stop"
590 );
591 ensure!(
592 !self.base_sync_recovery.authorizations.iter().any(|a| {
593 a.task == task && a.generation.is_some_and(|g| g >= approval.generation)
594 }) && !self
595 .base_sync_recovery
596 .renewals
597 .iter()
598 .any(|r| r.task == task && r.generation >= approval.generation),
599 "operator resumption generation already used"
600 );
601 self.authorize_base_sync(task)?;
602 self.base_sync_recovery
603 .authorizations
604 .last_mut()
605 .unwrap()
606 .generation = Some(approval.generation);
607 Ok(())
608 }
609
610 pub(crate) fn consume_base_recovery(&mut self, head: &str) -> bool {
613 if !self.base_recovery_pending() {
614 return false;
615 }
616 let a = self.base_sync_recovery.authorizations.last_mut().unwrap();
617 a.consumed = true;
618 if a.stop.head != head {
619 a.refuse(format!(
620 "retained HEAD changed from {} to {head}; inspect it and authorize again with --recover-base",
621 a.stop.head
622 ));
623 return false;
624 }
625 a.reviews = self.reviews.clone();
626 a.gate = std::mem::take(&mut self.gate);
627 a.gate_head = self.gate_head.take();
628 a.gate_ran = std::mem::replace(&mut self.gate_ran, false);
629 let interval = a.interval;
630 self.base_sync.as_mut().unwrap().conflict = None;
631 self.open_base_episode("explicit exhausted-base recovery");
632 self.base_sync_recovery.stop = None;
633 if !interval {
634 self.base_sync_recovery.episodes.last_mut().unwrap().used =
635 crate::graph::BASE_SYNC_ROUNDS - 1;
636 }
637 true
638 }
639}
640
641pub(crate) fn held_task(queue: &crate::queue::Queue, task: &crate::queue::Task) -> bool {
644 held_run(queue, task).is_some()
645}
646
647pub(crate) fn held_run(queue: &crate::queue::Queue, task: &crate::queue::Task) -> Option<RunState> {
648 let home = queue.root().parent()?;
649 task.execution_runs()
650 .last()
651 .and_then(|id| RunState::load_under(id, home).ok())
652 .filter(|state| {
653 state.base_sync_blocked()
654 && !state.base_recovery_pending()
655 && !state.base_sync_closure_pending()
656 })
657}
658
659impl crate::queue::Task {
660 pub(crate) fn base_sync_notice(&mut self, state: &RunState) {
662 let Some(sync) = state
663 .base_sync
664 .as_ref()
665 .filter(|_| state.base_sync_blocked())
666 else {
667 return;
668 };
669 let stop = state.base_sync_recovery.stop.as_ref();
670 self.held_at = Some(stop.map_or(state.updated_at, |s| s.at));
671 self.notice_cause("base-sync-stop", Some(&state.id), None);
672 if let Some(cause) = &mut self.hold_notice_cause {
673 cause.target = Some(match stop {
674 Some(s) => format!("{}:{}:{}", s.head, s.tip, s.at),
675 None => format!("legacy:{}:{}", sync.tip, sync.attempts),
676 });
677 }
678 }
679}
680
681pub fn ensure_generic_release(
683 queue: &crate::queue::Queue,
684 task: &crate::queue::Task,
685) -> Result<()> {
686 if let Some(state) = task
687 .execution_runs()
688 .last()
689 .and_then(|id| RunState::load_under(id, queue.root().parent()?).ok())
690 && let Some(reason) = crate::repair_budget::conflict_failure(task, &state)
691 {
692 anyhow::bail!(reason);
693 }
694 if let Some(state) = held_run(queue, task)
695 && state
696 .base_sync_recovery
697 .stop
698 .as_ref()
699 .is_some_and(|s| s.kind == StopKind::Conflict)
700 && !crate::repair_budget::conflict_pending(task, &state)
701 {
702 anyhow::bail!(
703 "generic release cannot authorize this stopped synchronization. {}",
704 state.base_sync_next_action()
705 );
706 }
707 Ok(())
708}