Skip to main content

magi/
task_completion.rs

1//! Audited task completion and conservative, held-only reopening.
2//!
3//! All operator surfaces share admission checks. Task claims serialize queue
4//! drivers; retained owner/fix/execution locks exclude direct run control until
5//! the admitted task snapshot has been committed. Reopening never alters a run,
6//! public pull request, or attempt budget. Verified completion may supersede
7//! earlier unsuccessful attempts, as automatic settlement does.
8use std::path::Path;
9
10use anyhow::{Context, Result, ensure};
11
12use crate::{
13    queue::{CompletionActor, CompletionContext, Queue, Task, TaskStatus},
14    run::{Liveness, RunState, RunStatus},
15};
16
17/// Locks retained from admission through the caller's durable task commit.
18/// Dropping these guards never changes any run or publication record.
19#[must_use = "keep completion guards alive until the task decision is committed"]
20pub struct CompletionGuards {
21    _fixes: Vec<crate::graph::FixClaim>,
22    _owners: Vec<crate::pr_head::OwnerLock>,
23    _leases: Vec<crate::driver::ExecutionLease>,
24}
25
26/// Statuses that still protect a retained run's work from being reopened into
27/// re-execution. Separate from close admission: `Ready` protects work against
28/// reopen without counting as confirmed landing for closing a change task.
29fn protects_from_reopen(status: RunStatus) -> bool {
30    matches!(
31        status,
32        RunStatus::Ready | RunStatus::Merged | RunStatus::AlreadyInBase
33    )
34}
35
36fn verify_run_belongs_to_task(task: &Task, state: &RunState) -> Result<()> {
37    let owner = state
38        .origin
39        .as_ref()
40        .and_then(|origin| origin.task.as_deref());
41    let same_repo = state.repo == task.repo
42        || state
43            .repo
44            .canonicalize()
45            .ok()
46            .zip(task.repo.canonicalize().ok())
47            .is_some_and(|(run, task)| run == task);
48    let implicit_repo = task.repo.as_os_str().is_empty() || task.repo == Path::new(".");
49    ensure!(
50        state.task_assignment == task.reassignments.len()
51            && owner.is_none_or(|owner| owner == task.id)
52            && (same_repo || (implicit_repo && owner == Some(task.id.as_str())))
53            && task.assignment_accepts(state),
54        "retained run {} does not belong to the task's current repository assignment",
55        state.id
56    );
57    ensure!(
58        crate::daemon::compatible_run_instruction(state, task),
59        "retained run {} does not match the current task instruction",
60        state.id
61    );
62    Ok(())
63}
64
65/// Capture local evidence and enforce synchronous close admission (used by
66/// scheduler/conductor paths that cannot perform forge probes).
67/// Call [`admit_close`] when committing an operator decision; this local helper
68/// alone does not exclude run owners or validate the forge.
69pub fn prepare_close(
70    task: &Task,
71    home: &Path,
72    actor: CompletionActor,
73    reason: Option<String>,
74    discard: bool,
75) -> Result<CompletionContext> {
76    ensure!(
77        task.status != TaskStatus::Running,
78        "task {} is running; stop its driver before closing it",
79        task.id
80    );
81    let mut context = CompletionContext::new(actor, reason, home, task);
82    context.discard = discard;
83    if discard {
84        validate_discard_reason(&context)?;
85        return Ok(context);
86    }
87    if task.investigation {
88        task.validate_investigation_result(None)?;
89        return Ok(context);
90    }
91    let assessment = Assessment::new(&context);
92    let Some(latest_id) = task.execution_runs().last() else {
93        anyhow::bail!(
94            "{}; no landed execution matches the current task; use --discard to explicitly abandon unfinished work",
95            assessment.describe()
96        );
97    };
98    let state = crate::landing::load_run(home, task, latest_id).with_context(|| {
99        format!(
100            "{}; use --discard to explicitly abandon unfinished work",
101            assessment.describe()
102        )
103    })?;
104    ensure!(
105        crate::landing::run_landed_for_settle(&state),
106        "{}; landing is not recorded on the base branch; use `magi task done` to verify landing or --discard to explicitly abandon unfinished work",
107        assessment.describe()
108    );
109    Ok(context)
110}
111
112struct Assessment<'a> {
113    run: Option<&'a crate::queue::CompletionRunSnapshot>,
114}
115
116impl<'a> Assessment<'a> {
117    fn new(context: &'a CompletionContext) -> Self {
118        Self {
119            run: context.run.as_ref(),
120        }
121    }
122
123    fn describe(&self) -> String {
124        let Some(run) = self.run else {
125            return "no retained run".into();
126        };
127        let mut text = format!(
128            "run {} {}; PR {} {}; head {}; branches {}",
129            run.id,
130            run.status.map_or("unknown", RunStatus::as_str),
131            run.pr_url.as_deref().unwrap_or("none"),
132            run.pr_state.as_deref().unwrap_or("none"),
133            run.pr_head.as_deref().unwrap_or("unknown"),
134            run.branches.join(", ")
135        );
136        if let Some(error) = &run.error {
137            text.push_str(&format!("; snapshot error: {error}"));
138        }
139        text
140    }
141}
142
143fn validate_discard_reason(context: &CompletionContext) -> Result<()> {
144    ensure!(
145        !context.discard
146            || context
147                .reason
148                .as_deref()
149                .is_some_and(|reason| !reason.trim().is_empty()),
150        "--discard requires a non-empty reason"
151    );
152    Ok(())
153}
154
155async fn guard_runs(
156    task: &Task,
157    home: &Path,
158    reopening: bool,
159    discard: bool,
160) -> Result<(CompletionGuards, Option<RunState>, Vec<String>)> {
161    let mut guards = CompletionGuards {
162        _fixes: Vec::new(),
163        _owners: Vec::new(),
164        _leases: Vec::new(),
165    };
166    let mut latest = None;
167    let mut unavailable = Vec::new();
168    let ids: std::collections::BTreeSet<_> = task
169        .runs
170        .iter()
171        .chain(task.startup_failures.iter().map(|failure| &failure.run))
172        .collect();
173    for id in ids {
174        if !discard {
175            RunState::load_under(id, home).with_context(|| {
176                format!(
177                    "cannot verify retained run {id}; its outcome is unknown{}",
178                    if reopening {
179                        ""
180                    } else {
181                        "; use --discard to explicitly abandon unfinished work"
182                    }
183                )
184            })?;
185        }
186        guards._fixes.push(
187            crate::graph::FixClaim::acquire(&home.join("runs").join(id))
188                .with_context(|| format!("run {id} targeted fix is active or unknown"))?,
189        );
190        guards._owners.push(
191            crate::pr_head::owner_lock(home, id)
192                .with_context(|| format!("run {id} ownership is busy"))?,
193        );
194        let mut state = match RunState::load_under(id, home) {
195            Ok(state) => state,
196            Err(error) if discard => {
197                unavailable.push(format!("run {id}: outcome unknown: {error:#}"));
198                guards._leases.push(
199                    crate::driver::maintenance(home, id)
200                        .with_context(|| format!("run {id} execution is busy or unknown"))?,
201                );
202                continue;
203            }
204            Err(error) => {
205                return Err(error).with_context(|| {
206                    format!("cannot verify retained run {id}; its outcome is unknown")
207                });
208            }
209        };
210        let claims = crate::daemon::is_working_on(home, id, jiff::Timestamp::now());
211        ensure!(
212            state.liveness_under(home, claims) == Liveness::Dead,
213            "run {id} driver is live or unknown; stop it before changing task completion"
214        );
215        ensure!(
216            state.active.is_empty(),
217            "run {id} retains active seats or commands; finish process cleanup first"
218        );
219        guards._leases.push(
220            crate::driver::maintenance(home, id)
221                .with_context(|| format!("run {id} execution is busy or unknown"))?,
222        );
223        if reopening {
224            ensure!(
225                !protects_from_reopen(state.status),
226                "cannot reopen: retained run {id} is {} (PR {}, state {}); completed work must not execute again",
227                state.status.as_str(),
228                state.pr.as_ref().map_or("none", |pr| pr.url.as_str()),
229                state.pr.as_ref().map_or("none", |pr| pr.state.as_str())
230            );
231            ensure!(
232                !state.pr_publication_pending && !state.land_sync_pending,
233                "cannot reopen: run {id} has unresolved publication/synchronization evidence"
234            );
235            ensure!(
236                !state.pr.as_ref().is_some_and(|pr| pr.state == "merged")
237                    && state.pr_merged_head.is_none(),
238                "cannot reopen: run {id} retains merged public PR evidence"
239            );
240        }
241        if let Some(pr) = &mut state.pr
242            && !discard
243        {
244            let lifecycle = crate::land::lifecycle(&state.repo, &pr.url)
245                .await
246                .with_context(|| {
247                    format!(
248                        "run {id} PR {} forge state is unknown; no task decision was saved",
249                        pr.url
250                    )
251                })?;
252            ensure!(
253                !reopening || lifecycle != crate::land::PrLifecycle::Merged,
254                "cannot reopen: run {id} PR {} is merged on the forge",
255                pr.url
256            );
257            pr.state = lifecycle.as_str().to_owned();
258        }
259        if reopening {
260            let merged = crate::land::find_external_merge_for_reopen(&state)
261                .await
262                .with_context(|| format!("run {id} public merge evidence is unknown"))?;
263            ensure!(
264                merged.is_none(),
265                "cannot reopen: run {id} has a merged public PR {}",
266                merged.as_ref().map_or("unknown", |pr| pr.url.as_str())
267            );
268        }
269        if task.runs.last() == Some(id) {
270            latest = Some(state);
271        }
272    }
273    Ok((guards, latest, unavailable))
274}
275
276/// Admit a close while the caller holds its task claim.
277/// Keep the returned guards until the local-decision receipt and task save are
278/// durable. Chat control uses this to commit its receipt and completion together.
279pub async fn admit_close(
280    task: &Task,
281    home: &Path,
282    actor: CompletionActor,
283    reason: Option<String>,
284    result: Option<String>,
285    discard: bool,
286) -> Result<(CompletionGuards, CompletionContext)> {
287    ensure!(
288        task.status != TaskStatus::Running,
289        "task {} is running; stop its driver before closing it",
290        task.id
291    );
292    if discard {
293        ensure!(
294            reason.as_deref().is_some_and(|r| !r.trim().is_empty()),
295            "--discard requires a non-empty reason"
296        );
297    } else if task.investigation {
298        task.validate_investigation_result(result.as_deref())?;
299    } else {
300        ensure!(
301            result.is_none(),
302            "--result is only for investigation tasks; use --reason to explain closing a change task"
303        );
304    }
305    let (guards, latest, unavailable) = guard_runs(task, home, false, discard).await?;
306    let mut context = match &latest {
307        Some(state) => CompletionContext::from_run(actor, reason, task, state),
308        None => CompletionContext::new(actor, reason, home, task),
309    };
310    context.discard = discard;
311    context.unavailable_runs = unavailable;
312    validate_discard_reason(&context)?;
313    if !discard && !task.investigation {
314        let assessment = Assessment::new(&context);
315        let Some(latest_id) = task.execution_runs().last() else {
316            anyhow::bail!(
317                "{}; no landed execution matches the current task; use --discard to explicitly abandon unfinished work",
318                assessment.describe()
319            );
320        };
321        let Some(state) = latest.as_ref().filter(|state| state.id == *latest_id) else {
322            anyhow::bail!(
323                "{}; retained run {latest_id} could not be verified; use --discard to explicitly abandon unfinished work",
324                assessment.describe()
325            );
326        };
327        verify_run_belongs_to_task(task, state).with_context(|| {
328            format!(
329                "{}; use --discard to explicitly abandon unfinished work",
330                assessment.describe()
331            )
332        })?;
333        let (verdict, why) =
334            crate::landing::verdict(state, crate::landing::Limits::default()).await;
335        if verdict != crate::landing::State::Landed {
336            anyhow::bail!(
337                "{}; landing not confirmed ({why}); use --discard to explicitly abandon unfinished work",
338                assessment.describe()
339            );
340        }
341    }
342    Ok((guards, context))
343}
344
345/// Mark an idle task done with one immutable completion occurrence.
346/// Already-done requests are idempotent and never create another notice.
347pub async fn close(
348    queue: &Queue,
349    home: &Path,
350    reference: &str,
351    actor: CompletionActor,
352    reason: Option<String>,
353    discard: bool,
354) -> Result<Task> {
355    close_with_result(queue, home, reference, actor, reason, None, discard).await
356}
357
358/// Mark an idle task done, optionally recording investigation findings (`result`).
359pub async fn close_with_result(
360    queue: &Queue,
361    home: &Path,
362    reference: &str,
363    actor: CompletionActor,
364    reason: Option<String>,
365    result: Option<String>,
366    discard: bool,
367) -> Result<Task> {
368    let id = queue.resolve_id(reference)?;
369    let claim = queue
370        .claim(&id)
371        .context("task is claimed; wait for its driver to stop")?;
372    let task = queue.get(&id)?;
373    close_claimed(queue, home, (claim, task), actor, reason, result, discard).await
374}
375
376pub(crate) async fn close_claimed(
377    queue: &Queue,
378    home: &Path,
379    (_claim, mut task): (crate::queue::Claim, Task),
380    actor: CompletionActor,
381    reason: Option<String>,
382    result: Option<String>,
383    discard: bool,
384) -> Result<Task> {
385    if task.status == TaskStatus::Done
386        && (!task.investigation
387            || discard
388            || (result.is_none() && task.current_investigation_result().is_some()))
389    {
390        return Ok(task);
391    }
392    let expected = task.clone();
393    let (_guards, context) =
394        admit_close(&task, home, actor, reason, result.clone(), discard).await?;
395    if !discard && task.investigation {
396        task.record_investigation_result(result.as_deref())?;
397    }
398    task.succeed(context);
399    queue.commit_completion(&mut task, &expected)?;
400    if !discard && expected.status != TaskStatus::Done {
401        crate::daemon::supersede_prior_runs(&task, home);
402    }
403    Ok(task)
404}
405
406/// Admit a held-only reopen while the caller holds the task claim.
407/// Keep the returned guards through the atomic task/decision-receipt save.
408pub async fn admit_reopen(
409    task: &Task,
410    home: &Path,
411    actor: CompletionActor,
412    reason: &str,
413) -> Result<(CompletionGuards, CompletionContext)> {
414    ensure!(
415        !reason.trim().is_empty(),
416        "reopen requires a non-empty reason"
417    );
418    ensure!(
419        task.status == TaskStatus::Done,
420        "only a done task can be reopened (currently {})",
421        task.status.as_str()
422    );
423    let (guards, latest, _) = guard_runs(task, home, true, false).await?;
424    let reason = Some(reason.to_owned());
425    let context = match latest {
426        Some(state) => CompletionContext::from_run(actor, reason, task, &state),
427        None => CompletionContext::new(actor, reason, home, task),
428    };
429    Ok((guards, context))
430}
431/// Reopen a completed task into an explicit operator hold, never into execution.
432/// Every retained run is checked, even runs from older repository assignments.
433pub async fn reopen(
434    queue: &Queue,
435    home: &Path,
436    reference: &str,
437    actor: CompletionActor,
438    reason: &str,
439) -> Result<Task> {
440    let id = queue.resolve_id(reference)?;
441    let claim = queue
442        .claim(&id)
443        .context("task is claimed; wait for its driver to stop")?;
444    reopen_claimed(queue, home, (claim, queue.get(&id)?), actor, reason).await
445}
446
447pub(crate) async fn reopen_claimed(
448    queue: &Queue,
449    home: &Path,
450    (_claim, mut task): (crate::queue::Claim, Task),
451    actor: CompletionActor,
452    reason: &str,
453) -> Result<Task> {
454    let expected = task.clone();
455    let (_guards, context) = admit_reopen(&task, home, actor, reason).await?;
456    task.reopen(context)?;
457    queue.commit_completion(&mut task, &expected)?;
458    Ok(task)
459}
460
461/// Human-readable audit and run/PR evidence for CLI and chat responses.
462pub fn describe(task: &Task) -> String {
463    let Some(event) = task.completion_history.last() else {
464        return format!(
465            "task {}: {} (legacy completion; actor and run evidence unknown)",
466            task.id,
467            task.status.as_str()
468        );
469    };
470    let mut text = format!(
471        "task {}: {}; occurrence {}; {:?} by {:?} at {}; prior {}; discard {}",
472        task.id,
473        task.status.as_str(),
474        event.occurrence,
475        event.action,
476        event.actor,
477        event.at,
478        event.prior_status.as_str(),
479        event.discard
480    );
481    if let Some(reason) = &event.reason {
482        text.push_str(&format!("; reason: {reason}"));
483    }
484    for (label, value) in [
485        ("prior hold", &event.prior_hold_reason),
486        ("prior dependency", &event.prior_block_reason),
487        ("prior error", &event.prior_error),
488    ] {
489        if let Some(value) = value {
490            text.push_str(&format!("; {label}: {value}"));
491        }
492    }
493    text.push_str("; ");
494    text.push_str(
495        &Assessment {
496            run: event.run.as_ref(),
497        }
498        .describe(),
499    );
500    for error in &event.unavailable_runs {
501        text.push_str(&format!("; unavailable retained evidence: {error}"));
502    }
503    text
504}
505
506#[cfg(test)]
507mod tests {
508    use super::*;
509    use crate::queue::{CompletionAction, Source};
510
511    fn task() -> Task {
512        Task::new(
513            "audit".into(),
514            "do the work".into(),
515            "repo".into(),
516            Source::Human,
517        )
518    }
519
520    fn retained(home: &Path, task: &mut Task, status: RunStatus) -> RunState {
521        let mut run = RunState::new(
522            "repo".into(),
523            "main".into(),
524            "base".into(),
525            "work".into(),
526            crate::config::Config::default(),
527        );
528        run.status = status;
529        run.save_under(home).unwrap();
530        task.link_run(&run.id);
531        run
532    }
533
534    #[tokio::test]
535    async fn legacy_completion_reopens_then_pins_the_same_run_checkpoint() {
536        let dir = tempfile::tempdir().unwrap();
537        let queue = Queue::at(dir.path().join("queue"));
538        let mut task = task();
539        let mut run = retained(dir.path(), &mut task, RunStatus::Blocked);
540        run.candidates.push(crate::run::Candidate {
541            index: 0,
542            label: 'A',
543            agent: "implementer".into(),
544            branch: "retained-candidate-A".into(),
545            worktree: dir.path().join("worktree-A"),
546            summary: "retained implementation".into(),
547            stat: String::new(),
548            files: 1,
549            commits: 1,
550            empty: false,
551            failed: None,
552            verified_noop: None,
553            duration_ms: 0,
554            folded: false,
555        });
556        run.gate_head = Some("retained-checkpoint".into());
557        run.gate_ran = true;
558        run.save_under(dir.path()).unwrap();
559        let before = serde_json::to_value(&run).unwrap();
560        // Legacy Done has no event. Do not fabricate a historical actor.
561        task.status = TaskStatus::Done;
562        task.attempts = 2;
563        queue.put(&mut task).unwrap();
564        let mut raw = serde_json::to_value(&task).unwrap();
565        raw.as_object_mut().unwrap().remove("completion_history");
566        std::fs::write(queue.path_of(&task.id), serde_json::to_vec(&raw).unwrap()).unwrap();
567        let held = reopen(
568            &queue,
569            dir.path(),
570            &task.id,
571            CompletionActor::Cli,
572            "inspect the old close",
573        )
574        .await
575        .unwrap();
576        assert_eq!(held.status, TaskStatus::Held);
577        assert_eq!(held.completion_history.len(), 1);
578        assert_eq!(held.completion_history[0].action, CompletionAction::Reopen);
579        assert_eq!(held.completion_history[0].prior_status, TaskStatus::Done);
580        assert_eq!(held.runs, vec![run.id.clone()]);
581        assert_eq!(held.attempts, 2);
582        assert_eq!(
583            held.completion_history[0].run.as_ref().unwrap().branches,
584            vec!["retained-candidate-A"]
585        );
586        assert!(crate::resume::pin_queued(&queue, &run.id, None, None).unwrap());
587        let queued = queue.get(&task.id).unwrap();
588        assert_eq!(queued.status, TaskStatus::Queued);
589        assert_eq!(queued.runs, held.runs);
590        assert_eq!(
591            queued.resume_override.unwrap().pinned_run.as_deref(),
592            Some(run.id.as_str())
593        );
594        assert_eq!(
595            serde_json::to_value(RunState::load_under(&run.id, dir.path()).unwrap()).unwrap(),
596            before
597        );
598    }
599
600    #[tokio::test]
601    async fn owner_and_execution_locks_are_retained_until_the_task_commit() {
602        let dir = tempfile::tempdir().unwrap();
603        let queue = Queue::at(dir.path().join("queue"));
604        let mut task = task();
605        let run = retained(dir.path(), &mut task, RunStatus::Blocked);
606        queue.put(&mut task).unwrap();
607        let claim = queue.claim(&task.id).unwrap();
608        let expected = queue.get(&task.id).unwrap();
609        let (guards, context) = admit_close(
610            &task,
611            dir.path(),
612            CompletionActor::Cli,
613            Some("discard unfinished work".into()),
614            None,
615            true,
616        )
617        .await
618        .unwrap();
619        assert!(crate::pr_head::owner_lock(dir.path(), &run.id).is_err());
620        assert!(crate::driver::maintenance(dir.path(), &run.id).is_err());
621        task.succeed(context);
622        queue.commit_completion(&mut task, &expected).unwrap();
623        assert!(crate::pr_head::owner_lock(dir.path(), &run.id).is_err());
624        drop(guards);
625        drop(claim);
626        assert!(crate::pr_head::owner_lock(dir.path(), &run.id).is_ok());
627        assert!(crate::driver::maintenance(dir.path(), &run.id).is_ok());
628    }
629
630    #[tokio::test]
631    async fn discard_retains_locks_even_when_run_evidence_is_unreadable() {
632        let dir = tempfile::tempdir().unwrap();
633        let mut task = task();
634        let run = retained(dir.path(), &mut task, RunStatus::Blocked);
635        std::fs::write(dir.path().join("runs").join(&run.id).join("run.json"), "{").unwrap();
636        let owner = crate::pr_head::owner_lock(dir.path(), &run.id).unwrap();
637        assert!(
638            admit_close(
639                &task,
640                dir.path(),
641                CompletionActor::Cli,
642                Some("discard".into()),
643                None,
644                true
645            )
646            .await
647            .is_err()
648        );
649        drop(owner);
650        let execution = crate::driver::maintenance(dir.path(), &run.id).unwrap();
651        assert!(
652            admit_close(
653                &task,
654                dir.path(),
655                CompletionActor::Cli,
656                Some("discard".into()),
657                None,
658                true
659            )
660            .await
661            .is_err()
662        );
663        drop(execution);
664        let (guards, context) = admit_close(
665            &task,
666            dir.path(),
667            CompletionActor::Cli,
668            Some("discard".into()),
669            None,
670            true,
671        )
672        .await
673        .unwrap();
674        assert!(
675            context
676                .unavailable_runs
677                .iter()
678                .any(|error| error.contains(&run.id))
679        );
680        assert!(crate::pr_head::owner_lock(dir.path(), &run.id).is_err());
681        assert!(crate::driver::maintenance(dir.path(), &run.id).is_err());
682        drop(guards);
683        assert!(crate::pr_head::owner_lock(dir.path(), &run.id).is_ok());
684        assert!(crate::driver::maintenance(dir.path(), &run.id).is_ok());
685    }
686
687    #[cfg(unix)]
688    #[tokio::test]
689    async fn forge_merge_and_unknown_forge_are_checked_before_task_changes() {
690        if !crate::standalone_test(
691            "task_completion::tests::forge_merge_and_unknown_forge_are_checked_before_task_changes",
692        ) {
693            return;
694        }
695        use std::os::unix::fs::PermissionsExt as _;
696        let dir = tempfile::tempdir().unwrap();
697        let bin = dir.path().join("bin");
698        std::fs::create_dir(&bin).unwrap();
699        let gh = bin.join("gh");
700        std::fs::write(&gh, "#!/bin/sh\nprintf '%s\\n' '{\"state\":\"MERGED\"}'\n").unwrap();
701        std::fs::set_permissions(&gh, std::fs::Permissions::from_mode(0o755)).unwrap();
702        let mut paths = vec![bin];
703        paths.extend(std::env::split_paths(
704            &std::env::var_os("PATH").unwrap_or_default(),
705        ));
706        // This fixture runs alone in a dedicated process, not alongside tests
707        // or agents that could read a concurrently changing environment.
708        unsafe {
709            std::env::set_var("PATH", std::env::join_paths(paths).unwrap());
710        }
711        let queue = Queue::at(dir.path().join("queue"));
712        let mut task = task();
713        task.repo = dir.path().to_owned();
714        let mut run = retained(dir.path(), &mut task, RunStatus::Blocked);
715        run.repo = dir.path().to_owned();
716        run.task_instruction = Some(task.instruction.clone());
717        run.task_instruction_rev = Some(task.instruction_rev);
718        run.pr_head = Some("magi/task-replacement".into());
719        run.pr = Some(crate::run::PrRecord {
720            url: "https://example.invalid/pull/1".into(),
721            number: 1,
722            state: "open".into(),
723            checks: "red".into(),
724            round: 1,
725            rounds: 1,
726            red_at_merge: Vec::new(),
727        });
728        run.save_under(dir.path()).unwrap();
729        queue.put(&mut task).unwrap();
730        // Lifecycle alone cannot establish the target base or exact head.
731        let error = close(
732            &queue,
733            dir.path(),
734            &task.id,
735            CompletionActor::Cli,
736            None,
737            false,
738        )
739        .await
740        .unwrap_err();
741        assert!(
742            error.to_string().contains("landing not confirmed"),
743            "{error:#}"
744        );
745        assert_eq!(queue.get(&task.id).unwrap().status, task.status);
746        // Seed a historical Done record to exercise the independent reopen guard.
747        task.status = TaskStatus::Done;
748        queue.put(&mut task).unwrap();
749        let done = queue.get(&task.id).unwrap();
750        let error = reopen(&queue, dir.path(), &task.id, CompletionActor::Cli, "retry")
751            .await
752            .unwrap_err();
753        assert!(
754            error.to_string().contains("merged on the forge"),
755            "{error:#}"
756        );
757        std::fs::write(
758            &gh,
759            r#"#!/bin/sh
760case "$2" in
761view) printf '%s\n' '{"state":"CLOSED"}' ;;
762list)
763    [ "$3" = '--head' ] && [ "$4" = 'magi/task-replacement' ] || exit 1
764    printf '%s\n' '[{"url":"https://example.invalid/pull/2","number":2,"mergedAt":"2099-01-01T00:00:00Z","baseRefName":"main"}]'
765    ;;
766*) exit 1 ;;
767esac
768"#,
769        )
770        .unwrap();
771        let error = reopen(&queue, dir.path(), &task.id, CompletionActor::Cli, "retry")
772            .await
773            .unwrap_err();
774        assert!(
775            error
776                .to_string()
777                .contains("merged public PR https://example.invalid/pull/2"),
778            "{error:#}"
779        );
780        assert_eq!(queue.get(&task.id).unwrap().status, TaskStatus::Done);
781        std::fs::write(
782            &gh,
783            "#!/bin/sh\nprintf '%s\\n' 'forge unavailable' >&2\nexit 1\n",
784        )
785        .unwrap();
786        let error = reopen(&queue, dir.path(), &task.id, CompletionActor::Cli, "retry")
787            .await
788            .unwrap_err();
789        assert!(error.to_string().contains("unknown"), "{error:#}");
790        assert_eq!(
791            queue.get(&task.id).unwrap().completion_history,
792            done.completion_history
793        );
794        assert_eq!(
795            RunState::load_under(&run.id, dir.path())
796                .unwrap()
797                .pr
798                .unwrap()
799                .state,
800            "open"
801        );
802    }
803}