nukadoko 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (159) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +417 -0
  3. data/README.ja.md +62 -7
  4. data/README.md +19 -5
  5. data/exe/nuka +8 -0
  6. data/lib/nukadoko/aria_snapshot.rb +1008 -0
  7. data/lib/nukadoko/aria_tree.rb +150 -0
  8. data/lib/nukadoko/base.rb +294 -0
  9. data/lib/nukadoko/check.rb +669 -22
  10. data/lib/nukadoko/claim_check.rb +177 -0
  11. data/lib/nukadoko/claim_check_run.rb +293 -0
  12. data/lib/nukadoko/claim_line.rb +381 -0
  13. data/lib/nukadoko/claim_rules.rb +519 -0
  14. data/lib/nukadoko/claim_sides.rb +469 -0
  15. data/lib/nukadoko/claims.rb +576 -37
  16. data/lib/nukadoko/cli.rb +814 -22
  17. data/lib/nukadoko/codes.json +947 -0
  18. data/lib/nukadoko/codes.rb +19 -0
  19. data/lib/nukadoko/command.rb +214 -12
  20. data/lib/nukadoko/criteria.rb +172 -0
  21. data/lib/nukadoko/definition.rb +33 -41
  22. data/lib/nukadoko/env_check.rb +88 -0
  23. data/lib/nukadoko/features.rb +80 -10
  24. data/lib/nukadoko/fixtures.rb +329 -11
  25. data/lib/nukadoko/http_recording.rb +68 -0
  26. data/lib/nukadoko/init.rb +129 -0
  27. data/lib/nukadoko/js_json.rb +274 -0
  28. data/lib/nukadoko/js_pattern.rb +531 -0
  29. data/lib/nukadoko/judge.rb +221 -0
  30. data/lib/nukadoko/judgment_file.rb +78 -0
  31. data/lib/nukadoko/judgments.rb +256 -0
  32. data/lib/nukadoko/literal.rb +129 -0
  33. data/lib/nukadoko/measured.rb +105 -0
  34. data/lib/nukadoko/order.rb +84 -0
  35. data/lib/nukadoko/parts.rb +43 -22
  36. data/lib/nukadoko/pattern.rb +73 -3
  37. data/lib/nukadoko/poll.rb +21 -8
  38. data/lib/nukadoko/program.rb +105 -17
  39. data/lib/nukadoko/project_files.rb +17 -0
  40. data/lib/nukadoko/project_fixtures.rb +17 -2
  41. data/lib/nukadoko/project_program.rb +119 -0
  42. data/lib/nukadoko/report_allure.rb +751 -0
  43. data/lib/nukadoko/report_messages.rb +167 -0
  44. data/lib/nukadoko/report_run.rb +169 -0
  45. data/lib/nukadoko/run.rb +898 -91
  46. data/lib/nukadoko/run_record.rb +535 -0
  47. data/lib/nukadoko/scaffold.rb +1015 -0
  48. data/lib/nukadoko/schema.rb +120 -21
  49. data/lib/nukadoko/secrets.rb +375 -0
  50. data/lib/nukadoko/selection.rb +163 -0
  51. data/lib/nukadoko/signature.rb +4 -1
  52. data/lib/nukadoko/skill.rb +36 -0
  53. data/lib/nukadoko/spaces.rb +28 -0
  54. data/lib/nukadoko/step.rb +68 -21
  55. data/lib/nukadoko/summary.rb +662 -0
  56. data/lib/nukadoko/table.rb +34 -2
  57. data/lib/nukadoko/text_fit.rb +179 -0
  58. data/lib/nukadoko/trace.rb +244 -0
  59. data/lib/nukadoko/trace_actions.rb +116 -0
  60. data/lib/nukadoko/tree_passes.rb +122 -0
  61. data/lib/nukadoko/verdict.rb +128 -0
  62. data/lib/nukadoko/version.rb +2 -1
  63. data/lib/nukadoko/vocabulary.rb +6 -0
  64. data/lib/nukadoko/walk.rb +305 -0
  65. data/lib/nukadoko/walk_files.rb +473 -0
  66. data/lib/nukadoko/walk_step.rb +149 -0
  67. data/lib/nukadoko.rb +60 -2
  68. data/llms.txt +297 -0
  69. data/sig/generated/nukadoko/aria_snapshot.rbs +331 -0
  70. data/sig/generated/nukadoko/aria_tree.rbs +142 -0
  71. data/sig/generated/nukadoko/base.rbs +142 -0
  72. data/sig/generated/nukadoko/check.rbs +255 -0
  73. data/sig/generated/nukadoko/claim_check.rbs +118 -0
  74. data/sig/generated/nukadoko/claim_check_run.rbs +88 -0
  75. data/sig/generated/nukadoko/claim_line.rbs +158 -0
  76. data/sig/generated/nukadoko/claim_rules.rbs +172 -0
  77. data/sig/generated/nukadoko/claim_sides.rbs +207 -0
  78. data/sig/generated/nukadoko/claims.rbs +208 -0
  79. data/sig/generated/nukadoko/cli.rbs +182 -0
  80. data/sig/generated/nukadoko/codes.rbs +16 -0
  81. data/sig/generated/nukadoko/command.rbs +109 -0
  82. data/sig/generated/nukadoko/criteria.rbs +83 -0
  83. data/sig/generated/nukadoko/definition.rbs +30 -0
  84. data/sig/generated/nukadoko/env_check.rbs +34 -0
  85. data/sig/generated/nukadoko/features.rbs +101 -0
  86. data/sig/generated/nukadoko/fixtures.rbs +175 -0
  87. data/sig/generated/nukadoko/http_recording.rbs +29 -0
  88. data/sig/generated/nukadoko/init.rbs +64 -0
  89. data/sig/generated/nukadoko/js_json.rbs +109 -0
  90. data/sig/generated/nukadoko/js_pattern.rbs +194 -0
  91. data/sig/generated/nukadoko/judge.rbs +64 -0
  92. data/sig/generated/nukadoko/judgment_file.rbs +39 -0
  93. data/sig/generated/nukadoko/judgments.rbs +120 -0
  94. data/sig/generated/nukadoko/literal.rbs +71 -0
  95. data/sig/generated/nukadoko/measured.rbs +42 -0
  96. data/sig/generated/nukadoko/order.rbs +54 -0
  97. data/sig/generated/nukadoko/parts.rbs +35 -0
  98. data/sig/generated/nukadoko/pattern.rbs +62 -0
  99. data/sig/generated/nukadoko/poll.rbs +41 -0
  100. data/sig/generated/nukadoko/program.rbs +101 -0
  101. data/sig/generated/nukadoko/project_files.rbs +19 -0
  102. data/sig/generated/nukadoko/project_fixtures.rbs +57 -0
  103. data/sig/generated/nukadoko/project_program.rbs +55 -0
  104. data/sig/generated/nukadoko/report_allure.rbs +268 -0
  105. data/sig/generated/nukadoko/report_messages.rbs +68 -0
  106. data/sig/generated/nukadoko/report_run.rbs +102 -0
  107. data/sig/generated/nukadoko/run.rbs +264 -0
  108. data/sig/generated/nukadoko/run_record.rbs +175 -0
  109. data/sig/generated/nukadoko/scaffold.rbs +328 -0
  110. data/sig/generated/nukadoko/schema.rbs +155 -0
  111. data/sig/generated/nukadoko/secrets.rbs +172 -0
  112. data/sig/generated/nukadoko/selection.rbs +73 -0
  113. data/sig/generated/nukadoko/signature.rbs +17 -0
  114. data/sig/generated/nukadoko/skill.rbs +20 -0
  115. data/sig/generated/nukadoko/spaces.rbs +31 -0
  116. data/sig/generated/nukadoko/step.rbs +115 -0
  117. data/sig/generated/nukadoko/summary.rbs +204 -0
  118. data/sig/generated/nukadoko/table.rbs +43 -0
  119. data/sig/generated/nukadoko/text_fit.rbs +70 -0
  120. data/sig/generated/nukadoko/trace.rbs +127 -0
  121. data/sig/generated/nukadoko/trace_actions.rbs +40 -0
  122. data/sig/generated/nukadoko/tree_passes.rbs +48 -0
  123. data/sig/generated/nukadoko/verdict.rbs +56 -0
  124. data/sig/generated/nukadoko/version.rbs +5 -0
  125. data/sig/generated/nukadoko/vocabulary.rbs +25 -0
  126. data/sig/generated/nukadoko/walk.rbs +139 -0
  127. data/sig/generated/nukadoko/walk_files.rbs +189 -0
  128. data/sig/generated/nukadoko/walk_step.rbs +50 -0
  129. data/sig/generated/nukadoko.rbs +26 -0
  130. data/sig/nukadoko.rbs +5 -48
  131. data/skills/nukadoko/SKILL.md +120 -0
  132. data/skills/nukadoko/references/checking-steps.md +200 -0
  133. data/skills/nukadoko/references/diagnosing.md +200 -0
  134. data/skills/nukadoko/references/done.md +99 -0
  135. data/skills/nukadoko/references/evidence.md +124 -0
  136. data/skills/nukadoko/references/examples/cli.md +230 -0
  137. data/skills/nukadoko/references/examples/http-api.md +342 -0
  138. data/skills/nukadoko/references/examples/workflow.md +173 -0
  139. data/skills/nukadoko/references/exploring.md +184 -0
  140. data/skills/nukadoko/references/fixtures.md +198 -0
  141. data/skills/nukadoko/references/from-prose.md +51 -0
  142. data/skills/nukadoko/references/judgments.md +95 -0
  143. data/skills/nukadoko/references/maintenance.md +97 -0
  144. data/skills/nukadoko/references/merge-risk.md +74 -0
  145. data/skills/nukadoko/references/parts.md +152 -0
  146. data/skills/nukadoko/references/perturbed-worlds.md +109 -0
  147. data/skills/nukadoko/references/program.md +200 -0
  148. data/skills/nukadoko/references/reviewing.md +200 -0
  149. data/skills/nukadoko/references/running.md +200 -0
  150. data/skills/nukadoko/references/scenario-rules.md +188 -0
  151. data/skills/nukadoko/references/states.md +66 -0
  152. data/skills/nukadoko/references/step-files.md +200 -0
  153. data/skills/nukadoko/references/verdicts.md +200 -0
  154. data/skills/nukadoko/references/writing-steps.md +200 -0
  155. data/skills/nukadoko/references/writing-the-feature.md +165 -0
  156. data/skills/nukadoko/scripts/claude-code-verdict-hook.mjs +99 -0
  157. data/skills/nukadoko/scripts/merge-risk.jq +56 -0
  158. data/skills/nukadoko-verification/SKILL.md +263 -0
  159. metadata +133 -1
data/lib/nukadoko/cli.rb CHANGED
@@ -1,26 +1,117 @@
1
1
  # frozen_string_literal: true
2
+ # rbs_inline: enabled
2
3
 
3
4
  # The `nuka` command. With --json it prints one envelope in the shape the
4
5
  # TypeScript engine prints, so an agent reads both engines the same way.
5
6
  module Nukadoko
6
7
  class CLI
8
+ FLAGS = %w[--json --no-check --dry-run --then --replace --allure --records --meets --misses --step].freeze
9
+ REPEATED = %w[--tag --env --use].freeze
10
+ VALUED = %w[--format --out --base --repeat --concurrency --order --proof-runs --args --pattern --description --feature --command --request --from --cwd --body --argv
11
+ --run --by --because --walk --timeout].freeze
12
+
13
+ #: (Array[String], ?project: String, ?out: IO) -> void
7
14
  def initialize(argv, project: Dir.pwd, out: $stdout)
8
15
  @command, *rest = argv
9
- @json = rest.delete("--json")
10
- @no_check = rest.delete("--no-check")
11
- @rest = rest
16
+ @words = rest.dup
17
+ @options = Hash.new { |h, k| h[k] = [] }
18
+ @rest = []
19
+ @unknown = []
20
+ parse(rest)
21
+ @json = @options.key?("--json")
22
+ @no_check = @options.key?("--no-check")
12
23
  @project = File.expand_path(project)
13
24
  @out = out
14
25
  end
15
26
 
27
+ # The commands by what a user reaches them for, in the TypeScript
28
+ # engine's words, so `nuka --help` reads the same in both.
29
+ HELP = <<~TEXT
30
+ nuka <command>
31
+
32
+ Everyday:
33
+ nuka init set up a project; ends with a self-check
34
+ nuka scaffold [name] typed step template that fails until implemented
35
+ nuka check [feature..] static checks: pattern/schema mismatches, claim steps
36
+ and where they are bound, undefined steps per feature,
37
+ duplicate patterns, config coherence, and notes on
38
+ unused declarations
39
+ nuka run [feature..] check, then execute scenarios from a feature file or a
40
+ directory of them (features/ when none is given);
41
+ step records + run.json
42
+ nuka report [run] render a finished run as Markdown, Allure results, or
43
+ a cucumber-messages stream, from its run directory
44
+ alone
45
+ nuka verdict say whether the newest run judged the working tree as
46
+ it is now and left nothing red; exits 1 when it did
47
+ not, and never starts a run
48
+ nuka judge <target> show the values a run read for a criterion whose Then
49
+ asks for a judgment (<feature file>:<scenario line>),
50
+ or record a judgment of them with --meets or --misses
51
+ nuka steps list the whole vocabulary: name, patterns,
52
+ description, mutates
53
+ nuka describe <name> full contract, schemas as JSON Schema
54
+
55
+ Exploring:
56
+ nuka do <name> execute one typed step; step record to stdout
57
+ nuka step follow and answer a walk of nuka run --step, one pause
58
+ at a time
59
+
60
+ Upkeep:
61
+ nuka clean delete accumulated runs, do records, and what nuka
62
+ report wrote under export/, in the state directory
63
+ nuka skill path the agent-facing skills' source directory
64
+ nuka sig write sig/nukadoko/steps.rbs, the RBS of each step's
65
+ args and returns, for Steep
66
+
67
+ Options:
68
+ --version Show version number
69
+ --help Show help
70
+
71
+ An agent starts at the llms.txt in the gem's directory, the one above what
72
+ nuka skill path prints: the loop, every command, and every finding code.
73
+ Its Ruby section is how a Ruby step and the project files are written.
74
+ TEXT
75
+ COMMANDS = %w[init scaffold check run report verdict judge steps describe do step clean skill sig __tree].freeze
76
+
77
+ #: () -> Integer
16
78
  def call
17
- %w[nukadoko.config.rb nukadoko.program.rb].each do |name|
18
- file = File.join(@project, name)
19
- load file if File.exist?(file)
79
+ if @command == "--help"
80
+ @out.write(HELP)
81
+ return 0
82
+ end
83
+ if @command == "--version"
84
+ @out.puts VERSION
85
+ return 0
86
+ end
87
+ unless COMMANDS.include?(@command)
88
+ @out = $stderr
89
+ message = @command.nil? ? "Not enough non-option arguments: got 0, need at least 1" : "Unknown argument: #{@command}"
90
+ return refuse(Engine::Refusal.new("invalid-arguments", message, run: "nuka --help"))
91
+ end
92
+ return refuse(Engine::Refusal.new("invalid-arguments", "Unknown argument: #{@unknown.first}")) if @unknown.any?
93
+ return verdict if @command == "verdict"
94
+ return Judge.new(@project, @rest, @options, json: @json, out: @out).call if @command == "judge"
95
+ return report if @command == "report"
96
+ return clean if @command == "clean"
97
+ return Walked.new(@project, @rest, @options, json: @json, out: @out).call if @command == "step"
98
+ return skill if @command == "skill"
99
+ return init if @command == "init"
100
+
101
+ begin
102
+ Nukadoko.load_project(@project)
103
+ rescue Engine::Refusal => e
104
+ return refuse(e)
20
105
  end
21
106
  steps = Nukadoko.load_steps(File.join(@project, "features", "steps"))
22
- scenarios = Dir.chdir(@project) { Engine.load_features("features") }
23
- check = Engine::Check.new(steps, scenarios)
107
+ problems = []
108
+ scenarios = Dir.chdir(@project) { Engine.load_features("features", problems: problems) }
109
+ declared = (Nukadoko.program_options[:environments] || {}).values.flat_map { (_1[:conditions] || {}).keys.map(&:to_s) }
110
+ # condition-unmet is judged for the selection a run without --env
111
+ # starts; a selection --env names is a choice of where to run.
112
+ selected = (Engine::Program.new(Nukadoko.program_options).environments if Array(@options["--env"]).empty?) rescue nil
113
+ check = Engine::Check.new(steps, scenarios, features: Dir.exist?(File.join(@project, "features")), full: @command == "check",
114
+ conditions: declared, environments: selected, problems: problems, config: env_findings)
24
115
  findings = check.findings.map { relative(_1).to_h }
25
116
  case @command
26
117
  when "check" then finish("check", check.passed?, findings: findings)
@@ -45,32 +136,733 @@ module Nukadoko
45
136
  end
46
137
 
47
138
  finish("describe", true, findings: findings, **Vocabulary.describe(step, @project))
48
- when "run"
49
- return finish("run", false, findings: findings) unless @no_check || check.passed?
50
-
51
- result = Engine::Run.new(@project, check.usable, scenarios, Nukadoko.program_options, out: @json ? $stderr : @out).call
52
- passed = result.delete(:passed)
53
- finish("run", passed, findings: findings, **result)
139
+ when "run" then @options.key?("--step") ? walk(steps) : run(steps)
140
+ when "do" then run_one(check)
141
+ when "scaffold" then scaffold(steps, scenarios)
142
+ when "__tree" then tree(steps)
54
143
  else
55
- warn "usage: nuka check|run|steps|describe <step>|sig [--json] [--no-check]"
56
- 2
144
+ raise "unreachable: #{@command} is in COMMANDS but has no branch"
57
145
  end
58
146
  end
59
147
 
60
148
  private
61
149
 
150
+ # `--name value` and `--name=value` for the repeated options, bare
151
+ # flags, and every other word a target. An unknown `--name` is kept to
152
+ # refuse, so a typo never reads as a target or is silently ignored.
153
+ #: (Array[String]) -> void
154
+ def parse(words)
155
+ until words.empty?
156
+ word = words.shift
157
+ name, value = word.split("=", 2)
158
+ name = name.to_s
159
+ if REPEATED.include?(name) || VALUED.include?(name)
160
+ # `--command` alone leaves the entry point a TODO, so a flag after
161
+ # it is the next option, not its value.
162
+ value ||= "" if name == "--command" && (words.empty? || words.first.start_with?("--"))
163
+ @command_before_name = @rest.empty? if name == "--command" && !word.include?("=")
164
+ value ||= words.shift
165
+ next @unknown << name.delete_prefix("--") if value.nil?
166
+
167
+ @options[name] << value
168
+ elsif FLAGS.include?(word) then @options[word]
169
+ elsif word.start_with?("--") then @unknown << name.delete_prefix("--")
170
+ else @rest << word
171
+ end
172
+ end
173
+ end
174
+
175
+ # `nuka run --step`: a run of one scenario that pauses after each step
176
+ # until `nuka step` answers. The walk is recorded before anything else,
177
+ # so every way the run stops reaches a `nuka step` waiting for it: a
178
+ # refusal or nothing selected ends it as not run, with what the run
179
+ # printed; a signal, which is what ends a pause nobody answers, as
180
+ # interrupted; an exception as an error.
181
+ #: (Array[singleton(Step)]) -> Integer
182
+ def walk(steps)
183
+ targets = @rest.empty? ? ["features"] : @rest
184
+ @walk_target = [*targets, *@options["--env"].flat_map { ["--env", _1] }].map { Engine::Selection.shell_word(_1) }.join(" ")
185
+ opened = Engine::WalkFiles.open(@project, @walk_target, announce: @json ? nil : ->(text) { $stderr.write(text) })
186
+ if opened.is_a?(Hash)
187
+ return refuse(Engine::Refusal.new("walk-in-progress", opened[:message], run: "nuka step wait"))
188
+ end
189
+
190
+ @walk = opened
191
+ previous = { "INT" => 130, "TERM" => 143 }.to_h do |name, code|
192
+ [name, Signal.trap(name) do
193
+ opened.end({ how: "interrupted", exit_code: code, signal: "SIG#{name}" })
194
+ exit(code)
195
+ end]
196
+ end
197
+ code = run(steps)
198
+ opened.end({ how: "not-run", exit_code: code, findings: @stopped_with || [] })
199
+ code
200
+ rescue StandardError => e
201
+ opened.end({ how: "error", exit_code: 1, findings: [{ severity: "error", code: "unexpected-error", message: e.message }] }) if opened.is_a?(Engine::WalkFiles::Handle)
202
+ raise
203
+ ensure
204
+ previous&.each { |name, handler| Signal.trap(name, handler || "DEFAULT") }
205
+ end
206
+
207
+ # Why a walk cannot walk this run, raised as step-needs-one-scenario: a
208
+ # walk is one execution of one scenario, in one environment, where its
209
+ # conditions hold, since a control would run again for its proof.
210
+ #: (Array[Engine::Scenario], Array[Engine::Environment]) -> void
211
+ def one_execution(kept, environments)
212
+ first = kept.first
213
+ at = Engine::Selection.shell_word("#{first.uri}:#{first.line}")
214
+ envs = @options["--env"].flat_map { ["--env", Engine::Selection.shell_word(_1)] }
215
+ reason, again = if kept.size > 1
216
+ ["the targets select #{kept.size} scenarios", Engine::Walk.restart_command([at, *envs].join(" "))]
217
+ elsif environments.size > 1
218
+ ["it runs in #{environments.size} environments (#{environments.map(&:name).join(", ")})",
219
+ Engine::Walk.restart_command([at, "--env", Engine::Selection.shell_word(environments.first.name)].join(" "))]
220
+ elsif Engine::Table.role(Engine::Table.condition_tags(first.tags), environments.first.conditions) == "control"
221
+ ["the scenario's conditions do not hold in #{environments.first.name}, so it would run as a control"]
222
+ end
223
+ return unless reason
224
+
225
+ raise Engine::Refusal.new("step-needs-one-scenario", "nuka run --step walks one execution of one scenario, and #{reason}", run: again)
226
+ end
227
+
228
+ # A run checks the scenarios it selected, then runs them in each world
229
+ # it selected; a target or a world it cannot reach is refused first.
230
+ #: (Array[singleton(Step)]) -> Integer
231
+ def run(steps)
232
+ repeat = count_flag("--repeat")
233
+ concurrency = count_flag("--concurrency")
234
+ Engine::Table.proof_runs = count_flag("--proof-runs")
235
+ order = Engine::Order.read(@options["--order"].last)
236
+ unless order
237
+ raise Engine::Refusal.new("invalid-value", "--order must be file, shuffled, or shuffled:<seed> with a whole number from 0 to #{Engine::Order::MAX_SEED} (got #{JSON.generate(@options["--order"].last)}).")
238
+ end
239
+
240
+ # Progress is stderr's, so stdout holds only what was asked for: the
241
+ # records under --records, the envelope under --json. Under --json
242
+ # nothing else is written, and a warning is a finding in the envelope.
243
+ records = @options.key?("--records") ? @out : nil
244
+ progress = @json ? File.open(File::NULL, "w") : $stderr
245
+ ref = @options["--base"].last
246
+ if @walk && (repeat > 1 || ref)
247
+ why = repeat > 1 ? "--repeat #{repeat} runs it #{repeat} times" : "--base runs it in more than one world"
248
+ raise Engine::Refusal.new("step-needs-one-scenario", "nuka run --step walks one execution of one scenario, and #{why}",
249
+ run: Engine::Walk.restart_command(@walk_target))
250
+ end
251
+ commit = ref && Engine::Base.resolve(@project, ref)
252
+ selection = Engine::Selection.new(@project, @rest, @options["--tag"])
253
+ program = Engine::Program.new(Nukadoko.program_options)
254
+ environments = program.environments(@options["--env"])
255
+ # A scenario whose conditions hold in no environment of the run is
256
+ # left out, and counted, since no cell of it could show it holds.
257
+ kept, left_out = selection.scenarios.partition { meets?(_1, environments) }
258
+ kept = Engine::Order.arrange(kept, order)
259
+ # Without --env, a scenario no environment meets is a check error,
260
+ # condition-unmet; a selection --env names leaves it out instead.
261
+ default = @options["--env"].empty?
262
+ declared = program.declared.values.flat_map { (_1[:conditions] || {}).keys.map(&:to_s) }
263
+ check = Engine::Check.new(steps, default ? selection.scenarios : kept, conditions: declared,
264
+ environments: (environments if default), problems: selection.problems, config: env_findings)
265
+ # The TypeScript engine refuses a declaration as its step file loads, so
266
+ # such a step file stops its run even under --no-check, naming the
267
+ # first one.
268
+ if @no_check && (failed = check.findings.find { _1.code == "step-file-import-failed" })
269
+ failed = relative(failed)
270
+ stop = { severity: "refused", code: failed.code, message: "#{failed.file}: #{failed.message}", fix: failed.fix, do: "nuka check" }
271
+ return finish("run", false, findings: [stop], verdict: "refused", exit_code: 2)
272
+ end
273
+ # Only the check's errors hold a run back, so only they are reported.
274
+ findings = @no_check ? [] : check.findings.map { relative(_1).to_h }.select { _1[:severity] == "error" }
275
+ unless @no_check || check.passed?
276
+ errors = findings.select { _1[:severity] == "error" }
277
+ stop = { severity: "refused", code: "check-errors",
278
+ message: "nuka run did not start: nuka check reports #{errors.size} #{errors.size == 1 ? "error" : "errors"} for these scenarios",
279
+ fix: "Correct each error the findings name, or pass --no-check to run anyway.", do: check_command }
280
+ return finish("run", false, findings: errors + [stop], verdict: "refused", exit_code: 2)
281
+ end
282
+ if kept.empty? && left_out.any?
283
+ return finish("run", false, findings: [left_out_stop(left_out, program)], verdict: "failed", exit_code: 1)
284
+ end
285
+ one_execution(kept, environments) if @walk && kept.any?
286
+
287
+ dir = File.join(@project, ".nukadoko", "runs", "run-#{Time.now.utc.strftime("%Y%m%d-%H%M%S")}-#{SecureRandom.alphanumeric(4).downcase}")
288
+ base = if commit
289
+ targets = @rest.empty? ? nil : @rest.map { _1.sub(/:\d+\z/, "") }
290
+ Engine::Base.new(project: @project, ref: ref, commit: commit, run_dir: dir, selected: kept.map { Engine::Criteria.key(_1.uri, _1.line) },
291
+ targets: targets, envs: @options["--env"], head_program: Nukadoko.program_options)
292
+ end
293
+ # Workers are handed whole feature files, so one file has nothing to
294
+ # spread across them.
295
+ if concurrency > 1 && kept.map(&:uri).uniq.size <= 1
296
+ progress.puts "--concurrency has nothing to distribute: this run selects one feature file."
297
+ concurrency = 1
298
+ end
299
+ result = Engine::Run.new(@project, check.usable, kept, Nukadoko.program_options,
300
+ environments: environments, left_out: left_out.size, out: progress,
301
+ dir: dir, base: base, env_flags: @options["--env"].flat_map { ["--env", _1] },
302
+ repeat: repeat, concurrency: concurrency, order: order, records: records, walk: @walk,
303
+ rerun: { targets: @rest, tags: @options["--tag"].flat_map { ["--tag", _1] }, whole_files: selection.whole_files }).call
304
+ passed = result.delete(:passed)
305
+ findings += result.delete(:failures)
306
+ started = result.slice(:run_id, :run_dir, :started_at, :finished_at, :commit, :environments, :worlds)
307
+ rest = result.except(*started.keys)
308
+ envelope = { **head("run", passed ? "passed" : "failed", findings, check: @no_check ? "skipped" : "ran"),
309
+ **started, selection: selection.selection, tag_selection: selection.tag_selection, **rest } #: Hash[Symbol, untyped]
310
+ envelope.delete(:tag_selection) unless envelope[:tag_selection]
311
+ # The limits restate the fields above, so they are read from them,
312
+ # and a run with none has no field.
313
+ limits = Engine::Summary.limits(JSON.parse(JSON.generate(envelope), symbolize_names: true))
314
+ envelope[:limits] = limits if limits.any?
315
+ File.write(File.join(@project, result[:run_dir], "run.json"), "#{JSON.pretty_generate(envelope)}\n")
316
+ # The summary is rendered from run.json as written, so it can say
317
+ # nothing the record does not.
318
+ written = JSON.parse(JSON.generate(envelope), symbolize_names: true)
319
+ File.write(File.join(@project, result[:run_dir], "summary.md"), Engine::Summary.render(written))
320
+ # After run.json, so a `nuka step` that reads the walk as ended finds
321
+ # the run's record there.
322
+ scenarios = envelope[:scenarios] #: Array[Hash[Symbol, untyped]]
323
+ stopped = scenarios.find { _1[:stopped] }&.dig(:stopped)
324
+ @walk&.end({ how: "finished", exit_code: passed ? 0 : 1, findings: findings, **(stopped ? { stopped: stopped } : {}) })
325
+ unless @json
326
+ written = Dir.children(File.join(@project, result[:run_dir], "steps")).size
327
+ steps_dir = "#{File.join(result[:run_dir], "steps")}/"
328
+ progress.puts "steps #{steps_dir.ljust([30, steps_dir.size + 2].max)}#{written}" if envelope[:counts][:scenarios].positive?
329
+ progress.puts "summary #{File.join(result[:run_dir], "summary.md")}"
330
+ progress.puts "run #{File.join(result[:run_dir], "run.json")}"
331
+ run_end(envelope, progress)
332
+ end
333
+ emit(envelope, findings, "run", io: progress)
334
+ if limits.any? && !@json
335
+ progress.puts "limits: #{limits.group_by { _1[:kind] }.map { |kind, group| "#{group.size} #{kind}" }.join(", ")} (run.json limits)"
336
+ end
337
+ repeat_tallies(scenarios, progress) if repeat > 1 && !@json
338
+ passed ? 0 : 1
339
+ rescue Engine::Refusal => e
340
+ refuse(e)
341
+ end
342
+
343
+ # `--repeat`, `--concurrency`, and `--proof-runs` take a whole number of 1 or more.
344
+ #: (String) -> Integer
345
+ def count_flag(name)
346
+ value = @options[name].last
347
+ return 1 if value.nil? && name != "--proof-runs"
348
+ return Engine::Table::PROOF_RUNS if value.nil?
349
+
350
+ number = Integer(value, 10, exception: false)
351
+ return number if number && number >= 1
352
+
353
+ raise Engine::Refusal.new("invalid-value", "#{name} must be a whole number of 1 or more (got #{value}).")
354
+ end
355
+
356
+ # One pass of a `--base` tree, in the tree's own directory: the plan
357
+ # names the world, the environment, and the rows at their place in this
358
+ # tree, and the result goes to the file it names.
359
+ #: (Array[singleton(Step)]) -> Integer
360
+ def tree(steps)
361
+ plan = JSON.parse(File.read(@rest.first), symbolize_names: true)
362
+ found = Dir.chdir(@project) { Engine.load_features(plan[:targets].map { _1[:feature] }.uniq) }
363
+ scenarios = plan[:targets].filter_map { |target| found.find { _1.uri == target[:feature] && _1.line == target[:line] } }
364
+ result = begin
365
+ environment = Engine::Program.new(Nukadoko.program_options).environments([plan[:environment]]).first
366
+ usable = Engine::Check.new(steps, scenarios).usable
367
+ run = Engine::Run.new(@project, usable, scenarios, Nukadoko.program_options, environments: [environment],
368
+ world: plan[:world], dir: plan[:dir], out: @out, head: plan[:head])
369
+ { results: run.tree_pass, worlds: run.world_entries }
370
+ rescue Engine::Refusal => e
371
+ { not_run: "the #{plan[:world]} tree's program does not give this environment: #{e.message}" }
372
+ end
373
+ File.write(plan[:result], JSON.generate(result))
374
+ 0
375
+ end
376
+
377
+ # `nuka do <step>`: one step alone, its args from --args and from the
378
+ # records --use names, in a world started for it. The step record goes
379
+ # to stdout and to .nukadoko/do/<id>/record.json, where a later
380
+ # `nuka do --use` reads it. A refusal goes to stderr, since stdout is
381
+ # the record's.
382
+ # Paths written go to stdout, notes and refusals to stderr.
383
+ #: () -> Integer
384
+ def init
385
+ @out = $stderr
386
+ return refuse(Engine::Refusal.new("invalid-arguments", "Unknown argument: json")) if @json
387
+ return refuse(Engine::Refusal.new("invalid-arguments", "--allure is not in the Ruby engine yet")) if @options.key?("--allure")
388
+
389
+ result = Engine::Init.new(@project, out: $stdout, err: $stderr).call
390
+ result.is_a?(Engine::Refusal) ? refuse(result) : result
391
+ end
392
+
393
+ # Writes stubs; their paths go to stdout, and notes and refusals to stderr.
394
+ #: (Array[singleton(Step)], Array[Engine::Scenario]) -> Integer
395
+ def scaffold(steps, scenarios)
396
+ @out = $stderr
397
+ return refuse(Engine::Refusal.new("invalid-arguments", "Unknown argument: json")) if @json
398
+ if @rest.empty? && !@options.key?("--feature")
399
+ missing = "Missing required argument: name (or --feature <path>)"
400
+ took = @options.fetch("--command", []).last.to_s
401
+ missing += "\n#{Engine::Scaffold.command_took_the_name(took)}" if took.match?(Engine::Scaffold::VALID_NAME)
402
+ return refuse(Engine::Refusal.new("invalid-arguments", missing))
403
+ end
404
+
405
+ scaffold = Engine::Scaffold.new(@project, @options, @rest, steps, scenarios)
406
+ scaffold.argv_words = @words.map { Engine::Selection.shell_word(_1) }
407
+ scaffold.command_before_name = @command_before_name || false
408
+ result = scaffold.call
409
+ return refuse(result) if result.is_a?(Engine::Refusal)
410
+
411
+ written, notes = result
412
+ written.each { $stdout.puts _1 }
413
+ notes.each { $stderr.puts _1 }
414
+ 0
415
+ end
416
+
417
+ #: (Engine::Check) -> Integer
418
+ def run_one(check)
419
+ @out = $stderr
420
+ return refuse(Engine::Refusal.new("invalid-arguments", "Unknown argument: json")) if @json
421
+
422
+ name = @rest.first
423
+ step = check.usable.find { _1.step_name == name }
424
+ return refuse(Engine::Refusal.new("unknown-step", "Unknown step: #{name}", fix: "Name a step that nuka steps lists.", run: "nuka steps")) unless step
425
+
426
+ describe = "nuka describe #{name}"
427
+ args_fix = "Pass --args as a JSON object with the keys that nuka describe <step> lists."
428
+ given = {}
429
+ if (text = @options["--args"].last)
430
+ begin
431
+ given = JSON.parse(text)
432
+ rescue JSON::ParserError => e
433
+ return refuse(Engine::Refusal.new("step-args-invalid", "Invalid JSON for --args: #{e.message.lines.first.strip}", fix: args_fix, run: describe))
434
+ end
435
+ return refuse(Engine::Refusal.new("step-args-invalid", "--args must be a JSON object", fix: args_fix, run: describe)) unless given.is_a?(Hash)
436
+ end
437
+ args, origins, used = used_args(step, @options["--use"])
438
+ if @options["--args"].empty? && (step.args.fields.map { _1.name.to_s } - args.keys).any?
439
+ return refuse(Engine::Refusal.new("step-args-invalid", "--args is required unless --use supplies this step's arguments", fix: args_fix, run: describe))
440
+ end
441
+
442
+ args = given.merge(args.reject { |key, _| given.key?(key) })
443
+ given.each_key { origins[_1] = "command_line:#{_1}" }
444
+ environment = Engine::Program.new(Nukadoko.program_options).environments(@options["--env"].last(1)).first
445
+ id = "step-#{Time.now.utc.strftime("%Y%m%d-%H%M%S")}-#{SecureRandom.alphanumeric(4).downcase}"
446
+ dir = File.join(@project, ".nukadoko", "do", id)
447
+ run = Engine::Run.new(@project, check.usable, [], Nukadoko.program_options, environments: [environment], dir: dir, out: $stderr)
448
+ texts = given.to_h { |key, value| [key, JSON.generate(value)] }
449
+ record = run.do_step(step, args, origins, texts, environment)
450
+ written = run.redact(do_record(record, id, step, given, origins, used, environment))
451
+ File.write(File.join(dir, "record.json"), JSON.pretty_generate(written))
452
+ $stdout.puts JSON.pretty_generate(written)
453
+ record[:status] == "passed" ? 0 : 1
454
+ rescue Engine::Refusal => e
455
+ refuse(e)
456
+ end
457
+
458
+ # Each from key of the step, from the newest record --use names whose
459
+ # step gives it, and where it came from.
460
+ #: (singleton(Step), Array[String]) -> [Hash[untyped, untyped], Hash[untyped, String], Array[Hash[Symbol, untyped]]]
461
+ def used_args(step, ids)
462
+ records = ids.map do |id|
463
+ path = [File.join(@project, ".nukadoko", "do", id, "record.json"), *Dir.glob(File.join(@project, ".nukadoko", "runs", "*", "steps", id, "record.json"))].find { File.exist?(_1) }
464
+ unless path
465
+ raise Engine::Refusal.new("step-inputs-invalid", "--use #{id}: no such step record. A step record is removed with its run once the run is older than the newest 20 runs, " \
466
+ "and a nuka do record once it is older than 7 days (retention in nukadoko.config.rb)")
467
+ end
468
+ [id, JSON.parse(File.read(path))]
469
+ end
470
+ args = {}
471
+ origins = {}
472
+ used = []
473
+ step.from.each do |key, sources|
474
+ sources.each do |cls, source_key|
475
+ id, found = records.reverse.find { |_, record| record["step"] == cls.step_name && record["result"].is_a?(Hash) && record["result"].key?(source_key.to_s) }
476
+ next unless found
477
+
478
+ args[key] = found["result"][source_key.to_s]
479
+ origins[key] = "from:#{cls.step_name}@#{id}.#{source_key}"
480
+ used << { step_record_id: id, step: cls.step_name, result: found["result"] } unless used.any? { _1[:step_record_id] == id }
481
+ break
482
+ end
483
+ end
484
+ [args, origins, used]
485
+ end
486
+
487
+ # The record `nuka do` prints, in the TypeScript engine's shape.
488
+ #: (Hash[Symbol, untyped], String, singleton(Step), Hash[untyped, untyped], Hash[untyped, String], Array[Hash[Symbol, untyped]], Engine::Environment) -> Hash[Symbol, untyped]
489
+ def do_record(record, id, step, given, origins, used, environment)
490
+ args_origin = (record[:args] || {}).keys.to_h do |key|
491
+ origin = origins[key]
492
+ if origin&.start_with?("from:")
493
+ step_name, rest = origin.delete_prefix("from:").split("@", 2)
494
+ record_id, source_key = rest.to_s.split(".", 2)
495
+ [key, { from: { step_record_id: record_id, step: step_name, key: source_key } }]
496
+ else [key, "command_line"]
497
+ end
498
+ end
499
+ passed = record[:status] == "passed"
500
+ outcome = passed ? { result: record[:result] || {}, returns_dropped: record[:returns_dropped] || [] } : { error: { message: record[:error], kind: record[:error_kind] } }
501
+ processes = record[:processes]
502
+ { schema_version: Engine::RunRecord::SCHEMA_VERSION, nukadoko: VERSION, step_record_id: id, step: step.step_name, kind: "do",
503
+ args: record[:args] || given, args_origin: args_origin, **outcome, status: record[:status], environment: environment.name,
504
+ world_name: nil, scenario_record_id: nil, run_id: nil, started_at: record[:started_at], finished_at: record[:finished_at],
505
+ evidence: { dir: File.join(".nukadoko", "do", id), screenshots: [] },
506
+ observed: { processes: processes&.any? ? processes : nil,
507
+ http: record[:http_count]&.positive? ? record[:http_count] : nil, files: nil, unmeasured: [] },
508
+ mutates: record[:mutates], **(used.any? ? { used: used } : {}),
509
+ **(record[:claim_records] ? { claims: record[:claim_records], observation: record[:observation] || "observed", attempts: 1 } : {}) }
510
+ end
511
+
512
+ #: (Engine::Scenario, Array[Engine::Environment]) -> bool
513
+ def meets?(scenario, environments)
514
+ tags = Engine::Table.condition_tags(scenario.tags)
515
+ environments.any? { Engine::Table.role(tags, _1.conditions) == "required" }
516
+ end
517
+
518
+ # The `nuka check` that reports the same errors: the files the targets
519
+ # name, and each --env.
520
+ #: () -> String
521
+ def check_command
522
+ files = @rest.map { _1.sub(/:\d+\z/, "") }.uniq
523
+ ["nuka check", *files.map { Engine::Selection.shell_word(_1) }, *@options["--env"].flat_map { ["--env", Engine::Selection.shell_word(_1)] }].join(" ")
524
+ end
525
+
526
+ # Why --env left out every selected scenario, and the run that meets
527
+ # them: the run without --env when it does, else the first environment
528
+ # of the program that meets each, or else one that meets some.
529
+ #: (Array[Engine::Scenario], Engine::Program) -> Hash[Symbol, String]
530
+ def left_out_stop(left_out, program)
531
+ envs = @options["--env"]
532
+ count = left_out.size
533
+ them = count == 1 ? "it" : "them"
534
+ meets_each = ->(names) { left_out.all? { meets?(_1, names.map { |name| program.environment(name) }) } }
535
+ defaults = program.default_names
536
+ without = "A run without --env selects #{defaults.join(", ")} (#{program.chosen_by})"
537
+ rerun = ->(env) { ["nuka run", *[*@rest, *env].map { Engine::Selection.shell_word(_1) }].join(" ") }
538
+ message = "no scenario to run: the conditions of the #{count} selected #{count == 1 ? "scenario" : "scenarios"} hold in no environment --env names (#{envs.join(", ")}), so nothing was checked"
539
+ finding = { severity: "failed", code: "nothing-selected", message: message }
540
+ return finding.merge(fix: "#{without}, which meets #{them}.", do: rerun.([])) if meets_each.(defaults)
541
+
542
+ candidates = [*program.declared.keys, *(program.declared.key?("default") ? [] : ["default"])] - envs
543
+ other = candidates.find { meets_each.([_1]) } || candidates.find { |name| left_out.any? { meets?(_1, [program.environment(name)]) } }
544
+ unless other
545
+ return finding.merge(fix: "#{without}, which does not meet #{them} either, and no environment of nukadoko.config.rb meets #{them}. " \
546
+ "Declare the conditions #{count == 1 ? "it needs" : "they need"} on an environment, or change #{count == 1 ? "its" : "their"} tags.")
547
+ end
548
+
549
+ finding.merge(fix: "#{without}, which does not meet #{them} either. #{other} meets #{meets_each.([other]) ? them : "some of them"}.",
550
+ do: rerun.(["--env", other]))
551
+ end
552
+
553
+ # Removes what runs left in the state directory: each run directory,
554
+ # each `nuka do` record, the Allure results nukadoko wrote, and the
555
+ # directories an earlier release left. --dry-run lists them only.
556
+ #: () -> Integer
557
+ def clean
558
+ state = File.join(@project, ".nukadoko")
559
+ listed = ->(dir) { Dir.children(File.join(state, dir)).select { File.directory?(File.join(state, dir, _1)) }.sort.map { ".nukadoko/#{dir}/#{_1}" } rescue [] }
560
+ results = File.join(state, "export", "allure-results")
561
+ # The run of a live walk stays: it still writes there, and `nuka
562
+ # step` answers through it. A walk still starting may have made its
563
+ # directory without naming it yet, so every run with no run.json
564
+ # stays while it starts.
565
+ live = Engine::WalkFiles.live_run(@project)
566
+ runs, kept = listed.("runs").partition do |dir|
567
+ next true unless live
568
+
569
+ live[:run_dir] == "starting" ? File.exist?(File.join(@project, dir, "run.json")) : dir != live[:run_dir]
570
+ end
571
+ plan = {
572
+ records: runs + listed.("do"),
573
+ export: File.directory?(results) && !Dir.empty?(results) ? [".nukadoko/export/allure-results"] : [],
574
+ legacy: %w[cache records].select { File.directory?(File.join(state, _1)) }.map { ".nukadoko/#{_1}" },
575
+ kept: kept
576
+ }
577
+ walk = live&.dig(:walk)
578
+ notes = kept.map do |dir|
579
+ { severity: "note", code: "walk-run-kept", message: "kept #{dir}: walk #{walk} is live and its run writes there", do: Engine::Walk.wait_command(walk.to_i) }
580
+ end
581
+ dry_run = @options.key?("--dry-run")
582
+ gone = plan[:records] + plan[:export] + plan[:legacy]
583
+ if @json
584
+ emit({ **head("clean", "passed", notes), **plan, dry_run: dry_run }, notes, "clean")
585
+ else
586
+ gone.each { @out.puts _1 }
587
+ @out.puts "ok: nothing to clean" if gone.empty?
588
+ notes.each { $stderr.puts [_1[:severity], _1[:code], Engine::Summary.where_of(_1), _1[:message]].join("\t"), " do: #{_1[:do]}" }
589
+ end
590
+ return 0 if dry_run
591
+
592
+ gone.each { FileUtils.rm_rf(File.join(@project, _1)) }
593
+ # An `allure watch` already pointed at the results directory keeps
594
+ # finding it.
595
+ FileUtils.mkdir_p(results) if plan[:export].any?
596
+ 0
597
+ end
598
+
599
+ # `nuka skill path`, the one verb, as the TypeScript engine has it.
600
+ #: () -> Integer
601
+ def skill
602
+ verb = @rest.first
603
+ return Skill.print_path(@out, $stderr) if verb == "path" && @rest.size == 1
604
+ return refuse(Engine::Refusal.new("invalid-arguments", "Not enough non-option arguments: got 0, need at least 1")) if verb.nil?
605
+
606
+ refuse(Engine::Refusal.new("invalid-arguments", "Unknown argument: #{(@rest - ["path"]).first || verb}"))
607
+ end
608
+
609
+ # Renders a finished run again from its run.json alone: the run a
610
+ # directory names, or the newest one.
611
+ #: () -> Integer
612
+ def report
613
+ format = @options["--format"].last
614
+ out = @options["--out"].last
615
+ raise Engine::Refusal.new("invalid-arguments", "Missing required argument: format") unless format
616
+ unless %w[markdown allure messages].include?(format)
617
+ raise Engine::Refusal.new("invalid-arguments", %(Invalid values:; Argument: format, Given: #{JSON.generate(format)}, Choices: "markdown", "allure", "messages"))
618
+ end
619
+ if @json && !out && format != "allure"
620
+ raise Engine::Refusal.new("invalid-arguments", "nuka report --json needs --out for --format #{format}, since the #{format} output itself would go to stdout",
621
+ fix: "Add --out <path>.")
622
+ end
623
+
624
+ dir = report_dir
625
+ kind = format == "allure" ? :dir : :file
626
+ target = out ? File.expand_path(out, @project) : (File.join(@project, ".nukadoko", "export", "allure-results") if kind == :dir)
627
+ label = out ? "--out #{out}" : "the default allure directory #{target && shown_path(target)}"
628
+ if target && (problem = out_problem(target, kind, label))
629
+ raise Engine::Refusal.new("report-out-invalid", problem)
630
+ end
631
+
632
+ problems = [] #: Array[String]
633
+ if format == "markdown"
634
+ doc = JSON.parse(File.read(File.join(dir, "run.json"), encoding: "UTF-8"), symbolize_names: true)
635
+ text = Engine::Summary.render(doc)
636
+ else
637
+ run = Engine::ReportRun.new(dir, project_root: @project)
638
+ doc = run.document
639
+ text = Engine::ReportMessages.render(run) if format == "messages"
640
+ problems = run.problems.dup
641
+ end
642
+ # A part of the run the render left out is a failed finding of its
643
+ # own, and the rest is still written.
644
+ findings = -> { problems.map { { severity: "failed", code: "report-incomplete", message: _1 } } }
645
+ unless target
646
+ emit({}, findings.(), "report", io: $stderr)
647
+ @out.write(text)
648
+ return problems.empty? ? 0 : 1
649
+ end
650
+
651
+ exports = own_exports(dir, doc[:run_id], problems)
652
+ replace_own_exports(exports, target, kind)
653
+ FileUtils.mkdir_p(kind == :dir ? target : File.dirname(target))
654
+ if run && format == "allure"
655
+ files = Engine::ReportAllure.write(run, target, ->(message) { problems << message })
656
+ else
657
+ File.write(target, text)
658
+ files = [target]
659
+ end
660
+ note_own_exports(exports, files)
661
+ written = Pathname.new(target).relative_path_from(Pathname.new(@project)).to_s
662
+ return finish("report", problems.empty?, findings: findings.(), run_id: doc[:run_id], format: format, written: [written]) if @json
663
+
664
+ emit({}, findings.(), "report", io: $stderr)
665
+ if kind == :dir
666
+ count = files.count { _1.end_with?("-result.json") }
667
+ $stderr.puts "#{format.ljust(10)}#{"#{written}/".then { _1.ljust([30, _1.size + 2].max) }}#{count}"
668
+ else
669
+ $stderr.puts "#{format.ljust(10)}#{written}"
670
+ end
671
+ problems.empty? ? 0 : 1
672
+ rescue Engine::Refusal => e
673
+ refuse(e)
674
+ end
675
+
676
+ # Why a report cannot go to `target`, or nil when it can.
677
+ #: (String, Symbol, String) -> String?
678
+ def out_problem(target, kind, label)
679
+ if File.exist?(target)
680
+ return "#{label} is a directory; markdown and messages write one file" if kind == :file && File.directory?(target)
681
+ return "#{label} is not a regular file (a FIFO, a socket, or a device), so it is not written" if kind == :file && !File.file?(target)
682
+ return "#{label} is not a directory; allure writes a directory of results" if kind == :dir && !File.directory?(target)
683
+
684
+ return nil
685
+ end
686
+ parent = File.dirname(target)
687
+ parent = File.dirname(parent) until File.exist?(parent) || File.dirname(parent) == parent
688
+ File.directory?(parent) ? nil : "#{label} lies under #{shown_path(parent)}, which is not a directory"
689
+ end
690
+
691
+ #: (String) -> String
692
+ def shown_path(absolute)
693
+ relative = Pathname.new(absolute).relative_path_from(Pathname.new(@project)).to_s
694
+ relative == ".." || relative.start_with?("../") ? absolute : relative
695
+ end
696
+
697
+ # The files this project's own run noted in its exports manifest under
698
+ # the export directory, so a render of the same run replaces what the
699
+ # last one wrote there and retention removes them with the run. A run
700
+ # that is not one of this project's own notes nothing.
701
+ #: (String, untyped, Array[String]) -> Hash[Symbol, untyped]?
702
+ def own_exports(dir, run_id, problems)
703
+ runs = File.join(@project, ".nukadoko", "runs")
704
+ return nil unless File.expand_path(dir) == File.join(runs, run_id.to_s) && !File.symlink?(dir)
705
+
706
+ manifest = File.join(dir, "exports")
707
+ if File.symlink?(manifest)
708
+ problems << "exports of run #{run_id} resolves outside the run directory, so this render is not noted in it"
709
+ return nil
710
+ end
711
+ export = File.join(@project, ".nukadoko", "export")
712
+ lines = File.exist?(manifest) ? File.readlines(manifest, chomp: true).reject(&:empty?).uniq : []
713
+ files = lines.map { [_1, File.expand_path(_1, @project)] }.select { |_, file| file.start_with?("#{export}/") && File.basename(file).casecmp("allure-history.jsonl") != 0 }
714
+ { manifest: manifest, export: export, files: files }
715
+ end
716
+
717
+ #: (Hash[Symbol, untyped]?, String, Symbol) -> void
718
+ def replace_own_exports(exports, target, kind)
719
+ return unless exports
720
+
721
+ gone = exports[:files].select { |_, file| kind == :file ? file == target : file.start_with?("#{target}/") }
722
+ return if gone.empty?
723
+
724
+ gone.each { |_, file| FileUtils.rm_f(file) }
725
+ kept = File.readlines(exports[:manifest], chomp: true).reject { |entry| entry.empty? || gone.any? { |line, _| line == entry } }
726
+ File.write(exports[:manifest], kept.map { "#{_1}\n" }.join)
727
+ end
728
+
729
+ #: (Hash[Symbol, untyped]?, Array[String]) -> void
730
+ def note_own_exports(exports, files)
731
+ return unless exports
732
+
733
+ noted = files.select { _1.start_with?("#{exports[:export]}/") }
734
+ File.open(exports[:manifest], "a") { |io| noted.each { io.puts Pathname.new(_1).relative_path_from(Pathname.new(@project)).to_s } } if noted.any?
735
+ end
736
+
737
+ #: () -> String
738
+ def report_dir
739
+ if (named = @rest.first)
740
+ dir = File.expand_path(named, @project)
741
+ return dir if File.file?(File.join(dir, "run.json"))
742
+
743
+ raise Engine::Refusal.new("run-not-found", "#{dir} holds no run.json that nuka run wrote",
744
+ fix: Engine::Codes.fix("run-not-found"), run: "nuka report --help")
745
+ end
746
+ newest = Engine::Verdict.newest_run(@project)
747
+ raise Engine::Refusal.new("run-not-found", "no run under .nukadoko/runs has a run.json", fix: Engine::Codes.fix("run-not-found"), run: "nuka run") unless newest
748
+
749
+ File.join(@project, newest[:run_dir] || File.join(".nukadoko", "runs", newest[:run_id]))
750
+ end
751
+
752
+ # Reads run.json files and git only, so it loads no step.
753
+ #: () -> Integer
754
+ def verdict
755
+ answer = Engine::Verdict.new(@project)
756
+ if @json
757
+ emit({ **head("verdict", answer.open? ? "failed" : "passed", answer.findings), **answer.envelope_fields }, answer.findings, "verdict")
758
+ else
759
+ @out.puts answer.headline
760
+ emit({}, answer.findings, "verdict")
761
+ end
762
+ answer.open? ? 1 : 0
763
+ end
764
+
765
+ # What check says about the env files; a file it cannot read, or a key
766
+ # both secrets lists name, stops the command instead.
767
+ #: () -> Array[Engine::Finding]
768
+ def env_findings
769
+ Engine::EnvCheck.validate!
770
+ Engine::EnvCheck.findings(@project)
771
+ rescue Engine::EnvFile::Unreadable => e
772
+ raise Engine::Refusal.new("env-file-unreadable", e.message)
773
+ end
774
+
775
+ #: (Engine::Refusal) -> Integer
776
+ def refuse(refusal)
777
+ finish(@command, false, findings: [refusal.to_h(@command)], verdict: refusal.severity, exit_code: refusal.exit_code)
778
+ end
779
+
780
+ #: (Engine::Finding) -> Engine::Finding
62
781
  def relative(finding)
63
- finding.with(file: finding.file&.delete_prefix("#{@project}/"))
782
+ finding.with(file: finding.file&.delete_prefix("#{@project}/"), message: finding.message.gsub("#{@project}/", ""))
783
+ end
784
+
785
+ # Every envelope opens the same way, in the TypeScript engine's order.
786
+ #: (String?, String, Array[untyped], **untyped) -> Hash[Symbol, untyped]
787
+ def head(command, verdict, findings, **more)
788
+ { schema_version: Engine::RunRecord::SCHEMA_VERSION, nukadoko: VERSION, command: command, **more, verdict: verdict, findings: findings }
789
+ end
790
+
791
+ #: (String?, bool, findings: Array[untyped], ?verdict: String, ?exit_code: Integer, **untyped) -> Integer
792
+ def finish(command, passed, findings:, verdict: passed ? "passed" : "failed", exit_code: passed ? 0 : 1, **rest)
793
+ # What a walk that stops here ends with.
794
+ @stopped_with = findings
795
+ emit({ **head(command, verdict, findings), **rest }, findings, command)
796
+ exit_code
64
797
  end
65
798
 
66
- def finish(command, passed, findings:, verdict: passed ? "passed" : "failed", **rest)
799
+ #: (Hash[Symbol, untyped], Array[untyped], String?, ?io: IO) -> void
800
+ def emit(envelope, findings, command, io: @out)
67
801
  if @json
68
- @out.puts JSON.pretty_generate({ nukadoko: VERSION, engine: "ruby", command: command, verdict: verdict, findings: findings, **rest })
802
+ @out.puts JSON.pretty_generate(envelope)
69
803
  else
70
- findings.each { @out.puts [_1[:severity], _1[:code], [_1[:file], _1[:line]].compact.join(":"), _1[:message]].join("\t") }
71
- @out.puts "ok: no issues found" if command == "check" && findings.empty?
804
+ findings.each do |f|
805
+ io.puts [f[:severity], f[:code], Engine::Summary.where_of(f), f[:message]].join("\t")
806
+ io.puts " fix: #{f[:fix]}" if f[:fix]
807
+ io.puts " do: #{f[:do]}" if f[:do]
808
+ end
809
+ io.puts "ok: no issues found" if command == "check" && findings.empty?
810
+ end
811
+ end
812
+
813
+ # The counts after where the run wrote, as the TypeScript engine prints
814
+ # them: the scenarios, then the control runs, then the criteria when a
815
+ # control or a base makes the scenario count no verdict count, then the
816
+ # criteria left out.
817
+ #: (Hash[Symbol, untyped], IO) -> void
818
+ def run_end(envelope, io)
819
+ counts = envelope[:counts] #: Hash[Symbol, Integer]
820
+ total = counts[:scenarios]
821
+ stopped = counts[:stopped]
822
+ io.puts "#{total} scenario#{total == 1 ? "" : "s"}: #{counts[:passed]} passed, #{total - counts[:passed] - stopped} failed" \
823
+ "#{stopped.positive? ? ", #{stopped} stopped" : ""}#{counts[:not_run].positive? ? ", #{counts[:not_run]} not run" : ""}" \
824
+ " (#{duration(envelope[:started_at], envelope[:finished_at])})"
825
+ if counts[:controls].positive? || counts[:controls_not_run].positive?
826
+ not_run = counts[:controls_not_run].positive? ? ", #{counts[:controls_not_run]} not run" : ""
827
+ io.puts "#{counts[:controls]} control run#{counts[:controls] == 1 ? "" : "s"}#{not_run}"
828
+ end
829
+ table = envelope[:table] #: Hash[Symbol, untyped]
830
+ rows = table[:rows] #: Array[Hash[Symbol, untyped]]
831
+ based = !table[:base].nil?
832
+ if based || counts[:controls].positive?
833
+ count = ->(word) { rows.count { _1[:verdict] == word } }
834
+ extra = based ? ", #{count.("unproven")} unproven, #{count.("moved")} moved, #{count.("removed")} removed" : ""
835
+ io.puts "criteria: #{count.("held")} held, #{count.("proven")} proven, #{count.("failed")} failed#{extra}"
836
+ end
837
+ left_out = table[:left_out].to_i
838
+ return unless left_out.positive?
839
+
840
+ io.puts left_out == 1 ? "1 criterion not run: its conditions hold in no selected environment" : "#{left_out} criteria not run: their conditions hold in no selected environment"
841
+ end
842
+
843
+ # `1h 2m 3s`, the unit a whole run reads in.
844
+ #: (String, String) -> String
845
+ def duration(started_at, finished_at)
846
+ total = [(Time.iso8601(finished_at) - Time.iso8601(started_at)).round, 0].max
847
+ hours, rest = total.divmod(3600)
848
+ minutes, seconds = rest.divmod(60)
849
+ [*(hours.positive? ? ["#{hours}h"] : []), *(hours.positive? || minutes.positive? ? ["#{minutes}m"] : []), "#{seconds}s"].join(" ")
850
+ end
851
+
852
+ # After the failed list, under --repeat, each scenario that failed at
853
+ # least once and how many of its executions passed. No verdict is
854
+ # named: one that fails every time is not flaky.
855
+ #: (Array[Hash[Symbol, untyped]], IO) -> void
856
+ def repeat_tallies(scenarios, io)
857
+ named = @options["--env"].size > 1
858
+ scenarios.reject { _1[:world] }.group_by { _1.values_at(:feature, :line, :environment) }.each_value do |runs|
859
+ passed = runs.count { _1[:status] == "passed" }
860
+ next if passed == runs.size
861
+
862
+ first = runs.first
863
+ name = named ? "#{first[:scenario]} (#{first[:environment]})" : first[:scenario]
864
+ io.puts "repeat #{first[:feature]}:#{first[:line]} #{name} #{passed} of #{runs.size} passed"
72
865
  end
73
- passed ? 0 : 1
74
866
  end
75
867
  end
76
868
  end