SLOPSHOPPER

pr-relay

Watches the session's pull request and wakes the session when it is merged or Codex reviews it

bandguardtoaststatusprompttool
★ 19v0.9.2no licenseupdated 2026-10-20HolyGrail/claude-mods/plugins/pr-relay
A shopper browsing a rack in a slop shop
README

pr-relay

セッションの PR を 1 分ごとに確かめ、マージされたときと Codex がレビューを付けたときだけセッションを起こす Claude Code の mod です。 人が GitHub を見て「マージした」「レビューが来た」と打たなくても、セッションが次の作業を始めます。 モデルがレビューの到着を待つために sleep やポーリングの tool を呼ぶ必要もなくなります。

監視する PR

Desktop アプリでは、セッションの PR バーの先頭に表示される PR(最後に紐付けた PR)を監視します。 新しい PR が紐付けられると、次の確認で監視先を切り替えます。 先頭の PR が再オープンした場合も、その PR の監視を始めます。 PR バーのほかの PR はマージとクローズだけを追い、トーストで知らせます。 マージされた PR には、それぞれ cleanup の行も出します。 この確認にはアプリのキャッシュを使い、GitHub への問い合わせは増やしません。

ターミナルでは、これまでどおりセッションの開始時に gh pr view で現在のブランチの OPEN な PR を探します。 Desktop アプリでも、先頭に OPEN な PR がない場合やアプリの情報を取得できない場合は、同じ方法で探します。

セッションの途中で gh pr create を実行すると、その出力の URL から監視を始めます。 gh pr new や gh -R owner/repo pr create も認識し、-Rowner/repo、--repo owner/repo、--repo=owner/repo の形式でも指定できます。 git push を実行したときに PR を監視していなければ、もう一度 gh pr view で探します。 git -C <dir> push では、指定したディレクトリのブランチの PR を探します。 相対パスはセッションの作業ディレクトリを基準にし、-C が複数ある場合は指定順に結合して、.. の解決はファイルシステムに任せます。 --work-tree=<dir> または --work-tree <dir> があれば、そのディレクトリの PR を探し、相対パスはすべての -C を適用した後のディレクトリを基準にします。 引用符で囲まれていない先頭の ~ や ~/ は HOME で展開し、引用符で囲まれたチルダは文字どおりの相対パスとして扱います。 ディレクトリに $ やバッククォートが含まれる場合、引用符のない ~user の形式の場合、HOME がなく ~ を展開できない場合は、その push による PR 検索を省略します。 1 回の Bash 呼び出しに複数の git push があり、解決した検索先のディレクトリが異なる場合も、push の追跡は続けて PR 検索だけを省略します。 git push-deploy や gh pr create-extra、gh pr new-extra は検出対象に含めません。 mcp__pr-relay__watch に pr_url を渡した場合も、その PR の監視を始めます。 Desktop アプリの先頭の PR が同じで OPEN のままなら、これらの方法で指定した監視先を保ちます。 アプリの情報が一部省略されても、確認済みの PR や状態は保ちます。

起こし方

GitHub で起きたことセッションへの知らせ方
Codex がレビューを付けた指摘の本文と場所を載せたプロンプトを送る
Codex が 👍 を付けた、または「Didn't find any major issues」とコメントしたCI の確認と完了の報告を促すプロンプトを送る
Codex の利用上限に達したトーストだけ出す
監視中の PR またはアプリに紐付いた PR のいずれかがマージされたトーストを出し、プロンプトの上の帯にその PR の cleanup ボタンを出す。押すと、マージ後の後処理(残った事項の issue 化、worktree とブランチの片付け、プロジェクト固有の手順など)を促すプロンプトを送る。監視中の PR なら、ほかのセッションへお知らせも出す
監視中の PR またはアプリに紐付いた PR がクローズされたトーストだけ出す

Desktop アプリで Auto-fix(CI モニター)が有効な PR では、Codex のレビュー、コメントによる approved、利用上限の通知を、コメント本文も届ける CI モニターに任せます。 その場合、pr-relay は Codex の 👍 とマージを引き続き知らせ、ステータス行に「CI モニター併用」と表示します。 先頭の PR はアプリの状態から、ほかの PR はセッションに届いた CI モニター自身の通知から Auto-fix が有効だと判断します。 アプリから PR の紐付けがないと報告された場合は、この判定をリセットします。 アプリが紐付いた PR の一覧を返した場合は、その一覧と先頭の PR から外れた PR の判定も解除します。 一覧が省略された場合は、これまでの判定を保ちます。

cleanup が頼むのは worktree の削除だけではなく、マージ後の後処理の全体です。 後処理は worktree やブランチを消すので、自動では始めずボタンにしています。 作業に使っているスキルやコマンドが後処理を定めていれば(/dev cleanup など)、プロンプトはそれに従うよう伝えます。 定めがなければ、次の順に進めるよう伝えます。

  1. PR の URL から、マージ済みであることとブランチを確かめる
  2. プロジェクトの CLAUDE.md が後処理を定めていれば、何かを消す前に読み、その手順と順序に従う
  3. 別の PR やスコープ外に回した事項が残っていれば、issue にするかをユーザーに確かめる
  4. そのブランチを checkout している worktree を探し、worktree とローカルブランチを片付ける。リモートのブランチが残っていれば、消すかをユーザーに確かめる
  5. 何をして、何を見送ったかを報告する

スキルの手順に従う場合も含めて、worktree が見つからないときや別のリポジトリの PR のときは、何も消さずに報告するよう伝えます。 消す前には未コミットの変更や push していないコミットを確かめ、残っていれば消さずに報告するよう伝えます。 cleanup の行は新しいものから最大 3 件を表示し、cleanup と 閉じる はその行だけに作用します。 デスクトップでは各行を角丸の枠で囲み、使用量メーターとは別のカードとして表示します。 監視先が変わってもほかの PR の行は残り、同じ PR を再び監視するとその行を消します。 アプリで OPEN と確認した PR の行も消します。 アプリのほかの PR は、このセッションで OPEN だったものがマージまたはクローズされたときだけ知らせます。 /resume、/clear、/branch で会話が変わると、アプリの PR の状態と cleanup の行をリセットします。 マージとクローズを見たら、その PR のポーリングは止めます。

ほかのセッションへのお知らせ

PR がマージされると、同じリポジトリで作業しているほかのセッションのブランチは、マージ先より古くなります。 監視中の PR のマージを見たセッションは、notice-board の /notice で次のお知らせを出します。

main advanced (#12). Rebase before the next push.

main の位置には、PR のマージ先のブランチ名が入ります。 ブランチ名が - で始まる場合は、/notice のオプションと読まれないよう Branch を前に付けます。 rebase を次の push の前まで待たせるのは、作業の途中で rebase すると、コンフリクトの解消が実装の変更と混ざるからです。

お知らせを出さない場合が 4 つあります。

  • notice-board が入っていない。/notice が存在しないので、トーストと cleanup ボタンだけが出ます
  • PR がマージされずにクローズされた。マージ先は進んでいません
  • PR がセッションのリポジトリのものではない(mcp__pr-relay__watch に別のリポジトリの URL を渡した場合など)。/notice はセッションのリポジトリ宛てに出るので、origin が PR の GitHub リポジトリと一致するときだけ出します
  • アプリの PR バーにある、監視中ではない PR がマージされた。こちらはトーストと cleanup の行だけです

同じ PR を複数のセッションが見ていても、お知らせを出すのはトーストを出すセッションだけです。 notice-board は投稿したセッションにも同じお知らせを伝えるので、マージを見たセッション自身の帯とモデルにも届きます。 2 つのセッションがまったく同時にマージを見た場合は、同じお知らせが 2 件並ぶことがあります。 お知らせは自動では消えないので、不要になったら /notice clear で消してください。 /notice はセッションが待機中になってから実行されるので、お知らせは数分遅れることがあります。

プロンプトは $.prompt.submit で送るので、実行中のターンには割り込まず、セッションが待機中になってから新しいターンを始めます。

ステータス行には、監視中の PR 番号と最後に確かめた時刻(JST)を出します。 起動時に gh pr view が失敗して PR を探せなかったとき(未認証、ネットワークの切断)は、PR 検索失敗 21:00: <gh のエラー> を出し、1 分ごとに探し直します。 git リポジトリではないフォルダ、remote のないリポジトリ、detached HEAD で開いたセッションは、探す PR がそもそもないので、失敗ではなく「PR なし」として扱います。 ステータス行には何も出さず、git push を実行するまで探し直しません。 gh pr create が出力した URL は、探し直しを待たずにその場で監視に入ります。

Codex の判定

Codex の 👍 は PR に 1 つしか付かず、作成時刻が前の push のときのまま残ることがあります。 そのため「👍 がある」だけでは approved と見なさず、最後の push より後のイベントだけを数えます。

最後の push の時刻には、次のうち最も新しいものを使います。

  • mcp__pr-relay__watch の since で指定した時刻、または gh pr create を始めた時刻
  • このセッションで git push を始めた時刻(push が終わってから、PR の head がその push の出力にあるコミットになったときだけ使う。出力にコミットがなければ、push 開始時に分かっていた head から変わったときに使う。Everything up-to-date や別ブランチへの push では基準時刻を進めない)
  • PR の最新コミットのコミット時刻

まだ知らせていないレビューがあれば、approved より先に知らせます。 最新のレビューより後に approved のイベントがあれば、レビューのプロンプトの末尾にその時刻を添え、別の approved のプロンプトは送りません。 最新のレビュー以前の approved も通知済みとして記録し、レビューだけを知らせます。

レビューを知らせるときだけ、対象のレビューの詳細を 1 回の追加クエリで取得し、指摘の本文と場所、コメント ID、URL をプロンプトに載せます。 本文は 1 件につき 4,000 文字で切り、プロンプト全体は 30,000 文字以内に収めます。 各レビューの inline コメントは 100 件まで取得し、載せきれないコメントは残りの件数と PR の files ページで案内します。 inline コメントがないレビューでは、<details> の部分を除いたレビュー本文を載せます。 詳細を取得できなくても、件数と gh api でコメントを読む手順を載せてセッションを起こします。

mod は通知済みかどうかを記録しますが、指摘への対応が済んだかや、現在の head がレビュー済みかは判定しません。 利用上限のトーストは、最後の push より後に上限のコメントがあれば、上限が解けた後でも出ます。

監視中の PR について、知らせたイベントは $.store に PR ごとに記録します。 同じ PR を見ている別のセッションや、再起動したセッションが、同じイベントでもう一度起こされることはありません。 同じ PR を複数のセッションが同時に確かめたときは、先に確認を始めたセッションだけを起こします(下の「制約」)。 プロンプトがセッションに入らなかったとき(送信の失敗や、別の plugin による拒否)は記録を戻し、次の確認で送り直します。

/dev スキルと組み合わせるとき

mod はツール mcp__pr-relay__watch を登録するので、モデルのツール一覧にこのツールがあれば mod が動いています。 /dev スキルからこのツールに pr_url と since を渡すと、PR と最後の push の時刻を mod に伝えられます。 引数なしで呼ぶと、監視中の PR を返します。 ツールの説明では、mod が監視している間はモデル自身でポーリングせず、ターンを終えて起こされるのを待つよう伝えています。 mod はスキルがないセッションでも動き、レビューへの対応や作業の完了に必要な手順をプロンプトで伝えます。

使い方

gh が PATH にあり、認証済みである必要があります。

インストール

Claude Code のプロンプトで、次の 3 つを順に実行します。

/plugin marketplace add HolyGrail/claude-mods
/plugin install pr-relay@claude-mods
/reload-plugins

更新の手順と注意点は、リポジトリの README にまとめてあります。

インストールせずに試す

clone したリポジトリのルートで、次のように起動します。

claude --plugin-dir ./plugins/pr-relay

手元のコードを常に読み込むなら、~/.claude/settings.json の env にある CLAUDE_CODE_PLUGIN_DIRS にこのディレクトリの絶対パスを足します。

制約

GitHub への定期的な問い合わせは、1 分に 1 回の GraphQL クエリです。 レビュー、コメント、👍 はそれぞれ新しい順に 100 件まで取り、100 件目がまだ最後の push より後なら、前のページを最大 10 ページまでたどります。 レビューを知らせるときは、指摘の本文を取得するクエリを 1 回追加します。 単純なクエリは 1 回 1 ポイントなので、12 セッションが同時に動いても毎時 720 ポイントで、上限の毎時 5,000 ポイントに収まります。

監視開始時に基準時刻が指定されず、どのセッションも git push の実行を見ていない PR では、最新コミットのコミット時刻を最後の push の時刻とみなします。 コミットしてから push するまでの間に付いた Codex のイベントを、新しいものと見なすことがあります。

$.store には atomic な更新がないので、同じ PR を見ているセッションは、確認を始めるたびに自分のキー(poll:<セッション ID>:<PR>)へ開始時刻を書きます。 30 秒以内に同じ PR の確認を先に始めたセッション、またはそれより前に始めてまだ GitHub の応答を待っているセッション(10 分まで)があれば、新しいイベントの通知はそのセッションに任せ、PR の記録にも書きません(読んだ時点より古い内容で上書きしないため)。 自分が知っている push の時刻(監視開始時の基準時刻や、GitHub にまだ head が反映されていない自分の git push を含む)は確認の開始時から自分のキーに書き、通知するセッションがそれを読んで基準時刻に加えます。 1 つのセッションの中では、前の確認が GitHub の応答を待っている間は次の確認を始めません。 GitHub への問い合わせは store への書き込みよりずっと長くかかるので、問い合わせの後に読めば先のセッションの書き込みが見えるという前提です。 任されたセッションが通知の前に終了しても、次の確認(1 分後)で残ったセッションが送ります。 確認に失敗したセッションや終了したセッションのキーは、通知を任される対象から外れますが、知っていた push の時刻は残ります。 このキーは 1 時間で消しますが、PR の記録がまだ数えていない push の時刻を持つものは 14 日まで残します。 マージやクローズも任されたセッションだけがトーストを出し、任せた側は次の確認で記録からそれを知って、ポーリングを止め cleanup ボタンを出します。 自分のキーを書けなかった確認は、他のセッションから見えないので、GitHub に問い合わせずに失敗としてステータス行に出します。 他のセッションのキーを読めなかった確認も、何も通知せずに失敗として出します。 どれかのセッションが git push を実行している間(開始から 10 分まで)は、GitHub がまだ置き換わる前の head を見せていることがあるので、どのセッションも通知しません。 どのセッションが起こされるかは確認の順番で決まり、/dev のセッションを優先するわけではありません。

gh の失敗(未認証、ネットワークの切断)はステータス行に出し、次の確認で再試行します。 レビュー詳細の取得に失敗した場合は、再試行を待たずにコメントの確認手順をプロンプトで伝えます。

CI の結果は監視しません。 Desktop アプリが PR の CI の結果をセッションへ送るので、両方で見ると同じ失敗で二重に起こされます。

テスト

cd plugins/pr-relay
claude plugin test
Source 1 files
hooks/register.js 1638 lines
1// Watches this session's pull request on a timer and wakes the session only when something
2// changed: a merge, a Codex review, or Codex's thumbs-up. The model then never has to poll.
3
4// How often to ask GitHub about the pull request. One GraphQL query a tick costs one point of the
5// 5,000 an hour, so even a dozen sessions polling at once stay far below the limit.
6const TICK_MS = 60_000
7// The desktop app exposes its cached pull requests through this tool
8const DESKTOP_STATUS = 'mcp__ccd_pr__get_status'
9// Codex's login as GraphQL spells it (REST adds "[bot]")
10const CODEX = 'chatgpt-codex-connector'
11// What this module has already relayed for a pull request lives under this prefix plus its URL, in
12// $.store, so another session on the same pull request, or this one after a restart, is not woken
13// again for the same event
14const KEY_PREFIX = 'pr:'
15// Each session notes under this prefix plus its id and the pull request's when it last started a
16// poll of it, as { pr, at, since, pending?, running?, idle? }, so sessions polling the same pull
17// request together let only the first of them relay. since is the last push the session knows of,
18// which the session that relays takes from it, and pending a push it ran that counts once the head
19// has moved, { at, head } with the head it last saw;
20// running stays set until the poll has written what it relayed; idle marks a note whose session
21// stopped polling, kept only for its since. A session writes only its own key, since $.store has
22// no atomic update.
23const POLL_PREFIX = 'poll:'
24// Polls of one pull request that started this close together are one round: the one that started
25// first relays what is new, and the others leave it to that one. The query a poll waits on takes
26// far longer than a store write, so each of them sees the earlier one's note by the time it reads.
27const ROUND_MS = 30_000
28// A poll still running holds back the later ones of other sessions past its round, since it has not
29// written what it relayed yet; one this old is taken to belong to a session that died mid-poll
30const RUNNING_MS = 10 * 60_000
31const LATE = 'poll outlasted its turn'
32const PR_URL = /https:\/\/github\.com\/([\w.-]+)\/([\w.-]+)\/pull\/(\d+)/
33// Option values are one unquoted, single-quoted or double-quoted shell word
34const SHELL_WORD = String.raw`(?:"[^"]*"|'[^']*'|[^\s"';&|<>]+)`
35// Accepts gh pr create or new, optionally preceded by -R repo, -Rrepo, --repo repo or --repo=repo
36const GH_PR_CREATE = new RegExp(String.raw`\bgh\s+(?:(?:-R\s*|--repo(?:\s+|=))${SHELL_WORD}\s+)*pr\s+(?:create|new)(?=$|[\s;&|)])`)
37const GIT_OPTION = String.raw`(?:-C\s+(${SHELL_WORD})|--work-tree(?:=|\s+)(${SHELL_WORD})|-c\s+${SHELL_WORD}|--git-dir(?:=|\s+)${SHELL_WORD}|--no-pager)`
38// Accepts git push with any combination of -C dir, -c key=value, --git-dir=dir,
39// --work-tree=dir and --no-pager before push, including space-separated directory values
40const GIT_PUSH = new RegExp(String.raw`\bgit\s+((?:${GIT_OPTION}\s+)*)push(?=$|[\s;&|)])`, 'g')
41// What gh pr view says when there is no pull request to find, as opposed to failing to ask: the
42// branch has none, the directory is not a git repository, the repository has no remote, or HEAD is
43// detached. A remote on an unknown host is left out: gh says the same of one not logged in to.
44const NO_PR = /no pull requests found|not a git repository|no git remotes found|not on any branch/i
45// The session.end reasons after which this module stops
46const FINAL_REASONS = ['prompt_input_exit', 'other']
47
48const HOUR_MS = 3_600_000
49// Records of pull requests that ended and are untouched this long are of no more use. One left
50// open keeps what was relayed for it far longer, since a session that finds it again would
51// otherwise be woken for the same events.
52const STALE_MS = 14 * 24 * HOUR_MS
53const OPEN_STALE_MS = 90 * 24 * HOUR_MS
54// Events are paged back only to the previous poll of the same watch, less this much
55const PAGE_OVERLAP_MS = 5 * 60_000
56// How a pull request that is no longer open reads
57const ENDED = { MERGED: 'マージ', CLOSED: 'クローズ' }
58// JST has no daylight saving time, so a fixed offset gives its clock
59const JST_OFFSET_MS = 9 * HOUR_MS
60
61// The newest events come last, and only those after the last push count. A page holds 100, the
62// most GraphQL gives; a connection whose oldest item on it is still after the push is followed
63// back a page at a time, up to MAX_PAGES.
64const PAGE = 'last: 100, before: $before'
65const PAGE_INFO = 'pageInfo { hasPreviousPage startCursor }'
66const CONNECTIONS = {
67  reactors: `reactionGroups { content reactors(${PAGE}) { ${PAGE_INFO} edges { reactedAt node { ... on Bot { login } ... on User { login } } } } }`,
68  reviews: `reviews(${PAGE}) { ${PAGE_INFO} nodes { id databaseId fullDatabaseId submittedAt author { login } comments { totalCount } } }`,
69  comments: `comments(${PAGE}) { ${PAGE_INFO} nodes { createdAt author { login } body } }`,
70}
71const MAX_PAGES = 10
72const queryOf = (fields) => `query($owner: String!, $name: String!, $number: Int!, $before: String) {
73  repository(owner: $owner, name: $name) { pullRequest(number: $number) { ${fields} } }
74}`
75const QUERY = queryOf(`state headRefOid headRefName baseRefName commits(last: 1) { nodes { commit { committedDate } } } ${Object.values(CONNECTIONS).join(' ')}`)
76// Review bodies stay out of the per-minute query so gh's output does not get cut
77const REVIEW_QUERY = `query($ids: [ID!]!) {
78  nodes(ids: $ids) { ... on PullRequestReview {
79    databaseId fullDatabaseId url submittedAt commit { oid } body
80    comments(first: 100) { totalCount nodes { databaseId fullDatabaseId path line originalLine url body outdated replyTo { id } subjectType } }
81  } }
82}`
83// The most characters of a body to include before linking to the full text
84const BODY_LIMIT = 4_000
85// The most characters in a review prompt, including the omitted count and approval note
86const PROMPT_LIMIT = 30_000
87
88// The pull request this session watches: { url, id, owner, name, number, since, pagedAt?, ended? },
89// or null. since is the last push the watch started from.
90let watched = null
91// The timers that poll it, kept so the next watch or session.start can stop them
92let timers = []
93// Bumped by every watch and stop, so a poll or a lookup started before leaves the state alone
94let generation = 0
95// The last poll: { at, error? }, for the status line
96let lastCheck = null
97// The last lookup of the pull request when gh could not answer it, { at, error }, for the status line
98let lookupFailure = null
99// The generation of the poll running now, so a tick that comes while one still waits on GitHub
100// leaves it its note rather than overwriting it with a later round's
101let polling = null
102// The last push this session knows of for the watched pull request, which its poll note carries
103let knownSince = 0
104// The head of the watched pull request as this session's last poll found it, and when
105let lastHead = null
106let lastHeadAt = 0
107// This session's latest poll note, { key, pr, at, since, pending, running, serial }, as last written,
108// so an older poll does not mark it finished, a push can update it and a stop can leave it idle
109let lastNote = null
110// The notes a stop left idle, by key, which a push that finishes later still updates
111const retired = new Map()
112// The last write of each note key still going out
113const noteWrites = new Map()
114// Tells apart the polls of one session, which may share a key and a time
115let noteSerial = 0
116// Cleanup offers stay newest first, with at most three rows shown
117let cleanupOffers = []
118// Offers waiting for their prompts stay in order but are hidden until submission settles
119const cleanupPending = new Set()
120// Desktop availability is asked once per conversation and kept separately from watch timers
121let desktopAvailable = null
122// The desktop timer survives a watch change or the watched pull request ending
123let desktopTimer = null
124// This generation is reading the desktop cache, so slow calls do not pile up within a watch
125let desktopPolling = null
126// Successful desktop reads keep the last primary URL here
127let lastPrimary = null
128// A primary becoming open counts as a change even when its URL stays the same
129let lastPrimaryOpen = false
130// This map keeps the last known bound states in this conversation by parsed URL id
131let boundStates = new Map()
132// The desktop CI monitor relays comments for these pull requests in this conversation
133const monitored = new Set()
134// The git push calls this session ran for the watched pull request that have not counted yet, each
135// { id, pr, at, head, shas, refs, running }: its own id, the pull request it was bound to (null when
136// none was watched), when it started, the head the pull request had as far as the session knew
137// then, and once it has finished, the commits it moved refs to and the commit each branch moved to
138// (null when its output does not say). A push becomes the baseline only once GitHub shows what it pushed, since one that changed
139// nothing ("Everything up-to-date", another branch) must not hide the events that came before it.
140// Notes hold the same objects, so a push that finishes after the session turned to another pull
141// request still updates the note it was in.
142let pushes = []
143// How many pushes this session started for each pull request
144const pushStarts = new Map()
145// The session id as last asked, so a push need not wait on it
146let sessionId = null
147let idAsks = 0
148// git push calls still running. While one is, what Codex said may be about the head it replaces,
149// so nothing is relayed until it ends.
150// The read, change and write of a record in this session, one after another: a poll and a send
151// that takes its mark back would otherwise each write what they read before the other wrote
152let writes = Promise.resolve()
153
154export function register(on) {
155  // Fires again on an enable or a worker respawn, which may keep this module's variables
156  on('session.start', async ($, e, next) => {
157    sessionIdOf($).catch(() => {})
158    stop({ desktop: true })
159    await retire($)
160    reset($)
161    await $.tool.register({
162      name: 'watch',
163      description:
164        'pr-relay polls a pull request for this session and sends a prompt when it is merged, when Codex ' +
165        'reviews it, or when Codex gives it a thumbs-up. While it watches, do not poll for those yourself ' +
166        '(sleep loops, polling scripts, ScheduleWakeup): end the turn and wait to be woken. ' +
167        'Without arguments, returns what it watches. With pr_url, watches that pull request; since (ISO ' +
168        '8601) is the last push, and only Codex activity after it counts.',
169      inputSchema: {
170        type: 'object',
171        properties: {
172          pr_url: { type: 'string', description: 'https://github.com/<owner>/<repo>/pull/<number>' },
173          since: { type: 'string', description: 'The last push, ISO 8601' },
174        },
175      },
176    })
177    startDesktop($)
178    // Finding the pull request calls tools, so it starts once the session is ready
179    timers.push($.clock.after(0, () => discover($)))
180    return next(e)
181  })
182
183  on('session.end', async ($, e, next) => {
184    if (FINAL_REASONS.includes(e.reason)) {
185      stop({ desktop: true })
186      await retire($)
187    }
188    return next(e)
189  })
190
191  // /resume can turn this process to another conversation without a new session.start, and that
192  // conversation may belong to another worktree and pull request. /clear and /branch (fork) go on
193  // in the same one, but under a new id as well: the note under the last id is left idle, since
194  // that conversation no longer runs here, and the pull request is looked up again
195  on('classic.SessionStart', { source: ['resume', 'clear', 'fork'] }, async ($, e, next) => {
196    // The new conversation has its own id, so a push before its first poll must not write under
197    // the last one's
198    sessionId = null
199    sessionIdOf($).catch(() => {})
200    stop({ desktop: true })
201    await retire($)
202    reset($)
203    startDesktop($)
204    timers.push($.clock.after(0, () => discover($)))
205    return next(e)
206  })
207
208  on('tool.call', { tool: 'mcp__pr-relay__watch' }, async ($, e) => {
209    if (typeof e.pr_url === 'string') {
210      if (!PR_URL.test(e.pr_url)) return { result: `Not a pull request URL: ${e.pr_url}` }
211      const since = typeof e.since === 'string' ? Date.parse(e.since) : NaN
212      watch($, { url: e.pr_url, since: Number.isNaN(since) ? 0 : since })
213    }
214    return { result: describe() }
215  })
216
217  on('prompt.submit', async ($, e, next) => {
218    if (e.origin?.kind !== 'sdk' || typeof e.text !== 'string' || !e.text.startsWith('<ci-monitor-event>')) return next(e)
219    let result
220    try {
221      result = await next(e)
222      if (result?.drop === undefined) {
223        // Only the notice's first line names its pull request; later lines may quote GitHub text
224        const firstLine = e.text.slice('<ci-monitor-event>'.length).trimStart().split(/\r?\n/, 1)[0]
225        const match = firstLine.match(/\bwatching ([\w.-]+\/[\w.-]+) PR #(\d+)\b/)
226        if (match) monitored.add(parse(`https://github.com/${match[1]}/pull/${match[2]}`).id)
227      }
228    } catch {}
229    return result
230  })
231
232  on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
233    const command = e.command ?? ''
234    // Best effort: a push made another way is caught by the head commit's date, and session.start
235    // looks up the branch's pull request
236    const creates = GH_PR_CREATE.test(command)
237    const pushMatches = creates ? [] : [...command.matchAll(GIT_PUSH)]
238    const pushing = pushMatches.length > 0
239    if (!creates && !pushing) return next(e)
240    // Bound to the pull request watched as the push starts, before anything else can turn the
241    // watch to another
242    const prId = watched && !watched.ended ? watched.id : null
243    // A failure to publish is shown only while the watch the push started under lasts
244    const watchGen = generation
245    // Codex reviews what was pushed, so its earlier activity says nothing about this push. The push
246    // is counted as started before anything is awaited, so a poll finishing meanwhile holds back
247    // what it read from the head being replaced; a watch that turns to another pull request while
248    // the time is read leaves it behind with the rest of the last one's pushes
249    let push = null
250    if (pushing) {
251      push = { id: null, pr: prId, at: null, head: null, shas: null, running: true }
252      if (prId) pushStarts.set(prId, (pushStarts.get(prId) ?? 0) + 1)
253      pushes.push(push)
254    }
255    // The time is set before the push runs, so a poll that sees the new head while it is still
256    // finishing already applies it, and put back if the push failed
257    const startedAt = await $.clock.now()
258    if (pushing) {
259      push.at = startedAt
260      // id tells parallel pushes started in the same millisecond apart, in this session and others
261      push.id = pushId(startedAt)
262      for (const note of notesOf(prId)) {
263        note.pending = [...note.pending.filter((p) => p !== push), push]
264        note.dirty = true
265      }
266      // A pull request with no note yet (its first poll has not written one, or the watch turned
267      // away first) gets an idle one, so the other sessions see the push run; the first poll takes
268      // it up
269      if (prId && !notesOf(prId).length) {
270        // The id is known from the start, so the push goes out without waiting on it
271        const key = `${POLL_PREFIX}${sessionId ?? (await sessionIdOf($))}:${prId}`
272        if (!notesOf(prId).length) retired.set(key, { key, pr: prId, at: startedAt, since: 0, pending: [push], idle: true, dirty: true })
273      }
274      // The other sessions hold back their relays only if they can see the push, so it goes out
275      // running before its head is looked up, and again with the head; a store that will not take
276      // it is shown rather than holding up the push
277      const publish = () =>
278        refreshNote($, { strict: true }).catch((error) => {
279          if (generation !== watchGen || (watched?.id ?? null) !== prId) return
280          lastCheck = { at: startedAt, error: `push note: ${error?.message ?? error}` }
281          showStatus($)
282        })
283      await publish()
284      push.head = await headBefore($, prId)
285      for (const note of notesOf(prId)) note.dirty = true
286      await publish()
287      // Codex activity that came while the notes went out is still about the head being replaced,
288      // so the push counts from when it actually runs; the notes take the time with its end
289      push.at = await $.clock.now()
290      for (const note of [lastNote, ...retired.values()]) if (note?.pending.includes(push)) note.dirty = true
291      // The other sessions hold back for RUNNING_MS from the time they see, so they see this one
292      await publish()
293      // Activity that came while that went out is still about the head being replaced, so the push
294      // counts from here; the notes take this time with the push's end, which is when it applies
295      push.at = await $.clock.now()
296      for (const note of [lastNote, ...retired.values()]) if (note?.pending.includes(push)) note.dirty = true
297      // and the other sessions hold back from it too, so it goes out as Bash runs, not before
298      publish()
299    }
300    // The other sessions hold back their relays only while the push runs
301    const finish = async ({ dropped = false, shas = null, refs = null } = {}) => {
302      // A poll whose GitHub answer came before this may have seen the head the push replaced
303      push.doneAt = await $.clock.now()
304      push.running = false
305      if (dropped) push.dropped = true
306      else {
307        push.shas = shas
308        push.refs = refs
309      }
310      pushes = pushes.filter((p) => !p.dropped)
311      for (const note of [lastNote, ...retired.values()]) if (note?.pending.includes(push)) note.dirty = true
312      await refreshNote($)
313    }
314    let ran
315    try {
316      ran = await next(e)
317    } catch (error) {
318      // Whether it pushed is unknown, so it counts only once the head moves
319      if (push) await finish().catch(() => {})
320      throw error
321    }
322    // A push that failed or moved nothing says nothing about what Codex reviewed
323    const failed = ran.deny !== undefined || ran.isError
324    const moved = push && !failed ? pushedCommits(ran) : null
325    if (push) await finish({ dropped: failed || moved?.shas.length === 0, shas: moved?.shas, refs: moved?.refs })
326    if (failed) return ran
327    if (creates) {
328      const url = ran.text?.match(PR_URL)?.[0]
329      if (url) watch($, { url, since: startedAt })
330    } else {
331      if (!watched || watched.ended) timers.push($.clock.after(0, async () => {
332        const directories = await Promise.all(pushMatches.map((match) => pushDirectory($, match[1])))
333        if (directories.includes(null)) return
334        const cwd = directories[0]
335        // A Bash call may push several repositories, so only an unambiguous directory is looked up
336        if (directories.length > 1) {
337          const sessionCwd = directories.includes(undefined) ? await $.session.cwd() : undefined
338          if (directories.some((dir) => (dir ?? sessionCwd) !== (cwd ?? sessionCwd))) return
339        }
340        await discover($, { branchOnly: true, cwd })
341      }))
342    }
343    return ran
344  })
345
346  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
347    if (!cleanupOffers.length) return next(e)
348    const elements = $.ui.resolve(e)
349    const lines = cleanupOffers.filter((offer) => !cleanupPending.has(offer)).slice(0, 3).map((offer) => {
350      const { url, number } = offer
351      const { id } = parse(url)
352      const close = () => {
353        cleanupOffers = cleanupOffers.filter((entry) => entry !== offer)
354        $.ui.invalidate('ui.render')
355      }
356      return elements.Box({
357        flexDirection: 'row',
358        columnGap: 2,
359        // On the desktop each offer is a card of its own, apart from the meters below it
360        ...(e.surface === 'desktop' && { borderStyle: 'round', paddingX: 1 }),
361        children: [
362          elements.Text({ children: [`PR #${number} がマージされました`] }),
363          elements.Button({
364            key: `cleanup-${id}`,
365            label: 'cleanup',
366            variant: 'primary',
367            onPress: async () => {
368              cleanupPending.add(offer)
369              $.ui.invalidate('ui.render')
370              // The merge's whole aftermath, not only the worktree: a workflow that defines its
371              // own (the dev skill's /dev cleanup) takes over, and the URL stays in the first
372              // sentence, which that skill matches against its sessions
373              const text =
374                `PR ${url} がマージされました。この PR のマージ後の後処理を進めてください。\n` +
375                'この作業で使っているスキルやコマンドがマージ後の後処理を定めていれば (/dev cleanup など)、それに従ってください。定めがなければ、次の順に進めてください。\n' +
376                `1. gh pr view ${url} --json state,headRefName,headRepository で、マージ済みであることとブランチを確かめる。\n` +
377                '2. プロジェクトの CLAUDE.md がマージ後の後処理を定めていれば、何かを消す前に読み、その手順と順序に従う。\n' +
378                '3. この作業で別の PR やスコープ外に回した事項が残っていれば、issue にするかをユーザーに確かめる。\n' +
379                '4. git worktree list でそのブランチを checkout している worktree を探し、worktree とローカルブランチを片付ける。リモートのブランチが残っていれば、消すかをユーザーに確かめる。\n' +
380                '5. 何をして、何を見送ったかを報告する。\n' +
381                'worktree が見つからない場合や、別のリポジトリの PR の場合は、何も消さずに報告してください。\n' +
382                '消す前に、未コミットの変更や push していないコミットが残っていないかを確かめ、残っていれば消さずに報告してください。'
383              // A prompt that did not enter reveals its row in place, unless a new watch or a
384              // conversation reset removed that offer while it waited
385              if (await submit($, text)) close()
386              cleanupPending.delete(offer)
387              $.ui.invalidate('ui.render')
388            },
389          }),
390          elements.Button({ key: `dismiss-${id}`, label: '閉じる', role: 'dismiss', onPress: close }),
391        ],
392      })
393    })
394    // Keep what the mods after this one draw in the band
395    const rest = await next(e)
396    return elements.Box({
397      flexDirection: 'column',
398      ...(e.surface === 'desktop' && { rowGap: 1 }),
399      children: [...lines, ...(rest ? [rest] : [])],
400    })
401  })
402}
403
404function reset($) {
405  watched = null
406  lastCheck = null
407  lookupFailure = null
408  cleanupOffers = []
409  cleanupPending.clear()
410  desktopAvailable = null
411  desktopPolling = null
412  lastPrimary = null
413  lastPrimaryOpen = false
414  boundStates = new Map()
415  monitored.clear()
416  pushes = []
417  $.ui.invalidate('ui.render')
418  showStatus($)
419}
420
421// Looks for the pull request to watch, and asks again a tick later when gh could not answer
422async function discover($, { branchOnly = false, cwd } = {}) {
423  if (watched && !watched.ended) return
424  const gen = generation
425  // Pruning is startup housekeeping, skipped for a lookup after a push; a store that fails it
426  // does not keep the pull request unwatched
427  if (!branchOnly) await prune($).catch(() => {})
428  if (gen !== generation) return
429  const desktop = branchOnly ? null : await readDesktop($)
430  if (gen !== generation) return
431  const found = desktop?.primary?.state === 'OPEN'
432    ? { url: desktop.primary.url, since: 0 }
433    : await findForBranch($, cwd)
434  const at = await $.clock.now()
435  if ((watched && !watched.ended) || gen !== generation) return
436  if (desktop) {
437    trackBound($, desktop)
438  }
439  if (found?.error !== undefined) {
440    // Shown in place of the watch's line, or of the ended pull request's when a push looks again
441    lookupFailure = { at, error: found.error }
442    showStatus($)
443    timers.push($.clock.after(TICK_MS, () => discover($, { branchOnly, cwd })))
444    return
445  }
446  if (lookupFailure) {
447    lookupFailure = null
448    showStatus($)
449  }
450  if (found) watch($, found)
451}
452
453// Starts watching. The first poll runs on the clock, never inside the caller's hook: a prompt it
454// submits starts its turn only once the session is idle, which a tool call still running is not.
455function watch($, { url, since }) {
456  stop()
457  const gen = generation
458  const pr = parse(url)
459  // The note of the poll this stops must not hold back the sessions still watching its pull request
460  // while this watch's first poll starts; watching the same pull request again, its first poll
461  // takes up what the note held
462  if (lastNote) retire($)
463  // A push still waiting for its head to move stays with the pull request it was bound to, even one
464  // that ended; one made while none was watched is the push that led here
465  if (watched?.id !== pr.id) pushes = pushes.filter((push) => !push.pr)
466  // The pull request that takes up a push made while none was watched keeps it
467  for (const push of pushes) push.pr ??= pr.id
468  // Watching the same pull request again keeps the baseline its polls learned
469  if (watched?.id !== pr.id) knownSince = 0
470  watched = { ...pr, since }
471  lookupFailure = null
472  lastHead = null
473  lastHeadAt = 0
474  // Watching a pull request again removes only its own cleanup offer
475  removeCleanup($, pr.id)
476  // Ask at once: a review or a merge may have come while no session watched
477  timers.push($.clock.after(0, () => poll($, gen)))
478  timers.push($.clock.every(TICK_MS, () => poll($, gen)))
479}
480
481function stop({ desktop = false } = {}) {
482  for (const timer of timers) timer?.cancel()
483  timers = []
484  if (desktop) {
485    desktopTimer?.cancel()
486    desktopTimer = null
487  }
488  generation += 1
489}
490
491// Each conversation starts its own desktop timer and asks once whether the tool is available
492function startDesktop($) {
493  desktopAvailable = $.tool.list().then(
494    (tools) => tools.some((tool) => tool.name === DESKTOP_STATUS),
495  ).catch(() => false)
496  desktopTimer = $.clock.every(TICK_MS, () => refreshDesktop($))
497}
498
499// This source reads only the app's cache and leaves gh discovery available after any tool failure
500async function readDesktop($) {
501  try {
502    if (!(await desktopAvailable)) return null
503    const ran = await $.tool.call({ tool: DESKTOP_STATUS })
504    if (ran.deny !== undefined || ran.isError) return null
505    const status = JSON.parse(ran.text)
506    if (!status || typeof status !== 'object' || Array.isArray(status)) return null
507    if (status.bound === false) return { bound: false, primary: null, others: [] }
508    const pull = (url, state) => {
509      if (typeof url !== 'string' || url.match(PR_URL)?.index !== 0) return null
510      const pr = parse(url)
511      if (!Number.isSafeInteger(pr.number) || pr.number <= 0) return null
512      return { url: pr.url, number: pr.number, state: typeof state === 'string' ? state.toUpperCase() : null }
513    }
514    const pr = status.pr
515    const primary = pr?.host == null || pr.host.toLowerCase?.() === 'github.com' ? pull(pr?.url, pr?.state) : null
516    const others = Array.isArray(status.otherBoundPrs) ? status.otherBoundPrs.flatMap((other) => {
517      if (typeof other?.repo !== 'string' || !/^[\w.-]+\/[\w.-]+$/.test(other.repo)) return []
518      if (!Number.isSafeInteger(other.number) || other.number <= 0) return []
519      const parsed = pull(`https://github.com/${other.repo}/pull/${other.number}`, other.state)
520      return parsed ? [parsed] : []
521    }) : null
522    return {
523      bound: status.bound,
524      primary: primary ? { url: primary.url, state: primary.state, autoFix: status.monitor?.auto_fix } : null,
525      others,
526    }
527  } catch {
528    return null
529  }
530}
531
532// A changed open primary takes over the watch, and an ended primary resumes when reopened
533async function refreshDesktop($) {
534  const gen = generation
535  if (desktopPolling === gen) return
536  desktopPolling = gen
537  try {
538    const desktop = await readDesktop($)
539    if (!desktop || gen !== generation) return
540    const primary = desktop.primary
541    const id = primary ? parse(primary.url).id : null
542    const changed = (id !== (lastPrimary ? parse(lastPrimary).id : null) || !lastPrimaryOpen) && id !== watched?.id
543    const reopened = id === watched?.id && watched.ended
544    if (primary?.state === 'OPEN' && (changed || reopened)) {
545      watch($, { url: primary.url, since: 0 })
546    }
547    trackBound($, desktop)
548  } finally {
549    if (desktopPolling === gen) desktopPolling = null
550  }
551}
552
553// Bound states include the watched pull request, whose notifications still come from its poll
554function trackBound($, { bound, primary, others }) {
555  if (bound === false) {
556    lastPrimary = null
557    lastPrimaryOpen = false
558    boundStates.clear()
559    const wasMonitored = monitored.has(watched?.id)
560    monitored.clear()
561    if (wasMonitored) showStatus($)
562    return
563  }
564  if (primary) {
565    const { id } = parse(primary.url)
566    const previous = monitored.has(id)
567    if (primary.autoFix === true) monitored.add(id)
568    else if (primary.autoFix === false) monitored.delete(id)
569    if (id === watched?.id && monitored.has(id) !== previous) showStatus($)
570  }
571  // An incomplete primary must not hide a later open state for the same URL
572  if (primary && ['OPEN', 'MERGED', 'CLOSED'].includes(primary.state)) {
573    lastPrimary = primary.url
574    lastPrimaryOpen = primary.state === 'OPEN'
575  }
576  const entries = [...(others ?? []), ...(primary ? [primary] : [])]
577  // Only a supplied list can unbind other pull requests; an omitted primary remains known
578  if (Array.isArray(others)) {
579    const ids = new Set(entries.map((entry) => parse(entry.url).id))
580    if (!primary && lastPrimary) ids.add(parse(lastPrimary).id)
581    for (const id of boundStates.keys()) if (!ids.has(id)) boundStates.delete(id)
582    const wasMonitored = monitored.has(watched?.id)
583    for (const id of monitored) if (!ids.has(id)) monitored.delete(id)
584    if (wasMonitored !== monitored.has(watched?.id)) showStatus($)
585  }
586  for (const entry of entries) {
587    const pr = parse(entry.url)
588    const { state } = entry
589    if (state !== 'OPEN' && state !== 'MERGED' && state !== 'CLOSED') continue
590    const previous = boundStates.get(pr.id)
591    boundStates.set(pr.id, state)
592    if (state === 'OPEN') removeCleanup($, pr.id)
593    if (pr.id === watched?.id || previous !== 'OPEN' || !ENDED[state]) continue
594    $.ui.toast(`PR #${pr.number} が${ENDED[state]}されました`)
595    if (state === 'MERGED') offerCleanup($, pr)
596  }
597}
598
599// A merged pull request goes at the front without duplicating an existing offer
600function offerCleanup($, { url, number }) {
601  const { id } = parse(url)
602  if (cleanupOffers.some((offer) => parse(offer.url).id === id)) return
603  cleanupOffers.unshift({ url, number })
604  $.ui.invalidate('ui.render')
605}
606
607// Watching or seeing a pull request open removes its own offer, including one awaiting a prompt
608function removeCleanup($, id) {
609  const remaining = cleanupOffers.filter((offer) => parse(offer.url).id !== id)
610  if (remaining.length === cleanupOffers.length) return
611  cleanupOffers = remaining
612  $.ui.invalidate('ui.render')
613}
614
615async function poll($, gen) {
616  if (polling === gen) return
617  polling = gen
618  try {
619    await pollOnce($, gen)
620  } finally {
621    if (polling === gen) polling = null
622  }
623}
624
625async function pollOnce($, gen) {
626  if (gen !== generation || !watched || watched.ended) return
627  await settleRetired($)
628  const pr = watched
629  const key = KEY_PREFIX + pr.id
630  // A watch that began while the retired notes settled owns what the session knows now
631  if (gen !== generation) return
632  // What an earlier poll of this watch paged through is not asked for again
633  const floor = Math.max(pr.since, (pr.pagedAt ?? 0) - PAGE_OVERLAP_MS)
634  // Noted before asking, so a session that starts polling while this one waits on GitHub finds it,
635  // with the pushes known already, so a session that relays before this one finishes counts them
636  knownSince = Math.max(knownSince, pr.since)
637  // A poll the other sessions cannot see would relay beside the one they elect, so it waits a tick
638  const note = await notePoll($, pr, gen).catch(async (error) => {
639    lastCheck = { at: await $.clock.now(), error: `poll note: ${error?.message ?? error}` }
640    showStatus($)
641    return null
642  })
643  if (!note) return
644  const now = note.at
645  try {
646    await pollNoted($, gen, { pr, key, now, floor, note })
647  } finally {
648    await finishNote($, note)
649  }
650}
651
652async function pollNoted($, gen, { pr, key, now, floor, note }) {
653  // Read before GitHub is asked: a push that starts, and even finishes, while the query or the
654  // record is on its way may have replaced the head the query saw
655  const started = pushStarts.get(pr.id) ?? 0
656  const answer = await query($, pr, floor).catch((error) => ({ error }))
657  // When GitHub showed the head, which is what tells a fresher head from a staler one
658  const seenAt = answer.seenAt
659  const answeredAt = await $.clock.now()
660  // A watch that began meanwhile owns the state now
661  if (gen !== generation) return
662  // A query that outlasted the time the others wait on a running note may have seen another
663  // session take the round over, which this one's election cannot tell: it relays nothing
664  if (!answer.error && lapsed(now, answeredAt)) answer.error = new Error(LATE)
665  if (answer.error) {
666    // A poll that learned nothing relays nothing, so it must not hold back the others' this round,
667    // but the push it knows of still counts
668    await retire($)
669    // A watch that began while the note was left idle shows its own state
670    if (gen !== generation) return
671    lastCheck = { at: now, error: String(answer.error?.message ?? answer.error) }
672    showStatus($)
673    return
674  }
675  const { data } = answer
676  // Another session polling this pull request in the same round, ahead of this one, relays what is
677  // new; this one leaves the record to it and passes on what it knows through its note
678  // Notes it could not read may hold an earlier poll, so this one then learned nothing either
679  const notes = await readNotes($, pr, note).catch((error) => ({ error }))
680  // Read before the watch is checked, so nothing waits between the check and what follows
681  const readAt = await $.clock.now()
682  if (gen !== generation) return
683  if (notes.error) {
684    await retire($)
685    if (gen !== generation) return
686    lastCheck = { at: now, error: `poll notes: ${notes.error?.message ?? notes.error}` }
687    showStatus($)
688    return
689  }
690  // So may one whose store answered too late
691  if (lapsed(now, readAt)) return late($, now, pr, note)
692  const { defers, since: othersSince, pending, pushing } = notes
693  // Said in the note, so a later poll of another session does not yield to this one in turn
694  if (defers && lastNote?.serial === note.serial) {
695    lastNote.deferred = true
696    // Written before the record is read, which the store may keep waiting. One the store refused
697    // would leave the others yielding to a poll that relays nothing, so the poll stops as failed
698    const refused = await writeNote($, lastNote, { strict: true }).then(
699      () => null,
700      (error) => error,
701    )
702    // A watch that began while it went out owns the head and the baseline now
703    if (gen !== generation) return
704    if (refused) {
705      await retire($)
706      if (gen !== generation) return
707      lastCheck = { at: now, error: `poll note: ${refused?.message ?? refused}` }
708      showStatus($)
709      return
710    }
711  }
712  if (data.headRefOid) {
713    lastHead = data.headRefOid
714    lastHeadAt = seenAt
715  }
716  lastCheck = { at: now }
717  // One that leaves the waking to another session leaves the end to it too, and sees it next round
718  // from the record, as the session that relays: only then does it stop and offer the cleanup
719  const ended = !defers && (data.state === 'MERGED' || data.state === 'CLOSED')
720  let endedGen = null
721  if (ended) {
722    stop()
723    endedGen = generation
724    watched = { ...watched, ended: data.state }
725    if (data.state === 'MERGED') {
726      offerCleanup($, pr)
727    }
728  }
729
730  // The watch ends only once the end is told: one a push took back, or that never reached the
731  // record, polls on so a later round tells it
732  let told = !ended
733  try {
734    let noted = 0
735    const sends = await exclusive(async () => {
736      const record = normalize(await $.store.get(key))
737      const writeAt = await $.clock.now()
738      // A watch that began while this waited its turn owns the pushes and the marks now
739      if (gen !== generation && !ended) return null
740      // Checked once more just before the record is written, since the store may have kept it waiting
741      if (lapsed(now, writeAt)) return LATE
742      // An ended poll goes on past a new watch, whose baseline is not this pull request's: it goes by
743      // what its note said
744      const owns = watched?.id === pr.id
745      noted = Math.max(othersSince, owns ? knownSince : note.since)
746      const sends = update($, pr, data, record, noted, pending, defers, pushing, now, seenAt)
747      // The session that relays writes the record at about this moment, so a copy read before its
748      // marks must not land over them: one that leaves it the waking writes only its own note
749      if (owns) knownSince = Math.max(knownSince, record.since)
750      if (defers) return sends
751      record.at = now
752      if (data.headRefOid) record.headAt = seenAt
753      await $.store.set(key, record)
754      // A write that landed past the lease may have gone over a session that took the round over and
755      // relayed the same, so this one sends nothing; $.store has no conditional write to stop it.
756      // Its marks are taken back, since a session that has not taken the round over yet would read
757      // them as sent, and nothing would send them
758      if (lapsed(now, await $.clock.now())) return { late: sends }
759      // Pages are skipped next time only once what they held is in the record: a session that leaves
760      // the waking to another goes through them again in case that one never writes it
761      if (gen === generation) watched = { ...watched, pagedAt: now }
762      return sends
763    })
764    if (sends === null) return
765    if (sends === LATE) return late($, now, pr, note)
766    if (sends.late) {
767      takeBackAll($, key, sends.late, pr)
768      return late($, now, pr, note)
769    }
770    // Only once the record says they were relayed, so a send that fails can take its mark back. A
771    // watch that began during the write (an ended pull request stopped the timers itself) takes
772    // the marks back instead, and a later watch of this pull request sends them.
773    // A push this session started meanwhile, running or already done, may have replaced the head
774    // they were read from
775    let pushedSince = (pushStarts.get(pr.id) ?? 0) !== started
776    // So may one another session started after its notes were read, which only they say
777    if (sends.length && !pushedSince) {
778      // A push known already that has finished since, even one that had run past the time it holds
779      // the relays back, counts the same as a new one
780      const state = (push) => `${push.running ? 'running' : 'done'}:${push.doneAt ?? ''}`
781      const known = new Map(pending.map((push) => [pushKey(push), state(push)]))
782      const moved = (again) =>
783        !again ||
784        again.pushing ||
785        again.since > noted ||
786        again.pending.some((push) => known.get(pushKey(push)) !== state(push))
787      pushedSince = moved(await readNotes($, pr, note).catch(() => null))
788      // A read the store kept waiting past the lease may have let another session take the round
789      // over; it read the marks, which this one wrote in time, so it sent nothing: they are taken back
790      // for the next round to send
791      if (lapsed(now, await $.clock.now())) {
792        takeBackAll($, key, sends, pr)
793        return late($, now, pr, note)
794      }
795      // A push this session started while the clock was read counts too, and so does one another
796      // session started meanwhile, which a last read of the notes shows; the lease keeps ROUND_MS
797      // for it, and nothing waits between it and the sends
798      pushedSince ||= (pushStarts.get(pr.id) ?? 0) !== started
799      if (!pushedSince) pushedSince = moved(await readNotes($, pr, note).catch(() => null))
800      pushedSince ||= (pushStarts.get(pr.id) ?? 0) !== started
801    }
802    const current = (gen === generation || ended) && !pushedSince && !(watched?.id === pr.id && pushes.some((push) => holds(push, now)))
803    if (current) {
804      told = true
805      for (const send of sends) deliver($, key, send)
806    } else takeBackAll($, key, sends, pr)
807    showStatus($)
808  } finally {
809    if (!told) reopen($, pr, endedGen)
810  }
811}
812
813// Watches a pull request again whose end a poll could not tell, unless a new watch began since
814function reopen($, pr, gen) {
815  if (gen !== generation || watched?.id !== pr.id || !watched.ended) return
816  watched = { ...watched, ended: null }
817  removeCleanup($, pr.id)
818  timers.push($.clock.every(TICK_MS, () => poll($, gen)))
819  showStatus($)
820}
821
822// Whether a poll started at now has run so long that another session may have taken its round over
823function lapsed(now, at) {
824  return at >= now + RUNNING_MS - ROUND_MS
825}
826
827// A poll that lapsed relays nothing, and says so. An ended one that a new watch went past leaves
828// that watch's note and status alone.
829async function late($, now, pr, note) {
830  if (lastNote?.serial === note.serial) await retire($)
831  if (watched?.id !== pr.id) return
832  lastCheck = { at: now, error: LATE }
833  showStatus($)
834}
835
836// Brings the record up to the pull request's state, and returns the prompts to send for what is new
837function update($, pr, data, record, notedPush, pending, defers, pushing, now, seenAt) {
838  // Codex reviews pushes, so only its activity after the latest push counts. The thumbs-up in
839  // particular is one reaction per pull request whose time can stay at an earlier push: its mere
840  // presence would read as an approval of every later push.
841  const committedAt = Date.parse(data.commits?.nodes?.[0]?.commit?.committedDate ?? '') || 0
842  record.since = Math.max(record.since, pr.since, committedAt, notedPush)
843  // An ended poll that finishes after the watch turned leaves the next pull request's pushes alone
844  if (watched?.id === pr.id) {
845    pushes = pushes.filter((push) => {
846      // The record's head is the head before the push only if GitHub showed it before the push
847      // started; one seen later may already be what the push put there
848      const recordHead = (record.headAt ?? 0) < push.at ? record.head : null
849      if (!pushCounts(push, data, now, { recordHead })) return true
850      record.since = Math.max(record.since, push.at)
851      return false
852    })
853  }
854  // Another session's push counts by the same rule; one that knew no head before it cannot tell a
855  // push that moved nothing from one that did, so it waits for that session's own poll
856  for (const push of pending) {
857    if (pushCounts(push, data, now)) record.since = Math.max(record.since, push.at)
858  }
859  record.head = data.headRefOid ?? record.head
860  if (data.state === 'MERGED' || data.state === 'CLOSED') {
861    if (!record.ended && !defers) {
862      const state = data.state
863      record.ended = state
864      // Raised once the record says so in time, like a prompt
865      return [
866        {
867          toast: `PR #${pr.number} が${ENDED[state]}されました`,
868          // Only a merge moves the base branch under the other sessions' work
869          notice: state === 'MERGED' ? `${baseName(data)} advanced (#${pr.number}). Rebase before the next push.` : null,
870          pr,
871          undo: (r) => {
872            if (r.ended === state) r.ended = null
873          },
874        },
875      ]
876    }
877    return []
878  }
879  // A reopened pull request ends again, and that end is news again
880  record.ended = null
881  // A push running in any session may be replacing the head GitHub still shows; this session's
882  // own are those it bound to this pull request
883  const running = pushes.some((push) => holds(push, now))
884  // So may one that finished after GitHub answered, which the head GitHub showed cannot tell from a
885  // push that moved nothing; the next poll sees what it left. One that finished in the same
886  // millisecond may have too, and one handed on with no end time counts from its start
887  const unseen = (push) => !push.running && (typeof push.doneAt === 'number' ? push.doneAt >= seenAt : push.at >= seenAt)
888  const replaced =
889    (watched?.id === pr.id && pushes.some(unseen)) || pending.some((push) => unseen(push) && !pushCounts(push, data, now))
890  return running || pushing || defers || replaced ? [] : relay($, pr, read(data, record.since), record)
891}
892
893// The cache takes only the latest answer, so one asked before a /resume cannot land over it
894async function sessionIdOf($) {
895  const ask = ++idAsks
896  const id = await $.session.id()
897  if (ask === idAsks) sessionId = id
898  return id
899}
900
901// Notes that this session starts a poll of the pull request now, and returns the note
902async function notePoll($, pr, gen) {
903  // One note per pull request, so a session that turns to another leaves this one's push behind
904  const key = `${POLL_PREFIX}${await sessionIdOf($)}:${pr.id}`
905  // A worker respawn starts this module afresh while the session's note from before stays in the
906  // store, still holding what the record may not have counted; a read that fails is retried
907  const stored = lastNote?.key === key || retired.has(key) ? null : await $.store.get(key)
908  // Read just before the note goes out, since the time is this poll's place in the election
909  const at = await $.clock.now()
910  if (gen !== generation) return null
911  // The note under the id before /clear or /resume would read as another session's poll
912  if (lastNote && lastNote.key !== key) await retire($)
913  // Watching the same pull request again starts from what its note last said
914  if (lastNote?.key === key) knownSince = Math.max(knownSince, lastNote.since)
915  // Coming back to a pull request this session left, its note still holds pushes the record may
916  // not have counted yet
917  const left = retired.get(key)
918  if (left) {
919    knownSince = Math.max(knownSince, left.since)
920    for (const push of left.pending) if (!push.dropped && !pushes.includes(push)) pushes.push(push)
921    retired.delete(key)
922  } else if (stored?.pr === pr.id) {
923    if (typeof stored.since === 'number') knownSince = Math.max(knownSince, stored.since)
924    for (const push of [].concat(stored.pending ?? [])) {
925      if (typeof push?.at !== 'number' || pushes.some((p) => pushKey(p) === pushKey(push))) continue
926      // Whether a push the last module saw running pushed anything is unknown, so it counts once
927      // the head moves; one that may still run (the worker went, not the Bash call) holds the
928      // relays back as long as another session's would
929      const finished = !push.running
930      const live = !finished && push.at >= at - RUNNING_MS
931      pushes.push({
932        id: push.id ?? null,
933        pr: pr.id,
934        at: push.at,
935        head: push.head ?? null,
936        shas: finished ? (push.shas ?? null) : null,
937        refs: finished ? (push.refs ?? null) : null,
938        ...(finished && typeof push.doneAt === 'number' ? { doneAt: push.doneAt } : {}),
939        running: live,
940      })
941    }
942  }
943  lastNote = { key, pr: pr.id, at, since: knownSince, pending: [...pushes], running: true, serial: ++noteSerial }
944  await writeNote($, lastNote, { strict: true })
945  // A note other sessions wrote while this one's was on its way may have been elected without
946  // seeing it, so the poll yields to those too
947  return { ...lastNote, landedAt: await $.clock.now() }
948}
949
950// Marks the note of a poll that has written what it relayed as finished, with what it now knows
951async function finishNote($, note) {
952  if (lastNote?.serial !== note.serial) return
953  catchUp(lastNote)
954  lastNote.running = false
955  await writeNote($, lastNote)
956}
957
958// Puts a push this session just started into its running or finished note, so a session that
959// relays before this one polls again counts it
960async function refreshNote($, { strict = false } = {}) {
961  const writes = []
962  for (const note of [lastNote, ...retired.values()]) {
963    if (!note || (note.pr !== watched?.id && !note.dirty)) continue
964    catchUp(note)
965    writes.push(writeNote($, note, { strict }))
966  }
967  await Promise.all(writes)
968}
969
970// Rewrites the notes this session left until the store has taken each as idle and with its pushes
971// as they stand; a write the store refused is tried again on the next poll. Each is kept for as
972// long as the session runs, since coming back to its pull request takes up what it held.
973async function settleRetired($) {
974  await Promise.all(
975    [...retired.values()].map(async (note) => {
976      if (note.dirty || !note.writtenIdle) {
977        catchUp(note)
978        await writeNote($, note, { strict: true }).catch(() => {})
979      }
980    }),
981  )
982}
983
984// The notes this session holds for a pull request
985function notesOf(prId) {
986  return prId ? [lastNote, ...retired.values()].filter((note) => note?.pr === prId) : []
987}
988
989// Leaves this session's note idle: it holds back no other session, and still hands on its push
990async function retire($) {
991  if (!lastNote) return
992  const note = lastNote
993  lastNote = null
994  // What the session knows belongs to the watch, which may have moved on to another pull request;
995  // then the note keeps what it last said
996  catchUp(note)
997  const idle = { ...note, pending: [...note.pending], running: false, idle: true, dirty: true }
998  retired.set(note.key, idle)
999  await writeNote($, idle)
1000}
1001
1002// Brings a note of the watched pull request up to what this session knows of its pushes
1003function catchUp(note) {
1004  if (note.pr !== watched?.id) return
1005  note.since = Math.max(note.since, knownSince)
1006  note.pending = [...pushes]
1007}
1008
1009// Writes a note as it stands, its pushes included. dirty says the store has not taken what the note
1010// holds now, and writtenIdle whether it last took the note as idle.
1011// Writes to one key go out one after another, each with the note as it stands when it goes out, so
1012// an earlier write that the store answers late never lands over a later one.
1013function writeNote($, note, { strict = false } = {}) {
1014  note.dirty = false
1015  const { key } = note
1016  let idle = false
1017  const write = (noteWrites.get(key) ?? Promise.resolve())
1018    .then(() => {
1019      idle = Boolean(note.idle)
1020      return $.store.set(key, noteValue(note))
1021    })
1022    .then(
1023      () => {
1024        note.writtenIdle = idle
1025      },
1026      (error) => {
1027        note.dirty = true
1028        throw error
1029      },
1030    )
1031  const tail = write.catch(() => {})
1032  noteWrites.set(key, tail)
1033  tail.then(() => {
1034    if (noteWrites.get(key) === tail) noteWrites.delete(key)
1035  })
1036  return strict ? write : tail
1037}
1038
1039function noteValue({ pr, at, since, pending = [], running, idle, deferred }) {
1040  const pushes = pending.filter((push) => !push.dropped).map(pushNote)
1041  return {
1042    pr,
1043    at,
1044    since,
1045    ...(pushes.length ? { pending: pushes } : {}),
1046    ...(running ? { running } : {}),
1047    ...(idle ? { idle } : {}),
1048    ...(deferred ? { deferred } : {}),
1049  }
1050}
1051
1052// A push as a note hands it on, for the session that relays to apply
1053function pushNote({ id, at, head, shas, refs, running, doneAt }) {
1054  return {
1055    ...(id ? { id } : {}),
1056    at,
1057    head,
1058    ...(shas ? { shas } : {}),
1059    ...(refs ? { refs } : {}),
1060    ...(running ? { running } : {}),
1061    ...(typeof doneAt === 'number' ? { doneAt } : {}),
1062  }
1063}
1064
1065// Whether a push of this session still holds back a poll started at now: one whose Bash call hung
1066// holds nothing back for long, the same as another session's in readNotes
1067function holds(push, now) {
1068  return push.running && (push.at === null || push.at >= now - RUNNING_MS)
1069}
1070
1071function pushId(at) {
1072  return `${at.toString(36)}-${Math.random().toString(36).slice(2, 10)}`
1073}
1074
1075// What tells one push from another: its id, or for a note written without one, its start
1076function pushKey(push) {
1077  return push.id ?? `at:${push.at}`
1078}
1079
1080// Whether a push moved the pull request to the head GitHub shows now: once it has finished, by the
1081// commits it pushed, or, when its output named none, by the head having changed since it started.
1082// A pushed commit the head already had before is some other ref moved to it. The session that
1083// pushed falls back on the record's head as GitHub showed it before the push; with no head known at all, the push stays pending, and
1084// the head commit's date is the baseline.
1085function pushCounts(push, data, now, { recordHead = null } = {}) {
1086  const head = data.headRefOid
1087  // A push whose Bash call hung past the time it holds the relays back is taken as finished with
1088  // nothing known of what it pushed: it counts once the head moves
1089  if (holds(push, now) || !head) return false
1090  const before = push.head ?? recordHead
1091  if (Array.isArray(push.shas)) {
1092    // A pushed commit the head has may be another ref moved to it, where the pull request's branch
1093    // got by itself: when the output says which branch moved where, only its own branch counts
1094    const own = data.headRefName ? push.refs?.[data.headRefName] : null
1095    const named = push.refs && Object.keys(push.refs).length > 0
1096    const moved = named ? typeof own === 'string' && head.startsWith(own) : push.shas.some((sha) => head.startsWith(sha))
1097    if (before != null) return before !== head && moved
1098    // Without the head before it, only the pull request's own branch moving to it says the push
1099    // moved the head
1100    return typeof own === 'string' && head.startsWith(own)
1101  }
1102  return before != null && head !== before
1103}
1104
1105// The commits a finished git push moved refs to, and the commit each branch moved to: none when it
1106// moved nothing, or null when its output does not say (a new branch, a quiet push)
1107function pushedCommits(ran) {
1108  const text = [ran.text, ran.result?.stdout, ran.result?.stderr].filter((t) => typeof t === 'string').join('\n')
1109  // The usual form (old..new  src -> dst) and --porcelain's (flag TAB src:dst TAB old..new)
1110  const moves = [
1111    ...[...text.matchAll(/\b[0-9a-f]{7,40}\.{2,3}([0-9a-f]{7,40})\s+\S+\s+->\s+(\S+)/g)].map((m) => [m[1], m[2]]),
1112    ...[...text.matchAll(/^[ +\-*!=]\t[^\t]*:(\S+)\t[0-9a-f]{7,40}\.{2,3}([0-9a-f]{7,40})\b/gm)].map((m) => [m[2], m[1]]),
1113  ]
1114  // Moved nothing only when no update was printed: one Bash call may run several pushes, of which
1115  // only the last was up to date. --porcelain says a ref already up to date with =
1116  if (!moves.length) return /Everything up-to-date|^=\t/m.test(text) ? { shas: [], refs: {} } : null
1117  // The branch each ref moved to its commit, so a push can be told to have moved the pull request's
1118  // own branch even with no head known before it
1119  const refs = Object.fromEntries(moves.map(([sha, ref]) => [ref.replace(/^refs\/heads\//, ''), sha]))
1120  return { shas: [...new Set(moves.map(([sha]) => sha))], refs }
1121}
1122
1123// The head the watched pull request had as lately as this session knows: its own last poll or the
1124// record another session wrote since
1125async function headBefore($, prId) {
1126  if (!prId) return null
1127  const own = watched?.id === prId ? lastHead : null
1128  // A record it cannot read may hold a fresher head than this session saw, so the head is unknown
1129  const record = await $.store.get(KEY_PREFIX + prId).catch(() => null)
1130  if (record === null) return null
1131  if (!record?.head || !own) return record?.head ?? own
1132  const recordAt = record.headAt ?? record.at ?? 0
1133  // Two heads seen in the same millisecond cannot be told apart, so neither is the head before
1134  if (recordAt === lastHeadAt && record.head !== own) return null
1135  return recordAt > lastHeadAt ? record.head : own
1136}
1137
1138// What the other sessions' notes on the same pull request say: defers, whether one of them started
1139// its poll before this one's (or at the same moment, under a smaller key) in the same round, or is
1140// still running it, so that every session agrees on the one that relays; since and pending, the
1141// pushes they know; and pushing, whether one of them is running a push. One that stopped polling or
1142// failed drops out of the next round by itself, or at once when it left its note idle. A store that
1143// cannot be read throws, since a note it hides may be the one this poll should yield to.
1144
1145async function readNotes($, pr, note) {
1146  const keys = (await $.store.keys()).filter((key) => key.startsWith(POLL_PREFIX) && key !== note.key)
1147  let defers = false
1148  let pushing = false
1149  let since = 0
1150  const pending = []
1151  for (const key of keys) {
1152    const other = await $.store.get(key)
1153    if (other?.pr !== pr.id || typeof other.at !== 'number') continue
1154    if (typeof other.since === 'number') since = Math.max(since, other.since)
1155    for (const push of [].concat(other.pending ?? [])) {
1156      if (typeof push?.at !== 'number') continue
1157      pending.push(push)
1158      // One left running by a session that died mid-push holds nothing back for long
1159      if (push.running && push.at >= note.at - RUNNING_MS) pushing = true
1160    }
1161    // A poll that left the round to another holds nothing back either: polls a few seconds apart
1162    // would otherwise each yield to the one before, round after round, and none would relay
1163    if (other.idle || other.deferred) continue
1164    // A note written while this one's was on its way, even in the same millisecond it was timed,
1165    // may have been elected without seeing it
1166    const landedAt = note.landedAt ?? note.at
1167    if (landedAt > note.at && other.at >= note.at && other.at <= landedAt) {
1168      defers = true
1169      continue
1170    }
1171    if (other.at > note.at) continue
1172    if (other.at < note.at - (other.running ? RUNNING_MS : ROUND_MS)) continue
1173    if (other.at < note.at || key < note.key) defers = true
1174  }
1175  return { defers, since, pending, pushing }
1176}
1177
1178// Marks what is new since the last push as relayed: reviews before an approval, then the usage
1179// limit. A newer approval is marked with the reviews, and mentioned only if it came after them.
1180// Review details are fetched at delivery, once the record is written, outside the write queue
1181function relay($, pr, signals, record) {
1182  const fresh = signals.reviews.filter((r) => !record.reviews.some((id) => String(id) === String(r.id))).sort((a, b) => a.at - b.at)
1183  const usesMonitor = monitored.has(pr.id)
1184  const approvedAt = usesMonitor ? signals.reactedAt : signals.approvedAt
1185  const previous = record.approvedAt
1186  if (usesMonitor) {
1187    // The monitor owns these comments, so their silent marks survive a failed approval prompt
1188    record.reviews.push(...fresh.map((r) => r.id))
1189    record.usageLimitAt = Math.max(record.usageLimitAt, signals.usageLimitAt)
1190    record.approvedAt = Math.max(record.approvedAt, signals.approvedAt)
1191    if (fresh.length && approvedAt <= fresh[fresh.length - 1].at) return []
1192  }
1193  if (fresh.length > 0 && !usesMonitor) {
1194    const previous = record.approvedAt
1195    const approvedAt = signals.approvedAt > previous ? signals.approvedAt : 0
1196    record.reviews.push(...fresh.map((r) => r.id))
1197    if (approvedAt) record.approvedAt = approvedAt
1198    return [
1199      {
1200        pr,