Module: PWN::AI::Agent::Curriculum
- Defined in:
- lib/pwn/ai/agent/curriculum.rb
Overview
PWN::AI::Agent::Curriculum is Tier 4/5 of the pwn-ai reinforcement loop — the SELF-PLAY layer that turns the agent from a passive experience-recorder into an active learner:
S1 .practice — Mistake-driven auto-curriculum. Reads
Mistakes.top(unresolved), asks Reflect to
generate 3 minimal reproducer prompts per
signature, self-plays each under Loop.run,
and auto-mistakes_resolve when Reward.judge
says the practice run solved it. THE AGENT
PRACTISES ITS OWN WEAKNESSES OVERNIGHT.
S2 .counterfactual — On a repeated in-turn failure, forks: branch
A continues with the correction_hint, branch
B asks an alt persona for a different tool.
Reward.judge picks the winner; (loser,
winner) → Reward.record_preference. Real
advantage estimation, not imagined rollouts.
S3 .critic — Constitutional critic persona with TOOL
ACCESS (can shell/extro_verify the claim).
Runs BEFORE note_outcome; its verdict feeds
Reward.judge and its concrete flaw becomes a
preference pair when the agent self-corrects.
S4 .red_team_plan — After plan_first, an adversarial persona
reviews the plan against THIS host's
Metrics/Mistakes/extro_drift and injects a
pre-emptive correction_hint on the step it
predicts will fail.
C3 .hindsight — Hindsight Experience Replay. On failure,
asks the judge "what DID this trajectory
accomplish?", relabels the episode with the
achieved-goal as success:true. Free positive
samples from failures — first HER on real
tool traces.
W2 .train_and_gate — export_finetune + export_dpo → local LoRA
(unsloth/axolotl if installed) → replay
Mistakes.top on vN vs vN+1 → promote iff
resolved(N+1) > resolved(N). Fully autonomous
weight-level self-improvement with a
regression gate.
W3 .calibrate — Tracks plan_first predicted p(success) vs
actual outcome → Brier score in Metrics.
All entry points are cron-safe (never raise into the caller) and depth-guarded via Swarm's Thread.current so a curriculum run cannot recurse into itself.
Constant Summary collapse
- CURRICULUM_DIR =
File.join(Dir.home, '.pwn', 'curriculum')
- MODELS_FILE =
File.join(CURRICULUM_DIR, 'models.json')
- CRITIC_NAME =
'pwn_critic'- RED_TEAM_NAME =
'pwn_red_team'- ALT_NAME =
'pwn_alt'- COOLDOWN_FAIL_NIGHTS =
Priority-fix 1 — N-night cooldown window for thrashing signatures and stale "needs_human" tags. Signatures that score ~0 for COOLDOWN_FAIL_NIGHTS consecutive practice nights are parked so the curriculum stops burning cycles on them.
3- COOLDOWN_FILE =
File.join(CURRICULUM_DIR, 'cooldown.json')
- KPI_FILE =
P1 — Outer curriculum KPI: does practice cut live [REPEATING]?
Snapshot unresolved repeating counts before/after practice nights into ~/.pwn/curriculum_kpi.jsonl so week-over-week delta is visible without scraping Mistakes by hand. practice() always appends a row.
File.join(Dir.home, '.pwn', 'curriculum_kpi.jsonl')
- TRAINER_CLI =
W2 trainer discovery/execution is pure Ruby filesystem + argv spawn. Never shell-out via backticks or shell-string Open3 for probe/install checks. unsloth/axolotl presence is inferred from PATH CLIs and site-packages layout; any external process uses argv arrays only.
{ unsloth: %w[unsloth], axolotl: %w[axolotl] }.freeze
- TRAINER_MODULE_HINTS =
{ unsloth: %w[unsloth/__init__.py unsloth/models/__init__.py], axolotl: %w[axolotl/__init__.py axolotl/cli/train.py] }.freeze
- DPO_DIR_CONST =
File.join(Dir.home, '.pwn', 'finetune')
Class Method Summary collapse
-
.authors ⇒ Object
- Author(s)
0day Inc.
- .calibrate(opts = {}) ⇒ Object
- .counterfactual(opts = {}) ⇒ Object
-
.critic(opts = {}) ⇒ Object
- Supported Method Parameters
v = PWN::AI::Agent::Curriculum.critic( request: 'required - user request', final: 'required - candidate final answer', session_id: 'optional - for evidence lookup' ).
-
.help ⇒ Object
Display Usage for this Module.
-
.hindsight(opts = {}) ⇒ Object
- Supported Method Parameters
PWN::AI::Agent::Curriculum.hindsight( request: 'required - the FAILED goal', final: 'required - the final produced anyway', session_id: 'required - trajectory to relabel' ).
-
.offline_judge(opts = {}) ⇒ Object
Priority-fix 3 — Offline ORM/PRM pass over recent sessions so local :failure_only introspect does not starve the reward corpus.
- .practice(opts = {}) ⇒ Object
- .practice_kpi(opts = {}) ⇒ Object
-
.preference_balance(opts = {}) ⇒ Object
P5 — W1 diversity report so monoculture is visible before DPO export.
- .reclassify_backlog(opts = {}) ⇒ Object
-
.red_team_plan(opts = {}) ⇒ Object
- Supported Method Parameters
hint = PWN::AI::Agent::Curriculum.red_team_plan( request: 'required - user goal', plan: 'required - numbered plan text from plan_first' ).
-
.repeating_trend(opts = {}) ⇒ Object
Week-over-week (or last-N snapshots) delta on repeating_n.
-
.train_and_gate(opts = {}) ⇒ Object
- Supported Method Parameters
r = PWN::AI::Agent::Curriculum.train_and_gate( base_model: 'optional - ollama base tag (default PWN::Env[:ollama][:model])', trainer: 'optional - :unsloth | :axolotl | :auto (default :auto)', dry_run: 'optional - export + build eval set but do not train (default true)' ).
Class Method Details
.authors ⇒ Object
- Author(s)
0day Inc. [email protected]
1622 1623 1624 |
# File 'lib/pwn/ai/agent/curriculum.rb', line 1622 public_class_method def self. "AUTHOR(S):\n 0day Inc. <[email protected]>\n" end |
.calibrate(opts = {}) ⇒ Object
771 772 773 774 775 776 777 |
# File 'lib/pwn/ai/agent/curriculum.rb', line 771 public_class_method def self.calibrate(opts = {}) p = (opts.key?(:predicted) && !opts[:predicted].nil? ? opts[:predicted] : 0.5).to_f.clamp(0.0, 1.0) a = opts[:actual].to_f.clamp(0.0, 1.0) brier = (p - a)**2 Metrics.record_calibration(predicted: p, actual: a, brier: brier, engine: opts[:engine]) if defined?(Metrics) && Metrics.respond_to?(:record_calibration) { predicted: p, actual: a, brier: brier.round(4) } end |
.counterfactual(opts = {}) ⇒ Object
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 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 |
# File 'lib/pwn/ai/agent/curriculum.rb', line 369 public_class_method def self.counterfactual(opts = {}) # P0 — when generator_mix marks counterfactual underfilled, run even # if the auto-flag would keep it off (remote-default still respected # only when mix is healthy). Still refuse recursion. mix_need = begin m = defined?(Reward) && Reward.respond_to?(:generator_mix) ? Reward.generator_mix : {} Array(m[:urgent]).include?('counterfactual') rescue StandardError false end return nil unless enabled?(key: :counterfactual) || mix_need || opts[:force] return nil if in_curriculum? request = opts[:request].to_s ensure_persona(name: ALT_NAME, role: 'You are an alternative-approach generator for pwn-ai. Given a failing tool call, propose ONE concrete DIFFERENT tool + args that would achieve the same sub-goal on this host. Reply with the tool call only, no prose.') branch_a = opts[:hint].to_s.strip branch_a = "retry #{opts[:name]} with corrected args" if branch_a.empty? branch_b = with_curriculum_guard do ask_persona(name: ALT_NAME, request: "Goal: #{request[0, 300]}\nFailing: #{opts[:name]}(#{opts[:args].to_s[0, 200]}) → #{opts[:error].to_s[0, 200]}\nPropose ONE different tool+args.") end return nil if branch_b.to_s.strip.empty? sa_h = score_branch_detailed(request: request, branch: branch_a) sb_h = score_branch_detailed(request: request, branch: branch_b) sa = sa_h[:score] sb = sb_h[:score] if sb > sa winner = branch_b loser = branch_a tag = :b = sb_h else winner = branch_a loser = branch_b tag = :a = sa_h end real_hit = sa_h[:mode] == :real_dispatch || sb_h[:mode] == :real_dispatch shape = real_hit ? :real_dispatch : :imagined if defined?(Reward) Reward.record_preference( prompt: "#{request} | failing: #{opts[:name]} → #{opts[:error]}", rejected: loser.to_s[0, 2_000], chosen: winner.to_s[0, 2_000], source: :counterfactual, shape: shape, meta: { a_score: sa, b_score: sb, a_mode: sa_h[:mode], b_mode: sb_h[:mode], winner_trace: [:trace].to_s[0, 500] } ) end log(event: :counterfactual, data: { branch: tag, a: sa, b: sb, tool: opts[:name].to_s, shape: shape }) { branch: tag, content: winner, score: [sa, sb].max, a: sa, b: sb, shape: shape, a_mode: sa_h[:mode], b_mode: sb_h[:mode] } rescue StandardError => e warn "[pwn-ai/curriculum] counterfactual swallowed: #{e.class}: #{e.}" nil end |
.critic(opts = {}) ⇒ Object
- Supported Method Parameters
v = PWN::AI::Agent::Curriculum.critic( request: 'required - user request', final: 'required - candidate final answer', session_id: 'optional - for evidence lookup' )
Returns { verdict: :pass|:flaw, flaw:, confidence: }. On :flaw the (final, flaw) pair is recorded as a preference so a future self-correction becomes DPO signal.
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 |
# File 'lib/pwn/ai/agent/curriculum.rb', line 445 public_class_method def self.critic(opts = {}) mix_need = begin m = defined?(Reward) && Reward.respond_to?(:generator_mix) ? Reward.generator_mix : {} Array(m[:urgent]).include?('critic') rescue StandardError false end return { verdict: :pass, source: :disabled } unless enabled?(key: :critic) || opts[:text_only] || mix_need || opts[:force] return { verdict: :pass, source: :recursion } if in_curriculum? # P24 — text_only: single Reflect shot, no tool-armed persona swarm. # Used when budget_exhaustion_hot? so critic cannot thrash the budget # that auto_introspect is trying to protect. return critic_text_only(request: opts[:request], final: opts[:final], session_id: opts[:session_id]) if opts[:text_only] ensure_persona(name: CRITIC_NAME, role: "You are pwn-ai's constitutional critic. Given a REQUEST and a candidate ANSWER, find ONE concrete, verifiable flaw (wrong fact, missing step, unsupported claim, broken command). You MAY call shell / extro_verify / pwn_eval to check. If none found reply exactly: PASS. Otherwise reply: FLAW: <one line>.") reply = with_curriculum_guard do ask_persona(name: CRITIC_NAME, request: "REQUEST:\n#{opts[:request].to_s[0, 800]}\n\nANSWER:\n#{opts[:final].to_s[0, 2_000]}") end if reply.to_s.strip.upcase.start_with?('PASS') log(event: :critic, data: { verdict: :pass }) { verdict: :pass, confidence: 0.7 } else flaw = reply.to_s.sub(/\AFLAW:\s*/i, '').strip[0, 300] Mistakes.record(tool: 'assistant_answer', error: "critic: #{flaw}", args: opts[:final].to_s[0, 200], session_id: opts[:session_id], source: :model) if defined?(Mistakes) # P9 — DPO pair geometry: rejected=bad final, chosen=REVISED full # answer (not "CORRECTION: flaw" prose). Prefer persona rewrite. if defined?(Reward) && !flaw.to_s.empty? revised = revise_after_flaw( request: opts[:request], final: opts[:final], flaw: flaw, session_id: opts[:session_id] ) Reward.record_preference( prompt: opts[:request].to_s[0, 1_000], rejected: opts[:final].to_s[0, 2_000], chosen: revised, source: :critic, shape: :revised_answer, meta: { flaw: flaw.to_s[0, 200] } ) end log(event: :critic, data: { verdict: :flaw, flaw: flaw.to_s[0, 200] }) { verdict: :flaw, flaw: flaw, confidence: 0.7 } end rescue StandardError => e { verdict: :pass, error: e. } end |
.help ⇒ Object
Display Usage for this Module
1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 |
# File 'lib/pwn/ai/agent/curriculum.rb', line 1628 public_class_method def self.help puts "USAGE: # Run practice and return its result #{self}.practice( limit: 'optional - limit value consumed by #practice', prompts_per: 'optional - prompts per value consumed by #practice', dry_run: 'optional - dry run value consumed by #practice' ) # Priority-fix 3 — Offline ORM/PRM pass over recent sessions so #{self}.offline_judge( local: 'optional - failure_only introspect does not starve the reward corpus.', since_hours: 'optional - lookback window (default 24)', limit: 'optional - max sessions to score (default 40)', prm: 'optional - also run Process Reward Model (default true)', commit: 'optional - write scores into learning/sentinel (default true)' ) # P5 — W1 diversity report so monoculture is visible before DPO export #{self}.preference_balance( limit: 'optional - limit value consumed by #preference_balance (defaults to 10_000)', scrub: 'optional - scrub value consumed by #preference_balance' ) # Run counterfactual and return its result #{self}.counterfactual( force: 'optional - force value consumed by #counterfactual', request: 'optional - request value consumed by #counterfactual', hint: 'optional - hint value consumed by #counterfactual', name: 'required - binary or identifier name', args: 'required - args value consumed by #counterfactual', error: 'optional - error value consumed by #counterfactual' ) # S3 — Constitutional critic (with tool access) #{self}.critic( request: 'required - user request', final: 'required - candidate final answer', session_id: 'optional - for evidence lookup', text_only: 'optional - text only value consumed by #critic', force: 'optional - force value consumed by #critic' ) # S4 — Adversarial plan review (grounded in telemetry) #{self}.red_team_plan( request: 'required - user goal', plan: 'required - numbered plan text from plan_first' ) # C3 — Hindsight Experience Replay #{self}.hindsight( request: 'required - the FAILED goal', final: 'required - the final produced anyway', session_id: 'required - trajectory to relabel' ) # W2 — Online LoRA A/B with regression gate #{self}.train_and_gate( base_model: 'optional - ollama base tag (default PWN::Env[:ai][:ollama][:model])', trainer: 'optional - :unsloth | :axolotl | :auto (default :auto)', dry_run: 'optional - export + build eval set but do not train (default true)' ) # Run reclassify backlog and return its result #{self}.reclassify_backlog( limit: 'optional - limit value consumed by #reclassify_backlog' ) # Run practice kpi and return its result #{self}.practice_kpi( results: 'optional - Array results value consumed by #practice_kpi', reclassified_n: 'optional - reclassified n value consumed by #practice_kpi' ) # Week-over-week (or last-N snapshots) delta on repeating_n #{self}.repeating_trend( limit: 'optional - limit value consumed by #repeating_trend' ) # Run calibrate and return its result #{self}.calibrate( predicted: 'optional - predicted value consumed by #calibrate', actual: 'optional - actual value consumed by #calibrate', engine: 'optional - engine value consumed by #calibrate' ) # Print the AUTHOR(S) string for this module. #{self}.authors " constants.sort end |
.hindsight(opts = {}) ⇒ Object
- Supported Method Parameters
PWN::AI::Agent::Curriculum.hindsight( request: 'required - the FAILED goal', final: 'required - the final produced anyway', session_id: 'required - trajectory to relabel' )
544 545 546 547 548 549 550 551 552 553 554 555 556 |
# File 'lib/pwn/ai/agent/curriculum.rb', line 544 public_class_method def self.hindsight(opts = {}) return nil unless enabled?(key: :hindsight, default: true) return nil unless reflect_available? req = "The agent FAILED at: #{opts[:request].to_s[0, 300]}\nBut it produced: #{opts[:final].to_s[0, 800]}\n\nIn ≤12 words, what goal DID this trajectory accomplish? Reply with the goal only, or NOTHING if truly nothing." achieved = Reflect.on(request: req, suppress_pii_warning: true).to_s.strip return nil if achieved.empty? || achieved.upcase == 'NOTHING' || achieved.length > 200 Learning.note_outcome(task: achieved, success: 'soft', details: "HER-relabelled from failed: #{opts[:request].to_s[0, 100]}", session_id: opts[:session_id], tags: %w[hindsight her soft], score: 0.7) if defined?(Learning) { original: opts[:request].to_s[0, 100], achieved: achieved } rescue StandardError nil end |
.offline_judge(opts = {}) ⇒ Object
Priority-fix 3 — Offline ORM/PRM pass over recent sessions so local :failure_only introspect does not starve the reward corpus. Cron this nightly. Never raises.
- Supported Method Parameters
r = PWN::AI::Agent::Curriculum.offline_judge( since_hours: 'optional - lookback window (default 24)', limit: 'optional - max sessions to score (default 40)', prm: 'optional - also run Process Reward Model (default true)', commit: 'optional - write scores into learning/sentinel (default true)' )
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 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 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 |
# File 'lib/pwn/ai/agent/curriculum.rb', line 222 public_class_method def self.offline_judge(opts = {}) return { skipped: 'no Sessions' } unless defined?(PWN::Sessions) return { skipped: 'no Reward' } unless defined?(Reward) since_h = (opts[:since_hours] || 24).to_i limit = (opts[:limit] || 40).to_i do_prm = opts.key?(:prm) ? opts[:prm] : true commit = opts.key?(:commit) ? opts[:commit] : true cutoff = Time.now.utc - (since_h * 3_600) # PWN::Sessions.list is arity-0 (no kwargs). Cap/sort after the call. sids = if PWN::Sessions.respond_to?(:list) Array(PWN::Sessions.list) .sort_by { |s| s.is_a?(Hash) ? s[:mtime].to_s : '' } .reverse .first(limit * 2) .map { |s| s.is_a?(Hash) ? (s[:id] || s[:session_id] || s['id'] || s['session_id']) : s.to_s } else dir = (PWN::Sessions::SESSIONS_DIR if defined?(PWN::Sessions::SESSIONS_DIR)) || File.join(Dir.home, '.pwn', 'sessions') Dir[File.join(dir, '*.jsonl')].sort_by { |f| -File.mtime(f).to_i }.first(limit * 2).map { |f| File.basename(f, '.jsonl') } end scored = [] sids.first(limit * 3).each do |sid| break if scored.length >= limit t = begin PWN::Sessions.load(session_id: sid) rescue StandardError [] end next if t.nil? || t.empty? mtime = begin path = File.join( (PWN::Sessions::SESSIONS_DIR if defined?(PWN::Sessions::SESSIONS_DIR)) || File.join(Dir.home, '.pwn', 'sessions'), "#{sid}.jsonl" ) File.exist?(path) ? File.mtime(path).utc : nil rescue StandardError nil end next if mtime && mtime < cutoff if commit && defined?(Learning) prior = Learning.outcomes(limit: 500).find do |o| o[:session_id].to_s == sid.to_s && !o[:training_score].nil? && Array(o[:tags]).include?('offline_judge') end next if prior end user = t.reverse.find { |e| e[:role].to_s == 'user' } final = t.reverse.find { |e| e[:role].to_s == 'assistant' && !e[:content].to_s.start_with?('PLAN:') } next unless user && final req = user[:content].to_s fin = final[:content].to_s next if req.strip.empty? || fin.strip.empty? v = Reward.judge(request: req, final: fin, session_id: sid, commit: commit) known = !v[:training_score].nil? Reward.prm(request: req, session_id: sid) if do_prm && commit && known # P7/W3 — offline path must also fill calibration so the controller # (force plan_first/critic at n≥8) actually becomes reachable under # :failure_only local introspect. Pull p(success)= out of any PLAN. if commit && known plan = t.find { |e| e[:role].to_s == 'assistant' && e[:content].to_s.start_with?('PLAN:') } pred = plan && plan[:content].to_s[/p\(success\)\s*=\s*([01](?:\.\d+)?)/i, 1] if pred eng = (PWN::Env.dig(:ai, :active) if defined?(PWN::Env)) calibrate(predicted: pred.to_f, actual: v[:success] ? 1.0 : 0.0, engine: eng) end end if commit && defined?(Learning) verd = v[:verdict].to_s Learning.note_outcome( task: req[0, 120], outcome: v, details: "offline_judge #{verd}(#{v[:score]}) #{v[:rationale]}", session_id: sid, tags: ['offline_judge', 'auto', verd], judge_source: v[:source] ) end scored << v.merge(session_id: sid) end mean = scored.empty? ? nil : (scored.sum { |r| r[:score].to_f } / scored.length).round(3) # P10 — keep R3 window warm so proxy_distrust can engage on local hosts warm = (Reward.warm_sentinel(limit: 120) if commit && defined?(Reward) && Reward.respond_to?(:warm_sentinel)) # P0 ops — nightly ledger hygiene so generator_mix success criteria can # fire: drop prose flood, backfill missing shapes, then snapshot mix+KPI. scrub = nil mix = nil kpi = nil if commit && defined?(Reward) scrub = Reward.scrub_preferences(dry_run: false) if Reward.respond_to?(:scrub_preferences) mix = Reward.generator_mix if Reward.respond_to?(:generator_mix) end rec = { reclassified: 0 } rec = reclassify_backlog if commit && respond_to?(:reclassify_backlog) kpi = practice_kpi(results: [], reclassified_n: rec[:reclassified]) if commit && respond_to?(:practice_kpi) out = { scored: scored.length, mean: mean, since_hours: since_h, results: scored.first(10), sentinel_warm: warm, scrub: scrub, generator_mix: mix, practice_kpi: kpi } log(event: :offline_judge, data: out.except(:results)) out rescue StandardError => e { error: "#{e.class}: #{e.}" } end |
.practice(opts = {}) ⇒ Object
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 |
# File 'lib/pwn/ai/agent/curriculum.rb', line 81 public_class_method def self.practice(opts = {}) limit = (opts[:limit] || 3).to_i per = (opts[:prompts_per] || 2).to_i dry_run = opts[:dry_run] ? true : false return { skipped: 'recursion guard' } if in_curriculum? FileUtils.mkdir_p(CURRICULUM_DIR) # 2.4 / 2.5 / P1 — skip reward_signal + needs_code_change / parked # + cooldown thrash + needs_human. Over-fetch so filters still fill. fetch_n = [limit * 4, 12].max candidates = if defined?(Mistakes) Mistakes.top(limit: fetch_n, unresolved_only: true, practiceable_only: true) else [] end cool = load_cooldown candidates = candidates.sort_by { |m| -m[:count].to_i } targets = candidates.reject { |m| practice_skip?(mistake: m, cooldown: cool) }.first(limit) results = [] with_curriculum_guard do targets.each do |m| next if practice_skip?(mistake: m, cooldown: cool) prompts = generate_reproducers(mistake: m, count: [per, 2].max) runs = dry_run ? [] : prompts.map { |p| self_play(prompt: p, tag: "practice:#{m[:signature]}") } solved = runs.select { |r| r[:success] == true && !r[:training_score].nil? } scored = runs.reject { |r| r[:training_score].nil? } mean = scored.empty? ? nil : (scored.sum { |r| r[:training_score].to_f } / scored.length) resolved = false # 2.4 — auto-resolve only with N≥2 holdout successes + store trace # P23 — auto-resolve only with N≥2 trusted holdout successes AND a # real tool trace (not empty-final luck). Budget fingerprints # additionally require mean holdout ≥0.7 and short-horizon tags. if solved.length >= 2 && defined?(Mistakes) best = solved.max_by { |r| r[:score] } winning = best[:trace].to_s.strip winning = best[:final].to_s.strip if winning.length < 20 budgetish = %w[agent_loop assistant_answer].include?(m[:tool].to_s) || m[:error].to_s.downcase.include?('budget') # refuse resolve on budget targets when winning_trace is prose-only trace_ok = winning.length >= 20 && ( !budgetish || winning.match?(/→|shell|pwn_eval|tool/i) || best[:final].to_s.length.between?(1, 800) ) poc_ok = if budgetish || %w[agent_loop assistant_answer].include?(m[:tool].to_s) practice_poc_ok?(run: best) else true end unless trace_ok && poc_ok bump_cooldown!(cooldown: cool, signature: m[:signature], mean: mean) unless dry_run results << { signature: m[:signature], tool: m[:tool], prompts: prompts, runs: runs, resolved: false, mean_score: mean.round(3), reason: 'holdouts_ok_but_trace_weak' } next end fix = best[:final].to_s.lines.first(3).join.strip[0, 400] Mistakes.resolve( signature: m[:signature], fix: "auto-curriculum: #{fix}", structured: { strategy: budgetish ? 'short_horizon_finish' : 'curriculum_practice', tool: m[:tool], holdout_tests: solved.map { |r| r[:prompt] || r[:request] }.compact.first(5), winning_trace: winning[0, 2_000] } ) # P14 — trajectory-shaped curriculum pair (not first-3-lines fix prose). # Mistakes.resolve also lands a mistakes_resolve pair via winning_trace; # this :curriculum row keeps W1 source diversity honest. if defined?(Reward) rejected = m[:snippet].to_s rejected = "FAILING: tool=#{m[:tool]} err=#{m[:error]}" if rejected.strip.empty? chosen = if best[:trace].to_s.strip.length >= 20 parts = [] parts << "STRATEGY: curriculum_practice | #{m[:tool]}" parts << "WINNING_TRACE:\n#{best[:trace].to_s[0, 3_000]}" parts << "FINAL:\n#{best[:final].to_s[0, 800]}" unless best[:final].to_s.strip.empty? parts.join("\n") else best[:final].to_s[0, 3_500] end Reward.record_preference( prompt: (best[:prompt] || prompts.first).to_s, rejected: rejected[0, 2_000], chosen: chosen, source: :curriculum, shape: :winning_trace, meta: { signature: m[:signature], score: best[:score], holdouts: solved.length } ) end resolved = true cool.delete(m[:signature].to_s) elsif !dry_run && !mean.nil? # P1 — track zero-progress nights; park after COOLDOWN_FAIL_NIGHTS bump_cooldown!(cooldown: cool, signature: m[:signature], mean: mean) end results << { signature: m[:signature], tool: m[:tool], prompts: prompts, runs: runs, resolved: resolved, mean_score: mean&.round(3) } end end save_cooldown(cooldown: cool) log(event: :practice, data: results) kpi = practice_kpi(results: results) { practiced: results.length, resolved: results.count { |r| r[:resolved] }, skipped_cooldown: cool.count { |_, v| v[:fail_nights].to_i >= COOLDOWN_FAIL_NIGHTS }, skipped_parked: (defined?(Mistakes) && Mistakes.respond_to?(:operator_inbox) ? Mistakes.operator_inbox[:count] : 0), operator_inbox: (defined?(Mistakes) && Mistakes.respond_to?(:operator_inbox) ? Mistakes.operator_inbox[:items] : []), results: results, dry_run: dry_run, kpi: kpi, generator_mix: (defined?(Reward) && Reward.respond_to?(:generator_mix) ? Reward.generator_mix : nil) } rescue StandardError => e { error: "#{e.class}: #{e.}" } end |
.practice_kpi(opts = {}) ⇒ Object
699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 |
# File 'lib/pwn/ai/agent/curriculum.rb', line 699 public_class_method def self.practice_kpi(opts = {}) results = Array(opts[:results]) top = defined?(Mistakes) ? Mistakes.top(limit: 50, unresolved_only: true) : [] repeating = top.select { |m| m[:count].to_i >= 3 } budgetish = repeating.count do |m| t = m[:tool].to_s e = m[:error].to_s.downcase t == 'agent_loop' || t == 'assistant_answer' || e.include?('budget') || e.include?('iteration budget') end row = { at: Time.now.utc.iso8601, unresolved_total: top.length, repeating_n: repeating.length, repeating_sum_count: repeating.sum { |m| m[:count].to_i }, budget_repeating_n: budgetish, practiced: results.length, resolved_tonight: results.count { |r| r[:resolved] }, reclassified_n: (opts[:reclassified_n] || 0).to_i, mean_holdout: begin hold = results.map { |r| r[:mean_score] || r[:score] }.compact hold = Learning.outcomes(limit: 20).filter_map { |o| o[:score] } if hold.empty? && defined?(Learning) hold.empty? ? 0.0 : (hold.sum(&:to_f) / hold.length).round(3) end } begin FileUtils.mkdir_p(File.dirname(KPI_FILE)) File.open(KPI_FILE, 'a') { |f| f.puts(JSON.generate(row)) } rescue StandardError nil end trend = repeating_trend row.merge(trend: trend) rescue StandardError => e { error: "#{e.class}: #{e.}" } end |
.preference_balance(opts = {}) ⇒ Object
P5 — W1 diversity report so monoculture is visible before DPO export.
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 |
# File 'lib/pwn/ai/agent/curriculum.rb', line 337 public_class_method def self.preference_balance(opts = {}) return { total: 0 } unless defined?(Reward) # P15 — prefer Reward.preference_balance (geometry-aware + optional scrub). if Reward.respond_to?(:preference_balance) return Reward.preference_balance( limit: opts[:limit] || 10_000, scrub: opts.key?(:scrub) ? opts[:scrub] : false ) end rows = Reward.preferences(limit: opts[:limit] || 10_000) by = Hash.new(0) rows.each { |r| by[r[:source].to_s] += 1 } total = rows.length frac = by.transform_values { |n| total.zero? ? 0.0 : (n.to_f / total).round(3) } monoculture = total.positive? && (by.values.max.to_f / total) > 0.7 { total: total, by_source: by, fractions: frac, monoculture: monoculture, advice: if monoculture 'W1 monoculture: enable :counterfactual/:critic or loosen S2 gates; DPO will overfit mistakes_resolve prose.' else 'W1 source mix OK' end } rescue StandardError => e { error: "#{e.class}: #{e.}" } end |
.reclassify_backlog(opts = {}) ⇒ Object
665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 |
# File 'lib/pwn/ai/agent/curriculum.rb', line 665 public_class_method def self.reclassify_backlog(opts = {}) rows = defined?(Mistakes) ? Mistakes.top(limit: opts[:limit] || 80, unresolved_only: true) : [] inbox = if defined?(Mistakes) && Mistakes.respond_to?(:operator_inbox) Array(Mistakes.operator_inbox(limit: 80)[:items] || Mistakes.operator_inbox(limit: 80)[:rows]) else [] end counts = { fixable_by_agent: 0, needs_code_change: 0, wontfix_obsolete: 0, reclassified: 0 } now = Time.now.utc (rows + inbox).uniq { |m| m[:signature] }.each do |m| next unless m.is_a?(Hash) err = m[:error].to_s age_d = begin (now - Time.parse(m[:last_seen].to_s)) / 86_400.0 rescue StandardError 0.0 end obsolete = err.match?(/PATH=|utf-8|invalid byte|generator/i) || (age_d > 7 && m[:count].to_i <= 1) if obsolete || (m[:parked] && age_d > 7) Mistakes.park(signature: m[:signature], reason: 'wontfix_obsolete') if defined?(Mistakes) && Mistakes.respond_to?(:park) counts[:wontfix_obsolete] += 1 counts[:reclassified] += 1 elsif m[:needs_code_change] counts[:needs_code_change] += 1 else counts[:fixable_by_agent] += 1 end end counts rescue StandardError => e { error: "#{e.class}: #{e.}" } end |
.red_team_plan(opts = {}) ⇒ Object
- Supported Method Parameters
hint = PWN::AI::Agent::Curriculum.red_team_plan( request: 'required - user goal', plan: 'required - numbered plan text from plan_first' )
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 |
# File 'lib/pwn/ai/agent/curriculum.rb', line 505 public_class_method def self.red_team_plan(opts = {}) return nil unless enabled?(key: :red_team_plan) return nil if in_curriculum? # P17 — never nest a red-team persona loop when budget_exhaustion # fingerprints dominate open mistakes (amplifier of agent_loop ×N). begin if defined?(Loop) && Loop.respond_to?(:budget_exhaustion_hot?, true) && Loop.send(:budget_exhaustion_hot?) return nil end rescue StandardError # fall through end ensure_persona(name: RED_TEAM_NAME, role: 'You are pwn-ai\'s adversarial plan reviewer. Given a numbered tool plan and telemetry from THIS host (tool success rates, known mistakes, environment drift), identify the ONE step most likely to fail and say why in ≤2 lines. Cite the metric/mistake/drift. If the plan is sound reply: SOUND.') telemetry = build_telemetry reply = with_curriculum_guard do ask_persona(name: RED_TEAM_NAME, request: "GOAL: #{opts[:request].to_s[0, 300]}\n\nPLAN:\n#{opts[:plan].to_s[0, 1_200]}\n\nHOST TELEMETRY:\n#{telemetry}", text_only: true) end return nil if reply.to_s.strip.upcase.start_with?('SOUND') || reply.to_s.strip.empty? "[pwn-ai/red_team] pre-emptive: #{reply.to_s.strip[0, 400]}" rescue StandardError => e warn "[pwn-ai/curriculum] red_team_plan swallowed: #{e.class}: #{e.}" nil end |
.repeating_trend(opts = {}) ⇒ Object
Week-over-week (or last-N snapshots) delta on repeating_n. Positive delta_repeating = getting worse; negative = practice working.
738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 |
# File 'lib/pwn/ai/agent/curriculum.rb', line 738 public_class_method def self.repeating_trend(opts = {}) limit = (opts[:limit] || 14).to_i return { samples: 0, delta_repeating: nil, status: :no_data } unless File.exist?(KPI_FILE) rows = File.readlines(KPI_FILE).last(limit).filter_map do |l| JSON.parse(l, symbolize_names: true) rescue StandardError nil end return { samples: 0, delta_repeating: nil, status: :no_data } if rows.empty? return { samples: rows.length, delta_repeating: 0, status: :baseline, latest: rows.last } if rows.length < 2 first = rows.first last = rows.last d_rep = last[:repeating_n].to_i - first[:repeating_n].to_i d_budget = last[:budget_repeating_n].to_i - first[:budget_repeating_n].to_i status = if d_rep <= -2 then :improving elsif d_rep >= 2 then :regressing else :flat end { samples: rows.length, from: first[:at], to: last[:at], delta_repeating: d_rep, delta_budget_repeating: d_budget, latest_repeating_n: last[:repeating_n], status: status } rescue StandardError => e { samples: 0, status: :error, error: "#{e.class}: #{e.}" } end |
.train_and_gate(opts = {}) ⇒ Object
- Supported Method Parameters
r = PWN::AI::Agent::Curriculum.train_and_gate( base_model: 'optional - ollama base tag (default PWN::Env[:ollama][:model])', trainer: 'optional - :unsloth | :axolotl | :auto (default :auto)', dry_run: 'optional - export + build eval set but do not train (default true)' )
Best-effort orchestrator. When a supported trainer is installed it produces ~/.pwn/finetune/pwn-vN/, cuts an ollama Modelfile with the LoRA adapter, then REPLAYS Mistakes.top against vN and vN+1 under Reward.judge. Promotes (writes MODELS_FILE) iff vN+1 resolves more signatures. When no trainer is present it still exports SFT+DPO and emits the exact CLI to run manually — so the pipeline is complete even on a box without GPU.
577 578 579 580 581 582 583 584 585 586 587 588 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 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 |
# File 'lib/pwn/ai/agent/curriculum.rb', line 577 public_class_method def self.train_and_gate(opts = {}) dry_run = if opts.key?(:dry_run) opts[:dry_run] else mix = defined?(Reward) && Reward.respond_to?(:generator_mix) ? Reward.generator_mix : {} healthy = mix.is_a?(Hash) && mix[:healthy] == true cal_ok = defined?(Metrics) && Metrics.respond_to?(:calibration_green?) && Metrics.calibration_green? !(healthy && cal_ok) end FileUtils.mkdir_p(CURRICULUM_DIR) sft = defined?(Learning) ? Learning.export_finetune(format: :sharegpt) : nil dpo = defined?(Reward) ? Reward.export_dpo : nil evalset = build_eval_set state = load_models version = state[:current].to_i + 1 base = opts[:base_model] || (PWN::Env.dig(:ai, :ollama, :model) if defined?(PWN::Env)) || 'llama3' trainer = detect_trainer(preference: opts[:trainer]) result = { version: version, base: base, trainer: trainer, sft: sft, dpo: dpo, eval_prompts: evalset.length, dry_run: dry_run } if dry_run || trainer.nil? result[:export_only] = true result[:weight_loop] = :export_ready result[:advice] = if trainer.nil? 'No trainer found — weight loop is EXPORT-ONLY on this host. ' \ 'Install unsloth or axolotl on a GPU box, then re-run with dry_run:false. ' \ "Datasets ready at #{sft&.[](:path)} + #{dpo&.[](:path)}." else 'dry_run — datasets + eval set exported; pass dry_run:false to train+gate+promote.' end result[:manual_cli] = manual_train_cli(base: base, sft: sft, dpo: dpo, version: version) # P5 — surface W1 monoculture beside the export so operators see it result[:preference_balance] = begin preference_balance rescue StandardError nil end log(event: :train_and_gate, data: result) return result end adapter = run_trainer(trainer: trainer, base: base, sft: sft, dpo: dpo, version: version) return result.merge(error: 'trainer produced no adapter') unless adapter candidate = ollama_create(base: base, adapter: adapter, version: version) baseline = state[:tag] || base # P11 — gate v2: resolved delta + mean judge + frozen smoke set. gate = ab_gate_v2(baseline: baseline, candidate: candidate, evalset: evalset) # P19 — refuse promote when W1 diet is still prose/monoculture. # Export-only is correct until scrubbed pairs show trajectory diversity. diet = preference_diet_gate gate = gate.merge(preference_diet: diet) promoted = gate[:promote] == true && diet[:ok] == true gate[:promote] = promoted gate[:promote_blocked_by_diet] = true unless diet[:ok] if promoted state[:previous] = state[:tag] state[:tag] = candidate state[:current] = version state[:promoted_at] = Time.now.utc.iso8601 state[:gate] = gate save_models(state: state) end result.merge(adapter: adapter, candidate: candidate, gate: gate, promoted: promoted, weight_loop: :closed) rescue StandardError => e { error: "#{e.class}: #{e.}" } end |