From a5bfb6a50e97ace08dca3e13365f6f85c79be663 Mon Sep 17 00:00:00 2001 From: Eder Ignatowicz Date: Fri, 13 Nov 2026 12:10:31 -0500 Subject: [PATCH 1/2] feat(issues): add tracker-neutral issue transitions Signed-off-by: Eder Ignatowicz --- docs/agents/code.md | 13 +- docs/cli/README.md | 1 + docs/guides/README.md | 2 +- docs/guides/dev/cli-internals.md | 2 +- .../layered-config-reference.md | 2 +- docs/guides/user/issues-commands.md | 58 ++++- docs/guides/user/jira-integration.md | 55 ++++- internal/cli/issues.go | 1 + internal/cli/issues_transition.go | 91 ++++++++ internal/cli/issues_transition_test.go | 85 ++++++++ internal/forge/jira/transition.go | 62 ++++++ internal/forge/jira/transition_test.go | 64 ++++++ internal/tracker/transition.go | 185 ++++++++++++++++ internal/tracker/transition_test.go | 201 ++++++++++++++++++ 14 files changed, 809 insertions(+), 13 deletions(-) create mode 100644 internal/cli/issues_transition.go create mode 100644 internal/cli/issues_transition_test.go create mode 100644 internal/forge/jira/transition.go create mode 100644 internal/forge/jira/transition_test.go create mode 100644 internal/tracker/transition.go create mode 100644 internal/tracker/transition_test.go diff --git a/docs/agents/code.md b/docs/agents/code.md index b6768cecad..710ef4102a 100644 --- a/docs/agents/code.md +++ b/docs/agents/code.md @@ -104,7 +104,18 @@ composition. ### Variables -None. +These optional settings belong in the code harness's `env.runner` mapping. +Use an agents version that includes the corresponding hooks and a Fullsend +version that provides `fullsend issues transition`. + +| Variable | Default | Purpose | +|---|---|---| +| `CODE_JIRA_STARTED_TRANSITION` | `"off"` | Jira transition after code preflight completes without a fatal error, before sandbox creation | +| `CODE_JIRA_PR_READY_TRANSITION` | `"off"` | Jira transition after confirming an open, non-draft PR or MR | + +Values are Jira transition names, not destination status names. See +[Optional code transitions](../guides/user/jira-integration.md#optional-code-transitions) +for configuration, permissions, and failure behavior. ## Source diff --git a/docs/cli/README.md b/docs/cli/README.md index 3dedfd2698..c31d3fdc04 100644 --- a/docs/cli/README.md +++ b/docs/cli/README.md @@ -35,6 +35,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. | ## Global flags diff --git a/docs/guides/README.md b/docs/guides/README.md index 84220d4188..a38659d777 100644 --- a/docs/guides/README.md +++ b/docs/guides/README.md @@ -42,7 +42,7 @@ Guides for developers working in repositories where fullsend is active. - [How fullsend authenticates](user/how-fullsend-authenticates.md) — Which credential path fullsend uses in each case: the mint, GCP and OpenAI Workload Identity, and the gateway's direct OIDC trust - [Using an inference gateway](user/inference-gateway.md) — Reach models through an OpenAI/Anthropic-compatible gateway with direct OIDC trust (no token exchange) or a gateway key - [Bugfix workflow](user/bugfix-workflow.md) — End-to-end guide to how fullsend handles a bug report from issue to merge -- [Issue commands](user/issues-commands.md) — Read, create, and post comments on issues across GitHub, GitLab, and Jira (`fullsend issues get`, `create`, `post-comment`) +- [Issue commands](user/issues-commands.md) — Read, create, comment on, and transition issues across GitHub, GitLab, and Jira (`fullsend issues get`, `create`, `post-comment`, `transition`) - [OWNERS file authorization](user/owners-file-authorization.md) — Authorize agent dispatch via Prow-style OWNERS files - [Running agents locally](user/running-agents-locally.md) — Run fullsend agents on your machine using released binaries (macOS + Linux) diff --git a/docs/guides/dev/cli-internals.md b/docs/guides/dev/cli-internals.md index 61501c2bdf..8cb1cdd2b6 100644 --- a/docs/guides/dev/cli-internals.md +++ b/docs/guides/dev/cli-internals.md @@ -920,7 +920,7 @@ var executableFiles = map[string]struct{}{ | `internal/cli/inference_openai.go` | ~900 | OpenAI WIF enrolment: request document, reply import, status/exchange | | `internal/cli/github.go` | ~966 | GitHub setup/set/status/uninstall/sync-scaffold/enroll/unenroll | | `internal/cli/github_client.go` | ~130 | GitHub token resolution and authenticated client construction | -| `internal/cli/issues.go` | ~971 | Issue read/write commands (`fullsend issues get`, `create`, `post-comment`, `link`) | +| `internal/cli/issues.go` | ~971 | Issue read/write commands (`fullsend issues get`, `create`, `post-comment`, `link`, `transition`; transitions are in `issues_transition.go`) | | `internal/cli/tracker_client.go` | ~122 | Tracker client factory (GitHub/GitLab/Jira) | | `internal/cli/run.go` | ~1923 | Agent execution lifecycle | | `internal/mint/main.go` | ~95 | GCF token mint entry point (wiring only) | diff --git a/docs/guides/infrastructure/layered-config-reference.md b/docs/guides/infrastructure/layered-config-reference.md index 2ebf1f7763..35d025c60a 100644 --- a/docs/guides/infrastructure/layered-config-reference.md +++ b/docs/guides/infrastructure/layered-config-reference.md @@ -481,7 +481,7 @@ The `tracker` field is the single, provider-discriminated issue-tracker mapping (`github`, `gitlab`, or `jira`; at most one). It replaces the former scalar `tracker` field, which is no longer accepted. The provider block that is present is the default for `--tracker` on `fullsend issues get`, -`create`, `post-comment`, and `link` (`link` supports only Jira, so a `github` +`create`, `post-comment`, `transition`, and `link` (`link` supports only Jira, so a `github` or `gitlab` provider makes it fail with a not-supported error unless `--tracker jira` is passed); an explicit `--tracker` flag overrides it. When no provider block is set, `--tracker` is required on every `fullsend issues` diff --git a/docs/guides/user/issues-commands.md b/docs/guides/user/issues-commands.md index 3a03a468a8..e62d1c4297 100644 --- a/docs/guides/user/issues-commands.md +++ b/docs/guides/user/issues-commands.md @@ -3,7 +3,7 @@ Read and write issue content across GitHub, GitLab, and Jira from custom agent scripts using `fullsend issues get`, `fullsend issues create`, `fullsend issues post-comment`, and -`fullsend issues link`. +`fullsend issues link`, and `fullsend issues transition`. ## When to use @@ -355,3 +355,59 @@ Jira site and project settings are never read from the environment; see - [Jira Integration](jira-integration.md) -- polling and dispatch setup - [Bring Your Own Agent](bring-your-own-agent.md) -- adding custom agents - [Layered Config Reference](../infrastructure/layered-config-reference.md) -- config field documentation + + +## `fullsend issues transition` + +Close an issue through its tracker, 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 --transition "Review" + +fullsend issues transition --fullsend-dir .fullsend --tracker jira \ + --number 42 --state closed --resolution "Fixed" --comment "Completed." +``` + +Exactly one selector 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`. | +| `--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. | +| `--comment TEXT` | Optional Markdown explanation. Jira submits it atomically with the transition; GitHub/GitLab post it after closing. | + +`--tracker`, `--project`, `--number`, `--fullsend-dir`, and `--token` +follow the connection and authentication rules above. Jira rejects `--token`; +credentials remain in the existing environment variables. `--number` must be +positive. Jira requires its connection settings in the configuration directory. + +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. Explicit named transitions always execute, +including self-transitions. The command does not infer that an unavailable action +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. +Resolution values are never guessed. A supplied `--comment` also satisfies a +required comment on the transition screen. Other required fields without defaults +produce an error. Configure the workflow or complete those actions in Jira. + +A failure is nonzero. On GitHub/GitLab, a comment failure can leave the issue +closed; the error reports that partial result. Network/server failures on the +Jira transition POST are not automatically retried because the action may have +already occurred. Inspect the issue before retrying any uncertain result; reruns +can repeat comments or self-transition side effects. Normal rejected-request +handling for rate limits and expired OAuth credentials remains in effect. + +This command is a shared operation, not a code-agent policy. A code-agent harness +can supply a named transition to its post-script; triage can independently call +portable closure. GitHub Projects fields, run-start transitions, and PR-merge +monitoring are outside this command's first implementation. diff --git a/docs/guides/user/jira-integration.md b/docs/guides/user/jira-integration.md index 46af3793e8..8a7cf65b15 100644 --- a/docs/guides/user/jira-integration.md +++ b/docs/guides/user/jira-integration.md @@ -446,8 +446,8 @@ explicit `FULLSEND_TRACKER` or `ISSUE_URL` points somewhere else. Code stops if `JIRA_DUPLICATE_TRANSITION`, `JIRA_NOT_PLANNED_TRANSITION`, and `JIRA_SPLIT_TRANSITION` in the triage harness's Jira overlay (by default `Duplicate`, `Won't Do`, and `Obsolete`). Override them in a harness if your - Jira workflow uses different names. Tracker-neutral transition discovery is - tracked in [#6704](https://github.com/fullsend-ai/fullsend/issues/6704). + Jira workflow uses different names. Code uses the shared + `fullsend issues transition` command for the optional hooks described below. - **Updates Jira cannot apply:** triage lists them under **Not applied in Jira** in its comment instead of dropping them. This covers a label add for a label not used anywhere on the Jira site (triage does not create new @@ -460,17 +460,19 @@ explicit `FULLSEND_TRACKER` or `ISSUE_URL` points somewhere else. Code stops if posts a new one. - **Write failures:** a failed Jira write fails the step, so it is never reported as a success. For triage this covers label adds and removals, - component updates, comments, and transitions. For code the step fails even - though the PR or MR already exists. + component updates, comments, and transitions. For code, a failed stage comment fails the step even + though the PR or MR already exists. Optional code transitions only warn + on failure; they do not fail the run. - **Bot loops:** the writes authenticate as `JIRA_USER_EMAIL` / `JIRA_TOKEN`, the same account the poller classifies as `actor.kind: bot`, so they do not dispatch agents again. See [How it works](#how-it-works). - **Credentials:** the triage and code harnesses pass `JIRA_USER_EMAIL` and - `JIRA_TOKEN` to the runner-side post-scripts only. The sandbox gets the + `JIRA_TOKEN` to runner-side pre- and post-scripts only. The sandbox gets the `jira-ro` provider's placeholder, not the real token. -When the code agent makes no PR or MR, or the run fails, nothing beyond the -run-status update is written to Jira. +When the code agent makes no PR or MR, it does not perform a PR-ready +transition. A configured run label or started transition may already have +been applied, even if the run later fails. Custom agents can use `fullsend issues post-comment --tracker jira` to post results back to Jira, and `fullsend issues create --tracker jira` to create @@ -479,6 +481,43 @@ implementation ([#5989](https://github.com/fullsend-ai/fullsend/issues/5989)). See [Issue commands](issues-commands.md) for usage. +### Optional code transitions + +Use a code-agent harness with the transition hooks and a Fullsend version that +provides `fullsend issues transition`. Configure these settings in the harness, +not in `config.yaml`: + +```yaml +env: + runner: + CODE_JIRA_STARTED_TRANSITION: "In Progress" + CODE_JIRA_PR_READY_TRANSITION: "Review" +``` + +Both settings default to `"off"`; unset or empty values also disable the hook. +They are independent. Values must exactly match **transition names** available +in your Jira workflow, not destination status names. `In Progress` works here +only if the workflow has a transition with that name. Jira defines the allowed +source statuses and checks the account's transition permissions and workflow +conditions. Restrict the transitions in Jira if they must not reopen or move +blocked issues. + +The started hook runs after Jira code preflight completes without a fatal error, +including its skip checks and dependency-setup phase. Skipped runs do not +execute the transition. Existing warning-only +setup failures remain nonfatal. This happens before sandbox creation, so it +means the run passed preflight, not that code generation started. A later startup +failure does not roll back the transition. + +The PR-ready hook runs after the code-stage comment succeeds and the post-script +confirms an open, non-draft GitHub PR or GitLab MR. It does not watch for later +draft-to-ready changes or merges. Both hooks use the shared +[`fullsend issues transition`](issues-commands.md) command on the source Jira +issue. Missing prerequisites, unavailable transitions, and failed optional +writes produce warnings rather than failing the run. The hooks do not +retry failed writes automatically. A subsequent run may execute the transition +again, including a Jira self-transition if the workflow allows it. + ## Prerequisites - A GitHub repo with fullsend installed (`fullsend github setup` completed). @@ -1303,4 +1342,4 @@ However, more pollers against the same Jira project means more API calls per cyc - [CEL Triggers Reference](cel-triggers-reference.md) — NormalizedEvent fields and routing rules - [Bring Your Own Agent](bring-your-own-agent.md) — adding custom agents - [Configuring agent behavior](customizing-agents.md) — harness configuration -- [Issue commands](issues-commands.md) — `fullsend issues get`, `create`, and `post-comment`, including Jira +- [Issue commands](issues-commands.md) — `fullsend issues get`, `create`, `post-comment`, and `transition`, including Jira diff --git a/internal/cli/issues.go b/internal/cli/issues.go index 3e8dc7348b..fc368c3c74 100644 --- a/internal/cli/issues.go +++ b/internal/cli/issues.go @@ -59,6 +59,7 @@ FULLSEND_JIRA_CLIENT_SECRET.`, cmd.AddCommand(newIssuesCreateCmd()) cmd.AddCommand(newIssuesPostCommentCmd()) cmd.AddCommand(newIssuesLinkCmd()) + cmd.AddCommand(newIssuesTransitionCmd()) return cmd } diff --git a/internal/cli/issues_transition.go b/internal/cli/issues_transition.go new file mode 100644 index 0000000000..5a38d58201 --- /dev/null +++ b/internal/cli/issues_transition.go @@ -0,0 +1,91 @@ +package cli + +import ( + "context" + "encoding/json" + "fmt" + "io" + "os" + + "github.com/fullsend-ai/fullsend/internal/config" + "github.com/fullsend-ai/fullsend/internal/tracker" + "github.com/spf13/cobra" +) + +type issuesTransitionConfig struct { + trackerName, project, token, fullsendDir string + number int + opts tracker.TransitionOptions + comment string + testClient tracker.Client + testConfigReader config.PerRepoConfigReader + testWriter io.Writer +} + +func newIssuesTransitionCmd() *cobra.Command { + var cfg issuesTransitionConfig + 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. No arbitrary workflow action is chosen. + +An optional --comment is submitted with the Jira transition, or after closing +on GitHub/GitLab. A comment failure on a forge leaves the issue closed and +returns an error. Inspect the issue after an uncertain failure before retrying.`, + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, args []string) error { return runIssuesTransition(cmd.Context(), &cfg) }, + } + cmd.Flags().StringVar(&cfg.trackerName, "tracker", "", "tracker backend: github, gitlab, or jira (required unless a default is set via config)") + cmd.Flags().StringVar(&cfg.project, "project", "", projectFlagUsage) + 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.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") + cmd.Flags().StringVar(&cfg.comment, "comment", "", "optional Markdown comment explaining the transition") + _ = cmd.MarkFlagRequired("number") + return cmd +} + +func runIssuesTransition(ctx context.Context, cfg *issuesTransitionConfig) error { + if cfg.number <= 0 { + return fmt.Errorf("--number must be a positive integer, got %d", cfg.number) + } + if err := cfg.opts.Validate(); err != nil { + return err + } + name, err := resolveTracker(cfg.trackerName, cfg.fullsendDir, cfg.testConfigReader) + if err != nil { + return err + } + project, err := resolveIssueProject(name, cfg.project, cfg.fullsendDir, cfg.testConfigReader) + if err != nil { + return err + } + tc := cfg.testClient + if tc == nil { + tc, err = newConfiguredTrackerClient(name, cfg.token, cfg.fullsendDir, cfg.testConfigReader) + if err != nil { + return err + } + } + transitioner, ok := tc.(tracker.Transitioner) + if !ok { + return fmt.Errorf("issue transitions: %w", tracker.ErrNotSupported) + } + opts := cfg.opts + opts.Comment = tracker.Body(cfg.comment) + result, err := transitioner.TransitionIssue(ctx, project, cfg.number, opts) + if err != nil { + return fmt.Errorf("transitioning issue: %w", err) + } + out := cfg.testWriter + if out == nil { + out = os.Stdout + } + return json.NewEncoder(out).Encode(result) +} diff --git a/internal/cli/issues_transition_test.go b/internal/cli/issues_transition_test.go new file mode 100644 index 0000000000..88d71c2bb2 --- /dev/null +++ b/internal/cli/issues_transition_test.go @@ -0,0 +1,85 @@ +package cli + +import ( + "bytes" + "context" + "errors" + "testing" + + "github.com/fullsend-ai/fullsend/internal/tracker" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +type transitionTracker struct { + tracker.Client + project string + number int + opts tracker.TransitionOptions + err error +} + +func (f *transitionTracker) TransitionIssue(_ context.Context, project string, number int, opts tracker.TransitionOptions) (*tracker.TransitionResult, error) { + f.project, f.number, f.opts = project, number, opts + return &tracker.TransitionResult{Changed: true, Transition: opts.Name}, f.err +} + +func TestIssuesTransitionCommand(t *testing.T) { + cmd := newIssuesCmd() + found, _, err := cmd.Find([]string{"transition"}) + require.NoError(t, err) + assert.Equal(t, "transition", found.Name()) + for _, name := range []string{"tracker", "project", "number", "fullsend-dir", "token", "transition", "state", "status", "resolution", "comment"} { + require.NotNil(t, found.Flags().Lookup(name)) + } + for _, args := range [][]string{{"--number", "1"}, {"--state", "closed"}, {"--number", "1", "unexpected"}} { + c := newIssuesTransitionCmd() + c.SetArgs(args) + require.Error(t, c.Execute()) + } +} + +func TestRunIssuesTransition(t *testing.T) { + for _, name := range []string{"jira", "github", "gitlab"} { + t.Run(name, func(t *testing.T) { + f := &transitionTracker{} + var out bytes.Buffer + cfg := &issuesTransitionConfig{trackerName: name, project: "owner/repo", number: 618, opts: tracker.TransitionOptions{State: "closed"}, comment: "Completed", testClient: f, testWriter: &out} + require.NoError(t, runIssuesTransition(context.Background(), cfg)) + assert.Equal(t, "owner/repo", f.project) + assert.Equal(t, 618, f.number) + assert.Equal(t, tracker.Body("Completed"), f.opts.Comment) + assert.Contains(t, out.String(), `"changed":true`) + }) + } +} + +func TestRunIssuesTransitionErrors(t *testing.T) { + for _, tt := range []struct { + name string + change func(*issuesTransitionConfig) + want string + }{ + {"number", func(c *issuesTransitionConfig) { c.number = 0 }, "positive"}, + {"selectors", func(c *issuesTransitionConfig) { c.opts.Name = "Review" }, "exactly one"}, + {"state", func(c *issuesTransitionConfig) { c.opts.State = "open" }, "unsupported lifecycle"}, + {"tracker", func(c *issuesTransitionConfig) { c.trackerName = "other" }, "unsupported --tracker"}, + {"missing tracker", func(c *issuesTransitionConfig) { c.trackerName = "" }, "--tracker is required"}, + {"project", func(c *issuesTransitionConfig) { c.project = "" }, "--project"}, + {"client config", func(c *issuesTransitionConfig) { c.trackerName = "jira"; c.testClient = nil }, "Jira requires"}, + {"unsupported", func(c *issuesTransitionConfig) { c.testClient = &noTransitionTracker{} }, "not supported"}, + {"backend", func(c *issuesTransitionConfig) { c.testClient = &transitionTracker{err: errors.New("workflow denied")} }, "workflow denied"}, + {"output", func(c *issuesTransitionConfig) { c.testWriter = failingTransitionWriter{} }, "write failed"}, + } { + t.Run(tt.name, func(t *testing.T) { + c := &issuesTransitionConfig{trackerName: "github", project: "o/r", number: 1, opts: tracker.TransitionOptions{State: "closed"}, testClient: &transitionTracker{}, testWriter: &bytes.Buffer{}} + tt.change(c) + require.ErrorContains(t, runIssuesTransition(context.Background(), c), tt.want) + }) + } +} + +type noTransitionTracker struct{ tracker.Client } +type failingTransitionWriter struct{} + +func (failingTransitionWriter) Write([]byte) (int, error) { return 0, errors.New("write failed") } diff --git a/internal/forge/jira/transition.go b/internal/forge/jira/transition.go new file mode 100644 index 0000000000..7c9f55b3b6 --- /dev/null +++ b/internal/forge/jira/transition.go @@ -0,0 +1,62 @@ +package jira + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "net/http" + "net/url" +) + +// Transition is an action available to the caller in the issue's current workflow. +type Transition struct { + ID string `json:"id"` + Name string `json:"name"` + To Status `json:"to"` + Fields map[string]TransitionField `json:"fields"` +} + +// TransitionField describes a field on a transition screen. +type TransitionField struct { + Required bool `json:"required"` + HasDefaultValue bool `json:"hasDefaultValue"` + AllowedValues []json.RawMessage `json:"allowedValues"` +} + +// ListTransitions returns available actions and their screen field requirements. +func (c *LiveClient) ListTransitions(ctx context.Context, key string) ([]Transition, error) { + var result struct { + Transitions []Transition `json:"transitions"` + } + err := c.do(ctx, http.MethodGet, "/issue/"+url.PathEscape(key)+"/transitions?expand=transitions.fields", nil, &result) + if err != nil { + return nil, fmt.Errorf("listing transitions for %q: %w", key, err) + } + return result.Transitions, nil +} + +// ApplyTransition submits the selected ID, fields and optional Markdown comment +// in one request. Ambiguous network/server failures are not retried by do. +func (c *LiveClient) ApplyTransition(ctx context.Context, key, id string, fields map[string]any, comment string) error { + request := struct { + Transition map[string]string `json:"transition"` + Fields map[string]any `json:"fields,omitempty"` + Update map[string]any `json:"update,omitempty"` + }{Transition: map[string]string{"id": id}, Fields: fields} + if comment != "" { + adf, err := MarkdownToADF(comment) + if err != nil { + return fmt.Errorf("converting transition comment: %w", err) + } + request.Update = map[string]any{"comment": []any{map[string]any{"add": map[string]any{"body": adf}}}} + } + body, err := json.Marshal(request) + if err != nil { + return fmt.Errorf("encoding transition: %w", err) + } + if err := c.do(ctx, http.MethodPost, "/issue/"+url.PathEscape(key)+"/transitions", bytes.NewReader(body), nil); err != nil { + return fmt.Errorf("applying transition %q to %q: %w", id, key, err) + } + return nil +} diff --git a/internal/forge/jira/transition_test.go b/internal/forge/jira/transition_test.go new file mode 100644 index 0000000000..36444e25ec --- /dev/null +++ b/internal/forge/jira/transition_test.go @@ -0,0 +1,64 @@ +package jira + +import ( + "context" + "encoding/json" + "net/http" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestTransitions(t *testing.T) { + c, mux := setupTest(t) + gets, posts := 0, 0 + mux.HandleFunc("/rest/api/3/issue/PROJ-1/transitions", func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodGet { + gets++ + assert.Equal(t, "transitions.fields", r.URL.Query().Get("expand")) + writeJSON(t, w, 200, map[string]any{"transitions": []Transition{{ID: "21", Name: "Review", Fields: map[string]TransitionField{"resolution": {Required: true, AllowedValues: []json.RawMessage{json.RawMessage(`{"id":"1","name":"Fixed"}`)}}}}}}) + return + } + posts++ + assert.Equal(t, http.MethodPost, r.Method) + var body map[string]any + require.NoError(t, json.NewDecoder(r.Body).Decode(&body)) + assert.Equal(t, map[string]any{"id": "21"}, body["transition"]) + assert.Equal(t, map[string]any{"resolution": map[string]any{"id": "1"}}, body["fields"]) + updates := body["update"].(map[string]any)["comment"].([]any) + adf := updates[0].(map[string]any)["add"].(map[string]any)["body"] + assert.Contains(t, ADFToMarkdown(adf), "Ready") + w.WriteHeader(204) + }) + tr, err := c.ListTransitions(context.Background(), "PROJ-1") + require.NoError(t, err) + require.Len(t, tr, 1) + assert.True(t, tr[0].Fields["resolution"].Required) + require.NoError(t, c.ApplyTransition(context.Background(), "PROJ-1", "21", map[string]any{"resolution": map[string]string{"id": "1"}}, "**Ready**")) + assert.Equal(t, 1, gets) + assert.Equal(t, 1, posts) +} + +func TestTransitionErrorsAndNoRetry(t *testing.T) { + for _, status := range []int{400, 401, 403, 404, 500} { + t.Run(http.StatusText(status), func(t *testing.T) { + c, mux := setupTest(t) + calls := 0 + mux.HandleFunc("/rest/api/3/issue/P-1/transitions", func(w http.ResponseWriter, r *http.Request) { + calls++ + w.WriteHeader(status) + _, _ = w.Write([]byte(`{"errorMessages":["denied"]}`)) + }) + err := c.ApplyTransition(context.Background(), "P-1", "1", nil, "") + require.Error(t, err) + assert.Equal(t, 1, calls) + if status < 500 { + _, err = c.ListTransitions(context.Background(), "P-1") + require.Error(t, err) + } + }) + } + c, _ := setupTest(t) + require.ErrorContains(t, c.ApplyTransition(context.Background(), "P-1", "1", map[string]any{"bad": make(chan int)}, ""), "encoding transition") +} diff --git a/internal/tracker/transition.go b/internal/tracker/transition.go new file mode 100644 index 0000000000..a206d0da00 --- /dev/null +++ b/internal/tracker/transition.go @@ -0,0 +1,185 @@ +package tracker + +import ( + "context" + "encoding/json" + "fmt" + "strings" + + "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. +type TransitionOptions struct { + State string + Name string + Status string + Resolution string + Comment Body +} + +// Validate rejects conflicting or missing selectors before any write. +func (o TransitionOptions) Validate() error { + selectors := 0 + for _, value := range []string{o.State, o.Name, o.Status} { + if value != "" { + selectors++ + } + } + if selectors != 1 { + return fmt.Errorf("specify exactly one of --state, --transition, or --status") + } + if o.State != "" && o.State != "closed" { + return fmt.Errorf("unsupported lifecycle state %q: use closed", o.State) + } + return nil +} + +// 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. +type TransitionResult struct { + Changed bool `json:"changed"` + Transition string `json:"transition,omitempty"` + Status string `json:"status,omitempty"` +} + +// Transitioner is the optional tracker capability for workflow changes. Callers +// authorize the target before invoking it. Implementations do not retry uncertain +// writes; an error can mean the action succeeded but its response was lost. +type Transitioner interface { + TransitionIssue(context.Context, string, int, TransitionOptions) (*TransitionResult, error) +} + +var _ Transitioner = (*ForgeClient)(nil) +var _ Transitioner = (*JiraClient)(nil) + +// TransitionIssue delegates portable closure to the forge. The optional comment +// is a second request; its failure explicitly reports the completed transition. +func (c *ForgeClient) TransitionIssue(ctx context.Context, project string, number int, opts TransitionOptions) (*TransitionResult, error) { + if err := opts.Validate(); err != nil { + return nil, err + } + if opts.State != "closed" || opts.Resolution != "" { + return nil, fmt.Errorf("named transitions, target statuses and resolutions: %w (Jira only)", ErrNotSupported) + } + owner, repo, err := splitProject(project) + if err != nil { + return nil, err + } + issue, err := c.forge.GetIssue(ctx, owner, repo, number) + if err != nil { + return nil, wrapNotFound(err) + } + changed := !strings.EqualFold(issue.State, "closed") + if changed { + if err := c.forge.CloseIssue(ctx, owner, repo, number); err != nil { + return nil, wrapNotFound(err) + } + } + if opts.Comment != "" { + if _, err := c.CreateComment(ctx, project, number, opts.Comment); err != nil { + return nil, fmt.Errorf("issue is closed, but posting the comment failed; do not blindly repeat the command: %w", err) + } + } + return &TransitionResult{Changed: changed, Status: "closed"}, nil +} + +type jiraTransitions interface { + ListTransitions(context.Context, string) ([]jira.Transition, error) + ApplyTransition(context.Context, string, string, map[string]any, string) error +} + +// TransitionIssue resolves a unique currently available Jira action. Workflow +// permissions and source-state restrictions stay in Jira, not in agent config. +func (c *JiraClient) TransitionIssue(ctx context.Context, project string, number int, opts TransitionOptions) (*TransitionResult, error) { + if err := opts.Validate(); err != nil { + return nil, err + } + api, ok := c.jira.(jiraTransitions) + if !ok { + return nil, ErrNotSupported + } + key := issueKey(project, number) + if opts.State == "closed" { + issue, err := c.jira.GetIssue(ctx, key) + if err != nil { + return nil, wrapNotFound(err) + } + if issue.Fields.Status.StatusCategory.Key == "done" { + 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 &TransitionResult{Status: issue.Fields.Status.Name}, nil + } + } + transitions, err := api.ListTransitions(ctx, key) + if err != nil { + return nil, wrapNotFound(err) + } + 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") { + matches = append(matches, tr) + } + } + if len(matches) == 0 { + 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)) + } + 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) + 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 +} + +func transitionFields(tr jira.Transition, resolution string, comment Body) (map[string]any, error) { + fields := make(map[string]any) + if resolution != "" { + field, ok := tr.Fields["resolution"] + if !ok { + return nil, fmt.Errorf("transition %q does not accept a resolution", tr.Name) + } + var matches []map[string]string + for _, raw := range field.AllowedValues { + var value struct { + ID string `json:"id"` + Name string `json:"name"` + } + if json.Unmarshal(raw, &value) == nil && (value.ID == resolution || value.Name == resolution) && value.ID != "" { + matches = append(matches, map[string]string{"id": value.ID}) + } + } + if len(matches) != 1 { + return nil, fmt.Errorf("resolution %q must match one allowed ID or name for transition %q", resolution, tr.Name) + } + fields["resolution"] = matches[0] + } + for name, field := range tr.Fields { + if !field.Required || field.HasDefaultValue || (name == "comment" && comment != "") { + continue + } + if _, ok := fields[name]; ok { + continue + } + if name == "resolution" { + return nil, fmt.Errorf("transition %q requires --resolution (an allowed resolution ID or name)", tr.Name) + } + return nil, fmt.Errorf("transition %q requires unsupported field %q; configure a transition with defaults or complete it in Jira", tr.Name, name) + } + return fields, nil +} diff --git a/internal/tracker/transition_test.go b/internal/tracker/transition_test.go new file mode 100644 index 0000000000..8a97322b25 --- /dev/null +++ b/internal/tracker/transition_test.go @@ -0,0 +1,201 @@ +package tracker + +import ( + "context" + "encoding/json" + "errors" + "testing" + + "github.com/fullsend-ai/fullsend/internal/forge" + "github.com/fullsend-ai/fullsend/internal/forge/jira" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +type transitionJira struct { + *FakeJiraClient + transitions []jira.Transition + listErr, applyErr error + calls int + key, id, comment string + fields map[string]any +} + +func (f *transitionJira) ListTransitions(context.Context, string) ([]jira.Transition, error) { + return f.transitions, f.listErr +} +func (f *transitionJira) ApplyTransition(_ context.Context, key, id string, fields map[string]any, comment string) error { + f.calls++ + f.key, f.id, f.fields, f.comment = key, id, fields, comment + return f.applyErr +} + +func TestJiraTransition(t *testing.T) { + review := jira.Transition{ID: "21", Name: "Review", To: jira.Status{Name: "In Review"}} + close := jira.Transition{ID: "31", Name: "Close", To: jira.Status{Name: "Done", StatusCategory: jira.StatusCategory{Key: "done"}}} + for _, tt := range []struct { + name string + opts TransitionOptions + transitions []jira.Transition + listErr, applyErr error + wantErr string + }{ + {name: "named", opts: TransitionOptions{Name: "Review", Comment: "**Ready**"}, transitions: []jira.Transition{review, close}}, + {name: "status", opts: TransitionOptions{Status: "In Review"}, transitions: []jira.Transition{review}}, + {name: "semantic close", opts: TransitionOptions{State: "closed"}, transitions: []jira.Transition{review, close}}, + {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"}, + {name: "required field", opts: TransitionOptions{Name: "Review"}, transitions: []jira.Transition{{ID: "21", Name: "Review", Fields: map[string]jira.TransitionField{"customfield_123": {Required: true}}}}, wantErr: "requires unsupported field"}, + {name: "invalid selectors", opts: TransitionOptions{Name: "Review", State: "closed"}, wantErr: "exactly one"}, + } { + t.Run(tt.name, func(t *testing.T) { + f := &transitionJira{FakeJiraClient: &FakeJiraClient{Issues: map[string]*jira.Issue{"PROJ-1": {}}}, transitions: tt.transitions, listErr: tt.listErr, applyErr: tt.applyErr} + c, err := NewJiraClient(f, "https://example.atlassian.net") + require.NoError(t, err) + result, err := c.TransitionIssue(context.Background(), "PROJ", 1, tt.opts) + if tt.wantErr != "" { + require.ErrorContains(t, err, tt.wantErr) + if tt.applyErr == nil { + assert.Zero(t, f.calls) + } + return + } + require.NoError(t, err) + assert.True(t, result.Changed) + assert.Equal(t, 1, f.calls) + assert.Equal(t, "PROJ-1", f.key) + assert.Equal(t, string(tt.opts.Comment), f.comment) + }) + } +} + +func TestTransitionFields(t *testing.T) { + resolution := jira.TransitionField{Required: true, AllowedValues: []json.RawMessage{json.RawMessage(`{"id":"1","name":"Fixed"}`), json.RawMessage(`{"id":"2","name":"Duplicate"}`)}} + for _, tt := range []struct { + name, res string + fields map[string]jira.TransitionField + wantErr string + }{ + {"name", "Fixed", map[string]jira.TransitionField{"resolution": resolution}, ""}, + {"id", "2", map[string]jira.TransitionField{"resolution": resolution}, ""}, + {"required", "", map[string]jira.TransitionField{"resolution": resolution}, "requires --resolution"}, + {"invalid", "unknown", map[string]jira.TransitionField{"resolution": resolution}, "must match one"}, + {"not on screen", "Fixed", nil, "does not accept"}, + {"default", "", map[string]jira.TransitionField{"resolution": {Required: true, HasDefaultValue: true}}, ""}, + {"optional", "", map[string]jira.TransitionField{"summary": {}}, ""}, + {"ambiguous", "Fixed", map[string]jira.TransitionField{"resolution": {AllowedValues: []json.RawMessage{resolution.AllowedValues[0], resolution.AllowedValues[0]}}}, "must match one"}, + {"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, "") + if tt.wantErr != "" { + require.ErrorContains(t, err, tt.wantErr) + } else { + require.NoError(t, err) + if tt.res != "" { + assert.NotEmpty(t, fields["resolution"]) + } + } + }) + } +} + +func TestJiraTransitionAlreadyClosed(t *testing.T) { + f := &transitionJira{FakeJiraClient: &FakeJiraClient{Issues: map[string]*jira.Issue{"P-1": {Fields: jira.IssueFields{Status: jira.Status{Name: "Done", StatusCategory: jira.StatusCategory{Key: "done"}}}}}}, transitions: []jira.Transition{{ID: "1", Name: "Close"}}} + c, err := NewJiraClient(f, "https://example.atlassian.net") + require.NoError(t, err) + result, err := c.TransitionIssue(context.Background(), "P", 1, TransitionOptions{State: "closed"}) + require.NoError(t, err) + assert.False(t, result.Changed) + assert.Zero(t, f.calls) + // Explicit named actions still execute even on a done issue (self-transitions). + _, err = c.TransitionIssue(context.Background(), "P", 1, TransitionOptions{Name: "Close"}) + require.NoError(t, err) + assert.Equal(t, 1, f.calls) + _, err = c.TransitionIssue(context.Background(), "P", 2, TransitionOptions{State: "closed"}) + require.Error(t, err) + assert.True(t, IsNotFound(err)) + plain, err := NewJiraClient(&FakeJiraClient{}, "https://example.atlassian.net") + require.NoError(t, err) + _, err = plain.TransitionIssue(context.Background(), "P", 1, TransitionOptions{Name: "Close"}) + assert.ErrorIs(t, err, ErrNotSupported) +} + +type transitionForge struct { + forge.Client + state string + getErr, closeErr, commentErr error + closes, comments int + project string + number int +} + +func (f *transitionForge) GetIssue(_ context.Context, owner, repo string, number int) (*forge.Issue, error) { + f.project = owner + "/" + repo + f.number = number + return &forge.Issue{State: f.state}, f.getErr +} +func (f *transitionForge) CloseIssue(context.Context, string, string, int) error { + f.closes++ + return f.closeErr +} +func (f *transitionForge) CreateIssueComment(context.Context, string, string, int, string) (*forge.IssueComment, error) { + f.comments++ + return &forge.IssueComment{}, f.commentErr +} +func TestForgeTransition(t *testing.T) { + for _, tt := range []struct { + name, state string + opts TransitionOptions + getErr, closeErr, commentErr error + wantErr string + closes, comments int + }{ + {name: "close with comment", opts: TransitionOptions{State: "closed", Comment: "done"}, closes: 1, comments: 1}, + {name: "already closed comment", state: "closed", opts: TransitionOptions{State: "closed", Comment: "done"}, comments: 1}, + {name: "already closed", state: "closed", opts: TransitionOptions{State: "closed"}}, + {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: "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}, + } { + t.Run(tt.name, func(t *testing.T) { + f := &transitionForge{state: tt.state, getErr: tt.getErr, closeErr: tt.closeErr, commentErr: tt.commentErr} + c := NewForgeClient(f) + result, err := c.TransitionIssue(context.Background(), "group/sub/repo", 7, tt.opts) + if tt.wantErr != "" { + require.ErrorContains(t, err, tt.wantErr) + } else { + require.NoError(t, err) + assert.Equal(t, tt.state != "closed", result.Changed) + assert.Equal(t, "group/sub/repo", f.project) + assert.Equal(t, 7, f.number) + } + assert.Equal(t, tt.closes, f.closes) + assert.Equal(t, tt.comments, f.comments) + }) + } + _, err := NewForgeClient(&transitionForge{}).TransitionIssue(context.Background(), "invalid", 1, TransitionOptions{State: "closed"}) + require.Error(t, err) +} + +func TestTransitionRequiredComment(t *testing.T) { + tr := jira.Transition{ID: "21", Name: "Review", Fields: map[string]jira.TransitionField{"comment": {Required: true}}} + f := &transitionJira{FakeJiraClient: &FakeJiraClient{}, transitions: []jira.Transition{tr}} + c, err := NewJiraClient(f, "https://example.atlassian.net") + require.NoError(t, err) + _, err = c.TransitionIssue(context.Background(), "P", 1, TransitionOptions{Name: "Review"}) + require.ErrorContains(t, err, `requires unsupported field "comment"`) + assert.Zero(t, f.calls) + _, err = c.TransitionIssue(context.Background(), "P", 1, TransitionOptions{Name: "Review", Comment: "Ready for review"}) + require.NoError(t, err) + assert.Equal(t, "Ready for review", f.comment) + assert.Equal(t, 1, f.calls) +} From 35ec01c8d3e69b36564f5ff72213959c80f23c19 Mon Sep 17 00:00:00 2001 From: Eder Ignatowicz Date: Fri, 13 Nov 2026 12:41:13 -0500 Subject: [PATCH 2/2] fix(issues): address Jira transition review findings Signed-off-by: Eder Ignatowicz --- docs/agents/code.md | 13 +---- docs/contributing/documentation.md | 2 +- docs/guides/user/issues-commands.md | 25 +++++---- docs/guides/user/jira-integration.md | 53 +++-------------- docs/reference/config-reference.md | 2 +- internal/cli/issues_transition.go | 43 ++++++++++---- internal/cli/issues_transition_test.go | 22 ++++++++ internal/forge/jira/transition.go | 16 +++--- internal/forge/jira/transition_test.go | 2 +- internal/tracker/transition.go | 42 ++++++++------ internal/tracker/transition_test.go | 78 +++++++++++++++++++++++++- 11 files changed, 189 insertions(+), 109 deletions(-) diff --git a/docs/agents/code.md b/docs/agents/code.md index 710ef4102a..b6768cecad 100644 --- a/docs/agents/code.md +++ b/docs/agents/code.md @@ -104,18 +104,7 @@ composition. ### Variables -These optional settings belong in the code harness's `env.runner` mapping. -Use an agents version that includes the corresponding hooks and a Fullsend -version that provides `fullsend issues transition`. - -| Variable | Default | Purpose | -|---|---|---| -| `CODE_JIRA_STARTED_TRANSITION` | `"off"` | Jira transition after code preflight completes without a fatal error, before sandbox creation | -| `CODE_JIRA_PR_READY_TRANSITION` | `"off"` | Jira transition after confirming an open, non-draft PR or MR | - -Values are Jira transition names, not destination status names. See -[Optional code transitions](../guides/user/jira-integration.md#optional-code-transitions) -for configuration, permissions, and failure behavior. +None. ## Source diff --git a/docs/contributing/documentation.md b/docs/contributing/documentation.md index 1b99fb3ce2..e158637d52 100644 --- a/docs/contributing/documentation.md +++ b/docs/contributing/documentation.md @@ -287,7 +287,7 @@ The `admin` command group's `uninstall`/`analyze`/`enable`/`disable` subcommands |----------|-------| | CLI reference | _(no dedicated page)_ | | Guides | `docs/guides/user/issues-commands.md`, `docs/guides/user/jira-integration.md`, `docs/guides/infrastructure/layered-config-reference.md`, `docs/guides/dev/cli-internals.md` | -| Go source | `internal/cli/issues.go` | +| Go source | `internal/cli/issues.go`, `internal/cli/issues_transition.go` | ## Minor commands diff --git a/docs/guides/user/issues-commands.md b/docs/guides/user/issues-commands.md index e62d1c4297..30fe89083f 100644 --- a/docs/guides/user/issues-commands.md +++ b/docs/guides/user/issues-commands.md @@ -2,7 +2,7 @@ Read and write issue content across GitHub, GitLab, and Jira from custom agent scripts using `fullsend issues get`, -`fullsend issues create`, `fullsend issues post-comment`, and +`fullsend issues create`, `fullsend issues post-comment`, `fullsend issues link`, and `fullsend issues transition`. ## When to use @@ -379,7 +379,7 @@ Exactly one selector is required: | `--state closed` | Portable closure on GitHub, GitLab, and Jira. Jira selects a unique available transition whose destination has status category `done`. | | `--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. | +| `--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. | | `--comment TEXT` | Optional Markdown explanation. Jira submits it atomically with the transition; GitHub/GitLab post it after closing. | `--tracker`, `--project`, `--number`, `--fullsend-dir`, and `--token` @@ -389,16 +389,22 @@ positive. Jira requires its connection settings in the configuration directory. 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. Explicit named transitions always execute, +but still posts a requested comment. 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 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. -Resolution values are never guessed. A supplied `--comment` also satisfies a -required comment on the transition screen. Other required fields without defaults -produce an error. Configure the workflow or complete those actions in Jira. +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 +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. A failure is nonzero. On GitHub/GitLab, a comment failure can leave the issue closed; the error reports that partial result. Network/server failures on the @@ -407,7 +413,6 @@ already occurred. Inspect the issue before retrying any uncertain result; reruns can repeat comments or self-transition side effects. Normal rejected-request handling for rate limits and expired OAuth credentials remains in effect. -This command is a shared operation, not a code-agent policy. A code-agent harness -can supply a named transition to its post-script; triage can independently call -portable closure. GitHub Projects fields, run-start transitions, and PR-merge -monitoring are outside this command's first implementation. +The command runs only when invoked. It does not install event handlers or +change the built-in code or triage harnesses. It updates issue lifecycle state, +not GitHub Projects fields. diff --git a/docs/guides/user/jira-integration.md b/docs/guides/user/jira-integration.md index 8a7cf65b15..359976e8c8 100644 --- a/docs/guides/user/jira-integration.md +++ b/docs/guides/user/jira-integration.md @@ -446,8 +446,9 @@ explicit `FULLSEND_TRACKER` or `ISSUE_URL` points somewhere else. Code stops if `JIRA_DUPLICATE_TRANSITION`, `JIRA_NOT_PLANNED_TRANSITION`, and `JIRA_SPLIT_TRANSITION` in the triage harness's Jira overlay (by default `Duplicate`, `Won't Do`, and `Obsolete`). Override them in a harness if your - Jira workflow uses different names. Code uses the shared - `fullsend issues transition` command for the optional hooks described below. + Jira workflow uses different names. Custom agents can use the shared + [`fullsend issues transition`](issues-commands.md#fullsend-issues-transition) + command to discover and apply Jira transitions. - **Updates Jira cannot apply:** triage lists them under **Not applied in Jira** in its comment instead of dropping them. This covers a label add for a label not used anywhere on the Jira site (triage does not create new @@ -460,9 +461,8 @@ explicit `FULLSEND_TRACKER` or `ISSUE_URL` points somewhere else. Code stops if posts a new one. - **Write failures:** a failed Jira write fails the step, so it is never reported as a success. For triage this covers label adds and removals, - component updates, comments, and transitions. For code, a failed stage comment fails the step even - though the PR or MR already exists. Optional code transitions only warn - on failure; they do not fail the run. + component updates, comments, and transitions. For code the step fails even + though the PR or MR already exists. - **Bot loops:** the writes authenticate as `JIRA_USER_EMAIL` / `JIRA_TOKEN`, the same account the poller classifies as `actor.kind: bot`, so they do not dispatch agents again. See [How it works](#how-it-works). @@ -470,9 +470,9 @@ explicit `FULLSEND_TRACKER` or `ISSUE_URL` points somewhere else. Code stops if `JIRA_TOKEN` to runner-side pre- and post-scripts only. The sandbox gets the `jira-ro` provider's placeholder, not the real token. -When the code agent makes no PR or MR, it does not perform a PR-ready -transition. A configured run label or started transition may already have -been applied, even if the run later fails. +When the code agent makes no PR or MR, or the run fails, no code-stage result +is written to Jira. Run-status updates and a configured run label may already +have been applied. Custom agents can use `fullsend issues post-comment --tracker jira` to post results back to Jira, and `fullsend issues create --tracker jira` to create @@ -481,43 +481,6 @@ implementation ([#5989](https://github.com/fullsend-ai/fullsend/issues/5989)). See [Issue commands](issues-commands.md) for usage. -### Optional code transitions - -Use a code-agent harness with the transition hooks and a Fullsend version that -provides `fullsend issues transition`. Configure these settings in the harness, -not in `config.yaml`: - -```yaml -env: - runner: - CODE_JIRA_STARTED_TRANSITION: "In Progress" - CODE_JIRA_PR_READY_TRANSITION: "Review" -``` - -Both settings default to `"off"`; unset or empty values also disable the hook. -They are independent. Values must exactly match **transition names** available -in your Jira workflow, not destination status names. `In Progress` works here -only if the workflow has a transition with that name. Jira defines the allowed -source statuses and checks the account's transition permissions and workflow -conditions. Restrict the transitions in Jira if they must not reopen or move -blocked issues. - -The started hook runs after Jira code preflight completes without a fatal error, -including its skip checks and dependency-setup phase. Skipped runs do not -execute the transition. Existing warning-only -setup failures remain nonfatal. This happens before sandbox creation, so it -means the run passed preflight, not that code generation started. A later startup -failure does not roll back the transition. - -The PR-ready hook runs after the code-stage comment succeeds and the post-script -confirms an open, non-draft GitHub PR or GitLab MR. It does not watch for later -draft-to-ready changes or merges. Both hooks use the shared -[`fullsend issues transition`](issues-commands.md) command on the source Jira -issue. Missing prerequisites, unavailable transitions, and failed optional -writes produce warnings rather than failing the run. The hooks do not -retry failed writes automatically. A subsequent run may execute the transition -again, including a Jira self-transition if the workflow allows it. - ## Prerequisites - A GitHub repo with fullsend installed (`fullsend github setup` completed). diff --git a/docs/reference/config-reference.md b/docs/reference/config-reference.md index 674acec46a..bcae19902b 100644 --- a/docs/reference/config-reference.md +++ b/docs/reference/config-reference.md @@ -431,7 +431,7 @@ shared Jira client: `FULLSEND_JIRA_TOKEN` is required and `FULLSEND_JIRA_CLIENT_SECRET` replace both, as described above. The legacy `JIRA_TOKEN` and `JIRA_USER_EMAIL` variables are not used by the poller. -The `fullsend issues` commands (`get`, `create`, `post-comment`, `link`), +The `fullsend issues` commands (`get`, `create`, `post-comment`, `link`, `transition`), `fullsend run` Jira status updates, and `fullsend reconcile-status` read the Jira connection only from these settings, with no flag or environment fallback: `base_url` and `project` must be set, and Jira API calls fail diff --git a/internal/cli/issues_transition.go b/internal/cli/issues_transition.go index 5a38d58201..c2d2b0dda7 100644 --- a/internal/cli/issues_transition.go +++ b/internal/cli/issues_transition.go @@ -13,29 +13,46 @@ import ( ) type issuesTransitionConfig struct { - trackerName, project, token, fullsendDir string - number int - opts tracker.TransitionOptions - comment string - testClient tracker.Client - testConfigReader config.PerRepoConfigReader - testWriter io.Writer + trackerName string + project string + token string + fullsendDir string + number int + opts tracker.TransitionOptions + comment string + + // Test overrides — when non-nil, bypass production dependencies. + testClient tracker.Client + testConfigReader config.PerRepoConfigReader + testWriter io.Writer +} + +// 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"` } func newIssuesTransitionCmd() *cobra.Command { var cfg issuesTransitionConfig cmd := &cobra.Command{ - Use: "transition", Short: "Transition an issue through its tracker workflow", + 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. No arbitrary workflow action is chosen. +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. An optional --comment is submitted with the Jira transition, or after closing on GitHub/GitLab. A comment failure on a forge leaves the issue closed and returns an error. Inspect the issue after an uncertain failure before retrying.`, Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { return runIssuesTransition(cmd.Context(), &cfg) }, + RunE: func(cmd *cobra.Command, args []string) error { + return runIssuesTransition(cmd.Context(), &cfg) + }, } cmd.Flags().StringVar(&cfg.trackerName, "tracker", "", "tracker backend: github, gitlab, or jira (required unless a default is set via config)") cmd.Flags().StringVar(&cfg.project, "project", "", projectFlagUsage) @@ -87,5 +104,9 @@ func runIssuesTransition(ctx context.Context, cfg *issuesTransitionConfig) error if out == nil { out = os.Stdout } - return json.NewEncoder(out).Encode(result) + return json.NewEncoder(out).Encode(issueTransitionResult{ + Changed: result.Changed, + Transition: result.Transition, + Status: result.Status, + }) } diff --git a/internal/cli/issues_transition_test.go b/internal/cli/issues_transition_test.go index 88d71c2bb2..283d6862d3 100644 --- a/internal/cli/issues_transition_test.go +++ b/internal/cli/issues_transition_test.go @@ -17,10 +17,14 @@ type transitionTracker struct { number int opts tracker.TransitionOptions err error + result *tracker.TransitionResult } func (f *transitionTracker) TransitionIssue(_ context.Context, project string, number int, opts tracker.TransitionOptions) (*tracker.TransitionResult, error) { f.project, f.number, f.opts = project, number, opts + if f.result != nil { + return f.result, f.err + } return &tracker.TransitionResult{Changed: true, Transition: opts.Name}, f.err } @@ -83,3 +87,21 @@ type noTransitionTracker struct{ tracker.Client } type failingTransitionWriter struct{} func (failingTransitionWriter) Write([]byte) (int, error) { return 0, errors.New("write failed") } + +func TestRunIssuesTransitionJSONContract(t *testing.T) { + for _, tt := range []struct { + name string + result tracker.TransitionResult + want string + }{ + {"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"}`}, + } { + t.Run(tt.name, func(t *testing.T) { + var out bytes.Buffer + cfg := &issuesTransitionConfig{trackerName: "jira", project: "PROJ", number: 1, opts: tracker.TransitionOptions{State: "closed"}, testClient: &transitionTracker{result: &tt.result}, testWriter: &out} + require.NoError(t, runIssuesTransition(context.Background(), cfg)) + assert.JSONEq(t, tt.want, out.String()) + }) + } +} diff --git a/internal/forge/jira/transition.go b/internal/forge/jira/transition.go index 7c9f55b3b6..1ba12dda5c 100644 --- a/internal/forge/jira/transition.go +++ b/internal/forge/jira/transition.go @@ -25,20 +25,20 @@ type TransitionField struct { } // ListTransitions returns available actions and their screen field requirements. -func (c *LiveClient) ListTransitions(ctx context.Context, key string) ([]Transition, error) { +func (c *LiveClient) ListTransitions(ctx context.Context, issueIDOrKey string) ([]Transition, error) { var result struct { Transitions []Transition `json:"transitions"` } - err := c.do(ctx, http.MethodGet, "/issue/"+url.PathEscape(key)+"/transitions?expand=transitions.fields", nil, &result) + err := c.do(ctx, http.MethodGet, "/issue/"+url.PathEscape(issueIDOrKey)+"/transitions?expand=transitions.fields", nil, &result) if err != nil { - return nil, fmt.Errorf("listing transitions for %q: %w", key, err) + return nil, fmt.Errorf("list transitions for %q: %w", issueIDOrKey, err) } return result.Transitions, nil } // ApplyTransition submits the selected ID, fields and optional Markdown comment // in one request. Ambiguous network/server failures are not retried by do. -func (c *LiveClient) ApplyTransition(ctx context.Context, key, id string, fields map[string]any, comment string) error { +func (c *LiveClient) ApplyTransition(ctx context.Context, issueIDOrKey, id string, fields map[string]any, comment string) error { request := struct { Transition map[string]string `json:"transition"` Fields map[string]any `json:"fields,omitempty"` @@ -47,16 +47,16 @@ func (c *LiveClient) ApplyTransition(ctx context.Context, key, id string, fields if comment != "" { adf, err := MarkdownToADF(comment) if err != nil { - return fmt.Errorf("converting transition comment: %w", err) + return fmt.Errorf("convert transition comment: %w", err) } request.Update = map[string]any{"comment": []any{map[string]any{"add": map[string]any{"body": adf}}}} } body, err := json.Marshal(request) if err != nil { - return fmt.Errorf("encoding transition: %w", err) + return fmt.Errorf("encode transition: %w", err) } - if err := c.do(ctx, http.MethodPost, "/issue/"+url.PathEscape(key)+"/transitions", bytes.NewReader(body), nil); err != nil { - return fmt.Errorf("applying transition %q to %q: %w", id, key, err) + if err := c.do(ctx, http.MethodPost, "/issue/"+url.PathEscape(issueIDOrKey)+"/transitions", bytes.NewReader(body), nil); err != nil { + return fmt.Errorf("apply transition %q to %q: %w", id, issueIDOrKey, err) } return nil } diff --git a/internal/forge/jira/transition_test.go b/internal/forge/jira/transition_test.go index 36444e25ec..63407225f3 100644 --- a/internal/forge/jira/transition_test.go +++ b/internal/forge/jira/transition_test.go @@ -60,5 +60,5 @@ 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)}, ""), "encoding transition") + require.ErrorContains(t, c.ApplyTransition(context.Background(), "P-1", "1", map[string]any{"bad": make(chan int)}, ""), "encode transition") } diff --git a/internal/tracker/transition.go b/internal/tracker/transition.go index a206d0da00..99588b9eb8 100644 --- a/internal/tracker/transition.go +++ b/internal/tracker/transition.go @@ -29,7 +29,7 @@ func (o TransitionOptions) Validate() error { } } if selectors != 1 { - return fmt.Errorf("specify exactly one of --state, --transition, or --status") + 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) @@ -41,16 +41,16 @@ 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. type TransitionResult struct { - Changed bool `json:"changed"` - Transition string `json:"transition,omitempty"` - Status string `json:"status,omitempty"` + Changed bool + Transition string + Status string } // Transitioner is the optional tracker capability for workflow changes. Callers // authorize the target before invoking it. Implementations do not retry uncertain // writes; an error can mean the action succeeded but its response was lost. type Transitioner interface { - TransitionIssue(context.Context, string, int, TransitionOptions) (*TransitionResult, error) + TransitionIssue(ctx context.Context, project string, number int, opts TransitionOptions) (*TransitionResult, error) } var _ Transitioner = (*ForgeClient)(nil) @@ -88,8 +88,8 @@ func (c *ForgeClient) TransitionIssue(ctx context.Context, project string, numbe } type jiraTransitions interface { - ListTransitions(context.Context, string) ([]jira.Transition, error) - ApplyTransition(context.Context, string, string, map[string]any, string) error + ListTransitions(ctx context.Context, issueIDOrKey string) ([]jira.Transition, error) + ApplyTransition(ctx context.Context, issueIDOrKey, id string, fields map[string]any, comment string) error } // TransitionIssue resolves a unique currently available Jira action. Workflow @@ -109,6 +109,9 @@ func (c *JiraClient) TransitionIssue(ctx context.Context, project string, number return nil, wrapNotFound(err) } if issue.Fields.Status.StatusCategory.Key == "done" { + 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) @@ -131,7 +134,7 @@ 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)) + return nil, fmt.Errorf("ambiguous Jira transition on %q (%d matches); choose a unique transition name", key, len(matches)) } tr := matches[0] if tr.ID == "" { @@ -169,17 +172,22 @@ func transitionFields(tr jira.Transition, resolution string, comment Body) (map[ } fields["resolution"] = matches[0] } - for name, field := range tr.Fields { - if !field.Required || field.HasDefaultValue || (name == "comment" && comment != "") { - continue + 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 _, ok := fields[name]; ok { - continue + 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) } - if name == "resolution" { - return nil, fmt.Errorf("transition %q requires --resolution (an allowed resolution ID or name)", tr.Name) - } - return nil, fmt.Errorf("transition %q requires unsupported field %q; configure a transition with defaults or complete it in Jira", tr.Name, name) + fields["resolution"] = map[string]string{"id": value.ID} + } + if field := tr.Fields["comment"]; field.Required && !field.HasDefaultValue && comment == "" { + return nil, fmt.Errorf("transition %q requires a comment", tr.Name) } + // Other required fields may already be populated on the issue. Leave + // them unchanged and let Jira validate the transition against its current + // values and workflow rules, rather than rejecting metadata alone. return fields, nil } diff --git a/internal/tracker/transition_test.go b/internal/tracker/transition_test.go index 8a97322b25..6c6c4f5efb 100644 --- a/internal/tracker/transition_test.go +++ b/internal/tracker/transition_test.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "errors" + "fmt" "testing" "github.com/fullsend-ai/fullsend/internal/forge" @@ -50,7 +51,7 @@ func TestJiraTransition(t *testing.T) { {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"}, - {name: "required field", opts: TransitionOptions{Name: "Review"}, transitions: []jira.Transition{{ID: "21", Name: "Review", Fields: map[string]jira.TransitionField{"customfield_123": {Required: true}}}}, wantErr: "requires unsupported field"}, + {name: "required field", opts: TransitionOptions{Name: "Review"}, transitions: []jira.Transition{{ID: "21", Name: "Review", Fields: map[string]jira.TransitionField{"customfield_123": {Required: true}}}}}, {name: "invalid selectors", opts: TransitionOptions{Name: "Review", State: "closed"}, wantErr: "exactly one"}, } { t.Run(tt.name, func(t *testing.T) { @@ -83,7 +84,7 @@ func TestTransitionFields(t *testing.T) { }{ {"name", "Fixed", map[string]jira.TransitionField{"resolution": resolution}, ""}, {"id", "2", map[string]jira.TransitionField{"resolution": resolution}, ""}, - {"required", "", map[string]jira.TransitionField{"resolution": resolution}, "requires --resolution"}, + {"required", "", map[string]jira.TransitionField{"resolution": resolution}, "requires a resolution"}, {"invalid", "unknown", map[string]jira.TransitionField{"resolution": resolution}, "must match one"}, {"not on screen", "Fixed", nil, "does not accept"}, {"default", "", map[string]jira.TransitionField{"resolution": {Required: true, HasDefaultValue: true}}, ""}, @@ -192,10 +193,81 @@ func TestTransitionRequiredComment(t *testing.T) { c, err := NewJiraClient(f, "https://example.atlassian.net") require.NoError(t, err) _, err = c.TransitionIssue(context.Background(), "P", 1, TransitionOptions{Name: "Review"}) - require.ErrorContains(t, err, `requires unsupported field "comment"`) + require.ErrorContains(t, err, "requires a comment") assert.Zero(t, f.calls) _, err = c.TransitionIssue(context.Background(), "P", 1, TransitionOptions{Name: "Review", Comment: "Ready for review"}) require.NoError(t, err) assert.Equal(t, "Ready for review", f.comment) assert.Equal(t, 1, f.calls) } + +func TestJiraAlreadyClosedResolutionDoesNotWrite(t *testing.T) { + for _, comment := range []Body{"", "reason"} { + f := &transitionJira{FakeJiraClient: &FakeJiraClient{Issues: map[string]*jira.Issue{"P-1": {Fields: jira.IssueFields{Status: jira.Status{StatusCategory: jira.StatusCategory{Key: "done"}}}}}}} + c, err := NewJiraClient(f, "https://example.atlassian.net") + require.NoError(t, err) + _, err = c.TransitionIssue(context.Background(), "P", 1, TransitionOptions{State: "closed", Resolution: "Fixed", Comment: comment}) + require.ErrorContains(t, err, "already closed") + assert.Zero(t, f.calls) + assert.Empty(t, f.Comments) + } +} + +func TestTransitionAutomaticResolution(t *testing.T) { + for _, tt := range []struct { + name string + values []json.RawMessage + optional, defaulted bool + wantID string + wantErr bool + }{ + {name: "single", values: []json.RawMessage{json.RawMessage(`{"id":"1","name":"Fixed"}`)}, wantID: "1"}, + {name: "none", wantErr: true}, + {name: "multiple", values: []json.RawMessage{json.RawMessage(`{"id":"1"}`), json.RawMessage(`{"id":"2"}`)}, wantErr: true}, + {name: "malformed alternative", values: []json.RawMessage{json.RawMessage(`{"id":"1"}`), json.RawMessage(`null`)}, wantErr: true}, + {name: "malformed", values: []json.RawMessage{json.RawMessage(`"bad"`)}, wantErr: true}, + {name: "missing ID", values: []json.RawMessage{json.RawMessage(`{"name":"Fixed"}`)}, wantErr: true}, + {name: "empty ID", values: []json.RawMessage{json.RawMessage(`{"id":""}`)}, wantErr: true}, + {name: "whitespace ID", values: []json.RawMessage{json.RawMessage(`{"id":" "}`)}, wantErr: true}, + {name: "numeric ID", values: []json.RawMessage{json.RawMessage(`{"id":1}`)}, wantErr: true}, + {name: "optional", values: []json.RawMessage{json.RawMessage(`{"id":"1"}`)}, optional: true}, + {name: "default", values: []json.RawMessage{json.RawMessage(`{"id":"1"}`)}, defaulted: true}, + } { + 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, "", "") + if tt.wantErr { + require.ErrorContains(t, err, "requires a resolution") + return + } + require.NoError(t, err) + if tt.wantID != "" { + assert.Equal(t, map[string]string{"id": tt.wantID}, fields["resolution"]) + } else { + assert.Empty(t, fields) + } + }) + } +} + +func TestJiraRequiredFieldsValidatedByServer(t *testing.T) { + for _, field := range []string{"summary", "assignee", "customfield_123"} { + for _, serverErr := range []error{nil, errors.New("Jira API: 400: required field is empty")} { + t.Run(field+"/"+fmt.Sprint(serverErr), func(t *testing.T) { + f := &transitionJira{FakeJiraClient: &FakeJiraClient{}, transitions: []jira.Transition{{ID: "21", Name: "Review", Fields: map[string]jira.TransitionField{field: {Required: true}}}}, applyErr: serverErr} + c, err := NewJiraClient(f, "https://example.atlassian.net") + require.NoError(t, err) + _, err = c.TransitionIssue(context.Background(), "P", 1, TransitionOptions{Name: "Review", Comment: "Ready"}) + if serverErr != nil { + require.ErrorIs(t, err, serverErr) + } else { + require.NoError(t, err) + } + assert.Equal(t, 1, f.calls) + assert.Empty(t, f.fields) + assert.Equal(t, "Ready", f.comment) + assert.Empty(t, f.Comments) + }) + } + } +}