Module: PWN::AI::Agent::Learning

Defined in:
lib/pwn/ai/agent/learning.rb

Overview

PWN::AI::Agent::Learning is the self-improvement engine that closes the pwn-ai feedback loop. It captures task outcomes, mines session transcripts for durable lessons, promotes successful workflows into reusable skills, and prunes / consolidates persistent memory so the agent gets sharper over time instead of accumulating noise.

Data flows:

Loop.run --(tool telemetry)--> Metrics.record
Loop.run --(final answer)----> Learning.auto_introspect (opt-in)
model    --(tool calls)------> learning_note_outcome / _distill_skill
PromptBuilder <----------------- Learning.to_context + Metrics.to_context

Everything is file-backed under ~/.pwn so it survives across REPL restarts and is shared by every future session.

Constant Summary collapse

LEARNING_FILE =
File.join(Dir.home, '.pwn', 'learning.jsonl')
FINETUNE_DIR =
File.join(Dir.home, '.pwn', 'finetune')
INTROSPECT_SOFT_MS =

P0 — post-answer introspect must not train "stop early" while spending the iteration budget after the final. Soft cap skips expensive stages (tool critic, PRM-LLM, reflect, extrospect); hard cap keeps only note_outcome + judge(heuristic) + sentinel.

2_500
INTROSPECT_HARD_MS =
8_000
INTROSPECT_MIN_STAGES =
%i[judge note_outcome fold_judge sentinel].freeze
MAX_MEMORY_ENTRIES =
200
CLAIM_METRIC_WORDS =

E3/P26 — only CVE-ids or software-name + full semver (x.y.z). Two-part floats ("cap 0.2", "proxy 1.0", "judge 37.0") are RL metric crumbs that were scraped by verify_as_reward and flooded learning.jsonl with extro_verify :unknown failures.

%w[
  cap share proxy judge success only now clears gap score rate mean
  brier overconf distrust trajectory_fraction handler orm prm delta
  limit window pct percent ms iter budget conf confidence n
  ruby python linux kernel host cwd e.g e.g.
].freeze
CLAIM_RX =
/
  CVE-\d{4}-\d{4,7}
  |
  \b
  (?!
    (?:cap|share|proxy|judge|success|only|now|clears|gap|score|rate|mean|
       brier|overconf|distrust|trajectory_fraction|handler|orm|prm|delta|
       limit|window|pct|percent|ms|iter|budget|conf|confidence|
       ruby|python|linux|kernel|host|cwd|e\.g)
    \b
  )
  [A-Za-z][\w.+-]{2,}
  \s+
  v?\d+\.\d+\.\d+(?:[-+][\w.]+)?
  \b
/x
SFT_MIN_SCORE =

P12 — SFT quality gate (as hard as DPO source-cap): drop HER/soft, low judge_score, auto-only noise without score, and PRM-compress trajectories so LoRA is not 5MB of "how we flailed".

0.6
SFT_MAX_TOOL_CHARS =
1_200
FAILURE_FINAL_RX =
/\[pwn-ai\] (iteration budget exhausted|engine returned no message)|\b(i (was )?unable to|i could not|i couldn'?t|cannot proceed|failed to)\b/i

Class Method Summary collapse

Class Method Details

.authorsObject

Author(s)

0day Inc. support@0dayinc.com



1002
1003
1004
# File 'lib/pwn/ai/agent/learning.rb', line 1002

public_class_method def self.authors
  "AUTHOR(S):\n  0day Inc. <support@0dayinc.com>\n"
end

.auto_introspect(opts = {}) ⇒ Object

Supported Method Parameters

PWN::AI::Agent::Learning.auto_introspect( session_id: 'required - id of the just-completed session', request: 'optional - original user request (for outcome logging)', final: 'optional - final assistant answer (for outcome logging)' )

Called by Loop.run when PWN::Env[:agent][:auto_introspect] is truthy. Never raises — learning must not break the primary loop.



390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
# File 'lib/pwn/ai/agent/learning.rb', line 390

public_class_method def self.auto_introspect(opts = {})
  session_id = opts[:session_id]
  return unless session_id
  return unless auto_introspect_enabled?

  t0 = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  stages_run = []
  stages_skipped = []
  budget_hot = begin
    defined?(Loop) && Loop.respond_to?(:budget_exhaustion_hot?, true) &&
      Loop.send(:budget_exhaustion_hot?)
  rescue StandardError
    false
  end

  elapsed_ms = lambda do
    ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - t0) * 1000).round
  end
  # soft = skip expensive; hard = stop almost everything
  over_soft = lambda do
    ms = elapsed_ms.call
    ms >= INTROSPECT_SOFT_MS || budget_hot
  end
  over_hard = lambda do
    ms = elapsed_ms.call
    ms >= INTROSPECT_HARD_MS
  end

  proxy_ok = infer_success(session_id: session_id, final: opts[:final])

  # S3 critic — BEFORE reward so verdict is evidence.
  # P24/P0 — budget_hot or soft-cap → text_only or skip.
  force_critic = begin
    eng = (PWN::Env.dig(:ai, :active) if defined?(PWN::Env))
    cal = defined?(Metrics) ? Metrics.calibration(engine: eng) : { n: 0 }
    cal[:n].to_i >= 8 && (cal[:brier].to_f > 0.35 || cal[:overconfidence].to_f > 0.25)
  rescue StandardError
    false
  end
  # P0 — when W1 mix urgently needs :critic pairs, prefer running critic
  need_critic_mix = begin
    mix = defined?(Reward) && Reward.respond_to?(:generator_mix) ? Reward.generator_mix : {}
    Array(mix[:urgent]).include?('critic')
  rescue StandardError
    false
  end

  crit = { verdict: :pass, source: :skipped }
  # Single skip path (Lint/DuplicateBranch): hard-budget OR no Curriculum.
  if !defined?(Curriculum) || (over_hard.call && !need_critic_mix)
    stages_skipped << :critic
  elsif budget_hot || (over_soft.call && !force_critic && !need_critic_mix)
    stages_run << :critic_text_only
    crit = Curriculum.critic(
      request: opts[:request],
      final: opts[:final],
      session_id: session_id,
      text_only: true
    )
  elsif force_critic
    stages_run << :critic_forced
    prev = (PWN::Env[:ai][:agent][:critic] if defined?(PWN::Env) && PWN::Env[:ai].is_a?(Hash) && PWN::Env[:ai][:agent].is_a?(Hash))
    begin
      PWN::Env[:ai][:agent][:critic] = true if defined?(PWN::Env) && PWN::Env[:ai].is_a?(Hash) && PWN::Env[:ai][:agent].is_a?(Hash) && !PWN::Env[:ai][:agent].frozen?
      crit = Curriculum.critic(request: opts[:request], final: opts[:final], session_id: session_id)
    ensure
      PWN::Env[:ai][:agent][:critic] = prev if defined?(PWN::Env) && PWN::Env[:ai].is_a?(Hash) && PWN::Env[:ai][:agent].is_a?(Hash) && !PWN::Env[:ai][:agent].frozen?
    end
  else
    stages_run << :critic
    crit = Curriculum.critic(request: opts[:request], final: opts[:final], session_id: session_id)
  end

  # R1 judge — always attempt (heuristic is cheap; LLM gated inside)
  stages_run << :judge
  v = Reward.judge(request: opts[:request], final: opts[:final], session_id: session_id, proxy_ok: proxy_ok) if defined?(Reward)
  v ||= { score: proxy_ok ? 1.0 : 0.0, success: proxy_ok, verdict: proxy_ok ? :solved : :wrong }
  v[:score] = [v[:score], 0.3].min if crit[:verdict] == :flaw
  ok = v[:score] >= 0.6

  # W1 pending user_correction pair
  pend = Thread.current[:pwn_pending_pref]
  if pend && ok && defined?(Reward)
    stages_run << :user_correction_pref
    Reward.record_preference(
      prompt: pend[:prompt],
      rejected: pend[:rejected],
      chosen: opts[:final].to_s,
      source: :user_correction,
      shape: :revised_answer,
      force: true
    )
    Thread.current[:pwn_pending_pref] = nil
  end

  stages_run << :note_outcome
  note_outcome(
    task: opts[:request].to_s[0, 120],
    success: ok,
    score: v[:score],
    details: "#{v[:verdict]}(#{v[:score].round(2)}) #{v[:rationale]} | #{opts[:final].to_s[0, 200]}",
    session_id: session_id,
    tags: ['auto', 'loop', v[:verdict].to_s]
  )

  stages_run << :fold_judge
  fold_judge_into_metrics(session_id: session_id, score: v[:score], confidence: v[:confidence])

  # R2 PRM — skip under hard cap (expensive LLM); keep under soft if heuristic path
  if over_hard.call
    stages_skipped << :prm
  elsif defined?(Reward)
    stages_run << :prm
    Reward.prm(request: opts[:request], session_id: session_id)
  end

  # C3 HER — only on failure; skip hard
  if !ok && defined?(Curriculum) && !over_hard.call
    stages_run << :hindsight
    Curriculum.hindsight(request: opts[:request], final: opts[:final], session_id: session_id)
  else
    stages_skipped << :hindsight unless ok
  end

  # W3 calibrate — cheap; always when predicted available
  predicted = opts[:predicted]
  predicted = recover_predicted_from_session(session_id: session_id) if predicted.nil?
  if !predicted.nil? && defined?(Curriculum)
    stages_run << :calibrate
    Curriculum.calibrate(predicted: predicted, actual: v[:score], engine: PWN::Env.dig(:ai, :active))
  end

  # reflect on success — skip soft/hard (LLM + memory writes)
  if ok && !over_soft.call
    stages_run << :reflect
    reflect(session_id: session_id)
  elsif ok
    stages_skipped << :reflect
  end

  # R3 sentinel — cheap disk math; always
  if defined?(Reward)
    stages_run << :sentinel
    Reward.sentinel
  end

  # E ambient extrospect — skip soft (can launch probes)
  if defined?(Extrospection) && !over_soft.call
    stages_run << :extrospect
    Extrospection.auto_extrospect(session_id: session_id)
  else
    stages_skipped << :extrospect
  end

  {
    ok: ok,
    score: v[:score],
    elapsed_ms: elapsed_ms.call,
    budget_hot: budget_hot,
    stages_run: stages_run,
    stages_skipped: stages_skipped
  }
rescue StandardError => e
  warn "[pwn-ai/learning] auto_introspect swallowed: #{e.class}: #{e.message}"
  nil
end

.consolidate(opts = {}) ⇒ Object

Supported Method Parameters

removed = PWN::AI::Agent::Learning.consolidate( max_entries: 'optional - hard cap on PWN::Memory size (default MAX_MEMORY_ENTRIES)' )

Deduplicates near-identical lesson values and prunes the oldest entries once the cap is exceeded so the injected MEMORY block stays high-signal.



589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
# File 'lib/pwn/ai/agent/learning.rb', line 589

public_class_method def self.consolidate(opts = {})
  cap = opts[:max_entries] || MAX_MEMORY_ENTRIES
  return { removed: 0 } unless defined?(PWN::Memory)

  mem = PWN::Memory.load
  removed = []

  # M1 — semantic clustering: embed :lesson entries, greedy-merge
  # near-duplicates (cosine ≥ 0.92) via Reflect into ONE imperative
  # lesson. Falls back to sha-dedup when no embed backend.
  removed.concat(semantic_merge(mem: mem)) if defined?(PWN::MemoryIndex) && PWN::MemoryIndex.available?

  seen = {}
  mem.each do |k, v|
    sig = Digest::SHA256.hexdigest(v[:value].to_s.strip.downcase)[0, 16]
    seen[sig] ? removed << k : seen[sig] = k
  end
  removed.uniq.each { |k| mem.delete(k) }

  # M3 — evict by (age/ttl) / (importance × confidence), NOT
  # oldest-first. Hand-written high-value lessons survive; low-
  # confidence :heuristic auto-gen self-evicts first.
  if mem.size > cap
    now = Time.now.utc
    sorted = mem.sort_by do |_k, v|
      age_d = (now - Time.parse(v[:timestamp].to_s)) / 86_400.0
      ttl_d = (v[:ttl].to_f / 86_400.0)
      imp   = (v[:importance] || 0.5).to_f.clamp(0.05, 1.0)
      conf  = (v[:confidence] || (v[:source].to_s == 'human' ? 0.95 : 0.5)).to_f.clamp(0.05, 1.0)
      staleness = ttl_d.positive? ? age_d / ttl_d : age_d / 90.0
      -(staleness / (imp * conf))
    rescue StandardError
      0.0
    end
    drop = sorted.first(mem.size - cap).map(&:first)
    drop.each { |k| mem.delete(k) }
    removed.concat(drop)
  end
  PWN::Memory.save(mem: mem)
  { removed: removed.uniq.length, remaining: mem.size }
end

.distill_skill(opts = {}) ⇒ Object

Supported Method Parameters

skill = PWN::AI::Agent::Learning.distill_skill( name: 'required - snake_case name for the new skill', session_id: 'optional - PWN::Sessions id to mine (uses its transcript)', content: 'optional - explicit markdown body; overrides transcript mining', references: 'optional - Array of reference URLs / CWE / CVE / ATT&CK ids' )



323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
# File 'lib/pwn/ai/agent/learning.rb', line 323

public_class_method def self.distill_skill(opts = {})
  raise 'ERROR: name is required' if opts[:name].to_s.strip.empty?

  body = opts[:content].to_s
  body = build_skill_from_session(session_id: opts[:session_id], name: opts[:name]) if body.strip.empty? && opts[:session_id]
  raise 'ERROR: content or session_id is required' if body.strip.empty?

  root = skills_dir
  out  = PWN::Config.write_skill(
    name: opts[:name],
    description: opts[:description],
    content: body,
    references: opts[:references],
    pwn_skills_path: root
  )
  PWN::Config.load_skills(pwn_skills_path: root) if PWN::Config.respond_to?(:load_skills)
  note_outcome(task: "distill_skill:#{out[:name]}", success: true, details: "Saved #{out[:path]}", tags: %w[skill auto])
  out.merge(saved: true)
end

.exemplars_for(opts = {}) ⇒ Object

Supported Method Parameters

msgs = PWN::AI::Agent::Learning.exemplars_for( request: 'required - current user request', limit: 'optional - max exemplar traces to return (default 1)', max_msgs: 'optional - cap on messages per exemplar (default 6)' )

Retrieval-augmented BEHAVIOUR: keyword-matches request against prior successful outcomes in learning.jsonl, loads the matching session, and compresses its (user, tool, assistant) trace into a short few-shot exemplar Loop.run splices between system and user. Local models are dramatically better with 1 concrete example than with 25 abstract lessons.



190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
# File 'lib/pwn/ai/agent/learning.rb', line 190

public_class_method def self.exemplars_for(opts = {})
  request  = opts[:request].to_s.downcase
  limit    = (opts[:limit]    || 1).to_i
  max_msgs = (opts[:max_msgs] || 6).to_i
  return [] if request.strip.empty?

  tokens = request.scan(/[a-z0-9_]{3,}/).uniq
  return [] if tokens.empty?

  now = Time.now.utc
  # C2 — prioritized replay: priority = judge_score × recency_decay × keyword_sim
  # C2 — strict success:true only (excludes HER success:'soft'). Also
  # down-weight any residual hindsight-tagged rows so partial failures
  # never launder into full-strength few-shot exemplars.
  # P20 — strict success:true AND prefer high judge scores. Drop rows
  # with explicit low ORM score so proxy-true / judge-low cannot be few-shot.
  pool = outcomes(limit: 500, success: true).reject { |r| r[:session_id].to_s.empty? }
  pool = pool.reject { |r| r.key?(:score) && r[:score].to_f < 0.6 }
  scored = pool.map do |r|
    sim   = tokens.count { |t| r[:task].to_s.downcase.include?(t) }.to_f / tokens.length
    age_d = (now - Time.parse(r[:timestamp].to_s)) / 86_400.0
    decay = Math.exp(-age_d / 30.0)
    score = (r[:score] || 1.0).to_f
    tags  = Array(r[:tags]).map(&:to_s)
    # HER / soft / hindsight → 0.35× so they cannot dominate C2 priority
    score *= 0.35 if r[:success].to_s == 'soft' || tags.intersect?(%w[hindsight her soft])
    [r, sim * decay * score]
  rescue StandardError
    [r, 0.0]
  end
  hits = scored.reject { |_, pr| pr <= 0.0 }.sort_by { |_, pr| -pr }.first(limit).map(&:first)

  hits.flat_map { |r| compress_exemplar(session_id: r[:session_id], max_msgs: max_msgs) }
rescue StandardError
  []
end

.export_finetune(opts = {}) ⇒ Object



247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
# File 'lib/pwn/ai/agent/learning.rb', line 247

public_class_method def self.export_finetune(opts = {})
  fmt       = (opts[:format] || :sharegpt).to_sym
  min_tools = (opts[:min_tools] || 1).to_i
  min_score = (opts[:min_score] || SFT_MIN_SCORE).to_f
  compress  = opts.key?(:compress) ? opts[:compress] : true
  FileUtils.mkdir_p(FINETUNE_DIR)
  out = opts[:out] || File.join(FINETUNE_DIR, "pwn-#{Time.now.utc.strftime('%Y%m%d')}.jsonl")

  # 4.1 / P12 — exclude HER soft-success + low-score + untagged auto flail
  gold = outcomes(limit: 10_000, success: true).reject do |r|
    tags = Array(r[:tags]).map(&:to_s)
    soft = r[:success].to_s == 'soft' || tags.intersect?(%w[hindsight her soft])
    low  = !r[:score].nil? && r[:score].to_f < min_score
    # require a score when present in corpus era that has scores
    soft || low
  end
  # prefer highest-score outcome per session
  by_sid = {}
  gold.each do |r|
    sid = r[:session_id].to_s
    next if sid.empty?

    prev = by_sid[sid]
    by_sid[sid] = r if prev.nil? || r[:score].to_f >= prev[:score].to_f
  end
  sids = by_sid.keys
  rows = 0
  dropped = { tools: 0, empty: 0, load: 0 }
  File.open(out, 'w') do |f|
    sids.each do |sid|
      t = begin
        PWN::Sessions.load(session_id: sid)
      rescue StandardError
        dropped[:load] += 1
        next
      end
      tool_n = t.count { |e| e[:role].to_s == 'tool' }
      if tool_n < min_tools
        dropped[:tools] += 1
        next
      end

      conv = if compress
               compress_finetune_trace(transcript: t, max_tool_chars: SFT_MAX_TOOL_CHARS)
             else
               t.map { |e| { role: e[:role].to_s, content: e[:content].to_s } }
                .reject { |e| e[:role] == 'system' && e[:content].start_with?('Session started') }
             end
      if conv.nil? || conv.empty? || conv.none? { |m| m[:role].to_s == 'assistant' }
        dropped[:empty] += 1
        next
      end

      line = case fmt
             when :openai_jsonl then { messages: conv }
             else { conversations: conv.map { |m| { from: sharegpt_role(role: m[:role]), value: m[:content] } } }
             end
      f.puts(JSON.generate(line))
      rows += 1
    end
  end
  {
    path: out, format: fmt, sessions: sids.length, samples: rows,
    bytes: File.size(out), min_score: min_score, compressed: compress,
    dropped: dropped
  }
end

.flip_last_outcome(opts = {}) ⇒ Object



557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
# File 'lib/pwn/ai/agent/learning.rb', line 557

public_class_method def self.flip_last_outcome(opts = {})
  return { flipped: false } unless File.exist?(LEARNING_FILE)

  lines = File.readlines(LEARNING_FILE)
  return { flipped: false } if lines.empty?

  last = JSON.parse(lines.last, symbolize_names: true)
  return { flipped: false } if opts[:session_id] && last[:session_id] && last[:session_id] != opts[:session_id]
  return { flipped: false } unless last[:success]

  last[:success]    = false
  last[:flipped_by] = 'user_correction'
  last[:details]    = "#{last[:details]} | CORRECTED: #{opts[:reason].to_s[0, 200]}".strip
  last[:score]      = 0.0
  lines[-1] = "#{JSON.generate(last)}\n"
  File.write(LEARNING_FILE, lines.join)
  # W1 — the (rejected_prev_answer, chosen_next_answer) pair is
  # captured by Mistakes.check_user_correction which has both.
  { flipped: true, id: last[:id], rejected: last[:details].to_s[0, 2_000] }
rescue StandardError
  { flipped: false }
end

.helpObject

Display Usage for this Module



1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
# File 'lib/pwn/ai/agent/learning.rb', line 1008

public_class_method def self.help
  puts <<~USAGE
    USAGE:
      PWN::AI::Agent::Learning.note_outcome(task: 'nmap sweep 10.0.0.0/24', success: true, details: '12 hosts up')
      PWN::AI::Agent::Learning.outcomes(limit: 20, success: false)
      PWN::AI::Agent::Learning.reflect(session_id: sid)              # LLM or heuristic → PWN::Memory
      PWN::AI::Agent::Learning.auto_introspect(session_id: sid, request: req, final: text)
      PWN::AI::Agent::Learning.distill_skill(name: 'quick_recon', session_id: sid)
      PWN::AI::Agent::Learning.exemplars_for(request: 'nmap sweep 10/8')  # few-shot for Loop.run
      PWN::AI::Agent::Learning.export_finetune(format: :sharegpt)        # -> ~/.pwn/finetune/*.jsonl
      PWN::AI::Agent::Learning.consolidate(max_entries: 200)         # M1 semantic-merge + M3 importance-evict
      PWN::AI::Agent::Learning.purge_noise                            # one-shot GC of pre-R1 garbage lessons
      PWN::AI::Agent::Learning.to_context(limit: 5)                  # injected by PromptBuilder
      PWN::AI::Agent::Learning.stats
      PWN::AI::Agent::Learning.reset

      Enable end-of-run auto-learning with:
        PWN::Env[:ai][:agent][:auto_introspect] = true

      #{self}.authors
  USAGE
end

.note_outcome(opts = {}) ⇒ Object

Supported Method Parameters

entry = PWN::AI::Agent::Learning.note_outcome( task: 'required - short description of what was attempted', success: 'required - Boolean, did the attempt achieve its goal', details: 'optional - free-form notes / error / evidence', session_id: 'optional - PWN::Sessions id this outcome belongs to', tags: 'optional - Array of String labels for later retrieval' )



73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/pwn/ai/agent/learning.rb', line 73

public_class_method def self.note_outcome(opts = {})
  task    = opts[:task].to_s
  # 4.1 — allow success: 'soft' (HER) distinct from true/false
  raw_ok  = opts[:success]
  success = if ['soft', :soft].include?(raw_ok)
              'soft'
            else
              raw_ok ? true : false
            end
  raise 'ERROR: task is required' if task.strip.empty?

  entry = {
    id: Digest::SHA256.hexdigest("#{task}-#{Time.now.to_f}")[0, 12],
    task: task,
    success: success,
    details: opts[:details].to_s[0, 2_000],
    session_id: opts[:session_id],
    tags: Array(opts[:tags]).map(&:to_s),
    timestamp: Time.now.utc.iso8601
  }
  entry[:score] = opts[:score].to_f if opts.key?(:score)
  FileUtils.mkdir_p(File.dirname(LEARNING_FILE))
  File.open(LEARNING_FILE, 'a') { |f| f.puts(JSON.generate(entry)) }

  # M4 — outcomes live in learning.jsonl ONLY. PWN::Memory[:lesson] is
  # reserved for reflect / mistakes_resolve / human — this alone
  # removed 40 % of the noise in the injected MEMORY block.
  entry
end

.outcomes(opts = {}) ⇒ Object

Supported Method Parameters

rows = PWN::AI::Agent::Learning.outcomes( limit: 'optional - max entries returned newest-first (default 50)', success: 'optional - filter by Boolean outcome', tag: 'optional - filter by tag substring' )



110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
# File 'lib/pwn/ai/agent/learning.rb', line 110

public_class_method def self.outcomes(opts = {})
  limit   = opts[:limit] || 50
  want_ok = opts.key?(:success) ? !opts[:success].nil? && opts[:success] != false : nil
  tag     = opts[:tag].to_s.downcase
  return [] unless File.exist?(LEARNING_FILE)

  rows = File.readlines(LEARNING_FILE).map do |l|
    JSON.parse(l, symbolize_names: true)
  rescue StandardError
    nil
  end
  rows.compact!
  rows.select! { |r| want_ok == true ? r[:success] == true : r[:success] == want_ok } unless want_ok.nil?
  rows.select! { |r| Array(r[:tags]).any? { |t| t.to_s.downcase.include?(tag) } } unless tag.empty?
  rows.reverse.first(limit)
end

.purge_noiseObject

Supported Method Parameters

PWN::AI::Agent::Learning.purge_noise

One-shot GC of the pre-R1 garbage: drops every PWN::Memory entry matching the old SUCCESS: <req> — <final> / Avoid repeating failure pattern from <tool>: {"success":true shapes. Run once after upgrading; subsequent writes never produce these.



984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
# File 'lib/pwn/ai/agent/learning.rb', line 984

public_class_method def self.purge_noise
  return { removed: 0 } unless defined?(PWN::Memory)

  mem = PWN::Memory.load
  before = mem.size
  mem.reject! do |_k, v|
    next false unless v[:category].to_s == 'lesson'

    val = v[:value].to_s
    val.start_with?('SUCCESS: ', 'FAILURE: ') ||
      val.match?(/\AAvoid repeating failure pattern from \w+: .{0,5}\{"success":true/)
  end
  PWN::Memory.save(mem: mem)
  { removed: before - mem.size, remaining: mem.size }
end

.reflect(opts = {}) ⇒ Object

Supported Method Parameters

report = PWN::AI::Agent::Learning.reflect( session_id: 'required - PWN::Sessions id to analyse', dry_run: 'optional - when true, do not write to Memory/Skills (default false)' )

Uses PWN::AI::Agent::Reflect (when available) to LLM-summarise the session into structured lessons. Falls back to a heuristic extractor when module_reflection is disabled so learning never stops.



353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
# File 'lib/pwn/ai/agent/learning.rb', line 353

public_class_method def self.reflect(opts = {})
  session_id = opts[:session_id]
  dry_run    = opts[:dry_run] ? true : false
  raise 'ERROR: session_id is required' if session_id.to_s.empty?

  transcript = PWN::Sessions.load(session_id: session_id)
  return { session_id: session_id, lessons: [], reason: 'empty transcript' } if transcript.empty?

  lessons = introspective_lessons(transcript: transcript)
  source, conf = lessons.empty? ? [:heuristic, 0.3] : [:reflect, 0.8]
  lessons = heuristic_lessons(transcript: transcript) if lessons.empty?

  saved = []
  lessons.each do |l|
    next if l.to_s.strip.empty?

    key = :"reflect_#{session_id}_#{Digest::SHA256.hexdigest(l)[0, 8]}"
    # M3 — provenance + confidence + ttl so consolidate evicts
    # low-confidence heuristic lessons before hand-written ones.
    PWN::Memory.remember(key: key, value: l, category: :lesson, source: source, confidence: conf, importance: conf, ttl: source == :heuristic ? 7 * 86_400 : nil) unless dry_run
    saved << { key: key, lesson: l }
  end
  consolidate unless dry_run

  { session_id: session_id, lessons: saved, count: saved.length, dry_run: dry_run }
end

.resetObject

Supported Method Parameters

PWN::AI::Agent::Learning.reset



634
635
636
637
# File 'lib/pwn/ai/agent/learning.rb', line 634

public_class_method def self.reset
  FileUtils.rm_f(LEARNING_FILE)
  { cleared: true }
end

.statsObject

Supported Method Parameters

stats = PWN::AI::Agent::Learning.stats



130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# File 'lib/pwn/ai/agent/learning.rb', line 130

public_class_method def self.stats
  rows   = outcomes(limit: 10_000)
  total  = rows.length
  ok     = rows.count { |r| r[:success] == true }
  jsum   = rows.sum { |r| r[:score] ? r[:score].to_f : { true => 1.0, false => 0.0 }[r[:success]] }
  skills = defined?(PWN::Skills) && PWN::Skills.is_a?(Hash) ? PWN::Skills.keys.length : 0
  mem    = defined?(PWN::Memory) ? PWN::Memory.load.keys.length : 0
  {
    total_outcomes: total,
    successes: ok,
    failures: total - ok,
    success_rate: total.positive? ? (ok.to_f / total).round(3) : 0.0,
    skills_known: skills,
    memory_entries: mem,
    judge_mean: total.positive? ? (jsum / total).round(3) : nil,
    reward_sentinel: (Reward.sentinel if defined?(Reward)),
    calibration: (Metrics.calibration if defined?(Metrics) && Metrics.respond_to?(:calibration)),
    preference_pairs: (Reward.preferences(limit: 100_000).length if defined?(Reward)),
    tool_metrics: (Metrics.summary(limit: 5) if defined?(Metrics)),
    extrospection: (Extrospection.stats if defined?(Extrospection))
  }
end

.to_context(opts = {}) ⇒ Object

Supported Method Parameters

ctx = PWN::AI::Agent::Learning.to_context( limit: 'optional - number of recent outcomes to surface (default 5)' )



158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
# File 'lib/pwn/ai/agent/learning.rb', line 158

public_class_method def self.to_context(opts = {})
  limit = opts[:limit] || 5
  rows  = outcomes(limit: limit)
  fails = outcomes(limit: 200, success: false).first(limit)
  return '' if rows.empty? && fails.empty?

  fmt = lambda do |r|
    flag = r[:success] ? '' : ''
    "  #{flag} #{r[:task].to_s[0, 100]} (#{r[:timestamp]})"
  end
  s   = stats
  jm  = s[:judge_mean]
  hdr = "RECENT OUTCOMES (success_rate=#{(s[:success_rate] * 100).round(1)}%#{" judge_mean=#{jm}" if jm} over #{s[:total_outcomes]} attempts)"
  out = "#{hdr}\n#{rows.map(&fmt).join("\n")}\n"
  out += "RECENT FAILURES (learn from these — do not repeat)\n#{fails.map(&fmt).join("\n")}\n" unless fails.empty?
  "#{out}\n"
end