Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(github): fetch PR snapshots without Contents permission (#9332)
LinYushen8d95e805596d
diff --git a/apps/docs/content/docs/github-integration.fr.mdx b/apps/docs/content/docs/github-integration.fr.mdxindex bf3914802f..094cbd2422 100644--- a/apps/docs/content/docs/github-integration.fr.mdx+++ b/apps/docs/content/docs/github-integration.fr.mdx@@ -122,7 +122,6 @@ Permissions de dépôt (Repository permissions) :| Permission | Niveau ||---|---|| Metadata | Read-only |-| Contents | Read-only ; requise par la requête d'instantané de PR, qui lit le commit de tête ainsi que la possibilité de fusion et le récapitulatif CI || Pull requests | Read-only || Checks | Read-only ; sert à afficher le statut CI || Commit statuses | Read-only ; sert à agréger la CI basée sur les statuts hérités (legacy statuses) |@@ -132,7 +131,7 @@ Abonnez-vous à ces événements :- **Pull request** ;- **Check suite**, **Check run** et **Status**, qui déclenchent l'actualisation de la CI et de la possibilité de fusion.-Si vous n'avez pas besoin d'afficher la CI dans Multica, vous pouvez vous passer des permissions Checks et Commit statuses ainsi que de leurs événements. Contents reste obligatoire : sans elle, la requête d'instantané échoue complètement et la carte de PR perd aussi l'état de fusion.+Les instantanés de PR utilisent les API REST Pull requests, Checks et Commit statuses. La permission Contents n'est pas nécessaire.<Callout type="warning">Il s'agit du **Webhook secret**, et non du Client secret OAuth. Si les deux côtés n'ont pas le même secret de webhook, les livraisons GitHub renvoient `401 invalid signature`.@@ -175,7 +174,7 @@ Redémarrez le serveur API, puis effectuez la connexion dans **Paramètres → C- **Le webhook renvoie 401** : vérifiez que la GitHub App et l'API utilisent le même secret de webhook, puis relancez la livraison depuis **Recent Deliveries** sur GitHub.- **PR non associée** : vérifiez que le dépôt fait partie du périmètre autorisé de l'App, que l'association automatique est activée et que l'identifiant appartient à l'espace de travail courant.- **Identifiant dans la description, mais PR non associée** : utilisez plutôt `Closes MUL-123`, ou placez l'identifiant dans le nom de branche ou le titre de la PR.-- **Aucun statut CI** : vérifiez que `GITHUB_APP_ID` et `GITHUB_APP_PRIVATE_KEY` sont configurées, et que l'App dispose des permissions Contents, Checks et Commit statuses en lecture seule, avec les événements correspondants souscrits. Sans Contents, tout l'instantané échoue : la carte de PR n'affiche alors ni CI ni état de fusion. Après l'ajout de permissions à une App déjà installée, le propriétaire de chaque installation doit aussi les approuver sur GitHub pour qu'elles prennent effet.+- **Aucun statut CI** : vérifiez que `GITHUB_APP_ID` et `GITHUB_APP_PRIVATE_KEY` sont configurées, et que l'App dispose des permissions Pull requests, Checks et Commit statuses en lecture seule, avec les événements correspondants souscrits. La permission Contents n'est pas nécessaire. Après l'ajout de permissions à une App déjà installée, le propriétaire de chaque installation doit les approuver sur GitHub pour qu'elles prennent effet.- **Tâche non terminée après la fusion de la PR** : vérifiez que la PR a utilisé un mot-clé de clôture, et si d'autres PR associées sont encore Ouvertes ou en Brouillon.## Étapes suivantesdiff --git a/apps/docs/content/docs/github-integration.ja.mdx b/apps/docs/content/docs/github-integration.ja.mdxindex 550ee67b50..015515f02d 100644--- a/apps/docs/content/docs/github-integration.ja.mdx+++ b/apps/docs/content/docs/github-integration.ja.mdx@@ -131,7 +131,6 @@ Repository permissions:| 権限 | レベル ||---|---|| Metadata | Read-only |-| Contents | Read-only。PR スナップショットのクエリが head commit・マージ可否・CI ロールアップをまとめて読み取るために必要 || Pull requests | Read-only || Checks | Read-only。CI の状態表示に使用 || Commit statuses | Read-only。legacy status 形式の CI 集計に使用 |@@ -141,7 +140,7 @@ Repository permissions:- **Pull request**- **Check suite**、**Check run**、**Status**。CI とマージ可能性を更新するために使用します。-Multica で CI を表示しない場合は、Checks と Commit statuses の権限、および関連イベントの購読を省略できます。ただし Contents は必須です。付与しないとスナップショットのクエリ自体が失敗し、PR カードからマージ状態も消えます。+PR スナップショットは Pull requests、Checks、Commit statuses の REST API から取得します。Contents 権限は不要です。<Callout type="warning">必要なのは **Webhook secret** であり、OAuth Client secret ではありません。GitHub と Multica に入力した Webhook secret が異なる場合、GitHub delivery は `401 invalid signature` を返します。@@ -184,7 +183,7 @@ API サービスを再起動し、**設定 → コード** から接続します- **Webhook が 401 を返す**: GitHub App と API が同じ Webhook secret を使っていることを確認し、GitHub の **Recent Deliveries** から再配信します。- **PR が紐づかない**: リポジトリが App の許可範囲にあること、PR の自動紐づけが有効であること、番号が現在のワークスペースのものであること、誰かがタスクから外していないかを確認します。- **本文に番号を書いても紐づかない**: `Closes MUL-123` を使うか、番号をブランチ名または PR タイトルに入れるか、手動で紐づけます。-- **CI の状態がない**: `GITHUB_APP_ID` と `GITHUB_APP_PRIVATE_KEY` が設定済みで、App に Contents、Checks、Commit statuses の read-only 権限があり、関連イベントを購読していることを確認します。Contents が欠けるとスナップショット全体が失敗し、PR カードには CI もマージ状態も表示されません。インストール済み App に権限を追加した場合は、各 installation の所有者が GitHub 上で承認するまで有効になりません。+- **CI の状態がない**: `GITHUB_APP_ID` と `GITHUB_APP_PRIVATE_KEY` が設定済みで、App に Pull requests、Checks、Commit statuses の read-only 権限があり、関連イベントを購読していることを確認します。Contents 権限は不要です。インストール済み App に権限を追加した場合は、各 installation の所有者が GitHub 上で承認するまで有効になりません。- **PR のマージ後もタスクのステータスが変わらない**: タスクの **Pull requests** リストの下にある説明を確認します。まだマージされていない PR やマージされずにクローズされた PR、またはこのタスクが PR マージでステータスを変えない設定であることが表示されます。説明がない場合は、ワークスペースが **変更しない** に設定されているか、タスクがすでに変更先のステータスです。## 次のステップdiff --git a/apps/docs/content/docs/github-integration.ko.mdx b/apps/docs/content/docs/github-integration.ko.mdxindex b167a479d4..ab5702d48f 100644--- a/apps/docs/content/docs/github-integration.ko.mdx+++ b/apps/docs/content/docs/github-integration.ko.mdx@@ -131,7 +131,6 @@ Repository permissions:| 권한 | 수준 ||---|---|| Metadata | Read-only |-| Contents | Read-only. PR snapshot 쿼리가 head commit과 머지 가능 여부, CI rollup을 함께 읽는 데 필요 || Pull requests | Read-only || Checks | Read-only. CI 상태 표시에 사용 || Commit statuses | Read-only. legacy status 형식의 CI 집계에 사용 |@@ -141,7 +140,7 @@ Repository permissions:- **Pull request**- CI와 merge 가능 여부 새로 고침을 트리거할 **Check suite**, **Check run**, **Status**-Multica에서 CI를 표시할 필요가 없다면 Checks 및 Commit statuses 권한을 부여하거나 관련 이벤트를 구독하지 않아도 됩니다. 단, Contents는 반드시 필요합니다. 없으면 snapshot 쿼리 자체가 실패해 PR 카드에서 머지 상태도 사라집니다.+PR snapshot은 Pull requests, Checks 및 Commit statuses REST API로 가져옵니다. Contents 권한은 필요하지 않습니다.<Callout type="warning">여기에는 OAuth Client secret이 아니라 **Webhook secret**이 필요합니다. 양쪽에 입력한 Webhook secret이 다르면 GitHub delivery가 `401 invalid signature`를 반환합니다.@@ -184,7 +183,7 @@ API 서비스를 다시 시작한 뒤 **설정 → 코드**에서 연결을 완- **Webhook이 401을 반환함**: GitHub App과 API가 같은 Webhook secret을 사용하는지 확인하고 GitHub의 **Recent Deliveries**에서 다시 전달합니다.- **PR이 연결되지 않음**: 저장소가 App 승인 범위에 있는지, 자동 연결이 켜져 있는지, 번호가 현재 워크스페이스에 속하는지, 누군가 태스크에서 PR을 제거하지 않았는지 확인합니다.- **본문에 번호를 썼는데 연결되지 않음**: `Closes MUL-123`을 사용하거나, 번호를 브랜치 이름이나 PR 제목에 넣거나, 직접 연결합니다.-- **CI 상태가 없음**: `GITHUB_APP_ID`와 `GITHUB_APP_PRIVATE_KEY`가 설정되었는지, App에 Contents, Checks 및 Commit statuses 읽기 권한이 있고 관련 이벤트를 구독했는지 확인합니다. Contents가 없으면 snapshot 전체가 실패해 PR 카드에 CI도 머지 상태도 표시되지 않습니다. 설치된 App에 권한을 추가한 뒤에는 각 installation owner가 GitHub에서 승인해야 적용됩니다.+- **CI 상태가 없음**: `GITHUB_APP_ID`와 `GITHUB_APP_PRIVATE_KEY`가 설정되었는지, App에 Pull requests, Checks 및 Commit statuses 읽기 권한이 있고 관련 이벤트를 구독했는지 확인합니다. Contents 권한은 필요하지 않습니다. 설치된 App에 권한을 추가한 뒤에는 각 installation owner가 GitHub에서 승인해야 적용됩니다.- **PR merge 후 태스크 상태가 바뀌지 않음**: 태스크의 **Pull requests** 목록 아래 설명을 확인합니다. 아직 merge되지 않았거나 merge 없이 닫힌 PR이 있는지, 또는 이 태스크가 PR 병합 후에도 상태를 유지하도록 설정되어 있는지 알려 줍니다. 설명이 없으면 워크스페이스가 **변경하지 않음**으로 설정되어 있거나 태스크가 이미 대상 상태입니다.## 다음 단계diff --git a/apps/docs/content/docs/github-integration.mdx b/apps/docs/content/docs/github-integration.mdxindex a371bc9cd7..af4958d7c5 100644--- a/apps/docs/content/docs/github-integration.mdx+++ b/apps/docs/content/docs/github-integration.mdx@@ -134,7 +134,6 @@ Repository permissions:| Permission | Level ||---|---|| Metadata | Read-only |-| Contents | Read-only; required by the PR snapshot query, which reads the head commit together with mergeability and the CI rollup || Pull requests | Read-only || Checks | Read-only; used to show CI status || Commit statuses | Read-only; used to aggregate legacy-status CI |@@ -144,7 +143,7 @@ Subscribe to these events:- **Pull request**;- **Check suite**, **Check run**, and **Status**, which trigger CI and mergeability refreshes.-If you don't need CI shown in Multica, you can skip the Checks and Commit statuses permissions and their events. Contents is still required — without it the snapshot query fails outright and the PR card also loses merge state.+PR snapshots use the Pull requests, Checks, and Commit statuses REST APIs. Contents access is not required.<Callout type="warning">This is the **Webhook secret**, not the OAuth Client secret. If the two sides have different webhook secrets, GitHub deliveries return `401 invalid signature`.@@ -187,7 +186,7 @@ Restart the API server, then complete the connection in **Settings → Code**.- **Webhook returns 401**: confirm the GitHub App and the API use the same webhook secret, then redeliver from GitHub's **Recent Deliveries**.- **PR not linked**: check that the repository is in the App's authorized scope, auto-linking is on, the identifier belongs to the current workspace, and nobody removed the PR from the issue.- **Identifier in the body but not linked**: put it right after a closing keyword (`Closes MUL-123`), or in the branch name or PR title, or link the PR by hand.-- **No CI status**: confirm `GITHUB_APP_ID` and `GITHUB_APP_PRIVATE_KEY` are configured, and that the App has read-only Contents, Checks, and Commit statuses permissions with the matching events subscribed. Without Contents the whole snapshot fails, so the PR card shows neither CI nor merge state. After adding permissions to an installed App, each installation's owner must also approve them on GitHub before they take effect.+- **No CI status**: confirm `GITHUB_APP_ID` and `GITHUB_APP_PRIVATE_KEY` are configured, and that the App has read-only Pull requests, Checks, and Commit statuses permissions with the matching events subscribed. Contents access is not required. If permissions were added to an installed App, each installation owner must approve them on GitHub before they take effect.- **Issue didn't move after the PR merged**: read the line under the issue's **Pull requests** list. It names any PR still open or closed without merging, or says the issue keeps its status when PRs merge. No line means the workspace setting is **Don't change**, or the issue already has the target status.## Next stepsdiff --git a/apps/docs/content/docs/github-integration.zh.mdx b/apps/docs/content/docs/github-integration.zh.mdxindex eaac179b57..6fc4a8cd67 100644--- a/apps/docs/content/docs/github-integration.zh.mdx+++ b/apps/docs/content/docs/github-integration.zh.mdx@@ -134,7 +134,6 @@ Repository permissions:| 权限 | 级别 ||---|---|| Metadata | Read-only |-| Contents | Read-only;PR 快照查询需要它,一次读取 head commit、可合并状态与 CI 汇总 || Pull requests | Read-only || Checks | Read-only;用于显示 CI 状态 || Commit statuses | Read-only;用于汇总 legacy status 形式的 CI |@@ -144,7 +143,7 @@ Repository permissions:- **Pull request**;- **Check suite**、**Check run** 和 **Status**,用于触发 CI 与可合并性刷新。-如果不需要在 Multica 中显示 CI,可以不授予 Checks 和 Commit statuses 权限,也不订阅对应事件。但 Contents 仍然必须授予——缺少它时整个快照查询会直接失败,PR 卡片连合并状态也会一起消失。+PR 快照通过 Pull requests、Checks 和 Commit statuses 的 REST API 获取,不需要 Contents 权限。<Callout type="warning">这里需要的是 **Webhook secret**,不是 OAuth Client secret。两边填写的 Webhook secret 不一致时,GitHub delivery 会返回 `401 invalid signature`。@@ -187,7 +186,7 @@ make migrate-up- **Webhook 返回 401**:确认 GitHub App 与 API 使用同一个 Webhook secret,然后在 GitHub 的 **Recent Deliveries** 中重新投递。- **PR 没有关联**:检查仓库是否在 App 授权范围内、自动关联是否开启、编号是否属于当前工作区,以及是否有人把它从任务上移除过。- **正文写了编号但没关联**:改用 `Closes MUL-123`,或把编号放到分支名、PR 标题中,或者手动关联。-- **没有 CI 状态**:确认 `GITHUB_APP_ID` 和 `GITHUB_APP_PRIVATE_KEY` 已配置,App 具有 Contents、Checks 与 Commit statuses 的只读权限并订阅了对应事件。缺少 Contents 会让整个快照失败,PR 卡片既没有 CI 也没有合并状态。给已安装的 App 补加权限后,还需要各 installation 的所有者在 GitHub 上批准才会生效。+- **没有 CI 状态**:确认 `GITHUB_APP_ID` 和 `GITHUB_APP_PRIVATE_KEY` 已配置,App 具有 Pull requests、Checks 与 Commit statuses 的只读权限并订阅了对应事件。不需要 Contents 权限。给已安装的 App 补加权限后,需要各 installation 的所有者在 GitHub 上批准才会生效。- **PR 合并后任务状态没变**:看任务 **Pull requests** 列表下方的说明,它会指出仍未合并或已关闭未合并的 PR,或者说明此任务合并后不改状态。没有这行说明,表示工作区设置为**不改变**,或者任务已经是目标状态。## 接下来diff --git a/server/internal/integrations/ghsnapshot/client.go b/server/internal/integrations/ghsnapshot/client.goindex 1b3168119f..b3e65d5ecc 100644--- a/server/internal/integrations/ghsnapshot/client.go+++ b/server/internal/integrations/ghsnapshot/client.go@@ -5,8 +5,8 @@//// The package has three layers:// - Client (this file): GitHub App auth — App JWT → installation access-// token (cached per installation, refreshed early) → GraphQL/REST calls.-// - snapshot.go: the single GraphQL query, contexts pagination, and+// token (cached per installation, refreshed early) → REST calls.+// - snapshot.go: PR / Checks / Statuses queries, pagination, and// normalization into a flat per-check snapshot.// - refresh.go: the outbound work queue (dedup, single in-flight per PR,// bounded concurrency, Retry-After backoff), the head-SHA-guarded atomic@@ -18,7 +18,6 @@package ghsnapshotimport (- "bytes""context""crypto/rsa""encoding/json"@@ -179,7 +178,7 @@ func (c *Client) mintInstallationToken(ctx context.Context, installationID int64}defer resp.Body.Close()body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))- if resp.StatusCode == http.StatusForbidden || resp.StatusCode == http.StatusTooManyRequests {+ if isRateLimited(resp, body) {return "", rateLimitFromResponse(resp, c.now())}if resp.StatusCode != http.StatusCreated && resp.StatusCode != http.StatusOK {@@ -209,64 +208,61 @@ func (c *Client) mintInstallationToken(ctx context.Context, installationID int64return parsed.Token, nil}-// graphQL runs a single GraphQL query as the given installation and returns the-// raw `data` object. GitHub returns HTTP 200 even for query-level errors, so we-// inspect the `errors` array too, mapping a RATE_LIMITED error type to a-// RateLimitError.-func (c *Client) graphQL(ctx context.Context, installationID int64, query string, variables map[string]any) (json.RawMessage, error) {+// restGet authenticates against a fixed API path. Response bodies and tokens+// never appear in errors; permission failures must not pause an installation.+func (c *Client) restGet(ctx context.Context, installationID int64, path string) (json.RawMessage, error) {token, err := c.installationToken(ctx, installationID)if err != nil {return nil, err}- payload, err := json.Marshal(map[string]any{"query": query, "variables": variables})- if err != nil {- return nil, err- }- endpoint := strings.TrimRight(c.apiBase, "/") + "/graphql"- req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(payload))+ endpoint := strings.TrimRight(c.apiBase, "/") + path+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)if err != nil {return nil, err}req.Header.Set("Accept", "application/vnd.github+json")- req.Header.Set("Content-Type", "application/json")req.Header.Set("Authorization", "Bearer "+token)-+ req.Header.Set("X-GitHub-Api-Version", "2022-11-28")resp, err := c.httpClient.Do(req)if err != nil {return nil, err}defer resp.Body.Close()- body, _ := io.ReadAll(io.LimitReader(resp.Body, 8<<20))- if resp.StatusCode == http.StatusForbidden || resp.StatusCode == http.StatusTooManyRequests {+ const maxBody = 8 << 20+ body, err := io.ReadAll(io.LimitReader(resp.Body, maxBody+1))+ if err != nil {+ return nil, errors.New("github REST: failed to read response")+ }+ if isRateLimited(resp, body) {return nil, rateLimitFromResponse(resp, c.now())}if resp.StatusCode != http.StatusOK {- return nil, fmt.Errorf("github graphql: unexpected status %d", resp.StatusCode)+ return nil, fmt.Errorf("github REST: unexpected status %d", resp.StatusCode)}- var envelope struct {- Data json.RawMessage `json:"data"`- Errors []struct {- Type string `json:"type"`- Message string `json:"message"`- } `json:"errors"`+ if len(body) > maxBody {+ return nil, errors.New("github REST: response exceeds size limit")}- if err := json.Unmarshal(body, &envelope); err != nil {- return nil, errors.New("github graphql: malformed response")+ return body, nil+}++func isRateLimited(resp *http.Response, body []byte) bool {+ if resp.StatusCode == http.StatusTooManyRequests {+ return true}- if len(envelope.Errors) > 0 {- for _, e := range envelope.Errors {- if e.Type == "RATE_LIMITED" {- return nil, &RateLimitError{RetryAfter: time.Minute}- }- }- // Surface the message but nothing else; GraphQL error messages do not- // contain credentials.- return nil, fmt.Errorf("github graphql error: %s", envelope.Errors[0].Message)+ if resp.StatusCode != http.StatusForbidden {+ return false+ }+ if resp.Header.Get("X-RateLimit-Remaining") == "0" || resp.Header.Get("Retry-After") != "" {+ return true+ }+ var failure struct {+ Message string `json:"message"`}- if len(envelope.Data) == 0 {- return nil, errors.New("github graphql: empty data")+ if json.Unmarshal(body, &failure) != nil {+ return false}- return envelope.Data, nil+ message := strings.ToLower(failure.Message)+ return strings.Contains(message, "secondary rate limit") || strings.Contains(message, "abuse detection")}// rateLimitFromResponse builds a RateLimitError from GitHub's throttlingdiff --git a/server/internal/integrations/ghsnapshot/client_test.go b/server/internal/integrations/ghsnapshot/client_test.goindex 8c742d1d94..be3ae8ae8a 100644--- a/server/internal/integrations/ghsnapshot/client_test.go+++ b/server/internal/integrations/ghsnapshot/client_test.go@@ -6,6 +6,7 @@ import ("crypto/rsa""crypto/x509""encoding/pem"+ "errors""net/http""net/http/httptest""strings"@@ -112,9 +113,9 @@ func TestInstallationTokenSingleflight(t *testing.T) {}}-// TestGraphQLRateLimited maps a 403 with Retry-After to a *RateLimitError so the+// TestRESTRateLimited maps a 403 with Retry-After to a *RateLimitError so the// refresh manager can back off (acceptance criterion 3).-func TestGraphQLRateLimited(t *testing.T) {+func TestRESTRateLimited(t *testing.T) {srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {if strings.HasSuffix(r.URL.Path, "/access_tokens") {w.WriteHeader(http.StatusCreated)@@ -128,7 +129,7 @@ func TestGraphQLRateLimited(t *testing.T) {defer srv.Close()c := newTestClient(t, srv.URL)- _, err := c.graphQL(context.Background(), 1, "query{}", nil)+ _, err := c.restGet(context.Background(), 1, "/repos/o/r/pulls/5")rl, ok := err.(*RateLimitError)if !ok {t.Fatalf("err = %T (%v), want *RateLimitError", err, err)@@ -163,6 +164,55 @@ func TestRateLimitFromResponse(t *testing.T) {}}+func TestRESTErrorsKeepPermissionsSeparateFromRateLimits(t *testing.T) {+ cases := []struct {+ name string+ status int+ headers map[string]string+ body string+ limited bool+ }{+ {"permission denied", 403, nil, `{"message":"Resource not accessible by integration: ghs_secret"}`, false},+ {"not found", 404, nil, `{"message":"private resource ghs_secret"}`, false},+ {"upstream unavailable", 503, nil, `{"message":"ghs_secret"}`, false},+ {"primary limit", 403, map[string]string{"X-RateLimit-Remaining": "0"}, `{}`, true},+ {"retry after", 403, map[string]string{"Retry-After": "20"}, `{}`, true},+ {"secondary limit", 403, nil, `{"message":"You have exceeded a secondary rate limit."}`, true},+ {"too many requests", 429, nil, `{}`, true},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ srv := snapshotServer(t, func(w http.ResponseWriter, r *http.Request) {+ for key, value := range tc.headers {+ w.Header().Set(key, value)+ }+ w.WriteHeader(tc.status)+ _, _ = w.Write([]byte(tc.body))+ })+ defer srv.Close()+ _, err := newTestClient(t, srv.URL).restGet(context.Background(), 1, "/repos/o/r/pulls/5")+ var limited *RateLimitError+ if err == nil || errors.As(err, &limited) != tc.limited {+ t.Fatalf("err=%v, want rate limit=%v", err, tc.limited)+ }+ if strings.Contains(err.Error(), "ghs_secret") {+ t.Fatal("response body leaked through error")+ }+ })+ }+}++func TestRESTRejectsOversizedResponse(t *testing.T) {+ srv := snapshotServer(t, func(w http.ResponseWriter, r *http.Request) {+ _, _ = w.Write([]byte(strings.Repeat(" ", (8<<20)+1)))+ })+ defer srv.Close()+ _, err := newTestClient(t, srv.URL).restGet(context.Background(), 1, "/repos/o/r/pulls/5")+ if err == nil || !strings.Contains(err.Error(), "size limit") {+ t.Fatalf("error=%v", err)+ }+}+// TestNewClientFromEnv covers the three configuration outcomes, including the// clean-degradation case (acceptance criterion 4): no key → nil client, no error.func TestNewClientFromEnv(t *testing.T) {diff --git a/server/internal/integrations/ghsnapshot/refresh_db_test.go b/server/internal/integrations/ghsnapshot/refresh_db_test.goindex 3929287230..e08c7d3090 100644--- a/server/internal/integrations/ghsnapshot/refresh_db_test.go+++ b/server/internal/integrations/ghsnapshot/refresh_db_test.go@@ -3,7 +3,10 @@ package ghsnapshotimport ("context""crypto/rand"+ "fmt"+ "net/http""os"+ "sync/atomic""testing""time"@@ -415,3 +418,55 @@ func TestApplySnapshotReplacesRuns(t *testing.T) {t.Fatalf("after replace: %d runs, want 1 (old runs deleted)", n)}}++func TestRESTSnapshotRefreshStoresResultsAndPreservesThemOnPermissionFailure(t *testing.T) {+ pool := testDBPool(t)+ q := db.New(pool)+ ctx := context.Background()+ pr := seedPRAt(t, pool, q, 1, "r", 5, "sha1")+ t.Cleanup(func() {+ _, _ = pool.Exec(ctx, `DELETE FROM github_pull_request_check_run WHERE pr_id=$1`, pr.ID)+ _, _ = pool.Exec(ctx, `DELETE FROM github_pull_request WHERE id=$1`, pr.ID)+ })+ var phase atomic.Int32+ srv := snapshotServer(t, func(w http.ResponseWriter, r *http.Request) {+ switch r.URL.Path {+ case "/repos/o/r/pulls/5":+ writeTestPR(w, "sha1", true, "clean")+ case "/repos/o/r/commits/sha1/check-runs":+ if phase.Load() == 2 {+ w.WriteHeader(http.StatusForbidden)+ return+ }+ conclusion := "success"+ if phase.Load() == 1 {+ conclusion = "failure"+ }+ _, _ = fmt.Fprintf(w, `{"total_count":1,"check_runs":[{"id":1,"head_sha":"sha1","name":"ci","status":"completed","conclusion":%q}]}`, conclusion)+ case "/repos/o/r/commits/sha1/status":+ _, _ = w.Write([]byte(`{"total_count":0,"statuses":[]}`))+ default:+ t.Errorf("unexpected request: %s", r.URL.Path)+ w.WriteHeader(http.StatusNotFound)+ }+ })+ defer srv.Close()+ applied := 0+ m := NewManager(newTestClient(t, srv.URL), q, pool, func(context.Context, pgtype.UUID) { applied++ })+ m.jitter = func() time.Duration { return 0 }+ addr := address{InstallationID: 1, Owner: "o", Repo: "r", Number: 5}+ for i, want := range []string{"SUCCESS", "FAILURE", "FAILURE"} {+ phase.Store(int32(i))+ m.process(ctx, addr)+ got, err := q.GetGitHubPullRequestByID(ctx, pr.ID)+ if err != nil {+ t.Fatal(err)+ }+ if got.SnapshotHeadSha != "sha1" || !got.SnapshotFetchedAt.Valid || got.ChecksRollupState.String != want || checkRunCount(t, pool, pr.ID) != 1 {+ t.Fatalf("phase %d: stored snapshot=%+v, want %s", i, got, want)+ }+ }+ if applied != 2 || len(m.rateUntil) != 0 {+ t.Fatalf("permission failure must preserve snapshot without notification or installation pause: applied=%d limits=%v", applied, m.rateUntil)+ }+}diff --git a/server/internal/integrations/ghsnapshot/rest_snapshot_test.go b/server/internal/integrations/ghsnapshot/rest_snapshot_test.gonew file mode 100644index 0000000000..1628dd9224--- /dev/null+++ b/server/internal/integrations/ghsnapshot/rest_snapshot_test.go@@ -0,0 +1,227 @@+package ghsnapshot++import (+ "context"+ "encoding/json"+ "fmt"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+ "time"+)++// Only the REST endpoints covered by the App's existing permissions are served.+// Fork PRs deliberately have a head repository outside the installation.+func snapshotServer(t *testing.T, handler http.HandlerFunc) *httptest.Server {+ t.Helper()+ return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ if r.URL.Path == "/app/installations/1/access_tokens" {+ w.WriteHeader(http.StatusCreated)+ _ = json.NewEncoder(w).Encode(map[string]any{+ "token": "ghs_secret", "expires_at": time.Now().Add(time.Hour).Format(time.RFC3339),+ "permissions": map[string]string{"pull_requests": "read", "checks": "read", "statuses": "read"},+ })+ return+ }+ if r.Method != http.MethodGet || r.Header.Get("Authorization") != "Bearer ghs_secret" {+ t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path)+ w.WriteHeader(http.StatusUnauthorized)+ return+ }+ handler(w, r)+ }))+}++func writeTestPR(w http.ResponseWriter, sha string, mergeable any, state string) {+ _ = json.NewEncoder(w).Encode(map[string]any{+ "head": map[string]any{"sha": sha, "repo": map[string]any{"full_name": "external/fork"}},+ "mergeable": mergeable, "mergeable_state": state,+ })+}++func TestFetchPRSnapshotRESTPagination(t *testing.T) {+ prCalls, runPages, statusPages := 0, 0, 0+ srv := snapshotServer(t, func(w http.ResponseWriter, r *http.Request) {+ switch r.URL.Path {+ case "/repos/o/r/pulls/5":+ prCalls+++ writeTestPR(w, "sha1", true, "clean")+ case "/repos/o/r/commits/sha1/check-runs":+ runPages+++ if r.URL.Query().Get("per_page") != "100" || r.URL.Query().Get("filter") != "latest" {+ t.Errorf("check query = %s", r.URL.RawQuery)+ }+ var runs []map[string]any+ if r.URL.Query().Get("page") == "1" {+ for i := 1; i <= 100; i++ {+ runs = append(runs, map[string]any{"id": i, "head_sha": "sha1", "name": fmt.Sprintf("job%d", i), "status": "completed", "conclusion": "success", "details_url": "https://example.com/run"})+ }+ } else {+ runs = []map[string]any{+ {"id": 101, "head_sha": "sha1", "name": "expired", "status": "completed", "conclusion": "stale"},+ {"id": 102, "head_sha": "sha1", "name": "running", "status": "in_progress", "conclusion": nil},+ }+ }+ _ = json.NewEncoder(w).Encode(map[string]any{"total_count": 102, "check_runs": runs})+ case "/repos/o/r/commits/sha1/status":+ statusPages+++ var statuses []map[string]any+ if r.URL.Query().Get("page") == "1" {+ for i := 1; i <= 100; i++ {+ statuses = append(statuses, map[string]any{"context": fmt.Sprintf("status%d", i), "state": "success", "target_url": "https://example.com/status"})+ }+ } else {+ statuses = []map[string]any{{"context": "deploy", "state": "pending"}}+ }+ _ = json.NewEncoder(w).Encode(map[string]any{"total_count": 101, "statuses": statuses})+ default:+ t.Errorf("request outside base repository REST endpoints: %s", r.URL.Path)+ w.WriteHeader(http.StatusNotFound)+ }+ })+ defer srv.Close()+ snap, err := FetchPRSnapshot(context.Background(), newTestClient(t, srv.URL), 1, "o", "r", 5)+ if err != nil {+ t.Fatal(err)+ }+ if snap.HeadSHA != "sha1" || snap.Mergeable != "MERGEABLE" || snap.MergeStateStatus != "CLEAN" || !snap.HasChecks || snap.RollupState != "FAILURE" {+ t.Fatalf("snapshot = %+v", snap)+ }+ if len(snap.Contexts) != 203 || prCalls != 2 || runPages != 2 || statusPages != 2 {+ t.Fatalf("contexts=%d PR calls=%d check pages=%d status pages=%d", len(snap.Contexts), prCalls, runPages, statusPages)+ }+ if snap.Contexts[100].Conclusion != "stale" || snap.Contexts[101].Status != "in_progress" || snap.Contexts[101].Conclusion != "" || snap.Decided() {+ t.Fatalf("failure plus running checks = %+v", snap)+ }+ if last := snap.Contexts[202]; last.Status != "in_progress" || !last.IsStatusContext {+ t.Fatalf("legacy pending status = %+v", last)+ }+}++func TestFetchPRSnapshotRESTResults(t *testing.T) {+ cases := []struct {+ name, runs, statuses, want string+ }{+ {"no checks", `[]`, `[]`, ""},+ {"only check run", `[{"id":1,"head_sha":"sha1","name":"ci","status":"completed","conclusion":"success"}]`, `[]`, "SUCCESS"},+ {"only status", `[]`, `[{"context":"deploy","state":"success"}]`, "SUCCESS"},+ {"status error", `[]`, `[{"context":"deploy","state":"error"}]`, "FAILURE"},+ {"stale fails", `[{"id":1,"head_sha":"sha1","name":"ci","status":"completed","conclusion":"stale"}]`, `[]`, "FAILURE"},+ {"unknown conclusion", `[{"id":1,"head_sha":"sha1","name":"ci","status":"completed","conclusion":"future_result"}]`, `[]`, "PENDING"},+ {"empty conclusion", `[{"id":1,"head_sha":"sha1","name":"ci","status":"completed","conclusion":null}]`, `[]`, "PENDING"},+ {"unknown status", `[]`, `[{"context":"deploy","state":"future_state"}]`, "PENDING"},+ {"failure before pending", `[{"id":1,"head_sha":"sha1","name":"ci","status":"completed","conclusion":"failure"}]`, `[{"context":"deploy","state":"pending"}]`, "FAILURE"},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ srv := snapshotServer(t, func(w http.ResponseWriter, r *http.Request) {+ switch r.URL.Path {+ case "/repos/o/r/pulls/5":+ writeTestPR(w, "sha1", nil, "unknown")+ case "/repos/o/r/commits/sha1/check-runs":+ var entries []json.RawMessage+ _ = json.Unmarshal([]byte(tc.runs), &entries)+ _, _ = fmt.Fprintf(w, `{"total_count":%d,"check_runs":%s}`, len(entries), tc.runs)+ case "/repos/o/r/commits/sha1/status":+ var entries []json.RawMessage+ _ = json.Unmarshal([]byte(tc.statuses), &entries)+ _, _ = fmt.Fprintf(w, `{"total_count":%d,"statuses":%s}`, len(entries), tc.statuses)+ default:+ w.WriteHeader(http.StatusNotFound)+ }+ })+ defer srv.Close()+ snap, err := FetchPRSnapshot(context.Background(), newTestClient(t, srv.URL), 1, "o", "r", 5)+ if err != nil {+ t.Fatal(err)+ }+ if tc.name == "unknown conclusion" || tc.name == "empty conclusion" {+ if snap.Contexts[0].Status == "completed" || snap.Contexts[0].Conclusion != "" {+ t.Fatalf("unknown result must stay running: %+v", snap.Contexts[0])+ }+ }+ if snap.RollupState != tc.want || snap.HasChecks != (tc.want != "") || snap.Mergeable != "UNKNOWN" || snap.MergeStateStatus != "UNKNOWN" || snap.Decided() {+ t.Fatalf("snapshot = %+v, want rollup %q", snap, tc.want)+ }+ })+ }+}++func TestFetchPRSnapshotRESTRejectsPartialResults(t *testing.T) {+ for _, failure := range []string{"head changed", "missing head", "check page failed", "status failed", "page limit", "truncated page", "count changed", "missing collection", "duplicate run", "wrong head"} {+ t.Run(failure, func(t *testing.T) {+ prCalls := 0+ srv := snapshotServer(t, func(w http.ResponseWriter, r *http.Request) {+ switch r.URL.Path {+ case "/repos/o/r/pulls/5":+ prCalls+++ sha := "sha1"+ if failure == "head changed" && prCalls == 2 {+ sha = "sha2"+ }+ if failure == "missing head" {+ sha = ""+ }+ writeTestPR(w, sha, false, "dirty")+ case "/repos/o/r/commits/sha1/check-runs":+ page := r.URL.Query().Get("page")+ if failure == "check page failed" && page == "2" {+ w.WriteHeader(500)+ return+ }+ if failure == "missing collection" {+ _, _ = w.Write([]byte(`{"total_count":0}`))+ return+ }+ if failure == "truncated page" {+ _, _ = w.Write([]byte(`{"total_count":1,"check_runs":[]}`))+ return+ }+ count := 0+ var runs []map[string]any = []map[string]any{}+ if failure == "check page failed" || failure == "page limit" || failure == "count changed" || failure == "duplicate run" {+ count = 101+ if failure == "page limit" {+ count = 100*maxSnapshotContextPages + 1+ }+ if failure == "count changed" && page == "2" {+ count = 102+ }+ for i := 0; i < 100; i++ {+ var n int+ _, _ = fmt.Sscan(page, &n)+ id := (n-1)*100 + i + 1+ if failure == "duplicate run" {+ id = 1+ }+ runs = append(runs, map[string]any{"id": id, "head_sha": "sha1", "name": fmt.Sprint(id), "status": "completed", "conclusion": "success"})+ }+ }+ if failure == "wrong head" {+ count = 1+ runs = []map[string]any{{"id": 1, "head_sha": "sha2", "name": "ci", "status": "completed", "conclusion": "success"}}+ }+ _ = json.NewEncoder(w).Encode(map[string]any{"total_count": count, "check_runs": runs})+ case "/repos/o/r/commits/sha1/status":+ if failure == "status failed" {+ w.WriteHeader(404)+ return+ }+ _, _ = w.Write([]byte(`{"total_count":0,"statuses":[]}`))+ default:+ w.WriteHeader(http.StatusNotFound)+ }+ })+ defer srv.Close()+ snap, err := FetchPRSnapshot(context.Background(), newTestClient(t, srv.URL), 1, "o", "r", 5)+ if err == nil || snap != nil {+ t.Fatalf("snapshot=%+v err=%v; partial results must be rejected", snap, err)+ }+ if strings.Contains(err.Error(), "ghs_secret") {+ t.Fatal("error leaked installation token")+ }+ })+ }+}diff --git a/server/internal/integrations/ghsnapshot/snapshot.go b/server/internal/integrations/ghsnapshot/snapshot.goindex a004102514..1807a00f07 100644--- a/server/internal/integrations/ghsnapshot/snapshot.go+++ b/server/internal/integrations/ghsnapshot/snapshot.go@@ -4,45 +4,13 @@ import ("context""encoding/json""errors"+ "fmt"+ "net/url""strings")-// prSnapshotQuery is the single GraphQL query behind the whole feature. It-// returns, in one round trip (Elon measured cost=1):-// - headRefOid: the head the snapshot describes (pins the anti-stale write);-// - mergeable: MERGEABLE / CONFLICTING / UNKNOWN — answers "is there a-// conflict" only;-// - mergeStateStatus: CLEAN / DIRTY / BLOCKED / BEHIND / UNSTABLE / ... —-// "Ready to merge" is derived ONLY from CLEAN;-// - statusCheckRollup: the overall CI verdict plus every check/status context.-//-// $cursor paginates statusCheckRollup.contexts; the caller loops until-// hasNextPage is false (acceptance criterion 2 — never assume <100 contexts).-const prSnapshotQuery = `query($owner:String!,$repo:String!,$number:Int!,$cursor:String){- repository(owner:$owner,name:$repo){- pullRequest(number:$number){- headRefOid- mergeable- mergeStateStatus- commits(last:1){nodes{commit{- statusCheckRollup{- state- contexts(first:100,after:$cursor){- pageInfo{hasNextPage endCursor}- nodes{- __typename- ... on CheckRun{name status conclusion detailsUrl}- ... on StatusContext{context state targetUrl}- }- }- }- }}}- }- }-}`--// CheckContext is one normalized check for a PR head. Both GraphQL CheckRun and-// StatusContext contexts are flattened into this shape (see normalizeNode), so+// CheckContext is one normalized check for a PR head. Both check runs and commit+// statuses are flattened into this shape, so// downstream storage and aggregation are uniform.type CheckContext struct {Name string@@ -58,16 +26,15 @@ type CheckContext struct {}// PRSnapshot is the atomic unit written per fetch. It mirrors exactly what the-// API returned — no incremental inference.+// API returned — no incremental inference from webhook events.type PRSnapshot struct {HeadSHA stringMergeable string // MERGEABLE / CONFLICTING / UNKNOWN (raw enum)MergeStateStatus string // CLEAN / DIRTY / BLOCKED / BEHIND / UNSTABLE / ... (raw enum)- // RollupState is statusCheckRollup.state (SUCCESS/FAILURE/PENDING/ERROR/- // EXPECTED). Empty ONLY when HasChecks is false.+ // RollupState aggregates the current head's check runs and commit statuses.+ // Empty ONLY when HasChecks is false.RollupState string- // HasChecks is false when statusCheckRollup was null — GitHub reports "no- // checks have been created for this commit yet". This must NEVER be rendered+ // HasChecks is false when both API collections are empty. This must NEVER be rendered// as passed (acceptance criterion 5).HasChecks boolContexts []CheckContext@@ -94,171 +61,204 @@ func (s *PRSnapshot) Decided() bool {return true}-type graphqlRollup struct {- State string `json:"state"`- Contexts struct {- PageInfo struct {- HasNextPage bool `json:"hasNextPage"`- EndCursor string `json:"endCursor"`- } `json:"pageInfo"`- Nodes []json.RawMessage `json:"nodes"`- } `json:"contexts"`-}+const (+ maxSnapshotContextPages = 100+ snapshotPageSize = 100+)-type graphqlPullRequest struct {- HeadRefOid string `json:"headRefOid"`- Mergeable string `json:"mergeable"`- MergeStateStatus string `json:"mergeStateStatus"`- Commits struct {- Nodes []struct {- Commit struct {- StatusCheckRollup *graphqlRollup `json:"statusCheckRollup"`- } `json:"commit"`- } `json:"nodes"`- } `json:"commits"`+type restPullRequest struct {+ Head struct {+ SHA string `json:"sha"`+ } `json:"head"`+ Mergeable *bool `json:"mergeable"`+ MergeableState string `json:"mergeable_state"`}-func (pr *graphqlPullRequest) rollup() *graphqlRollup {- if len(pr.Commits.Nodes) == 0 {- return nil- }- return pr.Commits.Nodes[0].Commit.StatusCheckRollup+type restCheckRun struct {+ ID int64 `json:"id"`+ HeadSHA string `json:"head_sha"`+ Name string `json:"name"`+ Status string `json:"status"`+ Conclusion string `json:"conclusion"`+ DetailsURL string `json:"details_url"`}-type graphqlPRData struct {- Repository struct {- PullRequest *graphqlPullRequest `json:"pullRequest"`- } `json:"repository"`+type restStatusContext struct {+ Context string `json:"context"`+ State string `json:"state"`+ TargetURL string `json:"target_url"`}-const maxSnapshotContextPages = 100--// FetchPRSnapshot runs prSnapshotQuery, paginating statusCheckRollup.contexts-// to completion, and returns the normalized snapshot. A nil rollup yields-// HasChecks=false with no contexts.+// FetchPRSnapshot uses only Pull requests, Checks and Commit statuses read+// permissions. Every page is pinned to one head; a final PR read detects pushes+// before the guarded atomic write in refresh.go.func FetchPRSnapshot(ctx context.Context, c *Client, installationID int64, owner, repo string, number int32) (*PRSnapshot, error) {if !c.Enabled() {return nil, errors.New("ghsnapshot: client not configured")}- snap := &PRSnapshot{}- cursor := ""- // Guard against a pathological cursor loop; 100 pages = 10k contexts, far- // beyond any real PR.- for page := 0; page < maxSnapshotContextPages; page++ {- vars := map[string]any{"owner": owner, "repo": repo, "number": number}- if cursor != "" {- vars["cursor"] = cursor+ base := "/repos/" + url.PathEscape(owner) + "/" + url.PathEscape(repo)+ prPath := fmt.Sprintf("%s/pulls/%d", base, number)+ pr, err := fetchSnapshotPR(ctx, c, installationID, prPath)+ if err != nil {+ return nil, err+ }+ commitPath := base + "/commits/" + url.PathEscape(pr.Head.SHA)+ runs, err := fetchSnapshotPages[restCheckRun](ctx, c, installationID, commitPath+"/check-runs?filter=latest", "check_runs")+ if err != nil {+ return nil, err+ }+ statuses, err := fetchSnapshotPages[restStatusContext](ctx, c, installationID, commitPath+"/status", "statuses")+ if err != nil {+ return nil, err+ }++ snap := &PRSnapshot{HeadSHA: pr.Head.SHA}+ seenRuns := make(map[int64]struct{}, len(runs))+ for _, run := range runs {+ if run.ID <= 0 || run.Name == "" || run.HeadSHA != snap.HeadSHA {+ return nil, errors.New("ghsnapshot: invalid check run or mismatched head")+ }+ if _, seen := seenRuns[run.ID]; seen {+ return nil, errors.New("ghsnapshot: duplicate check run during pagination")+ }+ seenRuns[run.ID] = struct{}{}+ status := normalizeRunStatus(run.Status)+ conclusion := strings.ToLower(run.Conclusion)+ if status != "completed" {+ conclusion = ""+ } else if rollupConclusion(conclusion) == "PENDING" {+ // Unknown/empty conclusions must remain undecided in both the+ // refresh queue and the persisted running-check counts.+ status, conclusion = "queued", ""+ }+ snap.Contexts = append(snap.Contexts, CheckContext{Name: run.Name, Status: status, Conclusion: conclusion, DetailsURL: run.DetailsURL})+ }+ seenStatuses := make(map[string]struct{}, len(statuses))+ for _, entry := range statuses {+ if entry.Context == "" {+ return nil, errors.New("ghsnapshot: missing status context")+ }+ if _, seen := seenStatuses[entry.Context]; seen {+ return nil, errors.New("ghsnapshot: duplicate status context during pagination")+ }+ seenStatuses[entry.Context] = struct{}{}+ status, conclusion := normalizeStatusState(entry.State)+ snap.Contexts = append(snap.Contexts, CheckContext{Name: entry.Context, Status: status, Conclusion: conclusion, DetailsURL: entry.TargetURL, IsStatusContext: true})+ }++ latest, err := fetchSnapshotPR(ctx, c, installationID, prPath)+ if err != nil {+ return nil, err+ }+ if latest.Head.SHA != snap.HeadSHA {+ return nil, errors.New("ghsnapshot: pull request head changed during fetch")+ }+ snap.Mergeable = "UNKNOWN"+ if latest.Mergeable != nil {+ if *latest.Mergeable {+ snap.Mergeable = "MERGEABLE"} else {- vars["cursor"] = nil+ snap.Mergeable = "CONFLICTING"}- data, err := c.graphQL(ctx, installationID, prSnapshotQuery, vars)+ }+ snap.MergeStateStatus = strings.ToUpper(latest.MergeableState)+ if latest.Mergeable == nil || snap.MergeStateStatus == "" {+ snap.MergeStateStatus = "UNKNOWN"+ }+ snap.HasChecks = len(snap.Contexts) > 0+ if snap.HasChecks {+ snap.RollupState = rollupContexts(snap.Contexts)+ }+ return snap, nil+}++func fetchSnapshotPR(ctx context.Context, c *Client, installationID int64, path string) (*restPullRequest, error) {+ data, err := c.restGet(ctx, installationID, path)+ if err != nil {+ return nil, err+ }+ var pr restPullRequest+ if json.Unmarshal(data, &pr) != nil || pr.Head.SHA == "" {+ return nil, errors.New("ghsnapshot: malformed pull request data")+ }+ return &pr, nil+}++// Counts must stay consistent across pages. Never commit a truncated collection+// or follow a pagination URL carrying the installation token to another host.+func fetchSnapshotPages[T any](ctx context.Context, c *Client, installationID int64, path, collection string) ([]T, error) {+ var items []T+ expected := -1+ separator := "?"+ if strings.Contains(path, "?") {+ separator = "&"+ }+ for page := 1; page <= maxSnapshotContextPages; page++ {+ data, err := c.restGet(ctx, installationID, fmt.Sprintf("%s%sper_page=%d&page=%d", path, separator, snapshotPageSize, page))if err != nil {return nil, err}- var parsed graphqlPRData- if err := json.Unmarshal(data, &parsed); err != nil {- return nil, errors.New("ghsnapshot: malformed pull request data")- }- pr := parsed.Repository.PullRequest- if pr == nil {- return nil, errors.New("ghsnapshot: pull request not found")+ var envelope map[string]json.RawMessage+ if json.Unmarshal(data, &envelope) != nil {+ return nil, errors.New("ghsnapshot: malformed check page")}- if page == 0 {- snap.HeadSHA = pr.HeadRefOid- snap.Mergeable = pr.Mergeable- snap.MergeStateStatus = pr.MergeStateStatus- } else if pr.HeadRefOid != snap.HeadSHA {- // Every page re-reads the PR's latest commit. If a synchronize- // event advances the head while pagination is in progress, mixing- // those pages would label new-head contexts as the old head.- return nil, errors.New("ghsnapshot: pull request head changed during pagination")+ var count *int+ var entries []T+ if json.Unmarshal(envelope["total_count"], &count) != nil || count == nil || *count < 0 ||+ json.Unmarshal(envelope[collection], &entries) != nil || entries == nil || len(entries) > snapshotPageSize {+ return nil, errors.New("ghsnapshot: malformed check collection")}- rollup := pr.rollup()- if rollup == nil {- // statusCheckRollup is null → no checks yet. Nothing to paginate.- if page > 0 {- return nil, errors.New("ghsnapshot: check rollup changed during pagination")- }- return snap, nil+ if expected == -1 {+ expected = *count+ } else if *count != expected {+ return nil, errors.New("ghsnapshot: check count changed during pagination")}- snap.HasChecks = true- snap.RollupState = rollup.State- for _, raw := range rollup.Contexts.Nodes {- if cc, ok := normalizeNode(raw); ok {- snap.Contexts = append(snap.Contexts, cc)- }+ items = append(items, entries...)+ if len(items) > expected {+ return nil, errors.New("ghsnapshot: check collection exceeds reported count")}- if !rollup.Contexts.PageInfo.HasNextPage {- return snap, nil+ if len(items) == expected {+ return items, nil}- nextCursor := rollup.Contexts.PageInfo.EndCursor- if nextCursor == "" || nextCursor == cursor {- return nil, errors.New("ghsnapshot: invalid check-context pagination cursor")+ if len(entries) == 0 {+ return nil, errors.New("ghsnapshot: truncated check collection")}- if page == maxSnapshotContextPages-1 {- return nil, errors.New("ghsnapshot: check-context pagination exceeds page limit")- }- cursor = nextCursor}return nil, errors.New("ghsnapshot: check-context pagination exceeds page limit")}-// normalizeNode flattens one GraphQL union node (CheckRun or StatusContext)-// into a CheckContext. CheckRun statuses/conclusions map to lowercase; legacy-// StatusContext states map onto the same lifecycle so aggregation is uniform:-//-// SUCCESS → completed / success-// FAILURE → completed / failure-// ERROR → completed / error-// PENDING → in_progress / (running)-// EXPECTED → queued / (running)-func normalizeNode(raw json.RawMessage) (CheckContext, bool) {- var probe struct {- Typename string `json:"__typename"`- }- if err := json.Unmarshal(raw, &probe); err != nil {- return CheckContext{}, false- }- switch probe.Typename {- case "CheckRun":- var n struct {- Name string `json:"name"`- Status string `json:"status"`- Conclusion string `json:"conclusion"`- DetailsURL string `json:"detailsUrl"`- }- if err := json.Unmarshal(raw, &n); err != nil {- return CheckContext{}, false- }- return CheckContext{- Name: n.Name,- Status: normalizeRunStatus(n.Status),- Conclusion: strings.ToLower(n.Conclusion),- DetailsURL: n.DetailsURL,- }, true- case "StatusContext":- var n struct {- Context string `json:"context"`- State string `json:"state"`- TargetURL string `json:"targetUrl"`+func rollupContexts(contexts []CheckContext) string {+ pending := false+ for _, cc := range contexts {+ if cc.Status != "completed" {+ pending = true+ continue}- if err := json.Unmarshal(raw, &n); err != nil {- return CheckContext{}, false+ switch rollupConclusion(cc.Conclusion) {+ case "FAILURE":+ return "FAILURE"+ case "PENDING":+ pending = true}- status, conclusion := normalizeStatusState(n.State)- return CheckContext{- Name: n.Context,- Status: status,- Conclusion: conclusion,- DetailsURL: n.TargetURL,- IsStatusContext: true,- }, true+ }+ if pending {+ return "PENDING"+ }+ return "SUCCESS"+}++func rollupConclusion(conclusion string) string {+ switch conclusion {+ case "failure", "cancelled", "timed_out", "action_required", "startup_failure", "stale", "error":+ return "FAILURE"+ case "success", "neutral", "skipped":+ return "SUCCESS"default:- return CheckContext{}, false+ return "PENDING"}}-// normalizeRunStatus maps a GraphQL CheckRun.status enum to our lifecycle.+// normalizeRunStatus maps a check run status to our lifecycle.// Only COMPLETED is terminal; QUEUED/IN_PROGRESS/WAITING/PENDING/REQUESTED are// all still running.func normalizeRunStatus(s string) string {diff --git a/server/internal/integrations/ghsnapshot/snapshot_test.go b/server/internal/integrations/ghsnapshot/snapshot_test.goindex 62d60cb086..b6c4fba309 100644--- a/server/internal/integrations/ghsnapshot/snapshot_test.go+++ b/server/internal/integrations/ghsnapshot/snapshot_test.go@@ -1,172 +1,6 @@package ghsnapshot-import (- "context"- "encoding/json"- "fmt"- "io"- "net/http"- "net/http/httptest"- "strings"- "testing"- "time"-)--// graphqlServer stands in for GitHub's GraphQL endpoint. tokenHandler mints a-// token; the queryFn produces the `data` payload for each GraphQL request,-// receiving the request variables so it can page.-func graphqlServer(t *testing.T, queryFn func(vars map[string]any) string) *httptest.Server {- t.Helper()- return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- if strings.HasSuffix(r.URL.Path, "/access_tokens") {- w.WriteHeader(http.StatusCreated)- _, _ = w.Write([]byte(`{"token":"ghs_secret","expires_at":"` +- time.Now().Add(time.Hour).UTC().Format(time.RFC3339) + `"}`))- return- }- body, _ := io.ReadAll(r.Body)- var req struct {- Variables map[string]any `json:"variables"`- }- _ = json.Unmarshal(body, &req)- _, _ = w.Write([]byte(`{"data":` + queryFn(req.Variables) + `}`))- }))-}--func graphqlSnapshotPage(head string, hasNext bool, endCursor string) string {- return fmt.Sprintf(`{"repository":{"pullRequest":{- "headRefOid":%q,"mergeable":"MERGEABLE","mergeStateStatus":"CLEAN",- "commits":{"nodes":[{"commit":{"statusCheckRollup":{"state":"PENDING","contexts":{- "pageInfo":{"hasNextPage":%t,"endCursor":%q},"nodes":[]- }}}}]}}}}`, head, hasNext, endCursor)-}--// TestFetchPRSnapshotPaginatesContexts is the acceptance-criterion-2 test:-// contexts spanning two pages must all be collected — never assume <100.-func TestFetchPRSnapshotPaginatesContexts(t *testing.T) {- srv := graphqlServer(t, func(vars map[string]any) string {- cursor, _ := vars["cursor"].(string)- if cursor == "" {- // Page 1: two contexts, more to come.- return `{"repository":{"pullRequest":{- "headRefOid":"sha1","mergeable":"MERGEABLE","mergeStateStatus":"CLEAN",- "commits":{"nodes":[{"commit":{"statusCheckRollup":{"state":"FAILURE","contexts":{- "pageInfo":{"hasNextPage":true,"endCursor":"CUR2"},- "nodes":[- {"__typename":"CheckRun","name":"backend","status":"COMPLETED","conclusion":"FAILURE","detailsUrl":"u1"},- {"__typename":"CheckRun","name":"frontend","status":"COMPLETED","conclusion":"SUCCESS","detailsUrl":"u2"}- ]}}}}]}}}}`- }- // Page 2 (cursor==CUR2): one more context, plus a legacy StatusContext.- return `{"repository":{"pullRequest":{- "headRefOid":"sha1","mergeable":"MERGEABLE","mergeStateStatus":"CLEAN",- "commits":{"nodes":[{"commit":{"statusCheckRollup":{"state":"FAILURE","contexts":{- "pageInfo":{"hasNextPage":false,"endCursor":""},- "nodes":[- {"__typename":"CheckRun","name":"e2e","status":"IN_PROGRESS","conclusion":null,"detailsUrl":"u3"},- {"__typename":"StatusContext","context":"vercel","state":"SUCCESS","targetUrl":"u4"}- ]}}}}]}}}}`- })- defer srv.Close()-- c := newTestClient(t, srv.URL)- snap, err := FetchPRSnapshot(context.Background(), c, 1, "o", "r", 5)- if err != nil {- t.Fatalf("FetchPRSnapshot: %v", err)- }- if snap.HeadSHA != "sha1" || snap.Mergeable != "MERGEABLE" || snap.MergeStateStatus != "CLEAN" {- t.Fatalf("head/merge = %+v", snap)- }- if !snap.HasChecks || snap.RollupState != "FAILURE" {- t.Fatalf("rollup = %q hasChecks=%v", snap.RollupState, snap.HasChecks)- }- if len(snap.Contexts) != 4 {- t.Fatalf("collected %d contexts across pages, want 4", len(snap.Contexts))- }- // StatusContext normalization: SUCCESS → completed/success, is_status_context.- last := snap.Contexts[3]- if last.Name != "vercel" || last.Status != "completed" || last.Conclusion != "success" || !last.IsStatusContext {- t.Fatalf("status context normalized wrong: %+v", last)- }- // In-progress CheckRun stays running.- if snap.Contexts[2].Status != "in_progress" || snap.Contexts[2].Conclusion != "" {- t.Fatalf("in-progress run normalized wrong: %+v", snap.Contexts[2])- }- if snap.Decided() {- t.Fatal("snapshot with an in-progress run must be undecided")- }-}--func TestFetchPRSnapshotRejectsHeadChangeDuringPagination(t *testing.T) {- calls := 0- srv := graphqlServer(t, func(vars map[string]any) string {- calls++- if calls == 1 {- return graphqlSnapshotPage("shaA", true, "CUR2")- }- return graphqlSnapshotPage("shaB", false, "")- })- defer srv.Close()-- c := newTestClient(t, srv.URL)- snap, err := FetchPRSnapshot(context.Background(), c, 1, "o", "r", 5)- if err == nil || !strings.Contains(err.Error(), "head changed during pagination") {- t.Fatalf("FetchPRSnapshot error = %v, want head-change rejection", err)- }- if snap != nil {- t.Fatalf("head-change response returned partial snapshot: %+v", snap)- }- if calls != 2 {- t.Fatalf("GraphQL calls = %d, want 2", calls)- }-}--func TestFetchPRSnapshotRejectsPaginationBeyondLimit(t *testing.T) {- calls := 0- srv := graphqlServer(t, func(vars map[string]any) string {- calls++- return graphqlSnapshotPage("shaA", true, fmt.Sprintf("CUR%d", calls))- })- defer srv.Close()-- c := newTestClient(t, srv.URL)- snap, err := FetchPRSnapshot(context.Background(), c, 1, "o", "r", 5)- if err == nil || !strings.Contains(err.Error(), "pagination exceeds page limit") {- t.Fatalf("FetchPRSnapshot error = %v, want page-limit rejection", err)- }- if snap != nil {- t.Fatalf("page-limit response returned truncated snapshot: %+v", snap)- }- if calls != maxSnapshotContextPages {- t.Fatalf("GraphQL calls = %d, want %d", calls, maxSnapshotContextPages)- }-}--// TestFetchPRSnapshotNullRollup is the acceptance-criterion-5 test: a null-// statusCheckRollup means "no checks yet" (HasChecks=false), never passed.-func TestFetchPRSnapshotNullRollup(t *testing.T) {- srv := graphqlServer(t, func(vars map[string]any) string {- return `{"repository":{"pullRequest":{- "headRefOid":"sha9","mergeable":"UNKNOWN","mergeStateStatus":"UNKNOWN",- "commits":{"nodes":[{"commit":{"statusCheckRollup":null}}]}}}}`- })- defer srv.Close()-- c := newTestClient(t, srv.URL)- snap, err := FetchPRSnapshot(context.Background(), c, 1, "o", "r", 5)- if err != nil {- t.Fatalf("FetchPRSnapshot: %v", err)- }- if snap.HasChecks {- t.Fatal("null rollup must yield HasChecks=false")- }- if snap.RollupState != "" || len(snap.Contexts) != 0 {- t.Fatalf("null rollup must have empty rollup/contexts, got %+v", snap)- }- if snap.Decided() {- t.Fatal("UNKNOWN mergeable must be undecided")- }-}+import "testing"func TestSnapshotDecided(t *testing.T) {cases := []struct {