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/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/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..62d96530bc 100644 --- a/docs/guides/dev/cli-internals.md +++ b/docs/guides/dev/cli-internals.md @@ -175,12 +175,23 @@ fullsend │ │ ├── --keep-history # Append previous content as collapsed history (default true) │ │ ├── --only-if-exists # Update an existing marked comment, never create one │ │ └── --fullsend-dir # .fullsend config directory (resolves keep_history default) -│ └── link # Create a typed link between two issues (Jira only) -│ ├── --tracker # Tracker backend; github/gitlab return "not supported" -│ ├── --from # Source issue key (e.g. PROJ-123) -│ ├── --to # Target issue key (e.g. PROJ-456) -│ ├── --type # Link type name (e.g. Blocks), passed through verbatim -│ └── --fullsend-dir # .fullsend config directory (resolves default --tracker) +│ ├── link # Create a typed link between two issues (Jira only) +│ │ ├── --tracker # Tracker backend; github/gitlab return "not supported" +│ │ ├── --from # Source issue key (e.g. PROJ-123) +│ │ ├── --to # Target issue key (e.g. PROJ-456) +│ │ ├── --type # Link type name (e.g. Blocks), passed through verbatim +│ │ └── --fullsend-dir # .fullsend config directory (resolves default --tracker) +│ └── transition # Change issue lifecycle state (rejects GitHub PR numbers) +│ ├── --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 +│ ├── --transition # Exact Jira transition name +│ ├── --status # Exact Jira destination status +│ ├── --resolution # Jira resolution allowed by the transition +│ ├── --comment # Optional Markdown explanation +│ ├── --token # GitHub/GitLab token; Jira uses runner credentials +│ └── --fullsend-dir # Config directory (Jira connection and allowed targets) ├── post-review # Post sticky PR/MR review comments (formal review is best-effort) │ ├── --forge # Forge backend: github (default) or gitlab │ ├── --base-url # Forge instance URL (e.g. https://gitlab.example.com) @@ -920,7 +931,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..08df50d46e 100644 --- a/docs/guides/user/issues-commands.md +++ b/docs/guides/user/issues-commands.md @@ -2,8 +2,8 @@ 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 create`, `fullsend issues post-comment`, +`fullsend issues link`, and `fullsend issues transition`. ## When to use @@ -11,6 +11,8 @@ The built-in agent pipeline handles comment posting automatically for GitHub-sourced events and for Jira-sourced triage and code runs. Use these commands when: +- An agent needs to **close an issue** or execute a configured Jira workflow transition. + - A custom agent needs to post results back to **Jira** or **GitLab**. - An agent script needs to **read** issue content (title, body, labels, comments) from any tracker as structured JSON. @@ -44,7 +46,7 @@ tracker: `https://api.atlassian.com`. Issue links in the output use `base_url`. - `project` is the repository's primary project and the default `--project`. -- `issues create` may target only `project` or a project listed in +- `issues create` and `issues transition` may target only `project` or a project listed in `allowed_targets.projects`. Any other project is refused before Jira is called. @@ -291,6 +293,71 @@ created in the type's outward direction: the example above records that | `--token` | No | Rejected for Jira, which reads `FULLSEND_JIRA_TOKEN` or the OAuth client credentials | | `--fullsend-dir` | Jira | Path to `.fullsend` config directory. Supplies the default `--tracker` and the [Jira connection settings](#jira-connection-settings) | +## `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." +``` + +### Flags + +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`. | +| `--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. | +| `--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` +follow the connection and authentication rules above. Jira rejects `--token`; +credentials remain in the existing environment variables. `--number` must be +positive. GitHub pull request numbers are rejected before any write. Jira requires +its connection settings in the configuration directory. The target project must be +`tracker.jira.project` or listed in `tracker.jira.allowed_targets.projects`; +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 +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. +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 +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. + +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. + ## Config-based default tracker Set a default tracker in `.fullsend/config.yaml` to avoid passing diff --git a/docs/guides/user/jira-integration.md b/docs/guides/user/jira-integration.md index 0e16d720d6..2f30b45621 100644 --- a/docs/guides/user/jira-integration.md +++ b/docs/guides/user/jira-integration.md @@ -517,8 +517,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. Tracker-neutral transition discovery is - tracked in [#6704](https://github.com/fullsend-ai/fullsend/issues/6704). + 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 @@ -538,12 +539,13 @@ explicit `FULLSEND_TRACKER` or `ISSUE_URL` points somewhere else. Code stops if `actor.kind: bot`, so they do not dispatch agents again. See [How it works](#how-it-works). - **Credentials:** the triage and code harnesses map `FULLSEND_JIRA_TOKEN` and - `FULLSEND_JIRA_EMAIL` in `env.runner` for the runner-side post-scripts only. + `FULLSEND_JIRA_EMAIL` in `env.runner` for runner-side scripts only. The `jira-ro` provider reads `FULLSEND_JIRA_TOKEN` on the host, and the sandbox gets the 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, 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 @@ -1439,5 +1441,5 @@ 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 - [Enabling fullsend on private repositories](../infrastructure/private-repositories.md#private-jira-projects-need-a-private-repository) — why a private Jira project needs a private repository diff --git a/docs/reference/config-reference.md b/docs/reference/config-reference.md index 674acec46a..ebe08edf7a 100644 --- a/docs/reference/config-reference.md +++ b/docs/reference/config-reference.md @@ -431,12 +431,13 @@ 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 without them. `project` is the default `--project` of the issues commands. -`fullsend issues create` refuses any other Jira project unless it is listed +`fullsend issues create` and `fullsend issues transition` refuse any other Jira +project unless it is listed in `allowed_targets.projects`. See [Issue commands](../guides/user/issues-commands.md#jira-connection-settings). 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..bec7ef4231 --- /dev/null +++ b/internal/cli/issues_transition.go @@ -0,0 +1,122 @@ +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 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", + 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. + +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 +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 + } + if name == trackerJira { + settings, err := loadJiraTrackingSettings(cfg.fullsendDir, cfg.testConfigReader) + if err != nil { + return err + } + if err := checkJiraTargetProject(settings, project); 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(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 new file mode 100644 index 0000000000..b791e3b9fe --- /dev/null +++ b/internal/cli/issues_transition_test.go @@ -0,0 +1,148 @@ +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 + 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 +} + +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} + if name == "jira" { + cfg.project = "PROJ" + cfg.testConfigReader = jiraCreateConfig(t, "PROJ") + } + require.NoError(t, runIssuesTransition(context.Background(), cfg)) + assert.Equal(t, cfg.project, 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") } + +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, testConfigReader: jiraCreateConfig(t, "PROJ")} + require.NoError(t, runIssuesTransition(context.Background(), cfg)) + assert.JSONEq(t, tt.want, out.String()) + }) + } +} + +func TestRunIssuesTransitionJiraProjectAuthorization(t *testing.T) { + for _, tt := range []struct { + name, project string + allowed []string + denied bool + }{ + {name: "default"}, + {name: "primary", project: "PROJ"}, + {name: "primary case insensitive", project: "proj"}, + {name: "allowed target", project: "OTHER", allowed: []string{"OTHER"}}, + {name: "allowed case insensitive", project: "other", allowed: []string{"OTHER"}}, + {name: "denied", project: "OTHER", denied: true}, + } { + t.Run(tt.name, func(t *testing.T) { + f := &transitionTracker{} + var out bytes.Buffer + cfg := &issuesTransitionConfig{trackerName: "jira", project: tt.project, number: 1, opts: tracker.TransitionOptions{State: "closed"}, testClient: f, testWriter: &out, testConfigReader: jiraCreateConfig(t, "PROJ", tt.allowed...)} + err := runIssuesTransition(context.Background(), cfg) + if tt.denied { + require.ErrorContains(t, err, "allowed_targets") + assert.Empty(t, f.project) + assert.Empty(t, out.String()) + // Authorization must also precede constructing the authenticated client. + cfg.testClient = nil + require.ErrorContains(t, runIssuesTransition(context.Background(), cfg), "allowed_targets") + } else { + require.NoError(t, err) + want := tt.project + if want == "" { + want = "PROJ" + } + assert.Equal(t, want, f.project) + } + }) + } +} diff --git a/internal/cli/tracker_client.go b/internal/cli/tracker_client.go index a96273ad3c..f1ad626790 100644 --- a/internal/cli/tracker_client.go +++ b/internal/cli/tracker_client.go @@ -182,7 +182,7 @@ func resolveIssueProject(trackerName, project, fullsendDir string, testConfigRea // checkJiraTargetProject refuses a Jira project that is neither the // repository's primary project (tracker.jira.project) nor listed in // tracker.jira.allowed_targets.projects. It guards cross-project issue -// creation only. Jira project keys are case-insensitive, so the +// creation and transitions. Jira project keys are case-insensitive, so the // comparison is too. func checkJiraTargetProject(settings *config.JiraTrackingConfig, project string) error { if strings.EqualFold(project, settings.Project) { diff --git a/internal/forge/forge.go b/internal/forge/forge.go index f8f9c69e38..207832f582 100644 --- a/internal/forge/forge.go +++ b/internal/forge/forge.go @@ -654,6 +654,9 @@ type Annotation struct { // Issue represents a forge issue. type Issue struct { + // IsPullRequest identifies pull requests returned by GitHub's issues + // endpoint. Populated by GetIssue; issue lifecycle operations must reject them. + IsPullRequest bool // Number is the display number: GitHub's per-repo issue number or // GitLab's per-project IID. It is not a stable identity. Number int diff --git a/internal/forge/github/github.go b/internal/forge/github/github.go index 9dc8e54cf2..d3745d5469 100644 --- a/internal/forge/github/github.go +++ b/internal/forge/github/github.go @@ -3536,21 +3536,23 @@ func (c *LiveClient) GetIssue(ctx context.Context, owner, repo string, number in Labels []struct { Name string `json:"name"` } `json:"labels"` - State string `json:"state"` - StateReason string `json:"state_reason"` + State string `json:"state"` + StateReason string `json:"state_reason"` + PullRequest *struct{} `json:"pull_request"` } if err := decodeJSON(resp, &result); err != nil { return nil, fmt.Errorf("decode issue #%d: %w", number, err) } return &forge.Issue{ - ID: result.ID, - Number: result.Number, - Title: result.Title, - Body: result.Body, - URL: result.HTMLURL, - Labels: labelNames(result.Labels), - State: result.State, - StateReason: result.StateReason, + ID: result.ID, + Number: result.Number, + Title: result.Title, + Body: result.Body, + URL: result.HTMLURL, + Labels: labelNames(result.Labels), + State: result.State, + StateReason: result.StateReason, + IsPullRequest: result.PullRequest != nil, }, nil } diff --git a/internal/forge/github/github_test.go b/internal/forge/github/github_test.go index 6a143b49af..fdb089d101 100644 --- a/internal/forge/github/github_test.go +++ b/internal/forge/github/github_test.go @@ -7965,3 +7965,26 @@ func TestGetRepoVariableInfo(t *testing.T) { }) } } + +func TestGetIssuePullRequestMarker(t *testing.T) { + for _, tt := range []struct { + name, payload string + want bool + }{ + {"issue", `{"number":1,"state":"open"}`, false}, + {"null", `{"number":1,"state":"open","pull_request":null}`, false}, + {"pull request", `{"number":1,"state":"open","pull_request":{"url":"https://api.github.com/repos/o/r/pulls/1"}}`, true}, + {"empty marker", `{"number":1,"state":"closed","pull_request":{}}`, true}, + } { + t.Run(tt.name, func(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + assert.Equal(t, "/repos/o/r/issues/1", r.URL.Path) + _, _ = w.Write([]byte(tt.payload)) + })) + defer srv.Close() + issue, err := newTestClient(t, srv).GetIssue(context.Background(), "o", "r", 1) + require.NoError(t, err) + assert.Equal(t, tt.want, issue.IsPullRequest) + }) + } +} diff --git a/internal/forge/jira/transition.go b/internal/forge/jira/transition.go new file mode 100644 index 0000000000..1ba12dda5c --- /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, issueIDOrKey string) ([]Transition, error) { + var result struct { + Transitions []Transition `json:"transitions"` + } + err := c.do(ctx, http.MethodGet, "/issue/"+url.PathEscape(issueIDOrKey)+"/transitions?expand=transitions.fields", nil, &result) + if err != nil { + 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, 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"` + 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("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("encode transition: %w", 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 new file mode 100644 index 0000000000..63407225f3 --- /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)}, ""), "encode transition") +} diff --git a/internal/tracker/transition.go b/internal/tracker/transition.go new file mode 100644 index 0000000000..c7223a1452 --- /dev/null +++ b/internal/tracker/transition.go @@ -0,0 +1,196 @@ +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 lifecycle state, transition name, or target 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 + 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(ctx context.Context, project string, number int, opts 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) + } + if issue.IsPullRequest { + return nil, fmt.Errorf("%s#%d is a pull request, not an issue; refusing to transition it", project, number) + } + 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(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 +// 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.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 &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] + } + 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) + } + 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_github_contract_test.go b/internal/tracker/transition_github_contract_test.go new file mode 100644 index 0000000000..4c008a03d3 --- /dev/null +++ b/internal/tracker/transition_github_contract_test.go @@ -0,0 +1,42 @@ +package tracker_test + +import ( + "context" + "fmt" + "net/http" + "net/http/httptest" + "testing" + + "github.com/fullsend-ai/fullsend/internal/forge/github" + "github.com/fullsend-ai/fullsend/internal/tracker" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// Exercise the real decoder and tracker together: GitHub's issue endpoint +// returns PRs too, but this command must never close or comment on one. +func TestGitHubTransitionRejectsPRWithoutWrites(t *testing.T) { + for _, state := range []string{"open", "closed"} { + for _, comment := range []tracker.Body{"", "Completed"} { + t.Run(state+"/"+string(comment), func(t *testing.T) { + var methods []string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + methods = append(methods, r.Method) + if r.Method == http.MethodGet { + assert.Equal(t, "/repos/owner/repo/issues/42", r.URL.Path) + _, _ = fmt.Fprintf(w, `{"number":42,"state":%q,"pull_request":{"url":"https://api.github.com/repos/owner/repo/pulls/42"}}`, state) + return + } + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{}`)) + })) + defer srv.Close() + client := tracker.NewForgeClient(github.New("test-token").WithBaseURL(srv.URL)) + result, err := client.TransitionIssue(context.Background(), "owner/repo", 42, tracker.TransitionOptions{State: "closed", Comment: comment}) + require.ErrorContains(t, err, "pull request, not an issue") + assert.Nil(t, result) + assert.Equal(t, []string{http.MethodGet}, methods) + }) + } + } +} diff --git a/internal/tracker/transition_test.go b/internal/tracker/transition_test.go new file mode 100644 index 0000000000..d36f76f1e6 --- /dev/null +++ b/internal/tracker/transition_test.go @@ -0,0 +1,289 @@ +package tracker + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "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}}}}}, + {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 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}}, ""}, + {"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 + isPullRequest bool + 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, IsPullRequest: f.isPullRequest}, 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 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) + }) + } + } +} + +func TestForgeTransitionRejectsPullRequests(t *testing.T) { + for _, state := range []string{"open", "closed"} { + for _, comment := range []Body{"", "Completed"} { + t.Run(state+"/"+string(comment), func(t *testing.T) { + f := &transitionForge{state: state, isPullRequest: true} + result, err := NewForgeClient(f).TransitionIssue(context.Background(), "owner/repo", 1, TransitionOptions{State: "closed", Comment: comment}) + require.ErrorContains(t, err, "pull request, not an issue") + assert.Nil(t, result) + assert.Zero(t, f.closes) + assert.Zero(t, f.comments) + }) + } + } +}