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
data/lib/nukadoko/run.rb CHANGED
@@ -1,4 +1,5 @@
1
1
  # frozen_string_literal: true
2
+ # rbs_inline: enabled
2
3
 
3
4
  require "securerandom"
4
5
  require "fileutils"
@@ -11,176 +12,918 @@ require "time"
11
12
  module Nukadoko
12
13
  module Engine
13
14
  class Run
14
- def initialize(project, steps, scenarios, program, out: $stdout)
15
+ # `world` is head for a run, or base or old for a tree's pass, which
16
+ # writes into the head run's directory `dir`. `base` is the
17
+ # comparison a `--base` run judges its rows by. `scenarios` are in the
18
+ # run's order, which every round of every pass keeps; `records`, when
19
+ # given, gets each scenario's run.json entry as one line as it ends,
20
+ # and `rerun` is what a shuffled run's rerun lines name.
21
+ #: (String, Array[singleton(Step)], Array[Scenario], Hash[Symbol, untyped], ?environments: Array[Environment]?, ?left_out: Integer, ?out: untyped, ?world: String, ?dir: String?, ?base: Base?, ?env_flags: Array[String], ?repeat: Integer, ?concurrency: Integer, ?order: Hash[Symbol, untyped], ?records: IO?, ?rerun: untyped, ?walk: WalkFiles::Handle?) -> void
22
+ def initialize(project, steps, scenarios, program, environments: nil, left_out: 0, out: $stdout, world: "head", dir: nil, base: nil, env_flags: [],
23
+ repeat: 1, concurrency: 1, order: Order::FILE, records: nil, rerun: nil, walk: nil)
15
24
  @project = project
16
25
  @steps = steps
17
26
  @scenarios = scenarios
18
27
  @program = Program.new(program)
28
+ @environments = environments || @program.environments
29
+ @left_out = left_out
19
30
  @out = out
20
- @id = new_id("run")
21
- @dir = File.join(project, ".nukadoko", "runs", @id)
31
+ @world = world
32
+ @base = base
33
+ @env_flags = env_flags
34
+ @repeat = repeat
35
+ @concurrency = concurrency
36
+ @incomplete = []
37
+ @world_entries = []
38
+ @order = order
39
+ @records = records
40
+ @rerun = rerun || { targets: [], tags: [], whole_files: [] }
41
+ # Under --step, the walk this run's one scenario pauses for.
42
+ @walk = walk
43
+ @id = dir ? File.basename(dir) : new_id("run")
44
+ @dir = dir || File.join(project, ".nukadoko", "runs", @id)
22
45
  end
23
46
 
47
+ #: () -> Hash[Symbol, untyped]
24
48
  def call
49
+ # An env file that cannot be read stops the run before anything starts.
50
+ @environments.each { read_env(_1) }
25
51
  FileUtils.mkdir_p(File.join(@dir, "steps"))
52
+ @started_at = now
53
+ write_sources
54
+ @commit = RunRecord.commit(@project)
55
+ # Said before any scenario, so a run a signal stops still names its seed.
56
+ @out.puts "order #{Order.text(@order)}" unless @order[:kind] == "file"
57
+ executions, cells = pass
58
+ tree_cells = {}
59
+ if @base
60
+ begin
61
+ trees = TreePasses.new(@base, @scenarios, cells, @environments, @dir, @out, ->(scenario) { Run.then_judged_by(scenario, executions) })
62
+ tree_cells = trees.call(executions)
63
+ @world_entries.concat(trees.worlds)
64
+ ensure
65
+ @base.cleanup
66
+ end
67
+ end
68
+ finish(executions, cells, tree_cells)
69
+ end
70
+
71
+ # One pass of a tree: each scenario in the one environment, as base or
72
+ # old, its executions and its cell.
73
+ #: () -> Array[Hash[Symbol, untyped]]
74
+ def tree_pass
75
+ FileUtils.mkdir_p(File.join(@dir, "steps"))
76
+ executions, cells = pass
77
+ @scenarios.map do |scenario|
78
+ { feature: scenario.uri, line: scenario.line, cell: cells[scenario].first,
79
+ executions: executions.select { _1[:json][:feature] == scenario.uri && _1[:json][:line] == scenario.line }.map { _1[:json] } }
80
+ end
81
+ end
82
+
83
+ # Each world this run started, as run.json's worlds holds it.
84
+ attr_reader :world_entries #: Array[Hash[Symbol, untyped]]
85
+
86
+ #: (Scenario, Environment) -> String
87
+ def role_of(scenario, environment) = Table.role(Table.condition_tags(scenario.tags), environment.conditions)
88
+
89
+ private
90
+
91
+ #: () -> [Array[Hash[Symbol, untyped]], Hash[Scenario, Array[Hash[Symbol, untyped]]]]
92
+ def pass
93
+ @base_urls = {}
26
94
  executions = []
27
95
  cells = Hash.new { |h, k| h[k] = [] }
28
- @program.environments.each do |environment|
29
- @out.puts "environment #{environment.name}"
30
- world_dir = File.join(@dir, "worlds", environment.name)
96
+ # Each scenario line is numbered across every environment and
97
+ # --repeat round, as the TypeScript engine numbers it; a proof run
98
+ # has a line of its own, so it is never one scenario more.
99
+ @played = 0
100
+ @to_play = @scenarios.size * @repeat * @environments.size
101
+ @environments.each do |environment|
102
+ # One environment needs no line of its own: every scenario is in it.
103
+ if @world != "head" then @out.puts "#{@world} #{environment.name}"
104
+ elsif @environments.size > 1 then @out.puts "environment #{environment.name}"
105
+ end
106
+ world_dir = File.join(@dir, "worlds", @world == "head" ? environment.name : "#{environment.name}@#{@world}")
31
107
  FileUtils.mkdir_p(world_dir)
108
+ read_env(environment)
32
109
  world = @program.start(environment, world_dir, @project)
33
- @process_fixtures = FixtureCache.new
34
- @browser = Browser.new(world.base_url, Nukadoko.config_options.fetch(:browser, {}))
35
- @scenarios.each do |scenario|
36
- role = Table.role(Table.condition_tags(scenario.tags), environment.conditions)
37
- runs = [play(scenario, environment, role, world)]
38
- runs << play(scenario, environment, role, world) while proving?(role, runs)
39
- executions.concat(runs)
40
- cells[scenario] << Table.cell(runs.map { _1[:execution] }).merge(environment: environment.name, role: role)
110
+ @program_log = world.log_path && Trace::Log.new(world.log_path, world.trace_prefix)
111
+ @base_urls[environment.name] = world.base_url
112
+ roles = @scenarios.to_h { [_1, @world == "head" ? role_of(_1, environment) : "required"] }
113
+ runs = Hash.new { |h, k| h[k] = [] }
114
+ ran = lambda do |scenario, execution|
115
+ runs[scenario] << execution
116
+ executions << execution
117
+ @records&.puts JSON.generate(execution[:json])
118
+ end
119
+ # Each control that broke a Then runs again, one round at a time,
120
+ # until it has broken the same claim at the same line --proof-runs
121
+ # times or a run disagrees.
122
+ due = -> { @scenarios.select { proving?(roles[_1], runs[_1]) } }
123
+ if @concurrency > 1
124
+ play_in_workers(environment, roles, world, due, ran, runs)
125
+ else
126
+ @process_fixtures = FixtureCache.new
127
+ @browser = Browser.new(world.base_url, Nukadoko.config_options.fetch(:browser, {}))
128
+ play_one = lambda do |scenario|
129
+ @out.puts boundary(scenario.uri, scenario.line, scenario.name, roles[scenario])
130
+ ran.(scenario, play(scenario, environment, roles[scenario], world))
131
+ end
132
+ # The whole selection once, then again, so a failure that depends
133
+ # on what ran before it meets the same neighbours every round.
134
+ @repeat.times { @scenarios.each(&play_one) }
135
+ until (round = due.()).empty?
136
+ round.each do |scenario|
137
+ @out.puts proof_boundary(scenario.uri, scenario.line, scenario.name, environment.name, runs[scenario].size + 1)
138
+ ran.(scenario, play(scenario, environment, roles[scenario], world))
139
+ end
140
+ end
41
141
  end
142
+ @scenarios.each { cells[_1] << cell(runs[_1], environment, roles[_1], _1) }
42
143
  ensure
43
144
  @browser&.close
44
145
  @process_fixtures&.teardown
45
146
  world&.stop
147
+ @world_entries << world_entry(environment, world, world_dir, (runs&.values || []).flatten) if world && @program.file?
148
+ @browser = @process_fixtures = @program_log = nil
46
149
  end
47
- finish(executions, cells)
150
+ [executions, cells]
48
151
  end
49
152
 
50
- private
153
+ # A stopped world as run.json names it. The lines of the program's log
154
+ # that came after their step's record was read go beside that record,
155
+ # and its run.json entry names them.
156
+ #: (Environment, World, String, Array[Hash[Symbol, untyped]]) -> Hash[Symbol, untyped]
157
+ def world_entry(environment, world, world_dir, executions)
158
+ entry = { name: environment.name, tree: @world, url: world.base_url, commands: world.commands, timings: world.timings,
159
+ log: world.log_path && File.join("worlds", File.basename(world_dir), "program.log"), error: nil }
160
+ return entry unless world.base_url
161
+ return entry.merge(program_log: nil) unless world.log_path
162
+
163
+ steps = executions.flat_map { _1[:json][:steps] || [] }.select { _1.dig(:observed, :program_log) }
164
+ traced = steps.to_h { |step| [step[:observed][:program_log][:trace_id], [step[:observed][:program_log][:lines], File.join(@dir, step[:record])]] }
165
+ found = Trace::Log.new(world.log_path, world.trace_prefix).late(traced)
166
+ steps.each do |step|
167
+ late = found[:late][step[:observed][:program_log][:trace_id]]
168
+ step[:program_log_late] = late if late
169
+ end
170
+ sum = ->(key) { steps.sum { _1[:observed][:program_log][key] } }
171
+ entry.merge(program_log: { stamped: sum.(:stamped), lines: sum.(:lines), late: found[:late].values.sum { _1[:lines] }, tagged: found[:tagged] })
172
+ end
173
+
174
+ # Under --concurrency the files go to worker processes in the run's
175
+ # order, round-robin, and each worker plays its own files --repeat
176
+ # times. A file whose Feature line is @nukadoko:serial runs after
177
+ # them, alone, and each round of proof runs is one worker of its own.
178
+ # The parent keeps the world each worker reaches, and takes each
179
+ # execution as it arrives.
180
+ #: (Environment, Hash[Scenario, String], World, ^() -> Array[Scenario], ^(Scenario, Hash[Symbol, untyped]) -> void, Hash[Scenario, Array[Hash[Symbol, untyped]]]) -> void
181
+ def play_in_workers(environment, roles, world, due, ran, runs)
182
+ files = @scenarios.group_by(&:uri).values
183
+ parallel, serial = files.partition { !_1.first.serial }
184
+ buckets = Array.new([@concurrency, parallel.size].min) { [] }
185
+ parallel.each_with_index { |file, i| buckets[i % buckets.size] << file } unless buckets.empty?
186
+ groups = buckets.map(&:flatten)
187
+ # The parent numbers a scenario's line when its execution arrives:
188
+ # the Nth to finish, since workers end in no fixed order.
189
+ line_for = lambda do |scenario, proof|
190
+ proof ? proof_boundary(scenario.uri, scenario.line, scenario.name, environment.name, runs[scenario].size + 1)
191
+ : boundary(scenario.uri, scenario.line, scenario.name, roles[scenario])
192
+ end
193
+ main = ->(scenario) { line_for.(scenario, false) }
194
+ unplayed = workers(groups.map { |group| @repeat.times.flat_map { group } }, environment, roles, world, ran, main)
195
+ serial.each { |file| unplayed += workers([@repeat.times.flat_map { file }], environment, roles, world, ran, main) }
196
+ until (round = due.()).empty?
197
+ break unless workers([round], environment, roles, world, ran, ->(scenario) { line_for.(scenario, true) }).empty?
198
+ end
199
+ return if unplayed.empty?
200
+
201
+ where = unplayed.uniq.sort.map { @environments.size > 1 ? "#{_1} (#{environment.name})" : _1 }
202
+ @incomplete << { severity: "failed", code: "run-incomplete",
203
+ message: "A worker exited without writing any record for: #{where.join(", ")}. This run is incomplete and cannot be treated as a pass" }
204
+ end
205
+
206
+ # Each list is one worker's scenarios in the order it plays them. A
207
+ # worker sends each line it prints and each execution down a pipe of
208
+ # its own, one Marshal frame at a time, so no line or record is ever
209
+ # spliced from two workers. Returns the files a worker that failed
210
+ # left without any execution.
211
+ #: (Array[Array[Scenario]], Environment, Hash[Scenario, String], World, ^(Scenario, Hash[Symbol, untyped]) -> void, ^(Scenario) -> String) -> Array[String]
212
+ def workers(lists, environment, roles, world, ran, line_for)
213
+ live = lists.each_with_index.map do |list, index|
214
+ reader, writer = IO.pipe
215
+ pid = fork do
216
+ reader.close
217
+ exit!(play_as_worker(index + 1, list, environment, roles, world, writer))
218
+ end
219
+ writer.close
220
+ worker = { pid: pid, reader: reader, list: list, played: Set.new } #: Hash[Symbol, untyped]
221
+ worker
222
+ end
223
+ by_key = @scenarios.to_h { [[_1.uri, _1.line], _1] }
224
+ until (open = live.reject { _1[:done] }).empty?
225
+ IO.select(open.map { _1[:reader] })&.first.to_a.each do |reader|
226
+ worker = open.find { _1[:reader] == reader } #: Hash[Symbol, untyped]
227
+ kind, *value = Marshal.load(reader)
228
+ if kind == :line then @out.puts value.first
229
+ else
230
+ scenario = by_key.fetch(value[0])
231
+ @out.puts line_for.(scenario)
232
+ value[2].each { @out.puts _1 }
233
+ worker[:played] << scenario.uri
234
+ ran.(scenario, value[1])
235
+ end
236
+ rescue EOFError
237
+ reader.close
238
+ ended = open.find { _1[:reader] == reader } #: Hash[Symbol, untyped]
239
+ ended[:done] = true
240
+ ended[:status] = Process.wait2(ended[:pid])[1]
241
+ end
242
+ end
243
+ live.reject { _1[:status].success? }.flat_map { |worker| worker[:list].map(&:uri).uniq - worker[:played].to_a }
244
+ end
245
+
246
+ #: (Integer, Array[Scenario], Environment, Hash[Scenario, String], World, IO) -> Integer
247
+ def play_as_worker(number, list, environment, roles, world, pipe)
248
+ @worker = number
249
+ @out = WorkerOut.new(pipe)
250
+ @records = nil
251
+ @process_fixtures = FixtureCache.new
252
+ @browser = Browser.new(world.base_url, Nukadoko.config_options.fetch(:browser, {}))
253
+ list.each do |scenario|
254
+ execution = play(scenario, environment, roles[scenario], world)
255
+ Marshal.dump([:execution, [scenario.uri, scenario.line], execution, @out.take], pipe)
256
+ end
257
+ 0
258
+ rescue Exception => e # rubocop:disable Lint/RescueException
259
+ Marshal.dump([:line, "worker #{number} stopped: #{e.class}: #{e.message}"], pipe) rescue nil
260
+ 1
261
+ ensure
262
+ @browser&.close
263
+ @process_fixtures&.teardown
264
+ pipe.close
265
+ end
266
+
267
+ # A worker's progress: the line that a scenario starts goes to the
268
+ # parent at once, and the scenario's other lines go with its
269
+ # execution, so one scenario's lines are never split by another's.
270
+ class WorkerOut
271
+ #: (IO) -> void
272
+ def initialize(pipe)
273
+ @pipe = pipe
274
+ @held = []
275
+ end
276
+
277
+ #: (?untyped) -> void
278
+ def puts(text = "")
279
+ text = text.to_s
280
+ text.start_with?("scenario start ") ? Marshal.dump([:line, text], @pipe) : @held << text
281
+ end
51
282
 
283
+ #: () -> Array[String]
284
+ def take = @held.slice!(0..)
285
+ end
286
+
287
+ # A head control and a base cell stand where the behaviour is absent,
288
+ # so a Then failing there the same way in each proof run is proof.
289
+ #: (String, Array[Hash[Symbol, untyped]]) -> bool
52
290
  def proving?(role, runs)
53
- role == "control" && runs.size < Table::PROOF_RUNS && runs.all? { _1[:execution].first == :fail } && runs.map { _1[:execution] }.uniq.size == 1
291
+ absent = @world == "base" || (@world == "head" && role == "control")
292
+ absent && runs.size < Table.proof_runs && runs.all? { _1[:execution].first == :fail } && runs.map { _1[:execution] }.uniq.size == 1
293
+ end
294
+
295
+ # A cell is what one scenario's executions in one environment came to;
296
+ # a cell whose first execution broke a claim names it and what it read.
297
+ # Its conditions are the ones the row's tags name, as the environment
298
+ # gives them.
299
+ #: (Array[Hash[Symbol, untyped]], Environment, String, Scenario) -> Hash[Symbol, untyped]
300
+ def cell(runs, environment, role, scenario)
301
+ executions = runs.map { _1[:execution] }
302
+ cell = Table.cell(executions)
303
+ entry = { world: @world, environment: environment.name, role: role, conditions: Table.conditions_of(scenario.tags, environment.conditions),
304
+ outcome: cell[:outcome], line: cell[:line], runs: cell[:runs] }.compact
305
+ if cell[:outcome] == "fail"
306
+ entry[:claim] = executions.first[2]
307
+ entry[:actuals] = runs.map { { value: _1[:actual] } }
308
+ end
309
+ entry
54
310
  end
55
311
 
56
- def finish(executions, cells)
312
+ # run.json is the --json envelope as a file: the commit and worlds the
313
+ # run judged, the counts, each execution, and the verdict table.
314
+ # `tree_cells` holds each row's base and old cells, by its scenario,
315
+ # under `--base`; each row is judged with what changed since the base.
316
+ #: (Array[Hash[Symbol, untyped]], Hash[Scenario, Array[Hash[Symbol, untyped]]], ?Hash[Scenario, Array[Hash[Symbol, untyped]]]) -> Hash[Symbol, untyped]
317
+ def finish(executions, cells, tree_cells = {})
57
318
  rows = @scenarios.map do |scenario|
58
- row_cells = cells[scenario]
59
- { feature: scenario.uri, line: scenario.line, name: scenario.name, conditions: Table.condition_tags(scenario.tags),
60
- cells: row_cells, verdict: Table.verdict(row_cells) }
319
+ change = @base&.changes&.[](Criteria.key(scenario.uri, scenario.line))
320
+ row_cells = cells[scenario] + tree_cells.fetch(scenario, [])
321
+ verdict, reason = RunRecord.judge_row(row_cells, context_of(scenario, change, executions))
322
+ row = { feature: scenario.uri, line: scenario.line, name: scenario.name, change: change&.dig(:change) }
323
+ row[:renamed_from] = change[:renamed_from] if change&.dig(:renamed_from)
324
+ row[:retagged] = true if change&.dig(:retagged)
325
+ row.merge(conditions: Table.row_tags(scenario.tags), cells: row_cells, verdict: verdict, reason: reason)
326
+ end
327
+ rows.sort_by! { [_1[:feature], _1[:line]] }
328
+ rows.concat(removed_rows) if @base
329
+ scenarios = executions.map { _1[:json] }
330
+ worlds = %w[head base old].flat_map do |world|
331
+ environments = world == "old" ? (@base&.old_environments || @environments) : @environments
332
+ environments.map(&:name).select { |name| world == "head" || rows.any? { |row| row[:cells].any? { _1[:world] == world && _1[:environment] == name } } }
333
+ .map { { world: world, environment: _1 } }
334
+ end
335
+ judged = @base ? judged_findings(rows) : []
336
+ # Judgments sit beside the verdicts, read after the table is built
337
+ # and never folded into a row's verdict. A file that cannot be read
338
+ # is a failed finding of its own, and its rows read as judged by
339
+ # nothing.
340
+ problems = [] #: Array[Hash[Symbol, untyped]]
341
+ entries = {} #: Hash[String, Array[Hash[Symbol, untyped]]]
342
+ entries_of = lambda do |feature|
343
+ entries[feature] ||= begin
344
+ read = JudgmentFile.read(@project, feature)
345
+ if read[:problem]
346
+ problems << { severity: "failed", code: "judgments-unread", file: JudgmentFile.of(feature),
347
+ message: "the judgments of #{feature} were not read: #{read[:problem]}, so its criteria read as judged by nothing",
348
+ fix: "repair #{JudgmentFile.of(feature)} by hand, or remove it and judge the criteria again with nuka judge" }
349
+ end
350
+ read[:entries] || []
351
+ end
352
+ end
353
+ rows = Judgments.with_judgments(rows, scenarios, entries_of)
354
+ # Under --base a reviewer reads which judgments the change added or
355
+ # replaced, as the summary lists the mapping files that changed.
356
+ warnings = [] #: Array[Hash[Symbol, untyped]]
357
+ changed = @base && JudgmentFile.changed(@project, @base.commit)
358
+ if @base && changed.nil?
359
+ warnings << { severity: "warning", code: "judgments-not-compared", message: "the judgment files were not compared with the base: git did not answer" }
360
+ end
361
+ judged += Judgments.findings(rows, @id) + problems
362
+ { run_id: @id, run_dir: File.join(".nukadoko/runs", @id), started_at: @started_at, finished_at: now, commit: @commit,
363
+ environments: @environments.map { environment_entry(_1) }, worlds: @world_entries, order: @order,
364
+ counts: RunRecord.counts(scenarios.reject { _1[:world] }), scenarios: scenarios,
365
+ table: { base: @base && { ref: @base.ref, commit: @base.commit }, mapping_changed: @base&.mapping&.dig(:changed),
366
+ mapping_changes: @base&.mapping_changes, **(changed ? { judgments_changed: changed } : {}),
367
+ worlds: worlds, rows: rows, left_out: @left_out, proof_runs: Table.proof_runs },
368
+ failures: warnings + executions.filter_map { _1[:failure] } + judged + @incomplete,
369
+ # A criterion whose Then asks for a judgment holds only once one
370
+ # cites what it read: the judgment column has a gate of its own.
371
+ passed: @incomplete.empty? && rows.none? { Summary::RED.include?(_1[:verdict]) } && !Judgments.open?(rows) && problems.empty?,
372
+ **(@walk ? { walk: @walk.record } : {}) }
373
+ end
374
+
375
+ # What `--base` knows of one row: its change, whether it carries
376
+ # @held, whether the mapping changed, whether its tags or its name or
377
+ # file changed, and whether its passing executions judged no claim in
378
+ # Then position.
379
+ #: (Scenario, Hash[Symbol, untyped]?, Array[Hash[Symbol, untyped]]) -> Hash[Symbol, untyped]?
380
+ def context_of(scenario, change, executions)
381
+ return nil unless change
382
+
383
+ no_claim = Run.then_judged_by(scenario, executions)
384
+ { change: change[:change], held: scenario.tags.include?(Criteria::HELD), mapping_changed: @base.mapping[:changed],
385
+ retagged: change[:retagged] == true, renamed: !change[:renamed_from].nil?, then_judges_no_claim: no_claim }
386
+ end
387
+
388
+ # sources.json: the feature text this run parsed its scenarios from,
389
+ # so `nuka report` renders the scenarios as they ran, long after the
390
+ # files moved on. The project name rides along: it is part of an
391
+ # Allure result's full name, and a copied run directory has no
392
+ # package.json beside it.
393
+ #: () -> void
394
+ def write_sources
395
+ package = File.join(@project, "package.json")
396
+ name = begin
397
+ (JSON.parse(File.read(package))["name"] if File.file?(package))
398
+ rescue JSON::ParserError
399
+ nil
400
+ end
401
+ features = @scenarios.map(&:uri).uniq.filter_map do |uri|
402
+ file = File.join(@project, uri)
403
+ { path: uri, source: File.read(file, encoding: "UTF-8") } if File.file?(file)
404
+ end
405
+ document = { schema_version: 1, project: name.is_a?(String) ? name : nil, features: features }
406
+ File.write(File.join(@dir, "sources.json"), "#{JSON.pretty_generate(document)}\n")
407
+ end
408
+
409
+ # Why head's passing required executions of a row judged no claim in
410
+ # Then position, from the first that says: `nothing`, or `judgment`
411
+ # when its only claims there are judged-as claims.
412
+ #: (Scenario, Array[Hash[Symbol, untyped]]) -> untyped
413
+ def self.then_judged_by(scenario, executions)
414
+ executions.lazy.map { _1[:json] }.filter_map do |json|
415
+ json[:judged_by] if json[:feature] == scenario.uri && json[:line] == scenario.line && !json[:world] && json[:role] == "required" && json[:status] == "passed"
416
+ end.first
417
+ end
418
+
419
+ #: () -> Array[Hash[Symbol, untyped]]
420
+ def removed_rows
421
+ @base.removed.sort_by { [_1.feature, _1.line] }.map do |criterion|
422
+ { feature: criterion.feature, line: criterion.line, name: criterion.name, change: "removed",
423
+ conditions: Table.row_tags(criterion.tags), cells: [], verdict: "removed",
424
+ reason: "the base holds this criterion, and head no longer does", lines: criterion.lines }
425
+ end
426
+ end
427
+
428
+ # A finding for each unproven and moved row, which has no failed
429
+ # execution to carry one, with the command that judges it again
430
+ # against the commit the run compared with.
431
+ #: (Array[Hash[Symbol, untyped]]) -> Array[Hash[Symbol, untyped]]
432
+ def judged_findings(rows)
433
+ rows.filter_map do |row|
434
+ next unless %w[unproven moved].include?(row[:verdict])
435
+
436
+ command = ["nuka", "run", "#{row[:feature]}:#{row[:line]}", "--base", @base.commit, *@env_flags].map { Selection.shell_word(_1) }.join(" ")
437
+ { severity: "failed", code: row[:verdict] == "unproven" ? "criterion-unproven" : "criterion-moved", file: row[:feature], line: row[:line],
438
+ message: %(Scenario "#{row[:name]}" is #{row[:verdict]}: it #{row[:reason]}), do: command }
439
+ end
440
+ end
441
+
442
+ #: (Environment) -> Hash[Symbol, untyped]
443
+ def environment_entry(environment)
444
+ { name: environment.name, conditions: environment.conditions.empty? ? nil : environment.conditions,
445
+ target_version: nil, base_url: @base_urls[environment.name] }.compact.merge(target_version: nil, base_url: @base_urls[environment.name])
446
+ end
447
+
448
+ # The line before a scenario's execution, numbered across the run, in
449
+ # the TypeScript engine's words so a log reads the same from either.
450
+ #: (String, Integer, String, String) -> String
451
+ def boundary(uri, line, name, role)
452
+ @played += 1
453
+ "scenario #{@played}/#{@to_play} #{uri}:#{line} #{name}#{role == "control" ? " (control)" : ""}"
454
+ end
455
+
456
+ # The line before a control runs again for proof: which run of its cell
457
+ # this is, of how many --proof-runs asks.
458
+ #: (String, Integer, String, String, Integer) -> String
459
+ def proof_boundary(uri, line, name, environment, run)
460
+ "proof run #{run}/#{Table.proof_runs} #{uri}:#{line} #{name} (control in #{environment})"
461
+ end
462
+
463
+ # Why a step failed, one line each: its error's first line, each step
464
+ # it read from whose program exited nonzero, and where its record is.
465
+ #: (Hash[Symbol, untyped]) -> Array[String]
466
+ def step_failure(record)
467
+ lines = [Summary.first_error_line(record[:error].to_s)]
468
+ Summary.exited_producers(record[:used]).each { |step, code, output| lines << "used #{step} exit #{code} #{output}" }
469
+ lines << "record #{File.join(".nukadoko", "runs", @id, "steps", record[:step_record_id])}" if record[:step_record_id]
470
+ lines
471
+ end
472
+
473
+ # Where a scenario's run starts again: its line, and its environment
474
+ # unless that is the only one a run without --env would start.
475
+ # In a shuffled order what ran before a scenario is part of what it
476
+ # met, so the line names those scenarios, then it, with the order and
477
+ # the run's --env flags. Under --repeat no one part of the order ran
478
+ # before it, so the line is the run's own targets and flags.
479
+ #: (Scenario, Environment) -> String
480
+ def again(scenario, environment)
481
+ if @order[:kind] == "file"
482
+ env = @environments.map(&:name) == ["default"] ? "" : " --env #{environment.name}"
483
+ return "nuka run #{scenario.uri}:#{scenario.line}#{env}"
61
484
  end
62
- write_summary(rows)
63
- @out.puts "summary #{File.join(".nukadoko/runs", @id, "summary.md")}"
64
- { run_id: @id, run_dir: File.join(".nukadoko/runs", @id), scenarios: executions.map { _1[:json] },
65
- table: { rows: rows }, passed: rows.none? { _1[:verdict] == "failed" } }
485
+
486
+ # Under --concurrency, what ran before it ran in other workers too.
487
+ words = if @repeat > 1 || @concurrency > 1
488
+ [*@rerun[:targets], *@rerun[:tags], *Order.flags(@order), *(["--repeat", @repeat.to_s] if @repeat > 1),
489
+ *(["--concurrency", @concurrency.to_s] if @concurrency > 1), *@env_flags]
490
+ else [*Order.replay_targets(@scenarios, @rerun[:whole_files], scenario), *Order.flags(@order), *@env_flags]
491
+ end
492
+ ["nuka", "run", *words].map { Selection.shell_word(_1) }.join(" ")
66
493
  end
67
494
 
495
+ #: (Scenario, Environment, String, World) -> Hash[Symbol, untyped]
68
496
  def play(scenario, environment, role, world)
69
- @out.puts "scenario #{scenario.uri}:#{scenario.line} #{scenario.name}#{role == "control" ? " (control)" : ""}"
497
+ # The numbered line is the caller's: a worker's goes out with its
498
+ # execution, numbered by the parent.
499
+ @out.puts "scenario start worker #{@worker} #{scenario.uri}:#{scenario.line} #{scenario.name}" if @worker
500
+ started_at = now
70
501
  results = []
71
- stopped = nil
72
- @scratch = Scratch.new
502
+ stopped = nil #: Array[untyped]?
503
+ @scratch = Scratch.new(@project)
73
504
  @scenario_fixtures = FixtureCache.new
74
- records = scenario.steps.map do |line|
75
- record = stopped ? skipped(line) : play_step(line, results, world)
76
- stopped ||= [record[:outcome], line.line, record[:claim]] if record[:status] == "failed"
77
- @out.puts " #{record[:status]} #{line.text}"
78
- @out.puts " #{record[:error]}" if record[:error]
505
+ scenario_record_id = new_id("scn")
506
+ @step_file = lambda do |record|
507
+ RunRecord.step_file(record, environment: environment.name, world_name: @program.file? ? environment.name : nil, run_id: @id,
508
+ scenario_record_id: scenario_record_id, evidence_dir: File.join(".nukadoko", "runs", @id, "steps", record[:step_record_id]))
509
+ end
510
+ # Where a person stopped the walk, as run.json's `stopped` says it.
511
+ walk_stopped = nil #: Hash[Symbol, untyped]?
512
+ @walk&.begin({ run_id: @id, run_dir: File.join(".nukadoko", "runs", @id),
513
+ scenario: { feature: scenario.uri, line: scenario.line, name: scenario.name, environment: environment.name },
514
+ world: world.base_url ? { url: world.base_url } : nil })
515
+ records = scenario.steps.each_with_index.map do |line, index|
516
+ began = Process.clock_gettime(Process::CLOCK_MONOTONIC)
517
+ record = stopped || walk_stopped ? skipped(line) : play_step(line, results, world)
518
+ stopped ||= [record[:outcome], line.line, record[:claim], record[:broken_actual]] if record[:status] == "failed"
519
+ seconds = format("%.1f", Process.clock_gettime(Process::CLOCK_MONOTONIC) - began)
520
+ @out.puts " step #{index + 1}/#{scenario.steps.size} #{record[:status]} #{seconds}s #{line.text}"
521
+ step_failure(record).each { @out.puts " #{_1}" } if record[:status] == "failed"
522
+ # A step with a written record ran, so a walk pauses after it.
523
+ if @walk && record[:step_record_id] && record[:status] != "skipped"
524
+ remaining = stopped ? 0 : scenario.steps.size - index - 1
525
+ answer = pause(record, line, index + 1, scenario.steps.size, remaining)
526
+ walk_stopped = { after_step: index + 1, line: line.line } if answer == "stop" && remaining.positive?
527
+ end
79
528
  record
80
529
  end
81
- @browser.end_scenario
530
+ browser = @browser.scenario_browser
531
+ final = @browser.end_scenario(File.join(@dir, "scenarios", scenario_record_id))
82
532
  @scenario_fixtures.teardown
83
533
  @scratch.remove_all
84
- execution = stopped ? stopped.compact : [:pass]
85
- { execution: execution,
86
- json: { feature: scenario.uri, line: scenario.line, scenario: scenario.name, environment: environment.name, role: role,
87
- status: stopped ? "failed" : "passed",
88
- steps: scenario.steps.zip(records).map do |line, record|
89
- { line: line.line, text: line.text, step: record[:step], status: record[:status], record: record[:step_record_id] }.compact
90
- end } }
534
+ execution = if stopped then stopped[0, 3].to_a.compact
535
+ elsif walk_stopped then [:stopped, walk_stopped[:line]]
536
+ else [:pass]
537
+ end
538
+ failed = records.find { _1[:status] == "failed" }
539
+ status = if stopped then "failed"
540
+ elsif walk_stopped then "stopped"
541
+ else "passed"
542
+ end
543
+ json = { scenario_record_id: scenario_record_id, feature: scenario.uri, line: scenario.line, scenario: scenario.name,
544
+ status: status, **(walk_stopped && !stopped ? { stopped: walk_stopped } : {}),
545
+ environment: environment.name, started_at: started_at, finished_at: now, **(browser ? { browser: browser } : {}),
546
+ steps: scenario.steps.zip(records).map { |line, record| step_entry(line, record) }, hooks: [] } #: Hash[Symbol, untyped]
547
+ json[:evidence] = { dir: File.join("scenarios", scenario_record_id), screenshots: final } if final.any?
548
+ json[:do] = again(scenario, environment) if (failed || status == "stopped") && role != "control"
549
+ json[:claims] = RunRecord.claim_counts(records)
550
+ # A scenario in which no claim on a Then line was judged says so,
551
+ # since a pass there shows only that nothing raised. A Then whose
552
+ # only claims a reader judges compared nothing: its judgment is
553
+ # what decides it.
554
+ then_claims = scenario.steps.zip(records).select { |line, _| line_kind(line) == :then }.flat_map { _2[:claim_records] || [] }
555
+ unless then_claims.any? { !%w[unobserved for-judgment].include?(_1[:outcome]) }
556
+ json[:judged_by] = then_claims.any? { _1[:outcome] == "for-judgment" } ? "judgment" : "nothing"
557
+ end
558
+ json[:role] = role
559
+ failure = if failed && role != "control"
560
+ { severity: "failed", code: "scenario-failed", file: scenario.uri, line: scenario.line,
561
+ message: "#{scenario.name}: #{failed[:error]}", do: json[:do] }
562
+ elsif (where = walk_stopped) && status == "stopped" && role != "control"
563
+ at = where[:line] ? " (line #{where[:line]})" : ""
564
+ { severity: "failed", code: "walk-stopped", file: scenario.uri, line: scenario.line,
565
+ message: "#{scenario.name}: the walk was stopped after step #{where[:after_step]}#{at} with nuka step stop, so the steps after it did not run",
566
+ do: json[:do] }
567
+ end
568
+ { execution: execution, actual: stopped && stopped[3], json: json, failure: failure }
569
+ end
570
+
571
+ # The pause after the step that ran `number`th, under --step. Before
572
+ # the walk waits, the open page's traffic moves to the pause's own
573
+ # directory: a page that polls while the person reads is not the
574
+ # step's work, and the step's record is already written. After a
575
+ # failure nothing runs on `next` either, so nothing remains and a
576
+ # `stop` there stops nothing.
577
+ #: (Hash[Symbol, untyped], PickleStep, Integer, Integer, Integer) -> String?
578
+ def pause(record, line, number, of, remaining)
579
+ facts = { step: number, of: of, line: line.line, text: line.text, step_name: record[:step], status: record[:status] == "passed" ? "passed" : "failed",
580
+ step_record_id: record[:step_record_id], record: "steps/#{record[:step_record_id]}",
581
+ **(record[:error] ? { failure: { by: "step", message: record[:error] } } : {}), remaining: remaining }
582
+ @walk.pause_after(facts) { |dir, recorded_as| @browser.hold(dir, recorded_as) }
583
+ ensure
584
+ @browser&.release
585
+ end
586
+
587
+ # One step as run.json's scenarios[].steps[] holds it.
588
+ #: (PickleStep, Hash[Symbol, untyped]) -> Hash[Symbol, untyped]
589
+ def step_entry(line, record)
590
+ # A line no step matches is `undefined`, and one more than one step
591
+ # matches is `ambiguous`, as cucumber names them, so a messages
592
+ # stream says the same of it as the TypeScript engine's.
593
+ entry = { line: line.line, text: line.text, step: record[:step], status: record[:never_began] || record[:status],
594
+ step_record_id: record[:step_record_id], record: record[:step_record_id] && "steps/#{record[:step_record_id]}" }
595
+ return entry if record[:status] == "skipped"
596
+
597
+ entry[:mutates] = record[:mutates]
598
+ processes = record[:processes]
599
+ # run.json keeps the record's observed without file content, so it stays small.
600
+ entry[:observed] = { processes: processes&.any? ? processes : nil, http: record[:http_count]&.positive? ? record[:http_count] : nil,
601
+ files: record[:files]&.map { _1.except(:content) }, unmeasured: [],
602
+ **(record.key?(:program_log) ? { program_log: record[:program_log] } : {}) }
603
+ entry[:error] = { kind: record[:error_kind], message: record[:error] } if record[:error]
604
+ # Only a failed step names what it read: a reader then sees the value it broke on.
605
+ entry[:used] = record[:used] if record[:used]&.any? && record[:status] == "failed"
606
+ if record[:claim_records]
607
+ # A judgment cites a judged-as value by the digest of the whole value.
608
+ entry[:claims] = record[:claim_records].map do |claim|
609
+ claim[:outcome] == "for-judgment" && claim.key?(:actual) && !claim[:each] ? { **claim, value_digest: Judgments.value_digest(claim[:actual]) } : claim
610
+ end
611
+ entry[:observation] = record[:observation] || "observed"
612
+ entry.merge!(RunRecord.poll_fields(record).except(:readings), **RunRecord.page_fields(record, File.join("steps", record[:step_record_id].to_s)))
613
+ end
614
+ entry
91
615
  end
92
616
 
93
- def skipped(line) = { step: Engine.matches(@steps, line.text).first&.first&.step_name, status: "skipped" }
617
+ #: (PickleStep) -> Hash[Symbol, untyped]
618
+ def skipped(line)
619
+ { step: Engine.matches(@steps, line.text).first&.first&.step_name, status: "skipped", step_record_id: nil }
620
+ end
94
621
 
622
+ #: (PickleStep, Array[untyped], World) -> Hash[Symbol, untyped]
95
623
  def play_step(line, results, world)
96
- step, captures = Engine.matches(@steps, line.text).first
97
- return { status: "failed", outcome: :broke, error: %(no step matches "#{line.text}") } unless step
624
+ matched = Engine.matches(@steps, line.text)
625
+ step, captures = matched.first
626
+ unless step
627
+ return { status: "failed", outcome: :broke, step_record_id: nil, error_kind: "step_error", error: %(No step definition matches "#{line.text}"), never_began: "undefined" }
628
+ end
629
+ # Under --no-check nothing refused the line before it ran, and
630
+ # running the first match would pass a line the author meant for
631
+ # another step.
632
+ names = matched.map { _1.first.step_name }.uniq.sort
633
+ if names.size > 1
634
+ return { status: "failed", outcome: :broke, step_record_id: nil, error_kind: "step_error",
635
+ error: %("#{line.text}" matches more than one step: #{names.join(", ")}), never_began: "ambiguous" }
636
+ end
98
637
 
99
638
  id = new_id("step")
100
639
  dir = File.join(@dir, "steps", id)
640
+ record = { step_record_id: id, step: step.step_name, text: line.text, started_at: Time.now.utc.iso8601(3) }
641
+ origins = {}
642
+ execute(step, record, dir, world, then_line: line_kind(line) == :then, at_line: line.line, results: results, origins: origins) do
643
+ args = bind_args(step, captures, line, results, origins, record)
644
+ [args, (Pattern.new(step.pattern.to_s).texts(line.text) || {}).merge(attachment_texts(step, captures, line))]
645
+ end
646
+ end
647
+
648
+ public
649
+
650
+ # One step alone, as `nuka do` runs it: its args given on the command
651
+ # line or by earlier records (`origins` says which), in a world
652
+ # started for this one execution, its evidence in this run's
653
+ # directory, which is the record's own.
654
+ #: (singleton(Step), Hash[String, untyped], Hash[String, String], Hash[String, String], Environment) -> Hash[Symbol, untyped]
655
+ def do_step(step, args, origins, texts, environment)
656
+ FileUtils.mkdir_p(@dir)
657
+ read_env(environment)
658
+ world = @program.start(environment, @dir, @project)
659
+ @program_log = world.log_path && Trace::Log.new(world.log_path, world.trace_prefix)
660
+ @scratch = Scratch.new(@project)
661
+ @scenario_fixtures = FixtureCache.new
662
+ @process_fixtures = FixtureCache.new
663
+ @browser = Browser.new(world.base_url, Nukadoko.config_options.fetch(:browser, {}))
664
+ record = { step_record_id: @id, step: step.step_name, started_at: now }
665
+ execute(step, record, @dir, world, then_line: true, at_line: nil, results: [], origins: origins) { [args, texts] }
666
+ ensure
667
+ @browser&.close
668
+ @scenario_fixtures&.teardown
669
+ @process_fixtures&.teardown
670
+ @scratch&.remove_all
671
+ world&.stop
672
+ end
673
+
674
+ # What `nuka do` writes its stdout and its record through.
675
+ #: (untyped) -> untyped
676
+ def redact(value) = secrets.redact(value)
677
+
678
+ private
679
+
680
+ # Runs one step whose args the block binds, and writes its record and
681
+ # HTTP log into `dir`.
682
+ #: (singleton(Step), Hash[Symbol, untyped], String, World, then_line: bool, at_line: Integer?, results: Array[untyped], origins: Hash[String, String]) { () -> [Hash[String, untyped], Hash[String, String]] } -> Hash[Symbol, untyped]
683
+ def execute(step, record, dir, world, then_line:, at_line:, results:, origins:)
101
684
  FileUtils.mkdir_p(dir)
102
685
  log = []
103
- record = { step_record_id: id, step: step.step_name, text: line.text, started_at: Time.now.utc.iso8601(3) }
104
686
  fixtures = {}
105
- finish = nil
687
+ finish = nil #: Proc?
106
688
  processes = []
689
+ scratch_dirs = @scratch&.dirs || []
690
+ scratch_before = @scratch&.snapshot || {}
691
+ # A world with a URL is one the step's requests can be traced into.
692
+ boundary = world.base_url && Trace::Boundary.new(Trace.new_id(world.trace_prefix), world.base_url)
107
693
  begin
108
- args = bind_args(step, captures, line, results)
694
+ record[:mutates] = step.mutating?
695
+ args, texts = yield
109
696
  record[:args] = args
110
697
  problems = step.args.problems(args)
111
- raise TypeError, "args: #{problems.join("; ")}" if problems.any?
698
+ if problems.any?
699
+ record[:error_kind] = "args_invalid"
700
+ raise TypeError, "args: #{problems.join("; ")}"
701
+ end
112
702
 
113
- fixtures, finish = build_fixtures(step, dir, log, world)
114
- Processes.collect(processes) { body(step, fixtures, args, line, record, results) }
703
+ @browser&.step = { step_record_id: record[:step_record_id], step: record[:step], line: at_line }
704
+ @browser&.begin_step
705
+ Trace.within(boundary) do
706
+ fixtures, finish = build_fixtures(step, dir, log, world, record)
707
+ HttpRecording.collect(log) do
708
+ Processes.collect(processes) { RedactedOutput.around(secrets) { body(step, fixtures, args, [then_line, at_line], record, results, origins, texts) } }
709
+ end
710
+ end
711
+ record[:page_view] = @browser.judged(dir, record[:step_record_id], aria_in_claims: step.claims.to_a.any? { !_1[:each] && _1[:compare] == "fits-aria-snapshot" }) if step.claims && fixtures[:page] && record[:observation] != "unobserved"
115
712
  record[:status] ||= "passed"
116
713
  rescue StandardError => e
117
- record.merge!(status: "failed", outcome: :broke, error: "#{e.class}: #{e.message}")
714
+ record.merge!(status: "failed", outcome: :broke, error: e.message)
715
+ record[:error_kind] ||= "step_error"
118
716
  ensure
717
+ @browser&.step = nil
119
718
  finish&.call
120
719
  log.concat(fixtures[:request].log) if fixtures[:request]
720
+ # A world at a URL has a log nukadoko does not read.
721
+ record[:program_log] = @program_log&.slice(dir, boundary) if boundary
121
722
  record[:finished_at] = Time.now.utc.iso8601(3)
723
+ # Each process's output is a file of the step's own, named by its number.
724
+ processes.each.with_index(1) do |process, n|
725
+ output = process.delete(:output) || {}
726
+ %i[stdout stderr stdin].each do |stream|
727
+ next if output[stream].to_s.empty?
728
+
729
+ File.write(File.join(dir, "process-#{n}.#{stream}.txt"), secrets.redact(output[stream]))
730
+ process[stream] = "process-#{n}.#{stream}.txt"
731
+ end
732
+ end
122
733
  record[:processes] = processes if processes&.any?
734
+ if @scratch
735
+ changes = @scratch.changes(scratch_before)
736
+ record[:files] = changes if changes.any?
737
+ made = @scratch.dirs - scratch_dirs
738
+ record[:scratch] = made if made.any?
739
+ end
123
740
  record[:calls] = fixtures[:call].calls if fixtures[:call]&.calls&.any?
124
- record[:observed] = { http: log.size, processes: processes&.size || 0 }
125
- File.write(File.join(dir, "http.jsonl"), log.map { JSON.generate(_1) }.join("\n"))
126
- File.write(File.join(dir, "record.json"), JSON.pretty_generate(record))
741
+ # A page's own traffic is in http.jsonl and the trace, not counted as the step's.
742
+ record[:http_count] = log.count { _1[:via] != "page" }
743
+ File.write(File.join(dir, "http.jsonl"), "#{log.map { JSON.generate(secrets.redact(_1)) }.join("\n")}\n") if log.any?
744
+ record[:http_file] = log.any?
745
+ if (traced = TraceActions.read(File.join(dir, "trace.zip")))
746
+ record[:trace] = "trace.zip"
747
+ record[:actions] = traced[:actions] if traced[:actions].any?
748
+ record[:actions_truncated] = traced[:truncated] if traced[:truncated]
749
+ end
750
+ measure(step, record, dir) if record[:claim_records]
751
+ File.write(File.join(dir, "record.json"), JSON.pretty_generate(secrets.redact(@step_file ? @step_file.(record) : record)))
127
752
  end
128
753
  record
129
754
  end
130
755
 
131
756
  # A Then step's claims are judged on what it observed, or on its args
132
757
  # when it reads nothing itself; any other step runs and returns.
133
- def body(step, fixtures, args, line, record, results)
758
+ # `step` is a step class whose observe or run its own file defines.
759
+ #: (untyped, Hash[Symbol, untyped], untyped, [bool, Integer?], Hash[Symbol, untyped], Array[untyped], Hash[String, String], Hash[String, String?]) -> void
760
+ def body(step, fixtures, args, position, record, results, origins, texts)
761
+ then_line, at_line = position
134
762
  if step.claims
135
763
  own = fixtures.slice(*step.fixtures)
136
- read = -> { step.method_defined?(:observe) ? step.new.observe(**own, args: step.inputs.load(args)) : args }
137
- observed = step.poll ? Poll.new(step.poll, step.claims, args).call(record, &read) : read.()
764
+ observes = step.method_defined?(:observe)
765
+ # A claim's actual that starts with a from key reads the value an
766
+ # earlier step returned, which wins over a key observe returns
767
+ # under the same name.
768
+ from_values = args.transform_keys(&:to_s).slice(*step.from.keys.map(&:to_s))
769
+ read = lambda do
770
+ next args unless observes
771
+
772
+ observed = step.new.observe(**step.keywords(own, step.inputs.load(args)))
773
+ observed = observed.is_a?(Hash) ? observed.transform_keys(&:to_s).merge(from_values) : observed
774
+ Claims.take_aria_snapshots(step.claims, observed)
775
+ end
776
+ # A reading with a page open is timed, so the record can say what the page had received by then.
777
+ read = (plain = read; -> { @browser.reading(&plain) }) if own[:page]
778
+ observed = begin
779
+ step.poll ? Poll.new(step.poll, step.claims, args).call(record, &read) : read.()
780
+ rescue StandardError => e
781
+ raise unless observes && !step.poll
782
+
783
+ # observe failing is no claim breaking: nothing was read to judge.
784
+ record[:observation] = "unobserved"
785
+ record[:claim_records] = step.claims.reject { _1[:each] }.map { RunRecord.unobserved_claim(_1, origins, texts, patterns: [step.pattern].compact) }
786
+ record[:error_kind] = "unobserved"
787
+ raise e.class, "the step observed nothing, so no claim was judged: #{e.message}"
788
+ end
138
789
  judged = Claims.judge(step.claims, observed, args)
139
790
  record[:claims] = judged
140
- broken = judged.index { !_1[:holds] }
141
- record.merge!(status: "failed", outcome: line_kind(line) == :then ? :fail : :broke, claim: broken, error: "claim #{broken} broke") if broken
142
- else
143
- value = step.new.run(**fixtures.slice(*step.fixtures), args: step.inputs.load(args))
144
- problems = step.returns ? step.returns.problems(value) : []
145
- raise TypeError, "returns: #{problems.join("; ")}" if problems.any?
791
+ # The value each claim read before its view, for `measured`.
792
+ record[:raw_actuals] = step.claims.map do |declared|
793
+ next nil if declared[:each]
146
794
 
147
- if step.returns
148
- dropped = step.returns.dropped(value)
149
- record[:returns_dropped] = dropped if dropped.any?
150
- value = step.returns.strip(value)
795
+ # Under a view the raw value is the text the view read; else the value at `at`.
796
+ read = Claims.read(observed, declared[:actual])
797
+ next nil if declared[:compare] == "fits-aria-snapshot"
798
+
799
+ declared[:view] ? read : Claims.dig(read, declared[:at])
800
+ rescue StandardError
801
+ nil
802
+ end
803
+ patterns = [step.pattern].compact
804
+ record[:claim_records] = step.claims.zip(judged).map do |declared, result|
805
+ if declared[:each]
806
+ RunRecord.each_claim(declared, observed, args, origins, texts, observed_from: observes && !from_values.key?(declared[:actual].to_s.split(".").first), patterns: patterns)
807
+ else
808
+ RunRecord.claim(declared, result, origins, texts, observed: observes && !from_values.key?(declared[:actual].to_s.split(".").first), patterns: patterns)
809
+ end
151
810
  end
152
- results << [step, value.transform_keys(&:to_s)]
811
+ broken = record[:claim_records].index { !%w[held for-judgment].include?(_1[:outcome]) }
812
+ return unless broken
813
+
814
+ message = RunRecord.broken_message(record[:claim_records])
815
+ first, *rest = message.split("\n", -1)
816
+ message = ["#{first}#{RunRecord.poll_end(step, record)}", *rest].join("\n")
817
+ record.merge!(status: "failed", outcome: then_line ? :fail : :broke, claim: broken,
818
+ broken_actual: judged[broken][:actual], error_kind: "claim_broken", error: message)
819
+ else
820
+ value, problems = step.returned(step.new.run(**step.keywords(fixtures.slice(*step.fixtures), step.inputs.load(args))))
821
+ if problems.any?
822
+ record[:error_kind] = "result_invalid"
823
+ raise TypeError, "returns validation failed: #{problems.join("; ")}"
824
+ end
825
+
826
+ record[:returns_dropped] = step.returns ? step.returns.drops(value) : []
827
+ value = step.returns.strip(value) if step.returns
828
+ results << [step, value.transform_keys(&:to_s), at_line, record[:step_record_id]]
153
829
  record[:result] = value
154
830
  end
155
831
  end
156
832
 
157
833
  # Captures first, then each `from` key from the nearest earlier step that
158
834
  # gave it, then a table or docstring for the one required key still open.
159
- def bind_args(step, captures, line, results)
835
+ # `origins` gets each from key's label, `from:<step>@<line>.<key>`, and
836
+ # `record[:used]` each earlier step a from key read, with its result.
837
+ # Each claim record's `measured`: the channel that holds the raw value
838
+ # it read, in the record of the step a `from` value came from, or in
839
+ # its own; and an expected value an earlier step gave, the same way.
840
+ #: (singleton(Step), Hash[Symbol, untyped], String) -> void
841
+ def measure(step, record, dir)
842
+ own = record[:step_record_id]
843
+ own_channels = Measured.channels(dir, { processes: record[:processes], files: record[:files] }, record[:http_count].to_i.positive? ? "http.jsonl" : nil)
844
+ cache = {}
845
+ channels_of = lambda do |id|
846
+ next own_channels if id == own
847
+
848
+ cache[id] ||= begin
849
+ found = [File.join(@dir, "steps", id), File.join(@project, ".nukadoko", "do", id)].find { File.exist?(File.join(_1, "record.json")) }
850
+ other = found && JSON.parse(File.read(File.join(found, "record.json")), symbolize_names: true)
851
+ other && found ? Measured.channels(found, other[:observed] || {}, other.dig(:evidence, :http)) : [{ channel: "record", unknown: true }]
852
+ end
853
+ end
854
+ from_of = ->(key) { (origin = (record[:args_origin] || {})[key.to_s.split(".").first]).is_a?(Hash) ? origin.dig(:from, :step_record_id) : nil }
855
+ (step.claims || []).zip(record[:claim_records], record[:raw_actuals] || []).each do |declared, claim, raw|
856
+ next if claim.nil? || claim[:outcome] == "unobserved" || declared[:each]
857
+ # A tree nukadoko took is a measurement of the page, not a value a channel carried.
858
+ next claim[:measured] = nil if declared[:compare] == "fits-aria-snapshot" || claim[:actual_from].to_s.start_with?(Judgments::ARIA_LABEL)
859
+
860
+ measured = Measured.channel_for(from_of.(declared[:actual]) || own, raw, channels_of)
861
+ claim[:measured] = measured
862
+ key = declared[:expected].is_a?(String) ? declared[:expected] : declared[:expected].is_a?(Hash) && declared[:expected][:from]
863
+ source = declared[:expected].is_a?(Hash) && declared[:expected].key?(:observe) ? own : key && from_of.(key)
864
+ next unless source && claim.key?(:expected)
865
+
866
+ # The expected side's channel comes before the actual's, as the TypeScript engine writes it.
867
+ claim.delete(:measured)
868
+ claim.merge!(expected_measured: Measured.channel_for(source, claim[:expected], channels_of, measured), measured: measured)
869
+ end
870
+ record.delete(:raw_actuals)
871
+ end
872
+
873
+ #: (singleton(Step), Hash[String, untyped], PickleStep, Array[untyped], Hash[String, String], Hash[Symbol, untyped]) -> Hash[String, untyped]
874
+ def bind_args(step, captures, line, results, origins, record)
160
875
  args = captures.dup
876
+ record[:args_origin] = captures.keys.to_h { [_1, "capture"] }
877
+ used = []
161
878
  step.from.each do |key, sources|
162
- cls, value = results.reverse_each.find { |c, _| sources.any? { _1.first == c } }
163
- raise ArgumentError, %(no earlier step in this scenario gave "#{key}") unless cls
879
+ cls, value, at_line, record_id = results.reverse_each.find { |c, _| sources.any? { _1.first == c } }
880
+ unless cls
881
+ record[:error_kind] = "binding_invalid"
882
+ raise ArgumentError, %(no earlier step in this scenario gave "#{key}")
883
+ end
164
884
 
165
- args[key] = value.fetch(sources.find { _1.first == cls }[1].to_s)
885
+ source_key = sources.find { _1.first == cls }[1].to_s
886
+ args[key] = value.fetch(source_key)
887
+ origins[key] = "from:#{cls.step_name}@#{at_line}.#{source_key}"
888
+ record[:args_origin][key] = { from: { step_record_id: record_id, step: cls.step_name, key: source_key } }
889
+ used << { step: cls.step_name, record: "steps/#{record_id}", result: value } unless used.any? { _1[:record] == "steps/#{record_id}" }
166
890
  end
891
+ record[:used] = used
167
892
  open = step.args.fields.map { _1.name.to_s } - args.keys
168
893
  attachment = line.table || line.doc_string
169
- args[open.first] = attachment if attachment && open.any?
170
- args
894
+ if attachment && open.any?
895
+ args[open.first] = attachment
896
+ record[:args_origin][open.first] = line.table ? "table" : "docstring"
897
+ end
898
+ # In the order the args schema declares, as the record shows them.
899
+ rank = step.args.fields.each_with_index.to_h { [_1.name.to_s, _2] }
900
+ record[:args_origin] = record[:args_origin].sort_by { |key, _| rank.fetch(key.to_s, rank.size) }.to_h
901
+ args.sort_by { |key, _| rank.fetch(key.to_s, rank.size) }.to_h
171
902
  end
172
903
 
904
+ # The docstring or table a line attaches is the sentence's own text
905
+ # for the one key it fills.
906
+ #: (singleton(Step), Hash[String, untyped], PickleStep) -> Hash[String, String]
907
+ def attachment_texts(step, captures, line)
908
+ open = step.args.fields.map { _1.name.to_s } - captures.keys - step.from.keys
909
+ return {} if open.empty?
910
+ return { open.first => line.doc_string } if line.doc_string
911
+ return { open.first => line.table.map { |row| "| #{row.join(" | ")} |" }.join("\n") } if line.table
912
+
913
+ {}
914
+ end
915
+
916
+ #: (PickleStep) -> Symbol
173
917
  def line_kind(line) = line.kind == "Outcome" ? :then : :other
174
918
 
175
919
  # A project fixture is built the first time a step of its scope names
176
920
  # it, directly or through another fixture, and kept until the scope ends.
921
+ #: (Symbol, World, Array[Symbol]) -> untyped
177
922
  def project_fixture(name, world, chain)
178
923
  fixture = Nukadoko.project_fixtures[name] or raise ArgumentError, "the Ruby engine has no fixture #{name} yet"
179
924
  raise ArgumentError, "fixtures depend on each other in a cycle: #{[*chain, name].join(" -> ")}" if chain.include?(name)
180
925
 
181
926
  cache = fixture.scope == :process ? @process_fixtures : @scenario_fixtures
182
- return cache[name] if cache.key?(name)
183
-
184
927
  deps = fixture.dependencies.to_h do |dep|
185
928
  case dep
186
929
  when :baseURL then [dep, world.base_url]
@@ -188,15 +931,53 @@ module Nukadoko
188
931
  else [dep, project_fixture(dep, world, [*chain, name])]
189
932
  end
190
933
  end
191
- cache.build(fixture, deps)
934
+ return cache[name].tap { note_fixture(name, fixture.scope, nil, nil) } if cache.key?(name)
935
+
936
+ at = now
937
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
938
+ cache.build(fixture, deps).tap { note_fixture(name, fixture.scope, Request.since(started), at) }
939
+ end
940
+
941
+ # Each project fixture a step's bag touched, once, as the step record
942
+ # lists it: built here with its setup time, or reused from its scope.
943
+ #: (Symbol, Symbol, Integer?, String?) -> void
944
+ def note_fixture(name, scope, setup_ms, at)
945
+ return if @fixture_usage.nil? || @fixture_usage.any? { _1[:name] == name.to_s }
946
+
947
+ @fixture_usage << { name: name.to_s, scope: scope.to_s, reused: setup_ms.nil?, setup_ms: setup_ms, at: at }.compact
192
948
  end
193
949
 
194
- def build_fixtures(step, dir, log, world)
950
+ # The secrets of the environment running now, which every record
951
+ # surface is written through.
952
+ #: () -> Secrets
953
+ def secrets = @secrets || Secrets.new
954
+
955
+ # What the env fixture holds: the env files, then the world's own env.
956
+ #: (World) -> Hash[String, String]
957
+ def step_env(world) = (@env_vars || {}).merge(world.env)
958
+
959
+ # Reads an environment's env files into the env fixture and the secret
960
+ # set, from the same read, so the two agree on what was loaded.
961
+ #: (Environment) -> void
962
+ def read_env(environment)
963
+ EnvCheck.validate!
964
+ config = Nukadoko.config_options.fetch(:secrets, {}) #: Hash[Symbol, untyped]
965
+ @env_vars = EnvFile.load(@project, environment.env_files)
966
+ @secrets = Secrets.of(@project, environment.env_files, public_keys: (config[:public] || []).map(&:to_s), redact_keys: (config[:redact] || []).map(&:to_s))
967
+ rescue EnvFile::Unreadable => e
968
+ raise Refusal.new("env-file-unreadable", e.message)
969
+ end
970
+
971
+ #: (singleton(Step), String, Array[Hash[Symbol, untyped]], World, Hash[Symbol, untyped]) -> [Hash[Symbol, untyped], (^() -> void)?]
972
+ def build_fixtures(step, dir, log, world, record)
195
973
  finish = nil
974
+ @fixture_usage = []
196
975
  fixtures = (step.bag - [:call]).to_h do |name|
197
976
  case name
198
977
  when :request then [name, Request.new(world.base_url)]
199
978
  when :baseURL then [name, world.base_url]
979
+ when :env then [name, step_env(world)]
980
+ when :requireEnv then [name, ->(key) { step_env(world).fetch(key.to_s) { raise %(requireEnv("#{key}"): the world's env has no #{key}) } }]
200
981
  when :scratch then [name, @scratch]
201
982
  when :page
202
983
  page, finish = @browser.page_for(dir, log)
@@ -205,20 +986,16 @@ module Nukadoko
205
986
  end
206
987
  end
207
988
  fixtures[:call] = Caller.new(step, fixtures) if step.fixtures.include?(:call)
989
+ record[:fixtures] = @fixture_usage if @fixture_usage.any?
990
+ @fixture_usage = nil
208
991
  [fixtures, finish]
209
992
  end
210
993
 
211
- def write_summary(rows)
212
- verdicts = rows.map { _1[:verdict] }.tally.map { |v, n| "#{n} #{v}" }.join(", ")
213
- lines = ["# nukadoko run #{rows.none? { _1[:verdict] == "failed" } ? "passed" : "failed"}: #{rows.size} criteria, #{verdicts}", ""]
214
- rows.each do |r|
215
- cells = r[:cells].map { |c| "#{c[:environment]} #{c[:outcome]}#{c[:line] ? "@#{c[:line]}" : ""}#{c[:role] == "control" ? " (control)" : ""}" }
216
- lines << "- #{r[:verdict]} #{r[:feature]}:#{r[:line]} #{r[:name]} #{cells.join(", ")}"
217
- end
218
- File.write(File.join(@dir, "summary.md"), "#{lines.join("\n")}\n")
219
- end
220
-
994
+ #: (String) -> String
221
995
  def new_id(kind) = "#{kind}-#{Time.now.utc.strftime("%Y%m%d-%H%M%S")}-#{SecureRandom.alphanumeric(4).downcase}"
996
+
997
+ #: () -> String
998
+ def now = Time.now.utc.iso8601(3)
222
999
  end
223
1000
  end
224
1001
  end