nukadoko 0.1.0 → 0.3.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.
Files changed (159) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +417 -0
  3. data/README.ja.md +62 -7
  4. data/README.md +19 -5
  5. data/exe/nuka +8 -0
  6. data/lib/nukadoko/aria_snapshot.rb +1008 -0
  7. data/lib/nukadoko/aria_tree.rb +150 -0
  8. data/lib/nukadoko/base.rb +294 -0
  9. data/lib/nukadoko/check.rb +669 -22
  10. data/lib/nukadoko/claim_check.rb +177 -0
  11. data/lib/nukadoko/claim_check_run.rb +293 -0
  12. data/lib/nukadoko/claim_line.rb +381 -0
  13. data/lib/nukadoko/claim_rules.rb +519 -0
  14. data/lib/nukadoko/claim_sides.rb +469 -0
  15. data/lib/nukadoko/claims.rb +576 -37
  16. data/lib/nukadoko/cli.rb +814 -22
  17. data/lib/nukadoko/codes.json +947 -0
  18. data/lib/nukadoko/codes.rb +19 -0
  19. data/lib/nukadoko/command.rb +214 -12
  20. data/lib/nukadoko/criteria.rb +172 -0
  21. data/lib/nukadoko/definition.rb +33 -41
  22. data/lib/nukadoko/env_check.rb +88 -0
  23. data/lib/nukadoko/features.rb +80 -10
  24. data/lib/nukadoko/fixtures.rb +329 -11
  25. data/lib/nukadoko/http_recording.rb +68 -0
  26. data/lib/nukadoko/init.rb +129 -0
  27. data/lib/nukadoko/js_json.rb +274 -0
  28. data/lib/nukadoko/js_pattern.rb +531 -0
  29. data/lib/nukadoko/judge.rb +221 -0
  30. data/lib/nukadoko/judgment_file.rb +78 -0
  31. data/lib/nukadoko/judgments.rb +256 -0
  32. data/lib/nukadoko/literal.rb +129 -0
  33. data/lib/nukadoko/measured.rb +105 -0
  34. data/lib/nukadoko/order.rb +84 -0
  35. data/lib/nukadoko/parts.rb +43 -22
  36. data/lib/nukadoko/pattern.rb +73 -3
  37. data/lib/nukadoko/poll.rb +21 -8
  38. data/lib/nukadoko/program.rb +105 -17
  39. data/lib/nukadoko/project_files.rb +17 -0
  40. data/lib/nukadoko/project_fixtures.rb +17 -2
  41. data/lib/nukadoko/project_program.rb +119 -0
  42. data/lib/nukadoko/report_allure.rb +751 -0
  43. data/lib/nukadoko/report_messages.rb +167 -0
  44. data/lib/nukadoko/report_run.rb +169 -0
  45. data/lib/nukadoko/run.rb +898 -91
  46. data/lib/nukadoko/run_record.rb +535 -0
  47. data/lib/nukadoko/scaffold.rb +1015 -0
  48. data/lib/nukadoko/schema.rb +120 -21
  49. data/lib/nukadoko/secrets.rb +375 -0
  50. data/lib/nukadoko/selection.rb +163 -0
  51. data/lib/nukadoko/signature.rb +4 -1
  52. data/lib/nukadoko/skill.rb +36 -0
  53. data/lib/nukadoko/spaces.rb +28 -0
  54. data/lib/nukadoko/step.rb +68 -21
  55. data/lib/nukadoko/summary.rb +662 -0
  56. data/lib/nukadoko/table.rb +34 -2
  57. data/lib/nukadoko/text_fit.rb +179 -0
  58. data/lib/nukadoko/trace.rb +244 -0
  59. data/lib/nukadoko/trace_actions.rb +116 -0
  60. data/lib/nukadoko/tree_passes.rb +122 -0
  61. data/lib/nukadoko/verdict.rb +128 -0
  62. data/lib/nukadoko/version.rb +2 -1
  63. data/lib/nukadoko/vocabulary.rb +6 -0
  64. data/lib/nukadoko/walk.rb +305 -0
  65. data/lib/nukadoko/walk_files.rb +473 -0
  66. data/lib/nukadoko/walk_step.rb +149 -0
  67. data/lib/nukadoko.rb +60 -2
  68. data/llms.txt +297 -0
  69. data/sig/generated/nukadoko/aria_snapshot.rbs +331 -0
  70. data/sig/generated/nukadoko/aria_tree.rbs +142 -0
  71. data/sig/generated/nukadoko/base.rbs +142 -0
  72. data/sig/generated/nukadoko/check.rbs +255 -0
  73. data/sig/generated/nukadoko/claim_check.rbs +118 -0
  74. data/sig/generated/nukadoko/claim_check_run.rbs +88 -0
  75. data/sig/generated/nukadoko/claim_line.rbs +158 -0
  76. data/sig/generated/nukadoko/claim_rules.rbs +172 -0
  77. data/sig/generated/nukadoko/claim_sides.rbs +207 -0
  78. data/sig/generated/nukadoko/claims.rbs +208 -0
  79. data/sig/generated/nukadoko/cli.rbs +182 -0
  80. data/sig/generated/nukadoko/codes.rbs +16 -0
  81. data/sig/generated/nukadoko/command.rbs +109 -0
  82. data/sig/generated/nukadoko/criteria.rbs +83 -0
  83. data/sig/generated/nukadoko/definition.rbs +30 -0
  84. data/sig/generated/nukadoko/env_check.rbs +34 -0
  85. data/sig/generated/nukadoko/features.rbs +101 -0
  86. data/sig/generated/nukadoko/fixtures.rbs +175 -0
  87. data/sig/generated/nukadoko/http_recording.rbs +29 -0
  88. data/sig/generated/nukadoko/init.rbs +64 -0
  89. data/sig/generated/nukadoko/js_json.rbs +109 -0
  90. data/sig/generated/nukadoko/js_pattern.rbs +194 -0
  91. data/sig/generated/nukadoko/judge.rbs +64 -0
  92. data/sig/generated/nukadoko/judgment_file.rbs +39 -0
  93. data/sig/generated/nukadoko/judgments.rbs +120 -0
  94. data/sig/generated/nukadoko/literal.rbs +71 -0
  95. data/sig/generated/nukadoko/measured.rbs +42 -0
  96. data/sig/generated/nukadoko/order.rbs +54 -0
  97. data/sig/generated/nukadoko/parts.rbs +35 -0
  98. data/sig/generated/nukadoko/pattern.rbs +62 -0
  99. data/sig/generated/nukadoko/poll.rbs +41 -0
  100. data/sig/generated/nukadoko/program.rbs +101 -0
  101. data/sig/generated/nukadoko/project_files.rbs +19 -0
  102. data/sig/generated/nukadoko/project_fixtures.rbs +57 -0
  103. data/sig/generated/nukadoko/project_program.rbs +55 -0
  104. data/sig/generated/nukadoko/report_allure.rbs +268 -0
  105. data/sig/generated/nukadoko/report_messages.rbs +68 -0
  106. data/sig/generated/nukadoko/report_run.rbs +102 -0
  107. data/sig/generated/nukadoko/run.rbs +264 -0
  108. data/sig/generated/nukadoko/run_record.rbs +175 -0
  109. data/sig/generated/nukadoko/scaffold.rbs +328 -0
  110. data/sig/generated/nukadoko/schema.rbs +155 -0
  111. data/sig/generated/nukadoko/secrets.rbs +172 -0
  112. data/sig/generated/nukadoko/selection.rbs +73 -0
  113. data/sig/generated/nukadoko/signature.rbs +17 -0
  114. data/sig/generated/nukadoko/skill.rbs +20 -0
  115. data/sig/generated/nukadoko/spaces.rbs +31 -0
  116. data/sig/generated/nukadoko/step.rbs +115 -0
  117. data/sig/generated/nukadoko/summary.rbs +204 -0
  118. data/sig/generated/nukadoko/table.rbs +43 -0
  119. data/sig/generated/nukadoko/text_fit.rbs +70 -0
  120. data/sig/generated/nukadoko/trace.rbs +127 -0
  121. data/sig/generated/nukadoko/trace_actions.rbs +40 -0
  122. data/sig/generated/nukadoko/tree_passes.rbs +48 -0
  123. data/sig/generated/nukadoko/verdict.rbs +56 -0
  124. data/sig/generated/nukadoko/version.rbs +5 -0
  125. data/sig/generated/nukadoko/vocabulary.rbs +25 -0
  126. data/sig/generated/nukadoko/walk.rbs +139 -0
  127. data/sig/generated/nukadoko/walk_files.rbs +189 -0
  128. data/sig/generated/nukadoko/walk_step.rbs +50 -0
  129. data/sig/generated/nukadoko.rbs +26 -0
  130. data/sig/nukadoko.rbs +5 -48
  131. data/skills/nukadoko/SKILL.md +120 -0
  132. data/skills/nukadoko/references/checking-steps.md +200 -0
  133. data/skills/nukadoko/references/diagnosing.md +200 -0
  134. data/skills/nukadoko/references/done.md +99 -0
  135. data/skills/nukadoko/references/evidence.md +124 -0
  136. data/skills/nukadoko/references/examples/cli.md +230 -0
  137. data/skills/nukadoko/references/examples/http-api.md +342 -0
  138. data/skills/nukadoko/references/examples/workflow.md +173 -0
  139. data/skills/nukadoko/references/exploring.md +184 -0
  140. data/skills/nukadoko/references/fixtures.md +198 -0
  141. data/skills/nukadoko/references/from-prose.md +51 -0
  142. data/skills/nukadoko/references/judgments.md +95 -0
  143. data/skills/nukadoko/references/maintenance.md +97 -0
  144. data/skills/nukadoko/references/merge-risk.md +74 -0
  145. data/skills/nukadoko/references/parts.md +152 -0
  146. data/skills/nukadoko/references/perturbed-worlds.md +109 -0
  147. data/skills/nukadoko/references/program.md +200 -0
  148. data/skills/nukadoko/references/reviewing.md +200 -0
  149. data/skills/nukadoko/references/running.md +200 -0
  150. data/skills/nukadoko/references/scenario-rules.md +188 -0
  151. data/skills/nukadoko/references/states.md +66 -0
  152. data/skills/nukadoko/references/step-files.md +200 -0
  153. data/skills/nukadoko/references/verdicts.md +200 -0
  154. data/skills/nukadoko/references/writing-steps.md +200 -0
  155. data/skills/nukadoko/references/writing-the-feature.md +165 -0
  156. data/skills/nukadoko/scripts/claude-code-verdict-hook.mjs +99 -0
  157. data/skills/nukadoko/scripts/merge-risk.jq +56 -0
  158. data/skills/nukadoko-verification/SKILL.md +263 -0
  159. metadata +133 -1
@@ -0,0 +1,535 @@
1
+ # frozen_string_literal: true
2
+ # rbs_inline: enabled
3
+
4
+ require "open3"
5
+ require "tmpdir"
6
+
7
+ # The shapes a run writes, in the TypeScript engine's run.json format: a
8
+ # claim as the step judged it with where each side came from, a row's
9
+ # verdict and the sentence that says why, the counts, and the commit the
10
+ # run judged. One reader reads a run from either engine; a field this
11
+ # engine cannot fill is null rather than missing.
12
+ module Nukadoko
13
+ module Engine
14
+ module RunRecord
15
+ SCHEMA_VERSION = 4
16
+
17
+ module_function
18
+
19
+ # A step's record.json as `nuka run` writes it, in the TypeScript engine's
20
+ # shape, from what the run kept of the step. The keywords name where it ran:
21
+ # the environment, the world, the run, the scenario, and the step's own
22
+ # directory. A record that passed names each step it used; a failed one
23
+ # names what each gave too, since that is what it failed on.
24
+ #: (Hash[Symbol, untyped], environment: String, world_name: String?, run_id: String?, scenario_record_id: String?, evidence_dir: String) -> Hash[Symbol, untyped]
25
+ def step_file(record, environment:, world_name:, run_id:, scenario_record_id:, evidence_dir:)
26
+ passed = record[:status] == "passed"
27
+ outcome = if passed then { result: record[:result] || {}, returns_dropped: record[:returns_dropped] }.compact
28
+ else { error: { message: record[:error], kind: record[:error_kind] } }
29
+ end
30
+ processes = record[:processes]
31
+ used = (record[:used] || []).map do |entry|
32
+ { step_record_id: File.basename(entry[:record]), step: entry[:step], **(passed ? {} : { result: entry[:result] }) }
33
+ end
34
+ { schema_version: SCHEMA_VERSION, nukadoko: VERSION, step_record_id: record[:step_record_id], step: record[:step], kind: "run",
35
+ args: record[:args] || {}, **(record[:args_origin]&.any? ? { args_origin: record[:args_origin] } : {}),
36
+ **outcome, status: record[:status], environment: environment, world_name: world_name,
37
+ scenario_record_id: scenario_record_id, run_id: run_id, started_at: record[:started_at], finished_at: record[:finished_at],
38
+ evidence: { dir: evidence_dir, screenshots: [], **(record[:scratch] ? { scratch: record[:scratch] } : {}),
39
+ **(record[:http_file] ? { http: "http.jsonl" } : {}), **(record[:trace] ? { trace: record[:trace] } : {}) },
40
+ observed: { processes: processes&.any? ? processes : nil, http: record[:http_count].to_i.positive? ? record[:http_count] : nil,
41
+ files: record[:files], unmeasured: [], **(record.key?(:program_log) ? { program_log: record[:program_log] } : {}) },
42
+ mutates: record[:mutates], **(used.any? ? { used: used } : {}), **(record[:calls] ? { calls: record[:calls] } : {}),
43
+ **(record[:actions] ? { actions: record[:actions] } : {}), **(record[:actions_truncated] ? { truncated: { actions: record[:actions_truncated] } } : {}),
44
+ **(record[:fixtures] ? { fixtures: record[:fixtures] } : {}),
45
+ **(record[:claim_records] ? { claims: record[:claim_records], observation: record[:observation] || "observed", **poll_fields(record), **page_fields(record) } : {}) }
46
+ end
47
+
48
+ # One comparison, as run.json's steps[].claims[] holds it. `origins`
49
+ # maps an args key to the label of where its value came from, and
50
+ # `texts` to the text the sentence stated it as.
51
+ #: (Hash[Symbol, untyped], Hash[Symbol, untyped], Hash[String, String], Hash[String, String?], observed: bool, ?patterns: Array[String]) -> Hash[Symbol, untyped]
52
+ def claim(declared, judged, origins, texts, observed:, patterns: [])
53
+ actual_key = declared[:actual].to_s
54
+ base = if observed then "observe:#{actual_key}"
55
+ else origins.fetch(actual_key, "sentence:#{actual_key}")
56
+ end
57
+ actual_from = counted(place(base, declared[:view], declared[:at]), declared[:count])
58
+ actual_from = "ARIA snapshot of #{base}" if declared[:compare] == "fits-aria-snapshot"
59
+ actual_from = "ARIA snapshot of observe:#{Claims.judged_path(declared)}" if judged[:aria]
60
+ expected_from, expected_text = expected_origin(declared, origins, texts, patterns)
61
+ { **judged.slice(:actual), actual_from: actual_from, **{ view: declared[:view], at: declared[:at]&.to_s, count: declared[:count] }.compact,
62
+ compare: declared[:compare], **judged.slice(:expected), expected_from: expected_from,
63
+ **{ expected_view: declared[:expected_view] }.compact }.merge(expected_text: expected_text, **outcome(judged), measured: nil)
64
+ end
65
+
66
+ READING_MAX_BYTES = 1024
67
+
68
+ # What a claim step's page had received by its judged reading, and
69
+ # what the page showed right after it. A file is named from the step
70
+ # record's directory, or from the run's when `under` names the step's.
71
+ #: (Hash[Symbol, untyped], ?String?) -> Hash[Symbol, untyped]
72
+ def page_fields(record, under = nil)
73
+ view = record[:page_view] or return {}
74
+ return view unless under && view[:judged_view]
75
+
76
+ pages = view[:judged_view][:pages].map do |page|
77
+ page.merge(%i[screenshot aria].to_h { |key| [key, page[key] && page[key].merge(file: File.join(under, page[key][:file]))] })
78
+ end
79
+ view.merge(judged_view: view[:judged_view].merge(pages: pages))
80
+ end
81
+
82
+ # How many times a claim step read, and for a polled one each reading
83
+ # and the settled conditions, with the reading the poll stopped on
84
+ # when two settled.
85
+ #: (Hash[Symbol, untyped]) -> Hash[Symbol, untyped]
86
+ def poll_fields(record)
87
+ poll = record[:poll] or return { attempts: 1 }
88
+
89
+ readings = record[:readings].map do |reading|
90
+ { attempt: reading[:attempt], at: reading[:at], held: reading[:holds],
91
+ **(reading[:error] ? { error: reading[:error] } : { actuals: reading[:actuals].map { reading_value(_1) } }),
92
+ **(reading.key?(:settled) ? { settled: reading[:settled] } : {}) }
93
+ end
94
+ settled = if poll[:conditions].any?
95
+ last = readings.last
96
+ stop = poll[:stop] == "settled" ? { stop: { reading: last[:attempt], actuals: last[:actuals] } } : {}
97
+ { settled: { conditions: poll[:conditions], **stop } }
98
+ else {}
99
+ end
100
+ { attempts: [readings.size, 1].max, readings: readings, **settled }
101
+ end
102
+
103
+ #: (untyped) -> Hash[Symbol, untyped]
104
+ def reading_value(value)
105
+ text = JSON.generate(value)
106
+ text.bytesize <= READING_MAX_BYTES ? { value: value } : { json_start: text.byteslice(0, READING_MAX_BYTES).to_s.scrub(""), json_bytes: text.bytesize }
107
+ end
108
+
109
+ # Why a poll whose claim broke stopped, on the failure's first line,
110
+ # so a reading that settled is never mistaken for the timeout passing.
111
+ #: (singleton(Step), Hash[Symbol, untyped]) -> String
112
+ def poll_end(step, record)
113
+ poll = record[:poll]
114
+ return "" if poll.nil? || poll[:conditions].empty? || poll[:stop] == "held"
115
+
116
+ conditions = poll[:conditions].join(" and ")
117
+ attempts = record[:readings].size
118
+ if poll[:stop] == "settled"
119
+ "; the poll stopped on reading #{attempts}, before its #{step.poll[:timeout_ms]} ms timeout, since readings #{attempts - 1} and #{attempts} settled (#{conditions})"
120
+ else
121
+ "; the poll read until its #{step.poll[:timeout_ms]} ms timeout, and no two consecutive readings settled (#{conditions})"
122
+ end
123
+ end
124
+
125
+ # A declared claim or settled condition as one line, as `nuka
126
+ # describe` writes it: `status not-equal "running"`.
127
+ #: (Hash[Symbol, untyped]) -> String
128
+ def describe_comparison(claim)
129
+ expected = case claim[:expected]
130
+ in String => key then key
131
+ in { from: key } then "from #{key}"
132
+ in { observe: key } then "observe #{key}"
133
+ in { literal: value } then JSON.generate(value)
134
+ end
135
+ "#{"count of " if claim[:count]}#{claim[:actual]}#{" as #{claim[:view]}" if claim[:view]}#{" at #{claim[:at]}" if claim[:at]} " \
136
+ "#{claim[:compare]} #{expected}#{" as #{claim[:expected_view]}" if claim[:expected_view]}"
137
+ end
138
+
139
+ EACH_RESULTS_CAP = 20
140
+ IDENTITY_FIELDS = %w[id name key].freeze
141
+
142
+ # A claim on each item of a list, as run.json holds it: each `where`
143
+ # and item claim as declared, how many items the list held and how
144
+ # many `where` selected, and the judged items, the broken first, at
145
+ # most 20, in index order.
146
+ #: (Hash[Symbol, untyped], Engine::ClaimSides::Inputs, Hash[String, String], Hash[String, String?], ?patterns: Array[String]) -> Hash[Symbol, untyped]
147
+ def each_claim(declared, inputs, origins, texts, patterns: [])
148
+ sides = Engine::ClaimSides
149
+ args = inputs.args
150
+ observed = inputs.observed
151
+ each = declared[:each]
152
+ where = each[:where] || []
153
+ declarations = { **(where.empty? ? {} : { where: where.map { item_declaration(_1, args, origins, texts, patterns, observed) } }),
154
+ claims: each[:claims].map { item_declaration(_1, args, origins, texts, patterns, observed) } }
155
+ array = sides.array_side(declared, inputs)
156
+ base = { actual_from: array.place.label, view: declared[:view], at: declared[:at]&.to_s }.compact
157
+ value = array.found[:value]
158
+ count = value.is_a?(Array) ? value.size : 0
159
+ ended = lambda do |reason, results = [], outcome = "broken"|
160
+ base.merge(each: { **declarations, items: count, selected: 0, results: results }, outcome: outcome, reason: reason, measured: nil)
161
+ end
162
+ stop = array.found.slice(:broken, :unjudged).then { _1.empty? ? nil : _1 } || sides.each_stop(declared, array.place, inputs)
163
+ return ended.(stop[:broken] || stop[:unjudged], [], stop[:unjudged] ? "unjudged" : "broken") if stop
164
+ return ended.("each reads an array, and the value is #{article(json_type(value))}") unless value.is_a?(Array)
165
+ return ended.("the array is empty, and a claim on every item of nothing measures nothing") if value.empty?
166
+
167
+ judged = []
168
+ value.each_with_index do |item, index|
169
+ place = sides.place_at(array.place, index.to_s)
170
+ compare = ->(entry) { item_comparison(entry, sides.item_side(item, place, entry), inputs, origins, texts, patterns) }
171
+ where_records = where.map(&compare)
172
+ # A where claim that could not compare says nothing about whether
173
+ # the item belongs, so leaving it out would turn "every item" into
174
+ # "the items that happen to compare".
175
+ if (unjudgeable = where_records.find { _1[:reason] })
176
+ outcome = unjudgeable[:outcome] == "unjudged" ? "unjudged" : "broken"
177
+ return ended.("where could not #{outcome == "unjudged" ? "judge" : "compare"} item #{index}: #{unjudgeable[:reason]}",
178
+ [{ index: index, selected: false, where: where_records }], outcome)
179
+ end
180
+ next judged << { index: index, selected: false, where: where_records } unless where_records.all? { _1[:outcome] == "held" }
181
+
182
+ claims = each[:claims].map(&compare)
183
+ outcome = claims.any? { _1[:outcome] == "broken" } ? "broken" : claims.any? { _1[:outcome] == "unjudged" } ? "unjudged" : "held"
184
+ identity = outcome == "broken" && item.is_a?(Hash) && IDENTITY_FIELDS.lazy.filter_map do |field|
185
+ v = item.transform_keys(&:to_s)[field]
186
+ { field: field, value: v } if v.is_a?(String) || (v.is_a?(Numeric) && v.finite?)
187
+ end.first
188
+ judged << { index: index, selected: true, **(where_records.empty? ? {} : { where: where_records }), outcome: outcome, claims: claims,
189
+ **(identity ? { identity: identity } : {}) }
190
+ end
191
+ selected = judged.count { _1[:selected] }
192
+ rank = ->(entry) { !entry[:selected] ? 2 : { "broken" => 0, "unjudged" => 1 }.fetch(entry[:outcome], 3) }
193
+ kept = judged.sort_by { [rank.(_1), _1[:index]] }.first(EACH_RESULTS_CAP).sort_by { _1[:index] }
194
+ truncated = judged.size > kept.size ? { results_truncated: judged.size } : {}
195
+ record = base.merge(each: { **declarations, items: value.size, selected: selected, results: kept, **truncated })
196
+ if selected.zero?
197
+ return record.merge(outcome: "broken", reason: "where selected none of the #{value.size} items, and a claim on none of them measures nothing", measured: nil)
198
+ end
199
+
200
+ outcomes = judged.select { _1[:selected] }.map { _1[:outcome] }
201
+ record.merge(outcome: outcomes.include?("broken") ? "broken" : outcomes.include?("unjudged") ? "unjudged" : "held", measured: nil)
202
+ end
203
+
204
+ #: (Hash[Symbol, untyped], untyped, Hash[String, String], Hash[String, String?], Array[String], untyped) -> Hash[Symbol, untyped]
205
+ def item_declaration(entry, args, origins, texts, patterns, observed)
206
+ expected_from, expected_text = expected_origin(entry, origins, texts, patterns)
207
+ expected = begin
208
+ { expected: Claims.expected_value(entry, args, observed) }
209
+ rescue StandardError
210
+ {}
211
+ end
212
+ { actual: entry[:actual]&.to_s, view: entry[:view], at: entry[:at]&.to_s, count: entry[:count] }.compact
213
+ .merge(compare: entry[:compare], **expected, expected_from: expected_from, **(entry[:expected_view] ? { expected_view: entry[:expected_view] } : {}),
214
+ expected_text: expected_text)
215
+ end
216
+
217
+ # One where or item claim on one item, judged on the side the item gives.
218
+ #: (Hash[Symbol, untyped], Engine::ClaimSides::Side, Engine::ClaimSides::Inputs, Hash[String, String], Hash[String, String?], Array[String]) -> Hash[Symbol, untyped]
219
+ def item_comparison(entry, side, inputs, origins, texts, patterns)
220
+ sides = Engine::ClaimSides
221
+ judged = sides.judge_comparison(entry, side, inputs)
222
+ label = sides.place_counted(sides.place_at(sides.place_viewed(side.place, entry[:view]), entry[:at]&.to_s), entry[:count]).label
223
+ expected_from, expected_text = expected_origin(entry, origins, texts, patterns)
224
+ { **judged.slice(:actual), actual_from: label, **{ view: entry[:view], at: entry[:at]&.to_s, count: entry[:count] }.compact }
225
+ .merge(compare: entry[:compare], **judged.slice(:expected), expected_from: expected_from,
226
+ **(entry[:expected_view] ? { expected_view: entry[:expected_view] } : {}), expected_text: expected_text,
227
+ **outcome(judged))
228
+ end
229
+
230
+ # The claims of a scenario's step records, counted by outcome, in the
231
+ # fields run.json gives them.
232
+ #: (Array[Hash[Symbol, untyped]]) -> Hash[Symbol, Integer]
233
+ def claim_counts(records)
234
+ outcomes = records.flat_map { _1[:claim_records] || [] }.map { _1[:outcome] }
235
+ counts = { held: outcomes.count("held"), broken: outcomes.count("broken") } #: Hash[Symbol, Integer]
236
+ { unobserved: "unobserved", unjudged: "unjudged", for_judgment: "for-judgment" }.each do |key, outcome|
237
+ counts[key] = outcomes.count(outcome) if outcomes.include?(outcome)
238
+ end
239
+ counts
240
+ end
241
+
242
+ # A claim's outcome and, when the two sides could not be compared or
243
+ # nothing judged them, why.
244
+ #: (Hash[Symbol, untyped]) -> Hash[Symbol, untyped]
245
+ def outcome(judged)
246
+ return { outcome: "for-judgment" } if judged[:for_judgment]
247
+ return { outcome: "held" } if judged[:holds]
248
+
249
+ { outcome: judged[:unjudged] ? "unjudged" : "broken", **(judged[:reason] ? { reason: judged[:reason] } : {}) }
250
+ end
251
+
252
+ #: (untyped) -> String
253
+ def json_type(value)
254
+ case value
255
+ when nil then "null"
256
+ when true, false then "boolean"
257
+ when Numeric then "number"
258
+ when String then "string"
259
+ when Array then "array"
260
+ else "object"
261
+ end
262
+ end
263
+
264
+ #: (String) -> String
265
+ def article(type) = %w[array object].include?(type) ? "an #{type}" : "a #{type}"
266
+
267
+ # A claim whose observe raised: where each side would come from, and no value.
268
+ #: (Hash[Symbol, untyped], Hash[String, String], Hash[String, String?], ?patterns: Array[String]) -> Hash[Symbol, untyped]
269
+ def unobserved_claim(declared, origins, texts, patterns: [])
270
+ expected_from, expected_text = expected_origin(declared, origins, texts, patterns)
271
+ { actual_from: declared[:compare] == "fits-aria-snapshot" ? "ARIA snapshot of observe:#{declared[:actual]}" : place("observe:#{declared[:actual]}", declared[:view], declared[:at]), view: declared[:view], at: declared[:at]&.to_s,
272
+ count: declared[:count], compare: declared[:compare], expected_from: expected_from, expected_view: declared[:expected_view], expected_text: expected_text,
273
+ outcome: "unobserved" }.compact.merge(measured: nil).tap { _1[:actual_from] = counted(_1[:actual_from], declared[:count]) }
274
+ end
275
+
276
+ # A count is the last step a claim takes, so its label names it first.
277
+ #: (String, untyped) -> String
278
+ def counted(label, count) = count ? "count of #{label}" : label
279
+
280
+ # Where a side of a claim reads: its origin, read through its view,
281
+ # then walked to its path, as the TypeScript engine labels it.
282
+ #: (String, String?, untyped) -> String
283
+ def place(base, view, at)
284
+ label = view ? "#{base} as #{view}" : base
285
+ return label unless at
286
+
287
+ "#{label}#{view ? " at " : "."}#{at}"
288
+ end
289
+
290
+ # A literal is named by the pattern words that state it, so the label
291
+ # reads as the sentence did.
292
+ #: (Hash[Symbol, untyped], Hash[String, String], Hash[String, String?], Array[String]) -> [String, String?]
293
+ def expected_origin(declared, origins, texts, patterns)
294
+ case declared[:expected]
295
+ in String => key then [place(origins.fetch(key, "sentence:#{key}"), declared[:expected_view], nil), texts[key]]
296
+ in { from: String => key } then [origins.fetch(key, "sentence:#{key}"), nil]
297
+ in { observe: String => path } then ["observe:#{path}", nil]
298
+ in { literal: value } then (words = Literal.stated_by_all(patterns, value) || "unstated"
299
+ ["literal:#{words}", words])
300
+ end
301
+ end
302
+
303
+ # The sentence a claim step's failure reads as, the same words the
304
+ # TypeScript engine prints.
305
+ #: (Array[Hash[Symbol, untyped]]) -> String
306
+ def broken_message(records) = ClaimLine.broken_claims_message(records)
307
+
308
+ #: (Integer) -> String
309
+ def runs_text(runs) = runs == 1 ? "1 run" : "#{runs} runs"
310
+
311
+ #: (Hash[Symbol, untyped]) -> String
312
+ def cell_text(cell) = { "pass" => "pass", "not-run" => "·" }.fetch(cell[:outcome]) { "#{cell[:outcome]}@#{cell[:line]}" }
313
+
314
+ # A head control or a base cell stands where the criterion's behaviour
315
+ # is absent, so a Then failing there the same way in each proof run
316
+ # proves the criterion tells the behaviour apart.
317
+ #: (Hash[Symbol, untyped]) -> bool
318
+ def proves?(cell)
319
+ absent = cell[:world] == "base" || (cell[:world] != "old" && cell[:role] == "control")
320
+ absent && cell[:outcome] == "fail" && cell[:runs] >= Table.proof_runs
321
+ end
322
+
323
+ #: (Hash[Symbol, untyped], String) -> String
324
+ def failed_reason(cell, where)
325
+ case cell[:outcome]
326
+ when "not-run" then "did not run #{where}: #{cell[:reason] || "no execution was recorded"}"
327
+ when "fail" then "a claim broke at line #{cell[:line]} #{where}"
328
+ when "broke" then "stopped at line #{cell[:line]} #{where} before a claim there was judged"
329
+ when "stopped" then "the walk was stopped with nuka step stop after line #{cell[:line]} #{where}, so the steps after it did not run and nothing shows it holds"
330
+ else "its #{runs_text(cell[:runs])} #{where} disagree, the first that did not pass at line #{cell[:line]}"
331
+ end
332
+ end
333
+
334
+ #: (Array[String]) -> String
335
+ def listed(parts) = parts.size <= 2 ? parts.join(" and ") : "#{parts[0..-2].to_a.join(", ")}, and #{parts.last}"
336
+
337
+ # What changed under an unchanged criterion, or nil when nothing did.
338
+ #: (Hash[Symbol, untyped]) -> String?
339
+ def underneath_change(context)
340
+ changed = { "the mapping" => :mapping_changed, "its tags" => :retagged, "its name or its file" => :renamed }.filter_map { |text, key| text if context[key] }
341
+ changed.empty? ? nil : "#{listed(changed)} changed since the base"
342
+ end
343
+
344
+ # The environments a row needs a base cell and an old cell in, from its
345
+ # head cells: none unless every required head cell passed; an
346
+ # unchanged row runs in the old world when something under it
347
+ # changed; a new or changed row runs at the base unless a head
348
+ # control already proves it, or it carries @held.
349
+ #: (Array[Hash[Symbol, untyped]], Hash[Symbol, untyped]?, Array[Hash[Symbol, untyped]]) -> Hash[Symbol, Array[String]]
350
+ def planned_world_cells(head_cells, context, old_roles)
351
+ none = { base: [], old: [] }
352
+ return none unless context
353
+
354
+ required = head_cells.select { _1[:role] == "required" }
355
+ return none if required.empty? || required.any? { _1[:outcome] != "pass" }
356
+ if context[:change] == "unchanged"
357
+ return none unless underneath_change(context)
358
+
359
+ return { base: [], old: old_roles.select { _1[:role] == "required" }.map { _1[:environment] } }
360
+ end
361
+ return none if !context[:held] && head_cells.any? { proves?(_1) }
362
+ # A Then a judgment decides compares nothing, so a base cell passes
363
+ # whatever the base does and cannot change the verdict.
364
+ return none if !context[:held] && context[:then_judges_no_claim] == "judgment"
365
+
366
+ { base: required.map { _1[:environment] }, old: [] }
367
+ end
368
+
369
+ #: (Hash[Symbol, untyped]) -> String
370
+ def world_cell_clause(cell)
371
+ where = cell[:world] == "old" ? "in the old world in #{cell[:environment]}" : "at the base in #{cell[:environment]}"
372
+ line = cell[:world] == "old" ? "line #{cell[:line]} of the base's feature file" : "line #{cell[:line]}"
373
+ case cell[:outcome]
374
+ when "not-run" then "it did not run #{where}: #{cell[:reason] || "no execution was recorded"}"
375
+ when "pass" then "it passed #{where}"
376
+ when "broke" then "it stopped at #{line} #{where} before a claim there was judged"
377
+ when "stopped" then "the walk was stopped after #{line} #{where}"
378
+ when "flaky" then "its #{runs_text(cell[:runs])} #{where} disagree, the first that did not pass at #{line}"
379
+ else
380
+ if cell[:world] == "base" && cell[:runs] < Table.proof_runs
381
+ "a claim broke at #{line} #{where} in only #{runs_text(cell[:runs])}, and proof needs #{Table.proof_runs}"
382
+ else
383
+ "a claim broke at #{line} #{where}"
384
+ end
385
+ end
386
+ end
387
+
388
+ #: (Array[Hash[Symbol, untyped]]) -> String
389
+ def world_cells_clause(cells)
390
+ template = world_cell_clause(cells.first.merge(environment: "\u0000"))
391
+ same = cells.select { world_cell_clause(_1.merge(environment: "\u0000")) == template }.map { _1[:environment] }
392
+ template.sub("\u0000") { same.join(", ") }
393
+ end
394
+
395
+ #: (String, Hash[Symbol, untyped]) -> String
396
+ def control_proof_reason(passed_in, proof)
397
+ "passes in #{passed_in}, and a claim broke at line #{proof[:line]} in #{proof[:environment]}, where its conditions do not hold, in each of #{runs_text(proof[:runs])}"
398
+ end
399
+
400
+ # A row's verdict and why, from its cells: red for a required cell that
401
+ # did not pass, or for a row with no required cell; proven when a
402
+ # control fails at a Then the same way in each proof run. Under
403
+ # `--base` (`context`), red too for a new or changed row nothing proves
404
+ # (unproven) and an unchanged row the old world does not pass (moved).
405
+ #: (Array[Hash[Symbol, untyped]], ?Hash[Symbol, untyped]?) -> [String, String]
406
+ def judge_row(cells, context = nil)
407
+ head = cells.select { _1[:world] == "head" }
408
+ required = head.select { _1[:role] == "required" }
409
+ if required.empty?
410
+ return ["failed", "no environment of this run meets its conditions, so every cell is a control and nothing shows that it holds"]
411
+ end
412
+
413
+ red = required.reject { _1[:outcome] == "pass" }
414
+ if red.any?
415
+ template = failed_reason(red.first, "in \u0000")
416
+ same = red.select { failed_reason(_1, "in \u0000") == template }.map { _1[:environment] }
417
+ clause = template.sub("\u0000") { same.join(", ") }
418
+ passed = required.select { _1[:outcome] == "pass" }.map { _1[:environment] }
419
+ return ["failed", passed.empty? ? clause : "#{clause}, and passes in #{passed.join(", ")}, where it is required too"]
420
+ end
421
+
422
+ passed_in = required.map { _1[:environment] }.join(", ")
423
+ controls = head.select { _1[:role] == "control" }
424
+ proof = controls.find { proves?(_1) }
425
+ unless context
426
+ return ["proven", control_proof_reason(passed_in, proof)] if proof
427
+ return ["held", "passes in #{passed_in}"] if controls.empty?
428
+
429
+ return ["held", "passes in #{passed_in}; no control shows a Then failing where its conditions do not hold (#{controls.map { "#{_1[:environment]}: #{cell_text(_1)}" }.join(", ")})"]
430
+ end
431
+
432
+ if context[:change] == "unchanged"
433
+ changed = underneath_change(context)
434
+ if changed
435
+ old = cells.select { _1[:world] == "old" }
436
+ moved = old.reject { _1[:outcome] == "pass" }
437
+ return ["moved", "passes in #{passed_in}, but #{changed} and the old world did not run it"] if old.empty?
438
+ return ["moved", "passes in #{passed_in}, but #{changed}, and #{world_cells_clause(moved)}"] if moved.any?
439
+ end
440
+ if proof
441
+ proven = control_proof_reason(passed_in, proof)
442
+ return ["proven", changed ? "#{proven}, and it passed in the old world, where the base's mapping runs head's code" : proven]
443
+ end
444
+ return ["held", "passes in #{passed_in}, and neither it nor the mapping changed since the base"] unless changed
445
+
446
+ return ["held", "passes in #{passed_in}, and in the old world, where the base's mapping runs head's code"]
447
+ end
448
+
449
+ base = cells.select { _1[:world] == "base" }
450
+ base_proof = base.find { proves?(_1) }
451
+ if base_proof
452
+ proven = "passes in #{passed_in}, and a claim broke at line #{base_proof[:line]} at the base in #{base_proof[:environment]} in each of #{runs_text(base_proof[:runs])}"
453
+ return ["proven", context[:held] ? "#{proven}, so the base does not have this behaviour and @held is not needed" : proven]
454
+ end
455
+ return ["proven", control_proof_reason(passed_in, proof)] if proof
456
+
457
+ if context[:held]
458
+ return ["held", "passes in #{passed_in} and at the base, as @held says"] if base.any? && base.all? { _1[:outcome] == "pass" }
459
+
460
+ short = base.reject { _1[:outcome] == "pass" }
461
+ clause = short.empty? ? "it did not run at the base" : world_cells_clause(short)
462
+ return ["unproven", "passes in #{passed_in}, and @held says the base has this behaviour, but #{clause}"]
463
+ end
464
+ absent = [*base.map { "base #{_1[:environment]}: #{cell_text(_1)}#{" (#{_1[:reason]})" if _1[:outcome] == "not-run" && _1[:reason]}" },
465
+ *controls.map { "control #{_1[:environment]}: #{cell_text(_1)}" }]
466
+ # A Then whose claims a reader judges compares nothing, so no world
467
+ # can prove it, and no world can leave it unproven either: the
468
+ # judgment column decides it, and the row is held on what the
469
+ # machine compared, which is everything before that Then.
470
+ if context[:then_judges_no_claim] == "judgment"
471
+ return ["held", "passes in #{passed_in}, and its Then asks for a judgment and compares nothing, so no world can show it failing where its behaviour is absent: " \
472
+ "its judgment decides it"]
473
+ end
474
+ if context[:then_judges_no_claim]
475
+ return ["unproven", "passes in #{passed_in}, but no claim step stands in its Then position, so no world can show a Then failing where its behaviour is absent" \
476
+ "#{absent.empty? ? "" : " (#{absent.join(", ")})"}"]
477
+ end
478
+ if absent.empty?
479
+ return ["unproven", "passes in #{passed_in}, and no world where its behaviour is absent ran it, so nothing shows a Then failing without the change"]
480
+ end
481
+
482
+ ["unproven", "passes in #{passed_in}, and nothing shows a Then failing where its behaviour is absent (#{absent.join(", ")})"]
483
+ end
484
+
485
+ #: (Array[Hash[Symbol, untyped]]) -> Hash[Symbol, Integer]
486
+ def counts(scenarios)
487
+ head = scenarios.reject { _1[:role] == "control" }
488
+ controls = scenarios.select { _1[:role] == "control" }
489
+ { scenarios: head.size, passed: head.count { _1[:status] == "passed" }, failed: head.count { _1[:status] == "failed" },
490
+ stopped: head.count { _1[:status] == "stopped" }, not_run: 0, controls: controls.size, controls_not_run: 0 }
491
+ end
492
+
493
+ # The commit HEAD named when the run started, whether the tree had an
494
+ # uncommitted change, and the working tree as one git tree id, written
495
+ # through a copy of the index so the real one is never touched. Null
496
+ # outside a git repository or before the first commit.
497
+ #: (String) -> Hash[Symbol, untyped]?
498
+ def commit(project)
499
+ sha, ok = git(project, "rev-parse", "--verify", "HEAD")
500
+ return nil unless ok
501
+
502
+ status, = git(project, "status", "--porcelain", "--untracked-files=all", "--", ".", ":(exclude).nukadoko")
503
+ { sha: sha, dirty: !status.empty?, working_tree: working_tree(project) }
504
+ end
505
+
506
+ #: (String) -> String?
507
+ def working_tree(project)
508
+ index, ok = git(project, "rev-parse", "--git-path", "index")
509
+ return nil unless ok
510
+
511
+ Dir.mktmpdir("nukadoko-index-") do |dir|
512
+ copy = File.join(dir, "index")
513
+ real = File.expand_path(index, project)
514
+ FileUtils.cp(real, copy) if File.exist?(real)
515
+ env = { "GIT_INDEX_FILE" => copy }
516
+ # Only the paths that changed are hashed, and --info-only records
517
+ # their ids without writing any file's contents to the object store.
518
+ changed, listed = git(project, "ls-files", "-z", "--modified", "--deleted", "--others", "--exclude-standard",
519
+ "--", ".", ":(exclude).nukadoko", env: env, strip: false)
520
+ _, updated = git(project, "update-index", "-z", "--add", "--remove", "--info-only", "--stdin", env: env, input: changed)
521
+ tree, wrote = git(project, "write-tree", "--missing-ok", env: env)
522
+ listed && updated && wrote ? tree : nil
523
+ end
524
+ end
525
+
526
+ #: (String, *String, ?env: Hash[String, String], ?input: String, ?strip: bool) -> [String, bool]
527
+ def git(project, *argv, env: {}, input: "", strip: true)
528
+ out, status = Open3.capture2(env, "git", *argv, chdir: project, err: File::NULL, stdin_data: input)
529
+ [strip ? out.strip : out, status.success?]
530
+ rescue SystemCallError
531
+ ["", false]
532
+ end
533
+ end
534
+ end
535
+ end