nukadoko 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (159) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +417 -0
  3. data/README.ja.md +62 -7
  4. data/README.md +19 -5
  5. data/exe/nuka +8 -0
  6. data/lib/nukadoko/aria_snapshot.rb +1008 -0
  7. data/lib/nukadoko/aria_tree.rb +150 -0
  8. data/lib/nukadoko/base.rb +294 -0
  9. data/lib/nukadoko/check.rb +669 -22
  10. data/lib/nukadoko/claim_check.rb +177 -0
  11. data/lib/nukadoko/claim_check_run.rb +293 -0
  12. data/lib/nukadoko/claim_line.rb +381 -0
  13. data/lib/nukadoko/claim_rules.rb +519 -0
  14. data/lib/nukadoko/claim_sides.rb +469 -0
  15. data/lib/nukadoko/claims.rb +576 -37
  16. data/lib/nukadoko/cli.rb +814 -22
  17. data/lib/nukadoko/codes.json +947 -0
  18. data/lib/nukadoko/codes.rb +19 -0
  19. data/lib/nukadoko/command.rb +214 -12
  20. data/lib/nukadoko/criteria.rb +172 -0
  21. data/lib/nukadoko/definition.rb +33 -41
  22. data/lib/nukadoko/env_check.rb +88 -0
  23. data/lib/nukadoko/features.rb +80 -10
  24. data/lib/nukadoko/fixtures.rb +329 -11
  25. data/lib/nukadoko/http_recording.rb +68 -0
  26. data/lib/nukadoko/init.rb +129 -0
  27. data/lib/nukadoko/js_json.rb +274 -0
  28. data/lib/nukadoko/js_pattern.rb +531 -0
  29. data/lib/nukadoko/judge.rb +221 -0
  30. data/lib/nukadoko/judgment_file.rb +78 -0
  31. data/lib/nukadoko/judgments.rb +256 -0
  32. data/lib/nukadoko/literal.rb +129 -0
  33. data/lib/nukadoko/measured.rb +105 -0
  34. data/lib/nukadoko/order.rb +84 -0
  35. data/lib/nukadoko/parts.rb +43 -22
  36. data/lib/nukadoko/pattern.rb +73 -3
  37. data/lib/nukadoko/poll.rb +21 -8
  38. data/lib/nukadoko/program.rb +105 -17
  39. data/lib/nukadoko/project_files.rb +17 -0
  40. data/lib/nukadoko/project_fixtures.rb +17 -2
  41. data/lib/nukadoko/project_program.rb +119 -0
  42. data/lib/nukadoko/report_allure.rb +751 -0
  43. data/lib/nukadoko/report_messages.rb +167 -0
  44. data/lib/nukadoko/report_run.rb +169 -0
  45. data/lib/nukadoko/run.rb +898 -91
  46. data/lib/nukadoko/run_record.rb +535 -0
  47. data/lib/nukadoko/scaffold.rb +1015 -0
  48. data/lib/nukadoko/schema.rb +120 -21
  49. data/lib/nukadoko/secrets.rb +375 -0
  50. data/lib/nukadoko/selection.rb +163 -0
  51. data/lib/nukadoko/signature.rb +4 -1
  52. data/lib/nukadoko/skill.rb +36 -0
  53. data/lib/nukadoko/spaces.rb +28 -0
  54. data/lib/nukadoko/step.rb +68 -21
  55. data/lib/nukadoko/summary.rb +662 -0
  56. data/lib/nukadoko/table.rb +34 -2
  57. data/lib/nukadoko/text_fit.rb +179 -0
  58. data/lib/nukadoko/trace.rb +244 -0
  59. data/lib/nukadoko/trace_actions.rb +116 -0
  60. data/lib/nukadoko/tree_passes.rb +122 -0
  61. data/lib/nukadoko/verdict.rb +128 -0
  62. data/lib/nukadoko/version.rb +2 -1
  63. data/lib/nukadoko/vocabulary.rb +6 -0
  64. data/lib/nukadoko/walk.rb +305 -0
  65. data/lib/nukadoko/walk_files.rb +473 -0
  66. data/lib/nukadoko/walk_step.rb +149 -0
  67. data/lib/nukadoko.rb +60 -2
  68. data/llms.txt +297 -0
  69. data/sig/generated/nukadoko/aria_snapshot.rbs +331 -0
  70. data/sig/generated/nukadoko/aria_tree.rbs +142 -0
  71. data/sig/generated/nukadoko/base.rbs +142 -0
  72. data/sig/generated/nukadoko/check.rbs +255 -0
  73. data/sig/generated/nukadoko/claim_check.rbs +118 -0
  74. data/sig/generated/nukadoko/claim_check_run.rbs +88 -0
  75. data/sig/generated/nukadoko/claim_line.rbs +158 -0
  76. data/sig/generated/nukadoko/claim_rules.rbs +172 -0
  77. data/sig/generated/nukadoko/claim_sides.rbs +207 -0
  78. data/sig/generated/nukadoko/claims.rbs +208 -0
  79. data/sig/generated/nukadoko/cli.rbs +182 -0
  80. data/sig/generated/nukadoko/codes.rbs +16 -0
  81. data/sig/generated/nukadoko/command.rbs +109 -0
  82. data/sig/generated/nukadoko/criteria.rbs +83 -0
  83. data/sig/generated/nukadoko/definition.rbs +30 -0
  84. data/sig/generated/nukadoko/env_check.rbs +34 -0
  85. data/sig/generated/nukadoko/features.rbs +101 -0
  86. data/sig/generated/nukadoko/fixtures.rbs +175 -0
  87. data/sig/generated/nukadoko/http_recording.rbs +29 -0
  88. data/sig/generated/nukadoko/init.rbs +64 -0
  89. data/sig/generated/nukadoko/js_json.rbs +109 -0
  90. data/sig/generated/nukadoko/js_pattern.rbs +194 -0
  91. data/sig/generated/nukadoko/judge.rbs +64 -0
  92. data/sig/generated/nukadoko/judgment_file.rbs +39 -0
  93. data/sig/generated/nukadoko/judgments.rbs +120 -0
  94. data/sig/generated/nukadoko/literal.rbs +71 -0
  95. data/sig/generated/nukadoko/measured.rbs +42 -0
  96. data/sig/generated/nukadoko/order.rbs +54 -0
  97. data/sig/generated/nukadoko/parts.rbs +35 -0
  98. data/sig/generated/nukadoko/pattern.rbs +62 -0
  99. data/sig/generated/nukadoko/poll.rbs +41 -0
  100. data/sig/generated/nukadoko/program.rbs +101 -0
  101. data/sig/generated/nukadoko/project_files.rbs +19 -0
  102. data/sig/generated/nukadoko/project_fixtures.rbs +57 -0
  103. data/sig/generated/nukadoko/project_program.rbs +55 -0
  104. data/sig/generated/nukadoko/report_allure.rbs +268 -0
  105. data/sig/generated/nukadoko/report_messages.rbs +68 -0
  106. data/sig/generated/nukadoko/report_run.rbs +102 -0
  107. data/sig/generated/nukadoko/run.rbs +264 -0
  108. data/sig/generated/nukadoko/run_record.rbs +175 -0
  109. data/sig/generated/nukadoko/scaffold.rbs +328 -0
  110. data/sig/generated/nukadoko/schema.rbs +155 -0
  111. data/sig/generated/nukadoko/secrets.rbs +172 -0
  112. data/sig/generated/nukadoko/selection.rbs +73 -0
  113. data/sig/generated/nukadoko/signature.rbs +17 -0
  114. data/sig/generated/nukadoko/skill.rbs +20 -0
  115. data/sig/generated/nukadoko/spaces.rbs +31 -0
  116. data/sig/generated/nukadoko/step.rbs +115 -0
  117. data/sig/generated/nukadoko/summary.rbs +204 -0
  118. data/sig/generated/nukadoko/table.rbs +43 -0
  119. data/sig/generated/nukadoko/text_fit.rbs +70 -0
  120. data/sig/generated/nukadoko/trace.rbs +127 -0
  121. data/sig/generated/nukadoko/trace_actions.rbs +40 -0
  122. data/sig/generated/nukadoko/tree_passes.rbs +48 -0
  123. data/sig/generated/nukadoko/verdict.rbs +56 -0
  124. data/sig/generated/nukadoko/version.rbs +5 -0
  125. data/sig/generated/nukadoko/vocabulary.rbs +25 -0
  126. data/sig/generated/nukadoko/walk.rbs +139 -0
  127. data/sig/generated/nukadoko/walk_files.rbs +189 -0
  128. data/sig/generated/nukadoko/walk_step.rbs +50 -0
  129. data/sig/generated/nukadoko.rbs +26 -0
  130. data/sig/nukadoko.rbs +5 -48
  131. data/skills/nukadoko/SKILL.md +120 -0
  132. data/skills/nukadoko/references/checking-steps.md +200 -0
  133. data/skills/nukadoko/references/diagnosing.md +200 -0
  134. data/skills/nukadoko/references/done.md +99 -0
  135. data/skills/nukadoko/references/evidence.md +124 -0
  136. data/skills/nukadoko/references/examples/cli.md +230 -0
  137. data/skills/nukadoko/references/examples/http-api.md +342 -0
  138. data/skills/nukadoko/references/examples/workflow.md +173 -0
  139. data/skills/nukadoko/references/exploring.md +184 -0
  140. data/skills/nukadoko/references/fixtures.md +198 -0
  141. data/skills/nukadoko/references/from-prose.md +51 -0
  142. data/skills/nukadoko/references/judgments.md +95 -0
  143. data/skills/nukadoko/references/maintenance.md +97 -0
  144. data/skills/nukadoko/references/merge-risk.md +74 -0
  145. data/skills/nukadoko/references/parts.md +152 -0
  146. data/skills/nukadoko/references/perturbed-worlds.md +109 -0
  147. data/skills/nukadoko/references/program.md +200 -0
  148. data/skills/nukadoko/references/reviewing.md +200 -0
  149. data/skills/nukadoko/references/running.md +200 -0
  150. data/skills/nukadoko/references/scenario-rules.md +188 -0
  151. data/skills/nukadoko/references/states.md +66 -0
  152. data/skills/nukadoko/references/step-files.md +200 -0
  153. data/skills/nukadoko/references/verdicts.md +200 -0
  154. data/skills/nukadoko/references/writing-steps.md +200 -0
  155. data/skills/nukadoko/references/writing-the-feature.md +165 -0
  156. data/skills/nukadoko/scripts/claude-code-verdict-hook.mjs +99 -0
  157. data/skills/nukadoko/scripts/merge-risk.jq +56 -0
  158. data/skills/nukadoko-verification/SKILL.md +263 -0
  159. metadata +133 -1
@@ -0,0 +1,473 @@
1
+ # frozen_string_literal: true
2
+ # rbs_inline: enabled
3
+
4
+ require "fileutils"
5
+ require "json"
6
+ require "securerandom"
7
+ require "time"
8
+
9
+ # The files a walk of `nuka run --step` and `nuka step` share, read and
10
+ # written from both sides, in the TypeScript engine's layout
11
+ # (src/run/walk-files.ts), so either engine's `nuka step` answers either
12
+ # engine's walk. Nothing else names these files, and nothing here decides
13
+ # anything: Walk says what a state becomes and what a call does next, Run
14
+ # says when a step is done, and the CLI prints.
15
+ #
16
+ # Each file has one writer, so no write needs a lock of its own:
17
+ #
18
+ # .nukadoko/walk.lock/<n> the run of walk n, created exclusively, holding its pid, then `released`
19
+ # .nukadoko/walk.json the run, replaced whole (written aside, then renamed)
20
+ # <run_dir>/answers/<n>.json nuka step, created exclusively, never rewritten
21
+ # <run_dir>/pauses/<n>/ the run: the views, and the open page's requests
22
+ # .nukadoko/walks-reported/<n> nuka step, created exclusively once it printed how walk n ended
23
+ #
24
+ # A process that holds the lock and is gone (a crash, a SIGKILL) leaves a
25
+ # walk.json that is not ended and a pid that is not alive: a reader sees the
26
+ # walk as gone, and the next `nuka run --step` takes the lock over. A pid
27
+ # check, not a lease a process renews: it needs no clock of its own.
28
+ module Nukadoko
29
+ module Engine
30
+ module WalkFiles
31
+ LOCK_DIR = "walk.lock"
32
+ RELEASED = "released"
33
+ STATE_FILE = "walk.json"
34
+ REPORTED_DIR = "walks-reported"
35
+ POLL = 0.1
36
+ STATES = %w[starting running paused ended].freeze
37
+
38
+ # The run's side of one walk.
39
+ class Handle
40
+ attr_reader :number
41
+
42
+ #: (String, String, Integer, Hash[Symbol, untyped], (^(String) -> void)?) -> void
43
+ def initialize(project, dir, number, state, announce)
44
+ @project = project
45
+ @dir = dir
46
+ @number = number
47
+ @state = state
48
+ @announce = announce
49
+ @pauses = []
50
+ @run_dir = nil
51
+ @ended = false
52
+ end
53
+
54
+ # The run has its directory and its one scenario.
55
+ #: (Hash[Symbol, untyped]) -> void
56
+ def begin(run)
57
+ @run_dir = run[:run_dir]
58
+ apply(kind: "begun", run: run)
59
+ end
60
+
61
+ # Writes the pause and waits for its answer. `hold` takes the pause's
62
+ # directory and the path the run records it as, and returns the
63
+ # views of the open page.
64
+ #: (Hash[Symbol, untyped]) { (String, String) -> Array[Hash[Symbol, untyped]] } -> String
65
+ def pause_after(facts)
66
+ raise "a walk pauses only after it began" unless @run_dir
67
+
68
+ k = facts[:step]
69
+ recorded_as = "pauses/#{k}"
70
+ pause_dir = File.join(@project, @run_dir, "pauses", k.to_s)
71
+ FileUtils.mkdir_p(pause_dir)
72
+ views = yield(pause_dir, recorded_as)
73
+ pause = { pause: k, of: facts[:of], line: facts[:line], text: facts[:text], step: facts[:step_name], status: facts[:status], record: facts[:record],
74
+ **(facts[:failure] ? { failure: facts[:failure] } : {}), remaining: facts[:remaining], paused_at: WalkFiles.now, views: views }
75
+ apply(kind: "paused", pause: pause)
76
+ @announce&.call(Walk.pause_lines(@number, pause))
77
+ answer_path = File.join(WalkFiles.answers_dir(@project, @run_dir), "#{k}.json")
78
+ answer = WalkFiles.wait_answer(answer_path)
79
+ @pauses << { pause: k, line: facts[:line], step_record_id: facts[:step_record_id], paused_at: pause[:paused_at],
80
+ answered_at: answer[:answered_at], answer: answer[:answer], views: views }
81
+ apply(kind: "answered", pause: k, answer: answer[:answer])
82
+ answer[:answer]
83
+ end
84
+
85
+ # run.json's `walk`: each pause so far, and its answer. It names only
86
+ # files that are there when it is written.
87
+ #: () -> Hash[Symbol, untyped]
88
+ def record
89
+ there = ->(file) { file && @run_dir && File.exist?(File.join(@project, @run_dir, file)) ? file : nil }
90
+ pauses = @pauses.map do |entry|
91
+ views = entry[:views].map { _1.merge(screenshot: there.(_1[:screenshot]), aria: there.(_1[:aria])) }
92
+ http = there.("pauses/#{entry[:pause]}/http.jsonl")
93
+ http ? entry.merge(views: views, http: http) : entry.merge(views: views)
94
+ end
95
+ { pauses: pauses }
96
+ end
97
+
98
+ # Records how the walk ended and releases the lock. The first call
99
+ # wins: a signal's cleanup and the run's own end can both reach it.
100
+ #: (Hash[Symbol, untyped]) -> void
101
+ def end(finish)
102
+ return if @ended
103
+
104
+ @ended = true
105
+ begin
106
+ apply(kind: "ended", end: finish, at: WalkFiles.now)
107
+ ensure
108
+ WalkFiles.release_lock(@dir, @number)
109
+ end
110
+ end
111
+
112
+ private
113
+
114
+ #: (Hash[Symbol, untyped]) -> void
115
+ def apply(event)
116
+ @state = Walk.advance(@state, event)
117
+ WalkFiles.replace_file(File.join(@dir, STATE_FILE), "#{JSON.pretty_generate(@state)}\n")
118
+ end
119
+ end
120
+
121
+ module_function
122
+
123
+ #: () -> String
124
+ def now = Time.now.utc.iso8601(3)
125
+
126
+ # Whether `pid` is a live process. EPERM is a process this one may
127
+ # not signal, which is alive.
128
+ #: (Integer) -> bool
129
+ def alive?(pid)
130
+ Process.kill(0, pid)
131
+ true
132
+ rescue Errno::EPERM
133
+ true
134
+ rescue Errno::ESRCH, RangeError
135
+ false
136
+ end
137
+
138
+ #: (String) -> String
139
+ def state_dir(project) = File.join(project, ".nukadoko")
140
+
141
+ #: (String, String) -> String
142
+ def answers_dir(project, run_dir) = File.join(project, run_dir, "answers")
143
+
144
+ #: (String, String) -> void
145
+ def replace_file(path, text)
146
+ aside = "#{path}.#{Process.pid}.tmp"
147
+ File.write(aside, text)
148
+ File.rename(aside, path)
149
+ end
150
+
151
+ # walk.json as one read found it: { state: } (nil for no file), or
152
+ # { unreadable: } with why. walk.json has one writer, so a reader
153
+ # checks only the fields every state carries and trusts the rest.
154
+ #: (String) -> Hash[Symbol, untyped]
155
+ def read_state(path)
156
+ parsed = begin
157
+ JSON.parse(File.read(path, encoding: "UTF-8"), symbolize_names: true)
158
+ rescue Errno::ENOENT
159
+ return { state: nil }
160
+ rescue StandardError => e
161
+ return { unreadable: e.message }
162
+ end
163
+ return { unreadable: "it holds no JSON object" } unless parsed.is_a?(Hash)
164
+
165
+ valid = STATES.include?(parsed[:state]) && parsed[:number].is_a?(Integer) && parsed[:pid].is_a?(Integer) &&
166
+ parsed[:target].is_a?(String) && parsed[:started_at].is_a?(String)
167
+ valid ? { state: parsed } : { unreadable: "it holds no walk state" }
168
+ end
169
+
170
+ # The whole-number names in a directory, and none when it is missing.
171
+ #: (String) -> Array[Integer]
172
+ def numbered(dir)
173
+ Dir.children(dir).grep(/\A\d+\z/).map(&:to_i)
174
+ rescue Errno::ENOENT
175
+ []
176
+ end
177
+
178
+ # One past every walk this project recorded, in walk.json or as a
179
+ # reported end, so a walk.json lost cannot give a new walk the number
180
+ # of one whose end a `nuka step` call already printed.
181
+ #: (String) -> Integer
182
+ def highest_recorded(dir)
183
+ stored = read_state(File.join(dir, STATE_FILE))[:state]
184
+ [stored ? stored[:number] : 0, *numbered(File.join(dir, REPORTED_DIR))].max
185
+ end
186
+
187
+ # The highest lock file and its holder: a pid, "released", or nil for
188
+ # a file that holds neither. Only a number below the highest is ever
189
+ # removed, so a file gone between the listing and the read means a
190
+ # higher one exists: list again.
191
+ #: (String) -> Hash[Symbol, untyped]?
192
+ def lock_top(lock_dir)
193
+ 100.times do
194
+ walks = numbered(lock_dir)
195
+ return nil if walks.empty?
196
+
197
+ walk = walks.max
198
+ text = begin
199
+ File.read(File.join(lock_dir, walk.to_s)).strip
200
+ rescue Errno::ENOENT
201
+ next
202
+ end
203
+ pid = Integer(text, 10, exception: false)
204
+ return { walk: walk, holder: text == RELEASED ? RELEASED : (pid&.positive? ? pid : nil) }
205
+ end
206
+ raise "#{lock_dir} changed on every one of 100 reads"
207
+ end
208
+
209
+ # Creates `target` with `text` only when it does not exist. A link is
210
+ # exclusive, and the file appears with its whole text: a process
211
+ # killed between an exclusive create and its write would leave an
212
+ # empty lock no reader could tell from one being written.
213
+ #: (String, String) -> bool
214
+ def link_whole(target, text)
215
+ aside = "#{target}.#{Process.pid}.#{SecureRandom.uuid}.tmp"
216
+ File.write(aside, text)
217
+ File.link(aside, target)
218
+ true
219
+ rescue Errno::EEXIST
220
+ false
221
+ ensure
222
+ File.unlink(aside) if aside && File.exist?(aside)
223
+ end
224
+
225
+ #: (String) -> void
226
+ def remove_quietly(path)
227
+ File.unlink(path)
228
+ rescue Errno::ENOENT
229
+ nil
230
+ end
231
+
232
+ # The pid of a live process, not this one, that holds a lock file
233
+ # below `walk`, or nil.
234
+ #: (String, Integer) -> Integer?
235
+ def live_holder_below(lock_dir, walk)
236
+ numbered(lock_dir).each do |lower|
237
+ next if lower >= walk
238
+
239
+ text = begin
240
+ File.read(File.join(lock_dir, lower.to_s)).strip
241
+ rescue Errno::ENOENT
242
+ next
243
+ end
244
+ pid = Integer(text, 10, exception: false)
245
+ return pid if pid&.positive? && pid != Process.pid && alive?(pid)
246
+ end
247
+ nil
248
+ end
249
+
250
+ # The lock is a directory with one file per walk that took it, named
251
+ # by the walk's number; the highest number holds it. A run takes the
252
+ # lock by creating the next number, so it never removes a file
253
+ # another process may hold: of two runs that find the same holder
254
+ # dead or released, only one creates the next number. A file is
255
+ # removed only once a higher one exists, and only by the process that
256
+ # created that higher one, or by its own creator giving way.
257
+ #: (String) -> Hash[Symbol, untyped]
258
+ def take_lock(dir)
259
+ lock_dir = File.join(dir, LOCK_DIR)
260
+ FileUtils.mkdir_p(lock_dir)
261
+ 3.times do
262
+ top = lock_top(lock_dir)
263
+ # A holder that is this process is a walk it left without ending:
264
+ # not a second walk.
265
+ holder = top && top[:holder]
266
+ return { holder: holder } if holder.is_a?(Integer) && holder != Process.pid && alive?(holder)
267
+
268
+ walk = [top ? top[:walk] : 0, highest_recorded(dir)].max + 1
269
+ file = File.join(lock_dir, walk.to_s)
270
+ next unless link_whole(file, "#{Process.pid}\n")
271
+
272
+ if lock_top(lock_dir)&.dig(:walk) != walk
273
+ remove_quietly(file)
274
+ next
275
+ end
276
+ # The number came from a reading that can be old: a live holder
277
+ # below gives this run way.
278
+ if (live = live_holder_below(lock_dir, walk))
279
+ remove_quietly(file)
280
+ return { holder: live }
281
+ end
282
+ numbered(lock_dir).each { remove_quietly(File.join(lock_dir, _1.to_s)) if _1 < walk }
283
+ return { taken: walk }
284
+ end
285
+ { raced: true }
286
+ end
287
+
288
+ # The file stays, so the highest number never goes back down; it says
289
+ # `released`, which the next run takes over like a dead pid.
290
+ #: (String, Integer) -> void
291
+ def release_lock(dir, walk)
292
+ file = File.join(dir, LOCK_DIR, walk.to_s)
293
+ held = begin
294
+ Integer(File.read(file).strip, 10, exception: false)
295
+ rescue Errno::ENOENT
296
+ return
297
+ end
298
+ replace_file(file, "#{RELEASED}\n") if held == Process.pid
299
+ end
300
+
301
+ # An answer file is created exclusively and written in one call, so a
302
+ # reader can catch it empty for a moment: that reads as not answered
303
+ # yet, and the next poll reads it whole.
304
+ #: (String) -> Hash[Symbol, String]?
305
+ def read_answer(path)
306
+ value = JSON.parse(File.read(path, encoding: "UTF-8"), symbolize_names: true)
307
+ return nil unless value.is_a?(Hash) && %w[next stop].include?(value[:answer]) && value[:answered_at].is_a?(String)
308
+
309
+ { answer: value[:answer], answered_at: value[:answered_at] }
310
+ rescue StandardError
311
+ nil
312
+ end
313
+
314
+ # The answer at `path`, once `nuka step` has written it.
315
+ #: (String) -> Hash[Symbol, String]
316
+ def wait_answer(path)
317
+ loop do
318
+ answer = read_answer(path)
319
+ return answer if answer
320
+
321
+ sleep POLL
322
+ end
323
+ end
324
+
325
+ # Starts the run's side of a walk: takes the lock, which numbers the
326
+ # walk one past every walk recorded, and writes it as starting. A
327
+ # Handle, or { refused: } with why. `announce` gets the lines of each
328
+ # pause, outside --json.
329
+ #: (String, String, ?announce: (^(String) -> void)?) -> (Handle | Hash[Symbol, untyped])
330
+ def open(project, target, announce: nil)
331
+ dir = state_dir(project)
332
+ FileUtils.mkdir_p(dir)
333
+ lock = take_lock(dir)
334
+ unless lock[:taken]
335
+ message = if lock[:raced] then "another nuka run --step took the walk lock at the same moment, so this one did not start"
336
+ else "another walk is in progress in this project: nuka run --step, pid #{lock[:holder]}"
337
+ end
338
+ return { refused: "walk-in-progress", message: message }
339
+ end
340
+ state = Walk.start({ number: lock[:taken], pid: Process.pid, target: target, started_at: now })
341
+ replace_file(File.join(dir, STATE_FILE), "#{JSON.pretty_generate(state)}\n")
342
+ Handle.new(project, dir, lock[:taken], state, announce)
343
+ end
344
+
345
+ # The run directory of the walk that is live now, relative to the
346
+ # project root: a walk running or paused whose pid is alive, nil for
347
+ # none. A walk still starting has no run directory yet, so for it
348
+ # "starting" is returned. `nuka clean` keeps what this names.
349
+ #: (String) -> Hash[Symbol, untyped]?
350
+ def live_run(project)
351
+ path = File.join(state_dir(project), STATE_FILE)
352
+ read = read_state(path)
353
+ 20.times do
354
+ break unless read[:unreadable]
355
+
356
+ sleep 0.05
357
+ read = read_state(path)
358
+ end
359
+ raise "#{path} could not be read: #{read[:unreadable]}" if read[:unreadable]
360
+
361
+ seen = Walk.see(read[:state], ->(pid) { alive?(pid) })
362
+ return { walk: seen[:number], run_dir: "starting" } if seen[:state] == "starting"
363
+ return { walk: seen[:number], run_dir: seen[:run_dir] } if %w[running paused].include?(seen[:state])
364
+
365
+ nil
366
+ end
367
+
368
+ #: (String, Hash[Symbol, untyped], Integer) -> Hash[Integer, String]
369
+ def answers_of(project, seen, target)
370
+ return {} if seen[:state] == "none"
371
+
372
+ state = seen[:state] == "gone" ? seen[:last] : seen #: Hash[Symbol, untyped]
373
+ return {} if state[:state] == "starting" || state[:number] != target
374
+
375
+ run_dir = state[:run_dir] #: String?
376
+ return {} unless run_dir
377
+
378
+ dir = answers_dir(project, run_dir)
379
+ names = begin
380
+ Dir.children(dir)
381
+ rescue SystemCallError
382
+ return {}
383
+ end
384
+ names.each_with_object({}) do |name, answers|
385
+ match = /\A(\d+)\.json\z/.match(name) or next
386
+ answer = read_answer(File.join(dir, name))
387
+ answers[match[1].to_i] = answer[:answer] if answer
388
+ end
389
+ end
390
+
391
+ # One empty file per walk whose end a `nuka step` call printed.
392
+ # Created exclusively, so two calls that print the same end leave one
393
+ # file.
394
+ #: (String, Integer) -> bool
395
+ def end_reported?(dir, walk) = File.exist?(File.join(dir, REPORTED_DIR, walk.to_s))
396
+
397
+ #: (String, Integer) -> void
398
+ def mark_end_reported(dir, walk)
399
+ FileUtils.mkdir_p(File.join(dir, REPORTED_DIR))
400
+ File.open(File.join(dir, REPORTED_DIR, walk.to_s), File::WRONLY | File::CREAT | File::EXCL, &:close)
401
+ rescue Errno::EEXIST
402
+ nil
403
+ end
404
+
405
+ #: (String, String, Integer, String) -> void
406
+ def write_answer(project, run_dir, pause, answer)
407
+ dir = answers_dir(project, run_dir)
408
+ FileUtils.mkdir_p(dir)
409
+ # Another call may have answered first: the next read of the answers
410
+ # decides whether this call repeats it or contradicts it.
411
+ File.open(File.join(dir, "#{pause}.json"), File::WRONLY | File::CREAT | File::EXCL) do |file|
412
+ file.write("#{JSON.generate({ answer: answer, answered_at: now })}\n")
413
+ end
414
+ rescue Errno::EEXIST
415
+ nil
416
+ end
417
+
418
+ # One `nuka step` call: reads walk.json until the walk reaches a state
419
+ # the call can report, writing the call's answer once when the walk
420
+ # waits at its pause. Repeating a call is safe. `timeout` (seconds)
421
+ # bounds the wait: a walk still running then is reported as running,
422
+ # with the call itself as its `do`, and a wait that never found its
423
+ # walk is refused as walk-not-found.
424
+ #: (String, Hash[Symbol, untyped], Numeric, ?alive: ^(Integer) -> bool) -> Hash[Symbol, untyped]
425
+ def step_call(project, call, timeout, alive: ->(pid) { alive?(pid) })
426
+ dir = state_dir(project)
427
+ path = File.join(dir, STATE_FILE)
428
+ deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + timeout
429
+ over = -> { Process.clock_gettime(Process::CLOCK_MONOTONIC) >= deadline }
430
+ target = nil #: Integer?
431
+ loop do
432
+ read = read_state(path)
433
+ if read[:unreadable]
434
+ raise ".nukadoko/#{STATE_FILE} could not be read for #{timeout.round}s: #{read[:unreadable]}" if over.()
435
+
436
+ sleep POLL
437
+ next
438
+ end
439
+ seen = Walk.see(read[:state], alive)
440
+ aim = (target ||= Walk.call_target(call, seen, ->(walk) { end_reported?(dir, walk) }))
441
+ decision = Walk.decide(call, aim, seen, answers_of(project, seen, aim))
442
+ case decision[:kind]
443
+ when "write-answer"
444
+ write_answer(project, decision[:run_dir], call[:pause], call[:answer]) if call[:kind] == "answer"
445
+ next
446
+ when "report"
447
+ reported = decision[:seen]
448
+ mark_end_reported(dir, reported[:last][:number]) if reported[:state] == "gone"
449
+ mark_end_reported(dir, reported[:number]) if reported[:state] == "ended"
450
+ return { kind: "report", report: Walk.report(reported, call), seen: reported }
451
+ when "refuse"
452
+ return { kind: "refuse", code: decision[:code], message: decision[:message], **(decision[:do] ? { do: decision[:do] } : {}) }
453
+ end
454
+ if over.()
455
+ # The walk the call is about, still on its way to a pause.
456
+ if !%w[none gone].include?(seen[:state]) && seen[:number] >= aim
457
+ return { kind: "report", report: Walk.report(seen, call), seen: seen }
458
+ end
459
+
460
+ last = case seen[:state]
461
+ when "none" then nil
462
+ when "gone" then seen[:last]
463
+ else seen
464
+ end
465
+ return { kind: "refuse", code: "walk-not-found", message: Walk.nothing_started_message(call[:kind] == "wait" ? call : { kind: "wait" }, timeout.round, seen),
466
+ fields: { walk: "none", last: last } }
467
+ end
468
+ sleep POLL
469
+ end
470
+ end
471
+ end
472
+ end
473
+ end
@@ -0,0 +1,149 @@
1
+ # frozen_string_literal: true
2
+ # rbs_inline: enabled
3
+
4
+ require "json"
5
+
6
+ # `nuka step wait`, `nuka step next <pause> --walk <n>`, and `nuka step stop
7
+ # <pause> --walk <n>`, the side of a walk that answers it, in the
8
+ # TypeScript engine's shape (src/cli/step.ts). This class reads its
9
+ # arguments and prints; WalkFiles reads and writes the walk's files, and
10
+ # Walk decides what a call does. Findings go to stderr outside --json, as
11
+ # the TypeScript engine prints them, so stdout holds only where the walk
12
+ # stands.
13
+ module Nukadoko
14
+ class CLI
15
+ class Walked
16
+ ACTIONS = %w[wait next stop].freeze
17
+ DEFAULT_TIMEOUT = 90
18
+
19
+ #: (String, Array[String], Hash[String, Array[String]], json: bool, out: IO, ?err: IO) -> void
20
+ def initialize(project, rest, options, json:, out:, err: $stderr)
21
+ @project = project
22
+ @action = rest[0]
23
+ @pause = rest[1]
24
+ @walk = options["--walk"]&.last
25
+ @timeout = options["--timeout"]&.last
26
+ @json = json
27
+ @out = out
28
+ @err = err
29
+ end
30
+
31
+ #: () -> Integer
32
+ def call
33
+ command = "step #{@action}"
34
+ unless ACTIONS.include?(@action)
35
+ return refuse(command, "invalid-arguments", "nuka step needs one of wait, next, or stop#{@action ? " (got #{@action})" : ""}", run: "nuka step wait")
36
+ end
37
+
38
+ call = call_of
39
+ return refuse(command, "invalid-value", call[:refused], run: "nuka step wait") if call[:refused]
40
+
41
+ timeout = @timeout.nil? ? DEFAULT_TIMEOUT : Float(@timeout, exception: false)
42
+ if timeout.nil? || !timeout.finite? || timeout.negative?
43
+ return refuse(command, "invalid-value", "--timeout must be a number of seconds, 0 or more (got #{@timeout}).")
44
+ end
45
+
46
+ result = Engine::WalkFiles.step_call(@project, call, timeout)
47
+ if result[:kind] == "refuse"
48
+ return refuse(command, result[:code], result[:message], run: result[:do], fields: result[:fields] || {})
49
+ end
50
+
51
+ report = result[:report]
52
+ if @json
53
+ @out.puts JSON.pretty_generate(envelope(command, report[:exit_code], report[:findings], report[:fields]))
54
+ else
55
+ @out.write(text(result[:seen], report[:fields]))
56
+ report[:findings].each { print_finding(_1) }
57
+ end
58
+ report[:exit_code]
59
+ end
60
+
61
+ private
62
+
63
+ # A whole number of 1 or more, as the command line gave it, or nil.
64
+ #: (String?) -> Integer?
65
+ def whole(word)
66
+ number = word && Integer(word, 10, exception: false)
67
+ number if number && number >= 1
68
+ end
69
+
70
+ #: () -> Hash[Symbol, untyped]
71
+ def call_of
72
+ walk = whole(@walk)
73
+ return { refused: "--walk needs the number of a walk, a whole number of 1 or more (got #{@walk})" } if @walk && walk.nil?
74
+ return walk ? { kind: "wait", walk: walk } : { kind: "wait" } if @action == "wait"
75
+
76
+ pause = whole(@pause)
77
+ unless pause
78
+ return { refused: "nuka step #{@action} needs the number of the pause it answers, a whole number of 1 or more#{@pause.nil? ? "" : " (got #{@pause})"}" }
79
+ end
80
+ # An answer without its walk could reach a walk that replaced the
81
+ # one the person was shown.
82
+ return { refused: "nuka step #{@action} needs --walk, the number of the walk whose pause it answers" } unless walk
83
+
84
+ { kind: "answer", walk: walk, pause: pause, answer: @action }
85
+ end
86
+
87
+ #: (String, String) -> String
88
+ def joined(run_dir, relative) = "#{run_dir}/#{relative.tr("\\", "/")}"
89
+
90
+ # What a person reads at a pause: where the step is, what it
91
+ # recorded, the views of the page it left open, and the two answers.
92
+ #: (Hash[Symbol, untyped], Hash[Symbol, untyped]) -> String
93
+ def text(seen, fields)
94
+ case seen[:state]
95
+ when "gone" then "walk #{seen[:last][:number]} #{Engine::Walk.standing(seen)}\n"
96
+ when "paused"
97
+ pause = seen[:pause]
98
+ run_dir = seen[:run_dir]
99
+ scenario = seen[:scenario]
100
+ views = pause[:views].map do |view|
101
+ files = [view[:screenshot], view[:aria]].compact.map { joined(run_dir, _1) }
102
+ name = view[:as].nil? ? "page #{view[:page]}" : "page #{view[:page]} of #{view[:as]}"
103
+ title = view[:title].nil? ? "(no title)" : JSON.generate(view[:title])
104
+ " view: #{name} #{view[:url]} #{title}#{files.empty? ? " (no capture)" : ": #{files.join(" ")}"}"
105
+ end
106
+ stop = pause[:remaining].positive? ? " (or: #{Engine::Walk.answer_command(seen[:number], pause[:pause], "stop")})" : ""
107
+ lines = [
108
+ "walk #{seen[:number]} paused after step #{pause[:pause]}/#{pause[:of]} (#{pause[:status]}): #{pause[:text]}",
109
+ " scenario: #{scenario[:feature]}:#{scenario[:line]} #{scenario[:name]} (#{scenario[:environment]})",
110
+ *(pause[:failure] ? [" failure: #{Engine::Walk.failure_text(pause)}"] : []),
111
+ " record: #{joined(run_dir, pause[:record])}/record.json",
112
+ *views,
113
+ *(seen[:world] ? [" world: #{seen[:world][:url]}"] : []),
114
+ " do: #{Engine::Walk.answer_command(seen[:number], pause[:pause], "next")}#{stop}"
115
+ ]
116
+ "#{lines.join("\n")}\n"
117
+ when "ended"
118
+ run = seen[:end][:how] == "finished" && seen[:run_dir] ? [" run: #{seen[:run_dir]}/run.json"] : []
119
+ "#{["walk #{seen[:number]} #{Engine::Walk.standing(seen)}", *run].join("\n")}\n"
120
+ else
121
+ where = seen[:state] == "starting" ? "is starting: its run has not begun the scenario yet" : Engine::Walk.standing(seen)
122
+ "walk #{seen[:number]} #{where}\n do: #{fields[:do]}\n"
123
+ end
124
+ end
125
+
126
+ #: (String, Integer, Array[Hash[Symbol, untyped]], Hash[Symbol, untyped]) -> Hash[Symbol, untyped]
127
+ def envelope(command, exit_code, findings, fields)
128
+ verdict = { 0 => "passed", 1 => "failed" }.fetch(exit_code, "refused")
129
+ { schema_version: Engine::RunRecord::SCHEMA_VERSION, nukadoko: VERSION, command: command, **fields, verdict: verdict, findings: findings }
130
+ end
131
+
132
+ #: (String, String, String, ?run: String?, ?fields: Hash[Symbol, untyped]) -> Integer
133
+ def refuse(command, code, message, run: nil, fields: {})
134
+ finding = Engine::Refusal.new(code, message, run: run).to_h(command)
135
+ if @json then @out.puts JSON.pretty_generate(envelope(command, 2, [finding], fields))
136
+ else print_finding(finding)
137
+ end
138
+ 2
139
+ end
140
+
141
+ #: (Hash[Symbol, untyped]) -> void
142
+ def print_finding(finding)
143
+ @err.puts [finding[:severity], finding[:code], Engine::Summary.where_of(finding), finding[:message]].join("\t")
144
+ @err.puts " fix: #{finding[:fix]}" if finding[:fix]
145
+ @err.puts " do: #{finding[:do]}" if finding[:do]
146
+ end
147
+ end
148
+ end
149
+ end