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,306 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'tmpdir'
4
+ require 'rexml/document'
5
+ require_relative '../../../../lib/utilities/schedules/os/launchd'
6
+ require_relative '../../../../lib/utilities/schedules/schedule'
7
+
8
+ # The fake runner, temp home and project folders sit next to the adapter under test
9
+ # rubocop:disable RSpec/MultipleMemoizedHelpers
10
+ RSpec.describe RubyRaider::Schedules::Os::Launchd do # rubocop:disable RSpec/FilePath
11
+ # Records every command and answers from a table (success unless told otherwise); never runs anything
12
+ let(:fake_runner_class) do
13
+ Class.new do
14
+ attr_reader :calls, :answers, :stdin
15
+
16
+ def initialize
17
+ @calls = []
18
+ @answers = {}
19
+ @stdin = []
20
+ end
21
+
22
+ def call(*argv, stdin_data: nil)
23
+ @calls << argv
24
+ @stdin << stdin_data
25
+ @seen&.call(argv)
26
+ stderr, status = answers.fetch(argv[1], ['', 0])
27
+ RubyRaider::Schedules::Os::CommandRunner::Result.new(stdout: '', stderr: stderr, exitstatus: status)
28
+ end
29
+
30
+ def on_call(&block) = @seen = block
31
+ end
32
+ end
33
+
34
+ let(:hostile) { %q('; rm -rf ~; ' </string> %h $(id) " \\ &) }
35
+ let(:tmp) { File.realpath(Dir.mktmpdir('schedules-launchd')) }
36
+ let(:home) { File.join(tmp, 'home') }
37
+ let(:project_dir) { File.join(tmp, 'plain') }
38
+ let(:runner) { fake_runner_class.new }
39
+ let(:launchd) { described_class.new(kind: RubyRaider::Schedules::Kind::TESTS, runner: runner, home: home, uid: 501) }
40
+ let(:now) { Time.utc(2026, 11, 9, 10, 0, 0) }
41
+ let(:agents) { File.join(home, 'Library', 'LaunchAgents') }
42
+
43
+ def schedule(dir: project_dir, gem_env: {}, bundle: '/opt/ruby/bin/bundle', **options)
44
+ FileUtils.mkdir_p(dir)
45
+ # Hermetic: the GEM_HOME/GEM_PATH and bundle this spec runs with never reach the entry; a spec passes its own
46
+ allow(RubyRaider::Schedules::Schedule).to receive_messages(captured_gem_env: gem_env, bundle_path: bundle)
47
+ project = RubyRaider::Schedules::Project.new(File.realpath(dir))
48
+ RubyRaider::Schedules::Schedule.build(project: project, name: 'report', every: 'day', at: '08:00', now: now, **options)
49
+ end
50
+
51
+ # plist XML back to Ruby: dict -> Hash, array -> Array, string -> String, integer -> Integer
52
+ def plist_value(element)
53
+ case element.name
54
+ when 'dict'
55
+ element.elements.to_a.each_slice(2).to_h { |key, value| [key.text, plist_value(value)] }
56
+ when 'array' then element.elements.map { |child| plist_value(child) }
57
+ when 'integer' then Integer(element.text)
58
+ else element.text.to_s
59
+ end
60
+ end
61
+
62
+ def parsed(text)
63
+ document = REXML::Document.new(text)
64
+ expect(document.root.name).to eq('plist')
65
+ plist_value(document.root.elements.first)
66
+ end
67
+
68
+ # What a daily 08:00 schedule must produce, byte for byte
69
+ def daily_plist(item)
70
+ env = item.env.map { |key, value| "\t\t<key>#{key}</key>\n\t\t<string>#{value}</string>\n" }.join
71
+ args = item.argv.map { |arg| "\t\t<string>#{arg}</string>\n" }.join
72
+
73
+ <<~PLIST
74
+ <?xml version="1.0" encoding="UTF-8"?>
75
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
76
+ <plist version="1.0">
77
+ <dict>
78
+ \t<key>Label</key>
79
+ \t<string>#{item.os_id}</string>
80
+ \t<key>ProgramArguments</key>
81
+ \t<array>
82
+ #{args.chomp}
83
+ \t</array>
84
+ \t<key>WorkingDirectory</key>
85
+ \t<string>#{item.working_directory}</string>
86
+ \t<key>StandardOutPath</key>
87
+ \t<string>#{item.log_path}</string>
88
+ \t<key>StandardErrorPath</key>
89
+ \t<string>#{item.log_path}</string>
90
+ \t<key>EnvironmentVariables</key>
91
+ \t<dict>
92
+ #{env.chomp}
93
+ \t</dict>
94
+ \t<key>StartCalendarInterval</key>
95
+ \t<dict>
96
+ \t\t<key>Hour</key>
97
+ \t\t<integer>8</integer>
98
+ \t\t<key>Minute</key>
99
+ \t\t<integer>0</integer>
100
+ \t</dict>
101
+ </dict>
102
+ </plist>
103
+ PLIST
104
+ end
105
+
106
+ def plist_path(item) = File.join(agents, "#{item.os_id}.plist")
107
+
108
+ after { FileUtils.rm_rf(tmp) }
109
+
110
+ it 'is called launchd in messages' do
111
+ expect(launchd.label).to eq('launchd')
112
+ end
113
+
114
+ describe '#plist' do
115
+ it 'writes the exact plist for a daily schedule' do
116
+ item = schedule
117
+ expect(launchd.plist(item)).to eq(daily_plist(item))
118
+ end
119
+
120
+ it 'round-trips every field and never sets RunAtLoad' do
121
+ item = schedule(retries: 2, selection: RubyRaider::Schedules::Selection.new(kind: 'tag', tag: 'smoke'))
122
+
123
+ expect(parsed(launchd.plist(item))).to eq(
124
+ 'Label' => item.os_id, 'ProgramArguments' => item.argv, 'WorkingDirectory' => item.working_directory,
125
+ 'StandardOutPath' => item.log_path, 'StandardErrorPath' => item.log_path, 'EnvironmentVariables' => item.env,
126
+ 'StartCalendarInterval' => { 'Hour' => 8, 'Minute' => 0 }
127
+ )
128
+ end
129
+
130
+ it 'keeps GEM_HOME and GEM_PATH in the environment when they were captured' do
131
+ env = parsed(launchd.plist(schedule(gem_env: { 'GEM_HOME' => '/g/home', 'GEM_PATH' => '/g/path' })))['EnvironmentVariables']
132
+
133
+ expect(env.slice('LANG', 'GEM_HOME', 'GEM_PATH')).to eq('LANG' => 'en_US.UTF-8', 'GEM_HOME' => '/g/home', 'GEM_PATH' => '/g/path')
134
+ end
135
+
136
+ it 'runs every hour at its minute' do
137
+ expect(parsed(launchd.plist(schedule(every: 'hour', at: ':15')))['StartCalendarInterval']).to eq('Minute' => 15)
138
+ end
139
+
140
+ it 'runs every weekday as five dicts, Monday 1 to Friday 5' do
141
+ interval = parsed(launchd.plist(schedule(every: 'weekday', at: '18:05')))['StartCalendarInterval']
142
+
143
+ expect(interval).to eq((1..5).map { |day| { 'Weekday' => day, 'Hour' => 18, 'Minute' => 5 } })
144
+ end
145
+
146
+ it 'runs every week on its day, Sunday 0 and Saturday 6' do
147
+ days = %w[sun mon sat].map { |on| parsed(launchd.plist(schedule(every: 'week', on: on)))['StartCalendarInterval'] }
148
+
149
+ expect(days).to eq([0, 1, 6].map { |day| { 'Weekday' => day, 'Hour' => 8, 'Minute' => 0 } })
150
+ end
151
+
152
+ describe 'with hostile values in the bundle path, GEM_HOME and the project path' do
153
+ let(:item) do
154
+ schedule(dir: File.join(tmp, "p#{hostile}<", "string> #{hostile}"), bundle: "/opt/#{hostile}/bundle", gem_env: { 'GEM_HOME' => "/g/#{hostile}" })
155
+ end
156
+ let(:text) { launchd.plist(item) }
157
+
158
+ it 'round-trips them exactly' do
159
+ data = parsed(text)
160
+
161
+ expect([data['ProgramArguments'], data['WorkingDirectory'], data['StandardOutPath']]).to eq([item.argv, item.working_directory, item.log_path])
162
+ expect([data['ProgramArguments'][1], data['EnvironmentVariables']['GEM_HOME']]).to eq(["/opt/#{hostile}/bundle", "/g/#{hostile}"])
163
+ expect(item.working_directory).to include('</string>', "'; rm -rf ~; '", '$(id)', '%h', '"', '\\', '&')
164
+ end
165
+
166
+ it 'writes them only in escaped form' do
167
+ expect(text).not_to include('</string> ', "'; rm", '" \\')
168
+ expect(text.scan(/&(?!amp;|lt;|gt;|quot;|apos;)/)).to be_empty
169
+ expect(text).to include('&lt;/string&gt;', '&apos;; rm -rf ~; &apos;', '&quot; \\ &amp;', '$(id)', '%h')
170
+ end
171
+ end
172
+ end
173
+
174
+ describe '#install' do
175
+ it 'writes the plist 0644, lints it, then boots out and bootstraps it' do
176
+ item = schedule
177
+ path = plist_path(item)
178
+ linted = nil
179
+ runner.on_call { |argv| linted = File.read(argv[2]) if argv[1] == '-lint' }
180
+
181
+ launchd.install(item)
182
+
183
+ expect(runner.calls).to match([
184
+ ['/usr/bin/plutil', '-lint', %r{\A#{Regexp.escape(agents)}/\..+\.tmp\z}],
185
+ ['/bin/launchctl', 'bootout', "gui/501/#{item.os_id}"],
186
+ ['/bin/launchctl', 'bootstrap', 'gui/501', path]
187
+ ])
188
+ expect([File.read(path), linted, format('%o', File.stat(path).mode & 0o777)]).to eq([launchd.plist(item), launchd.plist(item), '644'])
189
+ expect(Dir.children(agents)).to eq([File.basename(path)])
190
+ end
191
+
192
+ it 'replaces an existing entry and ignores a bootout that finds nothing' do
193
+ item = schedule
194
+ FileUtils.mkdir_p(agents)
195
+ File.write(plist_path(item), 'old')
196
+ runner.answers['bootout'] = ['Boot-out failed: 3: No such process', 3]
197
+
198
+ launchd.install(item)
199
+
200
+ expect(runner.calls.map { |argv| argv[1] }).to eq(%w[-lint bootout bootstrap])
201
+ expect(File.read(plist_path(item))).to eq(launchd.plist(item))
202
+ end
203
+
204
+ it 'removes the plist and raises with the scheduler error when bootstrap fails' do
205
+ item = schedule
206
+ runner.answers['bootstrap'] = ["Bootstrap failed: 5: Input/output error\e[2J\n", 5]
207
+
208
+ expect { launchd.install(item) }.to raise_error(RubyRaider::Schedules::Error, %r{launchd.*Bootstrap failed: 5: Input/output error\?\[2J})
209
+ expect(Dir.children(agents)).to be_empty
210
+ end
211
+
212
+ it 'says so when the plist a failed bootstrap left can not be deleted' do
213
+ item = schedule
214
+ runner.answers['bootstrap'] = ['Bootstrap failed: 5', 5]
215
+ allow(File).to receive(:unlink).and_call_original
216
+ allow(File).to receive(:unlink).with(plist_path(item)).and_raise(Errno::EACCES)
217
+
218
+ expect { launchd.install(item) }.to raise_error(RubyRaider::Schedules::Error, /Bootstrap failed: 5; also: Could not remove .*Permission denied/)
219
+ end
220
+
221
+ it 'raises a schedule error and runs nothing when it can not write the plist' do
222
+ FileUtils.mkdir_p(File.dirname(agents))
223
+ File.write(agents, 'not a folder')
224
+
225
+ expect { launchd.install(schedule) }.to raise_error(RubyRaider::Schedules::Error, /Could not write .*LaunchAgents/)
226
+ expect([runner.calls, File.read(agents)]).to eq([[], 'not a folder'])
227
+ end
228
+
229
+ it 'leaves the entry alone and raises when the plist does not lint' do
230
+ item = schedule
231
+ FileUtils.mkdir_p(agents)
232
+ File.write(plist_path(item), 'old')
233
+ runner.answers['-lint'] = ['bad plist', 1]
234
+
235
+ expect { launchd.install(item) }.to raise_error(RubyRaider::Schedules::Error, /bad plist/)
236
+ expect([runner.calls.map { |argv| argv[1] }, Dir.children(agents), File.read(plist_path(item))])
237
+ .to eq([['-lint'], [File.basename(plist_path(item))], 'old'])
238
+ end
239
+ end
240
+
241
+ describe '#remove' do
242
+ it 'deletes the plist, then boots out' do
243
+ item = schedule
244
+ FileUtils.mkdir_p(agents)
245
+ File.write(plist_path(item), 'x')
246
+ seen = []
247
+ runner.on_call { |argv| seen << [argv[1], File.exist?(plist_path(item))] }
248
+
249
+ expect(launchd.remove(item.os_id)).to be(true)
250
+ expect([runner.calls, seen]).to eq([[['/bin/launchctl', 'bootout', "gui/501/#{item.os_id}"]], [['bootout', false]]])
251
+ end
252
+
253
+ it 'is true when only the plist was there' do
254
+ item = schedule
255
+ FileUtils.mkdir_p(agents)
256
+ File.write(plist_path(item), 'x')
257
+ runner.answers['bootout'] = ['Boot-out failed: 3: No such process', 3]
258
+
259
+ expect([launchd.remove(item.os_id), File.exist?(plist_path(item))]).to eq([true, false])
260
+ end
261
+
262
+ it 'is true when only the service was loaded' do
263
+ expect(launchd.remove(schedule.os_id)).to be(true)
264
+ end
265
+
266
+ it 'is false when it was already gone' do
267
+ runner.answers['bootout'] = ['Boot-out failed: 3: No such process', 3]
268
+
269
+ expect(launchd.remove(schedule.os_id)).to be(false)
270
+ end
271
+
272
+ it 'raises when the plist can not be deleted' do
273
+ item = schedule
274
+ allow(File).to receive(:unlink).and_raise(Errno::EACCES)
275
+
276
+ expect { launchd.remove(item.os_id) }.to raise_error(RubyRaider::Schedules::Error, /Could not remove .*Permission denied/)
277
+ expect(runner.calls).to be_empty
278
+ end
279
+
280
+ it 'refuses an os_id that is not a schedule id' do
281
+ expect { launchd.remove('../../evil') }.to raise_error(RubyRaider::Schedules::Error, /Invalid os_id/)
282
+ expect(runner.calls).to be_empty
283
+ end
284
+ end
285
+
286
+ describe '#present?' do
287
+ it 'asks launchctl print' do
288
+ item = schedule
289
+
290
+ expect(launchd.present?(item.os_id)).to be(true)
291
+ expect(runner.calls).to eq([['/bin/launchctl', 'print', "gui/501/#{item.os_id}"]])
292
+ end
293
+
294
+ it 'refuses an os_id that is not a schedule id and runs nothing' do
295
+ expect { launchd.present?('../../evil') }.to raise_error(RubyRaider::Schedules::Error, /Invalid os_id/)
296
+ expect(runner.calls).to be_empty
297
+ end
298
+
299
+ it 'is false when launchctl print fails' do
300
+ runner.answers['print'] = ['Could not find service', 113]
301
+
302
+ expect(launchd.present?(schedule.os_id)).to be(false)
303
+ end
304
+ end
305
+ end
306
+ # rubocop:enable RSpec/MultipleMemoizedHelpers
@@ -0,0 +1,163 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'tmpdir'
4
+ require_relative '../../../../lib/utilities/schedules/os/linux'
5
+ require_relative '../../../../lib/utilities/schedules/schedule'
6
+
7
+ # rubocop:disable RSpec/MultipleMemoizedHelpers
8
+ RSpec.describe RubyRaider::Schedules::Os::Linux do # rubocop:disable RSpec/FilePath
9
+ # Plays systemctl --user and crontab: answers keyed by "systemctl verb" or "crontab -l"; never runs anything
10
+ let(:fake_runner_class) do
11
+ Class.new do
12
+ attr_reader :calls, :answers
13
+ attr_accessor :table
14
+
15
+ def initialize
16
+ @calls = []
17
+ @answers = {}
18
+ @table = nil
19
+ end
20
+
21
+ def call(*argv, stdin_data: nil)
22
+ @calls << argv
23
+ key = argv.first == 'crontab' ? "crontab #{argv[1]}" : "systemctl #{argv[2]}"
24
+ missing = key == 'crontab -l' && table.nil?
25
+ stderr, status = answers.fetch(key) { missing ? ['no crontab for raider', 1] : ['', 0] }
26
+ self.table = stdin_data if key == 'crontab -' && status.zero?
27
+ RubyRaider::Schedules::Os::CommandRunner::Result.new(stdout: key == 'crontab -l' ? table.to_s : '', stderr: stderr, exitstatus: status)
28
+ end
29
+ end
30
+ end
31
+
32
+ let(:tmp) { File.realpath(Dir.mktmpdir('schedules-linux')) }
33
+ let(:runner) { fake_runner_class.new }
34
+ let(:item) do
35
+ # Hermetic: the GEM_HOME/GEM_PATH and bundle this spec runs with never reach the entry
36
+ allow(RubyRaider::Schedules::Schedule).to receive_messages(captured_gem_env: {}, bundle_path: '/opt/ruby/bin/bundle')
37
+ project = RubyRaider::Schedules::Project.new(tmp)
38
+ RubyRaider::Schedules::Schedule.build(project: project, name: 'report', every: 'day', at: '08:00', now: Time.utc(2026, 11, 9))
39
+ end
40
+ let(:cron_block) { "# raider-schedule #{item.os_id}\n#{RubyRaider::Schedules::Os::Cron.new(kind: RubyRaider::Schedules::Kind::TESTS).line(item)}\n" }
41
+ let(:no_bus) { ['Failed to connect to bus', 1] }
42
+
43
+ # The systemd units go to a temp home, never the real one
44
+ def pick = described_class.new(kind: RubyRaider::Schedules::Kind::TESTS, runner: runner, systemd: RubyRaider::Schedules::Os::Systemd.new(kind: RubyRaider::Schedules::Kind::TESTS, runner: runner, home: tmp, config_home: nil))
45
+
46
+ after { FileUtils.rm_rf(tmp) }
47
+
48
+ it 'uses systemd when the user manager answers' do
49
+ linux = pick
50
+
51
+ expect([linux.label, linux.missed_runs_note, described_class.pick(runner, kind: RubyRaider::Schedules::Kind::TESTS).label]).to eq(['systemd', nil, 'systemd'])
52
+ expect(runner.calls.uniq).to eq([%w[systemctl --user show-environment]])
53
+ end
54
+
55
+ it 'falls back to cron when it does not, or systemctl is missing' do
56
+ [no_bus, ['Could not run systemctl', RubyRaider::Schedules::Os::CommandRunner::MISSING]].each do |answer|
57
+ runner.answers['systemctl show-environment'] = answer
58
+
59
+ expect([pick.label, pick.missed_runs_note]).to eq(['cron', '(cron: missed runs are skipped)'])
60
+ end
61
+ end
62
+
63
+ it 'installs with the primary scheduler only' do
64
+ runner.answers['systemctl show-environment'] = no_bus
65
+
66
+ pick.install(item)
67
+
68
+ expect([runner.table, runner.calls.map(&:first).uniq]).to eq([cron_block, %w[systemctl crontab]])
69
+ end
70
+
71
+ describe '#remove' do
72
+ it 'also removes a cron entry when systemd is the primary' do
73
+ runner.table = "#{cron_block}1 * * * * a\n"
74
+
75
+ expect(pick.remove(item.os_id)).to be(true)
76
+ expect(runner.table).to eq("1 * * * * a\n")
77
+ end
78
+
79
+ it 'is false when neither has it' do
80
+ expect(pick.remove(item.os_id)).to be(false)
81
+ end
82
+
83
+ it 'skips cron when crontab -l does not work' do
84
+ runner.answers['crontab -l'] = ['crontab: not found', 127]
85
+
86
+ expect(pick.remove(item.os_id)).to be(false)
87
+ expect(runner.calls).not_to include(%w[crontab -])
88
+ end
89
+
90
+ it 'never asks systemd when cron is the primary, since systemd did not answer' do
91
+ runner.answers['systemctl show-environment'] = no_bus
92
+ runner.table = cron_block
93
+
94
+ expect(pick.remove(item.os_id)).to be(true)
95
+ expect(runner.calls.select { |argv| argv.first == 'systemctl' }).to eq([%w[systemctl --user show-environment]])
96
+ end
97
+ end
98
+
99
+ describe 'with a systemd timer, from a session where systemd does not answer' do
100
+ let(:units) { File.join(tmp, '.config', 'systemd', 'user') }
101
+
102
+ before do
103
+ runner.answers['systemctl show-environment'] = no_bus
104
+ FileUtils.mkdir_p(units)
105
+ File.write(File.join(units, "#{item.os_id}.timer"), 'x')
106
+ end
107
+
108
+ it 'is present' do
109
+ expect(pick.present?(item.os_id)).to be(true)
110
+ end
111
+
112
+ it 'removes the cron block, then raises so the schedule is kept, and leaves the unit' do
113
+ runner.table = "#{cron_block}1 * * * * a\n"
114
+
115
+ expect { pick.remove(item.os_id) }
116
+ .to raise_error(RubyRaider::Schedules::Error, 'This schedule is a systemd timer; run raider schedule remove report ' \
117
+ 'from a session where systemctl --user works')
118
+ expect([runner.table, File.exist?(File.join(units, "#{item.os_id}.timer"))]).to eq(["1 * * * * a\n", true])
119
+ end
120
+
121
+ it 'names raider schedule list, with no name, for a 4.1 timer' do
122
+ legacy = RubyRaider::Schedules::Kind::FLOW_LEGACY
123
+ os_id = "#{legacy.os_id_prefix}.0123456789.report"
124
+ File.write(File.join(units, "#{os_id}.timer"), 'x')
125
+ linux = described_class.new(kind: legacy, runner: runner,
126
+ systemd: RubyRaider::Schedules::Os::Systemd.new(kind: legacy, runner: runner, home: tmp, config_home: nil))
127
+
128
+ expect { linux.remove(os_id) }
129
+ .to raise_error(RubyRaider::Schedules::Error, 'This schedule is a systemd timer; run raider schedule list ' \
130
+ 'from a session where systemctl --user works')
131
+ end
132
+ end
133
+
134
+ it 'does not look for systemd unit files when systemd is the primary' do
135
+ FileUtils.mkdir_p(File.join(tmp, '.config', 'systemd', 'user'))
136
+ File.write(File.join(tmp, '.config', 'systemd', 'user', "#{item.os_id}.timer"), 'x')
137
+
138
+ expect(pick.remove(item.os_id)).to be(true)
139
+ end
140
+
141
+ describe '#present?' do
142
+ it 'is true when only the other scheduler has it' do
143
+ runner.answers['systemctl is-enabled'] = ['disabled', 1]
144
+ runner.table = cron_block
145
+
146
+ expect(pick.present?(item.os_id)).to be(true)
147
+ end
148
+
149
+ it 'is false when neither has it' do
150
+ runner.answers['systemctl is-enabled'] = ['disabled', 1]
151
+
152
+ expect(pick.present?(item.os_id)).to be(false)
153
+ end
154
+
155
+ it 'counts a failing other scheduler as not there' do
156
+ runner.answers['systemctl is-enabled'] = ['disabled', 1]
157
+ runner.answers['crontab -l'] = ['crontab: permission denied', 1]
158
+
159
+ expect(pick.present?(item.os_id)).to be(false)
160
+ end
161
+ end
162
+ end
163
+ # rubocop:enable RSpec/MultipleMemoizedHelpers
@@ -0,0 +1,202 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'tmpdir'
4
+ require_relative '../../../../lib/utilities/schedules/adapter'
5
+ require_relative '../../../../lib/utilities/schedules/schedule'
6
+
7
+ # Every adapter's list_ids(prefix): the os_ids of one project's schedules of the adapter's Kind, found by
8
+ # enumerating the OS scheduler. Only a fake runner and a temp home: nothing real is read or run.
9
+ # rubocop:disable RSpec/MultipleMemoizedHelpers
10
+ RSpec.describe 'Schedules adapters #list_ids' do
11
+ # Answers each command from a table keyed by its first words; 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, stdin_data]
23
+ key = if argv.first.to_s.end_with?('schtasks.exe') then argv[1]
24
+ elsif argv.first == 'systemctl' then argv.first(3).join(' ')
25
+ else argv.first(2).join(' ')
26
+ end
27
+ stdout, status, stderr = answers.fetch(key, ['', 0, ''])
28
+ RubyRaider::Schedules::Os::CommandRunner::Result.new(stdout: stdout, stderr: stderr.to_s, exitstatus: status)
29
+ end
30
+ end
31
+ end
32
+
33
+ let(:kind) { RubyRaider::Schedules::Kind::TESTS }
34
+ let(:tmp) { File.realpath(Dir.mktmpdir('schedules-list-ids')) }
35
+ let(:home) { File.join(tmp, 'home') }
36
+ let(:runner) { fake_runner_class.new }
37
+ let(:root) { File.join(tmp, 'project') }
38
+ let(:prefix) { RubyRaider::Schedules::Schedule.os_id_prefix_for(root) }
39
+ let(:other_prefix) { RubyRaider::Schedules::Schedule.os_id_prefix_for(File.join(tmp, 'other')) }
40
+ let(:flow_prefix) { "#{RubyRaider::Schedules::Kind::FLOW_LEGACY.os_id_prefix}.#{prefix.split('.')[3]}." }
41
+ let(:bad_utf8) { "#{prefix}a\xFF".dup.force_encoding(Encoding::UTF_8) }
42
+ # What enumeration may see besides our two ids: another project, a flow schedule, a bad name, a longer
43
+ # name, path tricks and bytes that are not UTF-8
44
+ let(:noise) do
45
+ ["#{other_prefix}nightly", "#{flow_prefix}nightly", "#{prefix}Bad", "#{prefix}#{'a' * 61}", "#{prefix}a.b", "#{prefix}..",
46
+ "#{prefix}a b", prefix, "x#{prefix}nightly", bad_utf8]
47
+ end
48
+
49
+ let(:extra_children) { Hash.new { |hash, key| hash[key] = [] } }
50
+
51
+ after { FileUtils.rm_rf(tmp) }
52
+
53
+ # APFS refuses a file name that is not UTF-8, so those names are fed through Dir.children instead
54
+ def touch(dir, *names)
55
+ FileUtils.mkdir_p(dir)
56
+ names.each { |name| name.valid_encoding? ? File.write(File.join(dir, name), '') : extra_children[dir] << name }
57
+ end
58
+
59
+ before do
60
+ allow(Dir).to(receive(:children).and_wrap_original { |original, dir| original.call(dir) + extra_children[dir] })
61
+ end
62
+
63
+ it 'builds the prefix from the kind and the project path hash, ending in a dot' do
64
+ expect(prefix).to match(/\Adev\.rubyraider\.schedule\.[0-9a-f]{10}\.\z/)
65
+ expect(RubyRaider::Schedules::Schedule.os_id_for(root, 'nightly')).to eq("#{prefix}nightly")
66
+ end
67
+
68
+ describe RubyRaider::Schedules::Os::Launchd do
69
+ let(:adapter) { described_class.new(kind: kind, runner: runner, home: home, uid: 501) }
70
+ let(:agents) { File.join(home, 'Library', 'LaunchAgents') }
71
+
72
+ it 'lists the plist basenames of this project and kind, sorted, and runs nothing' do
73
+ touch(agents, "#{prefix}smoke.plist", "#{prefix}nightly.plist", "#{prefix}nightly.txt", ".#{prefix}x.plist.ab12.tmp",
74
+ *noise.map { |id| "#{id}.plist" })
75
+
76
+ expect(adapter.list_ids(prefix)).to eq(["#{prefix}nightly", "#{prefix}smoke"])
77
+ expect([runner.calls, extra_children[agents]]).to eq([[], ["#{bad_utf8}.plist"]])
78
+ end
79
+
80
+ it 'is empty when there is no LaunchAgents folder' do
81
+ expect(adapter.list_ids(prefix)).to eq([])
82
+ end
83
+
84
+ it 'raises an Error when the folder can not be read' do
85
+ FileUtils.mkdir_p(File.join(home, 'Library'))
86
+ File.write(agents, '')
87
+
88
+ expect { adapter.list_ids(prefix) }.to raise_error(RubyRaider::Schedules::Error, /Could not read .*LaunchAgents/)
89
+ end
90
+ end
91
+
92
+ describe RubyRaider::Schedules::Os::TaskScheduler do
93
+ let(:adapter) { described_class.new(kind: kind, runner: runner, schtasks: 'C:\\Windows\\System32\\schtasks.exe') }
94
+
95
+ def rows(*names) = names.map { |name| %("#{name}","11/10/2026 8:00:00 AM","Ready"\r\n) }.join
96
+
97
+ it 'lists the tasks under \\RubyRaider\\ of this project and kind from one query' do
98
+ listing = rows("\\RubyRaider\\#{prefix}smoke", "\\RubyRaider\\#{prefix}nightly", "\\Other\\#{prefix}elsewhere",
99
+ "\\RubyRaider\\sub\\#{prefix}deeper", "\\#{prefix}rootlevel", "\\RubyRaider\\#{prefix}smoke",
100
+ *noise.map { |id| "\\RubyRaider\\#{id}" })
101
+ listing = "#{listing}garbage line\r\n\"unterminated\r\n"
102
+ runner.answers['/Query'] = [listing.b, 0]
103
+
104
+ expect(adapter.list_ids(prefix)).to eq(["#{prefix}nightly", "#{prefix}smoke"])
105
+ expect(runner.calls.map(&:first)).to eq([['C:\\Windows\\System32\\schtasks.exe', '/Query', '/FO', 'CSV', '/NH']])
106
+ end
107
+
108
+ it 'raises an Error when the task list can not be read' do
109
+ runner.answers['/Query'] = ['', 1, "ERROR: \e[2Jdenied"]
110
+
111
+ expect { adapter.list_ids(prefix) }.to raise_error(RubyRaider::Schedules::Error, 'Task Scheduler could not list tasks: ERROR: ?[2Jdenied')
112
+ end
113
+ end
114
+
115
+ describe RubyRaider::Schedules::Os::Systemd do
116
+ let(:adapter) { described_class.new(kind: kind, runner: runner, home: home, config_home: nil) }
117
+ let(:units) { File.join(home, '.config', 'systemd', 'user') }
118
+
119
+ it 'lists the unit file names of this project and kind, without asking systemctl' do
120
+ touch(units, "#{prefix}smoke.timer", "#{prefix}smoke.service", "#{prefix}nightly.service", "#{prefix}other.socket",
121
+ ".#{prefix}x.timer.ab12.tmp", *noise.map { |id| "#{id}.timer" })
122
+
123
+ expect(adapter.list_ids(prefix)).to eq(["#{prefix}nightly", "#{prefix}smoke"])
124
+ expect(runner.calls).to be_empty
125
+ end
126
+
127
+ it 'reads the units folder under XDG_CONFIG_HOME when that is absolute' do
128
+ config = File.join(tmp, 'xdg')
129
+ touch(File.join(config, 'systemd', 'user'), "#{prefix}smoke.timer")
130
+
131
+ expect(described_class.new(kind: kind, runner: runner, home: home, config_home: config).list_ids(prefix)).to eq(["#{prefix}smoke"])
132
+ end
133
+
134
+ it 'is empty when there is no units folder' do
135
+ expect(adapter.list_ids(prefix)).to eq([])
136
+ end
137
+ end
138
+
139
+ describe RubyRaider::Schedules::Os::Cron do
140
+ let(:adapter) { described_class.new(kind: kind, runner: runner) }
141
+
142
+ it 'lists the ids on our tag lines only, keeping the crontab as it is' do
143
+ table = "MAILTO=x\n# raider-schedule #{prefix}smoke\n0 8 * * * cd /p && run\n# raider-schedule #{prefix}nightly\r\n" \
144
+ "# raider-schedule #{prefix}spaced\n# raider-schedule #{prefix}trailing \n" \
145
+ "0 1 * * * echo '# raider-schedule #{prefix}inline'\n" \
146
+ "#{noise.map { |id| "# raider-schedule #{id}\n" }.join}# raider-flow #{flow_prefix}legacy\n"
147
+ runner.answers['crontab -l'] = [table.b, 0]
148
+
149
+ expect(adapter.list_ids(prefix)).to eq(["#{prefix}nightly", "#{prefix}smoke"])
150
+ expect(runner.calls.map(&:first)).to eq([%w[crontab -l]])
151
+ end
152
+
153
+ it 'is empty with no crontab, and raises an Error when crontab -l fails otherwise' do
154
+ runner.answers['crontab -l'] = ['', 1, 'no crontab for raider']
155
+ expect(adapter.list_ids(prefix)).to eq([])
156
+
157
+ runner.answers['crontab -l'] = ['', 1, 'permission denied']
158
+ expect { adapter.list_ids(prefix) }.to raise_error(RubyRaider::Schedules::Error, /could not read the crontab/)
159
+ end
160
+
161
+ it 'raises an Error, not an encoding error, when crontab -l fails with bytes that are not UTF-8' do
162
+ runner.answers['crontab -l'] = ['', 1, "refus\xE9\e[2J".dup.force_encoding(Encoding::UTF_8)]
163
+
164
+ expect { adapter.list_ids(prefix) }.to raise_error(RubyRaider::Schedules::Error, 'cron could not read the crontab: refus??[2J')
165
+ end
166
+ end
167
+
168
+ describe RubyRaider::Schedules::Os::Linux do
169
+ let(:systemd) { RubyRaider::Schedules::Os::Systemd.new(kind: kind, runner: runner, home: home, config_home: nil) }
170
+ let(:cron) { RubyRaider::Schedules::Os::Cron.new(kind: kind, runner: runner) }
171
+ let(:units) { File.join(home, '.config', 'systemd', 'user') }
172
+
173
+ before do
174
+ touch(units, "#{prefix}timer_one.timer")
175
+ runner.answers['crontab -l'] = ["# raider-schedule #{prefix}cron_one\n", 0]
176
+ end
177
+
178
+ it 'with systemd answering: the unit files plus the cron tags' do
179
+ adapter = described_class.new(kind: kind, runner: runner, systemd: systemd, cron: cron)
180
+
181
+ expect(adapter.list_ids(prefix)).to eq(["#{prefix}cron_one", "#{prefix}timer_one"])
182
+ end
183
+
184
+ it 'with no user bus: the cron tags plus the stranded unit files' do
185
+ runner.answers['systemctl --user show-environment'] = ['', 1, 'Failed to connect to bus']
186
+ adapter = described_class.new(kind: kind, runner: runner, systemd: systemd, cron: cron)
187
+
188
+ expect(adapter.list_ids(prefix)).to eq(["#{prefix}cron_one", "#{prefix}timer_one"])
189
+ end
190
+
191
+ it 'leaves out the other scheduler when it fails, and raises when the primary one does' do
192
+ runner.answers['crontab -l'] = ['', 1, 'permission denied']
193
+ with_systemd = described_class.new(kind: kind, runner: runner, systemd: systemd, cron: cron)
194
+ expect(with_systemd.list_ids(prefix)).to eq(["#{prefix}timer_one"])
195
+
196
+ runner.answers['systemctl --user show-environment'] = ['', 1, 'Failed to connect to bus']
197
+ with_cron = described_class.new(kind: kind, runner: runner, systemd: systemd, cron: cron)
198
+ expect { with_cron.list_ids(prefix) }.to raise_error(RubyRaider::Schedules::Error, /could not read the crontab/)
199
+ end
200
+ end
201
+ end
202
+ # rubocop:enable RSpec/MultipleMemoizedHelpers