Skip to main content

agentmux_srv_core/backend/kanban/
prs.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! The Kanban and GitHub (docs/specs/SPEC_WARDEN_KANBAN_2026_10_20.md §6.9, D5):
5//!
6//! - **Finding the PR.** When an agent holding one task opens a PR, the card
7//!   gets the PR's address once GitHub lists it, so the card links to it
8//!   without the agent naming it. A result that names one PR ("PR #12") does
9//!   the same at hand-in, when that PR is from the branch the agent is on: a
10//!   result that only mentions someone else's PR links nothing, so that PR's
11//!   merge can't close the task.
12//! - **Closing on merge.** A task in Review whose PR has merged is accepted:
13//!   the merge was the review. Off with the setting `kanban:closeonmerge`.
14//! - **Merged, then Released** (SPEC_KANBAN_STAGES_COLOURS_AND_NARROW_VIEW_2026_10_23.md
15//!   §4): a task's PR that merged is recorded with when (`work_prs.rs`), so
16//!   the board can show the task in Merged even while its agent still holds
17//!   it; and once a release of the repository was made from a commit at or
18//!   after that merge, the task is recorded as in that release (Released).
19//!   `main` is linear (a merge queue), so a release made after a merge
20//!   contains it.
21//!
22//! srv holds no GitHub credential, so both read GitHub's public API without
23//! one: they work for public repositories, and a private one stays as it was
24//! (the agent links its PR with `Tasks`, the operator accepts by hand). The
25//! unauthenticated API allows 60 calls an hour per address, shared with
26//! everything else on the computer (several AgentMux instances run on a busy
27//! one, the update check among them), so this spends at most [`HOURLY_BUDGET`]
28//! and stops until GitHub's reset when told it is over. (Measured: an
29//! unauthenticated 304 answer counts against the limit like a 200, so asking
30//! with an ETag would save nothing.) A `task dev` build doesn't ask at all,
31//! unless `AGENTMUX_KANBAN_PR_POLL` is set: it shares the computer's limit and
32//! its Kanban with the instance the person uses.
33
34use std::collections::HashMap;
35use std::sync::atomic::{AtomicI64, Ordering};
36use std::sync::Mutex;
37
38use serde_json::Value;
39
40use super::{publish_changed, CONTEXT};
41use crate::backend::storage::store::Store;
42use crate::backend::storage::work_board::{BoardTask, CardUpdate, WorkEvent};
43use crate::backend::storage::work_card_prs::{self, CardPrState, PrReport, PrSource};
44use crate::backend::storage::work_queue::work_state;
45
46/// The setting that stops a merged PR closing its task (default on).
47pub const SETTING_CLOSE_ON_MERGE: &str = "kanban:closeonmerge";
48const API: &str = "https://api.github.com";
49/// How often the loop looks for tasks to check.
50const TICK_MS: u64 = 60_000;
51/// How often one task's PR is asked about while open.
52const CHECK_EVERY_MS: i64 = 10 * 60 * 1000;
53/// ... and once it was closed without merging (it may be reopened).
54const CLOSED_CHECK_EVERY_MS: i64 = 60 * 60 * 1000;
55/// A repository GitHub doesn't show without a login isn't asked about again
56/// for this long.
57const PRIVATE_FOR_MS: i64 = 6 * 60 * 60 * 1000;
58/// The most calls this srv makes in an hour.
59pub const HOURLY_BUDGET: usize = 20;
60/// When to look for a just-opened PR, in seconds after the command was seen.
61const FIND_AFTER_S: [u64; 4] = [20, 60, 180, 600];
62/// How often one repository's releases are asked about, while a merged task
63/// of it waits to be released.
64const RELEASES_EVERY_MS: i64 = 30 * 60 * 1000;
65
66/// A PR on GitHub: `owner/repo` and its number.
67#[derive(Debug, Clone, PartialEq, Eq, Hash)]
68pub struct PrRef {
69    pub repo: String,
70    pub number: u64,
71}
72
73impl PrRef {
74    pub fn url(&self) -> String {
75        format!("https://github.com/{}/pull/{}", self.repo, self.number)
76    }
77}
78
79/// `owner/repo`, as the card stores a repository from its `origin` remote;
80/// not a local folder (`local:…`).
81fn github_repo(repo: &str) -> Option<String> {
82    work_card_prs::github_repo(repo)
83}
84
85/// The PR a card's link names: a GitHub PR address, `owner/repo#12`, or
86/// `#12` / `12` in the card's repository.
87pub fn parse_pr_ref(link: &str, card_repo: &str) -> Option<PrRef> {
88    let (repo, number) = work_card_prs::parse_pr_ref(link, card_repo)?;
89    Some(PrRef { repo, number })
90}
91
92/// The one PR a hand-in's text names ("PR #12", a PR address), when it names
93/// exactly one; `None` for none or several.
94pub fn pr_in_text(text: &str, card_repo: &str) -> Option<PrRef> {
95    let mut found: Vec<PrRef> = Vec::new();
96    let mut add = |p: Option<PrRef>| {
97        if let Some(p) = p {
98            if !found.contains(&p) {
99                found.push(p);
100            }
101        }
102    };
103    for word in text.split(|c: char| c.is_whitespace() || matches!(c, '(' | ')' | ',' | ';' | '<' | '>' | '[' | ']')) {
104        let word = word.trim_end_matches(['.', ':', '!']);
105        if word.contains("github.com/") {
106            add(parse_pr_ref(word, card_repo));
107        }
108    }
109    // "PR #12", "PR 12", "pull request #12".
110    let lower = text.to_ascii_lowercase();
111    for marker in ["pr #", "pr ", "pull request #", "pr#"] {
112        let mut from = 0;
113        while let Some(i) = lower[from..].find(marker) {
114            let at = from + i;
115            from = at + marker.len();
116            let before_ok = at == 0 || !lower.as_bytes()[at - 1].is_ascii_alphanumeric();
117            let digits: String = lower[from..].chars().take_while(char::is_ascii_digit).collect();
118            if before_ok && !digits.is_empty() {
119                add(parse_pr_ref(&digits, card_repo));
120            }
121        }
122    }
123    match found.as_slice() {
124        [one] => Some(one.clone()),
125        _ => None,
126    }
127}
128
129/// What GitHub says about a PR.
130#[derive(Debug, Clone, PartialEq, Eq)]
131pub enum PrState {
132    Open,
133    Merged,
134    Closed,
135    /// No such PR in a repository GitHub shows (a mistyped link).
136    Missing,
137}
138
139/// When GitHub's answer for one PR says it merged (ms).
140pub fn merged_at(v: &Value) -> Option<i64> {
141    rfc3339_ms(v.get("merged_at")?.as_str()?)
142}
143
144fn rfc3339_ms(s: &str) -> Option<i64> {
145    chrono::DateTime::parse_from_rfc3339(s).ok().map(|d| d.timestamp_millis())
146}
147
148/// The first release (oldest; not a draft) made from a commit at or after
149/// `merged_ms`, from GitHub's list of a repository's releases: its tag and
150/// when it was published (ms). A release's `created_at` is the date of the
151/// commit it was made from.
152pub fn release_containing(releases: &Value, merged_ms: i64) -> Option<(String, i64)> {
153    releases
154        .as_array()?
155        .iter()
156        .filter(|r| r.get("draft").and_then(Value::as_bool) != Some(true))
157        .filter_map(|r| {
158            let made = rfc3339_ms(r.get("created_at")?.as_str()?)?;
159            let tag = r.get("tag_name")?.as_str()?.to_string();
160            let published = r.get("published_at").and_then(Value::as_str).and_then(rfc3339_ms).unwrap_or(made);
161            (made >= merged_ms).then_some((made, tag, published))
162        })
163        .min_by_key(|(made, ..)| *made)
164        .map(|(_, tag, published)| (tag, published))
165}
166
167/// The state in GitHub's answer for one PR.
168pub fn pr_state(v: &Value) -> Option<PrState> {
169    if v.get("merged_at").is_some_and(|m| !m.is_null()) || v.get("merged").and_then(Value::as_bool) == Some(true) {
170        return Some(PrState::Merged);
171    }
172    match v.get("state")?.as_str()? {
173        "open" => Some(PrState::Open),
174        "closed" => Some(PrState::Closed),
175        _ => None,
176    }
177}
178
179/// What GitHub's answer for one PR tells the card's list: its state, head, and when it was opened and last
180/// changed. `None` for an answer that names no state.
181pub fn report_of(pr: &PrRef, v: &Value, now_ms: i64) -> Option<PrReport> {
182    let state = match pr_state(v)? {
183        PrState::Open => CardPrState::Open,
184        PrState::Merged => CardPrState::Merged,
185        PrState::Closed => CardPrState::Closed,
186        PrState::Missing => return None,
187    };
188    let at = |key: &str| v.get(key).and_then(Value::as_str).and_then(rfc3339_ms);
189    Some(PrReport {
190        repo: pr.repo.clone(),
191        number: pr.number,
192        state,
193        head: v.pointer("/head/sha").and_then(Value::as_str).map(str::to_string),
194        opened_at: at("created_at"),
195        merged_at: merged_at(v),
196        updated_at: at("updated_at").unwrap_or(now_ms),
197    })
198}
199
200/// Why a call came back with nothing.
201#[derive(Debug)]
202enum Miss {
203    /// Not there, or not shown without a login (a private repository).
204    NotFound,
205    /// Over the limit: nothing more for now.
206    Limited,
207    Other(String),
208}
209
210/// Calls made in the last hour, and when GitHub said to wait until.
211struct Budget {
212    calls: Mutex<Vec<i64>>,
213    wait_until: AtomicI64,
214}
215
216static BUDGET: Budget = Budget { calls: Mutex::new(Vec::new()), wait_until: AtomicI64::new(0) };
217
218/// Whether this srv may ask GitHub at all: a `task dev` build doesn't unless
219/// `AGENTMUX_KANBAN_PR_POLL` is set.
220fn polling_allowed() -> bool {
221    static ALLOWED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
222    *ALLOWED.get_or_init(|| {
223        let dev = matches!(agentmux_common::RuntimeMode::from_env(), Some(agentmux_common::RuntimeMode::Dev { .. }));
224        let asked = std::env::var_os("AGENTMUX_KANBAN_PR_POLL").is_some_and(|v| !v.is_empty());
225        let allowed = !dev || asked;
226        if !allowed {
227            tracing::info!("kanban: a dev build doesn't ask GitHub about PRs (AGENTMUX_KANBAN_PR_POLL=1 turns it on)");
228        }
229        allowed
230    })
231}
232
233impl Budget {
234    /// Take one call, if the hour's budget and GitHub allow it.
235    fn take(&self, now_ms: i64) -> bool {
236        if now_ms < self.wait_until.load(Ordering::Relaxed) {
237            return false;
238        }
239        let mut calls = self.calls.lock().unwrap_or_else(|e| e.into_inner());
240        calls.retain(|at| now_ms - at < 3_600_000);
241        if calls.len() >= HOURLY_BUDGET {
242            return false;
243        }
244        calls.push(now_ms);
245        true
246    }
247}
248
249async fn get(client: &reqwest::Client, path: &str, now_ms: i64) -> Result<Value, Miss> {
250    if !polling_allowed() || !BUDGET.take(now_ms) {
251        return Err(Miss::Limited);
252    }
253    let resp = client
254        .get(format!("{API}{path}"))
255        .header("User-Agent", concat!("AgentMux/", env!("CARGO_PKG_VERSION")))
256        .header("Accept", "application/vnd.github+json")
257        .timeout(std::time::Duration::from_secs(15))
258        .send()
259        .await
260        .map_err(|e| Miss::Other(e.to_string()))?;
261    let status = resp.status().as_u16();
262    if status == 403 || status == 429 {
263        let reset_s = resp
264            .headers()
265            .get("x-ratelimit-reset")
266            .and_then(|v| v.to_str().ok())
267            .and_then(|v| v.parse::<i64>().ok());
268        let until = reset_s.map(|s| s * 1000).unwrap_or(now_ms + 15 * 60_000).max(now_ms + 60_000);
269        BUDGET.wait_until.store(until, Ordering::Relaxed);
270        return Err(Miss::Limited);
271    }
272    if status == 404 || status == 401 {
273        return Err(Miss::NotFound);
274    }
275    if !resp.status().is_success() {
276        return Err(Miss::Other(format!("GitHub answered {status}")));
277    }
278    resp.json().await.map_err(|e| Miss::Other(e.to_string()))
279}
280
281fn history(identity: &Store, work_id: &str, kind: &str, from: &str, to: &str, body: &str, now_ms: i64) {
282    let ev = WorkEvent {
283        work_id: work_id.to_string(),
284        at: now_ms,
285        actor: "GitHub".into(),
286        actor_kind: "system".into(),
287        kind: kind.to_string(),
288        from_state: from.to_string(),
289        to_state: to.to_string(),
290        body: body.to_string(),
291        ..Default::default()
292    };
293    if let Err(e) = identity.work_event_add(&ev) {
294        tracing::debug!(error = %e, "kanban: history line not written");
295    }
296}
297
298/// Link a task to its PR, unless it has one already; `source` says whose finding it is (the holder's own
299/// `gh pr create`, or a hand-in's text). Returns whether it did.
300pub fn link(identity: &Store, work_id: &str, pr: &PrRef, source: PrSource, now_ms: i64) -> bool {
301    let Ok(Some(t)) = identity.work_board_get(work_id) else { return false };
302    if !t.card.pr_url.is_empty() {
303        return false;
304    }
305    let url = pr.url();
306    if identity.work_card_update(work_id, &CardUpdate { pr_url: Some(url.clone()), pr_source: Some(source), ..Default::default() }, now_ms).is_err() {
307        return false;
308    }
309    history(identity, work_id, "linked", &t.item.state, &t.item.state, &url, now_ms);
310    true
311}
312
313/// A task's PR merged: accept it, if it is still in Review. Returns whether
314/// it moved (another srv on this computer may have got there first).
315pub fn close_merged(identity: &Store, work_id: &str, pr: &PrRef, now_ms: i64) -> bool {
316    match identity.work_accept(work_id, now_ms) {
317        Ok(Some(m)) => {
318            history(identity, work_id, "accepted", &m.from, &m.to, &format!("PR #{} merged", pr.number), now_ms);
319            true
320        }
321        _ => false,
322    }
323}
324
325/// Whether closing on merge is on (`kanban:closeonmerge`, default on).
326pub fn close_on_merge_enabled(extra: &HashMap<String, Value>) -> bool {
327    extra.get(SETTING_CLOSE_ON_MERGE).and_then(Value::as_bool).unwrap_or(true)
328}
329
330/// When each task's PR was last asked about, and what came back; when each
331/// repository's releases were.
332#[derive(Default)]
333struct Checked {
334    at: HashMap<String, (i64, Option<PrState>)>,
335    private_repos: HashMap<String, i64>,
336    releases_at: HashMap<String, i64>,
337}
338
339/// Whether a task's PR is worth asking about: in Review (its merge closes
340/// it), held with a PR in review (Review, then Merged), or finished with a
341/// PR whose merge srv hasn't seen yet (its time decides its release).
342fn watched(t: &BoardTask) -> bool {
343    let merged = t.card.pr.as_ref().is_some_and(|p| p.merged_at.is_some());
344    match t.item.state.as_str() {
345        work_state::REVIEW => true,
346        work_state::CLAIMED | work_state::BLOCKED | work_state::DONE => !merged,
347        _ => false,
348    }
349}
350
351/// The tasks whose PR is due a look, oldest look first.
352fn due(tasks: &[BoardTask], checked: &Checked, now_ms: i64) -> Vec<(String, PrRef)> {
353    let mut out: Vec<(i64, String, PrRef)> = tasks
354        .iter()
355        .filter(|t| watched(t))
356        .filter_map(|t| Some((t.item.id.clone(), parse_pr_ref(&t.card.pr_url, &t.card.repo)?)))
357        .filter(|(_, pr)| checked.private_repos.get(&pr.repo).is_none_or(|at| now_ms - at >= PRIVATE_FOR_MS))
358        .filter_map(|(id, pr)| {
359            let last = match checked.at.get(&id) {
360                None => i64::MIN,
361                Some((at, state)) => {
362                    let every = match state {
363                        Some(PrState::Closed | PrState::Missing) => CLOSED_CHECK_EVERY_MS,
364                        _ => CHECK_EVERY_MS,
365                    };
366                    if now_ms - at < every {
367                        return None;
368                    }
369                    *at
370                }
371            };
372            Some((last, id, pr))
373        })
374        .collect();
375    out.sort_by_key(|(last, ..)| *last);
376    out.into_iter().map(|(_, id, pr)| (id, pr)).collect()
377}
378
379/// The merged, unreleased tasks by repository, for the repositories whose
380/// releases are due a look.
381fn awaiting_release(tasks: &[BoardTask], checked: &Checked, now_ms: i64) -> HashMap<String, Vec<(String, i64)>> {
382    let mut out: HashMap<String, Vec<(String, i64)>> = HashMap::new();
383    for t in tasks {
384        let Some(pr) = t.card.pr.as_ref() else { continue };
385        let (Some(merged), true) = (pr.merged_at, pr.released_in.is_empty()) else { continue };
386        let Some(r) = parse_pr_ref(&t.card.pr_url, &t.card.repo) else { continue };
387        if checked.releases_at.get(&r.repo).is_some_and(|at| now_ms - at < RELEASES_EVERY_MS) {
388            continue;
389        }
390        out.entry(r.repo).or_default().push((t.item.id.clone(), merged));
391    }
392    out
393}
394
395/// The tasks the merge loop looks at: every one not finished, and those
396/// finished within the board's window, so a task its agent completed when
397/// its PR merged is still followed to its release.
398fn watch_list(identity: &Store, now_ms: i64) -> Result<Vec<BoardTask>, crate::backend::storage::StoreError> {
399    identity.work_board_list(now_ms - super::FINISHED_WINDOW_MS, 500, now_ms)
400}
401
402/// The merge loop: every minute, ask GitHub about the PRs of the tasks
403/// that are due a look; record merges and releases, and accept a task in
404/// Review whose PR merged. Started once, after [`super::install`].
405pub async fn run_merge_loop() {
406    if !polling_allowed() {
407        return;
408    }
409    let mut checked = Checked::default();
410    loop {
411        tokio::time::sleep(std::time::Duration::from_millis(TICK_MS)).await;
412        let Some(ctx) = CONTEXT.get() else { continue };
413        // The setting stops a merge accepting a task in Review; merges and
414        // releases are still recorded, for the Merged and Released columns.
415        let close_on_merge = close_on_merge_enabled(&ctx.config.get_settings().extra);
416        let now = agentmux_common::time::now_ms();
417        let identity = ctx.identity.clone();
418        let tasks = tokio::task::spawn_blocking(move || watch_list(&identity, now)).await;
419        let Ok(Ok(tasks)) = tasks else { continue };
420        let live: std::collections::HashSet<&str> = tasks.iter().map(|t| t.item.id.as_str()).collect();
421        checked.at.retain(|id, _| live.contains(id.as_str()));
422        let mut changed = false;
423        // Releases first: one call a repository, so the PR checks, one a task,
424        // can't use the hour's budget up before a shipped task is seen.
425        for (repo, waiting) in awaiting_release(&tasks, &checked, now) {
426            match get(&ctx.http, &format!("/repos/{repo}/releases?per_page=30"), now).await {
427                Ok(list) => {
428                    checked.releases_at.insert(repo, now);
429                    let identity = ctx.identity.clone();
430                    changed |= tokio::task::spawn_blocking(move || {
431                        let mut any = false;
432                        for (id, merged) in waiting {
433                            if let Some((tag, published)) = release_containing(&list, merged) {
434                                any |= identity.work_pr_released(&id, &tag, published, now).unwrap_or(false);
435                            }
436                        }
437                        any
438                    })
439                    .await
440                    .unwrap_or(false);
441                }
442                Err(Miss::Limited) => break,
443                Err(_) => {
444                    checked.releases_at.insert(repo, now);
445                }
446            }
447        }
448        for (id, pr) in due(&tasks, &checked, now) {
449            match get(&ctx.http, &format!("/repos/{}/pulls/{}", pr.repo, pr.number), now).await {
450                Ok(v) => {
451                    let state = pr_state(&v);
452                    checked.at.insert(id.clone(), (now, state.clone()));
453                    // The card's list takes what GitHub says (an older report than its row is ignored).
454                    if let Some(report) = report_of(&pr, &v, now) {
455                        let identity = ctx.identity.clone();
456                        let id = id.clone();
457                        changed |= tokio::task::spawn_blocking(move || {
458                            identity.work_card_pr_apply(&id, &report, PrSource::Read, now).map(|a| a.changed).unwrap_or(false)
459                        })
460                        .await
461                        .unwrap_or(false);
462                    }
463                    if state == Some(PrState::Merged) {
464                        let identity = ctx.identity.clone();
465                        let (id, pr) = (id.clone(), pr.clone());
466                        let when = merged_at(&v).unwrap_or(now);
467                        changed |= tokio::task::spawn_blocking(move || {
468                            let noted = identity.work_pr_merged(&id, when, now).unwrap_or(false);
469                            (close_on_merge && close_merged(&identity, &id, &pr, now)) || noted
470                        })
471                        .await
472                        .unwrap_or(false);
473                    }
474                }
475                // A missing PR, or a repository GitHub doesn't show without a
476                // login: only the second sets the whole repository aside.
477                Err(Miss::NotFound) => match get(&ctx.http, &format!("/repos/{}", pr.repo), now).await {
478                    Ok(_) => {
479                        checked.at.insert(id, (now, Some(PrState::Missing)));
480                    }
481                    Err(Miss::NotFound) => {
482                        checked.private_repos.insert(pr.repo.clone(), now);
483                    }
484                    Err(Miss::Limited) => break,
485                    Err(Miss::Other(_)) => {
486                        checked.at.insert(id, (now, None));
487                    }
488                },
489                Err(Miss::Limited) => break,
490                Err(Miss::Other(e)) => {
491                    checked.at.insert(id, (now, None));
492                    tracing::debug!(error = %e, "kanban: a PR's state not read");
493                }
494            }
495        }
496        if changed {
497            publish_changed(&ctx.broker);
498        }
499    }
500}
501
502/// How much earlier than the `gh pr create` srv saw a PR may say it was
503/// created and still be taken for that command's: clocks differ.
504const CREATED_SLACK_MS: i64 = 5 * 60 * 1000;
505
506/// The PR a just-seen `gh pr create` opened, from a list GitHub gave: the
507/// first created since `since_ms` (less [`CREATED_SLACK_MS`]), from `branch`
508/// when one is given. An older PR from the same branch (merged long ago, or
509/// open before this command) is not this command's.
510pub fn pick_opened(list: &Value, branch: Option<&str>, since_ms: i64) -> Option<u64> {
511    list.as_array()?.iter().find_map(|p| {
512        let created = p.get("created_at")?.as_str()?;
513        let created_ms = chrono::DateTime::parse_from_rfc3339(created).ok()?.timestamp_millis();
514        if created_ms < since_ms - CREATED_SLACK_MS {
515            return None;
516        }
517        if let Some(b) = branch {
518            if p.pointer("/head/ref").and_then(Value::as_str) != Some(b) {
519                return None;
520            }
521        }
522        p.get("number")?.as_u64()
523    })
524}
525
526/// An agent holding `work_id` was seen at `seen_ms` opening a PR from `branch`
527/// in `repo` (from `owner`'s fork when `--head` named one): look for it on
528/// GitHub a few times as it appears, and link the first found that was
529/// created by then. Without `--head`, `gh` may have pushed to a fork of the
530/// user's, whose owner srv doesn't know: the last look takes the newest open
531/// PRs and matches the branch instead.
532pub fn find_opened(work_id: String, repo: String, owner: Option<String>, branch: String, seen_ms: i64) {
533    let Some(ctx) = CONTEXT.get() else { return };
534    let Some(repo) = github_repo(&repo) else { return };
535    let Some((repo_owner, _)) = repo.split_once('/') else { return };
536    let implicit_owner = owner.is_none();
537    let owner = owner.unwrap_or_else(|| repo_owner.to_string());
538    let head: String = url::form_urlencoded::byte_serialize(format!("{owner}:{branch}").as_bytes()).collect();
539    let by_head = format!("/repos/{repo}/pulls?head={head}&state=all&per_page=10");
540    let newest = format!("/repos/{repo}/pulls?state=open&sort=created&direction=desc&per_page=30");
541    tokio::spawn(async move {
542        let mut waited = 0;
543        for (i, after) in FIND_AFTER_S.iter().enumerate() {
544            tokio::time::sleep(std::time::Duration::from_secs(after - waited)).await;
545            waited = *after;
546            let now = agentmux_common::time::now_ms();
547            let mut number = match get(&ctx.http, &by_head, now).await {
548                Ok(v) => pick_opened(&v, None, seen_ms),
549                Err(Miss::NotFound) => return,
550                Err(_) => None,
551            };
552            if number.is_none() && implicit_owner && i + 1 == FIND_AFTER_S.len() {
553                number = match get(&ctx.http, &newest, now).await {
554                    Ok(v) => pick_opened(&v, Some(&branch), seen_ms),
555                    Err(_) => None,
556                };
557            }
558            if let Some(number) = number {
559                let pr = PrRef { repo: repo.clone(), number };
560                let identity = ctx.identity.clone();
561                let id = work_id.clone();
562                if tokio::task::spawn_blocking(move || link(&identity, &id, &pr, PrSource::Holder, now)).await.unwrap_or(false) {
563                    publish_changed(&ctx.broker);
564                }
565                return;
566            }
567        }
568    });
569}
570
571/// A hand-in named `pr` while its agent was on `branch` of `repo` (its
572/// `origin`): link it if that PR is from that branch of that repository, so a
573/// PR the result only mentions (someone else's, one it built on, a fork's
574/// same-named branch) isn't taken for the task's own.
575pub fn link_if_from(work_id: String, pr: PrRef, repo: String, branch: String) {
576    let Some(ctx) = CONTEXT.get() else { return };
577    if branch.is_empty() {
578        return;
579    }
580    tokio::spawn(async move {
581        let now = agentmux_common::time::now_ms();
582        let Ok(v) = get(&ctx.http, &format!("/repos/{}/pulls/{}", pr.repo, pr.number), now).await else { return };
583        if !is_from_branch(&v, &repo, &branch) {
584            return;
585        }
586        let identity = ctx.identity.clone();
587        if tokio::task::spawn_blocking(move || link(&identity, &work_id, &pr, PrSource::HandIn, now)).await.unwrap_or(false) {
588            publish_changed(&ctx.broker);
589        }
590    });
591}
592
593/// Whether GitHub's answer for a PR says it is from `branch` of `repo`
594/// (`owner/repo`).
595pub fn is_from_branch(pr: &Value, repo: &str, branch: &str) -> bool {
596    let same_ref = pr.pointer("/head/ref").and_then(Value::as_str).is_some_and(|r| !branch.is_empty() && r == branch);
597    let same_repo = pr
598        .pointer("/head/repo/full_name")
599        .and_then(Value::as_str)
600        .is_some_and(|r| !repo.is_empty() && r.eq_ignore_ascii_case(repo));
601    same_ref && same_repo
602}
603
604#[cfg(test)]
605#[path = "prs_tests.rs"]
606mod tests;