Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-7672: only a closing keyword completes an issue on PR merge (#8794)
Bohan Jiang0da0b46bbf1a
diff --git a/apps/docs/content/docs/github-integration.ja.mdx b/apps/docs/content/docs/github-integration.ja.mdxindex 7d24cef664..5df60909e5 100644--- a/apps/docs/content/docs/github-integration.ja.mdx+++ b/apps/docs/content/docs/github-integration.ja.mdx@@ -36,7 +36,7 @@ GitHub 連携が読み取るのは、インストール時に許可されたリ| GitHub 連携 | メインスイッチ。無効にすると下の 3 項目は機能しなくなりますが、GitHub App の接続は解除されません。 || PR サイドバー | 紐づいた pull request をタスクの詳細画面に表示します。 || Co-authored-by | エージェントが作成する commit に `Co-authored-by: multica-agent <[email protected]>` を追加します。 |-| PR の自動紐づけ | ブランチ名かタイトルにタスク番号を含む PR を、そのタスクに紐づけます。 |+| PR の自動紐づけ | ブランチ名かタイトルにタスク番号を含む PR、または本文で closing keyword の直後にタスク番号を置いた PR を、そのタスクに紐づけます。 || **PR カード → CI とマージ可否** | 紐づいた各 PR について、Multica は認証済みの GitHub API スナップショットを取得し、その **CI ステータス**と**マージ可否**をカードにミラーリングします(下記の **PR カードに表示される内容** を参照)。 |@@ -54,7 +54,15 @@ MUL-123 ログイン後のリダイレクトを修正Multica は大文字と小文字を区別せず、現在のワークスペースのタスク接頭辞だけを照合します。1 つの PR を複数のタスクに紐づけることもできます。-Multica は PR 本文を読み取らず、キーワードにも特別な意味はありません。本文に `Closes MUL-123` や `Related to MUL-123` と書いても紐づきません。Commit message と PR コメントも紐づけの対象外です。+タスク番号を PR 本文だけに書く場合は、GitHub の closing keyword を必ず使ってください。++```text+Closes MUL-123+Fixes MUL-123+Resolves MUL-123+```++本文に `Related to MUL-123` のような通常の参照を書いただけでは、そのタスクへまったく紐づきません。Commit message と PR コメントも紐づけの対象外です。手動で紐づけることもできます。タスクの **Pull requests** セクションで **+** をクリックし、PR の URL を貼り付けます。PR をタスクから外すには、その行の **⋯** メニューから **タスクから外す** を選びます。以後、Multica がタイトルやブランチから再び紐づけることはありません。@@ -70,16 +78,19 @@ Multica は PR 本文を読み取らず、キーワードにも特別な意味CI の状態とマージ可能性は、Multica が GitHub API から取得したスナップショットで、互いに独立しています。マージ済みまたはクローズ済みの PR では、この 2 項目を表示しません。GitHub が一時的に利用できない場合、カードを空にせず、前回のスナップショットを古い情報として表示します。-リストの下には、次に何が起きるかを 1 行で表示します。たとえば「#19 がマージされると自動完了」や、マージされずにクローズされた PR です。+リストの下には、次に何が起きるかを 1 行で表示します。たとえば「#19 がマージされると自動完了」、`Closes MUL-123` と書いた PR がないこと、マージされずにクローズされた PR です。項目をクリックすると GitHub の PR が開きます。**PR サイドバー**を無効にしてもこのセクションが非表示になるだけで、接続は解除されません。## PR のマージで Done になる条件-**PR のマージでタスクを自動完了**(**設定 → タスクステータス → 自動化**、既定でオン)が有効な場合、タスクに紐づくすべての PR がマージされると、タスクは `Done` になります。+PR がマージされても、必ずしもタスクが完了するわけではありません。**PR のマージでタスクを自動完了**(**設定 → タスクステータス → 自動化**、既定でオン)が有効な場合、Multica がタスクを `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 → ⋯ → このタスクは自動完了しない**)。-1. タスクに紐づく PR が 1 つ以上あり、すべてが `Merged` である。`Open` や `Draft` の PR が残っているとタスクは待機を続けます。マージされずにクローズされた PR も、タスクから外すまで同様です。-2. タスクが `done` または `cancelled` ではなく、そのタスクだけ自動完了をオフにしていない(**Pull requests → ⋯ → このタスクは自動完了しない**)。マージ後にレビューやリリースが必要な作業向けです。+そのため、ブランチ名やタイトルに `MUL-123` を含めるだけで紐づけは作成されますが、それだけではタスクを完了にしません。マージでタスクを完了させたい場合にだけ closing keyword を使ってください。closing keyword はマージ時点の内容で判断されます。マージ後に書き足しても紐づけが作成されるだけで、タスクは完了しません。判定は PR イベントがタスクに関わったときだけ行います。紐づいた PR のマージ、紐づけの追加、紐づけの解除です。タスクを再度開いても `Done` には戻らず、次に紐づいた PR がマージされたときに完了します。設定をオンにしても、以前にマージされたタスクをさかのぼって完了にはしません。@@ -172,9 +183,9 @@ API サービスを再起動し、**設定 → GitHub** から接続します。- **接続ボタンを使用できない**: `GITHUB_APP_SLUG` と `GITHUB_WEBHOOK_SECRET` が API プロセスに設定されていることを確認します。- **Webhook が 401 を返す**: GitHub App と API が同じ Webhook secret を使っていることを確認し、GitHub の **Recent Deliveries** から再配信します。- **PR が紐づかない**: リポジトリが App の許可範囲にあること、PR の自動紐づけが有効であること、番号が現在のワークスペースのものであること、誰かがタスクから外していないかを確認します。-- **番号を本文にだけ書いている**: 番号をブランチ名または 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** リストの下にある説明を確認します。まだマージされていない PR やマージされずにクローズされた PR、またはタスクやワークスペースで自動完了がオフになっていることが表示されます。+- **PR のマージ後もタスクが完了しない**: タスクの **Pull requests** リストの下にある説明を確認します。closing keyword を使った PR がないこと、まだマージされていない PR やマージされずにクローズされた PR、またはタスクやワークスペースで自動完了がオフになっていることが表示されます。## 次のステップdiff --git a/apps/docs/content/docs/github-integration.ko.mdx b/apps/docs/content/docs/github-integration.ko.mdxindex 037d0a3af2..17ca53e300 100644--- a/apps/docs/content/docs/github-integration.ko.mdx+++ b/apps/docs/content/docs/github-integration.ko.mdx@@ -36,7 +36,7 @@ GitHub 연동은 설치할 때 승인한 저장소만 읽으며 코드, 댓글,| GitHub 연동 | 전체 스위치입니다. 끄면 아래 세 기능이 작동하지 않지만 GitHub App 연결은 해제되지 않습니다. || PR 사이드바 | 태스크 상세 화면에 연결된 pull request를 표시합니다. || Co-authored-by | 에이전트가 만든 commit에 `Co-authored-by: multica-agent <[email protected]>`를 추가합니다. |-| PR 자동 연결 | 브랜치 이름이나 제목에 태스크 번호가 있는 PR을 해당 태스크에 연결합니다. |+| PR 자동 연결 | 브랜치 이름이나 제목에 태스크 번호가 있거나, 본문에서 closing keyword 바로 뒤에 태스크 번호를 쓴 PR을 해당 태스크에 연결합니다. || **PR 카드 → CI와 머지 가능 여부** | 연결된 각 PR에 대해 Multica는 인증된 GitHub API 스냅샷을 가져와, 그 **CI 상태**와 **머지 가능 여부**를 카드에 미러링합니다(아래 **PR 카드에 표시되는 것** 참조). |@@ -54,7 +54,15 @@ MUL-123 로그인 후 리디렉션 수정Multica는 대소문자를 구분하지 않으며 현재 워크스페이스의 태스크 접두사만 매칭합니다. 하나의 PR을 여러 태스크에 연결할 수 있습니다.-Multica는 PR 본문을 읽지 않으며 키워드에도 특별한 의미가 없습니다. 본문에 `Closes MUL-123`이나 `Related to MUL-123`을 써도 연결되지 않습니다. Commit message와 PR 댓글도 연결을 트리거하지 않습니다.+태스크 번호를 PR 본문에만 쓴다면 GitHub의 closing keyword를 사용해야 합니다.++```text+Closes MUL-123+Fixes MUL-123+Resolves MUL-123+```++본문에 `Related to MUL-123`처럼 단순히 언급만 하면 해당 태스크와 전혀 연결되지 않습니다. Commit message와 PR 댓글도 연결을 트리거하지 않습니다.직접 연결할 수도 있습니다. 태스크의 **Pull requests** 영역에서 **+**를 누르고 PR URL을 붙여넣습니다. PR을 태스크에서 빼려면 해당 행의 **⋯** 메뉴에서 **태스크에서 제거**를 선택합니다. 이후 Multica는 제목이나 브랜치를 보고 다시 연결하지 않습니다.@@ -70,16 +78,19 @@ Multica는 PR 본문을 읽지 않으며 키워드에도 특별한 의미가 없CI 상태와 merge 가능 여부는 Multica가 GitHub API에서 가져온 snapshot이며 서로 독립적입니다. 이미 merge되거나 닫힌 PR에는 두 항목을 더 이상 표시하지 않습니다. GitHub를 일시적으로 사용할 수 없으면 카드가 비워지는 대신 마지막 snapshot을 유지하고 만료된 정보라고 표시합니다.-목록 아래에는 다음에 일어날 일을 한 줄로 보여 줍니다. 예를 들어 "#19 병합 시 자동 완료"나 병합되지 않고 닫힌 PR입니다.+목록 아래에는 다음에 일어날 일을 한 줄로 보여 줍니다. 예를 들어 "#19 병합 시 자동 완료", `Closes MUL-123`을 쓴 PR이 없다는 안내, 병합되지 않고 닫힌 PR입니다.항목을 클릭하면 GitHub의 PR이 열립니다. **PR 사이드바**를 꺼도 이 영역만 숨겨질 뿐 연결은 해제되지 않습니다.## PR merge 시 Done 전환 조건-**PR 병합 시 태스크 자동 완료**(**설정 → 태스크 상태 → 자동화**, 기본값 켜짐)가 켜져 있으면 태스크에 연결된 PR이 모두 merge될 때 태스크가 `Done`으로 바뀝니다.+PR이 merge되었다고 해서 태스크가 반드시 끝난 것은 아닙니다. **PR 병합 시 태스크 자동 완료**(**설정 → 태스크 상태 → 자동화**, 기본값 켜짐)가 켜져 있을 때, Multica는 다음 조건을 모두 만족할 때만 태스크를 `Done`으로 바꿉니다.++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 → ⋯ → 이 태스크는 자동 완료하지 않음**).-1. 태스크에 연결된 PR이 하나 이상 있고 모두 `Merged` 상태입니다. `Open`이나 `Draft` PR이 남아 있으면 태스크는 계속 기다립니다. merge되지 않고 닫힌 PR도 태스크에서 제거할 때까지 마찬가지입니다.-2. 태스크가 `done` 또는 `cancelled`가 아니고, 이 태스크만 자동 완료를 끄지 않았습니다(**Pull requests → ⋯ → 이 태스크는 자동 완료하지 않음**). merge 후에 리뷰나 릴리스가 필요한 작업에 사용합니다.+따라서 브랜치 이름이나 제목에만 `MUL-123`을 쓰면 연결은 되지만 그것만으로 태스크가 완료되지는 않습니다. merge와 함께 태스크를 끝내고 싶을 때만 closing keyword를 사용하세요. closing keyword는 merge 시점 기준으로 판단합니다. merge 후에 추가하면 연결만 되고 태스크는 완료되지 않습니다.판단은 PR 이벤트가 태스크에 닿을 때만 이루어집니다. 연결된 PR의 merge, 연결 추가, 연결 제거입니다. 태스크를 다시 열어도 `Done`으로 돌아가지 않으며, 다음에 연결된 PR이 merge될 때 완료됩니다. 설정을 켜도 이전에 merge된 태스크를 소급해 완료하지 않습니다.@@ -172,9 +183,9 @@ API 서비스를 다시 시작한 뒤 **설정 → GitHub**에서 연결을 완- **연결 버튼을 사용할 수 없음**: `GITHUB_APP_SLUG`와 `GITHUB_WEBHOOK_SECRET`이 API 프로세스에 전달되었는지 확인합니다.- **Webhook이 401을 반환함**: GitHub App과 API가 같은 Webhook secret을 사용하는지 확인하고 GitHub의 **Recent Deliveries**에서 다시 전달합니다.- **PR이 연결되지 않음**: 저장소가 App 승인 범위에 있는지, 자동 연결이 켜져 있는지, 번호가 현재 워크스페이스에 속하는지, 누군가 태스크에서 PR을 제거하지 않았는지 확인합니다.-- **번호를 본문에만 적음**: 번호를 브랜치 이름이나 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** 목록 아래 설명을 확인합니다. 아직 merge되지 않았거나 merge 없이 닫힌 PR, 또는 태스크나 워크스페이스에서 자동 완료가 꺼져 있음을 알려 줍니다.+- **PR merge 후 태스크가 완료되지 않음**: 태스크의 **Pull requests** 목록 아래 설명을 확인합니다. closing keyword를 쓴 PR이 없는지, 아직 merge되지 않았거나 merge 없이 닫힌 PR이 있는지, 또는 태스크나 워크스페이스에서 자동 완료가 꺼져 있는지 알려 줍니다.## 다음 단계diff --git a/apps/docs/content/docs/github-integration.mdx b/apps/docs/content/docs/github-integration.mdxindex 43e0a82da6..0f1b5bd76a 100644--- a/apps/docs/content/docs/github-integration.mdx+++ b/apps/docs/content/docs/github-integration.mdx@@ -36,7 +36,7 @@ The **GitHub connection** decides which repositories Multica receives PR events| GitHub integration | Master switch. When off, the three below stop working, but the GitHub App stays connected. || PR sidebar | Shows linked pull requests in issue detail. || Co-authored-by | Adds `Co-authored-by: multica-agent <[email protected]>` to commits created by agents. |-| Auto-link PRs | Links a PR to the issue whose identifier is in its branch name or title. |+| 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. || **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). |@@ -57,7 +57,15 @@ MUL-123 Fix the redirect after loginMultica ignores case and only matches the current workspace's issue prefix. One PR can link to multiple issues.-The PR body isn't scanned, and keywords carry no special meaning: `Closes MUL-123` or `Related to MUL-123` in the body links nothing. Commit messages and PR comments don't trigger linking either.+If the identifier appears only in the PR body, put it right after a closing keyword:++```text+Closes MUL-123+Fixes MUL-123+Resolves MUL-123+```++A bare mention in the body, such as `Related to MUL-123`, doesn't link the PR at all. Commit messages and PR comments don't trigger linking either.You can also link a PR by hand: in the issue's **Pull requests** block, click **+** and paste the PR URL. To take a PR off an issue, open the **⋯** menu on its row and choose **Remove from issue**; Multica won't link it again from its title or branch.@@ -73,16 +81,19 @@ Once linked, PRs appear in the **Pull requests** block of issue detail. Each entCI status and mergeability come from snapshots Multica pulls from the GitHub API, and the two are independent; merged or closed PRs no longer show either. When GitHub is temporarily unavailable, the card keeps the last snapshot and marks it stale instead of going blank.-Under the list, one line says what happens next — for example *Completes when #19 merges*, or which PR closed without merging.+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.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-With **Complete issues when their PRs merge** on (the default), an issue moves to `Done` when every PR linked to it is merged:+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:++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 → ⋯ → Don't auto-complete this issue**).-1. the issue has at least one linked PR, and every linked PR is `Merged` — an `Open` or `Draft` PR keeps it waiting, and so does a PR closed without merging until you remove it from the issue;-2. the issue isn't `done` or `cancelled`, and auto-complete hasn't been turned off for it (**Pull requests → ⋯ → Don't auto-complete this issue**), for work that needs review or a release after the merge.+So writing `MUL-123` only in the branch name or title 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.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.@@ -175,9 +186,9 @@ Restart the API server, then complete the connection in **Settings → GitHub**.- **Connect button disabled**: check that `GITHUB_APP_SLUG` and `GITHUB_WEBHOOK_SECRET` reached the API process.- **Webhook returns 401**: confirm the GitHub App and the API use the same webhook secret, then redeliver from GitHub's **Recent Deliveries**.- **PR not linked**: check that the repository is in the App's authorized scope, auto-linking is on, the identifier belongs to the current workspace, and nobody removed the PR from the issue.-- **Identifier only in the body**: put it in the branch name or PR title, or link the PR by hand.+- **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 names any PR still open or closed without merging, or says auto-complete is off for the issue or the workspace.+- **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.## Next stepsdiff --git a/apps/docs/content/docs/github-integration.zh.mdx b/apps/docs/content/docs/github-integration.zh.mdxindex 674a930e17..e15bcdb221 100644--- a/apps/docs/content/docs/github-integration.zh.mdx+++ b/apps/docs/content/docs/github-integration.zh.mdx@@ -36,7 +36,7 @@ GitHub 集成只读取安装时授权的仓库,不会提交代码、评论或| GitHub 集成 | 总开关。关闭后,下面三项不再生效,但不会断开 GitHub App。 || PR 侧栏 | 在任务详情中显示关联的 pull request。 || Co-authored-by | 在智能体创建的 commit 中加入 `Co-authored-by: multica-agent <[email protected]>`。 |-| 自动关联 PR | 分支名或标题含任务编号的 PR,会关联到对应任务。 |+| 自动关联 PR | 分支名或标题含任务编号、或正文中关闭语句后写了任务编号的 PR,会关联到对应任务。 || **PR 卡片 → CI 与可合并性** | 对每个关联的 PR,Multica 从 GitHub API 拉取一份经鉴权的快照,把它的 **CI 状态**和**可合并性**镜像到卡片上(见下方 **PR 卡片展示什么**)。 |@@ -57,7 +57,15 @@ MUL-123 修复登录后的跳转Multica 会忽略大小写,并且只匹配当前工作区的任务前缀。一个 PR 可以关联多个任务。-Multica 不读取 PR 正文,关键词也没有特殊含义:正文里写 `Closes MUL-123` 或 `Related to MUL-123` 都不会建立关联。Commit message 和 PR 评论也不会触发关联。+只在 PR 正文中写编号时,需要使用 GitHub 的关闭语句:++```text+Closes MUL-123+Fixes MUL-123+Resolves MUL-123+```++正文中的普通提及,例如 `Related to MUL-123`,不会与该任务建立关联。Commit message 和 PR 评论也不会触发关联。也可以手动关联:在任务的 **Pull requests** 区块点 **+**,粘贴 PR 链接。要把 PR 从任务上移除,打开这一行的 **⋯** 菜单,选择 **移除关联**;之后 Multica 不会再根据标题或分支把它关联回来。@@ -73,16 +81,19 @@ Multica 不读取 PR 正文,关键词也没有特殊含义:正文里写 `CloCI 状态和可合并性来自 Multica 从 GitHub API 拉取的快照,两者互相独立;已合并或已关闭的 PR 不再显示这两项。GitHub 暂时不可用时,卡片会保留上一次的快照并标记为过期,而不是清空。-列表下方有一行说明接下来会发生什么,例如「等待 #19 合并后自动完成」,或者哪个 PR 已关闭、未合并。+列表下方有一行说明接下来会发生什么,例如「等待 #19 合并后自动完成」、没有 PR 写 `Closes MUL-123`,或者哪个 PR 已关闭、未合并。点击记录可以打开 GitHub 上的 PR。关闭 **PR 侧栏** 只会隐藏这个区块,不会断开连接。## PR 合并转 Done 的条件-开启 **PR 合并后自动完成任务**(默认开启)时,任务的所有关联 PR 都合并后,任务改为 `Done`:+PR 合并不一定代表任务已完成。开启 **PR 合并后自动完成任务**(默认开启)时,只有以下条件同时成立,任务才会改为 `Done`:++1. 至少一个已合并的关联 PR 在标题或正文中使用了紧跟编号的关闭语句,例如 `Closes MUL-123`(`Closes login MUL-123` 这类中间隔词的写法不生效,分支名也不算);+2. 所有关联 PR 都是 `Merged`。仍为 `Open` 或 `Draft` 的 PR 会让任务继续等待;关闭但未合并的 PR 也一样,直到你把它从任务上移除;+3. 任务当前不是 `done` 或 `cancelled`,也没有单独关闭自动完成(**Pull requests → ⋯ → 此任务不自动完成**)。-1. 任务至少有一个关联 PR,且所有关联 PR 都是 `Merged`。仍为 `Open` 或 `Draft` 的 PR 会让任务继续等待;关闭但未合并的 PR 也一样,直到你把它从任务上移除;-2. 任务当前不是 `done` 或 `cancelled`,也没有单独关闭自动完成(**Pull requests → ⋯ → 此任务不自动完成**),适用于合并后还需要验收或发布的工作。+因此,仅在分支名或标题中写 `MUL-123` 会建立关联,但不会单独触发完成;只有希望 PR 合并即完成任务时,才使用关闭语句。关闭语句以合并时为准:PR 合并后再补写,只会建立关联,不会完成任务。只有 PR 事件会触发判断:关联 PR 合并、新增关联或移除关联。重新打开任务后,它不会被改回 `Done`,下一个关联 PR 合并时才会。开启这项设置,也不会补完成此前已合并的任务。@@ -175,9 +186,9 @@ make migrate-up- **连接按钮不可用**:检查 `GITHUB_APP_SLUG` 和 `GITHUB_WEBHOOK_SECRET` 是否已进入 API 进程。- **Webhook 返回 401**:确认 GitHub App 与 API 使用同一个 Webhook secret,然后在 GitHub 的 **Recent Deliveries** 中重新投递。- **PR 没有关联**:检查仓库是否在 App 授权范围内、自动关联是否开启、编号是否属于当前工作区,以及是否有人把它从任务上移除过。-- **编号只写在正文里**:把编号放到分支名或 PR 标题中,或者手动关联。+- **正文写了编号但没关联**:改用 `Closes MUL-123`,或把编号放到分支名、PR 标题中,或者手动关联。- **没有 CI 状态**:确认 `GITHUB_APP_ID` 和 `GITHUB_APP_PRIVATE_KEY` 已配置,App 具有 Contents、Checks 与 Commit statuses 的只读权限并订阅了对应事件。缺少 Contents 会让整个快照失败,PR 卡片既没有 CI 也没有合并状态。给已安装的 App 补加权限后,还需要各 installation 的所有者在 GitHub 上批准才会生效。-- **PR 合并后任务没完成**:看任务 **Pull requests** 列表下方的说明,它会指出仍未合并或已关闭未合并的 PR,或者说明任务、工作区关闭了自动完成。+- **PR 合并后任务没完成**:看任务 **Pull requests** 列表下方的说明,它会指出没有 PR 使用关闭语句、仍未合并或已关闭未合并的 PR,或者说明任务、工作区关闭了自动完成。## 接下来diff --git a/apps/docs/content/docs/issues.ja.mdx b/apps/docs/content/docs/issues.ja.mdxindex 7642af2dea..51b4eae861 100644--- a/apps/docs/content/docs/issues.ja.mdx+++ b/apps/docs/content/docs/issues.ja.mdx@@ -63,13 +63,13 @@ import { Callout } from "fumadocs-ui/components/callout";ステータス間に固定のフローはなく、メンバーもエージェントも直接変更できます。-エージェントは、作業がタスクに与えた実際の変化をそのままステータスに書き込みます。タスクが求めているもの(コードでも、調査でも、設計でも、タスク自身が求めるレビューでも)を作り始めた時点で `in_progress` に進め、実行中からボードに反映させます。納品したら `in_review` に進め、ターンを越えて作業が続く場合は `in_progress` のままにします。そのタスク自身の成果物を生まないターン(質問への回答、他所が持つ作業への助言)では、最初から最後までステータスを変更しません。これらの変更は、実行中にエージェントが Multica CLI から明示的に書き込むものです。実行の開始や完了でサーバーがタスクのステータスを切り替えることはありません(下記の 2 つのシステム例外を除く)。`done` は通常、人による確認か、タスクに紐づく PR がすべてマージされたときに設定されます。+エージェントは、作業がタスクに与えた実際の変化をそのままステータスに書き込みます。タスクが求めているもの(コードでも、調査でも、設計でも、タスク自身が求めるレビューでも)を作り始めた時点で `in_progress` に進め、実行中からボードに反映させます。納品したら `in_review` に進め、ターンを越えて作業が続く場合は `in_progress` のままにします。そのタスク自身の成果物を生まないターン(質問への回答、他所が持つ作業への助言)では、最初から最後までステータスを変更しません。これらの変更は、実行中にエージェントが Multica CLI から明示的に書き込むものです。実行の開始や完了でサーバーがタスクのステータスを切り替えることはありません(下記の 2 つのシステム例外を除く)。`done` は通常、人による確認か、`Closes MUL-123` のような closing keyword を含む紐づき PR のマージによって設定されます。<Callout type="info">次の 2 つの変更はシステムが行います。- 実行が失敗し、そのタスクにほかの実行がなく、リトライも起動しなかった場合、`in_progress` は `todo` に戻ります。-- タスクに紐づく PR がすべてマージされると、タスクは `done` になります。ワークスペースまたはそのタスクで PR による自動完了がオフの場合を除きます。詳しくは [GitHub 連携](/github-integration)を参照してください。+- タスクに紐づく PR がすべてマージされ、そのうち 1 つが `Closes MUL-123` のような closing keyword を含む場合、タスクは `done` になります。ワークスペースまたはそのタスクで PR による自動完了がオフの場合を除きます。詳しくは [GitHub 連携](/github-integration)を参照してください。</Callout>### カスタムステータスdiff --git a/apps/docs/content/docs/issues.ko.mdx b/apps/docs/content/docs/issues.ko.mdxindex 04487f8f9c..3107d9bf42 100644--- a/apps/docs/content/docs/issues.ko.mdx+++ b/apps/docs/content/docs/issues.ko.mdx@@ -63,13 +63,13 @@ import { Callout } from "fumadocs-ui/components/callout";상태 사이에는 고정된 전환 순서가 없으며 멤버와 에이전트 모두 상태를 직접 변경할 수 있습니다.-에이전트는 작업이 태스크에 실제로 일으킨 변화를 그대로 상태에 기록합니다. 태스크가 요구하는 것을 만들기 시작하면, 그것이 코드든 조사든 설계든 태스크 자체가 요청한 리뷰든 바로 `in_progress`로 옮겨 실행 중에도 보드에 드러나게 합니다. 전달하면 `in_review`로 옮기고, 작업이 이번 턴을 넘어 이어지면 `in_progress`로 유지합니다. 그 태스크 자체의 결과물을 만들지 않는 턴, 예를 들어 질문에 답하거나 다른 곳이 소유한 작업에 조언하는 경우에는 처음부터 끝까지 상태를 바꾸지 않습니다. 이 변경은 실행 중에 에이전트가 Multica CLI로 명시적으로 기록하는 것입니다. 실행이 시작되거나 끝날 때 서버가 태스크 상태를 바꾸지는 않습니다(아래 두 가지 시스템 예외 제외). `done`은 보통 사람의 확인이나, 태스크에 연결된 PR이 모두 병합될 때 지정됩니다.+에이전트는 작업이 태스크에 실제로 일으킨 변화를 그대로 상태에 기록합니다. 태스크가 요구하는 것을 만들기 시작하면, 그것이 코드든 조사든 설계든 태스크 자체가 요청한 리뷰든 바로 `in_progress`로 옮겨 실행 중에도 보드에 드러나게 합니다. 전달하면 `in_review`로 옮기고, 작업이 이번 턴을 넘어 이어지면 `in_progress`로 유지합니다. 그 태스크 자체의 결과물을 만들지 않는 턴, 예를 들어 질문에 답하거나 다른 곳이 소유한 작업에 조언하는 경우에는 처음부터 끝까지 상태를 바꾸지 않습니다. 이 변경은 실행 중에 에이전트가 Multica CLI로 명시적으로 기록하는 것입니다. 실행이 시작되거나 끝날 때 서버가 태스크 상태를 바꾸지는 않습니다(아래 두 가지 시스템 예외 제외). `done`은 보통 사람의 확인이나, `Closes MUL-123` 같은 closing keyword가 있는 연결 PR의 병합으로 지정됩니다.<Callout type="info">다음 두 가지 변경은 시스템이 수행합니다.- 실행이 실패하고 해당 태스크에 다른 실행이 없으며 재시도도 트리거되지 않으면 `in_progress`가 `todo`로 돌아갑니다.-- 태스크에 연결된 PR이 모두 병합되면 태스크가 `done`으로 바뀝니다. 워크스페이스나 해당 태스크에서 PR 자동 완료를 끈 경우는 제외합니다. 자세한 내용은 [GitHub 연동](/github-integration)을 참고하세요.+- 태스크에 연결된 PR이 모두 병합되고 그중 하나에 `Closes MUL-123` 같은 closing keyword가 있으면 태스크가 `done`으로 바뀝니다. 워크스페이스나 해당 태스크에서 PR 자동 완료를 끈 경우는 제외합니다. 자세한 내용은 [GitHub 연동](/github-integration)을 참고하세요.</Callout>### 사용자 지정 상태diff --git a/apps/docs/content/docs/issues.mdx b/apps/docs/content/docs/issues.mdxindex c90ee127c4..cd4e690e93 100644--- a/apps/docs/content/docs/issues.mdx+++ b/apps/docs/content/docs/issues.mdx@@ -63,13 +63,13 @@ Categories keep lifecycle reasoning simple. Boards, lists, filters, and sortingThere is no fixed flow between statuses — members and agents can change them directly.-Agents write the status the issue is in as their work changes it: starting work on what the issue asks for — in whatever form, research, design, or a review the issue itself requests — moves it to `in_progress` right away, so the board shows the work while it runs; delivering moves it to `in_review`; work that continues beyond the turn keeps it `in_progress`; a turn that produces nothing of the issue's own deliverable — answering questions, consulting on work owned elsewhere — leaves the status untouched throughout. These updates are written explicitly by the agent through the Multica CLI during the run — the server does not flip issue status when a run starts or completes (apart from the two system exceptions below). `done` is usually a human confirmation, or the merge of an issue's linked PRs.+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`.<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, 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 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).</Callout>### Custom statusesdiff --git a/apps/docs/content/docs/issues.zh.mdx b/apps/docs/content/docs/issues.zh.mdxindex 115e9202ff..5ea6155f2a 100644--- a/apps/docs/content/docs/issues.zh.mdx+++ b/apps/docs/content/docs/issues.zh.mdx@@ -63,13 +63,13 @@ import { Callout } from "fumadocs-ui/components/callout";状态之间没有固定流转,成员和智能体都可以直接修改。-智能体随着工作对任务的实际影响写入状态:开始产出任务本身要求的东西时立刻推到 `in_progress`——不论形式是代码、调研、设计,还是任务本身要求的 review——让看板在工作进行中就能反映出来;交付后推到 `in_review`;工作跨轮继续则保持 `in_progress`;没有产出本任务交付物的轮次(答疑、给别处的工作做咨询)则全程不改状态。这些状态变更由智能体在运行中通过 Multica CLI 显式写入——运行开始或完成时,服务端不会自动改任务状态(下面两个系统例外除外)。`done` 通常留给人工确认,或在任务的关联 PR 全部合并时由系统完成。+智能体随着工作对任务的实际影响写入状态:开始产出任务本身要求的东西时立刻推到 `in_progress`——不论形式是代码、调研、设计,还是任务本身要求的 review——让看板在工作进行中就能反映出来;交付后推到 `in_review`;工作跨轮继续则保持 `in_progress`;没有产出本任务交付物的轮次(答疑、给别处的工作做咨询)则全程不改状态。这些状态变更由智能体在运行中通过 Multica CLI 显式写入——运行开始或完成时,服务端不会自动改任务状态(下面两个系统例外除外)。`done` 通常留给人工确认,或由带关闭语句(例如 `Closes MUL-123`)的关联 PR 合并后由系统完成。<Callout type="info">两个变化由系统执行:- 执行失败,且该任务没有其他执行、也没有触发重试时,`in_progress` 回到 `todo`。-- 任务的所有关联 PR 都合并后,任务变为 `done`,除非工作区或该任务关闭了 PR 自动完成。详见 [GitHub 集成](/github-integration)。+- 任务的所有关联 PR 都合并、且其中有 PR 使用了关闭语句(例如 `Closes MUL-123`)时,任务变为 `done`,除非工作区或该任务关闭了 PR 自动完成。详见 [GitHub 集成](/github-integration)。</Callout>### 自定义状态diff --git a/apps/docs/content/docs/vcs-integration.ja.mdx b/apps/docs/content/docs/vcs-integration.ja.mdxindex 7ad88a79f4..1b95e275c7 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 を対応するタスクへ自動的に紐づけ、終了キーワードを含む PR のマージ時に「完了」へ移動して CI ステータスを表示します。---import { Callout } from "fumadocs-ui/components/callout";@@ -9,7 +9,7 @@ import { Callout } from "fumadocs-ui/components/callout";**セルフホスト版 Multica 専用です。** この連携は Multica を**自分でデプロイしている**場合のみ利用でき、Multica Cloud では提供されません。ここでの「セルフホスト」は **Multica 自体**のセルフホストを意味します。通常は独自ネットワーク内の Git インスタンスへアクセスするために使用します。サーバー運用者が `MULTICA_VCS_INTEGRATION_ENABLED=true` を設定して機能を有効にし、`MULTICA_VCS_SECRET_KEY` も設定する必要があります。それまでは、設定 → 連携にこのセクションは表示されません。</Callout>-Multica はワークスペースごとにセルフホストの Git ホスティング、**Forgejo**、**Gitea**、**GitLab** のいずれかへ接続します。接続後、ブランチ名かタイトルにタスク番号(例: `MUL-123`)を含む Pull Request(GitLab では Merge Request)は、対応する[タスク](/issues)へ**自動的に紐づけられ**、タスクサイドバーの **Pull requests** に表示されます。タスクに紐づく PR がすべてマージされると、タスクは「完了」へ移動します。head commit の CI はカード上のチェックバーとして表示されます。+Multica はワークスペースごとにセルフホストの Git ホスティング、**Forgejo**、**Gitea**、**GitLab** のいずれかへ接続します。接続後、ブランチ名かタイトルにタスク番号(例: `MUL-123`)を含む Pull Request(GitLab では Merge Request)、または本文で終了キーワードの直後にタスク番号を置いた PR は、対応する[タスク](/issues)へ**自動的に紐づけられ**、タスクサイドバーの **Pull requests** に表示されます。タスクに紐づく PR がすべてマージされ、そのうち 1 つが終了キーワードを含む場合、タスクは「完了」へ移動します。head commit の CI はカード上のチェックバーとして表示されます。これらの Git ホスティングは GitHub と並行して利用でき、1 つのワークスペースで任意に組み合わせられます。@@ -82,7 +82,7 @@ Multica は保存済みの secret で各 delivery を検証するため、一致## ミラーされる内容- **Pull / Merge Request** — open、closed、merged、draft の状態、作成者、ブランチ、および Git ホスティングが提供する場合は diff 統計。-- **タスクの紐づけ** — タイトルまたはブランチの番号で PR をタスクへ紐づけます。本文は読み取らないため、本文の `Closes MUL-123` では紐づきません。タスクに紐づく PR(GitHub とセルフホストの両方)がすべてマージされると、[GitHub](/github-integration) と同じワークスペース設定とルールに従ってタスクを「完了」へ移動します。+- **タスクの紐づけ** — タイトルまたはブランチの番号、および本文で終了キーワードの直後に置いた番号で PR をタスクへ紐づけます。本文中の通常の参照では紐づきません。タスクに紐づく PR(GitHub とセルフホストの両方)がすべてマージされ、そのうち 1 つが終了キーワード(`Closes`/`Fixes`/`Resolves MUL-123`)を含む場合、[GitHub](/github-integration) と同じワークスペース設定とルールに従ってタスクを「完了」へ移動します。- **CI** — Forgejo/Gitea の commit status と GitLab pipeline を、head commit の成功/失敗/進行中チェックバーへ集約します。## エージェントによる Pull Request の作成diff --git a/apps/docs/content/docs/vcs-integration.ko.mdx b/apps/docs/content/docs/vcs-integration.ko.mdxindex 2f08bc0455..c875762174 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를 해당 태스크에 자동 연결하고, 종료 키워드가 있는 PR이 merge되면 완료로 옮기며 CI 상태를 표시합니다.---import { Callout } from "fumadocs-ui/components/callout";@@ -9,7 +9,7 @@ import { Callout } from "fumadocs-ui/components/callout";**자체 배포한 Multica에서만 사용할 수 있습니다.** 이 연동은 Multica를 **직접 배포해 운영할 때만** 제공되며 Multica Cloud에서는 사용할 수 없습니다. 여기서 "자체 호스팅"은 **Multica 자체를 배포하는 것**을 뜻합니다. 일반적으로 자체 네트워크의 Git 인스턴스에 접근하기 위해 사용합니다. 서버 운영자가 `MULTICA_VCS_INTEGRATION_ENABLED=true`로 기능을 켜고 `MULTICA_VCS_SECRET_KEY`도 설정해야 합니다. 그전에는 설정 → 연동에 이 영역이 표시되지 않습니다.</Callout>-Multica는 워크스페이스별로 자체 호스팅 Git 코드 호스팅인 **Forgejo**, **Gitea**, **GitLab** 중 하나에 연결합니다. 연결하면 브랜치 이름이나 제목에 태스크 번호(예: `MUL-123`)가 포함된 Pull Request(GitLab에서는 Merge Request)가 해당 [태스크](/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을 태스크에 연결합니다. 본문은 읽지 않으므로 본문의 `Closes MUL-123`은 아무것도 연결하지 않습니다. 태스크에 연결된 PR(GitHub와 자체 호스팅 모두)이 모두 merge되면 [GitHub](/github-integration)와 같은 워크스페이스 설정과 규칙에 따라 태스크를 완료로 옮깁니다.+- **태스크 연결** — 제목이나 브랜치의 번호, 그리고 본문에서 종료 키워드 바로 뒤에 쓴 번호가 PR을 태스크에 연결합니다. 본문의 단순 언급은 연결하지 않습니다. 태스크에 연결된 PR(GitHub와 자체 호스팅 모두)이 모두 merge되고 그중 하나에 종료 키워드(`Closes`/`Fixes`/`Resolves MUL-123`)가 있으면 [GitHub](/github-integration)와 같은 워크스페이스 설정과 규칙에 따라 태스크를 완료로 옮깁니다.- **CI** — Forgejo/Gitea commit status와 GitLab pipeline을 head commit의 통과/실패/진행 중 check bar로 집계합니다.## 에이전트의 Pull Request 생성diff --git a/apps/docs/content/docs/vcs-integration.mdx b/apps/docs/content/docs/vcs-integration.mdxindex dc6a17af06..1c1cb51f85 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 auto-attach to that issue, move it to Done once every linked PR is merged, 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 Done when they merge with a closing keyword, and show CI status.---import { Callout } from "fumadocs-ui/components/callout";@@ -14,7 +14,7 @@ and set `MULTICA_VCS_SECRET_KEY`; until then the section does not appear inSettings → Integrations.</Callout>-Multica connects to a self-hosted Git provider per workspace: **Forgejo**, **Gitea**, or **GitLab**. Once connected, any pull request (GitLab: merge request) whose branch name or title contains an issue identifier (for example `MUL-123`) is **auto-linked** to that [issue](/issues) and appears under **Pull requests** in the issue sidebar. When every PR linked to the issue is merged, the issue moves to **Done**. CI for the head commit shows as a checks bar on the card.+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.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; the body isn't scanned, so `Closes MUL-123` there links nothing. Once every PR linked to the issue is merged — across GitHub and self-hosted providers — the issue moves to **Done**, under the same workspace setting and rules as [GitHub](/github-integration).+- **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).- **CI** — Forgejo/Gitea commit statuses and GitLab pipelines aggregate into a passed/failed/pending checks bar for the head commit.## Agents opening pull requestsdiff --git a/apps/docs/content/docs/vcs-integration.zh.mdx b/apps/docs/content/docs/vcs-integration.zh.mdxindex d618e9d079..d3c3d441c1 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`)的 Pull Request(GitLab 为 Merge Request)都会**自动关联**到对应的 [任务](/issues),出现在任务侧栏的 **Pull requests** 中;任务的所有关联 PR 都合并后,任务会被移动到「完成」。head commit 的 CI 会以检查条的形式显示在卡片上。+Multica 按工作区连接自托管的 Git 代码托管:**Forgejo**、**Gitea** 或 **GitLab**。连接后,任何在分支名或标题中包含任务编号(例如 `MUL-123`)、或在正文的关闭关键字后写出该编号(`Closes MUL-123`)的 Pull Request(GitLab 为 Merge Request)都会**自动关联**到对应的 [任务](/issues),出现在任务侧栏的 **Pull requests** 中;任务的所有关联 PR 都合并、且其中有 PR 使用了关闭关键字时,任务会被移动到「完成」。head commit 的 CI 会以检查条的形式显示在卡片上。这些代码托管与 GitHub 并行工作:一个工作区可任意组合使用。@@ -82,7 +82,7 @@ Multica 会用存储的密钥校验每次投递,因此没有匹配密钥的 We## 镜像的内容- **Pull / Merge Request** —— open、closed、merged、draft 状态,以及作者、分支和(在代码托管提供时)diff 统计。-- **任务关联** —— 标题或分支中的编号会将 PR 关联到任务;Multica 不读取正文,正文里写 `Closes MUL-123` 不会建立关联。任务的所有关联 PR(包括 GitHub 与自托管平台上的)都合并后,任务会被移动到「完成」,遵循与 [GitHub](/github-integration) 相同的工作区设置和规则。+- **任务关联** —— 标题或分支中的编号会将 PR 关联到任务,正文中的编号只有紧跟关闭关键字时才会关联;正文中的普通提及不会建立任何关联。任务的所有关联 PR(包括 GitHub 与自托管平台上的)都合并、且其中有 PR 使用了关闭关键字(`Closes`/`Fixes`/`Resolves MUL-123`)时,任务会被移动到「完成」,遵循与 [GitHub](/github-integration) 相同的工作区设置和规则。- **CI** —— Forgejo/Gitea 的提交状态与 GitLab 的流水线会汇总为 head commit 的通过/失败/进行中检查条。## 智能体创建 Pull Requestdiff --git a/packages/core/types/github.ts b/packages/core/types/github.tsindex d39b1390ea..ea97c96ce9 100644--- a/packages/core/types/github.ts+++ b/packages/core/types/github.ts@@ -58,17 +58,18 @@ export interface GitHubInstallation {}/** Why a PR is on an issue: linked by hand, or matched in its title / branch.- * "auto" is a link made under an older rule. */+ * "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 → Done" rule will do for one issue. The- * server computes it; the issue page only renders it. */+/** 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. */export type PRAutoCompleteState =| "none"| "workspace_disabled"| "issue_disabled"| "terminal"| "triage"+ | "no_close_intent"| "waiting"| "not_merged"| "all_merged";diff --git a/packages/views/issues/components/pull-request-list.test.tsx b/packages/views/issues/components/pull-request-list.test.tsxindex 3a07eae90c..f6807d82ee 100644--- a/packages/views/issues/components/pull-request-list.test.tsx+++ b/packages/views/issues/components/pull-request-list.test.tsx@@ -377,8 +377,9 @@ describe("PullRequestList sidebar rows", () => {});});-// MUL-7429: the line under the list says what "every linked PR merged → Done"-// will do, straight from the server's decision, and each row can be removed.+// 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.describe("PullRequestList auto-complete", () => {beforeEach(() => {mockAutoComplete = null;@@ -419,6 +420,15 @@ describe("PullRequestList auto-complete", () => {);});+ 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(+ "No PR says “Closes MUL-1”, so merging won’t complete this issue",+ );+ });+it("links the workspace setting when auto-complete is off there", async () => {mockPRs = [makePR({ id: "a", number: 12, state: "merged" })];mockAutoComplete = decision("workspace_disabled", [], { workspace_enabled: false });diff --git a/packages/views/issues/components/pull-request-list.tsx b/packages/views/issues/components/pull-request-list.tsxindex 54a1ee3180..53f8cff501 100644--- a/packages/views/issues/components/pull-request-list.tsx+++ b/packages/views/issues/components/pull-request-list.tsx@@ -123,7 +123,7 @@ export function PullRequestList({</div>) : null}{autoComplete ? (- <AutoCompleteLine issueId={issueId} prs={prs} autoComplete={autoComplete} />+ <AutoCompleteLine issueId={issueId} identifier={identifier} prs={prs} autoComplete={autoComplete} />) : null}</div>);@@ -215,16 +215,18 @@ function PullRequestRowMenu({ pr, actions }: { pr: GitHubPullRequest; actions: R}/**- * One line under the PR list saying what the "every linked PR merged → Done"- * rule will do for this issue, straight from the server's decision. Terminal,- * triage and unknown states render nothing.+ * 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.*/function AutoCompleteLine({issueId,+ identifier,prs,autoComplete,}: {issueId: string;+ identifier: string;prs: GitHubPullRequest[];autoComplete: PRAutoComplete;}) {@@ -266,6 +268,10 @@ 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);diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.jsonindex 519ccfe1f1..51e740d516 100644--- a/packages/views/locales/en/issues.json+++ b/packages/views/locales/en/issues.json@@ -1137,6 +1137,7 @@"waiting_other": "Completes when {{prs}} merge","not_merged": "{{prs}} closed without merging","not_merged_action": "Remove",+ "no_close_intent": "No PR says “Closes {{identifier}}”, so merging won’t complete this issue","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",diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.jsonindex 613cf4ea72..866c25f5b4 100644--- a/packages/views/locales/en/settings.json+++ b/packages/views/locales/en/settings.json@@ -84,9 +84,9 @@},"automation_title": "Automation","pr_auto_complete_label": "Complete issues when their PRs merge",- "pr_auto_complete_description": "An issue moves to Done once every linked PR is merged. Applies to PRs merged from now on.",- "pr_auto_complete_example": "PRs link by the issue ID in their title or branch name, e.g.",- "pr_auto_complete_example_title": "MUL-123: Fix login redirect",+ "pr_auto_complete_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": {@@ -793,7 +793,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.",+ "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",diff --git a/packages/views/locales/fr/issues.json b/packages/views/locales/fr/issues.jsonindex 699b00755c..3bcc35703f 100644--- a/packages/views/locales/fr/issues.json+++ b/packages/views/locales/fr/issues.json@@ -1137,6 +1137,7 @@"waiting_other": "Se termine quand {{prs}} sont fusionnées","not_merged": "{{prs}} fermée sans fusion","not_merged_action": "Retirer",+ "no_close_intent": "Aucune PR n’indique « Closes {{identifier}} » : la fusion ne terminera pas cette tâche","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",diff --git a/packages/views/locales/fr/settings.json b/packages/views/locales/fr/settings.jsonindex 5096834790..80bd0c75cb 100644--- a/packages/views/locales/fr/settings.json+++ b/packages/views/locales/fr/settings.json@@ -84,9 +84,9 @@},"automation_title": "Automatisation","pr_auto_complete_label": "Terminer les tâches quand leurs PR sont fusionnées",- "pr_auto_complete_description": "Une tâche passe à Terminé dès que toutes ses PR liées sont fusionnées. S’applique aux PR fusionnées à partir de maintenant.",- "pr_auto_complete_example": "Les PR sont liées par l’identifiant de la tâche dans leur titre ou leur branche, par ex.",- "pr_auto_complete_example_title": "MUL-123 : Corriger la redirection après connexion",+ "pr_auto_complete_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": {@@ -793,7 +793,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.",+ "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",diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.jsonindex 5cb1c879fd..22981b84d4 100644--- a/packages/views/locales/ja/issues.json+++ b/packages/views/locales/ja/issues.json@@ -1105,6 +1105,7 @@"waiting_other": "{{prs}} がマージされると自動完了","not_merged": "{{prs}} はマージされずにクローズされました","not_merged_action": "外す",+ "no_close_intent": "「Closes {{identifier}}」と書いた PR がないため、マージしても自動完了しません","all_merged": "PR はすべてマージ済みです。次に PR がマージされると自動完了します。","issue_disabled": "このタスクは自動完了しません","issue_disabled_action": "再開",diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.jsonindex c1ec137786..49843162a0 100644--- a/packages/views/locales/ja/settings.json+++ b/packages/views/locales/ja/settings.json@@ -84,9 +84,9 @@},"automation_title": "自動化","pr_auto_complete_label": "PR のマージでタスクを自動完了",- "pr_auto_complete_description": "関連する PR がすべてマージされると、タスクは「完了」になります。今後マージされる PR にのみ適用されます。",- "pr_auto_complete_example": "PR はタイトルかブランチ名のタスク番号で関連付けられます。例:",- "pr_auto_complete_example_title": "MUL-123: ログイン後のリダイレクトを修正",+ "pr_auto_complete_description": "関連する PR がすべてマージされ、そのうち 1 つがクローズキーワードでタスクを指定していると、タスクは「完了」になります。今後マージされる PR にのみ適用されます。",+ "pr_auto_complete_example": "キーワードは PR のタイトルか説明に書きます。例:",+ "pr_auto_complete_example_title": "Closes MUL-123","pr_auto_complete_badge": "PR のマージで自動設定"},"quick_actions": {@@ -791,7 +791,7 @@"repositories_shortcut_label": "リポジトリ URL はリポジトリタブにあります","repositories_shortcut_link": "リポジトリを管理 →","toast_failed": "GitHub 設定を更新できませんでした",- "feature_auto_link_description": "タイトルかブランチ名にタスク番号(例: {{example}})を含む PR を、そのタスクに関連付けます。",+ "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": "オフ · すべてのコードホストで共通",diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.jsonindex 7bcab4f4ab..9b3e5b38d9 100644--- a/packages/views/locales/ko/issues.json+++ b/packages/views/locales/ko/issues.json@@ -1105,6 +1105,7 @@"waiting_other": "{{prs}} 병합 시 자동 완료","not_merged": "{{prs}}이(가) 병합되지 않고 닫혔습니다","not_merged_action": "제거",+ "no_close_intent": "\"Closes {{identifier}}\"라고 쓴 PR이 없어 병합해도 자동 완료되지 않습니다","all_merged": "PR이 모두 병합되었습니다. 다음 PR이 병합되면 자동 완료됩니다.","issue_disabled": "이 태스크는 자동 완료하지 않습니다","issue_disabled_action": "다시 켜기",diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.jsonindex cacb494454..9ef4e7882f 100644--- a/packages/views/locales/ko/settings.json+++ b/packages/views/locales/ko/settings.json@@ -84,9 +84,9 @@},"automation_title": "자동화","pr_auto_complete_label": "PR 병합 시 태스크 자동 완료",- "pr_auto_complete_description": "연결된 PR이 모두 병합되면 태스크가 완료로 바뀝니다. 앞으로 병합되는 PR에만 적용됩니다.",- "pr_auto_complete_example": "PR은 제목이나 브랜치 이름의 태스크 번호로 연결됩니다. 예:",- "pr_auto_complete_example_title": "MUL-123: 로그인 리디렉션 수정",+ "pr_auto_complete_description": "연결된 PR이 모두 병합되고 그중 하나가 닫기 키워드로 태스크를 지정하면 태스크가 완료로 바뀝니다. 앞으로 병합되는 PR에만 적용됩니다.",+ "pr_auto_complete_example": "키워드는 PR 제목이나 설명에 씁니다. 예:",+ "pr_auto_complete_example_title": "Closes MUL-123","pr_auto_complete_badge": "PR 병합 시 자동 설정"},"quick_actions": {@@ -791,7 +791,7 @@"repositories_shortcut_label": "저장소 URL은 저장소 탭에 있습니다","repositories_shortcut_link": "저장소 관리 →","toast_failed": "GitHub 설정을 업데이트하지 못했습니다",- "feature_auto_link_description": "제목이나 브랜치 이름에 태스크 번호(예: {{example}})가 있는 PR을 해당 태스크에 연결합니다.",+ "feature_auto_link_description": "제목이나 브랜치 이름에 태스크 번호(예: {{example}})가 있거나 설명에 \"Closes {{example}}\"가 있는 PR을 해당 태스크에 연결합니다.","feature_pr_auto_complete_label": "PR 병합 시 태스크 자동 완료","feature_pr_auto_complete_on": "켜짐 · 모든 코드 호스트에 공통 적용","feature_pr_auto_complete_off": "꺼짐 · 모든 코드 호스트에 공통 적용",diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.jsonindex e7b5bf3397..172c479a3c 100644--- a/packages/views/locales/zh-Hans/issues.json+++ b/packages/views/locales/zh-Hans/issues.json@@ -1105,6 +1105,7 @@"waiting_other": "等待 {{prs}} 合并后自动完成","not_merged": "{{prs}} 已关闭,未合并","not_merged_action": "移除",+ "no_close_intent": "没有 PR 写 \"Closes {{identifier}}\",合并后不会自动完成","all_merged": "PR 均已合并。之后有新 PR 合并时会自动完成。","issue_disabled": "此任务不自动完成","issue_disabled_action": "恢复",diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.jsonindex 7cf4da3b19..b384bb9aac 100644--- a/packages/views/locales/zh-Hans/settings.json+++ b/packages/views/locales/zh-Hans/settings.json@@ -84,9 +84,9 @@},"automation_title": "自动化","pr_auto_complete_label": "PR 合并后自动完成任务",- "pr_auto_complete_description": "任务关联的 PR 全部合并后,状态改为「已完成」。只对之后合并的 PR 生效。",- "pr_auto_complete_example": "PR 标题或分支名含任务编号时自动关联,例如",- "pr_auto_complete_example_title": "MUL-123: 修复登录跳转",+ "pr_auto_complete_description": "任务关联的 PR 全部合并,且至少一个 PR 写了关闭语句时,状态改为「已完成」。只对之后合并的 PR 生效。",+ "pr_auto_complete_example": "关闭语句写在 PR 标题或正文里,例如",+ "pr_auto_complete_example_title": "Closes MUL-123","pr_auto_complete_badge": "PR 全部合并时自动进入"},"quick_actions": {@@ -791,7 +791,7 @@"repositories_shortcut_label": "仓库 URL 仍在\"代码仓库\"标签页中管理","repositories_shortcut_link": "前往管理 →","toast_failed": "更新 GitHub 设置失败",- "feature_auto_link_description": "PR 标题或分支名含任务编号(如 {{example}})时,自动关联到对应任务。",+ "feature_auto_link_description": "PR 标题或分支名含任务编号(如 {{example}}),或正文里写了 \"Closes {{example}}\" 时,自动关联到对应任务。","feature_pr_auto_complete_label": "PR 合并后自动完成任务","feature_pr_auto_complete_on": "已开启 · 所有代码托管平台共用","feature_pr_auto_complete_off": "未开启 · 所有代码托管平台共用",diff --git a/packages/views/settings/components/github-tab.test.tsx b/packages/views/settings/components/github-tab.test.tsxindex 43b6d540c0..cea703082d 100644--- a/packages/views/settings/components/github-tab.test.tsx+++ b/packages/views/settings/components/github-tab.test.tsx@@ -144,7 +144,7 @@ function resetFixtures() {describe("GitHubTab", () => {beforeEach(resetFixtures);- it.each([false, true])("states the title/branch linking rule beside auto-link when connected=%s", (connected) => {+ it.each([false, true])("states the linking rule beside auto-link when connected=%s", (connected) => {installationsRef.current.installations = connected? [{ id: "inst-1", account_login: "acme" }]: [];@@ -152,9 +152,7 @@ describe("GitHubTab", () => {const toggle = screen.getByRole("switch", { name: /Auto-link issues and PRs/i });const row = within(toggle.parentElement!);- expect(row.getByText(/e\.g\. MUL-123, is in its title or branch name/)).toBeTruthy();- // Keywords no longer carry meaning (MUL-7429), so the old rule is gone.- expect(screen.queryByText(/Closes MUL-123/)).toBeNull();+ 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; thediff --git a/server/internal/handler/github.go b/server/internal/handler/github.goindex fb9db9e107..27076ab5ec 100644--- a/server/internal/handler/github.go+++ b/server/internal/handler/github.go@@ -15,6 +15,7 @@ import ("net/url""os""regexp"+ "slices""sort""strconv""strings"@@ -1058,6 +1059,17 @@ func (h *Handler) broadcastPRSnapshotApplied(ctx context.Context, prID pgtype.UU// version numbers like "v1.2-3".var identifierRe = regexp.MustCompile(`(?i)\b([a-z][a-z0-9]{0,9})-(\d+)\b`)+// closingIdentifierRe extracts identifiers that appear immediately after a+// GitHub-style closing keyword ("close[sd]?", "fix(e[sd])?", "resolve[sd]?"),+// optionally separated by a colon and whitespace. Matching is intentionally+// strict on adjacency — "Fix MUL-1" closes MUL-1, but "Fix login MUL-1" does+// not. 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.+var closingIdentifierRe = regexp.MustCompile(+ `(?i)\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)[:\s]+([a-z][a-z0-9]{0,9})-(\d+)\b`,+)+// HandleGitHubWebhook (POST /api/webhooks/github) is GitHub's destination for// every event from a connected installation. We verify HMAC signature, route// on X-GitHub-Event, and either upsert PR rows + auto-link to issues or@@ -1312,11 +1324,12 @@ func (h *Handler) handlePullRequestEvent(ctx context.Context, body []byte) {// link, and is the single authority for that decision: the per-workspace mirror// pass consults it instead of re-deriving the answer from its own reads.//-// A link is a claim that the PR delivers the issue, and a fully merged link set-// completes the issue. So when one installation is bound to several workspaces,-// an identifier that resolves in more than one of them must not link anywhere —-// otherwise merging the PR would complete an issue in a workspace that has-// nothing to do with it (#6804). A member can still link the PR by hand.+// A link is a claim that the PR delivers the issue, and a merged link set with+// a closing keyword completes the issue. So when one installation is bound to+// several workspaces, an identifier that resolves in more than one of them must+// not link anywhere — otherwise merging the PR could complete an issue in a+// workspace that has nothing to do with it (#6804). A member can still link the+// PR by hand.type prLinkPolicy struct {// unrestricted marks the single-binding case: cross-workspace ambiguity is// impossible with one bound workspace, so the scan does no reads at all.@@ -1325,10 +1338,15 @@ type prLinkPolicy struct {// unique. The mirror pass then leaves links and statuses untouched for this// delivery rather than guessing either way.indeterminate bool- // owner maps an identifier to the one workspace proven to resolve it.+ // owner maps an identifier to the one auto-linking workspace proven to+ // resolve it.owner map[string]string- // ambiguous lists identifiers that resolved in more than one workspace.+ // 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.@@ -1340,17 +1358,35 @@ func (c prLinkPolicy) permits(identifier, workspaceID string) bool {return ok && owner == workspaceID}-// resolvePRLinkPolicy determines, before any workspace writes, which title and-// branch identifiers on this PR may link and in which workspace. An identifier-// is allowed only when exactly one bound workspace was proven to resolve it;+// 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.func (h *Handler) resolvePRLinkPolicy(ctx context.Context, insts []db.GithubInstallation, p *ghPullRequestPayload) prLinkPolicy {if len(insts) < 2 {return prLinkPolicy{unrestricted: true}}- idents := extractIdentifiers(p.PullRequest.Title, p.PullRequest.Head.Ref)- policy := prLinkPolicy{owner: map[string]string{}, ambiguous: map[string]bool{}}+ 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{}}if len(idents) == 0 {return policy}@@ -1361,21 +1397,25 @@ func (h *Handler) resolvePRLinkPolicy(ctx context.Context, insts []db.GithubInstreturn prLinkPolicy{indeterminate: true}}- resolvers := make(map[string][]string, len(idents))+ type resolver struct {+ workspaceID string+ autoLink bool+ }+ resolvers := make(map[string][]resolver, len(idents))for _, inst := range insts {ws, err := h.Queries.GetWorkspace(ctx, inst.WorkspaceID)if err != nil {return indeterminate("github: cannot load bound workspace, leaving links unchanged for this delivery", "err", err)}- // A workspace with auto-link off never writes a link row, so it is not- // a competing claimant. A settings blob we cannot parse is not evidence- // either way, so it fails closed.+ // A settings blob we cannot parse is not evidence either way, so it+ // fails closed.autoLink, err := autoLinkPRsEnabledForWorkspace(ws)if err != nil {return indeterminate("github: cannot read workspace auto-link setting, leaving links unchanged for this delivery","err", err, "workspace_id", uuidToString(inst.WorkspaceID))}- if !autoLink {+ // With GitHub off a workspace acts on nothing, so it claims nothing.+ if !githubFeaturesEnabled(ws) {continue}prefix := issuePrefixForWorkspace(ws)@@ -1394,10 +1434,24 @@ func (h *Handler) resolvePRLinkPolicy(ctx context.Context, insts []db.GithubInstreturn indeterminate("github: cannot resolve identifier in bound workspace, leaving links unchanged for this delivery","err", err, "identifier", id, "workspace_id", uuidToString(inst.WorkspaceID))}- resolvers[id] = append(resolvers[id], uuidToString(inst.WorkspaceID))+ resolvers[id] = append(resolvers[id], resolver{workspaceID: uuidToString(inst.WorkspaceID), autoLink: autoLink})}}- for id, wss := range resolvers {+ 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+ for _, r := range all {+ if r.autoLink {+ wss = append(wss, r.workspaceID)+ }+ }+ if len(wss) == 0 {+ continue+ }if len(wss) == 1 {policy.owner[id] = wss[0]continue@@ -1506,15 +1560,11 @@ func (h *Handler) triggerPRRefreshFromCIEvent(ctx context.Context, body []byte)// mirrorPullRequestForWorkspace mirrors a pull_request webhook into a single// workspace: it upserts the PR row, replays any check_suite events that// arrived before the PR was mirrored, auto-links referenced issues (gated by-// the workspace's github toggles), advances issues on terminal events, and-// broadcasts the change. Invoked once per workspace bound to the delivering-// installation.+// the workspace's github toggles), completes issues on a merge, and broadcasts+// the change. Invoked once per workspace bound to the delivering installation.//-// closePolicy is the delivery-wide verdict on which closing identifiers this-// workspace may act on; identifiers it does not permit still link, but never-// carry close_intent, so they can never advance an issue to done. This function-// only ever narrows that verdict — it cannot grant close intent the policy-// withheld.+// linkPolicy is the delivery-wide verdict on which identifiers this workspace+// may link; this function only ever narrows it.func (h *Handler) mirrorPullRequestForWorkspace(ctx context.Context, wsID pgtype.UUID, installationID int64, p *ghPullRequestPayload, linkPolicy prLinkPolicy) {state := derivePRState(p.PullRequest.State, p.PullRequest.Draft, p.PullRequest.Merged)mergeable, clearMergeable := derivePRMergeableState(p.Action, p.PullRequest.MergeableState, baseRefChanged(p.Changes))@@ -1574,9 +1624,10 @@ func (h *Handler) mirrorPullRequestForWorkspace(ctx context.Context, wsID pgtypews, 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)if autoLink, _ := autoLinkPRsEnabledForWorkspace(ws); autoLink {linkedIssueIDs, touched = h.reconcileAutoLinks(ctx, ws, pr.ID, state, prAutoLinkInput{- idents: extractIdentifiers(p.PullRequest.Title, p.PullRequest.Head.Ref),+ idents: idents,permits: func(id string) bool { return linkPolicy.permits(id, workspaceID) },ambiguous: func(id string) bool { return linkPolicy.ambiguous[id] },link: func(issueID pgtype.UUID) (int64, error) {@@ -1590,6 +1641,18 @@ 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" {@@ -1619,7 +1682,7 @@ func (h *Handler) mirrorPullRequestForWorkspace(ctx context.Context, wsID pgtype// prAutoLinkInput is what reconcileAutoLinks needs from one provider.type prAutoLinkInput struct {- idents []string // identifiers in the PR title and branch+ idents []string // identifiers the PR claims (see prClaimedIdentifiers)permits func(identifier string) bool // cross-workspace verdict (always true for VCS)ambiguous func(identifier string) bool // resolved in several workspaceslink func(pgtype.UUID) (int64, error) // automatic link; 1 when new@@ -1627,8 +1690,8 @@ type prAutoLinkInput struct {listAuto func() ([]pgtype.UUID, error) // issues currently auto-linked to the PR}-// reconcileAutoLinks makes the PR's automatic links match its title and branch.-// It returns the issue ids the PR is linked to after the pass, and the issues+// reconcileAutoLinks makes the PR's automatic links match its claims. It+// returns the issue ids the PR is linked to after the pass, and the issues// whose link set changed (a PR event for auto-complete).//// - A claimed identifier that resolves here links, unless a person removed@@ -1639,7 +1702,8 @@ 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.+// Manual links are never touched here, and close intent is not either (see+// closingIssueIDs).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)@@ -1704,6 +1768,27 @@ func (h *Handler) reconcileAutoLinks(ctx context.Context, ws db.Workspace, prIDreturn 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):@@ -1786,10 +1871,21 @@ func parseGHTimeRequired(s string) pgtype.Timestamptz {// extractIdentifiers pulls every "PREFIX-NUMBER" match across the supplied// fields, deduplicating in input order.func extractIdentifiers(parts ...string) []string {+ return extractMatchedIdentifiers(identifierRe, parts...)+}++// 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.+func extractClosingIdentifiers(parts ...string) []string {+ return extractMatchedIdentifiers(closingIdentifierRe, parts...)+}++func extractMatchedIdentifiers(re *regexp.Regexp, parts ...string) []string {seen := map[string]struct{}{}out := []string{}for _, src := range parts {- for _, m := range identifierRe.FindAllStringSubmatch(src, -1) {+ for _, m := range re.FindAllStringSubmatch(src, -1) {ident := strings.ToUpper(m[1]) + "-" + m[2]if _, dup := seen[ident]; dup {continue@@ -1801,6 +1897,21 @@ func extractIdentifiers(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 {+ if !slices.Contains(idents, id) {+ idents = append(idents, id)+ }+ }+ return idents, closing+}+// autoLinkPRsEnabledForWorkspace reports whether the workspace allows the// GitHub webhook to create issue ↔ PR link rows. Defaults to true so that// workspaces predating RFC MUL-2414 keep the historical "auto-link on"diff --git a/server/internal/handler/github_test.go b/server/internal/handler/github_test.goindex ccc4e2aa78..cec466fb00 100644--- a/server/internal/handler/github_test.go+++ b/server/internal/handler/github_test.go@@ -82,6 +82,93 @@ func TestExtractIdentifiers(t *testing.T) {}}+func TestExtractClosingIdentifiers(t *testing.T) {+ cases := []struct {+ name string+ in []string+ want []string+ }{+ {+ name: "single_closes",+ in: []string{"", "Closes MUL-1"},+ want: []string{"MUL-1"},+ },+ {+ name: "single_character_prefix",+ in: []string{"", "Closes H-412"},+ want: []string{"H-412"},+ },+ {+ name: "all_keyword_inflections",+ in: []string{+ "",+ "close MUL-1\nclosed MUL-2\ncloses MUL-3\nfix MUL-4\nfixes MUL-5\nfixed MUL-6\nresolve MUL-7\nresolves MUL-8\nresolved MUL-9",+ },+ want: []string{"MUL-1", "MUL-2", "MUL-3", "MUL-4", "MUL-5", "MUL-6", "MUL-7", "MUL-8", "MUL-9"},+ },+ {+ name: "case_insensitive_and_colon",+ in: []string{"CLOSES: MUL-1", "Fixes:MUL-2 resolves MUL-3"},+ want: []string{"MUL-1", "MUL-2", "MUL-3"},+ },+ {+ name: "bare_reference_does_not_close",+ // The bug-report repro: only ABC-1 carries closing intent.+ // ABC-2/ABC-3 are linked (extractIdentifiers) but must not+ // appear in the closing set.+ in: []string{"ABC-1: Lorem Ipsum", "Closes ABC-1. Follow up work planned in ABC-2. Unblocks ABC-3."},+ want: []string{"ABC-1"},+ },+ {+ name: "keyword_not_adjacent_does_not_close",+ // "Fix login MUL-1" — keyword present but the identifier is+ // not adjacent. Consistent with GitHub's closing-keyword+ // grammar; matches via extractIdentifiers for linking only.+ in: []string{"Fix login MUL-1", ""},+ want: []string{},+ },+ {+ name: "dedupe_across_fields",+ in: []string{"Closes MUL-1", "fixes mul-1"},+ want: []string{"MUL-1"},+ },+ {+ name: "no_match_on_disclosed_or_foreclose",+ // Word-boundary guards against keyword fragments embedded+ // in larger words ("Disclosed MUL-1", "Foreclose MUL-1").+ in: []string{"Disclosed MUL-1 in foreclose MUL-2", ""},+ want: []string{},+ },+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ got := extractClosingIdentifiers(tc.in...)+ if len(got) == 0 && len(tc.want) == 0 {+ return+ }+ if !reflect.DeepEqual(got, tc.want) {+ t.Errorf("extractClosingIdentifiers() = %v, want %v", got, tc.want)+ }+ })+ }+}++// TestPRClaimedIdentifiers: the title and branch link, a closing keyword in the+// title or body links and closes, and a bare body mention claims nothing.+func TestPRClaimedIdentifiers(t *testing.T) {+ idents, closing := prClaimedIdentifiers(+ "ABC-1: Lorem Ipsum",+ "Closes ABC-4. Follow up work planned in ABC-2.",+ "fix/abc-3-login",+ )+ 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) {cases := []struct {state string@@ -959,8 +1046,8 @@ func unlinkPRForTest(t *testing.T, issueID, prID string) {}// linkMergedGitHubPRForTest mirrors a merged PR in the test workspace and-// links it to issueID automatically, for tests that drive the completion path-// without a webhook.+// links it to issueID automatically with a closing keyword, for tests that+// drive the completion path without a webhook.func linkMergedGitHubPRForTest(t *testing.T, issueID, repo string) {t.Helper()ctx := context.Background()@@ -981,6 +1068,9 @@ 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 {@@ -994,11 +1084,10 @@ func githubPRIDForTest(t *testing.T, repo string, number int32) string {return uuidToString(pr.ID)}-// TestWebhook_BodyMentionsDoNotLink is the repro from #3264 under the new-// rule: only the title/branch identifier is a delivery claim. Body text —-// "Closes", "Follow up in", "Unblocks" alike — links nothing and completes-// nothing.-func TestWebhook_BodyMentionsDoNotLink(t *testing.T) {+// 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) {if testHandler == nil {t.Skip("handler test fixture not initialized (no DB?)")}@@ -1013,25 +1102,32 @@ func TestWebhook_BodyMentionsDoNotLink(t *testing.T) {body := fmt.Sprintf("Closes %s. Follow up work planned in %s.", closes.Identifier, followUp.Identifier)fireBareWebhook(t, secret, installationID, 1, title, body, "fix/login")- if n := linkedPRCountForTest(t, primary.ID); n != 1 {- t.Errorf("title identifier should link, got %d rows", n)+ for _, issue := range []IssueResponse{primary, closes} {+ 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 != "done" {- t.Errorf("title-linked issue: status = %q, want done", got)+ if got := issueStatusForTest(t, primary.ID); got != "in_progress" {+ t.Errorf("title-only issue: status = %q, want in_progress", got)}- for _, issue := range []IssueResponse{closes, followUp} {- if n := linkedPRCountForTest(t, issue.ID); n != 0 {- t.Errorf("%s is only in the body and must not link, got %d rows", issue.Identifier, n)- }- if got := issueStatusForTest(t, issue.ID); got != "in_progress" {- t.Errorf("%s: status = %q, want in_progress", issue.Identifier, got)- }+ 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 n := linkedPRCountForTest(t, followUp.ID); n != 0 {+ t.Errorf("a passing body mention must not link, got %d rows", n)+ }+ if got := issueStatusForTest(t, followUp.ID); got != "in_progress" {+ t.Errorf("mentioned issue: status = %q, want in_progress", got)}}-// TestWebhook_TitleAndBranchLinksComplete: a title prefix or a branch name is-// enough — no keyword needed — which is the MUL-7429 fix itself.-func TestWebhook_TitleAndBranchLinksComplete(t *testing.T) {+// 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) {if testHandler == nil {t.Skip("handler test fixture not initialized (no DB?)")}@@ -1040,18 +1136,25 @@ func TestWebhook_TitleAndBranchLinksComplete(t *testing.T) {const installationID int64 = 30264002byTitle := prAutoCompleteTestIssue(t, "title link", installationID)byBranch := prAutoCompleteTestIssue(t, "branch link", 0)+ byTitleKeyword := prAutoCompleteTestIssue(t, "title keyword", 0)fireBareWebhook(t, secret, installationID, 2, byTitle.Identifier+": Fix login flow", "", "feat/login")- fireBareWebhook(t, secret, installationID, 3, "Fix login flow", "", strings.ToLower(byBranch.Identifier)+"/fix-login")+ fireBareWebhook(t, secret, installationID, 3, "Fix login flow", "", "fix/"+strings.ToLower(byBranch.Identifier)+"-login")+ fireBareWebhook(t, secret, installationID, 4, "Fixes "+byTitleKeyword.Identifier+": login flow", "", "feat/login")- for _, issue := range []IssueResponse{byTitle, byBranch} {+ for _, issue := range []IssueResponse{byTitle, byBranch, byTitleKeyword} {if n := linkedPRCountForTest(t, issue.ID); n != 1 {t.Errorf("%s: expected 1 linked PR, got %d", issue.Identifier, n)}- if got := issueStatusForTest(t, issue.ID); got != "done" {- t.Errorf("%s: status = %q, want done", issue.Identifier, got)+ }+ 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, 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)@@ -1145,10 +1248,121 @@ func TestWebhook_IdentifierRemovedBeforeMergeUnlinks(t *testing.T) {}}-// TestWebhook_PostMergeTitleEditLinksAndCompletes: adding the identifier to a-// merged PR's title links it, and linking is a PR event — so the issue-// completes. Removing it again after merge keeps the link: the work landed.-func TestWebhook_PostMergeTitleEditLinksAndCompletes(t *testing.T) {+// 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) {+ if testHandler == nil {+ t.Skip("handler test fixture not initialized (no DB?)")+ }+ const secret = "auto-link-off-close-intent-secret"+ const installationID int64 = 30264012+ t.Setenv("GITHUB_WEBHOOK_SECRET", secret)+ issue := prAutoCompleteTestIssue(t, "auto-link off after linking", installationID)+ 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)+ })++ title := issue.Identifier + ": session refactor"+ firePRWebhook(t, secret, installationID, 1, title, "Closes "+issue.Identifier, "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)+ }+}++// 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) {if testHandler == nil {t.Skip("handler test fixture not initialized (no DB?)")}@@ -1161,12 +1375,15 @@ func TestWebhook_PostMergeTitleEditLinksAndCompletes(t *testing.T) {if n := linkedPRCountForTest(t, created.ID); n != 0 {t.Fatalf("PR without the identifier must not link, got %d rows", n)}- firePRWebhook(t, secret, installationID, 1, created.Identifier+": dependency bump", "", "chore/bump", "edited_merged")+ firePRWebhook(t, secret, installationID, 1, "Dependency bump", "Closes "+created.Identifier, "chore/bump", "edited_merged")if n := linkedPRCountForTest(t, created.ID); n != 1 {- t.Fatalf("post-merge title edit should link, got %d rows", n)+ t.Fatalf("post-merge edit should link, got %d rows", n)}- if got := issueStatusForTest(t, created.ID); got != "done" {- t.Errorf("status = %q, want done", got)+ 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)}firePRWebhook(t, secret, installationID, 1, "Dependency bump", "", "chore/bump", "edited_merged")if n := linkedPRCountForTest(t, created.ID); n != 1 {@@ -1189,8 +1406,8 @@ func TestWebhook_ReopenedIssueStaysOpenUntilNewPRMerges(t *testing.T) {const installationID int64 = 30264006created := prAutoCompleteTestIssue(t, "reopen flow", installationID)- firePRWebhook(t, secret, installationID, 1, created.Identifier+": first fix", "", "fix/one", "opened")- firePRWebhook(t, secret, installationID, 1, created.Identifier+": first fix", "", "fix/one", "merged")+ firePRWebhook(t, secret, installationID, 1, "First fix", "Closes "+created.Identifier, "fix/one", "opened")+ firePRWebhook(t, secret, installationID, 1, "First fix", "Closes "+created.Identifier, "fix/one", "merged")if got := issueStatusForTest(t, created.ID); got != "done" {t.Fatalf("status after first merge = %q, want done", got)}@@ -1201,7 +1418,7 @@ func TestWebhook_ReopenedIssueStaysOpenUntilNewPRMerges(t *testing.T) {t.Fatalf("reopen: %v", err)}// A later event on the already-merged PR (label, edit, redelivery).- firePRWebhook(t, secret, installationID, 1, created.Identifier+": first fix (edited)", "", "fix/one", "edited_merged")+ firePRWebhook(t, secret, installationID, 1, "First fix (edited)", "Closes "+created.Identifier, "fix/one", "edited_merged")if got := issueStatusForTest(t, created.ID); got != "in_progress" {t.Fatalf("reopened issue bounced back to %q on an event of a merged PR", got)}@@ -1209,11 +1426,11 @@ func TestWebhook_ReopenedIssueStaysOpenUntilNewPRMerges(t *testing.T) {t.Fatalf("auto_complete = %+v, want all_merged with the issue still enabled", got)}- firePRWebhook(t, secret, installationID, 2, created.Identifier+": follow-up fix", "", "fix/two", "opened")+ firePRWebhook(t, secret, installationID, 2, "Follow-up fix", "Fixes "+created.Identifier, "fix/two", "opened")if got := prAutoCompleteStateForTest(t, created.ID); got.State != prAutoCompleteWaiting {t.Fatalf("auto_complete = %+v, want waiting on the new PR", got)}- firePRWebhook(t, secret, installationID, 2, created.Identifier+": follow-up fix", "", "fix/two", "merged")+ firePRWebhook(t, secret, installationID, 2, "Follow-up fix", "Fixes "+created.Identifier, "fix/two", "merged")if got := issueStatusForTest(t, created.ID); got != "done" {t.Errorf("status after the follow-up merged = %q, want done", got)}@@ -1232,8 +1449,8 @@ func TestUnlinkIssuePullRequest_IsRememberedAndCompletes(t *testing.T) {created := prAutoCompleteTestIssue(t, "unlink flow", installationID)firePRWebhook(t, secret, installationID, 1, created.Identifier+": abandoned approach", "", "try/one", "opened")- firePRWebhook(t, secret, installationID, 2, created.Identifier+": real fix", "", "fix/two", "opened")- firePRWebhook(t, secret, installationID, 2, created.Identifier+": real fix", "", "fix/two", "merged")+ firePRWebhook(t, secret, installationID, 2, created.Identifier+": real fix", "Closes "+created.Identifier, "fix/two", "opened")+ firePRWebhook(t, secret, installationID, 2, created.Identifier+": real fix", "Closes "+created.Identifier, "fix/two", "merged")if got := issueStatusForTest(t, created.ID); got != "in_progress" {t.Fatalf("status = %q, want in_progress while #1 is open", got)}@@ -1250,8 +1467,9 @@ func TestUnlinkIssuePullRequest_IsRememberedAndCompletes(t *testing.T) {}// TestLinkIssuePullRequest_ByURL: a pasted PR URL (with trailing path/query)-// links a mirrored PR by hand; manual links survive title edits, and linking a-// merged PR is a PR event that can complete the issue. An unknown URL is 404.+// links a mirrored PR by hand, and manual links survive title edits. A manual+// link carries no close intent of its own, so linking a merged PR that never+// said "Closes" does not complete the issue. An unknown URL is 404.func TestLinkIssuePullRequest_ByURL(t *testing.T) {if testHandler == nil {t.Skip("handler test fixture not initialized (no DB?)")@@ -1277,8 +1495,11 @@ 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 != "done" {- t.Errorf("linking a merged PR: status = %q, want done", got)+ 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)+ }+ if list.AutoComplete.State != prAutoCompleteNoCloseIntent {+ t.Errorf("auto_complete = %+v, want no_close_intent", list.AutoComplete)}firePRWebhook(t, secret, installationID, 41, "Refactor session helper (renamed)", "", "refactor/session", "edited_merged")if n := linkedPRCountForTest(t, created.ID); n != 1 {@@ -1308,7 +1529,7 @@ func TestPRAutoComplete_WorkspaceAndIssueSwitches(t *testing.T) {})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, wsOff.Identifier+": work", "", "feat/one", "merged")+ firePRWebhook(t, secret, installationID, 1, "Work", "Closes "+wsOff.Identifier, "feat/one", "merged")if n := linkedPRCountForTest(t, wsOff.ID); n != 1 {t.Fatalf("setting off must still link, got %d rows", n)}@@ -1325,7 +1546,7 @@ func TestPRAutoComplete_WorkspaceAndIssueSwitches(t *testing.T) {put := withURLParam(newRequest("PUT", "/api/issues/"+issueOff.ID+"/pr-auto-complete", map[string]any{"disabled": true}), "id", issueOff.ID)testutil.Call(t, testHandler.SetIssuePRAutoComplete, put).Want(http.StatusOK)- firePRWebhook(t, secret, installationID, 2, issueOff.Identifier+": work", "", "feat/two", "merged")+ firePRWebhook(t, secret, installationID, 2, "Work", "Closes "+issueOff.Identifier, "feat/two", "merged")if got := issueStatusForTest(t, issueOff.ID); got != "in_progress" {t.Fatalf("issue switch off: status = %q, want in_progress", got)}@@ -2814,6 +3035,75 @@ 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+// (PR #8794 re-review).+func TestWebhook_AutoLinkOffKeepsValidClosingKeyword(t *testing.T) {+ if testHandler == nil {+ t.Skip("handler test fixture not initialized (no DB?)")+ }+ for _, shared := range []bool{false, true} {+ name := "single workspace"+ if shared {+ name = "shared installation, unique prefix"+ }+ t.Run(name, func(t *testing.T) {+ const secret = "auto-link-off-keeps-keyword-secret"+ const installationID int64 = 30264013+ t.Setenv("GITHUB_WEBHOOK_SECRET", secret)+ setWorkspaceIssuePrefixForTest(t, "RVA")+ if shared {+ bindSecondWorkspaceForTest(t, "auto-link-off-other-workspace", "RVB", installationID)+ }+ issue := prAutoCompleteTestIssue(t, name, installationID)+ 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)+ })++ firePRWebhook(t, secret, installationID, 1, "Session refactor", "Closes "+issue.Identifier, "refactor/session", "opened")+ if got := prAutoCompleteStateForTest(t, issue.ID); got.State != prAutoCompleteWaiting {+ t.Fatalf("before turning auto-link off: auto_complete = %+v, want waiting", got)+ }+ 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, "Session refactor", "Closes "+issue.Identifier, "refactor/session", "merged")+ if got := issueStatusForTest(t, issue.ID); got != "done" {+ t.Errorf("keyword kept, auto-link off: status = %q, want done (auto_complete = %+v)", got, prAutoCompleteStateForTest(t, issue.ID))+ }+ })+ }+}+// TestWebhook_PullRequest_UniqueResolverAmongBindingsStillAutoCompletes is the// other half of the #6804 fix: withholding links must be scoped to the// identifiers we could not attribute. Two workspaces share an installation anddiff --git a/server/internal/handler/pr_auto_complete.go b/server/internal/handler/pr_auto_complete.goindex 3d2ab06a98..890ebee75f 100644--- a/server/internal/handler/pr_auto_complete.go+++ b/server/internal/handler/pr_auto_complete.go@@ -27,11 +27,13 @@ import (// The whole rule, as users see it://// - A PR whose title or branch name carries an issue identifier is linked to-// that issue. A member can also link or remove a PR by hand. Keywords such-// as "Closes" have no special meaning and the PR body is not scanned.-// - When every PR linked to an issue is merged, the issue moves to Done —-// unless the workspace turned the setting off or someone turned it off for-// that one issue.+// 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.//// 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@@ -46,6 +48,7 @@ const (prAutoCompleteIssueDisabled = "issue_disabled" // turned off for this issueprAutoCompleteTerminal = "terminal" // already done / cancelledprAutoCompleteTriage = "triage" // not accepted yet+ prAutoCompleteNoCloseIntent = "no_close_intent" // no PR closes the issue with a keywordprAutoCompleteWaiting = "waiting" // some PRs still open / draftprAutoCompleteNotMerged = "not_merged" // some PRs closed without mergingprAutoCompleteAllMerged = "all_merged" // every linked PR merged@@ -116,15 +119,21 @@ func (h *Handler) decidePRAutoComplete(ctx context.Context, ws db.Workspace, issreturn d, nil}var open, closed []db.ListIssueLinkedPullRequestStatesRow+ closes := falsefor _, 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 = prAutoCompleteNoCloseIntentcase len(open) > 0:d.State, d.PRs = prAutoCompleteWaiting, opencase len(closed) > 0:@@ -136,10 +145,10 @@ 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. 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.+// moves it to Done when every linked PR is merged and one of them closes it.+// Safe to call for any issue: every guard lives in decidePRAutoComplete, and+// the status write is conditional on the status the decision saw, so+// concurrent merges complete the issue once.func (h *Handler) maybeAutoCompleteIssue(ctx context.Context, workspaceID, issueID pgtype.UUID, resolver *issuestatus.Resolver) {issue, err := h.Queries.GetIssueInWorkspace(ctx, db.GetIssueInWorkspaceParams{ID: issueID, WorkspaceID: workspaceID})if err != nil {@@ -245,8 +254,8 @@ func prAutoCompleteToResponse(ws db.Workspace, d prAutoCompleteDecision) prAutoC}// prLinkSource explains how a PR came to be linked: "manual", or the text the-// webhook matched ("title" / "branch"). "auto" covers links made under older-// rules (a body closing keyword) whose text no longer carries the identifier.+// webhook matched ("title" / "branch"). "auto" covers the rest: a closing+// keyword in the body (which is not stored) or a link whose text changed since.func prLinkSource(linkedByType, identifier, title, branch string) string {if linkedByType == "member" {return "manual"@@ -350,7 +359,8 @@ func (h *Handler) findPullRequestByID(ctx context.Context, workspaceID, id pgtyp// LinkIssuePullRequest (POST /api/issues/{id}/pull-requests) links a PR the// workspace already mirrors. Linking is a PR event for the issue, so it can-// complete the issue when every linked PR is merged.+// complete the issue when every linked PR is merged and one of them closes it.+// A manual link carries no close intent of its own; the PR text decides that.func (h *Handler) LinkIssuePullRequest(w http.ResponseWriter, r *http.Request) {userID, ok := requireUserID(w, r)if !ok {diff --git a/server/internal/handler/pr_auto_complete_race_test.go b/server/internal/handler/pr_auto_complete_race_test.goindex 94ea92db30..efc51242f5 100644--- a/server/internal/handler/pr_auto_complete_race_test.go+++ b/server/internal/handler/pr_auto_complete_race_test.go@@ -33,7 +33,7 @@ func TestPRAutoComplete_PRLinkedDuringCompletionKeepsIssueOpen(t *testing.T) {t.Setenv("GITHUB_WEBHOOK_SECRET", secret)const inst int64 = 8758002issue := prAutoCompleteTestIssue(t, "PR linked during completion", inst)- firePRWebhook(t, secret, inst, 1, issue.Identifier, "", "fix/a", "opened")+ firePRWebhook(t, secret, inst, 1, "Closes "+issue.Identifier, "", "fix/a", "opened")original := testHandler.TxStartert.Cleanup(func() { testHandler.TxStarter = original })// Schedule the second webhook after the first decision but before its write.@@ -42,7 +42,7 @@ func TestPRAutoComplete_PRLinkedDuringCompletionKeepsIssueOpen(t *testing.T) {firePRWebhook(t, secret, inst, 2, issue.Identifier, "", "fix/b", "opened")return nil}}- firePRWebhook(t, secret, inst, 1, issue.Identifier, "", "fix/a", "merged")+ firePRWebhook(t, secret, inst, 1, "Closes "+issue.Identifier, "", "fix/a", "merged")if n := linkedPRCountForTest(t, issue.ID); n != 2 {t.Fatalf("want 2 linked PRs, got %d", n)}@@ -51,14 +51,15 @@ func TestPRAutoComplete_PRLinkedDuringCompletionKeepsIssueOpen(t *testing.T) {}}-// fireTimedPRWebhook delivers a pull_request event with an explicit updated_at.+// fireTimedPRWebhook delivers a pull_request event that closes identifier,+// with an explicit updated_at.func fireTimedPRWebhook(t *testing.T, inst int64, identifier, state, timestamp string) {t.Helper()raw, err := json.Marshal(map[string]any{"action": "edited","installation": map[string]any{"id": inst},"repository": map[string]any{"name": "widget", "owner": map[string]any{"login": "acme"}},- "pull_request": map[string]any{"number": 1, "html_url": "https://github.com/acme/widget/pull/1", "title": identifier, "state": state, "merged": state == "closed", "created_at": "2026-09-22T00:00:00Z", "updated_at": timestamp, "head": map[string]any{"ref": "fix/a"}},+ "pull_request": map[string]any{"number": 1, "html_url": "https://github.com/acme/widget/pull/1", "title": "Closes " + identifier, "state": state, "merged": state == "closed", "created_at": "2026-09-22T00:00:00Z", "updated_at": timestamp, "head": map[string]any{"ref": "fix/a"}},})if err != nil {t.Fatal(err)diff --git a/server/internal/handler/vcs_webhook.go b/server/internal/handler/vcs_webhook.goindex a3a11dba3d..f12c325d65 100644--- a/server/internal/handler/vcs_webhook.go+++ b/server/internal/handler/vcs_webhook.go@@ -217,18 +217,20 @@ func (h *Handler) mirrorVCSPullRequest(ctx context.Context, conn db.VcsConnectioworkspaceID := uuidToString(conn.WorkspaceID)resp := vcsPullRequestToResponse(pr)- // Auto-link to issues by identifiers in the title and branch. Connecting a- // provider is the opt-in, so there is no separate per-workspace flag. The- // issue-side machinery is shared with GitHub (reconcileAutoLinks,- // maybeAutoCompleteIssue). A connection belongs to exactly one workspace, so- // there is no cross-workspace ambiguity to settle.+ // Auto-link to issues by identifiers in the title, branch, and closing+ // keywords. Connecting a provider is the opt-in, so there is no separate+ // per-workspace flag. The issue-side machinery is shared with GitHub+ // (reconcileAutoLinks, maybeAutoCompleteIssue). A connection belongs to+ // exactly one workspace, so there is no cross-workspace ambiguity to settle.linkedIssueIDs := make([]string, 0)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 }linkedIssueIDs, touched = h.reconcileAutoLinks(ctx, ws, pr.ID, ev.State, prAutoLinkInput{- idents: extractIdentifiers(ev.Title, ev.Branch),- permits: func(string) bool { return true },+ idents: idents,+ permits: permits,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})@@ -240,6 +242,16 @@ func (h *Handler) mirrorVCSPullRequest(ctx context.Context, conn db.VcsConnectioreturn 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.goindex 00f0323b6e..55d867ed29 100644--- a/server/internal/handler/vcs_webhook_test.go+++ b/server/internal/handler/vcs_webhook_test.go@@ -145,9 +145,10 @@ func TestVCSWebhook_ForgejoMirrorsAndCloses(t *testing.T) {}}-// A body mention (not in title or branch) claims nothing, so it must not link-// at all: it neither shows as a delivery PR nor blocks a title-linked sibling-// from completing the issue. Mirrors the GitHub rule (MUL-7429).+// A bare body mention ("Related MUL-X", no closing keyword, not in title or+// branch) claims nothing, so it must not link at all: it neither shows as a+// working PR nor blocks a genuine Closes sibling from completing the issue.+// Mirrors the GitHub claim rule (MUL-3739, MUL-7072).func TestVCSWebhook_BareBodyMentionIsNotLinked(t *testing.T) {ctx := context.Background()box := withVCSBox(t)@@ -193,8 +194,8 @@ func TestVCSWebhook_BareBodyMentionIsNotLinked(t *testing.T) {t.Fatalf("unlinked PR must not appear in the list, got %d rows", len(rows))}- // PR #8: MERGED with a title reference → linked. The still-open, unlinked- // PR #7 must NOT block completion.+ // PR #8: MERGED with a title reference + Closes keyword → a real claim with+ // close intent. The still-open, unlinked PR #7 must NOT block completion.closeRaw, _ := json.Marshal(map[string]any{"action": "closed","pull_request": map[string]any{@@ -223,8 +224,8 @@ func TestVCSWebhook_BareBodyMentionIsNotLinked(t *testing.T) {}// Auto-complete must span providers: an issue with an OPEN GitHub PR and a-// MERGED VCS merge request waits for the GitHub PR, and completes once it-// merges too.+// MERGED close-intent VCS merge request waits for the GitHub PR, and completes+// once it merges too.func TestAutoCompleteSpansProviders(t *testing.T) {ctx := context.Background()box := withVCSBox(t)@@ -274,6 +275,11 @@ 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" {@@ -346,6 +352,52 @@ 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) {+ ctx := context.Background()+ box := withVCSBox(t)+ connID := seedVCSConnection(t, ctx, box, "forgejo", "https://forgejo.test")+ issue := newVCSIssue(t, "Keyword removed before merge")+ t.Cleanup(func() { cleanupVCS(ctx, issue.ID) })++ fire := func(action, state string, merged bool, body, updatedAt string) {+ raw, _ := json.Marshal(map[string]any{+ "action": action,+ "pull_request": map[string]any{+ "number": 9, "html_url": "https://forgejo.test/acme/widget/pulls/9",+ "title": "Session refactor", "body": body, "state": state, "merged": merged,+ "created_at": "2026-05-01T00:00:00Z", "updated_at": updatedAt,+ "merged_at": "2026-05-02T00:00:00Z",+ "head": map[string]any{"ref": "refactor", "sha": "def"},+ "user": map[string]any{"username": "octo"},+ },+ "repository": map[string]any{"name": "widget", "owner": map[string]any{"username": "acme"}},+ })+ w := httptest.NewRecorder()+ testHandler.HandleVCSWebhook(w, vcsWebhookReq(connID, map[string]string{+ "X-Gitea-Event": "pull_request", "X-Gitea-Signature": giteaSig(raw),+ }, raw))+ if w.Code != http.StatusAccepted {+ t.Fatalf("%s event: %d %s", action, w.Code, w.Body.String())+ }+ }++ fire("opened", "open", false, "Closes "+issue.Identifier, "2026-05-01T00:00:00Z")+ 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")+ }+ 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("the merged PR must stay linked, got %d links", links)+ }+}+// A redelivered older event must not rewrite the link a newer event already// set. The PR-upsert monotonic guard protects the PR row; this covers the link.func TestVCSWebhook_StaleEventDoesNotRewriteLink(t *testing.T) {@@ -377,20 +429,20 @@ func TestVCSWebhook_StaleEventDoesNotRewriteLink(t *testing.T) {}}- // Newer terminal event: merged with the identifier in the title → linked.- fire("closed", "closed", true, "Fix "+issue.Identifier, "", "2026-05-02T00:00:00Z")- // Older redelivered "opened" event without the identifier. Without the- // guard this would drop the link the newer event wrote.+ // Newer terminal event: merged with a real claim (Closes) → close_intent.+ fire("closed", "closed", true, "Fix "+issue.Identifier, "Closes "+issue.Identifier, "2026-05-02T00:00:00Z")+ // Older redelivered "opened" event: bare body mention, generic title/branch.+ // Without the guard this clears close_intent and drops the link entirely.fire("opened", "open", false, "WIP", "touches "+issue.Identifier, "2026-05-01T00:00:00Z")- var links int+ var closeIntent boolif err := testPool.QueryRow(ctx,- `SELECT count(*) FROM issue_vcs_pull_request WHERE issue_id = $1`,- issue.ID).Scan(&links); err != nil {+ `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 links != 1 {- t.Errorf("stale event rewrote the link set: %d links, want 1", links)+ if !closeIntent {+ t.Errorf("stale event rewrote link: close_intent=%v, want true", closeIntent)}// The PR row also stayed at the newer merged state.rows, _ := testHandler.Queries.ListVCSPullRequestsByIssue(ctx, parseUUID(issue.ID))diff --git a/server/internal/handler/webhook_status_resolver_test.go b/server/internal/handler/webhook_status_resolver_test.goindex d51f702b4b..81855d871c 100644--- a/server/internal/handler/webhook_status_resolver_test.go+++ b/server/internal/handler/webhook_status_resolver_test.go@@ -79,7 +79,7 @@ func TestWebhookStatusResolver(t *testing.T) {var ids, closing []stringfor i, status := range tc.statuses {ids = append(ids, fixture.Issue(t, "Resolver fixture", testutil.Cols{"status": status, "number": i + 1}))- closing = append(closing, fmt.Sprintf("RSL-%d", i+1))+ closing = append(closing, fmt.Sprintf("Closes RSL-%d", i+1))}// Mirroring creates rows outside the fixture builders.for _, table := range []string{"issue_pull_request", "issue_vcs_pull_request"} {@@ -88,7 +88,7 @@ func TestWebhookStatusResolver(t *testing.T) {fixture.Cleanup(t, "DELETE FROM github_pull_request WHERE workspace_id = $1", ws)fixture.Cleanup(t, "DELETE FROM vcs_pull_request WHERE workspace_id = $1", ws)const timestamp = "2026-09-08T00:00:00Z"- // mirror delivers a merged PR whose title names every+ // mirror delivers a merged PR whose body closes every// fixture issue. Each PR number is a separate delivery.var mirror func(number int32)if provider == "github" {@@ -96,7 +96,8 @@ func TestWebhookStatusResolver(t *testing.T) {p := &ghPullRequestPayload{}p.Action = "closed"p.Repository.Owner.Login, p.Repository.Name = "fixture", "resolver"- p.PullRequest.Number, p.PullRequest.Title = number, "Resolve "+strings.Join(closing, " ")+ p.PullRequest.Number, p.PullRequest.Title = number, "Resolve linked issues"+ p.PullRequest.Body = strings.Join(closing, "\n")p.PullRequest.State, p.PullRequest.Merged = "closed", truep.PullRequest.HTMLURL = fmt.Sprintf("https://github.test/fixture/resolver/pull/%d", number)p.PullRequest.CreatedAt, p.PullRequest.UpdatedAt = timestamp, timestamp@@ -106,7 +107,7 @@ func TestWebhookStatusResolver(t *testing.T) {connID := fixture.Insert(t, "vcs_connection", testutil.Cols{"workspace_id": ws, "provider": provider, "instance_url": "https://forgejo.test", "account_login": "fixture", "access_token_encrypted": "unused", "webhook_secret_encrypted": "unused"})conn := db.VcsConnection{ID: parseUUID(connID), WorkspaceID: wsID, Provider: provider}mirror = func(number int32) {- ev := vcs.PullRequestEvent{Action: "closed", State: "merged", RepoOwner: "fixture", RepoName: "resolver", Number: number, Title: "Resolve " + strings.Join(closing, " "), HTMLURL: fmt.Sprintf("https://forgejo.test/fixture/resolver/pulls/%d", number), CreatedAt: timestamp, UpdatedAt: timestamp}+ ev := vcs.PullRequestEvent{Action: "closed", State: "merged", RepoOwner: "fixture", RepoName: "resolver", Number: number, Title: "Resolve linked issues", Body: strings.Join(closing, "\n"), HTMLURL: fmt.Sprintf("https://forgejo.test/fixture/resolver/pulls/%d", number), CreatedAt: timestamp, UpdatedAt: timestamp}h.mirrorVCSPullRequest(ctx, conn, ev)}}diff --git a/server/internal/service/builtin_skills/multica-platform/references/issues.md b/server/internal/service/builtin_skills/multica-platform/references/issues.mdindex 732b60a523..a1ac4e7e13 100644--- a/server/internal/service/builtin_skills/multica-platform/references/issues.md+++ b/server/internal/service/builtin_skills/multica-platform/references/issues.md@@ -13,29 +13,38 @@ Product contracts the runtime brief does not fully encode.## PR linking and auto-completeA PR is linked to an issue when its **title** or **branch name** contains a-routable issue key (`PREFIX-NUMBER`, e.g. `MUL-123`). The PR body is not-scanned, and keywords such as `Closes` / `Fixes` / `Resolves` have no special-meaning. People can also link a PR by URL or remove one on the issue page; a-removed PR is not linked again by later webhooks.+routable issue key (`PREFIX-NUMBER`, e.g. `MUL-123`), or when its title or body+puts the key **right after a closing keyword** (`Closes` / `Fixes` /+`Resolves`, optional `:` then whitespace). A key that appears in the body as a+bare mention links nothing. People can also link a PR by URL or remove one on+the issue page; a removed PR is not linked again by later webhooks.```textMUL-123: add the thing the issue asks for # key in title → linksagent/dana/mul-123-add-the-thing # key in branch → links-Closes MUL-123 (body only) # no link+Closes MUL-123 (body) # links AND closes+Related to MUL-123 (body only) # no link```-**Every linked PR is delivery.** When all PRs linked to an issue are merged, the-issue moves to `done` on its own — unless the workspace turned PR auto-complete-off (Settings → Issue statuses) or someone turned it off for that issue. A PR closed without-merging keeps the issue waiting until someone removes it from the issue.+**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 PRis linked, or a link is removed. Reopening an issue or changing the setting never-completes it by itself; the next linked PR's merge does.+completes it by itself.-While a PR is open, its automatic links follow the live title and branch: removing-the key drops the link. After merge or close, existing links stay. Adding the key-to an already-merged PR still links it, and that link can complete the issue.+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.### Default for code-changing issue work@@ -47,14 +56,14 @@ is blocked by auth, failing tests, or missing remote state, report that blockerinstead of pretending the run is complete.To make the PR show on the issue, put a routable issue key in the PR **title**-(preferred) or the **branch**. A key that appears only in the body links nothing.-A linked PR counts toward auto-complete, so when the PR delivers only part of the-issue or the issue needs work after the merge (review, release), say so in the-final comment; a person can turn auto-complete off for that issue.+(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`.```text-MUL-123: fix login redirect # key in title → links, counts toward done-Part of MUL-123 # body only → no link at all+MUL-123: fix login redirect # key in title → links, does not complete+Closes MUL-123 # only when merge should mark the issue done+Part of MUL-123 # body mention only → no link at all```In the final issue comment, include the PR URL when a PR exists. If the task did@@ -73,14 +82,15 @@ multica issue pull-requests <issue-id> --output jsonReturns `{"pull_requests": [...], "auto_complete": {...}}`.`auto_complete.state` says what the merge rule will do for this issue:-`waiting` (some linked PRs are still open or draft), `not_merged` (one was closed-without merging), `all_merged`, `workspace_disabled`, `issue_disabled`,-`terminal`, `triage`, or `none`; `auto_complete.pull_request_ids` names the PRs-the state is about. Each element of `pull_requests` exposes:+`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:- `number`, `html_url`, `title`- `link_source` — why the PR is on the issue: `title`, `branch`, `manual`, or- `auto` (linked under an older rule).+ `auto` (any other automatic link, such as a closing keyword in the body).- `state` — the PR lifecycle as a **single enum**, one of `merged`, `closed`,`draft`, `open`. There is no separate `draft` or `merged` boolean in theresponse; the server folds them into `state` (merged wins, then closed, then@@ -105,8 +115,9 @@ So "is it merged?" is `state == "merged"` (or `merged_at != null`); "is it stilla draft?" is `state == "draft"`; coarse CI status is `checks_conclusion`.If the command returns no linked PRs after a PR was opened, check the syntax-first: the key must be in the PR title or branch — the body does not count. When-the syntax is the problem, editing the title re-runs the scan. If a person removed+first: the key must be in the PR title or branch, or right after a closing+keyword in the body — a bare body mention does not count. When the syntax is the+problem, editing the title re-runs the scan. If a person removedthe PR from the issue, it stays removed until someone links it again.If the key is already written correctly and the list is still empty, stop editing@@ -247,8 +258,9 @@ archived statuses remain readable via an explicit status filter.- **`in_review`** is an accepted issue status. Some workflows use it while a PRis open and awaiting review; moving to it is an explicit mutation.- **`done`** on a child issue posts a system comment on its parent. When every- PR linked to the issue has merged, the server moves it to `done` itself (see- PR linking and auto-complete) — you do not also need to flip it manually.+ 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.- **`cancelled`** is a terminal, user-driven decision to close the issue. Like`done` it enqueues no new agent work, but it does **not** stop tasks already inflight — a run in progress keeps going. To stop a running task, cancel thediff --git a/server/internal/service/builtin_skills_test.go b/server/internal/service/builtin_skills_test.goindex c720794f21..9692759b21 100644--- a/server/internal/service/builtin_skills_test.go+++ b/server/internal/service/builtin_skills_test.go@@ -471,10 +471,10 @@ 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",- // MUL-7429: every linked PR counts toward auto-complete, and the- // exception is a person's per-issue switch, not a keyword.- "Every linked PR is delivery",- "a person can turn auto-complete off for that issue",+ // 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/pkg/db/generated/github.sql.go b/server/pkg/db/generated/github.sql.goindex 5a02c51b3e..ab26c03875 100644--- a/server/pkg/db/generated/github.sql.go+++ b/server/pkg/db/generated/github.sql.go@@ -359,9 +359,10 @@ type LinkIssueToPullRequestParams struct {// =====================// Issue ↔ Pull Request link// =====================-// Automatic link from a PR title or branch. Returns 1 only when the link is-// new, so the webhook evaluates auto-complete on the link event and not on-// every redelivery. An existing link (automatic or manual) is left untouched.+// 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.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 {@@ -684,6 +685,27 @@ func (q *Queries) ListPullRequestsByIssue(ctx context.Context, issueID pgtype.UUreturn 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 :execrowsDELETE FROM issue_pull_requestWHERE issue_id = $1 AND pull_request_id = $2diff --git a/server/pkg/db/generated/pr_automation.sql.go b/server/pkg/db/generated/pr_automation.sql.goindex 2b5853e392..6f58593dfc 100644--- a/server/pkg/db/generated/pr_automation.sql.go+++ b/server/pkg/db/generated/pr_automation.sql.go@@ -43,6 +43,11 @@ WHERE i.id = $1JOIN vcs_pull_request pr ON pr.id = ipr.pull_request_idWHERE 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`@@ -53,10 +58,10 @@ type CompleteIssueFromPullRequestsParams struct {}// Conditional status write for PR auto-complete. It lands only if the issue is-// still in the status the decision saw (two merges racing complete it once) and-// the linked PRs are still all merged when the write runs: a PR linked between-// the decision and this statement keeps the issue open. Repositions like-// UpdateIssueStatus does.+// 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@@ -179,12 +184,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+SELECT pr.id, 'github'::text AS provider, pr.pr_number, pr.state, ipr.close_intentFROM github_pull_request prJOIN issue_pull_request ipr ON ipr.pull_request_id = pr.idWHERE ipr.issue_id = $1UNION ALL-SELECT pr.id, pr.provider AS provider, pr.pr_number, pr.state+SELECT pr.id, pr.provider AS provider, pr.pr_number, pr.state, ipr.close_intentFROM vcs_pull_request prJOIN issue_vcs_pull_request ipr ON ipr.pull_request_id = pr.idWHERE ipr.issue_id = $1@@ -192,10 +197,11 @@ 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"`+ ID pgtype.UUID `json:"id"`+ Provider string `json:"provider"`+ PrNumber int32 `json:"pr_number"`+ State string `json:"state"`+ CloseIntent bool `json:"close_intent"`}// Every PR linked to the issue across GitHub and self-hosted providers, for@@ -214,6 +220,7 @@ func (q *Queries) ListIssueLinkedPullRequestStates(ctx context.Context, issueID&i.Provider,&i.PrNumber,&i.State,+ &i.CloseIntent,); err != nil {return nil, err}diff --git a/server/pkg/db/generated/vcs.sql.go b/server/pkg/db/generated/vcs.sql.goindex ed88522652..e38376fd50 100644--- a/server/pkg/db/generated/vcs.sql.go+++ b/server/pkg/db/generated/vcs.sql.go@@ -532,6 +532,24 @@ func (q *Queries) RotateVCSConnectionWebhookSecret(ctx context.Context, arg Rotareturn 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 :execrowsDELETE FROM issue_vcs_pull_requestWHERE issue_id = $1 AND pull_request_id = $2diff --git a/server/pkg/db/queries/github.sql b/server/pkg/db/queries/github.sqlindex f2981d2201..4ebe2446b5 100644--- a/server/pkg/db/queries/github.sql+++ b/server/pkg/db/queries/github.sql@@ -231,9 +231,10 @@ WHERE pull_request_id = $1;-- =====================-- name: LinkIssueToPullRequest :execrows--- Automatic link from a PR title or branch. Returns 1 only when the link is--- new, so the webhook evaluates auto-complete on the link event and not on--- every redelivery. An existing link (automatic or manual) is left untouched.+-- 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.INSERT INTO issue_pull_request (issue_id, pull_request_id, linked_by_type, linked_by_id) VALUES (@@ -241,6 +242,16 @@ 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 wasdiff --git a/server/pkg/db/queries/pr_automation.sql b/server/pkg/db/queries/pr_automation.sqlindex b71a230101..144460ebda 100644--- a/server/pkg/db/queries/pr_automation.sql+++ b/server/pkg/db/queries/pr_automation.sql@@ -44,12 +44,12 @@ 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+SELECT pr.id, 'github'::text AS provider, pr.pr_number, pr.state, ipr.close_intentFROM github_pull_request prJOIN issue_pull_request ipr ON ipr.pull_request_id = pr.idWHERE ipr.issue_id = $1UNION ALL-SELECT pr.id, pr.provider AS provider, pr.pr_number, pr.state+SELECT pr.id, pr.provider AS provider, pr.pr_number, pr.state, ipr.close_intentFROM vcs_pull_request prJOIN issue_vcs_pull_request ipr ON ipr.pull_request_id = pr.idWHERE ipr.issue_id = $1@@ -57,10 +57,10 @@ ORDER BY pr_number;-- name: CompleteIssueFromPullRequests :one-- Conditional status write for PR auto-complete. It lands only if the issue is--- still in the status the decision saw (two merges racing complete it once) and--- the linked PRs are still all merged when the write runs: a PR linked between--- the decision and this statement keeps the issue open. Repositions like--- UpdateIssueStatus does.+-- 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.UPDATE issue AS i SETstatus = 'done',duplicate_of_issue_id = NULL,@@ -92,4 +92,9 @@ WHERE i.id = $1JOIN vcs_pull_request pr ON pr.id = ipr.pull_request_idWHERE 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.sqlindex 94ef3cf9c0..cc4eafb539 100644--- a/server/pkg/db/queries/vcs.sql+++ b/server/pkg/db/queries/vcs.sql@@ -178,6 +178,13 @@ 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 :execrowsINSERT INTO issue_vcs_pull_request (issue_id, pull_request_id, linked_by_type, linked_by_id