diff --git a/internal/domain/sync.go b/internal/domain/sync.go index 163dd0274..18a8c580f 100644 --- a/internal/domain/sync.go +++ b/internal/domain/sync.go @@ -163,9 +163,34 @@ func (j ScheduleJob) DispatchLimit() int { return j.MaxDispatch } +// IssueStatusOptions are the issue lifecycle states the platform understands: +// the UI status picker (web/app/issue-model.js issueStatuses), the LOOP claim +// path, the scheduled trigger statuses below, analytics and issue history. +// "open" is accepted as an alias and stored as "backlog". +var IssueStatusOptions = []string{"backlog", "todo", "in_progress", "in_review", "blocked", "done", "closed", "cancelled"} + // ScheduleIssueStatusOptions are the statuses a trigger job may scan. var ScheduleIssueStatusOptions = []string{"backlog", "todo", "in_progress", "in_review", "blocked"} +// NormalizeIssueStatus returns the canonical spelling of an issue status, or +// false when the platform does not know it. Legacy trackers and clients send +// "open"; it maps to "backlog", which is also what an empty status means. +func NormalizeIssueStatus(raw string) (string, bool) { + switch s := strings.ToLower(strings.TrimSpace(raw)); s { + case "": + return "", true + case "open": + return "backlog", true + default: + for _, known := range IssueStatusOptions { + if s == known { + return s, true + } + } + return s, false + } +} + // DefaultScheduleIssueStatuses is what new trigger jobs persist when the // Studio form or API omits a list. var DefaultScheduleIssueStatuses = []string{"backlog", "todo"} diff --git a/internal/engine/workflow_graph.go b/internal/engine/workflow_graph.go index 0a27e5a31..d0ec5df22 100644 --- a/internal/engine/workflow_graph.go +++ b/internal/engine/workflow_graph.go @@ -181,6 +181,13 @@ func validate(wf domain.WorkflowDefinition) error { return validateWithStore(nil, wf) } +// ValidateWorkflowForSave is the save-time validator HTTP handlers call: it +// checks roles against the store and the whole graph, exactly as a run does. +// ValidateWorkflowRoutingWithStore alone checks only routing rules. +func ValidateWorkflowForSave(st *repo.Store, wf domain.WorkflowDefinition) error { + return validateGraphAndRouting(st, wf) +} + func validateWithStore(st *repo.Store, wf domain.WorkflowDefinition) error { if err := domain.ValidateWorkflowKnowledge(wf); err != nil { return err @@ -224,6 +231,28 @@ func validateWithStore(st *repo.Store, wf domain.WorkflowDefinition) error { return validateDAG(ids, wf.Edges) } +// validateGraphAndRouting checks the graph shape before routing. Routing only +// inspects edges that carry a condition, so a dangling or duplicated edge +// would otherwise be saved as long as no conditional edge pointed at the +// missing node. +func validateGraphAndRouting(st *repo.Store, wf domain.WorkflowDefinition) error { + if err := validateDAG(wfNodeIDs(wf), wf.Edges); err != nil { + return err + } + if st != nil { + return ValidateWorkflowRoutingWithStore(st, wf) + } + return validateRouting(wf) +} + +func wfNodeIDs(wf domain.WorkflowDefinition) map[string]bool { + ids := make(map[string]bool, len(wf.Nodes)) + for _, n := range wf.Nodes { + ids[n.ID] = true + } + return ids +} + // validateNode checks one node's own fields: its type-specific settings, the // onFailure/executionScope/retryStrategy enums and its artifact contracts. // workflowID guards sop nodes against referencing their own workflow. diff --git a/internal/httpapi/bot_interactions_test.go b/internal/httpapi/bot_interactions_test.go index 44a1c3611..9af9d69fb 100644 --- a/internal/httpapi/bot_interactions_test.go +++ b/internal/httpapi/bot_interactions_test.go @@ -111,7 +111,7 @@ func TestAutoModeStartsRecordTheChat(t *testing.T) { project.WorkflowID = "wf-dev" s.PutProject(project) for _, id := range []string{"by-tool", "by-draft"} { - if err := s.PutIssue(domain.Issue{ID: id, ProjectID: "p", Title: id, Status: "open"}); err != nil { + if err := s.PutIssue(domain.Issue{ID: id, ProjectID: "p", Title: id, Status: "todo"}); err != nil { t.Fatal(err) } } diff --git a/internal/httpapi/catalog.go b/internal/httpapi/catalog.go index 12d4595fe..4e3519022 100644 --- a/internal/httpapi/catalog.go +++ b/internal/httpapi/catalog.go @@ -1220,7 +1220,7 @@ func (h *catalogHandlers) workflows(c *gin.Context) { return } engine.NormalizeWorkflowRoutingEdgeIDs(&v) - if err := engine.ValidateWorkflowRoutingWithStore(h.repo, v); err != nil { + if err := engine.ValidateWorkflowForSave(h.repo, v); err != nil { c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()}) return } diff --git a/internal/httpapi/project_delete_test.go b/internal/httpapi/project_delete_test.go index 1edafb7e9..77deb1110 100644 --- a/internal/httpapi/project_delete_test.go +++ b/internal/httpapi/project_delete_test.go @@ -42,7 +42,7 @@ func TestProjectDeleteArchivesAndRestores(t *testing.T) { if err := s.PutProject(domain.Project{ID: "keep", Name: "保留", OwnerID: owner.ID}); err != nil { t.Fatal(err) } - if err := s.PutIssue(domain.Issue{ID: "okr-1", ProjectID: "okr-system", Title: "初始化", Status: "open"}); err != nil { + if err := s.PutIssue(domain.Issue{ID: "okr-1", ProjectID: "okr-system", Title: "初始化", Status: "todo"}); err != nil { t.Fatal(err) } h := New(s, engine.New(s, runtime.NewManager(filepath.Join(t.TempDir(), "workspaces"))), tracker.NewService(), "", "") diff --git a/internal/httpapi/workflow_dangling_edge_test.go b/internal/httpapi/workflow_dangling_edge_test.go new file mode 100644 index 000000000..7815a2223 --- /dev/null +++ b/internal/httpapi/workflow_dangling_edge_test.go @@ -0,0 +1,51 @@ +package httpapi + +import ( + "net/http" + "path/filepath" + "strings" + "testing" + + "agentflow/internal/domain" + "agentflow/internal/engine" + "agentflow/internal/repo" + "agentflow/internal/runtime" + "agentflow/internal/tracker" +) + +// Saving a LOOP used to validate routing rules but never the graph shape, so +// an edge pointing at a node that does not exist was stored and published and +// only failed when someone ran the LOOP. +func TestWorkflowSaveRejectsDanglingEdge(t *testing.T) { + st, err := repo.OpenTest() + if err != nil { + t.Fatal(err) + } + t.Cleanup(st.Close) + h := New(st, engine.New(st, runtime.NewManager(filepath.Join(t.TempDir(), "workspaces"))), tracker.NewService(), "", "") + wf := domain.WorkflowDefinition{ + ID: "dangling-edge", Name: "悬空边校验", ProjectID: "platform", SandboxProfileID: "test-native", + Nodes: []domain.WorkflowNode{ + {ID: "a", Name: "实现", Type: "script", ScriptLanguage: "shell", Script: "true"}, + {ID: "b", Name: "验收", Type: "script", ScriptLanguage: "shell", Script: "true"}, + }, + Edges: []domain.WorkflowEdge{{ID: "e1", Source: "a", Target: "b", When: "success"}}, + } + for name, edge := range map[string]domain.WorkflowEdge{ + "missing source": {ID: "bad", Source: "no", Target: "b", When: "success"}, + "missing target": {ID: "bad", Source: "a", Target: "nope", When: "success"}, + "missing both": {ID: "bad", Source: "no", Target: "nope", When: "success"}, + "no id": {Source: "no", Target: "b", When: "success"}, + } { + broken := wf + broken.Edges = append(append([]domain.WorkflowEdge(nil), wf.Edges...), edge) + got := requestJSON[map[string]string](t, h, http.MethodPut, "/api/workflows", broken, http.StatusBadRequest) + if !strings.Contains(got["error"], "edge references missing node") { + t.Fatalf("%s: error=%q", name, got["error"]) + } + } + saved := requestJSON[domain.WorkflowDefinition](t, h, http.MethodPut, "/api/workflows", wf, http.StatusOK) + if len(saved.Edges) != 1 { + t.Fatalf("valid LOOP not saved: %+v", saved.Edges) + } +} diff --git a/internal/repo/issues.go b/internal/repo/issues.go index 5e477608f..16e6e2169 100644 --- a/internal/repo/issues.go +++ b/internal/repo/issues.go @@ -3,6 +3,7 @@ package repo import ( "database/sql" "errors" + "fmt" "sort" "strings" "time" @@ -123,10 +124,22 @@ func (r *IssuesRepo) Issue(id string) (domain.Issue, bool) { if err := r.DB.Where("id = ?", id).Take(&row).Error; err != nil { return domain.Issue{}, false } + issue, ok := issueFromRow(row) + return issue, ok +} + +// issueFromRow reads an issue snapshot. The status column is what the list, +// status filters and tracker sync read (an old row edited before statuses were +// validated can hold a value the payload never saw), so it wins over the copy +// inside the payload. +func issueFromRow(row issueRow) (domain.Issue, bool) { var issue domain.Issue if jsonUnmarshal(row.Payload, &issue) != nil { return domain.Issue{}, false } + if row.Status != "" { + issue.Status = row.Status + } if row.AssigneeUserID != nil { issue.AssigneeUserID = *row.AssigneeUserID } else { @@ -296,9 +309,18 @@ func (r *IssuesRepo) prepareIssueForSave(v domain.Issue, fromSync, existingOnly } } if !preserveStatus { - if v.TrackerClosed() && v.Status != "closed" { + // An external tracker closing the issue wins over any client status. + if status, known := domain.NormalizeIssueStatus(v.Status); known && !v.TrackerClosed() { + // Canonical spelling, and the legacy "open" tracker adapters send. + v.Status = status + } else if v.TrackerClosed() { v.Status = "closed" v.CloseSource = "external" + } else { + return v, fmt.Errorf("invalid issue status %q", v.Status) + } + if ok && v.Status == old.Status && old.Status != "" { + v.CloseSource = old.CloseSource } if v.Status == "closed" { if v.CloseSource == "" { diff --git a/internal/repo/issues_test.go b/internal/repo/issues_test.go index be8a3e06a..5cb4d5953 100644 --- a/internal/repo/issues_test.go +++ b/internal/repo/issues_test.go @@ -1,6 +1,7 @@ package repo import ( + "strings" "testing" "time" @@ -227,3 +228,73 @@ func TestRestoreTrackerBindingFromStableID(t *testing.T) { t.Fatalf("existing snapshot should win: %+v", wiped) } } + +func TestPutIssueRejectsUnknownStatus(t *testing.T) { + s, err := OpenTest() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { s.Close() }) + if err := s.PutIssue(domain.Issue{ID: "bad-1", ProjectID: "platform", Title: "x", Status: "nope"}); err == nil || !strings.Contains(err.Error(), "invalid issue status") { + t.Fatalf("unknown status accepted: %v", err) + } + if _, ok := s.Issue("bad-1"); ok { + t.Fatal("rejected issue must not be stored") + } + if err := s.PutIssue(domain.Issue{ID: "ok-1", ProjectID: "platform", Title: "x", Status: "in_review"}); err != nil { + t.Fatal(err) + } + got, _ := s.Issue("ok-1") + if got.Status != "in_review" { + t.Fatalf("status = %q", got.Status) + } +} + +// A row stored with a status the platform does not know (before statuses were +// validated) can still be edited: an edit that asks for a known status repairs +// it. A new issue with an unknown status is refused. +func TestPutIssueEditOfStoredUnknownStatus(t *testing.T) { + s, err := OpenTest() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { s.Close() }) + legacy := domain.Issue{ID: "stored-unknown", ProjectID: "platform", Title: "old", Status: "backlog"} + if err := s.PutIssue(legacy); err != nil { + t.Fatal(err) + } + if err := s.DB.Exec("UPDATE issues SET status = ? WHERE id = ?", "ghost", legacy.ID).Error; err != nil { + t.Fatal(err) + } + if err := s.PutIssue(domain.Issue{ID: "new-unknown", ProjectID: "platform", Title: "new", Status: "phantom"}); err == nil || !strings.Contains(err.Error(), "invalid issue status") { + t.Fatalf("new issue with an unknown status: %v", err) + } + legacy.Title, legacy.Status = "renamed", "todo" + if err := s.PutIssue(legacy); err != nil { + t.Fatalf("repairing a stored unknown status: %v", err) + } + if got, _ := s.Issue(legacy.ID); got.Title != "renamed" || got.Status != "todo" { + t.Fatalf("stored row after repair: %+v", got) + } +} + +// The legacy "open" every tracker adapter sends maps to the canonical backlog. +func TestPutIssueMapsLegacyOpenToBacklog(t *testing.T) { + s, err := OpenTest() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { s.Close() }) + if err := s.PutIssue(domain.Issue{ID: "legacy-open", ProjectID: "platform", Title: "legacy", Status: "open"}); err != nil { + t.Fatalf("legacy open status: %v", err) + } + if got, _ := s.Issue("legacy-open"); got.Status != "backlog" { + t.Fatalf("status = %q, want backlog", got.Status) + } + if err := s.PutIssue(domain.Issue{ID: "padded", ProjectID: "platform", Title: "padded", Status: " In_Review "}); err != nil { + t.Fatal(err) + } + if got, _ := s.Issue("padded"); got.Status != "in_review" { + t.Fatalf("status = %q, want in_review", got.Status) + } +} diff --git a/internal/repo/payload_json_text_projection_test.go b/internal/repo/payload_json_text_projection_test.go index d1c8af322..1f0df2bcd 100644 --- a/internal/repo/payload_json_text_projection_test.go +++ b/internal/repo/payload_json_text_projection_test.go @@ -53,7 +53,7 @@ func TestBusinessDeliveryIssuesProjectsPayloadJSONColumns(t *testing.T) { t.Cleanup(s.Close) started := time.Date(2026, 11, 13, 9, 30, 0, 0, time.UTC) issue := domain.Issue{ - ID: "iss-lifecycle", ProjectID: "alpha", Title: "lifecycle", Status: "open", Kind: "requirement", Source: "platform", + ID: "iss-lifecycle", ProjectID: "alpha", Title: "lifecycle", Status: "todo", Kind: "requirement", Source: "platform", Clarification: domain.ClarificationAssessment{StartedAt: started}, Operations: []domain.IssueOperation{{At: started, Action: "create"}, {At: started.Add(time.Hour), Action: "close"}}, } diff --git a/review-assets/pr1751/pr1751-run-detail-en.png b/review-assets/pr1751/pr1751-run-detail-en.png new file mode 100644 index 000000000..6edac7ff7 Binary files /dev/null and b/review-assets/pr1751/pr1751-run-detail-en.png differ diff --git a/review-img/oc-zhipu-1711.png b/review-img/oc-zhipu-1711.png new file mode 100644 index 000000000..9868ddfca Binary files /dev/null and b/review-img/oc-zhipu-1711.png differ