nukadoko 0.1.0 → 0.2.0

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