diff --git a/API.md b/API.md
index 6fe17c1..e197675 100644
--- a/API.md
+++ b/API.md
@@ -133,9 +133,11 @@ rules = [
Positive dependency rules are allowlists: every selected dependency must match at least one target.
Negated dependency rules are blocklists: matching dependencies become violations.
-Cycle projection uses iterative strongly-connected-component and elementary-cycle traversals, so
-long dependency chains do not consume Ruby's call stack. It still enumerates all elementary cycles;
-dense graphs can have exponentially many results. Scope cycle rules to meaningful components.
+Cycle projection uses iterative traversals. By default, it enumerates all elementary cycles; dense
+graphs can have exponentially many results. To report one reproducible closed path per cyclic group,
+pass `CheckOptions.new(cycle_reporting: :witness)` to the check. Both modes decide whether the
+entire selected file graph is acyclic; the witness list is not a count of all paths.
+`CycleViolation#witness?` distinguishes a witness from an exhaustive result.
@@ -421,6 +423,9 @@ format option applies to init/check/explain and errors; help/version remain plai
`--format json` produces one document with `schema_version: 1`, `archunit_version`, `command`,
`project_root`, `config_path`, `dependency_analysis`, `rails_imports`, `load_paths`, `source_exclusions`,
`status`, `rules`, `analysis`, and `summary`. The new settings/diagnostics are additive schema-1 fields.
+With `check --cycle-reporting witness`, the report adds `cycle_reporting: "witness"` at the top
+level and on each witness violation. The default (`exhaustive`) omits these fields. The summary
+counts reported violations, not all possible cycles. Witness mode cannot generate or use a baseline.
Rule entries carry `name`, nullable `rationale`, `status`, `analysis`, and `violations`;
each violation carries its `type`,
shared formatter `message`, and `details`. Summary counts describe completed/listed rules and their
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 447aeed..deef757 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -20,6 +20,8 @@
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.
+- Add opt-in file cycle witnesses: one concrete path per cyclic group without enumerating all
+ paths. Exhaustive output stays the default and is required for path-based baselines.
## 1.1.0 - 2026-11-23
diff --git a/GUIDE.md b/GUIDE.md
index 9716687..5caa989 100644
--- a/GUIDE.md
+++ b/GUIDE.md
@@ -862,6 +862,12 @@ records the decision and probes. Graph queries are available, but semantic CLI t
PlantUML support is a small component-diagram subset. `.archignore` does not support negation or
nested ignore files. Dense graphs can have exponentially many cycles despite iterative traversal.
+
+For file cycle rules, `bundle exec archunit check --cycle-reporting witness` or
+`ArchUnit::CheckOptions.new(cycle_reporting: :witness)` shows one concrete cycle per cyclic group.
+The whole selected graph is checked; a shorter report cannot turn a cycle into a pass. Self-edges,
+external imports and dependencies outside the file selection are treated as in the default mode.
+Use the default exhaustive mode for path-based baselines and when you need every cycle path.
No-target-execution is not an OS sandbox against a hostile, concurrently changing filesystem.
For reproducible Linux/Windows timing, startup, memory and changed-source evidence, see the
diff --git a/benchmark/study/README.md b/benchmark/study/README.md
index 85a9160..9afe840 100644
--- a/benchmark/study/README.md
+++ b/benchmark/study/README.md
@@ -172,3 +172,21 @@ bundle exec ruby real_project.rb /path/to/pinned-sparse-discourse ../../pkg/disc
The root RSpec study test is candidate-only, with four pairs and one trial, no native comparator
or startup workers. The comparator is optional research tooling. Failed installation/controls are
study failures, never measured zeroes or evidence of superiority.
+
+## Bounded file cycle reporting
+
+From the repository root, run `bundle exec ruby benchmark/study/cycle_witnesses.rb`. Each fixture
+contains every forward edge and one closing edge, so there are exactly `2**(vertices - 2)` simple
+cycles. The script checks this count and the deterministic witness path. It compares the two
+projection/reporting modes only, excluding discovery, parsing, and serialization. Three alternating
+runs per mode; medians below from Ruby 4.0.6 on Windows. These are observations, not CI timing gates.
+
+| Vertices | Exhaustive → witness paths | Median time (ms) | Allocated Ruby objects |
+| ---: | ---: | ---: | ---: |
+| 10 | 256 → 1 | 2.47 → 0.40 | 7,944 → 927 |
+| 14 | 4,096 → 1 | 46.96 → 0.61 | 128,866 → 1,745 |
+| 18 | 65,536 → 1 | 1,710.71 → 0.86 | 2,296,780 → 2,835 |
+
+In the last case the exhaustive paths contain 655,360 edge entries versus three in the witness.
+Witness mode classifies all components; it bounds report size to one path per cyclic component,
+not a fixed number of paths across the project.
diff --git a/benchmark/study/cycle_witnesses.rb b/benchmark/study/cycle_witnesses.rb
new file mode 100644
index 0000000..6863cff
--- /dev/null
+++ b/benchmark/study/cycle_witnesses.rb
@@ -0,0 +1,70 @@
+# frozen_string_literal: true
+
+require 'archunit'
+require 'json'
+
+# Small, fixed graphs with an independently known exponential number of simple cycles.
+module CycleWitnessStudy
+ PROJECTION = ArchUnit::Common::Projection
+ private_constant :PROJECTION
+
+ module_function
+
+ def run
+ cases = [10, 14, 18].map { |size| measure(size) }
+ puts JSON.pretty_generate(ruby: RUBY_DESCRIPTION, runs_per_mode: 3, cases:)
+ end
+
+ def measure(size)
+ labels = (0...size).map { |index| format('file-%02d.rb', index) }
+ graph = fixture(labels)
+ samples = collect(graph, labels)
+ { vertices: size, edges: graph.length, modes: samples.transform_values { |rows| median(rows) } }
+ end
+
+ def collect(graph, labels)
+ counts = { exhaustive: 2**(labels.length - 2), witness: 1 }
+ samples = { exhaustive: [], witness: [] }
+ 3.times do |iteration|
+ order = iteration.odd? ? counts.keys.reverse : counts.keys
+ order.each { |mode| samples.fetch(mode) << sample(graph, labels, mode, counts.fetch(mode)) }
+ end
+ samples
+ end
+
+ def fixture(labels)
+ pairs = labels.combination(2).to_a << [labels.last, labels.first]
+ raw = pairs.map { |source, target| ArchUnit::Edge.new(source:, target:, external: false) }
+ PROJECTION.project_edges(raw, PROJECTION.per_internal_edge)
+ end
+
+ def sample(graph, labels, mode, count)
+ GC.start
+ allocations = GC.stat(:total_allocated_objects)
+ start = Process.clock_gettime(Process::CLOCK_MONOTONIC)
+ cycles = project(graph, mode)
+ seconds = Process.clock_gettime(Process::CLOCK_MONOTONIC) - start
+ allocated = GC.stat(:total_allocated_objects) - allocations
+ validate(cycles, labels, mode, count)
+ { milliseconds: (seconds * 1000).round(3), allocations: allocated,
+ reported_paths: cycles.length, reported_edge_steps: cycles.sum(&:length) }
+ end
+
+ def project(graph, mode)
+ mode == :witness ? PROJECTION.project_cycle_witnesses(graph) : PROJECTION.project_cycles(graph)
+ end
+
+ def validate(cycles, labels, mode, count)
+ abort "wrong count for #{mode}" unless cycles.length == count
+ return unless mode == :witness
+
+ path = cycles.fetch(0).map(&:source_label)
+ abort 'wrong path for witness' unless path == [labels[0], labels[1], labels.last]
+ end
+
+ def median(rows)
+ rows.first.keys.to_h { |key| [key, rows.map { |row| row.fetch(key) }.sort.fetch(1)] }
+ end
+end
+
+CycleWitnessStudy.run
diff --git a/lib/archunit/cli/baseline_identity.rb b/lib/archunit/cli/baseline_identity.rb
index 37f1b7c..f4262f5 100644
--- a/lib/archunit/cli/baseline_identity.rb
+++ b/lib/archunit/cli/baseline_identity.rb
@@ -57,6 +57,10 @@ def self.filter(value)
end
def self.cycle(value)
+ if value.witness?
+ raise ArgumentError, 'cycle witness reporting is incompatible with baselines'
+ end
+
edges = value.cycle.map { |item| edge(item) }
return unless edges.map(&:first).uniq.length == edges.length
diff --git a/lib/archunit/cli/cycle_reporting_options.rb b/lib/archunit/cli/cycle_reporting_options.rb
new file mode 100644
index 0000000..e9b3e69
--- /dev/null
+++ b/lib/archunit/cli/cycle_reporting_options.rb
@@ -0,0 +1,33 @@
+# frozen_string_literal: true
+
+module ArchUnit
+ module CLI
+ # Parsing and preflight validation for the file cycle report policy.
+ # @api private
+ module CycleReportingOptions
+ def cycle_reporting
+ @cycle_reporting || 'exhaustive'
+ end
+
+ private
+
+ def cycle_reporting_option(options)
+ options.on('--cycle-reporting MODE', %w[exhaustive witness],
+ 'File cycles: exhaustive (default) or one witness per cyclic group') do |value|
+ @cycle_reporting = value
+ end
+ end
+
+ def validate_cycle_reporting
+ return if cycle_reporting != 'witness' || %w[help version].include?(command)
+
+ if baseline_path || command == 'baseline'
+ raise ArgumentError, 'cycle witness reporting is incompatible with baselines'
+ end
+ return if command == 'check'
+
+ raise ArgumentError, '--cycle-reporting witness is only valid for check'
+ end
+ end
+ end
+end
diff --git a/lib/archunit/cli/options.rb b/lib/archunit/cli/options.rb
index 46b349f..ed982f5 100644
--- a/lib/archunit/cli/options.rb
+++ b/lib/archunit/cli/options.rb
@@ -3,6 +3,7 @@
require 'optparse'
require_relative '../common/extraction/source_exclusions'
require_relative 'baseline_options'
+require_relative 'cycle_reporting_options'
module ArchUnit
module CLI
@@ -10,6 +11,7 @@ module CLI
# @api private
class Options
include BaselineOptions
+ include CycleReportingOptions
attr_reader :command, :project_root, :config_path, :format, :dependency_analysis, :parser,
:rails_imports, :rails_associations, :load_paths, :source_exclusions
@@ -46,6 +48,7 @@ def parse!
def validate_arguments
validate_baseline_options
+ validate_cycle_reporting
unless @arguments.empty?
raise OptionParser::InvalidArgument, "unexpected arguments: #{@arguments.join(' ')}"
end
@@ -66,6 +69,7 @@ def build_parser
load_path_option(options)
source_exclusion_option(options)
baseline_options(options)
+ cycle_reporting_option(options)
output_options(options)
end
end
diff --git a/lib/archunit/cli/report.rb b/lib/archunit/cli/report.rb
index b31fe78..8b8b3a3 100644
--- a/lib/archunit/cli/report.rb
+++ b/lib/archunit/cli/report.rb
@@ -32,6 +32,7 @@ def initialize(options)
status: 'error', rules: [], analysis: AnalysisReport.new.to_h
}
@payload[:rails_associations] = true if options.rails_associations
+ @payload[:cycle_reporting] = 'witness' if options.cycle_reporting == 'witness'
end
def add_rule(rule, violations: nil, analysis: nil)
@@ -83,7 +84,13 @@ def rule_status(violations)
def violation_payload(violation)
formatted = Testing::ViolationFactory.from_violation(violation)
- { type: violation.class.name, message: formatted.message, details: formatted.details }
+ result = {
+ type: violation.class.name, message: formatted.message, details: formatted.details
+ }
+ if violation.is_a?(Files::Assertion::CycleViolation) && violation.witness?
+ result[:cycle_reporting] = 'witness'
+ end
+ result
end
def write_text(out)
@@ -101,6 +108,7 @@ def write_header(out)
end
def write_notice(out)
+ write_cycle_notice(out) if payload[:cycle_reporting] == 'witness'
out.puts('Rails require_dependency imports: enabled') if payload[:rails_imports]
out.puts('Rails explicit association class names: enabled') if payload[:rails_associations]
case payload[:status]
@@ -111,6 +119,10 @@ def write_notice(out)
end
end
+ def write_cycle_notice(out)
+ out.puts('Cycle reporting: one witness per cyclic group, not all cycle paths.')
+ end
+
def write_rule(rule, out)
out.puts("[#{rule[:status]}] #{rule[:name]}")
out.puts(" Because: #{rule[:rationale]}") if rule[:rationale]
diff --git a/lib/archunit/cli/runner.rb b/lib/archunit/cli/runner.rb
index f64d824..0e89f4b 100644
--- a/lib/archunit/cli/runner.rb
+++ b/lib/archunit/cli/runner.rb
@@ -81,8 +81,8 @@ def check(rules)
options = Common::FluentApi::CheckOptions.new(
dependency_analysis: @options.dependency_analysis.to_sym,
rails_imports: @options.rails_imports, rails_associations: @options.rails_associations,
- load_paths: @options.load_paths,
- source_exclusions: @options.source_exclusions
+ load_paths: @options.load_paths, source_exclusions: @options.source_exclusions,
+ cycle_reporting: @options.cycle_reporting.to_sym
)
check_rules(rules, options)
BaselineRun.new(@options).finish(@report, @evaluations)
diff --git a/lib/archunit/common/fluentapi/check_options.rb b/lib/archunit/common/fluentapi/check_options.rb
index 4f27558..bf88b9f 100644
--- a/lib/archunit/common/fluentapi/check_options.rb
+++ b/lib/archunit/common/fluentapi/check_options.rb
@@ -9,7 +9,7 @@ module FluentApi
# Immutable options shared by every terminal rule check.
CheckOptions = Data.define(
:allow_empty_tests, :logging, :clear_cache, :load_paths, :dependency_analysis,
- :rails_imports, :source_exclusions, :rails_associations
+ :rails_imports, :source_exclusions, :rails_associations, :cycle_reporting
) do
# Normalizes nil or an existing options value for terminal execution.
# @param value [CheckOptions, nil]
@@ -29,10 +29,11 @@ def self.resolve(value)
# @param rails_imports [Boolean] opt into static Rails require_dependency syntax
# @param rails_associations [Boolean] opt into explicit Rails association class names
# @param source_exclusions [Array] additional project-relative source globs
+ # @param cycle_reporting [Symbol] :exhaustive or one :witness per cyclic component
def initialize( # rubocop:disable Metrics/ParameterLists
allow_empty_tests: false, logging: nil, clear_cache: false, load_paths: [],
dependency_analysis: :imports, rails_imports: false, source_exclusions: [],
- rails_associations: false
+ rails_associations: false, cycle_reporting: :exhaustive
)
validate_boolean(allow_empty_tests, :allow_empty_tests)
validate_logging(logging)
@@ -40,9 +41,7 @@ def initialize( # rubocop:disable Metrics/ParameterLists
validate_rails_options(rails_imports, rails_associations)
load_paths = immutable_load_paths(load_paths)
source_exclusions = Common::Extraction::SourceExclusions.normalize(source_exclusions)
- unless %i[imports imports_and_constants].include?(dependency_analysis)
- raise ArgumentError, 'dependency_analysis must be :imports or :imports_and_constants'
- end
+ validate_modes(dependency_analysis, cycle_reporting)
super
end
@@ -71,6 +70,15 @@ def rails_associations?
private
+ def validate_modes(dependency_analysis, cycle_reporting)
+ unless %i[imports imports_and_constants].include?(dependency_analysis)
+ raise ArgumentError, 'dependency_analysis must be :imports or :imports_and_constants'
+ end
+ return if %i[exhaustive witness].include?(cycle_reporting)
+
+ raise ArgumentError, 'cycle_reporting must be :exhaustive or :witness'
+ end
+
def validate_rails_options(imports, associations)
validate_boolean(imports, :rails_imports)
validate_boolean(associations, :rails_associations)
diff --git a/lib/archunit/common/projection/cycles/cycle_witnesses.rb b/lib/archunit/common/projection/cycles/cycle_witnesses.rb
new file mode 100644
index 0000000..9f583d4
--- /dev/null
+++ b/lib/archunit/common/projection/cycles/cycle_witnesses.rb
@@ -0,0 +1,70 @@
+# frozen_string_literal: true
+
+require_relative 'tarjan_scc'
+
+module ArchUnit
+ module Common
+ module Projection
+ module Cycles
+ # Finds one reproducible non-self cycle in each cyclic component, without enumeration.
+ class CycleWitnesses
+ def self.call(adjacency)
+ new(adjacency).call
+ end
+
+ def initialize(adjacency)
+ @adjacency = adjacency.transform_values(&:sort)
+ end
+
+ def call
+ TarjanScc.call(@adjacency).select { |component| component.length > 1 }
+ .sort_by(&:first).map { |component| witness(component) }.freeze
+ end
+
+ private
+
+ def witness(component)
+ start = component.first
+ members = component.to_set
+ next_vertex = @adjacency.fetch(start).find do |target|
+ target != start && members.include?(target)
+ end
+ parents = search(next_vertex, start, members)
+ restore_path(start, parents)
+ end
+
+ def search(first, start, members)
+ queue = [first]
+ parents = { first => nil }
+ queue.each do |current|
+ break if current == start
+
+ enqueue_neighbours(current, parents, queue, members)
+ end
+ parents
+ end
+
+ def enqueue_neighbours(current, parents, queue, members)
+ @adjacency.fetch(current).each do |neighbour|
+ next if parents.key?(neighbour) || !members.include?(neighbour)
+
+ parents[neighbour] = current
+ queue << neighbour
+ end
+ end
+
+ def restore_path(start, parents)
+ path = []
+ current = start
+ until current.nil?
+ path << current
+ current = parents.fetch(current)
+ end
+ # Shared cycle projection attaches the closing edge itself.
+ [start, *path.drop(1).reverse].freeze
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/lib/archunit/common/projection/project_cycles.rb b/lib/archunit/common/projection/project_cycles.rb
index c903761..f049ed7 100644
--- a/lib/archunit/common/projection/project_cycles.rb
+++ b/lib/archunit/common/projection/project_cycles.rb
@@ -1,6 +1,7 @@
# frozen_string_literal: true
require_relative 'cycles/johnson_cycles'
+require_relative 'cycles/cycle_witnesses'
require_relative 'edge_projections'
require_relative 'project_edges'
require_relative 'projected_edge'
@@ -16,12 +17,22 @@ def project_internal_cycles(graph)
end
def project_cycles(edges)
+ project_cycle_paths(edges, Cycles::JohnsonCycles)
+ end
+
+ # Reports one evidence-backed path per cyclic component, not all its paths.
+ def project_cycle_witnesses(edges)
+ project_cycle_paths(edges, Cycles::CycleWitnesses, sort_labels: true)
+ end
+
+ def project_cycle_paths(edges, algorithm, sort_labels: false)
projected_edges = normalize_projected_edges(edges)
- label_ids = label_ids_for(projected_edges)
+ label_ids = label_ids_for(projected_edges, sort_labels:)
edges_by_ids = index_edges(projected_edges, label_ids)
- paths = Cycles::JohnsonCycles.call(adjacency_for(edges_by_ids))
+ paths = algorithm.call(adjacency_for(edges_by_ids))
cycles_from_paths(paths, edges_by_ids)
end
+ private_class_method :project_cycle_paths
def cycles_from_paths(paths, edges_by_ids)
paths.map do |path|
@@ -64,8 +75,9 @@ def projected_edges_from(groups)
end
private_class_method :projected_edges_from
- def label_ids_for(edges)
+ def label_ids_for(edges, sort_labels:)
labels = edges.flat_map { |edge| [edge.source_label, edge.target_label] }.uniq
+ labels.sort! if sort_labels
labels.each_with_index.to_h.freeze
end
private_class_method :label_ids_for
diff --git a/lib/archunit/extraction/graph_cache_key.rb b/lib/archunit/extraction/graph_cache_key.rb
index 153c321..2839e7d 100644
--- a/lib/archunit/extraction/graph_cache_key.rb
+++ b/lib/archunit/extraction/graph_cache_key.rb
@@ -5,7 +5,7 @@ module Extraction
# Execution-only options are excluded; source exclusions already live in the pattern key.
module GraphCacheKey
REPRESENTED_ELSEWHERE = %i[
- allow_empty_tests logging clear_cache source_exclusions
+ allow_empty_tests logging clear_cache source_exclusions cycle_reporting
].freeze
private_constant :REPRESENTED_ELSEWHERE
diff --git a/lib/archunit/files/assertion/cycle_free.rb b/lib/archunit/files/assertion/cycle_free.rb
index 390c446..b308e8b 100644
--- a/lib/archunit/files/assertion/cycle_free.rb
+++ b/lib/archunit/files/assertion/cycle_free.rb
@@ -11,19 +11,29 @@ module Assertion
class CycleViolation < Common::Assertion::Violation
attr_reader :cycle, :path
- def initialize(cycle:)
+ def initialize(cycle:, witness: false)
+ unless [true, false].include?(witness)
+ raise ArgumentError, 'witness must be true or false'
+ end
+
+ @witness = witness
@cycle = immutable_cycle(cycle)
@path = [cycle.first.source_label, *cycle.map(&:target_label)].freeze
super()
end
+ # @return [Boolean] whether this is one example, not exhaustive cycle reporting
+ def witness?
+ @witness
+ end
+
def ==(other)
- other.is_a?(self.class) && cycle == other.cycle
+ other.is_a?(self.class) && cycle == other.cycle && witness? == other.witness?
end
alias eql? ==
def hash
- [self.class, cycle].hash
+ [self.class, cycle, witness?].hash
end
private
@@ -48,10 +58,10 @@ def closed_cycle?(edges)
module_function
- def gather_cycle_violations(cycles)
+ def gather_cycle_violations(cycles, witness: false)
raise ArgumentError, 'cycles must be an Array' unless cycles.is_a?(Array)
- cycles.map { |cycle| CycleViolation.new(cycle:) }
+ cycles.map { |cycle| CycleViolation.new(cycle:, witness:) }
end
end
end
diff --git a/lib/archunit/files/fluentapi/cycle_free_file_condition.rb b/lib/archunit/files/fluentapi/cycle_free_file_condition.rb
index 1470872..8e7407b 100644
--- a/lib/archunit/files/fluentapi/cycle_free_file_condition.rb
+++ b/lib/archunit/files/fluentapi/cycle_free_file_condition.rb
@@ -37,16 +37,25 @@ def perform_check(options)
)
return empty_test if empty_test
- cycles = cycles_within(views.internal_edges, nodes)
- Assertion.gather_cycle_violations(cycles)
+ cycle_violations(views.internal_edges, nodes, options)
end
- def cycles_within(internal_edges, nodes)
+ def cycle_violations(internal_edges, nodes, options)
+ edges = edges_within(internal_edges, nodes)
+ projection = Common::Projection
+ if options.cycle_reporting == :witness
+ witnesses = projection.project_cycle_witnesses(edges)
+ Assertion.gather_cycle_violations(witnesses, witness: true)
+ else
+ Assertion.gather_cycle_violations(projection.project_cycles(edges))
+ end
+ end
+
+ def edges_within(internal_edges, nodes)
selected_labels = nodes.to_h { |node| [node.label, true] }
- edges = internal_edges.select do |edge|
+ internal_edges.select do |edge|
selected_labels[edge.source_label] && selected_labels[edge.target_label]
end
- Common::Projection.project_cycles(edges)
end
end
end
diff --git a/lib/archunit/testing/violation_factory.rb b/lib/archunit/testing/violation_factory.rb
index b6f7f40..0ac422d 100644
--- a/lib/archunit/testing/violation_factory.rb
+++ b/lib/archunit/testing/violation_factory.rb
@@ -96,9 +96,10 @@ def external_module_dependency(violation)
end
def cycle(violation)
+ label = violation.witness? ? 'Cycle witness (not exhaustive)' : 'Cycle'
TestViolation.new(
message: 'Circular dependency detected',
- details: "Cycle: #{violation.path.join(' -> ')}."
+ details: "#{label}: #{violation.path.join(' -> ')}."
)
end
diff --git a/scripts/check_cli.rb b/scripts/check_cli.rb
index 957b241..57bf307 100644
--- a/scripts/check_cli.rb
+++ b/scripts/check_cli.rb
@@ -19,6 +19,7 @@ def run
check_imports(executable, root)
check_constants(executable, root)
check_parse_failure(executable, root)
+ check_cycle_witness(executable, root)
end
puts "CLI init/check/explain passed for archunit #{ArchUnit::VERSION} from #{executable}"
end
@@ -56,6 +57,24 @@ def check_parse_failure(executable, root)
abort 'CLI explanation pretends to check' unless explanation['status'] == 'configured'
end
+ def check_cycle_witness(executable, root)
+ prepare_cycle(root)
+ payload = check(executable, root, 'check', '--format=json', '--cycle-reporting=witness',
+ expected: 1)
+ witness = payload.dig('rules', 0, 'violations', 0, 'cycle_reporting')
+ abort 'CLI failed to label cycle witnesses' unless witness == 'witness'
+ check(executable, root, 'baseline', '--format=json', '--cycle-reporting=witness',
+ '--output=debt.json', expected: 2)
+ abort 'CLI wrote a witness baseline' if File.exist?(File.join(root, 'debt.json'))
+ end
+
+ def prepare_cycle(root)
+ configuration = "rule('cycles') { project_files.should.have_no_cycles }"
+ File.write(File.join(root, '.archunit.rb'), configuration)
+ File.write(File.join(root, 'app/api/request.rb'), "require_relative '../db/settings'")
+ File.write(File.join(root, 'app/db/settings.rb'), "require_relative '../api/request'")
+ end
+
def prepare_project(root)
%w[api db].each { |folder| FileUtils.mkdir_p(File.join(root, 'app', folder)) }
File.write(File.join(root, 'Gemfile'), "raise 'Target Gemfile must not execute'")
diff --git a/spec/cli/cycle_reporting_spec.rb b/spec/cli/cycle_reporting_spec.rb
new file mode 100644
index 0000000..3bfae89
--- /dev/null
+++ b/spec/cli/cycle_reporting_spec.rb
@@ -0,0 +1,106 @@
+# frozen_string_literal: true
+
+require 'archunit/cli'
+require 'json'
+require 'pathname'
+require 'stringio'
+require 'tmpdir'
+
+RSpec.describe ArchUnit::CLI, 'bounded cycle reporting' do
+ around do |example|
+ Dir.mktmpdir('archunit-cycle-reporting') do |dir|
+ @root = Pathname.new(dir)
+ @root.join('Gemfile').write("raise 'do not execute target'")
+ @root.join('a.rb').write("require_relative 'b'\nrequire_relative 'c'")
+ @root.join('b.rb').write("require_relative 'c'\nrequire_relative 'a'")
+ @root.join('c.rb').write("require_relative 'a'")
+ @config = @root.join('.archunit.rb')
+ @config.write("rule('cycles') { project_files.should.have_no_cycles }")
+ @debt = @root.join('debt.json')
+ example.run
+ ensure
+ ArchUnit.clear_graph_cache
+ end
+ end
+
+ def invoke(*arguments, command: 'check', format: 'json')
+ out = StringIO.new
+ err = StringIO.new
+ args = [command, '--format', format, *arguments]
+ code = described_class.run(args, cwd: @root.to_s, out:, err:)
+ [code, format == 'json' ? JSON.parse(out.string) : out.string]
+ end
+
+ let(:flag) { %w[--cycle-reporting witness] }
+
+ it 'keeps the default payload and order identical to explicit exhaustive mode' do
+ legacy = invoke
+ expect(legacy).to eq(invoke('--cycle-reporting', 'exhaustive'))
+ expect(legacy.first).to eq(1)
+ expect(legacy.last.dig('summary', 'violation_count')).to eq(3)
+ expect(legacy.last).not_to have_key('cycle_reporting')
+ expect(invoke('--output', @debt.to_s, command: 'baseline').first).to eq(0)
+ bytes = @debt.binread
+ accepted = invoke('--baseline', @debt.to_s, '--cycle-reporting', 'exhaustive')
+ expect(accepted.last.dig('baseline', 'accepted_count')).to eq(3)
+ expect(@debt.binread).to eq(bytes)
+ end
+
+ it 'labels samples as witnesses in text and additive JSON without changing the failed exit' do
+ code, json = invoke(*flag)
+ expect(code).to eq(1)
+ expect(json).to include('cycle_reporting' => 'witness', 'schema_version' => 1)
+ expect(json.dig('summary', 'violation_count')).to eq(1)
+ expect(json.dig('rules', 0, 'violations', 0)).to include(
+ 'cycle_reporting' => 'witness', 'type' => ArchUnit::CycleViolation.name
+ )
+ expect(invoke(*flag, format: 'text').last).to include('Cycle witness (not exhaustive)')
+ @root.join('a.rb').write('# fixed')
+ code, json = invoke(*flag)
+ expect(code).to eq(0)
+ expect(json.dig('summary', 'violation_count')).to eq(0)
+ end
+
+ it 'fails before reading config, accepting debt, or touching baseline output' do
+ @config.write("raise 'config must not be loaded'")
+ @debt.write('unchanged')
+ [
+ invoke(*flag, '--baseline', @debt.to_s),
+ invoke(*flag, '--output', @debt.to_s, '--force', command: 'baseline')
+ ].each do |code, json|
+ expect(code).to eq(2)
+ expect(json.dig('error', 'message')).to include('incompatible with baselines')
+ end
+ expect(@debt.read).to eq('unchanged')
+ end
+
+ it 'also refuses a witness returned by a custom Checkable with local options' do
+ expect(invoke('--output', @debt.to_s, command: 'baseline').first).to eq(0)
+ bytes = @debt.binread
+ @config.write(<<~RUBY)
+ rule('cycles') do
+ delegate = project_files.should.have_no_cycles
+ Class.new do
+ include ArchUnit::Checkable
+ define_method(:perform_check) do |_options|
+ delegate.check(ArchUnit::CheckOptions.new(cycle_reporting: :witness))
+ end
+ end.new
+ end
+ RUBY
+ calls = [invoke('--baseline', @debt.to_s),
+ invoke('--output', @debt.to_s, '--force', command: 'baseline')]
+ calls.each do |code, json|
+ expect(code).to eq(2)
+ expect(json.dig('error', 'message')).to include('incompatible with baselines')
+ end
+ expect(@debt.binread).to eq(bytes)
+ end
+
+ it 'rejects unsupported modes and witness options on non-check commands' do
+ expect(invoke('--cycle-reporting', '0').first).to eq(2)
+ expect(invoke(*flag, command: 'explain').first).to eq(2)
+ expect { ArchUnit::CheckOptions.new(cycle_reporting: 'witness') }
+ .to raise_error(ArgumentError, /cycle_reporting/)
+ end
+end
diff --git a/spec/common/projection/cycles/deep_graph_spec.rb b/spec/common/projection/cycles/deep_graph_spec.rb
index dd1184b..30b386b 100644
--- a/spec/common/projection/cycles/deep_graph_spec.rb
+++ b/spec/common/projection/cycles/deep_graph_spec.rb
@@ -19,6 +19,12 @@
expect(algorithms::JohnsonCycles.call(ring)).to eq([vertices])
end
+ it 'finds no witnesses on a long chain and exactly one on a long ring' do
+ ring = vertices.to_h { |vertex| [vertex, [(vertex + 1) % size]] }
+ expect(algorithms::CycleWitnesses.call(chain)).to eq([])
+ expect(algorithms::CycleWitnesses.call(ring)).to eq([vertices])
+ end
+
it 'unblocks a deep dependency chain without recursion' do
search = algorithms::JohnsonCycles.new(chain)
blocked_by = vertices.to_h { |vertex| [vertex, Set.new(chain.fetch(vertex))] }
diff --git a/spec/common/projection/project_cycles_spec.rb b/spec/common/projection/project_cycles_spec.rb
index cdb9d4c..b1592bb 100644
--- a/spec/common/projection/project_cycles_spec.rb
+++ b/spec/common/projection/project_cycles_spec.rb
@@ -67,4 +67,40 @@ def projected_edge(source, target, raw: raw_edge(source, target))
expect { described_class.project_cycles([Object.new]) }
.to raise_error(ArgumentError, /only ProjectedEdge/)
end
+
+ it 'reports exactly one stable closed path per cyclic group with all its edge evidence' do
+ a_to_b = projected_edge('a', 'b')
+ duplicate = projected_edge('a', 'b', raw: raw_edge('a/helper.rb', 'b/main.rb', kind: :load))
+ reverse = projected_edge('b', 'a')
+ edges = [a_to_b, duplicate, reverse, projected_edge('b', 'c'), projected_edge('c', 'a'),
+ projected_edge('c', 'd'), projected_edge('d', 'e'), projected_edge('e', 'd'),
+ projected_edge('f', 'f'), projected_edge('f', 'a')]
+
+ paths = [%w[a b], %w[d e]]
+ [edges, edges.reverse, edges.shuffle(random: Random.new(42))].each do |order|
+ witnesses = described_class.project_cycle_witnesses(order)
+ expect(witnesses.map { |cycle| cycle.map(&:source_label) }).to eq(paths)
+ expect(witnesses).to be_frozen
+ expect(witnesses).to all(be_frozen)
+ raw = witnesses.first.first.cumulated_edges
+ expect(raw).to match_array(a_to_b.cumulated_edges + duplicate.cumulated_edges)
+ expect(witnesses.first.last).to eq(reverse)
+ end
+ end
+
+ it 'uses an SCC pass without enumerating the thousands of paths in a dense cyclic group' do
+ labels = (0...14).map { |index| format('file-%02d', index) }
+ edges = labels.combination(2).map { |source, target| projected_edge(source, target) }
+ edges << projected_edge(labels.last, labels.first)
+ expect(described_class.project_cycles(edges).length).to eq(4096)
+ expect(described_class::Cycles::JohnsonCycles).not_to receive(:call)
+ expect(described_class::Cycles::TarjanScc).to receive(:call).once.and_call_original
+ expect(described_class.project_cycle_witnesses(edges).first&.map(&:source_label))
+ .to eq([labels[0], labels[1], labels.last])
+ end
+
+ it 'returns no witnesses for an acyclic or self-only selected graph' do
+ edges = [projected_edge('a', 'b'), projected_edge('b', 'c'), projected_edge('c', 'c')]
+ expect(described_class.project_cycle_witnesses(edges)).to eq([])
+ end
end
diff --git a/spec/extraction/analysis_views_spec.rb b/spec/extraction/analysis_views_spec.rb
index 6189b80..91a89ce 100644
--- a/spec/extraction/analysis_views_spec.rb
+++ b/spec/extraction/analysis_views_spec.rb
@@ -33,6 +33,7 @@ def view_references
options = ArchUnit::CheckOptions.new(allow_empty_tests: true)
expect(views(options)).to equal(first)
expect(views.nodes).to equal(first.nodes)
+ expect(views(options.with(cycle_reporting: :witness))).to equal(first)
end
it 'keeps old views until explicit rebuild, even after an on-disk edit' do
diff --git a/spec/files/fluentapi/cycle_free_file_condition_spec.rb b/spec/files/fluentapi/cycle_free_file_condition_spec.rb
index 19a0da9..9a2845f 100644
--- a/spec/files/fluentapi/cycle_free_file_condition_spec.rb
+++ b/spec/files/fluentapi/cycle_free_file_condition_spec.rb
@@ -33,6 +33,21 @@ def create_file(relative_path, contents = '# fixture')
expect(rule.check).to eq([])
end
+ it 'reports a witness only for cycles wholly within the selected files' do
+ create_file('a.rb', "require_relative 'b'\nrequire_relative 'c'")
+ create_file('b.rb', "require_relative 'a'")
+ create_file('c.rb', "require_relative 'd'")
+ create_file('d.rb', "require_relative 'c'")
+ files = ArchUnit.files(@project_root)
+ options = ArchUnit::CheckOptions.new(cycle_reporting: :witness)
+ expect(files.should.have_no_cycles.check(options).map(&:path))
+ .to eq([%w[a.rb b.rb a.rb], %w[c.rb d.rb c.rb]])
+ selected = files.in_path('a.rb').should.have_no_cycles
+ expect(selected.check(options)).to be_empty
+ missing = files.in_path('missing.rb').should.have_no_cycles
+ expect(missing.check(options).first).to be_a(ArchUnit::EmptyTestViolation)
+ end
+
it 'reports every cycle as a readable closed path' do
create_file('lib/a.rb', "require_relative 'b'\n")
create_file('lib/b.rb', "require_relative 'a'\n")