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