pwn 0.5.803 → 0.5.805

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 (40) hide show
  1. checksums.yaml +4 -4
  2. data/Gemfile +4 -4
  3. data/documentation/Skills-Memory-Learning.md +7 -0
  4. data/lib/pwn/ai/agent/dispatch.rb +54 -1
  5. data/lib/pwn/ai/agent/loop.rb +3 -3
  6. data/lib/pwn/ai/agent/mission_namespace.rb +26 -4
  7. data/lib/pwn/ai/agent/request_runtime.rb +7 -0
  8. data/lib/pwn/ai/agent/tools/memory.rb +6 -11
  9. data/lib/pwn/ai/ollama.rb +10 -2
  10. data/lib/pwn/ai/open_web_ui.rb +7 -32
  11. data/lib/pwn/ai.rb +44 -0
  12. data/lib/pwn/memory.rb +9 -4
  13. data/lib/pwn/plugins/repl/ai_console.rb +152 -17
  14. data/lib/pwn/version.rb +1 -1
  15. data/spec/conventions_spec.rb +9 -7
  16. data/spec/integration/harness_evaluation_spec.rb +16 -24
  17. data/spec/lib/pwn/ai/agent/dispatch_spec.rb +80 -0
  18. data/spec/lib/pwn/ai/agent/mission_namespace_spec.rb +2 -1
  19. data/spec/lib/pwn/ai/agent/policy_spec.rb +3 -2
  20. data/spec/lib/pwn/ai/agent/result_spec.rb +6 -1
  21. data/spec/lib/pwn/ai/agent/tools/memory_spec.rb +7 -0
  22. data/spec/lib/pwn/ai/ollama_spec.rb +27 -0
  23. data/spec/lib/pwn/ai/open_web_ui_spec.rb +5 -5
  24. data/spec/lib/pwn/ai/provider_review_history_stream_regression_spec.rb +32 -0
  25. data/spec/lib/pwn/banner_spec.rb +67 -38
  26. data/spec/lib/pwn/cron_spec.rb +2 -39
  27. data/spec/lib/pwn/memory_spec.rb +46 -0
  28. data/spec/lib/pwn/plugins/android_review_fixes_spec.rb +14 -6
  29. data/spec/lib/pwn/plugins/android_transport_audit_spec.rb +2 -1
  30. data/spec/lib/pwn/plugins/artifact_registry_spec.rb +7 -3
  31. data/spec/lib/pwn/plugins/jobs_spec.rb +10 -1
  32. data/spec/lib/pwn/plugins/repl/ai_console_spec.rb +335 -15
  33. data/spec/lib/pwn/sdr/decoder/lora_spec.rb +36 -27
  34. data/spec/lib/pwn/setup_spec.rb +4 -19
  35. data/spec/spec_helper.rb +8 -4
  36. data/spec/support/harness/cli_faults.rb +2 -1
  37. data/spec/support/mission_pipe_queue.rb +12 -1
  38. data/spec/support/sandbox.rb +27 -0
  39. data/third_party/pwn_rdoc.jsonl +15 -1
  40. metadata +9 -9
@@ -349,18 +349,18 @@ describe PWN::AI::OpenWebUI, 'binary stream display recovery' do
349
349
  let(:previews) { [] }
350
350
 
351
351
  around do |example|
352
- previous = Thread.current[:pwn_openwebui_preview]
353
- Thread.current[:pwn_openwebui_preview] = ->(text, pending) { previews << [text, pending] }
352
+ previous = Thread.current[:pwn_stream_preview]
353
+ Thread.current[:pwn_stream_preview] = ->(*args) { previews << args }
354
354
  example.run
355
355
  ensure
356
- Thread.current[:pwn_openwebui_preview] = previous
356
+ Thread.current[:pwn_stream_preview] = previous
357
357
  end
358
358
 
359
359
  it 'recovers only visible assistant text, without returning a provider response' do
360
360
  event = JSON.generate(message: { role: 'assistant', thinking: 'private', content: 'Café' }, done: true)
361
361
  wire = "\uFEFF#{event}".b.freeze
362
362
  expect { described_class.send(:assemble_openwebui_stream, body: wire, rest_call: 'ollama/api/chat') }.to raise_error(RuntimeError, /display.only/i)
363
- expect(previews).to eq([['Café', false]])
363
+ expect(previews).to eq([['Open WebUI', 'Café', false]])
364
364
  expect(wire.encoding).to eq(Encoding::BINARY)
365
365
  end
366
366
 
@@ -369,7 +369,7 @@ describe PWN::AI::OpenWebUI, 'binary stream display recovery' do
369
369
  event = JSON.generate(choices: [{ delta: delta, finish_reason: 'function_call' }])
370
370
  wire = "data: #{event}\r\n\r\ndata: [DONE]\r\n\r\n".b
371
371
  expect { described_class.send(:assemble_openwebui_stream, body: wire, rest_call: 'api/v1/chat/completions') }.to raise_error(RuntimeError, /display.only/i)
372
- expect(previews).to eq([['Résumé', true]])
372
+ expect(previews).to eq([['Open WebUI', 'Résumé', true]])
373
373
  end
374
374
 
375
375
  it 'does not preview invalid bytes or an incomplete reply' do
@@ -100,6 +100,38 @@ end
100
100
  end
101
101
  end
102
102
 
103
+ RSpec.describe provider, 'display-only SSE completeness' do
104
+ let(:assemble) { key == :ollama ? :assemble_ollama_stream : :assemble_openwebui_stream }
105
+ let(:previews) { [] }
106
+ let(:partial) { "data: #{JSON.generate(choices: [{ index: 0, delta: { content: 'Café' } }])}\n\n" }
107
+
108
+ around do |example|
109
+ previous = Thread.current[:pwn_stream_preview]
110
+ Thread.current[:pwn_stream_preview] = ->(*args) { previews << args }
111
+ example.run
112
+ ensure
113
+ Thread.current[:pwn_stream_preview] = previous
114
+ end
115
+
116
+ it 'does not use another choice to finish the displayed text' do
117
+ other = "data: #{JSON.generate(choices: [{ index: 1, delta: {}, finish_reason: 'stop' }])}\n\n"
118
+ expect { described_class.send(assemble, body: (partial + other).b, rest_call: 'v1/chat/completions') }.to raise_error(RuntimeError, /incomplete/i)
119
+ expect(previews).to be_empty
120
+ end
121
+
122
+ it 'honors an error event even when its data is the normal end marker' do
123
+ wire = "#{partial}event: error\ndata: [DONE]\n\n".b
124
+ expect { described_class.send(assemble, body: wire, rest_call: 'v1/chat/completions') }.to raise_error(RuntimeError, /stream error/i)
125
+ expect(previews).to be_empty
126
+ end
127
+
128
+ it 'accepts the displayed choice finishing without a global end marker' do
129
+ finish = "data: #{JSON.generate(choices: [{ index: 0, delta: {}, finish_reason: 'stop' }])}\n\n"
130
+ expect { described_class.send(assemble, body: (partial + finish).b, rest_call: 'v1/chat/completions') }.to raise_error(RuntimeError, /display-only/)
131
+ expect(previews.map { |_, text, pending| [text, pending] }).to eq([['Café', false]])
132
+ end
133
+ end
134
+
103
135
  RSpec.describe provider, 'PR-LOG-01 strict-template history' do
104
136
  include_context 'provider review synthetic stream transport', key
105
137
 
@@ -543,8 +543,13 @@ describe PWN::Banner do
543
543
 
544
544
  it 'keeps every active tetromino color beside the stack throughout its fall and lock' do
545
545
  rotations = Hash.new { |hash, key| hash[key] = [] }
546
- [5, 8, 16, 20].product([1, 73, 74], [true, false]).each do |size, seed, branding|
546
+ # Finish on default seeded, branded boards; the following examples can read them through the real cache.
547
+ [1, 74, 73].product([false, true], [5, 8, 16, 20]).each do |seed, branding, size|
547
548
  args = { name: :falling_blocks, width: size, height: size, seed: seed, branding: branding }
549
+ decoded = {}
550
+ stack_colors = Hash.new do |cache, row|
551
+ cache[row] = row.chars.map { |pixel| pixel == ' ' ? :black : described_class::MINI_PIXELS.fetch(pixel)[1] }.freeze
552
+ end
548
553
  frames = described_class.send(:mini_replay, **args, height: size + (branding ? 0 : 1))
549
554
  frames.each_with_index do |frame, index|
550
555
  next unless frame[:state][:active]
@@ -553,9 +558,10 @@ describe PWN::Banner do
553
558
  type = frame[:state][:type]
554
559
  cells = described_class.mini_cells(**args, frame: index)
555
560
  color = %i[cyan yellow magenta blue red green green][type]
556
- expected = frame[:state][:stack].map { |row| row.chars.map { |pixel| pixel == ' ' ? :black : described_class::MINI_PIXELS.fetch(pixel)[1] } }
561
+ expected = frame[:state][:stack].map { |row| stack_colors[row].dup }
557
562
  points.each { |x, y| expected[y][x] = color }
558
- expect(block_colors(frame[:rows].drop(1))).to eq(expected)
563
+ actual_rows = frame[:rows].drop(1).flat_map { |row| decoded[row] ||= block_colors([row]) }
564
+ expect(actual_rows).to eq(expected)
559
565
  points.each do |x, y|
560
566
  expect(x).to be_between(0, size - 1)
561
567
  expect(y).to be_between(0, ((size - (branding ? 1 : 0)) * 2) - 1)
@@ -617,20 +623,27 @@ describe PWN::Banner do
617
623
  it 'packs blocks into two quadrants and snake segments into one without losing ink' do
618
624
  %i[falling_blocks snake].product((5..16).to_a).each do |name, size|
619
625
  frames = described_class.send(:mini_replay, name: name, width: size, height: size, seed: 73)
620
- frames.each do |frame|
621
- pixels = frame[:rows].drop(1).join.chars.reject { |pixel| pixel == ' ' }
622
- expect(pixels).to all(satisfy { |pixel| pixel.ord >= 256 })
623
- area = pixels.sum { |pixel| ((pixel.ord - 256) % 16).digits(2).sum }
626
+ # A packed row's ink depends only on its contents, not its place in the replay.
627
+ row_ink = {}
628
+ widths = [size] * size
629
+ label = 'PWN'.center(size)
630
+ frames.each_with_index do |frame, index|
631
+ area = frame[:rows].drop(1).sum do |row|
632
+ row_ink[row] ||= begin
633
+ pixels = row.delete(' ').codepoints
634
+ expect(pixels.find { |code| code < 256 }).to be_nil, -> { "Unpacked pixel in #{name} size #{size} frame #{index}: #{row.inspect}" }
635
+ pixels.sum { |code| ((code - 256) % 16).digits(2).sum }
636
+ end
637
+ end
624
638
  state = frame[:state]
625
639
  expected = if state[:body]
626
640
  state[:body].length + (state[:food] ? 1 : 0)
627
641
  elsif state[:active]
628
642
  (state[:stack].sum { |row| row.count('^ ') } + 4) * 2
629
643
  end
630
- expect(area).to eq(expected) if expected
631
- expect(frame[:rows].length).to eq(size)
632
- expect(frame[:rows].map(&:length)).to all(eq(size))
633
- expect(frame[:rows].first).to eq('PWN'.center(size))
644
+ expect(area).to eq(expected), -> { "#{name} size #{size} frame #{index}: expected #{expected} ink, got #{area}" } if expected
645
+ expect(frame[:rows].map(&:length)).to eq(widths)
646
+ expect(frame[:rows].first).to eq(label)
634
647
  end
635
648
  end
636
649
  end
@@ -739,7 +752,8 @@ describe PWN::Banner do
739
752
  end
740
753
 
741
754
  it 'spawns rocks clear of the ship instead of starting with overlapping sprites' do
742
- [5, 8, 16].product([1, 73, 74]).each do |size, seed|
755
+ # Walk back through the same cases so the real bounded cache can serve recent replays.
756
+ [5, 8, 16].product([1, 73, 74]).reverse_each do |size, seed|
743
757
  frames = described_class.send(:mini_replay, name: :asteroids, width: size, height: size, seed: seed)
744
758
  state = frames.find { |frame| frame[:state][:ship] }[:state]
745
759
  state[:rocks].each do |rock|
@@ -834,23 +848,28 @@ describe PWN::Banner do
834
848
  end
835
849
 
836
850
  it 'keeps every frame bounded, single-column, named-color, deterministic and side-effect free' do
851
+ colors = %i[black red green yellow blue magenta cyan white]
852
+ glyphs = /\A[ PWN█▀▄▌▐░▒·●▘▝▖▗▞▛▚▜▙▟ᗧᗤᗢᗣ│•✹═≈▰▱\u2800-\u28ff]\z/
853
+ # Exercise cache initialization and replay construction under the guards, even when run last.
854
+ described_class.instance_variable_set(:@mini_replays, nil)
837
855
  expect(Random).not_to receive(:rand)
838
856
  expect(Time).not_to receive(:now)
839
857
  expect(Process).not_to receive(:clock_gettime)
840
858
  expect(Thread).not_to receive(:new)
841
859
  expect(described_class).not_to receive(:sleep)
842
860
  expect do
843
- described_class.mini_names.each do |name|
861
+ described_class.mini_names.reverse_each do |name|
844
862
  (5..16).each do |size|
845
863
  args = { name: name, width: size, height: size }
846
864
  frames = Array.new(60) { |frame| described_class.mini_cells(**args, frame: frame) }
847
865
  expect(frames.uniq.length).to be >= 4
848
866
  expect(frames.map(&:length)).to all(eq(size))
849
867
  expect(frames.flatten(1).map(&:length)).to all(eq(size))
850
- frames.flatten(2).each do |cell|
851
- expect(cell.keys).to contain_exactly(:glyph, :foreground, :background)
852
- expect(cell[:glyph]).to match(/\A[ PWN█▀▄▌▐░▒·●▘▝▖▗▞▛▚▜▙▟ᗧᗤᗢᗣ│•✹═≈▰▱\u2800-\u28ff]\z/)
853
- expect(%i[black red green yellow blue magenta cyan white]).to include(cell[:foreground], cell[:background])
868
+ frames.each_with_index do |board, frame|
869
+ board.each_with_index do |row, y|
870
+ x = row.index { |cell| !valid_mini_cell?(cell, glyphs, colors) }
871
+ raise "Invalid #{name} cell (size #{size}, frame #{frame}, x #{x}, y #{y}): #{row[x].inspect}" if x
872
+ end
854
873
  end
855
874
  expect(described_class.mini_cells(**args, frame: described_class::MINI_FRAME_COUNT)).to eq(frames.first)
856
875
  expect(described_class.mini_cells(**args, frame: -1)).to eq(described_class.mini_cells(**args, frame: described_class::MINI_FRAME_COUNT - 1))
@@ -866,22 +885,29 @@ describe PWN::Banner do
866
885
  expect { described_class.mini_cells(name: :unknown) }.to raise_error(ArgumentError, /Unknown mini-banner/)
867
886
  end
868
887
 
888
+ def valid_mini_cell?(cell, glyphs, colors)
889
+ cell.is_a?(Hash) && cell.size == 3 && cell.key?(:glyph) && cell.key?(:foreground) && cell.key?(:background) &&
890
+ cell[:glyph].is_a?(String) && glyphs.match?(cell[:glyph]) && colors.include?(cell[:foreground]) && colors.include?(cell[:background])
891
+ end
892
+
869
893
  def replay(name, size, seed = 73)
870
894
  described_class.send(:mini_replay, name: name, width: size, height: size, seed: seed)
871
895
  end
872
896
 
873
- def logical_ink(frame, full: false)
897
+ def logical_ink(frame, row_cache, full: false)
874
898
  width = frame[:rows].first.length
875
899
  height = frame[:rows].length - 1
876
900
  height *= 2 if full
901
+ halves = row_cache[[width, full]] ||= [{}, {}]
877
902
  Array.new(height) do |y|
878
- Array.new(width) do |x|
903
+ py = y + (full ? 0 : height / 2)
904
+ row = frame[:rows][1 + (py / 2)]
905
+ halves[py % 2][row] ||= Array.new(width) do |x|
879
906
  px = full ? x * 2 : x + (width / 2)
880
- py = y + (full ? 0 : height / 2)
881
- pixel = frame[:rows][1 + (py / 2)][px / 2]
907
+ pixel = row[px / 2]
882
908
  mask = pixel == ' ' ? 0 : (pixel.ord - 256) % 16
883
909
  mask[(py % 2 * 2) + (px % 2)] == 1 ? '*' : ' '
884
- end.join
910
+ end.join.freeze
885
911
  end
886
912
  end
887
913
 
@@ -900,22 +926,23 @@ describe PWN::Banner do
900
926
  end
901
927
 
902
928
  it 'stacks all seven four-cell tetrominoes with legal gravity, rotations and line collapse' do
903
- (5..16).each do |size|
929
+ # Start with the larger, more expensive boards which may still be in the production cache.
930
+ (5..16).reverse_each do |size|
904
931
  frames = replay(:falling_blocks, size)
932
+ row_cache = {}
905
933
  active = frames.select { |frame| frame[:state][:active] }
906
934
  expect(active.map { |frame| frame[:state][:type] }.uniq.length).to eq(7)
907
935
  expect(frames.map { |frame| frame[:event] }).to include(:lock, :clear, :collapse)
908
936
  active.each do |frame|
909
937
  points, stack = frame[:state].values_at(:active, :stack)
910
938
  expect(points.uniq.length).to eq(4)
911
- points.each do |x, y|
912
- expect(x).to be_between(0, size - 1)
913
- expect(y).to be_between(0, ((size - 1) * 2) - 1)
914
- expect(stack[y][x]).to eq(' ')
939
+ blocked = points.find do |x, y|
940
+ !x.between?(0, size - 1) || !y.between?(0, ((size - 1) * 2) - 1) || stack[y][x] != ' '
915
941
  end
942
+ expect(blocked).to be_nil, -> { "Active piece outside the board or overlapping the stack: #{blocked.inspect} at size #{size}" }
916
943
  expected = stack.map { |row| row.gsub(/[^ ]/, '*') }
917
944
  points.each { |x, y| expected[y][x] = '*' }
918
- expect(logical_ink(frame, full: true)).to eq(expected)
945
+ expect(logical_ink(frame, row_cache, full: true)).to eq(expected)
919
946
  end
920
947
  frames.each_cons(2) do |before, after|
921
948
  a = before[:state][:active]
@@ -930,9 +957,10 @@ describe PWN::Banner do
930
957
  expect(after[:rows]).to eq(before[:rows])
931
958
  elsif before[:event] == :clear && after[:event] == :collapse
932
959
  lines = before[:state][:lines]
933
- expect(lines.map { |y| logical_ink(before, full: true)[y] }).to all(eq('*' * size))
934
- survivors = logical_ink(before, full: true).each_with_index.filter_map { |row, y| row unless lines.include?(y) }
935
- expect(logical_ink(after, full: true)).to eq(Array.new(lines.length, ' ' * size) + survivors)
960
+ ink = logical_ink(before, row_cache, full: true)
961
+ expect(lines.map { |y| ink[y] }).to all(eq('*' * size))
962
+ survivors = ink.each_with_index.filter_map { |row, y| row unless lines.include?(y) }
963
+ expect(logical_ink(after, row_cache, full: true)).to eq(Array.new(lines.length, ' ' * size) + survivors)
936
964
  end
937
965
  end
938
966
  end
@@ -941,16 +969,16 @@ describe PWN::Banner do
941
969
  it 'moves a contiguous non-overlapping snake toward real food and grows only on pickup' do
942
970
  (5..16).each do |size|
943
971
  frames = replay(:snake, size)
972
+ row_cache = {}
944
973
  states = frames.filter_map { |frame| frame[:state] if frame[:state][:body] }
945
974
  expect(states.map { |state| state[:body].length }.max).to be > 6
946
975
  states.each do |state|
947
976
  body, food = state.values_at(:body, :food)
948
977
  expect(body.uniq.length).to eq(body.length)
949
- body.each do |x, y|
950
- expect(x).to be_between(0, size - 1)
951
- expect(y).to be_between(0, size - 2)
952
- end
953
- body.each_cons(2) { |a, b| expect(a.zip(b).sum { |x, y| (x - y).abs }).to eq(1) }
978
+ outside = body.find { |x, y| !x.between?(0, size - 1) || !y.between?(0, size - 2) }
979
+ expect(outside).to be_nil, -> { "Snake outside #{size}x#{size - 1} board: #{outside.inspect}" }
980
+ gap = body.each_cons(2).find { |a, b| a.zip(b).sum { |x, y| (x - y).abs } != 1 }
981
+ expect(gap).to be_nil, -> { "Disconnected snake segments at size #{size}: #{gap.inspect}" }
954
982
  expect(body).not_to include(food) if food
955
983
  end
956
984
  frames.each do |frame|
@@ -959,7 +987,7 @@ describe PWN::Banner do
959
987
 
960
988
  expected = Array.new(size - 1) { ' ' * size }
961
989
  (body + [food].compact).each { |x, y| expected[y][x] = '*' }
962
- expect(logical_ink(frame)).to eq(expected)
990
+ expect(logical_ink(frame, row_cache)).to eq(expected)
963
991
  end
964
992
  frames.each_cons(2) do |before, after|
965
993
  a = before[:state]
@@ -1059,11 +1087,12 @@ describe PWN::Banner do
1059
1087
  described_class.mini_names.each do |name|
1060
1088
  (5..16).each do |size|
1061
1089
  args = { name: name, width: size, height: size }
1062
- frames = Array.new(described_class::MINI_FRAME_COUNT) { |frame| described_class.mini_frame(**args, frame: frame) }
1090
+ frames = Array.new(described_class::MINI_ASCII_FRAME_COUNT) { |frame| described_class.mini_frame(**args, frame: frame) }
1063
1091
  expect(frames.uniq.length).to be >= 4
1064
1092
  expect(frames.flatten).to all(match(/\A[ -~]{#{size}}\z/))
1065
1093
  expect(frames.map(&:length)).to all(eq(size))
1066
1094
  expect(frames.map(&:first)).to all(include('PWN'))
1095
+ expect(described_class.mini_frame(**args, frame: 60)).to eq(frames.first)
1067
1096
  expect(described_class.mini_frame(**args, frame: described_class::MINI_FRAME_COUNT)).to eq(frames.first)
1068
1097
  expect(described_class.mini_frame(**args, name: name.to_s, frame: -1)).to eq(frames.last)
1069
1098
  expect(described_class.mini_frame(**args, frame: 3)).to eq(frames[3])
@@ -16,24 +16,7 @@ describe PWN::Cron do
16
16
  expect(help_response).to respond_to :help
17
17
  end
18
18
 
19
- describe 'in-process scheduler' do
20
- before do
21
- @tmp = Dir.mktmpdir('pwn-cron-spec-')
22
- stub_const('PWN::Cron::CRON_DIR', @tmp)
23
- stub_const('PWN::Cron::JOBS_FILE', File.join(@tmp, 'jobs.yml'))
24
- stub_const('PWN::Cron::PID_FILE', File.join(@tmp, 'worker.pid'))
25
- stub_const('PWN::Cron::WORKER_LOG', File.join(@tmp, 'worker.log'))
26
- end
27
-
28
- after do
29
- begin
30
- PWN::Cron.stop_worker
31
- rescue StandardError
32
- nil
33
- end
34
- FileUtils.remove_entry(@tmp) if @tmp && Dir.exist?(@tmp)
35
- end
36
-
19
+ describe 'in-process scheduler', :isolated_cron_store do
37
20
  it 'removes only a schedule without native effects when explicitly requested' do
38
21
  target = described_class.create(name: 'curriculum_practice_nightly', enabled: false, sync_native: false)
39
22
  other = described_class.create(name: 'custom', enabled: false, sync_native: false)
@@ -160,7 +143,6 @@ describe PWN::Cron do
160
143
  schedule: 'every 1s',
161
144
  ruby: "File.write(#{marker.inspect}, Time.now.utc.iso8601)"
162
145
  )
163
- ENV['PWN_CRON_DIR'] = @tmp
164
146
  begin
165
147
  res = PWN::Cron.start_worker(interval: 1, restart: true)
166
148
  expect(res[:started]).to be(true), "worker did not start: #{res.inspect} log=#{begin
@@ -180,7 +162,6 @@ describe PWN::Cron do
180
162
  expect(last).not_to be_nil
181
163
  expect(File).to exist(marker)
182
164
  ensure
183
- ENV.delete('PWN_CRON_DIR')
184
165
  PWN::Cron.stop_worker
185
166
  expect(PWN::Cron.worker_status[:running]).to be false
186
167
  end
@@ -200,25 +181,7 @@ describe PWN::Cron do
200
181
  end
201
182
 
202
183
  describe PWN::Cron do
203
- describe 'OS-agnostic scheduler' do
204
- before do
205
- # install_defaults owns siblings of cron_dir (maintenance/cache/tmp).
206
- # Give it a complete private root, never the shared Dir.tmpdir parent.
207
- @root = Dir.mktmpdir('pwn-cron-os-spec-')
208
- @tmp = File.join(@root, 'cron')
209
- FileUtils.mkdir_p(@tmp)
210
- stub_const('PWN::Cron::CRON_DIR', @tmp)
211
- stub_const('PWN::Cron::JOBS_FILE', File.join(@tmp, 'jobs.yml'))
212
- stub_const('PWN::Cron::PID_FILE', File.join(@tmp, 'worker.pid'))
213
- stub_const('PWN::Cron::WORKER_LOG', File.join(@tmp, 'worker.log'))
214
- ENV['PWN_CRON_DIR'] = @tmp
215
- end
216
-
217
- after do
218
- ENV.delete('PWN_CRON_DIR')
219
- FileUtils.remove_entry(@root) if @root && Dir.exist?(@root)
220
- end
221
-
184
+ describe 'OS-agnostic scheduler', :isolated_cron_store do
222
185
  it 'keeps default housekeeping off every native installer' do
223
186
  allow(described_class).to receive(:scheduler_backend).and_return(:systemd_user)
224
187
  expect(described_class).not_to receive(:systemd_user)
@@ -5,6 +5,52 @@ require 'tmpdir'
5
5
  require 'fileutils'
6
6
 
7
7
  RSpec.describe PWN::Memory do
8
+ describe 'atomic publication' do
9
+ include_context 'pwn tmp sandbox'
10
+
11
+ let(:path) { described_class::MEMORY_FILE }
12
+
13
+ it 'commits the reviewed entry without consuming an existing temporary file' do
14
+ old_tmp = File.join(@tmp, ".memory.json.#{Process.pid}.tmp")
15
+ File.write(old_tmp, 'unrelated contents')
16
+ File.write(path, '{"before":{"value":"original"}}')
17
+
18
+ described_class.remember(key: :reviewed, value: 'approved')
19
+
20
+ expect(described_class.load.transform_values { |entry| entry[:value] }).to eq(before: 'original', reviewed: 'approved')
21
+ expect(File).to exist(old_tmp)
22
+ expect(File.read(old_tmp)).to eq('unrelated contents')
23
+ expect(Dir.children(@tmp)).to contain_exactly('memory.json', 'memory.json.write.lock', File.basename(old_tmp))
24
+ end
25
+
26
+ it 'leaves an occupied candidate and the current store untouched if exclusive creation fails' do
27
+ allow(SecureRandom).to receive(:hex).and_return('reserved')
28
+ candidate = File.join(@tmp, '.memory.json.reserved.tmp')
29
+ File.write(candidate, 'reserved contents')
30
+ original = '{"before":{"value":"original"}}'
31
+ File.write(path, original)
32
+
33
+ expect { described_class.remember(key: :reviewed, value: 'approved') }.to raise_error(Errno::EEXIST)
34
+ expect(File.read(candidate)).to eq('reserved contents')
35
+ expect(File.read(path)).to eq(original)
36
+ end
37
+
38
+ it 'discards the private temporary file and leaves the original intact when rename fails' do
39
+ original = '{"before":{"value":"original"}}'
40
+ File.write(path, original)
41
+ allow(File).to receive(:rename).with(anything, path) do |tmp, _path|
42
+ expect(File.dirname(tmp)).to eq(File.dirname(path))
43
+ expect(File.stat(tmp).mode & 0o077).to eq(0)
44
+ expect(JSON.parse(File.read(tmp)).dig('reviewed', 'value')).to eq('approved')
45
+ raise Errno::EIO
46
+ end
47
+
48
+ expect { described_class.remember(key: :reviewed, value: 'approved') }.to raise_error(Errno::EIO)
49
+ expect(File.read(path)).to eq(original)
50
+ expect(Dir.children(@tmp)).to contain_exactly('memory.json', 'memory.json.write.lock')
51
+ end
52
+ end
53
+
8
54
  describe 'store transactions' do
9
55
  include_context 'pwn tmp sandbox'
10
56
 
@@ -7,13 +7,22 @@ require 'rbconfig'
7
7
  require 'timeout'
8
8
 
9
9
  RSpec.describe PWN::Plugins::Android do
10
+ def write_fixture_adb(script)
11
+ # These standalone children need no test bundle; leave the runner's RUBYOPT alone.
12
+ File.write(@adb, "#!#{RbConfig.ruby} --disable=gems,rubyopt\n#{script}")
13
+ File.chmod(0o700, @adb)
14
+ end
15
+
10
16
  around do |example|
11
17
  Dir.mktmpdir('android-review-') do |root|
12
18
  @root = root
13
19
  @adb = File.join(root, 'adb literal ; executable')
14
20
  @calls = File.join(root, 'calls.jsonl')
15
- File.write(@adb, "#!#{RbConfig.ruby}\nrequire 'json'\nFile.open(#{@calls.inspect}, 'a') { |f| f.puts(JSON.generate(ARGV)) }\nputs 'synthetic'\n")
16
- File.chmod(0o700, @adb)
21
+ write_fixture_adb(<<~RUBY)
22
+ require 'json'
23
+ File.open(#{@calls.inspect}, 'a') { |f| f.puts(JSON.generate(ARGV)) }
24
+ puts 'synthetic'
25
+ RUBY
17
26
  example.run
18
27
  end
19
28
  end
@@ -21,8 +30,7 @@ RSpec.describe PWN::Plugins::Android do
21
30
  it 'cancels and reaps only its owned process group, including TERM-resistant descendants' do
22
31
  pidfile = File.join(@root, 'pids')
23
32
  release = File.join(@root, 'release')
24
- File.write(@adb, <<~RUBY)
25
- #!#{RbConfig.ruby}
33
+ write_fixture_adb(<<~RUBY)
26
34
  child = fork do
27
35
  trap('TERM') {}
28
36
  File.write(#{"#{pidfile}.ready".inspect}, '')
@@ -76,7 +84,7 @@ RSpec.describe PWN::Plugins::Android do
76
84
  end
77
85
 
78
86
  it 'bounds an owned child that closes stdout but never exits, without exposing its output' do
79
- File.write(@adb, "#!#{RbConfig.ruby}\nSTDOUT.close\nsleep 20\n")
87
+ write_fixture_adb("STDOUT.close\nsleep 20\n")
80
88
  stub_const('PWN::Plugins::Android::COMMAND_TIMEOUT', 1)
81
89
  owned = nil
82
90
  allow(Process).to receive(:spawn).and_wrap_original do |original, *args, **kwargs|
@@ -89,7 +97,7 @@ RSpec.describe PWN::Plugins::Android do
89
97
  end
90
98
 
91
99
  it 'bounds capture output and suppresses private child stderr on failure' do
92
- File.write(@adb, "#!#{RbConfig.ruby}\nSTDERR.puts 'synthetic-private'\nprint 'x' * 2048\n")
100
+ write_fixture_adb("STDERR.puts 'synthetic-private'\nprint 'x' * 2048\n")
93
101
  stub_const('PWN::Plugins::Android::MAX_OUTPUT_BYTES', 1024)
94
102
  spawn_options = nil
95
103
  allow(Process).to receive(:spawn).and_wrap_original do |original, *args, **kwargs|
@@ -14,8 +14,9 @@ RSpec.describe PWN::Plugins::Android do
14
14
  @exit = File.join(root, 'exit')
15
15
  File.write(@output, '')
16
16
  File.write(@exit, '0')
17
+ # Run this argv recorder without loading the parent test bundle in every child.
17
18
  File.write(@adb, <<~RUBY)
18
- #!#{RbConfig.ruby}
19
+ #!#{RbConfig.ruby} --disable=gems,rubyopt
19
20
  require 'json'
20
21
  File.open(#{@calls.inspect}, 'a') { |f| f.puts(JSON.generate(ARGV)) }
21
22
  print File.binread(#{@output.inspect})
@@ -38,13 +38,17 @@ describe PWN::Plugins::ArtifactRegistry do
38
38
  stored = described_class.spill(bytes: bytes, session_id: 'large')
39
39
  expected = Digest::SHA256.hexdigest(bytes)
40
40
  digest = Digest::SHA256.new
41
+ metadata = [stored[:handle], bytes.bytesize, 'base64', 'base64']
41
42
  offset = 0
42
43
  pages = 0
43
44
  loop do
44
45
  page = described_class.read_page(handle: stored[:handle], offset: offset, length: 1_000_000)
45
- expect(page[:bytes]).to be <= 2048
46
- expect(page).to include(handle: stored[:handle], total_bytes: bytes.bytesize, encoding: 'base64', mode: 'base64')
46
+ raise "Invalid page metadata at byte #{offset}" unless page.values_at(:handle, :total_bytes, :encoding, :mode) == metadata
47
+
47
48
  decoded = Base64.strict_decode64(page[:body])
49
+ valid_size = (1..2048).cover?(page[:bytes]) && decoded.bytesize == page[:bytes]
50
+ raise "Invalid page bounds at byte #{offset}" unless valid_size && page[:next_offset] == offset + page[:bytes]
51
+
48
52
  digest.update(decoded)
49
53
  offset = page[:next_offset]
50
54
  pages += 1
@@ -52,7 +56,7 @@ describe PWN::Plugins::ArtifactRegistry do
52
56
  end
53
57
  expect(offset).to eq(bytes.bytesize)
54
58
  expect(digest.hexdigest).to eq(expected)
55
- puts "artifact paging verified: bytes=#{offset} pages=#{pages} sha256=#{digest.hexdigest}"
59
+ expect(pages).to be >= (bytes.bytesize / 2048)
56
60
  end
57
61
 
58
62
  it 'preserves split UTF-8 bytes, explicit encodings, refs and EOF metadata' do
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require 'spec_helper'
4
+ require 'shellwords'
4
5
 
5
6
  describe PWN::Plugins::Jobs do
6
7
  before do
@@ -65,7 +66,9 @@ describe PWN::Plugins::Jobs do
65
66
  end
66
67
 
67
68
  it 'pages binary logs with byte offsets and distinguishes EOF from completion' do
68
- row = described_class.start(command: "printf 'abc\\377def'; sleep 1", max_runtime: 5)
69
+ release = File.join(@root, 'release')
70
+ writer = 'STDOUT.binmode; STDOUT.write("abc\\xffdef".b); STDOUT.flush; sleep 0.01 until File.exist?(ARGV.fetch(0))'
71
+ row = described_class.start(command: Shellwords.join([RbConfig.ruby, '--disable=gems,rubyopt', '-e', writer, release]), max_runtime: 5)
69
72
  first = Timeout.timeout(8) do
70
73
  loop do
71
74
  page = described_class.job_tail(handle: row[:id], offset: 0, length: 4)
@@ -80,9 +83,15 @@ describe PWN::Plugins::Jobs do
80
83
  expect(Base64.strict_decode64(first[:data])).to eq("abc\xFF".b)
81
84
  last = described_class.tail(id: row[:id], offset: 4, length: 100)
82
85
  expect(last).to include(body: 'def', data: 'def', bytes: 3, next_offset: 7, eof: true, status: 'RUNNING')
86
+ File.write(release, '')
83
87
  finished(row[:id])
84
88
  expect(described_class.tail(id: row[:id], offset: 7)).to include(bytes: 0, eof: true, status: 'COMPLETED')
85
89
  expect(described_class.tail(id: row[:id])).to be_a(String)
90
+ ensure
91
+ if row && !File.exist?(release)
92
+ File.write(release, '')
93
+ finished(row[:id])
94
+ end
86
95
  end
87
96
 
88
97
  it 'filters and limits durable jobs across sessions' do