Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(workflows): explain inherited task step mismatches (#10039)
Multica Eve32b3c076515f
diff --git a/apps/docs/content/docs/issue-wakeups.mdx b/apps/docs/content/docs/issue-wakeups.mdxindex ec79ceeddb..9a7416095e 100644--- a/apps/docs/content/docs/issue-wakeups.mdx+++ b/apps/docs/content/docs/issue-wakeups.mdx@@ -78,6 +78,22 @@ When the issue's assignee is an agent, members' comments already trigger it. A "- If the same agent already has a run waiting to start on the issue, the wakeup joins that run instead of starting another one.- While a wakeup is waiting, the issue header shows what the issue is waiting for, such as "Ops helper: Waiting for a reply". Click it to jump to the Wakeups section.+## Workflow steps on continued work [#workflow-steps]++A run has a workflow step binding as well as an execution ID. A new execution ID or a reused agent conversation does not decide which step it can advance.++| How work starts | Step binding |+|---|---|+| A wakeup created by an agent during a run | Inherits the source run's step, when it has one. |+| A wakeup created by a member that starts a new run | The issue's current status when the wakeup fires. |+| An automatic retry | Keeps the parent run's binding. |+| A member explicitly reruns the work | The issue's current status when the new run is queued. |+| A wakeup joins an existing run waiting to start | Keeps that waiting run's binding. |++Named workflows and **Default** workflows with handoffs protect against stale status changes. If another actor moves the issue away from a run's bound step, that run cannot advance the issue. Its brief shows both steps and asks it to leave the current status unchanged and comment if attention is needed. A rejected status change returns `409 workflow_step_moved`; retrying it does not refresh the binding.++To continue from the new state, a member should review the external move and explicitly rerun the work from the execution log. The old run is not automatically rebound.+## View and manage wakeups [#manage]The Wakeups section of the issue sidebar lists the issue's rules: the condition, who is woken, when it fires next, and how long is left. Click a rule for its details, including its source, its deadline, its instruction, and its **trigger history** (the latest runs, whether each posted a comment, and what each silent check found).diff --git a/docs/engineering/issue-wakeups.md b/docs/engineering/issue-wakeups.mdindex ece401332b..9154b22117 100644--- a/docs/engineering/issue-wakeups.md+++ b/docs/engineering/issue-wakeups.md@@ -7,6 +7,34 @@ sub-issue status, a linked pull request's state); business completion is stilldecided by the agent after reading current state. There is no sleeping processor second run lifecycle.+## Workflow step bindings++Wakeup tasks and automatic retries can be continuations of older work. Their+new task IDs and provider-session reuse do not determine their workflow bindings:++| Task source | `workflow_step` |+|---|---|+| Agent-created wakeup (`CreateWakeupTask`) | The registering task's step, falling back to the current issue status when no source step exists. |+| Member-created wakeup that creates a task | The issue status at dispatch. |+| Automatic retry (`CreateRetryTask`) | The parent task's binding, including NULL. |+| Member-requested rerun (`RerunIssue`) | The issue status when `CreateAgentTask` queues the new task. |+| Wakeup joined into an existing pending task | The pending task's binding is unchanged. |++For named workflows and Default workflows with handoffs, the claim brief uses+the same step-mismatch predicate as the status-write guard. A mismatch takes+precedence over assignee, observer and handlerless-step instructions. The brief+names the bound step and current issue status, identifies the last status mover+when available, and includes the workflow's status catalog without any status+commands. It explicitly overrides runtime start/finish status rules, including+on older daemons. The existing server-rendered `project_workflow.brief` wire field+carries this text; no daemon upgrade or protocol extension is required.++The write guard still returns `409 workflow_step_moved`. Claiming or retrying+does not rebind a stale continuation. After reviewing an external move, a member+can explicitly rerun the work to create a task bound to the current status.+Issues without a project and Default workflows without handoffs retain their+existing behavior.+## Product contractThe shared web/Desktop issue sidebar lists event and time wakeups together,diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.goindex 1c178bf3c7..a911d079b1 100644--- a/server/internal/handler/agent.go+++ b/server/internal/handler/agent.go@@ -373,6 +373,8 @@ type TaskIssueStatusData struct {// in the per-turn prompt, never in the cached runtime brief.type TaskProjectWorkflowData struct {Brief string `json:"brief"`+ // stepMoved selects the server-side leader briefing without changing the wire.+ stepMoved bool}// ClaimParentIssue points a sub-issue's run at its parent issue, where thediff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex 5a47f04639..6981cd47c6 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -3208,7 +3208,9 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQuleaderWorkflow := leaderNoWorkflowif projectWorkflow != nil {leaderWorkflow = leaderWorkflowCurrentDaemon- if legacyRuntimeRules {+ if projectWorkflow.stepMoved {+ leaderWorkflow = leaderWorkflowStepMoved+ } else if legacyRuntimeRules {leaderWorkflow = leaderWorkflowLegacyDaemon}}diff --git a/server/internal/handler/issue_workflow_entry.go b/server/internal/handler/issue_workflow_entry.goindex 5682d7660f..3446b683e0 100644--- a/server/internal/handler/issue_workflow_entry.go+++ b/server/internal/handler/issue_workflow_entry.go@@ -81,8 +81,7 @@ func (h *Handler) applyIssueWorkflow(ctx context.Context, prev db.Issue, params// made for a step the issue has left, and applying it would undo that move.// Default without handoffs keeps the pre-workflow behavior, so workspaces// that never adopt workflows see no change.- if run != nil && run.WorkflowStep.Valid && run.WorkflowStep.String != prev.Status &&- (!def.IsDefault || def.HandsOffAnywhere()) &&+ if workflowStepMoved(def, prev.Status, run) &&statusExplicit && params.Status.Valid && params.Status.String != prev.Status {return nil, h.stepMovedError(ctx, prev, run.WorkflowStep.String)}@@ -116,6 +115,13 @@ func (h *Handler) applyIssueWorkflow(ctx context.Context, prev db.Issue, paramsreturn &workflowHandoff{def: *def, step: step, project: project}, nil}+// workflowStepMoved shares the step guard with the claim brief so a run is+// never told to advance a step its status changes cannot act on.+func workflowStepMoved(def *issueworkflow.Definition, status string, run *db.AgentTaskQueue) bool {+ return def != nil && run != nil && run.WorkflowStep.Valid && run.WorkflowStep.String != status &&+ (!def.IsDefault || def.HandsOffAnywhere())+}+// workflowHandoffPayload describes a handoff on the issue:updated event, so// the activity log can record the status change and the handoff as one// timeline entry.@@ -223,11 +229,16 @@ func (h *Handler) stepMovedError(ctx context.Context, issue db.Issue, step strinStepName: resolver.Name(ctx, h.Queries, step),Current: issue.Status,CurrentName: resolver.Name(ctx, h.Queries, issue.Status),+ MovedBy: h.lastIssueStatusMover(ctx, issue),}+ return out+}++func (h *Handler) lastIssueStatusMover(ctx context.Context, issue db.Issue) string {if last, err := h.Queries.GetLastIssueStatusChange(ctx, issue.ID); err == nil && last.ActorID.Valid {- out.MovedBy = h.actorDisplayName(ctx, issue.WorkspaceID, last.ActorType.String, last.ActorID)+ return h.actorDisplayName(ctx, issue.WorkspaceID, last.ActorType.String, last.ActorID)}- return out+ return ""}// workflowHandoffBrief renders the brief a handoff's agent or squad will@@ -361,13 +372,17 @@ func (h *Handler) claimProjectWorkflow(ctx context.Context, issue db.Issue, task}in := h.workflowBriefInput(ctx, issue, *def, project)in.LegacyRuntimeRules = legacyRuntimeRules- if !taskRunsForAssignee(issue, task) {+ stepMoved := workflowStepMoved(def, issue.Status, task)+ if stepMoved {+ in.BoundStep = task.WorkflowStep.String+ in.MovedBy = h.lastIssueStatusMover(ctx, issue)+ } else if !taskRunsForAssignee(issue, task) {in.Observer = trueif issue.AssigneeType.Valid && issue.AssigneeID.Valid {in.AssigneeName = h.actorDisplayName(ctx, issue.WorkspaceID, issue.AssigneeType.String, issue.AssigneeID)}}- return &TaskProjectWorkflowData{Brief: issueworkflow.Brief(in)}+ return &TaskProjectWorkflowData{Brief: issueworkflow.Brief(in), stepMoved: stepMoved}}// taskRunsForAssignee reports whether a run works on the issue as itsdiff --git a/server/internal/handler/issue_workflow_test.go b/server/internal/handler/issue_workflow_test.goindex 2deb93c70c..128705618a 100644--- a/server/internal/handler/issue_workflow_test.go+++ b/server/internal/handler/issue_workflow_test.go@@ -900,6 +900,10 @@ func TestClaimCarriesProjectWorkflow(t *testing.T) {if testHandler.claimProjectWorkflow(context.Background(), quietIssue, nil, false) != nil {t.Fatal("a Default project without handoffs must not carry a workflow")}+ stale := db.AgentTaskQueue{AgentID: util.MustParseUUID(agentID), WorkflowStep: pgtype.Text{String: "waiting_for_merge", Valid: true}}+ if testHandler.claimProjectWorkflow(context.Background(), quietIssue, &stale, false) != nil {+ t.Fatal("a Default project without handoffs must not restrict a stale binding")+ }projectID := deliveryProject(t, "Workflow claim project", agentID)issueID := dbfx.Issue(t, "claim context", testutil.Cols{@@ -918,6 +922,9 @@ func TestClaimCarriesProjectWorkflow(t *testing.T) {t.Fatalf("assignee brief is missing %q:\n%s", want, brief)}}+ if matched := claimBriefForTest(t, issueID, db.AgentTaskQueue{AgentID: util.MustParseUUID(agentID), WorkflowStep: pgtype.Text{String: "in_progress", Valid: true}}); matched != brief {+ t.Fatalf("matching and NULL bindings must receive the same brief:\n%s", matched)+ }// Any other agent on the issue — mentioned in a comment, say — gets the// statuses and is told to leave them to the assignee.@@ -933,6 +940,76 @@ func TestClaimCarriesProjectWorkflow(t *testing.T) {}}+func TestClaimExplainsMovedWorkflowStep(t *testing.T) {+ seedTestCatalog(t)+ agentID := seededReadyAgentID(t)+ projectID := deliveryProject(t, "Workflow continuation project", agentID)+ issueID := dbfx.Issue(t, "continued after an external move", testutil.Cols{+ "project_id": projectID, "status": "in_progress", "assignee_type": "agent", "assignee_id": agentID,+ })+ taskID := dbfx.Task(t, agentID, testutil.Cols{+ "issue_id": issueID, "runtime_id": handlerTestRuntimeID(t), "status": "running",+ "started_at": time.Now(), "workflow_step": "waiting_for_merge",+ })+ ctx := context.Background()+ issue, err := testHandler.Queries.GetIssue(ctx, util.MustParseUUID(issueID))+ if err != nil {+ t.Fatal(err)+ }+ task, err := testHandler.Queries.GetAgentTask(ctx, util.MustParseUUID(taskID))+ if err != nil {+ t.Fatal(err)+ }+ other := util.MustParseUUID(dbfx.Agent(t, "Workflow continuation observer", handlerTestRuntimeID(t)))+ for _, observer := range []bool{false, true} {+ for _, legacy := range []bool{false, true} {+ t.Run(fmt.Sprintf("observer=%v/legacy=%v", observer, legacy), func(t *testing.T) {+ claim := task+ if observer {+ claim.AgentID = other+ }+ got := testHandler.claimProjectWorkflow(ctx, issue, &claim, legacy)+ if got == nil {+ t.Fatal("missing workflow brief")+ }+ for _, want := range []string{`bound to "waiting_for_merge"`, `"in_progress"`, "Do not change", "member"} {+ if !strings.Contains(got.Brief, want) {+ t.Errorf("brief missing %q:\n%s", want, got.Brief)+ }+ }+ for _, leak := range []string{"Implement it and open a PR.", "Your moves:", "multica issue status", "unless you are explicitly asked", "Before your run ends, either run"} {+ if strings.Contains(got.Brief, leak) {+ t.Errorf("stale run received %q:\n%s", leak, got.Brief)+ }+ }+ })+ }+ }+ if got := taskWorkflowStep(t, taskID); got != "waiting_for_merge" {+ t.Fatalf("claim rebound the task to %q", got)+ }+ body := agentUpdateIssue(t, issueID, agentID, taskID, map[string]any{"status": "in_review"}).Want(http.StatusConflict).Map()+ if body["code"] != "workflow_step_moved" || body["current_status"] != "in_progress" {+ t.Fatalf("stale run's rejection = %v", body)+ }+ if status, _, _ := issueStatusAndAssignee(t, issueID); status != "in_progress" {+ t.Fatalf("refused change moved issue to %q", status)+ }+ dbfx.Insert(t, "activity_log", testutil.Cols{+ "workspace_id": testWorkspaceID, "issue_id": issueID, "actor_type": "member", "actor_id": testUserID,+ "action": "status_changed", "details": `{"from":"waiting_for_merge","to":"in_progress"}`,+ })+ if brief := claimBriefForTest(t, issueID, task); !strings.Contains(brief, "last moved by "+handlerTestName) {+ t.Fatalf("brief lost the known status mover:\n%s", brief)+ }+ named := createTestWorkflow(t, "Continuation "+workflowTestSuffix(), "in_progress", "in_review")+ setProjectWorkflow(t, projectID, map[string]any{"workflow_id": named.ID}).Want(http.StatusOK)+ if brief := claimBriefForTest(t, issueID, task); !strings.Contains(brief, `bound to "waiting_for_merge"`) || strings.Contains(brief, "multica issue status") {+ t.Fatalf("named workflow without handoffs lost the step guard:\n%s", brief)+ }+ agentUpdateIssue(t, issueID, agentID, taskID, map[string]any{"status": "in_review"}).Want(http.StatusConflict)+}+// claimBriefForTest renders the workflow brief a claim of task would carry// for the issue as it is now.func claimBriefForTest(t *testing.T, issueID string, task db.AgentTaskQueue) string {diff --git a/server/internal/handler/squad_briefing.go b/server/internal/handler/squad_briefing.goindex 86c39884de..7cf93c8427 100644--- a/server/internal/handler/squad_briefing.go+++ b/server/internal/handler/squad_briefing.go@@ -136,8 +136,19 @@ const (// in_progress first and in_review on delivery, so responsibility 6 has// to rule those moves out for this issue.leaderWorkflowLegacyDaemon+ // leaderWorkflowStepMoved: the run's binding no longer matches the issue,+ // so it must leave status unchanged even when its squad owns the issue.+ leaderWorkflowStepMoved)+const squadParentStatusStepMoved = `6. **Leave the parent issue's status unchanged for this run.** This issue+ is assigned to your squad, but this run's workflow binding no longer matches+ the issue's current step. Follow the explanation in ` + "`" + `[Project workflow]` + "`" + `.+ Keep the current status even when you confirm the overall goal is met; do+ not change it to mark progress or delivery. This overrides the status rules+ in your runtime instructions. Leave a comment if something needs attention;+ a member can review the current state and explicitly rerun the work.`+// squadParentStatusOwnedInWorkflow is responsibility 6 for an owning leader// whose issue follows a project workflow that came with the claim (MUL-8145).// The workflow may list neither in_progress nor in_review — the server rejects@@ -227,6 +238,8 @@ const squadSteerRule = `- A worker already running on this issue gets a new commfunc squadOperatingProtocolFor(ownsIssueStatus bool, workflow leaderWorkflow) string {status := squadParentStatusNotOwnedswitch {+ case ownsIssueStatus && workflow == leaderWorkflowStepMoved:+ status = squadParentStatusStepMovedcase ownsIssueStatus && workflow == leaderWorkflowCurrentDaemon:status = squadParentStatusOwnedInWorkflowcase ownsIssueStatus && workflow == leaderWorkflowLegacyDaemon:diff --git a/server/internal/handler/squad_briefing_claim_test.go b/server/internal/handler/squad_briefing_claim_test.goindex 69479b7273..35207fa67e 100644--- a/server/internal/handler/squad_briefing_claim_test.go+++ b/server/internal/handler/squad_briefing_claim_test.go@@ -3,10 +3,14 @@ package handlerimport ("context""encoding/json"+ "fmt""net/http""net/http/httptest""strings""testing"++ "github.com/multica-ai/multica/server/internal/testutil"+ "github.com/multica-ai/multica/server/pkg/protocol")// claimAgentInstructionsForTest claims the next queued task for runtimeID and@@ -151,6 +155,54 @@ func TestClaim_LeaderTaskFromCommentMention_InjectsBriefing(t *testing.T) {}}+func TestClaim_LeaderTaskWithMovedStepLeavesStatusUnchanged(t *testing.T) {+ seedTestCatalog(t)+ for _, bound := range []string{"waiting_for_merge", "in_progress", ""} {+ for _, legacy := range []bool{false, true} {+ t.Run(fmt.Sprintf("bound=%s/legacy=%v", bound, legacy), func(t *testing.T) {+ fx := newSquadBriefingClaimFixture(t, t.Context(), "Workflow leader")+ projectID := deliveryProject(t, "Leader workflow project", fx.AgentID)+ dbfx.Exec(t, `UPDATE issue SET project_id=$2,status='in_progress',assignee_type='squad',assignee_id=$3 WHERE id=$1`, fx.IssueID, projectID, fx.SquadID)+ cols := testutil.Cols{+ "runtime_id": fx.RuntimeID, "issue_id": fx.IssueID,+ "is_leader_task": true, "squad_id": fx.SquadID,+ }+ if bound != "" {+ cols["workflow_step"] = bound+ }+ taskID := dbfx.Task(t, fx.AgentID, cols)+ req := withURLParam(newOwnerDaemonRequest(http.MethodPost, "/api/daemon/runtimes/"+fx.RuntimeID+"/tasks/claim", nil), "runtimeId", fx.RuntimeID)+ if !legacy {+ req.Header.Set("X-Client-Capabilities", protocol.DaemonCapabilityWorkflowStatusRulesV1)+ }+ var resp struct {+ Task *AgentTaskResponse `json:"task"`+ }+ testutil.Call(t, testHandler.ClaimTaskByRuntime, req).Want(http.StatusOK).JSON(&resp)+ if resp.Task == nil || resp.Task.ID != taskID || !resp.Task.IsLeaderTask || resp.Task.Agent == nil || resp.Task.ProjectWorkflow == nil {+ t.Fatalf("missing workflow leader claim: %+v", resp.Task)+ }+ instructions := resp.Task.Agent.Instructions+ if !strings.Contains(instructions, "## Squad Roster") {+ t.Fatal("workflow restriction removed the leader's coordination briefing")+ }+ if bound == "waiting_for_merge" {+ if !strings.Contains(instructions, "Leave the parent issue's status unchanged") || strings.Contains(instructions, "run that block's Step done command") {+ t.Fatalf("stale leader's instructions contradict its workflow brief:\n%s", instructions)+ }+ for _, move := range builtInParentMoves {+ if strings.Contains(strings.Join(strings.Fields(instructions), " "), move) {+ t.Errorf("stale leader received built-in move %q", move)+ }+ }+ } else if !strings.Contains(instructions, "run that block's Step done command") {+ t.Fatalf("current or unbound leader lost its wrap-up instruction:\n%s", instructions)+ }+ })+ }+ }+}+// TestClaim_NonLeaderTask_NoBriefing guards the negative: a task that is NOT a// leader task (is_leader_task=false), even with a squad_id present, must not// receive the briefing. This keeps worker/mention runs free of leader framing.diff --git a/server/internal/handler/squad_workflow_status_contract_test.go b/server/internal/handler/squad_workflow_status_contract_test.goindex 419451fde1..b6c8f93cac 100644--- a/server/internal/handler/squad_workflow_status_contract_test.go+++ b/server/internal/handler/squad_workflow_status_contract_test.go@@ -98,8 +98,10 @@ func TestOwningLeaderWithoutWorkflowKeepsBuiltInMoves(t *testing.T) {// A guest leader gets the prohibition whether or not the issue has a// workflow: the workflow never widens status authority.func TestGuestLeaderProtocolIgnoresWorkflow(t *testing.T) {- if squadOperatingProtocolFor(false, leaderWorkflowCurrentDaemon) != squadOperatingProtocolFor(false, leaderNoWorkflow) || squadOperatingProtocolFor(false, leaderWorkflowLegacyDaemon) != squadOperatingProtocolFor(false, leaderNoWorkflow) {- t.Fatal("guest leader protocol must not vary with the project workflow")+ for _, workflow := range []leaderWorkflow{leaderWorkflowCurrentDaemon, leaderWorkflowLegacyDaemon, leaderWorkflowStepMoved} {+ if squadOperatingProtocolFor(false, workflow) != squadOperatingProtocolFor(false, leaderNoWorkflow) {+ t.Fatal("guest leader protocol must not vary with the project workflow")+ }}if strings.Contains(squadOperatingProtocolFor(false, leaderWorkflowCurrentDaemon), "Step done") {t.Fatal("guest leader protocol must not hand out the Step done move")diff --git a/server/internal/issueworkflow/issueworkflow.go b/server/internal/issueworkflow/issueworkflow.goindex e9b823a55d..2f55de0fd3 100644--- a/server/internal/issueworkflow/issueworkflow.go+++ b/server/internal/issueworkflow/issueworkflow.go@@ -732,6 +732,12 @@ type BriefInput struct {ProjectName stringStatusKey stringIssueIdentifier string+ // BoundStep is the task's effective step when its binding must be respected.+ // A different StatusKey renders a continuation brief without status moves.+ // Empty preserves the normal handoff, preview and unbound-run brief.+ BoundStep string+ // MovedBy names whoever last changed the status, when known.+ MovedBy string// StatusName resolves a catalog key to its display name.StatusName func(key string) string// HandlerName describes who a step hands off to, e.g. "Sentinel" or@@ -768,6 +774,7 @@ type BriefInput struct {// names are kept to one line.func Brief(in BriefInput) string {step, _ := in.Workflow.Step(in.StatusKey)+ stepMoved := in.BoundStep != "" && in.BoundStep != in.StatusKeyname := func(key string) string {if in.StatusName == nil {return key@@ -798,17 +805,25 @@ func Brief(in BriefInput) string {// An older daemon still states the built-in rules itself, so its brief// keeps the per-step wording rather than add a second in_progress rule.var span handlerlessSpan- if !in.Observer && !in.LegacyRuntimeRules {+ if !stepMoved && !in.Observer && !in.LegacyRuntimeRules {span = in.Workflow.handlerlessSpan(in.StatusKey)}- if in.LegacyRuntimeRules {+ if in.LegacyRuntimeRules && !stepMoved {b.WriteString("This workflow replaces the status rules in your runtime instructions: use only the status keys below")if !in.Workflow.Has(issuestatus.InReview) {fmt.Fprintf(&b, ", never `%s`", issuestatus.InReview)}b.WriteString(".\n")}- if in.Observer {+ if stepMoved {+ mover := briefLine(in.MovedBy)+ if mover == "" {+ mover = "someone else"+ }+ fmt.Fprintf(&b, "This run remains bound to %s, but %s is now at %s (last moved by %s).\n",+ statusLabel(name(in.BoundStep), in.BoundStep), in.IssueIdentifier, statusLabel(name(in.StatusKey), in.StatusKey), mover)+ b.WriteString("Do not change the issue's status in this run, including when starting or finishing work; this overrides the status rules in your runtime instructions. Do not retry a refused status change. Leave a comment if something needs attention. A member can review the current state and explicitly rerun the work.\n")+ } else if in.Observer {assignee := "is unassigned"if who := briefLine(in.AssigneeName); who != "" {assignee = "is assigned to " + who@@ -853,6 +868,9 @@ func Brief(in BriefInput) string {}b.WriteString("\n")}+ if stepMoved {+ return b.String()+ }if in.Observer {b.WriteString("\nMoving the issue into a step that hands off reassigns it to that step's handler and starts their run.\n")return b.String()diff --git a/server/internal/issueworkflow/issueworkflow_test.go b/server/internal/issueworkflow/issueworkflow_test.goindex d30b4f11e7..c463ae5033 100644--- a/server/internal/issueworkflow/issueworkflow_test.go+++ b/server/internal/issueworkflow/issueworkflow_test.go@@ -2,6 +2,7 @@ package issueworkflowimport ("errors"+ "fmt""reflect""strings""testing"@@ -287,6 +288,58 @@ func TestBriefNamesStepCommandsAndHandlers(t *testing.T) {}}+func TestBriefForMovedStep(t *testing.T) {+ for _, current := range []string{"implement", "todo"} {+ for _, observer := range []bool{false, true} {+ for _, legacy := range []bool{false, true} {+ t.Run(fmt.Sprintf("%s/observer=%v/legacy=%v", current, observer, legacy), func(t *testing.T) {+ in := BriefInput{+ Workflow: devDefinition(), StatusKey: current, BoundStep: "waiting_for_merge",+ IssueIdentifier: "MUL-7", Observer: observer, LegacyRuntimeRules: legacy,+ MovedBy: "Lin\n\tLee\x01", StatusName: func(key string) string { return testCatalog()[key].Name },+ }+ brief := Brief(in)+ for _, want := range []string{+ `bound to "waiting_for_merge"`, statusLabel(testCatalog()[current].Name, current),+ "last moved by Lin Lee", "Do not change", "overrides the status rules", "member",+ "Statuses in this workflow:", " ← current",+ } {+ if !strings.Contains(brief, want) {+ t.Errorf("brief missing %q:\n%s", want, brief)+ }+ }+ for _, leak := range []string{+ "Implement it.", "Step instructions:", "You are handling", "Your moves:", "multica issue status",+ "Needs changes", "Can't proceed", "unless you are explicitly asked", "Before your run ends, either run",+ "Lin\n", "\x01",+ } {+ if strings.Contains(brief, leak) {+ t.Errorf("stale run received %q:\n%s", leak, brief)+ }+ }+ in.MovedBy = ""+ if unknown := Brief(in); !strings.Contains(unknown, "last moved by someone else") {+ t.Fatalf("missing mover must not prevent a mismatch brief:\n%s", unknown)+ }+ })+ }+ }+ }+}++func TestBriefMatchingBindingKeepsNormalInstructions(t *testing.T) {+ for _, observer := range []bool{false, true} {+ for _, legacy := range []bool{false, true} {+ in := BriefInput{Workflow: devDefinition(), StatusKey: "implement", IssueIdentifier: "MUL-7", Observer: observer, LegacyRuntimeRules: legacy}+ unbound := Brief(in)+ in.BoundStep, in.MovedBy = in.StatusKey, "Lin"+ if got := Brief(in); got != unbound {+ t.Errorf("observer=%v/legacy=%v: matching binding changed the normal brief:\n%s", observer, legacy, got)+ }+ }+ }+}+// A current daemon's runtime brief states no built-in status rules and owns// the exit check, so the brief neither overrides nor repeats them; an older// daemon's still states them, so its brief keeps the override lines (MUL-8145).diff --git a/server/internal/service/issue_wakeup_workflow_test.go b/server/internal/service/issue_wakeup_workflow_test.goindex d4fe476602..ea6524a3ea 100644--- a/server/internal/service/issue_wakeup_workflow_test.go+++ b/server/internal/service/issue_wakeup_workflow_test.go@@ -6,6 +6,7 @@ import ("github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/testutil"+ "github.com/multica-ai/multica/server/internal/util"db "github.com/multica-ai/multica/server/pkg/db/generated")@@ -77,3 +78,48 @@ func TestRetryKeepsWorkflowHandoffBrief(t *testing.T) {t.Fatalf("retry revived a retired note: %q", got.HandoffNote.String)}}++func TestManualRerunBindsToCurrentWorkflowStep(t *testing.T) {+ f, _, issue, agent := wakeFixture(t)+ ctx := context.Background()+ source := f.Task(t, agent, testutil.Cols{+ "issue_id": issue, "status": "failed", "workflow_step": "in_progress",+ "session_id": "existing-provider-session",+ "runtime_id": testutil.Raw("(SELECT runtime_id FROM agent WHERE id='" + agent + "')"),+ })+ f.Exec(t, "UPDATE issue SET status='blocked',assignee_type='agent',assignee_id=$2 WHERE id=$1", issue, agent)+ rerun, err := f.svc.TaskSvc.RerunIssue(ctx, issue, parseTestUUID(t, source), pgtype.UUID{}, parseTestUUID(t, f.UserID), false, func(db.Agent) bool { return true })+ if err != nil {+ t.Fatal(err)+ }+ if rerun.WorkflowStep.String != "blocked" || rerun.RerunOfTaskID != parseTestUUID(t, source) {+ t.Fatalf("manual rerun must bind to the current step while retaining its source: step=%q source=%v", rerun.WorkflowStep.String, rerun.RerunOfTaskID)+ }+ original, err := f.q.GetAgentTask(ctx, parseTestUUID(t, source))+ if err != nil {+ t.Fatal(err)+ }+ if original.WorkflowStep.String != "in_progress" {+ t.Fatalf("manual rerun rebound its source to %q", original.WorkflowStep.String)+ }+}++func TestJoinedWakeupKeepsTheWaitingRunsWorkflowStep(t *testing.T) {+ f, s, issue, agent := wakeFixture(t)+ w := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "event", EventTypes: []string{"comment.created"}, Instruction: "Inspect the reply"})+ waiting := wakeWaitingRun(t, f, issue, agent, f.UserID)+ f.Exec(t, "UPDATE agent_task_queue SET workflow_step='todo' WHERE id=$1", waiting)+ f.Exec(t, "UPDATE issue SET status='blocked' WHERE id=$1", issue)+ f.Comment(t, util.UUIDToString(issue), "a reply")+ wakeDispatch(t, s, w)+ if notes := wakeClaim(t, f, s, waiting); notes == "" {+ t.Fatal("wakeup did not join the waiting run")+ }+ task, err := f.q.GetAgentTask(context.Background(), parseTestUUID(t, waiting))+ if err != nil {+ t.Fatal(err)+ }+ if task.WorkflowStep.String != "todo" {+ t.Fatalf("joined wakeup rebound its waiting run to %q", task.WorkflowStep.String)+ }+}