From 78037b8fe05f364bf4af2d325b8c599ad3229d37 Mon Sep 17 00:00:00 2001 From: TristanKruse Date: Sun, 22 Nov 2026 09:17:54 +0100 Subject: [PATCH 1/4] Add explicit accepted-debt baselines with stale detection (#89) --- .github/PRE_RELEASE_CHECKLIST.md | 15 +- .github/workflows/ci.yml | 4 + API.md | 35 ++++ CHANGELOG.md | 3 + README.md | 27 +++ lib/archunit/cli/baseline_context.rb | 42 ++++ lib/archunit/cli/baseline_document.rb | 58 ++++++ lib/archunit/cli/baseline_fingerprint.rb | 36 ++++ lib/archunit/cli/baseline_identity.rb | 85 ++++++++ lib/archunit/cli/baseline_ledger.rb | 38 ++++ lib/archunit/cli/baseline_object.rb | 15 ++ lib/archunit/cli/baseline_options.rb | 48 +++++ lib/archunit/cli/baseline_run.rb | 85 ++++++++ lib/archunit/cli/baseline_schema.rb | 53 +++++ lib/archunit/cli/baseline_text.rb | 31 +++ lib/archunit/cli/options.rb | 9 +- lib/archunit/cli/report.rb | 2 + lib/archunit/cli/runner.rb | 7 +- scripts/check_baselines.rb | 73 +++++++ spec/ci/workflow_spec.rb | 5 + spec/cli/baseline_fingerprint_spec.rb | 93 +++++++++ spec/cli/baseline_spec.rb | 239 +++++++++++++++++++++++ 22 files changed, 992 insertions(+), 11 deletions(-) create mode 100644 lib/archunit/cli/baseline_context.rb create mode 100644 lib/archunit/cli/baseline_document.rb create mode 100644 lib/archunit/cli/baseline_fingerprint.rb create mode 100644 lib/archunit/cli/baseline_identity.rb create mode 100644 lib/archunit/cli/baseline_ledger.rb create mode 100644 lib/archunit/cli/baseline_object.rb create mode 100644 lib/archunit/cli/baseline_options.rb create mode 100644 lib/archunit/cli/baseline_run.rb create mode 100644 lib/archunit/cli/baseline_schema.rb create mode 100644 lib/archunit/cli/baseline_text.rb create mode 100644 scripts/check_baselines.rb create mode 100644 spec/cli/baseline_fingerprint_spec.rb create mode 100644 spec/cli/baseline_spec.rb diff --git a/.github/PRE_RELEASE_CHECKLIST.md b/.github/PRE_RELEASE_CHECKLIST.md index 8aa6030..dc75f24 100644 --- a/.github/PRE_RELEASE_CHECKLIST.md +++ b/.github/PRE_RELEASE_CHECKLIST.md @@ -2,8 +2,9 @@ The original feature backlog (#47, #48, #54, #55) and the correctness/QA audit fixes (#63-65) are merged. PRs #68-70 were reviewed and merged on 2026-10-26; the resulting `main` passed CI, security -scanning, and documentation deployment. This checklist tracks the 1.0.0 preparation, not proof that -RubyGems publication has happened. The preceding published gem is 0.0.1. +scanning, and documentation deployment. The 1.0.0 preparation and publication below are historical: +1.0.0 was published and verified in #71. Current main contains unreleased 1.1 development; these +old evidence counts are not the current suite or authorization to publish a new version. ## 1.0.0 preparation @@ -29,16 +30,18 @@ refresh, and strict malformed-source diagnostics, plus both dependency-analysis ## Publication remains a separate approval -- [ ] Review and merge the preparation PR, then verify the full matrix on that exact `main` revision: +- [x] Review and merge the preparation PR, then verify the full matrix on that exact `main` revision: supported Ruby versions, Windows/Linux, library-only coverage, lint, dogfooding, docs, packaging, installed-gem checks, security, and the downstream RAG fixture. -- [ ] Confirm the changelog date at publication and explicitly authorize the trusted-publisher +- [x] Confirm the changelog date at publication and explicitly authorize the trusted-publisher `Release` workflow for version `1.0.0` on `main`. Verify the RubyGems account and configured release environment still belong to the intended maintainers. Never publish merely to run checks. -- [ ] Verify the published 1.0.0 gem and generated tag, install from RubyGems in a clean project, +- [x] Verify the published 1.0.0 gem and generated tag, install from RubyGems in a clean project, and rerun passing/failing architecture examples before announcing availability. -CLI, richer semantic method/protocol rules, presets, and gradual-adoption baselines remain in #66. +Publication evidence: #71 (registry checksum, tag and clean-project acceptance verified). +CLI execution/diagnostics are now merged (#73, #88). Further baselines, presets, bounded semantic +evaluation and representative Linux performance studies are tracked by #89–92 under #66. They are not prerequisites for the initial stable API baseline. ## Audit coverage added diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4fdea57..54e61ab 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -65,6 +65,9 @@ jobs: - name: Exercise cache-aware analysis diagnostics run: bundle exec ruby scripts/check_analysis_diagnostics.rb + - name: Exercise explicit accepted-debt baselines + run: bundle exec ruby scripts/check_baselines.rb + quality: name: Quality and package — Ruby 4.0 on Ubuntu runs-on: ubuntu-latest @@ -164,6 +167,7 @@ jobs: ruby scripts/check_rails_imports.rb ruby scripts/check_source_exclusions.rb ruby scripts/check_analysis_diagnostics.rb + ruby scripts/check_baselines.rb ruby scripts/check_cli.rb ruby -e " require 'json' diff --git a/API.md b/API.md index a9733ce..14e2fb1 100644 --- a/API.md +++ b/API.md @@ -381,6 +381,41 @@ actual work (zero repeated cold counters); diagnostic snapshots are separate fro ## Errors and support +### Explicit violation baselines (unreleased 1.1) + +`archunit baseline --output FILE.json` evaluates every rule and atomically writes an explicitly +reviewable accepted-debt document. It refuses existing output without `--force`, non-JSON output +names, empty-selection violations, custom/unknown violation types, and unobserved scopes. No output +is written until all rules finish; parse/configuration failures never replace existing debt. +`archunit check --baseline FILE` remains read-only. All sources/rules are still checked; it returns +0 only when there are no new violations or stale entries. A run with accepted violations has +`status: accepted`, not `passed`. Baseline creation has `status: baseline_created`, not an +architecture pass. Without either flag/command normal strict checks are unchanged. + +The document has `schema_version: 1`, `fingerprint_version: 1`, and `entries`. Each entry contains +`fingerprint` (SHA256 of canonical rule/type/data/context), positive occurrence `count`, `rule`, +`type`, structured `data`, and scope `context`. Input validates schema, duplicate fingerprints, +counts, fingerprint/data consistency, size (2 MB), nesting (32) and entry limit (10,000). Paths are +project-relative; regex source/options are data. Line evidence, formatter wording, object identity, +graph counters/cache state and checkout absolute paths are not identity. Actual source policies and +dependency-analysis settings are included, so a different mode/policy cannot silently reuse debt. +Deleted/renamed rules leave stale entries. Counts are matched one-to-one, not set membership. + +Built-in file/external dependencies, patterns, simple directed cycles, layer/slice dependencies, +and numeric metric thresholds have explicit adapters. Metric predicates/zones, custom violations, +empty selectors and unsupported types are never auto-recorded; under an existing baseline they +remain new violations. There is no generic `inspect`/formatted-message fallback. Public Checkable +results are unchanged; this first delivery is CLI-only. + +Schema-1 CLI output adds `baseline` metadata. During check it contains `status: checked`, `path`, +`accepted_count`, `new_count`, `stale_count` and `stale_entries`; every raw violation retains its +original type/message/details and adds `baseline.status` (`accepted` / `new`) and nullable +`baseline.fingerprint`. Per-rule status can be `accepted`. Existing summary violation counts remain +raw counts, not just new debt. Invalid input/IO/analysis exits 2, new/stale debt exits 1. Atomic +creation uses a same-directory hard link (unsupported filesystems fail closed); force replacement +uses rename after rejecting non-regular paths. Concurrent hostile filesystem mutation is outside +this library's isolation guarantees. Do not blindly regenerate baselines in CI. + Invalid API input raises `ArchUnit::UserError` or `ArgumentError`; library or environment failures raise `ArchUnit::TechnicalError`. Rule failures remain violation data. diff --git a/CHANGELOG.md b/CHANGELOG.md index aea5bc4..e24efe8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,9 @@ ## 1.1.0 (unreleased) +- Add explicit CLI accepted-debt baselines with versioned structured fingerprints, one-to-one + occurrence matching, stale-entry failures, strict JSON validation and safe explicit output. + - Expose additive CLI analysis scopes with source/uncertainty counts, truthful warm-cache reuse, unavailable values for unperformed/failed analysis, and explicit static-analysis limitations. diff --git a/README.md b/README.md index 5301209..d0c2b27 100644 --- a/README.md +++ b/README.md @@ -124,6 +124,33 @@ evaluate a target Gemfile/gemspec, install its dependencies, or boot Rails. Invo still has Bundler's normal Gemfile behavior. RSpec/Minitest remain fully supported; the CLI composes the same Checkable rules and is not a replacement for their integrations. +#### Gradual adoption with explicit accepted debt (unreleased 1.1) + +```sh +# Evaluate all rules and explicitly record current supported violations; review this JSON in Git. +bundle exec archunit baseline --output .archunit-baseline.json +bundle exec archunit check --baseline .archunit-baseline.json +``` + +Every rule still runs over the same sources. The baseline accepts specific violations, not whole +files. New violations **and stale entries for fixed/removed violations** fail with exit 1; invalid +baseline/config/source errors exit 2. A fully accepted result exits 0 with status `accepted`, not a +clean `passed` result. Raw violations stay visible, with separate accepted/new/stale counts. +`check` never rewrites debt. Explicitly regenerate with `baseline --output ... --force` only after +reviewing changes; recording debt is not proof that the architecture passes. + +Versioned fingerprints use rule names, structured violation data and analysis scope/settings, not +message prose, line numbers or absolute checkout paths. Line edits/relocation preserve identities; +changed rule names, policies or analysis modes can invalidate them. Duplicate occurrences match +one-for-one. Supported identities: built-in file/external dependencies, naming, simple directed +cycles, layer/slice dependencies and numeric metric thresholds. Empty-selection failures, custom +predicates/violations, metric zones and unknown types cannot be recorded silently. Baselines are +bounded JSON (2 MB / 10,000 entries), not executable configuration; symlinks and directories are +rejected. Creation requires a `.json` output and refuses overwrite unless `--force` is explicit. +Atomic output needs a filesystem supporting same-directory hard links; an unsupported filesystem +fails with exit 2, never falls back to overwriting. This is not a sandbox against concurrent hostile +filesystem changes. Review baseline diffs in CI as carefully as rule changes. + [ClickGems download analytics](https://clickgems.clickhouse.com/dashboard/archunit) show trends by date, gem version, Ruby version, system, and country. Download totals count package fetches rather than unique users, so repeated installs and automated clients may contribute to the total. The diff --git a/lib/archunit/cli/baseline_context.rb b/lib/archunit/cli/baseline_context.rb new file mode 100644 index 0000000..91242d4 --- /dev/null +++ b/lib/archunit/cli/baseline_context.rb @@ -0,0 +1,42 @@ +# frozen_string_literal: true + +require 'pathname' +require 'json' + +module ArchUnit + module CLI + # Scope settings prevent an imports-only acceptance from hiding expanded-analysis findings. + # @api private + module BaselineContext + def self.for(name, analysis, project_root) + scopes = analysis[:scopes].select { |scope| scope[:rule_names].include?(name) } + return if scopes.empty? || scopes.any? { |scope| scope[:status] != 'analyzed' } + + contexts = scopes.map { |scope| settings(scope, project_root) }.uniq + contexts.sort_by { |item| JSON.generate(item) } + end + + def self.settings(scope, root) + { + 'root' => relative(scope[:project_root], root), 'kind' => scope[:kind], + 'dependency_analysis' => scope[:dependency_analysis], + 'rails_imports' => scope[:rails_imports], 'load_paths' => load_paths(scope), + 'source_exclusions' => scope[:effective_source_exclusions] + } + end + + def self.relative(path, root) + Pathname.new(path).relative_path_from(Pathname.new(root).realpath).to_s.tr('\\', '/') + end + + def self.load_path(path, root) + Pathname.new(path).absolute? ? relative(path, root) : path + end + + def self.load_paths(scope) + scope[:load_paths]&.map { |path| load_path(path, scope[:project_root]) }&.sort + end + private_class_method :settings, :relative, :load_path, :load_paths + end + end +end diff --git a/lib/archunit/cli/baseline_document.rb b/lib/archunit/cli/baseline_document.rb new file mode 100644 index 0000000..cda9ea6 --- /dev/null +++ b/lib/archunit/cli/baseline_document.rb @@ -0,0 +1,58 @@ +# frozen_string_literal: true + +require 'json' +require 'tempfile' +require_relative 'baseline_schema' +require_relative 'baseline_object' + +module ArchUnit + module CLI + # Strict, bounded JSON input and explicit, atomic accepted-debt output. + # @api private + module BaselineDocument + MAX_BYTES = 2_000_000 + private_constant :MAX_BYTES + + def self.load(path) + validate_regular_file(path) + bytes = File.open(path, 'rb') { |file| file.read(MAX_BYTES + 1) } + raise ArgumentError, 'baseline exceeds 2 MB' if bytes.bytesize > MAX_BYTES + + document = JSON.parse(bytes, max_nesting: 32, object_class: BaselineObject) + BaselineSchema.validate(document) + rescue JSON::ParserError => e + raise ArgumentError, "invalid baseline JSON: #{e.message}" + end + + def self.write(path, entries, force: false) + document = { 'schema_version' => 1, 'fingerprint_version' => 1, 'entries' => entries } + json = "#{JSON.pretty_generate(document)}\n" + BaselineSchema.validate(JSON.parse(json)) + raise ArgumentError, 'baseline exceeds 2 MB' if json.bytesize > MAX_BYTES + + atomic_write(path, json, force:) + end + + def self.atomic_write(path, json, force:) + Tempfile.create(['.archunit-baseline-', '.json'], File.dirname(path)) do |file| + file.write(json) + file.close + force ? replace(file.path, path) : File.link(file.path, path) + end + end + + def self.replace(temporary, path) + validate_regular_file(path) if File.exist?(path) || File.symlink?(path) + File.rename(temporary, path) + end + + def self.validate_regular_file(path) + stat = File.lstat(path) + return if stat.file? && !stat.symlink? + + raise ArgumentError, 'baseline must be a regular file, not a symlink or directory' + end + private_class_method :atomic_write, :replace, :validate_regular_file + end + end +end diff --git a/lib/archunit/cli/baseline_fingerprint.rb b/lib/archunit/cli/baseline_fingerprint.rb new file mode 100644 index 0000000..205ceaa --- /dev/null +++ b/lib/archunit/cli/baseline_fingerprint.rb @@ -0,0 +1,36 @@ +# frozen_string_literal: true + +require 'digest' +require 'json' +require_relative 'baseline_identity' +require_relative 'baseline_context' + +module ArchUnit + module CLI + # Version-one fingerprints are structured data, not formatter prose or source locations. + # @api private + module BaselineFingerprint + def self.entry(name, violation, context) + data = BaselineIdentity.for(violation) + return unless data && context + + entry = { 'rule' => name, 'type' => violation.class.name, 'data' => data, + 'context' => context } + entry.merge('fingerprint' => digest(entry), 'count' => 1) + end + + def self.digest(entry) + identity = entry.except('fingerprint', 'count') + Digest::SHA256.hexdigest(JSON.generate(canonical(identity))) + end + + def self.canonical(value) + case value + when Hash then value.keys.sort.to_h { |key| [key, canonical(value.fetch(key))] } + when Array then value.map { |item| canonical(item) } + else value + end + end + end + end +end diff --git a/lib/archunit/cli/baseline_identity.rb b/lib/archunit/cli/baseline_identity.rb new file mode 100644 index 0000000..37f1b7c --- /dev/null +++ b/lib/archunit/cli/baseline_identity.rb @@ -0,0 +1,85 @@ +# frozen_string_literal: true + +require_relative '../testing/violation_factory' +require 'json' + +module ArchUnit + module CLI + # Explicit adapters: unknown/custom/empty-selection failures are never accepted implicitly. + # @api private + module BaselineIdentity + TYPES = { + Files::Assertion::FileDependencyViolation => :dependency, + Files::Assertion::ExternalModuleDependencyViolation => :dependency, + Files::Assertion::FilePatternViolation => :pattern, + Files::Assertion::CycleViolation => :cycle, + Layers::Assertion::LayerDependencyViolation => :layer, + Slices::Assertion::SliceDependencyViolation => :slice, + Metrics::Assertion::MetricThresholdViolation => :threshold + }.freeze + private_constant :TYPES + + def self.for(violation) + adapter = TYPES[violation.class] + send(adapter, violation) if adapter + end + + def self.dependency(value) + { 'edge' => edge(value.dependency), 'negated' => value.negated? } + end + + def self.edge(value) + pairs = value.cumulated_edges.map do |raw| + [identifier(raw.source), identifier(raw.target), raw.external] + end + [identifier(value.source_label), identifier(value.target_label), pairs.uniq.sort] + end + + def self.layer(value) + { 'edge' => edge(value.dependency), 'source_layer' => value.source_layer, + 'target_layer' => value.target_layer, 'predicate' => value.rule.to_s } + end + + def self.slice(value) + dependency(value).merge('source_slice' => value.source_slice, + 'target_slice' => value.target_slice, + 'predicate' => value.rule.to_s) + end + + def self.pattern(value) + { 'file' => identifier(value.projected_node.label), 'filter' => filter(value.check_filter), + 'negated' => value.negated? } + 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) }] + end + + def self.cycle(value) + edges = value.cycle.map { |item| edge(item) } + return unless edges.map(&:first).uniq.length == edges.length + + start = edges.each_index.min_by { |index| JSON.generate(edges[index]) } + { 'cycle' => edges.rotate(start) } + end + + def self.threshold(value) + { 'subject' => identifier(value.identifier), 'metric' => value.metric_name.to_s, + 'value' => value.value, 'threshold' => value.threshold, + 'comparison' => value.comparison.to_s } + end + + def self.identifier(value) + normalized = value.tr('\\', '/') + if normalized.start_with?('/') || normalized.match?(/\A[a-z]:/i) + raise ArgumentError, 'baseline identities require project-relative identifiers' + end + + normalized + end + private_class_method :dependency, :edge, :layer, :slice, :pattern, :filter, :cycle, + :threshold, :identifier + end + end +end diff --git a/lib/archunit/cli/baseline_ledger.rb b/lib/archunit/cli/baseline_ledger.rb new file mode 100644 index 0000000..8d2ba56 --- /dev/null +++ b/lib/archunit/cli/baseline_ledger.rb @@ -0,0 +1,38 @@ +# frozen_string_literal: true + +module ArchUnit + module CLI + # One-to-one matching; duplicate occurrences cannot share one accepted-debt entry. + # @api private + class BaselineLedger + def initialize(entries) + @entries = entries + @remaining = entries.to_h { |entry| [entry['fingerprint'], entry['count']] } + end + + def classify(entry) + id = entry&.fetch('fingerprint') + accepted = id && @remaining.fetch(id, 0).positive? + @remaining[id] -= 1 if accepted + { status: accepted ? 'accepted' : 'new', fingerprint: id } + end + + def stale_entries + @entries.filter_map do |entry| + count = @remaining.fetch(entry['fingerprint']) + entry.merge('count' => count) if count.positive? + end + end + + def self.group(records) + if records.any?(&:nil?) + raise ArgumentError, 'cannot baseline empty, custom/unsupported or unobserved violations' + end + + groups = records.group_by { |entry| entry['fingerprint'] }.values + entries = groups.map { |group| group.first.merge('count' => group.length) } + entries.sort_by { |entry| entry['fingerprint'] } + end + end + end +end diff --git a/lib/archunit/cli/baseline_object.rb b/lib/archunit/cli/baseline_object.rb new file mode 100644 index 0000000..7ce87b4 --- /dev/null +++ b/lib/archunit/cli/baseline_object.rb @@ -0,0 +1,15 @@ +# frozen_string_literal: true + +module ArchUnit + module CLI + # JSON duplicate members are ambiguous configuration, not a last-key-wins policy. + # @api private + class BaselineObject < Hash + def []=(key, value) + raise ArgumentError, "duplicate baseline JSON member: #{key}" if key?(key) + + super + end + end + end +end diff --git a/lib/archunit/cli/baseline_options.rb b/lib/archunit/cli/baseline_options.rb new file mode 100644 index 0000000..3a0b258 --- /dev/null +++ b/lib/archunit/cli/baseline_options.rb @@ -0,0 +1,48 @@ +# frozen_string_literal: true + +module ArchUnit + module CLI + # Separate parsing keeps accepted-debt writes explicit and check commands read-only. + # @api private + module BaselineOptions + attr_reader :baseline_path, :output_path + + def force + @force || false + end + + private + + def baseline_options(options) + options.on('--baseline FILE', 'Check accepted debt (check only)') do |value| + @baseline_path = File.expand_path(value, @cwd) + end + options.on('--output FILE', 'Write accepted debt (baseline command only)') do |value| + @output_path = File.expand_path(value, @cwd) + end + options.on('--force', 'Replace existing regular baseline output') { @force = true } + end + + def validate_baseline_options + return if %w[help version].include?(command) + + if baseline_path && command != 'check' + raise ArgumentError, '--baseline is only valid for check' + end + + return validate_baseline_output if command == 'baseline' + + return unless output_path || force + + raise ArgumentError, '--output and --force are only valid for baseline' + end + + def validate_baseline_output + raise ArgumentError, 'baseline requires --output FILE' unless output_path + return if File.extname(output_path) == '.json' + + raise ArgumentError, 'baseline output must have a .json extension' + end + end + end +end diff --git a/lib/archunit/cli/baseline_run.rb b/lib/archunit/cli/baseline_run.rb new file mode 100644 index 0000000..a81bae4 --- /dev/null +++ b/lib/archunit/cli/baseline_run.rb @@ -0,0 +1,85 @@ +# frozen_string_literal: true + +require_relative 'baseline_document' +require_relative 'baseline_ledger' + +module ArchUnit + module CLI + # Baselines classify evaluated violations; they never skip source or alter Checkable results. + # @api private + class BaselineRun + def initialize(options) + @options = options + end + + def finish(report, evaluations) + return finish_normal(report) unless @options.baseline_path || @options.command == 'baseline' + + records = records_for(report, evaluations) + return create(report, records) if @options.command == 'baseline' + + apply(report, records) + end + + private + + def finish_normal(report) + failed = report.payload[:rules].any? { |rule| rule[:status] == 'failed' } + report.finish(failed ? 'failed' : 'passed') + failed ? 1 : 0 + end + + def records_for(report, evaluations) + evaluations.flat_map do |name, violations| + context = BaselineContext.for(name, report.payload[:analysis], @options.project_root) + violations.map { |violation| BaselineFingerprint.entry(name, violation, context) } + end + end + + def create(report, records) + entries = BaselineLedger.group(records) + BaselineDocument.write(@options.output_path, entries, force: @options.force) + report.payload[:baseline] = { status: 'created', path: @options.output_path, + accepted_count: records.length, entries: entries.length } + report.finish('baseline_created') + 0 + end + + def apply(report, records) + ledger = BaselineLedger.new(BaselineDocument.load(@options.baseline_path)) + classify(report, records, ledger) + finish_baseline(report, ledger.stale_entries) + end + + def classify(report, records, ledger) + report.payload[:rules].each do |rule| + rule[:violations].each do |violation| + violation[:baseline] = ledger.classify(records.shift) + end + update_rule_status(rule) unless rule[:violations].empty? + end + end + + def update_rule_status(rule) + accepted = rule[:violations].all? { |value| value[:baseline][:status] == 'accepted' } + rule[:status] = accepted ? 'accepted' : 'failed' + end + + def finish_baseline(report, stale) + summary = baseline_summary(report, stale) + report.payload[:baseline] = summary.merge(status: 'checked', path: @options.baseline_path) + failed = summary[:new_count].positive? || summary[:stale_count].positive? + clean_status = summary[:accepted_count].positive? ? 'accepted' : 'passed' + report.finish(failed ? 'failed' : clean_status) + failed ? 1 : 0 + end + + def baseline_summary(report, stale) + violations = report.payload[:rules].flat_map { |rule| rule[:violations] } + accepted = violations.count { |v| v[:baseline][:status] == 'accepted' } + { accepted_count: accepted, new_count: violations.length - accepted, + stale_count: stale.sum { |entry| entry['count'] }, stale_entries: stale } + end + end + end +end diff --git a/lib/archunit/cli/baseline_schema.rb b/lib/archunit/cli/baseline_schema.rb new file mode 100644 index 0000000..06f88c1 --- /dev/null +++ b/lib/archunit/cli/baseline_schema.rb @@ -0,0 +1,53 @@ +# frozen_string_literal: true + +require_relative 'baseline_fingerprint' + +module ArchUnit + module CLI + # Pure format validation, including identity/data consistency (not authentication). + # @api private + module BaselineSchema + HEADER = %w[entries fingerprint_version schema_version].freeze + ENTRY = %w[context count data fingerprint rule type].freeze + private_constant :HEADER, :ENTRY + + def self.validate(document) + unless valid_header?(document) + raise ArgumentError, 'invalid baseline schema (expected schema/fingerprint version 1)' + end + + entries = document.fetch('entries').map { |entry| validate_entry(entry) } + ids = entries.map { |entry| entry['fingerprint'] } + raise ArgumentError, 'duplicate baseline fingerprints' unless ids.uniq.length == ids.length + + entries + end + + def self.valid_header?(document) + document.is_a?(Hash) && document.keys.sort == HEADER && + document.values_at('schema_version', 'fingerprint_version').all? { |v| v.eql?(1) } && + document['entries'].is_a?(Array) && document['entries'].length <= 10_000 + end + + def self.validate_entry(entry) + unless entry.is_a?(Hash) && entry.keys.sort == ENTRY && valid_identity?(entry) && + valid_count?(entry['count']) && + entry['fingerprint'] == BaselineFingerprint.digest(entry) + raise ArgumentError, 'invalid baseline entry or fingerprint' + end + + entry + end + + def self.valid_count?(value) + value.is_a?(Integer) && value.between?(1, 1_000_000) + end + + def self.valid_identity?(entry) + %w[rule type].all? { |key| entry[key].is_a?(String) && !entry[key].empty? } && + entry['data'].is_a?(Hash) && entry['context'].is_a?(Array) && !entry['context'].empty? + end + private_class_method :valid_header?, :validate_entry, :valid_count?, :valid_identity? + end + end +end diff --git a/lib/archunit/cli/baseline_text.rb b/lib/archunit/cli/baseline_text.rb new file mode 100644 index 0000000..4964e29 --- /dev/null +++ b/lib/archunit/cli/baseline_text.rb @@ -0,0 +1,31 @@ +# frozen_string_literal: true + +module ArchUnit + module CLI + # Accepted debt remains visible, including stale entries after an architectural improvement. + # @api private + module BaselineText + def self.write(baseline, out) + return unless baseline + + return created(baseline, out) if baseline[:status] == 'created' + + checked(baseline, out) + end + + def self.created(baseline, out) + out.puts("Baseline created: #{baseline[:path]} (#{baseline[:accepted_count]} violations).") + out.puts('Review accepted debt before committing; this is not a clean architecture result.') + end + + def self.checked(baseline, out) + out.puts("Baseline: #{baseline[:accepted_count]} accepted, #{baseline[:new_count]} new, " \ + "#{baseline[:stale_count]} stale. #{baseline[:path]}") + baseline[:stale_entries].each do |entry| + out.puts(" Stale: #{entry['rule']} — #{entry['type']} (#{entry['count']})") + end + end + private_class_method :created, :checked + end + end +end diff --git a/lib/archunit/cli/options.rb b/lib/archunit/cli/options.rb index 2ccd9e5..3bd9a8d 100644 --- a/lib/archunit/cli/options.rb +++ b/lib/archunit/cli/options.rb @@ -2,12 +2,15 @@ require 'optparse' require_relative '../common/extraction/source_exclusions' +require_relative 'baseline_options' module ArchUnit module CLI # Internal command parsing; does not discover or execute project code. # @api private class Options + include BaselineOptions + attr_reader :command, :project_root, :config_path, :format, :dependency_analysis, :parser, :rails_imports, :load_paths, :source_exclusions @@ -42,10 +45,11 @@ def parse! private def validate_arguments + validate_baseline_options unless @arguments.empty? raise OptionParser::InvalidArgument, "unexpected arguments: #{@arguments.join(' ')}" end - return if %w[init check explain help version].include?(command) + return if %w[init check explain baseline help version].include?(command) raise OptionParser::InvalidArgument, "unknown command: #{command}" end @@ -57,10 +61,11 @@ def json_requested? def build_parser OptionParser.new do |options| - options.banner = 'Usage: archunit [init|check|explain] [options]' + options.banner = 'Usage: archunit [init|check|explain|baseline] [options]' project_options(options) load_path_option(options) source_exclusion_option(options) + baseline_options(options) output_options(options) end end diff --git a/lib/archunit/cli/report.rb b/lib/archunit/cli/report.rb index 900f02d..cfafbd5 100644 --- a/lib/archunit/cli/report.rb +++ b/lib/archunit/cli/report.rb @@ -6,6 +6,7 @@ require_relative '../error/source_parse_error' require_relative 'analysis_report' require_relative 'analysis_text' +require_relative 'baseline_text' module ArchUnit module CLI @@ -89,6 +90,7 @@ def write_text(out) write_notice(out) payload[:rules].each { |rule| write_rule(rule, out) } AnalysisText.write(payload[:analysis], out) + BaselineText.write(payload[:baseline], out) end def write_header(out) diff --git a/lib/archunit/cli/runner.rb b/lib/archunit/cli/runner.rb index 5416696..3b9b6c0 100644 --- a/lib/archunit/cli/runner.rb +++ b/lib/archunit/cli/runner.rb @@ -4,6 +4,7 @@ require_relative 'configuration' require_relative 'report' require_relative '../extraction/analysis_observer' +require_relative 'baseline_run' module ArchUnit module CLI @@ -83,13 +84,12 @@ def check(rules) source_exclusions: @options.source_exclusions ) check_rules(rules, options) - failed = @report.payload[:rules].any? { |rule| rule[:status] == 'failed' } - @report.finish(failed ? 'failed' : 'passed') - failed ? 1 : 0 + BaselineRun.new(@options).finish(@report, @evaluations) end def check_rules(rules, options) analysis = AnalysisReport.new + @evaluations = [] Extraction::AnalysisObserver.capture(analysis) do rules.each { |rule| check_rule(rule, options, analysis) } end @@ -101,6 +101,7 @@ def check_rule(rule, options, analysis) @current_rule = rule violations = analysis.for_rule(rule.name) { rule.checkable.check(options) } @report.add_rule(rule, violations:, analysis: analysis.for_name(rule.name)) + @evaluations << [rule.name, violations] end end end diff --git a/scripts/check_baselines.rb b/scripts/check_baselines.rb new file mode 100644 index 0000000..de087a7 --- /dev/null +++ b/scripts/check_baselines.rb @@ -0,0 +1,73 @@ +# frozen_string_literal: true + +require 'archunit' +require 'fileutils' +require 'json' +require 'open3' +require 'rbconfig' +require 'tmpdir' + +# Exercise the real executable from the source bundle and the isolated installed gem. +module BaselineSmoke + module_function + + def run + Dir.mktmpdir('archunit-baseline-smoke') do |base| + root, config, baseline = prepare(base) + check(root, config, 'check', expected: 1) + created = check(root, config, 'baseline', '--output', baseline, expected: 0) + abort 'baseline creation pretends to pass' unless created['status'] == 'baseline_created' + verify_accepted(root, config, baseline) + verify_stale_and_error(root, config, baseline) + end + puts 'Explicit baseline creation, accepted/new/stale debt, and parse failures passed.' + end + + def prepare(base) + root = File.join(base, 'project') + FileUtils.mkdir_p(root) + File.write(File.join(root, 'Gemfile'), "raise 'do not run target Gemfile'") + File.write(File.join(root, 'api.rb'), "require_relative 'store'\nraise 'do not run target'") + File.write(File.join(root, 'store.rb'), 'class Store; end') + config = File.join(base, 'trusted.rb') + write_config(config) + [root, config, File.join(base, 'debt.json')] + end + + def write_config(path) + File.write(path, <<~RUBY) + rule('boundary') do + project_files.in_path('api.rb').should_not.depend_on_files.in_path('store.rb') + end + RUBY + end + + def verify_accepted(root, config, baseline) + accepted = check(root, config, 'check', '--baseline', baseline, expected: 0) + abort 'accepted debt hidden' unless accepted['status'] == 'accepted' + abort 'raw violation lost' unless accepted.dig('summary', 'violation_count') == 1 + check(root, config, 'baseline', '--output', baseline, expected: 2) + end + + def verify_stale_and_error(root, config, baseline) + File.write(File.join(root, 'api.rb'), '# fixed') + stale = check(root, config, 'check', '--baseline', baseline, expected: 1) + abort 'fixed debt not stale' unless stale.dig('baseline', 'stale_count') == 1 + before = File.binread(baseline) + File.write(File.join(root, 'api.rb'), 'class Broken <') + check(root, config, 'baseline', '--output', baseline, '--force', expected: 2) + abort 'parse failure changed accepted debt' unless File.binread(baseline) == before + end + + def check(root, config, *arguments, expected:) + executable = Gem.bin_path('archunit', 'archunit') + args = [executable, *arguments, '--project', root, '--config', config, '--format', 'json'] + output, errors, status = Open3.capture3(RbConfig.ruby, *args) + unless status.exitstatus == expected && errors.empty? + abort "baseline CLI expected #{expected}, got #{status.exitstatus}: #{output}#{errors}" + end + JSON.parse(output) + end +end + +BaselineSmoke.run diff --git a/spec/ci/workflow_spec.rb b/spec/ci/workflow_spec.rb index 3335e7f..94c736a 100644 --- a/spec/ci/workflow_spec.rb +++ b/spec/ci/workflow_spec.rb @@ -50,6 +50,7 @@ 'ruby scripts/check_rails_imports.rb', 'ruby scripts/check_source_exclusions.rb', 'ruby scripts/check_analysis_diagnostics.rb', + 'ruby scripts/check_baselines.rb', 'ruby scripts/check_cli.rb', 'depend_on_files', 'depend_on_external_modules', "matching('json')", 'adhere_to', 'file.extension', 'ArchUnit::Checkable', @@ -116,6 +117,10 @@ expect(steps).to include(include('run' => command)) end + it 'exercises explicit baselines on every compatibility platform' do + expect(steps).to include(include('run' => 'bundle exec ruby scripts/check_baselines.rb')) + end + it 'keeps the installed-gem smoke program syntactically valid Ruby' do install_step = quality_job.fetch('steps').find do |step| step['name'] == 'Install and load the built gem' diff --git a/spec/cli/baseline_fingerprint_spec.rb b/spec/cli/baseline_fingerprint_spec.rb new file mode 100644 index 0000000..7fec60f --- /dev/null +++ b/spec/cli/baseline_fingerprint_spec.rb @@ -0,0 +1,93 @@ +# frozen_string_literal: true + +require 'archunit/cli' + +RSpec.describe ArchUnit::CLI::BaselineFingerprint do + let(:context) { [{ 'root' => '.', 'dependency_analysis' => 'imports' }] } + + def edge(source = 'app/api.rb', target = 'app/db.rb', external: false) + raw = ArchUnit::Common::Extraction::Edge.new(source:, target:, external:) + ArchUnit::Common::Projection::ProjectedEdge.new(source_label: source, target_label: target, + cumulated_edges: [raw]) + end + + def fingerprint(violation, name: 'boundary') + described_class.entry(name, violation, context).fetch('fingerprint') + end + + it 'explicitly fingerprints dependency, layer, slice, pattern and numeric-threshold data' do + filter = ArchUnit::Common::RegexFactory.filename_matcher('allowed.rb', except: '*.legacy.rb') + node = ArchUnit::Common::Projection::ProjectedNode.new(label: 'app/api.rb') + subject = Data.define(:identifier).new(identifier: 'app/api.rb') + violations = [ + ArchUnit::Files::Assertion::FileDependencyViolation.new(dependency: edge, is_negated: true), + ArchUnit::Files::Assertion::ExternalModuleDependencyViolation.new( + dependency: edge('app/api.rb', 'json', external: true) + ), + ArchUnit::Layers::Assertion::LayerDependencyViolation.new( + dependency: edge, source_layer: 'api', target_layer: 'db', rule: :may_not_depend_on_layers + ), + ArchUnit::Slices::Assertion::SliceDependencyViolation.new( + dependency: edge, source_slice: 'api', target_slice: 'db', rule: :contain_dependency, + is_negated: true + ), + ArchUnit::Files::Assertion::FilePatternViolation.new(check_filter: filter, + projected_node: node), + ArchUnit::Metrics::Assertion::MetricThresholdViolation.new( + subject:, metric_name: :classes, value: 3, threshold: 2, comparison: :below + ) + ] + ids = violations.map { |violation| fingerprint(violation) } + expect(ids.uniq.length).to eq(violations.length) + expect(ids).to all(match(/\A[a-f0-9]{64}\z/)) + end + + it 'canonicalizes directed cycle rotations without reversing the direction' do + edges = [edge('a.rb', 'b.rb'), edge('b.rb', 'c.rb'), edge('c.rb', 'a.rb')] + first = ArchUnit::Files::Assertion::CycleViolation.new(cycle: edges) + rotated = ArchUnit::Files::Assertion::CycleViolation.new(cycle: edges.rotate(1)) + expect(fingerprint(first)).to eq(fingerprint(rotated)) + reversed = [edge('a.rb', 'c.rb'), edge('c.rb', 'b.rb'), edge('b.rb', 'a.rb')] + backwards = ArchUnit::Files::Assertion::CycleViolation.new(cycle: reversed) + expect(fingerprint(first)).not_to eq(fingerprint(backwards)) + repeated = ArchUnit::Files::Assertion::CycleViolation.new(cycle: edges * 2) + expect(described_class.entry('repeated', repeated, context)).to be_nil + end + + it 'ignores edge order and source evidence locations but not changed dependencies or rules' do + first = ArchUnit::Files::Assertion::FileDependencyViolation.new(dependency: edge) + other = ArchUnit::Files::Assertion::FileDependencyViolation.new(dependency: edge('app/api.rb', + 'other.rb')) + expect(fingerprint(first)).not_to eq(fingerprint(other)) + expect(fingerprint(first, name: 'renamed')).not_to eq(fingerprint(first)) + raw = edge.cumulated_edges.first + evidence = ArchUnit::Common::Extraction::DependencyEvidence.new( + source: raw.source, kind: :require, name: 'db', line_number: 100, end_line: 100 + ) + located = raw.with(evidence: [evidence]) + projected = edge.with(cumulated_edges: [located]) + moved = ArchUnit::Files::Assertion::FileDependencyViolation.new(dependency: projected) + expect(fingerprint(moved)).to eq(fingerprint(first)) + end + + it 'rejects empty selections, unrecognized/custom subclasses and unobserved scopes' do + empty = ArchUnit::Common::Assertion::EmptyTestViolation.new(filters: []) + expect(described_class.entry('typo', empty, context)).to be_nil + custom = Class.new(ArchUnit::Files::Assertion::FileDependencyViolation).new(dependency: edge) + expect(described_class.entry('custom', custom, context)).to be_nil + normal = ArchUnit::Files::Assertion::FileDependencyViolation.new(dependency: edge) + expect(described_class.entry('no scope', normal, nil)).to be_nil + absolute = ArchUnit::Files::Assertion::FileDependencyViolation.new( + dependency: edge('C:/outside.rb', 'db.rb') + ) + expect { fingerprint(absolute) }.to raise_error(ArgumentError, /project-relative/) + end + + it 'canonicalizes hash order and leaves caller-owned entries unchanged' do + entry = { 'rule' => 'a', 'data' => { 'b' => 1, 'a' => [2, 3] } } + original = Marshal.load(Marshal.dump(entry)) + reversed = { 'data' => { 'a' => [2, 3], 'b' => 1 }, 'rule' => 'a' } + expect(described_class.digest(entry)).to eq(described_class.digest(reversed)) + expect(entry).to eq(original) + end +end diff --git a/spec/cli/baseline_spec.rb b/spec/cli/baseline_spec.rb new file mode 100644 index 0000000..46e9f74 --- /dev/null +++ b/spec/cli/baseline_spec.rb @@ -0,0 +1,239 @@ +# frozen_string_literal: true + +require 'archunit/cli' +require 'fileutils' +require 'json' +require 'pathname' +require 'stringio' +require 'tmpdir' + +RSpec.describe ArchUnit::CLI, 'accepted-debt baselines' do + around do |example| + Dir.mktmpdir('archunit-baseline') do |base| + @base = Pathname.new(base) + @root = @base.join('project') + @root.join('app/db').mkpath + @root.join('Gemfile').write("raise 'never run target Gemfile'") + @root.join('app/api.rb').write("require_relative 'db/store'\nraise 'never run target source'") + @root.join('app/db/store.rb').write('class Store; end') + @root.join('app/db/other.rb').write('class Other; end') + @config = @base.join('trusted.rb') + @baseline = @base.join('debt.json') + @config.write(<<~RUBY) + rule('API boundary') do + project_files.in_path('app/api.rb').should_not.depend_on_files.in_path('app/db/**') + end + RUBY + example.run + ensure + ArchUnit.clear_graph_cache + end + end + + def invoke(command = 'check', *arguments, root: @root, format: 'json') + output = StringIO.new + errors = StringIO.new + status = described_class.run( + [command, '--project', root.to_s, '--config', @config.to_s, '--format', format, *arguments], + out: output, err: errors, cwd: @base.to_s + ) + [status, format == 'json' ? JSON.parse(output.string) : output.string, errors.string] + end + + def create(*arguments) + invoke('baseline', '--output', @baseline.to_s, *arguments) + end + + def check(*arguments, **keywords) + invoke('check', '--baseline', @baseline.to_s, *arguments, **keywords) + end + + it 'explicitly creates reviewed debt without turning raw violations into a clean result' do + expect(invoke.first).to eq(1) + code, report = create + expect(code).to eq(0) + expect(report[:error]).to be_nil + expect(report['status']).to eq('baseline_created') + expect(report['summary']['violation_count']).to eq(1) + expect(report.dig('rules', 0, 'status')).to eq('failed') + document = JSON.parse(@baseline.read) + expect(document).to include('schema_version' => 1, 'fingerprint_version' => 1) + expect(document['entries'].first).to include('rule' => 'API boundary', 'count' => 1) + expect(document['entries'].first['fingerprint']).to match(/\A[a-f0-9]{64}\z/) + expect(@root.join('.archignore')).not_to exist + expect(invoke.first).to eq(1) + end + + it 'retains accepted violation data and never writes during check' do + create + bytes = @baseline.binread + code, report = check + expect(code).to eq(0) + expect(report['status']).to eq('accepted') + expect(report['summary']).to eq('rule_count' => 1, 'violation_count' => 1) + expect(report['baseline']).to include('accepted_count' => 1, 'new_count' => 0, + 'stale_count' => 0) + violation = report.dig('rules', 0, 'violations', 0) + expect(violation['details']).to include('app/api.rb', 'app/db/store.rb') + expect(violation['baseline']['status']).to eq('accepted') + expect(@baseline.binread).to eq(bytes) + expect(check(format: 'text')[1]).to include('1 accepted, 0 new, 0 stale', + '[accepted] API boundary') + end + + it 'keeps fingerprints stable across relocation and irrelevant source line changes' do + create + @root.join('app/api.rb').write("# new line\n\nrequire_relative 'db/store'") + expect(check.first).to eq(0) + relocated = @base.join('relocated') + FileUtils.cp_r(@root, relocated) + code, report = check(root: relocated) + expect(code).to eq(0) + expect(report['baseline']['accepted_count']).to eq(1) + end + + it 'reports new violations and stale fixed debt separately and fails for either' do + create + @root.join('app/api.rb').write("require_relative 'db/store'\nrequire_relative 'db/other'") + code, report = check + expect(code).to eq(1) + expect(report['baseline']).to include('accepted_count' => 1, 'new_count' => 1, + 'stale_count' => 0) + @root.join('app/api.rb').write('# fixed architecture') + code, report = check + expect(code).to eq(1) + expect(report['baseline']).to include('accepted_count' => 0, 'new_count' => 0, + 'stale_count' => 1) + expect(check(format: 'text')[1]).to include('Stale: API boundary') + end + + it 'does not match renamed rules or changed analysis mode/settings' do + create + code, report = check('--dependency-analysis', 'imports_and_constants') + expect(code).to eq(1) + expect(report['baseline']).to include('new_count' => 1, 'stale_count' => 1) + @config.write(@config.read.sub('API boundary', 'renamed rule')) + expect(check.first).to eq(1) + end + + def repeated_rule(count) + @config.write(<<~RUBY) + rule('repeated') do + base = project_files.in_path('app/api.rb').should_not.depend_on_files.in_path('app/db/**') + Class.new do + include ArchUnit::Checkable + define_method(:perform_check) { |options| base.check(options) * #{count} } + end.new + end + RUBY + end + + it 'consumes duplicate fingerprints one occurrence at a time' do + repeated_rule(2) + expect(create.first).to eq(0) + expect(JSON.parse(@baseline.read)['entries'].first['count']).to eq(2) + repeated_rule(3) + expect(check[1]['baseline']).to include('accepted_count' => 2, 'new_count' => 1) + repeated_rule(1) + expect(check[1]['baseline']).to include('accepted_count' => 1, 'stale_count' => 1) + end + + it 'makes removed rules stale and can explicitly record a healthy empty baseline' do + create + @config.write("rule('healthy') { project_files.should.have_name('*.rb') }") + expect(check.first).to eq(1) + expect(create('--force').first).to eq(0) + expect(JSON.parse(@baseline.read)['entries']).to eq([]) + expect(check.first).to eq(0) + end + + it 'never overwrites existing output without explicit force' do + @baseline.write('original') + expect(create.first).to eq(2) + expect(@baseline.read).to eq('original') + expect(create('--force').first).to eq(0) + expect(check.first).to eq(0) + expect(@base.glob('.archunit-baseline-*')).to eq([]) + end + + ['class Broken <', 'exit 0'].each do |failure| + it "never creates or changes accepted debt after failure: #{failure}" do + create + bytes = @baseline.binread + if failure.start_with?('class') + @root.join('broken.rb').write(failure) + else + @config.write(failure) + end + expect(create('--force').first).to eq(2) + expect(@baseline.binread).to eq(bytes) + expect(check.first).to eq(2) + end + end + + it 'refuses empty selections and unsupported custom violation identities' do + @config.write("rule('empty') { project_files.in_path('missing/**').should.have_no_cycles }") + expect(create.first).to eq(2) + expect(@baseline).not_to exist + custom = "rule('custom') { project_files.should.adhere_to(->(_file) { false }, 'custom') }" + @config.write(custom) + expect(create.first).to eq(2) + expect(@baseline).not_to exist + end + + it 'rejects malformed, tampered, unsupported and missing documents' do + expect(check.first).to eq(2) + invalid_json = ['not json', '[]', '{}', '{"schema_version": 2}', '{"entries": null}', + '{"schema_version":1,"schema_version":2}'] + invalid_json.each do |invalid| + @baseline.write(invalid) + expect(check.first).to eq(2) + end + create('--force') + document = JSON.parse(@baseline.read) + document['entries'].first['rule'] = 'tampered' + @baseline.write(JSON.generate(document)) + expect(check.first).to eq(2) + end + + it 'rejects duplicate entries, oversize files, directories and nonsensical counts' do + create + original = JSON.parse(@baseline.read) + duplicate = Marshal.load(Marshal.dump(original)) + duplicate['entries'] *= 2 + @baseline.write(JSON.generate(duplicate)) + expect(check.first).to eq(2) + [0, -1, 1.5, '1', 1_000_001].each do |count| + original['entries'].first['count'] = count + @baseline.write(JSON.generate(original)) + expect(check.first).to eq(2) + end + @baseline.write(' ' * 2_000_001) + expect(check.first).to eq(2) + expect(invoke('check', '--baseline', @root.to_s).first).to eq(2) + end + + it 'requires explicit write flags only on the baseline command and JSON output names' do + expect(invoke('baseline').first).to eq(2) + expect(invoke('check', '--force').first).to eq(2) + expect(invoke('explain', '--baseline', @baseline.to_s).first).to eq(2) + expect(invoke('baseline', '--output', @config.to_s, '--force').first).to eq(2) + expect(@config.read).to include('API boundary') + end + + it 'rejects symlink inputs and outputs, including dangling outputs on supported platforms' do + create + link = @base.join('link.json') + begin + File.symlink(@baseline, link) + rescue NotImplementedError, SystemCallError + skip 'creating symlinks is not available for this user or platform' + end + expect(invoke('check', '--baseline', link.to_s).first).to eq(2) + expect(invoke('baseline', '--output', link.to_s, '--force').first).to eq(2) + dangling = @base.join('dangling.json') + File.symlink(@base.join('absent.json'), dangling) + expect(invoke('baseline', '--output', dangling.to_s, '--force').first).to eq(2) + expect(@base.join('absent.json')).not_to exist + end +end From afc2338d5b70bd5674fe09c09e5ae8c75e37822b Mon Sep 17 00:00:00 2001 From: TristanKruse Date: Sun, 22 Nov 2026 09:29:59 +0100 Subject: [PATCH 2/4] Compose layered, hexagonal and Rails architecture presets (#90) --- .github/workflows/ci.yml | 4 + API.md | 27 +++ CHANGELOG.md | 3 + README.md | 33 ++++ lib/archunit.rb | 2 + lib/archunit/cli/configuration.rb | 7 + .../layers/fluentapi/architecture_preset.rb | 49 +++++ .../layers/fluentapi/preset_definitions.rb | 39 ++++ .../layers/fluentapi/preset_options.rb | 69 +++++++ lib/archunit/layers/fluentapi/preset_rule.rb | 45 +++++ scripts/check_presets.rb | 70 +++++++ spec/ci/workflow_spec.rb | 5 + spec/common/fluentapi/rule_rationale_spec.rb | 1 + spec/layers/architecture_preset_spec.rb | 171 ++++++++++++++++++ 14 files changed, 525 insertions(+) create mode 100644 lib/archunit/layers/fluentapi/architecture_preset.rb create mode 100644 lib/archunit/layers/fluentapi/preset_definitions.rb create mode 100644 lib/archunit/layers/fluentapi/preset_options.rb create mode 100644 lib/archunit/layers/fluentapi/preset_rule.rb create mode 100644 scripts/check_presets.rb create mode 100644 spec/layers/architecture_preset_spec.rb diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 54e61ab..f14d5ad 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -68,6 +68,9 @@ jobs: - name: Exercise explicit accepted-debt baselines run: bundle exec ruby scripts/check_baselines.rb + - name: Exercise architecture presets + run: bundle exec ruby scripts/check_presets.rb + quality: name: Quality and package — Ruby 4.0 on Ubuntu runs-on: ubuntu-latest @@ -168,6 +171,7 @@ jobs: ruby scripts/check_source_exclusions.rb ruby scripts/check_analysis_diagnostics.rb ruby scripts/check_baselines.rb + ruby scripts/check_presets.rb ruby scripts/check_cli.rb ruby -e " require 'json' diff --git a/API.md b/API.md index 14e2fb1..2b4690f 100644 --- a/API.md +++ b/API.md @@ -299,6 +299,33 @@ the same file pair merge into one edge. Import-only edge evidence stays empty fo `ArchUnit::Extraction.extract_imports` retains import call locations in both modes. The analysis mode participates in graph-cache identity, and `clear_cache: true` rebuilds the symbol index. +## Architecture presets (unreleased 1.1) + +`ArchUnit.architecture_preset(name, options = nil)` returns an immutable Checkable `PresetRule`. +`ArchUnit::PresetOptions.new(project_locator: nil, folders: {})` is its options bag. Names are +`:layered`, `:hexagonal`, or `:rails`; unknown names and malformed/duplicate override layer keys fail +at construction. Each folder override is a non-empty String or Array of source globs; multiple +patterns are ORed within one layer. No project reads occur until check. + +Layered maps presentation/application/persistence to `app/api/**`, `app/services/**`, `app/db/**`, +allowing only presentation→application and application→persistence across layers. Hexagonal maps +domain/application/adapters to `app/domain/**`, `app/application/**`, `app/adapters/**`, allowing +application→domain and adapters→application/domain. Rails maps controllers/services/models to +their `app/` folders, allowing controllers→services/models and services→models. Same-layer edges +are allowed; the innermost layer has no allowed outgoing cross-layer edge. All mappings are +overridable. Unmapped files/external modules are outside this policy, not excluded from extraction. + +Presets construct `LayeredArchitecture` rules and use existing assertion code. The guard rejects +observed files matching multiple layers with UserError; empty layers use the normal +EmptyTestViolation defense unless explicitly permitted. CheckOptions controls analysis, exclusions, +cache and logging as usual; source parse errors remain fatal. `.because` and framework matchers +work normally. Rails conventions do not boot Rails or automatically turn on expanded/helper modes. +These presets are not complete architecture/cycle/protocol verification; compose more rules or +build arbitrary policies with `project_layers`. + +Trusted CLI configurations have `architecture_preset(name, options = nil)`, defaulting the locator +to their selected project root. This preserves the public locator/auto-discovery distinction. + ## CLI contract (unreleased 1.1 milestone) The new executable is development-only until a 1.1 release; it is not included in 1.0.0. It wraps diff --git a/CHANGELOG.md b/CHANGELOG.md index e24efe8..c200888 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,9 @@ ## 1.1.0 (unreleased) +- Compose layered, hexagonal and Rails folder presets from existing layer rules, with immutable + pattern overrides, CLI integration, overlap errors and unchanged empty/source-analysis defenses. + - Add explicit CLI accepted-debt baselines with versioned structured fingerprints, one-to-one occurrence matching, stale-entry failures, strict JSON validation and safe explicit output. diff --git a/README.md b/README.md index d0c2b27..dd48d6f 100644 --- a/README.md +++ b/README.md @@ -194,6 +194,39 @@ is required: run: bundle exec rspec spec/architecture_spec.rb ~~~ +## Reusable architecture presets (unreleased 1.1) + +Presets compose the existing named-layer rules, preserving CheckOptions, empty-selection failures, +RSpec/Minitest, CLI, and static-analysis limitations. Construction is lazy; no Rails app is booted. + +~~~ruby +rule = ArchUnit.architecture_preset( + :hexagonal, + ArchUnit::PresetOptions.new(project_locator: '.', folders: { domain: 'lib/domain/**' }) +).because('Keep the domain independent of infrastructure') +expect(rule).to pass +~~~ + +| Preset | Default layers / source patterns | Allowed cross-layer directions | +| --- | --- | --- | +| `:layered` | presentation `app/api/**`; application `app/services/**`; persistence `app/db/**` | presentation → application → persistence; no skipping | +| `:hexagonal` | domain `app/domain/**`; application `app/application/**`; adapters `app/adapters/**` | application → domain; adapters → application/domain | +| `:rails` | controllers `app/controllers/**`; services `app/services/**`; models `app/models/**` | controllers → services/models; services → models | + +Dependencies within a layer are allowed; the innermost layer may not depend on another mapped layer. +Unmapped files and external modules are not constrained by this folder policy; source discovery is +not narrowed. Add file/layer/cycle rules for additional boundaries. Missing policy layers fail by +default; override patterns or consciously use `CheckOptions.new(allow_empty_tests: true)` if intended. +Overlapping observed membership raises UserError instead of choosing a layer silently. All source +patterns can be overridden with `PresetOptions.folders` (String or Array of source globs per layer). +Unknown/duplicate keys and empty patterns are errors. For arbitrary policies use `project_layers`. +The Rails preset is opinionated and expects a services layer; it is not full Rails/DDD verification +and does not automatically enable `rails_imports` or constant analysis. + +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. + ## 🎬 Demo https://github.com/user-attachments/assets/9b7305a0-deee-454d-b99e-f8fac63d06ab diff --git a/lib/archunit.rb b/lib/archunit.rb index 2a01f2b..3d7bffb 100644 --- a/lib/archunit.rb +++ b/lib/archunit.rb @@ -36,6 +36,7 @@ require_relative 'archunit/extraction/extract_graph' require_relative 'archunit/files/fluentapi/files' require_relative 'archunit/layers/fluentapi/layers' +require_relative 'archunit/layers/fluentapi/architecture_preset' require_relative 'archunit/slices/fluentapi/slices' require_relative 'archunit/graph/fluentapi/graph' require_relative 'archunit/metrics/fluentapi/metrics' @@ -68,6 +69,7 @@ module ArchUnit CustomFileViolation = Files::Assertion::CustomFileViolation LayerDefinition = Layers::Assertion::LayerDefinition LayerDependencyViolation = Layers::Assertion::LayerDependencyViolation + PresetOptions = Layers::FluentApi::PresetOptions SliceProjection = Slices::Projection::SliceProjection SliceProjections = Slices::Projection SliceDependencyViolation = Slices::Assertion::SliceDependencyViolation diff --git a/lib/archunit/cli/configuration.rb b/lib/archunit/cli/configuration.rb index fb1d9c0..99b6a1c 100644 --- a/lib/archunit/cli/configuration.rb +++ b/lib/archunit/cli/configuration.rb @@ -3,6 +3,7 @@ require_relative '../common/fluentapi/checkable' require_relative '../files/fluentapi/files' require_relative '../layers/fluentapi/layers' +require_relative '../layers/fluentapi/architecture_preset' require_relative '../slices/fluentapi/slices' require_relative '../metrics/fluentapi/metrics' @@ -53,6 +54,12 @@ def project_layers end alias layers project_layers + def architecture_preset(name, options = nil) + options = Layers::FluentApi::PresetOptions.resolve(options) + options = options.with(project_locator: options.project_locator || @project_root) + Layers::FluentApi::ArchitecturePreset.build(name, options) + end + def project_slices Slices::FluentApi.project_slices(@project_root) end diff --git a/lib/archunit/layers/fluentapi/architecture_preset.rb b/lib/archunit/layers/fluentapi/architecture_preset.rb new file mode 100644 index 0000000..97104f7 --- /dev/null +++ b/lib/archunit/layers/fluentapi/architecture_preset.rb @@ -0,0 +1,49 @@ +# frozen_string_literal: true + +require_relative 'preset_options' +require_relative 'preset_definitions' +require_relative 'preset_rule' + +# Public preset entry point composed from the existing named-layer vocabulary. +module ArchUnit + module Layers + module FluentApi + # Composes named-layer builders, so presets share all existing extraction/assertion semantics. + # @api private + module ArchitecturePreset + def self.build(name, options = nil) + options = PresetOptions.resolve(options) + folders = PresetDefinitions.folders(name, options.folders) + architecture = define_layers(folders, options.project_locator) + policy = apply_policy(architecture, name) + PresetRule.new(name:, architecture: policy) + end + + def self.apply_policy(architecture, name) + dependencies = PresetDefinitions::ALLOWED.fetch(name) + dependencies.reduce(architecture) do |rule, (source, targets)| + rule.where_layer(source).may_only_depend_on_layers(*targets) + end + end + + def self.define_layers(folders, locator) + architecture = LayeredArchitecture.new(project_locator: locator) + folders.reduce(architecture) do |rule, (name, patterns)| + Array(patterns).reduce(rule) do |current, pattern| + current.layer(name).defined_by(pattern) + end + end + end + private_class_method :define_layers, :apply_policy + end + end + end + + # Starts a completed layered, hexagonal, or Rails folder policy. + # @param name [Symbol] :layered, :hexagonal or :rails + # @param options [Layers::FluentApi::PresetOptions, nil] source locator/pattern overrides + # @return [Layers::FluentApi::PresetRule] lazy, immutable Checkable + def self.architecture_preset(name, options = nil) + Layers::FluentApi::ArchitecturePreset.build(name, options) + end +end diff --git a/lib/archunit/layers/fluentapi/preset_definitions.rb b/lib/archunit/layers/fluentapi/preset_definitions.rb new file mode 100644 index 0000000..2d6fa42 --- /dev/null +++ b/lib/archunit/layers/fluentapi/preset_definitions.rb @@ -0,0 +1,39 @@ +# frozen_string_literal: true + +module ArchUnit + module Layers + module FluentApi + # Small opinionated policies, not a claim to recognize an application's architecture. + # @api private + module PresetDefinitions + FOLDERS = { + layered: { 'presentation' => 'app/api/**', 'application' => 'app/services/**', + 'persistence' => 'app/db/**' }.freeze, + hexagonal: { 'domain' => 'app/domain/**', 'application' => 'app/application/**', + 'adapters' => 'app/adapters/**' }.freeze, + rails: { 'controllers' => 'app/controllers/**', 'services' => 'app/services/**', + 'models' => 'app/models/**' }.freeze + }.freeze + ALLOWED = { + layered: { 'presentation' => %w[application].freeze, + 'application' => %w[persistence].freeze, 'persistence' => [].freeze }.freeze, + hexagonal: { 'domain' => [].freeze, 'application' => %w[domain].freeze, + 'adapters' => %w[application domain].freeze }.freeze, + rails: { 'controllers' => %w[services models].freeze, 'services' => %w[models].freeze, + 'models' => [].freeze }.freeze + }.freeze + + def self.folders(name, overrides) + defaults = FOLDERS.fetch(name) do + raise ArgumentError, "unknown architecture preset: #{name}" + end + unknown = overrides.keys - defaults.keys + raise ArgumentError, "unknown preset layers: #{unknown.join(', ')}" unless unknown.empty? + + defaults.merge(overrides) + end + end + private_constant :PresetDefinitions + end + end +end diff --git a/lib/archunit/layers/fluentapi/preset_options.rb b/lib/archunit/layers/fluentapi/preset_options.rb new file mode 100644 index 0000000..55449d7 --- /dev/null +++ b/lib/archunit/layers/fluentapi/preset_options.rb @@ -0,0 +1,69 @@ +# frozen_string_literal: true + +module ArchUnit + module Layers + module FluentApi + # Immutable source-pattern overrides for an architecture preset; no I/O during construction. + PresetOptions = Data.define(:project_locator, :folders) do + def initialize(project_locator: nil, folders: {}) + project_locator = immutable_locator(project_locator) + folders = immutable_folders(folders) + super + end + + def self.resolve(value) + return new if value.nil? + return value if value.is_a?(self) + + raise ArgumentError, 'options must be a PresetOptions value or nil' + end + + private + + def immutable_locator(value) + return if value.nil? + + value = value.to_path if value.respond_to?(:to_path) + return value.dup.freeze if value.is_a?(String) && !value.empty? + + raise ArgumentError, 'project_locator must be a non-empty path or nil' + end + + def immutable_folders(value) + unless value.is_a?(Hash) + raise ArgumentError, + 'folders must map layer names to source globs' + end + + entries = value.map { |name, patterns| folder_entry(name, patterns) } + if entries.map(&:first).uniq.length != entries.length + raise ArgumentError, 'duplicate normalized preset layer names' + end + + entries.to_h.freeze + end + + def folder_entry(name, patterns) + unless name.is_a?(Symbol) || (name.is_a?(String) && !name.empty?) + raise ArgumentError, 'preset layer names must be Symbols or non-empty Strings' + end + + [name.to_s.dup.freeze, immutable_patterns(patterns)] + end + + def immutable_patterns(value) + patterns = value.is_a?(Array) ? value : [value] + unless !patterns.empty? && patterns.all? { |item| valid_pattern?(item) } + raise ArgumentError, 'preset folders must contain non-empty source globs' + end + + patterns.map { |pattern| pattern.tr('\\', '/').freeze }.uniq.freeze + end + + def valid_pattern?(value) + value.is_a?(String) && !value.strip.empty? + end + end + end + end +end diff --git a/lib/archunit/layers/fluentapi/preset_rule.rb b/lib/archunit/layers/fluentapi/preset_rule.rb new file mode 100644 index 0000000..510933b --- /dev/null +++ b/lib/archunit/layers/fluentapi/preset_rule.rb @@ -0,0 +1,45 @@ +# frozen_string_literal: true + +require_relative 'layered_architecture' +require_relative '../../error/user_error' + +module ArchUnit + module Layers + module FluentApi + # Completed preset: existing layer assertions plus an explicit ambiguity guard. + class PresetRule + include Common::FluentApi::Checkable + + attr_reader :name, :architecture + + def initialize(name:, architecture:) + unless name.is_a?(Symbol) && architecture.is_a?(LayeredArchitecture) + raise ArgumentError, 'preset requires a Symbol name and LayeredArchitecture' + end + + @name = name + @architecture = architecture + freeze + end + + private + + def perform_check(options) + graph = ArchUnit::Extraction.extract_graph(architecture.project_locator, options:) + graph.each do |edge| + validate_membership(edge.source) if edge.source == edge.target && !edge.external + 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 + + names = matches.map(&:name).join(', ') + raise UserError, "preset file '#{path}' matches multiple layers: #{names}" + end + end + end + end +end diff --git a/scripts/check_presets.rb b/scripts/check_presets.rb new file mode 100644 index 0000000..129dd8c --- /dev/null +++ b/scripts/check_presets.rb @@ -0,0 +1,70 @@ +# frozen_string_literal: true + +require 'archunit' +require 'archunit/cli' +require 'fileutils' +require 'json' +require 'stringio' +require 'tmpdir' + +# Shared acceptance for the source bundle and the isolated installed gem. +module PresetSmoke + module_function + + def run + Dir.mktmpdir('archunit-preset-smoke') do |base| + %i[layered hexagonal rails].each { |name| verify(base, name) } + end + puts 'Layered, hexagonal and Rails presets passed allowed/forbidden controls in both modes.' + end + + def verify(base, name) + root, folders = fixture(base, name) + rule = ArchUnit.architecture_preset(name, ArchUnit::PresetOptions.new(project_locator: root)) + verify_allowed(rule) + verify_cli(base, root, name) + target = File.basename(folders.first) + File.write(File.join(root, folders.last, 'unit.rb'), "require_relative '../#{target}/unit'") + verify_forbidden(rule) + ensure + ArchUnit.clear_graph_cache + end + + def verify_allowed(rule) + %i[imports imports_and_constants].each do |mode| + options = ArchUnit::CheckOptions.new(dependency_analysis: mode, clear_cache: true) + abort 'preset rejected allowed direction' unless rule.check(options).empty? + end + end + + def fixture(base, name) + folders = { layered: %w[api services db], hexagonal: %w[adapters application domain], + rails: %w[controllers services models] }.fetch(name) + root = File.join(base, name.to_s) + folders.each { |folder| FileUtils.mkdir_p(File.join(root, 'app', folder)) } + File.write(File.join(root, 'Gemfile'), "raise 'target must not boot'") + folders.each_with_index do |folder, index| + code = index < 2 ? "require_relative '../#{folders[index + 1]}/unit'" : '# core' + File.write(File.join(root, 'app', folder, 'unit.rb'), "#{code}\nraise 'do not run source'") + end + [root, folders.map { |folder| "app/#{folder}" }] + end + + def verify_forbidden(rule) + %i[imports imports_and_constants].each do |mode| + options = ArchUnit::CheckOptions.new(dependency_analysis: mode, clear_cache: true) + abort 'preset missed forbidden direction' unless rule.check(options).length == 1 + end + end + + def verify_cli(base, root, name) + config = File.join(base, "#{name}-trusted.rb") + File.write(config, "rule('preset') { architecture_preset(:#{name}) }") + output = StringIO.new + arguments = ['check', '--project', root, '--config', config, '--format', 'json'] + status = ArchUnit::CLI.run(arguments, out: output, err: StringIO.new) + abort 'CLI preset failed' unless status.zero? && JSON.parse(output.string)['status'] == 'passed' + end +end + +PresetSmoke.run diff --git a/spec/ci/workflow_spec.rb b/spec/ci/workflow_spec.rb index 94c736a..3e2da14 100644 --- a/spec/ci/workflow_spec.rb +++ b/spec/ci/workflow_spec.rb @@ -51,6 +51,7 @@ 'ruby scripts/check_source_exclusions.rb', 'ruby scripts/check_analysis_diagnostics.rb', 'ruby scripts/check_baselines.rb', + 'ruby scripts/check_presets.rb', 'ruby scripts/check_cli.rb', 'depend_on_files', 'depend_on_external_modules', "matching('json')", 'adhere_to', 'file.extension', 'ArchUnit::Checkable', @@ -121,6 +122,10 @@ expect(steps).to include(include('run' => 'bundle exec ruby scripts/check_baselines.rb')) end + it 'exercises architecture presets on every compatibility platform' do + expect(steps).to include(include('run' => 'bundle exec ruby scripts/check_presets.rb')) + end + it 'keeps the installed-gem smoke program syntactically valid Ruby' do install_step = quality_job.fetch('steps').find do |step| step['name'] == 'Install and load the built gem' diff --git a/spec/common/fluentapi/rule_rationale_spec.rb b/spec/common/fluentapi/rule_rationale_spec.rb index d9389a9..6d3828f 100644 --- a/spec/common/fluentapi/rule_rationale_spec.rb +++ b/spec/common/fluentapi/rule_rationale_spec.rb @@ -40,6 +40,7 @@ def all_terminals 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, + ArchUnit.architecture_preset(:layered, ArchUnit::PresetOptions.new(project_locator: @root)), slices.should_not.contain_dependency('api', 'database'), slices.should.adhere_to_diagram(slices.to_plantuml), metrics.count.classes.should_be_above(0), diff --git a/spec/layers/architecture_preset_spec.rb b/spec/layers/architecture_preset_spec.rb new file mode 100644 index 0000000..83410be --- /dev/null +++ b/spec/layers/architecture_preset_spec.rb @@ -0,0 +1,171 @@ +# frozen_string_literal: true + +require 'fileutils' +require 'pathname' +require 'tmpdir' +require 'archunit/cli' + +PRESET_FIXTURES = { + layered: %w[app/api app/services app/db], + hexagonal: %w[app/adapters app/application app/domain], + rails: %w[app/controllers app/services app/models] +}.freeze + +RSpec.describe 'Architecture presets' do + around do |example| + Dir.mktmpdir('archunit-presets') do |directory| + @root = Pathname.new(directory).realpath + @root.join('Gemfile').write("raise 'must not boot target project'") + example.run + ensure + ArchUnit.clear_graph_cache + end + end + + def source(path, text) + file = @root.join(path) + file.dirname.mkpath + file.write(text) + end + + def fixture(folders) + folders.each_with_index do |folder, index| + next_folder = folders[index + 1] + dependency = next_folder ? import(folder, next_folder) : '' + source("#{folder}/unit.rb", "#{dependency}\nraise 'must not execute target source'") + end + end + + def import(from, to) + relative = Pathname.new("#{to}/unit").relative_path_from(Pathname.new(from)) + "require_relative #{relative.to_s.tr('\\', '/').dump}" + end + + PRESET_FIXTURES.each do |name, folders| + %i[imports imports_and_constants].each do |mode| + it "enforces #{name} allowed/forbidden directions in #{mode} without executing source" do + fixture(folders) + rule = ArchUnit.architecture_preset(name, + ArchUnit::PresetOptions.new(project_locator: @root)) + options = ArchUnit::CheckOptions.new(dependency_analysis: mode) + expect(rule).to be_frozen + expect(rule.check(options)).to eq([]) + source("#{folders.last}/unit.rb", import(folders.last, folders.first)) + violations = rule.check(options.with(clear_cache: true)) + expect(violations.length).to eq(1) + expect(violations.first).to be_a(ArchUnit::LayerDependencyViolation) + expect(violations.first.dependency.source_label).to eq("#{folders.last}/unit.rb") + reason = 'keep the core independent' + expect(rule.because(reason).rationale).to eq(reason) + end + end + end + + it 'constructs policies lazily and shares the existing named-layer assertion engine' do + expect(ArchUnit::Extraction).not_to receive(:extract_graph) + rule = ArchUnit.architecture_preset(:hexagonal) + expect(rule).to be_a(ArchUnit::Checkable) + expect(rule.architecture).to be_a(ArchUnit::Layers::FluentApi::LayeredArchitecture) + expect(rule.architecture.allowed_dependencies).to eq( + 'domain' => [], 'application' => ['domain'], 'adapters' => %w[application domain] + ) + end + + it 'defensively copies all override values without freezing caller-owned names or patterns' do + name = +'domain' + pattern = +'src/core/**' + folders = { name => [pattern] } + options = ArchUnit::PresetOptions.new(project_locator: @root, folders:) + pattern.replace('changed/**') + expect(name).not_to be_frozen + expect(options.folders).to eq('domain' => ['src/core/**']) + expect(options.folders).to be_frozen + expect(options.folders['domain']).to be_frozen + expect(options.folders['domain'].first).to be_frozen + rule = ArchUnit.architecture_preset(:hexagonal, options) + default = ArchUnit.architecture_preset(:hexagonal) + expect(rule.architecture.layer_definitions.first.filters) + .not_to eq(default.architecture.layer_definitions.first.filters) + end + + it 'supports multiple patterns per layer and keeps unmapped sources visible' do + folders = { domain: ['core/**', 'shared/**'], application: 'use_cases/**', adapters: 'web/**' } + fixture(%w[web use_cases core]) + source('shared/other.rb', '# another domain source') + source('unmapped.rb', '# not part of this preset policy') + rule = ArchUnit.architecture_preset(:hexagonal, + ArchUnit::PresetOptions.new(project_locator: @root, + folders:)) + expect(rule.check).to eq([]) + graph = ArchUnit::Extraction.extract_graph(@root) + expect(graph.map(&:source)).to include('unmapped.rb') + end + + it 'rejects ambiguous observed layer membership instead of silently taking the first layer' do + fixture(PRESET_FIXTURES[:hexagonal]) + options = ArchUnit::PresetOptions.new(project_locator: @root, folders: { domain: 'app/**' }) + rule = ArchUnit.architecture_preset(:hexagonal, options) + expect { rule.check }.to raise_error(ArchUnit::UserError, /matches multiple layers/) + end + + it 'rebuilds only once when clear_cache is requested and reuses that graph for the layer check' do + fixture(PRESET_FIXTURES[:hexagonal]) + options = ArchUnit::PresetOptions.new(project_locator: @root) + rule = ArchUnit.architecture_preset(:hexagonal, options) + report = ArchUnit::CLI::AnalysisReport.new + ArchUnit::Extraction::AnalysisObserver.capture(report) do + expect(rule.check(ArchUnit::CheckOptions.new(clear_cache: true))).to eq([]) + end + scopes = report.to_h[:scopes] + expect(scopes.length).to eq(1) + expect(scopes.first).to include(observations: 2, cache_hits: 1) + end + + it 'keeps empty-layer and malformed-source defenses and forwards CheckOptions' do + rule = ArchUnit.architecture_preset(:layered, + ArchUnit::PresetOptions.new(project_locator: @root)) + expect(rule.check.length).to eq(3) + expect(rule.check).to all(be_a(ArchUnit::EmptyTestViolation)) + expect(rule.check(ArchUnit::CheckOptions.new(allow_empty_tests: true))).to eq([]) + source('lib/broken.rb', 'class Broken <') + expect { rule.check(ArchUnit::CheckOptions.new(clear_cache: true)) } + .to raise_error(ArchUnit::SourceParseError) + expect(rule.check(ArchUnit::CheckOptions.new(source_exclusions: ['lib/broken.rb'], + allow_empty_tests: true))).to eq([]) + end + + it 'integrates with trusted CLI configuration using its selected project root' do + fixture(PRESET_FIXTURES[:rails]) + config = @root.dirname.join("#{@root.basename}-trusted.rb") + begin + config.write("rule('Rails layers') { architecture_preset(:rails) }") + configuration = ArchUnit::CLI::Configuration.new(@root.to_s) + rule = configuration.load(config.to_s).first.checkable + expect(rule.architecture.project_locator).to eq(@root.to_s) + expect(rule.check).to eq([]) + ensure + File.unlink(config) if config.exist? + end + end + + it 'rejects unknown presets, duplicate names and malformed overrides' do + expect { ArchUnit.architecture_preset(:unknown) }.to raise_error(ArgumentError, /unknown/) + options = ArchUnit::PresetOptions.new(folders: { typo: '**' }) + expect do + ArchUnit.architecture_preset(:rails, options) + end.to raise_error(ArgumentError, /unknown/) + expect do + ArchUnit.architecture_preset(:rails, {}) + end.to raise_error(ArgumentError, /PresetOptions/) + expect { ArchUnit::PresetOptions.new(folders: { domain: 'x', 'domain' => 'y' }) } + .to raise_error(ArgumentError, /duplicate/) + [nil, [], { nil => 'app/**' }, { domain: [] }, { domain: [''] }, + { domain: [42] }].each do |value| + expect { ArchUnit::PresetOptions.new(folders: value) }.to raise_error(ArgumentError) + end + expect { ArchUnit::PresetOptions.new(project_locator: 123) }.to raise_error(ArgumentError) + expect do + ArchUnit::Layers::FluentApi::PresetRule.new(name: 'rails', architecture: nil) + end.to raise_error(ArgumentError) + end +end From b6b1858147fde293fc23567a72e6719111e0581c Mon Sep 17 00:00:00 2001 From: TristanKruse Date: Sun, 22 Nov 2026 09:38:33 +0100 Subject: [PATCH 3/4] Evaluate bounded semantic rule and selector support (#91) --- API.md | 6 + benchmark/semantic/cases.json | 90 ++++ benchmark/semantic/comparator.rb | 51 ++ benchmark/semantic/evidence-windows.json | 598 +++++++++++++++++++++++ benchmark/semantic/probes.rb | 95 ++++ benchmark/semantic/syntax_facts.rb | 33 ++ design/semantic-boundaries.md | 106 ++++ spec/benchmark/semantic_probes_spec.rb | 22 + 8 files changed, 1001 insertions(+) create mode 100644 benchmark/semantic/cases.json create mode 100644 benchmark/semantic/comparator.rb create mode 100644 benchmark/semantic/evidence-windows.json create mode 100644 benchmark/semantic/probes.rb create mode 100644 benchmark/semantic/syntax_facts.rb create mode 100644 design/semantic-boundaries.md create mode 100644 spec/benchmark/semantic_probes_spec.rb diff --git a/API.md b/API.md index 2b4690f..da84097 100644 --- a/API.md +++ b/API.md @@ -301,6 +301,12 @@ mode participates in graph-cache identity, and `clear_cache: true` rebuilds the ## Architecture presets (unreleased 1.1) +Method-call restrictions, effective method/signature protocols, and semantic component selectors +are not provided by the current file graph or metric method facts. The bounded +[semantic evaluation](https://github.com/dragonsec-ai/ArchUnitRuby/blob/main/design/semantic-boundaries.md) +records exact comparator pins, executable probes and the compatibility/unknowns required before +adding such APIs. This is a technical evaluation, not a newly shipped semantic backend. + `ArchUnit.architecture_preset(name, options = nil)` returns an immutable Checkable `PresetRule`. `ArchUnit::PresetOptions.new(project_locator: nil, folders: {})` is its options bag. Names are `:layered`, `:hexagonal`, or `:rails`; unknown names and malformed/duplicate override layer keys fail diff --git a/benchmark/semantic/cases.json b/benchmark/semantic/cases.json new file mode 100644 index 0000000..26f71da --- /dev/null +++ b/benchmark/semantic/cases.json @@ -0,0 +1,90 @@ +[ + { + "name": "explicit_constant_forbidden_method", + "source": "module Api; class Request; def call = ::Db::Store.delete_all; end; end", + "expected_direct_db": 1, + "comparator_policy": "method_name" + }, + { + "name": "explicit_constant_allowed_method", + "source": "module Api; class Request; def call = ::Db::Store.read; end; end", + "expected_direct_db": 1, + "comparator_policy": "method_name" + }, + { + "name": "explicit_constant_receiver_qualified_policy", + "source": "module Api; class Request; def call = ::Db::Store.delete_all; end; end", + "expected_direct_db": 1, + "comparator_policy": "method" + }, + { + "name": "dynamic_parameter_receiver", + "source": "module Api; class Request; def call(store) = store.delete_all; end; end", + "expected_direct_db": 0, + "comparator_policy": "method" + }, + { + "name": "inherited_unqualified_constant", + "source": "module Api; class Request < ::Base; def call = Store.new; end; end", + "expected_direct_db": 0, + "comparator_policy": "dependency" + }, + { + "name": "inherited_explicit_root_control", + "source": "module Api; class Request < ::Base; def call = ::Db::Store.new; end; end", + "expected_direct_db": 1, + "comparator_policy": "dependency" + }, + { + "name": "alias_member_lookup", + "source": "module Api; class Request; def call = ::AliasDb::Store.new; end; end", + "expected_direct_db": 0, + "comparator_policy": "dependency" + }, + { + "name": "protocol_explicit_signature", + "source": "module Api; class Request; def call(value, context:); end; end; end", + "expected_direct_db": 0, + "comparator_policy": "protocol" + }, + { + "name": "protocol_wrong_signature", + "source": "module Api; class Request; def call; end; end; end", + "expected_direct_db": 0, + "comparator_policy": "protocol" + }, + { + "name": "dynamic_method_definition", + "source": "module Api; class Request; define_method(:call) { |value, context:| value }; end; end", + "expected_direct_db": 0, + "comparator_policy": "protocol" + }, + { + "name": "descendant_declaration", + "source": "module Api; class Request < ::Base; end; end", + "expected_direct_db": 0, + "comparator_policy": "protocol", + "selector": "descendant" + }, + { + "name": "namespace_component_selector", + "source": "module Api; class Request; end; end", + "expected_direct_db": 0, + "comparator_policy": "protocol", + "selector": "namespace" + }, + { + "name": "constant_component_selector", + "source": "module Api; class Request; end; end", + "expected_direct_db": 0, + "comparator_policy": "protocol", + "selector": "constant" + }, + { + "name": "reopened_ambiguous_constant", + "source": "module Api; class Request; def call = ::Db::Store.new; end; end", + "extra_source": "module Db; class Store; end; end", + "expected_direct_db": 0, + "comparator_policy": "dependency" + } +] diff --git a/benchmark/semantic/comparator.rb b/benchmark/semantic/comparator.rb new file mode 100644 index 0000000..654cf74 --- /dev/null +++ b/benchmark/semantic/comparator.rb @@ -0,0 +1,51 @@ +# frozen_string_literal: true + +module SemanticStudy + # Optional exact published comparator. Never added to production gem dependencies. + module Comparator + def self.load + gem 'archspec', '= 1.1.0' + gem 'rubydex', '= 0.4.0' + require 'archspec' + end + + def self.facts(root, specification) + kind = specification.fetch('comparator_policy') + definition = definition(kind, specification['selector']) + graph = ArchSpec::Analyzer.analyze(definition, root:) + diagnostics = ArchSpec::Evaluator.evaluate(definition, graph) + { policy: kind, selector: specification['selector'], rules: diagnostics.map(&:rule), + version: ArchSpec::VERSION, rubydex: Gem.loaded_specs.fetch('rubydex').version.to_s } + end + + def self.definition(kind, selector) + settings = component_settings(selector) + definition = ArchSpec.define do + source '**/*.rb' + component :api, **settings + component :db, in: 'app/db/**/*.rb' + end + attach_policy(definition.api, kind) + definition + end + + def self.attach_policy(api, kind) + case kind + when 'method' then api.cannot_call :delete_all, receiver: 'Db::Store' + when 'method_name' then api.cannot_call :delete_all + when 'protocol' then api.must_implement :call, arity: 1, keywords: [:context] + else api.cannot_use :db + end + end + + def self.component_settings(selector) + case selector + when 'namespace' then { namespace: 'Api' } + when 'constant' then { constants: ['Api::Request'] } + when 'descendant' then { descendants_of: 'Base' } + else { in: 'app/api/**/*.rb' } + end + end + private_class_method :definition, :attach_policy, :component_settings + end +end diff --git a/benchmark/semantic/evidence-windows.json b/benchmark/semantic/evidence-windows.json new file mode 100644 index 0000000..6c995d0 --- /dev/null +++ b/benchmark/semantic/evidence-windows.json @@ -0,0 +1,598 @@ +{ + "runtime": { + "ruby": "4.0.6", + "platform": "x64-mingw-ucrt", + "archunit": "1.1.0", + "prism": "1.9.0" + }, + "cases": [ + { + "name": "explicit_constant_forbidden_method", + "direct_file_boundary_violations": 1, + "counters": { + "source_files": 4, + "malformed_files": 0, + "imports": 0, + "unresolved_imports": 0, + "unresolved_constant_references": 0, + "ambiguous_constant_references": 0, + "resolution_cache_hits": 0, + "resolution_cache_misses": 0, + "raw_edges": 7, + "merged_edges": 7 + }, + "syntax": { + "calls": [ + { + "name": "delete_all", + "receiver_node": "Prism::ConstantPathNode", + "resolved_runtime_receiver": null + } + ], + "declarations": [ + { + "name": "call", + "parameters_node": null + } + ], + "superclasses": [] + }, + "metric_method_fields": [ + "name", + "accessed_fields" + ], + "has_semantic_method_edges": false, + "archspec": { + "policy": "method_name", + "selector": null, + "rules": [ + "methods.forbid" + ], + "version": "1.1.0", + "rubydex": "0.4.0" + } + }, + { + "name": "explicit_constant_allowed_method", + "direct_file_boundary_violations": 1, + "counters": { + "source_files": 4, + "malformed_files": 0, + "imports": 0, + "unresolved_imports": 0, + "unresolved_constant_references": 0, + "ambiguous_constant_references": 0, + "resolution_cache_hits": 0, + "resolution_cache_misses": 0, + "raw_edges": 7, + "merged_edges": 7 + }, + "syntax": { + "calls": [ + { + "name": "read", + "receiver_node": "Prism::ConstantPathNode", + "resolved_runtime_receiver": null + } + ], + "declarations": [ + { + "name": "call", + "parameters_node": null + } + ], + "superclasses": [] + }, + "metric_method_fields": [ + "name", + "accessed_fields" + ], + "has_semantic_method_edges": false, + "archspec": { + "policy": "method_name", + "selector": null, + "rules": [], + "version": "1.1.0", + "rubydex": "0.4.0" + } + }, + { + "name": "explicit_constant_receiver_qualified_policy", + "direct_file_boundary_violations": 1, + "counters": { + "source_files": 4, + "malformed_files": 0, + "imports": 0, + "unresolved_imports": 0, + "unresolved_constant_references": 0, + "ambiguous_constant_references": 0, + "resolution_cache_hits": 0, + "resolution_cache_misses": 0, + "raw_edges": 7, + "merged_edges": 7 + }, + "syntax": { + "calls": [ + { + "name": "delete_all", + "receiver_node": "Prism::ConstantPathNode", + "resolved_runtime_receiver": null + } + ], + "declarations": [ + { + "name": "call", + "parameters_node": null + } + ], + "superclasses": [] + }, + "metric_method_fields": [ + "name", + "accessed_fields" + ], + "has_semantic_method_edges": false, + "archspec": { + "policy": "method", + "selector": null, + "rules": [], + "version": "1.1.0", + "rubydex": "0.4.0" + } + }, + { + "name": "dynamic_parameter_receiver", + "direct_file_boundary_violations": 0, + "counters": { + "source_files": 4, + "malformed_files": 0, + "imports": 0, + "unresolved_imports": 0, + "unresolved_constant_references": 0, + "ambiguous_constant_references": 0, + "resolution_cache_hits": 0, + "resolution_cache_misses": 0, + "raw_edges": 6, + "merged_edges": 6 + }, + "syntax": { + "calls": [ + { + "name": "delete_all", + "receiver_node": "Prism::LocalVariableReadNode", + "resolved_runtime_receiver": null + } + ], + "declarations": [ + { + "name": "call", + "parameters_node": "Prism::ParametersNode" + } + ], + "superclasses": [] + }, + "metric_method_fields": [ + "name", + "accessed_fields" + ], + "has_semantic_method_edges": false, + "archspec": { + "policy": "method", + "selector": null, + "rules": [], + "version": "1.1.0", + "rubydex": "0.4.0" + } + }, + { + "name": "inherited_unqualified_constant", + "direct_file_boundary_violations": 0, + "counters": { + "source_files": 4, + "malformed_files": 0, + "imports": 0, + "unresolved_imports": 0, + "unresolved_constant_references": 1, + "ambiguous_constant_references": 0, + "resolution_cache_hits": 0, + "resolution_cache_misses": 0, + "raw_edges": 7, + "merged_edges": 7 + }, + "syntax": { + "calls": [ + { + "name": "new", + "receiver_node": "Prism::ConstantReadNode", + "resolved_runtime_receiver": null + } + ], + "declarations": [ + { + "name": "call", + "parameters_node": null + } + ], + "superclasses": [ + "::Base" + ] + }, + "metric_method_fields": [ + "name", + "accessed_fields" + ], + "has_semantic_method_edges": false, + "archspec": { + "policy": "dependency", + "selector": null, + "rules": [], + "version": "1.1.0", + "rubydex": "0.4.0" + } + }, + { + "name": "inherited_explicit_root_control", + "direct_file_boundary_violations": 1, + "counters": { + "source_files": 4, + "malformed_files": 0, + "imports": 0, + "unresolved_imports": 0, + "unresolved_constant_references": 0, + "ambiguous_constant_references": 0, + "resolution_cache_hits": 0, + "resolution_cache_misses": 0, + "raw_edges": 8, + "merged_edges": 8 + }, + "syntax": { + "calls": [ + { + "name": "new", + "receiver_node": "Prism::ConstantPathNode", + "resolved_runtime_receiver": null + } + ], + "declarations": [ + { + "name": "call", + "parameters_node": null + } + ], + "superclasses": [ + "::Base" + ] + }, + "metric_method_fields": [ + "name", + "accessed_fields" + ], + "has_semantic_method_edges": false, + "archspec": { + "policy": "dependency", + "selector": null, + "rules": [ + "dependencies.forbid" + ], + "version": "1.1.0", + "rubydex": "0.4.0" + } + }, + { + "name": "alias_member_lookup", + "direct_file_boundary_violations": 0, + "counters": { + "source_files": 4, + "malformed_files": 0, + "imports": 0, + "unresolved_imports": 0, + "unresolved_constant_references": 1, + "ambiguous_constant_references": 0, + "resolution_cache_hits": 0, + "resolution_cache_misses": 0, + "raw_edges": 6, + "merged_edges": 6 + }, + "syntax": { + "calls": [ + { + "name": "new", + "receiver_node": "Prism::ConstantPathNode", + "resolved_runtime_receiver": null + } + ], + "declarations": [ + { + "name": "call", + "parameters_node": null + } + ], + "superclasses": [] + }, + "metric_method_fields": [ + "name", + "accessed_fields" + ], + "has_semantic_method_edges": false, + "archspec": { + "policy": "dependency", + "selector": null, + "rules": [], + "version": "1.1.0", + "rubydex": "0.4.0" + } + }, + { + "name": "protocol_explicit_signature", + "direct_file_boundary_violations": 0, + "counters": { + "source_files": 4, + "malformed_files": 0, + "imports": 0, + "unresolved_imports": 0, + "unresolved_constant_references": 0, + "ambiguous_constant_references": 0, + "resolution_cache_hits": 0, + "resolution_cache_misses": 0, + "raw_edges": 6, + "merged_edges": 6 + }, + "syntax": { + "calls": [], + "declarations": [ + { + "name": "call", + "parameters_node": "Prism::ParametersNode" + } + ], + "superclasses": [] + }, + "metric_method_fields": [ + "name", + "accessed_fields" + ], + "has_semantic_method_edges": false, + "archspec": { + "policy": "protocol", + "selector": null, + "rules": [], + "version": "1.1.0", + "rubydex": "0.4.0" + } + }, + { + "name": "protocol_wrong_signature", + "direct_file_boundary_violations": 0, + "counters": { + "source_files": 4, + "malformed_files": 0, + "imports": 0, + "unresolved_imports": 0, + "unresolved_constant_references": 0, + "ambiguous_constant_references": 0, + "resolution_cache_hits": 0, + "resolution_cache_misses": 0, + "raw_edges": 6, + "merged_edges": 6 + }, + "syntax": { + "calls": [], + "declarations": [ + { + "name": "call", + "parameters_node": null + } + ], + "superclasses": [] + }, + "metric_method_fields": [ + "name", + "accessed_fields" + ], + "has_semantic_method_edges": false, + "archspec": { + "policy": "protocol", + "selector": null, + "rules": [ + "protocol.must_implement" + ], + "version": "1.1.0", + "rubydex": "0.4.0" + } + }, + { + "name": "dynamic_method_definition", + "direct_file_boundary_violations": 0, + "counters": { + "source_files": 4, + "malformed_files": 0, + "imports": 0, + "unresolved_imports": 0, + "unresolved_constant_references": 0, + "ambiguous_constant_references": 0, + "resolution_cache_hits": 0, + "resolution_cache_misses": 0, + "raw_edges": 6, + "merged_edges": 6 + }, + "syntax": { + "calls": [ + { + "name": "define_method", + "receiver_node": null, + "resolved_runtime_receiver": null + } + ], + "declarations": [], + "superclasses": [] + }, + "metric_method_fields": [ + "name", + "accessed_fields" + ], + "has_semantic_method_edges": false, + "archspec": { + "policy": "protocol", + "selector": null, + "rules": [ + "protocol.must_implement" + ], + "version": "1.1.0", + "rubydex": "0.4.0" + } + }, + { + "name": "descendant_declaration", + "direct_file_boundary_violations": 0, + "counters": { + "source_files": 4, + "malformed_files": 0, + "imports": 0, + "unresolved_imports": 0, + "unresolved_constant_references": 0, + "ambiguous_constant_references": 0, + "resolution_cache_hits": 0, + "resolution_cache_misses": 0, + "raw_edges": 7, + "merged_edges": 7 + }, + "syntax": { + "calls": [], + "declarations": [], + "superclasses": [ + "::Base" + ] + }, + "metric_method_fields": [ + "name", + "accessed_fields" + ], + "has_semantic_method_edges": false, + "archspec": { + "policy": "protocol", + "selector": "descendant", + "rules": [ + "protocol.must_implement" + ], + "version": "1.1.0", + "rubydex": "0.4.0" + } + }, + { + "name": "namespace_component_selector", + "direct_file_boundary_violations": 0, + "counters": { + "source_files": 4, + "malformed_files": 0, + "imports": 0, + "unresolved_imports": 0, + "unresolved_constant_references": 0, + "ambiguous_constant_references": 0, + "resolution_cache_hits": 0, + "resolution_cache_misses": 0, + "raw_edges": 6, + "merged_edges": 6 + }, + "syntax": { + "calls": [], + "declarations": [], + "superclasses": [] + }, + "metric_method_fields": [ + "name", + "accessed_fields" + ], + "has_semantic_method_edges": false, + "archspec": { + "policy": "protocol", + "selector": "namespace", + "rules": [ + "protocol.must_implement" + ], + "version": "1.1.0", + "rubydex": "0.4.0" + } + }, + { + "name": "constant_component_selector", + "direct_file_boundary_violations": 0, + "counters": { + "source_files": 4, + "malformed_files": 0, + "imports": 0, + "unresolved_imports": 0, + "unresolved_constant_references": 0, + "ambiguous_constant_references": 0, + "resolution_cache_hits": 0, + "resolution_cache_misses": 0, + "raw_edges": 6, + "merged_edges": 6 + }, + "syntax": { + "calls": [], + "declarations": [], + "superclasses": [] + }, + "metric_method_fields": [ + "name", + "accessed_fields" + ], + "has_semantic_method_edges": false, + "archspec": { + "policy": "protocol", + "selector": "constant", + "rules": [ + "protocol.must_implement" + ], + "version": "1.1.0", + "rubydex": "0.4.0" + } + }, + { + "name": "reopened_ambiguous_constant", + "direct_file_boundary_violations": 0, + "counters": { + "source_files": 5, + "malformed_files": 0, + "imports": 0, + "unresolved_imports": 0, + "unresolved_constant_references": 0, + "ambiguous_constant_references": 3, + "resolution_cache_hits": 0, + "resolution_cache_misses": 0, + "raw_edges": 5, + "merged_edges": 5 + }, + "syntax": { + "calls": [ + { + "name": "new", + "receiver_node": "Prism::ConstantPathNode", + "resolved_runtime_receiver": null + } + ], + "declarations": [ + { + "name": "call", + "parameters_node": null + } + ], + "superclasses": [] + }, + "metric_method_fields": [ + "name", + "accessed_fields" + ], + "has_semantic_method_edges": false, + "archspec": { + "policy": "dependency", + "selector": null, + "rules": [ + "dependencies.forbid" + ], + "version": "1.1.0", + "rubydex": "0.4.0" + } + } + ] +} \ No newline at end of file diff --git a/benchmark/semantic/probes.rb b/benchmark/semantic/probes.rb new file mode 100644 index 0000000..6db6a0d --- /dev/null +++ b/benchmark/semantic/probes.rb @@ -0,0 +1,95 @@ +# frozen_string_literal: true + +require 'archunit' +require 'fileutils' +require 'json' +require 'tmpdir' +require_relative 'syntax_facts' +require_relative 'comparator' + +module SemanticStudy + # Read-only analysis of generated production fixtures; no source/config/Gemfile execution. + module Probes + DB = 'module Db; class Store; def self.delete_all; end; def self.read; end; end; end' + + module_function + + def run(compare: false) + Comparator.load if compare + cases = JSON.parse(File.read(File.join(__dir__, 'cases.json'))) + cases.map { |specification| observe(specification, compare:) } + end + + def observe(specification, compare:) + Dir.mktmpdir('archunit-semantic-probe') do |root| + prepare(root, specification) + result = library_facts(root, specification) + result[:archspec] = Comparator.facts(root, specification) if compare + result + ensure + ArchUnit.clear_graph_cache + end + end + + def prepare(root, specification) + fixture_files(specification).each do |name, source| + file = File.join(root, name) + FileUtils.mkdir_p(File.dirname(file)) + File.write(file, "#{source}\nraise 'must not execute target source'") + end + end + + def fixture_files(specification) + files = { + 'Gemfile' => "raise 'must not execute target Gemfile'", + 'app/api/request.rb' => specification.fetch('source'), 'app/db/store.rb' => DB, + 'base.rb' => 'class Base; Store = ::Db::Store; end', 'alias.rb' => 'AliasDb = ::Db' + } + files['app/db/reopened.rb'] = specification['extra_source'] if specification['extra_source'] + files + end + + def library_facts(root, specification) + profile = ArchUnit::Extraction::ExtractionProfile.new + options = ArchUnit::CheckOptions.new(dependency_analysis: :imports_and_constants) + graph = ArchUnit::Extraction.extract_graph(root, options:, profile:) + count = boundary_count(root, specification, options) + { name: specification['name'], direct_file_boundary_violations: count, + counters: profile.counters, syntax: syntax_facts(specification), + metric_method_fields: ArchUnit::MetricMethodInfo.members, + has_semantic_method_edges: graph.any? { |edge| edge.respond_to?(:resolved_method) } } + end + + def boundary_count(root, specification, options) + rule = ArchUnit.project_files(root).in_path('app/api/**') + .should_not.depend_on_files.in_path('app/db/**') + count = rule.check(options).length + unless count == specification['expected_direct_db'] + raise "unexpected direct dependency: #{specification['name']}" + end + + count + end + + def syntax_facts(specification) + parsed = Prism.parse(specification.fetch('source')) + raise 'invalid probe source' unless parsed.success? + + syntax = SyntaxFacts.new + syntax.visit(parsed.value) + { calls: syntax.calls, declarations: syntax.methods, superclasses: syntax.superclasses } + end + end +end + +if $PROGRAM_NAME == __FILE__ + compare = ARGV.delete('--archspec') + output = ARGV.shift + raise ArgumentError, 'usage: probes.rb [--archspec] [output.json]' unless ARGV.empty? + + results = SemanticStudy::Probes.run(compare:) + runtime = { ruby: RUBY_VERSION, platform: RUBY_PLATFORM, archunit: ArchUnit::VERSION, + prism: Gem.loaded_specs.fetch('prism').version.to_s } + payload = JSON.pretty_generate(runtime:, cases: results) + output ? File.write(output, payload) : puts(payload) +end diff --git a/benchmark/semantic/syntax_facts.rb b/benchmark/semantic/syntax_facts.rb new file mode 100644 index 0000000..cfb9995 --- /dev/null +++ b/benchmark/semantic/syntax_facts.rb @@ -0,0 +1,33 @@ +# frozen_string_literal: true + +require 'prism' + +module SemanticStudy + # Probe-only syntax inventory: deliberately no receiver/type/ancestry inference. + class SyntaxFacts < Prism::Visitor + attr_reader :calls, :methods, :superclasses + + def initialize + super + @calls = [] + @methods = [] + @superclasses = [] + end + + def visit_call_node(node) + calls << { name: node.name, receiver_node: node.receiver&.class&.name, + resolved_runtime_receiver: nil } + super + end + + def visit_def_node(node) + methods << { name: node.name, parameters_node: node.parameters&.class&.name } + super + end + + def visit_class_node(node) + superclasses << node.superclass.slice if node.superclass + super + end + end +end diff --git a/design/semantic-boundaries.md b/design/semantic-boundaries.md new file mode 100644 index 0000000..d599c2e --- /dev/null +++ b/design/semantic-boundaries.md @@ -0,0 +1,106 @@ +# Semantic rule/selector evaluation — #91 + +Status: evaluated on the unreleased 1.1 candidate after #93/#94, 2026-11-22. +This is a technical decision record, not a shipped method/protocol API or a claim of competitor parity. + +## Decision + +Retain Prism and the existing import-only/default versus opt-in constant-file graph contract. +Do not add RubyDEX as a mandatory production dependency or advertise regex/AST receiver spelling +as semantic call resolution. The graph's file identities, evidence, uncertainty counters, cache +settings, no-target-execution guarantee and baseline contract remain unchanged. + +The method/protocol and component-selector gaps remain meaningful. A future first semantic delivery +should introduce explicit declaration facts (constant ownership, declared methods/signatures and +known ancestry) and bounded declaration-based selectors before claiming arbitrary receiver/method +dispatch. A syntactic method-name restriction can also be useful if honestly named/documented as +such. Full inherited/effective protocols, aliases, reopened classes and runtime receiver inference +need a separately designed semantic model and confidence/unknown contract, not another file glob. +No such public API is silently added by this evaluation. + +Maintainer testing/request (#66 and this follow-up) establishes interest. We have no measured user +adoption/request counts and do not invent demand data. Baselines and composed presets are lower-risk +adoption improvements; they do not remove the semantic gap. + +## Reproducible evidence + +`benchmark/semantic/cases.json` defines 14 small fixtures. The default harness runs against our +library without optional dependencies; `--archspec` runs the exact published comparator. Fixtures +raise if their source or Gemfile is executed. No target configuration or dependency installation +is used. `syntax_facts.rb` is a probe-only Prism visitor, **not** a new production resolver. + +The checked-in `benchmark/semantic/evidence-windows.json` records Ruby 4.0.6, Prism 1.9.0 and current +unreleased ArchUnit 1.1, with ArchSpec 1.1.0 / RubyDEX 0.4.0. Official immutable source pins: + +- [ArchSpec 1.1.0](https://github.com/crmne/archspec/tree/1d321d3585a86672e65b2488681393f9d52656a9) + (`v1.1.0`), including its `protocol_rules.rb`, `component_spec.rb` and `rubydex_index.rb`. +- [RubyDEX 0.4.0](https://github.com/Shopify/rubydex/tree/e0ed5e7d722a0c37c0534878a722d7b67f4b63ac) + (`v0.4.0`). This is not a statement about newer releases or master. + +Verified cached package SHA256s match the earlier lock: ArchSpec +`861d4869c81617139ea9e42e6de1456ba00d0538f3994476073829de223a754d`; +RubyDEX Windows x64 UCRT +`7becaee5f1d89bdbea031daecbd46137f03e30e9e218f19cc03a538865830ba5`. + +| Bounded control | Our result / boundary | Pinned comparator observation | +| --- | --- | --- | +| Explicit `Db::Store.delete_all` vs `Db::Store.read` | A no-DB-file rule rejects both; it cannot express a method-name policy | Unqualified `cannot_call :delete_all` rejects the former only | +| Same explicit call with receiver-qualified restriction | File edge remains visible, no method target API | `receiver: 'Db::Store'` emitted no diagnostic in this fixture | +| Method parameter receiver `store.delete_all` | Name is visible syntactically, runtime receiver is unknown | Receiver-qualified policy emitted no diagnostic | +| Unqualified inherited constant vs explicit-root control | Inherited form stays unresolved; explicit root produces the direct DB edge | Direct dependency policy catches the root control, not the unqualified form | +| Alias-member lookup | No direct DB edge is inferred; uncertainty remains | No direct DB diagnostic in this fixture | +| Correct/wrong explicit method signature | Metric methods expose name/field facts, not arity/keyword protocols | Protocol accepts the correct signature and flags the wrong one | +| `define_method` matching the runtime protocol | Probe sees syntax but does not execute/infer a runtime API | Protocol still flags this fixture; do not infer complete metaprogramming support | +| Namespace/constant/descendant component selection | No first-class file/component selector based on those semantics | Each selects the fixture class for a missing-protocol diagnostic | +| Reopened constant definitions | Kept ambiguous rather than selecting a definition | Direct dependency policy reports a DB dependency in this fixture | + +These observations compare particular policies, not a universal correctness oracle. Especially the +first rows do **not** compare equivalent policies: an architectural file dependency is broader +than a method restriction. A zero diagnostic is not proof that a runtime behavior is safe. No +global semantic-coverage percentage or performance winner is derived. + +## Backend tradeoffs + +Prism already gives explicit class/module/def/call/parameter syntax without executing applications. +It does not by itself resolve dynamic dispatch, included/inherited method lookup, alias expansion, +load order or reflection. Our current metric `MethodInfo` is only `name` / `accessed_fields`; its +class selection is a metric selector, not a semantic component selector or protocol check. + +ArchSpec's published adapter combines a RubyDEX resolved index with a Prism syntax overlay; +its method model includes signatures, effective ancestry and alias information. Reusing a semantic +index could avoid reimplementing all Ruby lookup rules, but does not eliminate unknowns demonstrated +above. The pinned RubyDEX package is native/Rust and declares Ruby `>= 3.2, < 4.1.dev`, narrower +than simply depending on our current Ruby 3.3+ parser toolchain. A mandatory switch would couple +installation/platform availability, Ruby-version upgrades, native-parser failure modes, indexing +time and memory to every user, including those only using imports/metrics. No unmeasured resource +or platform support claim is made; #92 evaluates representative timing/memory separately. + +If an optional semantic adapter is later chosen, isolate its dependency/version/platform contract, +label its facts/confidence and cache identity explicitly, preserve old-mode graph fingerprints, +and test it on Linux and Windows. Native indexing must not gain authority to boot applications; +resource limits and process isolation should be evaluated for hostile/large inputs. This is a +design consideration, not a claim of a discovered native vulnerability. + +## Acceptance boundaries for any subsequent semantic delivery + +1. Specify a sentence-like API and structured fact/violation model; choose declaration-only versus + effective/runtime behavior explicitly. No method/protocol predicates inferred from formatted text. +2. Keep imports and imports_and_constants behavior unchanged when semantic features are off. New + options must participate in cache/scope identity and accepted-debt fingerprints. +3. Report unsupported/ambiguous facts as unknown; distinguish an absent declaration from a proven + absent runtime method. Decide strictness per documented rule, not a default false clean pass. +4. Cover singleton/instance methods, positional/optional/rest/keyword/block/forward signatures, + aliases, mixins/inheritance, reopened/conditional declarations, dynamic `define_method`, + `method_missing`, reflective mutation, descendant cycles and multiple source roots. +5. Verify installed-package/platform support, no target boot, startup/index/reuse/memory costs and + passing **and** failing controls before claiming shipped semantic capability. + +Run current-only probes from the library's bundle: + +```sh +bundle exec ruby benchmark/semantic/probes.rb output.json +``` + +For the exact comparator, use a separate trusted benchmark environment containing ArchSpec 1.1.0, +RubyDEX 0.4.0 and Prism 1.9.0, with this checkout on the load path; then add `--archspec`. Never +install or evaluate the target fixture's Gemfile to run these checks. diff --git a/spec/benchmark/semantic_probes_spec.rb b/spec/benchmark/semantic_probes_spec.rb new file mode 100644 index 0000000..fd3eed5 --- /dev/null +++ b/spec/benchmark/semantic_probes_spec.rb @@ -0,0 +1,22 @@ +# frozen_string_literal: true + +require_relative '../../benchmark/semantic/probes' + +RSpec.describe SemanticStudy::Probes do + it 'records bounded facts without claiming method semantics or executing probe code' do + observations = described_class.run + expect(observations.length).to eq(14) + expect(observations.map { |item| item[:has_semantic_method_edges] }).to all(be(false)) + expect(observations.map do |item| + item[:metric_method_fields] + end).to all(eq(%i[name accessed_fields])) + dynamic = observations.find { |item| item[:name] == 'dynamic_parameter_receiver' } + expect(dynamic[:syntax][:calls]).to include(include(name: :delete_all, + resolved_runtime_receiver: nil)) + inherited = observations.find { |item| item[:name] == 'inherited_unqualified_constant' } + expect(inherited[:direct_file_boundary_violations]).to eq(0) + expect(inherited[:counters][:unresolved_constant_references]).to be_positive + reopened = observations.find { |item| item[:name] == 'reopened_ambiguous_constant' } + expect(reopened[:counters][:ambiguous_constant_references]).to be_positive + end +end From 8a6753b8d71d9bcd040096d4994db028aea4b5c3 Mon Sep 17 00:00:00 2001 From: TristanKruse Date: Sun, 22 Nov 2026 15:13:37 +0100 Subject: [PATCH 4/4] Add oracle-checked Linux architecture performance study (#92) --- .github/workflows/performance-study.yml | 88 ++++++++++++++++++++ benchmark/README.md | 3 + benchmark/study/Gemfile | 11 +++ benchmark/study/Gemfile.lock | 43 ++++++++++ benchmark/study/README.md | 68 +++++++++++++++ benchmark/study/adapters.rb | 52 ++++++++++++ benchmark/study/fixture.rb | 77 +++++++++++++++++ benchmark/study/measurements.rb | 65 +++++++++++++++ benchmark/study/real_project.rb | 101 +++++++++++++++++++++++ benchmark/study/run.rb | 86 +++++++++++++++++++ benchmark/study/startup.rb | 17 ++++ benchmark/study/startup_samples.rb | 27 ++++++ spec/benchmark/performance_study_spec.rb | 45 ++++++++++ 13 files changed, 683 insertions(+) create mode 100644 .github/workflows/performance-study.yml create mode 100644 benchmark/study/Gemfile create mode 100644 benchmark/study/Gemfile.lock create mode 100644 benchmark/study/README.md create mode 100644 benchmark/study/adapters.rb create mode 100644 benchmark/study/fixture.rb create mode 100644 benchmark/study/measurements.rb create mode 100644 benchmark/study/real_project.rb create mode 100644 benchmark/study/run.rb create mode 100644 benchmark/study/startup.rb create mode 100644 benchmark/study/startup_samples.rb create mode 100644 spec/benchmark/performance_study_spec.rb diff --git a/.github/workflows/performance-study.yml b/.github/workflows/performance-study.yml new file mode 100644 index 0000000..9ce2344 --- /dev/null +++ b/.github/workflows/performance-study.yml @@ -0,0 +1,88 @@ +name: Representative performance study + +on: + workflow_dispatch: + pull_request: + paths: + - 'benchmark/study/**' + - 'benchmark/semantic/**' + - 'spec/benchmark/performance_study_spec.rb' + - '.github/workflows/performance-study.yml' + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + study: + name: Oracle-checked Linux performance evidence + runs-on: ubuntu-latest + timeout-minutes: 15 + defaults: + run: + working-directory: archunit/benchmark/study + steps: + - name: Check out candidate + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + path: archunit + persist-credentials: false + + - name: Check out pinned Rails application as source only + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + repository: discourse/discourse + ref: 2de9c9be4f89e392fe500dd27f928d6b1184bf09 + path: corpus + persist-credentials: false + sparse-checkout-cone-mode: false + sparse-checkout: | + /lib/**/*.rb + /app/**/*.rb + /config/**/*.rb + /src/**/*.rb + /*.rb + /*.gemspec + /Gemfile + /.archignore + /LICENSE* + /README* + !/**/fixtures/** + !/**/spec/** + !/**/test/** + !/**/tests/** + + - name: Set up isolated checksum-locked research dependencies + uses: ruby/setup-ruby@be3c7df29b3349ec6bcfc6b4792f1cf9f5237d18 # v1 + with: + ruby-version: '4.0' + bundler-cache: true + working-directory: archunit/benchmark/study + + - name: Repeated alternating shared-policy trials and fresh startup + run: bundle exec ruby run.rb --archspec ../../pkg/study-linux.json + env: + STUDY_PAIRS: '100' + STUDY_TRIALS: '5' + + - name: Reproduce bounded semantic comparison on Linux + run: bundle exec ruby ../semantic/probes.rb --archspec ../../pkg/semantic-linux.json + + - name: Profile real pinned production source without booting it + run: bundle exec ruby real_project.rb ../../../corpus ../../pkg/discourse-linux.json + + - name: Retain raw evidence and exact dependency lock + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: performance-study-${{ github.run_id }} + path: | + archunit/pkg/study-linux.json + archunit/pkg/semantic-linux.json + archunit/pkg/discourse-linux.json + archunit/benchmark/study/Gemfile.lock + if-no-files-found: warn + retention-days: 14 diff --git a/benchmark/README.md b/benchmark/README.md index 53e429c..6a3edb9 100644 --- a/benchmark/README.md +++ b/benchmark/README.md @@ -1,5 +1,8 @@ # Extraction performance benchmark +For repeated Linux shared-policy comparisons, fresh-process startup/memory, source changes and +pinned Rails production-source evidence, see the [representative study](study/README.md). + For pinned production-library compatibility checks, public passing/failing rule witnesses, and real-world timing artifacts, see the [static canary guide](canary/README.md). diff --git a/benchmark/study/Gemfile b/benchmark/study/Gemfile new file mode 100644 index 0000000..aaf0dea --- /dev/null +++ b/benchmark/study/Gemfile @@ -0,0 +1,11 @@ +# frozen_string_literal: true + +# Isolated research bundle, never evaluated from a target project or shipped as runtime deps. +source 'https://rubygems.org' + +gem 'archspec', '= 1.1.0' +gem 'archunit', path: '../..' +gem 'csv', '= 3.3.7' +gem 'json', '= 2.21.2' +gem 'prism', '= 1.9.0' +gem 'rubydex', '= 0.4.0' diff --git a/benchmark/study/Gemfile.lock b/benchmark/study/Gemfile.lock new file mode 100644 index 0000000..c2eb756 --- /dev/null +++ b/benchmark/study/Gemfile.lock @@ -0,0 +1,43 @@ +PATH + remote: ../.. + specs: + archunit (1.1.0) + csv (>= 3.3, < 4.0) + json (>= 2.7, < 3.0) + prism (>= 1.0, < 2.0) + +GEM + remote: https://rubygems.org/ + specs: + archspec (1.1.0) + prism (>= 1.0) + rubydex (~> 0.4.0) + csv (3.3.7) + json (2.21.2) + prism (1.9.0) + rubydex (0.4.0-x64-mingw-ucrt) + rubydex (0.4.0-x86_64-linux) + +PLATFORMS + x64-mingw-ucrt + x86_64-linux + +DEPENDENCIES + archspec (= 1.1.0) + archunit! + csv (= 3.3.7) + json (= 2.21.2) + prism (= 1.9.0) + rubydex (= 0.4.0) + +CHECKSUMS + archspec (1.1.0) sha256=861d4869c81617139ea9e42e6de1456ba00d0538f3994476073829de223a754d + archunit (1.1.0) + csv (3.3.7) sha256=15a3f16f6628da8664d455eb634e7f22031bcf53044923caf56975109e71b9f8 + json (2.21.2) sha256=1f1d3b7cf2b3ba1a69beca0bb6db13d5438b80bff3cd54cdaaa620b9b07c1c6a + prism (1.9.0) sha256=7b530c6a9f92c24300014919c9dcbc055bf4cdf51ec30aed099b06cd6674ef85 + rubydex (0.4.0-x64-mingw-ucrt) sha256=7becaee5f1d89bdbea031daecbd46137f03e30e9e218f19cc03a538865830ba5 + rubydex (0.4.0-x86_64-linux) sha256=75a4e1c6c4691ff815aee820dd26fb080f8053430a0ad248dd9b3125d621df86 + +BUNDLED WITH + 4.0.16 diff --git a/benchmark/study/README.md b/benchmark/study/README.md new file mode 100644 index 0000000..6c04155 --- /dev/null +++ b/benchmark/study/README.md @@ -0,0 +1,68 @@ +# Representative performance study (#92) + +This research bundle is separate from the production gem. Comparison pins: ArchSpec 1.1.0, +RubyDEX 0.4.0, Prism 1.9.0, JSON 2.21.2 and CSV 3.3.7. Its lock contains Linux/Windows native +package checksums without changing root dependencies. The candidate is the checkout revision, +not necessarily the published gem. + +## Shared-policy study + +`run.rb` generates Rails-like and four-engine layouts with 200 Ruby files by default. Density +1 and 3, each with allowed/forbidden policies, give eight cases. Unique API/database classes, +explicit imports and root-qualified references provide known expected counts. Every measurement +validates its result; a source edit adds one deterministic edge and forbidden diagnostic. +Unexpected results abort the study, rather than recording an apparently fast incorrect run. +Fixtures raise if executed; their source, Gemfile, tests or dependencies are never run/installed. + +Five alternating trials per tool retain raw samples and medians: + +- `cold`: libraries/definitions preloaded, graph rebuilt plus check. This is not fresh-process + startup or cold disk; OS file caches are not flushed. +- `warm`: same in-memory graph. Our public check performs discovery/cache lookup; ArchSpec uses + its public evaluator on the returned graph. Useful workflows, not identical internal operations. +- `after_change`: rewrite one source, explicitly rebuild, check, restore before the next tool. + Allowed policies remain zero; forbidden policies gain one diagnostic. Stale results are rejected. +- `startup`: fresh Ruby processes loading only their chosen analyzer. `wall_seconds` includes + launch/load/analysis/check; child `seconds` isolates post-load analysis/check. Order alternates. +- Memory: ObjectSpace Ruby-heap bytes/growth exclude native memory. Fresh-child Linux `VmHWM` + is peak process RSS; Windows unavailable values are null, not zero. Parent heaps include both + preloaded libraries, GC and small retained result objects, not independent process peaks. + +The analyzers do different semantic work. Counts validate only shared fixture policies, not equal +Ruby coverage. Engine shapes are generated, not full monorepo/Rails applications. Do not derive +a universal winner or optimize to a leaderboard. Shared-runner times are observations, not hard +timing gates; no graph baseline is auto-updated. Existing correctness canaries stay separate. + +## Real production source + +`real_project.rb` checks pinned Discourse `2de9c9be4f89e392fe500dd27f928d6b1184bf09`, with three +cold/warm pairs per mode. It verifies the revision and pristine Git status, requires the reviewed +2,510-source view, asserts warm graph identity and zero repeated cold counters, and checks status +unchanged afterward. Source/graph/uncertainty facts accompany timing/memory. Source-count changes +fail instead of silently blessing another corpus. + +Sparse patterns in the workflow include production `lib/app/config/src` and root Ruby/markers, +excluding test/spec/fixture contents. This is not full Discourse, an upstream architecture/security +verdict, or a shared semantic-policy comparison against ArchSpec. Its RSS is explicitly a +process-lifetime high-water mark, not per-mode allocation. No target source, tests, configuration, +Gemfile/gemspec or Rails boot is executed. Evidence outputs go to our own `pkg`. + +## Linux CI and reproduction + +`Representative performance study` is manually dispatchable and runs on relevant study PRs, +not a timer or every code change. It uses immutable action/source pins, read-only permissions, +no persisted checkout credentials, a separate frozen/checksum-locked bundle, 15-minute timeout, +concurrency cancellation and 14-day artifacts. It also repeats the 14 semantic probes on Linux. + +From this trusted research directory, never from the target application: + +```sh +bundle install +STUDY_PAIRS=100 STUDY_TRIALS=5 bundle exec ruby run.rb --archspec ../../pkg/study.json +bundle exec ruby ../semantic/probes.rb --archspec ../../pkg/semantic.json +bundle exec ruby real_project.rb /path/to/pinned-sparse-discourse ../../pkg/discourse.json +``` + +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. diff --git a/benchmark/study/adapters.rb b/benchmark/study/adapters.rb new file mode 100644 index 0000000..63b70c6 --- /dev/null +++ b/benchmark/study/adapters.rb @@ -0,0 +1,52 @@ +# frozen_string_literal: true + +module PerformanceStudy + # Public rule/extraction calls only; neither adapter evaluates the fixture project. + module Adapters + # Current expanded-file graph and ordinary fluent rule execution. + class Candidate + def initialize(root, policy) + mood = ArchUnit.project_files(root).in_path('**/app/api/**') + mood = policy == 'forbidden' ? mood.should_not : mood.should + @rule = mood.depend_on_files.in_path('**/app/db/**') + @options = ArchUnit::CheckOptions.new(dependency_analysis: :imports_and_constants) + end + + def cold + ArchUnit.clear_graph_cache + warm + end + + def warm + @rule.check(@options) + end + end + + # Published comparator with explicit in-memory graph reuse for warm evaluation. + class Comparator + def initialize(root, policy) + @root = root + @definition = ArchSpec.define do + source '**/*.rb' + component :api, in: '**/app/api/**/*.rb' + component :db, in: '**/app/db/**/*.rb' + policy == 'forbidden' ? api.cannot_use(:db) : api.can_only_use(:db) + end + end + + def cold + @graph = ArchSpec::Analyzer.analyze(@definition, root: @root) + warm + end + + def warm + ArchSpec::Evaluator.evaluate(@definition, @graph) + end + end + + def self.build(name, root, policy) + type = name == 'archunit' ? Candidate : Comparator + type.new(root, policy) + end + end +end diff --git a/benchmark/study/fixture.rb b/benchmark/study/fixture.rb new file mode 100644 index 0000000..ba4e337 --- /dev/null +++ b/benchmark/study/fixture.rb @@ -0,0 +1,77 @@ +# frozen_string_literal: true + +require 'fileutils' +require 'pathname' + +module PerformanceStudy + # Generated Ruby production shapes with an independently known directed-edge oracle. + class Fixture + attr_reader :root, :pairs, :density, :shape + + def initialize(root:, pairs:, density:, shape:) + unless pairs.is_a?(Integer) && pairs.between?(4, 1000) && [1, 3].include?(density) + raise ArgumentError, 'study requires 4..1000 pairs and density 1 or 3' + end + raise ArgumentError, 'unknown study shape' unless %w[rails engines].include?(shape) + + @root = root + @pairs = pairs + @density = density + @shape = shape + end + + def prepare + FileUtils.mkdir_p(root) + File.write(File.join(root, 'Gemfile'), "raise 'do not evaluate target Gemfile'") + pairs.times do |index| + write_api(index) + write(db(index), "module Db; class Store#{index}; end; end\nraise 'do not run target'") + end + end + + def api(index) + "#{prefix(index)}/app/api/request_#{index}.rb".delete_prefix('/') + end + + def db(index) + "#{prefix(index)}/app/db/store_#{index}.rb".delete_prefix('/') + end + + def oracle(extra: false) + pairs.times.flat_map do |index| + targets(index, extra: extra && index.zero?).map { |target| [api(index), db(target)] } + end + end + + def write_api(index, extra: false) + dependencies = targets(index, extra:) + imports = dependencies.map { |target| import(api(index), db(target)) } + calls = dependencies.map { |target| "::Db::Store#{target}.new" } + code = [*imports, "module Api; class Request#{index}; def call;", *calls, + "end; end; end\nraise 'do not run target'"] + write(api(index), code.join("\n")) + end + + private + + def prefix(index) + shape == 'engines' ? "engines/package_#{index % 4}" : '' + end + + def targets(index, extra: false) + (density + (extra ? 1 : 0)).times.map { |offset| (index + offset) % pairs } + end + + def import(from, to) + directory = Pathname.new(from).dirname + relative = Pathname.new(to.delete_suffix('.rb')).relative_path_from(directory) + "require_relative #{relative.to_s.tr('\\', '/').dump}" + end + + def write(path, contents) + full_path = File.join(root, path) + FileUtils.mkdir_p(File.dirname(full_path)) + File.write(full_path, contents) + end + end +end diff --git a/benchmark/study/measurements.rb b/benchmark/study/measurements.rb new file mode 100644 index 0000000..9d5ced2 --- /dev/null +++ b/benchmark/study/measurements.rb @@ -0,0 +1,65 @@ +# frozen_string_literal: true + +require 'objspace' + +module PerformanceStudy + # Timings are accepted only after the expected policy result has been verified. + module Measurements + def self.clock + Process.clock_gettime(Process::CLOCK_MONOTONIC) + end + + def self.sample(adapter, stage, expected) + started = clock + result = adapter.public_send(stage) + seconds = clock - started + unless result.length == expected + raise "expected #{expected} diagnostics, got #{result.length}" + end + + { seconds:, violations: result.length, ruby_heap_bytes: ObjectSpace.memsize_of_all } + end + + def self.trial(tool, fixture, policy) + before = prepare_trial(fixture) + adapter = Adapters.build(tool, fixture.root, policy) + expected = policy == 'forbidden' ? fixture.oracle.length : 0 + result = initial_samples(adapter, expected) + result[:after_change] = changed_sample(adapter, fixture, policy) + result.merge(ruby_heap_growth_bytes: result[:cold][:ruby_heap_bytes] - before) + ensure + fixture.write_api(0) + ArchUnit.clear_graph_cache + end + + def self.prepare_trial(fixture) + fixture.write_api(0) + ArchUnit.clear_graph_cache + GC.start + ObjectSpace.memsize_of_all + end + + def self.changed_sample(adapter, fixture, policy) + fixture.write_api(0, extra: true) + expected = policy == 'forbidden' ? fixture.oracle(extra: true).length : 0 + sample(adapter, :cold, expected) + end + + def self.initial_samples(adapter, expected) + { cold: sample(adapter, :cold, expected), warm: sample(adapter, :warm, expected) } + end + + def self.summarize(samples) + values = samples.sort + middle = values.length / 2 + median = values.length.odd? ? values[middle] : (values[middle - 1] + values[middle]) / 2.0 + { median_seconds: median, samples_seconds: samples } + end + + def self.peak_rss_kb + return unless File.file?('/proc/self/status') + + File.read('/proc/self/status')[/^VmHWM:\s+(\d+)/, 1]&.to_i + end + end +end diff --git a/benchmark/study/real_project.rb b/benchmark/study/real_project.rb new file mode 100644 index 0000000..270647d --- /dev/null +++ b/benchmark/study/real_project.rb @@ -0,0 +1,101 @@ +# frozen_string_literal: true + +require 'archunit' +require 'fileutils' +require 'json' +require 'objspace' +require 'open3' +require_relative 'measurements' + +module PerformanceStudy + # Pinned production-source study, not an upstream architecture/security judgment. + module RealProject + def self.run(root, trials: 3, expected_sources: 2510) + before = prepare_root(root) + results = %i[imports imports_and_constants].map do |mode| + samples = Array.new(trials) { profile(root, mode, expected_sources) } + seconds = samples.map { |item| item[:cold_seconds] } + { mode:, samples:, summary: Measurements.summarize(seconds) } + end + raise 'target checkout changed during analysis' unless before == git_status(root) + + results + ensure + ArchUnit.clear_graph_cache + end + + def self.prepare_root(root) + verify_revision(root) + before = git_status(root) + raise 'pinned checkout must start clean' unless before.empty? + + before + end + + def self.verify_revision(root) + output, errors, status = Open3.capture3('git', '-C', root, 'rev-parse', 'HEAD') + expected = '2de9c9be4f89e392fe500dd27f928d6b1184bf09' + return if status.success? && output.strip == expected + + raise "wrong pinned revision: #{output}#{errors}" + end + + def self.profile(root, mode, expected_sources) + graph, cold, options = cold_profile(root, mode, expected_sources) + warm = warm_profile(root, options, graph) + { cold_seconds: cold.stage_seconds[:total], warm_seconds: warm.stage_seconds[:total], + graph_edges: graph.length, counters: cold.counters, + ruby_heap_bytes: ObjectSpace.memsize_of_all, + process_lifetime_peak_rss_kb: Measurements.peak_rss_kb } + end + + def self.cold_profile(root, mode, expected_sources) + ArchUnit.clear_graph_cache + GC.start + options = ArchUnit::CheckOptions.new(dependency_analysis: mode) + cold = ArchUnit::Extraction::ExtractionProfile.new + graph = ArchUnit::Extraction.extract_graph(root, options:, profile: cold) + unless cold.counters[:source_files] == expected_sources + raise 'pinned source scope changed; review, do not auto-bless it' + end + + [graph, cold, options] + end + + def self.warm_profile(root, options, graph) + warm = ArchUnit::Extraction::ExtractionProfile.new + cached = ArchUnit::Extraction.extract_graph(root, options:, profile: warm) + raise 'warm graph not reused' unless cached.equal?(graph) && warm.cache_hit? + raise 'warm graph repeats cold work' unless warm.counters.values.all?(&:zero?) + + warm + end + + def self.git_status(root) + output, errors, status = Open3.capture3( + { 'GIT_OPTIONAL_LOCKS' => '0' }, 'git', '-C', root, 'status', '--porcelain' + ) + raise "could not verify checkout: #{errors}" unless status.success? + + output + end + end +end + +if $PROGRAM_NAME == __FILE__ + root, output = ARGV + unless root && output && ARGV.length == 2 + raise ArgumentError, + 'usage: real_project.rb ROOT OUTPUT.json' + end + + results = PerformanceStudy::RealProject.run(root) + payload = { ruby: RUBY_VERSION, platform: RUBY_PLATFORM, candidate_version: ArchUnit::VERSION, + revision: ENV.fetch('GITHUB_SHA', nil), + target_revision: '2de9c9be4f89e392fe500dd27f928d6b1184bf09', + limitations: 'Sparse source; no target boot or semantic-completeness claim', + cases: results } + FileUtils.mkdir_p(File.dirname(output)) + File.write(output, JSON.pretty_generate(payload)) + puts "Read-only Discourse profiling passed in both modes; evidence: #{output}" +end diff --git a/benchmark/study/run.rb b/benchmark/study/run.rb new file mode 100644 index 0000000..0f8a990 --- /dev/null +++ b/benchmark/study/run.rb @@ -0,0 +1,86 @@ +# frozen_string_literal: true + +require 'json' +require 'tmpdir' +require 'archunit' +require_relative 'fixture' +require_relative 'adapters' +require_relative 'measurements' +require_relative 'startup_samples' +require_relative '../semantic/comparator' + +module PerformanceStudy + # Repeated, alternating, oracle-checked trials; no machine-speed threshold or leaderboard. + module Runner + module_function + + def run(pairs: 100, trials: 5, compare: false, startup: true) + raise ArgumentError, 'trials must be between 1 and 9' unless (1..9).cover?(trials) + + SemanticStudy::Comparator.load if compare + cases(pairs).map { |settings| measure_case(settings, trials, compare:, startup:) } + end + + def cases(pairs) + %w[rails engines].product([1, 3], %w[allowed forbidden]).map do |shape, density, policy| + { shape:, density:, pairs:, policy: } + end + end + + def measure_case(settings, trials, compare:, startup:) + Dir.mktmpdir('archunit-performance-study') do |root| + fixture = Fixture.new(root:, **settings.except(:policy)) + fixture.prepare + tools = compare ? %w[archunit archspec] : ['archunit'] + samples = repeated_trials(tools, fixture, settings[:policy], trials) + starts = startup_samples(tools, fixture, settings[:policy], trials) if startup + settings.merge(files: fixture.pairs * 2, trials:, samples:, startup: starts, + summary: summary(samples)) + end + end + + def repeated_trials(tools, fixture, policy, trials) + samples = tools.to_h { |tool| [tool, []] } + trials.times do |index| + order = index.even? ? tools : tools.reverse + order.each { |tool| samples[tool] << Measurements.trial(tool, fixture, policy) } + end + samples + end + + def startup_samples(tools, fixture, policy, trials) + samples = tools.to_h { |tool| [tool, []] } + trials.times do |index| + order = index.even? ? tools : tools.reverse + order.each { |tool| samples[tool] << StartupSamples.run(tool, fixture, policy) } + end + samples + end + + def summary(samples) + samples.transform_values do |trials| + %i[cold warm after_change].to_h do |stage| + [stage, Measurements.summarize(trials.map { |trial| trial[stage][:seconds] })] + end + end + end + end +end + +if $PROGRAM_NAME == __FILE__ + compare = ARGV.delete('--archspec') + output = ARGV.shift || 'pkg/performance-study.json' + raise ArgumentError, 'usage: run.rb [--archspec] [output.json]' unless ARGV.empty? + + trials = Integer(ENV.fetch('STUDY_TRIALS', '5')) + pairs = Integer(ENV.fetch('STUDY_PAIRS', '100')) + results = PerformanceStudy::Runner.run(pairs:, trials:, compare:) + gems = %w[archunit archspec rubydex prism json csv].to_h do |name| + [name, Gem.loaded_specs[name]&.version&.to_s] + end + runtime = { ruby: RUBY_VERSION, platform: RUBY_PLATFORM, candidate_version: ArchUnit::VERSION, + revision: ENV.fetch('GITHUB_SHA', nil), gems: } + FileUtils.mkdir_p(File.dirname(output)) + File.write(output, JSON.pretty_generate(schema_version: 1, runtime:, cases: results)) + puts "Validated #{results.length} performance shapes/policies; evidence: #{output}" +end diff --git a/benchmark/study/startup.rb b/benchmark/study/startup.rb new file mode 100644 index 0000000..47599b4 --- /dev/null +++ b/benchmark/study/startup.rb @@ -0,0 +1,17 @@ +# frozen_string_literal: true + +require 'json' +require_relative 'adapters' +require_relative 'measurements' + +tool, root, policy, expected = ARGV +if tool == 'archspec' + gem 'archspec', '= 1.1.0' + gem 'rubydex', '= 0.4.0' + require 'archspec' +else + require 'archunit' +end +adapter = PerformanceStudy::Adapters.build(tool, root, policy) +result = PerformanceStudy::Measurements.sample(adapter, :cold, Integer(expected)) +puts JSON.generate(result.merge(peak_rss_kb: PerformanceStudy::Measurements.peak_rss_kb)) diff --git a/benchmark/study/startup_samples.rb b/benchmark/study/startup_samples.rb new file mode 100644 index 0000000..af49732 --- /dev/null +++ b/benchmark/study/startup_samples.rb @@ -0,0 +1,27 @@ +# frozen_string_literal: true + +require 'json' +require 'open3' +require 'rbconfig' +require_relative 'measurements' + +module PerformanceStudy + # Fresh-process wall time includes Ruby boot, library load, analysis and one policy check. + module StartupSamples + def self.run(tool, fixture, policy) + started = Measurements.clock + output, errors, status = Open3.capture3(*arguments(tool, fixture, policy)) + seconds = Measurements.clock - started + raise "startup failed: #{output}#{errors}" unless status.success? && errors.empty? + + JSON.parse(output).merge('wall_seconds' => seconds) + end + + def self.arguments(tool, fixture, policy) + expected = policy == 'forbidden' ? fixture.oracle.length : 0 + [RbConfig.ruby, '-I', File.expand_path('../../lib', __dir__), + File.join(__dir__, 'startup.rb'), tool, fixture.root, policy, expected.to_s] + end + private_class_method :arguments + end +end diff --git a/spec/benchmark/performance_study_spec.rb b/spec/benchmark/performance_study_spec.rb new file mode 100644 index 0000000..66a07da --- /dev/null +++ b/spec/benchmark/performance_study_spec.rb @@ -0,0 +1,45 @@ +# frozen_string_literal: true + +require 'json' +require 'tmpdir' +require 'yaml' +require_relative '../../benchmark/study/run' + +RSpec.describe PerformanceStudy::Runner do + it 'checks permitted, forbidden and changed-source policies across all shapes and densities' do + results = described_class.run(pairs: 4, trials: 1, compare: false, startup: false) + expect(results.length).to eq(8) + results.each do |result| + sample = result[:samples].fetch('archunit').first + expected = result[:policy] == 'forbidden' ? result[:pairs] * result[:density] : 0 + changed = result[:policy] == 'forbidden' ? expected + 1 : 0 + expect(sample[:cold][:violations]).to eq(expected) + expect(sample[:warm][:violations]).to eq(expected) + expect(sample[:after_change][:violations]).to eq(changed) + expect(result[:summary]['archunit'][:cold][:samples_seconds].length).to eq(1) + end + end + + it 'computes medians correctly for odd and even samples without a timing threshold' do + expect(PerformanceStudy::Measurements.summarize([3.0, 1.0, 2.0])[:median_seconds]).to eq(2.0) + expect(PerformanceStudy::Measurements.summarize([4.0, 1.0, 3.0, + 2.0])[:median_seconds]).to eq(2.5) + expect { described_class.run(trials: 0) }.to raise_error(ArgumentError) + end + + it 'uses bounded read-only Linux CI with immutable sources, research-only deps and artifacts' do + path = File.expand_path('../../.github/workflows/performance-study.yml', __dir__) + workflow = YAML.safe_load_file(path, aliases: true) + expect(workflow['permissions']).to eq('contents' => 'read') + job = workflow.fetch('jobs').fetch('study') + expect(job['timeout-minutes']).to eq(15) + commands = job['steps'].filter_map { |step| step['run'] }.join("\n") + expect(commands).to include('--archspec', 'real_project.rb', 'semantic/probes.rb') + expect(commands).not_to include('bundle update', 'gem push') + actions = job['steps'].filter_map { |step| step['uses'] } + expect(actions).to all(match(/@[a-f0-9]{40}\z/)) + checkout = job['steps'].find { |step| step.dig('with', 'repository') == 'discourse/discourse' } + expect(checkout['with']['ref']).to eq('2de9c9be4f89e392fe500dd27f928d6b1184bf09') + expect(checkout['with']['persist-credentials']).to be(false) + end +end