From cf628ed797112bacc4392bb448fe58bafef2d66b Mon Sep 17 00:00:00 2001 From: fullsend-code <278716306+fullsend-ai-coder[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:46:08 +0000 Subject: [PATCH 1/2] refactor(#9883): let the Jira poller take a set of project keys The poller assumed one Jira project: Options.JiraProject, one role roster per cycle, and a search JQL the CLI scoped beforehand. This change replaces that with an explicit project set. The config shape does not change: tracker.jira.project is passed as a one-item set. - Options.JiraProjects replaces JiraProject. Options.JQL is now the predicate before scoping. Run checks the set (non-empty, valid keys, no duplicates) and the predicate's parentheses before the auth preflight, so a bad scope makes no Jira request. - The poller scopes every search itself with config.ScopeJQLToProjects, keeping a trailing ORDER BY last. A one-item set gives exactly the JQL PollJQL built before, so the CLI path sends unchanged JQL. Two or more projects use `project in (...)`. - Role rosters are kept per project and loaded lazily. Each issue resolves its actor through its own project's roster. A load failure for any project still fails the cycle with no checkpoint advanced. - The set is searched once, so M, N and pagination apply across it. Repeated rows of the same issue (same ID, or same key when the ID is missing) are dropped before processing. - Key validation uses config.ValidJiraProjectKey, the same rule tracker.jira.project uses. The poller's own default predicate is now config.DefaultJiraPollQuery. Note: pre-commit could not fetch its hook repos (no network). gofmt, go vet ./..., lint-broken-symlinks and a whitespace check passed when run directly. semgrep-scan skipped because its ruleset could not be downloaded. gitleaks was covered by scan-secrets. Closes #9883 Co-Authored-By: Claude Opus 5.5 --- internal/cli/jira_lifecycle_test.go | 6 +- internal/cli/poll.go | 17 +- internal/cli/poll_jira_config_test.go | 17 +- internal/cli/poll_jira_gitlab_test.go | 2 +- internal/cli/poll_test.go | 14 +- internal/config/issue_targets.go | 38 +- internal/config/jira_tracking_test.go | 19 + internal/jirapoll/auth.go | 112 +++-- internal/jirapoll/auth_test.go | 44 +- internal/jirapoll/convert.go | 20 +- internal/jirapoll/convert_test.go | 72 +-- internal/jirapoll/gitlab_target_test.go | 12 +- internal/jirapoll/issue_type_test.go | 2 +- internal/jirapoll/multi_project_test.go | 443 ++++++++++++++++++ internal/jirapoll/poller.go | 191 +++++--- internal/jirapoll/poller_invalid_id_test.go | 55 ++- internal/jirapoll/poller_test.go | 286 +++++------ internal/jirapoll/types.go | 4 +- pkg/behaviourtest/steps/jirapoll.go | 10 +- pkg/behaviourtest/steps/jirapoll_transport.go | 12 +- 20 files changed, 990 insertions(+), 386 deletions(-) create mode 100644 internal/jirapoll/multi_project_test.go diff --git a/internal/cli/jira_lifecycle_test.go b/internal/cli/jira_lifecycle_test.go index 4b77d085ce..6f3a3cd603 100644 --- a/internal/cli/jira_lifecycle_test.go +++ b/internal/cli/jira_lifecycle_test.go @@ -252,9 +252,9 @@ func (l *jiraLifecycle) comment(accountID, displayName, body string) { // runJiraPoll for GitHub and runJiraPollGitLab for GitLab. func (l *jiraLifecycle) options() jirapoll.Options { opts := jirapoll.Options{ - TargetRepo: l.repo, - JiraBaseURL: lifecycleJiraBaseURL, - JiraProject: "PROJ", + TargetRepo: l.repo, + JiraBaseURL: lifecycleJiraBaseURL, + JiraProjects: []string{"PROJ"}, } if l.host == jirapoll.TargetForgeGitLab { opts.TargetForge = jirapoll.TargetForgeGitLab diff --git a/internal/cli/poll.go b/internal/cli/poll.go index 846158fc9b..8d08ac14e8 100644 --- a/internal/cli/poll.go +++ b/internal/cli/poll.go @@ -343,15 +343,15 @@ type jiraPollSettings struct { baseURL string // tracker.jira.base_url: the Jira site URL apiURL string // tracker.jira.api_url, or its default project string // tracker.jira.project - jql string // tracker.jira.poll.query (or the default) scoped to project + query string // tracker.jira.poll.query, or the default; the poller scopes it to project enabled bool // tracker.jira.poll.enabled is true } // loadJiraPollSettings reads the Jira site, API gateway, project, and poll // settings from tracker.jira in the effective config.yaml. The config is // the only source of these settings: base_url and project are required, -// api_url and poll.query fall back to their defaults, and the JQL is always -// the query scoped to the project as `project = "" AND ()` +// api_url and poll.query fall back to their defaults, and the poller always +// scopes the query to the project as `project = "" AND ()` // with any ORDER BY last. The removed --jira-url, --jira-project, and --jql // flags are rejected with a pointer to the config fields, and environment // variables such as JIRA_BASE_URL are not read. @@ -385,7 +385,7 @@ func loadJiraPollSettings(fullsendDir, jiraURL, jiraProject, jql string) (jiraPo baseURL: jiraCfg.BaseURL, apiURL: jiraCfg.EffectiveAPIURL(), project: jiraCfg.Project, - jql: jiraCfg.PollJQL(), + query: jiraCfg.PollQuery(), enabled: jiraCfg.PollEnabled(), }, nil } @@ -573,9 +573,12 @@ func jiraPollOptions(args jiraPollArgs, matcher *celMatcher, getenv func(string) return jirapoll.Options{ TargetRepo: args.targetRepo, JiraBaseURL: args.jira.baseURL, - JiraProject: args.jira.project, - JQL: args.jira.jql, - OutputPath: args.outputPath, + // tracker.jira.project is the poller's one-item project set; the + // poller scopes the query to it, so the search JQL is + // config.JiraTrackingConfig.PollJQL's. + JiraProjects: []string{args.jira.project}, + JQL: args.jira.query, + OutputPath: args.outputPath, Authorization: jiraPollAuthorization(matcher.jiraAuth, getenv), } diff --git a/internal/cli/poll_jira_config_test.go b/internal/cli/poll_jira_config_test.go index b190d99e61..7039bab594 100644 --- a/internal/cli/poll_jira_config_test.go +++ b/internal/cli/poll_jira_config_test.go @@ -50,9 +50,16 @@ func TestLoadJiraPollSettings_ReadsConfig(t *testing.T) { baseURL: "https://example.atlassian.net", apiURL: "https://gateway.example.com", project: "PROJ", - jql: `project = "PROJ" AND (labels = "fullsend") ORDER BY updated DESC`, + query: `labels = "fullsend" ORDER BY updated DESC`, enabled: true, }, got) + + // The poller gets the project as a one-item set and the query before + // scoping, and scopes it to exactly the JQL PollJQL builds. + opts := jiraPollOptions(jiraPollArgs{jira: got}, &celMatcher{}, noJiraEnv) + assert.Equal(t, []string{"PROJ"}, opts.JiraProjects) + assert.Equal(t, `project = "PROJ" AND (labels = "fullsend") ORDER BY updated DESC`, + config.ScopeJQLToProjects(opts.JiraProjects, opts.JQL)) } func TestLoadJiraPollSettings_Defaults(t *testing.T) { @@ -60,7 +67,9 @@ func TestLoadJiraPollSettings_Defaults(t *testing.T) { got, err := loadJiraPollSettings(dir, "", "", "") require.NoError(t, err) assert.Equal(t, config.DefaultJiraAPIURL, got.apiURL) - assert.Equal(t, `project = "PROJ" AND (statusCategory != Done) ORDER BY updated DESC`, got.jql) + assert.Equal(t, config.DefaultJiraPollQuery, got.query) + assert.Equal(t, `project = "PROJ" AND (statusCategory != Done) ORDER BY updated DESC`, + config.ScopeJQLToProjects([]string{got.project}, got.query)) assert.False(t, got.enabled, "an omitted poll mapping leaves polling disabled") } @@ -68,7 +77,9 @@ func TestLoadJiraPollSettings_QueryWithoutOrderBy(t *testing.T) { dir := writeJiraPollConfig(t, "tracker:\n jira:\n base_url: https://example.atlassian.net\n project: PROJ\n poll:\n enabled: false\n query: 'labels = a OR labels = b'\n") got, err := loadJiraPollSettings(dir, "", "", "") require.NoError(t, err) - assert.Equal(t, `project = "PROJ" AND (labels = a OR labels = b)`, got.jql, + assert.Equal(t, `labels = a OR labels = b`, got.query) + assert.Equal(t, `project = "PROJ" AND (labels = a OR labels = b)`, + config.ScopeJQLToProjects([]string{got.project}, got.query), "an OR query stays inside the project scope") assert.False(t, got.enabled) } diff --git a/internal/cli/poll_jira_gitlab_test.go b/internal/cli/poll_jira_gitlab_test.go index 5cda72b1ed..c400d10552 100644 --- a/internal/cli/poll_jira_gitlab_test.go +++ b/internal/cli/poll_jira_gitlab_test.go @@ -22,7 +22,7 @@ import ( ) func TestValidateJiraGitLabPollArgs(t *testing.T) { - settings := jiraPollSettings{baseURL: "https://acme.atlassian.net", project: "PROJ", jql: `project = "PROJ"`, enabled: true} + settings := jiraPollSettings{baseURL: "https://acme.atlassian.net", project: "PROJ", query: "statusCategory != Done", enabled: true} base := jiraPollGitLabFlags{ projectPath: "group/sub/project", gitlabURL: "https://gitlab.com", diff --git a/internal/cli/poll_test.go b/internal/cli/poll_test.go index d07baa6fef..cd7c4da358 100644 --- a/internal/cli/poll_test.go +++ b/internal/cli/poll_test.go @@ -158,7 +158,7 @@ trigger: | func TestValidateJiraPollArgs(t *testing.T) { fullsendDir := t.TempDir() - settings := jiraPollSettings{baseURL: "https://acme.atlassian.net", project: "PROJ", jql: `project = "PROJ"`, enabled: true} + settings := jiraPollSettings{baseURL: "https://acme.atlassian.net", project: "PROJ", query: config.DefaultJiraPollQuery, enabled: true} tests := []struct { name string @@ -783,16 +783,16 @@ authorization: require.NoError(t, err) args := jiraPollArgs{ - jira: jiraPollSettings{baseURL: "https://jira.example.com", apiURL: config.DefaultJiraAPIURL, project: "PROJ", jql: "project = PROJ", enabled: true}, + jira: jiraPollSettings{baseURL: "https://jira.example.com", apiURL: config.DefaultJiraAPIURL, project: "PROJ", query: `labels = "fullsend"`, enabled: true}, targetRepo: "group/sub/repo", outputPath: "out.json", fullsendDir: dir, } opts := jiraPollOptions(args, m, noJiraEnv) assert.Equal(t, jirapoll.Options{ - TargetRepo: "group/sub/repo", - JiraBaseURL: "https://jira.example.com", - JiraProject: "PROJ", - JQL: "project = PROJ", - OutputPath: "out.json", + TargetRepo: "group/sub/repo", + JiraBaseURL: "https://jira.example.com", + JiraProjects: []string{"PROJ"}, + JQL: `labels = "fullsend"`, + OutputPath: "out.json", Authorization: jirapoll.Authorization{ Configured: true, Write: jirapoll.ActorList{Groups: []string{"devs"}}, diff --git a/internal/config/issue_targets.go b/internal/config/issue_targets.go index 84cfee510f..8679f8f823 100644 --- a/internal/config/issue_targets.go +++ b/internal/config/issue_targets.go @@ -229,10 +229,29 @@ var jqlOrderByRe = regexp.MustCompile(`(?i)\border\s+by\b`) // value is not split. An empty predicate (a query that is only an // ORDER BY clause) yields `project = ""` plus the ORDER BY. func ScopeJQLToProject(project, query string) string { + return ScopeJQLToProjects([]string{project}, query) +} + +// ScopeJQLToProjects scopes query to exactly projects the way +// ScopeJQLToProject scopes it to one project. A one-item set yields the +// same JQL as ScopeJQLToProject; a larger set uses +// `project in ("", "") AND ()`. The caller validates the +// keys and the predicate's parentheses (see ValidJiraProjectKey and +// JQLParensBalanced): this function only formats. +func ScopeJQLToProjects(projects []string, query string) string { predicate, orderBy := splitJQLOrderBy(query) predicate = strings.TrimSpace(predicate) - // Quote the key so a reserved-word key (AND, OR, IN) stays a value. - scoped := fmt.Sprintf("project = %q", project) + // Quote each key so a reserved-word key (AND, OR, IN) stays a value. + quoted := make([]string, len(projects)) + for i, project := range projects { + quoted[i] = fmt.Sprintf("%q", project) + } + var scoped string + if len(quoted) == 1 { + scoped = "project = " + quoted[0] + } else { + scoped = "project in (" + strings.Join(quoted, ", ") + ")" + } if predicate != "" { scoped += " AND (" + predicate + ")" } @@ -463,6 +482,12 @@ func cloneTracking(src *TrackingConfig) *TrackingConfig { // followed by uppercase letters, digits, or underscores. var jiraProjectKeyRe = regexp.MustCompile(`^[A-Z][A-Z0-9_]*$`) +// ValidJiraProjectKey reports whether key is a Jira project key in the +// form tracker.jira.project accepts (see jiraProjectKeyRe). +func ValidJiraProjectKey(key string) bool { + return jiraProjectKeyRe.MatchString(key) +} + // validPathSegments reports whether p is a slash-separated path with at // least minSegments segments and no empty segment. func validPathSegments(p string, minSegments int) bool { @@ -561,16 +586,17 @@ func (j *JiraTrackingConfig) ValidateConnection() error { if !jiraProjectKeyRe.MatchString(j.Project) { return fmt.Errorf("tracker.jira: project %q must be a Jira project key (for example PROJ)", j.Project) } - if j.Poll != nil && !jqlParensBalanced(j.Poll.Query) { + if j.Poll != nil && !JQLParensBalanced(j.Poll.Query) { return fmt.Errorf("tracker.jira: poll.query has unbalanced parentheses: the query is wrapped in parentheses to scope it to the project") } return nil } -// jqlParensBalanced reports whether the parentheses of query, ignoring +// JQLParensBalanced reports whether the parentheses of query, ignoring // those inside quoted strings, are balanced and never close before they -// open. -func jqlParensBalanced(query string) bool { +// open. A query that passes cannot close the parenthesis ScopeJQLToProjects +// wraps it in, so it cannot widen the project scope. +func JQLParensBalanced(query string) bool { quoted := quotedRanges(query) depth := 0 for i := 0; i < len(query); i++ { diff --git a/internal/config/jira_tracking_test.go b/internal/config/jira_tracking_test.go index 8194b105ac..6745d5c1f3 100644 --- a/internal/config/jira_tracking_test.go +++ b/internal/config/jira_tracking_test.go @@ -207,6 +207,25 @@ func TestScopeJQLToProject(t *testing.T) { } } +func TestScopeJQLToProjects(t *testing.T) { + query := `labels = a OR project = OTHER ORDER BY updated DESC` + assert.Equal(t, ScopeJQLToProject("PROJ", query), ScopeJQLToProjects([]string{"PROJ"}, query), + "a one-item set scopes exactly as ScopeJQLToProject") + assert.Equal(t, `project in ("ALPHA", "BETA") AND (labels = a OR project = OTHER) ORDER BY updated DESC`, + ScopeJQLToProjects([]string{"ALPHA", "BETA"}, query)) + assert.Equal(t, `project in ("AND", "OR") ORDER BY key`, ScopeJQLToProjects([]string{"AND", "OR"}, "ORDER BY key"), + "reserved-word keys stay quoted values") +} + +func TestValidJiraProjectKey(t *testing.T) { + for _, key := range []string{"P", "PROJ", "MY_PROJ", "ABC123"} { + assert.True(t, ValidJiraProjectKey(key), key) + } + for _, key := range []string{"", "proj", "1PROJ", "_PROJ", "PR OJ", `PROJ"`} { + assert.False(t, ValidJiraProjectKey(key), key) + } +} + func TestScopeJQLToProject_QuotesReservedWordKey(t *testing.T) { for _, key := range []string{"AND", "OR", "IN"} { assert.Equal(t, `project = "`+key+`" AND (labels = a)`, ScopeJQLToProject(key, "labels = a")) diff --git a/internal/jirapoll/auth.go b/internal/jirapoll/auth.go index 175ecf4624..b17fe5a6e1 100644 --- a/internal/jirapoll/auth.go +++ b/internal/jirapoll/auth.go @@ -84,51 +84,56 @@ func (p *Poller) roleSourceFor(event JiraEvent) roleSource { return roleNotResolved } -// roleLoadError marks a failure to load the project role roster. Run fails +// roleLoadError marks a failure to load a project role roster. Run fails // the whole cycle on it, without committing any checkpoint, instead of // failing only the issue being processed. type roleLoadError struct { - err error + project string + err error } func (e *roleLoadError) Error() string { return e.err.Error() } func (e *roleLoadError) Unwrap() error { return e.err } -// ensureRoleStructure loads the project role roster once per cycle, the -// first time an event needs it. A load failure is returned as a -// *roleLoadError: with no roster every actor would resolve to "external", -// write-gated events would route to nothing, and the checkpoint would still -// advance past them, permanently dropping real events over a transient -// roles-API error. (A missing project key is different: JQL-only mode is -// documented as always-external, so that path proceeds.) -func (p *Poller) ensureRoleStructure(ctx context.Context) error { - if p.rolesLoaded { - return nil +// ensureRoleStructure returns project's role roster, loading it once per +// cycle the first time an event of that project needs it. It returns nil, +// and loads nothing, for a project outside Options.JiraProjects: the +// search is scoped to the set, so such an issue (for example one moved +// between projects) gets no project role and resolveRole fails it closed +// to "external". A load failure is returned as a *roleLoadError: with no +// roster every actor would resolve to "external", write-gated events would +// route to nothing, and the checkpoint would still advance past them, +// permanently dropping real events over a transient roles-API error. +func (p *Poller) ensureRoleStructure(ctx context.Context, project string) (*projectRoster, error) { + if roster, ok := p.rosters[project]; ok { + return roster, nil } - if p.opts.JiraProject == "" { - log.Printf("WARNING: no Jira project key set, cannot resolve actor roles (defaulting to external)") - p.rolesLoaded = true - return nil + if !slices.Contains(p.opts.JiraProjects, project) { + return nil, nil } - if err := p.loadRoleStructure(ctx, p.opts.JiraProject); err != nil { - return &roleLoadError{err: err} + roster, err := p.loadRoleStructure(ctx, project) + if err != nil { + return nil, &roleLoadError{project: project, err: err} } - p.rolesLoaded = true - return nil + if p.rosters == nil { + p.rosters = make(map[string]*projectRoster) + } + p.rosters[project] = roster + return roster, nil } // resolveEventRoles fetches what toNormalizedEvent needs to resolve each -// event's actor.role: the project role roster, only when some event uses -// it, and the group memberships of actors that the jira lists or the -// roster's role-assigned groups may match. Group memberships are cached -// per actor for the cycle. +// event's actor.role: the role roster of the event's issue project, only +// when some event of that project uses it, and the group memberships of +// actors that the jira lists or the roster's role-assigned groups may +// match. Group memberships are cached per actor for the cycle. // // Any group lookup failure, partial or total, fails this issue so it is // retried next cycle, rather than dispatching a role downgraded by the // missing membership. func (p *Poller) resolveEventRoles(ctx context.Context, events []JiraEvent) error { - var listActors, roleActors []string - needRoster := false + var listActors, rosterProjects []string + roleActors := make(map[string][]string) // issue project → actors resolved through its roster for _, event := range events { // An event that fails validation is skipped after this, so it must // not make the cycle depend on the roster or group lookups. Ask @@ -139,18 +144,18 @@ func (p *Poller) resolveEventRoles(ctx context.Context, events []JiraEvent) erro continue } aid := actorID(event) - source := p.roleSourceFor(event) - if source == roleFromProjectRoles { - needRoster = true - } - switch source { + switch p.roleSourceFor(event) { case roleFromLists: if p.listsNeedGroups(aid) && !slices.Contains(listActors, aid) { listActors = append(listActors, aid) } case roleFromProjectRoles: - if !slices.Contains(roleActors, aid) { - roleActors = append(roleActors, aid) + project := issueProjectKey(event.IssueKey) + if _, ok := roleActors[project]; !ok { + rosterProjects = append(rosterProjects, project) + } + if !slices.Contains(roleActors[project], aid) { + roleActors[project] = append(roleActors[project], aid) } } } @@ -159,27 +164,30 @@ func (p *Poller) resolveEventRoles(ctx context.Context, events []JiraEvent) erro return fmt.Errorf("resolve jira list groups: %w", err) } - if !needRoster { - return nil - } - if err := p.ensureRoleStructure(ctx); err != nil { - return err - } - if p.opts.JiraProject == "" || len(p.roleGroups) == 0 { - return nil - } - // Check groups for actors below the highest possible priority - // (Administrators). A direct role assignment doesn't rule out also - // belonging to a higher-priority group, so every such actor is - // checked, not just ones with no role yet. roleGroupsChecked skips - // actors already resolved via groups earlier this cycle. - var candidates []string - for _, aid := range roleActors { - if !p.roleGroupsChecked[aid] && jira.RolePriority(p.roleMembership[aid]) < maxRolePriority { - candidates = append(candidates, aid) + for _, project := range rosterProjects { + roster, err := p.ensureRoleStructure(ctx, project) + if err != nil { + return err + } + if roster == nil || len(roster.groups) == 0 { + continue + } + // Check groups for actors below the highest possible priority + // (Administrators). A direct role assignment doesn't rule out also + // belonging to a higher-priority group, so every such actor is + // checked, not just ones with no role yet. groupsChecked skips + // actors already resolved via this project's groups this cycle. + var candidates []string + for _, aid := range roleActors[project] { + if !roster.groupsChecked[aid] && jira.RolePriority(roster.membership[aid]) < maxRolePriority { + candidates = append(candidates, aid) + } + } + if err := p.resolveActorRoles(ctx, roster, candidates); err != nil { + return err } } - return p.resolveActorRoles(ctx, candidates) + return nil } // listsNeedGroups reports whether resolving aid against the jira lists diff --git a/internal/jirapoll/auth_test.go b/internal/jirapoll/auth_test.go index 16a2c44015..dd5b00c06c 100644 --- a/internal/jirapoll/auth_test.go +++ b/internal/jirapoll/auth_test.go @@ -113,7 +113,7 @@ func authTestPoller(mc *mockClient, m EventMatcher, auth Authorization) *Poller return newTestPoller(mc, m, Options{ TargetRepo: "acme/platform", JiraBaseURL: "https://acme.atlassian.net", - JiraProject: "PROJ", + JiraProjects: []string{"PROJ"}, N: 50, Authorization: auth, }) @@ -606,10 +606,10 @@ func TestRunAuth_ListsAuthorizeIssueOpened(t *testing.T) { func TestResolveRole_ListsApplyToNonCommandEvents(t *testing.T) { p := &Poller{ opts: Options{ - JiraProject: "PROJ", + JiraProjects: []string{"PROJ"}, Authorization: Authorization{Configured: true, Triage: ActorList{Accounts: []string{"t"}}}, }, - roleMembership: map[string]string{"t": "Administrators"}, + rosters: testRosters("PROJ", map[string]string{"t": "Administrators"}), } opened := JiraEvent{Type: "opened", IssueKey: "PROJ-1", Reporter: jira.User{AccountID: "t"}} if got := p.toNormalizedEvent(opened).Actor.Role; got != "triage" { @@ -664,22 +664,42 @@ func TestRoleSourceFor(t *testing.T) { } } -func TestEnsureRoleStructure_NoProjectKey(t *testing.T) { +func TestEnsureRoleStructure_ProjectOutsideSet(t *testing.T) { mc := newMockClient() - p := &Poller{client: mc} - if err := p.ensureRoleStructure(context.Background()); err != nil { - t.Fatalf("ensureRoleStructure() error: %v", err) - } - if err := p.ensureRoleStructure(context.Background()); err != nil { - t.Fatalf("ensureRoleStructure() second call error: %v", err) + p := &Poller{client: mc, opts: Options{JiraProjects: []string{"PROJ"}}} + for _, project := range []string{"OTHER", ""} { + roster, err := p.ensureRoleStructure(context.Background(), project) + if err != nil { + t.Fatalf("ensureRoleStructure(%q) error: %v", project, err) + } + if roster != nil { + t.Errorf("ensureRoleStructure(%q) returned a roster for a project outside the set", project) + } } if mc.roleActorsCalls != 0 { - t.Errorf("GetProjectRoleActors called %d times without a project key, want 0", mc.roleActorsCalls) + t.Errorf("GetProjectRoleActors called %d times for projects outside the set, want 0", mc.roleActorsCalls) + } +} + +func TestEnsureRoleStructure_LoadsOncePerProject(t *testing.T) { + mc := newMockClient() + p := &Poller{client: mc, opts: Options{JiraProjects: []string{"PROJ"}}} + for range 2 { + roster, err := p.ensureRoleStructure(context.Background(), "PROJ") + if err != nil { + t.Fatalf("ensureRoleStructure() error: %v", err) + } + if roster == nil { + t.Fatal("ensureRoleStructure() returned no roster for a project in the set") + } + } + if mc.roleActorsCalls != 1 { + t.Errorf("GetProjectRoleActors called %d times, want 1 per project per cycle", mc.roleActorsCalls) } } func TestRoleLoadError(t *testing.T) { - err := &roleLoadError{err: errAdminOnly} + err := &roleLoadError{project: "PROJ", err: errAdminOnly} if err.Error() != errAdminOnly.Error() { t.Errorf("Error() = %q", err.Error()) } diff --git a/internal/jirapoll/convert.go b/internal/jirapoll/convert.go index 522d7dd8ee..0e9c5bd563 100644 --- a/internal/jirapoll/convert.go +++ b/internal/jirapoll/convert.go @@ -261,13 +261,14 @@ func extractCommand(body string) (command, instruction string) { // "none"), no resolution ("none", for label-added events the dispatch gate // authorizes by Jira's Edit Issues permission), or the Jira project role. // -// roleMembership is loaded once per cycle for a single p.opts.JiraProject. -// The poller query is scoped to that project, but as defensive validation -// (for example a misconfigured poll.query, or an issue moved between -// projects) an actor's project role is only honored for issues in the -// configured project; anything else fails closed to "external" rather than -// leaking a role granted in one project onto an issue in another (see PR -// #5778 review). +// A project role comes only from the roster of the event's own issue +// project (the project part of its key), loaded once per cycle for each +// project of p.opts.JiraProjects that needs it. The search is scoped to +// that set, but as defensive validation (for example an issue moved +// between projects) an issue whose project has no roster this cycle, +// including any project outside the set (ensureRoleStructure never loads +// one), fails closed to "external" rather than leaking a role granted in +// one project onto an issue in another (see PR #5778 review). func (p *Poller) resolveRole(event JiraEvent) string { aid := actorID(event) if aid == "" { @@ -279,10 +280,11 @@ func (p *Poller) resolveRole(event JiraEvent) string { case roleFromLists: return p.listRole(aid) } - if p.opts.JiraProject != "" && issueProjectKey(event.IssueKey) != p.opts.JiraProject { + roster, ok := p.rosters[issueProjectKey(event.IssueKey)] + if !ok || roster == nil { return "external" } - roleName, ok := p.roleMembership[aid] + roleName, ok := roster.membership[aid] if !ok { return "external" } diff --git a/internal/jirapoll/convert_test.go b/internal/jirapoll/convert_test.go index 46a6499ff9..8ae16d1e37 100644 --- a/internal/jirapoll/convert_test.go +++ b/internal/jirapoll/convert_test.go @@ -28,9 +28,9 @@ func TestToNormalizedEvent_MatchesFixture(t *testing.T) { TargetRepo: "acme/platform", JiraBaseURL: "https://acme.atlassian.net", }, - roleMembership: map[string]string{ + rosters: testRosters("PROJ", map[string]string{ "557058:abc123def456": "Developers", - }, + }), } event := JiraEvent{ @@ -116,9 +116,9 @@ func TestToNormalizedEvent_CommentWithSlashCommand(t *testing.T) { TargetRepo: "acme/platform", JiraBaseURL: "https://acme.atlassian.net", }, - roleMembership: map[string]string{ + rosters: testRosters("PROJ", map[string]string{ "user1": "Developers", - }, + }), } event := JiraEvent{ @@ -185,9 +185,9 @@ func TestToNormalizedEvent_CommentWithoutSlashCommand(t *testing.T) { TargetRepo: "acme/platform", JiraBaseURL: "https://acme.atlassian.net", }, - roleMembership: map[string]string{ + rosters: testRosters("PROJ", map[string]string{ "user1": "Developers", - }, + }), } event := JiraEvent{ @@ -224,9 +224,9 @@ func TestToNormalizedEvent_LabelAdded(t *testing.T) { TargetRepo: "acme/platform", JiraBaseURL: "https://acme.atlassian.net", }, - roleMembership: map[string]string{ + rosters: testRosters("PROJ", map[string]string{ "user1": "Developers", - }, + }), } event := JiraEvent{ @@ -271,7 +271,7 @@ func TestToNormalizedEvent_BotActor(t *testing.T) { TargetRepo: "acme/platform", JiraBaseURL: "https://acme.atlassian.net", }, - roleMembership: map[string]string{}, + rosters: testRosters("PROJ", map[string]string{}), } event := JiraEvent{ @@ -484,9 +484,9 @@ func TestToNormalizedEvent_IsEntityAuthor(t *testing.T) { TargetRepo: "acme/platform", JiraBaseURL: "https://acme.atlassian.net", }, - roleMembership: map[string]string{ + rosters: testRosters("PROJ", map[string]string{ "user1": "Developers", - }, + }), } event := JiraEvent{ @@ -520,11 +520,11 @@ func TestToNormalizedEvent_IsEntityAssignee(t *testing.T) { TargetRepo: "acme/platform", JiraBaseURL: "https://acme.atlassian.net", }, - roleMembership: map[string]string{ + rosters: testRosters("PROJ", map[string]string{ "reporter-r": "Developers", "assignee-a": "Developers", "other-b": "Developers", - }, + }), } comment := func(author string, assignee jira.User) JiraEvent { return JiraEvent{ @@ -851,9 +851,9 @@ func TestToNormalizedEvent_JSONRoundTrip(t *testing.T) { TargetRepo: "acme/platform", JiraBaseURL: "https://acme.atlassian.net", }, - roleMembership: map[string]string{ + rosters: testRosters("PROJ", map[string]string{ "557058:abc123def456": "Developers", - }, + }), } event := JiraEvent{ @@ -929,9 +929,9 @@ func TestResolveRole_ExternalActor(t *testing.T) { TargetRepo: "acme/platform", JiraBaseURL: "https://acme.atlassian.net", }, - roleMembership: map[string]string{ + rosters: testRosters("PROJ", map[string]string{ "known-user": "Developers", - }, + }), } // Actor not in membership map should resolve to "external". @@ -957,7 +957,7 @@ func TestResolveRole_EmptyActorID(t *testing.T) { TargetRepo: "acme/platform", JiraBaseURL: "https://acme.atlassian.net", }, - roleMembership: map[string]string{}, + rosters: testRosters("PROJ", map[string]string{}), } // Event with no actor ID should resolve to "external". @@ -978,18 +978,18 @@ func TestResolveRole_EmptyActorID(t *testing.T) { } func TestResolveRole_CrossProjectFailsClosed(t *testing.T) { - // roleMembership was loaded for PROJ1 only. An actor who is a Developer + // The roster was loaded for PROJ1 only. An actor who is a Developer // there must not inherit that role on an issue from a different project - // matched by a multi-project --jql (see PR #5778 review). + // (see PR #5778 review). p := &Poller{ opts: Options{ - TargetRepo: "acme/platform", - JiraBaseURL: "https://acme.atlassian.net", - JiraProject: "PROJ1", + TargetRepo: "acme/platform", + JiraBaseURL: "https://acme.atlassian.net", + JiraProjects: []string{"PROJ1"}, }, - roleMembership: map[string]string{ + rosters: testRosters("PROJ1", map[string]string{ "dev-user": "Developers", - }, + }), } event := JiraEvent{ @@ -1011,13 +1011,13 @@ func TestResolveRole_CrossProjectFailsClosed(t *testing.T) { func TestResolveRole_SameProjectSucceeds(t *testing.T) { p := &Poller{ opts: Options{ - TargetRepo: "acme/platform", - JiraBaseURL: "https://acme.atlassian.net", - JiraProject: "PROJ1", + TargetRepo: "acme/platform", + JiraBaseURL: "https://acme.atlassian.net", + JiraProjects: []string{"PROJ1"}, }, - roleMembership: map[string]string{ + rosters: testRosters("PROJ1", map[string]string{ "dev-user": "Developers", - }, + }), } event := JiraEvent{ @@ -1042,9 +1042,9 @@ func TestResolveRole_AdminActor(t *testing.T) { TargetRepo: "acme/platform", JiraBaseURL: "https://acme.atlassian.net", }, - roleMembership: map[string]string{ + rosters: testRosters("PROJ", map[string]string{ "admin-user": "Administrators", - }, + }), } event := JiraEvent{ @@ -1080,9 +1080,9 @@ func TestToNormalizedEvent_CommandBodyCarriedWhole(t *testing.T) { TargetForge: TargetForgeGitLab, JiraBaseURL: "https://acme.atlassian.net", }, - roleMembership: map[string]string{ + rosters: testRosters("PROJ", map[string]string{ "dev-user": "Developers", - }, + }), } commandBody := "/fs-triage review the acceptance criteria\n" + @@ -1147,9 +1147,9 @@ func TestToNormalizedEvent_GitHubTargetCommandBodyCapped(t *testing.T) { TargetForge: TargetForgeGitHub, JiraBaseURL: "https://acme.atlassian.net", }, - roleMembership: map[string]string{ + rosters: testRosters("PROJ", map[string]string{ "dev-user": "Developers", - }, + }), } commandBody := "/fs-triage review the acceptance criteria\n" + diff --git a/internal/jirapoll/gitlab_target_test.go b/internal/jirapoll/gitlab_target_test.go index 6af1406c16..6c023023d5 100644 --- a/internal/jirapoll/gitlab_target_test.go +++ b/internal/jirapoll/gitlab_target_test.go @@ -83,12 +83,12 @@ func seedSlashCommandIssues(mc *mockClient, keys ...string) { func gitlabTargetOptions(d RecordDispatcher) Options { return Options{ - TargetRepo: "group/sub/project", - TargetForge: TargetForgeGitLab, - GitLabURL: "https://gitlab.example.com", - JiraBaseURL: "https://acme.atlassian.net", - JiraProject: "PROJ", - Dispatcher: d, + TargetRepo: "group/sub/project", + TargetForge: TargetForgeGitLab, + GitLabURL: "https://gitlab.example.com", + JiraBaseURL: "https://acme.atlassian.net", + JiraProjects: []string{"PROJ"}, + Dispatcher: d, } } diff --git a/internal/jirapoll/issue_type_test.go b/internal/jirapoll/issue_type_test.go index 7d5d3bc4d8..f732fc0ffc 100644 --- a/internal/jirapoll/issue_type_test.go +++ b/internal/jirapoll/issue_type_test.go @@ -39,7 +39,7 @@ func TestIssueType_DiscoveryAndCEL(t *testing.T) { }}} client.statuses["open"] = jira.Status{StatusCategory: jira.StatusCategory{Key: "new"}} client.statuses["done"] = jira.Status{StatusCategory: jira.StatusCategory{Key: "done"}} - p := New(client, nil, Options{TargetRepo: "acme/platform", JiraBaseURL: "https://example.atlassian.net", JiraProject: "PROJ"}) + p := New(client, nil, Options{TargetRepo: "acme/platform", JiraBaseURL: "https://example.atlassian.net", JiraProjects: []string{"PROJ"}}) result, err := p.detectChanges(context.Background(), issue, time.Time{}) require.NoError(t, err) require.Len(t, result.events, 6) diff --git a/internal/jirapoll/multi_project_test.go b/internal/jirapoll/multi_project_test.go new file mode 100644 index 0000000000..10085490ff --- /dev/null +++ b/internal/jirapoll/multi_project_test.go @@ -0,0 +1,443 @@ +package jirapoll + +import ( + "context" + "errors" + "strings" + "testing" + "time" + + "github.com/fullsend-ai/fullsend/internal/config" + "github.com/fullsend-ai/fullsend/internal/forge/jira" + "github.com/fullsend-ai/fullsend/internal/harnessdispatch" +) + +// testRosters returns a rosters map holding membership as the direct-user +// role roster of project, for tests that build a Poller by hand. +func testRosters(project string, membership map[string]string) map[string]*projectRoster { + return map[string]*projectRoster{project: { + membership: membership, + groups: map[string][]string{}, + groupsChecked: map[string]bool{}, + }} +} + +// membershipOf returns the role membership loaded for project this cycle, +// or nil when its roster was not loaded. +func membershipOf(p *Poller, project string) map[string]string { + if roster := p.rosters[project]; roster != nil { + return roster.membership + } + return nil +} + +// noRequestClient fails the test on any Jira request: its embedded client +// is nil, so every method call panics. +type noRequestClient struct { + JiraClient +} + +// projectRolesClient serves a separate role roster per project and counts +// the searches and roster loads it serves. +type projectRolesClient struct { + *mockClient + rosters map[string]map[string]string // project → accountID → role name + rosterErr map[string]error // project → load error + rosterCalls map[string]int + searchCalls int +} + +func newProjectRolesClient() *projectRolesClient { + return &projectRolesClient{ + mockClient: newMockClient(), + rosters: map[string]map[string]string{}, + rosterErr: map[string]error{}, + rosterCalls: map[string]int{}, + } +} + +func (c *projectRolesClient) SearchIssues(ctx context.Context, jql string, limit int) ([]jira.Issue, error) { + c.searchCalls++ + return c.mockClient.SearchIssues(ctx, jql, limit) +} + +func (c *projectRolesClient) GetProjectRoleActors(_ context.Context, project string) (map[string]jira.ProjectRoleActors, error) { + c.rosterCalls[project]++ + if err := c.rosterErr[project]; err != nil { + return nil, err + } + out := map[string]jira.ProjectRoleActors{} + for aid, role := range c.rosters[project] { + ra, ok := out[role] + if !ok { + ra = jira.ProjectRoleActors{DirectUsers: map[string]bool{}} + } + ra.DirectUsers[aid] = true + out[role] = ra + } + return out, nil +} + +// multiProjectIssue is an open issue with numeric id, created an hour ago. +func multiProjectIssue(id, key string, now time.Time) jira.Issue { + issue := authTestIssue(key, now) + issue.ID = id + return issue +} + +// roleByIssue returns the actor.role the matcher saw for each issue key. +func roleByIssue(m *gateMatcher) map[string]string { + out := map[string]string{} + for _, ev := range m.events { + out[ev.Entity.Key] = string(ev.Actor.Role) + } + return out +} + +func TestSearchJQL(t *testing.T) { + tests := []struct { + name string + projects []string + query string + want string + }{ + { + name: "one project, default predicate", + projects: []string{"PROJ"}, + want: `project = "PROJ" AND (statusCategory != Done) ORDER BY updated DESC`, + }, + { + name: "one project, configured predicate with ORDER BY", + projects: []string{"PROJ"}, + query: `labels = "fullsend" ORDER BY updated DESC`, + want: `project = "PROJ" AND (labels = "fullsend") ORDER BY updated DESC`, + }, + { + name: "two projects", + projects: []string{"ALPHA", "BETA"}, + query: `labels = "fullsend" ORDER BY created ASC`, + want: `project in ("ALPHA", "BETA") AND (labels = "fullsend") ORDER BY created ASC`, + }, + { + name: "predicate OR stays inside the scope", + projects: []string{"ALPHA", "BETA"}, + query: `labels = a OR labels = b`, + want: `project in ("ALPHA", "BETA") AND (labels = a OR labels = b)`, + }, + { + name: "predicate's own project clause cannot widen the scope", + projects: []string{"ALPHA", "BETA"}, + query: `project = OTHER OR project in (GAMMA) ORDER BY key`, + want: `project in ("ALPHA", "BETA") AND (project = OTHER OR project in (GAMMA)) ORDER BY key`, + }, + { + name: "single-character key", + projects: []string{"P"}, + query: `labels = a`, + want: `project = "P" AND (labels = a)`, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + p := New(nil, nil, Options{JiraProjects: tt.projects, JQL: tt.query}) + got, err := p.searchJQL() + if err != nil { + t.Fatalf("searchJQL() error: %v", err) + } + if got != tt.want { + t.Errorf("searchJQL() = %q, want %q", got, tt.want) + } + }) + } +} + +// TestSearchJQL_OneProjectMatchesConfigScoping pins that a one-item set +// searches exactly the JQL the single-project config path built before +// the poller took a project set. +func TestSearchJQL_OneProjectMatchesConfigScoping(t *testing.T) { + for _, query := range []string{ + config.DefaultJiraPollQuery, + `labels = "fullsend" AND statusCategory != Done ORDER BY updated DESC`, + `labels = a OR labels = b`, + `summary ~ "order by" AND status = Open`, + `ORDER BY updated DESC`, + } { + p := New(nil, nil, Options{JiraProjects: []string{"PROJ"}, JQL: query}) + got, err := p.searchJQL() + if err != nil { + t.Fatalf("searchJQL(%q) error: %v", query, err) + } + if want := config.ScopeJQLToProject("PROJ", query); got != want { + t.Errorf("searchJQL(%q) = %q, want %q", query, got, want) + } + } +} + +func TestSearchJQL_Rejects(t *testing.T) { + tests := []struct { + name string + projects []string + query string + wantErr string + }{ + {"nil set", nil, "", "no Jira project keys"}, + {"empty set", []string{}, "", "no Jira project keys"}, + {"empty key", []string{""}, "", `invalid Jira project key ""`}, + {"lowercase key", []string{"proj"}, "", `invalid Jira project key "proj"`}, + {"leading digit", []string{"1PROJ"}, "", `invalid Jira project key "1PROJ"`}, + {"quote injection", []string{`PROJ" OR project = "X`}, "", "invalid Jira project key"}, + {"malformed among valid", []string{"ALPHA", "be ta"}, "", `invalid Jira project key "be ta"`}, + {"duplicate key", []string{"ALPHA", "BETA", "ALPHA"}, "", `duplicate Jira project key "ALPHA"`}, + {"predicate closes the scope", []string{"PROJ"}, `labels = a) OR (project = OTHER`, "unbalanced parentheses"}, + {"predicate leaves a parenthesis open", []string{"PROJ"}, `(labels = a`, "unbalanced parentheses"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + p := New(nil, nil, Options{JiraProjects: tt.projects, JQL: tt.query}) + _, err := p.searchJQL() + if err == nil || !strings.Contains(err.Error(), tt.wantErr) { + t.Fatalf("searchJQL() error = %v, want it to contain %q", err, tt.wantErr) + } + }) + } +} + +// TestRun_InvalidScopeMakesNoJiraRequest: an empty or malformed project +// set (or an unscopable predicate) fails the cycle before the auth +// preflight or any other Jira request. +func TestRun_InvalidScopeMakesNoJiraRequest(t *testing.T) { + for name, opts := range map[string]Options{ + "empty set": {}, + "malformed key": {JiraProjects: []string{"PROJ", "bad-key"}}, + "duplicate key": {JiraProjects: []string{"PROJ", "PROJ"}}, + "unbalanced JQL": {JiraProjects: []string{"PROJ"}, JQL: `a = b) OR (c = d`}, + "empty key in set": {JiraProjects: []string{""}}, + } { + t.Run(name, func(t *testing.T) { + p := newTestPoller(noRequestClient{}, nil, opts) + err := p.Run(context.Background()) + if err == nil || !strings.Contains(err.Error(), "invalid poll scope") { + t.Fatalf("Run() error = %v, want an invalid poll scope error", err) + } + }) + } +} + +// TestRun_TwoProjectsShareOneSearch: the set is searched once, scoped to +// both projects, so M and the pagination budget apply across the set and +// N selects across it. +func TestRun_TwoProjectsShareOneSearch(t *testing.T) { + now := time.Now().Truncate(time.Second) + mc := newProjectRolesClient() + mc.searchResult = []jira.Issue{ + multiProjectIssue("1", "ALPHA-1", now), + multiProjectIssue("2", "BETA-1", now), + multiProjectIssue("3", "ALPHA-2", now), + multiProjectIssue("4", "BETA-2", now), + multiProjectIssue("5", "ALPHA-3", now), + } + p := newTestPoller(mc, nil, Options{ + TargetRepo: "acme/platform", + JiraBaseURL: "https://acme.atlassian.net", + JiraProjects: []string{"ALPHA", "BETA"}, + JQL: `labels = x OR project = OTHER ORDER BY created ASC`, + M: 3, + N: 2, + }) + if err := p.Run(context.Background()); err != nil { + t.Fatalf("Run() error: %v", err) + } + if mc.searchCalls != 1 { + t.Errorf("SearchIssues called %d times, want once for the whole set", mc.searchCalls) + } + if mc.lastLimit != 3 { + t.Errorf("SearchIssues limit = %d, want M = 3 across the set", mc.lastLimit) + } + if want := `project in ("ALPHA", "BETA") AND (labels = x OR project = OTHER) ORDER BY created ASC`; mc.lastQuery != want { + t.Errorf("JQL = %q, want %q", mc.lastQuery, want) + } + // N = 2 issues of the 3 candidates are processed: each processed issue + // gets its lastCheck read under the lock. + locked := 0 + for _, key := range []string{"ALPHA-1", "BETA-1", "ALPHA-2", "BETA-2", "ALPHA-3"} { + if _, ok := mc.properties[key]; ok { + locked++ + } + } + if locked > 2 { + t.Errorf("%d issues were processed, want at most N = 2 across the set", locked) + } +} + +// TestRun_MixedProjectRoleResolution: each issue's actor resolves through +// its own project's roster, loaded once per project per cycle. +func TestRun_MixedProjectRoleResolution(t *testing.T) { + now := time.Now().Truncate(time.Second) + mc := newProjectRolesClient() + mc.rosters["ALPHA"] = map[string]string{"dev": "Developers"} + mc.rosters["BETA"] = map[string]string{"dev": "Viewers", "lead": "Administrators"} + mc.searchResult = []jira.Issue{ + multiProjectIssue("1", "ALPHA-1", now), + multiProjectIssue("2", "BETA-1", now), + multiProjectIssue("3", "ALPHA-2", now), + } + mc.comments["ALPHA-1"] = []jira.Comment{authTestComment("10", "dev", "/fs-code go", now.Add(-10*time.Minute))} + mc.comments["BETA-1"] = []jira.Comment{authTestComment("20", "dev", "/fs-code go", now.Add(-10*time.Minute))} + mc.comments["ALPHA-2"] = []jira.Comment{authTestComment("30", "lead", "/fs-code go", now.Add(-10*time.Minute))} + + m := newGateMatcher(harnessdispatch.AuthOptions{}) + p := newTestPoller(mc, m, Options{ + TargetRepo: "acme/platform", + JiraBaseURL: "https://acme.atlassian.net", + JiraProjects: []string{"ALPHA", "BETA"}, + N: 50, + }) + if err := p.Run(context.Background()); err != nil { + t.Fatalf("Run() error: %v", err) + } + got := roleByIssue(m) + want := map[string]string{ + "ALPHA-1": "write", // Developers in ALPHA + "BETA-1": "read", // Viewers in BETA, not ALPHA's Developers + "ALPHA-2": "external", // BETA's Administrator has no role in ALPHA + } + for key, role := range want { + if got[key] != role { + t.Errorf("actor.role on %s = %q, want %q", key, got[key], role) + } + } + for _, project := range []string{"ALPHA", "BETA"} { + if mc.rosterCalls[project] != 1 { + t.Errorf("roster for %s loaded %d times, want once per cycle", project, mc.rosterCalls[project]) + } + } +} + +// TestRun_ProjectRosterFailureFailsClosedThenRetries: a roster load +// failure for any project of the set fails the cycle without advancing +// any issue's checkpoint, and the next cycle retries the same activity. +func TestRun_ProjectRosterFailureFailsClosedThenRetries(t *testing.T) { + now := time.Now().Truncate(time.Second) + mc := newProjectRolesClient() + mc.rosters["ALPHA"] = map[string]string{"dev": "Developers"} + mc.rosters["BETA"] = map[string]string{"dev": "Developers"} + mc.rosterErr["BETA"] = errAdminOnly + mc.searchResult = []jira.Issue{ + multiProjectIssue("1", "ALPHA-1", now), + multiProjectIssue("2", "BETA-1", now), + } + mc.comments["ALPHA-1"] = []jira.Comment{authTestComment("10", "dev", "/fs-code go", now.Add(-10*time.Minute))} + mc.comments["BETA-1"] = []jira.Comment{authTestComment("20", "dev", "/fs-code go", now.Add(-10*time.Minute))} + + opts := Options{ + TargetRepo: "acme/platform", + JiraBaseURL: "https://acme.atlassian.net", + JiraProjects: []string{"ALPHA", "BETA"}, + N: 50, + } + p := newTestPoller(mc, newGateMatcher(harnessdispatch.AuthOptions{}), opts) + err := p.Run(context.Background()) + if err == nil || !strings.Contains(err.Error(), "load project roles for BETA") { + t.Fatalf("Run() error = %v, want a BETA role load failure", err) + } + if !errors.Is(err, errAdminOnly) { + t.Errorf("Run() error = %v, want it to wrap the roster error", err) + } + for _, key := range []string{"ALPHA-1", "BETA-1"} { + lastCheck, err := p.readLastCheck(context.Background(), key) + if err != nil { + t.Fatalf("readLastCheck(%s) error: %v", key, err) + } + if !lastCheck.IsZero() { + t.Errorf("lastCheck of %s advanced to %v after a failed cycle, want unset", key, lastCheck) + } + } + + delete(mc.rosterErr, "BETA") + m := newGateMatcher(harnessdispatch.AuthOptions{}) + p = newTestPoller(mc, m, opts) + if err := p.Run(context.Background()); err != nil { + t.Fatalf("retry Run() error: %v", err) + } + got := roleByIssue(m) + for _, key := range []string{"ALPHA-1", "BETA-1"} { + if got[key] != "write" { + t.Errorf("retry actor.role on %s = %q, want write", key, got[key]) + } + lastCheck, err := p.readLastCheck(context.Background(), key) + if err != nil { + t.Fatalf("readLastCheck(%s) error: %v", key, err) + } + if lastCheck.IsZero() { + t.Errorf("lastCheck of %s not advanced after the retry succeeded", key) + } + } +} + +// TestRun_DuplicateCanonicalIssueProcessedOnce: the same issue returned +// twice, under one key or under an old and a new key after a move within +// the set, is processed and dispatched once per cycle. +func TestRun_DuplicateCanonicalIssueProcessedOnce(t *testing.T) { + now := time.Now().Truncate(time.Second) + mc := newProjectRolesClient() + mc.rosters["ALPHA"] = map[string]string{"dev": "Developers"} + mc.rosters["BETA"] = map[string]string{"dev": "Developers"} + mc.searchResult = []jira.Issue{ + multiProjectIssue("1", "ALPHA-1", now), + multiProjectIssue("1", "ALPHA-1", now), + multiProjectIssue("2", "ALPHA-2", now), + multiProjectIssue("2", "BETA-9", now), // ALPHA-2 moved to BETA + } + mc.comments["ALPHA-1"] = []jira.Comment{authTestComment("10", "dev", "/fs-code go", now.Add(-10*time.Minute))} + mc.comments["ALPHA-2"] = []jira.Comment{authTestComment("20", "dev", "/fs-code go", now.Add(-10*time.Minute))} + mc.comments["BETA-9"] = mc.comments["ALPHA-2"] + + p := newTestPoller(mc, &stubMatcher{agents: []string{"code"}}, Options{ + TargetRepo: "acme/platform", + JiraBaseURL: "https://acme.atlassian.net", + JiraProjects: []string{"ALPHA", "BETA"}, + N: 50, + }) + if err := p.Run(context.Background()); err != nil { + t.Fatalf("Run() error: %v", err) + } + // Each canonical issue dispatches its opened event and its comment + // once: no row is processed a second time. + perIssue := map[string]int{} + for _, d := range p.dispatches { + perIssue[d.StatusNumber+"/"+d.EventType]++ + } + want := map[string]int{"1/issue": 1, "1/comment": 1, "2/issue": 1, "2/comment": 1} + if len(perIssue) != len(want) { + t.Errorf("dispatches = %v, want %v", perIssue, want) + } + for k, n := range want { + if perIssue[k] != n { + t.Errorf("dispatches for %s = %d, want %d (all: %v)", k, perIssue[k], n, perIssue) + } + } + if _, ok := mc.properties["BETA-9"]; ok { + t.Error("the duplicate row BETA-9 of issue 2 was processed") + } +} + +func TestUniqueIssues(t *testing.T) { + got := uniqueIssues([]jira.Issue{ + {ID: "1", Key: "A-1"}, + {ID: "2", Key: "A-2"}, + {ID: "1", Key: "B-1"}, + {Key: "A-3"}, + {Key: "A-3"}, + {Key: "A-4"}, + }) + var keys []string + for _, issue := range got { + keys = append(keys, issue.Key) + } + if want := "A-1,A-2,A-3,A-4"; strings.Join(keys, ",") != want { + t.Errorf("uniqueIssues() keys = %v, want %s", keys, want) + } + if got := uniqueIssues(nil); len(got) != 0 { + t.Errorf("uniqueIssues(nil) = %v, want empty", got) + } +} diff --git a/internal/jirapoll/poller.go b/internal/jirapoll/poller.go index e1d66dfa27..95a5cb85b5 100644 --- a/internal/jirapoll/poller.go +++ b/internal/jirapoll/poller.go @@ -10,9 +10,11 @@ import ( "fmt" "log" "os" - "regexp" + "slices" + "strings" "time" + "github.com/fullsend-ai/fullsend/internal/config" "github.com/fullsend-ai/fullsend/internal/dispatch" "github.com/fullsend-ai/fullsend/internal/forge/jira" "github.com/fullsend-ai/fullsend/internal/normevent" @@ -47,13 +49,6 @@ type DispatchRecord struct { // normal per-cycle volume so it only trips on a flood. const maxEventsPerIssue = 100 -// validProjectKey matches Jira Cloud project keys: 2–10 uppercase -// alphanumeric characters, starting with a letter. Jira Cloud only allows -// uppercase letters and digits in project keys (the driver is Cloud-only; -// Data Center's jira.projectkey.pattern is admin-customizable and not -// supported here). Validated before interpolation into JQL. -var validProjectKey = regexp.MustCompile(`^[A-Z][A-Z0-9]{1,9}$`) - // Poller discovers Jira events and dispatches agent stages. type Poller struct { client JiraClient @@ -61,10 +56,7 @@ type Poller struct { opts Options dispatches []DispatchRecord sleepFn func(context.Context, time.Duration) // overridable for testing - roleMembership map[string]string // accountID → Jira project role name - roleGroups map[string][]string // Jira role name → group IDs for per-actor resolution - roleGroupsChecked map[string]bool // accountID → group membership already fetched this cycle - rolesLoaded bool // project role roster loaded (or skipped for a missing project key) this cycle + rosters map[string]*projectRoster // project key → role roster loaded this cycle userGroups map[string][]jira.UserGroupInfo // accountID → GetUserGroups result, cached per cycle statusCategoryCache map[string]string // status name → statusCategory key, reset each cycle selfAccountID string // authenticated Jira account from GetMyself; used to classify self-authored events as bot @@ -112,12 +104,17 @@ func (p *Poller) Run(ctx context.Context) error { p.dispatches = nil p.eventsSeen, p.eventsInvalid, p.eventsMatchErrors = 0, 0, 0 p.statusCategoryCache = make(map[string]string) - p.roleMembership = make(map[string]string) - p.roleGroups = make(map[string][]string) - p.roleGroupsChecked = make(map[string]bool) - p.rolesLoaded = false + p.rosters = make(map[string]*projectRoster) p.userGroups = make(map[string][]jira.UserGroupInfo) + // Validate the project set and build the scoped search before the + // first Jira request, so an empty or malformed set (or a predicate that + // could escape the scope) never reaches Jira. + jql, err := p.searchJQL() + if err != nil { + return fmt.Errorf("invalid poll scope: %w", err) + } + // Auth preflight: verify credentials before any discovery, lock, or // checkpoint operations. Without this, bad credentials cause Jira to // treat the request as unauthenticated and return empty results — @@ -137,7 +134,7 @@ func (p *Poller) Run(ctx context.Context) error { p.selfAccountID = userID(*myself) // Step 1: Execute JQL to get candidate issues. - candidates, err := p.searchCandidates(ctx) + candidates, err := p.searchCandidates(ctx, jql) if err != nil { return fmt.Errorf("search candidates: %w", err) } @@ -151,14 +148,15 @@ func (p *Poller) Run(ctx context.Context) error { // Step 3: Randomly select min(N, len(unlocked)) candidates. selected := selectRandom(unlocked, p.opts.N) - // The project role roster (GET /project/{key}/role, which Jira Cloud - // serves only with the Administer Projects permission) is not loaded - // here. processIssue loads it on first use, only when an event needs - // project-role resolution (see roleSourceFor), so a setup whose jira - // authorization entry uses the lists, or only label triggers under - // the jira_editors rule, never calls it. A load FAILURE fails the whole - // cycle (see ensureRoleStructure), leaving checkpoints untouched so - // the next cron run retries. + // The project role rosters (GET /project/{key}/role, which Jira Cloud + // serves only with the Administer Projects permission) are not loaded + // here. processIssue loads an issue project's roster on first use, + // only when an event needs project-role resolution (see roleSourceFor), + // so a setup whose jira authorization entry uses the lists, or only + // label triggers under the jira_editors rule, never calls it. A load + // FAILURE for any project fails the whole cycle (see + // ensureRoleStructure), leaving checkpoints untouched so the next cron + // run retries. // Step 4: Process each selected issue. Checkpoint advances are not // committed to Jira here — detectChanges/routing only compute the @@ -176,7 +174,7 @@ func (p *Poller) Run(ctx context.Context) error { if err != nil { var rle *roleLoadError if errors.As(err, &rle) { - return fmt.Errorf("load project roles for %s: %w", p.opts.JiraProject, rle.err) + return fmt.Errorf("load project roles for %s: %w", rle.project, rle.err) } log.Printf("WARNING: processing %s: %v", issue.Key, err) processErrors++ @@ -321,52 +319,61 @@ type pendingCheckpoint struct { // for them. const maxRolePriority = 2 -// loadRoleStructure loads the project role structure (direct users and -// group assignments) without enumerating group members. Direct user -// actors are added to roleMembership immediately; group IDs are stored -// in roleGroups for lazy per-actor resolution in resolveActorRoles. -func (p *Poller) loadRoleStructure(ctx context.Context, projectKey string) error { +// projectRoster is one Jira project's role roster for the current cycle. +// Each project in Options.JiraProjects has its own, so a role granted in +// one project never applies to an issue in another. +type projectRoster struct { + membership map[string]string // accountID → Jira project role name + groups map[string][]string // Jira role name → group IDs for per-actor resolution + groupsChecked map[string]bool // accountID → group-based roles already resolved this cycle +} + +// loadRoleStructure loads the role structure of projectKey (direct users +// and group assignments) without enumerating group members. Direct user +// actors go into the roster's membership immediately; group IDs are stored +// in its groups for lazy per-actor resolution in resolveActorRoles. +func (p *Poller) loadRoleStructure(ctx context.Context, projectKey string) (*projectRoster, error) { actors, err := p.client.GetProjectRoleActors(ctx, projectKey) if err != nil { - return err + return nil, err } - if p.roleMembership == nil { - p.roleMembership = make(map[string]string) - } - if p.roleGroups == nil { - p.roleGroups = make(map[string][]string) + roster := &projectRoster{ + membership: make(map[string]string), + groups: make(map[string][]string), + groupsChecked: make(map[string]bool), } for roleName, ra := range actors { for aid := range ra.DirectUsers { - existing, ok := p.roleMembership[aid] + existing, ok := roster.membership[aid] if !ok || jira.RolePriority(roleName) > jira.RolePriority(existing) { - p.roleMembership[aid] = roleName + roster.membership[aid] = roleName } } if len(ra.GroupIDs) > 0 { - p.roleGroups[roleName] = ra.GroupIDs + roster.groups[roleName] = ra.GroupIDs } } - return nil + return roster, nil } -// resolveActorRoles resolves group-based role membership for the given -// actors, each of whom is below maxRolePriority (the caller filters). -// A direct role assignment doesn't rule out also belonging to a +// resolveActorRoles resolves group-based role membership in roster for +// the given actors, each of whom is below maxRolePriority (the caller +// filters). A direct role assignment doesn't rule out also belonging to a // higher-priority group, so this always fetches and checks group // membership rather than skipping actors who already have some role. -// For each actor, it calls GetUserGroups to retrieve the actor's group -// memberships and cross-references them with the groups assigned to -// each project role (stored in roleGroups), upgrading roleMembership -// only if a higher-priority match is found. +// For each actor, it calls GetUserGroups (cached per cycle across +// projects) to retrieve the actor's group memberships and cross-references +// them with the groups assigned to each of the project's roles (stored in +// roster.groups), upgrading roster.membership only if a higher-priority +// match is found. // // Any lookup failure — partial or total — propagates an error so the // issue is retried next cycle, rather than silently leaving the failed // actor's role unresolved (defaulting to "external" in resolveRole) and // dispatching their event anyway with a possibly-wrong, unrecoverable // privilege downgrade for this cycle. -func (p *Poller) resolveActorRoles(ctx context.Context, actorIDs []string) error { - if len(p.roleGroups) == 0 || len(actorIDs) == 0 { +func (p *Poller) resolveActorRoles(ctx context.Context, roster *projectRoster, actorIDs []string) error { + if len(roster.groups) == 0 || len(actorIDs) == 0 { return nil } var lastErr error @@ -379,16 +386,16 @@ func (p *Poller) resolveActorRoles(ctx context.Context, actorIDs []string) error errorCount++ continue } - p.roleGroupsChecked[aid] = true + roster.groupsChecked[aid] = true userGroupIDs := make(map[string]bool, len(groups)) for _, g := range groups { userGroupIDs[g.GroupID] = true } - for roleName, groupIDs := range p.roleGroups { + for roleName, groupIDs := range roster.groups { for _, gid := range groupIDs { if userGroupIDs[gid] { - if existing := p.roleMembership[aid]; jira.RolePriority(roleName) > jira.RolePriority(existing) { - p.roleMembership[aid] = roleName + if existing := roster.membership[aid]; jira.RolePriority(roleName) > jira.RolePriority(existing) { + roster.membership[aid] = roleName } break } @@ -401,17 +408,77 @@ func (p *Poller) resolveActorRoles(ctx context.Context, actorIDs []string) error return nil } -// searchCandidates executes JQL and collects up to M results. -func (p *Poller) searchCandidates(ctx context.Context) ([]jira.Issue, error) { - jql := p.opts.JQL - if jql == "" { - if !validProjectKey.MatchString(p.opts.JiraProject) { - return nil, fmt.Errorf("invalid Jira project key %q: must match %s", p.opts.JiraProject, validProjectKey.String()) +// validateProjectSet checks that projects is a non-empty set of distinct +// Jira project keys, each in the form tracker.jira.project accepts. Keys +// are validated before they are interpolated into JQL. +func validateProjectSet(projects []string) error { + if len(projects) == 0 { + return errors.New("no Jira project keys: the poller needs at least one project to scope its search to") + } + for i, key := range projects { + if !config.ValidJiraProjectKey(key) { + return fmt.Errorf("invalid Jira project key %q: must be an uppercase letter followed by uppercase letters, digits, or underscores", key) } - jql = fmt.Sprintf("project = %q AND statusCategory != Done ORDER BY updated DESC", p.opts.JiraProject) + if slices.Contains(projects[:i], key) { + return fmt.Errorf("duplicate Jira project key %q", key) + } + } + return nil +} + +// searchJQL returns the JQL every search runs: the configured predicate +// (or config.DefaultJiraPollQuery) scoped to exactly Options.JiraProjects, +// with a trailing ORDER BY kept last (see config.ScopeJQLToProjects). The +// scoping clause is applied outside the predicate's parentheses, and a +// predicate whose parentheses do not balance is rejected, so no predicate +// (an OR, or its own project clause) can widen the search beyond the set. +// It makes no Jira request. +func (p *Poller) searchJQL() (string, error) { + if err := validateProjectSet(p.opts.JiraProjects); err != nil { + return "", err + } + query := p.opts.JQL + if strings.TrimSpace(query) == "" { + query = config.DefaultJiraPollQuery + } + if !config.JQLParensBalanced(query) { + return "", errors.New("the JQL predicate has unbalanced parentheses: it is wrapped in parentheses to scope it to the project set") + } + return config.ScopeJQLToProjects(p.opts.JiraProjects, query), nil +} + +// searchCandidates runs the scoped search jql once, so the M limit and the +// client's pagination budget apply across the whole project set, and +// drops repeated rows of the same canonical issue (see uniqueIssues). +func (p *Poller) searchCandidates(ctx context.Context, jql string) ([]jira.Issue, error) { + issues, err := p.client.SearchIssues(ctx, jql, p.opts.M) + if err != nil { + return nil, err } + return uniqueIssues(issues), nil +} - return p.client.SearchIssues(ctx, jql, p.opts.M) +// uniqueIssues keeps the first row of each canonical issue: its numeric +// ID, which stays the same when an issue moves between projects of the +// set, or its key when Jira serves no ID. Jira can return the same issue +// twice when results shift between the pages of one search; processing it +// once per cycle keeps its lock, checkpoint and dispatches single. +func uniqueIssues(issues []jira.Issue) []jira.Issue { + seen := make(map[string]bool, len(issues)) + unique := issues[:0:0] + for _, issue := range issues { + id := "id:" + issue.ID + if issue.ID == "" { + id = "key:" + issue.Key + } + if seen[id] { + log.Printf("WARNING: search returned %s more than once; processing it once this cycle", issue.Key) + continue + } + seen[id] = true + unique = append(unique, issue) + } + return unique } // filterLocked removes locked issues and cleans up stale locks. If every diff --git a/internal/jirapoll/poller_invalid_id_test.go b/internal/jirapoll/poller_invalid_id_test.go index f2979bda37..db3f43b3e9 100644 --- a/internal/jirapoll/poller_invalid_id_test.go +++ b/internal/jirapoll/poller_invalid_id_test.go @@ -55,9 +55,9 @@ func TestRun_InvalidEventSkippedWithoutRoster(t *testing.T) { } p := newTestPoller(mc, &stubMatcher{agents: []string{"code"}}, Options{ - TargetRepo: "acme/platform", - JiraBaseURL: "https://acme.atlassian.net", - JiraProject: "PROJ", + TargetRepo: "acme/platform", + JiraBaseURL: "https://acme.atlassian.net", + JiraProjects: []string{"PROJ"}, }) logBuf := captureLog(t) if err := p.Run(context.Background()); err == nil || !strings.Contains(err.Error(), "failed normalized-event validation") { @@ -116,9 +116,9 @@ func TestRun_MixedInvalidEventsCycleSucceeds(t *testing.T) { } p := newTestPoller(mc, &stubMatcher{agents: []string{"code"}}, Options{ - TargetRepo: "acme/platform", - JiraBaseURL: "https://acme.atlassian.net", - JiraProject: "PROJ", + TargetRepo: "acme/platform", + JiraBaseURL: "https://acme.atlassian.net", + JiraProjects: []string{"PROJ"}, }) logBuf := captureLog(t) if err := p.Run(context.Background()); err != nil { @@ -201,9 +201,9 @@ func TestRun_NilLabelsTreatedAsUnlabeled(t *testing.T) { } p := newTestPoller(&rawSearchClient{mc}, &stubMatcher{agents: []string{"code"}}, Options{ - TargetRepo: "acme/platform", - JiraBaseURL: "https://acme.atlassian.net", - JiraProject: "PROJ", + TargetRepo: "acme/platform", + JiraBaseURL: "https://acme.atlassian.net", + JiraProjects: []string{"PROJ"}, }) logBuf := captureLog(t) if err := p.Run(context.Background()); err != nil { @@ -291,9 +291,9 @@ func TestRun_MatcherErrEventsDroppedNotLost(t *testing.T) { t.Run("all events fail matching", func(t *testing.T) { p := newTestPoller(newClient(), &stubMatcher{agents: []string{"code"}, err: fmt.Errorf("matcher: trigger evaluation failed")}, Options{ - TargetRepo: "acme/platform", - JiraBaseURL: "https://acme.atlassian.net", - JiraProject: "PROJ", + TargetRepo: "acme/platform", + JiraBaseURL: "https://acme.atlassian.net", + JiraProjects: []string{"PROJ"}, }) logBuf := captureLog(t) err := p.Run(context.Background()) @@ -316,9 +316,9 @@ func TestRun_MatcherErrEventsDroppedNotLost(t *testing.T) { t.Run("one issue's events fail matching", func(t *testing.T) { p := newTestPoller(newClient(), &errOnStatusMatcher{stubMatcher: stubMatcher{agents: []string{"code"}}, failStatus: "10042"}, Options{ - TargetRepo: "acme/platform", - JiraBaseURL: "https://acme.atlassian.net", - JiraProject: "PROJ", + TargetRepo: "acme/platform", + JiraBaseURL: "https://acme.atlassian.net", + JiraProjects: []string{"PROJ"}, }) logBuf := captureLog(t) if err := p.Run(context.Background()); err != nil { @@ -353,9 +353,9 @@ func TestRun_MatcherErrEventsDroppedNotLost(t *testing.T) { mc := newClient() mc.searchResult[1].ID = "not-a-number" // PROJ-123's events fail validation; PROJ-122's fail matching p := newTestPoller(mc, &stubMatcher{agents: []string{"code"}, err: fmt.Errorf("matcher: trigger evaluation failed")}, Options{ - TargetRepo: "acme/platform", - JiraBaseURL: "https://acme.atlassian.net", - JiraProject: "PROJ", + TargetRepo: "acme/platform", + JiraBaseURL: "https://acme.atlassian.net", + JiraProjects: []string{"PROJ"}, }) logBuf := captureLog(t) const wantErr = "all 4 events this cycle were dropped before dispatch (2 failed normalized-event validation, 2 failed matching)" @@ -390,10 +390,9 @@ func TestRun_MatcherErrEventsDroppedNotLost(t *testing.T) { // through a custom tracker.jira.poll.query, and on a legacy Server/Data // Center deployment whose project key is a single character (which the // config gate's jiraProjectKeyRe accepts) through the scoped default query -// too: the CLI always sets a JQL, so the project-key check in -// searchCandidates (which runs only with no JQL at all) never intercepts -// it. The mock serves the issue regardless of the JQL, as Jira does for -// either query. +// too: the poller's project-set check accepts the same keys as that gate, +// so it never intercepts it. The mock serves the issue regardless of the +// JQL, as Jira does for either query. func TestRun_MalformedKeyEventSkipped(t *testing.T) { now := time.Now().Truncate(time.Second) mc := newMockClient() @@ -429,9 +428,9 @@ func TestRun_MalformedKeyEventSkipped(t *testing.T) { } p := newTestPoller(mc, &stubMatcher{agents: []string{"code"}}, Options{ - TargetRepo: "acme/platform", - JiraBaseURL: "https://acme.atlassian.net", - JiraProject: "PROJ", + TargetRepo: "acme/platform", + JiraBaseURL: "https://acme.atlassian.net", + JiraProjects: []string{"PROJ"}, }) logBuf := captureLog(t) if err := p.Run(context.Background()); err != nil { @@ -486,9 +485,9 @@ func TestRun_LoneBadEventFailsEveryCycle(t *testing.T) { } p := newTestPoller(mc, &stubMatcher{agents: []string{"code"}}, Options{ - TargetRepo: "acme/platform", - JiraBaseURL: "https://acme.atlassian.net", - JiraProject: "PROJ", + TargetRepo: "acme/platform", + JiraBaseURL: "https://acme.atlassian.net", + JiraProjects: []string{"PROJ"}, }) for cycle := 1; cycle <= 2; cycle++ { logBuf := captureLog(t) diff --git a/internal/jirapoll/poller_test.go b/internal/jirapoll/poller_test.go index 737a99d99c..b73b971eae 100644 --- a/internal/jirapoll/poller_test.go +++ b/internal/jirapoll/poller_test.go @@ -274,9 +274,9 @@ func (m *stubMatcher) Match(_ context.Context, event *normevent.Event) ([]Dispat func TestNew(t *testing.T) { mc := newMockClient() p := New(mc, nil, Options{ - TargetRepo: "acme/platform", - JiraBaseURL: "https://acme.atlassian.net", - JiraProject: "PROJ", + TargetRepo: "acme/platform", + JiraBaseURL: "https://acme.atlassian.net", + JiraProjects: []string{"PROJ"}, }) if p.opts.M != 50 { t.Errorf("M = %d, want default 50", p.opts.M) @@ -296,10 +296,10 @@ func TestRunEmptyPoll(t *testing.T) { outputPath := filepath.Join(dir, "dispatches.json") p := newTestPoller(mc, nil, Options{ - TargetRepo: "acme/platform", - JiraBaseURL: "https://acme.atlassian.net", - JiraProject: "PROJ", - OutputPath: outputPath, + TargetRepo: "acme/platform", + JiraBaseURL: "https://acme.atlassian.net", + JiraProjects: []string{"PROJ"}, + OutputPath: outputPath, }) err := p.Run(context.Background()) @@ -328,10 +328,10 @@ func TestRun_AuthPreflightFailure(t *testing.T) { outputPath := filepath.Join(dir, "dispatches.json") p := newTestPoller(mc, nil, Options{ - TargetRepo: "acme/platform", - JiraBaseURL: "https://acme.atlassian.net", - JiraProject: "PROJ", - OutputPath: outputPath, + TargetRepo: "acme/platform", + JiraBaseURL: "https://acme.atlassian.net", + JiraProjects: []string{"PROJ"}, + OutputPath: outputPath, }) err := p.Run(context.Background()) @@ -364,9 +364,9 @@ func TestRun_AuthPreflightInactiveAccount(t *testing.T) { } p := newTestPoller(mc, nil, Options{ - TargetRepo: "acme/platform", - JiraBaseURL: "https://acme.atlassian.net", - JiraProject: "PROJ", + TargetRepo: "acme/platform", + JiraBaseURL: "https://acme.atlassian.net", + JiraProjects: []string{"PROJ"}, }) err := p.Run(context.Background()) @@ -391,10 +391,10 @@ func TestRun_AuthPreflightSuccess(t *testing.T) { outputPath := filepath.Join(dir, "dispatches.json") p := newTestPoller(mc, nil, Options{ - TargetRepo: "acme/platform", - JiraBaseURL: "https://acme.atlassian.net", - JiraProject: "PROJ", - OutputPath: outputPath, + TargetRepo: "acme/platform", + JiraBaseURL: "https://acme.atlassian.net", + JiraProjects: []string{"PROJ"}, + OutputPath: outputPath, }) err := p.Run(context.Background()) @@ -454,10 +454,10 @@ func TestRunHappyPath_CommentWithSlashCommand(t *testing.T) { router := &stubMatcher{agents: []string{"triage"}} p := newTestPoller(mc, router, Options{ - TargetRepo: "acme/platform", - JiraBaseURL: "https://acme.atlassian.net", - JiraProject: "PROJ", - OutputPath: outputPath, + TargetRepo: "acme/platform", + JiraBaseURL: "https://acme.atlassian.net", + JiraProjects: []string{"PROJ"}, + OutputPath: outputPath, }) if err := p.Run(context.Background()); err != nil { @@ -531,10 +531,10 @@ func TestRun_InvalidEventNotDispatched(t *testing.T) { outputPath := filepath.Join(t.TempDir(), "dispatches.json") p := newTestPoller(mc, &stubMatcher{agents: []string{"triage"}}, Options{ - TargetRepo: "acme/platform", - JiraBaseURL: "https://acme.atlassian.net", - JiraProject: "PROJ", - OutputPath: outputPath, + TargetRepo: "acme/platform", + JiraBaseURL: "https://acme.atlassian.net", + JiraProjects: []string{"PROJ"}, + OutputPath: outputPath, }) logBuf := captureLog(t) err := p.Run(context.Background()) @@ -606,9 +606,9 @@ func TestRunDispatchWriteFailure_NoCheckpointCommitted(t *testing.T) { router := &stubMatcher{agents: []string{"triage"}} p := newTestPoller(mc, router, Options{ - TargetRepo: "acme/platform", - JiraBaseURL: "https://acme.atlassian.net", - JiraProject: "PROJ", + TargetRepo: "acme/platform", + JiraBaseURL: "https://acme.atlassian.net", + JiraProjects: []string{"PROJ"}, // A path under a nonexistent directory: os.WriteFile fails. OutputPath: filepath.Join(t.TempDir(), "no-such-dir", "dispatches.json"), }) @@ -658,10 +658,10 @@ func TestRunCheckpointRespectsSafetyMargin(t *testing.T) { } p := newTestPoller(mc, &stubMatcher{agents: []string{"triage"}}, Options{ - TargetRepo: "acme/platform", - JiraBaseURL: "https://acme.atlassian.net", - JiraProject: "PROJ", - OutputPath: filepath.Join(t.TempDir(), "dispatches.json"), + TargetRepo: "acme/platform", + JiraBaseURL: "https://acme.atlassian.net", + JiraProjects: []string{"PROJ"}, + OutputPath: filepath.Join(t.TempDir(), "dispatches.json"), }) if err := p.Run(context.Background()); err != nil { @@ -699,9 +699,9 @@ func TestProcessIssue_CheckpointNeverRegresses(t *testing.T) { } p := newTestPoller(mc, &stubMatcher{agents: []string{"triage"}}, Options{ - TargetRepo: "acme/platform", - JiraBaseURL: "https://acme.atlassian.net", - JiraProject: "PROJ", + TargetRepo: "acme/platform", + JiraBaseURL: "https://acme.atlassian.net", + JiraProjects: []string{"PROJ"}, }) if err := p.advanceLastCheck(context.Background(), "PROJ-123", storedLastCheck); err != nil { t.Fatalf("seed lastCheck: %v", err) @@ -760,9 +760,9 @@ func TestRun_NoActorEventSkippedWithoutRoster(t *testing.T) { } p := newTestPoller(mc, &stubMatcher{agents: []string{"code"}}, Options{ - TargetRepo: "acme/platform", - JiraBaseURL: "https://acme.atlassian.net", - JiraProject: "PROJ", + TargetRepo: "acme/platform", + JiraBaseURL: "https://acme.atlassian.net", + JiraProjects: []string{"PROJ"}, }) logBuf := captureLog(t) if err := p.Run(context.Background()); err == nil || !strings.Contains(err.Error(), "failed normalized-event validation") { @@ -808,9 +808,9 @@ func TestRunRoleLoadFailure_FailsCycle(t *testing.T) { } p := newTestPoller(mc, &stubMatcher{agents: []string{"code"}}, Options{ - TargetRepo: "acme/platform", - JiraBaseURL: "https://acme.atlassian.net", - JiraProject: "PROJ", + TargetRepo: "acme/platform", + JiraBaseURL: "https://acme.atlassian.net", + JiraProjects: []string{"PROJ"}, }) if err := p.Run(context.Background()); err == nil { @@ -846,7 +846,7 @@ func TestDetectChanges_EditedCommentAttributedToEditor(t *testing.T) { }, } - p := New(mc, nil, Options{TargetRepo: "acme/platform", JiraBaseURL: "https://acme.atlassian.net", JiraProject: "PROJ"}) + p := New(mc, nil, Options{TargetRepo: "acme/platform", JiraBaseURL: "https://acme.atlassian.net", JiraProjects: []string{"PROJ"}}) issue := jira.Issue{ ID: "10042", Key: "PROJ-123", @@ -903,7 +903,7 @@ func TestEditedComment_IsEntityAssigneeFollowsEditor(t *testing.T) { Author: jira.User{AccountID: tc.author, AccountType: "atlassian"}, UpdateAuthor: jira.User{AccountID: tc.editor, AccountType: "atlassian"}, }} - p := New(mc, nil, Options{TargetRepo: "acme/platform", JiraBaseURL: "https://acme.atlassian.net", JiraProject: "PROJ"}) + p := New(mc, nil, Options{TargetRepo: "acme/platform", JiraBaseURL: "https://acme.atlassian.net", JiraProjects: []string{"PROJ"}}) issue := jira.Issue{ ID: "10042", Key: "PROJ-123", @@ -957,7 +957,7 @@ func TestDetectChanges_CarriesAssignee(t *testing.T) { }, } - p := New(mc, nil, Options{TargetRepo: "acme/platform", JiraBaseURL: "https://acme.atlassian.net", JiraProject: "PROJ"}) + p := New(mc, nil, Options{TargetRepo: "acme/platform", JiraBaseURL: "https://acme.atlassian.net", JiraProjects: []string{"PROJ"}}) issue := jira.Issue{ ID: "10042", Key: "PROJ-123", @@ -1068,9 +1068,9 @@ func TestProcessIssue_CapsEventsPerIssue(t *testing.T) { mc.roleMembership = map[string]string{"u1": "Developers"} p := newTestPoller(mc, &stubMatcher{agents: []string{"triage"}}, Options{ - TargetRepo: "acme/platform", - JiraBaseURL: "https://acme.atlassian.net", - JiraProject: "PROJ", + TargetRepo: "acme/platform", + JiraBaseURL: "https://acme.atlassian.net", + JiraProjects: []string{"PROJ"}, }) if _, err := p.processIssue(context.Background(), jira.Issue{ ID: "10042", @@ -1135,10 +1135,10 @@ func TestRunLabelChange(t *testing.T) { router := &stubMatcher{agents: []string{"code"}} p := newTestPoller(mc, router, Options{ - TargetRepo: "acme/platform", - JiraBaseURL: "https://acme.atlassian.net", - JiraProject: "PROJ", - OutputPath: outputPath, + TargetRepo: "acme/platform", + JiraBaseURL: "https://acme.atlassian.net", + JiraProjects: []string{"PROJ"}, + OutputPath: outputPath, }) if err := p.Run(context.Background()); err != nil { @@ -1203,10 +1203,10 @@ func TestRunBotFiltering(t *testing.T) { router := &stubMatcher{agents: []string{"triage"}} p := newTestPoller(mc, router, Options{ - TargetRepo: "acme/platform", - JiraBaseURL: "https://acme.atlassian.net", - JiraProject: "PROJ", - OutputPath: outputPath, + TargetRepo: "acme/platform", + JiraBaseURL: "https://acme.atlassian.net", + JiraProjects: []string{"PROJ"}, + OutputPath: outputPath, }) if err := p.Run(context.Background()); err != nil { @@ -1286,10 +1286,10 @@ func TestRunSelfAuthoredEventsFiltered(t *testing.T) { router := &stubMatcher{agents: []string{"triage"}} p := newTestPoller(mc, router, Options{ - TargetRepo: "acme/platform", - JiraBaseURL: "https://acme.atlassian.net", - JiraProject: "PROJ", - OutputPath: outputPath, + TargetRepo: "acme/platform", + JiraBaseURL: "https://acme.atlassian.net", + JiraProjects: []string{"PROJ"}, + OutputPath: outputPath, }) if err := p.Run(context.Background()); err != nil { @@ -1398,10 +1398,10 @@ func TestRunHumanFollowupAlongsideSelfAuthored(t *testing.T) { router := &stubMatcher{agents: []string{"triage"}} p := newTestPoller(mc, router, Options{ - TargetRepo: "acme/platform", - JiraBaseURL: "https://acme.atlassian.net", - JiraProject: "PROJ", - OutputPath: outputPath, + TargetRepo: "acme/platform", + JiraBaseURL: "https://acme.atlassian.net", + JiraProjects: []string{"PROJ"}, + OutputPath: outputPath, }) if err := p.Run(context.Background()); err != nil { @@ -1509,10 +1509,10 @@ func TestRunLockContention(t *testing.T) { router := &stubMatcher{agents: []string{"triage"}} p := newTestPoller(mc, router, Options{ - TargetRepo: "acme/platform", - JiraBaseURL: "https://acme.atlassian.net", - JiraProject: "PROJ", - OutputPath: outputPath, + TargetRepo: "acme/platform", + JiraBaseURL: "https://acme.atlassian.net", + JiraProjects: []string{"PROJ"}, + OutputPath: outputPath, }) if err := p.Run(context.Background()); err != nil { @@ -1577,7 +1577,7 @@ func TestRunStaleLock(t *testing.T) { p := newTestPoller(mc, router, Options{ TargetRepo: "acme/platform", JiraBaseURL: "https://acme.atlassian.net", - JiraProject: "PROJ", + JiraProjects: []string{"PROJ"}, OutputPath: outputPath, StaleThreshold: 15 * time.Minute, }) @@ -1685,13 +1685,19 @@ func TestFilterLockedErrorsWhenAllLockReadsFail(t *testing.T) { // against JQL injection even though the key is already validated upstream. func TestSearchCandidatesQuotesProjectKey(t *testing.T) { mc := newMockClient() - p := newTestPoller(mc, nil, Options{JiraProject: "PROJ"}) + p := newTestPoller(mc, nil, Options{JiraProjects: []string{"PROJ"}}) - if _, err := p.searchCandidates(context.Background()); err != nil { + jql, err := p.searchJQL() + if err != nil { + t.Fatalf("searchJQL() error: %v", err) + } + if _, err := p.searchCandidates(context.Background(), jql); err != nil { t.Fatalf("searchCandidates() error: %v", err) } - want := `project = "PROJ" AND statusCategory != Done ORDER BY updated DESC` + // The default predicate is config.DefaultJiraPollQuery, scoped exactly + // as the CLI's tracker.jira.poll default is. + want := `project = "PROJ" AND (statusCategory != Done) ORDER BY updated DESC` if mc.lastQuery != want { t.Errorf("JQL = %q, want %q", mc.lastQuery, want) } @@ -1706,9 +1712,9 @@ func TestSearchCandidatesBoundsBySettingM(t *testing.T) { for i := range mc.searchResult { mc.searchResult[i] = jira.Issue{ID: fmt.Sprintf("%d", i+1), Key: fmt.Sprintf("PROJ-%d", i+1)} } - p := newTestPoller(mc, nil, Options{JiraProject: "PROJ", M: 50}) + p := newTestPoller(mc, nil, Options{JiraProjects: []string{"PROJ"}, M: 50}) - candidates, err := p.searchCandidates(context.Background()) + candidates, err := p.searchCandidates(context.Background(), `project = "PROJ"`) if err != nil { t.Fatalf("searchCandidates() error: %v", err) } @@ -1758,10 +1764,10 @@ func TestRunNoChangesSinceLastCheck(t *testing.T) { router := &stubMatcher{agents: []string{"triage"}} p := newTestPoller(mc, router, Options{ - TargetRepo: "acme/platform", - JiraBaseURL: "https://acme.atlassian.net", - JiraProject: "PROJ", - OutputPath: outputPath, + TargetRepo: "acme/platform", + JiraBaseURL: "https://acme.atlassian.net", + JiraProjects: []string{"PROJ"}, + OutputPath: outputPath, }) if err := p.Run(context.Background()); err != nil { @@ -1830,10 +1836,10 @@ func TestRunMultipleEvents(t *testing.T) { router := &stubMatcher{agents: []string{"triage"}} p := newTestPoller(mc, router, Options{ - TargetRepo: "acme/platform", - JiraBaseURL: "https://acme.atlassian.net", - JiraProject: "PROJ", - OutputPath: outputPath, + TargetRepo: "acme/platform", + JiraBaseURL: "https://acme.atlassian.net", + JiraProjects: []string{"PROJ"}, + OutputPath: outputPath, }) if err := p.Run(context.Background()); err != nil { @@ -2002,9 +2008,9 @@ func TestDetectChanges_FirstPoll(t *testing.T) { mc := newMockClient() p := New(mc, nil, Options{ - TargetRepo: "acme/platform", - JiraBaseURL: "https://acme.atlassian.net", - JiraProject: "PROJ", + TargetRepo: "acme/platform", + JiraBaseURL: "https://acme.atlassian.net", + JiraProjects: []string{"PROJ"}, }) issue := jira.Issue{ @@ -2055,9 +2061,9 @@ func TestDetectChanges_FirstPoll_BackfillWindow(t *testing.T) { } p := New(mc, nil, Options{ - TargetRepo: "acme/platform", - JiraBaseURL: "https://acme.atlassian.net", - JiraProject: "PROJ", + TargetRepo: "acme/platform", + JiraBaseURL: "https://acme.atlassian.net", + JiraProjects: []string{"PROJ"}, }) issue := jira.Issue{ @@ -2133,9 +2139,9 @@ func TestDetectChanges_EditedComment(t *testing.T) { } p := New(mc, nil, Options{ - TargetRepo: "acme/platform", - JiraBaseURL: "https://acme.atlassian.net", - JiraProject: "PROJ", + TargetRepo: "acme/platform", + JiraBaseURL: "https://acme.atlassian.net", + JiraProjects: []string{"PROJ"}, }) issue := jira.Issue{ @@ -2182,9 +2188,9 @@ func TestDetectChanges_FirstPoll_UnparseableCreated(t *testing.T) { mc := newMockClient() p := New(mc, nil, Options{ - TargetRepo: "acme/platform", - JiraBaseURL: "https://acme.atlassian.net", - JiraProject: "PROJ", + TargetRepo: "acme/platform", + JiraBaseURL: "https://acme.atlassian.net", + JiraProjects: []string{"PROJ"}, }) issue := jira.Issue{ @@ -2243,9 +2249,9 @@ func TestDetectChanges_CommentTimestampFallbacks(t *testing.T) { } p := New(mc, nil, Options{ - TargetRepo: "acme/platform", - JiraBaseURL: "https://acme.atlassian.net", - JiraProject: "PROJ", + TargetRepo: "acme/platform", + JiraBaseURL: "https://acme.atlassian.net", + JiraProjects: []string{"PROJ"}, }) issue := jira.Issue{ @@ -2315,9 +2321,9 @@ func TestDetectChanges_StatusChange(t *testing.T) { mc.statuses["Open"] = jira.Status{Name: "Open", StatusCategory: jira.StatusCategory{Key: "new"}} p := New(mc, nil, Options{ - TargetRepo: "acme/platform", - JiraBaseURL: "https://acme.atlassian.net", - JiraProject: "PROJ", + TargetRepo: "acme/platform", + JiraBaseURL: "https://acme.atlassian.net", + JiraProjects: []string{"PROJ"}, }) issue := jira.Issue{ @@ -2515,9 +2521,9 @@ func TestDetectChanges_UnsupportedFieldAdvancesMaxSeen(t *testing.T) { } p := New(mc, nil, Options{ - TargetRepo: "acme/platform", - JiraBaseURL: "https://acme.atlassian.net", - JiraProject: "PROJ", + TargetRepo: "acme/platform", + JiraBaseURL: "https://acme.atlassian.net", + JiraProjects: []string{"PROJ"}, }) issue := jira.Issue{ @@ -2669,10 +2675,10 @@ func TestRunFirstPoll_NoLockProperty(t *testing.T) { router := &stubMatcher{agents: []string{"triage"}} p := newTestPoller(mc, router, Options{ - TargetRepo: "acme/platform", - JiraBaseURL: "https://acme.atlassian.net", - JiraProject: "PROJ", - OutputPath: outputPath, + TargetRepo: "acme/platform", + JiraBaseURL: "https://acme.atlassian.net", + JiraProjects: []string{"PROJ"}, + OutputPath: outputPath, }) if err := p.Run(context.Background()); err != nil { @@ -2737,10 +2743,10 @@ func TestRunUnsupportedChangelogField_AdvancesLastCheck(t *testing.T) { router := &stubMatcher{agents: []string{"triage"}} p := newTestPoller(mc, router, Options{ - TargetRepo: "acme/platform", - JiraBaseURL: "https://acme.atlassian.net", - JiraProject: "PROJ", - OutputPath: outputPath, + TargetRepo: "acme/platform", + JiraBaseURL: "https://acme.atlassian.net", + JiraProjects: []string{"PROJ"}, + OutputPath: outputPath, }) if err := p.Run(context.Background()); err != nil { @@ -2826,10 +2832,10 @@ func TestRunPerActorGroupResolution(t *testing.T) { router := &stubMatcher{agents: []string{"triage"}} p := newTestPoller(mc, router, Options{ - TargetRepo: "acme/platform", - JiraBaseURL: "https://acme.atlassian.net", - JiraProject: "PROJ", - OutputPath: outputPath, + TargetRepo: "acme/platform", + JiraBaseURL: "https://acme.atlassian.net", + JiraProjects: []string{"PROJ"}, + OutputPath: outputPath, }) if err := p.Run(context.Background()); err != nil { @@ -2837,7 +2843,7 @@ func TestRunPerActorGroupResolution(t *testing.T) { } // Verify the actor was resolved to "write" (Developers role) via group. - if role, ok := p.roleMembership["group-member-user"]; !ok { + if role, ok := membershipOf(p, "PROJ")["group-member-user"]; !ok { t.Error("expected group-member-user to be in roleMembership") } else if role != "Developers" { t.Errorf("roleMembership[group-member-user] = %q, want %q", role, "Developers") @@ -2917,17 +2923,17 @@ func TestRunPerActorGroupResolution_HighestPriorityWins(t *testing.T) { } p := newTestPoller(mc, &stubMatcher{agents: []string{"triage"}}, Options{ - TargetRepo: "acme/platform", - JiraBaseURL: "https://acme.atlassian.net", - JiraProject: "PROJ", - OutputPath: filepath.Join(t.TempDir(), "dispatches.json"), + TargetRepo: "acme/platform", + JiraBaseURL: "https://acme.atlassian.net", + JiraProjects: []string{"PROJ"}, + OutputPath: filepath.Join(t.TempDir(), "dispatches.json"), }) if err := p.Run(context.Background()); err != nil { t.Fatalf("Run() error: %v", err) } - if role := p.roleMembership["dual-group-user"]; role != "Administrators" { + if role := membershipOf(p, "PROJ")["dual-group-user"]; role != "Administrators" { t.Errorf("roleMembership[dual-group-user] = %q, want %q (highest priority)", role, "Administrators") } } @@ -2978,17 +2984,17 @@ func TestRunPerActorGroupResolution_DirectPlusGroupPriority(t *testing.T) { } p := newTestPoller(mc, &stubMatcher{agents: []string{"triage"}}, Options{ - TargetRepo: "acme/platform", - JiraBaseURL: "https://acme.atlassian.net", - JiraProject: "PROJ", - OutputPath: filepath.Join(t.TempDir(), "dispatches.json"), + TargetRepo: "acme/platform", + JiraBaseURL: "https://acme.atlassian.net", + JiraProjects: []string{"PROJ"}, + OutputPath: filepath.Join(t.TempDir(), "dispatches.json"), }) if err := p.Run(context.Background()); err != nil { t.Fatalf("Run() error: %v", err) } - if role := p.roleMembership["dev-and-admin-user"]; role != "Administrators" { + if role := membershipOf(p, "PROJ")["dev-and-admin-user"]; role != "Administrators" { t.Errorf("roleMembership[dev-and-admin-user] = %q, want %q (direct Developers + group Administrators should upgrade)", role, "Administrators") } } @@ -3033,17 +3039,17 @@ func TestRunPerActorGroupResolution_NoGroupMatch(t *testing.T) { } p := newTestPoller(mc, &stubMatcher{agents: []string{"triage"}}, Options{ - TargetRepo: "acme/platform", - JiraBaseURL: "https://acme.atlassian.net", - JiraProject: "PROJ", - OutputPath: filepath.Join(t.TempDir(), "dispatches.json"), + TargetRepo: "acme/platform", + JiraBaseURL: "https://acme.atlassian.net", + JiraProjects: []string{"PROJ"}, + OutputPath: filepath.Join(t.TempDir(), "dispatches.json"), }) if err := p.Run(context.Background()); err != nil { t.Fatalf("Run() error: %v", err) } - if _, ok := p.roleMembership["outsider-user"]; ok { + if _, ok := membershipOf(p, "PROJ")["outsider-user"]; ok { t.Error("expected outsider-user to NOT be in roleMembership") } } @@ -3115,10 +3121,10 @@ func TestRunPerActorGroupResolution_APIError(t *testing.T) { } p := newTestPoller(mc, &stubMatcher{agents: []string{"triage"}}, Options{ - TargetRepo: "acme/platform", - JiraBaseURL: "https://acme.atlassian.net", - JiraProject: "PROJ", - OutputPath: filepath.Join(t.TempDir(), "dispatches.json"), + TargetRepo: "acme/platform", + JiraBaseURL: "https://acme.atlassian.net", + JiraProjects: []string{"PROJ"}, + OutputPath: filepath.Join(t.TempDir(), "dispatches.json"), }) // Should fail closed: even one actor's lookup failure fails this @@ -3129,7 +3135,7 @@ func TestRunPerActorGroupResolution_APIError(t *testing.T) { } // group-user-fail should NOT be in roleMembership (API failed). - if _, ok := p.roleMembership["group-user-fail"]; ok { + if _, ok := membershipOf(p, "PROJ")["group-user-fail"]; ok { t.Error("expected group-user-fail to NOT be in roleMembership after API error") } } @@ -3170,10 +3176,10 @@ func TestRunPerActorGroupResolution_AllActorsAPIError(t *testing.T) { } p := newTestPoller(mc, &stubMatcher{agents: []string{"triage"}}, Options{ - TargetRepo: "acme/platform", - JiraBaseURL: "https://acme.atlassian.net", - JiraProject: "PROJ", - OutputPath: filepath.Join(t.TempDir(), "dispatches.json"), + TargetRepo: "acme/platform", + JiraBaseURL: "https://acme.atlassian.net", + JiraProjects: []string{"PROJ"}, + OutputPath: filepath.Join(t.TempDir(), "dispatches.json"), }) // Should fail because ALL actors have errors and only 1 issue → all failed. diff --git a/internal/jirapoll/types.go b/internal/jirapoll/types.go index 61b1cdda92..53107838ab 100644 --- a/internal/jirapoll/types.go +++ b/internal/jirapoll/types.go @@ -60,8 +60,8 @@ type Options struct { GitLabURL string // GitLab instance URL when TargetForge is TargetForgeGitLab; part of the coordination namespace Dispatcher RecordDispatcher // Optional output driver that schedules records directly (GitLab) JiraBaseURL string // Jira instance base URL - JiraProject string // Jira project key for default JQL - JQL string // Custom JQL override + JiraProjects []string // Jira project keys every search is scoped to; required, non-empty, no duplicates + JQL string // JQL predicate (optionally with a trailing ORDER BY) scoped to JiraProjects; empty means config.DefaultJiraPollQuery OutputPath string // Path to write dispatch records JSON M int // Max candidate issues per cycle (default: 50) N int // Max issues to process per cycle (default: 5) diff --git a/pkg/behaviourtest/steps/jirapoll.go b/pkg/behaviourtest/steps/jirapoll.go index adf095813b..35c416f45e 100644 --- a/pkg/behaviourtest/steps/jirapoll.go +++ b/pkg/behaviourtest/steps/jirapoll.go @@ -232,11 +232,11 @@ func whenJiraPollerRuns(ctx context.Context, w *world.World) error { outputPath := filepath.Join(w.JiraConfigDir, "dispatches.json") opts := jirapoll.Options{ - TargetRepo: "test-org/test-repo", - JiraBaseURL: w.JiraMockServer.URL, - JiraProject: "PROJ", - OutputPath: outputPath, - N: 50, // process all candidates + TargetRepo: "test-org/test-repo", + JiraBaseURL: w.JiraMockServer.URL, + JiraProjects: []string{"PROJ"}, + OutputPath: outputPath, + N: 50, // process all candidates } poller := jirapoll.New(jiraClient, matcher, opts) diff --git a/pkg/behaviourtest/steps/jirapoll_transport.go b/pkg/behaviourtest/steps/jirapoll_transport.go index 212694e4fa..a31eae41db 100644 --- a/pkg/behaviourtest/steps/jirapoll_transport.go +++ b/pkg/behaviourtest/steps/jirapoll_transport.go @@ -328,12 +328,12 @@ func whenJiraGitLabPollerRuns(ctx context.Context, w *world.World) error { // so it names the pretend Atlassian instance, not the mock // server the client below talks to (same split // jira_lifecycle_test.go uses). - JiraBaseURL: "https://acme.atlassian.net", - JiraProject: "PROJ", - N: 50, // process all candidates - TargetForge: jirapoll.TargetForgeGitLab, - GitLabURL: "https://gitlab.example.com", - Dispatcher: jiradispatch.GitLabDispatcher{Poller: glPoller}, + JiraBaseURL: "https://acme.atlassian.net", + JiraProjects: []string{"PROJ"}, + N: 50, // process all candidates + TargetForge: jirapoll.TargetForgeGitLab, + GitLabURL: "https://gitlab.example.com", + Dispatcher: jiradispatch.GitLabDispatcher{Poller: glPoller}, } poller := jirapoll.New(jiraClient, matcher, opts) if err := poller.Run(ctx); err != nil { From 1ecce65b771ac66b5a3ed32802aab8f6004821bc Mon Sep 17 00:00:00 2001 From: fullsend-fix <278716306+fullsend-ai-coder[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 11:10:00 +0000 Subject: [PATCH 2/2] docs(#9883): update jira poll adapter project-key validation note on PR #9887 Rewrite the stale searchCandidates reference: project-set validation now runs via validateProjectSet on every cycle. Not addressed: the config import in internal/jirapoll is a disclosed interim step until the helpers move to a neutral package. Addresses #9887 Co-Authored-By: Claude Sonnet 5.5 --- docs/normative/normalized-event/v1/jira-poll-adapter.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/normative/normalized-event/v1/jira-poll-adapter.md b/docs/normative/normalized-event/v1/jira-poll-adapter.md index 4693efed63..7398d11277 100644 --- a/docs/normative/normalized-event/v1/jira-poll-adapter.md +++ b/docs/normative/normalized-event/v1/jira-poll-adapter.md @@ -35,9 +35,10 @@ deployment. The config gate's `jiraProjectKeyRe` accepts single-character project keys, and the CLI always scopes the query to the project, so such a project is polled on the default query too: every one of its events fails validation and the all-invalid guard fails each cycle (see the Jira guide's -troubleshooting table). The project-key check inside `searchCandidates` runs -only when no JQL is set at all — direct API use such as the behaviour-test -step, not the CLI — so it never intercepts these keys. +troubleshooting table). The poller's project-set validation +(`validateProjectSet`, via `config.ValidJiraProjectKey`) runs on every cycle +and accepts the same keys as the config gate, so it never intercepts +single-character keys. One further consumer has no downstream key check: `fullsend dispatch --input-driver json` (or `--route ` with a JSON event) validates the key at parse time, so it now rejects such a key instead of printing a route