1use std::collections::{BTreeSet, HashMap};
28use std::fmt;
29use std::future::Future;
30use std::path::{Path, PathBuf};
31use std::pin::Pin;
32use std::process::{Command, Stdio};
33use std::time::{Duration, Instant};
34
35use anyhow::{Context as _, Result, bail};
36use serde::Deserialize;
37
38use crate::agent;
39use crate::config::Config;
40use crate::prompt;
41
42use crate::land::PrLifecycle;
43use crate::proc::Quiet as _;
44use crate::queue::{Queue, Task, TaskStatus};
45use crate::run::RunStatus;
46
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
49pub enum Signal {
50 Branch,
52 Sha,
54 Pr,
56}
57
58#[derive(Debug, Clone, PartialEq, Eq)]
60pub enum Owner {
61 Task,
63 Run,
65 Pr,
67}
68
69#[derive(Debug, Clone, PartialEq, Eq)]
71pub struct Hit {
72 pub owner: Owner,
74 pub id: String,
76 pub status: String,
78 pub signal: Signal,
80 pub token: String,
82 pub via: String,
84 pub about: String,
87}
88
89impl fmt::Display for Hit {
90 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91 let kind = match self.owner {
92 Owner::Task => "task",
93 Owner::Run => "run",
94 Owner::Pr => "pull request",
95 };
96 let what = match self.signal {
97 Signal::Branch => "names branch",
98 Signal::Sha => "names commit",
99 Signal::Pr => "names pull request",
100 };
101 write!(
102 f,
103 "{kind} {} ({}): this work {what} {}, {}",
104 crate::queue::short(&self.id),
105 self.status,
106 self.token,
107 self.via
108 )
109 }
110}
111
112#[derive(Debug, Clone)]
114pub struct Duplicate {
115 pub hits: Vec<Hit>,
117 pub judge: Option<String>,
120}
121
122impl Duplicate {
123 pub fn new(hits: Vec<Hit>) -> Self {
125 Self { hits, judge: None }
126 }
127
128 pub fn render(&self, override_hint: &str) -> String {
130 let mut out = String::from("this looks like work that is already in flight:");
131 for h in &self.hits {
132 out.push_str("\n - ");
133 out.push_str(&h.to_string());
134 }
135 if let Some(j) = &self.judge {
136 out.push('\n');
137 out.push_str(j);
138 }
139 out.push('\n');
140 out.push_str(override_hint);
141 out
142 }
143}
144
145impl fmt::Display for Duplicate {
146 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
147 f.write_str(&self.render(
148 "If it is not a duplicate, pass --force to file it anyway \
149 (an agent should report this to the operator instead).",
150 ))
151 }
152}
153
154impl std::error::Error for Duplicate {}
155
156#[derive(Debug, Clone, PartialEq, Eq)]
158pub struct Judgement {
159 pub duplicate: bool,
161 pub reason: String,
163 pub agent: String,
165}
166
167#[derive(Debug, Clone, PartialEq, Eq)]
169pub enum Screened {
170 Clean,
172 Cleared(Judgement),
174 Unjudged(String),
176}
177
178pub type JudgeFuture = Pin<Box<dyn Future<Output = Result<Judgement>> + Send>>;
181
182const JUDGE_BUDGET: Duration = Duration::from_secs(45);
184const JUDGE_TURN: Duration = Duration::from_secs(30);
186
187fn parse_judgement(text: &str) -> Result<(bool, String)> {
191 #[derive(Deserialize)]
192 struct Raw {
193 duplicate: bool,
194 reason: String,
195 }
196 let mut body = text.trim();
200 if let Some(rest) = body.strip_prefix("```") {
201 let rest = rest.strip_prefix("json").unwrap_or(rest);
202 body = rest.trim().strip_suffix("```").unwrap_or(rest).trim();
203 }
204 let raw: Raw =
205 serde_json::from_str(body).context("the judge's reply is not a single JSON object")?;
206 let reason = raw.reason.split_whitespace().collect::<Vec<_>>().join(" ");
207 if reason.is_empty() {
208 bail!("the judge gave no reason");
209 }
210 Ok((raw.duplicate, reason.chars().take(300).collect()))
211}
212
213pub async fn chain_judge(
218 cfg: &Config,
219 repo: &Path,
220 instruction: String,
221 hits: Vec<Hit>,
222) -> Result<Judgement> {
223 let chain = agent::pick_chain(
224 &cfg.agents,
225 cfg.roles
226 .dupes_judge
227 .as_ref()
228 .or(cfg.roles.chatter.as_ref()),
229 &agent::installed,
230 "dupes_judge",
231 )?;
232 let claims: Vec<(String, String)> = hits
233 .iter()
234 .map(|h| (h.to_string(), h.about.clone()))
235 .collect();
236 let body = prompt::dupes_judge(&instruction, &claims);
237 let artifacts = std::env::temp_dir().join(format!("magi-dupes-{:016x}", crate::rng::entropy()));
238 let started = Instant::now();
239 let mut last: anyhow::Error = anyhow::anyhow!("no judge agent ran");
240 let mut result = None;
241 for spec in &chain {
242 let left = JUDGE_BUDGET.saturating_sub(started.elapsed());
243 if left.is_zero() {
244 break;
245 }
246 let mut seat = agent::SeatState::new("dupes", &spec.id, crate::rng::entropy());
247 let inv = agent::Invocation {
248 coordination: cfg.coordination.as_ref(),
249 fetched_base: None,
250 cwd: repo,
251 prompt: &body,
252 timeout: left.min(JUDGE_TURN),
253 allow_write: false,
254 sessions: false,
255 artifacts: &artifacts,
256 stem: &format!("judge-{}", spec.id),
257 run: "dupes",
258 node: "dupes",
259 cache_dir: None,
260 attachments: &[],
261 writable: &[],
262 };
263 let out = agent::invoke(spec, &mut seat, &inv).await;
264 if agent::chain_advances(&out) {
265 last = match out {
266 Err(e) => e.context(format!("judge `{}` failed", spec.id)),
267 Ok(o) => anyhow::anyhow!(
268 "judge `{}` gave no usable reply ({})",
269 spec.id,
270 crate::notices::turn_status(o.exit_code, o.timed_out, o.quota_exhausted())
271 ),
272 };
273 continue;
274 }
275 result = Some(
276 out.and_then(|o| parse_judgement(&o.text))
277 .map(|(duplicate, reason)| Judgement {
278 duplicate,
279 reason,
280 agent: spec.id.clone(),
281 }),
282 );
283 break;
284 }
285 let _ = std::fs::remove_dir_all(&artifacts);
286 result.unwrap_or(Err(last))
287}
288
289pub async fn screen(
304 hits: Vec<Hit>,
305 text: &str,
306 review_branch: Option<&str>,
307 judge: &(dyn Fn(String, Vec<Hit>) -> JudgeFuture + Sync),
308) -> Result<Screened, Duplicate> {
309 if hits.is_empty() {
310 return Ok(Screened::Clean);
311 }
312 let unjudged = |why: String| {
313 tracing::warn!(hits = hits.len(), %why, "duplicate check: judgement unavailable, letting the work through");
314 Ok(Screened::Unjudged(why))
315 };
316 let mut subject = squeeze(text, prompt::DUPES_JUDGE_MAX_CHARS);
317 if let Some(b) = review_branch {
318 if !subject.is_empty() {
319 subject.push_str("\n\n");
320 }
321 subject.push_str(&format!(
322 "(This is a review-only request for branch `{b}`: it would do work on that branch.)"
323 ));
324 }
325 match judge(subject, hits.clone()).await {
326 Ok(j) if !j.duplicate => {
327 tracing::info!(
328 agent = %j.agent,
329 reason = %j.reason,
330 hits = hits.len(),
331 "duplicate check: the judge says this is not duplicate work"
332 );
333 Ok(Screened::Cleared(j))
334 }
335 Ok(j) => Err(Duplicate {
336 hits,
337 judge: Some(format!("judge ({}): duplicate - {}", j.agent, j.reason)),
338 }),
339 Err(e) => unjudged(format!("{e:#}")),
340 }
341}
342
343pub async fn screen_with_config(
346 hits: Vec<Hit>,
347 text: &str,
348 review_branch: Option<&str>,
349 repo: &Path,
350 cfg: Option<&Config>,
351) -> Result<Screened, Duplicate> {
352 let judge = |instruction: String, hits: Vec<Hit>| -> JudgeFuture {
353 let cfg = cfg.cloned();
354 let repo = repo.to_path_buf();
355 Box::pin(async move {
356 match cfg {
357 Some(cfg) => {
358 let dir = repo.clone();
359 let hits = tokio::task::spawn_blocking(move || {
360 let mut hits = hits;
361 describe_forge_hits(&dir, &mut hits);
362 hits
363 })
364 .await
365 .context("describing the pull request")?;
366 chain_judge(&cfg, &repo, instruction, hits).await
367 }
368 None => bail!("no readable configuration to resolve a judge agent from"),
369 }
370 })
371 };
372 screen(hits, text, review_branch, &judge).await
373}
374
375#[derive(Debug, Default, Deserialize)]
378struct RunView {
379 #[serde(default)]
380 id: String,
381 #[serde(default)]
382 repo: PathBuf,
383 #[serde(default)]
384 status: String,
385 #[serde(default)]
386 base_commit: String,
387 #[serde(default)]
388 instruction: String,
389 #[serde(default)]
390 candidates: Vec<CandView>,
391 #[serde(default)]
392 foreign_checkout: Option<CandView>,
393 #[serde(default)]
394 pr: Option<PrView>,
395 #[serde(default)]
397 released_to: Option<String>,
398 #[serde(default)]
399 pr_head: Option<String>,
400 #[serde(default)]
401 pr_taken_over_by: Option<String>,
402 #[serde(default)]
403 stale_public_pr: Option<crate::run::StalePublicPr>,
404 #[serde(default)]
405 origin: Option<OriginView>,
406 #[serde(default)]
407 pr_pushed_head: Option<String>,
408}
409
410#[derive(Debug, Deserialize)]
411struct OriginView {
412 #[serde(default)]
413 task: Option<String>,
414}
415
416#[derive(Debug, Default, Deserialize)]
417struct CandView {
418 #[serde(default)]
419 branch: String,
420}
421
422#[derive(Debug, Default, Deserialize)]
423struct PrView {
424 #[serde(default)]
425 url: String,
426 #[serde(default)]
427 number: u64,
428 #[serde(default)]
429 state: String,
430}
431
432impl RunView {
433 fn read(runs_root: &Path, id: &str) -> Option<Self> {
434 let raw = std::fs::read_to_string(runs_root.join(id).join("run.json")).ok()?;
435 serde_json::from_str(&raw).ok()
436 }
437
438 fn terminal(&self) -> bool {
441 serde_json::from_value::<RunStatus>(serde_json::Value::String(self.status.clone()))
442 .map(RunStatus::done)
443 .unwrap_or(false)
444 }
445
446 fn pr_open(&self) -> bool {
447 self.pr.as_ref().is_some_and(|p| p.state == "open")
448 }
449}
450
451struct Staleness<'a> {
468 runs_root: &'a Path,
469 lookup: &'a dyn Fn(&Path, u64) -> Option<PrLifecycle>,
470 cache: HashMap<u64, bool>,
471 asked: usize,
472 failed: bool,
473}
474
475const MAX_FORGE_LOOKUPS: usize = 5;
478
479impl<'a> Staleness<'a> {
480 fn new(runs_root: &'a Path, lookup: &'a dyn Fn(&Path, u64) -> Option<PrLifecycle>) -> Self {
481 Self {
482 runs_root,
483 lookup,
484 cache: HashMap::new(),
485 asked: 0,
486 failed: false,
487 }
488 }
489
490 fn pr_released(&mut self, repo: &Path, view: &RunView) -> bool {
493 if let Some(next) = &view.pr_taken_over_by
494 && next != &view.id
495 && RunView::read(self.runs_root, next).is_some()
496 {
497 return true;
498 }
499 let Some(pr) = view.pr.as_ref().filter(|p| p.state == "open") else {
500 return false;
501 };
502 if let Some(next) = &view.released_to
503 && next != &view.id
504 && RunView::read(self.runs_root, next).is_some()
505 {
506 return true;
507 }
508 if pr.number == 0 {
509 return false;
510 }
511 if let Some(known) = self.cache.get(&pr.number) {
512 return *known;
513 }
514 if self.failed || self.asked >= MAX_FORGE_LOOKUPS {
515 return false;
516 }
517 self.asked += 1;
518 let settled = match (self.lookup)(repo, pr.number) {
519 Some(PrLifecycle::Merged | PrLifecycle::Closed) => true,
520 Some(PrLifecycle::Open) => false,
521 None => {
522 self.failed = true;
523 false
524 }
525 };
526 self.cache.insert(pr.number, settled);
527 settled
528 }
529}
530
531#[derive(Debug, Clone)]
533struct Claim {
534 owner: Owner,
535 id: String,
536 status: String,
537 via: String,
538 about: String,
540 branch: Option<String>,
541 base: Option<String>,
543 pr: Option<(u64, String)>,
545}
546
547pub fn check(
551 queue: &Queue,
552 runs_root: &Path,
553 repo: &Path,
554 text: &str,
555 review_branch: Option<&str>,
556 ignore_task: Option<&str>,
557) -> Vec<Hit> {
558 check_with(
559 queue,
560 runs_root,
561 repo,
562 text,
563 review_branch,
564 ignore_task,
565 &gh_open_pr,
566 &gh_pr_state,
567 )
568}
569
570#[allow(clippy::too_many_arguments)]
577pub fn check_with(
578 queue: &Queue,
579 runs_root: &Path,
580 repo: &Path,
581 text: &str,
582 review_branch: Option<&str>,
583 ignore_task: Option<&str>,
584 open_pr: &dyn Fn(&Path, u64) -> Option<String>,
585 pr_state: &dyn Fn(&Path, u64) -> Option<PrLifecycle>,
586) -> Vec<Hit> {
587 let mut stale = Staleness::new(runs_root, pr_state);
588 let mut idents = Idents::default();
589 let here = idents.of(repo);
590 let tasks = queue.list();
591 let own_runs: BTreeSet<String> = tasks
592 .iter()
593 .filter(|t| Some(t.id.as_str()) == ignore_task)
594 .flat_map(|t| t.runs.iter().cloned())
595 .collect();
596 let own_prs: BTreeSet<u64> = own_runs
598 .iter()
599 .filter_map(|id| RunView::read(runs_root, id))
600 .filter(|v| idents.of(&v.repo) == here)
601 .filter_map(|v| v.pr.map(|p| p.number))
602 .collect();
603
604 let mut claims: Vec<Claim> = Vec::new();
605 let mut from_task: BTreeSet<String> = BTreeSet::new();
606 for t in tasks
607 .iter()
608 .filter(|t| t.status != TaskStatus::Done && Some(t.id.as_str()) != ignore_task)
609 .filter(|t| idents.of(&t.repo) == here)
610 {
611 claims.extend(task_claims(t, runs_root, &mut from_task, repo, &mut stale));
612 }
613 for id in crate::run::list_ids_in(runs_root) {
614 if own_runs.contains(&id) {
615 continue;
616 }
617 let Some(view) = RunView::read(runs_root, &id) else {
618 continue;
619 };
620 if from_task.contains(&id) && view.pr_head.is_some() {
623 continue;
624 }
625 if (view.terminal() && !view.pr_open()) || idents.of(&view.repo) != here {
626 continue;
627 }
628 let released = stale.pr_released(repo, &view);
629 if view.terminal() && released {
632 continue;
633 }
634 claims.extend(run_claims(
635 &view,
636 Owner::Run,
637 None,
638 "its own run",
639 !released,
640 ("", &view.instruction),
641 ));
642 }
643
644 let mut hits: Vec<Hit> = Vec::new();
645 let mut push = |c: &Claim, signal: Signal, token: String| {
646 let hit = Hit {
647 owner: c.owner.clone(),
648 id: c.id.clone(),
649 status: c.status.clone(),
650 signal,
651 token,
652 via: c.via.clone(),
653 about: c.about.clone(),
654 };
655 if !hits.contains(&hit) {
656 hits.push(hit);
657 }
658 };
659
660 let prs = pr_numbers(text);
661 let shas = sha_candidates(repo, text);
662 for c in &claims {
663 if let Some(b) = &c.branch {
664 if names_branch(text, b) || review_branch == Some(b.as_str()) {
665 push(c, Signal::Branch, b.clone());
666 }
667 if let Some(base) = &c.base {
668 for sha in &shas {
669 if on_branch_only(repo, sha, b, base) {
670 push(c, Signal::Sha, short_sha(sha));
671 }
672 }
673 }
674 }
675 if let Some((n, url)) = &c.pr {
676 if prs.contains(&Mention::Number(*n))
677 || prs.iter().any(|p| matches!(p, Mention::Url(u) if u == url))
678 {
679 push(c, Signal::Pr, format!("#{n}"));
680 }
681 }
682 }
683 let mut asked = BTreeSet::new();
684 for n in prs.iter().filter_map(|m| match m {
685 Mention::Number(n) => Some(*n),
686 Mention::Url(u) => u.rsplit('/').next().and_then(|d| d.parse().ok()),
687 }) {
688 let token = format!("#{n}");
689 if hits
690 .iter()
691 .any(|h| h.signal == Signal::Pr && h.token == token)
692 || own_prs.contains(&n)
693 || !asked.insert(n)
694 {
695 continue;
696 }
697 if let Some(url) = open_pr(repo, n) {
698 hits.push(Hit {
699 owner: Owner::Pr,
700 id: token.clone(),
701 status: "open".into(),
702 signal: Signal::Pr,
703 token,
704 via: format!("an open pull request with no run record here ({url})"),
705 about: String::new(),
706 });
707 }
708 }
709 hits
710}
711
712fn gh_open_pr(repo: &Path, n: u64) -> Option<String> {
717 let v = gh_pr_view(repo, n, "state,url")?;
718 (v["state"] == "OPEN")
719 .then(|| v["url"].as_str().map(str::to_owned))
720 .flatten()
721}
722
723fn gh_pr_state(repo: &Path, n: u64) -> Option<PrLifecycle> {
726 match gh_pr_view(repo, n, "state,url")?["state"].as_str()? {
727 "OPEN" => Some(PrLifecycle::Open),
728 "MERGED" => Some(PrLifecycle::Merged),
729 "CLOSED" => Some(PrLifecycle::Closed),
730 _ => None,
731 }
732}
733
734fn gh_pr_view(repo: &Path, n: u64, fields: &str) -> Option<serde_json::Value> {
735 let mut child = Command::new("gh")
736 .quiet()
737 .args(["pr", "view", &n.to_string(), "--json", fields])
738 .current_dir(repo)
739 .env_remove("GH_REPO")
740 .env("GH_PROMPT_DISABLED", "1")
741 .stdin(Stdio::null())
742 .stdout(Stdio::piped())
743 .stderr(Stdio::null())
744 .spawn()
745 .ok()?;
746 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
747 loop {
748 match child.try_wait().ok()? {
749 Some(status) if status.success() => break,
750 Some(_) => return None,
751 None if std::time::Instant::now() >= deadline => {
752 let _ = child.kill();
753 let _ = child.wait();
754 return None;
755 }
756 None => std::thread::sleep(std::time::Duration::from_millis(50)),
757 }
758 }
759 let mut raw = String::new();
760 std::io::Read::read_to_string(&mut child.stdout.take()?, &mut raw).ok()?;
761 serde_json::from_str(&raw).ok()
762}
763
764fn describe_forge_hits(repo: &Path, hits: &mut [Hit]) {
769 for h in hits
770 .iter_mut()
771 .filter(|h| h.owner == Owner::Pr && h.about.is_empty())
772 {
773 let Some(n) = h.token.trim_start_matches('#').parse::<u64>().ok() else {
774 continue;
775 };
776 if let Some(v) = gh_pr_view(repo, n, "title,body") {
777 h.about = about_of(
778 v["title"].as_str().unwrap_or(""),
779 v["body"].as_str().unwrap_or(""),
780 );
781 }
782 }
783}
784
785fn squeeze(s: &str, max: usize) -> String {
789 let n = s.chars().count();
790 if n <= max {
791 return s.to_owned();
792 }
793 let half = max / 2;
794 let head: String = s.chars().take(half).collect();
795 let tail: String = s.chars().skip(n - half).collect();
796 format!(
797 "{head}\n[... {} characters omitted ...]\n{tail}",
798 n - 2 * half
799 )
800}
801
802fn about_of(title: &str, instruction: &str) -> String {
807 let body = instruction.split_whitespace().collect::<Vec<_>>().join(" ");
808 let title = title.trim();
809 let full = match (title.is_empty(), body.is_empty()) {
810 (true, _) => body,
811 (false, true) => title.to_owned(),
812 (false, false) => format!("{title}: {body}"),
813 };
814 squeeze(&full, ABOUT_MAX_CHARS)
815}
816
817const ABOUT_MAX_CHARS: usize = prompt::DUPES_JUDGE_MAX_CHARS;
821
822fn task_claims(
823 t: &Task,
824 runs_root: &Path,
825 seen: &mut BTreeSet<String>,
826 repo: &Path,
827 stale: &mut Staleness<'_>,
828) -> Vec<Claim> {
829 let status = t.status.as_str().to_owned();
830 let mut out = Vec::new();
831 if let Some(b) = &t.review_branch {
832 out.push(Claim {
833 owner: Owner::Task,
834 id: t.id.clone(),
835 status: status.clone(),
836 via: "its review branch".into(),
837 about: about_of(&t.title, &t.instruction),
838 branch: Some(b.clone()),
839 base: None,
840 pr: None,
841 });
842 }
843 let mut idents = Idents::default();
844 let here = idents.of(repo);
845 for rid in &t.runs {
846 if let Some(view) = RunView::read(runs_root, rid) {
847 if idents.of(&view.repo) != here {
850 continue;
851 }
852 seen.insert(rid.clone());
853 let live_pr = !(view.terminal() && stale.pr_released(repo, &view));
856 if view.terminal() && !live_pr && view.pr_taken_over_by.is_some() {
857 continue;
858 }
859 out.extend(run_claims(
860 &view,
861 Owner::Task,
862 Some((&t.id, &status)),
863 &format!("produced by its run {}", crate::queue::short(rid)),
864 live_pr,
865 (&t.title, &t.instruction),
866 ));
867 }
868 }
869 out
870}
871
872fn run_claims(
877 view: &RunView,
878 owner: Owner,
879 task: Option<(&str, &str)>,
880 via: &str,
881 live_pr: bool,
882 (title, instruction): (&str, &str),
883) -> Vec<Claim> {
884 let about = about_of(title, instruction);
885 let (id, status) = match task {
886 Some((id, status)) => (id.to_owned(), status.to_owned()),
887 None => (view.id.clone(), view.status.clone()),
888 };
889 let pr = view
890 .pr
891 .as_ref()
892 .filter(|p| live_pr && p.state == "open" && p.number > 0)
893 .map(|p| (p.number, p.url.clone()));
894 let via_pr = |extra: &str| match &pr {
895 Some((n, url)) => {
896 let task_id = task
897 .map(|(id, _)| id)
898 .or_else(|| view.origin.as_ref()?.task.as_deref());
899 let head = view
900 .stale_public_pr
901 .as_ref()
902 .map(|p| p.head.as_str())
903 .or(view.pr_pushed_head.as_deref());
904 let recovery = match (task_id, head) {
905 (Some(task), Some(head)) if view.status == "ready" => format!(
906 "; recover with `{}`",
907 crate::land::stale_pr_recovery_command(task, url, head)
908 ),
909 _ => String::new(),
910 };
911 format!("{via} (PR #{n} open){extra}{recovery}")
912 }
913 None => format!("{via}{extra}"),
914 };
915 let mut out: Vec<Claim> = view
916 .candidates
917 .iter()
918 .chain(view.foreign_checkout.iter())
919 .filter(|c| !c.branch.is_empty())
920 .map(|c| Claim {
921 owner: owner.clone(),
922 id: id.clone(),
923 status: status.clone(),
924 via: via_pr(""),
925 about: about.clone(),
926 branch: Some(c.branch.clone()),
927 base: (!view.base_commit.is_empty()).then(|| view.base_commit.clone()),
928 pr: None,
929 })
930 .collect();
931 let settled = view
934 .pr
935 .as_ref()
936 .is_some_and(|p| p.state == "merged" || p.state == "closed");
937 if live_pr
938 && !settled
939 && let Some(branch) = &view.pr_head
940 {
941 out.push(Claim {
942 owner: owner.clone(),
943 id: id.clone(),
944 status: status.clone(),
945 via: via_pr(""),
946 about: about.clone(),
947 branch: Some(branch.clone()),
948 base: None,
949 pr: None,
950 });
951 }
952 if pr.is_some() {
953 out.push(Claim {
954 owner,
955 id,
956 status,
957 via: via_pr(""),
958 about,
959 branch: None,
960 base: None,
961 pr,
962 });
963 }
964 out
965}
966
967#[test]
968fn stale_ready_owner_claim_names_recovery_control() {
969 let view: RunView = serde_json::from_value(serde_json::json!({
970 "status": "ready",
971 "pr": {"url": "https://github.com/o/r/pull/4", "number": 4, "state": "open"},
972 "origin": {"task": "task-id"},
973 "stale_public_pr": {"head": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "state": "conflicting"}
974 }))
975 .unwrap();
976 let claims = run_claims(&view, Owner::Run, None, "existing run", true, ("", ""));
977 let claim = claims.iter().find(|claim| claim.pr.is_some()).unwrap();
978 assert!(claim.via.contains("magi task recover-pr task-id --pr https://github.com/o/r/pull/4 --head aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa --disposition land"));
979}
980
981#[derive(Default)]
984struct Idents(HashMap<PathBuf, PathBuf>);
985
986impl Idents {
987 fn of(&mut self, path: &Path) -> PathBuf {
988 self.0
989 .entry(path.to_path_buf())
990 .or_insert_with(|| {
991 git(
992 path,
993 &["rev-parse", "--path-format=absolute", "--git-common-dir"],
994 )
995 .map(PathBuf::from)
996 .and_then(|p| p.canonicalize().ok())
997 .or_else(|| path.canonicalize().ok())
998 .unwrap_or_else(|| path.to_path_buf())
999 })
1000 .clone()
1001 }
1002}
1003
1004fn git(cwd: &Path, args: &[&str]) -> Option<String> {
1005 let out = Command::new("git")
1006 .quiet()
1007 .args(args)
1008 .current_dir(cwd)
1009 .stdin(Stdio::null())
1010 .stderr(Stdio::null())
1011 .env("GIT_TERMINAL_PROMPT", "0")
1012 .output()
1013 .ok()?;
1014 out.status
1015 .success()
1016 .then(|| String::from_utf8_lossy(&out.stdout).trim().to_owned())
1017}
1018
1019fn git_ok(cwd: &Path, args: &[&str]) -> bool {
1020 git(cwd, args).is_some()
1021}
1022
1023fn is_ref_char(c: char) -> bool {
1024 c.is_alphanumeric() || matches!(c, '_' | '-')
1025}
1026
1027fn names_branch(text: &str, branch: &str) -> bool {
1031 if branch.len() < 3 {
1032 return false;
1033 }
1034 text.match_indices(branch).any(|(i, _)| {
1035 let before = text[..i].chars().next_back();
1036 let after = text[i + branch.len()..].chars().next();
1037 let after_ok = match after {
1038 None => true,
1039 Some('/') => false,
1040 Some('.') => !text[i + branch.len() + 1..]
1041 .chars()
1042 .next()
1043 .is_some_and(is_ref_char),
1044 Some(c) => !is_ref_char(c),
1045 };
1046 before.is_none_or(|c| !is_ref_char(c) && c != '.') && after_ok
1047 })
1048}
1049
1050#[derive(Debug, PartialEq, Eq)]
1051enum Mention {
1052 Number(u64),
1053 Url(String),
1054}
1055
1056fn pr_numbers(text: &str) -> Vec<Mention> {
1058 let mut out = Vec::new();
1059 let bytes = text.as_bytes();
1060 let digits = |from: usize| -> Option<(u64, usize)> {
1061 let n = text[from..].bytes().take_while(u8::is_ascii_digit).count();
1062 (n > 0 && n < 10)
1063 .then(|| text[from..from + n].parse().ok().map(|v| (v, from + n)))
1064 .flatten()
1065 };
1066 for (i, _) in text.match_indices('#') {
1067 if let Some((n, _)) = digits(i + 1) {
1068 let word_before = i > 0 && is_ref_char(bytes[i - 1] as char);
1069 if !word_before {
1070 out.push(Mention::Number(n));
1071 }
1072 }
1073 }
1074 let lower = text.to_ascii_lowercase();
1075 for key in ["pull request ", "pr "] {
1076 for (i, _) in lower.match_indices(key) {
1077 if i > 0 && is_ref_char(bytes[i - 1] as char) {
1078 continue;
1079 }
1080 let from = i + key.len();
1081 let from = if text[from..].starts_with('#') {
1082 from + 1
1083 } else {
1084 from
1085 };
1086 if let Some((n, _)) = digits(from) {
1087 out.push(Mention::Number(n));
1088 }
1089 }
1090 }
1091 for (i, _) in text.match_indices("/pull/") {
1092 if let Some((_, end)) = digits(i + 6) {
1093 let start = text[..i]
1094 .rfind(|c: char| c.is_whitespace() || matches!(c, '(' | '<' | '"' | '\''))
1095 .map_or(0, |p| p + 1);
1096 out.push(Mention::Url(text[start..end].to_owned()));
1097 }
1098 }
1099 out
1100}
1101
1102fn sha_candidates(repo: &Path, text: &str) -> Vec<String> {
1104 let mut seen = BTreeSet::new();
1105 let mut out = Vec::new();
1106 for word in text.split(|c: char| !c.is_ascii_alphanumeric()) {
1107 if !(7..=40).contains(&word.len()) || !word.bytes().all(|b| b.is_ascii_hexdigit()) {
1108 continue;
1109 }
1110 if seen.len() >= 16 || !seen.insert(word.to_ascii_lowercase()) {
1111 continue;
1112 }
1113 if let Some(full) = git(
1114 repo,
1115 &[
1116 "rev-parse",
1117 "--verify",
1118 "--quiet",
1119 &format!("{word}^{{commit}}"),
1120 ],
1121 ) {
1122 out.push(full);
1123 }
1124 }
1125 out
1126}
1127
1128fn on_branch_only(repo: &Path, sha: &str, branch: &str, base: &str) -> bool {
1131 let tip = format!("{branch}^{{commit}}");
1132 git_ok(repo, &["rev-parse", "--verify", "--quiet", &tip])
1133 && git_ok(repo, &["merge-base", "--is-ancestor", sha, branch])
1134 && !git_ok(repo, &["merge-base", "--is-ancestor", sha, base])
1135}
1136
1137fn short_sha(sha: &str) -> String {
1138 sha.chars().take(7).collect()
1139}
1140
1141#[cfg(test)]
1142mod tests {
1143 use super::*;
1144 use crate::queue::{Source, Task};
1145
1146 #[cfg(unix)]
1147 fn judge_agent(id: &str, fails: bool) -> crate::config::AgentSpec {
1148 crate::config::AgentSpec {
1149 id: id.to_owned(),
1150 kind: crate::config::AgentKind::Command,
1151 model: None,
1152 command: vec![
1153 "sh".into(),
1154 "-c".into(),
1155 format!(
1156 "echo {id} >> calls; {}",
1157 if fails {
1158 "exit 1"
1159 } else {
1160 r#"printf '%s' '{"duplicate":false,"reason":"different work"}'"#
1161 }
1162 ),
1163 ],
1164 extra_args: Vec::new(),
1165 env: Default::default(),
1166 prompt_delivery: None,
1167 max_turn_secs: None,
1168 }
1169 }
1170
1171 #[cfg(unix)]
1172 fn judge_config() -> Config {
1173 let mut cfg = Config {
1174 agents: vec![
1175 judge_agent("chat", false),
1176 judge_agent("dedicated", false),
1177 judge_agent("failed", true),
1178 ],
1179 ..Config::default()
1180 };
1181 cfg.roles.chatter = Some("chat".into());
1182 cfg
1183 }
1184
1185 #[cfg(unix)]
1186 #[tokio::test]
1187 async fn dupes_judge_overrides_chatter() {
1188 let dir = tempfile::tempdir().unwrap();
1189 let mut cfg = judge_config();
1190 cfg.roles.dupes_judge = Some("dedicated".into());
1191 let verdict = chain_judge(&cfg, dir.path(), "task".into(), vec![])
1192 .await
1193 .unwrap();
1194 assert_eq!(verdict.agent, "dedicated");
1195 assert!(!verdict.duplicate);
1196 assert_eq!(
1197 std::fs::read_to_string(dir.path().join("calls")).unwrap(),
1198 "dedicated\n"
1199 );
1200 assert_eq!(cfg.roles.chatter.as_ref().unwrap().ids(), ["chat"]);
1201 }
1202
1203 #[cfg(unix)]
1204 #[tokio::test]
1205 async fn dupes_judge_unset_inherits_chatter() {
1206 let dir = tempfile::tempdir().unwrap();
1207 let cfg = judge_config();
1208 let verdict = chain_judge(&cfg, dir.path(), "task".into(), vec![])
1209 .await
1210 .unwrap();
1211 assert_eq!(verdict.agent, "chat");
1212 assert_eq!(
1213 std::fs::read_to_string(dir.path().join("calls")).unwrap(),
1214 "chat\n"
1215 );
1216 }
1217
1218 #[cfg(unix)]
1219 #[tokio::test]
1220 async fn dupes_judge_dedicated_and_inherited_chains_advance_on_failure() {
1221 for dedicated in [true, false] {
1222 let dir = tempfile::tempdir().unwrap();
1223 let mut cfg = judge_config();
1224 let chain =
1225 crate::config::AgentChoice::Chain(vec!["failed".into(), "dedicated".into()]);
1226 if dedicated {
1227 cfg.roles.dupes_judge = Some(chain);
1228 } else {
1229 cfg.roles.chatter = Some(chain);
1230 }
1231 let verdict = chain_judge(&cfg, dir.path(), "task".into(), vec![])
1232 .await
1233 .unwrap();
1234 assert_eq!(verdict.agent, "dedicated");
1235 assert_eq!(
1236 std::fs::read_to_string(dir.path().join("calls")).unwrap(),
1237 "failed\ndedicated\n"
1238 );
1239 }
1240 }
1241
1242 #[cfg(unix)]
1243 #[tokio::test]
1244 async fn dupes_judge_unavailable_choice_does_not_inherit_chatter() {
1245 let dir = tempfile::tempdir().unwrap();
1246 let mut cfg = judge_config();
1247 cfg.roles.dupes_judge = Some("missing".into());
1248 let err = chain_judge(&cfg, dir.path(), "task".into(), vec![])
1249 .await
1250 .unwrap_err();
1251 assert!(err.to_string().contains("[roles] dupes_judge"), "{err}");
1252 assert!(!dir.path().join("calls").exists());
1253 }
1254
1255 #[cfg(unix)]
1256 #[tokio::test]
1257 async fn dupes_judge_empty_choice_uses_default_instead_of_chatter() {
1258 let dir = tempfile::tempdir().unwrap();
1259 let mut cfg = judge_config();
1260 cfg.roles.chatter = Some("dedicated".into());
1261 cfg.roles.dupes_judge = Some(crate::config::AgentChoice::Chain(vec![]));
1262 let verdict = chain_judge(&cfg, dir.path(), "task".into(), vec![])
1263 .await
1264 .unwrap();
1265 assert_eq!(
1266 verdict.agent, "chat",
1267 "the first roster agent is the default"
1268 );
1269 assert_eq!(
1270 std::fs::read_to_string(dir.path().join("calls")).unwrap(),
1271 "chat\n"
1272 );
1273 }
1274
1275 struct Fx {
1276 _tmp: tempfile::TempDir,
1277 repo: PathBuf,
1278 runs: PathBuf,
1279 q: Queue,
1280 }
1281
1282 fn sh(cwd: &Path, args: &[&str]) -> String {
1283 let out = Command::new("git")
1284 .quiet()
1285 .args(["-c", "user.name=t", "-c", "user.email=t@t"])
1286 .args(args)
1287 .current_dir(cwd)
1288 .output()
1289 .unwrap();
1290 assert!(out.status.success(), "git {args:?}: {out:?}");
1291 String::from_utf8_lossy(&out.stdout).trim().to_owned()
1292 }
1293
1294 fn fx() -> (Fx, String, String) {
1297 let tmp = tempfile::tempdir().unwrap();
1298 let repo = tmp.path().join("repo");
1299 std::fs::create_dir_all(&repo).unwrap();
1300 sh(&repo, &["init", "-q", "-b", "main"]);
1301 std::fs::write(repo.join("a"), "1").unwrap();
1302 sh(&repo, &["add", "."]);
1303 sh(&repo, &["commit", "-q", "-m", "base"]);
1304 let base = sh(&repo, &["rev-parse", "HEAD"]);
1305 sh(&repo, &["checkout", "-q", "-b", "magi/aaaa/A"]);
1306 std::fs::write(repo.join("a"), "2").unwrap();
1307 sh(&repo, &["commit", "-q", "-am", "work"]);
1308 let tip = sh(&repo, &["rev-parse", "HEAD"]);
1309 sh(&repo, &["checkout", "-q", "main"]);
1310 let runs = tmp.path().join("runs");
1311 std::fs::create_dir_all(&runs).unwrap();
1312 let q = Queue::at(tmp.path().join("queue"));
1313 (
1314 Fx {
1315 _tmp: tmp,
1316 repo,
1317 runs,
1318 q,
1319 },
1320 base,
1321 tip,
1322 )
1323 }
1324
1325 fn write_run(f: &Fx, id: &str, status: &str, base: &str, pr: Option<(u64, &str)>) {
1326 let dir = f.runs.join(id);
1327 std::fs::create_dir_all(&dir).unwrap();
1328 let pr = pr.map(|(n, s)| {
1329 serde_json::json!({"url": format!("https://github.com/o/r/pull/{n}"), "number": n, "state": s})
1330 });
1331 let v = serde_json::json!({
1332 "schema": 999, "id": id, "repo": f.repo, "status": status,
1333 "base_commit": base, "candidates": [{"branch": "magi/aaaa/A"}], "pr": pr,
1334 });
1335 std::fs::write(dir.join("run.json"), v.to_string()).unwrap();
1336 }
1337
1338 fn file_task(f: &Fx, status: TaskStatus, runs: &[&str]) -> Task {
1339 let mut t = Task::new("t".into(), "x".into(), f.repo.clone(), Source::Human);
1340 t.status = status;
1341 t.runs = runs.iter().map(|s| (*s).to_owned()).collect();
1342 f.q.put(&mut t).unwrap();
1343 t
1344 }
1345
1346 const RID: &str = "20260901-100000-aaaa";
1347
1348 fn run(f: &Fx, text: &str, review: Option<&str>) -> Vec<Hit> {
1349 check_with(
1350 &f.q,
1351 &f.runs,
1352 &f.repo,
1353 text,
1354 review,
1355 None,
1356 &|_, _| None,
1357 &|_, _| None,
1358 )
1359 }
1360
1361 #[test]
1362 fn branch_matches_a_live_run_and_its_task() {
1363 let (f, base, _) = fx();
1364 write_run(&f, RID, "reviewing", &base, None);
1365 let t = file_task(&f, TaskStatus::Running, &[RID]);
1366 let hits = run(&f, "land magi/aaaa/A onto a fresh branch.", None);
1367 assert!(hits.iter().any(|h| h.owner == Owner::Task
1368 && h.id == t.id
1369 && h.signal == Signal::Branch
1370 && h.token == "magi/aaaa/A"));
1371 assert!(hits.iter().any(|h| h.owner == Owner::Run && h.id == RID));
1372 let msg = Duplicate::new(hits).to_string();
1373 assert!(
1374 msg.contains("--force") && msg.contains("magi/aaaa/A"),
1375 "{msg}"
1376 );
1377 }
1378
1379 #[test]
1380 fn reassigned_history_keeps_original_claims_and_pr_numbers_are_repository_scoped() {
1381 let (f, base, _) = fx();
1382 write_run(&f, RID, "blocked", &base, Some((48, "open")));
1383 let mut task = file_task(&f, TaskStatus::Held, &[RID]);
1384 let other = f.repo.parent().unwrap().join("other-repository");
1385 std::fs::create_dir(&other).unwrap();
1386 task.repo = other.clone();
1387 f.q.put(&mut task).unwrap();
1388 let hits = check_with(
1389 &f.q,
1390 &f.runs,
1391 &other,
1392 "land magi/aaaa/A",
1393 None,
1394 None,
1395 &|_, _| None,
1396 &|_, _| Some(PrLifecycle::Open),
1397 );
1398 assert!(
1399 hits.is_empty(),
1400 "old branch must not be claimed in the destination: {hits:?}"
1401 );
1402 assert!(
1403 !run(&f, "land magi/aaaa/A", None).is_empty(),
1404 "history still claims the original repository"
1405 );
1406 let hits = check_with(
1407 &f.q,
1408 &f.runs,
1409 &other,
1410 "finish PR #48",
1411 None,
1412 Some(&task.id),
1413 &|_, _| Some("https://example.test/pull/48".into()),
1414 &|_, _| Some(PrLifecycle::Open),
1415 );
1416 assert!(
1417 hits.iter().any(|hit| hit.owner == Owner::Pr),
1418 "an unrelated destination PR cannot be ignored: {hits:?}"
1419 );
1420 }
1421
1422 #[test]
1423 fn branch_must_match_whole_word() {
1424 let (f, base, _) = fx();
1425 write_run(&f, RID, "reviewing", &base, None);
1426 assert!(run(&f, "see magi/aaaa/AB and magi/aaaa/A/x", None).is_empty());
1427 }
1428
1429 #[test]
1430 fn sha_on_the_branch_matches_but_one_in_base_does_not() {
1431 let (f, base, tip) = fx();
1432 write_run(&f, RID, "reviewing", &base, None);
1433 let hits = run(&f, &format!("land commit {} please", &tip[..8]), None);
1434 assert!(
1435 hits.iter().any(|h| h.signal == Signal::Sha && h.id == RID),
1436 "{hits:?}"
1437 );
1438 assert!(run(&f, &format!("see {}", &base[..9]), None).is_empty());
1439 assert!(run(&f, "deadbeef and 1234567", None).is_empty());
1441 }
1442
1443 #[test]
1444 fn pr_number_matches_in_every_spelling() {
1445 let (f, base, _) = fx();
1446 write_run(&f, RID, "ready", &base, Some((48, "open")));
1447 for text in [
1448 "finish #48",
1449 "PR 48 is stale",
1450 "pr #48",
1451 "pull request 48",
1452 "https://github.com/o/r/pull/48",
1453 ] {
1454 let hits = run(&f, text, None);
1455 assert!(
1456 hits.iter().any(|h| h.signal == Signal::Pr),
1457 "{text}: {hits:?}"
1458 );
1459 }
1460 assert!(run(&f, "see #480 and PR 4 and issue48", None).is_empty());
1461 }
1462
1463 #[test]
1464 fn terminal_runs_and_done_tasks_do_not_match() {
1465 let (f, base, tip) = fx();
1466 write_run(&f, RID, "merged", &base, Some((48, "merged")));
1467 file_task(&f, TaskStatus::Done, &[RID]);
1468 let text = format!("magi/aaaa/A {} #48", &tip[..8]);
1469 assert!(run(&f, &text, None).is_empty());
1470 }
1471
1472 #[test]
1473 fn terminal_run_with_open_pr_or_open_task_still_claims() {
1474 let (f, base, _) = fx();
1479 write_run(&f, RID, "ready", &base, Some((48, "open")));
1480 assert!(!run(&f, "magi/aaaa/A", None).is_empty());
1481 let (g, base, _) = fx();
1482 write_run(&g, RID, "ready", &base, None);
1483 assert!(run(&g, "magi/aaaa/A", None).is_empty());
1484 let t = file_task(&g, TaskStatus::Held, &[RID]);
1485 let hits = run(&g, "magi/aaaa/A", None);
1486 assert!(hits.iter().any(|h| h.id == t.id), "{hits:?}");
1487 }
1488
1489 #[test]
1490 fn review_only_matches_a_branch_a_live_task_owns() {
1491 let (f, base, _) = fx();
1492 write_run(&f, RID, "ready", &base, None);
1493 assert!(run(&f, "", Some("magi/aaaa/A")).is_empty());
1494 let mut t = file_task(&f, TaskStatus::Queued, &[]);
1495 t.review_branch = Some("magi/aaaa/A".into());
1496 f.q.put(&mut t).unwrap();
1497 let hits = run(&f, "", Some("magi/aaaa/A"));
1498 assert!(
1499 hits.iter()
1500 .any(|h| h.id == t.id && h.signal == Signal::Branch)
1501 );
1502 }
1503
1504 #[test]
1505 fn other_repository_and_edited_task_do_not_match() {
1506 let (f, base, _) = fx();
1507 write_run(&f, RID, "reviewing", &base, None);
1508 let t = file_task(&f, TaskStatus::Running, &[RID]);
1509 let other = f._tmp.path().join("other");
1510 std::fs::create_dir_all(&other).unwrap();
1511 sh(&other, &["init", "-q"]);
1512 assert!(
1513 check_with(
1514 &f.q,
1515 &f.runs,
1516 &other,
1517 "magi/aaaa/A",
1518 None,
1519 None,
1520 &|_, _| None,
1521 &|_, _| None,
1522 )
1523 .is_empty()
1524 );
1525 assert!(
1527 check_with(
1528 &f.q,
1529 &f.runs,
1530 &f.repo,
1531 "magi/aaaa/A",
1532 None,
1533 Some(&t.id),
1534 &|_, _| None,
1535 &|_, _| None,
1536 )
1537 .is_empty()
1538 );
1539 }
1540
1541 #[test]
1542 fn a_worktree_is_the_same_repository() {
1543 let (f, base, _) = fx();
1544 write_run(&f, RID, "reviewing", &base, None);
1545 let wt = f._tmp.path().join("wt");
1546 sh(
1547 &f.repo,
1548 &["worktree", "add", "-q", wt.to_str().unwrap(), "-b", "other"],
1549 );
1550 assert!(
1551 !check_with(
1552 &f.q,
1553 &f.runs,
1554 &wt,
1555 "magi/aaaa/A",
1556 None,
1557 None,
1558 &|_, _| None,
1559 &|_, _| None,
1560 )
1561 .is_empty()
1562 );
1563 }
1564
1565 #[test]
1566 fn an_open_pr_without_a_run_record_matches_through_the_forge() {
1567 let (f, _, _) = fx();
1568 let open = |_: &Path, n: u64| (n == 48).then(|| "https://example.test/pull/48".to_owned());
1569 let hit = |text: &str| {
1570 check_with(&f.q, &f.runs, &f.repo, text, None, None, &open, &|_, _| {
1571 None
1572 })
1573 };
1574 let hits = hit("finish PR #48");
1575 assert_eq!(hits.len(), 1, "{hits:?}");
1576 assert_eq!(hits[0].owner, Owner::Pr);
1577 assert!(hits[0].to_string().contains("#48"));
1578 assert!(hit("finish PR #49").is_empty());
1580 assert!(hit("finish the work").is_empty());
1581 }
1582
1583 #[test]
1584 fn a_forge_hit_does_not_repeat_a_pr_a_run_already_explains() {
1585 let (f, base, _) = fx();
1586 write_run(&f, RID, "ready", &base, Some((48, "open")));
1587 let open = |_: &Path, _: u64| Some("u".to_owned());
1588 let hits = check_with(&f.q, &f.runs, &f.repo, "#48", None, None, &open, &|_, _| {
1589 None
1590 });
1591 assert!(hits.iter().all(|h| h.owner != Owner::Pr), "{hits:?}");
1592 assert!(!hits.is_empty());
1593 }
1594
1595 #[test]
1596 fn an_edited_tasks_own_open_pr_is_not_a_forge_hit() {
1597 let (f, base, _) = fx();
1598 write_run(&f, RID, "ready", &base, Some((48, "open")));
1599 let t = file_task(&f, TaskStatus::Running, &[RID]);
1600 let open = |_: &Path, _: u64| Some("u".to_owned());
1601 let hits = check_with(
1602 &f.q,
1603 &f.runs,
1604 &f.repo,
1605 "#48",
1606 None,
1607 Some(&t.id),
1608 &open,
1609 &|_, _| None,
1610 );
1611 assert!(hits.is_empty(), "{hits:?}");
1612 }
1613
1614 fn with_forge(f: &Fx, text: &str, state: Option<PrLifecycle>) -> Vec<Hit> {
1615 check_with(
1616 &f.q,
1617 &f.runs,
1618 &f.repo,
1619 text,
1620 None,
1621 None,
1622 &|_, _| None,
1623 &move |_, _| state,
1624 )
1625 }
1626
1627 fn release(f: &Fx, id: &str, to: &str) {
1628 let path = f.runs.join(id).join("run.json");
1629 let mut v: serde_json::Value =
1630 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
1631 v["released_to"] = serde_json::json!(to);
1632 std::fs::write(path, v.to_string()).unwrap();
1633 }
1634
1635 #[test]
1636 fn a_task_public_head_and_pr_are_claimed_only_by_the_successor() {
1637 let (f, base, _) = fx();
1638 write_run(&f, RID, "blocked", &base, Some((48, "open")));
1639 let next = "20260901-000001-bbbb";
1640 write_run(&f, next, "landing", &base, Some((48, "open")));
1641 for id in [RID, next] {
1642 let path = f.runs.join(id).join("run.json");
1643 let mut value: serde_json::Value =
1644 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
1645 value["pr_head"] = serde_json::json!("magi/task-abcd-1234");
1646 if id == RID {
1647 value["pr_taken_over_by"] = serde_json::json!(next);
1648 }
1649 std::fs::write(path, value.to_string()).unwrap();
1650 }
1651 for text in ["update #48", "update magi/task-abcd-1234"] {
1652 let hits = with_forge(&f, text, Some(PrLifecycle::Open));
1653 assert!(!hits.is_empty());
1654 assert!(hits.iter().all(|h| h.id == next), "{hits:?}");
1655 }
1656 let task = file_task(&f, TaskStatus::Held, &[RID, next]);
1657 let hits = with_forge(&f, "update magi/task-abcd-1234", Some(PrLifecycle::Open));
1658 assert_eq!(hits.len(), 1, "{hits:?}");
1659 assert_eq!(hits[0].id, task.id);
1660 }
1661
1662 #[test]
1663 fn stale_open_pr_that_the_forge_says_is_merged_or_closed_does_not_claim() {
1664 for state in [PrLifecycle::Merged, PrLifecycle::Closed] {
1665 let (f, base, _) = fx();
1666 write_run(&f, RID, "superseded", &base, Some((48, "open")));
1667 assert!(with_forge(&f, "follow up on #48", Some(state)).is_empty());
1668 assert!(with_forge(&f, "magi/aaaa/A", Some(state)).is_empty());
1669 file_task(&f, TaskStatus::Held, &[RID]);
1671 let hits = with_forge(&f, "follow up on #48", Some(state));
1672 assert!(hits.iter().all(|h| h.signal != Signal::Pr), "{hits:?}");
1673 }
1674 }
1675
1676 #[test]
1677 fn stale_open_pr_with_an_unreadable_forge_still_claims() {
1678 let (f, base, _) = fx();
1679 write_run(&f, RID, "superseded", &base, Some((48, "open")));
1680 let hits = with_forge(&f, "follow up on #48", None);
1681 assert!(hits.iter().any(|h| h.signal == Signal::Pr), "{hits:?}");
1682 }
1683
1684 #[test]
1685 fn a_genuinely_open_pr_still_claims() {
1686 let (f, base, _) = fx();
1687 write_run(&f, RID, "blocked", &base, Some((48, "open")));
1688 let hits = with_forge(&f, "follow up on #48", Some(PrLifecycle::Open));
1689 assert!(hits.iter().any(|h| h.signal == Signal::Pr), "{hits:?}");
1690 }
1691
1692 #[test]
1693 fn a_released_run_defers_to_its_successor_without_asking_the_forge() {
1694 let (f, base, _) = fx();
1695 let next = "20260901-110000-bbbb";
1696 write_run(&f, RID, "superseded", &base, Some((48, "open")));
1697 write_run(&f, next, "merged", &base, Some((48, "merged")));
1698 release(&f, RID, next);
1699 let asked = std::cell::Cell::new(0);
1700 let hits = check_with(
1701 &f.q,
1702 &f.runs,
1703 &f.repo,
1704 "follow up on #48",
1705 None,
1706 None,
1707 &|_, _| None,
1708 &|_, _| {
1709 asked.set(asked.get() + 1);
1710 None
1711 },
1712 );
1713 assert!(hits.is_empty(), "{hits:?}");
1714 assert_eq!(asked.get(), 0);
1715 std::fs::remove_dir_all(f.runs.join(next)).unwrap();
1717 let hits = with_forge(&f, "follow up on #48", None);
1718 assert!(hits.iter().any(|h| h.signal == Signal::Pr), "{hits:?}");
1719 }
1720
1721 #[test]
1722 fn forge_lookups_are_cached_and_stop_after_a_failure() {
1723 let (f, base, _) = fx();
1724 for (i, id) in ["20260901-100000-aaa1", "20260901-100000-aaa2"]
1725 .iter()
1726 .enumerate()
1727 {
1728 write_run(&f, id, "blocked", &base, Some((48 + i as u64, "open")));
1729 }
1730 let asked = std::cell::Cell::new(0);
1731 check_with(
1732 &f.q,
1733 &f.runs,
1734 &f.repo,
1735 "x",
1736 None,
1737 None,
1738 &|_, _| None,
1739 &|_, _| {
1740 asked.set(asked.get() + 1);
1741 None
1742 },
1743 );
1744 assert_eq!(
1745 asked.get(),
1746 1,
1747 "an unreadable forge is asked once, not per PR"
1748 );
1749 }
1750
1751 use std::sync::Arc;
1752 use std::sync::atomic::{AtomicUsize, Ordering};
1753
1754 fn verdict(duplicate: bool) -> Result<Judgement> {
1755 Ok(Judgement {
1756 duplicate,
1757 reason: "because".into(),
1758 agent: "j".into(),
1759 })
1760 }
1761
1762 fn judged(
1765 f: &Fx,
1766 text: &str,
1767 answer: impl Fn() -> Result<Judgement> + Send + Sync + 'static,
1768 ) -> (Result<Screened, Duplicate>, usize) {
1769 let calls = Arc::new(AtomicUsize::new(0));
1770 let seen = calls.clone();
1771 let judge = move |_: String, _: Vec<Hit>| -> JudgeFuture {
1772 seen.fetch_add(1, Ordering::SeqCst);
1773 let r = answer();
1774 Box::pin(async move { r })
1775 };
1776 let hits = run(f, text, None);
1777 let out = tokio::runtime::Builder::new_current_thread()
1778 .build()
1779 .unwrap()
1780 .block_on(screen(hits, text, None, &judge));
1781 (out, calls.load(Ordering::SeqCst))
1782 }
1783
1784 const NAMES: &str = "seen on magi/aaaa/A, which does not touch this file";
1785
1786 fn fx_with_run() -> Fx {
1787 let (f, base, _) = fx();
1788 write_run(&f, RID, "reviewing", &base, None);
1789 f
1790 }
1791
1792 #[test]
1793 fn a_no_ruling_lets_the_work_through() {
1794 let f = fx_with_run();
1795 let (out, calls) = judged(&f, NAMES, || verdict(false));
1796 assert!(matches!(out, Ok(Screened::Cleared(_))));
1797 assert_eq!(calls, 1);
1798 }
1799
1800 #[test]
1801 fn a_yes_ruling_refuses_and_says_why() {
1802 let f = fx_with_run();
1803 let (out, _) = judged(&f, NAMES, || verdict(true));
1804 let msg = out.unwrap_err().to_string();
1805 assert!(
1806 msg.contains("duplicate - because") && msg.contains("--force"),
1807 "{msg}"
1808 );
1809 assert!(msg.contains("magi/aaaa/A"), "{msg}");
1810 }
1811
1812 #[test]
1813 fn a_failing_judge_lets_it_through_unjudged() {
1814 let f = fx_with_run();
1815 let (out, calls) = judged(&f, NAMES, || Err(anyhow::anyhow!("quota")));
1816 match out {
1817 Ok(Screened::Unjudged(why)) => assert!(why.contains("quota"), "{why}"),
1818 other => panic!("{other:?}"),
1819 }
1820 assert_eq!(calls, 1);
1821 }
1822
1823 #[test]
1824 fn garbage_replies_do_not_parse() {
1825 assert!(parse_judgement("sure, go ahead").is_err());
1826 assert!(parse_judgement(r#"{"duplicate":"maybe","reason":"x"}"#).is_err());
1827 assert!(parse_judgement(r#"{"duplicate":false}"#).is_err());
1828 assert!(parse_judgement(r#"{"duplicate":false,"reason":" "}"#).is_err());
1829 let two = "{\"duplicate\":false,\"reason\":\"c\"}\n{\"duplicate\":true}";
1830 assert!(parse_judgement(two).is_err());
1831 assert!(parse_judgement("ok {\"duplicate\":false,\"reason\":\"c\"}").is_err());
1832 let (d, why) = parse_judgement("{\"duplicate\":true,\"reason\":\"same\\nPR\"}").unwrap();
1833 assert_eq!((d, why.as_str()), (true, "same PR"));
1834 }
1835
1836 #[test]
1837 fn a_text_too_long_is_squeezed_and_still_judged() {
1838 let f = fx_with_run();
1839 let long = format!("{NAMES} {}", "x".repeat(prompt::DUPES_JUDGE_MAX_CHARS));
1840 let (out, calls) = judged(&f, &long, || verdict(false));
1841 assert!(matches!(out, Ok(Screened::Cleared(_))));
1842 assert_eq!(calls, 1);
1843 }
1844
1845 #[test]
1846 fn no_hit_never_asks_the_judge() {
1847 let (f, _, _) = fx();
1848 let (out, calls) = judged(&f, "nothing named here", || verdict(true));
1849 assert_eq!(out.unwrap(), Screened::Clean);
1850 assert_eq!(calls, 0);
1851 }
1852
1853 #[test]
1854 fn without_a_config_a_hit_passes_unjudged() {
1855 let f = fx_with_run();
1856 let hits = run(&f, NAMES, None);
1857 let out = tokio::runtime::Builder::new_current_thread()
1858 .build()
1859 .unwrap()
1860 .block_on(screen_with_config(hits, NAMES, None, &f.repo, None));
1861 assert!(matches!(out, Ok(Screened::Unjudged(_))));
1862 }
1863
1864 #[test]
1865 fn about_carries_title_and_whole_instruction() {
1866 assert_eq!(
1867 about_of("Retries", "# Task\nFix auth\nretries"),
1868 "Retries: # Task Fix auth retries"
1869 );
1870 assert_eq!(about_of("", "x"), "x");
1871 let mid = format!("{} MIDDLE {}", "a ".repeat(2000), "b ".repeat(500));
1872 assert!(about_of("", &mid).contains("MIDDLE"));
1873 let long = format!("{} TAIL", "y ".repeat(5000));
1874 let a = about_of("", &long);
1875 assert!(a.ends_with("TAIL") && a.chars().count() < 6100, "{a}");
1876 }
1877}