archunit 1.0.0 → 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 (62) hide show
  1. checksums.yaml +4 -4
  2. data/API.md +213 -5
  3. data/CHANGELOG.md +41 -1
  4. data/CODE_OF_CONDUCT.md +40 -0
  5. data/CONTRIBUTING.md +75 -0
  6. data/GUIDE.md +804 -0
  7. data/README.md +198 -562
  8. data/SECURITY.md +64 -0
  9. data/SUPPORT.md +23 -0
  10. data/exe/archunit +7 -0
  11. data/lib/archunit/cli/analysis_report.rb +62 -0
  12. data/lib/archunit/cli/analysis_text.rb +25 -0
  13. data/lib/archunit/cli/baseline_context.rb +42 -0
  14. data/lib/archunit/cli/baseline_document.rb +58 -0
  15. data/lib/archunit/cli/baseline_fingerprint.rb +36 -0
  16. data/lib/archunit/cli/baseline_identity.rb +85 -0
  17. data/lib/archunit/cli/baseline_ledger.rb +38 -0
  18. data/lib/archunit/cli/baseline_object.rb +15 -0
  19. data/lib/archunit/cli/baseline_options.rb +48 -0
  20. data/lib/archunit/cli/baseline_run.rb +85 -0
  21. data/lib/archunit/cli/baseline_schema.rb +53 -0
  22. data/lib/archunit/cli/baseline_text.rb +31 -0
  23. data/lib/archunit/cli/configuration.rb +93 -0
  24. data/lib/archunit/cli/options.rb +117 -0
  25. data/lib/archunit/cli/report.rb +121 -0
  26. data/lib/archunit/cli/runner.rb +108 -0
  27. data/lib/archunit/cli.rb +15 -0
  28. data/lib/archunit/common/extraction/import_kind.rb +3 -1
  29. data/lib/archunit/common/extraction/source_exclusions.rb +43 -0
  30. data/lib/archunit/common/fluentapi/check_options.rb +13 -3
  31. data/lib/archunit/extraction/analysis_observer.rb +24 -0
  32. data/lib/archunit/extraction/analysis_profile.rb +30 -0
  33. data/lib/archunit/extraction/analysis_snapshot.rb +51 -0
  34. data/lib/archunit/extraction/constant_visitor.rb +8 -0
  35. data/lib/archunit/extraction/dependency_context.rb +30 -0
  36. data/lib/archunit/extraction/enumerate_source_files.rb +17 -5
  37. data/lib/archunit/extraction/extract_dependencies.rb +5 -14
  38. data/lib/archunit/extraction/extract_graph.rb +45 -55
  39. data/lib/archunit/extraction/extract_imports.rb +11 -14
  40. data/lib/archunit/extraction/graph_assembly.rb +32 -0
  41. data/lib/archunit/extraction/graph_cache_key.rb +27 -0
  42. data/lib/archunit/extraction/import_calls.rb +93 -0
  43. data/lib/archunit/extraction/import_resolver.rb +11 -2
  44. data/lib/archunit/extraction/import_source_policy.rb +123 -0
  45. data/lib/archunit/extraction/import_visitor.rb +31 -46
  46. data/lib/archunit/extraction/load_arguments.rb +34 -0
  47. data/lib/archunit/extraction/local_string_tracker.rb +4 -3
  48. data/lib/archunit/extraction/resolve_load_paths.rb +5 -0
  49. data/lib/archunit/extraction/source_analysis.rb +26 -0
  50. data/lib/archunit/extraction/static_import_path.rb +111 -0
  51. data/lib/archunit/layers/fluentapi/architecture_preset.rb +49 -0
  52. data/lib/archunit/layers/fluentapi/preset_definitions.rb +39 -0
  53. data/lib/archunit/layers/fluentapi/preset_options.rb +69 -0
  54. data/lib/archunit/layers/fluentapi/preset_rule.rb +45 -0
  55. data/lib/archunit/metrics/extraction/extract_distance_info.rb +1 -1
  56. data/lib/archunit/metrics/extraction/extract_project_info.rb +8 -4
  57. data/lib/archunit/metrics/fluentapi/metric_report_builder.rb +4 -3
  58. data/lib/archunit/metrics/fluentapi/metrics_builder.rb +3 -3
  59. data/lib/archunit/metrics/reporting/metrics_export_options.rb +6 -2
  60. data/lib/archunit/version.rb +1 -1
  61. data/lib/archunit.rb +2 -0
  62. metadata +48 -8
data/GUIDE.md ADDED
@@ -0,0 +1,804 @@
1
+ # ArchUnitRuby user guide
2
+
3
+ Recipes and operational details for the 1.x API, including the additions in 1.1.
4
+ Start with the [README](README.md#quickstart), use this guide for complete workflows, and consult
5
+ the [API contract](API.md) for exact semantics. The documentation site follows `main`, not the
6
+ published gem. CLI, baselines, presets, Rails helper imports and caller-owned exclusions require
7
+ 1.1 or newer; they are not included in 1.0.0. Check [RubyGems](https://rubygems.org/gems/archunit)
8
+ for published versions.
9
+
10
+ [Projects, selectors and options](#projects) · [Rule recipes](#recipes) · [Test-framework integration](#frameworks) · [Logging and failure reports](#logging) · [Static analysis and Ruby resolution](#analysis) · [Command line (1.1+)](#cli) · [Architecture presets (1.1+)](#presets) · [Example project and dogfooding](#example) · [Development and validation](#development) · [Compatibility and migration](#migration)
11
+
12
+ <a id="projects"></a>
13
+
14
+ ## Projects, selectors and options
15
+
16
+ ### Explain why a rule exists
17
+
18
+ Append `.because(...)` to a completed file, layer, slice, or metric rule:
19
+
20
+ ~~~ ruby
21
+ rule = ArchUnit.project_files.in_folder('app/api/**')
22
+ .should_not.depend_on_files.in_folder('app/database/**')
23
+ .because('Keep persistence out of the API')
24
+
25
+ expect(rule).to pass
26
+ ~~~
27
+
28
+ The explanation appears once in a failed RSpec, Minitest, or `ArchUnit.assert_passes` assertion.
29
+ It is available as `rule.rationale`. Calling `.because(...)` returns a distinct frozen rule;
30
+ the original rule and direct `check` results are unchanged. Reasons must be non-blank strings.
31
+ Add the explanation after all selectors and modifiers.
32
+
33
+ ### Project Location
34
+
35
+ The project locator is optional. With no argument, ArchUnitRuby searches from the current directory
36
+ for a `Gemfile` or gemspec. Pass a directory or either marker file when analyzing another project:
37
+
38
+ ~~~ ruby
39
+ ArchUnit.project_files('/workspace/my_app')
40
+ ArchUnit.project_files('/workspace/my_app/Gemfile')
41
+ ~~~
42
+
43
+ Source discovery skips symlinked files and directories, including project-local aliases. This
44
+ avoids duplicate file identities and unintentionally parsing linked source outside the project.
45
+ Direct file-information extraction also checks the canonical source path against the project root.
46
+
47
+ ### Project-wide exclusions
48
+
49
+ Add a `.archignore` at the detected project root to keep generated or intentionally out-of-scope
50
+ Ruby files out of dependency graphs and file-based metrics:
51
+
52
+ ~~~ text
53
+ # Architecture exclusions (not a full gitignore parser)
54
+ /db/migrate/
55
+ generated/
56
+ **/*_generated.rb
57
+ ~~~
58
+
59
+ Blank lines and full-line `#` comments are ignored. Bare names match at any directory depth;
60
+ patterns containing `/` are project-relative, and a leading `/` anchors a pattern to the root.
61
+ A trailing `/` matches directories and their descendants, not similarly named files. Windows
62
+ separators are normalized. Only the root file is read; nested `.archignore` files are not inherited.
63
+
64
+ These patterns combine with the built-in exclusions or explicit `exclude_patterns:`; `[]` disables
65
+ the defaults, not `.archignore`. Effective pattern changes automatically select a fresh cached graph.
66
+ Source-code edits still require `clear_cache: true` in a long-lived process. The file is limited to
67
+ 1 MiB, must be a regular non-symlink file, and is decoded as UTF-8 with invalid bytes replaced.
68
+ Negation (`!pattern`), NUL characters, and a bare `/` are rejected with `ArchUnit::UserError`.
69
+ No configuration or application code is executed.
70
+
71
+ For read-only audits, 1.1 also accepts caller-owned exclusions without creating or
72
+ editing a target `.archignore`:
73
+
74
+ ~~~ ruby
75
+ options = ArchUnit::CheckOptions.new(
76
+ source_exclusions: ['lib/generators/active_record/templates/migration.rb']
77
+ )
78
+ violations = rule.check(options)
79
+ graph = ArchUnit.project_graph.with_check_options(options).to_json
80
+ counts = ArchUnit.metrics.count.classes.measure(options)
81
+ report_options = ArchUnit::MetricsExportOptions.new(check_options: options)
82
+ ArchUnit.metrics.count.export_as_html('metrics.html', report_options)
83
+ ~~~
84
+
85
+ ~~~ sh
86
+ bundle exec archunit check --config /path/to/your/trusted-rules.rb \
87
+ --exclude-source 'lib/generators/active_record/templates/migration.rb' \
88
+ --exclude-source 'lib/generators/active_record/templates/migration_existing.rb'
89
+ ~~~
90
+
91
+ `source_exclusions` is an immutable array of project-relative globs. It is **additive** to defaults
92
+ and root `.archignore`; it never re-enables repository-excluded files. Only the low-level legacy
93
+ `exclude_patterns: []` argument disables defaults, and repository/caller exclusions still apply.
94
+ Separators and leading `./` normalize, directory-only patterns retain their meaning, and duplicates
95
+ or ordering do not create a different graph-cache entry. Negation, parent traversal, drive/UNC
96
+ paths, NUL/newlines, empty patterns and a bare `/` are rejected.
97
+
98
+ Graphs, source metrics, coupling metrics and reports share this source policy. Fluent selectors
99
+ such as `.in_path('app/**')` select rule subjects **after** whole-project discovery; they do not
100
+ exclude generator templates from parsing. Included malformed Ruby remains `SourceParseError`
101
+ (CLI exit 2); zero selected subjects remain violations. No directory named `templates` is ignored
102
+ automatically: exclude only identified non-source files, or fix actual Ruby syntax errors.
103
+
104
+ ### Fluent Grammar
105
+
106
+ Every rule is built left to right from the same small grammar:
107
+
108
+ | Stage | Purpose | Examples |
109
+ | --- | --- | --- |
110
+ | Entry | Choose the architectural vocabulary | `project_files`, `project_layers`, `project_slices`, `project_graph`, `metrics` |
111
+ | Scope | Select subjects; repeated scopes use AND | `in_folder`, `in_path`, `with_name`, `for_classes_matching` |
112
+ | Mood | Choose the expected direction | `should`, `should_not` |
113
+ | Predicate | State the policy | `have_no_cycles`, `depend_on_files`, `adhere_to_diagram` |
114
+ | Object | Select the target of a relational rule | `in_folder`, `matching`, a layer or slice name |
115
+ | Terminal | Execute or render | `check`, `to_json`, `export_as_html`, `measure` |
116
+
117
+ Building a rule is lazy and does not scan the filesystem. `check`, `measure`, snapshot/report
118
+ terminals, and export terminals perform the work. Builders are immutable, so a scope can be reused:
119
+
120
+ ~~~ ruby
121
+ services = ArchUnit.project_files.in_folder('app/services/**')
122
+
123
+ cycle_rule = services.should.have_no_cycles
124
+ database_rule = services.should_not.depend_on_files.in_folder('app/database/**')
125
+ ~~~
126
+
127
+ String patterns are anchored globs. `*` stays inside one path segment, `**` crosses directories,
128
+ and `?` matches one non-separator character. Most selectors also accept regular expressions;
129
+ `defined_by_regex` is the explicit regex form for slices, while `in_file` takes one exact path.
130
+ Paths are project-relative and normalized to `/` separators.
131
+
132
+ A scope matching zero files returns `EmptyTestViolation`; it does not silently pass. Opt out only
133
+ when an empty result is genuinely valid:
134
+
135
+ ~~~ ruby
136
+ rule.check(ArchUnit::CheckOptions.new(allow_empty_tests: true))
137
+ ~~~
138
+
139
+ <a id="recipes"></a>
140
+
141
+ ## Rule recipes
142
+
143
+ ### File Rules
144
+
145
+ File rules cover cycles, naming, location, internal dependencies, external modules, and custom
146
+ source predicates:
147
+
148
+ ~~~ ruby
149
+ rules = [
150
+ ArchUnit.project_files.in_path('lib/**/*.rb').should.have_no_cycles,
151
+ ArchUnit.project_files.in_folder('app/services/**')
152
+ .should.have_name('*_service.rb'),
153
+ ArchUnit.project_files.in_folder('app/domain/**')
154
+ .should_not.depend_on_external_modules.matching('faraday')
155
+ ]
156
+
157
+ rules.each { |rule| ArchUnit.assert_passes(rule) }
158
+ ~~~
159
+
160
+ A custom predicate receives an immutable `FileInfo` with `path`, `name`, `extension`, `directory`,
161
+ complete `content`, and non-blank `lines_of_code`:
162
+
163
+ ~~~ ruby
164
+ rule = ArchUnit.project_files.in_folder('app/services/**')
165
+ .should.adhere_to(
166
+ ->(file) { file.lines_of_code < 300 },
167
+ 'services must stay below 300 non-blank lines'
168
+ )
169
+ ~~~
170
+
171
+ ### Layer Dependencies
172
+
173
+ Named layers express an allowlist or blocklist over groups of files:
174
+
175
+ ~~~ ruby
176
+ rule = ArchUnit.project_layers
177
+ .layer('api').defined_by('app/api/**/*.rb')
178
+ .layer('services').defined_by('app/services/**/*.rb')
179
+ .layer('database').defined_by('app/database/**/*.rb')
180
+ .where_layer('api').may_only_depend_on_layers('services')
181
+ .where_layer('services').may_only_depend_on_layers('database')
182
+ .where_layer('database').may_only_depend_on_layers
183
+
184
+ expect(rule).to pass
185
+ ~~~
186
+
187
+ Dependencies within one layer are always allowed. Edges with an unassigned endpoint are ignored.
188
+ Calling `may_only_depend_on_layers` without targets seals a layer; `may_not_depend_on_layers`
189
+ requires at least one forbidden target.
190
+
191
+ ### Architecture Slices and PlantUML
192
+
193
+ Slices group files by one captured path segment and preserve every concrete dependency as evidence:
194
+
195
+ ~~~ ruby
196
+ slices = ArchUnit.project_slices.defined_by('lib/my_app/(**)/')
197
+ rule = slices.should_not.contain_dependency('api', 'database')
198
+
199
+ expect(rule).to pass
200
+ ~~~
201
+
202
+ `(**)` is the slice capture. `defined_by_regex` uses the first regular-expression capture instead.
203
+
204
+ A checked-in PlantUML component diagram can also be the architecture contract:
205
+
206
+ ~~~ ruby
207
+ rule = slices.should
208
+ .ignoring_external_slices
209
+ .adhere_to_diagram_in_file('docs/architecture.puml')
210
+
211
+ expect(rule).to pass
212
+ ~~~
213
+
214
+ The supported subset recognizes components, directed dependencies, comments, and `@startuml` /
215
+ `@enduml`. Use `to_plantuml` or `export_as_plantuml(path)` to generate a diagram from the real graph.
216
+
217
+ ### Dependency Graph Reports
218
+
219
+ Graph reporting builds one immutable snapshot and renders it consistently as DOT, Mermaid, D2, CSV,
220
+ JSON, or self-contained HTML:
221
+
222
+ ~~~ ruby
223
+ report = ArchUnit.project_graph
224
+ .include_external_dependencies
225
+ .focus_on('app/services/**', 2)
226
+ .collapse_to_folder_depth(2)
227
+ .titled('Service dependencies')
228
+
229
+ puts report.summary.node_count
230
+ report.export_as_html('reports/services.html')
231
+ ~~~
232
+
233
+ Queries include `focus_on`, `reachable_from`, and `dependents_of`. Collapse by folder depth or a
234
+ regular-expression replacement. Every format has an in-memory `to_<format>` and an
235
+ `export_as_<format>(path)` terminal.
236
+
237
+ ### Code Metrics
238
+
239
+ Metric scopes select files and Ruby classes before measurement or assertion:
240
+
241
+ ~~~ ruby
242
+ services = ArchUnit.metrics
243
+ .in_path('app/services/**/*.rb')
244
+ .for_classes_matching('*Service')
245
+
246
+ size_rule = services.count.method_count.should_be_below_or_equal(20)
247
+ cohesion_rule = services.lcom.lcom4.should_be(1)
248
+ distance_rule = services.distance.instability.should_be_below(0.8)
249
+
250
+ [size_rule, cohesion_rule, distance_rule].each { |rule| ArchUnit.assert_passes(rule) }
251
+ ~~~
252
+
253
+ Count metrics cover class methods and fields plus file lines, statements, imports, classes, and
254
+ top-level functions. Cohesion includes LCOM96a, LCOM96b, LCOM1-5, and LCOM*. Dependency-derived
255
+ metrics include abstractness, instability, main-sequence distance, coupling factor, and normalized
256
+ distance. Zone guards detect the conventional zones of pain and uselessness.
257
+
258
+ Use `measure` for immutable numeric results, `custom_metric` for a calculation over `ClassInfo`, and
259
+ `export_as_html` for an offline metrics report:
260
+
261
+ ~~~ ruby
262
+ services.count.export_as_html('reports/service-counts')
263
+ ~~~
264
+
265
+ The threshold vocabulary is intentionally limited to `should_be_below`, `should_be_above`,
266
+ `should_be`, `should_be_below_or_equal`, `should_be_above_or_equal`, and `should_satisfy`.
267
+
268
+ ### Pattern Exclusions
269
+
270
+ Every selector accepts `except:` in the same call. A plain pattern or array uses the parent
271
+ selector's context, including filenames for path and folder selectors:
272
+
273
+ ~~~ ruby
274
+ scope = ArchUnit.project_files.in_path(
275
+ 'app/**/*.rb',
276
+ except: ['app/generated/**', 'schema.rb']
277
+ )
278
+ ~~~
279
+
280
+ Use explicit targets when needed. Supported keys are `in_path`, `in_folder`, `with_name`, and
281
+ `for_classes_matching`:
282
+
283
+ ~~~ ruby
284
+ scope = ArchUnit.metrics.in_path(
285
+ 'app/**/*.rb',
286
+ except: { in_folder: 'app/generated', with_name: '*_spec.rb' }
287
+ )
288
+ ~~~
289
+
290
+ <a id="frameworks"></a>
291
+
292
+ ## Test-framework integration
293
+
294
+ ### Results and Test Frameworks
295
+
296
+ `check` returns an array of structured violations. Architecture disagreement is data, not an
297
+ exception:
298
+
299
+ ~~~ ruby
300
+ violations = rule.check
301
+ violations.each { |violation| puts violation.class }
302
+ ~~~
303
+
304
+ Translate that result into a test failure at the boundary that suits your suite:
305
+
306
+ ~~~ ruby
307
+ expect(rule).to pass # RSpec
308
+ assert_passes(rule) # Minitest test case
309
+ ArchUnit.assert_passes(rule) # Framework-neutral
310
+ ~~~
311
+
312
+ `ArchUnit.format_violations` and `ResultFactory` provide stable human-readable output. All
313
+ violations retain the concrete dependency, file, layer, slice, or metric evidence that caused them.
314
+
315
+ <a id="logging"></a>
316
+
317
+ ## Logging and failure reports
318
+
319
+ Logging is off by default and belongs to one check; there is no process-global configuration:
320
+
321
+ ~~~ ruby
322
+ logging = ArchUnit::LoggingOptions.new(
323
+ level: :debug,
324
+ output_directory: 'tmp/archunit-logs',
325
+ append: false
326
+ )
327
+
328
+ violations = rule.check(ArchUnit::CheckOptions.new(logging: logging))
329
+ ~~~
330
+
331
+ Levels are `debug`, `info`, `warn`, and `error`. The fixed events cover check start/end, progress,
332
+ violations, and metric evidence. `io:` defaults to `$stderr`, accepts any writable stream, and may be
333
+ `nil`. File output creates missing directories and writes timestamped `archunit-*.log` files.
334
+
335
+ At `:debug`, inspection includes the project root, each discovered file, every dependency with
336
+ its import kind and external flag, selected files, and all metric calculations (including passing
337
+ values). It observes the same graph on both cold and cached checks. Custom metrics run once.
338
+ Check options and returned violations retain their existing behavior.
339
+
340
+ | Level | Included output |
341
+ | --- | --- |
342
+ | `:debug` | Graph inspection, selections, metric values, and everything below |
343
+ | `:info` | Check lifecycle and progress, violations, technical errors |
344
+ | `:warn` | Violations and technical errors |
345
+ | `:error` | Technical errors |
346
+
347
+ Example debug lines (timestamp prefixes omitted):
348
+
349
+ ~~~ text
350
+ [DEBUG] inspect: discovered file: "lib/service.rb"
351
+ [DEBUG] inspect: dependency: "lib/service.rb" -> "json" (external=true, kinds=[:require])
352
+ [DEBUG] inspect: selected file: "lib/service.rb"
353
+ [DEBUG] log metric: method_count=3 [lib/service.rb:Service]
354
+ ~~~
355
+
356
+ For file-only CI artifacts, use `io: nil` with `output_directory:` and archive that directory.
357
+ Logging sink errors still propagate. Debug details are produced lazily; checks with logging
358
+ disabled create no output or log files.
359
+
360
+ ### Readable, colored failure reports
361
+
362
+ The same formatted, numbered reports work with RSpec, Minitest, or standalone checks:
363
+
364
+ ~~~ ruby
365
+ puts ArchUnit.format_violations(violations) # Detect terminal support
366
+ puts ArchUnit.format_violations(violations, color: true) # Force ANSI colors
367
+ puts ArchUnit.format_violations(violations, color: false) # Plain CI/file output
368
+ ~~~
369
+
370
+ Failure headings are bold red, violation headings yellow, and successful results green. Reports
371
+ include dependency, file, or metric evidence. Automatic color detection respects `NO_COLOR`,
372
+ `TERM=dumb`, and non-terminal output. Log files remain plain text for searching and CI artifacts.
373
+
374
+ <a id="analysis"></a>
375
+
376
+ ## Static analysis and Ruby resolution
377
+
378
+ ### What ArchUnitRuby Extracts
379
+
380
+ ArchUnitRuby uses Prism and statically recognizes:
381
+
382
+ | Ruby source form | Import kind |
383
+ | --- | --- |
384
+ | `require 'json'` | `:require` |
385
+ | `require_relative '../models/order'` | `:require_relative` |
386
+ | `autoload :Order, 'models/order'` | `:autoload` |
387
+ | `load 'config/setup.rb'` | `:load` |
388
+ | `load 'config/setup.rb', true` | `:load` |
389
+ | `require_dependency 'item'` (explicit Rails opt-in) | `:require_dependency` |
390
+
391
+ `load` also accepts its optional wrap argument with implicit, `Kernel`, or `::Kernel` receivers.
392
+ The path must still be a literal or safely known local string. Effectful wrap expressions or
393
+ explicit `&` block conversions invalidate tracked local paths; splatted/forwarded arguments stay
394
+ unresolved rather than inventing a dependency. The analyzer never executes the load or wrap code.
395
+
396
+ Project dependencies use normalized, project-relative paths. Standard-library and gem dependencies
397
+ retain the module name written in source. Inline or immediately preceding ignore directives can
398
+ suppress known compatibility imports:
399
+
400
+ ~~~ ruby
401
+ require 'legacy/client' # archunit: ignore legacy/client
402
+
403
+ # archunit: ignore experimental/plugin
404
+ require 'experimental/plugin'
405
+ ~~~
406
+
407
+ Preceding local assignments to literal strings are also recognized for all four import forms:
408
+
409
+ ~~~ ruby
410
+ path = '../retrieval/store'
411
+ require_relative path
412
+ ~~~
413
+
414
+ Inference follows assignment order within straight-line lexical scopes. Reassignment replaces the
415
+ value; aliases, mutation, unknown calls receiving the value, reflection, and unsupported control
416
+ flow invalidate it. Values are not carried across branches, loops, exception handlers, or captured
417
+ blocks. Once a closure or reflective binding can access an enclosing scope, local inference remains
418
+ disabled for that scope. Independent literal assignments inside a method or block can still resolve. Runtime values
419
+ such as `ENV.fetch('PLUGIN_PATH')`, interpolation, and method results remain unresolved. No source,
420
+ Gemfile, gemspec, initializer, or `const_missing` hook is executed.
421
+
422
+ A bounded AST whitelist also recognizes file-relative construction, including the pattern used by
423
+ RestClient:
424
+
425
+ ~~~ ruby
426
+ require File.dirname(__FILE__) + '/restclient/version'
427
+ require File.expand_path('../db/store', __dir__)
428
+ path = __dir__ + '/../db/store.rb'
429
+ load path, true
430
+ ~~~
431
+
432
+ Supported operands are string literals, `__FILE__`, zero-argument implicit `__dir__`, and nested
433
+ whitelisted expressions. String `+` concatenates two such operands. `File`/`::File.dirname` accepts
434
+ one absolute operand; `File`/`::File.expand_path` accepts an absolute operand or a path with an
435
+ explicit absolute base. CWD/drive-relative expansion, `~` expansion, interpolation, `File.join`,
436
+ `Pathname`, local variables *inside* these expressions, and arbitrary methods remain unresolved.
437
+ An entire computed result can be assigned to a local and used under the same safety rules above.
438
+ Folding is bounded to 12 nested levels and 16 KiB strings.
439
+
440
+ These intrinsics assume ordinary Ruby core semantics. Source-local `File`/`String` shadowing or
441
+ reopening, `__dir__` overrides, refinements, and reflective mutation disable the affected inference
442
+ conservatively across that source file. Arbitrary cross-file core monkey-patches are not modeled.
443
+ Existing exclusions, canonical target matching and symlink boundaries still apply. See Ruby's
444
+ [path expansion](https://docs.ruby-lang.org/en/3.3/File.html#method-c-expand_path) and
445
+ [`__dir__`](https://docs.ruby-lang.org/en/3.3/Kernel.html#method-i-__dir__) semantics.
446
+
447
+ ### Rails Helper Imports (Opt-in, 1.1+)
448
+
449
+ File-relative expression folding above and the Rails helper option below require 1.1 or newer;
450
+ 1.0.0 retains its literal/local-literal import contract.
451
+
452
+ Enable static `require_dependency` recognition only for code where that name has Rails semantics:
453
+
454
+ ~~~ ruby
455
+ options = ArchUnit::CheckOptions.new(
456
+ rails_imports: true,
457
+ load_paths: ['app/models', 'app/services'],
458
+ dependency_analysis: :imports_and_constants # optional; imports mode also works
459
+ )
460
+ rule = ArchUnit.project_files.in_path('app/controllers/**')
461
+ .should_not.depend_on_files.in_path('app/models/**')
462
+ ArchUnit.assert_passes(rule, options)
463
+ ~~~
464
+
465
+ The default is `rails_imports: false`. Under the opt-in, implicit and `self.require_dependency`
466
+ calls with supported literal/local/static paths produce `:require_dependency` edges. Explicit
467
+ custom receivers are not assumed to be Rails. Source-local helper overrides or reflection make
468
+ accepted calls unresolved instead of inventing targets; cross-file method replacement is not
469
+ modeled. Dynamic `Rails.root`/glob paths, forwarded arguments and unknown local values increment
470
+ the unresolved-import counter. Counters describe static call sites, not runtime loop iterations.
471
+
472
+ Explicit `load_paths` are validated project-local directories and are searched first, in supplied
473
+ order, for the helper; ordinary `require` keeps its existing search order. The opt-in does not
474
+ discover Rails autoload paths or boot Rails. Missing helper targets retain the existing external
475
+ dependency representation. Exclusions, source evidence, rule/report integration and cache identity
476
+ use the same pipeline in both analysis modes.
477
+
478
+ ~~~ sh
479
+ bundle exec archunit check --rails-imports --load-path app/models --load-path app/services
480
+ ~~~
481
+
482
+ CLI JSON includes additive `rails_imports` and `load_paths` settings; `--no-rails-imports` disables
483
+ the helper explicitly. Rails itself documents
484
+ [`require_dependency` as obsolete for modern autoloading](https://api.rubyonrails.org/classes/ActiveSupport/Dependencies/RequireDependency.html).
485
+ This compatibility option models existing legacy/engine code, not complete Rails runtime behavior.
486
+
487
+ ### Constant References (Opt-in)
488
+
489
+ For autoloaded applications, enable dependencies from known project constants alongside imports:
490
+
491
+ ~~~ ruby
492
+ options = ArchUnit::CheckOptions.new(dependency_analysis: :imports_and_constants)
493
+
494
+ # Detects Retrieval::Store.new even without require_relative.
495
+ rule = ArchUnit.project_files
496
+ .in_path('app/api/**')
497
+ .should_not.depend_on_files.in_path('app/retrieval/**')
498
+ violations = rule.check(options)
499
+
500
+ report = ArchUnit.project_graph.with_check_options(options)
501
+ puts report.to_json
502
+ puts ArchUnit.project_slices.defined_by('app/(**)/').to_plantuml(options)
503
+ values = ArchUnit.metrics.distance.instability.measure(options)
504
+ ~~~
505
+
506
+ The default remains `dependency_analysis: :imports`. Expanded mode indexes declarations from the
507
+ same included source files, then resolves references to definition files. Files remain graph nodes.
508
+ It supports lexical nesting, compact namespaces, root-qualified names, and explicit superclass,
509
+ `include`, `prepend`, and `extend` references. Nested `module A; module B` includes `A` in lexical
510
+ lookup; top-level `module A::B` does not. A nearer namespace shadows a root namespace even when its
511
+ requested child is missing.
512
+
513
+ Ordinary `=` and conditional `||=` constant declarations are indexed, including qualified and
514
+ root-qualified forms. A conditional declaration records a possible definition file, not proof that
515
+ the assignment executes or its resulting value. Multiple candidate files stay ambiguous. Other
516
+ compound writes (`&&=`, operators) and multiple-assignment declarations are not inferred as new
517
+ definition owners; unsupported targets remain unresolved rather than inventing ownership.
518
+
519
+ Qualified class/module declarations and `=`/`||=` writes also read their namespace receiver:
520
+ `class Db::Service` and `Db::VALUE = 42` depend on the unique file defining `Db`, not on a prior
521
+ definition of `Service` or `VALUE`. Root qualification and enclosing lexical lookup are preserved;
522
+ unknown or reopened namespace owners remain unresolved or ambiguous.
523
+
524
+ References with multiple definition files (reopened classes/modules), missing definitions, and
525
+ dynamic definitions are omitted, never assigned to an arbitrary file. `Alias = Original` defines
526
+ `Alias` in its own file and records the reference to `Original`; lookup through aliases such as
527
+ `Alias::Child` is not followed. Inherited constant members and singleton-class lexical lookup are
528
+ not modeled. Unqualified root fallback is conservatively suppressed in scopes with an explicit
529
+ superclass, mixins, or dynamic constant operations. Use explicit `::Namespace::Constant` references
530
+ or import rules where those limits matter. Static analysis does not establish runtime load order
531
+ or whether a conditional use executes. Qualified declaration owners are stabilized before lookup;
532
+ if they do not stabilize within eight index passes, the project contributes imports only and its
533
+ constant uses are counted as unresolved.
534
+
535
+ In expanded mode, an import and a constant use between the same files produce one logical edge.
536
+ Its `import_kinds`
537
+ includes `:constant_reference`; `edge.evidence` and JSON graph exports retain the referenced name,
538
+ source span, and definition line for constant uses. Import evidence retains its call span. CSV,
539
+ HTML, and diagram reports use the same merged graph; CSV/HTML distinguish dependency kinds.
540
+ `# archunit: ignore` continues to suppress imports only, not constant references. Import-only mode
541
+ leaves `edge.evidence` empty for compatibility with existing edge-value comparisons;
542
+ `ArchUnit::Extraction.extract_imports` retains call locations in both modes.
543
+
544
+ For diagnostics, pass an `ArchUnit::Extraction::ExtractionProfile` to
545
+ `ArchUnit::Extraction.extract_graph(root, options: options, profile: profile)`. Its counters include
546
+ `unresolved_imports`, `unresolved_constant_references`, and `ambiguous_constant_references`; unknown
547
+ third-party constants do not become architecture violations. These counts describe a cold analysis;
548
+ a cache hit does not rerun diagnostics. Included malformed Ruby now raises
549
+ `ArchUnit::SourceParseError < ArchUnit::TechnicalError` in both modes and in AST metrics, rather
550
+ than silently returning a partial graph or zero counts. Its immutable `diagnostics` contain
551
+ `path`, one-based `line` and `column`, and the parser `message`; the extraction profile increments
552
+ `malformed_files`. Fix or explicitly exclude invalid files using the project source policy.
553
+ Fluent rule selectors do not limit graph discovery. Failed graph builds are not cached; after
554
+ editing previously cached valid source, the normal explicit `clear_cache: true` policy still applies.
555
+ This intentionally changes the 0.0.1 prototype's permissive behavior in the 1.0 API.
556
+
557
+ Expanded analysis uses a bounded Prism index and adds no runtime dependency. The design spike
558
+ considered [RubyDEX](https://github.com/Shopify/rubydex), whose semantic index is broader but adds a
559
+ Rust/native extension and platform packaging requirements. Reusing our existing Prism parser keeps
560
+ the Ruby 3.3/3.4/4.0 Windows/Linux support contract; each included source is parsed once per graph
561
+ build. A later semantic backend can broaden the documented lookup subset. Lookup fixtures follow
562
+ the [Ruby constant-scope documentation](https://docs.ruby-lang.org/en/master/syntax/modules_and_classes_rdoc.html#label-Constants).
563
+
564
+ Repositories containing multiple gems are discovered statically: every `*.gemspec` beneath the
565
+ project root contributes its adjacent existing `lib` directory to feature resolution. Gemspecs are
566
+ never evaluated. Add non-standard source roots explicitly through the per-check options bag; paths
567
+ are relative to the project root, must remain inside it, and use the order given after the normal
568
+ top-level `lib` and project-root search locations:
569
+
570
+ ~~~ ruby
571
+ options = ArchUnit::CheckOptions.new(
572
+ load_paths: ['components/billing/source', 'plugins/search/lib']
573
+ )
574
+
575
+ violations = rule.check(options)
576
+ report = ArchUnit.project_graph.with_check_options(options)
577
+ ~~~
578
+
579
+ Load-path choices and dependency-analysis mode affect graph caching. Equivalent normalized choices
580
+ reuse a cached graph, while a different mode or load-path set builds a separate graph. Use
581
+ `clear_cache: true` after changing files, constant definitions, or gemspec
582
+ layout within one process.
583
+
584
+ <a id="cli"></a>
585
+
586
+ ## Command line (1.1+)
587
+
588
+ ArchUnitRuby 1.1 adds an `archunit` executable; 1.0.0 does not include it. Run it through Bundler
589
+ to use the version selected by your project's lockfile:
590
+
591
+ ~~~sh
592
+ bundle exec archunit init
593
+ # Review and customize .archunit.rb before running checks.
594
+ bundle exec archunit check
595
+ bundle exec archunit check --format json --dependency-analysis imports_and_constants
596
+ bundle exec archunit explain
597
+ ~~~
598
+
599
+ The starter checks cycles in `lib/**/*.rb`. Replace or extend it with named rules, for example:
600
+
601
+ ~~~ruby
602
+ # .archunit.rb -- trusted executable Ruby
603
+ rule 'API stays out of storage' do
604
+ project_files.in_path('app/api/**').should_not.depend_on_files.in_path('app/db/**')
605
+ .because('Keep storage private')
606
+ end
607
+ ~~~
608
+
609
+ Configuration helpers `project_files` / `files`, `project_layers` / `layers`, `project_slices`, and
610
+ `metrics` default to `--project DIRECTORY` (the working directory otherwise). `--config FILE` selects
611
+ a configuration relative to the invocation directory; the default is `PROJECT/.archunit.rb`.
612
+ `init` refuses to overwrite an existing destination, including directories and dangling symlinks.
613
+
614
+ `check` returns exit **0** when every rule passes, **1** for architecture violations (including empty
615
+ selections), and **2** for argument, configuration, or analysis errors. Text uses the existing
616
+ violation wording. `--format json` returns a schema-versioned document with per-rule names, rationales,
617
+ violations, summary counts, and structured parse diagnostics for malformed source. `explain` lists
618
+ configured rules and settings without checking them: `configured` / `not_checked` is not a passing
619
+ architecture result. It is not yet a semantic dependency trace or focused-path report.
620
+
621
+ CLI diagnostics (1.1+) include an additive schema-1 `analysis` section and per-rule
622
+ scope IDs. Each scope reports its project root, effective source exclusions, actual analysis
623
+ mode, source-file count, unresolved imports/constants, and ambiguous constant references.
624
+ Repeated rules sharing a cached graph share its original counts; different roots, policies,
625
+ modes, or refreshed graphs have separate scopes. Counts are not summed across overlapping scopes.
626
+ `null` in JSON / `unavailable` in text means that analysis was not performed or did not finish,
627
+ not a measured zero. Metric-only rules report source counts but no dependency-analysis counts;
628
+ `explain` does not claim to have analyzed sources.
629
+
630
+ These counters describe observations, **not a semantic-coverage percentage or proven missing
631
+ dependencies**. Unresolved imports count unsupported/dynamic import expressions, not every literal
632
+ external gem import. Unresolved constants can include external symbols and unsupported lookup;
633
+ ambiguity includes constants reopened across files. Unknowns remain nonfatal, while included
634
+ syntax errors still exit 2. Passing a rule means no violations in the statically resolved graph,
635
+ not proof of complete runtime architecture.
636
+
637
+ Only run configurations you trust: `.archunit.rb` is arbitrary executable Ruby, **not a sandbox**,
638
+ and `explain` also loads it. For an untrusted target repository, provide your own trusted
639
+ configuration via `--config`. The CLI does not automatically load target application source,
640
+ evaluate a target Gemfile/gemspec, install its dependencies, or boot Rails. Invoking Bundler yourself
641
+ still has Bundler's normal Gemfile behavior. RSpec/Minitest remain fully supported; the CLI composes
642
+ the same Checkable rules and is not a replacement for their integrations.
643
+
644
+ #### Gradual adoption with explicit accepted debt (1.1+)
645
+
646
+ ```sh
647
+ # Evaluate all rules and explicitly record current supported violations; review this JSON in Git.
648
+ bundle exec archunit baseline --output .archunit-baseline.json
649
+ bundle exec archunit check --baseline .archunit-baseline.json
650
+ ```
651
+
652
+ Every rule still runs over the same sources. The baseline accepts specific violations, not whole
653
+ files. New violations **and stale entries for fixed/removed violations** fail with exit 1; invalid
654
+ baseline/config/source errors exit 2. A fully accepted result exits 0 with status `accepted`, not a
655
+ clean `passed` result. Raw violations stay visible, with separate accepted/new/stale counts.
656
+ `check` never rewrites debt. Explicitly regenerate with `baseline --output ... --force` only after
657
+ reviewing changes; recording debt is not proof that the architecture passes.
658
+
659
+ Versioned fingerprints use rule names, structured violation data and analysis scope/settings, not
660
+ message prose, line numbers or absolute checkout paths. Line edits/relocation preserve identities;
661
+ changed rule names, policies or analysis modes can invalidate them. Duplicate occurrences match
662
+ one-for-one. Supported identities: built-in file/external dependencies, naming, simple directed
663
+ cycles, layer/slice dependencies and numeric metric thresholds. Empty-selection failures, custom
664
+ predicates/violations, metric zones and unknown types cannot be recorded silently. Baselines are
665
+ bounded JSON (2 MB / 10,000 entries), not executable configuration; symlinks and directories are
666
+ rejected. Creation requires a `.json` output and refuses overwrite unless `--force` is explicit.
667
+ Atomic output needs a filesystem supporting same-directory hard links; an unsupported filesystem
668
+ fails with exit 2, never falls back to overwriting. This is not a sandbox against concurrent hostile
669
+ filesystem changes. Review baseline diffs in CI as carefully as rule changes.
670
+
671
+ <a id="presets"></a>
672
+
673
+ ## Architecture presets (1.1+)
674
+
675
+ Presets compose the existing named-layer rules, preserving CheckOptions, empty-selection failures,
676
+ RSpec/Minitest, CLI, and static-analysis limitations. Construction is lazy; no Rails app is booted.
677
+
678
+ ~~~ruby
679
+ rule = ArchUnit.architecture_preset(
680
+ :hexagonal,
681
+ ArchUnit::PresetOptions.new(project_locator: '.', folders: { domain: 'lib/domain/**' })
682
+ ).because('Keep the domain independent of infrastructure')
683
+ expect(rule).to pass
684
+ ~~~
685
+
686
+ | Preset | Default layers / source patterns | Allowed cross-layer directions |
687
+ | --- | --- | --- |
688
+ | `:layered` | presentation `app/api/**`; application `app/services/**`; persistence `app/db/**` | presentation → application → persistence; no skipping |
689
+ | `:hexagonal` | domain `app/domain/**`; application `app/application/**`; adapters `app/adapters/**` | application → domain; adapters → application/domain |
690
+ | `:rails` | controllers `app/controllers/**`; services `app/services/**`; models `app/models/**` | controllers → services/models; services → models |
691
+
692
+ Dependencies within a layer are allowed; the innermost layer may not depend on another mapped layer.
693
+ Unmapped files and external modules are not constrained by this folder policy; source discovery is
694
+ not narrowed. Add file/layer/cycle rules for additional boundaries. Missing policy layers fail by
695
+ default; override patterns or consciously use `CheckOptions.new(allow_empty_tests: true)` if intended.
696
+ Overlapping observed membership raises UserError instead of choosing a layer silently. All source
697
+ patterns can be overridden with `PresetOptions.folders` (String or Array of source globs per layer).
698
+ Unknown/duplicate keys and empty patterns are errors. For arbitrary policies use `project_layers`.
699
+ The Rails preset is opinionated and expects a services layer; it is not full Rails/DDD verification
700
+ and does not automatically enable `rails_imports` or constant analysis.
701
+
702
+ In trusted CLI configuration use `rule('Core independent') { architecture_preset(:hexagonal) }`;
703
+ the helper defaults to the CLI's selected project root. Public `ArchUnit.architecture_preset` uses
704
+ normal project auto-discovery when no locator is supplied.
705
+
706
+ <a id="example"></a>
707
+
708
+ ## Example project and dogfooding
709
+
710
+ The [ArchUnitRuby RAG test repository](https://github.com/TristanKruse/ArchUnitRuby-TestRepo-RAG)
711
+ is a small layered retrieval-augmented-generation application with two deliberate architecture
712
+ violations. Its test suite exercises the public APIs above against real Ruby source on Linux and
713
+ Windows.
714
+
715
+ ArchUnitRuby also dogfoods itself in `spec/architecture_spec.rb`: `common` is isolated, domain
716
+ modules cannot depend on one another, implementation files cannot depend on the public surface, and
717
+ the complete library graph must remain cycle-free.
718
+
719
+ <a id="development"></a>
720
+
721
+ ## Development and validation
722
+
723
+ Start with [CONTRIBUTING.md](CONTRIBUTING.md) for the complete development and pull-request guide.
724
+
725
+ ~~~ bash
726
+ git clone https://github.com/dragonsec-ai/ArchUnitRuby.git
727
+ cd ArchUnitRuby
728
+ bundle install
729
+ bundle exec rake
730
+ bundle exec rake docs
731
+ gem build archunit.gemspec --strict
732
+ ~~~
733
+
734
+ `bundle exec rake` validates release metadata, then runs the randomized RSpec suite and RuboCop.
735
+ CI additionally enforces 98% line
736
+ and 90% branch coverage, runs the dogfooding rules explicitly, builds the documentation, loads the
737
+ public API with Ruby warnings, tests optional RSpec/Minitest integrations, builds and installs the
738
+ gem artifact, runs the external RAG fixture, and checks Ruby 3.3, 3.4, and 4.0 across Ubuntu and
739
+ Windows.
740
+
741
+ Cold and warm extraction can be profiled independently with a generated multi-gem corpus. The
742
+ benchmark reports stage timings, resolution-cache effectiveness, Ruby heap growth, and peak RSS on
743
+ platforms that expose it:
744
+
745
+ ~~~ bash
746
+ bundle exec ruby benchmark/extraction.rb
747
+ ~~~
748
+
749
+ See the [benchmark guide](https://github.com/dragonsec-ai/ArchUnitRuby/blob/main/benchmark/README.md)
750
+ for corpus controls, JSON output, and CI limits.
751
+
752
+ The separate [real-world canary](https://github.com/dragonsec-ai/ArchUnitRuby/blob/main/benchmark/canary/README.md)
753
+ checks pinned Rack, Rake, RSpec, and RestClient production-library sources in both dependency modes, including
754
+ passing and deliberately failing rules, graph baselines, and cold/warm performance. It never runs
755
+ those projects or installs their dependencies, and is not scheduled automatically yet.
756
+
757
+ The implementation conventions and intended dependency directions live in [`AGENTS.md`](AGENTS.md).
758
+
759
+ <a id="migration"></a>
760
+
761
+ ## Compatibility and migration
762
+
763
+ The documented entry points, fluent rule methods, options, public data/error types, and report
764
+ formats in the [API guide](https://dragonsec-ai.github.io/ArchUnitRuby/file.API.html) form the 1.x
765
+ compatibility baseline. Additive capabilities may be introduced in minor versions; incompatible
766
+ public API changes require a new major version and migration notes. Private implementation helpers
767
+ are not part of that contract. Correctness fixes can reveal violations that earlier versions missed;
768
+ review the changelog when updating.
769
+
770
+ When upgrading from 0.0.1:
771
+
772
+ - The default remains import-only. Explicitly opt into `dependency_analysis: :imports_and_constants`
773
+ when you want the documented static constant-reference model; it may reveal additional violations.
774
+ - Included malformed Ruby now raises `SourceParseError < TechnicalError`, rather than silently
775
+ passing or returning zero AST counts. Fix or explicitly exclude invalid source files.
776
+ - Project `.archignore` exclusions and skipped symlinked source entries can change the discovered
777
+ file set. Empty selections are still violations by default; check selectors rather than blindly
778
+ allowing empty tests.
779
+ - Cached graph results still require explicit clearing after source edits in a long-lived process.
780
+
781
+ Stable API compatibility does not mean complete Ruby interpretation or exhaustive runtime detection.
782
+ The supported static-analysis boundaries below remain part of the contract.
783
+
784
+ <a id="limits"></a>
785
+
786
+ ## Boundaries and further research
787
+
788
+ File dependencies remain the primary vocabulary. Dynamic import paths, unsupported/inherited lookup,
789
+ ambiguous declarations and runtime metaprogramming cannot be resolved completely. Neither a passing
790
+ rule nor an uncertainty count proves complete runtime architecture. Full method-call/signature
791
+ protocols and semantic component selectors are not shipped; the
792
+ [bounded evaluation](https://github.com/dragonsec-ai/ArchUnitRuby/blob/main/design/semantic-boundaries.md)
793
+ records the decision and probes. Graph queries are available, but semantic CLI tracing is not claimed.
794
+
795
+ PlantUML support is a small component-diagram subset. `.archignore` does not support negation or
796
+ nested ignore files. Dense graphs can have exponentially many cycles despite iterative traversal.
797
+ No-target-execution is not an OS sandbox against a hostile, concurrently changing filesystem.
798
+
799
+ For reproducible Linux/Windows timing, startup, memory and changed-source evidence, see the
800
+ [representative performance study](https://github.com/dragonsec-ai/ArchUnitRuby/blob/main/benchmark/study/README.md).
801
+ Its generated shared-policy shapes and pinned sparse Discourse profile do not establish universal
802
+ speed or semantic parity. The study bundle is separate from the gem's runtime dependencies.
803
+
804
+ [Support](SUPPORT.md) · [Security](SECURITY.md) · [Contributing](CONTRIBUTING.md)