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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions .github/workflows/canary.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ on:
- 'benchmark/extraction.rb'
- 'benchmark/real_world_canary.rb'
- 'benchmark/canary/**'
- 'scripts/check_rails_zeitwerk_canary.rb'
- 'spec/benchmark/**'
- '.github/workflows/canary.yml'

Expand Down Expand Up @@ -77,3 +78,46 @@ jobs:
path: archunit/pkg/canary-${{ matrix.name }}.json
if-no-files-found: warn
retention-days: 14

rails-preset:
name: Rails preset — pinned Discourse
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@v7
with:
path: archunit
persist-credentials: false
- name: Check out pinned Rails source only
uses: actions/checkout@v7
with:
repository: discourse/discourse
ref: 2de9c9be4f89e392fe500dd27f928d6b1184bf09
path: corpus
fetch-depth: 1
persist-credentials: false
sparse-checkout-cone-mode: false
sparse-checkout: |
/app/controllers/about_controller.rb
/app/services/badge_granter.rb
/app/models/badge.rb
/config/application.rb
- uses: ruby/setup-ruby@v1
with:
ruby-version: '4.0'
bundler-cache: true
working-directory: archunit
- name: Verify the allowed and forbidden cases
working-directory: archunit
run: |
mkdir -p pkg
bundle exec ruby scripts/check_rails_zeitwerk_canary.rb ../corpus | tee pkg/rails-zeitwerk.json
shell: bash
- name: Retain the canary results
if: always()
uses: actions/upload-artifact@v7
with:
name: canary-rails-zeitwerk
path: archunit/pkg/rails-zeitwerk.json
if-no-files-found: warn
retention-days: 14
2 changes: 1 addition & 1 deletion API.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# ArchUnitRuby API Guide

This guide is the stable map of ArchUnitRuby's public fluent API. The
[class and method reference](https://dragonsec-ai.github.io/ArchUnitRuby/class_list.html)
[class and method reference](https://dragonsec-ai.github.io/ArchUnitRuby/_index.html)
is generated from the source, while this page explains
which entry point to choose and how the stages fit together.

Expand Down
6 changes: 6 additions & 0 deletions GUIDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -779,6 +779,12 @@ layers contain files but no cross-file import connects any two selected files. A
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.

The [pinned Discourse canary](https://github.com/dragonsec-ai/ArchUnitRuby/blob/main/scripts/check_rails_zeitwerk_canary.rb)
checks real controller, service, and model files from a Rails app without booting it. In a
disposable copy, a model-to-controller constant reference fails expanded analysis. Imports-only
still passes; adding one unrelated, allowed import removes even its advisory. Use
`imports_and_constants` in Rails CI for this policy, and verify it against a known violation.

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.
Expand Down
15 changes: 13 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ ArchUnit.project_files.in_folder('app/api/**')
ArchUnitRuby analyzes source with Prism without booting your application. It is the Ruby member
of the [ArchUnitEverything family](#community), inspired by—but not affiliated with—ArchUnit.

[Quickstart](#quickstart) · [Capabilities](#capabilities) · [User guide](GUIDE.md) ·
[Quickstart](#quickstart) · [Demo](#demo) · [Capabilities](#capabilities) · [User guide](GUIDE.md) ·
[API contract](API.md) · [Documentation site](https://dragonsec-ai.github.io/ArchUnitRuby/) ·
[Example project](#example-project) · [Limitations](#limitations)

Expand Down Expand Up @@ -123,7 +123,18 @@ Remove that dependency in this small fixture to return to green. In an applicati
the interaction through your intended service boundary instead of merely suppressing the test.
In a long-lived process, clear the graph cache after source edits; separate RSpec runs start fresh.

[Complete workflows](GUIDE.md) · [Watch the recorded demo](https://github.com/user-attachments/assets/9b7305a0-deee-454d-b99e-f8fac63d06ab)
[Complete workflows](GUIDE.md)

<a id="demo"></a>

## Demo

See ArchUnitRuby in action in the same screencast featured on the
[ArchUnit Ruby page](https://www.archunit.net/ruby/).

[![Watch the ArchUnitRuby demo on YouTube](https://i.ytimg.com/vi/yMbZWEv8DJA/hqdefault.jpg)](https://www.youtube.com/watch?v=yMbZWEv8DJA)

[Watch on YouTube](https://www.youtube.com/watch?v=yMbZWEv8DJA)

<a id="capabilities"></a>

Expand Down
20 changes: 16 additions & 4 deletions scripts/check_docs.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

ROOT = Pathname.new(__dir__).join('..').expand_path
OUTPUT = ROOT.join('docs')
PAGES_SITE = 'https://dragonsec-ai.github.io/ArchUnitRuby/'
REQUIRED_FILES = %w[
index.html file.API.html file.GUIDE.html _index.html class_list.html css/archunit.css
js/archunit.js assets/logo-rounded.png assets/social-preview.png .nojekyll robots.txt sitemap.xml
Expand All @@ -21,12 +22,23 @@ def internal_target(page, href)
end

def check_reference_navigation(page, content)
return unless content.include?('class="archunit-topbar"')
check_reference_link(page, content, 'Reference') if content.include?('class="archunit-topbar"')
return unless page.basename.to_s == 'file.API.html'

href = content[%r{<a href="([^"]+)">Reference</a>}, 1]
return if href && internal_target(page, href) == OUTPUT.join('_index.html')
check_reference_link(page, content, 'class and method reference')
end

def check_reference_link(page, content, label)
hrefs = content.scan(%r{<a href="([^"]+)">#{label}</a>}).flatten
return if !hrefs.empty? && hrefs.all? { |href| full_reference_index?(page, href) }

raise "#{label} must link to the full API index from #{page.relative_path_from(OUTPUT)}"
end

def full_reference_index?(page, href)
return href == "#{PAGES_SITE}_index.html" if href.start_with?(PAGES_SITE)

raise "Reference must link to the full API index from #{page.relative_path_from(OUTPUT)}"
internal_target(page, href) == OUTPUT.join('_index.html')
end

missing = REQUIRED_FILES.reject { |relative| OUTPUT.join(relative).exist? }
Expand Down
107 changes: 107 additions & 0 deletions scripts/check_rails_zeitwerk_canary.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
# frozen_string_literal: true

require 'archunit'
require 'archunit/cli'
require 'fileutils'
require 'json'
require 'pathname'
require 'stringio'
require 'tmpdir'

# The only executed configuration is written by this harness. Discourse files
# are input data; no Gemfile, Rails environment, or application code is loaded.
module RailsZeitwerkCanary
REVISION = '2de9c9be4f89e392fe500dd27f928d6b1184bf09'
CONTROLLER = 'app/controllers/about_controller.rb'
SERVICE = 'app/services/badge_granter.rb'
MODEL = 'app/models/badge.rb'
FILES = [CONTROLLER, SERVICE, MODEL, 'config/application.rb'].freeze
MODES = %i[imports imports_and_constants].freeze
ADVISORY = 'rails_no_scoped_imports'

module_function

def run(corpus)
Dir.mktmpdir('archunit-discourse-canary') do |dir|
root = Pathname.new(dir)
copy_project(corpus, root)
results, forbidden_edge = exercise(root)
{ repository: 'discourse/discourse', revision: REVISION, files: FILES, results:,
forbidden_edge: }
end
end

def exercise(root)
results = { clean: verify_case(root, codes: [0, 0], advisories: [true, false]) }
root.join(MODEL).open('ab') { |file| file.write("\n::AboutController\n") }
results[:forbidden] = verify_case(root, codes: [0, 1], advisories: [true, false])
forbidden_edge = verify_edge(root)
allowed_import = "\nrequire_relative '../services/badge_granter'\n"
root.join(CONTROLLER).open('ab') { |file| file.write(allowed_import) }
results[:forbidden_with_allowed_import] =
verify_case(root, codes: [0, 1], advisories: [false, false])
[results, forbidden_edge]
end

def copy_project(corpus, root)
FILES.each do |path|
source = corpus.join(path)
abort "Canary requires pinned Discourse source: #{source}" unless source.file?

destination = root.join(path)
destination.dirname.mkpath
FileUtils.cp(source, destination)
end
root.join('Gemfile').write("raise 'do not execute the target Gemfile'\n")
config = "rule('Discourse Rails layers') { architecture_preset(:rails) }\n"
root.join('.archunit.rb').write(config)
end

def check(root, mode)
status, report = cli_report(root, mode)
advisory = Array(report.dig('analysis', 'advisories')).any? { |item| item['code'] == ADVISORY }
{ status:, advisory:, violations: report.fetch('summary').fetch('violation_count') }
end

def cli_report(root, mode)
output = StringIO.new
errors = StringIO.new
arguments = ['check', '--format=json', '--dependency-analysis', mode.to_s]
status = ArchUnit::CLI.run(arguments, cwd: root.to_s, out: output, err: errors)
report = JSON.parse(output.string)
abort "Unexpected #{mode} analysis error: #{report.inspect}" if status == 2

[status, report]
end

def verify_case(root, codes:, advisories:)
MODES.each_with_index.to_h do |mode, index|
row = check(root, mode)
expected = { status: codes.fetch(index), advisory: advisories.fetch(index),
violations: codes.fetch(index) }
unless row == expected
abort "Unexpected #{mode} result: #{row.inspect}, expected #{expected.inspect}"
end

[mode, row]
end
end

def verify_edge(root)
options = ArchUnit::CheckOptions.new(dependency_analysis: :imports_and_constants)
graph = ArchUnit::Extraction.extract_graph(root, options:)
edge = graph.find { |item| forbidden?(item) }
evidence = edge&.evidence&.find { |item| item.kind == :constant_reference }
abort 'Missing source evidence for the inserted forbidden dependency' unless evidence

{ source: edge.source, target: edge.target, line: evidence.line_number, kind: evidence.kind }
end

def forbidden?(edge)
edge.source == MODEL && edge.target == CONTROLLER && !edge.external
end
end

abort 'Pass one pinned Discourse source root to check_rails_zeitwerk_canary.rb' unless ARGV.one?

puts JSON.pretty_generate(RailsZeitwerkCanary.run(Pathname.new(ARGV.fetch(0)).expand_path))
77 changes: 77 additions & 0 deletions spec/common/projection/cycle_oracle_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
# frozen_string_literal: true

RSpec.describe ArchUnit::Common::Projection, 'cycle witness cross-check' do
# Independent transitive closure: vertices in a cyclic group can reach each
# other via nonempty paths. Do not use the SCC or cycle enumeration code here.
def cyclic_groups(size, pairs)
reached = Array.new(size) { Array.new(size, false) }
pairs.each { |from, to| reached[from][to] = true }
size.times { |via| close_paths(reached, via) }
groups(reached)
end

def close_paths(reached, via)
reached.each do |row|
next unless row[via]

reached.fetch(via).each_with_index { |route, target| row[target] ||= route }
end
end

def groups(reached)
reached.each_index.filter_map do |vertex|
next unless reached[vertex][vertex]

group = reached.each_index.select { |other| reached[vertex][other] && reached[other][vertex] }
group if group.first == vertex
end
end

def small_graphs
pairs = (0...3).to_a.permutation(2).to_a
(0...(1 << pairs.size)).map do |mask|
[3, pairs.each_with_index.filter_map { |pair, index| pair if mask[index] == 1 }]
end
end

def larger_graphs
random = Random.new(120)
Array.new(200) do |index|
size = random.rand(3..8)
density = ((index % 7) + 1) / 8.0
[size, (0...size).to_a.permutation(2).select { random.rand < density }]
end
end

def project(pairs)
pairs.map do |from, to|
source = from.to_s
target = to.to_s
edge = ArchUnit::Edge.new(source:, target:, external: false, import_kinds: [:require])
ArchUnit::ProjectedEdge.new(
source_label: source, target_label: target, cumulated_edges: [edge]
)
end
end

it 'returns one valid, stable witness per cyclic group without changing the decision' do
(small_graphs + larger_graphs).each_with_index do |(size, pairs), index|
input = project(pairs)
witnesses = described_class.project_cycle_witnesses(input)
expected = cyclic_groups(size, pairs)
expect(witnesses.size).to eq(expected.size), "cyclic group count for sample #{index}"
expect(witnesses.empty?).to eq(described_class.project_cycles(input).empty?),
"exhaustive decision for sample #{index}"
expect(witnesses).to eq(described_class.project_cycle_witnesses(input.reverse)),
"stable order for sample #{index}"
groups = witnesses.map do |cycle|
sources = cycle.map { |edge| edge.source_label.to_i }
targets = cycle.map { |edge| edge.target_label.to_i }
expect(targets).to eq(sources.rotate), "closed path for sample #{index}"
expect(pairs).to include(*sources.zip(targets))
expected.find { |group| (sources - group).empty? }
end
expect(groups).to match_array(expected), "group coverage for sample #{index}"
end
end
end