gitlab-triage 1.58.0 → 1.59.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 8a6d5407a6cccbf8711ab5d9e6cfd060165831e32880681257a6d12ed2290df3
4
- data.tar.gz: 30aca49b70d3c65f56fcb5cd34275d6aad83aea62f54b683d1196af54c8c312a
3
+ metadata.gz: f0eb4b3c4c796bca65d1ec29040c8a7963cbdc4f9a7a2aca442819dd18e9473e
4
+ data.tar.gz: 5d39d860952878d6843c430e216308d72d6457cb077d4731267597832b4eb32b
5
5
  SHA512:
6
- metadata.gz: ba6a0e711a7c06f6c99f1af0471d68cd7c335dbfd53d5456f571414e79ce6c9454f6e9df0379ff89fdb57f155f8947cde33ce164ee19766f75c75f89cc8df345
7
- data.tar.gz: da23490510ce31cf2abb2ece62189c9d464421ef15be0b07a44245fce4619afb0df52216674759a9dd07c2d07a7284b00fde9ef66e252c5e1a9e43fb81635c81
6
+ metadata.gz: a20e94634c5849d85e93018377672bb5070dcebe504fa5bb309ed2fd2027ccd54057be3efa9c44b3ca2e7bbe3657ce2994fd479d8017f90f70ed0f9f8acd6fac
7
+ data.tar.gz: 8a127ec91870fae1afa0337880593390ca3430506b715bcf99c948c0c0cd6a8ad74343c832624b687f20664953a86e7f31afbd5ee1fa691056ee0e6c959edeb7
data/.gitlab/CODEOWNERS CHANGED
@@ -1 +1 @@
1
- * @gl-dx
1
+ * @gl-dx/development-health @@maintainer
data/Gemfile.lock CHANGED
@@ -1,7 +1,7 @@
1
1
  PATH
2
2
  remote: .
3
3
  specs:
4
- gitlab-triage (1.58.0)
4
+ gitlab-triage (1.59.0)
5
5
  activesupport (>= 5.1)
6
6
  globalid (~> 1.0, >= 1.0.1)
7
7
  graphql (>= 2.4.13, < 2.7.0)
@@ -161,7 +161,7 @@ GEM
161
161
  method_source (~> 1.0)
162
162
  public_suffix (6.0.2)
163
163
  racc (1.8.0)
164
- rack (3.2.7)
164
+ rack (3.2.8)
165
165
  rainbow (3.1.1)
166
166
  rake (13.2.1)
167
167
  rb-fsevent (0.11.2)
data/README.md CHANGED
@@ -221,6 +221,20 @@ Sent to the Work Items REST API:
221
221
 
222
222
  Dry-run a rule that uses `upcoming` or `started` before moving it from
223
223
  `issues` to `work_items`.
224
+ - `weight` - a whole number of 0 or more, quoted or not, or `none` or `any`
225
+ (case-insensitive). Maps to the `weight` or `weight_wildcard_id` filter.
226
+ Anything else is rejected at load time. `none` matches only work items with no
227
+ weight set, and 0 is a weight, so a work item weighted 0 matches `any` and
228
+ `0` but not `none`. The API documents weight filtering as Premium and Ultimate
229
+ only. On GitLab Community Edition the API doesn't have the filter and ignores
230
+ it, so the rule matches work items of any weight.
231
+ - `iteration` - `none` or `any` (case-insensitive). Maps to the
232
+ `iteration_wildcard_id` filter. Unlike on `issues`, an iteration name is
233
+ rejected at load time, because the Work Items REST API can't filter by
234
+ iteration name. Anything else is rejected at load time too. The API documents
235
+ iteration filtering as Premium and Ultimate only. On GitLab Community Edition
236
+ the API doesn't have the filter and ignores it, so the rule matches work items
237
+ in any iteration or none.
224
238
  - `date` - `created_at` / `updated_at` staleness (same shape as the
225
239
  [date condition](#date-condition)). `attribute`, `condition`,
226
240
  `interval_type`, and `interval` are all required and checked at load time,
@@ -237,8 +251,8 @@ Run in Ruby on the fetched work items:
237
251
  - `no_additional_labels` - see [no additional labels condition](#no-additional-labels-condition).
238
252
  - `work_item_status` - see [work item status condition](#work-item-status-condition).
239
253
 
240
- Any other condition key (for example `issue_type`, `weight`, or a misspelled
241
- key) is rejected at load time, before any resource is fetched, with an error
254
+ Any other condition key (for example `issue_type` or a misspelled key) is
255
+ rejected at load time, before any resource is fetched, with an error
242
256
  listing the supported conditions. Ignoring it instead would make the rule match
243
257
  more work items than intended. `votes`, `upvotes`, and `discussions` are not
244
258
  supported yet (tracked in
@@ -254,13 +268,36 @@ supported yet (tracked in
254
268
  - `assignees` - set assignees by username. If any requested username does not
255
269
  exist, the automation stops immediately rather than sending an empty
256
270
  assignee set (which would unassign everyone).
271
+ - `state` - close the work item with `state: close` or reopen it with
272
+ `state: reopen`, the same values as the `status` action on `issues`. The
273
+ `state` condition still takes `opened` and `closed`, so a rule that closes
274
+ open work items has `state: opened` in its conditions and `state: close` in
275
+ its actions. On `work_items`, `status` is reserved for the configurable work
276
+ item status, so `status: close` and `status: reopen` are rejected with a
277
+ pointer to `state`.
278
+ - The state change runs last, in its own update, after the rule's label,
279
+ assignee, and comment actions. If a label or assignee change fails, or the
280
+ note request keeps failing with 429 or 500 after retries, the run stops
281
+ before the state changes, so the next run retries it. Any other note error
282
+ (for example a 403 or 503) is reported as a warning, and the state still
283
+ changes.
284
+ - If the state change fails on some work items, the others still change
285
+ state, and then the run stops with an error that lists the failed ones. A
286
+ failed work item still matches the rule, so with `comment` it gets the
287
+ note again on each run until the cause is fixed.
288
+ - In a rule without `comment` or `mention`, work items already in the
289
+ requested state are skipped.
290
+ - Where configurable work item status is available, closing or reopening
291
+ also moves the status to its lifecycle default, for example the default
292
+ closed status.
257
293
  - `comment` - post a comment (note) on the work item through the Work Items REST
258
294
  API. Supports the same body templating as the `issues` type, along with
259
295
  `mention`, `comment_type: thread`, `comment_internal`, and
260
296
  `redact_confidential_resources`. The `{{closed_by}}` placeholder needs
261
297
  GitLab 19.6 or later. Quick actions in the body are run by the API, but the
262
298
  available command set follows the work item type's enabled widgets, so some
263
- issue-only commands are no-ops on work items.
299
+ issue-only commands are no-ops on work items. The comment is posted before the
300
+ `state` action runs, so `state` wins over a `/close` or `/reopen` in the body.
264
301
 
265
302
  Summaries are also supported (`summarize` and `comment_on_summary`). Any other
266
303
  action key (for example `move` or `status`) is rejected at load time with an
@@ -269,9 +306,9 @@ error listing the supported actions, since those actions are not wired for the
269
306
 
270
307
  Actions require a token with sufficient permissions (Planner or Reporter role
271
308
  and above). The update endpoint can return success without persisting a change
272
- when the token lacks permission, so after each update the applied labels and
273
- assignees are read back from the response and the run raises if the change was
274
- not reflected.
309
+ when the token lacks permission, so after each update the applied labels,
310
+ assignees, and state are read back from the response and the run raises if the
311
+ change was not reflected.
275
312
 
276
313
  The `work_items` type works against both project and group sources
277
314
  (`--source projects` or `--source groups`). Fetches use the source you run
@@ -288,6 +325,31 @@ Community Edition or a namespace without the license for health status. After a
288
325
  license downgrade, work items can keep a stored health status that the API no
289
326
  longer returns, so a rule such as `resource[:health_status] != 'at_risk'` can
290
327
  match work items that are at risk.
328
+ `resource[:description]` is the work item's description in Markdown, the same as
329
+ on `issues`.
330
+
331
+ `resource[:moved_to_id]` and `resource[:moved_to_work_item_url]` are the id and
332
+ URL of the work item it was moved to, so rules that skip moved items with
333
+ `resource[:moved_to_id].nil?` work the same as on `issues`. `moved_to_id` needs
334
+ GitLab 19.6 or later. Earlier versions leave out fields they do not support
335
+ without an error, so `moved_to_id` would be `nil` for every work item.
336
+ `moved_to_work_item_url` works on earlier versions too. When a `work_items`
337
+ rule or summary rule has a `ruby` condition that reads `moved_to_id`,
338
+ `gitlab-triage` checks the GitLab version before running any rule in that
339
+ policy file. On an older version, it stops with an error naming those
340
+ rules. If it cannot read the version, for example because the version request
341
+ fails with a server error or returns a page that isn't JSON, it prints a
342
+ warning and instead stops when one of those rules fetches work items that have
343
+ no `moved_to_id`, so rules before it in the file have already run. An
344
+ unauthorized token still stops the run. Templates and other conditions that
345
+ read `moved_to_id` are not checked, and on older versions they read `nil`.
346
+
347
+ On `issues`, `moved_to_id` is set for every moved issue. On `work_items`,
348
+ `moved_to_id` and `moved_to_work_item_url` are set only when the token can read
349
+ the work item it was moved to. Otherwise they're `nil`, so
350
+ `resource[:moved_to_id].nil?` also matches work items moved to a project the
351
+ token can't read. Run such rules on GitLab 19.6 or later, with a token that can
352
+ read the projects work items are moved to.
291
353
 
292
354
  The `api:` field is not applicable to the `work_items` type, since the type
293
355
  already fixes the transport to the Work Items REST API.
@@ -296,13 +358,18 @@ already fixes the transport to the Work Items REST API.
296
358
 
297
359
  The `work_items` condition names (`type`, `status`, `state`) are deliberately
298
360
  cleaner than the `issues` equivalents (`issue_type`, `work_item_status`,
299
- `state`). This is intentional: they are meant to become the shared vocabulary
300
- that `issues` converges onto over time (long term, `issues` would alias to
301
- `work_items` and eventually deprecate in a major version), not a throwaway
302
- parallel dialect. `state` (`opened` / `closed`) already means the same on both
303
- types; `status` is new on `work_items` and has no clean one-to-one equivalent
304
- on `issues` (where it is the prefixed `work_item_status`). Whether the old
305
- names are carried as aliases or dropped at a major bump is a future decision.
361
+ `state`). `issues` keeps its names as they are. It is planned to be deprecated,
362
+ and then removed in a major version once `work_items` has feature parity
363
+ (tracked in
364
+ [gitlab-org/gitlab#634685](https://gitlab.com/gitlab-org/gitlab/-/work_items/634685)).
365
+ `state` (`opened` / `closed`) means the same on both types. `status` is new on
366
+ `work_items` and has no clean one-to-one equivalent on `issues` (where it is the
367
+ prefixed `work_item_status`).
368
+
369
+ The same applies to actions. On `issues`, the `status` action closes or reopens
370
+ the item (`status: close` / `status: reopen`). On `work_items`, that is the
371
+ `state` action with the same values (`state: close` / `state: reopen`), and
372
+ `status` is reserved for the configurable work item status.
306
373
 
307
374
  ### Fields
308
375
 
@@ -1173,6 +1240,10 @@ Changes the open or closed state of the resource.
1173
1240
  This sets the open or closed state, not the work item lifecycle status. To
1174
1241
  change work item status, see the [`work_item_status` action](#work-item-status-action).
1175
1242
 
1243
+ On the `work_items` type, use the [`state` action](#supported-actions) with the
1244
+ same values (`state: close` / `state: reopen`). There, `status` is reserved for
1245
+ the configurable work item status.
1246
+
1176
1247
  Accepts a string.
1177
1248
 
1178
1249
  | State transition | Type | Value |
@@ -0,0 +1,79 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'work_item'
4
+
5
+ module Gitlab
6
+ module Triage
7
+ module Action
8
+ # Sends state_event in its own PATCH, after WorkItem and WorkItemComment.
9
+ # In one combined PATCH GitLab closes first, so a dropped label or
10
+ # assignee would leave the item closed and never matched again.
11
+ class WorkItemState < WorkItem
12
+ STATES_AFTER_EVENT = { 'close' => 'closed', 'reopen' => 'opened' }.freeze
13
+
14
+ # Without this, const_get(:Dry) would resolve to WorkItem::Dry.
15
+ class Dry < WorkItemState
16
+ def act
17
+ puts "The following work items would change state for the rule **#{policy.name}**:\n\n"
18
+
19
+ super
20
+ end
21
+
22
+ private
23
+
24
+ def perform(resource)
25
+ puts "# #{resource[:web_url]}"
26
+ puts "Would #{state_event} the work item\n\n"
27
+ end
28
+ end
29
+
30
+ def verify!; end
31
+
32
+ def act
33
+ return unless state_event
34
+
35
+ failures = policy.resources.filter_map do |resource|
36
+ # A no-op close still bumps updated_at. A comment's quick action can
37
+ # change the state after the fetch, so only skip without a comment.
38
+ next if resource[:state] == target_state && !policy.comment?
39
+
40
+ perform(resource)
41
+ nil
42
+ rescue UpdateNotAppliedError => e
43
+ e.message
44
+ end
45
+
46
+ raise UpdateNotAppliedError, failures.join("\n") if failures.any?
47
+ end
48
+
49
+ private
50
+
51
+ # `fields: state` makes the response echo the resulting state.
52
+ def perform(resource)
53
+ response = source.update(resource, {}, { state_event: state_event, fields: 'state' })
54
+
55
+ verify_state_applied!(resource, response)
56
+ end
57
+
58
+ def state_event
59
+ policy.actions[:state]&.to_s
60
+ end
61
+
62
+ def target_state
63
+ STATES_AFTER_EVENT.fetch(state_event)
64
+ end
65
+
66
+ # A rejected PATCH returns an error body with no state, so show the API's
67
+ # reason when there is one instead of always blaming permissions.
68
+ def verify_state_applied!(resource, response)
69
+ return if response[:state] == target_state
70
+
71
+ reason = response[:message] || response[:error] || 'the token may lack permission'
72
+
73
+ raise UpdateNotAppliedError,
74
+ "State was not set to #{target_state} on #{resource[:web_url]} (#{reason})."
75
+ end
76
+ end
77
+ end
78
+ end
79
+ end
@@ -8,6 +8,7 @@ require_relative 'action/delete'
8
8
  require_relative 'action/work_item_status'
9
9
  require_relative 'action/work_item'
10
10
  require_relative 'action/work_item_comment'
11
+ require_relative 'action/work_item_state'
11
12
  require_relative 'action/update'
12
13
 
13
14
  module Gitlab
@@ -36,17 +37,20 @@ module Gitlab
36
37
 
37
38
  # Work items are fetched and updated through the Work Items REST API,
38
39
  # which does not share the issues note/quick-action write path. Their
39
- # actions are handled by dedicated actions: WorkItem (assign, label) and
40
+ # actions are handled by dedicated actions: WorkItem (assign, label),
40
41
  # WorkItemComment, which posts through the REST notes endpoint rather than
41
- # the issues Comment path. Unlike issues, labels are written before the
42
- # note: a failed label write then loses a note once, instead of leaving
43
- # unlabeled items that get the note again on every run.
42
+ # the issues Comment path, and WorkItemState. Unlike issues, labels are
43
+ # written before the note: a failed label write then loses a note once,
44
+ # instead of leaving unlabeled items that get the note again on every run.
45
+ # State goes last, so a label, assignee, or note write that raises leaves
46
+ # the item matching the rule, and the next run retries it.
44
47
  def self.actions_for(policy)
45
48
  if policy.type == 'work_items'
46
49
  [
47
50
  [Summarize, policy.summarize?],
48
51
  [WorkItem, policy.work_item?],
49
52
  [WorkItemComment, policy.comment?],
53
+ [WorkItemState, policy.work_item_state?],
50
54
  [CommentOnSummary, policy.comment_on_summary?]
51
55
  ]
52
56
  else
@@ -76,7 +76,7 @@ module Gitlab
76
76
  work_items: Validators::PolicyValidator::WORK_ITEM_STATES
77
77
  }.with_indifferent_access.freeze
78
78
  MILESTONE_TIMEBOX_VALUES = MilestoneWildcards::VALUES
79
- ITERATION_SELECTION_VALUES = %w[none any].freeze
79
+ ITERATION_SELECTION_VALUES = Validators::PolicyValidator::ITERATION_WILDCARDS
80
80
  EpicsTriagingForProjectImpossibleError = Class.new(StandardError)
81
81
  MultiPolicyInInjectionModeError = Class.new(StandardError)
82
82
 
@@ -100,6 +100,7 @@ module Gitlab
100
100
 
101
101
  def perform
102
102
  Validators::PolicyValidator.new(resource_rules).validate!
103
+ assert_moved_to_supported!
103
104
 
104
105
  puts "Performing a dry run.\n\n" if options.dry_run
105
106
 
@@ -224,6 +225,13 @@ module Gitlab
224
225
  raise EpicsTriagingForProjectImpossibleError, "Epics can only be triaged at the group level. Please set the `--source groups` option."
225
226
  end
226
227
 
228
+ def assert_moved_to_supported!
229
+ work_items_definition = resource_rules[:work_items]
230
+ return if work_items_definition.blank? || !right_resource_type_for_resource_option?('work_items')
231
+
232
+ work_items_source.assert_moved_to_supported!(work_items_definition)
233
+ end
234
+
227
235
  def resource_rules
228
236
  @resource_rules ||= policies.delete(:resource_rules) { {} }
229
237
  end
@@ -450,7 +458,7 @@ module Gitlab
450
458
  end
451
459
 
452
460
  def fetch_resources(resource_type, expanded_conditions, rule_definition)
453
- return fetch_work_items(expanded_conditions) if resource_type == 'work_items'
461
+ return fetch_work_items(expanded_conditions, rule_definition) if resource_type == 'work_items'
454
462
 
455
463
  resources = []
456
464
 
@@ -514,13 +522,13 @@ module Gitlab
514
522
  resources
515
523
  end
516
524
 
517
- def fetch_work_items(expanded_conditions)
525
+ def fetch_work_items(expanded_conditions, rule_definition)
518
526
  conditions = expanded_conditions.dup
519
527
  conditions[:iids] = options.resource_reference[1..] if options.resource_reference
520
528
 
521
529
  # The work_items path bypasses build_get_url, so `state` is not checked by
522
530
  # the URL builders. PolicyValidator checks it in #perform before any fetch.
523
- work_items_source.list(conditions)
531
+ work_items_source.list(conditions, rule_definition)
524
532
  end
525
533
 
526
534
  def attach_resource_type(resources, resource_type)
@@ -23,6 +23,7 @@ module Gitlab
23
23
  iid: resource[:iid],
24
24
  web_url: resource[:web_url],
25
25
  title: resource[:title],
26
+ description: features.dig(:description, :description),
26
27
  state: resource[:state],
27
28
  confidential: resource[:confidential],
28
29
  created_at: resource[:created_at],
@@ -30,6 +31,8 @@ module Gitlab
30
31
  closed_at: resource[:closed_at],
31
32
  author: resource[:author],
32
33
  closed_by: resource[:closed_by],
34
+ moved_to_id: resource[:moved_to_id],
35
+ moved_to_work_item_url: resource[:moved_to_work_item_url],
33
36
  # Same shape as the Issues API, which full_resource_reference and
34
37
  # the {{full_reference}} placeholder read.
35
38
  references: ({ full: resource[:reference] } if resource[:reference]),
@@ -83,6 +83,10 @@ module Gitlab
83
83
  (actions.keys.map(&:to_sym) & %i[labels remove_labels assignees]).any?
84
84
  end
85
85
 
86
+ def work_item_state?
87
+ actions.key?(:state)
88
+ end
89
+
86
90
  def build_issue
87
91
  raise NotImplementedError
88
92
  end
@@ -7,6 +7,7 @@ require_relative '../url_builders/url_builder'
7
7
  require_relative '../normalizers/work_item_normalizer'
8
8
  require_relative '../errors'
9
9
  require_relative '../ui'
10
+ require_relative '../resource/instance_version'
10
11
  require_relative '../validators/policy_validator'
11
12
 
12
13
  module Gitlab
@@ -27,10 +28,22 @@ module Gitlab
27
28
  UnavailableError = Class.new(StandardError)
28
29
  ScopeError = Class.new(StandardError)
29
30
  NoteNotCreatedError = Class.new(StandardError)
31
+ UnsupportedVersionError = Class.new(StandardError)
32
+
33
+ MOVED_TO_ID_MINIMUM_VERSION = '19.6'
34
+ # moved_to_work_item_url is returned before 19.6 too, so only moved_to_id is checked.
35
+ MOVED_TO_ID_PATTERN = /\bmoved_to_id\b/
30
36
 
31
37
  # Base fields opted into on the list endpoint. The endpoint is sparse
32
38
  # by default (id, iid, global_id, title only); every field a filter or
33
39
  # template reads must be requested here or it comes back nil.
40
+ # Up to 19.5, GitLab drops a field it does not know without an error, so there
41
+ # moved_to_id (https://gitlab.com/gitlab-org/gitlab/-/merge_requests/266007)
42
+ # comes back nil for every work item, moved or not. Since 19.6 an unknown
43
+ # field or feature fails the whole list request with a 400.
44
+ # moved_to_id is an integer here, where the work items GraphQL API returns a
45
+ # WorkItem global ID. Both work items APIs return nil when the token cannot
46
+ # read the target; the Issues REST API returns it regardless.
34
47
  LIST_FIELDS = %w[
35
48
  state
36
49
  confidential
@@ -43,6 +56,8 @@ module Gitlab
43
56
  reference
44
57
  closed_at
45
58
  closed_by
59
+ moved_to_work_item_url
60
+ moved_to_id
46
61
  ].freeze
47
62
 
48
63
  # Widget payloads opted into via `features`. status and health_status are EE
@@ -56,6 +71,7 @@ module Gitlab
56
71
  start_and_due_date
57
72
  award_emoji
58
73
  health_status
74
+ description
59
75
  ].freeze
60
76
 
61
77
  def initialize(network:, options:, per_page: 100, normalizer: Normalizers::WorkItemNormalizer.new)
@@ -65,16 +81,51 @@ module Gitlab
65
81
  @normalizer = normalizer
66
82
  end
67
83
 
68
- def list(conditions)
84
+ # rule_definition is the policy's own rule hash, which the engine passes so the
85
+ # fallback moved_to_id check can name the rule that fetched.
86
+ def list(conditions, rule_definition = nil)
69
87
  raw = @network.query_api(build_list_url(conditions))
70
88
 
71
89
  raise_if_unavailable!(raw)
90
+ raise_if_moved_to_missing!(raw, conditions, rule_definition)
72
91
 
73
92
  raw.map { |item| resolve_project_id!(@normalizer.call(item)) }
74
93
  end
75
94
 
76
- def update(resource, features)
77
- @network.patch_api(work_item_url(resource), features: features)
95
+ # Before 19.6, GitLab leaves moved_to_id out without an error, so a rule that
96
+ # skips moved work items would act on all of them. The engine calls this before
97
+ # any rule in the policy file runs, so when GitLab returns its version the file
98
+ # cannot stop halfway.
99
+ def assert_moved_to_supported!(work_items_definition)
100
+ labels_by_rule = moved_to_labels_by_rule(work_items_definition)
101
+ return if labels_by_rule.empty?
102
+
103
+ rule_labels = labels_by_rule.values
104
+
105
+ version = readable_instance_version
106
+ version_short = version.to_s[/^\d+\.\d+/]
107
+
108
+ if version_short.nil?
109
+ # Without a version, fall back to checking the list responses, which stops
110
+ # the run when an affected rule fetches instead of before any rule runs.
111
+ @moved_to_labels_to_check = labels_by_rule
112
+ puts Gitlab::Triage::UI.warn(
113
+ "Could not read the GitLab version. moved_to_id needs GitLab #{MOVED_TO_ID_MINIMUM_VERSION} or later, " \
114
+ "so #{rule_labels.join(', ')} will stop the run if the work items " \
115
+ "#{rule_labels.one? ? 'it fetches' : 'they fetch'} have no moved_to_id.\n\n")
116
+ return
117
+ end
118
+
119
+ return if Gem::Version.new(version_short) >= Gem::Version.new(MOVED_TO_ID_MINIMUM_VERSION)
120
+
121
+ raise_moved_to_unsupported(rule_labels, "This instance is #{version}.")
122
+ end
123
+
124
+ def update(resource, features, attributes = {})
125
+ body = attributes.dup
126
+ body[:features] = features if features.any?
127
+
128
+ @network.patch_api(work_item_url(resource), body)
78
129
  end
79
130
 
80
131
  # The adapter does not raise on a 4xx. Check for an error message, not a
@@ -146,6 +197,72 @@ module Gitlab
146
197
  ).build
147
198
  end
148
199
 
200
+ # A 500 that outlasts the retries, or a response that isn't JSON (for example a load
201
+ # balancer's HTML error page), leaves the version unknown, the same as an error hash, so
202
+ # the list responses are checked instead. A rejected token still stops the run.
203
+ def readable_instance_version
204
+ Resource::InstanceVersion.new(network: @network).version
205
+ rescue Errors::Network::InternalServerError, Errors::Network::UnexpectedResponse
206
+ nil
207
+ end
208
+
209
+ # Keyed by identity: the engine passes these same rule hashes to #list. A rule
210
+ # without a name is labelled by its one-based position in the policy file.
211
+ def moved_to_labels_by_rule(work_items_definition)
212
+ labels_by_rule = {}.compare_by_identity
213
+
214
+ Array(work_items_definition[:rules]).each.with_index(1) do |rule_definition, number|
215
+ add_moved_to_label(labels_by_rule, rule_definition, "##{number} under work_items.rules")
216
+ end
217
+
218
+ Array(work_items_definition[:summaries]).each.with_index(1) do |summary, summary_number|
219
+ summary_label = summary[:name].presence || "##{summary_number}"
220
+
221
+ Array(summary[:rules]).each.with_index(1) do |rule_definition, number|
222
+ add_moved_to_label(labels_by_rule, rule_definition, "##{number} in summary #{summary_label}")
223
+ end
224
+ end
225
+
226
+ labels_by_rule
227
+ end
228
+
229
+ def add_moved_to_label(labels_by_rule, rule_definition, position)
230
+ return unless reads_moved_to_id?(rule_definition[:conditions])
231
+
232
+ labels_by_rule[rule_definition] = "**#{rule_definition[:name].presence || position}**"
233
+ end
234
+
235
+ def reads_moved_to_id?(conditions)
236
+ conditions&.[](:ruby).to_s.match?(MOVED_TO_ID_PATTERN)
237
+ end
238
+
239
+ # GitLab 19.6 and later return moved_to_id on every work item once it is
240
+ # requested, as null when the work item was not moved. The conditions decide
241
+ # whether to check, so a copied rule hash only loses its label, not the check.
242
+ def raise_if_moved_to_missing!(raw, conditions, rule_definition)
243
+ return if @moved_to_labels_to_check.nil? || !reads_moved_to_id?(conditions)
244
+ return if raw.empty? || raw.first.key?(:moved_to_id)
245
+
246
+ rule_label = @moved_to_labels_to_check[rule_definition] ||
247
+ "**#{rule_definition&.[](:name).presence || conditions[:ruby]}**"
248
+
249
+ raise_moved_to_unsupported([rule_label],
250
+ 'This instance did not return its version, and its work items have no moved_to_id.')
251
+ end
252
+
253
+ def raise_moved_to_unsupported(rule_labels, version_explanation)
254
+ rules_clause =
255
+ if rule_labels.one?
256
+ "The ruby condition of rule #{rule_labels.first} reads"
257
+ else
258
+ "The ruby conditions of rules #{rule_labels.join(', ')} read"
259
+ end
260
+
261
+ raise UnsupportedVersionError,
262
+ "#{rules_clause} moved_to_id, which needs GitLab " \
263
+ "#{MOVED_TO_ID_MINIMUM_VERSION} or later on the work_items policy type. #{version_explanation}"
264
+ end
265
+
149
266
  # The Work Items REST API is behind the :work_item_rest_api feature
150
267
  # flag. When it is off, or the token lacks access, or the endpoint is
151
268
  # absent, the response is an error hash (e.g. a 403 "feature flag is
@@ -229,6 +346,8 @@ module Gitlab
229
346
  params['status[name]'] = conditions[:status] if conditions[:status]
230
347
 
231
348
  apply_milestone_filter(params, conditions[:milestone]) if conditions[:milestone]
349
+ apply_weight_filter(params, conditions[:weight]) unless conditions[:weight].nil?
350
+ apply_iteration_filter(params, conditions[:iteration]) unless conditions[:iteration].nil?
232
351
  apply_date_filter(params, conditions[:date]) if conditions[:date]
233
352
  end
234
353
 
@@ -248,6 +367,23 @@ module Gitlab
248
367
  end
249
368
  end
250
369
 
370
+ # The API takes the wildcards titleized. Both are single words, so capitalize is enough.
371
+ def apply_weight_filter(params, weight)
372
+ Validators::PolicyValidator.validate_work_items_weight!(weight)
373
+
374
+ if Validators::PolicyValidator.weight_number?(weight)
375
+ params[:weight] = weight
376
+ else
377
+ params[:weight_wildcard_id] = weight.capitalize
378
+ end
379
+ end
380
+
381
+ def apply_iteration_filter(params, iteration)
382
+ Validators::PolicyValidator.validate_work_items_iteration!(iteration)
383
+
384
+ params[:iteration_wildcard_id] = iteration.capitalize
385
+ end
386
+
251
387
  # A bad date condition would otherwise send no date filter, or the opposite one,
252
388
  # and widen the matched set, so raise even if load-time validation was skipped.
253
389
  def apply_date_filter(params, date_condition)
@@ -23,7 +23,7 @@ module Gitlab
23
23
  # Anything outside this list would silently do nothing, so reject it up
24
24
  # front.
25
25
  SUPPORTED_WORK_ITEM_ACTIONS = %i[
26
- labels remove_labels assignees
26
+ labels remove_labels assignees state
27
27
  comment mention comment_type comment_internal redact_confidential_resources
28
28
  summarize comment_on_summary
29
29
  ].freeze
@@ -36,8 +36,14 @@ module Gitlab
36
36
  # summarize action and runs nothing else.
37
37
  SUPPORTED_SUMMARY_RULE_ACTIONS = %i[summarize].freeze
38
38
 
39
+ # Sent to the API as state_event. On issues, `status: close` does the same,
40
+ # but on work_items `status` is kept for the configurable work item status.
41
+ WORK_ITEM_STATE_EVENTS = %w[close reopen].freeze
42
+
39
43
  # Sent to the Work Items REST API as query params by WorkItemsRestSource#apply_filters.
40
- API_WORK_ITEM_CONDITIONS = %i[type state status labels forbidden_labels assignees milestone date].freeze
44
+ API_WORK_ITEM_CONDITIONS = %i[
45
+ type state status labels forbidden_labels assignees milestone weight iteration date
46
+ ].freeze
41
47
 
42
48
  # Applied in Ruby to the fetched work items through Engine::FILTER_MAP.
43
49
  RUBY_WORK_ITEM_CONDITIONS = %i[author_member assignee_member ruby no_additional_labels work_item_status].freeze
@@ -49,6 +55,61 @@ module Gitlab
49
55
  # this too, since the engine requires this file and not the other way round.
50
56
  WORK_ITEM_STATES = %w[opened closed].freeze
51
57
 
58
+ # Weight values the Work Items REST API's weight_wildcard_id filter takes, lowercased.
59
+ WORK_ITEM_WEIGHT_WILDCARDS = %w[none any].freeze
60
+
61
+ # The Issues REST API coerces a quoted number, so issues rules may write weight: '3'.
62
+ WORK_ITEM_QUOTED_WEIGHT_PATTERN = /\A\d+\z/
63
+
64
+ # Iteration wildcards the issues and work_items policy types take, lowercased.
65
+ # Engine::ITERATION_SELECTION_VALUES reads this too, so work_items keeps taking the same
66
+ # wildcards as issues. The APIs also take Current, which neither policy type takes as a wildcard.
67
+ ITERATION_WILDCARDS = %w[none any].freeze
68
+
69
+ # Error hints for the two rejected values that work on the issues policy type.
70
+ ITERATION_CURRENT_HINT = ' current is left out to match the issues policy type, which reads it as an ' \
71
+ 'iteration name, not the Current wildcard.'
72
+ ITERATION_NAME_HINT = ' The Work Items REST API cannot filter by iteration name.'
73
+
74
+ # WorkItemsRestSource#apply_weight_filter sends a number as weight and anything else as
75
+ # weight_wildcard_id, which the API rejects for any value but None or Any, so check before
76
+ # any earlier rule has acted. The source calls this too, so a weight that skipped load-time
77
+ # validation cannot be reported as an unavailable API, or skip the filter.
78
+ def self.validate_work_items_weight!(weight)
79
+ return if weight_number?(weight)
80
+ return if weight.is_a?(String) && WORK_ITEM_WEIGHT_WILDCARDS.include?(weight.downcase)
81
+
82
+ raise InvalidConditionError,
83
+ "The weight condition on work_items policies takes a whole number of 0 or more, " \
84
+ "or one of #{WORK_ITEM_WEIGHT_WILDCARDS.join(', ')}, but got #{weight.inspect}."
85
+ end
86
+
87
+ def self.weight_number?(weight)
88
+ return weight >= 0 if weight.is_a?(Integer)
89
+
90
+ weight.is_a?(String) && weight.match?(WORK_ITEM_QUOTED_WEIGHT_PATTERN)
91
+ end
92
+
93
+ # The Work Items REST API declares no iteration_title filter, so unlike on the issues
94
+ # policy type an iteration name is rejected rather than sent. Anything else would be
95
+ # sent as an iteration_wildcard_id the API rejects. The source calls this too, so an
96
+ # iteration that skipped load-time validation cannot be reported as an unavailable API.
97
+ def self.validate_work_items_iteration!(iteration)
98
+ return if iteration.is_a?(String) && ITERATION_WILDCARDS.include?(iteration.downcase)
99
+
100
+ message = "The iteration condition on work_items policies takes one of " \
101
+ "#{ITERATION_WILDCARDS.join(', ')}, but got #{iteration.inspect}."
102
+ message += iteration_hint(iteration).to_s
103
+
104
+ raise InvalidConditionError, message
105
+ end
106
+
107
+ def self.iteration_hint(iteration)
108
+ return unless iteration.is_a?(String) && iteration.strip.present?
109
+
110
+ iteration.casecmp?('current') ? ITERATION_CURRENT_HINT : ITERATION_NAME_HINT
111
+ end
112
+
52
113
  # WorkItemsRestSource#apply_date_filter would send no date filter for a bad attribute
53
114
  # or a missing interval, so the rule would match every item, and reads any condition
54
115
  # other than older_than as newer_than. Check the values against the same parameters
@@ -111,6 +172,8 @@ module Gitlab
111
172
 
112
173
  validate_state!(conditions[:state]) if conditions.key?(:state)
113
174
  validate_milestone!(conditions[:milestone]) if conditions.key?(:milestone)
175
+ self.class.validate_work_items_weight!(conditions[:weight]) if conditions.key?(:weight)
176
+ self.class.validate_work_items_iteration!(conditions[:iteration]) if conditions.key?(:iteration)
114
177
  self.class.validate_work_items_date!(conditions[:date]) if conditions.key?(:date)
115
178
  end
116
179
  end
@@ -155,6 +218,8 @@ module Gitlab
155
218
 
156
219
  def validate_work_items_actions!(policy_definition)
157
220
  action_sets_from(policy_definition).each do |actions, supported, scope|
221
+ validate_state_action!(actions) if supported.include?(:state)
222
+
158
223
  # GitLab applies remove_label_ids after add_label_ids, so a label in
159
224
  # both lists is always removed. Catch the typo here rather than let the
160
225
  # run fail later with a misleading "token may lack permission" error.
@@ -174,6 +239,21 @@ module Gitlab
174
239
  end
175
240
  end
176
241
 
242
+ def validate_state_action!(actions)
243
+ if WORK_ITEM_STATE_EVENTS.include?(actions[:status].to_s)
244
+ raise UnsupportedActionError,
245
+ "`status: #{actions[:status]}` is not supported on work_items policies. " \
246
+ "Use `state: #{actions[:status]}` instead."
247
+ end
248
+
249
+ return unless actions.key?(:state)
250
+ return if WORK_ITEM_STATE_EVENTS.include?(actions[:state].to_s)
251
+
252
+ raise UnsupportedActionError,
253
+ "Unsupported state action for work_items policies: #{actions[:state]}. " \
254
+ "Supported values: #{WORK_ITEM_STATE_EVENTS.join(', ')}."
255
+ end
256
+
177
257
  # Every place a policy definition can carry actions, with the actions
178
258
  # allowed there: top-level rules, rules nested in summaries, and the
179
259
  # summaries' own actions.
@@ -2,6 +2,6 @@
2
2
 
3
3
  module Gitlab
4
4
  module Triage
5
- VERSION = '1.58.0'
5
+ VERSION = '1.59.0'
6
6
  end
7
7
  end
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: gitlab-triage
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.58.0
4
+ version: 1.59.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - GitLab
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2026-10-29 00:00:00.000000000 Z
11
+ date: 2026-11-25 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: activesupport
@@ -253,6 +253,7 @@ files:
253
253
  - lib/gitlab/triage/action/update.rb
254
254
  - lib/gitlab/triage/action/work_item.rb
255
255
  - lib/gitlab/triage/action/work_item_comment.rb
256
+ - lib/gitlab/triage/action/work_item_state.rb
256
257
  - lib/gitlab/triage/action/work_item_status.rb
257
258
  - lib/gitlab/triage/api_observability.rb
258
259
  - lib/gitlab/triage/api_query_builders/base_query_param_builder.rb