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