agent_primitives 0.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.
@@ -0,0 +1,424 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "optparse"
4
+ require "json"
5
+ require_relative "../agent_primitives"
6
+ require_relative "evals"
7
+ require_relative "guard"
8
+ require_relative "proof_report"
9
+ require_relative "importer"
10
+
11
+ module AgentPrimitives
12
+ # Command line entry point. Returns exit codes rather than calling exit, so the
13
+ # whole thing is testable without forking.
14
+ class CLI
15
+ FORMATS = %w[text json].freeze
16
+
17
+ # The commands that take one positional argument, and the option it fills.
18
+ POSITIONAL = { "proofs" => :scope, "import" => :destination }.freeze
19
+
20
+ USAGE = <<~TEXT
21
+ usage: agent_primitives <command> [options]
22
+
23
+ commands:
24
+ evals check every intent clause in docs/primitives/ is proven by a spec (use in CI)
25
+ guard report what this change did to intent and the specs that prove it
26
+ proofs list the examples proving each intent clause
27
+ import copy this gem's skills into a skills directory
28
+ version print the gem version
29
+
30
+ options:
31
+ --path PATH evals/guard/proofs: project root (default: current directory)
32
+ --format FORMAT evals/guard/proofs: text (default) or json
33
+ --base REF guard: revision to compare against (default: HEAD)
34
+ --since REF proofs: only clauses whose spec files this change touched
35
+ -h, --help print this help
36
+
37
+ examples:
38
+ agent_primitives evals # in CI: exits 1 on unproven intent
39
+ agent_primitives guard --base main # what this branch changed
40
+ agent_primitives proofs 'orders#I3' # one clause, with its proving examples
41
+ agent_primitives proofs --since main # the clauses this branch's specs touch
42
+ agent_primitives import .claude/skills # add the skills beside those already there
43
+
44
+ Import only adds: it writes this gem's skill files into the directory and
45
+ never deletes or replaces anything else in it. Re-run it after a gem bump
46
+ and review the result with git diff.
47
+
48
+ Guard answers the question evals cannot: not "is every clause hooked up to a
49
+ spec" but "did this change quietly reword a promise, delete one, or hollow
50
+ out the example proving it". It parses the tree twice — at --base and in the
51
+ working tree — and reports what got smaller or different. Growth is silent.
52
+
53
+ Every guard finding is a notice and the exit code is 0 whenever the
54
+ comparison ran: each check has a legitimate cause as well as a suspicious
55
+ one, and a check that stops honest work gets routed around. An agent
56
+ reading its own notices should restore proof it dropped by accident; it
57
+ should not write the provenance line that discharges an intent notice —
58
+ that decision is the user's.
59
+
60
+ Proofs answers a third question, and is a lookup rather than a check: which
61
+ examples prove this clause. Evals is satisfied by one tag per file, so a
62
+ clause the plan meant to prove with four denials passes with three tagged —
63
+ the tagged listing is what a verify step compares against the plan's proof
64
+ set, and a planned example missing from it is found in the spec file and
65
+ tagged, or written. Nothing here is an offence and the exit code is always
66
+ 0: most examples in a spec file carry no tag by design, so a tagged count
67
+ is a number to compare with the plan, not a verdict. A tag on a `describe`
68
+ is named as proving nothing rather than shown among the proofs, and the
69
+ footer counts every tag evals will reject. --format json additionally
70
+ carries every untagged example in the files a clause names.
71
+
72
+ Evals reads intent clauses from each capability doc's YAML frontmatter and
73
+ the `intent: "<capability>#I<n>"` metadata on spec examples; the same tag
74
+ runs the proof: rspec --tag 'intent:comment_threads#I2'. Tags belong on the
75
+ example, not the group around it. Every active clause on a built doc must
76
+ name a spec. A doc with status amending has shipped and has an approved
77
+ plan changing it, named by its plan: key: its clauses with no row yet,
78
+ and tags pointing at them, warn instead of failing until close-out.
79
+ TEXT
80
+
81
+ def initialize(argv, out: $stdout, err: $stderr)
82
+ @argv = argv.dup
83
+ @out = out
84
+ @err = err
85
+ @options = { path: Dir.pwd, format: "text", base: Guard::DEFAULT_BASE }
86
+ end
87
+
88
+ def run
89
+ command = parse!
90
+ return usage(1) if command.nil?
91
+
92
+ case command
93
+ when "evals" then evals
94
+ when "guard" then guard
95
+ when "proofs" then proofs
96
+ when "import" then import
97
+ when "version" then say(VERSION)
98
+ when "help" then usage(0)
99
+ else
100
+ @err.puts "unknown command: #{command}"
101
+ usage(1)
102
+ end
103
+ rescue Error, OptionParser::ParseError => e
104
+ @err.puts "error: #{e.message}"
105
+ 1
106
+ end
107
+
108
+ private
109
+
110
+ def say(text)
111
+ @out.puts(text)
112
+ 0
113
+ end
114
+
115
+ # OptionParser#parse works on a dup of the array, so the -h callback sets a
116
+ # flag rather than mutating @argv, which the parser would never see.
117
+ def parse!
118
+ help = false
119
+ parser = OptionParser.new do |o|
120
+ o.on("--path PATH") { |v| @options[:path] = v }
121
+ o.on("--format FORMAT") { |v| @options[:format] = v }
122
+ o.on("--base REF") { |v| @options[:base] = v }
123
+ o.on("--since REF") { |v| @options[:since] = v }
124
+ o.on("-h", "--help") { help = true }
125
+ end
126
+ rest = parser.parse(@argv)
127
+ return "help" if help
128
+
129
+ command, *positional = rest
130
+ key = POSITIONAL[command]
131
+ @options[key] = positional.shift if key
132
+ raise Error, "unexpected argument: #{positional.first}" if positional.any?
133
+
134
+ command
135
+ end
136
+
137
+ def evals
138
+ validate_format!
139
+ result = Evals.run(root: File.expand_path(@options[:path]))
140
+ @options[:format] == "json" ? evals_json(result) : evals_text(result)
141
+ result.ok? ? 0 : 1
142
+ end
143
+
144
+ def validate_format!
145
+ return if FORMATS.include?(@options[:format])
146
+
147
+ raise Error, "format must be text or json, not #{@options[:format].inspect}"
148
+ end
149
+
150
+ # Always 0 when the comparison ran. Guard reports; it does not judge, and a
151
+ # non-zero exit here would turn every notice into a gate.
152
+ def guard
153
+ validate_format!
154
+ result = Guard.run(root: File.expand_path(@options[:path]), base: @options[:base])
155
+ @options[:format] == "json" ? guard_json(result) : guard_text(result)
156
+ 0
157
+ end
158
+
159
+ def guard_text(result)
160
+ findings_text(result.findings)
161
+ @out.puts "compared against #{short(result.base)}: #{guard_summary(result)}"
162
+ end
163
+
164
+ # Findings grouped under one path header per file, so a burst of notices in
165
+ # one file reads as a block rather than a wall of repeated paths.
166
+ def findings_text(findings)
167
+ findings.group_by(&:path).each do |path, group|
168
+ @out.puts path
169
+ width = group.map { |finding| position(finding).length }.max
170
+ group.each { |finding| finding_text(finding, width) }
171
+ @out.puts
172
+ end
173
+ end
174
+
175
+ def position(finding) = "#{finding.line}:#{finding.column}"
176
+
177
+ def finding_text(finding, width)
178
+ @out.puts " #{position(finding).ljust(width)} #{paint(finding.letter, severity_colour(finding))} " \
179
+ "#{finding.message} [#{finding.code}]"
180
+ (finding.details || []).each { |detail| detail_text(detail, width) }
181
+ end
182
+
183
+ # Indented to sit under the severity letter. Labelled lines are clause text
184
+ # and get clipped; `--format json` carries them whole.
185
+ def detail_text(detail, width)
186
+ indent = " " * (width + 5)
187
+ body = detail.label ? "#{detail.label}: #{clip(detail.text)}" : detail.text
188
+ @out.puts " #{indent}#{body}"
189
+ end
190
+
191
+ def clip(text, limit: 100)
192
+ text.length > limit ? "#{text[0, limit - 1]}…" : text
193
+ end
194
+
195
+ def guard_summary(result)
196
+ return "no change to intent or the specs that prove it" if result.clean?
197
+
198
+ "#{pluralize(result.findings.size, 'notice')} for review — none of this fails the run"
199
+ end
200
+
201
+ def guard_json(result)
202
+ @out.puts JSON.pretty_generate(
203
+ base: result.base, capabilities: result.capabilities,
204
+ notices: result.findings.size, findings: result.findings.map(&:to_h)
205
+ )
206
+ end
207
+
208
+ def short(ref) = ref[0, 12]
209
+
210
+ # Always 0. Proofs reports what proves what; the verdict on whether that is
211
+ # enough belongs to `evals` and to review.
212
+ def proofs
213
+ validate_format!
214
+ result = ProofReport.run(root: File.expand_path(@options[:path]), scope: @options[:scope],
215
+ since: @options[:since])
216
+ @options[:format] == "json" ? proofs_json(result) : proofs_text(result)
217
+ 0
218
+ end
219
+
220
+ def proofs_text(result)
221
+ return @out.puts(nothing_to_report(result)) if result.empty?
222
+
223
+ result.detail == :summary ? proofs_summary(result) : proofs_detail(result)
224
+ @out.puts
225
+ proofs_misplaced(result)
226
+ proofs_footer(result)
227
+ end
228
+
229
+ def nothing_to_report(result)
230
+ return "no spec file proving an intent clause changed since #{short(result.base)}" if result.base
231
+
232
+ "no intent clauses found — `agent_primitives evals` explains what a capability doc needs"
233
+ end
234
+
235
+ # One line per clause under its capability: the health-pass density, which
236
+ # stays scannable at two hundred clauses. Whether a count is the *right*
237
+ # count is a question for the plan, so drilling in is a second command
238
+ # rather than more output here.
239
+ def proofs_summary(result)
240
+ each_capability(result) do |rows|
241
+ width = rows.map { |row| clause_line(row).length }.max
242
+ rows.each { |row| @out.puts "#{clause_line(row).ljust(width)} #{clause_summary(row)}" }
243
+ end
244
+ end
245
+
246
+ def each_capability(result)
247
+ result.rows.group_by(&:capability).each_with_index do |(capability, rows), index|
248
+ @out.puts if index.positive?
249
+ @out.puts "#{capability} (#{rows.first.status || 'no status'})"
250
+ yield rows
251
+ end
252
+ end
253
+
254
+ def clause_line(row) = " #{row.clause.id} #{row.clause.text}"
255
+
256
+ def clause_summary(row)
257
+ return inactive_summary(row) if row.state
258
+ return "no evaluations" if row.files.empty?
259
+
260
+ count = pluralize(row.tagged, "tagged example")
261
+ row.tagged.zero? ? paint(count, 31) : count
262
+ end
263
+
264
+ # A tag on a superseded or retired clause is still a real example, and one
265
+ # `evals` calls an offence — so the count is shown rather than swallowed by
266
+ # the state, and the footer's total reconciles with the rows above it.
267
+ def inactive_summary(row)
268
+ return row.state if row.tagged.zero?
269
+
270
+ "#{row.state} — #{pluralize(row.tagged, 'example')} still tagged"
271
+ end
272
+
273
+ def proofs_detail(result)
274
+ each_capability(result) do |rows|
275
+ rows.each { |row| proofs_clause(row) }
276
+ end
277
+ end
278
+
279
+ def proofs_clause(row)
280
+ state = row.state ? " [#{row.state}]" : ""
281
+ @out.puts
282
+ @out.puts " #{paint(row.clause.id, 1)} #{row.clause.text}#{state}"
283
+ return @out.puts " no evaluations" if row.files.empty?
284
+
285
+ row.files.each { |file| proofs_file(file) }
286
+ end
287
+
288
+ def proofs_file(file)
289
+ return @out.puts " #{file.path} (file not found)" unless file.exists
290
+
291
+ undeclared = file.declared ? "" : " (not in this clause's `evaluations:`)"
292
+ count = pluralize(file.tagged.size, "tagged example")
293
+ @out.puts " #{file.path} — #{file.tagged.empty? ? paint(count, 31) : count}#{undeclared}"
294
+ proofs_examples(file.tagged)
295
+ end
296
+
297
+ def proofs_examples(tagged)
298
+ return if tagged.empty?
299
+
300
+ openers = tagged.map { |proof| ":#{proof.opener}" }
301
+ described = tagged.map { |proof| description(proof.description) }
302
+ opener_width = openers.map(&:length).max
303
+ description_width = described.map(&:length).max
304
+
305
+ tagged.each_with_index do |proof, index|
306
+ @out.puts " #{openers[index].ljust(opener_width)} #{described[index].ljust(description_width)}" \
307
+ " #{pluralize(proof.assertions, 'assertion')}"
308
+ end
309
+ end
310
+
311
+ # A tag on a group has no example under it, so it never appears among the
312
+ # proofs — it is named for what it is instead, with its address. Deduplicated
313
+ # because one file can prove several of the listed clauses.
314
+ def proofs_misplaced(result)
315
+ tags = result.rows.flat_map do |row|
316
+ row.files.flat_map { |file| file.misplaced.map { |proof| [ file.path, proof.line, proof.group ] } }
317
+ end.uniq
318
+ return if tags.empty?
319
+
320
+ tags.each do |path, line, group|
321
+ @out.puts "tag proving nothing: #{path}:#{line} sits on `#{group}` — no example under it"
322
+ end
323
+ @out.puts
324
+ end
325
+
326
+ def description(text) = text.to_s.strip.empty? ? "(no description)" : text
327
+
328
+ def proofs_footer(result)
329
+ parts = [ pluralize(result.rows.size, "clause"), pluralize(result.tagged, "tagged example") ]
330
+ parts << "in files changed since #{short(result.base)}" if result.base
331
+ @out.puts parts.join(", ")
332
+ @out.puts unusable_summary(result.unusable) unless result.unusable.values.sum.zero?
333
+ end
334
+
335
+ # Every kind gets a line's worth of mention, so the report never looks like
336
+ # the whole picture when some of the suite's tags are not proof at all.
337
+ UNUSABLE = { unresolved: "naming no active clause", misplaced: "on a group rather than an example",
338
+ malformed: "not in `<capability>#I<n>` form" }.freeze
339
+
340
+ def unusable_summary(unusable)
341
+ total = unusable.values.sum
342
+ named = UNUSABLE.filter_map { |kind, phrase| [ unusable[kind], phrase ] unless unusable[kind].zero? }
343
+ count = "#{pluralize(total, 'tag')} in the suite #{total == 1 ? 'is' : 'are'}"
344
+ tail = "`agent_primitives evals` reports #{total == 1 ? 'it' : 'each'}"
345
+ return "#{count} #{named.first.last} — #{tail}" if named.one?
346
+
347
+ "#{count} not usable proof — #{named.map { |n, phrase| "#{n} #{phrase}" }.join(', ')}; #{tail}"
348
+ end
349
+
350
+ def proofs_json(result)
351
+ @out.puts JSON.pretty_generate(
352
+ scope: result.scope, base: result.base, detail: result.detail,
353
+ capabilities: result.capabilities, clauses: result.rows.size,
354
+ tagged_examples: result.tagged, unresolved_tags: result.unusable[:unresolved],
355
+ misplaced_tags: result.unusable[:misplaced], malformed_tags: result.unusable[:malformed],
356
+ proofs: result.rows.map(&:to_h)
357
+ )
358
+ end
359
+
360
+ def import
361
+ raise Error, "import needs a directory: agent_primitives import <dir>" if @options[:destination].nil?
362
+
363
+ result = Importer.new(destination: File.expand_path(@options[:destination])).run
364
+ return say("skills in #{@options[:destination]} are already current") if result.written.empty?
365
+
366
+ list("new", result.created)
367
+ list("updated", result.updated)
368
+ 0
369
+ end
370
+
371
+ def list(label, files)
372
+ return if files.empty?
373
+
374
+ @out.puts "#{label}:"
375
+ files.each { |file| @out.puts " #{file}" }
376
+ end
377
+
378
+ def evals_text(result)
379
+ findings_text(result.findings)
380
+ @out.puts evals_summary(result)
381
+ end
382
+
383
+ def evals_summary(result)
384
+ warnings = result.findings.size - result.errors.size
385
+ counted = [ pluralize(result.capabilities, "capability", "capabilities"),
386
+ pluralize(result.clauses, "clause") ]
387
+ tail = result.findings.empty? ? "no offences" : pluralize(result.errors.size, "offence")
388
+ tail += ", #{pluralize(warnings, 'warning')}" if warnings.positive?
389
+ "#{counted.join(', ')} — #{tail}"
390
+ end
391
+
392
+ def evals_json(result)
393
+ @out.puts JSON.pretty_generate(
394
+ capabilities: result.capabilities, clauses: result.clauses,
395
+ errors: result.errors.size, findings: result.findings.map(&:to_h)
396
+ )
397
+ end
398
+
399
+ def pluralize(count, singular, plural = "#{singular}s")
400
+ "#{count} #{count == 1 ? singular : plural}"
401
+ end
402
+
403
+ SEVERITY_COLOURS = { "E" => 31, "W" => 33, "N" => 33 }.freeze
404
+
405
+ def severity_colour(finding) = SEVERITY_COLOURS[finding.letter]
406
+
407
+ # Colour only when a person is watching: a TTY without NO_COLOR set. Piped
408
+ # output — CI logs, agents, redirects — gets exactly the plain text.
409
+ def paint(text, code)
410
+ colour? && code ? "\e[#{code}m#{text}\e[0m" : text
411
+ end
412
+
413
+ def colour?
414
+ return @colour if defined?(@colour)
415
+
416
+ @colour = @out.respond_to?(:tty?) && @out.tty? && ENV["NO_COLOR"].to_s.empty?
417
+ end
418
+
419
+ def usage(code)
420
+ (code.zero? ? @out : @err).puts USAGE
421
+ code
422
+ end
423
+ end
424
+ end
@@ -0,0 +1,222 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "yaml"
4
+ require "date"
5
+
6
+ module AgentPrimitives
7
+ module Evals
8
+ # One parsed capability doc from docs/primitives/capabilities/.
9
+ #
10
+ # Intent clauses and their evaluations live in YAML frontmatter, not in prose
11
+ # sections, so this is a parse rather than a guess:
12
+ #
13
+ # ---
14
+ # status: built
15
+ # intent:
16
+ # - id: I1
17
+ # clause: A reader can reply to any comment.
18
+ # evaluations:
19
+ # - spec/system/comment_threads_spec.rb
20
+ # - id: I4
21
+ # clause: Threads never nest deeper than 3 levels.
22
+ # superseded_by: [ I5, I6 ]
23
+ # superseded_on: 2026-09-18
24
+ # ---
25
+ #
26
+ # The key is `superseded_on`, not `on`: YAML 1.1 resolves a bare `on` to the
27
+ # boolean `true`, so an `on:` key would parse as `true` and the date would be
28
+ # unreachable. Psych does this silently — hence the longer name.
29
+ #
30
+ # Structural problems are returned as findings rather than raised, because a
31
+ # single malformed doc must not stop the rest of the tree being checked.
32
+ class Capability
33
+ STATUSES = %w[shaping planned built amending deprecated].freeze
34
+ CLAUSE_ID = /\AI[1-9]\d*\z/
35
+ FRONTMATTER = /\A---\r?\n(.*?)\r?\n---(?:\r?\n|\z)/m
36
+
37
+ # Retired prose sections. A doc still carrying them either predates the
38
+ # frontmatter format or was half-migrated; either way its clauses are not
39
+ # where this tool looks, so it must fail loudly instead of reporting zero
40
+ # clauses and passing.
41
+ LEGACY_HEADING = /^##\s+(Intent|Evaluations)\s*$/
42
+ LEGACY_SPECS_KEY = /^specs:/
43
+
44
+ # One intent clause. `line` is where its `id:` sits in the source file, so
45
+ # an offence points at the clause rather than at the top of the document.
46
+ Clause = Struct.new(:id, :text, :evaluations, :superseded_by, :retired_on, :line,
47
+ keyword_init: true) do
48
+ def active? = superseded_by.empty? && retired_on.nil?
49
+ end
50
+
51
+ attr_reader :path, :relative_path, :name, :status, :plan, :clauses, :findings
52
+
53
+ def self.load_all(dir, root:)
54
+ Dir.glob(File.join(dir, "*.md")).sort.map { |path| new(path, root: root) }
55
+ end
56
+
57
+ def initialize(path, root:)
58
+ @path = path
59
+ @root = root
60
+ @relative_path = path.delete_prefix("#{root}/")
61
+ @name = File.basename(path, ".md")
62
+ @clauses = []
63
+ @findings = []
64
+ @source = File.read(path, encoding: "UTF-8")
65
+
66
+ parse
67
+ end
68
+
69
+ def built? = status == "built"
70
+
71
+ # Shipped, and an approved plan is changing it. Set at plan approval and
72
+ # cleared at close-out, never inferred: nothing in this tool reads
73
+ # provenance, which is prose and append-only.
74
+ def amending? = status == "amending"
75
+
76
+ # An approved plan is running against this doc. Rows are filed at
77
+ # close-out, so its clauses can legitimately have none yet.
78
+ def in_flight? = %w[planned amending].include?(status)
79
+
80
+ def active_clauses = clauses.select(&:active?)
81
+
82
+ def clause(id) = clauses.find { |c| c.id == id }
83
+
84
+ private
85
+
86
+ def parse
87
+ return finding(:error, 1, "no YAML frontmatter — the capability format is frontmatter, not prose sections", "doc/malformed") unless (match = FRONTMATTER.match(@source))
88
+
89
+ return if legacy_format?
90
+
91
+ data = load_frontmatter(match[1])
92
+ return if data.nil?
93
+
94
+ @status = data["status"]
95
+ @plan = data["plan"].to_s.strip.then { |path| path unless path.empty? }
96
+ validate_status
97
+ check_plan
98
+ build_clauses(data["intent"])
99
+ end
100
+
101
+ # Reported before anything else: a legacy doc's clauses are in prose this
102
+ # parser does not read, so every downstream check would be measuring an
103
+ # empty document.
104
+ def legacy_format?
105
+ heading = line_of(LEGACY_HEADING)
106
+ specs_key = line_of(LEGACY_SPECS_KEY)
107
+ return false unless heading || specs_key
108
+
109
+ finding(:error, heading || specs_key,
110
+ "uses the retired prose format — move intent clauses and evaluations into frontmatter",
111
+ "doc/legacy-format")
112
+ true
113
+ end
114
+
115
+ def load_frontmatter(yaml)
116
+ YAML.safe_load(yaml, permitted_classes: [ Date ])
117
+ .tap { |data| return type_error unless data.is_a?(Hash) }
118
+ rescue Psych::Exception => e
119
+ finding(:error, 1, "frontmatter is not valid YAML (#{e.message})", "doc/malformed")
120
+ nil
121
+ end
122
+
123
+ def type_error
124
+ finding(:error, 1, "frontmatter must be a mapping with `status:` and `intent:` keys", "doc/malformed")
125
+ nil
126
+ end
127
+
128
+ def validate_status
129
+ return if STATUSES.include?(@status)
130
+
131
+ finding(:error, line_of(/^status:/) || 1,
132
+ "status #{@status.inspect} is not one of #{STATUSES.join(', ')}", "doc/malformed")
133
+ end
134
+
135
+ # `plan:` is the amendment's pointer to the plan doing it, set with
136
+ # `status: amending` and removed with it. Absent on an amending doc, no
137
+ # reader can tell which plan to finish. Present on any other doc, close-out
138
+ # stopped halfway.
139
+ def check_plan
140
+ if amending? && plan.nil?
141
+ finding(:error, status_line,
142
+ "an amending doc names the plan changing it — add `plan: docs/plans/<plan>.md`",
143
+ "status/plan-unnamed")
144
+ elsif amending? && !File.file?(File.join(@root, plan))
145
+ finding(:warning, plan_line,
146
+ "plan #{plan} does not exist — point `plan:` at where it moved, or record why it " \
147
+ "stopped and return the doc to `built`",
148
+ "status/plan-missing")
149
+ elsif !amending? && plan
150
+ finding(:error, plan_line,
151
+ "`plan:` belongs only on an amending doc — close-out removes it when the doc returns to `built`",
152
+ "status/plan-stale")
153
+ end
154
+ end
155
+
156
+ def status_line = line_of(/^status:/) || 1
157
+ def plan_line = line_of(/^plan:/) || 1
158
+
159
+ def build_clauses(intent)
160
+ unless intent.is_a?(Array) && !intent.empty?
161
+ return finding(:error, line_of(/^intent:/) || 1,
162
+ "frontmatter has no `intent:` list — every capability doc declares at least one clause",
163
+ "doc/malformed")
164
+ end
165
+
166
+ intent.each { |entry| build_clause(entry) }
167
+ flag_duplicate_ids
168
+ flag_dangling_supersessions
169
+ end
170
+
171
+ def build_clause(entry)
172
+ return finding(:error, 1, "every `intent:` entry must be a mapping with `id:` and `clause:`", "doc/malformed") unless entry.is_a?(Hash)
173
+
174
+ id = entry["id"].to_s
175
+ line = line_of(/^\s*-?\s*id:\s*#{Regexp.escape(id)}\s*$/) || 1
176
+
177
+ return finding(:error, line, "clause id #{entry['id'].inspect} must look like I1, I2, …", "doc/malformed") unless CLAUSE_ID.match?(id)
178
+ return finding(:error, line, "clause #{id} has no `clause:` sentence", "doc/malformed") if entry["clause"].to_s.strip.empty?
179
+
180
+ @clauses << Clause.new(
181
+ id: id, text: entry["clause"], line: line,
182
+ evaluations: Array(entry["evaluations"]).map(&:to_s),
183
+ superseded_by: Array(entry["superseded_by"]).map(&:to_s),
184
+ retired_on: entry["retired_on"]
185
+ )
186
+ end
187
+
188
+ def flag_duplicate_ids
189
+ @clauses.group_by(&:id).each_value do |group|
190
+ next if group.one?
191
+
192
+ finding(:error, group.last.line,
193
+ "clause id #{group.first.id} appears #{group.size} times — ids are assigned once and never reused",
194
+ "clause/duplicate-id")
195
+ end
196
+ end
197
+
198
+ def flag_dangling_supersessions
199
+ ids = @clauses.map(&:id)
200
+
201
+ @clauses.each do |clause|
202
+ (clause.superseded_by - ids).each do |missing|
203
+ finding(:error, clause.line,
204
+ "#{clause.id} is superseded by #{missing}, which this doc does not define",
205
+ "clause/dangling-supersession")
206
+ end
207
+ end
208
+ end
209
+
210
+ def line_of(pattern)
211
+ index = @source.lines.index { |line| pattern.match?(line) }
212
+ index && index + 1
213
+ end
214
+
215
+ def finding(severity, line, message, code)
216
+ @findings << Finding.new(severity: severity, path: relative_path, line: line, column: 1,
217
+ message: message, code: code)
218
+ nil
219
+ end
220
+ end
221
+ end
222
+ end
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AgentPrimitives
4
+ module Evals
5
+ # One offence. Shaped like a RuboCop offence so the text formatter can print
6
+ # `path:line:column: S: message [code]` and the JSON formatter can dump the
7
+ # same fields without a second representation.
8
+ #
9
+ # `code` is a stable `category/detail` slug (e.g. `clause/unproven`) — the
10
+ # thing a reader greps for and a CI log gets filtered on. Messages may be
11
+ # reworded; codes are the contract.
12
+ #
13
+ # `:notice` is `guard`'s only severity and never an offence: it reports what
14
+ # a change did to intent and its proof, for a person to judge.
15
+ #
16
+ # `details` carries what does not belong on the headline: labelled lines
17
+ # (was/now clause text) and unlabelled guidance. The text renderer truncates
18
+ # labelled text; `to_h` keeps it whole, so JSON is the full record.
19
+ Finding = Struct.new(:severity, :path, :line, :column, :message, :code, :details,
20
+ keyword_init: true) do
21
+ SEVERITY_LETTERS = { error: "E", warning: "W", notice: "N" }.freeze
22
+
23
+ def error? = severity == :error
24
+
25
+ def letter = SEVERITY_LETTERS.fetch(severity)
26
+
27
+ def to_s
28
+ "#{path}:#{line}:#{column}: #{letter}: #{message} [#{code}]"
29
+ end
30
+
31
+ def to_h
32
+ base = { severity: severity, path: path, line: line, column: column, message: message, code: code }
33
+ details.nil? || details.empty? ? base : base.merge(details: details.map(&:to_h))
34
+ end
35
+ end
36
+
37
+ # Assigned onto the class rather than inside its block: a constant assigned
38
+ # in the block would land on the lexically enclosing module, not on Finding.
39
+ Finding::Detail = Struct.new(:label, :text, keyword_init: true)
40
+ end
41
+ end