ui_guardrails 1.7.0 → 2.0.0.rc1

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 (45) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +254 -46
  3. data/doc/A11Y.md +4 -4
  4. data/doc/PRD.md +7 -7
  5. data/doc/PUBLISHING.md +4 -0
  6. data/doc/ROADMAP.md +30 -10
  7. data/doc/VISUAL-DIFF.md +8 -8
  8. data/exe/guardrails-hook +1 -1
  9. data/exe/ui_guardrails-mcp +32 -0
  10. data/lib/guardrails/a11y_deep.rb +1 -1
  11. data/lib/guardrails/audit/markdown_writer.rb +5 -0
  12. data/lib/guardrails/audit.rb +129 -6
  13. data/lib/guardrails/class_itis.rb +2 -45
  14. data/lib/guardrails/erb_parser.rb +53 -0
  15. data/lib/guardrails/feed_ramp/agent_rules.rb +309 -0
  16. data/lib/guardrails/feed_ramp/components_markdown.rb +135 -0
  17. data/lib/guardrails/feed_ramp/config.rb +113 -0
  18. data/lib/guardrails/feed_ramp/design_tokens.rb +112 -0
  19. data/lib/guardrails/feed_ramp/discovery.rb +201 -0
  20. data/lib/guardrails/feed_ramp/libraries.rb +27 -0
  21. data/lib/guardrails/feed_ramp/manifest.rb +142 -0
  22. data/lib/guardrails/feed_ramp/mcp.rb +325 -0
  23. data/lib/guardrails/feed_ramp/mcp_install.rb +150 -0
  24. data/lib/guardrails/feed_ramp/modern_web.rb +83 -0
  25. data/lib/guardrails/feed_ramp/rails_config.rb +144 -0
  26. data/lib/guardrails/feed_ramp/root_element.rb +361 -0
  27. data/lib/guardrails/feed_ramp/ruby_source.rb +230 -0
  28. data/lib/guardrails/feed_ramp/score.rb +256 -0
  29. data/lib/guardrails/feed_ramp/snippet_check.rb +221 -0
  30. data/lib/guardrails/feed_ramp/usages.rb +174 -0
  31. data/lib/guardrails/feed_ramp.rb +27 -0
  32. data/lib/guardrails/hooks/config_file.rb +28 -2
  33. data/lib/guardrails/hooks/installer.rb +5 -2
  34. data/lib/guardrails/hooks.rb +24 -1
  35. data/lib/guardrails/init/config_writer.rb +21 -4
  36. data/lib/guardrails/init/prompter.rb +1 -1
  37. data/lib/guardrails/railtie.rb +2 -0
  38. data/lib/guardrails/report/detectors.rb +1 -1
  39. data/lib/guardrails/report/run.rb +6 -5
  40. data/lib/guardrails/tokens.rb +9 -9
  41. data/lib/guardrails/tui.rb +2 -2
  42. data/lib/guardrails/version.rb +1 -1
  43. data/lib/tasks/guardrails.rake +16 -156
  44. data/lib/tasks/ui_guardrails.rake +304 -0
  45. metadata +21 -1
@@ -0,0 +1,309 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "pathname"
4
+ require_relative "../../guardrails"
5
+ require_relative "config"
6
+ require_relative "modern_web"
7
+
8
+ module Guardrails
9
+ module FeedRamp
10
+ # Tells coding agents the component library exists, in the files they
11
+ # read at the start of every session: a block between two marker
12
+ # comments in CLAUDE.md, AGENTS.md (and, opted in, GEMINI.md and
13
+ # .github/copilot-instructions.md), and a Cursor rule file of its own.
14
+ #
15
+ # Only the block is ever written. Everything outside the markers is
16
+ # left byte for byte, a file without them gets the block at the end,
17
+ # and running it again with the same manifest changes nothing. A file
18
+ # whose markers are duplicated or unpaired is left alone with an
19
+ # error, since there's no telling which part is ours.
20
+ class AgentRules
21
+ BEGIN_MARKER = "<!-- ui_guardrails:feed_ramp:begin -->"
22
+ END_MARKER = "<!-- ui_guardrails:feed_ramp:end -->"
23
+
24
+ TARGETS = {
25
+ "claude" => "CLAUDE.md",
26
+ "agents" => "AGENTS.md",
27
+ "cursor" => ".cursor/rules/ui-guardrails.mdc",
28
+ "gemini" => "GEMINI.md",
29
+ "copilot" => ".github/copilot-instructions.md"
30
+ }.freeze
31
+ DEFAULT_TARGETS = Config::DEFAULT_RULES_TARGETS
32
+
33
+ # The Cursor rule is a file of its own: it's rewritten whole.
34
+ OWNED = %w[cursor].freeze
35
+
36
+ # Claude Code's `@AGENTS.md` import: the block is already in context
37
+ # through AGENTS.md, so CLAUDE.md doesn't get a second copy.
38
+ AGENTS_IMPORT = %r{(?:\A|\s)@(?:\./)?AGENTS\.md\b}
39
+
40
+ # Project configs that can start the Feed Ramp MCP server.
41
+ MCP_CONFIGS = %w[.mcp.json .codex/config.toml .cursor/mcp.json .gemini/settings.json].freeze
42
+
43
+ COMPONENT_INDEX_LIMIT = 50
44
+ TOKEN_EXAMPLES = 3
45
+
46
+ # `status` is :created, :updated, :unchanged, :removed or :skipped
47
+ # (with `reason`).
48
+ Change = Struct.new(:target, :path, :status, :reason, keyword_init: true)
49
+
50
+ # The rules for a Manifest, to the targets in its config unless
51
+ # others are given.
52
+ def self.for(manifest, targets: nil)
53
+ new(root: manifest.root, manifest: manifest.to_h,
54
+ manifest_path: manifest.path.relative_path_from(manifest.root),
55
+ markdown_path: manifest.markdown_path.relative_path_from(manifest.root),
56
+ targets: targets || manifest.config.rules_targets, component_paths: manifest.config.component_paths,
57
+ modern_web: manifest.config.modern_web_guidance)
58
+ end
59
+
60
+ # `manifest` is a Manifest's `to_h`; `manifest_path` and
61
+ # `markdown_path` are where its files are, relative to root.
62
+ # `modern_web` says whether to mention the Modern Web Guidance
63
+ # skill; nil goes by whether it's installed in the project.
64
+ def initialize(root:, manifest:, manifest_path:, markdown_path:, targets: DEFAULT_TARGETS, component_paths: [],
65
+ modern_web: nil)
66
+ @root = Pathname(root)
67
+ @manifest = manifest
68
+ @manifest_path = manifest_path.to_s
69
+ @markdown_path = markdown_path.to_s
70
+ @targets = Array(targets).map(&:to_s).uniq
71
+ @component_paths = component_paths
72
+ @modern_web = modern_web
73
+ unknown = @targets - TARGETS.keys
74
+ raise Error, "Unknown agent rules target #{unknown.join(", ")}; expected #{TARGETS.keys.join(", ")}" if unknown.any?
75
+ end
76
+
77
+ # Writes the block to each target. Returns one Change per target.
78
+ def write
79
+ each_target { |target, path| write_target(target, path) }
80
+ end
81
+
82
+ # Takes the block out of each target, and deletes a file left empty
83
+ # (or the Cursor rule).
84
+ def remove
85
+ each_target(skip_imports: false) { |target, path| remove_target(target, path) }
86
+ end
87
+
88
+ # Targets whose file doesn't hold the current block.
89
+ def stale
90
+ each_target(dry_run: true) { |target, path| write_target(target, path, dry_run: true) }
91
+ .reject { |change| %i[unchanged skipped].include?(change.status) }
92
+ end
93
+
94
+ # The managed block, markers included, with no trailing newline.
95
+ def block(heading: "##")
96
+ lines = [BEGIN_MARKER,
97
+ "<!-- Generated by `rake ui_guardrails:feed_ramp:rules` from #{@manifest_path}. " \
98
+ "Edits between these markers are overwritten. -->",
99
+ "#{heading} UI components and design tokens", ""]
100
+ lines.concat(instructions)
101
+ lines.concat(["", *component_index]) if components.any?
102
+ lines.concat(["", *token_index]) if tokens.any?
103
+ lines << END_MARKER
104
+ lines.join("\n")
105
+ end
106
+
107
+ private
108
+
109
+ def components
110
+ @manifest.fetch("components", [])
111
+ end
112
+
113
+ def tokens
114
+ @manifest.fetch("tokens", [])
115
+ end
116
+
117
+ def instructions
118
+ list = []
119
+ if components.any?
120
+ list << "- This app has a component library. Before writing markup in a view, partial or component, " \
121
+ "look in `#{@markdown_path}` for a component that already does the job and render it. " \
122
+ "Each one's params, slots, previews and a real usage example are there; " \
123
+ "`#{@manifest_path}` has the same data as JSON."
124
+ list << "- Follow the component's usage example rather than copying its HTML. " \
125
+ "Only write a new component when none fits, and say why."
126
+ if mcp_installed?
127
+ list << "- The `ui_guardrails` MCP server answers the same questions as tools: `search_components`, " \
128
+ "`get_component`, and `check_snippet` to check ERB or Phlex before writing the file."
129
+ end
130
+ end
131
+ if tokens.any?
132
+ list << "- Use the design tokens listed in `#{@markdown_path}` instead of raw colours, " \
133
+ "pixel sizes or arbitrary Tailwind values."
134
+ end
135
+ list << modern_web_instruction if modern_web?
136
+ list << "- `rake ui_guardrails:audit` reports UI drift (raw colours, inline styles, missing alt text) " \
137
+ "in the views you changed."
138
+ list
139
+ end
140
+
141
+ def modern_web?
142
+ @modern_web.nil? ? ModernWeb.installed?(@root) : @modern_web
143
+ end
144
+
145
+ # The app's own library comes first: a guide is for what no
146
+ # component covers, and for the inside of the components.
147
+ def modern_web_instruction
148
+ line = "- For HTML, CSS and client-side JavaScript the platform may already cover (dialogs, popovers, " \
149
+ "forms, layout, animation, performance), search the `#{ModernWeb::SKILL}` skill " \
150
+ "([#{ModernWeb::NAME}](#{ModernWeb::URL})) before writing it."
151
+ return line unless components.any? || tokens.any?
152
+
153
+ "#{line} This app's components and design tokens come first: follow a guide where none of them " \
154
+ "does the job, and inside the components themselves."
155
+ end
156
+
157
+ def mcp_installed?
158
+ MCP_CONFIGS.any? { |file| (path = @root.join(file)).file? && path.read.include?("ui_guardrails-mcp") }
159
+ end
160
+
161
+ def component_index
162
+ shown = components.first(COMPONENT_INDEX_LIMIT).map do |component|
163
+ summary = first_sentence(component["description"])
164
+ "- `#{component["name"]}`#{" — #{summary}" if summary}"
165
+ end
166
+ more = components.length - shown.length
167
+ shown << "- …and #{more} more in `#{@markdown_path}`." if more.positive?
168
+ ["Components (#{components.length}):", "", *shown]
169
+ end
170
+
171
+ def token_index
172
+ by_category = tokens.group_by { |token| token["category"] }.sort_by { |category, _| category.to_s }
173
+ lines = by_category.map do |category, list|
174
+ names = list.first(TOKEN_EXAMPLES).map { |token| "`#{token["name"]}`" }
175
+ names << "…" if list.length > TOKEN_EXAMPLES
176
+ "- #{category} (#{list.length}): #{names.join(", ")}"
177
+ end
178
+ ["Design tokens (#{tokens.length}):", "", *lines]
179
+ end
180
+
181
+ def first_sentence(text)
182
+ return nil if text.nil? || text.strip.empty?
183
+
184
+ sentence = text.strip.split(/(?<=[.!?])\s+/).first.gsub(/\s+/, " ")
185
+ sentence.length > 120 ? "#{sentence[0, 119].rstrip}…" : sentence
186
+ end
187
+
188
+ # Yields each target and its path, skipping CLAUDE.md when it
189
+ # imports AGENTS.md (and AGENTS.md is a target), and any file that's
190
+ # a link to one already handled.
191
+ def each_target(skip_imports: true, dry_run: false)
192
+ seen = {}
193
+ @targets.map do |target|
194
+ path = @root.join(TARGETS.fetch(target))
195
+ real = path.exist? ? path.realpath : path
196
+ if (other = seen[real])
197
+ next Change.new(target: target, path: path, status: :skipped, reason: "same file as #{TARGETS[other]}")
198
+ end
199
+
200
+ seen[real] = target
201
+ if skip_imports && imports_agents?(target, path)
202
+ # A block written before the import was added goes; the one
203
+ # in AGENTS.md is what Claude reads now.
204
+ had_block = !markers(path.read, path).nil?
205
+ remove_target(target, path) if had_block && !dry_run
206
+ next Change.new(target: target, path: path, status: had_block ? :removed : :skipped,
207
+ reason: "imports AGENTS.md")
208
+ end
209
+
210
+ yield target, path
211
+ end
212
+ end
213
+
214
+ def imports_agents?(target, path)
215
+ target == "claude" && @targets.include?("agents") && path.file? && path.read.match?(AGENTS_IMPORT)
216
+ end
217
+
218
+ def write_target(target, path, dry_run: false)
219
+ text = path.file? ? path.read : nil
220
+ content = OWNED.include?(target) ? owned_content(text, path) : with_block(text, path)
221
+ status = if text.nil? then :created
222
+ elsif text == content then :unchanged
223
+ else :updated
224
+ end
225
+ if !dry_run && status != :unchanged
226
+ path.dirname.mkpath
227
+ path.write(content)
228
+ end
229
+ Change.new(target: target, path: path, status: status)
230
+ end
231
+
232
+ def remove_target(target, path)
233
+ return Change.new(target: target, path: path, status: :unchanged) unless path.file?
234
+
235
+ text = path.read
236
+ range = markers(text, path)
237
+ return Change.new(target: target, path: path, status: :unchanged) unless range
238
+
239
+ eol = text.include?("\r\n") ? "\r\n" : "\n"
240
+ before = text[0...range.begin].sub(/\s*\z/, "")
241
+ after = text[range.end..].sub(/\A\s*\n/, "")
242
+ rest = OWNED.include?(target) ? "" : [before, after].reject(&:empty?).join(eol * 2)
243
+ if rest.strip.empty?
244
+ path.delete
245
+ path.dirname.rmdir if OWNED.include?(target) && path.dirname.empty?
246
+ else
247
+ path.write(after.empty? ? "#{rest}#{eol}" : rest)
248
+ end
249
+ Change.new(target: target, path: path, status: :removed)
250
+ end
251
+
252
+ # The file with the block in place of the old one, or added at the
253
+ # end. Keeps the file's own line endings.
254
+ def with_block(text, path)
255
+ crlf = text&.include?("\r\n")
256
+ block = crlf ? self.block.gsub("\n", "\r\n") : self.block
257
+ eol = crlf ? "\r\n" : "\n"
258
+ return "#{block}#{eol}" if text.nil? || text.strip.empty?
259
+
260
+ range = markers(text, path)
261
+ return "#{text[0...range.begin]}#{block}#{text[range.end..]}" if range
262
+
263
+ "#{text.sub(/\s*\z/, "")}#{eol}#{eol}#{block}#{eol}"
264
+ end
265
+
266
+ # A Cursor project rule, attached when the agent works on views and
267
+ # components. Refuses to replace a file Feed Ramp didn't write.
268
+ def owned_content(text, path)
269
+ if text && !text.strip.empty? && markers(text, path).nil?
270
+ raise Error, "#{relative(path)} wasn't written by ui_guardrails; move it aside or add the rules by hand"
271
+ end
272
+
273
+ dirs = (["app/views"] + @component_paths).map { |dir| dir.chomp("/") }.uniq
274
+ globs = dirs.reject { |dir| dirs.any? { |other| dir.start_with?("#{other}/") } }.map { |dir| "#{dir}/**/*" }
275
+ <<~MDC
276
+ ---
277
+ description: Use this app's UI components and design tokens instead of writing markup by hand
278
+ globs: #{globs.join(",")}
279
+ alwaysApply: false
280
+ ---
281
+
282
+ #{block(heading: "#")}
283
+ MDC
284
+ end
285
+
286
+ # The character range from the begin marker to the end of the end
287
+ # marker, or nil when the text has neither.
288
+ def markers(text, path)
289
+ begins = text.scan(BEGIN_MARKER).length
290
+ ends = text.scan(END_MARKER).length
291
+ return nil if begins.zero? && ends.zero?
292
+
293
+ start = text.index(BEGIN_MARKER)
294
+ finish = text.index(END_MARKER)
295
+ if begins != 1 || ends != 1 || finish < start
296
+ found = begins == 1 && ends == 1 ? "the end marker before the begin marker" : "#{begins} begin and #{ends} end markers"
297
+ raise Error, "#{relative(path)}: expected one ui_guardrails:feed_ramp begin marker followed by one end marker, " \
298
+ "found #{found}; fix them by hand"
299
+ end
300
+
301
+ start...(finish + END_MARKER.length)
302
+ end
303
+
304
+ def relative(path)
305
+ path.relative_path_from(@root).to_s
306
+ end
307
+ end
308
+ end
309
+ end
@@ -0,0 +1,135 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Guardrails
4
+ module FeedRamp
5
+ # COMPONENTS.md: the manifest as a page an agent (or a person) reads
6
+ # before writing view markup. Rendered from the manifest hash alone,
7
+ # so it's exactly as deterministic as the manifest.
8
+ class ComponentsMarkdown
9
+ KIND_LABELS = { "view_component" => "ViewComponent", "phlex" => "Phlex" }.freeze
10
+
11
+ def initialize(manifest, manifest_path:)
12
+ @manifest = manifest
13
+ @manifest_path = manifest_path
14
+ end
15
+
16
+ def render
17
+ sections = [header]
18
+ sections << index unless components.empty?
19
+ sections.concat(components.map { |component| component_section(component) })
20
+ sections << tokens_section unless tokens.empty?
21
+ "#{sections.join("\n\n")}\n"
22
+ end
23
+
24
+ private
25
+
26
+ def components
27
+ @manifest["components"]
28
+ end
29
+
30
+ def tokens
31
+ @manifest["tokens"]
32
+ end
33
+
34
+ def header
35
+ <<~MD.chomp
36
+ # Components
37
+
38
+ <!-- Generated by `rake ui_guardrails:feed_ramp:manifest` (#{@manifest["generator"]}). Don't edit; regenerate. -->
39
+
40
+ This app's component library and design tokens. Render one of these components instead of writing
41
+ the same markup by hand, and use a token instead of a hardcoded colour or size whenever one exists.
42
+ Machine-readable version: `#{@manifest_path}`.
43
+
44
+ #{summary}
45
+ MD
46
+ end
47
+
48
+ def summary
49
+ noun = components.length == 1 ? "component" : "components"
50
+ "#{components.length} #{noun}, #{tokens.length} #{tokens.length == 1 ? "token" : "tokens"}."
51
+ end
52
+
53
+ def index
54
+ components.map { |c| "- [`#{c["name"]}`](##{anchor(c["name"])}) — #{first_line(c["description"]) || KIND_LABELS[c["kind"]]}" }
55
+ .join("\n")
56
+ end
57
+
58
+ def component_section(component)
59
+ parts = ["## #{component["name"]}"]
60
+ source = ["`#{component["file"]}`", component["template"] && "`#{component["template"]}`", KIND_LABELS[component["kind"]]]
61
+ parts << source.compact.join(" · ")
62
+ parts << component["description"] if component["description"]
63
+ parts << params_section(component["params"]) unless component["params"].empty?
64
+ parts << slots_section(component["slots"]) unless component["slots"].empty?
65
+ parts << previews_section(component["previews"]) unless component["previews"].empty?
66
+ parts << example_section(component["example"])
67
+ parts.join("\n\n")
68
+ end
69
+
70
+ def params_section(params)
71
+ lines = params.map do |param|
72
+ text = "- `#{param_signature(param)}`"
73
+ text += param["required"] ? " (required)" : ""
74
+ text += " [#{param["type"]}]" if param["type"]
75
+ text += " — #{param["description"]}" if param["description"]
76
+ text
77
+ end
78
+ "**Params**\n\n#{lines.join("\n")}"
79
+ end
80
+
81
+ def param_signature(param)
82
+ name = param["name"]
83
+ case param["kind"]
84
+ when "keyword" then param["default"] ? "#{name}: #{param["default"]}" : "#{name}:"
85
+ when "rest" then "*#{name}"
86
+ when "keyrest" then "**#{name}"
87
+ when "block" then "&#{name}"
88
+ else param["default"] ? "#{name} = #{param["default"]}" : name
89
+ end
90
+ end
91
+
92
+ def slots_section(slots)
93
+ lines = slots.map do |slot|
94
+ text = "- `#{slot["name"]}` (#{slot["kind"]})"
95
+ text += " → `#{slot["type"]}`" if slot["type"] && !%w[lambda polymorphic].include?(slot["type"])
96
+ text += " — one of #{slot["types"].map { |t| "`#{t}`" }.join(", ")}" if slot["types"]&.any?
97
+ text += " — takes #{slot["params"].map { |p| "`#{param_signature(p)}`" }.join(", ")}" if slot["params"].any?
98
+ text
99
+ end
100
+ heading = slots.any? { |slot| slot["heuristic"] } ? "**Slots** (methods that take a block)" : "**Slots**"
101
+ "#{heading}\n\n#{lines.join("\n")}"
102
+ end
103
+
104
+ def previews_section(previews)
105
+ names = previews.reject { |p| p["hidden"] }.map { |p| p["label"] ? "#{p["name"]} (#{p["label"]})" : p["name"] }
106
+ return "**Previews**: none visible" if names.empty?
107
+
108
+ "**Previews**: #{names.join(", ")}"
109
+ end
110
+
111
+ def example_section(example)
112
+ return "**Example**: no usage found in previews or views." unless example
113
+
114
+ "**Example** (from `#{example["file"]}:#{example["line"]}`)\n\n```#{example["language"]}\n#{example["source"]}\n```"
115
+ end
116
+
117
+ def tokens_section
118
+ rows = tokens.map do |token|
119
+ where = token["line"] ? "#{token["file"]}:#{token["line"]}" : token["file"]
120
+ "| `#{token["name"]}` | `#{token["value"].gsub("|", "\\|")}` | #{token["category"]} | #{where} |"
121
+ end
122
+ "## Tokens\n\n| Token | Value | Category | Defined in |\n|---|---|---|---|\n#{rows.join("\n")}"
123
+ end
124
+
125
+ def first_line(text)
126
+ text&.lines&.first&.strip
127
+ end
128
+
129
+ # GitHub's heading anchors: lowercase, punctuation dropped.
130
+ def anchor(name)
131
+ name.downcase.gsub(/[^a-z0-9 _-]/, "").tr(" ", "-")
132
+ end
133
+ end
134
+ end
135
+ end
@@ -0,0 +1,113 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "pathname"
4
+ require "yaml"
5
+
6
+ module Guardrails
7
+ module FeedRamp
8
+ # The `feed_ramp:` section of guardrails.yml. Every key is optional:
9
+ #
10
+ # guardrails:
11
+ # feed_ramp:
12
+ # component_paths: [app/components, app/views/components]
13
+ # preview_paths: [test/components/previews, spec/components/previews]
14
+ # token_files: [app/assets/stylesheets/tokens/_spacing.css]
15
+ # output_dir: .ui_guardrails
16
+ # rules_targets: [claude, agents, cursor]
17
+ # modern_web_guidance: true # mention the Modern Web Guidance skill in the agent rules;
18
+ # # unset, they do when the skill is in the project
19
+ # component_match:
20
+ # severity: warning # or suggestion (reports, never fails), error, off
21
+ # min_classes: 3 # a component's root needs this many static classes to be matched
22
+ # coverage: 0.8 # share of those classes hand-written markup must carry
23
+ #
24
+ # Preview directories the app adds in config/application.rb or
25
+ # config/environments (`config.view_component.previews.paths << …`,
26
+ # `config.lookbook.preview_paths`) are found too, when they're written
27
+ # as literals; list any others here.
28
+ class Config
29
+ DEFAULT_COMPONENT_PATHS = %w[app/components app/views/components].freeze
30
+ DEFAULT_PREVIEW_PATHS = %w[test/components/previews spec/components/previews lookbook/previews].freeze
31
+ DEFAULT_OUTPUT_DIR = ".ui_guardrails"
32
+ DEFAULT_RULES_TARGETS = %w[claude agents cursor].freeze
33
+ MANIFEST_FILENAME = "manifest.json"
34
+ MARKDOWN_FILENAME = "COMPONENTS.md"
35
+
36
+ # How `component_match` in the audit flags hand-written markup that
37
+ # copies a component's root element. `severity` is nil when off.
38
+ ComponentMatch = Struct.new(:severity, :min_classes, :coverage, keyword_init: true)
39
+ SEVERITIES = { "error" => :error, "warning" => :warning, "suggestion" => :suggestion, "off" => nil }.freeze
40
+ DEFAULT_COMPONENT_MATCH = { "severity" => "warning", "min_classes" => 3, "coverage" => 0.8 }.freeze
41
+
42
+ attr_reader :component_paths, :preview_paths, :token_files, :output_dir, :rules_targets, :component_match,
43
+ :modern_web_guidance
44
+
45
+ def self.load(root)
46
+ path = Pathname(root).join("guardrails.yml")
47
+ section = path.file? ? (YAML.safe_load_file(path) || {}).dig("guardrails", "feed_ramp") : nil
48
+ keys = %i[component_paths preview_paths token_files output_dir rules_targets component_match
49
+ modern_web_guidance]
50
+ new(**(section || {}).transform_keys(&:to_sym).slice(*keys))
51
+ rescue Psych::Exception
52
+ new
53
+ end
54
+
55
+ def initialize(component_paths: DEFAULT_COMPONENT_PATHS, preview_paths: DEFAULT_PREVIEW_PATHS,
56
+ token_files: [], output_dir: DEFAULT_OUTPUT_DIR, rules_targets: DEFAULT_RULES_TARGETS,
57
+ component_match: {}, modern_web_guidance: nil)
58
+ @component_paths = Array(component_paths).map(&:to_s)
59
+ @preview_paths = Array(preview_paths).map(&:to_s)
60
+ @token_files = Array(token_files).map(&:to_s)
61
+ @output_dir = output_dir.to_s
62
+ @rules_targets = Array(rules_targets).map(&:to_s)
63
+ @component_match = parse_component_match(component_match)
64
+ @modern_web_guidance = parse_modern_web_guidance(modern_web_guidance)
65
+ end
66
+
67
+ # `preview_paths` plus the ones the app's Rails config adds. Read on
68
+ # demand, so loading the config stays cheap for the hooks.
69
+ def all_preview_paths(root)
70
+ require_relative "rails_config"
71
+ (@preview_paths + RailsConfig.preview_paths(root)).uniq
72
+ end
73
+
74
+ def manifest_path(root)
75
+ Pathname(root).join(@output_dir, MANIFEST_FILENAME)
76
+ end
77
+
78
+ def markdown_path(root)
79
+ Pathname(root).join(@output_dir, MARKDOWN_FILENAME)
80
+ end
81
+
82
+ private
83
+
84
+ # true, false, or nil to go by whether the skill is in the project.
85
+ def parse_modern_web_guidance(value)
86
+ return value if [true, false, nil].include?(value)
87
+
88
+ raise ArgumentError, "feed_ramp.modern_web_guidance #{value.inspect} in guardrails.yml isn't true or false"
89
+ end
90
+
91
+ # `component_match: suggestion` is short for setting the severity.
92
+ # A typo raises rather than quietly changing what fails the audit.
93
+ def parse_component_match(value)
94
+ value = { "severity" => value } unless value.is_a?(Hash)
95
+ settings = DEFAULT_COMPONENT_MATCH.merge(value.transform_keys(&:to_s).compact)
96
+ severity = settings["severity"] == false ? "off" : settings["severity"].to_s.strip.downcase # YAML reads `off` as false
97
+ unless SEVERITIES.key?(severity)
98
+ raise ArgumentError, "feed_ramp.component_match severity #{settings["severity"].inspect} in guardrails.yml " \
99
+ "isn't one of #{SEVERITIES.keys.join(", ")}"
100
+ end
101
+
102
+ ComponentMatch.new(severity: SEVERITIES[severity], **numbers(settings))
103
+ end
104
+
105
+ def numbers(settings)
106
+ { min_classes: Integer(settings["min_classes"]), coverage: Float(settings["coverage"]) }
107
+ rescue TypeError, ArgumentError
108
+ raise ArgumentError, "feed_ramp.component_match in guardrails.yml needs a whole-number min_classes " \
109
+ "and a coverage between 0 and 1"
110
+ end
111
+ end
112
+ end
113
+ end
@@ -0,0 +1,112 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "pathname"
4
+ require "stringio"
5
+ require_relative "../tokens"
6
+
7
+ module Guardrails
8
+ module FeedRamp
9
+ # The design tokens agents should reach for. Starts from what
10
+ # `ui_guardrails:tokens` reads (the configured colour and type-scale
11
+ # files, a Tailwind v3 config), then adds custom properties from
12
+ # `feed_ramp.token_files` and from the `:root { }` and Tailwind v4
13
+ # `@theme { }` blocks in the app's stylesheets, so spacing and radius
14
+ # tokens are found too. The extra sources are Feed Ramp's own:
15
+ # `ui_guardrails:tokens` and the audit read what they always did.
16
+ class DesignTokens
17
+ BLOCK_START = /(?:@theme\b[^{;]*|:root\b[^{,;]*)\{/
18
+
19
+ CATEGORIES = [
20
+ [/\A(?:colou?r|bg|background|border-colou?r|fill|stroke)\b|-colou?r\b/, "color"],
21
+ [/\A(?:spacing|space|gap|inset|size|container)\b/, "spacing"],
22
+ [/\A(?:text|font|leading|tracking|line-height|letter-spacing|type)\b/, "typography"],
23
+ [/\A(?:radius|rounded|border-radius)\b/, "radius"],
24
+ [/\A(?:shadow|drop-shadow|elevation)\b/, "shadow"],
25
+ [/\A(?:breakpoint|screen)\b/, "breakpoint"],
26
+ [/\A(?:ease|animate|duration|transition)\b/, "motion"]
27
+ ].freeze
28
+
29
+ COLOR_VALUE = /\A(?:#\h{3,8}\b|(?:rgb|hsl|oklch|oklab|lab|lch|color)a?\()/i
30
+
31
+ def initialize(root:, config:)
32
+ @root = Pathname(root)
33
+ @config = config
34
+ @tokens = Tokens.new(root: @root, output: StringIO.new)
35
+ end
36
+
37
+ # One entry per token name, the first definition found winning (a
38
+ # dark-mode `:root` override doesn't replace the default value).
39
+ def to_a
40
+ found = @tokens.parse_tokens.map { |t| entry(t.name, t.value, t.syntax, t.file.to_s, t.line) }
41
+ found += token_files.flat_map { |file| custom_properties(file, whole_file: true) }
42
+ found += stylesheets.flat_map { |file| custom_properties(file, whole_file: false) }
43
+ found.uniq { |t| t["name"] }.sort_by { |t| t["name"] }
44
+ end
45
+
46
+ private
47
+
48
+ def token_files
49
+ @config.token_files.select { |file| @root.join(file).file? }
50
+ end
51
+
52
+ def stylesheets
53
+ Tokens::STYLESHEET_PATTERNS.flat_map { |pattern| Dir.glob(@root.join(pattern)) }.uniq.sort
54
+ .map { |path| relative(Pathname(path)) }
55
+ .reject { |file| (Tokens::IMPLICIT_IGNORE_SEGMENTS & file.split("/")).any? }
56
+ end
57
+
58
+ def custom_properties(file, whole_file:)
59
+ text = @tokens.strip_comments(File.read(@root.join(file), encoding: Encoding::UTF_8))
60
+ ranges = whole_file ? [0...text.length] : blocks(text)
61
+ ranges.flat_map do |range|
62
+ found = []
63
+ text[range].to_enum(:scan, Tokens::CSS_VAR_PATTERN).each do
64
+ match = Regexp.last_match
65
+ line = text[0, range.begin + match.begin(0)].count("\n") + 1
66
+ found << entry(match[1], match[2].strip, :css_var, file, line)
67
+ end
68
+ found
69
+ end
70
+ end
71
+
72
+ # Character ranges of each `:root { }` / `@theme { }` body.
73
+ def blocks(text)
74
+ ranges = []
75
+ offset = 0
76
+ while (match = BLOCK_START.match(text, offset))
77
+ depth = 1
78
+ i = match.end(0)
79
+ while i < text.length && depth.positive?
80
+ depth += 1 if text[i] == "{"
81
+ depth -= 1 if text[i] == "}"
82
+ i += 1
83
+ end
84
+ ranges << (match.end(0)...(i - 1))
85
+ offset = i
86
+ end
87
+ ranges
88
+ end
89
+
90
+ def entry(name, value, syntax, file, line)
91
+ written = case syntax.to_sym
92
+ when :css_var then "--#{name}"
93
+ when :scss_var then "$#{name}"
94
+ else name
95
+ end
96
+ { "name" => written, "value" => value, "syntax" => syntax.to_s, "category" => category(name, value, syntax),
97
+ "file" => file, "line" => line.zero? ? nil : line }
98
+ end
99
+
100
+ def category(name, value, syntax)
101
+ return "color" if syntax.to_sym == :tailwind # v3 configs are parsed for colours only
102
+
103
+ CATEGORIES.each { |pattern, category| return category if name.match?(pattern) }
104
+ value.match?(COLOR_VALUE) ? "color" : "other"
105
+ end
106
+
107
+ def relative(path)
108
+ path.relative_path_from(@root).to_s
109
+ end
110
+ end
111
+ end
112
+ end