Skip to content

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

Go

MUL-7449: fix: distinguish cancelled child work from done in stage progress (#8495)

NanPan8006317f11e2
diff --git a/server/internal/handler/issue_batch_test.go b/server/internal/handler/issue_batch_test.go
index 8725ab58f0..746b872b11 100644
--- a/server/internal/handler/issue_batch_test.go
+++ b/server/internal/handler/issue_batch_test.go
@@ -365,8 +365,8 @@ func TestBatchChildDoneCrossStage_OneComment(t *testing.T) {
}
// TestBatchChildDoneCrossStage_Cancelled — cancelling every stage in one batch
-// is terminal too and must behave identically: one accurate final comment, no
-// stale advance instruction.
+// is terminal too, but the notification must distinguish cancellation from
+// successful completion while still emitting one accurate final comment.
func TestBatchChildDoneCrossStage_Cancelled(t *testing.T) {
fx := newStagedBatchFixture(t)
batchSetStatus(t, []string{fx.stage1[0].ID, fx.stage1[1].ID, fx.stage2[0].ID, fx.stage2[1].ID}, "cancelled")
@@ -375,8 +375,11 @@ func TestBatchChildDoneCrossStage_Cancelled(t *testing.T) {
t.Fatalf("expected exactly 1 system comment on parent, got %d", got)
}
content, _, _, _ := systemCommentOn(t, fx.parent.ID)
- if !strings.Contains(content, "Stage 2 of this issue is complete") {
- t.Errorf("expected Stage 2 completion announcement, got: %s", content)
+ if !strings.Contains(content, "Stage 2 of this issue is closed") {
+ t.Errorf("expected Stage 2 closed announcement for cancelled work, got: %s", content)
+ }
+ if !strings.Contains(content, "Stage 1: 0/2 done, 2 cancelled; Stage 2: 0/2 done, 2 cancelled") {
+ t.Errorf("expected cancelled children to be counted separately from done, got: %s", content)
}
if strings.Contains(content, "is next") || strings.Contains(content, "(next)") {
t.Errorf("comment must not carry a stale next-stage instruction, got: %s", content)
diff --git a/server/internal/handler/issue_child_done.go b/server/internal/handler/issue_child_done.go
index 677c0de4d7..7a2a0c4923 100644
--- a/server/internal/handler/issue_child_done.go
+++ b/server/internal/handler/issue_child_done.go
@@ -138,7 +138,7 @@ func (h *Handler) notifyParentOfChildDone(ctx context.Context, prev, issue db.Is
// sub-issue finishes" instead of the old fire-on-every-child behavior that
// caused the surprise cascade. A completion that does not close a stage is
// silent: no comment, no wake. ListChildIssues already reflects this child's
- // committed `done` status (the status update commits before this runs).
+ // committed terminal status (the status update commits before this runs).
children, err := h.Queries.ListChildIssues(ctx, parent.ID)
if err != nil {
slog.Warn("child done: failed to list siblings for stage barrier",
@@ -147,12 +147,12 @@ func (h *Handler) notifyParentOfChildDone(ctx context.Context, prev, issue db.Is
"parent_id", uuidToString(parent.ID))
return
}
- isTerminal, err := resolveTerminalChildren(children, effective)
+ statuses, err := resolveChildStatuses(children, effective)
if err != nil {
slog.Warn("child done: failed to resolve sibling statuses", "error", err, "parent_id", uuidToString(parent.ID))
return
}
- if !stageBarrierClosed(children, issue, isTerminal) {
+ if !stageBarrierClosed(children, issue, statuses.isTerminal) {
return
}
staged := siblingsAreStaged(children)
@@ -163,7 +163,7 @@ func (h *Handler) notifyParentOfChildDone(ctx context.Context, prev, issue db.Is
if staged {
closedStage = issue.Stage.Int32
}
- h.postChildDoneComment(ctx, parent, issue, children, staged, closedStage, false, isTerminal)
+ h.postChildDoneComment(ctx, parent, issue, children, staged, closedStage, false, statuses, nil)
}
// notifyParentsOfBatchChildDone emits child-done parent notifications for a
@@ -239,7 +239,7 @@ func (h *Handler) notifyParentsOfBatchChildDone(ctx context.Context, completed [
continue
}
- isTerminal, err := resolveTerminalChildren(children, effective)
+ statuses, err := resolveChildStatuses(children, effective)
if err != nil {
slog.Warn("batch child done: failed to resolve sibling statuses", "error", err, "parent_id", uuidToString(parent.ID))
continue
@@ -249,10 +249,10 @@ func (h *Handler) notifyParentsOfBatchChildDone(ctx context.Context, completed [
// Unstaged: one implicit stage. Fire once iff every child is terminal
// in the final state. stageBarrierClosed ignores `completed` on the
// unstaged path, so any completed child stands in for the barrier check.
- if !stageBarrierClosed(children, g.children[0], isTerminal) {
+ if !stageBarrierClosed(children, g.children[0], statuses.isTerminal) {
continue
}
- h.postChildDoneComment(ctx, parent, g.children[0], children, false, 0, batch, isTerminal)
+ h.postChildDoneComment(ctx, parent, g.children[0], children, false, 0, batch, statuses, g.children)
continue
}
@@ -264,19 +264,20 @@ func (h *Handler) notifyParentsOfBatchChildDone(ctx context.Context, completed [
// reality rather than a mid-batch snapshot. A lower closed stage would
// re-introduce the stale "advance the next stage" instruction the bug was
// about.
- rep, found := highestClosedBatchStage(children, g.children, isTerminal)
+ rep, found := highestClosedBatchStage(children, g.children, statuses.isTerminal)
if !found {
continue
}
- h.postChildDoneComment(ctx, parent, rep, children, true, rep.Stage.Int32, batch, isTerminal)
+ h.postChildDoneComment(ctx, parent, rep, children, true, rep.Stage.Int32, batch, statuses, g.children)
}
}
// highestClosedBatchStage selects the first completed child in the highest
// closed stage of a staged sibling set. The terminal predicate must come from
-// resolveTerminalChildren: all required statuses must be known before selection.
-// A stage S is closed iff no non-terminal staged sibling has stage <= S, so
-// finding the earliest open stage once reduces selection from O(N*K) to O(N+K).
+// a pre-resolved child-status snapshot: all required statuses must be known
+// before selection. A stage S is closed iff no non-terminal staged sibling has
+// stage <= S, so finding the earliest open stage once reduces selection from
+// O(N*K) to O(N+K).
func highestClosedBatchStage(children, completed []db.Issue, isTerminal func(db.Issue) bool) (db.Issue, bool) {
var lowestCompleted pgtype.Int4
for _, c := range completed {
@@ -321,17 +322,17 @@ func highestClosedBatchStage(children, completed []db.Issue, isTerminal func(db.
// has already passed and that `completed` is a terminal child whose barrier is
// closed within `children` (the final sibling set).
//
-// `completed` is the representative finished child named in the comment.
+// `completed` is the representative terminal child named in the comment.
// `staged`/`closedStage` describe the closed barrier (closedStage is unused for
-// an unstaged set). `batch` selects batch-aware wording: a single update keeps
-// its historical byte-identical copy, while a batch that finished several
-// children at once must not claim "the last sub-issue just finished".
-func (h *Handler) postChildDoneComment(ctx context.Context, parent, completed db.Issue, children []db.Issue, staged bool, closedStage int32, batch bool, isTerminal func(db.Issue) bool) {
+// an unstaged set). `batch` selects batch-aware wording. `batchCompleted` is the
+// set that transitioned to terminal in this batch; it is nil for single updates.
+func (h *Handler) postChildDoneComment(ctx context.Context, parent, completed db.Issue, children []db.Issue, staged bool, closedStage int32, batch bool, statuses resolvedChildStatuses, batchCompleted []db.Issue) {
prefix := h.getIssuePrefix(ctx, completed.WorkspaceID)
identifier := prefix + "-" + strconv.Itoa(int(completed.Number))
childID := uuidToString(completed.ID)
title := sanitizeChildTitleForSystemComment(completed.Title)
parentID := uuidToString(parent.ID)
+ completedStatus := statuses.status(completed)
// Build the parent-assignee mention prefix. Empty when the parent has no
// assignee or the assignee row is missing (deleted member, archived
@@ -340,30 +341,87 @@ func (h *Handler) postChildDoneComment(ctx context.Context, parent, completed db
var content string
if staged {
- summary, nextStage := stageProgressSummary(children, closedStage, isTerminal)
- advance := stageAdvanceInstruction(nextStage, parentID)
+ stageCancelled := stageHasCancelled(children, closedStage, statuses.status)
+ advanceHasCancelled := stageCancelled
if batch {
+ // A single batch can close several stages. Always preserve cancellation
+ // already present in the named stage, and also account for lower stages
+ // newly cancelled by this same batch without repeating older lower-stage
+ // warnings.
+ advanceHasCancelled = stageCancelled || batchClosedScopeHasCancelled(children, batchCompleted, closedStage, statuses.status)
+ }
+ summary, nextStage := stageProgressSummary(children, closedStage, statuses.status)
+ advance := stageAdvanceInstruction(nextStage, parentID, advanceHasCancelled)
+ if !stageCancelled {
+ // Keep the historical no-cancellation wording byte-identical for the
+ // named stage. A lower stage cancelled in the same batch can still add
+ // the dependency warning through advanceHasCancelled above.
+ if batch {
+ content = fmt.Sprintf(
+ "%sStage %d of this issue is complete — its sub-issues just finished together in a batch update, most recently [%s](mention://issue/%s) — \"%s\". Stage progress — %s.%s",
+ mentionPrefix, closedStage, identifier, childID, title, summary, advance,
+ )
+ } else {
+ content = fmt.Sprintf(
+ "%sStage %d of this issue is complete — its last sub-issue [%s](mention://issue/%s) — \"%s\" — just finished. Stage progress — %s.%s",
+ mentionPrefix, closedStage, identifier, childID, title, summary, advance,
+ )
+ }
+ } else if batch {
+ lastAction := "finished"
+ if completedStatus == "cancelled" {
+ lastAction = "was cancelled"
+ }
content = fmt.Sprintf(
- "%sStage %d of this issue is complete — its sub-issues just finished together in a batch update, most recently [%s](mention://issue/%s) — \"%s\". Stage progress — %s.%s",
- mentionPrefix, closedStage, identifier, childID, title, summary, advance,
+ "%sStage %d of this issue is closed — its sub-issues reached terminal states together in a batch update; most recently, [%s](mention://issue/%s) — \"%s\" — %s. Stage progress — %s.%s",
+ mentionPrefix, closedStage, identifier, childID, title, lastAction, summary, advance,
)
} else {
+ lastAction := "just finished"
+ if completedStatus == "cancelled" {
+ lastAction = "was just cancelled"
+ }
content = fmt.Sprintf(
- "%sStage %d of this issue is complete — its last sub-issue [%s](mention://issue/%s) — \"%s\" — just finished. Stage progress — %s.%s",
- mentionPrefix, closedStage, identifier, childID, title, summary, advance,
+ "%sStage %d of this issue is closed — its last sub-issue [%s](mention://issue/%s) — \"%s\" — %s. Stage progress — %s.%s",
+ mentionPrefix, closedStage, identifier, childID, title, lastAction, summary, advance,
)
}
} else {
- if batch {
- content = fmt.Sprintf(
- "%sAll sub-issues are complete — they just finished together in a batch update, most recently [%s](mention://issue/%s) — \"%s\". Continue the parent: synthesize the children's results and move it forward, or — if nothing remains — run `multica issue status %s in_review` to mark the parent ready for review.",
- mentionPrefix, identifier, childID, title, parentID,
- )
+ hasCancelled := anyCancelledChildren(children, statuses.status)
+ if !hasCancelled {
+ // Keep the historical no-cancellation wording byte-identical.
+ if batch {
+ content = fmt.Sprintf(
+ "%sAll sub-issues are complete — they just finished together in a batch update, most recently [%s](mention://issue/%s) — \"%s\". Continue the parent: synthesize the children's results and move it forward, or — if nothing remains — run `multica issue status %s in_review` to mark the parent ready for review.",
+ mentionPrefix, identifier, childID, title, parentID,
+ )
+ } else {
+ content = fmt.Sprintf(
+ "%sAll sub-issues are complete — the last one, [%s](mention://issue/%s) — \"%s\", just finished. Continue the parent: synthesize the children's results and move it forward, or — if nothing remains — run `multica issue status %s in_review` to mark the parent ready for review.",
+ mentionPrefix, identifier, childID, title, parentID,
+ )
+ }
} else {
- content = fmt.Sprintf(
- "%sAll sub-issues are complete — the last one, [%s](mention://issue/%s) — \"%s\", just finished. Continue the parent: synthesize the children's results and move it forward, or — if nothing remains — run `multica issue status %s in_review` to mark the parent ready for review.",
- mentionPrefix, identifier, childID, title, parentID,
- )
+ lastAction := "finished"
+ if completedStatus == "cancelled" {
+ lastAction = "was cancelled"
+ }
+ warning := unstagedCancellationInstruction()
+ if !batch {
+ lastAction = "just finished"
+ if completedStatus == "cancelled" {
+ lastAction = "was just cancelled"
+ }
+ content = fmt.Sprintf(
+ "%sAll sub-issues are closed — the last one, [%s](mention://issue/%s) — \"%s\", %s.%s Continue the parent: synthesize the children's results and move it forward, or — if nothing remains — run `multica issue status %s in_review` to mark the parent ready for review.",
+ mentionPrefix, identifier, childID, title, lastAction, warning, parentID,
+ )
+ } else {
+ content = fmt.Sprintf(
+ "%sAll sub-issues are closed — they reached terminal states together in a batch update; most recently, [%s](mention://issue/%s) — \"%s\" — %s.%s Continue the parent: synthesize the children's results and move it forward, or — if nothing remains — run `multica issue status %s in_review` to mark the parent ready for review.",
+ mentionPrefix, identifier, childID, title, lastAction, warning, parentID,
+ )
+ }
}
}
@@ -449,12 +507,26 @@ func (h *Handler) childStatusResolver(ctx context.Context) func(db.Issue) (strin
}
}
-// resolveTerminalChildren checks every status needed by the stage barrier and
-// progress summary before either can produce a notification. The returned
-// predicate only reads this snapshot, so a late catalog failure cannot be
-// hidden by the bool-only stage helpers. Stored status keys stay untouched.
-func resolveTerminalChildren(children []db.Issue, effective func(db.Issue) (string, error)) (func(db.Issue) bool, error) {
- terminal := make(map[pgtype.UUID]bool, len(children))
+// resolvedChildStatuses keeps the canonical status of every child needed by
+// the barrier and comment builders. Keeping the three-state information here
+// (open / done / cancelled) prevents the reporting path from mistaking
+// "terminal" for "done" while still letting the barrier ask its narrower
+// terminality question.
+type resolvedChildStatuses map[pgtype.UUID]string
+
+func (s resolvedChildStatuses) status(child db.Issue) string {
+ return s[child.ID]
+}
+
+func (s resolvedChildStatuses) isTerminal(child db.Issue) bool {
+ return isTerminalChildStatus(s.status(child))
+}
+
+// resolveChildStatuses checks every status needed by the stage barrier and
+// progress summary before either can produce a notification. Stored status
+// keys stay untouched; the returned snapshot contains their canonical values.
+func resolveChildStatuses(children []db.Issue, effective func(db.Issue) (string, error)) (resolvedChildStatuses, error) {
+ statuses := make(resolvedChildStatuses, len(children))
staged := siblingsAreStaged(children)
for _, child := range children {
if staged && !child.Stage.Valid {
@@ -464,9 +536,9 @@ func resolveTerminalChildren(children []db.Issue, effective func(db.Issue) (stri
if err != nil {
return nil, fmt.Errorf("resolve child %s status %q: %w", uuidToString(child.ID), child.Status, err)
}
- terminal[child.ID] = isTerminalChildStatus(status)
+ statuses[child.ID] = status
}
- return func(child db.Issue) bool { return terminal[child.ID] }, nil
+ return statuses, nil
}
// siblingsAreStaged reports whether any child in the set carries an explicit
@@ -522,13 +594,12 @@ func stageBarrierClosed(children []db.Issue, completed db.Issue, isTerminal func
}
// stageProgressSummary renders a compact per-stage breakdown for the
-// child-done system comment (e.g. "Stage 1: 3/3 done; Stage 2: 0/4 done") and
-// returns the lowest stage above closedStage that still has non-terminal
-// children — the next group to promote — or 0 when none remain. Unstaged
-// children are skipped (they are not part of any stage), so the breakdown
-// never renders a "Stage 0".
-func stageProgressSummary(children []db.Issue, closedStage int32, isTerminal func(db.Issue) bool) (summary string, nextStage int32) {
- type agg struct{ total, done int }
+// child-done system comment. `done` counts only genuinely completed children;
+// canonical `cancelled` children are surfaced separately. nextStage is the
+// lowest stage above closedStage that still has non-terminal children, or 0
+// when none remain. Unstaged children are skipped.
+func stageProgressSummary(children []db.Issue, closedStage int32, statusOf func(db.Issue) string) (summary string, nextStage int32) {
+ type agg struct{ total, done, cancelled, terminal int }
byStage := map[int32]*agg{}
order := []int32{}
for _, c := range children {
@@ -543,8 +614,13 @@ func stageProgressSummary(children []db.Issue, closedStage int32, isTerminal fun
order = append(order, s)
}
a.total++
- if isTerminal(c) {
+ switch statusOf(c) {
+ case "done":
a.done++
+ a.terminal++
+ case "cancelled":
+ a.cancelled++
+ a.terminal++
}
}
sort.Slice(order, func(i, j int) bool { return order[i] < order[j] })
@@ -552,7 +628,10 @@ func stageProgressSummary(children []db.Issue, closedStage int32, isTerminal fun
for _, s := range order {
a := byStage[s]
label := fmt.Sprintf("Stage %d: %d/%d done", s, a.done, a.total)
- if nextStage == 0 && s > closedStage && a.done < a.total {
+ if a.cancelled > 0 {
+ label += fmt.Sprintf(", %d cancelled", a.cancelled)
+ }
+ if nextStage == 0 && s > closedStage && a.terminal < a.total {
nextStage = s
label += " (next)"
}
@@ -561,6 +640,45 @@ func stageProgressSummary(children []db.Issue, closedStage int32, isTerminal fun
return strings.Join(parts, "; "), nextStage
}
+func stageHasCancelled(children []db.Issue, stage int32, statusOf func(db.Issue) string) bool {
+ for _, child := range children {
+ if child.Stage.Valid && child.Stage.Int32 == stage && statusOf(child) == "cancelled" {
+ return true
+ }
+ }
+ return false
+}
+
+// batchClosedScopeHasCancelled reports whether this batch newly cancelled work
+// in any stage up to the highest closed stage represented by the aggregated
+// notification. It reads stage/status from the final sibling snapshot, using
+// the batch rows only as an ID set, so a concurrently moved child cannot make a
+// stale stage number leak into the decision.
+func batchClosedScopeHasCancelled(children, batchCompleted []db.Issue, closedStage int32, statusOf func(db.Issue) string) bool {
+ completedIDs := make(map[pgtype.UUID]struct{}, len(batchCompleted))
+ for _, child := range batchCompleted {
+ completedIDs[child.ID] = struct{}{}
+ }
+ for _, child := range children {
+ if _, ok := completedIDs[child.ID]; !ok {
+ continue
+ }
+ if child.Stage.Valid && child.Stage.Int32 <= closedStage && statusOf(child) == "cancelled" {
+ return true
+ }
+ }
+ return false
+}
+
+func anyCancelledChildren(children []db.Issue, statusOf func(db.Issue) string) bool {
+ for _, child := range children {
+ if statusOf(child) == "cancelled" {
+ return true
+ }
+ }
+ return false
+}
+
// stageAdvanceInstruction returns the trailing instruction appended to a
// staged child-done system comment, given the next stage with pending work
// among the sub-issues that currently exist (nextStage, 0 = none).
@@ -577,14 +695,27 @@ func stageProgressSummary(children []db.Issue, closedStage int32, isTerminal fun
// asserted a finality the server cannot know and pushed leaders to wrap up
// mid-workflow (MUL-4062 / #4927). The message now names both possibilities
// and hands the create-next-vs-wrap-up decision back to the leader.
-func stageAdvanceInstruction(nextStage int32, parentID string) string {
+// - hasCancelled: one of the stages just closed contains cancelled work, so
+// the instruction asks the assignee to confirm it is not a dependency
+// before advancing. The server still does not decide that question itself.
+func stageAdvanceInstruction(nextStage int32, parentID string, hasCancelled bool) string {
+ var instruction string
if nextStage > 0 {
- return fmt.Sprintf(
+ instruction = fmt.Sprintf(
" Stage %d is next. Review the full layout with `multica issue children %s`, and if Stage %d's dependencies are satisfied promote its `backlog` sub-issues to `todo` to continue. Read each sub-issue's description first and only promote items whose stated dependencies are already met — do not rely on this parent's higher-level breakdown alone. If a description conflicts with that breakdown, leave it `backlog` and post a comment to confirm first.",
nextStage, parentID, nextStage,
)
+ } else {
+ instruction = fmt.Sprintf(" Completing this stage does not mean the whole issue is done. Decide whether the issue is actually complete — if so, synthesize the results and run `multica issue status %s in_review` to mark the parent ready for review — or whether the next stage still needs to be created, in which case create that stage and its sub-issues now.", parentID)
+ }
+ if !hasCancelled {
+ return instruction
}
- return fmt.Sprintf(" Completing this stage does not mean the whole issue is done. Decide whether the issue is actually complete — if so, synthesize the results and run `multica issue status %s in_review` to mark the parent ready for review — or whether the next stage still needs to be created, in which case create that stage and its sub-issues now.", parentID)
+ return instruction + " The just-closed work includes cancelled items: confirm that the cancelled work is not a dependency of whatever comes next before advancing. If unsure, do not promote or create the next stage yet; post a comment to confirm first."
+}
+
+func unstagedCancellationInstruction() string {
+ return " Before moving the parent forward, confirm that the cancelled work is not required by whatever comes next. If unsure, leave the parent as-is and post a comment to confirm first."
}
// sanitizeChildTitleForSystemComment removes mention-style markdown from a
diff --git a/server/internal/handler/issue_child_done_batch_stage_test.go b/server/internal/handler/issue_child_done_batch_stage_test.go
index 28ed96aef3..df42c4ddc4 100644
--- a/server/internal/handler/issue_child_done_batch_stage_test.go
+++ b/server/internal/handler/issue_child_done_batch_stage_test.go
@@ -175,12 +175,13 @@ func TestHighestClosedBatchStageEarlyExit(t *testing.T) {
func TestBatchChildDonePreservesRepresentativeAndParentOrder(t *testing.T) {
for _, staged := range []bool{false, true} {
- for _, status := range []string{"done", "cancelled", "approved"} {
+ for _, status := range []string{"done", "cancelled", "approved", "wont_do"} {
t.Run(fmt.Sprintf("staged=%t/%s", staged, status), func(t *testing.T) {
ws := dbfx.Workspace(t, "Batch stage selection", "batch-stage-selection", testutil.Cols{"issue_prefix": "BST"})
fx := testutil.New(testPool, ws, testUserID)
fx.Member(t, ws, testUserID, "owner")
fx.Insert(t, "issue_status", testutil.Cols{"workspace_id": ws, "key": "approved", "name": "Approved", "category": "done", "color": "#123456"})
+ fx.Insert(t, "issue_status", testutil.Cols{"workspace_id": ws, "key": "wont_do", "name": "Won't Do", "category": "closed", "color": "#654321"})
var parents, agents []string
var children [][]string
for p := range 2 {
@@ -235,6 +236,7 @@ func TestBatchChildDonePreservesRepresentativeAndParentOrder(t *testing.T) {
if !slices.Equal(notified, []string{parents[1], parents[0]}) {
t.Fatalf("notification order=%v, want second parent then first", notified)
}
+ cancelledLike := status == "cancelled" || status == "wont_do"
for p, parent := range parents {
if countSystemCommentsOn(t, parent) != 1 || countPendingTasksForAgent(t, parent, agents[p]) != 1 {
t.Fatal("each parent must receive exactly one comment and one pending run")
@@ -247,11 +249,26 @@ func TestBatchChildDonePreservesRepresentativeAndParentOrder(t *testing.T) {
if !strings.Contains(content, "together in a batch update") || !strings.Contains(content, "](mention://issue/"+rep+")") {
t.Fatalf("lost batch wording or first representative: %s", content)
}
- if staged && (!strings.Contains(content, "Stage 7 of this issue is complete") || !strings.Contains(content, "Stage 2: 1/1 done; Stage 7: 2/2 done; Stage 20: 0/1 done (next)") || !strings.Contains(content, "Stage 20 is next")) {
- t.Fatalf("inaccurate final-state summary: %s", content)
+ if staged {
+ if cancelledLike {
+ if !strings.Contains(content, "Stage 7 of this issue is closed") ||
+ !strings.Contains(content, "Stage 2: 0/1 done, 1 cancelled; Stage 7: 0/2 done, 2 cancelled; Stage 20: 0/1 done (next)") ||
+ !strings.Contains(content, "Stage 20 is next") ||
+ !strings.Contains(content, "confirm that the cancelled work is not a dependency") {
+ t.Fatalf("inaccurate cancelled-stage summary: %s", content)
+ }
+ } else if !strings.Contains(content, "Stage 7 of this issue is complete") || !strings.Contains(content, "Stage 2: 1/1 done; Stage 7: 2/2 done; Stage 20: 0/1 done (next)") || !strings.Contains(content, "Stage 20 is next") {
+ t.Fatalf("inaccurate final-state summary: %s", content)
+ }
}
- if !staged && !strings.Contains(content, "All sub-issues are complete") {
- t.Fatalf("lost unstaged completion: %s", content)
+ if !staged {
+ if cancelledLike {
+ if !strings.Contains(content, "All sub-issues are closed") || !strings.Contains(content, "confirm that the cancelled work is not required") {
+ t.Fatalf("inaccurate unstaged cancellation summary: %s", content)
+ }
+ } else if !strings.Contains(content, "All sub-issues are complete") {
+ t.Fatalf("lost unstaged completion: %s", content)
+ }
}
if got, want := triggerCommentIDForAgentTask(t, parent, agents[p]), systemCommentIDOn(t, parent); got != want {
t.Fatalf("run trigger=%s, want final comment %s", got, want)
@@ -284,10 +301,11 @@ func BenchmarkBatchStageSelection(b *testing.B) {
children[0].Status = shape.firstStatus
// Both algorithms use the same pre-resolved snapshot as production.
// Fixture construction and status resolution are outside the timed loop.
- terminal, err := resolveTerminalChildren(children, func(c db.Issue) (string, error) { return c.Status, nil })
+ statuses, err := resolveChildStatuses(children, func(c db.Issue) (string, error) { return c.Status, nil })
if err != nil {
b.Fatal(err)
}
+ terminal := statuses.isTerminal
for _, tc := range []struct {
name string
pick func([]db.Issue, []db.Issue, func(db.Issue) bool) (db.Issue, bool)
diff --git a/server/internal/handler/issue_child_done_cancelled_batch_review_test.go b/server/internal/handler/issue_child_done_cancelled_batch_review_test.go
new file mode 100644
index 0000000000..2534fdfb2a
--- /dev/null
+++ b/server/internal/handler/issue_child_done_cancelled_batch_review_test.go
@@ -0,0 +1,69 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestBatchChildDoneNamedStageHistoricalCancellationStillWarns(t *testing.T) {
+ fx := newStagedBatchFixture(t)
+
+ // Add a third Stage 2 child so one can already be cancelled while at least
+ // two remaining children transition to done together in the closing batch.
+ cw := httptest.NewRecorder()
+ creq := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{
+ "title": "batch-stage historical-cancel child " + time.Now().Format(time.RFC3339Nano),
+ "status": "in_progress",
+ "parent_issue_id": fx.parent.ID,
+ })
+ testHandler.CreateIssue(cw, creq)
+ if cw.Code != 201 {
+ t.Fatalf("create extra child: expected 201, got %d: %s", cw.Code, cw.Body.String())
+ }
+ var extra IssueResponse
+ if err := json.NewDecoder(cw.Body).Decode(&extra); err != nil {
+ t.Fatalf("decode extra child: %v", err)
+ }
+ if _, err := testPool.Exec(context.Background(),
+ `UPDATE issue SET stage = $2 WHERE id = $1`, extra.ID, 2); err != nil {
+ t.Fatalf("set extra child stage: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, extra.ID)
+ })
+
+ // This cancellation is historical by the time the later batch closes Stage 2.
+ // Stage 1 is still open, so it must not emit a parent completion comment yet.
+ batchSetStatus(t, []string{fx.stage2[0].ID}, "cancelled")
+ if got := countSystemCommentsOn(t, fx.parent.ID); got != 0 {
+ t.Fatalf("historical cancellation must not close the blocked stage, got %d comments", got)
+ }
+
+ // Close Stage 1 and finish the two remaining Stage 2 children in one batch.
+ // The named Stage 2 already contains the cancelled child above, so the final
+ // advance instruction must still include the dependency-confirmation warning.
+ batchSetStatus(t, []string{
+ fx.stage1[0].ID,
+ fx.stage1[1].ID,
+ fx.stage2[1].ID,
+ extra.ID,
+ }, "done")
+
+ if got := countSystemCommentsOn(t, fx.parent.ID); got != 1 {
+ t.Fatalf("expected exactly 1 final system comment, got %d", got)
+ }
+ content, _, _, _ := systemCommentOn(t, fx.parent.ID)
+ if !strings.Contains(content, "Stage 2 of this issue is closed") {
+ t.Errorf("expected Stage 2 closed announcement, got: %s", content)
+ }
+ if !strings.Contains(content, "Stage 2: 2/3 done, 1 cancelled") {
+ t.Errorf("expected final Stage 2 cancellation summary, got: %s", content)
+ }
+ if !strings.Contains(content, "confirm that the cancelled work is not a dependency") {
+ t.Errorf("expected cancellation dependency warning, got: %s", content)
+ }
+}
diff --git a/server/internal/handler/issue_child_done_cancelled_test.go b/server/internal/handler/issue_child_done_cancelled_test.go
new file mode 100644
index 0000000000..5a089faac4
--- /dev/null
+++ b/server/internal/handler/issue_child_done_cancelled_test.go
@@ -0,0 +1,103 @@
+package handler
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+func TestStageProgressSummarySeparatesCancelledFromDone(t *testing.T) {
+ children := []db.Issue{
+ child(1, "done"),
+ child(2, "cancelled"), child(2, "cancelled"),
+ child(3, "backlog"),
+ }
+
+ summary, next := stageProgressSummary(children, 2, literalChildStatus)
+ want := "Stage 1: 1/1 done; Stage 2: 0/2 done, 2 cancelled; Stage 3: 0/1 done (next)"
+ if summary != want {
+ t.Fatalf("summary = %q, want %q", summary, want)
+ }
+ if next != 3 {
+ t.Fatalf("nextStage = %d, want 3", next)
+ }
+}
+
+func TestResolvedChildStatusesKeepCanonicalCancelled(t *testing.T) {
+ doneID := pgtype.UUID{Bytes: [16]byte{1}, Valid: true}
+ cancelledID := pgtype.UUID{Bytes: [16]byte{2}, Valid: true}
+ children := []db.Issue{
+ {ID: doneID, Status: "approved", Stage: pgtype.Int4{Int32: 1, Valid: true}},
+ {ID: cancelledID, Status: "wont_do", Stage: pgtype.Int4{Int32: 1, Valid: true}},
+ }
+
+ statuses, err := resolveChildStatuses(children, func(c db.Issue) (string, error) {
+ switch c.Status {
+ case "approved":
+ return "done", nil
+ case "wont_do":
+ return "cancelled", nil
+ default:
+ return c.Status, nil
+ }
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got := statuses.status(children[1]); got != "cancelled" {
+ t.Fatalf("canonical status = %q, want cancelled", got)
+ }
+ if !statuses.isTerminal(children[1]) {
+ t.Fatal("canonical cancelled status must still close the barrier")
+ }
+
+ summary, _ := stageProgressSummary(children, 1, statuses.status)
+ if want := "Stage 1: 1/2 done, 1 cancelled"; summary != want {
+ t.Fatalf("summary = %q, want %q", summary, want)
+ }
+}
+
+func TestBatchClosedScopeHasCancelled(t *testing.T) {
+ stage2Cancelled := child(2, "cancelled")
+ stage2Cancelled.ID = pgtype.UUID{Bytes: [16]byte{2}, Valid: true}
+ stage7Done := child(7, "done")
+ stage7Done.ID = pgtype.UUID{Bytes: [16]byte{7}, Valid: true}
+ stage20Cancelled := child(20, "cancelled")
+ stage20Cancelled.ID = pgtype.UUID{Bytes: [16]byte{20}, Valid: true}
+ children := []db.Issue{stage2Cancelled, stage7Done, stage20Cancelled}
+ statusOf := func(c db.Issue) string { return c.Status }
+
+ t.Run("lower stage cancelled in the same batch warns", func(t *testing.T) {
+ if !batchClosedScopeHasCancelled(children, []db.Issue{stage2Cancelled, stage7Done}, 7, statusOf) {
+ t.Fatal("expected cancellation in a lower stage closed by the same batch to be reported")
+ }
+ })
+
+ t.Run("later unopened stage cancellation is ignored", func(t *testing.T) {
+ if batchClosedScopeHasCancelled(children, []db.Issue{stage7Done, stage20Cancelled}, 7, statusOf) {
+ t.Fatal("a cancellation above the highest closed stage must not affect the current advance decision")
+ }
+ })
+
+ t.Run("historical lower-stage cancellation is not repeated", func(t *testing.T) {
+ if batchClosedScopeHasCancelled(children, []db.Issue{stage7Done}, 7, statusOf) {
+ t.Fatal("a lower-stage cancellation outside this batch must not re-trigger the warning")
+ }
+ })
+}
+
+func TestStageAdvanceInstructionWarnsOnCancelledWork(t *testing.T) {
+ got := stageAdvanceInstruction(3, "parent-id", true)
+ for _, want := range []string{
+ "Stage 3 is next",
+ "confirm that the cancelled work is not a dependency",
+ "do not promote or create the next stage yet",
+ "post a comment to confirm first",
+ } {
+ if !strings.Contains(got, want) {
+ t.Fatalf("instruction missing %q: %s", want, got)
+ }
+ }
+}
diff --git a/server/internal/handler/issue_child_done_stage_test.go b/server/internal/handler/issue_child_done_stage_test.go
index ab3102e0ba..9126536005 100644
--- a/server/internal/handler/issue_child_done_stage_test.go
+++ b/server/internal/handler/issue_child_done_stage_test.go
@@ -109,7 +109,7 @@ func TestStageProgressSummary(t *testing.T) {
child(2, "backlog"), child(2, "backlog"), child(2, "backlog"), child(2, "backlog"),
child(3, "backlog"), child(3, "backlog"),
}
- summary, next := stageProgressSummary(children, 1, literalTerminalChild)
+ summary, next := stageProgressSummary(children, 1, literalChildStatus)
want := "Stage 1: 3/3 done; Stage 2: 0/4 done (next); Stage 3: 0/2 done"
if summary != want {
t.Fatalf("summary = %q, want %q", summary, want)
@@ -124,7 +124,7 @@ func TestStageProgressSummary_FinalStageNoNext(t *testing.T) {
child(1, "done"), child(1, "done"),
child(2, "done"),
}
- _, next := stageProgressSummary(children, 2, literalTerminalChild)
+ _, next := stageProgressSummary(children, 2, literalChildStatus)
if next != 0 {
t.Fatalf("nextStage = %d, want 0 (no further stages)", next)
}
@@ -137,7 +137,7 @@ func TestStageProgressSummary_SkipsUnstaged(t *testing.T) {
child(1, "done"), child(1, "done"),
child(2, "backlog"),
}
- summary, next := stageProgressSummary(children, 1, literalTerminalChild)
+ summary, next := stageProgressSummary(children, 1, literalChildStatus)
want := "Stage 1: 2/2 done; Stage 2: 0/1 done (next)"
if summary != want {
t.Fatalf("summary = %q, want %q", summary, want)
@@ -155,14 +155,14 @@ func TestStageAdvanceInstruction(t *testing.T) {
const parentID = "parent-uuid"
t.Run("a known next stage points the leader at it", func(t *testing.T) {
- got := stageAdvanceInstruction(3, parentID)
+ got := stageAdvanceInstruction(3, parentID, false)
if !strings.Contains(got, "Stage 3 is next") {
t.Fatalf("expected next-stage instruction, got %q", got)
}
})
t.Run("no created next stage does not assert finality", func(t *testing.T) {
- got := stageAdvanceInstruction(0, parentID)
+ got := stageAdvanceInstruction(0, parentID, false)
// Regression guard for MUL-4062: an intermediate stage in a lazily
// created workflow also reaches nextStage==0, so the message must not
// claim this was definitively the final stage.
@@ -229,6 +229,10 @@ func TestStageBarrierClosed_UnstagedIgnoredInStagedSet(t *testing.T) {
})
}
+func literalChildStatus(c db.Issue) string {
+ return c.Status
+}
+
// literalTerminalChild is the pre-MUL-6243 terminal test: it reads the status
// literal directly, with no catalog resolution. The stage-barrier logic these
// tests cover is pure and operates on CANONICAL statuses, so pinning it with a