ruby_raider 4.0.1 → 4.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 (104) hide show
  1. checksums.yaml +4 -4
  2. data/.github/workflows/e2e_tests.yml +3 -0
  3. data/README.md +58 -1
  4. data/RELEASE.md +25 -0
  5. data/lib/commands/schedule_commands.rb +84 -0
  6. data/lib/generators/templates/common/git_ignore.tt +1 -0
  7. data/lib/ruby_raider/runtime/retry_reset.rb +32 -0
  8. data/lib/ruby_raider/runtime/rspec.rb +1 -0
  9. data/lib/ruby_raider/runtime/show_browser.rb +53 -0
  10. data/lib/ruby_raider/runtime.rb +2 -0
  11. data/lib/ruby_raider.rb +31 -0
  12. data/lib/utilities/schedules/adapter.rb +22 -0
  13. data/lib/utilities/schedules/base.rb +27 -0
  14. data/lib/utilities/schedules/kind.rb +74 -0
  15. data/lib/utilities/schedules/legacy.rb +196 -0
  16. data/lib/utilities/schedules/legacy_stub.rb +62 -0
  17. data/lib/utilities/schedules/next_run.rb +61 -0
  18. data/lib/utilities/schedules/notifier.rb +76 -0
  19. data/lib/utilities/schedules/os/command_runner.rb +73 -0
  20. data/lib/utilities/schedules/os/cron.rb +147 -0
  21. data/lib/utilities/schedules/os/launchd.rb +182 -0
  22. data/lib/utilities/schedules/os/linux.rb +81 -0
  23. data/lib/utilities/schedules/os/systemd.rb +194 -0
  24. data/lib/utilities/schedules/os/task_scheduler.rb +195 -0
  25. data/lib/utilities/schedules/os_enumerator.rb +30 -0
  26. data/lib/utilities/schedules/project.rb +70 -0
  27. data/lib/utilities/schedules/rule.rb +162 -0
  28. data/lib/utilities/schedules/run_lock.rb +160 -0
  29. data/lib/utilities/schedules/run_log.rb +122 -0
  30. data/lib/utilities/schedules/run_report.rb +139 -0
  31. data/lib/utilities/schedules/run_wrapper.rb +216 -0
  32. data/lib/utilities/schedules/schedule.rb +89 -0
  33. data/lib/utilities/schedules/schedule_store.rb +53 -0
  34. data/lib/utilities/schedules/scheduler.rb +178 -0
  35. data/lib/utilities/schedules/scheduler_steps.rb +69 -0
  36. data/lib/utilities/schedules/selection.rb +133 -0
  37. data/lib/utilities/schedules/spawn.rb +68 -0
  38. data/lib/utilities/schedules/store.rb +139 -0
  39. data/lib/version +1 -1
  40. data/ruby_raider.gemspec +1 -0
  41. data/sig/commands/schedule_commands.rbs +12 -0
  42. data/sig/ruby_raider/runtime/retry_reset.rbs +7 -0
  43. data/sig/ruby_raider/runtime/show_browser.rbs +27 -0
  44. data/sig/ruby_raider.rbs +6 -0
  45. data/sig/utilities/schedules/adapter.rbs +5 -0
  46. data/sig/utilities/schedules/base.rbs +15 -0
  47. data/sig/utilities/schedules/kind.rbs +32 -0
  48. data/sig/utilities/schedules/legacy.rbs +45 -0
  49. data/sig/utilities/schedules/legacy_stub.rbs +15 -0
  50. data/sig/utilities/schedules/next_run.rbs +15 -0
  51. data/sig/utilities/schedules/notifier.rbs +29 -0
  52. data/sig/utilities/schedules/os/command_runner.rbs +27 -0
  53. data/sig/utilities/schedules/os/cron.rbs +34 -0
  54. data/sig/utilities/schedules/os/launchd.rbs +46 -0
  55. data/sig/utilities/schedules/os/linux.rbs +33 -0
  56. data/sig/utilities/schedules/os/systemd.rbs +44 -0
  57. data/sig/utilities/schedules/os/task_scheduler.rbs +56 -0
  58. data/sig/utilities/schedules/os_enumerator.rbs +12 -0
  59. data/sig/utilities/schedules/project.rbs +22 -0
  60. data/sig/utilities/schedules/rule.rbs +72 -0
  61. data/sig/utilities/schedules/run_lock.rbs +29 -0
  62. data/sig/utilities/schedules/run_log.rbs +33 -0
  63. data/sig/utilities/schedules/run_report.rbs +34 -0
  64. data/sig/utilities/schedules/run_wrapper.rbs +45 -0
  65. data/sig/utilities/schedules/schedule.rbs +27 -0
  66. data/sig/utilities/schedules/schedule_store.rbs +21 -0
  67. data/sig/utilities/schedules/scheduler.rbs +49 -0
  68. data/sig/utilities/schedules/scheduler_steps.rbs +22 -0
  69. data/sig/utilities/schedules/selection.rbs +36 -0
  70. data/sig/utilities/schedules/spawn.rbs +10 -0
  71. data/sig/utilities/schedules/store.rbs +39 -0
  72. data/spec/commands/schedule_commands_spec.rb +284 -0
  73. data/spec/integration/content/common_content_spec.rb +8 -2
  74. data/spec/integration/content/gemfile_content_spec.rb +2 -2
  75. data/spec/runtime/retry_reset_spec.rb +112 -0
  76. data/spec/runtime/show_browser_project_spec.rb +70 -0
  77. data/spec/runtime/show_browser_spec.rb +101 -0
  78. data/spec/utilities/schedules/kind_spec.rb +81 -0
  79. data/spec/utilities/schedules/legacy_spec.rb +433 -0
  80. data/spec/utilities/schedules/legacy_stub_spec.rb +144 -0
  81. data/spec/utilities/schedules/next_run_spec.rb +119 -0
  82. data/spec/utilities/schedules/notifier_spec.rb +120 -0
  83. data/spec/utilities/schedules/os/command_runner_spec.rb +55 -0
  84. data/spec/utilities/schedules/os/cron_spec.rb +292 -0
  85. data/spec/utilities/schedules/os/launchd_spec.rb +306 -0
  86. data/spec/utilities/schedules/os/linux_spec.rb +163 -0
  87. data/spec/utilities/schedules/os/list_ids_spec.rb +202 -0
  88. data/spec/utilities/schedules/os/systemd_spec.rb +333 -0
  89. data/spec/utilities/schedules/os/task_scheduler_spec.rb +511 -0
  90. data/spec/utilities/schedules/os_entry_spec.rb +54 -0
  91. data/spec/utilities/schedules/os_enumerator_spec.rb +57 -0
  92. data/spec/utilities/schedules/project_spec.rb +125 -0
  93. data/spec/utilities/schedules/run_lock_spec.rb +143 -0
  94. data/spec/utilities/schedules/run_log_spec.rb +83 -0
  95. data/spec/utilities/schedules/run_report_spec.rb +150 -0
  96. data/spec/utilities/schedules/run_wrapper_integration_spec.rb +166 -0
  97. data/spec/utilities/schedules/run_wrapper_spec.rb +430 -0
  98. data/spec/utilities/schedules/schedule_spec.rb +120 -0
  99. data/spec/utilities/schedules/schedule_store_spec.rb +151 -0
  100. data/spec/utilities/schedules/scheduler_launchd_spec.rb +77 -0
  101. data/spec/utilities/schedules/scheduler_spec.rb +445 -0
  102. data/spec/utilities/schedules/selection_spec.rb +176 -0
  103. data/spec/utilities/schedules/spawn_spec.rb +104 -0
  104. metadata +106 -2
@@ -0,0 +1,511 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'tmpdir'
4
+ require 'rexml/document'
5
+ require_relative '../../../../lib/utilities/schedules/os/task_scheduler'
6
+ require_relative '../../../../lib/utilities/schedules/schedule'
7
+
8
+ # The fake runner, fixed clock and project folders sit next to the adapter under test
9
+ # rubocop:disable RSpec/MultipleMemoizedHelpers
10
+ RSpec.describe RubyRaider::Schedules::Os::TaskScheduler do # rubocop:disable RSpec/FilePath
11
+ # Records every command and answers from a table keyed by the schtasks verb; never runs anything
12
+ let(:fake_runner_class) do
13
+ Class.new do
14
+ attr_reader :calls, :answers
15
+
16
+ def initialize
17
+ @calls = []
18
+ @answers = {}
19
+ end
20
+
21
+ def call(*argv, stdin_data: nil)
22
+ @calls << argv
23
+ @seen&.call(argv, stdin_data)
24
+ stderr, status, stdout = answers.fetch(argv[1], ['', 0])
25
+ RubyRaider::Schedules::Os::CommandRunner::Result.new(stdout: stdout.to_s, stderr: stderr, exitstatus: status)
26
+ end
27
+
28
+ def on_call(&block) = @seen = block
29
+ end
30
+ end
31
+
32
+ let(:hostile) { %q('; rm -rf ~; ' </string> %h $(id) " \\ &) }
33
+ let(:tmp) { File.realpath(Dir.mktmpdir('schedules-schtasks')) }
34
+ let(:project_dir) { File.join(tmp, 'plain') }
35
+ let(:runner) { fake_runner_class.new }
36
+ let(:clock) { Struct.new(:now).new(Time.new(2026, 11, 9, 10, 30, 0)) }
37
+ let(:schtasks) { 'C:\\Windows\\System32\\schtasks.exe' }
38
+ let(:scheduler) { described_class.new(kind: RubyRaider::Schedules::Kind::TESTS, runner: runner, clock: clock, schtasks: schtasks) }
39
+ let(:now) { Time.utc(2026, 11, 9, 10, 0, 0) }
40
+
41
+ def schedule(dir: project_dir, gem_env: {}, bundle: '/opt/ruby/bin/bundle', **options)
42
+ FileUtils.mkdir_p(dir)
43
+ # Hermetic: the GEM_HOME/GEM_PATH and bundle this spec runs with never reach the entry; a spec passes its own
44
+ allow(RubyRaider::Schedules::Schedule).to receive_messages(captured_gem_env: gem_env, bundle_path: bundle)
45
+ project = RubyRaider::Schedules::Project.new(File.realpath(dir))
46
+ RubyRaider::Schedules::Schedule.build(project: project, name: 'report', every: 'day', at: '08:00', now: now, **options)
47
+ end
48
+
49
+ def task_name(item) = "\\RubyRaider\\#{item.os_id}"
50
+
51
+ # schtasks /Query /FO CSV /NH: one row per task, full name first
52
+ def csv_rows(*names) = names.map { |name| %("#{name}","11/10/2026 8:00:00 AM","Ready"\r\n) }.join
53
+
54
+ def list_call = [schtasks, '/Query', '/FO', 'CSV', '/NH']
55
+
56
+ # CommandLineToArgvW / MSVCRT rules for the arguments after the program name: 2n backslashes and a
57
+ # quote give n backslashes and toggle quoting, 2n+1 give n and a literal quote, other backslashes are
58
+ # literal, unquoted space or tab splits. The quoter never writes "" inside quotes, so the post-2008
59
+ # MSVCRT "" rule never applies.
60
+ def split_arguments(line)
61
+ args = []
62
+ current = nil
63
+ quoted = false
64
+ index = 0
65
+ while index < line.length
66
+ char = line[index]
67
+ if char == '\\'
68
+ run = line[index..][/\A\\+/].length
69
+ index += run
70
+ if line[index] == '"'
71
+ current = "#{current}#{'\\' * (run / 2)}"
72
+ if run.odd?
73
+ current += '"'
74
+ index += 1
75
+ end
76
+ else
77
+ current = "#{current}#{'\\' * run}"
78
+ end
79
+ next
80
+ elsif char == '"'
81
+ quoted = !quoted
82
+ current ||= +''
83
+ elsif [' ', "\t"].include?(char) && !quoted
84
+ args << current if current
85
+ current = nil
86
+ else
87
+ current = "#{current}#{char}"
88
+ end
89
+ index += 1
90
+ end
91
+ args << current if current
92
+ args
93
+ end
94
+
95
+ # ruby.exe's own reading: a port of w32_cmdvector in ruby/win32/win32.c. Pass 1 splits on unquoted
96
+ # space, tab or newline (' and " both quote; a backslash counts toward escaping a quote except inside
97
+ # '...'), and marks a * ? [ { outside '...' (even inside "...") for globbing. Pass 2 strips the quotes:
98
+ # an even run of backslashes before a quote of the other kind is left as it is, every other quote eats
99
+ # (run + 1) / 2 backslashes. A globbed element is refused here: the quoter must never produce one.
100
+ def ruby_split_arguments(line)
101
+ elements = []
102
+ index = 0
103
+ loop do
104
+ index += 1 while line[index]&.match?(/[ \t\n\v\f\r]/)
105
+ break if index >= line.length
106
+
107
+ element, index, glob = ruby_element(line, index)
108
+ raise "ruby.exe would glob #{element.inspect} in #{line.inspect}" if glob
109
+
110
+ elements << element
111
+ end
112
+ elements
113
+ end
114
+
115
+ def ruby_element(line, index)
116
+ base = index
117
+ quote = nil
118
+ slashes = 0
119
+ glob = false
120
+ done = false
121
+ while !done && index < line.length
122
+ char = line[index]
123
+ case char
124
+ when '\\' then slashes += 1 unless quote == "'"
125
+ when ' ', "\t", "\n"
126
+ done = true unless quote
127
+ slashes = 0
128
+ when '*', '?', '[', '{'
129
+ glob = true unless quote == "'"
130
+ slashes = 0
131
+ when "'", '"'
132
+ if slashes.even?
133
+ if quote.nil? then quote = char
134
+ elsif quote == char
135
+ index += 1 if char == '"' && line[index + 1] == '"'
136
+ quote = nil
137
+ end
138
+ end
139
+ slashes = 0
140
+ else slashes = 0
141
+ end
142
+ index += 1
143
+ end
144
+ length = index - base - (done ? 1 : 0)
145
+ [ruby_unquote(line[base, length]), index, glob]
146
+ end
147
+
148
+ def ruby_unquote(text)
149
+ chars = text.chars
150
+ at = 0
151
+ slashes = 0
152
+ quote = nil
153
+ while at < chars.length
154
+ char = chars[at]
155
+ if char == '\\'
156
+ at += 1
157
+ slashes += 1 unless quote == "'"
158
+ next
159
+ end
160
+ unless ["'", '"'].include?(char)
161
+ at += 1
162
+ slashes = 0
163
+ next
164
+ end
165
+ if slashes.even? && quote && quote != char
166
+ at += 1
167
+ slashes = 0
168
+ next
169
+ end
170
+ eaten = (slashes + 1) / 2
171
+ chars.slice!(at - eaten, eaten + (slashes.even? ? 1 : 0))
172
+ at -= eaten
173
+ if slashes.odd?
174
+ at += 1
175
+ elsif quote
176
+ at += 1 if quote == '"' && chars[at] == '"'
177
+ quote = nil
178
+ else
179
+ quote = char
180
+ end
181
+ slashes = 0
182
+ end
183
+ chars.join
184
+ end
185
+
186
+ def parsed(text) = REXML::Document.new(text)
187
+
188
+ def field(text, path) = parsed(text).elements[path]&.text.to_s
189
+
190
+ # What a daily 08:00 schedule must produce, byte for byte
191
+ def daily_xml(item)
192
+ args = described_class.join(item.argv.drop(1))
193
+
194
+ <<~XML
195
+ <?xml version="1.0" encoding="UTF-16"?>
196
+ <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
197
+ <RegistrationInfo>
198
+ <Description>Ruby Raider schedule report (every day at 08:00)</Description>
199
+ <URI>\\RubyRaider\\#{item.os_id}</URI>
200
+ </RegistrationInfo>
201
+ <Triggers>
202
+ <CalendarTrigger>
203
+ <StartBoundary>2026-11-10T08:00:00</StartBoundary>
204
+ <Enabled>true</Enabled>
205
+ <ScheduleByDay>
206
+ <DaysInterval>1</DaysInterval>
207
+ </ScheduleByDay>
208
+ </CalendarTrigger>
209
+ </Triggers>
210
+ <Principals>
211
+ <Principal id="Author">
212
+ <LogonType>InteractiveToken</LogonType>
213
+ <RunLevel>LeastPrivilege</RunLevel>
214
+ </Principal>
215
+ </Principals>
216
+ <Settings>
217
+ <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
218
+ <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
219
+ <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
220
+ <StartWhenAvailable>true</StartWhenAvailable>
221
+ <Enabled>true</Enabled>
222
+ </Settings>
223
+ <Actions Context="Author">
224
+ <Exec>
225
+ <Command>#{item.ruby}</Command>
226
+ <Arguments>#{args}</Arguments>
227
+ <WorkingDirectory>#{item.working_directory}</WorkingDirectory>
228
+ </Exec>
229
+ </Actions>
230
+ </Task>
231
+ XML
232
+ end
233
+
234
+ after { FileUtils.rm_rf(tmp) }
235
+
236
+ it 'is called Task Scheduler in messages' do
237
+ expect(scheduler.label).to eq('Task Scheduler')
238
+ end
239
+
240
+ it 'names the task under the RubyRaider folder' do
241
+ item = schedule
242
+ expect(scheduler.task_name(item.os_id)).to eq(task_name(item))
243
+ end
244
+
245
+ describe '.quote' do
246
+ {
247
+ 'plain' => 'plain',
248
+ '' => '""',
249
+ 'with space' => '"with space"',
250
+ "tab\there" => "\"tab\there\"",
251
+ 'C:\\path with space\\' => '"C:\\path with space\\\\"',
252
+ 'C:\\no\\space\\' => 'C:\\no\\space\\',
253
+ 'a\\"b' => '"a\\\\\\"b"',
254
+ 'say "hi"' => '"say \\"hi\\""',
255
+ 'a\\\\b c' => '"a\\\\b c"',
256
+ '%h&$(id)' => '%h&$(id)',
257
+ "O'Brien" => %("O'Brien"),
258
+ 'a*b' => "'a*b'",
259
+ 'p[1]' => "'p[1]'",
260
+ 'q?' => "'q?'",
261
+ '{x}' => "'{x}'",
262
+ 'x{1,2}' => "'x{1,2}'",
263
+ 'C:\\a b\\*.rb' => "'C:\\a b\\*.rb'",
264
+ 'a*"b' => %('a*"b'),
265
+ "a\\'b c" => %("a\\\\\\'b c"),
266
+ "a\\\\'b c" => %("a\\\\'b c")
267
+ }.each do |arg, quoted|
268
+ it "quotes #{arg.inspect} as #{quoted.inspect}" do
269
+ expect(described_class.quote(arg)).to eq(quoted)
270
+ end
271
+ end
272
+
273
+ # ruby.exe is the real reader; CommandLineToArgvW agrees except on '...' and on backslashes before '
274
+ it 'gives back every argument when the joined line is read by ruby.exe, and by CommandLineToArgvW where they agree' do
275
+ plain = ['', 'C:\\path with space\\', 'a\\"b', '\\\\', '"', 'x\\', "'; rm -rf ~; '", '</string>', '%h', '$(id)', '\\', '&', hostile,
276
+ "C:\\Users\\O'Brien\\proj", "a=x'", "b=y'", "it's \\\"x\\\" \\"]
277
+ ruby_only = ['p[1]', 'a*b', 'q?', '{x}', 'x{1,2}', 'C:\\a b\\*.rb', 'a*"b\\', "a\\'b c", "a\\\\'b c", "a\\\\\\'b c", "C:\\x\\'q' y"]
278
+
279
+ expect(ruby_split_arguments(described_class.join(plain + ruby_only))).to eq(plain + ruby_only)
280
+ expect(split_arguments(described_class.join(plain))).to eq(plain)
281
+ end
282
+
283
+ it "refuses an argument with both ' and a glob character" do
284
+ expect { described_class.quote("a'*") }.to raise_error(RubyRaider::Schedules::Error, /can not pass "a'\*" to ruby\.exe/)
285
+ end
286
+ end
287
+
288
+ describe '#task_xml' do
289
+ it 'writes the exact task for a daily schedule' do
290
+ item = schedule
291
+ expect(scheduler.task_xml(item)).to eq(daily_xml(item))
292
+ end
293
+
294
+ it 'carries no environment and no log file' do
295
+ # Without the random temp folder's name, which may hold any of these words
296
+ text = scheduler.task_xml(schedule).gsub(tmp, '')
297
+
298
+ expect(text).not_to include('scheduler.log', 'Environment', 'GEM_HOME', 'cmd', 'powershell')
299
+ end
300
+
301
+ it 'runs ruby with the bundle path and the schedule run arguments' do
302
+ item = schedule(retries: 2, selection: RubyRaider::Schedules::Selection.new(kind: 'tag', tag: 'smoke'))
303
+ text = scheduler.task_xml(item)
304
+
305
+ expect(field(text, 'Task/Actions/Exec/Command')).to eq(item.ruby)
306
+ expect(split_arguments(field(text, 'Task/Actions/Exec/Arguments'))).to eq(item.argv.drop(1))
307
+ expect(field(text, 'Task/Actions/Exec/WorkingDirectory')).to eq(item.working_directory)
308
+ end
309
+
310
+ it 'starts at the next run: an 11:00 rule at 10:30 starts today at 11:00' do
311
+ trigger = parsed(scheduler.task_xml(schedule(every: 'day', at: '11:00'))).elements['Task/Triggers/CalendarTrigger']
312
+
313
+ expect(trigger.elements['StartBoundary'].text).to eq('2026-11-09T11:00:00')
314
+ end
315
+
316
+ it 'runs every hour from its next run, repeating hourly for a day' do
317
+ trigger = parsed(scheduler.task_xml(schedule(every: 'hour', at: ':15'))).elements['Task/Triggers/CalendarTrigger']
318
+
319
+ expect(trigger.elements.map(&:name)).to eq(%w[Repetition StartBoundary Enabled ScheduleByDay])
320
+ expect(%w[Repetition/Interval Repetition/Duration StartBoundary ScheduleByDay/DaysInterval].map { |path| trigger.elements[path].text })
321
+ .to eq(%w[PT1H P1D 2026-11-09T11:15:00 1])
322
+ end
323
+
324
+ it 'runs every weekday Monday to Friday, weekly' do
325
+ trigger = parsed(scheduler.task_xml(schedule(every: 'weekday', at: '18:05'))).elements['Task/Triggers/CalendarTrigger']
326
+
327
+ expect(trigger.elements['StartBoundary'].text).to eq('2026-11-09T18:05:00')
328
+ expect(trigger.elements['ScheduleByWeek'].elements.map(&:name)).to eq(%w[DaysOfWeek WeeksInterval])
329
+ expect(trigger.elements['ScheduleByWeek/DaysOfWeek'].elements.map(&:name)).to eq(%w[Monday Tuesday Wednesday Thursday Friday])
330
+ expect(trigger.elements['ScheduleByWeek/WeeksInterval'].text).to eq('1')
331
+ end
332
+
333
+ it 'runs every week on its one day' do
334
+ days = %w[mon sat sun].map do |on|
335
+ trigger = parsed(scheduler.task_xml(schedule(every: 'week', on: on))).elements['Task/Triggers/CalendarTrigger']
336
+ [trigger.elements['ScheduleByWeek/DaysOfWeek'].elements.map(&:name), trigger.elements['StartBoundary'].text]
337
+ end
338
+
339
+ expect(days).to eq([[%w[Monday], '2026-11-16T08:00:00'], [%w[Saturday], '2026-11-14T08:00:00'], [%w[Sunday], '2026-11-15T08:00:00']])
340
+ end
341
+
342
+ # One at a time: a lone % in both would read as %...% across the joined Arguments and be refused
343
+ {
344
+ 'the bundle path' => ->(spec) { spec.schedule(bundle: "/opt/#{spec.hostile}/bundle") },
345
+ 'the project path' => ->(spec) { spec.schedule(dir: File.join(spec.tmp, 'p<', "string> #{spec.hostile}")) }
346
+ }.each do |where, build|
347
+ describe "with hostile values in #{where}" do
348
+ let(:item) { build.call(self) }
349
+ let(:text) { scheduler.task_xml(item) }
350
+
351
+ it 'round-trips them through CRT quoting and XML escaping' do
352
+ line = field(text, 'Task/Actions/Exec/Arguments')
353
+
354
+ expect([split_arguments(line), ruby_split_arguments(line)]).to eq([item.argv.drop(1), item.argv.drop(1)])
355
+ expect(field(text, 'Task/Actions/Exec/WorkingDirectory')).to eq(item.working_directory)
356
+ expect(item.argv.join).to include('</string>', "'; rm -rf ~; '", '$(id)', '%h', '"', '\\', '&')
357
+ end
358
+
359
+ it 'writes them only in escaped form' do
360
+ expect(text).not_to include('</string>', "'; rm", '" \\')
361
+ expect(text.scan(/&(?!amp;|lt;|gt;|quot;|apos;)/)).to be_empty
362
+ expect(text).to include('&lt;/string&gt;', '&apos;; rm -rf ~; &apos;', '\\&quot; \\ &amp;', '$(id)', '%h')
363
+ end
364
+ end
365
+ end
366
+ end
367
+
368
+ describe 'with quotes and glob characters but no spaces' do
369
+ let(:item) { schedule(dir: File.join(tmp, 'Users', "O'Brien", "proj'"), bundle: '/opt/p[1]/a*b/bundle') }
370
+
371
+ it "quotes them so ruby.exe reads the exact argv back and globs nothing ('...' around a glob)" do
372
+ line = field(scheduler.task_xml(item), 'Task/Actions/Exec/Arguments')
373
+
374
+ expect(ruby_split_arguments(line)).to eq(item.argv.drop(1))
375
+ expect(line).to include(%("#{item.project_root}"), "'/opt/p[1]/a*b/bundle'")
376
+ end
377
+
378
+ it "refuses an argument with both ' and a glob character before any schtasks call" do
379
+ expect { scheduler.install(schedule(bundle: "/opt/a'*/bundle")) }.to raise_error(RubyRaider::Schedules::Error, /ruby\.exe/)
380
+ expect(runner.calls).to be_empty
381
+ end
382
+ end
383
+
384
+ describe 'with %NAME% that Task Scheduler would expand' do
385
+ it 'refuses it in the bundle path before any schtasks call' do
386
+ item = schedule(bundle: '/opt/%PATH%/bundle')
387
+
388
+ expect { scheduler.install(item) }.to raise_error(RubyRaider::Schedules::Error, /Task Scheduler would expand %PATH% as an environment variable/)
389
+ expect(runner.calls).to be_empty
390
+ end
391
+
392
+ it 'refuses it in the project path before any schtasks call' do
393
+ item = schedule(dir: File.join(tmp, '%PATH%', 'proj'))
394
+
395
+ expect { scheduler.install(item) }.to raise_error(RubyRaider::Schedules::Error, /would expand %PATH%/)
396
+ expect { scheduler.task_xml(item) }.to raise_error(RubyRaider::Schedules::Error, /would expand %PATH%/)
397
+ expect(runner.calls).to be_empty
398
+ end
399
+
400
+ it 'refuses a %...% formed across two arguments in the joined Arguments' do
401
+ item = schedule(dir: File.join(tmp, 'y%'), bundle: '/opt/%x/bundle')
402
+
403
+ expect { scheduler.install(item) }.to raise_error(RubyRaider::Schedules::Error, %r{would expand %x/bundle exec raider schedule run report --project .*/y%})
404
+ expect(runner.calls).to be_empty
405
+ end
406
+
407
+ it 'keeps a lone %' do
408
+ item = schedule(dir: File.join(tmp, '100% sure'))
409
+
410
+ expect(split_arguments(field(scheduler.task_xml(item), 'Task/Actions/Exec/Arguments'))).to eq(item.argv.drop(1))
411
+ expect(item.project_root).to end_with('/100% sure')
412
+ end
413
+ end
414
+
415
+ describe '#install' do
416
+ it 'writes the task as UTF-16LE with a BOM, creates it with schtasks and deletes the file' do
417
+ item = schedule
418
+ written = nil
419
+ path = nil
420
+ runner.on_call { |argv, _| written = File.binread(path = argv[5]) if argv[1] == '/Create' }
421
+
422
+ expect(scheduler.install(item)).to be(true)
423
+ expect(runner.calls).to eq([[schtasks, '/Create', '/TN', task_name(item), '/XML', path, '/F']])
424
+ expect(written.byteslice(0, 2).bytes).to eq([0xFF, 0xFE])
425
+ expect(written.byteslice(2..).force_encoding(Encoding::UTF_16LE).encode(Encoding::UTF_8)).to eq(scheduler.task_xml(item))
426
+ expect(File.exist?(path)).to be(false)
427
+ end
428
+
429
+ it 'raises with the scheduler error and still deletes the file when schtasks fails' do
430
+ item = schedule
431
+ path = nil
432
+ runner.on_call { |argv, _| path = argv[5] }
433
+ runner.answers['/Create'] = ["ERROR: Access is denied.\e[2J\n", 1]
434
+
435
+ expect { scheduler.install(item) }.to raise_error(RubyRaider::Schedules::Error, /Task Scheduler.*#{Regexp.escape(item.os_id)}.*Access is denied\.\?\[2J/)
436
+ expect(File.exist?(path)).to be(false)
437
+ end
438
+ end
439
+
440
+ describe '#remove' do
441
+ it 'deletes the task' do
442
+ item = schedule
443
+
444
+ expect(scheduler.remove(item.os_id)).to be(true)
445
+ expect(runner.calls).to eq([[schtasks, '/Delete', '/TN', task_name(item), '/F']])
446
+ end
447
+
448
+ it 'is false when the delete fails and the task list does not show it' do
449
+ item = schedule
450
+ runner.answers['/Delete'] = ['ERROR: The system cannot find the file specified.', 1]
451
+ runner.answers['/Query'] = ['', 0, csv_rows('\\Other', "#{task_name(item)}_old")]
452
+
453
+ expect(scheduler.remove(item.os_id)).to be(false)
454
+ expect(runner.calls).to eq([[schtasks, '/Delete', '/TN', task_name(item), '/F'], list_call])
455
+ end
456
+
457
+ it 'raises with the delete error when the task list still shows it' do
458
+ item = schedule
459
+ runner.answers['/Delete'] = ["ERROR: Access\e is denied.\n", 1]
460
+ runner.answers['/Query'] = ['', 0, csv_rows('\\Other', task_name(item))]
461
+
462
+ expect { scheduler.remove(item.os_id) }.to raise_error(RubyRaider::Schedules::Error, /Task Scheduler could not delete .*Access\? is denied\.\z/)
463
+ end
464
+
465
+ it 'raises with the delete error when the task list can not be read' do
466
+ runner.answers['/Delete'] = ['ERROR: Access is denied.', 1]
467
+ runner.answers['/Query'] = ['ERROR: list failed', 1]
468
+
469
+ expect { scheduler.remove(schedule.os_id) }.to raise_error(RubyRaider::Schedules::Error, /could not delete .*Access is denied/)
470
+ end
471
+
472
+ it 'refuses an os_id that is not a schedule id' do
473
+ expect { scheduler.remove('..\\..\\evil') }.to raise_error(RubyRaider::Schedules::Error, /Invalid os_id/)
474
+ expect(runner.calls).to be_empty
475
+ end
476
+ end
477
+
478
+ describe '#present?' do
479
+ it 'is true when the task list shows the exact task name' do
480
+ item = schedule
481
+ runner.answers['/Query'] = ['', 0, csv_rows('\\Other', task_name(item))]
482
+
483
+ expect(scheduler.present?(item.os_id)).to be(true)
484
+ expect(runner.calls).to eq([list_call])
485
+ end
486
+
487
+ it 'is false when it shows only other tasks' do
488
+ item = schedule
489
+ runner.answers['/Query'] = ['', 0, csv_rows("#{task_name(item)}_old", '\\Other')]
490
+
491
+ expect(scheduler.present?(item.os_id)).to be(false)
492
+ end
493
+
494
+ it 'raises when the task list can not be read' do
495
+ runner.answers['/Query'] = ["ERROR: no\e list", 1]
496
+
497
+ expect { scheduler.present?(schedule.os_id) }.to raise_error(RubyRaider::Schedules::Error, /could not list tasks: ERROR: no\? list/)
498
+ end
499
+ end
500
+
501
+ it 'runs schtasks.exe from SystemRoot by default' do
502
+ allow(ENV).to receive(:fetch).and_call_original
503
+ allow(ENV).to receive(:fetch).with('SystemRoot', anything).and_return('D:\\Win')
504
+ item = schedule
505
+
506
+ described_class.new(kind: RubyRaider::Schedules::Kind::TESTS, runner: runner, clock: clock).remove(item.os_id)
507
+
508
+ expect(runner.calls.first.first).to eq(File.join('D:\\Win', 'System32', 'schtasks.exe'))
509
+ end
510
+ end
511
+ # rubocop:enable RSpec/MultipleMemoizedHelpers
@@ -0,0 +1,54 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'tmpdir'
4
+ require_relative '../../../lib/utilities/schedules/schedule'
5
+ require_relative '../../../lib/utilities/schedules/os/launchd'
6
+ require_relative '../../../lib/utilities/schedules/os/task_scheduler'
7
+ require_relative '../../../lib/utilities/schedules/os/systemd'
8
+ require_relative '../../../lib/utilities/schedules/os/cron'
9
+
10
+ # The OS entry of a test schedule holds its name only: the selection, retries, notify and show_browser
11
+ # are read from schedules.yml at run time, so no file name or tag can reach a plist, XML, unit or crontab.
12
+ RSpec.describe 'A test schedule OS entry' do
13
+ let(:tmp) { File.realpath(Dir.mktmpdir('schedules-entry')) }
14
+ let(:root) { File.join(tmp, 'project') }
15
+ let(:runner) { instance_double(RubyRaider::Schedules::Os::CommandRunner) }
16
+ let(:now) { Time.utc(2026, 11, 9, 10, 0, 0) }
17
+ let(:hostile) { %q(spec/$(id) & <x> "q" 'p' %PATH% `w`; rm -rf ~_spec.rb) }
18
+
19
+ before do
20
+ FileUtils.mkdir_p(File.join(root, 'spec'))
21
+ [hostile, 'spec/a_spec.rb'].each { |file| File.write(File.join(root, file), '') }
22
+ end
23
+
24
+ after { FileUtils.rm_rf(tmp) }
25
+
26
+ def schedule(**options)
27
+ project = RubyRaider::Schedules::Project.new(root)
28
+ RubyRaider::Schedules::Schedule.build(project: project, name: 'nightly', every: 'weekday', at: '07:30', now: now, host_os: 'darwin24', **options)
29
+ end
30
+
31
+ def kind = RubyRaider::Schedules::Kind::TESTS
32
+
33
+ def entries(item)
34
+ clock = Struct.new(:now).new(Time.new(2026, 11, 9, 10, 30, 0))
35
+ systemd = RubyRaider::Schedules::Os::Systemd.new(kind: kind, runner: runner, home: tmp, config_home: nil)
36
+ [RubyRaider::Schedules::Os::Launchd.new(kind: kind, runner: runner, home: tmp, uid: 501).plist(item),
37
+ RubyRaider::Schedules::Os::TaskScheduler.new(kind: kind, runner: runner, clock: clock, schtasks: 'C:\\schtasks.exe').task_xml(item),
38
+ systemd.service(item), systemd.timer(item), RubyRaider::Schedules::Os::Cron.new(kind: kind, runner: runner).line(item)]
39
+ end
40
+
41
+ it 'is byte-identical for two different selections, retries, notify and show_browser' do
42
+ files = RubyRaider::Schedules::Selection.parse(files: [hostile, 'spec/a_spec.rb'], tag: nil, root: root, host_os: 'darwin24')
43
+ all_tests = entries(schedule)
44
+ picked = entries(schedule(selection: files, retries: 3, notify: true, show_browser: true))
45
+ tagged = entries(schedule(selection: RubyRaider::Schedules::Selection.parse(files: [], tag: 'zz_tag_sentinel', root: root, host_os: 'darwin24')))
46
+
47
+ expect([picked, tagged]).to eq([all_tests, all_tests])
48
+ expect(all_tests.join).not_to include('rm -rf', '%PATH%', 'a_spec.rb', 'zz_tag_sentinel', '--retries', '--notify', 'show-browser', 'show_browser')
49
+ end
50
+
51
+ it 'names the test schedule kind and the schedule in every entry' do
52
+ expect(entries(schedule)).to all(include('nightly', 'schedule'))
53
+ end
54
+ end
@@ -0,0 +1,57 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'tmpdir'
4
+ require_relative '../../../lib/utilities/schedules/os_enumerator'
5
+ require_relative '../../../lib/utilities/schedules/schedule'
6
+
7
+ RSpec.describe RubyRaider::Schedules::OsEnumerator do # rubocop:disable RSpec/FilePath
8
+ # Answers list_ids with what it was given, recording the prefix asked for
9
+ let(:fake_adapter) do
10
+ Class.new do
11
+ attr_reader :asked
12
+
13
+ def initialize(ids = [], error: nil)
14
+ @ids = ids
15
+ @error = error
16
+ end
17
+
18
+ def list_ids(prefix)
19
+ @asked = prefix
20
+ raise @error if @error
21
+
22
+ @ids
23
+ end
24
+ end
25
+ end
26
+
27
+ let(:root) { '/projects/shop' }
28
+ let(:prefix) { RubyRaider::Schedules::Schedule.os_id_prefix_for(root) }
29
+ let(:other) { RubyRaider::Schedules::Schedule.os_id_prefix_for('/projects/other') }
30
+ let(:legacy) { Class.new(RubyRaider::Schedules::Rule) { def self.kind = RubyRaider::Schedules::Kind::FLOW_LEGACY }.os_id_prefix_for(root) }
31
+
32
+ def enumerator(adapter) = described_class.new(adapter, schedule_class: RubyRaider::Schedules::Schedule, root: root)
33
+
34
+ it "asks for this project's prefix and returns the schedule names, sorted and once each" do
35
+ adapter = fake_adapter.new(["#{prefix}smoke", "#{prefix}nightly", "#{prefix}smoke"])
36
+
37
+ expect(enumerator(adapter).names).to eq(%w[nightly smoke])
38
+ expect(adapter.asked).to eq(prefix)
39
+ end
40
+
41
+ it "ignores what an adapter should not have returned: another project's, a flow's and hostile ids" do
42
+ hostile = ["#{other}nightly", "#{legacy}nightly", "#{prefix}../../x", "#{prefix}a;rm -rf ~", "#{prefix}Bad", nil, 42,
43
+ "#{prefix}ok\nx", "#{prefix}a\xFF".dup.force_encoding(Encoding::UTF_8), "#{prefix}#{'a' * 61}"]
44
+
45
+ expect(enumerator(fake_adapter.new(hostile + ["#{prefix}ok"])).names).to eq(%w[ok])
46
+ end
47
+
48
+ it 'is empty when the OS scheduler can not be read, or the adapter can not enumerate' do
49
+ failing = fake_adapter.new(error: RubyRaider::Schedules::Error.new('task list unreadable'))
50
+
51
+ expect([enumerator(failing).names, enumerator(Object.new).names, enumerator(fake_adapter.new(nil)).names]).to eq([[], [], []])
52
+ end
53
+
54
+ it 'lets an unexpected error through' do
55
+ expect { enumerator(fake_adapter.new(error: ArgumentError.new('bug'))).names }.to raise_error(ArgumentError, 'bug')
56
+ end
57
+ end