Skip to main content

magi/
head_e2e_stop.rs

1//! Typed stop identity, change detection, and single-use owner approval for
2//! conclusive current-head `verify.e2e` failures (`RunState::head_e2e`).
3//!
4//! `graph::verify_current_head` correctly refuses to treat a recorded red
5//! `head_e2e` as green on an unchanged candidate SHA. This module stops
6//! automatic queue settlement, dispatch, conductor, triage, standing chat,
7//! and notifications from re-running or re-paging the same unchanged failure
8//! while still permitting changed facts, fresh repair evidence, and explicit
9//! one-shot owner approvals.
10use std::fmt::Write as _;
11use std::path::Path;
12
13use jiff::Timestamp;
14use serde::{Deserialize, Serialize};
15use sha2::{Digest, Sha256};
16
17use crate::proc::Quiet as _;
18use crate::queue::{HoldSource, Queue, Task, TaskStatus};
19use crate::run::{CommandOutcome, MergeRepairPhase, RunState, RunStatus};
20
21fn short(commit: &str) -> String {
22    commit.chars().take(7).collect()
23}
24
25/// Notice stage recorded in [`crate::queue::NoticeCause::stage`] for a
26/// conclusive `head_e2e` hold.
27pub const NOTICE_STAGE: &str = "head-e2e-stop";
28
29/// Stable identity of a conclusive current-head `verify.e2e` failure.
30///
31/// `id` hashes only the durable failure facts (`run`, `head`, `base`,
32/// `generation`, and the command/result fingerprint). Pass index, wall-clock
33/// timestamps, command duration, and rendered prose are deliberately excluded.
34#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
35pub struct Stop {
36    /// Stable stop identifier (`head-e2e:<hex>`).
37    pub id: String,
38    /// Run that recorded this failure.
39    pub run: String,
40    /// Exact candidate HEAD that failed `verify.e2e`.
41    pub head: String,
42    /// Base SHA (`<remote>/<base>`) observed when the failure was recorded.
43    pub base: String,
44    /// Verification history generation at the time this result was recorded.
45    pub generation: usize,
46    /// SHA-256 digest of the failing command sequence and results (excluding duration).
47    pub evidence: String,
48    /// Timestamp when the verification result was recorded (not part of `id`).
49    #[serde(default, skip_serializing_if = "Option::is_none")]
50    pub recorded_at: Option<Timestamp>,
51    /// Run pass index that actually executed the verification (not part of `id`).
52    #[serde(default, skip_serializing_if = "Option::is_none")]
53    pub recorded_pass: Option<usize>,
54    /// Number of events in `RunState::events` right after recording this failure (not part of `id`).
55    #[serde(default, skip_serializing_if = "Option::is_none")]
56    pub recorded_events: Option<usize>,
57    /// Task `resumption.generation` active when the recording pass began (not part of `id`).
58    #[serde(default, skip_serializing_if = "Option::is_none")]
59    pub resumption_generation: Option<u64>,
60}
61
62/// One explicit owner release/resume approval consumed against a `head_e2e` stop.
63///
64/// Persisted on [`RunState::head_e2e_resumptions`] before executing the pass so
65/// restarts and automatic retries can never reuse the same approval.
66#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
67pub struct Resumption {
68    /// Owning task id.
69    pub task: String,
70    /// Stop id that this approval authorized one retry against.
71    pub stop_id: String,
72    /// Consumed [`crate::queue::Resumption::generation`].
73    pub generation: u64,
74    /// Timestamp of the consumed approval.
75    pub approval_at: Timestamp,
76}
77
78/// Result of checking whether candidate/base/repair facts changed since [`Stop`].
79#[derive(Debug, Clone, PartialEq, Eq)]
80pub(crate) enum FactCheck {
81    /// Candidate HEAD, remote base SHA, and repair inputs all match the stop.
82    Unchanged,
83    /// At least one material fact changed, permitting existing recovery paths.
84    Changed(String),
85    /// One or more Git references could not be read; never treated as a change.
86    Unreadable(String),
87}
88
89/// Action required when holding a task for a conclusive `head_e2e` stop.
90#[derive(Debug, Clone)]
91pub(crate) struct HoldAction {
92    pub(crate) stop: Stop,
93    pub(crate) reason: String,
94    pub(crate) detail: String,
95    pub(crate) diagnostic: Option<String>,
96}
97
98impl HoldAction {
99    /// Apply this hold to `task` without resetting `attempts` or erasing history.
100    pub(crate) fn apply(&self, task: &mut Task) {
101        let existing_diagnostic = task.diagnostic.clone();
102        task.hold_head_e2e(self.stop.clone(), self.reason.clone(), self.detail.clone());
103        task.head_e2e_notice(&self.stop);
104        task.diagnostic = self.diagnostic.clone().or(existing_diagnostic);
105    }
106}
107
108/// Pre-attempt gate decision for a task whose latest run has a conclusive `head_e2e` stop.
109#[derive(Debug, Clone)]
110pub(crate) enum AttemptGate {
111    /// Hold the task immediately without starting a pass or charging an attempt.
112    Hold(HoldAction),
113    /// Permit this run once under an explicit, unconsumed owner approval.
114    ConsumeOwnerApproval {
115        run: String,
116        stop_id: String,
117        generation: u64,
118        approval_at: Timestamp,
119    },
120}
121
122/// How held-task triage should classify a `Held` task with respect to `head_e2e`.
123#[derive(Debug, Clone, Copy, PartialEq, Eq)]
124pub(crate) enum TriageStatus {
125    /// Not a `head_e2e` machine hold; ordinary triage rules apply.
126    NotHeadE2e,
127    /// Conclusive `head_e2e` stop still stands (unchanged or unreadable); keep held quietly.
128    HoldStillActive,
129    /// Candidate HEAD, remote base, or repair evidence changed; safe to resume without resetting attempts.
130    ResolvedChanged,
131}
132
133fn sha256_hex(bytes: &[u8]) -> String {
134    let mut out = String::with_capacity(64);
135    for byte in Sha256::digest(bytes) {
136        let _ = write!(&mut out, "{byte:02x}");
137    }
138    out
139}
140
141fn outcomes_fingerprint(outcomes: &[CommandOutcome]) -> String {
142    let normalized: Vec<_> = outcomes
143        .iter()
144        .map(|o| (&o.command, o.code, o.resource_blocked, &o.output_tail))
145        .collect();
146    let bytes = serde_json::to_vec(&normalized).unwrap_or_default();
147    sha256_hex(&bytes)
148}
149
150/// Extract a conclusive `head_e2e` stop from `state`, if and only if every
151/// strict conclusiveness condition holds.
152///
153/// Returns `None` for inconclusive/resource-blocked verification, empty
154/// outcomes, parked runs, base-sync/prep/merge/gate failures, transferred
155/// ownership, or active repair grants/merge repairs.
156pub fn conclusive(state: &RunState) -> Option<Stop> {
157    if state.status != RunStatus::Blocked
158        || state.parked
159        || state.resource_block.is_some()
160        || state.base_sync_blocked()
161        || state.prep_failure.is_some()
162        || state.merge_decision.is_some()
163        || state.land_unrelated.is_some()
164        || state.land_approval.is_some()
165        || state.pr.is_some()
166        || state.pr_publication_pending
167        || state.github_text.as_ref().is_some_and(|g| !g.resolved)
168        || state.released_to.is_some()
169        || state.retired_to.is_some()
170        || state.pr_taken_over_by.is_some()
171        || state
172            .merge_repairs
173            .last()
174            .is_some_and(|r| r.phase != MergeRepairPhase::Complete)
175        || state
176            .repair_grants
177            .last()
178            .is_some_and(|g| g.phase != crate::repair_budget::Phase::Complete)
179        || state.winner().is_none()
180        || crate::graph::review_conclusion(&state.reviews, state.config.graph.review_rounds)
181            != Some(RunStatus::Gating)
182        || (state.gate_ran && state.gate.iter().any(|o| !o.ok()))
183    {
184        return None;
185    }
186
187    let e2e = state.head_e2e.as_ref()?;
188    if e2e.head.is_empty()
189        || e2e.passed
190        || e2e.outcomes.is_empty()
191        || e2e.outcomes.iter().any(|o| o.resource_blocked)
192        || !e2e.outcomes.iter().any(|o| !o.ok())
193    {
194        return None;
195    }
196
197    // Legacy records lack the verification base. Use the run's starting base,
198    // not the mutable synchronization tip, to keep their stop identity stable.
199    let base = e2e
200        .base_commit
201        .as_deref()
202        .filter(|s| !s.is_empty())
203        .unwrap_or(&state.base_commit)
204        .to_owned();
205    let generation = e2e.generation.unwrap_or(state.verification_history.len());
206    let evidence = outcomes_fingerprint(&e2e.outcomes);
207    let id_input = serde_json::to_vec(&(&state.id, &e2e.head, &base, generation, &evidence))
208        .unwrap_or_default();
209    let id = format!("head-e2e:{}", &sha256_hex(&id_input)[..32]);
210    let recorded_at = e2e
211        .recorded_at
212        .or_else(|| {
213            state
214                .events
215                .iter()
216                .rev()
217                .find(|ev| ev.node == "e2e" && ev.message.contains(&e2e.head))
218                .map(|ev| ev.at)
219        })
220        .or(Some(state.updated_at));
221
222    Some(Stop {
223        id,
224        run: state.id.clone(),
225        head: e2e.head.clone(),
226        base,
227        generation,
228        evidence,
229        recorded_at,
230        recorded_pass: e2e.pass,
231        recorded_events: e2e.recorded_events,
232        resumption_generation: e2e.resumption_generation,
233    })
234}
235
236/// True only when the latest pass on `state` is provably a no-op reconsumption
237/// of an earlier pass's conclusive `head_e2e` failure with zero new events.
238///
239/// Legacy records without `recorded_pass` / `recorded_events` return `false`
240/// so historical attempts are never retroactively altered.
241pub(crate) fn reconsumed_without_new_verification(state: &RunState, stop: &Stop) -> bool {
242    let (Some(current), Some(recorded_pass), Some(recorded_events)) = (
243        state.passes.last(),
244        stop.recorded_pass,
245        stop.recorded_events,
246    ) else {
247        return false;
248    };
249    recorded_pass < current.index && state.events.len() == recorded_events
250}
251
252fn git_rev_parse_sync(dir: &Path, rev: &str) -> Result<String, String> {
253    let output = std::process::Command::new("git")
254        .current_dir(dir)
255        .args(["rev-parse", "--verify", "--quiet", rev])
256        .quiet()
257        .output()
258        .map_err(|e| format!("git rev-parse {rev} in {}: {e}", dir.display()))?;
259    if !output.status.success() {
260        let stderr = String::from_utf8_lossy(&output.stderr).trim().to_owned();
261        return Err(if stderr.is_empty() {
262            format!("git rev-parse {rev} failed in {}", dir.display())
263        } else {
264            format!("git rev-parse {rev} failed in {}: {stderr}", dir.display())
265        });
266    }
267    let sha = String::from_utf8_lossy(&output.stdout).trim().to_owned();
268    if sha.is_empty() {
269        Err(format!("git rev-parse {rev} returned empty output"))
270    } else {
271        Ok(sha)
272    }
273}
274
275/// Check whether candidate HEAD, remote base SHA, or repair/task inputs have
276/// materially changed since `stop`. Read failures are reported via
277/// [`FactCheck::Unreadable`] and are never treated as evidence of change.
278pub(crate) fn inspect_facts(task: &Task, state: &RunState, stop: &Stop) -> FactCheck {
279    if task.fresh_start {
280        return FactCheck::Changed("explicit fresh start requested".into());
281    }
282    if task.pr_recovery.is_some() {
283        return FactCheck::Changed("explicit PR recovery selection present".into());
284    }
285    if task.replacement.as_ref().is_some_and(|replacement| {
286        state.replaces.as_ref().is_none_or(|applied| {
287            applied.question != replacement.question
288                || applied.run != replacement.run
289                || applied.agent != replacement.agent
290        })
291    }) {
292        return FactCheck::Changed("new explicit replacement selection present".into());
293    }
294    if !crate::daemon::compatible_run_instruction(state, task) {
295        return FactCheck::Changed("task instruction changed".into());
296    }
297    if crate::repair_budget::pending(task, state) {
298        return FactCheck::Changed("pending repair grant present".into());
299    }
300
301    let Some(winner) = state.winner() else {
302        return FactCheck::Unreadable("retained winner record is missing".into());
303    };
304    let mut diagnostics = Vec::new();
305
306    if winner.worktree.exists() {
307        match git_rev_parse_sync(&winner.worktree, "HEAD") {
308            Ok(wt_head) if wt_head != stop.head => {
309                return FactCheck::Changed(format!(
310                    "winner worktree HEAD moved from {} to {}",
311                    short(&stop.head),
312                    short(&wt_head)
313                ));
314            }
315            Ok(_) => {}
316            Err(err) => diagnostics.push(err),
317        }
318    } else {
319        diagnostics.push(format!(
320            "winner worktree {} is unavailable",
321            winner.worktree.display()
322        ));
323    }
324
325    let branch_ref = format!("refs/heads/{}", winner.branch);
326    match git_rev_parse_sync(&state.repo, &branch_ref) {
327        Ok(branch_head) if branch_head != stop.head => {
328            return FactCheck::Changed(format!(
329                "candidate branch {} moved from {} to {}",
330                winner.branch,
331                short(&stop.head),
332                short(&branch_head)
333            ));
334        }
335        Ok(_) => {}
336        Err(err) => diagnostics.push(err),
337    }
338
339    let tracking = format!(
340        "refs/remotes/{}/{}",
341        state.config.merge.remote, state.base_branch
342    );
343    // A successful sync can incorporate a new base without changing HEAD.
344    // Its tip is the dispatch baseline; the failed verification's base
345    // remains immutable evidence for the stop identity.
346    let synchronized_base = state
347        .base_sync
348        .as_ref()
349        .filter(|sync| sync.conflict.is_none() && !sync.tip.is_empty())
350        .map_or(stop.base.as_str(), |sync| sync.tip.as_str());
351    match git_rev_parse_sync(&state.repo, &tracking) {
352        Ok(base_tip) if !synchronized_base.is_empty() && base_tip != synchronized_base => {
353            return FactCheck::Changed(format!(
354                "remote base {} moved from {} to {}",
355                tracking,
356                short(synchronized_base),
357                short(&base_tip)
358            ));
359        }
360        Ok(_) => {}
361        Err(err) => diagnostics.push(err),
362    }
363
364    if !diagnostics.is_empty() {
365        FactCheck::Unreadable(diagnostics.join("; "))
366    } else {
367        FactCheck::Unchanged
368    }
369}
370
371/// Return the task's unconsumed explicit owner approval if one was recorded
372/// after `stop`, or `None` if no new approval exists.
373pub(crate) fn pending_owner_approval<'a>(
374    task: &'a Task,
375    state: &RunState,
376    stop: &Stop,
377) -> Option<&'a crate::queue::Resumption> {
378    let approval = task.resumption.as_ref()?;
379    if state
380        .head_e2e_resumptions
381        .iter()
382        .any(|r| r.task == task.id && r.generation >= approval.generation)
383    {
384        return None;
385    }
386    match stop.resumption_generation {
387        Some(recorded_gen) => (approval.generation > recorded_gen).then_some(approval),
388        None => stop
389            .recorded_at
390            .is_some_and(|at| approval.at > at)
391            .then_some(approval),
392    }
393}
394
395/// Record that an explicit owner approval was consumed for one pass against `stop_id`.
396pub(crate) fn record_consumed_approval(
397    state: &mut RunState,
398    task_id: &str,
399    stop_id: &str,
400    generation: u64,
401    approval_at: Timestamp,
402) {
403    if state
404        .head_e2e_resumptions
405        .iter()
406        .any(|r| r.task == task_id && r.generation >= generation)
407    {
408        return;
409    }
410    state.head_e2e_resumptions.push(Resumption {
411        task: task_id.to_owned(),
412        stop_id: stop_id.to_owned(),
413        generation,
414        approval_at,
415    });
416}
417
418/// Deterministic, actionable hold reason naming the stop evidence and recovery options.
419pub(crate) fn hold_reason(
420    task: &Task,
421    state: &RunState,
422    stop: &Stop,
423    read_diagnostic: Option<&str>,
424) -> String {
425    let failed_summary = state
426        .head_e2e
427        .as_ref()
428        .and_then(|e2e| e2e.outcomes.iter().find(|o| !o.ok() && !o.resource_blocked))
429        .map(|o| crate::stop_reason::command_failure("verify.e2e", o))
430        .unwrap_or_else(|| format!("verify.e2e failed on head {}", short(&stop.head)));
431    let base_note = if stop.base.is_empty() {
432        String::new()
433    } else {
434        format!(", base {}", short(&stop.base))
435    };
436    let read_note = read_diagnostic
437        .map(|diag| format!(" Repository check could not confirm a change ({diag})."))
438        .unwrap_or_default();
439    format!(
440        "[head-e2e] {failed_summary} on head {}{base_note} [run {}, stop {}].{read_note} Automatic retries are held while candidate HEAD and base remain unchanged. To recover: update the candidate branch or {}/{}, explicitly release/resume once (`magi task release {}` or `magi run --resume {}`), or edit the task instruction.",
441        short(&stop.head),
442        stop.run,
443        stop.id,
444        state.config.merge.remote,
445        state.base_branch,
446        task.id,
447        stop.run,
448    )
449}
450
451fn load_latest_run(queue: &Queue, task: &Task) -> Option<RunState> {
452    let home = queue.root().parent()?;
453    let id = task.execution_runs().last()?;
454    RunState::load_under(id, home).ok().filter(|s| s.id == *id)
455}
456
457fn build_hold(
458    task: &Task,
459    state: &RunState,
460    stop: Stop,
461    read_diagnostic: Option<&str>,
462) -> HoldAction {
463    let reason = hold_reason(task, state, &stop, read_diagnostic);
464    let detail = state
465        .verification_blocking_cause()
466        .unwrap_or_else(|| format!("verify.e2e failed on head {}; nothing published", stop.head));
467    let diagnostic = crate::daemon::diagnostic_for(state);
468    HoldAction {
469        stop,
470        reason,
471        detail,
472        diagnostic,
473    }
474}
475
476/// Shared eligibility check for [`crate::daemon::claim_dispatch`].
477///
478/// Returns `Some(HoldAction)` when dispatching `task` would only reconsume an
479/// unchanged conclusive `head_e2e` failure without a new explicit owner
480/// approval or changed candidate/base/repair facts.
481pub(crate) fn dispatch_hold(queue: &Queue, task: &Task) -> Option<HoldAction> {
482    match check_attempt(queue, task) {
483        Some(AttemptGate::Hold(action)) => Some(action),
484        Some(AttemptGate::ConsumeOwnerApproval { .. }) | None => None,
485    }
486}
487
488/// Shared eligibility check for [`crate::daemon::attempt`].
489pub(crate) fn check_attempt(queue: &Queue, task: &Task) -> Option<AttemptGate> {
490    let state = load_latest_run(queue, task)?;
491    let stop = conclusive(&state)?;
492    if task
493        .sync_only
494        .as_ref()
495        .is_some_and(|request| request.run == state.id)
496    {
497        return None;
498    }
499    let read_diagnostic = match inspect_facts(task, &state, &stop) {
500        FactCheck::Changed(_) => return None,
501        FactCheck::Unchanged => None,
502        FactCheck::Unreadable(diag) => Some(diag),
503    };
504    if let Some(approval) = pending_owner_approval(task, &state, &stop) {
505        return Some(AttemptGate::ConsumeOwnerApproval {
506            run: stop.run,
507            stop_id: stop.id,
508            generation: approval.generation,
509            approval_at: approval.at,
510        });
511    }
512    Some(AttemptGate::Hold(build_hold(
513        task,
514        &state,
515        stop,
516        read_diagnostic.as_deref(),
517    )))
518}
519
520/// True when automatic conductor recovery (`Review` / `Requeue` / re-hold) must
521/// be suppressed because the latest run sits on an unchanged conclusive
522/// `head_e2e` stop.
523pub(crate) fn blocks_automatic_recovery(queue: &Queue, task: &Task) -> bool {
524    let Some(state) = load_latest_run(queue, task) else {
525        return false;
526    };
527    let Some(stop) = conclusive(&state) else {
528        return false;
529    };
530    !matches!(inspect_facts(task, &state, &stop), FactCheck::Changed(_))
531}
532
533/// Classification for [`crate::triage::run_once`] on a `Held` machine task.
534pub(crate) fn triage_status(queue: &Queue, task: &Task) -> TriageStatus {
535    if task.status != TaskStatus::Held
536        || task.hold_source != Some(HoldSource::Machine)
537        || !task.has_head_e2e_cause()
538    {
539        return TriageStatus::NotHeadE2e;
540    }
541    let Some(state) = load_latest_run(queue, task) else {
542        return TriageStatus::HoldStillActive;
543    };
544    if let Some(stop) = conclusive(&state) {
545        return match inspect_facts(task, &state, &stop) {
546            FactCheck::Changed(_) => TriageStatus::ResolvedChanged,
547            FactCheck::Unchanged | FactCheck::Unreadable(_) => TriageStatus::HoldStillActive,
548        };
549    }
550    if state.status.resumable()
551        && !state.base_sync_blocked()
552        && state.prep_failure.is_none()
553        && state.resource_block.is_none()
554    {
555        TriageStatus::ResolvedChanged
556    } else {
557        TriageStatus::NotHeadE2e
558    }
559}
560
561/// Refusal message for standing chat recovery (`resume` / `retry` / `release`)
562/// when the retained run is stopped on an unchanged conclusive `head_e2e` red.
563pub(crate) fn standing_refusal(task: &Task, state: &RunState) -> Option<String> {
564    let stop = conclusive(state)?;
565    match inspect_facts(task, state, &stop) {
566        FactCheck::Changed(_) => None,
567        FactCheck::Unchanged => Some(format!(
568            "conclusive head_e2e failure ({}) on unchanged head {} / base {}; standing recovery cannot re-dispatch unchanged work. Update the candidate branch or {}/{}, grant a repair, or ask the owner for an explicit decision.",
569            stop.id,
570            short(&stop.head),
571            short(&stop.base),
572            state.config.merge.remote,
573            state.base_branch,
574        )),
575        FactCheck::Unreadable(diag) => Some(format!(
576            "conclusive head_e2e failure ({}) could not verify any candidate/base change ({diag}); standing recovery cannot re-dispatch unchanged work. Inspect the retained repository state or ask the owner.",
577            stop.id,
578        )),
579    }
580}
581
582#[cfg(test)]
583mod tests {
584    use super::*;
585    use crate::ask::Question;
586    use crate::config::Config;
587    use crate::notices;
588    use crate::queue::{Queue, Source, Task};
589    use crate::run::{Candidate, CommandOutcome, GateRepairE2e, RunState, RunStatus, Tally};
590    use crate::talk::{Talks, seeded_for_test};
591
592    fn git_sync(dir: &Path, args: &[&str]) -> String {
593        let out = std::process::Command::new("git")
594            .current_dir(dir)
595            .args(args)
596            .env("GIT_AUTHOR_NAME", "test")
597            .env("GIT_AUTHOR_EMAIL", "test@example.com")
598            .env("GIT_COMMITTER_NAME", "test")
599            .env("GIT_COMMITTER_EMAIL", "test@example.com")
600            .output()
601            .expect("spawn git");
602        assert!(
603            out.status.success(),
604            "git {:?} failed: {}",
605            args,
606            String::from_utf8_lossy(&out.stderr)
607        );
608        String::from_utf8_lossy(&out.stdout).trim().to_owned()
609    }
610
611    fn init_repo_with_origin(
612        root: &Path,
613    ) -> (std::path::PathBuf, std::path::PathBuf, String, String) {
614        let origin = root.join("origin.git");
615        let repo = root.join("repo");
616        std::fs::create_dir_all(&origin).unwrap();
617        std::fs::create_dir_all(&repo).unwrap();
618        git_sync(&origin, &["init", "--bare", "-b", "main"]);
619        git_sync(&repo, &["init", "-b", "main"]);
620        std::fs::write(repo.join("README.md"), "base\n").unwrap();
621        git_sync(&repo, &["add", "README.md"]);
622        git_sync(&repo, &["commit", "-m", "initial"]);
623        let base_sha = git_sync(&repo, &["rev-parse", "HEAD"]);
624        git_sync(
625            &repo,
626            &["remote", "add", "origin", &origin.to_string_lossy()],
627        );
628        git_sync(&repo, &["push", "-u", "origin", "main"]);
629        git_sync(&repo, &["checkout", "-b", "feat/candidate"]);
630        std::fs::write(repo.join("change.txt"), "candidate\n").unwrap();
631        git_sync(&repo, &["add", "change.txt"]);
632        git_sync(&repo, &["commit", "-m", "candidate change"]);
633        let head_sha = git_sync(&repo, &["rev-parse", "HEAD"]);
634        git_sync(&repo, &["checkout", "main"]);
635        let wt = root.join("wt");
636        git_sync(
637            &repo,
638            &["worktree", "add", &wt.to_string_lossy(), "feat/candidate"],
639        );
640        (repo, wt, base_sha, head_sha)
641    }
642
643    fn failed_outcome(
644        command: &str,
645        code: Option<i32>,
646        tail: &str,
647        resource_blocked: bool,
648    ) -> CommandOutcome {
649        CommandOutcome {
650            command: command.into(),
651            code,
652            output_tail: tail.into(),
653            resource_blocked,
654            ..Default::default()
655        }
656    }
657
658    fn sample_blocked_state(repo: &Path, wt: &Path, base: &str, head: &str) -> RunState {
659        let mut cfg = Config::default();
660        cfg.graph.review_rounds = 0;
661        cfg.verify.e2e = vec!["cargo test --test typography".into()];
662        let mut state = RunState::new(
663            repo.to_path_buf(),
664            "main".into(),
665            base.into(),
666            "fix typography".into(),
667            cfg,
668        );
669        state.status = RunStatus::Blocked;
670        let candidate: Candidate = serde_json::from_value(serde_json::json!({
671            "index": 0,
672            "label": "A",
673            "agent": "existing",
674            "branch": "feat/candidate",
675            "worktree": wt,
676            "commits": 1,
677        }))
678        .unwrap();
679        state.candidates.push(candidate);
680        state.tally = Some(
681            serde_json::from_value::<Tally>(serde_json::json!({
682                "first_choice": {"A": 1},
683                "borda": {"A": 1},
684                "winner": "A",
685                "unanimous_initial": true,
686                "deliberated": false,
687                "changed_votes": 0,
688                "unanimous_final": true,
689            }))
690            .unwrap(),
691        );
692        state.begin_pass();
693        let mut e2e = GateRepairE2e::new(
694            head.into(),
695            false,
696            vec![failed_outcome(
697                "cargo test --test typography",
698                Some(1),
699                "test typo_spec ... FAILED",
700                false,
701            )],
702        );
703        e2e.base_commit = Some(base.into());
704        e2e.generation = Some(0);
705        e2e.pass = Some(0);
706        e2e.recorded_at = Some(Timestamp::now());
707        e2e.resumption_generation = Some(0);
708        state.event(
709            "e2e",
710            format!("verify.e2e failed on head {head}; nothing published"),
711        );
712        e2e.recorded_events = Some(state.events.len());
713        state.head_e2e = Some(e2e);
714        state
715    }
716
717    #[test]
718    fn conclusive_excludes_inconclusive_resource_other_stops_and_active_repairs() {
719        let tmp = tempfile::tempdir().unwrap();
720        let (repo, wt, base, head) = init_repo_with_origin(tmp.path());
721        let base_state = sample_blocked_state(&repo, &wt, &base, &head);
722        assert!(conclusive(&base_state).is_some());
723
724        // Inconclusive resource-blocked outcome.
725        let mut s = base_state.clone();
726        s.head_e2e.as_mut().unwrap().outcomes[0].resource_blocked = true;
727        assert!(conclusive(&s).is_none());
728
729        // Empty outcomes placeholder (interrupted before finishing).
730        let mut s = base_state.clone();
731        s.head_e2e.as_mut().unwrap().outcomes.clear();
732        assert!(conclusive(&s).is_none());
733
734        // Passed head_e2e.
735        let mut s = base_state.clone();
736        s.head_e2e.as_mut().unwrap().passed = true;
737        assert!(conclusive(&s).is_none());
738
739        // Parked run.
740        let mut s = base_state.clone();
741        s.parked = true;
742        assert!(conclusive(&s).is_none());
743
744        // Resource block present.
745        let mut s = base_state.clone();
746        s.resource_block = Some(crate::run::ResourceBlock {
747            cause: crate::run::ResourceBlockCause::Other,
748            node: "e2e".into(),
749            kind: "shared build cache".into(),
750            detail: "busy".into(),
751            at: Timestamp::now(),
752        });
753        assert!(conclusive(&s).is_none());
754
755        // Base-sync stop present.
756        let mut s = base_state.clone();
757        s.base_sync = Some(crate::run::BaseSync {
758            tip: base.clone(),
759            behind: 1,
760            attempts: 1,
761            conflict: Some("conflict".into()),
762            already_in: None,
763        });
764        assert!(conclusive(&s).is_none());
765
766        // Prep failure present.
767        let mut s = base_state.clone();
768        s.prep_failure = Some("setup failed".into());
769        assert!(conclusive(&s).is_none());
770
771        // Gate failure takes precedence.
772        let mut s = base_state.clone();
773        s.gate_ran = true;
774        s.gate = vec![failed_outcome(
775            "cargo make check",
776            Some(1),
777            "lint failed",
778            false,
779        )];
780        assert!(conclusive(&s).is_none());
781
782        // Active repair grant in progress.
783        let mut s = base_state.clone();
784        s.repair_grants.push(crate::repair_budget::Applied {
785            receipt: crate::repair_budget::Receipt {
786                request: crate::repair_budget::Request {
787                    task: "t".into(),
788                    run: s.id.clone(),
789                    kind: crate::repair_budget::Kind::Gate,
790                    rounds: 1,
791                    head: head.clone(),
792                    expect_pass: 0,
793                    request: "req-1".into(),
794                    reason: "repair".into(),
795                    tip: None,
796                    instruction: None,
797                    replace_request: None,
798                    evidence_digest: None,
799                    reopen_occurrence: None,
800                    confirm_legacy_reopen_hold: None,
801                },
802                at: Timestamp::now(),
803                decision: None,
804                contract: String::new(),
805                stop: None,
806                legacy: None,
807                review_transition: None,
808            },
809            spent: 0,
810            phase: crate::repair_budget::Phase::Pending,
811            review_start: 0,
812            head: head.clone(),
813            succeeded: false,
814            conflict: None,
815        });
816        assert!(conclusive(&s).is_none());
817    }
818
819    #[test]
820    fn stop_identity_ignores_pass_time_duration_and_prose_and_tracks_evidence() {
821        let tmp = tempfile::tempdir().unwrap();
822        let (repo, wt, base, head) = init_repo_with_origin(tmp.path());
823        let s1 = sample_blocked_state(&repo, &wt, &base, &head);
824        let stop1 = conclusive(&s1).unwrap();
825
826        // Varying pass index, timestamps, duration_ms, and event prose must not change stop.id.
827        let mut s2 = s1.clone();
828        s2.begin_pass();
829        s2.head_e2e.as_mut().unwrap().pass = Some(5);
830        s2.head_e2e.as_mut().unwrap().recorded_at = Some(
831            Timestamp::now()
832                .checked_add(jiff::SignedDuration::from_hours(2))
833                .unwrap(),
834        );
835        s2.head_e2e.as_mut().unwrap().outcomes[0].duration_ms = 999_999;
836        s2.event("e2e", "rephrased prose");
837        let stop2 = conclusive(&s2).unwrap();
838        assert_eq!(stop1.id, stop2.id);
839
840        // Changing head, base, generation, command, exit code, or output MUST change stop.id.
841        let mut diff_head = s1.clone();
842        diff_head.head_e2e.as_mut().unwrap().head =
843            "1111111111111111111111111111111111111111".into();
844        assert_ne!(conclusive(&diff_head).unwrap().id, stop1.id);
845
846        let mut diff_base = s1.clone();
847        diff_base.head_e2e.as_mut().unwrap().base_commit =
848            Some("2222222222222222222222222222222222222222".into());
849        assert_ne!(conclusive(&diff_base).unwrap().id, stop1.id);
850
851        let mut diff_gen = s1.clone();
852        diff_gen.head_e2e.as_mut().unwrap().generation = Some(1);
853        assert_ne!(conclusive(&diff_gen).unwrap().id, stop1.id);
854
855        let mut diff_cmd = s1.clone();
856        diff_cmd.head_e2e.as_mut().unwrap().outcomes[0].command = "cargo test --test other".into();
857        assert_ne!(conclusive(&diff_cmd).unwrap().id, stop1.id);
858
859        let mut diff_out = s1.clone();
860        diff_out.head_e2e.as_mut().unwrap().outcomes[0].output_tail = "different failure".into();
861        assert_ne!(conclusive(&diff_out).unwrap().id, stop1.id);
862    }
863
864    #[test]
865    fn legacy_stop_identity_survives_base_sync_without_new_verification() {
866        let tmp = tempfile::tempdir().unwrap();
867        let (repo, wt, base, head) = init_repo_with_origin(tmp.path());
868        let mut state = sample_blocked_state(&repo, &wt, &base, &head);
869        let task = Task::new(
870            "t".into(),
871            "fix typography".into(),
872            repo.clone(),
873            Source::Human,
874        );
875        state.head_e2e.as_mut().unwrap().base_commit = None;
876        let before = conclusive(&state).unwrap();
877        git_sync(&repo, &["update-ref", "refs/remotes/origin/main", &head]);
878        assert!(matches!(
879            inspect_facts(&task, &state, &before),
880            FactCheck::Changed(_)
881        ));
882        state.base_sync = Some(crate::run::BaseSync {
883            tip: head.clone(),
884            behind: 0,
885            attempts: 1,
886            conflict: None,
887            already_in: None,
888        });
889        let after = conclusive(&state).unwrap();
890        assert_eq!(before.id, after.id);
891        assert_eq!(after.base, base);
892        assert_eq!(inspect_facts(&task, &state, &after), FactCheck::Unchanged);
893
894        state.head_e2e.as_mut().unwrap().base_commit = Some(String::new());
895        assert_eq!(conclusive(&state).unwrap().id, before.id);
896
897        let mut different_base = state.clone();
898        different_base.base_commit = head.clone();
899        assert_ne!(conclusive(&different_base).unwrap().id, before.id);
900
901        let mut different_head = state.clone();
902        different_head.head_e2e.as_mut().unwrap().head = base.clone();
903        assert_ne!(conclusive(&different_head).unwrap().id, before.id);
904
905        let mut different_failure = state.clone();
906        different_failure.head_e2e.as_mut().unwrap().outcomes[0].output_tail =
907            "another failure".into();
908        assert_ne!(conclusive(&different_failure).unwrap().id, before.id);
909
910        state.head_e2e.as_mut().unwrap().base_commit = Some(head);
911        let recorded = conclusive(&state).unwrap();
912        assert_ne!(recorded.id, before.id);
913        state.base_commit = "another initial base".into();
914        state.base_sync.as_mut().unwrap().tip = base;
915        assert_eq!(conclusive(&state).unwrap().id, recorded.id);
916    }
917
918    #[test]
919    fn reconsumption_detection_is_exact_and_conservative_on_legacy() {
920        let tmp = tempfile::tempdir().unwrap();
921        let (repo, wt, base, head) = init_repo_with_origin(tmp.path());
922        let mut state = sample_blocked_state(&repo, &wt, &base, &head);
923        let stop = conclusive(&state).unwrap();
924        assert!(!reconsumed_without_new_verification(&state, &stop));
925
926        // Legacy record (no recorded_pass): never retroactively refunded.
927        let mut legacy = state.clone();
928        legacy.begin_pass();
929        legacy.head_e2e.as_mut().unwrap().pass = None;
930        let legacy_stop = conclusive(&legacy).unwrap();
931        assert!(!reconsumed_without_new_verification(&legacy, &legacy_stop));
932
933        // New pass with zero new events: provably reconsumed.
934        state.begin_pass();
935        let stop = conclusive(&state).unwrap();
936        assert!(reconsumed_without_new_verification(&state, &stop));
937
938        // New pass with a new event: not a pure reconsumption.
939        state.event("e2e", "fresh verification event");
940        let stop = conclusive(&state).unwrap();
941        assert!(!reconsumed_without_new_verification(&state, &stop));
942    }
943
944    #[test]
945    fn inspect_facts_detects_head_base_and_repair_changes_and_refuses_unreadable() {
946        let tmp = tempfile::tempdir().unwrap();
947        let (repo, wt, base, head) = init_repo_with_origin(tmp.path());
948        let state = sample_blocked_state(&repo, &wt, &base, &head);
949        let stop = conclusive(&state).unwrap();
950        let task = Task::new(
951            "t".into(),
952            "fix typography".into(),
953            repo.clone(),
954            Source::Human,
955        );
956
957        assert_eq!(inspect_facts(&task, &state, &stop), FactCheck::Unchanged);
958
959        // Moving remote base SHA (even without changing candidate HEAD) is detected.
960        std::fs::write(repo.join("base2.txt"), "moved\n").unwrap();
961        git_sync(&repo, &["add", "base2.txt"]);
962        git_sync(&repo, &["commit", "-m", "advance base"]);
963        git_sync(&repo, &["push", "origin", "main"]);
964        assert!(matches!(
965            inspect_facts(&task, &state, &stop),
966            FactCheck::Changed(msg) if msg.contains("remote base")
967        ));
968
969        // Reset remote base back to original SHA so we can test candidate HEAD move.
970        git_sync(&repo, &["reset", "--hard", &base]);
971        git_sync(&repo, &["push", "--force", "origin", "main"]);
972        assert_eq!(inspect_facts(&task, &state, &stop), FactCheck::Unchanged);
973
974        // Moving candidate HEAD in worktree is detected.
975        std::fs::write(wt.join("change2.txt"), "fix\n").unwrap();
976        git_sync(&wt, &["add", "change2.txt"]);
977        git_sync(&wt, &["commit", "-m", "fix candidate"]);
978        assert!(matches!(
979            inspect_facts(&task, &state, &stop),
980            FactCheck::Changed(msg) if msg.contains("HEAD moved")
981        ));
982
983        // Reset candidate back, then break the tracking ref so git read fails -> Unreadable, NOT Changed!
984        git_sync(&wt, &["reset", "--hard", &head]);
985        assert_eq!(inspect_facts(&task, &state, &stop), FactCheck::Unchanged);
986        let mut missing_base = state.clone();
987        missing_base.base_branch = "nonexistent-base".into();
988        assert!(matches!(
989            inspect_facts(&task, &missing_base, &stop),
990            FactCheck::Unreadable(_)
991        ));
992    }
993
994    #[test]
995    fn dispatch_and_triage_respect_explicit_sync_and_hold_ownership() {
996        let tmp = tempfile::tempdir().unwrap();
997        let (repo, wt, base, head) = init_repo_with_origin(tmp.path());
998        let mut state = sample_blocked_state(&repo, &wt, &base, &head);
999        let queue = Queue::at(tmp.path().join("queue"));
1000        let mut task = Task::new(
1001            "t".into(),
1002            "fix typography".into(),
1003            repo.clone(),
1004            Source::Human,
1005        );
1006        task.start(state.id.clone());
1007        let replacement = crate::merge_decision::Replacement {
1008            question: "replacement".into(),
1009            run: "previous".into(),
1010            pr: "previous-pr".into(),
1011            agent: "existing".into(),
1012            context: String::new(),
1013        };
1014        task.replacement = Some(replacement.clone());
1015        state.replaces = Some(replacement);
1016        state.save_under(tmp.path()).unwrap();
1017        let stop = conclusive(&state).unwrap();
1018        let hold =
1019            dispatch_hold(&queue, &task).expect("historical replacement is not new evidence");
1020        hold.apply(&mut task);
1021        assert_eq!(triage_status(&queue, &task), TriageStatus::HoldStillActive);
1022        task.resume_head_e2e_wait();
1023        task.sync_only = Some(crate::base_sync_only::Request {
1024            run: state.id.clone(),
1025            at: Timestamp::now(),
1026        });
1027        assert!(dispatch_hold(&queue, &task).is_none());
1028        task.sync_only = None;
1029        assert!(dispatch_hold(&queue, &task).is_some());
1030
1031        git_sync(&repo, &["update-ref", "refs/remotes/origin/main", &head]);
1032        task.hold_machine(Some("disk capacity unavailable".into()));
1033        task.mark_disk_capacity();
1034        assert_eq!(triage_status(&queue, &task), TriageStatus::NotHeadE2e);
1035        build_hold(&task, &state, stop, None).apply(&mut task);
1036        assert_eq!(triage_status(&queue, &task), TriageStatus::ResolvedChanged);
1037    }
1038
1039    #[test]
1040    fn conductor_preserves_independent_question_on_unchanged_stop() {
1041        let tmp = tempfile::tempdir().unwrap();
1042        let (repo, wt, base, head) = init_repo_with_origin(tmp.path());
1043        let mut state = sample_blocked_state(&repo, &wt, &base, &head);
1044        state.save_under(tmp.path()).unwrap();
1045        let queue = Queue::at(tmp.path().join("queue"));
1046        let questions = crate::ask::Questions::at(tmp.path().join("questions"));
1047        let mut task = Task::new("t".into(), "fix typography".into(), repo, Source::Human);
1048        task.start(state.id.clone());
1049        dispatch_hold(&queue, &task).unwrap().apply(&mut task);
1050        queue.put(&mut task).unwrap();
1051        crate::conduct::apply(
1052            &queue,
1053            &questions,
1054            &crate::conduct::Verdict {
1055                decisions: vec![crate::conduct::Decision {
1056                    id: task.id.clone(),
1057                    blocked_by: Vec::new(),
1058                    missing_dependencies: Vec::new(),
1059                    reason: Some("Independent scope decision".into()),
1060                    recovery: Some(crate::conduct::Recovery::Hold),
1061                    question: Some("Should the scope include another component?".into()),
1062                    choices: vec!["hold".into()],
1063                    actions: Default::default(),
1064                    question_decision: None,
1065                    evidence: Vec::new(),
1066                }],
1067            },
1068        )
1069        .unwrap();
1070        let blocked = queue.get(&task.id).unwrap();
1071        assert_eq!(blocked.status, TaskStatus::Blocked);
1072        let question = questions.get(&blocked.blocked_by[0]).unwrap();
1073        assert!(question.status.open());
1074        assert_eq!(
1075            question.summary,
1076            "Should the scope include another component?"
1077        );
1078    }
1079
1080    #[test]
1081    fn notice_semantics_unifies_run_ended_task_held_and_outcome_for_same_stop() {
1082        let tmp = tempfile::tempdir().unwrap();
1083        let (repo, wt, base, head) = init_repo_with_origin(tmp.path());
1084        let mut state = sample_blocked_state(&repo, &wt, &base, &head);
1085        state.save_under(tmp.path()).unwrap();
1086        let stop = conclusive(&state).unwrap();
1087
1088        let talks = Talks::at(tmp.path().join("talks"));
1089        let mut chat = seeded_for_test("chat-1", repo.clone());
1090        talks.put(&mut chat).unwrap();
1091
1092        let queue = Queue::at(tmp.path().join("queue"));
1093        let mut task = Task::new(
1094            "typography".into(),
1095            "fix typography".into(),
1096            repo.clone(),
1097            Source::Agent {
1098                run: chat.id.clone(),
1099                node: crate::queue::CHAT_NODE.into(),
1100            },
1101        );
1102        task.start(state.id.clone());
1103        // Even while task is still Running (race before settlement), run_ended normalizes identically.
1104        let run_notice = notices::run_ended(&state).unwrap();
1105        assert_eq!(run_notice.cause.as_deref(), Some(stop.id.as_str()));
1106        let sem_run_while_running = crate::notice_semantics::attention(
1107            tmp.path(),
1108            Some(&task),
1109            Some(&state.id),
1110            &run_notice,
1111        )
1112        .unwrap();
1113
1114        let hold = build_hold(&task, &state, stop.clone(), None);
1115        hold.apply(&mut task);
1116        queue.put(&mut task).unwrap();
1117        let held_notice = notices::task_held(&task).unwrap();
1118        assert_eq!(held_notice.cause.as_deref(), Some(stop.id.as_str()));
1119
1120        let sem_held = crate::notice_semantics::attention(
1121            tmp.path(),
1122            Some(&task),
1123            Some(&state.id),
1124            &held_notice,
1125        )
1126        .unwrap();
1127        let sem_run_after_hold = crate::notice_semantics::attention(
1128            tmp.path(),
1129            Some(&task),
1130            Some(&state.id),
1131            &run_notice,
1132        )
1133        .unwrap();
1134        let sem_outcome = crate::notice_semantics::outcome(tmp.path(), &task);
1135
1136        assert_eq!(sem_run_while_running, sem_held);
1137        assert_eq!(sem_held, sem_run_after_hold);
1138        assert_eq!(sem_held, sem_outcome);
1139
1140        // A separate admission failure on the same retained run must not
1141        // inherit the earlier E2E delivery receipt.
1142        let mut disk_held = task.clone();
1143        disk_held.release_operator("cli", None);
1144        disk_held.hold_machine(Some("disk capacity unavailable".into()));
1145        disk_held.mark_disk_capacity();
1146        let disk_outcome = crate::notice_semantics::outcome(tmp.path(), &disk_held);
1147        assert!(!crate::notice_semantics::covers(
1148            &sem_outcome,
1149            &disk_outcome
1150        ));
1151        let disk_notice = notices::task_held(&disk_held).unwrap();
1152        let disk_attention = crate::notice_semantics::attention(
1153            tmp.path(),
1154            Some(&disk_held),
1155            Some(&state.id),
1156            &disk_notice,
1157        )
1158        .unwrap();
1159        assert!(!crate::notice_semantics::covers(
1160            &sem_outcome,
1161            &disk_attention
1162        ));
1163
1164        // New pass reconsuming the same stop (and later held_at) still produces the same semantic receipt.
1165        state.begin_pass();
1166        state.save_under(tmp.path()).unwrap();
1167        let sem_next_pass = crate::notice_semantics::outcome(tmp.path(), &task);
1168        assert!(crate::notice_semantics::covers(
1169            &sem_outcome,
1170            &sem_next_pass
1171        ));
1172
1173        // Distinct new failure (new head) produces a distinct receipt that is NOT covered.
1174        let mut new_head_state = state.clone();
1175        new_head_state.head_e2e.as_mut().unwrap().head =
1176            "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".into();
1177        new_head_state.save_under(tmp.path()).unwrap();
1178        let new_stop = conclusive(&new_head_state).unwrap();
1179        assert_ne!(new_stop.id, stop.id);
1180        let new_hold = build_hold(&task, &new_head_state, new_stop, None);
1181        new_hold.apply(&mut task);
1182        let sem_new_head = crate::notice_semantics::outcome(tmp.path(), &task);
1183        assert!(!crate::notice_semantics::covers(
1184            &sem_outcome,
1185            &sem_new_head
1186        ));
1187
1188        // Restore original stop and verify an actionable new Question is NEVER flattened.
1189        state.save_under(tmp.path()).unwrap();
1190        hold.apply(&mut task);
1191        let q = Question::new(
1192            task.id.clone(),
1193            "conduct".into(),
1194            "conductor".into(),
1195            "Need direction".into(),
1196            "Choose next step".into(),
1197            vec!["resume".into(), "hold".into()],
1198        );
1199        let sem_question = crate::notice_semantics::question(tmp.path(), &task, &state.id, &q);
1200        assert!(!crate::notice_semantics::covers(
1201            &sem_outcome,
1202            &sem_question
1203        ));
1204    }
1205
1206    #[test]
1207    fn standing_refusal_blocks_unchanged_and_permits_changed_head_or_base() {
1208        let tmp = tempfile::tempdir().unwrap();
1209        let (repo, wt, base, head) = init_repo_with_origin(tmp.path());
1210        let state = sample_blocked_state(&repo, &wt, &base, &head);
1211        let task = Task::new(
1212            "t".into(),
1213            "fix typography".into(),
1214            repo.clone(),
1215            Source::Human,
1216        );
1217
1218        let refused = standing_refusal(&task, &state).expect("unchanged must be refused");
1219        assert!(refused.contains("head-e2e:"));
1220        assert!(refused.contains("standing recovery"));
1221
1222        // Moving candidate HEAD permits standing recovery again.
1223        std::fs::write(wt.join("fix.txt"), "fix\n").unwrap();
1224        git_sync(&wt, &["add", "fix.txt"]);
1225        git_sync(&wt, &["commit", "-m", "fix"]);
1226        assert!(standing_refusal(&task, &state).is_none());
1227    }
1228}