judgelint 0.1.9 → 0.2.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.
@@ -1,240 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- module Judgelint
4
- # Finds rules where a team already writes its conventions: a
5
- # CONVENTIONS.md or *.judgelint.md, or a README whose frontmatter says which
6
- # files it governs, with one convention per top-level bullet.
7
- #
8
- # A CONVENTIONS.md or *.judgelint.md needs no frontmatter. Without paths:,
9
- # it governs the files under its own directory, except Markdown and
10
- # lockfiles. A README is a spec only when it has paths:.
11
- #
12
- # ---
13
- # paths: ["src/services/*.ts"]
14
- # excludes: ["src/services/legacy-import.ts"]
15
- # ---
16
- # # Service conventions
17
- #
18
- # - **Domain failures are values, never exceptions.** A service returns
19
- # { ok: false, error } for anything a caller could plausibly cause.
20
- # - **No I/O except through the injected Store.** No timers, no fetch.
21
- #
22
- # Each bullet becomes a rule, with an id from its lead words, such as
23
- # src/services/domain-failures-are-values-never-exceptions. The model sees
24
- # the spec's prose alongside the file, and is asked whether the code breaks
25
- # the bullet and whether it follows it. Indented `violation:` and
26
- # `compliant:` lines under a bullet say what each looks like:
27
- #
28
- # - **No I/O except through the injected Store.**
29
- # violation: calls fetch, console, or a timer directly
30
- # compliant: reads and writes only through the Store it's given
31
- #
32
- # Files in .judgelint/rules/ work the same way, and one there with a
33
- # question: in its frontmatter is a single rule asked exactly that way.
34
- module Spec
35
- PATTERNS = ["**/README.md", "**/CONVENTIONS.md", "**/*.judgelint.md"].freeze
36
- # What a spec without paths: leaves out of its directory.
37
- UNJUDGED = ["**/*.md", "**/*.lock", "**/package-lock.json", "**/pnpm-lock.yaml"].freeze
38
- KEYS = %w[paths excludes context scope cohort type severity threshold].freeze
39
- COHORTS = { "by_file" => "file", "by_directory" => "directory" }.freeze
40
- BULLET = /\A(?:[-*+]|\d+[.)])\s+(\S.*)\z/
41
- CRITERION = /\A(violation|compliant):\s*(\S.*)\z/i
42
- LABEL = /\A[*_]*(bad|good)[*_]*:?[*_]*\z/i
43
- LEAD = /\A\*\*(.+?)\*\*/
44
-
45
- # +readmes+ false looks in +rules_dir+ alone.
46
- def self.discover(rules_dir:, default_threshold:, ignore: [], readmes: true)
47
- # path.dup: Spinel can't yet share these Strings into the rules it builds.
48
- found = Dir.glob(File.join(rules_dir, "*.md")).sort.flat_map do |path|
49
- load(path.dup, default_threshold: default_threshold, required: true)
50
- end
51
- specs = readmes ? Glob.files(PATTERNS) : []
52
- specs = specs.reject { |path| path.start_with?("#{rules_dir}/") || Glob.match_any?(ignore, path) }
53
- found += specs.flat_map { |path| load(path.dup, default_threshold: default_threshold, required: false) }
54
- raise ConfigError, "No rules: write your conventions as bullets in CONVENTIONS.md, or run `judgelint init`" if found.empty?
55
-
56
- found.group_by(&:question_key).each_value do |same|
57
- raise ConfigError, "Rule ids collide: #{same.map(&:id).join(', ')}" if same.size > 1
58
- end
59
- found
60
- end
61
-
62
- # A README without frontmatter, or without paths:, isn't a spec.
63
- def self.load(path, default_threshold:, required:)
64
- content = File.read(path)
65
- match = Rule::FRONTMATTER.match(content)
66
- own = !required && File.basename(path) != "README.md"
67
- raise ConfigError, "#{path}: rules start with a --- frontmatter block" if match.nil? && required
68
- return [] if match.nil? && !own
69
-
70
- data = match ? Judgelint.parse_yaml(match[1], path) : {}
71
- body = match ? match[2] : content
72
- return [Rule.new(data, source: path, body: body.strip, default_threshold: default_threshold)] if data.key?("question")
73
- return [] unless required || own || data.key?("paths")
74
-
75
- unknown = data.keys - KEYS
76
- raise ConfigError, "#{path}: unknown keys #{unknown.join(', ')}" unless unknown.empty?
77
-
78
- shared = shared_settings(path, data)
79
- unless shared.key?("paths") || required
80
- dir = File.dirname(path)
81
- shared["paths"] = [dir == "." ? "**/*" : "#{dir}/**/*"]
82
- excludes = shared["excludes"] || []
83
- shared["excludes"] = (excludes.is_a?(Array) ? excludes : [excludes]) + UNJUDGED
84
- end
85
- found = bullets(body, content[0, content.size - body.size].count("\n"))
86
- raise ConfigError, "#{path}: a rule needs a question, or bullets to turn into rules" if found.empty? && required
87
-
88
- prose = body.strip
89
- ids = []
90
- found.map do |text, criteria, examples|
91
- id = unique("#{name(path)}/#{slug(text)}", ids)
92
- rule = shared.merge("id" => id, "convention" => plain(text), "message" => lead(text))
93
- rule["yes_means"] = plain(criteria["violation"]) if criteria["violation"]
94
- rule["no_means"] = plain(criteria["compliant"]) if criteria["compliant"]
95
- rule["severity"] = severity(text) unless data.key?("severity")
96
- Rule.new(rule, source: path, default_threshold: default_threshold, prose: prose,
97
- examples_dir: File.join(".judgelint", "examples", id), inline_examples: examples)
98
- end
99
- end
100
-
101
- def self.shared_settings(path, data)
102
- settings = {}
103
- %w[paths excludes context severity threshold].each { |key| settings[key] = data[key] if data.key?(key) }
104
- if data.key?("cohort")
105
- cohort = data["cohort"].to_s
106
- raise ConfigError, "#{path}: cohort is by_file or by_directory, not #{cohort}" unless COHORTS.key?(cohort)
107
-
108
- settings["scope"] = COHORTS.fetch(cohort)
109
- end
110
- settings["scope"] = data["scope"] if data.key?("scope")
111
- settings
112
- end
113
-
114
- # The top-level bullets of the body, outside code fences, as [text,
115
- # criteria, examples]: the text with its continuation lines and nested
116
- # bullets, any indented violation: or compliant: lines, and the code blocks
117
- # under a "Bad:" or "Good:" line. +offset+ is the number of lines before
118
- # the body, so an example's line number is the spec file's.
119
- def self.bullets(body, offset = 0)
120
- found = []
121
- current = nil
122
- criteria = {}
123
- criterion = nil
124
- examples = []
125
- label = nil
126
- fenced = false
127
- indent = 0
128
- code = nil
129
- language = ""
130
- start = 0
131
- number = offset
132
- body.each_line do |raw|
133
- number += 1
134
- line = raw.chomp
135
- if line.lstrip.start_with?("```")
136
- if fenced
137
- examples << InlineExample.new(label, code.join, start, language) if code
138
- code = nil
139
- else
140
- indent = line.size - line.lstrip.size
141
- if current && label && indent.positive?
142
- code = []
143
- start = number + 1
144
- language = line.strip.delete_prefix("```").split(" ").first.to_s
145
- end
146
- end
147
- fenced = !fenced
148
- next
149
- end
150
- if fenced
151
- code << deindent(raw, indent) if code
152
- next
153
- end
154
-
155
- bullet = BULLET.match(line)
156
- if bullet
157
- found << [current, criteria, examples] if current
158
- current = bullet[1]
159
- criteria = {}
160
- criterion = nil
161
- examples = []
162
- label = nil
163
- elsif current && line.start_with?(" ", "\t") && !line.strip.empty?
164
- nested = BULLET.match(line.strip)
165
- text = nested ? nested[1] : line.strip
166
- named = CRITERION.match(text)
167
- labeled = LABEL.match(text)
168
- if named
169
- criterion = named[1].downcase
170
- criteria[criterion] = named[2]
171
- elsif labeled
172
- label = labeled[1].downcase
173
- criterion = nil
174
- elsif label
175
- # Commentary on the examples isn't part of the rule.
176
- elsif criterion
177
- criteria[criterion] = "#{criteria[criterion]} #{text}"
178
- else
179
- current = "#{current} #{text}"
180
- end
181
- elsif current && !line.strip.empty?
182
- found << [current, criteria, examples]
183
- current = nil
184
- end
185
- end
186
- found << [current, criteria, examples] if current
187
- found
188
- end
189
-
190
- # A code block's line without the indentation its fence had.
191
- def self.deindent(raw, indent)
192
- cut = 0
193
- cut += 1 while cut < indent && [" ", "\t"].include?(raw[cut])
194
- raw[cut..].to_s
195
- end
196
-
197
- # The bullet with its markdown emphasis removed: what the model is asked about.
198
- def self.plain(text)
199
- text.gsub("**", "").gsub(/\s+/, " ").strip
200
- end
201
-
202
- # The bold lead, or the first sentence: what judgelint prints for a finding.
203
- def self.lead(text)
204
- bold = LEAD.match(text)
205
- sentence = bold ? bold[1] : plain(text)
206
- sentence = sentence[0, sentence.index(/[.!?:](\s|\z)/) || sentence.size]
207
- "#{sentence.strip.sub(/[.!?:]\z/, '')}."
208
- end
209
-
210
- def self.slug(text)
211
- words = lead(text).downcase.scan(/[a-z0-9]+/).first(6)
212
- words.empty? ? "rule" : words.join("-")
213
- end
214
-
215
- def self.unique(id, taken)
216
- candidate = id
217
- number = 1
218
- while taken.include?(candidate)
219
- number += 1
220
- candidate = "#{id}-#{number}"
221
- end
222
- taken << candidate
223
- candidate
224
- end
225
-
226
- # Spec names: a README's directory, a *.judgelint.md's stem, or a rules file's name.
227
- def self.name(path)
228
- dir = File.dirname(path)
229
- return(dir == "." ? "root" : dir) if %w[README.md CONVENTIONS.md].include?(File.basename(path))
230
-
231
- File.basename(path).delete_suffix(".md").delete_suffix(".judgelint")
232
- end
233
-
234
- # Praxis's reading: "should" and "prefer" are advice, anything else is a rule.
235
- def self.severity(text)
236
- advisory = /\b(should|prefer|ideally|consider)\b/i.match?(text)
237
- advisory && !/\b(must|never|always)\b/i.match?(text) ? "warning" : "error"
238
- end
239
- end
240
- end
@@ -1,53 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- module Judgelint
4
- # Requests and input tokens across a run, and what they cost. Decision
5
- # models bill input only, so input tokens are the cost. Shared by every
6
- # model's client in a run.
7
- class Usage
8
- attr_reader :requests, :input_tokens
9
-
10
- def initialize
11
- @requests = 0
12
- @input_tokens = 0
13
- @cost = 0.0
14
- @unpriced = false
15
- @lock = Mutex.new
16
- end
17
-
18
- # OpenRouter reports each request's cost; for the rest it's tokens x the
19
- # model's price. A request with neither makes the run's cost unknown.
20
- def record(data, price_per_million)
21
- usage = data["usage"].is_a?(Hash) ? data["usage"] : {}
22
- tokens = usage["input_tokens"].to_i
23
- @lock.synchronize do
24
- @requests += 1
25
- @input_tokens += tokens
26
- if usage["cost"].is_a?(Numeric)
27
- @cost += usage["cost"].to_f
28
- elsif price_per_million
29
- @cost += tokens * price_per_million / 1_000_000.0
30
- else
31
- @unpriced = true
32
- end
33
- end
34
- end
35
-
36
- def cost
37
- @unpriced ? nil : @cost
38
- end
39
-
40
- def to_h
41
- { "requests" => requests, "input_tokens" => input_tokens, "cost_usd" => cost&.round(6) }
42
- end
43
-
44
- def line
45
- cost_text = cost ? format("$%.4f", cost) : "cost unknown (no price for a model)"
46
- "judgelint: #{requests} #{requests == 1 ? 'request' : 'requests'}, #{Usage.delimit(input_tokens)} input tokens, #{cost_text}"
47
- end
48
-
49
- def self.delimit(number)
50
- number.to_s.reverse.scan(/\d{1,3}/).join(",").reverse
51
- end
52
- end
53
- end
@@ -1,65 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- module Judgelint
4
- # One rule's outcome for one file.
5
- #
6
- # +status+ is :violation (at or above the rule's threshold), :uncertain
7
- # (between warn_at and the threshold), :pass, :skipped (the file is too
8
- # large to judge), :refused (the model declined the question), or :excused
9
- # (a violation or uncertain, but a judgehint excuses it). Skipped and
10
- # refused files are reported, never silently passed. +lines+ is the [first,
11
- # last] range the verdict came from. +line+ is the line in it that breaks
12
- # the rule, and +file+ the file in a directory, when the model could say.
13
- #
14
- # An example's verdict also knows the answer it should have had: +expected+
15
- # is :pass or :fail for files under rules/<id>/pass and rules/<id>/fail.
16
- # Not Data.define: Spinel can't compile a Data or Struct in a program that also uses net/https and json.
17
- class Verdict
18
- attr_reader :rule, :path, :probability, :status, :lines, :line, :file, :expected
19
-
20
- def initialize(rule:, path:, probability:, status:, lines: nil, line: nil, file: nil, expected: nil)
21
- @rule = rule
22
- @path = path
23
- @probability = probability
24
- @status = status
25
- @lines = lines
26
- @line = line
27
- @file = file
28
- @expected = expected
29
- end
30
-
31
- def as_example(expected)
32
- Verdict.new(rule: rule, path: path, probability: probability, status: status, lines: lines, line: line, file: file,
33
- expected: expected)
34
- end
35
-
36
- # +probability+ is the probability the code breaks the rule.
37
- def self.classify(rule, path, probability, warn_at:, lines: nil, line: nil, file: nil)
38
- status =
39
- if probability >= rule.threshold then :violation
40
- elsif probability >= warn_at then :uncertain
41
- else :pass
42
- end
43
- new(rule: rule, path: path, probability: probability, status: status, lines: lines, line: line, file: file)
44
- end
45
-
46
- def failing?
47
- status == :violation && rule.error?
48
- end
49
-
50
- # A refused or skipped example is a miss either way: the rule didn't work
51
- # on it. An excused one isn't a violation.
52
- def correct?
53
- return false if %i[refused skipped].include?(status)
54
-
55
- (status == :violation) == (expected == :fail)
56
- end
57
-
58
- def to_h
59
- {
60
- "path" => path, "lines" => lines, "line" => line, "file" => file, "rule" => rule.id, "severity" => rule.severity, "status" => status.to_s,
61
- "probability" => probability&.round(3), "message" => rule.message
62
- }.merge(expected ? { "expected" => expected.to_s, "correct" => correct? } : {})
63
- end
64
- end
65
- end
@@ -1,5 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- module Judgelint
4
- VERSION = "0.1.9"
5
- end
data/lib/judgelint.rb DELETED
@@ -1,61 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- require "json"
4
- require "yaml"
5
- require "digest"
6
- require "fileutils"
7
- require "net/https"
8
- require "open3"
9
-
10
- require_relative "judgelint/version"
11
- require_relative "judgelint/errors"
12
- require_relative "judgelint/glob"
13
- require_relative "judgelint/rule"
14
- require_relative "judgelint/spec"
15
- require_relative "judgelint/source"
16
- require_relative "judgelint/question"
17
- require_relative "judgelint/changes"
18
- require_relative "judgelint/providers"
19
- require_relative "judgelint/config"
20
- require_relative "judgelint/cache"
21
- require_relative "judgelint/usage"
22
- require_relative "judgelint/pool"
23
- require_relative "judgelint/verdict"
24
- require_relative "judgelint/protocol"
25
- require_relative "judgelint/client"
26
- require_relative "judgelint/runner"
27
- require_relative "judgelint/paint"
28
- require_relative "judgelint/reporter"
29
- require_relative "judgelint/scaffold"
30
- require_relative "judgelint/cli"
31
-
32
- # Lints files against conventions that only a reader can check. Each rule is a
33
- # yes/no question that a System One decision model answers with a probability.
34
- module Judgelint
35
- NUMBER = /\A-?\d+(?:\.\d+)?(?:[eE][-+]?\d+)?\z/
36
-
37
- # Float(), without the rescue: answers nil for anything that isn't a number.
38
- def self.number(value)
39
- string = value.to_s.strip
40
- NUMBER.match?(string) ? string.to_f : nil
41
- end
42
-
43
- def self.read_yaml(path, required:)
44
- return parse_yaml(File.read(path), path) if File.exist?(path)
45
- raise ConfigError, "No config file at #{path}" if required
46
-
47
- {}
48
- end
49
-
50
- def self.parse_yaml(yaml, path)
51
- data = YAML.safe_load(yaml) || {}
52
- raise ConfigError, "#{path} must be a mapping" unless data.is_a?(Hash)
53
-
54
- data
55
- rescue Psych::AliasesNotEnabled
56
- raise ConfigError, "#{path}: YAML aliases aren't supported"
57
- rescue Psych::Exception => e
58
- # Bad syntax, or a tag naming a class safe_load won't build.
59
- raise ConfigError, "#{path}: #{e.message}"
60
- end
61
- end