1use 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
25pub const NOTICE_STAGE: &str = "head-e2e-stop";
28
29#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
35pub struct Stop {
36 pub id: String,
38 pub run: String,
40 pub head: String,
42 pub base: String,
44 pub generation: usize,
46 pub evidence: String,
48 #[serde(default, skip_serializing_if = "Option::is_none")]
50 pub recorded_at: Option<Timestamp>,
51 #[serde(default, skip_serializing_if = "Option::is_none")]
53 pub recorded_pass: Option<usize>,
54 #[serde(default, skip_serializing_if = "Option::is_none")]
56 pub recorded_events: Option<usize>,
57 #[serde(default, skip_serializing_if = "Option::is_none")]
59 pub resumption_generation: Option<u64>,
60}
61
62#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
67pub struct Resumption {
68 pub task: String,
70 pub stop_id: String,
72 pub generation: u64,
74 pub approval_at: Timestamp,
76}
77
78#[derive(Debug, Clone, PartialEq, Eq)]
80pub(crate) enum FactCheck {
81 Unchanged,
83 Changed(String),
85 Unreadable(String),
87}
88
89#[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 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#[derive(Debug, Clone)]
110pub(crate) enum AttemptGate {
111 Hold(HoldAction),
113 ConsumeOwnerApproval {
115 run: String,
116 stop_id: String,
117 generation: u64,
118 approval_at: Timestamp,
119 },
120}
121
122#[derive(Debug, Clone, Copy, PartialEq, Eq)]
124pub(crate) enum TriageStatus {
125 NotHeadE2e,
127 HoldStillActive,
129 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
150pub 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 let base = e2e
198 .base_commit
199 .as_deref()
200 .filter(|s| !s.is_empty())
201 .or_else(|| {
202 state
203 .base_sync
204 .as_ref()
205 .map(|s| s.tip.as_str())
206 .filter(|s| !s.is_empty())
207 })
208 .unwrap_or(&state.base_commit)
209 .to_owned();
210 let generation = e2e.generation.unwrap_or(state.verification_history.len());
211 let evidence = outcomes_fingerprint(&e2e.outcomes);
212 let id_input = serde_json::to_vec(&(&state.id, &e2e.head, &base, generation, &evidence))
213 .unwrap_or_default();
214 let id = format!("head-e2e:{}", &sha256_hex(&id_input)[..32]);
215 let recorded_at = e2e
216 .recorded_at
217 .or_else(|| {
218 state
219 .events
220 .iter()
221 .rev()
222 .find(|ev| ev.node == "e2e" && ev.message.contains(&e2e.head))
223 .map(|ev| ev.at)
224 })
225 .or(Some(state.updated_at));
226
227 Some(Stop {
228 id,
229 run: state.id.clone(),
230 head: e2e.head.clone(),
231 base,
232 generation,
233 evidence,
234 recorded_at,
235 recorded_pass: e2e.pass,
236 recorded_events: e2e.recorded_events,
237 resumption_generation: e2e.resumption_generation,
238 })
239}
240
241pub(crate) fn reconsumed_without_new_verification(state: &RunState, stop: &Stop) -> bool {
247 let (Some(current), Some(recorded_pass), Some(recorded_events)) = (
248 state.passes.last(),
249 stop.recorded_pass,
250 stop.recorded_events,
251 ) else {
252 return false;
253 };
254 recorded_pass < current.index && state.events.len() == recorded_events
255}
256
257fn git_rev_parse_sync(dir: &Path, rev: &str) -> Result<String, String> {
258 let output = std::process::Command::new("git")
259 .current_dir(dir)
260 .args(["rev-parse", "--verify", "--quiet", rev])
261 .quiet()
262 .output()
263 .map_err(|e| format!("git rev-parse {rev} in {}: {e}", dir.display()))?;
264 if !output.status.success() {
265 let stderr = String::from_utf8_lossy(&output.stderr).trim().to_owned();
266 return Err(if stderr.is_empty() {
267 format!("git rev-parse {rev} failed in {}", dir.display())
268 } else {
269 format!("git rev-parse {rev} failed in {}: {stderr}", dir.display())
270 });
271 }
272 let sha = String::from_utf8_lossy(&output.stdout).trim().to_owned();
273 if sha.is_empty() {
274 Err(format!("git rev-parse {rev} returned empty output"))
275 } else {
276 Ok(sha)
277 }
278}
279
280pub(crate) fn inspect_facts(task: &Task, state: &RunState, stop: &Stop) -> FactCheck {
284 if task.fresh_start {
285 return FactCheck::Changed("explicit fresh start requested".into());
286 }
287 if task.pr_recovery.is_some() {
288 return FactCheck::Changed("explicit PR recovery selection present".into());
289 }
290 if task.replacement.as_ref().is_some_and(|replacement| {
291 state.replaces.as_ref().is_none_or(|applied| {
292 applied.question != replacement.question
293 || applied.run != replacement.run
294 || applied.agent != replacement.agent
295 })
296 }) {
297 return FactCheck::Changed("new explicit replacement selection present".into());
298 }
299 if !crate::daemon::compatible_run_instruction(state, task) {
300 return FactCheck::Changed("task instruction changed".into());
301 }
302 if crate::repair_budget::pending(task, state) {
303 return FactCheck::Changed("pending repair grant present".into());
304 }
305
306 let Some(winner) = state.winner() else {
307 return FactCheck::Unreadable("retained winner record is missing".into());
308 };
309 let mut diagnostics = Vec::new();
310
311 if winner.worktree.exists() {
312 match git_rev_parse_sync(&winner.worktree, "HEAD") {
313 Ok(wt_head) if wt_head != stop.head => {
314 return FactCheck::Changed(format!(
315 "winner worktree HEAD moved from {} to {}",
316 short(&stop.head),
317 short(&wt_head)
318 ));
319 }
320 Ok(_) => {}
321 Err(err) => diagnostics.push(err),
322 }
323 } else {
324 diagnostics.push(format!(
325 "winner worktree {} is unavailable",
326 winner.worktree.display()
327 ));
328 }
329
330 let branch_ref = format!("refs/heads/{}", winner.branch);
331 match git_rev_parse_sync(&state.repo, &branch_ref) {
332 Ok(branch_head) if branch_head != stop.head => {
333 return FactCheck::Changed(format!(
334 "candidate branch {} moved from {} to {}",
335 winner.branch,
336 short(&stop.head),
337 short(&branch_head)
338 ));
339 }
340 Ok(_) => {}
341 Err(err) => diagnostics.push(err),
342 }
343
344 let tracking = format!(
345 "refs/remotes/{}/{}",
346 state.config.merge.remote, state.base_branch
347 );
348 let synchronized_base = state
352 .base_sync
353 .as_ref()
354 .filter(|sync| sync.conflict.is_none() && !sync.tip.is_empty())
355 .map_or(stop.base.as_str(), |sync| sync.tip.as_str());
356 match git_rev_parse_sync(&state.repo, &tracking) {
357 Ok(base_tip) if !synchronized_base.is_empty() && base_tip != synchronized_base => {
358 return FactCheck::Changed(format!(
359 "remote base {} moved from {} to {}",
360 tracking,
361 short(synchronized_base),
362 short(&base_tip)
363 ));
364 }
365 Ok(_) => {}
366 Err(err) => diagnostics.push(err),
367 }
368
369 if !diagnostics.is_empty() {
370 FactCheck::Unreadable(diagnostics.join("; "))
371 } else {
372 FactCheck::Unchanged
373 }
374}
375
376pub(crate) fn pending_owner_approval<'a>(
379 task: &'a Task,
380 state: &RunState,
381 stop: &Stop,
382) -> Option<&'a crate::queue::Resumption> {
383 let approval = task.resumption.as_ref()?;
384 if state
385 .head_e2e_resumptions
386 .iter()
387 .any(|r| r.task == task.id && r.generation >= approval.generation)
388 {
389 return None;
390 }
391 match stop.resumption_generation {
392 Some(recorded_gen) => (approval.generation > recorded_gen).then_some(approval),
393 None => stop
394 .recorded_at
395 .is_some_and(|at| approval.at > at)
396 .then_some(approval),
397 }
398}
399
400pub(crate) fn record_consumed_approval(
402 state: &mut RunState,
403 task_id: &str,
404 stop_id: &str,
405 generation: u64,
406 approval_at: Timestamp,
407) {
408 if state
409 .head_e2e_resumptions
410 .iter()
411 .any(|r| r.task == task_id && r.generation >= generation)
412 {
413 return;
414 }
415 state.head_e2e_resumptions.push(Resumption {
416 task: task_id.to_owned(),
417 stop_id: stop_id.to_owned(),
418 generation,
419 approval_at,
420 });
421}
422
423pub(crate) fn hold_reason(
425 task: &Task,
426 state: &RunState,
427 stop: &Stop,
428 read_diagnostic: Option<&str>,
429) -> String {
430 let failed_summary = state
431 .head_e2e
432 .as_ref()
433 .and_then(|e2e| e2e.outcomes.iter().find(|o| !o.ok() && !o.resource_blocked))
434 .map(|o| crate::stop_reason::command_failure("verify.e2e", o))
435 .unwrap_or_else(|| format!("verify.e2e failed on head {}", short(&stop.head)));
436 let base_note = if stop.base.is_empty() {
437 String::new()
438 } else {
439 format!(", base {}", short(&stop.base))
440 };
441 let read_note = read_diagnostic
442 .map(|diag| format!(" Repository check could not confirm a change ({diag})."))
443 .unwrap_or_default();
444 format!(
445 "[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.",
446 short(&stop.head),
447 stop.run,
448 stop.id,
449 state.config.merge.remote,
450 state.base_branch,
451 task.id,
452 stop.run,
453 )
454}
455
456fn load_latest_run(queue: &Queue, task: &Task) -> Option<RunState> {
457 let home = queue.root().parent()?;
458 let id = task.execution_runs().last()?;
459 RunState::load_under(id, home).ok().filter(|s| s.id == *id)
460}
461
462fn build_hold(
463 task: &Task,
464 state: &RunState,
465 stop: Stop,
466 read_diagnostic: Option<&str>,
467) -> HoldAction {
468 let reason = hold_reason(task, state, &stop, read_diagnostic);
469 let detail = state
470 .verification_blocking_cause()
471 .unwrap_or_else(|| format!("verify.e2e failed on head {}; nothing published", stop.head));
472 let diagnostic = crate::daemon::diagnostic_for(state);
473 HoldAction {
474 stop,
475 reason,
476 detail,
477 diagnostic,
478 }
479}
480
481pub(crate) fn dispatch_hold(queue: &Queue, task: &Task) -> Option<HoldAction> {
487 match check_attempt(queue, task) {
488 Some(AttemptGate::Hold(action)) => Some(action),
489 Some(AttemptGate::ConsumeOwnerApproval { .. }) | None => None,
490 }
491}
492
493pub(crate) fn check_attempt(queue: &Queue, task: &Task) -> Option<AttemptGate> {
495 let state = load_latest_run(queue, task)?;
496 let stop = conclusive(&state)?;
497 if task
498 .sync_only
499 .as_ref()
500 .is_some_and(|request| request.run == state.id)
501 {
502 return None;
503 }
504 let read_diagnostic = match inspect_facts(task, &state, &stop) {
505 FactCheck::Changed(_) => return None,
506 FactCheck::Unchanged => None,
507 FactCheck::Unreadable(diag) => Some(diag),
508 };
509 if let Some(approval) = pending_owner_approval(task, &state, &stop) {
510 return Some(AttemptGate::ConsumeOwnerApproval {
511 run: stop.run,
512 stop_id: stop.id,
513 generation: approval.generation,
514 approval_at: approval.at,
515 });
516 }
517 Some(AttemptGate::Hold(build_hold(
518 task,
519 &state,
520 stop,
521 read_diagnostic.as_deref(),
522 )))
523}
524
525pub(crate) fn blocks_automatic_recovery(queue: &Queue, task: &Task) -> bool {
529 let Some(state) = load_latest_run(queue, task) else {
530 return false;
531 };
532 let Some(stop) = conclusive(&state) else {
533 return false;
534 };
535 !matches!(inspect_facts(task, &state, &stop), FactCheck::Changed(_))
536}
537
538pub(crate) fn triage_status(queue: &Queue, task: &Task) -> TriageStatus {
540 if task.status != TaskStatus::Held
541 || task.hold_source != Some(HoldSource::Machine)
542 || !task.has_head_e2e_cause()
543 {
544 return TriageStatus::NotHeadE2e;
545 }
546 let Some(state) = load_latest_run(queue, task) else {
547 return TriageStatus::HoldStillActive;
548 };
549 if let Some(stop) = conclusive(&state) {
550 return match inspect_facts(task, &state, &stop) {
551 FactCheck::Changed(_) => TriageStatus::ResolvedChanged,
552 FactCheck::Unchanged | FactCheck::Unreadable(_) => TriageStatus::HoldStillActive,
553 };
554 }
555 if state.status.resumable()
556 && !state.base_sync_blocked()
557 && state.prep_failure.is_none()
558 && state.resource_block.is_none()
559 {
560 TriageStatus::ResolvedChanged
561 } else {
562 TriageStatus::NotHeadE2e
563 }
564}
565
566pub(crate) fn standing_refusal(task: &Task, state: &RunState) -> Option<String> {
569 let stop = conclusive(state)?;
570 match inspect_facts(task, state, &stop) {
571 FactCheck::Changed(_) => None,
572 FactCheck::Unchanged => Some(format!(
573 "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.",
574 stop.id,
575 short(&stop.head),
576 short(&stop.base),
577 state.config.merge.remote,
578 state.base_branch,
579 )),
580 FactCheck::Unreadable(diag) => Some(format!(
581 "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.",
582 stop.id,
583 )),
584 }
585}
586
587#[cfg(test)]
588mod tests {
589 use super::*;
590 use crate::ask::Question;
591 use crate::config::Config;
592 use crate::notices;
593 use crate::queue::{Queue, Source, Task};
594 use crate::run::{Candidate, CommandOutcome, GateRepairE2e, RunState, RunStatus, Tally};
595 use crate::talk::{Talks, seeded_for_test};
596
597 fn git_sync(dir: &Path, args: &[&str]) -> String {
598 let out = std::process::Command::new("git")
599 .current_dir(dir)
600 .args(args)
601 .env("GIT_AUTHOR_NAME", "test")
602 .env("GIT_AUTHOR_EMAIL", "test@example.com")
603 .env("GIT_COMMITTER_NAME", "test")
604 .env("GIT_COMMITTER_EMAIL", "test@example.com")
605 .output()
606 .expect("spawn git");
607 assert!(
608 out.status.success(),
609 "git {:?} failed: {}",
610 args,
611 String::from_utf8_lossy(&out.stderr)
612 );
613 String::from_utf8_lossy(&out.stdout).trim().to_owned()
614 }
615
616 fn init_repo_with_origin(
617 root: &Path,
618 ) -> (std::path::PathBuf, std::path::PathBuf, String, String) {
619 let origin = root.join("origin.git");
620 let repo = root.join("repo");
621 std::fs::create_dir_all(&origin).unwrap();
622 std::fs::create_dir_all(&repo).unwrap();
623 git_sync(&origin, &["init", "--bare", "-b", "main"]);
624 git_sync(&repo, &["init", "-b", "main"]);
625 std::fs::write(repo.join("README.md"), "base\n").unwrap();
626 git_sync(&repo, &["add", "README.md"]);
627 git_sync(&repo, &["commit", "-m", "initial"]);
628 let base_sha = git_sync(&repo, &["rev-parse", "HEAD"]);
629 git_sync(
630 &repo,
631 &["remote", "add", "origin", &origin.to_string_lossy()],
632 );
633 git_sync(&repo, &["push", "-u", "origin", "main"]);
634 git_sync(&repo, &["checkout", "-b", "feat/candidate"]);
635 std::fs::write(repo.join("change.txt"), "candidate\n").unwrap();
636 git_sync(&repo, &["add", "change.txt"]);
637 git_sync(&repo, &["commit", "-m", "candidate change"]);
638 let head_sha = git_sync(&repo, &["rev-parse", "HEAD"]);
639 git_sync(&repo, &["checkout", "main"]);
640 let wt = root.join("wt");
641 git_sync(
642 &repo,
643 &["worktree", "add", &wt.to_string_lossy(), "feat/candidate"],
644 );
645 (repo, wt, base_sha, head_sha)
646 }
647
648 fn failed_outcome(
649 command: &str,
650 code: Option<i32>,
651 tail: &str,
652 resource_blocked: bool,
653 ) -> CommandOutcome {
654 CommandOutcome {
655 command: command.into(),
656 code,
657 output_tail: tail.into(),
658 resource_blocked,
659 ..Default::default()
660 }
661 }
662
663 fn sample_blocked_state(repo: &Path, wt: &Path, base: &str, head: &str) -> RunState {
664 let mut cfg = Config::default();
665 cfg.graph.review_rounds = 0;
666 cfg.verify.e2e = vec!["cargo test --test typography".into()];
667 let mut state = RunState::new(
668 repo.to_path_buf(),
669 "main".into(),
670 base.into(),
671 "fix typography".into(),
672 cfg,
673 );
674 state.status = RunStatus::Blocked;
675 let candidate: Candidate = serde_json::from_value(serde_json::json!({
676 "index": 0,
677 "label": "A",
678 "agent": "existing",
679 "branch": "feat/candidate",
680 "worktree": wt,
681 "commits": 1,
682 }))
683 .unwrap();
684 state.candidates.push(candidate);
685 state.tally = Some(
686 serde_json::from_value::<Tally>(serde_json::json!({
687 "first_choice": {"A": 1},
688 "borda": {"A": 1},
689 "winner": "A",
690 "unanimous_initial": true,
691 "deliberated": false,
692 "changed_votes": 0,
693 "unanimous_final": true,
694 }))
695 .unwrap(),
696 );
697 state.begin_pass();
698 let mut e2e = GateRepairE2e::new(
699 head.into(),
700 false,
701 vec![failed_outcome(
702 "cargo test --test typography",
703 Some(1),
704 "test typo_spec ... FAILED",
705 false,
706 )],
707 );
708 e2e.base_commit = Some(base.into());
709 e2e.generation = Some(0);
710 e2e.pass = Some(0);
711 e2e.recorded_at = Some(Timestamp::now());
712 e2e.resumption_generation = Some(0);
713 state.event(
714 "e2e",
715 format!("verify.e2e failed on head {head}; nothing published"),
716 );
717 e2e.recorded_events = Some(state.events.len());
718 state.head_e2e = Some(e2e);
719 state
720 }
721
722 #[test]
723 fn conclusive_excludes_inconclusive_resource_other_stops_and_active_repairs() {
724 let tmp = tempfile::tempdir().unwrap();
725 let (repo, wt, base, head) = init_repo_with_origin(tmp.path());
726 let base_state = sample_blocked_state(&repo, &wt, &base, &head);
727 assert!(conclusive(&base_state).is_some());
728
729 let mut s = base_state.clone();
731 s.head_e2e.as_mut().unwrap().outcomes[0].resource_blocked = true;
732 assert!(conclusive(&s).is_none());
733
734 let mut s = base_state.clone();
736 s.head_e2e.as_mut().unwrap().outcomes.clear();
737 assert!(conclusive(&s).is_none());
738
739 let mut s = base_state.clone();
741 s.head_e2e.as_mut().unwrap().passed = true;
742 assert!(conclusive(&s).is_none());
743
744 let mut s = base_state.clone();
746 s.parked = true;
747 assert!(conclusive(&s).is_none());
748
749 let mut s = base_state.clone();
751 s.resource_block = Some(crate::run::ResourceBlock {
752 cause: crate::run::ResourceBlockCause::Other,
753 node: "e2e".into(),
754 kind: "shared build cache".into(),
755 detail: "busy".into(),
756 at: Timestamp::now(),
757 });
758 assert!(conclusive(&s).is_none());
759
760 let mut s = base_state.clone();
762 s.base_sync = Some(crate::run::BaseSync {
763 tip: base.clone(),
764 behind: 1,
765 attempts: 1,
766 conflict: Some("conflict".into()),
767 already_in: None,
768 });
769 assert!(conclusive(&s).is_none());
770
771 let mut s = base_state.clone();
773 s.prep_failure = Some("setup failed".into());
774 assert!(conclusive(&s).is_none());
775
776 let mut s = base_state.clone();
778 s.gate_ran = true;
779 s.gate = vec![failed_outcome(
780 "cargo make check",
781 Some(1),
782 "lint failed",
783 false,
784 )];
785 assert!(conclusive(&s).is_none());
786
787 let mut s = base_state.clone();
789 s.repair_grants.push(crate::repair_budget::Applied {
790 receipt: crate::repair_budget::Receipt {
791 request: crate::repair_budget::Request {
792 task: "t".into(),
793 run: s.id.clone(),
794 kind: crate::repair_budget::Kind::Gate,
795 rounds: 1,
796 head: head.clone(),
797 expect_pass: 0,
798 request: "req-1".into(),
799 reason: "repair".into(),
800 tip: None,
801 instruction: None,
802 replace_request: None,
803 evidence_digest: None,
804 },
805 at: Timestamp::now(),
806 decision: None,
807 contract: String::new(),
808 stop: None,
809 legacy: None,
810 },
811 spent: 0,
812 phase: crate::repair_budget::Phase::Pending,
813 review_start: 0,
814 head: head.clone(),
815 succeeded: false,
816 conflict: None,
817 });
818 assert!(conclusive(&s).is_none());
819 }
820
821 #[test]
822 fn stop_identity_ignores_pass_time_duration_and_prose_and_tracks_evidence() {
823 let tmp = tempfile::tempdir().unwrap();
824 let (repo, wt, base, head) = init_repo_with_origin(tmp.path());
825 let s1 = sample_blocked_state(&repo, &wt, &base, &head);
826 let stop1 = conclusive(&s1).unwrap();
827
828 let mut s2 = s1.clone();
830 s2.begin_pass();
831 s2.head_e2e.as_mut().unwrap().pass = Some(5);
832 s2.head_e2e.as_mut().unwrap().recorded_at = Some(
833 Timestamp::now()
834 .checked_add(jiff::SignedDuration::from_hours(2))
835 .unwrap(),
836 );
837 s2.head_e2e.as_mut().unwrap().outcomes[0].duration_ms = 999_999;
838 s2.event("e2e", "rephrased prose");
839 let stop2 = conclusive(&s2).unwrap();
840 assert_eq!(stop1.id, stop2.id);
841
842 let mut diff_head = s1.clone();
844 diff_head.head_e2e.as_mut().unwrap().head =
845 "1111111111111111111111111111111111111111".into();
846 assert_ne!(conclusive(&diff_head).unwrap().id, stop1.id);
847
848 let mut diff_base = s1.clone();
849 diff_base.head_e2e.as_mut().unwrap().base_commit =
850 Some("2222222222222222222222222222222222222222".into());
851 assert_ne!(conclusive(&diff_base).unwrap().id, stop1.id);
852
853 let mut diff_gen = s1.clone();
854 diff_gen.head_e2e.as_mut().unwrap().generation = Some(1);
855 assert_ne!(conclusive(&diff_gen).unwrap().id, stop1.id);
856
857 let mut diff_cmd = s1.clone();
858 diff_cmd.head_e2e.as_mut().unwrap().outcomes[0].command = "cargo test --test other".into();
859 assert_ne!(conclusive(&diff_cmd).unwrap().id, stop1.id);
860
861 let mut diff_out = s1.clone();
862 diff_out.head_e2e.as_mut().unwrap().outcomes[0].output_tail = "different failure".into();
863 assert_ne!(conclusive(&diff_out).unwrap().id, stop1.id);
864 }
865
866 #[test]
867 fn reconsumption_detection_is_exact_and_conservative_on_legacy() {
868 let tmp = tempfile::tempdir().unwrap();
869 let (repo, wt, base, head) = init_repo_with_origin(tmp.path());
870 let mut state = sample_blocked_state(&repo, &wt, &base, &head);
871 let stop = conclusive(&state).unwrap();
872 assert!(!reconsumed_without_new_verification(&state, &stop));
873
874 let mut legacy = state.clone();
876 legacy.begin_pass();
877 legacy.head_e2e.as_mut().unwrap().pass = None;
878 let legacy_stop = conclusive(&legacy).unwrap();
879 assert!(!reconsumed_without_new_verification(&legacy, &legacy_stop));
880
881 state.begin_pass();
883 let stop = conclusive(&state).unwrap();
884 assert!(reconsumed_without_new_verification(&state, &stop));
885
886 state.event("e2e", "fresh verification event");
888 let stop = conclusive(&state).unwrap();
889 assert!(!reconsumed_without_new_verification(&state, &stop));
890 }
891
892 #[test]
893 fn inspect_facts_detects_head_base_and_repair_changes_and_refuses_unreadable() {
894 let tmp = tempfile::tempdir().unwrap();
895 let (repo, wt, base, head) = init_repo_with_origin(tmp.path());
896 let state = sample_blocked_state(&repo, &wt, &base, &head);
897 let stop = conclusive(&state).unwrap();
898 let task = Task::new(
899 "t".into(),
900 "fix typography".into(),
901 repo.clone(),
902 Source::Human,
903 );
904
905 assert_eq!(inspect_facts(&task, &state, &stop), FactCheck::Unchanged);
906
907 std::fs::write(repo.join("base2.txt"), "moved\n").unwrap();
909 git_sync(&repo, &["add", "base2.txt"]);
910 git_sync(&repo, &["commit", "-m", "advance base"]);
911 git_sync(&repo, &["push", "origin", "main"]);
912 assert!(matches!(
913 inspect_facts(&task, &state, &stop),
914 FactCheck::Changed(msg) if msg.contains("remote base")
915 ));
916
917 git_sync(&repo, &["reset", "--hard", &base]);
919 git_sync(&repo, &["push", "--force", "origin", "main"]);
920 assert_eq!(inspect_facts(&task, &state, &stop), FactCheck::Unchanged);
921
922 std::fs::write(wt.join("change2.txt"), "fix\n").unwrap();
924 git_sync(&wt, &["add", "change2.txt"]);
925 git_sync(&wt, &["commit", "-m", "fix candidate"]);
926 assert!(matches!(
927 inspect_facts(&task, &state, &stop),
928 FactCheck::Changed(msg) if msg.contains("HEAD moved")
929 ));
930
931 git_sync(&wt, &["reset", "--hard", &head]);
933 assert_eq!(inspect_facts(&task, &state, &stop), FactCheck::Unchanged);
934 let mut missing_base = state.clone();
935 missing_base.base_branch = "nonexistent-base".into();
936 assert!(matches!(
937 inspect_facts(&task, &missing_base, &stop),
938 FactCheck::Unreadable(_)
939 ));
940 }
941
942 #[test]
943 fn dispatch_and_triage_respect_explicit_sync_and_hold_ownership() {
944 let tmp = tempfile::tempdir().unwrap();
945 let (repo, wt, base, head) = init_repo_with_origin(tmp.path());
946 let mut state = sample_blocked_state(&repo, &wt, &base, &head);
947 let queue = Queue::at(tmp.path().join("queue"));
948 let mut task = Task::new(
949 "t".into(),
950 "fix typography".into(),
951 repo.clone(),
952 Source::Human,
953 );
954 task.start(state.id.clone());
955 let replacement = crate::merge_decision::Replacement {
956 question: "replacement".into(),
957 run: "previous".into(),
958 pr: "previous-pr".into(),
959 agent: "existing".into(),
960 context: String::new(),
961 };
962 task.replacement = Some(replacement.clone());
963 state.replaces = Some(replacement);
964 state.save_under(tmp.path()).unwrap();
965 let stop = conclusive(&state).unwrap();
966 let hold =
967 dispatch_hold(&queue, &task).expect("historical replacement is not new evidence");
968 hold.apply(&mut task);
969 assert_eq!(triage_status(&queue, &task), TriageStatus::HoldStillActive);
970 task.resume_head_e2e_wait();
971 task.sync_only = Some(crate::base_sync_only::Request {
972 run: state.id.clone(),
973 at: Timestamp::now(),
974 });
975 assert!(dispatch_hold(&queue, &task).is_none());
976 task.sync_only = None;
977 assert!(dispatch_hold(&queue, &task).is_some());
978
979 git_sync(&repo, &["update-ref", "refs/remotes/origin/main", &head]);
980 task.hold_machine(Some("disk capacity unavailable".into()));
981 task.mark_disk_capacity();
982 assert_eq!(triage_status(&queue, &task), TriageStatus::NotHeadE2e);
983 build_hold(&task, &state, stop, None).apply(&mut task);
984 assert_eq!(triage_status(&queue, &task), TriageStatus::ResolvedChanged);
985 }
986
987 #[test]
988 fn conductor_preserves_independent_question_on_unchanged_stop() {
989 let tmp = tempfile::tempdir().unwrap();
990 let (repo, wt, base, head) = init_repo_with_origin(tmp.path());
991 let mut state = sample_blocked_state(&repo, &wt, &base, &head);
992 state.save_under(tmp.path()).unwrap();
993 let queue = Queue::at(tmp.path().join("queue"));
994 let questions = crate::ask::Questions::at(tmp.path().join("questions"));
995 let mut task = Task::new("t".into(), "fix typography".into(), repo, Source::Human);
996 task.start(state.id.clone());
997 dispatch_hold(&queue, &task).unwrap().apply(&mut task);
998 queue.put(&mut task).unwrap();
999 crate::conduct::apply(
1000 &queue,
1001 &questions,
1002 &crate::conduct::Verdict {
1003 decisions: vec![crate::conduct::Decision {
1004 id: task.id.clone(),
1005 blocked_by: Vec::new(),
1006 missing_dependencies: Vec::new(),
1007 reason: Some("Independent scope decision".into()),
1008 recovery: Some(crate::conduct::Recovery::Hold),
1009 question: Some("Should the scope include another component?".into()),
1010 choices: vec!["hold".into()],
1011 actions: Default::default(),
1012 question_decision: None,
1013 evidence: Vec::new(),
1014 }],
1015 },
1016 )
1017 .unwrap();
1018 let blocked = queue.get(&task.id).unwrap();
1019 assert_eq!(blocked.status, TaskStatus::Blocked);
1020 let question = questions.get(&blocked.blocked_by[0]).unwrap();
1021 assert!(question.status.open());
1022 assert_eq!(
1023 question.summary,
1024 "Should the scope include another component?"
1025 );
1026 }
1027
1028 #[test]
1029 fn notice_semantics_unifies_run_ended_task_held_and_outcome_for_same_stop() {
1030 let tmp = tempfile::tempdir().unwrap();
1031 let (repo, wt, base, head) = init_repo_with_origin(tmp.path());
1032 let mut state = sample_blocked_state(&repo, &wt, &base, &head);
1033 state.save_under(tmp.path()).unwrap();
1034 let stop = conclusive(&state).unwrap();
1035
1036 let talks = Talks::at(tmp.path().join("talks"));
1037 let mut chat = seeded_for_test("chat-1", repo.clone());
1038 talks.put(&mut chat).unwrap();
1039
1040 let queue = Queue::at(tmp.path().join("queue"));
1041 let mut task = Task::new(
1042 "typography".into(),
1043 "fix typography".into(),
1044 repo.clone(),
1045 Source::Agent {
1046 run: chat.id.clone(),
1047 node: crate::queue::CHAT_NODE.into(),
1048 },
1049 );
1050 task.start(state.id.clone());
1051 let run_notice = notices::run_ended(&state).unwrap();
1053 assert_eq!(run_notice.cause.as_deref(), Some(stop.id.as_str()));
1054 let sem_run_while_running = crate::notice_semantics::attention(
1055 tmp.path(),
1056 Some(&task),
1057 Some(&state.id),
1058 &run_notice,
1059 )
1060 .unwrap();
1061
1062 let hold = build_hold(&task, &state, stop.clone(), None);
1063 hold.apply(&mut task);
1064 queue.put(&mut task).unwrap();
1065 let held_notice = notices::task_held(&task).unwrap();
1066 assert_eq!(held_notice.cause.as_deref(), Some(stop.id.as_str()));
1067
1068 let sem_held = crate::notice_semantics::attention(
1069 tmp.path(),
1070 Some(&task),
1071 Some(&state.id),
1072 &held_notice,
1073 )
1074 .unwrap();
1075 let sem_run_after_hold = crate::notice_semantics::attention(
1076 tmp.path(),
1077 Some(&task),
1078 Some(&state.id),
1079 &run_notice,
1080 )
1081 .unwrap();
1082 let sem_outcome = crate::notice_semantics::outcome(tmp.path(), &task);
1083
1084 assert_eq!(sem_run_while_running, sem_held);
1085 assert_eq!(sem_held, sem_run_after_hold);
1086 assert_eq!(sem_held, sem_outcome);
1087
1088 let mut disk_held = task.clone();
1091 disk_held.release_operator("cli", None);
1092 disk_held.hold_machine(Some("disk capacity unavailable".into()));
1093 disk_held.mark_disk_capacity();
1094 let disk_outcome = crate::notice_semantics::outcome(tmp.path(), &disk_held);
1095 assert!(!crate::notice_semantics::covers(
1096 &sem_outcome,
1097 &disk_outcome
1098 ));
1099 let disk_notice = notices::task_held(&disk_held).unwrap();
1100 let disk_attention = crate::notice_semantics::attention(
1101 tmp.path(),
1102 Some(&disk_held),
1103 Some(&state.id),
1104 &disk_notice,
1105 )
1106 .unwrap();
1107 assert!(!crate::notice_semantics::covers(
1108 &sem_outcome,
1109 &disk_attention
1110 ));
1111
1112 state.begin_pass();
1114 state.save_under(tmp.path()).unwrap();
1115 let sem_next_pass = crate::notice_semantics::outcome(tmp.path(), &task);
1116 assert!(crate::notice_semantics::covers(
1117 &sem_outcome,
1118 &sem_next_pass
1119 ));
1120
1121 let mut new_head_state = state.clone();
1123 new_head_state.head_e2e.as_mut().unwrap().head =
1124 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".into();
1125 new_head_state.save_under(tmp.path()).unwrap();
1126 let new_stop = conclusive(&new_head_state).unwrap();
1127 assert_ne!(new_stop.id, stop.id);
1128 let new_hold = build_hold(&task, &new_head_state, new_stop, None);
1129 new_hold.apply(&mut task);
1130 let sem_new_head = crate::notice_semantics::outcome(tmp.path(), &task);
1131 assert!(!crate::notice_semantics::covers(
1132 &sem_outcome,
1133 &sem_new_head
1134 ));
1135
1136 state.save_under(tmp.path()).unwrap();
1138 hold.apply(&mut task);
1139 let q = Question::new(
1140 task.id.clone(),
1141 "conduct".into(),
1142 "conductor".into(),
1143 "Need direction".into(),
1144 "Choose next step".into(),
1145 vec!["resume".into(), "hold".into()],
1146 );
1147 let sem_question = crate::notice_semantics::question(tmp.path(), &task, &state.id, &q);
1148 assert!(!crate::notice_semantics::covers(
1149 &sem_outcome,
1150 &sem_question
1151 ));
1152 }
1153
1154 #[test]
1155 fn standing_refusal_blocks_unchanged_and_permits_changed_head_or_base() {
1156 let tmp = tempfile::tempdir().unwrap();
1157 let (repo, wt, base, head) = init_repo_with_origin(tmp.path());
1158 let state = sample_blocked_state(&repo, &wt, &base, &head);
1159 let task = Task::new(
1160 "t".into(),
1161 "fix typography".into(),
1162 repo.clone(),
1163 Source::Human,
1164 );
1165
1166 let refused = standing_refusal(&task, &state).expect("unchanged must be refused");
1167 assert!(refused.contains("head-e2e:"));
1168 assert!(refused.contains("standing recovery"));
1169
1170 std::fs::write(wt.join("fix.txt"), "fix\n").unwrap();
1172 git_sync(&wt, &["add", "fix.txt"]);
1173 git_sync(&wt, &["commit", "-m", "fix"]);
1174 assert!(standing_refusal(&task, &state).is_none());
1175 }
1176}