rigortype 0.3.3 → 0.3.4

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 (158) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +1 -1
  3. data/data/builtins/ruby_core/array.yml +11 -24
  4. data/data/builtins/ruby_core/enumerable.yml +4 -8
  5. data/data/builtins/ruby_core/exception.yml +6 -9
  6. data/data/builtins/ruby_core/hash.yml +13 -20
  7. data/data/builtins/ruby_core/io.yml +6 -9
  8. data/data/builtins/ruby_core/numeric.yml +2 -3
  9. data/data/builtins/ruby_core/proc.yml +4 -8
  10. data/data/builtins/ruby_core/re.yml +6 -9
  11. data/data/builtins/ruby_core/set.yml +2 -3
  12. data/data/builtins/ruby_core/string.yml +4 -7
  13. data/data/builtins/ruby_core/struct.yml +0 -6
  14. data/data/builtins/ruby_core/time.yml +3 -6
  15. data/data/effects/core.yml +843 -0
  16. data/data/effects/registry.yml +67 -0
  17. data/docs/handbook/07-rbs-and-extended.md +106 -5
  18. data/docs/manual/02-cli-reference.md +311 -1
  19. data/docs/manual/03-configuration.md +84 -1
  20. data/docs/manual/04-diagnostics.md +6 -2
  21. data/docs/manual/16-rbs-extended-annotations.md +77 -0
  22. data/docs/manual/18-removing-dead-code.md +326 -0
  23. data/docs/manual/README.md +5 -0
  24. data/docs/manual/plugins/rigor-actionmailer.md +5 -0
  25. data/docs/manual/plugins/rigor-activejob.md +47 -0
  26. data/docs/manual/plugins/rigor-factorybot.md +16 -0
  27. data/docs/manual/plugins/rigor-pundit.md +26 -0
  28. data/docs/manual/plugins/rigor-rails-routes.md +41 -2
  29. data/docs/manual/plugins/rigor-rspec-rails.md +5 -0
  30. data/docs/manual/plugins/rigor-rspec.md +8 -0
  31. data/docs/manual/plugins/rigor-sidekiq.md +54 -0
  32. data/lib/rigor/analysis/check_rules/rule_ids.rb +28 -2
  33. data/lib/rigor/analysis/incremental_session.rb +140 -6
  34. data/lib/rigor/analysis/reachability/graph.rb +244 -0
  35. data/lib/rigor/analysis/reachability/plugin_roots.rb +164 -0
  36. data/lib/rigor/analysis/reachability/project_files.rb +58 -0
  37. data/lib/rigor/analysis/reachability/scan.rb +241 -0
  38. data/lib/rigor/analysis/reachability/signature_scan.rb +134 -0
  39. data/lib/rigor/analysis/rule_catalog.rb +158 -0
  40. data/lib/rigor/analysis/run_cache_key.rb +16 -0
  41. data/lib/rigor/analysis/runner/declaration_position.rb +54 -0
  42. data/lib/rigor/analysis/runner/effect_annotation_residual_pass.rb +108 -0
  43. data/lib/rigor/analysis/runner/effect_envelope_pass.rb +358 -0
  44. data/lib/rigor/analysis/runner/envelope_messages.rb +61 -0
  45. data/lib/rigor/analysis/runner/pool_coordinator.rb +68 -10
  46. data/lib/rigor/analysis/runner.rb +420 -10
  47. data/lib/rigor/analysis/worker_session.rb +58 -2
  48. data/lib/rigor/bleeding_edge.rb +22 -0
  49. data/lib/rigor/cache/incremental_snapshot.rb +24 -5
  50. data/lib/rigor/cli/check_command.rb +13 -1
  51. data/lib/rigor/cli/check_runner_factory.rb +4 -1
  52. data/lib/rigor/cli/effects_command.rb +131 -0
  53. data/lib/rigor/cli/effects_diff_renderer.rb +123 -0
  54. data/lib/rigor/cli/effects_explain_renderer.rb +68 -0
  55. data/lib/rigor/cli/effects_renderer.rb +54 -0
  56. data/lib/rigor/cli/effects_report.rb +53 -0
  57. data/lib/rigor/cli/effects_snapshot_command.rb +256 -0
  58. data/lib/rigor/cli/unused_command.rb +288 -0
  59. data/lib/rigor/cli.rb +16 -0
  60. data/lib/rigor/configuration/severity_profile.rb +23 -0
  61. data/lib/rigor/configuration.rb +296 -14
  62. data/lib/rigor/effects/attribution.rb +76 -0
  63. data/lib/rigor/effects/catalog.rb +275 -0
  64. data/lib/rigor/effects/collector.rb +182 -0
  65. data/lib/rigor/effects/config_envelopes.rb +185 -0
  66. data/lib/rigor/effects/discharge.rb +69 -0
  67. data/lib/rigor/effects/effect_table.rb +92 -0
  68. data/lib/rigor/effects/entry_points.rb +93 -0
  69. data/lib/rigor/effects/envelope.rb +86 -0
  70. data/lib/rigor/effects/envelope_check.rb +172 -0
  71. data/lib/rigor/effects/envelope_index.rb +157 -0
  72. data/lib/rigor/effects/file_collection.rb +160 -0
  73. data/lib/rigor/effects/framework_units.rb +167 -0
  74. data/lib/rigor/effects/identity.rb +104 -0
  75. data/lib/rigor/effects/label.rb +77 -0
  76. data/lib/rigor/effects/label_intent.rb +73 -0
  77. data/lib/rigor/effects/label_set.rb +136 -0
  78. data/lib/rigor/effects/liskov_check.rb +167 -0
  79. data/lib/rigor/effects/local_ownership.rb +132 -0
  80. data/lib/rigor/effects/method_key.rb +40 -0
  81. data/lib/rigor/effects/mutation_classifier.rb +92 -0
  82. data/lib/rigor/effects/narrowing.rb +202 -0
  83. data/lib/rigor/effects/origin.rb +66 -0
  84. data/lib/rigor/effects/path_finder.rb +89 -0
  85. data/lib/rigor/effects/plugin_facts.rb +335 -0
  86. data/lib/rigor/effects/propagator.rb +275 -0
  87. data/lib/rigor/effects/registry.rb +193 -0
  88. data/lib/rigor/effects/scanner.rb +290 -0
  89. data/lib/rigor/effects/signature_sources.rb +74 -0
  90. data/lib/rigor/effects/snapshot.rb +380 -0
  91. data/lib/rigor/effects/snapshot_diff.rb +265 -0
  92. data/lib/rigor/effects/summary.rb +154 -0
  93. data/lib/rigor/effects/taint_cause.rb +38 -0
  94. data/lib/rigor/effects/unit_scan.rb +572 -0
  95. data/lib/rigor/effects/unknown_label_check.rb +86 -0
  96. data/lib/rigor/effects/unknown_label_report.rb +59 -0
  97. data/lib/rigor/effects.rb +47 -0
  98. data/lib/rigor/environment/rbs_loader.rb +34 -0
  99. data/lib/rigor/environment.rb +8 -1
  100. data/lib/rigor/flow_contribution/element.rb +1 -0
  101. data/lib/rigor/flow_contribution/merge_result.rb +5 -3
  102. data/lib/rigor/flow_contribution/merger.rb +16 -1
  103. data/lib/rigor/flow_contribution.rb +20 -4
  104. data/lib/rigor/inference/expression_typer.rb +18 -4
  105. data/lib/rigor/inference/pre_eval_constants.rb +189 -0
  106. data/lib/rigor/inference/scope_indexer.rb +15 -3
  107. data/lib/rigor/plugin/base.rb +24 -0
  108. data/lib/rigor/plugin/effect_attribution.rb +208 -0
  109. data/lib/rigor/plugin/effect_edge.rb +101 -0
  110. data/lib/rigor/plugin/effect_entry_points.rb +51 -0
  111. data/lib/rigor/plugin/first_party.rb +57 -0
  112. data/lib/rigor/plugin/isolation.rb +4 -1
  113. data/lib/rigor/plugin/manifest.rb +103 -3
  114. data/lib/rigor/plugin/registry.rb +48 -0
  115. data/lib/rigor/plugin.rb +1 -0
  116. data/lib/rigor/rbs_extended/envelope_scanner.rb +160 -0
  117. data/lib/rigor/rbs_extended.rb +168 -0
  118. data/lib/rigor/reflection.rb +131 -30
  119. data/lib/rigor/version.rb +1 -1
  120. data/lib/rigor.rb +1 -0
  121. data/plugins/rigor-actioncable/lib/rigor/plugin/actioncable/effects.rb +90 -0
  122. data/plugins/rigor-actioncable/lib/rigor/plugin/actioncable.rb +7 -1
  123. data/plugins/rigor-actionmailer/lib/rigor/plugin/actionmailer/effects.rb +85 -0
  124. data/plugins/rigor-actionmailer/lib/rigor/plugin/actionmailer.rb +8 -1
  125. data/plugins/rigor-actionpack/lib/rigor/plugin/actionpack/effects.rb +152 -0
  126. data/plugins/rigor-actionpack/lib/rigor/plugin/actionpack.rb +9 -1
  127. data/plugins/rigor-activejob/lib/rigor/plugin/activejob/effects.rb +156 -0
  128. data/plugins/rigor-activejob/lib/rigor/plugin/activejob/recurring_scan.rb +113 -0
  129. data/plugins/rigor-activejob/lib/rigor/plugin/activejob.rb +68 -3
  130. data/plugins/rigor-activerecord/lib/rigor/plugin/activerecord/effects.rb +186 -0
  131. data/plugins/rigor-activerecord/lib/rigor/plugin/activerecord.rb +12 -1
  132. data/plugins/rigor-activerecord/sig/active_record/relation.rbs +145 -0
  133. data/plugins/rigor-activestorage/lib/rigor/plugin/activestorage/effects.rb +77 -0
  134. data/plugins/rigor-activestorage/lib/rigor/plugin/activestorage.rb +6 -1
  135. data/plugins/rigor-activesupport-core-ext/lib/rigor/plugin/activesupport_core_ext/effects.rb +143 -0
  136. data/plugins/rigor-activesupport-core-ext/lib/rigor/plugin/activesupport_core_ext.rb +9 -1
  137. data/plugins/rigor-activesupport-core-ext/sig/active_support/core_ext.rbs +385 -28
  138. data/plugins/rigor-factorybot/lib/rigor/plugin/factorybot.rb +30 -2
  139. data/plugins/rigor-pundit/lib/rigor/plugin/pundit/authorization_scan.rb +151 -0
  140. data/plugins/rigor-pundit/lib/rigor/plugin/pundit.rb +46 -3
  141. data/plugins/rigor-rails/lib/rigor-rails.rb +1 -0
  142. data/plugins/rigor-rails-i18n/lib/rigor/plugin/rails_i18n/effects.rb +47 -0
  143. data/plugins/rigor-rails-i18n/lib/rigor/plugin/rails_i18n.rb +7 -1
  144. data/plugins/rigor-rails-routes/lib/rigor/plugin/rails_routes/acronyms.rb +81 -0
  145. data/plugins/rigor-rails-routes/lib/rigor/plugin/rails_routes/helper_table.rb +13 -1
  146. data/plugins/rigor-rails-routes/lib/rigor/plugin/rails_routes/routes_parser.rb +202 -15
  147. data/plugins/rigor-rails-routes/lib/rigor/plugin/rails_routes.rb +43 -3
  148. data/plugins/rigor-railties/lib/rigor/plugin/railties/effects.rb +171 -0
  149. data/plugins/rigor-railties/lib/rigor/plugin/railties.rb +62 -0
  150. data/plugins/rigor-railties/lib/rigor-railties.rb +3 -0
  151. data/plugins/rigor-sidekiq/lib/rigor/plugin/sidekiq/schedule_scan.rb +122 -0
  152. data/plugins/rigor-sidekiq/lib/rigor/plugin/sidekiq.rb +56 -3
  153. data/sig/rigor/analysis/fact_store.rbs +1 -0
  154. data/sig/rigor/inference.rbs +2 -0
  155. data/sig/rigor/rbs_extended.rbs +6 -0
  156. data/sig/rigor.rbs +17 -1
  157. data/skills/rigor-unused-adjudicate/SKILL.md +90 -0
  158. metadata +79 -1
@@ -50,11 +50,61 @@ plugins:
50
50
  config:
51
51
  worker_search_paths: ["app/workers", "app/sidekiq"] # default
52
52
  worker_marker_modules: ["Sidekiq::Job", "Sidekiq::Worker"] # default
53
+ schedule_paths: # default
54
+ - "config/schedule.yml"
55
+ - "config/sidekiq.yml"
53
56
  ```
54
57
 
55
58
  The default `worker_marker_modules` covers both modern Sidekiq
56
59
  (`Sidekiq::Job`, since 6.3) and the legacy `Sidekiq::Worker`.
57
60
 
61
+ `schedule_paths` are the schedule *files* — not directories — behind
62
+ the reachability roots below. The defaults are where the two schedule
63
+ layouts conventionally live; list your own path if you keep the
64
+ schedule elsewhere.
65
+
66
+ ## Worker roots for `rigor unused`
67
+
68
+ A cron-scheduled worker is enqueued **by name from YAML**, so
69
+ `NightlyReportWorker` can appear nowhere in your code. Without help,
70
+ [`rigor unused`](../02-cli-reference.md#rigor-unused) reports a job
71
+ that runs every night as possibly dead. This plugin supplies the
72
+ workers your schedule names, so they drop out of the candidate list:
73
+
74
+ ```yaml
75
+ # config/schedule.yml (sidekiq-cron) config/sidekiq.yml (sidekiq-scheduler)
76
+ nightly_report: :scheduler:
77
+ cron: "0 3 * * *" :schedule:
78
+ class: "NightlyReportWorker" nightly_report:
79
+ every: "1h"
80
+ class: "NightlyReportWorker"
81
+ ```
82
+
83
+ It reads the `class:` key and nothing else. In particular a **queue
84
+ name is not a class name**: the `:queues:` list in `sidekiq.yml`
85
+ supplies no roots, because inflecting `report_worker` into
86
+ `ReportWorker` would root a worker on a naming coincidence. And a
87
+ `class:` naming a worker the plugin never discovered is dropped rather
88
+ than published, so a typo costs you a root instead of quietly hiding a
89
+ dead worker.
90
+
91
+ `MyWorker.perform_async` still supplies nothing — it is an ordinary
92
+ constant reference the report already sees. Neither does the mere
93
+ existence of a file under `app/workers`: a worker nothing enqueues
94
+ stays in the report, which is the answer you wanted.
95
+
96
+ The schedule is read with `YAML.safe_load`; nothing boots.
97
+ A missing, unreadable or malformed file is skipped without affecting
98
+ the rest of the run.
99
+
100
+ If your workers include a project concern (`include ApplicationWorker`)
101
+ rather than `Sidekiq::Job` directly, add that concern to
102
+ `worker_marker_modules` — otherwise the plugin discovers no workers,
103
+ every scheduled name is dropped, and you get no roots at all. GitLab's
104
+ `config/schedule.yml` names 111 workers, all of them concern-based:
105
+ with the default markers that is 0 roots, and with `ApplicationWorker`
106
+ added it is 100.
107
+
58
108
  ## Limitations
59
109
 
60
110
  - **Direct `include` only.** A worker that mixes in a custom concern
@@ -68,6 +118,10 @@ The default `worker_marker_modules` covers both modern Sidekiq
68
118
  `perform_at` is consumed as the schedule regardless of its type.
69
119
  - **Chained `set(...)`** (`Worker.set(queue: "low").perform_async(...)`)
70
120
  is validated as a normal call; `set`'s own options are not checked.
121
+ - **Schedule roots are read from `class:` only.** `sidekiq-cron`'s
122
+ alternative `klass:` spelling, and a schedule built in Ruby with
123
+ `Sidekiq::Cron::Job.load_from_hash!`, supply no roots — the worker
124
+ stays a `rigor unused` candidate rather than being guessed at.
71
125
 
72
126
  ## Plugin internals
73
127
 
@@ -44,6 +44,28 @@ module Rigor
44
44
  # return, used in value context. Authored `:warning`, resolved `:off` by every profile and promoted to
45
45
  # `:warning` only by the `use-of-void-value` bleeding-edge feature.
46
46
  RULE_VALUE_USE_VOID = "static.value-use.void"
47
+ # ADR-103 WD8 / #383 — the first `effect.*` id: a method whose PROVEN effect labels are not
48
+ # subsumed by the envelope its author declared (`%a{pure}` / `%a{rigor:v1:effect ...}`). Opt-in
49
+ # twice over — the `effects:` block enables collection, and the envelope is the author's own
50
+ # directive — so it is never unsolicited.
51
+ RULE_EFFECT_ENVELOPE_EXCEEDED = "effect.envelope-exceeded"
52
+ # ADR-103 WD1 / #384 — the paired vocabulary diagnostic. An unknown label degrades the whole tag
53
+ # to ⊤, which is silent by construction; this is what keeps that fail-open reading honest. It
54
+ # fires only where label intent is evident (`Effects::LabelIntent`'s four signals), so a project
55
+ # opening its own vocabulary is never nagged, and it is gated by the same `effects.check` switch
56
+ # as its sibling: opting into envelope enforcement is exactly what turns on the diagnostic that
57
+ # says an envelope stopped enforcing.
58
+ RULE_EFFECT_UNKNOWN_LABEL = "effect.unknown-label"
59
+ # ADR-103 WD1 / WD14 / #386 — the inherited-bound reading. An override performs, or itself
60
+ # declares, an effect the envelope written on the method it overrides does not admit. Implementations
61
+ # may be purer than the bound they inherit, never less pure; both-sides-authored in the ADR-35 sense,
62
+ # so nothing fires unless someone wrote an envelope on the ancestor.
63
+ RULE_EFFECT_LISKOV_WIDENED = "effect.liskov-widened"
64
+ # ADR-103 WD13 commitment 1 / #384 — the residual. A project whose RBS carries `%a{pure}` /
65
+ # `%a{rigor:v1:effect …}` but no `effects:` block gets ONE `:info` per run saying so. An
66
+ # annotation must never turn collection on by itself (that would be a project-wide cost cliff
67
+ # nobody asked for), and it must equally never be silently inert.
68
+ RULE_EFFECT_ANNOTATIONS_UNCHECKED = "effect.annotations-unchecked"
47
69
 
48
70
  ALL_RULES = [
49
71
  RULE_UNDEFINED_METHOD,
@@ -72,7 +94,11 @@ module Rigor
72
94
  RULE_SUPPRESSION_UNKNOWN_RULE,
73
95
  RULE_SUPPRESSION_EMPTY,
74
96
  RULE_SUPPRESSION_UNKNOWN_MARKER,
75
- RULE_VALUE_USE_VOID
97
+ RULE_VALUE_USE_VOID,
98
+ RULE_EFFECT_ENVELOPE_EXCEEDED,
99
+ RULE_EFFECT_LISKOV_WIDENED,
100
+ RULE_EFFECT_UNKNOWN_LABEL,
101
+ RULE_EFFECT_ANNOTATIONS_UNCHECKED
76
102
  ].freeze
77
103
 
78
104
  # Backward-compat alias table (ADR-8 § "Backward compatibility"). Existing user code with
@@ -102,7 +128,7 @@ module Rigor
102
128
 
103
129
  # Family wildcard — a `<family>` token in a suppression comment or `disable:` list disables every rule
104
130
  # whose canonical id starts with `<family>.`. Per ADR-8 § "1".
105
- RULE_FAMILIES = %w[call flow assert dump def suppression static].freeze
131
+ RULE_FAMILIES = %w[call flow assert dump def suppression static effect].freeze
106
132
 
107
133
  # Families of diagnostics the engine emits OUTSIDE the CheckRules catalogue (aggregator-level and
108
134
  # reporter-level diagnostics such as `rbs_extended.unsatisfied-conformance`,
@@ -5,6 +5,9 @@ require_relative "incremental"
5
5
  require_relative "plugin_fact_fingerprint"
6
6
  require_relative "../cache/file_digest"
7
7
  require_relative "../cache/incremental_snapshot"
8
+ require_relative "../effects/file_collection"
9
+ require_relative "../effects/identity"
10
+ require_relative "../effects/propagator"
8
11
  require_relative "../inference/scope_indexer"
9
12
 
10
13
  module Rigor
@@ -105,6 +108,7 @@ module Rigor
105
108
  # and a missing invalidation edge is impossible by construction — the reason this is a table diff
106
109
  # and not the caller→callee edge recording #204 first sketched.
107
110
  @param_table = {}
111
+ reset_effect_state
108
112
  # ADR-88 WD1 — the plugin fact-surface digest computed for THIS invocation (nil until a
109
113
  # `#run_incremental` pass runs / a plugin-free project) and the reporting flags a caller (the CLI
110
114
  # banner + `--cache-stats`) reads after `#run_incremental`. `@last_runner` is the analysis runner the
@@ -122,6 +126,32 @@ module Rigor
122
126
  @analyzed
123
127
  end
124
128
 
129
+ # ADR-103 WD12 / issue #382 — the session's effect graph: the fixpoint over the merged whole,
130
+ # recomputed on every ask. This is the invariant that makes per-file collection reuse sound — the
131
+ # closure is never partially reused, only its per-file *inputs* are, so a leaf edit whose new label
132
+ # reaches a caller in an unchanged file still shows up in that caller's `reach`.
133
+ def effect_table
134
+ Effects::Propagator.propagate(
135
+ effect_collection, discharge: Effects::Discharge.new(@configuration.effects_tolerated)
136
+ )
137
+ end
138
+
139
+ # The merged direct summaries the table above closes over.
140
+ def effect_collection
141
+ Effects::FileCollection.merge_all(sorted_effect_collections)
142
+ end
143
+
144
+ # Where each unit was defined — the same shape (and the same purpose: the snapshot's `reach:` globs)
145
+ # as `Runner#effect_sources`, answered from the session's own per-file collections.
146
+ def effect_sources
147
+ sorted_effect_collections.each_with_object({}) do |collection, out|
148
+ path = collection.path
149
+ next if path.nil?
150
+
151
+ collection.summaries.each_key { |key| (out[key] ||= []) << path }
152
+ end
153
+ end
154
+
125
155
  # Full baseline analysis with recording. Returns the run's diagnostics; populates the in-process cache
126
156
  # + dependency state.
127
157
  def baseline
@@ -135,6 +165,9 @@ module Rigor
135
165
  # ADR-67 WD6c lift — the seed table the runner's own pre-pass computed ({} when the gate is off).
136
166
  # Reading it back, rather than computing it here, keeps the baseline single-collect.
137
167
  @param_table = runner.param_inferred_types
168
+ # ADR-103 WD13 / #382 — a baseline collects every file, so its collections are the whole world.
169
+ @effect_collections = runner.effect_collections_by_path
170
+ @effects_identity = current_effects_identity
138
171
  @cache = per_file(diagnostics)
139
172
  @digests = @analyzed.to_h { |path| [path, pack_digest(path)] }
140
173
  diagnostics
@@ -417,10 +450,18 @@ module Rigor
417
450
  # (types with no fingerprint surface) make the snapshot un-reusable.
418
451
  if restored
419
452
  restore(restored)
453
+ # ADR-103 WD13 / #382 — the effects sidecar joins the same reuse decision, for a structurally
454
+ # identical reason: a snapshot whose summaries were collected under a different vocabulary /
455
+ # catalogue / `effects:` block restores as empty, and a recheck only re-collects the changed
456
+ # closure, so the merged table would be missing every unchanged file. A full baseline is the
457
+ # honest answer — it is what "recompute effects" means when collecting requires analysing, and
458
+ # it is paid on the first collecting run and on an identity change, never with collection off.
459
+ # Asked BEFORE the recheck, which re-stamps the session with the current identity.
460
+ effects_reusable = effects_reuse_permitted?(restored)
420
461
  result = recheck
421
462
  adopt_plugin_fact_fingerprint
422
- reuse = @plugin_fact_reusable.reusable_against?(restored.plugin_fact_digest)
423
- if reuse
463
+ fact_reusable = @plugin_fact_reusable.reusable_against?(restored.plugin_fact_digest)
464
+ if fact_reusable && effects_reusable
424
465
  diagnostics = result.diagnostics
425
466
  warm = true
426
467
  # ADR-87 WD3 — a warm recheck that changed nothing leaves the session state byte-equivalent to the
@@ -428,10 +469,12 @@ module Rigor
428
469
  # A cold baseline always persists — there was no valid snapshot to reuse.
429
470
  skip_save = result.no_change?
430
471
  else
431
- # The fact surface moved (a plugin sig/catalog edit) or a plugin is opaque: the cached-served
432
- # files the recheck merged may be stale, so re-analyze the whole tree. The current fact-surface
472
+ # The fact surface moved (a plugin sig/catalog edit), a plugin is opaque, or the effects
473
+ # identity moved: the cached-served files the recheck merged may be stale (or, for effects, a
474
+ # partial collection cannot be closed), so re-analyze the whole tree. The current fact-surface
433
475
  # digest (from the recheck runner) is unchanged by the re-analysis, so it is kept for the save.
434
- @fact_surface_invalidated = true
476
+ # Only a genuine fact-surface reason sets the reporting flag the CLI banner reads.
477
+ @fact_surface_invalidated = true unless fact_reusable
435
478
  diagnostics = baseline
436
479
  warm = false
437
480
  skip_save = false
@@ -459,6 +502,12 @@ module Rigor
459
502
 
460
503
  private
461
504
 
505
+ # Path-sorted, so the fold is reproducible whatever order the files were absorbed in (the same reason
506
+ # `Runner#effect_collections` sorts).
507
+ def sorted_effect_collections
508
+ @effect_collections.sort_by { |path, _| path.to_s }.map(&:last)
509
+ end
510
+
462
511
  # ADR-88 WD1 — capture this invocation's fact-surface fingerprint (from the last analysis runner) onto the
463
512
  # reporting ivars + the `@plugin_fact_reusable` decision object.
464
513
  def adopt_plugin_fact_fingerprint
@@ -509,6 +558,12 @@ module Rigor
509
558
  @class_decls = payload.class_decls || {}
510
559
  @return_summaries = payload.return_summaries || {}
511
560
  @param_table = payload.param_table || {} # ADR-67 WD6c lift — the seeds the cache was built under.
561
+ # ADR-103 WD13 / #382 — the effects sidecar rides its own identity, so a snapshot whose summaries
562
+ # were collected under a different vocabulary / catalogue / `effects:` block restores as EMPTY
563
+ # rather than as stale rows. {#run_incremental} turns that emptiness into a full baseline, because
564
+ # a partial re-collection cannot be closed into a whole-project fixpoint.
565
+ @effects_identity = payload.effects_identity
566
+ @effect_collections = effect_collections_reusable?(payload) ? payload.effect_collections.dup : {}
512
567
  @symbol_dependents = Incremental.invert_symbols(@symbol_sources)
513
568
  @ancestry_dependents = Incremental.invert(@ancestry_sources)
514
569
  @negative_dependents = Incremental.invert(@missing)
@@ -522,10 +577,71 @@ module Rigor
522
577
  class_decls: @class_decls, seed_bundles: @seed_bundles,
523
578
  plugin_fact_digest: @plugin_fact_digest,
524
579
  return_summaries: marshal_safe_return_summaries,
525
- param_table: marshal_safe_param_table
580
+ param_table: marshal_safe_param_table,
581
+ effect_collections: marshal_safe_effect_collections,
582
+ effects_identity: @effects_identity
526
583
  )
527
584
  end
528
585
 
586
+ # ADR-103 WD13 / issue #382 — the per-file effect collections the session serves unchanged files
587
+ # from, and the effects identity they were collected under. Empty / nil when collection is off, which
588
+ # is every run that does not carry an `effects:` block. The PROPAGATED table is never kept here:
589
+ # {#effect_table} re-runs the fixpoint over the merged whole on every ask, because a leaf's summary
590
+ # reaches every caller and there is no per-file invalidation for a whole-graph closure.
591
+ def reset_effect_state
592
+ @effect_collections = {}
593
+ @effects_identity = nil
594
+ end
595
+
596
+ # Whether the effects half of a restored snapshot permits reuse. Collection off is vacuously true —
597
+ # the session keeps no collections, writes none, and the pre-#382 reuse decision stands unchanged.
598
+ def effects_reuse_permitted?(payload)
599
+ !@configuration.effects_enabled? || effect_collections_reusable?(payload)
600
+ end
601
+
602
+ # ADR-103 WD13 / #382 — whether a restored payload's effect collections may be served this run:
603
+ # collection is on, and they were collected under the identity this run computes. Collection being
604
+ # OFF answers false and costs nothing — the session then keeps no collections, writes none, and is
605
+ # the pre-#382 session in every observable way.
606
+ def effect_collections_reusable?(payload)
607
+ return false unless @configuration.effects_enabled?
608
+ return false if payload.effects_identity.nil? || !payload.effect_collections.is_a?(Hash)
609
+
610
+ payload.effects_identity == current_effects_identity
611
+ end
612
+
613
+ # The effects identity for THIS run, memoised: it digests a YAML catalogue and the `effects:` block,
614
+ # and a recheck asks for it on both the restore and the absorb side. nil when collection is off, so a
615
+ # non-collecting run never loads the catalogue at all.
616
+ #
617
+ # **Deliberately plugin-blind**, unlike the ADR-45 whole-run effects slot, whose descriptor carries
618
+ # {Effects::PluginFacts#digest} (#387). The two sides of this comparison sit on opposite sides of the
619
+ # run: the restore asks before any plugin is loaded and the save asks after, so folding the plugin
620
+ # facts in here would compare a blind digest against a sighted one and miss every single time. The
621
+ # bound it leaves — a plugin upgrade that moves a row does not invalidate an `--incremental`
622
+ # snapshot's effect collections — is recorded in `docs/internal-spec/effect-summaries.md`; the
623
+ # primary (whole-run) path has no such hole, and `--incremental` is opt-in.
624
+ def current_effects_identity
625
+ return nil unless @configuration.effects_enabled?
626
+
627
+ @current_effects_identity ||= Effects::Identity.digest(configuration: @configuration)
628
+ end
629
+
630
+ # The same Marshal-clean guard {#marshal_safe_return_summaries} applies, for the same reason: a
631
+ # snapshot save must never raise. A dropped collection makes that file's summaries absent from the
632
+ # next run's merged table, which understates its effects — so it is dropped only when it genuinely
633
+ # will not serialise, and {FileCollection} is built to (the fork pool marshals one per file already).
634
+ def marshal_safe_effect_collections
635
+ return {} unless @configuration.effects_enabled?
636
+
637
+ @effect_collections.each_with_object({}) do |(path, collection), safe|
638
+ Marshal.dump(collection)
639
+ safe[path] = collection
640
+ rescue StandardError
641
+ next
642
+ end
643
+ end
644
+
529
645
  # ADR-89 WD2 — the return summaries filtered to Marshal-clean entries. A summary's `keys` hold live
530
646
  # `Type` objects; the common carriers (Nominal, Constant, Union, shapes, Dynamic) Marshal, but a type
531
647
  # holding a live AST node would raise and abort the WHOLE snapshot save (a cache must never break a
@@ -568,6 +684,21 @@ module Rigor
568
684
  end
569
685
  absorb_dependency_graph(runner)
570
686
  refresh_return_summaries(runner, analyze_set)
687
+ refresh_effect_collections(runner, analyze_set)
688
+ end
689
+
690
+ # ADR-103 WD13 / #382 — the effects analogue of {#refresh_return_summaries}, and the same soundness
691
+ # order: drop every re-analyzed file's collection first, then fold this run's harvest in. A file the
692
+ # recheck did NOT analyze keeps the collection the snapshot carried, which is exactly the reuse the
693
+ # slot exists for; a re-analyzed file that produced nothing (a parse failure, a file of constants)
694
+ # correctly ends up with nothing rather than with its pre-edit summaries.
695
+ def refresh_effect_collections(runner, analyze_set)
696
+ return unless @configuration.effects_enabled?
697
+
698
+ analyzed = analyze_set.to_set
699
+ @effect_collections.reject! { |path, _| analyzed.include?(path) }
700
+ @effect_collections.merge!(runner.effect_collections_by_path)
701
+ @effects_identity = current_effects_identity
571
702
  end
572
703
 
573
704
  # ADR-89 WD2 — replace the behavioural summaries of every re-analyzed file with THIS run's harvest: drop
@@ -599,6 +730,9 @@ module Rigor
599
730
  @symbol_fingerprints.delete(path)
600
731
  # ADR-89 WD2 — drop every behavioural summary a removed file provided (keys are `[path, symbol]`).
601
732
  @return_summaries.reject! { |(summary_path, _symbol), _| summary_path == path }
733
+ # ADR-103 WD13 / #382 — and its effect collection, so a deleted file stops contributing summaries
734
+ # and edges to the merged table the fixpoint closes.
735
+ @effect_collections.delete(path)
602
736
  # @class_decls is wholesale-replaced from the (removed-excluding)
603
737
  # pre-pass in absorb_dependency_graph, and is frozen, so no delete.
604
738
  end
@@ -0,0 +1,244 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "scan"
4
+
5
+ module Rigor
6
+ module Analysis
7
+ module Reachability
8
+ # ADR-102 — the cross-file half: resolves every as-written reference to a declaration, then marks from the
9
+ # root set. Pure data; no engine coupling, so `rigor check`'s diagnostic stream is untouched by
10
+ # construction rather than by a gate (WD1).
11
+ #
12
+ # Resolution mirrors `Reflection.resolve_constant_type`'s candidate order — lexical nesting innermost
13
+ # first, then the ancestors of the innermost cresting scope, then the bare name — because a reference
14
+ # index that resolved names differently from the engine would report on a graph the analyzer does not
15
+ # believe in. The two walks are separate implementations (this one is name-level and needs no types), so
16
+ # `spec/rigor/analysis/reachability/graph_spec.rb` pins them to the same answers on shared fixtures.
17
+ class Graph
18
+ Candidate = Data.define(:fqn, :path, :line)
19
+
20
+ # `test_only` is its own list, not a flag on `candidates`: a candidate is by definition unreachable, so
21
+ # a flag there could never be true. "Reachable, but only from test code" is a SEPARATE and more
22
+ # actionable answer — dead production code with a live test — which is exactly what ADR-102 WD8 requires
23
+ # be reported as its own category rather than folded into a bucket boundary.
24
+ Report = Data.define(:declared, :reachable, :candidates, :undecidable, :test_only, :namespaces,
25
+ :roots, :edges)
26
+
27
+ # A candidate demoted out of `candidates` because something can reach it by a mechanism this reading
28
+ # cannot follow (ADR-102 WD4). Carries the reason so the reader can judge it rather than take the
29
+ # bucket on trust.
30
+ Undecidable = Data.define(:fqn, :path, :line, :reason)
31
+
32
+ # @param declarations [Array<Scan::Declaration>]
33
+ # @param references [Array<Scan::Reference>]
34
+ # @param root_fqns [Enumerable<String>] declarations that are entry points regardless of who references
35
+ # them (config-declared globs in this slice; plugin-supplied roots are #349).
36
+ # @param foreign [#call] predicate answering "is this FQN owned by something outside the project?" —
37
+ # a reopened gem or stdlib class must never be a candidate (WD6). Defaults to "nothing is foreign".
38
+ # @param dynamic_uses [Array<Scan::DynamicUse>] sites where a constant is reached by name at runtime.
39
+ # A literal-argument site contributes a real reference; a dynamic one taints a namespace (WD4).
40
+ def initialize(declarations:, references:, root_fqns: [], dynamic_uses: [], foreign: ->(_fqn) { false })
41
+ @declarations = declarations
42
+ @dynamic_uses = dynamic_uses
43
+ @references = references + literal_dynamic_references(dynamic_uses)
44
+ @root_fqns = root_fqns.to_set
45
+ @foreign = foreign
46
+ @by_fqn = declarations.group_by(&:fqn)
47
+ @owned = @by_fqn.keys.reject { |fqn| @foreign.call(fqn) }.to_set
48
+ @ancestors = {}
49
+ end
50
+
51
+ def report
52
+ edges = resolved_edges
53
+ production = walk(edges, seeds: production_seeds, roles: %i[production task config])
54
+ reachable = walk(edges, seeds: production_seeds | test_seeds, roles: %i[production task config test])
55
+ unreached = @owned - reachable
56
+ namespaces = namespace_only(unreached, reachable)
57
+ undecidable = tainted(unreached - namespaces)
58
+ Report.new(declared: @owned.size, reachable: reachable.size,
59
+ candidates: rows(unreached - namespaces - undecidable.keys.to_set),
60
+ undecidable: undecidable.map { |fqn, reason| undecidable_row(fqn, reason) }.freeze,
61
+ test_only: rows(reachable - production),
62
+ namespaces: namespaces.size, roots: production_seeds.size, edges: edges.size)
63
+ end
64
+
65
+ private
66
+
67
+ # A literal-argument `"Foo::Bar".constantize` names its constant exactly, so it is a REFERENCE, not an
68
+ # unknown. Keeping this distinct from the taint below is what stops the tier being a blanket namespace
69
+ # poison — Rigor knows the argument's shape, and a type-free indexer does not.
70
+ def literal_dynamic_references(dynamic_uses)
71
+ dynamic_uses.filter_map do |use|
72
+ next if use.name.nil?
73
+
74
+ Scan::Reference.new(as_written: use.name.sub(/\A::/, ""), nesting: [].freeze, from: nil,
75
+ role: :production, path: use.path, line: use.line)
76
+ end
77
+ end
78
+
79
+ # `{fqn => reason}` for every unreached declaration a dynamic site could still be naming. A site with a
80
+ # literal prefix taints that namespace and everything under it; a site with no prefix at all cannot be
81
+ # bounded, so it taints nothing rather than everything — poisoning the whole project would empty the
82
+ # report and teach the reader that the tier means nothing.
83
+ def tainted(unreached)
84
+ prefixes = @dynamic_uses.filter_map { |use| [use.prefix, use] if use.name.nil? && use.prefix }
85
+
86
+ return {} if prefixes.empty?
87
+
88
+ unreached.each_with_object({}) do |fqn, out|
89
+ _, use = prefixes.find { |prefix, _| fqn == prefix || fqn.start_with?("#{prefix}::") }
90
+ out[fqn] = use.site.nil? ? use.reason : "#{use.reason} (#{use.site})" if use
91
+ end
92
+ end
93
+
94
+ def undecidable_row(fqn, reason)
95
+ site = @by_fqn.fetch(fqn).first
96
+ Undecidable.new(fqn: fqn, path: site.path, line: site.line, reason: reason)
97
+ end
98
+
99
+ # `module A; end` wrapping a live `A::B` is not dead code, but nothing ever references `A` by itself:
100
+ # a reference to `A::B::Leaf` records the leaf only, never the intermediate segments. Reporting these
101
+ # buried the real rows — 12 of 18 candidates on Rigor's own `lib`, and 22 of 140 in the #345 probe,
102
+ # were pure namespaces.
103
+ #
104
+ # The test is deliberately "some REACHABLE declaration lives under it", not "some declaration lives
105
+ # under it": a namespace whose entire contents are dead is itself a genuine finding, and its children
106
+ # appear alongside it rather than being explained away.
107
+ def namespace_only(unreached, reachable)
108
+ unreached.select do |fqn|
109
+ prefix = "#{fqn}::"
110
+ reachable.any? { |other| other.start_with?(prefix) }
111
+ end.to_set
112
+ end
113
+
114
+ # Seeds that make a declaration live in PRODUCTION: named entry points, plus anything referenced at
115
+ # file level by a non-test file (file-level code runs on load, so its target is live).
116
+ def production_seeds
117
+ @production_seeds ||= (@root_fqns & @owned) | seeds_from { |ref| ref.from.nil? && ref.role != :test }
118
+ end
119
+
120
+ # Seeds that make a declaration live only through TEST code. Kept separate from production seeds
121
+ # rather than folded in: a spec's file-level `Foo.new` would otherwise promote `Foo` to a root and
122
+ # erase the very distinction WD8 exists to report.
123
+ def test_seeds
124
+ @test_seeds ||= seeds_from { |ref| ref.from.nil? && ref.role == :test }
125
+ end
126
+
127
+ def seeds_from
128
+ set = Set.new
129
+ @references.each do |ref|
130
+ next unless yield(ref)
131
+
132
+ target = resolve(ref.as_written, ref.nesting)
133
+ set << target if target && @owned.include?(target)
134
+ end
135
+ set
136
+ end
137
+
138
+ # `[from_fqn_or_nil, to_fqn, role]` for every reference that resolves to an owned declaration.
139
+ def resolved_edges
140
+ @resolved_edges ||= @references.filter_map do |ref|
141
+ target = resolve(ref.as_written, ref.nesting)
142
+ next unless target && @owned.include?(target)
143
+ next if ref.from == target # a declaration referencing itself is not evidence of use
144
+
145
+ [ref.from, target, ref.role]
146
+ end
147
+ end
148
+
149
+ # Mark-and-sweep, not reference counting: an edge only propagates if its SOURCE is itself reachable, so
150
+ # a cluster of mutually-referencing dead classes stays dead (ADR-102 WD2).
151
+ #
152
+ # Run twice with different edge roles admitted (WD8). The production pass admits everything except
153
+ # test-sourced edges; the full pass admits all of them. The difference is exactly "reachable, but only
154
+ # from test code" — dead production code with a live test, which is a finding rather than a bucket edge.
155
+ def walk(edges, seeds:, roles:)
156
+ admitted = roles.to_set
157
+ out = Hash.new { |h, k| h[k] = [] }
158
+ edges.each { |from, to, role| out[from] << to if admitted.include?(role) }
159
+
160
+ seen = seeds.dup
161
+ queue = seeds.to_a
162
+ until queue.empty?
163
+ out[queue.shift].each do |target|
164
+ next if seen.include?(target)
165
+
166
+ seen << target
167
+ queue << target
168
+ end
169
+ end
170
+ seen
171
+ end
172
+
173
+ def rows(fqns)
174
+ fqns.sort.map do |fqn|
175
+ site = @by_fqn.fetch(fqn).first
176
+ Candidate.new(fqn: fqn, path: site.path, line: site.line)
177
+ end.freeze
178
+ end
179
+
180
+ # Ruby's constant lookup at name granularity: `Module.nesting` innermost first, then the ancestors of
181
+ # the innermost cresting scope (#354), then the bare name.
182
+ def resolve(as_written, nesting)
183
+ walker = nesting.dup
184
+ until walker.empty?
185
+ candidate = (walker + [as_written]).join("::")
186
+ return candidate if @by_fqn.key?(candidate)
187
+
188
+ walker.pop
189
+ end
190
+
191
+ unless nesting.empty?
192
+ ancestor_scopes(nesting.join("::")).each do |ancestor|
193
+ candidate = "#{ancestor}::#{as_written}"
194
+ return candidate if @by_fqn.key?(candidate)
195
+ end
196
+ end
197
+
198
+ return as_written if @by_fqn.key?(as_written)
199
+
200
+ # `Scope::DiscoveryIndex::EMPTY` names a constant INSIDE a class, and reading it is a use of that
201
+ # class — but the leaf is not itself a declaration, so the reference would resolve to nothing and
202
+ # `Scope::DiscoveryIndex` would be reported as unused despite being read all over the engine (it was,
203
+ # on the first run of this report against Rigor's own `lib`). Peel the trailing segment and retry:
204
+ # a reference to a member is a reference to its owner.
205
+ idx = as_written.rindex("::")
206
+ idx ? resolve(as_written[0, idx], nesting) : nil
207
+ end
208
+
209
+ # Breadth-first over superclass + included modules, mixins first, terminating on a cycle. As-written
210
+ # ancestor names resolve against the subclass's own nesting; a name naming no declaration is dropped.
211
+ def ancestor_scopes(fqn)
212
+ @ancestors[fqn] ||= begin
213
+ seen = Set[fqn]
214
+ queue = [fqn]
215
+ out = []
216
+ until queue.empty?
217
+ current = queue.shift
218
+ @by_fqn.fetch(current, []).each do |decl|
219
+ (decl.includes + [decl.superclass]).compact.each do |raw|
220
+ resolved = resolve_ancestor(current, raw)
221
+ next if resolved.nil? || seen.include?(resolved)
222
+
223
+ seen << resolved
224
+ out << resolved
225
+ queue << resolved
226
+ end
227
+ end
228
+ end
229
+ out.freeze
230
+ end
231
+ end
232
+
233
+ def resolve_ancestor(subclass_fqn, raw)
234
+ segments = subclass_fqn.split("::")
235
+ (segments.length - 1).downto(0) do |i|
236
+ candidate = (segments[0, i] + [raw]).join("::")
237
+ return candidate if @by_fqn.key?(candidate)
238
+ end
239
+ nil
240
+ end
241
+ end
242
+ end
243
+ end
244
+ end