Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 31 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,35 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

## [0.2.0] - 2026-06-23

### Added

- **Custom action verbs.** Declare a named action inside the `signoff` block —
`action(name, to:, from: nil)` — to model any workflow verb beyond the built-in
`submit`/`approve`/`reject`. Each declared action generates a `name!` transition
method (accepting the usual `user:`, `comment:`, `metadata:`, `ip_address:`,
`user_agent:` keywords) and a non-raising `can_name?(user = nil)` predicate, and
records a `Signoff::Event` whose `action` is the verb name verbatim — so the
audit trail stays semantically truthful (e.g. `request_changes`, `cancel`,
`escalate`). Like `reject`, a custom action is a guarded *side transition*: its
target is never a forward edge, so it cannot make `approve!` ambiguous. `from:`
limits the permitted source states (single state or array) and defaults to every
non-finalized state except the action's own target. Custom actions reuse the
source state's `allow_transition` guard.
- **Multi-source forward transitions.** `transition` now accepts an array for
`from` as well as `to`, so several states can share one forward edge —
`transition [:draft, :rejected, :changes_requested], to: :review`.

### Changed

- `approved?` / the `.approved` scope now exclude custom-action target states, and
`pending?` / the `.pending` scope treat a *terminal* custom-action target (e.g.
`cancelled`) as finalized while a *looping* target (e.g. `changes_requested`,
which re-submits) stays in flight. Workflows without custom actions are
unaffected — the finalized set remains exactly the approval terminals plus the
reject state.

## [0.1.0] - 2026-06-05

Initial public release. `signoff` adds concurrency-safe approval workflows
Expand Down Expand Up @@ -75,5 +104,6 @@ and 8.x, backed by PostgreSQL — no external services required.
`MissingColumnError`.
- **Rails 7.x and 8.x support** on Ruby >= 3.2 with PostgreSQL.

[Unreleased]: https://github.com/JijoBose/Signoff/compare/v0.1.0...HEAD
[Unreleased]: https://github.com/JijoBose/Signoff/compare/v0.2.0...HEAD
[0.2.0]: https://github.com/JijoBose/Signoff/compare/v0.1.0...v0.2.0
[0.1.0]: https://github.com/JijoBose/Signoff/releases/tag/v0.1.0
72 changes: 67 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -471,15 +471,71 @@ the state column for a single model (e.g. `signoff(column: :workflow_state) do`)
| `state(name, initial: false)` | Declare a state. `initial: true` marks the start state. |
| `states(*names)` | Declare several states at once. |
| `initial_state(name)` | Set the start state explicitly (defaults to the first declared). |
| `transition(from, to:)` | Declare a forward transition. `to:` accepts a symbol or an array. |
| `transition(from, to:)` | Declare a forward transition. Both `from` and `to:` accept a symbol or an array. |
| `reject_to(state)` | The state `reject!` moves a record into. |
| `action(name, to:, from: nil)` | Declare a custom verb (e.g. `:request_changes`). Generates `name!` / `can_name?` and records `action` verbatim. A guarded side transition — never a forward edge. `from:` limits sources (defaults to any non-finalized state). |
| `allow_transition(from) { \|user[, record]\| ... }` | Authorize transitions **out of** `from`. |
| `before_transition { \|record, from, to\| ... }` | Run inside the transaction, before the state is written. |
| `after_transition { \|record, event\| ... }` | Run after the transaction commits (great for jobs/mail). |

Definitions are validated when the class loads. You'll get a descriptive
`Signoff::DefinitionError` for duplicate states, transitions to/from
undeclared states, a missing initial state, or an undeclared reject state.
undeclared states, a missing initial state, an undeclared reject state, or a
custom `action` that is named after a built-in verb or targets an undeclared
state.

### Custom actions

`submit`, `approve`, and `reject` cover the common path, but real workflows have
more verbs — request changes, escalate, cancel, return-to-sender. Declare them
with `action` and the audit trail stays truthful (the recorded `action` is the
verb name, not a repurposed `"reject"`):

```ruby
class Post < ApplicationRecord
include Signoff

signoff do
states :draft, :in_review, :approved, :rejected, :changes_requested, :cancelled

# Several states share one forward edge (re-submission re-enters review):
transition %i[draft rejected changes_requested], to: :in_review
transition :in_review, to: :approved

reject_to :rejected

# A looping off-ramp — re-submission brings it back into review:
action :request_changes, from: :in_review, to: :changes_requested
# A terminal off-ramp from any in-flight state (no :from given):
action :cancel, to: :cancelled

allow_transition :in_review do |user|
user.editor?
end
end
end

post.request_changes!(user: current_user, comment: "Tighten the intro")
post.current_state # => :changes_requested
post.workflow_history.last.action # => "request_changes" (truthful)
post.can_request_changes?(other) # => true / false (never raises)
post.submit! # changes_requested -> in_review again
post.cancel!(user: current_user) # -> cancelled
```

A custom action behaves like a first-class `reject`:

- It is a **guarded side transition** — its target is never a forward edge, so a
state can offer `approve!` *and* `request_changes!`/`cancel!` without making
`approve!` ambiguous.
- It reuses the **source state's `allow_transition` guard**. Unauthorized calls
raise `Signoff::UnauthorizedError`; the generated `can_<name>?` predicate reports
permission without raising.
- `from:` limits the permitted source states (a symbol or array). Omit it and the
action is allowed from any non-finalized state except its own target.
- Targets that **loop back** into the flow (like `changes_requested`) count as
*in flight* (`pending?` / `.pending`); targets with no way out (like
`cancelled`) count as *finalized* — and neither is ever reported as `approved?`.

## Instance API

Expand All @@ -491,6 +547,9 @@ Including `Signoff` and declaring a workflow generates:
report.submit!(user: nil, comment: nil, metadata: {}, to: nil)
report.approve!(user: nil, comment: nil, metadata: {}, to: nil)
report.reject!(user: nil, comment: nil, metadata: {})

# Plus one method per declared custom action, e.g.:
report.request_changes!(user: nil, comment: nil, metadata: {})
```

- `submit!` and `approve!` both advance the **single forward transition** from the
Expand All @@ -499,6 +558,8 @@ report.reject!(user: nil, comment: nil, metadata: {})
- When a state has **more than one** forward transition, pass `to:` to disambiguate
(`report.approve!(to: :finance_review)`).
- `reject!` moves the record to the `reject_to` state.
- Each custom `action :name` generates a `name!` method that records `"name"` as
the audit `action` (see [Custom actions](#custom-actions)).
- All accept `ip_address:` and `user_agent:` keyword overrides (see
[Configuration](#configuration)).
- Each returns the created `Signoff::Event`.
Expand All @@ -521,11 +582,12 @@ report.finance_review?
### Authorization predicates

```ruby
report.can_approve?(current_user) # => true / false (never raises)
report.can_reject?(current_user) # => true / false
report.can_approve?(current_user) # => true / false (never raises)
report.can_reject?(current_user) # => true / false
report.can_request_changes?(current_user) # => one per custom action
```

Both fall back to `Signoff::Current.user` when no argument is given.
All fall back to `Signoff::Current.user` when no argument is given.

### Audit helpers

Expand Down
97 changes: 88 additions & 9 deletions lib/signoff/definition.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,19 @@ module Signoff
# lifecycle callbacks. Built by Signoff::DSL and stored on the model
# class as +signoff_definition+.
class Definition
# Built-in verbs that own their own transition methods on the model; a
# custom +action+ may not reuse these names.
RESERVED_ACTIONS = %i[submit approve reject].freeze

attr_reader :states, :transitions, :authorizations,
:before_callbacks, :after_callbacks, :state_column
:before_callbacks, :after_callbacks, :state_column, :actions
attr_writer :initial_state

def initialize(state_column: :approval_state)
@states = []
@transitions = {} # from(Symbol) => [to(Symbol), ...]
@authorizations = {} # from(Symbol) => callable guard
@actions = {} # name(Symbol) => { to: Symbol, from: [Symbol]|nil }
@before_callbacks = []
@after_callbacks = []
@initial_state = nil
Expand All @@ -31,18 +36,36 @@ def add_state(name)
end

def add_transition(from, to)
from = from.to_sym
Array(to).each do |target|
target = target.to_sym
@transitions[from] ||= []
@transitions[from] << target unless @transitions[from].include?(target)
Array(from).each do |source|
source = source.to_sym
Array(to).each do |target|
target = target.to_sym
@transitions[source] ||= []
@transitions[source] << target unless @transitions[source].include?(target)
end
end
end

def add_authorization(from, guard)
@authorizations[from.to_sym] = guard
end

# Register a named custom action: a guarded "side transition" that moves a
# record to +to+ and records an event whose +action+ is the name verbatim.
# Like +reject+, the target is NOT a forward transition, so it never makes
# +approve!+ ambiguous. +from+ limits the source states (defaults to every
# non-finalized state except the target itself).
def add_action(name, to:, from: nil)
name = name.to_sym
raise DefinitionError, "duplicate action #{name.inspect}" if @actions.key?(name)
raise DefinitionError, "action #{name.inspect} requires a :to state" if to.nil?

@actions[name] = {
to: to.to_sym,
from: from.nil? ? nil : Array(from).map(&:to_sym)
}
end

def reject_state=(name)
@reject_state = name&.to_sym
end
Expand All @@ -65,10 +88,42 @@ def terminal_states
@states.reject { |s| forward_targets(s).any? }
end

# Terminal states that represent successful completion (everything that is
# terminal except the reject state).
# Terminal states that represent successful completion: terminal via the
# forward flow and not reachable only as an off-ramp (reject or a custom
# action target). This keeps +approved?+ true for genuine end states only.
def approval_terminal_states
terminal_states - [reject_state].compact
terminal_states - [reject_state].compact - action_target_states
end

# Every state that ends the workflow: successful terminals, the reject
# state, and any custom-action target that has no forward transition out
# (e.g. a +cancel+ action's +cancelled+ state). Off-ramp targets that loop
# back (e.g. +changes_requested+ -> re-submit) stay in flight, not finalized.
def finalized_states
terminal_action_targets = action_target_states.select { |s| forward_targets(s).empty? }
(approval_terminal_states + [reject_state].compact + terminal_action_targets).uniq
end

# The distinct set of states reachable via custom actions.
def action_target_states
@actions.values.map { |spec| spec[:to] }.uniq
end

def action_names
@actions.keys
end

def action_for(name)
@actions[name.to_sym]
end

# States a custom action may be invoked from. An explicit +from:+ wins;
# otherwise any non-finalized state except the action's own target.
def action_allowed_from(name)
spec = @actions.fetch(name.to_sym)
return spec[:from] if spec[:from]

states - finalized_states - [spec[:to]]
end

def guard_for(state)
Expand Down Expand Up @@ -111,6 +166,7 @@ def validate!
validate_transitions!
validate_reject_state!
validate_authorizations!
validate_actions!
self
end

Expand Down Expand Up @@ -155,5 +211,28 @@ def validate_authorizations!
"allow_transition references undeclared state #{state.inspect}"
end
end

def validate_actions!
@actions.each do |name, spec|
if RESERVED_ACTIONS.include?(name)
raise DefinitionError,
"action #{name.inspect} is reserved; #{name}! is a built-in verb"
end

unless @states.include?(spec[:to])
raise DefinitionError,
"action #{name.inspect} targets undeclared state #{spec[:to].inspect}"
end

next unless spec[:from]

spec[:from].each do |from|
next if @states.include?(from)

raise DefinitionError,
"action #{name.inspect} references undeclared from-state #{from.inspect}"
end
end
end
end
end
20 changes: 19 additions & 1 deletion lib/signoff/dsl.rb
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,9 @@ def initial_state(name)
@definition.initial_state = name
end

# Declare a forward transition. +to+ accepts a single state or an array.
# Declare a forward transition. Both +from+ and +to+ accept a single state
# or an array, so several source states can share one forward edge
# (e.g. +transition [:draft, :rejected], to: :review+).
def transition(from, to:)
@definition.add_transition(from, to)
end
Expand All @@ -57,6 +59,22 @@ def reject_to(state)
@definition.reject_state = state
end

# Declare a named custom action. It generates a +name!+ transition method
# and a +can_name?+ predicate on the model, records an event whose +action+
# is the name verbatim, and is authorized by the same +allow_transition+
# guard as the source state. Like +reject+, the target is a side-transition
# (never a forward edge), so +approve!+ stays unambiguous. This is the
# extension point for modelling any workflow verb beyond submit/approve/reject.
#
# action :request_changes, from: :pending_review, to: :changes_requested
# action :cancel, to: :cancelled # from any in-flight state
#
# +from+ is optional and may be a single state or an array; when omitted the
# action is allowed from every non-finalized state except its own target.
def action(name, to:, from: nil)
@definition.add_action(name, to: to, from: from)
end

# Authorize transitions out of +from_state+. The block receives the acting
# user (and optionally the record) and must return a truthy value to allow
# the transition.
Expand Down
Loading
Loading