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
@@ -23,9 +23,31 @@ module PWN
23
23
  pwn_reflect_depth pwn_request_intent pwn_loop_budget_s pwn_loop_mutations pwn_loop_tokens].freeze
24
24
  attr_reader :status
25
25
 
26
+ @fork_lock = Mutex.new
27
+ @control_writers = ObjectSpace::WeakMap.new
28
+
26
29
  class << self
27
30
  attr_accessor :owned, :bootstrap_requires, :force_exec
28
31
 
32
+ # Register the parent endpoint atomically with respect to all mission
33
+ # forks, including sibling missions started by another console thread.
34
+ def control_socket_pair
35
+ @fork_lock.synchronize do
36
+ UNIXSocket.pair.tap { |_reader, writer| @control_writers[writer] = true }
37
+ end
38
+ end
39
+
40
+ def fork_mission
41
+ @fork_lock.synchronize do
42
+ writers = @control_writers.keys # Pin live endpoints across fork, not for the console's lifetime.
43
+ fork do
44
+ @fork_lock = Mutex.new # Nested missions must not use the parent's held lock.
45
+ writers.each(&:close) # Close the copies, never shutdown the shared socket.
46
+ yield
47
+ end
48
+ end
49
+ end
50
+
29
51
  def prepared?
30
52
  rows = File.readlines('/proc/self/uid_map').map { |line| line.split.map(&:to_i) }
31
53
  count = rows.length == 1 ? rows.first.last : nil
@@ -59,6 +81,7 @@ module PWN
59
81
  raise ArgumentError, 'mission snapshot is too deep or cyclic' if depth > 30
60
82
 
61
83
  case value
84
+ when PWN::Config::SkillCatalog then ['skill_catalog', encode(value.root, depth + 1), encode(value.to_h, depth)]
62
85
  when Hash then ['hash', value.map { |key, item| [encode(key, depth + 1), encode(item, depth + 1)] }]
63
86
  when Array then ['array', value.map { |item| encode(item, depth + 1) }]
64
87
  when Time then ['time', value.to_i, value.nsec, value.utc_offset, value.utc?]
@@ -74,6 +97,7 @@ module PWN
74
97
  def decode(value)
75
98
  type, body, encoding = value
76
99
  case type
100
+ when 'skill_catalog' then PWN::Config::SkillCatalog.new(decode(body)).replace(decode(value.fetch(2))).freeze
77
101
  when 'hash' then body.to_h { |key, item| [decode(key), decode(item)] }
78
102
  when 'array' then body.map { |item| decode(item) }
79
103
  when 'time' then value[4] ? Time.at(body, encoding, :nanosecond).utc : Time.at(body, encoding, :nanosecond).getlocal(value[3])
@@ -92,7 +116,7 @@ module PWN
92
116
  checked(native('unshare', [Fiddle::TYPE_INT]).call(0x20000000), 'unshare PID namespace') if pid_namespace
93
117
  reader, writer = IO.pipe
94
118
  armed, arm = IO.pipe
95
- init = fork do
119
+ init = fork_mission do
96
120
  armed.close
97
121
  checked(native('prctl', [Fiddle::TYPE_INT, Fiddle::TYPE_LONG, Fiddle::TYPE_LONG, Fiddle::TYPE_LONG, Fiddle::TYPE_LONG]).call(1, Signal.list.fetch('KILL'), 0, 0, 0), 'PR_SET_PDEATHSIG')
98
122
  arm.write('1')
@@ -167,7 +191,7 @@ module PWN
167
191
  require 'pwn/ai/cli'
168
192
  PWN::AI::CLI.send(:mission_entry, descriptor)
169
193
  when :protected
170
- PWN::Plugins::AISandbox.send(:mission_entry, descriptor)
194
+ PWN::AI::Sandbox.send(:mission_entry, descriptor)
171
195
  when :console, :slash
172
196
  PWN::Plugins::REPL::AIConsole::Console.send(:mission_entry, descriptor: descriptor)
173
197
  when :legacy, :steerable
@@ -192,7 +216,7 @@ module PWN
192
216
  if operation
193
217
  raise Unavailable, 'host closures cannot cross an exec boundary; use a mission descriptor or explicitly bootstrap under unshare --user --map-current-user --keep-caps' unless self.class.owned
194
218
 
195
- @pid = fork do
219
+ @pid = self.class.fork_mission do
196
220
  Thread.handle_interrupt(Exception => :immediate) { operation.call }
197
221
  ensure
198
222
  exit!
@@ -200,15 +224,9 @@ module PWN
200
224
  @pidfd = IO.new(self.class.checked(self.class.native('pidfd_open', [Fiddle::TYPE_INT, Fiddle::TYPE_INT]).call(@pid, 0), 'pidfd_open'))
201
225
  return
202
226
  end
203
- snapshot = { requires: Array(self.class.bootstrap_requires), descriptor: opts.fetch(:descriptor), env: PWN::Env, locals: CONTEXT_KEYS.to_h { |key| [key, Thread.current[key]] } }
204
- if PWN.const_defined?(:Skills)
205
- snapshot[:skills] = PWN::Skills
206
- ruby_skills = PWN::Skills.values.select { |skill| skill[:loaded] && skill[:type] == :ruby }
207
- snapshot[:requires] += ruby_skills.flat_map do |skill|
208
- skill[:format] == :legacy ? [skill.fetch(:path)] : Dir.glob(File.join(skill.fetch(:dir), 'scripts', '*.rb'))
209
- end
210
- snapshot[:requires].uniq!
211
- end
227
+ snapshot = { requires: trusted_bootstrap_paths, descriptor: opts.fetch(:descriptor), env: PWN::Env, locals: CONTEXT_KEYS.to_h { |key| [key, Thread.current[key]] } }
228
+ # The writable catalog is reference data, never a source of bootstrap requires.
229
+ snapshot[:skills] = PWN::Skills if PWN.const_defined?(:Skills)
212
230
  mode = opts[:containment] == :host ? :host : :namespace
213
231
  payload = JSON.generate(self.class.encode(snapshot))
214
232
  start_supervisor(payload, opts, mode)
@@ -278,6 +296,26 @@ module PWN
278
296
 
279
297
  private
280
298
 
299
+ def trusted_bootstrap_paths
300
+ paths = Array(self.class.bootstrap_requires)
301
+ return [] if paths.empty?
302
+
303
+ library = PWN::Config.pwn_skills_path
304
+ roots = [library]
305
+ roots << File.realpath(library) if File.directory?(library)
306
+ paths.map do |path|
307
+ raise Unavailable, 'mission snapshot bootstrap requires an absolute file path' unless path.is_a?(String) && path.start_with?('/')
308
+
309
+ resolved = File.realpath(path)
310
+ in_catalog = [File.expand_path(path), resolved].any? { |file| roots.any? { |dir| file == dir || file.start_with?("#{dir}/") } }
311
+ raise Unavailable, 'mission snapshot bootstrap files must be outside the writable skills library' if in_catalog
312
+
313
+ resolved
314
+ end
315
+ rescue SystemCallError => e
316
+ raise Unavailable, "mission snapshot bootstrap file unavailable: #{e.message}"
317
+ end
318
+
281
319
  def start_supervisor(payload, opts, mode)
282
320
  @channel, child = UNIXSocket.pair
283
321
  err_read, err_write = IO.pipe
@@ -320,7 +358,7 @@ module PWN
320
358
  ready, announce = IO.pipe
321
359
  release, gate = IO.pipe
322
360
  owner = Process.pid
323
- @pid = fork do
361
+ @pid = self.class.fork_mission do
324
362
  ready.close
325
363
  gate.close
326
364
  begin
@@ -328,7 +366,7 @@ module PWN
328
366
  exit! unless Process.ppid == owner
329
367
  self.class.checked(self.class.native('unshare', [Fiddle::TYPE_INT]).call(0x20000000), 'unshare PID namespace')
330
368
  armed, arm = IO.pipe
331
- init = fork do
369
+ init = self.class.fork_mission do
332
370
  armed.close
333
371
  announce.close
334
372
  self.class.checked(self.class.native('prctl', [Fiddle::TYPE_INT, Fiddle::TYPE_LONG, Fiddle::TYPE_LONG, Fiddle::TYPE_LONG, Fiddle::TYPE_LONG]).call(1, Signal.list.fetch('KILL'), 0, 0, 0), 'PR_SET_PDEATHSIG')
@@ -57,21 +57,39 @@ module PWN
57
57
  }
58
58
  runtime = Thread.current[:pwn_request_runtime]
59
59
  row.merge!(request_id: runtime.request_id, checkpoint_path: runtime.checkpoint_path) if runtime
60
- atomic_write(path: goal_file, row: row)
61
- atomic_write(path: File.join(File.dirname(goal_file), 'current.json'), row: row) if runtime
60
+ path = goal_file
61
+ if opts[:answered_id]
62
+ waiting = pending_reply(opts)
63
+ return :held unless waiting
64
+
65
+ row = waiting.merge(updated_at: row[:updated_at], reply_after: Digest::SHA256.hexdigest(request))
66
+ path = File.join(File.dirname(path), "#{Digest::SHA256.hexdigest(waiting.fetch(:request_id))}.json")
67
+ end
68
+ row.merge!(reply_question: opts[:reply_question], reply_medium: opts[:reply_medium]) if runtime && opts[:reply_medium]
69
+ atomic_write(path: path, row: row)
70
+ atomic_write(path: File.join(File.dirname(path), 'current.json'), row: row) if runtime
62
71
  row
63
72
  end
64
73
 
65
74
  public_class_method def self.clear!(opts = {})
66
75
  return :ok unless opts.is_a?(Hash)
67
- return :ok unless File.file?(goal_file)
76
+
77
+ path = goal_file
78
+ id = Thread.current[:pwn_request_runtime]&.request_id
79
+ if (answered = opts[:answered_id])
80
+ return :held unless pending_reply(opts)
81
+
82
+ id = answered
83
+ path = File.join(File.dirname(path), "#{Digest::SHA256.hexdigest(id)}.json")
84
+ end
85
+ return :ok unless File.file?(path)
68
86
  return :held if mission_open?
69
87
 
70
- File.delete(goal_file)
71
- pointer = File.join(File.dirname(goal_file), 'current.json')
88
+ File.delete(path)
89
+ pointer = File.join(File.dirname(path), 'current.json')
72
90
  if Thread.current[:pwn_request_runtime] && File.file?(pointer)
73
91
  row = JSON.parse(File.read(pointer), symbolize_names: true)
74
- File.delete(pointer) if row[:request_id] == Thread.current[:pwn_request_runtime].request_id
92
+ File.delete(pointer) if row[:request_id] == id
75
93
  end
76
94
  :ok
77
95
  rescue StandardError
@@ -108,11 +126,14 @@ module PWN
108
126
  #{self}.begin!(
109
127
  request: 'required - request value consumed by #begin!',
110
128
  session_id: 'optional - session id value consumed by #begin!',
111
- mission_id: 'optional - durable mission id consumed by #begin!'
129
+ mission_id: 'optional - durable mission id consumed by #begin!',
130
+ answered_id: 'optional - retain this immediately preceding conversational goal when another input is needed',
131
+ reply_question: 'optional - digest of a saved question awaiting operator input',
132
+ reply_medium: 'optional - text or information delivery for that pending answer'
112
133
  )
113
134
 
114
- # Run clear and return its result
115
- #{self}.clear!
135
+ # Close only the owning request or its immediately answered conversational question.
136
+ #{self}.clear!(answered_id: 'optional - exact pending conversational request id in the current session')
116
137
 
117
138
  # Run resume and return its result
118
139
  #{self}.resume?(
@@ -125,6 +146,12 @@ module PWN
125
146
  constants.sort
126
147
  end
127
148
 
149
+ private_class_method def self.pending_reply(opts = {})
150
+ runtime = Thread.current[:pwn_request_runtime]
151
+ row = for_session(session_id: runtime.session_id) if runtime
152
+ row if row && row[:request_id] == opts[:answered_id] && row[:reply_question] && row[:mission_id].to_s.empty?
153
+ end
154
+
128
155
  private_class_method def self.atomic_write(opts = {})
129
156
  path = opts[:path]
130
157
  FileUtils.mkdir_p(File.dirname(path), mode: 0o700)
@@ -4,7 +4,9 @@ require 'json'
4
4
  require 'fileutils'
5
5
  require 'time'
6
6
  require 'digest'
7
+ require 'tempfile'
7
8
  require_relative '../../memory'
9
+ require_relative 'turn_finalizer'
8
10
 
9
11
  module PWN
10
12
  module AI
@@ -194,6 +196,9 @@ module PWN
194
196
  )
195
197
  ep = {
196
198
  session_id: sid,
199
+ submission_scope: Thread.current[:pwn_loop_submission_scope],
200
+ submission_id: Thread.current[:pwn_loop_submission_scope]&.root_id,
201
+ request_id: opts[:request_id],
197
202
  request: opts[:request].to_s.dup,
198
203
  kind: normalize_kind(raw: opts[:kind]),
199
204
  intent: opts[:intent].to_s,
@@ -343,6 +348,9 @@ module PWN
343
348
  attribute_terminal!(episode: ep, reward: terminal, attribution: opts[:attribution])
344
349
  ep[:steps].last[:terminal] = true
345
350
  ep[:score] = opts[:score]
351
+ role = opts[:close_role].to_s
352
+ role = Thread.current[TurnFinalizer::INLINE_KEY] ? 'deferred' : 'direct' unless %w[controller steering learning deferred].include?(role)
353
+ ep[:close_role] = role
346
354
  ep[:verdict] = opts[:verdict]
347
355
  ep[:return] = opts[:score].nil? ? nil : discounted_return(steps: ep[:steps])
348
356
  ep[:ended_at] = Time.now.utc.iso8601
@@ -547,8 +555,11 @@ module PWN
547
555
  end
548
556
 
549
557
  public_class_method def self.attach_episode!(opts = {})
550
- Thread.current[EP_KEY] = opts[:episode]
551
- opts[:episode]
558
+ episode = opts[:episode]
559
+ # The dedicated reviewer may start an internal turn after it has
560
+ # already closed this episode. Only the opaque correlation ID survives.
561
+ Thread.current[:pwn_review_submission_id] ||= episode[:submission_id] if episode && Thread.current[TurnFinalizer::INLINE_KEY]
562
+ Thread.current[EP_KEY] = episode
552
563
  end
553
564
 
554
565
  # ----------------------------------------------------------------
@@ -714,9 +725,11 @@ module PWN
714
725
  rest = keep.reject { |_, _, g| g }.last([MAX_TRAJ - gold.length, 0].max).map { |_, line, _| line }
715
726
  out = gold + rest
716
727
  unless dry
717
- tmp = "#{TRAJECTORY_FILE}.#{Process.pid}.tmp"
718
- File.write(tmp, out.join)
719
- File.rename(tmp, TRAJECTORY_FILE)
728
+ Tempfile.create(['.policy-trajectory-', '.tmp'], File.dirname(TRAJECTORY_FILE)) do |file|
729
+ file.write(out.join)
730
+ file.flush
731
+ File.rename(file.path, TRAJECTORY_FILE)
732
+ end
720
733
  end
721
734
  { removed: rows.length - out.length, remaining: out.length, dry_run: dry }
722
735
  rescue StandardError => e
@@ -796,6 +809,7 @@ module PWN
796
809
  # Episode / environment loop
797
810
  #{self}.begin_episode(
798
811
  session_id: 'optional - PWN::Sessions id (defaults to ep_)',
812
+ request_id: 'optional - stable request identity; only its SHA-256 enters the trajectory',
799
813
  request: 'optional - user request',
800
814
  kind: 'optional - request kind',
801
815
  intent: 'optional - Loop.request_intent',
@@ -824,6 +838,7 @@ module PWN
824
838
  # Run finish and return its result
825
839
  #{self}.finish(
826
840
  session_id: 'optional - active episode id',
841
+ close_role: 'optional - controller, steering, learning or deferred; records who closed this episode without affecting training',
827
842
  score: 'optional - Reward.judge 0..1 (training target)',
828
843
  verdict: 'optional - solved|partial|wrong|refused',
829
844
  proxy_ok: 'optional - Boolean fallback when no judge score',
@@ -1393,12 +1408,18 @@ module PWN
1393
1408
  ep = opts[:episode]
1394
1409
  return unless ep.is_a?(Hash)
1395
1410
 
1396
- tab = load
1397
- tab[:returns] = (Array(tab[:returns]) + [ep[:return].to_f]).last(200) unless ep[:score].nil?
1398
- save(table: tab)
1399
- FileUtils.mkdir_p(File.dirname(TRAJECTORY_FILE))
1411
+ unless ep[:score].nil?
1412
+ tab = load
1413
+ tab[:returns] = (Array(tab[:returns]) + [ep[:return].to_f]).last(200)
1414
+ save(table: tab)
1415
+ end
1416
+ FileUtils.mkdir_p(File.dirname(TRAJECTORY_FILE), mode: 0o700)
1400
1417
  row = {
1401
1418
  session_id: ep[:session_id],
1419
+ submission_id: ep[:submission_id],
1420
+ episode_role: ep[:submission_scope]&.role || 'standalone',
1421
+ close_role: ep[:close_role],
1422
+ request_key: (Digest::SHA256.hexdigest(ep[:request_id]) if ep[:request_id]),
1402
1423
  request_family: task_family(text: ep[:request]),
1403
1424
  kind: ep[:kind],
1404
1425
  engine: ep[:engine],
@@ -1410,7 +1431,13 @@ module PWN
1410
1431
  attribution: ep[:attribution],
1411
1432
  steps: ep[:steps]
1412
1433
  }
1413
- File.open(TRAJECTORY_FILE, 'a') { |f| f.puts(JSON.dump(row)) }
1434
+ File.open(TRAJECTORY_FILE, File::WRONLY | File::APPEND | File::CREAT | File::NOFOLLOW | File::NONBLOCK, 0o600) do |file|
1435
+ stat = file.stat
1436
+ raise IOError, 'unsafe trajectory file' unless stat.file? && stat.nlink == 1 && stat.owned?
1437
+
1438
+ file.chmod(stat.mode & 0o600) unless stat.mode.nobits?(0o077)
1439
+ file.puts(JSON.dump(row))
1440
+ end
1414
1441
  end
1415
1442
  end
1416
1443
  end
@@ -38,24 +38,31 @@ module PWN
38
38
  engine = active_engine
39
39
  # thin: greeting/statement/howto/recall — base + ENV + optional recent turns.
40
40
  # Full MEMORY/METRICS/MISTAKES/EXTRO only for act/recon (default).
41
- thin = opts[:thin] == true || opts[:mode].to_s == 'thin'
41
+ mode = opts[:mode].to_s
42
+ thin = opts[:thin] == true || %w[thin conversation].include?(mode)
42
43
  b = budget
43
44
  base = (PWN::Env.dig(:ai, engine, :system_role_content) if defined?(PWN::Env)) || 'You are a world-class introspective offensive cyber security and research engineer. You specialize in discovering zero day vulnerabilities focused on responsible disclosure prior to threat actors discovering and exploiting. You are self-aware of your harness, pwn which begins with the ruby namespace `PWN` operating inside the pwn REPL. For every request you first begin by determining if PWN has a module capable of satisfying the request.'
44
45
 
45
46
  if thin
46
47
  recent = recent_turns_block(session_id: session_id, request: request, limit: [b[:recent_turns].to_i, 2].min)
47
- return <<~PROMPT
48
+ context = <<~PROMPT
48
49
  #{base}
49
50
 
50
51
  ENVIRONMENT
51
52
  host : #{host_line}
52
- cwd : #{Thread.current[:pwn_request_runtime]&.contract&.dig(:cwd) || PWN::Plugins::AISandbox.task_directory}
53
- writes : new files go to #{PWN::Plugins::AISandbox.workspace} unless the original operator request names another path
53
+ cwd : #{Thread.current[:pwn_request_runtime]&.contract&.dig(:cwd) || PWN::AI::Sandbox.task_directory}
54
+ writes : new files go to #{PWN::AI::Sandbox.workspace} unless the original operator request names another path
54
55
  ruby : #{RUBY_VERSION}
55
56
  pwn : #{pwn_version}
56
57
  session_id : #{session_id || '(none)'}
57
58
 
58
- #{recent}TOOL USE
59
+ PROMPT
60
+ context += recent
61
+ # Conversational source availability is bound at the provider hop.
62
+ return context if mode == 'conversation'
63
+
64
+ return context + <<~PROMPT
65
+ TOOL USE
59
66
  No tools on this turn unless a single factual lookup is already in
60
67
  context. Answer concisely in plain US English. Do not plan multi-step
61
68
  work, invent task traces, or run live recon.
@@ -78,8 +85,8 @@ module PWN
78
85
 
79
86
  ENVIRONMENT
80
87
  host : #{host_line}
81
- cwd : #{Thread.current[:pwn_request_runtime]&.contract&.dig(:cwd) || PWN::Plugins::AISandbox.task_directory}
82
- writes : new files go to #{PWN::Plugins::AISandbox.workspace} unless the original operator request names another path
88
+ cwd : #{Thread.current[:pwn_request_runtime]&.contract&.dig(:cwd) || PWN::AI::Sandbox.task_directory}
89
+ writes : new files go to #{PWN::AI::Sandbox.workspace} unless the original operator request names another path
83
90
  ruby : #{RUBY_VERSION}
84
91
  pwn : #{pwn_version}
85
92
  session_id : #{session_id || '(none)'}
@@ -424,7 +431,7 @@ module PWN
424
431
  session_id: 'optional - PWN::Sessions id to embed in the ENV block',
425
432
  request: 'optional - user request; enables relevance-ranked MEMORY when provided',
426
433
  thin: 'optional - thin value consumed by #build',
427
- mode: 'optional - mode value consumed by #build',
434
+ mode: 'optional - thin for short replies, or conversation when the provider supplies the lookup instructions',
428
435
  expand_harness: 'optional - expand harness value consumed by #build',
429
436
  stuck: 'optional - stuck value consumed by #build'
430
437
  )
@@ -16,15 +16,30 @@ module PWN
16
16
  module Agent
17
17
  # Connect request-scoped routing, evidence context and replay records.
18
18
  class RequestRuntime # rubocop:disable Metrics/ClassLength -- one owner for routing, scope and durable evidence
19
+ class MemoryWriteNotStarted < StandardError; end
20
+
19
21
  OUTCOMES = %w[complete incomplete blocked cancelled verification_error].freeze
20
- attr_reader :original_request, :request, :session_id, :request_id, :contract, :amendments, :outcome, :checkpoint_path, :engine, :last_provider_attempts
22
+ # Only literal operands can be quoted. The rest must be an entire
23
+ # affirmative directive; free text before "to" can itself be an example.
24
+ SKILL_OPERAND = %r{(?<!\S)(?:(?<quote>["'`])(?<quoted>(?:~?/|\.\.?/)[[:alnum:]\x20_./+-]+|[\w+-]+\.[[:alnum:]]+)\k<quote>|
25
+ (?<bare>(?:~?/|\.\.?/)[[:alnum:]_./+-]+|[\w+-]+\.[[:alnum:]]+))}x
26
+ SKILL_DOCUMENT = /(?:(?:the|a|an|my|our|this|these)\s+)?(?:(?:new|local|supporting|reference|skill)\s+){0,3}
27
+ (?:notes?|document|template|file|report|summary|skill|(?:guide|reference)(?!\s+to\b))|
28
+ (?:the|my|our)\s+(?!(?:no|not|never|without|if|unless)\b)[\w-]+\s+(?:notes?\s+)?skill/ix
29
+ SKILL_READ = /\A(?:please\s+)?(?:read|inspect|review)\s+(?:(?:the\s+)?file\s+)?\x00\z/i
30
+ SKILL_WRITE = /\A(?:please\s+)?
31
+ (?:(?:write|save|store|create|edit|update|modify|append|put|export|generate)\s+(?:#{SKILL_DOCUMENT}\s+)?
32
+ (?:(?:(?<inside>under|inside|within|beneath)|to|at|as|in|into)\s+)?|
33
+ copy\s+(?:from\s+)?\x00\s+(?:to|into)\s+)
34
+ (?:(?<container>(?:(?:the|a)\s+)?(?:directory|folder))\s+(?:(?:at|named)\s+)?)?\x00\z/ix
35
+ attr_reader :original_request, :request, :session_id, :request_id, :contract, :amendments, :outcome, :checkpoint_path, :engine, :last_provider_attempts, :submission_id, :submission_report
21
36
 
22
37
  def initialize(opts = {})
23
38
  @session_id = opts[:session_id].to_s
24
39
  @request_id = (opts[:request_id] || SecureRandom.uuid).to_s.freeze
25
40
  @original_request = PWN::AI::Agent::Result.utf8_text(text: opts[:request]).freeze
26
41
  @request = @original_request
27
- @cwd = Thread.current[:pwn_solve_workspace] || PWN::Plugins::AISandbox.task_directory
42
+ @cwd = Thread.current[:pwn_solve_workspace] || PWN::AI::Sandbox.task_directory
28
43
  @amendments = [].freeze
29
44
  @observations = {}
30
45
  @events = []
@@ -45,8 +60,8 @@ module PWN
45
60
  @retrieve = opts.fetch(:retrieve, true)
46
61
  root = opts[:artifact_root] || File.join(PWN::Sessions.sessions_dir, 'requests')
47
62
  @checkpoint_path = File.join(root, Digest::SHA256.hexdigest(@session_id), "#{Digest::SHA256.hexdigest(@request_id)}.json")
48
- restore! if opts[:resume]
49
- rebuild_contract!
63
+ prior_destinations = restore! if opts[:resume]
64
+ rebuild_contract!(prior_destinations)
50
65
  @profile = opts[:profile]
51
66
  @router = Profiles.new(profiles: opts[:profiles] || {})
52
67
  @engine = @router.lookup(name: @profile)[:provider] if @profile && !@explicit_route
@@ -60,7 +75,9 @@ module PWN
60
75
  end
61
76
 
62
77
  # A resumed execution cannot inherit an earlier terminal success.
63
- def start!
78
+ def start!(submission_id: nil)
79
+ @submission_id = submission_id
80
+ @submission_report = nil
64
81
  @outcome = nil
65
82
  checkpoint!
66
83
  end
@@ -91,7 +108,7 @@ module PWN
91
108
  # to the caller; the enclosing namespace is the child's cancellation owner.
92
109
  def mission_snapshot
93
110
  @mutex.synchronize do
94
- state = instance_variables.reject { |key| %i[@mutex @cancel @memory @router].include?(key) }.to_h { |key| [key, instance_variable_get(key)] }
111
+ state = instance_variables.reject { |key| %i[@mutex @cancel @memory @router @submission_report].include?(key) }.to_h { |key| [key, instance_variable_get(key)] }
95
112
  state[:memory] = @memory.instance_variables.to_h { |key| [key, @memory.instance_variable_get(key)] }
96
113
  state[:router] = @router.instance_variables.to_h { |key| [key, @router.instance_variable_get(key)] }
97
114
  state
@@ -100,6 +117,11 @@ module PWN
100
117
 
101
118
  private_class_method def self.from_mission_snapshot(opts = {})
102
119
  state = opts.fetch(:state).dup
120
+ # The tagged transport preserves types, not frozen containers. Keep
121
+ # the host's decision; never reclassify a file in the worker.
122
+ contract = state.fetch(:@contract)
123
+ contract.fetch(:skill_destinations).freeze
124
+ contract.freeze
103
125
  runtime = allocate
104
126
  { memory: EngagementMemory, router: Profiles }.each do |key, klass|
105
127
  object = klass.allocate
@@ -276,10 +298,12 @@ module PWN
276
298
  raise ArgumentError, 'evidence must name an original or amended requirement' if requirement.empty? || !source || !@request.include?(requirement)
277
299
  raise ArgumentError, 'unsupported evidence kind' unless %w[http command answer].include?(opts[:kind].to_s)
278
300
 
301
+ transcript = opts[:kind].to_s == 'answer' && opts[:locator] == 'chat:reply'
302
+ passed = opts[:passed] == true && evidence_target_matches?(opts) unless transcript
279
303
  row = { id: SecureRandom.uuid, request_id: @request_id, source_id: source[:id], requirement: requirement,
280
304
  offset: source[:text].index(requirement), requirement_sha256: Digest::SHA256.hexdigest(requirement),
281
305
  scope_sha256: Digest::SHA256.hexdigest(@request), kind: opts[:kind].to_s, locator: opts[:locator],
282
- sha256: opts.fetch(:sha256), passed: opts[:passed] == true && evidence_target_matches?(opts), provenance: 'host_verifier',
306
+ sha256: opts.fetch(:sha256), passed: passed, provenance: transcript ? 'session_transcript' : 'host_verifier',
283
307
  observed_at: Time.now.utc.iso8601(9), max_age: opts[:max_age] || (300 if opts[:kind].to_s == 'http') }
284
308
  @mutex.synchronize do
285
309
  @evidence << Marshal.load(Marshal.dump(row))
@@ -413,7 +437,12 @@ module PWN
413
437
  'failed'
414
438
  end
415
439
  result
416
- rescue PWN::Plugins::AISandbox::NotStarted => e
440
+ rescue MemoryWriteNotStarted => e
441
+ raise unless opts[:reviewed_memory] && opts[:name] == 'memory_remember'
442
+
443
+ state = 'failed'
444
+ { success: false, error: e.message, saved: false, execution_state: 'not_started' }
445
+ rescue PWN::AI::Sandbox::NotStarted => e
417
446
  state = 'rejected'
418
447
  action[:diagnostic] = e.message
419
448
  { success: false, error: e.message, execution_state: 'not_started' }
@@ -431,7 +460,13 @@ module PWN
431
460
  status = opts.fetch(:status).to_s
432
461
  raise ArgumentError, 'invalid request outcome' unless OUTCOMES.include?(status)
433
462
 
434
- @outcome = { status: status, unmet: Array(opts[:unmet]), at: Time.now.utc.iso8601 }.freeze
463
+ # Only the native report used at this terminal boundary; never replay
464
+ # a report from a discarded candidate, steering segment or checkpoint.
465
+ @submission_report = opts[:verification_report] if @submission_id
466
+ @outcome = { status: status, unmet: Array(opts[:unmet]), at: Time.now.utc.iso8601,
467
+ stage: opts.fetch(:stage, status == 'cancelled' ? 'cancellation' : 'finalization').to_s,
468
+ goal_status: opts.fetch(:goal_status, status).to_s,
469
+ submission_id: @submission_id, request_id: @request_id }.freeze
435
470
  checkpoint!
436
471
  @outcome
437
472
  end
@@ -555,16 +590,71 @@ module PWN
555
590
  end
556
591
  end
557
592
 
558
- def rebuild_contract!
593
+ def skill_path?(path, library)
594
+ path == library || path.start_with?("#{library}/")
595
+ end
596
+
597
+ def skill_destination_kind(path, directory)
598
+ stat = File.lstat(path)
599
+ return :directory if stat.directory?
600
+
601
+ :file if stat.file? && !directory
602
+ rescue Errno::ENOENT
603
+ directory ? :directory : :file
604
+ rescue SystemCallError
605
+ nil
606
+ end
607
+
608
+ # A catalog grant must match the whole operator instruction. The general
609
+ # artifact scanner recognizes mentions as well as destinations.
610
+ def skill_destinations(library)
611
+ return {} unless @amendments.empty? && @request == @original_request && !@original_request.include?("\0")
612
+ return {} unless @original_request.include?(library) || @original_request.include?('~/')
613
+
614
+ text = @original_request.strip
615
+ text = text.delete_suffix('.') unless text.end_with?('/.', '..')
616
+ operands = []
617
+ shape = text.gsub(SKILL_OPERAND) do
618
+ operands << (Regexp.last_match[:quoted] || Regexp.last_match[:bare])
619
+ "\0"
620
+ end
621
+ shape.split(/\s*;\s*|\s+and\s+(?:then\s+)?/i, -1).each_with_object({}) do |clause, destinations|
622
+ literal = operands.shift(clause.count("\0")).last
623
+ next if SKILL_READ.match?(clause)
624
+
625
+ match = SKILL_WRITE.match(clause)
626
+ return {} unless match
627
+ next unless literal.start_with?('/', '~/')
628
+ return {} if literal.split('/').intersect?(%w[. ..]) || literal.include?('//')
629
+
630
+ path = File.expand_path(literal)
631
+ next unless skill_path?(path, library)
632
+
633
+ directory = path == library || literal.end_with?('/') || match[:container] || match[:inside]
634
+ kind = skill_destination_kind(path, directory)
635
+ return {} if !kind || (destinations.key?(path) && destinations[path] != kind)
636
+
637
+ destinations[path] = kind
638
+ end
639
+ end
640
+
641
+ def rebuild_contract!(prior_destinations = nil)
642
+ library = File.expand_path(PWN::Config.pwn_skills_path)
643
+ destinations = skill_destinations(library)
644
+ # A checkpoint can only narrow freshly parsed wording. In particular
645
+ # a missing file that became a directory must not gain a subtree.
646
+ destinations.select! { |path, kind| prior_destinations[path] == kind.to_s } if prior_destinations
647
+ paths = TurnFinalizer.output_paths(request: @request, cwd: @cwd)
648
+ paths.reject! { |path| skill_path?(path, library) && !destinations.key?(path) }
559
649
  @contract = { id: @request_id, request: @request, cwd: @cwd,
560
- required_artifacts: TurnFinalizer.output_paths(request: @request, cwd: @cwd).map(&:freeze).freeze,
650
+ required_artifacts: (paths | destinations.keys).map(&:freeze).freeze, skill_destinations: destinations.freeze,
561
651
  started_at: @started_at }.freeze
562
652
  end
563
653
 
564
654
  def checkpoint!
565
655
  return if @worker_copy
566
656
 
567
- PWN::Plugins::AISandbox.control_directory(path: File.dirname(@checkpoint_path)) do |directory|
657
+ PWN::AI::Sandbox.control_directory(path: File.dirname(@checkpoint_path)) do |directory|
568
658
  path = File.join(directory, File.basename(@checkpoint_path))
569
659
  File.open("#{path}.lock", File::RDWR | File::CREAT | File::NOFOLLOW, 0o600) do |lock|
570
660
  raise IOError, 'checkpoint lock must be a singly linked regular file' unless lock.stat.file? && lock.stat.nlink == 1
@@ -596,7 +686,7 @@ module PWN
596
686
  end
597
687
  data = { version: 1, generation: @generation, session_id: @session_id, request_id: @request_id, original_request: @original_request,
598
688
  request: @request, amendments: @amendments, cwd: @cwd, started_at: @started_at.iso8601(9),
599
- observations: rows, outcome: @outcome, events: @events, effects: @effects, evidence: @evidence,
689
+ observations: rows, outcome: @outcome, events: @events, effects: @effects, evidence: @evidence, skill_destinations: @contract.fetch(:skill_destinations),
600
690
  enabled_toolsets: @enabled_toolsets, verification_contract: @verification_contract }
601
691
  temp = "#{path}.#{SecureRandom.hex(8)}.tmp"
602
692
  File.open(temp, File::WRONLY | File::CREAT | File::EXCL, 0o600) do |file|
@@ -628,6 +718,7 @@ module PWN
628
718
  @observations = data.fetch(:observations).to_h do |path, row|
629
719
  [path.to_s, row.merge(head: Base64.strict_decode64(row[:head]), tail: Base64.strict_decode64(row[:tail]))]
630
720
  end
721
+ data.fetch(:skill_destinations, {}).transform_keys(&:to_s)
631
722
  end
632
723
 
633
724
  def record(event:, data:)
@@ -663,6 +754,8 @@ module PWN
663
754
 
664
755
  # RequestRuntime instances own immutable original_request, ordered amendments,
665
756
  # an effective request, a revision-bound host observation ledger and outcome.
757
+ # contract[:skill_destinations] is a frozen map of explicitly named default
758
+ # catalog paths (expanded absolute String keys) to :file or :directory.
666
759
  # new accepts request:, session_id:, request_id:, artifact_root:, resume:,
667
760
  # profile:, profiles:, window:, tool_cap:, trace:, retrieve:,
668
761
  # enabled_toolsets:, verification_contract:, provider_config:, engine:,