diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6b19ffd..c1ad98f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -74,6 +74,9 @@ jobs: - name: Exercise opt-in declaration extraction run: bundle exec ruby scripts/check_declarations.rb + - name: Exercise declared method signatures + run: bundle exec ruby scripts/check_method_signatures.rb + - name: Exercise architecture presets run: bundle exec ruby scripts/check_presets.rb @@ -185,6 +188,7 @@ jobs: ruby scripts/check_analysis_diagnostics.rb ruby scripts/check_baselines.rb ruby scripts/check_declarations.rb + ruby scripts/check_method_signatures.rb ruby scripts/check_presets.rb ruby scripts/check_named_calls.rb ruby scripts/check_documentation_examples.rb diff --git a/API.md b/API.md index 6f7ebed..991e6cb 100644 --- a/API.md +++ b/API.md @@ -289,6 +289,37 @@ selector covers all in-scope declaration sites for a class, not a particular fol Use `CheckOptions.new(source_exclusions: ...)` to limit the source set. Cached declaration facts refresh with `clear_cache: true` or `ArchUnit.clear_graph_cache`. +### Declared method signatures (unreleased) + +~~~ ruby +shape = ArchUnit::MethodSignature.new(name: :call, positional: 1, keywords: %i[actor request_id]) +rule = ArchUnit.project_classes(root).in_namespace('Commands').should.declare_method(shape) +ArchUnit.assert_passes(rule) +~~~ + +The rule requires an ordinary `def` on each selected class that accepts the specified call. +`positional` is the number passed, not the number written. `keywords` is the exact set passed: +omitting a required keyword fails, and a keyword-rest parameter accepts extras. Implicit conversion +to a positional Hash is not a named keyword interface. `scope: :singleton` checks `def self.call` +and `class << self`; `block: :declared` requires explicit block capture or forwarding syntax. +The default is `scope: :instance, block: :any`. +Use method and keyword names in their declared source encoding for non-ASCII identifiers. + +This is declaration-only: methods inherited or supplied by mixins, aliasing, or metaprogramming +do not satisfy it. It does not prove public visibility, receiver behavior, or return types. +Conditional definitions, ambiguous class selection, or conflicting signatures fail as unknown. +Multiple known declarations satisfy the rule if they all accept the requested call. Empty scopes +fail unless explicitly allowed; that option does not suppress unknown results. The negative mood +is not offered. + +The same scope is available as `project_classes` in a named CLI rule. JSON adds a +`method_signature` object carrying the expected shape, observed candidates and source locations. +Non-ASCII identifiers in legacy encodings are reported with `text`, `encoding`, and hex +`bytes` rather than a bare string; this preserves distinct Ruby names with the same spelling. +Confirmed failures can use baselines; the fingerprint includes the normalized selector and +expected shape. Unknowns fail a plain CLI check (exit 1) and reject baseline creation or use +before any accepted-debt write (exit 2). + ## Checking and test frameworks Every architecture rule includes `ArchUnit::Checkable` and exposes `check(options = nil)`. It returns diff --git a/CHANGELOG.md b/CHANGELOG.md index ecb7b85..5e2bc87 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,8 @@ reports. This can reveal previously missed violations, including in imports-only projects. - Inspect declared classes by exact constant name, namespace, or bounded superclass ancestry. Keep reopened source sites and surface uncertain results without changing file dependency rules. +- Require written instance or singleton methods with a compatible call shape, reporting uncertainty + as a failure rather than counting it as a supported signature or accepted debt. - Lazily reuse immutable node/internal/external-edge views within each cached graph analysis across file and layer checks. Invalidation, per-rule filtering, callbacks and logging stay intact; views trade additional retained memory for less repeated projection work. diff --git a/benchmark/study/README.md b/benchmark/study/README.md index c47a2e1..6355793 100644 --- a/benchmark/study/README.md +++ b/benchmark/study/README.md @@ -150,6 +150,14 @@ Ruby allocations respectively. The median post-GC heap increase after the cold c gem require and first opt-in scope setup, and verifies the default require did not load declaration extraction. These are fixture measurements, not timing ceilings. +Run `bundle exec ruby benchmark/study/method_signatures.rb` to reuse that fixture for 20 +declaration-based rules (ten passing, ten rejecting all 499 subclasses). Every trial checks all +findings before accepting the measurement. Five Windows / Ruby 4.0.6 trials measured a median +**560,233 allocations with one shared inventory** versus **2,244,077** when deliberately +rebuilding before each rule. Median added Ruby heap after GC for the shared run was about +**287 KiB**. The timings (1.78 s and 14.98 s respectively) and startup sample were taken with +other checks running on the local machine; do not read them as isolated latency guarantees. + ## Real production source `real_project.rb` checks pinned Discourse `2de9c9be4f89e392fe500dd27f928d6b1184bf09`, with three diff --git a/benchmark/study/declaration_selection.rb b/benchmark/study/declaration_selection.rb index c2269e6..48a43f6 100644 --- a/benchmark/study/declaration_selection.rb +++ b/benchmark/study/declaration_selection.rb @@ -87,4 +87,4 @@ def median(samples) end end -DeclarationSelectionStudy.run +DeclarationSelectionStudy.run if $PROGRAM_NAME == __FILE__ diff --git a/benchmark/study/method_signatures.rb b/benchmark/study/method_signatures.rb new file mode 100644 index 0000000..bcbbc89 --- /dev/null +++ b/benchmark/study/method_signatures.rb @@ -0,0 +1,58 @@ +# frozen_string_literal: true + +require_relative 'declaration_selection' + +# Compares one shared index with deliberately refreshing it before each rule. +module MethodSignatureStudy + STUDY = DeclarationSelectionStudy + RULES = 20 + private_constant :STUDY, :RULES + + module_function + + def run + startup = STUDY.measure_default_load + Dir.mktmpdir('archunit-signature-bench') do |directory| + root = Pathname.new(directory) + STUDY.fixture(root) + rules = fixtures(root) + result = measurements(rules).merge(ruby: RUBY_DESCRIPTION, startup:, rules: RULES, + files: STUDY::FILES, trials: STUDY::TRIALS) + puts JSON.pretty_generate(result) + end + end + + def fixtures(root) + scope = ArchUnit.project_classes(root).descendants_of('Node0') + Array.new(RULES) do |index| + signature = ArchUnit::MethodSignature.new(name: :call, positional: index.even? ? 1 : 2) + scope.should.declare_method(signature) + end + end + + def measurements(rules) + shared, refresh, retained = Array.new(STUDY::TRIALS) { paired_sample(rules) }.transpose + { shared_median: STUDY.median(shared), refreshed_median: STUDY.median(refresh), + retained_heap_bytes: retained.sort.fetch(STUDY::TRIALS / 2) } + end + + def paired_sample(rules) + ArchUnit.clear_graph_cache + before = STUDY.heap_bytes + shared = STUDY.measure { verify(rules) } + retained = STUDY.heap_bytes - before + clear = ArchUnit::CheckOptions.new(clear_cache: true) + refreshed = STUDY.measure { verify(rules, clear) } + [shared, refreshed, retained] + end + + def verify(rules, options = nil) + rules.each_with_index do |rule, index| + results = rule.check(options) + expected = index.even? ? 0 : STUDY::FILES - 1 + raise 'wrong number of findings' unless results.size == expected && results.none?(&:unknown?) + end + end +end + +MethodSignatureStudy.run diff --git a/design/declared-method-signatures.md b/design/declared-method-signatures.md new file mode 100644 index 0000000..97c4ab3 --- /dev/null +++ b/design/declared-method-signatures.md @@ -0,0 +1,34 @@ +# Declared method signatures (#105) + +The first rule reads “project classes in Commands should declare method call with this signature”: + +~~~ruby +signature = ArchUnit::MethodSignature.new(name: :call, positional: 1, keywords: %i[actor request_id]) +rule = ArchUnit.project_classes.in_namespace('Commands').should.declare_method(signature) +~~~ + +This is the **declared-here** milestone: an ordinary `def` on each selected class must accept the +given call shape. Inheritance, mixins, aliases, `define_method`, and `method_missing` do not count as +direct declarations. The rule does not claim runtime visibility, method behavior, or effective API +coverage. A separate effective-lookup feature needs precedence, alias, reflection, and uncertainty +decisions before it can share any public meaning of “implements”. Negative mood is not exposed. + +Positional options describe the number passed (optional/rest parameters may accept it). +Keywords describe the exact named arguments passed: extra required keywords invalidate the +contract, `**kwargs` accepts extras, and `**nil` accepts no nonempty keyword set. Implicit Ruby +conversion of keywords to a positional Hash is not a declared keyword interface. +`scope: :singleton` matches methods written as `def self.name` or `class << self`. +`block: :declared` requires `&block`, anonymous `&`, or forwarding `...`; this does not prove +that code invokes a block. Without that option, no explicit block-capture parameter is required. + +Conditional declarations, ambiguous ownership and mixed compatible/incompatible reopens are +unknown. If all direct candidates accept the shape, a compatible shape is known without choosing +load order. If none accepts it, the signature is incompatible. Missing written declarations, +incompatible shapes, and unknowns are distinct findings; all fail the check. A known empty +selection follows the standard empty-test guard. Unknowns cannot be suppressed with +`allow_empty_tests` or written to or accepted by an accepted-debt baseline. + +Confirmed failures use a structured identity covering the normalized selector, policy version, +expected shape, class name, and observed shape/file evidence without line numbers. The observed +source snapshot has its own `source_declarations` context and the same exclusions/refresh rules as +class selection. The dependency graph does not change. diff --git a/lib/archunit.rb b/lib/archunit.rb index 9357430..991be32 100644 --- a/lib/archunit.rb +++ b/lib/archunit.rb @@ -24,6 +24,7 @@ require_relative 'archunit/common/projection/project_edges' require_relative 'archunit/common/projection/project_to_nodes' require_relative 'archunit/classes/fluentapi/classes' +require_relative 'archunit/classes/fluentapi/method_signature' require_relative 'archunit/common/projection/project_cycles' require_relative 'archunit/extraction/locate_project' require_relative 'archunit/extraction/enumerate_source_files' @@ -109,6 +110,7 @@ module ArchUnit MetricPredicateViolation = Metrics::Assertion::MetricPredicateViolation CustomMetricViolation = Metrics::Assertion::CustomMetricViolation TestViolation = Testing::TestViolation + MethodSignatureViolation = Classes::Assertion::MethodSignatureViolation TestResult = Testing::TestResult ColorUtils = Testing::ColorUtils ViolationFactory = Testing::ViolationFactory diff --git a/lib/archunit/classes/assertion/callable_shape.rb b/lib/archunit/classes/assertion/callable_shape.rb new file mode 100644 index 0000000..5c220cb --- /dev/null +++ b/lib/archunit/classes/assertion/callable_shape.rb @@ -0,0 +1,48 @@ +# frozen_string_literal: true + +module ArchUnit + module Classes + module Assertion + # Checks call compatibility using only a method's written parameter shapes. + module CallableShape + REQUIRED = %i[required post destructured].freeze + private_constant :REQUIRED + + def self.matches?(parameters, signature) + groups = parameters.group_by(&:kind) + accepts_positionals?(groups, signature.positional) && + accepts_keywords?(groups, signature.keywords) && + accepts_block?(groups, signature.block) + end + + def self.accepts_positionals?(groups, count) + minimum = REQUIRED.sum { |key| groups.fetch(key, []).size } + return false if count < minimum + return true if groups.key?(:rest) || groups.key?(:forwarding) + + count <= minimum + groups.fetch(:optional, []).size + end + + def self.accepts_keywords?(groups, requested) + return requested.empty? if groups.key?(:no_keywords) + + required = names(groups, :required_keyword) + return false unless (required - requested).empty? + return true if groups.key?(:keyword_rest) || groups.key?(:forwarding) + + (requested - required - names(groups, :optional_keyword)).empty? + end + + def self.names(groups, kind) + groups.fetch(kind, []).map { |parameter| parameter.name.to_s } + end + + def self.accepts_block?(groups, policy) + policy == :any || groups.key?(:block) || groups.key?(:forwarding) + end + private_class_method :accepts_positionals?, :accepts_keywords?, :names, :accepts_block? + end + private_constant :CallableShape + end + end +end diff --git a/lib/archunit/classes/assertion/empty_class_selection_violation.rb b/lib/archunit/classes/assertion/empty_class_selection_violation.rb new file mode 100644 index 0000000..c56b2e9 --- /dev/null +++ b/lib/archunit/classes/assertion/empty_class_selection_violation.rb @@ -0,0 +1,28 @@ +# frozen_string_literal: true + +require_relative '../../common/assertion/empty_test_violation' + +module ArchUnit + module Classes + module Assertion + # The ordinary empty-test defense with the actual class selector attached. + class EmptyClassSelectionViolation < Common::Assertion::EmptyTestViolation + attr_reader :scope + + def initialize(scope) + @scope = scope + super(filters: []) + end + + def ==(other) + other.instance_of?(self.class) && scope == other.scope + end + alias eql? == + + def hash + [self.class, scope].hash + end + end + end + end +end diff --git a/lib/archunit/classes/assertion/method_signature_violation.rb b/lib/archunit/classes/assertion/method_signature_violation.rb new file mode 100644 index 0000000..2e411cf --- /dev/null +++ b/lib/archunit/classes/assertion/method_signature_violation.rb @@ -0,0 +1,39 @@ +# frozen_string_literal: true + +require_relative '../../common/assertion/violation' + +module ArchUnit + module Classes + module Assertion + # Data describing a missing, incompatible, or uncertain written method contract. + class MethodSignatureViolation < Common::Assertion::Violation + Finding = Data.define(:owner, :expected, :reason, :candidates, :declarations, :scope, + :ancestor) + CONFIRMED = %i[missing_declaration incompatible_signature].freeze + private_constant :CONFIRMED + + attr_reader :finding + + def initialize(finding) + raise ArgumentError, 'finding must be a method finding' unless finding.is_a?(Finding) + + @finding = finding + super() + end + + def unknown? + !CONFIRMED.include?(finding.reason) + end + + def ==(other) + other.is_a?(self.class) && finding == other.finding + end + alias eql? == + + def hash + [self.class, finding].hash + end + end + end + end +end diff --git a/lib/archunit/classes/assertion/method_signatures.rb b/lib/archunit/classes/assertion/method_signatures.rb new file mode 100644 index 0000000..f8045a0 --- /dev/null +++ b/lib/archunit/classes/assertion/method_signatures.rb @@ -0,0 +1,64 @@ +# frozen_string_literal: true + +require_relative 'callable_shape' +require_relative 'method_signature_violation' + +module ArchUnit + module Classes + # Pure checks on explicit class/method declarations. + module Assertion + module_function + + def gather_method_signature_violations(selection, signature, scope) + definite = selection.matches.filter_map { |klass| check_signature(klass, signature, scope) } + unresolved = selection.uncertainties.map do |subject| + signature_violation(subject, signature, scope, [].freeze, subject.reason) + end + definite + unresolved + end + + def check_signature(subject, signature, scope) + candidates = method_candidates(subject, signature) + reason = signature_failure(candidates, signature) + signature_violation(subject, signature, scope, candidates, reason) if reason + end + private_class_method :check_signature + + def method_candidates(subject, signature) + subject.method_declarations.select do |method| + (method.scope == signature.scope || method.scope == :unknown) && + method.name.to_s == signature.name + end.freeze + end + private_class_method :method_candidates + + def signature_failure(candidates, signature) + return :missing_declaration if candidates.empty? + return :uncertain_method_declaration if candidates.any? { |method| uncertain?(method) } + + matching = candidates.count do |method| + CallableShape.matches?(method.parameters, signature) + end + return :incompatible_signature if matching.zero? + + :conflicting_signatures if matching != candidates.size + end + private_class_method :signature_failure + + def uncertain?(method) + method.context != :direct || method.scope == :unknown + end + private_class_method :uncertain? + + def signature_violation(subject, expected, scope, candidates, reason) + ancestor = subject.ancestor if subject.respond_to?(:ancestor) + finding = MethodSignatureViolation::Finding.new( + owner: subject.name, expected:, reason:, candidates:, declarations: subject.declarations, + scope:, ancestor: + ) + MethodSignatureViolation.new(finding) + end + private_class_method :signature_violation + end + end +end diff --git a/lib/archunit/classes/fluentapi/class_scope.rb b/lib/archunit/classes/fluentapi/class_scope.rb index 29ef098..3d8963d 100644 --- a/lib/archunit/classes/fluentapi/class_scope.rb +++ b/lib/archunit/classes/fluentapi/class_scope.rb @@ -4,6 +4,7 @@ require_relative '../../extraction/declarations' require_relative '../projection/select_classes' require_relative 'class_filters' +require_relative 'positive_class_condition_builder' module ArchUnit # Inspection of bounded class declarations, kept separate from file graph rules. @@ -35,6 +36,17 @@ def descendants_of(name) adding(:ancestor, name) end + # Begins a positive declaration rule without reading the project. + # @return [PositiveClassConditionBuilder] + def should + PositiveClassConditionBuilder.new(self) + end + + # @api private + def identity + @filters.to_h.transform_values { |names| names.sort.freeze }.freeze + end + # Reads a declaration snapshot. This is inspection, not a passing/failing rule. # @param options [CheckOptions, nil] # @return [ClassSelection] diff --git a/lib/archunit/classes/fluentapi/declared_method_condition.rb b/lib/archunit/classes/fluentapi/declared_method_condition.rb new file mode 100644 index 0000000..dff3905 --- /dev/null +++ b/lib/archunit/classes/fluentapi/declared_method_condition.rb @@ -0,0 +1,40 @@ +# frozen_string_literal: true + +require_relative '../../common/fluentapi/checkable' +require_relative '../assertion/empty_class_selection_violation' +require_relative '../assertion/method_signatures' +require_relative 'method_signature' + +module ArchUnit + module Classes + module FluentApi + # Executable contract against ordinary declarations on every selected class. + class DeclaredMethodCondition + include Common::FluentApi::Checkable + + def initialize(scope, signature) + unless signature.is_a?(ArchUnit::MethodSignature) + raise ArgumentError, 'declare_method requires a MethodSignature' + end + + @scope = scope + @signature = signature + freeze + end + + private + + def perform_check(options) + selection = @scope.selection(options) + return empty_selection(options) if selection.status == :empty + + Assertion.gather_method_signature_violations(selection, @signature, @scope.identity) + end + + def empty_selection(options) + options.allow_empty_tests? ? [] : [Assertion::EmptyClassSelectionViolation.new(@scope.identity)] + end + end + end + end +end diff --git a/lib/archunit/classes/fluentapi/method_signature.rb b/lib/archunit/classes/fluentapi/method_signature.rb new file mode 100644 index 0000000..3cee0f6 --- /dev/null +++ b/lib/archunit/classes/fluentapi/method_signature.rb @@ -0,0 +1,50 @@ +# frozen_string_literal: true + +module ArchUnit + # Immutable expected call shape for a declared-method rule. + MethodSignature = Data.define(:name, :positional, :keywords, :scope, :block) do + # @param name [String, Symbol] exact Ruby method name + # @param positional [Integer] number of positional arguments passed + # @param keywords [Array] exact keyword names passed + # @param scope [Symbol] :instance or :singleton + # @param block [Symbol] :any or :declared block parameter/forwarding shape + def initialize(name:, positional: 0, keywords: [], scope: :instance, block: :any) + name = normalized_name(name) + keywords = normalized_keywords(keywords) + validate_shape(positional, scope, block) + super + end + + private + + def normalized_name(value) + name = value.to_s if value.is_a?(String) || value.is_a?(Symbol) + return name.dup.freeze if valid_name?(name) + + raise ArgumentError, 'method and keyword names must be non-blank Strings or Symbols' + end + + def valid_name?(name) + name&.encoding&.ascii_compatible? && name.valid_encoding? && + !name.strip.empty? && !name.match?(/[[:cntrl:]]/) + end + + def normalized_keywords(values) + raise ArgumentError, 'keywords must be an Array of names' unless values.is_a?(Array) + + values.map { |value| normalized_name(value) }.uniq.sort.freeze + end + + def validate_shape(count, scope, block) + unless count.is_a?(Integer) && count >= 0 + raise ArgumentError, 'positional must be a non-negative Integer' + end + unless %i[instance singleton].include?(scope) + raise ArgumentError, 'scope must be :instance or :singleton' + end + return if %i[any declared].include?(block) + + raise ArgumentError, 'block must be :any or :declared' + end + end +end diff --git a/lib/archunit/classes/fluentapi/positive_class_condition_builder.rb b/lib/archunit/classes/fluentapi/positive_class_condition_builder.rb new file mode 100644 index 0000000..f70bf53 --- /dev/null +++ b/lib/archunit/classes/fluentapi/positive_class_condition_builder.rb @@ -0,0 +1,24 @@ +# frozen_string_literal: true + +require_relative 'declared_method_condition' + +module ArchUnit + module Classes + module FluentApi + # Positive mood for declaration-based class rules. + class PositiveClassConditionBuilder + def initialize(scope) + @scope = scope + freeze + end + + # Requires a direct written method compatible with the specified call shape. + # @param signature [ArchUnit::MethodSignature] + # @return [DeclaredMethodCondition] + def declare_method(signature) + DeclaredMethodCondition.new(@scope, signature) + end + end + end + end +end diff --git a/lib/archunit/cli/baseline_identity.rb b/lib/archunit/cli/baseline_identity.rb index bd386f9..569de55 100644 --- a/lib/archunit/cli/baseline_identity.rb +++ b/lib/archunit/cli/baseline_identity.rb @@ -1,6 +1,7 @@ # frozen_string_literal: true require_relative '../testing/violation_factory' +require_relative 'method_signature_payload' require 'json' module ArchUnit @@ -14,6 +15,7 @@ module BaselineIdentity Files::Assertion::FilePatternViolation => :pattern, Files::Assertion::NamedCallViolation => :named_call, Files::Assertion::CycleViolation => :cycle, + Classes::Assertion::MethodSignatureViolation => :method_signature, Layers::Assertion::LayerDependencyViolation => :layer, Slices::Assertion::SliceDependencyViolation => :slice, Metrics::Assertion::MetricThresholdViolation => :threshold @@ -58,6 +60,10 @@ def self.named_call(value) 'safe_navigation' => call.safe_navigation } end + def self.method_signature(value) + MethodSignaturePayload.identity(value) + end + def self.filter(value) [value.regexp.source, value.regexp.options, value.target.to_s, value.matching.to_s, value.exclusions.map { |item| filter(item) }.sort_by { |item| JSON.generate(item) }] @@ -90,7 +96,7 @@ def self.identifier(value) normalized end private_class_method :dependency, :edge, :layer, :slice, :pattern, :named_call, :filter, - :cycle, :threshold, :identifier + :cycle, :method_signature, :threshold, :identifier end end end diff --git a/lib/archunit/cli/configuration.rb b/lib/archunit/cli/configuration.rb index 99b6a1c..bdd9fd4 100644 --- a/lib/archunit/cli/configuration.rb +++ b/lib/archunit/cli/configuration.rb @@ -1,6 +1,7 @@ # frozen_string_literal: true require_relative '../common/fluentapi/checkable' +require_relative '../classes/fluentapi/classes' require_relative '../files/fluentapi/files' require_relative '../layers/fluentapi/layers' require_relative '../layers/fluentapi/architecture_preset' @@ -49,6 +50,10 @@ def project_files end alias files project_files + def project_classes + ArchUnit.project_classes(@project_root) + end + def project_layers Layers::FluentApi.project_layers(@project_root) end diff --git a/lib/archunit/cli/method_signature_payload.rb b/lib/archunit/cli/method_signature_payload.rb new file mode 100644 index 0000000..641dd93 --- /dev/null +++ b/lib/archunit/cli/method_signature_payload.rb @@ -0,0 +1,84 @@ +# frozen_string_literal: true + +require 'json' +require_relative '../common/identifier_text' + +module ArchUnit + module CLI + # One explicit adapter for report evidence and stable accepted-debt identities. + # @api private + module MethodSignaturePayload + POLICY = 'declared_shape_v1' + private_constant :POLICY + + def self.build(violation) + finding = violation.finding + shared_fields(finding).merge( + 'unknown' => violation.unknown?, 'ancestor' => identifier(finding.ancestor), + 'declarations' => finding.declarations.map { |fact| fact.site.to_h }, + 'candidates' => finding.candidates.map { |method| with_site(method) } + ) + end + + def self.identity(violation) + if violation.unknown? + raise ArgumentError, 'cannot baseline an unknown method signature or class selection' + end + + finding = violation.finding + shared_fields(finding).merge( + 'definitions' => finding.declarations.map { |fact| fact.site.file }.uniq.sort, + 'observed' => observed_shapes(finding.candidates) + ) + end + + def self.selector(scope) + scope.transform_keys(&:to_s).transform_values do |names| + names.map { |name| identifier(name) } + end + end + + def self.shared_fields(finding) + { + 'policy' => POLICY, 'owner' => identifier(finding.owner), 'reason' => finding.reason.to_s, + 'selector' => selector(finding.scope), 'expected' => expected_shape(finding.expected) + } + end + + def self.expected_shape(signature) + keywords = signature.keywords.map { |name| identifier(name) } + signature.to_h.transform_keys(&:to_s).merge( + 'name' => identifier(signature.name), 'keywords' => keywords + ) + end + + def self.shape(method) + parameters = method.parameters.map { |param| [param.kind.to_s, identifier(param.name)] } + { 'name' => identifier(method.name), 'scope' => method.scope.to_s, + 'parameters' => parameters } + end + + def self.identifier(value) + return if value.nil? + + name = value.to_s + return name if name.ascii_only? || name.encoding == Encoding::UTF_8 + + # JSON alone transcodes distinct Ruby names to the same spelling. + { 'text' => Common::IdentifierText.utf8(name), 'encoding' => name.encoding.name, + 'bytes' => name.unpack1('H*') } + end + + def self.with_site(method) + shape(method).merge('site' => method.site.to_h, 'context' => method.context.to_s) + end + + def self.observed_shapes(methods) + methods.map { |method| shape(method).merge('file' => method.site.file) } + .sort_by { |value| JSON.generate(value) } + end + private_class_method :shared_fields, :expected_shape, :shape, :identifier, :with_site, + :observed_shapes + end + end +end diff --git a/lib/archunit/cli/violation_payload.rb b/lib/archunit/cli/violation_payload.rb index 9195f78..e00701e 100644 --- a/lib/archunit/cli/violation_payload.rb +++ b/lib/archunit/cli/violation_payload.rb @@ -1,6 +1,7 @@ # frozen_string_literal: true require_relative '../testing/violation_factory' +require_relative 'method_signature_payload' module ArchUnit module CLI @@ -22,6 +23,10 @@ def self.add_evidence(result, violation) result[:cycle_reporting] = 'witness' if violation.witness? when Files::Assertion::NamedCallViolation result[:call] = violation.call.to_h + when Classes::Assertion::MethodSignatureViolation + result[:method_signature] = MethodSignaturePayload.build(violation) + when Classes::Assertion::EmptyClassSelectionViolation + result[:class_selector] = MethodSignaturePayload.selector(violation.scope) end end private_class_method :add_evidence diff --git a/lib/archunit/common/assertion/empty_test_violation.rb b/lib/archunit/common/assertion/empty_test_violation.rb index 67dad53..17e9919 100644 --- a/lib/archunit/common/assertion/empty_test_violation.rb +++ b/lib/archunit/common/assertion/empty_test_violation.rb @@ -21,7 +21,8 @@ def negated? end def ==(other) - other.is_a?(self.class) && filters == other.filters && is_negated == other.is_negated + other.instance_of?(self.class) && filters == other.filters && + is_negated == other.is_negated end alias eql? == diff --git a/lib/archunit/common/identifier_text.rb b/lib/archunit/common/identifier_text.rb new file mode 100644 index 0000000..077ce3e --- /dev/null +++ b/lib/archunit/common/identifier_text.rb @@ -0,0 +1,15 @@ +# frozen_string_literal: true + +module ArchUnit + module Common + # Presentation only. Analysis compares the original identifier strings. + # @api private + module IdentifierText + def self.utf8(identifier) + identifier.encode(Encoding::UTF_8) + rescue EncodingError + identifier.dump + end + end + end +end diff --git a/lib/archunit/testing/method_signature_formatter.rb b/lib/archunit/testing/method_signature_formatter.rb new file mode 100644 index 0000000..2fa6b14 --- /dev/null +++ b/lib/archunit/testing/method_signature_formatter.rb @@ -0,0 +1,56 @@ +# frozen_string_literal: true + +require_relative 'test_violation' +require_relative '../common/identifier_text' +require_relative '../classes/assertion/method_signature_violation' +require_relative '../classes/assertion/empty_class_selection_violation' + +module ArchUnit + module Testing + # Describes the written call shape and where the analyzer found or expected it. + module MethodSignatureFormatter + FORMATTERS = { + Classes::Assertion::EmptyClassSelectionViolation => :empty_class_selection, + Classes::Assertion::MethodSignatureViolation => :method_signature + }.freeze + + private + + def method_signature(violation) + finding = violation.finding + message = violation.unknown? ? 'Method signature unknown' : 'Declared signature violation' + reason = finding.reason.to_s.tr('_', ' ') + details = ["#{signature_summary(finding)}: #{reason}.", + "Source: #{signature_location(finding)}."].join(' ') + TestViolation.new(message:, details:) + end + + def empty_class_selection(violation) + selectors = violation.scope.reject { |_kind, names| names.empty? } + details = selectors.map { |kind, names| "#{kind}: #{identifier_list(names)}" }.join('; ') + details = 'The unfiltered scope contained no declared classes.' if details.empty? + TestViolation.new(message: 'No classes matched the rule scope', details:) + end + + def signature_summary(finding) + signature = finding.expected + separator = signature.scope == :singleton ? '.' : '#' + owner = Common::IdentifierText.utf8(finding.owner || '') + keywords = identifier_list(signature.keywords) + method = "#{owner}#{separator}#{Common::IdentifierText.utf8(signature.name)}" + shape = "#{signature.positional} positional and keywords [#{keywords}]" + "#{method} expects a declaration accepting #{shape} (block: #{signature.block})" + end + + def identifier_list(names) + names.map { |name| Common::IdentifierText.utf8(name) }.join(', ') + end + + def signature_location(finding) + fact = finding.candidates.first || finding.declarations.first + site = fact.site + "#{site.file}:#{site.line}:#{site.column}" + end + end + end +end diff --git a/lib/archunit/testing/violation_factory.rb b/lib/archunit/testing/violation_factory.rb index 7d8b17c..6589aea 100644 --- a/lib/archunit/testing/violation_factory.rb +++ b/lib/archunit/testing/violation_factory.rb @@ -16,6 +16,7 @@ require_relative '../slices/assertion/slice_dependency_violation' require_relative 'layer_violation_formatter' require_relative 'metric_violation_formatter' +require_relative 'method_signature_formatter' require_relative 'named_call_formatter' require_relative 'slice_violation_formatter' require_relative 'test_violation' @@ -27,10 +28,11 @@ module Testing class ViolationFactory extend LayerViolationFormatter extend MetricViolationFormatter + extend MethodSignatureFormatter extend NamedCallFormatter extend SliceViolationFormatter - FORMATTERS = { + FORMATTERS = MethodSignatureFormatter::FORMATTERS.merge( Common::Assertion::EmptyTestViolation => :empty_test, Files::Assertion::FilePatternViolation => :file_pattern, Files::Assertion::FileDependencyViolation => :file_dependency, @@ -40,7 +42,7 @@ class ViolationFactory Files::Assertion::NamedCallViolation => :named_call, Layers::Assertion::LayerDependencyViolation => :layer_dependency, Slices::Assertion::SliceDependencyViolation => :slice_dependency - }.merge(MetricViolationFormatter::FORMATTERS).freeze + ).merge(MetricViolationFormatter::FORMATTERS).freeze class << self def from_violation(violation) @@ -120,10 +122,8 @@ def custom_file(violation) end def generic(violation) - TestViolation.new( - message: 'Architecture violation', - details: "Unformatted violation type: #{violation.class.name}." - ) + details = "Unformatted violation type: #{violation.class.name}." + TestViolation.new(message: 'Architecture violation', details:) end def describe_filter(filter) diff --git a/scripts/check_method_signatures.rb b/scripts/check_method_signatures.rb new file mode 100644 index 0000000..324b1b9 --- /dev/null +++ b/scripts/check_method_signatures.rb @@ -0,0 +1,41 @@ +# frozen_string_literal: true + +require 'archunit' +require 'archunit/cli' +require 'json' +require 'pathname' +require 'stringio' +require 'tmpdir' + +def signature_check(root, *flags, expected:) + output = StringIO.new + args = [*flags, '--format=json'] + status = ArchUnit::CLI.run(args, cwd: root.to_s, out: output, err: StringIO.new) + abort "expected #{expected}, got #{status}: #{output.string}" unless status == expected + + JSON.parse(output.string) +end + +Dir.mktmpdir('archunit-signature-smoke') do |dir| + root = Pathname.new(dir) + root.join('Gemfile').write("raise 'must not boot target'") + root.join('.archunit.rb').write(<<~RUBY) + rule('commands') do + shape = ArchUnit::MethodSignature.new(name: :call, positional: 1, keywords: [:actor]) + project_classes.in_namespace('Commands').should.declare_method(shape) + end + RUBY + source = root.join('command.rb') + source.write("module Commands; class Run; def call; end; end; end\nraise 'do not execute'") + failure = signature_check(root, 'check', expected: 1) + reason = failure.dig('rules', 0, 'violations', 0, 'method_signature', 'reason') + abort 'missing structured signature evidence' unless reason == 'incompatible_signature' + source.write('module Commands; class Run; def call(id, actor:); end; end; end') + signature_check(root, 'check', expected: 0) + source.write('module Commands; class Run; def call(id, actor:); end if flag?; end; end') + refused = signature_check(root, 'baseline', '--output', 'debt.json', expected: 2) + message = refused.dig('error', 'message') + abort 'baseline did not reject an unknown shape' unless message&.include?('unknown method') + abort 'unknown signature created an accepted-debt baseline' if root.join('debt.json').exist? +end +puts 'Declared method rule passed the CLI red-to-green and baseline safety smoke.' diff --git a/spec/classes/callable_shape_spec.rb b/spec/classes/callable_shape_spec.rb new file mode 100644 index 0000000..1863509 --- /dev/null +++ b/spec/classes/callable_shape_spec.rb @@ -0,0 +1,41 @@ +# frozen_string_literal: true + +require 'archunit/extraction/declarations' +require 'archunit/classes/assertion/callable_shape' + +RSpec.describe 'Declared callable shapes' do + def accepts?(params, positional, keywords = [], block: :any) + source = "class Command; def call(#{params}); end; end" + facts = ArchUnit::Extraction::Declarations.collect(Prism.parse(source), file: 'command.rb') + shape = ArchUnit::Classes::Assertion.const_get(:CallableShape) + expected = ArchUnit::MethodSignature.new(name: :call, positional:, keywords:, block:) + shape.matches?(facts.method_declarations.first.parameters, expected) + end + + it 'accepts optional, destructured, rest and post positional parameters' do + expect(accepts?('first, second = nil', 1)).to be(true) + expect(accepts?('first, second = nil', 2)).to be(true) + expect(accepts?('first, second = nil', 3)).to be(false) + expect(accepts?('(left, right)', 1)).to be(true) + expect(accepts?('head, *items, tail', 1)).to be(false) + expect(accepts?('head, *items, tail', 12)).to be(true) + end + + it 'requires all required keyword arguments and does not invent a named keyword interface' do + expect(accepts?('x, actor:, request_id: nil', 1, %i[actor request_id])).to be(true) + expect(accepts?('x, actor:, required:', 1, [:actor])).to be(false) + expect(accepts?('x, **kwargs', 1, [:actor])).to be(true) + expect(accepts?('x, **nil', 1, [:actor])).to be(false) + expect(accepts?('x, **nil', 1)).to be(true) + expect(accepts?('options', 0, [:actor])).to be(false) + expect(accepts?('x, actor:', 1, %i[actor extra])).to be(false) + end + + it 'recognizes explicit block capture and bounded shape forwarding' do + expect(accepts?('head, ...', 0, [:actor])).to be(false) + expect(accepts?('head, ...', 2, [:actor], block: :declared)).to be(true) + expect(accepts?('a, &', 1, block: :declared)).to be(true) + expect(accepts?('a', 1, block: :declared)).to be(false) + expect(accepts?('a', 1)).to be(true) + end +end diff --git a/spec/classes/declared_method_condition_spec.rb b/spec/classes/declared_method_condition_spec.rb new file mode 100644 index 0000000..cd58817 --- /dev/null +++ b/spec/classes/declared_method_condition_spec.rb @@ -0,0 +1,181 @@ +# frozen_string_literal: true + +require 'minitest' +require 'pathname' +require 'tmpdir' + +RSpec.describe 'Declared method rules' do + around do |example| + Dir.mktmpdir('archunit-declared-method') do |directory| + @root = Pathname.new(directory) + @root.join('Gemfile').write("raise 'do not boot'") + example.run + ensure + ArchUnit.clear_graph_cache + end + end + + def write(path, source) + @root.join(path).write(source) + end + + def scope + ArchUnit.project_classes(@root).in_namespace('Commands') + end + + def contract(**options) + defaults = { name: :call, positional: 1, keywords: %i[actor request_id] } + ArchUnit::MethodSignature.new(**defaults, **options) + end + + def verify(**options) + scope.should.declare_method(contract(**options)) + end + + it 'requires every selected class to declare a compatible shape, independent of file layout' do + write('flat.rb', <<~RUBY) + module Commands + class Good; def call(id, actor:, request_id: nil); end; end + class Missing; end + class Wrong; def call(id, actor:, required:); end; end + end + raise 'do not execute target' + RUBY + findings = verify.check.map(&:finding) + expect(findings.map { |f| [f.owner, f.reason] }).to eq( + [['Commands::Missing', :missing_declaration], ['Commands::Wrong', :incompatible_signature]] + ) + wrong = findings.last + expect(wrong.candidates.first.site.file).to eq('flat.rb') + expect(wrong.candidates.first.site.line).to eq(4) + expect(ArchUnit.format_violations(verify.check)).to include('Commands::Wrong#call') + expect(scope.with_constant_name('Commands::Good').should.declare_method(contract)).to pass + end + + it 'can require either singleton syntax and does not equate an instance def with a singleton' do + write('singleton.rb', <<~RUBY) + module Commands + class First; def self.call(*args, **kwargs); end; end + class Second + class << self + def call(id, actor:, request_id:); end + end + end + end + RUBY + expect(verify(scope: :singleton)).to pass + reasons = verify.check.map { |violation| violation.finding.reason } + expect(reasons).to all(eq(:missing_declaration)) + end + + it 'distinguishes same-spelled method and keyword names with different encodings' do + method_name = "\u00E9crire" + keyword = "r\u00F4le" + legacy_name = method_name.encode('ISO-8859-1') + legacy_key = keyword.encode('ISO-8859-1') + source = "# encoding: ISO-8859-1\nmodule Commands; class Run; " \ + "def #{method_name}(id, #{keyword}:); end; end; end" + @root.join('legacy.rb').binwrite(source.encode(legacy_name.encoding)) + + expect(verify(name: legacy_name, keywords: [legacy_key])).to pass + method_mismatch = verify(name: method_name, keywords: [legacy_key]).check.first + keyword_mismatch = verify(name: legacy_name, keywords: [keyword]).check.first + expect(method_mismatch.finding.reason).to eq(:missing_declaration) + expect(keyword_mismatch.finding.reason).to eq(:incompatible_signature) + expect(ArchUnit.format_violations([keyword_mismatch])).to include(method_name, keyword) + end + + it 'does not accept inherited, mixed-in, aliased or generated substitutes for a def' do + write('dynamic.rb', <<~RUBY) + class Parent; def call(...); end; end + module Helpers; def call(...); end; end + module Commands + class Inherited < ::Parent; end + class Mixed; include ::Helpers; end + class Aliased; def invoke(...); end; alias call invoke; end + class Generated; define_method(:call) { |*args, **keywords| }; end + class CatchAll; def method_missing(...); end; end + end + RUBY + findings = verify.check.map(&:finding) + expected = %w[Aliased CatchAll Generated Inherited Mixed].map { |name| "Commands::#{name}" } + expect(findings.map(&:owner)).to eq(expected) + expect(findings.map(&:reason)).to all(eq(:missing_declaration)) + end + + it 'fails on conflicting reopens and conditional or receiver-unknown method candidates' do + write('original.rb', <<~RUBY) + module Commands + class Reopened; def call(*, **); end; end + class Conditional; def call(*, **); end if features?; end + class Foreign; def target.call(*, **); end; end + end + RUBY + write('reopen.rb', 'class Commands::Reopened; def call; end; end') + results = verify.check(ArchUnit::CheckOptions.new(allow_empty_tests: true)) + expect(results).to all(be_unknown) + expect(results.map { |result| result.finding.reason }) + .to eq(%i[uncertain_method_declaration uncertain_method_declaration conflicting_signatures]) + expect(results.last.finding.candidates.map { |method| method.site.file }) + .to eq(%w[original.rb reopen.rb]) + end + + it 'does not need reopen order when all written shapes accept the requested call' do + write('original.rb', <<~RUBY) + module Commands; class Run; def call(id, actor:, request_id:); end; end; end + RUBY + write('reopen.rb', 'class Commands::Run; def call(*, **); end; end') + expect(verify).to pass + end + + it 'uses opt-out only for known empty selection and keeps unresolved class selection failing' do + write('first.rb', 'module Commands; class Child < ::Missing; end; end') + empty = scope.with_constant_name('Commands::Other').should.declare_method(contract) + allow_empty = ArchUnit::CheckOptions.new(allow_empty_tests: true) + expect(empty.check.first).to be_a(ArchUnit::EmptyTestViolation) + expect(ArchUnit::EmptyTestViolation.new(filters: [])).not_to eq(empty.check.first) + expect(ArchUnit.format_violations(empty.check)).to include('No classes matched') + expect(empty.check(allow_empty)).to be_empty + unknown = scope.descendants_of('Missing').should.declare_method(contract) + result = unknown.check(allow_empty).first + expect(result).to be_unknown + expect(result.finding).to have_attributes(reason: :unresolved_ancestry, ancestor: 'Missing') + end + + it 'shares the declaration snapshot across rules and does no analysis while building them' do + write('class.rb', 'module Commands; class Run; def call(*, **); end; end; end') + expect(Prism).to receive(:parse).once.and_call_original + first = verify + second = scope.should.declare_method(contract(positional: 4)) + expect([scope, first, second, contract]).to all(be_frozen) + expect(scope.class.instance_methods(false)).not_to include(:should_not) + expect(first).to pass + expect(second).to pass + end + + it 'reports missing written methods through the shared Minitest assertion' do + ArchUnit::Testing::MinitestAdapter.install! + context = Class.new do + include Minitest::Assertions + + attr_accessor :assertions + end.new + context.assertions = 0 + write('class.rb', 'module Commands; class Run; end; end') + expect { context.assert_passes(verify) }.to raise_error(Minitest::Assertion, /Commands::Run#call/) + end + + it 'owns validated signature values and normalizes keyword ordering' do + key = +'actor' + expected = contract(keywords: [:request_id, key, :actor]) + key.replace('user') + expect(expected.keywords).to eq(%w[actor request_id]) + expect(expected.keywords).to be_frozen + expect(expected.keywords).to all(be_frozen) + [{ positional: -1 }, { keywords: :actor }, { name: '' }, { scope: :class }, + { block: true }].each do |invalid| + expect { contract(**invalid) }.to raise_error(ArgumentError) + end + expect { scope.should.declare_method(:call) }.to raise_error(ArgumentError, /MethodSignature/) + end +end diff --git a/spec/cli/method_signatures_spec.rb b/spec/cli/method_signatures_spec.rb new file mode 100644 index 0000000..1366d07 --- /dev/null +++ b/spec/cli/method_signatures_spec.rb @@ -0,0 +1,124 @@ +# frozen_string_literal: true + +require 'archunit/cli' +require 'json' +require 'pathname' +require 'stringio' +require 'tmpdir' + +RSpec.describe ArchUnit::CLI, 'declared method signatures' do + around do |example| + Dir.mktmpdir('archunit-signature-cli') do |directory| + @root = Pathname.new(directory) + @root.join('Gemfile').write("raise 'never execute target'") + @source = @root.join('command.rb') + @baseline = @root.join('debt.json') + source('def call; end') + configure + example.run + ensure + ArchUnit.clear_graph_cache + end + end + + def source(body) + @source.write("module Commands; class Run; #{body}; end; end\nraise 'never boot'") + end + + def configure(positionals: 1, selector: "in_namespace('Commands')") + @root.join('.archunit.rb').write(<<~RUBY) + rule('command shape') do + shape = ArchUnit::MethodSignature.new(name: :call, positional: #{positionals}, keywords: [:actor]) + project_classes.#{selector}.should.declare_method(shape) + end + RUBY + end + + def invoke(command = 'check', *flags) + out = StringIO.new + args = [command, '--format=json', *flags] + status = described_class.run(args, cwd: @root.to_s, out:, err: StringIO.new) + [status, JSON.parse(out.string)] + end + + it 'reports source declarations and structured evidence for incompatible shapes' do + code, report = invoke + expect(code).to eq(1) + expect(report.dig('analysis', 'scopes', 0, 'kind')).to eq('source_declarations') + finding = report.dig('rules', 0, 'violations', 0, 'method_signature') + expect(finding).to include('owner' => 'Commands::Run', 'reason' => 'incompatible_signature', + 'unknown' => false) + expected = { 'name' => 'call', 'positional' => 1, 'keywords' => ['actor'] } + expect(finding['expected']).to include(expected) + expect(finding['candidates']).to contain_exactly( + include('parameters' => [], 'site' => include('file' => 'command.rb', 'line' => 1)) + ) + source('def call(id, actor:); end') + expect(invoke.first).to eq(0) + end + + it 'preserves baselines across line movement but not shape or scope changes' do + code, report = invoke('baseline', '--output', @baseline.to_s) + expect(code).to eq(0) + expect(report.dig('baseline', 'accepted_count')).to eq(1) + document = JSON.parse(@baseline.read) + entry = document.fetch('entries').first + expect(entry.dig('data', 'policy')).to eq('declared_shape_v1') + expect(entry.dig('context', 0, 'kind')).to eq('source_declarations') + @source.write("# moved\n#{@source.read}") + expect(invoke('check', '--baseline', @baseline.to_s).first).to eq(0) + configure(positionals: 2) + expect(invoke('check', '--baseline', @baseline.to_s).last.fetch('baseline')) + .to include('new_count' => 1, 'stale_count' => 1) + configure(selector: "with_constant_name('Commands::Run')") + expect(invoke('check', '--baseline', @baseline.to_s).first).to eq(1) + end + + it 'never creates or applies accepted debt for a conditional or unknown result' do + expect(invoke('baseline', '--output', @baseline.to_s).first).to eq(0) + before = @baseline.binread + source('def call(id, actor:); end if feature?') + code, report = invoke + expect(code).to eq(1) + finding = report.dig('rules', 0, 'violations', 0, 'method_signature') + expect(finding).to include('reason' => 'uncertain_method_declaration', 'unknown' => true) + attempts = [ + invoke('check', '--baseline', @baseline.to_s), + invoke('baseline', '--output', @baseline.to_s, '--force') + ] + attempts.each do |status, result| + expect(status).to eq(2) + message = result.dig('error', 'message') + expect(message).to include('cannot baseline an unknown method signature') + end + expect(@baseline.binread).to eq(before) + end + + it 'does not transfer debt between same-spelled constants in different encodings' do + name = "\u00C9quipe" + declaration = "class #{name}; def call; end; end" + @source.binwrite(declaration) + configure(selector: 'with_constant_name("\u00C9quipe")') + expect(invoke('baseline', '--output', @baseline.to_s).first).to eq(0) + + @source.binwrite("# encoding: ISO-8859-1\n#{declaration}".encode('ISO-8859-1')) + configure(selector: 'with_constant_name("\u00C9quipe".encode("ISO-8859-1"))') + status, report = invoke('check', '--baseline', @baseline.to_s) + expect(status).to eq(1) + expect(report.fetch('baseline')).to include('new_count' => 1, 'stale_count' => 1) + finding = report.dig('rules', 0, 'violations', 0, 'method_signature') + identifier = { 'text' => name, 'encoding' => 'ISO-8859-1', 'bytes' => 'c97175697065' } + expect(finding.fetch('owner')).to eq(identifier) + expect(finding.dig('selector', 'constants')).to eq([identifier]) + end + + it 'reports no selected classes separately and does not baseline an empty guard' do + configure(selector: "in_namespace('Elsewhere')") + code, report = invoke + expect(code).to eq(1) + expect(report.dig('rules', 0, 'violations', 0, 'class_selector', 'namespaces')) + .to eq(['Elsewhere']) + expect(invoke('baseline', '--output', @baseline.to_s).first).to eq(2) + expect(@baseline).not_to exist + end +end diff --git a/spec/common/fluentapi/rule_rationale_spec.rb b/spec/common/fluentapi/rule_rationale_spec.rb index 6be4c85..083eb05 100644 --- a/spec/common/fluentapi/rule_rationale_spec.rb +++ b/spec/common/fluentapi/rule_rationale_spec.rb @@ -32,12 +32,14 @@ def all_terminals files = ArchUnit.project_files(@root) metrics = ArchUnit.metrics(@root) slices = ArchUnit.project_slices(@root).defined_by('app/(**)/') + call_shape = ArchUnit::MethodSignature.new(name: :call) [ files.should.have_name('*.rb'), files.should.have_no_cycles, files.should_not.depend_on_files.in_folder('app/database/**'), files.should_not.depend_on_external_modules.matching('json'), files.should_not.contain_calls_named(:require_relative), + ArchUnit.project_classes(@root).should.declare_method(call_shape), files.should.adhere_to(->(_file) { true }, 'Ruby files'), ArchUnit.project_layers(@root).layer('api').defined_by('app/api/**') .where_layer('api').may_only_depend_on_layers,