archunit 0.0.1 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. checksums.yaml +4 -4
  2. data/API.md +498 -0
  3. data/CHANGELOG.md +85 -0
  4. data/CODE_OF_CONDUCT.md +40 -0
  5. data/CONTRIBUTING.md +75 -0
  6. data/GUIDE.md +804 -0
  7. data/README.md +224 -289
  8. data/SECURITY.md +64 -0
  9. data/SUPPORT.md +23 -0
  10. data/assets/logo-rounded.png +0 -0
  11. data/exe/archunit +7 -0
  12. data/lib/archunit/cli/analysis_report.rb +62 -0
  13. data/lib/archunit/cli/analysis_text.rb +25 -0
  14. data/lib/archunit/cli/baseline_context.rb +42 -0
  15. data/lib/archunit/cli/baseline_document.rb +58 -0
  16. data/lib/archunit/cli/baseline_fingerprint.rb +36 -0
  17. data/lib/archunit/cli/baseline_identity.rb +85 -0
  18. data/lib/archunit/cli/baseline_ledger.rb +38 -0
  19. data/lib/archunit/cli/baseline_object.rb +15 -0
  20. data/lib/archunit/cli/baseline_options.rb +48 -0
  21. data/lib/archunit/cli/baseline_run.rb +85 -0
  22. data/lib/archunit/cli/baseline_schema.rb +53 -0
  23. data/lib/archunit/cli/baseline_text.rb +31 -0
  24. data/lib/archunit/cli/configuration.rb +93 -0
  25. data/lib/archunit/cli/options.rb +117 -0
  26. data/lib/archunit/cli/report.rb +121 -0
  27. data/lib/archunit/cli/runner.rb +108 -0
  28. data/lib/archunit/cli.rb +15 -0
  29. data/lib/archunit/common/extraction/dependency_evidence.rb +44 -0
  30. data/lib/archunit/common/extraction/edge.rb +7 -2
  31. data/lib/archunit/common/extraction/import_kind.rb +4 -1
  32. data/lib/archunit/common/extraction/parse_diagnostic.rb +23 -0
  33. data/lib/archunit/common/extraction/source_exclusions.rb +43 -0
  34. data/lib/archunit/common/fluentapi/check_options.rb +53 -2
  35. data/lib/archunit/common/fluentapi/checkable.rb +25 -1
  36. data/lib/archunit/common/logging/check_logger.rb +8 -0
  37. data/lib/archunit/common/logging/inspection.rb +59 -0
  38. data/lib/archunit/common/logging/logging_options.rb +5 -0
  39. data/lib/archunit/common/pattern.rb +18 -8
  40. data/lib/archunit/common/projection/cycles/johnson_cycles.rb +35 -19
  41. data/lib/archunit/common/projection/cycles/tarjan_scc.rb +30 -10
  42. data/lib/archunit/error/source_parse_error.rb +38 -0
  43. data/lib/archunit/extraction/analysis_observer.rb +24 -0
  44. data/lib/archunit/extraction/analysis_profile.rb +30 -0
  45. data/lib/archunit/extraction/analysis_snapshot.rb +51 -0
  46. data/lib/archunit/extraction/arch_ignore.rb +91 -0
  47. data/lib/archunit/extraction/conservative_local_flow.rb +100 -0
  48. data/lib/archunit/extraction/constant_index.rb +110 -0
  49. data/lib/archunit/extraction/constant_visitor.rb +137 -0
  50. data/lib/archunit/extraction/dependency_context.rb +30 -0
  51. data/lib/archunit/extraction/discover_gemspec_load_paths.rb +96 -0
  52. data/lib/archunit/extraction/enumerate_source_files.rb +36 -9
  53. data/lib/archunit/extraction/extract_dependencies.rb +74 -15
  54. data/lib/archunit/extraction/extract_graph.rb +74 -40
  55. data/lib/archunit/extraction/extract_imports.rb +57 -124
  56. data/lib/archunit/extraction/extraction_profile.rb +105 -0
  57. data/lib/archunit/extraction/graph_assembly.rb +32 -0
  58. data/lib/archunit/extraction/graph_cache_key.rb +27 -0
  59. data/lib/archunit/extraction/import_calls.rb +93 -0
  60. data/lib/archunit/extraction/import_resolver.rb +65 -0
  61. data/lib/archunit/extraction/import_source_policy.rb +123 -0
  62. data/lib/archunit/extraction/import_visitor.rb +89 -0
  63. data/lib/archunit/extraction/load_arguments.rb +34 -0
  64. data/lib/archunit/extraction/local_string_tracker.rb +81 -0
  65. data/lib/archunit/extraction/resolve_import.rb +5 -3
  66. data/lib/archunit/extraction/resolve_load_paths.rb +98 -0
  67. data/lib/archunit/extraction/resolved_import.rb +5 -2
  68. data/lib/archunit/extraction/source_analysis.rb +26 -0
  69. data/lib/archunit/extraction/static_import_path.rb +111 -0
  70. data/lib/archunit/extraction/validate_extraction_paths.rb +37 -0
  71. data/lib/archunit/files/extraction/extract_file_info.rb +14 -5
  72. data/lib/archunit/files/extraction/file_info.rb +1 -2
  73. data/lib/archunit/files/fluentapi/depend_on_external_module_condition.rb +2 -0
  74. data/lib/archunit/files/fluentapi/depend_on_external_module_condition_builder.rb +2 -0
  75. data/lib/archunit/files/fluentapi/depend_on_file_condition.rb +6 -0
  76. data/lib/archunit/files/fluentapi/depend_on_file_condition_builder.rb +6 -0
  77. data/lib/archunit/files/fluentapi/file_condition_builder.rb +12 -0
  78. data/lib/archunit/files/fluentapi/file_rule_support.rb +8 -1
  79. data/lib/archunit/files/fluentapi/files.rb +6 -0
  80. data/lib/archunit/files/fluentapi/match_pattern_file_condition_builder.rb +14 -0
  81. data/lib/archunit/files/fluentapi/positive_match_pattern_file_condition_builder.rb +2 -0
  82. data/lib/archunit/graph/fluentapi/graph.rb +5 -0
  83. data/lib/archunit/graph/fluentapi/project_graph_builder.rb +44 -0
  84. data/lib/archunit/graph/projection/aggregate_edges.rb +4 -2
  85. data/lib/archunit/graph/projection/graph_query_options.rb +1 -2
  86. data/lib/archunit/graph/projection/graph_report_edge.rb +12 -2
  87. data/lib/archunit/graph/rendering/json_renderer.rb +3 -1
  88. data/lib/archunit/layers/fluentapi/architecture_preset.rb +49 -0
  89. data/lib/archunit/layers/fluentapi/layer_definition_builder.rb +4 -0
  90. data/lib/archunit/layers/fluentapi/layer_dependency_rule_builder.rb +4 -0
  91. data/lib/archunit/layers/fluentapi/layered_architecture.rb +5 -0
  92. data/lib/archunit/layers/fluentapi/layers.rb +5 -0
  93. data/lib/archunit/layers/fluentapi/preset_definitions.rb +39 -0
  94. data/lib/archunit/layers/fluentapi/preset_options.rb +69 -0
  95. data/lib/archunit/layers/fluentapi/preset_rule.rb +45 -0
  96. data/lib/archunit/metrics/extraction/extract_distance_info.rb +2 -3
  97. data/lib/archunit/metrics/extraction/extract_project_info.rb +14 -10
  98. data/lib/archunit/metrics/extraction/metric_info.rb +2 -4
  99. data/lib/archunit/metrics/extraction/source_metrics_visitor.rb +2 -4
  100. data/lib/archunit/metrics/fluentapi/custom_metric_builder.rb +2 -0
  101. data/lib/archunit/metrics/fluentapi/custom_metric_condition.rb +4 -1
  102. data/lib/archunit/metrics/fluentapi/logged_metric.rb +23 -0
  103. data/lib/archunit/metrics/fluentapi/metric_predicate_condition.rb +4 -1
  104. data/lib/archunit/metrics/fluentapi/metric_report_builder.rb +6 -3
  105. data/lib/archunit/metrics/fluentapi/metric_selection.rb +18 -2
  106. data/lib/archunit/metrics/fluentapi/metric_threshold_condition.rb +2 -1
  107. data/lib/archunit/metrics/fluentapi/metrics.rb +5 -0
  108. data/lib/archunit/metrics/fluentapi/metrics_builder.rb +18 -3
  109. data/lib/archunit/metrics/reporting/metrics_export_options.rb +6 -2
  110. data/lib/archunit/slices/fluentapi/diagram_slice_condition.rb +1 -0
  111. data/lib/archunit/slices/fluentapi/forbidden_slice_dependency_condition.rb +1 -0
  112. data/lib/archunit/slices/fluentapi/negative_slice_condition_builder.rb +2 -0
  113. data/lib/archunit/slices/fluentapi/positive_slice_condition_builder.rb +8 -0
  114. data/lib/archunit/slices/fluentapi/slice_scope_builder.rb +12 -0
  115. data/lib/archunit/slices/fluentapi/slices.rb +5 -0
  116. data/lib/archunit/testing/assert_passes.rb +4 -0
  117. data/lib/archunit/testing/result_factory.rb +16 -4
  118. data/lib/archunit/testing/rspec_adapter.rb +1 -2
  119. data/lib/archunit/testing.rb +7 -3
  120. data/lib/archunit/version.rb +1 -1
  121. data/lib/archunit.rb +11 -0
  122. metadata +67 -9
data/SECURITY.md ADDED
@@ -0,0 +1,64 @@
1
+ # Security Policy
2
+
3
+ ## Supported versions
4
+
5
+ Security fixes target the latest published release and the `main` branch. The published gem and
6
+ development checkout can differ; see [release status](README.md#availability).
7
+
8
+ | Version | Supported |
9
+ | --- | --- |
10
+ | Latest published `1.x` release | Yes |
11
+ | `main` (unreleased development) | Yes |
12
+ | Older releases | No |
13
+
14
+ ## Reporting a vulnerability
15
+
16
+ Please do not open a public issue for a suspected vulnerability. Use GitHub's
17
+ [private vulnerability reporting](https://github.com/dragonsec-ai/ArchUnitRuby/security/advisories/new)
18
+ to share the affected version, impact, reproduction steps, and any suggested mitigation.
19
+
20
+ Do not include real credentials, private source code, or customer data. A minimal synthetic
21
+ reproduction is preferred. The maintainers aim to acknowledge a report within three business days
22
+ and will coordinate validation, remediation, release, and disclosure with the reporter.
23
+
24
+ ## Security model
25
+
26
+ ArchUnitRuby statically reads Ruby source and gemspec text; it does not intentionally execute the
27
+ analyzed project or evaluate gemspecs. Dynamic import expressions are omitted instead of executed.
28
+ Run architecture analysis with the same filesystem permissions you would grant any test tool, and
29
+ review exported reports before sharing them because paths and dependency names may reveal project
30
+ structure.
31
+
32
+ The CLI (1.1+) evaluates trusted `.archunit.rb` rule configuration as executable Ruby, including
33
+ during `explain`. It is not a sandbox. For an untrusted target, supply your own trusted `--config`
34
+ and do not run its Gemfile, tests or application. Baselines are JSON accepted-debt data, not code,
35
+ but changes to them and source exclusions still require review. Concurrent hostile filesystem
36
+ mutation and the security of your Ruby interpreter are outside this library's isolation guarantees.
37
+
38
+ ## Locked dependency scanning
39
+
40
+ `bundle exec rake security` refreshes the public [Ruby advisory database](https://github.com/rubysec/ruby-advisory-db)
41
+ and scans this checkout's `Gemfile.lock` with [bundler-audit](https://github.com/rubysec/bundler-audit).
42
+ The scanner is a development dependency, not a runtime dependency of the published gem.
43
+
44
+ The separate dependency-security workflow runs on pull requests, pushes to `main`, manual dispatch,
45
+ and Mondays at 07:17 UTC after this workflow reaches the default branch. It has read-only repository
46
+ permissions, a ten-minute limit, and retains JSON evidence for 14 days even on failure. No automatic
47
+ advisory exceptions or dependency upgrades are applied.
48
+
49
+ The wrapper normalizes Windows database paths, rejects empty databases, and verifies detection of
50
+ a known-vulnerable synthetic lockfile before accepting a clean result. No vulnerable gem is installed
51
+ or executed for that health check. Failed database updates fail the scan rather than silently using
52
+ stale data. Reports include the advisory count and database commit.
53
+
54
+ For an explicitly offline repeat using an already downloaded database:
55
+
56
+ ~~~bash
57
+ bundle exec ruby scripts/check_dependency_security.rb --no-update
58
+ ~~~
59
+
60
+ The report is saved to `pkg/dependency-audit.json`; `--database PATH` and `--output PATH` override
61
+ locations. A clean scan means no matches in that database snapshot, not a security certification.
62
+ It does not audit Ruby itself, all versions allowed by the gemspec, or an application's unrelated
63
+ dependency lockfile. Default tests remain offline; only the separate security task refreshes data.
64
+
data/SUPPORT.md ADDED
@@ -0,0 +1,23 @@
1
+ # ArchUnitRuby Support
2
+
3
+ ## Using the library
4
+
5
+ Start with the [quickstart](README.md#quickstart), then use the [user guide](GUIDE.md),
6
+ [API contract](API.md) and searchable
7
+ [reference](https://dragonsec-ai.github.io/ArchUnitRuby/class_list.html).
8
+
9
+ For questions, unexpected rule output, or feature ideas, search and then open a
10
+ [GitHub issue](https://github.com/dragonsec-ai/ArchUnitRuby/issues). Include:
11
+
12
+ - ArchUnitRuby and Ruby versions;
13
+ - operating system and test framework;
14
+ - the smallest architecture rule and project layout that reproduce the behavior;
15
+ - expected and actual violations, with sensitive paths or code removed.
16
+
17
+ The documented API has a [1.x compatibility contract](API.md#compatibility). Features added in
18
+ 1.1 are labeled separately; include your exact version and whether you installed from RubyGems or
19
+ a Git checkout. See [release status](README.md#availability) and [limitations](README.md#limitations).
20
+
21
+ Suspected vulnerabilities belong in a private report following [SECURITY.md](SECURITY.md), never in
22
+ a public support issue.
23
+
Binary file
data/exe/archunit ADDED
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require 'archunit'
5
+ require 'archunit/cli'
6
+
7
+ exit ArchUnit::CLI.run(ARGV)
@@ -0,0 +1,62 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ArchUnit
4
+ module CLI
5
+ # Groups observations by immutable analysis identity, never summing overlapping scopes.
6
+ # @api private
7
+ class AnalysisReport
8
+ NOTICE = 'Counts describe bounded static analysis, not semantic coverage or proven missed ' \
9
+ 'dependencies. A passing policy is not proof of complete runtime architecture.'
10
+
11
+ def initialize
12
+ @scopes = {}.compare_by_identity
13
+ @rules = []
14
+ end
15
+
16
+ def for_rule(name)
17
+ previous = @current_rule
18
+ @current_rule = name
19
+ @rules << name unless @rules.include?(name)
20
+ yield
21
+ ensure
22
+ @current_rule = previous
23
+ end
24
+
25
+ def observe(snapshot, cache_hit: false)
26
+ scope = scope_for(snapshot)
27
+ scope[:observations] += 1
28
+ scope[:cache_hits] += 1 if cache_hit
29
+ names = scope[:rule_names]
30
+ names << @current_rule if @current_rule && !names.include?(@current_rule)
31
+ end
32
+
33
+ def for_name(name)
34
+ scopes = @scopes.values.select { |scope| scope[:rule_names].include?(name) }
35
+ { status: availability(scopes), scope_ids: scopes.map { |scope| scope[:id] } }
36
+ end
37
+
38
+ def to_h
39
+ scopes = @scopes.values.map { |scope| scope.merge(rule_names: scope[:rule_names].dup) }
40
+ status = availability(scopes)
41
+ if status == 'available' && @rules.any? { |name| for_name(name)[:status] != 'available' }
42
+ status = 'partial'
43
+ end
44
+ { status:, scopes:, notice: NOTICE }
45
+ end
46
+
47
+ private
48
+
49
+ def scope_for(snapshot)
50
+ @scopes[snapshot] ||= snapshot.merge(
51
+ id: @scopes.length + 1, observations: 0, cache_hits: 0, rule_names: []
52
+ )
53
+ end
54
+
55
+ def availability(scopes)
56
+ return 'unavailable' if scopes.empty?
57
+
58
+ scopes.all? { |scope| scope[:status] == 'analyzed' } ? 'available' : 'partial'
59
+ end
60
+ end
61
+ end
62
+ end
@@ -0,0 +1,25 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ArchUnit
4
+ module CLI
5
+ # Concise human diagnostics; nil remains unavailable, never zero.
6
+ # @api private
7
+ module AnalysisText
8
+ def self.write(analysis, out)
9
+ out.puts("Analysis: #{analysis[:status]}")
10
+ analysis[:scopes].each { |scope| write_scope(scope, out) }
11
+ out.puts(analysis[:notice]) unless analysis[:scopes].empty?
12
+ end
13
+
14
+ def self.write_scope(scope, out)
15
+ mode = scope[:dependency_analysis] || 'source metrics (dependency analysis unavailable)'
16
+ out.puts(" Scope #{scope[:id]}: #{scope[:project_root]} — #{mode}; #{scope[:status]}")
17
+ counts = scope[:counters].map do |name, value|
18
+ "#{name}=#{value.nil? ? 'unavailable' : value}"
19
+ end
20
+ out.puts(" #{counts.join(', ')}; cache_hits=#{scope[:cache_hits]}")
21
+ end
22
+ private_class_method :write_scope
23
+ end
24
+ end
25
+ end
@@ -0,0 +1,42 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'pathname'
4
+ require 'json'
5
+
6
+ module ArchUnit
7
+ module CLI
8
+ # Scope settings prevent an imports-only acceptance from hiding expanded-analysis findings.
9
+ # @api private
10
+ module BaselineContext
11
+ def self.for(name, analysis, project_root)
12
+ scopes = analysis[:scopes].select { |scope| scope[:rule_names].include?(name) }
13
+ return if scopes.empty? || scopes.any? { |scope| scope[:status] != 'analyzed' }
14
+
15
+ contexts = scopes.map { |scope| settings(scope, project_root) }.uniq
16
+ contexts.sort_by { |item| JSON.generate(item) }
17
+ end
18
+
19
+ def self.settings(scope, root)
20
+ {
21
+ 'root' => relative(scope[:project_root], root), 'kind' => scope[:kind],
22
+ 'dependency_analysis' => scope[:dependency_analysis],
23
+ 'rails_imports' => scope[:rails_imports], 'load_paths' => load_paths(scope),
24
+ 'source_exclusions' => scope[:effective_source_exclusions]
25
+ }
26
+ end
27
+
28
+ def self.relative(path, root)
29
+ Pathname.new(path).relative_path_from(Pathname.new(root).realpath).to_s.tr('\\', '/')
30
+ end
31
+
32
+ def self.load_path(path, root)
33
+ Pathname.new(path).absolute? ? relative(path, root) : path
34
+ end
35
+
36
+ def self.load_paths(scope)
37
+ scope[:load_paths]&.map { |path| load_path(path, scope[:project_root]) }&.sort
38
+ end
39
+ private_class_method :settings, :relative, :load_path, :load_paths
40
+ end
41
+ end
42
+ end
@@ -0,0 +1,58 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json'
4
+ require 'tempfile'
5
+ require_relative 'baseline_schema'
6
+ require_relative 'baseline_object'
7
+
8
+ module ArchUnit
9
+ module CLI
10
+ # Strict, bounded JSON input and explicit, atomic accepted-debt output.
11
+ # @api private
12
+ module BaselineDocument
13
+ MAX_BYTES = 2_000_000
14
+ private_constant :MAX_BYTES
15
+
16
+ def self.load(path)
17
+ validate_regular_file(path)
18
+ bytes = File.open(path, 'rb') { |file| file.read(MAX_BYTES + 1) }
19
+ raise ArgumentError, 'baseline exceeds 2 MB' if bytes.bytesize > MAX_BYTES
20
+
21
+ document = JSON.parse(bytes, max_nesting: 32, object_class: BaselineObject)
22
+ BaselineSchema.validate(document)
23
+ rescue JSON::ParserError => e
24
+ raise ArgumentError, "invalid baseline JSON: #{e.message}"
25
+ end
26
+
27
+ def self.write(path, entries, force: false)
28
+ document = { 'schema_version' => 1, 'fingerprint_version' => 1, 'entries' => entries }
29
+ json = "#{JSON.pretty_generate(document)}\n"
30
+ BaselineSchema.validate(JSON.parse(json))
31
+ raise ArgumentError, 'baseline exceeds 2 MB' if json.bytesize > MAX_BYTES
32
+
33
+ atomic_write(path, json, force:)
34
+ end
35
+
36
+ def self.atomic_write(path, json, force:)
37
+ Tempfile.create(['.archunit-baseline-', '.json'], File.dirname(path)) do |file|
38
+ file.write(json)
39
+ file.close
40
+ force ? replace(file.path, path) : File.link(file.path, path)
41
+ end
42
+ end
43
+
44
+ def self.replace(temporary, path)
45
+ validate_regular_file(path) if File.exist?(path) || File.symlink?(path)
46
+ File.rename(temporary, path)
47
+ end
48
+
49
+ def self.validate_regular_file(path)
50
+ stat = File.lstat(path)
51
+ return if stat.file? && !stat.symlink?
52
+
53
+ raise ArgumentError, 'baseline must be a regular file, not a symlink or directory'
54
+ end
55
+ private_class_method :atomic_write, :replace, :validate_regular_file
56
+ end
57
+ end
58
+ end
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'digest'
4
+ require 'json'
5
+ require_relative 'baseline_identity'
6
+ require_relative 'baseline_context'
7
+
8
+ module ArchUnit
9
+ module CLI
10
+ # Version-one fingerprints are structured data, not formatter prose or source locations.
11
+ # @api private
12
+ module BaselineFingerprint
13
+ def self.entry(name, violation, context)
14
+ data = BaselineIdentity.for(violation)
15
+ return unless data && context
16
+
17
+ entry = { 'rule' => name, 'type' => violation.class.name, 'data' => data,
18
+ 'context' => context }
19
+ entry.merge('fingerprint' => digest(entry), 'count' => 1)
20
+ end
21
+
22
+ def self.digest(entry)
23
+ identity = entry.except('fingerprint', 'count')
24
+ Digest::SHA256.hexdigest(JSON.generate(canonical(identity)))
25
+ end
26
+
27
+ def self.canonical(value)
28
+ case value
29
+ when Hash then value.keys.sort.to_h { |key| [key, canonical(value.fetch(key))] }
30
+ when Array then value.map { |item| canonical(item) }
31
+ else value
32
+ end
33
+ end
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,85 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative '../testing/violation_factory'
4
+ require 'json'
5
+
6
+ module ArchUnit
7
+ module CLI
8
+ # Explicit adapters: unknown/custom/empty-selection failures are never accepted implicitly.
9
+ # @api private
10
+ module BaselineIdentity
11
+ TYPES = {
12
+ Files::Assertion::FileDependencyViolation => :dependency,
13
+ Files::Assertion::ExternalModuleDependencyViolation => :dependency,
14
+ Files::Assertion::FilePatternViolation => :pattern,
15
+ Files::Assertion::CycleViolation => :cycle,
16
+ Layers::Assertion::LayerDependencyViolation => :layer,
17
+ Slices::Assertion::SliceDependencyViolation => :slice,
18
+ Metrics::Assertion::MetricThresholdViolation => :threshold
19
+ }.freeze
20
+ private_constant :TYPES
21
+
22
+ def self.for(violation)
23
+ adapter = TYPES[violation.class]
24
+ send(adapter, violation) if adapter
25
+ end
26
+
27
+ def self.dependency(value)
28
+ { 'edge' => edge(value.dependency), 'negated' => value.negated? }
29
+ end
30
+
31
+ def self.edge(value)
32
+ pairs = value.cumulated_edges.map do |raw|
33
+ [identifier(raw.source), identifier(raw.target), raw.external]
34
+ end
35
+ [identifier(value.source_label), identifier(value.target_label), pairs.uniq.sort]
36
+ end
37
+
38
+ def self.layer(value)
39
+ { 'edge' => edge(value.dependency), 'source_layer' => value.source_layer,
40
+ 'target_layer' => value.target_layer, 'predicate' => value.rule.to_s }
41
+ end
42
+
43
+ def self.slice(value)
44
+ dependency(value).merge('source_slice' => value.source_slice,
45
+ 'target_slice' => value.target_slice,
46
+ 'predicate' => value.rule.to_s)
47
+ end
48
+
49
+ def self.pattern(value)
50
+ { 'file' => identifier(value.projected_node.label), 'filter' => filter(value.check_filter),
51
+ 'negated' => value.negated? }
52
+ end
53
+
54
+ def self.filter(value)
55
+ [value.regexp.source, value.regexp.options, value.target.to_s, value.matching.to_s,
56
+ value.exclusions.map { |item| filter(item) }.sort_by { |item| JSON.generate(item) }]
57
+ end
58
+
59
+ def self.cycle(value)
60
+ edges = value.cycle.map { |item| edge(item) }
61
+ return unless edges.map(&:first).uniq.length == edges.length
62
+
63
+ start = edges.each_index.min_by { |index| JSON.generate(edges[index]) }
64
+ { 'cycle' => edges.rotate(start) }
65
+ end
66
+
67
+ def self.threshold(value)
68
+ { 'subject' => identifier(value.identifier), 'metric' => value.metric_name.to_s,
69
+ 'value' => value.value, 'threshold' => value.threshold,
70
+ 'comparison' => value.comparison.to_s }
71
+ end
72
+
73
+ def self.identifier(value)
74
+ normalized = value.tr('\\', '/')
75
+ if normalized.start_with?('/') || normalized.match?(/\A[a-z]:/i)
76
+ raise ArgumentError, 'baseline identities require project-relative identifiers'
77
+ end
78
+
79
+ normalized
80
+ end
81
+ private_class_method :dependency, :edge, :layer, :slice, :pattern, :filter, :cycle,
82
+ :threshold, :identifier
83
+ end
84
+ end
85
+ end
@@ -0,0 +1,38 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ArchUnit
4
+ module CLI
5
+ # One-to-one matching; duplicate occurrences cannot share one accepted-debt entry.
6
+ # @api private
7
+ class BaselineLedger
8
+ def initialize(entries)
9
+ @entries = entries
10
+ @remaining = entries.to_h { |entry| [entry['fingerprint'], entry['count']] }
11
+ end
12
+
13
+ def classify(entry)
14
+ id = entry&.fetch('fingerprint')
15
+ accepted = id && @remaining.fetch(id, 0).positive?
16
+ @remaining[id] -= 1 if accepted
17
+ { status: accepted ? 'accepted' : 'new', fingerprint: id }
18
+ end
19
+
20
+ def stale_entries
21
+ @entries.filter_map do |entry|
22
+ count = @remaining.fetch(entry['fingerprint'])
23
+ entry.merge('count' => count) if count.positive?
24
+ end
25
+ end
26
+
27
+ def self.group(records)
28
+ if records.any?(&:nil?)
29
+ raise ArgumentError, 'cannot baseline empty, custom/unsupported or unobserved violations'
30
+ end
31
+
32
+ groups = records.group_by { |entry| entry['fingerprint'] }.values
33
+ entries = groups.map { |group| group.first.merge('count' => group.length) }
34
+ entries.sort_by { |entry| entry['fingerprint'] }
35
+ end
36
+ end
37
+ end
38
+ end
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ArchUnit
4
+ module CLI
5
+ # JSON duplicate members are ambiguous configuration, not a last-key-wins policy.
6
+ # @api private
7
+ class BaselineObject < Hash
8
+ def []=(key, value)
9
+ raise ArgumentError, "duplicate baseline JSON member: #{key}" if key?(key)
10
+
11
+ super
12
+ end
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,48 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ArchUnit
4
+ module CLI
5
+ # Separate parsing keeps accepted-debt writes explicit and check commands read-only.
6
+ # @api private
7
+ module BaselineOptions
8
+ attr_reader :baseline_path, :output_path
9
+
10
+ def force
11
+ @force || false
12
+ end
13
+
14
+ private
15
+
16
+ def baseline_options(options)
17
+ options.on('--baseline FILE', 'Check accepted debt (check only)') do |value|
18
+ @baseline_path = File.expand_path(value, @cwd)
19
+ end
20
+ options.on('--output FILE', 'Write accepted debt (baseline command only)') do |value|
21
+ @output_path = File.expand_path(value, @cwd)
22
+ end
23
+ options.on('--force', 'Replace existing regular baseline output') { @force = true }
24
+ end
25
+
26
+ def validate_baseline_options
27
+ return if %w[help version].include?(command)
28
+
29
+ if baseline_path && command != 'check'
30
+ raise ArgumentError, '--baseline is only valid for check'
31
+ end
32
+
33
+ return validate_baseline_output if command == 'baseline'
34
+
35
+ return unless output_path || force
36
+
37
+ raise ArgumentError, '--output and --force are only valid for baseline'
38
+ end
39
+
40
+ def validate_baseline_output
41
+ raise ArgumentError, 'baseline requires --output FILE' unless output_path
42
+ return if File.extname(output_path) == '.json'
43
+
44
+ raise ArgumentError, 'baseline output must have a .json extension'
45
+ end
46
+ end
47
+ end
48
+ end
@@ -0,0 +1,85 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'baseline_document'
4
+ require_relative 'baseline_ledger'
5
+
6
+ module ArchUnit
7
+ module CLI
8
+ # Baselines classify evaluated violations; they never skip source or alter Checkable results.
9
+ # @api private
10
+ class BaselineRun
11
+ def initialize(options)
12
+ @options = options
13
+ end
14
+
15
+ def finish(report, evaluations)
16
+ return finish_normal(report) unless @options.baseline_path || @options.command == 'baseline'
17
+
18
+ records = records_for(report, evaluations)
19
+ return create(report, records) if @options.command == 'baseline'
20
+
21
+ apply(report, records)
22
+ end
23
+
24
+ private
25
+
26
+ def finish_normal(report)
27
+ failed = report.payload[:rules].any? { |rule| rule[:status] == 'failed' }
28
+ report.finish(failed ? 'failed' : 'passed')
29
+ failed ? 1 : 0
30
+ end
31
+
32
+ def records_for(report, evaluations)
33
+ evaluations.flat_map do |name, violations|
34
+ context = BaselineContext.for(name, report.payload[:analysis], @options.project_root)
35
+ violations.map { |violation| BaselineFingerprint.entry(name, violation, context) }
36
+ end
37
+ end
38
+
39
+ def create(report, records)
40
+ entries = BaselineLedger.group(records)
41
+ BaselineDocument.write(@options.output_path, entries, force: @options.force)
42
+ report.payload[:baseline] = { status: 'created', path: @options.output_path,
43
+ accepted_count: records.length, entries: entries.length }
44
+ report.finish('baseline_created')
45
+ 0
46
+ end
47
+
48
+ def apply(report, records)
49
+ ledger = BaselineLedger.new(BaselineDocument.load(@options.baseline_path))
50
+ classify(report, records, ledger)
51
+ finish_baseline(report, ledger.stale_entries)
52
+ end
53
+
54
+ def classify(report, records, ledger)
55
+ report.payload[:rules].each do |rule|
56
+ rule[:violations].each do |violation|
57
+ violation[:baseline] = ledger.classify(records.shift)
58
+ end
59
+ update_rule_status(rule) unless rule[:violations].empty?
60
+ end
61
+ end
62
+
63
+ def update_rule_status(rule)
64
+ accepted = rule[:violations].all? { |value| value[:baseline][:status] == 'accepted' }
65
+ rule[:status] = accepted ? 'accepted' : 'failed'
66
+ end
67
+
68
+ def finish_baseline(report, stale)
69
+ summary = baseline_summary(report, stale)
70
+ report.payload[:baseline] = summary.merge(status: 'checked', path: @options.baseline_path)
71
+ failed = summary[:new_count].positive? || summary[:stale_count].positive?
72
+ clean_status = summary[:accepted_count].positive? ? 'accepted' : 'passed'
73
+ report.finish(failed ? 'failed' : clean_status)
74
+ failed ? 1 : 0
75
+ end
76
+
77
+ def baseline_summary(report, stale)
78
+ violations = report.payload[:rules].flat_map { |rule| rule[:violations] }
79
+ accepted = violations.count { |v| v[:baseline][:status] == 'accepted' }
80
+ { accepted_count: accepted, new_count: violations.length - accepted,
81
+ stale_count: stale.sum { |entry| entry['count'] }, stale_entries: stale }
82
+ end
83
+ end
84
+ end
85
+ end
@@ -0,0 +1,53 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'baseline_fingerprint'
4
+
5
+ module ArchUnit
6
+ module CLI
7
+ # Pure format validation, including identity/data consistency (not authentication).
8
+ # @api private
9
+ module BaselineSchema
10
+ HEADER = %w[entries fingerprint_version schema_version].freeze
11
+ ENTRY = %w[context count data fingerprint rule type].freeze
12
+ private_constant :HEADER, :ENTRY
13
+
14
+ def self.validate(document)
15
+ unless valid_header?(document)
16
+ raise ArgumentError, 'invalid baseline schema (expected schema/fingerprint version 1)'
17
+ end
18
+
19
+ entries = document.fetch('entries').map { |entry| validate_entry(entry) }
20
+ ids = entries.map { |entry| entry['fingerprint'] }
21
+ raise ArgumentError, 'duplicate baseline fingerprints' unless ids.uniq.length == ids.length
22
+
23
+ entries
24
+ end
25
+
26
+ def self.valid_header?(document)
27
+ document.is_a?(Hash) && document.keys.sort == HEADER &&
28
+ document.values_at('schema_version', 'fingerprint_version').all? { |v| v.eql?(1) } &&
29
+ document['entries'].is_a?(Array) && document['entries'].length <= 10_000
30
+ end
31
+
32
+ def self.validate_entry(entry)
33
+ unless entry.is_a?(Hash) && entry.keys.sort == ENTRY && valid_identity?(entry) &&
34
+ valid_count?(entry['count']) &&
35
+ entry['fingerprint'] == BaselineFingerprint.digest(entry)
36
+ raise ArgumentError, 'invalid baseline entry or fingerprint'
37
+ end
38
+
39
+ entry
40
+ end
41
+
42
+ def self.valid_count?(value)
43
+ value.is_a?(Integer) && value.between?(1, 1_000_000)
44
+ end
45
+
46
+ def self.valid_identity?(entry)
47
+ %w[rule type].all? { |key| entry[key].is_a?(String) && !entry[key].empty? } &&
48
+ entry['data'].is_a?(Hash) && entry['context'].is_a?(Array) && !entry['context'].empty?
49
+ end
50
+ private_class_method :valid_header?, :validate_entry, :valid_count?, :valid_identity?
51
+ end
52
+ end
53
+ end