Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(wakeup): prevent duplicate stage handoffs (MUL-9643) (#10977)
Bohan Jiangee5de54e0002
diff --git a/apps/docs/content/docs/issue-wakeups.fr.mdx b/apps/docs/content/docs/issue-wakeups.fr.mdxindex a4550be7ad..3c7577fab4 100644--- a/apps/docs/content/docs/issue-wakeups.fr.mdx+++ b/apps/docs/content/docs/issue-wakeups.fr.mdx@@ -106,6 +106,7 @@ Pour voir tous les réveils de l'espace de travail, ouvrez **Automatisation** etQuand une tâche a des sous-tâches, sa section Réveils affiche une règle marquée **Système**. Personne n'a besoin de la créer :- Quand toutes les sous-tâches d'une étape sont closes alors qu'une étape suivante attend, elle réveille l'assigné du parent, puis une fois encore quand toutes les sous-tâches sont closes. Des sous-tâches sans étape réveillent le parent une fois, à la clôture de la dernière.+- Ajouter ou rouvrir une sous-tâche ne réveille personne, y compris une étape ajoutée après la clôture de toutes les autres : sortez-la de `backlog` pour la lancer, ou mentionnez l'assigné pour qu'il l'organise.- Un agent assigné est réveillé ; pour un squad, c'est son chef ; un membre assigné reçoit plutôt une notification dans sa boîte de réception. Sans assigné, personne n'est réveillé.- Tant que le parent est en `backlog`, rien n'est réveillé ; le réveil a lieu une fois le parent sorti de `backlog`.- L'instruction par défaut indique à l'agent quelle étape s'est close et laquelle suit : vérifier ses dépendances, puis sortir de `backlog` les sous-tâches de l'étape suivante. Quand tout est clos, il rassemble les résultats sur le parent.diff --git a/apps/docs/content/docs/issue-wakeups.ja.mdx b/apps/docs/content/docs/issue-wakeups.ja.mdxindex 1a69a27f6b..0628b5a401 100644--- a/apps/docs/content/docs/issue-wakeups.ja.mdx+++ b/apps/docs/content/docs/issue-wakeups.ja.mdx@@ -106,6 +106,7 @@ import { WakeupDemo } from "@/components/demos/wakeup-demo";サブタスクがあるタスクでは、ウェイクアップ欄に**システム**の印が付いたルールが表示されます。手で作る必要はありません。- あるステージのサブタスクがすべて閉じ、後ろのステージがまだ待っているときに、親タスクの担当者を起こします。すべてのサブタスクが閉じたときにもう一度起こします。ステージのないサブタスクは、最後の 1 件が閉じたときに一度起こします。+- サブタスクの追加や再オープンでは起こしません。すべて閉じた後に足したステージも同じで、`backlog` から出せば始まります。担当者に段取りを任せたいときはメンションしてください。- 担当者がエージェントならそのエージェントを、スクワッドならリーダーを起こします。メンバーには代わりにインボックスへ通知します。担当者がいなければ誰も起こしません。- 親タスクが `backlog` の間は起こしません。`backlog` を出たときにまとめて一度起こします。- 既定の指示は、どのステージが閉じ、次がどれかをエージェントに伝え、依存関係を確認してから次のステージのサブタスクを `backlog` から出すよう求めます。すべて閉じたときは、結果を親タスクにまとめます。diff --git a/apps/docs/content/docs/issue-wakeups.ko.mdx b/apps/docs/content/docs/issue-wakeups.ko.mdxindex a08f7c6862..1d73eb0c76 100644--- a/apps/docs/content/docs/issue-wakeups.ko.mdx+++ b/apps/docs/content/docs/issue-wakeups.ko.mdx@@ -106,6 +106,7 @@ import { WakeupDemo } from "@/components/demos/wakeup-demo";하위 태스크가 있는 태스크의 깨우기 영역에는 **시스템** 표시가 붙은 규칙이 나타납니다. 따로 만들 필요는 없습니다.- 한 단계의 하위 태스크가 모두 닫히고 뒤 단계가 아직 기다리고 있으면 상위 태스크의 담당자를 깨웁니다. 모든 하위 태스크가 닫히면 한 번 더 깨웁니다. 단계가 없는 하위 태스크는 마지막 하나가 닫힐 때 한 번 깨웁니다.+- 하위 태스크를 추가하거나 다시 열 때는 깨우지 않으며, 모두 닫힌 뒤에 추가한 단계도 마찬가지입니다. `backlog`에서 꺼내면 시작되고, 담당자가 정리해야 하면 멘션하세요.- 담당자가 에이전트면 그 에이전트를, 스쿼드면 리더를 깨웁니다. 멤버에게는 대신 인박스 알림을 보냅니다. 담당자가 없으면 아무도 깨우지 않습니다.- 상위 태스크가 `backlog`에 있는 동안은 깨우지 않고, `backlog`를 벗어나면 한 번 몰아서 깨웁니다.- 기본 지시는 어떤 단계가 닫혔고 다음 단계가 무엇인지 알려 주며, 의존성을 확인한 뒤 다음 단계의 하위 태스크를 `backlog`에서 꺼내라고 합니다. 모두 닫히면 결과를 상위 태스크에 모으게 합니다.diff --git a/apps/docs/content/docs/issue-wakeups.mdx b/apps/docs/content/docs/issue-wakeups.mdxindex d98ac0f208..9f8bb1b0c8 100644--- a/apps/docs/content/docs/issue-wakeups.mdx+++ b/apps/docs/content/docs/issue-wakeups.mdx@@ -122,6 +122,7 @@ To see every wakeup in the workspace, open **Autopilot** and switch to the **IssWhen an issue has sub-issues, its Wakeups section shows a rule marked **System**. Nobody needs to create it:- When every sub-issue in a stage is closed and a later stage is still waiting, it wakes the parent's assignee, and it wakes them once more when every sub-issue is closed. Sub-issues without stages wake the parent once, when the last one closes.+- Adding or reopening a sub-issue does not wake anyone, including a stage added after every sub-issue closed: move it out of `backlog` to start it, or mention the assignee to organize it.- An agent assignee is woken; for a squad, its leader is woken; a member assignee gets an inbox notification instead. Without an assignee, nobody is woken.- While the parent is in `backlog`, nothing is woken; it catches up once the parent leaves `backlog`.- The default instruction tells the agent which stage closed and which comes next: check its dependencies, then move the next stage's sub-issues out of `backlog`. When every sub-issue is closed, it brings their results together on the parent.diff --git a/apps/docs/content/docs/issue-wakeups.zh-Hant.mdx b/apps/docs/content/docs/issue-wakeups.zh-Hant.mdxindex bc168ac48a..bd7d9afd8d 100644--- a/apps/docs/content/docs/issue-wakeups.zh-Hant.mdx+++ b/apps/docs/content/docs/issue-wakeups.zh-Hant.mdx@@ -106,6 +106,7 @@ import { WakeupDemo } from "@/components/demos/wakeup-demo";任務有子任務時,喚醒區域會出現一條帶**系統**標記的規則,它不用手動建立:- 某個階段的子任務全部結束、後面還有階段在等時,喚醒父任務的負責人;全部子任務結束時再喚醒一次。沒有分階段的子任務,全部結束時喚醒一次。+- 新建或重新開啟子任務不會喚醒,全部結束後再補的階段也一樣:把它移出 `backlog` 就會開始,需要負責人安排時 @ 一下。- 負責人是 AI 代理時喚醒它,是小隊時喚醒隊長,是成員時改發收件箱通知;沒有負責人就不喚醒。- 父任務在 `backlog` 時暫不喚醒,移出 `backlog` 後補一次。- 預設指令告訴 AI 代理哪個階段結束了、下一個是哪個:先檢查依賴,再把下一階段的子任務移出 `backlog`;全部結束時把結果彙總到父任務上。diff --git a/apps/docs/content/docs/issue-wakeups.zh.mdx b/apps/docs/content/docs/issue-wakeups.zh.mdxindex bf109f11c2..8eb8323172 100644--- a/apps/docs/content/docs/issue-wakeups.zh.mdx+++ b/apps/docs/content/docs/issue-wakeups.zh.mdx@@ -106,6 +106,7 @@ import { WakeupDemo } from "@/components/demos/wakeup-demo";任务有子任务时,唤醒区域会出现一条带**系统**标记的规则,它不用手动创建:- 某个阶段的子任务全部结束、后面还有阶段在等时,唤醒父任务的负责人;全部子任务结束时再唤醒一次。没有分阶段的子任务,全部结束时唤醒一次。+- 新建或重新打开子任务不会唤醒,全部结束后再补的阶段也一样:把它移出 `backlog` 就会开始,需要负责人安排时 @ 一下。- 负责人是智能体时唤醒它,是小队时唤醒队长,是成员时改发收件箱通知;没有负责人就不唤醒。- 父任务在 `backlog` 时暂不唤醒,移出 `backlog` 后补一次。- 默认指令告诉智能体哪个阶段结束了、下一个是哪个:先检查依赖,再把下一阶段的子任务移出 `backlog`;全部结束时把结果汇总到父任务上。diff --git a/server/internal/handler/issue_child_done_test.go b/server/internal/handler/issue_child_done_test.goindex b540a1324b..a16cd5392b 100644--- a/server/internal/handler/issue_child_done_test.go+++ b/server/internal/handler/issue_child_done_test.go@@ -481,6 +481,98 @@ func TestChildDoneStagesThenWrapUp(t *testing.T) {}}+// Only a sub-issue closing wakes the assignee. Adding the next stage after+// every sub-issue closed, or reopening a later one, closes nothing: the rule+// records the new reading without a run, and the next close wakes as usual+// (GitHub #10960).+func TestChildDoneAddingOrReopeningAStageDoesNotWake(t *testing.T) {+ fx := newChildDoneFixture(t, "in_progress")+ agentID := handlerTestAgentID(t)+ setIssueAssigneeDirect(t, fx.parent.ID, "agent", agentID)+ dbfx.Exec(t, `UPDATE issue SET stage = 1 WHERE id = $1`, fx.child.ID)+ completeRuns := func() {+ dbfx.Exec(t, `UPDATE agent_task_queue SET status = 'completed', completed_at = now() WHERE issue_id = $1`, fx.parent.ID)+ }+ expect := func(step string, n int) {+ t.Helper()+ if entries, runs := childDoneEntries(t, fx.parent.ID), childDoneRuns(t, fx.parent.ID); len(entries) != n || len(runs) != n {+ t.Fatalf("%s: entries = %+v runs = %+v, want %d of each", step, entries, runs, n)+ }+ }++ updateChildStatus(t, fx.child.ID, "done")+ expect("stage 1 closed", 1)+ completeRuns()++ // Creating a sub-issue leaves its change to the scheduler sweep; process+ // it now, as the sweep would, before stage 2 closes.+ next := createStagedChild(t, fx.parent.ID, 2, "todo")+ if err := (&service.IssueWakeupService{Tasks: testHandler.TaskService}).ProcessChildEvents(context.Background(), parseUUID(fx.parent.ID)); err != nil {+ t.Fatal(err)+ }+ expect("stage 2 added", 1)++ updateChildStatus(t, next.ID, "done")+ expect("stage 2 closed", 2)+ completeRuns()++ updateChildStatus(t, next.ID, "in_progress")+ runWakeupTick(t)+ expect("stage 2 reopened", 2)++ updateChildStatus(t, next.ID, "done")+ expect("stage 2 closed again", 3)+}++// A pass that only sees a sub-issue being added can still read a close whose+// change has not reached the rule yet. It must not record that close as seen:+// the close's own pass wakes the assignee.+func TestChildDoneAddedStageKeepsAPendingCloseForItsOwnPass(t *testing.T) {+ ctx := context.Background()+ fx := newChildDoneFixture(t, "in_progress")+ agentID := handlerTestAgentID(t)+ setIssueAssigneeDirect(t, fx.parent.ID, "agent", agentID)+ dbfx.Exec(t, `UPDATE issue SET stage = 1 WHERE id = $1`, fx.child.ID)+ second := createStagedChild(t, fx.parent.ID, 2, "todo")+ updateChildStatus(t, fx.child.ID, "done")+ if runs := childDoneRuns(t, fx.parent.ID); len(runs) != 1 {+ t.Fatalf("stage 1 closed: runs = %+v", runs)+ }+ dbfx.Exec(t, `UPDATE agent_task_queue SET status = 'completed', completed_at = now() WHERE issue_id = $1`, fx.parent.ID)++ // Stage 3 is added and its change is handed to the rule, whose immediate+ // pass cannot take the rule's lock. Stage 2 then closes before the+ // scheduler's pass runs, so that pass sees the addition and the close.+ createStagedChild(t, fx.parent.ID, 3, "backlog")+ lock, err := testPool.Begin(ctx)+ if err != nil {+ t.Fatal(err)+ }+ if _, err = lock.Exec(ctx, `SELECT 1 FROM issue_wakeup WHERE issue_id = $1 AND system_rule = 'child_done' FOR UPDATE`, fx.parent.ID); err != nil {+ t.Fatal(err)+ }+ svc := &service.IssueWakeupService{Tasks: testHandler.TaskService}+ if err = svc.ProcessChildEvents(ctx, parseUUID(fx.parent.ID)); err != nil {+ t.Fatal(err)+ }+ if err = lock.Rollback(ctx); err != nil {+ t.Fatal(err)+ }+ dbfx.Exec(t, `UPDATE issue SET status = 'done' WHERE id = $1`, second.ID)+ runWakeupTick(t)+ if runs := childDoneRuns(t, fx.parent.ID); len(runs) != 1 {+ t.Fatalf("the addition's pass woke the assignee: runs = %+v", runs)+ }++ if err = svc.ProcessChildEvents(ctx, parseUUID(fx.parent.ID)); err != nil {+ t.Fatal(err)+ }+ runs := childDoneRuns(t, fx.parent.ID)+ if len(runs) != 2 || !strings.Contains(runs[1].Note, `"next_stage":3`) {+ t.Fatalf("stage 2 closed: runs = %+v, want a second run naming stage 3", runs)+ }+}+// Another run of the same agent that has not started yet reads the current// sub-issues when it does, so the rule hands it the stage facts when it is// claimed instead of queuing a second run. Claimed by a daemon that cannotdiff --git a/server/internal/service/issue_wakeup.go b/server/internal/service/issue_wakeup.goindex 3a9710f30a..2dadc7ce3e 100644--- a/server/internal/service/issue_wakeup.go+++ b/server/internal/service/issue_wakeup.go@@ -1113,7 +1113,7 @@ func (s *IssueWakeupService) dispatch(ctx context.Context, prev db.IssueWakeup)if next, err = s.pollCondition(ctx, tx, q, w, now); err != nil {return err}- } else if _, _, err = consumeConditionHints(ctx, tx, w.ID); err != nil {+ } else if _, _, _, err = consumeConditionHints(ctx, tx, w.ID); err != nil {return err}}diff --git a/server/internal/service/issue_wakeup_condition.go b/server/internal/service/issue_wakeup_condition.goindex b4f25c7986..820f5316bf 100644--- a/server/internal/service/issue_wakeup_condition.go+++ b/server/internal/service/issue_wakeup_condition.go@@ -429,25 +429,29 @@ const conditionHintSQL = "wakeup_id=$1 AND processed_at IS NULL AND event_type N// consumeConditionHints marks the pending hints processed. It also returns the// agent runs that caused them, or nil when any hint came from elsewhere (a// person, the platform, or several merged events), so a satisfied condition-// can tell whether the target agent brought it about itself.-func consumeConditionHints(ctx context.Context, tx pgx.Tx, id pgtype.UUID) (bool, []string, error) {- rows, err := tx.Query(ctx, "UPDATE issue_wakeup_receipt SET processed_at=now() WHERE "+conditionHintSQL+" RETURNING payload", id)+// can tell whether the target agent brought it about itself. onlyAdded reports+// that every hint was sub-issues being added or reopened, changes that close+// nothing (false when there was no hint).+func consumeConditionHints(ctx context.Context, tx pgx.Tx, id pgtype.UUID) (hinted bool, causes []string, onlyAdded bool, err error) {+ rows, err := tx.Query(ctx, "UPDATE issue_wakeup_receipt SET processed_at=now() WHERE "+conditionHintSQL+" RETURNING event_type,payload", id)if err != nil {- return false, nil, err+ return false, nil, false, err}defer rows.Close()- hinted, complete := false, true- var causes []string+ complete := true+ onlyAdded = truefor rows.Next() {+ var eventType stringvar raw []byte- if err = rows.Scan(&raw); err != nil {- return false, nil, err+ if err = rows.Scan(&eventType, &raw); err != nil {+ return false, nil, false, err}hinted = truevar p struct {SourceTaskID string `json:"source_task_id"`SourceTaskIDs []string `json:"source_task_ids"`Count int64 `json:"coalesced_count"`+ Changes []string `json:"changes"`}_ = json.Unmarshal(raw, &p)switch {@@ -458,21 +462,29 @@ func consumeConditionHints(ctx context.Context, tx pgx.Tx, id pgtype.UUID) (booldefault:complete = false}+ if eventType != childChangeHint || len(p.Changes) == 0 {+ onlyAdded = false+ }+ for _, change := range p.Changes {+ if change != "attached" && change != "reopened" {+ onlyAdded = false+ }+ }}if err = rows.Err(); err != nil {- return false, nil, err+ return false, nil, false, err}if !complete {causes = nil}- return hinted, causes, nil+ return hinted, causes, hinted && onlyAdded, nil}// pollCondition evaluates a condition rule when it is due or a related event// arrived, and returns the next scheduled evaluation. A newly satisfied// predicate becomes one condition.met input for the ordinary dispatch below.func (s *IssueWakeupService) pollCondition(ctx context.Context, tx pgx.Tx, q *db.Queries, w db.IssueWakeup, now time.Time) (pgtype.Timestamptz, error) {- hinted, causes, err := consumeConditionHints(ctx, tx, w.ID)+ hinted, causes, _, err := consumeConditionHints(ctx, tx, w.ID)if err != nil {return w.NextFireAt, err}diff --git a/server/internal/service/issue_wakeup_system.go b/server/internal/service/issue_wakeup_system.goindex 26852df0b2..29545ca609 100644--- a/server/internal/service/issue_wakeup_system.go+++ b/server/internal/service/issue_wakeup_system.go@@ -22,13 +22,14 @@ import (// The child_done system rule wakes a parent's assignee when a stage of its// sub-issues closes while a later stage waits, and once more when every-// sub-issue is closed. It is an ordinary issue_wakeup row with system_rule set:-// the shared condition, receipts, runaway protection, activity and run model-// apply. What differs is owned by the platform: it has no fixed agent or-// creator (the target is the parent's assignee when it fires, a squad's leader-// for a squad, an inbox notification for a member), it cannot be deleted or-// edited by agents, and it is evaluated when sub-issues change instead of on a-// polling schedule.+// sub-issue is closed. Only a sub-issue closing, leaving or changing stage can+// wake; adding or reopening one is recorded without a run. It is an ordinary+// issue_wakeup row with system_rule set: the shared condition, receipts,+// runaway protection, activity and run model apply. What differs is owned by+// the platform: it has no fixed agent or creator (the target is the parent's+// assignee when it fires, a squad's leader for a squad, an inbox notification+// for a member), it cannot be deleted or edited by agents, and it is evaluated+// when sub-issues change instead of on a polling schedule.const (SystemRuleChildDone = "child_done"// MaxSystemWakeupInstruction bounds per-issue and workspace instructions.@@ -383,6 +384,16 @@ func childDoneFacts(receipts []db.IssueWakeupReceipt) map[string]any {return facts}+// closingChangePending reports whether a sub-issue change that can close a+// stage is recorded but has not reached the rule yet: a change not processed,+// or a hint that arrived after this pass took its own.+func closingChangePending(ctx context.Context, tx pgx.Tx, w db.IssueWakeup) (bool, error) {+ var pending bool+ err := tx.QueryRow(ctx, "SELECT EXISTS(SELECT 1 FROM issue_wakeup_receipt WHERE "+conditionHintSQL+") OR "++ "EXISTS(SELECT 1 FROM issue_child_event WHERE parent_id=$2 AND processed_at IS NULL AND kind NOT IN ('attached','reopened'))", w.ID, w.IssueID).Scan(&pending)+ return pending, err+}+// dispatchSystem evaluates a system rule and wakes, notifies or records its// outcome. It mirrors dispatch: the same lock order, receipts, runaway// protection and timeline entries.@@ -466,7 +477,7 @@ func (s *IssueWakeupService) dispatchSystem(ctx context.Context, prev db.IssueWa// A parked parent holds: nothing fires and nothing is marked as seen, so// a stage that closed meanwhile wakes the assignee once it leaves backlog.if issuestatus.Effective(ctx, q, issue.WorkspaceID, issue.Status) == "backlog" {- if _, _, err = consumeConditionHints(ctx, tx, w.ID); err != nil {+ if _, _, _, err = consumeConditionHints(ctx, tx, w.ID); err != nil {return err}return tx.Commit(ctx)@@ -475,7 +486,7 @@ func (s *IssueWakeupService) dispatchSystem(ctx context.Context, prev db.IssueWaif err = tx.QueryRow(ctx, "SELECT now()").Scan(&now); err != nil {return err}- _, causes, err := consumeConditionHints(ctx, tx, w.ID)+ _, causes, onlyAdded, err := consumeConditionHints(ctx, tx, w.ID)if err != nil {return err}@@ -485,6 +496,19 @@ func (s *IssueWakeupService) dispatchSystem(ctx context.Context, prev db.IssueWa}state := w.ConditionStateswitch {+ case met && fingerprint != state && onlyAdded:+ // Adding or reopening sub-issues closed nothing: a next stage added+ // after the last one closed reads as a stage boundary, but the+ // assignee was already woken for that close. Record it as seen; the+ // next close wakes again. A close this pass already reads but whose+ // change is still on its way keeps the state for that change's pass.+ pending, err := closingChangePending(ctx, tx, w)+ if err != nil {+ return err+ }+ if !pending {+ state = fingerprint+ }case met && fingerprint != state:if err = recordConditionMet(ctx, q, w, observed, causes, now); err != nil {return err