Skip to content

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

Go

MUL-8135: feat(wakeups): wake on linked PR merge conflicts (--until-pr conflicts) (#9406)

Jiayuan Zhange720fe221947
diff --git a/docs/engineering/issue-wakeups.md b/docs/engineering/issue-wakeups.md
index f6cec55cf5..c02d01de01 100644
--- a/docs/engineering/issue-wakeups.md
+++ b/docs/engineering/issue-wakeups.md
@@ -579,7 +579,7 @@ the scheduler evaluates:
| `issue_field` | `field=label`, `label_id` | it has that label |
| `issue_field` | `field=property`, `property_id`, `value` | the property's stored value equals `value` |
| `children_done` | optional `stage` | every sub-issue (or every one up to that stage) is closed |
-| `pull_request` | `event=checks_finished` or `merged` | a linked PR's checks finished on its current head, or it merged |
+| `pull_request` | `event=checks_finished`, `merged` or `conflicts` | a linked PR's checks finished on its current head, it merged, or an open GitHub PR is `CONFLICTING` on its current head |
| `other_issue` | `issue_id`, `state=done`, `ended` or `in_review` | another issue in the workspace reaches that state |
A condition rule stays `kind=event`. Validation derives the same-issue events
@@ -593,6 +593,26 @@ head's result, another sub-issue set). States already true at registration fire
on the first check; finished checks from before registration are ignored. The
watched issue's identifier is stored in the condition for display.
+`conflicts` reads the GitHub API snapshot (`api_mergeable`) and counts only a
+snapshot fetched for the PR's current head, so a verdict from before a push
+never fires. Its key is `pr_id@head:conflicting` (PR numbers and heads repeat
+across forks). GitHub reports
+`UNKNOWN` while it recomputes mergeability; on the same head that keeps the
+previous verdict, so a continuous rule is not woken twice for one conflict.
+Self-hosted VCS rows store no mergeability; a rule linked only to them records
+a diagnostic. For every linked-PR condition, a run starts only when some PR
+key occurs more often than in `condition_state` (checks and merged keys carry
+only the PR number, so same-numbered PRs from two repositories share one); a
+PR leaving the set (resolved, closed, unlinked) only updates
+`condition_state`, so it does not wake the agent again for the PRs that stayed. A base-branch move sends no event for the PR, so the snapshot
+pipeline keeps watched PRs (linked to an issue with an enabled `conflicts`
+rule) fresh: the 10-minute sweep re-fetches them once their snapshot is older
+than 5 minutes even when decided, rotating an address cursor like the
+undecided sweep so repeatedly failing fetches cannot starve the rest, and a merged `pull_request` webhook
+re-fetches the repository's other watched open PRs after 30 seconds and 3
+minutes. No migration is involved; older clients show the rule without a
+condition label.
+
**Runaway protection.** Repeating event rules default to `max_fires=20`
(1–1000, any repeating rule may set it); the run that reaches the cap is
created and the rule is paused with `paused_reason=max_fires`. Each wakeup run
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index 6afcda1d96..321d4a21d9 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -3719,7 +3719,7 @@ export const WakeupConditionSchema = z.union([
z.object({ type: z.literal("issue_field"), field: z.literal("label"), label_id: z.string() }),
z.object({ type: z.literal("issue_field"), field: z.literal("property"), property_id: z.string(), value: z.unknown() }),
z.object({ type: z.literal("children_done"), stage: z.number().int().nullish() }),
- z.object({ type: z.literal("pull_request"), event: z.enum(["checks_finished", "merged"]) }),
+ z.object({ type: z.literal("pull_request"), event: z.enum(["checks_finished", "merged", "conflicts"]) }),
z.object({ type: z.literal("other_issue"), issue_id: z.string(), state: z.enum(["done", "ended", "in_review"]), identifier: z.string().optional() }),
]);
diff --git a/packages/core/types/issue-wakeup.ts b/packages/core/types/issue-wakeup.ts
index c608fbc8e5..ecf4ebb4b4 100644
--- a/packages/core/types/issue-wakeup.ts
+++ b/packages/core/types/issue-wakeup.ts
@@ -53,7 +53,7 @@ export type WakeupCondition =
| { type: "issue_field"; field: "label"; label_id: string }
| { type: "issue_field"; field: "property"; property_id: string; value: unknown }
| { type: "children_done"; stage?: number | null }
- | { type: "pull_request"; event: "checks_finished" | "merged" }
+ | { type: "pull_request"; event: "checks_finished" | "merged" | "conflicts" }
| { type: "other_issue"; issue_id: string; state: "done" | "ended" | "in_review"; identifier?: string };
/** One run a rule started, for its trigger history. */
diff --git a/packages/views/issues/components/wakeup-activity.test.tsx b/packages/views/issues/components/wakeup-activity.test.tsx
index 21aa65a428..b099f7b940 100644
--- a/packages/views/issues/components/wakeup-activity.test.tsx
+++ b/packages/views/issues/components/wakeup-activity.test.tsx
@@ -39,6 +39,9 @@ describe("wakeup timeline entries", () => {
expect(read(entry("wakeup_triggered", { wakeup: { ...reply, condition: { type: "pull_request", event: "checks_finished" } } }))).toBe(
"当关联 PR 的 CI 结束时,唤醒了 Emacs",
);
+ expect(read(entry("wakeup_triggered", { wakeup: { ...reply, condition: { type: "pull_request", event: "conflicts" } } }))).toBe(
+ "当关联 PR 出现合并冲突时,唤醒了 Emacs",
+ );
expect(read(entry("wakeup_triggered", { wakeup: reply, events: ["wakeup.manual"], actor_type: "member", actor_id: "u" }))).toBe(
"Jiayuan 立即唤醒了 Emacs",
);
diff --git a/packages/views/issues/components/wakeup-create.tsx b/packages/views/issues/components/wakeup-create.tsx
index 1b3cfa43a1..ee894adbea 100644
--- a/packages/views/issues/components/wakeup-create.tsx
+++ b/packages/views/issues/components/wakeup-create.tsx
@@ -459,6 +459,7 @@ function ConditionParams({
options={[
{ value: "checks_finished", label: t(($) => $.wakeups.create.pr_checks) },
{ value: "merged", label: t(($) => $.wakeups.create.pr_merged) },
+ { value: "conflicts", label: t(($) => $.wakeups.create.pr_conflicts) },
]}
onChange={(prEvent) => update({ prEvent: prEvent as WakeupDraft["prEvent"] })}
/>
diff --git a/packages/views/issues/components/wakeup-draft.test.ts b/packages/views/issues/components/wakeup-draft.test.ts
index aeab540099..cc82278604 100644
--- a/packages/views/issues/components/wakeup-draft.test.ts
+++ b/packages/views/issues/components/wakeup-draft.test.ts
@@ -87,6 +87,7 @@ describe("platform conditions", () => {
expect(input({ condition: "children", stage: 2 })).toMatchObject({ input: { condition: { type: "children_done", stage: 2 } } });
expect(input({ condition: "children", stage: null })).toMatchObject({ input: { condition: { type: "children_done" } } });
expect(input({ condition: "pull_request", prEvent: "merged" })).toMatchObject({ input: { condition: { type: "pull_request", event: "merged" } } });
+ expect(input({ condition: "pull_request", prEvent: "conflicts" })).toMatchObject({ input: { condition: { type: "pull_request", event: "conflicts" } } });
expect(input({ condition: "other_issue", otherIssue: { id: "i2", identifier: "MUL-2" }, otherState: "ended" })).toMatchObject({
input: { condition: { type: "other_issue", issue_id: "i2", state: "ended" } },
});
diff --git a/packages/views/issues/components/wakeup-draft.ts b/packages/views/issues/components/wakeup-draft.ts
index 7ae741378d..11423b18db 100644
--- a/packages/views/issues/components/wakeup-draft.ts
+++ b/packages/views/issues/components/wakeup-draft.ts
@@ -78,7 +78,7 @@ export interface WakeupDraft {
assignee: { type: "member" | "agent" | "squad"; id: string } | null;
/** Null waits for every sub-issue. */
stage: number | null;
- prEvent: "checks_finished" | "merged";
+ prEvent: "checks_finished" | "merged" | "conflicts";
otherIssue: { id: string; identifier: string } | null;
otherState: "done" | "ended" | "in_review";
maxFires: number;
diff --git a/packages/views/issues/components/wakeup-presentation.ts b/packages/views/issues/components/wakeup-presentation.ts
index 3a5b756d95..626b4c6500 100644
--- a/packages/views/issues/components/wakeup-presentation.ts
+++ b/packages/views/issues/components/wakeup-presentation.ts
@@ -236,7 +236,10 @@ export function useWakeupText() {
case "children_done":
return c.stage ? { key: "children_stage" as const, values: { stage: c.stage } } : { key: "children_all" as const, values: {} };
case "pull_request":
- return { key: c.event === "merged" ? ("pr_merged" as const) : ("pr_checks" as const), values: {} };
+ return {
+ key: c.event === "merged" ? ("pr_merged" as const) : c.event === "conflicts" ? ("pr_conflicts" as const) : ("pr_checks" as const),
+ values: {},
+ };
case "other_issue":
return {
key: c.state === "ended" ? ("other_ended" as const) : c.state === "in_review" ? ("other_in_review" as const) : ("other_done" as const),
diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.json
index d304925a39..709e8cc968 100644
--- a/packages/views/locales/en/issues.json
+++ b/packages/views/locales/en/issues.json
@@ -1297,6 +1297,7 @@
"children_stage": "Stage {{stage}}",
"pr_checks": "CI finishes",
"pr_merged": "It merges",
+ "pr_conflicts": "It has merge conflicts",
"choose_issue": "Choose an issue",
"pick_issue_title": "Watch an issue",
"pick_issue_description": "Wake the agent when this issue reaches the state you choose.",
@@ -1354,6 +1355,7 @@
"children_stage": "When stage {{stage}}'s sub-issues all finish",
"pr_checks": "When a linked PR's CI finishes",
"pr_merged": "When a linked PR merges",
+ "pr_conflicts": "When a linked PR has merge conflicts",
"other_done": "When {{issue}} is done",
"other_ended": "When {{issue}} is done or cancelled",
"other_in_review": "When {{issue}} moves to In Review",
@@ -1376,6 +1378,7 @@
"children_stage": "Waiting for stage {{stage}}",
"pr_checks": "Waiting for CI",
"pr_merged": "Waiting for the PR to merge",
+ "pr_conflicts": "Watching for merge conflicts",
"other_done": "Waiting for {{issue}}",
"other_ended": "Waiting for {{issue}} to end",
"other_in_review": "Waiting for {{issue}} to reach review",
diff --git a/packages/views/locales/fr/issues.json b/packages/views/locales/fr/issues.json
index 43d38823ba..37b5a333af 100644
--- a/packages/views/locales/fr/issues.json
+++ b/packages/views/locales/fr/issues.json
@@ -1297,6 +1297,7 @@
"children_stage": "Étape {{stage}}",
"pr_checks": "Fin de la CI",
"pr_merged": "Fusion",
+ "pr_conflicts": "Conflits de fusion",
"choose_issue": "Choisir une tâche",
"pick_issue_title": "Suivre une tâche",
"pick_issue_description": "Réveille l’agent quand cette tâche atteint l’état choisi.",
@@ -1354,6 +1355,7 @@
"children_stage": "Quand les sous-tâches de l’étape {{stage}} sont terminées",
"pr_checks": "Quand la CI d’une PR liée se termine",
"pr_merged": "Quand une PR liée est fusionnée",
+ "pr_conflicts": "Quand une PR liée a des conflits de fusion",
"other_done": "Quand {{issue}} est terminée",
"other_ended": "Quand {{issue}} est terminée ou annulée",
"other_in_review": "Quand {{issue}} passe en revue",
@@ -1376,6 +1378,7 @@
"children_stage": "Attend l’étape {{stage}}",
"pr_checks": "Attend la CI",
"pr_merged": "Attend la fusion de la PR",
+ "pr_conflicts": "Surveille les conflits de fusion",
"other_done": "Attend {{issue}}",
"other_ended": "Attend la fin de {{issue}}",
"other_in_review": "Attend la revue de {{issue}}",
diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.json
index 8c1bac1462..4916f7d8c0 100644
--- a/packages/views/locales/ja/issues.json
+++ b/packages/views/locales/ja/issues.json
@@ -1254,6 +1254,7 @@
"children_stage": "ステージ {{stage}}",
"pr_checks": "CI 終了",
"pr_merged": "マージ",
+ "pr_conflicts": "マージコンフリクト発生",
"choose_issue": "タスクを選択",
"pick_issue_title": "見守るタスク",
"pick_issue_description": "このタスクが選んだ状態になったらエージェントを起こします。",
@@ -1309,6 +1310,7 @@
"children_stage": "ステージ {{stage}} のサブタスクがすべて終わったとき",
"pr_checks": "関連 PR の CI が終わったとき",
"pr_merged": "関連 PR がマージされたとき",
+ "pr_conflicts": "関連 PR にマージコンフリクトが発生したとき",
"other_done": "{{issue}} が完了したとき",
"other_ended": "{{issue}} が完了またはキャンセルされたとき",
"other_in_review": "{{issue}} がレビュー中になったとき",
@@ -1331,6 +1333,7 @@
"children_stage": "ステージ {{stage}} 待ち",
"pr_checks": "CI 待ち",
"pr_merged": "PR のマージ待ち",
+ "pr_conflicts": "マージコンフリクトを監視中",
"other_done": "{{issue}} の完了待ち",
"other_ended": "{{issue}} の終了待ち",
"other_in_review": "{{issue}} のレビュー待ち",
diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.json
index d640679846..fbe6c03031 100644
--- a/packages/views/locales/ko/issues.json
+++ b/packages/views/locales/ko/issues.json
@@ -1254,6 +1254,7 @@
"children_stage": "{{stage}}단계",
"pr_checks": "CI 종료",
"pr_merged": "병합",
+ "pr_conflicts": "병합 충돌 발생",
"choose_issue": "태스크 선택",
"pick_issue_title": "지켜볼 태스크",
"pick_issue_description": "이 태스크가 선택한 상태가 되면 에이전트를 깨웁니다.",
@@ -1309,6 +1310,7 @@
"children_stage": "{{stage}}단계 하위 태스크가 모두 끝나면",
"pr_checks": "연결된 PR의 CI가 끝나면",
"pr_merged": "연결된 PR이 병합되면",
+ "pr_conflicts": "연결된 PR에 병합 충돌이 생기면",
"other_done": "{{issue}}이(가) 완료되면",
"other_ended": "{{issue}}이(가) 완료되거나 취소되면",
"other_in_review": "{{issue}}이(가) 검토 중으로 바뀌면",
@@ -1331,6 +1333,7 @@
"children_stage": "{{stage}}단계 대기",
"pr_checks": "CI 대기",
"pr_merged": "PR 병합 대기",
+ "pr_conflicts": "병합 충돌 감시 중",
"other_done": "{{issue}} 완료 대기",
"other_ended": "{{issue}} 종료 대기",
"other_in_review": "{{issue}} 검토 대기",
diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.json
index 03ab93bea6..3f6ae11af4 100644
--- a/packages/views/locales/zh-Hans/issues.json
+++ b/packages/views/locales/zh-Hans/issues.json
@@ -1254,6 +1254,7 @@
"children_stage": "第 {{stage}} 阶段",
"pr_checks": "CI 结束",
"pr_merged": "合并",
+ "pr_conflicts": "出现合并冲突",
"choose_issue": "选择任务",
"pick_issue_title": "选择要关注的任务",
"pick_issue_description": "该任务达到所选状态时唤醒智能体。",
@@ -1309,6 +1310,7 @@
"children_stage": "当第 {{stage}} 阶段的子任务全部结束时",
"pr_checks": "当关联 PR 的 CI 结束时",
"pr_merged": "当关联 PR 合并时",
+ "pr_conflicts": "当关联 PR 出现合并冲突时",
"other_done": "当 {{issue}} 完成时",
"other_ended": "当 {{issue}} 完成或取消时",
"other_in_review": "当 {{issue}} 进入审核中时",
@@ -1331,6 +1333,7 @@
"children_stage": "等第 {{stage}} 阶段完成",
"pr_checks": "等 CI 结束",
"pr_merged": "等 PR 合并",
+ "pr_conflicts": "监视合并冲突",
"other_done": "等 {{issue}} 完成",
"other_ended": "等 {{issue}} 结束",
"other_in_review": "等 {{issue}} 进入审核",
diff --git a/server/cmd/multica/cmd_issue_wakeup.go b/server/cmd/multica/cmd_issue_wakeup.go
index d942469bd7..e99ea6edef 100644
--- a/server/cmd/multica/cmd_issue_wakeup.go
+++ b/server/cmd/multica/cmd_issue_wakeup.go
@@ -21,7 +21,7 @@ func init() { issueCmd.AddCommand(newIssueWakeupCommand()) }
func newIssueWakeupCommand() *cobra.Command {
wake := &cobra.Command{Use: "wakeup", Short: "Manage event and time wakeups that start ordinary runs"}
wake.AddCommand(&cobra.Command{Use: "events", Short: "List supported event types and filters", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error {
- return cli.PrintJSON(os.Stdout, map[string]any{"event_types": eventcontract.WakeupTypes, "platform_only_event_types": eventcontract.LifecycleTypes, "platform_only_reason": "Creation precedes subscription; deletion withdraws the issue's wakeups. Cross-issue subscriptions are not supported.", "scope": "current issue", "filters": []string{"filter_agent_id (task events; legacy mutation alias)", "filter_task_id (task events only)", "filter_actor_type + filter_actor_id (member or agent; mutation events only)"}, "modes": []string{"once (default)", "continuous"}, "conditions": []string{"--until-status KEY", "--until-assignee member|agent|squad:ID", "--until-label LABEL_ID", "--until-property PROPERTY_ID=VALUE", "--until-children-done [--stage N]", "--until-pr checks|merged", "--until-issue ISSUE [--until-issue-state done|ended|in_review]"}, "loop_protection": "Events from the registering run and runs started by the same rule are excluded when source identity is available. Repeating rules stop after --max-fires runs (default 20 for continuous event rules). A rule is paused when its trigger chain passes through it a third time without a person in between, or when it starts more than 12 runs in an hour."})
+ return cli.PrintJSON(os.Stdout, map[string]any{"event_types": eventcontract.WakeupTypes, "platform_only_event_types": eventcontract.LifecycleTypes, "platform_only_reason": "Creation precedes subscription; deletion withdraws the issue's wakeups. Cross-issue subscriptions are not supported.", "scope": "current issue", "filters": []string{"filter_agent_id (task events; legacy mutation alias)", "filter_task_id (task events only)", "filter_actor_type + filter_actor_id (member or agent; mutation events only)"}, "modes": []string{"once (default)", "continuous"}, "conditions": []string{"--until-status KEY", "--until-assignee member|agent|squad:ID", "--until-label LABEL_ID", "--until-property PROPERTY_ID=VALUE", "--until-children-done [--stage N]", "--until-pr checks|merged|conflicts", "--until-issue ISSUE [--until-issue-state done|ended|in_review]"}, "loop_protection": "Events from the registering run and runs started by the same rule are excluded when source identity is available. Repeating rules stop after --max-fires runs (default 20 for continuous event rules). A rule is paused when its trigger chain passes through it a third time without a person in between, or when it starts more than 12 runs in an hour."})
}})
for _, action := range []string{"list", "get", "disable", "create", "update", "trigger", "delete", "checkin", "runs"} {
action := action
@@ -81,7 +81,7 @@ func newIssueWakeupCommand() *cobra.Command {
c.Flags().String("until-property", "", "Condition: property PROPERTY_ID equals VALUE (PROPERTY_ID=VALUE; VALUE may be JSON)")
c.Flags().Bool("until-children-done", false, "Condition: every sub-issue is closed (or those up to --stage)")
c.Flags().Int32("stage", 0, "With --until-children-done: wait for this stage and earlier ones")
- c.Flags().String("until-pr", "", "Condition: a linked pull request's checks finish (checks) or it merges (merged)")
+ c.Flags().String("until-pr", "", "Condition: a linked pull request's checks finish (checks), it merges (merged), or it has merge conflicts on its current head (conflicts; GitHub only)")
c.Flags().String("until-issue", "", "Condition: another issue in this workspace reaches --until-issue-state")
c.Flags().String("until-issue-state", "done", "With --until-issue: done, ended (done or cancelled) or in_review")
c.Flags().Int32("max-fires", 0, "Repeating rules: stop after this many runs (1-1000; continuous event rules default to 20)")
@@ -291,9 +291,9 @@ func wakeupConditionFromFlags(ctx context.Context, cmd *cobra.Command, client *c
return nil, fmt.Errorf("--stage requires --until-children-done")
}
if v, _ := cmd.Flags().GetString("until-pr"); v != "" {
- event := map[string]string{"checks": "checks_finished", "merged": "merged"}[v]
+ event := map[string]string{"checks": "checks_finished", "merged": "merged", "conflicts": "conflicts"}[v]
if event == "" {
- return nil, fmt.Errorf("--until-pr takes checks or merged")
+ return nil, fmt.Errorf("--until-pr takes checks, merged or conflicts")
}
conditions = append(conditions, map[string]any{"type": "pull_request", "event": event})
}
diff --git a/server/cmd/multica/cmd_issue_wakeup_test.go b/server/cmd/multica/cmd_issue_wakeup_test.go
index d29ccbd5d3..64b5bde58c 100644
--- a/server/cmd/multica/cmd_issue_wakeup_test.go
+++ b/server/cmd/multica/cmd_issue_wakeup_test.go
@@ -177,6 +177,7 @@ func TestIssueWakeupCLIConditionsAndManagement(t *testing.T) {
{[]string{"--until-property", "p1=approved"}, `{"field":"property","property_id":"p1","type":"issue_field","value":"approved"}`},
{[]string{"--until-children-done", "--stage", "2"}, `{"stage":2,"type":"children_done"}`},
{[]string{"--until-pr", "checks", "--mode", "continuous", "--max-fires", "5"}, `{"event":"checks_finished","type":"pull_request"}`},
+ {[]string{"--until-pr", "conflicts", "--mode", "continuous", "--max-fires", "5"}, `{"event":"conflicts","type":"pull_request"}`},
{[]string{"--until-assignee", "agent:a1"}, `{"assignee_id":"a1","assignee_type":"agent","field":"assignee","type":"issue_field"}`},
} {
calls = nil
diff --git a/server/internal/daemon/execenv/runtime_config_sections.go b/server/internal/daemon/execenv/runtime_config_sections.go
index 92ebda662a..a3dc847030 100644
--- a/server/internal/daemon/execenv/runtime_config_sections.go
+++ b/server/internal/daemon/execenv/runtime_config_sections.go
@@ -221,7 +221,7 @@ func writeAvailableCommands(b *strings.Builder, ctx TaskContextForEnv) {
b.WriteString("- `multica issue assign <id> (--to X | --to-id <uuid> | --unassign)` — change ownership; assigning to an agent can start a run.\n")
writeIssueStatusCommand(b, ctx)
b.WriteString(duplicateOfCommandLine)
- b.WriteString("- `multica issue wakeup <create|list|get|update|disable|trigger|delete|runs|events>` — persist an event, condition or time wakeup on this issue, then finish the current run. When the platform can check the fact itself, use a condition (`--until-status`, `--until-pr checks`, `--until-children-done`, `--until-issue`) so no run starts before it holds. PR conditions watch only PRs linked to this exact issue; `--until-pr checks` also requires server-side GitHub check snapshots. Check the rule's `last_error` for missing links or unavailable snapshots; delayed links and snapshots are retried automatically. Use `--event comment.created --filter-actor-type member --filter-actor-id USER_ID` to wait for a specific member to comment. See `multica issue wakeup --help` and the multica-platform issues reference.\n")
+ b.WriteString("- `multica issue wakeup <create|list|get|update|disable|trigger|delete|runs|events>` — persist an event, condition or time wakeup on this issue, then finish the current run. When the platform can check the fact itself, use a condition (`--until-status`, `--until-pr checks|conflicts`, `--until-children-done`, `--until-issue`) so no run starts before it holds. PR conditions watch only PRs linked to this exact issue; `--until-pr checks|conflicts` also requires server-side GitHub snapshots. Check the rule's `last_error` for missing links or unavailable snapshots; delayed links and snapshots are retried automatically. Use `--event comment.created --filter-actor-type member --filter-actor-id USER_ID` to wait for a specific member to comment. See `multica issue wakeup --help` and the multica-platform issues reference.\n")
b.WriteString("- `multica issue children <id> [--output json]` — list a parent's sub-issues grouped by stage.\n")
b.WriteString("- `multica issue comment add <issue-id> [--content \"...\" | --content-file <path> | --content-stdin] [--parent <comment-id>] [--attachment <path>]` — post a comment. Agent-authored bodies MUST use `--content-file`; see `## Comment Formatting` for why. `multica issue comment add --help` for full flags.\n")
b.WriteString("- `multica repo checkout <url> [--ref <branch-or-sha>] [--fresh]` — repository checkout on a dedicated branch. Re-running it keeps an existing checkout that has uncommitted or unpushed work, or is already on this task's branch, and only fetches. `--fresh` discards uncommitted and untracked files and starts a new branch; commits stay on the old branch, but push any you still need first.\n\n")
diff --git a/server/internal/handler/github.go b/server/internal/handler/github.go
index 8b0e541dbe..210e57afcd 100644
--- a/server/internal/handler/github.go
+++ b/server/internal/handler/github.go
@@ -1318,6 +1318,9 @@ func (h *Handler) handlePullRequestEvent(ctx context.Context, body []byte) {
// only the doorbell — its own mergeable/checks payload is not used for
// display anymore (MUL-5265).
h.PRRefresh.Enqueue(p.Installation.ID, p.Repository.Owner.Login, p.Repository.Name, p.PullRequest.Number)
+ if p.Action == "closed" && p.PullRequest.Merged {
+ h.PRRefresh.RefreshConflictWatchers(ctx, p.Installation.ID, p.Repository.Owner.Login, p.Repository.Name, p.PullRequest.Number)
+ }
}
// prLinkPolicy decides which (identifier, workspace) pairs this delivery may
diff --git a/server/internal/integrations/ghsnapshot/refresh.go b/server/internal/integrations/ghsnapshot/refresh.go
index 9e3c68490d..ea2f28eed2 100644
--- a/server/internal/integrations/ghsnapshot/refresh.go
+++ b/server/internal/integrations/ghsnapshot/refresh.go
@@ -40,8 +40,15 @@ var (
defaultSweepTTL = 10 * time.Minute
defaultSweepInterval = 10 * time.Minute
defaultSweepMaxRows = int32(200)
- maxChaseAttempts = 12
- queueBuffer = 2048
+ // PRs watched by a "wake on merge conflict" rule stay in the sweep even
+ // when decided, re-fetched once their snapshot is older than this.
+ defaultWatchTTL = 5 * time.Minute
+ // After a merge into a repository, GitHub recomputes the other PRs'
+ // mergeability asynchronously and may still answer with the old verdict
+ // at first, so watched PRs are fetched after each of these delays.
+ defaultMergeWatchDelays = []time.Duration{30 * time.Second, 3 * time.Minute}
+ maxChaseAttempts = 12
+ queueBuffer = 2048
)
// Manager owns the outbound GitHub API refresh pipeline. A Manager whose client
@@ -61,6 +68,8 @@ type Manager struct {
sweepTTL time.Duration
sweepInterval time.Duration
sweepMaxRows int32
+ watchTTL time.Duration
+ mergeDelays []time.Duration
chaseBackoff []time.Duration
now func() time.Time
jitter func() time.Duration
@@ -79,6 +88,8 @@ type Manager struct {
// this cursor and wraps, preventing a fixed first page from starving later
// installations when early addresses repeatedly fail.
sweepAfter address
+ // The same rotation for the conflict-watch sweep.
+ watchAfter address
// Secondary rate limits are scoped to the installation whose token incurred
// them. One customer must never pause every other installation.
rateUntil map[int64]time.Time
@@ -102,6 +113,8 @@ func NewManager(client *Client, queries *db.Queries, pool TxBeginner, onApplied
sweepTTL: defaultSweepTTL,
sweepInterval: defaultSweepInterval,
sweepMaxRows: defaultSweepMaxRows,
+ watchTTL: defaultWatchTTL,
+ mergeDelays: defaultMergeWatchDelays,
chaseBackoff: defaultChaseBackoff,
now: time.Now,
jitter: func() time.Duration { return time.Duration(rand.Int63n(int64(250 * time.Millisecond))) },
@@ -491,11 +504,16 @@ func (m *Manager) sweepLoop(ctx context.Context) {
}
}
-// sweepOnce enqueues a refresh for every open PR whose snapshot is both stale
-// and undecided. Bounded by sweepMaxRows. This is the safety net for an
+func (m *Manager) sweepOnce(ctx context.Context) {
+ m.sweepUndecided(ctx)
+ m.sweepConflictWatched(ctx)
+}
+
+// sweepUndecided enqueues a refresh for every open PR whose snapshot is both
+// stale and undecided. Bounded by sweepMaxRows. This is the safety net for an
// undecided PR whose base branch changes without a pull_request webhook, and
// for any webhook that was dropped during a deploy.
-func (m *Manager) sweepOnce(ctx context.Context) {
+func (m *Manager) sweepUndecided(ctx context.Context) {
m.mu.Lock()
after := m.sweepAfter
m.mu.Unlock()
@@ -528,6 +546,62 @@ func (m *Manager) sweepOnce(ctx context.Context) {
}
}
+// sweepConflictWatched keeps the PRs a "wake on merge conflict" rule watches
+// fresh. A decided snapshot leaves the undecided sweep, yet a direct push to
+// the base branch can make it conflicting with no event for the PR itself.
+func (m *Manager) sweepConflictWatched(ctx context.Context) {
+ m.mu.Lock()
+ after := m.watchAfter
+ m.mu.Unlock()
+
+ rows, err := m.queries.ListStaleConflictWatchedGitHubPRs(ctx, db.ListStaleConflictWatchedGitHubPRsParams{
+ OlderThan: tsFromTime(m.now().Add(-m.watchTTL)),
+ AfterInstallationID: after.InstallationID,
+ AfterRepoOwner: after.Owner,
+ AfterRepoName: after.Repo,
+ AfterPrNumber: after.Number,
+ MaxRows: m.sweepMaxRows,
+ })
+ if err != nil {
+ slog.Warn("ghsnapshot: conflict-watch sweep query failed", "err", err.Error())
+ return
+ }
+ if len(rows) > 0 {
+ last := rows[len(rows)-1]
+ m.mu.Lock()
+ m.watchAfter = address{InstallationID: last.InstallationID, Owner: last.RepoOwner, Repo: last.RepoName, Number: last.PrNumber}
+ m.mu.Unlock()
+ }
+ for _, r := range rows {
+ m.Enqueue(r.InstallationID, r.RepoOwner, r.RepoName, r.PrNumber)
+ }
+}
+
+// RefreshConflictWatchers schedules refreshes for the open PRs in a repository
+// that a "wake on merge conflict" rule watches, after the PR numbered merged
+// merged there. That can move their base, which sends no event for them.
+func (m *Manager) RefreshConflictWatchers(ctx context.Context, installationID int64, owner, repo string, merged int32) {
+ if !m.Enabled() {
+ return
+ }
+ numbers, err := m.queries.ListConflictWatchedGitHubPRNumbersInRepo(ctx, db.ListConflictWatchedGitHubPRNumbersInRepoParams{
+ InstallationID: installationID,
+ RepoOwner: owner,
+ RepoName: repo,
+ PrNumber: merged,
+ })
+ if err != nil {
+ slog.Warn("ghsnapshot: conflict-watch lookup failed", "err", err.Error())
+ return
+ }
+ for _, number := range numbers {
+ addr := address{InstallationID: installationID, Owner: owner, Repo: repo, Number: number}
+ for _, delay := range m.mergeDelays {
+ m.scheduleRetry(addr, delay)
+ }
+ }
+}
+
// ── helpers ──────────────────────────────────────────────────────────────────
func asRateLimit(err error, target **RateLimitError) bool {
diff --git a/server/internal/integrations/ghsnapshot/refresh_db_test.go b/server/internal/integrations/ghsnapshot/refresh_db_test.go
index e08c7d3090..4a1fc4cd8f 100644
--- a/server/internal/integrations/ghsnapshot/refresh_db_test.go
+++ b/server/internal/integrations/ghsnapshot/refresh_db_test.go
@@ -221,6 +221,178 @@ func TestListStaleUndecidedGitHubPRsExcludesDecidedAndRotatesCursor(t *testing.T
}
}
+// watchPR links pr to a new issue carrying a pull_request wakeup rule for
+// event, as a "wake on merge conflict" rule does.
+func watchPR(t *testing.T, pool *pgxpool.Pool, pr db.GithubPullRequest, event string, enabled bool) {
+ t.Helper()
+ ctx := context.Background()
+ var issueID pgtype.UUID
+ if err := pool.QueryRow(ctx, `INSERT INTO issue (workspace_id,title,creator_type,creator_id)
+ VALUES ($1,'watch','member',gen_random_uuid()) RETURNING id`, pr.WorkspaceID).Scan(&issueID); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() {
+ _, _ = pool.Exec(context.Background(), `DELETE FROM issue_wakeup WHERE issue_id=$1`, issueID)
+ _, _ = pool.Exec(context.Background(), `DELETE FROM issue_pull_request WHERE issue_id=$1`, issueID)
+ _, _ = pool.Exec(context.Background(), `DELETE FROM issue WHERE id=$1`, issueID)
+ })
+ if _, err := pool.Exec(ctx, `INSERT INTO issue_pull_request(issue_id,pull_request_id) VALUES($1,$2)`, issueID, pr.ID); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := pool.Exec(ctx, `INSERT INTO issue_wakeup(id,workspace_id,issue_id,instruction,kind,mode,enabled,condition)
+ VALUES(gen_random_uuid(),$1,$2,'go','event','once',$3,jsonb_build_object('type','pull_request','event',$4::text))`,
+ pr.WorkspaceID, issueID, enabled, event); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// A watched address whose fetches keep failing never gets a newer snapshot.
+// The bounded sweep must still move past it to the others.
+func TestConflictWatchSweepRotatesPastFailingAddresses(t *testing.T) {
+ pool := testDBPool(t)
+ q := db.New(pool)
+ ctx := context.Background()
+ now := time.Now()
+ const installationID int64 = 7_313_000_002
+ repo := "rotate-" + randHex(t)
+ for number := int32(1); number <= 2; number++ {
+ pr := seedPRAt(t, pool, q, installationID, repo, number, "H")
+ t.Cleanup(func() { _, _ = pool.Exec(context.Background(), `DELETE FROM github_pull_request WHERE id=$1`, pr.ID) })
+ if _, err := pool.Exec(ctx, `UPDATE github_pull_request
+ SET snapshot_head_sha=head_sha, snapshot_fetched_at=$2, api_mergeable='MERGEABLE', checks_rollup_state='SUCCESS'
+ WHERE id=$1`, pr.ID, now.Add(time.Duration(number-3)*time.Hour)); err != nil {
+ t.Fatal(err)
+ }
+ watchPR(t, pool, pr, "conflicts", true)
+ }
+
+ m := NewManager(enabledClient(t), q, pool, nil)
+ m.sweepMaxRows = 1
+ seen := map[int32]bool{}
+ // Other packages' fixtures share this database, so allow enough passes
+ // to wrap past them; fetches never run, as if every one failed.
+ for sweep := 0; sweep < 50 && !(seen[1] && seen[2]); sweep++ {
+ m.sweepConflictWatched(ctx)
+ for len(m.queue) > 0 {
+ addr := <-m.queue
+ if addr.InstallationID == installationID && addr.Repo == repo {
+ seen[addr.Number] = true
+ }
+ m.mu.Lock()
+ delete(m.active, addr)
+ m.mu.Unlock()
+ }
+ }
+ if !seen[1] || !seen[2] {
+ t.Fatalf("bounded sweeps visited %v; a failing address starved the rest", seen)
+ }
+}
+
+func TestConflictWatchedGitHubPRQueries(t *testing.T) {
+ pool := testDBPool(t)
+ q := db.New(pool)
+ ctx := context.Background()
+ now := time.Now()
+ const installationID int64 = 7_313_000_001
+ repo := "watch-" + randHex(t)
+
+ seed := func(number int32, state string, fetchedAt time.Time) db.GithubPullRequest {
+ t.Helper()
+ pr := seedPRAt(t, pool, q, installationID, repo, number, fmt.Sprintf("H%d", number))
+ if _, err := pool.Exec(ctx, `UPDATE github_pull_request
+ SET state=$2, snapshot_head_sha=head_sha, snapshot_fetched_at=$3, api_mergeable='MERGEABLE', checks_rollup_state='SUCCESS'
+ WHERE id=$1`, pr.ID, state, fetchedAt); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _, _ = pool.Exec(context.Background(), `DELETE FROM github_pull_request WHERE id=$1`, pr.ID) })
+ return pr
+ }
+ watch := func(pr db.GithubPullRequest, event string, enabled bool) {
+ t.Helper()
+ watchPR(t, pool, pr, event, enabled)
+ }
+
+ stale := now.Add(-time.Hour)
+ watched := seed(1, "open", stale)
+ watch(watched, "conflicts", true)
+ draft := seed(2, "draft", stale)
+ watch(draft, "conflicts", true)
+ fresh := seed(3, "open", now)
+ watch(fresh, "conflicts", true)
+ checksOnly := seed(4, "open", stale)
+ watch(checksOnly, "checks_finished", true)
+ disabled := seed(5, "open", stale)
+ watch(disabled, "conflicts", false)
+ closed := seed(6, "closed", stale)
+ watch(closed, "conflicts", true)
+ seed(7, "open", stale)
+
+ rows, err := q.ListStaleConflictWatchedGitHubPRs(ctx, db.ListStaleConflictWatchedGitHubPRsParams{
+ OlderThan: tsFromTime(now.Add(-5 * time.Minute)),
+ MaxRows: 1000,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ var swept []int32
+ for _, r := range rows {
+ if r.InstallationID == installationID && r.RepoName == repo {
+ swept = append(swept, r.PrNumber)
+ }
+ }
+ // Decided snapshots stay in this sweep; only stale, open, watched PRs.
+ if fmt.Sprint(swept) != "[1 2]" && fmt.Sprint(swept) != "[2 1]" {
+ t.Fatalf("watched sweep = %v, want PRs 1 and 2", swept)
+ }
+
+ numbers, err := q.ListConflictWatchedGitHubPRNumbersInRepo(ctx, db.ListConflictWatchedGitHubPRNumbersInRepoParams{
+ InstallationID: installationID, RepoOwner: "o", RepoName: repo, PrNumber: 2,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ // After PR 2 merges: every other open watched PR, fresh or not.
+ if fmt.Sprint(numbers) != "[1 3]" {
+ t.Fatalf("watched PRs after a merge = %v, want [1 3]", numbers)
+ }
+ other, err := q.ListConflictWatchedGitHubPRNumbersInRepo(ctx, db.ListConflictWatchedGitHubPRNumbersInRepoParams{
+ InstallationID: installationID, RepoOwner: "o", RepoName: repo + "-other", PrNumber: 0,
+ })
+ if err != nil || len(other) != 0 {
+ t.Fatalf("another repository's merge must not reach these PRs: %v %v", other, err)
+ }
+
+ // Workers are not started, so the queue shows what each trigger enqueued.
+ m := NewManager(enabledClient(t), q, pool, nil)
+ m.mergeDelays = []time.Duration{time.Millisecond, 2 * time.Millisecond}
+ queued := func() []int32 {
+ t.Helper()
+ var got []int32
+ for {
+ select {
+ case addr := <-m.queue:
+ if addr.InstallationID == installationID && addr.Repo == repo {
+ got = append(got, addr.Number)
+ }
+ default:
+ m.mu.Lock()
+ m.active = map[address]bool{}
+ m.mu.Unlock()
+ return got
+ }
+ }
+ }
+ m.RefreshConflictWatchers(ctx, installationID, "o", repo, 2)
+ time.Sleep(50 * time.Millisecond)
+ if got := queued(); fmt.Sprint(got) != "[1 3]" && fmt.Sprint(got) != "[3 1]" {
+ t.Fatalf("merge refreshed %v, want PRs 1 and 3 once each", got)
+ }
+ m.sweepOnce(ctx)
+ if got := queued(); fmt.Sprint(got) != "[1 2]" && fmt.Sprint(got) != "[2 1]" {
+ t.Fatalf("sweep refreshed %v, want stale watched PRs 1 and 2", got)
+ }
+}
+
// TestApplySnapshotHeadSHAGuard is the acceptance-criterion-1 regression: a slow
// response for an old head must never overwrite a newer head's snapshot.
func TestApplySnapshotHeadSHAGuard(t *testing.T) {
diff --git a/server/internal/service/builtin_skills/multica-platform/references/issues.md b/server/internal/service/builtin_skills/multica-platform/references/issues.md
index ca35f98444..bcc61558b4 100644
--- a/server/internal/service/builtin_skills/multica-platform/references/issues.md
+++ b/server/internal/service/builtin_skills/multica-platform/references/issues.md
@@ -434,19 +434,20 @@ current run. A wakeup persists on the issue; it is not a sleeping process.
- `wakeup events` lists supported business facts. These work with plugins disabled.
- `wakeup create <issue> --agent-id <target> --kind event --event task.completed,task.failed,task.cancelled --task-id <run> --instruction-file ./instruction.md` wakes once. Omit `--agent-id` only when acting as the authenticated agent. A specific run must belong to this issue; if already terminal, registration captures its matching state immediately.
- For a continuing subscription use `--mode continuous`. For task events, use `--filter-agent-id` to match that agent's future runs; this does not replay historical runs. For comment/issue/reaction/attachment changes, use `--filter-actor-type member|agent --filter-actor-id <user-or-agent-id>` to match the actual author/editor. Mutation-only `--filter-agent-id` remains a legacy alias for actor=agent; do not combine it with actor flags.
-- A condition lets the platform check a stored fact itself and wake the target only when it holds. Pass exactly one `--until-*` flag and no `--event`, `--task-id` or actor/agent filter; the rule stays `kind=event`. The platform checks about every 30 seconds, so a condition that already holds fires on the next check, except `--until-pr checks`, which ignores results that finished before registration. A condition wakes once by default. With `--mode continuous` it fires again only after the predicate turns false or the facts behind it change (a new check result or PR head, another linked PR merging, the number of sub-issues changing).
+- A condition lets the platform check a stored fact itself and wake the target only when it holds. Pass exactly one `--until-*` flag and no `--event`, `--task-id` or actor/agent filter; the rule stays `kind=event`. The platform checks about every 30 seconds, so a condition that already holds fires on the next check, except `--until-pr checks`, which ignores results that finished before registration. A condition wakes once by default. With `--mode continuous` it fires again only after the predicate turns false or the facts behind it change (a new check result or PR head, another linked PR merging, a resolved conflict coming back, the number of sub-issues changing).
```bash
multica issue wakeup create <issue> --until-status in_review --instruction-file ./instruction.md
multica issue wakeup create <issue> --until-pr checks --expires-in 2h --on-timeout wake --instruction-file ./instruction.md
multica issue wakeup create <issue> --until-pr merged --instruction-file ./instruction.md
+multica issue wakeup create <issue> --until-pr conflicts --mode continuous --instruction-file ./instruction.md
multica issue wakeup create <issue> --until-children-done --instruction-file ./instruction.md
multica issue wakeup create <issue> --until-children-done --stage 2 --instruction-file ./instruction.md
multica issue wakeup create <issue> --until-issue <other-issue-id> --until-issue-state done --instruction-file ./instruction.md
```
- `--until-status KEY` — this issue's status is that key (built-in or one of the workspace's statuses).
-- `--until-pr checks` — a linked pull request's checks finished, passing or failing, on its current head. `--until-pr merged` — a linked pull request merged. With several linked pull requests, any one satisfies it. Both conditions inspect only PRs linked directly to this issue; they do not inherit a parent issue's PRs. Check evaluation also requires server-side GitHub snapshots. A missing link or snapshot is recorded in the rule's `last_error` and retried automatically rather than rejecting the rule.
+- `--until-pr checks` — a linked pull request's checks finished, passing or failing, on its current head. `--until-pr merged` — a linked pull request merged. `--until-pr conflicts` — an open linked GitHub pull request has merge conflicts on its current head, for example after another PR merged into its base; with `--mode continuous` it fires again each time a resolved conflict comes back or a new head is still conflicting. With several linked pull requests, any one satisfies it. These conditions inspect only PRs linked directly to this issue; they do not inherit a parent issue's PRs. Checks and conflicts also require server-side GitHub snapshots; conflicts are not detected on Forgejo, Gitea or GitLab pull requests. A missing link or snapshot is recorded in the rule's `last_error` and retried automatically rather than rejecting the rule.
- `--until-children-done` — every sub-issue, staged or not, is closed (`done` or `cancelled`). With `--stage N` it waits only for staged sub-issues up to stage N, and stage N must have at least one. A parent with no sub-issues never fires. The parent's assignee already gets the sub-issue wakeup described under Stages; do not add this condition for the same wake.
- `--until-issue ISSUE` — another issue in this workspace (identifier or UUID) reaches `--until-issue-state`: `done` (default), `ended` (done or cancelled), or `in_review`.
- The same form also accepts `--until-assignee member|agent|squad:ID`, `--until-label LABEL_ID`, and `--until-property PROPERTY_ID=VALUE` (VALUE may be JSON). `multica issue wakeup create --help` lists them.
@@ -464,7 +465,7 @@ multica issue wakeup create <issue> --until-issue <other-issue-id> --until-issue
Read current state with issue get, comment list, and run inspection before
judging business completion. Wait for a linked pull request with `--until-pr`
-(`checks` or `merged`) rather than polling it from a timer. There is no separate
+(`checks`, `merged` or `conflicts`) rather than polling it from a timer. There is no separate
CI event; when the woken run needs check details or logs, use the existing
GitHub tools. A failed run does not imply its business goal is complete.
Automatic retry chains are not followed by event filters; subscribe to a new run
diff --git a/server/internal/service/issue_wakeup_condition.go b/server/internal/service/issue_wakeup_condition.go
index 6bd07efe22..8a413c2d75 100644
--- a/server/internal/service/issue_wakeup_condition.go
+++ b/server/internal/service/issue_wakeup_condition.go
@@ -47,7 +47,7 @@ type WakeupCondition struct {
// every stage closing while a later one waits, then every sub-issue
// closing. Only the platform sets it.
EachStage bool `json:"each_stage,omitempty"`
- // pull_request: checks_finished | merged
+ // pull_request: checks_finished | merged | conflicts
Event string `json:"event,omitempty"`
// other_issue: the watched issue and done | ended | in_review. The
// identifier is recorded for display; clients never set it.
@@ -64,10 +64,11 @@ var (
errPRSnapshotsUnavailable = errors.New("PR checks cannot be evaluated: GitHub snapshot refresh is unavailable on this server; ask the server administrator to configure the GitHub App snapshot client")
errPRNotLinked = errors.New("No pull request is linked to this issue; link the PR to this issue (a parent issue's PR is not included), or wait for the linking webhook")
errPRSnapshotPending = errors.New("PR check snapshot is not available yet; inspect this issue's pull-requests snapshot_available field and ask the server administrator to check snapshot refresh if it persists")
+ errPRConflictsUnsupported = errors.New("Merge conflicts can only be detected on GitHub pull requests; this issue links only self-hosted (Forgejo/Gitea/GitLab) pull requests")
)
func conditionDiagnostic(err error) bool {
- return errors.Is(err, errPRSnapshotsUnavailable) || errors.Is(err, errPRNotLinked) || errors.Is(err, errPRSnapshotPending)
+ return errors.Is(err, errPRSnapshotsUnavailable) || errors.Is(err, errPRNotLinked) || errors.Is(err, errPRSnapshotPending) || errors.Is(err, errPRConflictsUnsupported)
}
func badCondition(msg string) error {
@@ -186,8 +187,8 @@ func validateCondition(ctx context.Context, tx pgx.Tx, issue db.Issue, raw json.
}
out = WakeupCondition{Type: c.Type, Stage: c.Stage}
case "pull_request":
- if c.Event != "checks_finished" && c.Event != "merged" {
- return nil, nil, badCondition("event must be checks_finished or merged")
+ if c.Event != "checks_finished" && c.Event != "merged" && c.Event != "conflicts" {
+ return nil, nil, badCondition("event must be checks_finished, merged or conflicts")
}
out = WakeupCondition{Type: c.Type, Event: c.Event}
case "other_issue":
@@ -260,10 +261,14 @@ func (s *IssueWakeupService) evaluateCondition(ctx context.Context, tx pgx.Tx, q
return met, fingerprint, observed, nil
case "pull_request":
// Without the snapshot client GitHub rows are never refreshed, so their
- // checks neither satisfy nor stall the rule. Self-hosted VCS rows carry
+ // checks and mergeability neither satisfy nor stall the rule. Self-hosted VCS rows carry
// their own commit statuses and are evaluated regardless (#9034).
- githubChecks := c.Event != "checks_finished" || (s.Tasks != nil && s.Tasks.PRSnapshotsEnabled)
- rows, err := tx.Query(ctx, `SELECT pr.pr_number,pr.state,COALESCE(pr.snapshot_head_sha,''),COALESCE(pr.checks_rollup_state,'')
+ githubChecks := c.Event == "merged" || (s.Tasks != nil && s.Tasks.PRSnapshotsEnabled)
+ // GitHub reports UNKNOWN while it recomputes mergeability (after any
+ // base-branch move). On the same head that keeps the previous verdict,
+ // so a recompute does not read as resolved-then-conflicting again.
+ previous := prConditionKeys(w.ConditionState)
+ rows, err := tx.Query(ctx, `SELECT pr.pr_number,pr.state,COALESCE(pr.snapshot_head_sha,''),COALESCE(pr.checks_rollup_state,''),pr.head_sha,COALESCE(pr.api_mergeable,''),pr.id::text
FROM github_pull_request pr JOIN issue_pull_request ipr ON ipr.pull_request_id=pr.id WHERE ipr.issue_id=$1`, w.IssueID)
if err != nil {
return false, "", nil, err
@@ -273,8 +278,8 @@ func (s *IssueWakeupService) evaluateCondition(ctx context.Context, tx pgx.Tx, q
var prs []map[string]any
for rows.Next() {
var number int32
- var state, head, checks string
- if err = rows.Scan(&number, &state, &head, &checks); err != nil {
+ var state, head, checks, currentHead, mergeable, id string
+ if err = rows.Scan(&number, &state, &head, &checks, &currentHead, &mergeable, &id); err != nil {
rows.Close()
return false, "", nil, err
}
@@ -294,6 +299,21 @@ func (s *IssueWakeupService) evaluateCondition(ctx context.Context, tx pgx.Tx, q
keys = append(keys, fmt.Sprintf("%d@%s:%s", number, head, checks))
prs = append(prs, map[string]any{"number": number, "head_sha": head, "checks": strings.ToLower(checks)})
}
+ case "conflicts":
+ if !githubChecks || (state != "open" && state != "draft") {
+ continue
+ }
+ // A verdict for an older head says nothing about the pushed one.
+ if head == "" || head != currentHead {
+ missingSnapshot = true
+ continue
+ }
+ // PR numbers and heads can repeat across repositories (forks).
+ key := fmt.Sprintf("%s@%s:conflicting", id, head)
+ if mergeable == "CONFLICTING" || ((mergeable == "UNKNOWN" || mergeable == "") && previous[key] > 0) {
+ keys = append(keys, key)
+ prs = append(prs, map[string]any{"number": number, "head_sha": head, "mergeable": "conflicting"})
+ }
}
}
rows.Close()
@@ -363,7 +383,10 @@ func (s *IssueWakeupService) evaluateCondition(ctx context.Context, tx pgx.Tx, q
if linked == 0 && vcsLinked == 0 {
return false, "", nil, errPRNotLinked
}
- if c.Event == "checks_finished" && missingSnapshot {
+ if c.Event == "conflicts" && linked == 0 {
+ return false, "", nil, errPRConflictsUnsupported
+ }
+ if c.Event != "merged" && missingSnapshot {
return false, "", nil, errPRSnapshotPending
}
}
@@ -464,18 +487,50 @@ func (s *IssueWakeupService) pollCondition(ctx context.Context, tx pgx.Tx, q *db
// condition_state dedups a satisfied predicate; each new satisfaction
// gets its own receipt key.
state := w.ConditionState
- if met && fingerprint != state {
- if err = recordConditionMet(ctx, q, w, observed, causes, now); err != nil {
- return w.NextFireAt, err
+ if met {
+ if conditionNewlyMet(state, fingerprint) {
+ if err = recordConditionMet(ctx, q, w, observed, causes, now); err != nil {
+ return w.NextFireAt, err
+ }
}
state = fingerprint
- } else if !met {
+ } else {
state = ""
}
next := pgtype.Timestamptz{Time: now.Add(conditionPollInterval), Valid: true}
return next, q.SetWakeupConditionState(ctx, db.SetWakeupConditionStateParams{ID: w.ID, ConditionState: state, NextFireAt: next})
}
+// prConditionKeys counts the per-PR keys of a linked-PR fingerprint. Checks
+// and merged keys carry only the PR number, so two satisfying PRs from
+// different repositories can share a key; the count keeps both.
+func prConditionKeys(fingerprint string) map[string]int {
+ keys := map[string]int{}
+ if rest, ok := strings.CutPrefix(fingerprint, "pr:"); ok && rest != "" {
+ for _, key := range strings.Split(rest, ",") {
+ keys[key]++
+ }
+ }
+ return keys
+}
+
+// conditionNewlyMet reports whether a satisfied predicate is news to the rule.
+// A linked-PR fingerprint holds one key per satisfying PR, and only a key that
+// occurs more often than the rule has seen is news: one PR leaving the set
+// (resolved, closed, unlinked) must not wake the agent again for the others.
+func conditionNewlyMet(previous, current string) bool {
+ if !strings.HasPrefix(current, "pr:") {
+ return current != previous
+ }
+ seen := prConditionKeys(previous)
+ for key, n := range prConditionKeys(current) {
+ if n > seen[key] {
+ return true
+ }
+ }
+ return false
+}
+
// conditionFiresOnChange reports whether facts already true at registration
// are ignored. Finished checks usually belong to the head the agent just
// replaced, so a checks condition waits for a newer result; states such as a
diff --git a/server/internal/service/issue_wakeup_condition_pr_test.go b/server/internal/service/issue_wakeup_condition_pr_test.go
index 7e1b4e1815..20b30ec4ad 100644
--- a/server/internal/service/issue_wakeup_condition_pr_test.go
+++ b/server/internal/service/issue_wakeup_condition_pr_test.go
@@ -57,7 +57,12 @@ func (tx *prConditionTx) Exec(_ context.Context, sql string, args ...any) (pgcon
}
func TestWakeupConditionPREvaluation(t *testing.T) {
- row := func(state, head, checks string) []any { return []any{int32(1), state, head, checks} }
+ row := func(state, head, checks string) []any { return []any{int32(1), state, head, checks, head, "", "p1"} }
+ // conflictRow describes a PR whose snapshot was fetched for snapshotHead
+ // while the PR's current head is "head".
+ conflictRow := func(state, snapshotHead, mergeable string) []any {
+ return []any{int32(1), state, snapshotHead, "", "head", mergeable, "p1"}
+ }
for _, tc := range []struct {
name, event string
available bool
@@ -77,6 +82,17 @@ func TestWakeupConditionPREvaluation(t *testing.T) {
{"one matching PR", "checks_finished", true, [][]any{row("open", "", ""), row("open", "head", "SUCCESS")}, nil, true},
{"merge without snapshots", "merged", false, [][]any{row("merged", "", "")}, nil, true},
{"open without snapshots", "merged", false, [][]any{row("open", "", "")}, nil, false},
+ {"conflicts unconfigured", "conflicts", false, [][]any{conflictRow("open", "head", "CONFLICTING")}, errPRSnapshotsUnavailable, false},
+ {"conflicts unlinked", "conflicts", true, nil, errPRNotLinked, false},
+ {"conflicts no snapshot", "conflicts", true, [][]any{conflictRow("open", "", "")}, errPRSnapshotPending, false},
+ {"conflicts verdict for an older head", "conflicts", true, [][]any{conflictRow("open", "old", "CONFLICTING")}, errPRSnapshotPending, false},
+ {"mergeable", "conflicts", true, [][]any{conflictRow("open", "head", "MERGEABLE")}, nil, false},
+ {"mergeability unknown", "conflicts", true, [][]any{conflictRow("open", "head", "UNKNOWN")}, nil, false},
+ {"conflicting", "conflicts", true, [][]any{conflictRow("open", "head", "CONFLICTING")}, nil, true},
+ {"conflicting draft", "conflicts", true, [][]any{conflictRow("draft", "head", "CONFLICTING")}, nil, true},
+ {"conflicting but closed", "conflicts", true, [][]any{conflictRow("closed", "head", "CONFLICTING")}, nil, false},
+ {"conflicting but merged", "conflicts", true, [][]any{conflictRow("merged", "head", "CONFLICTING")}, nil, false},
+ {"one conflicting PR", "conflicts", true, [][]any{conflictRow("open", "old", "MERGEABLE"), conflictRow("open", "head", "CONFLICTING")}, nil, true},
} {
t.Run(tc.name, func(t *testing.T) {
s := &IssueWakeupService{Tasks: &TaskService{PRSnapshotsEnabled: tc.available}}
@@ -93,6 +109,65 @@ func TestWakeupConditionPREvaluation(t *testing.T) {
}
}
+func TestConditionNewlyMet(t *testing.T) {
+ for _, tc := range []struct {
+ previous, current string
+ want bool
+ }{
+ {"", "pr:a@1:conflicting", true},
+ {"pr:a@1:conflicting", "pr:a@1:conflicting", false},
+ {"pr:a@1:conflicting,b@1:conflicting", "pr:b@1:conflicting", false},
+ {"pr:b@1:conflicting", "pr:a@1:conflicting,b@1:conflicting", true},
+ {"pr:a@1:conflicting", "pr:a@2:conflicting", true},
+ {"pr:1@h:SUCCESS,2@h:FAILURE", "pr:2@h:FAILURE", false},
+ // Number-only keys repeat across repositories; a second one is news.
+ {"pr:7", "pr:7,7", true},
+ {"pr:7,7", "pr:7", false},
+ {"pr:7,7", "pr:7,7", false},
+ {"status:todo", "status:in_review", true},
+ {"status:in_review", "status:in_review", false},
+ {`property:{"a":1,"b":2}`, `property:{"a":1,"b":2}`, false},
+ {"children:2", "children:3", true},
+ } {
+ if got := conditionNewlyMet(tc.previous, tc.current); got != tc.want {
+ t.Errorf("conditionNewlyMet(%q, %q) = %t, want %t", tc.previous, tc.current, got, tc.want)
+ }
+ }
+}
+
+func TestWakeupConditionPRConflictsAcrossRecompute(t *testing.T) {
+ ctx := context.Background()
+ s := &IssueWakeupService{Tasks: &TaskService{PRSnapshotsEnabled: true}}
+ w := db.IssueWakeup{ID: dbid.NewV7(), IssueID: dbid.NewV7(), Condition: condition(t, map[string]any{"type": "pull_request", "event": "conflicts"})}
+ tx := &prConditionTx{issue: w.IssueID}
+ q := db.New(tx)
+ snapshot := func(head, mergeable string) [][]any {
+ return [][]any{{int32(1), "open", head, "", head, mergeable, "p1"}}
+ }
+ for _, step := range []struct {
+ name, previous string
+ prs [][]any
+ wantMet bool
+ wantState string
+ }{
+ {"conflict", "", snapshot("a", "CONFLICTING"), true, "pr:p1@a:conflicting"},
+ {"recompute on the same head keeps it", "pr:p1@a:conflicting", snapshot("a", "UNKNOWN"), true, "pr:p1@a:conflicting"},
+ {"resolved", "pr:p1@a:conflicting", snapshot("a", "MERGEABLE"), false, ""},
+ {"recompute after resolving stays resolved", "", snapshot("a", "UNKNOWN"), false, ""},
+ {"recompute on a new head starts over", "pr:p1@a:conflicting", snapshot("b", "UNKNOWN"), false, ""},
+ {"new head still conflicting", "pr:p1@a:conflicting", snapshot("b", "CONFLICTING"), true, "pr:p1@b:conflicting"},
+ } {
+ t.Run(step.name, func(t *testing.T) {
+ tx.prs = step.prs
+ w.ConditionState = step.previous
+ met, fingerprint, _, err := s.evaluateCondition(ctx, tx, q, w)
+ if err != nil || met != step.wantMet || (met && fingerprint != step.wantState) {
+ t.Fatalf("met=%t fingerprint=%q err=%v; want met=%t fingerprint=%q", met, fingerprint, err, step.wantMet, step.wantState)
+ }
+ })
+ }
+}
+
func TestWakeupConditionPRDiagnosticPolling(t *testing.T) {
ctx := context.Background()
s := &IssueWakeupService{Tasks: &TaskService{}}
@@ -114,8 +189,8 @@ func TestWakeupConditionPRDiagnosticPolling(t *testing.T) {
want error
}{
{nil, errPRNotLinked},
- {[][]any{{int32(1), "open", "", ""}}, errPRSnapshotPending},
- {[][]any{{int32(1), "open", "head", "PENDING"}}, nil},
+ {[][]any{{int32(1), "open", "", "", "head", "", "p1"}}, errPRSnapshotPending},
+ {[][]any{{int32(1), "open", "head", "PENDING", "head", "MERGEABLE", "p1"}}, nil},
} {
tx.prs = step.prs
w.LastError = tx.lastError
diff --git a/server/internal/service/issue_wakeup_condition_test.go b/server/internal/service/issue_wakeup_condition_test.go
index bb404b1b0d..f0947347ce 100644
--- a/server/internal/service/issue_wakeup_condition_test.go
+++ b/server/internal/service/issue_wakeup_condition_test.go
@@ -186,6 +186,168 @@ func TestWakeupConditionRepeatsOnlyWhenItBecomesTrueAgain(t *testing.T) {
}
}
+func TestWakeupConditionPRConflictsWakesOnEachNewConflict(t *testing.T) {
+ f, s, issue, agent := conditionFixture(t)
+ s.Tasks.PRSnapshotsEnabled = true
+ pr := f.Insert(t, "github_pull_request", testutil.Cols{
+ "workspace_id": f.WorkspaceID, "installation_id": 1,
+ "repo_owner": "fixture", "repo_name": "conflicts", "pr_number": 7,
+ "title": "PR", "state": "open", "html_url": "https://example.test/pr/7",
+ "pr_created_at": "2026-01-01T00:00:00Z", "pr_updated_at": "2026-01-01T00:00:00Z",
+ "head_sha": "a", "snapshot_head_sha": "a", "api_mergeable": "MERGEABLE",
+ })
+ f.Cleanup(t, "DELETE FROM issue_pull_request WHERE pull_request_id=$1", pr)
+ f.Exec(t, "INSERT INTO issue_pull_request(issue_id,pull_request_id) VALUES($1,$2)", issue, pr)
+ w := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "event", Mode: "continuous", Instruction: "Resolve the conflict",
+ Condition: condition(t, map[string]any{"type": "pull_request", "event": "conflicts"})})
+ finishRuns := func() {
+ f.Exec(t, "UPDATE agent_task_queue SET status='completed',completed_at=now() WHERE context->>'wakeup_id'=$1 AND status<>'completed'", util.UUIDToString(w.ID))
+ }
+ snapshot := func(head, snapshotHead, mergeable string) db.IssueWakeup {
+ t.Helper()
+ f.Exec(t, "UPDATE github_pull_request SET head_sha=$2,snapshot_head_sha=$3,api_mergeable=$4 WHERE id=$1", pr, head, snapshotHead, mergeable)
+ return wakeTick(t, f, s, w.ID)
+ }
+ expectRuns := func(want int, step string) {
+ t.Helper()
+ if n := wakeRuns(t, f, w.ID); n != want {
+ t.Fatalf("%s: %d runs, want %d", step, n, want)
+ }
+ }
+
+ snapshot("a", "a", "MERGEABLE")
+ expectRuns(0, "mergeable")
+ got := snapshot("a", "a", "CONFLICTING")
+ expectRuns(1, "conflict")
+ task, err := f.q.GetAgentTask(context.Background(), got.LastTaskID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !strings.Contains(task.HandoffNote.String, `"mergeable":"conflicting"`) || !strings.Contains(task.HandoffNote.String, `"head_sha":"a"`) {
+ t.Fatalf("conflict facts missing from the run: %s", task.HandoffNote.String)
+ }
+ finishRuns()
+ // GitHub recomputing after another base move is not a new conflict.
+ snapshot("a", "a", "UNKNOWN")
+ snapshot("a", "a", "CONFLICTING")
+ expectRuns(1, "recompute")
+ // The agent pushed a fix; until the new head is fetched the old verdict
+ // does not count, and the pending snapshot is visible on the rule.
+ got = snapshot("b", "a", "CONFLICTING")
+ expectRuns(1, "pushed head awaiting a snapshot")
+ if !got.LastError.Valid || got.LastError.String != conditionDiagnosticPrefix+errPRSnapshotPending.Error() {
+ t.Fatalf("pending snapshot diagnostic = %+v", got.LastError)
+ }
+ snapshot("b", "b", "MERGEABLE")
+ expectRuns(1, "resolved")
+ got = snapshot("b", "b", "CONFLICTING")
+ expectRuns(2, "conflict again")
+ if !got.Enabled || got.FireCount != 2 || got.LastError.Valid {
+ t.Fatalf("continuous rule after two conflicts: enabled=%t fire_count=%d error=%+v", got.Enabled, got.FireCount, got.LastError)
+ }
+ finishRuns()
+ f.Exec(t, "UPDATE github_pull_request SET state='merged' WHERE id=$1", pr)
+ wakeTick(t, f, s, w.ID)
+ expectRuns(2, "merged PR")
+}
+
+func TestWakeupConditionPRConflictsAcrossSeveralPRs(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ sameNumber bool
+ wantRuns int
+ }{
+ {"resolving one PR does not re-wake for the other", false, 1},
+ {"PRs in different repositories keep distinct identities", true, 2},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ f, s, issue, agent := conditionFixture(t)
+ s.Tasks.PRSnapshotsEnabled = true
+ insertPR := func(repo string, number int, mergeable string) string {
+ pr := f.Insert(t, "github_pull_request", testutil.Cols{
+ "workspace_id": f.WorkspaceID, "installation_id": 1,
+ "repo_owner": "fixture", "repo_name": repo, "pr_number": number,
+ "title": "PR", "state": "open", "html_url": "https://example.test/" + repo,
+ "pr_created_at": "2026-01-01T00:00:00Z", "pr_updated_at": "2026-01-01T00:00:00Z",
+ "head_sha": "shared-head", "snapshot_head_sha": "shared-head", "api_mergeable": mergeable,
+ })
+ f.Cleanup(t, "DELETE FROM issue_pull_request WHERE pull_request_id=$1", pr)
+ f.Exec(t, "INSERT INTO issue_pull_request(issue_id,pull_request_id) VALUES($1,$2)", issue, pr)
+ return pr
+ }
+ a := insertPR("repo-a", 1, "CONFLICTING")
+ bNumber, bMergeable := 2, "CONFLICTING"
+ if tc.sameNumber {
+ // A fork's PR can share both the number and the head commit.
+ bNumber, bMergeable = 1, "MERGEABLE"
+ }
+ b := insertPR("repo-b", bNumber, bMergeable)
+ w := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "event", Mode: "continuous", Instruction: "Resolve conflicts",
+ Condition: condition(t, map[string]any{"type": "pull_request", "event": "conflicts"})})
+ wakeTick(t, f, s, w.ID)
+ if n := wakeRuns(t, f, w.ID); n != 1 {
+ t.Fatalf("initial conflict runs = %d, want 1", n)
+ }
+ f.Exec(t, "UPDATE agent_task_queue SET status='completed',completed_at=now() WHERE context->>'wakeup_id'=$1", util.UUIDToString(w.ID))
+ f.Exec(t, "UPDATE github_pull_request SET api_mergeable='MERGEABLE' WHERE id=$1", a)
+ if tc.sameNumber {
+ f.Exec(t, "UPDATE github_pull_request SET api_mergeable='CONFLICTING' WHERE id=$1", b)
+ }
+ wakeTick(t, f, s, w.ID)
+ if n := wakeRuns(t, f, w.ID); n != tc.wantRuns {
+ t.Fatalf("after the conflict moved runs = %d, want %d", n, tc.wantRuns)
+ }
+ })
+ }
+}
+
+// Checks and merged keys carry only the PR number, so same-numbered PRs from
+// two repositories share a key. The second one satisfying still wakes.
+func TestWakeupConditionPRSharedNumberWakesForEachPR(t *testing.T) {
+ for _, event := range []string{"merged", "checks_finished"} {
+ t.Run(event, func(t *testing.T) {
+ f, s, issue, agent := conditionFixture(t)
+ s.Tasks.PRSnapshotsEnabled = true
+ insertPR := func(repo string) string {
+ pr := f.Insert(t, "github_pull_request", testutil.Cols{
+ "workspace_id": f.WorkspaceID, "installation_id": 1,
+ "repo_owner": "fixture", "repo_name": repo, "pr_number": 7,
+ "title": "PR", "state": "open", "html_url": "https://example.test/" + repo,
+ "pr_created_at": "2026-01-01T00:00:00Z", "pr_updated_at": "2026-01-01T00:00:00Z",
+ "head_sha": "shared-head", "snapshot_head_sha": "shared-head", "checks_rollup_state": "PENDING",
+ })
+ f.Cleanup(t, "DELETE FROM issue_pull_request WHERE pull_request_id=$1", pr)
+ f.Exec(t, "INSERT INTO issue_pull_request(issue_id,pull_request_id) VALUES($1,$2)", issue, pr)
+ return pr
+ }
+ a, b := insertPR("repo-a"), insertPR("repo-b")
+ w := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "event", Mode: "continuous", Instruction: "Follow each pull request",
+ Condition: condition(t, map[string]any{"type": "pull_request", "event": event})})
+ wakeTick(t, f, s, w.ID)
+ if n := wakeRuns(t, f, w.ID); n != 0 {
+ t.Fatalf("before either PR satisfies: %d runs, want 0", n)
+ }
+ satisfy := func(pr string) {
+ if event == "merged" {
+ f.Exec(t, "UPDATE github_pull_request SET state='merged' WHERE id=$1", pr)
+ } else {
+ f.Exec(t, "UPDATE github_pull_request SET checks_rollup_state='SUCCESS' WHERE id=$1", pr)
+ }
+ wakeTick(t, f, s, w.ID)
+ }
+ satisfy(a)
+ if n := wakeRuns(t, f, w.ID); n != 1 {
+ t.Fatalf("after the first PR: %d runs, want 1", n)
+ }
+ f.Exec(t, "UPDATE agent_task_queue SET status='completed',completed_at=now() WHERE context->>'wakeup_id'=$1", util.UUIDToString(w.ID))
+ satisfy(b)
+ if n := wakeRuns(t, f, w.ID); n != 2 {
+ t.Fatalf("after the second PR: %d runs, want 2", n)
+ }
+ })
+ }
+}
+
func TestWakeupConditionChildrenAndOtherIssue(t *testing.T) {
f, s, issue, agent := conditionFixture(t)
first := f.Issue(t, "Stage 1 child", testutil.Cols{"parent_issue_id": issue, "status": "todo", "stage": 1})
diff --git a/server/pkg/db/generated/github_snapshot.sql.go b/server/pkg/db/generated/github_snapshot.sql.go
index 00b74cef8a..bfd9d118bd 100644
--- a/server/pkg/db/generated/github_snapshot.sql.go
+++ b/server/pkg/db/generated/github_snapshot.sql.go
@@ -95,6 +95,56 @@ func (q *Queries) InsertGitHubPRCheckRun(ctx context.Context, arg InsertGitHubPR
return err
}
+const listConflictWatchedGitHubPRNumbersInRepo = `-- name: ListConflictWatchedGitHubPRNumbersInRepo :many
+SELECT DISTINCT pr.pr_number
+FROM issue_wakeup AS w
+JOIN issue_pull_request AS ipr ON ipr.issue_id = w.issue_id
+JOIN github_pull_request AS pr ON pr.id = ipr.pull_request_id
+WHERE w.enabled
+ AND w.condition->>'type' = 'pull_request'
+ AND w.condition->>'event' = 'conflicts'
+ AND pr.installation_id = $1 AND pr.repo_owner = $2 AND pr.repo_name = $3
+ AND pr.state IN ('open', 'draft')
+ AND pr.pr_number <> $4
+ORDER BY pr.pr_number
+LIMIT 200
+`
+
+type ListConflictWatchedGitHubPRNumbersInRepoParams struct {
+ InstallationID int64 `json:"installation_id"`
+ RepoOwner string `json:"repo_owner"`
+ RepoName string `json:"repo_name"`
+ PrNumber int32 `json:"pr_number"`
+}
+
+// Open/draft PRs in one repository that an enabled "wake on merge conflict"
+// rule watches. A merge into the repository can make them conflicting without
+// an event of their own, so the merge webhook re-fetches them.
+func (q *Queries) ListConflictWatchedGitHubPRNumbersInRepo(ctx context.Context, arg ListConflictWatchedGitHubPRNumbersInRepoParams) ([]int32, error) {
+ rows, err := q.db.Query(ctx, listConflictWatchedGitHubPRNumbersInRepo,
+ arg.InstallationID,
+ arg.RepoOwner,
+ arg.RepoName,
+ arg.PrNumber,
+ )
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []int32{}
+ for rows.Next() {
+ var pr_number int32
+ if err := rows.Scan(&pr_number); err != nil {
+ return nil, err
+ }
+ items = append(items, pr_number)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const listGitHubPRNumbersByHeadSHA = `-- name: ListGitHubPRNumbersByHeadSHA :many
SELECT DISTINCT pr_number
FROM github_pull_request
@@ -199,6 +249,92 @@ func (q *Queries) ListGitHubPRRowsByAddress(ctx context.Context, arg ListGitHubP
return items, nil
}
+const listStaleConflictWatchedGitHubPRs = `-- name: ListStaleConflictWatchedGitHubPRs :many
+WITH candidates AS (
+ SELECT pr.installation_id, pr.repo_owner, pr.repo_name, pr.pr_number
+ FROM github_pull_request AS pr
+ WHERE pr.state IN ('open', 'draft')
+ AND (pr.snapshot_fetched_at IS NULL OR pr.snapshot_fetched_at < $6)
+ AND pr.id IN (
+ SELECT ipr.pull_request_id
+ FROM issue_wakeup AS w
+ JOIN issue_pull_request AS ipr ON ipr.issue_id = w.issue_id
+ WHERE w.enabled
+ AND w.condition->>'type' = 'pull_request'
+ AND w.condition->>'event' = 'conflicts'
+ )
+ GROUP BY pr.installation_id, pr.repo_owner, pr.repo_name, pr.pr_number
+)
+SELECT installation_id, repo_owner, repo_name, pr_number
+FROM candidates
+ORDER BY (
+ ROW(installation_id, repo_owner, repo_name, pr_number) >
+ ROW(
+ $1::BIGINT,
+ $2::TEXT,
+ $3::TEXT,
+ $4::INTEGER
+ )
+) DESC,
+installation_id, repo_owner, repo_name, pr_number
+LIMIT $5
+`
+
+type ListStaleConflictWatchedGitHubPRsParams struct {
+ AfterInstallationID int64 `json:"after_installation_id"`
+ AfterRepoOwner string `json:"after_repo_owner"`
+ AfterRepoName string `json:"after_repo_name"`
+ AfterPrNumber int32 `json:"after_pr_number"`
+ MaxRows int32 `json:"max_rows"`
+ OlderThan pgtype.Timestamptz `json:"older_than"`
+}
+
+type ListStaleConflictWatchedGitHubPRsRow struct {
+ InstallationID int64 `json:"installation_id"`
+ RepoOwner string `json:"repo_owner"`
+ RepoName string `json:"repo_name"`
+ PrNumber int32 `json:"pr_number"`
+}
+
+// Second sweep source: open/draft PRs linked to an issue with an enabled
+// "wake on merge conflict" rule. A decided snapshot leaves the undecided sweep,
+// but a base-branch move can turn it conflicting without any event for this
+// PR, so watched PRs are re-fetched on the TTL regardless. The candidate set
+// comes from the enabled rules, whose count is capped. Like the undecided
+// sweep, an address cursor rotates the bounded batch, so addresses whose
+// fetches keep failing (their snapshot never gets newer) cannot pin it.
+func (q *Queries) ListStaleConflictWatchedGitHubPRs(ctx context.Context, arg ListStaleConflictWatchedGitHubPRsParams) ([]ListStaleConflictWatchedGitHubPRsRow, error) {
+ rows, err := q.db.Query(ctx, listStaleConflictWatchedGitHubPRs,
+ arg.AfterInstallationID,
+ arg.AfterRepoOwner,
+ arg.AfterRepoName,
+ arg.AfterPrNumber,
+ arg.MaxRows,
+ arg.OlderThan,
+ )
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []ListStaleConflictWatchedGitHubPRsRow{}
+ for rows.Next() {
+ var i ListStaleConflictWatchedGitHubPRsRow
+ if err := rows.Scan(
+ &i.InstallationID,
+ &i.RepoOwner,
+ &i.RepoName,
+ &i.PrNumber,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const listStaleUndecidedGitHubPRs = `-- name: ListStaleUndecidedGitHubPRs :many
WITH candidates AS (
SELECT installation_id, repo_owner, repo_name, pr_number
diff --git a/server/pkg/db/queries/github_snapshot.sql b/server/pkg/db/queries/github_snapshot.sql
index 732d015bb1..94779e92a0 100644
--- a/server/pkg/db/queries/github_snapshot.sql
+++ b/server/pkg/db/queries/github_snapshot.sql
@@ -82,6 +82,60 @@ ORDER BY (
installation_id, repo_owner, repo_name, pr_number
LIMIT sqlc.arg('max_rows');
+-- name: ListStaleConflictWatchedGitHubPRs :many
+-- Second sweep source: open/draft PRs linked to an issue with an enabled
+-- "wake on merge conflict" rule. A decided snapshot leaves the undecided sweep,
+-- but a base-branch move can turn it conflicting without any event for this
+-- PR, so watched PRs are re-fetched on the TTL regardless. The candidate set
+-- comes from the enabled rules, whose count is capped. Like the undecided
+-- sweep, an address cursor rotates the bounded batch, so addresses whose
+-- fetches keep failing (their snapshot never gets newer) cannot pin it.
+WITH candidates AS (
+ SELECT pr.installation_id, pr.repo_owner, pr.repo_name, pr.pr_number
+ FROM github_pull_request AS pr
+ WHERE pr.state IN ('open', 'draft')
+ AND (pr.snapshot_fetched_at IS NULL OR pr.snapshot_fetched_at < sqlc.arg('older_than'))
+ AND pr.id IN (
+ SELECT ipr.pull_request_id
+ FROM issue_wakeup AS w
+ JOIN issue_pull_request AS ipr ON ipr.issue_id = w.issue_id
+ WHERE w.enabled
+ AND w.condition->>'type' = 'pull_request'
+ AND w.condition->>'event' = 'conflicts'
+ )
+ GROUP BY pr.installation_id, pr.repo_owner, pr.repo_name, pr.pr_number
+)
+SELECT installation_id, repo_owner, repo_name, pr_number
+FROM candidates
+ORDER BY (
+ ROW(installation_id, repo_owner, repo_name, pr_number) >
+ ROW(
+ sqlc.arg('after_installation_id')::BIGINT,
+ sqlc.arg('after_repo_owner')::TEXT,
+ sqlc.arg('after_repo_name')::TEXT,
+ sqlc.arg('after_pr_number')::INTEGER
+ )
+) DESC,
+installation_id, repo_owner, repo_name, pr_number
+LIMIT sqlc.arg('max_rows');
+
+-- name: ListConflictWatchedGitHubPRNumbersInRepo :many
+-- Open/draft PRs in one repository that an enabled "wake on merge conflict"
+-- rule watches. A merge into the repository can make them conflicting without
+-- an event of their own, so the merge webhook re-fetches them.
+SELECT DISTINCT pr.pr_number
+FROM issue_wakeup AS w
+JOIN issue_pull_request AS ipr ON ipr.issue_id = w.issue_id
+JOIN github_pull_request AS pr ON pr.id = ipr.pull_request_id
+WHERE w.enabled
+ AND w.condition->>'type' = 'pull_request'
+ AND w.condition->>'event' = 'conflicts'
+ AND pr.installation_id = $1 AND pr.repo_owner = $2 AND pr.repo_name = $3
+ AND pr.state IN ('open', 'draft')
+ AND pr.pr_number <> $4
+ORDER BY pr.pr_number
+LIMIT 200;
+
-- name: ListGitHubPRNumbersByHeadSHA :many
-- Resolves a commit SHA to the PR numbers whose head it is. `status` webhook
-- events (legacy commit statuses) carry a SHA + repo but no PR number, so we