pwn 0.5.804 → 0.5.805

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 4e61218b09e4d32bf5d481b3d4786acd8876e1a125af191b3b6eb767f63a6a23
4
- data.tar.gz: dd662b30064a1ed70bf7abb444f2f76d0e67a913ccc56bd220782dd54806032b
3
+ metadata.gz: 4c49ea1e0a11b6e4a590478793cccfcded7c6bc35e6c350aea35d4d70105068b
4
+ data.tar.gz: 5728257760ae7f42005b438f2cfcb164c9fb1da71e1653d6d283f6dbd37a4d66
5
5
  SHA512:
6
- metadata.gz: b747be32f0773d25e0d46cf6428dd75ddd3811c5b0d6bad5a671d89b900c4c3c79eb9b44dd1a52734fdacaddb5dd983d426a02f9265ddf980d0ea3ee619c935f
7
- data.tar.gz: c790fee5e8820c0e78dc9541f10a6ed8cc43ba87333e70f2b485bd8c64f011f697211cf03f2fe5deab846a985ad3a444c0db9c0ed2256221c8c5366ebd9eb1ef
6
+ metadata.gz: ab00b67b6f6e1f8dd1961e1656fd96fd0617589e2234244918e0e30141b773100e115296b74ca7aaf67d956feaf298bd6fd53a8498fff9c39601d53342cc3397
7
+ data.tar.gz: 28e0c26e8e1755f1e205783bb82940cbc19cc9fdec9b467dc3b51990a358185446a7dcd0be00d61cc211e09851f945a0805a43ed210bfe74a0959721e9f38496
data/Gemfile CHANGED
@@ -45,7 +45,7 @@ gem 'js-beautify', '0.1.8'
45
45
  gem 'json', '>=2.13.2'
46
46
  gem 'jsonpath', '1.1.5'
47
47
  gem 'json_schemer', '2.5.0'
48
- gem 'jwt', '3.3.0'
48
+ gem 'jwt', '3.3.1'
49
49
  gem 'libusb', '0.8.0'
50
50
  gem 'luhn', '3.0.0'
51
51
  gem 'mail', '2.9.1'
@@ -169,6 +169,13 @@ when deciding which side of the loop to exercise.
169
169
 
170
170
  ### Memory (`memory_remember`, `memory_recall`, `memory_forget`, `memory_clear`)
171
171
 
172
+ In the interactive pwn-ai console, `memory_remember` shows the proposed key,
173
+ category, and value. Use the approval or decline command shown with that entry.
174
+ Approval applies to one save, not the session. pwn-ai reports success only after
175
+ reading the saved entry back. Without interactive review, the tool does not
176
+ write; an operator can use `/memory remember KEY VALUE` directly. An older
177
+ save with an unknown outcome is not automatically retried.
178
+
172
179
  - "Remember that our preferred AI engine for long recon chains is `grok`."
173
180
  - "What do we already know about OpenSSH 8.2p1 from prior sessions?"
174
181
  - "Forget the stale fact about the old HackRF serial - it was replaced."
@@ -72,7 +72,8 @@ module PWN
72
72
  violation = JSONSchemer.schema(JSON.parse(JSON.generate(type_schema))).validate(JSON.parse(JSON.generate(args))).first
73
73
  return schema_denial(violation.transform_keys(&:to_sym)) if violation
74
74
 
75
- if defined?(PWN::Plugins::Vault)
75
+ reviewed_memory = entry.name == 'memory_remember'
76
+ if !reviewed_memory && defined?(PWN::Plugins::Vault)
76
77
  begin
77
78
  args = expand_vault_args(args: args)
78
79
  rescue StandardError
@@ -128,6 +129,13 @@ module PWN
128
129
  budget = prepare_budget(opts.merge(entry: entry, args: args))
129
130
  return JSON.generate(budget[:denial]) if budget && budget[:denial]
130
131
 
132
+ # Controller receipts contain no entry contents or external tool output.
133
+ # Reporting a reviewed save must not require opening an operator vault.
134
+ if reviewed_memory
135
+ receipt = review_memory_save(runtime: owner, args: args, action_id: tool_call[:id] || tool_call['id'])
136
+ return JSON.generate(success: receipt[:saved] == true, effect: 'store', result: receipt)
137
+ end
138
+
131
139
  started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
132
140
  begin
133
141
  runtime = Thread.current[:pwn_request_runtime]
@@ -213,6 +221,51 @@ module PWN
213
221
  nil
214
222
  end
215
223
 
224
+ # This one fixed operation uses the controller's writer. Neither a
225
+ # registry handler nor caller-selected paths execute on the controller.
226
+ private_class_method def self.review_memory_save(opts = {})
227
+ runtime = opts[:runtime]
228
+ no_write = { success: false, saved: false, execution_state: 'not_started' }
229
+ return { success: false, error: 'uncertain_side_effect', hint: 'An earlier memory save is unresolved; no new save was attempted.' } if runtime && runtime.blocking_effects.any? { |row| row[:tool] == 'memory_remember' }
230
+
231
+ review = Thread.current[:pwn_review_memory]
232
+ return no_write.merge(error: 'Memory was not saved. Use /memory remember KEY VALUE or review the proposed save in the interactive console.') unless runtime && review && !Thread.current[:pwn_repository_worker]
233
+
234
+ args = opts.fetch(:args)
235
+ fields = { category: 'fact' }.merge(args)
236
+ key, value, category = fields.values_at(:key, :value, :category)
237
+ valid = (fields.keys - %i[key value category]).empty? && %w[fact preference lesson env].include?(category) &&
238
+ key.is_a?(String) && key.bytesize <= 128 && !key.strip.empty? &&
239
+ value.is_a?(String) && value.bytesize <= PWN::Memory::VALUE_MAX_CHARS && !value.strip.empty?
240
+ return no_write.merge(error: 'Invalid memory fields. Supply only a short key, a text value and an optional category.') unless valid
241
+ return no_write.merge(error: 'Cannot save a credential or vault reference to prompt memory.') if fields.values.any? { |text| text.include?('{{vault:') } || PWN::Redaction.redact(value: { key => value }) != { key => value }
242
+
243
+ fields = fields.transform_values { |text| text.dup.freeze }.freeze
244
+ return no_write.merge(error: 'Memory save not approved; nothing was saved.') unless review.call(fields).equal?(true)
245
+
246
+ runtime.execute_tool(name: 'memory_remember', args: args, action_id: opts[:action_id], effect: :store, reviewed_memory: true) { save_reviewed_memory(fields) }
247
+ rescue StandardError => e
248
+ { success: false, error: "Memory save did not return a verified receipt (#{e.class})." }
249
+ end
250
+
251
+ private_class_method def self.save_reviewed_memory(opts = {})
252
+ admitted = false
253
+ PWN::Memory.transaction do
254
+ admitted = true
255
+ PWN::Memory.remember(**opts)
256
+ stored = PWN::Memory.load
257
+ row = stored.fetch(opts.fetch(:key).to_sym)
258
+ raise IOError, 'memory save could not be verified' unless row[:value] == opts[:value] && row[:category].to_s == opts[:category]
259
+
260
+ { saved: true }
261
+ end
262
+ rescue SystemCallError => e
263
+ # Once inside the transaction even EACCES could be after rename.
264
+ raise if admitted
265
+
266
+ raise RequestRuntime::MemoryWriteNotStarted, "Memory writer unavailable (#{e.class}); nothing was saved."
267
+ end
268
+
216
269
  private_class_method def self.schema_denial(opts = {})
217
270
  pointer = opts[:data_pointer].to_s
218
271
  message = opts[:error].to_s
@@ -3181,7 +3181,7 @@ module PWN
3181
3181
 
3182
3182
  private_class_method def self.engine_failure_text(opts = {})
3183
3183
  attempts = opts[:runtime]&.last_provider_attempts || opts[:attempts]
3184
- "[pwn-ai] engine hop failed after #{attempts} tries: #{opts[:error].message.to_s[0, 240]}"
3184
+ "[pwn-ai] engine hop failed after #{attempts} tries: #{opts[:error].message}"
3185
3185
  end
3186
3186
 
3187
3187
  private_class_method def self.engine_retry_exhausted?(opts = {})
@@ -3305,7 +3305,7 @@ module PWN
3305
3305
  final_chars = 0
3306
3306
  start_debug_session(opts)
3307
3307
  loud_debug_tui!(debug: opts[:debug])
3308
- debug_progress(msg: "Loop.run start request=#{request[0, 240]}", debug: opts[:debug])
3308
+ debug_progress(msg: "Loop.run start request=#{request}", debug: opts[:debug])
3309
3309
  ToolGuard.reset_timeout_budget! if defined?(ToolGuard) && ToolGuard.respond_to?(:reset_timeout_budget!)
3310
3310
  nested = opts[:nested] == true || Thread.current[:pwn_swarm_depth].to_i.positive? || (defined?(TurnFinalizer) && TurnFinalizer.user_path?)
3311
3311
  TurnFinalizer.enter_user_path! if defined?(TurnFinalizer)
@@ -3560,7 +3560,7 @@ module PWN
3560
3560
  rescue StandardError => e
3561
3561
  if engine_transient?(error: e)
3562
3562
  engine_blips += 1
3563
- debug_progress(msg: "engine hop failed #{e.class}: #{e.message.to_s[0, 240]} blip=#{engine_blips}")
3563
+ debug_progress(msg: "engine hop failed #{e.class}: #{e.message} blip=#{engine_blips}")
3564
3564
  if engine_retry_exhausted?(runtime: runtime, attempts: engine_blips)
3565
3565
  txt = engine_failure_text(runtime: runtime, attempts: engine_blips, error: e)
3566
3566
  debug_final_text!(text: txt)
@@ -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
@@ -92,7 +114,7 @@ module PWN
92
114
  checked(native('unshare', [Fiddle::TYPE_INT]).call(0x20000000), 'unshare PID namespace') if pid_namespace
93
115
  reader, writer = IO.pipe
94
116
  armed, arm = IO.pipe
95
- init = fork do
117
+ init = fork_mission do
96
118
  armed.close
97
119
  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
120
  arm.write('1')
@@ -192,7 +214,7 @@ module PWN
192
214
  if operation
193
215
  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
216
 
195
- @pid = fork do
217
+ @pid = self.class.fork_mission do
196
218
  Thread.handle_interrupt(Exception => :immediate) { operation.call }
197
219
  ensure
198
220
  exit!
@@ -320,7 +342,7 @@ module PWN
320
342
  ready, announce = IO.pipe
321
343
  release, gate = IO.pipe
322
344
  owner = Process.pid
323
- @pid = fork do
345
+ @pid = self.class.fork_mission do
324
346
  ready.close
325
347
  gate.close
326
348
  begin
@@ -328,7 +350,7 @@ module PWN
328
350
  exit! unless Process.ppid == owner
329
351
  self.class.checked(self.class.native('unshare', [Fiddle::TYPE_INT]).call(0x20000000), 'unshare PID namespace')
330
352
  armed, arm = IO.pipe
331
- init = fork do
353
+ init = self.class.fork_mission do
332
354
  armed.close
333
355
  announce.close
334
356
  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')
@@ -16,6 +16,8 @@ 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
22
  attr_reader :original_request, :request, :session_id, :request_id, :contract, :amendments, :outcome, :checkpoint_path, :engine, :last_provider_attempts
21
23
 
@@ -413,6 +415,11 @@ module PWN
413
415
  'failed'
414
416
  end
415
417
  result
418
+ rescue MemoryWriteNotStarted => e
419
+ raise unless opts[:reviewed_memory] && opts[:name] == 'memory_remember'
420
+
421
+ state = 'failed'
422
+ { success: false, error: e.message, saved: false, execution_state: 'not_started' }
416
423
  rescue PWN::Plugins::AISandbox::NotStarted => e
417
424
  state = 'rejected'
418
425
  action[:diagnostic] = e.message
@@ -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(
data/lib/pwn/memory.rb CHANGED
@@ -2,6 +2,7 @@
2
2
 
3
3
  require 'json'
4
4
  require 'fileutils'
5
+ require 'securerandom'
5
6
  require 'time'
6
7
 
7
8
  module PWN
@@ -93,17 +94,21 @@ module PWN
93
94
  private_class_method def self.atomic_write(opts = {})
94
95
  path = opts[:path]
95
96
  body = opts[:body]
96
- tmp = File.join(File.dirname(path), ".#{File.basename(path)}.#{Process.pid}.tmp")
97
- File.open(tmp, File::WRONLY | File::CREAT | File::TRUNC, 0o644) do |f|
97
+ dir = File.dirname(path)
98
+ tmp = File.join(dir, ".#{File.basename(path)}.#{SecureRandom.hex(16)}.tmp")
99
+ owned_tmp = nil # Never remove a candidate that we failed to create.
100
+ File.open(tmp, File::WRONLY | File::CREAT | File::EXCL | File::NOFOLLOW, 0o600) do |f|
101
+ owned_tmp = tmp
98
102
  f.flock(File::LOCK_EX)
99
103
  f.write(body)
100
104
  f.flush
101
105
  f.fsync
102
106
  end
103
107
  File.rename(tmp, path)
104
- File.open(File.dirname(path), File::RDONLY, &:fsync)
108
+ owned_tmp = nil
109
+ File.open(dir, File::RDONLY, &:fsync)
105
110
  ensure
106
- FileUtils.rm_f(tmp) if defined?(tmp) && tmp && File.exist?(tmp)
111
+ FileUtils.rm_f(owned_tmp) if owned_tmp
107
112
  end
108
113
 
109
114
  # Best-effort re-read used by the empty-overwrite guard (no raise).
@@ -7,6 +7,7 @@ require 'fcntl'
7
7
  require 'digest'
8
8
  require 'fileutils'
9
9
  require 'json'
10
+ require 'socket'
10
11
  require 'tmpdir'
11
12
  require 'tempfile'
12
13
  require 'yaml'
@@ -19,6 +20,8 @@ module PWN
19
20
  module REPL
20
21
  # Single-owner fullscreen console: wrapped completion and private /vault edit; Ctrl+S saves encrypted, Esc cancels.
21
22
  module AIConsole
23
+ MEMORY_DECISION = %r{\A[[:space:]]*/memory[[:space:]]+(?:approve|decline)\b}
24
+
22
25
  public_class_method def self.run(opts = {})
23
26
  input = opts[:input] || $stdin
24
27
  output = opts[:output] || $stdout
@@ -386,7 +389,7 @@ module PWN
386
389
 
387
390
  def preload(lines)
388
391
  Array(lines).each do |line|
389
- next if line.to_s.strip.empty? || line.match?(%r{\A\s*/input(?:\s|\z)}) || @history.last == line
392
+ next if line.to_s.strip.empty? || line.match?(%r{\A\s*/input(?:\s|\z)}) || line.match?(MEMORY_DECISION) || @history.last == line
390
393
 
391
394
  @history << line.dup
392
395
  end
@@ -457,7 +460,7 @@ module PWN
457
460
 
458
461
  def submit
459
462
  line = @text.dup
460
- @history << line.dup unless line.strip.empty? || @history.last == line || line.match?(%r{\A\s*/input(?:\s|\z)})
463
+ @history << line.dup unless line.strip.empty? || @history.last == line || line.match?(%r{\A\s*/input(?:\s|\z)}) || line.match?(MEMORY_DECISION)
461
464
  @index = @history.length
462
465
  replace('')
463
466
  line
@@ -481,7 +484,62 @@ module PWN
481
484
  end
482
485
  end
483
486
 
484
- # Parent-side steering endpoint; cancellation belongs to the process owner.
487
+ # Child-side rendezvous for one exact memory_remember call, never tool stdin.
488
+ class MemoryReview
489
+ WAIT_SECONDS = 180
490
+
491
+ def initialize(events, generation)
492
+ @events = events
493
+ @generation = generation
494
+ @lock = Mutex.new
495
+ end
496
+
497
+ def call(fields)
498
+ return false unless fields.is_a?(Hash) && fields.size == 3 && %i[key value category].all? { |key| fields[key].is_a?(String) }
499
+ return false unless PWN::Redaction.redact(value: fields) == fields
500
+
501
+ # No indentation: wrap_command must not insert spaces into a continued value.
502
+ display = JSON.pretty_generate(fields, ascii_only: true, indent: '').gsub("\x7f", '\\u007f')
503
+ return false unless PWN::Redaction.redact(value: display) == display
504
+
505
+ ticket = SecureRandom.hex(8)
506
+ reply = Queue.new
507
+ @lock.synchronize do
508
+ return false if @closed || @reply
509
+
510
+ @ticket = ticket
511
+ @reply = reply
512
+ end
513
+ begin
514
+ @events << [:memory_review, { ticket: ticket, display: display }]
515
+ approved = reply.pop(timeout: WAIT_SECONDS) == true
516
+ @events << [:memory_review_closed, ticket]
517
+ approved
518
+ ensure
519
+ @lock.synchronize { @reply = @ticket = nil }
520
+ end
521
+ rescue IOError, SystemCallError, JSON::GeneratorError, ArgumentError
522
+ false
523
+ end
524
+
525
+ def decide(frame)
526
+ @lock.synchronize do
527
+ return unless @reply && !@reply.closed? && frame[:type] == 'memory_decision' && frame[:generation] == @generation && frame[:ticket] == @ticket && %w[approve decline].include?(frame[:decision])
528
+
529
+ @reply << (frame[:decision] == 'approve')
530
+ @reply.close
531
+ end
532
+ end
533
+
534
+ def close
535
+ @lock.synchronize do
536
+ @closed = true
537
+ @reply&.close
538
+ end
539
+ end
540
+ end
541
+
542
+ # Parent-side control endpoint; cancellation belongs to the process owner.
485
543
  class MissionControl
486
544
  def initialize(io)
487
545
  @io = io
@@ -492,6 +550,20 @@ module PWN
492
550
  @io.flush
493
551
  end
494
552
 
553
+ def memory_decision(generation, ticket, decision)
554
+ frame = "#{JSON.generate(type: 'memory_decision', generation: generation, ticket: ticket, decision: decision)}\n"
555
+ return if @io.write_nonblock(frame, exception: false) == frame.bytesize
556
+
557
+ close
558
+ raise IOError, 'Incomplete memory decision'
559
+ end
560
+
561
+ def close
562
+ @io.shutdown(Socket::SHUT_WR) unless @io.closed?
563
+ ensure
564
+ @io.close unless @io.closed?
565
+ end
566
+
495
567
  def phase
496
568
  'mission process'
497
569
  end
@@ -657,6 +729,15 @@ module PWN
657
729
  next if generation && generation != @mission_generation && generation != @swarm_generation
658
730
 
659
731
  case type
732
+ when :memory_review, :memory_review_closed
733
+ next unless generation && generation == @mission_generation && @running && !@command && !@cancelling && !@leaving
734
+
735
+ if type == :memory_review
736
+ present_memory_review(text, generation)
737
+ elsif @memory_review == [generation, text]
738
+ @memory_review = nil
739
+ add(:command_notice, 'Memory review closed without a decision.')
740
+ end
660
741
  when :command_state
661
742
  if text[:ai].is_a?(Hash)
662
743
  text[:ai][:active] = text[:ai][:active].to_sym if PWN::Env.dig(:ai, :active).is_a?(Symbol) && text[:ai][:active].is_a?(String)
@@ -671,9 +752,10 @@ module PWN
671
752
  @worker.join
672
753
  finish_request_metrics
673
754
  @running = false
755
+ @memory_review = nil
756
+ @control&.close
674
757
  @control = nil
675
758
  @mission = nil
676
- @mission_commands&.close unless @mission_commands&.closed?
677
759
  when :operator_loaded
678
760
  generation, data = text
679
761
  if @operator_view && @operator_view[:generation] == generation
@@ -729,11 +811,12 @@ module PWN
729
811
  @title_worker.report_on_exception = false
730
812
  end
731
813
 
732
- def add(type, text)
814
+ def add(type, text, exact: false)
733
815
  command_notice = type == :command_notice
734
816
  type = :notice if command_notice
735
817
  clean = PWN::Redaction.redact(value: text.to_s)
736
818
  clean = clean.gsub(/\e\][^\a]*(?:\a|\e\\)/, '').gsub(%r{\e\[[0-?]*[ -/]*[@-~]}, '').gsub(/[\x00-\x08\x0b-\x1f\x7f]/, '')
819
+ return false if exact && clean != text
737
820
  return if clean.strip.empty?
738
821
 
739
822
  @event_count += 1
@@ -749,6 +832,7 @@ module PWN
749
832
  @scroll = [@scroll - removed[3].fetch(:rows, []).length, 0].max if @scroll
750
833
  end
751
834
  PWN::Plugins::Log.mirror_tui!(msg: "#{type.to_s.upcase}\n#{clean}") if @pry.config.pwn_ai_debug && type != :notice
835
+ true
752
836
  end
753
837
 
754
838
  private_class_method def self.mission_entry(opts = {})
@@ -793,8 +877,20 @@ module PWN
793
877
  control = Control.new(input: @input, output: output)
794
878
  Thread.current[:pwn_steering_input] = control
795
879
  Thread.current[:pwn_usage_observer] = ->(usage) { events << [:usage, usage] }
796
- Thread.new do
797
- commands.each_line { |line| control.submit(JSON.parse(line)) }
880
+ review = MemoryReview.new(events, generation)
881
+ command_reader = Thread.new do
882
+ commands.each_line do |line|
883
+ break unless line.end_with?("\n")
884
+
885
+ frame = JSON.parse(line, symbolize_names: true)
886
+ control.submit(frame) if frame.is_a?(String)
887
+ review.decide(frame) if frame.is_a?(Hash)
888
+ end
889
+ rescue IOError, SystemCallError, JSON::ParserError
890
+ # A lost or invalid command channel cannot grant approval.
891
+ nil
892
+ ensure
893
+ review.close
798
894
  end
799
895
  begin
800
896
  workspace = File.realpath(Dir.pwd)
@@ -812,10 +908,14 @@ module PWN
812
908
  end
813
909
  end
814
910
  final = with_stream_preview(events) do
911
+ previous = Thread.current[:pwn_review_memory]
912
+ Thread.current[:pwn_review_memory] = review.method(:call)
815
913
  PWN::AI::Agent::Loop.run(request: request, session_id: session_id,
816
914
  enabled_toolsets: PWN::Env.dig(:ai, :agent, :toolsets),
817
915
  on_tool: on_tool, steering: control, debug: @pry.config.pwn_ai_debug,
818
916
  trace: @pry.config.pwn_ai_trace, debug_tee: output)
917
+ ensure
918
+ Thread.current[:pwn_review_memory] = previous
819
919
  end
820
920
  promoted = Thread.current[:pwn_thinking_promoted] && final.to_s.strip == Thread.current[:pwn_last_thinking].to_s.strip
821
921
  events << [:assistant, final.to_s] unless promoted
@@ -835,6 +935,8 @@ module PWN
835
935
  end
836
936
  events << [:warning, warning]
837
937
  ensure
938
+ review.close
939
+ command_reader.kill.join
838
940
  output.flush
839
941
  writer.close
840
942
  end
@@ -887,20 +989,22 @@ module PWN
887
989
  begin_request_metrics
888
990
  add(:operator, request)
889
991
  reader, writer = IO.pipe
890
- commands, @mission_commands = IO.pipe
992
+ commands, sender = PWN::AI::Agent::MissionNamespace.control_socket_pair
993
+ commands.shutdown(Socket::SHUT_WR)
994
+ @control = MissionControl.new(sender)
891
995
  @mission = PWN::Plugins::AISandbox::MissionProcess.new(
892
996
  descriptor: { operation: :console, request: request, generation: generation, session_id: session_id, title_config: title_config, config: mission_config },
893
997
  fds: { 4 => writer, 5 => @input, 6 => commands }
894
998
  )
895
999
  writer.close
896
1000
  commands.close
897
- @control = MissionControl.new(@mission_commands)
1001
+
898
1002
  @running = true
899
1003
  mission = @mission
900
1004
  @worker = Thread.new do
901
1005
  reader.each_line do |line|
902
1006
  tag, type, text = JSON.parse(line, symbolize_names: true)
903
- next unless tag == generation && %w[task thinking tool result assistant notice warning session_title usage].include?(type)
1007
+ next unless tag == generation && %w[task thinking tool result assistant notice warning session_title usage memory_review memory_review_closed].include?(type)
904
1008
 
905
1009
  @events << [type.to_sym, text, tag]
906
1010
  end
@@ -913,9 +1017,9 @@ module PWN
913
1017
  end
914
1018
  @worker.report_on_exception = false
915
1019
  rescue StandardError => e
916
- [reader, writer, commands, @mission_commands].compact.each { |io| io.close unless io.closed? }
1020
+ [reader, writer, commands, sender].compact.each { |io| io.close unless io.closed? }
917
1021
  @mission&.close
918
- @mission = nil
1022
+ @mission = @control = nil
919
1023
  @running = false
920
1024
  add(:warning, "Mission not started: #{e.message}")
921
1025
  end
@@ -925,9 +1029,10 @@ module PWN
925
1029
  # reaps namespace PID 1, including all provider and tool descendants.
926
1030
  @cancelling = true
927
1031
  @mission_generation = nil
1032
+ @memory_review = nil
928
1033
  @mission.close
929
1034
  @worker&.join
930
- @mission_commands&.close unless @mission_commands&.closed?
1035
+ @control&.close
931
1036
  @tool_input&.close unless @tool_input&.closed?
932
1037
  @mission = @control = nil
933
1038
  @running = false
@@ -1029,6 +1134,7 @@ module PWN
1029
1134
  # Preserve normal request text and the exact internal title bytes.
1030
1135
  line = line.gsub(/\A[[:space:]]+|[[:space:]]+\z/, '') if line.match?(%r{\A[[:space:]]*/})
1031
1136
  return if line.strip.empty?
1137
+ return decide_memory(line) if line.match?(MEMORY_DECISION)
1032
1138
 
1033
1139
  # Pry owns the existing pwn_history format, append and deduplication.
1034
1140
  # Curses bypasses Pry's input evaluator, so record once here, not on recall.
@@ -1087,6 +1193,35 @@ module PWN
1087
1193
  add(:warning, "#{e.class}: #{e.message}")
1088
1194
  end
1089
1195
 
1196
+ def present_memory_review(event, generation)
1197
+ return if @memory_review || !event.is_a?(Hash)
1198
+
1199
+ ticket = event[:ticket]
1200
+ return unless ticket.is_a?(String) && ticket.match?(/\A[0-9a-f]{16}\z/)
1201
+
1202
+ display = event[:display]
1203
+ prompt = "Review this one memory_remember write (escaped JSON):\n#{display}\nType /memory approve #{ticket} or /memory decline #{ticket}."
1204
+ if display.is_a?(String) && display.match?(/\A[\x20-\x7e\n]+\z/) && add(:command_notice, prompt, exact: true)
1205
+ @memory_review = [generation, ticket]
1206
+ else
1207
+ @control.memory_decision(generation, ticket, 'decline')
1208
+ add(:command_notice, 'Memory write declined: the exact proposal could not be displayed.')
1209
+ end
1210
+ rescue IOError, SystemCallError
1211
+ add(:warning, 'Memory review closed: mission control channel disconnected.')
1212
+ end
1213
+
1214
+ def decide_memory(line)
1215
+ decision, ticket = line.match(%r{\A/memory +(approve|decline) +([0-9a-f]{16})\z})&.captures
1216
+ return add(:command_notice, 'No matching pending memory review.') unless ticket && @running && @memory_review == [@mission_generation, ticket]
1217
+
1218
+ @memory_review = nil
1219
+ @control.memory_decision(@mission_generation, ticket, decision)
1220
+ add(:command_notice, 'Memory decision sent.')
1221
+ rescue IOError, SystemCallError
1222
+ add(:warning, 'Memory decision not delivered: mission control channel closed.')
1223
+ end
1224
+
1090
1225
  def busy_command(line)
1091
1226
  if line.match?(%r{\A/steer(?:\s|$)})
1092
1227
  if @control.nil?
data/lib/pwn/version.rb CHANGED
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module PWN
4
- VERSION = '0.5.804'
4
+ VERSION = '0.5.805'
5
5
  end
@@ -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]