From 78ecd658abc85e7bde45e3ed714a91437982f3c3 Mon Sep 17 00:00:00 2001 From: TristanKruse Date: Fri, 27 Nov 2026 18:07:54 +0100 Subject: [PATCH] Advise on Rails preset checks with no scoped imports --- API.md | 6 + CHANGELOG.md | 2 + GUIDE.md | 5 + lib/archunit/cli/analysis_report.rb | 23 +++- lib/archunit/cli/analysis_text.rb | 3 + lib/archunit/extraction/analysis_observer.rb | 5 + lib/archunit/layers/fluentapi/preset_rule.rb | 17 ++- .../layers/fluentapi/rails_import_coverage.rb | 52 ++++++++ scripts/check_presets.rb | 32 ++++- spec/cli/rails_imports_advisory_spec.rb | 125 ++++++++++++++++++ 10 files changed, 264 insertions(+), 6 deletions(-) create mode 100644 lib/archunit/layers/fluentapi/rails_import_coverage.rb create mode 100644 spec/cli/rails_imports_advisory_spec.rb diff --git a/API.md b/API.md index bc33ec6..e6830b1 100644 --- a/API.md +++ b/API.md @@ -442,6 +442,12 @@ multiple roots can overlap, and a metric pass and a graph pass can inspect the s Scopes describe synchronous built-in extraction in the current check, not arbitrary user work started in other threads/fibers. +In the development version, `analysis.advisories` is an optional schema-1 array. Each entry has +a stable `code`, affected `rule_names`, and the same `message` as the text report. The +`rails_no_scoped_imports` hint applies only to passing, populated Rails presets in imports mode +with zero cross-file imports among their selected files. It does not count skipped constants or +affect violations, baselines or exit codes. No advisory field is emitted when there is no hint. + `imports` counts accepted static import expressions, including external imports. Unresolved imports count unsupported/dynamic import expressions; literal external gem imports are not counted as unresolved expressions. Unresolved/ambiguous constant observations can include diff --git a/CHANGELOG.md b/CHANGELOG.md index 132155f..dbb91f7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,8 @@ silent listing-error skip. Excluded trees are still pruned without opening their descendants. - Extend the existing extraction benchmark with allocation counts, full graph/evidence digests, and excluded-tree workloads; retain generous CI timing ceilings. +- Explain potentially misleading imports-only Rails preset passes in CLI text and JSON when no + imports connect the selected files. Default rules, baselines and exit codes are unchanged. ## 1.1.0 - 2026-11-23 diff --git a/GUIDE.md b/GUIDE.md index 770901e..870aa97 100644 --- a/GUIDE.md +++ b/GUIDE.md @@ -718,6 +718,11 @@ ArchUnit.assert_passes(rule, options) For a CLI-configured preset use `bundle exec archunit check --dependency-analysis imports_and_constants`. Neither option boots Rails or reproduces its runtime autoloading. +In the development version, a passing imports-only Rails preset gets a CLI hint if all its +layers contain files but no cross-file import connects any two selected files. A genuinely +independent set of files can also trigger the hint. It is not a violation or a count of missed +references, and it does not change the exit code. Plain Ruby, RSpec and Minitest checks stay silent. + In trusted CLI configuration use `rule('Core independent') { architecture_preset(:hexagonal) }`; the helper defaults to the CLI's selected project root. Public `ArchUnit.architecture_preset` uses normal project auto-discovery when no locator is supplied. diff --git a/lib/archunit/cli/analysis_report.rb b/lib/archunit/cli/analysis_report.rb index 9a0b2bf..03cd270 100644 --- a/lib/archunit/cli/analysis_report.rb +++ b/lib/archunit/cli/analysis_report.rb @@ -7,10 +7,17 @@ module CLI class AnalysisReport NOTICE = 'Counts describe bounded static analysis, not semantic coverage or proven missed ' \ 'dependencies. A passing policy is not proof of complete runtime architecture.' + MESSAGES = { + rails_no_scoped_imports: 'No cross-file imports found among the selected Rails files. ' \ + 'Constant references were not checked. If these files rely on ' \ + 'autoloading, try --dependency-analysis imports_and_constants.' + }.freeze + private_constant :MESSAGES def initialize @scopes = {}.compare_by_identity @rules = [] + @advisories = {} end def for_rule(name) @@ -35,17 +42,31 @@ def for_name(name) { status: availability(scopes), scope_ids: scopes.map { |scope| scope[:id] } } end + def advise(code) + return unless @current_rule + + (@advisories[code] ||= Set.new).add(@current_rule) + end + def to_h scopes = @scopes.values.map { |scope| scope.merge(rule_names: scope[:rule_names].dup) } status = availability(scopes) if status == 'available' && @rules.any? { |name| for_name(name)[:status] != 'available' } status = 'partial' end - { status:, scopes:, notice: NOTICE } + result = { status:, scopes:, notice: NOTICE } + result[:advisories] = advisory_entries unless @advisories.empty? + result end private + def advisory_entries + @advisories.map do |code, names| + { code: code.to_s, rule_names: names.to_a, message: MESSAGES.fetch(code) } + end + end + def scope_for(snapshot) @scopes[snapshot] ||= snapshot.merge( id: @scopes.length + 1, observations: 0, cache_hits: 0, rule_names: [] diff --git a/lib/archunit/cli/analysis_text.rb b/lib/archunit/cli/analysis_text.rb index 516285d..04f43e3 100644 --- a/lib/archunit/cli/analysis_text.rb +++ b/lib/archunit/cli/analysis_text.rb @@ -8,6 +8,9 @@ module AnalysisText def self.write(analysis, out) out.puts("Analysis: #{analysis[:status]}") analysis[:scopes].each { |scope| write_scope(scope, out) } + analysis.fetch(:advisories, []).each do |hint| + out.puts(" Advisory (#{hint[:rule_names].join(', ')}): #{hint[:message]}") + end out.puts(analysis[:notice]) unless analysis[:scopes].empty? end diff --git a/lib/archunit/extraction/analysis_observer.rb b/lib/archunit/extraction/analysis_observer.rb index 91a472d..ff00fc6 100644 --- a/lib/archunit/extraction/analysis_observer.rb +++ b/lib/archunit/extraction/analysis_observer.rb @@ -19,6 +19,11 @@ def self.capture(observer) def self.record(snapshot, cache_hit: false) Thread.current[KEY]&.observe(snapshot, cache_hit:) end + + def self.advisory_sink + observer = Thread.current[KEY] + observer if observer.respond_to?(:advise) + end end end end diff --git a/lib/archunit/layers/fluentapi/preset_rule.rb b/lib/archunit/layers/fluentapi/preset_rule.rb index 510933b..ecc13e2 100644 --- a/lib/archunit/layers/fluentapi/preset_rule.rb +++ b/lib/archunit/layers/fluentapi/preset_rule.rb @@ -1,6 +1,7 @@ # frozen_string_literal: true require_relative 'layered_architecture' +require_relative 'rails_import_coverage' require_relative '../../error/user_error' module ArchUnit @@ -26,15 +27,25 @@ def initialize(name:, architecture:) def perform_check(options) graph = ArchUnit::Extraction.extract_graph(architecture.project_locator, options:) + coverage = RailsImportCoverage.for(name, options, architecture.layer_definitions.size) + validate_files(graph, coverage) + architecture.check(options.with(clear_cache: false)).tap do |violations| + coverage&.finish(graph) if violations.empty? + end + end + + def validate_files(graph, coverage) graph.each do |edge| - validate_membership(edge.source) if edge.source == edge.target && !edge.external + next if edge.external || edge.source != edge.target + + layer = validate_membership(edge.source) + coverage&.record(edge.source, layer) end - architecture.check(options.with(clear_cache: false)) end def validate_membership(path) matches = architecture.layer_definitions.select { |layer| layer.matches?(path) } - return if matches.length <= 1 + return matches.first if matches.length <= 1 names = matches.map(&:name).join(', ') raise UserError, "preset file '#{path}' matches multiple layers: #{names}" diff --git a/lib/archunit/layers/fluentapi/rails_import_coverage.rb b/lib/archunit/layers/fluentapi/rails_import_coverage.rb new file mode 100644 index 0000000..50acba3 --- /dev/null +++ b/lib/archunit/layers/fluentapi/rails_import_coverage.rb @@ -0,0 +1,52 @@ +# frozen_string_literal: true + +require_relative '../../extraction/analysis_observer' + +module ArchUnit + module Layers + module FluentApi + # Ephemeral CLI diagnostic, using only already validated layer memberships and graph edges. + # @api private + class RailsImportCoverage + IMPORTS = %i[require require_relative autoload load require_dependency].freeze + private_constant :IMPORTS + + def self.for(name, options, layer_count) + return unless name == :rails && !options.constant_references? + + sink = ArchUnit::Extraction::AnalysisObserver.advisory_sink + new(sink, layer_count) if sink + end + + def initialize(sink, layer_count) + @sink = sink + @layer_count = layer_count + @files = {} + @present = Set.new + end + + def record(path, layer) + return unless layer + + @files[path] = true + @present.add(layer.name) + end + + def finish(graph) + return unless @present.size == @layer_count + return if graph.any? { |edge| scoped_import?(edge) } + + @sink.advise(:rails_no_scoped_imports) + end + + private + + def scoped_import?(edge) + !edge.external && edge.source != edge.target && @files.key?(edge.source) && + @files.key?(edge.target) && edge.import_kinds.intersect?(IMPORTS) + end + end + private_constant :RailsImportCoverage + end + end +end diff --git a/scripts/check_presets.rb b/scripts/check_presets.rb index 129dd8c..97e4d6c 100644 --- a/scripts/check_presets.rb +++ b/scripts/check_presets.rb @@ -14,6 +14,7 @@ module PresetSmoke def run Dir.mktmpdir('archunit-preset-smoke') do |base| %i[layered hexagonal rails].each { |name| verify(base, name) } + verify_autoload(base) end puts 'Layered, hexagonal and Rails presets passed allowed/forbidden controls in both modes.' end @@ -60,10 +61,37 @@ def verify_forbidden(rule) def verify_cli(base, root, name) config = File.join(base, "#{name}-trusted.rb") File.write(config, "rule('preset') { architecture_preset(:#{name}) }") + status, report = check_cli(root, config) + abort 'CLI preset failed' unless status.zero? && report['status'] == 'passed' + abort 'unexpected hint for explicit imports' if report.fetch('analysis').key?('advisories') + end + + def autoload_fixture(base) + root, folders = fixture(base, :rails) + sources = ['class OrdersController; end', 'class OrderService; end', + 'class Order; def ui; ::OrdersController; end; end'] + folders.zip(sources).each do |folder, source| + File.write(File.join(root, folder, 'unit.rb'), source) + end + root + end + + def verify_autoload(base) + root = autoload_fixture(base) + config = File.join(base, 'rails-trusted.rb') + status, report = check_cli(root, config) + code = report.dig('analysis', 'advisories', 0, 'code') + abort 'missing Rails hint' unless status.zero? && code == 'rails_no_scoped_imports' + status, report = check_cli(root, config, '--dependency-analysis', 'imports_and_constants') + count = report.dig('summary', 'violation_count') + abort 'missing dependency in expanded mode' unless status == 1 && count == 1 + end + + def check_cli(root, config, *flags) output = StringIO.new - arguments = ['check', '--project', root, '--config', config, '--format', 'json'] + arguments = ['check', '--project', root, '--config', config, '--format', 'json', *flags] status = ArchUnit::CLI.run(arguments, out: output, err: StringIO.new) - abort 'CLI preset failed' unless status.zero? && JSON.parse(output.string)['status'] == 'passed' + [status, JSON.parse(output.string)] end end diff --git a/spec/cli/rails_imports_advisory_spec.rb b/spec/cli/rails_imports_advisory_spec.rb new file mode 100644 index 0000000..d0b3cb6 --- /dev/null +++ b/spec/cli/rails_imports_advisory_spec.rb @@ -0,0 +1,125 @@ +# frozen_string_literal: true + +require 'archunit/cli' +require 'json' +require 'pathname' +require 'stringio' +require 'tmpdir' + +RSpec.describe ArchUnit::CLI, 'Rails imports-only advisory' do + around do |example| + Dir.mktmpdir('archunit-advisory') do |dir| + @root = Pathname.new(dir) + write('Gemfile', "raise 'do not boot'") + write('app/controllers/orders_controller.rb', 'class OrdersController; end') + write('app/services/order_service.rb', 'class OrderService; end') + write('app/models/order.rb', 'class Order; def controller; ::OrdersController; end; end') + config("rule('boundaries') { architecture_preset(:rails) }") + example.run + ensure + ArchUnit.clear_graph_cache + end + end + + def write(path, contents) + file = @root.join(path) + file.dirname.mkpath + file.write(contents) + end + + def config(source) + write('.archunit.rb', source) + end + + def invoke(*args, format: 'json', command: 'check') + out = StringIO.new + code = described_class.run([command, '--format', format, *args], + out:, err: StringIO.new, cwd: @root.to_s) + [code, format == 'json' ? JSON.parse(out.string) : out.string] + end + + it 'explains a passing default, while expanded mode reports the actual forbidden direction' do + code, payload = invoke + expect(code).to eq(0) + expect(payload.dig('summary', 'violation_count')).to eq(0) + hint = payload.fetch('analysis').fetch('advisories').fetch(0) + expect(hint).to include('code' => 'rails_no_scoped_imports', 'rule_names' => ['boundaries']) + expect(hint.fetch('message')).to include('--dependency-analysis imports_and_constants') + expect(invoke(format: 'text').last).to include(hint.fetch('message'), 'boundaries') + + code, payload = invoke('--dependency-analysis', 'imports_and_constants') + expect(code).to eq(1) + expect(payload.dig('summary', 'violation_count')).to eq(1) + expect(payload.fetch('analysis')).not_to have_key('advisories') + end + + it 'ignores self, external and out-of-scope edges and deduplicates just the affected rules' do + write('app/controllers/orders_controller.rb', <<~RUBY) + require 'json' + require_relative 'orders_controller' + require_relative '../../lib/helper' + class OrdersController; end + RUBY + write('lib/helper.rb', "require_relative '../app/models/order'") + config(<<~RUBY) + rule('one') { architecture_preset(:rails) } + rule('ordinary') { project_files.should.have_no_cycles } + rule('two') { architecture_preset(:rails) } + RUBY + hints = invoke.last.fetch('analysis').fetch('advisories') + expect(hints).to contain_exactly(include('rule_names' => %w[one two])) + expect(invoke(format: 'text').last.scan(hints.first.fetch('message')).size).to eq(1) + end + + it 'uses the actual override folders, and counts a same-layer cross-file import' do + config(<<~RUBY) + rule('custom') do + architecture_preset(:rails, ArchUnit::PresetOptions.new(folders: { models: 'domain/**' })) + end + RUBY + write('domain/entity.rb', '# no imports') + write('domain/order.rb', "require_relative 'entity'") + expect(invoke.last.fetch('analysis')).not_to have_key('advisories') + write('domain/order.rb', '# no imports') + expect(invoke.last.dig('analysis', 'advisories')).not_to be_empty + end + + it 'does not advise on missing layers, failed parses, explain or non-Rails rules' do + expect(invoke(command: 'explain').last.fetch('analysis')).not_to have_key('advisories') + config("rule('plain') { project_files.should.have_no_cycles }") + expect(invoke.last.fetch('analysis')).not_to have_key('advisories') + config("rule('rails') { architecture_preset(:rails) }") + code, payload = invoke('--exclude-source', 'app/models/**') + expect(code).to eq(1) + expect(payload.fetch('analysis')).not_to have_key('advisories') + write('app/models/order.rb', 'class Broken <') + code, payload = invoke + expect(code).to eq(2) + expect(payload.fetch('analysis')).not_to have_key('advisories') + end + + it 'counts an explicitly enabled Rails import but does not index constants to decide' do + expect(ArchUnit::Extraction.const_get(:ConstantIndex)).not_to receive(:new) + write('app/services/order_service.rb', "require_dependency 'order'") + expect(invoke('--load-path', 'app/models').last.dig('analysis', 'advisories')).not_to be_empty + result = invoke('--rails-imports', '--load-path', 'app/models') + expect(result.first).to eq(0) + expect(result.last.fetch('analysis')).not_to have_key('advisories') + end + + it 'does not treat a hint as baseline debt or change its exit status' do + path = @root.join('debt.json').to_s + code, payload = invoke('--output', path, command: 'baseline') + expect(code).to eq(0) + expect(payload.dig('baseline', 'accepted_count')).to eq(0) + expect(JSON.parse(File.read(path)).fetch('entries')).to eq([]) + expect(invoke('--baseline', path).first).to eq(0) + end + + it 'does not collect or emit advisories in a direct library check' do + rule = ArchUnit.architecture_preset(:rails, ArchUnit::PresetOptions.new(project_locator: @root)) + expect(ArchUnit::Layers::FluentApi.const_get(:RailsImportCoverage)).not_to receive(:new) + expect(ArchUnit::Extraction.const_get(:ConstantIndex)).not_to receive(:new) + expect(rule.check).to eq([]) + end +end