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
@@ -0,0 +1,367 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'digest'
4
+ require 'json'
5
+ require 'securerandom'
6
+
7
+ module PWN
8
+ module AI
9
+ module Agent
10
+ # One private, metadata-only receipt per top-level submission. Neither
11
+ # delivery nor a controller decision is an independent correctness label.
12
+ module Submission
13
+ STATUSES = %w[complete incomplete blocked cancelled verification_error].freeze
14
+ GOALS = (STATUSES + %w[partial awaiting_input]).freeze
15
+ STAGES = %w[admission controller planning provider tool verification clarification cancellation finalization].freeze
16
+ DELIVERIES = %w[displayed not_displayed].freeze
17
+ ID = /\A[0-9a-f]{32}\z/
18
+ DIGEST = /\A[0-9a-f]{64}\z/
19
+ DIGEST_FIELDS = %i[request_key request_digest].freeze
20
+ CATEGORIES = { status: (STATUSES + ['pending']).freeze, goal_status: (GOALS + ['pending']).freeze, stage: STAGES,
21
+ delivery: (DELIVERIES + ['unknown']).freeze, adjudication: %w[pass fail unknown].freeze }.freeze
22
+
23
+ # Misuse of an explicit reservation, as distinct from optional I/O.
24
+ class InvalidClaim < ArgumentError; end
25
+
26
+ # Identity of this invocation, not just its reusable session/request ID.
27
+ # Children share a correlation ID but cannot claim or close the receipt.
28
+ class Scope
29
+ attr_reader :id, :root_id, :role
30
+
31
+ def initialize(opts)
32
+ parent = Thread.current[:pwn_loop_submission_scope]
33
+ nested = parent || opts[:nested] == true || Thread.current[:pwn_swarm_depth].to_i.positive? || TurnFinalizer.user_path? || Thread.current[TurnFinalizer::INLINE_KEY]
34
+ @role = nested ? 'nested' : 'top_level'
35
+ if nested
36
+ runtime = Thread.current[:pwn_request_runtime]
37
+ @root_id = parent&.root_id || Thread.current[:pwn_review_submission_id] || Policy.current_episode&.dig(:submission_id) || (runtime.submission_id if runtime.respond_to?(:submission_id))
38
+ else
39
+ @id = Submission.optional { opts[:submission_id].nil? ? Submission.open!(claimed: true) : Submission.claim!(submission_id: opts[:submission_id]) }
40
+ @root_id = @id
41
+ end
42
+ end
43
+
44
+ def owns?(episode)
45
+ episode && episode[:submission_scope].equal?(self)
46
+ end
47
+
48
+ def notify(callback, row, failure)
49
+ callback&.call(row)
50
+ rescue StandardError, SecurityError
51
+ raise unless failure # An observer is not a replacement for the original request error.
52
+ end
53
+
54
+ def close(runtime, request, interrupted: false)
55
+ row = runtime&.outcome || { status: interrupted ? 'cancelled' : 'blocked', stage: interrupted ? 'cancellation' : 'admission' }
56
+ return row unless id
57
+
58
+ receipt = Submission.optional do
59
+ Submission.close!(submission_id: id, outcome: row, request_key: (Digest::SHA256.hexdigest(runtime.request_id) if runtime),
60
+ request_digest: Digest::SHA256.hexdigest(runtime ? runtime.request : request.to_s))
61
+ end
62
+ if receipt
63
+ checked = Submission.optional do
64
+ report = runtime&.submission_report
65
+ Submission.adjudicate!(submission_id: id, report: report.merge(submission_id: id)) if report
66
+ end
67
+ end
68
+ row.merge(checked || receipt || { submission_id: id })
69
+ end
70
+ end
71
+
72
+ public_class_method def self.open!(opts = {})
73
+ claimed = opts.fetch(:claimed, false)
74
+ raise ArgumentError, 'claimed must be a boolean' unless [true, false].include?(claimed)
75
+
76
+ id = SecureRandom.hex(16)
77
+ edit(id: id, create: true) do
78
+ { submission_id: id, claimed: claimed, status: 'pending', goal_status: 'pending', stage: 'admission', delivery: 'unknown', adjudication: 'unknown' }
79
+ end
80
+ id
81
+ end
82
+
83
+ public_class_method def self.claim!(opts = {})
84
+ id = opts[:submission_id]
85
+ raise InvalidClaim, 'invalid submission identity' unless id.is_a?(String) && ID.match?(id)
86
+
87
+ edit(id: id, claim: true) do |row|
88
+ raise InvalidClaim, 'submission unavailable' if row[:claimed] || row[:status] != 'pending'
89
+
90
+ row.merge(claimed: true)
91
+ end
92
+ id
93
+ end
94
+
95
+ # Parent-only recovery after admission failure or reaping the worker.
96
+ public_class_method def self.abandon!(opts = {})
97
+ status = enum(value: opts[:status], allowed: %w[blocked incomplete cancelled])
98
+ stage = enum(value: opts[:stage], allowed: %w[admission controller cancellation])
99
+ edit(id: opts[:submission_id]) { |row| row[:status] == 'pending' ? row.merge(status: status, goal_status: status, stage: stage) : row }
100
+ end
101
+
102
+ public_class_method def self.close!(opts = {})
103
+ outcome = opts.fetch(:outcome)
104
+ fields = { status: enum(value: outcome[:status], allowed: STATUSES),
105
+ goal_status: enum(value: outcome.fetch(:goal_status, outcome[:status]), allowed: GOALS),
106
+ stage: enum(value: outcome.fetch(:stage, 'controller'), allowed: STAGES) }
107
+ DIGEST_FIELDS.each do |key|
108
+ value = opts[key]
109
+ next if value.nil?
110
+ raise ArgumentError, 'invalid request digest' unless value.is_a?(String) && DIGEST.match?(value)
111
+
112
+ fields[key] = value
113
+ end
114
+ edit(id: opts[:submission_id]) do |row|
115
+ raise ArgumentError, 'submission is not claimed' unless row[:claimed]
116
+ raise ArgumentError, 'submission already closed differently' unless row[:status] == 'pending' || row.slice(*fields.keys) == fields
117
+
118
+ row.merge(fields)
119
+ end
120
+ end
121
+
122
+ public_class_method def self.delivery!(opts = {})
123
+ edit(id: opts[:submission_id]) do |row|
124
+ observe(row: row, key: :delivery, value: enum(value: opts[:delivery], allowed: DELIVERIES))
125
+ end
126
+ end
127
+
128
+ # Trusted host API, not a tool. Never accept a bare verdict or retain
129
+ # the report (which can contain private criteria, paths or answers).
130
+ public_class_method def self.adjudicate!(opts = {})
131
+ edit(id: opts[:submission_id]) do |row|
132
+ raise ArgumentError, 'submission has not closed' if row[:status] == 'pending'
133
+
134
+ verdict = checked_verdict(row: row, report: opts[:report])
135
+ observe(row: row, key: :adjudication, value: verdict)
136
+ end
137
+ end
138
+
139
+ public_class_method def self.stats
140
+ totals = { total: 0, unknown: 0, unreadable: 0, checked_blocks: 0, checked_completions: 0, false_blocks: 0, false_completions: 0,
141
+ false_block_rate: nil, false_completion_rate: nil, by_status: Hash.new(0), by_goal: Hash.new(0), by_delivery: Hash.new(0), by_stage: Hash.new(0) }
142
+ begin
143
+ File.lstat(root)
144
+ rescue Errno::ENOENT
145
+ return totals
146
+ end
147
+
148
+ locked(shared: true) do |directory|
149
+ Dir.each_child(directory) do |name|
150
+ next unless ID.match?(name)
151
+
152
+ totals[:total] += 1
153
+ begin
154
+ tally(row: read(path: File.join(directory, name)), totals: totals)
155
+ rescue IOError, SystemCallError, JSON::ParserError, ArgumentError, KeyError, TypeError
156
+ totals[:unknown] += 1
157
+ totals[:unreadable] += 1
158
+ end
159
+ end
160
+ end
161
+ totals[:false_block_rate] = totals[:false_blocks].fdiv(totals[:checked_blocks]) if totals[:checked_blocks].positive?
162
+ totals[:false_completion_rate] = totals[:false_completions].fdiv(totals[:checked_completions]) if totals[:checked_completions].positive?
163
+ totals
164
+ end
165
+
166
+ # Only wrap optional metadata operations, never request execution,
167
+ # authorization, checkpointing, or calls to an acceptance checker.
168
+ public_class_method def self.optional
169
+ yield
170
+ rescue InvalidClaim
171
+ raise
172
+ rescue StandardError, SecurityError
173
+ nil
174
+ end
175
+
176
+ public_class_method def self.authors
177
+ "AUTHOR(S):\n 0day Inc. <support@0dayinc.com>\n"
178
+ end
179
+
180
+ public_class_method def self.help
181
+ puts "USAGE:
182
+ # Reserve one top-level receipt before admission.
183
+ #{self}.open!(
184
+ claimed: 'optional - true for a Loop that opens its own receipt; false reserves it for a child'
185
+ )
186
+ # Claim a pending parent reservation exactly once.
187
+ #{self}.claim!(
188
+ submission_id: 'required - opaque identity returned by open!'
189
+ )
190
+ # Close a still-pending reservation after admission fails or a worker is reaped.
191
+ #{self}.abandon!(
192
+ submission_id: 'required - identity of the reserved submission',
193
+ status: 'required - blocked, incomplete or cancelled',
194
+ stage: 'required - admission, controller or cancellation'
195
+ )
196
+ # Record the controller decision without storing private request content.
197
+ #{self}.close!(
198
+ submission_id: 'required - claimed submission identity',
199
+ outcome: 'required - terminal status and optional goal_status and stage',
200
+ request_key: 'optional - SHA-256 of the stable runtime request identifier',
201
+ request_digest: 'optional - SHA-256 of the effective request, needed for independent adjudication'
202
+ )
203
+ # Record what the presentation owner actually observed.
204
+ #{self}.delivery!(
205
+ submission_id: 'required - submission whose presentation was observed',
206
+ delivery: 'required - displayed or not_displayed; do not infer this from controller completion'
207
+ )
208
+ # Attach a separately observed native acceptance check to its submission.
209
+ #{self}.adjudicate!(
210
+ submission_id: 'required - identity of the closed submission checked by the host',
211
+ report: 'required - native Verification.run report bound by the host to this submission_id and effective request digest'
212
+ )
213
+ # Count submissions, checked disagreements, and unknown observations.
214
+ #{self}.stats
215
+ # Isolate optional receipt I/O without swallowing an invalid explicit claim.
216
+ #{self}.optional { ... }
217
+ # Display module author information.
218
+ #{self}.authors
219
+ "
220
+ end
221
+
222
+ private_class_method def self.checked_verdict(opts = {})
223
+ row = opts[:row]
224
+ report = opts[:report]
225
+ unless report.is_a?(Hash) && report[:runner_version] == 1 && report[:attribution].is_a?(Hash) && report.dig(:attribution, :source) == 'independent_verifier' &&
226
+ report[:submission_id] == row[:submission_id] && row[:request_digest] && report[:request_digest] == row[:request_digest]
227
+ raise ArgumentError, 'bound native verification report required'
228
+ end
229
+
230
+ requirements = report[:requirements]
231
+ checks = report[:checks]
232
+ unless requirements.is_a?(Array) && !requirements.empty? && requirements.all? { |r| r.is_a?(String) && !r.strip.empty? } &&
233
+ checks.is_a?(Array) && checks.all? { |c| c.is_a?(Hash) && requirements.include?(c[:criterion]) && [true, false, nil].include?(c[:passed]) && !c[:evidence].to_s.empty? }
234
+ raise ArgumentError, 'invalid verification criteria or checks'
235
+ end
236
+
237
+ missing = requirements - checks.map { |c| c[:criterion] }
238
+ verdict = if checks.any? { |c| c[:passed] == false } then 'fail'
239
+ elsif missing.empty? && checks.all? { |c| c[:passed] == true } then 'pass'
240
+ else 'unknown'
241
+ end
242
+ raise ArgumentError, 'inconsistent verification report' unless report[:missing] == missing && report[:status].to_s == verdict
243
+
244
+ verdict
245
+ end
246
+
247
+ private_class_method def self.observe(opts = {})
248
+ row, key, value = opts.values_at(:row, :key, :value)
249
+ raise ArgumentError, "conflicting #{key} acknowledgment" unless ['unknown', value].include?(row.fetch(key))
250
+
251
+ row.merge(key => value)
252
+ end
253
+
254
+ private_class_method def self.tally(opts = {})
255
+ row = opts[:row]
256
+ totals = opts[:totals]
257
+ totals[:by_status][row[:status]] += 1
258
+ totals[:by_goal][row[:goal_status]] += 1
259
+ totals[:by_stage][row[:stage]] += 1
260
+ totals[:by_delivery][row[:delivery]] += 1
261
+ if row[:adjudication] == 'unknown'
262
+ totals[:unknown] += 1
263
+ elsif row[:status] == 'blocked'
264
+ totals[:checked_blocks] += 1
265
+ totals[:false_blocks] += 1 if row[:adjudication] == 'pass'
266
+ elsif row[:goal_status] == 'complete'
267
+ totals[:checked_completions] += 1
268
+ totals[:false_completions] += 1 if row[:adjudication] == 'fail'
269
+ end
270
+ end
271
+
272
+ private_class_method def self.enum(opts = {})
273
+ value = opts[:value].to_s
274
+ raise ArgumentError, 'invalid submission metadata' unless opts[:allowed].include?(value)
275
+
276
+ value
277
+ end
278
+
279
+ private_class_method def self.root
280
+ File.join(PWN::Sessions.sessions_dir(read_only: true), 'support', 'submissions')
281
+ end
282
+
283
+ private_class_method def self.locked(opts = {})
284
+ shared = opts[:shared]
285
+ PWN::AI::Sandbox.control_directory(path: root) do |directory|
286
+ stat = File.stat(directory)
287
+ raise IOError, 'unsafe submission directory' unless stat.owned? && stat.mode.nobits?(0o077)
288
+
289
+ flags = shared ? File::RDONLY : File::RDWR | File::CREAT
290
+ File.open(File.join(directory, '.lock'), flags | File::NOFOLLOW | File::NONBLOCK, 0o600) do |lock|
291
+ private_file!(stat: lock.stat)
292
+ # A stalled reader/writer must never stall ordinary admission.
293
+ mode = (shared ? File::LOCK_SH : File::LOCK_EX) | File::LOCK_NB
294
+ deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 0.25
295
+ until lock.flock(mode)
296
+ raise IOError, 'submission index busy' if Process.clock_gettime(Process::CLOCK_MONOTONIC) >= deadline
297
+
298
+ sleep 0.005
299
+ end
300
+ yield directory
301
+ end
302
+ end
303
+ end
304
+
305
+ private_class_method def self.private_file!(opts = {})
306
+ stat = opts[:stat]
307
+ raise IOError, 'unsafe submission file' unless stat.file? && stat.nlink == 1 && stat.owned? && stat.mode.nobits?(0o077)
308
+ end
309
+
310
+ private_class_method def self.valid_row?(opts = {})
311
+ row = opts[:row]
312
+ row.is_a?(Hash) && row[:submission_id] == opts[:id] && [true, false].include?(row[:claimed]) &&
313
+ (row.keys - CATEGORIES.keys - DIGEST_FIELDS - %i[submission_id claimed]).empty? &&
314
+ CATEGORIES.all? { |key, values| values.include?(row[key]) } &&
315
+ DIGEST_FIELDS.all? { |key| row[key].nil? || (row[key].is_a?(String) && DIGEST.match?(row[key])) }
316
+ end
317
+
318
+ private_class_method def self.read(opts = {})
319
+ path = opts[:path]
320
+ File.open(path, File::RDONLY | File::NOFOLLOW | File::NONBLOCK) do |file|
321
+ private_file!(stat: file.stat)
322
+ data = file.read(1025)
323
+ raise IOError, 'invalid submission receipt' unless data && data.bytesize <= 1024
324
+
325
+ row = JSON.parse(data, symbolize_names: true)
326
+ raise IOError, 'invalid submission metadata' unless valid_row?(row: row, id: File.basename(path))
327
+
328
+ row
329
+ end
330
+ end
331
+
332
+ private_class_method def self.edit(opts = {})
333
+ id = opts[:id]
334
+ raise ArgumentError, 'invalid submission identity' unless id.is_a?(String) && ID.match?(id)
335
+
336
+ locked do |directory|
337
+ path = File.join(directory, id)
338
+ raise IOError, 'submission identity collision' if opts[:create] && (File.exist?(path) || File.symlink?(path))
339
+
340
+ begin
341
+ old = read(path: path) unless opts[:create]
342
+ rescue Errno::ENOENT
343
+ raise InvalidClaim, 'submission unavailable' if opts[:claim]
344
+
345
+ raise
346
+ end
347
+ row = yield old
348
+ next row if old == row
349
+
350
+ temp = "#{path}.#{SecureRandom.hex(8)}.tmp"
351
+ owned = false
352
+ File.open(temp, File::WRONLY | File::CREAT | File::EXCL, 0o600) do |file|
353
+ owned = true
354
+ file.write(JSON.generate(row))
355
+ file.fsync
356
+ end
357
+ File.rename(temp, path)
358
+ owned = false
359
+ row
360
+ ensure
361
+ File.unlink(temp) if owned
362
+ end
363
+ end
364
+ end
365
+ end
366
+ end
367
+ end
@@ -89,7 +89,7 @@ module PWN
89
89
  # )
90
90
 
91
91
  public_class_method def self.spawn(opts = {})
92
- return PWN::Plugins::AISandbox.swarm_control(operation: 'spawn', args: opts) if Thread.current[:pwn_swarm_controller]
92
+ return PWN::AI::Sandbox.swarm_control(operation: 'spawn', args: opts) if Thread.current[:pwn_swarm_controller]
93
93
 
94
94
  name = opts[:name].to_s
95
95
  raise ArgumentError, 'name is required' if name.strip.empty?
@@ -245,7 +245,7 @@ module PWN
245
245
  empty_tools = false
246
246
  prior_id = Thread.current[:pwn_swarm_id]
247
247
  prior_honesty = Thread.current[:pwn_swarm_honesty]
248
- return PWN::Plugins::AISandbox.swarm_control(operation: 'ask', args: opts) if Thread.current[:pwn_swarm_controller]
248
+ return PWN::AI::Sandbox.swarm_control(operation: 'ask', args: opts) if Thread.current[:pwn_swarm_controller]
249
249
 
250
250
  sid = opts[:swarm_id] || create(topic: opts[:request].to_s[0, 60])[:swarm_id]
251
251
  persona = opts[:persona] || personas(swarm_id: sid)[name.to_sym]
@@ -175,7 +175,7 @@ module PWN
175
175
  tool = opts[:tool].to_s
176
176
  args = opts[:args] || {}
177
177
  payload = args['command'] || args[:command] || args['code'] || args[:code] || JSON.generate(args)
178
- kind = PWN::Plugins::AISandbox.classify(payload: payload, side_effect: opts[:side_effect])
178
+ kind = PWN::AI::Sandbox.classify(payload: payload, side_effect: opts[:side_effect])
179
179
  case kind.to_s
180
180
  when 'write' then 'destructive'
181
181
  when 'network' then 'active_scan'
@@ -336,7 +336,9 @@ module PWN
336
336
  end
337
337
  end
338
338
 
339
- tasks = normalize_task_list(tasks: tasks, goal: goal)
339
+ # The operator already supplied a list. Do not shorten it to a how-to
340
+ # or pad it with a reporting step from the generated-plan template.
341
+ tasks = source == :enumerated ? tasks.first(MAX_PLAN_TASKS) : normalize_task_list(tasks: tasks, goal: goal)
340
342
  if opts[:state].is_a?(Hash)
341
343
  opts[:state][:plan] = tasks
342
344
  opts[:state][:original_request] = goal if opts[:state][:original_request].to_s.empty?
@@ -458,20 +460,52 @@ module PWN
458
460
  end
459
461
  end
460
462
  if chunks.length < MIN_PLAN_TASKS
461
- # Inline: "1. do X 2. do Y 3. do Z"
462
- inline = goal.scan(/(?:^|\s)\d+[.):]\s+([^\d]+?)(?=(?:\s+\d+[.):]\s+)|$)/)
463
- chunks = inline.flatten.map(&:strip) if inline.length >= MIN_PLAN_TASKS
464
- end
465
- if chunks.length < MIN_PLAN_TASKS
466
- # Numbered improvement list like "1. the task ... 2. once a request"
467
- inline = goal.split(/(?=(?:^|\s)\d+\.\s+)/).map(&:strip).reject(&:empty?)
468
- chunks = inline.map { |c| c.sub(/\A\d+\.\s+/, '') }.reject(&:empty?) if inline.length >= MIN_PLAN_TASKS
463
+ inline = inline_numbered_steps(text: goal, keep_lead: true)
464
+ chunks = inline if inline.length >= MIN_PLAN_TASKS
469
465
  end
470
466
  reject_scaffold_tasks(tasks: chunks)
471
467
  rescue StandardError
472
468
  []
473
469
  end
474
470
 
471
+ # Split at successive list markers, not at digits in the operands.
472
+ # A lead before 1 is context; a lead followed by 2, 3 is the missing
473
+ # first item. Keep its words rather than inventing a corrected step.
474
+ private_class_method def self.inline_numbered_steps(opts = {})
475
+ text = opts.fetch(:text)
476
+ markers = []
477
+ previous_start = 0
478
+ last_clear = false
479
+ text.scan(/(?<!\S)(\d+)([.):])(?=[ \t]+\S)/) do |number, separator|
480
+ mark = Regexp.last_match
481
+ before = text[previous_start...mark.begin(0)]
482
+ at_start = previous_start.zero? && before.strip.empty?
483
+ previous_start = mark.begin(0)
484
+ clear = at_start || separator != '.' || before.match?(/[.!?;:]\s*\z|\n[ \t]*\z/)
485
+ last = markers.last
486
+ if last.nil?
487
+ next unless at_start || (clear && %w[1 2].include?(number))
488
+ elsif number == last[1]
489
+ # A sentence-ending operand can resemble the next ordinal. If
490
+ # the actual marker follows it, leave the operand in its item.
491
+ next if last_clear || !clear
492
+
493
+ markers.pop
494
+ elsif number != last[1].succ
495
+ next
496
+ end
497
+ markers << mark
498
+ last_clear = clear
499
+ end
500
+ return [] if markers.empty?
501
+
502
+ steps = markers.each_cons(2).map { |a, b| text[a.end(0)...b.begin(0)].strip }
503
+ steps << text[markers.last.end(0)..].strip
504
+ lead = text[0...markers.first.begin(0)].strip
505
+ steps.unshift(lead) if opts[:keep_lead] && markers.first[1] == '2' && !lead.empty?
506
+ steps
507
+ end
508
+
475
509
  # ------------------------------------------------------------------
476
510
  # LLM-backed decomposition for arbitrary requests.
477
511
  # ------------------------------------------------------------------
@@ -653,8 +687,8 @@ module PWN
653
687
  tasks = []
654
688
 
655
689
  # If the operator already spelled improvement bullets, surface them.
656
- bullets = goal_text.scan(/(?:^|\s)(?:\d+\.|[-*])\s*([^.;]+)/).flatten.map(&:strip)
657
- bullets = reject_scaffold_tasks(tasks: bullets)
690
+ bullets = extract_enumerated_steps(goal: goal_text)
691
+ bullets = reject_scaffold_tasks(tasks: goal_text.scan(/(?:^|\s)[-*]\s*([^.;]+)/).flatten) if bullets.length < MIN_PLAN_TASKS
658
692
  if bullets.length >= MIN_PLAN_TASKS
659
693
  bullets.first(8).each { |b| tasks << b.sub(/\Athe\s+/i, '').sub(/\.\s*\z/, '') }
660
694
  return tasks
@@ -1233,8 +1267,8 @@ module PWN
1233
1267
  tasks << item unless item.empty?
1234
1268
  end
1235
1269
  if tasks.length < MIN_PLAN_TASKS
1236
- inline = text.scan(/(?:^|\s)\d+[.):]\s+([^\d]+?)(?=(?:\s+\d+[.):]\s+)|$)/)
1237
- tasks = inline.flatten.map { |t| t.to_s.gsub(/\s+/, ' ').strip }.reject(&:empty?) if inline.length >= MIN_PLAN_TASKS
1270
+ inline = text.lines.flat_map { |line| inline_numbered_steps(text: line.strip) }
1271
+ tasks = inline if inline.length >= MIN_PLAN_TASKS
1238
1272
  end
1239
1273
  tasks = tasks.map { |t| t.to_s.gsub(/\s+/, ' ').strip }.reject(&:empty?).uniq
1240
1274
  tasks.first(MAX_PLAN_TASKS)
@@ -10,11 +10,11 @@ PWN::AI::Agent::Registry.register(
10
10
  toolset: 'memory',
11
11
  schema: {
12
12
  name: 'memory_remember',
13
- description: 'Save a durable fact, preference, or lesson to persistent ' \
14
- 'memory (~/.pwn/memory.json). Re-injected into the system ' \
15
- 'prompt of every future pwn-ai session.',
13
+ description: 'Propose a durable fact, preference, or lesson for future sessions. ' \
14
+ 'The interactive operator reviews the exact entry before it is saved. Never include credentials.',
16
15
  parameters: {
17
16
  type: 'object',
17
+ additionalProperties: false,
18
18
  properties: {
19
19
  key: { type: 'string', description: 'Short unique identifier for this memory.' },
20
20
  value: { type: 'string', description: 'The fact / preference / lesson to remember.' },
@@ -24,14 +24,9 @@ PWN::AI::Agent::Registry.register(
24
24
  }
25
25
  },
26
26
  check: -> { defined?(PWN::Memory) },
27
- handler: lambda { |args|
28
- PWN::Memory.remember(
29
- key: args[:key].to_s.to_sym,
30
- value: args[:value],
31
- category: (args[:category] || 'fact').to_sym
32
- )
33
- { saved: true, key: args[:key], total: PWN::Memory.load.keys.length }
34
- }
27
+ # Dispatch owns the reviewed transaction. Never grant an isolated registry
28
+ # handler direct access to the cross-session prompt store.
29
+ handler: ->(_args) { { success: false, saved: false, execution_state: 'not_started', error: 'Memory save requires operator review.' } }
35
30
  )
36
31
 
37
32
  PWN::AI::Agent::Registry.register(
@@ -71,7 +71,7 @@ PWN::AI::Agent::Registry.register(
71
71
 
72
72
  timeout = PWN::AI::Agent::ToolGuard.deadline_s(timeout: args[:timeout], kind: :eval, payload: code)
73
73
  PWN::AI::Agent::ToolGuard.protect_http!
74
- sandboxed = PWN::Plugins::AISandbox.wrap_ruby(code: code, timeout: timeout)
74
+ sandboxed = PWN::AI::Sandbox.wrap_ruby(code: code, timeout: timeout)
75
75
  return sandboxed unless sandboxed.nil?
76
76
 
77
77
  blocked = PWN::Plugins::MethodCatalog.guard_eval(code: code)
@@ -93,7 +93,7 @@ PWN::AI::Agent::Registry.register(
93
93
  scoped = PWN::AI::Agent::ToolGuard.scope_refusal(command: cmd)
94
94
  return scoped if scoped
95
95
 
96
- sandboxed = PWN::Plugins::AISandbox.wrap_shell(command: cmd, timeout: timeout)
96
+ sandboxed = PWN::AI::Sandbox.wrap_shell(command: cmd, timeout: timeout)
97
97
  return sandboxed unless sandboxed.nil?
98
98
 
99
99
  return PWN::Plugins::Jobs.start(command: cmd, max_runtime: args[:max_runtime], session_id: Thread.current[:pwn_session_id]).merge(routed: 'job_run') if args[:background] == true || (args[:timeout].to_i <= 0 && PWN::AI::Agent::ToolGuard.auto_job?(payload: cmd))
@@ -4,13 +4,13 @@ require 'fileutils'
4
4
  require 'pwn/ai/agent/registry'
5
5
 
6
6
  # Thin wrappers around the PWN::Skills store so the model can list / read /
7
- # write reusable procedures. PromptBuilder injects the index (name +
8
- # description); skill_view loads the full body on demand — the two-tier
7
+ # write reusable procedures. PromptBuilder summarizes the catalog;
8
+ # skill_view returns the full body on demand — the two-tier
9
9
  # progressive-disclosure pattern from https://agentskills.io/specification.
10
10
  #
11
11
  # On disk (spec-conformant, written by PWN::Config.write_skill):
12
12
  # ~/.pwn/skills/<name>/SKILL.md ← YAML frontmatter (name, description, …)
13
- # ~/.pwn/skills/<name>/scripts/ ← optional executable helpers
13
+ # ~/.pwn/skills/<name>/scripts/ ← optional files; not loaded as code
14
14
  # ~/.pwn/skills/<name>/references/ ← optional supporting docs
15
15
  #
16
16
  # Legacy flat ~/.pwn/skills/<name>.md files are still LOADED (format:
@@ -200,7 +200,7 @@ PWN::AI::Agent::Registry.register(
200
200
  name: 'skill_create',
201
201
  description: 'Save a new reusable skill to ~/.pwn/skills/<name>/SKILL.md ' \
202
202
  '(agentskills.io format: required name + description YAML ' \
203
- 'frontmatter). Appears in every future pwn-ai system prompt. ' \
203
+ 'frontmatter). Available for lookup in future sessions. ' \
204
204
  'Optionally attach references (URLs, CWE/CVE ids, MITRE ' \
205
205
  'ATT&CK, NIST 800-53, docs) and an allowed-tools allowlist.',
206
206
  parameters: {
@@ -347,7 +347,7 @@ PWN::AI::Agent::Registry.register(
347
347
  description: 'Delete a skill from ~/.pwn/skills/ by name. Removes the ' \
348
348
  'entire <name>/ directory (agentskills format) or the flat ' \
349
349
  'file (legacy). Use to prune low-quality auto-distilled ' \
350
- 'skills so they stop appearing in every future system prompt. ' \
350
+ 'skills from the catalog. ' \
351
351
  'Irreversible.',
352
352
  parameters: {
353
353
  type: 'object',