magi-cli 0.278.0

Blind multi-agent implementation competition: N agents implement, M judges rank blind, deliberate, vote privately, winner survives double review + E2E gate
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
//! Owner-authorized adoption of a revised task instruction into the retained
//! run and open pull request that already carry the task.
//!
//! The ordinary fences stay as they are: a run whose instruction generation
//! differs from its task's is not resumable, and `retry` only edits the task.
//! This operation is the one explicit way across that fence. It is
//! owner-authenticated (CLI terminal or an explicit chat turn), bound to the
//! exact retained/public head, and recorded in three durable phases:
//!
//! 1. `prepared`: immutable request, task snapshot and head, before any state changes.
//! 2. `authorized`: the run adopts the instruction generation, files one bounded
//!    repair request on the same PR and drops every approval and verification
//!    that belonged to the old generation.
//! 3. `applied`: the exact-run queue pin and request marker are committed on the task.
//!
//! Replaying the same request after an interruption continues from the saved
//! phase and never adopts twice or grants another repair. The repair itself is
//! the existing bounded fix-and-re-review path: it spends the run's own
//! `land_rounds` / `review_rounds` budget, reruns E2E and the gate, and ends
//! at a fresh head-bound approval question.
use std::path::{Path, PathBuf};

use anyhow::{Context, Result, anyhow, ensure};
use jiff::Timestamp;
use serde::{Deserialize, Serialize};

use crate::{
    git,
    land_sync_recovery::{GhPrObserver, PrObserver},
    queue::{OperatorResume, Queue, Task, TaskStatus},
    run::{LandApproval, Liveness, MergeRepair, MergeRepairPhase, RunState, RunStatus},
};

pub use crate::land_sync_recovery_control::BeforeWrite;

fn before_write<T>(result: Result<T>) -> Result<T> {
    result.map_err(|error| {
        if error.is::<BeforeWrite>() {
            error
        } else {
            anyhow::Error::new(BeforeWrite(error))
        }
    })
}

/// Validated instruction-adoption request.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Request {
    /// Full retained run ID.
    pub run: String,
    /// Full 40-character HEAD SHA inspected on the retained worktree, recorded
    /// publication, public branch and open PR.
    pub head: String,
    /// Actor namespace (`"cli"` or chat talk ID).
    pub actor: String,
    /// Durable idempotency key; reuse only with identical arguments.
    pub request: String,
}

/// Result of an adoption request.
#[derive(Debug, Clone)]
pub struct Outcome {
    /// Owning task after admission or idempotent reconciliation.
    pub task: Task,
    /// `true` when this exact request had already been applied.
    pub repeated: bool,
    /// `true` when an interrupted acceptance was completed.
    pub reconciled: bool,
}

/// One adopted instruction generation, kept on the run as history.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Revision {
    /// `actor/request` key of the owner operation.
    pub request: String,
    /// Task instruction generation adopted.
    pub rev: u64,
    /// Instruction now handed to fixers and reviewers.
    pub instruction: String,
    /// Run instruction before adoption; expired history, never a requirement.
    pub previous_instruction: String,
    /// Authored task instruction before adoption.
    pub previous_task_instruction: Option<String>,
    /// Task instruction generation before adoption.
    pub previous_rev: Option<u64>,
    /// Exact head the repair starts from.
    pub head: String,
    /// Question of the repair request filed for this revision.
    pub repair: String,
    /// Approval binding that was revoked, if any.
    pub invalidated_approval: Option<LandApproval>,
    /// When the run adopted the revision.
    pub at: Timestamp,
}

impl RunState {
    /// Whether `question` carried an approval the owner gave for an
    /// instruction generation that has since been replaced.
    pub fn approval_revoked_by_revision(&self, question: &str) -> bool {
        self.instruction_revisions.iter().any(|r| {
            r.invalidated_approval
                .as_ref()
                .is_some_and(|a| a.question == question)
        })
    }

    /// Only the repair bound to the current instruction generation can
    /// authorize its return to normal landing.
    pub(crate) fn unfinished_instruction_revision(&self) -> Option<&Revision> {
        self.instruction_revisions.last().filter(|revision| {
            !self.merge_repairs.iter().any(|repair| {
                repair.question == revision.repair && repair.phase == MergeRepairPhase::Complete
            })
        })
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
enum Phase {
    Prepared,
    Authorized,
    Applied,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct Binding {
    task: serde_json::Value,
    instruction: String,
    rev: u64,
    head: String,
    pr: String,
    repair: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct Receipt {
    request: Request,
    phase: Phase,
    binding: Binding,
    queued: Task,
    created_at: Timestamp,
    #[serde(default)]
    applied_at: Option<Timestamp>,
}

fn save_receipt(path: &Path, receipt: &Receipt) -> Result<()> {
    let tmp = path.with_extension("tmp");
    std::fs::write(&tmp, serde_json::to_vec_pretty(receipt)?)?;
    std::fs::rename(tmp, path)?;
    Ok(())
}

/// Receipt path for `request` of `actor` under `home`.
pub fn receipt_path(home: &Path, actor: &str, request: &str) -> PathBuf {
    home.join("instruction-revision-controls")
        .join(actor)
        .join(format!("{request}.json"))
}

/// Move `state` onto the revised instruction and file the bounded repair.
///
/// Everything that vouched for the old generation stops counting: the approval
/// binding, the armed-merge record, the head verification and the gate. The
/// reviews stay, copied into the repair request as immutable history.
pub fn adopt_into_run(
    state: &mut RunState,
    key: &str,
    repair: &str,
    instruction: &str,
    rev: u64,
    head: &str,
    pr: &str,
) {
    let at = Timestamp::now();
    state.instruction_revisions.push(Revision {
        request: key.to_owned(),
        rev,
        instruction: instruction.to_owned(),
        previous_instruction: std::mem::replace(&mut state.instruction, instruction.to_owned()),
        previous_task_instruction: state.task_instruction.replace(instruction.to_owned()),
        previous_rev: state.task_instruction_rev.replace(rev),
        head: head.to_owned(),
        repair: repair.to_owned(),
        invalidated_approval: state.land_approval.take(),
        at,
    });
    if let Some(e2e) = state.head_e2e.take() {
        state
            .verification_history
            .push(crate::run::VerificationEvidence {
                superseded_by: None,
                archived_at: Some(at),
                fixes_spent: Some(state.gate_fixes.len()),
                gate_head: None,
                gate_ran: false,
                gate: Vec::new(),
                e2e: Some(e2e),
            });
    }
    state.merge_repairs.push(MergeRepair {
        question: repair.to_owned(),
        head: head.to_owned(),
        pr: pr.to_owned(),
        reviews: state.reviews.clone(),
        gate: state.gate.clone(),
        gate_head: state.gate_head.clone(),
        gate_fixes: state.gate_fixes.clone(),
        pre_gate: state.pre_gate.clone(),
        phase: MergeRepairPhase::Requested,
        failure: None,
    });
    state.gate_ran = false;
    state.gate_head = None;
    state.land_armed_head = None;
    state.land_reruns = None;
    state.parked = false;
    state.status = RunStatus::Landing;
    state.event(
        "instruction-revision",
        format!(
            "owner adopted task instruction generation {rev} into this run and PR; bounded repair and a fresh review, E2E, gate and head-bound approval are required"
        ),
    );
}

/// Adopt the task's current instruction into its retained run, using `gh pr view`.
pub async fn adopt(queue: &Queue, home: &Path, request: Request) -> Result<Outcome> {
    adopt_with(queue, home, request, &GhPrObserver).await
}

/// [`adopt`] with an injectable PR observer.
#[allow(clippy::too_many_lines)]
pub async fn adopt_with<O: PrObserver>(
    queue: &Queue,
    home: &Path,
    mut request: Request,
    observer: &O,
) -> Result<Outcome> {
    before_write((|| -> Result<()> {
        ensure!(
            crate::run::is_run_id(&request.run),
            "instruction adoption needs a full run id"
        );
        ensure!(
            crate::ask::valid_asset_name(&request.actor)
                && crate::ask::valid_asset_name(&request.request),
            "actor and request must be safe filenames of at most 64 bytes"
        );
        ensure!(
            request.head.len() == 40 && request.head.bytes().all(|c| c.is_ascii_hexdigit()),
            "instruction adoption needs a full 40-character HEAD SHA"
        );
        Ok(())
    })())?;
    request.head = request.head.to_ascii_lowercase();

    let dir = home
        .join("instruction-revision-controls")
        .join(&request.actor);
    before_write(std::fs::create_dir_all(&dir).map_err(Into::into))?;
    let lock = before_write(
        std::fs::OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(false)
            .open(dir.join(format!("{}.lock", request.request)))
            .map_err(Into::into),
    )?;
    before_write(crate::pr_head::try_lock_file(&lock).map_err(Into::into))?;

    let path = receipt_path(home, &request.actor, &request.request);
    let key = format!("{}/{}", request.actor, request.request);
    let repair = format!("instruction-{}-{}", request.actor, request.request);

    let prior: Option<Receipt> = if path.exists() {
        let bytes = std::fs::read(&path).with_context(|| {
            format!(
                "uncertain instruction revision receipt: could not read {}; inspect before retrying",
                path.display()
            )
        })?;
        Some(serde_json::from_slice(&bytes).with_context(|| {
            format!(
                "uncertain instruction revision receipt: corrupt JSON in {}; inspect before retrying",
                path.display()
            )
        })?)
    } else {
        None
    };

    if let Some(prior) = &prior {
        if prior.request != request {
            return Err(anyhow::Error::new(BeforeWrite(anyhow!(
                "request ID already binds a different operation"
            ))));
        }
        let task = queue.get(&prior.queued.id).with_context(|| {
            format!(
                "uncertain instruction revision receipt: owning task {} unreadable",
                prior.queued.id
            )
        })?;
        if prior.phase == Phase::Applied {
            return Ok(Outcome {
                task,
                repeated: true,
                reconciled: false,
            });
        }
        if task.instruction_revision_requests.contains(&key) {
            let mut completed = prior.clone();
            completed.phase = Phase::Applied;
            completed.applied_at = Some(Timestamp::now());
            save_receipt(&path, &completed)?;
            return Ok(Outcome {
                task,
                repeated: true,
                reconciled: true,
            });
        }
    }

    let fresh = prior.is_none();
    let wrap = |err: anyhow::Error| -> anyhow::Error {
        if fresh {
            anyhow::Error::new(BeforeWrite(err))
        } else {
            err
        }
    };

    crate::task_reassign::ensure_current(queue, &request.run).map_err(&wrap)?;
    let mut owners = queue
        .list()
        .into_iter()
        .filter(|t| t.execution_runs().last() == Some(&request.run));
    let listed = owners
        .next()
        .context("run has no eligible latest task owner")
        .map_err(&wrap)?;
    if owners.next().is_some() {
        return Err(wrap(anyhow!("run has ambiguous task ownership")));
    }
    if let Some(prior) = &prior
        && prior.queued.id != listed.id
    {
        return Err(anyhow!(
            "uncertain instruction revision receipt: receipt targets task {} but current owner is {}",
            prior.queued.id,
            listed.id
        ));
    }
    let _claim = queue
        .claim_for_instruction_revision(&listed.id)
        .context("task is claimed by a running daemon or another control")
        .map_err(&wrap)?;
    let task = queue.get(&listed.id).map_err(&wrap)?;

    let _owner = crate::pr_head::owner_lock(home, &request.run).map_err(&wrap)?;
    let mut state = RunState::load_under(&request.run, home).map_err(&wrap)?;
    crate::pr_head::ensure_owner(&state).map_err(&wrap)?;
    let adopted = state.instruction_revisions.iter().any(|r| r.request == key);
    if state.instruction_revisions.last().is_some_and(|revision| {
        revision.request != key
            && !task
                .instruction_revision_requests
                .contains(&revision.request)
    }) {
        return Err(wrap(anyhow!(
            "another instruction adoption is interrupted; replay its owner request first"
        )));
    }
    match (&prior, adopted) {
        (None, true) => {
            return Err(anyhow!(
                "uncertain instruction revision state: run already adopted request `{key}` without a receipt; inspect before retrying"
            ));
        }
        (Some(p), false) if p.phase == Phase::Authorized => {
            return Err(anyhow!(
                "uncertain instruction revision receipt: receipt recorded adoption but the run has none for `{key}`; inspect before retrying"
            ));
        }
        _ => {}
    }
    if !adopted {
        verify(home, &request, &task, &state, observer, &wrap).await?;
    } else {
        // The run was adopted before the interruption; only the queue pin is left.
        ensure!(
            task.execution_runs().last() == Some(&state.id)
                && !matches!(task.status, TaskStatus::Running | TaskStatus::Done),
            "run task ownership or queue status changed"
        );
        let claimed = crate::daemon::is_working_on_other(home, &state.id, Timestamp::now())?;
        ensure!(
            state.liveness_under(home, claimed) == Liveness::Dead,
            "run is live or its ownership is unknown"
        );
    }
    let _maintenance = crate::driver::maintenance(home, &state.id).map_err(&wrap)?;

    let pr = state
        .pr
        .as_ref()
        .map(|p| p.url.clone())
        .context("run has no recorded pull request")
        .map_err(&wrap)?;
    let binding = Binding {
        task: serde_json::to_value(&task)
            .map_err(anyhow::Error::from)
            .map_err(&wrap)?,
        instruction: task.instruction.clone(),
        rev: task.instruction_rev,
        head: request.head.clone(),
        pr,
        repair: repair.clone(),
    };

    let reconciled = prior.is_some();
    let mut receipt = if let Some(prior) = prior {
        ensure!(
            prior.binding == binding || adopted && prior.binding.same_operation(&binding),
            "interrupted instruction revision is stale: task, instruction, HEAD or PR changed"
        );
        prior
    } else {
        let mut queued = task.clone();
        if !crate::repair_budget::queue_resumption(queue, &mut queued, &state.id).map_err(&wrap)? {
            queued.release_operator("instruction-revision", None);
        }
        queued.resume_override = Some(OperatorResume {
            question_id: String::new(),
            at: Timestamp::now(),
            conductor_rehold: None,
            forced: true,
            pinned_run: Some(state.id.clone()),
        });
        queued.instruction_revision_requests.push(key.clone());
        let prepared = Receipt {
            request: request.clone(),
            phase: Phase::Prepared,
            binding,
            queued,
            created_at: Timestamp::now(),
            applied_at: None,
        };
        save_receipt(&path, &prepared)?;
        prepared
    };

    if !adopted {
        adopt_into_run(
            &mut state,
            &key,
            &repair,
            &receipt.binding.instruction,
            receipt.binding.rev,
            &receipt.binding.head,
            &receipt.binding.pr,
        );
        state.save_under(home)?;
    }
    revoke_open_approval(&state, &key)?;
    if receipt.phase == Phase::Prepared {
        receipt.phase = Phase::Authorized;
        save_receipt(&path, &receipt)?;
    }

    queue.commit_instruction_revision(&mut receipt.queued, &receipt.binding.task)?;
    receipt.phase = Phase::Applied;
    receipt.applied_at = Some(Timestamp::now());
    save_receipt(&path, &receipt)?;

    Ok(Outcome {
        task: queue.get(&task.id)?,
        repeated: false,
        reconciled,
    })
}

impl Binding {
    /// Same owner request; the task snapshot differs only because adoption
    /// itself never touches the task before the pin commit.
    fn same_operation(&self, other: &Self) -> bool {
        self.instruction == other.instruction
            && self.rev == other.rev
            && self.head == other.head
            && self.pr == other.pr
            && self.repair == other.repair
    }
}

/// An open approval question for the replaced generation can no longer be
/// answered into a merge. Closed or answered questions stay as history; the
/// run's revision record is what makes a queued answer stale.
fn revoke_open_approval(state: &RunState, key: &str) -> Result<()> {
    let Some(revision) = state
        .instruction_revisions
        .iter()
        .find(|r| r.request == key)
    else {
        return Ok(());
    };
    let Some(approval) = &revision.invalidated_approval else {
        return Ok(());
    };
    let store = crate::ask::Questions::open();
    if let Ok(mut question) = store.get_for_effects(&approval.question)
        && question.status == crate::ask::QuestionStatus::Open
    {
        question.abandon("the task instruction was revised; this approval no longer applies");
        store.put(&mut question)?;
    }
    Ok(())
}

/// Prove the run, task, repository, ownership and heads before any write.
async fn verify<O: PrObserver>(
    home: &Path,
    request: &Request,
    task: &Task,
    state: &RunState,
    observer: &O,
    wrap: &impl Fn(anyhow::Error) -> anyhow::Error,
) -> Result<()> {
    (|| -> Result<()> {
        ensure!(
            task.execution_runs().last() == Some(&state.id)
                && task.assignment_accepts(state)
                && !matches!(task.status, TaskStatus::Running | TaskStatus::Done)
                && !task.fresh_start
                && task.review_branch.is_none()
                && task.pr_recovery.is_none(),
            "run task ownership or queue status changed"
        );
        ensure!(
            state
                .origin
                .as_ref()
                .and_then(|o| o.task.as_deref())
                .is_none_or(|owner| owner == task.id),
            "run belongs to another task"
        );
        ensure!(
            task.instruction_rev > state.task_instruction_rev.unwrap_or(0)
                && !task.instruction.trim().is_empty(),
            "task has no newer instruction generation than the retained run"
        );
        let claimed = crate::daemon::is_working_on_other(home, &state.id, Timestamp::now())?;
        ensure!(
            state.liveness_under(home, claimed) == Liveness::Dead,
            "run is live or its ownership is unknown"
        );
        ensure!(
            state.status.resumable()
                && state.released_to.is_none()
                && state.retired_to.is_none()
                && state.pr_taken_over_by.is_none()
                && state.merge_decision.is_none(),
            "run ownership is final or holds an owner stop decision"
        );
        ensure!(
            state.merge_repairs.iter().all(|r| matches!(
                r.phase,
                MergeRepairPhase::Complete | MergeRepairPhase::Failed
            )),
            "a repair is already in flight on this run"
        );
        ensure!(
            state.merge_repairs.len() < state.config.graph.land_rounds
                && state.config.graph.review_rounds > 0,
            "repair generation budget exhausted or review disabled; no instruction revision was adopted"
        );
        Ok(())
    })()
    .map_err(wrap)?;

    let winner = state
        .winner()
        .cloned()
        .context("run has no retained winner")
        .map_err(wrap)?;
    if !git::is_clean(&winner.worktree).await.map_err(wrap)? {
        return Err(wrap(anyhow!("retained worktree has uncommitted changes")));
    }
    let scratch = home.join("runs").join(&state.id).join("rebase");
    if git::checked_rebase_in_progress(&scratch)
        .await
        .map_err(wrap)?
    {
        return Err(wrap(anyhow!(
            "landing rebase is already in progress in scratch worktree"
        )));
    }
    let local = git::rev_parse(&winner.worktree, "HEAD")
        .await
        .map_err(wrap)?;
    let branch = git::rev_parse(&state.repo, &format!("refs/heads/{}", winner.branch))
        .await
        .map_err(wrap)?;
    if local != branch {
        return Err(wrap(anyhow!(
            "retained worktree does not match the winner branch"
        )));
    }
    if !local.eq_ignore_ascii_case(&request.head) {
        return Err(wrap(anyhow!(
            "retained HEAD changed since the owner request (expected {}, actual {local})",
            request.head
        )));
    }
    let pushed = state
        .pr_pushed_head
        .as_deref()
        .context("run has no recorded published PR head")
        .map_err(wrap)?;
    if !pushed.eq_ignore_ascii_case(&local) {
        return Err(wrap(anyhow!(
            "retained HEAD ({local}) does not match recorded published PR head ({pushed})"
        )));
    }
    let record = state
        .pr
        .as_ref()
        .context("run has no recorded pull request")
        .map_err(wrap)?;
    if record.state != "open" {
        return Err(wrap(anyhow!("recorded pull request is not open")));
    }
    let public = state.pr_branch().unwrap_or(&winner.branch).to_owned();
    let remote = git::remote_head(&state.repo, &state.config.merge.remote, &public)
        .await
        .map_err(wrap)?;
    if !remote
        .as_deref()
        .is_some_and(|r| r.eq_ignore_ascii_case(&local))
    {
        return Err(wrap(anyhow!(
            "public branch `{public}` ({}) does not match retained HEAD ({local})",
            remote.as_deref().unwrap_or("missing")
        )));
    }
    let observed = observer
        .observe_pr(&state.repo, &record.url)
        .await
        .map_err(wrap)?;
    (|| -> Result<()> {
        ensure!(observed.open, "pull request is no longer open");
        ensure!(
            observed.url == record.url && observed.number == record.number,
            "observed pull request does not match the run's recorded pull request"
        );
        ensure!(
            observed.head.eq_ignore_ascii_case(&local),
            "published PR head ({}) does not match retained HEAD ({local})",
            observed.head
        );
        if let Some(base) = observed.base_branch.as_deref().filter(|b| !b.is_empty()) {
            ensure!(
                base == state.base_branch,
                "pull request base branch changed (expected {}, observed {base})",
                state.base_branch
            );
        }
        Ok(())
    })()
    .map_err(wrap)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::run::GateRepairE2e;

    #[test]
    fn adoption_revokes_approval_and_verification_but_keeps_history() {
        let mut state = RunState::new(
            PathBuf::from("."),
            "main".into(),
            "abc".into(),
            "use teravars 0.7.0".into(),
            crate::config::Config::default(),
        );
        state.task_instruction = Some("use teravars 0.7.0".into());
        state.land_approval = Some(LandApproval {
            question: "q-old".into(),
            head: "h".into(),
        });
        state.land_armed_head = Some("h".into());
        state.gate_ran = true;
        state.gate_head = Some("h".into());
        state.head_e2e = Some(GateRepairE2e::new("h".into(), true, Vec::new()));

        adopt_into_run(
            &mut state,
            "cli/r",
            "instruction-cli-r",
            "use teravars 0.8.0",
            3,
            "h",
            "https://github.com/o/r/pull/1",
        );

        assert!(state.land_approval.is_none() && state.land_armed_head.is_none());
        assert!(!state.gate_ran && state.gate_head.is_none() && state.head_e2e.is_none());
        assert_eq!(state.verification_history.len(), 1);
        assert!(state.approval_revoked_by_revision("q-old"));
        assert!(!state.approval_revoked_by_revision("q-new"));
        // The fixer and reviewers read these fields.
        assert_eq!(state.instruction, "use teravars 0.8.0");
        assert_eq!(
            state.task_instruction.as_deref(),
            Some("use teravars 0.8.0")
        );
        assert_eq!(state.task_instruction_rev, Some(3));
        let revision = &state.instruction_revisions[0];
        assert_eq!(revision.previous_instruction, "use teravars 0.7.0");
        assert_eq!(state.merge_repairs.len(), 1);
        assert_eq!(state.merge_repairs[0].phase, MergeRepairPhase::Requested);
        assert_eq!(state.merge_repairs[0].gate_head.as_deref(), Some("h"));
    }
}