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,139 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "digest"
4
+ require_relative "tags"
5
+
6
+ module AgentPrimitives
7
+ module Evals
8
+ # A tagged example, read as the proof of one clause: which file it lives in,
9
+ # what it asserts, and a digest of its body.
10
+ #
11
+ # `Evals::Tags` finds where a tag sits; this reads the example around it,
12
+ # because "the tag is still there" and "the example still proves anything"
13
+ # are different questions and only the second one needs the body.
14
+ #
15
+ # Textual, like the tag scan itself — this must run with no database and no
16
+ # Rails environment. The body is delimited by indentation: the `end` at the
17
+ # example opener's column, or — for a `{ … }` one-liner, which has no `end`
18
+ # to find — the opening line alone. RuboCop keeps app suites in that shape,
19
+ # and an example this cannot delimit falls back to its opening line, which
20
+ # reads as "changed" more often than it should rather than silently as
21
+ # unchanged.
22
+ #
23
+ # `opener` is the line the example starts on, which is not always the tag's
24
+ # own line — metadata wraps. `proofs` needs it to say which of a file's
25
+ # examples are the tagged ones.
26
+ #
27
+ # `group` is set when the tag sits on a `describe` or `context` instead of an
28
+ # example. There is no example around such a tag, so everything read here
29
+ # describes the group line: no description, no assertions. It is carried
30
+ # rather than dropped because a consumer that showed it as an ordinary proof
31
+ # would be showing a phantom.
32
+ Proof = Struct.new(:capability, :clause_id, :path, :line, :opener, :group, :description, :assertions,
33
+ :digest, keyword_init: true) do
34
+ def clause_key = [ capability, clause_id ]
35
+
36
+ def file_key = [ capability, clause_id, path ]
37
+
38
+ def misplaced? = !group.nil?
39
+ end
40
+
41
+ # One example opener, tagged or not. The untagged ones are what turn "this
42
+ # file is an evaluation" into "three of this file's seven examples carry the
43
+ # tag" — the difference the file-granular checks in `Evals` cannot see.
44
+ Example = Struct.new(:line, :description, keyword_init: true)
45
+
46
+ module Proofs
47
+ ASSERTION = /\b(?:expect|is_expected|assert|assert_not)\b/
48
+ # The example's name: the first string literal on the opening line, which
49
+ # precedes the `intent:` tag's own quoted value. The two quote styles are
50
+ # separate alternatives rather than one `["']` class, so an apostrophe in
51
+ # a double-quoted name — "rejects a typo'd clause" — does not end the
52
+ # match half way through the description a reader is about to read.
53
+ DESCRIPTION = /"([^"]*)"|'([^']*)'/
54
+
55
+ # Reads each spec file once, whatever number of tags it carries.
56
+ def self.read(tags, root:)
57
+ tags.group_by(&:path).flat_map do |relative, file_tags|
58
+ path = File.join(root, relative)
59
+ next [] unless File.exist?(path)
60
+
61
+ lines = File.readlines(path, chomp: true, encoding: "UTF-8")
62
+ file_tags.map { |tag| build(tag, lines) }
63
+ end
64
+ end
65
+
66
+ # Every example in a file, in source order. Group openers are skipped:
67
+ # a `describe` is not a candidate proof, and counting it would inflate the
68
+ # denominator of a ratio a reader is about to compare with a plan.
69
+ def self.examples(lines)
70
+ lines.each_with_index.filter_map do |line, index|
71
+ next unless Tags.example_opener?(line)
72
+
73
+ Example.new(line: index + 1, description: description_of(line))
74
+ end
75
+ end
76
+
77
+ def self.build(tag, lines)
78
+ opener = opener_index(lines, tag.line - 1)
79
+ body = body_of(lines, tag.line - 1, opener)
80
+
81
+ Proof.new(capability: tag.capability, clause_id: tag.clause_id, path: tag.path, line: tag.line,
82
+ opener: opener ? opener + 1 : tag.line, group: tag.group,
83
+ description: opener && description_of(lines[opener]),
84
+ assertions: body.count { |line| ASSERTION.match?(line) },
85
+ digest: Digest::SHA256.hexdigest(body.join("\n")))
86
+ end
87
+
88
+ def self.description_of(line) = DESCRIPTION.match(line.to_s)&.captures&.compact&.first
89
+
90
+ # Dedented before digesting, so wrapping an example in one more `context`
91
+ # is not reported as a change to what it proves.
92
+ def self.body_of(lines, index, opener)
93
+ return [ lines[index].to_s.strip ] if opener.nil?
94
+
95
+ indent = lines[opener][/\A[ \t]*/]
96
+ closer = closing_index(lines, opener, indent)
97
+
98
+ lines[opener..closer].map { |line| line.delete_prefix(indent).rstrip }
99
+ end
100
+
101
+ # The example this tag is metadata for. Same lookback as the tag scan:
102
+ # metadata wrapped onto its own line under a long example name is still on
103
+ # that example.
104
+ def self.opener_index(lines, index)
105
+ index.downto([ index - Tags::LOOKBACK, 0 ].max) do |candidate|
106
+ return candidate if Tags.example_opener?(lines[candidate])
107
+ end
108
+
109
+ nil
110
+ end
111
+
112
+ # Stops at the example's own `end`, or at the next example that starts at
113
+ # the same column — whichever comes first. The second bound is what keeps a
114
+ # `{ … }` one-liner from swallowing its siblings all the way down to some
115
+ # later example's `end`, and reporting an untouched example as changed
116
+ # every time a neighbour is added.
117
+ def self.closing_index(lines, opener, indent)
118
+ return opener if one_liner?(lines[opener])
119
+
120
+ terminator = /\A#{Regexp.escape(indent)}end\b/
121
+ sibling = /\A#{Regexp.escape(indent)}\S/
122
+
123
+ ((opener + 1)...lines.size).each do |index|
124
+ line = lines[index].to_s
125
+ return index if terminator.match?(line)
126
+ return index - 1 if sibling.match?(line) && Tags.example_opener?(line)
127
+ end
128
+
129
+ opener
130
+ end
131
+
132
+ # `it("replies", intent: "x") { expect(…).to be(true) }` closes on its own
133
+ # line. A trailing `do` (or an opening `{` with the body below) does not.
134
+ def self.one_liner?(line) = line.to_s.rstrip.end_with?("}")
135
+
136
+ private_class_method :build, :body_of, :opener_index, :closing_index, :one_liner?, :description_of
137
+ end
138
+ end
139
+ end
@@ -0,0 +1,160 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AgentPrimitives
4
+ module Evals
5
+ # Every `intent:` metadata tag in the spec suite.
6
+ #
7
+ # it "shows replies nested under their parent", intent: "comment_threads#I2" do
8
+ # it "nests three deep", intent: %w[comment_threads#I2 comment_threads#I3] do
9
+ #
10
+ # Real RSpec metadata rather than a comment, so the same tag that binds the
11
+ # clause also selects the proof:
12
+ #
13
+ # bundle exec rspec --tag 'intent:comment_threads#I2'
14
+ #
15
+ # A tag belongs on the example, never on the group around it — see
16
+ # PLACEMENT below.
17
+ #
18
+ # Scanned textually rather than by booting RSpec: this must run in any CI
19
+ # job, with no database and no Rails environment. The honest cost is that a
20
+ # tag inside commented-out or unreachable code still counts — the same
21
+ # trade-off bin/check-references makes. A tag that resolves here but whose
22
+ # example no longer runs is caught by the suite itself going red, not here.
23
+ module Tags
24
+ # `intent:` followed by one string, a %w list, or a bracketed list.
25
+ PATTERN = /
26
+ \bintent:\s*
27
+ (?:
28
+ %[wi]\[(?<list>[^\]]*)\]
29
+ | \[(?<bracketed>[^\]]*)\]
30
+ | (?<quote>["'])(?<single>[^"']*)\k<quote>
31
+ )
32
+ /x
33
+ QUOTED = /["']([^"']+)["']/
34
+
35
+ # Placement: the tag must sit on the example that proves the clause.
36
+ #
37
+ # A group tag looks like the tidier option — one line standing for four
38
+ # examples — and it is the one form that can go on lying. Delete the
39
+ # example the tag was really for, and its siblings keep the group green;
40
+ # `rspec --tag` still returns passing examples, and the clause still
41
+ # claims a proof that no longer exists. Per-example tags cost a repeated
42
+ # line and buy the loud break: the last one goes, and the clause fails as
43
+ # unproven.
44
+ #
45
+ # Longest-first alternation so `its` is not shadowed by `it`. The
46
+ # `[fx]` prefix catches `fit`, `xdescribe` and friends — a focused or
47
+ # skipped example is still an example for placement purposes; whether it
48
+ # should carry a tag at all is rubocop-rspec's argument to have.
49
+ #
50
+ # The one place an opener is recognised. `Proofs` reads examples with
51
+ # `example_opener?` rather than a regex of its own: two patterns one
52
+ # require apart would drift, and a shape only one of them accepted would
53
+ # count as a proof in one place and not exist in the other.
54
+ EXAMPLE_METHODS = %w[specify scenario example its it].freeze
55
+ GROUP_METHODS = %w[shared_examples_for shared_examples shared_context describe context feature].freeze
56
+ OPENER = /^[ \t]*(?:RSpec\.)?[fx]?(?<method>#{(EXAMPLE_METHODS + GROUP_METHODS).join('|')})[\s({]/
57
+
58
+ # True for `it`, `specify`, `scenario` and friends; false for the groups
59
+ # around them and for any other line.
60
+ def self.example_opener?(line)
61
+ match = OPENER.match(line.to_s)
62
+ !match.nil? && EXAMPLE_METHODS.include?(match[:method])
63
+ end
64
+
65
+ # How far back to look for the call a tag is metadata for. Almost always
66
+ # the tag's own line; a couple more covers metadata wrapped onto its own
67
+ # line under a long example name. Past that the scan gives up rather than
68
+ # guess — an unclassified tag is reported as nothing, not as an offence.
69
+ LOOKBACK = 3
70
+
71
+ # `group` is the group method a misplaced tag sits on, or nil for a tag on
72
+ # an example. Carried on the tag rather than left in the findings, so a
73
+ # consumer holding the tag can tell proof from phantom without matching
74
+ # findings back by line and column.
75
+ Tag = Struct.new(:capability, :clause_id, :path, :line, :column, :group, keyword_init: true) do
76
+ def to_s = "#{capability}##{clause_id}"
77
+
78
+ def misplaced? = !group.nil?
79
+ end
80
+
81
+ # Returns [ tags, findings ] — findings covering values that are not
82
+ # `<capability>#I<n>`, and tags sitting on a group rather than an example.
83
+ # An intent-tag lint cop, where the app has one, catches both at lint time.
84
+ #
85
+ # A misplaced tag is still returned as a tag: it names a real clause, and
86
+ # reporting it a second time as an untagged evaluation would describe one
87
+ # mistake twice.
88
+ def self.scan(dir, root:)
89
+ tags = []
90
+ findings = []
91
+ return [ tags, findings ] unless Dir.exist?(dir)
92
+
93
+ Dir.glob(File.join(dir, "**", "*_spec.rb")).sort.each do |path|
94
+ relative = path.delete_prefix("#{root}/")
95
+ lines = File.readlines(path, chomp: true, encoding: "UTF-8")
96
+
97
+ lines.each_with_index do |line, index|
98
+ line.to_enum(:scan, PATTERN).each do
99
+ match = Regexp.last_match
100
+ column = match.begin(0) + 1
101
+
102
+ values(match).each do |value|
103
+ tag = parse(value, relative, index + 1, column)
104
+ next findings << malformed(value, relative, index + 1, column) if tag.nil?
105
+
106
+ tag.group = enclosing_group(lines, index)
107
+ tags << tag
108
+ findings << misplaced(tag, column) if tag.misplaced?
109
+ end
110
+ end
111
+ end
112
+ end
113
+
114
+ [ tags, findings ]
115
+ end
116
+
117
+ # The group method this tag is metadata for, or nil when it sits on an
118
+ # example or on nothing this scan can name.
119
+ def self.enclosing_group(lines, index)
120
+ index.downto([ index - LOOKBACK, 0 ].max) do |candidate|
121
+ match = OPENER.match(lines[candidate])
122
+ next unless match
123
+
124
+ return GROUP_METHODS.include?(match[:method]) ? match[:method] : nil
125
+ end
126
+
127
+ nil
128
+ end
129
+
130
+ def self.values(match)
131
+ return match[:list].split if match[:list]
132
+ return match[:bracketed].scan(QUOTED).flatten if match[:bracketed]
133
+
134
+ [ match[:single] ]
135
+ end
136
+
137
+ def self.parse(value, path, line, column)
138
+ capability, clause_id = value.split("#", 2)
139
+ return nil unless clause_id && Capability::CLAUSE_ID.match?(clause_id) && !capability.to_s.empty?
140
+
141
+ Tag.new(capability: capability, clause_id: clause_id, path: path, line: line, column: column)
142
+ end
143
+
144
+ def self.malformed(value, path, line, column)
145
+ Finding.new(severity: :error, path: path, line: line, column: column,
146
+ message: "intent tag #{value.inspect} is not in `<capability>#I<n>` form",
147
+ code: "tag/malformed")
148
+ end
149
+
150
+ def self.misplaced(tag, column)
151
+ Finding.new(severity: :error, path: tag.path, line: tag.line, column: column,
152
+ message: "intent tag #{tag.to_s.inspect} is on `#{tag.group}` — tag the example that " \
153
+ "proves the clause, or the tag outlives the example it stood for",
154
+ code: "tag/misplaced")
155
+ end
156
+
157
+ private_class_method :values, :parse, :malformed, :misplaced, :enclosing_group
158
+ end
159
+ end
160
+ end
@@ -0,0 +1,152 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../agent_primitives"
4
+ require_relative "evals/finding"
5
+ require_relative "evals/capability"
6
+ require_relative "evals/tags"
7
+ require_relative "evals/proofs"
8
+
9
+ module AgentPrimitives
10
+ # Checks that every intent clause in docs/primitives/ is proven by a spec, and
11
+ # that every intent tag in the suite names a clause that exists.
12
+ #
13
+ # Deliberately narrow: clause ↔ evaluation, plus the `plan:` key an amending
14
+ # doc must carry, so a green run has one unambiguous meaning. Tree health — index sync, size tripwires, orphan
15
+ # docs, provenance style — stays with the maintaining-primitives skill, where
16
+ # it needs judgment rather than a parser.
17
+ module Evals
18
+ DEFAULT_PRIMITIVES_DIR = "docs/primitives"
19
+ DEFAULT_SPECS_DIR = "spec"
20
+ CAPABILITIES_SUBDIR = "capabilities"
21
+
22
+ Result = Struct.new(:findings, :capabilities, :clauses, keyword_init: true) do
23
+ def errors = findings.select(&:error?)
24
+ def ok? = errors.empty?
25
+ end
26
+
27
+ class << self
28
+ def run(root:, primitives_dir: DEFAULT_PRIMITIVES_DIR, specs_dir: DEFAULT_SPECS_DIR)
29
+ capabilities_dir = File.join(root, primitives_dir, CAPABILITIES_SUBDIR)
30
+ raise Error, "no capability docs at #{primitives_dir}/#{CAPABILITIES_SUBDIR}/" unless Dir.exist?(capabilities_dir)
31
+
32
+ capabilities = Capability.load_all(capabilities_dir, root: root)
33
+ tags, findings = Tags.scan(File.join(root, specs_dir), root: root)
34
+
35
+ findings += nested_docs(capabilities_dir, root: root)
36
+ findings += capabilities.flat_map(&:findings)
37
+ findings += check_evaluations(capabilities, tags, root: root)
38
+ findings += check_tags(capabilities, tags)
39
+
40
+ Result.new(findings: sort(findings), capabilities: capabilities.size,
41
+ clauses: capabilities.sum { |c| c.clauses.size })
42
+ end
43
+
44
+ private
45
+
46
+ # A capability doc in a subdirectory is invisible to `Capability.load_all`,
47
+ # which globs one level deep — and an `intent:` tag names a bare filename
48
+ # with no path in it, so nesting could not be addressed even if it were
49
+ # loaded. Reported rather than swept up: the failure it replaces is a doc
50
+ # whose clauses simply do not exist as far as this tool is concerned, with
51
+ # a green run over the top.
52
+ def nested_docs(dir, root:)
53
+ Dir.glob(File.join(dir, "**", "*.md")).sort
54
+ .reject { |path| File.dirname(path) == dir }
55
+ .map do |path|
56
+ Finding.new(severity: :error, path: path.delete_prefix("#{root}/"), line: 1, column: 1,
57
+ message: "capability docs live directly in #{CAPABILITIES_SUBDIR}/ — group with a " "name prefix instead (billing/plans.md becomes billing_plans.md), " "because an `intent:` tag names a filename with no path in it",
58
+ code: "doc/nested")
59
+ end
60
+ end
61
+
62
+ # Doc → suite: does each clause name a spec, and does that spec carry the
63
+ # tag it claims?
64
+ def check_evaluations(capabilities, tags, root:)
65
+ tagged = tags.group_by { |tag| [ tag.capability, tag.clause_id ] }
66
+
67
+ capabilities.flat_map do |capability|
68
+ capability.active_clauses.flat_map do |clause|
69
+ coverage(capability, clause) +
70
+ declared_paths(capability, clause, tagged, root: root)
71
+ end
72
+ end
73
+ end
74
+
75
+ # Every active clause on a built doc names a spec. An amending doc still
76
+ # owes the rows it has, and `declared_paths` checks those like any other.
77
+ # Its new clauses get rows at close-out, so a missing one is a warning,
78
+ # not a failure.
79
+ def coverage(capability, clause)
80
+ return [] unless clause.evaluations.empty?
81
+
82
+ if capability.built?
83
+ [ finding(:error, capability, clause,
84
+ "#{clause.id} has no evaluation — a built clause must name the spec that proves it", "clause/unproven") ]
85
+ elsif capability.amending?
86
+ [ finding(:warning, capability, clause,
87
+ "#{clause.id} has no evaluation yet; this doc is amending, and close-out files it", "clause/in-flight") ]
88
+ else
89
+ []
90
+ end
91
+ end
92
+
93
+ def declared_paths(capability, clause, tagged, root:)
94
+ carriers = (tagged[[ capability.name, clause.id ]] || []).map(&:path)
95
+
96
+ clause.evaluations.flat_map do |relative|
97
+ if !File.exist?(File.join(root, relative))
98
+ [ finding(:error, capability, clause, "#{clause.id} names #{relative}, which does not exist", "evaluation/missing-file") ]
99
+ elsif !carriers.include?(relative)
100
+ [ finding(:error, capability, clause,
101
+ "#{relative} carries no `intent: \"#{capability.name}##{clause.id}\"` tag", "evaluation/untagged") ]
102
+ else
103
+ []
104
+ end
105
+ end
106
+ end
107
+
108
+ # Suite → doc: does each tag name a clause that exists, is still active,
109
+ # and lists this spec file?
110
+ def check_tags(capabilities, tags)
111
+ by_name = capabilities.to_h { |capability| [ capability.name, capability ] }
112
+
113
+ tags.filter_map do |tag|
114
+ capability = by_name[tag.capability]
115
+ next unresolved(tag, "no capability doc is named #{tag.capability}.md") if capability.nil?
116
+
117
+ clause = capability.clause(tag.clause_id)
118
+ next unresolved(tag, "#{capability.name} defines no #{tag.clause_id}") if clause.nil?
119
+ next unresolved(tag, "#{tag} is superseded or retired — retag or remove this example") unless clause.active?
120
+ next if clause.evaluations.include?(tag.path)
121
+ next in_flight_tag(tag) if capability.in_flight? && clause.evaluations.empty?
122
+
123
+ Finding.new(severity: :error, path: tag.path, line: tag.line, column: tag.column,
124
+ message: "#{tag} is not listed in that clause's `evaluations:`", code: "tag/undeclared")
125
+ end
126
+ end
127
+
128
+ # A plan tags its specs task by task and files the rows at close-out, so a
129
+ # tag on a clause with no row yet is the plan running, not drift. A clause
130
+ # that already has rows keeps the error: a new carrier for a proven clause
131
+ # is a row to add now.
132
+ def in_flight_tag(tag)
133
+ Finding.new(severity: :warning, path: tag.path, line: tag.line, column: tag.column,
134
+ message: "#{tag} has no `evaluations:` row yet; close-out files it", code: "tag/in-flight")
135
+ end
136
+
137
+ def unresolved(tag, message)
138
+ Finding.new(severity: :error, path: tag.path, line: tag.line, column: tag.column,
139
+ message: "intent tag #{tag.to_s.inspect}: #{message}", code: "tag/unresolved")
140
+ end
141
+
142
+ def finding(severity, capability, clause, message, code)
143
+ Finding.new(severity: severity, path: capability.relative_path, line: clause.line, column: 1,
144
+ message: message, code: code)
145
+ end
146
+
147
+ def sort(findings)
148
+ findings.sort_by { |f| [ f.path, f.line, f.column, f.code ] }
149
+ end
150
+ end
151
+ end
152
+ end
@@ -0,0 +1,71 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "open3"
4
+ require "tmpdir"
5
+
6
+ module AgentPrimitives
7
+ module Guard
8
+ # The "before" side of the comparison: the primitives tree and the spec suite
9
+ # as they stood at a base revision, extracted into a temp directory.
10
+ #
11
+ # Materialised as files rather than read as blobs so the *same* parsers read
12
+ # both sides — `Evals::Capability` and `Evals::Tags` take a directory, and a
13
+ # second blob-reading path for the base would be a second thing to keep in
14
+ # step with the format.
15
+ module Baseline
16
+ # Every git call goes through here: no shell, so a branch name with a
17
+ # space or a `;` in it is an argument rather than a command.
18
+ def self.git(root, *args)
19
+ out, err, status = Open3.capture3("git", "-C", root, *args)
20
+ [ status.success?, out, err ]
21
+ end
22
+
23
+ # Yields [ directory, resolved ref ]. The directory holds only the paths
24
+ # that existed at that revision, so a capability tree added on this branch
25
+ # yields an empty baseline rather than an error — everything in it is new,
26
+ # which is the one shape that never produces a notice.
27
+ def self.capture(root:, base:, paths:)
28
+ ref = resolve(root, base)
29
+
30
+ Dir.mktmpdir("agent-primitives-guard") do |dir|
31
+ present = paths.select { |path| tracked?(root, ref, path) }
32
+ extract(root, ref, present, dir) unless present.empty?
33
+ yield dir, ref
34
+ end
35
+ end
36
+
37
+ # The comparison point for `--base main` is where this work started, not
38
+ # where main has since got to: a commit someone else pushed to main is not
39
+ # this agent's change. Falls back to the ref itself when there is no
40
+ # common ancestor to find.
41
+ def self.resolve(root, base)
42
+ raise Error, "not a git repository: #{root}" unless git(root, "rev-parse", "--git-dir").first
43
+
44
+ ok, sha = git(root, "rev-parse", "--verify", "--quiet", "#{base}^{commit}")
45
+ raise Error, "cannot resolve #{base.inspect} to a commit — pass an existing ref with --base" unless ok
46
+
47
+ merged, ancestor = git(root, "merge-base", sha.strip, "HEAD")
48
+ merged ? ancestor.strip : sha.strip
49
+ end
50
+
51
+ def self.tracked?(root, ref, path)
52
+ ok, out = git(root, "ls-tree", "--name-only", ref, "--", path)
53
+ ok && !out.strip.empty?
54
+ end
55
+
56
+ # `git archive` streamed straight into tar: no intermediate archive on
57
+ # disk, and no second checkout of the working tree.
58
+ def self.extract(root, ref, paths, dir)
59
+ statuses = Open3.pipeline(
60
+ [ "git", "-C", root, "archive", "--format=tar", ref, "--", *paths ],
61
+ [ "tar", "-x", "-C", dir ]
62
+ )
63
+ return if statuses.all?(&:success?)
64
+
65
+ raise Error, "could not read #{paths.join(', ')} at #{ref[0, 12]}"
66
+ end
67
+
68
+ private_class_method :git, :tracked?, :extract
69
+ end
70
+ end
71
+ end