Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-6048 fix(github): withhold close intent when a PR identifier is ambiguous across workspaces (#6808)

Bohan Jiangb4692a192dd8
diff --git a/server/internal/handler/github.go b/server/internal/handler/github.go
index 75f89e0288..4cfaba2160 100644
--- a/server/internal/handler/github.go
+++ b/server/internal/handler/github.go
@@ -1279,8 +1279,16 @@ func (h *Handler) handlePullRequestEvent(ctx context.Context, body []byte) {
// authorized the installation for; we deliberately don't gate on the
// workspace.repos registry — that list is "code the agent clones", not a
// webhook subscription (MUL-4343).
+ //
+ // Fanning out means an identifier can resolve in more than one workspace at
+ // once (issue prefixes are not globally unique and issue numbers restart at
+ // 1 per workspace, so two bound workspaces can both own a real "ABC-100").
+ // Settle who — if anyone — may act on a closing keyword BEFORE any workspace
+ // links, and treat that verdict as authoritative for the whole delivery, so
+ // the mirror pass cannot re-derive a different answer. See closeIntentPolicy.
+ closePolicy := h.resolveCloseIntentPolicy(ctx, insts, &p)
for _, inst := range insts {
- h.mirrorPullRequestForWorkspace(ctx, inst.WorkspaceID, inst.InstallationID, &p)
+ h.mirrorPullRequestForWorkspace(ctx, inst.WorkspaceID, inst.InstallationID, &p, closePolicy)
}
// The PR row(s) now carry the new head; ask the API pipeline for the
// authoritative CI + mergeability snapshot for that head. The webhook is
@@ -1289,6 +1297,136 @@ func (h *Handler) handlePullRequestEvent(ctx context.Context, body []byte) {
h.PRRefresh.Enqueue(p.Installation.ID, p.Repository.Owner.Login, p.Repository.Name, p.PullRequest.Number)
}
+// closeIntentPolicy decides which (closing identifier, workspace) pairs this
+// delivery is allowed to act on, and is the single authority for that decision:
+// the per-workspace mirror pass consults it instead of re-deriving the answer
+// from its own reads.
+//
+// It is an allowlist, not a denylist, so it fails closed by construction — an
+// identifier we could not positively attribute to exactly one workspace is
+// simply absent, and absence denies. The zero value therefore permits nothing,
+// which is what every indeterminate read returns.
+type closeIntentPolicy struct {
+ // unrestricted marks the single-binding case: cross-workspace ambiguity is
+ // impossible with one bound workspace, so every closing identifier keeps
+ // its pre-#6804 behavior and the scan does no reads at all.
+ unrestricted bool
+ // owner maps a closing identifier to the one workspace proven to resolve
+ // it. Recording the winner (rather than a bare "allowed") also closes the
+ // window between the scan and the mirror pass: if a second workspace grows
+ // a same-numbered issue in between, it is not the recorded owner, so it
+ // still cannot act.
+ owner map[string]string
+}
+
+// permits reports whether workspaceID may carry close intent for identifier.
+func (c closeIntentPolicy) permits(identifier, workspaceID string) bool {
+ if c.unrestricted {
+ return true
+ }
+ owner, ok := c.owner[identifier]
+ return ok && owner == workspaceID
+}
+
+// resolveCloseIntentPolicy determines, before any workspace links, which
+// closing identifiers on this PR may advance an issue and in which workspace.
+//
+// Issue prefixes are deliberately not globally unique (#2797) and issue numbers
+// restart at 1 in every workspace, so once #5183 fanned PR webhooks out to every
+// bound workspace, "Closes ABC-100" could resolve to a genuine — but different —
+// issue in each of them. Linking in both is recoverable noise; auto-advancing
+// both to done is not, because it silently rewrites the status of an issue in a
+// workspace that has nothing to do with this PR (#6804).
+//
+// An identifier is allowed only when exactly one bound workspace was *proven*
+// to resolve it. Anything else — two resolvers, or a read we could not complete
+// — leaves it out, so no workspace acts on it. That asymmetry is deliberate:
+// misjudging "unique" as "ambiguous" costs an auto-complete a human can perform,
+// while misjudging "ambiguous" as "unique" silently closes someone else's issue.
+//
+// Only closing identifiers are examined, and only when the installation has more
+// than one binding, so a PR without a closing keyword — or the overwhelmingly
+// common single-workspace installation — does no extra work.
+func (h *Handler) resolveCloseIntentPolicy(ctx context.Context, insts []db.GithubInstallation, p *ghPullRequestPayload) closeIntentPolicy {
+ if len(insts) < 2 {
+ return closeIntentPolicy{unrestricted: true}
+ }
+ idents := extractClosingIdentifiers(p.PullRequest.Title, p.PullRequest.Body)
+ if len(idents) == 0 {
+ return closeIntentPolicy{}
+ }
+ prNumber := p.PullRequest.Number
+ repo := p.Repository.Owner.Login + "/" + p.Repository.Name
+
+ // Collect every workspace that resolves each identifier. Any read we cannot
+ // complete abandons the whole event: a workspace we failed to inspect might
+ // be a second resolver, and without ruling that out we cannot call any other
+ // workspace the unique one.
+ resolvers := make(map[string][]string, len(idents))
+ for _, inst := range insts {
+ ws, err := h.Queries.GetWorkspace(ctx, inst.WorkspaceID)
+ if err != nil {
+ slog.Warn("github: cannot load bound workspace, withholding close intent for this delivery",
+ "err", err, "installation_id", p.Installation.ID, "repo", repo, "pr_number", prNumber)
+ return closeIntentPolicy{}
+ }
+ // A workspace with auto-link off never writes a link row, so it is not a
+ // competing claimant and must not suppress one that would legitimately
+ // act. A settings blob we cannot parse is not evidence of either, so it
+ // fails closed rather than defaulting to "enabled".
+ autoLink, err := autoLinkPRsEnabledForWorkspace(ws)
+ if err != nil {
+ slog.Warn("github: cannot read workspace auto-link setting, withholding close intent for this delivery",
+ "err", err, "workspace_id", uuidToString(inst.WorkspaceID),
+ "installation_id", p.Installation.ID, "repo", repo, "pr_number", prNumber)
+ return closeIntentPolicy{}
+ }
+ if !autoLink {
+ continue
+ }
+ prefix := issuePrefixForWorkspace(ws)
+ for _, id := range idents {
+ number, ok := issueNumberForPrefix(id, prefix)
+ if !ok {
+ continue
+ }
+ if _, err := h.Queries.GetIssueByNumber(ctx, db.GetIssueByNumberParams{
+ WorkspaceID: inst.WorkspaceID,
+ Number: number,
+ }); err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ // Proven miss: this workspace has no such issue.
+ continue
+ }
+ slog.Warn("github: cannot resolve identifier in bound workspace, withholding close intent for this delivery",
+ "err", err, "identifier", id, "workspace_id", uuidToString(inst.WorkspaceID),
+ "installation_id", p.Installation.ID, "repo", repo, "pr_number", prNumber)
+ return closeIntentPolicy{}
+ }
+ resolvers[id] = append(resolvers[id], uuidToString(inst.WorkspaceID))
+ }
+ }
+
+ policy := closeIntentPolicy{owner: make(map[string]string, len(resolvers))}
+ for id, wss := range resolvers {
+ if len(wss) == 1 {
+ policy.owner[id] = wss[0]
+ continue
+ }
+ // The symptom this prevents (an issue advancing to done for no visible
+ // reason) is otherwise untraceable back to GitHub, so leave a breadcrumb
+ // naming the collision an operator has to resolve by changing a prefix.
+ slog.Warn("github: ambiguous closing identifier across bound workspaces, withholding close intent",
+ "identifier", id,
+ "workspaces", len(wss),
+ "installation_id", p.Installation.ID,
+ "repo", repo,
+ "pr_number", prNumber,
+ )
+ }
+ return policy
+}
+
// ghCIEventPayload captures the shared shape of the check_suite / check_run /
// status webhooks — enough to resolve which PR to refresh. These events are
// pure triggers under Plan C: their payload data is never read for display.
@@ -1386,7 +1524,13 @@ func (h *Handler) triggerPRRefreshFromCIEvent(ctx context.Context, body []byte)
// the workspace's github toggles), advances issues on terminal events, and
// broadcasts the change. Invoked once per workspace bound to the delivering
// installation.
-func (h *Handler) mirrorPullRequestForWorkspace(ctx context.Context, wsID pgtype.UUID, installationID int64, p *ghPullRequestPayload) {
+//
+// closePolicy is the delivery-wide verdict on which closing identifiers this
+// workspace may act on; identifiers it does not permit still link, but never
+// carry close_intent, so they can never advance an issue to done. This function
+// only ever narrows that verdict — it cannot grant close intent the policy
+// withheld.
+func (h *Handler) mirrorPullRequestForWorkspace(ctx context.Context, wsID pgtype.UUID, installationID int64, p *ghPullRequestPayload, closePolicy closeIntentPolicy) {
state := derivePRState(p.PullRequest.State, p.PullRequest.Draft, p.PullRequest.Merged)
mergeable, clearMergeable := derivePRMergeableState(p.Action, p.PullRequest.MergeableState, baseRefChanged(p.Changes))
pr, err := h.Queries.UpsertGitHubPullRequest(ctx, db.UpsertGitHubPullRequestParams{
@@ -1481,6 +1625,14 @@ func (h *Handler) mirrorPullRequestForWorkspace(ctx context.Context, wsID pgtype
continue
}
_, declared := closingIdents[id]
+ if declared && !closePolicy.permits(id, workspaceID) {
+ // The delivery-wide scan did not prove this workspace is the one
+ // this closing keyword refers to, so it does not act on it.
+ // Falling through with declared=false also clears close_intent
+ // on a row a pre-#6804 delivery had already set, so a re-fired
+ // webhook heals the stored decision.
+ declared = false
+ }
closeIntent := declared && !preserveCloseIntent
_, qualifies := qualifyingIdents[id]
referenceOnly := !qualifies
@@ -1662,51 +1814,76 @@ func extractClosingIdentifiers(parts ...string) []string {
return out
}
-// lookupIssueByIdentifier looks up an issue in the given workspace by its
-// "PREFIX-NUMBER" identifier. Returns the row + true if the prefix matches
-// workspaceAutoLinkPRsEnabled reports whether the workspace allows the
+// autoLinkPRsEnabledForWorkspace reports whether the workspace allows the
// GitHub webhook to create issue ↔ PR link rows. Defaults to true so that
// workspaces predating RFC MUL-2414 keep the historical "auto-link on"
// behavior, and short-circuits to false whenever the master GitHub switch
// is explicitly off — mirroring the precedence used on the client side.
-func (h *Handler) workspaceAutoLinkPRsEnabled(ctx context.Context, workspaceID pgtype.UUID) bool {
- ws, err := h.Queries.GetWorkspace(ctx, workspaceID)
- if err != nil || len(ws.Settings) == 0 {
- return true
+//
+// An unparseable settings blob is surfaced as an error instead of being folded
+// into the permissive default. Callers deciding whether to write a link row
+// keep taking the default, but the close-intent scan has to tell "auto-link is
+// on" apart from "we could not find out" — see closeIntentPolicy.
+func autoLinkPRsEnabledForWorkspace(ws db.Workspace) (bool, error) {
+ if len(ws.Settings) == 0 {
+ return true, nil
}
var s struct {
GitHubEnabled *bool `json:"github_enabled"`
GitHubAutoLinkPRsEnabled *bool `json:"github_auto_link_prs_enabled"`
}
if err := json.Unmarshal(ws.Settings, &s); err != nil {
- return true
+ return true, err
}
if s.GitHubEnabled != nil && !*s.GitHubEnabled {
- return false
+ return false, nil
}
if s.GitHubAutoLinkPRsEnabled == nil {
+ return true, nil
+ }
+ return *s.GitHubAutoLinkPRsEnabled, nil
+}
+
+func (h *Handler) workspaceAutoLinkPRsEnabled(ctx context.Context, workspaceID pgtype.UUID) bool {
+ ws, err := h.Queries.GetWorkspace(ctx, workspaceID)
+ if err != nil {
return true
}
- return *s.GitHubAutoLinkPRsEnabled
+ enabled, _ := autoLinkPRsEnabledForWorkspace(ws)
+ return enabled
}
-// the workspace's configured prefix and the number resolves to a real issue.
-func (h *Handler) lookupIssueByIdentifier(ctx context.Context, workspaceID pgtype.UUID, prefix, identifier string) (db.Issue, bool) {
+// issueNumberForPrefix returns the issue number encoded in a "PREFIX-NUMBER"
+// identifier, and false when the identifier is malformed or carries a prefix
+// that is not the workspace's. Case-insensitive: branch names are
+// conventionally lowercase while issue prefixes are uppercase.
+func issueNumberForPrefix(identifier, prefix string) (int32, bool) {
idx := strings.LastIndex(identifier, "-")
if idx < 0 {
- return db.Issue{}, false
+ return 0, false
}
gotPrefix, numStr := identifier[:idx], identifier[idx+1:]
if !strings.EqualFold(gotPrefix, prefix) {
- return db.Issue{}, false
+ return 0, false
}
n, err := strconv.Atoi(numStr)
if err != nil {
+ return 0, false
+ }
+ return int32(n), true
+}
+
+// lookupIssueByIdentifier looks up an issue in the given workspace by its
+// "PREFIX-NUMBER" identifier. Returns the row + true if the prefix matches
+// the workspace's configured prefix and the number resolves to a real issue.
+func (h *Handler) lookupIssueByIdentifier(ctx context.Context, workspaceID pgtype.UUID, prefix, identifier string) (db.Issue, bool) {
+ number, ok := issueNumberForPrefix(identifier, prefix)
+ if !ok {
return db.Issue{}, false
}
issue, err := h.Queries.GetIssueByNumber(ctx, db.GetIssueByNumberParams{
WorkspaceID: workspaceID,
- Number: int32(n),
+ Number: number,
})
if err != nil {
return db.Issue{}, false
diff --git a/server/internal/handler/github_test.go b/server/internal/handler/github_test.go
index 2a5ada35dd..1ca9c09c10 100644
--- a/server/internal/handler/github_test.go
+++ b/server/internal/handler/github_test.go
@@ -2893,6 +2893,346 @@ func TestWebhook_PullRequest_FansOutToBoundWorkspaces(t *testing.T) {
}
}
+// TestWebhook_PullRequest_AmbiguousCloseAcrossWorkspaces is the #6804
+// regression. Two workspaces bound to the same installation share an issue
+// prefix (permitted by #2797) and both own a real issue at the same number
+// (issue numbers restart at 1 per workspace), so a PR titled "Fix AMB-<n>"
+// resolves in BOTH after the #5183 fan-out. The PR must still link in both —
+// the link is visible and a human can unlink it — but neither issue may be
+// auto-advanced to done, because nothing in the event says which workspace the
+// PR belongs to. Before the fix, the workspace that had nothing to do with the
+// PR was silently moved to done.
+func TestWebhook_PullRequest_AmbiguousCloseAcrossWorkspaces(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("handler test fixture not initialized (no DB?)")
+ }
+ ctx := context.Background()
+ secret := "ambiguous-close-secret"
+ t.Setenv("GITHUB_WEBHOOK_SECRET", secret)
+
+ // Both workspaces answer to "AMB" — the collision #2797 allows.
+ setWorkspaceIssuePrefixForTest(t, "AMB")
+
+ // Workspace B is the shared test workspace and owns the issue the PR is
+ // really for.
+ w := httptest.NewRecorder()
+ testHandler.CreateIssue(w, newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{
+ "title": "ambiguous close test",
+ "status": "in_progress",
+ }))
+ if w.Code != http.StatusCreated {
+ t.Fatalf("CreateIssue: %d %s", w.Code, w.Body.String())
+ }
+ var issueB IssueResponse
+ json.NewDecoder(w.Body).Decode(&issueB)
+
+ const repo = "ambiguous-close-repo"
+ const prNumber int32 = 6804
+ const installationID int64 = 660480000
+
+ testPool.Exec(ctx, `DELETE FROM github_installation WHERE installation_id = $1`, installationID)
+ testPool.Exec(ctx, `DELETE FROM workspace WHERE slug = $1`, "ambiguous-close-ws-a")
+ wsA, err := testHandler.Queries.CreateWorkspace(ctx, db.CreateWorkspaceParams{
+ Name: "ambiguous-close-ws-a", Slug: "ambiguous-close-ws-a", IssuePrefix: "AMB",
+ })
+ if err != nil {
+ t.Fatalf("CreateWorkspace: %v", err)
+ }
+ // Workspace A's own issue at the SAME number. `number` is an explicit
+ // column, so we can place the collision directly instead of pumping the
+ // workspace's issue counter up to B's.
+ issueA, err := testHandler.Queries.CreateIssue(ctx, db.CreateIssueParams{
+ WorkspaceID: wsA.ID,
+ Title: "unrelated issue that happens to share a number",
+ Status: "in_progress",
+ Priority: "none",
+ CreatorType: "member",
+ CreatorID: parseUUID(testUserID),
+ Number: issueB.Number,
+ })
+ if err != nil {
+ t.Fatalf("CreateIssue in workspace A: %v", err)
+ }
+
+ for _, wsID := range []pgtype.UUID{parseUUID(testWorkspaceID), wsA.ID} {
+ if _, err := testHandler.Queries.CreateGitHubInstallation(ctx, db.CreateGitHubInstallationParams{
+ WorkspaceID: wsID, InstallationID: installationID, AccountLogin: "acme", AccountType: "User",
+ }); err != nil {
+ t.Fatalf("CreateGitHubInstallation: %v", err)
+ }
+ }
+
+ t.Cleanup(func() {
+ bg := context.Background()
+ testPool.Exec(bg, `DELETE FROM issue_pull_request WHERE issue_id = ANY($1)`,
+ []string{issueB.ID, uuidToString(issueA.ID)})
+ testPool.Exec(bg, `DELETE FROM github_pull_request WHERE repo_owner = 'acme' AND repo_name = $1`, repo)
+ testPool.Exec(bg, `DELETE FROM github_installation WHERE installation_id = $1`, installationID)
+ testPool.Exec(bg, `DELETE FROM activity_log WHERE issue_id = ANY($1)`,
+ []string{issueB.ID, uuidToString(issueA.ID)})
+ testPool.Exec(bg, `DELETE FROM issue WHERE id = ANY($1)`,
+ []string{issueB.ID, uuidToString(issueA.ID)})
+ testPool.Exec(bg, `DELETE FROM workspace WHERE id = $1`, wsA.ID)
+ })
+
+ // firePullRequestWebhook titles the PR "Fix <identifier>", which is a
+ // closing keyword under closingIdentifierRe — exactly the payload that
+ // used to auto-advance both issues.
+ firePullRequestWebhook(t, secret, issueB.Identifier, installationID, repo, prNumber, "open")
+ firePullRequestWebhook(t, secret, issueB.Identifier, installationID, repo, prNumber, "merged")
+
+ // The link still lands in both workspaces: suppressing the link would hide
+ // the collision, and hiding it is what made #6804 hard to notice.
+ for _, tc := range []struct {
+ name string
+ issueID pgtype.UUID
+ }{
+ {"workspace B (owns the PR)", parseUUID(issueB.ID)},
+ {"workspace A (collision)", issueA.ID},
+ } {
+ linked, err := testHandler.Queries.ListPullRequestsByIssue(ctx, tc.issueID)
+ if err != nil {
+ t.Fatalf("%s: ListPullRequestsByIssue: %v", tc.name, err)
+ }
+ if len(linked) != 1 {
+ t.Fatalf("%s: expected the PR to still link, got %d links", tc.name, len(linked))
+ }
+
+ var closeIntent bool
+ if err := testPool.QueryRow(ctx,
+ `SELECT close_intent FROM issue_pull_request WHERE issue_id = $1`, tc.issueID,
+ ).Scan(&closeIntent); err != nil {
+ t.Fatalf("%s: read close_intent: %v", tc.name, err)
+ }
+ if closeIntent {
+ t.Errorf("%s: close_intent must be withheld while the identifier is ambiguous", tc.name)
+ }
+
+ issue, err := testHandler.Queries.GetIssue(ctx, tc.issueID)
+ if err != nil {
+ t.Fatalf("%s: GetIssue: %v", tc.name, err)
+ }
+ if issue.Status == "done" {
+ t.Errorf("%s: issue was auto-advanced to done on an ambiguous close (#6804)", tc.name)
+ }
+ }
+}
+
+// TestCloseIntentPolicyPermits pins the fail-closed invariant at the type
+// level: the policy is an allowlist, so anything it was not able to prove is
+// denied. The zero value is what every indeterminate read in
+// resolveCloseIntentPolicy returns, and it must permit nothing.
+func TestCloseIntentPolicyPermits(t *testing.T) {
+ const wsA, wsB = "workspace-a", "workspace-b"
+
+ for _, tc := range []struct {
+ name string
+ policy closeIntentPolicy
+ ws string
+ want bool
+ }{
+ {
+ name: "zero value denies (what an indeterminate read returns)",
+ policy: closeIntentPolicy{},
+ ws: wsA,
+ want: false,
+ },
+ {
+ name: "single-binding delivery is unrestricted",
+ policy: closeIntentPolicy{unrestricted: true},
+ ws: wsA,
+ want: true,
+ },
+ {
+ name: "recorded owner may act",
+ policy: closeIntentPolicy{owner: map[string]string{"ABC-100": wsA}},
+ ws: wsA,
+ want: true,
+ },
+ {
+ // A workspace that grew a same-numbered issue after the scan is not
+ // the recorded owner, so it still cannot act.
+ name: "workspace that is not the recorded owner may not act",
+ policy: closeIntentPolicy{owner: map[string]string{"ABC-100": wsA}},
+ ws: wsB,
+ want: false,
+ },
+ {
+ name: "identifier absent from the allowlist is denied",
+ policy: closeIntentPolicy{owner: map[string]string{"ABC-1": wsA}},
+ ws: wsA,
+ want: false,
+ },
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := tc.policy.permits("ABC-100", tc.ws); got != tc.want {
+ t.Errorf("permits(ABC-100, %s) = %v, want %v", tc.ws, got, tc.want)
+ }
+ })
+ }
+}
+
+// TestWebhook_PullRequest_UniqueResolverAmongBindingsStillAutoCompletes is the
+// other half of the #6804 fix: withholding close intent must be scoped to the
+// identifiers we could not attribute. Two workspaces share an installation and
+// a prefix, but only one of them actually has an issue at that number — that is
+// a proven unique owner, so auto-complete must still fire for it.
+func TestWebhook_PullRequest_UniqueResolverAmongBindingsStillAutoCompletes(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("handler test fixture not initialized (no DB?)")
+ }
+ ctx := context.Background()
+ secret := "unique-resolver-secret"
+ t.Setenv("GITHUB_WEBHOOK_SECRET", secret)
+ setWorkspaceIssuePrefixForTest(t, "UNQ")
+
+ w := httptest.NewRecorder()
+ testHandler.CreateIssue(w, newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{
+ "title": "unique resolver test",
+ "status": "in_progress",
+ }))
+ if w.Code != http.StatusCreated {
+ t.Fatalf("CreateIssue: %d %s", w.Code, w.Body.String())
+ }
+ var issueB IssueResponse
+ json.NewDecoder(w.Body).Decode(&issueB)
+
+ const repo = "unique-resolver-repo"
+ const prNumber int32 = 6809
+ const installationID int64 = 660480001
+
+ // Workspace A shares the prefix but has no issue at all, so it can never be
+ // a second resolver.
+ bindSecondWorkspaceForTest(t, "unique-resolver-ws-a", "UNQ", installationID)
+ if _, err := testHandler.Queries.CreateGitHubInstallation(ctx, db.CreateGitHubInstallationParams{
+ WorkspaceID: parseUUID(testWorkspaceID), InstallationID: installationID, AccountLogin: "acme", AccountType: "User",
+ }); err != nil {
+ t.Fatalf("CreateGitHubInstallation B: %v", err)
+ }
+
+ t.Cleanup(func() {
+ bg := context.Background()
+ testPool.Exec(bg, `DELETE FROM issue_pull_request WHERE issue_id = $1`, issueB.ID)
+ testPool.Exec(bg, `DELETE FROM github_pull_request WHERE repo_owner = 'acme' AND repo_name = $1`, repo)
+ testPool.Exec(bg, `DELETE FROM activity_log WHERE issue_id = $1`, issueB.ID)
+ testPool.Exec(bg, `DELETE FROM issue WHERE id = $1`, issueB.ID)
+ })
+
+ firePullRequestWebhook(t, secret, issueB.Identifier, installationID, repo, prNumber, "open")
+ firePullRequestWebhook(t, secret, issueB.Identifier, installationID, repo, prNumber, "merged")
+
+ issue, err := testHandler.Queries.GetIssue(ctx, parseUUID(issueB.ID))
+ if err != nil {
+ t.Fatalf("GetIssue: %v", err)
+ }
+ if issue.Status != "done" {
+ t.Errorf("issue status = %q, want done — a proven unique resolver must keep auto-complete", issue.Status)
+ }
+}
+
+// TestWebhook_PullRequest_UnreadableWorkspaceWithholdsCloseIntent covers the
+// fail-closed half of resolveCloseIntentPolicy. The setup is identical to the
+// unique-resolver test above — one real resolver, which would auto-complete —
+// except that a bound workspace's settings cannot be parsed. That workspace
+// might or might not be a second resolver, and since we cannot rule it out, no
+// workspace may act: a transient read failure must never be able to promote an
+// ambiguous identifier back into an auto-complete.
+func TestWebhook_PullRequest_UnreadableWorkspaceWithholdsCloseIntent(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("handler test fixture not initialized (no DB?)")
+ }
+ ctx := context.Background()
+ secret := "unreadable-ws-secret"
+ t.Setenv("GITHUB_WEBHOOK_SECRET", secret)
+ setWorkspaceIssuePrefixForTest(t, "UNR")
+
+ w := httptest.NewRecorder()
+ testHandler.CreateIssue(w, newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{
+ "title": "unreadable workspace test",
+ "status": "in_progress",
+ }))
+ if w.Code != http.StatusCreated {
+ t.Fatalf("CreateIssue: %d %s", w.Code, w.Body.String())
+ }
+ var issueB IssueResponse
+ json.NewDecoder(w.Body).Decode(&issueB)
+
+ const repo = "unreadable-ws-repo"
+ const prNumber int32 = 6810
+ const installationID int64 = 660480002
+
+ wsA := bindSecondWorkspaceForTest(t, "unreadable-ws-a", "UNR", installationID)
+ if _, err := testHandler.Queries.CreateGitHubInstallation(ctx, db.CreateGitHubInstallationParams{
+ WorkspaceID: parseUUID(testWorkspaceID), InstallationID: installationID, AccountLogin: "acme", AccountType: "User",
+ }); err != nil {
+ t.Fatalf("CreateGitHubInstallation B: %v", err)
+ }
+ // Valid JSONB, but the auto-link flag is not a bool — the settings blob
+ // parses in Postgres and fails in the handler, which is exactly the
+ // "we could not find out" case.
+ if _, err := testPool.Exec(ctx,
+ `UPDATE workspace SET settings = '{"github_auto_link_prs_enabled": 5}'::jsonb WHERE id = $1`, wsA,
+ ); err != nil {
+ t.Fatalf("corrupt workspace settings: %v", err)
+ }
+
+ t.Cleanup(func() {
+ bg := context.Background()
+ testPool.Exec(bg, `DELETE FROM issue_pull_request WHERE issue_id = $1`, issueB.ID)
+ testPool.Exec(bg, `DELETE FROM github_pull_request WHERE repo_owner = 'acme' AND repo_name = $1`, repo)
+ testPool.Exec(bg, `DELETE FROM activity_log WHERE issue_id = $1`, issueB.ID)
+ testPool.Exec(bg, `DELETE FROM issue WHERE id = $1`, issueB.ID)
+ })
+
+ firePullRequestWebhook(t, secret, issueB.Identifier, installationID, repo, prNumber, "open")
+ firePullRequestWebhook(t, secret, issueB.Identifier, installationID, repo, prNumber, "merged")
+
+ var closeIntent bool
+ if err := testPool.QueryRow(ctx,
+ `SELECT close_intent FROM issue_pull_request WHERE issue_id = $1`, parseUUID(issueB.ID),
+ ).Scan(&closeIntent); err != nil {
+ t.Fatalf("read close_intent: %v", err)
+ }
+ if closeIntent {
+ t.Error("close_intent must be withheld when a bound workspace could not be inspected")
+ }
+
+ issue, err := testHandler.Queries.GetIssue(ctx, parseUUID(issueB.ID))
+ if err != nil {
+ t.Fatalf("GetIssue: %v", err)
+ }
+ if issue.Status == "done" {
+ t.Error("issue was auto-advanced despite an unreadable bound workspace — the scan failed open")
+ }
+}
+
+// bindSecondWorkspaceForTest creates a throwaway workspace with the given issue
+// prefix, binds it to installationID, and registers cleanup for both. Returns
+// the new workspace id.
+func bindSecondWorkspaceForTest(t *testing.T, slug, prefix string, installationID int64) pgtype.UUID {
+ t.Helper()
+ ctx := context.Background()
+ testPool.Exec(ctx, `DELETE FROM github_installation WHERE installation_id = $1`, installationID)
+ testPool.Exec(ctx, `DELETE FROM workspace WHERE slug = $1`, slug)
+ ws, err := testHandler.Queries.CreateWorkspace(ctx, db.CreateWorkspaceParams{
+ Name: slug, Slug: slug, IssuePrefix: prefix,
+ })
+ if err != nil {
+ t.Fatalf("CreateWorkspace %s: %v", slug, err)
+ }
+ if _, err := testHandler.Queries.CreateGitHubInstallation(ctx, db.CreateGitHubInstallationParams{
+ WorkspaceID: ws.ID, InstallationID: installationID, AccountLogin: "acme", AccountType: "User",
+ }); err != nil {
+ t.Fatalf("CreateGitHubInstallation %s: %v", slug, err)
+ }
+ t.Cleanup(func() {
+ bg := context.Background()
+ testPool.Exec(bg, `DELETE FROM github_installation WHERE installation_id = $1`, installationID)
+ testPool.Exec(bg, `DELETE FROM workspace WHERE id = $1`, ws.ID)
+ })
+ return ws.ID
+}
+
// TestSecondWorkspaceBindDoesNotUnbindFirst is the #4823 regression: binding
// the same GitHub App installation in a second workspace must NOT overwrite the
// first workspace's binding. Both bindings coexist, and re-binding an existing
diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.go
index be6936c1ea..bfbefdaef7 100644
--- a/server/internal/handler/handler.go
+++ b/server/internal/handler/handler.go
@@ -986,18 +986,27 @@ func splitIdentifier(id string) *identifierParts {
return &identifierParts{prefix: id[:idx], number: int32(num)}
}
-// getIssuePrefix fetches the issue_prefix for a workspace.
-// Falls back to generating a prefix from the workspace name if the stored
-// prefix is empty (e.g. workspaces created before the prefix was introduced).
+// issuePrefixForWorkspace resolves a workspace row's effective issue prefix:
+// the configured value, or one generated from the workspace name when the
+// stored prefix is empty (e.g. workspaces created before the prefix was
+// introduced). Split out from getIssuePrefix so callers that already hold the
+// row — such as the GitHub close-intent scan, which must not re-read it — can
+// reuse the rule.
+func issuePrefixForWorkspace(ws db.Workspace) string {
+ if ws.IssuePrefix != "" {
+ return ws.IssuePrefix
+ }
+ return generateIssuePrefix(ws.Name)
+}
+
+// getIssuePrefix fetches the effective issue_prefix for a workspace, and
+// returns "" when the workspace row cannot be loaded.
func (h *Handler) getIssuePrefix(ctx context.Context, workspaceID pgtype.UUID) string {
ws, err := h.Queries.GetWorkspace(ctx, workspaceID)
if err != nil {
return ""
}
- if ws.IssuePrefix != "" {
- return ws.IssuePrefix
- }
- return generateIssuePrefix(ws.Name)
+ return issuePrefixForWorkspace(ws)
}
func (h *Handler) loadAgentForUser(w http.ResponseWriter, r *http.Request, agentID string) (db.Agent, bool) {