Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8386: feat(cli): add workflow and project workflow commands (#9714)
Multica Eve354243b45947
diff --git a/apps/docs/content/docs/cli.mdx b/apps/docs/content/docs/cli.mdxindex c63c2039ef..d6a1cf4cda 100644--- a/apps/docs/content/docs/cli.mdx+++ b/apps/docs/content/docs/cli.mdx@@ -300,7 +300,8 @@ multica autopilot trigger-add <autopilot-id> --cron "0 9 * * 1" --timezone Europ| Command | Purpose || --- | --- || `issue` | Create, update, assign, and search issues; manage comments, subscribers, labels, properties, wakeups, the timeline, and runs |-| `project` | Manage projects and their resources |+| `project` | Manage projects, their resources, and the workflow they use |+| `workflow` | Manage issue workflows: statuses and who handles each one || `label`, `property` | Manage workspace labels and custom properties || `agent`, `skill`, `squad` | Manage agents, skills, and squads || `autopilot` | Manage automations, triggers, and run history |@@ -394,6 +395,9 @@ The tables below cover every current top-level command, grouped the way the CLI| `project` | `list/get/create/update/delete` | Manage projects | `create`: `--title` (required), `--lead`, `--status`, `--icon`, `--start-date`, `--due-date`, `--repo` (repeatable) || | `status <id> <status>` | Change project status | || | `resource list/add/update/remove` | Manage project resources | `--type`, `--url`, `--default-branch-hint`, `--ref`, `--local-path`, `--daemon-id`, `--execution-mode` (`in_place` / `worktree` for a local directory) |+| | `workflow get/set <project-id>` | Show the project's effective workflow, or switch it | `set <project-id> <workflow\|default>`: `--map old=new` (repeatable), `--dry-run` prints the status migration plan; the switch neither reassigns issues nor starts runs. Admins and the project lead only |+| `workflow` | `list/get/create/update/delete` | Manage workflows; `get` and other commands accept an ID, ID prefix, exact name, or `default` | `create` / `update`: `--name`, `--description`, `--steps-file` (JSON array of steps; replaces all steps); `update`: `--map old=new` (repeatable), `--dry-run`. Edits and deletes are limited to the workflow owner and workspace admins; a workflow still used by a project cannot be deleted |+| | `handoff set <workflow> <status-key>` | Set one step's handler, instructions, and next/back status; unchanged fields are kept | `--handler` (`none`, `project_lead`, `creator`, or a member/agent/squad name or UUID), `--instructions` / `--instructions-file`, `--next`, `--back`, `--copy-for-project` || `label` | `list/get/create/update/delete` | Manage workspace labels | `list`: `--resource-type` (`issue` or `skill`), `--full-id`; `create`: `--name`, `--color`, `--resource-type` (`issue` or `skill`), `--description` || `property` | `list/get/create/update/archive/unarchive` | Manage workspace custom properties | `create`: `--name`, `--type` (`text`, `number`, `select`, `multi_select`, `date`, `checkbox`, `url`, `actor`, `multi_actor`, `multi_text`, `multi_url`), `--option` (repeatable, select types only); `list`: `--include-archived`; the type cannot be changed after creation || `agent` | `list/get/create/update/archive/restore` | Manage agents | `--name`, `--runtime-id` (required for `create`), `--instructions`, `--conversation-starters`, `--model`, `--thinking-level`, `--custom-env` / `--custom-env-file` / `--custom-env-stdin` (`create` only), `--custom-args`, `--mcp-config` / `--mcp-config-file` / `--mcp-config-stdin`, `--permission-mode`, `--visibility` (older form), `--max-concurrent-tasks` |diff --git a/apps/docs/content/docs/cli.zh.mdx b/apps/docs/content/docs/cli.zh.mdxindex 09a6fa5e38..eeb1b32081 100644--- a/apps/docs/content/docs/cli.zh.mdx+++ b/apps/docs/content/docs/cli.zh.mdx@@ -285,7 +285,8 @@ multica autopilot trigger-add <autopilot-id> --cron "0 9 * * 1" --timezone Asia/| 命令 | 用途 || --- | --- || `issue` | 创建、更新、分配和搜索任务;管理评论、订阅、标签、属性、唤醒、时间线与执行记录 |-| `project` | 管理项目及其资源 |+| `project` | 管理项目、项目资源和项目使用的工作流 |+| `workflow` | 管理工作流:状态以及每个状态交给谁处理 || `label`、`property` | 管理工作区标签和自定义属性 || `agent`、`skill`、`squad` | 管理智能体、skill 和小队 || `autopilot` | 管理自动化、触发器和运行历史 |@@ -371,6 +372,9 @@ CLI 配置文件包含可代表你访问 Multica 的令牌。不要提交到仓| `project` | `list/get/create/update/delete` | 管理项目 | `create`:`--title`(必填)、`--lead`、`--status`、`--icon`、`--start-date`、`--due-date`、`--repo`(可重复) || | `status <id> <status>` | 修改项目状态 | || | `resource list/add/update/remove` | 管理项目附加资源 | `--type`、`--url`、`--default-branch-hint`、`--ref`、`--local-path`、`--daemon-id`、`--execution-mode`(本地目录的 `in_place` / `worktree`) |+| | `workflow get/set <project-id>` | 查看项目当前生效的工作流,或切换工作流 | `set <project-id> <workflow\|default>`:`--map old=new`(可重复),`--dry-run` 打印状态迁移计划;切换不会重新分配任务,也不会启动运行。仅管理员和项目负责人可操作 |+| `workflow` | `list/get/create/update/delete` | 管理工作流;`get` 等命令接受 ID、ID 前缀、完整名称或 `default` | `create` / `update`:`--name`、`--description`、`--steps-file`(步骤的 JSON 数组,整体替换);`update`:`--map old=new`(可重复)、`--dry-run`。编辑和删除仅限工作流所有者和工作区管理员;仍被项目使用的工作流不能删除 |+| | `handoff set <workflow> <status-key>` | 设置单个步骤的处理人、说明和下一步/退回状态,未指定的字段保持不变 | `--handler`(`none`、`project_lead`、`creator`,或成员/智能体/小队的名称或 UUID)、`--instructions` / `--instructions-file`、`--next`、`--back`、`--copy-for-project` || `label` | `list/get/create/update/delete` | 管理工作区标签 | `list`:`--resource-type`(`issue` 或 `skill`)、`--full-id`;`create`:`--name`、`--color`、`--resource-type`(`issue` 或 `skill`)、`--description` || `property` | `list/get/create/update/archive/unarchive` | 管理工作区自定义属性 | `create`:`--name`、`--type`(`text`、`number`、`select`、`multi_select`、`date`、`checkbox`、`url`、`actor`、`multi_actor`、`multi_text`、`multi_url`)、`--option`(可重复,仅 select 类型);`list`:`--include-archived`;类型创建后不可修改 || `agent` | `list/get/create/update/archive/restore` | 管理智能体 | `--name`、`--runtime-id`(`create` 必填)、`--instructions`、`--conversation-starters`、`--model`、`--thinking-level`、`--custom-env` / `--custom-env-file` / `--custom-env-stdin`(仅 `create`)、`--custom-args`、`--mcp-config` / `--mcp-config-file` / `--mcp-config-stdin`、`--permission-mode`、`--visibility`(旧写法)、`--max-concurrent-tasks` |diff --git a/server/cmd/multica/cmd_workflow.go b/server/cmd/multica/cmd_workflow.gonew file mode 100644index 0000000000..9f29c08ed0--- /dev/null+++ b/server/cmd/multica/cmd_workflow.go@@ -0,0 +1,738 @@+package main++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "net/http"+ "net/url"+ "os"+ "strconv"+ "strings"++ "github.com/spf13/cobra"++ "github.com/multica-ai/multica/server/internal/cli"+)++// Workflow commands wrap /api/issue-workflows and the project workflow+// switch. Permission checks stay on the server: edits and deletes are limited+// to the workflow owner and workspace admins, switching a project's workflow+// to admins and the project lead. The CLI reports the server's error as is.++var workflowCmd = &cobra.Command{+ Use: "workflow",+ Short: "Work with issue workflows (statuses and their handoffs)",+}++var workflowListCmd = &cobra.Command{+ Use: "list",+ Short: "List workflows in the workspace",+ RunE: runWorkflowList,+}++var workflowGetCmd = &cobra.Command{+ Use: "get <workflow>",+ Short: "Get a workflow and its steps (accepts an ID, ID prefix, exact name, or \"default\")",+ Args: exactArgs(1),+ RunE: runWorkflowGet,+}++var workflowCreateCmd = &cobra.Command{+ Use: "create",+ Short: "Create a workflow",+ Long: `Create a workflow.++--steps-file takes a JSON array of steps in board order, the same shape the+API accepts, e.g.:++ [+ {"status_key": "todo"},+ {"status_key": "in_review", "handler": {"type": "agent", "id": "<agent-id>"},+ "instructions": "Review the PR", "next_status_key": "done"},+ {"new_status": {"name": "QA", "category": "started"}},+ {"status_key": "done"}+ ]++Todo, done and cancelled are added when missing.`,+ RunE: runWorkflowCreate,+}++var workflowUpdateCmd = &cobra.Command{+ Use: "update <workflow>",+ Short: "Update a workflow's name, description, or steps",+ Long: `Update a workflow's name, description, or steps.++--steps-file replaces all steps (same JSON shape as "workflow create"). When+the new steps drop a status that issues still use, map each dropped status+with --map old=new. Use --dry-run to print the migration plan without writing.`,+ Args: exactArgs(1),+ RunE: runWorkflowUpdate,+}++var workflowDeleteCmd = &cobra.Command{+ Use: "delete <workflow>",+ Short: "Delete a workflow (rejected while a project still uses it)",+ Args: exactArgs(1),+ RunE: runWorkflowDelete,+}++var workflowHandoffCmd = &cobra.Command{+ Use: "handoff",+ Short: "Manage what happens when an issue enters a workflow status",+}++var workflowHandoffSetCmd = &cobra.Command{+ Use: "set <workflow> <status-key>",+ Short: "Set the handler, instructions, and next/back status for one step",+ Long: `Set the handoff of one step. Only the flags you pass change; the rest of+the step is kept.++--handler accepts none, project_lead, creator, or a member, agent, or squad+name or UUID.`,+ Args: exactArgs(2),+ RunE: runWorkflowHandoffSet,+}++var projectWorkflowCmd = &cobra.Command{+ Use: "workflow",+ Short: "Show or switch the workflow a project uses",+}++var projectWorkflowGetCmd = &cobra.Command{+ Use: "get <project-id>",+ Short: "Show the project's effective workflow (Default when none is set)",+ Args: exactArgs(1),+ RunE: runProjectWorkflowGet,+}++var projectWorkflowSetCmd = &cobra.Command{+ Use: "set <project-id> <workflow|default>",+ Short: "Switch the project to another workflow",+ Long: `Switch the project to another workflow, or back to the workspace Default.++Issues on statuses the new workflow does not list must be mapped with+--map old=new. Use --dry-run to print the migration plan first. Moving issues+this way neither reassigns them nor starts runs.`,+ Args: exactArgs(2),+ RunE: runProjectWorkflowSet,+}++func init() {+ workflowCmd.AddCommand(workflowListCmd)+ workflowCmd.AddCommand(workflowGetCmd)+ workflowCmd.AddCommand(workflowCreateCmd)+ workflowCmd.AddCommand(workflowUpdateCmd)+ workflowCmd.AddCommand(workflowDeleteCmd)+ workflowCmd.AddCommand(workflowHandoffCmd)+ workflowHandoffCmd.AddCommand(workflowHandoffSetCmd)++ projectCmd.AddCommand(projectWorkflowCmd)+ projectWorkflowCmd.AddCommand(projectWorkflowGetCmd)+ projectWorkflowCmd.AddCommand(projectWorkflowSetCmd)++ workflowListCmd.Flags().String("output", "table", "Output format: table or json")+ workflowListCmd.Flags().Bool("full-id", false, "Show full UUIDs in table output")++ workflowGetCmd.Flags().String("output", "json", "Output format: table or json")++ workflowCreateCmd.Flags().String("name", "", "Workflow name (required)")+ workflowCreateCmd.Flags().String("description", "", "Workflow description")+ workflowCreateCmd.Flags().String("steps-file", "", "Path to a JSON array of steps")+ workflowCreateCmd.Flags().String("output", "json", "Output format: table or json")++ workflowUpdateCmd.Flags().String("name", "", "New name")+ workflowUpdateCmd.Flags().String("description", "", "New description")+ workflowUpdateCmd.Flags().String("steps-file", "", "Path to a JSON array of steps; replaces all steps")+ workflowUpdateCmd.Flags().StringArray("map", nil, "Move issues off a dropped status: old=new (repeatable)")+ workflowUpdateCmd.Flags().Bool("dry-run", false, "Print the migration plan without writing")+ workflowUpdateCmd.Flags().String("output", "json", "Output format: table or json")++ workflowDeleteCmd.Flags().String("output", "table", "Output format: table or json")++ workflowHandoffSetCmd.Flags().String("handler", "", "none, project_lead, creator, or a member/agent/squad name or UUID")+ workflowHandoffSetCmd.Flags().String("instructions", "", "Instructions the handler's run gets")+ workflowHandoffSetCmd.Flags().String("instructions-file", "", "Read instructions from a file")+ workflowHandoffSetCmd.Flags().String("next", "", "Status the handler moves the issue to when done (empty to clear)")+ workflowHandoffSetCmd.Flags().String("back", "", "Status the handler sends the issue back to (empty to clear)")+ workflowHandoffSetCmd.Flags().String("copy-for-project", "", "Save on a copy of the workflow used only by this project")+ workflowHandoffSetCmd.Flags().String("output", "json", "Output format: table or json")++ projectWorkflowGetCmd.Flags().String("output", "json", "Output format: table or json")++ projectWorkflowSetCmd.Flags().StringArray("map", nil, "Move issues off a status the new workflow lacks: old=new (repeatable)")+ projectWorkflowSetCmd.Flags().Bool("dry-run", false, "Print the migration plan without writing")+ projectWorkflowSetCmd.Flags().String("output", "json", "Output format: table or json")+}++// --- helpers ---++func listWorkflows(ctx context.Context, client *cli.APIClient) ([]map[string]any, error) {+ path := "/api/issue-workflows"+ if client.WorkspaceID != "" {+ path += "?" + url.Values{"workspace_id": {client.WorkspaceID}}.Encode()+ }+ var result struct {+ Workflows []map[string]any `json:"workflows"`+ }+ if err := client.GetJSON(ctx, path, &result); err != nil {+ return nil, err+ }+ return result.Workflows, nil+}++// resolveWorkflow accepts "default", a full UUID, an exact name+// (case-insensitive), or a unique ID prefix.+func resolveWorkflow(ctx context.Context, client *cli.APIClient, input string) (map[string]any, error) {+ ref := strings.TrimSpace(input)+ if ref == "" {+ return nil, fmt.Errorf("workflow is required")+ }+ if uuidRegexp.MatchString(ref) {+ var wf map[string]any+ if err := client.GetJSON(ctx, "/api/issue-workflows/"+ref, &wf); err != nil {+ return nil, err+ }+ return wf, nil+ }+ workflows, err := listWorkflows(ctx, client)+ if err != nil {+ return nil, err+ }+ if strings.EqualFold(ref, "default") {+ for _, wf := range workflows {+ if b, _ := wf["is_default"].(bool); b {+ return wf, nil+ }+ }+ }+ var byName []map[string]any+ for _, wf := range workflows {+ if strings.EqualFold(strVal(wf, "name"), ref) {+ byName = append(byName, wf)+ }+ }+ if len(byName) == 1 {+ return byName[0], nil+ }+ if len(byName) > 1 {+ return nil, fmt.Errorf("more than one workflow is named %q; pass its ID", ref)+ }+ prefix, err := normalizeUUIDPrefix(ref)+ if err != nil {+ return nil, fmt.Errorf("no workflow named %q", ref)+ }+ var matches []idCandidate+ var found map[string]any+ for _, wf := range workflows {+ if strings.HasPrefix(compactUUID(strVal(wf, "id")), prefix) {+ matches = append(matches, idCandidate{ID: strVal(wf, "id")})+ found = wf+ }+ }+ switch len(matches) {+ case 0:+ return nil, fmt.Errorf("no workflow found matching %q; run `multica workflow list --full-id`", ref)+ case 1:+ return found, nil+ default:+ return nil, ambiguousIDPrefixError("workflow", ref, matches)+ }+}++// parseStatusMapping turns repeated old=new flags into a mapping.+func parseStatusMapping(pairs []string) (map[string]string, error) {+ if len(pairs) == 0 {+ return nil, nil+ }+ out := make(map[string]string, len(pairs))+ for _, p := range pairs {+ from, to, ok := strings.Cut(p, "=")+ from, to = strings.TrimSpace(from), strings.TrimSpace(to)+ if !ok || from == "" || to == "" {+ return nil, fmt.Errorf("invalid --map %q; expected old=new", p)+ }+ if prev, dup := out[from]; dup && prev != to {+ return nil, fmt.Errorf("--map maps %q twice (%q and %q)", from, prev, to)+ }+ out[from] = to+ }+ return out, nil+}++func readStepsFile(path string) ([]any, error) {+ data, err := os.ReadFile(path)+ if err != nil {+ return nil, fmt.Errorf("read --steps-file: %w", err)+ }+ var steps []any+ if err := json.Unmarshal(data, &steps); err != nil {+ return nil, fmt.Errorf("--steps-file must be a JSON array of steps: %w", err)+ }+ return steps, nil+}++func workflowSteps(wf map[string]any) []map[string]any {+ raw, _ := wf["steps"].([]any)+ out := make([]map[string]any, 0, len(raw))+ for _, s := range raw {+ if m, ok := s.(map[string]any); ok {+ out = append(out, m)+ }+ }+ return out+}++func formatStepHandler(step map[string]any) string {+ h, _ := step["handler"].(map[string]any)+ typ := strVal(h, "type")+ if typ == "" {+ typ = "none"+ }+ if id := strVal(h, "id"); id != "" {+ return typ + ":" + id+ }+ return typ+}++func printWorkflowTable(wf map[string]any) {+ fmt.Fprintf(os.Stdout, "%s (%s)\n", strVal(wf, "name"), strVal(wf, "id"))+ headers := []string{"STATUS", "HANDLER", "NEXT", "BACK"}+ steps := workflowSteps(wf)+ rows := make([][]string, 0, len(steps))+ for _, s := range steps {+ rows = append(rows, []string{+ strVal(s, "status_key"),+ formatStepHandler(s),+ strVal(s, "next_status_key"),+ strVal(s, "back_status_key"),+ })+ }+ cli.PrintTable(os.Stdout, headers, rows)+}++func printMappingPlan(plan map[string]any) {+ fmt.Fprintf(os.Stdout, "Dry run: %v of %v issue(s) would move.\n", plan["affected_issues"], plan["total_issues"])+ if required, _ := plan["required"].([]any); len(required) > 0 {+ printMappingRequired(plan)+ }+}++// reportMappingRequired handles the server's 409+// workflow_status_mapping_required. The default error formatter keeps only+// the first message line, which drops the plan a script needs to supply every+// mapping at once. This prints the full body (JSON) or the plan (table) to+// stdout, the server message to stderr, and returns errSilent so the command+// still exits non-zero (1, as for any other conflict) without printing twice. Any other error returns nil and is left to the+// caller.+func reportMappingRequired(cmd *cobra.Command, err error) error {+ var httpErr *cli.HTTPError+ if !errors.As(err, &httpErr) || httpErr.StatusCode != http.StatusConflict {+ return nil+ }+ var body map[string]any+ if json.Unmarshal([]byte(httpErr.Body), &body) != nil || strVal(body, "code") != "workflow_status_mapping_required" {+ return nil+ }+ if output, _ := cmd.Flags().GetString("output"); output == "table" {+ if plan, ok := body["plan"].(map[string]any); ok {+ printMappingRequired(plan)+ }+ } else if perr := cli.PrintJSON(os.Stdout, body); perr != nil {+ return perr+ }+ fmt.Fprintf(os.Stderr, "Error: %s; pass --map old=new for each status listed\n", strVal(body, "error"))+ return errSilent+}++func printMappingRequired(plan map[string]any) {+ required, _ := plan["required"].([]any)+ headers := []string{"FROM STATUS", "ISSUES", "SUGGESTED"}+ rows := make([][]string, 0, len(required))+ for _, raw := range required {+ r, _ := raw.(map[string]any)+ rows = append(rows, []string{strVal(r, "status_key"), fmt.Sprint(r["issue_count"]), strVal(r, "suggested_status_key")})+ }+ cli.PrintTable(os.Stdout, headers, rows)+}++// resolveHandoffHandler maps the --handler value to a handler payload.+func resolveHandoffHandler(ctx context.Context, client *cli.APIClient, value string) (map[string]any, error) {+ v := strings.TrimSpace(value)+ switch strings.ToLower(v) {+ case "", "none":+ return map[string]any{"type": "none"}, nil+ case "project_lead", "creator":+ return map[string]any{"type": strings.ToLower(v)}, nil+ }+ var typ, id string+ var err error+ if uuidRegexp.MatchString(v) {+ typ, id, err = resolveAssigneeByID(ctx, client, v, issueAssigneeKinds)+ } else {+ typ, id, err = resolveAssignee(ctx, client, v, issueAssigneeKinds)+ }+ if err != nil {+ return nil, fmt.Errorf("resolve handler: %w", err)+ }+ return map[string]any{"type": typ, "id": id}, nil+}++// --- workflow commands ---++func runWorkflowList(cmd *cobra.Command, _ []string) error {+ client, err := newAPIClient(cmd)+ if err != nil {+ return err+ }+ ctx, cancel := cli.APIContext(context.Background())+ defer cancel()++ workflows, err := listWorkflows(ctx, client)+ if err != nil {+ return fmt.Errorf("list workflows: %w", err)+ }+ if output, _ := cmd.Flags().GetString("output"); output == "json" {+ return cli.PrintJSON(os.Stdout, workflows)+ }+ fullID, _ := cmd.Flags().GetBool("full-id")+ headers := []string{"ID", "NAME", "DEFAULT", "STEPS", "PROJECTS"}+ rows := make([][]string, 0, len(workflows))+ for _, wf := range workflows {+ isDefault := ""+ if b, _ := wf["is_default"].(bool); b {+ isDefault = "yes"+ }+ projects, _ := wf["project_ids"].([]any)+ rows = append(rows, []string{+ displayID(strVal(wf, "id"), fullID),+ strVal(wf, "name"),+ isDefault,+ strconv.Itoa(len(workflowSteps(wf))),+ strconv.Itoa(len(projects)),+ })+ }+ cli.PrintTable(os.Stdout, headers, rows)+ return nil+}++func runWorkflowGet(cmd *cobra.Command, args []string) error {+ client, err := newAPIClient(cmd)+ if err != nil {+ return err+ }+ ctx, cancel := cli.APIContext(context.Background())+ defer cancel()++ wf, err := resolveWorkflow(ctx, client, args[0])+ if err != nil {+ return fmt.Errorf("get workflow: %w", err)+ }+ if output, _ := cmd.Flags().GetString("output"); output == "table" {+ printWorkflowTable(wf)+ return nil+ }+ return cli.PrintJSON(os.Stdout, wf)+}++func runWorkflowCreate(cmd *cobra.Command, _ []string) error {+ name, _ := cmd.Flags().GetString("name")+ if strings.TrimSpace(name) == "" {+ return fmt.Errorf("--name is required")+ }+ body := map[string]any{"name": name}+ if cmd.Flags().Changed("description") {+ v, _ := cmd.Flags().GetString("description")+ body["description"] = v+ }+ if path, _ := cmd.Flags().GetString("steps-file"); path != "" {+ steps, err := readStepsFile(path)+ if err != nil {+ return err+ }+ body["steps"] = steps+ }++ client, err := newAPIClient(cmd)+ if err != nil {+ return err+ }+ ctx, cancel := cli.APIContext(context.Background())+ defer cancel()++ var result map[string]any+ if err := client.PostJSON(ctx, "/api/issue-workflows", body, &result); err != nil {+ return fmt.Errorf("create workflow: %w", err)+ }+ if output, _ := cmd.Flags().GetString("output"); output == "table" {+ printWorkflowTable(result)+ return nil+ }+ return cli.PrintJSON(os.Stdout, result)+}++func runWorkflowUpdate(cmd *cobra.Command, args []string) error {+ body := map[string]any{}+ if cmd.Flags().Changed("name") {+ v, _ := cmd.Flags().GetString("name")+ body["name"] = v+ }+ if cmd.Flags().Changed("description") {+ v, _ := cmd.Flags().GetString("description")+ body["description"] = v+ }+ if path, _ := cmd.Flags().GetString("steps-file"); path != "" {+ steps, err := readStepsFile(path)+ if err != nil {+ return err+ }+ body["steps"] = steps+ }+ if len(body) == 0 {+ return fmt.Errorf("nothing to update; provide --name, --description, and/or --steps-file")+ }+ pairs, _ := cmd.Flags().GetStringArray("map")+ mapping, err := parseStatusMapping(pairs)+ if err != nil {+ return err+ }+ if mapping != nil {+ body["status_mapping"] = mapping+ }+ dryRun, _ := cmd.Flags().GetBool("dry-run")+ if dryRun {+ body["dry_run"] = true+ }++ client, err := newAPIClient(cmd)+ if err != nil {+ return err+ }+ ctx, cancel := cli.APIContext(context.Background())+ defer cancel()++ wf, err := resolveWorkflow(ctx, client, args[0])+ if err != nil {+ return fmt.Errorf("resolve workflow: %w", err)+ }+ var result map[string]any+ if err := client.PatchJSON(ctx, "/api/issue-workflows/"+strVal(wf, "id"), body, &result); err != nil {+ if reported := reportMappingRequired(cmd, err); reported != nil {+ return reported+ }+ return fmt.Errorf("update workflow: %w", err)+ }+ output, _ := cmd.Flags().GetString("output")+ if output == "table" {+ if plan, ok := result["plan"].(map[string]any); ok && dryRun {+ printMappingPlan(plan)+ return nil+ }+ printWorkflowTable(result)+ return nil+ }+ return cli.PrintJSON(os.Stdout, result)+}++func runWorkflowDelete(cmd *cobra.Command, args []string) error {+ client, err := newAPIClient(cmd)+ if err != nil {+ return err+ }+ ctx, cancel := cli.APIContext(context.Background())+ defer cancel()++ wf, err := resolveWorkflow(ctx, client, args[0])+ if err != nil {+ return fmt.Errorf("resolve workflow: %w", err)+ }+ id := strVal(wf, "id")+ if err := client.DeleteJSON(ctx, "/api/issue-workflows/"+id); err != nil {+ return fmt.Errorf("delete workflow: %w", err)+ }+ if output, _ := cmd.Flags().GetString("output"); output == "json" {+ return cli.PrintJSON(os.Stdout, map[string]any{"id": id, "deleted": true})+ }+ fmt.Fprintf(os.Stdout, "Workflow %s deleted.\n", strVal(wf, "name"))+ return nil+}++func runWorkflowHandoffSet(cmd *cobra.Command, args []string) error {+ statusKey := strings.TrimSpace(args[1])+ if cmd.Flags().Changed("instructions") && cmd.Flags().Changed("instructions-file") {+ return fmt.Errorf("use either --instructions or --instructions-file, not both")+ }++ client, err := newAPIClient(cmd)+ if err != nil {+ return err+ }+ ctx, cancel := cli.APIContext(context.Background())+ defer cancel()++ wf, err := resolveWorkflow(ctx, client, args[0])+ if err != nil {+ return fmt.Errorf("resolve workflow: %w", err)+ }+ var current map[string]any+ for _, s := range workflowSteps(wf) {+ if strVal(s, "status_key") == statusKey {+ current = s+ break+ }+ }+ if current == nil {+ return fmt.Errorf("workflow %s has no step %q", strVal(wf, "name"), statusKey)+ }++ // The API replaces the whole handoff; start from the current step so+ // only the flags passed change.+ body := map[string]any{+ "handler": current["handler"],+ "instructions": strVal(current, "instructions"),+ "next_status_key": strVal(current, "next_status_key"),+ "back_status_key": strVal(current, "back_status_key"),+ }+ if cmd.Flags().Changed("handler") {+ v, _ := cmd.Flags().GetString("handler")+ handler, err := resolveHandoffHandler(ctx, client, v)+ if err != nil {+ return err+ }+ body["handler"] = handler+ }+ if cmd.Flags().Changed("instructions") {+ v, _ := cmd.Flags().GetString("instructions")+ body["instructions"] = v+ }+ if path, _ := cmd.Flags().GetString("instructions-file"); path != "" {+ data, err := os.ReadFile(path)+ if err != nil {+ return fmt.Errorf("read --instructions-file: %w", err)+ }+ body["instructions"] = string(data)+ }+ if cmd.Flags().Changed("next") {+ v, _ := cmd.Flags().GetString("next")+ body["next_status_key"] = v+ }+ if cmd.Flags().Changed("back") {+ v, _ := cmd.Flags().GetString("back")+ body["back_status_key"] = v+ }+ if v, _ := cmd.Flags().GetString("copy-for-project"); v != "" {+ projectRef, err := resolveProjectID(ctx, client, v)+ if err != nil {+ return fmt.Errorf("resolve project: %w", err)+ }+ body["copy_for_project_id"] = projectRef.ID+ }++ var result map[string]any+ path := "/api/issue-workflows/" + strVal(wf, "id") + "/handoffs/" + url.PathEscape(statusKey)+ if err := client.PutJSON(ctx, path, body, &result); err != nil {+ return fmt.Errorf("set handoff: %w", err)+ }+ if output, _ := cmd.Flags().GetString("output"); output == "table" {+ printWorkflowTable(result)+ return nil+ }+ return cli.PrintJSON(os.Stdout, result)+}++// --- project workflow commands ---++func runProjectWorkflowGet(cmd *cobra.Command, args []string) error {+ client, err := newAPIClient(cmd)+ if err != nil {+ return err+ }+ ctx, cancel := cli.APIContext(context.Background())+ defer cancel()++ projectRef, err := resolveProjectID(ctx, client, args[0])+ if err != nil {+ return fmt.Errorf("resolve project: %w", err)+ }+ var project map[string]any+ if err := client.GetJSON(ctx, "/api/projects/"+projectRef.ID, &project); err != nil {+ return fmt.Errorf("get project: %w", err)+ }+ ref := strVal(project, "workflow_id")+ usesDefault := ref == ""+ if usesDefault {+ ref = "default"+ }+ wf, err := resolveWorkflow(ctx, client, ref)+ if err != nil {+ return fmt.Errorf("get workflow: %w", err)+ }++ if output, _ := cmd.Flags().GetString("output"); output == "table" {+ if usesDefault {+ fmt.Fprintln(os.Stdout, "Project uses the workspace Default workflow.")+ }+ printWorkflowTable(wf)+ return nil+ }+ return cli.PrintJSON(os.Stdout, map[string]any{+ "project_id": projectRef.ID,+ "uses_default": usesDefault,+ "workflow": wf,+ })+}++func runProjectWorkflowSet(cmd *cobra.Command, args []string) error {+ pairs, _ := cmd.Flags().GetStringArray("map")+ mapping, err := parseStatusMapping(pairs)+ if err != nil {+ return err+ }+ dryRun, _ := cmd.Flags().GetBool("dry-run")++ client, err := newAPIClient(cmd)+ if err != nil {+ return err+ }+ ctx, cancel := cli.APIContext(context.Background())+ defer cancel()++ projectRef, err := resolveProjectID(ctx, client, args[0])+ if err != nil {+ return fmt.Errorf("resolve project: %w", err)+ }+ // workflow_id null switches back to Default.+ body := map[string]any{"workflow_id": nil}+ if !strings.EqualFold(strings.TrimSpace(args[1]), "default") {+ wf, err := resolveWorkflow(ctx, client, args[1])+ if err != nil {+ return fmt.Errorf("resolve workflow: %w", err)+ }+ body["workflow_id"] = strVal(wf, "id")+ }+ if mapping != nil {+ body["status_mapping"] = mapping+ }+ if dryRun {+ body["dry_run"] = true+ }++ var result map[string]any+ if err := client.PostJSON(ctx, "/api/projects/"+projectRef.ID+"/workflow", body, &result); err != nil {+ if reported := reportMappingRequired(cmd, err); reported != nil {+ return reported+ }+ return fmt.Errorf("set project workflow: %w", err)+ }+ if output, _ := cmd.Flags().GetString("output"); output == "table" {+ plan, _ := result["plan"].(map[string]any)+ if dryRun {+ printMappingPlan(plan)+ return nil+ }+ fmt.Fprintf(os.Stdout, "Project workflow changed; %v issue(s) moved.\n", result["updated_issues"])+ return nil+ }+ return cli.PrintJSON(os.Stdout, result)+}diff --git a/server/cmd/multica/cmd_workflow_test.go b/server/cmd/multica/cmd_workflow_test.gonew file mode 100644index 0000000000..f43d4c57c0--- /dev/null+++ b/server/cmd/multica/cmd_workflow_test.go@@ -0,0 +1,440 @@+package main++import (+ "encoding/json"+ "fmt"+ "net/http"+ "net/http/httptest"+ "strings"+ "sync"+ "testing"++ "github.com/spf13/cobra"+)++const (+ testWorkflowUUID = "22222222-2222-2222-2222-222222222222"+ testDefaultUUID = "33333333-3333-3333-3333-333333333333"+ testProjectUUID = "44444444-4444-4444-4444-444444444444"+ testAgentUUID = "55555555-5555-5555-5555-555555555555"+)++type recordedRequest struct {+ Method string+ Path string+ Body map[string]any+}++// workflowTestServer serves a small fixed workspace: a Default workflow, a+// "Review flow" workflow, and one project that uses Default.+func workflowTestServer(t *testing.T) (*httptest.Server, *[]recordedRequest) {+ t.Helper()+ var mu sync.Mutex+ var reqs []recordedRequest+ review := map[string]any{+ "id": testWorkflowUUID, "name": "Review flow", "is_default": false,+ "project_ids": []any{},+ "steps": []any{+ map[string]any{"status_key": "todo", "handler": map[string]any{"type": "none"}},+ map[string]any{+ "status_key": "in_review", "handler": map[string]any{"type": "agent", "id": testAgentUUID},+ "instructions": "Review the PR", "next_status_key": "done", "back_status_key": "todo",+ },+ map[string]any{"status_key": "done", "handler": map[string]any{"type": "none"}},+ },+ }+ def := map[string]any{+ "id": testDefaultUUID, "name": "Default", "is_default": true,+ "project_ids": []any{testProjectUUID}, "steps": []any{},+ }+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ rec := recordedRequest{Method: r.Method, Path: r.URL.Path}+ if r.Body != nil && (r.Method == http.MethodPost || r.Method == http.MethodPatch || r.Method == http.MethodPut) {+ _ = json.NewDecoder(r.Body).Decode(&rec.Body)+ }+ mu.Lock()+ reqs = append(reqs, rec)+ mu.Unlock()++ switch {+ case r.Method == http.MethodGet && r.URL.Path == "/api/issue-workflows":+ _ = json.NewEncoder(w).Encode(map[string]any{"workflows": []any{def, review}, "total": 2})+ case r.Method == http.MethodGet && r.URL.Path == "/api/issue-workflows/"+testWorkflowUUID:+ _ = json.NewEncoder(w).Encode(review)+ case r.Method == http.MethodGet && r.URL.Path == "/api/projects/"+testProjectUUID:+ _ = json.NewEncoder(w).Encode(map[string]any{"id": testProjectUUID, "title": "P", "workflow_id": nil})+ case r.Method == http.MethodPost && r.URL.Path == "/api/projects/"+testProjectUUID+"/workflow":+ _ = json.NewEncoder(w).Encode(map[string]any{"dry_run": true, "plan": map[string]any{"required": []any{}, "total_issues": 3, "affected_issues": 0}})+ case r.Method == http.MethodPut && strings.HasPrefix(r.URL.Path, "/api/issue-workflows/"+testWorkflowUUID+"/handoffs/"):+ _ = json.NewEncoder(w).Encode(review)+ case r.Method == http.MethodPatch && r.URL.Path == "/api/issue-workflows/"+testWorkflowUUID:+ _ = json.NewEncoder(w).Encode(map[string]any{"dry_run": true, "plan": map[string]any{}})+ case r.Method == http.MethodDelete && r.URL.Path == "/api/issue-workflows/"+testWorkflowUUID:+ w.WriteHeader(http.StatusNoContent)+ default:+ t.Errorf("unexpected request %s %s", r.Method, r.URL.Path)+ w.WriteHeader(http.StatusNotFound)+ }+ }))+ t.Cleanup(srv.Close)+ setCLITestServerEnv(t, srv.URL)+ return srv, &reqs+}++func lastRequest(t *testing.T, reqs []recordedRequest, method string) recordedRequest {+ t.Helper()+ for i := len(reqs) - 1; i >= 0; i-- {+ if reqs[i].Method == method {+ return reqs[i]+ }+ }+ t.Fatalf("no %s request recorded; got %+v", method, reqs)+ return recordedRequest{}+}++func TestParseStatusMapping(t *testing.T) {+ got, err := parseStatusMapping([]string{"qa=in_review", " blocked = todo "})+ if err != nil {+ t.Fatalf("parse: %v", err)+ }+ if got["qa"] != "in_review" || got["blocked"] != "todo" || len(got) != 2 {+ t.Fatalf("mapping = %v", got)+ }+ for _, bad := range [][]string{{"qa"}, {"=todo"}, {"qa="}, {"qa=a", "qa=b"}} {+ if _, err := parseStatusMapping(bad); err == nil {+ t.Errorf("parseStatusMapping(%v) = nil error, want error", bad)+ }+ }+ if got, err := parseStatusMapping(nil); err != nil || got != nil {+ t.Fatalf("empty input = %v, %v; want nil, nil", got, err)+ }+}++func TestResolveWorkflowByNameDefaultAndPrefix(t *testing.T) {+ _, _ = workflowTestServer(t)+ cmd := &cobra.Command{}+ client, err := newAPIClient(cmd)+ if err != nil {+ t.Fatal(err)+ }+ ctx := t.Context()+ for input, want := range map[string]string{+ "default": testDefaultUUID,+ "review FLOW": testWorkflowUUID,+ "22222222": testWorkflowUUID,+ testWorkflowUUID: testWorkflowUUID,+ } {+ wf, err := resolveWorkflow(ctx, client, input)+ if err != nil {+ t.Fatalf("resolveWorkflow(%q): %v", input, err)+ }+ if strVal(wf, "id") != want {+ t.Errorf("resolveWorkflow(%q) = %s, want %s", input, strVal(wf, "id"), want)+ }+ }+ if _, err := resolveWorkflow(ctx, client, "nope"); err == nil {+ t.Fatal("resolveWorkflow(nope) = nil error, want error")+ }+}++func TestProjectWorkflowSetSendsMappingAndDryRun(t *testing.T) {+ _, reqs := workflowTestServer(t)+ cmd := &cobra.Command{}+ cmd.Flags().StringArray("map", nil, "")+ cmd.Flags().Bool("dry-run", false, "")+ cmd.Flags().String("output", "json", "")+ _ = cmd.Flags().Set("map", "in_progress=in_review")+ _ = cmd.Flags().Set("dry-run", "true")++ if err := runProjectWorkflowSet(cmd, []string{testProjectUUID, "Review flow"}); err != nil {+ t.Fatalf("run: %v", err)+ }+ post := lastRequest(t, *reqs, http.MethodPost)+ if post.Path != "/api/projects/"+testProjectUUID+"/workflow" {+ t.Fatalf("path = %s", post.Path)+ }+ if post.Body["workflow_id"] != testWorkflowUUID || post.Body["dry_run"] != true {+ t.Fatalf("body = %v", post.Body)+ }+ mapping, _ := post.Body["status_mapping"].(map[string]any)+ if mapping["in_progress"] != "in_review" {+ t.Fatalf("status_mapping = %v", post.Body["status_mapping"])+ }+}++func TestProjectWorkflowSetDefaultSendsNull(t *testing.T) {+ _, reqs := workflowTestServer(t)+ cmd := &cobra.Command{}+ cmd.Flags().StringArray("map", nil, "")+ cmd.Flags().Bool("dry-run", false, "")+ cmd.Flags().String("output", "json", "")++ if err := runProjectWorkflowSet(cmd, []string{testProjectUUID, "Default"}); err != nil {+ t.Fatalf("run: %v", err)+ }+ post := lastRequest(t, *reqs, http.MethodPost)+ v, present := post.Body["workflow_id"]+ if !present || v != nil {+ t.Fatalf("workflow_id = %v (present=%v), want explicit null", v, present)+ }+ if _, ok := post.Body["dry_run"]; ok {+ t.Fatalf("dry_run sent without --dry-run: %v", post.Body)+ }+}++func TestWorkflowHandoffSetKeepsUnchangedFields(t *testing.T) {+ _, reqs := workflowTestServer(t)+ cmd := &cobra.Command{}+ cmd.Flags().String("handler", "", "")+ cmd.Flags().String("instructions", "", "")+ cmd.Flags().String("instructions-file", "", "")+ cmd.Flags().String("next", "", "")+ cmd.Flags().String("back", "", "")+ cmd.Flags().String("copy-for-project", "", "")+ cmd.Flags().String("output", "json", "")+ _ = cmd.Flags().Set("instructions", "Check tests too")+ _ = cmd.Flags().Set("back", "")++ if err := runWorkflowHandoffSet(cmd, []string{testWorkflowUUID, "in_review"}); err != nil {+ t.Fatalf("run: %v", err)+ }+ put := lastRequest(t, *reqs, http.MethodPut)+ if put.Path != "/api/issue-workflows/"+testWorkflowUUID+"/handoffs/in_review" {+ t.Fatalf("path = %s", put.Path)+ }+ handler, _ := put.Body["handler"].(map[string]any)+ if handler["type"] != "agent" || handler["id"] != testAgentUUID {+ t.Fatalf("handler = %v, want the existing agent kept", put.Body["handler"])+ }+ if put.Body["instructions"] != "Check tests too" {+ t.Fatalf("instructions = %v", put.Body["instructions"])+ }+ if put.Body["next_status_key"] != "done" {+ t.Fatalf("next_status_key = %v, want kept", put.Body["next_status_key"])+ }+ if put.Body["back_status_key"] != "" {+ t.Fatalf("back_status_key = %v, want cleared", put.Body["back_status_key"])+ }+}++func TestWorkflowHandoffSetRejectsUnknownStep(t *testing.T) {+ _, _ = workflowTestServer(t)+ cmd := &cobra.Command{}+ cmd.Flags().String("handler", "", "")+ cmd.Flags().String("instructions", "", "")+ cmd.Flags().String("instructions-file", "", "")+ cmd.Flags().String("next", "", "")+ cmd.Flags().String("back", "", "")+ cmd.Flags().String("copy-for-project", "", "")+ cmd.Flags().String("output", "json", "")+ if err := runWorkflowHandoffSet(cmd, []string{testWorkflowUUID, "qa"}); err == nil {+ t.Fatal("want error for a status the workflow does not list")+ }+}++func TestWorkflowUpdateRequiresAField(t *testing.T) {+ cmd := &cobra.Command{}+ cmd.Flags().String("name", "", "")+ cmd.Flags().String("description", "", "")+ cmd.Flags().String("steps-file", "", "")+ cmd.Flags().StringArray("map", nil, "")+ cmd.Flags().Bool("dry-run", false, "")+ cmd.Flags().String("output", "json", "")+ _ = cmd.Flags().Set("dry-run", "true")+ if err := runWorkflowUpdate(cmd, []string{testWorkflowUUID}); err == nil || !strings.Contains(err.Error(), "nothing to update") {+ t.Fatalf("err = %v, want nothing to update", err)+ }+}++func TestWorkflowUpdateSendsPatch(t *testing.T) {+ _, reqs := workflowTestServer(t)+ cmd := &cobra.Command{}+ cmd.Flags().String("name", "", "")+ cmd.Flags().String("description", "", "")+ cmd.Flags().String("steps-file", "", "")+ cmd.Flags().StringArray("map", nil, "")+ cmd.Flags().Bool("dry-run", false, "")+ cmd.Flags().String("output", "json", "")+ _ = cmd.Flags().Set("name", "Renamed")+ _ = cmd.Flags().Set("map", "qa=in_review")+ _ = cmd.Flags().Set("dry-run", "true")++ if err := runWorkflowUpdate(cmd, []string{testWorkflowUUID}); err != nil {+ t.Fatalf("run: %v", err)+ }+ patch := lastRequest(t, *reqs, http.MethodPatch)+ if patch.Body["name"] != "Renamed" || patch.Body["dry_run"] != true {+ t.Fatalf("body = %v", patch.Body)+ }+ if _, ok := patch.Body["steps"]; ok {+ t.Fatalf("steps sent without --steps-file: %v", patch.Body)+ }+}++func TestProjectWorkflowGetFallsBackToDefault(t *testing.T) {+ _, reqs := workflowTestServer(t)+ cmd := &cobra.Command{}+ cmd.Flags().String("output", "json", "")+ if err := runProjectWorkflowGet(cmd, []string{testProjectUUID}); err != nil {+ t.Fatalf("run: %v", err)+ }+ sawList := false+ for _, r := range *reqs {+ if r.Method == http.MethodGet && r.Path == "/api/issue-workflows" {+ sawList = true+ }+ }+ if !sawList {+ t.Fatalf("expected the Default workflow to be looked up from the list; got %+v", *reqs)+ }+}++// mappingRequiredServer answers every write with the server's 409+// workflow_status_mapping_required, listing two statuses to map.+func mappingRequiredServer(t *testing.T) {+ t.Helper()+ body := map[string]any{+ "error": `issues still use "qa"; map it to a status of the target workflow`,+ "code": "workflow_status_mapping_required",+ "plan": map[string]any{+ "required": []any{+ map[string]any{"status_key": "qa", "issue_count": 2, "suggested_status_key": "in_review"},+ map[string]any{"status_key": "blocked", "issue_count": 1, "suggested_status_key": "todo"},+ },+ "unchanged": []any{},+ "total_issues": 5,+ "affected_issues": 3,+ },+ }+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.Method == http.MethodGet {+ _ = json.NewEncoder(w).Encode(map[string]any{"id": testWorkflowUUID, "name": "Review flow", "steps": []any{}})+ return+ }+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(http.StatusConflict)+ _ = json.NewEncoder(w).Encode(body)+ }))+ t.Cleanup(srv.Close)+ setCLITestServerEnv(t, srv.URL)+}++func newProjectWorkflowSetTestCmd(output string) *cobra.Command {+ cmd := &cobra.Command{}+ cmd.Flags().StringArray("map", nil, "")+ cmd.Flags().Bool("dry-run", false, "")+ cmd.Flags().String("output", output, "")+ return cmd+}++func TestProjectWorkflowSetMappingRequiredPrintsFullPlanJSON(t *testing.T) {+ mappingRequiredServer(t)+ cmd := newProjectWorkflowSetTestCmd("json")+ out, err := captureStdout(t, func() error {+ return runProjectWorkflowSet(cmd, []string{testProjectUUID, testWorkflowUUID})+ })+ if err != errSilent {+ t.Fatalf("err = %v, want errSilent so the command exits non-zero without printing twice", err)+ }+ var got map[string]any+ if jerr := json.Unmarshal([]byte(out), &got); jerr != nil {+ t.Fatalf("stdout is not JSON: %v\n%s", jerr, out)+ }+ if got["code"] != "workflow_status_mapping_required" {+ t.Fatalf("code = %v", got["code"])+ }+ plan, _ := got["plan"].(map[string]any)+ required, _ := plan["required"].([]any)+ if len(required) != 2 {+ t.Fatalf("plan.required has %d entries, want both statuses: %s", len(required), out)+ }+}++func TestWorkflowUpdateMappingRequiredPrintsPlanTable(t *testing.T) {+ mappingRequiredServer(t)+ cmd := &cobra.Command{}+ cmd.Flags().String("name", "", "")+ cmd.Flags().String("description", "", "")+ cmd.Flags().String("steps-file", "", "")+ cmd.Flags().StringArray("map", nil, "")+ cmd.Flags().Bool("dry-run", false, "")+ cmd.Flags().String("output", "table", "")+ _ = cmd.Flags().Set("name", "Renamed")+ out, err := captureStdout(t, func() error {+ return runWorkflowUpdate(cmd, []string{testWorkflowUUID})+ })+ if err != errSilent {+ t.Fatalf("err = %v, want errSilent", err)+ }+ for _, want := range []string{"qa", "in_review", "blocked", "todo"} {+ if !strings.Contains(out, want) {+ t.Errorf("table output missing %q:\n%s", want, out)+ }+ }+}++func TestProjectWorkflowSetOtherConflictKeepsDefaultError(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(http.StatusForbidden)+ _, _ = w.Write([]byte(`{"error":"only workspace admins and the project lead can change this project's workflow"}`))+ }))+ t.Cleanup(srv.Close)+ setCLITestServerEnv(t, srv.URL)+ cmd := newProjectWorkflowSetTestCmd("json")+ out, err := captureStdout(t, func() error {+ return runProjectWorkflowSet(cmd, []string{testProjectUUID, "default"})+ })+ if err == nil || err == errSilent {+ t.Fatalf("err = %v, want the HTTP error for the default formatter", err)+ }+ if out != "" {+ t.Fatalf("stdout = %q, want empty", out)+ }+}++// The same plan with 45 statuses runs past 4 KiB; the command must still+// print all of it through the real HTTP client.+func TestProjectWorkflowSetMappingRequiredKeepsLargePlan(t *testing.T) {+ required := make([]any, 0, 45)+ for i := 0; i < 45; i++ {+ required = append(required, map[string]any{+ "status_key": fmt.Sprintf("custom_status_with_a_long_key_%02d", i),+ "issue_count": 1,+ "suggested_status_key": "todo",+ })+ }+ payload, _ := json.Marshal(map[string]any{+ "error": "map every status", "code": "workflow_status_mapping_required",+ "plan": map[string]any{"required": required, "unchanged": []any{}, "total_issues": 45, "affected_issues": 45},+ })+ if len(payload) <= 4096 {+ t.Fatalf("fixture is %d bytes; it must exceed 4096", len(payload))+ }+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.Method == http.MethodGet {+ _ = json.NewEncoder(w).Encode(map[string]any{"id": testWorkflowUUID, "name": "Review flow", "steps": []any{}})+ return+ }+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(http.StatusConflict)+ _, _ = w.Write(payload)+ }))+ t.Cleanup(srv.Close)+ setCLITestServerEnv(t, srv.URL)++ cmd := newProjectWorkflowSetTestCmd("json")+ out, err := captureStdout(t, func() error {+ return runProjectWorkflowSet(cmd, []string{testProjectUUID, testWorkflowUUID})+ })+ if err != errSilent {+ t.Fatalf("err = %v, want errSilent", err)+ }+ var got map[string]any+ if jerr := json.Unmarshal([]byte(out), &got); jerr != nil {+ t.Fatalf("stdout is not JSON: %v", jerr)+ }+ plan, _ := got["plan"].(map[string]any)+ if rows, _ := plan["required"].([]any); len(rows) != 45 {+ t.Fatalf("plan.required has %d rows, want 45", len(rows))+ }+}diff --git a/server/cmd/multica/main.go b/server/cmd/multica/main.goindex 626149dc82..62276b7e4e 100644--- a/server/cmd/multica/main.go+++ b/server/cmd/multica/main.go@@ -50,6 +50,7 @@ func init() {// Core commandsissueCmd.GroupID = groupCoreprojectCmd.GroupID = groupCore+ workflowCmd.GroupID = groupCorelabelCmd.GroupID = groupCorepropertyCmd.GroupID = groupCoreagentCmd.GroupID = groupCore@@ -76,6 +77,7 @@ func init() {rootCmd.AddCommand(issueCmd)rootCmd.AddCommand(projectCmd)+ rootCmd.AddCommand(workflowCmd)rootCmd.AddCommand(labelCmd)rootCmd.AddCommand(propertyCmd)rootCmd.AddCommand(agentCmd)diff --git a/server/internal/cli/client.go b/server/internal/cli/client.goindex 9834237857..84fd220449 100644--- a/server/internal/cli/client.go+++ b/server/internal/cli/client.go@@ -92,13 +92,19 @@ func (e *HTTPError) Error() string {return fmt.Sprintf("%s %s returned %d: %s", e.Method, e.Path, e.StatusCode, strings.TrimSpace(e.Body))}+// maxErrorBodyBytes caps how much of an error response is kept. It must hold+// a whole structured error: a workflow's 409 status mapping plan lists one row+// per status in use (up to 50) and runs past 4 KiB, and a truncated body no+// longer parses as JSON. Only --debug prints the raw body.+const maxErrorBodyBytes = 64 << 10+// newHTTPError builds a *HTTPError from an error response (status >= 400),// reading a capped slice of the body. Every Multica API helper funnels its// >= 400 responses through this so the top-level FormatError / ExitCodeFor can// classify the failure via errors.As(err, **HTTPError) regardless of which// HTTP verb the command used.func newHTTPError(method, path string, resp *http.Response) *HTTPError {- data, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))+ data, _ := io.ReadAll(io.LimitReader(resp.Body, maxErrorBodyBytes))return &HTTPError{Method: method,Path: path,diff --git a/server/internal/cli/client_test.go b/server/internal/cli/client_test.goindex e3c25eceb7..44594aa88c 100644--- a/server/internal/cli/client_test.go+++ b/server/internal/cli/client_test.go@@ -625,3 +625,48 @@ func TestHTTPErrorTaskScopedFollowsTheRequestNotTheClient(t *testing.T) {}})}++// A structured error body past 4 KiB must arrive whole: callers parse it as+// JSON (e.g. a workflow's 409 status mapping plan), and a cut body does not+// parse.+func TestHTTPErrorKeepsLargeStructuredBody(t *testing.T) {+ required := make([]map[string]any, 0, 45)+ for i := 0; i < 45; i++ {+ required = append(required, map[string]any{+ "status_key": "custom_status_" + strings.Repeat("x", 20) + string(rune('a'+i%26)) + string(rune('a'+i/26)),+ "issue_count": 1, "suggested_status_key": "todo",+ })+ }+ payload, _ := json.Marshal(map[string]any{+ "error": "map every status", "code": "workflow_status_mapping_required",+ "plan": map[string]any{"required": required},+ })+ if len(payload) <= 4096 {+ t.Fatalf("fixture is %d bytes; it must exceed 4096 to cover the old cap", len(payload))+ }+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(http.StatusConflict)+ _, _ = w.Write(payload)+ }))+ defer srv.Close()++ client := NewAPIClient(srv.URL, "", "test-token")+ err := client.PostJSON(context.Background(), "/api/projects/p/workflow", map[string]any{}, nil)+ var httpErr *HTTPError+ if !errors.As(err, &httpErr) {+ t.Fatalf("err = %v, want *HTTPError", err)+ }+ var got struct {+ Code string `json:"code"`+ Plan struct {+ Required []any `json:"required"`+ } `json:"plan"`+ }+ if jerr := json.Unmarshal([]byte(httpErr.Body), &got); jerr != nil {+ t.Fatalf("body of %d bytes did not parse (kept %d): %v", len(payload), len(httpErr.Body), jerr)+ }+ if got.Code != "workflow_status_mapping_required" || len(got.Plan.Required) != 45 {+ t.Fatalf("code = %q, required = %d; want the full plan", got.Code, len(got.Plan.Required))+ }+}diff --git a/server/internal/service/builtin_skills/multica-platform/SKILL.md b/server/internal/service/builtin_skills/multica-platform/SKILL.mdindex bfa75722a0..6318325a76 100644--- a/server/internal/service/builtin_skills/multica-platform/SKILL.md+++ b/server/internal/service/builtin_skills/multica-platform/SKILL.md@@ -24,7 +24,7 @@ Read the invariants below, then open the reference(s) your task actually needs| `references/agents.md` | Creating, copying or debugging an agent definition: fields, secrets, MCP config, skill binding || `references/squads.md` | Squads: leader routing, roster, recording leader activity, why a squad did or did not run || `references/autopilots.md` | Autopilots: schedule / webhook / manual triggers, `create_issue` vs `run_only`, why one did not fire |-| `references/projects.md` | Projects and their durable resources (`github_repo`, `local_directory`, worktree mode); project workflows — status columns, handoffs, a `[Project workflow]` block in your prompt |+| `references/projects.md` | Projects and their durable resources (`github_repo`, `local_directory`, worktree mode); project workflows — status columns, handoffs, a `[Project workflow]` block in your prompt, reading or changing a workflow (`multica workflow`, `multica project workflow`) || `references/runtimes.md` | Runtimes, daemons, `repo checkout`, and the task CLI boundary || `references/skill-import.md` | Importing a skill into this workspace from a URL or a local archive |diff --git a/server/internal/service/builtin_skills/multica-platform/references/projects.md b/server/internal/service/builtin_skills/multica-platform/references/projects.mdindex 5b04f04f1e..6d4478c3e4 100644--- a/server/internal/service/builtin_skills/multica-platform/references/projects.md+++ b/server/internal/service/builtin_skills/multica-platform/references/projects.md@@ -12,6 +12,7 @@ display metadata; it is context later injected into task briefs and- [Debugging wrong context](#debugging-wrong-context)- [Side effects](#side-effects)- [Project workflows](#project-workflows)+- [Reading and changing workflows](#reading-and-changing-workflows)## Core model@@ -200,3 +201,34 @@ reference (`in_progress` on start, `in_review` on delivery) do not apply.- **No `blocked` column.** When the workflow has none, comment why you cannotproceed, then use the "needs changes" status if the step has one, or leavethe status as it is.++## Reading and changing workflows++Use these only when the task is about the workflow itself: who handles a+status, a step's instructions, or which workflow a project uses. Working an+issue inside a workflow needs none of them.++- Read first: `multica workflow list`, `multica workflow get <workflow>`+ (an ID, ID prefix, exact name, or `default`), and+ `multica project workflow get <project-id>`, which returns the effective+ workflow with `uses_default: true` when the project has none set.+- One step: `multica workflow handoff set <workflow> <status-key>` with+ `--handler` (`none`, `project_lead`, `creator`, or a member/agent/squad),+ `--instructions` / `--instructions-file`, `--next`, `--back`. Flags you do+ not pass keep their current value. The change applies to every project on+ that workflow; `--copy-for-project <project-id>` saves it on a copy only that+ project uses.+- Whole workflow: `multica workflow create|update --steps-file <json>`+ replaces all steps; `multica workflow delete` is refused for Default and for+ a workflow a project still uses.+- Switching: `multica project workflow set <project-id> <workflow|default>`.+ Run it with `--dry-run` first. Issues on statuses the target lacks need+ `--map old=new`; a missing mapping fails with+ `workflow_status_mapping_required` and the plan. Pick each target from the+ plan or ask; never guess. The move neither reassigns issues nor starts runs.+- Permissions are the server's: editing or deleting a workflow needs its owner+ or a workspace admin, switching a project needs an admin or the project+ lead. A 403 is the answer, not something to work around.++All of these except the reads change what every later issue in those projects+does. Ask before running one the user did not request.