Skip to content

Self-hosted project management for devs and their clients: tickets, time tracking, docs and meetings, with an AI assistant that cites its sources. AGPL-3.0.

Move the rule of update_ticket into Tickets::Change

Guido Boyke29807910dc6e
diff --git a/.github/workflows/guards.yml b/.github/workflows/guards.yml
index d60caa9..50b1971 100644
--- a/.github/workflows/guards.yml
+++ b/.github/workflows/guards.yml
@@ -275,6 +275,7 @@ jobs:
spec/services/lalabase/tools/post_comment_spec.rb
spec/services/lalabase/tools/post_comment_failure_spec.rb
spec/services/posts/comment_spec.rb
+ spec/services/tickets/change_spec.rb
spec/requests/api/inbox_organisation_filter_spec.rb
spec/services/lalabase/tools/get_ticket_paging_spec.rb
spec/services/lalabase/tools/get_ticket_assistant_limits_spec.rb
diff --git a/app/services/lalabase/tools/ticket_title.rb b/app/services/lalabase/tools/ticket_title.rb
index c507a13..df37442 100644
--- a/app/services/lalabase/tools/ticket_title.rb
+++ b/app/services/lalabase/tools/ticket_title.rb
@@ -2,17 +2,19 @@
module Lalabase
module Tools
- # The title of a ticket as an MCP write takes it: create_ticket and
- # update_ticket check it here, so the two tools cannot drift apart. ONE line
- # of printable text, at most Ticket::TITLE_MAX_LENGTH characters (the model
- # holds the bound, this answers it first, in English, as invalid_input).
+ # The title of a ticket as a token write takes it: create_ticket checks it
+ # here, and Tickets::Change for update_ticket and the HTTP API, so the
+ # surfaces cannot drift apart. ONE line of printable text, at most
+ # Ticket::TITLE_MAX_LENGTH characters (the model holds the bound, this answers
+ # it first, as a refusal of the input).
#
# Refused, not cleaned: web titles are not normalised, and silently changing
# what a client sent would make the answer differ from the input. The check
# runs on the value as sent, before the edges are trimmed, so a control
# character at the start or the end is refused instead of cut away unseen.
#
- # Entry point: check
+ # Entry point: read (the refusal named, for Tickets::Change, which leaves the
+ # wording to its callers) or check (the refusal in the English of the tools)
module TicketTitle
# The name contract's invisible and direction characters
# (Project::NAME_INVISIBLE_CHARS), plus what that set leaves to its
@@ -34,15 +36,31 @@ module Lalabase
# variation selectors are no letters at all.
VISIBLE = /[[\p{L}\p{N}\p{P}\p{S}]&&[^\u115F\u1160\u3164\uFFA0\u2800]]/
+ # The refusals of the rule, in the order it checks, in the tools' wording.
+ REFUSAL_TEXT = {
+ title_not_string: 'title must be a string',
+ title_invalid_utf8: 'title must be valid UTF-8',
+ title_forbidden: 'title must be one line without control characters',
+ title_empty: 'title is required',
+ title_too_long: "title is longer than #{Ticket::TITLE_MAX_LENGTH} characters"
+ }.freeze
+ REFUSALS = REFUSAL_TEXT.keys.freeze
+
# @return [String] the title to store, or [Result] the refusal to return
def self.check(value)
- return Result.invalid_input('title must be a string') unless value.is_a?(String)
- return Result.invalid_input('title must be valid UTF-8') unless value.valid_encoding?
- return Result.invalid_input('title must be one line without control characters') if forbidden?(value)
+ title = read(value)
+ title.is_a?(Symbol) ? Result.invalid_input(REFUSAL_TEXT.fetch(title)) : title
+ end
+
+ # @return [String] the title to store, or [Symbol] the refusal (REFUSALS)
+ def self.read(value)
+ return :title_not_string unless value.is_a?(String)
+ return :title_invalid_utf8 unless value.valid_encoding?
+ return :title_forbidden if forbidden?(value)
title = value.gsub(EDGE_SPACES, '')
- return Result.invalid_input('title is required') unless title.match?(VISIBLE)
- return Result.invalid_input("title is longer than #{Ticket::TITLE_MAX_LENGTH} characters") if title.length > Ticket::TITLE_MAX_LENGTH
+ return :title_empty unless title.match?(VISIBLE)
+ return :title_too_long if title.length > Ticket::TITLE_MAX_LENGTH
title
end
diff --git a/app/services/lalabase/tools/update_ticket.rb b/app/services/lalabase/tools/update_ticket.rb
index 6ac00c0..c2d9e34 100644
--- a/app/services/lalabase/tools/update_ticket.rb
+++ b/app/services/lalabase/tools/update_ticket.rb
@@ -4,29 +4,14 @@ module Lalabase
module Tools
# Changes ONE thing on a ticket per call: its title, its status or its
# assignees (terminal client S2, lalabase-private
- # doc/terminal_client_s2_update_ticket_plan.md). It adds no write path of its
- # own, one per field:
- # * status and assignees: Actors::ApplyTicketChanges with one ticket, the
- # call the board and the head's people menu make
- # (TicketsController#update_kanban_attribute). It writes only the status
- # key of custom_attributes and adds/removes against the CURRENT assignees
- # under the row lock, so "assign to me" removes nobody and a stale list in
- # a client cannot remove anybody it did not name.
- # * title: Actors::SaveTicket with the title alone. Never with assignee_ids
- # (that REPLACES the list, and TicketAssignmentSync silently drops a new
- # person who may not be assigned),
- # never with custom_attributes. Under a lock on the ticket in THIS
- # project: SaveTicket finds a ticket organisation-wide and builds a new
- # one for an id it does not find, so a ticket moved or deleted after the
- # rights check would otherwise be renamed elsewhere or created anew.
+ # doc/terminal_client_s2_update_ticket_plan.md). The rule, its write paths and
+ # the reading of their results are Tickets::Change's, shared with
+ # POST /api/v1/tickets/:id/changes (REST R3b); here stay the arguments, the
+ # rights and the texts.
#
- # The kind is decided by which keys are PRESENT, not by their values, so
- # `{title: "", status: "x"}` is a mixed call, and a key the tool does not
- # know is refused rather than ignored (an agent that guessed `priority`
- # must not read "ok"). The schema stays flat on purpose (no oneOf): the
- # terminal client detects a feature by the top-level properties of a schema
- # only, so the rule lives here. The title rule is shared with create_ticket
- # (TicketTitle).
+ # The schema stays flat on purpose (no oneOf): the terminal client detects a
+ # feature by the top-level properties of a schema only, so the rule lives in
+ # the service.
#
# Errors: what the request alone decides is invalid_input; what the project's
# state decides is refused with a reason (value_not_allowed,
@@ -38,25 +23,41 @@ module Lalabase
# ticket is authorized :update? before the write; a missing or unreadable
# ticket answers kind: :empty and writes nothing.
class UpdateTicket < Base
- MAX_ASSIGNEE_IDS = 50
- # Stands for the caller in either assignee list, as `assignee: "me"` does
- # in list_tickets.
- ME = 'me'
- ASSIGNEE_KEYS = %i[add_assignee_ids remove_assignee_ids].freeze
- KIND_KEYS = { title: %i[title], status: %i[status], assignees: ASSIGNEE_KEYS }.freeze
- # Every argument the tool reads. Mcp::ToolCall strips project_id and
- # idempotency_key before the tool runs.
- KNOWN_KEYS = ([:ticket_id] + KIND_KEYS.values.flatten).freeze
+ MAX_ASSIGNEE_IDS = Tickets::Change::MAX_ASSIGNEE_IDS
# The names a client may print: a key is caller text like any value, so
# one with control characters or of any length is counted, not repeated.
PLAIN_NAME = /\A[A-Za-z0-9_]{1,64}\z/
- ONE_CHANGE = 'exactly one change per call: title, status, or add_assignee_ids/remove_assignee_ids'
+ # The refusals of this surface (Tickets::Change::REFUSALS), unchanged since
+ # the tool's first answer.
+ REFUSAL_TEXT = {
+ unknown_keys: 'unknown arguments: %<names>s',
+ invalid_utf8: 'arguments must be valid UTF-8',
+ one_kind: 'exactly one change per call: title, status, or add_assignee_ids/remove_assignee_ids',
+ **TicketTitle::REFUSAL_TEXT,
+ status_not_string: 'status must be a string',
+ status_empty: 'status is required',
+ assignees_not_a_list: %(%<list>s must be a list of user UUIDs or "#{Tickets::Change::ME}"),
+ too_many_assignees: "at most #{MAX_ASSIGNEE_IDS} user ids per list",
+ assignee_invalid: 'invalid user id in %<list>s',
+ no_assignees: 'add_assignee_ids or remove_assignee_ids must name at least one user',
+ assignees_overlap: 'add_assignee_ids and remove_assignee_ids name the same user'
+ }.freeze
+
+ # The failures of this surface (Tickets::Change::FAILURES). Neither answer
+ # repeats a value: a client prints the answer, and the value is whatever
+ # the caller sent, control characters included. The allowed statuses come
+ # from list_tickets. Unknown person and person without access read the
+ # same, so the answer tells no existence.
+ FAILURE_TEXT = {
+ no_status_field: 'this project has no status field',
+ status_not_allowed: 'status is not a status of this project; use a key from meta.available_statuses',
+ assignee_not_allowed: 'a user in this change cannot be assigned in this project',
+ user_not_assignable: 'nothing was changed: a person in this change no longer has access to this project',
+ title_not_saved: 'title could not be saved',
+ ticket_not_saved: 'the ticket could not be saved'
+ }.freeze
UPDATE_FAILED = 'update failed'
- NO_STATUS_FIELD = 'this project has no status field'
- # The actor answers these for a status when the project has no active
- # single-select field named "status" (a multiselect gives nothing_to_change).
- NO_STATUS_FIELD_CODES = %i[unknown_field nothing_to_change unknown_kind].freeze
# Writes on behalf of context.actor. No chat set may ever carry a mutating
# tool, so the Runner's bar can never fire here; the declaration is kept
@@ -106,19 +107,15 @@ module Lalabase
return Result.new(error: 'project context missing') if context.project.nil?
args = symbolized(args)
- refusal = refused_arguments(args)
- return refusal if refusal
+ change = Tickets::Change.parse(args, actor: context.actor, beside: %i[ticket_id])
+ # The order this tool always answered in: the keys and their encoding,
+ # then its own id, then the change.
+ return refused(change) if change.unreadable?
ticket_id = args[:ticket_id].to_s.strip
return Result.invalid_input('ticket_id is required') if ticket_id.empty?
return Result.invalid_input('invalid ticket_id format') unless ticket_id.match?(UUID_FORMAT)
-
- kinds = KIND_KEYS.select { |_kind, keys| keys.any? { |key| args.key?(key) } }.keys
- return Result.invalid_input(ONE_CHANGE) unless kinds.one?
-
- kind = kinds.first
- change = requested_change(kind, args, context)
- return change if change.is_a?(Result)
+ return refused(change) if change.refused?
# Inside the read scope: a ticket the caller may not read answers like a
# missing one (Base.readable_tickets).
@@ -128,187 +125,43 @@ module Lalabase
# The right the board and the head menu ask for every field.
authorize!(context, ticket, :update?)
- result = write(kind, change, ticket, context)
- # nil: the ticket left this project, or was deleted, after the lookup.
- return not_found(ticket_id) if result.nil?
- return failure(kind, result, ticket_id) unless result.success?
+ outcome = change.write(ticket: ticket, project: context.project)
+ return not_found(ticket_id) if outcome.gone?
+ return failure(outcome) unless outcome.written?
json_result(Tickets::Serializer.new(current_user: context.actor).summary(ticket.reload))
end
- # Unknown keys, and text that is not UTF-8 (a direct call; JSON over the
- # wire is always UTF-8), anywhere in the arguments.
- def self.refused_arguments(args)
- unknown = args.keys - KNOWN_KEYS
- return unknown_arguments(unknown) if unknown.any?
-
- texts = args.values.flat_map { |value| Array(value) }.grep(String)
- Result.invalid_input('arguments must be valid UTF-8') unless texts.all?(&:valid_encoding?)
+ def self.refused(change)
+ details = change.refusal_details
+ details = { names: printable_names(details[:keys]) } if change.refusal == :unknown_keys
+ Result.invalid_input(format(REFUSAL_TEXT.fetch(change.refusal), details))
end
- private_class_method :refused_arguments
+ private_class_method :refused
- def self.unknown_arguments(keys)
+ def self.printable_names(keys)
names = keys.map(&:to_s)
plain = names.grep(PLAIN_NAME).sort
hidden = names.size - plain.size
- listed = plain + (hidden.positive? ? ["#{hidden} not shown"] : [])
- Result.invalid_input("unknown arguments: #{listed.join(', ')}")
- end
- private_class_method :unknown_arguments
-
- # The title (String), the status change or the assignee change the actor
- # takes, or the Result that refuses the request.
- def self.requested_change(kind, args, context)
- case kind
- when :title then TicketTitle.check(args[:title])
- when :status then requested_status(args[:status])
- else requested_assignees(args, context)
- end
- end
- private_class_method :requested_change
-
- def self.requested_status(value)
- return Result.invalid_input('status must be a string') unless value.is_a?(String)
-
- status = value.strip
- return Result.invalid_input('status is required') if status.empty?
-
- { 'field' => 'status', 'value' => status }
- end
- private_class_method :requested_status
-
- def self.requested_assignees(args, context)
- lists = {}
- ASSIGNEE_KEYS.each do |key|
- ids = args.key?(key) ? requested_user_ids(key, args[key], context) : []
- return ids if ids.is_a?(Result)
-
- lists[key] = ids
- end
- add, remove = lists.values_at(*ASSIGNEE_KEYS)
- return Result.invalid_input('add_assignee_ids or remove_assignee_ids must name at least one user') if add.empty? && remove.empty?
- # The actor would let add win; a client that sends both has a bug, and
- # "add wins" would hide it.
- return Result.invalid_input('add_assignee_ids and remove_assignee_ids name the same user') if add.intersect?(remove)
-
- { 'field' => 'assignees', 'add' => add, 'remove' => remove }
- end
- private_class_method :requested_assignees
-
- def self.requested_user_ids(key, value, context)
- return Result.invalid_input(%(#{key} must be a list of user UUIDs or "#{ME}")) unless value.is_a?(Array) && value.all?(String)
- return Result.invalid_input("at most #{MAX_ASSIGNEE_IDS} user ids per list") if value.size > MAX_ASSIGNEE_IDS
-
- ids = value.map(&:strip)
- return Result.invalid_input("invalid user id in #{key}") unless ids.all? { |id| id == ME || Lalabase::Uuid.valid?(id) }
-
- # One spelling (the one Postgres hands back), so the same person in
- # capitals or without dashes is the same person in the overlap check
- # and in the actor's option list. Duplicates stay: the actor collapses
- # them (AddRemoveBase#add).
- ids.map { |id| id == ME ? context.actor.id.to_s : Lalabase::Uuid.dashed(id) }
+ (plain + (hidden.positive? ? ["#{hidden} not shown"] : [])).join(', ')
end
- private_class_method :requested_user_ids
+ private_class_method :printable_names
- # The actor's result, a Result the tool answers with, or nil when the
- # ticket is no longer in this project.
- def self.write(kind, change, ticket, context)
- return write_title(change, ticket, context) if kind == :title
- return Result.refused(NO_STATUS_FIELD, reason: :no_status_field) if kind == :status && !status_field?(context)
+ def self.failure(outcome)
+ return Result.refused(UPDATE_FAILED, reason: nil) if outcome.unexpected?
- Actors::ApplyTicketChanges.call(project: context.project, ticket_ids: [ticket.id], changes: [change],
- current_user: context.actor)
- end
- private_class_method :write
-
- # The status field of the tool's contract is the one list_tickets reads its
- # keys from: an active single select named "status". The bulk actor writes
- # any active field of that name, a checkbox or a date included.
- def self.status_field?(context)
- TicketAttributeDefinition.select_for(context.project, 'status').present?
- end
- private_class_method :status_field?
-
- # The row is locked in THIS project for the whole write, so SaveTicket's
- # organisation-wide lookup finds exactly this ticket: it can neither have
- # moved to a project the caller may not write nor have been deleted (and
- # then built anew).
- #
- # The caller is Current.user around the WHOLE transaction: the title
- # activity is written on commit and names Current.user, and this commit
- # comes after SaveTicket's own with_actor_context restored the previous
- # value. Current.set restores it afterwards in turn.
- def self.write_title(title, ticket, context)
- result = nil
- Current.set(user: context.actor) do
- ActiveRecord::Base.transaction do
- next unless context.project.tickets.lock.exists?(id: ticket.id)
-
- result = Actors::SaveTicket.call(project: context.project, params: { title: title }, id: ticket.id,
- current_user: context.actor)
- end
- end
- result
- end
- private_class_method :write_title
-
- def self.failure(kind, result, ticket_id)
- # A refusal of the tool's own (no status field).
- return result if result.is_a?(Result)
-
- code = result.code&.to_sym
- # The ticket left the project between the lookup and the actor's row lock.
- return not_found(ticket_id) if code == :outside_scope
- return refused_value(kind) if code == :value_not_allowed
- return Result.refused(NO_STATUS_FIELD, reason: :no_status_field) if kind == :status && NO_STATUS_FIELD_CODES.include?(code)
- return refused_validation(kind, result) if code == :validation_failed
-
- if code == :user_not_assignable
- # Only a person the change ADDS is checked (Ticket#assignable_user_ids
- # keeps whoever stays assigned), so this is one who lost access after
- # the option list was read.
- return Result.refused('nothing was changed: a person in this change no longer has access to this project',
- reason: :user_not_assignable)
- end
-
- Result.refused(UPDATE_FAILED, reason: nil)
+ Result.refused(failure_text(outcome), reason: outcome.reason)
end
private_class_method :failure
- # Neither answer repeats the value: a client prints the answer, and the
- # value is whatever the caller sent, control characters included. The
- # allowed statuses come from list_tickets. Unknown person and person
- # without access read the same, so the answer tells no existence.
- def self.refused_value(kind)
- if kind == :status
- Result.refused('status is not a status of this project; use a key from meta.available_statuses',
- reason: :value_not_allowed)
- else
- Result.refused('a user in this change cannot be assigned in this project', reason: :value_not_allowed)
- end
- end
- private_class_method :refused_value
-
- # SaveTicket's messages are the model's validation messages, read again in
+ # A title's messages are the model's validation messages, read again in
# English (the actor rendered them in the request's locale; the MCP answer
- # is English like every other tool text). The bulk actor's are a generic
- # board text, so a status or assignee change says only that the ticket
- # refused it.
- def self.refused_validation(kind, result)
- return Result.refused('the ticket could not be saved', reason: :validation_failed) unless kind == :title
-
- messages = english_messages(result.resource)
- message = ['title could not be saved', messages.join(', ').presence].compact.join(': ')
- Result.refused(message, reason: :validation_failed)
- end
- private_class_method :refused_validation
-
- def self.english_messages(record)
- return [] unless record.respond_to?(:errors)
-
- I18n.with_locale(:en) { record.errors.full_messages }
+ # is English like every other tool text).
+ def self.failure_text(outcome)
+ messages = I18n.with_locale(:en) { outcome.messages }
+ [FAILURE_TEXT.fetch(outcome.failure), messages.join(', ').presence].compact.join(': ')
end
- private_class_method :english_messages
+ private_class_method :failure_text
def self.not_found(ticket_id)
Result.new(content: "No ticket found for #{ticket_id}.", citations: [], kind: :empty)
diff --git a/app/services/tickets/change.rb b/app/services/tickets/change.rb
new file mode 100644
index 0000000..f4c9ad5
--- /dev/null
+++ b/app/services/tickets/change.rb
@@ -0,0 +1,275 @@
+# frozen_string_literal: true
+
+# The one rule of a ticket change through a token: the MCP tool update_ticket
+# and POST /api/v1/tickets/:id/changes both change a ticket through it, so the
+# two surfaces cannot drift apart (REST R3b). ONE thing per call: the title, the
+# status or the assignees. PATCH /api/v1/tickets/:id is another write on purpose:
+# its assignee_ids REPLACE the list.
+#
+# Entry point: parse
+#
+# Two steps, because the callers find and authorize the ticket in between:
+# `parse` refuses what the request alone decides, and `write` changes a ticket the
+# caller has found readable and may write. Rights stay with the callers, this
+# object holds none, and so does the wording: a refusal and a failure are names,
+# each surface says them in its own words.
+#
+# No write path of its own, one per field:
+# * status and assignees: Actors::ApplyTicketChanges with one ticket, the
+# call the board and the head's people menu make
+# (TicketsController#update_kanban_attribute). It writes only the status
+# key of custom_attributes and adds/removes against the CURRENT assignees
+# under the row lock, so "assign to me" removes nobody and a stale list in
+# a client cannot remove anybody it did not name.
+# * title: Actors::SaveTicket with the title alone. Never with assignee_ids
+# (that REPLACES the list, and TicketAssignmentSync silently drops a new
+# person who may not be assigned),
+# never with custom_attributes. Under a lock on the ticket in THIS
+# project: SaveTicket finds a ticket organisation-wide and builds a new
+# one for an id it does not find, so a ticket moved or deleted after the
+# rights check would otherwise be renamed elsewhere or created anew.
+#
+# The kind is decided by which keys are PRESENT, not by their values, so
+# `{title: "", status: "x"}` is a mixed call, and a key the rule does not
+# know is refused rather than ignored (a client that guessed `priority`
+# must not read "ok"). The title rule is shared with create_ticket
+# (Lalabase::Tools::TicketTitle).
+module Tickets
+ class Change
+ MAX_ASSIGNEE_IDS = 50
+ # Stands for the caller in either assignee list, as `assignee: "me"` does
+ # in list_tickets.
+ ME = 'me'
+ ASSIGNEE_KEYS = %i[add_assignee_ids remove_assignee_ids].freeze
+ KIND_KEYS = { title: %i[title], status: %i[status], assignees: ASSIGNEE_KEYS }.freeze
+ KEYS = KIND_KEYS.values.flatten.freeze
+
+ # Why `parse` turns a change away, in the order it checks: what the request
+ # alone decides. Each caller words it for its surface.
+ REFUSALS = [
+ :unknown_keys, :invalid_utf8, :one_kind,
+ *Lalabase::Tools::TicketTitle::REFUSALS,
+ :status_not_string, :status_empty,
+ :assignees_not_a_list, :too_many_assignees, :assignee_invalid, :no_assignees, :assignees_overlap
+ ].freeze
+ # The first two come before a caller's own arguments, see #unreadable?.
+ UNREADABLE = %i[unknown_keys invalid_utf8].freeze
+
+ # Why `write` changes nothing although the request was fine: what the
+ # project's state decides. Each with the reason a client branches on; each
+ # caller words the failure itself.
+ REASONS = {
+ no_status_field: :no_status_field,
+ status_not_allowed: :value_not_allowed,
+ assignee_not_allowed: :value_not_allowed,
+ user_not_assignable: :user_not_assignable,
+ title_not_saved: :validation_failed,
+ ticket_not_saved: :validation_failed
+ }.freeze
+ FAILURES = REASONS.keys.freeze
+
+ # The actor answers these for a status when the project has no active
+ # single-select field named "status" (a multiselect gives nothing_to_change).
+ NO_STATUS_FIELD_CODES = %i[unknown_field nothing_to_change unknown_kind].freeze
+
+ # What a write came to. `failure` is nil when the change is written, :gone
+ # when the ticket left the project or was deleted after the caller found it
+ # (answered like a missing ticket), one of FAILURES, or :unexpected: anything
+ # else, to be answered with a fixed text, because the actor's message may be
+ # the exception of an unexpected failure (a PostgreSQL error, say).
+ Outcome = Struct.new(:failure, :record, keyword_init: true) do
+ def written?
+ failure.nil?
+ end
+
+ def gone?
+ failure == :gone
+ end
+
+ def unexpected?
+ failure == :unexpected
+ end
+
+ def reason
+ REASONS.fetch(failure)
+ end
+
+ # What the model said about a refused title, in the current locale. The
+ # other failures have no messages worth repeating: the bulk actor's are a
+ # generic board text.
+ def messages
+ return [] unless failure == :title_not_saved && record.respond_to?(:errors)
+
+ record.errors.full_messages
+ end
+ end
+
+ # `fields` are the keys of the change, symbols or strings. `beside` names
+ # what the caller reads itself (the MCP tool's ticket_id): no unknown key and
+ # no kind, but text like the rest.
+ def self.parse(fields, actor:, beside: [])
+ new(fields: fields, actor: actor, beside: beside)
+ end
+
+ attr_reader :kind, :refusal, :refusal_details
+
+ def initialize(fields:, actor:, beside:)
+ @actor = actor
+ @refusal_details = {}
+ @refusal = refusal_for(fields.to_h.symbolize_keys, beside)
+ end
+
+ def refused?
+ end
+
+ # Refused before the fields were read: for a caller that answers these ahead
+ # of its own arguments, as the MCP tool always did.
+ def unreadable?
+ UNREADABLE.include?(@refusal)
+ end
+
+ # => Outcome. A change the actor refuses writes nothing.
+ def write(ticket:, project:)
+ raise ArgumentError, "refused change: #{@refusal}" if refused?
+ return Outcome.new(failure: :no_status_field) if @kind == :status && !status_field?(project)
+
+ result = @kind == :title ? write_title(ticket, project) : write_field(ticket, project)
+ # nil: the ticket left this project, or was deleted, after the lookup.
+ return Outcome.new(failure: :gone) if result.nil?
+ return Outcome.new if result.success?
+
+ Outcome.new(failure: failure_of(result), record: result.resource)
+ end
+
+ private
+
+ def refusal_for(fields, beside)
+ unknown = fields.keys - KEYS - beside
+ return refuse(:unknown_keys, keys: unknown) if unknown.any?
+ return refuse(:invalid_utf8) unless fields.values.flat_map { |value| Array(value) }.grep(String).all? { |text| utf8?(text) }
+
+ kinds = KIND_KEYS.select { |_kind, keys| keys.any? { |key| fields.key?(key) } }.keys
+ return refuse(:one_kind) unless kinds.one?
+
+ @kind = kinds.first
+ case @kind
+ when :title then read_title(fields[:title])
+ when :status then read_status(fields[:status])
+ else read_assignees(fields)
+ end
+ end
+
+ def refuse(refusal, **details)
+ @refusal_details = details
+ refusal
+ end
+
+ # JSON and forms give UTF-8 (a raw invalid byte in a form or JSON body is a
+ # 400 before any controller, Rails' own check). Only a multipart part (REST)
+ # can name a charset of its own or none, and the title's patterns and
+ # String#strip raise on those unless the text is plain ASCII.
+ def utf8?(text)
+ text.valid_encoding? && (text.encoding == Encoding::UTF_8 || text.ascii_only?)
+ end
+
+ def read_title(value)
+ title = Lalabase::Tools::TicketTitle.read(value)
+ return refuse(title, max: Ticket::TITLE_MAX_LENGTH) if title.is_a?(Symbol)
+
+ @title = title
+ nil
+ end
+
+ def read_status(value)
+ return refuse(:status_not_string) unless value.is_a?(String)
+
+ status = value.strip
+ return refuse(:status_empty) if status.empty?
+
+ @field_change = { 'field' => 'status', 'value' => status }
+ nil
+ end
+
+ def read_assignees(fields)
+ lists = {}
+ ASSIGNEE_KEYS.each do |key|
+ ids = fields.key?(key) ? user_ids(key, fields[key]) : []
+ return ids if ids.is_a?(Symbol)
+
+ lists[key] = ids
+ end
+ add, remove = lists.values_at(*ASSIGNEE_KEYS)
+ return refuse(:no_assignees) if add.empty? && remove.empty?
+ # The actor would let add win; a client that sends both has a bug, and
+ # "add wins" would hide it.
+ return refuse(:assignees_overlap) if add.intersect?(remove)
+
+ @field_change = { 'field' => 'assignees', 'add' => add, 'remove' => remove }
+ nil
+ end
+
+ def user_ids(key, value)
+ return refuse(:assignees_not_a_list, list: key) unless value.is_a?(Array) && value.all?(String)
+ return refuse(:too_many_assignees, max: MAX_ASSIGNEE_IDS) if value.size > MAX_ASSIGNEE_IDS
+
+ ids = value.map(&:strip)
+ return refuse(:assignee_invalid, list: key) unless ids.all? { |id| id == ME || Lalabase::Uuid.valid?(id) }
+
+ # One spelling (the one Postgres hands back), so the same person in
+ # capitals or without dashes is the same person in the overlap check
+ # and in the actor's option list. Duplicates stay: the actor collapses
+ # them (AddRemoveBase#add).
+ ids.map { |id| id == ME ? @actor.id.to_s : Lalabase::Uuid.dashed(id) }
+ end
+
+ # The status field of the rule is the one list_tickets reads its keys from:
+ # an active single select named "status". The bulk actor writes any active
+ # field of that name, a checkbox or a date included.
+ def status_field?(project)
+ TicketAttributeDefinition.select_for(project, 'status').present?
+ end
+
+ def write_field(ticket, project)
+ Actors::ApplyTicketChanges.call(project: project, ticket_ids: [ticket.id], changes: [@field_change],
+ current_user: @actor)
+ end
+
+ # The row is locked in THIS project for the whole write, so SaveTicket's
+ # organisation-wide lookup finds exactly this ticket: it can neither have
+ # moved to a project the caller may not write nor have been deleted (and
+ # then built anew).
+ #
+ # The caller is Current.user around the WHOLE transaction: the title
+ # activity is written on commit and names Current.user, and this commit
+ # comes after SaveTicket's own with_actor_context restored the previous
+ # value. Current.set restores it afterwards in turn.
+ def write_title(ticket, project)
+ result = nil
+ Current.set(user: @actor) do
+ ActiveRecord::Base.transaction do
+ next unless project.tickets.lock.exists?(id: ticket.id)
+
+ result = Actors::SaveTicket.call(project: project, params: { title: @title }, id: ticket.id,
+ current_user: @actor)
+ end
+ end
+ result
+ end
+
+ def failure_of(result)
+ code = result.code&.to_sym
+ # The ticket left the project between the lookup and the actor's row lock.
+ return :gone if code == :outside_scope
+ return @kind == :status ? :status_not_allowed : :assignee_not_allowed if code == :value_not_allowed
+ return :no_status_field if @kind == :status && NO_STATUS_FIELD_CODES.include?(code)
+ return @kind == :title ? :title_not_saved : :ticket_not_saved if code == :validation_failed
+ # Only a person the change ADDS is checked (Ticket#assignable_user_ids
+ # keeps whoever stays assigned), so this is one who lost access after
+ # the option list was read.
+ return :user_not_assignable if code == :user_not_assignable
+
+ :unexpected
+ end
+ end
+end
diff --git a/spec/services/tickets/change_spec.rb b/spec/services/tickets/change_spec.rb
new file mode 100644
index 0000000..7462997
--- /dev/null
+++ b/spec/services/tickets/change_spec.rb
@@ -0,0 +1,471 @@
+# frozen_string_literal: true
+
+require 'rails_helper'
+
+# What: Tickets::Change, the one rule of a ticket change through a token: the MCP
+# tool update_ticket and POST /api/v1/tickets/:id/changes (REST R3b).
+# Type: service spec. The tool's answers stay pinned in update_ticket_spec.rb and
+# the wire in the request specs; here is what each surface takes from the
+# rule: the refusal of an input and how a write ended, both named, never
+# worded.
+# Why: The rule moved out of the tool so the two surfaces cannot drift apart.
+# Pinned here: a person removed who was not named, a person who may not be
+# assigned passed over, another JSONB key written, a ticket that moved or
+# was deleted changed or built anew, an actor's exception text handed on.
+#
+# Not tagged :bulk_edit, so Prosopite scans every example here: one write of each
+# kind runs below without draining jobs.
+RSpec.describe Tickets::Change, :ci_guard do
+ let(:organisation) { create(:organisation) }
+ let(:writer) { create(:user) }
+ let(:colleague) { create(:user) }
+ let(:project) { create(:project, organisation: organisation) }
+ let(:ticket) do
+ bulk_ticket({ 'status' => 'open', 'priority' => 'high', 'area' => 'backend' }, title: 'Login bricht ab')
+ end
+
+ before do
+ bulk_project_setup
+ bulk_member(colleague)
+ end
+ after { ActsAsTenant.current_tenant = nil }
+
+ def parse(fields = {}, beside: [], **more)
+ described_class.parse(fields.merge(more), actor: writer, beside: beside)
+ end
+
+ def write(fields, on: ticket, project_of: project)
+ parse(fields).write(ticket: on, project: project_of)
+ end
+
+ def assignees_of(record)
+ record.reload.ticket_assignments.pluck(:user_id)
+ end
+
+ def actor_failure(code, errors: ['PG::Error: secret detail'], resource: nil)
+ Actors::BaseActor::Result.new(success: false, errors: errors, code: code, resource: resource)
+ end
+
+ def broken = "x\xFF".dup.force_encoding('UTF-8')
+
+ describe '.parse' do
+ it 'reads a change of each kind' do
+ expect(parse(title: 'Neu')).to have_attributes(refused?: false, unreadable?: false, kind: :title)
+ expect(parse(status: 'wip')).to have_attributes(refused?: false, kind: :status)
+ expect(parse(add_assignee_ids: ['me'])).to have_attributes(refused?: false, kind: :assignees)
+ expect(parse(remove_assignee_ids: ['me'])).to have_attributes(refused?: false, kind: :assignees)
+ expect(parse(add_assignee_ids: ['me'], remove_assignee_ids: [colleague.id])).to have_attributes(refused?: false)
+ end
+
+ # The two surfaces hand their keys over in their own form.
+ it 'reads string keys like symbols' do
+ expect(parse('status' => 'wip')).to have_attributes(refused?: false, kind: :status)
+ expect(parse(ActiveSupport::HashWithIndifferentAccess.new(status: 'wip'))).to have_attributes(refused?: false, kind: :status)
+ end
+
+ describe 'the keys' do
+ it 'refuses a key it does not know, not ignores it, and hands it to the caller' do
+ change = parse(title: 'Neu', priority: 'low')
+ expect(change).to have_attributes(refusal: :unknown_keys, refused?: true, unreadable?: true)
+ expect(change.refusal_details).to eq(keys: [:priority])
+ end
+
+ it 'takes what the caller reads itself as no unknown key, and as no kind' do
+ expect(parse({ ticket_id: 'x', status: 'wip' }, beside: %i[ticket_id])).to have_attributes(refused?: false, kind: :status)
+ expect(parse({ ticket_id: 'x' }, beside: %i[ticket_id]).refusal).to eq(:one_kind)
+ end
+
+ it 'refuses that key without the caller naming it' do
+ expect(parse(ticket_id: 'x', status: 'wip').refusal).to eq(:unknown_keys)
+ end
+
+ # Rack hands a form key on as it came; Symbol#to_sym cannot hold these bytes.
+ it 'refuses a key of invalid bytes instead of crashing on it' do
+ expect(parse(broken => 1, 'status' => 'wip').refusal).to eq(:unknown_keys)
+ end
+ end
+
+ describe 'the encoding' do
+ # Refused for every field, before any string method runs on them: strip
+ # and the title's patterns raise on these.
+ {
+ 'bytes that are no UTF-8' => -> { broken },
+ 'a part in Latin-1' => -> { "\xE4x".dup.force_encoding('ISO-8859-1') },
+ 'a part in UTF-16' => -> { 'ab'.encode('UTF-16LE').force_encoding('UTF-16') },
+ 'a binary part' => -> { "\xC3\xA4".b }
+ }.each do |label, text|
+ it "refuses #{label} as a title, a status and a list entry" do
+ value = instance_exec(&text)
+ [{ title: value }, { status: value }, { add_assignee_ids: [value] }, { remove_assignee_ids: ['me', value] }].each do |fields|
+ expect(parse(fields)).to have_attributes(refusal: :invalid_utf8, unreadable?: true)
+ end
+ end
+ end
+
+ it 'checks what the caller reads itself too' do
+ expect(parse({ ticket_id: broken, status: 'wip' }, beside: %i[ticket_id])).to have_attributes(refusal: :invalid_utf8)
+ end
+
+ it 'answers an unknown key before the bytes' do
+ expect(parse(status: broken, priority: 'low').refusal).to eq(:unknown_keys)
+ end
+ end
+
+ describe 'one kind per change, by which keys are present' do
+ {
+ 'no change' => {},
+ 'title and status' => { title: 'Neu', status: 'wip' },
+ 'title and add' => { title: 'Neu', add_assignee_ids: ['me'] },
+ 'status and remove' => { status: 'wip', remove_assignee_ids: ['me'] },
+ 'an empty title next to a status' => { title: '', status: 'wip' },
+ 'a nil title next to a status' => { title: nil, status: 'wip' },
+ 'an empty list next to a title' => { title: 'Neu', add_assignee_ids: [] }
+ }.each do |label, fields|
+ it "refuses #{label}" do
+ expect(parse(fields)).to have_attributes(refusal: :one_kind, refused?: true, unreadable?: false)
+ end
+ end
+
+ it 'counts both assignee lists as one kind' do
+ expect(parse(add_assignee_ids: ['me'], remove_assignee_ids: [colleague.id]).refused?).to be false
+ end
+ end
+
+ describe 'the title' do
+ limit = Ticket::TITLE_MAX_LENGTH
+
+ {
+ 'a number' => [5, :title_not_string],
+ 'nil' => [nil, :title_not_string],
+ 'a list' => [['Neu'], :title_not_string],
+ 'a line break' => ["a\nb", :title_forbidden],
+ 'a NUL byte' => ["a#{0.chr}b", :title_forbidden],
+ 'an empty text' => ['', :title_empty],
+ 'spaces alone' => [' ', :title_empty],
+ 'a no-break space alone' => [0xA0.chr(Encoding::UTF_8), :title_empty],
+ 'a text over the limit' => ['a' * (limit + 1), :title_too_long]
+ }.each do |label, (value, refusal)|
+ it "refuses #{label} as #{refusal}" do
+ expect(parse(title: value).refusal).to eq(refusal)
+ end
+ end
+
+ it 'names the limit a too long title is over' do
+ expect(parse(title: 'a' * (limit + 1)).refusal_details).to include(max: limit)
+ end
+
+ it 'takes the limit' do
+ expect(parse(title: 'a' * limit).refused?).to be false
+ end
+ end
+
+ describe 'the status' do
+ { 'a number' => [5, :status_not_string], 'a list' => [['wip'], :status_not_string], 'nil' => [nil, :status_not_string],
+ 'spaces alone' => [' ', :status_empty] }.each do |label, (value, refusal)|
+ it "refuses #{label} as #{refusal}" do
+ expect(parse(status: value).refusal).to eq(refusal)
+ end
+ end
+ end
+
+ describe 'the assignee lists' do
+ %i[add_assignee_ids remove_assignee_ids].each do |key|
+ it "refuses #{key} that is no list of texts, naming the list" do
+ ['some-uuid', nil, [5], [nil], { id: 'me' }].each do |value|
+ change = parse(key => value)
+ expect(change.refusal).to eq(:assignees_not_a_list)
+ expect(change.refusal_details).to eq(list: key)
+ end
+ end
+
+ it "refuses an entry of #{key} that is no user id, naming the list" do
+ change = parse(key => %w[me oops])
+ expect(change.refusal).to eq(:assignee_invalid)
+ expect(change.refusal_details).to eq(list: key)
+ end
+ end
+
+ it 'takes the limit and refuses one more, naming it' do
+ at_limit = Array.new(described_class::MAX_ASSIGNEE_IDS) { SecureRandom.uuid }
+
+ expect(parse(add_assignee_ids: at_limit).refused?).to be false
+ over = parse(remove_assignee_ids: at_limit + [SecureRandom.uuid])
+ expect(over.refusal).to eq(:too_many_assignees)
+ expect(over.refusal_details).to eq(max: 50)
+ end
+
+ it 'refuses lists that name nobody' do
+ expect(parse(add_assignee_ids: []).refusal).to eq(:no_assignees)
+ expect(parse(add_assignee_ids: [], remove_assignee_ids: []).refusal).to eq(:no_assignees)
+ end
+
+ it 'refuses the same user in both lists, however they are spelled' do
+ expect(parse(add_assignee_ids: [colleague.id], remove_assignee_ids: [colleague.id]).refusal).to eq(:assignees_overlap)
+ expect(parse(add_assignee_ids: ['me'], remove_assignee_ids: [writer.id]).refusal).to eq(:assignees_overlap)
+ expect(parse(add_assignee_ids: [writer.id.delete('-').upcase], remove_assignee_ids: ['me']).refusal).to eq(:assignees_overlap)
+ end
+
+ it 'keeps "me" in lower case only' do
+ expect(parse(add_assignee_ids: ['ME']).refusal).to eq(:assignee_invalid)
+ end
+ end
+
+ it 'holds no refusal outside REFUSALS' do
+ expect(%i[unknown_keys invalid_utf8 one_kind status_not_string assignees_overlap] - described_class::REFUSALS).to be_empty
+ end
+ end
+
+ describe '#write' do
+ it 'writes no refused change' do
+ expect(Actors::SaveTicket).not_to receive(:call)
+ expect { write({ title: '' }) }.to raise_error(ArgumentError, /title_empty/)
+ end
+
+ describe 'a status' do
+ it 'goes through the board actor and writes only the status key' do
+ expect(Actors::ApplyTicketChanges).to receive(:call).once.and_call_original
+ outcome = nil
+ expect { outcome = write({ status: ' wip ' }) }.to change(TicketBulkRun, :count).by(1)
+
+ expect(outcome).to have_attributes(written?: true, gone?: false, unexpected?: false, failure: nil)
+ expect(ticket.reload.custom_attributes).to eq('status' => 'wip', 'priority' => 'high', 'area' => 'backend')
+ end
+
+ # Keys come from the project; compared as they are, spelled by the project.
+ it 'refuses a value outside the project catalogue, writing nothing' do
+ ticket
+ outcome = nil
+ expect { outcome = write({ status: 'WIP' }) }.not_to change(TicketBulkRun, :count)
+
+ expect(outcome).to have_attributes(written?: false, failure: :status_not_allowed, reason: :value_not_allowed, messages: [])
+ expect(ticket.reload.custom_attributes['status']).to eq('open')
+ end
+
+ context 'in a project without a status field' do
+ let(:bare_project) { create(:project, organisation: organisation) }
+ let(:bare_ticket) { create(:ticket, project: bare_project, organisation: organisation, creator: writer, title: 'Ohne Status') }
+
+ def status_write
+ write({ status: 'wip' }, on: bare_ticket, project_of: bare_project)
+ end
+
+ it 'is refused before any actor runs' do
+ expect(Actors::ApplyTicketChanges).not_to receive(:call)
+ expect(status_write).to have_attributes(failure: :no_status_field, reason: :no_status_field)
+ end
+
+ # The board writes any active field named "status"; the rule's status is
+ # the select list_tickets reads its keys from.
+ { 'multiselect' => 'wip', 'checkbox' => 'true', 'date' => '2026-10-09' }.each do |field_type, value|
+ it "stays refused when \"status\" is a #{field_type}" do
+ create(:ticket_attribute_definition, project: bare_project, name: 'status', field_type: field_type, position: 1,
+ labels: { 'de' => 'Status', 'en' => 'Status' },
+ options: { 'allowed_values' => [{ 'value' => 'wip', 'labels' => { 'de' => 'wip' } }] })
+ before = bare_ticket.reload.custom_attributes
+
+ outcome = write({ status: value }, on: bare_ticket, project_of: bare_project)
+
+ expect(outcome.failure).to eq(:no_status_field)
+ expect(bare_ticket.reload.custom_attributes).to eq(before)
+ end
+ end
+
+ it 'stays refused when the status select is switched off' do
+ create(:ticket_attribute_definition, project: bare_project, name: 'status', field_type: 'select', position: 1,
+ active: false, labels: { 'de' => 'Status', 'en' => 'Status' },
+ options: { 'allowed_values' => [{ 'value' => 'wip', 'labels' => { 'de' => 'wip' } }] })
+ expect(status_write.failure).to eq(:no_status_field)
+ end
+
+ %i[unknown_field nothing_to_change unknown_kind].each do |code|
+ it "reads the actor's #{code} as no status field" do
+ create(:ticket_attribute_definition, project: bare_project, name: 'status', field_type: 'select', position: 1,
+ labels: { 'de' => 'Status', 'en' => 'Status' },
+ options: { 'allowed_values' => [{ 'value' => 'wip', 'labels' => { 'de' => 'wip' } }] })
+ allow(Actors::ApplyTicketChanges).to receive(:call).and_return(actor_failure(code))
+
+ expect(status_write.failure).to eq(:no_status_field)
+ end
+ end
+ end
+
+ it 'reads a save the model refuses as a ticket not saved, without the board text' do
+ allow(Actors::ApplyTicketChanges).to receive(:call).and_return(actor_failure(:validation_failed, errors: ['Kartentext']))
+
+ expect(write({ status: 'wip' })).to have_attributes(failure: :ticket_not_saved, reason: :validation_failed, messages: [])
+ end
+ end
+
+ describe 'assignees' do
+ it 'adds "me" against the current list, keeping the people on it' do
+ ticket.assignees << colleague
+
+ expect(write({ add_assignee_ids: ['me'] })).to be_written
+ expect(assignees_of(ticket)).to contain_exactly(colleague.id, writer.id)
+ end
+
+ it 'removes only who is named' do
+ ticket.assignees << colleague
+ ticket.assignees << writer
+
+ expect(write({ remove_assignee_ids: [colleague.id] })).to be_written
+ expect(assignees_of(ticket)).to eq([writer.id])
+ end
+
+ it 'reads the list under the actor, not from the ticket the caller holds' do
+ held = Ticket.find(ticket.id)
+ held.assignees.load
+ ticket.assignees << colleague
+
+ expect(write({ add_assignee_ids: ['me'] }, on: held)).to be_written
+ expect(assignees_of(ticket)).to contain_exactly(colleague.id, writer.id)
+ end
+
+ it 'refuses a person the project does not offer, and takes nobody off' do
+ ticket.assignees << colleague
+ outcome = write({ add_assignee_ids: [SecureRandom.uuid], remove_assignee_ids: [colleague.id] })
+
+ expect(outcome).to have_attributes(failure: :assignee_not_allowed, reason: :value_not_allowed)
+ expect(assignees_of(ticket)).to eq([colleague.id])
+ end
+
+ it 'refuses a person who lost access meanwhile, and takes nobody off' do
+ ticket.assignees << colleague
+ allow_any_instance_of(Ticket).to receive(:assignable_user_ids).and_return([])
+
+ outcome = write({ add_assignee_ids: ['me'], remove_assignee_ids: [colleague.id] })
+
+ expect(outcome).to have_attributes(failure: :user_not_assignable, reason: :user_not_assignable)
+ expect(assignees_of(ticket)).to eq([colleague.id])
+ end
+
+ it 'keeps a stale assignee who is not named' do
+ stale = create(:user)
+ create(:membership, user: stale, organisation: organisation, role: create(:role, organisation: organisation))
+ ticket.ticket_assignments.create!(user: stale)
+
+ expect(write({ add_assignee_ids: ['me'] })).to be_written
+ expect(assignees_of(ticket)).to contain_exactly(stale.id, writer.id)
+ end
+ end
+
+ describe 'a title' do
+ before { ticket.assignees << colleague }
+
+ it 'goes through SaveTicket alone, with the title alone' do
+ expect(Actors::SaveTicket).to receive(:call)
+ .with(project: project, params: { title: 'Neu' }, id: ticket.id, current_user: writer).and_call_original
+ expect(Actors::ApplyTicketChanges).not_to receive(:call)
+
+ expect(write({ title: ' Neu ' })).to be_written
+ expect(ticket.reload).to have_attributes(title: 'Neu', assignees: [colleague],
+ custom_attributes: { 'status' => 'open', 'priority' => 'high', 'area' => 'backend' })
+ end
+
+ it 'names the caller in the history, also without an ambient Current.user' do
+ Current.reset
+
+ expect { write({ title: 'Neu' }) }.to change { Activity.where(trackable: ticket, key: 'ticket.title_changed', actor: writer).count }.by(1)
+ expect(Current.user).to be_nil
+ end
+
+ it 'hands on the messages of a title the model refuses' do
+ ticket.update_column(:number, nil)
+
+ outcome = I18n.with_locale(:en) { write({ title: 'Neu' }) }
+
+ expect(outcome).to have_attributes(failure: :title_not_saved, reason: :validation_failed)
+ expect(I18n.with_locale(:en) { outcome.messages }).to eq(["Number can't be blank"])
+ expect(I18n.with_locale(:de) { outcome.messages }).to eq(['Nummer darf nicht leer sein'])
+ expect(ticket.reload.title).to eq('Login bricht ab')
+ end
+
+ it 'locks the ticket in this project and writes inside that transaction' do
+ ticket
+ statements = []
+ depth_at_write = nil
+ outer_depth = ActiveRecord::Base.connection.open_transactions
+ allow(Actors::SaveTicket).to receive(:call).and_wrap_original do |original, **kwargs|
+ depth_at_write = ActiveRecord::Base.connection.open_transactions
+ original.call(**kwargs)
+ end
+ collect = ->(*, payload) { statements << payload[:sql] }
+
+ ActiveSupport::Notifications.subscribed(collect, 'sql.active_record') { write({ title: 'Neu' }) }
+
+ lock = statements.find { |sql| sql.include?('FROM "tickets"') && sql.include?('FOR UPDATE') }
+ expect(lock).to include('"tickets"."project_id"')
+ expect(depth_at_write).to be > outer_depth
+ end
+ end
+
+ # After the caller's lookup: SaveTicket finds a ticket organisation-wide and
+ # builds a new one for an id it does not find.
+ describe 'a ticket that left after the lookup' do
+ let(:elsewhere) { create(:project, organisation: organisation) }
+
+ it 'keeps a moved ticket from being renamed there' do
+ ticket
+ Ticket.where(id: ticket.id).update_all(project_id: elsewhere.id)
+
+ expect(write({ title: 'Gekapert' })).to have_attributes(gone?: true, written?: false, unexpected?: false)
+ expect(ticket.reload.title).to eq('Login bricht ab')
+ end
+
+ it 'builds no ticket for a deleted one' do
+ ticket
+ Ticket.where(id: ticket.id).delete_all
+
+ expect(write({ title: 'Phantom' })).to be_gone
+ expect(Ticket.where(title: 'Phantom')).not_to exist
+ end
+
+ it 'answers a moved ticket as gone for a status too' do
+ ticket
+ Ticket.where(id: ticket.id).update_all(project_id: elsewhere.id)
+
+ expect(write({ status: 'wip' })).to be_gone
+ expect(ticket.reload.custom_attributes['status']).to eq('open')
+ end
+
+ it "reads the actor's outside_scope as gone" do
+ allow(Actors::ApplyTicketChanges).to receive(:call).and_return(actor_failure(:outside_scope))
+
+ expect(write({ status: 'wip' })).to be_gone
+ end
+ end
+
+ describe 'a failure the rule does not name' do
+ %i[internal_error stale_object not_member stock_changed].each do |code|
+ it "is unexpected for #{code}, and hands on no text" do
+ allow(Actors::ApplyTicketChanges).to receive(:call).and_return(actor_failure(code))
+ outcome = write({ status: 'wip' })
+
+ expect(outcome).to have_attributes(written?: false, unexpected?: true, messages: [])
+ end
+ end
+
+ it 'is unexpected for SaveTicket as well' do
+ allow(Actors::SaveTicket).to receive(:call).and_return(actor_failure(:internal_error, resource: ticket))
+
+ expect(write({ title: 'Neu' })).to have_attributes(unexpected?: true, messages: [])
+ end
+
+ # On a title or an assignee list the codes of a missing status field mean
+ # something else, and the rule does not read them as that.
+ it 'is unexpected for an unknown field on an assignee change' do
+ allow(Actors::ApplyTicketChanges).to receive(:call).and_return(actor_failure(:unknown_field))
+
+ expect(write({ add_assignee_ids: ['me'] })).to be_unexpected
+ end
+ end
+ end
+
+ describe 'the lists a caller words' do
+ it 'names every failure once, each with a reason a client reads' do
+ expect(described_class::REASONS.values.uniq)
+ .to contain_exactly(:value_not_allowed, :user_not_assignable, :no_status_field, :validation_failed)
+ expect(described_class::FAILURES).to eq(described_class::REASONS.keys)
+ end
+ end
+end