Skip to main content

magi/
instruction_revision_control.rs

1//! Owner-authorized adoption of a revised task instruction into the retained
2//! run and open pull request that already carry the task.
3//!
4//! The ordinary fences stay as they are: a run whose instruction generation
5//! differs from its task's is not resumable, and `retry` only edits the task.
6//! This operation is the one explicit way across that fence. It is
7//! owner-authenticated (CLI terminal or an explicit chat turn), bound to the
8//! exact retained/public head, and recorded in three durable phases:
9//!
10//! 1. `prepared`: immutable request, task snapshot and head, before any state changes.
11//! 2. `authorized`: the run adopts the instruction generation, files one bounded
12//!    repair request on the same PR and drops every approval and verification
13//!    that belonged to the old generation.
14//! 3. `applied`: the exact-run queue pin and request marker are committed on the task.
15//!
16//! Replaying the same request after an interruption continues from the saved
17//! phase and never adopts twice or grants another repair. The repair itself is
18//! the existing bounded fix-and-re-review path: it spends the run's own
19//! `land_rounds` / `review_rounds` budget, reruns E2E and the gate, and ends
20//! at a fresh head-bound approval question.
21use std::path::{Path, PathBuf};
22
23use anyhow::{Context, Result, anyhow, ensure};
24use jiff::Timestamp;
25use serde::{Deserialize, Serialize};
26
27use crate::{
28    git,
29    land_sync_recovery::{GhPrObserver, PrObserver},
30    queue::{OperatorResume, Queue, Task, TaskStatus},
31    run::{LandApproval, Liveness, MergeRepair, MergeRepairPhase, RunState, RunStatus},
32};
33
34pub use crate::land_sync_recovery_control::BeforeWrite;
35
36fn before_write<T>(result: Result<T>) -> Result<T> {
37    result.map_err(|error| {
38        if error.is::<BeforeWrite>() {
39            error
40        } else {
41            anyhow::Error::new(BeforeWrite(error))
42        }
43    })
44}
45
46/// Validated instruction-adoption request.
47#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
48pub struct Request {
49    /// Full retained run ID.
50    pub run: String,
51    /// Full 40-character HEAD SHA inspected on the retained worktree, recorded
52    /// publication, public branch and open PR.
53    pub head: String,
54    /// Actor namespace (`"cli"` or chat talk ID).
55    pub actor: String,
56    /// Durable idempotency key; reuse only with identical arguments.
57    pub request: String,
58}
59
60/// Result of an adoption request.
61#[derive(Debug, Clone)]
62pub struct Outcome {
63    /// Owning task after admission or idempotent reconciliation.
64    pub task: Task,
65    /// `true` when this exact request had already been applied.
66    pub repeated: bool,
67    /// `true` when an interrupted acceptance was completed.
68    pub reconciled: bool,
69}
70
71/// One adopted instruction generation, kept on the run as history.
72#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
73pub struct Revision {
74    /// `actor/request` key of the owner operation.
75    pub request: String,
76    /// Task instruction generation adopted.
77    pub rev: u64,
78    /// Instruction now handed to fixers and reviewers.
79    pub instruction: String,
80    /// Run instruction before adoption; expired history, never a requirement.
81    pub previous_instruction: String,
82    /// Authored task instruction before adoption.
83    pub previous_task_instruction: Option<String>,
84    /// Task instruction generation before adoption.
85    pub previous_rev: Option<u64>,
86    /// Exact head the repair starts from.
87    pub head: String,
88    /// Question of the repair request filed for this revision.
89    pub repair: String,
90    /// Approval binding that was revoked, if any.
91    pub invalidated_approval: Option<LandApproval>,
92    /// When the run adopted the revision.
93    pub at: Timestamp,
94}
95
96impl RunState {
97    /// Whether `question` carried an approval the owner gave for an
98    /// instruction generation that has since been replaced.
99    pub fn approval_revoked_by_revision(&self, question: &str) -> bool {
100        self.instruction_revisions.iter().any(|r| {
101            r.invalidated_approval
102                .as_ref()
103                .is_some_and(|a| a.question == question)
104        })
105    }
106
107    /// Only the repair bound to the current instruction generation can
108    /// authorize its return to normal landing.
109    pub(crate) fn unfinished_instruction_revision(&self) -> Option<&Revision> {
110        self.instruction_revisions.last().filter(|revision| {
111            !self.merge_repairs.iter().any(|repair| {
112                repair.question == revision.repair && repair.phase == MergeRepairPhase::Complete
113            })
114        })
115    }
116}
117
118#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
119#[serde(rename_all = "snake_case")]
120enum Phase {
121    Prepared,
122    Authorized,
123    Applied,
124}
125
126#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
127struct Binding {
128    task: serde_json::Value,
129    instruction: String,
130    rev: u64,
131    head: String,
132    pr: String,
133    repair: String,
134}
135
136#[derive(Debug, Clone, Serialize, Deserialize)]
137struct Receipt {
138    request: Request,
139    phase: Phase,
140    binding: Binding,
141    queued: Task,
142    created_at: Timestamp,
143    #[serde(default)]
144    applied_at: Option<Timestamp>,
145}
146
147fn save_receipt(path: &Path, receipt: &Receipt) -> Result<()> {
148    let tmp = path.with_extension("tmp");
149    std::fs::write(&tmp, serde_json::to_vec_pretty(receipt)?)?;
150    std::fs::rename(tmp, path)?;
151    Ok(())
152}
153
154/// Receipt path for `request` of `actor` under `home`.
155pub fn receipt_path(home: &Path, actor: &str, request: &str) -> PathBuf {
156    home.join("instruction-revision-controls")
157        .join(actor)
158        .join(format!("{request}.json"))
159}
160
161/// Move `state` onto the revised instruction and file the bounded repair.
162///
163/// Everything that vouched for the old generation stops counting: the approval
164/// binding, the armed-merge record, the head verification and the gate. The
165/// reviews stay, copied into the repair request as immutable history.
166pub fn adopt_into_run(
167    state: &mut RunState,
168    key: &str,
169    repair: &str,
170    instruction: &str,
171    rev: u64,
172    head: &str,
173    pr: &str,
174) {
175    let at = Timestamp::now();
176    state.instruction_revisions.push(Revision {
177        request: key.to_owned(),
178        rev,
179        instruction: instruction.to_owned(),
180        previous_instruction: std::mem::replace(&mut state.instruction, instruction.to_owned()),
181        previous_task_instruction: state.task_instruction.replace(instruction.to_owned()),
182        previous_rev: state.task_instruction_rev.replace(rev),
183        head: head.to_owned(),
184        repair: repair.to_owned(),
185        invalidated_approval: state.land_approval.take(),
186        at,
187    });
188    if let Some(e2e) = state.head_e2e.take() {
189        state
190            .verification_history
191            .push(crate::run::VerificationEvidence {
192                superseded_by: None,
193                archived_at: Some(at),
194                fixes_spent: Some(state.gate_fixes.len()),
195                gate_head: None,
196                gate_ran: false,
197                gate: Vec::new(),
198                e2e: Some(e2e),
199            });
200    }
201    state.merge_repairs.push(MergeRepair {
202        question: repair.to_owned(),
203        head: head.to_owned(),
204        pr: pr.to_owned(),
205        reviews: state.reviews.clone(),
206        gate: state.gate.clone(),
207        gate_head: state.gate_head.clone(),
208        gate_fixes: state.gate_fixes.clone(),
209        pre_gate: state.pre_gate.clone(),
210        phase: MergeRepairPhase::Requested,
211        failure: None,
212    });
213    state.gate_ran = false;
214    state.gate_head = None;
215    state.land_armed_head = None;
216    state.land_reruns = None;
217    state.parked = false;
218    state.status = RunStatus::Landing;
219    state.event(
220        "instruction-revision",
221        format!(
222            "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"
223        ),
224    );
225}
226
227/// Adopt the task's current instruction into its retained run, using `gh pr view`.
228pub async fn adopt(queue: &Queue, home: &Path, request: Request) -> Result<Outcome> {
229    adopt_with(queue, home, request, &GhPrObserver).await
230}
231
232/// [`adopt`] with an injectable PR observer.
233#[allow(clippy::too_many_lines)]
234pub async fn adopt_with<O: PrObserver>(
235    queue: &Queue,
236    home: &Path,
237    mut request: Request,
238    observer: &O,
239) -> Result<Outcome> {
240    before_write((|| -> Result<()> {
241        ensure!(
242            crate::run::is_run_id(&request.run),
243            "instruction adoption needs a full run id"
244        );
245        ensure!(
246            crate::ask::valid_asset_name(&request.actor)
247                && crate::ask::valid_asset_name(&request.request),
248            "actor and request must be safe filenames of at most 64 bytes"
249        );
250        ensure!(
251            request.head.len() == 40 && request.head.bytes().all(|c| c.is_ascii_hexdigit()),
252            "instruction adoption needs a full 40-character HEAD SHA"
253        );
254        Ok(())
255    })())?;
256    request.head = request.head.to_ascii_lowercase();
257
258    let dir = home
259        .join("instruction-revision-controls")
260        .join(&request.actor);
261    before_write(std::fs::create_dir_all(&dir).map_err(Into::into))?;
262    let lock = before_write(
263        std::fs::OpenOptions::new()
264            .write(true)
265            .create(true)
266            .truncate(false)
267            .open(dir.join(format!("{}.lock", request.request)))
268            .map_err(Into::into),
269    )?;
270    before_write(crate::pr_head::try_lock_file(&lock).map_err(Into::into))?;
271
272    let path = receipt_path(home, &request.actor, &request.request);
273    let key = format!("{}/{}", request.actor, request.request);
274    let repair = format!("instruction-{}-{}", request.actor, request.request);
275
276    let prior: Option<Receipt> = if path.exists() {
277        let bytes = std::fs::read(&path).with_context(|| {
278            format!(
279                "uncertain instruction revision receipt: could not read {}; inspect before retrying",
280                path.display()
281            )
282        })?;
283        Some(serde_json::from_slice(&bytes).with_context(|| {
284            format!(
285                "uncertain instruction revision receipt: corrupt JSON in {}; inspect before retrying",
286                path.display()
287            )
288        })?)
289    } else {
290        None
291    };
292
293    if let Some(prior) = &prior {
294        if prior.request != request {
295            return Err(anyhow::Error::new(BeforeWrite(anyhow!(
296                "request ID already binds a different operation"
297            ))));
298        }
299        let task = queue.get(&prior.queued.id).with_context(|| {
300            format!(
301                "uncertain instruction revision receipt: owning task {} unreadable",
302                prior.queued.id
303            )
304        })?;
305        if prior.phase == Phase::Applied {
306            return Ok(Outcome {
307                task,
308                repeated: true,
309                reconciled: false,
310            });
311        }
312        if task.instruction_revision_requests.contains(&key) {
313            let mut completed = prior.clone();
314            completed.phase = Phase::Applied;
315            completed.applied_at = Some(Timestamp::now());
316            save_receipt(&path, &completed)?;
317            return Ok(Outcome {
318                task,
319                repeated: true,
320                reconciled: true,
321            });
322        }
323    }
324
325    let fresh = prior.is_none();
326    let wrap = |err: anyhow::Error| -> anyhow::Error {
327        if fresh {
328            anyhow::Error::new(BeforeWrite(err))
329        } else {
330            err
331        }
332    };
333
334    crate::task_reassign::ensure_current(queue, &request.run).map_err(&wrap)?;
335    let mut owners = queue
336        .list()
337        .into_iter()
338        .filter(|t| t.execution_runs().last() == Some(&request.run));
339    let listed = owners
340        .next()
341        .context("run has no eligible latest task owner")
342        .map_err(&wrap)?;
343    if owners.next().is_some() {
344        return Err(wrap(anyhow!("run has ambiguous task ownership")));
345    }
346    if let Some(prior) = &prior
347        && prior.queued.id != listed.id
348    {
349        return Err(anyhow!(
350            "uncertain instruction revision receipt: receipt targets task {} but current owner is {}",
351            prior.queued.id,
352            listed.id
353        ));
354    }
355    let _claim = queue
356        .claim_for_instruction_revision(&listed.id)
357        .context("task is claimed by a running daemon or another control")
358        .map_err(&wrap)?;
359    let task = queue.get(&listed.id).map_err(&wrap)?;
360
361    let _owner = crate::pr_head::owner_lock(home, &request.run).map_err(&wrap)?;
362    let mut state = RunState::load_under(&request.run, home).map_err(&wrap)?;
363    crate::pr_head::ensure_owner(&state).map_err(&wrap)?;
364    let adopted = state.instruction_revisions.iter().any(|r| r.request == key);
365    if state.instruction_revisions.last().is_some_and(|revision| {
366        revision.request != key
367            && !task
368                .instruction_revision_requests
369                .contains(&revision.request)
370    }) {
371        return Err(wrap(anyhow!(
372            "another instruction adoption is interrupted; replay its owner request first"
373        )));
374    }
375    match (&prior, adopted) {
376        (None, true) => {
377            return Err(anyhow!(
378                "uncertain instruction revision state: run already adopted request `{key}` without a receipt; inspect before retrying"
379            ));
380        }
381        (Some(p), false) if p.phase == Phase::Authorized => {
382            return Err(anyhow!(
383                "uncertain instruction revision receipt: receipt recorded adoption but the run has none for `{key}`; inspect before retrying"
384            ));
385        }
386        _ => {}
387    }
388    if !adopted {
389        verify(home, &request, &task, &state, observer, &wrap).await?;
390    } else {
391        // The run was adopted before the interruption; only the queue pin is left.
392        ensure!(
393            task.execution_runs().last() == Some(&state.id)
394                && !matches!(task.status, TaskStatus::Running | TaskStatus::Done),
395            "run task ownership or queue status changed"
396        );
397        let claimed = crate::daemon::is_working_on_other(home, &state.id, Timestamp::now())?;
398        ensure!(
399            state.liveness_under(home, claimed) == Liveness::Dead,
400            "run is live or its ownership is unknown"
401        );
402    }
403    let _maintenance = crate::driver::maintenance(home, &state.id).map_err(&wrap)?;
404
405    let pr = state
406        .pr
407        .as_ref()
408        .map(|p| p.url.clone())
409        .context("run has no recorded pull request")
410        .map_err(&wrap)?;
411    let binding = Binding {
412        task: serde_json::to_value(&task)
413            .map_err(anyhow::Error::from)
414            .map_err(&wrap)?,
415        instruction: task.instruction.clone(),
416        rev: task.instruction_rev,
417        head: request.head.clone(),
418        pr,
419        repair: repair.clone(),
420    };
421
422    let reconciled = prior.is_some();
423    let mut receipt = if let Some(prior) = prior {
424        ensure!(
425            prior.binding == binding || adopted && prior.binding.same_operation(&binding),
426            "interrupted instruction revision is stale: task, instruction, HEAD or PR changed"
427        );
428        prior
429    } else {
430        let mut queued = task.clone();
431        if !crate::repair_budget::queue_resumption(queue, &mut queued, &state.id).map_err(&wrap)? {
432            queued.release_operator("instruction-revision", None);
433        }
434        queued.resume_override = Some(OperatorResume {
435            question_id: String::new(),
436            at: Timestamp::now(),
437            conductor_rehold: None,
438            forced: true,
439            pinned_run: Some(state.id.clone()),
440        });
441        queued.instruction_revision_requests.push(key.clone());
442        let prepared = Receipt {
443            request: request.clone(),
444            phase: Phase::Prepared,
445            binding,
446            queued,
447            created_at: Timestamp::now(),
448            applied_at: None,
449        };
450        save_receipt(&path, &prepared)?;
451        prepared
452    };
453
454    if !adopted {
455        adopt_into_run(
456            &mut state,
457            &key,
458            &repair,
459            &receipt.binding.instruction,
460            receipt.binding.rev,
461            &receipt.binding.head,
462            &receipt.binding.pr,
463        );
464        state.save_under(home)?;
465    }
466    revoke_open_approval(&state, &key)?;
467    if receipt.phase == Phase::Prepared {
468        receipt.phase = Phase::Authorized;
469        save_receipt(&path, &receipt)?;
470    }
471
472    queue.commit_instruction_revision(&mut receipt.queued, &receipt.binding.task)?;
473    receipt.phase = Phase::Applied;
474    receipt.applied_at = Some(Timestamp::now());
475    save_receipt(&path, &receipt)?;
476
477    Ok(Outcome {
478        task: queue.get(&task.id)?,
479        repeated: false,
480        reconciled,
481    })
482}
483
484impl Binding {
485    /// Same owner request; the task snapshot differs only because adoption
486    /// itself never touches the task before the pin commit.
487    fn same_operation(&self, other: &Self) -> bool {
488        self.instruction == other.instruction
489            && self.rev == other.rev
490            && self.head == other.head
491            && self.pr == other.pr
492            && self.repair == other.repair
493    }
494}
495
496/// An open approval question for the replaced generation can no longer be
497/// answered into a merge. Closed or answered questions stay as history; the
498/// run's revision record is what makes a queued answer stale.
499fn revoke_open_approval(state: &RunState, key: &str) -> Result<()> {
500    let Some(revision) = state
501        .instruction_revisions
502        .iter()
503        .find(|r| r.request == key)
504    else {
505        return Ok(());
506    };
507    let Some(approval) = &revision.invalidated_approval else {
508        return Ok(());
509    };
510    let store = crate::ask::Questions::open();
511    if let Ok(mut question) = store.get_for_effects(&approval.question)
512        && question.status == crate::ask::QuestionStatus::Open
513    {
514        question.abandon("the task instruction was revised; this approval no longer applies");
515        store.put(&mut question)?;
516    }
517    Ok(())
518}
519
520/// Prove the run, task, repository, ownership and heads before any write.
521async fn verify<O: PrObserver>(
522    home: &Path,
523    request: &Request,
524    task: &Task,
525    state: &RunState,
526    observer: &O,
527    wrap: &impl Fn(anyhow::Error) -> anyhow::Error,
528) -> Result<()> {
529    (|| -> Result<()> {
530        ensure!(
531            task.execution_runs().last() == Some(&state.id)
532                && task.assignment_accepts(state)
533                && !matches!(task.status, TaskStatus::Running | TaskStatus::Done)
534                && !task.fresh_start
535                && task.review_branch.is_none()
536                && task.pr_recovery.is_none(),
537            "run task ownership or queue status changed"
538        );
539        ensure!(
540            state
541                .origin
542                .as_ref()
543                .and_then(|o| o.task.as_deref())
544                .is_none_or(|owner| owner == task.id),
545            "run belongs to another task"
546        );
547        ensure!(
548            task.instruction_rev > state.task_instruction_rev.unwrap_or(0)
549                && !task.instruction.trim().is_empty(),
550            "task has no newer instruction generation than the retained run"
551        );
552        let claimed = crate::daemon::is_working_on_other(home, &state.id, Timestamp::now())?;
553        ensure!(
554            state.liveness_under(home, claimed) == Liveness::Dead,
555            "run is live or its ownership is unknown"
556        );
557        ensure!(
558            state.status.resumable()
559                && state.released_to.is_none()
560                && state.retired_to.is_none()
561                && state.pr_taken_over_by.is_none()
562                && state.merge_decision.is_none(),
563            "run ownership is final or holds an owner stop decision"
564        );
565        ensure!(
566            state.merge_repairs.iter().all(|r| matches!(
567                r.phase,
568                MergeRepairPhase::Complete | MergeRepairPhase::Failed
569            )),
570            "a repair is already in flight on this run"
571        );
572        ensure!(
573            state.merge_repairs.len() < state.config.graph.land_rounds
574                && state.config.graph.review_rounds > 0,
575            "repair generation budget exhausted or review disabled; no instruction revision was adopted"
576        );
577        Ok(())
578    })()
579    .map_err(wrap)?;
580
581    let winner = state
582        .winner()
583        .cloned()
584        .context("run has no retained winner")
585        .map_err(wrap)?;
586    if !git::is_clean(&winner.worktree).await.map_err(wrap)? {
587        return Err(wrap(anyhow!("retained worktree has uncommitted changes")));
588    }
589    let scratch = home.join("runs").join(&state.id).join("rebase");
590    if git::checked_rebase_in_progress(&scratch)
591        .await
592        .map_err(wrap)?
593    {
594        return Err(wrap(anyhow!(
595            "landing rebase is already in progress in scratch worktree"
596        )));
597    }
598    let local = git::rev_parse(&winner.worktree, "HEAD")
599        .await
600        .map_err(wrap)?;
601    let branch = git::rev_parse(&state.repo, &format!("refs/heads/{}", winner.branch))
602        .await
603        .map_err(wrap)?;
604    if local != branch {
605        return Err(wrap(anyhow!(
606            "retained worktree does not match the winner branch"
607        )));
608    }
609    if !local.eq_ignore_ascii_case(&request.head) {
610        return Err(wrap(anyhow!(
611            "retained HEAD changed since the owner request (expected {}, actual {local})",
612            request.head
613        )));
614    }
615    let pushed = state
616        .pr_pushed_head
617        .as_deref()
618        .context("run has no recorded published PR head")
619        .map_err(wrap)?;
620    if !pushed.eq_ignore_ascii_case(&local) {
621        return Err(wrap(anyhow!(
622            "retained HEAD ({local}) does not match recorded published PR head ({pushed})"
623        )));
624    }
625    let record = state
626        .pr
627        .as_ref()
628        .context("run has no recorded pull request")
629        .map_err(wrap)?;
630    if record.state != "open" {
631        return Err(wrap(anyhow!("recorded pull request is not open")));
632    }
633    let public = state.pr_branch().unwrap_or(&winner.branch).to_owned();
634    let remote = git::remote_head(&state.repo, &state.config.merge.remote, &public)
635        .await
636        .map_err(wrap)?;
637    if !remote
638        .as_deref()
639        .is_some_and(|r| r.eq_ignore_ascii_case(&local))
640    {
641        return Err(wrap(anyhow!(
642            "public branch `{public}` ({}) does not match retained HEAD ({local})",
643            remote.as_deref().unwrap_or("missing")
644        )));
645    }
646    let observed = observer
647        .observe_pr(&state.repo, &record.url)
648        .await
649        .map_err(wrap)?;
650    (|| -> Result<()> {
651        ensure!(observed.open, "pull request is no longer open");
652        ensure!(
653            observed.url == record.url && observed.number == record.number,
654            "observed pull request does not match the run's recorded pull request"
655        );
656        ensure!(
657            observed.head.eq_ignore_ascii_case(&local),
658            "published PR head ({}) does not match retained HEAD ({local})",
659            observed.head
660        );
661        if let Some(base) = observed.base_branch.as_deref().filter(|b| !b.is_empty()) {
662            ensure!(
663                base == state.base_branch,
664                "pull request base branch changed (expected {}, observed {base})",
665                state.base_branch
666            );
667        }
668        Ok(())
669    })()
670    .map_err(wrap)
671}
672
673#[cfg(test)]
674mod tests {
675    use super::*;
676    use crate::run::GateRepairE2e;
677
678    #[test]
679    fn adoption_revokes_approval_and_verification_but_keeps_history() {
680        let mut state = RunState::new(
681            PathBuf::from("."),
682            "main".into(),
683            "abc".into(),
684            "use teravars 0.7.0".into(),
685            crate::config::Config::default(),
686        );
687        state.task_instruction = Some("use teravars 0.7.0".into());
688        state.land_approval = Some(LandApproval {
689            question: "q-old".into(),
690            head: "h".into(),
691        });
692        state.land_armed_head = Some("h".into());
693        state.gate_ran = true;
694        state.gate_head = Some("h".into());
695        state.head_e2e = Some(GateRepairE2e::new("h".into(), true, Vec::new()));
696
697        adopt_into_run(
698            &mut state,
699            "cli/r",
700            "instruction-cli-r",
701            "use teravars 0.8.0",
702            3,
703            "h",
704            "https://github.com/o/r/pull/1",
705        );
706
707        assert!(state.land_approval.is_none() && state.land_armed_head.is_none());
708        assert!(!state.gate_ran && state.gate_head.is_none() && state.head_e2e.is_none());
709        assert_eq!(state.verification_history.len(), 1);
710        assert!(state.approval_revoked_by_revision("q-old"));
711        assert!(!state.approval_revoked_by_revision("q-new"));
712        // The fixer and reviewers read these fields.
713        assert_eq!(state.instruction, "use teravars 0.8.0");
714        assert_eq!(
715            state.task_instruction.as_deref(),
716            Some("use teravars 0.8.0")
717        );
718        assert_eq!(state.task_instruction_rev, Some(3));
719        let revision = &state.instruction_revisions[0];
720        assert_eq!(revision.previous_instruction, "use teravars 0.7.0");
721        assert_eq!(state.merge_repairs.len(), 1);
722        assert_eq!(state.merge_repairs[0].phase, MergeRepairPhase::Requested);
723        assert_eq!(state.merge_repairs[0].gate_head.as_deref(), Some("h"));
724    }
725}