From cc8c7ad9a1b2d5b5dd783e818330f2dc100b38bb Mon Sep 17 00:00:00 2001 From: fullsend-code <278716306+fullsend-ai-coder[bot]@users.noreply.github.com> Date: Sun, 29 Nov 2026 11:45:20 +0000 Subject: [PATCH 1/4] feat(#9536)!: resolve Jira started and closed states from status categories `fullsend issues transition --state` now finds the Jira transition by status category, so repositories no longer need to configure status names for starting or closing an issue. - `--state started` (Jira only) takes the available transition whose target status category is `indeterminate`. It does nothing on an issue that is already in progress or done, so a re-run is safe and a start never reopens a closed issue. GitHub and GitLab return ErrNotSupported, and `--resolution` is rejected with it. - When several transitions fit `started` or `closed`, Jira's default status names break the tie: In Progress for a start; Done, then Closed, then Resolved for a close (case-insensitive). - If that still does not leave exactly one transition, nothing is written (not even the comment). The command exits 0 with a skip result: `skipped`, `reason`, and `candidates` (each with `transition` and `status`). - When a `--state closed` transition requires a resolution and none was passed, and there is no single allowed value, the site default from GET /resolution/search?onlyDefault=true is sent if the transition allows it. Otherwise it still errors. `--transition` and `--status` keep their current resolution handling. - jira.IssueType gains HierarchyLevel. The JSON result of `--state` runs includes `issue_type` and `hierarchy_level`, so callers can leave epics alone without listing type names. Docs: issues-commands guide and CLI reference updated. Note: pre-commit could not fetch its remote hook repositories (TLS failure in the sandbox). The hooks were run directly instead: whitespace/EOF checks, gofmt, go vet ./..., broken-symlink, docs-link and lychee link checks, plus the scan-secrets secret scan. All passed. The semgrep hook skipped: it could not download its pinned ruleset. BREAKING CHANGE: `--state closed` on Jira no longer exits non-zero when several done-category transitions are available and none targets a unique Done, Closed, or Resolved status. It now exits 0 with "skipped": true and lists the candidates. Callers that relied on the error must check the `skipped` field. Closes #9536 Co-Authored-By: Claude Opus 5.5 --- docs/cli/README.md | 2 +- docs/guides/user/issues-commands.md | 41 ++++-- internal/cli/issues_transition.go | 57 ++++++-- internal/cli/issues_transition_test.go | 3 + internal/forge/jira/transition.go | 28 ++++ internal/forge/jira/transition_test.go | 52 +++++++ internal/forge/jira/types.go | 4 + internal/tracker/transition.go | 191 +++++++++++++++++++++---- internal/tracker/transition_test.go | 165 ++++++++++++++++++++- 9 files changed, 494 insertions(+), 49 deletions(-) diff --git a/docs/cli/README.md b/docs/cli/README.md index bf10214f68..36aa76261f 100644 --- a/docs/cli/README.md +++ b/docs/cli/README.md @@ -37,7 +37,7 @@ To update an installed binary later, run [`fullsend self-update`](self-update.md | [`fullsend self-update`](self-update.md) | Update the local `fullsend` binary to the latest release, or to `--version`, after verifying the release's Sigstore signature and checksum. | | `fullsend eval-measure` | Score wild-run traces into `eval-measurements.jsonl`. See [Eval measurements](../guides/infrastructure/eval-measurements.md). | | `fullsend prepare-artifacts` | Build, in `--artifact-dir`, the filtered copy of a run's `--output-dir` that CI uploads as the run artifact. The level (`all`, `metadata` or `none`) comes from `config.yaml`'s [`artifacts`](../reference/config-reference.md#artifacts) setting and the run's source; a run whose source is unknown gets the strictest configured level. Prints the level on stdout and the rule it applied on stderr. If the level cannot be resolved, it leaves `--artifact-dir` empty and exits non-zero. `action.yml` and the GitLab agent job run it after `eval-measure`. See [Run artifacts and private data](../guides/user/run-artifacts-and-private-data.md). | -| `fullsend issues transition` | Transition an issue: exactly one of `--state closed`, `--transition NAME` (Jira), or `--status NAME` (Jira). Accepts `--resolution ID_OR_NAME` (Jira) and `--comment TEXT`, plus the existing `--tracker`, `--project`, `--number`, `--fullsend-dir`, and `--token` flags. See [Issue transitions](../guides/user/issues-commands.md#fullsend-issues-transition) for permissions, ambiguity handling, and partial failures. | +| `fullsend issues transition` | Transition an issue: exactly one of `--state closed`, `--state started` (Jira), `--transition NAME` (Jira), or `--status NAME` (Jira). Jira `--state` selects by status category and returns a skip listing the candidates when no single transition fits. Accepts `--resolution ID_OR_NAME` (Jira) and `--comment TEXT`, plus the existing `--tracker`, `--project`, `--number`, `--fullsend-dir`, and `--token` flags. See [Issue transitions](../guides/user/issues-commands.md#fullsend-issues-transition) for permissions, ambiguity handling, and partial failures. | ## Global flags diff --git a/docs/guides/user/issues-commands.md b/docs/guides/user/issues-commands.md index 08df50d46e..a48102cf3d 100644 --- a/docs/guides/user/issues-commands.md +++ b/docs/guides/user/issues-commands.md @@ -295,12 +295,16 @@ created in the type's outward direction: the example above records that ## `fullsend issues transition` -Close an issue through its tracker, or execute a named Jira workflow action: +Close an issue through its tracker, start a Jira issue, or execute a named Jira +workflow action: ```bash fullsend issues transition --tracker github --project owner/repo \ --number 42 --state closed --comment "Triage complete." +fullsend issues transition --fullsend-dir .fullsend --tracker jira \ + --project PROJ --number 42 --state started + fullsend issues transition --fullsend-dir .fullsend --tracker jira \ --project PROJ --number 42 --transition "Review" @@ -314,10 +318,11 @@ Exactly one of `--state`, `--transition`, or `--status` is required: | Flag | Meaning | |------|---------| -| `--state closed` | Portable closure on GitHub, GitLab, and Jira. Jira selects a unique available transition whose destination has status category `done`. | +| `--state closed` | Portable closure on GitHub, GitLab, and Jira. Jira selects the available transition whose destination has status category `done`. | +| `--state started` | Jira only. Selects the available transition whose destination has status category `indeterminate` (in progress). Does nothing when the issue is already in progress or done. GitHub and GitLab return a not-supported error. | | `--transition NAME` | Exact, case-sensitive Jira transition name, such as `Review`. This names an action, not its destination status. | | `--status NAME` | Exact Jira destination status name. Requires one available transition to that status. | -| `--resolution ID_OR_NAME` | Jira resolution selected from the transition's allowed values. Required when the transition requires a resolution without a default and does not offer exactly one valid allowed value. | +| `--resolution ID_OR_NAME` | Jira resolution selected from the transition's allowed values. Required when the transition requires a resolution without a default and does not offer exactly one valid allowed value (or, for `--state closed`, does not allow the site default resolution). Not accepted with `--state started`. | | `--comment TEXT` | Optional Markdown explanation. Jira sends it in the same request as the transition; GitHub/GitLab post it after closing. | `--tracker`, `--project`, `--number`, `--fullsend-dir`, and `--token` @@ -329,8 +334,13 @@ its connection settings in the configuration directory. The target project must other projects are rejected before a client is built. The command prints JSON with `changed`, and, where available, `transition` and -`status`. Portable closure of an already closed issue returns `changed: false`, -but still posts a requested comment. For Jira, supplying `--resolution` on an +`status`. For Jira `--state`, it also prints `issue_type` and `hierarchy_level` +(`-1` sub-task, `0` standard work, `1` epic, higher above epics) when Jira +reports them, so a caller can leave epics alone without listing type names. +Portable closure of an already closed issue returns `changed: false`, +but still posts a requested comment. `--state started` on an issue already in +progress or done also returns `changed: false` and posts a requested comment; a +start never reopens a closed issue. For Jira, supplying `--resolution` on an already closed issue instead returns an error before posting a comment: no transition would run to apply that resolution. Explicit named transitions always execute, including self-transitions. The command does not infer that an unavailable action @@ -338,11 +348,26 @@ means the issue is already at the desired destination. Jira controls allowed source states and account permissions. The account needs issue visibility and Transition Issues permission (and permission to add a comment -when one is requested). Zero or multiple matching actions fail without a write. +when one is requested). Zero matching actions fail without a write. Multiple +actions matching `--transition` or `--status` also fail without a write. + +`--state` selects by Jira status category, so no status names are configured. +When more than one available action reaches the category, the command prefers +Jira's default status names: `In Progress` for a start, and `Done`, `Closed`, +then `Resolved` for a close. If that does not leave exactly one action (none of +the names is available, or several actions reach the same name), nothing is +written, not even the comment. The command exits 0 and prints a skip that lists +the candidates; choose one with `--transition` or `--status`: + +```json +{"changed":false,"skipped":true,"reason":"2 Jira transitions on \"PROJ-42\" fit lifecycle state \"started\" ...","candidates":[{"transition":"Review","status":"Review"},{"transition":"Code","status":"Coding"}],"issue_type":"Bug","hierarchy_level":0} +``` + When Jira requires a resolution without a default, the command selects it automatically only if the allowed-values list contains exactly one valid ID. -Otherwise, supply `--resolution`; the command never chooses among different -resolution meanings. A supplied `--comment` satisfies a required comment on the +For `--state closed`, it otherwise sends the site default resolution when the +transition allows it. Otherwise, supply `--resolution`; the command never +chooses among different resolution meanings. A supplied `--comment` satisfies a required comment on the transition screen. Jira validates other required fields against the existing issue values. If a required field is missing, Jira rejects the transition and the command reports the API error. Complete those fields in Jira before retrying. diff --git a/internal/cli/issues_transition.go b/internal/cli/issues_transition.go index bec7ef4231..f18fd58d39 100644 --- a/internal/cli/issues_transition.go +++ b/internal/cli/issues_transition.go @@ -29,9 +29,20 @@ type issuesTransitionConfig struct { // issueTransitionResult is the CLI JSON representation of a tracker result. type issueTransitionResult struct { - Changed bool `json:"changed"` - Transition string `json:"transition,omitempty"` - Status string `json:"status,omitempty"` + Changed bool `json:"changed"` + Transition string `json:"transition,omitempty"` + Status string `json:"status,omitempty"` + Skipped bool `json:"skipped,omitempty"` + Reason string `json:"reason,omitempty"` + Candidates []issueTransitionCandidate `json:"candidates,omitempty"` + IssueType string `json:"issue_type,omitempty"` + HierarchyLevel *int `json:"hierarchy_level,omitempty"` +} + +// issueTransitionCandidate is one Jira transition listed in a skipped result. +type issueTransitionCandidate struct { + Transition string `json:"transition"` + Status string `json:"status"` } func newIssuesTransitionCmd() *cobra.Command { @@ -39,12 +50,23 @@ func newIssuesTransitionCmd() *cobra.Command { cmd := &cobra.Command{ Use: "transition", Short: "Transition an issue through its tracker workflow", - Long: `Close an issue with --state closed, or select an exact Jira transition -name with --transition or target status with --status. Exactly one selector -is required. Jira resolves a unique available action and accepts --resolution -when the workflow requires it. A required resolution is selected automatically -only when Jira offers exactly one valid allowed value and no default. No arbitrary -workflow action or resolution is chosen. + Long: `Close an issue with --state closed, start a Jira issue with --state started, +or select an exact Jira transition name with --transition or target status with +--status. Exactly one selector is required. Jira resolves a unique available +action and accepts --resolution when the workflow requires it. + +On Jira, --state picks the available transition whose target status category is +"indeterminate" (started) or "done" (closed), so no status names are configured. +--state started does nothing on an issue already in progress or done. When +several transitions fit, the Jira default status name wins: In Progress for a +start, then Done, Closed, Resolved for a close. If that still leaves more than +one, nothing is written and the JSON result has "skipped": true and lists the +candidates. + +A required resolution is selected automatically only when Jira offers exactly +one valid allowed value and no default, or, for --state closed, when the site +default resolution is among the allowed values. No arbitrary workflow action or +resolution is chosen. An optional --comment is sent in the same request as the Jira transition, or after closing on GitHub/GitLab. A comment failure on a forge leaves the issue closed and @@ -59,7 +81,7 @@ returns an error. Inspect the issue after an uncertain failure before retrying.` cmd.Flags().IntVar(&cfg.number, "number", 0, "issue number (required)") cmd.Flags().StringVar(&cfg.fullsendDir, "fullsend-dir", "", fullsendDirFlagUsage) cmd.Flags().StringVar(&cfg.token, "token", "", tokenFlagUsage) - cmd.Flags().StringVar(&cfg.opts.State, "state", "", "semantic lifecycle state: closed") + cmd.Flags().StringVar(&cfg.opts.State, "state", "", "semantic lifecycle state: started (Jira only) or closed") cmd.Flags().StringVar(&cfg.opts.Name, "transition", "", "exact Jira transition name") cmd.Flags().StringVar(&cfg.opts.Status, "status", "", "exact Jira target status name") cmd.Flags().StringVar(&cfg.opts.Resolution, "resolution", "", "Jira resolution ID or name allowed by the transition") @@ -114,9 +136,18 @@ func runIssuesTransition(ctx context.Context, cfg *issuesTransitionConfig) error if out == nil { out = os.Stdout } + var candidates []issueTransitionCandidate + for _, c := range result.Candidates { + candidates = append(candidates, issueTransitionCandidate{Transition: c.Transition, Status: c.Status}) + } return json.NewEncoder(out).Encode(issueTransitionResult{ - Changed: result.Changed, - Transition: result.Transition, - Status: result.Status, + Changed: result.Changed, + Transition: result.Transition, + Status: result.Status, + Skipped: result.Skipped, + Reason: result.Reason, + Candidates: candidates, + IssueType: result.IssueType, + HierarchyLevel: result.HierarchyLevel, }) } diff --git a/internal/cli/issues_transition_test.go b/internal/cli/issues_transition_test.go index b791e3b9fe..460da77047 100644 --- a/internal/cli/issues_transition_test.go +++ b/internal/cli/issues_transition_test.go @@ -93,6 +93,7 @@ type failingTransitionWriter struct{} func (failingTransitionWriter) Write([]byte) (int, error) { return 0, errors.New("write failed") } func TestRunIssuesTransitionJSONContract(t *testing.T) { + zeroLevel, epicLevel := 0, 1 for _, tt := range []struct { name string result tracker.TransitionResult @@ -100,6 +101,8 @@ func TestRunIssuesTransitionJSONContract(t *testing.T) { }{ {"changed", tracker.TransitionResult{Changed: true, Transition: "Review", Status: "In Review"}, `{"changed":true,"transition":"Review","status":"In Review"}`}, {"already closed", tracker.TransitionResult{Status: "Closed"}, `{"changed":false,"status":"Closed"}`}, + {"skipped", tracker.TransitionResult{Skipped: true, Reason: "ambiguous", Candidates: []tracker.TransitionCandidate{{Transition: "Review", Status: "Review"}, {Transition: "Code", Status: "Coding"}}, IssueType: "Bug", HierarchyLevel: &zeroLevel}, `{"changed":false,"skipped":true,"reason":"ambiguous","candidates":[{"transition":"Review","status":"Review"},{"transition":"Code","status":"Coding"}],"issue_type":"Bug","hierarchy_level":0}`}, + {"started", tracker.TransitionResult{Changed: true, Transition: "Start", Status: "In Progress", IssueType: "Epic", HierarchyLevel: &epicLevel}, `{"changed":true,"transition":"Start","status":"In Progress","issue_type":"Epic","hierarchy_level":1}`}, } { t.Run(tt.name, func(t *testing.T) { var out bytes.Buffer diff --git a/internal/forge/jira/transition.go b/internal/forge/jira/transition.go index 1ba12dda5c..075752e2b9 100644 --- a/internal/forge/jira/transition.go +++ b/internal/forge/jira/transition.go @@ -7,6 +7,7 @@ import ( "fmt" "net/http" "net/url" + "strings" ) // Transition is an action available to the caller in the issue's current workflow. @@ -60,3 +61,30 @@ func (c *LiveClient) ApplyTransition(ctx context.Context, issueIDOrKey, id strin } return nil } + +// Resolution is a Jira issue resolution. The site-default flag is decoded +// from both "default" and "isDefault", so either spelling is honored. +type Resolution struct { + ID string `json:"id"` + Name string `json:"name"` + Default bool `json:"default"` + IsDefault bool `json:"isDefault"` +} + +// DefaultResolution returns the site's default resolution, or nil when the +// site has none. Reading resolutions needs no Jira administrator rights. +func (c *LiveClient) DefaultResolution(ctx context.Context) (*Resolution, error) { + var page struct { + Values []Resolution `json:"values"` + } + if err := c.do(ctx, http.MethodGet, "/resolution/search?onlyDefault=true", nil, &page); err != nil { + return nil, fmt.Errorf("get default resolution: %w", err) + } + for i := range page.Values { + r := page.Values[i] + if (r.Default || r.IsDefault) && strings.TrimSpace(r.ID) != "" { + return &r, nil + } + } + return nil, nil +} diff --git a/internal/forge/jira/transition_test.go b/internal/forge/jira/transition_test.go index 63407225f3..7210f595ff 100644 --- a/internal/forge/jira/transition_test.go +++ b/internal/forge/jira/transition_test.go @@ -62,3 +62,55 @@ func TestTransitionErrorsAndNoRetry(t *testing.T) { c, _ := setupTest(t) require.ErrorContains(t, c.ApplyTransition(context.Background(), "P-1", "1", map[string]any{"bad": make(chan int)}, ""), "encode transition") } + +func TestDefaultResolution(t *testing.T) { + for _, tt := range []struct { + name string + values string + status int + wantID string + err bool + }{ + {name: "default field", values: `[{"id":"10000","name":"Done","default":true}]`, wantID: "10000"}, + {name: "isDefault field", values: `[{"id":"10001","name":"Done","isDefault":true}]`, wantID: "10001"}, + {name: "none", values: `[]`}, + {name: "not flagged", values: `[{"id":"10000","name":"Done"}]`}, + {name: "empty id", values: `[{"id":" ","default":true}]`}, + {name: "error", status: 403, err: true}, + } { + t.Run(tt.name, func(t *testing.T) { + c, mux := setupTest(t) + mux.HandleFunc("/rest/api/3/resolution/search", func(w http.ResponseWriter, r *http.Request) { + assert.Equal(t, http.MethodGet, r.Method) + assert.Equal(t, "true", r.URL.Query().Get("onlyDefault")) + if tt.status != 0 { + w.WriteHeader(tt.status) + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"isLast":true,"values":` + tt.values + `}`)) + }) + r, err := c.DefaultResolution(context.Background()) + if tt.err { + require.ErrorContains(t, err, "default resolution") + return + } + require.NoError(t, err) + if tt.wantID == "" { + assert.Nil(t, r) + return + } + require.NotNil(t, r) + assert.Equal(t, tt.wantID, r.ID) + }) + } +} + +func TestIssueTypeHierarchyLevel(t *testing.T) { + var fields IssueFields + require.NoError(t, json.Unmarshal([]byte(`{"issuetype":{"id":"1","name":"Epic","hierarchyLevel":1}}`), &fields)) + require.NotNil(t, fields.IssueType.HierarchyLevel) + assert.Equal(t, 1, *fields.IssueType.HierarchyLevel) + require.NoError(t, json.Unmarshal([]byte(`{"issuetype":{"id":"2","name":"Bug"}}`), &fields)) + assert.Nil(t, fields.IssueType.HierarchyLevel) +} diff --git a/internal/forge/jira/types.go b/internal/forge/jira/types.go index d72332080d..bb9eefa47f 100644 --- a/internal/forge/jira/types.go +++ b/internal/forge/jira/types.go @@ -85,6 +85,10 @@ type IssueType struct { ID string `json:"id"` Name string `json:"name"` Subtask bool `json:"subtask"` + // HierarchyLevel is the type's level in the issue hierarchy: -1 for a + // sub-task, 0 for standard work, 1 for an epic, and higher for levels + // above epics. Nil when Jira did not report it. + HierarchyLevel *int `json:"hierarchyLevel,omitempty"` } // Status represents the status of a Jira issue. diff --git a/internal/tracker/transition.go b/internal/tracker/transition.go index c7223a1452..95a4e41c76 100644 --- a/internal/tracker/transition.go +++ b/internal/tracker/transition.go @@ -9,9 +9,35 @@ import ( "github.com/fullsend-ai/fullsend/internal/forge/jira" ) -// TransitionOptions selects exactly one semantic State (currently "closed"), -// exact Jira transition Name, or exact Jira target Status. Resolution is an -// optional Jira resolution ID/name; Comment explains the action in Markdown. +// Semantic lifecycle states accepted by TransitionOptions.State. +const ( + // StateStarted moves a Jira issue to its in-progress status + // (category "indeterminate"). Jira only. + StateStarted = "started" + // StateClosed closes an issue: a Jira transition to a status in category + // "done", or a GitHub/GitLab close. + StateClosed = "closed" +) + +// stateCategories maps each semantic state to the Jira status category that +// satisfies it. +var stateCategories = map[string]string{ + StateStarted: "indeterminate", + StateClosed: "done", +} + +// preferredStatuses ranks Jira's default status names for a semantic state. +// They break ties when more than one available transition reaches the +// state's category. +var preferredStatuses = map[string][]string{ + StateStarted: {"In Progress"}, + StateClosed: {"Done", "Closed", "Resolved"}, +} + +// TransitionOptions selects exactly one semantic State ("started" or +// "closed"), exact Jira transition Name, or exact Jira target Status. +// Resolution is an optional Jira resolution ID/name; Comment explains the +// action in Markdown. type TransitionOptions struct { State string Name string @@ -31,8 +57,11 @@ func (o TransitionOptions) Validate() error { if selectors != 1 { return fmt.Errorf("specify exactly one lifecycle state, transition name, or target status") } - if o.State != "" && o.State != "closed" { - return fmt.Errorf("unsupported lifecycle state %q: use closed", o.State) + if o.State != "" && stateCategories[o.State] == "" { + return fmt.Errorf("unsupported lifecycle state %q: use started or closed", o.State) + } + if o.State == StateStarted && o.Resolution != "" { + return fmt.Errorf("a resolution cannot be applied with lifecycle state %q", o.State) } return nil } @@ -40,8 +69,27 @@ func (o TransitionOptions) Validate() error { // TransitionResult describes a successful action. Changed=false means the // semantic lifecycle state was already satisfied; any requested comment is // still posted. Named transitions are explicit actions, including self-transitions. +// +// Skipped=true means nothing was written, not even the comment: more than one +// available transition fits State and none is singled out by Jira's default +// status names. Reason explains the skip and Candidates lists the transitions. +// +// IssueType and HierarchyLevel describe the Jira issue when a semantic State +// read it, so callers can leave epics and above alone without type names. type TransitionResult struct { - Changed bool + Changed bool + Transition string + Status string + Skipped bool + Reason string + Candidates []TransitionCandidate + IssueType string + HierarchyLevel *int +} + +// TransitionCandidate is one available Jira transition that fit a semantic +// state in a skipped result. +type TransitionCandidate struct { Transition string Status string } @@ -62,7 +110,10 @@ func (c *ForgeClient) TransitionIssue(ctx context.Context, project string, numbe if err := opts.Validate(); err != nil { return nil, err } - if opts.State != "closed" || opts.Resolution != "" { + if opts.State == StateStarted { + return nil, fmt.Errorf("lifecycle state %q: %w (Jira only)", opts.State, ErrNotSupported) + } + if opts.State != StateClosed || opts.Resolution != "" { return nil, fmt.Errorf("named transitions, target statuses and resolutions: %w (Jira only)", ErrNotSupported) } owner, repo, err := splitProject(project) @@ -95,8 +146,18 @@ type jiraTransitions interface { ApplyTransition(ctx context.Context, issueIDOrKey, id string, fields map[string]any, comment string) error } +// jiraResolutions is the optional lookup of the site default resolution, +// used when a semantic close requires a resolution and none was passed. +type jiraResolutions interface { + DefaultResolution(ctx context.Context) (*jira.Resolution, error) +} + +var _ jiraTransitions = (*jira.LiveClient)(nil) +var _ jiraResolutions = (*jira.LiveClient)(nil) + // TransitionIssue resolves a unique currently available Jira action. Workflow // permissions and source-state restrictions stay in Jira, not in agent config. +// A semantic State selects by status category, so no status names are needed. func (c *JiraClient) TransitionIssue(ctx context.Context, project string, number int, opts TransitionOptions) (*TransitionResult, error) { if err := opts.Validate(); err != nil { return nil, err @@ -106,21 +167,29 @@ func (c *JiraClient) TransitionIssue(ctx context.Context, project string, number return nil, ErrNotSupported } key := issueKey(project, number) - if opts.State == "closed" { + var issueType string + var hierarchyLevel *int + if opts.State != "" { issue, err := c.jira.GetIssue(ctx, key) if err != nil { return nil, wrapNotFound(err) } - if issue.Fields.Status.StatusCategory.Key == "done" { + if it := issue.Fields.IssueType; it != nil { + issueType, hierarchyLevel = it.Name, it.HierarchyLevel + } + // A start is satisfied by an in-progress or done issue, so a re-run is + // safe and a start never reopens a closed issue. + category := issue.Fields.Status.StatusCategory.Key + if category == "done" || (opts.State == StateStarted && category == "indeterminate") { if opts.Resolution != "" { return nil, fmt.Errorf("issue %q is already closed; applying a resolution requires an explicit transition name or target status", key) } if opts.Comment != "" { if _, err := c.CreateComment(ctx, project, number, opts.Comment); err != nil { - return nil, fmt.Errorf("issue already closed, but posting the comment failed: %w", err) + return nil, fmt.Errorf("issue already %s, but posting the comment failed: %w", opts.State, err) } } - return &TransitionResult{Status: issue.Fields.Status.Name}, nil + return &TransitionResult{Status: issue.Fields.Status.Name, IssueType: issueType, HierarchyLevel: hierarchyLevel}, nil } } transitions, err := api.ListTransitions(ctx, key) @@ -129,7 +198,7 @@ func (c *JiraClient) TransitionIssue(ctx context.Context, project string, number } var matches []jira.Transition for _, tr := range transitions { - if (opts.Name != "" && tr.Name == opts.Name) || (opts.Status != "" && tr.To.Name == opts.Status) || (opts.State == "closed" && tr.To.StatusCategory.Key == "done") { + if (opts.Name != "" && tr.Name == opts.Name) || (opts.Status != "" && tr.To.Name == opts.Status) || (opts.State != "" && tr.To.StatusCategory.Key == stateCategories[opts.State]) { matches = append(matches, tr) } } @@ -137,23 +206,74 @@ func (c *JiraClient) TransitionIssue(ctx context.Context, project string, number return nil, fmt.Errorf("no matching Jira transition available on %q; check workflow and Transition Issues permission", key) } if len(matches) != 1 { - return nil, fmt.Errorf("ambiguous Jira transition on %q (%d matches); choose a unique transition name", key, len(matches)) + if opts.State == "" { + return nil, fmt.Errorf("ambiguous Jira transition on %q (%d matches); choose a unique transition name", key, len(matches)) + } + preferred, ok := preferDefaultStatus(matches, preferredStatuses[opts.State]) + if !ok { + candidates := make([]TransitionCandidate, len(matches)) + for i, tr := range matches { + candidates[i] = TransitionCandidate{Transition: tr.Name, Status: tr.To.Name} + } + return &TransitionResult{ + Skipped: true, + Reason: fmt.Sprintf("%d Jira transitions on %q fit lifecycle state %q and none reaches a unique default status (%s); choose one with --transition or --status", len(matches), key, opts.State, strings.Join(preferredStatuses[opts.State], ", ")), + Candidates: candidates, + IssueType: issueType, + HierarchyLevel: hierarchyLevel, + }, nil + } + matches = []jira.Transition{preferred} } tr := matches[0] if tr.ID == "" { return nil, fmt.Errorf("Jira transition %q has no ID", tr.Name) } - fields, err := transitionFields(tr, opts.Resolution, opts.Comment) + var siteDefault func() (string, error) + if resolutions, ok := c.jira.(jiraResolutions); ok && opts.State == StateClosed { + siteDefault = func() (string, error) { + r, err := resolutions.DefaultResolution(ctx) + if err != nil || r == nil { + return "", err + } + return r.ID, nil + } + } + fields, err := transitionFields(tr, opts.Resolution, opts.Comment, siteDefault) if err != nil { return nil, err } if err := api.ApplyTransition(ctx, key, tr.ID, fields, string(opts.Comment)); err != nil { return nil, wrapNotFound(err) } - return &TransitionResult{Changed: true, Transition: tr.Name, Status: tr.To.Name}, nil + return &TransitionResult{Changed: true, Transition: tr.Name, Status: tr.To.Name, IssueType: issueType, HierarchyLevel: hierarchyLevel}, nil } -func transitionFields(tr jira.Transition, resolution string, comment Body) (map[string]any, error) { +// preferDefaultStatus returns the one transition whose target status has the +// highest-ranked default name. A name that several transitions reach is still +// ambiguous, so it reports false rather than trying a lower-ranked name. +func preferDefaultStatus(matches []jira.Transition, ranked []string) (jira.Transition, bool) { + for _, name := range ranked { + var found []jira.Transition + for _, tr := range matches { + if strings.EqualFold(tr.To.Name, name) { + found = append(found, tr) + } + } + if len(found) == 1 { + return found[0], true + } + if len(found) > 1 { + return jira.Transition{}, false + } + } + return jira.Transition{}, false +} + +// transitionFields builds the transition request fields. siteDefault, when +// non-nil, returns the site default resolution ID (empty when none) and is +// consulted only when a required resolution has no single allowed value. +func transitionFields(tr jira.Transition, resolution string, comment Body, siteDefault func() (string, error)) (map[string]any, error) { fields := make(map[string]any) if resolution != "" { field, ok := tr.Fields["resolution"] @@ -176,15 +296,11 @@ func transitionFields(tr jira.Transition, resolution string, comment Body) (map[ fields["resolution"] = matches[0] } if field, ok := tr.Fields["resolution"]; ok && field.Required && !field.HasDefaultValue && resolution == "" { - // Select only an unambiguous workflow-provided value, never a guessed - // resolution or the first usable entry in a malformed list. - var value struct { - ID string `json:"id"` - } - if len(field.AllowedValues) != 1 || json.Unmarshal(field.AllowedValues[0], &value) != nil || strings.TrimSpace(value.ID) == "" { - return nil, fmt.Errorf("transition %q requires a resolution (an allowed resolution ID or name)", tr.Name) + id, err := automaticResolution(tr.Name, field, siteDefault) + if err != nil { + return nil, err } - fields["resolution"] = map[string]string{"id": value.ID} + fields["resolution"] = map[string]string{"id": id} } if field := tr.Fields["comment"]; field.Required && !field.HasDefaultValue && comment == "" { return nil, fmt.Errorf("transition %q requires a comment", tr.Name) @@ -194,3 +310,30 @@ func transitionFields(tr jira.Transition, resolution string, comment Body) (map[ // values and workflow rules, rather than rejecting metadata alone. return fields, nil } + +// automaticResolution selects only an unambiguous value, never a guessed +// resolution or the first usable entry in a malformed list: the single +// allowed value, or else the site default when the transition allows it. +func automaticResolution(transition string, field jira.TransitionField, siteDefault func() (string, error)) (string, error) { + var value struct { + ID string `json:"id"` + } + if len(field.AllowedValues) == 1 && json.Unmarshal(field.AllowedValues[0], &value) == nil && strings.TrimSpace(value.ID) != "" { + return value.ID, nil + } + if siteDefault != nil { + id, err := siteDefault() + if err != nil { + return "", fmt.Errorf("transition %q requires a resolution and looking up the site default failed: %w", transition, err) + } + for _, raw := range field.AllowedValues { + var allowed struct { + ID string `json:"id"` + } + if id != "" && json.Unmarshal(raw, &allowed) == nil && allowed.ID == id { + return id, nil + } + } + } + return "", fmt.Errorf("transition %q requires a resolution (an allowed resolution ID or name)", transition) +} diff --git a/internal/tracker/transition_test.go b/internal/tracker/transition_test.go index d36f76f1e6..016a769ae7 100644 --- a/internal/tracker/transition_test.go +++ b/internal/tracker/transition_test.go @@ -20,6 +20,22 @@ type transitionJira struct { calls int key, id, comment string fields map[string]any + defaultRes *jira.Resolution + resErr error + resCalls int + commentErr error +} + +func (f *transitionJira) CreateComment(ctx context.Context, key, body string) (*jira.Comment, error) { + if f.commentErr != nil { + return nil, f.commentErr + } + return f.FakeJiraClient.CreateComment(ctx, key, body) +} + +func (f *transitionJira) DefaultResolution(context.Context) (*jira.Resolution, error) { + f.resCalls++ + return f.defaultRes, f.resErr } func (f *transitionJira) ListTransitions(context.Context, string) ([]jira.Transition, error) { @@ -47,7 +63,6 @@ func TestJiraTransition(t *testing.T) { {name: "missing", opts: TransitionOptions{Name: "Review"}, wantErr: "no matching"}, {name: "case sensitive", opts: TransitionOptions{Name: "review"}, transitions: []jira.Transition{review}, wantErr: "no matching"}, {name: "ambiguous", opts: TransitionOptions{Name: "Review"}, transitions: []jira.Transition{review, review}, wantErr: "ambiguous"}, - {name: "ambiguous close", opts: TransitionOptions{State: "closed"}, transitions: []jira.Transition{close, close}, wantErr: "ambiguous"}, {name: "no id", opts: TransitionOptions{Name: "Review"}, transitions: []jira.Transition{{Name: "Review"}}, wantErr: "no ID"}, {name: "list error", opts: TransitionOptions{Name: "Review"}, listErr: forge.ErrNotFound, wantErr: "not found"}, {name: "apply error", opts: TransitionOptions{Name: "Review"}, transitions: []jira.Transition{review}, applyErr: errors.New("permission denied"), wantErr: "permission denied"}, @@ -93,7 +108,7 @@ func TestTransitionFields(t *testing.T) { {"bad data", "Fixed", map[string]jira.TransitionField{"resolution": {AllowedValues: []json.RawMessage{json.RawMessage(`"bad"`), json.RawMessage(`{"name":"Fixed"}`)}}}, "must match one"}, } { t.Run(tt.name, func(t *testing.T) { - fields, err := transitionFields(jira.Transition{Name: "Close", Fields: tt.fields}, tt.res, "") + fields, err := transitionFields(jira.Transition{Name: "Close", Fields: tt.fields}, tt.res, "", nil) if tt.wantErr != "" { require.ErrorContains(t, err, tt.wantErr) } else { @@ -164,6 +179,7 @@ func TestForgeTransition(t *testing.T) { {name: "unsupported", opts: TransitionOptions{Name: "Review"}, wantErr: "not supported"}, {name: "resolution", opts: TransitionOptions{State: "closed", Resolution: "Fixed"}, wantErr: "not supported"}, {name: "invalid", opts: TransitionOptions{State: "open"}, wantErr: "unsupported lifecycle"}, + {name: "started", opts: TransitionOptions{State: "started"}, wantErr: "not supported"}, {name: "get fails", opts: TransitionOptions{State: "closed"}, getErr: forge.ErrNotFound, wantErr: "not found"}, {name: "close fails", opts: TransitionOptions{State: "closed", Comment: "done"}, closeErr: errors.New("close denied"), wantErr: "close denied", closes: 1}, {name: "comment fails", opts: TransitionOptions{State: "closed", Comment: "done"}, commentErr: errors.New("comment denied"), wantErr: "issue is closed, but", closes: 1, comments: 1}, @@ -236,7 +252,7 @@ func TestTransitionAutomaticResolution(t *testing.T) { } { t.Run(tt.name, func(t *testing.T) { tr := jira.Transition{Name: "Close", Fields: map[string]jira.TransitionField{"resolution": {Required: !tt.optional, HasDefaultValue: tt.defaulted, AllowedValues: tt.values}}} - fields, err := transitionFields(tr, "", "") + fields, err := transitionFields(tr, "", "", nil) if tt.wantErr { require.ErrorContains(t, err, "requires a resolution") return @@ -287,3 +303,146 @@ func TestForgeTransitionRejectsPullRequests(t *testing.T) { } } } + +func jiraStatus(name, category string) jira.Status { + return jira.Status{Name: name, StatusCategory: jira.StatusCategory{Key: category}} +} + +func intPtr(v int) *int { return &v } + +func TestJiraTransitionSemanticState(t *testing.T) { + newMove := jira.Transition{ID: "11", Name: "New", To: jiraStatus("New", "new")} + refine := jira.Transition{ID: "12", Name: "Refinement", To: jiraStatus("Refinement", "new")} + start := jira.Transition{ID: "21", Name: "Start", To: jiraStatus("In Progress", "indeterminate")} + review := jira.Transition{ID: "22", Name: "Review", To: jiraStatus("Review", "indeterminate")} + coding := jira.Transition{ID: "23", Name: "Code", To: jiraStatus("Coding", "indeterminate")} + closed := jira.Transition{ID: "31", Name: "Close", To: jiraStatus("Closed", "done")} + done := jira.Transition{ID: "32", Name: "Finish", To: jiraStatus("done", "done")} + pending := jira.Transition{ID: "33", Name: "Release", To: jiraStatus("Release Pending", "done")} + resolve := jira.Transition{ID: "34", Name: "Resolve", To: jiraStatus("Resolved", "done")} + for _, tt := range []struct { + name string + state string + current string + transitions []jira.Transition + wantTransition string + wantCandidates []TransitionCandidate + }{ + {name: "start from new", state: "started", current: "new", transitions: []jira.Transition{newMove, refine, start, closed}, wantTransition: "Start"}, + {name: "start prefers In Progress", state: "started", current: "new", transitions: []jira.Transition{review, start}, wantTransition: "Start"}, + {name: "start without category", state: "started", transitions: []jira.Transition{coding}, wantTransition: "Code"}, + {name: "start ambiguous", state: "started", current: "new", transitions: []jira.Transition{review, coding, closed}, wantCandidates: []TransitionCandidate{{"Review", "Review"}, {"Code", "Coding"}}}, + {name: "start duplicate default", state: "started", current: "new", transitions: []jira.Transition{start, start}, wantCandidates: []TransitionCandidate{{"Start", "In Progress"}, {"Start", "In Progress"}}}, + {name: "close prefers Done", state: "closed", current: "indeterminate", transitions: []jira.Transition{resolve, closed, done}, wantTransition: "Finish"}, + {name: "close prefers Closed", state: "closed", current: "indeterminate", transitions: []jira.Transition{pending, closed}, wantTransition: "Close"}, + {name: "close falls back to Resolved", state: "closed", current: "new", transitions: []jira.Transition{pending, resolve}, wantTransition: "Resolve"}, + {name: "close ambiguous", state: "closed", current: "new", transitions: []jira.Transition{pending, {ID: "35", Name: "Reject", To: jiraStatus("Rejected", "done")}}, wantCandidates: []TransitionCandidate{{"Release", "Release Pending"}, {"Reject", "Rejected"}}}, + {name: "close duplicate default", state: "closed", current: "new", transitions: []jira.Transition{closed, closed, done, done}, wantCandidates: []TransitionCandidate{{"Close", "Closed"}, {"Close", "Closed"}, {"Finish", "done"}, {"Finish", "done"}}}, + } { + t.Run(tt.name, func(t *testing.T) { + issue := &jira.Issue{Fields: jira.IssueFields{Status: jiraStatus("Current", tt.current), IssueType: &jira.IssueType{Name: "Story", HierarchyLevel: intPtr(0)}}} + f := &transitionJira{FakeJiraClient: &FakeJiraClient{Issues: map[string]*jira.Issue{"P-1": issue}}, transitions: tt.transitions} + c, err := NewJiraClient(f, "https://example.atlassian.net") + require.NoError(t, err) + result, err := c.TransitionIssue(context.Background(), "P", 1, TransitionOptions{State: tt.state, Comment: "Started"}) + require.NoError(t, err) + assert.Equal(t, "Story", result.IssueType) + assert.Equal(t, intPtr(0), result.HierarchyLevel) + if tt.wantCandidates != nil { + assert.True(t, result.Skipped) + assert.False(t, result.Changed) + assert.Contains(t, result.Reason, "--transition") + assert.Equal(t, tt.wantCandidates, result.Candidates) + assert.Zero(t, f.calls) + assert.Empty(t, f.Comments, "a skip must not post the comment") + return + } + assert.False(t, result.Skipped) + assert.True(t, result.Changed) + assert.Equal(t, tt.wantTransition, result.Transition) + assert.Equal(t, 1, f.calls) + assert.Equal(t, "Started", f.comment) + }) + } +} + +func TestJiraTransitionStartedAlreadySatisfied(t *testing.T) { + start := jira.Transition{ID: "21", Name: "Start", To: jiraStatus("In Progress", "indeterminate")} + for _, category := range []string{"indeterminate", "done"} { + for _, comment := range []Body{"", "Picked up"} { + t.Run(category+"/"+string(comment), func(t *testing.T) { + issue := &jira.Issue{Fields: jira.IssueFields{Status: jiraStatus("Current", category), IssueType: &jira.IssueType{Name: "Epic", HierarchyLevel: intPtr(1)}}} + f := &transitionJira{FakeJiraClient: &FakeJiraClient{Issues: map[string]*jira.Issue{"P-1": issue}}, transitions: []jira.Transition{start}} + c, err := NewJiraClient(f, "https://example.atlassian.net") + require.NoError(t, err) + result, err := c.TransitionIssue(context.Background(), "P", 1, TransitionOptions{State: "started", Comment: comment}) + require.NoError(t, err) + assert.False(t, result.Changed) + assert.Equal(t, "Current", result.Status) + assert.Equal(t, intPtr(1), result.HierarchyLevel) + assert.Zero(t, f.calls) + if comment != "" { + assert.Len(t, f.Comments["P-1"], 1) + } else { + assert.Empty(t, f.Comments) + } + }) + } + } +} + +func TestJiraTransitionStartedErrors(t *testing.T) { + f := &transitionJira{FakeJiraClient: &FakeJiraClient{Issues: map[string]*jira.Issue{"P-1": {}}}} + c, err := NewJiraClient(f, "https://example.atlassian.net") + require.NoError(t, err) + _, err = c.TransitionIssue(context.Background(), "P", 1, TransitionOptions{State: "started", Resolution: "Fixed"}) + require.ErrorContains(t, err, "resolution cannot be applied") + _, err = c.TransitionIssue(context.Background(), "P", 1, TransitionOptions{State: "started"}) + require.ErrorContains(t, err, "no matching") + _, err = c.TransitionIssue(context.Background(), "P", 2, TransitionOptions{State: "started"}) + assert.True(t, IsNotFound(err)) + f.Issues["P-1"].Fields.Status = jiraStatus("Doing", "indeterminate") + f.commentErr = errors.New("comment denied") + _, err = c.TransitionIssue(context.Background(), "P", 1, TransitionOptions{State: "started", Comment: "x"}) + require.ErrorContains(t, err, "issue already started, but posting the comment failed") + assert.Zero(t, f.calls) +} + +func TestJiraTransitionSiteDefaultResolution(t *testing.T) { + required := jira.TransitionField{Required: true, AllowedValues: []json.RawMessage{ + json.RawMessage(`{"id":"1","name":"Done"}`), json.RawMessage(`null`), json.RawMessage(`{"id":"2","name":"Won't Do"}`), json.RawMessage(`{"id":"3","name":"Duplicate"}`), + }} + closeTr := jira.Transition{ID: "31", Name: "Close", To: jiraStatus("Closed", "done"), Fields: map[string]jira.TransitionField{"resolution": required}} + for _, tt := range []struct { + name string + opts TransitionOptions + defaultRes *jira.Resolution + resErr error + wantID string + wantErr string + wantLookup bool + }{ + {name: "default allowed", opts: TransitionOptions{State: "closed"}, defaultRes: &jira.Resolution{ID: "2", Default: true}, wantID: "2", wantLookup: true}, + {name: "default not allowed", opts: TransitionOptions{State: "closed"}, defaultRes: &jira.Resolution{ID: "9", Default: true}, wantErr: "requires a resolution", wantLookup: true}, + {name: "no site default", opts: TransitionOptions{State: "closed"}, wantErr: "requires a resolution", wantLookup: true}, + {name: "lookup fails", opts: TransitionOptions{State: "closed"}, resErr: errors.New("rate limited"), wantErr: "rate limited", wantLookup: true}, + {name: "explicit resolution", opts: TransitionOptions{State: "closed", Resolution: "Duplicate"}, defaultRes: &jira.Resolution{ID: "2"}, wantID: "3"}, + {name: "named transition unchanged", opts: TransitionOptions{Name: "Close"}, defaultRes: &jira.Resolution{ID: "2"}, wantErr: "requires a resolution"}, + {name: "status unchanged", opts: TransitionOptions{Status: "Closed"}, defaultRes: &jira.Resolution{ID: "2"}, wantErr: "requires a resolution"}, + } { + t.Run(tt.name, func(t *testing.T) { + f := &transitionJira{FakeJiraClient: &FakeJiraClient{Issues: map[string]*jira.Issue{"P-1": {}}}, transitions: []jira.Transition{closeTr}, defaultRes: tt.defaultRes, resErr: tt.resErr} + c, err := NewJiraClient(f, "https://example.atlassian.net") + require.NoError(t, err) + _, err = c.TransitionIssue(context.Background(), "P", 1, tt.opts) + assert.Equal(t, tt.wantLookup, f.resCalls == 1) + if tt.wantErr != "" { + require.ErrorContains(t, err, tt.wantErr) + assert.Zero(t, f.calls) + return + } + require.NoError(t, err) + assert.Equal(t, map[string]any{"resolution": map[string]string{"id": tt.wantID}}, f.fields) + }) + } +} From 4e0bbafda89f6379da47320bbe995f97d48a8f7e Mon Sep 17 00:00:00 2001 From: fullsend-fix <278716306+fullsend-ai-coder[bot]@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:24:46 +0000 Subject: [PATCH 2/4] docs(#9536): document --state started and closed in CLI internals Address review feedback on PR #9925: the command tree for 'fullsend issues transition' listed only --state closed. List both values, noting that started is Jira only. Note: pre-commit hooks were not run (infrastructure failure: could not fetch hook repositories); trailing-whitespace, end-of-file and line-ending checks were verified manually. Go tests/lint not run as the change is documentation-only. Co-Authored-By: Claude Sonnet 5.5 --- docs/guides/dev/cli-internals.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/guides/dev/cli-internals.md b/docs/guides/dev/cli-internals.md index 90948d84e0..c85b84e9c2 100644 --- a/docs/guides/dev/cli-internals.md +++ b/docs/guides/dev/cli-internals.md @@ -193,7 +193,8 @@ fullsend │ ├── --tracker # Tracker backend: github, gitlab, or jira │ ├── --project # owner/repo or an allowed Jira project key │ ├── --number # Issue number -│ ├── --state closed # Portable closure; one selector required +│ ├── --state started # Jira only: move to an in-progress status; one selector required +│ ├── --state closed # Portable closure on all trackers; one selector required │ ├── --transition # Exact Jira transition name │ ├── --status # Exact Jira destination status │ ├── --resolution # Jira resolution allowed by the transition From f794ee12b943fad380023c955439437c898a1ce3 Mon Sep 17 00:00:00 2001 From: fullsend-fix <278716306+fullsend-ai-coder[bot]@users.noreply.github.com> Date: Wed, 2 Dec 2026 12:19:52 +0000 Subject: [PATCH 3/4] fix: address review feedback on PR #9925 Assert the httptest handler was invoked in TestDefaultResolution so a URL path mismatch cannot pass via the default 404. Addresses #9925 Co-Authored-By: Claude Sonnet 5.5 --- internal/forge/jira/transition_test.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/internal/forge/jira/transition_test.go b/internal/forge/jira/transition_test.go index 7210f595ff..dbe42d3128 100644 --- a/internal/forge/jira/transition_test.go +++ b/internal/forge/jira/transition_test.go @@ -80,7 +80,9 @@ func TestDefaultResolution(t *testing.T) { } { t.Run(tt.name, func(t *testing.T) { c, mux := setupTest(t) + handlerCalled := false mux.HandleFunc("/rest/api/3/resolution/search", func(w http.ResponseWriter, r *http.Request) { + handlerCalled = true assert.Equal(t, http.MethodGet, r.Method) assert.Equal(t, "true", r.URL.Query().Get("onlyDefault")) if tt.status != 0 { @@ -91,6 +93,7 @@ func TestDefaultResolution(t *testing.T) { _, _ = w.Write([]byte(`{"isLast":true,"values":` + tt.values + `}`)) }) r, err := c.DefaultResolution(context.Background()) + assert.True(t, handlerCalled, "handler was not called — URL path mismatch") if tt.err { require.ErrorContains(t, err, "default resolution") return From 34627d645765487b93354d028e7550a9e8cefee5 Mon Sep 17 00:00:00 2001 From: fullsend-fix <278716306+fullsend-ai-coder[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 10:26:40 +0000 Subject: [PATCH 4/4] fix(#9536)!: exit nonzero on ambiguous Jira --state skip Address maintainer review on PR #9925 (revised #9536 requirements). - An ambiguous `--state started|closed` on Jira (several transitions fit and no default status name picks one) still prints the skip JSON on stdout, including reason and candidates, then exits with the dedicated code 11 through the ExitCode() hook. A JSON write error takes precedence. Zero matching transitions stays an ordinary error; successful transitions and already-satisfied states still exit 0. tracker.TransitionResult gains Ambiguous so only this skip fails; other skips (for example #9534 issue-type filters) stay successful. - Help and docs say `--state started` on an already started or done issue leaves the status unchanged and still posts a requested comment, instead of "does nothing". - Drop the claim that issue_type and hierarchy_level let callers keep epics from moving: the result is built after the transition. The fields stay and report the kind of issue acted on. - CLI tests cover the skip JSON plus exit code for starts and closes, write-error precedence, zero matches, non-ambiguous skips, and already-satisfied states. Note: pre-commit could not fetch its hook repositories (TLS failure in the sandbox), so it did not run. gofmt, go vet, and git diff --check were run directly, and go test passed for ./internal/tracker/, ./internal/forge/jira/ and ./internal/cli/. BREAKING CHANGE: `--state` on Jira now exits 11 (after printing the skip JSON with "skipped": true) when several transitions fit and none reaches a unique default status, so the issue is not moved. Earlier in this PR `--state closed` exited non-zero as an ambiguous error here before becoming an exit-0 skip; callers should treat code 11 as "not moved, choose with --transition or --status". The command also now picks Done, Closed or Resolved automatically when exactly one is reachable, and falls back to the site default resolution when a required resolution cannot be selected, instead of failing as before. Addresses #9925 Co-Authored-By: Claude Sonnet 5.5 --- docs/cli/README.md | 2 +- docs/guides/user/issues-commands.md | 16 +++++-- internal/cli/issues_transition.go | 41 ++++++++++++++--- internal/cli/issues_transition_test.go | 62 ++++++++++++++++++++++++++ internal/tracker/transition.go | 15 ++++--- internal/tracker/transition_test.go | 2 + 6 files changed, 121 insertions(+), 17 deletions(-) diff --git a/docs/cli/README.md b/docs/cli/README.md index ae0bf6addf..0ab56ea22b 100644 --- a/docs/cli/README.md +++ b/docs/cli/README.md @@ -38,7 +38,7 @@ To update an installed binary later, run [`fullsend self-update`](self-update.md | [`fullsend self-update`](self-update.md) | Update the local `fullsend` binary to the latest release, or to `--version`, after verifying the release's Sigstore signature and checksum. | | `fullsend eval-measure` | Score wild-run traces into `eval-measurements.jsonl`. See [Eval measurements](../guides/infrastructure/eval-measurements.md). | | `fullsend prepare-artifacts` | Build, in `--artifact-dir`, the filtered copy of a run's `--output-dir` that CI uploads as the run artifact. The level (`all`, `metadata` or `none`) comes from `config.yaml`'s [`artifacts`](../reference/config-reference.md#artifacts) setting and the run's source; a run whose source is unknown gets the strictest configured level. Prints the level on stdout and the rule it applied on stderr. If the level cannot be resolved, it leaves `--artifact-dir` empty and exits non-zero. `action.yml` and the GitLab agent job run it after `eval-measure`. See [Run artifacts and private data](../guides/user/run-artifacts-and-private-data.md). | -| `fullsend issues transition` | Transition an issue: exactly one of `--state closed`, `--state started` (Jira), `--transition NAME` (Jira), or `--status NAME` (Jira). Jira `--state` selects by status category and returns a skip listing the candidates when no single transition fits. Accepts `--resolution ID_OR_NAME` (Jira) and `--comment TEXT`, plus the existing `--tracker`, `--project`, `--number`, `--fullsend-dir`, and `--token` flags. See [Issue transitions](../guides/user/issues-commands.md#fullsend-issues-transition) for permissions, ambiguity handling, and partial failures. | +| `fullsend issues transition` | Transition an issue: exactly one of `--state closed`, `--state started` (Jira), `--transition NAME` (Jira), or `--status NAME` (Jira). Jira `--state` selects by status category and prints a skip listing the candidates and exits with code 11 when no single transition fits. Accepts `--resolution ID_OR_NAME` (Jira) and `--comment TEXT`, plus the existing `--tracker`, `--project`, `--number`, `--fullsend-dir`, and `--token` flags. See [Issue transitions](../guides/user/issues-commands.md#fullsend-issues-transition) for permissions, ambiguity handling, and partial failures. | ## Global flags diff --git a/docs/guides/user/issues-commands.md b/docs/guides/user/issues-commands.md index e21eab97f7..7e006cab4b 100644 --- a/docs/guides/user/issues-commands.md +++ b/docs/guides/user/issues-commands.md @@ -346,7 +346,7 @@ Exactly one of `--state`, `--transition`, or `--status` is required: | Flag | Meaning | |------|---------| | `--state closed` | Portable closure on GitHub, GitLab, and Jira. Jira selects the available transition whose destination has status category `done`. | -| `--state started` | Jira only. Selects the available transition whose destination has status category `indeterminate` (in progress). Does nothing when the issue is already in progress or done. GitHub and GitLab return a not-supported error. | +| `--state started` | Jira only. Selects the available transition whose destination has status category `indeterminate` (in progress). Leaves the status unchanged when the issue is already in progress or done, and still posts a requested comment. GitHub and GitLab return a not-supported error. | | `--transition NAME` | Exact, case-sensitive Jira transition name, such as `Review`. This names an action, not its destination status. | | `--status NAME` | Exact Jira destination status name. Requires one available transition to that status. | | `--resolution ID_OR_NAME` | Jira resolution selected from the transition's allowed values. Required when the transition requires a resolution without a default and does not offer exactly one valid allowed value (or, for `--state closed`, does not allow the site default resolution). Not accepted with `--state started`. | @@ -363,7 +363,10 @@ other projects are rejected before a client is built. The command prints JSON with `changed`, and, where available, `transition` and `status`. For Jira `--state`, it also prints `issue_type` and `hierarchy_level` (`-1` sub-task, `0` standard work, `1` epic, higher above epics) when Jira -reports them, so a caller can leave epics alone without listing type names. +reports them. They report the kind of issue the command acted on. A run that +moves the issue builds them after the transition, so they cannot keep an epic +from moving, and the command has no filter or dry run to check the level +beforehand. Portable closure of an already closed issue returns `changed: false`, but still posts a requested comment. `--state started` on an issue already in progress or done also returns `changed: false` and posts a requested comment; a @@ -383,8 +386,13 @@ When more than one available action reaches the category, the command prefers Jira's default status names: `In Progress` for a start, and `Done`, `Closed`, then `Resolved` for a close. If that does not leave exactly one action (none of the names is available, or several actions reach the same name), nothing is -written, not even the comment. The command exits 0 and prints a skip that lists -the candidates; choose one with `--transition` or `--status`: +written, not even the comment. The command prints a skip that lists the +candidates on stdout, then exits with code 11 so that a script checking only the +exit code sees the issue was not moved. Choose one candidate with `--transition` +or `--status`. Exit code 1 still means any other error, including zero matching +transitions, and a failure to write the JSON takes precedence over code 11. A +successful transition and an already-satisfied state still exit 0. Example skip +output: ```json {"changed":false,"skipped":true,"reason":"2 Jira transitions on \"PROJ-42\" fit lifecycle state \"started\" ...","candidates":[{"transition":"Review","status":"Review"},{"transition":"Code","status":"Coding"}],"issue_type":"Bug","hierarchy_level":0} diff --git a/internal/cli/issues_transition.go b/internal/cli/issues_transition.go index b8c2207c0c..616b455d0d 100644 --- a/internal/cli/issues_transition.go +++ b/internal/cli/issues_transition.go @@ -57,11 +57,12 @@ action and accepts --resolution when the workflow requires it. On Jira, --state picks the available transition whose target status category is "indeterminate" (started) or "done" (closed), so no status names are configured. ---state started does nothing on an issue already in progress or done. When -several transitions fit, the Jira default status name wins: In Progress for a -start, then Done, Closed, Resolved for a close. If that still leaves more than -one, nothing is written and the JSON result has "skipped": true and lists the -candidates. +--state started leaves the status unchanged on an issue already in progress or +done, and still posts a requested comment. When several transitions fit, the +Jira default status name wins: In Progress for a start, then Done, Closed, +Resolved for a close. If that still leaves more than one, nothing is written, +the JSON result with "skipped": true lists the candidates on stdout, and the +command exits with code 11. Zero matching transitions is an ordinary error. A required resolution is selected automatically only when Jira offers exactly one valid allowed value and no default, or, for --state closed, when the site @@ -136,7 +137,7 @@ func runIssuesTransition(ctx context.Context, cfg *issuesTransitionConfig) error for _, c := range result.Candidates { candidates = append(candidates, issueTransitionCandidate{Transition: c.Transition, Status: c.Status}) } - return json.NewEncoder(out).Encode(issueTransitionResult{ + if err := json.NewEncoder(out).Encode(issueTransitionResult{ Changed: result.Changed, Transition: result.Transition, Status: result.Status, @@ -145,5 +146,31 @@ func runIssuesTransition(ctx context.Context, cfg *issuesTransitionConfig) error Candidates: candidates, IssueType: result.IssueType, HierarchyLevel: result.HierarchyLevel, - }) + }); err != nil { + return err + } + // The skip JSON is printed first so a caller can read the candidates. An + // ambiguous skip then fails with its own exit code, because the command could + // not choose and the issue was not moved. Other skips stay successful. + if result.Ambiguous { + return &transitionAmbiguousError{reason: result.Reason} + } + return nil +} + +// TransitionAmbiguousExitCode is the process exit code used when --state matches +// several Jira transitions and none is singled out by a default status name. The +// skip JSON is still printed on stdout. It differs from 1 (any other error) and +// StaleHeadExitCode so a script can handle the ambiguity on its own. +const TransitionAmbiguousExitCode = 11 + +// transitionAmbiguousError reports an ambiguous --state skip. It carries +// TransitionAmbiguousExitCode through the ExitCode() hook in main.go. +type transitionAmbiguousError struct{ reason string } + +func (e *transitionAmbiguousError) Error() string { + return "issue not transitioned: " + e.reason } + +// ExitCode returns TransitionAmbiguousExitCode. +func (e *transitionAmbiguousError) ExitCode() int { return TransitionAmbiguousExitCode } diff --git a/internal/cli/issues_transition_test.go b/internal/cli/issues_transition_test.go index 460da77047..14d6a89a83 100644 --- a/internal/cli/issues_transition_test.go +++ b/internal/cli/issues_transition_test.go @@ -113,6 +113,68 @@ func TestRunIssuesTransitionJSONContract(t *testing.T) { } } +// An ambiguous --state skip prints its JSON, then fails with its own exit code. +// Zero matches stays an ordinary error and a non-ambiguous skip stays a success. +func TestRunIssuesTransitionAmbiguousExitCode(t *testing.T) { + zeroLevel := 0 + ambiguous := tracker.TransitionResult{ + Skipped: true, + Ambiguous: true, + Reason: "2 Jira transitions fit", + Candidates: []tracker.TransitionCandidate{{Transition: "Review", Status: "Review"}, {Transition: "Code", Status: "Coding"}}, + IssueType: "Bug", + HierarchyLevel: &zeroLevel, + } + want := `{"changed":false,"skipped":true,"reason":"2 Jira transitions fit","candidates":[{"transition":"Review","status":"Review"},{"transition":"Code","status":"Coding"}],"issue_type":"Bug","hierarchy_level":0}` + for _, state := range []string{"started", "closed"} { + t.Run(state, func(t *testing.T) { + var out bytes.Buffer + cfg := &issuesTransitionConfig{trackerName: "jira", project: "PROJ", number: 1, opts: tracker.TransitionOptions{State: state}, testClient: &transitionTracker{result: &ambiguous}, testWriter: &out, testConfigReader: jiraCreateConfig(t, "PROJ")} + err := runIssuesTransition(context.Background(), cfg) + require.ErrorContains(t, err, "2 Jira transitions fit") + var ec interface{ ExitCode() int } + require.True(t, errors.As(err, &ec)) + assert.Equal(t, TransitionAmbiguousExitCode, ec.ExitCode()) + assert.NotEqual(t, StaleHeadExitCode, ec.ExitCode()) + assert.JSONEq(t, want, out.String(), "the skip JSON is printed before the failure") + }) + } + + t.Run("output write error takes precedence", func(t *testing.T) { + cfg := &issuesTransitionConfig{trackerName: "jira", project: "PROJ", number: 1, opts: tracker.TransitionOptions{State: "closed"}, testClient: &transitionTracker{result: &ambiguous}, testWriter: failingTransitionWriter{}, testConfigReader: jiraCreateConfig(t, "PROJ")} + err := runIssuesTransition(context.Background(), cfg) + require.ErrorContains(t, err, "write failed") + var ec interface{ ExitCode() int } + assert.False(t, errors.As(err, &ec), "a write error must not carry the ambiguity exit code") + }) + + t.Run("zero matching transitions is an ordinary error", func(t *testing.T) { + var out bytes.Buffer + cfg := &issuesTransitionConfig{trackerName: "jira", project: "PROJ", number: 1, opts: tracker.TransitionOptions{State: "started"}, testClient: &transitionTracker{err: errors.New("no matching Jira transition")}, testWriter: &out, testConfigReader: jiraCreateConfig(t, "PROJ")} + err := runIssuesTransition(context.Background(), cfg) + require.ErrorContains(t, err, "no matching Jira transition") + var ec interface{ ExitCode() int } + assert.False(t, errors.As(err, &ec)) + assert.Empty(t, out.String()) + }) + + t.Run("a skip that is not ambiguous exits 0", func(t *testing.T) { + var out bytes.Buffer + res := tracker.TransitionResult{Skipped: true, Reason: "filtered by issue type"} + cfg := &issuesTransitionConfig{trackerName: "jira", project: "PROJ", number: 1, opts: tracker.TransitionOptions{State: "closed"}, testClient: &transitionTracker{result: &res}, testWriter: &out, testConfigReader: jiraCreateConfig(t, "PROJ")} + require.NoError(t, runIssuesTransition(context.Background(), cfg)) + assert.JSONEq(t, `{"changed":false,"skipped":true,"reason":"filtered by issue type"}`, out.String()) + }) + + t.Run("already satisfied exits 0", func(t *testing.T) { + var out bytes.Buffer + res := tracker.TransitionResult{Status: "In Progress"} + cfg := &issuesTransitionConfig{trackerName: "jira", project: "PROJ", number: 1, opts: tracker.TransitionOptions{State: "started"}, testClient: &transitionTracker{result: &res}, testWriter: &out, testConfigReader: jiraCreateConfig(t, "PROJ")} + require.NoError(t, runIssuesTransition(context.Background(), cfg)) + assert.JSONEq(t, `{"changed":false,"status":"In Progress"}`, out.String()) + }) +} + func TestRunIssuesTransitionJiraProjectAuthorization(t *testing.T) { for _, tt := range []struct { name, project string diff --git a/internal/tracker/transition.go b/internal/tracker/transition.go index 95a4e41c76..a437f5c107 100644 --- a/internal/tracker/transition.go +++ b/internal/tracker/transition.go @@ -70,17 +70,21 @@ func (o TransitionOptions) Validate() error { // semantic lifecycle state was already satisfied; any requested comment is // still posted. Named transitions are explicit actions, including self-transitions. // -// Skipped=true means nothing was written, not even the comment: more than one -// available transition fits State and none is singled out by Jira's default -// status names. Reason explains the skip and Candidates lists the transitions. +// Skipped=true means nothing was written, not even the comment. Reason explains +// the skip. Ambiguous=true marks the skip where more than one available +// transition fits State and none is singled out by Jira's default status names; +// Candidates lists those transitions. The command reports an ambiguous skip as a +// failure, since it could not choose, while other skips stay successful. // -// IssueType and HierarchyLevel describe the Jira issue when a semantic State -// read it, so callers can leave epics and above alone without type names. +// IssueType and HierarchyLevel report the kind of Jira issue the command acted +// on when a semantic State read it. A moving run builds them after the +// transition is applied, so they do not let a caller prevent a move. type TransitionResult struct { Changed bool Transition string Status string Skipped bool + Ambiguous bool Reason string Candidates []TransitionCandidate IssueType string @@ -217,6 +221,7 @@ func (c *JiraClient) TransitionIssue(ctx context.Context, project string, number } return &TransitionResult{ Skipped: true, + Ambiguous: true, Reason: fmt.Sprintf("%d Jira transitions on %q fit lifecycle state %q and none reaches a unique default status (%s); choose one with --transition or --status", len(matches), key, opts.State, strings.Join(preferredStatuses[opts.State], ", ")), Candidates: candidates, IssueType: issueType, diff --git a/internal/tracker/transition_test.go b/internal/tracker/transition_test.go index 016a769ae7..e00ddf6919 100644 --- a/internal/tracker/transition_test.go +++ b/internal/tracker/transition_test.go @@ -350,6 +350,7 @@ func TestJiraTransitionSemanticState(t *testing.T) { assert.Equal(t, intPtr(0), result.HierarchyLevel) if tt.wantCandidates != nil { assert.True(t, result.Skipped) + assert.True(t, result.Ambiguous) assert.False(t, result.Changed) assert.Contains(t, result.Reason, "--transition") assert.Equal(t, tt.wantCandidates, result.Candidates) @@ -358,6 +359,7 @@ func TestJiraTransitionSemanticState(t *testing.T) { return } assert.False(t, result.Skipped) + assert.False(t, result.Ambiguous) assert.True(t, result.Changed) assert.Equal(t, tt.wantTransition, result.Transition) assert.Equal(t, 1, f.calls)