gitlab-triage 1.58.0 → 1.60.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: 362f986d9736e3815c32e29afcfd5c47d230c18716e41fbb751123955fd86be2
4
+ data.tar.gz: 30f6942c9386605d5d3e788c284933f3811e1d4f0b7e97e2a1211b20bc1663d0
5
5
  SHA512:
6
- metadata.gz: ba6a0e711a7c06f6c99f1af0471d68cd7c335dbfd53d5456f571414e79ce6c9454f6e9df0379ff89fdb57f155f8947cde33ce164ee19766f75c75f89cc8df345
7
- data.tar.gz: da23490510ce31cf2abb2ece62189c9d464421ef15be0b07a44245fce4619afb0df52216674759a9dd07c2d07a7284b00fde9ef66e252c5e1a9e43fb81635c81
6
+ metadata.gz: b73d2d85f6650d9fd4a26a463e9affef97638e47926c6bd00fa91d45b3aa8a510c4c4ba4fe2afbb14c1394d43148ba1bba0e59fc6f07b69113cc61f18faf3abd
7
+ data.tar.gz: 98a66293d0194fd0b6d7636664e788f86c6918ebadb02a6f58cb0ae136b36f8a8fd1d3b883c64cc2a96f2a08421a08f56950e6c0065ede92f782357e2ab99f55
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.60.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,35 @@ 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[:weight]` is the work item's own weight, the same as on `issues`. It is
332
+ `nil` when no weight is set, and always `nil` on GitLab Community Edition or a
333
+ namespace without the license for weights.
334
+
335
+ `resource[:moved_to_id]` and `resource[:moved_to_work_item_url]` are the id and
336
+ URL of the work item it was moved to, so rules that skip moved items with
337
+ `resource[:moved_to_id].nil?` work the same as on `issues`. `moved_to_id` needs
338
+ GitLab 19.6 or later. Earlier versions leave out fields they do not support
339
+ without an error, so `moved_to_id` would be `nil` for every work item.
340
+ `moved_to_work_item_url` works on earlier versions too. When a `work_items`
341
+ rule or summary rule has a `ruby` condition that reads `moved_to_id`,
342
+ `gitlab-triage` checks the GitLab version before running any rule in that
343
+ policy file. On an older version, it stops with an error naming those
344
+ rules. If it cannot read the version, for example because the version request
345
+ fails with a server error or returns a page that isn't JSON, it prints a
346
+ warning and instead stops when one of those rules fetches work items that have
347
+ no `moved_to_id`, so rules before it in the file have already run. An
348
+ unauthorized token still stops the run. Templates and other conditions that
349
+ read `moved_to_id` are not checked, and on older versions they read `nil`.
350
+
351
+ On `issues`, `moved_to_id` is set for every moved issue. On `work_items`,
352
+ `moved_to_id` and `moved_to_work_item_url` are set only when the token can read
353
+ the work item it was moved to. Otherwise they're `nil`, so
354
+ `resource[:moved_to_id].nil?` also matches work items moved to a project the
355
+ token can't read. Run such rules on GitLab 19.6 or later, with a token that can
356
+ read the projects work items are moved to.
291
357
 
292
358
  The `api:` field is not applicable to the `work_items` type, since the type
293
359
  already fixes the transport to the Work Items REST API.
@@ -296,13 +362,18 @@ already fixes the transport to the Work Items REST API.
296
362
 
297
363
  The `work_items` condition names (`type`, `status`, `state`) are deliberately
298
364
  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.
365
+ `state`). `issues` keeps its names as they are. It is planned to be deprecated,
366
+ and then removed in a major version once `work_items` has feature parity
367
+ (tracked in
368
+ [gitlab-org/gitlab#634685](https://gitlab.com/gitlab-org/gitlab/-/work_items/634685)).
369
+ `state` (`opened` / `closed`) means the same on both types. `status` is new on
370
+ `work_items` and has no clean one-to-one equivalent on `issues` (where it is the
371
+ prefixed `work_item_status`).
372
+
373
+ The same applies to actions. On `issues`, the `status` action closes or reopens
374
+ the item (`status: close` / `status: reopen`). On `work_items`, that is the
375
+ `state` action with the same values (`state: close` / `state: reopen`), and
376
+ `status` is reserved for the configurable work item status.
306
377
 
307
378
  ### Fields
308
379
 
@@ -1173,6 +1244,10 @@ Changes the open or closed state of the resource.
1173
1244
  This sets the open or closed state, not the work item lifecycle status. To
1174
1245
  change work item status, see the [`work_item_status` action](#work-item-status-action).
1175
1246
 
1247
+ On the `work_items` type, use the [`state` action](#supported-actions) with the
1248
+ same values (`state: close` / `state: reopen`). There, `status` is reserved for
1249
+ the configurable work item status.
1250
+
1176
1251
  Accepts a string.
1177
1252
 
1178
1253
  | 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
@@ -6,7 +6,8 @@ module Gitlab
6
6
  module Triage
7
7
  module APIObservability
8
8
  class Tracker
9
- PAGINATION_PARAMS = %w[page per_page].freeze
9
+ # Keyset next links also echo the server's defaults (id, order_by, sort, include_archived).
10
+ PAGINATION_PARAMS = %w[page per_page cursor pagination id order_by sort include_archived].freeze
10
11
 
11
12
  attr_reader :calls, :resources_fetched
12
13
 
@@ -60,7 +61,7 @@ module Gitlab
60
61
  .sub(%r{/groups/[^/]+}, '/groups/:id')
61
62
  .gsub(%r{/\d+(/|\z)}, '/:id\1')
62
63
 
63
- query_keys = (URI.decode_www_form(uri.query || '').map(&:first) - PAGINATION_PARAMS).sort
64
+ query_keys = (URI.decode_www_form(uri.query || '').map { |key, _| key.delete_suffix('[]') }.uniq - PAGINATION_PARAMS).sort
64
65
 
65
66
  path += "?#{query_keys.join('&')}" if query_keys.any?
66
67
  path
@@ -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)
@@ -24,9 +24,11 @@ module Gitlab
24
24
  raise_on_internal_server_error!(response)
25
25
  raise_on_too_many_requests!(response)
26
26
 
27
+ next_url = next_page_url(url, response)
28
+
27
29
  result = {
28
- more_pages: (response.headers["x-next-page"].to_s != ""),
29
- next_page_url: next_page_url(url, response),
30
+ more_pages: next_url.present?,
31
+ next_page_url: next_url,
30
32
  results: response.parsed_response,
31
33
  ratelimit_remaining: rate_limit_remaining(response.headers),
32
34
  ratelimit_reset_at: rate_limit_reset_at(response.headers)
@@ -160,8 +162,17 @@ module Gitlab
160
162
  end
161
163
 
162
164
  def next_page_url(url, response)
163
- return unless response.headers['x-next-page'].present?
165
+ return next_offset_page_url(url, response) if response.headers['x-next-page'].present?
166
+
167
+ next_link = response.headers['link'].to_s[/<([^>]+)>;\s*rel="next"/, 1]
168
+ return unless next_link
169
+
170
+ # Keyset pages have no X-Next-Page. The Link host comes from the server's
171
+ # own config and can differ from ours, so only its query is used.
172
+ "#{url.split('?', 2).first}?#{next_link.split('?', 2).last}"
173
+ end
164
174
 
175
+ def next_offset_page_url(url, response)
165
176
  next_page = "&page=#{response.headers['x-next-page']}"
166
177
 
167
178
  if url.include?('&page')
@@ -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]),
@@ -43,6 +46,7 @@ module Gitlab
43
46
  # Flat string, like the Issues API: ruby conditions compare
44
47
  # resource[:health_status] with values such as 'at_risk'.
45
48
  health_status: features.dig(:health_status, :health_status),
49
+ weight: features.dig(:weight, :weight),
46
50
  work_item_type: resource.dig(:work_item_type, :name),
47
51
  work_item_status: status_name(features),
48
52
  start_date: features.dig(:start_and_due_date, :start_date),
@@ -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,10 +56,12 @@ 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
- # Widget payloads opted into via `features`. status and health_status are EE
49
- # only: CE accepts them on read endpoints and leaves them out of the response,
63
+ # Widget payloads opted into via `features`. status, weight and health_status are
64
+ # EE only: CE accepts them on read endpoints and leaves them out of the response,
50
65
  # as an unlicensed EE namespace does, so their values are then nil.
51
66
  LIST_FEATURES = %w[
52
67
  labels
@@ -54,8 +69,10 @@ module Gitlab
54
69
  milestone
55
70
  status
56
71
  start_and_due_date
72
+ weight
57
73
  award_emoji
58
74
  health_status
75
+ description
59
76
  ].freeze
60
77
 
61
78
  def initialize(network:, options:, per_page: 100, normalizer: Normalizers::WorkItemNormalizer.new)
@@ -65,16 +82,51 @@ module Gitlab
65
82
  @normalizer = normalizer
66
83
  end
67
84
 
68
- def list(conditions)
85
+ # rule_definition is the policy's own rule hash, which the engine passes so the
86
+ # fallback moved_to_id check can name the rule that fetched.
87
+ def list(conditions, rule_definition = nil)
69
88
  raw = @network.query_api(build_list_url(conditions))
70
89
 
71
90
  raise_if_unavailable!(raw)
91
+ raise_if_moved_to_missing!(raw, conditions, rule_definition)
72
92
 
73
93
  raw.map { |item| resolve_project_id!(@normalizer.call(item)) }
74
94
  end
75
95
 
76
- def update(resource, features)
77
- @network.patch_api(work_item_url(resource), features: features)
96
+ # Before 19.6, GitLab leaves moved_to_id out without an error, so a rule that
97
+ # skips moved work items would act on all of them. The engine calls this before
98
+ # any rule in the policy file runs, so when GitLab returns its version the file
99
+ # cannot stop halfway.
100
+ def assert_moved_to_supported!(work_items_definition)
101
+ labels_by_rule = moved_to_labels_by_rule(work_items_definition)
102
+ return if labels_by_rule.empty?
103
+
104
+ rule_labels = labels_by_rule.values
105
+
106
+ version = readable_instance_version
107
+ version_short = version.to_s[/^\d+\.\d+/]
108
+
109
+ if version_short.nil?
110
+ # Without a version, fall back to checking the list responses, which stops
111
+ # the run when an affected rule fetches instead of before any rule runs.
112
+ @moved_to_labels_to_check = labels_by_rule
113
+ puts Gitlab::Triage::UI.warn(
114
+ "Could not read the GitLab version. moved_to_id needs GitLab #{MOVED_TO_ID_MINIMUM_VERSION} or later, " \
115
+ "so #{rule_labels.join(', ')} will stop the run if the work items " \
116
+ "#{rule_labels.one? ? 'it fetches' : 'they fetch'} have no moved_to_id.\n\n")
117
+ return
118
+ end
119
+
120
+ return if Gem::Version.new(version_short) >= Gem::Version.new(MOVED_TO_ID_MINIMUM_VERSION)
121
+
122
+ raise_moved_to_unsupported(rule_labels, "This instance is #{version}.")
123
+ end
124
+
125
+ def update(resource, features, attributes = {})
126
+ body = attributes.dup
127
+ body[:features] = features if features.any?
128
+
129
+ @network.patch_api(work_item_url(resource), body)
78
130
  end
79
131
 
80
132
  # The adapter does not raise on a 4xx. Check for an error message, not a
@@ -146,6 +198,72 @@ module Gitlab
146
198
  ).build
147
199
  end
148
200
 
201
+ # A 500 that outlasts the retries, or a response that isn't JSON (for example a load
202
+ # balancer's HTML error page), leaves the version unknown, the same as an error hash, so
203
+ # the list responses are checked instead. A rejected token still stops the run.
204
+ def readable_instance_version
205
+ Resource::InstanceVersion.new(network: @network).version
206
+ rescue Errors::Network::InternalServerError, Errors::Network::UnexpectedResponse
207
+ nil
208
+ end
209
+
210
+ # Keyed by identity: the engine passes these same rule hashes to #list. A rule
211
+ # without a name is labelled by its one-based position in the policy file.
212
+ def moved_to_labels_by_rule(work_items_definition)
213
+ labels_by_rule = {}.compare_by_identity
214
+
215
+ Array(work_items_definition[:rules]).each.with_index(1) do |rule_definition, number|
216
+ add_moved_to_label(labels_by_rule, rule_definition, "##{number} under work_items.rules")
217
+ end
218
+
219
+ Array(work_items_definition[:summaries]).each.with_index(1) do |summary, summary_number|
220
+ summary_label = summary[:name].presence || "##{summary_number}"
221
+
222
+ Array(summary[:rules]).each.with_index(1) do |rule_definition, number|
223
+ add_moved_to_label(labels_by_rule, rule_definition, "##{number} in summary #{summary_label}")
224
+ end
225
+ end
226
+
227
+ labels_by_rule
228
+ end
229
+
230
+ def add_moved_to_label(labels_by_rule, rule_definition, position)
231
+ return unless reads_moved_to_id?(rule_definition[:conditions])
232
+
233
+ labels_by_rule[rule_definition] = "**#{rule_definition[:name].presence || position}**"
234
+ end
235
+
236
+ def reads_moved_to_id?(conditions)
237
+ conditions&.[](:ruby).to_s.match?(MOVED_TO_ID_PATTERN)
238
+ end
239
+
240
+ # GitLab 19.6 and later return moved_to_id on every work item once it is
241
+ # requested, as null when the work item was not moved. The conditions decide
242
+ # whether to check, so a copied rule hash only loses its label, not the check.
243
+ def raise_if_moved_to_missing!(raw, conditions, rule_definition)
244
+ return if @moved_to_labels_to_check.nil? || !reads_moved_to_id?(conditions)
245
+ return if raw.empty? || raw.first.key?(:moved_to_id)
246
+
247
+ rule_label = @moved_to_labels_to_check[rule_definition] ||
248
+ "**#{rule_definition&.[](:name).presence || conditions[:ruby]}**"
249
+
250
+ raise_moved_to_unsupported([rule_label],
251
+ 'This instance did not return its version, and its work items have no moved_to_id.')
252
+ end
253
+
254
+ def raise_moved_to_unsupported(rule_labels, version_explanation)
255
+ rules_clause =
256
+ if rule_labels.one?
257
+ "The ruby condition of rule #{rule_labels.first} reads"
258
+ else
259
+ "The ruby conditions of rules #{rule_labels.join(', ')} read"
260
+ end
261
+
262
+ raise UnsupportedVersionError,
263
+ "#{rules_clause} moved_to_id, which needs GitLab " \
264
+ "#{MOVED_TO_ID_MINIMUM_VERSION} or later on the work_items policy type. #{version_explanation}"
265
+ end
266
+
149
267
  # The Work Items REST API is behind the :work_item_rest_api feature
150
268
  # flag. When it is off, or the token lacks access, or the endpoint is
151
269
  # absent, the response is an error hash (e.g. a 403 "feature flag is
@@ -229,6 +347,8 @@ module Gitlab
229
347
  params['status[name]'] = conditions[:status] if conditions[:status]
230
348
 
231
349
  apply_milestone_filter(params, conditions[:milestone]) if conditions[:milestone]
350
+ apply_weight_filter(params, conditions[:weight]) unless conditions[:weight].nil?
351
+ apply_iteration_filter(params, conditions[:iteration]) unless conditions[:iteration].nil?
232
352
  apply_date_filter(params, conditions[:date]) if conditions[:date]
233
353
  end
234
354
 
@@ -248,6 +368,23 @@ module Gitlab
248
368
  end
249
369
  end
250
370
 
371
+ # The API takes the wildcards titleized. Both are single words, so capitalize is enough.
372
+ def apply_weight_filter(params, weight)
373
+ Validators::PolicyValidator.validate_work_items_weight!(weight)
374
+
375
+ if Validators::PolicyValidator.weight_number?(weight)
376
+ params[:weight] = weight
377
+ else
378
+ params[:weight_wildcard_id] = weight.capitalize
379
+ end
380
+ end
381
+
382
+ def apply_iteration_filter(params, iteration)
383
+ Validators::PolicyValidator.validate_work_items_iteration!(iteration)
384
+
385
+ params[:iteration_wildcard_id] = iteration.capitalize
386
+ end
387
+
251
388
  # A bad date condition would otherwise send no date filter, or the opposite one,
252
389
  # and widen the matched set, so raise even if load-time validation was skipped.
253
390
  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.60.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.60.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-26 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