Skip to main content

magi/
dupes.rs

1//! Duplicate-work detection at the moment work is filed.
2//!
3//! Two tasks once chased the same commit without knowing about each other: an
4//! open task and its open pull request already covered a change when a chat
5//! filed a second task that named the same branch and commit. Nothing at
6//! filing time said so. This module is that check, and it is deliberately
7//! small: **concrete identifiers only** - a branch name, a commit SHA, a pull
8//! request number - never text similarity. A false positive costs one
9//! `--force`; a false negative is the behaviour before this module existed.
10//!
11//! A *claim* is a thing an unfinished piece of work owns: the branches of its
12//! candidates and the pull request it opened. The claims come from
13//!
14//! - every task that is not `done`: its `review_branch`, and each run in
15//!   `Task::runs`;
16//! - every run that has not reached a terminal status;
17//! - every run that is terminal but whose pull request is still open (the
18//!   shape of the original accident: the run ended, the PR did not).
19//!
20//! Run records are read through a tolerant view rather than `RunState::load`:
21//! a schema bump must not turn into a silent false negative (the same lesson
22//! as `clean::fold_due`).
23//!
24//! Everything here is synchronous, read-only and takes its roots as
25//! arguments, so tests need no process-global home.
26
27use 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/// What kind of identifier matched.
48#[derive(Debug, Clone, Copy, PartialEq, Eq)]
49pub enum Signal {
50    /// A branch name.
51    Branch,
52    /// A commit SHA.
53    Sha,
54    /// A pull request number or URL.
55    Pr,
56}
57
58/// Who owns the thing that matched.
59#[derive(Debug, Clone, PartialEq, Eq)]
60pub enum Owner {
61    /// A queued task.
62    Task,
63    /// A recorded run.
64    Run,
65    /// A pull request the forge reports open that no record here owns.
66    Pr,
67}
68
69/// One reason a new piece of work looks like one already under way.
70#[derive(Debug, Clone, PartialEq, Eq)]
71pub struct Hit {
72    /// Task or run.
73    pub owner: Owner,
74    /// Full id of the task or run.
75    pub id: String,
76    /// The owner's status word (`queued`, `reviewing`, ...).
77    pub status: String,
78    /// What kind of identifier matched.
79    pub signal: Signal,
80    /// The identifier as it matched: a branch, a SHA, `#48`.
81    pub token: String,
82    /// How the owner is tied to it, e.g. `produced by its run c9eb`.
83    pub via: String,
84    /// The owner's title and instruction (collapsed, cut), for the
85    /// judge only: never shown in [`Display`]. Empty when no record has it.
86    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/// The refusal: one or more [`Hit`]s and nothing filed.
113#[derive(Debug, Clone)]
114pub struct Duplicate {
115    /// What matched.
116    pub hits: Vec<Hit>,
117    /// The judge's word, when one was asked: a ready-made line for the
118    /// refusal text. `None` when no judge ran.
119    pub judge: Option<String>,
120}
121
122impl Duplicate {
123    /// A refusal on the identifier match alone.
124    pub fn new(hits: Vec<Hit>) -> Self {
125        Self { hits, judge: None }
126    }
127
128    /// The refusal text, ending in how to override it.
129    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/// The judge's answer, with the agent that gave it.
157#[derive(Debug, Clone, PartialEq, Eq)]
158pub struct Judgement {
159    /// True when the new work is genuinely a duplicate of the matched claims.
160    pub duplicate: bool,
161    /// One line, as the agent wrote it.
162    pub reason: String,
163    /// Id of the agent that answered.
164    pub agent: String,
165}
166
167/// How [`screen`] let work through.
168#[derive(Debug, Clone, PartialEq, Eq)]
169pub enum Screened {
170    /// No identifier matched; no judge was asked.
171    Clean,
172    /// A match was found and the judge said it is not a duplicate.
173    Cleared(Judgement),
174    /// A match was found and nobody could judge it (the reason): let through.
175    Unjudged(String),
176}
177
178/// A judge: given the instruction and the matched claims, rules on them.
179/// Owned arguments, so a boxed future needs no borrow.
180pub type JudgeFuture = Pin<Box<dyn Future<Output = Result<Judgement>> + Send>>;
181
182/// Whole-chain wall-clock budget for the judge call.
183const JUDGE_BUDGET: Duration = Duration::from_secs(45);
184/// Per-agent cap inside that budget.
185const JUDGE_TURN: Duration = Duration::from_secs(30);
186
187/// Read the judge's reply. Strict: anything but one JSON object with a bool
188/// `duplicate` and a non-empty reason is an error (the caller lets the work
189/// through unjudged, see [`screen`]).
190fn parse_judgement(text: &str) -> Result<(bool, String)> {
191    #[derive(Deserialize)]
192    struct Raw {
193        duplicate: bool,
194        reason: String,
195    }
196    // The whole reply must be one object (optionally in a code fence): hunting
197    // for an object inside prose or a second answer could recover a verdict
198    // from a reply that is not itself a single valid one.
199    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
213/// Ask the `[roles] dupes_judge` chain, or inherit `chatter` when unset.
214/// With neither role set, use the default agent. Each agent is
215/// tried at most once, with a fresh seat; only an error, quota or unusable
216/// answer moves on. A usable answer that does not parse ends the chain.
217pub 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            cwd: repo,
249            prompt: &body,
250            timeout: left.min(JUDGE_TURN),
251            allow_write: false,
252            unsandboxed: false,
253            sessions: false,
254            artifacts: &artifacts,
255            stem: &format!("judge-{}", spec.id),
256            run: "dupes",
257            node: "dupes",
258            cache_dir: None,
259            attachments: &[],
260            writable: &[],
261        };
262        let out = agent::invoke(spec, &mut seat, &inv).await;
263        if agent::chain_advances(&out) {
264            last = match out {
265                Err(e) => e.context(format!("judge `{}` failed", spec.id)),
266                Ok(o) => anyhow::anyhow!(
267                    "judge `{}` gave no usable reply (exit {:?}, timed out {}, quota {})",
268                    spec.id,
269                    o.exit_code,
270                    o.timed_out,
271                    o.quota_exhausted()
272                ),
273            };
274            continue;
275        }
276        result = Some(
277            out.and_then(|o| parse_judgement(&o.text))
278                .map(|(duplicate, reason)| Judgement {
279                    duplicate,
280                    reason,
281                    agent: spec.id.clone(),
282                }),
283        );
284        break;
285    }
286    let _ = std::fs::remove_dir_all(&artifacts);
287    result.unwrap_or(Err(last))
288}
289
290/// The one decision point every caller shares. `hits` is [`check`]'s output:
291/// empty passes without the judge being asked. Otherwise the judge is asked
292/// once (a long text is squeezed to its head and tail first), and only a `duplicate: true` answer refuses (with its reason).
293///
294/// **Fail mode: open.** If the judge cannot answer (agent error, timeout,
295/// quota, unparseable reply, no readable config) the work is let through as [`Screened::Unjudged`] and a
296/// `tracing::warn` is logged; callers also say so on stderr. A mechanical
297/// match cannot tell "continue from PR #28" from a real duplicate, so refusing
298/// whenever the judge is away would bring back exactly the false positives the
299/// judge exists to remove. The cost is that a real duplicate slips through
300/// while no agent is available, which is why it is never silent.
301///
302/// For a review-only request `text` is empty, so `review_branch` is put in
303/// front of the judge as the thing the work is about.
304pub async fn screen(
305    hits: Vec<Hit>,
306    text: &str,
307    review_branch: Option<&str>,
308    judge: &(dyn Fn(String, Vec<Hit>) -> JudgeFuture + Sync),
309) -> Result<Screened, Duplicate> {
310    if hits.is_empty() {
311        return Ok(Screened::Clean);
312    }
313    let unjudged = |why: String| {
314        tracing::warn!(hits = hits.len(), %why, "duplicate check: judgement unavailable, letting the work through");
315        Ok(Screened::Unjudged(why))
316    };
317    let mut subject = squeeze(text, prompt::DUPES_JUDGE_MAX_CHARS);
318    if let Some(b) = review_branch {
319        if !subject.is_empty() {
320            subject.push_str("\n\n");
321        }
322        subject.push_str(&format!(
323            "(This is a review-only request for branch `{b}`: it would do work on that branch.)"
324        ));
325    }
326    match judge(subject, hits.clone()).await {
327        Ok(j) if !j.duplicate => {
328            tracing::info!(
329                agent = %j.agent,
330                reason = %j.reason,
331                hits = hits.len(),
332                "duplicate check: the judge says this is not duplicate work"
333            );
334            Ok(Screened::Cleared(j))
335        }
336        Ok(j) => Err(Duplicate {
337            hits,
338            judge: Some(format!("judge ({}): duplicate - {}", j.agent, j.reason)),
339        }),
340        Err(e) => unjudged(format!("{e:#}")),
341    }
342}
343
344/// [`screen`] with the production judge: `dupes_judge`, inheriting `chatter` when unset.
345/// No config (`None`) means no judge, so a hit is let through unjudged.
346pub async fn screen_with_config(
347    hits: Vec<Hit>,
348    text: &str,
349    review_branch: Option<&str>,
350    repo: &Path,
351    cfg: Option<&Config>,
352) -> Result<Screened, Duplicate> {
353    let judge = |instruction: String, hits: Vec<Hit>| -> JudgeFuture {
354        let cfg = cfg.cloned();
355        let repo = repo.to_path_buf();
356        Box::pin(async move {
357            match cfg {
358                Some(cfg) => {
359                    let dir = repo.clone();
360                    let hits = tokio::task::spawn_blocking(move || {
361                        let mut hits = hits;
362                        describe_forge_hits(&dir, &mut hits);
363                        hits
364                    })
365                    .await
366                    .context("describing the pull request")?;
367                    chain_judge(&cfg, &repo, instruction, hits).await
368                }
369                None => bail!("no readable configuration to resolve a judge agent from"),
370            }
371        })
372    };
373    screen(hits, text, review_branch, &judge).await
374}
375
376/// The slice of `run.json` this module needs. Every field is optional so a
377/// record from any schema still yields what it has.
378#[derive(Debug, Default, Deserialize)]
379struct RunView {
380    #[serde(default)]
381    id: String,
382    #[serde(default)]
383    repo: PathBuf,
384    #[serde(default)]
385    status: String,
386    #[serde(default)]
387    base_commit: String,
388    #[serde(default)]
389    instruction: String,
390    #[serde(default)]
391    candidates: Vec<CandView>,
392    #[serde(default)]
393    pr: Option<PrView>,
394    /// The run that took this one's worktree (and pull request) over.
395    #[serde(default)]
396    released_to: Option<String>,
397    #[serde(default)]
398    pr_head: Option<String>,
399    #[serde(default)]
400    pr_taken_over_by: Option<String>,
401}
402
403#[derive(Debug, Default, Deserialize)]
404struct CandView {
405    #[serde(default)]
406    branch: String,
407}
408
409#[derive(Debug, Default, Deserialize)]
410struct PrView {
411    #[serde(default)]
412    url: String,
413    #[serde(default)]
414    number: u64,
415    #[serde(default)]
416    state: String,
417}
418
419impl RunView {
420    fn read(runs_root: &Path, id: &str) -> Option<Self> {
421        let raw = std::fs::read_to_string(runs_root.join(id).join("run.json")).ok()?;
422        serde_json::from_str(&raw).ok()
423    }
424
425    /// An unknown status word counts as unfinished: claiming too much is the
426    /// cheap error here.
427    fn terminal(&self) -> bool {
428        serde_json::from_value::<RunStatus>(serde_json::Value::String(self.status.clone()))
429            .map(RunStatus::done)
430            .unwrap_or(false)
431    }
432
433    fn pr_open(&self) -> bool {
434        self.pr.as_ref().is_some_and(|p| p.state == "open")
435    }
436}
437
438/// Decides whether the pull request a run's record still calls open is in fact
439/// settled, so a stale record stops claiming it.
440///
441/// A record freezes the last state its land loop polled. A run that was handed
442/// over (`released_to`) or left blocked while another run landed the same pull
443/// request keeps saying `open` forever, so the record alone cannot be trusted
444/// to *keep* a claim alive. Two answers, cheapest first:
445///
446/// 1. a released run does not own the pull request any more: ownership follows
447///    `released_to`, and the successor's own record (read like any other run's)
448///    decides - provided that record is readable;
449/// 2. otherwise the forge is asked, once per number, at most
450///    [`MAX_FORGE_LOOKUPS`] numbers, and never again after one lookup failed
451///    (offline stays fast). Merged or closed means no claim; open, an error or
452///    a skipped lookup means the claim stands. Claiming too much is the cheap
453///    error.
454struct Staleness<'a> {
455    runs_root: &'a Path,
456    lookup: &'a dyn Fn(&Path, u64) -> Option<PrLifecycle>,
457    cache: HashMap<u64, bool>,
458    asked: usize,
459    failed: bool,
460}
461
462/// How many pull requests one invocation may put to the forge on behalf of
463/// stale records.
464const MAX_FORGE_LOOKUPS: usize = 5;
465
466impl<'a> Staleness<'a> {
467    fn new(runs_root: &'a Path, lookup: &'a dyn Fn(&Path, u64) -> Option<PrLifecycle>) -> Self {
468        Self {
469            runs_root,
470            lookup,
471            cache: HashMap::new(),
472            asked: 0,
473            failed: false,
474        }
475    }
476
477    /// `true` when `view`'s recorded-open pull request is known not to be this
478    /// run's to claim any more.
479    fn pr_released(&mut self, repo: &Path, view: &RunView) -> bool {
480        if let Some(next) = &view.pr_taken_over_by
481            && next != &view.id
482            && RunView::read(self.runs_root, next).is_some()
483        {
484            return true;
485        }
486        let Some(pr) = view.pr.as_ref().filter(|p| p.state == "open") else {
487            return false;
488        };
489        if let Some(next) = &view.released_to
490            && next != &view.id
491            && RunView::read(self.runs_root, next).is_some()
492        {
493            return true;
494        }
495        if pr.number == 0 {
496            return false;
497        }
498        if let Some(known) = self.cache.get(&pr.number) {
499            return *known;
500        }
501        if self.failed || self.asked >= MAX_FORGE_LOOKUPS {
502            return false;
503        }
504        self.asked += 1;
505        let settled = match (self.lookup)(repo, pr.number) {
506            Some(PrLifecycle::Merged | PrLifecycle::Closed) => true,
507            Some(PrLifecycle::Open) => false,
508            None => {
509                self.failed = true;
510                false
511            }
512        };
513        self.cache.insert(pr.number, settled);
514        settled
515    }
516}
517
518/// Something an unfinished piece of work owns.
519#[derive(Debug, Clone)]
520struct Claim {
521    owner: Owner,
522    id: String,
523    status: String,
524    via: String,
525    /// The owner's title and instruction, for the judge.
526    about: String,
527    branch: Option<String>,
528    /// Commit the branch forked from; without it a SHA cannot be judged.
529    base: Option<String>,
530    /// `(number, url)` of an open pull request.
531    pr: Option<(u64, String)>,
532}
533
534/// Look for work already in flight that `text` (and `review_branch`, for a
535/// review-only run) points at. `repo` is the repository the new work is for;
536/// `ignore_task` is a task being edited, whose own claims never count.
537pub fn check(
538    queue: &Queue,
539    runs_root: &Path,
540    repo: &Path,
541    text: &str,
542    review_branch: Option<&str>,
543    ignore_task: Option<&str>,
544) -> Vec<Hit> {
545    check_with(
546        queue,
547        runs_root,
548        repo,
549        text,
550        review_branch,
551        ignore_task,
552        &gh_open_pr,
553        &gh_pr_state,
554    )
555}
556
557/// [`check`] with the forge lookup supplied: `open_pr(repo, n)` says whether
558/// pull request `n` of `repo` is open (`Some(url)`) or not / unknown (`None`).
559/// It is asked only about numbers the text names that no local record already
560/// explained, so a PR magi never produced (opened by hand) still collides.
561/// `pr_state(repo, n)` is the forge's word on a pull request a run record calls
562/// open (`None` = unreadable, which keeps the claim); see [`Staleness`].
563#[allow(clippy::too_many_arguments)]
564pub fn check_with(
565    queue: &Queue,
566    runs_root: &Path,
567    repo: &Path,
568    text: &str,
569    review_branch: Option<&str>,
570    ignore_task: Option<&str>,
571    open_pr: &dyn Fn(&Path, u64) -> Option<String>,
572    pr_state: &dyn Fn(&Path, u64) -> Option<PrLifecycle>,
573) -> Vec<Hit> {
574    let mut stale = Staleness::new(runs_root, pr_state);
575    let mut idents = Idents::default();
576    let here = idents.of(repo);
577    let tasks = queue.list();
578    let own_runs: BTreeSet<String> = tasks
579        .iter()
580        .filter(|t| Some(t.id.as_str()) == ignore_task)
581        .flat_map(|t| t.runs.iter().cloned())
582        .collect();
583    // PRs the edited task's own runs opened: never a rival, forge or not.
584    let own_prs: BTreeSet<u64> = own_runs
585        .iter()
586        .filter_map(|id| RunView::read(runs_root, id))
587        .filter_map(|v| v.pr.map(|p| p.number))
588        .collect();
589
590    let mut claims: Vec<Claim> = Vec::new();
591    let mut from_task: BTreeSet<String> = BTreeSet::new();
592    for t in tasks
593        .iter()
594        .filter(|t| t.status != TaskStatus::Done && Some(t.id.as_str()) != ignore_task)
595        .filter(|t| idents.of(&t.repo) == here)
596    {
597        claims.extend(task_claims(t, runs_root, &mut from_task, repo, &mut stale));
598    }
599    for id in crate::run::list_ids_in(runs_root) {
600        if own_runs.contains(&id) {
601            continue;
602        }
603        let Some(view) = RunView::read(runs_root, &id) else {
604            continue;
605        };
606        // A task-scoped publication is one task's hand-off, even when
607        // several run records retain its history.
608        if from_task.contains(&id) && view.pr_head.is_some() {
609            continue;
610        }
611        if (view.terminal() && !view.pr_open()) || idents.of(&view.repo) != here {
612            continue;
613        }
614        let released = stale.pr_released(repo, &view);
615        // A terminal run held up only by a pull request that is not its own
616        // (any more) claims nothing at all.
617        if view.terminal() && released {
618            continue;
619        }
620        claims.extend(run_claims(
621            &view,
622            Owner::Run,
623            None,
624            "its own run",
625            !released,
626            ("", &view.instruction),
627        ));
628    }
629
630    let mut hits: Vec<Hit> = Vec::new();
631    let mut push = |c: &Claim, signal: Signal, token: String| {
632        let hit = Hit {
633            owner: c.owner.clone(),
634            id: c.id.clone(),
635            status: c.status.clone(),
636            signal,
637            token,
638            via: c.via.clone(),
639            about: c.about.clone(),
640        };
641        if !hits.contains(&hit) {
642            hits.push(hit);
643        }
644    };
645
646    let prs = pr_numbers(text);
647    let shas = sha_candidates(repo, text);
648    for c in &claims {
649        if let Some(b) = &c.branch {
650            if names_branch(text, b) || review_branch == Some(b.as_str()) {
651                push(c, Signal::Branch, b.clone());
652            }
653            if let Some(base) = &c.base {
654                for sha in &shas {
655                    if on_branch_only(repo, sha, b, base) {
656                        push(c, Signal::Sha, short_sha(sha));
657                    }
658                }
659            }
660        }
661        if let Some((n, url)) = &c.pr {
662            if prs.contains(&Mention::Number(*n))
663                || prs.iter().any(|p| matches!(p, Mention::Url(u) if u == url))
664            {
665                push(c, Signal::Pr, format!("#{n}"));
666            }
667        }
668    }
669    let mut asked = BTreeSet::new();
670    for n in prs.iter().filter_map(|m| match m {
671        Mention::Number(n) => Some(*n),
672        Mention::Url(u) => u.rsplit('/').next().and_then(|d| d.parse().ok()),
673    }) {
674        let token = format!("#{n}");
675        if hits
676            .iter()
677            .any(|h| h.signal == Signal::Pr && h.token == token)
678            || own_prs.contains(&n)
679            || !asked.insert(n)
680        {
681            continue;
682        }
683        if let Some(url) = open_pr(repo, n) {
684            hits.push(Hit {
685                owner: Owner::Pr,
686                id: token.clone(),
687                status: "open".into(),
688                signal: Signal::Pr,
689                token,
690                via: format!("an open pull request with no run record here ({url})"),
691                about: String::new(),
692            });
693        }
694    }
695    hits
696}
697
698/// Ask the forge, via `gh`, whether PR `n` is open. Best effort and bounded:
699/// any failure (no `gh`, no remote, offline, a slow answer) is `None`, i.e.
700/// today's behaviour. `GH_REPO` is dropped so the PR is looked up in `repo`'s
701/// own remote, not whatever the environment points at.
702fn gh_open_pr(repo: &Path, n: u64) -> Option<String> {
703    let v = gh_pr_view(repo, n, "state,url")?;
704    (v["state"] == "OPEN")
705        .then(|| v["url"].as_str().map(str::to_owned))
706        .flatten()
707}
708
709/// [`gh_open_pr`]'s question asked of a pull request a run record names: its
710/// lifecycle, or `None` when the forge cannot say.
711fn gh_pr_state(repo: &Path, n: u64) -> Option<PrLifecycle> {
712    match gh_pr_view(repo, n, "state,url")?["state"].as_str()? {
713        "OPEN" => Some(PrLifecycle::Open),
714        "MERGED" => Some(PrLifecycle::Merged),
715        "CLOSED" => Some(PrLifecycle::Closed),
716        _ => None,
717    }
718}
719
720fn gh_pr_view(repo: &Path, n: u64, fields: &str) -> Option<serde_json::Value> {
721    let mut child = Command::new("gh")
722        .quiet()
723        .args(["pr", "view", &n.to_string(), "--json", fields])
724        .current_dir(repo)
725        .env_remove("GH_REPO")
726        .env("GH_PROMPT_DISABLED", "1")
727        .stdin(Stdio::null())
728        .stdout(Stdio::piped())
729        .stderr(Stdio::null())
730        .spawn()
731        .ok()?;
732    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
733    loop {
734        match child.try_wait().ok()? {
735            Some(status) if status.success() => break,
736            Some(_) => return None,
737            None if std::time::Instant::now() >= deadline => {
738                let _ = child.kill();
739                let _ = child.wait();
740                return None;
741            }
742            None => std::thread::sleep(std::time::Duration::from_millis(50)),
743        }
744    }
745    let mut raw = String::new();
746    std::io::Read::read_to_string(&mut child.stdout.take()?, &mut raw).ok()?;
747    serde_json::from_str(&raw).ok()
748}
749
750/// Fill in what a forge-only hit (an open pull request no record here owns)
751/// is about, from its title and body. Only the judge reads it, so this runs
752/// after the mechanical check, only on a hit, and best effort: an unreadable
753/// forge leaves `about` empty, never drops the hit.
754fn describe_forge_hits(repo: &Path, hits: &mut [Hit]) {
755    for h in hits
756        .iter_mut()
757        .filter(|h| h.owner == Owner::Pr && h.about.is_empty())
758    {
759        let Some(n) = h.token.trim_start_matches('#').parse::<u64>().ok() else {
760            continue;
761        };
762        if let Some(v) = gh_pr_view(repo, n, "title,body") {
763            h.about = about_of(
764                v["title"].as_str().unwrap_or(""),
765                v["body"].as_str().unwrap_or(""),
766            );
767        }
768    }
769}
770
771/// Keep the head and the tail of `s` within `max` characters, marking the cut.
772/// A long instruction often has background first and the concrete change last,
773/// so dropping only the end would lose exactly what the judge compares.
774fn squeeze(s: &str, max: usize) -> String {
775    let n = s.chars().count();
776    if n <= max {
777        return s.to_owned();
778    }
779    let half = max / 2;
780    let head: String = s.chars().take(half).collect();
781    let tail: String = s.chars().skip(n - half).collect();
782    format!(
783        "{head}\n[... {} characters omitted ...]\n{tail}",
784        n - 2 * half
785    )
786}
787
788/// The owner's work for the judge: its title (when it has one) and its
789/// instruction with whitespace collapsed, keeping the head and the tail when
790/// it is long. The whole instruction is used, not its first line: a heading
791/// such as `# Task` says nothing about what the work is.
792fn about_of(title: &str, instruction: &str) -> String {
793    let body = instruction.split_whitespace().collect::<Vec<_>>().join(" ");
794    let title = title.trim();
795    let full = match (title.is_empty(), body.is_empty()) {
796        (true, _) => body,
797        (false, true) => title.to_owned(),
798        (false, false) => format!("{title}: {body}"),
799    };
800    squeeze(&full, ABOUT_MAX_CHARS)
801}
802
803/// Longest description of one owner's work given to the judge: the same limit
804/// as the new text, so an instruction the judge accepts on one side is not
805/// cut on the other.
806const ABOUT_MAX_CHARS: usize = prompt::DUPES_JUDGE_MAX_CHARS;
807
808fn task_claims(
809    t: &Task,
810    runs_root: &Path,
811    seen: &mut BTreeSet<String>,
812    repo: &Path,
813    stale: &mut Staleness<'_>,
814) -> Vec<Claim> {
815    let status = t.status.as_str().to_owned();
816    let mut out = Vec::new();
817    if let Some(b) = &t.review_branch {
818        out.push(Claim {
819            owner: Owner::Task,
820            id: t.id.clone(),
821            status: status.clone(),
822            via: "its review branch".into(),
823            about: about_of(&t.title, &t.instruction),
824            branch: Some(b.clone()),
825            base: None,
826            pr: None,
827        });
828    }
829    for rid in &t.runs {
830        if let Some(view) = RunView::read(runs_root, rid) {
831            seen.insert(rid.clone());
832            // A merged or closed pull request is not in flight, even when the
833            // task that owns it is.
834            let live_pr = !(view.terminal() && stale.pr_released(repo, &view));
835            if view.terminal() && !live_pr && view.pr_taken_over_by.is_some() {
836                continue;
837            }
838            out.extend(run_claims(
839                &view,
840                Owner::Task,
841                Some((&t.id, &status)),
842                &format!("produced by its run {}", crate::queue::short(rid)),
843                live_pr,
844                (&t.title, &t.instruction),
845            ));
846        }
847    }
848    out
849}
850
851/// The claims of one run, attributed to `owner` (the task, when there is one).
852///
853/// `live_pr` is false when the record's open pull request is known to be
854/// settled or somebody else's (see [`Staleness`]); it then names no PR.
855fn run_claims(
856    view: &RunView,
857    owner: Owner,
858    task: Option<(&str, &str)>,
859    via: &str,
860    live_pr: bool,
861    (title, instruction): (&str, &str),
862) -> Vec<Claim> {
863    let about = about_of(title, instruction);
864    let (id, status) = match task {
865        Some((id, status)) => (id.to_owned(), status.to_owned()),
866        None => (view.id.clone(), view.status.clone()),
867    };
868    let pr = view
869        .pr
870        .as_ref()
871        .filter(|p| live_pr && p.state == "open" && p.number > 0)
872        .map(|p| (p.number, p.url.clone()));
873    let via_pr = |extra: &str| match &pr {
874        Some((n, _)) => format!("{via} (PR #{n} open){extra}"),
875        None => format!("{via}{extra}"),
876    };
877    let mut out: Vec<Claim> = view
878        .candidates
879        .iter()
880        .filter(|c| !c.branch.is_empty())
881        .map(|c| Claim {
882            owner: owner.clone(),
883            id: id.clone(),
884            status: status.clone(),
885            via: via_pr(""),
886            about: about.clone(),
887            branch: Some(c.branch.clone()),
888            base: (!view.base_commit.is_empty()).then(|| view.base_commit.clone()),
889            pr: None,
890        })
891        .collect();
892    if live_pr && let Some(branch) = &view.pr_head {
893        out.push(Claim {
894            owner: owner.clone(),
895            id: id.clone(),
896            status: status.clone(),
897            via: via_pr(""),
898            about: about.clone(),
899            branch: Some(branch.clone()),
900            base: None,
901            pr: None,
902        });
903    }
904    if pr.is_some() {
905        out.push(Claim {
906            owner,
907            id,
908            status,
909            via: via_pr(""),
910            about,
911            branch: None,
912            base: None,
913            pr,
914        });
915    }
916    out
917}
918
919/// Repository identity: the canonical git common dir, so two worktrees of one
920/// repository are the same repository and a path spelled two ways is too.
921#[derive(Default)]
922struct Idents(HashMap<PathBuf, PathBuf>);
923
924impl Idents {
925    fn of(&mut self, path: &Path) -> PathBuf {
926        self.0
927            .entry(path.to_path_buf())
928            .or_insert_with(|| {
929                git(
930                    path,
931                    &["rev-parse", "--path-format=absolute", "--git-common-dir"],
932                )
933                .map(PathBuf::from)
934                .and_then(|p| p.canonicalize().ok())
935                .or_else(|| path.canonicalize().ok())
936                .unwrap_or_else(|| path.to_path_buf())
937            })
938            .clone()
939    }
940}
941
942fn git(cwd: &Path, args: &[&str]) -> Option<String> {
943    let out = Command::new("git")
944        .quiet()
945        .args(args)
946        .current_dir(cwd)
947        .stdin(Stdio::null())
948        .stderr(Stdio::null())
949        .env("GIT_TERMINAL_PROMPT", "0")
950        .output()
951        .ok()?;
952    out.status
953        .success()
954        .then(|| String::from_utf8_lossy(&out.stdout).trim().to_owned())
955}
956
957fn git_ok(cwd: &Path, args: &[&str]) -> bool {
958    git(cwd, args).is_some()
959}
960
961fn is_ref_char(c: char) -> bool {
962    c.is_alphanumeric() || matches!(c, '_' | '-')
963}
964
965/// Does `text` contain `branch` as a whole word? `.` and `/` before it are
966/// fine (`origin/magi/x/A`), a name character on either side is not, so
967/// `magi/27b2/A` does not match inside `magi/27b2/AB`.
968fn names_branch(text: &str, branch: &str) -> bool {
969    if branch.len() < 3 {
970        return false;
971    }
972    text.match_indices(branch).any(|(i, _)| {
973        let before = text[..i].chars().next_back();
974        let after = text[i + branch.len()..].chars().next();
975        let after_ok = match after {
976            None => true,
977            Some('/') => false,
978            Some('.') => !text[i + branch.len() + 1..]
979                .chars()
980                .next()
981                .is_some_and(is_ref_char),
982            Some(c) => !is_ref_char(c),
983        };
984        before.is_none_or(|c| !is_ref_char(c) && c != '.') && after_ok
985    })
986}
987
988#[derive(Debug, PartialEq, Eq)]
989enum Mention {
990    Number(u64),
991    Url(String),
992}
993
994/// `#48`, `PR 48`, `PR #48`, `pull request 48`, and `.../pull/48` URLs.
995fn pr_numbers(text: &str) -> Vec<Mention> {
996    let mut out = Vec::new();
997    let bytes = text.as_bytes();
998    let digits = |from: usize| -> Option<(u64, usize)> {
999        let n = text[from..].bytes().take_while(u8::is_ascii_digit).count();
1000        (n > 0 && n < 10)
1001            .then(|| text[from..from + n].parse().ok().map(|v| (v, from + n)))
1002            .flatten()
1003    };
1004    for (i, _) in text.match_indices('#') {
1005        if let Some((n, _)) = digits(i + 1) {
1006            let word_before = i > 0 && is_ref_char(bytes[i - 1] as char);
1007            if !word_before {
1008                out.push(Mention::Number(n));
1009            }
1010        }
1011    }
1012    let lower = text.to_ascii_lowercase();
1013    for key in ["pull request ", "pr "] {
1014        for (i, _) in lower.match_indices(key) {
1015            if i > 0 && is_ref_char(bytes[i - 1] as char) {
1016                continue;
1017            }
1018            let from = i + key.len();
1019            let from = if text[from..].starts_with('#') {
1020                from + 1
1021            } else {
1022                from
1023            };
1024            if let Some((n, _)) = digits(from) {
1025                out.push(Mention::Number(n));
1026            }
1027        }
1028    }
1029    for (i, _) in text.match_indices("/pull/") {
1030        if let Some((_, end)) = digits(i + 6) {
1031            let start = text[..i]
1032                .rfind(|c: char| c.is_whitespace() || matches!(c, '(' | '<' | '"' | '\''))
1033                .map_or(0, |p| p + 1);
1034            out.push(Mention::Url(text[start..end].to_owned()));
1035        }
1036    }
1037    out
1038}
1039
1040/// Hex words of 7..=40 chars in `text` that resolve to a commit in `repo`.
1041fn sha_candidates(repo: &Path, text: &str) -> Vec<String> {
1042    let mut seen = BTreeSet::new();
1043    let mut out = Vec::new();
1044    for word in text.split(|c: char| !c.is_ascii_alphanumeric()) {
1045        if !(7..=40).contains(&word.len()) || !word.bytes().all(|b| b.is_ascii_hexdigit()) {
1046            continue;
1047        }
1048        if seen.len() >= 16 || !seen.insert(word.to_ascii_lowercase()) {
1049            continue;
1050        }
1051        if let Some(full) = git(
1052            repo,
1053            &[
1054                "rev-parse",
1055                "--verify",
1056                "--quiet",
1057                &format!("{word}^{{commit}}"),
1058            ],
1059        ) {
1060            out.push(full);
1061        }
1062    }
1063    out
1064}
1065
1066/// Is `sha` reachable from `branch` but not from `base`? A SHA already in the
1067/// base would match every branch there is.
1068fn on_branch_only(repo: &Path, sha: &str, branch: &str, base: &str) -> bool {
1069    let tip = format!("{branch}^{{commit}}");
1070    git_ok(repo, &["rev-parse", "--verify", "--quiet", &tip])
1071        && git_ok(repo, &["merge-base", "--is-ancestor", sha, branch])
1072        && !git_ok(repo, &["merge-base", "--is-ancestor", sha, base])
1073}
1074
1075fn short_sha(sha: &str) -> String {
1076    sha.chars().take(7).collect()
1077}
1078
1079#[cfg(test)]
1080mod tests {
1081    use super::*;
1082    use crate::queue::{Source, Task};
1083
1084    #[cfg(unix)]
1085    fn judge_agent(id: &str, fails: bool) -> crate::config::AgentSpec {
1086        crate::config::AgentSpec {
1087            id: id.to_owned(),
1088            kind: crate::config::AgentKind::Command,
1089            model: None,
1090            command: vec![
1091                "sh".into(),
1092                "-c".into(),
1093                format!(
1094                    "echo {id} >> calls; {}",
1095                    if fails {
1096                        "exit 1"
1097                    } else {
1098                        r#"printf '%s' '{"duplicate":false,"reason":"different work"}'"#
1099                    }
1100                ),
1101            ],
1102            extra_args: Vec::new(),
1103            env: Default::default(),
1104            prompt_delivery: None,
1105        }
1106    }
1107
1108    #[cfg(unix)]
1109    fn judge_config() -> Config {
1110        let mut cfg = Config {
1111            agents: vec![
1112                judge_agent("chat", false),
1113                judge_agent("dedicated", false),
1114                judge_agent("failed", true),
1115            ],
1116            ..Config::default()
1117        };
1118        cfg.roles.chatter = Some("chat".into());
1119        cfg
1120    }
1121
1122    #[cfg(unix)]
1123    #[tokio::test]
1124    async fn dupes_judge_overrides_chatter() {
1125        let dir = tempfile::tempdir().unwrap();
1126        let mut cfg = judge_config();
1127        cfg.roles.dupes_judge = Some("dedicated".into());
1128        let verdict = chain_judge(&cfg, dir.path(), "task".into(), vec![])
1129            .await
1130            .unwrap();
1131        assert_eq!(verdict.agent, "dedicated");
1132        assert!(!verdict.duplicate);
1133        assert_eq!(
1134            std::fs::read_to_string(dir.path().join("calls")).unwrap(),
1135            "dedicated\n"
1136        );
1137        assert_eq!(cfg.roles.chatter.as_ref().unwrap().ids(), ["chat"]);
1138    }
1139
1140    #[cfg(unix)]
1141    #[tokio::test]
1142    async fn dupes_judge_unset_inherits_chatter() {
1143        let dir = tempfile::tempdir().unwrap();
1144        let cfg = judge_config();
1145        let verdict = chain_judge(&cfg, dir.path(), "task".into(), vec![])
1146            .await
1147            .unwrap();
1148        assert_eq!(verdict.agent, "chat");
1149        assert_eq!(
1150            std::fs::read_to_string(dir.path().join("calls")).unwrap(),
1151            "chat\n"
1152        );
1153    }
1154
1155    #[cfg(unix)]
1156    #[tokio::test]
1157    async fn dupes_judge_dedicated_and_inherited_chains_advance_on_failure() {
1158        for dedicated in [true, false] {
1159            let dir = tempfile::tempdir().unwrap();
1160            let mut cfg = judge_config();
1161            let chain =
1162                crate::config::AgentChoice::Chain(vec!["failed".into(), "dedicated".into()]);
1163            if dedicated {
1164                cfg.roles.dupes_judge = Some(chain);
1165            } else {
1166                cfg.roles.chatter = Some(chain);
1167            }
1168            let verdict = chain_judge(&cfg, dir.path(), "task".into(), vec![])
1169                .await
1170                .unwrap();
1171            assert_eq!(verdict.agent, "dedicated");
1172            assert_eq!(
1173                std::fs::read_to_string(dir.path().join("calls")).unwrap(),
1174                "failed\ndedicated\n"
1175            );
1176        }
1177    }
1178
1179    #[cfg(unix)]
1180    #[tokio::test]
1181    async fn dupes_judge_unavailable_choice_does_not_inherit_chatter() {
1182        let dir = tempfile::tempdir().unwrap();
1183        let mut cfg = judge_config();
1184        cfg.roles.dupes_judge = Some("missing".into());
1185        let err = chain_judge(&cfg, dir.path(), "task".into(), vec![])
1186            .await
1187            .unwrap_err();
1188        assert!(err.to_string().contains("[roles] dupes_judge"), "{err}");
1189        assert!(!dir.path().join("calls").exists());
1190    }
1191
1192    #[cfg(unix)]
1193    #[tokio::test]
1194    async fn dupes_judge_empty_choice_uses_default_instead_of_chatter() {
1195        let dir = tempfile::tempdir().unwrap();
1196        let mut cfg = judge_config();
1197        cfg.roles.chatter = Some("dedicated".into());
1198        cfg.roles.dupes_judge = Some(crate::config::AgentChoice::Chain(vec![]));
1199        let verdict = chain_judge(&cfg, dir.path(), "task".into(), vec![])
1200            .await
1201            .unwrap();
1202        assert_eq!(
1203            verdict.agent, "chat",
1204            "the first roster agent is the default"
1205        );
1206        assert_eq!(
1207            std::fs::read_to_string(dir.path().join("calls")).unwrap(),
1208            "chat\n"
1209        );
1210    }
1211
1212    struct Fx {
1213        _tmp: tempfile::TempDir,
1214        repo: PathBuf,
1215        runs: PathBuf,
1216        q: Queue,
1217    }
1218
1219    fn sh(cwd: &Path, args: &[&str]) -> String {
1220        let out = Command::new("git")
1221            .quiet()
1222            .args(["-c", "user.name=t", "-c", "user.email=t@t"])
1223            .args(args)
1224            .current_dir(cwd)
1225            .output()
1226            .unwrap();
1227        assert!(out.status.success(), "git {args:?}: {out:?}");
1228        String::from_utf8_lossy(&out.stdout).trim().to_owned()
1229    }
1230
1231    /// A repo with `main` and a branch `magi/aaaa/A` one commit ahead.
1232    /// Returns the fixture plus the (main, branch) tip SHAs.
1233    fn fx() -> (Fx, String, String) {
1234        let tmp = tempfile::tempdir().unwrap();
1235        let repo = tmp.path().join("repo");
1236        std::fs::create_dir_all(&repo).unwrap();
1237        sh(&repo, &["init", "-q", "-b", "main"]);
1238        std::fs::write(repo.join("a"), "1").unwrap();
1239        sh(&repo, &["add", "."]);
1240        sh(&repo, &["commit", "-q", "-m", "base"]);
1241        let base = sh(&repo, &["rev-parse", "HEAD"]);
1242        sh(&repo, &["checkout", "-q", "-b", "magi/aaaa/A"]);
1243        std::fs::write(repo.join("a"), "2").unwrap();
1244        sh(&repo, &["commit", "-q", "-am", "work"]);
1245        let tip = sh(&repo, &["rev-parse", "HEAD"]);
1246        sh(&repo, &["checkout", "-q", "main"]);
1247        let runs = tmp.path().join("runs");
1248        std::fs::create_dir_all(&runs).unwrap();
1249        let q = Queue::at(tmp.path().join("queue"));
1250        (
1251            Fx {
1252                _tmp: tmp,
1253                repo,
1254                runs,
1255                q,
1256            },
1257            base,
1258            tip,
1259        )
1260    }
1261
1262    fn write_run(f: &Fx, id: &str, status: &str, base: &str, pr: Option<(u64, &str)>) {
1263        let dir = f.runs.join(id);
1264        std::fs::create_dir_all(&dir).unwrap();
1265        let pr = pr.map(|(n, s)| {
1266            serde_json::json!({"url": format!("https://github.com/o/r/pull/{n}"), "number": n, "state": s})
1267        });
1268        let v = serde_json::json!({
1269            "schema": 999, "id": id, "repo": f.repo, "status": status,
1270            "base_commit": base, "candidates": [{"branch": "magi/aaaa/A"}], "pr": pr,
1271        });
1272        std::fs::write(dir.join("run.json"), v.to_string()).unwrap();
1273    }
1274
1275    fn file_task(f: &Fx, status: TaskStatus, runs: &[&str]) -> Task {
1276        let mut t = Task::new("t".into(), "x".into(), f.repo.clone(), Source::Human);
1277        t.status = status;
1278        t.runs = runs.iter().map(|s| (*s).to_owned()).collect();
1279        f.q.put(&mut t).unwrap();
1280        t
1281    }
1282
1283    const RID: &str = "20260901-100000-aaaa";
1284
1285    fn run(f: &Fx, text: &str, review: Option<&str>) -> Vec<Hit> {
1286        check_with(
1287            &f.q,
1288            &f.runs,
1289            &f.repo,
1290            text,
1291            review,
1292            None,
1293            &|_, _| None,
1294            &|_, _| None,
1295        )
1296    }
1297
1298    #[test]
1299    fn branch_matches_a_live_run_and_its_task() {
1300        let (f, base, _) = fx();
1301        write_run(&f, RID, "reviewing", &base, None);
1302        let t = file_task(&f, TaskStatus::Running, &[RID]);
1303        let hits = run(&f, "land magi/aaaa/A onto a fresh branch.", None);
1304        assert!(hits.iter().any(|h| h.owner == Owner::Task
1305            && h.id == t.id
1306            && h.signal == Signal::Branch
1307            && h.token == "magi/aaaa/A"));
1308        assert!(hits.iter().any(|h| h.owner == Owner::Run && h.id == RID));
1309        let msg = Duplicate::new(hits).to_string();
1310        assert!(
1311            msg.contains("--force") && msg.contains("magi/aaaa/A"),
1312            "{msg}"
1313        );
1314    }
1315
1316    #[test]
1317    fn branch_must_match_whole_word() {
1318        let (f, base, _) = fx();
1319        write_run(&f, RID, "reviewing", &base, None);
1320        assert!(run(&f, "see magi/aaaa/AB and magi/aaaa/A/x", None).is_empty());
1321    }
1322
1323    #[test]
1324    fn sha_on_the_branch_matches_but_one_in_base_does_not() {
1325        let (f, base, tip) = fx();
1326        write_run(&f, RID, "reviewing", &base, None);
1327        let hits = run(&f, &format!("land commit {} please", &tip[..8]), None);
1328        assert!(
1329            hits.iter().any(|h| h.signal == Signal::Sha && h.id == RID),
1330            "{hits:?}"
1331        );
1332        assert!(run(&f, &format!("see {}", &base[..9]), None).is_empty());
1333        // Hex that resolves to nothing is ignored.
1334        assert!(run(&f, "deadbeef and 1234567", None).is_empty());
1335    }
1336
1337    #[test]
1338    fn pr_number_matches_in_every_spelling() {
1339        let (f, base, _) = fx();
1340        write_run(&f, RID, "ready", &base, Some((48, "open")));
1341        for text in [
1342            "finish #48",
1343            "PR 48 is stale",
1344            "pr #48",
1345            "pull request 48",
1346            "https://github.com/o/r/pull/48",
1347        ] {
1348            let hits = run(&f, text, None);
1349            assert!(
1350                hits.iter().any(|h| h.signal == Signal::Pr),
1351                "{text}: {hits:?}"
1352            );
1353        }
1354        assert!(run(&f, "see #480 and PR 4 and issue48", None).is_empty());
1355    }
1356
1357    #[test]
1358    fn terminal_runs_and_done_tasks_do_not_match() {
1359        let (f, base, tip) = fx();
1360        write_run(&f, RID, "merged", &base, Some((48, "merged")));
1361        file_task(&f, TaskStatus::Done, &[RID]);
1362        let text = format!("magi/aaaa/A {} #48", &tip[..8]);
1363        assert!(run(&f, &text, None).is_empty());
1364    }
1365
1366    #[test]
1367    fn terminal_run_with_open_pr_or_open_task_still_claims() {
1368        // Changed deliberately: a terminal run's recorded-open PR now claims
1369        // only while the forge says open or cannot be read (`run` passes an
1370        // unreadable forge). A merged / closed answer or a released run no
1371        // longer claims; see the `stale_open_*` tests below.
1372        let (f, base, _) = fx();
1373        write_run(&f, RID, "ready", &base, Some((48, "open")));
1374        assert!(!run(&f, "magi/aaaa/A", None).is_empty());
1375        let (g, base, _) = fx();
1376        write_run(&g, RID, "ready", &base, None);
1377        assert!(run(&g, "magi/aaaa/A", None).is_empty());
1378        let t = file_task(&g, TaskStatus::Held, &[RID]);
1379        let hits = run(&g, "magi/aaaa/A", None);
1380        assert!(hits.iter().any(|h| h.id == t.id), "{hits:?}");
1381    }
1382
1383    #[test]
1384    fn review_only_matches_a_branch_a_live_task_owns() {
1385        let (f, base, _) = fx();
1386        write_run(&f, RID, "ready", &base, None);
1387        assert!(run(&f, "", Some("magi/aaaa/A")).is_empty());
1388        let mut t = file_task(&f, TaskStatus::Queued, &[]);
1389        t.review_branch = Some("magi/aaaa/A".into());
1390        f.q.put(&mut t).unwrap();
1391        let hits = run(&f, "", Some("magi/aaaa/A"));
1392        assert!(
1393            hits.iter()
1394                .any(|h| h.id == t.id && h.signal == Signal::Branch)
1395        );
1396    }
1397
1398    #[test]
1399    fn other_repository_and_edited_task_do_not_match() {
1400        let (f, base, _) = fx();
1401        write_run(&f, RID, "reviewing", &base, None);
1402        let t = file_task(&f, TaskStatus::Running, &[RID]);
1403        let other = f._tmp.path().join("other");
1404        std::fs::create_dir_all(&other).unwrap();
1405        sh(&other, &["init", "-q"]);
1406        assert!(
1407            check_with(
1408                &f.q,
1409                &f.runs,
1410                &other,
1411                "magi/aaaa/A",
1412                None,
1413                None,
1414                &|_, _| None,
1415                &|_, _| None,
1416            )
1417            .is_empty()
1418        );
1419        // Editing the task that owns the run never collides with itself.
1420        assert!(
1421            check_with(
1422                &f.q,
1423                &f.runs,
1424                &f.repo,
1425                "magi/aaaa/A",
1426                None,
1427                Some(&t.id),
1428                &|_, _| None,
1429                &|_, _| None,
1430            )
1431            .is_empty()
1432        );
1433    }
1434
1435    #[test]
1436    fn a_worktree_is_the_same_repository() {
1437        let (f, base, _) = fx();
1438        write_run(&f, RID, "reviewing", &base, None);
1439        let wt = f._tmp.path().join("wt");
1440        sh(
1441            &f.repo,
1442            &["worktree", "add", "-q", wt.to_str().unwrap(), "-b", "other"],
1443        );
1444        assert!(
1445            !check_with(
1446                &f.q,
1447                &f.runs,
1448                &wt,
1449                "magi/aaaa/A",
1450                None,
1451                None,
1452                &|_, _| None,
1453                &|_, _| None,
1454            )
1455            .is_empty()
1456        );
1457    }
1458
1459    #[test]
1460    fn an_open_pr_without_a_run_record_matches_through_the_forge() {
1461        let (f, _, _) = fx();
1462        let open = |_: &Path, n: u64| (n == 48).then(|| "https://example.test/pull/48".to_owned());
1463        let hit = |text: &str| {
1464            check_with(&f.q, &f.runs, &f.repo, text, None, None, &open, &|_, _| {
1465                None
1466            })
1467        };
1468        let hits = hit("finish PR #48");
1469        assert_eq!(hits.len(), 1, "{hits:?}");
1470        assert_eq!(hits[0].owner, Owner::Pr);
1471        assert!(hits[0].to_string().contains("#48"));
1472        // Closed / unknown / unnamed PRs never match.
1473        assert!(hit("finish PR #49").is_empty());
1474        assert!(hit("finish the work").is_empty());
1475    }
1476
1477    #[test]
1478    fn a_forge_hit_does_not_repeat_a_pr_a_run_already_explains() {
1479        let (f, base, _) = fx();
1480        write_run(&f, RID, "ready", &base, Some((48, "open")));
1481        let open = |_: &Path, _: u64| Some("u".to_owned());
1482        let hits = check_with(&f.q, &f.runs, &f.repo, "#48", None, None, &open, &|_, _| {
1483            None
1484        });
1485        assert!(hits.iter().all(|h| h.owner != Owner::Pr), "{hits:?}");
1486        assert!(!hits.is_empty());
1487    }
1488
1489    #[test]
1490    fn an_edited_tasks_own_open_pr_is_not_a_forge_hit() {
1491        let (f, base, _) = fx();
1492        write_run(&f, RID, "ready", &base, Some((48, "open")));
1493        let t = file_task(&f, TaskStatus::Running, &[RID]);
1494        let open = |_: &Path, _: u64| Some("u".to_owned());
1495        let hits = check_with(
1496            &f.q,
1497            &f.runs,
1498            &f.repo,
1499            "#48",
1500            None,
1501            Some(&t.id),
1502            &open,
1503            &|_, _| None,
1504        );
1505        assert!(hits.is_empty(), "{hits:?}");
1506    }
1507
1508    fn with_forge(f: &Fx, text: &str, state: Option<PrLifecycle>) -> Vec<Hit> {
1509        check_with(
1510            &f.q,
1511            &f.runs,
1512            &f.repo,
1513            text,
1514            None,
1515            None,
1516            &|_, _| None,
1517            &move |_, _| state,
1518        )
1519    }
1520
1521    fn release(f: &Fx, id: &str, to: &str) {
1522        let path = f.runs.join(id).join("run.json");
1523        let mut v: serde_json::Value =
1524            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
1525        v["released_to"] = serde_json::json!(to);
1526        std::fs::write(path, v.to_string()).unwrap();
1527    }
1528
1529    #[test]
1530    fn a_task_public_head_and_pr_are_claimed_only_by_the_successor() {
1531        let (f, base, _) = fx();
1532        write_run(&f, RID, "blocked", &base, Some((48, "open")));
1533        let next = "20260901-000001-bbbb";
1534        write_run(&f, next, "landing", &base, Some((48, "open")));
1535        for id in [RID, next] {
1536            let path = f.runs.join(id).join("run.json");
1537            let mut value: serde_json::Value =
1538                serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
1539            value["pr_head"] = serde_json::json!("magi/task-abcd-1234");
1540            if id == RID {
1541                value["pr_taken_over_by"] = serde_json::json!(next);
1542            }
1543            std::fs::write(path, value.to_string()).unwrap();
1544        }
1545        for text in ["update #48", "update magi/task-abcd-1234"] {
1546            let hits = with_forge(&f, text, Some(PrLifecycle::Open));
1547            assert!(!hits.is_empty());
1548            assert!(hits.iter().all(|h| h.id == next), "{hits:?}");
1549        }
1550        let task = file_task(&f, TaskStatus::Held, &[RID, next]);
1551        let hits = with_forge(&f, "update magi/task-abcd-1234", Some(PrLifecycle::Open));
1552        assert_eq!(hits.len(), 1, "{hits:?}");
1553        assert_eq!(hits[0].id, task.id);
1554    }
1555
1556    #[test]
1557    fn stale_open_pr_that_the_forge_says_is_merged_or_closed_does_not_claim() {
1558        for state in [PrLifecycle::Merged, PrLifecycle::Closed] {
1559            let (f, base, _) = fx();
1560            write_run(&f, RID, "superseded", &base, Some((48, "open")));
1561            assert!(with_forge(&f, "follow up on #48", Some(state)).is_empty());
1562            assert!(with_forge(&f, "magi/aaaa/A", Some(state)).is_empty());
1563            // Same through an owning, still-live task: the PR is not its claim.
1564            file_task(&f, TaskStatus::Held, &[RID]);
1565            let hits = with_forge(&f, "follow up on #48", Some(state));
1566            assert!(hits.iter().all(|h| h.signal != Signal::Pr), "{hits:?}");
1567        }
1568    }
1569
1570    #[test]
1571    fn stale_open_pr_with_an_unreadable_forge_still_claims() {
1572        let (f, base, _) = fx();
1573        write_run(&f, RID, "superseded", &base, Some((48, "open")));
1574        let hits = with_forge(&f, "follow up on #48", None);
1575        assert!(hits.iter().any(|h| h.signal == Signal::Pr), "{hits:?}");
1576    }
1577
1578    #[test]
1579    fn a_genuinely_open_pr_still_claims() {
1580        let (f, base, _) = fx();
1581        write_run(&f, RID, "blocked", &base, Some((48, "open")));
1582        let hits = with_forge(&f, "follow up on #48", Some(PrLifecycle::Open));
1583        assert!(hits.iter().any(|h| h.signal == Signal::Pr), "{hits:?}");
1584    }
1585
1586    #[test]
1587    fn a_released_run_defers_to_its_successor_without_asking_the_forge() {
1588        let (f, base, _) = fx();
1589        let next = "20260901-110000-bbbb";
1590        write_run(&f, RID, "superseded", &base, Some((48, "open")));
1591        write_run(&f, next, "merged", &base, Some((48, "merged")));
1592        release(&f, RID, next);
1593        let asked = std::cell::Cell::new(0);
1594        let hits = check_with(
1595            &f.q,
1596            &f.runs,
1597            &f.repo,
1598            "follow up on #48",
1599            None,
1600            None,
1601            &|_, _| None,
1602            &|_, _| {
1603                asked.set(asked.get() + 1);
1604                None
1605            },
1606        );
1607        assert!(hits.is_empty(), "{hits:?}");
1608        assert_eq!(asked.get(), 0);
1609        // A successor that cannot be read decides nothing: claim stands.
1610        std::fs::remove_dir_all(f.runs.join(next)).unwrap();
1611        let hits = with_forge(&f, "follow up on #48", None);
1612        assert!(hits.iter().any(|h| h.signal == Signal::Pr), "{hits:?}");
1613    }
1614
1615    #[test]
1616    fn forge_lookups_are_cached_and_stop_after_a_failure() {
1617        let (f, base, _) = fx();
1618        for (i, id) in ["20260901-100000-aaa1", "20260901-100000-aaa2"]
1619            .iter()
1620            .enumerate()
1621        {
1622            write_run(&f, id, "blocked", &base, Some((48 + i as u64, "open")));
1623        }
1624        let asked = std::cell::Cell::new(0);
1625        check_with(
1626            &f.q,
1627            &f.runs,
1628            &f.repo,
1629            "x",
1630            None,
1631            None,
1632            &|_, _| None,
1633            &|_, _| {
1634                asked.set(asked.get() + 1);
1635                None
1636            },
1637        );
1638        assert_eq!(
1639            asked.get(),
1640            1,
1641            "an unreadable forge is asked once, not per PR"
1642        );
1643    }
1644
1645    use std::sync::Arc;
1646    use std::sync::atomic::{AtomicUsize, Ordering};
1647
1648    fn verdict(duplicate: bool) -> Result<Judgement> {
1649        Ok(Judgement {
1650            duplicate,
1651            reason: "because".into(),
1652            agent: "j".into(),
1653        })
1654    }
1655
1656    /// Run `screen` over `text` with a judge answering `answer`; returns the
1657    /// outcome and how many times the judge was asked.
1658    fn judged(
1659        f: &Fx,
1660        text: &str,
1661        answer: impl Fn() -> Result<Judgement> + Send + Sync + 'static,
1662    ) -> (Result<Screened, Duplicate>, usize) {
1663        let calls = Arc::new(AtomicUsize::new(0));
1664        let seen = calls.clone();
1665        let judge = move |_: String, _: Vec<Hit>| -> JudgeFuture {
1666            seen.fetch_add(1, Ordering::SeqCst);
1667            let r = answer();
1668            Box::pin(async move { r })
1669        };
1670        let hits = run(f, text, None);
1671        let out = tokio::runtime::Builder::new_current_thread()
1672            .build()
1673            .unwrap()
1674            .block_on(screen(hits, text, None, &judge));
1675        (out, calls.load(Ordering::SeqCst))
1676    }
1677
1678    const NAMES: &str = "seen on magi/aaaa/A, which does not touch this file";
1679
1680    fn fx_with_run() -> Fx {
1681        let (f, base, _) = fx();
1682        write_run(&f, RID, "reviewing", &base, None);
1683        f
1684    }
1685
1686    #[test]
1687    fn a_no_ruling_lets_the_work_through() {
1688        let f = fx_with_run();
1689        let (out, calls) = judged(&f, NAMES, || verdict(false));
1690        assert!(matches!(out, Ok(Screened::Cleared(_))));
1691        assert_eq!(calls, 1);
1692    }
1693
1694    #[test]
1695    fn a_yes_ruling_refuses_and_says_why() {
1696        let f = fx_with_run();
1697        let (out, _) = judged(&f, NAMES, || verdict(true));
1698        let msg = out.unwrap_err().to_string();
1699        assert!(
1700            msg.contains("duplicate - because") && msg.contains("--force"),
1701            "{msg}"
1702        );
1703        assert!(msg.contains("magi/aaaa/A"), "{msg}");
1704    }
1705
1706    #[test]
1707    fn a_failing_judge_lets_it_through_unjudged() {
1708        let f = fx_with_run();
1709        let (out, calls) = judged(&f, NAMES, || Err(anyhow::anyhow!("quota")));
1710        match out {
1711            Ok(Screened::Unjudged(why)) => assert!(why.contains("quota"), "{why}"),
1712            other => panic!("{other:?}"),
1713        }
1714        assert_eq!(calls, 1);
1715    }
1716
1717    #[test]
1718    fn garbage_replies_do_not_parse() {
1719        assert!(parse_judgement("sure, go ahead").is_err());
1720        assert!(parse_judgement(r#"{"duplicate":"maybe","reason":"x"}"#).is_err());
1721        assert!(parse_judgement(r#"{"duplicate":false}"#).is_err());
1722        assert!(parse_judgement(r#"{"duplicate":false,"reason":"  "}"#).is_err());
1723        let two = "{\"duplicate\":false,\"reason\":\"c\"}\n{\"duplicate\":true}";
1724        assert!(parse_judgement(two).is_err());
1725        assert!(parse_judgement("ok {\"duplicate\":false,\"reason\":\"c\"}").is_err());
1726        let (d, why) = parse_judgement("{\"duplicate\":true,\"reason\":\"same\\nPR\"}").unwrap();
1727        assert_eq!((d, why.as_str()), (true, "same PR"));
1728    }
1729
1730    #[test]
1731    fn a_text_too_long_is_squeezed_and_still_judged() {
1732        let f = fx_with_run();
1733        let long = format!("{NAMES} {}", "x".repeat(prompt::DUPES_JUDGE_MAX_CHARS));
1734        let (out, calls) = judged(&f, &long, || verdict(false));
1735        assert!(matches!(out, Ok(Screened::Cleared(_))));
1736        assert_eq!(calls, 1);
1737    }
1738
1739    #[test]
1740    fn no_hit_never_asks_the_judge() {
1741        let (f, _, _) = fx();
1742        let (out, calls) = judged(&f, "nothing named here", || verdict(true));
1743        assert_eq!(out.unwrap(), Screened::Clean);
1744        assert_eq!(calls, 0);
1745    }
1746
1747    #[test]
1748    fn without_a_config_a_hit_passes_unjudged() {
1749        let f = fx_with_run();
1750        let hits = run(&f, NAMES, None);
1751        let out = tokio::runtime::Builder::new_current_thread()
1752            .build()
1753            .unwrap()
1754            .block_on(screen_with_config(hits, NAMES, None, &f.repo, None));
1755        assert!(matches!(out, Ok(Screened::Unjudged(_))));
1756    }
1757
1758    #[test]
1759    fn about_carries_title_and_whole_instruction() {
1760        assert_eq!(
1761            about_of("Retries", "# Task\nFix  auth\nretries"),
1762            "Retries: # Task Fix auth retries"
1763        );
1764        assert_eq!(about_of("", "x"), "x");
1765        let mid = format!("{} MIDDLE {}", "a ".repeat(2000), "b ".repeat(500));
1766        assert!(about_of("", &mid).contains("MIDDLE"));
1767        let long = format!("{} TAIL", "y ".repeat(5000));
1768        let a = about_of("", &long);
1769        assert!(a.ends_with("TAIL") && a.chars().count() < 6100, "{a}");
1770    }
1771}