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                },
800                at: Timestamp::now(),
801                decision: None,
802                contract: String::new(),
803                stop: None,
804                legacy: None,
805            },
806            spent: 0,
807            phase: crate::repair_budget::Phase::Pending,
808            review_start: 0,
809            head: head.clone(),
810            succeeded: false,
811            conflict: None,
812        });
813        assert!(conclusive(&s).is_none());
814    }
815
816    #[test]
817    fn stop_identity_ignores_pass_time_duration_and_prose_and_tracks_evidence() {
818        let tmp = tempfile::tempdir().unwrap();
819        let (repo, wt, base, head) = init_repo_with_origin(tmp.path());
820        let s1 = sample_blocked_state(&repo, &wt, &base, &head);
821        let stop1 = conclusive(&s1).unwrap();
822
823        // Varying pass index, timestamps, duration_ms, and event prose must not change stop.id.
824        let mut s2 = s1.clone();
825        s2.begin_pass();
826        s2.head_e2e.as_mut().unwrap().pass = Some(5);
827        s2.head_e2e.as_mut().unwrap().recorded_at = Some(
828            Timestamp::now()
829                .checked_add(jiff::SignedDuration::from_hours(2))
830                .unwrap(),
831        );
832        s2.head_e2e.as_mut().unwrap().outcomes[0].duration_ms = 999_999;
833        s2.event("e2e", "rephrased prose");
834        let stop2 = conclusive(&s2).unwrap();
835        assert_eq!(stop1.id, stop2.id);
836
837        // Changing head, base, generation, command, exit code, or output MUST change stop.id.
838        let mut diff_head = s1.clone();
839        diff_head.head_e2e.as_mut().unwrap().head =
840            "1111111111111111111111111111111111111111".into();
841        assert_ne!(conclusive(&diff_head).unwrap().id, stop1.id);
842
843        let mut diff_base = s1.clone();
844        diff_base.head_e2e.as_mut().unwrap().base_commit =
845            Some("2222222222222222222222222222222222222222".into());
846        assert_ne!(conclusive(&diff_base).unwrap().id, stop1.id);
847
848        let mut diff_gen = s1.clone();
849        diff_gen.head_e2e.as_mut().unwrap().generation = Some(1);
850        assert_ne!(conclusive(&diff_gen).unwrap().id, stop1.id);
851
852        let mut diff_cmd = s1.clone();
853        diff_cmd.head_e2e.as_mut().unwrap().outcomes[0].command = "cargo test --test other".into();
854        assert_ne!(conclusive(&diff_cmd).unwrap().id, stop1.id);
855
856        let mut diff_out = s1.clone();
857        diff_out.head_e2e.as_mut().unwrap().outcomes[0].output_tail = "different failure".into();
858        assert_ne!(conclusive(&diff_out).unwrap().id, stop1.id);
859    }
860
861    #[test]
862    fn legacy_stop_identity_survives_base_sync_without_new_verification() {
863        let tmp = tempfile::tempdir().unwrap();
864        let (repo, wt, base, head) = init_repo_with_origin(tmp.path());
865        let mut state = sample_blocked_state(&repo, &wt, &base, &head);
866        let task = Task::new(
867            "t".into(),
868            "fix typography".into(),
869            repo.clone(),
870            Source::Human,
871        );
872        state.head_e2e.as_mut().unwrap().base_commit = None;
873        let before = conclusive(&state).unwrap();
874        git_sync(&repo, &["update-ref", "refs/remotes/origin/main", &head]);
875        assert!(matches!(
876            inspect_facts(&task, &state, &before),
877            FactCheck::Changed(_)
878        ));
879        state.base_sync = Some(crate::run::BaseSync {
880            tip: head.clone(),
881            behind: 0,
882            attempts: 1,
883            conflict: None,
884            already_in: None,
885        });
886        let after = conclusive(&state).unwrap();
887        assert_eq!(before.id, after.id);
888        assert_eq!(after.base, base);
889        assert_eq!(inspect_facts(&task, &state, &after), FactCheck::Unchanged);
890
891        state.head_e2e.as_mut().unwrap().base_commit = Some(String::new());
892        assert_eq!(conclusive(&state).unwrap().id, before.id);
893
894        let mut different_base = state.clone();
895        different_base.base_commit = head.clone();
896        assert_ne!(conclusive(&different_base).unwrap().id, before.id);
897
898        let mut different_head = state.clone();
899        different_head.head_e2e.as_mut().unwrap().head = base.clone();
900        assert_ne!(conclusive(&different_head).unwrap().id, before.id);
901
902        let mut different_failure = state.clone();
903        different_failure.head_e2e.as_mut().unwrap().outcomes[0].output_tail =
904            "another failure".into();
905        assert_ne!(conclusive(&different_failure).unwrap().id, before.id);
906
907        state.head_e2e.as_mut().unwrap().base_commit = Some(head);
908        let recorded = conclusive(&state).unwrap();
909        assert_ne!(recorded.id, before.id);
910        state.base_commit = "another initial base".into();
911        state.base_sync.as_mut().unwrap().tip = base;
912        assert_eq!(conclusive(&state).unwrap().id, recorded.id);
913    }
914
915    #[test]
916    fn reconsumption_detection_is_exact_and_conservative_on_legacy() {
917        let tmp = tempfile::tempdir().unwrap();
918        let (repo, wt, base, head) = init_repo_with_origin(tmp.path());
919        let mut state = sample_blocked_state(&repo, &wt, &base, &head);
920        let stop = conclusive(&state).unwrap();
921        assert!(!reconsumed_without_new_verification(&state, &stop));
922
923        // Legacy record (no recorded_pass): never retroactively refunded.
924        let mut legacy = state.clone();
925        legacy.begin_pass();
926        legacy.head_e2e.as_mut().unwrap().pass = None;
927        let legacy_stop = conclusive(&legacy).unwrap();
928        assert!(!reconsumed_without_new_verification(&legacy, &legacy_stop));
929
930        // New pass with zero new events: provably reconsumed.
931        state.begin_pass();
932        let stop = conclusive(&state).unwrap();
933        assert!(reconsumed_without_new_verification(&state, &stop));
934
935        // New pass with a new event: not a pure reconsumption.
936        state.event("e2e", "fresh verification event");
937        let stop = conclusive(&state).unwrap();
938        assert!(!reconsumed_without_new_verification(&state, &stop));
939    }
940
941    #[test]
942    fn inspect_facts_detects_head_base_and_repair_changes_and_refuses_unreadable() {
943        let tmp = tempfile::tempdir().unwrap();
944        let (repo, wt, base, head) = init_repo_with_origin(tmp.path());
945        let state = sample_blocked_state(&repo, &wt, &base, &head);
946        let stop = conclusive(&state).unwrap();
947        let task = Task::new(
948            "t".into(),
949            "fix typography".into(),
950            repo.clone(),
951            Source::Human,
952        );
953
954        assert_eq!(inspect_facts(&task, &state, &stop), FactCheck::Unchanged);
955
956        // Moving remote base SHA (even without changing candidate HEAD) is detected.
957        std::fs::write(repo.join("base2.txt"), "moved\n").unwrap();
958        git_sync(&repo, &["add", "base2.txt"]);
959        git_sync(&repo, &["commit", "-m", "advance base"]);
960        git_sync(&repo, &["push", "origin", "main"]);
961        assert!(matches!(
962            inspect_facts(&task, &state, &stop),
963            FactCheck::Changed(msg) if msg.contains("remote base")
964        ));
965
966        // Reset remote base back to original SHA so we can test candidate HEAD move.
967        git_sync(&repo, &["reset", "--hard", &base]);
968        git_sync(&repo, &["push", "--force", "origin", "main"]);
969        assert_eq!(inspect_facts(&task, &state, &stop), FactCheck::Unchanged);
970
971        // Moving candidate HEAD in worktree is detected.
972        std::fs::write(wt.join("change2.txt"), "fix\n").unwrap();
973        git_sync(&wt, &["add", "change2.txt"]);
974        git_sync(&wt, &["commit", "-m", "fix candidate"]);
975        assert!(matches!(
976            inspect_facts(&task, &state, &stop),
977            FactCheck::Changed(msg) if msg.contains("HEAD moved")
978        ));
979
980        // Reset candidate back, then break the tracking ref so git read fails -> Unreadable, NOT Changed!
981        git_sync(&wt, &["reset", "--hard", &head]);
982        assert_eq!(inspect_facts(&task, &state, &stop), FactCheck::Unchanged);
983        let mut missing_base = state.clone();
984        missing_base.base_branch = "nonexistent-base".into();
985        assert!(matches!(
986            inspect_facts(&task, &missing_base, &stop),
987            FactCheck::Unreadable(_)
988        ));
989    }
990
991    #[test]
992    fn dispatch_and_triage_respect_explicit_sync_and_hold_ownership() {
993        let tmp = tempfile::tempdir().unwrap();
994        let (repo, wt, base, head) = init_repo_with_origin(tmp.path());
995        let mut state = sample_blocked_state(&repo, &wt, &base, &head);
996        let queue = Queue::at(tmp.path().join("queue"));
997        let mut task = Task::new(
998            "t".into(),
999            "fix typography".into(),
1000            repo.clone(),
1001            Source::Human,
1002        );
1003        task.start(state.id.clone());
1004        let replacement = crate::merge_decision::Replacement {
1005            question: "replacement".into(),
1006            run: "previous".into(),
1007            pr: "previous-pr".into(),
1008            agent: "existing".into(),
1009            context: String::new(),
1010        };
1011        task.replacement = Some(replacement.clone());
1012        state.replaces = Some(replacement);
1013        state.save_under(tmp.path()).unwrap();
1014        let stop = conclusive(&state).unwrap();
1015        let hold =
1016            dispatch_hold(&queue, &task).expect("historical replacement is not new evidence");
1017        hold.apply(&mut task);
1018        assert_eq!(triage_status(&queue, &task), TriageStatus::HoldStillActive);
1019        task.resume_head_e2e_wait();
1020        task.sync_only = Some(crate::base_sync_only::Request {
1021            run: state.id.clone(),
1022            at: Timestamp::now(),
1023        });
1024        assert!(dispatch_hold(&queue, &task).is_none());
1025        task.sync_only = None;
1026        assert!(dispatch_hold(&queue, &task).is_some());
1027
1028        git_sync(&repo, &["update-ref", "refs/remotes/origin/main", &head]);
1029        task.hold_machine(Some("disk capacity unavailable".into()));
1030        task.mark_disk_capacity();
1031        assert_eq!(triage_status(&queue, &task), TriageStatus::NotHeadE2e);
1032        build_hold(&task, &state, stop, None).apply(&mut task);
1033        assert_eq!(triage_status(&queue, &task), TriageStatus::ResolvedChanged);
1034    }
1035
1036    #[test]
1037    fn conductor_preserves_independent_question_on_unchanged_stop() {
1038        let tmp = tempfile::tempdir().unwrap();
1039        let (repo, wt, base, head) = init_repo_with_origin(tmp.path());
1040        let mut state = sample_blocked_state(&repo, &wt, &base, &head);
1041        state.save_under(tmp.path()).unwrap();
1042        let queue = Queue::at(tmp.path().join("queue"));
1043        let questions = crate::ask::Questions::at(tmp.path().join("questions"));
1044        let mut task = Task::new("t".into(), "fix typography".into(), repo, Source::Human);
1045        task.start(state.id.clone());
1046        dispatch_hold(&queue, &task).unwrap().apply(&mut task);
1047        queue.put(&mut task).unwrap();
1048        crate::conduct::apply(
1049            &queue,
1050            &questions,
1051            &crate::conduct::Verdict {
1052                decisions: vec![crate::conduct::Decision {
1053                    id: task.id.clone(),
1054                    blocked_by: Vec::new(),
1055                    missing_dependencies: Vec::new(),
1056                    reason: Some("Independent scope decision".into()),
1057                    recovery: Some(crate::conduct::Recovery::Hold),
1058                    question: Some("Should the scope include another component?".into()),
1059                    choices: vec!["hold".into()],
1060                    actions: Default::default(),
1061                    question_decision: None,
1062                    evidence: Vec::new(),
1063                }],
1064            },
1065        )
1066        .unwrap();
1067        let blocked = queue.get(&task.id).unwrap();
1068        assert_eq!(blocked.status, TaskStatus::Blocked);
1069        let question = questions.get(&blocked.blocked_by[0]).unwrap();
1070        assert!(question.status.open());
1071        assert_eq!(
1072            question.summary,
1073            "Should the scope include another component?"
1074        );
1075    }
1076
1077    #[test]
1078    fn notice_semantics_unifies_run_ended_task_held_and_outcome_for_same_stop() {
1079        let tmp = tempfile::tempdir().unwrap();
1080        let (repo, wt, base, head) = init_repo_with_origin(tmp.path());
1081        let mut state = sample_blocked_state(&repo, &wt, &base, &head);
1082        state.save_under(tmp.path()).unwrap();
1083        let stop = conclusive(&state).unwrap();
1084
1085        let talks = Talks::at(tmp.path().join("talks"));
1086        let mut chat = seeded_for_test("chat-1", repo.clone());
1087        talks.put(&mut chat).unwrap();
1088
1089        let queue = Queue::at(tmp.path().join("queue"));
1090        let mut task = Task::new(
1091            "typography".into(),
1092            "fix typography".into(),
1093            repo.clone(),
1094            Source::Agent {
1095                run: chat.id.clone(),
1096                node: crate::queue::CHAT_NODE.into(),
1097            },
1098        );
1099        task.start(state.id.clone());
1100        // Even while task is still Running (race before settlement), run_ended normalizes identically.
1101        let run_notice = notices::run_ended(&state).unwrap();
1102        assert_eq!(run_notice.cause.as_deref(), Some(stop.id.as_str()));
1103        let sem_run_while_running = crate::notice_semantics::attention(
1104            tmp.path(),
1105            Some(&task),
1106            Some(&state.id),
1107            &run_notice,
1108        )
1109        .unwrap();
1110
1111        let hold = build_hold(&task, &state, stop.clone(), None);
1112        hold.apply(&mut task);
1113        queue.put(&mut task).unwrap();
1114        let held_notice = notices::task_held(&task).unwrap();
1115        assert_eq!(held_notice.cause.as_deref(), Some(stop.id.as_str()));
1116
1117        let sem_held = crate::notice_semantics::attention(
1118            tmp.path(),
1119            Some(&task),
1120            Some(&state.id),
1121            &held_notice,
1122        )
1123        .unwrap();
1124        let sem_run_after_hold = crate::notice_semantics::attention(
1125            tmp.path(),
1126            Some(&task),
1127            Some(&state.id),
1128            &run_notice,
1129        )
1130        .unwrap();
1131        let sem_outcome = crate::notice_semantics::outcome(tmp.path(), &task);
1132
1133        assert_eq!(sem_run_while_running, sem_held);
1134        assert_eq!(sem_held, sem_run_after_hold);
1135        assert_eq!(sem_held, sem_outcome);
1136
1137        // A separate admission failure on the same retained run must not
1138        // inherit the earlier E2E delivery receipt.
1139        let mut disk_held = task.clone();
1140        disk_held.release_operator("cli", None);
1141        disk_held.hold_machine(Some("disk capacity unavailable".into()));
1142        disk_held.mark_disk_capacity();
1143        let disk_outcome = crate::notice_semantics::outcome(tmp.path(), &disk_held);
1144        assert!(!crate::notice_semantics::covers(
1145            &sem_outcome,
1146            &disk_outcome
1147        ));
1148        let disk_notice = notices::task_held(&disk_held).unwrap();
1149        let disk_attention = crate::notice_semantics::attention(
1150            tmp.path(),
1151            Some(&disk_held),
1152            Some(&state.id),
1153            &disk_notice,
1154        )
1155        .unwrap();
1156        assert!(!crate::notice_semantics::covers(
1157            &sem_outcome,
1158            &disk_attention
1159        ));
1160
1161        // New pass reconsuming the same stop (and later held_at) still produces the same semantic receipt.
1162        state.begin_pass();
1163        state.save_under(tmp.path()).unwrap();
1164        let sem_next_pass = crate::notice_semantics::outcome(tmp.path(), &task);
1165        assert!(crate::notice_semantics::covers(
1166            &sem_outcome,
1167            &sem_next_pass
1168        ));
1169
1170        // Distinct new failure (new head) produces a distinct receipt that is NOT covered.
1171        let mut new_head_state = state.clone();
1172        new_head_state.head_e2e.as_mut().unwrap().head =
1173            "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".into();
1174        new_head_state.save_under(tmp.path()).unwrap();
1175        let new_stop = conclusive(&new_head_state).unwrap();
1176        assert_ne!(new_stop.id, stop.id);
1177        let new_hold = build_hold(&task, &new_head_state, new_stop, None);
1178        new_hold.apply(&mut task);
1179        let sem_new_head = crate::notice_semantics::outcome(tmp.path(), &task);
1180        assert!(!crate::notice_semantics::covers(
1181            &sem_outcome,
1182            &sem_new_head
1183        ));
1184
1185        // Restore original stop and verify an actionable new Question is NEVER flattened.
1186        state.save_under(tmp.path()).unwrap();
1187        hold.apply(&mut task);
1188        let q = Question::new(
1189            task.id.clone(),
1190            "conduct".into(),
1191            "conductor".into(),
1192            "Need direction".into(),
1193            "Choose next step".into(),
1194            vec!["resume".into(), "hold".into()],
1195        );
1196        let sem_question = crate::notice_semantics::question(tmp.path(), &task, &state.id, &q);
1197        assert!(!crate::notice_semantics::covers(
1198            &sem_outcome,
1199            &sem_question
1200        ));
1201    }
1202
1203    #[test]
1204    fn standing_refusal_blocks_unchanged_and_permits_changed_head_or_base() {
1205        let tmp = tempfile::tempdir().unwrap();
1206        let (repo, wt, base, head) = init_repo_with_origin(tmp.path());
1207        let state = sample_blocked_state(&repo, &wt, &base, &head);
1208        let task = Task::new(
1209            "t".into(),
1210            "fix typography".into(),
1211            repo.clone(),
1212            Source::Human,
1213        );
1214
1215        let refused = standing_refusal(&task, &state).expect("unchanged must be refused");
1216        assert!(refused.contains("head-e2e:"));
1217        assert!(refused.contains("standing recovery"));
1218
1219        // Moving candidate HEAD permits standing recovery again.
1220        std::fs::write(wt.join("fix.txt"), "fix\n").unwrap();
1221        git_sync(&wt, &["add", "fix.txt"]);
1222        git_sync(&wt, &["commit", "-m", "fix"]);
1223        assert!(standing_refusal(&task, &state).is_none());
1224    }
1225}