Skip to content

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

Go

MUL-7726: let the workspace choose the status merged PRs move an issue to (#8862)

Jiayuan Zhangfc4a61570063
diff --git a/apps/docs/content/docs/environment-variables.fr.mdx b/apps/docs/content/docs/environment-variables.fr.mdx
index dac958f832..3fb7ecebb7 100644
--- a/apps/docs/content/docs/environment-variables.fr.mdx
+++ b/apps/docs/content/docs/environment-variables.fr.mdx
@@ -192,7 +192,7 @@ Les limites de débit d'authentification nécessitent `REDIS_URL` ; sans cette v
| Plugins | `MULTICA_PLUGIN_API_URL` | URL de base complète et versionnée de la Plugin Public API, comme `https://plugin-api.example.com/v1` ; se rabat sur `MULTICA_PUBLIC_URL` + `/v1` |
| Plugins | `MULTICA_PLUGIN_DIR` | Répertoire absolu facultatif utilisé pour publier des bundles de plugins locaux pendant le développement |
-Sans `GITHUB_APP_ID` et la clé privée, les PR sont toujours liées, reflétées et déclenchent normalement le passage à `done` lors du merge, mais les cartes n'affichent ni statut CI ni possibilité de fusion, et l'entrée de dépôt « Choisir depuis GitHub » est désactivée.
+Sans `GITHUB_APP_ID` et la clé privée, les PR sont toujours liées, reflétées et changent normalement le statut de la tâche lors du merge, mais les cartes n'affichent ni statut CI ni possibilité de fusion, et l'entrée de dépôt « Choisir depuis GitHub » est désactivée.
Pour les étapes de configuration, consultez [Intégration GitHub](/github-integration#configuration-en-auto-hébergement), [Bot Lark](/lark-bot-integration#configuration-en-auto-hébergement), [Bot Slack](/slack-bot-integration#configuration-en-auto-hébergement) et [Bot Telegram](/telegram-bot-integration#configuration-en-auto-hébergement).
diff --git a/apps/docs/content/docs/environment-variables.ja.mdx b/apps/docs/content/docs/environment-variables.ja.mdx
index 6e6be9f550..49c4c987f0 100644
--- a/apps/docs/content/docs/environment-variables.ja.mdx
+++ b/apps/docs/content/docs/environment-variables.ja.mdx
@@ -192,7 +192,7 @@ allowlist の正確な判定順序は[ログインとサインアップ](/auth-s
| Plugins | `MULTICA_PLUGIN_API_URL` | バージョンを含む Plugin Public API の完全な Base URL(例: `https://plugin-api.example.com/v1`)。未設定時は `MULTICA_PUBLIC_URL` + `/v1` |
| Plugins | `MULTICA_PLUGIN_DIR` | 開発時にローカル plugin bundle を公開するための任意の絶対ディレクトリ |
-`GITHUB_APP_ID` と秘密鍵を設定しなくても、PR の関連付け・ミラー・マージによる done への遷移は通常どおり動きますが、カードに CI とマージ可否のステータスが表示されず、「GitHub から選択」のリポジトリ入口も無効になります。
+`GITHUB_APP_ID` と秘密鍵を設定しなくても、PR の関連付け・ミラー・マージ時のステータス変更は通常どおり動きますが、カードに CI とマージ可否のステータスが表示されず、「GitHub から選択」のリポジトリ入口も無効になります。
設定手順は [GitHub 連携](/github-integration#セルフホスト設定)、[Lark Bot](/lark-bot-integration#セルフホスト設定)、[Slack Bot](/slack-bot-integration#セルフホスト設定)、[Telegram Bot](/telegram-bot-integration#管理とセルフホスティング)を参照してください。
diff --git a/apps/docs/content/docs/environment-variables.ko.mdx b/apps/docs/content/docs/environment-variables.ko.mdx
index 72eee39b0f..4ce9f977da 100644
--- a/apps/docs/content/docs/environment-variables.ko.mdx
+++ b/apps/docs/content/docs/environment-variables.ko.mdx
@@ -192,7 +192,7 @@ reverse proxy 뒤에 배포한다면 실제 proxy 네트워크를 입력해야
| Plugins | `MULTICA_PLUGIN_API_URL` | 버전을 포함한 Plugin Public API의 전체 Base URL(예: `https://plugin-api.example.com/v1`). 설정하지 않으면 `MULTICA_PUBLIC_URL` + `/v1` 사용 |
| Plugins | `MULTICA_PLUGIN_DIR` | 개발 중 로컬 plugin bundle을 게시하는 선택적 절대 디렉터리 |
-`GITHUB_APP_ID`와 private key를 설정하지 않아도 PR 연결, 미러링, merge 시 done 전환은 정상적으로 작동합니다. 다만 카드에 CI와 merge 가능 상태가 표시되지 않고 "GitHub에서 선택" 저장소 메뉴도 비활성화됩니다.
+`GITHUB_APP_ID`와 private key를 설정하지 않아도 PR 연결, 미러링, merge 시 상태 변경은 정상적으로 작동합니다. 다만 카드에 CI와 merge 가능 상태가 표시되지 않고 "GitHub에서 선택" 저장소 메뉴도 비활성화됩니다.
설정 단계는 [GitHub 연동](/github-integration#자체-호스팅-설정), [Feishu Bot](/lark-bot-integration#자체-호스팅-설정), [Slack Bot](/slack-bot-integration#자체-호스팅-설정), [Telegram Bot](/telegram-bot-integration#관리-및-자체-호스팅)을 참고하세요.
diff --git a/apps/docs/content/docs/environment-variables.mdx b/apps/docs/content/docs/environment-variables.mdx
index 63bcba7ee0..871e6660d9 100644
--- a/apps/docs/content/docs/environment-variables.mdx
+++ b/apps/docs/content/docs/environment-variables.mdx
@@ -192,7 +192,7 @@ The auth rate limits require `REDIS_URL`; without it, the startup log notes that
| Plugins | `MULTICA_PLUGIN_API_URL` | Complete versioned Plugin Public API base URL, such as `https://plugin-api.example.com/v1`; falls back to `MULTICA_PUBLIC_URL` + `/v1` |
| Plugins | `MULTICA_PLUGIN_DIR` | Optional absolute directory used to publish local plugin bundles during development |
-Without `GITHUB_APP_ID` and the private key, PRs still link, mirror, and trigger merge-to-done normally, but cards show no CI or mergeability status, and the "pick from GitHub" repository entry is disabled.
+Without `GITHUB_APP_ID` and the private key, PRs still link, mirror, and move issues on merge normally, but cards show no CI or mergeability status, and the "pick from GitHub" repository entry is disabled.
For setup steps, see [GitHub integration](/github-integration#self-hosting-setup), [Lark bot](/lark-bot-integration#self-hosting-setup), [Slack bot](/slack-bot-integration#self-hosting-setup), and [Telegram bot](/telegram-bot-integration#self-hosting-setup).
diff --git a/apps/docs/content/docs/environment-variables.zh.mdx b/apps/docs/content/docs/environment-variables.zh.mdx
index ac9adc29e1..59df60d2f5 100644
--- a/apps/docs/content/docs/environment-variables.zh.mdx
+++ b/apps/docs/content/docs/environment-variables.zh.mdx
@@ -192,7 +192,7 @@ MULTICA_PUBLIC_URL=https://api.multica.example.com
| 插件 | `MULTICA_PLUGIN_API_URL` | 带版本的插件 Public API 完整 Base URL,例如 `https://plugin-api.example.com/v1`;未设置时使用 `MULTICA_PUBLIC_URL` + `/v1` |
| 插件 | `MULTICA_PLUGIN_DIR` | 开发时用于发布本地插件包的可选绝对目录 |
-不配置 `GITHUB_APP_ID` 和私钥时,PR 仍会正常关联、镜像和触发合并转 done,但卡片上不显示 CI 与可合并状态,"从 GitHub 选择"仓库入口也会禁用。
+不配置 `GITHUB_APP_ID` 和私钥时,PR 仍会正常关联、镜像,并在合并后改状态,但卡片上不显示 CI 与可合并状态,"从 GitHub 选择"仓库入口也会禁用。
配置步骤见 [GitHub 集成](/github-integration#自托管配置)、[飞书 Bot](/lark-bot-integration#自托管配置)、[Slack Bot](/slack-bot-integration#自托管配置)和 [Telegram Bot](/telegram-bot-integration#自托管配置)。
diff --git a/apps/docs/content/docs/github-integration.ja.mdx b/apps/docs/content/docs/github-integration.ja.mdx
index 5df60909e5..bf981bfd62 100644
--- a/apps/docs/content/docs/github-integration.ja.mdx
+++ b/apps/docs/content/docs/github-integration.ja.mdx
@@ -9,7 +9,7 @@ GitHub を接続すると、Multica はタスク番号を使って pull request
GitHub 連携が読み取るのは、インストール時に許可されたリポジトリだけです。コード、コメント、status check を書き込むことはありません。
-セルフホスト版 Multica では、セルフホストの Forgejo、Gitea、GitLab インスタンスも同時に接続できます。PR の自動紐づけ、マージ時の Done への変更、CI 表示を同じように利用できます。**設定 → 連携 → Git ホスティング**から設定してください。詳しくは[セルフホスト Git ホスティング](/vcs-integration)を参照してください。Multica Cloud にはこの項目はありません。
+セルフホスト版 Multica では、セルフホストの Forgejo、Gitea、GitLab インスタンスも同時に接続できます。PR の自動紐づけ、マージ時のステータス変更、CI 表示を同じように利用できます。**設定 → 連携 → Git ホスティング**から設定してください。詳しくは[セルフホスト Git ホスティング](/vcs-integration)を参照してください。Multica Cloud にはこの項目はありません。
## GitHub を接続する
@@ -29,14 +29,15 @@ GitHub 連携が読み取るのは、インストール時に許可されたリ
## 機能スイッチ
-**設定 → GitHub** には 4 つのスイッチがあります。
+**設定 → 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 がすべてマージされたとき、タスクをあるステータス(既定は `Done`)に変更するか、変更しないかを選びます。下記の **PR マージ後のステータス変更** を参照してください。 |
| **PR カード → CI とマージ可否** | 紐づいた各 PR について、Multica は認証済みの GitHub API スナップショットを取得し、その **CI ステータス**と**マージ可否**をカードにミラーリングします(下記の **PR カードに表示される内容** を参照)。 |
@@ -78,23 +79,24 @@ Resolves MUL-123
CI の状態とマージ可能性は、Multica が GitHub API から取得したスナップショットで、互いに独立しています。マージ済みまたはクローズ済みの PR では、この 2 項目を表示しません。GitHub が一時的に利用できない場合、カードを空にせず、前回のスナップショットを古い情報として表示します。
-リストの下には、次に何が起きるかを 1 行で表示します。たとえば「#19 がマージされると自動完了」、`Closes MUL-123` と書いた PR がないこと、マージされずにクローズされた PR です。
+リストの下には、次に何が起きるかを 1 行で表示します。たとえば「#19 がマージされると 完了 に変更」や、マージされずにクローズされた PR です。ワークスペースが「変更しない」に設定されている場合や、タスクがすでに変更先のステータスにある場合は表示されません。
項目をクリックすると GitHub の PR が開きます。**PR サイドバー**を無効にしてもこのセクションが非表示になるだけで、接続は解除されません。
-## PR のマージで Done になる条件
+## PR マージ後のステータス変更
-PR がマージされても、必ずしもタスクが完了するわけではありません。**PR のマージでタスクを自動完了**(**設定 → タスクステータス → 自動化**、既定でオン)が有効な場合、Multica がタスクを `Done` に変更するのは、次の条件をすべて満たす場合だけです。
+PR がマージされても、必ずしもタスクが完了するわけではありません。そのため、マージ後に何をするかはワークスペースが決めます: **設定 → 連携 → GitHub → PR マージ後のタスクのステータス**。`Done`(新しいワークスペースの既定値)、ほかの「開始済み」「完了」カテゴリーのステータス(「回帰テスト待ち」のようなカスタムステータスも可)、または **変更しない** を選べます。この設定ができる前からあるワークスペースは、これまでの挙動を保ちます。マージしても必ずタスクが完了していたわけではない場合、初期値は **変更しない** です。
-1. 紐づいたマージ済み PR のうち少なくとも 1 つが、タイトルか本文で `Closes MUL-123` のように closing keyword の直後にタスク番号を指定している。`Closes login MUL-123` のように間に別の単語がある形式や、ブランチ名は対象外です。
-2. タスクに紐づく PR がすべて `Merged` である。`Open` や `Draft` の PR が残っているとタスクは待機を続けます。マージされずにクローズされた PR も、タスクから外すまで同様です。
-3. タスクが `done` または `cancelled` ではなく、そのタスクだけ自動完了をオフにしていない(**Pull requests → ⋯ → このタスクは自動完了しない**)。
+次の条件をすべて満たすと、タスクは選んだステータスに変わります。
-そのため、ブランチ名やタイトルに `MUL-123` を含めるだけで紐づけは作成されますが、それだけではタスクを完了にしません。マージでタスクを完了させたい場合にだけ closing keyword を使ってください。closing keyword はマージ時点の内容で判断されます。マージ後に書き足しても紐づけが作成されるだけで、タスクは完了しません。
+1. タスクに紐づく PR がすべて `Merged` である。`Open` や `Draft` の PR が残っているとタスクは待機を続けます。マージされずにクローズされた PR も、タスクから外すまで同様です。
+2. タスクが `done` または `cancelled` ではなく、Triage 中でもなく、すでに変更先のステータスでもなく、このタスクだけ変更をオフにしていない(**Pull requests → ⋯ → PR マージ後もステータスを変えない**)。
-判定は PR イベントがタスクに関わったときだけ行います。紐づいた PR のマージ、紐づけの追加、紐づけの解除です。タスクを再度開いても `Done` には戻らず、次に紐づいた PR がマージされたときに完了します。設定をオンにしても、以前にマージされたタスクをさかのぼって完了にはしません。
+PR の紐づけ方は結果に影響しません。タイトル、ブランチ名、本文の `Closes MUL-123` はどれも紐づけるだけで、マージ後の動作は決めません。PR がタスクの一部しか納品しない場合や、マージ後にリリースや確認が必要な場合は、そのタスクの **Pull requests** メニューからステータスを変えないように設定します。
-状態の変更は関連する PR を示したシステム操作としてタイムラインに記録され、そのタスクを購読しているメンバーへ通知されます。この設定は[セルフホスト Git ホスティング](/vcs-integration)を含むすべてのコードホストで共通です。
+判定は PR イベントがタスクに関わったときだけ行います。紐づいた PR のマージ、紐づけの追加、紐づけの解除です。タスクを再度開いても元には戻らず、次に紐づいた PR がマージされたときに変更されます。設定を変えても、以前にマージされたタスクには影響しません。
+
+状態の変更は関連する PR を示したシステム操作としてタイムラインに記録され、そのタスクを購読しているメンバーへ通知されます。この設定は[セルフホスト Git ホスティング](/vcs-integration)を含むすべてのコードホストで共通で、そちらのページにも同じ設定が表示されます。
## 複数のワークスペース
@@ -166,7 +168,7 @@ GITHUB_APP_ID=<numeric GitHub App ID>
GITHUB_APP_PRIVATE_KEY=<complete PEM private key, including BEGIN/END lines and newlines>
```
-秘密鍵は GitHub App の **Private keys → Generate a private key** から生成します。設定しない場合も連携は安全に縮退します。PR のミラー、タスクの自動紐づけ、マージ時の Done への変更は動作しますが、PR カードに CI やマージ状態は表示されません。
+秘密鍵は GitHub App の **Private keys → Generate a private key** から生成します。設定しない場合も連携は安全に縮退します。PR のミラー、タスクの自動紐づけ、マージ時のステータス変更は動作しますが、PR カードに CI やマージ状態は表示されません。
### 3. データベースを更新して接続する
@@ -185,10 +187,10 @@ API サービスを再起動し、**設定 → GitHub** から接続します。
- **PR が紐づかない**: リポジトリが App の許可範囲にあること、PR の自動紐づけが有効であること、番号が現在のワークスペースのものであること、誰かがタスクから外していないかを確認します。
- **本文に番号を書いても紐づかない**: `Closes MUL-123` を使うか、番号をブランチ名または PR タイトルに入れるか、手動で紐づけます。
- **CI の状態がない**: `GITHUB_APP_ID` と `GITHUB_APP_PRIVATE_KEY` が設定済みで、App に Contents、Checks、Commit statuses の read-only 権限があり、関連イベントを購読していることを確認します。Contents が欠けるとスナップショット全体が失敗し、PR カードには CI もマージ状態も表示されません。インストール済み App に権限を追加した場合は、各 installation の所有者が GitHub 上で承認するまで有効になりません。
-- **PR のマージ後もタスクが完了しない**: タスクの **Pull requests** リストの下にある説明を確認します。closing keyword を使った PR がないこと、まだマージされていない PR やマージされずにクローズされた PR、またはタスクやワークスペースで自動完了がオフになっていることが表示されます。
+- **PR のマージ後もタスクのステータスが変わらない**: タスクの **Pull requests** リストの下にある説明を確認します。まだマージされていない PR やマージされずにクローズされた PR、またはこのタスクが PR マージでステータスを変えない設定であることが表示されます。説明がない場合は、ワークスペースが **変更しない** に設定されているか、タスクがすでに変更先のステータスです。
## 次のステップ
-- [タスク](/issues) — 状態遷移と PR マージによる Done への変更
+- [タスク](/issues) — 状態遷移と PR マージの関係
- [プロジェクトリソース](/project-resources) — エージェントが実行時に使えるリポジトリ
- [環境変数](/environment-variables) — セルフホスト GitHub App の全設定
diff --git a/apps/docs/content/docs/github-integration.ko.mdx b/apps/docs/content/docs/github-integration.ko.mdx
index 17ca53e300..7fc4936402 100644
--- a/apps/docs/content/docs/github-integration.ko.mdx
+++ b/apps/docs/content/docs/github-integration.ko.mdx
@@ -9,7 +9,7 @@ GitHub를 연결하면 Multica가 태스크 번호를 기준으로 pull request
GitHub 연동은 설치할 때 승인한 저장소만 읽으며 코드, 댓글, status check를 제출하지 않습니다.
-자체 배포한 Multica에서는 자체 호스팅 Forgejo, Gitea, GitLab 인스턴스도 동시에 연결해 동일한 PR 자동 연결, merge 시 Done 전환, CI 표시 기능을 사용할 수 있습니다. **설정 → 연동 → Git 코드 호스팅**에서 연결하며 자세한 내용은 [자체 호스팅 Git 코드 호스팅](/vcs-integration)을 참고하세요. Multica Cloud에는 이 메뉴가 없습니다.
+자체 배포한 Multica에서는 자체 호스팅 Forgejo, Gitea, GitLab 인스턴스도 동시에 연결해 동일한 PR 자동 연결, merge 시 상태 변경, CI 표시 기능을 사용할 수 있습니다. **설정 → 연동 → Git 코드 호스팅**에서 연결하며 자세한 내용은 [자체 호스팅 Git 코드 호스팅](/vcs-integration)을 참고하세요. Multica Cloud에는 이 메뉴가 없습니다.
## GitHub 연결
@@ -29,14 +29,15 @@ GitHub 연동은 설치할 때 승인한 저장소만 읽으며 코드, 댓글,
## 기능 스위치
-**설정 → GitHub**에는 네 가지 스위치가 있습니다.
+**설정 → GitHub**에는 다음 설정이 있습니다.
-| 스위치 | 역할 |
+| 설정 | 역할 |
|---|---|
| GitHub 연동 | 전체 스위치입니다. 끄면 아래 세 기능이 작동하지 않지만 GitHub App 연결은 해제되지 않습니다. |
| PR 사이드바 | 태스크 상세 화면에 연결된 pull request를 표시합니다. |
| Co-authored-by | 에이전트가 만든 commit에 `Co-authored-by: multica-agent <[email protected]>`를 추가합니다. |
| PR 자동 연결 | 브랜치 이름이나 제목에 태스크 번호가 있거나, 본문에서 closing keyword 바로 뒤에 태스크 번호를 쓴 PR을 해당 태스크에 연결합니다. |
+| PR 병합 후 태스크 상태 | 태스크에 연결된 PR이 모두 병합되면 태스크를 특정 상태(기본값 `Done`)로 바꿀지, 바꾸지 않을지 정합니다. 아래 **PR 병합 후 상태 변경**을 참고하세요. |
| **PR 카드 → CI와 머지 가능 여부** | 연결된 각 PR에 대해 Multica는 인증된 GitHub API 스냅샷을 가져와, 그 **CI 상태**와 **머지 가능 여부**를 카드에 미러링합니다(아래 **PR 카드에 표시되는 것** 참조). |
@@ -78,23 +79,24 @@ Resolves MUL-123
CI 상태와 merge 가능 여부는 Multica가 GitHub API에서 가져온 snapshot이며 서로 독립적입니다. 이미 merge되거나 닫힌 PR에는 두 항목을 더 이상 표시하지 않습니다. GitHub를 일시적으로 사용할 수 없으면 카드가 비워지는 대신 마지막 snapshot을 유지하고 만료된 정보라고 표시합니다.
-목록 아래에는 다음에 일어날 일을 한 줄로 보여 줍니다. 예를 들어 "#19 병합 시 자동 완료", `Closes MUL-123`을 쓴 PR이 없다는 안내, 병합되지 않고 닫힌 PR입니다.
+목록 아래에는 다음에 일어날 일을 한 줄로 보여 줍니다. 예를 들어 "#19 병합 시 완료(으)로 변경"이나 병합되지 않고 닫힌 PR입니다. 워크스페이스가 "변경하지 않음"으로 설정되어 있거나 태스크가 이미 대상 상태이면 표시되지 않습니다.
항목을 클릭하면 GitHub의 PR이 열립니다. **PR 사이드바**를 꺼도 이 영역만 숨겨질 뿐 연결은 해제되지 않습니다.
-## PR merge 시 Done 전환 조건
+## PR 병합 후 상태 변경
-PR이 merge되었다고 해서 태스크가 반드시 끝난 것은 아닙니다. **PR 병합 시 태스크 자동 완료**(**설정 → 태스크 상태 → 자동화**, 기본값 켜짐)가 켜져 있을 때, Multica는 다음 조건을 모두 만족할 때만 태스크를 `Done`으로 바꿉니다.
+PR이 merge되었다고 해서 태스크가 반드시 끝난 것은 아닙니다. 그래서 merge 후에 무엇을 할지는 워크스페이스가 정합니다: **설정 → 연동 → GitHub → PR 병합 후 태스크 상태**. `Done`(새 워크스페이스의 기본값), 다른 "시작됨" 또는 "완료" 카테고리의 상태("회귀 테스트 대기" 같은 사용자 지정 상태도 가능), 또는 **변경하지 않음**을 고를 수 있습니다. 이 설정이 생기기 전부터 있던 워크스페이스는 기존 동작을 유지합니다. merge해도 태스크가 항상 완료되지는 않았다면 초기값은 **변경하지 않음**입니다.
-1. merge된 연결 PR 중 적어도 하나가 제목이나 본문에서 `Closes MUL-123`처럼 closing keyword 바로 뒤에 태스크 번호를 썼습니다. `Closes login MUL-123`처럼 중간에 다른 단어가 있거나 브랜치 이름에만 있는 경우는 해당하지 않습니다.
-2. 태스크에 연결된 PR이 모두 `Merged` 상태입니다. `Open`이나 `Draft` PR이 남아 있으면 태스크는 계속 기다립니다. merge되지 않고 닫힌 PR도 태스크에서 제거할 때까지 마찬가지입니다.
-3. 태스크가 `done` 또는 `cancelled`가 아니고, 이 태스크만 자동 완료를 끄지 않았습니다(**Pull requests → ⋯ → 이 태스크는 자동 완료하지 않음**).
+다음 조건을 모두 만족하면 태스크가 선택한 상태로 바뀝니다.
-따라서 브랜치 이름이나 제목에만 `MUL-123`을 쓰면 연결은 되지만 그것만으로 태스크가 완료되지는 않습니다. merge와 함께 태스크를 끝내고 싶을 때만 closing keyword를 사용하세요. closing keyword는 merge 시점 기준으로 판단합니다. merge 후에 추가하면 연결만 되고 태스크는 완료되지 않습니다.
+1. 태스크에 연결된 PR이 모두 `Merged` 상태입니다. `Open`이나 `Draft` PR이 남아 있으면 태스크는 계속 기다립니다. merge되지 않고 닫힌 PR도 태스크에서 제거할 때까지 마찬가지입니다.
+2. 태스크가 `done` 또는 `cancelled`가 아니고, Triage 중이 아니며, 이미 대상 상태가 아니고, 이 태스크만 상태 변경을 끄지 않았습니다(**Pull requests → ⋯ → PR 병합 후에도 상태 유지**).
-판단은 PR 이벤트가 태스크에 닿을 때만 이루어집니다. 연결된 PR의 merge, 연결 추가, 연결 제거입니다. 태스크를 다시 열어도 `Done`으로 돌아가지 않으며, 다음에 연결된 PR이 merge될 때 완료됩니다. 설정을 켜도 이전에 merge된 태스크를 소급해 완료하지 않습니다.
+PR을 어떻게 연결했는지는 결과에 영향을 주지 않습니다. 제목, 브랜치 이름, 본문의 `Closes MUL-123`은 모두 연결만 하고, merge 후 동작을 정하지 않습니다. PR이 태스크의 일부만 전달하거나 merge 후에 릴리스나 확인이 필요하면 그 태스크의 **Pull requests** 메뉴에서 상태를 유지하도록 설정하세요.
-상태 변경은 관련 PR을 적은 시스템 작업으로 타임라인에 기록되고 해당 태스크 구독자에게 알림이 전달됩니다. 이 설정은 [자체 호스팅 Git 코드 호스팅](/vcs-integration)을 포함한 모든 코드 호스트에 공통으로 적용됩니다.
+판단은 PR 이벤트가 태스크에 닿을 때만 이루어집니다. 연결된 PR의 merge, 연결 추가, 연결 제거입니다. 태스크를 다시 열어도 원래대로 돌아가지 않으며, 다음에 연결된 PR이 merge될 때 바뀝니다. 설정을 바꿔도 이전에 merge된 태스크에는 영향을 주지 않습니다.
+
+상태 변경은 관련 PR을 적은 시스템 작업으로 타임라인에 기록되고 해당 태스크 구독자에게 알림이 전달됩니다. 이 설정은 [자체 호스팅 Git 코드 호스팅](/vcs-integration)을 포함한 모든 코드 호스트에 공통으로 적용되며, 그 페이지에도 같은 설정이 표시됩니다.
## 여러 워크스페이스
@@ -166,7 +168,7 @@ GITHUB_APP_ID=<GitHub App 숫자 ID>
GITHUB_APP_PRIVATE_KEY=<BEGIN/END 줄과 줄바꿈을 유지한 전체 PEM private key>
```
-Private key는 GitHub App의 **Private keys → Generate a private key**에서 생성합니다. 설정하지 않으면 연동 기능이 자연스럽게 축소됩니다. PR은 계속 미러링되고 태스크 자동 연결과 merge 시 Done 전환도 정상적으로 작동하지만 PR 카드에 CI 또는 merge 상태가 표시되지 않습니다.
+Private key는 GitHub App의 **Private keys → Generate a private key**에서 생성합니다. 설정하지 않으면 연동 기능이 자연스럽게 축소됩니다. PR은 계속 미러링되고 태스크 자동 연결과 merge 시 상태 변경도 정상적으로 작동하지만 PR 카드에 CI 또는 merge 상태가 표시되지 않습니다.
### 3. 데이터베이스 업데이트 및 연결
@@ -185,10 +187,10 @@ API 서비스를 다시 시작한 뒤 **설정 → GitHub**에서 연결을 완
- **PR이 연결되지 않음**: 저장소가 App 승인 범위에 있는지, 자동 연결이 켜져 있는지, 번호가 현재 워크스페이스에 속하는지, 누군가 태스크에서 PR을 제거하지 않았는지 확인합니다.
- **본문에 번호를 썼는데 연결되지 않음**: `Closes MUL-123`을 사용하거나, 번호를 브랜치 이름이나 PR 제목에 넣거나, 직접 연결합니다.
- **CI 상태가 없음**: `GITHUB_APP_ID`와 `GITHUB_APP_PRIVATE_KEY`가 설정되었는지, App에 Contents, Checks 및 Commit statuses 읽기 권한이 있고 관련 이벤트를 구독했는지 확인합니다. Contents가 없으면 snapshot 전체가 실패해 PR 카드에 CI도 머지 상태도 표시되지 않습니다. 설치된 App에 권한을 추가한 뒤에는 각 installation owner가 GitHub에서 승인해야 적용됩니다.
-- **PR merge 후 태스크가 완료되지 않음**: 태스크의 **Pull requests** 목록 아래 설명을 확인합니다. closing keyword를 쓴 PR이 없는지, 아직 merge되지 않았거나 merge 없이 닫힌 PR이 있는지, 또는 태스크나 워크스페이스에서 자동 완료가 꺼져 있는지 알려 줍니다.
+- **PR merge 후 태스크 상태가 바뀌지 않음**: 태스크의 **Pull requests** 목록 아래 설명을 확인합니다. 아직 merge되지 않았거나 merge 없이 닫힌 PR이 있는지, 또는 이 태스크가 PR 병합 후에도 상태를 유지하도록 설정되어 있는지 알려 줍니다. 설명이 없으면 워크스페이스가 **변경하지 않음**으로 설정되어 있거나 태스크가 이미 대상 상태입니다.
## 다음 단계
-- [태스크](/issues) — 상태 전환과 PR merge 시 Done 전환의 관계를 알아봅니다.
+- [태스크](/issues) — 상태 전환과 PR merge의 관계를 알아봅니다.
- [프로젝트 리소스](/project-resources) — 에이전트 실행에서 사용할 저장소를 정합니다.
- [환경 변수](/environment-variables) — 자체 호스팅 GitHub App의 전체 설정을 확인합니다.
diff --git a/apps/docs/content/docs/github-integration.mdx b/apps/docs/content/docs/github-integration.mdx
index e943756116..c6e514ab4b 100644
--- a/apps/docs/content/docs/github-integration.mdx
+++ b/apps/docs/content/docs/github-integration.mdx
@@ -9,7 +9,7 @@ Once GitHub is connected, Multica automatically links pull requests based on iss
The GitHub integration only reads the repositories authorized at install time; it never pushes commits, comments, or status checks.
-Self-hosted Multica can also connect self-hosted Forgejo, Gitea, or GitLab instances in parallel, with the same PR auto-linking, merge-to-Done, and CI display. The entry point is **Settings → Integrations → Git hosting**; see [Self-hosted Git hosting](/vcs-integration). Multica Cloud does not offer this entry point.
+Self-hosted Multica can also connect self-hosted Forgejo, Gitea, or GitLab instances in parallel, with the same PR auto-linking, merge-driven status changes, and CI display. The entry point is **Settings → Integrations → Git hosting**; see [Self-hosted Git hosting](/vcs-integration). Multica Cloud does not offer this entry point.
## Connect GitHub
@@ -29,7 +29,7 @@ The **GitHub connection** decides which repositories Multica receives PR events
## Feature switches
-**Settings → GitHub** has four switches:
+**Settings → GitHub** has these settings:
| Switch | Effect |
|---|---|
@@ -37,11 +37,12 @@ The **GitHub connection** decides which repositories Multica receives PR events
| 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 | Links a PR to the issue whose identifier is in its branch name or title, or follows a closing keyword in its body. |
+| After PRs merge, move the issue to | What merging every PR linked to an issue does: move it to a status (`Done` by default) or leave it alone. See [When merged PRs move an issue](#when-merged-prs-move-an-issue). |
| **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).
+**After PRs merge, move the issue to** applies to every code host, including [self-hosted Git hosting](/vcs-integration), whose page shows the same setting.
## Link a PR to an issue
@@ -81,21 +82,22 @@ Once linked, PRs appear in the **Pull requests** block of issue detail. Each ent
CI 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*, that no PR says `Closes MUL-123`, or which PR closed without merging.
+Under the list, one line says what happens next — for example *Moves to Done when #19 merges*, or which PR closed without merging. There's no line when the workspace leaves status alone or the issue already has the target status.
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
+## When merged PRs move an issue
-A merged PR doesn't necessarily mean the issue is finished. With **Complete issues when their PRs merge** on (the default), an issue moves to `Done` only when all of the following hold:
+A merged PR doesn't necessarily mean the issue is finished, so the workspace decides what a merge does: **Settings → Integrations → GitHub → After PRs merge, move the issue to**. Pick `Done` (the default for new workspaces), another started or done status — a custom one such as *Awaiting regression* works too — or **Don't change**. Workspaces that existed before this setting keep their behavior: if merging didn't always complete their issues, they start on **Don't change**.
-1. at least one merged linked PR puts a closing keyword right before the identifier in its title or body, such as `Closes MUL-123` (forms with words in between, like `Closes login MUL-123`, don't count, and neither does a branch name);
-2. every linked PR is `Merged` — an `Open` or `Draft` PR keeps the issue waiting, and so does a PR closed without merging until you remove it from the issue;
-3. the issue isn't `done` or `cancelled`, and auto-complete hasn't been turned off for it (**Pull requests → ⋯ → Turn off auto-complete**).
+An issue moves to the chosen status when all of the following hold:
-So writing `MUL-123` only in the branch name or title links the PR but doesn't complete the issue by itself — use a closing keyword only when merging the PR should finish the issue. The keyword counts as of the merge: adding it to a PR that has already merged links the PR but doesn't complete the issue.
+1. every linked PR is `Merged` — an `Open` or `Draft` PR keeps the issue waiting, and so does a PR closed without merging until you remove it from the issue;
+2. the issue isn't `done` or `cancelled`, isn't in Triage, doesn't already have the target status, and hasn't been switched off for this issue (**Pull requests → ⋯ → Keep status when PRs merge**).
-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.
+How a PR was linked doesn't matter: the title, the branch name and a `Closes MUL-123` in the body all link it, and none of them changes what the merge does. When a PR delivers only part of the issue, or a release or a check has to follow the merge, keep that issue's status from its **Pull requests** menu.
+
+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 move it back — the next linked PR that merges does. Changing the setting doesn't move issues whose PRs merged earlier.
The status change is written to the timeline as a system action naming the PRs, and members subscribed to the issue are notified.
@@ -169,7 +171,7 @@ GITHUB_APP_ID=<the GitHub App's numeric ID>
GITHUB_APP_PRIVATE_KEY=<full PEM private key, keeping the BEGIN/END lines and newlines>
```
-Generate the private key under the GitHub App's **Private keys → Generate a private key**. Without them the integration degrades gracefully: PRs still mirror, issues still auto-link and move to Done on merge — the PR card just shows no CI or merge state.
+Generate the private key under the GitHub App's **Private keys → Generate a private key**. Without them the integration degrades gracefully: PRs still mirror, issues still auto-link and move on merge — the PR card just shows no CI or merge state.
### 3. Update the database and connect
@@ -188,10 +190,10 @@ Restart the API server, then complete the connection in **Settings → GitHub**.
- **PR not linked**: check that the repository is in the App's authorized scope, auto-linking is on, the identifier belongs to the current workspace, and nobody removed the PR from the issue.
- **Identifier in the body but not linked**: put it right after a closing keyword (`Closes MUL-123`), or in the branch name or PR title, or link the PR by hand.
- **No CI status**: confirm `GITHUB_APP_ID` and `GITHUB_APP_PRIVATE_KEY` are configured, and that the App has read-only Contents, Checks, and Commit statuses permissions with the matching events subscribed. Without Contents the whole snapshot fails, so the PR card shows neither CI nor merge state. After adding permissions to an installed App, each installation's owner must also approve them on GitHub before they take effect.
-- **Issue not completed after the PR merged**: read the line under the issue's **Pull requests** list. It says when no PR used a closing keyword, names any PR still open or closed without merging, or says auto-complete is off for the issue or the workspace.
+- **Issue didn't move after the PR merged**: read the line under the issue's **Pull requests** list. It names any PR still open or closed without merging, or says the issue keeps its status when PRs merge. No line means the workspace setting is **Don't change**, or the issue already has the target status.
## Next steps
-- [Issues](/issues) — how status transitions relate to merge-to-Done.
+- [Issues](/issues) — how status transitions relate to merged PRs.
- [Project resources](/project-resources) — which repositories agents use when running.
- [Environment variables](/environment-variables) — the full self-hosted GitHub App configuration.
diff --git a/apps/docs/content/docs/github-integration.zh.mdx b/apps/docs/content/docs/github-integration.zh.mdx
index e15bcdb221..77cac267be 100644
--- a/apps/docs/content/docs/github-integration.zh.mdx
+++ b/apps/docs/content/docs/github-integration.zh.mdx
@@ -9,7 +9,7 @@ import { Callout } from "fumadocs-ui/components/callout";
GitHub 集成只读取安装时授权的仓库,不会提交代码、评论或 status check。
-自部署的 Multica 还可以并行连接自托管的 Forgejo、Gitea 或 GitLab 实例,获得同样的 PR 自动关联、合并转 Done 和 CI 展示,入口在 **设置 → 集成 → Git 代码托管**,详见[自托管 Git 代码托管](/vcs-integration)。Multica Cloud 不提供该入口。
+自部署的 Multica 还可以并行连接自托管的 Forgejo、Gitea 或 GitLab 实例,获得同样的 PR 自动关联、合并后改状态和 CI 展示,入口在 **设置 → 集成 → Git 代码托管**,详见[自托管 Git 代码托管](/vcs-integration)。Multica Cloud 不提供该入口。
## 连接 GitHub
@@ -29,19 +29,20 @@ GitHub 集成只读取安装时授权的仓库,不会提交代码、评论或
## 功能开关
-**设置 → GitHub** 中有四个开关:
+**设置 → GitHub** 中有以下设置:
-| 开关 | 作用 |
+| 设置 | 作用 |
|---|---|
| GitHub 集成 | 总开关。关闭后,下面三项不再生效,但不会断开 GitHub App。 |
| PR 侧栏 | 在任务详情中显示关联的 pull request。 |
| Co-authored-by | 在智能体创建的 commit 中加入 `Co-authored-by: multica-agent <[email protected]>`。 |
| 自动关联 PR | 分支名或标题含任务编号、或正文中关闭语句后写了任务编号的 PR,会关联到对应任务。 |
+| PR 合并后,任务状态改为 | 任务关联的 PR 全部合并后,把任务改成某个状态(默认 `Done`),或者不改。见下方 **PR 合并后怎样改状态**。 |
| **PR 卡片 → CI 与可合并性** | 对每个关联的 PR,Multica 从 GitHub API 拉取一份经鉴权的快照,把它的 **CI 状态**和**可合并性**镜像到卡片上(见下方 **PR 卡片展示什么**)。 |
-PR 合并后是否自动完成任务,是另一项工作区设置:**设置 → 任务状态 → 自动化 → PR 合并后自动完成任务**。它对所有代码托管平台生效,包括[自托管 Git 代码托管](/vcs-integration)。
+**PR 合并后,任务状态改为** 对所有代码托管平台生效,包括[自托管 Git 代码托管](/vcs-integration),那个页面显示的是同一项设置。
## 让 PR 关联到任务
@@ -81,21 +82,22 @@ Resolves MUL-123
CI 状态和可合并性来自 Multica 从 GitHub API 拉取的快照,两者互相独立;已合并或已关闭的 PR 不再显示这两项。GitHub 暂时不可用时,卡片会保留上一次的快照并标记为过期,而不是清空。
-列表下方有一行说明接下来会发生什么,例如「等待 #19 合并后自动完成」、没有 PR 写 `Closes MUL-123`,或者哪个 PR 已关闭、未合并。
+列表下方有一行说明接下来会发生什么,例如「等待 #19 合并后改为 已完成」,或者哪个 PR 已关闭、未合并。工作区设置为不改变、或者任务已经是目标状态时,不显示这行说明。
点击记录可以打开 GitHub 上的 PR。关闭 **PR 侧栏** 只会隐藏这个区块,不会断开连接。
-## PR 合并转 Done 的条件
+## PR 合并后怎样改状态
-PR 合并不一定代表任务已完成。开启 **PR 合并后自动完成任务**(默认开启)时,只有以下条件同时成立,任务才会改为 `Done`:
+PR 合并不一定代表任务已完成,所以由工作区决定合并后做什么:**设置 → 集成 → GitHub → PR 合并后,任务状态改为**。可以选 `Done`(新工作区的默认值)、其他"已开始"或"已完成"类的状态(自定义状态也可以,例如「待回归」),或者**不改变**。这项设置出现之前就已存在的工作区保持原来的行为:如果以前的合并并不总会完成任务,初始值就是**不改变**。
-1. 至少一个已合并的关联 PR 在标题或正文中使用了紧跟编号的关闭语句,例如 `Closes MUL-123`(`Closes login MUL-123` 这类中间隔词的写法不生效,分支名也不算);
-2. 所有关联 PR 都是 `Merged`。仍为 `Open` 或 `Draft` 的 PR 会让任务继续等待;关闭但未合并的 PR 也一样,直到你把它从任务上移除;
-3. 任务当前不是 `done` 或 `cancelled`,也没有单独关闭自动完成(**Pull requests → ⋯ → 此任务不自动完成**)。
+以下条件同时成立时,任务会改为选定的状态:
-因此,仅在分支名或标题中写 `MUL-123` 会建立关联,但不会单独触发完成;只有希望 PR 合并即完成任务时,才使用关闭语句。关闭语句以合并时为准:PR 合并后再补写,只会建立关联,不会完成任务。
+1. 所有关联 PR 都是 `Merged`。仍为 `Open` 或 `Draft` 的 PR 会让任务继续等待;关闭但未合并的 PR 也一样,直到你把它从任务上移除;
+2. 任务当前不是 `done` 或 `cancelled`,不在 Triage 中,还不是目标状态,也没有单独设置合并后不改状态(**Pull requests → ⋯ → 此任务合并后不改状态**)。
-只有 PR 事件会触发判断:关联 PR 合并、新增关联或移除关联。重新打开任务后,它不会被改回 `Done`,下一个关联 PR 合并时才会。开启这项设置,也不会补完成此前已合并的任务。
+PR 怎么关联的不影响结果:标题、分支名和正文里的 `Closes MUL-123` 都只负责关联,不决定合并后做什么。如果一个 PR 只交付了任务的一部分,或者合并后还要发布、验证,就在这个任务的 **Pull requests** 菜单里设置合并后不改状态。
+
+只有 PR 事件会触发判断:关联 PR 合并、新增关联或移除关联。重新打开任务后,它不会被改回去,下一个关联 PR 合并时才会。修改这项设置,也不会改动此前已合并的任务。
状态变化会以系统操作写入时间线并列出相关 PR,订阅该任务的成员会收到通知。
@@ -169,7 +171,7 @@ GITHUB_APP_ID=<GitHub App 的数字 ID>
GITHUB_APP_PRIVATE_KEY=<完整 PEM 私钥,保留 BEGIN/END 行和换行>
```
-私钥在 GitHub App 的 **Private keys → Generate a private key** 中生成。不配置时集成会平稳降级:PR 照常镜像,任务照常自动关联并在合并时转 Done,只是 PR 卡片不显示 CI 或合并状态。
+私钥在 GitHub App 的 **Private keys → Generate a private key** 中生成。不配置时集成会平稳降级:PR 照常镜像,任务照常自动关联并在合并时改状态,只是 PR 卡片不显示 CI 或合并状态。
### 3. 更新数据库并连接
@@ -188,10 +190,10 @@ make migrate-up
- **PR 没有关联**:检查仓库是否在 App 授权范围内、自动关联是否开启、编号是否属于当前工作区,以及是否有人把它从任务上移除过。
- **正文写了编号但没关联**:改用 `Closes MUL-123`,或把编号放到分支名、PR 标题中,或者手动关联。
- **没有 CI 状态**:确认 `GITHUB_APP_ID` 和 `GITHUB_APP_PRIVATE_KEY` 已配置,App 具有 Contents、Checks 与 Commit statuses 的只读权限并订阅了对应事件。缺少 Contents 会让整个快照失败,PR 卡片既没有 CI 也没有合并状态。给已安装的 App 补加权限后,还需要各 installation 的所有者在 GitHub 上批准才会生效。
-- **PR 合并后任务没完成**:看任务 **Pull requests** 列表下方的说明,它会指出没有 PR 使用关闭语句、仍未合并或已关闭未合并的 PR,或者说明任务、工作区关闭了自动完成。
+- **PR 合并后任务状态没变**:看任务 **Pull requests** 列表下方的说明,它会指出仍未合并或已关闭未合并的 PR,或者说明此任务合并后不改状态。没有这行说明,表示工作区设置为**不改变**,或者任务已经是目标状态。
## 接下来
-- [任务](/issues) — 状态流转与 PR 合并转 Done 的关系。
+- [任务](/issues) — 状态流转与 PR 合并的关系。
- [项目资源](/project-resources) — 智能体执行时使用哪些仓库。
- [环境变量](/environment-variables) — 自托管 GitHub App 的完整配置。
diff --git a/apps/docs/content/docs/issues.ja.mdx b/apps/docs/content/docs/issues.ja.mdx
index 51b4eae861..85d5610493 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` は通常、人による確認か、`Closes MUL-123` のような closing keyword を含む紐づき PR のマージによって設定されます。
+エージェントは、作業がタスクに与えた実際の変化をそのままステータスに書き込みます。タスクが求めているもの(コードでも、調査でも、設計でも、タスク自身が求めるレビューでも)を作り始めた時点で `in_progress` に進め、実行中からボードに反映させます。納品したら `in_review` に進め、ターンを越えて作業が続く場合は `in_progress` のままにします。そのタスク自身の成果物を生まないターン(質問への回答、他所が持つ作業への助言)では、最初から最後までステータスを変更しません。これらの変更は、実行中にエージェントが Multica CLI から明示的に書き込むものです。実行の開始や完了でサーバーがタスクのステータスを切り替えることはありません(下記の 2 つのシステム例外を除く)。`done` は通常、人による確認か、ワークスペースがマージ後の変更先を `done` にしている場合の紐づき PR のマージによって設定されます。
<Callout type="info">
次の 2 つの変更はシステムが行います。
- 実行が失敗し、そのタスクにほかの実行がなく、リトライも起動しなかった場合、`in_progress` は `todo` に戻ります。
-- タスクに紐づく PR がすべてマージされ、そのうち 1 つが `Closes MUL-123` のような closing keyword を含む場合、タスクは `done` になります。ワークスペースまたはそのタスクで PR による自動完了がオフの場合を除きます。詳しくは [GitHub 連携](/github-integration)を参照してください。
+- タスクに紐づく PR がすべてマージされると、タスクはワークスペースが選んだステータス(既定は `done`)に変わります。ワークスペースが「変更しない」に設定している場合や、そのタスクだけ変更をオフにしている場合を除きます。詳しくは [GitHub 連携](/github-integration)を参照してください。
</Callout>
### カスタムステータス
diff --git a/apps/docs/content/docs/issues.ko.mdx b/apps/docs/content/docs/issues.ko.mdx
index 3107d9bf42..a31928105e 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`은 보통 사람의 확인이나, `Closes MUL-123` 같은 closing keyword가 있는 연결 PR의 병합으로 지정됩니다.
+에이전트는 작업이 태스크에 실제로 일으킨 변화를 그대로 상태에 기록합니다. 태스크가 요구하는 것을 만들기 시작하면, 그것이 코드든 조사든 설계든 태스크 자체가 요청한 리뷰든 바로 `in_progress`로 옮겨 실행 중에도 보드에 드러나게 합니다. 전달하면 `in_review`로 옮기고, 작업이 이번 턴을 넘어 이어지면 `in_progress`로 유지합니다. 그 태스크 자체의 결과물을 만들지 않는 턴, 예를 들어 질문에 답하거나 다른 곳이 소유한 작업에 조언하는 경우에는 처음부터 끝까지 상태를 바꾸지 않습니다. 이 변경은 실행 중에 에이전트가 Multica CLI로 명시적으로 기록하는 것입니다. 실행이 시작되거나 끝날 때 서버가 태스크 상태를 바꾸지는 않습니다(아래 두 가지 시스템 예외 제외). `done`은 보통 사람의 확인이나, 워크스페이스가 병합 후 대상 상태를 `done`으로 정한 경우 연결 PR의 병합으로 지정됩니다.
<Callout type="info">
다음 두 가지 변경은 시스템이 수행합니다.
- 실행이 실패하고 해당 태스크에 다른 실행이 없으며 재시도도 트리거되지 않으면 `in_progress`가 `todo`로 돌아갑니다.
-- 태스크에 연결된 PR이 모두 병합되고 그중 하나에 `Closes MUL-123` 같은 closing keyword가 있으면 태스크가 `done`으로 바뀝니다. 워크스페이스나 해당 태스크에서 PR 자동 완료를 끈 경우는 제외합니다. 자세한 내용은 [GitHub 연동](/github-integration)을 참고하세요.
+- 태스크에 연결된 PR이 모두 병합되면 태스크가 워크스페이스가 정한 상태(기본값 `done`)로 바뀝니다. 워크스페이스가 "변경하지 않음"으로 설정했거나 해당 태스크만 상태 변경을 끈 경우는 제외합니다. 자세한 내용은 [GitHub 연동](/github-integration)을 참고하세요.
</Callout>
### 사용자 지정 상태
diff --git a/apps/docs/content/docs/issues.mdx b/apps/docs/content/docs/issues.mdx
index cd4e690e93..3d4ddcc4fd 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 sorting
There 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 the merge of a linked PR that closes the issue with a keyword such as `Closes MUL-123`.
+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 the issue's linked PRs when the workspace moves merged issues to `done`.
<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 every PR linked to the issue is merged and one of them closes it with a keyword such as `Closes MUL-123`, the issue becomes `done` — unless PR auto-complete is off for the workspace or the issue. See [GitHub integration](/github-integration).
+- When every PR linked to the issue is merged, the issue moves to the status the workspace chose (`done` by default) — unless the workspace leaves status alone or the issue is switched off. See [GitHub integration](/github-integration#when-merged-prs-move-an-issue).
</Callout>
### Custom statuses
diff --git a/apps/docs/content/docs/issues.zh.mdx b/apps/docs/content/docs/issues.zh.mdx
index 5ea6155f2a..4005985518 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` 通常留给人工确认,或由带关闭语句(例如 `Closes MUL-123`)的关联 PR 合并后由系统完成。
+智能体随着工作对任务的实际影响写入状态:开始产出任务本身要求的东西时立刻推到 `in_progress`——不论形式是代码、调研、设计,还是任务本身要求的 review——让看板在工作进行中就能反映出来;交付后推到 `in_review`;工作跨轮继续则保持 `in_progress`;没有产出本任务交付物的轮次(答疑、给别处的工作做咨询)则全程不改状态。这些状态变更由智能体在运行中通过 Multica CLI 显式写入——运行开始或完成时,服务端不会自动改任务状态(下面两个系统例外除外)。`done` 通常留给人工确认,或在工作区设置合并后改为 `done` 时,由关联 PR 全部合并后系统写入。
<Callout type="info">
两个变化由系统执行:
- 执行失败,且该任务没有其他执行、也没有触发重试时,`in_progress` 回到 `todo`。
-- 任务的所有关联 PR 都合并、且其中有 PR 使用了关闭语句(例如 `Closes MUL-123`)时,任务变为 `done`,除非工作区或该任务关闭了 PR 自动完成。详见 [GitHub 集成](/github-integration)。
+- 任务的所有关联 PR 都合并时,任务改为工作区选定的状态(默认 `done`),除非工作区设置为不改变,或该任务设置了合并后不改状态。详见 [GitHub 集成](/github-integration)。
</Callout>
### 自定义状态
diff --git a/apps/docs/content/docs/vcs-integration.fr.mdx b/apps/docs/content/docs/vcs-integration.fr.mdx
index b3aa5d2ca9..3278a7b541 100644
--- a/apps/docs/content/docs/vcs-integration.fr.mdx
+++ b/apps/docs/content/docs/vcs-integration.fr.mdx
@@ -1,6 +1,6 @@
---
title: Fournisseurs Git auto-hébergés
-description: Connectez une instance Forgejo, Gitea ou GitLab auto-hébergée par espace de travail, afin que les pull/merge requests portant un identifiant de tâche dans leur nom de branche ou leur titre, ou après un mot-clé de clôture dans leur description, soient automatiquement associées à cette tâche, la fassent passer à Terminé à la fusion et affichent le statut CI.
+description: Connectez une instance Forgejo, Gitea ou GitLab auto-hébergée par espace de travail, afin que les pull/merge requests portant un identifiant de tâche dans leur nom de branche ou leur titre, ou après un mot-clé de clôture dans leur description, soient automatiquement associées à cette tâche, la fassent passer au statut choisi par l'espace de travail à la fusion et affichent le statut CI.
---
import { Callout } from "fumadocs-ui/components/callout";
@@ -14,7 +14,7 @@ une instance Git sur votre propre réseau. Un opérateur du serveur doit l'activ
la section n'apparaît pas dans Paramètres → Intégrations.
</Callout>
-Multica se connecte à un fournisseur Git auto-hébergé par espace de travail : **Forgejo**, **Gitea** ou **GitLab**. Une fois la connexion établie, toute pull request (GitLab : merge request) dont le nom de branche ou le titre contient un identifiant de tâche (par exemple `MUL-123`), ou dont la description en cite un après un mot-clé de clôture (`Closes MUL-123`), est **associée automatiquement** à cette [tâche](/issues), apparaît sous **Pull requests** dans la barre latérale de la tâche et — lorsqu'elle est fusionnée avec un mot-clé de clôture — fait passer la tâche à **Terminé**. La CI du commit de tête s'affiche sous forme de barre de vérifications sur la carte.
+Multica se connecte à un fournisseur Git auto-hébergé par espace de travail : **Forgejo**, **Gitea** ou **GitLab**. Une fois la connexion établie, toute pull request (GitLab : merge request) dont le nom de branche ou le titre contient un identifiant de tâche (par exemple `MUL-123`), ou dont la description en cite un après un mot-clé de clôture (`Closes MUL-123`), est **associée automatiquement** à cette [tâche](/issues), apparaît sous **Pull requests** dans la barre latérale de la tâche et — une fois toutes les PR associées fusionnées — fait passer la tâche au statut choisi par l'espace de travail (**Terminé** par défaut). La CI du commit de tête s'affiche sous forme de barre de vérifications sur la carte.
Ces fournisseurs fonctionnent en parallèle de GitHub : un espace de travail peut les combiner librement.
@@ -87,7 +87,7 @@ Multica authentifie chaque livraison à l'aide du secret stocké : un webhook qu
## Ce qui est reflété
- **Pull requests / merge requests** — état ouvert, fermé, fusionné et brouillon, auteur, branche et (lorsque le fournisseur les fournit) statistiques de diff.
-- **Liens vers les tâches** — un identifiant dans le titre ou la branche associe la PR à la tâche, tout comme un identifiant placé après un mot-clé de clôture dans la description ; une simple mention dans la description n'associe rien. Un mot-clé de clôture (`Closes`/`Fixes`/`Resolves MUL-123`) sur une PR fusionnée fait passer la tâche à **Terminé** dès qu'aucune PR associée n'est encore ouverte.
+- **Liens vers les tâches** — un identifiant dans le titre ou la branche associe la PR à la tâche, tout comme un identifiant placé après un mot-clé de clôture dans la description ; une simple mention dans la description n'associe rien. Une fois toutes les PR associées fusionnées, la tâche passe au statut choisi par l'espace de travail, selon le même paramètre que [GitHub](/github-integration).
- **CI** — les statuts de commit Forgejo/Gitea et les pipelines GitLab sont agrégés dans une barre de vérifications réussie/en échec/en attente pour le commit de tête.
## Agents qui ouvrent des pull requests
diff --git a/apps/docs/content/docs/vcs-integration.ja.mdx b/apps/docs/content/docs/vcs-integration.ja.mdx
index 1b95e275c7..d4402dd9bd 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 を対応するタスクへ自動的に紐づけ、終了キーワードを含む PR のマージ時に「完了」へ移動して CI ステータスを表示します。
+description: ワークスペースごとにセルフホストの Forgejo、Gitea、GitLab インスタンスを接続し、ブランチ名かタイトルにタスク番号を含む、または本文で終了キーワードの直後にタスク番号を置いた Pull Request / Merge Request を対応するタスクへ自動的に紐づけ、マージ時にワークスペースが選んだステータスへ移動して 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 がすべてマージされ、そのうち 1 つが終了キーワードを含む場合、タスクは「完了」へ移動します。head commit の CI はカード上のチェックバーとして表示されます。
+Multica はワークスペースごとにセルフホストの Git ホスティング、**Forgejo**、**Gitea**、**GitLab** のいずれかへ接続します。接続後、ブランチ名かタイトルにタスク番号(例: `MUL-123`)を含む Pull Request(GitLab では Merge Request)、または本文で終了キーワードの直後にタスク番号を置いた PR は、対応する[タスク](/issues)へ**自動的に紐づけられ**、タスクサイドバーの **Pull requests** に表示されます。タスクに紐づく PR がすべてマージされると、タスクはワークスペースが選んだステータス(既定は「完了」)へ移動します。head commit の CI はカード上のチェックバーとして表示されます。
これらの Git ホスティングは GitHub と並行して利用でき、1 つのワークスペースで任意に組み合わせられます。
@@ -82,7 +82,7 @@ Multica は保存済みの secret で各 delivery を検証するため、一致
## ミラーされる内容
- **Pull / Merge Request** — open、closed、merged、draft の状態、作成者、ブランチ、および Git ホスティングが提供する場合は diff 統計。
-- **タスクの紐づけ** — タイトルまたはブランチの番号、および本文で終了キーワードの直後に置いた番号で PR をタスクへ紐づけます。本文中の通常の参照では紐づきません。タスクに紐づく PR(GitHub とセルフホストの両方)がすべてマージされ、そのうち 1 つが終了キーワード(`Closes`/`Fixes`/`Resolves MUL-123`)を含む場合、[GitHub](/github-integration) と同じワークスペース設定とルールに従ってタスクを「完了」へ移動します。
+- **タスクの紐づけ** — タイトルまたはブランチの番号、および本文で終了キーワードの直後に置いた番号で PR をタスクへ紐づけます。本文中の通常の参照では紐づきません。タスクに紐づく PR(GitHub とセルフホストの両方)がすべてマージされると、[GitHub](/github-integration) と同じ設定とルールに従って、ワークスペースが選んだステータスへタスクを移動します。プロバイダーを接続すると、このページにも同じ **PR マージ後のタスクのステータス** 設定が表示されます。
- **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.mdx
index c875762174..28f1190000 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를 해당 태스크에 자동 연결하고, 종료 키워드가 있는 PR이 merge되면 완료로 옮기며 CI 상태를 표시합니다.
+description: 워크스페이스마다 자체 호스팅 Forgejo, Gitea, GitLab 인스턴스를 연결해 브랜치 이름이나 제목에 태스크 번호가 있거나 본문의 종료 키워드 뒤에 태스크 번호가 있는 Pull Request / Merge Request를 해당 태스크에 자동 연결하고, 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`)가 포함되거나 본문의 종료 키워드 뒤에 태스크 번호(`Closes MUL-123`)가 있는 Pull Request(GitLab에서는 Merge Request)가 해당 [태스크](/issues)에 **자동으로 연결**되고 태스크 사이드바의 **Pull requests**에 표시됩니다. 태스크에 연결된 PR이 모두 merge되고 그중 하나에 종료 키워드가 있으면 태스크가 완료로 이동합니다. head commit의 CI는 카드에 check bar로 표시됩니다.
+Multica는 워크스페이스별로 자체 호스팅 Git 코드 호스팅인 **Forgejo**, **Gitea**, **GitLab** 중 하나에 연결합니다. 연결하면 브랜치 이름이나 제목에 태스크 번호(예: `MUL-123`)가 포함되거나 본문의 종료 키워드 뒤에 태스크 번호(`Closes MUL-123`)가 있는 Pull Request(GitLab에서는 Merge Request)가 해당 [태스크](/issues)에 **자동으로 연결**되고 태스크 사이드바의 **Pull requests**에 표시됩니다. 태스크에 연결된 PR이 모두 merge되면 태스크가 워크스페이스가 정한 상태(기본값 완료)로 이동합니다. head commit의 CI는 카드에 check bar로 표시됩니다.
이 코드 호스팅은 GitHub와 동시에 사용할 수 있으며 워크스페이스 하나에서 원하는 대로 조합할 수 있습니다.
@@ -82,7 +82,7 @@ Multica는 저장된 secret으로 모든 delivery를 검증하므로 일치하
## 미러링되는 내용
- **Pull / Merge Request** — open, closed, merged, draft 상태와 작성자, 브랜치, 그리고 코드 호스팅이 제공하는 경우 diff 통계.
-- **태스크 연결** — 제목이나 브랜치의 번호, 그리고 본문에서 종료 키워드 바로 뒤에 쓴 번호가 PR을 태스크에 연결합니다. 본문의 단순 언급은 연결하지 않습니다. 태스크에 연결된 PR(GitHub와 자체 호스팅 모두)이 모두 merge되고 그중 하나에 종료 키워드(`Closes`/`Fixes`/`Resolves MUL-123`)가 있으면 [GitHub](/github-integration)와 같은 워크스페이스 설정과 규칙에 따라 태스크를 완료로 옮깁니다.
+- **태스크 연결** — 제목이나 브랜치의 번호, 그리고 본문에서 종료 키워드 바로 뒤에 쓴 번호가 PR을 태스크에 연결합니다. 본문의 단순 언급은 연결하지 않습니다. 태스크에 연결된 PR(GitHub와 자체 호스팅 모두)이 모두 merge되면 [GitHub](/github-integration)와 같은 설정과 규칙에 따라 워크스페이스가 정한 상태로 태스크를 옮깁니다. 제공자를 연결하면 이 페이지에도 같은 **PR 병합 후 태스크 상태** 설정이 표시됩니다.
- **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.mdx
index 1c1cb51f85..f643f2a635 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 when they merge with a closing keyword, 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, or after a closing keyword in the body, auto-attach to that issue, move it to the workspace's chosen status when they merge, 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 in
Settings → 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) and appears under **Pull requests** in the issue sidebar. When every PR linked to the issue is merged and one of them used a closing keyword, the issue moves 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`), or whose body names one after a closing keyword (`Closes 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 the status the workspace chose (**Done** by default). CI for the head commit shows as a checks bar on the card.
These providers run alongside GitHub: a workspace can use any combination.
@@ -87,7 +87,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. Once every PR linked to the issue is merged — across GitHub and self-hosted providers — and one of them used a closing keyword (`Closes`/`Fixes`/`Resolves MUL-123`), the issue moves to **Done**, under the same workspace setting and rules as [GitHub](/github-integration).
+- **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. Once every PR linked to the issue is merged — across GitHub and self-hosted providers — the issue moves to the status the workspace chose, under the same setting and rules as [GitHub](/github-integration#when-merged-prs-move-an-issue). This page shows the same **After PRs merge, move the issue to** setting once a provider is connected.
- **CI** — Forgejo/Gitea commit statuses and GitLab pipelines aggregate into a passed/failed/pending checks bar for the head commit.
## Agents opening pull requests
diff --git a/apps/docs/content/docs/vcs-integration.zh.mdx b/apps/docs/content/docs/vcs-integration.zh.mdx
index d3c3d441c1..36096c7841 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 自动关联到对应任务,在带关闭关键字的 PR 合并时将其移动到「完成」,并展示 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 都合并、且其中有 PR 使用了关闭关键字时,任务会被移动到「完成」。head commit 的 CI 会以检查条的形式显示在卡片上。
+Multica 按工作区连接自托管的 Git 代码托管:**Forgejo**、**Gitea** 或 **GitLab**。连接后,任何在分支名或标题中包含任务编号(例如 `MUL-123`)、或在正文的关闭关键字后写出该编号(`Closes MUL-123`)的 Pull Request(GitLab 为 Merge Request)都会**自动关联**到对应的 [任务](/issues),出现在任务侧栏的 **Pull requests** 中;任务的所有关联 PR 都合并后,任务会改为工作区选定的状态(默认「完成」)。head commit 的 CI 会以检查条的形式显示在卡片上。
这些代码托管与 GitHub 并行工作:一个工作区可任意组合使用。
@@ -82,7 +82,7 @@ Multica 会用存储的密钥校验每次投递,因此没有匹配密钥的 We
## 镜像的内容
- **Pull / Merge Request** —— open、closed、merged、draft 状态,以及作者、分支和(在代码托管提供时)diff 统计。
-- **任务关联** —— 标题或分支中的编号会将 PR 关联到任务,正文中的编号只有紧跟关闭关键字时才会关联;正文中的普通提及不会建立任何关联。任务的所有关联 PR(包括 GitHub 与自托管平台上的)都合并、且其中有 PR 使用了关闭关键字(`Closes`/`Fixes`/`Resolves MUL-123`)时,任务会被移动到「完成」,遵循与 [GitHub](/github-integration) 相同的工作区设置和规则。
+- **任务关联** —— 标题或分支中的编号会将 PR 关联到任务,正文中的编号只有紧跟关闭关键字时才会关联;正文中的普通提及不会建立任何关联。任务的所有关联 PR(包括 GitHub 与自托管平台上的)都合并后,任务会改为工作区选定的状态,遵循与 [GitHub](/github-integration) 相同的设置和规则。连接平台后,本页也会显示同一项 **PR 合并后,任务状态改为** 设置。
- **CI** —— Forgejo/Gitea 的提交状态与 GitLab 的流水线会汇总为 head commit 的通过/失败/进行中检查条。
## 智能体创建 Pull Request
diff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.ts
index 5c91bf1f35..c145c94d6e 100644
--- a/packages/core/api/client.test.ts
+++ b/packages/core/api/client.test.ts
@@ -237,7 +237,7 @@ describe("ApiClient pull-request response schema", () => {
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 },
+ auto_complete: { state: "waiting", pull_request_ids: ["pr-1"], issue_disabled: false, workspace_enabled: true, target_status: "in_review" },
});
const result = await new ApiClient("https://api.example.test").listIssuePullRequests("issue-1");
expect(result.pull_requests[0]?.link_source).toBe("title");
@@ -246,6 +246,7 @@ describe("ApiClient pull-request response schema", () => {
pull_request_ids: ["pr-1"],
issue_disabled: false,
workspace_enabled: true,
+ target_status: "in_review",
});
});
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index 6efded1c7d..9258805540 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -436,6 +436,7 @@ export const PRAutoCompleteSchema = z.object({
pull_request_ids: z.array(z.string()).default([]),
issue_disabled: z.boolean().default(false),
workspace_enabled: z.boolean().default(true),
+ target_status: z.string().optional().catch(undefined),
}).loose();
export const IssuePullRequestsResponseSchema = z.object({
diff --git a/packages/core/github/settings.test.ts b/packages/core/github/settings.test.ts
index 6c03665c3e..192bda5fa7 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, derivePRAutoCompleteEnabled } from "./settings";
+import { deriveGitHubSettings, derivePRMergeStatus } from "./settings";
import type { Workspace } from "../types";
function ws(settings: Record<string, unknown>): Pick<Workspace, "settings"> {
@@ -65,14 +65,25 @@ describe("deriveGitHubSettings", () => {
});
});
-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);
+describe("derivePRMergeStatus", () => {
+ it("defaults to Done and reads the chosen key", () => {
+ expect(derivePRMergeStatus(null)).toBe("done");
+ expect(derivePRMergeStatus(ws({}))).toBe("done");
+ expect(derivePRMergeStatus(ws({ pr_merge_status: "none" }))).toBe("none");
+ expect(derivePRMergeStatus(ws({ pr_merge_status: " In_Review " }))).toBe("in_review");
});
- it("does not follow the GitHub master switch", () => {
- expect(derivePRAutoCompleteEnabled(ws({ github_enabled: false }))).toBe(true);
+ it("fails closed on a malformed value", () => {
+ expect(derivePRMergeStatus(ws({ pr_merge_status: "" }))).toBe("none");
+ expect(derivePRMergeStatus(ws({ pr_merge_status: 5 }))).toBe("none");
+ });
+
+ it("follows the retired switch only when no status is chosen", () => {
+ expect(derivePRMergeStatus(ws({ pr_auto_complete_enabled: false }))).toBe("none");
+ expect(derivePRMergeStatus(ws({ pr_auto_complete_enabled: false, pr_merge_status: "in_review" }))).toBe("in_review");
+ });
+
+ it("ignores the GitHub master switch", () => {
+ expect(derivePRMergeStatus(ws({ github_enabled: false }))).toBe("done");
});
});
diff --git a/packages/core/github/settings.ts b/packages/core/github/settings.ts
index 9440ec6273..4b439edc0d 100644
--- a/packages/core/github/settings.ts
+++ b/packages/core/github/settings.ts
@@ -28,14 +28,26 @@ export function deriveGitHubSettings(
};
}
+/** The `pr_merge_status` value that leaves an issue's status alone. */
+export const PR_MERGE_STATUS_NONE = "none";
+
/**
- * 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.
+ * What merging every PR linked to an issue does (MUL-7726): `"none"`, or the
+ * key of the status the issue moves to. Without the key it follows the retired
+ * `pr_auto_complete_enabled` switch (off → none, else Done), as the server does.
+ * Not GitHub-specific — self-hosted providers follow the same setting — so it
+ * ignores the GitHub master switch. The server re-validates the key against
+ * the status catalog.
*/
-export function derivePRAutoCompleteEnabled(
+export function derivePRMergeStatus(
workspace: Pick<Workspace, "settings"> | null | undefined,
-): boolean {
+): string {
const s = (workspace?.settings ?? {}) as Record<string, unknown>;
- return s.pr_auto_complete_enabled !== false;
+ const value = s.pr_merge_status;
+ if (value === undefined || value === null) {
+ const legacy = s.pr_auto_complete_enabled;
+ return legacy === undefined || legacy === null || legacy === true ? "done" : PR_MERGE_STATUS_NONE;
+ }
+ if (typeof value !== "string") return PR_MERGE_STATUS_NONE;
+ return value.trim().toLowerCase() || PR_MERGE_STATUS_NONE;
}
diff --git a/packages/core/types/github.ts b/packages/core/types/github.ts
index ea97c96ce9..3a44d77b4c 100644
--- a/packages/core/types/github.ts
+++ b/packages/core/types/github.ts
@@ -61,15 +61,16 @@ export interface GitHubInstallation {
* "auto" is any other automatic link, such as "Closes MUL-1" in the body. */
export type PullRequestLinkSource = "manual" | "title" | "branch" | "auto";
-/** What the "every linked PR merged, one says Closes → Done" rule will do for
- * one issue. The server computes it; the issue page only renders it. */
+/** What "every linked PR merged → move the issue to the workspace's target
+ * status" will do for one issue. The server computes it; the issue page only
+ * renders it. Older backends may still send `no_close_intent`. */
export type PRAutoCompleteState =
| "none"
| "workspace_disabled"
| "issue_disabled"
| "terminal"
| "triage"
- | "no_close_intent"
+ | "at_target"
| "waiting"
| "not_merged"
| "all_merged";
@@ -82,6 +83,9 @@ export interface PRAutoComplete {
pull_request_ids: string[];
issue_disabled: boolean;
workspace_enabled: boolean;
+ /** Status key a merge moves the issue to, or "none". Older backends omit
+ * it; they only ever moved issues to Done. */
+ target_status?: string;
}
export interface IssuePullRequestsResponse {
diff --git a/packages/views/issues/components/issue-detail.test.tsx b/packages/views/issues/components/issue-detail.test.tsx
index 487b5fc99c..1af247c25b 100644
--- a/packages/views/issues/components/issue-detail.test.tsx
+++ b/packages/views/issues/components/issue-detail.test.tsx
@@ -1922,7 +1922,7 @@ describe("IssueDetail (shared)", () => {
// MUL-7429: an automatic status change says why, and the per-issue switch
// shows on the timeline.
- it("explains PR auto-complete activity", async () => {
+ it("explains PR merge automation activity", async () => {
mockApiObj.listTimeline.mockResolvedValue([
{
type: "activity",
@@ -1949,7 +1949,7 @@ describe("IssueDetail (shared)", () => {
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();
+ expect(screen.getByText(/set this issue to keep its status when PRs merge/i)).toBeInTheDocument();
});
it("renders activity rows with unknown status values without crashing", async () => {
diff --git a/packages/views/issues/components/pull-request-list.test.tsx b/packages/views/issues/components/pull-request-list.test.tsx
index eb2e6b2196..7432b97730 100644
--- a/packages/views/issues/components/pull-request-list.test.tsx
+++ b/packages/views/issues/components/pull-request-list.test.tsx
@@ -33,9 +33,11 @@ vi.mock("@multica/core/api", async (importOriginal) => ({
}));
const toastMock = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn() }));
vi.mock("sonner", () => ({ toast: toastMock }));
+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));
vi.mock("@multica/core/paths", async (importOriginal) => ({
...(await importOriginal<typeof import("@multica/core/paths")>()),
useWorkspacePaths: () => ({ settings: () => "/acme/settings" }),
+ useCurrentWorkspace: () => ({ id: "ws-1", slug: "acme", settings: {} }),
}));
vi.mock("../../navigation", () => ({
AppLink: ({ href, children, className }: { href: string; children: React.ReactNode; className?: string }) => (
@@ -377,9 +379,9 @@ describe("PullRequestList sidebar rows", () => {
});
});
-// MUL-7429: the line under the list says what "every linked PR merged, one says
-// Closes → Done" will do, straight from the server's decision, and each row can
-// be removed.
+// MUL-7429 / MUL-7726: the line under the list says what merging will do to the
+// issue's status, straight from the server's decision, and each row can be
+// removed.
describe("PullRequestList auto-complete", () => {
beforeEach(() => {
mockAutoComplete = null;
@@ -394,14 +396,22 @@ describe("PullRequestList auto-complete", () => {
pull_request_ids: ids,
issue_disabled: false,
workspace_enabled: true,
+ target_status: "done",
...extra,
});
- it("names the PR the issue is waiting on", async () => {
+ it("names the PR the issue is waiting on and the status it moves to", async () => {
mockPRs = [makePR({ id: "a", number: 12, state: "merged" }), makePR({ id: "b", number: 19 })];
- mockAutoComplete = decision("waiting", ["b"]);
+ mockAutoComplete = decision("waiting", ["b"], { target_status: "in_review" });
renderList();
- expect(await screen.findByText("Completes when #19 merges")).toBeInTheDocument();
+ expect(await screen.findByTestId("pr-auto-complete-line")).toHaveTextContent("Moves to In Review when #19 merges");
+ });
+
+ it("falls back to Done on a backend that does not name the target", async () => {
+ mockPRs = [makePR({ id: "b", number: 19 })];
+ mockAutoComplete = decision("waiting", ["b"], { target_status: undefined });
+ renderList();
+ expect(await screen.findByTestId("pr-auto-complete-line")).toHaveTextContent("Moves to Done when #19 merges");
});
it("offers to remove a PR that closed without merging", async () => {
@@ -413,47 +423,33 @@ describe("PullRequestList auto-complete", () => {
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
+ // Removing the last unmerged PR moved 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("says merging won't complete the issue when no PR closes it", async () => {
- mockPRs = [makePR({ id: "a", number: 12, link_source: "title" })];
- mockAutoComplete = decision("no_close_intent");
- renderList();
- expect(await screen.findByTestId("pr-auto-complete-line")).toHaveTextContent(
- "Won’t complete: no “Closes MUL-1”",
+ expect(toastMock.success).toHaveBeenCalledWith("Removed #19. Every remaining PR is merged, so the issue moved to Done."),
);
});
- it("links the workspace setting when auto-complete is off there", async () => {
+ // The workspace chose to leave status alone: a team choice, not repeated on
+ // every issue. An older backend's no_close_intent says nothing either.
+ it.each(["workspace_disabled", "no_close_intent", "at_target", "terminal"])("says nothing for %s", async (state) => {
mockPRs = [makePR({ id: "a", number: 12, state: "merged" })];
- mockAutoComplete = decision("workspace_disabled", [], { workspace_enabled: false });
+ mockAutoComplete = decision(state, [], state === "workspace_disabled" ? { workspace_enabled: false, target_status: "none" } : {});
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");
+ await waitForRender();
+ expect(screen.queryByTestId("pr-auto-complete-line")).toBeNull();
});
- it("turns auto-complete back on for the issue from the line", async () => {
+ it("turns the merge status change 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" }));
+ expect(await screen.findByTestId("pr-auto-complete-line")).toHaveTextContent("PR merges won’t change this issue");
+ fireEvent.click(screen.getByRole("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;
diff --git a/packages/views/issues/components/pull-request-list.tsx b/packages/views/issues/components/pull-request-list.tsx
index 53f8cff501..4483ab0550 100644
--- a/packages/views/issues/components/pull-request-list.tsx
+++ b/packages/views/issues/components/pull-request-list.tsx
@@ -29,7 +29,8 @@ import {
type PullRequestChecksStatus,
type PullRequestMergeStatus,
} from "@multica/core/github";
-import { useWorkspacePaths } from "@multica/core/paths";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
import type {
GitHubPullRequest,
GitHubPullRequestState,
@@ -45,8 +46,9 @@ import {
DropdownMenuTrigger,
} from "@multica/ui/components/ui/dropdown-menu";
import { cn } from "@multica/ui/lib/utils";
-import { AppLink } from "../../navigation";
import { useT, useTimeAgo } from "../../i18n";
+import { useStatusLabel } from "../utils/status-label";
+import { StatusIcon } from "./status-icon";
type IssuesT = ReturnType<typeof useT<"issues">>["t"];
@@ -123,7 +125,7 @@ export function PullRequestList({
</div>
) : null}
{autoComplete ? (
- <AutoCompleteLine issueId={issueId} identifier={identifier} prs={prs} autoComplete={autoComplete} />
+ <AutoCompleteLine issueId={issueId} prs={prs} autoComplete={autoComplete} />
) : null}
</div>
);
@@ -138,23 +140,35 @@ interface RowActions {
const prLabel = (pr: Pick<GitHubPullRequest, "number">) => `#${pr.number}`;
+/** Where a merge moves the issue; older backends only ever moved it to Done. */
+const mergeTarget = (autoComplete: PRAutoComplete) => autoComplete.target_status ?? "done";
+
+/** States in which the merge has nothing left to do for this issue. */
+const SETTLED = new Set(["terminal", "at_target"]);
+
/**
* 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
+ * unmerged PR can move 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 statusLabel = useStatusLabel(useWorkspaceId());
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) }));
+ const moved =
+ !SETTLED.has(before.state) && !!after.auto_complete && SETTLED.has(after.auto_complete.state);
+ if (moved) {
+ toast.success(
+ t(($) => $.pr_automation.unlinked_moved, {
+ pr: prLabel(pr),
+ status: statusLabel(mergeTarget(after.auto_complete!)),
+ }),
+ );
return;
}
toast.success(t(($) => $.pr_automation.unlinked, { pr: prLabel(pr) }), {
@@ -214,24 +228,30 @@ function PullRequestRowMenu({ pr, actions }: { pr: GitHubPullRequest; actions: R
);
}
+// Splits a translated sentence around the target status so each language keeps
+// its own word order and the status renders as a chip, not plain text.
+const STATUS_SLOT = "\u2063status\u2063";
+
/**
- * One line under the PR list saying what the "every linked PR merged, one says
- * Closes → Done" rule will do for this issue, straight from the server's
- * decision. Terminal, triage and unknown states render nothing.
+ * One line under the PR list saying what "every linked PR merged → move the
+ * issue to the workspace's target status" will do for this issue, straight
+ * from the server's decision. It speaks only when a merge would move the issue
+ * or this issue opted out: a workspace that leaves status alone, a finished or
+ * triaged issue, one already in the target, and unknown states render nothing.
*/
function AutoCompleteLine({
issueId,
- identifier,
prs,
autoComplete,
}: {
issueId: string;
- identifier: string;
prs: GitHubPullRequest[];
autoComplete: PRAutoComplete;
}) {
const { t } = useT("issues");
- const paths = useWorkspacePaths();
+ const wsId = useWorkspaceId();
+ const catalog = useIssueStatuses(wsId);
+ const statusLabel = useStatusLabel(wsId);
const unlink = useUnlinkPullRequest(issueId, autoComplete);
const setAutoComplete = useSetIssuePRAutoComplete(issueId);
const named = autoComplete.pull_request_ids
@@ -247,6 +267,26 @@ function AutoCompleteLine({
{label}
</button>
);
+ const target = mergeTarget(autoComplete);
+ const withTarget = (sentence: string) => {
+ const [before, after = ""] = sentence.split(STATUS_SLOT);
+ return (
+ <>
+ {before}
+ <span className="inline-flex items-center gap-1 align-[-2px] font-medium text-foreground">
+ <StatusIcon
+ status={target}
+ category={catalog.categoryOf(target)}
+ color={catalog.colorOf(target)}
+ icon={catalog.iconOf(target)}
+ className="size-3"
+ />
+ {statusLabel(target)}
+ </span>
+ {after}
+ </>
+ );
+ };
let icon: React.ReactNode;
let body: React.ReactNode;
@@ -254,7 +294,7 @@ function AutoCompleteLine({
case "waiting":
if (named.length === 0) return null;
icon = <CircleDashed className="text-muted-foreground" />;
- body = t(($) => $.pr_automation.waiting, { count: named.length, prs: list });
+ body = withTarget(t(($) => $.pr_automation.waiting_to, { count: named.length, prs: list, status: STATUS_SLOT }));
break;
case "not_merged": {
if (named.length === 0) return null;
@@ -268,13 +308,9 @@ function AutoCompleteLine({
);
break;
}
- case "no_close_intent":
- icon = <CircleSlash className="text-muted-foreground" />;
- body = t(($) => $.pr_automation.no_close_intent, { identifier });
- break;
case "all_merged":
icon = <CheckCircle2 className="text-muted-foreground" />;
- body = t(($) => $.pr_automation.all_merged);
+ body = withTarget(t(($) => $.pr_automation.all_merged_to, { status: STATUS_SLOT }));
break;
case "issue_disabled":
icon = <CircleSlash className="text-muted-foreground" />;
@@ -289,20 +325,6 @@ function AutoCompleteLine({
</>
);
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;
}
diff --git a/packages/views/issues/components/pull-requests-section.test.tsx b/packages/views/issues/components/pull-requests-section.test.tsx
index c045efbc68..7047ff9514 100644
--- a/packages/views/issues/components/pull-requests-section.test.tsx
+++ b/packages/views/issues/components/pull-requests-section.test.tsx
@@ -36,9 +36,12 @@ vi.mock("../../navigation", () => ({
useNavigation: () => ({ push: navigatePush }),
AppLink: ({ href, children }: { href: string; children: React.ReactNode }) => <a href={href}>{children}</a>,
}));
+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));
+let mockWorkspaceSettings: Record<string, unknown> = {};
vi.mock("@multica/core/paths", async (importOriginal) => ({
...(await importOriginal<typeof import("@multica/core/paths")>()),
useWorkspacePaths: () => ({ settings: () => "/acme/settings" }),
+ useCurrentWorkspace: () => ({ id: "ws-1", slug: "acme", settings: mockWorkspaceSettings }),
}));
import { PullRequestsSection } from "./pull-requests-section";
@@ -64,6 +67,7 @@ const decision: PRAutoComplete = {
describe("PullRequestsSection (MUL-7429)", () => {
beforeEach(() => {
mockAutoComplete = decision;
+ mockWorkspaceSettings = {};
apiMock.linkIssuePullRequest.mockReset();
apiMock.setIssuePRAutoComplete.mockReset();
navigatePush.mockReset();
@@ -111,14 +115,37 @@ describe("PullRequestsSection (MUL-7429)", () => {
);
});
- it("turns auto-complete off for this issue from the section menu", async () => {
+ it("keeps this issue's status on merge 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: "Turn off auto-complete" }));
+ fireEvent.click(await screen.findByRole("menuitem", { name: "Keep status when PRs merge" }));
await waitFor(() => expect(apiMock.setIssuePRAutoComplete).toHaveBeenCalledWith("issue-1", true));
});
+ it("opens the GitHub setting from the section menu", async () => {
+ renderSection();
+ fireEvent.click(await screen.findByRole("button", { name: "Pull request automation" }));
+ fireEvent.click(await screen.findByRole("menuitem", { name: "PR merge settings" }));
+ expect(navigatePush).toHaveBeenCalledWith("/acme/settings?tab=integrations&integration=github");
+ });
+
+ it("offers only the settings link while the workspace leaves status alone", async () => {
+ mockAutoComplete = { ...decision, workspace_enabled: false };
+ renderSection();
+ fireEvent.click(await screen.findByRole("button", { name: "Pull request automation" }));
+ expect(await screen.findByRole("menuitem", { name: "PR merge settings" })).toBeInTheDocument();
+ expect(screen.queryByRole("menuitem", { name: "Keep status when PRs merge" })).toBeNull();
+ });
+
+ it("drops the auto-link hint when the workspace does not auto-link PRs", async () => {
+ mockWorkspaceSettings = { github_auto_link_prs_enabled: false };
+ renderSection();
+ fireEvent.click(await screen.findByRole("button", { name: "Link pull request" }));
+ await screen.findByRole("textbox", { name: "Link pull request" });
+ expect(screen.queryByText("PRs with MUL-1 in the title or branch name link automatically.")).toBeNull();
+ });
+
it("hides the actions on a backend without auto-complete", async () => {
mockAutoComplete = null;
renderSection();
diff --git a/packages/views/issues/components/pull-requests-section.tsx b/packages/views/issues/components/pull-requests-section.tsx
index 4d817c0088..4ed563f375 100644
--- a/packages/views/issues/components/pull-requests-section.tsx
+++ b/packages/views/issues/components/pull-requests-section.tsx
@@ -7,6 +7,7 @@ import { ChevronRight, CircleSlash, MoreHorizontal, Plus, RotateCcw, Settings }
import { ApiError } from "@multica/core/api";
import {
issuePullRequestsOptions,
+ useGitHubSettings,
useLinkIssuePullRequest,
useSetIssuePRAutoComplete,
} from "@multica/core/github";
@@ -26,10 +27,10 @@ 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).
+ * The issue sidebar's Pull requests section: the linked PRs, what merging them
+ * will do to this issue's status, and the two exceptions a person can make —
+ * link a PR by hand, or keep this one issue's status when its PRs merge
+ * (MUL-7429, MUL-7726).
*/
export function PullRequestsSection({
issueId,
@@ -64,7 +65,11 @@ export function PullRequestsSection({
{supported ? (
<>
<LinkPullRequestPopover issueId={issueId} identifier={identifier} onLinked={() => onOpenChange(true)} />
- <AutoCompleteMenu issueId={issueId} disabled={data?.auto_complete?.issue_disabled ?? false} />
+ <AutoCompleteMenu
+ issueId={issueId}
+ disabled={data?.auto_complete?.issue_disabled ?? false}
+ workspaceEnabled={data?.auto_complete?.workspace_enabled ?? true}
+ />
</>
) : null}
</div>
@@ -87,6 +92,7 @@ function LinkPullRequestPopover({
onLinked: () => void;
}) {
const { t } = useT("issues");
+ const { autoLinkPRs } = useGitHubSettings();
const [open, setOpen] = useState(false);
const [url, setUrl] = useState("");
const link = useLinkIssuePullRequest(issueId);
@@ -148,7 +154,7 @@ function LinkPullRequestPopover({
value={url}
placeholder={t(($) => $.pr_automation.link_placeholder)}
aria-invalid={error ? true : undefined}
- aria-describedby={`link-pr-${issueId}-hint`}
+ aria-describedby={error || !autoLinkPRs ? undefined : `link-pr-${issueId}-hint`}
onChange={(e) => {
setUrl(e.target.value);
if (link.error) link.reset();
@@ -158,11 +164,12 @@ function LinkPullRequestPopover({
<p role="alert" className="text-caption text-destructive">
{error}
</p>
- ) : (
+ ) : autoLinkPRs ? (
+ // Only true while the workspace auto-links PRs.
<p id={`link-pr-${issueId}-hint`} className="text-caption text-muted-foreground">
{t(($) => $.pr_automation.link_hint, { identifier })}
</p>
- )}
+ ) : null}
<div className="flex justify-end">
<Button
type="submit"
@@ -179,7 +186,15 @@ function LinkPullRequestPopover({
);
}
-function AutoCompleteMenu({ issueId, disabled }: { issueId: string; disabled: boolean }) {
+function AutoCompleteMenu({
+ issueId,
+ disabled,
+ workspaceEnabled,
+}: {
+ issueId: string;
+ disabled: boolean;
+ workspaceEnabled: boolean;
+}) {
const { t } = useT("issues");
const paths = useWorkspacePaths();
const navigation = useNavigation();
@@ -195,19 +210,24 @@ function AutoCompleteMenu({ issueId, disabled }: { issueId: string; disabled: bo
}
/>
<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`)}>
+ {/* When the workspace leaves status alone, the issue switch changes nothing. */}
+ {workspaceEnabled ? (
+ <>
+ <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 />
+ </>
+ ) : null}
+ <DropdownMenuItem onClick={() => navigation.push(`${paths.settings()}?tab=integrations&integration=github`)}>
<Settings />
{t(($) => $.pr_automation.settings)}
</DropdownMenuItem>
diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.json
index 2f2965eda1..3166f17701 100644
--- a/packages/views/locales/en/issues.json
+++ b/packages/views/locales/en/issues.json
@@ -517,8 +517,8 @@
"duplicate_added": "marked {{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"
+ "pr_auto_complete_disabled": "set this issue to keep its status when PRs merge",
+ "pr_auto_complete_enabled": "set this issue to change status when PRs merge again"
},
"comment": {
"add_reaction": "Add reaction",
@@ -1138,22 +1138,19 @@
"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.",
+ "unlinked_moved": "Removed {{pr}}. Every remaining PR is merged, so the issue moved to {{status}}.",
"unlink_failed": "Couldn’t remove the pull request.",
"undo": "Undo",
- "disable": "Turn off auto-complete",
- "enable": "Turn on auto-complete",
- "settings": "Auto-complete settings",
- "update_failed": "Couldn’t update auto-complete.",
- "waiting_one": "Completes when {{prs}} merges",
- "waiting_other": "Completes when {{prs}} merge",
+ "disable": "Keep status when PRs merge",
+ "enable": "Change status when PRs merge",
+ "settings": "PR merge settings",
+ "update_failed": "Couldn’t update the PR merge setting.",
+ "waiting_to_one": "Moves to {{status}} when {{prs}} merges",
+ "waiting_to_other": "Moves to {{status}} when {{prs}} merge",
"not_merged": "{{prs}} closed without merging",
"not_merged_action": "Remove",
- "no_close_intent": "Won’t complete: no “Closes {{identifier}}”",
- "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"
+ "all_merged_to": "All PRs merged. The next merged PR moves this issue to {{status}}.",
+ "issue_disabled": "PR merges won’t change this issue",
+ "issue_disabled_action": "Turn on"
}
}
diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.json
index bf50be59eb..d2b1983cd1 100644
--- a/packages/views/locales/en/settings.json
+++ b/packages/views/locales/en/settings.json
@@ -82,11 +82,6 @@
"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 and one of them closes it with a keyword. Applies to PRs merged from now on.",
- "pr_auto_complete_example": "Write the keyword in the PR title or description, e.g.",
- "pr_auto_complete_example_title": "Closes MUL-123",
"pr_auto_complete_badge": "Set when PRs merge"
},
"quick_actions": {
@@ -799,11 +794,7 @@
"repositories_shortcut_label": "Repository URLs live in the Repositories tab",
"repositories_shortcut_link": "Manage repositories →",
"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, or follows “Closes” in its description.",
- "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"
+ "feature_auto_link_description": "Links a PR to the issue whose ID, e.g. {{example}}, is in its title or branch name, or follows “Closes” in its description."
},
"vcs": {
"section_title": "Git providers (self-hosted)",
@@ -1371,5 +1362,10 @@
"status_loading": "Checking...",
"status_unknown": "Status unavailable",
"channel_hint": "Chat with agents and create issues from {{channel}}."
+ },
+ "pr_merge_status": {
+ "label": "After PRs merge, move the issue to",
+ "description": "Applies once every PR linked to an issue has merged, and only to merges from now on.",
+ "none": "Don’t change"
}
}
diff --git a/packages/views/locales/fr/issues.json b/packages/views/locales/fr/issues.json
index 5e8e95bd16..37cb9551e3 100644
--- a/packages/views/locales/fr/issues.json
+++ b/packages/views/locales/fr/issues.json
@@ -517,8 +517,8 @@
"duplicate_added": "a marqué {{identifier}} comme doublon de cette tâche",
"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"
+ "pr_auto_complete_disabled": "a configuré cette tâche pour garder son statut à la fusion des PR",
+ "pr_auto_complete_enabled": "a de nouveau fait changer le statut de cette tâche à la fusion des PR"
},
"comment": {
"add_reaction": "Ajouter une réaction",
@@ -1138,22 +1138,19 @@
"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.",
+ "unlinked_moved": "{{pr}} retirée. Toutes les PR restantes sont fusionnées, la tâche est passée à {{status}}.",
"unlink_failed": "Impossible de retirer la pull request.",
"undo": "Annuler",
- "disable": "Désactiver la fin automatique",
- "enable": "Réactiver la fin automatique",
- "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",
+ "disable": "Garder le statut à la fusion des PR",
+ "enable": "Changer le statut à la fusion des PR",
+ "settings": "Paramètres de fusion des PR",
+ "update_failed": "Impossible de mettre à jour le paramètre de fusion des PR.",
+ "waiting_to_one": "Passe à {{status}} quand {{prs}} est fusionnée",
+ "waiting_to_other": "Passe à {{status}} quand {{prs}} sont fusionnées",
"not_merged": "{{prs}} fermée sans fusion",
"not_merged_action": "Retirer",
- "no_close_intent": "Ne se termine pas : pas de « Closes {{identifier}} »",
- "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"
+ "all_merged_to": "Toutes les PR sont fusionnées. La prochaine PR fusionnée fera passer la tâche à {{status}}.",
+ "issue_disabled": "Les fusions de PR ne changent pas cette tâche",
+ "issue_disabled_action": "Réactiver"
}
}
diff --git a/packages/views/locales/fr/settings.json b/packages/views/locales/fr/settings.json
index 7e06ad84b1..b8dbe615b4 100644
--- a/packages/views/locales/fr/settings.json
+++ b/packages/views/locales/fr/settings.json
@@ -82,11 +82,6 @@
"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 et que l’une d’elles la ferme par un mot-clé. S’applique aux PR fusionnées à partir de maintenant.",
- "pr_auto_complete_example": "Écrivez le mot-clé dans le titre ou la description de la PR, par ex.",
- "pr_auto_complete_example_title": "Closes MUL-123",
"pr_auto_complete_badge": "Définie à la fusion des PR"
},
"quick_actions": {
@@ -799,11 +794,7 @@
"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",
- "feature_auto_link_description": "Lie une PR à la tâche dont l’identifiant, par ex. {{example}}, figure dans son titre ou sa branche, ou suit « Closes » dans sa description.",
- "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"
+ "feature_auto_link_description": "Lie une PR à la tâche dont l’identifiant, par ex. {{example}}, figure dans son titre ou sa branche, ou suit « Closes » dans sa description."
},
"vcs": {
"section_title": "Fournisseurs git (auto-hébergés)",
@@ -1371,5 +1362,10 @@
"status_loading": "Vérification...",
"status_unknown": "État indisponible",
"channel_hint": "Discutez avec les agents et créez des tâches depuis {{channel}}."
+ },
+ "pr_merge_status": {
+ "label": "Après la fusion des PR, passer la tâche à",
+ "description": "S’applique quand toutes les PR liées à une tâche sont fusionnées, pour les fusions à venir uniquement.",
+ "none": "Ne pas changer"
}
}
diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.json
index ac2796b90e..b4f632e755 100644
--- a/packages/views/locales/ja/issues.json
+++ b/packages/views/locales/ja/issues.json
@@ -508,8 +508,8 @@
"duplicate_added": "{{identifier}} をこのタスクの重複としてマークしました",
"duplicate_removed": "{{identifier}} の重複マークを解除しました",
"status_changed_pr": "関連するすべての PR がマージされたため({{prs}})、ステータスを {{from}} から {{to}} に変更しました",
- "pr_auto_complete_disabled": "このタスクの PR による自動完了をオフにしました",
- "pr_auto_complete_enabled": "このタスクの PR による自動完了を再開しました"
+ "pr_auto_complete_disabled": "このタスクを PR マージでステータスを変えないように設定しました",
+ "pr_auto_complete_enabled": "このタスクの PR マージ後のステータス変更を再開しました"
},
"comment": {
"add_reaction": "リアクションを追加",
@@ -1106,21 +1106,18 @@
"source_auto": "自動で関連付け",
"unlink": "タスクから外す",
"unlinked": "{{pr}} を外しました",
- "unlinked_completed": "{{pr}} を外しました。残りの PR はすべてマージ済みのため、タスクは完了しました。",
+ "unlinked_moved": "{{pr}} を外しました。残りの PR はすべてマージ済みのため、タスクを {{status}} に変更しました。",
"unlink_failed": "PR を外せませんでした。",
"undo": "元に戻す",
- "disable": "このタスクは自動完了しない",
- "enable": "自動完了を再開",
- "settings": "自動完了の設定",
- "update_failed": "自動完了を更新できませんでした。",
- "waiting_other": "{{prs}} がマージされると自動完了",
+ "disable": "PR マージ後もステータスを変えない",
+ "enable": "PR マージ後のステータス変更を再開",
+ "settings": "PR マージ設定",
+ "update_failed": "PR マージ設定を更新できませんでした。",
+ "waiting_to_other": "{{prs}} がマージされると {{status}} に変更",
"not_merged": "{{prs}} はマージされずにクローズされました",
"not_merged_action": "外す",
- "no_close_intent": "自動完了しません:「Closes {{identifier}}」なし",
- "all_merged": "PR はすべてマージ済みです。次に PR がマージされると自動完了します。",
- "issue_disabled": "このタスクは自動完了しません",
- "issue_disabled_action": "再開",
- "workspace_disabled": "このワークスペースでは PR による自動完了がオフです",
- "workspace_disabled_action": "設定"
+ "all_merged_to": "PR はすべてマージ済みです。次に PR がマージされると {{status}} に変更します。",
+ "issue_disabled": "このタスクは PR マージでステータスを変えません",
+ "issue_disabled_action": "再開"
}
}
diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.json
index fe9211c02a..4e84b010d5 100644
--- a/packages/views/locales/ja/settings.json
+++ b/packages/views/locales/ja/settings.json
@@ -82,11 +82,6 @@
"done": "完了。",
"cancelled": "見送り。"
},
- "automation_title": "自動化",
- "pr_auto_complete_label": "PR のマージでタスクを自動完了",
- "pr_auto_complete_description": "関連する PR がすべてマージされ、そのうち 1 つがクローズキーワードでタスクを指定していると、タスクは「完了」になります。今後マージされる PR にのみ適用されます。",
- "pr_auto_complete_example": "キーワードは PR のタイトルか説明に書きます。例:",
- "pr_auto_complete_example_title": "Closes MUL-123",
"pr_auto_complete_badge": "PR のマージで自動設定"
},
"quick_actions": {
@@ -797,11 +792,7 @@
"repositories_shortcut_label": "リポジトリ URL はリポジトリタブにあります",
"repositories_shortcut_link": "リポジトリを管理 →",
"toast_failed": "GitHub 設定を更新できませんでした",
- "feature_auto_link_description": "タイトルかブランチ名にタスク番号(例: {{example}})を含む PR、または説明に「Closes {{example}}」と書いた PR を、そのタスクに関連付けます。",
- "feature_pr_auto_complete_label": "PR のマージでタスクを自動完了",
- "feature_pr_auto_complete_on": "オン · すべてのコードホストで共通",
- "feature_pr_auto_complete_off": "オフ · すべてのコードホストで共通",
- "feature_pr_auto_complete_manage": "設定"
+ "feature_auto_link_description": "タイトルかブランチ名にタスク番号(例: {{example}})を含む PR、または説明に「Closes {{example}}」と書いた PR を、そのタスクに関連付けます。"
},
"vcs": {
"section_title": "Git providers (self-hosted)",
@@ -1364,5 +1355,10 @@
"status_loading": "確認中...",
"status_unknown": "状態を取得できません",
"channel_hint": "{{channel}} でエージェントと会話し、タスクを作成します。"
+ },
+ "pr_merge_status": {
+ "label": "PR マージ後のタスクのステータス",
+ "description": "紐づいた PR がすべてマージされたときに適用され、今後のマージにのみ影響します。",
+ "none": "変更しない"
}
}
diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.json
index db5d028bb1..146cbbb346 100644
--- a/packages/views/locales/ko/issues.json
+++ b/packages/views/locales/ko/issues.json
@@ -508,8 +508,8 @@
"duplicate_added": "{{identifier}}을(를) 이 태스크의 중복으로 표시했습니다",
"duplicate_removed": "{{identifier}}의 중복 표시를 해제했습니다",
"status_changed_pr": "연결된 PR이 모두 병합되어({{prs}}) 상태를 {{from}}에서 {{to}}로 변경했습니다",
- "pr_auto_complete_disabled": "이 태스크의 PR 자동 완료를 껐습니다",
- "pr_auto_complete_enabled": "이 태스크의 PR 자동 완료를 다시 켰습니다"
+ "pr_auto_complete_disabled": "이 태스크가 PR 병합 시 상태를 유지하도록 설정했습니다",
+ "pr_auto_complete_enabled": "이 태스크의 PR 병합 후 상태 변경을 다시 켰습니다"
},
"comment": {
"add_reaction": "반응 추가",
@@ -1106,21 +1106,18 @@
"source_auto": "자동으로 연결됨",
"unlink": "태스크에서 제거",
"unlinked": "{{pr}}을(를) 제거했습니다",
- "unlinked_completed": "{{pr}}을(를) 제거했습니다. 나머지 PR이 모두 병합되어 태스크가 완료되었습니다.",
+ "unlinked_moved": "{{pr}}을(를) 제거했습니다. 남은 PR이 모두 병합되어 태스크를 {{status}}(으)로 변경했습니다.",
"unlink_failed": "PR을 제거하지 못했습니다.",
"undo": "실행 취소",
- "disable": "이 태스크는 자동 완료하지 않음",
- "enable": "자동 완료 다시 켜기",
- "settings": "자동 완료 설정",
- "update_failed": "자동 완료를 변경하지 못했습니다.",
- "waiting_other": "{{prs}} 병합 시 자동 완료",
+ "disable": "PR 병합 후에도 상태 유지",
+ "enable": "PR 병합 후 상태 변경 다시 켜기",
+ "settings": "PR 병합 설정",
+ "update_failed": "PR 병합 설정을 업데이트하지 못했습니다.",
+ "waiting_to_other": "{{prs}} 병합 시 {{status}}(으)로 변경",
"not_merged": "{{prs}}이(가) 병합되지 않고 닫혔습니다",
"not_merged_action": "제거",
- "no_close_intent": "자동 완료되지 않음: \"Closes {{identifier}}\" 없음",
- "all_merged": "PR이 모두 병합되었습니다. 다음 PR이 병합되면 자동 완료됩니다.",
- "issue_disabled": "이 태스크는 자동 완료하지 않습니다",
- "issue_disabled_action": "다시 켜기",
- "workspace_disabled": "이 워크스페이스는 PR 자동 완료가 꺼져 있습니다",
- "workspace_disabled_action": "설정"
+ "all_merged_to": "PR이 모두 병합되었습니다. 다음 PR이 병합되면 {{status}}(으)로 변경합니다.",
+ "issue_disabled": "이 태스크는 PR 병합 시 상태를 바꾸지 않음",
+ "issue_disabled_action": "다시 켜기"
}
}
diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.json
index ffc28d6a87..9a0a664499 100644
--- a/packages/views/locales/ko/settings.json
+++ b/packages/views/locales/ko/settings.json
@@ -82,11 +82,6 @@
"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": "Closes MUL-123",
"pr_auto_complete_badge": "PR 병합 시 자동 설정"
},
"quick_actions": {
@@ -797,11 +792,7 @@
"repositories_shortcut_label": "저장소 URL은 저장소 탭에 있습니다",
"repositories_shortcut_link": "저장소 관리 →",
"toast_failed": "GitHub 설정을 업데이트하지 못했습니다",
- "feature_auto_link_description": "제목이나 브랜치 이름에 태스크 번호(예: {{example}})가 있거나 설명에 \"Closes {{example}}\"가 있는 PR을 해당 태스크에 연결합니다.",
- "feature_pr_auto_complete_label": "PR 병합 시 태스크 자동 완료",
- "feature_pr_auto_complete_on": "켜짐 · 모든 코드 호스트에 공통 적용",
- "feature_pr_auto_complete_off": "꺼짐 · 모든 코드 호스트에 공통 적용",
- "feature_pr_auto_complete_manage": "설정"
+ "feature_auto_link_description": "제목이나 브랜치 이름에 태스크 번호(예: {{example}})가 있거나 설명에 \"Closes {{example}}\"가 있는 PR을 해당 태스크에 연결합니다."
},
"vcs": {
"section_title": "Git providers (self-hosted)",
@@ -1364,5 +1355,10 @@
"status_loading": "확인 중...",
"status_unknown": "상태를 확인할 수 없음",
"channel_hint": "{{channel}}에서 에이전트와 대화하고 태스크를 생성합니다."
+ },
+ "pr_merge_status": {
+ "label": "PR 병합 후 태스크 상태",
+ "description": "연결된 PR이 모두 병합되면 적용되며, 이후 병합에만 영향을 줍니다.",
+ "none": "변경하지 않음"
}
}
diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.json
index d70e7a8bcb..00624f390b 100644
--- a/packages/views/locales/zh-Hans/issues.json
+++ b/packages/views/locales/zh-Hans/issues.json
@@ -508,8 +508,8 @@
"duplicate_added": "把 {{identifier}} 标记为这个任务的重复",
"duplicate_removed": "取消了 {{identifier}} 对这个任务的重复标记",
"status_changed_pr": "所有关联 PR 均已合并({{prs}}),状态从 {{from}} 改为 {{to}}",
- "pr_auto_complete_disabled": "关闭了此任务的 PR 自动完成",
- "pr_auto_complete_enabled": "恢复了此任务的 PR 自动完成"
+ "pr_auto_complete_disabled": "设置此任务合并后不改状态",
+ "pr_auto_complete_enabled": "恢复了此任务合并后改状态"
},
"comment": {
"add_reaction": "添加表情回应",
@@ -1106,21 +1106,18 @@
"source_auto": "自动关联",
"unlink": "移除关联",
"unlinked": "已移除 {{pr}}",
- "unlinked_completed": "已移除 {{pr}}。其余 PR 均已合并,任务已完成。",
+ "unlinked_moved": "已移除 {{pr}}。其余 PR 均已合并,任务已改为 {{status}}。",
"unlink_failed": "移除关联失败。",
"undo": "撤销",
- "disable": "此任务不自动完成",
- "enable": "恢复自动完成",
- "settings": "自动完成设置",
- "update_failed": "更新自动完成失败。",
- "waiting_other": "等待 {{prs}} 合并后自动完成",
+ "disable": "此任务合并后不改状态",
+ "enable": "恢复合并后改状态",
+ "settings": "PR 合并设置",
+ "update_failed": "更新 PR 合并设置失败。",
+ "waiting_to_other": "等待 {{prs}} 合并后改为 {{status}}",
"not_merged": "{{prs}} 已关闭,未合并",
"not_merged_action": "移除",
- "no_close_intent": "不会自动完成:缺少 \"Closes {{identifier}}\"",
- "all_merged": "PR 均已合并。之后有新 PR 合并时会自动完成。",
- "issue_disabled": "此任务不自动完成",
- "issue_disabled_action": "恢复",
- "workspace_disabled": "工作区未开启 PR 自动完成",
- "workspace_disabled_action": "设置"
+ "all_merged_to": "PR 均已合并。之后有新 PR 合并时会改为 {{status}}。",
+ "issue_disabled": "此任务合并后不改状态",
+ "issue_disabled_action": "恢复"
}
}
diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.json
index 759d1ad37a..c2e76a2044 100644
--- a/packages/views/locales/zh-Hans/settings.json
+++ b/packages/views/locales/zh-Hans/settings.json
@@ -82,12 +82,7 @@
"done": "已完成。",
"cancelled": "决定不做。"
},
- "automation_title": "自动化",
- "pr_auto_complete_label": "PR 合并后自动完成任务",
- "pr_auto_complete_description": "任务关联的 PR 全部合并,且至少一个 PR 写了关闭语句时,状态改为「已完成」。只对之后合并的 PR 生效。",
- "pr_auto_complete_example": "关闭语句写在 PR 标题或正文里,例如",
- "pr_auto_complete_example_title": "Closes MUL-123",
- "pr_auto_complete_badge": "PR 全部合并时自动进入"
+ "pr_auto_complete_badge": "PR 合并后自动进入"
},
"quick_actions": {
"title": "快捷操作",
@@ -797,11 +792,7 @@
"repositories_shortcut_label": "仓库 URL 仍在\"代码仓库\"标签页中管理",
"repositories_shortcut_link": "前往管理 →",
"toast_failed": "更新 GitHub 设置失败",
- "feature_auto_link_description": "PR 标题或分支名含任务编号(如 {{example}}),或正文里写了 \"Closes {{example}}\" 时,自动关联到对应任务。",
- "feature_pr_auto_complete_label": "PR 合并后自动完成任务",
- "feature_pr_auto_complete_on": "已开启 · 所有代码托管平台共用",
- "feature_pr_auto_complete_off": "未开启 · 所有代码托管平台共用",
- "feature_pr_auto_complete_manage": "设置"
+ "feature_auto_link_description": "PR 标题或分支名含任务编号(如 {{example}}),或正文里写了 \"Closes {{example}}\" 时,自动关联到对应任务。"
},
"vcs": {
"section_title": "Git 代码托管(自托管)",
@@ -1364,5 +1355,10 @@
"status_loading": "正在检查...",
"status_unknown": "状态暂不可用",
"channel_hint": "在 {{channel}} 中与智能体对话、创建任务。"
+ },
+ "pr_merge_status": {
+ "label": "PR 合并后,任务状态改为",
+ "description": "关联的 PR 全部合并后生效,只影响之后合并的 PR。",
+ "none": "不改变"
}
}
diff --git a/packages/views/settings/components/github-tab.test.tsx b/packages/views/settings/components/github-tab.test.tsx
index cea703082d..257d5e351e 100644
--- a/packages/views/settings/components/github-tab.test.tsx
+++ b/packages/views/settings/components/github-tab.test.tsx
@@ -4,6 +4,7 @@ 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";
+import enIssues from "../../locales/en/issues.json";
import enSettings from "../../locales/en/settings.json";
const mockUpdateWorkspace = vi.hoisted(() => vi.fn());
@@ -117,7 +118,7 @@ vi.mock("sonner", () => ({
import { GitHubTab } from "./github-tab";
const TEST_RESOURCES = {
- en: { common: enCommon, settings: enSettings },
+ en: { common: enCommon, issues: enIssues, settings: enSettings },
};
function I18nWrapper({ children }: { children: ReactNode }) {
@@ -155,18 +156,39 @@ describe("GitHubTab", () => {
expect(row.getByText(/e\.g\. MUL-123, is in its title or branch name, or follows “Closes” in its description/)).toBeTruthy();
});
- // 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", () => {
+ // MUL-7726: what a merge does is chosen here, with the other PR features.
+ it("picks the status a merge moves issues to, Done by default", () => {
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");
+ const select = screen.getByRole("combobox", { name: "After PRs merge, move the issue to" });
+ expect(select).toHaveTextContent("Done");
cleanup();
- workspaceRef.current.settings = { pr_auto_complete_enabled: false };
+ workspaceRef.current.settings = { pr_merge_status: "none" };
render(<GitHubTab />, { wrapper: I18nWrapper });
- expect(screen.getByText(/^Off · /)).toBeTruthy();
+ expect(screen.getByRole("combobox", { name: "After PRs merge, move the issue to" })).toHaveTextContent("Don’t change");
+ });
+
+ it("saves the chosen status into the workspace settings", async () => {
+ const user = userEvent.setup();
+ workspaceRef.current.settings = { github_enabled: true };
+ mockUpdateWorkspace.mockResolvedValue({ ...workspaceRef.current, settings: { github_enabled: true, pr_merge_status: "in_review" } });
+ render(<GitHubTab />, { wrapper: I18nWrapper });
+ await user.click(screen.getByRole("combobox", { name: "After PRs merge, move the issue to" }));
+ const inReview = await screen.findByRole("option", { name: "In Review" });
+ // A merge never blocks an issue.
+ expect(screen.queryByRole("option", { name: "Blocked" })).toBeNull();
+ await user.click(inReview);
+ await waitFor(() =>
+ expect(mockUpdateWorkspace).toHaveBeenCalledWith("workspace-1", {
+ settings: { github_enabled: true, pr_merge_status: "in_review" },
+ }),
+ );
+ });
+
+ it("greys out the merge status with the other features when GitHub is off", () => {
+ workspaceRef.current.settings = { github_enabled: false };
+ render(<GitHubTab />, { wrapper: I18nWrapper });
+ expect(screen.getByRole("combobox", { name: "After PRs merge, move the issue to" })).toBeDisabled();
});
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.tsx
index 60f3974f44..ee3695f80e 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 { CircleCheck, ExternalLink, GitCommitHorizontal, Link2, PanelRight } from "lucide-react";
+import { 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";
@@ -22,17 +22,14 @@ import { useAuthStore } from "@multica/core/auth";
import { useWorkspaceId } from "@multica/core/hooks";
import { useCurrentWorkspace } from "@multica/core/paths";
import { memberListOptions, workspaceKeys } from "@multica/core/workspace/queries";
-import {
- deriveGitHubSettings,
- derivePRAutoCompleteEnabled,
- githubInstallationsOptions,
-} from "@multica/core/github";
+import { deriveGitHubSettings, githubInstallationsOptions } from "@multica/core/github";
import { api } from "@multica/core/api";
import type { Workspace } from "@multica/core/types";
import { AppLink, useNavigation } from "../../navigation";
import { useT } from "../../i18n";
import { SettingsTab } from "./settings-layout";
import { GitHubMark } from "./github-mark";
+import { PRMergeStatusRow } from "./pr-merge-status-row";
type SettingsKey =
| "github_enabled"
@@ -67,7 +64,6 @@ 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);
@@ -296,32 +292,10 @@ export function GitHubTab() {
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>
+ {/* Shared by every code host; the self-hosted Git page shows the
+ same value. Greyed out with the rest of the GitHub features when
+ the master switch is off. */}
+ <PRMergeStatusRow canManage={canManage} disabled={!flags.enabled} />
</CardContent>
</Card>
</section>
diff --git a/packages/views/settings/components/issue-statuses-tab.test.tsx b/packages/views/settings/components/issue-statuses-tab.test.tsx
index 91ba0020e2..796be1ca04 100644
--- a/packages/views/settings/components/issue-statuses-tab.test.tsx
+++ b/packages/views/settings/components/issue-statuses-tab.test.tsx
@@ -25,7 +25,16 @@ vi.mock("@multica/core/api", async (importOriginal) => ({
...(await importOriginal<typeof import("@multica/core/api")>()),
api: { updateWorkspace },
}));
-vi.mock("../../navigation", () => ({ useNavigation: () => ({ push: navigatePush }) }));
+vi.mock("../../navigation", () => ({
+ useNavigation: () => ({
+ push: navigatePush,
+ pathname: "/acme/settings",
+ searchParams: new URLSearchParams("tab=issue-statuses"),
+ }),
+ AppLink: ({ href, children, className }: { href: string; children: React.ReactNode; className?: string }) => (
+ <a href={href} className={className}>{children}</a>
+ ),
+}));
vi.mock("../../issues/surface/issue-surface", () => ({
IssueSurfaceWithStore: ({ store, scope }: { store: { getState: () => { statusFilters: string[] } }; scope: { actorKind: string } }) =>
<div data-testid="inspection-list">{scope.actorKind}:{store.getState().statusFilters.join(",")}</div>,
@@ -121,38 +130,28 @@ afterEach(() => {
});
describe("IssueStatusesTab", () => {
- describe("PR auto-complete (MUL-7429)", () => {
+ describe("PR merge status badge (MUL-7726)", () => {
const BUILT_IN_DONE = entry({ id: "done", key: "done", name: "Done", category: "done", is_system: true, position: 0 });
+ const QA = entry({ key: "qa", name: "QA" });
+ const badgeLink = () => screen.getByText(en.issue_statuses.pr_auto_complete_badge).closest("a");
- it("saves the workspace setting as soon as the switch changes", async () => {
- workspaceSettings = { github_enabled: true };
- updateWorkspace.mockResolvedValue({ id: "ws-1", settings: {} });
+ it("badges Done by default and links to the GitHub setting", () => {
+ catalog = [BUILT_IN_DONE, QA];
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 },
- }),
- );
+ expect(screen.getAllByText(en.issue_statuses.pr_auto_complete_badge)).toHaveLength(1);
+ expect(badgeLink()?.getAttribute("href")).toBe("/acme/settings?tab=integrations&integration=github");
+ expect(badgeLink()?.closest(".group\\/row")).toHaveTextContent(en.issue_statuses.built_in_descriptions.done);
});
- it("badges the built-in Done row only while the setting is on", () => {
- catalog = [BUILT_IN_DONE];
+ it("moves the badge to the chosen status and drops it for no change", () => {
+ catalog = [BUILT_IN_DONE, QA];
+ workspaceSettings = { pr_merge_status: "qa" };
render(<IssueStatusesTab />);
- expect(screen.getByText(en.issue_statuses.pr_auto_complete_badge)).toBeInTheDocument();
+ expect(badgeLink()?.closest(".group\\/row")).toHaveTextContent("QA");
cleanup();
- workspaceSettings = { pr_auto_complete_enabled: false };
+ workspaceSettings = { pr_merge_status: "none" };
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");
});
});
diff --git a/packages/views/settings/components/issue-statuses-tab.tsx b/packages/views/settings/components/issue-statuses-tab.tsx
index ee76649a76..751f718acb 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, useQueryClient } from "@tanstack/react-query";
+import { useQuery } from "@tanstack/react-query";
import {
Archive,
ArrowLeft,
@@ -33,10 +33,8 @@ 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 { derivePRMergeStatus } 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";
@@ -59,7 +57,6 @@ 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";
@@ -107,7 +104,9 @@ 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 { SettingsCard, SettingsRow, SettingsSection, SettingsTab } from "./settings-layout";
+import { AppLink, useNavigation } from "../../navigation";
+import { SettingsTab } from "./settings-layout";
+import { settingsHref } from "./settings-navigation";
/**
* Workspace issue status catalog management (MUL-6243).
@@ -143,6 +142,7 @@ const EMPTY_DRAFT: StatusDraft = {
export function IssueStatusesTab() {
const { t } = useT("settings");
const wsId = useWorkspaceId();
+ const navigation = useNavigation();
const [showArchived, setShowArchived] = useState(false);
const [createCategory, setCreateCategory] = useState<IssueStatusCategory | null>(null);
@@ -161,7 +161,12 @@ 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());
+ // The status a merge moves issues to is set on the GitHub page (MUL-7726);
+ // its row carries a badge linking there.
+ const mergeTarget = derivePRMergeStatus(useCurrentWorkspace());
+ const mergeSettingsHref = settingsHref(navigation.pathname, navigation.searchParams, "integrations", {
+ integration: "github",
+ });
const groups = useMemo(
() =>
@@ -221,7 +226,8 @@ export function IssueStatusesTab() {
category={group.category}
entries={group.entries}
canManage={isAdmin}
- prAutoComplete={prAutoComplete}
+ mergeTarget={mergeTarget}
+ mergeSettingsHref={mergeSettingsHref}
onCreate={() => setCreateCategory(group.category)}
onEdit={(entry) => entry.is_system ? setShowBuiltInNotice(true) : setEditing(entry)}
onArchive={(entry) => {
@@ -235,8 +241,6 @@ export function IssueStatusesTab() {
)}
</div>
- <PRAutoCompleteSection canManage={isAdmin} />
-
<StatusEditorDialog
open={createCategory !== null}
onOpenChange={(open) => !open && setCreateCategory(null)}
@@ -277,7 +281,8 @@ function CategorySection({
category,
entries,
canManage,
- prAutoComplete,
+ mergeTarget,
+ mergeSettingsHref,
onCreate,
onEdit,
onArchive,
@@ -287,7 +292,8 @@ function CategorySection({
entries: IssueStatusEntry[];
canManage: boolean;
/** Badge the built-in Done row: PR auto-complete writes that status. */
- prAutoComplete: boolean;
+ mergeTarget: string;
+ mergeSettingsHref: string;
onCreate: () => void;
onEdit: (status: IssueStatusEntry) => void;
onArchive: (status: IssueStatusEntry) => void;
@@ -389,7 +395,7 @@ function CategorySection({
<StatusRow
key={entry.id}
entry={entry}
- autoCompleteBadge={prAutoComplete && entry.is_system && entry.key === "done"}
+ mergeBadgeHref={entry.key === mergeTarget && !entry.archived_at ? mergeSettingsHref : null}
label={entry.is_system ? labelOf(entry.key) : entry.name}
description={entry.is_system
? t(($) => $.issue_statuses.built_in_descriptions[entry.key as BuiltInIssueStatus])
@@ -418,7 +424,7 @@ function CategorySection({
function StatusRow({
entry,
- autoCompleteBadge,
+ mergeBadgeHref,
label,
description,
canManage,
@@ -431,7 +437,8 @@ function StatusRow({
onMoveDown,
}: {
entry: IssueStatusEntry;
- autoCompleteBadge: boolean;
+ /** Where the "set when PRs merge" badge links, or null for no badge. */
+ mergeBadgeHref: string | null;
label: string;
description: string;
canManage: boolean;
@@ -482,11 +489,14 @@ 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">
+ {mergeBadgeHref && (
+ <AppLink
+ href={mergeBadgeHref}
+ 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 transition-colors hover:bg-info/15 focus-visible:outline-2 focus-visible:outline-ring"
+ >
<Zap className="size-3" aria-hidden="true" />
{t(($) => $.issue_statuses.pr_auto_complete_badge)}
- </span>
+ </AppLink>
)}
{archived && (
<Tooltip>
@@ -885,65 +895,3 @@ 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/packages/views/settings/components/pr-merge-status-row.tsx b/packages/views/settings/components/pr-merge-status-row.tsx
new file mode 100644
index 0000000000..97d6056fac
--- /dev/null
+++ b/packages/views/settings/components/pr-merge-status-row.tsx
@@ -0,0 +1,140 @@
+"use client";
+
+import { useState } from "react";
+import { useQueryClient } from "@tanstack/react-query";
+import { toast } from "sonner";
+import { CircleOff, GitMerge } from "lucide-react";
+import { api } from "@multica/core/api";
+import { derivePRMergeStatus, PR_MERGE_STATUS_NONE } from "@multica/core/github";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
+import { useCurrentWorkspace } from "@multica/core/paths";
+import type { IssueStatusCategory, Workspace } from "@multica/core/types";
+import { workspaceKeys } from "@multica/core/workspace/queries";
+import { Label } from "@multica/ui/components/ui/label";
+import {
+ Select,
+ SelectContent,
+ SelectGroup,
+ SelectItem,
+ SelectLabel,
+ SelectSeparator,
+ SelectTrigger,
+ SelectValue,
+} from "@multica/ui/components/ui/select";
+import { StatusIcon } from "../../issues/components/status-icon";
+import { useStatusLabel } from "../../issues/utils/status-label";
+import { useT } from "../../i18n";
+
+/** The categories a merge may move an issue into, with their built-ins.
+ * Blocked is left out: a merge never blocks an issue. */
+const TARGET_CATEGORIES: { category: IssueStatusCategory; builtIns: string[] }[] = [
+ { category: "started", builtIns: ["in_progress", "in_review"] },
+ { category: "done", builtIns: ["done"] },
+];
+
+/**
+ * "After PRs merge, move the issue to" (MUL-7726): the one PR merge setting,
+ * shared by GitHub and self-hosted providers. It saves on change like the
+ * other integration switches and only affects merges from now on.
+ */
+export function PRMergeStatusRow({ canManage, disabled = false }: { canManage: boolean; disabled?: boolean }) {
+ const { t } = useT("settings");
+ const workspace = useCurrentWorkspace();
+ const wsId = useWorkspaceId();
+ const qc = useQueryClient();
+ const catalog = useIssueStatuses(wsId);
+ const statusLabel = useStatusLabel(wsId);
+ const [saving, setSaving] = useState(false);
+
+ // Built-ins are always offered: the server accepts them before the catalog
+ // is seeded, and the catalog may still be loading.
+ const groups = TARGET_CATEGORIES.map(({ category, builtIns }) => {
+ const listed = catalog.inCategory(category).map((entry) => entry.key).filter((key) => key !== "blocked");
+ return { category, keys: [...builtIns.filter((key) => !listed.includes(key)), ...listed] };
+ });
+ const stored = derivePRMergeStatus(workspace);
+ // A choice that no longer names an offered status (archived since) moves
+ // nothing on the server, so it reads as "no change" here too.
+ const value = !catalog.isLoaded || groups.some((group) => group.keys.includes(stored)) ? stored : PR_MERGE_STATUS_NONE;
+
+ async function persist(next: string) {
+ if (!workspace || saving || next === value) return;
+ setSaving(true);
+ try {
+ const updated = await api.updateWorkspace(workspace.id, {
+ settings: { ...((workspace.settings as Record<string, unknown>) ?? {}), pr_merge_status: 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);
+ }
+ }
+
+ const option = (key: string) =>
+ key === PR_MERGE_STATUS_NONE ? (
+ <>
+ <CircleOff className="text-muted-foreground" />
+ {t(($) => $.pr_merge_status.none)}
+ </>
+ ) : (
+ <>
+ <StatusIcon
+ status={key}
+ category={catalog.categoryOf(key)}
+ color={catalog.colorOf(key)}
+ icon={catalog.iconOf(key)}
+ className="size-3.5"
+ />
+ {statusLabel(key)}
+ </>
+ );
+
+ return (
+ <div className="flex items-start 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">
+ <GitMerge className="h-4 w-4" />
+ </div>
+ <div className="space-y-1">
+ <Label htmlFor="pr-merge-status" className="text-body font-medium">
+ {t(($) => $.pr_merge_status.label)}
+ </Label>
+ <p className="text-body text-muted-foreground">{t(($) => $.pr_merge_status.description)}</p>
+ </div>
+ </div>
+ <Select
+ items={[
+ { value: PR_MERGE_STATUS_NONE, label: t(($) => $.pr_merge_status.none) },
+ ...groups.flatMap((group) => group.keys.map((key) => ({ value: key, label: statusLabel(key) }))),
+ ]}
+ value={value}
+ onValueChange={(next) => next && void persist(next)}
+ disabled={!canManage || disabled || saving}
+ >
+ <SelectTrigger id="pr-merge-status" className="w-48 shrink-0" aria-busy={saving || undefined}>
+ <SelectValue>{() => option(value)}</SelectValue>
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value={PR_MERGE_STATUS_NONE}>{option(PR_MERGE_STATUS_NONE)}</SelectItem>
+ {groups.map((group) => (
+ <SelectGroup key={group.category}>
+ <SelectSeparator />
+ <SelectLabel>{t(($) => $.issue_statuses.category_labels[group.category])}</SelectLabel>
+ {group.keys.map((key) => (
+ <SelectItem key={key} value={key}>
+ {option(key)}
+ </SelectItem>
+ ))}
+ </SelectGroup>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ );
+}
diff --git a/packages/views/settings/components/vcs-tab.tsx b/packages/views/settings/components/vcs-tab.tsx
index 188c735b3f..d59aea0e46 100644
--- a/packages/views/settings/components/vcs-tab.tsx
+++ b/packages/views/settings/components/vcs-tab.tsx
@@ -30,6 +30,7 @@ import { vcsConnectionsOptions } from "@multica/core/vcs";
import { api } from "@multica/core/api";
import type { ConnectVCSResponse, VCSProvider } from "@multica/core/types";
import { useT } from "../../i18n";
+import { PRMergeStatusRow } from "./pr-merge-status-row";
const PROVIDERS: VCSProvider[] = ["forgejo", "gitea", "gitlab"];
const PROVIDER_LABELS: Record<VCSProvider, string> = {
@@ -169,6 +170,16 @@ export function VCSTab() {
</div>
)}
+ {/* The PR merge setting is shared with GitHub; shown here once a
+ provider is connected, since that is when it starts to matter. */}
+ {connections.length > 0 && (
+ <Card className="py-0">
+ <CardContent className="px-0">
+ <PRMergeStatusRow canManage={canManage} />
+ </CardContent>
+ </Card>
+ )}
+
{justConnected && (
<Card className="border-primary/40">
<CardContent className="space-y-3">
diff --git a/server/internal/handler/github.go b/server/internal/handler/github.go
index 27076ab5ec..8b0e541dbe 100644
--- a/server/internal/handler/github.go
+++ b/server/internal/handler/github.go
@@ -1023,7 +1023,7 @@ func (h *Handler) ListPullRequestsForIssue(w http.ResponseWriter, r *http.Reques
}
writeJSON(w, http.StatusOK, map[string]any{
"pull_requests": out,
- "auto_complete": prAutoCompleteToResponse(ws, decision),
+ "auto_complete": prAutoCompleteToResponse(decision),
})
}
@@ -1062,10 +1062,10 @@ 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. A closing keyword is what lets a merged PR complete its issue; a bare
-// title prefix like "MUL-1: ..." or a branch reference links the PR but never
-// completes the issue on its own.
+// strict on adjacency — "Fix MUL-1" names MUL-1, but "Fix login MUL-1" does
+// not. It is the one way a PR body links an issue; a bare body mention links
+// nothing. Since MUL-7726 the keyword only links: what a merge does is the
+// workspace's choice, not the PR text's.
var closingIdentifierRe = regexp.MustCompile(
`(?i)\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)[:\s]+([a-z][a-z0-9]{0,9})-(\d+)\b`,
)
@@ -1344,9 +1344,6 @@ type prLinkPolicy struct {
// ambiguous lists identifiers that resolved in more than one auto-linking
// workspace.
ambiguous map[string]bool
- // sole maps an identifier to the workspace proven to be the only bound one
- // resolving it, auto-link on or off (see permitsClose).
- sole map[string]string
}
// permits reports whether workspaceID may link identifier.
@@ -1358,35 +1355,17 @@ func (c prLinkPolicy) permits(identifier, workspaceID string) bool {
return ok && owner == workspaceID
}
-// permitsClose reports whether workspaceID may act on a closing keyword for
-// identifier on the links it already has. Auto-link decides which links get
-// created, not whether their keywords count, so a workspace that turned it off
-// still acts when no other bound workspace resolves the identifier. The
-// auto-linking owner acts too: another resolver with auto-link off holds only
-// links a person added, and does not act.
-func (c prLinkPolicy) permitsClose(identifier, workspaceID string) bool {
- if c.unrestricted {
- return true
- }
- if owner, ok := c.owner[identifier]; ok && owner == workspaceID {
- return true
- }
- sole, ok := c.sole[identifier]
- return ok && sole == workspaceID
-}
-
// resolvePRLinkPolicy determines, before any workspace writes, which claimed
-// identifiers on this PR may link, or carry close intent, and in which
-// workspace. An identifier is allowed only when exactly one bound workspace
-// was proven to resolve it (see permits and permitsClose for which count);
-// misjudging "unique" as "ambiguous" costs a link a person can add by hand,
-// while the reverse would complete someone else's issue.
+// identifiers on this PR may link, and in which workspace. An identifier is
+// allowed only when exactly one auto-linking bound workspace was proven to
+// resolve it; misjudging "unique" as "ambiguous" costs a link a person can add
+// by hand, while the reverse would move someone else's issue on merge.
func (h *Handler) resolvePRLinkPolicy(ctx context.Context, insts []db.GithubInstallation, p *ghPullRequestPayload) prLinkPolicy {
if len(insts) < 2 {
return prLinkPolicy{unrestricted: true}
}
- idents, _ := prClaimedIdentifiers(p.PullRequest.Title, p.PullRequest.Body, p.PullRequest.Head.Ref)
- policy := prLinkPolicy{owner: map[string]string{}, ambiguous: map[string]bool{}, sole: map[string]string{}}
+ idents := prClaimedIdentifiers(p.PullRequest.Title, p.PullRequest.Body, p.PullRequest.Head.Ref)
+ policy := prLinkPolicy{owner: map[string]string{}, ambiguous: map[string]bool{}}
if len(idents) == 0 {
return policy
}
@@ -1438,9 +1417,6 @@ func (h *Handler) resolvePRLinkPolicy(ctx context.Context, insts []db.GithubInst
}
}
for id, all := range resolvers {
- if len(all) == 1 {
- policy.sole[id] = all[0].workspaceID
- }
// A workspace with auto-link off never writes a link row, so it is not
// a competing claimant for the link.
var wss []string
@@ -1624,7 +1600,7 @@ func (h *Handler) mirrorPullRequestForWorkspace(ctx context.Context, wsID pgtype
ws, err := h.Queries.GetWorkspace(ctx, wsID)
if err == nil && githubFeaturesEnabled(ws) && !linkPolicy.indeterminate {
touched := map[pgtype.UUID]struct{}{}
- idents, closing := prClaimedIdentifiers(p.PullRequest.Title, p.PullRequest.Body, p.PullRequest.Head.Ref)
+ idents := prClaimedIdentifiers(p.PullRequest.Title, p.PullRequest.Body, p.PullRequest.Head.Ref)
if autoLink, _ := autoLinkPRsEnabledForWorkspace(ws); autoLink {
linkedIssueIDs, touched = h.reconcileAutoLinks(ctx, ws, pr.ID, state, prAutoLinkInput{
idents: idents,
@@ -1641,18 +1617,6 @@ func (h *Handler) mirrorPullRequestForWorkspace(ctx context.Context, wsID pgtype
},
})
}
- // Close intent is read from the PR text whether or not auto-link is on:
- // the flag decides which links get created, not whether an existing
- // link's keyword still stands. The merge/close event itself still
- // records the text; later edits of a merged or closed PR do not.
- if p.Action == "closed" || (state != "merged" && state != "closed") {
- if err := h.Queries.SyncPullRequestCloseIntent(ctx, db.SyncPullRequestCloseIntentParams{
- PullRequestID: pr.ID,
- ClosingIssueIds: h.closingIssueIDs(ctx, ws, closing, func(id string) bool { return linkPolicy.permitsClose(id, workspaceID) }),
- }); err != nil {
- slog.Warn("github: sync close intent failed", "err", err)
- }
- }
// A merge is a PR event for every issue this PR is linked to, manual
// links included.
if state == "merged" && prevState != "merged" {
@@ -1702,8 +1666,7 @@ type prAutoLinkInput struct {
// - 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, and close intent is not either (see
-// closingIssueIDs).
+// 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)
@@ -1768,27 +1731,6 @@ func (h *Handler) reconcileAutoLinks(ctx context.Context, ws db.Workspace, prID
return linked, touched
}
-// closingIssueIDs resolves the identifiers a PR closes with a keyword to this
-// workspace's issues, for the PR-wide close_intent sync: every link of the PR,
-// automatic or manual, gets close intent exactly when its issue is in this
-// list, so a keyword removed from the text stops counting. It honors the
-// delivery's cross-workspace verdict (permitsClose on GitHub). Close intent
-// only decides anything once the PR merges — a PR event of its own — so the
-// sync is not one. Never nil: an empty list clears every link's close intent.
-func (h *Handler) closingIssueIDs(ctx context.Context, ws db.Workspace, closing []string, permits func(string) bool) []pgtype.UUID {
- ids := make([]pgtype.UUID, 0, len(closing))
- prefix := issuePrefixForWorkspace(ws)
- for _, id := range closing {
- if !permits(id) {
- continue
- }
- if issue, ok := h.lookupIssueByIdentifier(ctx, ws.ID, prefix, id); ok {
- ids = append(ids, issue.ID)
- }
- }
- return ids
-}
-
// 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):
@@ -1875,8 +1817,8 @@ func extractIdentifiers(parts ...string) []string {
}
// extractClosingIdentifiers pulls every identifier that appears immediately
-// after a closing keyword. Callers pass the title and body only: a branch name
-// is not natural language, so "fix/mul-1-login" is a reference, not a close.
+// after a closing keyword. Callers pass the title and body only: in a branch
+// name any identifier links already.
func extractClosingIdentifiers(parts ...string) []string {
return extractMatchedIdentifiers(closingIdentifierRe, parts...)
}
@@ -1897,19 +1839,17 @@ func extractMatchedIdentifiers(re *regexp.Regexp, parts ...string) []string {
return out
}
-// prClaimedIdentifiers returns the identifiers a PR claims, and which of them
-// it closes. The title and branch name link an issue; a closing keyword in the
-// title or body ("Closes MUL-1") links it too and marks the PR as the one that
-// completes it. A bare mention in the body claims nothing.
-func prClaimedIdentifiers(title, body, branch string) (idents, closing []string) {
- idents = extractIdentifiers(title, branch)
- closing = extractClosingIdentifiers(title, body)
- for _, id := range closing {
+// prClaimedIdentifiers returns the identifiers a PR claims. The title and
+// branch name link an issue, and so does a closing keyword in the body
+// ("Closes MUL-1"). A bare mention in the body claims nothing.
+func prClaimedIdentifiers(title, body, branch string) []string {
+ idents := extractIdentifiers(title, branch)
+ for _, id := range extractClosingIdentifiers(title, body) {
if !slices.Contains(idents, id) {
idents = append(idents, id)
}
}
- return idents, closing
+ return idents
}
// autoLinkPRsEnabledForWorkspace reports whether the workspace allows the
diff --git a/server/internal/handler/github_test.go b/server/internal/handler/github_test.go
index cec466fb00..4e00deb5fb 100644
--- a/server/internal/handler/github_test.go
+++ b/server/internal/handler/github_test.go
@@ -154,9 +154,9 @@ func TestExtractClosingIdentifiers(t *testing.T) {
}
// TestPRClaimedIdentifiers: the title and branch link, a closing keyword in the
-// title or body links and closes, and a bare body mention claims nothing.
+// title or body links too, and a bare body mention claims nothing.
func TestPRClaimedIdentifiers(t *testing.T) {
- idents, closing := prClaimedIdentifiers(
+ idents := prClaimedIdentifiers(
"ABC-1: Lorem Ipsum",
"Closes ABC-4. Follow up work planned in ABC-2.",
"fix/abc-3-login",
@@ -164,9 +164,6 @@ func TestPRClaimedIdentifiers(t *testing.T) {
if want := []string{"ABC-1", "ABC-3", "ABC-4"}; !reflect.DeepEqual(idents, want) {
t.Errorf("idents = %v, want %v", idents, want)
}
- if want := []string{"ABC-4"}; !reflect.DeepEqual(closing, want) {
- t.Errorf("closing = %v, want %v", closing, want)
- }
}
func TestDerivePRState(t *testing.T) {
@@ -1046,8 +1043,8 @@ func unlinkPRForTest(t *testing.T, issueID, prID string) {
}
// linkMergedGitHubPRForTest mirrors a merged PR in the test workspace and
-// links it to issueID automatically with a closing keyword, for tests that
-// drive the completion path without a webhook.
+// links it to issueID automatically, for tests that drive the merge
+// automation without a webhook.
func linkMergedGitHubPRForTest(t *testing.T, issueID, repo string) {
t.Helper()
ctx := context.Background()
@@ -1068,9 +1065,6 @@ func linkMergedGitHubPRForTest(t *testing.T, issueID, repo string) {
if _, err := testHandler.Queries.LinkIssueToPullRequest(ctx, db.LinkIssueToPullRequestParams{IssueID: parseUUID(issueID), PullRequestID: pr.ID}); err != nil {
t.Fatalf("link: %v", err)
}
- if err := testHandler.Queries.SyncPullRequestCloseIntent(ctx, db.SyncPullRequestCloseIntentParams{PullRequestID: pr.ID, ClosingIssueIds: []pgtype.UUID{parseUUID(issueID)}}); err != nil {
- t.Fatalf("close intent: %v", err)
- }
}
func githubPRIDForTest(t *testing.T, repo string, number int32) string {
@@ -1084,10 +1078,11 @@ func githubPRIDForTest(t *testing.T, repo string, number int32) string {
return uuidToString(pr.ID)
}
-// TestWebhook_OnlyClosingKeywordCompletes is the repro from #3264: a title
-// identifier links but does not complete, a body "Closes" links and completes,
-// and a passing body mention ("Follow up in") links nothing.
-func TestWebhook_OnlyClosingKeywordCompletes(t *testing.T) {
+// TestWebhook_EveryLinkedIssueMovesOnMerge is the repro from #3264 under the
+// MUL-7726 rule: a title identifier and a body "Closes" both link, so the
+// merge moves both issues, while a passing body mention ("Follow up in") links
+// nothing and moves nothing.
+func TestWebhook_EveryLinkedIssueMovesOnMerge(t *testing.T) {
if testHandler == nil {
t.Skip("handler test fixture not initialized (no DB?)")
}
@@ -1106,15 +1101,9 @@ func TestWebhook_OnlyClosingKeywordCompletes(t *testing.T) {
if n := linkedPRCountForTest(t, issue.ID); n != 1 {
t.Errorf("%s should link, got %d rows", issue.Identifier, n)
}
- }
- if got := issueStatusForTest(t, primary.ID); got != "in_progress" {
- t.Errorf("title-only issue: status = %q, want in_progress", got)
- }
- if got := prAutoCompleteStateForTest(t, primary.ID); got.State != prAutoCompleteNoCloseIntent {
- t.Errorf("title-only issue: auto_complete = %+v, want no_close_intent", got)
- }
- if got := issueStatusForTest(t, closes.ID); got != "done" {
- t.Errorf("closing-keyword issue: status = %q, want done", got)
+ if got := issueStatusForTest(t, issue.ID); got != "done" {
+ t.Errorf("%s: status = %q, want done", issue.Identifier, got)
+ }
}
if n := linkedPRCountForTest(t, followUp.ID); n != 0 {
t.Errorf("a passing body mention must not link, got %d rows", n)
@@ -1124,10 +1113,10 @@ func TestWebhook_OnlyClosingKeywordCompletes(t *testing.T) {
}
}
-// TestWebhook_TitleAndBranchLinkWithoutCompleting: a title prefix or a branch
-// name links the PR, but only a closing keyword completes the issue — and a
-// branch name is never read as one.
-func TestWebhook_TitleAndBranchLinkWithoutCompleting(t *testing.T) {
+// TestWebhook_TitleBranchAndKeywordLinksAllMove: a title identifier, a branch
+// name and a title closing keyword each link the PR, and the merge moves the
+// issue whichever way it was linked.
+func TestWebhook_TitleBranchAndKeywordLinksAllMove(t *testing.T) {
if testHandler == nil {
t.Skip("handler test fixture not initialized (no DB?)")
}
@@ -1146,15 +1135,10 @@ func TestWebhook_TitleAndBranchLinkWithoutCompleting(t *testing.T) {
if n := linkedPRCountForTest(t, issue.ID); n != 1 {
t.Errorf("%s: expected 1 linked PR, got %d", issue.Identifier, n)
}
- }
- for _, issue := range []IssueResponse{byTitle, byBranch} {
- if got := issueStatusForTest(t, issue.ID); got != "in_progress" {
- t.Errorf("%s: status = %q, want in_progress", issue.Identifier, got)
+ if got := issueStatusForTest(t, issue.ID); got != "done" {
+ t.Errorf("%s: status = %q, want done", issue.Identifier, got)
}
}
- if got := issueStatusForTest(t, byTitleKeyword.ID); got != "done" {
- t.Errorf("title closing keyword: status = %q, want done", 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)
@@ -1248,97 +1232,13 @@ func TestWebhook_IdentifierRemovedBeforeMergeUnlinks(t *testing.T) {
}
}
-// TestWebhook_CloseIntentFollowsPRTextUntilMerge: while the PR is open its
-// close intent follows the text — downgrading "Closes" to a plain mention keeps
-// the title link but not the completion, and adding it back restores it. It
-// follows the PR on a manual link too.
-func TestWebhook_CloseIntentFollowsPRTextUntilMerge(t *testing.T) {
- if testHandler == nil {
- t.Skip("handler test fixture not initialized (no DB?)")
- }
- secret := "close-intent-follows-secret"
- t.Setenv("GITHUB_WEBHOOK_SECRET", secret)
- const installationID int64 = 30264010
- byTitle := prAutoCompleteTestIssue(t, "close intent follows text", installationID)
- manual := prAutoCompleteTestIssue(t, "close intent on a manual link", 0)
-
- title := byTitle.Identifier + ": login flow"
- firePRWebhook(t, secret, installationID, 1, title, "Closes "+byTitle.Identifier, "feat/login", "opened")
- if got := prAutoCompleteStateForTest(t, byTitle.ID); got.State != prAutoCompleteWaiting {
- t.Fatalf("auto_complete = %+v, want waiting", got)
- }
- firePRWebhook(t, secret, installationID, 1, title, "Related to "+byTitle.Identifier, "feat/login", "edited")
- if got := prAutoCompleteStateForTest(t, byTitle.ID); got.State != prAutoCompleteNoCloseIntent {
- t.Fatalf("after dropping the keyword: auto_complete = %+v, want no_close_intent", got)
- }
- firePRWebhook(t, secret, installationID, 1, title, "Fixes "+byTitle.Identifier, "feat/login", "edited")
- firePRWebhook(t, secret, installationID, 1, title, "Fixes "+byTitle.Identifier, "feat/login", "merged")
- if got := issueStatusForTest(t, byTitle.ID); got != "done" {
- t.Errorf("keyword restored before merge: status = %q, want done", got)
- }
-
- firePRWebhook(t, secret, installationID, 2, "Session refactor", "", "refactor/session", "opened")
- req := withURLParam(newRequest("POST", "/api/issues/"+manual.ID+"/pull-requests", map[string]any{"url": "https://github.com/acme/widget/pull/2"}), "id", manual.ID)
- testutil.Call(t, testHandler.LinkIssuePullRequest, req).Want(http.StatusOK)
- firePRWebhook(t, secret, installationID, 2, "Session refactor", "Closes "+manual.Identifier, "refactor/session", "edited")
- firePRWebhook(t, secret, installationID, 2, "Session refactor", "Closes "+manual.Identifier, "refactor/session", "merged")
- if got := issueStatusForTest(t, manual.ID); got != "done" {
- t.Errorf("manual link whose PR says Closes: status = %q, want done", got)
- }
- if list := listIssuePRsForTest(t, manual.ID); len(list.PullRequests) != 1 || list.PullRequests[0].LinkSource != "manual" {
- t.Errorf("pull_requests = %+v, want the manual link kept", list.PullRequests)
- }
-}
-
-// TestWebhook_RemovedKeywordStopsCounting: dropping "Closes" from the PR text
-// clears close intent on every link of the PR, not only on identifiers the PR
-// still claims — a manual link, or an automatic link whose merge event (which
-// carries the final text) arrives before the edit event (PR #8794 review).
-func TestWebhook_RemovedKeywordStopsCounting(t *testing.T) {
- if testHandler == nil {
- t.Skip("handler test fixture not initialized (no DB?)")
- }
- for _, tc := range []struct {
- name string
- manual bool
- editBeforeMerge bool
- }{
- {"manual link, keyword edited to a mention", true, true},
- {"automatic link, merge arrives before the edit", false, false},
- } {
- t.Run(tc.name, func(t *testing.T) {
- const secret = "removed-keyword-secret"
- const installationID int64 = 30264011
- t.Setenv("GITHUB_WEBHOOK_SECRET", secret)
- issue := prAutoCompleteTestIssue(t, tc.name, installationID)
-
- firePRWebhook(t, secret, installationID, 1, "Session refactor", "Closes "+issue.Identifier, "refactor/session", "opened")
- if tc.manual {
- req := withURLParam(newRequest("POST", "/api/issues/"+issue.ID+"/pull-requests", map[string]any{"url": "https://github.com/acme/widget/pull/1"}), "id", issue.ID)
- testutil.Call(t, testHandler.LinkIssuePullRequest, req).Want(http.StatusOK)
- }
- if tc.editBeforeMerge {
- firePRWebhook(t, secret, installationID, 1, "Session refactor", "Related to "+issue.Identifier, "refactor/session", "edited")
- if got := prAutoCompleteStateForTest(t, issue.ID); got.State != prAutoCompleteNoCloseIntent {
- t.Errorf("after removing the keyword: auto_complete = %+v, want no_close_intent", got)
- }
- }
- firePRWebhook(t, secret, installationID, 1, "Session refactor", "Related to "+issue.Identifier, "refactor/session", "merged")
- if got := issueStatusForTest(t, issue.ID); got != "in_progress" {
- t.Errorf("merged without a closing keyword: status = %q, want in_progress", got)
- }
- })
- }
-}
-
-// TestWebhook_AutoLinkOffStillReadsCloseIntent: turning auto-link off stops
-// new links, not the reading of existing links' keywords — otherwise a
-// keyword removed afterwards would still complete the issue (PR #8794 review).
-func TestWebhook_AutoLinkOffStillReadsCloseIntent(t *testing.T) {
+// TestWebhook_AutoLinkOffKeepsExistingLinksMoving: turning auto-link off stops
+// new links, not what the merge does for links the issue already has.
+func TestWebhook_AutoLinkOffKeepsExistingLinksMoving(t *testing.T) {
if testHandler == nil {
t.Skip("handler test fixture not initialized (no DB?)")
}
- const secret = "auto-link-off-close-intent-secret"
+ const secret = "auto-link-off-existing-secret"
const installationID int64 = 30264012
t.Setenv("GITHUB_WEBHOOK_SECRET", secret)
issue := prAutoCompleteTestIssue(t, "auto-link off after linking", installationID)
@@ -1349,20 +1249,18 @@ func TestWebhook_AutoLinkOffStillReadsCloseIntent(t *testing.T) {
})
title := issue.Identifier + ": session refactor"
- firePRWebhook(t, secret, installationID, 1, title, "Closes "+issue.Identifier, "refactor/session", "opened")
+ firePRWebhook(t, secret, installationID, 1, title, "", "refactor/session", "opened")
dbfx.Exec(t, `UPDATE workspace SET settings = COALESCE(settings, '{}'::jsonb) || '{"github_auto_link_prs_enabled": false}'::jsonb WHERE id = $1`, testWorkspaceID)
- firePRWebhook(t, secret, installationID, 1, title, "", "refactor/session", "edited")
firePRWebhook(t, secret, installationID, 1, title, "", "refactor/session", "merged")
- if got := issueStatusForTest(t, issue.ID); got != "in_progress" {
- t.Errorf("keyword removed while auto-link was off: status = %q, want in_progress", got)
+ if got := issueStatusForTest(t, issue.ID); got != "done" {
+ t.Errorf("merge after auto-link was turned off: status = %q, want done", got)
}
}
-// TestWebhook_PostMergeEditLinksWithoutCompleting: adding a closing keyword to
-// a merged PR links it, but close intent is decided at merge time, so the
-// issue does not complete. Removing it again after merge keeps the link: the
-// work landed.
-func TestWebhook_PostMergeEditLinksWithoutCompleting(t *testing.T) {
+// TestWebhook_PostMergeEditLinksAndMoves: adding a closing keyword to a merged
+// PR links it, and the new link is a PR event, so the issue moves. Removing it
+// again after merge keeps the link: the work landed.
+func TestWebhook_PostMergeEditLinksAndMoves(t *testing.T) {
if testHandler == nil {
t.Skip("handler test fixture not initialized (no DB?)")
}
@@ -1379,11 +1277,8 @@ func TestWebhook_PostMergeEditLinksWithoutCompleting(t *testing.T) {
if n := linkedPRCountForTest(t, created.ID); n != 1 {
t.Fatalf("post-merge edit should link, got %d rows", n)
}
- if got := issueStatusForTest(t, created.ID); got != "in_progress" {
- t.Errorf("status = %q, want in_progress", got)
- }
- if got := prAutoCompleteStateForTest(t, created.ID); got.State != prAutoCompleteNoCloseIntent {
- t.Errorf("auto_complete = %+v, want no_close_intent", got)
+ if got := issueStatusForTest(t, created.ID); got != "done" {
+ t.Errorf("status = %q, want done", got)
}
firePRWebhook(t, secret, installationID, 1, "Dependency bump", "", "chore/bump", "edited_merged")
if n := linkedPRCountForTest(t, created.ID); n != 1 {
@@ -1495,11 +1390,12 @@ func TestLinkIssuePullRequest_ByURL(t *testing.T) {
if len(list.PullRequests) != 1 || list.PullRequests[0].LinkSource != "manual" {
t.Fatalf("pull_requests = %+v, want one manual link", list.PullRequests)
}
- if got := issueStatusForTest(t, created.ID); got != "in_progress" {
- t.Errorf("linking a merged PR without a closing keyword: status = %q, want in_progress", got)
+ // Linking is a PR event: with every linked PR merged, the issue moves.
+ if got := issueStatusForTest(t, created.ID); got != "done" {
+ t.Errorf("linking a merged PR by hand: status = %q, want done", got)
}
- if list.AutoComplete.State != prAutoCompleteNoCloseIntent {
- t.Errorf("auto_complete = %+v, want no_close_intent", list.AutoComplete)
+ if list.AutoComplete.State != prAutoCompleteTerminal {
+ t.Errorf("auto_complete = %+v, want terminal", list.AutoComplete)
}
firePRWebhook(t, secret, installationID, 41, "Refactor session helper (renamed)", "", "refactor/session", "edited_merged")
if n := linkedPRCountForTest(t, created.ID); n != 1 {
@@ -1507,46 +1403,56 @@ func TestLinkIssuePullRequest_ByURL(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.
+// setWorkspacePRMergeStatusForTest pins settings.pr_merge_status for the test
+// workspace and restores the previous settings afterwards. An empty value
+// removes the key (the Done default).
+func setWorkspacePRMergeStatusForTest(t *testing.T, value string) {
+ t.Helper()
+ var previous []byte
+ dbfx.QueryRow(t, `SELECT settings FROM workspace WHERE id = $1`, testWorkspaceID).Scan(&previous)
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `UPDATE workspace SET settings = $1 WHERE id = $2`, previous, testWorkspaceID)
+ })
+ if value == "" {
+ dbfx.Exec(t, `UPDATE workspace SET settings = settings - 'pr_merge_status' WHERE id = $1`, testWorkspaceID)
+ return
+ }
+ dbfx.Exec(t, `UPDATE workspace SET settings = COALESCE(settings, '{}'::jsonb) || jsonb_build_object('pr_merge_status', $2::text) WHERE id = $1`, testWorkspaceID, value)
+}
+
+// TestPRAutoComplete_WorkspaceAndIssueSwitches: "none" keeps PRs linked but
+// writes no status, and choosing a status later moves nothing retroactively.
+// The per-issue switch does the same for one issue and is recorded on the
+// timeline. Neither switch is reported on a finished issue.
func TestPRAutoComplete_WorkspaceAndIssueSwitches(t *testing.T) {
if testHandler == nil {
t.Skip("handler test fixture not initialized (no DB?)")
}
- ctx := context.Background()
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)
+ setWorkspacePRMergeStatusForTest(t, "none")
- var previous []byte
- dbfx.QueryRow(t, `SELECT settings FROM workspace WHERE id = $1`, testWorkspaceID).Scan(&previous)
- t.Cleanup(func() {
- 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)
-
- firePRWebhook(t, secret, installationID, 1, "Work", "Closes "+wsOff.Identifier, "feat/one", "merged")
+ 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)
+ t.Fatalf("\"none\" must still link, got %d rows", n)
}
if got := issueStatusForTest(t, wsOff.ID); got != "in_progress" {
- t.Fatalf("setting off: status = %q, want in_progress", got)
+ t.Fatalf("\"none\": 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 got := prAutoCompleteStateForTest(t, wsOff.ID); got.State != prAutoCompleteWorkspaceDisabled || got.WorkspaceEnabled || got.TargetStatus != "none" {
+ t.Fatalf("auto_complete = %+v, want workspace_disabled with target none", got)
}
- dbfx.Exec(t, `UPDATE workspace SET settings = settings || '{"pr_auto_complete_enabled": true}'::jsonb WHERE id = $1`, testWorkspaceID)
+ dbfx.Exec(t, `UPDATE workspace SET settings = settings - 'pr_merge_status' 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)
+ t.Fatalf("choosing a status must not move history, got %q", got)
}
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, "Work", "Closes "+issueOff.Identifier, "feat/two", "merged")
+ 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)
}
@@ -1558,7 +1464,160 @@ func TestPRAutoComplete_WorkspaceAndIssueSwitches(t *testing.T) {
if recorded != 1 {
t.Errorf("expected the switch change on the timeline, got %d entries", recorded)
}
- _ = ctx
+ dbfx.Exec(t, `UPDATE issue SET status = 'done' WHERE id = $1`, issueOff.ID)
+ if got := prAutoCompleteStateForTest(t, issueOff.ID); got.State != prAutoCompleteTerminal || !got.IssueDisabled {
+ t.Fatalf("done issue, switch off: auto_complete = %+v, want terminal", got)
+ }
+}
+
+// TestPRAutoComplete_TargetStatus: the workspace picks the status a merge
+// moves an issue to. A custom started status works like Done; an issue already
+// in the target reports at_target and is not written; a choice that no longer
+// names a live started or done status, or names Blocked, moves nothing.
+func TestPRAutoComplete_TargetStatus(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("handler test fixture not initialized (no DB?)")
+ }
+ secret := "target-status-secret"
+ t.Setenv("GITHUB_WEBHOOK_SECRET", secret)
+ const installationID int64 = 30264013
+ regress := createTestCustomStatus(t, "awaiting_regression", "started")
+ moved := prAutoCompleteTestIssue(t, "moves to a custom status", installationID)
+ inReview := prAutoCompleteTestIssue(t, "already in review", 0)
+ setWorkspacePRMergeStatusForTest(t, regress.Key)
+
+ firePRWebhook(t, secret, installationID, 1, moved.Identifier+": fix", "", "fix/one", "opened")
+ if got := prAutoCompleteStateForTest(t, moved.ID); got.State != prAutoCompleteWaiting || got.TargetStatus != regress.Key || !got.WorkspaceEnabled {
+ t.Fatalf("auto_complete = %+v, want waiting for %s", got, regress.Key)
+ }
+ firePRWebhook(t, secret, installationID, 1, moved.Identifier+": fix", "", "fix/one", "merged")
+ if got := issueStatusForTest(t, moved.ID); got != regress.Key {
+ t.Fatalf("status = %q, want %s", got, regress.Key)
+ }
+ if got := prAutoCompleteStateForTest(t, moved.ID); got.State != prAutoCompleteAtTarget {
+ t.Fatalf("after the move: auto_complete = %+v, want at_target", got)
+ }
+
+ dbfx.Exec(t, `UPDATE workspace SET settings = settings || '{"pr_merge_status": "in_review"}'::jsonb WHERE id = $1`, testWorkspaceID)
+ dbfx.Exec(t, `UPDATE issue SET status = 'in_review' WHERE id = $1`, inReview.ID)
+ firePRWebhook(t, secret, installationID, 2, inReview.Identifier+": fix", "", "fix/two", "opened")
+ if got := prAutoCompleteStateForTest(t, inReview.ID); got.State != prAutoCompleteAtTarget {
+ t.Fatalf("issue already in the target: auto_complete = %+v, want at_target", got)
+ }
+
+ for _, value := range []string{"blocked", "todo", "cancelled", "no_such_status"} {
+ dbfx.Exec(t, `UPDATE workspace SET settings = settings || jsonb_build_object('pr_merge_status', $2::text) WHERE id = $1`, testWorkspaceID, value)
+ if got := prAutoCompleteStateForTest(t, inReview.ID); got.State != prAutoCompleteWorkspaceDisabled || got.TargetStatus != "none" {
+ t.Errorf("target %q: auto_complete = %+v, want workspace_disabled", value, got)
+ }
+ }
+ dbfx.Exec(t, `UPDATE issue_status SET archived_at = now() WHERE id = $1`, regress.ID)
+ dbfx.Exec(t, `UPDATE workspace SET settings = settings || jsonb_build_object('pr_merge_status', $2::text) WHERE id = $1`, testWorkspaceID, regress.Key)
+ dbfx.Exec(t, `UPDATE issue SET status = 'in_progress' WHERE id = $1`, inReview.ID)
+ firePRWebhook(t, secret, installationID, 2, inReview.Identifier+": fix", "", "fix/two", "merged")
+ if got := issueStatusForTest(t, inReview.ID); got != "in_progress" {
+ t.Errorf("archived target: status = %q, want in_progress", got)
+ }
+}
+
+func TestPRMergeStatusSetting(t *testing.T) {
+ for _, tc := range []struct {
+ settings string
+ want string
+ }{
+ {"", "done"},
+ {`{}`, "done"},
+ {`{"pr_merge_status": "none"}`, "none"},
+ {`{"pr_merge_status": " In_Review "}`, "in_review"},
+ {`{"pr_merge_status": ""}`, "none"},
+ // Written only by a client or pod from before MUL-7726.
+ {`{"pr_auto_complete_enabled": false}`, "none"},
+ {`{"pr_auto_complete_enabled": "off"}`, "none"},
+ {`{"pr_auto_complete_enabled": false, "pr_merge_status": "in_review"}`, "in_review"},
+ {`not json`, "none"},
+ } {
+ if got := prMergeStatusSetting(db.Workspace{Settings: []byte(tc.settings)}); got != tc.want {
+ t.Errorf("prMergeStatusSetting(%q) = %q, want %q", tc.settings, got, tc.want)
+ }
+ }
+}
+
+// TestReconcilePRMergeSettings: a desktop client from before MUL-7726 flips
+// only the retired switch and echoes the rest of its settings. The flip becomes
+// a choice, an echo changes nothing, and the switch always mirrors the choice.
+func TestReconcilePRMergeSettings(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ stored, incoming string
+ wantStatus any
+ wantLegacy any // nil = key absent
+ }{
+ {"old client turns it off", `{}`, `{"pr_auto_complete_enabled": false}`, "none", false},
+ {"old client turns it back on", `{"pr_merge_status": "none", "pr_auto_complete_enabled": false}`, `{"pr_merge_status": "none", "pr_auto_complete_enabled": true}`, "done", nil},
+ {"old client echoes a custom target", `{"pr_merge_status": "awaiting_regression"}`, `{"pr_merge_status": "awaiting_regression", "github_pr_sidebar_enabled": false}`, "awaiting_regression", nil},
+ {"new client picks a status", `{"pr_merge_status": "none", "pr_auto_complete_enabled": false}`, `{"pr_merge_status": "in_review", "pr_auto_complete_enabled": false}`, "in_review", nil},
+ {"new client picks no change", `{}`, `{"pr_merge_status": "none"}`, "none", false},
+ {"unreadable stored settings, switch off", ``, `{"pr_auto_complete_enabled": false}`, "none", false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ var stored, incoming map[string]any
+ if tc.stored != "" {
+ json.Unmarshal([]byte(tc.stored), &stored)
+ }
+ json.Unmarshal([]byte(tc.incoming), &incoming)
+ reconcilePRMergeSettings(stored, incoming)
+ if got := incoming["pr_merge_status"]; got != tc.wantStatus {
+ t.Errorf("pr_merge_status = %v, want %v", got, tc.wantStatus)
+ }
+ got, present := incoming["pr_auto_complete_enabled"]
+ if tc.wantLegacy == nil && present {
+ t.Errorf("pr_auto_complete_enabled = %v, want absent", got)
+ }
+ if tc.wantLegacy != nil && got != tc.wantLegacy {
+ t.Errorf("pr_auto_complete_enabled = %v, want %v", got, tc.wantLegacy)
+ }
+ })
+ }
+}
+
+// TestUpdateWorkspace_RetiredPRSwitch: turning the old switch off from a
+// desktop client that predates MUL-7726 must stop merges from moving issues,
+// not just save a key the server no longer reads (PR #8862 review).
+func TestUpdateWorkspace_RetiredPRSwitch(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("handler test fixture not initialized (no DB?)")
+ }
+ wsID := dbfx.Insert(t, "workspace", testutil.Cols{
+ "name": "Retired PR switch", "slug": "retired-pr-switch", "description": "", "issue_prefix": "RPS",
+ })
+ dbfx.Exec(t, `INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'owner')`, wsID, testUserID)
+ save := func(settings map[string]any) string {
+ t.Helper()
+ req := withURLParam(newRequest("PATCH", "/api/workspaces/"+wsID, map[string]any{"settings": settings}), "id", wsID)
+ testutil.Call(t, testHandler.UpdateWorkspace, req).Want(http.StatusOK)
+ ws, err := testHandler.Queries.GetWorkspace(context.Background(), parseUUID(wsID))
+ if err != nil {
+ t.Fatalf("GetWorkspace: %v", err)
+ }
+ return prMergeStatusSetting(ws)
+ }
+ if got := save(map[string]any{"pr_auto_complete_enabled": false}); got != "none" {
+ t.Fatalf("old client turned the switch off: merge status = %q, want none", got)
+ }
+ if got := save(map[string]any{"pr_merge_status": "none", "pr_auto_complete_enabled": true}); got != "done" {
+ t.Fatalf("old client turned the switch back on: merge status = %q, want done", got)
+ }
+ if got := save(map[string]any{"pr_merge_status": "in_review"}); got != "in_review" {
+ t.Fatalf("new client choice: merge status = %q, want in_review", got)
+ }
+ if got := save(map[string]any{"pr_merge_status": "in_review", "github_pr_sidebar_enabled": false}); got != "in_review" {
+ t.Fatalf("old client echo of other settings: merge status = %q, want in_review", got)
+ }
+ // The review case: a target is chosen, and an old client turns its switch
+ // off while echoing that target back.
+ if got := save(map[string]any{"pr_merge_status": "in_review", "pr_auto_complete_enabled": false}); got != "none" {
+ t.Fatalf("old client turned the switch off over a chosen target: merge status = %q, want none", got)
+ }
}
func TestNormalizePullRequestURL(t *testing.T) {
@@ -3035,34 +3094,6 @@ func TestPRLinkPolicyPermits(t *testing.T) {
}
}
-// TestPRLinkPolicyPermitsClose: auto-link decides which links get created, not
-// whether a closing keyword counts on links a workspace already has. A
-// workspace that is the only resolver acts with auto-link off; a resolver
-// that shares the identifier with an auto-linking owner does not.
-func TestPRLinkPolicyPermitsClose(t *testing.T) {
- const wsA, wsB = "workspace-a", "workspace-b"
-
- for _, tc := range []struct {
- name string
- policy prLinkPolicy
- ws string
- want bool
- }{
- {"zero value denies", prLinkPolicy{}, wsA, false},
- {"single-binding delivery is unrestricted", prLinkPolicy{unrestricted: true}, wsA, true},
- {"auto-linking owner acts", prLinkPolicy{owner: map[string]string{"ABC-100": wsA}}, wsA, true},
- {"sole resolver with auto-link off acts", prLinkPolicy{sole: map[string]string{"ABC-100": wsA}}, wsA, true},
- {"resolver beside an auto-linking owner does not act", prLinkPolicy{owner: map[string]string{"ABC-100": wsA}}, wsB, false},
- {"ambiguous identifier is denied everywhere", prLinkPolicy{ambiguous: map[string]bool{"ABC-100": true}}, wsA, false},
- } {
- t.Run(tc.name, func(t *testing.T) {
- if got := tc.policy.permitsClose("ABC-100", tc.ws); got != tc.want {
- t.Errorf("permitsClose(ABC-100, %s) = %v, want %v", tc.ws, got, tc.want)
- }
- })
- }
-}
-
// TestWebhook_AutoLinkOffKeepsValidClosingKeyword: turning auto-link off in a
// workspace that shares its installation with another must not drop a closing
// keyword only this workspace resolves — the merge still completes the issue
@@ -3162,14 +3193,14 @@ func TestWebhook_PullRequest_UniqueResolverAmongBindingsStillAutoCompletes(t *te
}
}
-// TestWebhook_PullRequest_UnreadableWorkspaceWithholdsCloseIntent covers 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, 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) {
+// TestWebhook_PullRequest_UnreadableWorkspaceLinksNothing covers the
+// fail-closed half of resolvePRLinkPolicy: one real resolver, which would link
+// and move the issue on merge, 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, the delivery changes no link and no status: a
+// transient read failure must never promote an ambiguous identifier into a
+// status write.
+func TestWebhook_PullRequest_UnreadableWorkspaceLinksNothing(t *testing.T) {
if testHandler == nil || testPool == nil {
t.Skip("handler test fixture not initialized (no DB?)")
}
diff --git a/server/internal/handler/pr_auto_complete.go b/server/internal/handler/pr_auto_complete.go
index 890ebee75f..459ad7cbfa 100644
--- a/server/internal/handler/pr_auto_complete.go
+++ b/server/internal/handler/pr_auto_complete.go
@@ -22,40 +22,55 @@ import (
"github.com/multica-ai/multica/server/pkg/protocol"
)
-// PR auto-complete (MUL-7429).
+// PR merge automation (MUL-7429, MUL-7726).
//
// The whole rule, as users see it:
//
// - A PR whose title or branch name carries an issue identifier is linked to
-// that issue, and so is one that closes it with a keyword ("Closes MUL-1")
-// in its title or body. A member can also link or remove a PR by hand.
-// - When every PR linked to an issue is merged and at least one of them
-// closes it with a keyword, the issue moves to Done — unless the workspace
-// turned the setting off or someone turned it off for that one issue. A
-// PR linked only by its title or branch is related work: it has to merge
-// too, but it never completes the issue by itself.
+// that issue, and so is one whose title or body puts it after a closing
+// keyword ("Closes MUL-1"). A member can also link or remove a PR by hand.
+// The keyword only links; it has no say in what the merge does.
+// - The workspace picks what a merge does: move the issue to one status (Done
+// by default, or any started or done status, custom ones included) or leave
+// it alone. When every PR linked to an issue is merged, the issue moves to
+// that status, unless someone turned the automation 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, or accepting it from Triage is not a PR event, so it never moves 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).
+// The names predate the configurable target and stay for installed clients.
const (
prAutoCompleteNone = "none" // no linked PR
- prAutoCompleteWorkspaceDisabled = "workspace_disabled" // workspace setting off
+ prAutoCompleteWorkspaceDisabled = "workspace_disabled" // workspace leaves status alone
prAutoCompleteIssueDisabled = "issue_disabled" // turned off for this issue
prAutoCompleteTerminal = "terminal" // already done / cancelled
prAutoCompleteTriage = "triage" // not accepted yet
- prAutoCompleteNoCloseIntent = "no_close_intent" // no PR closes the issue with a keyword
+ prAutoCompleteAtTarget = "at_target" // already in the target status
prAutoCompleteWaiting = "waiting" // some PRs still open / draft
prAutoCompleteNotMerged = "not_merged" // some PRs closed without merging
prAutoCompleteAllMerged = "all_merged" // every linked PR merged
)
+// Workspace settings keys. pr_auto_complete_enabled is the switch desktop
+// clients before MUL-7726 still show and write; prMergeStatusFromSettings
+// reads it when pr_merge_status is absent, and reconcilePRMergeSettings keeps
+// the two in step on every write.
+const (
+ prMergeStatusKey = "pr_merge_status"
+ prAutoCompleteLegacyKey = "pr_auto_complete_enabled"
+ // prMergeStatusNone is the value that leaves an issue's status alone.
+ prMergeStatusNone = "none"
+)
+
type prAutoCompleteDecision struct {
State string
+ // Target is the status a merge moves the issue to, or "" when the
+ // workspace leaves status alone (or its choice no longer resolves).
+ Target string
// PRs the state is about: still open for waiting, closed-unmerged for
// not_merged, every linked PR for all_merged.
PRs []db.ListIssueLinkedPullRequestStatesRow
@@ -64,20 +79,89 @@ type prAutoCompleteDecision struct {
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 {
+// prMergeStatusSetting reads the workspace's choice: "none", or the key of the
+// status a merge moves an issue to. An unreadable settings blob means none:
+// the setting authorizes a status write, so it must not default to the
+// permissive side.
+func prMergeStatusSetting(ws db.Workspace) string {
if len(ws.Settings) == 0 {
+ return issuestatus.Done
+ }
+ var s map[string]any
+ if err := json.Unmarshal(ws.Settings, &s); err != nil {
+ return prMergeStatusNone
+ }
+ return prMergeStatusFromSettings(s)
+}
+
+// prMergeStatusFromSettings is prMergeStatusSetting on decoded settings.
+// Without pr_merge_status it follows the retired switch (a pod or client from
+// before MUL-7726 may have written only that): off means none, else Done.
+func prMergeStatusFromSettings(s map[string]any) string {
+ raw, ok := s[prMergeStatusKey]
+ if !ok || raw == nil {
+ if prAutoCompleteLegacyOn(s) {
+ return issuestatus.Done
+ }
+ return prMergeStatusNone
+ }
+ value, ok := raw.(string)
+ if !ok {
+ return prMergeStatusNone
+ }
+ if key := strings.ToLower(strings.TrimSpace(value)); key != "" {
+ return key
+ }
+ return prMergeStatusNone
+}
+
+// prAutoCompleteLegacyOn reads the retired switch the way releases before
+// MUL-7726 did: absent means on, anything but a boolean means off.
+func prAutoCompleteLegacyOn(s map[string]any) bool {
+ raw, ok := s[prAutoCompleteLegacyKey]
+ if !ok || raw == nil {
return true
}
- var s struct {
- Enabled *bool `json:"pr_auto_complete_enabled"`
+ on, ok := raw.(bool)
+ return ok && on
+}
+
+// reconcilePRMergeSettings adjusts a settings write so desktop clients from
+// before MUL-7726 keep working. Those clients show and flip only the retired
+// switch, and send back the rest of the settings they hold. A flip of that
+// switch becomes a choice here (off → none, on → Done). Every write then
+// mirrors the switch from the effective choice, so an old client shows it
+// correctly. stored may be nil when the current settings could not be read.
+func reconcilePRMergeSettings(stored, incoming map[string]any) {
+ if _, sent := incoming[prAutoCompleteLegacyKey]; sent && prAutoCompleteLegacyOn(incoming) != prAutoCompleteLegacyOn(stored) {
+ if prAutoCompleteLegacyOn(incoming) {
+ incoming[prMergeStatusKey] = issuestatus.Done
+ } else {
+ incoming[prMergeStatusKey] = prMergeStatusNone
+ }
}
- if err := json.Unmarshal(ws.Settings, &s); err != nil {
- return false
+ if prMergeStatusFromSettings(incoming) == prMergeStatusNone {
+ incoming[prAutoCompleteLegacyKey] = false
+ } else {
+ delete(incoming, prAutoCompleteLegacyKey)
}
- return s.Enabled == nil || *s.Enabled
+}
+
+// resolvePRMergeTarget returns the status a merge moves issues to in this
+// workspace, or "" to leave status alone. The chosen key must still name a
+// live started or done status other than Blocked; anything else (an archived
+// custom status, a failed catalog read) fails closed to no write. It shares
+// the delivery's resolver, so a built-in target costs no catalog read.
+func (h *Handler) resolvePRMergeTarget(ctx context.Context, ws db.Workspace, resolver *issuestatus.Resolver) string {
+ key := prMergeStatusSetting(ws)
+ if key == prMergeStatusNone || key == issuestatus.Blocked {
+ return ""
+ }
+ switch resolver.WritableCategory(ctx, h.issueStatusCatalog(), key) {
+ case issuestatus.CategoryStarted, issuestatus.CategoryDone:
+ return key
+ }
+ return ""
}
// decidePRAutoComplete computes the decision for one issue. resolver may be
@@ -92,48 +176,46 @@ func (h *Handler) decidePRAutoComplete(ctx context.Context, ws db.Workspace, iss
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)
}
+ d := prAutoCompleteDecision{IssueDisabled: disabled, Target: h.resolvePRMergeTarget(ctx, ws, resolver)}
+ if len(prs) == 0 {
+ d.State = prAutoCompleteNone
+ return d, nil
+ }
// 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" {
+ // The guards that make a merge change nothing come first, so the issue page
+ // only speaks when a merge would move the issue.
+ switch {
+ case effective == issuestatus.Done || effective == issuestatus.Cancelled:
d.State = prAutoCompleteTerminal
return d, nil
- }
- if issue.TriageState.Valid {
+ case issue.TriageState.Valid:
d.State = prAutoCompleteTriage
return d, nil
+ case d.Target == "":
+ d.State = prAutoCompleteWorkspaceDisabled
+ return d, nil
+ case disabled:
+ d.State = prAutoCompleteIssueDisabled
+ return d, nil
+ case issue.Status == d.Target:
+ d.State = prAutoCompleteAtTarget
+ return d, nil
}
var open, closed []db.ListIssueLinkedPullRequestStatesRow
- closes := false
for _, pr := range prs {
switch pr.State {
case "open", "draft":
open = append(open, pr)
case "closed":
closed = append(closed, pr)
- // A PR closed without merging never delivers, whatever it says.
- continue
}
- closes = closes || pr.CloseIntent
}
switch {
- case !closes:
- d.State = prAutoCompleteNoCloseIntent
case len(open) > 0:
d.State, d.PRs = prAutoCompleteWaiting, open
case len(closed) > 0:
@@ -145,10 +227,11 @@ func (h *Handler) decidePRAutoComplete(ctx context.Context, ws db.Workspace, iss
}
// maybeAutoCompleteIssue runs the decision for one issue after a PR event and
-// moves it to Done when every linked PR is merged and one of them closes it.
+// moves it to the workspace's target status 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.
+// concurrent merges move the issue once. It starts no agent run: a merge is not
+// a person handing the issue to anyone.
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 {
@@ -178,9 +261,10 @@ func (h *Handler) maybeAutoCompleteIssue(ctx context.Context, workspaceID, issue
}
defer tx.Rollback(ctx)
qtx := h.Queries.WithTx(tx)
- updated, err := qtx.CompleteIssueFromPullRequests(ctx, db.CompleteIssueFromPullRequestsParams{
+ updated, err := qtx.MoveIssueFromPullRequests(ctx, db.MoveIssueFromPullRequestsParams{
ID: issue.ID,
WorkspaceID: issue.WorkspaceID,
+ TargetStatus: d.Target,
ExpectedStatus: issue.Status,
})
if errors.Is(err, pgx.ErrNoRows) {
@@ -189,6 +273,7 @@ func (h *Handler) maybeAutoCompleteIssue(ctx context.Context, workspaceID, issue
}
var cancelledWakeups []db.AgentTaskQueue
if err == nil {
+ // A no-op unless the target closes the issue.
cancelledWakeups, err = service.StopClosedIssueWakeups(ctx, qtx, updated)
}
if err == nil {
@@ -214,8 +299,8 @@ func (h *Handler) maybeAutoCompleteIssue(ctx context.Context, workspaceID, issue
"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.
+ // Moving out of cancelled 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),
})
@@ -235,21 +320,29 @@ func prNumberList(prs []db.ListIssueLinkedPullRequestStatesRow) string {
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"`
+ PullRequestIDs []string `json:"pull_request_ids"`
+ IssueDisabled bool `json:"issue_disabled"`
+ // WorkspaceEnabled is true when a merge moves issues at all.
+ WorkspaceEnabled bool `json:"workspace_enabled"`
+ // TargetStatus is the status key a merge moves the issue to, or "none".
+ TargetStatus string `json:"target_status"`
}
-func prAutoCompleteToResponse(ws db.Workspace, d prAutoCompleteDecision) prAutoCompleteResponse {
+func prAutoCompleteToResponse(d prAutoCompleteDecision) prAutoCompleteResponse {
ids := make([]string, 0, len(d.PRs))
for _, pr := range d.PRs {
ids = append(ids, uuidToString(pr.ID))
}
+ target := d.Target
+ if target == "" {
+ target = prMergeStatusNone
+ }
return prAutoCompleteResponse{
State: d.State,
PullRequestIDs: ids,
IssueDisabled: d.IssueDisabled,
- WorkspaceEnabled: prAutoCompleteEnabledForWorkspace(ws),
+ WorkspaceEnabled: d.Target != "",
+ TargetStatus: target,
}
}
diff --git a/server/internal/handler/pr_merge_status_migration_test.go b/server/internal/handler/pr_merge_status_migration_test.go
new file mode 100644
index 0000000000..c50833bdfd
--- /dev/null
+++ b/server/internal/handler/pr_merge_status_migration_test.go
@@ -0,0 +1,92 @@
+package handler
+
+import (
+ "context"
+ "fmt"
+ "os"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/testutil"
+)
+
+// TestPRMergeStatusMigration runs migration 551 against workspaces with each
+// kind of PR history (MUL-7726). Workspaces whose merges never all completed
+// their issues are pinned to "none"; the rest keep the Done default. The
+// migration runs inside a rolled-back transaction, twice, to prove a replay is
+// harmless.
+func TestPRMergeStatusMigration(t *testing.T) {
+ if testPool == nil {
+ t.Skip("handler test fixture not initialized (no DB?)")
+ }
+ ctx := context.Background()
+ type link struct {
+ state string
+ closes bool
+ }
+ cases := []struct {
+ name string
+ settings string
+ links []link
+ want string // "" = key absent (Done default)
+ }{
+ {"no links", `{}`, nil, ""},
+ {"only keyword merges", `{}`, []link{{"merged", true}, {"open", false}}, ""},
+ {"plain merge", `{}`, []link{{"merged", false}}, "none"},
+ {"mixed merges", `{}`, []link{{"merged", true}, {"merged", false}}, "none"},
+ {"nothing merged yet", `{}`, []link{{"open", true}}, "none"},
+ {"switched off", `{"pr_auto_complete_enabled": false}`, nil, "none"},
+ {"already chosen", `{"pr_merge_status": "in_review"}`, []link{{"merged", false}}, "in_review"},
+ }
+ workspaces := make([]string, len(cases))
+ for i, tc := range cases {
+ ws := dbfx.Workspace(t, "PR merge status migration", fmt.Sprintf("pr-merge-migration-%d", i),
+ testutil.Cols{"issue_prefix": "PMM", "settings": testutil.Raw(fmt.Sprintf("'%s'::jsonb", tc.settings))})
+ workspaces[i] = ws
+ fixture := testutil.New(testPool, ws, testUserID)
+ for j, l := range tc.links {
+ issue := fixture.Issue(t, "Migration fixture")
+ pr := fixture.Insert(t, "github_pull_request", testutil.Cols{
+ "workspace_id": ws, "installation_id": 551, "repo_owner": "acme", "repo_name": "migration",
+ "pr_number": j + 1, "title": "Fixture", "state": l.state,
+ "html_url": fmt.Sprintf("https://github.com/acme/migration/pull/%d", j+1),
+ "pr_created_at": testutil.Raw("now()"), "pr_updated_at": testutil.Raw("now()"),
+ })
+ fixture.InsertNoID(t, "issue_pull_request",
+ testutil.Cols{"issue_id": issue, "pull_request_id": pr, "close_intent": l.closes},
+ "issue_id = $1 AND pull_request_id = $2", issue, pr)
+ }
+ }
+
+ migration, err := os.ReadFile("../../migrations/551_pr_merge_status.up.sql")
+ if err != nil {
+ t.Fatal(err)
+ }
+ tx, err := testPool.Begin(ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer tx.Rollback(ctx)
+ for range 2 {
+ if _, err := tx.Exec(ctx, string(migration)); err != nil {
+ t.Fatalf("migration: %v", err)
+ }
+ }
+ for i, tc := range cases {
+ var got, legacy *string
+ if err := tx.QueryRow(ctx, `SELECT settings->>'pr_merge_status', settings->>'pr_auto_complete_enabled' FROM workspace WHERE id = $1`, workspaces[i]).Scan(&got, &legacy); err != nil {
+ t.Fatalf("%s: %v", tc.name, err)
+ }
+ value := ""
+ if got != nil {
+ value = *got
+ }
+ if value != tc.want {
+ t.Errorf("%s: pr_merge_status = %q, want %q", tc.name, value, tc.want)
+ }
+ // Desktop clients from before the change show the retired switch; a
+ // pinned workspace must show it off there.
+ if tc.want == "none" && (legacy == nil || *legacy != "false") {
+ t.Errorf("%s: pr_auto_complete_enabled = %v, want false", tc.name, legacy)
+ }
+ }
+}
diff --git a/server/internal/handler/vcs_webhook.go b/server/internal/handler/vcs_webhook.go
index f12c325d65..1855e70a1f 100644
--- a/server/internal/handler/vcs_webhook.go
+++ b/server/internal/handler/vcs_webhook.go
@@ -226,11 +226,10 @@ func (h *Handler) mirrorVCSPullRequest(ctx context.Context, conn db.VcsConnectio
ws, err := h.Queries.GetWorkspace(ctx, conn.WorkspaceID)
if err == nil {
var touched map[pgtype.UUID]struct{}
- idents, closing := prClaimedIdentifiers(ev.Title, ev.Body, ev.Branch)
- permits := func(string) bool { return true }
+ idents := prClaimedIdentifiers(ev.Title, ev.Body, ev.Branch)
linkedIssueIDs, touched = h.reconcileAutoLinks(ctx, ws, pr.ID, ev.State, prAutoLinkInput{
idents: idents,
- permits: permits,
+ 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})
@@ -242,16 +241,6 @@ func (h *Handler) mirrorVCSPullRequest(ctx context.Context, conn db.VcsConnectio
return h.Queries.ListAutoLinkedIssueIDsForVCSPullRequest(ctx, pr.ID)
},
})
- // Close intent follows the PR text up to and including the merge/close
- // event, on every link of the PR (see closingIssueIDs).
- if ev.Terminal() || (ev.State != "merged" && ev.State != "closed") {
- if err := h.Queries.SyncVCSPullRequestCloseIntent(ctx, db.SyncVCSPullRequestCloseIntentParams{
- PullRequestID: pr.ID,
- ClosingIssueIds: h.closingIssueIDs(ctx, ws, closing, permits),
- }); err != nil {
- slog.Warn("vcs: sync close intent failed", "err", err)
- }
- }
if ev.State == "merged" && prevState != "merged" {
issueIDs, err := h.Queries.ListIssueIDsForVCSPullRequest(ctx, pr.ID)
if err != nil {
diff --git a/server/internal/handler/vcs_webhook_test.go b/server/internal/handler/vcs_webhook_test.go
index 55d867ed29..81cbebffe0 100644
--- a/server/internal/handler/vcs_webhook_test.go
+++ b/server/internal/handler/vcs_webhook_test.go
@@ -223,9 +223,9 @@ func TestVCSWebhook_BareBodyMentionIsNotLinked(t *testing.T) {
}
}
-// Auto-complete must span providers: an issue with an OPEN GitHub PR and a
-// MERGED close-intent VCS merge request waits for the GitHub PR, and completes
-// once it merges too.
+// The merge automation must span providers: an issue with an OPEN GitHub PR
+// and a MERGED VCS merge request waits for the GitHub PR, and moves once it
+// merges too.
func TestAutoCompleteSpansProviders(t *testing.T) {
ctx := context.Background()
box := withVCSBox(t)
@@ -275,11 +275,6 @@ func TestAutoCompleteSpansProviders(t *testing.T) {
}); err != nil {
t.Fatalf("LinkIssueToVCSPullRequest: %v", err)
}
- if err := testHandler.Queries.SyncVCSPullRequestCloseIntent(ctx, db.SyncVCSPullRequestCloseIntentParams{
- PullRequestID: vcsPR.ID, ClosingIssueIds: []pgtype.UUID{parseUUID(issue.ID)},
- }); err != nil {
- t.Fatalf("SyncVCSPullRequestCloseIntent: %v", err)
- }
testHandler.maybeAutoCompleteIssue(ctx, parseUUID(testWorkspaceID), parseUUID(issue.ID), nil)
if got, _ := testHandler.Queries.GetIssue(ctx, parseUUID(issue.ID)); got.Status == "done" {
@@ -352,10 +347,9 @@ func TestDeleteIssue_VCSLinkCleanupIsWorkspaceScoped(t *testing.T) {
}
}
-// A merge whose text no longer closes the issue clears the close intent an
-// earlier event recorded, even though the link itself is kept after merge
-// (PR #8794 review; mirrors TestWebhook_RemovedKeywordStopsCounting).
-func TestVCSWebhook_MergeWithoutKeywordDoesNotComplete(t *testing.T) {
+// A PR linked while open stays linked when its merge event no longer names the
+// issue, and that merge moves the issue: the keyword only links (MUL-7726).
+func TestVCSWebhook_MergeMovesIssueLinkedEarlier(t *testing.T) {
ctx := context.Background()
box := withVCSBox(t)
connID := seedVCSConnection(t, ctx, box, "forgejo", "https://forgejo.test")
@@ -388,8 +382,8 @@ func TestVCSWebhook_MergeWithoutKeywordDoesNotComplete(t *testing.T) {
fire("closed", "closed", true, "Related to "+issue.Identifier, "2026-05-02T00:00:00Z")
updated, _ := testHandler.Queries.GetIssue(ctx, parseUUID(issue.ID))
- if updated.Status == "done" {
- t.Errorf("merged without a closing keyword, but the issue moved to done")
+ if updated.Status != "done" {
+ t.Errorf("status = %q, want done", updated.Status)
}
var links int
testPool.QueryRow(ctx, `SELECT count(*) FROM issue_vcs_pull_request WHERE issue_id = $1`, issue.ID).Scan(&links)
@@ -429,20 +423,17 @@ func TestVCSWebhook_StaleEventDoesNotRewriteLink(t *testing.T) {
}
}
- // Newer terminal event: merged with a real claim (Closes) → close_intent.
+ // Newer terminal event: merged with a real claim (Closes).
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.
+ // Without the guard this would drop the link: an open PR that no longer
+ // claims the issue is unlinked.
fire("opened", "open", false, "WIP", "touches "+issue.Identifier, "2026-05-01T00:00:00Z")
- var closeIntent bool
- if err := testPool.QueryRow(ctx,
- `SELECT close_intent FROM issue_vcs_pull_request WHERE issue_id = $1`,
- issue.ID).Scan(&closeIntent); err != nil {
- t.Fatalf("select link: %v", err)
- }
- if !closeIntent {
- t.Errorf("stale event rewrote link: close_intent=%v, want true", closeIntent)
+ var links int
+ testPool.QueryRow(ctx, `SELECT count(*) FROM issue_vcs_pull_request WHERE issue_id = $1`, issue.ID).Scan(&links)
+ if links != 1 {
+ t.Errorf("stale event rewrote the link: %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/workspace.go b/server/internal/handler/workspace.go
index 8f0c55f516..d0a685d58c 100644
--- a/server/internal/handler/workspace.go
+++ b/server/internal/handler/workspace.go
@@ -401,6 +401,17 @@ func (h *Handler) UpdateWorkspace(w http.ResponseWriter, r *http.Request) {
params.Context = pgtype.Text{String: *req.Context, Valid: true}
}
if req.Settings != nil {
+ if incoming, ok := req.Settings.(map[string]any); ok {
+ // Only an old client's flip of the retired PR switch needs the
+ // stored value; see reconcilePRMergeSettings.
+ var stored map[string]any
+ if _, sent := incoming[prAutoCompleteLegacyKey]; sent {
+ if existing, err := h.Queries.GetWorkspace(r.Context(), idUUID); err == nil {
+ _ = json.Unmarshal(existing.Settings, &stored)
+ }
+ }
+ reconcilePRMergeSettings(stored, incoming)
+ }
s, _ := json.Marshal(req.Settings)
params.Settings = s
}
diff --git a/server/internal/issuestatus/issuestatus.go b/server/internal/issuestatus/issuestatus.go
index e24f6d0d24..c808c1f056 100644
--- a/server/internal/issuestatus/issuestatus.go
+++ b/server/internal/issuestatus/issuestatus.go
@@ -586,6 +586,7 @@ type Resolver struct {
workspaceID pgtype.UUID
categories map[string]string
names map[string]string
+ archived map[string]bool
loaded bool
loadErr error
}
@@ -615,9 +616,13 @@ func (r *Resolver) load(ctx context.Context, q Querier) {
}
r.categories = make(map[string]string, len(entries))
r.names = make(map[string]string, len(entries))
+ r.archived = make(map[string]bool)
for _, e := range entries {
r.categories[e.Key] = e.Category
r.names[e.Key] = e.Name
+ if e.ArchivedAt.Valid {
+ r.archived[e.Key] = true
+ }
}
}
@@ -657,6 +662,27 @@ func (r *Resolver) Category(ctx context.Context, q Querier, status string) strin
return category
}
+// WritableCategory returns the category of a status a background writer may
+// still move an issue to: a built-in (resolved without I/O), or a custom
+// status that exists and is not archived. It returns "" for anything else,
+// including a failed catalog read, so side-effect callers fail closed. It
+// mirrors Resolve's rules while sharing the Resolver's single catalog read.
+func (r *Resolver) WritableCategory(ctx context.Context, q Querier, status string) string {
+ if IsBuiltIn(status) {
+ category, _ := CategoryForBehavior(status)
+ return category
+ }
+ r.load(ctx, q)
+ if r.archived[status] {
+ return ""
+ }
+ category := r.categories[status]
+ if !IsCategory(category) {
+ return ""
+ }
+ return category
+}
+
// Name returns a CUSTOM status's display name, or "" for a built-in and for a
// key the catalog does not hold.
//
diff --git a/server/internal/issuestatus/issuestatus_test.go b/server/internal/issuestatus/issuestatus_test.go
index a15e3714ca..8ed0e76de3 100644
--- a/server/internal/issuestatus/issuestatus_test.go
+++ b/server/internal/issuestatus/issuestatus_test.go
@@ -677,3 +677,41 @@ func TestExpandCategories(t *testing.T) {
}
})
}
+
+// WritableCategory answers Resolve's question for background writers: a
+// built-in without I/O, a live custom status from the shared catalog read,
+// and "" for an archived, unknown or unreadable one.
+func TestResolverWritableCategory(t *testing.T) {
+ archived := custom("retired", InProgress)
+ archived.ArchivedAt = pgtype.Timestamptz{Valid: true}
+ q := newFakeQuerier(custom("awaiting_regression", InReview), archived)
+ r := NewResolver(testWorkspace)
+ ctx := context.Background()
+
+ if got := r.WritableCategory(ctx, q, Done); got != CategoryDone {
+ t.Errorf("WritableCategory(done) = %q, want %q", got, CategoryDone)
+ }
+ if got := r.WritableCategory(ctx, q, InReview); got != CategoryStarted {
+ t.Errorf("WritableCategory(in_review) = %q, want %q", got, CategoryStarted)
+ }
+ if q.lists != 0 || q.lookups != 0 {
+ t.Errorf("built-ins touched the catalog: %d list(s), %d lookup(s)", q.lists, q.lookups)
+ }
+ if got := r.WritableCategory(ctx, q, "awaiting_regression"); got != CategoryStarted {
+ t.Errorf("WritableCategory(awaiting_regression) = %q, want %q", got, CategoryStarted)
+ }
+ for _, key := range []string{"retired", "ghost"} {
+ if got := r.WritableCategory(ctx, q, key); got != "" {
+ t.Errorf("WritableCategory(%q) = %q, want empty", key, got)
+ }
+ }
+ if q.lists != 1 || q.lookups != 0 {
+ t.Errorf("catalog reads = %d list(s), %d lookup(s); want 1 and 0", q.lists, q.lookups)
+ }
+
+ failing := newFakeQuerier(custom("awaiting_regression", InReview))
+ failing.err = errors.New("connection refused")
+ if got := NewResolver(testWorkspace).WritableCategory(ctx, failing, "awaiting_regression"); got != "" {
+ t.Errorf("WritableCategory on a failed read = %q, want empty", got)
+ }
+}
diff --git a/server/internal/service/builtin_skills/multica-platform/SKILL.md b/server/internal/service/builtin_skills/multica-platform/SKILL.md
index 7b1137d034..ba67142a71 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 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/issues.md` | Issues: PR linking, 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.md
index bf0b138278..e90d36e2d3 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 auto-complete](#pr-linking-and-auto-complete)
+- [PR linking](#pr-linking)
- [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)
@@ -12,7 +12,7 @@ Product contracts the runtime brief does not fully encode.
To attach a local file to an existing issue description, use `multica issue update <id> --attachment <local-path>`. The CLI appends the file's Markdown reference to the end of the description; to replace an image, also use `--description-file` to remove the old reference. Do not put local filesystem paths in the description.
-## PR linking and auto-complete
+## PR linking
A PR is linked to an issue when its **title** or **branch name** contains a
routable issue key (`PREFIX-NUMBER`, e.g. `MUL-123`), or when its title or body
@@ -24,29 +24,12 @@ the issue page; a removed PR is not linked again by later webhooks.
```text
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) # links AND closes
+Closes MUL-123 (body) # key after a keyword → links
Related to MUL-123 (body only) # no link
```
-**Only a closing keyword completes the issue.** When every PR linked to an issue
-is merged and at least one of them puts a closing keyword right before the key
-(`Closes MUL-123`; `Fix login MUL-123` does not count, and a branch name never
-does), 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 title or branch key alone links the PR but never completes the issue.
-A linked PR still open or draft keeps the issue waiting, and so does a PR closed
-without merging until someone removes it from the issue.
-
-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.
-
-While a PR is open, its automatic links and its closing keyword follow the live
-title, branch, and body: removing the key drops the link, and downgrading
-`Closes MUL-123` to a plain mention keeps the title link but drops the close.
-After merge or close, existing links and the close decision stay. Adding a key to
-an already-merged PR still links it, but that late link does not complete the
-issue.
+While a PR is open, its automatic links follow the live title, branch, and
+body: removing the key drops the link. After merge or close, existing links stay.
### Default for code-changing issue work
@@ -59,12 +42,10 @@ instead 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 merging the PR should move the issue to `done`.
+body links nothing.
```text
-MUL-123: fix login redirect # key in title → links, does not complete
-Closes MUL-123 # only when merge should mark the issue done
+MUL-123: fix login redirect # key in title → links
Part of MUL-123 # body mention only → no link at all
```
@@ -82,13 +63,7 @@ an earlier run.
multica issue pull-requests <issue-id> --output json
```
-Returns `{"pull_requests": [...], "auto_complete": {...}}`.
-`auto_complete.state` says what the merge rule will do for this issue:
-`no_close_intent` (no linked PR closes the issue with a keyword, so merging
-completes nothing), `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:
+Returns `{"pull_requests": [...], ...}`. Each element of `pull_requests` exposes:
- `number`, `html_url`, `title`
- `link_source` — why the PR is on the issue: `title`, `branch`, `manual`, or
@@ -259,10 +234,7 @@ 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 PR
is open and awaiting review; moving to it is an explicit mutation.
-- **`done`** on a child issue posts a system comment on its parent. When every
- PR linked to the issue has merged and one of them carries a closing keyword
- (`Closes MUL-XXXX`), the server moves it to `done` itself (see PR linking and
- auto-complete) — you do not also need to flip it manually.
+- **`done`** on a child issue posts a system comment on its parent.
- **`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 in
flight — a run in progress keeps going. To stop a running task, cancel the
diff --git a/server/internal/service/builtin_skills_test.go b/server/internal/service/builtin_skills_test.go
index 9692759b21..c64b15d011 100644
--- a/server/internal/service/builtin_skills_test.go
+++ b/server/internal/service/builtin_skills_test.go
@@ -471,10 +471,6 @@ func TestPlatformSkillCoversPlatformContracts(t *testing.T) {
"stop editing the PR blind",
"whether the installation is bound to this workspace",
"redelivered once the receiving side is fixed",
- // Only a closing keyword completes an issue on merge, so agents
- // must not add one to a PR that delivers only part of the work.
- "Only a closing keyword completes the issue",
- "unless merging the PR should move the issue to `done`",
"include the PR URL when a PR exists",
"Closes MUL-123",
"--status backlog",
diff --git a/server/migrations/551_pr_merge_status.down.sql b/server/migrations/551_pr_merge_status.down.sql
new file mode 100644
index 0000000000..96efc36ecd
--- /dev/null
+++ b/server/migrations/551_pr_merge_status.down.sql
@@ -0,0 +1,5 @@
+-- Drops the setting entirely, including values admins chose after the up
+-- migration; the previous release does not read it.
+UPDATE workspace
+SET settings = settings - 'pr_merge_status'
+WHERE jsonb_typeof(settings) = 'object' AND settings ? 'pr_merge_status';
diff --git a/server/migrations/551_pr_merge_status.up.sql b/server/migrations/551_pr_merge_status.up.sql
new file mode 100644
index 0000000000..cb7fbad27f
--- /dev/null
+++ b/server/migrations/551_pr_merge_status.up.sql
@@ -0,0 +1,51 @@
+-- PR merge automation target (MUL-7726). The workspace setting
+-- settings.pr_merge_status picks what merging every PR linked to an issue does:
+-- "none", or the key of the status the issue moves to. Absent means Done.
+--
+-- Until now a merge completed an issue only when a PR said "Closes MUL-1" in
+-- its title or body, and settings.pr_auto_complete_enabled = false turned that
+-- off. Pin "none" on existing workspaces whose history says a merge never
+-- completed their issues regardless of the text, so the new Done default only
+-- reaches workspaces that never linked a PR or only ever merged keyword PRs:
+--
+-- * pr_auto_complete_enabled = false -> none
+-- * a linked PR exists, and not every merged link carried a
+-- closing keyword (or nothing merged yet) -> none
+-- * no linked PR, or every merged link carried a keyword -> left absent
+--
+-- Pinned workspaces also get pr_auto_complete_enabled = false, the switch
+-- desktop clients from before this change still show, so they show it off.
+-- Only workspaces without an explicit pr_merge_status are touched, so a replay
+-- is harmless. The scan reads link rows once; the write touches only the
+-- pinned workspaces.
+WITH link_history AS (
+ SELECT i.workspace_id,
+ bool_or(pr.state = 'merged') AS any_merged,
+ bool_and(pr.state <> 'merged' OR ipr.close_intent) AS merged_with_keyword
+ FROM issue_pull_request ipr
+ JOIN issue i ON i.id = ipr.issue_id
+ JOIN github_pull_request pr ON pr.id = ipr.pull_request_id
+ GROUP BY i.workspace_id
+ UNION ALL
+ SELECT i.workspace_id,
+ bool_or(pr.state = 'merged') AS any_merged,
+ bool_and(pr.state <> 'merged' OR ipr.close_intent) AS merged_with_keyword
+ FROM issue_vcs_pull_request ipr
+ JOIN issue i ON i.id = ipr.issue_id
+ JOIN vcs_pull_request pr ON pr.id = ipr.pull_request_id
+ GROUP BY i.workspace_id
+),
+pinned AS (
+ SELECT workspace_id
+ FROM link_history
+ GROUP BY workspace_id
+ HAVING NOT (bool_or(any_merged) AND bool_and(merged_with_keyword))
+)
+UPDATE workspace AS w
+SET settings = (CASE WHEN jsonb_typeof(w.settings) = 'object' THEN w.settings ELSE '{}'::jsonb END)
+ || '{"pr_merge_status": "none", "pr_auto_complete_enabled": false}'::jsonb
+WHERE NOT (jsonb_typeof(w.settings) = 'object' AND w.settings ? 'pr_merge_status')
+ AND (
+ (jsonb_typeof(w.settings) = 'object' AND w.settings->>'pr_auto_complete_enabled' = 'false')
+ OR w.id IN (SELECT workspace_id FROM pinned)
+ );
diff --git a/server/pkg/db/generated/github.sql.go b/server/pkg/db/generated/github.sql.go
index ab26c03875..68c70c4672 100644
--- a/server/pkg/db/generated/github.sql.go
+++ b/server/pkg/db/generated/github.sql.go
@@ -360,9 +360,10 @@ type LinkIssueToPullRequestParams struct {
// Issue ↔ Pull Request link
// =====================
// Automatic link from a PR title, branch, or closing keyword. 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; close_intent is set by SyncPullRequestCloseIntent.
+// when the link is new, so the webhook evaluates the merge automation on the
+// link event and not on every redelivery. An existing link (automatic or
+// manual) is left untouched. close_intent is no longer read or written
+// (MUL-7726).
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 {
@@ -685,27 +686,6 @@ func (q *Queries) ListPullRequestsByIssue(ctx context.Context, issueID pgtype.UU
return items, nil
}
-const syncPullRequestCloseIntent = `-- name: SyncPullRequestCloseIntent :exec
-UPDATE issue_pull_request
-SET close_intent = (issue_id = ANY($1::uuid[]))
-WHERE pull_request_id = $2
- AND close_intent <> (issue_id = ANY($1::uuid[]))
-`
-
-type SyncPullRequestCloseIntentParams struct {
- ClosingIssueIds []pgtype.UUID `json:"closing_issue_ids"`
- PullRequestID pgtype.UUID `json:"pull_request_id"`
-}
-
-// Sets close_intent on every link of the PR, automatic or manual, to whether
-// the PR text closes that issue with a keyword ("Closes MUL-1" in its title or
-// body), so a keyword removed before the merge stops counting. The webhook
-// calls it until the PR's merge/close event, which fixes the decision.
-func (q *Queries) SyncPullRequestCloseIntent(ctx context.Context, arg SyncPullRequestCloseIntentParams) error {
- _, err := q.db.Exec(ctx, syncPullRequestCloseIntent, arg.ClosingIssueIds, arg.PullRequestID)
- return err
-}
-
const unlinkIssueFromPullRequest = `-- name: UnlinkIssueFromPullRequest :execrows
DELETE FROM issue_pull_request
WHERE issue_id = $1 AND pull_request_id = $2
diff --git a/server/pkg/db/generated/pr_automation.sql.go b/server/pkg/db/generated/pr_automation.sql.go
index 6f58593dfc..f329c8a2d2 100644
--- a/server/pkg/db/generated/pr_automation.sql.go
+++ b/server/pkg/db/generated/pr_automation.sql.go
@@ -11,95 +11,6 @@ import (
"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'
- )
- AND EXISTS (
- SELECT 1 FROM issue_pull_request ipr WHERE ipr.issue_id = i.id AND ipr.close_intent
- UNION ALL
- SELECT 1 FROM issue_vcs_pull_request ipr WHERE ipr.issue_id = i.id AND ipr.close_intent
- )
-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),
-// the linked PRs are still all merged when the write runs (a PR linked between
-// the decision and this statement keeps the issue open), and one of them still
-// closes the issue with a keyword. 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
@@ -184,12 +95,12 @@ func (q *Queries) IsPullRequestExcludedFromIssue(ctx context.Context, arg IsPull
}
const listIssueLinkedPullRequestStates = `-- name: ListIssueLinkedPullRequestStates :many
-SELECT pr.id, 'github'::text AS provider, pr.pr_number, pr.state, ipr.close_intent
+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, ipr.close_intent
+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
@@ -197,15 +108,14 @@ 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"`
- CloseIntent bool `json:"close_intent"`
+ 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.
+// the merge 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 {
@@ -220,7 +130,6 @@ func (q *Queries) ListIssueLinkedPullRequestStates(ctx context.Context, issueID
&i.Provider,
&i.PrNumber,
&i.State,
- &i.CloseIntent,
); err != nil {
return nil, err
}
@@ -232,6 +141,97 @@ func (q *Queries) ListIssueLinkedPullRequestStates(ctx context.Context, issueID
return items, nil
}
+const moveIssueFromPullRequests = `-- name: MoveIssueFromPullRequests :one
+UPDATE issue AS i SET
+ status = $3::text,
+ 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 = $3::text
+ ),
+ 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 = $4::text
+ AND i.status <> $3::text
+ 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 MoveIssueFromPullRequestsParams struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ TargetStatus string `json:"target_status"`
+ ExpectedStatus string `json:"expected_status"`
+}
+
+// Conditional status write for the PR merge automation. It lands only if the
+// issue is still in the status the decision saw (two merges racing move it
+// once), is not already in the target, and the linked PRs are still all merged
+// when the write runs (a PR linked between the decision and this statement
+// keeps the issue where it is). Repositions and clears a duplicate mark like
+// UpdateIssueStatus does; the target is never cancelled.
+func (q *Queries) MoveIssueFromPullRequests(ctx context.Context, arg MoveIssueFromPullRequestsParams) (Issue, error) {
+ row := q.db.QueryRow(ctx, moveIssueFromPullRequests,
+ arg.ID,
+ arg.WorkspaceID,
+ arg.TargetStatus,
+ 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 setIssuePRAutoCompleteDisabled = `-- name: SetIssuePRAutoCompleteDisabled :exec
INSERT INTO issue_pr_automation (
issue_id, workspace_id, auto_complete_disabled, updated_by_type, updated_by_id
diff --git a/server/pkg/db/generated/vcs.sql.go b/server/pkg/db/generated/vcs.sql.go
index e38376fd50..ed88522652 100644
--- a/server/pkg/db/generated/vcs.sql.go
+++ b/server/pkg/db/generated/vcs.sql.go
@@ -532,24 +532,6 @@ func (q *Queries) RotateVCSConnectionWebhookSecret(ctx context.Context, arg Rota
return i, err
}
-const syncVCSPullRequestCloseIntent = `-- name: SyncVCSPullRequestCloseIntent :exec
-UPDATE issue_vcs_pull_request
-SET close_intent = (issue_id = ANY($1::uuid[]))
-WHERE pull_request_id = $2
- AND close_intent <> (issue_id = ANY($1::uuid[]))
-`
-
-type SyncVCSPullRequestCloseIntentParams struct {
- ClosingIssueIds []pgtype.UUID `json:"closing_issue_ids"`
- PullRequestID pgtype.UUID `json:"pull_request_id"`
-}
-
-// Mirrors SyncPullRequestCloseIntent.
-func (q *Queries) SyncVCSPullRequestCloseIntent(ctx context.Context, arg SyncVCSPullRequestCloseIntentParams) error {
- _, err := q.db.Exec(ctx, syncVCSPullRequestCloseIntent, arg.ClosingIssueIds, arg.PullRequestID)
- return err
-}
-
const unlinkIssueFromVCSPullRequest = `-- name: UnlinkIssueFromVCSPullRequest :execrows
DELETE FROM issue_vcs_pull_request
WHERE issue_id = $1 AND pull_request_id = $2
diff --git a/server/pkg/db/queries/github.sql b/server/pkg/db/queries/github.sql
index 4ebe2446b5..e11463788a 100644
--- a/server/pkg/db/queries/github.sql
+++ b/server/pkg/db/queries/github.sql
@@ -232,9 +232,10 @@ WHERE pull_request_id = $1;
-- name: LinkIssueToPullRequest :execrows
-- Automatic link from a PR title, branch, or closing keyword. 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; close_intent is set by SyncPullRequestCloseIntent.
+-- when the link is new, so the webhook evaluates the merge automation on the
+-- link event and not on every redelivery. An existing link (automatic or
+-- manual) is left untouched. close_intent is no longer read or written
+-- (MUL-7726).
INSERT INTO issue_pull_request (
issue_id, pull_request_id, linked_by_type, linked_by_id
) VALUES (
@@ -242,16 +243,6 @@ INSERT INTO issue_pull_request (
)
ON CONFLICT (issue_id, pull_request_id) DO NOTHING;
--- name: SyncPullRequestCloseIntent :exec
--- Sets close_intent on every link of the PR, automatic or manual, to whether
--- the PR text closes that issue with a keyword ("Closes MUL-1" in its title or
--- body), so a keyword removed before the merge stops counting. The webhook
--- calls it until the PR's merge/close event, which fixes the decision.
-UPDATE issue_pull_request
-SET close_intent = (issue_id = ANY(sqlc.arg('closing_issue_ids')::uuid[]))
-WHERE pull_request_id = sqlc.arg('pull_request_id')
- AND close_intent <> (issue_id = ANY(sqlc.arg('closing_issue_ids')::uuid[]));
-
-- 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
diff --git a/server/pkg/db/queries/pr_automation.sql b/server/pkg/db/queries/pr_automation.sql
index 144460ebda..fd87061d59 100644
--- a/server/pkg/db/queries/pr_automation.sql
+++ b/server/pkg/db/queries/pr_automation.sql
@@ -43,32 +43,33 @@ 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, ipr.close_intent
+-- the merge 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, ipr.close_intent
+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),
--- the linked PRs are still all merged when the write runs (a PR linked between
--- the decision and this statement keeps the issue open), and one of them still
--- closes the issue with a keyword. Repositions like UpdateIssueStatus does.
+-- name: MoveIssueFromPullRequests :one
+-- Conditional status write for the PR merge automation. It lands only if the
+-- issue is still in the status the decision saw (two merges racing move it
+-- once), is not already in the target, and the linked PRs are still all merged
+-- when the write runs (a PR linked between the decision and this statement
+-- keeps the issue where it is). Repositions and clears a duplicate mark like
+-- UpdateIssueStatus does; the target is never cancelled.
UPDATE issue AS i SET
- status = 'done',
+ status = sqlc.arg('target_status')::text,
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'
+ AND target.status = sqlc.arg('target_status')::text
),
revision = i.revision + 1,
last_activity_at = GREATEST(COALESCE(i.last_activity_at, i.updated_at), now()),
@@ -76,7 +77,7 @@ UPDATE issue AS i SET
WHERE i.id = $1
AND i.workspace_id = $2
AND i.status = sqlc.arg('expected_status')::text
- AND i.status <> 'done'
+ AND i.status <> sqlc.arg('target_status')::text
AND EXISTS (
SELECT 1 FROM issue_pull_request ipr WHERE ipr.issue_id = i.id
UNION ALL
@@ -92,9 +93,4 @@ WHERE i.id = $1
JOIN vcs_pull_request pr ON pr.id = ipr.pull_request_id
WHERE ipr.issue_id = i.id AND pr.state <> 'merged'
)
- AND EXISTS (
- SELECT 1 FROM issue_pull_request ipr WHERE ipr.issue_id = i.id AND ipr.close_intent
- UNION ALL
- SELECT 1 FROM issue_vcs_pull_request ipr WHERE ipr.issue_id = i.id AND ipr.close_intent
- )
RETURNING i.*;
diff --git a/server/pkg/db/queries/vcs.sql b/server/pkg/db/queries/vcs.sql
index cc4eafb539..94ef3cf9c0 100644
--- a/server/pkg/db/queries/vcs.sql
+++ b/server/pkg/db/queries/vcs.sql
@@ -178,13 +178,6 @@ INSERT INTO issue_vcs_pull_request (
)
ON CONFLICT (issue_id, pull_request_id) DO NOTHING;
--- name: SyncVCSPullRequestCloseIntent :exec
--- Mirrors SyncPullRequestCloseIntent.
-UPDATE issue_vcs_pull_request
-SET close_intent = (issue_id = ANY(sqlc.arg('closing_issue_ids')::uuid[]))
-WHERE pull_request_id = sqlc.arg('pull_request_id')
- AND close_intent <> (issue_id = ANY(sqlc.arg('closing_issue_ids')::uuid[]));
-
-- name: LinkIssueToVCSPullRequestManually :execrows
INSERT INTO issue_vcs_pull_request (
issue_id, pull_request_id, linked_by_type, linked_by_id