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,392 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../agent_primitives"
4
+ require_relative "evals"
5
+ require_relative "guard/baseline"
6
+
7
+ module AgentPrimitives
8
+ # Reports what a change did to the promises in docs/primitives/ and to the
9
+ # specs that prove them.
10
+ #
11
+ # `Evals` asks a stateless question — is every clause hooked up to a spec right
12
+ # now — and a whole class of drift passes it. Reword a clause under the same
13
+ # id, hollow out a tagged example, move a browser promise onto a model spec:
14
+ # the links stay well-formed and the run stays green while the record quietly
15
+ # stops describing the app. Catching that needs a *before*, which is what this
16
+ # adds by parsing the tree twice, at the base revision and in the working tree.
17
+ #
18
+ # Everything here is a **notice**. Nothing fails, nothing blocks, and the exit
19
+ # code is 0 whenever the comparison ran — because every check in it has a
20
+ # legitimate cause as well as a suspicious one, and a check that stops honest
21
+ # work is a check that gets routed around. The audience is a person deciding
22
+ # whether the agent's change to the record was the one they asked for; the
23
+ # agent reading its own notices mid-turn gets to put back a proof it dropped
24
+ # by accident. What an agent must not do is *discharge* a notice about intent
25
+ # by writing the provenance line that silences it — that hands the tool the
26
+ # job of laundering the change it was built to surface. Intent notices go to
27
+ # the user.
28
+ #
29
+ # Growth is silent by design: new clauses, new tagged examples, added
30
+ # evaluations and appended provenance produce nothing. Only the record getting
31
+ # smaller or different is worth a person's attention.
32
+ module Guard
33
+ DEFAULT_BASE = "HEAD"
34
+ PROVENANCE_HEADING = /^##\s+Provenance\s*$/
35
+ PROVENANCE_ENTRY = /^\s*[-*]\s+(.+)$/
36
+ NEXT_HEADING = /^##\s+/
37
+
38
+ # Statuses ordered by how much they promise. `deprecated` sits below
39
+ # `shaping` deliberately: it is the one status that retires a capability's
40
+ # obligations wholesale, so arriving at it is always worth a line.
41
+ #
42
+ # Anything unrecognised ranks below all of them, so `built` → a typo reads as
43
+ # the downgrade it is. Ranking an unknown status *above* `built` would let the
44
+ # single most consequential edit — shedding every obligation the status
45
+ # carried — pass as no change at all.
46
+ #
47
+ # `amending` ranks with `built`. The capability has shipped either way, and
48
+ # a plan that marks its amendment is the record working, not shedding the
49
+ # coverage it owed.
50
+ STATUS_RANK = { "deprecated" => 0, "shaping" => 1, "planned" => 2, "built" => 3, "amending" => 3 }.freeze
51
+ UNKNOWN_STATUS_RANK = -1
52
+
53
+ # Codes from `Evals::Capability` meaning the clauses could not be read at all.
54
+ UNREADABLE_CODES = %w[doc/malformed doc/legacy-format].freeze
55
+
56
+ Result = Struct.new(:findings, :base, :capabilities, keyword_init: true) do
57
+ def notices = findings
58
+ def clean? = findings.empty?
59
+ end
60
+
61
+ # One side of the comparison: capability docs by name, their provenance
62
+ # lines, and every tagged example in the suite.
63
+ Snapshot = Struct.new(:capabilities, :provenance, :proofs, keyword_init: true) do
64
+ def capability(name) = capabilities[name]
65
+ end
66
+
67
+ class << self
68
+ def run(root:, base: DEFAULT_BASE, primitives_dir: Evals::DEFAULT_PRIMITIVES_DIR,
69
+ specs_dir: Evals::DEFAULT_SPECS_DIR)
70
+ capabilities_dir = File.join(primitives_dir, Evals::CAPABILITIES_SUBDIR)
71
+ unless Dir.exist?(File.join(root, capabilities_dir))
72
+ raise Error, "no capability docs at #{capabilities_dir}/"
73
+ end
74
+
75
+ current = snapshot(root, capabilities_dir, specs_dir)
76
+
77
+ Baseline.capture(root: root, base: base, paths: [ primitives_dir, specs_dir ]) do |dir, ref|
78
+ Result.new(findings: sort(compare(snapshot(dir, capabilities_dir, specs_dir), current)),
79
+ base: ref, capabilities: current.capabilities.size)
80
+ end
81
+ end
82
+
83
+ private
84
+
85
+ def snapshot(root, capabilities_dir, specs_dir)
86
+ docs = Evals::Capability.load_all(File.join(root, capabilities_dir), root: root)
87
+ tags, = Evals::Tags.scan(File.join(root, specs_dir), root: root)
88
+
89
+ Snapshot.new(capabilities: docs.to_h { |doc| [ doc.name, doc ] },
90
+ provenance: docs.to_h { |doc| [ doc.name, provenance_of(doc.path) ] },
91
+ proofs: Evals::Proofs.read(tags, root: root))
92
+ end
93
+
94
+ # Entries under `## Provenance`, one per bullet, with runs of internal
95
+ # whitespace squeezed so re-spacing a line is not read as rewriting it.
96
+ # A provenance entry is one line by rule (`primitives-format` § Provenance —
97
+ # a multi-line entry is a lint finding), so a bullet wrapped onto a second
98
+ # line is itself an edit worth reporting, and its continuation is
99
+ # deliberately not stitched back on.
100
+ def provenance_of(path)
101
+ lines = File.readlines(path, chomp: true, encoding: "UTF-8")
102
+ start = lines.index { |line| PROVENANCE_HEADING.match?(line) }
103
+ return [] if start.nil?
104
+
105
+ lines[(start + 1)..].to_a
106
+ .take_while { |line| !NEXT_HEADING.match?(line) }
107
+ .filter_map { |line| PROVENANCE_ENTRY.match(line)&.captures&.first&.squeeze(" ")&.strip }
108
+ end
109
+
110
+ def compare(base, current)
111
+ base.capabilities.flat_map { |name, doc| capability_findings(name, doc, base, current) } +
112
+ proof_findings(base, current)
113
+ end
114
+
115
+ def capability_findings(name, was, base, current)
116
+ now = current.capability(name)
117
+ return [ removed_doc(was) ] if now.nil?
118
+
119
+ # A doc that no longer parses has no clauses to compare, and comparing
120
+ # anyway reports every clause as deleted — a cascade that describes the
121
+ # parse failure as eleven separate decisions nobody made.
122
+ unreadable = unreadable_findings(now)
123
+ return unreadable if unreadable.any?
124
+
125
+ clause_findings(was, now, discharged_ids(base.provenance[name], current.provenance[name])) +
126
+ status_findings(was, now) +
127
+ provenance_findings(now, base.provenance[name], current.provenance[name])
128
+ end
129
+
130
+ # Only when the doc yielded **nothing**. `doc/malformed` also covers faults
131
+ # a doc survives — an unrecognised `status:`, one bad clause entry — and
132
+ # those leave clauses readable, so they are `evals`' business rather than a
133
+ # reason to stop comparing.
134
+ def unreadable_findings(now)
135
+ return [] unless now.clauses.empty?
136
+
137
+ now.findings.select { |finding| UNREADABLE_CODES.include?(finding.code) }.map do |finding|
138
+ notice(now.relative_path, finding.line,
139
+ "this doc no longer parses, so what it promises cannot be compared with what it " \
140
+ "promised — #{finding.message}",
141
+ "doc/unreadable")
142
+ end
143
+ end
144
+
145
+ def removed_doc(was)
146
+ notice(was.relative_path, 1,
147
+ "capability doc deleted — #{was.active_clauses.size} active clause(s) went with it; " \
148
+ "a capability that is gone is normally `status: deprecated` with a provenance entry, " \
149
+ "so the promises it made stay readable",
150
+ "doc/removed")
151
+ end
152
+
153
+ # Growth is otherwise silent, and `amending` → `built` is no change in
154
+ # rank. It is still the one move worth a line, because it is the moment
155
+ # the new clauses' rows become owed in full, and a reviewer should see
156
+ # that they were filed.
157
+ def status_findings(was, now)
158
+ if rank(now.status) < rank(was.status)
159
+ [ notice(now.relative_path, 1,
160
+ "status went #{was.status} → #{now.status || '(none)'}, which drops the coverage this doc owed",
161
+ "status/downgraded") ]
162
+ elsif was.status == "amending" && now.status == "built"
163
+ [ notice(now.relative_path, 1,
164
+ "status went amending → built — confirm every clause the plan's Intent impact block named " \
165
+ "has its `evaluations:` row",
166
+ "status/closed-out") ]
167
+ else
168
+ []
169
+ end
170
+ end
171
+
172
+ def rank(status) = STATUS_RANK.fetch(status, UNKNOWN_STATUS_RANK)
173
+
174
+ # Provenance is append-only, and it is also the trace every other notice
175
+ # here is discharged against — so an edit to it is the one change that
176
+ # degrades the record's ability to describe the next one.
177
+ #
178
+ # Compared as a prefix rather than as a set: entries are appended at the
179
+ # end, so the old list must still be the front of the new one. A set
180
+ # difference would miss a reordering, and would miss deleting one of two
181
+ # identical entries. Only the first divergence is reported — inserting a
182
+ # line mid-history moves every entry after it, and eleven notices for one
183
+ # edit describe it worse than one does.
184
+ def provenance_findings(now, before, after)
185
+ index = before.each_index.find { |i| after[i] != before[i] }
186
+ return [] if index.nil?
187
+
188
+ [ notice(now.relative_path, 1,
189
+ "provenance entry #{summarise(before[index])} was edited, removed, or reordered — provenance " \
190
+ "is append-only: new entries go at the end, and a wrong entry is corrected by a new entry",
191
+ "provenance/rewritten") ]
192
+ end
193
+
194
+ def clause_findings(was, now, discharged)
195
+ was.clauses.flat_map do |before|
196
+ after = now.clause(before.id)
197
+ next [ vanished(now, before) ] if after.nil?
198
+ next [ deactivated(now, before, after) ] if before.active? && !after.active?
199
+ next [] unless after.active?
200
+
201
+ rewritten(was, now, before, after, discharged) + evaluation_findings(now, before, after)
202
+ end
203
+ end
204
+
205
+ def vanished(now, before)
206
+ notice(now.relative_path, 1,
207
+ "#{before.id} is gone — #{summarise(before.text)}. Ids are never deleted or reused: " \
208
+ "supersede it with `superseded_by:` so a future reader learns the promise existed and why it went",
209
+ "intent/vanished")
210
+ end
211
+
212
+ def deactivated(now, before, after)
213
+ verb = after.retired_on ? "retired" : "superseded by #{after.superseded_by.join(', ')}"
214
+
215
+ notice(now.relative_path, after.line,
216
+ "#{before.id} was #{verb} — #{summarise(before.text)}. The sanctioned path, and " \
217
+ "worth confirming it was asked for",
218
+ "intent/deactivated")
219
+ end
220
+
221
+ # In-place rewording is legitimate while a doc is still drafting; it stops
222
+ # being legitimate once a plan has been approved against those clauses,
223
+ # which `planned`, `built` and `amending` mark.
224
+ def rewritten(was, now, before, after, discharged)
225
+ return [] unless %w[planned built amending].include?(was.status)
226
+ return [] if before.text.to_s.strip == after.text.to_s.strip
227
+ return [] if discharged.include?(before.id)
228
+
229
+ [ notice(now.relative_path, after.line,
230
+ "#{before.id} now promises something else, under the same id and with no provenance entry",
231
+ "intent/rewritten",
232
+ details: [
233
+ Evals::Finding::Detail.new(label: "was", text: clean(before.text)),
234
+ Evals::Finding::Detail.new(label: "now", text: clean(after.text)),
235
+ Evals::Finding::Detail.new(label: nil, text: "an amendment supersedes the old clause " \
236
+ "and records the decision — only the " \
237
+ "user's decision changes intent")
238
+ ]) ]
239
+ end
240
+
241
+ # Three outcomes, because "this clause names a different file now" and
242
+ # "this clause names one fewer file" are different events and only the
243
+ # second one is a loss of coverage.
244
+ def evaluation_findings(now, before, after)
245
+ dropped = before.evaluations - after.evaluations
246
+ return [] if dropped.empty?
247
+
248
+ added = after.evaluations - before.evaluations
249
+ relayered_to = added.reject { |path| layers(dropped).include?(layer(path)) }
250
+
251
+ return [ relayered(now, after, dropped, relayered_to) ] if relayered_to.any?
252
+ return [ moved_evaluation(now, after, dropped, added) ] if added.any?
253
+
254
+ [ dropped_evaluation(now, after, dropped) ]
255
+ end
256
+
257
+ def relayered(now, after, dropped, moved)
258
+ notice(now.relative_path, after.line,
259
+ "#{after.id} moved its proof from #{dropped.join(', ')} to #{moved.join(', ')} — a clause " \
260
+ "is only proven at a layer that can hold it, so check the new home can fail for the " \
261
+ "reason the old one could",
262
+ "evaluation/relayered")
263
+ end
264
+
265
+ # Same layer, so the clause is not proven by less — it is proven somewhere
266
+ # else, and whether the new file proves the same thing is the open question.
267
+ def moved_evaluation(now, after, dropped, added)
268
+ notice(now.relative_path, after.line,
269
+ "#{after.id} moved its proof from #{dropped.join(', ')} to #{added.join(', ')} at the same " \
270
+ "layer — confirm the new file proves what the old one did",
271
+ "evaluation/moved")
272
+ end
273
+
274
+ def dropped_evaluation(now, after, dropped)
275
+ notice(now.relative_path, after.line,
276
+ "#{after.id} no longer names #{dropped.join(', ')} — an active clause is proven by less " \
277
+ "than it was",
278
+ "evaluation/dropped")
279
+ end
280
+
281
+ # Examples are compared per (clause, file) rather than by name, so renaming
282
+ # one reads as a change to it and never as a deletion plus an unrelated
283
+ # addition.
284
+ #
285
+ # Within a group, identical bodies are paired off **first**. Pairing purely
286
+ # by position would report a spurious change for every untouched example
287
+ # that a new sibling was inserted above — which breaks the one invariant
288
+ # this tool is sold on, that growth is silent.
289
+ def proof_findings(base, current)
290
+ after = current.proofs.group_by(&:file_key)
291
+
292
+ base.proofs.group_by(&:file_key).flat_map do |key, before|
293
+ next [] unless still_owed?(current, key)
294
+
295
+ now = after[key] || []
296
+ gone = now.size < before.size ? [ vanished_proof(before, now.size) ] : []
297
+
298
+ gone + align(before, now).flat_map { |was, is| changed_proof(was, is) }
299
+ end
300
+ end
301
+
302
+ # Pairs each example with what it became, in three passes: identical bodies
303
+ # first (nothing to say about those), then same name with a changed body,
304
+ # then whatever is left, by position — which is what makes a rename read as
305
+ # a change rather than as a deletion.
306
+ #
307
+ # The name pass is what keeps the pairing honest when the counts differ:
308
+ # position alone would marry a deleted example to an unrelated survivor and
309
+ # describe the pair as one edit.
310
+ def align(before, now)
311
+ remaining = now.dup
312
+ changed = before.reject { |was| take(remaining) { |is| is.digest == was.digest } }
313
+ named, rest = changed.partition { |was| was.description && remaining.any? { |is| is.description == was.description } }
314
+
315
+ named.map { |was| [ was, take(remaining) { |is| is.description == was.description } ] } +
316
+ rest.each_with_index.map { |was, index| [ was, remaining[index] ] }
317
+ end
318
+
319
+ # Removes the first match from `list` and returns it, or nil.
320
+ def take(list, &)
321
+ index = list.index(&)
322
+ index && list.delete_at(index)
323
+ end
324
+
325
+ # A proof that went with a clause its change also tombstoned is not a
326
+ # missing proof — the promise it covered is no longer being made.
327
+ def still_owed?(current, (name, clause_id, _path))
328
+ capability = current.capability(name)
329
+ return false if capability.nil?
330
+
331
+ clause = capability.clause(clause_id)
332
+ !clause.nil? && clause.active?
333
+ end
334
+
335
+ def vanished_proof(before, remaining)
336
+ gone = before.size - remaining
337
+ first = before.first
338
+
339
+ notice(first.path, remaining.zero? ? 1 : first.line,
340
+ "#{gone} tagged example(s) for #{first.capability}##{first.clause_id} " \
341
+ "#{gone == 1 ? 'is' : 'are'} gone from this file, and the clause is still active",
342
+ "proof/removed")
343
+ end
344
+
345
+ def changed_proof(was, is)
346
+ return [] if is.nil? || was.digest == is.digest
347
+
348
+ if is.assertions < was.assertions
349
+ [ notice(is.path, is.line,
350
+ "the example proving #{is.capability}##{is.clause_id} lost #{was.assertions - is.assertions} " \
351
+ "assertion(s) — it still carries the tag while proving less of the clause",
352
+ "proof/weakened") ]
353
+ else
354
+ [ notice(is.path, is.line,
355
+ "the example proving #{is.capability}##{is.clause_id} changed — confirm it can still fail " \
356
+ "for the reason the clause could stop being true",
357
+ "proof/changed") ]
358
+ end
359
+ end
360
+
361
+ # A clause id named by a provenance entry this change added. The record of
362
+ # the decision is what separates an amendment from a rewrite — and writing
363
+ # that line is the user's call, not the agent's.
364
+ def discharged_ids(before, after)
365
+ (after - before).flat_map { |entry| entry.scan(/\bI[1-9]\d*\b/) }.uniq
366
+ end
367
+
368
+ def layers(paths) = paths.map { |path| layer(path) }
369
+
370
+ # spec/system/comment_threads_spec.rb → "system"
371
+ def layer(path) = path.split("/")[1]
372
+
373
+ def summarise(text, limit: 70)
374
+ one_line = clean(text)
375
+ one_line.length > limit ? "#{one_line[0, limit - 1]}…".inspect : one_line.inspect
376
+ end
377
+
378
+ # Untruncated, for detail lines: the renderer decides how much fits, and
379
+ # JSON carries the whole clause either way.
380
+ def clean(text) = text.to_s.squeeze(" ").strip.tr("\n", " ")
381
+
382
+ def notice(path, line, message, code, details: nil)
383
+ Evals::Finding.new(severity: :notice, path: path, line: line, column: 1, message: message,
384
+ code: code, details: details)
385
+ end
386
+
387
+ def sort(findings)
388
+ findings.sort_by { |finding| [ finding.path, finding.line, finding.code ] }
389
+ end
390
+ end
391
+ end
392
+ end
@@ -0,0 +1,50 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "fileutils"
4
+ require_relative "../agent_primitives"
5
+
6
+ module AgentPrimitives
7
+ # Copies this gem's skills into a directory an editor reads skills from.
8
+ #
9
+ # Additive by design: it writes its own files and nothing else. It never
10
+ # deletes, so a skill the app keeps beside these is safe, and a file this gem
11
+ # stops shipping stays until someone removes it — the CHANGELOG names those.
12
+ class Importer
13
+ Result = Struct.new(:created, :updated, keyword_init: true) do
14
+ def written = created + updated
15
+ end
16
+
17
+ def initialize(destination:, source: AgentPrimitives.skills)
18
+ @destination = destination
19
+ @source = source
20
+ end
21
+
22
+ def run
23
+ raise Error, "no such directory: #{@destination}" unless Dir.exist?(@destination)
24
+
25
+ result = Result.new(created: [], updated: [])
26
+ files.each { |relative| copy(relative, result) }
27
+ result
28
+ end
29
+
30
+ private
31
+
32
+ def files
33
+ Dir.glob("**/*", base: @source)
34
+ .select { |relative| File.file?(File.join(@source, relative)) }
35
+ .reject { |relative| AgentPrimitives.dev_only?(relative) }
36
+ .sort
37
+ end
38
+
39
+ def copy(relative, result)
40
+ target = File.join(@destination, relative)
41
+ body = File.binread(File.join(@source, relative))
42
+ existed = File.exist?(target)
43
+ return if existed && File.binread(target) == body
44
+
45
+ FileUtils.mkdir_p(File.dirname(target))
46
+ File.binwrite(target, body)
47
+ (existed ? result.updated : result.created) << relative
48
+ end
49
+ end
50
+ end
@@ -0,0 +1,220 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "open3"
4
+ require_relative "../agent_primitives"
5
+ require_relative "evals"
6
+ require_relative "guard/baseline"
7
+
8
+ module AgentPrimitives
9
+ # Lists the examples that prove each intent clause, and — the part no other
10
+ # command can see — how many of the examples in an evaluation file carry the
11
+ # tag.
12
+ #
13
+ # `Evals` is a gate whose unit of coverage is the **file**: a clause naming
14
+ # `spec/policies/long_list_policy_spec.rb` is satisfied the moment *one*
15
+ # example in that file carries the tag. So a clause the plan meant to prove
16
+ # with four denials, three of which got tagged, passes — and `Guard` is silent
17
+ # too, because an untagged new example is growth and growth is silent there by
18
+ # design. The rule those two leave unenforced is the one in
19
+ # `tagging-intent` § Tagging the Intent a Spec Proves:
20
+ # a clause proven by four examples is tagged on all four.
21
+ #
22
+ # This closes that gap as a **report**, not a gate. Exit code is always 0 and
23
+ # nothing here is a finding: most examples in a spec file legitimately carry no
24
+ # tag ("only evaluation examples are tagged"), so a tagged count is a number
25
+ # for a reader to compare against the plan's proof set, never an offence. Made
26
+ # an offence it would fire on almost every file and get routed around.
27
+ #
28
+ # Textual, like the tag scan: it must run with no database and no Rails
29
+ # environment. `rspec --tag 'intent:x#I1'` can list the tagged examples but
30
+ # needs the whole app booted. The untagged siblings are collected too — a
31
+ # planned example that never got its tag is found among them — but only
32
+ # `--format json` carries them: printed, they drowned the report in any
33
+ # real spec file, and a reader holding the plan already knows which example
34
+ # is missing from the tagged list.
35
+ module ProofReport
36
+ # Scope, and with it output density. Unscoped and `--since` are health
37
+ # passes, so they stay one line per clause; naming a capability or a clause
38
+ # is a question about it, and earns the per-file example listings.
39
+ SCOPE = /\A(?<capability>[a-z0-9_]+)(?:#(?<clause>I[1-9]\d*))?\z/
40
+
41
+ # One file a clause is proven in: its examples, which of them carry the tag,
42
+ # and which do not.
43
+ Coverage = Struct.new(:path, :declared, :exists, :examples, :tagged, :untagged, :misplaced,
44
+ keyword_init: true) do
45
+ def to_h
46
+ { path: path, declared: declared, exists: exists, examples: examples,
47
+ tagged: tagged.map { |proof| { line: proof.opener, description: proof.description, assertions: proof.assertions } },
48
+ untagged: untagged.map { |example| { line: example.line, description: example.description } },
49
+ misplaced: misplaced.map { |proof| { line: proof.line, group: proof.group } } }
50
+ end
51
+ end
52
+
53
+ # One clause and everywhere it is proven.
54
+ Row = Struct.new(:capability, :status, :clause, :files, keyword_init: true) do
55
+ def id = "#{capability}##{clause.id}"
56
+
57
+ def tagged = files.sum { |file| file.tagged.size }
58
+
59
+ def state
60
+ return "superseded by #{clause.superseded_by.join(', ')}" unless clause.superseded_by.empty?
61
+
62
+ clause.retired_on ? "retired #{clause.retired_on}" : nil
63
+ end
64
+
65
+ def to_h
66
+ { capability: capability, clause_id: clause.id, clause: clause.text, status: status,
67
+ active: clause.active?, state: state, files: files.map(&:to_h) }
68
+ end
69
+ end
70
+
71
+ Result = Struct.new(:rows, :scope, :detail, :capabilities, :unusable, :base, keyword_init: true) do
72
+ def tagged = rows.sum(&:tagged)
73
+
74
+ def empty? = rows.empty?
75
+ end
76
+
77
+ class << self
78
+ def run(root:, scope: nil, since: nil, primitives_dir: Evals::DEFAULT_PRIMITIVES_DIR,
79
+ specs_dir: Evals::DEFAULT_SPECS_DIR)
80
+ capabilities_dir = File.join(root, primitives_dir, Evals::CAPABILITIES_SUBDIR)
81
+ raise Error, "no capability docs at #{primitives_dir}/#{Evals::CAPABILITIES_SUBDIR}/" unless Dir.exist?(capabilities_dir)
82
+
83
+ target = parse_scope(scope)
84
+ capabilities = Evals::Capability.load_all(capabilities_dir, root: root)
85
+ tags, findings = Evals::Tags.scan(File.join(root, specs_dir), root: root)
86
+ found = Evals::Proofs.read(tags, root: root)
87
+
88
+ rows = build_rows(capabilities, found.group_by(&:clause_key),
89
+ found.group_by(&:path).transform_values { |list| list.map(&:opener) }, root: root)
90
+ base, touched = since ? changed_paths(root, since) : [ nil, nil ]
91
+
92
+ Result.new(rows: select(rows, target, touched, primitives_dir),
93
+ scope: scope, detail: detail_for(target, since), capabilities: capabilities.size,
94
+ unusable: unusable(capabilities, tags, findings), base: base)
95
+ end
96
+
97
+ private
98
+
99
+ def parse_scope(scope)
100
+ return nil if scope.nil?
101
+
102
+ match = SCOPE.match(scope)
103
+ raise Error, "scope #{scope.inspect} reads `<capability>` or `<capability>#I<n>`, e.g. comment_threads#I2" if match.nil?
104
+
105
+ [ match[:capability], match[:clause] ]
106
+ end
107
+
108
+ # `--since` stays at summary density on purpose: it is the shape a task's
109
+ # verify step runs, and that step reads counts against the plan's proof
110
+ # set — a count that comes up short is drilled into by naming the clause.
111
+ def detail_for(target, _since)
112
+ target ? :detail : :summary
113
+ end
114
+
115
+ def build_rows(capabilities, proofs, tagged_lines, root:)
116
+ lines = {}
117
+
118
+ capabilities.flat_map do |capability|
119
+ capability.clauses.map do |clause|
120
+ Row.new(capability: capability.name, status: capability.status, clause: clause,
121
+ files: coverage(clause, proofs[[ capability.name, clause.id ]] || [],
122
+ tagged_lines, lines, root: root))
123
+ end
124
+ end
125
+ end
126
+
127
+ # Union of what the clause declares and where its tags actually are: a tag
128
+ # in a file the clause does not list is real proof, and hiding it would
129
+ # describe the suite as thinner than it is. `declared` carries which is
130
+ # which — `evals` is the one that calls the undeclared case an offence.
131
+ def coverage(clause, proofs, tagged_lines, lines, root:)
132
+ found = proofs.group_by(&:path)
133
+
134
+ (clause.evaluations | found.keys).sort.map do |relative|
135
+ # A tag on a `describe` has no example around it, so everything read
136
+ # from it describes the group line. Kept out of `tagged` for that
137
+ # reason: counting it would put a phantom in the numerator of a ratio
138
+ # someone is about to hold against a plan.
139
+ misplaced, tagged = (found[relative] || []).sort_by(&:opener).partition(&:misplaced?)
140
+ examples = lines[relative] ||= read(File.join(root, relative))
141
+ next missing(relative, tagged, misplaced) if examples.nil?
142
+
143
+ # Anything carrying *any* intent tag is excluded, not just this
144
+ # clause's: an example proving a sibling clause is not a candidate this
145
+ # change forgot to tag, and listing it as one would send a reader to
146
+ # check work that is already done.
147
+ carried = tagged_lines[relative] || []
148
+
149
+ Coverage.new(path: relative, declared: clause.evaluations.include?(relative), exists: true,
150
+ examples: examples.size, tagged: tagged, misplaced: misplaced,
151
+ untagged: examples.reject { |example| carried.include?(example.line) })
152
+ end
153
+ end
154
+
155
+ # nil for a file the clause names and the app does not have — read once per
156
+ # file however many clauses it proves.
157
+ def read(path)
158
+ return nil unless File.exist?(path)
159
+
160
+ Evals::Proofs.examples(File.readlines(path, chomp: true, encoding: "UTF-8"))
161
+ end
162
+
163
+ def missing(relative, tagged, misplaced)
164
+ Coverage.new(path: relative, declared: true, exists: false, examples: 0, tagged: tagged,
165
+ untagged: [], misplaced: misplaced)
166
+ end
167
+
168
+ def select(rows, target, touched, primitives_dir)
169
+ rows = rows.select { |row| row.capability == target.first } if target
170
+ rows = rows.select { |row| row.clause.id == target.last } if target&.last
171
+ raise Error, "nothing named #{target.compact.join('#')} in #{primitives_dir}/" if target && rows.empty?
172
+
173
+ touched ? rows.select { |row| row.files.any? { |file| touched.include?(file.path) } } : rows
174
+ end
175
+
176
+ # Clauses whose evaluation files this change touched, so the verify step of
177
+ # one task does not have to enumerate the clauses it served. Untracked
178
+ # files are included deliberately: a brand-new spec file carrying the first
179
+ # tags for a clause is the commonest shape of the omission this reports.
180
+ # Resolved through `Guard::Baseline` so `--since main` means the same thing
181
+ # as `guard --base main`: where this work started, not where main has since
182
+ # got to.
183
+ def changed_paths(root, since)
184
+ base = Guard::Baseline.resolve(root, since)
185
+ paths = git(root, "diff", "--name-only", base).lines +
186
+ git(root, "ls-files", "--others", "--exclude-standard").lines
187
+
188
+ [ base, paths.map(&:strip).reject(&:empty?) ]
189
+ end
190
+
191
+ # No shell, so a branch name with a space or a `;` in it is an argument.
192
+ def git(root, *args)
193
+ out, err, status = Open3.capture3("git", "-C", root, *args)
194
+ raise Error, "git #{args.first} failed: #{err.strip}" unless status.success?
195
+
196
+ out
197
+ end
198
+
199
+ # Counted, not listed: every one of these is `evals`' offence to report, and
200
+ # repeating the detail here would describe one mistake in two voices. The
201
+ # counts are still worth a line — each kind is another way a clause ends up
202
+ # proven by less than the plan said, and a reader who sees none of them
203
+ # named would read this report as the whole picture.
204
+ #
205
+ # One label per tag, most disqualifying first: a tag naming nothing real is
206
+ # reported as unresolved even when it also sits on a group, so the counts
207
+ # sum to the number of unusable tags rather than double-counting.
208
+ def unusable(capabilities, tags, findings)
209
+ by_name = capabilities.to_h { |capability| [ capability.name, capability ] }
210
+ unresolved, placed = tags.partition do |tag|
211
+ clause = by_name[tag.capability]&.clause(tag.clause_id)
212
+ clause.nil? || !clause.active?
213
+ end
214
+
215
+ { unresolved: unresolved.size, misplaced: placed.count(&:misplaced?),
216
+ malformed: findings.count { |finding| finding.code == "tag/malformed" } }
217
+ end
218
+ end
219
+ end
220
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AgentPrimitives
4
+ VERSION = "0.1.0"
5
+ end