Skip to content

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

Go

feat(issues): mention parent assignee in child-done system comment (MUL-2538) (#3065)

Bohan Jiang0bb51ccd0e45
diff --git a/server/internal/handler/github_test.go b/server/internal/handler/github_test.go
index 9d341f3e4e..871e05ed08 100644
--- a/server/internal/handler/github_test.go
+++ b/server/internal/handler/github_test.go
@@ -1468,9 +1468,12 @@ func TestWebhook_MergedPR_ChildWithParent_NotifiesParent(t *testing.T) {
if !strings.Contains(content, child.Identifier) {
t.Errorf("system comment should reference child identifier %q, got: %s", child.Identifier, content)
}
+ // Parent has no assignee in this fixture, so the routing mentions stay
+ // absent. Behavior for assigned parents is covered in
+ // issue_child_done_test.go (MUL-2538 Option C).
for _, banned := range []string{"mention://agent/", "mention://member/", "mention://squad/"} {
if strings.Contains(content, banned) {
- t.Errorf("system comment must not include %q mention, got: %s", banned, content)
+ t.Errorf("system comment must not include %q mention (parent unassigned), got: %s", banned, content)
}
}
}
diff --git a/server/internal/handler/issue_child_done.go b/server/internal/handler/issue_child_done.go
index 90f5f98389..a90f1ef42c 100644
--- a/server/internal/handler/issue_child_done.go
+++ b/server/internal/handler/issue_child_done.go
@@ -5,6 +5,7 @@ import (
"fmt"
"log/slog"
"strconv"
+ "strings"
"github.com/jackc/pgx/v5/pgtype"
db "github.com/multica-ai/multica/server/pkg/db/generated"
@@ -18,20 +19,31 @@ import (
// self-mention loops, planner ping-pong, and accidental `MUL-` prefix
// hardcoding because the agent did not always know the workspace prefix).
//
-// Guards:
+// Guards on whether the comment fires at all:
// - prev.Status must not already be "done" (idempotent — repeat saves of
// done do not re-fire; only the transition fires)
// - issue.Status must be "done"
// - issue.ParentIssueID must be set
// - parent must not be "done" or "cancelled" — the parent is already
// closed and a notification has no follow-up to drive
+// - parent assignee must not be a member (human). Humans read their
+// issues manually; an automated system comment is pure noise for them
+// and there is nothing to "trigger" on a human assignee. Skipping the
+// comment entirely (Bohan's call on MUL-2538) also sidesteps the
+// mention question — no comment, no mention, no inbox row.
//
// The comment is inserted directly via db.Queries (not through the
-// CreateComment HTTP handler) so it bypasses the assignee on_comment trigger
-// and the mention-based agent enqueue paths. The content carries no
-// `mention://agent/...` / `mention://member/...` / `mention://squad/...`
-// links — only the safe issue mention for the child identifier. This is the
-// "no default mention side-effect" requirement from MUL-2538.
+// CreateComment HTTP handler) so it bypasses the generic on_comment trigger
+// path. When the parent has an agent or squad assignee, the comment body
+// embeds a single `mention://{agent,squad}/<id>` link that targets the
+// parent assignee — Bohan's product call on MUL-2538 ("system child-done
+// comment 无脑 mention parent assignee,member/squad/agent 都覆盖", later
+// narrowed to skip member assignees outright). To keep the platform in
+// control of side effects, the cmd/server notification + subscriber
+// listeners still skip system comments wholesale, so smuggled mentions from
+// the child title cannot light up unrelated members. The parent assignee's
+// own trigger is fired explicitly by dispatchParentAssigneeTrigger below,
+// with the loop and idempotency guards documented there.
//
// Errors are logged at warn level and swallowed: this is a best-effort
// notification on the side of a successful status update; failing it must
@@ -54,14 +66,26 @@ func (h *Handler) notifyParentOfChildDone(ctx context.Context, prev, issue db.Is
if parent.Status == "done" || parent.Status == "cancelled" {
return
}
+ // Human-assigned parents read their own timeline; an automated system
+ // comment is just noise and there is no agent task to trigger. Skip the
+ // whole notification (comment + mention + inbox row) — MUL-2538.
+ if parent.AssigneeType.Valid && parent.AssigneeType.String == "member" {
+ return
+ }
prefix := h.getIssuePrefix(ctx, issue.WorkspaceID)
identifier := prefix + "-" + strconv.Itoa(int(issue.Number))
childID := uuidToString(issue.ID)
- title := issue.Title
+ title := sanitizeChildTitleForSystemComment(issue.Title)
+
+ // Build the parent-assignee mention prefix. Empty when the parent has no
+ // assignee or the assignee row is missing (deleted member, archived
+ // agent the workspace lost track of, etc.).
+ mentionPrefix := h.buildParentAssigneeMention(ctx, parent)
+
content := fmt.Sprintf(
- "Sub-issue [%s](mention://issue/%s) — \"%s\" — is done. Confirm whether to advance the next step on this parent (and promote any waiting `backlog` sub-issues).",
- identifier, childID, title,
+ "%sSub-issue [%s](mention://issue/%s) — \"%s\" — is done. Confirm whether to advance the next step on this parent (and promote any waiting `backlog` sub-issues).",
+ mentionPrefix, identifier, childID, title,
)
// author_type='system', author_id=zero UUID. The zero UUID is a valid 16
@@ -91,4 +115,262 @@ func (h *Handler) notifyParentOfChildDone(ctx context.Context, prev, issue db.Is
"issue_assignee_id": uuidToPtr(parent.AssigneeID),
"issue_status": parent.Status,
})
+
+ // Dispatch the explicit trigger / inbox row for the parent assignee.
+ // Listener-level mention parsing is intentionally NOT involved (the
+ // notification + subscriber listeners both short-circuit on
+ // author_type='system'); this keeps smuggled mentions from the child
+ // title inert and gives the platform a single place to apply the loop
+ // and idempotency guards.
+ h.dispatchParentAssigneeTrigger(ctx, parent, issue, comment)
+}
+
+// sanitizeChildTitleForSystemComment removes mention-style markdown from a
+// child issue's title before it is embedded into the parent's system
+// comment. Smuggled mentions are already harmless on the listener path
+// (notification + subscriber listeners both skip system comments), but the
+// timeline still renders the title verbatim — stripping the markdown keeps
+// the rendered comment readable and stops a maliciously titled child issue
+// from looking like a directive ("@all please look").
+func sanitizeChildTitleForSystemComment(title string) string {
+ // Replace any markdown link target so the regex no longer matches it,
+ // while preserving the human-readable label text. `]` and `(` are the
+ // minimum delimiters of the mention regex; replacing the `(` is enough
+ // to break the match without mangling the label.
+ cleaned := strings.ReplaceAll(title, "](mention://", "] (mention-stripped://")
+ return cleaned
+}
+
+// buildParentAssigneeMention returns the markdown prefix that the system
+// comment should lead with, including a trailing space, so the body reads
+// like a normal mention-led comment. Returns the empty string when the
+// parent has no assignee or the assignee row could not be loaded.
+func (h *Handler) buildParentAssigneeMention(ctx context.Context, parent db.Issue) string {
+ if !parent.AssigneeType.Valid || !parent.AssigneeID.Valid {
+ return ""
+ }
+ label, ok := h.resolveAssigneeMentionLabel(ctx, parent.WorkspaceID, parent.AssigneeType.String, parent.AssigneeID)
+ if !ok {
+ return ""
+ }
+ return fmt.Sprintf("[@%s](mention://%s/%s) ", label, parent.AssigneeType.String, uuidToString(parent.AssigneeID))
+}
+
+// resolveAssigneeMentionLabel returns the label text to render inside the
+// mention link. The label is for human display only — the mention regex
+// keys off the URL path, not the label — but a sensible fallback keeps the
+// rendered comment legible if the frontend has not pre-loaded the assignee.
+// Returns ok=false when the assignee row cannot be loaded; the caller
+// should then omit the mention entirely rather than emit a broken link.
+func (h *Handler) resolveAssigneeMentionLabel(ctx context.Context, workspaceID pgtype.UUID, assigneeType string, assigneeID pgtype.UUID) (string, bool) {
+ switch assigneeType {
+ case "agent":
+ agent, err := h.Queries.GetAgentInWorkspace(ctx, db.GetAgentInWorkspaceParams{
+ ID: assigneeID,
+ WorkspaceID: workspaceID,
+ })
+ if err != nil {
+ return "", false
+ }
+ return sanitizeMentionLabel(agent.Name), true
+ case "squad":
+ squad, err := h.Queries.GetSquadInWorkspace(ctx, db.GetSquadInWorkspaceParams{
+ ID: assigneeID,
+ WorkspaceID: workspaceID,
+ })
+ if err != nil {
+ return "", false
+ }
+ return sanitizeMentionLabel(squad.Name), true
+ }
+ return "", false
+}
+
+// sanitizeMentionLabel strips characters that would break the mention
+// markdown if a name contained them. The mention regex is non-greedy on the
+// label, so a stray `]` would short-circuit it. Names with `]` are
+// vanishingly rare but cheap to defend against.
+func sanitizeMentionLabel(name string) string {
+ cleaned := strings.ReplaceAll(name, "]", "")
+ cleaned = strings.TrimSpace(cleaned)
+ if cleaned == "" {
+ return "assignee"
+ }
+ return cleaned
+}
+
+// dispatchParentAssigneeTrigger fires the explicit side effect that pairs
+// with the @mention link in the system comment body — an agent task for
+// agent or squad-leader assignees. Member assignees never reach this code
+// path; notifyParentOfChildDone skips them outright. The generic comment
+// listener is intentionally bypassed (it short-circuits on
+// author_type='system'), so this is the single place where the platform
+// applies loop and idempotency guards for the child-done notification.
+//
+// Side-effect semantics (intentionally narrower than a normal @mention):
+// - agent parent: one EnqueueTaskForMention on the parent assignee, same
+// trigger surface as a real @-mention so dedupe and readiness checks
+// match what users already rely on.
+// - squad parent: one EnqueueTaskForSquadLeader on the squad LEADER only.
+// Unlike a human @squad mention, this does NOT fan out to squad members
+// — child-done is a coordination signal, the leader decides whether
+// and how to wake the rest of the squad. Documented here so reviewers
+// don't read "system mention" as inheriting the full member fan-out.
+// - notification_preference is not consulted: this is a platform routing
+// signal targeted at the assignee that already owns the parent, not a
+// general notification. Per-user mute settings are evaluated by the
+// downstream agent_task / inbox pipeline once the task is dispatched.
+// - notification_listeners.go short-circuits on author_type='system', so
+// subscriber emails and member-inbox rows from smuggled mentions in the
+// child title are inert — only the explicit dispatch below runs.
+//
+// Guards applied here:
+// - No-op when the parent has no assignee row.
+// - Loop guard: skip when the agent that effectively "owns" the child
+// (its agent assignee, or the leader of its squad assignee) is the same
+// agent the parent would trigger (the parent agent itself, or the
+// parent squad's leader). Without this an agent that drives both child
+// and parent immediately re-runs on the parent and can post another
+// child, looping — including the cross-squad case where two different
+// squads share a leader.
+// - Idempotency: HasPendingTaskForIssueAndAgent dedupes rapid-fire enqueues
+// for the same parent (e.g. two children finishing back-to-back).
+// - Readiness: archived agents / missing runtimes are silently skipped
+// so a closed-out agent does not surface as a phantom assignee.
+func (h *Handler) dispatchParentAssigneeTrigger(ctx context.Context, parent, child db.Issue, systemComment db.Comment) {
+ if !parent.AssigneeType.Valid || !parent.AssigneeID.Valid {
+ return
+ }
+
+ switch parent.AssigneeType.String {
+ case "agent":
+ h.triggerChildDoneAgent(ctx, parent, child, systemComment.ID)
+ case "squad":
+ h.triggerChildDoneSquad(ctx, parent, child, systemComment.ID)
+ }
+}
+
+// triggerChildDoneAgent enqueues a mention-style task for the parent's
+// agent assignee, applying the self-trigger guard documented on
+// dispatchParentAssigneeTrigger.
+func (h *Handler) triggerChildDoneAgent(ctx context.Context, parent, child db.Issue, triggerCommentID pgtype.UUID) {
+ if owner := h.effectiveChildAgentOwner(ctx, child); owner.Valid &&
+ uuidToString(owner) == uuidToString(parent.AssigneeID) {
+ return
+ }
+
+ agent, err := h.Queries.GetAgentInWorkspace(ctx, db.GetAgentInWorkspaceParams{
+ ID: parent.AssigneeID,
+ WorkspaceID: parent.WorkspaceID,
+ })
+ if err != nil || !agent.RuntimeID.Valid || agent.ArchivedAt.Valid {
+ return
+ }
+
+ hasPending, err := h.Queries.HasPendingTaskForIssueAndAgent(ctx, db.HasPendingTaskForIssueAndAgentParams{
+ IssueID: parent.ID,
+ AgentID: parent.AssigneeID,
+ })
+ if err != nil || hasPending {
+ return
+ }
+
+ if _, err := h.TaskService.EnqueueTaskForMention(ctx, parent, parent.AssigneeID, triggerCommentID); err != nil {
+ slog.Warn("child done: enqueue parent agent task failed",
+ "error", err,
+ "parent_id", uuidToString(parent.ID),
+ "agent_id", uuidToString(parent.AssigneeID))
+ }
+}
+
+// triggerChildDoneSquad enqueues a leader-role task for the parent's squad
+// assignee, applying the self-trigger guard against:
+// - same squad on both sides (the leader already observed the child via
+// its own coordination cycle), and
+// - same effective leader on both sides — child agent == leader, or
+// child squad's leader == this squad's leader (the cross-squad shared
+// leader loop).
+func (h *Handler) triggerChildDoneSquad(ctx context.Context, parent, child db.Issue, triggerCommentID pgtype.UUID) {
+ squad, err := h.Queries.GetSquadInWorkspace(ctx, db.GetSquadInWorkspaceParams{
+ ID: parent.AssigneeID,
+ WorkspaceID: parent.WorkspaceID,
+ })
+ if err != nil {
+ return
+ }
+
+ // Same-squad child → the leader has already observed the work via its
+ // own coordination cycle on the child; firing again on the parent would
+ // just re-trigger the same leader run with no new signal.
+ if childAssigneeIsSquad(child, parent.AssigneeID) {
+ return
+ }
+ // Shared-leader loop: child driven directly by the parent squad's leader,
+ // or by another squad whose leader is the same agent.
+ if owner := h.effectiveChildAgentOwner(ctx, child); owner.Valid &&
+ uuidToString(owner) == uuidToString(squad.LeaderID) {
+ return
+ }
+
+ agent, err := h.Queries.GetAgent(ctx, squad.LeaderID)
+ if err != nil || !agent.RuntimeID.Valid || agent.ArchivedAt.Valid {
+ return
+ }
+
+ hasPending, err := h.Queries.HasPendingTaskForIssueAndAgent(ctx, db.HasPendingTaskForIssueAndAgentParams{
+ IssueID: parent.ID,
+ AgentID: squad.LeaderID,
+ })
+ if err != nil || hasPending {
+ return
+ }
+
+ if _, err := h.TaskService.EnqueueTaskForSquadLeader(ctx, parent, squad.LeaderID, triggerCommentID); err != nil {
+ slog.Warn("child done: enqueue parent squad leader task failed",
+ "error", err,
+ "parent_id", uuidToString(parent.ID),
+ "squad_id", uuidToString(squad.ID),
+ "leader_id", uuidToString(squad.LeaderID))
+ }
+}
+
+// effectiveChildAgentOwner returns the agent identity that effectively
+// "owns" the child issue from the perspective of the child-done trigger:
+//
+// - child agent assignee → that agent
+// - child squad assignee → that squad's leader (the agent that would
+// actually act on a leader task and is the entry point for any squad
+// work; a shared leader across two squads is the loop vector the
+// callers above defend against)
+// - anything else (member assignee, no assignee, missing squad row) →
+// invalid UUID, signalling "no shared owner to compare against"
+//
+// Callers compare this against the agent they are about to trigger; equality
+// means we'd be enqueueing the same agent that just finished the child,
+// which is the loop case.
+func (h *Handler) effectiveChildAgentOwner(ctx context.Context, child db.Issue) pgtype.UUID {
+ if !child.AssigneeType.Valid || !child.AssigneeID.Valid {
+ return pgtype.UUID{}
+ }
+ switch child.AssigneeType.String {
+ case "agent":
+ return child.AssigneeID
+ case "squad":
+ squad, err := h.Queries.GetSquadInWorkspace(ctx, db.GetSquadInWorkspaceParams{
+ ID: child.AssigneeID,
+ WorkspaceID: child.WorkspaceID,
+ })
+ if err != nil {
+ return pgtype.UUID{}
+ }
+ return squad.LeaderID
+ }
+ return pgtype.UUID{}
+}
+
+func childAssigneeIsSquad(child db.Issue, squadID pgtype.UUID) bool {
+ if !child.AssigneeType.Valid || child.AssigneeType.String != "squad" || !child.AssigneeID.Valid {
+ return false
+ }
+ return uuidToString(child.AssigneeID) == uuidToString(squadID)
}
diff --git a/server/internal/handler/issue_child_done_test.go b/server/internal/handler/issue_child_done_test.go
index 16f19b2d2c..61da70b796 100644
--- a/server/internal/handler/issue_child_done_test.go
+++ b/server/internal/handler/issue_child_done_test.go
@@ -104,13 +104,15 @@ func systemCommentOn(t *testing.T, issueID string) (content, authorIDStr string,
return
}
-// TestChildDoneNotifiesParent — the happy path. A child transitioning from a
-// non-done status into `done` while its parent is open must produce exactly
-// one top-level platform-generated comment on the parent. The comment must
-// reference the child by its workspace-specific identifier (NOT a hardcoded
-// `MUL-` prefix — that was the bug PR #2918 review called out) and must not
-// carry an `@mention` link to any member/agent/squad (those would re-trigger
-// the parent's assignee, which is the noise this change removed).
+// TestChildDoneNotifiesParent — the happy path for an unassigned parent. A
+// child transitioning from a non-done status into `done` while its parent is
+// open must produce exactly one top-level platform-generated comment on the
+// parent. The comment must reference the child by its workspace-specific
+// identifier (NOT a hardcoded `MUL-` prefix — that was the bug PR #2918
+// review called out). When the parent has no assignee, the body must NOT
+// carry any agent/member/squad mention either; the assignee-mention is the
+// only mention we ever inject (see MUL-2538 Option C — covered separately
+// in TestChildDoneMentionsParentAssignee_* below).
func TestChildDoneNotifiesParent(t *testing.T) {
fx := newChildDoneFixture(t, "in_progress")
@@ -140,15 +142,14 @@ func TestChildDoneNotifiesParent(t *testing.T) {
t.Errorf("comment must not hardcode MUL- prefix, got: %s", content)
}
- // The comment must contain the safe issue mention but NOT any
- // agent/member/squad mention (those would re-trigger the parent's
- // assignee).
+ // The comment must contain the safe issue mention. With no parent
+ // assignee, none of the routing mentions should appear either.
if !strings.Contains(content, "mention://issue/"+fx.child.ID) {
t.Errorf("expected mention://issue/<child-id> link in comment, got: %s", content)
}
for _, banned := range []string{"mention://agent/", "mention://member/", "mention://squad/"} {
if strings.Contains(content, banned) {
- t.Errorf("comment must not include %q mention (auto-mention side effect), got: %s", banned, content)
+ t.Errorf("parent has no assignee but comment included %q mention, got: %s", banned, content)
}
}
}
@@ -239,3 +240,265 @@ func TestChildDoneSkippedWhenNoParent(t *testing.T) {
t.Errorf("orphan must not receive a self-notification, got %d system comments", got)
}
}
+
+// setIssueAssigneeDirect bypasses UpdateIssue (and its assignment trigger
+// side effects) by writing to the assignee columns directly. The child-done
+// notification helper reads the parent row through GetIssue at fire time,
+// so a direct UPDATE is enough to drive the dispatch under each assignee
+// type without queuing a parallel agent task at setup.
+func setIssueAssigneeDirect(t *testing.T, issueID, assigneeType, assigneeID string) {
+ t.Helper()
+ if _, err := testPool.Exec(context.Background(),
+ `UPDATE issue SET assignee_type = $2, assignee_id = $3 WHERE id = $1`,
+ issueID, assigneeType, assigneeID,
+ ); err != nil {
+ t.Fatalf("set parent assignee: %v", err)
+ }
+}
+
+func parentSystemCommentContent(t *testing.T, issueID string) string {
+ t.Helper()
+ if got := countSystemCommentsOn(t, issueID); got != 1 {
+ t.Fatalf("expected exactly 1 system comment on parent, got %d", got)
+ }
+ content, _, _, _ := systemCommentOn(t, issueID)
+ return content
+}
+
+func countPendingTasksForAgent(t *testing.T, issueID, agentID string) int {
+ t.Helper()
+ var n int
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT count(*) FROM agent_task_queue
+ WHERE issue_id = $1 AND agent_id = $2
+ AND status IN ('queued', 'dispatched', 'running')`,
+ issueID, agentID,
+ ).Scan(&n); err != nil {
+ t.Fatalf("count pending tasks: %v", err)
+ }
+ return n
+}
+
+func countInboxItems(t *testing.T, recipientUserID, issueID string) int {
+ t.Helper()
+ var n int
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT count(*) FROM inbox_item
+ WHERE recipient_id = $1 AND issue_id = $2`,
+ recipientUserID, issueID,
+ ).Scan(&n); err != nil {
+ t.Fatalf("count inbox items: %v", err)
+ }
+ return n
+}
+
+// TestChildDoneMentionsParentAssignee_Agent verifies the MUL-2538 Option C
+// happy path for an agent parent assignee: the system comment carries a
+// `mention://agent/<id>` link AND a real mention-style task is enqueued on
+// the parent. The trigger fires through TaskService.EnqueueTaskForMention,
+// so the dedupe + readiness checks match the @-mention path users already
+// rely on.
+func TestChildDoneMentionsParentAssignee_Agent(t *testing.T) {
+ fx := newChildDoneFixture(t, "in_progress")
+
+ var agentID string
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT id FROM agent WHERE workspace_id = $1 AND name = $2`,
+ testWorkspaceID, "Handler Test Agent",
+ ).Scan(&agentID); err != nil {
+ t.Fatalf("locate test agent: %v", err)
+ }
+ setIssueAssigneeDirect(t, fx.parent.ID, "agent", agentID)
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(),
+ `DELETE FROM agent_task_queue WHERE issue_id = $1`, fx.parent.ID)
+ })
+
+ updateChildStatus(t, fx.child.ID, "done")
+
+ content := parentSystemCommentContent(t, fx.parent.ID)
+ wantMention := "mention://agent/" + agentID
+ if !strings.Contains(content, wantMention) {
+ t.Errorf("expected %q in system comment, got: %s", wantMention, content)
+ }
+ if got := countPendingTasksForAgent(t, fx.parent.ID, agentID); got != 1 {
+ t.Errorf("expected 1 pending task for parent agent, got %d", got)
+ }
+}
+
+// TestChildDoneSkippedWhenParentMember verifies the MUL-2538 follow-up: a
+// human parent assignee should NOT receive the platform-generated system
+// comment at all. Humans read their own timeline manually; the automated
+// notification is pure noise and skipping it also removes the question of
+// whether to mention/inbox-row the member.
+//
+// The assignee row uses `user_id` (NOT `member.id`) — that is the
+// production invariant validated by validateAssigneePair for member
+// assignees (see server/internal/handler/issue.go), so the fixture must
+// match or it would be exercising a state that cannot occur for real.
+func TestChildDoneSkippedWhenParentMember(t *testing.T) {
+ fx := newChildDoneFixture(t, "in_progress")
+
+ var userID string
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT user_id FROM member WHERE workspace_id = $1 LIMIT 1`,
+ testWorkspaceID,
+ ).Scan(&userID); err != nil {
+ t.Fatalf("locate workspace member: %v", err)
+ }
+ setIssueAssigneeDirect(t, fx.parent.ID, "member", userID)
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(),
+ `DELETE FROM inbox_item WHERE issue_id = $1`, fx.parent.ID)
+ })
+
+ updateChildStatus(t, fx.child.ID, "done")
+
+ if got := countSystemCommentsOn(t, fx.parent.ID); got != 0 {
+ t.Errorf("parent with member assignee should not receive a system comment, got %d", got)
+ }
+ if got := countInboxItems(t, userID, fx.parent.ID); got != 0 {
+ t.Errorf("parent with member assignee should not receive an inbox row, got %d", got)
+ }
+}
+
+// TestChildDoneMentionsParentAssignee_Squad verifies the squad branch: the
+// system comment carries a `mention://squad/<id>` link and the squad
+// leader receives a leader-role task. Reuses the squad fixture helper from
+// squad_comment_trigger_test.go.
+func TestChildDoneMentionsParentAssignee_Squad(t *testing.T) {
+ fx := newChildDoneFixture(t, "in_progress")
+ sq := newSquadCommentTriggerFixture(t)
+
+ setIssueAssigneeDirect(t, fx.parent.ID, "squad", sq.SquadID)
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(),
+ `DELETE FROM agent_task_queue WHERE issue_id = $1`, fx.parent.ID)
+ })
+
+ updateChildStatus(t, fx.child.ID, "done")
+
+ content := parentSystemCommentContent(t, fx.parent.ID)
+ wantMention := "mention://squad/" + sq.SquadID
+ if !strings.Contains(content, wantMention) {
+ t.Errorf("expected %q in system comment, got: %s", wantMention, content)
+ }
+ if got := countPendingTasksForAgent(t, fx.parent.ID, sq.LeaderID); got != 1 {
+ t.Errorf("expected 1 pending leader task for parent squad, got %d", got)
+ }
+}
+
+// TestChildDoneSelfTriggerGuard_SameAgent — when the parent assignee is
+// the same agent that owns the child, the comment still records the
+// completion (so the timeline tells the full story) but no new task is
+// enqueued. Without this guard the agent immediately re-runs on the
+// parent and can post another child, looping.
+func TestChildDoneSelfTriggerGuard_SameAgent(t *testing.T) {
+ fx := newChildDoneFixture(t, "in_progress")
+
+ var agentID string
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT id FROM agent WHERE workspace_id = $1 AND name = $2`,
+ testWorkspaceID, "Handler Test Agent",
+ ).Scan(&agentID); err != nil {
+ t.Fatalf("locate test agent: %v", err)
+ }
+ // Both child and parent assigned to the same agent. Setting the child
+ // assignee via direct SQL avoids the assignment-trigger side effect
+ // that would otherwise queue an unrelated task on the child.
+ setIssueAssigneeDirect(t, fx.parent.ID, "agent", agentID)
+ setIssueAssigneeDirect(t, fx.child.ID, "agent", agentID)
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(),
+ `DELETE FROM agent_task_queue WHERE issue_id IN ($1, $2)`,
+ fx.parent.ID, fx.child.ID)
+ })
+
+ updateChildStatus(t, fx.child.ID, "done")
+
+ // The comment should still be created (the human user reading the
+ // timeline still benefits from seeing that the child finished). The
+ // task enqueue is what gets skipped.
+ content := parentSystemCommentContent(t, fx.parent.ID)
+ if !strings.Contains(content, "mention://agent/"+agentID) {
+ t.Errorf("expected parent-assignee mention in system comment, got: %s", content)
+ }
+ if got := countPendingTasksForAgent(t, fx.parent.ID, agentID); got != 0 {
+ t.Errorf("expected 0 pending tasks on parent (self-trigger guard), got %d", got)
+ }
+}
+
+// TestChildDoneSelfTriggerGuard_AgentParentSquadChildSameLeader — the
+// cross-type loop case Elon called out. Parent is assigned to agent A
+// directly; child is assigned to a squad whose leader is also agent A.
+// Without `effectiveChildAgentOwner`, the parent-agent path only checked
+// the child's direct assignee and would happily enqueue agent A on the
+// parent, restarting the loop through the squad. The system comment is
+// still created (timeline parity); only the task enqueue is suppressed.
+func TestChildDoneSelfTriggerGuard_AgentParentSquadChildSameLeader(t *testing.T) {
+ fx := newChildDoneFixture(t, "in_progress")
+ sq := newSquadCommentTriggerFixture(t)
+
+ // Parent agent == squad leader, child assigned to the squad.
+ setIssueAssigneeDirect(t, fx.parent.ID, "agent", sq.LeaderID)
+ setIssueAssigneeDirect(t, fx.child.ID, "squad", sq.SquadID)
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(),
+ `DELETE FROM agent_task_queue WHERE issue_id IN ($1, $2)`,
+ fx.parent.ID, fx.child.ID)
+ })
+
+ updateChildStatus(t, fx.child.ID, "done")
+
+ content := parentSystemCommentContent(t, fx.parent.ID)
+ if !strings.Contains(content, "mention://agent/"+sq.LeaderID) {
+ t.Errorf("expected parent-agent mention in system comment, got: %s", content)
+ }
+ if got := countPendingTasksForAgent(t, fx.parent.ID, sq.LeaderID); got != 0 {
+ t.Errorf("expected 0 pending tasks on parent (shared-leader guard), got %d", got)
+ }
+}
+
+// TestChildDoneSelfTriggerGuard_SquadParentDifferentSquadSameLeader — the
+// cross-squad shared-leader loop. Parent is squad A, child is squad B,
+// both squads have the same leader agent. The previous guard only blocked
+// `parent.squad == child.squad`, so two distinct squads sharing a leader
+// would still wake the same agent. effectiveChildAgentOwner reduces both
+// sides to "leader agent" and blocks the enqueue.
+func TestChildDoneSelfTriggerGuard_SquadParentDifferentSquadSameLeader(t *testing.T) {
+ fx := newChildDoneFixture(t, "in_progress")
+ parentSquad := newSquadCommentTriggerFixture(t)
+
+ // Spin up a SECOND squad that reuses the same leader as parentSquad.
+ ctx := context.Background()
+ var childSquadID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO squad (workspace_id, name, description, leader_id, creator_id)
+ VALUES ($1, $2, '', $3, $4)
+ RETURNING id
+ `, testWorkspaceID, "Child Done Shared Leader Squad", parentSquad.LeaderID, testUserID).
+ Scan(&childSquadID); err != nil {
+ t.Fatalf("create second squad: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM squad WHERE id = $1`, childSquadID)
+ })
+
+ setIssueAssigneeDirect(t, fx.parent.ID, "squad", parentSquad.SquadID)
+ setIssueAssigneeDirect(t, fx.child.ID, "squad", childSquadID)
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(),
+ `DELETE FROM agent_task_queue WHERE issue_id IN ($1, $2)`,
+ fx.parent.ID, fx.child.ID)
+ })
+
+ updateChildStatus(t, fx.child.ID, "done")
+
+ content := parentSystemCommentContent(t, fx.parent.ID)
+ if !strings.Contains(content, "mention://squad/"+parentSquad.SquadID) {
+ t.Errorf("expected parent-squad mention in system comment, got: %s", content)
+ }
+ if got := countPendingTasksForAgent(t, fx.parent.ID, parentSquad.LeaderID); got != 0 {
+ t.Errorf("expected 0 pending leader tasks on parent (cross-squad shared-leader guard), got %d", got)
+ }
+}