Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-7429: complete issues when every linked PR merges (#8758)
Jiayuan Zhang9df0cae78a86
diff --git a/apps/docs/content/docs/github-integration.ja.mdx b/apps/docs/content/docs/github-integration.ja.mdxindex 89ca19b51b..7d24cef664 100644--- a/apps/docs/content/docs/github-integration.ja.mdx+++ b/apps/docs/content/docs/github-integration.ja.mdx@@ -36,7 +36,7 @@ GitHub 連携が読み取るのは、インストール時に許可されたリ| GitHub 連携 | メインスイッチ。無効にすると下の 3 項目は機能しなくなりますが、GitHub App の接続は解除されません。 || PR サイドバー | 紐づいた pull request をタスクの詳細画面に表示します。 || Co-authored-by | エージェントが作成する commit に `Co-authored-by: multica-agent <[email protected]>` を追加します。 |-| PR の自動紐づけ | PR のブランチ名とタイトルからタスク番号を検出します。本文では closing keyword の直後にある番号だけを検出します。 |+| PR の自動紐づけ | ブランチ名かタイトルにタスク番号を含む PR を、そのタスクに紐づけます。 || **PR カード → CI とマージ可否** | 紐づいた各 PR について、Multica は認証済みの GitHub API スナップショットを取得し、その **CI ステータス**と**マージ可否**をカードにミラーリングします(下記の **PR カードに表示される内容** を参照)。 |@@ -54,15 +54,9 @@ MUL-123 ログイン後のリダイレクトを修正Multica は大文字と小文字を区別せず、現在のワークスペースのタスク接頭辞だけを照合します。1 つの PR を複数のタスクに紐づけることもできます。-タスク番号を PR 本文だけに書く場合は、GitHub の closing keyword を必ず使ってください。+Multica は PR 本文を読み取らず、キーワードにも特別な意味はありません。本文に `Closes MUL-123` や `Related to MUL-123` と書いても紐づきません。Commit message と PR コメントも紐づけの対象外です。-```text-Closes MUL-123-Fixes MUL-123-Resolves MUL-123-```--本文に `Related to MUL-123` のような通常の参照を書いただけでは、そのタスクへまったく紐づきません。Commit message と PR コメントも紐づけの対象外です。+手動で紐づけることもできます。タスクの **Pull requests** セクションで **+** をクリックし、PR の URL を貼り付けます。PR をタスクから外すには、その行の **⋯** メニューから **タスクから外す** を選びます。以後、Multica がタイトルやブランチから再び紐づけることはありません。## タスクから PR を確認する@@ -76,19 +70,20 @@ Resolves MUL-123CI の状態とマージ可能性は、Multica が GitHub API から取得したスナップショットで、互いに独立しています。マージ済みまたはクローズ済みの PR では、この 2 項目を表示しません。GitHub が一時的に利用できない場合、カードを空にせず、前回のスナップショットを古い情報として表示します。+リストの下には、次に何が起きるかを 1 行で表示します。たとえば「#19 がマージされると自動完了」や、マージされずにクローズされた PR です。+項目をクリックすると GitHub の PR が開きます。**PR サイドバー**を無効にしてもこのセクションが非表示になるだけで、接続は解除されません。## PR のマージで Done になる条件-PR がマージされても、必ずしもタスクが完了するわけではありません。Multica がタスクを `Done` に変更するのは、次の条件をすべて満たす場合だけです。+**PR のマージでタスクを自動完了**(**設定 → タスクステータス → 自動化**、既定でオン)が有効な場合、タスクに紐づくすべての PR がマージされると、タスクは `Done` になります。-1. 紐づいたマージ済み PR のうち少なくとも 1 つで、`Closes MUL-123` のように closing keyword の直後にタスク番号を指定している。`Closes login MUL-123` のように間に別の単語がある形式は無効です。-2. そのタスクに、`Open` または `Draft` の紐づいた PR がほかに残っていない。-3. タスクの現在の状態が `done` または `cancelled` ではない。+1. タスクに紐づく PR が 1 つ以上あり、すべてが `Merged` である。`Open` や `Draft` の PR が残っているとタスクは待機を続けます。マージされずにクローズされた PR も、タスクから外すまで同様です。+2. タスクが `done` または `cancelled` ではなく、そのタスクだけ自動完了をオフにしていない(**Pull requests → ⋯ → このタスクは自動完了しない**)。マージ後にレビューやリリースが必要な作業向けです。-そのため、ブランチ名やタイトルに `MUL-123` を含めるだけで紐づけは作成されますが、それだけではタスクを完了にしません。PR をマージせずにクローズした場合も、タスクは完了しません。+判定は PR イベントがタスクに関わったときだけ行います。紐づいた PR のマージ、紐づけの追加、紐づけの解除です。タスクを再度開いても `Done` には戻らず、次に紐づいた PR がマージされたときに完了します。設定をオンにしても、以前にマージされたタスクをさかのぼって完了にはしません。-状態の変更はシステム操作としてタイムラインに記録され、そのタスクを購読しているメンバーへ通知されます。+状態の変更は関連する PR を示したシステム操作としてタイムラインに記録され、そのタスクを購読しているメンバーへ通知されます。この設定は[セルフホスト Git ホスティング](/vcs-integration)を含むすべてのコードホストで共通です。## 複数のワークスペース@@ -96,6 +91,8 @@ PR がマージされても、必ずしもタスクが完了するわけではたとえば、1 つの PR が `MUL-1` と `ENG-2` の両方を参照している場合、異なる接頭辞を持つ 2 つのワークスペースでそれぞれ紐づけられます。ワークスペース間で相手のタスクが見えることはありません。+同じ番号が接続中の複数のワークスペースでタスクに一致する場合(接頭辞が同じときに起こり得ます)、Multica はどのワークスペースでも自動では紐づけません。関係のないタスクがマージで完了しないようにするためです。正しいワークスペースで手動で紐づけてください。+## 接続を解除する**設定 → GitHub** の**接続解除**をクリックすると、現在の Multica ワークスペースと installation の関係だけが削除されます。GitHub から App がアンインストールされることはありません。既存の PR 記録は保持されますが、新しいイベントはこのワークスペースに届かなくなります。@@ -174,10 +171,10 @@ API サービスを再起動し、**設定 → GitHub** から接続します。- **接続ボタンを使用できない**: `GITHUB_APP_SLUG` と `GITHUB_WEBHOOK_SECRET` が API プロセスに設定されていることを確認します。- **Webhook が 401 を返す**: GitHub App と API が同じ Webhook secret を使っていることを確認し、GitHub の **Recent Deliveries** から再配信します。-- **PR が紐づかない**: リポジトリが App の許可範囲にあること、PR の自動紐づけが有効であること、番号が現在のワークスペースのものかを確認します。-- **本文に番号を書いても紐づかない**: `Closes MUL-123` を使うか、番号をブランチ名または PR タイトルに入れます。+- **PR が紐づかない**: リポジトリが App の許可範囲にあること、PR の自動紐づけが有効であること、番号が現在のワークスペースのものであること、誰かがタスクから外していないかを確認します。+- **番号を本文にだけ書いている**: 番号をブランチ名または PR タイトルに入れるか、手動で紐づけます。- **CI の状態がない**: `GITHUB_APP_ID` と `GITHUB_APP_PRIVATE_KEY` が設定済みで、App に Contents、Checks、Commit statuses の read-only 権限があり、関連イベントを購読していることを確認します。Contents が欠けるとスナップショット全体が失敗し、PR カードには CI もマージ状態も表示されません。インストール済み App に権限を追加した場合は、各 installation の所有者が GitHub 上で承認するまで有効になりません。-- **PR のマージ後もタスクが完了しない**: PR で closing keyword を使っていることと、`Open` または `Draft` の関連 PR がほかに残っていないことを確認します。+- **PR のマージ後もタスクが完了しない**: タスクの **Pull requests** リストの下にある説明を確認します。まだマージされていない PR やマージされずにクローズされた PR、またはタスクやワークスペースで自動完了がオフになっていることが表示されます。## 次のステップdiff --git a/apps/docs/content/docs/github-integration.ko.mdx b/apps/docs/content/docs/github-integration.ko.mdxindex f8b34e8c4c..037d0a3af2 100644--- a/apps/docs/content/docs/github-integration.ko.mdx+++ b/apps/docs/content/docs/github-integration.ko.mdx@@ -36,7 +36,7 @@ GitHub 연동은 설치할 때 승인한 저장소만 읽으며 코드, 댓글,| GitHub 연동 | 전체 스위치입니다. 끄면 아래 세 기능이 작동하지 않지만 GitHub App 연결은 해제되지 않습니다. || PR 사이드바 | 태스크 상세 화면에 연결된 pull request를 표시합니다. || Co-authored-by | 에이전트가 만든 commit에 `Co-authored-by: multica-agent <[email protected]>`를 추가합니다. |-| PR 자동 연결 | PR의 브랜치 이름과 제목에서 태스크 번호를 찾고, 본문에서는 종료 문구 바로 뒤에 있는 번호만 찾습니다. |+| PR 자동 연결 | 브랜치 이름이나 제목에 태스크 번호가 있는 PR을 해당 태스크에 연결합니다. || **PR 카드 → CI와 머지 가능 여부** | 연결된 각 PR에 대해 Multica는 인증된 GitHub API 스냅샷을 가져와, 그 **CI 상태**와 **머지 가능 여부**를 카드에 미러링합니다(아래 **PR 카드에 표시되는 것** 참조). |@@ -54,15 +54,9 @@ MUL-123 로그인 후 리디렉션 수정Multica는 대소문자를 구분하지 않으며 현재 워크스페이스의 태스크 접두사만 매칭합니다. 하나의 PR을 여러 태스크에 연결할 수 있습니다.-태스크 번호를 PR 본문에만 쓸 때는 GitHub의 종료 문구를 사용해야 합니다.+Multica는 PR 본문을 읽지 않으며 키워드에도 특별한 의미가 없습니다. 본문에 `Closes MUL-123`이나 `Related to MUL-123`을 써도 연결되지 않습니다. Commit message와 PR 댓글도 연결을 트리거하지 않습니다.-```text-Closes MUL-123-Fixes MUL-123-Resolves MUL-123-```--본문의 `Related to MUL-123` 같은 일반 언급은 해당 태스크에 전혀 연결되지 않습니다. Commit message와 PR 댓글도 연결을 트리거하지 않습니다.+직접 연결할 수도 있습니다. 태스크의 **Pull requests** 영역에서 **+**를 누르고 PR URL을 붙여넣습니다. PR을 태스크에서 빼려면 해당 행의 **⋯** 메뉴에서 **태스크에서 제거**를 선택합니다. 이후 Multica는 제목이나 브랜치를 보고 다시 연결하지 않습니다.## 태스크에서 PR 확인@@ -76,19 +70,20 @@ Resolves MUL-123CI 상태와 merge 가능 여부는 Multica가 GitHub API에서 가져온 snapshot이며 서로 독립적입니다. 이미 merge되거나 닫힌 PR에는 두 항목을 더 이상 표시하지 않습니다. GitHub를 일시적으로 사용할 수 없으면 카드가 비워지는 대신 마지막 snapshot을 유지하고 만료된 정보라고 표시합니다.+목록 아래에는 다음에 일어날 일을 한 줄로 보여 줍니다. 예를 들어 "#19 병합 시 자동 완료"나 병합되지 않고 닫힌 PR입니다.+항목을 클릭하면 GitHub의 PR이 열립니다. **PR 사이드바**를 꺼도 이 영역만 숨겨질 뿐 연결은 해제되지 않습니다.## PR merge 시 Done 전환 조건-PR이 merge되었다고 태스크가 반드시 완료된 것은 아닙니다. Multica는 다음 조건이 모두 충족될 때만 태스크를 `Done`으로 바꿉니다.+**PR 병합 시 태스크 자동 완료**(**설정 → 태스크 상태 → 자동화**, 기본값 켜짐)가 켜져 있으면 태스크에 연결된 PR이 모두 merge될 때 태스크가 `Done`으로 바뀝니다.-1. merge된 연결 PR이 하나 이상 있고, `Closes MUL-123`처럼 종료 문구 바로 뒤에 번호가 있습니다(`Closes login MUL-123`처럼 중간에 다른 단어가 있으면 적용되지 않음).-2. 해당 태스크에 `Open` 또는 `Draft` 상태인 다른 연결 PR이 없습니다.-3. 태스크의 현재 상태가 `done` 또는 `cancelled`가 아닙니다.+1. 태스크에 연결된 PR이 하나 이상 있고 모두 `Merged` 상태입니다. `Open`이나 `Draft` PR이 남아 있으면 태스크는 계속 기다립니다. merge되지 않고 닫힌 PR도 태스크에서 제거할 때까지 마찬가지입니다.+2. 태스크가 `done` 또는 `cancelled`가 아니고, 이 태스크만 자동 완료를 끄지 않았습니다(**Pull requests → ⋯ → 이 태스크는 자동 완료하지 않음**). merge 후에 리뷰나 릴리스가 필요한 작업에 사용합니다.-따라서 브랜치 이름이나 제목에 `MUL-123`만 넣으면 연결은 되지만 그것만으로 완료를 트리거하지 않습니다. PR을 merge하지 않고 닫아도 태스크가 완료되지 않습니다.+판단은 PR 이벤트가 태스크에 닿을 때만 이루어집니다. 연결된 PR의 merge, 연결 추가, 연결 제거입니다. 태스크를 다시 열어도 `Done`으로 돌아가지 않으며, 다음에 연결된 PR이 merge될 때 완료됩니다. 설정을 켜도 이전에 merge된 태스크를 소급해 완료하지 않습니다.-상태 변경은 시스템 작업으로 타임라인에 기록되고 해당 태스크 구독자에게 알림이 전달됩니다.+상태 변경은 관련 PR을 적은 시스템 작업으로 타임라인에 기록되고 해당 태스크 구독자에게 알림이 전달됩니다. 이 설정은 [자체 호스팅 Git 코드 호스팅](/vcs-integration)을 포함한 모든 코드 호스트에 공통으로 적용됩니다.## 여러 워크스페이스@@ -96,6 +91,8 @@ PR이 merge되었다고 태스크가 반드시 완료된 것은 아닙니다. Mu예를 들어 PR 하나에서 `MUL-1`과 `ENG-2`를 함께 참조하면 서로 다른 접두사를 사용하는 두 워크스페이스에 각각 연결될 수 있습니다. 워크스페이스는 서로의 태스크를 볼 수 없습니다.+같은 번호가 연결된 여러 워크스페이스에서 태스크와 일치하면(접두사가 같을 때 생길 수 있음) Multica는 어느 워크스페이스에서도 자동으로 연결하지 않습니다. merge로 관련 없는 태스크가 완료되지 않도록 하기 위해서입니다. 올바른 워크스페이스에서 직접 연결하세요.+## 연결 해제**설정 → GitHub**에서 **연결 해제**를 클릭하면 현재 Multica 워크스페이스와 해당 installation의 관계만 제거됩니다. GitHub에서 App을 대신 제거하지는 않습니다. 기존 PR 기록은 유지되고 새 이벤트만 해당 워크스페이스에 들어오지 않습니다.@@ -174,10 +171,10 @@ API 서비스를 다시 시작한 뒤 **설정 → GitHub**에서 연결을 완- **연결 버튼을 사용할 수 없음**: `GITHUB_APP_SLUG`와 `GITHUB_WEBHOOK_SECRET`이 API 프로세스에 전달되었는지 확인합니다.- **Webhook이 401을 반환함**: GitHub App과 API가 같은 Webhook secret을 사용하는지 확인하고 GitHub의 **Recent Deliveries**에서 다시 전달합니다.-- **PR이 연결되지 않음**: 저장소가 App 승인 범위에 있는지, 자동 연결이 켜져 있는지, 번호가 현재 워크스페이스에 속하는지 확인합니다.-- **본문에 번호를 썼지만 연결되지 않음**: `Closes MUL-123`을 사용하거나 번호를 브랜치 이름 또는 PR 제목에 넣습니다.+- **PR이 연결되지 않음**: 저장소가 App 승인 범위에 있는지, 자동 연결이 켜져 있는지, 번호가 현재 워크스페이스에 속하는지, 누군가 태스크에서 PR을 제거하지 않았는지 확인합니다.+- **번호를 본문에만 적음**: 번호를 브랜치 이름이나 PR 제목에 넣거나 직접 연결합니다.- **CI 상태가 없음**: `GITHUB_APP_ID`와 `GITHUB_APP_PRIVATE_KEY`가 설정되었는지, App에 Contents, Checks 및 Commit statuses 읽기 권한이 있고 관련 이벤트를 구독했는지 확인합니다. Contents가 없으면 snapshot 전체가 실패해 PR 카드에 CI도 머지 상태도 표시되지 않습니다. 설치된 App에 권한을 추가한 뒤에는 각 installation owner가 GitHub에서 승인해야 적용됩니다.-- **PR merge 후 태스크가 완료되지 않음**: PR에 종료 문구가 있는지 확인하고 다른 연결 PR이 Open 또는 Draft 상태로 남아 있는지 확인합니다.+- **PR merge 후 태스크가 완료되지 않음**: 태스크의 **Pull requests** 목록 아래 설명을 확인합니다. 아직 merge되지 않았거나 merge 없이 닫힌 PR, 또는 태스크나 워크스페이스에서 자동 완료가 꺼져 있음을 알려 줍니다.## 다음 단계diff --git a/apps/docs/content/docs/github-integration.mdx b/apps/docs/content/docs/github-integration.mdxindex a50eb0fb44..43e0a82da6 100644--- a/apps/docs/content/docs/github-integration.mdx+++ b/apps/docs/content/docs/github-integration.mdx@@ -36,11 +36,13 @@ The **GitHub connection** decides which repositories Multica receives PR events| GitHub integration | Master switch. When off, the three below stop working, but the GitHub App stays connected. || PR sidebar | Shows linked pull requests in issue detail. || Co-authored-by | Adds `Co-authored-by: multica-agent <[email protected]>` to commits created by agents. |-| Auto-link PRs | Detects issue identifiers in a PR's branch name or title, and in the body when they follow a close intent. |+| Auto-link PRs | Links a PR to the issue whose identifier is in its branch name or title. || **PR card → CI & mergeability** | For each linked PR, Multica fetches an authenticated GitHub API snapshot and mirrors its **CI status** and **mergeability** onto the card (see **What the PR card shows** below). |+Whether a merged PR completes its issue is a separate, workspace-wide setting: **Settings → Issue statuses → Automation → Complete issues when their PRs merge**. It applies to every code host, including [self-hosted Git hosting](/vcs-integration).+## Link a PR to an issueThe simplest approach is to put the issue identifier in the branch name or PR title. For example, for issue `MUL-123`:@@ -55,15 +57,9 @@ MUL-123 Fix the redirect after loginMultica ignores case and only matches the current workspace's issue prefix. One PR can link to multiple issues.-If the identifier appears only in the PR body, you must use one of GitHub's close intents:--```text-Closes MUL-123-Fixes MUL-123-Resolves MUL-123-```+The PR body isn't scanned, and keywords carry no special meaning: `Closes MUL-123` or `Related to MUL-123` in the body links nothing. Commit messages and PR comments don't trigger linking either.-A bare mention in the body, such as `Related to MUL-123`, doesn't link the PR to that issue at all. Commit messages and PR comments don't trigger linking either.+You can also link a PR by hand: in the issue's **Pull requests** block, click **+** and paste the PR URL. To take a PR off an issue, open the **⋯** menu on its row and choose **Remove from issue**; Multica won't link it again from its title or branch.## View PRs on an issue@@ -77,19 +73,20 @@ Once linked, PRs appear in the **Pull requests** block of issue detail. Each entCI status and mergeability come from snapshots Multica pulls from the GitHub API, and the two are independent; merged or closed PRs no longer show either. When GitHub is temporarily unavailable, the card keeps the last snapshot and marks it stale instead of going blank.+Under the list, one line says what happens next — for example *Completes when #19 merges*, or which PR closed without merging.+Click an entry to open the PR on GitHub. Turning off the **PR sidebar** only hides this block; it doesn't disconnect anything.## When a merged PR moves an issue to Done-A merged PR doesn't necessarily mean the issue is finished. Multica only moves an issue to `Done` when all of the following hold:+With **Complete issues when their PRs merge** on (the default), an issue moves to `Done` when every PR linked to it is merged:-1. at least one merged linked PR used a close intent immediately followed by the identifier, such as `Closes MUL-123` (forms with words in between, like `Closes login MUL-123`, don't count);-2. the issue has no other linked PR still `Open` or `Draft`;-3. the issue is not currently `done` or `cancelled`.+1. the issue has at least one linked PR, and every linked PR is `Merged` — an `Open` or `Draft` PR keeps it waiting, and so does a PR closed without merging until you remove it from the issue;+2. the issue isn't `done` or `cancelled`, and auto-complete hasn't been turned off for it (**Pull requests → ⋯ → Don't auto-complete this issue**), for work that needs review or a release after the merge.-So writing `MUL-123` only in the branch name or title establishes the link but doesn't by itself trigger completion. A PR closed without merging doesn't complete the issue either.+The check runs when a PR event touches the issue: a linked PR merges, a PR is linked, or a link is removed. Reopening an issue doesn't bring it back to `Done` — the next linked PR that merges does. Turning the setting on doesn't complete issues whose PRs merged earlier.-The status change is written to the timeline as a system action, and members subscribed to the issue are notified.+The status change is written to the timeline as a system action naming the PRs, and members subscribed to the issue are notified.## Multiple workspaces@@ -97,6 +94,8 @@ The same GitHub App installation can be connected to multiple Multica workspacesFor example, a PR that references both `MUL-1` and `ENG-2` can link in two workspaces with different prefixes. Workspaces never see each other's issues.+If one identifier matches an issue in more than one of the connected workspaces (possible when they share a prefix), Multica doesn't link it automatically in any of them, so merging the PR can't complete an unrelated issue. Link the PR by hand in the right workspace.+## DisconnectClicking **Disconnect** in **Settings → GitHub** only removes the relationship between the current Multica workspace and the installation; it does not uninstall the App from GitHub for you. Existing PR records are kept, and new events stop flowing into that workspace.@@ -175,10 +174,10 @@ Restart the API server, then complete the connection in **Settings → GitHub**.- **Connect button disabled**: check that `GITHUB_APP_SLUG` and `GITHUB_WEBHOOK_SECRET` reached the API process.- **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, and the identifier belongs to the current workspace.-- **Identifier in the body but not linked**: switch to `Closes MUL-123`, or put the identifier in the branch name or PR title.+- **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 only in the body**: put it 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.-- **Issue not completed after the PR merged**: confirm the PR used a close intent, and check whether other linked PRs are still Open or Draft.+- **Issue not completed 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 auto-complete is off for the issue or the workspace.## Next stepsdiff --git a/apps/docs/content/docs/github-integration.zh.mdx b/apps/docs/content/docs/github-integration.zh.mdxindex 68f7d927ee..674a930e17 100644--- a/apps/docs/content/docs/github-integration.zh.mdx+++ b/apps/docs/content/docs/github-integration.zh.mdx@@ -36,11 +36,13 @@ GitHub 集成只读取安装时授权的仓库,不会提交代码、评论或| GitHub 集成 | 总开关。关闭后,下面三项不再生效,但不会断开 GitHub App。 || PR 侧栏 | 在任务详情中显示关联的 pull request。 || Co-authored-by | 在智能体创建的 commit 中加入 `Co-authored-by: multica-agent <[email protected]>`。 |-| 自动关联 PR | 从 PR 的分支名和标题中识别任务编号;正文中只识别紧跟关闭语句的编号。 |+| 自动关联 PR | 分支名或标题含任务编号的 PR,会关联到对应任务。 || **PR 卡片 → CI 与可合并性** | 对每个关联的 PR,Multica 从 GitHub API 拉取一份经鉴权的快照,把它的 **CI 状态**和**可合并性**镜像到卡片上(见下方 **PR 卡片展示什么**)。 |+PR 合并后是否自动完成任务,是另一项工作区设置:**设置 → 任务状态 → 自动化 → PR 合并后自动完成任务**。它对所有代码托管平台生效,包括[自托管 Git 代码托管](/vcs-integration)。+## 让 PR 关联到任务最简单的做法,是把任务编号写进分支名或 PR 标题。例如任务为 `MUL-123`:@@ -55,15 +57,9 @@ MUL-123 修复登录后的跳转Multica 会忽略大小写,并且只匹配当前工作区的任务前缀。一个 PR 可以关联多个任务。-只在 PR 正文中写编号时,需要使用 GitHub 的关闭语句:--```text-Closes MUL-123-Fixes MUL-123-Resolves MUL-123-```+Multica 不读取 PR 正文,关键词也没有特殊含义:正文里写 `Closes MUL-123` 或 `Related to MUL-123` 都不会建立关联。Commit message 和 PR 评论也不会触发关联。-正文中的普通提及,例如 `Related to MUL-123`,根本不会与该任务建立关联。Commit message 和 PR 评论也不会触发关联。+也可以手动关联:在任务的 **Pull requests** 区块点 **+**,粘贴 PR 链接。要把 PR 从任务上移除,打开这一行的 **⋯** 菜单,选择 **移除关联**;之后 Multica 不会再根据标题或分支把它关联回来。## 在任务中查看 PR@@ -77,19 +73,20 @@ Resolves MUL-123CI 状态和可合并性来自 Multica 从 GitHub API 拉取的快照,两者互相独立;已合并或已关闭的 PR 不再显示这两项。GitHub 暂时不可用时,卡片会保留上一次的快照并标记为过期,而不是清空。+列表下方有一行说明接下来会发生什么,例如「等待 #19 合并后自动完成」,或者哪个 PR 已关闭、未合并。+点击记录可以打开 GitHub 上的 PR。关闭 **PR 侧栏** 只会隐藏这个区块,不会断开连接。## PR 合并转 Done 的条件-PR 合并不一定代表任务已完成。Multica 只有在以下条件同时成立时,才把任务改为 `Done`:+开启 **PR 合并后自动完成任务**(默认开启)时,任务的所有关联 PR 都合并后,任务改为 `Done`:-1. 至少一个已合并的关联 PR 使用了紧跟编号的关闭语句,例如 `Closes MUL-123`(`Closes login MUL-123` 这类中间隔词的写法不生效);-2. 该任务没有其他仍为 `Open` 或 `Draft` 的关联 PR;-3. 任务当前不是 `done` 或 `cancelled`。+1. 任务至少有一个关联 PR,且所有关联 PR 都是 `Merged`。仍为 `Open` 或 `Draft` 的 PR 会让任务继续等待;关闭但未合并的 PR 也一样,直到你把它从任务上移除;+2. 任务当前不是 `done` 或 `cancelled`,也没有单独关闭自动完成(**Pull requests → ⋯ → 此任务不自动完成**),适用于合并后还需要验收或发布的工作。-因此,仅在分支名或标题中写 `MUL-123` 会建立关联,但不会单独触发完成。PR 关闭但没有合并,也不会完成任务。+只有 PR 事件会触发判断:关联 PR 合并、新增关联或移除关联。重新打开任务后,它不会被改回 `Done`,下一个关联 PR 合并时才会。开启这项设置,也不会补完成此前已合并的任务。-状态变化会以系统操作写入时间线,订阅该任务的成员会收到通知。+状态变化会以系统操作写入时间线并列出相关 PR,订阅该任务的成员会收到通知。## 多个工作区@@ -97,6 +94,8 @@ PR 合并不一定代表任务已完成。Multica 只有在以下条件同时成例如一个 PR 同时引用 `MUL-1` 和 `ENG-2`,它可以在两个不同前缀的工作区中分别关联。工作区之间不会看到对方的任务。+如果同一个编号在多个已连接的工作区中都对应到任务(前缀相同时可能出现),Multica 不会在任何一个工作区自动关联,避免合并时完成无关的任务。请在正确的工作区手动关联。+## 断开连接在 **设置 → GitHub** 点击 **断开**,只会移除当前 Multica 工作区与该 installation 的关系,不会替你从 GitHub 卸载 App。已有 PR 记录会保留,新的事件不再进入该工作区。@@ -175,10 +174,10 @@ make migrate-up- **连接按钮不可用**:检查 `GITHUB_APP_SLUG` 和 `GITHUB_WEBHOOK_SECRET` 是否已进入 API 进程。- **Webhook 返回 401**:确认 GitHub App 与 API 使用同一个 Webhook secret,然后在 GitHub 的 **Recent Deliveries** 中重新投递。-- **PR 没有关联**:检查仓库是否在 App 授权范围内、自动关联是否开启,以及编号是否属于当前工作区。-- **正文写了编号但没关联**:改用 `Closes MUL-123`,或把编号放到分支名、PR 标题中。+- **PR 没有关联**:检查仓库是否在 App 授权范围内、自动关联是否开启、编号是否属于当前工作区,以及是否有人把它从任务上移除过。+- **编号只写在正文里**:把编号放到分支名或 PR 标题中,或者手动关联。- **没有 CI 状态**:确认 `GITHUB_APP_ID` 和 `GITHUB_APP_PRIVATE_KEY` 已配置,App 具有 Contents、Checks 与 Commit statuses 的只读权限并订阅了对应事件。缺少 Contents 会让整个快照失败,PR 卡片既没有 CI 也没有合并状态。给已安装的 App 补加权限后,还需要各 installation 的所有者在 GitHub 上批准才会生效。-- **PR 合并后任务没完成**:确认 PR 使用了关闭语句,并检查是否还有其他关联 PR 处于 Open 或 Draft。+- **PR 合并后任务没完成**:看任务 **Pull requests** 列表下方的说明,它会指出仍未合并或已关闭未合并的 PR,或者说明任务、工作区关闭了自动完成。## 接下来diff --git a/apps/docs/content/docs/issues.ja.mdx b/apps/docs/content/docs/issues.ja.mdxindex a8299dfdb2..7642af2dea 100644--- a/apps/docs/content/docs/issues.ja.mdx+++ b/apps/docs/content/docs/issues.ja.mdx@@ -63,13 +63,13 @@ import { Callout } from "fumadocs-ui/components/callout";ステータス間に固定のフローはなく、メンバーもエージェントも直接変更できます。-エージェントは、作業がタスクに与えた実際の変化をそのままステータスに書き込みます。タスクが求めているもの(コードでも、調査でも、設計でも、タスク自身が求めるレビューでも)を作り始めた時点で `in_progress` に進め、実行中からボードに反映させます。納品したら `in_review` に進め、ターンを越えて作業が続く場合は `in_progress` のままにします。そのタスク自身の成果物を生まないターン(質問への回答、他所が持つ作業への助言)では、最初から最後までステータスを変更しません。これらの変更は、実行中にエージェントが Multica CLI から明示的に書き込むものです。実行の開始や完了でサーバーがタスクのステータスを切り替えることはありません(下記の 2 つのシステム例外を除く)。`done` は通常、人による確認か、クローズ意図付き PR のマージのような連携によって設定されます。+エージェントは、作業がタスクに与えた実際の変化をそのままステータスに書き込みます。タスクが求めているもの(コードでも、調査でも、設計でも、タスク自身が求めるレビューでも)を作り始めた時点で `in_progress` に進め、実行中からボードに反映させます。納品したら `in_review` に進め、ターンを越えて作業が続く場合は `in_progress` のままにします。そのタスク自身の成果物を生まないターン(質問への回答、他所が持つ作業への助言)では、最初から最後までステータスを変更しません。これらの変更は、実行中にエージェントが Multica CLI から明示的に書き込むものです。実行の開始や完了でサーバーがタスクのステータスを切り替えることはありません(下記の 2 つのシステム例外を除く)。`done` は通常、人による確認か、タスクに紐づく PR がすべてマージされたときに設定されます。<Callout type="info">次の 2 つの変更はシステムが行います。- 実行が失敗し、そのタスクにほかの実行がなく、リトライも起動しなかった場合、`in_progress` は `todo` に戻ります。-- 紐づく GitHub PR がクローズ意図付きでマージされ、open または draft のまま残る紐づき PR がほかにない場合、タスクは `done` になります。+- タスクに紐づく PR がすべてマージされると、タスクは `done` になります。ワークスペースまたはそのタスクで PR による自動完了がオフの場合を除きます。詳しくは [GitHub 連携](/github-integration)を参照してください。</Callout>### カスタムステータスdiff --git a/apps/docs/content/docs/issues.ko.mdx b/apps/docs/content/docs/issues.ko.mdxindex c45f2e083e..04487f8f9c 100644--- a/apps/docs/content/docs/issues.ko.mdx+++ b/apps/docs/content/docs/issues.ko.mdx@@ -63,13 +63,13 @@ import { Callout } from "fumadocs-ui/components/callout";상태 사이에는 고정된 전환 순서가 없으며 멤버와 에이전트 모두 상태를 직접 변경할 수 있습니다.-에이전트는 작업이 태스크에 실제로 일으킨 변화를 그대로 상태에 기록합니다. 태스크가 요구하는 것을 만들기 시작하면, 그것이 코드든 조사든 설계든 태스크 자체가 요청한 리뷰든 바로 `in_progress`로 옮겨 실행 중에도 보드에 드러나게 합니다. 전달하면 `in_review`로 옮기고, 작업이 이번 턴을 넘어 이어지면 `in_progress`로 유지합니다. 그 태스크 자체의 결과물을 만들지 않는 턴, 예를 들어 질문에 답하거나 다른 곳이 소유한 작업에 조언하는 경우에는 처음부터 끝까지 상태를 바꾸지 않습니다. 이 변경은 실행 중에 에이전트가 Multica CLI로 명시적으로 기록하는 것입니다. 실행이 시작되거나 끝날 때 서버가 태스크 상태를 바꾸지는 않습니다(아래 두 가지 시스템 예외 제외). `done`은 보통 사람의 확인이나, 종료 의도를 포함한 PR 병합 같은 연동으로 지정됩니다.+에이전트는 작업이 태스크에 실제로 일으킨 변화를 그대로 상태에 기록합니다. 태스크가 요구하는 것을 만들기 시작하면, 그것이 코드든 조사든 설계든 태스크 자체가 요청한 리뷰든 바로 `in_progress`로 옮겨 실행 중에도 보드에 드러나게 합니다. 전달하면 `in_review`로 옮기고, 작업이 이번 턴을 넘어 이어지면 `in_progress`로 유지합니다. 그 태스크 자체의 결과물을 만들지 않는 턴, 예를 들어 질문에 답하거나 다른 곳이 소유한 작업에 조언하는 경우에는 처음부터 끝까지 상태를 바꾸지 않습니다. 이 변경은 실행 중에 에이전트가 Multica CLI로 명시적으로 기록하는 것입니다. 실행이 시작되거나 끝날 때 서버가 태스크 상태를 바꾸지는 않습니다(아래 두 가지 시스템 예외 제외). `done`은 보통 사람의 확인이나, 태스크에 연결된 PR이 모두 병합될 때 지정됩니다.<Callout type="info">다음 두 가지 변경은 시스템이 수행합니다.- 실행이 실패하고 해당 태스크에 다른 실행이 없으며 재시도도 트리거되지 않으면 `in_progress`가 `todo`로 돌아갑니다.-- 연결된 GitHub PR이 종료 의도를 포함한 채 병합되고, 여전히 open 또는 draft 상태인 다른 연결 PR이 없으면 태스크가 `done`으로 바뀝니다.+- 태스크에 연결된 PR이 모두 병합되면 태스크가 `done`으로 바뀝니다. 워크스페이스나 해당 태스크에서 PR 자동 완료를 끈 경우는 제외합니다. 자세한 내용은 [GitHub 연동](/github-integration)을 참고하세요.</Callout>### 사용자 지정 상태diff --git a/apps/docs/content/docs/issues.mdx b/apps/docs/content/docs/issues.mdxindex 0657023369..c90ee127c4 100644--- a/apps/docs/content/docs/issues.mdx+++ b/apps/docs/content/docs/issues.mdx@@ -63,13 +63,13 @@ Categories keep lifecycle reasoning simple. Boards, lists, filters, and sortingThere is no fixed flow between statuses — members and agents can change them directly.-Agents write the status the issue is in as their work changes it: starting work on what the issue asks for — in whatever form, research, design, or a review the issue itself requests — moves it to `in_progress` right away, so the board shows the work while it runs; delivering moves it to `in_review`; work that continues beyond the turn keeps it `in_progress`; a turn that produces nothing of the issue's own deliverable — answering questions, consulting on work owned elsewhere — leaves the status untouched throughout. These updates are written explicitly by the agent through the Multica CLI during the run — the server does not flip issue status when a run starts or completes (apart from the two system exceptions below). `done` is usually a human confirmation, or an integration such as a PR with close intent that merges.+Agents write the status the issue is in as their work changes it: starting work on what the issue asks for — in whatever form, research, design, or a review the issue itself requests — moves it to `in_progress` right away, so the board shows the work while it runs; delivering moves it to `in_review`; work that continues beyond the turn keeps it `in_progress`; a turn that produces nothing of the issue's own deliverable — answering questions, consulting on work owned elsewhere — leaves the status untouched throughout. These updates are written explicitly by the agent through the Multica CLI during the run — the server does not flip issue status when a run starts or completes (apart from the two system exceptions below). `done` is usually a human confirmation, or the merge of an issue's linked PRs.<Callout type="info">Two changes are made by the system:- When a run fails, the issue has no other runs, and no retry is triggered, `in_progress` rolls back to `todo`.-- When a linked GitHub PR merges with close intent and no other linked PR is still open or draft, the issue becomes `done`.+- When every PR linked to the issue is merged, the issue becomes `done` — unless PR auto-complete is off for the workspace or the issue. See [GitHub integration](/github-integration).</Callout>### Custom statusesdiff --git a/apps/docs/content/docs/issues.zh.mdx b/apps/docs/content/docs/issues.zh.mdxindex a88c0023e8..115e9202ff 100644--- a/apps/docs/content/docs/issues.zh.mdx+++ b/apps/docs/content/docs/issues.zh.mdx@@ -63,13 +63,13 @@ import { Callout } from "fumadocs-ui/components/callout";状态之间没有固定流转,成员和智能体都可以直接修改。-智能体随着工作对任务的实际影响写入状态:开始产出任务本身要求的东西时立刻推到 `in_progress`——不论形式是代码、调研、设计,还是任务本身要求的 review——让看板在工作进行中就能反映出来;交付后推到 `in_review`;工作跨轮继续则保持 `in_progress`;没有产出本任务交付物的轮次(答疑、给别处的工作做咨询)则全程不改状态。这些状态变更由智能体在运行中通过 Multica CLI 显式写入——运行开始或完成时,服务端不会自动改任务状态(下面两个系统例外除外)。`done` 通常留给人工确认,或由集成完成(例如带关闭意图的 PR 合并)。+智能体随着工作对任务的实际影响写入状态:开始产出任务本身要求的东西时立刻推到 `in_progress`——不论形式是代码、调研、设计,还是任务本身要求的 review——让看板在工作进行中就能反映出来;交付后推到 `in_review`;工作跨轮继续则保持 `in_progress`;没有产出本任务交付物的轮次(答疑、给别处的工作做咨询)则全程不改状态。这些状态变更由智能体在运行中通过 Multica CLI 显式写入——运行开始或完成时,服务端不会自动改任务状态(下面两个系统例外除外)。`done` 通常留给人工确认,或在任务的关联 PR 全部合并时由系统完成。<Callout type="info">两个变化由系统执行:- 执行失败,且该任务没有其他执行、也没有触发重试时,`in_progress` 回到 `todo`。-- 关联的 GitHub PR 带关闭意图合并,且没有其他仍处于 open 或 draft 的关联 PR 时,任务变为 `done`。+- 任务的所有关联 PR 都合并后,任务变为 `done`,除非工作区或该任务关闭了 PR 自动完成。详见 [GitHub 集成](/github-integration)。</Callout>### 自定义状态diff --git a/apps/docs/content/docs/vcs-integration.ja.mdx b/apps/docs/content/docs/vcs-integration.ja.mdxindex 30f692925e..5e678bf8ba 100644--- a/apps/docs/content/docs/vcs-integration.ja.mdx+++ b/apps/docs/content/docs/vcs-integration.ja.mdx@@ -1,6 +1,6 @@---title: セルフホスト Git ホスティング-description: ワークスペースごとにセルフホストの Forgejo、Gitea、GitLab インスタンスを接続し、ブランチ名かタイトルにタスク番号を含む、または本文で終了キーワードの直後にタスク番号を置いた Pull Request / Merge Request を対応するタスクへ自動的に紐づけ、マージ時に「完了」へ移動して CI ステータスを表示します。+description: ワークスペースごとにセルフホストの Forgejo、Gitea、GitLab インスタンスを接続し、ブランチ名かタイトルにタスク番号を含む Pull Request / Merge Request を対応するタスクへ自動的に紐づけ、紐づく PR がすべてマージされると「完了」へ移動し、CI ステータスを表示します。---import { Callout } from "fumadocs-ui/components/callout";@@ -9,7 +9,7 @@ import { Callout } from "fumadocs-ui/components/callout";**セルフホスト版 Multica 専用です。** この連携は Multica を**自分でデプロイしている**場合のみ利用でき、Multica Cloud では提供されません。ここでの「セルフホスト」は **Multica 自体**のセルフホストを意味します。通常は独自ネットワーク内の Git インスタンスへアクセスするために使用します。サーバー運用者が `MULTICA_VCS_INTEGRATION_ENABLED=true` を設定して機能を有効にし、`MULTICA_VCS_SECRET_KEY` も設定する必要があります。それまでは、設定 → 連携にこのセクションは表示されません。</Callout>-Multica はワークスペースごとにセルフホストの Git ホスティング、**Forgejo**、**Gitea**、**GitLab** のいずれかへ接続します。接続後、ブランチ名かタイトルにタスク番号(例: `MUL-123`)を含む Pull Request(GitLab では Merge Request)、または本文で終了キーワードの直後にタスク番号を置いた PR は、対応する[タスク](/issues)へ**自動的に紐づけられ**、タスクサイドバーの **Pull requests** に表示されます。終了キーワードを含む PR がマージされると、タスクは「完了」へ移動します。head commit の CI はカード上のチェックバーとして表示されます。+Multica はワークスペースごとにセルフホストの Git ホスティング、**Forgejo**、**Gitea**、**GitLab** のいずれかへ接続します。接続後、ブランチ名かタイトルにタスク番号(例: `MUL-123`)を含む Pull Request(GitLab では Merge Request)は、対応する[タスク](/issues)へ**自動的に紐づけられ**、タスクサイドバーの **Pull requests** に表示されます。タスクに紐づく PR がすべてマージされると、タスクは「完了」へ移動します。head commit の CI はカード上のチェックバーとして表示されます。これらの Git ホスティングは GitHub と並行して利用でき、1 つのワークスペースで任意に組み合わせられます。@@ -76,7 +76,7 @@ Multica は保存済みの secret で各 delivery を検証するため、一致## ミラーされる内容- **Pull / Merge Request** — open、closed、merged、draft の状態、作成者、ブランチ、および Git ホスティングが提供する場合は diff 統計。-- **タスクの紐づけ** — タイトルまたはブランチの番号、および本文で終了キーワードの直後に置いた番号で PR をタスクへ紐づけます。本文中の通常の参照では紐づきません。マージ済み PR に終了キーワード(`Closes`/`Fixes`/`Resolves MUL-123`)があり、open の関連 PR が残っていなければ、タスクを「完了」へ移動します。+- **タスクの紐づけ** — タイトルまたはブランチの番号で PR をタスクへ紐づけます。本文は読み取らないため、本文の `Closes MUL-123` では紐づきません。タスクに紐づく PR(GitHub とセルフホストの両方)がすべてマージされると、[GitHub](/github-integration) と同じワークスペース設定とルールに従ってタスクを「完了」へ移動します。- **CI** — Forgejo/Gitea の commit status と GitLab pipeline を、head commit の成功/失敗/進行中チェックバーへ集約します。## エージェントによる Pull Request の作成diff --git a/apps/docs/content/docs/vcs-integration.ko.mdx b/apps/docs/content/docs/vcs-integration.ko.mdxindex 702944ae28..c6ecf4dd3f 100644--- a/apps/docs/content/docs/vcs-integration.ko.mdx+++ b/apps/docs/content/docs/vcs-integration.ko.mdx@@ -1,6 +1,6 @@---title: 자체 호스팅 Git 코드 호스팅-description: 워크스페이스마다 자체 호스팅 Forgejo, Gitea, GitLab 인스턴스를 연결해 브랜치 이름이나 제목에 태스크 번호가 있거나 본문에서 종료 키워드 바로 뒤에 태스크 번호를 적은 Pull Request / Merge Request를 해당 태스크에 자동 연결하고, merge 시 완료로 옮기며 CI 상태를 표시합니다.+description: 워크스페이스마다 자체 호스팅 Forgejo, Gitea, GitLab 인스턴스를 연결해 브랜치 이름이나 제목에 태스크 번호가 있는 Pull Request / Merge Request를 해당 태스크에 자동 연결하고, 연결된 PR이 모두 merge되면 완료로 옮기며 CI 상태를 표시합니다.---import { Callout } from "fumadocs-ui/components/callout";@@ -9,7 +9,7 @@ import { Callout } from "fumadocs-ui/components/callout";**자체 배포한 Multica에서만 사용할 수 있습니다.** 이 연동은 Multica를 **직접 배포해 운영할 때만** 제공되며 Multica Cloud에서는 사용할 수 없습니다. 여기서 "자체 호스팅"은 **Multica 자체를 배포하는 것**을 뜻합니다. 일반적으로 자체 네트워크의 Git 인스턴스에 접근하기 위해 사용합니다. 서버 운영자가 `MULTICA_VCS_INTEGRATION_ENABLED=true`로 기능을 켜고 `MULTICA_VCS_SECRET_KEY`도 설정해야 합니다. 그전에는 설정 → 연동에 이 영역이 표시되지 않습니다.</Callout>-Multica는 워크스페이스별로 자체 호스팅 Git 코드 호스팅인 **Forgejo**, **Gitea**, **GitLab** 중 하나에 연결합니다. 연결하면 브랜치 이름이나 제목에 태스크 번호(예: `MUL-123`)가 포함된 Pull Request(GitLab에서는 Merge Request), 또는 본문에서 종료 키워드 바로 뒤에 번호를 적은 PR이 해당 [태스크](/issues)에 **자동으로 연결**되고 태스크 사이드바의 **Pull requests**에 표시됩니다. 종료 키워드가 있는 PR이 merge되면 태스크가 완료로 이동합니다. head commit의 CI는 카드에 check bar로 표시됩니다.+Multica는 워크스페이스별로 자체 호스팅 Git 코드 호스팅인 **Forgejo**, **Gitea**, **GitLab** 중 하나에 연결합니다. 연결하면 브랜치 이름이나 제목에 태스크 번호(예: `MUL-123`)가 포함된 Pull Request(GitLab에서는 Merge Request)가 해당 [태스크](/issues)에 **자동으로 연결**되고 태스크 사이드바의 **Pull requests**에 표시됩니다. 태스크에 연결된 PR이 모두 merge되면 태스크가 완료로 이동합니다. head commit의 CI는 카드에 check bar로 표시됩니다.이 코드 호스팅은 GitHub와 동시에 사용할 수 있으며 워크스페이스 하나에서 원하는 대로 조합할 수 있습니다.@@ -76,7 +76,7 @@ Multica는 저장된 secret으로 모든 delivery를 검증하므로 일치하## 미러링되는 내용- **Pull / Merge Request** — open, closed, merged, draft 상태와 작성자, 브랜치, 그리고 코드 호스팅이 제공하는 경우 diff 통계.-- **태스크 연결** — 제목이나 브랜치의 번호, 그리고 본문에서 종료 키워드 바로 뒤에 있는 번호가 PR을 태스크에 연결합니다. 본문의 일반 언급은 아무것도 연결하지 않습니다. merge된 PR에 종료 키워드(`Closes`/`Fixes`/`Resolves MUL-123`)가 있고 open 상태인 연결 PR이 더 없으면 태스크를 완료로 옮깁니다.+- **태스크 연결** — 제목이나 브랜치의 번호가 PR을 태스크에 연결합니다. 본문은 읽지 않으므로 본문의 `Closes MUL-123`은 아무것도 연결하지 않습니다. 태스크에 연결된 PR(GitHub와 자체 호스팅 모두)이 모두 merge되면 [GitHub](/github-integration)와 같은 워크스페이스 설정과 규칙에 따라 태스크를 완료로 옮깁니다.- **CI** — Forgejo/Gitea commit status와 GitLab pipeline을 head commit의 통과/실패/진행 중 check bar로 집계합니다.## 에이전트의 Pull Request 생성diff --git a/apps/docs/content/docs/vcs-integration.mdx b/apps/docs/content/docs/vcs-integration.mdxindex f62108fa1b..6442a3c13f 100644--- a/apps/docs/content/docs/vcs-integration.mdx+++ b/apps/docs/content/docs/vcs-integration.mdx@@ -1,6 +1,6 @@---title: Self-hosted Git providers-description: Connect a self-hosted Forgejo, Gitea, or GitLab instance per workspace so pull/merge requests that carry an issue identifier in their branch name or title, or after a closing keyword in the body, auto-attach to that issue, move it to Done on merge, and show CI status.+description: Connect a self-hosted Forgejo, Gitea, or GitLab instance per workspace so pull/merge requests that carry an issue identifier in their branch name or title auto-attach to that issue, move it to Done once every linked PR is merged, and show CI status.---import { Callout } from "fumadocs-ui/components/callout";@@ -14,7 +14,7 @@ and set `MULTICA_VCS_SECRET_KEY`; until then the section does not appear inSettings → Integrations.</Callout>-Multica connects to a self-hosted Git provider per workspace: **Forgejo**, **Gitea**, or **GitLab**. Once connected, any pull request (GitLab: merge request) whose branch name or title contains an issue identifier (for example `MUL-123`), or whose body names one after a closing keyword (`Closes MUL-123`), is **auto-linked** to that [issue](/issues), appears under **Pull requests** in the issue sidebar, and — when merged with a closing keyword — moves the issue to **Done**. CI for the head commit shows as a checks bar on the card.+Multica connects to a self-hosted Git provider per workspace: **Forgejo**, **Gitea**, or **GitLab**. Once connected, any pull request (GitLab: merge request) whose branch name or title contains an issue identifier (for example `MUL-123`) is **auto-linked** to that [issue](/issues) and appears under **Pull requests** in the issue sidebar. When every PR linked to the issue is merged, the issue moves to **Done**. CI for the head commit shows as a checks bar on the card.These providers run alongside GitHub: a workspace can use any combination.@@ -81,7 +81,7 @@ Multica authenticates every delivery against the stored secret, so a webhook wit## What gets mirrored- **Pull / merge requests** — open, closed, merged, and draft state, author, branch, and (where the provider supplies them) diff stats.-- **Issue links** — an identifier in the title or branch links the PR to the issue, as does an identifier after a closing keyword in the body; a bare mention in the body links nothing. A closing keyword (`Closes`/`Fixes`/`Resolves MUL-123`) on a merged PR moves the issue to **Done** once no linked PR is still open.+- **Issue links** — an identifier in the title or branch links the PR to the issue; the body isn't scanned, so `Closes MUL-123` there links nothing. Once every PR linked to the issue is merged — across GitHub and self-hosted providers — the issue moves to **Done**, under the same workspace setting and rules as [GitHub](/github-integration).- **CI** — Forgejo/Gitea commit statuses and GitLab pipelines aggregate into a passed/failed/pending checks bar for the head commit.## Agents opening pull requestsdiff --git a/apps/docs/content/docs/vcs-integration.zh.mdx b/apps/docs/content/docs/vcs-integration.zh.mdxindex d5801735c6..82dd71ef01 100644--- a/apps/docs/content/docs/vcs-integration.zh.mdx+++ b/apps/docs/content/docs/vcs-integration.zh.mdx@@ -1,6 +1,6 @@---title: 自托管 Git 代码托管-description: 为每个工作区连接自托管的 Forgejo、Gitea 或 GitLab 实例,使分支名或标题中带有任务编号、或正文中在关闭关键字后带有任务编号的 Pull Request / Merge Request 自动关联到对应任务,在合并时将其移动到「完成」,并展示 CI 状态。+description: 为每个工作区连接自托管的 Forgejo、Gitea 或 GitLab 实例,使分支名或标题中带有任务编号的 Pull Request / Merge Request 自动关联到对应任务,在所有关联 PR 合并后将其移动到「完成」,并展示 CI 状态。---import { Callout } from "fumadocs-ui/components/callout";@@ -9,7 +9,7 @@ import { Callout } from "fumadocs-ui/components/callout";**仅适用于自部署的 Multica。** 此集成只在你**自己部署 Multica** 时可用,Multica 云端不提供。这里的「自托管」指的是 **Multica 本身自部署**——通常是为了让它能访问你自己网络内的 Git 实例。需要服务端运维开启(`MULTICA_VCS_INTEGRATION_ENABLED=true`)并设置 `MULTICA_VCS_SECRET_KEY`;在此之前,设置 → 集成里不会出现该板块。</Callout>-Multica 按工作区连接自托管的 Git 代码托管:**Forgejo**、**Gitea** 或 **GitLab**。连接后,任何在分支名或标题中包含任务编号(例如 `MUL-123`)、或在正文的关闭关键字后写出该编号(`Closes MUL-123`)的 Pull Request(GitLab 为 Merge Request)都会**自动关联**到对应的 [任务](/issues),出现在任务侧栏的 **Pull requests** 中;当带有关闭关键字的 PR 合并后,任务会被移动到「完成」。head commit 的 CI 会以检查条的形式显示在卡片上。+Multica 按工作区连接自托管的 Git 代码托管:**Forgejo**、**Gitea** 或 **GitLab**。连接后,任何在分支名或标题中包含任务编号(例如 `MUL-123`)的 Pull Request(GitLab 为 Merge Request)都会**自动关联**到对应的 [任务](/issues),出现在任务侧栏的 **Pull requests** 中;任务的所有关联 PR 都合并后,任务会被移动到「完成」。head commit 的 CI 会以检查条的形式显示在卡片上。这些代码托管与 GitHub 并行工作:一个工作区可任意组合使用。@@ -76,7 +76,7 @@ Multica 会用存储的密钥校验每次投递,因此没有匹配密钥的 We## 镜像的内容- **Pull / Merge Request** —— open、closed、merged、draft 状态,以及作者、分支和(在代码托管提供时)diff 统计。-- **任务关联** —— 标题或分支中的编号会将 PR 关联到任务,正文中的编号只有紧跟关闭关键字时才会关联;正文中的普通提及不会建立任何关联。合并的 PR 带有关闭关键字(`Closes`/`Fixes`/`Resolves MUL-123`)且没有仍处于 open 的关联 PR 时,任务会被移动到「完成」。+- **任务关联** —— 标题或分支中的编号会将 PR 关联到任务;Multica 不读取正文,正文里写 `Closes MUL-123` 不会建立关联。任务的所有关联 PR(包括 GitHub 与自托管平台上的)都合并后,任务会被移动到「完成」,遵循与 [GitHub](/github-integration) 相同的工作区设置和规则。- **CI** —— Forgejo/Gitea 的提交状态与 GitLab 的流水线会汇总为 head commit 的通过/失败/进行中检查条。## 智能体创建 Pull Requestdiff --git a/apps/ui-lab/src/product-fixtures.ts b/apps/ui-lab/src/product-fixtures.tsindex 666b9ed050..3afbe8b8dc 100644--- a/apps/ui-lab/src/product-fixtures.ts+++ b/apps/ui-lab/src/product-fixtures.ts@@ -300,7 +300,7 @@ export function createFixtureApi(getLocale: () => LabLocale = () => "en") {installations: [],configured: false,}),- listIssuePullRequests: async () => ({ pull_requests: [] }),+ listIssuePullRequests: async () => ({ pull_requests: [], auto_complete: null }),listAttachments: async () => [],listIssueSubscribers: async () => [],getAssigneeFrequency: async () => [],diff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.tsindex bdf3bb3f0e..5c91bf1f35 100644--- a/packages/core/api/client.test.ts+++ b/packages/core/api/client.test.ts@@ -219,7 +219,52 @@ describe("ApiClient pull-request response schema", () => {await expect(new ApiClient("https://api.example.test").listIssuePullRequests("issue-1"),- ).resolves.toEqual({ pull_requests: [] });+ ).resolves.toEqual({ pull_requests: [], auto_complete: null });+ });++ function stubPullRequests(body: unknown) {+ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue(+ new Response(JSON.stringify(body), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ }),+ ),+ );+ }++ it("parses the auto-complete decision and link source", async () => {+ stubPullRequests({+ pull_requests: [{ ...validPR, link_source: "title" }],+ auto_complete: { state: "waiting", pull_request_ids: ["pr-1"], issue_disabled: false, workspace_enabled: true },+ });+ const result = await new ApiClient("https://api.example.test").listIssuePullRequests("issue-1");+ expect(result.pull_requests[0]?.link_source).toBe("title");+ expect(result.auto_complete).toEqual({+ state: "waiting",+ pull_request_ids: ["pr-1"],+ issue_disabled: false,+ workspace_enabled: true,+ });+ });++ it("treats a missing auto-complete block (older backend) as null", async () => {+ stubPullRequests({ pull_requests: [validPR] });+ const result = await new ApiClient("https://api.example.test").listIssuePullRequests("issue-1");+ expect(result.auto_complete).toBeNull();+ expect(result.pull_requests).toHaveLength(1);+ });++ it("keeps the PR list when only the auto-complete block or link source is malformed", async () => {+ stubPullRequests({+ pull_requests: [{ ...validPR, link_source: "psychic" }],+ auto_complete: { state: 42 },+ });+ const result = await new ApiClient("https://api.example.test").listIssuePullRequests("issue-1");+ expect(result.auto_complete).toBeNull();+ expect(result.pull_requests).toHaveLength(1);+ expect(result.pull_requests[0]?.link_source).toBeUndefined();});});diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 74c6553891..a53f706d3f 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -168,7 +168,7 @@ import type {PluginPreviewRequest,PluginInstallRequest,PluginConfigRequest,- GitHubPullRequest,+ IssuePullRequestsResponse,ListGitHubInstallationsResponse,ListGitHubRepositoriesResponse,GitHubConnectResponse,@@ -4702,7 +4702,7 @@ export class ApiClient {});}- async listIssuePullRequests(issueId: string): Promise<{ pull_requests: GitHubPullRequest[] }> {+ async listIssuePullRequests(issueId: string): Promise<IssuePullRequestsResponse> {const raw = await this.fetch<unknown>(`/api/issues/${issueId}/pull-requests`);return parseWithFallback(raw,@@ -4712,6 +4712,51 @@ export class ApiClient {);}+ /** Link a PR the workspace already mirrors, by pasted URL or by id (undo). */+ async linkIssuePullRequest(+ issueId: string,+ body: { url: string } | { pull_request_id: string },+ ): Promise<IssuePullRequestsResponse> {+ const raw = await this.fetch<unknown>(`/api/issues/${issueId}/pull-requests`, {+ method: "POST",+ body: JSON.stringify(body),+ });+ return parseWithFallback(+ raw,+ IssuePullRequestsResponseSchema,+ EMPTY_ISSUE_PULL_REQUESTS_RESPONSE,+ { endpoint: "POST /api/issues/:id/pull-requests" },+ );+ }++ /** Remove a PR from an issue; later webhooks will not link it again. */+ async unlinkIssuePullRequest(issueId: string, pullRequestId: string): Promise<IssuePullRequestsResponse> {+ const raw = await this.fetch<unknown>(+ `/api/issues/${issueId}/pull-requests/${pullRequestId}`,+ { method: "DELETE" },+ );+ return parseWithFallback(+ raw,+ IssuePullRequestsResponseSchema,+ EMPTY_ISSUE_PULL_REQUESTS_RESPONSE,+ { endpoint: "DELETE /api/issues/:id/pull-requests/:prId" },+ );+ }++ /** Turn PR auto-complete off (or back on) for one issue. */+ async setIssuePRAutoComplete(issueId: string, disabled: boolean): Promise<IssuePullRequestsResponse> {+ const raw = await this.fetch<unknown>(`/api/issues/${issueId}/pr-auto-complete`, {+ method: "PUT",+ body: JSON.stringify({ disabled }),+ });+ return parseWithFallback(+ raw,+ IssuePullRequestsResponseSchema,+ EMPTY_ISSUE_PULL_REQUESTS_RESPONSE,+ { endpoint: "PUT /api/issues/:id/pr-auto-complete" },+ );+ }+// VCS integration (Forgejo / Gitea / GitLab)async listVCSConnections(workspaceId: string): Promise<ListVCSConnectionsResponse> {return this.fetch(`/api/workspaces/${workspaceId}/vcs/connections`);diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex 28406b2e48..1be3216a9c 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -46,7 +46,7 @@ import type {RedeemTelegramBindingTokenResponse,GroupedIssuesResponse,GitHubConnectResponse,- GitHubPullRequest,+ IssuePullRequestsResponse,InboxItem,InboxWorkspaceUnread,Label,@@ -409,6 +409,7 @@ export const GitHubPullRequestSchema = z.object({closed_at: z.string().nullable(),pr_created_at: z.string(),pr_updated_at: z.string(),+ link_source: z.enum(["manual", "title", "branch", "auto"]).optional().catch(undefined),mergeable: z.string().nullable().optional(),merge_state_status: z.string().nullable().optional(),snapshot_available: z.boolean().optional(),@@ -428,12 +429,23 @@ export const GitHubPullRequestSchema = z.object({changed_files: z.number().optional().default(0),}).loose();+// A malformed auto_complete block degrades to null (the issue page shows no+// automation line) instead of discarding the PR list with it.+export const PRAutoCompleteSchema = z.object({+ state: z.string(),+ pull_request_ids: z.array(z.string()).default([]),+ issue_disabled: z.boolean().default(false),+ workspace_enabled: z.boolean().default(true),+}).loose();+export const IssuePullRequestsResponseSchema = z.object({pull_requests: z.array(GitHubPullRequestSchema).default([]),+ auto_complete: PRAutoCompleteSchema.nullable().optional().default(null).catch(null),}).loose();-export const EMPTY_ISSUE_PULL_REQUESTS_RESPONSE: { pull_requests: GitHubPullRequest[] } = {+export const EMPTY_ISSUE_PULL_REQUESTS_RESPONSE: IssuePullRequestsResponse = {pull_requests: [],+ auto_complete: null,};// Label responses are consumed by settings tables and resource pickers. Keepdiff --git a/packages/core/github/index.ts b/packages/core/github/index.tsindex 387a5f39ab..dde1485c9c 100644--- a/packages/core/github/index.ts+++ b/packages/core/github/index.ts@@ -1,4 +1,5 @@export * from "./queries";+export * from "./mutations";export * from "./pull-request-status";export * from "./settings";export * from "./use-github-settings";diff --git a/packages/core/github/mutations.ts b/packages/core/github/mutations.tsnew file mode 100644index 0000000000..59200b7e32--- /dev/null+++ b/packages/core/github/mutations.ts@@ -0,0 +1,40 @@+import { useMutation, useQueryClient } from "@tanstack/react-query";+import { api } from "../api";+import type { IssuePullRequestsResponse } from "../types";+import { githubKeys } from "./queries";++// Each endpoint answers with the issue's fresh PR list and auto-complete+// decision, so the cache is replaced with the server's answer rather than+// patched optimistically. A status change the action caused (auto-complete)+// arrives through the issue:updated realtime event.+function useWritePullRequests(issueId: string) {+ const qc = useQueryClient();+ return (data: IssuePullRequestsResponse) => {+ qc.setQueryData(githubKeys.pullRequests(issueId), data);+ };+}++export function useLinkIssuePullRequest(issueId: string) {+ const write = useWritePullRequests(issueId);+ return useMutation({+ mutationFn: (body: { url: string } | { pull_request_id: string }) =>+ api.linkIssuePullRequest(issueId, body),+ onSuccess: write,+ });+}++export function useUnlinkIssuePullRequest(issueId: string) {+ const write = useWritePullRequests(issueId);+ return useMutation({+ mutationFn: (pullRequestId: string) => api.unlinkIssuePullRequest(issueId, pullRequestId),+ onSuccess: write,+ });+}++export function useSetIssuePRAutoComplete(issueId: string) {+ const write = useWritePullRequests(issueId);+ return useMutation({+ mutationFn: (disabled: boolean) => api.setIssuePRAutoComplete(issueId, disabled),+ onSuccess: write,+ });+}diff --git a/packages/core/github/settings.test.ts b/packages/core/github/settings.test.tsindex d277dfaaf6..6c03665c3e 100644--- a/packages/core/github/settings.test.ts+++ b/packages/core/github/settings.test.ts@@ -1,5 +1,5 @@import { describe, it, expect } from "vitest";-import { deriveGitHubSettings } from "./settings";+import { deriveGitHubSettings, derivePRAutoCompleteEnabled } from "./settings";import type { Workspace } from "../types";function ws(settings: Record<string, unknown>): Pick<Workspace, "settings"> {@@ -64,3 +64,15 @@ describe("deriveGitHubSettings", () => {).toMatchObject({ enabled: true, prSidebar: true });});});++describe("derivePRAutoCompleteEnabled", () => {+ it("is on unless explicitly turned off", () => {+ expect(derivePRAutoCompleteEnabled(null)).toBe(true);+ expect(derivePRAutoCompleteEnabled(ws({}))).toBe(true);+ expect(derivePRAutoCompleteEnabled(ws({ pr_auto_complete_enabled: false }))).toBe(false);+ });++ it("does not follow the GitHub master switch", () => {+ expect(derivePRAutoCompleteEnabled(ws({ github_enabled: false }))).toBe(true);+ });+});diff --git a/packages/core/github/settings.ts b/packages/core/github/settings.tsindex 5a6c66d5cb..9440ec6273 100644--- a/packages/core/github/settings.ts+++ b/packages/core/github/settings.ts@@ -27,3 +27,15 @@ export function deriveGitHubSettings(autoLinkPRs: enabled && s.github_auto_link_prs_enabled !== false,};}++/**+ * Workspace-wide PR auto-complete: when every PR linked to an issue is merged,+ * the issue moves to Done. Absent means on. Not GitHub-specific — self-hosted+ * providers follow the same setting — so it ignores the GitHub master switch.+ */+export function derivePRAutoCompleteEnabled(+ workspace: Pick<Workspace, "settings"> | null | undefined,+): boolean {+ const s = (workspace?.settings ?? {}) as Record<string, unknown>;+ return s.pr_auto_complete_enabled !== false;+}diff --git a/packages/core/types/github.ts b/packages/core/types/github.tsindex 8d40424e5a..d39b1390ea 100644--- a/packages/core/types/github.ts+++ b/packages/core/types/github.ts@@ -57,6 +57,38 @@ export interface GitHubInstallation {connected_by?: string;}+/** Why a PR is on an issue: linked by hand, or matched in its title / branch.+ * "auto" is a link made under an older rule. */+export type PullRequestLinkSource = "manual" | "title" | "branch" | "auto";++/** What the "every linked PR merged → Done" rule will do for one issue. The+ * server computes it; the issue page only renders it. */+export type PRAutoCompleteState =+ | "none"+ | "workspace_disabled"+ | "issue_disabled"+ | "terminal"+ | "triage"+ | "waiting"+ | "not_merged"+ | "all_merged";++export interface PRAutoComplete {+ /** Unknown future states are kept as strings; the UI renders nothing for them. */+ state: PRAutoCompleteState | (string & {});+ /** PRs the state is about: still open for `waiting`, closed without merging+ * for `not_merged`, every linked PR for `all_merged`. */+ pull_request_ids: string[];+ issue_disabled: boolean;+ workspace_enabled: boolean;+}++export interface IssuePullRequestsResponse {+ pull_requests: GitHubPullRequest[];+ /** Absent on older backends. */+ auto_complete: PRAutoComplete | null;+}+export interface GitHubPullRequest {id: string;/** Source provider. Older GitHub-only backends omit it. */@@ -75,6 +107,8 @@ export interface GitHubPullRequest {closed_at: string | null;pr_created_at: string;pr_updated_at: string;+ /** Only set on an issue's PR list. Older backends omit it. */+ link_source?: PullRequestLinkSource;/** Conflict verdict from the GitHub API snapshot. Answers ONLY* "is there a conflict"; older backends omit it. */mergeable?: GitHubPullRequestMergeable | null;diff --git a/packages/core/types/index.ts b/packages/core/types/index.tsindex 17e85f789f..c80945219a 100644--- a/packages/core/types/index.ts+++ b/packages/core/types/index.ts@@ -200,6 +200,10 @@ export type {GitHubPullRequestMergeable,GitHubPullRequestMergeStateStatus,GitHubPullRequestState,+ IssuePullRequestsResponse,+ PRAutoComplete,+ PRAutoCompleteState,+ PullRequestLinkSource,ListGitHubInstallationsResponse,GitHubRepository,ListGitHubRepositoriesResponse,diff --git a/packages/views/issues/components/issue-detail.test.tsx b/packages/views/issues/components/issue-detail.test.tsxindex 0ce6bdcc1b..dbf446630b 100644--- a/packages/views/issues/components/issue-detail.test.tsx+++ b/packages/views/issues/components/issue-detail.test.tsx@@ -1847,6 +1847,38 @@ describe("IssueDetail (shared)", () => {expect(screen.getAllByRole("link", { name: "MUL-9" })).toHaveLength(2);});+ // MUL-7429: an automatic status change says why, and the per-issue switch+ // shows on the timeline.+ it("explains PR auto-complete activity", async () => {+ mockApiObj.listTimeline.mockResolvedValue([+ {+ type: "activity",+ id: "act-pr-done",+ actor_type: "system",+ actor_id: null,+ action: "status_changed",+ details: { from: "in_progress", to: "done", source: "pr_automation", pull_requests: "#12, #19" },+ created_at: "2026-01-18T00:00:00Z",+ },+ {+ type: "activity",+ id: "act-pr-off",+ actor_type: "member",+ actor_id: "user-1",+ action: "pr_auto_complete_changed",+ details: { disabled: true },+ created_at: "2026-01-18T01:00:00Z",+ },+ ] as unknown as TimelineEntry[]);++ renderIssueDetail();++ await waitFor(() => {+ expect(screen.getByText(/after every linked PR merged \(#12, #19\)/i)).toBeInTheDocument();+ });+ expect(screen.getByText(/turned off PR auto-complete for this issue/i)).toBeInTheDocument();+ });+it("renders activity rows with unknown status values without crashing", async () => {mockApiObj.listTimeline.mockResolvedValue([{diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsxindex 3c808adb65..10cf54d6e9 100644--- a/packages/views/issues/components/issue-detail.tsx+++ b/packages/views/issues/components/issue-detail.tsx@@ -103,7 +103,7 @@ import { ExecutionLogSection } from "./execution-log-section";import { WakeupsSection } from "./wakeups-section";import { QuickActionsSection } from "./quick-actions-section";import { PluginPanelSection } from "../../plugins";-import { PullRequestList } from "./pull-request-list";+import { PullRequestsSection } from "./pull-requests-section";import { useGitHubSettings } from "@multica/core/github";import { useQuery } from "@tanstack/react-query";import { useAuthStore } from "@multica/core/auth";@@ -308,10 +308,22 @@ function formatActivity(case "created":return t(($) => $.activity.created);case "status_changed":+ // PR auto-complete (MUL-7429) says why the status moved.+ if (details.source === "pr_automation") {+ return t(($) => $.activity.status_changed_pr, {+ from: statusLabel(details.from ?? "?", t, resolveStatusLabel),+ to: statusLabel(details.to ?? "?", t, resolveStatusLabel),+ prs: details.pull_requests ?? "",+ });+ }return t(($) => $.activity.status_changed, {from: statusLabel(details.from ?? "?", t, resolveStatusLabel),to: statusLabel(details.to ?? "?", t, resolveStatusLabel),});+ case "pr_auto_complete_changed":+ return (entry.details as { disabled?: unknown } | undefined)?.disabled === true+ ? t(($) => $.activity.pr_auto_complete_disabled)+ : t(($) => $.activity.pr_auto_complete_enabled);case "priority_changed":return t(($) => $.activity.priority_changed, {from: priorityLabel(details.from ?? "?", t),@@ -2664,17 +2676,12 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr(or the GitHub master switch is off). Backend data is kept eitherway so re-enabling restores the section instantly. */}{githubSettings.prSidebar && (- <div>- <button- type="button"- className={`flex w-full items-center gap-1 rounded-md px-2 py-1 text-caption font-medium transition-colors mb-2 hover:bg-accent/70 ${pullRequestsOpen ? "" : "text-muted-foreground hover:text-foreground"}`}- onClick={() => setPullRequestsOpen(!pullRequestsOpen)}- >- {t(($) => $.detail.section_pull_requests)}- <ChevronRight className={`!size-3 shrink-0 stroke-[2.5] text-muted-foreground transition-transform ${pullRequestsOpen ? "rotate-90" : ""}`} />- </button>- {pullRequestsOpen && <div className="pl-2"><PullRequestList issueId={id} /></div>}- </div>+ <PullRequestsSection+ issueId={id}+ identifier={issue.identifier}+ open={pullRequestsOpen}+ onOpenChange={setPullRequestsOpen}+ />)}{/* Execution log — active runs + collapsed past runs, each carrying itsdiff --git a/packages/views/issues/components/pull-request-list.test.tsx b/packages/views/issues/components/pull-request-list.test.tsxindex d432e5ca77..3a07eae90c 100644--- a/packages/views/issues/components/pull-request-list.test.tsx+++ b/packages/views/issues/components/pull-request-list.test.tsx@@ -1,8 +1,8 @@-import { describe, expect, it, vi } from "vitest";-import { render, screen } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { fireEvent, render, screen, waitFor } from "@testing-library/react";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { I18nProvider } from "@multica/core/i18n/react";-import type { GitHubPullRequest } from "@multica/core/types";+import type { GitHubPullRequest, PRAutoComplete } from "@multica/core/types";import enCommon from "../../locales/en/common.json";import enIssues from "../../locales/en/issues.json";@@ -16,15 +16,37 @@ vi.mock("@multica/core/github/queries", async () => {...actual,issuePullRequestsOptions: (issueId: string) => ({queryKey: ["github", "pull-requests", issueId],- queryFn: async () => ({ pull_requests: mockPRs }),+ queryFn: async () => ({ pull_requests: mockPRs, auto_complete: mockAutoComplete }),enabled: !!issueId,}),};});+const apiMock = vi.hoisted(() => ({+ unlinkIssuePullRequest: vi.fn(),+ linkIssuePullRequest: vi.fn(),+ setIssuePRAutoComplete: vi.fn(),+}));+vi.mock("@multica/core/api", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@multica/core/api")>()),+ api: apiMock,+}));+const toastMock = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn() }));+vi.mock("sonner", () => ({ toast: toastMock }));+vi.mock("@multica/core/paths", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@multica/core/paths")>()),+ useWorkspacePaths: () => ({ settings: () => "/acme/settings" }),+}));+vi.mock("../../navigation", () => ({+ AppLink: ({ href, children, className }: { href: string; children: React.ReactNode; className?: string }) => (+ <a href={href} className={className}>{children}</a>+ ),+}));+import { PullRequestList } from "./pull-request-list";let mockPRs: GitHubPullRequest[] = [];+let mockAutoComplete: PRAutoComplete | null = null;function makePR(overrides: Partial<GitHubPullRequest> = {}): GitHubPullRequest {return {@@ -67,7 +89,7 @@ function renderList() {return render(<QueryClientProvider client={qc}><I18nProvider resources={TEST_RESOURCES} locale="en">- <PullRequestList issueId="issue-1" />+ <PullRequestList issueId="issue-1" identifier="MUL-1" /></I18nProvider></QueryClientProvider>,);@@ -354,3 +376,89 @@ describe("PullRequestList sidebar rows", () => {expect(screen.getByText("Show 1 more")).toBeInTheDocument();});});++// MUL-7429: the line under the list says what "every linked PR merged → Done"+// will do, straight from the server's decision, and each row can be removed.+describe("PullRequestList auto-complete", () => {+ beforeEach(() => {+ mockAutoComplete = null;+ apiMock.unlinkIssuePullRequest.mockReset();+ apiMock.linkIssuePullRequest.mockReset();+ apiMock.setIssuePRAutoComplete.mockReset();+ toastMock.success.mockReset();+ });++ const decision = (state: string, ids: string[] = [], extra: Partial<PRAutoComplete> = {}): PRAutoComplete => ({+ state,+ pull_request_ids: ids,+ issue_disabled: false,+ workspace_enabled: true,+ ...extra,+ });++ it("names the PR the issue is waiting on", async () => {+ mockPRs = [makePR({ id: "a", number: 12, state: "merged" }), makePR({ id: "b", number: 19 })];+ mockAutoComplete = decision("waiting", ["b"]);+ renderList();+ expect(await screen.findByText("Completes when #19 merges")).toBeInTheDocument();+ });++ it("offers to remove a PR that closed without merging", async () => {+ mockPRs = [makePR({ id: "a", number: 12, state: "merged" }), makePR({ id: "b", number: 19, state: "closed" })];+ mockAutoComplete = decision("not_merged", ["b"]);+ apiMock.unlinkIssuePullRequest.mockResolvedValue({ pull_requests: [], auto_complete: decision("terminal") });+ renderList();+ const line = await screen.findByTestId("pr-auto-complete-line");+ expect(line).toHaveTextContent("#19 closed without merging");+ fireEvent.click(screen.getByRole("button", { name: "Remove" }));+ await waitFor(() => expect(apiMock.unlinkIssuePullRequest).toHaveBeenCalledWith("issue-1", "b"));+ // Removing the last unmerged PR completed the issue; the toast says so and+ // offers no undo.+ await waitFor(() =>+ expect(toastMock.success).toHaveBeenCalledWith("Removed #19. Every remaining PR is merged, so the issue is done."),+ );+ });++ it("links the workspace setting when auto-complete is off there", async () => {+ mockPRs = [makePR({ id: "a", number: 12, state: "merged" })];+ mockAutoComplete = decision("workspace_disabled", [], { workspace_enabled: false });+ renderList();+ expect(await screen.findByTestId("pr-auto-complete-line")).toHaveTextContent("PR auto-complete is off for this workspace");+ expect(screen.getByText("Settings").closest("a")?.getAttribute("href")).toBe("/acme/settings?tab=issue-statuses");+ });++ it("turns auto-complete back on for the issue from the line", async () => {+ mockPRs = [makePR({ id: "a", number: 12 })];+ mockAutoComplete = decision("issue_disabled", [], { issue_disabled: true });+ apiMock.setIssuePRAutoComplete.mockResolvedValue({ pull_requests: mockPRs, auto_complete: decision("waiting", ["a"]) });+ renderList();+ fireEvent.click(await screen.findByRole("button", { name: "Turn on" }));+ await waitFor(() => expect(apiMock.setIssuePRAutoComplete).toHaveBeenCalledWith("issue-1", false));+ });++ it("says nothing for a finished issue", async () => {+ mockPRs = [makePR({ id: "a", number: 12, state: "merged" })];+ mockAutoComplete = decision("terminal");+ renderList();+ await waitForRender();+ expect(screen.queryByTestId("pr-auto-complete-line")).toBeNull();+ });++ it("hides row actions and the line on a backend without auto-complete", async () => {+ mockPRs = [makePR({ id: "a", number: 12 })];+ mockAutoComplete = null;+ renderList();+ await waitForRender();+ expect(screen.queryByRole("button", { name: "Pull request actions" })).toBeNull();+ expect(screen.queryByTestId("pr-auto-complete-line")).toBeNull();+ });++ it("explains how a PR was linked in its menu", async () => {+ mockPRs = [makePR({ id: "a", number: 12, link_source: "title" })];+ mockAutoComplete = decision("waiting", ["a"]);+ renderList();+ fireEvent.click(await screen.findByRole("button", { name: "Pull request actions" }));+ expect(await screen.findByText("Linked by MUL-1 in the title")).toBeInTheDocument();+ expect(screen.getByRole("menuitem", { name: "Remove from issue" })).toBeInTheDocument();+ });+});diff --git a/packages/views/issues/components/pull-request-list.tsx b/packages/views/issues/components/pull-request-list.tsxindex aabbb66e2f..54a1ee3180 100644--- a/packages/views/issues/components/pull-request-list.tsx+++ b/packages/views/issues/components/pull-request-list.tsx@@ -2,12 +2,15 @@import { useState } from "react";import { useQuery } from "@tanstack/react-query";+import { toast } from "sonner";import {CheckCircle2,Circle,CircleDashed,CircleSlash,GitMerge,+ MoreHorizontal,+ Unlink,GitPullRequest,GitPullRequestArrow,GitPullRequestClosed,@@ -20,15 +23,34 @@ import {deriveChecksStatus,deriveMergeStatus,shouldShowPullRequestStats,+ useLinkIssuePullRequest,+ useSetIssuePRAutoComplete,+ useUnlinkIssuePullRequest,type PullRequestChecksStatus,type PullRequestMergeStatus,} from "@multica/core/github";-import type { GitHubPullRequest, GitHubPullRequestState } from "@multica/core/types";+import { useWorkspacePaths } from "@multica/core/paths";+import type {+ GitHubPullRequest,+ GitHubPullRequestState,+ PRAutoComplete,+} from "@multica/core/types";+import { Button } from "@multica/ui/components/ui/button";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuGroup,+ DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuTrigger,+} from "@multica/ui/components/ui/dropdown-menu";import { cn } from "@multica/ui/lib/utils";+import { AppLink } from "../../navigation";import { useT, useTimeAgo } from "../../i18n";type IssuesT = ReturnType<typeof useT<"issues">>["t"];+// Keep the existing sidebar density: show the first 3 PR rows inline, then// collapse the rest once the section reaches 4 rows.const PR_LIMIT_BEFORE_COLLAPSE = 4;@@ -43,11 +65,22 @@ const STATE_ICON: Record<closed: { icon: GitPullRequestClosed, className: "text-rose-600 dark:text-rose-400" },};-export function PullRequestList({ issueId }: { issueId: string }) {+export function PullRequestList({+ issueId,+ identifier = "",+}: {+ issueId: string;+ /** The issue's identifier, for the "linked by MUL-1 in the title" label. */+ identifier?: string;+}) {const { t } = useT("issues");const [expanded, setExpanded] = useState(false);const { data, isLoading } = useQuery(issuePullRequestsOptions(issueId));const prs = data?.pull_requests ?? [];+ // Older backends send no auto-complete block and have no link/unlink+ // endpoints, so the row actions stay hidden with it.+ const autoComplete = data?.auto_complete ?? null;+ const rowActions = autoComplete ? { issueId, identifier, autoComplete } : null;if (isLoading) {return <p className="text-caption text-muted-foreground px-2">{t(($) => $.detail.pull_requests_loading)}</p>;@@ -71,12 +104,12 @@ export function PullRequestList({ issueId }: { issueId: string }) {return (<div className="space-y-1">{expandedHead.map((pr) => (- <PullRequestRow key={pr.id} pr={pr} />+ <PullRequestRow key={pr.id} pr={pr} actions={rowActions} />))}{useCollapse ? (<div className="space-y-1">{expanded- ? collapsedTail.map((pr) => <PullRequestRow key={pr.id} pr={pr} />)+ ? collapsedTail.map((pr) => <PullRequestRow key={pr.id} pr={pr} actions={rowActions} />): null}<buttontype="button"@@ -89,25 +122,214 @@ export function PullRequestList({ issueId }: { issueId: string }) {</button></div>) : null}+ {autoComplete ? (+ <AutoCompleteLine issueId={issueId} prs={prs} autoComplete={autoComplete} />+ ) : null}</div>);}-function PullRequestRow({ pr }: { pr: GitHubPullRequest }) {++interface RowActions {+ issueId: string;+ identifier: string;+ autoComplete: PRAutoComplete;+}++const prLabel = (pr: Pick<GitHubPullRequest, "number">) => `#${pr.number}`;++/**+ * Remove a PR from the issue. The server remembers the removal (webhooks will+ * not link it again) and treats it as a PR event, so removing the last+ * unmerged PR can complete the issue — the toast says so, and offers undo only+ * when nothing else changed.+ */+function useUnlinkPullRequest(issueId: string, before: PRAutoComplete) {+ const { t } = useT("issues");+ const unlink = useUnlinkIssuePullRequest(issueId);+ const relink = useLinkIssuePullRequest(issueId);+ return (pr: GitHubPullRequest) => {+ unlink.mutate(pr.id, {+ onSuccess: (after) => {+ const completed =+ before.state !== "terminal" && after.auto_complete?.state === "terminal";+ if (completed) {+ toast.success(t(($) => $.pr_automation.unlinked_completed, { pr: prLabel(pr) }));+ return;+ }+ toast.success(t(($) => $.pr_automation.unlinked, { pr: prLabel(pr) }), {+ action: {+ label: t(($) => $.pr_automation.undo),+ onClick: () => relink.mutate({ pull_request_id: pr.id }),+ },+ });+ },+ onError: () => toast.error(t(($) => $.pr_automation.unlink_failed)),+ });+ };+}++function linkSourceLabel(pr: GitHubPullRequest, identifier: string, t: IssuesT): string {+ switch (pr.link_source) {+ case "manual":+ return t(($) => $.pr_automation.source_manual);+ case "title":+ return t(($) => $.pr_automation.source_title, { identifier });+ case "branch":+ return t(($) => $.pr_automation.source_branch);+ default:+ return t(($) => $.pr_automation.source_auto);+ }+}++function PullRequestRowMenu({ pr, actions }: { pr: GitHubPullRequest; actions: RowActions }) {+ const { t } = useT("issues");+ const unlink = useUnlinkPullRequest(actions.issueId, actions.autoComplete);+ return (+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button+ variant="ghost"+ size="icon-xs"+ aria-label={t(($) => $.pr_automation.row_menu)}+ className="absolute top-1 right-0 opacity-0 group-hover/pr:opacity-100 group-focus-within/pr:opacity-100 data-popup-open:opacity-100 [@media(pointer:coarse)]:opacity-100"+ >+ <MoreHorizontal />+ </Button>+ }+ />+ <DropdownMenuContent align="end" className="w-56">+ <DropdownMenuGroup>+ <DropdownMenuLabel className="font-normal">+ {linkSourceLabel(pr, actions.identifier, t)}+ </DropdownMenuLabel>+ <DropdownMenuItem onClick={() => unlink(pr)}>+ <Unlink />+ {t(($) => $.pr_automation.unlink)}+ </DropdownMenuItem>+ </DropdownMenuGroup>+ </DropdownMenuContent>+ </DropdownMenu>+ );+}++/**+ * One line under the PR list saying what the "every linked PR merged → Done"+ * rule will do for this issue, straight from the server's decision. Terminal,+ * triage and unknown states render nothing.+ */+function AutoCompleteLine({+ issueId,+ prs,+ autoComplete,+}: {+ issueId: string;+ prs: GitHubPullRequest[];+ autoComplete: PRAutoComplete;+}) {+ const { t } = useT("issues");+ const paths = useWorkspacePaths();+ const unlink = useUnlinkPullRequest(issueId, autoComplete);+ const setAutoComplete = useSetIssuePRAutoComplete(issueId);+ const named = autoComplete.pull_request_ids+ .map((id) => prs.find((pr) => pr.id === id))+ .filter((pr): pr is GitHubPullRequest => !!pr);+ const list = named.map(prLabel).join(", ");+ const action = (label: string, onClick: () => void) => (+ <button+ type="button"+ onClick={onClick}+ className="font-medium text-foreground underline decoration-border underline-offset-2 hover:decoration-foreground"+ >+ {label}+ </button>+ );++ let icon: React.ReactNode;+ let body: React.ReactNode;+ switch (autoComplete.state) {+ case "waiting":+ if (named.length === 0) return null;+ icon = <CircleDashed className="text-muted-foreground" />;+ body = t(($) => $.pr_automation.waiting, { count: named.length, prs: list });+ break;+ case "not_merged": {+ if (named.length === 0) return null;+ const only = named.length === 1 ? named[0] : undefined;+ icon = <TriangleAlert className="text-amber-600 dark:text-amber-400" />;+ body = (+ <>+ {t(($) => $.pr_automation.not_merged, { prs: list })}+ {only ? <> · {action(t(($) => $.pr_automation.not_merged_action), () => unlink(only))}</> : null}+ </>+ );+ break;+ }+ case "all_merged":+ icon = <CheckCircle2 className="text-muted-foreground" />;+ body = t(($) => $.pr_automation.all_merged);+ break;+ case "issue_disabled":+ icon = <CircleSlash className="text-muted-foreground" />;+ body = (+ <>+ {t(($) => $.pr_automation.issue_disabled)} ·{" "}+ {action(t(($) => $.pr_automation.issue_disabled_action), () =>+ setAutoComplete.mutate(false, {+ onError: () => toast.error(t(($) => $.pr_automation.update_failed)),+ }),+ )}+ </>+ );+ break;+ case "workspace_disabled":+ icon = <CircleSlash className="text-muted-foreground" />;+ body = (+ <>+ {t(($) => $.pr_automation.workspace_disabled)} ·{" "}+ <AppLink+ href={`${paths.settings()}?tab=issue-statuses`}+ className="font-medium text-foreground underline decoration-border underline-offset-2 hover:decoration-foreground"+ >+ {t(($) => $.pr_automation.workspace_disabled_action)}+ </AppLink>+ </>+ );+ break;+ default:+ return null;+ }+ return (+ <p+ data-testid="pr-auto-complete-line"+ className="mt-1 flex items-start gap-1.5 border-t border-border pt-2 text-caption text-muted-foreground [&>svg]:mt-0.5 [&>svg]:size-3.5 [&>svg]:shrink-0"+ >+ {icon}+ <span className="min-w-0">{body}</span>+ </p>+ );+}++function PullRequestRow({ pr, actions }: { pr: GitHubPullRequest; actions: RowActions | null }) {const { t } = useT("issues");const cfg = STATE_ICON[pr.state] ?? { icon: GitPullRequest, className: "" };const StateIcon = cfg.icon;const isDraft = pr.state === "draft";const stateLabel = getStateLabel(pr.state, t);+ // The row link and its menu are siblings: a button inside an anchor is+ // invalid HTML, and the menu must not open the PR.return (+ <div className="group/pr relative -mx-2 rounded-md transition-colors hover:bg-accent/50"><adata-testid="pull-request-row"href={pr.html_url}target="_blank"rel="noreferrer noopener"className={cn(- "flex items-start gap-2 rounded-md px-2 py-1.5 -mx-2 hover:bg-accent/50 transition-colors group",+ "flex items-start gap-2 rounded-md px-2 py-1.5 group",+ actions ? "pr-7" : null,isDraft ? "opacity-80" : null,)}>@@ -123,6 +345,8 @@ function PullRequestRow({ pr }: { pr: GitHubPullRequest }) {<PullRequestRowDetails pr={pr} /></div></a>+ {actions ? <PullRequestRowMenu pr={pr} actions={actions} /> : null}+ </div>);}diff --git a/packages/views/issues/components/pull-requests-section.test.tsx b/packages/views/issues/components/pull-requests-section.test.tsxnew file mode 100644index 0000000000..1c3e4122c5--- /dev/null+++ b/packages/views/issues/components/pull-requests-section.test.tsx@@ -0,0 +1,129 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { I18nProvider } from "@multica/core/i18n/react";+import { ApiError } from "@multica/core/api";+import type { PRAutoComplete } from "@multica/core/types";+import enCommon from "../../locales/en/common.json";+import enIssues from "../../locales/en/issues.json";++const TEST_RESOURCES = { en: { common: enCommon, issues: enIssues } };++let mockAutoComplete: PRAutoComplete | null = null;+vi.mock("@multica/core/github/queries", async () => {+ const actual = await vi.importActual<typeof import("@multica/core/github/queries")>(+ "@multica/core/github/queries",+ );+ return {+ ...actual,+ issuePullRequestsOptions: (issueId: string) => ({+ queryKey: ["github", "pull-requests", issueId],+ queryFn: async () => ({ pull_requests: [], auto_complete: mockAutoComplete }),+ enabled: !!issueId,+ }),+ };+});+const apiMock = vi.hoisted(() => ({+ linkIssuePullRequest: vi.fn(),+ setIssuePRAutoComplete: vi.fn(),+}));+vi.mock("@multica/core/api", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@multica/core/api")>()),+ api: apiMock,+}));+const navigatePush = vi.hoisted(() => vi.fn());+vi.mock("../../navigation", () => ({+ useNavigation: () => ({ push: navigatePush }),+ AppLink: ({ href, children }: { href: string; children: React.ReactNode }) => <a href={href}>{children}</a>,+}));+vi.mock("@multica/core/paths", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@multica/core/paths")>()),+ useWorkspacePaths: () => ({ settings: () => "/acme/settings" }),+}));++import { PullRequestsSection } from "./pull-requests-section";++function renderSection() {+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ return render(+ <QueryClientProvider client={qc}>+ <I18nProvider resources={TEST_RESOURCES} locale="en">+ <PullRequestsSection issueId="issue-1" identifier="MUL-1" open onOpenChange={() => {}} />+ </I18nProvider>+ </QueryClientProvider>,+ );+}++const decision: PRAutoComplete = {+ state: "none",+ pull_request_ids: [],+ issue_disabled: false,+ workspace_enabled: true,+};++describe("PullRequestsSection (MUL-7429)", () => {+ beforeEach(() => {+ mockAutoComplete = decision;+ apiMock.linkIssuePullRequest.mockReset();+ apiMock.setIssuePRAutoComplete.mockReset();+ navigatePush.mockReset();+ });++ it("links a pasted PR URL", async () => {+ apiMock.linkIssuePullRequest.mockResolvedValue({ pull_requests: [], auto_complete: decision });+ renderSection();+ fireEvent.click(await screen.findByRole("button", { name: "Link pull request" }));+ fireEvent.change(await screen.findByRole("textbox", { name: "Link pull request" }), {+ target: { value: "https://github.com/acme/widget/pull/41" },+ });+ expect(screen.getByText("PRs with MUL-1 in the title or branch name link automatically.")).toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Link" }));+ await waitFor(() =>+ expect(apiMock.linkIssuePullRequest).toHaveBeenCalledWith("issue-1", {+ url: "https://github.com/acme/widget/pull/41",+ }),+ );+ });++ it("accepts a link pasted without a scheme", async () => {+ apiMock.linkIssuePullRequest.mockResolvedValue({ pull_requests: [], auto_complete: decision });+ renderSection();+ fireEvent.click(await screen.findByRole("button", { name: "Link pull request" }));+ fireEvent.change(await screen.findByRole("textbox", { name: "Link pull request" }), {+ target: { value: "github.com/acme/widget/pull/41/files" },+ });+ fireEvent.submit(screen.getByRole("textbox", { name: "Link pull request" }).closest("form")!);+ await waitFor(() =>+ expect(apiMock.linkIssuePullRequest).toHaveBeenCalledWith("issue-1", { url: "github.com/acme/widget/pull/41/files" }),+ );+ });++ it("explains a PR Multica has not received", async () => {+ apiMock.linkIssuePullRequest.mockRejectedValue(new ApiError("not found", 404, "Not Found"));+ renderSection();+ fireEvent.click(await screen.findByRole("button", { name: "Link pull request" }));+ fireEvent.change(await screen.findByRole("textbox", { name: "Link pull request" }), {+ target: { value: "https://github.com/acme/widget/pull/999" },+ });+ fireEvent.click(screen.getByRole("button", { name: "Link" }));+ expect(await screen.findByRole("alert")).toHaveTextContent(+ "Multica hasn’t received this PR yet. Check that its repository is connected.",+ );+ });++ it("turns auto-complete off for this issue from the section menu", async () => {+ apiMock.setIssuePRAutoComplete.mockResolvedValue({ pull_requests: [], auto_complete: { ...decision, issue_disabled: true } });+ renderSection();+ fireEvent.click(await screen.findByRole("button", { name: "Pull request automation" }));+ fireEvent.click(await screen.findByRole("menuitem", { name: "Don’t auto-complete this issue" }));+ await waitFor(() => expect(apiMock.setIssuePRAutoComplete).toHaveBeenCalledWith("issue-1", true));+ });++ it("hides the actions on a backend without auto-complete", async () => {+ mockAutoComplete = null;+ renderSection();+ await screen.findByText("No linked pull requests.");+ expect(screen.queryByRole("button", { name: "Link pull request" })).toBeNull();+ expect(screen.queryByRole("button", { name: "Pull request automation" })).toBeNull();+ });+});diff --git a/packages/views/issues/components/pull-requests-section.tsx b/packages/views/issues/components/pull-requests-section.tsxnew file mode 100644index 0000000000..4d817c0088--- /dev/null+++ b/packages/views/issues/components/pull-requests-section.tsx@@ -0,0 +1,217 @@+"use client";++import { useState } from "react";+import { useQuery } from "@tanstack/react-query";+import { toast } from "sonner";+import { ChevronRight, CircleSlash, MoreHorizontal, Plus, RotateCcw, Settings } from "lucide-react";+import { ApiError } from "@multica/core/api";+import {+ issuePullRequestsOptions,+ useLinkIssuePullRequest,+ useSetIssuePRAutoComplete,+} from "@multica/core/github";+import { useWorkspacePaths } from "@multica/core/paths";+import { Button } from "@multica/ui/components/ui/button";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "@multica/ui/components/ui/dropdown-menu";+import { Input } from "@multica/ui/components/ui/input";+import { Popover, PopoverContent, PopoverTrigger } from "@multica/ui/components/ui/popover";+import { useNavigation } from "../../navigation";+import { useT } from "../../i18n";+import { PullRequestList } from "./pull-request-list";++/**+ * The issue sidebar's Pull requests section: the linked PRs, what the+ * "every linked PR merged → Done" rule will do for this issue, and the two+ * exceptions a person can make — link a PR by hand, or turn auto-complete off+ * for this one issue (MUL-7429).+ */+export function PullRequestsSection({+ issueId,+ identifier,+ open,+ onOpenChange,+}: {+ issueId: string;+ identifier: string;+ open: boolean;+ onOpenChange: (open: boolean) => void;+}) {+ const { t } = useT("issues");+ const { data } = useQuery(issuePullRequestsOptions(issueId));+ // Older backends have no link / auto-complete endpoints; keep the header+ // actions hidden until the server says it supports them.+ const supported = !!data?.auto_complete;++ return (+ <div>+ {/* Label and actions are siblings, not a button wrapping buttons. */}+ <div className="mb-2 flex w-full items-center gap-0.5">+ <button+ type="button"+ aria-expanded={open}+ className={`flex min-w-0 flex-1 items-center gap-1 rounded-md px-2 py-1 text-caption font-medium transition-colors hover:bg-accent/70 ${open ? "" : "text-muted-foreground hover:text-foreground"}`}+ onClick={() => onOpenChange(!open)}+ >+ <span className="truncate">{t(($) => $.detail.section_pull_requests)}</span>+ <ChevronRight className={`!size-3 shrink-0 stroke-[2.5] text-muted-foreground transition-transform ${open ? "rotate-90" : ""}`} />+ </button>+ {supported ? (+ <>+ <LinkPullRequestPopover issueId={issueId} identifier={identifier} onLinked={() => onOpenChange(true)} />+ <AutoCompleteMenu issueId={issueId} disabled={data?.auto_complete?.issue_disabled ?? false} />+ </>+ ) : null}+ </div>+ {open && (+ <div className="pl-2">+ <PullRequestList issueId={issueId} identifier={identifier} />+ </div>+ )}+ </div>+ );+}++function LinkPullRequestPopover({+ issueId,+ identifier,+ onLinked,+}: {+ issueId: string;+ identifier: string;+ onLinked: () => void;+}) {+ const { t } = useT("issues");+ const [open, setOpen] = useState(false);+ const [url, setUrl] = useState("");+ const link = useLinkIssuePullRequest(issueId);+ const error = link.error+ ? link.error instanceof ApiError && link.error.status === 404+ ? t(($) => $.pr_automation.link_not_found)+ : t(($) => $.pr_automation.link_failed)+ : null;++ return (+ <Popover+ open={open}+ onOpenChange={(next) => {+ setOpen(next);+ if (!next) {+ setUrl("");+ link.reset();+ }+ }}+ >+ <PopoverTrigger+ render={+ <Button variant="ghost" size="icon-xs" aria-label={t(($) => $.pr_automation.link_action)}>+ <Plus />+ </Button>+ }+ />+ <PopoverContent align="end" className="w-80">+ <form+ className="flex flex-col gap-2"+ onSubmit={(e) => {+ e.preventDefault();+ const value = url.trim();+ if (!value || link.isPending) return;+ link.mutate(+ { url: value },+ {+ onSuccess: () => {+ setOpen(false);+ setUrl("");+ onLinked();+ },+ },+ );+ }}+ >+ <label htmlFor={`link-pr-${issueId}`} className="text-caption font-medium">+ {t(($) => $.pr_automation.link_action)}+ </label>+ <Input+ id={`link-pr-${issueId}`}+ // Not type="url": the browser would block "github.com/…" without a+ // scheme, which the server accepts.+ type="text"+ inputMode="url"+ autoComplete="off"+ spellCheck={false}+ autoFocus+ value={url}+ placeholder={t(($) => $.pr_automation.link_placeholder)}+ aria-invalid={error ? true : undefined}+ aria-describedby={`link-pr-${issueId}-hint`}+ onChange={(e) => {+ setUrl(e.target.value);+ if (link.error) link.reset();+ }}+ />+ {error ? (+ <p role="alert" className="text-caption text-destructive">+ {error}+ </p>+ ) : (+ <p id={`link-pr-${issueId}-hint`} className="text-caption text-muted-foreground">+ {t(($) => $.pr_automation.link_hint, { identifier })}+ </p>+ )}+ <div className="flex justify-end">+ <Button+ type="submit"+ size="sm"+ disabled={!url.trim() || link.isPending}+ aria-busy={link.isPending || undefined}+ >+ {t(($) => $.pr_automation.link_submit)}+ </Button>+ </div>+ </form>+ </PopoverContent>+ </Popover>+ );+}++function AutoCompleteMenu({ issueId, disabled }: { issueId: string; disabled: boolean }) {+ const { t } = useT("issues");+ const paths = useWorkspacePaths();+ const navigation = useNavigation();+ const setAutoComplete = useSetIssuePRAutoComplete(issueId);++ return (+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button variant="ghost" size="icon-xs" aria-label={t(($) => $.pr_automation.section_menu)}>+ <MoreHorizontal />+ </Button>+ }+ />+ <DropdownMenuContent align="end" className="w-60">+ <DropdownMenuItem+ disabled={setAutoComplete.isPending}+ onClick={() =>+ setAutoComplete.mutate(!disabled, {+ onError: () => toast.error(t(($) => $.pr_automation.update_failed)),+ })+ }+ >+ {disabled ? <RotateCcw /> : <CircleSlash />}+ {disabled ? t(($) => $.pr_automation.enable) : t(($) => $.pr_automation.disable)}+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem onClick={() => navigation.push(`${paths.settings()}?tab=issue-statuses`)}>+ <Settings />+ {t(($) => $.pr_automation.settings)}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ );+}diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.jsonindex 372d0147ae..519ccfe1f1 100644--- a/packages/views/locales/en/issues.json+++ b/packages/views/locales/en/issues.json@@ -519,7 +519,10 @@"duplicate_unmarked_to": "unmarked this issue as a duplicate of {{identifier}} and moved it to {{status}}","duplicate_unmarked_original_deleted": "removed the duplicate mark, {{identifier}} was deleted","duplicate_added": "marked {{identifier}} as a duplicate of this issue",- "duplicate_removed": "unmarked {{identifier}} as a duplicate of this issue"+ "duplicate_removed": "unmarked {{identifier}} as a duplicate of this issue",+ "status_changed_pr": "changed status from {{from}} to {{to}} after every linked PR merged ({{prs}})",+ "pr_auto_complete_disabled": "turned off PR auto-complete for this issue",+ "pr_auto_complete_enabled": "turned PR auto-complete back on for this issue"},"comment": {"add_reaction": "Add reaction",@@ -1107,5 +1110,37 @@"unmark": "Not a duplicate","section_title": "Duplicates","unmark_toast": "Reopened as Todo"+ },+ "pr_automation": {+ "link_action": "Link pull request",+ "link_placeholder": "Paste a pull request URL",+ "link_hint": "PRs with {{identifier}} in the title or branch name link automatically.",+ "link_submit": "Link",+ "link_not_found": "Multica hasn’t received this PR yet. Check that its repository is connected.",+ "link_failed": "Couldn’t link the pull request.",+ "row_menu": "Pull request actions",+ "section_menu": "Pull request automation",+ "source_title": "Linked by {{identifier}} in the title",+ "source_branch": "Linked by the branch name",+ "source_manual": "Linked manually",+ "source_auto": "Linked automatically",+ "unlink": "Remove from issue",+ "unlinked": "Removed {{pr}}",+ "unlinked_completed": "Removed {{pr}}. Every remaining PR is merged, so the issue is done.",+ "unlink_failed": "Couldn’t remove the pull request.",+ "undo": "Undo",+ "disable": "Don’t auto-complete this issue",+ "enable": "Auto-complete this issue",+ "settings": "Auto-complete settings",+ "update_failed": "Couldn’t update auto-complete.",+ "waiting_one": "Completes when {{prs}} merges",+ "waiting_other": "Completes when {{prs}} merge",+ "not_merged": "{{prs}} closed without merging",+ "not_merged_action": "Remove",+ "all_merged": "All PRs merged. The next merged PR completes this issue.",+ "issue_disabled": "Auto-complete is off for this issue",+ "issue_disabled_action": "Turn on",+ "workspace_disabled": "PR auto-complete is off for this workspace",+ "workspace_disabled_action": "Settings"}}diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.jsonindex fac029e638..613cf4ea72 100644--- a/packages/views/locales/en/settings.json+++ b/packages/views/locales/en/settings.json@@ -81,7 +81,13 @@"blocked": "Stalled on an external dependency.","done": "Completed.","cancelled": "Decided not to do."- }+ },+ "automation_title": "Automation",+ "pr_auto_complete_label": "Complete issues when their PRs merge",+ "pr_auto_complete_description": "An issue moves to Done once every linked PR is merged. Applies to PRs merged from now on.",+ "pr_auto_complete_example": "PRs link by the issue ID in their title or branch name, e.g.",+ "pr_auto_complete_example_title": "MUL-123: Fix login redirect",+ "pr_auto_complete_badge": "Set when PRs merge"},"quick_actions": {"title": "Quick Actions",@@ -757,10 +763,6 @@"master_description_off": "GitHub features are paused. Existing data is kept.","section_connection": "Connection","connection_title": "GitHub App",- "connection_description_prefix": "Link issues to pull requests automatically. A PR links when",- "connection_description_suffix": "is in its branch name or title, or its body says Closes MUL-123. Merging a PR with that closing keyword also moves the issue to",- "connection_description_done": "Done",- "connection_identifier_example": "MUL-123","connected_to": "Connected to {{login}}","connect_github": "Connect GitHub","connect_opening": "Opening…",@@ -790,7 +792,12 @@"section_repositories": "Repositories","repositories_shortcut_label": "Repository URLs live in the Repositories tab","repositories_shortcut_link": "Manage repositories →",- "toast_failed": "Failed to update GitHub settings"+ "toast_failed": "Failed to update GitHub settings",+ "feature_auto_link_description": "Links a PR to the issue whose ID, e.g. {{example}}, is in its title or branch name.",+ "feature_pr_auto_complete_label": "Complete issues when their PRs merge",+ "feature_pr_auto_complete_on": "On · shared by every code host",+ "feature_pr_auto_complete_off": "Off · shared by every code host",+ "feature_pr_auto_complete_manage": "Manage"},"vcs": {"section_title": "Git providers (self-hosted)",diff --git a/packages/views/locales/fr/issues.json b/packages/views/locales/fr/issues.jsonindex c85762bd78..699b00755c 100644--- a/packages/views/locales/fr/issues.json+++ b/packages/views/locales/fr/issues.json@@ -519,7 +519,10 @@"duplicate_unmarked_to": "a retiré la marque de doublon de {{identifier}} sur cette tâche et l'a passée en {{status}}","duplicate_unmarked_original_deleted": "a retiré la marque de doublon, {{identifier}} a été supprimée","duplicate_added": "a marqué {{identifier}} comme doublon de cette tâche",- "duplicate_removed": "a retiré la marque de doublon de {{identifier}}"+ "duplicate_removed": "a retiré la marque de doublon de {{identifier}}",+ "status_changed_pr": "a changé le statut de {{from}} à {{to}} après la fusion de toutes les PR liées ({{prs}})",+ "pr_auto_complete_disabled": "a désactivé la fin automatique par PR pour cette tâche",+ "pr_auto_complete_enabled": "a réactivé la fin automatique par PR pour cette tâche"},"comment": {"add_reaction": "Ajouter une réaction",@@ -1107,5 +1110,37 @@"unmark": "Pas un doublon","section_title": "Doublons","unmark_toast": "Rouverte en À faire"+ },+ "pr_automation": {+ "link_action": "Lier une pull request",+ "link_placeholder": "Collez l’URL de la pull request",+ "link_hint": "Les PR dont le titre ou la branche contient {{identifier}} sont liées automatiquement.",+ "link_submit": "Lier",+ "link_not_found": "Multica n’a pas encore reçu cette PR. Vérifiez que son dépôt est connecté.",+ "link_failed": "Impossible de lier la pull request.",+ "row_menu": "Actions de la pull request",+ "section_menu": "Automatisation des pull requests",+ "source_title": "Liée par {{identifier}} dans le titre",+ "source_branch": "Liée par le nom de branche",+ "source_manual": "Liée manuellement",+ "source_auto": "Liée automatiquement",+ "unlink": "Retirer de la tâche",+ "unlinked": "{{pr}} retirée",+ "unlinked_completed": "{{pr}} retirée. Les autres PR sont fusionnées, la tâche est terminée.",+ "unlink_failed": "Impossible de retirer la pull request.",+ "undo": "Annuler",+ "disable": "Ne pas terminer cette tâche automatiquement",+ "enable": "Terminer cette tâche automatiquement",+ "settings": "Réglages de fin automatique",+ "update_failed": "Impossible de modifier la fin automatique.",+ "waiting_one": "Se termine quand {{prs}} est fusionnée",+ "waiting_other": "Se termine quand {{prs}} sont fusionnées",+ "not_merged": "{{prs}} fermée sans fusion",+ "not_merged_action": "Retirer",+ "all_merged": "Toutes les PR sont fusionnées. La prochaine PR fusionnée terminera la tâche.",+ "issue_disabled": "Fin automatique désactivée pour cette tâche",+ "issue_disabled_action": "Réactiver",+ "workspace_disabled": "La fin automatique par PR est désactivée pour cet espace",+ "workspace_disabled_action": "Réglages"}}diff --git a/packages/views/locales/fr/settings.json b/packages/views/locales/fr/settings.jsonindex 77e6ad6ba7..5096834790 100644--- a/packages/views/locales/fr/settings.json+++ b/packages/views/locales/fr/settings.json@@ -81,7 +81,13 @@"blocked": "À l'arrêt, en attente d'une dépendance extérieure.","done": "Terminé.","cancelled": "Abandonné."- }+ },+ "automation_title": "Automatisation",+ "pr_auto_complete_label": "Terminer les tâches quand leurs PR sont fusionnées",+ "pr_auto_complete_description": "Une tâche passe à Terminé dès que toutes ses PR liées sont fusionnées. S’applique aux PR fusionnées à partir de maintenant.",+ "pr_auto_complete_example": "Les PR sont liées par l’identifiant de la tâche dans leur titre ou leur branche, par ex.",+ "pr_auto_complete_example_title": "MUL-123 : Corriger la redirection après connexion",+ "pr_auto_complete_badge": "Définie à la fusion des PR"},"quick_actions": {"title": "Actions rapides",@@ -757,10 +763,6 @@"master_description_off": "Les fonctionnalités GitHub sont en pause. Les données existantes sont conservées.","section_connection": "Connexion","connection_title": "GitHub App",- "connection_description_prefix": "Associez automatiquement les tâches aux pull requests. Une PR est associée lorsque",- "connection_description_suffix": "figure dans le nom de sa branche ou son titre, ou que sa description contient Closes MUL-123. Fusionner une PR contenant ce mot-clé de clôture fait également passer la tâche à",- "connection_description_done": "Terminé",- "connection_identifier_example": "MUL-123","connected_to": "Connecté à {{login}}","connect_github": "Connecter GitHub","connect_opening": "Ouverture…",@@ -790,7 +792,12 @@"section_repositories": "Dépôts","repositories_shortcut_label": "Les URL de dépôts se trouvent dans l'onglet Dépôts","repositories_shortcut_link": "Gérer les dépôts →",- "toast_failed": "Échec de la mise à jour des paramètres GitHub"+ "toast_failed": "Échec de la mise à jour des paramètres GitHub",+ "feature_auto_link_description": "Lie une PR à la tâche dont l’identifiant, par ex. {{example}}, figure dans son titre ou sa branche.",+ "feature_pr_auto_complete_label": "Terminer les tâches quand leurs PR sont fusionnées",+ "feature_pr_auto_complete_on": "Activé · commun à tous les hébergeurs de code",+ "feature_pr_auto_complete_off": "Désactivé · commun à tous les hébergeurs de code",+ "feature_pr_auto_complete_manage": "Gérer"},"vcs": {"section_title": "Fournisseurs git (auto-hébergés)",diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.jsonindex d5740d0638..5cb1c879fd 100644--- a/packages/views/locales/ja/issues.json+++ b/packages/views/locales/ja/issues.json@@ -510,7 +510,10 @@"duplicate_unmarked_to": "このタスクの {{identifier}} との重複マークを解除し、{{status}} に移動しました","duplicate_unmarked_original_deleted": "重複マークを解除しました({{identifier}} は削除されました)","duplicate_added": "{{identifier}} をこのタスクの重複としてマークしました",- "duplicate_removed": "{{identifier}} の重複マークを解除しました"+ "duplicate_removed": "{{identifier}} の重複マークを解除しました",+ "status_changed_pr": "関連するすべての PR がマージされたため({{prs}})、ステータスを {{from}} から {{to}} に変更しました",+ "pr_auto_complete_disabled": "このタスクの PR による自動完了をオフにしました",+ "pr_auto_complete_enabled": "このタスクの PR による自動完了を再開しました"},"comment": {"add_reaction": "リアクションを追加",@@ -1076,5 +1079,36 @@"unmark": "重複ではない","section_title": "重複","unmark_toast": "未着手として再開しました"+ },+ "pr_automation": {+ "link_action": "PR を関連付け",+ "link_placeholder": "PR の URL を貼り付け",+ "link_hint": "タイトルかブランチ名に {{identifier}} を含む PR は自動で関連付けられます。",+ "link_submit": "関連付け",+ "link_not_found": "Multica はまだこの PR を受け取っていません。リポジトリが接続されているか確認してください。",+ "link_failed": "PR を関連付けられませんでした。",+ "row_menu": "PR の操作",+ "section_menu": "PR の自動化",+ "source_title": "タイトルの {{identifier}} で関連付け",+ "source_branch": "ブランチ名で関連付け",+ "source_manual": "手動で関連付け",+ "source_auto": "自動で関連付け",+ "unlink": "タスクから外す",+ "unlinked": "{{pr}} を外しました",+ "unlinked_completed": "{{pr}} を外しました。残りの PR はすべてマージ済みのため、タスクは完了しました。",+ "unlink_failed": "PR を外せませんでした。",+ "undo": "元に戻す",+ "disable": "このタスクは自動完了しない",+ "enable": "自動完了を再開",+ "settings": "自動完了の設定",+ "update_failed": "自動完了を更新できませんでした。",+ "waiting_other": "{{prs}} がマージされると自動完了",+ "not_merged": "{{prs}} はマージされずにクローズされました",+ "not_merged_action": "外す",+ "all_merged": "PR はすべてマージ済みです。次に PR がマージされると自動完了します。",+ "issue_disabled": "このタスクは自動完了しません",+ "issue_disabled_action": "再開",+ "workspace_disabled": "このワークスペースでは PR による自動完了がオフです",+ "workspace_disabled_action": "設定"}}diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.jsonindex 066d6374b4..c1ec137786 100644--- a/packages/views/locales/ja/settings.json+++ b/packages/views/locales/ja/settings.json@@ -81,7 +81,13 @@"blocked": "外部依存でブロック中。","done": "完了。","cancelled": "見送り。"- }+ },+ "automation_title": "自動化",+ "pr_auto_complete_label": "PR のマージでタスクを自動完了",+ "pr_auto_complete_description": "関連する PR がすべてマージされると、タスクは「完了」になります。今後マージされる PR にのみ適用されます。",+ "pr_auto_complete_example": "PR はタイトルかブランチ名のタスク番号で関連付けられます。例:",+ "pr_auto_complete_example_title": "MUL-123: ログイン後のリダイレクトを修正",+ "pr_auto_complete_badge": "PR のマージで自動設定"},"quick_actions": {"title": "クイックアクション",@@ -755,10 +761,6 @@"master_description_off": "GitHub 機能は停止中です。既存データは保持されています。","section_connection": "接続","connection_title": "GitHub App",- "connection_description_prefix": "タスクを Pull request に自動でリンクします。PR のブランチ名かタイトルに",- "connection_description_suffix": "があるか、本文に Closes MUL-123 と書かれていれば、対応するタスクにリンクされます。その closing keyword を含む PR がマージされたときだけ、タスクが次のステータスに移動します:",- "connection_description_done": "完了",- "connection_identifier_example": "MUL-123","connected_to": "{{login}} に接続済み","connect_github": "GitHub を接続","connect_opening": "開いています…",@@ -788,7 +790,12 @@"section_repositories": "リポジトリ","repositories_shortcut_label": "リポジトリ URL はリポジトリタブにあります","repositories_shortcut_link": "リポジトリを管理 →",- "toast_failed": "GitHub 設定を更新できませんでした"+ "toast_failed": "GitHub 設定を更新できませんでした",+ "feature_auto_link_description": "タイトルかブランチ名にタスク番号(例: {{example}})を含む PR を、そのタスクに関連付けます。",+ "feature_pr_auto_complete_label": "PR のマージでタスクを自動完了",+ "feature_pr_auto_complete_on": "オン · すべてのコードホストで共通",+ "feature_pr_auto_complete_off": "オフ · すべてのコードホストで共通",+ "feature_pr_auto_complete_manage": "設定"},"vcs": {"section_title": "Git providers (self-hosted)",diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.jsonindex be22974c67..7bcab4f4ab 100644--- a/packages/views/locales/ko/issues.json+++ b/packages/views/locales/ko/issues.json@@ -510,7 +510,10 @@"duplicate_unmarked_to": "이 태스크의 {{identifier}} 중복 표시를 해제하고 {{status}}(으)로 이동했습니다","duplicate_unmarked_original_deleted": "중복 표시를 해제했습니다 ({{identifier}} 삭제됨)","duplicate_added": "{{identifier}}을(를) 이 태스크의 중복으로 표시했습니다",- "duplicate_removed": "{{identifier}}의 중복 표시를 해제했습니다"+ "duplicate_removed": "{{identifier}}의 중복 표시를 해제했습니다",+ "status_changed_pr": "연결된 PR이 모두 병합되어({{prs}}) 상태를 {{from}}에서 {{to}}로 변경했습니다",+ "pr_auto_complete_disabled": "이 태스크의 PR 자동 완료를 껐습니다",+ "pr_auto_complete_enabled": "이 태스크의 PR 자동 완료를 다시 켰습니다"},"comment": {"add_reaction": "반응 추가",@@ -1076,5 +1079,36 @@"unmark": "중복 아님","section_title": "중복 항목","unmark_toast": "할 일로 다시 열었습니다"+ },+ "pr_automation": {+ "link_action": "PR 연결",+ "link_placeholder": "PR URL 붙여넣기",+ "link_hint": "제목이나 브랜치 이름에 {{identifier}}가 있는 PR은 자동으로 연결됩니다.",+ "link_submit": "연결",+ "link_not_found": "Multica가 아직 이 PR을 받지 못했습니다. 저장소가 연결되어 있는지 확인하세요.",+ "link_failed": "PR을 연결하지 못했습니다.",+ "row_menu": "PR 작업",+ "section_menu": "PR 자동화",+ "source_title": "제목의 {{identifier}}로 연결됨",+ "source_branch": "브랜치 이름으로 연결됨",+ "source_manual": "수동으로 연결됨",+ "source_auto": "자동으로 연결됨",+ "unlink": "태스크에서 제거",+ "unlinked": "{{pr}}을(를) 제거했습니다",+ "unlinked_completed": "{{pr}}을(를) 제거했습니다. 나머지 PR이 모두 병합되어 태스크가 완료되었습니다.",+ "unlink_failed": "PR을 제거하지 못했습니다.",+ "undo": "실행 취소",+ "disable": "이 태스크는 자동 완료하지 않음",+ "enable": "자동 완료 다시 켜기",+ "settings": "자동 완료 설정",+ "update_failed": "자동 완료를 변경하지 못했습니다.",+ "waiting_other": "{{prs}} 병합 시 자동 완료",+ "not_merged": "{{prs}}이(가) 병합되지 않고 닫혔습니다",+ "not_merged_action": "제거",+ "all_merged": "PR이 모두 병합되었습니다. 다음 PR이 병합되면 자동 완료됩니다.",+ "issue_disabled": "이 태스크는 자동 완료하지 않습니다",+ "issue_disabled_action": "다시 켜기",+ "workspace_disabled": "이 워크스페이스는 PR 자동 완료가 꺼져 있습니다",+ "workspace_disabled_action": "설정"}}diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.jsonindex d23371d761..cacb494454 100644--- a/packages/views/locales/ko/settings.json+++ b/packages/views/locales/ko/settings.json@@ -81,7 +81,13 @@"blocked": "외부 의존성으로 중단됨.","done": "완료.","cancelled": "진행하지 않기로 함."- }+ },+ "automation_title": "자동화",+ "pr_auto_complete_label": "PR 병합 시 태스크 자동 완료",+ "pr_auto_complete_description": "연결된 PR이 모두 병합되면 태스크가 완료로 바뀝니다. 앞으로 병합되는 PR에만 적용됩니다.",+ "pr_auto_complete_example": "PR은 제목이나 브랜치 이름의 태스크 번호로 연결됩니다. 예:",+ "pr_auto_complete_example_title": "MUL-123: 로그인 리디렉션 수정",+ "pr_auto_complete_badge": "PR 병합 시 자동 설정"},"quick_actions": {"title": "퀵 액션",@@ -755,10 +761,6 @@"master_description_off": "GitHub 기능이 일시 중지되었습니다. 기존 데이터는 유지됩니다.","section_connection": "연결","connection_title": "GitHub App",- "connection_description_prefix": "태스크를 Pull request에 자동으로 연결합니다. PR의 브랜치 이름이나 제목에",- "connection_description_suffix": "이(가) 있거나 본문에 Closes MUL-123이 있으면 해당 태스크에 연결되고, 그 종료 키워드가 있는 PR이 병합될 때만 해당 태스크가",- "connection_description_done": "완료",- "connection_identifier_example": "MUL-123","connected_to": "{{login}}에 연결됨","connect_github": "GitHub 연결","connect_opening": "여는 중...",@@ -788,7 +790,12 @@"section_repositories": "저장소","repositories_shortcut_label": "저장소 URL은 저장소 탭에 있습니다","repositories_shortcut_link": "저장소 관리 →",- "toast_failed": "GitHub 설정을 업데이트하지 못했습니다"+ "toast_failed": "GitHub 설정을 업데이트하지 못했습니다",+ "feature_auto_link_description": "제목이나 브랜치 이름에 태스크 번호(예: {{example}})가 있는 PR을 해당 태스크에 연결합니다.",+ "feature_pr_auto_complete_label": "PR 병합 시 태스크 자동 완료",+ "feature_pr_auto_complete_on": "켜짐 · 모든 코드 호스트에 공통 적용",+ "feature_pr_auto_complete_off": "꺼짐 · 모든 코드 호스트에 공통 적용",+ "feature_pr_auto_complete_manage": "설정"},"vcs": {"section_title": "Git providers (self-hosted)",diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.jsonindex 93bf39a6b5..e7b5bf3397 100644--- a/packages/views/locales/zh-Hans/issues.json+++ b/packages/views/locales/zh-Hans/issues.json@@ -510,7 +510,10 @@"duplicate_unmarked_to": "取消了这个任务对 {{identifier}} 的重复标记,并移至{{status}}","duplicate_unmarked_original_deleted": "移除了重复标记,{{identifier}} 已被删除","duplicate_added": "把 {{identifier}} 标记为这个任务的重复",- "duplicate_removed": "取消了 {{identifier}} 对这个任务的重复标记"+ "duplicate_removed": "取消了 {{identifier}} 对这个任务的重复标记",+ "status_changed_pr": "所有关联 PR 均已合并({{prs}}),状态从 {{from}} 改为 {{to}}",+ "pr_auto_complete_disabled": "关闭了此任务的 PR 自动完成",+ "pr_auto_complete_enabled": "恢复了此任务的 PR 自动完成"},"comment": {"add_reaction": "添加表情回应",@@ -1076,5 +1079,36 @@"unmark": "不是重复","section_title": "重复项","unmark_toast": "已重新打开为待办"+ },+ "pr_automation": {+ "link_action": "关联 PR",+ "link_placeholder": "粘贴 PR 链接",+ "link_hint": "标题或分支名含 {{identifier}} 的 PR 会自动关联。",+ "link_submit": "关联",+ "link_not_found": "Multica 还没有收到这个 PR。请确认它所在的仓库已连接。",+ "link_failed": "关联 PR 失败。",+ "row_menu": "PR 操作",+ "section_menu": "PR 自动化",+ "source_title": "通过标题中的 {{identifier}} 关联",+ "source_branch": "通过分支名关联",+ "source_manual": "手动关联",+ "source_auto": "自动关联",+ "unlink": "移除关联",+ "unlinked": "已移除 {{pr}}",+ "unlinked_completed": "已移除 {{pr}}。其余 PR 均已合并,任务已完成。",+ "unlink_failed": "移除关联失败。",+ "undo": "撤销",+ "disable": "此任务不自动完成",+ "enable": "恢复自动完成",+ "settings": "自动完成设置",+ "update_failed": "更新自动完成失败。",+ "waiting_other": "等待 {{prs}} 合并后自动完成",+ "not_merged": "{{prs}} 已关闭,未合并",+ "not_merged_action": "移除",+ "all_merged": "PR 均已合并。之后有新 PR 合并时会自动完成。",+ "issue_disabled": "此任务不自动完成",+ "issue_disabled_action": "恢复",+ "workspace_disabled": "工作区未开启 PR 自动完成",+ "workspace_disabled_action": "设置"}}diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.jsonindex c15b139171..7cf4da3b19 100644--- a/packages/views/locales/zh-Hans/settings.json+++ b/packages/views/locales/zh-Hans/settings.json@@ -81,7 +81,13 @@"blocked": "被外部依赖阻塞。","done": "已完成。","cancelled": "决定不做。"- }+ },+ "automation_title": "自动化",+ "pr_auto_complete_label": "PR 合并后自动完成任务",+ "pr_auto_complete_description": "任务关联的 PR 全部合并后,状态改为「已完成」。只对之后合并的 PR 生效。",+ "pr_auto_complete_example": "PR 标题或分支名含任务编号时自动关联,例如",+ "pr_auto_complete_example_title": "MUL-123: 修复登录跳转",+ "pr_auto_complete_badge": "PR 全部合并时自动进入"},"quick_actions": {"title": "快捷操作",@@ -755,10 +761,6 @@"master_description_off": "GitHub 功能已暂停,已有数据保留。","section_connection": "连接","connection_title": "GitHub App",- "connection_description_prefix": "自动把任务关联到 Pull Request。只要 PR 的分支名或标题里出现",- "connection_description_suffix": "或正文里写了 Closes MUL-123,PR 就会关联到对应任务;只有带关闭关键字的 PR 合并后,任务才会转为",- "connection_description_done": "已完成",- "connection_identifier_example": "MUL-123","connected_to": "已连接到 {{login}}","connect_github": "连接 GitHub","connect_opening": "正在打开…",@@ -788,7 +790,12 @@"section_repositories": "代码仓库","repositories_shortcut_label": "仓库 URL 仍在\"代码仓库\"标签页中管理","repositories_shortcut_link": "前往管理 →",- "toast_failed": "更新 GitHub 设置失败"+ "toast_failed": "更新 GitHub 设置失败",+ "feature_auto_link_description": "PR 标题或分支名含任务编号(如 {{example}})时,自动关联到对应任务。",+ "feature_pr_auto_complete_label": "PR 合并后自动完成任务",+ "feature_pr_auto_complete_on": "已开启 · 所有代码托管平台共用",+ "feature_pr_auto_complete_off": "未开启 · 所有代码托管平台共用",+ "feature_pr_auto_complete_manage": "设置"},"vcs": {"section_title": "Git 代码托管(自托管)",diff --git a/packages/views/settings/components/github-tab.test.tsx b/packages/views/settings/components/github-tab.test.tsxindex e01826c6dc..43b6d540c0 100644--- a/packages/views/settings/components/github-tab.test.tsx+++ b/packages/views/settings/components/github-tab.test.tsx@@ -1,6 +1,6 @@import type { ReactNode } from "react";import { describe, it, expect, beforeEach, vi } from "vitest";-import { render, screen, waitFor, within } from "@testing-library/react";+import { cleanup, render, screen, waitFor, within } from "@testing-library/react";import userEvent from "@testing-library/user-event";import { I18nProvider } from "@multica/core/i18n/react";import enCommon from "../../locales/en/common.json";@@ -144,7 +144,7 @@ function resetFixtures() {describe("GitHubTab", () => {beforeEach(resetFixtures);- it.each([false, true])("keeps matching and close rules beside auto-link when connected=%s", (connected) => {+ it.each([false, true])("states the title/branch linking rule beside auto-link when connected=%s", (connected) => {installationsRef.current.installations = connected? [{ id: "inst-1", account_login: "acme" }]: [];@@ -152,9 +152,23 @@ describe("GitHubTab", () => {const toggle = screen.getByRole("switch", { name: /Auto-link issues and PRs/i });const row = within(toggle.parentElement!);- expect(row.getByText(/is in its branch name or title, or its body says Closes MUL-123/)).toBeTruthy();- expect(row.getByText("Done")).toBeTruthy();- expect(screen.getAllByText("MUL-123")).toHaveLength(1);+ expect(row.getByText(/e\.g\. MUL-123, is in its title or branch name/)).toBeTruthy();+ // Keywords no longer carry meaning (MUL-7429), so the old rule is gone.+ expect(screen.queryByText(/Closes MUL-123/)).toBeNull();+ });++ // Completion is shared by every code host and lives with the statuses; the+ // GitHub page only reports it and points there.+ it("reports PR auto-complete and links to the issue statuses page", () => {+ render(<GitHubTab />, { wrapper: I18nWrapper });+ expect(screen.getByText("Complete issues when their PRs merge")).toBeTruthy();+ expect(screen.getByText(/^On · /)).toBeTruthy();+ expect(screen.getByText("Manage").closest("a")?.getAttribute("href")).toContain("tab=issue-statuses");++ cleanup();+ workspaceRef.current.settings = { pr_auto_complete_enabled: false };+ render(<GitHubTab />, { wrapper: I18nWrapper });+ expect(screen.getByText(/^Off · /)).toBeTruthy();});it("offers the master switch without a separate turn-off callout", () => {diff --git a/packages/views/settings/components/github-tab.tsx b/packages/views/settings/components/github-tab.tsxindex e9c1fb38ca..60f3974f44 100644--- a/packages/views/settings/components/github-tab.tsx+++ b/packages/views/settings/components/github-tab.tsx@@ -3,7 +3,7 @@import { useState } from "react";import { useQuery, useQueryClient } from "@tanstack/react-query";import { toast } from "sonner";-import { ExternalLink, GitCommitHorizontal, Link2, PanelRight } from "lucide-react";+import { CircleCheck, ExternalLink, GitCommitHorizontal, Link2, PanelRight } from "lucide-react";import { Button } from "@multica/ui/components/ui/button";import { Card, CardContent } from "@multica/ui/components/ui/card";import { Label } from "@multica/ui/components/ui/label";@@ -24,6 +24,7 @@ import { useCurrentWorkspace } from "@multica/core/paths";import { memberListOptions, workspaceKeys } from "@multica/core/workspace/queries";import {deriveGitHubSettings,+ derivePRAutoCompleteEnabled,githubInstallationsOptions,} from "@multica/core/github";import { api } from "@multica/core/api";@@ -66,6 +67,7 @@ export function GitHubTab() {const primaryInstallation = installations[0] ?? null;const flags = deriveGitHubSettings(workspace);+ const prAutoComplete = derivePRAutoCompleteEnabled(workspace);const [savingKey, setSavingKey] = useState<SettingsKey | null>(null);const [connecting, setConnecting] = useState(false);const [disconnectTarget, setDisconnectTarget] = useState<string | null>(null);@@ -285,19 +287,41 @@ export function GitHubTab() {icon={<Link2 className="h-4 w-4" />}label={t(($) => $.github.feature_auto_link_label)}description={- <p className="text-caption text-muted-foreground">- {t(($) => $.github.connection_description_prefix)}{" "}- <code className="rounded-xs bg-muted px-1 py-0.5 text-micro">- {t(($) => $.github.connection_identifier_example)}- </code>{" "}- {t(($) => $.github.connection_description_suffix)}{" "}- <strong>{t(($) => $.github.connection_description_done)}</strong>.+ <p className="text-body text-muted-foreground">+ {t(($) => $.github.feature_auto_link_description, { example: "MUL-123" })}</p>}checked={flags.autoLinkPRs}disabled={!canManage || !flags.enabled || savingKey === "github_auto_link_prs_enabled"}onCheckedChange={(v) => persistSetting("github_auto_link_prs_enabled", v)}/>++ {/* Completion is not a GitHub setting: it is shared by every code+ host and lives with the statuses it writes. This row only+ reports it and points there. */}+ <div className="flex items-center justify-between gap-4 px-4 py-3.5">+ <div className="flex items-start gap-3">+ <div className="rounded-md border bg-muted/50 p-2 text-muted-foreground">+ <CircleCheck className="h-4 w-4" />+ </div>+ <div className="space-y-1">+ <p className="text-body font-medium">{t(($) => $.github.feature_pr_auto_complete_label)}</p>+ <p className="text-body text-muted-foreground">+ {prAutoComplete+ ? t(($) => $.github.feature_pr_auto_complete_on)+ : t(($) => $.github.feature_pr_auto_complete_off)}+ </p>+ </div>+ </div>+ <Button+ variant="outline"+ size="sm"+ render={<AppLink href={`${navigation.pathname}?tab=issue-statuses`} />}+ nativeButton={false}+ >+ {t(($) => $.github.feature_pr_auto_complete_manage)}+ </Button>+ </div></CardContent></Card></section>diff --git a/packages/views/settings/components/issue-statuses-tab.test.tsx b/packages/views/settings/components/issue-statuses-tab.test.tsxindex 29c5796bd3..91ba0020e2 100644--- a/packages/views/settings/components/issue-statuses-tab.test.tsx+++ b/packages/views/settings/components/issue-statuses-tab.test.tsx@@ -15,7 +15,16 @@ const createMutate = vi.hoisted(() => vi.fn());const updateMutate = vi.hoisted(() => vi.fn());const archiveMutate = vi.hoisted(() => vi.fn());const navigatePush = vi.hoisted(() => vi.fn());-vi.mock("@multica/core/paths", () => ({ useWorkspacePaths: () => ({ issues: () => "/dev/issues" }) }));+const updateWorkspace = vi.hoisted(() => vi.fn());+let workspaceSettings: Record<string, unknown> = {};+vi.mock("@multica/core/paths", () => ({+ useWorkspacePaths: () => ({ issues: () => "/dev/issues" }),+ useCurrentWorkspace: () => ({ id: "ws-1", settings: workspaceSettings }),+}));+vi.mock("@multica/core/api", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@multica/core/api")>()),+ api: { updateWorkspace },+}));vi.mock("../../navigation", () => ({ useNavigation: () => ({ push: navigatePush }) }));vi.mock("../../issues/surface/issue-surface", () => ({IssueSurfaceWithStore: ({ store, scope }: { store: { getState: () => { statusFilters: string[] } }; scope: { actorKind: string } }) =>@@ -29,6 +38,7 @@ vi.mock("@tanstack/react-query", () => ({data: options.queryKey[0] === "issue-statuses" ? catalog : members(),isLoading: false,}),+ useQueryClient: () => ({ setQueryData: vi.fn() }),}));vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));vi.mock("@multica/core/auth", () => ({@@ -36,6 +46,7 @@ vi.mock("@multica/core/auth", () => ({}));vi.mock("@multica/core/workspace/queries", () => ({memberListOptions: () => ({ queryKey: ["members", "ws-1"] }),+ workspaceKeys: { list: () => ["workspaces"] },}));// Only the fetch is stubbed. The module's pure helpers (`issueStatusColor`)// are what the rows render with, and a stub of those would test the stub.@@ -92,6 +103,10 @@ const BUILT_IN_IN_REVIEW = entry({position: 0,});+// Two switches now render (show archived, PR auto-complete); name the one meant.+const archivedToggle = () =>+ screen.queryByRole("switch", { name: new RegExp(`^${en.issue_statuses.show_archived.split(" (")[0]}`) });+afterEach(() => {cleanup();reorderMutate.mockClear();@@ -99,11 +114,48 @@ afterEach(() => {updateMutate.mockClear();archiveMutate.mockReset();navigatePush.mockClear();+ updateWorkspace.mockReset();+ workspaceSettings = {};catalog = [];role = "owner";});describe("IssueStatusesTab", () => {+ describe("PR auto-complete (MUL-7429)", () => {+ const BUILT_IN_DONE = entry({ id: "done", key: "done", name: "Done", category: "done", is_system: true, position: 0 });++ it("saves the workspace setting as soon as the switch changes", async () => {+ workspaceSettings = { github_enabled: true };+ updateWorkspace.mockResolvedValue({ id: "ws-1", settings: {} });+ render(<IssueStatusesTab />);+ const toggle = screen.getByRole("switch", { name: en.issue_statuses.pr_auto_complete_label });+ expect(toggle).toHaveAttribute("aria-checked", "true");+ fireEvent.click(toggle);+ await waitFor(() =>+ expect(updateWorkspace).toHaveBeenCalledWith("ws-1", {+ settings: { github_enabled: true, pr_auto_complete_enabled: false },+ }),+ );+ });++ it("badges the built-in Done row only while the setting is on", () => {+ catalog = [BUILT_IN_DONE];+ render(<IssueStatusesTab />);+ expect(screen.getByText(en.issue_statuses.pr_auto_complete_badge)).toBeInTheDocument();+ cleanup();+ workspaceSettings = { pr_auto_complete_enabled: false };+ render(<IssueStatusesTab />);+ expect(screen.queryByText(en.issue_statuses.pr_auto_complete_badge)).toBeNull();+ expect(screen.getByRole("switch", { name: en.issue_statuses.pr_auto_complete_label })).toHaveAttribute("aria-checked", "false");+ });++ it("shows the setting read-only to a member", () => {+ role = "member";+ render(<IssueStatusesTab />);+ expect(screen.getByRole("switch", { name: en.issue_statuses.pr_auto_complete_label })).toHaveAttribute("aria-disabled", "true");+ });+ });+it("aligns category and row actions with equal end padding and pointer target sizes", () => {catalog = [BUILT_IN_IN_REVIEW, entry({ key: "qa", name: "QA" })];render(<IssueStatusesTab />);@@ -312,7 +364,7 @@ describe("IssueStatusesTab", () => {// Hidden until the toggle is on, but the toggle itself is enabled because// the workspace has one.expect(screen.queryByText("QA")).toBeNull();- expect(screen.getByRole("switch")).toBeEnabled();+ expect(archivedToggle()).toBeEnabled();});// The category header used to repeat the sentence its built-in row already@@ -331,7 +383,7 @@ describe("IssueStatusesTab", () => {catalog = [BUILT_IN_IN_REVIEW, entry({ key: "qa", name: "QA" })];render(<IssueStatusesTab />);- expect(screen.queryByRole("switch")).toBeNull();+ expect(archivedToggle()).toBeNull();});it("allows a single custom status to move relative to built-ins", () => {@@ -376,7 +428,7 @@ describe("IssueStatusesTab", () => {entry({ key: "qa", name: "QA", position: 2 }),];render(<IssueStatusesTab />);- fireEvent.click(screen.getByRole("switch"));+ fireEvent.click(archivedToggle()!);expect(screen.getByText("Old")).toBeInTheDocument();fireEvent.click(screen.getByLabelText(en.issue_statuses.actions.open.replace("{{name}}", "QA")));fireEvent.click(await screen.findByRole("menuitem", { name: en.issue_statuses.actions.move_up }));diff --git a/packages/views/settings/components/issue-statuses-tab.tsx b/packages/views/settings/components/issue-statuses-tab.tsxindex 07e7abe233..ee76649a76 100644--- a/packages/views/settings/components/issue-statuses-tab.tsx+++ b/packages/views/settings/components/issue-statuses-tab.tsx@@ -1,7 +1,7 @@"use client";import { useEffect, useMemo, useRef, useState } from "react";-import { useQuery } from "@tanstack/react-query";+import { useQuery, useQueryClient } from "@tanstack/react-query";import {Archive,ArrowLeft,@@ -11,6 +11,7 @@ import {MoreHorizontal,Pencil,Plus,+ Zap,} from "lucide-react";import { toast } from "sonner";import {@@ -32,6 +33,10 @@ import {import { CSS } from "@dnd-kit/utilities";import { useWorkspaceId } from "@multica/core/hooks";import { useAuthStore } from "@multica/core/auth";+import { api } from "@multica/core/api";+import { derivePRAutoCompleteEnabled } from "@multica/core/github";+import { useCurrentWorkspace } from "@multica/core/paths";+import { workspaceKeys } from "@multica/core/workspace/queries";import { issueStatusArchiveConflictCount, createIssueStatusListStore } from "@multica/core/issue-statuses";import { baselineFromQuery } from "@multica/core/issue-views/baseline";import { IssueSurfaceWithStore } from "../../issues/surface/issue-surface";@@ -54,6 +59,7 @@ import type {IssueStatusCategory,IssueStatusEntry,IssueStatusIcon,+ Workspace,} from "@multica/core/types";import { ISSUE_STATUS_ICONS } from "@multica/core/types/issue-status";import { Button } from "@multica/ui/components/ui/button";@@ -101,7 +107,7 @@ import { ColorPicker, COLOR_PICKER_PRESETS } from "../../common/color-picker";import { StatusIcon } from "../../issues/components/status-icon";import { useStatusLabel } from "../../issues/utils/status-label";import { useT } from "../../i18n";-import { SettingsTab } from "./settings-layout";+import { SettingsCard, SettingsRow, SettingsSection, SettingsTab } from "./settings-layout";/*** Workspace issue status catalog management (MUL-6243).@@ -155,6 +161,7 @@ export function IssueStatusesTab() {return members.find((m) => m.user_id === currentUser.id)?.role ?? null;}, [members, currentUser]);const isAdmin = myRole === "owner" || myRole === "admin";+ const prAutoComplete = derivePRAutoCompleteEnabled(useCurrentWorkspace());const groups = useMemo(() =>@@ -214,6 +221,7 @@ export function IssueStatusesTab() {category={group.category}entries={group.entries}canManage={isAdmin}+ prAutoComplete={prAutoComplete}onCreate={() => setCreateCategory(group.category)}onEdit={(entry) => entry.is_system ? setShowBuiltInNotice(true) : setEditing(entry)}onArchive={(entry) => {@@ -227,6 +235,8 @@ export function IssueStatusesTab() {)}</div>+ <PRAutoCompleteSection canManage={isAdmin} />+<StatusEditorDialogopen={createCategory !== null}onOpenChange={(open) => !open && setCreateCategory(null)}@@ -267,6 +277,7 @@ function CategorySection({category,entries,canManage,+ prAutoComplete,onCreate,onEdit,onArchive,@@ -275,6 +286,8 @@ function CategorySection({category: IssueStatusCategory;entries: IssueStatusEntry[];canManage: boolean;+ /** Badge the built-in Done row: PR auto-complete writes that status. */+ prAutoComplete: boolean;onCreate: () => void;onEdit: (status: IssueStatusEntry) => void;onArchive: (status: IssueStatusEntry) => void;@@ -376,6 +389,7 @@ function CategorySection({<StatusRowkey={entry.id}entry={entry}+ autoCompleteBadge={prAutoComplete && entry.is_system && entry.key === "done"}label={entry.is_system ? labelOf(entry.key) : entry.name}description={entry.is_system? t(($) => $.issue_statuses.built_in_descriptions[entry.key as BuiltInIssueStatus])@@ -404,6 +418,7 @@ function CategorySection({function StatusRow({entry,+ autoCompleteBadge,label,description,canManage,@@ -416,6 +431,7 @@ function StatusRow({onMoveDown,}: {entry: IssueStatusEntry;+ autoCompleteBadge: boolean;label: string;description: string;canManage: boolean;@@ -466,6 +482,12 @@ function StatusRow({<div className="min-w-0 flex-1"><div className="flex min-w-0 items-center gap-2"><span className="truncate text-body font-medium">{label}</span>+ {autoCompleteBadge && (+ <span className="inline-flex shrink-0 items-center gap-1 rounded-full bg-info/10 px-1.5 py-0.5 text-micro font-medium text-info">+ <Zap className="size-3" aria-hidden="true" />+ {t(($) => $.issue_statuses.pr_auto_complete_badge)}+ </span>+ )}{archived && (<Tooltip><TooltipTrigger@@ -863,3 +885,65 @@ function ArchiveStatusDialog({</AlertDialog>);}++/**+ * The one PR automation setting (MUL-7429): when every PR linked to an issue+ * is merged, the issue moves to Done. It lives with the statuses because it+ * decides a status change, and it is shared by every code host. Saves on+ * toggle, like the other workspace switches; it only affects merges from now+ * on, so there is no preview.+ */+function PRAutoCompleteSection({ canManage }: { canManage: boolean }) {+ const { t } = useT("settings");+ const workspace = useCurrentWorkspace();+ const qc = useQueryClient();+ const [saving, setSaving] = useState(false);+ const enabled = derivePRAutoCompleteEnabled(workspace);++ async function persist(next: boolean) {+ if (!workspace || saving) return;+ setSaving(true);+ try {+ const updated = await api.updateWorkspace(workspace.id, {+ settings: { ...((workspace.settings as Record<string, unknown>) ?? {}), pr_auto_complete_enabled: next },+ });+ qc.setQueryData(workspaceKeys.list(), (old: Workspace[] | undefined) =>+ old?.map((ws) => (ws.id === updated.id ? updated : ws)),+ );+ toast.success(t(($) => $.auto_save.toast_saved), { id: "settings-auto-save" });+ } catch (e) {+ toast.error(e instanceof Error ? e.message : t(($) => $.auto_save.failed));+ } finally {+ setSaving(false);+ }+ }++ return (+ <SettingsSection title={t(($) => $.issue_statuses.automation_title)}>+ <SettingsCard>+ <SettingsRow+ label={<label htmlFor="pr-auto-complete">{t(($) => $.issue_statuses.pr_auto_complete_label)}</label>}+ description={+ <>+ {t(($) => $.issue_statuses.pr_auto_complete_description)}+ <span className="mt-1.5 block">+ {t(($) => $.issue_statuses.pr_auto_complete_example)}{" "}+ <code className="rounded-xs bg-muted px-1 py-0.5 text-micro text-foreground">+ {t(($) => $.issue_statuses.pr_auto_complete_example_title)}+ </code>+ </span>+ </>+ }+ >+ <Switch+ id="pr-auto-complete"+ checked={enabled}+ disabled={!canManage || saving}+ aria-busy={saving || undefined}+ onCheckedChange={(v) => void persist(v)}+ />+ </SettingsRow>+ </SettingsCard>+ </SettingsSection>+ );+}diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.goindex cc3c03b906..7eb4c160e1 100644--- a/server/cmd/migrate/main.go+++ b/server/cmd/migrate/main.go@@ -144,6 +144,8 @@ var concurrentIndexCleanups = map[string]string{"539_task_supplement_request_index": "task_supplement_task_request_uidx","540_task_supplement_capability_index": "task_supplement_capability_task_uidx","541_task_supplement_comment_index": "task_supplement_comment_uidx",+ "546_issue_pr_automation_workspace_index": "idx_issue_pr_automation_workspace",+ "547_issue_pull_request_exclusion_workspace_index": "idx_issue_pull_request_exclusion_workspace","510_wakeup_id": "issue_wakeup_id_idx","511_wakeup_issue": "issue_wakeup_issue_idx","512_wakeup_due": "issue_wakeup_due_idx",diff --git a/server/cmd/server/activity_listeners.go b/server/cmd/server/activity_listeners.goindex 4dff79685a..9ee19a2cea 100644--- a/server/cmd/server/activity_listeners.go+++ b/server/cmd/server/activity_listeners.go@@ -78,10 +78,19 @@ func registerActivityListeners(bus *events.Bus, queries *db.Queries) {if statusChanged {prevStatus, _ := payload["prev_status"].(string)- details, _ := json.Marshal(map[string]string{+ detailsMap := map[string]string{"from": prevStatus,"to": issue.Status,- })+ }+ // PR auto-complete (MUL-7429): say why the status moved, so the+ // timeline explains the change without a hidden rule.+ if source, _ := payload["source"].(string); source == "pr_automation" {+ detailsMap["source"] = source+ if prs, _ := payload["pull_requests"].(string); prs != "" {+ detailsMap["pull_requests"] = prs+ }+ }+ details, _ := json.Marshal(detailsMap)activity, err := queries.CreateActivity(ctx, db.CreateActivityParams{ID: dbid.NewV7(),WorkspaceID: parseUUID(issue.WorkspaceID),diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 0342e10d8a..7ad585fc9d 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -2021,6 +2021,9 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Put("/properties/{propertyId}", h.SetIssueProperty)r.Delete("/properties/{propertyId}", h.DeleteIssueProperty)r.Get("/pull-requests", h.ListPullRequestsForIssue)+ r.Post("/pull-requests", h.LinkIssuePullRequest)+ r.Delete("/pull-requests/{prId}", h.UnlinkIssuePullRequest)+ r.Put("/pr-auto-complete", h.SetIssuePRAutoComplete)})})diff --git a/server/internal/handler/github.go b/server/internal/handler/github.goindex 6d7acf34da..fb9db9e107 100644--- a/server/internal/handler/github.go+++ b/server/internal/handler/github.go@@ -26,7 +26,6 @@ import ("github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/issuestatus""github.com/multica-ai/multica/server/internal/middleware"- "github.com/multica-ai/multica/server/internal/service"db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/protocol")@@ -82,6 +81,9 @@ type GitHubPullRequestResponse struct {ClosedAt *string `json:"closed_at"`PRCreatedAt string `json:"pr_created_at"`PRUpdatedAt string `json:"pr_updated_at"`+ // LinkSource explains why the PR is on the issue: "manual", "title",+ // "branch", or "auto" (an older rule). Only set on the issue PR list.+ LinkSource string `json:"link_source,omitempty"`// Mergeable state mirrors GitHub's REST `mergeable_state` field, retained// for compatibility. The card now reads the richer GraphQL fields below.MergeableState *string `json:"mergeable_state"`@@ -966,6 +968,12 @@ func (h *Handler) ListPullRequestsForIssue(w http.ResponseWriter, r *http.Requesif !ok {return}+ ws, err := h.Queries.GetWorkspace(r.Context(), issue.WorkspaceID)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list pull requests")+ return+ }+ identifier := fmt.Sprintf("%s-%d", issuePrefixForWorkspace(ws), issue.Number)rows, err := h.Queries.ListPullRequestsByIssue(r.Context(), issue.ID)if err != nil {writeError(w, http.StatusInternalServerError, "failed to list pull requests")@@ -973,7 +981,9 @@ func (h *Handler) ListPullRequestsForIssue(w http.ResponseWriter, r *http.Reques}out := make([]GitHubPullRequestResponse, 0, len(rows))for _, row := range rows {- out = append(out, issuePullRequestRowToResponse(row, h.PRRefresh.Enabled()))+ resp := issuePullRequestRowToResponse(row, h.PRRefresh.Enabled())+ resp.LinkSource = prLinkSource(row.LinkedByType, identifier, row.Title, row.Branch.String)+ out = append(out, resp)// Page-visit trigger (MUL-5265): if this card's snapshot is missing or// older than the view TTL, kick an async refresh. Non-blocking — the// current (possibly stale) response is returned immediately and the@@ -996,12 +1006,24 @@ func (h *Handler) ListPullRequestsForIssue(w http.ResponseWriter, r *http.Requesreturn}for _, row := range vcsRows {- out = append(out, vcsPullRequestRowToResponse(row))+ resp := vcsPullRequestRowToResponse(row)+ resp.LinkSource = prLinkSource(row.LinkedByType, identifier, row.Title, row.Branch.String)+ out = append(out, resp)}sort.SliceStable(out, func(i, j int) bool {return out[i].PRCreatedAt > out[j].PRCreatedAt})- writeJSON(w, http.StatusOK, map[string]any{"pull_requests": out})+ // The one auto-complete decision the issue page renders, so the UI never+ // re-derives the rule on its own.+ decision, err := h.decidePRAutoComplete(r.Context(), ws, issue, nil)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list pull requests")+ return+ }+ writeJSON(w, http.StatusOK, map[string]any{+ "pull_requests": out,+ "auto_complete": prAutoCompleteToResponse(ws, decision),+ })}// broadcastPRSnapshotApplied is the ghsnapshot pipeline's onApplied callback:@@ -1036,19 +1058,6 @@ func (h *Handler) broadcastPRSnapshotApplied(ctx context.Context, prID pgtype.UU// version numbers like "v1.2-3".var identifierRe = regexp.MustCompile(`(?i)\b([a-z][a-z0-9]{0,9})-(\d+)\b`)-// closingIdentifierRe extracts identifiers that appear immediately after a-// GitHub-style closing keyword ("close[sd]?", "fix(e[sd])?", "resolve[sd]?"),-// optionally separated by a colon and whitespace. Matching is intentionally-// strict on adjacency — "Fix MUL-1" closes MUL-1, but "Fix login MUL-1"-// does not. This mirrors GitHub's own closing-keyword grammar and is the-// gate the webhook uses to decide whether to auto-advance an issue to-// `done` after a PR merges. References like "Follow up in MUL-2" and bare-// title prefixes like "MUL-1: ..." link the PR (via identifierRe) but-// never auto-close.-var closingIdentifierRe = regexp.MustCompile(- `(?i)\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)[:\s]+([a-z][a-z0-9]{0,9})-(\d+)\b`,-)-// HandleGitHubWebhook (POST /api/webhooks/github) is GitHub's destination for// every event from a connected installation. We verify HMAC signature, route// on X-GitHub-Event, and either upsert PR rows + auto-link to issues or@@ -1285,12 +1294,12 @@ func (h *Handler) handlePullRequestEvent(ctx context.Context, body []byte) {// 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)+ // Settle who — if anyone — may link each identifier BEFORE any workspace+ // writes, and treat that verdict as authoritative for the whole delivery.+ // See prLinkPolicy.+ linkPolicy := h.resolvePRLinkPolicy(ctx, insts, &p)for _, inst := range insts {- h.mirrorPullRequestForWorkspace(ctx, inst.WorkspaceID, inst.InstallationID, &p, closePolicy)+ h.mirrorPullRequestForWorkspace(ctx, inst.WorkspaceID, inst.InstallationID, &p, linkPolicy)}// 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@@ -1299,30 +1308,31 @@ 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.+// prLinkPolicy decides which (identifier, workspace) pairs this delivery may+// link, 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 {+// A link is a claim that the PR delivers the issue, and a fully merged link set+// completes the issue. So when one installation is bound to several workspaces,+// an identifier that resolves in more than one of them must not link anywhere —+// otherwise merging the PR would complete an issue in a workspace that has+// nothing to do with it (#6804). A member can still link the PR by hand.+type prLinkPolicy 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.+ // impossible with one bound workspace, so 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.+ // indeterminate means a read failed, so we cannot tell ambiguous from+ // unique. The mirror pass then leaves links and statuses untouched for this+ // delivery rather than guessing either way.+ indeterminate bool+ // owner maps an identifier to the one workspace proven to resolve it.owner map[string]string+ // ambiguous lists identifiers that resolved in more than one workspace.+ ambiguous map[string]bool}-// permits reports whether workspaceID may carry close intent for identifier.-func (c closeIntentPolicy) permits(identifier, workspaceID string) bool {+// permits reports whether workspaceID may link identifier.+func (c prLinkPolicy) permits(identifier, workspaceID string) bool {if c.unrestricted {return true}@@ -1330,58 +1340,40 @@ func (c closeIntentPolicy) permits(identifier, workspaceID string) bool {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 {+// resolvePRLinkPolicy determines, before any workspace writes, which title and+// branch identifiers on this PR may link and in which workspace. An identifier+// is allowed only when exactly one bound workspace was proven to resolve it;+// misjudging "unique" as "ambiguous" costs a link a person can add by hand,+// while the reverse would complete someone else's issue.+func (h *Handler) resolvePRLinkPolicy(ctx context.Context, insts []db.GithubInstallation, p *ghPullRequestPayload) prLinkPolicy {if len(insts) < 2 {- return closeIntentPolicy{unrestricted: true}+ return prLinkPolicy{unrestricted: true}}- idents := extractClosingIdentifiers(p.PullRequest.Title, p.PullRequest.Body)+ idents := extractIdentifiers(p.PullRequest.Title, p.PullRequest.Head.Ref)+ policy := prLinkPolicy{owner: map[string]string{}, ambiguous: map[string]bool{}}if len(idents) == 0 {- return closeIntentPolicy{}+ return policy}prNumber := p.PullRequest.Numberrepo := p.Repository.Owner.Login + "/" + p.Repository.Name+ indeterminate := func(msg string, args ...any) prLinkPolicy {+ slog.Warn(msg, append(args, "installation_id", p.Installation.ID, "repo", repo, "pr_number", prNumber)...)+ return prLinkPolicy{indeterminate: true}+ }- // 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{}+ return indeterminate("github: cannot load bound workspace, leaving links unchanged for this delivery", "err", err)}- // 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".+ // A workspace with auto-link off never writes a link row, so it is not+ // a competing claimant. A settings blob we cannot parse is not evidence+ // either way, so it fails closed.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{}+ return indeterminate("github: cannot read workspace auto-link setting, leaving links unchanged for this delivery",+ "err", err, "workspace_id", uuidToString(inst.WorkspaceID))}if !autoLink {continue@@ -1397,34 +1389,25 @@ func (h *Handler) resolveCloseIntentPolicy(ctx context.Context, insts []db.GithuNumber: 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{}+ return indeterminate("github: cannot resolve identifier in bound workspace, leaving links unchanged for this delivery",+ "err", err, "identifier", id, "workspace_id", uuidToString(inst.WorkspaceID))}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,- )+ policy.ambiguous[id] = true+ // An issue that never auto-links is otherwise untraceable back to+ // GitHub, so leave a breadcrumb naming the collision.+ slog.Warn("github: identifier resolves in several bound workspaces, not auto-linking it",+ "identifier", id, "workspaces", len(wss),+ "installation_id", p.Installation.ID, "repo", repo, "pr_number", prNumber)}return policy}@@ -1532,9 +1515,21 @@ func (h *Handler) triggerPRRefreshFromCIEvent(ctx context.Context, body []byte)// 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) {+func (h *Handler) mirrorPullRequestForWorkspace(ctx context.Context, wsID pgtype.UUID, installationID int64, p *ghPullRequestPayload, linkPolicy prLinkPolicy) {state := derivePRState(p.PullRequest.State, p.PullRequest.Draft, p.PullRequest.Merged)mergeable, clearMergeable := derivePRMergeableState(p.Action, p.PullRequest.MergeableState, baseRefChanged(p.Changes))+ // The stored state before this event, so a merge is acted on once — when it+ // happens — and not again on a later edit/label event of a merged PR (that+ // would re-complete an issue someone reopened on purpose).+ prevState := ""+ if prev, err := h.Queries.GetGitHubPullRequest(ctx, db.GetGitHubPullRequestParams{+ WorkspaceID: wsID,+ RepoOwner: p.Repository.Owner.Login,+ RepoName: p.Repository.Name,+ PrNumber: p.PullRequest.Number,+ }); err == nil {+ prevState = prev.State+ }pr, err := h.Queries.UpsertGitHubPullRequest(ctx, db.UpsertGitHubPullRequestParams{WorkspaceID: wsID,InstallationID: installationID,@@ -1558,6 +1553,12 @@ func (h *Handler) mirrorPullRequestForWorkspace(ctx context.Context, wsID pgtypeDeletions: p.PullRequest.Deletions,ChangedFiles: p.PullRequest.ChangedFiles,})+ if errors.Is(err, pgx.ErrNoRows) {+ // A stale redelivery: the stored row is newer, and the newer event+ // already linked and published. Acting on this one would roll links+ // and merge detection back.+ return+ }if err != nil {slog.Warn("github: upsert pr failed", "err", err)return@@ -1565,152 +1566,46 @@ func (h *Handler) mirrorPullRequestForWorkspace(ctx context.Context, wsID pgtypeworkspaceID := uuidToString(wsID)resp := githubPullRequestToResponse(pr, h.PRRefresh.Enabled())+ linkedIssueIDs := make([]string, 0)- // Auto-link: scan title/body/branch for issue identifiers, look them- // up in this workspace, attach the link rows. Idempotent (ON CONFLICT- // upserts the close_intent flag — see LinkIssueToPullRequest) so- // re-firing the webhook doesn't duplicate.- //// RFC MUL-2414 §4.8: the PR mirror upsert above always runs (so re-enabling- // GitHub features restores history without backfill), but the link rows- // are a "new side-effect" and must be gated by the workspace's auto-link- // flag (which itself short-circuits when the master `github_enabled`- // switch is off).- linkedIssueIDs := make([]string, 0)- if h.workspaceAutoLinkPRsEnabled(ctx, wsID) {- idents := extractIdentifiers(p.PullRequest.Title, p.PullRequest.Body, p.PullRequest.Head.Ref)- // closingIdents is the subset of identifiers that this PR explicitly- // declared via a closing keyword ("Closes/Fixes/Resolves MUL-X"). The- // link row's close_intent column — and therefore whether the- // auto-advance gate eventually fires — is only set for keyword-- // declared identifiers. Bare title prefixes and branch-name- // references are link-only.- closingIdents := map[string]struct{}{}- for _, c := range extractClosingIdentifiers(p.PullRequest.Title, p.PullRequest.Body) {- closingIdents[c] = struct{}{}- }- // claimedIdents are the identifiers this PR actually claims: a title- // prefix, a branch-name reference, or a body closing keyword. An- // identifier matched only by a bare mention in the body ("Related- // MUL-1", "Follow up in MUL-1") is not a claim — a passing mention must- // not surface the PR as a working PR for that issue (MUL-3739) — so it- // gets no link row at all, and drops one an earlier claim had created.- //- // MUL-3739 used to write that row anyway and flag it reference_only,- // hidden from every read path. A hidden row had no reader, and once the- // PR went terminal the preserve gate froze the flag, so adding a closing- // keyword to a merged PR's body could never surface it — the one- // recovery action a user can take was the one that could not work- // (MUL-7072).- claimedIdents := map[string]struct{}{}- for _, id := range extractIdentifiers(p.PullRequest.Title, p.PullRequest.Head.Ref) {- claimedIdents[id] = struct{}{}- }- for c := range closingIdents {- claimedIdents[c] = struct{}{}+ // GitHub features restores history without backfill), but links and status+ // changes are side-effects gated by the master `github_enabled` switch.+ ws, err := h.Queries.GetWorkspace(ctx, wsID)+ if err == nil && githubFeaturesEnabled(ws) && !linkPolicy.indeterminate {+ touched := map[pgtype.UUID]struct{}{}+ if autoLink, _ := autoLinkPRsEnabledForWorkspace(ws); autoLink {+ linkedIssueIDs, touched = h.reconcileAutoLinks(ctx, ws, pr.ID, state, prAutoLinkInput{+ idents: extractIdentifiers(p.PullRequest.Title, p.PullRequest.Head.Ref),+ permits: func(id string) bool { return linkPolicy.permits(id, workspaceID) },+ ambiguous: func(id string) bool { return linkPolicy.ambiguous[id] },+ link: func(issueID pgtype.UUID) (int64, error) {+ return h.Queries.LinkIssueToPullRequest(ctx, db.LinkIssueToPullRequestParams{IssueID: issueID, PullRequestID: pr.ID})+ },+ unlink: func(issueID pgtype.UUID) (int64, error) {+ return h.Queries.UnlinkIssueFromPullRequest(ctx, db.UnlinkIssueFromPullRequestParams{IssueID: issueID, PullRequestID: pr.ID})+ },+ listAuto: func() ([]pgtype.UUID, error) {+ return h.Queries.ListAutoLinkedIssueIDsForPullRequest(ctx, pr.ID)+ },+ })}- // close_intent should follow the PR title/body while the PR is still- // editable before its terminal close event. Once GitHub has delivered- // a terminal event, later edit/synchronize webhooks must not rewrite- // the merge-time close decision.- preserveCloseIntent := p.Action != "closed" && (state == "merged" || state == "closed")- prefix := h.getIssuePrefix(ctx, wsID)- // reevalIssues collects each issue whose link row we just touched so- // we can re-run the auto-advance gate against the persisted aggregate- // after every link upsert in this event. Driving the gate off- // persisted state (instead of "did *this* webhook declare closing- // intent?") is what fixes the multi-PR sibling case: a PR with- // `Closes MUL-1` merges first while a link-only sibling is still- // open, then the sibling closes later — its webhook has no closing- // keyword, but the earlier link row carries close_intent=true, so- // MUL-1 still advances.- reevalIssues := make([]db.Issue, 0, len(idents))- for _, id := range idents {- issue, ok := h.lookupIssueByIdentifier(ctx, wsID, prefix, id)- if !ok {- continue- }- if _, claimed := claimedIdents[id]; !claimed {- // A passing mention. Never links; while the PR is still- // editable it also drops a link an earlier claim created, so- // the list follows the live parse. Once the PR is terminal the- // same preserve rule that freezes close_intent applies: a- // post-merge edit must not unlink a PR that did the work.- if preserveCloseIntent {- continue- }- if err := h.Queries.UnlinkIssueFromPullRequest(ctx, db.UnlinkIssueFromPullRequestParams{- IssueID: issue.ID,- PullRequestID: pr.ID,- }); err != nil {- slog.Warn("github: unlink failed", "err", err)- continue- }- // Dropping a link can be what lets the issue advance, so the- // gate below still re-evaluates it.- reevalIssues = append(reevalIssues, issue)- continue+ // A merge is a PR event for every issue this PR is linked to, manual+ // links included.+ if state == "merged" && prevState != "merged" {+ issueIDs, err := h.Queries.ListIssueIDsForPullRequest(ctx, pr.ID)+ if err != nil {+ slog.Warn("github: list linked issues failed", "err", err)}- _, 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+ for _, id := range issueIDs {+ touched[id] = struct{}{}}- closeIntent := declared && !preserveCloseIntent- if err := h.Queries.LinkIssueToPullRequest(ctx, db.LinkIssueToPullRequestParams{- IssueID: issue.ID,- PullRequestID: pr.ID,- CloseIntent: closeIntent,- PreserveCloseIntent: preserveCloseIntent,- LinkedByType: strToText("system"),- LinkedByID: pgtype.UUID{},- }); err != nil {- slog.Warn("github: link failed", "err", err)- continue- }- linkedIssueIDs = append(linkedIssueIDs, uuidToString(issue.ID))- reevalIssues = append(reevalIssues, issue)}-- // A terminal PR event (`merged` or `closed`) may be the moment the- // last in-flight sibling resolves. We re-evaluate every issue we- // just linked once both the PR row and the link row are persisted,- // so the aggregate query sees the freshest state. We advance the- // issue to done when:- // 1. the issue isn't already terminal (`done` / `cancelled`);- // 2. no linked PR is still `open` / `draft`;- // 3. at least one merged linked PR declared close_intent (a- // "Closes/Fixes/Resolves" keyword on its link row).- // Rule (3) is what prevents "Follow up in MUL-2" / "Unblocks MUL-3"- // references from being treated the same as "Closes MUL-1", and- // also prevents an "all closed-without-merge" sequence from- // silently auto-closing the issue — if nothing carrying closing- // intent was ever delivered, the user should decide manually.- if state == "merged" || state == "closed" {- // All linked issues belong to this workspace. Resolve custom statuses- // once per delivery; built-in statuses still need no catalog read.- resolver := issuestatus.NewResolver(wsID)- for _, issue := range reevalIssues {- // A custom terminal status counts as terminal here. (MUL-6243)- if s := resolver.Effective(ctx, h.issueStatusCatalog(), issue.Status); s == "done" || s == "cancelled" {- continue- }- // Combined across providers: an issue may also carry a still-open- // self-hosted VCS PR, which must block auto-advance here just as- // an open GitHub PR blocks it on the VCS webhook path.- counts, err := h.Queries.GetIssueCombinedPullRequestCloseAggregate(ctx, issue.ID)- if err != nil {- slog.Warn("github: count linked pr states failed", "err", err, "issue_id", uuidToString(issue.ID))- continue- }- if counts.OpenCount == 0 && counts.MergedWithCloseIntentCount > 0 {- h.advanceIssueToDone(ctx, issue, workspaceID)- }- }+ // One status-catalog read per workspace per delivery, however many+ // issues the PR touches.+ resolver := issuestatus.NewResolver(wsID)+ for issueID := range touched {+ h.maybeAutoCompleteIssue(ctx, wsID, issueID, resolver)}}@@ -1722,6 +1617,93 @@ func (h *Handler) mirrorPullRequestForWorkspace(ctx context.Context, wsID pgtype})}+// prAutoLinkInput is what reconcileAutoLinks needs from one provider.+type prAutoLinkInput struct {+ idents []string // identifiers in the PR title and branch+ permits func(identifier string) bool // cross-workspace verdict (always true for VCS)+ ambiguous func(identifier string) bool // resolved in several workspaces+ link func(pgtype.UUID) (int64, error) // automatic link; 1 when new+ unlink func(pgtype.UUID) (int64, error) // drop a link; 1 when removed+ listAuto func() ([]pgtype.UUID, error) // issues currently auto-linked to the PR+}++// reconcileAutoLinks makes the PR's automatic links match its title and branch.+// It returns the issue ids the PR is linked to after the pass, and the issues+// whose link set changed (a PR event for auto-complete).+//+// - A claimed identifier that resolves here links, unless a person removed+// that PR from that issue before.+// - An automatic link the PR no longer claims is dropped while the PR is still+// open. After merge/close it is kept: a later title edit must not take the+// delivered work off the issue.+// - An automatic link for an identifier that turned out to be ambiguous+// across bound workspaces is always dropped (see prLinkPolicy).+//+// Manual links are never touched here.+func (h *Handler) reconcileAutoLinks(ctx context.Context, ws db.Workspace, prID pgtype.UUID, state string, in prAutoLinkInput) ([]string, map[pgtype.UUID]struct{}) {+ touched := map[pgtype.UUID]struct{}{}+ linked := make([]string, 0)+ claimed := map[pgtype.UUID]struct{}{}+ ambiguousIssues := map[pgtype.UUID]struct{}{}+ prefix := issuePrefixForWorkspace(ws)+ for _, id := range in.idents {+ issue, ok := h.lookupIssueByIdentifier(ctx, ws.ID, prefix, id)+ if !ok {+ continue+ }+ if !in.permits(id) {+ if in.ambiguous(id) {+ ambiguousIssues[issue.ID] = struct{}{}+ }+ continue+ }+ excluded, err := h.Queries.IsPullRequestExcludedFromIssue(ctx, db.IsPullRequestExcludedFromIssueParams{IssueID: issue.ID, PullRequestID: prID})+ if err != nil {+ slog.Warn("pr link: exclusion lookup failed", "err", err)+ continue+ }+ if excluded {+ continue+ }+ claimed[issue.ID] = struct{}{}+ rows, err := in.link(issue.ID)+ if err != nil {+ slog.Warn("pr link: link failed", "err", err)+ continue+ }+ linked = append(linked, uuidToString(issue.ID))+ if rows > 0 {+ touched[issue.ID] = struct{}{}+ }+ }++ terminal := state == "merged" || state == "closed"+ current, err := in.listAuto()+ if err != nil {+ slog.Warn("pr link: list auto links failed", "err", err)+ return linked, touched+ }+ for _, issueID := range current {+ if _, ok := claimed[issueID]; ok {+ continue+ }+ _, ambiguous := ambiguousIssues[issueID]+ if terminal && !ambiguous {+ continue+ }+ rows, err := in.unlink(issueID)+ if err != nil {+ slog.Warn("pr link: unlink failed", "err", err)+ continue+ }+ if rows > 0 {+ // Dropping an unmerged PR can leave only merged ones behind.+ touched[issueID] = struct{}{}+ }+ }+ return linked, touched+}+// derivePRMergeableState resolves the upsert behaviour for the PR row's// mergeable_state column on a `pull_request` webhook. It returns three// states encoded as (value, clear):@@ -1819,29 +1801,6 @@ func extractIdentifiers(parts ...string) []string {return out}-// extractClosingIdentifiers pulls every "PREFIX-NUMBER" identifier that-// appears immediately after a GitHub-style closing keyword in the supplied-// fields, deduplicating in input order. Identifiers in branch names are-// intentionally excluded — callers should pass only title and body — because-// branch names are not natural-language fields and treating "mul-1/fix-login"-// as a close declaration would silently re-open the bug this gate is meant-// to fix.-func extractClosingIdentifiers(parts ...string) []string {- seen := map[string]struct{}{}- out := []string{}- for _, src := range parts {- for _, m := range closingIdentifierRe.FindAllStringSubmatch(src, -1) {- ident := strings.ToUpper(m[1]) + "-" + m[2]- if _, dup := seen[ident]; dup {- continue- }- seen[ident] = struct{}{}- out = append(out, ident)- }- }- return out-}-// 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"@@ -1850,8 +1809,8 @@ func extractClosingIdentifiers(parts ...string) []string {//// 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.+// keep taking the default, but the cross-workspace scan has to tell "auto-link+// is on" apart from "we could not find out" — see prLinkPolicy.func autoLinkPRsEnabledForWorkspace(ws db.Workspace) (bool, error) {if len(ws.Settings) == 0 {return true, nil@@ -1872,13 +1831,18 @@ func autoLinkPRsEnabledForWorkspace(ws db.Workspace) (bool, error) {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 {+// githubFeaturesEnabled reads the GitHub master switch. Absent means on.+func githubFeaturesEnabled(ws db.Workspace) bool {+ if len(ws.Settings) == 0 {+ return true+ }+ var s struct {+ GitHubEnabled *bool `json:"github_enabled"`+ }+ if err := json.Unmarshal(ws.Settings, &s); err != nil {return true}- enabled, _ := autoLinkPRsEnabledForWorkspace(ws)- return enabled+ return s.GitHubEnabled == nil || *s.GitHubEnabled}// issueNumberForPrefix returns the issue number encoded in a "PREFIX-NUMBER"@@ -1919,62 +1883,6 @@ func (h *Handler) lookupIssueByIdentifier(ctx context.Context, workspaceID pgtypreturn issue, true}-func (h *Handler) advanceIssueToDone(ctx context.Context, issue db.Issue, workspaceID string) {- // An issue leaves Triage only by being accepted; a merged "Closes" PR- // links to it but must not move it out. (MUL-7189 §2.2)- if issue.TriageState.Valid {- return- }- tx, err := h.TxStarter.Begin(ctx)- if err != nil {- slog.Warn("github: advance issue to done failed", "err", err)- return- }- defer tx.Rollback(ctx)- qtx := h.Queries.WithTx(tx)- updated, err := qtx.UpdateIssueStatus(ctx, db.UpdateIssueStatusParams{- ID: issue.ID,- Status: "done",- WorkspaceID: issue.WorkspaceID,- })- var cancelledWakeups []db.AgentTaskQueue- if err == nil {- cancelledWakeups, err = service.StopClosedIssueWakeups(ctx, qtx, updated)- }- if err == nil {- err = tx.Commit(ctx)- }- if err != nil {- slog.Warn("github: advance issue to done failed", "err", err)- return- }- h.broadcastCancelledWakeups(ctx, updated.WorkspaceID, cancelledWakeups)-- // Fire the platform parent-notification path on the same transition the- // HTTP UpdateIssue / BatchUpdateIssues paths use. A merged PR is one of- // the most common ways a sub-issue actually reaches `done`, and skipping- // it here would leave the parent silent for the dominant completion path.- // notifyParentOfChildDone re-checks every guard (prev != done, parent- // exists, parent not terminal), so calling it unconditionally is safe.- h.notifyParentOfChildDone(ctx, issue, updated)-- prefix := h.getIssuePrefix(ctx, issue.WorkspaceID)- resp := issueToResponse(updated, prefix)- h.fillStatusCategory(ctx, updated.WorkspaceID, &resp)- h.publish(protocol.EventIssueUpdated, workspaceID, "system", "", map[string]any{- "issue": resp,- "status_changed": true,- "prev_status": issue.Status,- "creator_type": issue.CreatorType,- "creator_id": uuidToString(issue.CreatorID),- "source": "github_pr_merged",- // Reaching done clears a duplicate mark (MUL-7349); carry both ends so- // the activity log and clients see the mark go.- "duplicate_of_issue_id": liveDuplicateMark(updated.Status, updated.DuplicateOfIssueID),- "prev_duplicate_of_issue_id": liveDuplicateMark(issue.Status, issue.DuplicateOfIssueID),- })-}-// ── Helpers ─────────────────────────────────────────────────────────────────func parseStrictUUID(s string) (pgtype.UUID, error) {diff --git a/server/internal/handler/github_test.go b/server/internal/handler/github_test.goindex 954e0be2d2..ccc4e2aa78 100644--- a/server/internal/handler/github_test.go+++ b/server/internal/handler/github_test.go@@ -82,77 +82,6 @@ func TestExtractIdentifiers(t *testing.T) {}}-func TestExtractClosingIdentifiers(t *testing.T) {- cases := []struct {- name string- in []string- want []string- }{- {- name: "single_closes",- in: []string{"", "Closes MUL-1"},- want: []string{"MUL-1"},- },- {- name: "single_character_prefix",- in: []string{"", "Closes H-412"},- want: []string{"H-412"},- },- {- name: "all_keyword_inflections",- in: []string{- "",- "close MUL-1\nclosed MUL-2\ncloses MUL-3\nfix MUL-4\nfixes MUL-5\nfixed MUL-6\nresolve MUL-7\nresolves MUL-8\nresolved MUL-9",- },- want: []string{"MUL-1", "MUL-2", "MUL-3", "MUL-4", "MUL-5", "MUL-6", "MUL-7", "MUL-8", "MUL-9"},- },- {- name: "case_insensitive_and_colon",- in: []string{"CLOSES: MUL-1", "Fixes:MUL-2 resolves MUL-3"},- want: []string{"MUL-1", "MUL-2", "MUL-3"},- },- {- name: "bare_reference_does_not_close",- // The bug-report repro: only ABC-1 carries closing intent.- // ABC-2/ABC-3 are linked (extractIdentifiers) but must not- // appear in the closing set.- in: []string{"ABC-1: Lorem Ipsum", "Closes ABC-1. Follow up work planned in ABC-2. Unblocks ABC-3."},- want: []string{"ABC-1"},- },- {- name: "keyword_not_adjacent_does_not_close",- // "Fix login MUL-1" — keyword present but the identifier is- // not adjacent. Consistent with GitHub's closing-keyword- // grammar; matches via extractIdentifiers for linking only.- in: []string{"Fix login MUL-1", ""},- want: []string{},- },- {- name: "dedupe_across_fields",- in: []string{"Closes MUL-1", "fixes mul-1"},- want: []string{"MUL-1"},- },- {- name: "no_match_on_disclosed_or_foreclose",- // Word-boundary guards against keyword fragments embedded- // in larger words ("Disclosed MUL-1", "Foreclose MUL-1").- in: []string{"Disclosed MUL-1 in foreclose MUL-2", ""},- want: []string{},- },- }- for _, tc := range cases {- t.Run(tc.name, func(t *testing.T) {- got := extractClosingIdentifiers(tc.in...)- if len(got) == 0 && len(tc.want) == 0 {- return- }- if !reflect.DeepEqual(got, tc.want) {- t.Errorf("extractClosingIdentifiers() = %v, want %v", got, tc.want)- }- })- }-}-func TestDerivePRState(t *testing.T) {cases := []struct {state string@@ -765,10 +694,10 @@ func firePullRequestWebhook(t *testing.T, secret, identifier string, installatio}}-// TestWebhook_ClosedSiblingAfterMerge guards the ordering bug GPT-Boy flagged-// on PR #2470: PR-A merges first (issue stays in_progress because PR-B is-// open), then PR-B closes WITHOUT merging. Because PR-A already delivered the-// work, that close event must re-evaluate the issue and advance it to done.+// TestWebhook_ClosedSiblingAfterMerge pins the MUL-7429 rule for a sibling+// that closes without merging: "all linked PRs merged" is the only completion+// condition, so the issue waits and shows the unmerged PR. Removing that PR+// from the issue is a PR event and completes it.func TestWebhook_ClosedSiblingAfterMerge(t *testing.T) {if testHandler == nil {t.Skip("handler test fixture not initialized (no DB?)")@@ -786,6 +715,7 @@ func TestWebhook_ClosedSiblingAfterMerge(t *testing.T) {json.NewDecoder(w.Body).Decode(&created)t.Cleanup(func() {+ testPool.Exec(ctx, `DELETE FROM issue_pull_request_exclusion WHERE issue_id = $1`, created.ID)testPool.Exec(ctx, `DELETE FROM issue_pull_request WHERE issue_id = $1`, created.ID)testPool.Exec(ctx, `DELETE FROM github_pull_request WHERE workspace_id = $1`, testWorkspaceID)testPool.Exec(ctx, `DELETE FROM github_installation WHERE workspace_id = $1`, testWorkspaceID)@@ -817,15 +747,28 @@ func TestWebhook_ClosedSiblingAfterMerge(t *testing.T) {t.Fatalf("issue should stay in_progress while sibling PR open, got %q", intermediate.Status)}- // Close PR B WITHOUT merging — issue should now advance to done because- // PR-A's merge already delivered the work.+ // Close PR B WITHOUT merging — a closed PR is not a merged one, so the+ // issue keeps waiting and names the unmerged PR.firePullRequestWebhook(t, secret, created.Identifier, installationID, "repo-b", 2, "closed")+ afterClose, err := testHandler.Queries.GetIssue(ctx, parseUUID(created.ID))+ if err != nil {+ t.Fatalf("GetIssue: %v", err)+ }+ if afterClose.Status != "in_progress" {+ t.Fatalf("a closed-unmerged sibling must block auto-complete, got %q", afterClose.Status)+ }+ if got := prAutoCompleteStateForTest(t, created.ID); got.State != prAutoCompleteNotMerged || len(got.PullRequestIDs) != 1 {+ t.Fatalf("auto_complete = %+v, want not_merged naming the closed PR", got)+ }++ // Removing the abandoned PR leaves only merged work behind.+ unlinkPRForTest(t, created.ID, githubPRIDForTest(t, "repo-b", 2))final, err := testHandler.Queries.GetIssue(ctx, parseUUID(created.ID))if err != nil {t.Fatalf("GetIssue: %v", err)}if final.Status != "done" {- t.Errorf("expected issue 'done' after sibling closed-without-merge follows a prior merge, got %q", final.Status)+ t.Errorf("expected issue 'done' after the unmerged PR was removed, got %q", final.Status)}}@@ -923,232 +866,201 @@ func fireBareWebhook(t *testing.T, secret string, installationID int64, prNumber}}-// TestWebhook_MergedPR_OnlyClosesIdentifiersWithClosingKeyword is the repro-// from GitHub issue multica-ai/multica#3264: a PR that mentions three issues-// must only auto-complete the one declared with a closing keyword. Follow-up-// / unblocks references are linked but stay in their previous status.-func TestWebhook_MergedPR_OnlyClosesIdentifiersWithClosingKeyword(t *testing.T) {- if testHandler == nil {- t.Skip("handler test fixture not initialized (no DB?)")- }+// ── PR auto-complete (MUL-7429) ────────────────────────────────────────────+//+// The rule these tests pin: a PR links to an issue when its title or branch+// carries the identifier (or a member links it by hand); when every linked PR+// is merged, the issue moves to Done. Keywords have no special meaning and the+// body is not scanned. The decision runs only on a PR event for the issue.++// prAutoCompleteTestIssue creates an in_progress issue plus a GitHub+// installation for the test workspace, with cleanup for everything the+// webhook and the link endpoints can write.+func prAutoCompleteTestIssue(t *testing.T, title string, installationID int64) IssueResponse {+ t.Helper()ctx := context.Background()- secret := "closing-keyword-secret"- t.Setenv("GITHUB_WEBHOOK_SECRET", secret)-- // Three issues to mention in the same PR body.- createIssue := func(title string) IssueResponse {- t.Helper()- req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{- "title": title,- "status": "in_progress",- })- w := testutil.Call(t, testHandler.CreateIssue, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateIssue %q: %d %s", title, w.Code, w.Body.String())- }- var out IssueResponse- json.NewDecoder(w.Body).Decode(&out)- return out- }- closes := createIssue("primary work")- followUp := createIssue("follow up work")- unblocks := createIssue("unblocked work")-+ req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{+ "title": title,+ "status": "in_progress",+ })+ w := testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusCreated)+ var created IssueResponse+ json.NewDecoder(w.Body).Decode(&created)t.Cleanup(func() {- for _, id := range []string{closes.ID, followUp.ID, unblocks.ID} {- testPool.Exec(ctx, `DELETE FROM issue_pull_request WHERE issue_id = $1`, id)- testPool.Exec(ctx, `DELETE FROM activity_log WHERE issue_id = $1`, id)- testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, id)+ bg := context.Background()+ testPool.Exec(bg, `DELETE FROM issue_pull_request WHERE issue_id = $1`, created.ID)+ testPool.Exec(bg, `DELETE FROM issue_pull_request_exclusion WHERE issue_id = $1`, created.ID)+ testPool.Exec(bg, `DELETE FROM issue_pr_automation WHERE issue_id = $1`, created.ID)+ testPool.Exec(bg, `DELETE FROM activity_log WHERE issue_id = $1`, created.ID)+ testPool.Exec(bg, `DELETE FROM github_pull_request WHERE workspace_id = $1`, testWorkspaceID)+ testPool.Exec(bg, `DELETE FROM github_installation WHERE workspace_id = $1`, testWorkspaceID)+ testPool.Exec(bg, `DELETE FROM issue WHERE id = $1`, created.ID)+ })+ if installationID != 0 {+ if _, err := testHandler.Queries.CreateGitHubInstallation(ctx, db.CreateGitHubInstallationParams{+ WorkspaceID: parseUUID(testWorkspaceID),+ InstallationID: installationID,+ AccountLogin: fmt.Sprintf("acct-%d", installationID),+ AccountType: "User",+ }); err != nil {+ t.Fatalf("CreateGitHubInstallation: %v", err)}- testPool.Exec(ctx, `DELETE FROM github_pull_request WHERE workspace_id = $1`, testWorkspaceID)- testPool.Exec(ctx, `DELETE FROM github_installation WHERE workspace_id = $1`, testWorkspaceID)- })-- const installationID int64 = 30264001- if _, err := testHandler.Queries.CreateGitHubInstallation(ctx, db.CreateGitHubInstallationParams{- WorkspaceID: parseUUID(testWorkspaceID),- InstallationID: installationID,- AccountLogin: "closing-keyword-acct",- AccountType: "User",- }); err != nil {- t.Fatalf("CreateGitHubInstallation: %v", err)}+ return created+}- // PR title mirrors the reporter's repro shape — bare identifier prefix —- // and body declares closing intent on `closes` only.- title := closes.Identifier + ": Lorem Ipsum dolor sit amet"- body := fmt.Sprintf(- "Closes %s. Follow up work planned in %s. Unblocks %s.",- closes.Identifier, followUp.Identifier, unblocks.Identifier,- )- fireBareWebhook(t, secret, installationID, 1, title, body, "fix/login")-- // The closing-keyword issue (also a bare title prefix) is a genuine target,- // so it shows in the PR list. The follow-up / unblocks issues are matched- // only by a bare body mention, which claims nothing and is therefore not- // linked at all (MUL-3739, MUL-7072).- listed, err := testHandler.Queries.ListPullRequestsByIssue(ctx, parseUUID(closes.ID))+func issueStatusForTest(t *testing.T, issueID string) string {+ t.Helper()+ issue, err := testHandler.Queries.GetIssue(context.Background(), parseUUID(issueID))if err != nil {- t.Fatalf("ListPullRequestsByIssue(%s): %v", closes.Identifier, err)- }- if len(listed) != 1 {- t.Errorf("expected %s (closing keyword) to show in the PR list, got %d rows", closes.Identifier, len(listed))- }- for _, issue := range []IssueResponse{followUp, unblocks} {- listed, err := testHandler.Queries.ListPullRequestsByIssue(ctx, parseUUID(issue.ID))- if err != nil {- t.Fatalf("ListPullRequestsByIssue(%s): %v", issue.Identifier, err)- }- if len(listed) != 0 {- t.Errorf("expected %s (bare body mention) to be absent from the PR list, got %d rows", issue.Identifier, len(listed))- }- // And no row was written: a passing mention leaves nothing behind that a- // later read path or a schema change could surface.- var links int- dbfx.QueryRow(t,- `SELECT count(*) FROM issue_pull_request WHERE issue_id = $1`, issue.ID,- ).Scan(&links)- if links != 0 {- t.Errorf("expected %s to have no link row, got %d", issue.Identifier, links)- }- }-- // Only the closing-keyword identifier advances to done.- wantStatus := map[string]string{- closes.ID: "done",- followUp.ID: "in_progress",- unblocks.ID: "in_progress",- }- for _, issue := range []IssueResponse{closes, followUp, unblocks} {- got, err := testHandler.Queries.GetIssue(ctx, parseUUID(issue.ID))- if err != nil {- t.Fatalf("GetIssue(%s): %v", issue.Identifier, err)- }- if got.Status != wantStatus[issue.ID] {- t.Errorf("issue %s: status = %q, want %q", issue.Identifier, got.Status, wantStatus[issue.ID])- }+ t.Fatalf("GetIssue: %v", err)}+ return issue.Status}-// TestWebhook_MergedPR_TitlePrefixDoesNotClose locks in the design choice-// that a bare "MUL-X: foo" title (no closing keyword) links but never-// auto-completes. The user must write `Closes MUL-X` somewhere if they want-// the merge to flip the status.-func TestWebhook_MergedPR_TitlePrefixDoesNotClose(t *testing.T) {- if testHandler == nil {- t.Skip("handler test fixture not initialized (no DB?)")+func linkedPRCountForTest(t *testing.T, issueID string) int {+ t.Helper()+ rows, err := testHandler.Queries.ListPullRequestsByIssue(context.Background(), parseUUID(issueID))+ if err != nil {+ t.Fatalf("ListPullRequestsByIssue: %v", err)}- ctx := context.Background()- secret := "title-prefix-secret"- t.Setenv("GITHUB_WEBHOOK_SECRET", secret)-- req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{- "title": "title-prefix repro",- "status": "in_progress",- })- w := testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusCreated)- var created IssueResponse- json.NewDecoder(w.Body).Decode(&created)+ return len(rows)+}- t.Cleanup(func() {- testPool.Exec(ctx, `DELETE FROM issue_pull_request WHERE issue_id = $1`, created.ID)- testPool.Exec(ctx, `DELETE FROM activity_log WHERE issue_id = $1`, created.ID)- testPool.Exec(ctx, `DELETE FROM github_pull_request WHERE workspace_id = $1`, testWorkspaceID)- testPool.Exec(ctx, `DELETE FROM github_installation WHERE workspace_id = $1`, testWorkspaceID)- testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, created.ID)- })+type issuePullRequestsBodyForTest struct {+ PullRequests []GitHubPullRequestResponse `json:"pull_requests"`+ AutoComplete prAutoCompleteResponse `json:"auto_complete"`+}- const installationID int64 = 30264002- if _, err := testHandler.Queries.CreateGitHubInstallation(ctx, db.CreateGitHubInstallationParams{- WorkspaceID: parseUUID(testWorkspaceID),- InstallationID: installationID,- AccountLogin: "title-prefix-acct",- AccountType: "User",- }); err != nil {- t.Fatalf("CreateGitHubInstallation: %v", err)+func listIssuePRsForTest(t *testing.T, issueID string) issuePullRequestsBodyForTest {+ t.Helper()+ req := withURLParam(newRequest("GET", "/api/issues/"+issueID+"/pull-requests", nil), "id", issueID)+ w := testutil.Call(t, testHandler.ListPullRequestsForIssue, req).Want(http.StatusOK)+ var out issuePullRequestsBodyForTest+ if err := json.NewDecoder(w.Body).Decode(&out); err != nil {+ t.Fatalf("decode pull requests: %v", err)}+ return out+}- fireBareWebhook(t, secret, installationID, 2, created.Identifier+": fix something", "", "fix/login")+func prAutoCompleteStateForTest(t *testing.T, issueID string) prAutoCompleteResponse {+ t.Helper()+ return listIssuePRsForTest(t, issueID).AutoComplete+}- linked, err := testHandler.Queries.ListPullRequestsByIssue(ctx, parseUUID(created.ID))+func unlinkPRForTest(t *testing.T, issueID, prID string) {+ t.Helper()+ req := newRequest("DELETE", "/api/issues/"+issueID+"/pull-requests/"+prID, nil)+ rctx := chi.NewRouteContext()+ rctx.URLParams.Add("id", issueID)+ rctx.URLParams.Add("prId", prID)+ req = req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))+ testutil.Call(t, testHandler.UnlinkIssuePullRequest, req).Want(http.StatusOK)+}++// linkMergedGitHubPRForTest mirrors a merged PR in the test workspace and+// links it to issueID automatically, for tests that drive the completion path+// without a webhook.+func linkMergedGitHubPRForTest(t *testing.T, issueID, repo string) {+ t.Helper()+ ctx := context.Background()+ now := pgtype.Timestamptz{Time: time.Now(), Valid: true}+ pr, err := testHandler.Queries.UpsertGitHubPullRequest(ctx, db.UpsertGitHubPullRequestParams{+ WorkspaceID: parseUUID(testWorkspaceID), InstallationID: 1, RepoOwner: "acme", RepoName: repo,+ PrNumber: 1, Title: "merged work", State: "merged", HtmlUrl: "https://github.com/acme/" + repo + "/pull/1",+ PrCreatedAt: now, PrUpdatedAt: now,+ })if err != nil {- t.Fatalf("ListPullRequestsByIssue: %v", err)+ t.Fatalf("upsert pr: %v", err)}- if len(linked) != 1 {- t.Errorf("expected 1 linked PR even without a closing keyword, got %d", len(linked))+ t.Cleanup(func() {+ bg := context.Background()+ testPool.Exec(bg, `DELETE FROM issue_pull_request WHERE pull_request_id = $1`, pr.ID)+ testPool.Exec(bg, `DELETE FROM github_pull_request WHERE id = $1`, pr.ID)+ })+ if _, err := testHandler.Queries.LinkIssueToPullRequest(ctx, db.LinkIssueToPullRequestParams{IssueID: parseUUID(issueID), PullRequestID: pr.ID}); err != nil {+ t.Fatalf("link: %v", err)}+}- got, err := testHandler.Queries.GetIssue(ctx, parseUUID(created.ID))+func githubPRIDForTest(t *testing.T, repo string, number int32) string {+ t.Helper()+ pr, err := testHandler.Queries.GetGitHubPullRequest(context.Background(), db.GetGitHubPullRequestParams{+ WorkspaceID: parseUUID(testWorkspaceID), RepoOwner: "acme", RepoName: repo, PrNumber: number,+ })if err != nil {- t.Fatalf("GetIssue: %v", err)- }- if got.Status != "in_progress" {- t.Errorf("expected issue to stay in_progress (title prefix alone is not closing intent), got %q", got.Status)+ t.Fatalf("GetGitHubPullRequest %s#%d: %v", repo, number, err)}+ return uuidToString(pr.ID)}-// TestWebhook_MergedPR_BranchNameDoesNotClose guards the conservative design-// decision that identifiers extracted from the branch name link the PR but-// never auto-complete the issue — branch names are not natural-language-// fields and cannot carry a closing keyword.-func TestWebhook_MergedPR_BranchNameDoesNotClose(t *testing.T) {+// TestWebhook_BodyMentionsDoNotLink is the repro from #3264 under the new+// rule: only the title/branch identifier is a delivery claim. Body text —+// "Closes", "Follow up in", "Unblocks" alike — links nothing and completes+// nothing.+func TestWebhook_BodyMentionsDoNotLink(t *testing.T) {if testHandler == nil {t.Skip("handler test fixture not initialized (no DB?)")}- ctx := context.Background()- secret := "branch-name-secret"+ secret := "body-mention-secret"t.Setenv("GITHUB_WEBHOOK_SECRET", secret)+ const installationID int64 = 30264001+ primary := prAutoCompleteTestIssue(t, "primary work", installationID)+ closes := prAutoCompleteTestIssue(t, "closed only in body", 0)+ followUp := prAutoCompleteTestIssue(t, "follow up work", 0)- req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{- "title": "branch-name repro",- "status": "in_progress",- })- w := testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusCreated)- var created IssueResponse- json.NewDecoder(w.Body).Decode(&created)-- t.Cleanup(func() {- testPool.Exec(ctx, `DELETE FROM issue_pull_request WHERE issue_id = $1`, created.ID)- testPool.Exec(ctx, `DELETE FROM activity_log WHERE issue_id = $1`, created.ID)- testPool.Exec(ctx, `DELETE FROM github_pull_request WHERE workspace_id = $1`, testWorkspaceID)- testPool.Exec(ctx, `DELETE FROM github_installation WHERE workspace_id = $1`, testWorkspaceID)- testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, created.ID)- })+ title := primary.Identifier + ": Lorem Ipsum dolor sit amet"+ body := fmt.Sprintf("Closes %s. Follow up work planned in %s.", closes.Identifier, followUp.Identifier)+ fireBareWebhook(t, secret, installationID, 1, title, body, "fix/login")- const installationID int64 = 30264003- if _, err := testHandler.Queries.CreateGitHubInstallation(ctx, db.CreateGitHubInstallationParams{- WorkspaceID: parseUUID(testWorkspaceID),- InstallationID: installationID,- AccountLogin: "branch-name-acct",- AccountType: "User",- }); err != nil {- t.Fatalf("CreateGitHubInstallation: %v", err)+ if n := linkedPRCountForTest(t, primary.ID); n != 1 {+ t.Errorf("title identifier should link, got %d rows", n)}-- branch := strings.ToLower(created.Identifier) + "/fix-login"- fireBareWebhook(t, secret, installationID, 3, "Fix login flow", "", branch)-- linked, err := testHandler.Queries.ListPullRequestsByIssue(ctx, parseUUID(created.ID))- if err != nil {- t.Fatalf("ListPullRequestsByIssue: %v", err)+ if got := issueStatusForTest(t, primary.ID); got != "done" {+ t.Errorf("title-linked issue: status = %q, want done", got)}- if len(linked) != 1 {- t.Errorf("expected branch-name reference to still link the PR, got %d link rows", len(linked))+ for _, issue := range []IssueResponse{closes, followUp} {+ if n := linkedPRCountForTest(t, issue.ID); n != 0 {+ t.Errorf("%s is only in the body and must not link, got %d rows", issue.Identifier, n)+ }+ if got := issueStatusForTest(t, issue.ID); got != "in_progress" {+ t.Errorf("%s: status = %q, want in_progress", issue.Identifier, got)+ }}+}- got, err := testHandler.Queries.GetIssue(ctx, parseUUID(created.ID))- if err != nil {- t.Fatalf("GetIssue: %v", err)+// TestWebhook_TitleAndBranchLinksComplete: a title prefix or a branch name is+// enough — no keyword needed — which is the MUL-7429 fix itself.+func TestWebhook_TitleAndBranchLinksComplete(t *testing.T) {+ if testHandler == nil {+ t.Skip("handler test fixture not initialized (no DB?)")}- if got.Status != "in_progress" {- t.Errorf("expected issue to stay in_progress (branch-name reference is not closing intent), got %q", got.Status)+ secret := "title-branch-secret"+ t.Setenv("GITHUB_WEBHOOK_SECRET", secret)+ const installationID int64 = 30264002+ byTitle := prAutoCompleteTestIssue(t, "title link", installationID)+ byBranch := prAutoCompleteTestIssue(t, "branch link", 0)++ fireBareWebhook(t, secret, installationID, 2, byTitle.Identifier+": Fix login flow", "", "feat/login")+ fireBareWebhook(t, secret, installationID, 3, "Fix login flow", "", strings.ToLower(byBranch.Identifier)+"/fix-login")++ for _, issue := range []IssueResponse{byTitle, byBranch} {+ if n := linkedPRCountForTest(t, issue.ID); n != 1 {+ t.Errorf("%s: expected 1 linked PR, got %d", issue.Identifier, n)+ }+ if got := issueStatusForTest(t, issue.ID); got != "done" {+ t.Errorf("%s: status = %q, want done", issue.Identifier, got)+ }+ }+ list := listIssuePRsForTest(t, byBranch.ID)+ if len(list.PullRequests) != 1 || list.PullRequests[0].LinkSource != "branch" {+ t.Errorf("link_source = %+v, want branch", list.PullRequests)}}// firePRWebhook fires a webhook for a single PR with caller-controlled-// title, body, branch, and lifecycle (open / merged / closed without-// merge). Tests below need the open→merged sequence so close_intent on-// one PR has to persist across multiple webhook events for a sibling PR.+// title, body, branch, and lifecycle (open / edited / merged / closed without+// merge / edited after merge).func firePRWebhook(t *testing.T, secret string, installationID int64, prNumber int32, title, body, branch, lifecycle string) {t.Helper()var action, state string@@ -1207,403 +1119,244 @@ func firePRWebhook(t *testing.T, secret string, installationID int64, prNumber i}}-func TestWebhook_CloseKeywordRemovedBeforeMergeDoesNotClose(t *testing.T) {+// TestWebhook_IdentifierRemovedBeforeMergeUnlinks: automatic links follow the+// PR's title and branch while it is open, so dropping the identifier removes+// the link and the later merge completes nothing.+func TestWebhook_IdentifierRemovedBeforeMergeUnlinks(t *testing.T) {if testHandler == nil {t.Skip("handler test fixture not initialized (no DB?)")}- ctx := context.Background()- secret := "close-intent-removal-secret"+ secret := "identifier-removed-secret"t.Setenv("GITHUB_WEBHOOK_SECRET", secret)+ const installationID int64 = 30264004+ created := prAutoCompleteTestIssue(t, "identifier removed", installationID)- req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{- "title": "close intent can be removed",- "status": "in_progress",- })- w := testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusCreated)- var created IssueResponse- json.NewDecoder(w.Body).Decode(&created)-- t.Cleanup(func() {- testPool.Exec(ctx, `DELETE FROM issue_pull_request WHERE issue_id = $1`, created.ID)- testPool.Exec(ctx, `DELETE FROM activity_log WHERE issue_id = $1`, created.ID)- testPool.Exec(ctx, `DELETE FROM github_pull_request WHERE workspace_id = $1`, testWorkspaceID)- testPool.Exec(ctx, `DELETE FROM github_installation WHERE workspace_id = $1`, testWorkspaceID)- testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, created.ID)- })-- const installationID int64 = 30264005- if _, err := testHandler.Queries.CreateGitHubInstallation(ctx, db.CreateGitHubInstallationParams{- WorkspaceID: parseUUID(testWorkspaceID),- InstallationID: installationID,- AccountLogin: "close-intent-removal-acct",- AccountType: "User",- }); err != nil {- t.Fatalf("CreateGitHubInstallation: %v", err)- }-- firePRWebhook(t, secret, installationID, 1, "Implement removal path", "Closes "+created.Identifier, "feat/remove-close-intent", "opened")- firePRWebhook(t, secret, installationID, 1, "Implement removal path", "Related "+created.Identifier, "feat/remove-close-intent", "edited")- firePRWebhook(t, secret, installationID, 1, "Implement removal path", "Related "+created.Identifier, "feat/remove-close-intent", "merged")-- got, err := testHandler.Queries.GetIssue(ctx, parseUUID(created.ID))- if err != nil {- t.Fatalf("GetIssue after merge: %v", err)+ firePRWebhook(t, secret, installationID, 1, created.Identifier+": first attempt", "", "feat/attempt", "opened")+ if n := linkedPRCountForTest(t, created.ID); n != 1 {+ t.Fatalf("expected the title to link, got %d rows", n)}- if got.Status != "in_progress" {- t.Fatalf("after closing keyword was removed before merge: status = %q, want in_progress", got.Status)+ firePRWebhook(t, secret, installationID, 1, "Unrelated refactor", "", "feat/attempt", "edited")+ if n := linkedPRCountForTest(t, created.ID); n != 0 {+ t.Fatalf("removing the identifier while open should unlink, got %d rows", n)}- counts, err := testHandler.Queries.GetIssuePullRequestCloseAggregate(ctx, parseUUID(created.ID))- if err != nil {- t.Fatalf("GetIssuePullRequestCloseAggregate: %v", err)- }- if counts.MergedWithCloseIntentCount != 0 {- t.Fatalf("merged_with_close_intent_count = %d, want 0", counts.MergedWithCloseIntentCount)+ firePRWebhook(t, secret, installationID, 1, "Unrelated refactor", "", "feat/attempt", "merged")+ if got := issueStatusForTest(t, created.ID); got != "in_progress" {+ t.Errorf("status = %q, want in_progress", got)}+}- req = newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{- "title": "post merge close keyword is link only",- "status": "in_progress",- })- w = testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusCreated)- var second IssueResponse- json.NewDecoder(w.Body).Decode(&second)- t.Cleanup(func() {- testPool.Exec(ctx, `DELETE FROM issue_pull_request WHERE issue_id = $1`, second.ID)- testPool.Exec(ctx, `DELETE FROM activity_log WHERE issue_id = $1`, second.ID)- testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, second.ID)- })+// TestWebhook_PostMergeTitleEditLinksAndCompletes: adding the identifier to a+// merged PR's title links it, and linking is a PR event — so the issue+// completes. Removing it again after merge keeps the link: the work landed.+func TestWebhook_PostMergeTitleEditLinksAndCompletes(t *testing.T) {+ if testHandler == nil {+ t.Skip("handler test fixture not initialized (no DB?)")+ }+ secret := "post-merge-edit-secret"+ t.Setenv("GITHUB_WEBHOOK_SECRET", secret)+ const installationID int64 = 30264005+ created := prAutoCompleteTestIssue(t, "post-merge link", installationID)- // Adding a closing keyword after the merge must not rewrite the- // merge-time decision and retroactively close either an existing link- // or a newly mentioned issue.- firePRWebhook(t, secret, installationID, 1, "Implement removal path", "Closes "+created.Identifier+"\nCloses "+second.Identifier, "feat/remove-close-intent", "edited_merged")- got, err = testHandler.Queries.GetIssue(ctx, parseUUID(created.ID))- if err != nil {- t.Fatalf("GetIssue after post-merge edit: %v", err)+ firePRWebhook(t, secret, installationID, 1, "Dependency bump", "", "chore/bump", "merged")+ if n := linkedPRCountForTest(t, created.ID); n != 0 {+ t.Fatalf("PR without the identifier must not link, got %d rows", n)}- if got.Status != "in_progress" {- t.Errorf("after adding closing keyword post-merge: status = %q, want in_progress", got.Status)+ firePRWebhook(t, secret, installationID, 1, created.Identifier+": dependency bump", "", "chore/bump", "edited_merged")+ if n := linkedPRCountForTest(t, created.ID); n != 1 {+ t.Fatalf("post-merge title edit should link, got %d rows", n)}- got, err = testHandler.Queries.GetIssue(ctx, parseUUID(second.ID))- if err != nil {- t.Fatalf("GetIssue second after post-merge edit: %v", err)+ if got := issueStatusForTest(t, created.ID); got != "done" {+ t.Errorf("status = %q, want done", got)}- if got.Status != "in_progress" {- t.Errorf("second issue after post-merge closing keyword: status = %q, want in_progress", got.Status)+ firePRWebhook(t, secret, installationID, 1, "Dependency bump", "", "chore/bump", "edited_merged")+ if n := linkedPRCountForTest(t, created.ID); n != 1 {+ t.Errorf("a post-merge edit must not take delivered work off the issue, got %d rows", n)}}-// TestWebhook_LinkOnlySiblingMergeAfterCloseKeywordPR is the regression-// guard for the multi-PR sibling case Elon flagged on the first attempt-// of this fix. Scenario:-//-// 1. PR A declares closing intent (`Closes MUL-X`) and is opened.-// 2. PR B references the same issue (link-only — no closing keyword)-// and is opened.-// 3. PR A merges. The issue stays in_progress because PR B is open.-// 4. PR B merges later. PR B's webhook has no closing keyword, so the-// previous implementation skipped re-evaluating the issue and the-// issue stayed stuck in_progress forever.-//-// The persisted close_intent column on issue_pull_request fixes this:-// the aggregate sees PR A's merged+close_intent row regardless of which-// webhook drives the re-evaluation, so PR B's merge advances the issue.-func TestWebhook_LinkOnlySiblingMergeAfterCloseKeywordPR(t *testing.T) {+// TestWebhook_ReopenedIssueStaysOpenUntilNewPRMerges is the reason the+// decision is edge-triggered. A reopened issue whose PRs are all merged must+// not bounce back to Done on the next unrelated event of a merged PR; the next+// fix PR's merge completes it again — with no hidden per-issue switch flipped+// behind the user's back.+func TestWebhook_ReopenedIssueStaysOpenUntilNewPRMerges(t *testing.T) {if testHandler == nil {t.Skip("handler test fixture not initialized (no DB?)")}ctx := context.Background()- secret := "link-only-sibling-secret"+ secret := "reopen-secret"t.Setenv("GITHUB_WEBHOOK_SECRET", secret)+ const installationID int64 = 30264006+ created := prAutoCompleteTestIssue(t, "reopen flow", installationID)- req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{- "title": "needs two prs",- "status": "in_progress",- })- w := testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusCreated)- var created IssueResponse- json.NewDecoder(w.Body).Decode(&created)-- t.Cleanup(func() {- testPool.Exec(ctx, `DELETE FROM issue_pull_request WHERE issue_id = $1`, created.ID)- testPool.Exec(ctx, `DELETE FROM activity_log WHERE issue_id = $1`, created.ID)- testPool.Exec(ctx, `DELETE FROM github_pull_request WHERE workspace_id = $1`, testWorkspaceID)- testPool.Exec(ctx, `DELETE FROM github_installation WHERE workspace_id = $1`, testWorkspaceID)- testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, created.ID)- })-- const installationID int64 = 30264004- if _, err := testHandler.Queries.CreateGitHubInstallation(ctx, db.CreateGitHubInstallationParams{- WorkspaceID: parseUUID(testWorkspaceID),- InstallationID: installationID,- AccountLogin: "link-only-sibling-acct",- AccountType: "User",- }); err != nil {- t.Fatalf("CreateGitHubInstallation: %v", err)+ firePRWebhook(t, secret, installationID, 1, created.Identifier+": first fix", "", "fix/one", "opened")+ firePRWebhook(t, secret, installationID, 1, created.Identifier+": first fix", "", "fix/one", "merged")+ if got := issueStatusForTest(t, created.ID); got != "done" {+ t.Fatalf("status after first merge = %q, want done", got)}- // 1) PR A opens with closing intent.- firePRWebhook(t, secret, installationID, 1, "Implement primary path", "Closes "+created.Identifier, "feat/primary", "opened")- // 2) PR B opens link-only — title prefix mention, no closing keyword.- firePRWebhook(t, secret, installationID, 2, created.Identifier+": follow-up cleanup", "", "feat/cleanup", "opened")-- // Sanity: issue is still in_progress (both PRs open).- got, err := testHandler.Queries.GetIssue(ctx, parseUUID(created.ID))- if err != nil {- t.Fatalf("GetIssue after open: %v", err)- }- if got.Status != "in_progress" {- t.Fatalf("after both PRs opened: status = %q, want in_progress", got.Status)+ if _, err := testHandler.Queries.UpdateIssueStatus(ctx, db.UpdateIssueStatusParams{+ ID: parseUUID(created.ID), Status: "in_progress", WorkspaceID: parseUUID(testWorkspaceID),+ }); err != nil {+ t.Fatalf("reopen: %v", err)}-- // 3) PR A merges. PR B still open → issue stays in_progress.- firePRWebhook(t, secret, installationID, 1, "Implement primary path", "Closes "+created.Identifier, "feat/primary", "merged")- got, err = testHandler.Queries.GetIssue(ctx, parseUUID(created.ID))- if err != nil {- t.Fatalf("GetIssue after A merge: %v", err)+ // A later event on the already-merged PR (label, edit, redelivery).+ firePRWebhook(t, secret, installationID, 1, created.Identifier+": first fix (edited)", "", "fix/one", "edited_merged")+ if got := issueStatusForTest(t, created.ID); got != "in_progress" {+ t.Fatalf("reopened issue bounced back to %q on an event of a merged PR", got)}- if got.Status != "in_progress" {- t.Fatalf("after PR A merged with PR B still open: status = %q, want in_progress", got.Status)+ if got := prAutoCompleteStateForTest(t, created.ID); got.State != prAutoCompleteAllMerged || got.IssueDisabled {+ t.Fatalf("auto_complete = %+v, want all_merged with the issue still enabled", got)}- // 4) PR B merges (link-only, no closing keyword). The persisted- // close_intent on PR A's link must still carry the advance.- firePRWebhook(t, secret, installationID, 2, created.Identifier+": follow-up cleanup", "", "feat/cleanup", "merged")- got, err = testHandler.Queries.GetIssue(ctx, parseUUID(created.ID))- if err != nil {- t.Fatalf("GetIssue after B merge: %v", err)+ firePRWebhook(t, secret, installationID, 2, created.Identifier+": follow-up fix", "", "fix/two", "opened")+ if got := prAutoCompleteStateForTest(t, created.ID); got.State != prAutoCompleteWaiting {+ t.Fatalf("auto_complete = %+v, want waiting on the new PR", got)}- if got.Status != "done" {- t.Errorf("after both PRs merged (A with close_intent, B link-only): status = %q, want done", got.Status)+ firePRWebhook(t, secret, installationID, 2, created.Identifier+": follow-up fix", "", "fix/two", "merged")+ if got := issueStatusForTest(t, created.ID); got != "done" {+ t.Errorf("status after the follow-up merged = %q, want done", got)}}-// TestWebhook_BareBodyMentionIsNotLinked is the regression guard for MUL-3739:-// a PR that only mentions an issue identifier in its body (no closing keyword,-// no title prefix, no branch reference) claims nothing, so it must not appear in-// that issue's PR list. Editing the body to add or remove a closing keyword-// flips the link itself — while the PR is still open the link follows the live-// title/body parse (MUL-7072).-func TestWebhook_BareBodyMentionIsNotLinked(t *testing.T) {+// TestUnlinkIssuePullRequest_IsRememberedAndCompletes: a removed PR stays+// removed across webhook redeliveries, and removing the last unmerged PR is+// the PR event that completes the issue.+func TestUnlinkIssuePullRequest_IsRememberedAndCompletes(t *testing.T) {if testHandler == nil {t.Skip("handler test fixture not initialized (no DB?)")}- ctx := context.Background()- secret := "bare-mention-secret"+ secret := "unlink-secret"t.Setenv("GITHUB_WEBHOOK_SECRET", secret)+ const installationID int64 = 30264007+ created := prAutoCompleteTestIssue(t, "unlink flow", installationID)- req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{- "title": "mentioned in passing",- "status": "in_progress",- })- w := testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusCreated)- var created IssueResponse- json.NewDecoder(w.Body).Decode(&created)-- t.Cleanup(func() {- testPool.Exec(ctx, `DELETE FROM issue_pull_request WHERE issue_id = $1`, created.ID)- testPool.Exec(ctx, `DELETE FROM activity_log WHERE issue_id = $1`, created.ID)- testPool.Exec(ctx, `DELETE FROM github_pull_request WHERE workspace_id = $1`, testWorkspaceID)- testPool.Exec(ctx, `DELETE FROM github_installation WHERE workspace_id = $1`, testWorkspaceID)- testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, created.ID)- })-- const installationID int64 = 30264006- if _, err := testHandler.Queries.CreateGitHubInstallation(ctx, db.CreateGitHubInstallationParams{- WorkspaceID: parseUUID(testWorkspaceID),- InstallationID: installationID,- AccountLogin: "bare-mention-acct",- AccountType: "User",- }); err != nil {- t.Fatalf("CreateGitHubInstallation: %v", err)- }-- listLen := func() int {- t.Helper()- rows, err := testHandler.Queries.ListPullRequestsByIssue(ctx, parseUUID(created.ID))- if err != nil {- t.Fatalf("ListPullRequestsByIssue: %v", err)- }- return len(rows)- }-- // 1) Opened with only a bare body mention → no link, nothing in the list.- firePRWebhook(t, secret, installationID, 1, "Unrelated cleanup", "Context for reviewers: see "+created.Identifier, "feat/cleanup", "opened")- if n := listLen(); n != 0 {- t.Errorf("bare body mention should not link, got %d rows", n)- }-- // 2) Edited to declare closing intent → now a genuine target, shown.- firePRWebhook(t, secret, installationID, 1, "Unrelated cleanup", "Closes "+created.Identifier, "feat/cleanup", "edited")- if n := listLen(); n != 1 {- t.Errorf("after adding a closing keyword the PR should show, got %d rows", n)+ firePRWebhook(t, secret, installationID, 1, created.Identifier+": abandoned approach", "", "try/one", "opened")+ firePRWebhook(t, secret, installationID, 2, created.Identifier+": real fix", "", "fix/two", "opened")+ firePRWebhook(t, secret, installationID, 2, created.Identifier+": real fix", "", "fix/two", "merged")+ if got := issueStatusForTest(t, created.ID); got != "in_progress" {+ t.Fatalf("status = %q, want in_progress while #1 is open", got)}- // 3) Edited back to a bare mention → the claim is withdrawn, link dropped.- firePRWebhook(t, secret, installationID, 1, "Unrelated cleanup", "Reverting: just referencing "+created.Identifier, "feat/cleanup", "edited")- if n := listLen(); n != 0 {- t.Errorf("after removing the closing keyword the PR should be unlinked, got %d rows", n)+ unlinkPRForTest(t, created.ID, githubPRIDForTest(t, "widget", 1))+ if got := issueStatusForTest(t, created.ID); got != "done" {+ t.Fatalf("status after removing the open PR = %q, want done", got)}- // 4) The same withdrawal must leave no row behind, not a hidden one.- var links int- dbfx.QueryRow(t,- `SELECT count(*) FROM issue_pull_request WHERE issue_id = $1`, created.ID,- ).Scan(&links)- if links != 0 {- t.Errorf("withdrawn claim should leave no link row, got %d", links)+ firePRWebhook(t, secret, installationID, 1, created.Identifier+": abandoned approach", "", "try/one", "edited")+ if n := linkedPRCountForTest(t, created.ID); n != 1 {+ t.Errorf("a removed PR must not be re-linked by the next webhook, got %d rows", n)}}-// TestWebhook_PostMergeClosingKeywordLinksThePR is the MUL-7072 regression-// guard. A PR that only mentioned the issue in its body, merged, and then had-// `Closes KEY` added to the body must show up on the issue: editing the body is-// the one repair a user can make from GitHub, and the pre-MUL-7072 reference_only-// row made it a no-op forever (the preserve gate kept the row hidden, and no-// unlink surface existed to clear it).-//-// The close-intent decision still stays frozen at merge time: the PR appears,-// but it does not retroactively advance the issue to done.-func TestWebhook_PostMergeClosingKeywordLinksThePR(t *testing.T) {+// TestLinkIssuePullRequest_ByURL: a pasted PR URL (with trailing path/query)+// links a mirrored PR by hand; manual links survive title edits, and linking a+// merged PR is a PR event that can complete the issue. An unknown URL is 404.+func TestLinkIssuePullRequest_ByURL(t *testing.T) {if testHandler == nil {t.Skip("handler test fixture not initialized (no DB?)")}- ctx := context.Background()- secret := "post-merge-closes-secret"+ secret := "manual-link-secret"t.Setenv("GITHUB_WEBHOOK_SECRET", secret)+ const installationID int64 = 30264008+ created := prAutoCompleteTestIssue(t, "manual link", installationID)- req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{- "title": "repaired after merge",- "status": "in_progress",- })- w := testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusCreated)- var created IssueResponse- json.NewDecoder(w.Body).Decode(&created)-- t.Cleanup(func() {- testPool.Exec(ctx, `DELETE FROM issue_pull_request WHERE issue_id = $1`, created.ID)- testPool.Exec(ctx, `DELETE FROM activity_log WHERE issue_id = $1`, created.ID)- testPool.Exec(ctx, `DELETE FROM github_pull_request WHERE workspace_id = $1`, testWorkspaceID)- testPool.Exec(ctx, `DELETE FROM github_installation WHERE workspace_id = $1`, testWorkspaceID)- testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, created.ID)- })-- const installationID int64 = 30264009- if _, err := testHandler.Queries.CreateGitHubInstallation(ctx, db.CreateGitHubInstallationParams{- WorkspaceID: parseUUID(testWorkspaceID),- InstallationID: installationID,- AccountLogin: "post-merge-closes-acct",- AccountType: "User",- }); err != nil {- t.Fatalf("CreateGitHubInstallation: %v", err)- }+ firePRWebhook(t, secret, installationID, 41, "Refactor session helper", "", "refactor/session", "merged")- // Opened and merged with nothing but a passing body mention: no link.- firePRWebhook(t, secret, installationID, 1, "Dependency bump", "Context: see "+created.Identifier, "chore/bump", "opened")- firePRWebhook(t, secret, installationID, 1, "Dependency bump", "Context: see "+created.Identifier, "chore/bump", "merged")- listed, err := testHandler.Queries.ListPullRequestsByIssue(ctx, parseUUID(created.ID))- if err != nil {- t.Fatalf("ListPullRequestsByIssue after merge: %v", err)- }- if len(listed) != 0 {- t.Fatalf("passing mention must not link, got %d rows", len(listed))+ link := func(url string) *testutil.Response {+ req := withURLParam(newRequest("POST", "/api/issues/"+created.ID+"/pull-requests", map[string]any{"url": url}), "id", created.ID)+ return testutil.Call(t, testHandler.LinkIssuePullRequest, req)}-- // The author edits the merged PR's body to declare the issue properly.- firePRWebhook(t, secret, installationID, 1, "Dependency bump", "Closes "+created.Identifier, "chore/bump", "edited_merged")- listed, err = testHandler.Queries.ListPullRequestsByIssue(ctx, parseUUID(created.ID))- if err != nil {- t.Fatalf("ListPullRequestsByIssue after post-merge edit: %v", err)+ if rec := link("https://github.com/acme/widget/pull/999"); rec.Code != http.StatusNotFound {+ t.Fatalf("unknown PR: expected 404, got %d (%s)", rec.Code, rec.Body.String())}- if len(listed) != 1 {- t.Fatalf("post-merge closing keyword should link the PR, got %d rows", len(listed))+ if rec := link("github.com/Acme/widget/pull/41/files?w=1"); rec.Code != http.StatusOK {+ t.Fatalf("link: expected 200, got %d (%s)", rec.Code, rec.Body.String())}- if listed[0].State != "merged" {- t.Errorf("linked PR state = %q, want merged", listed[0].State)+ list := listIssuePRsForTest(t, created.ID)+ if len(list.PullRequests) != 1 || list.PullRequests[0].LinkSource != "manual" {+ t.Fatalf("pull_requests = %+v, want one manual link", list.PullRequests)}-- // Close intent stays a merge-time decision: the issue must not advance.- got, err := testHandler.Queries.GetIssue(ctx, parseUUID(created.ID))- if err != nil {- t.Fatalf("GetIssue after post-merge edit: %v", err)+ if got := issueStatusForTest(t, created.ID); got != "done" {+ t.Errorf("linking a merged PR: status = %q, want done", got)}- if got.Status != "in_progress" {- t.Errorf("post-merge closing keyword must not advance the issue: status = %q, want in_progress", got.Status)+ firePRWebhook(t, secret, installationID, 41, "Refactor session helper (renamed)", "", "refactor/session", "edited_merged")+ if n := linkedPRCountForTest(t, created.ID); n != 1 {+ t.Errorf("a manual link must survive webhook reconciliation, got %d rows", n)}}-// TestWebhook_UnlinkedBodyMentionDoesNotBlockAutoAdvance guards the P1 the code-// review flagged on PR #4611: a PR that only mentions the issue in its body does-// not show in the PR list, so it must not silently gate auto-advance either.-// Here PR B stays open with a bare body mention while PR A merges with a closing-// keyword — the issue must still reach `done`, because PR B was never linked and-// so never reaches the close aggregate's open_count.-func TestWebhook_UnlinkedBodyMentionDoesNotBlockAutoAdvance(t *testing.T) {+// TestPRAutoComplete_WorkspaceAndIssueSwitches: turning the workspace setting+// off keeps PRs linked but writes no status; turning it back on completes+// nothing retroactively. The per-issue switch does the same for one issue and+// is recorded on the timeline.+func TestPRAutoComplete_WorkspaceAndIssueSwitches(t *testing.T) {if testHandler == nil {t.Skip("handler test fixture not initialized (no DB?)")}ctx := context.Background()- secret := "hidden-mention-gate-secret"+ secret := "switches-secret"t.Setenv("GITHUB_WEBHOOK_SECRET", secret)+ const installationID int64 = 30264009+ wsOff := prAutoCompleteTestIssue(t, "workspace switch", installationID)+ issueOff := prAutoCompleteTestIssue(t, "issue switch", 0)- req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{- "title": "closing PR plus invisible mention",- "status": "in_progress",- })- w := testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusCreated)- var created IssueResponse- json.NewDecoder(w.Body).Decode(&created)-+ var previous []byte+ dbfx.QueryRow(t, `SELECT settings FROM workspace WHERE id = $1`, testWorkspaceID).Scan(&previous)t.Cleanup(func() {- testPool.Exec(ctx, `DELETE FROM issue_pull_request WHERE issue_id = $1`, created.ID)- testPool.Exec(ctx, `DELETE FROM activity_log WHERE issue_id = $1`, created.ID)- testPool.Exec(ctx, `DELETE FROM github_pull_request WHERE workspace_id = $1`, testWorkspaceID)- testPool.Exec(ctx, `DELETE FROM github_installation WHERE workspace_id = $1`, testWorkspaceID)- testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, created.ID)+ testPool.Exec(context.Background(), `UPDATE workspace SET settings = $1 WHERE id = $2`, previous, testWorkspaceID)})+ dbfx.Exec(t, `UPDATE workspace SET settings = COALESCE(settings, '{}'::jsonb) || '{"pr_auto_complete_enabled": false}'::jsonb WHERE id = $1`, testWorkspaceID)- const installationID int64 = 30264007- if _, err := testHandler.Queries.CreateGitHubInstallation(ctx, db.CreateGitHubInstallationParams{- WorkspaceID: parseUUID(testWorkspaceID),- InstallationID: installationID,- AccountLogin: "hidden-mention-gate-acct",- AccountType: "User",- }); err != nil {- t.Fatalf("CreateGitHubInstallation: %v", err)+ firePRWebhook(t, secret, installationID, 1, wsOff.Identifier+": work", "", "feat/one", "merged")+ if n := linkedPRCountForTest(t, wsOff.ID); n != 1 {+ t.Fatalf("setting off must still link, got %d rows", n)}-- // PR B opens with only a bare body mention → claims nothing, not linked.- firePRWebhook(t, secret, installationID, 1, "Unrelated cleanup", "Context: see "+created.Identifier, "feat/cleanup", "opened")- // PR A opens with a closing keyword → genuine closing PR.- firePRWebhook(t, secret, installationID, 2, "Primary work", "Closes "+created.Identifier, "feat/primary", "opened")-- // Only PR A shows in the list; PR B was never linked.- listed, err := testHandler.Queries.ListPullRequestsByIssue(ctx, parseUUID(created.ID))- if err != nil {- t.Fatalf("ListPullRequestsByIssue: %v", err)+ if got := issueStatusForTest(t, wsOff.ID); got != "in_progress" {+ t.Fatalf("setting off: status = %q, want in_progress", got)+ }+ if got := prAutoCompleteStateForTest(t, wsOff.ID); got.State != prAutoCompleteWorkspaceDisabled || got.WorkspaceEnabled {+ t.Fatalf("auto_complete = %+v, want workspace_disabled", got)}- if len(listed) != 1 {- t.Fatalf("expected only the closing PR to show, got %d rows", len(listed))+ dbfx.Exec(t, `UPDATE workspace SET settings = settings || '{"pr_auto_complete_enabled": true}'::jsonb WHERE id = $1`, testWorkspaceID)+ if got := issueStatusForTest(t, wsOff.ID); got != "in_progress" {+ t.Fatalf("turning the setting on must not complete history, got %q", got)}- // Sanity: issue is still in_progress (PR A open).- got, err := testHandler.Queries.GetIssue(ctx, parseUUID(created.ID))- if err != nil {- t.Fatalf("GetIssue after open: %v", err)+ put := withURLParam(newRequest("PUT", "/api/issues/"+issueOff.ID+"/pr-auto-complete", map[string]any{"disabled": true}), "id", issueOff.ID)+ testutil.Call(t, testHandler.SetIssuePRAutoComplete, put).Want(http.StatusOK)+ firePRWebhook(t, secret, installationID, 2, issueOff.Identifier+": work", "", "feat/two", "merged")+ if got := issueStatusForTest(t, issueOff.ID); got != "in_progress" {+ t.Fatalf("issue switch off: status = %q, want in_progress", got)}- if got.Status != "in_progress" {- t.Fatalf("after both PRs opened: status = %q, want in_progress", got.Status)+ if got := prAutoCompleteStateForTest(t, issueOff.ID); got.State != prAutoCompleteIssueDisabled || !got.IssueDisabled {+ t.Fatalf("auto_complete = %+v, want issue_disabled", got)}-- // PR A merges. PR B is still open but unlinked, so it must NOT count toward- // open_count — the issue should advance to done.- firePRWebhook(t, secret, installationID, 2, "Primary work", "Closes "+created.Identifier, "feat/primary", "merged")- got, err = testHandler.Queries.GetIssue(ctx, parseUUID(created.ID))- if err != nil {- t.Fatalf("GetIssue after merge: %v", err)+ var recorded int+ dbfx.QueryRow(t, `SELECT count(*) FROM activity_log WHERE issue_id = $1 AND action = 'pr_auto_complete_changed'`, issueOff.ID).Scan(&recorded)+ if recorded != 1 {+ t.Errorf("expected the switch change on the timeline, got %d entries", recorded)}- if got.Status != "done" {- t.Errorf("closing PR merged while only an unlinked body-only mention is open: status = %q, want done", got.Status)+ _ = ctx+}++func TestNormalizePullRequestURL(t *testing.T) {+ for _, tc := range []struct {+ in, want string+ ok bool+ }{+ {"https://github.com/Acme/Widget/pull/12", "https://github.com/acme/widget/pull/12", true},+ {"github.com/acme/widget/pull/12/files?diff=split#r1", "https://github.com/acme/widget/pull/12", true},+ {"https://gitlab.example.com/group/sub/repo/-/merge_requests/7/diffs", "https://gitlab.example.com/group/sub/repo/-/merge_requests/7", true},+ {"https://git.example.com/acme/widget/pulls/3", "https://git.example.com/acme/widget/pulls/3", true},+ {"https://github.com/acme/widget/issues/12", "", false},+ {"not a url", "", false},+ {"", "", false},+ } {+ got, ok := normalizePullRequestURL(tc.in)+ if ok != tc.ok || got != tc.want {+ t.Errorf("normalizePullRequestURL(%q) = (%q, %v), want (%q, %v)", tc.in, got, ok, tc.want, tc.ok)+ }}}@@ -2098,9 +1851,9 @@ func TestGitHubInstallationBroadcastRedaction(t *testing.T) {// TestWebhook_MergedPR_ChildWithParent_NotifiesParent guards the MUL-2538// must-fix: a merged PR is the dominant path by which a sub-issue actually-// reaches `done`, and that path goes through advanceIssueToDone — not the+// reaches `done`, and that path goes through maybeAutoCompleteIssue — not the// HTTP UpdateIssue / BatchUpdateIssues handlers that originally wired up-// notifyParentOfChildDone. Without the helper call inside advanceIssueToDone,+// notifyParentOfChildDone. Without the helper call inside maybeAutoCompleteIssue,// the parent receives nothing when a child is closed by merging its PR.// This test fires a `pull_request closed merged` webhook against a child// issue and verifies the parent gets exactly one platform-generated system@@ -2898,14 +2651,13 @@ 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.+// regression under MUL-7429. Two workspaces bound to the same installation share+// an issue prefix (permitted by #2797) and both own a real issue at the same+// number, so a PR titled "Fix AMB-<n>" resolves in BOTH after the #5183+// fan-out. A link now means "this PR delivers the issue" and a merged link set+// completes it, so an identifier nothing in the event can attribute must not+// link in either workspace — otherwise the merge would complete an issue in a+// workspace that has nothing to do with the PR. A member links it by hand.func TestWebhook_PullRequest_AmbiguousCloseAcrossWorkspaces(t *testing.T) {if testHandler == nil || testPool == nil {t.Skip("handler test fixture not initialized (no DB?)")@@ -2979,14 +2731,12 @@ func TestWebhook_PullRequest_AmbiguousCloseAcrossWorkspaces(t *testing.T) {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.+ // A stale automatic link from before this rule must not survive either.firePullRequestWebhook(t, secret, issueB.Identifier, installationID, repo, prNumber, "open")+ prB := githubPRIDForTest(t, repo, prNumber)+ dbfx.Exec(t, `INSERT INTO issue_pull_request (issue_id, pull_request_id, linked_by_type) VALUES ($1, $2, 'system')`, issueB.ID, prB)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 stringissueID pgtype.UUID@@ -2998,16 +2748,8 @@ func TestWebhook_PullRequest_AmbiguousCloseAcrossWorkspaces(t *testing.T) {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- dbfx.QueryRow(t,- `SELECT close_intent FROM issue_pull_request WHERE issue_id = $1`, tc.issueID,- ).Scan(&closeIntent)- if closeIntent {- t.Errorf("%s: close_intent must be withheld while the identifier is ambiguous", tc.name)+ if len(linked) != 0 {+ t.Fatalf("%s: an ambiguous identifier must not auto-link, got %d links", tc.name, len(linked))}issue, err := testHandler.Queries.GetIssue(ctx, tc.issueID)@@ -3020,48 +2762,46 @@ func TestWebhook_PullRequest_AmbiguousCloseAcrossWorkspaces(t *testing.T) {}}-// 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) {+// TestPRLinkPolicyPermits pins the fail-closed invariant at the type level:+// the policy is an allowlist, so anything it was not able to prove is denied.+func TestPRLinkPolicyPermits(t *testing.T) {const wsA, wsB = "workspace-a", "workspace-b"for _, tc := range []struct {name string- policy closeIntentPolicy+ policy prLinkPolicyws stringwant bool}{{- name: "zero value denies (what an indeterminate read returns)",- policy: closeIntentPolicy{},+ name: "zero value denies",+ policy: prLinkPolicy{},ws: wsA,want: false,},{name: "single-binding delivery is unrestricted",- policy: closeIntentPolicy{unrestricted: true},+ policy: prLinkPolicy{unrestricted: true},ws: wsA,want: true,},{- name: "recorded owner may act",- policy: closeIntentPolicy{owner: map[string]string{"ABC-100": wsA}},+ name: "recorded owner may link",+ policy: prLinkPolicy{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}},+ // the recorded owner, so it still cannot link.+ name: "workspace that is not the recorded owner may not link",+ policy: prLinkPolicy{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}},+ name: "ambiguous identifier is denied everywhere",+ policy: prLinkPolicy{owner: map[string]string{}, ambiguous: map[string]bool{"ABC-100": true}},ws: wsA,want: false,},@@ -3075,7 +2815,7 @@ func TestCloseIntentPolicyPermits(t *testing.T) {}// TestWebhook_PullRequest_UniqueResolverAmongBindingsStillAutoCompletes is the-// other half of the #6804 fix: withholding close intent must be scoped to the+// other half of the #6804 fix: withholding links 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.@@ -3133,12 +2873,12 @@ func TestWebhook_PullRequest_UniqueResolverAmongBindingsStillAutoCompletes(t *te}// TestWebhook_PullRequest_UnreadableWorkspaceWithholdsCloseIntent covers the-// fail-closed half of resolveCloseIntentPolicy. The setup is identical to the+// fail-closed half of resolvePRLinkPolicy. 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.+// might or might not be a second resolver, and since we cannot rule it out, the+// delivery changes no link and no status: a transient read failure must never+// promote an ambiguous identifier 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?)")@@ -3187,12 +2927,8 @@ func TestWebhook_PullRequest_UnreadableWorkspaceWithholdsCloseIntent(t *testing.firePullRequestWebhook(t, secret, issueB.Identifier, installationID, repo, prNumber, "open")firePullRequestWebhook(t, secret, issueB.Identifier, installationID, repo, prNumber, "merged")- var closeIntent bool- dbfx.QueryRow(t,- `SELECT close_intent FROM issue_pull_request WHERE issue_id = $1`, parseUUID(issueB.ID),- ).Scan(&closeIntent)- if closeIntent {- t.Error("close_intent must be withheld when a bound workspace could not be inspected")+ if n := linkedPRCountForTest(t, issueB.ID); n != 0 {+ t.Errorf("no link may be written when a bound workspace could not be inspected, got %d", n)}issue, err := testHandler.Queries.GetIssue(ctx, parseUUID(issueB.ID))diff --git a/server/internal/handler/issue_triage_guard_test.go b/server/internal/handler/issue_triage_guard_test.goindex c580270750..30c477391d 100644--- a/server/internal/handler/issue_triage_guard_test.go+++ b/server/internal/handler/issue_triage_guard_test.go@@ -184,14 +184,12 @@ func TestTriageIssueIsNotAnActiveDuplicate(t *testing.T) {dbfx.Cleanup(t, `DELETE FROM issue WHERE id = $1`, parseUUID(created.ID))}-// A merged "Closes" PR links to a triage issue but must not move it out.+// A merged PR links to a triage issue but must not move it out.func TestPullRequestMergeDoesNotAdvanceTriageIssue(t *testing.T) {issueID := triageIssueForTest(t, "closed by a PR while in triage")- issue, err := testHandler.Queries.GetIssue(context.Background(), parseUUID(issueID))- if err != nil {- t.Fatalf("load issue: %v", err)- }- testHandler.advanceIssueToDone(context.Background(), issue, testWorkspaceID)+ ctx := context.Background()+ linkMergedGitHubPRForTest(t, issueID, "triage-guard")+ testHandler.maybeAutoCompleteIssue(ctx, parseUUID(testWorkspaceID), parseUUID(issueID), nil)if got := issueStatusOf(t, issueID); got == "done" {t.Fatalf("merged PR moved a Triage entry to done")}diff --git a/server/internal/handler/issue_wakeup_close_test.go b/server/internal/handler/issue_wakeup_close_test.goindex 09bc6405a6..0e67f37dca 100644--- a/server/internal/handler/issue_wakeup_close_test.go+++ b/server/internal/handler/issue_wakeup_close_test.go@@ -32,11 +32,8 @@ func TestIssueCloseStopsWakeupsInApplication(t *testing.T) {testutil.Call(t, testHandler.BatchUpdateIssues, req).Want(http.StatusOK)}},{"merged pull request", func(t *testing.T, issue string) {- row, err := testHandler.Queries.GetIssue(ctx, parseUUID(issue))- if err != nil {- t.Fatal(err)- }- testHandler.advanceIssueToDone(ctx, row, testWorkspaceID)+ linkMergedGitHubPRForTest(t, issue, "wake-close")+ testHandler.maybeAutoCompleteIssue(ctx, parseUUID(testWorkspaceID), parseUUID(issue), nil)}},} {t.Run(tc.name, func(t *testing.T) {diff --git a/server/internal/handler/pr_auto_complete.go b/server/internal/handler/pr_auto_complete.gonew file mode 100644index 0000000000..3d2ab06a98--- /dev/null+++ b/server/internal/handler/pr_auto_complete.go@@ -0,0 +1,576 @@+package handler++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "log/slog"+ "net/http"+ "net/url"+ "regexp"+ "strings"++ "github.com/go-chi/chi/v5"+ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/issuestatus"+ "github.com/multica-ai/multica/server/internal/service"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/dbid"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++// PR auto-complete (MUL-7429).+//+// The whole rule, as users see it:+//+// - A PR whose title or branch name carries an issue identifier is linked to+// that issue. A member can also link or remove a PR by hand. Keywords such+// as "Closes" have no special meaning and the PR body is not scanned.+// - When every PR linked to an issue is merged, the issue moves to Done —+// unless the workspace turned the setting off or someone turned it off for+// that one issue.+//+// The decision is evaluated only when a PR event touches the issue: a linked PR+// merges, a PR is linked, or a link is removed. Changing a setting, reopening an+// issue, or accepting it from Triage is not a PR event, so it never completes an+// issue by itself. That is what keeps a reopened issue open until new work+// lands, without any hidden per-issue switch.++// Decision states, shared with the issue page (see prAutoCompleteResponse).+const (+ prAutoCompleteNone = "none" // no linked PR+ prAutoCompleteWorkspaceDisabled = "workspace_disabled" // workspace setting off+ prAutoCompleteIssueDisabled = "issue_disabled" // turned off for this issue+ prAutoCompleteTerminal = "terminal" // already done / cancelled+ prAutoCompleteTriage = "triage" // not accepted yet+ prAutoCompleteWaiting = "waiting" // some PRs still open / draft+ prAutoCompleteNotMerged = "not_merged" // some PRs closed without merging+ prAutoCompleteAllMerged = "all_merged" // every linked PR merged+)++type prAutoCompleteDecision struct {+ State string+ // PRs the state is about: still open for waiting, closed-unmerged for+ // not_merged, every linked PR for all_merged.+ PRs []db.ListIssueLinkedPullRequestStatesRow+ // IssueDisabled is reported independently of State so the issue menu can+ // show the right toggle label even when another state wins.+ IssueDisabled bool+}++// prAutoCompleteEnabledForWorkspace reads the workspace-wide switch. Absent+// means on. An unreadable settings blob means off: this switch authorizes a+// status write, so it must not default to the permissive side.+func prAutoCompleteEnabledForWorkspace(ws db.Workspace) bool {+ if len(ws.Settings) == 0 {+ return true+ }+ var s struct {+ Enabled *bool `json:"pr_auto_complete_enabled"`+ }+ if err := json.Unmarshal(ws.Settings, &s); err != nil {+ return false+ }+ return s.Enabled == nil || *s.Enabled+}++// decidePRAutoComplete computes the decision for one issue. resolver may be+// shared across one delivery so a webhook touching many issues reads the+// workspace status catalog at most once; nil builds a fresh one.+func (h *Handler) decidePRAutoComplete(ctx context.Context, ws db.Workspace, issue db.Issue, resolver *issuestatus.Resolver) (prAutoCompleteDecision, error) {+ prs, err := h.Queries.ListIssueLinkedPullRequestStates(ctx, issue.ID)+ if err != nil {+ return prAutoCompleteDecision{}, err+ }+ disabled, err := h.Queries.GetIssuePRAutoCompleteDisabled(ctx, issue.ID)+ if err != nil {+ return prAutoCompleteDecision{}, err+ }+ d := prAutoCompleteDecision{IssueDisabled: disabled}+ switch {+ case len(prs) == 0:+ d.State = prAutoCompleteNone+ return d, nil+ case !prAutoCompleteEnabledForWorkspace(ws):+ d.State = prAutoCompleteWorkspaceDisabled+ return d, nil+ case disabled:+ d.State = prAutoCompleteIssueDisabled+ return d, nil+ }+ if resolver == nil {+ resolver = issuestatus.NewResolver(issue.WorkspaceID)+ }+ // An unresolvable custom key is returned unchanged and treated as not+ // terminal, the same direction the previous merge gate took.+ effective := resolver.Effective(ctx, h.issueStatusCatalog(), issue.Status)+ if effective == "done" || effective == "cancelled" {+ d.State = prAutoCompleteTerminal+ return d, nil+ }+ if issue.TriageState.Valid {+ d.State = prAutoCompleteTriage+ return d, nil+ }+ var open, closed []db.ListIssueLinkedPullRequestStatesRow+ for _, pr := range prs {+ switch pr.State {+ case "open", "draft":+ open = append(open, pr)+ case "closed":+ closed = append(closed, pr)+ }+ }+ switch {+ case len(open) > 0:+ d.State, d.PRs = prAutoCompleteWaiting, open+ case len(closed) > 0:+ d.State, d.PRs = prAutoCompleteNotMerged, closed+ default:+ d.State, d.PRs = prAutoCompleteAllMerged, prs+ }+ return d, nil+}++// maybeAutoCompleteIssue runs the decision for one issue after a PR event and+// moves it to Done when every linked PR is merged. Safe to call for any issue:+// every guard lives in decidePRAutoComplete, and the status write is+// conditional on the status the decision saw, so concurrent merges complete the+// issue once.+func (h *Handler) maybeAutoCompleteIssue(ctx context.Context, workspaceID, issueID pgtype.UUID, resolver *issuestatus.Resolver) {+ issue, err := h.Queries.GetIssueInWorkspace(ctx, db.GetIssueInWorkspaceParams{ID: issueID, WorkspaceID: workspaceID})+ if err != nil {+ if !errors.Is(err, pgx.ErrNoRows) {+ slog.Warn("pr auto-complete: load issue failed", "err", err, "issue_id", uuidToString(issueID))+ }+ return+ }+ ws, err := h.Queries.GetWorkspace(ctx, workspaceID)+ if err != nil {+ slog.Warn("pr auto-complete: load workspace failed", "err", err, "workspace_id", uuidToString(workspaceID))+ return+ }+ d, err := h.decidePRAutoComplete(ctx, ws, issue, resolver)+ if err != nil {+ slog.Warn("pr auto-complete: decision failed", "err", err, "issue_id", uuidToString(issueID))+ return+ }+ if d.State != prAutoCompleteAllMerged {+ return+ }++ tx, err := h.TxStarter.Begin(ctx)+ if err != nil {+ slog.Warn("pr auto-complete: begin failed", "err", err)+ return+ }+ defer tx.Rollback(ctx)+ qtx := h.Queries.WithTx(tx)+ updated, err := qtx.CompleteIssueFromPullRequests(ctx, db.CompleteIssueFromPullRequestsParams{+ ID: issue.ID,+ WorkspaceID: issue.WorkspaceID,+ ExpectedStatus: issue.Status,+ })+ if errors.Is(err, pgx.ErrNoRows) {+ // Someone changed the status since the decision; their write wins.+ return+ }+ var cancelledWakeups []db.AgentTaskQueue+ if err == nil {+ cancelledWakeups, err = service.StopClosedIssueWakeups(ctx, qtx, updated)+ }+ if err == nil {+ err = tx.Commit(ctx)+ }+ if err != nil {+ slog.Warn("pr auto-complete: status write failed", "err", err, "issue_id", uuidToString(issueID))+ return+ }+ h.broadcastCancelledWakeups(ctx, updated.WorkspaceID, cancelledWakeups)+ // A merged PR is the most common way a sub-issue reaches done; the parent+ // hears about it on the same path as a manual status change.+ h.notifyParentOfChildDone(ctx, issue, updated)++ prefix := h.getIssuePrefix(ctx, issue.WorkspaceID)+ resp := issueToResponse(updated, prefix)+ h.fillStatusCategory(ctx, updated.WorkspaceID, &resp)+ h.publish(protocol.EventIssueUpdated, uuidToString(workspaceID), "system", "", map[string]any{+ "issue": resp,+ "status_changed": true,+ "prev_status": issue.Status,+ "creator_type": issue.CreatorType,+ "creator_id": uuidToString(issue.CreatorID),+ "source": "pr_automation",+ "pull_requests": prNumberList(d.PRs),+ // Reaching done clears a duplicate mark (MUL-7349); carry both ends so+ // the activity log and clients see the mark go.+ "duplicate_of_issue_id": liveDuplicateMark(updated.Status, updated.DuplicateOfIssueID),+ "prev_duplicate_of_issue_id": liveDuplicateMark(issue.Status, issue.DuplicateOfIssueID),+ })+}++// prNumberList renders "#12, #15" for the activity entry.+func prNumberList(prs []db.ListIssueLinkedPullRequestStatesRow) string {+ parts := make([]string, 0, len(prs))+ for _, pr := range prs {+ parts = append(parts, fmt.Sprintf("#%d", pr.PrNumber))+ }+ return strings.Join(parts, ", ")+}++// ── Issue page read model ───────────────────────────────────────────────────++type prAutoCompleteResponse struct {+ State string `json:"state"`+ // PR ids the state refers to (see prAutoCompleteDecision.PRs).+ PullRequestIDs []string `json:"pull_request_ids"`+ IssueDisabled bool `json:"issue_disabled"`+ WorkspaceEnabled bool `json:"workspace_enabled"`+}++func prAutoCompleteToResponse(ws db.Workspace, d prAutoCompleteDecision) prAutoCompleteResponse {+ ids := make([]string, 0, len(d.PRs))+ for _, pr := range d.PRs {+ ids = append(ids, uuidToString(pr.ID))+ }+ return prAutoCompleteResponse{+ State: d.State,+ PullRequestIDs: ids,+ IssueDisabled: d.IssueDisabled,+ WorkspaceEnabled: prAutoCompleteEnabledForWorkspace(ws),+ }+}++// prLinkSource explains how a PR came to be linked: "manual", or the text the+// webhook matched ("title" / "branch"). "auto" covers links made under older+// rules (a body closing keyword) whose text no longer carries the identifier.+func prLinkSource(linkedByType, identifier, title, branch string) string {+ if linkedByType == "member" {+ return "manual"+ }+ if containsIdentifier(title, identifier) {+ return "title"+ }+ if containsIdentifier(branch, identifier) {+ return "branch"+ }+ return "auto"+}++func containsIdentifier(text, identifier string) bool {+ for _, id := range extractIdentifiers(text) {+ if strings.EqualFold(id, identifier) {+ return true+ }+ }+ return false+}++// ── Manual link / unlink ────────────────────────────────────────────────────++type LinkIssuePullRequestRequest struct {+ // Either a pasted PR URL or the id of an already-listed PR (undo of a+ // removal).+ URL string `json:"url"`+ PullRequestID string `json:"pull_request_id"`+}++// prURLPattern keeps scheme://host/owner/repo/(pull|pulls|-/merge_requests)/N+// and drops anything after it (/files, ?query, #fragment).+var prURLPattern = regexp.MustCompile(`^(https?://[^/?#]+/.+?/(?:pull|pulls|merge_requests)/\d+)(?:[/?#].*)?$`)++func normalizePullRequestURL(raw string) (string, bool) {+ raw = strings.TrimSpace(raw)+ if raw == "" {+ return "", false+ }+ if !strings.Contains(raw, "://") {+ raw = "https://" + raw+ }+ u, err := url.Parse(raw)+ if err != nil || u.Host == "" {+ return "", false+ }+ m := prURLPattern.FindStringSubmatch(u.Scheme + "://" + u.Host + u.EscapedPath())+ if m == nil {+ return "", false+ }+ return strings.ToLower(strings.TrimRight(m[1], "/")), true+}++// linkedPR is a PR resolved from either provider table.+type linkedPR struct {+ ID pgtype.UUID+ Provider string // "github" or the VCS provider name+ Number int32+ github bool+}++func (h *Handler) findPullRequestForLink(ctx context.Context, workspaceID pgtype.UUID, req LinkIssuePullRequestRequest) (linkedPR, bool, error) {+ if req.PullRequestID != "" {+ id, err := util.ParseUUID(req.PullRequestID)+ if err != nil {+ return linkedPR{}, false, nil+ }+ return h.findPullRequestByID(ctx, workspaceID, id)+ }+ normalized, ok := normalizePullRequestURL(req.URL)+ if !ok {+ return linkedPR{}, false, nil+ }+ if pr, err := h.Queries.FindGitHubPullRequestByURL(ctx, db.FindGitHubPullRequestByURLParams{WorkspaceID: workspaceID, HtmlUrl: normalized}); err == nil {+ return linkedPR{ID: pr.ID, Provider: "github", Number: pr.PrNumber, github: true}, true, nil+ } else if !errors.Is(err, pgx.ErrNoRows) {+ return linkedPR{}, false, err+ }+ if pr, err := h.Queries.FindVCSPullRequestByURL(ctx, db.FindVCSPullRequestByURLParams{WorkspaceID: workspaceID, HtmlUrl: normalized}); err == nil {+ return linkedPR{ID: pr.ID, Provider: pr.Provider, Number: pr.PrNumber}, true, nil+ } else if !errors.Is(err, pgx.ErrNoRows) {+ return linkedPR{}, false, err+ }+ return linkedPR{}, false, nil+}++func (h *Handler) findPullRequestByID(ctx context.Context, workspaceID, id pgtype.UUID) (linkedPR, bool, error) {+ if pr, err := h.Queries.GetGitHubPullRequestInWorkspace(ctx, db.GetGitHubPullRequestInWorkspaceParams{ID: id, WorkspaceID: workspaceID}); err == nil {+ return linkedPR{ID: pr.ID, Provider: "github", Number: pr.PrNumber, github: true}, true, nil+ } else if !errors.Is(err, pgx.ErrNoRows) {+ return linkedPR{}, false, err+ }+ if pr, err := h.Queries.GetVCSPullRequestInWorkspace(ctx, db.GetVCSPullRequestInWorkspaceParams{ID: id, WorkspaceID: workspaceID}); err == nil {+ return linkedPR{ID: pr.ID, Provider: pr.Provider, Number: pr.PrNumber}, true, nil+ } else if !errors.Is(err, pgx.ErrNoRows) {+ return linkedPR{}, false, err+ }+ return linkedPR{}, false, nil+}++// LinkIssuePullRequest (POST /api/issues/{id}/pull-requests) links a PR the+// workspace already mirrors. Linking is a PR event for the issue, so it can+// complete the issue when every linked PR is merged.+func (h *Handler) LinkIssuePullRequest(w http.ResponseWriter, r *http.Request) {+ userID, ok := requireUserID(w, r)+ if !ok {+ return+ }+ issue, ok := h.loadIssueForUser(w, r, chi.URLParam(r, "id"))+ if !ok {+ return+ }+ var req LinkIssuePullRequestRequest+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }+ if strings.TrimSpace(req.URL) == "" && req.PullRequestID == "" {+ writeError(w, http.StatusBadRequest, "url is required")+ return+ }+ pr, found, err := h.findPullRequestForLink(r.Context(), issue.WorkspaceID, req)+ if err != nil {+ slog.Warn("link pull request: lookup failed", "err", err)+ writeError(w, http.StatusInternalServerError, "failed to link pull request")+ return+ }+ if !found {+ writeError(w, http.StatusNotFound, "pull request not found; it appears here once its repository is connected and the PR has been synced")+ return+ }+ workspaceID := uuidToString(issue.WorkspaceID)+ _, actorID := h.resolveActor(r, userID, workspaceID)+ linkedBy := pgtype.UUID{}+ if parsed, err := util.ParseUUID(actorID); err == nil {+ linkedBy = parsed+ }+ var rows int64+ if pr.github {+ rows, err = h.Queries.LinkIssueToPullRequestManually(r.Context(), db.LinkIssueToPullRequestManuallyParams{+ IssueID: issue.ID, PullRequestID: pr.ID, LinkedByID: linkedBy,+ })+ } else {+ rows, err = h.Queries.LinkIssueToVCSPullRequestManually(r.Context(), db.LinkIssueToVCSPullRequestManuallyParams{+ IssueID: issue.ID, PullRequestID: pr.ID, LinkedByID: linkedBy,+ })+ }+ if err == nil {+ err = h.Queries.DeletePullRequestExclusion(r.Context(), db.DeletePullRequestExclusionParams{IssueID: issue.ID, PullRequestID: pr.ID})+ }+ if err != nil {+ slog.Warn("link pull request failed", "err", err)+ writeError(w, http.StatusInternalServerError, "failed to link pull request")+ return+ }+ if rows > 0 {+ h.maybeAutoCompleteIssue(r.Context(), issue.WorkspaceID, issue.ID, nil)+ }+ h.publishIssuePullRequestsChanged(workspaceID, issue.ID)+ h.ListPullRequestsForIssue(w, r)+}++// UnlinkIssuePullRequest (DELETE /api/issues/{id}/pull-requests/{prId})+// removes a link and remembers the choice, so the next webhook for that PR does+// not link it again from its title or branch.+func (h *Handler) UnlinkIssuePullRequest(w http.ResponseWriter, r *http.Request) {+ userID, ok := requireUserID(w, r)+ if !ok {+ return+ }+ issue, ok := h.loadIssueForUser(w, r, chi.URLParam(r, "id"))+ if !ok {+ return+ }+ prID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "prId"), "pull request id")+ if !ok {+ return+ }+ pr, found, err := h.findPullRequestByID(r.Context(), issue.WorkspaceID, prID)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to unlink pull request")+ return+ }+ if !found {+ writeError(w, http.StatusNotFound, "pull request not found")+ return+ }+ workspaceID := uuidToString(issue.WorkspaceID)+ actorType, actorID := h.resolveActor(r, userID, workspaceID)+ excludedBy := pgtype.UUID{}+ if parsed, err := util.ParseUUID(actorID); err == nil {+ excludedBy = parsed+ }++ tx, err := h.TxStarter.Begin(r.Context())+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to unlink pull request")+ return+ }+ defer tx.Rollback(r.Context())+ qtx := h.Queries.WithTx(tx)+ var rows int64+ if pr.github {+ rows, err = qtx.UnlinkIssueFromPullRequest(r.Context(), db.UnlinkIssueFromPullRequestParams{IssueID: issue.ID, PullRequestID: pr.ID})+ } else {+ rows, err = qtx.UnlinkIssueFromVCSPullRequest(r.Context(), db.UnlinkIssueFromVCSPullRequestParams{IssueID: issue.ID, PullRequestID: pr.ID})+ }+ if err == nil {+ err = qtx.ExcludePullRequestFromIssue(r.Context(), db.ExcludePullRequestFromIssueParams{+ IssueID: issue.ID,+ PullRequestID: pr.ID,+ WorkspaceID: issue.WorkspaceID,+ ExcludedByType: strToText(actorType),+ ExcludedByID: excludedBy,+ })+ }+ if err == nil {+ err = tx.Commit(r.Context())+ }+ if err != nil {+ slog.Warn("unlink pull request failed", "err", err)+ writeError(w, http.StatusInternalServerError, "failed to unlink pull request")+ return+ }+ if rows > 0 {+ // Removing the last unmerged PR can leave only merged ones behind.+ h.maybeAutoCompleteIssue(r.Context(), issue.WorkspaceID, issue.ID, nil)+ }+ h.publishIssuePullRequestsChanged(workspaceID, issue.ID)+ h.ListPullRequestsForIssue(w, r)+}++type SetIssuePRAutoCompleteRequest struct {+ Disabled *bool `json:"disabled"`+}++// SetIssuePRAutoComplete (PUT /api/issues/{id}/pr-auto-complete) turns PR+// auto-complete off (or back on) for one issue — for work that needs review or+// a release after the merge. Turning it back on does not complete the issue by+// itself; the next PR event does.+func (h *Handler) SetIssuePRAutoComplete(w http.ResponseWriter, r *http.Request) {+ userID, ok := requireUserID(w, r)+ if !ok {+ return+ }+ issue, ok := h.loadIssueForUser(w, r, chi.URLParam(r, "id"))+ if !ok {+ return+ }+ var req SetIssuePRAutoCompleteRequest+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.Disabled == nil {+ writeError(w, http.StatusBadRequest, "disabled is required")+ return+ }+ workspaceID := uuidToString(issue.WorkspaceID)+ actorType, actorID := h.resolveActor(r, userID, workspaceID)+ actorUUID := pgtype.UUID{}+ if parsed, err := util.ParseUUID(actorID); err == nil {+ actorUUID = parsed+ }+ before, err := h.Queries.GetIssuePRAutoCompleteDisabled(r.Context(), issue.ID)+ if err == nil {+ err = h.Queries.SetIssuePRAutoCompleteDisabled(r.Context(), db.SetIssuePRAutoCompleteDisabledParams{+ IssueID: issue.ID,+ WorkspaceID: issue.WorkspaceID,+ AutoCompleteDisabled: *req.Disabled,+ UpdatedByType: strToText(actorType),+ UpdatedByID: actorUUID,+ })+ }+ if err != nil {+ slog.Warn("set issue pr auto-complete failed", "err", err)+ writeError(w, http.StatusInternalServerError, "failed to update pull request automation")+ return+ }+ if before != *req.Disabled {+ h.recordPRAutoCompleteActivity(r.Context(), issue, actorType, actorID, *req.Disabled)+ }+ h.publishIssuePullRequestsChanged(workspaceID, issue.ID)+ h.ListPullRequestsForIssue(w, r)+}++func (h *Handler) recordPRAutoCompleteActivity(ctx context.Context, issue db.Issue, actorType, actorID string, disabled bool) {+ details, _ := json.Marshal(map[string]bool{"disabled": disabled})+ activity, err := h.Queries.CreateActivity(ctx, db.CreateActivityParams{+ ID: dbid.NewV7(),+ WorkspaceID: issue.WorkspaceID,+ IssueID: issue.ID,+ ActorType: strToText(actorType),+ ActorID: optionalActorUUID(actorID),+ Action: "pr_auto_complete_changed",+ Details: details,+ })+ if err != nil {+ slog.Warn("record pr auto-complete activity failed", "err", err)+ return+ }+ h.publish(protocol.EventActivityCreated, uuidToString(issue.WorkspaceID), actorType, actorID, map[string]any{+ "issue_id": uuidToString(issue.ID),+ "entry": map[string]any{+ "type": "activity",+ "id": uuidToString(activity.ID),+ "actor_type": actorType,+ "actor_id": actorID,+ "action": activity.Action,+ "details": json.RawMessage(details),+ "created_at": timestampToString(activity.CreatedAt),+ },+ })+}++func optionalActorUUID(id string) pgtype.UUID {+ parsed, err := util.ParseUUID(id)+ if err != nil {+ return pgtype.UUID{}+ }+ return parsed+}++// publishIssuePullRequestsChanged makes open issue pages refetch their PR list.+func (h *Handler) publishIssuePullRequestsChanged(workspaceID string, issueID pgtype.UUID) {+ h.publish(protocol.EventPullRequestUpdated, workspaceID, "system", "", map[string]any{+ "issue_id": uuidToString(issueID),+ "linked_issue_ids": []string{uuidToString(issueID)},+ })+}diff --git a/server/internal/handler/pr_auto_complete_race_test.go b/server/internal/handler/pr_auto_complete_race_test.gonew file mode 100644index 0000000000..94ea92db30--- /dev/null+++ b/server/internal/handler/pr_auto_complete_race_test.go@@ -0,0 +1,92 @@+package handler++import (+ "context"+ "encoding/json"+ "testing"++ "github.com/jackc/pgx/v5"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// hookedTxStarter runs hook before starting a transaction, to schedule work+// inside a handler's decision→write window.+type hookedTxStarter struct {+ base txStarter+ hook func() error+}++func (h hookedTxStarter) Begin(ctx context.Context) (pgx.Tx, error) {+ if err := h.hook(); err != nil {+ return nil, err+ }+ return h.base.Begin(ctx)+}++// A PR linked between the auto-complete decision and the status write must+// keep the issue open: the write re-checks the linked PRs (MUL-7429 review).+func TestPRAutoComplete_PRLinkedDuringCompletionKeepsIssueOpen(t *testing.T) {+ if testHandler == nil {+ t.Skip("handler test fixture not initialized (no DB?)")+ }+ secret := "pr-linked-during-completion"+ t.Setenv("GITHUB_WEBHOOK_SECRET", secret)+ const inst int64 = 8758002+ issue := prAutoCompleteTestIssue(t, "PR linked during completion", inst)+ firePRWebhook(t, secret, inst, 1, issue.Identifier, "", "fix/a", "opened")+ original := testHandler.TxStarter+ t.Cleanup(func() { testHandler.TxStarter = original })+ // Schedule the second webhook after the first decision but before its write.+ testHandler.TxStarter = hookedTxStarter{base: original, hook: func() error {+ testHandler.TxStarter = original+ firePRWebhook(t, secret, inst, 2, issue.Identifier, "", "fix/b", "opened")+ return nil+ }}+ firePRWebhook(t, secret, inst, 1, issue.Identifier, "", "fix/a", "merged")+ if n := linkedPRCountForTest(t, issue.ID); n != 2 {+ t.Fatalf("want 2 linked PRs, got %d", n)+ }+ if got := issueStatusForTest(t, issue.ID); got != "in_progress" {+ t.Fatalf("completed with linked open PR: got %s, want in_progress", got)+ }+}++// fireTimedPRWebhook delivers a pull_request event with an explicit updated_at.+func fireTimedPRWebhook(t *testing.T, inst int64, identifier, state, timestamp string) {+ t.Helper()+ raw, err := json.Marshal(map[string]any{+ "action": "edited",+ "installation": map[string]any{"id": inst},+ "repository": map[string]any{"name": "widget", "owner": map[string]any{"login": "acme"}},+ "pull_request": map[string]any{"number": 1, "html_url": "https://github.com/acme/widget/pull/1", "title": identifier, "state": state, "merged": state == "closed", "created_at": "2026-09-22T00:00:00Z", "updated_at": timestamp, "head": map[string]any{"ref": "fix/a"}},+ })+ if err != nil {+ t.Fatal(err)+ }+ testHandler.handlePullRequestEvent(context.Background(), raw)+}++// GitHub can deliver an old event late. It must not roll a merged PR back to+// open, which would make a redelivered merge look new and complete an issue a+// person reopened (MUL-7429 review).+func TestPRAutoComplete_StaleGitHubEventDoesNotRecompleteReopenedIssue(t *testing.T) {+ if testHandler == nil {+ t.Skip("handler test fixture not initialized (no DB?)")+ }+ const inst int64 = 8758003+ issue := prAutoCompleteTestIssue(t, "stale GitHub event", inst)+ fireTimedPRWebhook(t, inst, issue.Identifier, "open", "2026-09-22T01:00:00Z")+ fireTimedPRWebhook(t, inst, issue.Identifier, "closed", "2026-09-22T02:00:00Z")+ if got := issueStatusForTest(t, issue.ID); got != "done" {+ t.Fatalf("initial merge got %s", got)+ }+ _, err := testHandler.Queries.UpdateIssueStatus(context.Background(), db.UpdateIssueStatusParams{ID: parseUUID(issue.ID), WorkspaceID: parseUUID(testWorkspaceID), Status: "in_progress"})+ if err != nil {+ t.Fatal(err)+ }+ fireTimedPRWebhook(t, inst, issue.Identifier, "open", "2026-09-22T01:00:00Z")+ fireTimedPRWebhook(t, inst, issue.Identifier, "closed", "2026-09-22T02:00:00Z")+ if got := issueStatusForTest(t, issue.ID); got != "in_progress" {+ t.Fatalf("old deliveries re-completed reopened issue: got %s", got)+ }+}diff --git a/server/internal/handler/vcs_webhook.go b/server/internal/handler/vcs_webhook.goindex 32b3c218c5..a3a11dba3d 100644--- a/server/internal/handler/vcs_webhook.go+++ b/server/internal/handler/vcs_webhook.go@@ -161,6 +161,18 @@ func (h *Handler) mirrorVCSPullRequest(ctx context.Context, conn db.VcsConnectioreturn}+ // The stored state before this event, so a merge completes issues once —+ // when it happens — and not again on a later event of a merged PR.+ prevState := ""+ if prev, err := h.Queries.GetVCSPullRequestByKey(ctx, db.GetVCSPullRequestByKeyParams{+ ConnectionID: conn.ID,+ RepoOwner: ev.RepoOwner,+ RepoName: ev.RepoName,+ PrNumber: ev.Number,+ }); err == nil {+ prevState = prev.State+ }+pr, err := h.Queries.UpsertVCSPullRequest(ctx, db.UpsertVCSPullRequestParams{WorkspaceID: conn.WorkspaceID,ConnectionID: conn.ID,@@ -190,15 +202,13 @@ func (h *Handler) mirrorVCSPullRequest(ctx context.Context, conn db.VcsConnectio// Out-of-order guard for the link write. UpsertVCSPullRequest keeps the// newer persisted row on a stale redelivery, so `pr` may reflect a newer- // event than this `ev`. Everything the link write decides below — whether- // the PR still claims the issue, close_intent, preserveCloseIntent — comes- // from `ev`, so acting on a stale event would undo what the newer one- // already recorded (e.g. a redelivered older "opened" event clearing the- // close intent on a merged PR's link, blocking auto-advance, or dropping a- // link that event had just written). If the persisted row is strictly newer- // than this event, the newer event already linked and published — stop- // here. (An event with no usable timestamp falls back to now(), which is- // never strictly after the stored value, so it proceeds.)+ // event than this `ev`. Everything the link pass decides below comes from+ // `ev`, so acting on a stale event would undo what the newer one already+ // recorded (e.g. a redelivered older event dropping a link the newer title+ // carries). If the persisted row is strictly newer than this event, the+ // newer event already linked and published — stop here. (An event with no+ // usable timestamp falls back to now(), which is never strictly after the+ // stored value, so it proceeds.)evUpdatedAt := parseGHTimeRequired(ev.UpdatedAt)if pr.PrUpdatedAt.Valid && evUpdatedAt.Valid && pr.PrUpdatedAt.Time.After(evUpdatedAt.Time) {return@@ -207,88 +217,44 @@ func (h *Handler) mirrorVCSPullRequest(ctx context.Context, conn db.VcsConnectioworkspaceID := uuidToString(conn.WorkspaceID)resp := vcsPullRequestToResponse(pr)- // Auto-link to issues by identifiers in title/body/branch. Connecting a- // a provider is the opt-in, so there is no separate per-workspace flag. The- // issue-side machinery is shared with GitHub.+ // Auto-link to issues by identifiers in the title and branch. Connecting a+ // provider is the opt-in, so there is no separate per-workspace flag. The+ // issue-side machinery is shared with GitHub (reconcileAutoLinks,+ // maybeAutoCompleteIssue). A connection belongs to exactly one workspace, so+ // there is no cross-workspace ambiguity to settle.linkedIssueIDs := make([]string, 0)- idents := extractIdentifiers(ev.Title, ev.Body, ev.Branch)- closingIdents := map[string]struct{}{}- for _, c := range extractClosingIdentifiers(ev.Title, ev.Body) {- closingIdents[c] = struct{}{}- }- // claimedIdents are the identifiers this PR claims: a title prefix, a- // branch-name reference, or a body closing keyword. An identifier matched- // ONLY by a bare body mention is a drive-by reference — it claims nothing,- // so it gets no link row and drops one an earlier claim created. Mirrors the- // GitHub path (MUL-3739, MUL-7072); branch is deliberately excluded from the- // closing-keyword scan there and here.- claimedIdents := map[string]struct{}{}- for _, id := range extractIdentifiers(ev.Title, ev.Branch) {- claimedIdents[id] = struct{}{}- }- for c := range closingIdents {- claimedIdents[c] = struct{}{}- }- // Freeze close_intent once the terminal merge/close event has arrived.- preserveCloseIntent := !ev.Terminal() && (ev.State == "merged" || ev.State == "closed")- prefix := h.getIssuePrefix(ctx, conn.WorkspaceID)- reevalIssues := make([]db.Issue, 0, len(idents))- for _, id := range idents {- issue, ok := h.lookupIssueByIdentifier(ctx, conn.WorkspaceID, prefix, id)- if !ok {- continue- }- if _, claimed := claimedIdents[id]; !claimed {- // Passing mention: never links, and drops an earlier claim's link- // while the PR is still editable. Frozen once terminal, like- // close_intent.- if preserveCloseIntent {- continue+ ws, err := h.Queries.GetWorkspace(ctx, conn.WorkspaceID)+ if err == nil {+ var touched map[pgtype.UUID]struct{}+ linkedIssueIDs, touched = h.reconcileAutoLinks(ctx, ws, pr.ID, ev.State, prAutoLinkInput{+ idents: extractIdentifiers(ev.Title, ev.Branch),+ permits: func(string) bool { return true },+ ambiguous: func(string) bool { return false },+ link: func(issueID pgtype.UUID) (int64, error) {+ return h.Queries.LinkIssueToVCSPullRequest(ctx, db.LinkIssueToVCSPullRequestParams{IssueID: issueID, PullRequestID: pr.ID})+ },+ unlink: func(issueID pgtype.UUID) (int64, error) {+ return h.Queries.UnlinkIssueFromVCSPullRequest(ctx, db.UnlinkIssueFromVCSPullRequestParams{IssueID: issueID, PullRequestID: pr.ID})+ },+ listAuto: func() ([]pgtype.UUID, error) {+ return h.Queries.ListAutoLinkedIssueIDsForVCSPullRequest(ctx, pr.ID)+ },+ })+ if ev.State == "merged" && prevState != "merged" {+ issueIDs, err := h.Queries.ListIssueIDsForVCSPullRequest(ctx, pr.ID)+ if err != nil {+ slog.Warn("vcs: list linked issues failed", "err", err)}- if err := h.Queries.UnlinkIssueFromVCSPullRequest(ctx, db.UnlinkIssueFromVCSPullRequestParams{- IssueID: issue.ID,- PullRequestID: pr.ID,- }); err != nil {- slog.Warn("vcs: unlink failed", "err", err)- continue+ for _, id := range issueIDs {+ touched[id] = struct{}{}}- reevalIssues = append(reevalIssues, issue)- continue- }- _, declared := closingIdents[id]- closeIntent := declared && !preserveCloseIntent- if err := h.Queries.LinkIssueToVCSPullRequest(ctx, db.LinkIssueToVCSPullRequestParams{- IssueID: issue.ID,- PullRequestID: pr.ID,- CloseIntent: closeIntent,- PreserveCloseIntent: preserveCloseIntent,- LinkedByType: strToText("system"),- LinkedByID: pgtype.UUID{},- }); err != nil {- slog.Warn("vcs: link failed", "err", err)- continue}- linkedIssueIDs = append(linkedIssueIDs, uuidToString(issue.ID))- reevalIssues = append(reevalIssues, issue)- }-- if ev.State == "merged" || ev.State == "closed" {- // Keep the catalog local to this delivery and connection's workspace.resolver := issuestatus.NewResolver(conn.WorkspaceID)- for _, issue := range reevalIssues {- // A custom terminal status counts as terminal here. (MUL-6243)- if s := resolver.Effective(ctx, h.issueStatusCatalog(), issue.Status); s == "done" || s == "cancelled" {- continue- }- counts, err := h.Queries.GetIssueCombinedPullRequestCloseAggregate(ctx, issue.ID)- if err != nil {- slog.Warn("vcs: count linked pr states failed", "err", err, "issue_id", uuidToString(issue.ID))- continue- }- if counts.OpenCount == 0 && counts.MergedWithCloseIntentCount > 0 {- h.advanceIssueToDone(ctx, issue, workspaceID)- }+ for issueID := range touched {+ h.maybeAutoCompleteIssue(ctx, conn.WorkspaceID, issueID, resolver)}+ } else {+ slog.Warn("vcs: load workspace failed", "err", err)}h.publish(protocol.EventPullRequestUpdated, workspaceID, "system", "", map[string]any{diff --git a/server/internal/handler/vcs_webhook_test.go b/server/internal/handler/vcs_webhook_test.goindex 504eb5f352..00f0323b6e 100644--- a/server/internal/handler/vcs_webhook_test.go+++ b/server/internal/handler/vcs_webhook_test.go@@ -145,10 +145,9 @@ func TestVCSWebhook_ForgejoMirrorsAndCloses(t *testing.T) {}}-// A bare body mention ("Related MUL-X", no closing keyword, not in title or-// branch) claims nothing, so it must not link at all: it neither shows as a-// working PR nor blocks a genuine Closes sibling from advancing the issue.-// Mirrors the GitHub claim rule (MUL-3739, MUL-7072).+// A body mention (not in title or branch) claims nothing, so it must not link+// at all: it neither shows as a delivery PR nor blocks a title-linked sibling+// from completing the issue. Mirrors the GitHub rule (MUL-7429).func TestVCSWebhook_BareBodyMentionIsNotLinked(t *testing.T) {ctx := context.Background()box := withVCSBox(t)@@ -194,8 +193,8 @@ func TestVCSWebhook_BareBodyMentionIsNotLinked(t *testing.T) {t.Fatalf("unlinked PR must not appear in the list, got %d rows", len(rows))}- // PR #8: MERGED with a title reference + Closes keyword → a real claim with- // close_intent. The still-open, unlinked PR #7 must NOT block advance.+ // PR #8: MERGED with a title reference → linked. The still-open, unlinked+ // PR #7 must NOT block completion.closeRaw, _ := json.Marshal(map[string]any{"action": "closed","pull_request": map[string]any{@@ -223,40 +222,43 @@ func TestVCSWebhook_BareBodyMentionIsNotLinked(t *testing.T) {}}-// The close gate must span providers: an issue with an OPEN GitHub PR and a-// MERGED close-intent VCS PR must report open_count > 0, so neither webhook-// auto-advances it out from under the still-open GitHub work (and vice versa).-func TestCombinedCloseAggregateSpansProviders(t *testing.T) {+// Auto-complete must span providers: an issue with an OPEN GitHub PR and a+// MERGED VCS merge request waits for the GitHub PR, and completes once it+// merges too.+func TestAutoCompleteSpansProviders(t *testing.T) {ctx := context.Background()box := withVCSBox(t)connID := seedVCSConnection(t, ctx, box, "gitlab", "https://gitlab.test")- issue := newVCSIssue(t, "Cross-provider close gate")+ issue := newVCSIssue(t, "Cross-provider auto-complete")now := pgtype.Timestamptz{Time: time.Now().UTC(), Valid: true}t.Cleanup(func() {testPool.Exec(ctx, `DELETE FROM issue_pull_request WHERE issue_id = $1`, issue.ID)testPool.Exec(ctx, `DELETE FROM github_pull_request WHERE workspace_id = $1`, testWorkspaceID)+ testPool.Exec(ctx, `DELETE FROM activity_log WHERE issue_id = $1`, issue.ID)cleanupVCS(ctx, issue.ID)})- // OPEN GitHub PR linked to the issue (installation_id carries no FK).- ghPR, err := testHandler.Queries.UpsertGitHubPullRequest(ctx, db.UpsertGitHubPullRequestParams{- WorkspaceID: parseUUID(testWorkspaceID), InstallationID: 987654,- RepoOwner: "acme", RepoName: "gh", PrNumber: 3,- Title: "WIP " + issue.Identifier, State: "open",- HtmlUrl: "https://github.com/acme/gh/pull/3",- PrCreatedAt: now, PrUpdatedAt: now, HeadSha: "ghsha",- })- if err != nil {- t.Fatalf("UpsertGitHubPullRequest: %v", err)+ upsertGH := func(state string) db.GithubPullRequest {+ t.Helper()+ pr, err := testHandler.Queries.UpsertGitHubPullRequest(ctx, db.UpsertGitHubPullRequestParams{+ WorkspaceID: parseUUID(testWorkspaceID), InstallationID: 987654,+ RepoOwner: "acme", RepoName: "gh", PrNumber: 3,+ Title: "WIP " + issue.Identifier, State: state,+ HtmlUrl: "https://github.com/acme/gh/pull/3",+ PrCreatedAt: now, PrUpdatedAt: now, HeadSha: "ghsha",+ })+ if err != nil {+ t.Fatalf("UpsertGitHubPullRequest: %v", err)+ }+ return pr}- if err := testHandler.Queries.LinkIssueToPullRequest(ctx, db.LinkIssueToPullRequestParams{- IssueID: parseUUID(issue.ID), PullRequestID: ghPR.ID, CloseIntent: false,- LinkedByType: strToText("system"),+ ghPR := upsertGH("open")+ if _, err := testHandler.Queries.LinkIssueToPullRequest(ctx, db.LinkIssueToPullRequestParams{+ IssueID: parseUUID(issue.ID), PullRequestID: ghPR.ID,}); err != nil {t.Fatalf("LinkIssueToPullRequest: %v", err)}- // MERGED close-intent VCS PR linked to the same issue.vcsPR, err := testHandler.Queries.UpsertVCSPullRequest(ctx, db.UpsertVCSPullRequestParams{WorkspaceID: parseUUID(testWorkspaceID), ConnectionID: parseUUID(connID),Provider: "gitlab", RepoOwner: "acme", RepoName: "gl", PrNumber: 4,@@ -267,22 +269,21 @@ func TestCombinedCloseAggregateSpansProviders(t *testing.T) {if err != nil {t.Fatalf("UpsertVCSPullRequest: %v", err)}- if err := testHandler.Queries.LinkIssueToVCSPullRequest(ctx, db.LinkIssueToVCSPullRequestParams{- IssueID: parseUUID(issue.ID), PullRequestID: vcsPR.ID, CloseIntent: true,- LinkedByType: strToText("system"),+ if _, err := testHandler.Queries.LinkIssueToVCSPullRequest(ctx, db.LinkIssueToVCSPullRequestParams{+ IssueID: parseUUID(issue.ID), PullRequestID: vcsPR.ID,}); err != nil {t.Fatalf("LinkIssueToVCSPullRequest: %v", err)}- counts, err := testHandler.Queries.GetIssueCombinedPullRequestCloseAggregate(ctx, parseUUID(issue.ID))- if err != nil {- t.Fatalf("GetIssueCombinedPullRequestCloseAggregate: %v", err)+ testHandler.maybeAutoCompleteIssue(ctx, parseUUID(testWorkspaceID), parseUUID(issue.ID), nil)+ if got, _ := testHandler.Queries.GetIssue(ctx, parseUUID(issue.ID)); got.Status == "done" {+ t.Fatal("the open GitHub PR must hold the issue open")}- if counts.OpenCount != 1 {- t.Errorf("open_count = %d, want 1 (the open GitHub PR must be seen)", counts.OpenCount)- }- if counts.MergedWithCloseIntentCount != 1 {- t.Errorf("merged_with_close_intent_count = %d, want 1 (the VCS MR)", counts.MergedWithCloseIntentCount)++ upsertGH("merged")+ testHandler.maybeAutoCompleteIssue(ctx, parseUUID(testWorkspaceID), parseUUID(issue.ID), nil)+ if got, _ := testHandler.Queries.GetIssue(ctx, parseUUID(issue.ID)); got.Status != "done" {+ t.Errorf("status = %q, want done once both providers' PRs merged", got.Status)}}@@ -346,8 +347,7 @@ func TestDeleteIssue_VCSLinkCleanupIsWorkspaceScoped(t *testing.T) {}// A redelivered older event must not rewrite the link a newer event already-// set. The PR-upsert monotonic guard protects the PR row; this covers the link-// (close_intent, and the link's existence at all).+// set. The PR-upsert monotonic guard protects the PR row; this covers the link.func TestVCSWebhook_StaleEventDoesNotRewriteLink(t *testing.T) {ctx := context.Background()box := withVCSBox(t)@@ -377,20 +377,20 @@ func TestVCSWebhook_StaleEventDoesNotRewriteLink(t *testing.T) {}}- // Newer terminal event: merged with a real claim (Closes) → close_intent.- fire("closed", "closed", true, "Fix "+issue.Identifier, "Closes "+issue.Identifier, "2026-05-02T00:00:00Z")- // Older redelivered "opened" event: bare body mention, generic title/branch.- // Without the guard this clears close_intent and drops the link entirely.+ // Newer terminal event: merged with the identifier in the title → linked.+ fire("closed", "closed", true, "Fix "+issue.Identifier, "", "2026-05-02T00:00:00Z")+ // Older redelivered "opened" event without the identifier. Without the+ // guard this would drop the link the newer event wrote.fire("opened", "open", false, "WIP", "touches "+issue.Identifier, "2026-05-01T00:00:00Z")- var closeIntent bool+ var links intif err := testPool.QueryRow(ctx,- `SELECT close_intent FROM issue_vcs_pull_request WHERE issue_id = $1`,- issue.ID).Scan(&closeIntent); err != nil {+ `SELECT count(*) FROM issue_vcs_pull_request WHERE issue_id = $1`,+ issue.ID).Scan(&links); err != nil {t.Fatalf("select link: %v", err)}- if !closeIntent {- t.Errorf("stale event rewrote link: close_intent=%v, want true", closeIntent)+ if links != 1 {+ t.Errorf("stale event rewrote the link set: %d links, want 1", links)}// The PR row also stayed at the newer merged state.rows, _ := testHandler.Queries.ListVCSPullRequestsByIssue(ctx, parseUUID(issue.ID))diff --git a/server/internal/handler/webhook_status_resolver_test.go b/server/internal/handler/webhook_status_resolver_test.goindex 4cb9ced06a..d51f702b4b 100644--- a/server/internal/handler/webhook_status_resolver_test.go+++ b/server/internal/handler/webhook_status_resolver_test.go@@ -37,7 +37,7 @@ func (c *webhookStatusCatalog) GetIssueStatusEntryByKey(ctx context.Context, argreturn c.Querier.GetIssueStatusEntryByKey(ctx, arg)}-// Exercise both real mirror paths, including their persisted PR close gate.+// Exercise both real mirror paths, including the PR auto-complete gate.// Signature parsing is covered by the existing provider webhook suites.func TestWebhookStatusResolver(t *testing.T) {ctx := context.Background()@@ -79,7 +79,7 @@ func TestWebhookStatusResolver(t *testing.T) {var ids, closing []stringfor i, status := range tc.statuses {ids = append(ids, fixture.Issue(t, "Resolver fixture", testutil.Cols{"status": status, "number": i + 1}))- closing = append(closing, fmt.Sprintf("Closes RSL-%d", i+1))+ closing = append(closing, fmt.Sprintf("RSL-%d", i+1))}// Mirroring creates rows outside the fixture builders.for _, table := range []string{"issue_pull_request", "issue_vcs_pull_request"} {@@ -88,26 +88,29 @@ func TestWebhookStatusResolver(t *testing.T) {fixture.Cleanup(t, "DELETE FROM github_pull_request WHERE workspace_id = $1", ws)fixture.Cleanup(t, "DELETE FROM vcs_pull_request WHERE workspace_id = $1", ws)const timestamp = "2026-09-08T00:00:00Z"- var mirror func()+ // mirror delivers a merged PR whose title names every+ // fixture issue. Each PR number is a separate delivery.+ var mirror func(number int32)if provider == "github" {- p := &ghPullRequestPayload{}- p.Action = "closed"- p.Repository.Owner.Login, p.Repository.Name = "fixture", "resolver"- p.PullRequest.Number, p.PullRequest.Title = 1, "Resolve linked issues"- p.PullRequest.Body = strings.Join(closing, "\n")- p.PullRequest.State, p.PullRequest.Merged = "closed", true- p.PullRequest.HTMLURL = "https://github.test/fixture/resolver/pull/1"- p.PullRequest.CreatedAt, p.PullRequest.UpdatedAt = timestamp, timestamp- mirror = func() {- h.mirrorPullRequestForWorkspace(ctx, wsID, int64(91000+workspace), p, closeIntentPolicy{unrestricted: true})+ mirror = func(number int32) {+ p := &ghPullRequestPayload{}+ p.Action = "closed"+ p.Repository.Owner.Login, p.Repository.Name = "fixture", "resolver"+ p.PullRequest.Number, p.PullRequest.Title = number, "Resolve "+strings.Join(closing, " ")+ p.PullRequest.State, p.PullRequest.Merged = "closed", true+ p.PullRequest.HTMLURL = fmt.Sprintf("https://github.test/fixture/resolver/pull/%d", number)+ p.PullRequest.CreatedAt, p.PullRequest.UpdatedAt = timestamp, timestamp+ h.mirrorPullRequestForWorkspace(ctx, wsID, int64(91000+workspace), p, prLinkPolicy{unrestricted: true})}} else {connID := fixture.Insert(t, "vcs_connection", testutil.Cols{"workspace_id": ws, "provider": provider, "instance_url": "https://forgejo.test", "account_login": "fixture", "access_token_encrypted": "unused", "webhook_secret_encrypted": "unused"})conn := db.VcsConnection{ID: parseUUID(connID), WorkspaceID: wsID, Provider: provider}- ev := vcs.PullRequestEvent{Action: "closed", State: "merged", RepoOwner: "fixture", RepoName: "resolver", Number: 1, Title: "Resolve linked issues", Body: strings.Join(closing, "\n"), HTMLURL: "https://forgejo.test/fixture/resolver/pulls/1", CreatedAt: timestamp, UpdatedAt: timestamp}- mirror = func() { h.mirrorVCSPullRequest(ctx, conn, ev) }+ mirror = func(number int32) {+ ev := vcs.PullRequestEvent{Action: "closed", State: "merged", RepoOwner: "fixture", RepoName: "resolver", Number: number, Title: "Resolve " + strings.Join(closing, " "), HTMLURL: fmt.Sprintf("https://forgejo.test/fixture/resolver/pulls/%d", number), CreatedAt: timestamp, UpdatedAt: timestamp}+ h.mirrorVCSPullRequest(ctx, conn, ev)+ }}- mirror()+ mirror(1)if got := catalog.reads[wsID]; got != tc.wantReads {t.Errorf("workspace %d catalog reads = %d, want %d", workspace, got, tc.wantReads)}@@ -122,13 +125,19 @@ func TestWebhookStatusResolver(t *testing.T) {t.Errorf("workspace %d issue %d status = %q, want %q", workspace, i, status, want)}}- // A fresh delivery must not reuse even a successful prior- // resolver. Reset one row onto a custom terminal key and replay.+ // A redelivery of the same merge is not a new PR event, so it+ // decides nothing and reads nothing.if tc.name == "custom" {fixture.Exec(t, "UPDATE issue SET status = 'dropped' WHERE id = $1", ids[0])- mirror()+ mirror(1)+ if catalog.reads[wsID] != 1 {+ t.Errorf("redelivered merge reads = %d, want 1 total", catalog.reads[wsID])+ }+ // A fresh delivery must not reuse even a successful+ // prior resolver: a second merged PR re-reads once.+ mirror(2)if catalog.reads[wsID] != 2 {- t.Errorf("replayed delivery reads = %d, want 2 total", catalog.reads[wsID])+ t.Errorf("second delivery reads = %d, want 2 total", catalog.reads[wsID])}var status stringfixture.QueryRow(t, "SELECT status FROM issue WHERE id = $1", ids[0]).Scan(&status)diff --git a/server/internal/handler/workspace_delete_manifest_test.go b/server/internal/handler/workspace_delete_manifest_test.goindex f5cdce9c9d..bcb456d62e 100644--- a/server/internal/handler/workspace_delete_manifest_test.go+++ b/server/internal/handler/workspace_delete_manifest_test.go@@ -78,7 +78,9 @@ var workspaceDeletionManifest = map[string]workspaceDeleteAction{"issue_dependency": workspaceDelete,"issue_label": workspaceDelete,"issue_property": workspaceDelete,+ "issue_pr_automation": workspaceDelete,"issue_pull_request": workspaceDelete,+ "issue_pull_request_exclusion": workspaceDelete,"issue_reaction": workspaceDelete,"issue_source_context": workspaceDelete,"issue_source_context_object_intent": workspaceDeleteSettle,diff --git a/server/internal/service/builtin_skills/multica-platform/SKILL.md b/server/internal/service/builtin_skills/multica-platform/SKILL.mdindex a4f405d50f..7b1137d034 100644--- a/server/internal/service/builtin_skills/multica-platform/SKILL.md+++ b/server/internal/service/builtin_skills/multica-platform/SKILL.md@@ -19,7 +19,7 @@ Read the invariants below, then open the reference(s) your task actually needs| Open | When the task is about ||---|---|-| `references/issues.md` | Issues: PR linking vs close intent, reading a linked PR's state, custom properties, status side effects, sub-issues and stages, who else is running, event/time wakeups |+| `references/issues.md` | Issues: PR linking and auto-complete, reading a linked PR's state, custom properties, status side effects, sub-issues and stages, who else is running, event/time wakeups || `references/mentions.md` | Writing a `mention://` link: which types enqueue a run, which are inert, why one silently did nothing || `references/agents.md` | Creating, copying or debugging an agent definition: fields, secrets, MCP config, skill binding || `references/squads.md` | Squads: leader routing, roster, recording leader activity, why a squad did or did not run |diff --git a/server/internal/service/builtin_skills/multica-platform/references/issues.md b/server/internal/service/builtin_skills/multica-platform/references/issues.mdindex 24a15c1b40..732b60a523 100644--- a/server/internal/service/builtin_skills/multica-platform/references/issues.md+++ b/server/internal/service/builtin_skills/multica-platform/references/issues.md@@ -2,7 +2,7 @@Product contracts the runtime brief does not fully encode.-- [PR linking and close intent are two distinct contracts](#pr-linking-and-close-intent-are-two-distinct-contracts)+- [PR linking and auto-complete](#pr-linking-and-auto-complete)- [Reading a linked PR's real state](#reading-a-linked-prs-real-state)- [Custom properties: typed workflow state](#custom-properties-typed-workflow-state)- [Status changes have server side effects](#status-changes-have-server-side-effects)@@ -10,61 +10,32 @@ Product contracts the runtime brief does not fully encode.- [Sub-issues: todo starts work now, backlog parks it](#sub-issues-todo-starts-work-now-backlog-parks-it)- [Incorrect to correct](#incorrect-to-correct)-## PR linking and close intent are two distinct contracts+## PR linking and auto-complete-The GitHub webhook runs two separate scans over an incoming PR. They are not the-same gate and they read different fields.--**Linking** scans three places for a routable issue key (`PREFIX-NUMBER`, e.g.-`MUL-123`): the PR **title**, the **branch name**, and the **body right after a-closing keyword**. Each match writes an issue to PR link row — the link that-`multica issue pull-requests` reads back. A key that appears in the body as a-bare mention, with nothing in the title or branch and no closing keyword, is a-passing reference and links nothing.+A PR is linked to an issue when its **title** or **branch name** contains a+routable issue key (`PREFIX-NUMBER`, e.g. `MUL-123`). The PR body is not+scanned, and keywords such as `Closes` / `Fixes` / `Resolves` have no special+meaning. People can also link a PR by URL or remove one on the issue page; a+removed PR is not linked again by later webhooks.```text-MUL-123: add the thing the issue asks for # key anywhere in title → links-agent/dana/mul-123-add-the-thing # branch ref → links-Closes MUL-123 # body + closing keyword → links-Related to MUL-123 # body mention only → no link+MUL-123: add the thing the issue asks for # key in title → links+agent/dana/mul-123-add-the-thing # key in branch → links+Closes MUL-123 (body only) # no link```-**Close intent** is stricter and is a separate scan over **title or body only —-never the branch**. It fires only for a key placed immediately after a closing-keyword (`Closes` / `Fixes` / `Resolves`, optional `:` then whitespace). That-adjacency is what sets the link row's close-intent flag, the gate that-auto-advances the issue to `done` when the PR merges.--```text-Closes MUL-123 # links AND records close intent-Fixes MUL-123-Resolves MUL-123-Fix login MUL-123 # in a title: links, no close intent-```+**Every linked PR is delivery.** When all PRs linked to an issue are merged, the+issue moves to `done` on its own — unless the workspace turned PR auto-complete+off (Settings → Issue statuses) or someone turned it off for that issue. A PR closed without+merging keeps the issue waiting until someone removes it from the issue.-Consequence: a bare key in the title or a branch reference links the PR but does-not close the issue on merge. A closing keyword immediately adjacent to the issue key-records close intent; on merge, that close intent can move the linked issue to-`done`.--**Passing mentions link nothing.** A key that appears **only** as a bare mention-in the body — no closing keyword, and not in the title or branch — does not link-the PR at all. This keeps `Related MUL-123` or `Follow up in MUL-123` from-surfacing an unrelated PR as if it were working on that issue. To make a PR show-up for an issue, put the key in the title, the branch, or after a closing keyword-in the body — not as a loose body reference.--While the PR is still open the link follows the live title and body: adding a key-links it, and downgrading that key to a plain mention drops the link. Once the PR-has merged or closed, existing links and their close-intent decision are frozen —-but a PR that was never linked can still be linked by editing it, so a forgotten-key is repairable after the fact. That late link does not move the issue to-`done`; close intent is decided at merge time.+The check runs only when a PR event touches the issue: a linked PR merges, a PR+is linked, or a link is removed. Reopening an issue or changing the setting never+completes it by itself; the next linked PR's merge does.-```text-Closes MUL-123 in the body # links-Related to MUL-123 in the body (no title/branch) # no link-```+While a PR is open, its automatic links follow the live title and branch: removing+the key drops the link. After merge or close, existing links stay. Adding the key+to an already-merged PR still links it, and that link can complete the issue.### Default for code-changing issue work@@ -76,14 +47,14 @@ is blocked by auth, failing tests, or missing remote state, report that blockerinstead of pretending the run is complete.To make the PR show on the issue, put a routable issue key in the PR **title**-(preferred) or the **branch**. A key that appears only as a bare mention in the-body links nothing. Do not use a closing keyword (`Closes` / `Fixes` /-`Resolves`) unless the issue should auto-advance to `done` on merge.+(preferred) or the **branch**. A key that appears only in the body links nothing.+A linked PR counts toward auto-complete, so when the PR delivers only part of the+issue or the issue needs work after the merge (review, release), say so in the+final comment; a person can turn auto-complete off for that issue.```text-MUL-123: fix login redirect # key anywhere in title → links-Closes MUL-123 # only when merge should mark the issue done-Part of MUL-123 # body mention only → no link at all+MUL-123: fix login redirect # key in title → links, counts toward done+Part of MUL-123 # body only → no link at all```In the final issue comment, include the PR URL when a PR exists. If the task did@@ -100,9 +71,16 @@ an earlier run.multica issue pull-requests <issue-id> --output json```-Returns `{"pull_requests": [...]}`. Each element exposes:+Returns `{"pull_requests": [...], "auto_complete": {...}}`.+`auto_complete.state` says what the merge rule will do for this issue:+`waiting` (some linked PRs are still open or draft), `not_merged` (one was closed+without merging), `all_merged`, `workspace_disabled`, `issue_disabled`,+`terminal`, `triage`, or `none`; `auto_complete.pull_request_ids` names the PRs+the state is about. Each element of `pull_requests` exposes:- `number`, `html_url`, `title`+- `link_source` — why the PR is on the issue: `title`, `branch`, `manual`, or+ `auto` (linked under an older rule).- `state` — the PR lifecycle as a **single enum**, one of `merged`, `closed`,`draft`, `open`. There is no separate `draft` or `merged` boolean in theresponse; the server folds them into `state` (merged wins, then closed, then@@ -127,10 +105,9 @@ So "is it merged?" is `state == "merged"` (or `merged_at != null`); "is it stilla draft?" is `state == "draft"`; coarse CI status is `checks_conclusion`.If the command returns no linked PRs after a PR was opened, check the syntax-first: the scanner needs a routable issue key in the PR title or branch, or one-right after a closing keyword in the body — a bare body mention does not count-(see the passing-mention rule above). When the syntax is the problem, editing the-title or adding a closing keyword re-runs the scan.+first: the key must be in the PR title or branch — the body does not count. When+the syntax is the problem, editing the title re-runs the scan. If a person removed+the PR from the issue, it stays removed until someone links it again.If the key is already written correctly and the list is still empty, stop editingthe PR blind: another no-op edit cannot fix an integration that never received the@@ -269,9 +246,9 @@ archived statuses remain readable via an explicit status filter.later re-trigger confirms the overall goal is met.- **`in_review`** is an accepted issue status. Some workflows use it while a PRis open and awaiting review; moving to it is an explicit mutation.-- **`done`** on a child issue posts a system comment on its parent. If a PR- carries close intent (`Closes MUL-XXXX`), it advances the issue to `done`- itself on merge — you do not also need to flip it manually.+- **`done`** on a child issue posts a system comment on its parent. When every+ PR linked to the issue has merged, the server moves it to `done` itself (see+ PR linking and auto-complete) — you do not also need to flip it manually.- **`cancelled`** is a terminal, user-driven decision to close the issue. Like`done` it enqueues no new agent work, but it does **not** stop tasks already inflight — a run in progress keeps going. To stop a running task, cancel thediff --git a/server/internal/service/builtin_skills_test.go b/server/internal/service/builtin_skills_test.goindex d947f5d2dc..c720794f21 100644--- a/server/internal/service/builtin_skills_test.go+++ b/server/internal/service/builtin_skills_test.go@@ -467,11 +467,14 @@ func TestPlatformSkillCoversPlatformContracts(t *testing.T) {// both halves of it are pinned: a syntax problem is repairable// by editing the PR, and an integration problem is not — an// agent that keeps editing burns deliveries on a no-op.- "editing the title or adding a closing keyword re-runs the scan",+ "editing the title re-runs the scan","stop editing the PR blind","whether the installation is bound to this workspace","redelivered once the receiving side is fixed",- "unless the issue should auto-advance",+ // MUL-7429: every linked PR counts toward auto-complete, and the+ // exception is a person's per-issue switch, not a keyword.+ "Every linked PR is delivery",+ "a person can turn auto-complete off for that issue","include the PR URL when a PR exists","Closes MUL-123","--status backlog",diff --git a/server/migrations/545_pr_auto_complete.down.sql b/server/migrations/545_pr_auto_complete.down.sqlnew file mode 100644index 0000000000..0c605b0eab--- /dev/null+++ b/server/migrations/545_pr_auto_complete.down.sql@@ -0,0 +1,2 @@+DROP TABLE IF EXISTS issue_pull_request_exclusion;+DROP TABLE IF EXISTS issue_pr_automation;diff --git a/server/migrations/545_pr_auto_complete.up.sql b/server/migrations/545_pr_auto_complete.up.sqlnew file mode 100644index 0000000000..250d765827--- /dev/null+++ b/server/migrations/545_pr_auto_complete.up.sql@@ -0,0 +1,30 @@+-- PR auto-complete (MUL-7429). Two small per-issue records:+--+-- issue_pr_automation: an explicit "do not auto-complete this issue from PR+-- merges" choice. Absent row = follow the workspace setting.+--+-- issue_pull_request_exclusion: a PR a person removed from an issue. The+-- webhook must not re-link it from the title/branch on the next delivery.+-- pull_request_id points at github_pull_request or vcs_pull_request (both use+-- uuid ids).+--+-- No foreign keys: issue and workspace deletion are application-owned and+-- sweep both tables explicitly (DeleteIssue, DeleteWorkspaceData).+CREATE TABLE IF NOT EXISTS issue_pr_automation (+ issue_id UUID PRIMARY KEY,+ workspace_id UUID NOT NULL,+ auto_complete_disabled BOOLEAN NOT NULL DEFAULT FALSE,+ updated_by_type TEXT,+ updated_by_id UUID,+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()+);++CREATE TABLE IF NOT EXISTS issue_pull_request_exclusion (+ issue_id UUID NOT NULL,+ pull_request_id UUID NOT NULL,+ workspace_id UUID NOT NULL,+ excluded_by_type TEXT,+ excluded_by_id UUID,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ PRIMARY KEY (issue_id, pull_request_id)+);diff --git a/server/migrations/546_issue_pr_automation_workspace_index.down.sql b/server/migrations/546_issue_pr_automation_workspace_index.down.sqlnew file mode 100644index 0000000000..59c0e11499--- /dev/null+++ b/server/migrations/546_issue_pr_automation_workspace_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_issue_pr_automation_workspace;diff --git a/server/migrations/546_issue_pr_automation_workspace_index.up.sql b/server/migrations/546_issue_pr_automation_workspace_index.up.sqlnew file mode 100644index 0000000000..ea101d7e20--- /dev/null+++ b/server/migrations/546_issue_pr_automation_workspace_index.up.sql@@ -0,0 +1,2 @@+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_issue_pr_automation_workspace+ ON issue_pr_automation (workspace_id);diff --git a/server/migrations/547_issue_pull_request_exclusion_workspace_index.down.sql b/server/migrations/547_issue_pull_request_exclusion_workspace_index.down.sqlnew file mode 100644index 0000000000..fe0d35d104--- /dev/null+++ b/server/migrations/547_issue_pull_request_exclusion_workspace_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_issue_pull_request_exclusion_workspace;diff --git a/server/migrations/547_issue_pull_request_exclusion_workspace_index.up.sql b/server/migrations/547_issue_pull_request_exclusion_workspace_index.up.sqlnew file mode 100644index 0000000000..d552148823--- /dev/null+++ b/server/migrations/547_issue_pull_request_exclusion_workspace_index.up.sql@@ -0,0 +1,2 @@+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_issue_pull_request_exclusion_workspace+ ON issue_pull_request_exclusion (workspace_id);diff --git a/server/pkg/db/generated/github.sql.go b/server/pkg/db/generated/github.sql.goindex e2544fba1d..5a02c51b3e 100644--- a/server/pkg/db/generated/github.sql.go+++ b/server/pkg/db/generated/github.sql.go@@ -115,6 +115,57 @@ func (q *Queries) DeletePendingGitHubInstallation(ctx context.Context, installatreturn err}+const findGitHubPullRequestByURL = `-- name: FindGitHubPullRequestByURL :one+SELECT id, workspace_id, installation_id, repo_owner, repo_name, pr_number, title, state, html_url, branch, author_login, author_avatar_url, merged_at, closed_at, pr_created_at, pr_updated_at, created_at, updated_at, head_sha, mergeable_state, additions, deletions, changed_files, api_mergeable, api_merge_state_status, checks_rollup_state, snapshot_head_sha, snapshot_fetched_at FROM github_pull_request+WHERE workspace_id = $1+ AND lower(rtrim(html_url, '/')) = lower($2::text)+ORDER BY pr_updated_at DESC+LIMIT 1+`++type FindGitHubPullRequestByURLParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ HtmlUrl string `json:"html_url"`+}++// Resolves a pasted PR URL to a mirrored PR. The caller normalizes the URL to+// scheme://host/owner/repo/pull/N; html_url is stored in that shape.+func (q *Queries) FindGitHubPullRequestByURL(ctx context.Context, arg FindGitHubPullRequestByURLParams) (GithubPullRequest, error) {+ row := q.db.QueryRow(ctx, findGitHubPullRequestByURL, arg.WorkspaceID, arg.HtmlUrl)+ var i GithubPullRequest+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.InstallationID,+ &i.RepoOwner,+ &i.RepoName,+ &i.PrNumber,+ &i.Title,+ &i.State,+ &i.HtmlUrl,+ &i.Branch,+ &i.AuthorLogin,+ &i.AuthorAvatarUrl,+ &i.MergedAt,+ &i.ClosedAt,+ &i.PrCreatedAt,+ &i.PrUpdatedAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.HeadSha,+ &i.MergeableState,+ &i.Additions,+ &i.Deletions,+ &i.ChangedFiles,+ &i.ApiMergeable,+ &i.ApiMergeStateStatus,+ &i.ChecksRollupState,+ &i.SnapshotHeadSha,+ &i.SnapshotFetchedAt,+ )+ return i, err+}+const getGitHubInstallationByID = `-- name: GetGitHubInstallationByID :oneSELECT id, workspace_id, installation_id, account_login, account_type, account_avatar_url, connected_by_id, created_at, updated_at FROM github_installationWHERE id = $1@@ -190,33 +241,49 @@ func (q *Queries) GetGitHubPullRequest(ctx context.Context, arg GetGitHubPullReqreturn i, err}-const getIssuePullRequestCloseAggregate = `-- name: GetIssuePullRequestCloseAggregate :one-SELECT- COALESCE(SUM(CASE WHEN pr.state IN ('open', 'draft') THEN 1 ELSE 0 END), 0)::bigint AS open_count,- COALESCE(SUM(CASE WHEN pr.state = 'merged' AND ipr.close_intent THEN 1 ELSE 0 END), 0)::bigint AS merged_with_close_intent_count-FROM github_pull_request pr-JOIN issue_pull_request ipr ON ipr.pull_request_id = pr.id-WHERE ipr.issue_id = $1+const getGitHubPullRequestInWorkspace = `-- name: GetGitHubPullRequestInWorkspace :one+SELECT id, workspace_id, installation_id, repo_owner, repo_name, pr_number, title, state, html_url, branch, author_login, author_avatar_url, merged_at, closed_at, pr_created_at, pr_updated_at, created_at, updated_at, head_sha, mergeable_state, additions, deletions, changed_files, api_mergeable, api_merge_state_status, checks_rollup_state, snapshot_head_sha, snapshot_fetched_at FROM github_pull_request+WHERE id = $1 AND workspace_id = $2`-type GetIssuePullRequestCloseAggregateRow struct {- OpenCount int64 `json:"open_count"`- MergedWithCloseIntentCount int64 `json:"merged_with_close_intent_count"`-}--// Aggregates the issue's linked PRs into the two counts that gate-// auto-advance: how many are still in flight (`open` or `draft`) and how-// many merged PRs declared explicit closing intent on the link row. The-// webhook auto-advances the issue when open_count = 0 AND-// merged_with_close_intent_count > 0. Both the PR state and the link row-// (with close_intent) are persisted before this query runs, so the result-// is event-agnostic — a link-only sibling closing after a closing-keyword-// PR has already merged still resolves the issue. A bare body mention is not-// linked at all, so a passing reference can never keep open_count > 0.-func (q *Queries) GetIssuePullRequestCloseAggregate(ctx context.Context, issueID pgtype.UUID) (GetIssuePullRequestCloseAggregateRow, error) {- row := q.db.QueryRow(ctx, getIssuePullRequestCloseAggregate, issueID)- var i GetIssuePullRequestCloseAggregateRow- err := row.Scan(&i.OpenCount, &i.MergedWithCloseIntentCount)+type GetGitHubPullRequestInWorkspaceParams struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++func (q *Queries) GetGitHubPullRequestInWorkspace(ctx context.Context, arg GetGitHubPullRequestInWorkspaceParams) (GithubPullRequest, error) {+ row := q.db.QueryRow(ctx, getGitHubPullRequestInWorkspace, arg.ID, arg.WorkspaceID)+ var i GithubPullRequest+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.InstallationID,+ &i.RepoOwner,+ &i.RepoName,+ &i.PrNumber,+ &i.Title,+ &i.State,+ &i.HtmlUrl,+ &i.Branch,+ &i.AuthorLogin,+ &i.AuthorAvatarUrl,+ &i.MergedAt,+ &i.ClosedAt,+ &i.PrCreatedAt,+ &i.PrUpdatedAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.HeadSha,+ &i.MergeableState,+ &i.Additions,+ &i.Deletions,+ &i.ChangedFiles,+ &i.ApiMergeable,+ &i.ApiMergeStateStatus,+ &i.ChecksRollupState,+ &i.SnapshotHeadSha,+ &i.SnapshotFetchedAt,+ )return i, err}@@ -274,47 +341,90 @@ func (q *Queries) GetPendingGitHubInstallation(ctx context.Context, installationreturn i, err}-const linkIssueToPullRequest = `-- name: LinkIssueToPullRequest :exec+const linkIssueToPullRequest = `-- name: LinkIssueToPullRequest :execrowsINSERT INTO issue_pull_request (- issue_id, pull_request_id, linked_by_type, linked_by_id, close_intent+ issue_id, pull_request_id, linked_by_type, linked_by_id) VALUES (- $1, $2, $4, $5, $3+ $1, $2, 'system', NULL)-ON CONFLICT (issue_id, pull_request_id) DO UPDATE SET- close_intent = CASE- WHEN $6 THEN issue_pull_request.close_intent- ELSE EXCLUDED.close_intent- END+ON CONFLICT (issue_id, pull_request_id) DO NOTHING`type LinkIssueToPullRequestParams struct {- IssueID pgtype.UUID `json:"issue_id"`- PullRequestID pgtype.UUID `json:"pull_request_id"`- CloseIntent bool `json:"close_intent"`- LinkedByType pgtype.Text `json:"linked_by_type"`- LinkedByID pgtype.UUID `json:"linked_by_id"`- PreserveCloseIntent bool `json:"preserve_close_intent"`+ IssueID pgtype.UUID `json:"issue_id"`+ PullRequestID pgtype.UUID `json:"pull_request_id"`}// =====================// Issue ↔ Pull Request link// =====================-// close_intent reflects the PR's explicit close declaration at the moment-// the webhook is allowed to update that intent. Open/edit/merge webhooks use-// the current title/body parse result so authors can remove a closing keyword-// before merge. Post-terminal edits can opt into preserving the stored value,-// keeping the merge-time decision stable.-func (q *Queries) LinkIssueToPullRequest(ctx context.Context, arg LinkIssueToPullRequestParams) error {- _, err := q.db.Exec(ctx, linkIssueToPullRequest,- arg.IssueID,- arg.PullRequestID,- arg.CloseIntent,- arg.LinkedByType,- arg.LinkedByID,- arg.PreserveCloseIntent,- )- return err+// Automatic link from a PR title or branch. Returns 1 only when the link is+// new, so the webhook evaluates auto-complete on the link event and not on+// every redelivery. An existing link (automatic or manual) is left untouched.+func (q *Queries) LinkIssueToPullRequest(ctx context.Context, arg LinkIssueToPullRequestParams) (int64, error) {+ result, err := q.db.Exec(ctx, linkIssueToPullRequest, arg.IssueID, arg.PullRequestID)+ if err != nil {+ return 0, err+ }+ return result.RowsAffected(), nil+}++const linkIssueToPullRequestManually = `-- name: LinkIssueToPullRequestManually :execrows+INSERT INTO issue_pull_request (+ issue_id, pull_request_id, linked_by_type, linked_by_id+) VALUES (+ $1, $2, 'member', $3+)+ON CONFLICT (issue_id, pull_request_id) DO UPDATE SET+ linked_by_type = 'member',+ linked_by_id = EXCLUDED.linked_by_id+WHERE issue_pull_request.linked_by_type IS DISTINCT FROM 'member'+`++type LinkIssueToPullRequestManuallyParams struct {+ IssueID pgtype.UUID `json:"issue_id"`+ PullRequestID pgtype.UUID `json:"pull_request_id"`+ LinkedByID pgtype.UUID `json:"linked_by_id"`+}++// A member linked this PR by hand. Marking an existing automatic link as+// manual keeps a later title edit from removing it. Returns 1 when the row was+// inserted or converted.+func (q *Queries) LinkIssueToPullRequestManually(ctx context.Context, arg LinkIssueToPullRequestManuallyParams) (int64, error) {+ result, err := q.db.Exec(ctx, linkIssueToPullRequestManually, arg.IssueID, arg.PullRequestID, arg.LinkedByID)+ if err != nil {+ return 0, err+ }+ return result.RowsAffected(), nil+}++const listAutoLinkedIssueIDsForPullRequest = `-- name: ListAutoLinkedIssueIDsForPullRequest :many+SELECT issue_id FROM issue_pull_request+WHERE pull_request_id = $1+ AND COALESCE(linked_by_type, 'system') <> 'member'+`++// Issues this PR is linked to automatically. Manual links are not listed: the+// webhook reconciles only what it created itself.+func (q *Queries) ListAutoLinkedIssueIDsForPullRequest(ctx context.Context, pullRequestID pgtype.UUID) ([]pgtype.UUID, error) {+ rows, err := q.db.Query(ctx, listAutoLinkedIssueIDsForPullRequest, pullRequestID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []pgtype.UUID{}+ for rows.Next() {+ var issue_id pgtype.UUID+ if err := rows.Scan(&issue_id); err != nil {+ return nil, err+ }+ items = append(items, issue_id)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil}const listGitHubInstallationsByInstallationID = `-- name: ListGitHubInstallationsByInstallationID :many@@ -459,6 +569,7 @@ SELECTpr.api_mergeable, pr.api_merge_state_status, pr.checks_rollup_state,pr.snapshot_head_sha, pr.snapshot_fetched_at,pr.created_at, pr.updated_at,+ COALESCE(ipr.linked_by_type, 'system')::text AS linked_by_type,COALESCE(c.total, 0)::bigint AS checks_total,COALESCE(c.passed, 0)::bigint AS checks_passed,COALESCE(c.failed, 0)::bigint AS checks_failed,@@ -500,6 +611,7 @@ type ListPullRequestsByIssueRow struct {SnapshotFetchedAt pgtype.Timestamptz `json:"snapshot_fetched_at"`CreatedAt pgtype.Timestamptz `json:"created_at"`UpdatedAt pgtype.Timestamptz `json:"updated_at"`+ LinkedByType string `json:"linked_by_type"`ChecksTotal int64 `json:"checks_total"`ChecksPassed int64 `json:"checks_passed"`ChecksFailed int64 `json:"checks_failed"`@@ -514,10 +626,9 @@ type ListPullRequestsByIssueRow struct {// refresh pipeline — NOT the legacy suite-level webhook aggregation, which is// removed. The `issue_prs` CTE narrows to this issue's PR ids first so the// aggregation only touches check rows for those PRs. Rows for an OLD head are-// excluded by the snapshot_head_sha filter. Every link row is a working PR:-// the webhook only links an identifier it read from the PR title, the branch-// name, or a body closing keyword, so a bare body mention never lands here-// (MUL-7072).+// excluded by the snapshot_head_sha filter. Every link row is a delivery PR:+// the webhook links an identifier it read from the PR title or branch name, and+// a member can link one by hand (linked_by_type = 'member'). MUL-7429.func (q *Queries) ListPullRequestsByIssue(ctx context.Context, issueID pgtype.UUID) ([]ListPullRequestsByIssueRow, error) {rows, err := q.db.Query(ctx, listPullRequestsByIssue, issueID)if err != nil {@@ -556,6 +667,7 @@ func (q *Queries) ListPullRequestsByIssue(ctx context.Context, issueID pgtype.UU&i.SnapshotFetchedAt,&i.CreatedAt,&i.UpdatedAt,+ &i.LinkedByType,&i.ChecksTotal,&i.ChecksPassed,&i.ChecksFailed,@@ -572,7 +684,7 @@ func (q *Queries) ListPullRequestsByIssue(ctx context.Context, issueID pgtype.UUreturn items, nil}-const unlinkIssueFromPullRequest = `-- name: UnlinkIssueFromPullRequest :exec+const unlinkIssueFromPullRequest = `-- name: UnlinkIssueFromPullRequest :execrowsDELETE FROM issue_pull_requestWHERE issue_id = $1 AND pull_request_id = $2`@@ -582,9 +694,12 @@ type UnlinkIssueFromPullRequestParams struct {PullRequestID pgtype.UUID `json:"pull_request_id"`}-func (q *Queries) UnlinkIssueFromPullRequest(ctx context.Context, arg UnlinkIssueFromPullRequestParams) error {- _, err := q.db.Exec(ctx, unlinkIssueFromPullRequest, arg.IssueID, arg.PullRequestID)- return err+func (q *Queries) UnlinkIssueFromPullRequest(ctx context.Context, arg UnlinkIssueFromPullRequestParams) (int64, error) {+ result, err := q.db.Exec(ctx, unlinkIssueFromPullRequest, arg.IssueID, arg.PullRequestID)+ if err != nil {+ return 0, err+ }+ return result.RowsAffected(), nil}const updateGitHubInstallationAccountByInstallationID = `-- name: UpdateGitHubInstallationAccountByInstallationID :many@@ -678,6 +793,7 @@ ON CONFLICT (workspace_id, repo_owner, repo_name, pr_number) DO UPDATE SETdeletions = EXCLUDED.deletions,changed_files = EXCLUDED.changed_files,updated_at = now()+WHERE EXCLUDED.pr_updated_at >= github_pull_request.pr_updated_atRETURNING id, workspace_id, installation_id, repo_owner, repo_name, pr_number, title, state, html_url, branch, author_login, author_avatar_url, merged_at, closed_at, pr_created_at, pr_updated_at, created_at, updated_at, head_sha, mergeable_state, additions, deletions, changed_files, api_mergeable, api_merge_state_status, checks_rollup_state, snapshot_head_sha, snapshot_fetched_at`@@ -718,6 +834,10 @@ type UpsertGitHubPullRequestParams struct {// information that GitHub only re-computes lazily.//// INSERT path always writes the incoming value (NULL acceptable for a new row).+//+// GitHub may deliver events out of order. An event older than the stored row+// (pr_updated_at) updates nothing and returns no row, so a late "opened" can't+// roll a merged PR back to open — the same guard UpsertVCSPullRequest has.func (q *Queries) UpsertGitHubPullRequest(ctx context.Context, arg UpsertGitHubPullRequestParams) (GithubPullRequest, error) {row := q.db.QueryRow(ctx, upsertGitHubPullRequest,arg.WorkspaceID,diff --git a/server/pkg/db/generated/issue.sql.go b/server/pkg/db/generated/issue.sql.goindex 7ed7830626..0f62606346 100644--- a/server/pkg/db/generated/issue.sql.go+++ b/server/pkg/db/generated/issue.sql.go@@ -495,6 +495,12 @@ cleared_task_supplement_capabilities AS (),cleared_vcs_pr_links AS (DELETE FROM issue_vcs_pull_request WHERE issue_id IN (SELECT target.id FROM target)+),+cleared_pr_automation AS (+ DELETE FROM issue_pr_automation WHERE issue_id IN (SELECT target.id FROM target)+),+cleared_pr_exclusions AS (+ DELETE FROM issue_pull_request_exclusion WHERE issue_id IN (SELECT target.id FROM target))DELETE FROM issue WHERE issue.id IN (SELECT target.id FROM target)`diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex 64247266b2..50d6cdce97 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -844,6 +844,15 @@ type IssueLabel struct {Description string `json:"description"`}+type IssuePrAutomation struct {+ IssueID pgtype.UUID `json:"issue_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ AutoCompleteDisabled bool `json:"auto_complete_disabled"`+ UpdatedByType pgtype.Text `json:"updated_by_type"`+ UpdatedByID pgtype.UUID `json:"updated_by_id"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+}+type IssueProperty struct {ID pgtype.UUID `json:"id"`WorkspaceID pgtype.UUID `json:"workspace_id"`@@ -867,6 +876,15 @@ type IssuePullRequest struct {CloseIntent bool `json:"close_intent"`}+type IssuePullRequestExclusion struct {+ IssueID pgtype.UUID `json:"issue_id"`+ PullRequestID pgtype.UUID `json:"pull_request_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ ExcludedByType pgtype.Text `json:"excluded_by_type"`+ ExcludedByID pgtype.UUID `json:"excluded_by_id"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+}+type IssueReaction struct {ID pgtype.UUID `json:"id"`IssueID pgtype.UUID `json:"issue_id"`diff --git a/server/pkg/db/generated/pr_automation.sql.go b/server/pkg/db/generated/pr_automation.sql.gonew file mode 100644index 0000000000..2b5853e392--- /dev/null+++ b/server/pkg/db/generated/pr_automation.sql.go@@ -0,0 +1,258 @@+// Code generated by sqlc. DO NOT EDIT.+// versions:+// sqlc v1.31.1+// source: pr_automation.sql++package db++import (+ "context"++ "github.com/jackc/pgx/v5/pgtype"+)++const completeIssueFromPullRequests = `-- name: CompleteIssueFromPullRequests :one+UPDATE issue AS i SET+ status = 'done',+ duplicate_of_issue_id = NULL,+ position = (+ SELECT COALESCE(MIN(target.position), 0) - 1+ FROM issue AS target+ WHERE target.workspace_id = i.workspace_id+ AND target.status = 'done'+ ),+ revision = i.revision + 1,+ last_activity_at = GREATEST(COALESCE(i.last_activity_at, i.updated_at), now()),+ updated_at = now()+WHERE i.id = $1+ AND i.workspace_id = $2+ AND i.status = $3::text+ AND i.status <> 'done'+ AND EXISTS (+ SELECT 1 FROM issue_pull_request ipr WHERE ipr.issue_id = i.id+ UNION ALL+ SELECT 1 FROM issue_vcs_pull_request ipr WHERE ipr.issue_id = i.id+ )+ AND NOT EXISTS (+ SELECT 1 FROM issue_pull_request ipr+ JOIN github_pull_request pr ON pr.id = ipr.pull_request_id+ WHERE ipr.issue_id = i.id AND pr.state <> 'merged'+ )+ AND NOT EXISTS (+ SELECT 1 FROM issue_vcs_pull_request ipr+ JOIN vcs_pull_request pr ON pr.id = ipr.pull_request_id+ WHERE ipr.issue_id = i.id AND pr.state <> 'merged'+ )+RETURNING i.id, i.workspace_id, i.title, i.description, i.status, i.priority, i.assignee_type, i.assignee_id, i.creator_type, i.creator_id, i.parent_issue_id, i.acceptance_criteria, i.context_refs, i.position, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.origin_type, i.origin_id, i.first_executed_at, i.start_date, i.metadata, i.stage, i.properties, i.revision, i.last_activity_at, i.triage_state, i.duplicate_of_issue_id+`++type CompleteIssueFromPullRequestsParams struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ ExpectedStatus string `json:"expected_status"`+}++// Conditional status write for PR auto-complete. It lands only if the issue is+// still in the status the decision saw (two merges racing complete it once) and+// the linked PRs are still all merged when the write runs: a PR linked between+// the decision and this statement keeps the issue open. Repositions like+// UpdateIssueStatus does.+func (q *Queries) CompleteIssueFromPullRequests(ctx context.Context, arg CompleteIssueFromPullRequestsParams) (Issue, error) {+ row := q.db.QueryRow(ctx, completeIssueFromPullRequests, arg.ID, arg.WorkspaceID, arg.ExpectedStatus)+ var i Issue+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.Title,+ &i.Description,+ &i.Status,+ &i.Priority,+ &i.AssigneeType,+ &i.AssigneeID,+ &i.CreatorType,+ &i.CreatorID,+ &i.ParentIssueID,+ &i.AcceptanceCriteria,+ &i.ContextRefs,+ &i.Position,+ &i.DueDate,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.Number,+ &i.ProjectID,+ &i.OriginType,+ &i.OriginID,+ &i.FirstExecutedAt,+ &i.StartDate,+ &i.Metadata,+ &i.Stage,+ &i.Properties,+ &i.Revision,+ &i.LastActivityAt,+ &i.TriageState,+ &i.DuplicateOfIssueID,+ )+ return i, err+}++const deletePullRequestExclusion = `-- name: DeletePullRequestExclusion :exec+DELETE FROM issue_pull_request_exclusion+WHERE issue_id = $1 AND pull_request_id = $2+`++type DeletePullRequestExclusionParams struct {+ IssueID pgtype.UUID `json:"issue_id"`+ PullRequestID pgtype.UUID `json:"pull_request_id"`+}++func (q *Queries) DeletePullRequestExclusion(ctx context.Context, arg DeletePullRequestExclusionParams) error {+ _, err := q.db.Exec(ctx, deletePullRequestExclusion, arg.IssueID, arg.PullRequestID)+ return err+}++const excludePullRequestFromIssue = `-- name: ExcludePullRequestFromIssue :exec+INSERT INTO issue_pull_request_exclusion (+ issue_id, pull_request_id, workspace_id, excluded_by_type, excluded_by_id+) VALUES (+ $1, $2, $3, $4, $5+)+ON CONFLICT (issue_id, pull_request_id) DO UPDATE SET+ excluded_by_type = EXCLUDED.excluded_by_type,+ excluded_by_id = EXCLUDED.excluded_by_id,+ created_at = now()+`++type ExcludePullRequestFromIssueParams struct {+ IssueID pgtype.UUID `json:"issue_id"`+ PullRequestID pgtype.UUID `json:"pull_request_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ ExcludedByType pgtype.Text `json:"excluded_by_type"`+ ExcludedByID pgtype.UUID `json:"excluded_by_id"`+}++func (q *Queries) ExcludePullRequestFromIssue(ctx context.Context, arg ExcludePullRequestFromIssueParams) error {+ _, err := q.db.Exec(ctx, excludePullRequestFromIssue,+ arg.IssueID,+ arg.PullRequestID,+ arg.WorkspaceID,+ arg.ExcludedByType,+ arg.ExcludedByID,+ )+ return err+}++const getIssuePRAutoCompleteDisabled = `-- name: GetIssuePRAutoCompleteDisabled :one++SELECT EXISTS (+ SELECT 1 FROM issue_pr_automation+ WHERE issue_id = $1 AND auto_complete_disabled+)::boolean AS disabled+`++// =====================+// PR auto-complete (MUL-7429)+// =====================+func (q *Queries) GetIssuePRAutoCompleteDisabled(ctx context.Context, issueID pgtype.UUID) (bool, error) {+ row := q.db.QueryRow(ctx, getIssuePRAutoCompleteDisabled, issueID)+ var disabled bool+ err := row.Scan(&disabled)+ return disabled, err+}++const isPullRequestExcludedFromIssue = `-- name: IsPullRequestExcludedFromIssue :one+SELECT EXISTS (+ SELECT 1 FROM issue_pull_request_exclusion+ WHERE issue_id = $1 AND pull_request_id = $2+)::boolean AS excluded+`++type IsPullRequestExcludedFromIssueParams struct {+ IssueID pgtype.UUID `json:"issue_id"`+ PullRequestID pgtype.UUID `json:"pull_request_id"`+}++func (q *Queries) IsPullRequestExcludedFromIssue(ctx context.Context, arg IsPullRequestExcludedFromIssueParams) (bool, error) {+ row := q.db.QueryRow(ctx, isPullRequestExcludedFromIssue, arg.IssueID, arg.PullRequestID)+ var excluded bool+ err := row.Scan(&excluded)+ return excluded, err+}++const listIssueLinkedPullRequestStates = `-- name: ListIssueLinkedPullRequestStates :many+SELECT pr.id, 'github'::text AS provider, pr.pr_number, pr.state+FROM github_pull_request pr+JOIN issue_pull_request ipr ON ipr.pull_request_id = pr.id+WHERE ipr.issue_id = $1+UNION ALL+SELECT pr.id, pr.provider AS provider, pr.pr_number, pr.state+FROM vcs_pull_request pr+JOIN issue_vcs_pull_request ipr ON ipr.pull_request_id = pr.id+WHERE ipr.issue_id = $1+ORDER BY pr_number+`++type ListIssueLinkedPullRequestStatesRow struct {+ ID pgtype.UUID `json:"id"`+ Provider string `json:"provider"`+ PrNumber int32 `json:"pr_number"`+ State string `json:"state"`+}++// Every PR linked to the issue across GitHub and self-hosted providers, for+// the auto-complete decision. Ordered by number so reasons read stably.+func (q *Queries) ListIssueLinkedPullRequestStates(ctx context.Context, issueID pgtype.UUID) ([]ListIssueLinkedPullRequestStatesRow, error) {+ rows, err := q.db.Query(ctx, listIssueLinkedPullRequestStates, issueID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ListIssueLinkedPullRequestStatesRow{}+ for rows.Next() {+ var i ListIssueLinkedPullRequestStatesRow+ if err := rows.Scan(+ &i.ID,+ &i.Provider,+ &i.PrNumber,+ &i.State,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const setIssuePRAutoCompleteDisabled = `-- name: SetIssuePRAutoCompleteDisabled :exec+INSERT INTO issue_pr_automation (+ issue_id, workspace_id, auto_complete_disabled, updated_by_type, updated_by_id+) VALUES (+ $1, $2, $3, $4, $5+)+ON CONFLICT (issue_id) DO UPDATE SET+ auto_complete_disabled = EXCLUDED.auto_complete_disabled,+ updated_by_type = EXCLUDED.updated_by_type,+ updated_by_id = EXCLUDED.updated_by_id,+ updated_at = now()+`++type SetIssuePRAutoCompleteDisabledParams struct {+ IssueID pgtype.UUID `json:"issue_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ AutoCompleteDisabled bool `json:"auto_complete_disabled"`+ UpdatedByType pgtype.Text `json:"updated_by_type"`+ UpdatedByID pgtype.UUID `json:"updated_by_id"`+}++func (q *Queries) SetIssuePRAutoCompleteDisabled(ctx context.Context, arg SetIssuePRAutoCompleteDisabledParams) error {+ _, err := q.db.Exec(ctx, setIssuePRAutoCompleteDisabled,+ arg.IssueID,+ arg.WorkspaceID,+ arg.AutoCompleteDisabled,+ arg.UpdatedByType,+ arg.UpdatedByID,+ )+ return err+}diff --git a/server/pkg/db/generated/vcs.sql.go b/server/pkg/db/generated/vcs.sql.goindex 104f2ea698..ed88522652 100644--- a/server/pkg/db/generated/vcs.sql.go+++ b/server/pkg/db/generated/vcs.sql.go@@ -47,42 +47,47 @@ func (q *Queries) DeleteVCSConnection(ctx context.Context, arg DeleteVCSConnectireturn err}-const getIssueCombinedPullRequestCloseAggregate = `-- name: GetIssueCombinedPullRequestCloseAggregate :one-WITH combined AS (- SELECT pr.state AS state, ipr.close_intent AS close_intent- FROM github_pull_request pr- JOIN issue_pull_request ipr ON ipr.pull_request_id = pr.id- WHERE ipr.issue_id = $1- UNION ALL- SELECT pr.state AS state, ipr.close_intent AS close_intent- FROM vcs_pull_request pr- JOIN issue_vcs_pull_request ipr ON ipr.pull_request_id = pr.id- WHERE ipr.issue_id = $1-)-SELECT- COALESCE(SUM(CASE WHEN state IN ('open', 'draft') THEN 1 ELSE 0 END), 0)::bigint AS open_count,- COALESCE(SUM(CASE WHEN state = 'merged' AND close_intent THEN 1 ELSE 0 END), 0)::bigint AS merged_with_close_intent_count-FROM combined+const findVCSPullRequestByURL = `-- name: FindVCSPullRequestByURL :one+SELECT id, workspace_id, connection_id, provider, repo_owner, repo_name, pr_number, title, state, html_url, branch, head_sha, author_login, author_avatar_url, merged_at, closed_at, pr_created_at, pr_updated_at, additions, deletions, changed_files, created_at, updated_at FROM vcs_pull_request+WHERE workspace_id = $1+ AND lower(rtrim(html_url, '/')) = lower($2::text)+ORDER BY pr_updated_at DESC+LIMIT 1`-type GetIssueCombinedPullRequestCloseAggregateRow struct {- OpenCount int64 `json:"open_count"`- MergedWithCloseIntentCount int64 `json:"merged_with_close_intent_count"`+type FindVCSPullRequestByURLParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ HtmlUrl string `json:"html_url"`}-// Cross-provider close gate. An issue can carry PRs from GitHub AND a-// self-hosted VCS provider at the same time, so auto-advance has to see BOTH-// table pairs. Reading only one (as the per-provider aggregates do) lets a-// merged close-intent PR/MR on one provider advance an issue that still has an-// open PR on the other — either webhook is blind to the other's in-flight work.-// Sum the in-flight (open/draft) and merged-with-close-intent counts across-// github_pull_request+issue_pull_request and vcs_pull_request+-// issue_vcs_pull_request. A bare body mention is not linked on either side, so-// a passing reference never counts as in-flight.-func (q *Queries) GetIssueCombinedPullRequestCloseAggregate(ctx context.Context, issueID pgtype.UUID) (GetIssueCombinedPullRequestCloseAggregateRow, error) {- row := q.db.QueryRow(ctx, getIssueCombinedPullRequestCloseAggregate, issueID)- var i GetIssueCombinedPullRequestCloseAggregateRow- err := row.Scan(&i.OpenCount, &i.MergedWithCloseIntentCount)+func (q *Queries) FindVCSPullRequestByURL(ctx context.Context, arg FindVCSPullRequestByURLParams) (VcsPullRequest, error) {+ row := q.db.QueryRow(ctx, findVCSPullRequestByURL, arg.WorkspaceID, arg.HtmlUrl)+ var i VcsPullRequest+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.ConnectionID,+ &i.Provider,+ &i.RepoOwner,+ &i.RepoName,+ &i.PrNumber,+ &i.Title,+ &i.State,+ &i.HtmlUrl,+ &i.Branch,+ &i.HeadSha,+ &i.AuthorLogin,+ &i.AuthorAvatarUrl,+ &i.MergedAt,+ &i.ClosedAt,+ &i.PrCreatedAt,+ &i.PrUpdatedAt,+ &i.Additions,+ &i.Deletions,+ &i.ChangedFiles,+ &i.CreatedAt,+ &i.UpdatedAt,+ )return i, err}@@ -109,44 +114,174 @@ func (q *Queries) GetVCSConnectionByID(ctx context.Context, id pgtype.UUID) (Vcsreturn i, err}-const linkIssueToVCSPullRequest = `-- name: LinkIssueToVCSPullRequest :exec+const getVCSPullRequestByKey = `-- name: GetVCSPullRequestByKey :one+SELECT id, workspace_id, connection_id, provider, repo_owner, repo_name, pr_number, title, state, html_url, branch, head_sha, author_login, author_avatar_url, merged_at, closed_at, pr_created_at, pr_updated_at, additions, deletions, changed_files, created_at, updated_at FROM vcs_pull_request+WHERE connection_id = $1 AND repo_owner = $2 AND repo_name = $3 AND pr_number = $4+`++type GetVCSPullRequestByKeyParams struct {+ ConnectionID pgtype.UUID `json:"connection_id"`+ RepoOwner string `json:"repo_owner"`+ RepoName string `json:"repo_name"`+ PrNumber int32 `json:"pr_number"`+}++// The stored row before a webhook upsert, so the handler can tell a merge+// transition apart from a later event on an already-merged PR.+func (q *Queries) GetVCSPullRequestByKey(ctx context.Context, arg GetVCSPullRequestByKeyParams) (VcsPullRequest, error) {+ row := q.db.QueryRow(ctx, getVCSPullRequestByKey,+ arg.ConnectionID,+ arg.RepoOwner,+ arg.RepoName,+ arg.PrNumber,+ )+ var i VcsPullRequest+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.ConnectionID,+ &i.Provider,+ &i.RepoOwner,+ &i.RepoName,+ &i.PrNumber,+ &i.Title,+ &i.State,+ &i.HtmlUrl,+ &i.Branch,+ &i.HeadSha,+ &i.AuthorLogin,+ &i.AuthorAvatarUrl,+ &i.MergedAt,+ &i.ClosedAt,+ &i.PrCreatedAt,+ &i.PrUpdatedAt,+ &i.Additions,+ &i.Deletions,+ &i.ChangedFiles,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}++const getVCSPullRequestInWorkspace = `-- name: GetVCSPullRequestInWorkspace :one+SELECT id, workspace_id, connection_id, provider, repo_owner, repo_name, pr_number, title, state, html_url, branch, head_sha, author_login, author_avatar_url, merged_at, closed_at, pr_created_at, pr_updated_at, additions, deletions, changed_files, created_at, updated_at FROM vcs_pull_request+WHERE id = $1 AND workspace_id = $2+`++type GetVCSPullRequestInWorkspaceParams struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++func (q *Queries) GetVCSPullRequestInWorkspace(ctx context.Context, arg GetVCSPullRequestInWorkspaceParams) (VcsPullRequest, error) {+ row := q.db.QueryRow(ctx, getVCSPullRequestInWorkspace, arg.ID, arg.WorkspaceID)+ var i VcsPullRequest+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.ConnectionID,+ &i.Provider,+ &i.RepoOwner,+ &i.RepoName,+ &i.PrNumber,+ &i.Title,+ &i.State,+ &i.HtmlUrl,+ &i.Branch,+ &i.HeadSha,+ &i.AuthorLogin,+ &i.AuthorAvatarUrl,+ &i.MergedAt,+ &i.ClosedAt,+ &i.PrCreatedAt,+ &i.PrUpdatedAt,+ &i.Additions,+ &i.Deletions,+ &i.ChangedFiles,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}++const linkIssueToVCSPullRequest = `-- name: LinkIssueToVCSPullRequest :execrowsINSERT INTO issue_vcs_pull_request (- issue_id, pull_request_id, linked_by_type, linked_by_id, close_intent+ issue_id, pull_request_id, linked_by_type, linked_by_id) VALUES (- $1, $2, $4, $5, $3+ $1, $2, 'system', NULL)-ON CONFLICT (issue_id, pull_request_id) DO UPDATE SET- close_intent = CASE- WHEN $6 THEN issue_vcs_pull_request.close_intent- ELSE EXCLUDED.close_intent- END+ON CONFLICT (issue_id, pull_request_id) DO NOTHING`type LinkIssueToVCSPullRequestParams struct {- IssueID pgtype.UUID `json:"issue_id"`- PullRequestID pgtype.UUID `json:"pull_request_id"`- CloseIntent bool `json:"close_intent"`- LinkedByType pgtype.Text `json:"linked_by_type"`- LinkedByID pgtype.UUID `json:"linked_by_id"`- PreserveCloseIntent bool `json:"preserve_close_intent"`+ IssueID pgtype.UUID `json:"issue_id"`+ PullRequestID pgtype.UUID `json:"pull_request_id"`}// =====================// Issue ↔ VCS PR link// =====================-// Mirrors the GitHub link upsert: preserve_close_intent freezes close_intent-// once a terminal merge/close event has been recorded.-func (q *Queries) LinkIssueToVCSPullRequest(ctx context.Context, arg LinkIssueToVCSPullRequestParams) error {- _, err := q.db.Exec(ctx, linkIssueToVCSPullRequest,- arg.IssueID,- arg.PullRequestID,- arg.CloseIntent,- arg.LinkedByType,- arg.LinkedByID,- arg.PreserveCloseIntent,- )- return err+// Mirrors LinkIssueToPullRequest: automatic link, 1 only when new.+func (q *Queries) LinkIssueToVCSPullRequest(ctx context.Context, arg LinkIssueToVCSPullRequestParams) (int64, error) {+ result, err := q.db.Exec(ctx, linkIssueToVCSPullRequest, arg.IssueID, arg.PullRequestID)+ if err != nil {+ return 0, err+ }+ return result.RowsAffected(), nil+}++const linkIssueToVCSPullRequestManually = `-- name: LinkIssueToVCSPullRequestManually :execrows+INSERT INTO issue_vcs_pull_request (+ issue_id, pull_request_id, linked_by_type, linked_by_id+) VALUES (+ $1, $2, 'member', $3+)+ON CONFLICT (issue_id, pull_request_id) DO UPDATE SET+ linked_by_type = 'member',+ linked_by_id = EXCLUDED.linked_by_id+WHERE issue_vcs_pull_request.linked_by_type IS DISTINCT FROM 'member'+`++type LinkIssueToVCSPullRequestManuallyParams struct {+ IssueID pgtype.UUID `json:"issue_id"`+ PullRequestID pgtype.UUID `json:"pull_request_id"`+ LinkedByID pgtype.UUID `json:"linked_by_id"`+}++func (q *Queries) LinkIssueToVCSPullRequestManually(ctx context.Context, arg LinkIssueToVCSPullRequestManuallyParams) (int64, error) {+ result, err := q.db.Exec(ctx, linkIssueToVCSPullRequestManually, arg.IssueID, arg.PullRequestID, arg.LinkedByID)+ if err != nil {+ return 0, err+ }+ return result.RowsAffected(), nil+}++const listAutoLinkedIssueIDsForVCSPullRequest = `-- name: ListAutoLinkedIssueIDsForVCSPullRequest :many+SELECT issue_id FROM issue_vcs_pull_request+WHERE pull_request_id = $1+ AND COALESCE(linked_by_type, 'system') <> 'member'+`++func (q *Queries) ListAutoLinkedIssueIDsForVCSPullRequest(ctx context.Context, pullRequestID pgtype.UUID) ([]pgtype.UUID, error) {+ rows, err := q.db.Query(ctx, listAutoLinkedIssueIDsForVCSPullRequest, pullRequestID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []pgtype.UUID{}+ for rows.Next() {+ var issue_id pgtype.UUID+ if err := rows.Scan(&issue_id); err != nil {+ return nil, err+ }+ items = append(items, issue_id)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil}const listIssueIDsForVCSPRHead = `-- name: ListIssueIDsForVCSPRHead :many@@ -183,6 +318,31 @@ func (q *Queries) ListIssueIDsForVCSPRHead(ctx context.Context, arg ListIssueIDsreturn items, nil}+const listIssueIDsForVCSPullRequest = `-- name: ListIssueIDsForVCSPullRequest :many+SELECT issue_id FROM issue_vcs_pull_request+WHERE pull_request_id = $1+`++func (q *Queries) ListIssueIDsForVCSPullRequest(ctx context.Context, pullRequestID pgtype.UUID) ([]pgtype.UUID, error) {+ rows, err := q.db.Query(ctx, listIssueIDsForVCSPullRequest, pullRequestID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []pgtype.UUID{}+ for rows.Next() {+ var issue_id pgtype.UUID+ if err := rows.Scan(&issue_id); err != nil {+ return nil, err+ }+ items = append(items, issue_id)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const listVCSConnectionsByWorkspace = `-- name: ListVCSConnectionsByWorkspace :manySELECT id, workspace_id, provider, instance_url, account_login, access_token_encrypted, webhook_secret_encrypted, connected_by_id, created_at, updated_at FROM vcs_connection@@ -243,6 +403,7 @@ WITH checks AS ()SELECTpr.id, pr.workspace_id, pr.connection_id, pr.provider, pr.repo_owner, pr.repo_name, pr.pr_number, pr.title, pr.state, pr.html_url, pr.branch, pr.head_sha, pr.author_login, pr.author_avatar_url, pr.merged_at, pr.closed_at, pr.pr_created_at, pr.pr_updated_at, pr.additions, pr.deletions, pr.changed_files, pr.created_at, pr.updated_at,+ COALESCE(ipr.linked_by_type, 'system')::text AS linked_by_type,COALESCE(c.total, 0)::bigint AS checks_total,COALESCE(c.passed, 0)::bigint AS checks_passed,COALESCE(c.failed, 0)::bigint AS checks_failed,@@ -278,6 +439,7 @@ type ListVCSPullRequestsByIssueRow struct {ChangedFiles int32 `json:"changed_files"`CreatedAt pgtype.Timestamptz `json:"created_at"`UpdatedAt pgtype.Timestamptz `json:"updated_at"`+ LinkedByType string `json:"linked_by_type"`ChecksTotal int64 `json:"checks_total"`ChecksPassed int64 `json:"checks_passed"`ChecksFailed int64 `json:"checks_failed"`@@ -322,6 +484,7 @@ func (q *Queries) ListVCSPullRequestsByIssue(ctx context.Context, issueID pgtype&i.ChangedFiles,&i.CreatedAt,&i.UpdatedAt,+ &i.LinkedByType,&i.ChecksTotal,&i.ChecksPassed,&i.ChecksFailed,@@ -369,7 +532,7 @@ func (q *Queries) RotateVCSConnectionWebhookSecret(ctx context.Context, arg Rotareturn i, err}-const unlinkIssueFromVCSPullRequest = `-- name: UnlinkIssueFromVCSPullRequest :exec+const unlinkIssueFromVCSPullRequest = `-- name: UnlinkIssueFromVCSPullRequest :execrowsDELETE FROM issue_vcs_pull_requestWHERE issue_id = $1 AND pull_request_id = $2`@@ -379,17 +542,12 @@ type UnlinkIssueFromVCSPullRequestParams struct {PullRequestID pgtype.UUID `json:"pull_request_id"`}-// Drops a link an earlier claim created, for the GitHub twin's reason: while a-// PR is still editable, the link follows the live title/body parse, so a key the-// payload still carries but no longer claims — "Closes MUL-1" edited down to-// "Related MUL-1" — loses its link. A key deleted from the PR outright is NOT-// covered: the payload keeps no trace of it, so noticing that needs the stored-// links instead, which is its own change. Callers must not run this once the PR-// has gone terminal — a post-merge edit cannot retroactively unlink a PR that-// did the work.-func (q *Queries) UnlinkIssueFromVCSPullRequest(ctx context.Context, arg UnlinkIssueFromVCSPullRequestParams) error {- _, err := q.db.Exec(ctx, unlinkIssueFromVCSPullRequest, arg.IssueID, arg.PullRequestID)- return err+func (q *Queries) UnlinkIssueFromVCSPullRequest(ctx context.Context, arg UnlinkIssueFromVCSPullRequestParams) (int64, error) {+ result, err := q.db.Exec(ctx, unlinkIssueFromVCSPullRequest, arg.IssueID, arg.PullRequestID)+ if err != nil {+ return 0, err+ }+ return result.RowsAffected(), nil}const upsertVCSCommitStatus = `-- name: UpsertVCSCommitStatus :execdiff --git a/server/pkg/db/generated/workspace_delete.sql.go b/server/pkg/db/generated/workspace_delete.sql.goindex 561adc9ca5..6ed9cd8b2f 100644--- a/server/pkg/db/generated/workspace_delete.sql.go+++ b/server/pkg/db/generated/workspace_delete.sql.go@@ -380,6 +380,12 @@ deleted_issue_vcs_links AS (WHERE issue_id IN (SELECT id FROM ws_issues)OR pull_request_id IN (SELECT id FROM ws_vcs_prs)),+deleted_issue_pr_automation AS (+ DELETE FROM issue_pr_automation WHERE workspace_id = $1+),+deleted_issue_pr_exclusions AS (+ DELETE FROM issue_pull_request_exclusion WHERE workspace_id = $1+),deleted_agent_invocation_targets AS (DELETE FROM agent_invocation_targetWHERE agent_id IN (SELECT id FROM ws_agents)diff --git a/server/pkg/db/queries/github.sql b/server/pkg/db/queries/github.sqlindex 1d34a1a2e4..f2981d2201 100644--- a/server/pkg/db/queries/github.sql+++ b/server/pkg/db/queries/github.sql@@ -89,6 +89,10 @@ SELECT * FROM github_pending_installation WHERE installation_id = $1-- mergeability, and silently clobbering a known clean/dirty would lose-- information that GitHub only re-computes lazily.-- INSERT path always writes the incoming value (NULL acceptable for a new row).+--+-- GitHub may deliver events out of order. An event older than the stored row+-- (pr_updated_at) updates nothing and returns no row, so a late "opened" can't+-- roll a merged PR back to open — the same guard UpsertVCSPullRequest has.INSERT INTO github_pull_request (workspace_id, installation_id, repo_owner, repo_name, pr_number,title, state, html_url, branch, author_login, author_avatar_url,@@ -123,6 +127,7 @@ ON CONFLICT (workspace_id, repo_owner, repo_name, pr_number) DO UPDATE SETdeletions = EXCLUDED.deletions,changed_files = EXCLUDED.changed_files,updated_at = now()+WHERE EXCLUDED.pr_updated_at >= github_pull_request.pr_updated_atRETURNING *;-- name: GetGitHubPullRequest :one@@ -137,10 +142,9 @@ WHERE workspace_id = $1 AND repo_owner = $2 AND repo_name = $3 AND pr_number = $-- refresh pipeline — NOT the legacy suite-level webhook aggregation, which is-- removed. The `issue_prs` CTE narrows to this issue's PR ids first so the-- aggregation only touches check rows for those PRs. Rows for an OLD head are--- excluded by the snapshot_head_sha filter. Every link row is a working PR:--- the webhook only links an identifier it read from the PR title, the branch--- name, or a body closing keyword, so a bare body mention never lands here--- (MUL-7072).+-- excluded by the snapshot_head_sha filter. Every link row is a delivery PR:+-- the webhook links an identifier it read from the PR title or branch name, and+-- a member can link one by hand (linked_by_type = 'member'). MUL-7429.WITH issue_prs AS (SELECT pr.id, pr.snapshot_head_shaFROM github_pull_request pr@@ -178,6 +182,7 @@ SELECTpr.api_mergeable, pr.api_merge_state_status, pr.checks_rollup_state,pr.snapshot_head_sha, pr.snapshot_fetched_at,pr.created_at, pr.updated_at,+ COALESCE(ipr.linked_by_type, 'system')::text AS linked_by_type,COALESCE(c.total, 0)::bigint AS checks_total,COALESCE(c.passed, 0)::bigint AS checks_passed,COALESCE(c.failed, 0)::bigint AS checks_failed,@@ -221,44 +226,55 @@ LIMIT 1;SELECT issue_id FROM issue_pull_requestWHERE pull_request_id = $1;--- name: GetIssuePullRequestCloseAggregate :one--- Aggregates the issue's linked PRs into the two counts that gate--- auto-advance: how many are still in flight (`open` or `draft`) and how--- many merged PRs declared explicit closing intent on the link row. The--- webhook auto-advances the issue when open_count = 0 AND--- merged_with_close_intent_count > 0. Both the PR state and the link row--- (with close_intent) are persisted before this query runs, so the result--- is event-agnostic — a link-only sibling closing after a closing-keyword--- PR has already merged still resolves the issue. A bare body mention is not--- linked at all, so a passing reference can never keep open_count > 0.-SELECT- COALESCE(SUM(CASE WHEN pr.state IN ('open', 'draft') THEN 1 ELSE 0 END), 0)::bigint AS open_count,- COALESCE(SUM(CASE WHEN pr.state = 'merged' AND ipr.close_intent THEN 1 ELSE 0 END), 0)::bigint AS merged_with_close_intent_count-FROM github_pull_request pr-JOIN issue_pull_request ipr ON ipr.pull_request_id = pr.id-WHERE ipr.issue_id = $1;--- =====================-- Issue ↔ Pull Request link-- =====================--- name: LinkIssueToPullRequest :exec--- close_intent reflects the PR's explicit close declaration at the moment--- the webhook is allowed to update that intent. Open/edit/merge webhooks use--- the current title/body parse result so authors can remove a closing keyword--- before merge. Post-terminal edits can opt into preserving the stored value,--- keeping the merge-time decision stable.+-- name: LinkIssueToPullRequest :execrows+-- Automatic link from a PR title or branch. Returns 1 only when the link is+-- new, so the webhook evaluates auto-complete on the link event and not on+-- every redelivery. An existing link (automatic or manual) is left untouched.+INSERT INTO issue_pull_request (+ issue_id, pull_request_id, linked_by_type, linked_by_id+) VALUES (+ $1, $2, 'system', NULL+)+ON CONFLICT (issue_id, pull_request_id) DO NOTHING;++-- name: LinkIssueToPullRequestManually :execrows+-- A member linked this PR by hand. Marking an existing automatic link as+-- manual keeps a later title edit from removing it. Returns 1 when the row was+-- inserted or converted.INSERT INTO issue_pull_request (- issue_id, pull_request_id, linked_by_type, linked_by_id, close_intent+ issue_id, pull_request_id, linked_by_type, linked_by_id) VALUES (- $1, $2, sqlc.narg('linked_by_type'), sqlc.narg('linked_by_id'), $3+ $1, $2, 'member', sqlc.narg('linked_by_id'))ON CONFLICT (issue_id, pull_request_id) DO UPDATE SET- close_intent = CASE- WHEN sqlc.arg('preserve_close_intent') THEN issue_pull_request.close_intent- ELSE EXCLUDED.close_intent- END;+ linked_by_type = 'member',+ linked_by_id = EXCLUDED.linked_by_id+WHERE issue_pull_request.linked_by_type IS DISTINCT FROM 'member';--- name: UnlinkIssueFromPullRequest :exec+-- name: ListAutoLinkedIssueIDsForPullRequest :many+-- Issues this PR is linked to automatically. Manual links are not listed: the+-- webhook reconciles only what it created itself.+SELECT issue_id FROM issue_pull_request+WHERE pull_request_id = $1+ AND COALESCE(linked_by_type, 'system') <> 'member';++-- name: UnlinkIssueFromPullRequest :execrowsDELETE FROM issue_pull_requestWHERE issue_id = $1 AND pull_request_id = $2;++-- name: GetGitHubPullRequestInWorkspace :one+SELECT * FROM github_pull_request+WHERE id = $1 AND workspace_id = $2;++-- name: FindGitHubPullRequestByURL :one+-- Resolves a pasted PR URL to a mirrored PR. The caller normalizes the URL to+-- scheme://host/owner/repo/pull/N; html_url is stored in that shape.+SELECT * FROM github_pull_request+WHERE workspace_id = $1+ AND lower(rtrim(html_url, '/')) = lower(sqlc.arg('html_url')::text)+ORDER BY pr_updated_at DESC+LIMIT 1;diff --git a/server/pkg/db/queries/issue.sql b/server/pkg/db/queries/issue.sqlindex 0bc41314c0..a6d5d4bd4a 100644--- a/server/pkg/db/queries/issue.sql+++ b/server/pkg/db/queries/issue.sql@@ -492,6 +492,12 @@ cleared_task_supplement_capabilities AS (),cleared_vcs_pr_links AS (DELETE FROM issue_vcs_pull_request WHERE issue_id IN (SELECT target.id FROM target)+),+cleared_pr_automation AS (+ DELETE FROM issue_pr_automation WHERE issue_id IN (SELECT target.id FROM target)+),+cleared_pr_exclusions AS (+ DELETE FROM issue_pull_request_exclusion WHERE issue_id IN (SELECT target.id FROM target))DELETE FROM issue WHERE issue.id IN (SELECT target.id FROM target);diff --git a/server/pkg/db/queries/pr_automation.sql b/server/pkg/db/queries/pr_automation.sqlnew file mode 100644index 0000000000..b71a230101--- /dev/null+++ b/server/pkg/db/queries/pr_automation.sql@@ -0,0 +1,95 @@+-- =====================+-- PR auto-complete (MUL-7429)+-- =====================++-- name: GetIssuePRAutoCompleteDisabled :one+SELECT EXISTS (+ SELECT 1 FROM issue_pr_automation+ WHERE issue_id = $1 AND auto_complete_disabled+)::boolean AS disabled;++-- name: SetIssuePRAutoCompleteDisabled :exec+INSERT INTO issue_pr_automation (+ issue_id, workspace_id, auto_complete_disabled, updated_by_type, updated_by_id+) VALUES (+ $1, $2, $3, sqlc.narg('updated_by_type'), sqlc.narg('updated_by_id')+)+ON CONFLICT (issue_id) DO UPDATE SET+ auto_complete_disabled = EXCLUDED.auto_complete_disabled,+ updated_by_type = EXCLUDED.updated_by_type,+ updated_by_id = EXCLUDED.updated_by_id,+ updated_at = now();++-- name: IsPullRequestExcludedFromIssue :one+SELECT EXISTS (+ SELECT 1 FROM issue_pull_request_exclusion+ WHERE issue_id = $1 AND pull_request_id = $2+)::boolean AS excluded;++-- name: ExcludePullRequestFromIssue :exec+INSERT INTO issue_pull_request_exclusion (+ issue_id, pull_request_id, workspace_id, excluded_by_type, excluded_by_id+) VALUES (+ $1, $2, $3, sqlc.narg('excluded_by_type'), sqlc.narg('excluded_by_id')+)+ON CONFLICT (issue_id, pull_request_id) DO UPDATE SET+ excluded_by_type = EXCLUDED.excluded_by_type,+ excluded_by_id = EXCLUDED.excluded_by_id,+ created_at = now();++-- name: DeletePullRequestExclusion :exec+DELETE FROM issue_pull_request_exclusion+WHERE issue_id = $1 AND pull_request_id = $2;++-- name: ListIssueLinkedPullRequestStates :many+-- Every PR linked to the issue across GitHub and self-hosted providers, for+-- the auto-complete decision. Ordered by number so reasons read stably.+SELECT pr.id, 'github'::text AS provider, pr.pr_number, pr.state+FROM github_pull_request pr+JOIN issue_pull_request ipr ON ipr.pull_request_id = pr.id+WHERE ipr.issue_id = $1+UNION ALL+SELECT pr.id, pr.provider AS provider, pr.pr_number, pr.state+FROM vcs_pull_request pr+JOIN issue_vcs_pull_request ipr ON ipr.pull_request_id = pr.id+WHERE ipr.issue_id = $1+ORDER BY pr_number;++-- name: CompleteIssueFromPullRequests :one+-- Conditional status write for PR auto-complete. It lands only if the issue is+-- still in the status the decision saw (two merges racing complete it once) and+-- the linked PRs are still all merged when the write runs: a PR linked between+-- the decision and this statement keeps the issue open. Repositions like+-- UpdateIssueStatus does.+UPDATE issue AS i SET+ status = 'done',+ duplicate_of_issue_id = NULL,+ position = (+ SELECT COALESCE(MIN(target.position), 0) - 1+ FROM issue AS target+ WHERE target.workspace_id = i.workspace_id+ AND target.status = 'done'+ ),+ revision = i.revision + 1,+ last_activity_at = GREATEST(COALESCE(i.last_activity_at, i.updated_at), now()),+ updated_at = now()+WHERE i.id = $1+ AND i.workspace_id = $2+ AND i.status = sqlc.arg('expected_status')::text+ AND i.status <> 'done'+ AND EXISTS (+ SELECT 1 FROM issue_pull_request ipr WHERE ipr.issue_id = i.id+ UNION ALL+ SELECT 1 FROM issue_vcs_pull_request ipr WHERE ipr.issue_id = i.id+ )+ AND NOT EXISTS (+ SELECT 1 FROM issue_pull_request ipr+ JOIN github_pull_request pr ON pr.id = ipr.pull_request_id+ WHERE ipr.issue_id = i.id AND pr.state <> 'merged'+ )+ AND NOT EXISTS (+ SELECT 1 FROM issue_vcs_pull_request ipr+ JOIN vcs_pull_request pr ON pr.id = ipr.pull_request_id+ WHERE ipr.issue_id = i.id AND pr.state <> 'merged'+ )+RETURNING i.*;diff --git a/server/pkg/db/queries/vcs.sql b/server/pkg/db/queries/vcs.sqlindex 5b92494fcb..94ef3cf9c0 100644--- a/server/pkg/db/queries/vcs.sql+++ b/server/pkg/db/queries/vcs.sql@@ -126,6 +126,7 @@ WITH checks AS ()SELECTpr.*,+ COALESCE(ipr.linked_by_type, 'system')::text AS linked_by_type,COALESCE(c.total, 0)::bigint AS checks_total,COALESCE(c.passed, 0)::bigint AS checks_passed,COALESCE(c.failed, 0)::bigint AS checks_failed,@@ -136,32 +137,6 @@ LEFT JOIN checks c ON c.pr_id = pr.idWHERE ipr.issue_id = sqlc.arg('issue_id')ORDER BY pr.pr_created_at DESC;--- name: GetIssueCombinedPullRequestCloseAggregate :one--- Cross-provider close gate. An issue can carry PRs from GitHub AND a--- self-hosted VCS provider at the same time, so auto-advance has to see BOTH--- table pairs. Reading only one (as the per-provider aggregates do) lets a--- merged close-intent PR/MR on one provider advance an issue that still has an--- open PR on the other — either webhook is blind to the other's in-flight work.--- Sum the in-flight (open/draft) and merged-with-close-intent counts across--- github_pull_request+issue_pull_request and vcs_pull_request+--- issue_vcs_pull_request. A bare body mention is not linked on either side, so--- a passing reference never counts as in-flight.-WITH combined AS (- SELECT pr.state AS state, ipr.close_intent AS close_intent- FROM github_pull_request pr- JOIN issue_pull_request ipr ON ipr.pull_request_id = pr.id- WHERE ipr.issue_id = $1- UNION ALL- SELECT pr.state AS state, ipr.close_intent AS close_intent- FROM vcs_pull_request pr- JOIN issue_vcs_pull_request ipr ON ipr.pull_request_id = pr.id- WHERE ipr.issue_id = $1-)-SELECT- COALESCE(SUM(CASE WHEN state IN ('open', 'draft') THEN 1 ELSE 0 END), 0)::bigint AS open_count,- COALESCE(SUM(CASE WHEN state = 'merged' AND close_intent THEN 1 ELSE 0 END), 0)::bigint AS merged_with_close_intent_count-FROM combined;--- =====================-- VCS commit status (CI)-- =====================@@ -194,28 +169,52 @@ WHERE pr.connection_id = $1 AND pr.head_sha = $2 AND pr.head_sha <> '';-- Issue ↔ VCS PR link-- =====================--- name: LinkIssueToVCSPullRequest :exec--- Mirrors the GitHub link upsert: preserve_close_intent freezes close_intent--- once a terminal merge/close event has been recorded.+-- name: LinkIssueToVCSPullRequest :execrows+-- Mirrors LinkIssueToPullRequest: automatic link, 1 only when new.+INSERT INTO issue_vcs_pull_request (+ issue_id, pull_request_id, linked_by_type, linked_by_id+) VALUES (+ $1, $2, 'system', NULL+)+ON CONFLICT (issue_id, pull_request_id) DO NOTHING;++-- name: LinkIssueToVCSPullRequestManually :execrowsINSERT INTO issue_vcs_pull_request (- issue_id, pull_request_id, linked_by_type, linked_by_id, close_intent+ issue_id, pull_request_id, linked_by_type, linked_by_id) VALUES (- $1, $2, sqlc.narg('linked_by_type'), sqlc.narg('linked_by_id'), $3+ $1, $2, 'member', sqlc.narg('linked_by_id'))ON CONFLICT (issue_id, pull_request_id) DO UPDATE SET- close_intent = CASE- WHEN sqlc.arg('preserve_close_intent') THEN issue_vcs_pull_request.close_intent- ELSE EXCLUDED.close_intent- END;---- name: UnlinkIssueFromVCSPullRequest :exec--- Drops a link an earlier claim created, for the GitHub twin's reason: while a--- PR is still editable, the link follows the live title/body parse, so a key the--- payload still carries but no longer claims — "Closes MUL-1" edited down to--- "Related MUL-1" — loses its link. A key deleted from the PR outright is NOT--- covered: the payload keeps no trace of it, so noticing that needs the stored--- links instead, which is its own change. Callers must not run this once the PR--- has gone terminal — a post-merge edit cannot retroactively unlink a PR that--- did the work.+ linked_by_type = 'member',+ linked_by_id = EXCLUDED.linked_by_id+WHERE issue_vcs_pull_request.linked_by_type IS DISTINCT FROM 'member';++-- name: ListIssueIDsForVCSPullRequest :many+SELECT issue_id FROM issue_vcs_pull_request+WHERE pull_request_id = $1;++-- name: ListAutoLinkedIssueIDsForVCSPullRequest :many+SELECT issue_id FROM issue_vcs_pull_request+WHERE pull_request_id = $1+ AND COALESCE(linked_by_type, 'system') <> 'member';++-- name: UnlinkIssueFromVCSPullRequest :execrowsDELETE FROM issue_vcs_pull_requestWHERE issue_id = $1 AND pull_request_id = $2;++-- name: GetVCSPullRequestByKey :one+-- The stored row before a webhook upsert, so the handler can tell a merge+-- transition apart from a later event on an already-merged PR.+SELECT * FROM vcs_pull_request+WHERE connection_id = $1 AND repo_owner = $2 AND repo_name = $3 AND pr_number = $4;++-- name: GetVCSPullRequestInWorkspace :one+SELECT * FROM vcs_pull_request+WHERE id = $1 AND workspace_id = $2;++-- name: FindVCSPullRequestByURL :one+SELECT * FROM vcs_pull_request+WHERE workspace_id = $1+ AND lower(rtrim(html_url, '/')) = lower(sqlc.arg('html_url')::text)+ORDER BY pr_updated_at DESC+LIMIT 1;diff --git a/server/pkg/db/queries/workspace_delete.sql b/server/pkg/db/queries/workspace_delete.sqlindex 3160bfc86d..c90d69c98e 100644--- a/server/pkg/db/queries/workspace_delete.sql+++ b/server/pkg/db/queries/workspace_delete.sql@@ -396,6 +396,12 @@ deleted_issue_vcs_links AS (WHERE issue_id IN (SELECT id FROM ws_issues)OR pull_request_id IN (SELECT id FROM ws_vcs_prs)),+deleted_issue_pr_automation AS (+ DELETE FROM issue_pr_automation WHERE workspace_id = $1+),+deleted_issue_pr_exclusions AS (+ DELETE FROM issue_pull_request_exclusion WHERE workspace_id = $1+),deleted_agent_invocation_targets AS (DELETE FROM agent_invocation_targetWHERE agent_id IN (SELECT id FROM ws_agents)