pwn 0.5.804 → 0.5.806

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 (114) hide show
  1. checksums.yaml +4 -4
  2. data/Gemfile +8 -8
  3. data/documentation/AI-Integration.md +27 -1
  4. data/documentation/Contributing.md +1 -1
  5. data/documentation/Diagrams.md +1 -1
  6. data/documentation/General-PWN-Usage.md +1 -1
  7. data/documentation/Home.md +2 -2
  8. data/documentation/How-PWN-Works.md +1 -1
  9. data/documentation/Mission-Cancellation.md +4 -3
  10. data/documentation/Persistence.md +1 -1
  11. data/documentation/Plugins.md +3 -2
  12. data/documentation/Runtime-Source-Protection.md +20 -2
  13. data/documentation/Skills-Memory-Learning.md +15 -1
  14. data/documentation/What-is-PWN.md +1 -1
  15. data/documentation/diagrams/dot/plugin-ecosystem.dot +1 -1
  16. data/documentation/diagrams/plugin-ecosystem.svg +1 -1
  17. data/etc/default_skills/pwn/ai/agent/submission/SKILL.md +23 -0
  18. data/etc/default_skills/pwn/ai/sandbox/SKILL.md +59 -0
  19. data/lib/pwn/ai/agent/confirmation.rb +1 -1
  20. data/lib/pwn/ai/agent/dispatch.rb +55 -2
  21. data/lib/pwn/ai/agent/learning.rb +7 -3
  22. data/lib/pwn/ai/agent/loop.rb +388 -251
  23. data/lib/pwn/ai/agent/mission_namespace.rb +52 -14
  24. data/lib/pwn/ai/agent/open_goal.rb +36 -9
  25. data/lib/pwn/ai/agent/policy.rb +37 -10
  26. data/lib/pwn/ai/agent/prompt_builder.rb +15 -8
  27. data/lib/pwn/ai/agent/request_runtime.rb +106 -13
  28. data/lib/pwn/ai/agent/submission.rb +367 -0
  29. data/lib/pwn/ai/agent/swarm.rb +2 -2
  30. data/lib/pwn/ai/agent/task_dag.rb +1 -1
  31. data/lib/pwn/ai/agent/task_summarizer.rb +47 -13
  32. data/lib/pwn/ai/agent/tools/memory.rb +6 -11
  33. data/lib/pwn/ai/agent/tools/ruby_eval.rb +1 -1
  34. data/lib/pwn/ai/agent/tools/shell.rb +1 -1
  35. data/lib/pwn/ai/agent/tools/skills.rb +5 -5
  36. data/lib/pwn/ai/agent/turn_finalizer.rb +659 -27
  37. data/lib/pwn/ai/agent.rb +1 -0
  38. data/lib/pwn/ai/cli.rb +2 -0
  39. data/lib/pwn/ai/grok.rb +106 -1
  40. data/lib/pwn/{plugins/ai_sandbox.rb → ai/sandbox.rb} +116 -32
  41. data/lib/pwn/ai.rb +1 -0
  42. data/lib/pwn/config.rb +36 -32
  43. data/lib/pwn/memory.rb +9 -4
  44. data/lib/pwn/plugins/log.rb +15 -1
  45. data/lib/pwn/plugins/repl/ai.rb +3 -7
  46. data/lib/pwn/plugins/repl/ai_console.rb +234 -41
  47. data/lib/pwn/plugins/repl/ai_swarm.rb +1 -1
  48. data/lib/pwn/plugins.rb +0 -1
  49. data/lib/pwn/sessions.rb +9 -1
  50. data/lib/pwn/version.rb +1 -1
  51. data/pwn_upgrade-aarch64.txt +9533 -0
  52. data/spec/conventions_spec.rb +9 -7
  53. data/spec/integration/controller_spill_spec.rb +8 -2
  54. data/spec/integration/harness_evaluation_spec.rb +16 -24
  55. data/spec/integration/harness_package_spec.rb +17 -6
  56. data/spec/integration/mission_cancel_spec.rb +2 -2
  57. data/spec/integration/reinforced_feedback_loop_spec.rb +1 -1
  58. data/spec/landlock_capability_spec.rb +23 -0
  59. data/spec/lib/pwn/ai/agent/chat_deliverable_spec.rb +188 -0
  60. data/spec/lib/pwn/ai/agent/dispatch_spec.rb +82 -2
  61. data/spec/lib/pwn/ai/agent/loop_artifacts_spec.rb +102 -1
  62. data/spec/lib/pwn/ai/agent/loop_partial_delivery_spec.rb +62 -0
  63. data/spec/lib/pwn/ai/agent/loop_permission_spec.rb +152 -0
  64. data/spec/lib/pwn/ai/agent/loop_spec.rb +100 -23
  65. data/spec/lib/pwn/ai/agent/loop_submission_spec.rb +271 -0
  66. data/spec/lib/pwn/ai/agent/mission_namespace_spec.rb +78 -4
  67. data/spec/lib/pwn/ai/agent/policy_spec.rb +3 -2
  68. data/spec/lib/pwn/ai/agent/provider_window_timing_spec.rb +63 -0
  69. data/spec/lib/pwn/ai/agent/request_runtime_spec.rb +142 -1
  70. data/spec/lib/pwn/ai/agent/result_spec.rb +6 -1
  71. data/spec/lib/pwn/ai/agent/reward_dispatch_review_spec.rb +1 -1
  72. data/spec/lib/pwn/ai/agent/solve_spec.rb +1 -1
  73. data/spec/lib/pwn/ai/agent/submission_spec.rb +81 -0
  74. data/spec/lib/pwn/ai/agent/task_summarizer_spec.rb +29 -0
  75. data/spec/lib/pwn/ai/agent/tools/memory_spec.rb +7 -0
  76. data/spec/lib/pwn/ai/agent/tools/skills_spec.rb +23 -0
  77. data/spec/lib/pwn/ai/agent/turn_finalizer_spec.rb +384 -1
  78. data/spec/lib/pwn/ai/cli_spec.rb +17 -0
  79. data/spec/lib/pwn/ai/grok_spec.rb +153 -0
  80. data/spec/lib/pwn/ai/sandbox_boundary_review_spec.rb +231 -0
  81. data/spec/lib/pwn/{plugins/ai_sandbox_spec.rb → ai/sandbox_spec.rb} +29 -14
  82. data/spec/lib/pwn/ai_spec.rb +5 -0
  83. data/spec/lib/pwn/banner_spec.rb +67 -38
  84. data/spec/lib/pwn/config_skills_regression_spec.rb +78 -20
  85. data/spec/lib/pwn/memory_spec.rb +46 -0
  86. data/spec/lib/pwn/plugins/android_review_fixes_spec.rb +15 -8
  87. data/spec/lib/pwn/plugins/android_transport_audit_spec.rb +2 -1
  88. data/spec/lib/pwn/plugins/artifact_registry_spec.rb +7 -3
  89. data/spec/lib/pwn/plugins/jobs_spec.rb +10 -1
  90. data/spec/lib/pwn/plugins/log_spec.rb +95 -0
  91. data/spec/lib/pwn/plugins/plugins_b_operational_regression_spec.rb +1 -1
  92. data/spec/lib/pwn/plugins/repl/ai_console_spec.rb +551 -40
  93. data/spec/lib/pwn/plugins/repl/ai_legacy_containment_spec.rb +25 -10
  94. data/spec/lib/pwn/sdr/decoder/lora_spec.rb +36 -27
  95. data/spec/lib/pwn/sessions_lifecycle_supplement_spec.rb +50 -0
  96. data/spec/spec_helper.rb +8 -4
  97. data/spec/support/harness/cli_faults.rb +2 -1
  98. data/spec/support/harness/controller_spill.rb +2 -2
  99. data/spec/support/harness/controller_state.rb +3 -3
  100. data/spec/support/harness/evaluate.rb +21 -15
  101. data/spec/support/harness/mission_dispatch.rb +2 -2
  102. data/spec/support/harness/mission_job_lifetime.rb +2 -2
  103. data/spec/support/harness/mission_normal_exit.rb +1 -1
  104. data/spec/support/harness/mission_unsupported.rb +2 -2
  105. data/spec/support/harness/package_acceptance.rb +25 -4
  106. data/spec/support/harness/package_sandbox_rejection.rb +21 -0
  107. data/spec/support/harness/swarm_control.rb +5 -5
  108. data/spec/support/landlock.rb +23 -0
  109. data/spec/support/mission_pipe_queue.rb +12 -1
  110. data/spec/support/sandbox.rb +4 -0
  111. data/third_party/pwn_rdoc.jsonl +138 -48
  112. metadata +34 -22
  113. data/etc/default_skills/pwn/plugins/ai_sandbox/SKILL.md +0 -52
  114. data/spec/lib/pwn/plugins/ai_sandbox_boundary_review_spec.rb +0 -57
@@ -153,9 +153,10 @@ module PWNConventions
153
153
 
154
154
  def method_body_excerpt(lines, idx)
155
155
  indent = lines[idx][/^[ \t]*/]
156
+ terminator = /^#{Regexp.escape(indent)}end\b/
156
157
  buf = []
157
158
  ((idx + 1)...lines.length).each do |i|
158
- break if lines[i].match?(/^#{Regexp.escape(indent)}end\b/)
159
+ break if lines[i].match?(terminator)
159
160
 
160
161
  buf << lines[i]
161
162
  break if buf.length >= 120
@@ -235,9 +236,10 @@ module PWNConventions
235
236
  return '' unless idx
236
237
 
237
238
  indent = lines[idx][/^[ \t]*/]
239
+ terminator = /^#{Regexp.escape(indent)}end\b/
238
240
  buf = []
239
241
  ((idx + 1)...lines.length).each do |i|
240
- break if lines[i].match?(/^#{Regexp.escape(indent)}end\b/)
242
+ break if lines[i].match?(terminator)
241
243
 
242
244
  buf << lines[i]
243
245
  end
@@ -262,7 +264,8 @@ module PWNConventions
262
264
 
263
265
  def purpose_above?(help, name)
264
266
  lines = help.to_s.lines
265
- idx = lines.find_index { |l| l.match?(/\#\{self\}(?:::[A-Z]\w*)*\.#{Regexp.escape(name)}(?!\w)/) }
267
+ signature = /\#\{self\}(?:::[A-Z]\w*)*\.#{Regexp.escape(name)}(?!\w)/
268
+ idx = lines.find_index { |l| l.match?(signature) }
266
269
  return false unless idx
267
270
 
268
271
  prev = nil
@@ -357,15 +360,14 @@ describe 'PWN module conventions' do
357
360
  # ---------------------------------------------------------------- 6 --
358
361
  it '6) every public class method is documented in help with required/optional options (Google.help shape)' do
359
362
  misses = []
363
+ methods_by_file = c::ALL_METHODS.group_by { |m| m[:file] }
360
364
  c::MODULE_FILES.each do |path|
361
365
  next if c::NAMESPACE_INDEX_FILES.include?(c.rel(path))
362
366
 
363
367
  help = c.help_text(path)
364
368
  misses << "#{c.rel(path)} missing method authors in help" unless help.match?(/\.authors(?!\w)/)
365
- pubs = c::ALL_METHODS.select do |m|
366
- m[:file] == path &&
367
- m[:decorator] == 'public_class_method' &&
368
- !c::HELP_SKIP.include?(m[:name])
369
+ pubs = methods_by_file.fetch(path, []).select do |m|
370
+ m[:decorator] == 'public_class_method' && !c::HELP_SKIP.include?(m[:name])
369
371
  end
370
372
  pubs.each do |meth|
371
373
  name = meth[:name]
@@ -20,13 +20,19 @@ RSpec.describe 'controller spill boundary through actual Dispatch' do
20
20
  row = JSON.parse(stdout)
21
21
  expect(row['changed']).to be(false), row.inspect
22
22
  expect(row['dispatch_success']).to be(false)
23
- expect(row['dispatch_error']).to include('Permission denied')
23
+ if (reason = PwnSpecLandlock.unavailable_reason)
24
+ expect(JSON.parse(row.fetch('dispatch_error')).fetch('result')).to include(
25
+ 'execution_state' => 'not_started', 'error' => "repository protection: #{reason}"
26
+ )
27
+ else
28
+ expect(row['dispatch_error']).to include('Permission denied')
29
+ end
24
30
  end
25
31
  end
26
32
  end
27
33
 
28
34
  %w[ordinary aliased].each do |mode|
29
- it "denies the #{mode} controller-state inventory while preserving workspace output" do
35
+ it "denies the #{mode} controller-state inventory while preserving workspace output", :requires_landlock do
30
36
  Dir.mktmpdir('controller-inventory-') do |root|
31
37
  source = File.join(root, 'source')
32
38
  home = File.join(root, 'home')
@@ -4,7 +4,6 @@ require 'spec_helper'
4
4
  require 'tmpdir'
5
5
  require_relative '../support/harness/evaluate'
6
6
  require_relative '../support/harness/experiments'
7
- require_relative '../support/harness/cli_faults'
8
7
 
9
8
  RSpec.describe 'offline harness evaluation' do
10
9
  it 'refuses unknown or unequal comparison identities before launching anything' do
@@ -50,7 +49,7 @@ RSpec.describe 'offline harness evaluation' do
50
49
  end
51
50
  end
52
51
 
53
- it 'runs real CLI/Loop/tool effects and independently rejects a lying artifact claim' do
52
+ it 'runs real CLI/Loop/tool effects and independently rejects a lying artifact claim', :aggregate_failures, :requires_landlock do
54
53
  Dir.mktmpdir('pwn-harness-spec-', '/tmp') do |root|
55
54
  report = JSON.parse(JSON.generate(HarnessEvaluation.run(output: root)))
56
55
  results = report.fetch('results').to_h { |row| [row.fetch('task'), row] }
@@ -72,9 +71,8 @@ RSpec.describe 'offline harness evaluation' do
72
71
  expect(row).to include('outcome' => row.fetch('expected_outcome'), 'false_success' => false, 'repeated_effects' => 0)
73
72
  end
74
73
  expect(report.fetch('runtime_fault_process')).to include('exit_status' => 0, 'resource_cap' => false)
75
- expect(report.fetch('experiments')).to include('snapshot_unchanged' => true, 'input_manifests_unchanged' => true)
76
- expect(report.fetch('experiments').fetch('results')).to all(include('outcome' => 'PASS', 'inputs_unchanged' => true, 'false_success' => false, 'repeated_effects' => 0))
77
- expect(report.fetch('cli_faults').fetch('results')).to all(include('outcome' => 'PASS'))
74
+ expect_frozen_experiments(report.fetch('experiments'))
75
+ expect_cli_faults(report.fetch('cli_faults'))
78
76
  expect(report.fetch('runtime_faults').fetch('results').map { |row| row.fetch('outcome') }).to eq(%w[PASS PASS PASS PASS])
79
77
  expect(results.values).to all(include('tokens' => nil, 'cost' => nil))
80
78
  ensure
@@ -101,27 +99,21 @@ RSpec.describe 'offline harness evaluation' do
101
99
  end
102
100
  end
103
101
 
104
- it 'executes fault stimuli through the actual CLI, Loop, persisted runtime and shell' do
105
- Dir.mktmpdir('pwn-cli-faults-', '/tmp') do |root|
106
- report = JSON.parse(JSON.generate(HarnessCLIFaults.run(output: root)))
107
- expect(report.fetch('results').map { |row| row.fetch('id') }).to eq(%w[compaction-steering provider-retry cancel-during-provider checkpoint-restart resource-cap-restart])
108
- expect(report.fetch('results')).to all(include('outcome' => 'PASS', 'tokens' => nil, 'cost' => nil))
109
- expect(report.fetch('model_quality')).to eq('NOT_RUN')
110
- end
102
+ def expect_cli_faults(report)
103
+ rows = report.fetch('results')
104
+ expect(rows.map { |row| row.fetch('id') }).to eq(%w[compaction-steering provider-retry cancel-during-provider checkpoint-restart resource-cap-restart])
105
+ expect(rows).to all(include('outcome' => 'PASS', 'tokens' => nil, 'cost' => nil))
106
+ expect(report.fetch('model_quality')).to eq('NOT_RUN')
111
107
  end
112
108
 
113
- it 'runs independently frozen split tasks through real single, swarm and learning snapshot paths' do
114
- Dir.mktmpdir('pwn-heldout-', '/tmp') do |root|
115
- report = JSON.parse(JSON.generate(HarnessExperiments.run(output: root)))
116
- expect(report.fetch('model_quality')).to eq('NOT_RUN')
117
- expect(report.fetch('results').length).to eq(8)
118
- expect(report.fetch('results')).to all(include('outcome' => 'PASS', 'inputs_unchanged' => true, 'tokens' => nil, 'cost' => nil))
119
- expect(report.fetch('results').select { |row| row['arm'] == 'swarm-snapshot' }).to all(include('nested_provider_calls' => 3))
120
- expect(report.fetch('snapshot_unchanged')).to be(true)
121
- expect(report.fetch('results').select { |row| row['arm'] == 'single-policy' }.map { |row| row['policy_episodes'] }).to all(be > 0)
122
- ensure
123
- Dir.glob(File.join(root, '**', '*'), File::FNM_DOTMATCH).each { |path| File.chmod(0o700, path) if File.directory?(path) }
124
- end
109
+ def expect_frozen_experiments(report)
110
+ expect(report).to include('model_quality' => 'NOT_RUN', 'snapshot_unchanged' => true, 'input_manifests_unchanged' => true)
111
+ rows = report.fetch('results')
112
+ expect(rows.length).to eq(8)
113
+ expect(rows).to all(include('outcome' => 'PASS', 'inputs_unchanged' => true, 'false_success' => false, 'repeated_effects' => 0, 'tokens' => nil, 'cost' => nil))
114
+ arms = rows.group_by { |row| row.fetch('arm') }
115
+ expect(arms.fetch('swarm-snapshot')).to all(include('nested_provider_calls' => 3))
116
+ expect(arms.fetch('single-policy').map { |row| row.fetch('policy_episodes') }).to all(be > 0)
125
117
  end
126
118
 
127
119
  it 'requires explicit live approval before importing the reference agent or reading credentials' do
@@ -4,18 +4,29 @@ require 'spec_helper'
4
4
  require_relative '../support/harness/package_acceptance'
5
5
 
6
6
  RSpec.describe 'installed gem harness acceptance' do
7
- it 'runs the packaged executable with isolated HOME and GEM_HOME and rejects false success' do
7
+ it 'checks the isolated installation against the independently probed kernel capability' do
8
+ reason = PwnSpecLandlock.unavailable_reason
8
9
  Dir.mktmpdir('pwn-package-spec-', '/tmp') do |root|
9
- report = HarnessPackageAcceptance.run(output: root)
10
- expect(report.fetch(:package)).to include(installed_source_mismatches: [], source_changes_during_run: [])
10
+ report = HarnessPackageAcceptance.run(output: root, landlock_unavailable_reason: reason)
11
+ package = report.fetch(:package)
12
+ expect(package).to include(installed_source_mismatches: [], source_changes_during_run: [])
13
+ expect(report.fetch(:runtime_fault_process)).to include(exit_status: 0, resource_cap: false)
14
+ expect(report.fetch(:runtime_faults).fetch('results').map { |row| row.fetch('id') }).to eq(%w[compaction-preserves-goal-and-steering resource-cap-checkpoint-recovery retry-provider-fallback-before-effects cancel-blocked-provider])
15
+ expect(report.fetch(:runtime_faults).fetch('results')).to all(include('outcome' => 'PASS'))
16
+ if reason
17
+ expect(report.fetch(:behavioral_evaluation)).to eq(outcome: 'NOT_RUN', reason: reason)
18
+ rejection = report.fetch(:sandbox_rejection)
19
+ installed = package.fetch(:installed_root)
20
+ expect(rejection).to include(outcome: 'NOT_STARTED', activated_gem_root: installed, sandbox_source: File.join(installed, 'lib/pwn/ai/sandbox.rb'))
21
+ expect(File.exist?(File.join(rejection.fetch(:artifact_root), 'marker'))).to be(false)
22
+ next
23
+ end
24
+
11
25
  expect(report.fetch(:results).map { |row| row.fetch(:task) }).to contain_exactly('coding', 'exact-file', 'security-toy', 'structured', 'artifact-lie', 'timeout-replay')
12
26
  report.fetch(:results).each do |row|
13
27
  expect(row).to include(outcome: row.fetch(:expected_outcome), false_success: false, repeated_effects: 0)
14
28
  expect(row.fetch(:command)).to include(File.join(File.dirname(report.dig(:package, :installed_root)), '..', 'bin/pwn-ai').then { |path| File.expand_path(path) })
15
29
  end
16
- expect(report.fetch(:runtime_fault_process)).to include(exit_status: 0, resource_cap: false)
17
- expect(report.fetch(:runtime_faults).fetch('results').map { |row| row.fetch('id') }).to eq(%w[compaction-preserves-goal-and-steering resource-cap-checkpoint-recovery retry-provider-fallback-before-effects cancel-blocked-provider])
18
- expect(report.fetch(:runtime_faults).fetch('results')).to all(include('outcome' => 'PASS'))
19
30
  expect(report.fetch(:cli_faults).fetch(:results).map { |row| row.fetch(:id) }).to eq(%w[compaction-steering provider-retry cancel-during-provider checkpoint-restart resource-cap-restart])
20
31
  expect(report.fetch(:cli_faults).fetch(:results)).to all(include(outcome: 'PASS', repeated_effects: 0))
21
32
  expect(report.fetch(:swarm_acceptance).fetch(:results).map { |row| row.fetch(:id) }).to eq(%w[correct lie stale missing tampered])
@@ -57,7 +57,7 @@ RSpec.describe 'mission cancellation through real subprocesses' do
57
57
  expect(mission_fixture('mission_console', 'command')).to include('ready' => true, 'late' => false, 'second' => true, 'fenced' => true)
58
58
  end
59
59
 
60
- it 'keeps detached tool jobs alive until their enclosing mission exits' do
60
+ it 'keeps detached tool jobs alive until their enclosing mission exits', :requires_landlock do
61
61
  expect(mission_fixture('mission_job_lifetime')).to include('survived_tool' => true)
62
62
  end
63
63
 
@@ -73,7 +73,7 @@ RSpec.describe 'mission cancellation through real subprocesses' do
73
73
  expect(mission_fixture('mission_normal_exit')).to include('reaped' => true, 'late' => false, 'unrelated' => true)
74
74
  end
75
75
 
76
- it 'stops and reaps a setsid descendant before cancellation returns' do
76
+ it 'stops and reaps a setsid descendant before cancellation returns', :requires_landlock do
77
77
  expect(mission_fixture('mission_dispatch')).to include('cancelled' => true, 'descendant_started' => true, 'reaped' => true, 'post_cancel_write' => false)
78
78
  end
79
79
  end
@@ -1540,7 +1540,7 @@ RSpec.describe 'PWN::AI::Agent reinforced feedback loop', :aggregate_failures do
1540
1540
  expect(src).to match(/INCOMPLETE_FINAL_RX/)
1541
1541
  expect(src).to match(/MONOLOGUE_TOOL_INTENT_RX/)
1542
1542
  expect(src).to match(%r{\[pwn-ai/p28\]})
1543
- expect(src).to include('unless may_finalize?(', 'completion_unmet(request: request, messages: messages)')
1543
+ expect(src).to include('unless may_finalize?(', 'unmet = completion_unmet(request: request, messages: messages, input_pages: input_pages)')
1544
1544
  # last-iter wording no longer coaches "next single step" handoffs
1545
1545
  expect(src).not_to match(/next single step/)
1546
1546
  expect(src).to match(/Do NOT monologue/)
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'spec_helper'
4
+
5
+ RSpec.describe PwnSpecLandlock do
6
+ %w[aarch64-linux aarch64-linux-gnu aarch64_be-linux x86_64-linux].each do |platform|
7
+ it "runs protected-worker examples on #{platform} when the kernel supports ABI 3" do
8
+ stub_const('RUBY_PLATFORM', platform)
9
+ expect(Kernel).to receive(:syscall).with(444, 0, 0, 1).and_return(3)
10
+ expect(described_class.unavailable_reason).to be_nil
11
+ end
12
+ end
13
+
14
+ it 'distinguishes an older ABI and an absent syscall from unexpected probe failures' do
15
+ stub_const('RUBY_PLATFORM', 'aarch64-linux')
16
+ allow(Kernel).to receive(:syscall).with(444, 0, 0, 1).and_return(2)
17
+ expect(described_class.unavailable_reason).to include('ABI 3')
18
+ allow(Kernel).to receive(:syscall).with(444, 0, 0, 1).and_raise(Errno::ENOSYS)
19
+ expect(described_class.unavailable_reason).to eq("Errno::ENOSYS: #{Errno::ENOSYS.new.message}")
20
+ allow(Kernel).to receive(:syscall).with(444, 0, 0, 1).and_raise(Errno::EINVAL)
21
+ expect { described_class.unavailable_reason }.to raise_error(Errno::EINVAL)
22
+ end
23
+ end
@@ -0,0 +1,188 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'spec_helper'
4
+
5
+ describe PWN::AI::Agent::Loop, 'chat deliverables' do
6
+ include_context 'pwn tmp sandbox'
7
+
8
+ let(:sid) { PWN::Sessions.create[:id] }
9
+ let(:note) { 'Thank you for making time for me.' }
10
+ let(:missing) { 'Translate the following sentence into Italian.' }
11
+ let(:question) { 'Which sentence would you like me to translate?' }
12
+
13
+ before do
14
+ allow(Dir).to receive(:home).and_return(@tmp)
15
+ PWN::Env[:ai][:active] = :openai
16
+ PWN::Env[:ai][:openai] = { model: 'gpt-5', server_tools: ['web_search'] }
17
+ @agent_cfg[:plan_first] = true
18
+ expect(PWN::AI::Agent::Dispatch).not_to receive(:call)
19
+ expect(PWN::AI::Agent::Reward).not_to receive(:judge)
20
+ end
21
+
22
+ def submit(request, **opts)
23
+ described_class.run(request: request, session_id: sid, on_outcome: ->(row) { @outcome = row }, **opts)
24
+ end
25
+
26
+ def reply(text)
27
+ { choices: [{ message: { role: 'assistant', content: text } }] }
28
+ end
29
+
30
+ def checkpoints
31
+ Dir.glob(File.join(PWN::Sessions.sessions_dir, 'requests', Digest::SHA256.hexdigest(sid), '*.json')).map { |path| JSON.parse(File.read(path), symbolize_names: true) }
32
+ end
33
+
34
+ def public_history
35
+ PWN::Sessions.load(session_id: sid).drop(1).map { |row| row.values_at(:role, :content) }
36
+ end
37
+
38
+ {
39
+ 'Write a one-sentence thank-you note here in chat.' => 'Thank you for making time for me.',
40
+ 'Give me a one-sentence thank-you note here in chat.' => 'Thank you for making time for me.',
41
+ 'Write a one-sentence thank-you note.' => 'Thank you for making time for me.',
42
+ 'Write me an epitaph for an imaginary constellation.' => 'The dark remembers where you shone.',
43
+ 'Could you compose a short birthday greeting?' => 'Happy birthday!',
44
+ 'Draft a cheerful poem about spring.' => 'A bud unfolds in April rain.',
45
+ 'Compose an inscription for a cracked observatory lens.' => 'Even imperfect glass can hold a star.',
46
+ 'How many sides does a triangle have?' => 'Three.',
47
+ 'What is the number of edges of a cube?' => 'Twelve.',
48
+ 'Convert two hours to minutes.' => '120 minutes.',
49
+ 'How many centimeters are in 1.5 meters?' => '150 centimeters.',
50
+ 'Translate this sentence into Spanish: "I like apples."' => 'Me gustan las manzanas.'
51
+ }.each do |request, answer|
52
+ it "delivers #{request.inspect} on one untooled model turn and saves answer-only evidence" do
53
+ expect(described_class).not_to receive(:plan_first)
54
+ expect(PWN::AI::OpenAI).to receive(:chat_with_tools).once do |wire|
55
+ expect([*wire[:tools], *wire[:server_tools], wire[:tool_choice]].compact).to be_empty
56
+ expect(wire[:messages].last).to include(role: 'user', content: request)
57
+ reply(answer)
58
+ end
59
+ expect(submit(request)).to eq(answer)
60
+ expect(public_history).to eq([['user', request], ['assistant', answer]])
61
+ expect(@outcome).to include(status: 'complete', unmet: [])
62
+ expect(checkpoints.fetch(0)[:evidence]).to contain_exactly(hash_including(kind: 'answer', requirement: request, sha256: Digest::SHA256.hexdigest(answer)))
63
+ end
64
+ end
65
+
66
+ it 'preserves public text but does not execute or certify an unsolicited action on a reply turn' do
67
+ answer = 'Velvet dusk.'
68
+ call = { id: 'unused', type: 'function', function: { name: 'fixture_action', arguments: '{}' } }
69
+ expect(PWN::AI::OpenAI).to receive(:chat_with_tools).once.and_return(choices: [{ message: { role: 'assistant', content: answer, tool_calls: [call] } }])
70
+ result = submit('Compose a two-word caption.')
71
+ expect(result).to be_a(described_class::TurnNotice)
72
+ expect(result).to include(answer, 'not processed')
73
+ expect(@outcome).to include(status: 'incomplete', adjudication: 'unknown')
74
+ expect(public_history.last).to eq(['notice', result])
75
+ expect(checkpoints.first).to include(evidence: [], effects: {})
76
+ end
77
+
78
+ it 'records that a draft was saved, not that an independent verifier passed the original goal' do
79
+ runtime = nil
80
+ expect(PWN::AI::OpenAI).to receive(:chat_with_tools).once do
81
+ runtime = Thread.current[:pwn_request_runtime]
82
+ reply(note)
83
+ end
84
+ expect(submit('Draft a thank-you note.')).to eq(note)
85
+ expect(@outcome).to include(status: 'complete', adjudication: 'unknown')
86
+ expect(checkpoints.first.fetch(:evidence)).to contain_exactly(hash_including(kind: 'answer', locator: 'chat:reply', provenance: 'session_transcript', passed: nil))
87
+ expect(runtime.scope_evidenced?).to be(false)
88
+ end
89
+
90
+ it 'uses only the public disposition in a recovered non-ASCII clarification, without completing it or replaying actions' do
91
+ prompt = 'Quel énoncé souhaitez-vous traduire ?'
92
+ frame = JSON.generate(pwn_turn: 'needs_input', text: prompt, remaining: 'source sentence')
93
+ wire = JSON.generate(message: { role: 'assistant', content: frame, thinking: 'private fixture' }, done: true).b
94
+ expect(PWN::AI::Ollama).to receive(:chat_with_tools).once do |opts|
95
+ expect(Array(opts[:tools])).to be_empty
96
+ PWN::AI::Ollama.send(:assemble_ollama_stream, body: wire, rest_call: 'api/chat')
97
+ end
98
+ notices = []
99
+ expect(submit(missing, engine: :ollama, on_notice: ->(msg) { notices << msg })).to eq(prompt)
100
+ expect(@outcome).to include(status: 'incomplete', goal_status: 'awaiting_input', adjudication: 'unknown')
101
+ expect(public_history).to eq([['user', missing], ['assistant', prompt]])
102
+ expect(checkpoints.first).to include(evidence: [], effects: {})
103
+ expect(PWN::AI::Agent::OpenGoal.for_session(session_id: sid)).to include(request: missing)
104
+ end
105
+
106
+ it 'shows only public text and a warning when a recovered reply also contains a pending action' do
107
+ caption = 'Un été calme.'
108
+ frame = JSON.generate(pwn_turn: 'answer', text: caption)
109
+ message = { role: 'assistant', content: frame, tool_calls: [{ function: { name: 'fixture', arguments: { value: 'private marker' } } }] }
110
+ wire = JSON.generate(message: message, done: true).b
111
+ expect(PWN::AI::Ollama).to receive(:chat_with_tools).once do
112
+ PWN::AI::Ollama.send(:assemble_ollama_stream, body: wire, rest_call: 'api/chat')
113
+ end
114
+ notices = []
115
+ expect(submit('Draft a short caption.', engine: :ollama, on_notice: ->(msg) { notices << msg })).to eq(caption)
116
+ expect(notices).to contain_exactly(a_string_matching(/Ollama: .*action was not processed/))
117
+ expect(@outcome).to include(status: 'incomplete', unmet: ['unprocessed_action'], adjudication: 'unknown')
118
+ expect(public_history.last).to eq(['notice', "#{caption}\n\n#{notices.first}"])
119
+ expect(checkpoints.first).to include(evidence: [], effects: {})
120
+ end
121
+
122
+ it 'accepts a question as the supplied translation text without opening a different goal' do
123
+ source = 'Where are my glasses?'
124
+ translation = 'Dove sono i miei occhiali?'
125
+ expect(PWN::AI::OpenAI).to receive(:chat_with_tools).once.and_return(reply(JSON.generate(pwn_turn: 'needs_input', text: question, remaining: 'source sentence')))
126
+ expect(submit(missing)).to eq(question)
127
+ expect(PWN::AI::OpenAI).to receive(:chat_with_tools).once do |wire|
128
+ expect([*wire[:tools], *wire[:server_tools], wire[:tool_choice]].compact).to be_empty
129
+ expect(wire[:messages].last(3).map { |row| row[:content] }).to eq([missing, question, source])
130
+ reply(JSON.generate(pwn_turn: 'answer', text: translation, continues: true))
131
+ end
132
+ expect(submit(source)).to eq(translation)
133
+ expect(PWN::AI::Agent::OpenGoal.for_session(session_id: sid)).to be_nil
134
+ end
135
+
136
+ it 'keeps the original open goal through two different clarification questions' do
137
+ request = 'Translate the following sentence.'
138
+ language = 'Which language should I translate it into?'
139
+ source = 'Our lantern is still lit.'
140
+ answer = 'La nostra lanterna è ancora accesa.'
141
+ frames = [[question, 'needs_input', 'source sentence', false], [language, 'needs_input', 'language', true], [answer, 'answer', nil, true]]
142
+ expect(described_class).not_to receive(:plan_first)
143
+ expect(PWN::AI::OpenAI).to receive(:chat_with_tools).exactly(3).times do |wire|
144
+ text, state, remaining, continues = frames.shift
145
+ expect([*wire[:tools], *wire[:server_tools]]).to be_empty
146
+ reply(JSON.generate(pwn_turn: state, text: text, remaining: remaining, continues: continues))
147
+ end
148
+ expect(submit(request)).to eq(question)
149
+ goal = PWN::AI::Agent::OpenGoal.for_session(session_id: sid)
150
+ expect(submit(source)).to eq(language)
151
+ expect(PWN::AI::Agent::OpenGoal.for_session(session_id: sid)).to include(request: request, request_id: goal[:request_id], reply_question: Digest::SHA256.hexdigest(language))
152
+ expect(submit('Italian')).to eq(answer)
153
+ expect(PWN::AI::Agent::OpenGoal.for_session(session_id: sid)).to be_nil
154
+ end
155
+
156
+ it 'does not publish private reasoning or invent an unprocessed action for a thinking-only response' do
157
+ expect(PWN::AI::OpenAI).to receive(:chat_with_tools).once.and_return(choices: [{ message: { role: 'assistant', content: '', thinking: 'private synthetic reasoning' } }])
158
+ result = submit('Draft a two-word caption.')
159
+ expect(result).to be_a(described_class::TurnNotice)
160
+ expect(result).to include('No public answer')
161
+ expect(result).not_to include('private synthetic reasoning', 'An action')
162
+ expect(@outcome).to include(status: 'incomplete', unmet: ['public_reply_missing'])
163
+ end
164
+
165
+ it 'keeps missing source input open, then delivers the translation of the actual follow-up on its original request' do
166
+ expect(described_class).not_to receive(:plan_first)
167
+ expect(PWN::AI::OpenAI).to receive(:chat_with_tools).once.and_return(reply(JSON.generate(pwn_turn: 'needs_input', text: question, remaining: 'source sentence')))
168
+ expect(submit(missing)).to eq(question)
169
+ expect(@outcome).to include(status: 'incomplete', goal_status: 'awaiting_input', unmet: ['source sentence'])
170
+ waiting = checkpoints.fetch(0)
171
+ expect(waiting).to include(original_request: missing, evidence: [], effects: {})
172
+ expect(PWN::AI::Agent::OpenGoal.for_session(session_id: sid)).to include(request_id: waiting[:request_id])
173
+ expect(public_history).to eq([['user', missing], ['assistant', question]])
174
+ source = 'Our lantern is still lit.'
175
+ translation = 'La nostra lanterna è ancora accesa.'
176
+ expect(PWN::AI::OpenAI).to receive(:chat_with_tools).once do |wire|
177
+ expect([*wire[:tools], *wire[:server_tools], wire[:tool_choice]].compact).to be_empty
178
+ expect(wire[:messages].last(3).map { |row| row.values_at(:role, :content) }).to eq([['user', missing], ['assistant', question], ['user', source]])
179
+ reply(JSON.generate(pwn_turn: 'answer', text: translation, continues: true))
180
+ end
181
+ expect(submit(source)).to eq(translation)
182
+ expect(@outcome).to include(status: 'complete', unmet: [])
183
+ expect(public_history.last(2)).to eq([['user', source], ['assistant', translation]])
184
+ expect(checkpoints).to contain_exactly(hash_including(request_id: waiting[:request_id], outcome: hash_including(goal_status: 'awaiting_input')),
185
+ hash_including(original_request: source, evidence: [hash_including(kind: 'answer', sha256: Digest::SHA256.hexdigest(translation))]))
186
+ expect(PWN::AI::Agent::OpenGoal.for_session(session_id: sid)).to be_nil
187
+ end
188
+ end
@@ -4,11 +4,91 @@ require 'spec_helper'
4
4
  require 'json'
5
5
 
6
6
  describe PWN::AI::Agent::Dispatch do
7
- it 'does not replay a timed-out real shell mutation after restoring its request checkpoint' do
7
+ describe 'reviewed cross-session memory saves' do
8
+ include_context 'pwn tmp sandbox'
9
+
10
+ let(:proposal) { { key: 'display_units', value: 'Use °C', category: 'preference' } }
11
+ let(:runtime_options) { { request: 'Remember my display preference', session_id: 'review', request_id: 'memory', artifact_root: File.join(@tmp, 'requests'), trace: false } }
12
+ let(:runtime) { PWN::AI::Agent::RequestRuntime.new(runtime_options) }
13
+
14
+ around do |example|
15
+ previous = [Thread.current[:pwn_review_memory], Thread.current[:pwn_request_runtime]]
16
+ Thread.current[:pwn_review_memory] = nil
17
+ example.run
18
+ ensure
19
+ Thread.current[:pwn_review_memory], Thread.current[:pwn_request_runtime] = previous
20
+ end
21
+
22
+ before do
23
+ allow(Dir).to receive(:home).and_return(@tmp)
24
+ PWN::AI::Agent::Registry.discover
25
+ Thread.current[:pwn_request_runtime] = runtime
26
+ expect(PWN::Plugins::Vault).not_to receive(:expand)
27
+ expect(PWN::Plugins::Vault).not_to receive(:redact)
28
+ end
29
+
30
+ def save_memory(fields)
31
+ call = { id: 'save-preference', function: { name: 'memory_remember', arguments: fields } }
32
+ JSON.parse(described_class.call(tool_call: call), symbolize_names: true)
33
+ end
34
+
35
+ it 'saves only the reviewed fields, with a durable completion and independent file readback' do
36
+ seen = []
37
+ Thread.current[:pwn_review_memory] = lambda do |fields|
38
+ seen << fields
39
+ expect(fields).to be_frozen
40
+ expect(fields.values).to all(be_frozen)
41
+ expect(File).not_to exist(PWN::Memory::MEMORY_FILE)
42
+ true
43
+ end
44
+ expect(save_memory(proposal)).to eq(success: true, effect: 'store', result: { saved: true })
45
+ expect(seen).to eq([proposal])
46
+ expect(JSON.parse(File.read(PWN::Memory::MEMORY_FILE)).fetch('display_units')).to include('value' => 'Use °C', 'category' => 'preference')
47
+ expect(runtime.events.last).to include(phase: 'end', state: 'completed', action_id: 'save-preference')
48
+ expect(runtime.blocker).to be_nil
49
+ end
50
+
51
+ it 'does not start a write on missing review, decline, or a self-approved tool payload' do
52
+ expect(save_memory(proposal)).to include(success: false, result: include(execution_state: 'not_started'))
53
+ Thread.current[:pwn_review_memory] = ->(_fields) { false }
54
+ expect(save_memory(proposal)).to include(success: false, result: include(execution_state: 'not_started'))
55
+ reviewer = double('operator review')
56
+ expect(reviewer).not_to receive(:call)
57
+ Thread.current[:pwn_review_memory] = reviewer
58
+ expect(save_memory(proposal.merge(operator_ack: true))).to include(success: false)
59
+ expect(save_memory(proposal.merge(value: '{{vault:fixture}}'))).to include(success: false)
60
+ expect(File).not_to exist(PWN::Memory::MEMORY_FILE)
61
+ expect(runtime.events).to be_empty
62
+ end
63
+
64
+ it 'distinguishes lock denial before mutation from a lost receipt after a write and never replays the latter' do
65
+ Thread.current[:pwn_review_memory] = ->(_fields) { true }
66
+ allow(File).to receive(:open).and_call_original
67
+ allow(File).to receive(:open).with("#{PWN::Memory::MEMORY_FILE}.write.lock", anything, anything).and_raise(Errno::EACCES)
68
+ expect(save_memory(proposal)).to include(success: false, result: include(execution_state: 'not_started'))
69
+ expect(runtime.blocker).to be_nil
70
+ expect(File).not_to exist(PWN::Memory::MEMORY_FILE)
71
+
72
+ allow(File).to receive(:open).with("#{PWN::Memory::MEMORY_FILE}.write.lock", anything, anything).and_call_original
73
+ allow(PWN::Memory).to receive(:remember).and_wrap_original do |writer, **options|
74
+ writer.call(**options)
75
+ raise Errno::EACCES, 'after write'
76
+ end
77
+ expect(save_memory(proposal)).to include(success: false)
78
+ expect(PWN::Memory.load.fetch(:display_units)).to include(value: 'Use °C')
79
+ restored = PWN::AI::Agent::RequestRuntime.new(runtime_options.merge(resume: true))
80
+ Thread.current[:pwn_request_runtime] = restored
81
+ expect(restored.blocker).to include('Uncertain side effect: memory_remember')
82
+ expect(save_memory(proposal)).to include(success: false, result: include(error: 'uncertain_side_effect'))
83
+ expect(PWN::Memory).to have_received(:remember).once
84
+ end
85
+ end
86
+
87
+ it 'does not replay a timed-out real shell mutation after restoring its request checkpoint', :requires_landlock do
8
88
  Dir.mktmpdir do |root|
9
89
  work = File.join(root, 'work')
10
90
  FileUtils.mkdir_p(work)
11
- allow(PWN::Plugins::AISandbox).to receive(:workspace).and_return(work)
91
+ allow(PWN::AI::Sandbox).to receive(:workspace).and_return(work)
12
92
  options = { request: 'Write counter', session_id: 'timeout', request_id: 'fixture', artifact_root: File.join(root, 'control'), trace: false }
13
93
  runtime = PWN::AI::Agent::RequestRuntime.new(options)
14
94
  Thread.current[:pwn_request_runtime] = runtime