pwn 0.5.795 → 0.5.798

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (384) hide show
  1. checksums.yaml +4 -4
  2. data/Gemfile +8 -8
  3. data/bin/pwn_autoinc_version +4 -5
  4. data/bin/pwn_web_cache_deception +40 -29
  5. data/documentation/AWS.md +15 -5
  6. data/documentation/Diagrams.md +1 -1
  7. data/documentation/Home.md +2 -2
  8. data/documentation/How-PWN-Works.md +1 -1
  9. data/documentation/Mission-Cancellation.md +6 -4
  10. data/documentation/Operability.md +1 -1
  11. data/documentation/What-is-PWN.md +1 -1
  12. data/documentation/diagrams/aws-cloud-security.svg +1 -1
  13. data/documentation/diagrams/dot/aws-cloud-security.dot +1 -1
  14. data/documentation/diagrams/dot/network-infra-testing.dot +1 -1
  15. data/documentation/diagrams/network-infra-testing.svg +1 -1
  16. data/etc/default_cron/session_cleanup.rb +84 -51
  17. data/etc/default_skills/pwn/ai/agent/mission_namespace/SKILL.md +6 -4
  18. data/lib/pwn/ai/agent/assembly.rb +0 -2
  19. data/lib/pwn/ai/agent/btc.rb +0 -2
  20. data/lib/pwn/ai/agent/burp_suite.rb +0 -2
  21. data/lib/pwn/ai/agent/curriculum.rb +2 -2
  22. data/lib/pwn/ai/agent/dispatch.rb +3 -0
  23. data/lib/pwn/ai/agent/engagement.rb +96 -41
  24. data/lib/pwn/ai/agent/extrospection/osint/bridges.rb +2 -0
  25. data/lib/pwn/ai/agent/extrospection.rb +50 -13
  26. data/lib/pwn/ai/agent/gqrx.rb +0 -2
  27. data/lib/pwn/ai/agent/hacker_one.rb +0 -2
  28. data/lib/pwn/ai/agent/learning.rb +45 -13
  29. data/lib/pwn/ai/agent/loop.rb +16 -11
  30. data/lib/pwn/ai/agent/metrics.rb +1 -1
  31. data/lib/pwn/ai/agent/mission.rb +6 -3
  32. data/lib/pwn/ai/agent/mission_namespace.rb +70 -14
  33. data/lib/pwn/ai/agent/policy.rb +1 -1
  34. data/lib/pwn/ai/agent/policy_evaluation.rb +2 -2
  35. data/lib/pwn/ai/agent/reflect.rb +1 -0
  36. data/lib/pwn/ai/agent/request_runtime.rb +1 -1
  37. data/lib/pwn/ai/agent/reward.rb +155 -53
  38. data/lib/pwn/ai/agent/sast.rb +0 -2
  39. data/lib/pwn/ai/agent/task_dag.rb +5 -3
  40. data/lib/pwn/ai/agent/task_summarizer.rb +21 -11
  41. data/lib/pwn/ai/agent/tool_guard.rb +19 -0
  42. data/lib/pwn/ai/agent/tools/ruby_eval.rb +1 -1
  43. data/lib/pwn/ai/agent/tools/verify.rb +7 -3
  44. data/lib/pwn/ai/agent/transparent_browser.rb +0 -2
  45. data/lib/pwn/ai/agent/turn_finalizer.rb +3 -0
  46. data/lib/pwn/ai/anthropic.rb +3 -3
  47. data/lib/pwn/ai/context.rb +2 -1
  48. data/lib/pwn/ai/gemini.rb +7 -5
  49. data/lib/pwn/ai/grok.rb +37 -18
  50. data/lib/pwn/ai/mcp.rb +17 -5
  51. data/lib/pwn/ai/ollama.rb +76 -35
  52. data/lib/pwn/ai/open_ai.rb +7 -19
  53. data/lib/pwn/ai/open_web_ui.rb +76 -40
  54. data/lib/pwn/aws/cloud_search_domain.rb +6 -0
  55. data/lib/pwn/aws/iam.rb +2 -2
  56. data/lib/pwn/aws/workspaces.rb +2 -2
  57. data/lib/pwn/aws.rb +0 -5
  58. data/lib/pwn/bounty/lifecycle_authz_replay.rb +1 -1
  59. data/lib/pwn/config.rb +17 -10
  60. data/lib/pwn/corpus.rb +33 -5
  61. data/lib/pwn/cron.rb +60 -17
  62. data/lib/pwn/driver.rb +2 -3
  63. data/lib/pwn/engagement.rb +28 -10
  64. data/lib/pwn/ffi/capstone.rb +3 -2
  65. data/lib/pwn/ffi/fftw.rb +8 -6
  66. data/lib/pwn/ffi/keystone.rb +3 -2
  67. data/lib/pwn/ffi/soapy_sdr.rb +10 -6
  68. data/lib/pwn/json_text.rb +25 -13
  69. data/lib/pwn/memory_index.rb +6 -4
  70. data/lib/pwn/module_skills.rb +3 -1
  71. data/lib/pwn/plugins/aflplusplus.rb +1 -0
  72. data/lib/pwn/plugins/ai_sandbox.rb +42 -10
  73. data/lib/pwn/plugins/android.rb +429 -466
  74. data/lib/pwn/plugins/artifact_registry.rb +12 -2
  75. data/lib/pwn/plugins/assembly.rb +9 -42
  76. data/lib/pwn/plugins/authentication_helper.rb +4 -3
  77. data/lib/pwn/plugins/baresip.rb +70 -28
  78. data/lib/pwn/plugins/binary_analysis.rb +14 -5
  79. data/lib/pwn/plugins/binary_parser.rb +42 -7
  80. data/lib/pwn/plugins/black_duck_binary_analysis.rb +3 -3
  81. data/lib/pwn/plugins/burp_suite.rb +15 -12
  82. data/lib/pwn/plugins/bus_pirate.rb +3 -7
  83. data/lib/pwn/plugins/char.rb +9 -3
  84. data/lib/pwn/plugins/credit_card.rb +7 -0
  85. data/lib/pwn/plugins/dao_ldap.rb +2 -2
  86. data/lib/pwn/plugins/dao_mongo.rb +1 -1
  87. data/lib/pwn/plugins/debugger.rb +1 -1
  88. data/lib/pwn/plugins/defect_dojo.rb +7 -3
  89. data/lib/pwn/plugins/detect_os.rb +1 -1
  90. data/lib/pwn/plugins/detonate.rb +9 -19
  91. data/lib/pwn/plugins/exploit_db.rb +1 -1
  92. data/lib/pwn/plugins/file_fu.rb +4 -1
  93. data/lib/pwn/plugins/findings.rb +76 -2
  94. data/lib/pwn/plugins/fuzz.rb +12 -3
  95. data/lib/pwn/plugins/gdb.rb +7 -2
  96. data/lib/pwn/plugins/gdbmi.rb +10 -6
  97. data/lib/pwn/plugins/git.rb +18 -13
  98. data/lib/pwn/plugins/github.rb +11 -6
  99. data/lib/pwn/plugins/google_workspace.rb +11 -3
  100. data/lib/pwn/plugins/hacker_one.rb +5 -1
  101. data/lib/pwn/plugins/httpx.rb +24 -8
  102. data/lib/pwn/plugins/ip_info.rb +11 -8
  103. data/lib/pwn/plugins/irc.rb +73 -45
  104. data/lib/pwn/plugins/jenkins.rb +2 -2
  105. data/lib/pwn/plugins/jira_data_center.rb +13 -6
  106. data/lib/pwn/plugins/jobs.rb +62 -4
  107. data/lib/pwn/plugins/log.rb +1 -1
  108. data/lib/pwn/plugins/monkey_patch.rb +1 -1
  109. data/lib/pwn/plugins/msr206.rb +157 -182
  110. data/lib/pwn/plugins/nessus_cloud.rb +2 -2
  111. data/lib/pwn/plugins/nexpose_vuln_scan.rb +44 -33
  112. data/lib/pwn/plugins/nuclei.rb +24 -8
  113. data/lib/pwn/plugins/ocr.rb +3 -1
  114. data/lib/pwn/plugins/open_api.rb +0 -4
  115. data/lib/pwn/plugins/openvas.rb +31 -43
  116. data/lib/pwn/plugins/packet.rb +40 -25
  117. data/lib/pwn/plugins/pony.rb +2 -2
  118. data/lib/pwn/plugins/preflight_checker.rb +1 -1
  119. data/lib/pwn/plugins/process_tube.rb +17 -2
  120. data/lib/pwn/plugins/ps.rb +6 -1
  121. data/lib/pwn/plugins/pwn_logger.rb +37 -1
  122. data/lib/pwn/plugins/repl/ai.rb +1 -0
  123. data/lib/pwn/plugins/repl/ai_console.rb +18 -6
  124. data/lib/pwn/plugins/repl/mesh.rb +51 -28
  125. data/lib/pwn/plugins/sbom.rb +59 -27
  126. data/lib/pwn/plugins/scannable_codes.rb +3 -1
  127. data/lib/pwn/plugins/serial.rb +102 -44
  128. data/lib/pwn/plugins/shodan.rb +4 -10
  129. data/lib/pwn/plugins/sock.rb +16 -11
  130. data/lib/pwn/plugins/ssn.rb +3 -1
  131. data/lib/pwn/plugins/transparent_browser.rb +43 -3
  132. data/lib/pwn/plugins/vault.rb +92 -30
  133. data/lib/pwn/plugins/vin.rb +2 -1
  134. data/lib/pwn/plugins/vsphere.rb +2 -1
  135. data/lib/pwn/plugins/xxd.rb +3 -5
  136. data/lib/pwn/plugins/yubikey/security_domain/scp.rb +4 -0
  137. data/lib/pwn/plugins/yubikey/transport.rb +42 -11
  138. data/lib/pwn/plugins/yubikey.rb +21 -6
  139. data/lib/pwn/plugins/zaproxy.rb +3 -4
  140. data/lib/pwn/reports/ai_red_team.rb +4 -4
  141. data/lib/pwn/reports/pdf.rb +9 -5
  142. data/lib/pwn/reports/sast.rb +4 -4
  143. data/lib/pwn/sast/keystore.rb +2 -2
  144. data/lib/pwn/sast/logger.rb +1 -1
  145. data/lib/pwn/sast/php_type_juggling.rb +3 -6
  146. data/lib/pwn/sast/pom_version.rb +12 -6
  147. data/lib/pwn/sast/port.rb +1 -1
  148. data/lib/pwn/sast/sql.rb +3 -7
  149. data/lib/pwn/sast/test_case_engine.rb +62 -16
  150. data/lib/pwn/sast/type_script_type_juggling.rb +3 -6
  151. data/lib/pwn/sdr/decoder/base.rb +8 -0
  152. data/lib/pwn/sdr/decoder/lora.rb +1 -1
  153. data/lib/pwn/sdr/flipper_zero.rb +4 -7
  154. data/lib/pwn/sdr/gqrx.rb +35 -16
  155. data/lib/pwn/sdr/son_micro_rfid.rb +44 -26
  156. data/lib/pwn/sdr.rb +1 -1
  157. data/lib/pwn/session_trace.rb +7 -2
  158. data/lib/pwn/sessions.rb +310 -41
  159. data/lib/pwn/setup.rb +4 -3
  160. data/lib/pwn/version.rb +1 -1
  161. data/lib/pwn/www/app_cobalt_io.rb +14 -2
  162. data/lib/pwn/www/bing.rb +13 -1
  163. data/lib/pwn/www/bug_crowd.rb +14 -2
  164. data/lib/pwn/www/checkip.rb +13 -1
  165. data/lib/pwn/www/coinbase_pro.rb +14 -2
  166. data/lib/pwn/www/duckduckgo.rb +13 -1
  167. data/lib/pwn/www/facebook.rb +14 -2
  168. data/lib/pwn/www/github.rb +14 -2
  169. data/lib/pwn/www/google.rb +13 -1
  170. data/lib/pwn/www/hacker_one.rb +117 -33
  171. data/lib/pwn/www/linkedin.rb +14 -2
  172. data/lib/pwn/www/pandora.rb +14 -2
  173. data/lib/pwn/www/pastebin.rb +13 -1
  174. data/lib/pwn/www/paypal.rb +16 -4
  175. data/lib/pwn/www/synack.rb +14 -2
  176. data/lib/pwn/www/torch.rb +17 -3
  177. data/lib/pwn/www/trading_view.rb +14 -2
  178. data/lib/pwn/www/twitter.rb +14 -2
  179. data/lib/pwn/www/uber.rb +14 -2
  180. data/lib/pwn/www/upwork.rb +14 -2
  181. data/lib/pwn/www/wayback_machine.rb +16 -2
  182. data/lib/pwn/www/youtube.rb +13 -1
  183. data/lib/pwn.rb +11 -0
  184. data/pwn.gemspec +4 -0
  185. data/spec/conventions_spec.rb +43 -0
  186. data/spec/integration/authentication_helper_oath_spec.rb +1 -1
  187. data/spec/integration/autoinc_lifecycle_supplement_spec.rb +47 -0
  188. data/spec/integration/gemspec_deleted_files_spec.rb +43 -0
  189. data/spec/integration/harness_evaluation_spec.rb +22 -31
  190. data/spec/integration/harness_live_spec.rb +8 -18
  191. data/spec/integration/spec_curriculum_isolation_spec.rb +41 -0
  192. data/spec/integration/verify_acceptance_eui_regression_spec.rb +162 -0
  193. data/spec/integration/web_cache_lifecycle_closure_spec.rb +89 -0
  194. data/spec/integration/web_cache_lifecycle_supplement_spec.rb +70 -0
  195. data/spec/lib/pwn/ai/agent/analysis_errors_regression_spec.rb +33 -0
  196. data/spec/lib/pwn/ai/agent/curriculum_cooldown_regression_spec.rb +19 -0
  197. data/spec/lib/pwn/ai/agent/curriculum_spec.rb +2 -0
  198. data/spec/lib/pwn/ai/agent/engagement_boundary_regression_spec.rb +42 -0
  199. data/spec/lib/pwn/ai/agent/engagement_dispatch_review_spec.rb +82 -0
  200. data/spec/lib/pwn/ai/agent/engagement_roe_regression_spec.rb +25 -0
  201. data/spec/lib/pwn/ai/agent/engagement_scope_regression_spec.rb +37 -0
  202. data/spec/lib/pwn/ai/agent/extrospection/osint/bridges_spec.rb +4 -0
  203. data/spec/lib/pwn/ai/agent/extrospection_input_regression_spec.rb +31 -0
  204. data/spec/lib/pwn/ai/agent/extrospection_review_spec.rb +61 -0
  205. data/spec/lib/pwn/ai/agent/extrospection_serial_review_spec.rb +42 -0
  206. data/spec/lib/pwn/ai/agent/extrospection_spec.rb +9 -0
  207. data/spec/lib/pwn/ai/agent/extrospection_verification_regression_spec.rb +39 -0
  208. data/spec/lib/pwn/ai/agent/learning_last_answer_regression_spec.rb +32 -0
  209. data/spec/lib/pwn/ai/agent/learning_lifecycle_closure_spec.rb +84 -0
  210. data/spec/lib/pwn/ai/agent/learning_prune_regression_spec.rb +17 -0
  211. data/spec/lib/pwn/ai/agent/learning_spec.rb +2 -1
  212. data/spec/lib/pwn/ai/agent/loop_execution_audit_spec.rb +30 -0
  213. data/spec/lib/pwn/ai/agent/metrics_usage_regression_spec.rb +20 -0
  214. data/spec/lib/pwn/ai/agent/mission_execution_audit_spec.rb +27 -0
  215. data/spec/lib/pwn/ai/agent/mission_namespace_spec.rb +218 -18
  216. data/spec/lib/pwn/ai/agent/policy_confidence_regression_spec.rb +16 -0
  217. data/spec/lib/pwn/ai/agent/policy_evaluation_spec.rb +1 -1
  218. data/spec/lib/pwn/ai/agent/policy_evaluation_tmp_regression_spec.rb +36 -0
  219. data/spec/lib/pwn/ai/agent/reflect_model_regression_spec.rb +15 -0
  220. data/spec/lib/pwn/ai/agent/request_runtime_execution_audit_spec.rb +43 -0
  221. data/spec/lib/pwn/ai/agent/reward_binding_review_spec.rb +129 -0
  222. data/spec/lib/pwn/ai/agent/reward_dispatch_review_spec.rb +154 -0
  223. data/spec/lib/pwn/ai/agent/reward_envelope_regression_spec.rb +45 -0
  224. data/spec/lib/pwn/ai/agent/reward_turn_regression_spec.rb +40 -0
  225. data/spec/lib/pwn/ai/agent/swarm_spec.rb +2 -2
  226. data/spec/lib/pwn/ai/agent/task_dag_execution_audit_spec.rb +45 -0
  227. data/spec/lib/pwn/ai/agent/task_summarizer_failure_regression_spec.rb +26 -0
  228. data/spec/lib/pwn/ai/agent/tools/verify_execution_audit_spec.rb +33 -0
  229. data/spec/lib/pwn/ai/context_range_audit_spec.rb +24 -0
  230. data/spec/lib/pwn/ai/gemini_roundtrip_audit_spec.rb +33 -0
  231. data/spec/lib/pwn/ai/grok_reasoning_effort_spec.rb +43 -0
  232. data/spec/lib/pwn/ai/mcp_session_audit_spec.rb +36 -0
  233. data/spec/lib/pwn/ai/ollama_spec.rb +6 -11
  234. data/spec/lib/pwn/ai/open_web_ui_spec.rb +6 -11
  235. data/spec/lib/pwn/ai/provider_history_audit_spec.rb +44 -0
  236. data/spec/lib/pwn/ai/provider_operations_audit_spec.rb +53 -0
  237. data/spec/lib/pwn/ai/provider_review_history_stream_regression_spec.rb +143 -0
  238. data/spec/lib/pwn/ai/provider_review_tls_regression_spec.rb +62 -0
  239. data/spec/lib/pwn/ai/provider_stream_audit_spec.rb +49 -0
  240. data/spec/lib/pwn/aws/iam_decoding_regression_spec.rb +23 -0
  241. data/spec/lib/pwn/aws/services_runtime_regression_spec.rb +51 -0
  242. data/spec/lib/pwn/aws_spec.rb +6 -0
  243. data/spec/lib/pwn/banner_operational_audit_spec.rb +105 -0
  244. data/spec/lib/pwn/bounty/lifecycle_authz_replay_spec.rb +17 -0
  245. data/spec/lib/pwn/config_redaction_regression_spec.rb +24 -0
  246. data/spec/lib/pwn/config_skills_regression_spec.rb +38 -0
  247. data/spec/lib/pwn/corpus_core_review_regression_spec.rb +96 -0
  248. data/spec/lib/pwn/corpus_spec.rb +13 -0
  249. data/spec/lib/pwn/cron_core_review_regression_spec.rb +95 -0
  250. data/spec/lib/pwn/cron_execution_spec.rb +75 -0
  251. data/spec/lib/pwn/driver_core_review_regression_spec.rb +38 -0
  252. data/spec/lib/pwn/driver_spec.rb +13 -0
  253. data/spec/lib/pwn/engagement_core_review_regression_spec.rb +88 -0
  254. data/spec/lib/pwn/engagement_storage_regression_spec.rb +44 -0
  255. data/spec/lib/pwn/ffi/capstone_spec.rb +19 -0
  256. data/spec/lib/pwn/ffi/fftw_spec.rb +19 -0
  257. data/spec/lib/pwn/ffi/keystone_spec.rb +13 -0
  258. data/spec/lib/pwn/ffi/soapy_sdr_spec.rb +13 -0
  259. data/spec/lib/pwn/json_schemer_regexp_parser_spec.rb +12 -0
  260. data/spec/lib/pwn/json_text_spec.rb +25 -0
  261. data/spec/lib/pwn/memory_index_spec.rb +23 -0
  262. data/spec/lib/pwn/module_skills_parsing_regression_spec.rb +34 -0
  263. data/spec/lib/pwn/module_skills_spec.rb +11 -1
  264. data/spec/lib/pwn/plugins/ai_sandbox_boundary_review_spec.rb +57 -0
  265. data/spec/lib/pwn/plugins/ai_sandbox_spec.rb +10 -18
  266. data/spec/lib/pwn/plugins/android_review_fixes_spec.rb +121 -0
  267. data/spec/lib/pwn/plugins/android_transport_audit_spec.rb +64 -0
  268. data/spec/lib/pwn/plugins/api_import_namespace_audit_spec.rb +49 -0
  269. data/spec/lib/pwn/plugins/artifact_registry_namespace_audit_spec.rb +20 -0
  270. data/spec/lib/pwn/plugins/artifact_registry_review_fixes_spec.rb +63 -0
  271. data/spec/lib/pwn/plugins/assembly_namespace_audit_spec.rb +16 -0
  272. data/spec/lib/pwn/plugins/assembly_review_fixes_spec.rb +33 -0
  273. data/spec/lib/pwn/plugins/authentication_helper_spec.rb +14 -0
  274. data/spec/lib/pwn/plugins/baresip_review_fixes_spec.rb +127 -0
  275. data/spec/lib/pwn/plugins/baresip_transport_audit_spec.rb +59 -0
  276. data/spec/lib/pwn/plugins/binary_analysis_process_review_spec.rb +57 -0
  277. data/spec/lib/pwn/plugins/black_duck_namespace_audit_spec.rb +25 -0
  278. data/spec/lib/pwn/plugins/burp_suite_har_review_fixes_spec.rb +60 -0
  279. data/spec/lib/pwn/plugins/burp_suite_import_review_fixes_spec.rb +62 -0
  280. data/spec/lib/pwn/plugins/burp_suite_namespace_audit_spec.rb +37 -0
  281. data/spec/lib/pwn/plugins/bus_pirate_transport_audit_spec.rb +19 -0
  282. data/spec/lib/pwn/plugins/file_fu_namespace_audit_spec.rb +17 -0
  283. data/spec/lib/pwn/plugins/findings_structured_spec.rb +1 -1
  284. data/spec/lib/pwn/plugins/gdbmi_namespace_audit_spec.rb +28 -0
  285. data/spec/lib/pwn/plugins/gdbmi_review_fixes_spec.rb +73 -0
  286. data/spec/lib/pwn/plugins/github_argv_review_spec.rb +49 -0
  287. data/spec/lib/pwn/plugins/google_workspace_provider_review_oauth_spec.rb +80 -0
  288. data/spec/lib/pwn/plugins/irc_review_fixes_spec.rb +92 -0
  289. data/spec/lib/pwn/plugins/irc_transport_audit_spec.rb +37 -0
  290. data/spec/lib/pwn/plugins/jenkins_namespace_audit_spec.rb +12 -0
  291. data/spec/lib/pwn/plugins/jira_data_center_namespace_audit_spec.rb +44 -0
  292. data/spec/lib/pwn/plugins/jira_data_center_review_fixes_spec.rb +81 -0
  293. data/spec/lib/pwn/plugins/jsonl_elf_review_fixes_spec.rb +59 -0
  294. data/spec/lib/pwn/plugins/log_spec.rb +36 -20
  295. data/spec/lib/pwn/plugins/monkey_patch_spec.rb +16 -0
  296. data/spec/lib/pwn/plugins/msr206_readback_review_fixes_spec.rb +119 -0
  297. data/spec/lib/pwn/plugins/msr206_review_fixes_spec.rb +50 -0
  298. data/spec/lib/pwn/plugins/msr206_transport_audit_spec.rb +64 -0
  299. data/spec/lib/pwn/plugins/nessus_cloud_namespace_audit_spec.rb +14 -0
  300. data/spec/lib/pwn/plugins/nexpose_review_fixes_spec.rb +55 -0
  301. data/spec/lib/pwn/plugins/open_api_namespace_audit_spec.rb +22 -0
  302. data/spec/lib/pwn/plugins/packet_transport_audit_spec.rb +47 -0
  303. data/spec/lib/pwn/plugins/plugins_b_operational_regression_spec.rb +600 -0
  304. data/spec/lib/pwn/plugins/pony_namespace_audit_spec.rb +17 -0
  305. data/spec/lib/pwn/plugins/pony_review_fixes_spec.rb +33 -0
  306. data/spec/lib/pwn/plugins/process_tube_namespace_audit_spec.rb +19 -0
  307. data/spec/lib/pwn/plugins/ps_namespace_audit_spec.rb +12 -0
  308. data/spec/lib/pwn/plugins/pwn_logger_spec.rb +30 -0
  309. data/spec/lib/pwn/plugins/repl/ai_console_spec.rb +127 -0
  310. data/spec/lib/pwn/plugins/repl/ai_spec.rb +38 -0
  311. data/spec/lib/pwn/plugins/repl/mesh_spec.rb +52 -0
  312. data/spec/lib/pwn/plugins/repl_mesh_rx_errors_spec.rb +18 -0
  313. data/spec/lib/pwn/plugins/sandbox_spec.rb +9 -7
  314. data/spec/lib/pwn/plugins/sbom_review_fixes_spec.rb +43 -0
  315. data/spec/lib/pwn/plugins/scannable_codes_namespace_audit_spec.rb +15 -0
  316. data/spec/lib/pwn/plugins/serial_review_fixes_spec.rb +76 -0
  317. data/spec/lib/pwn/plugins/serial_transport_audit_spec.rb +102 -0
  318. data/spec/lib/pwn/plugins/shodan_namespace_audit_spec.rb +10 -0
  319. data/spec/lib/pwn/plugins/sock_transport_audit_spec.rb +55 -0
  320. data/spec/lib/pwn/plugins/transparent_browser_navigation_review_spec.rb +21 -0
  321. data/spec/lib/pwn/plugins/vault_master_key_eui_regression_spec.rb +242 -0
  322. data/spec/lib/pwn/plugins/vault_spec.rb +58 -0
  323. data/spec/lib/pwn/plugins/vault_store_safety_spec.rb +1 -1
  324. data/spec/lib/pwn/plugins/xxd_namespace_audit_spec.rb +34 -0
  325. data/spec/lib/pwn/plugins/yubikey_hid_cleanup_review_fixes_spec.rb +52 -0
  326. data/spec/lib/pwn/plugins/yubikey_lifecycle_audit_spec.rb +65 -0
  327. data/spec/lib/pwn/plugins/yubikey_options_audit_spec.rb +30 -0
  328. data/spec/lib/pwn/plugins/yubikey_selector_audit_spec.rb +26 -0
  329. data/spec/lib/pwn/plugins/yubikey_spec.rb +1 -1
  330. data/spec/lib/pwn/plugins/zaproxy_namespace_audit_spec.rb +30 -0
  331. data/spec/lib/pwn/reports/empty_report_audit_spec.rb +18 -0
  332. data/spec/lib/pwn/reports/pdf_spec.rb +25 -0
  333. data/spec/lib/pwn/reports/provider_review_encoding_regression_spec.rb +35 -0
  334. data/spec/lib/pwn/sast/engine_runtime_regression_spec.rb +91 -0
  335. data/spec/lib/pwn/sast/filter_edge_regression_spec.rb +39 -0
  336. data/spec/lib/pwn/sast/formatter_review_fixes_spec.rb +178 -0
  337. data/spec/lib/pwn/sast/path_review_fixes_spec.rb +60 -0
  338. data/spec/lib/pwn/sast/pom_runtime_regression_spec.rb +37 -0
  339. data/spec/lib/pwn/sast/rules_runtime_regression_spec.rb +78 -0
  340. data/spec/lib/pwn/sast/sql_review_fixes_spec.rb +38 -0
  341. data/spec/lib/pwn/sdr/decoder/base_iq_spec.rb +21 -18
  342. data/spec/lib/pwn/sdr/decoder/base_review_fixes_spec.rb +49 -0
  343. data/spec/lib/pwn/sdr/decoder/base_validation_spec.rb +78 -0
  344. data/spec/lib/pwn/sdr/decoder/lora_spec.rb +9 -0
  345. data/spec/lib/pwn/sdr/flipper_zero_review_fixes_spec.rb +34 -0
  346. data/spec/lib/pwn/sdr/gqrx_operational_spec.rb +83 -0
  347. data/spec/lib/pwn/sdr/gqrx_review_fixes_spec.rb +22 -0
  348. data/spec/lib/pwn/sdr/son_micro_rfid_review_fixes_spec.rb +113 -0
  349. data/spec/lib/pwn/sdr/son_micro_rfid_serial_review_fixes_spec.rb +76 -0
  350. data/spec/lib/pwn/sdr/son_micro_rfid_spec.rb +39 -0
  351. data/spec/lib/pwn/sdr_spec.rb +5 -0
  352. data/spec/lib/pwn/session_cleanup_concurrency_spec.rb +21 -0
  353. data/spec/lib/pwn/session_cleanup_default_spec.rb +1 -1
  354. data/spec/lib/pwn/session_cleanup_lifecycle_supplement_spec.rb +39 -0
  355. data/spec/lib/pwn/session_cleanup_payload_spec.rb +3 -2
  356. data/spec/lib/pwn/session_trace_lifecycle_supplement_spec.rb +39 -0
  357. data/spec/lib/pwn/sessions_archive_closure_spec.rb +126 -0
  358. data/spec/lib/pwn/sessions_lifecycle_closure_spec.rb +373 -0
  359. data/spec/lib/pwn/sessions_lifecycle_supplement_spec.rb +204 -0
  360. data/spec/lib/pwn/setup_operational_regression_spec.rb +36 -0
  361. data/spec/lib/pwn/www/browser_review_fixes_spec.rb +70 -0
  362. data/spec/lib/pwn/www/browser_runtime_regression_spec.rb +100 -0
  363. data/spec/lib/pwn/www/hacker_one_runtime_regression_spec.rb +146 -0
  364. data/spec/lib/pwn/www/pagination_review_fixes_spec.rb +84 -0
  365. data/spec/spec_helper.rb +34 -5
  366. data/spec/support/namespace_controller_observability_fixture.rb +141 -0
  367. data/spec/support/sandbox.rb +8 -5
  368. data/third_party/pwn_rdoc.jsonl +83 -32
  369. metadata +7690 -7386
  370. data/etc/default_skills/pwn/aws/elastic_transcoder/SKILL.md +0 -48
  371. data/etc/default_skills/pwn/aws/lambda_preview/SKILL.md +0 -48
  372. data/etc/default_skills/pwn/aws/ops_works/SKILL.md +0 -48
  373. data/etc/default_skills/pwn/aws/ops_works_cm/SKILL.md +0 -48
  374. data/etc/default_skills/pwn/aws/sms/SKILL.md +0 -48
  375. data/lib/pwn/aws/elastic_transcoder.rb +0 -95
  376. data/lib/pwn/aws/lambda_preview.rb +0 -95
  377. data/lib/pwn/aws/ops_works.rb +0 -95
  378. data/lib/pwn/aws/ops_works_cm.rb +0 -95
  379. data/lib/pwn/aws/sms.rb +0 -95
  380. data/spec/lib/pwn/aws/elastic_transcoder_spec.rb +0 -15
  381. data/spec/lib/pwn/aws/lambda_preview_spec.rb +0 -15
  382. data/spec/lib/pwn/aws/ops_works_cm_spec.rb +0 -15
  383. data/spec/lib/pwn/aws/ops_works_spec.rb +0 -15
  384. data/spec/lib/pwn/aws/sms_spec.rb +0 -15
@@ -1354,12 +1354,12 @@ module PWN
1354
1354
  # additionally knows grep exit 1 / diff exit 1 / xargs 123 are
1355
1355
  # informational. Metrics records :ok; Mistakes only records
1356
1356
  # !semantic_ok. Kills the phantom 31f1871b8a15 class permanently.
1357
- sem = defined?(Reward) ? Reward.semantic_ok(name: name, raw: raw, args: opts[:args]) : { ok: raw.include?('"success":true'), semantic_ok: raw.include?('"success":true'), err: raw[/"error":"([^"]{1,300})"/, 1] }
1357
+ sem = defined?(Reward) ? Reward.semantic_ok(name: name, raw: raw, args: opts[:args]) : { ok: nil, semantic_ok: nil, err: nil, shape: :unknown }
1358
1358
  dur = started ? (Time.now - started) : 0.0
1359
1359
  # 1.2 — align Metrics proxy with R4 semantic_ok (handler-ok alone
1360
1360
  # was the reward-signal lie: grep exit 1 looked like 100% success
1361
1361
  # while Mistakes stayed quiet, OR the inverse phantom class).
1362
- Metrics.record(name: name, success: sem[:semantic_ok], duration: dur, error: sem[:err], engine: opts[:engine]) if defined?(Metrics)
1362
+ Metrics.record(name: name, success: sem[:semantic_ok], duration: dur, error: sem[:err], engine: opts[:engine]) if defined?(Metrics) && !sem[:semantic_ok].nil?
1363
1363
  # R5 — live MDP step. Hygiene reward only; terminal credit is judge.
1364
1364
  if defined?(PWN::AI::Agent::Policy) && Policy.respond_to?(:observe_step)
1365
1365
  policy_args = begin
@@ -1382,7 +1382,7 @@ module PWN
1382
1382
  )
1383
1383
  end
1384
1384
  m = nil
1385
- if !sem[:semantic_ok] && defined?(Mistakes) && sem[:shape].to_s != 'invalid_payload' && !raw.include?('extinguished_repeat')
1385
+ if sem[:semantic_ok] == false && defined?(Mistakes) && sem[:shape].to_s != 'invalid_payload' && !raw.include?('extinguished_repeat')
1386
1386
  cause = attribute_cause(name: name)
1387
1387
  err = sem[:err] || raw[0, 300]
1388
1388
  shape = sem[:shape]
@@ -1690,6 +1690,10 @@ module PWN
1690
1690
  Thread.current[:pwn_plan_predicted] = predicted
1691
1691
  predicted
1692
1692
  rescue StandardError => e
1693
+ # A forbidden request is not a missing plan. Stop before calling the
1694
+ # provider a second time with tools enabled.
1695
+ raise if e.respond_to?(:http_code) && e.http_code == 403
1696
+
1693
1697
  warn "[pwn-ai/loop] plan_first swallowed: #{e.class}: #{e.message}"
1694
1698
  nil
1695
1699
  end
@@ -2873,6 +2877,7 @@ module PWN
2873
2877
  private_class_method def self.answer_recall(opts = {})
2874
2878
  request = opts[:request].to_s
2875
2879
  session_id = opts[:session_id]
2880
+ source_session_id = session_id
2876
2881
  system_role_content = opts[:system_role_content].to_s
2877
2882
  target = recall_target(request: request)
2878
2883
  last_session = request.match?(LAST_SESSION_RX)
@@ -2885,7 +2890,7 @@ module PWN
2885
2890
  return txt
2886
2891
  end
2887
2892
 
2888
- session_id = prev
2893
+ source_session_id = prev
2889
2894
  end
2890
2895
 
2891
2896
  prior_user = nil
@@ -2901,20 +2906,20 @@ module PWN
2901
2906
  pair =
2902
2907
  if match == :non_meta || match.nil?
2903
2908
  PWN::Memory.find_turn_pair(
2904
- session_id: session_id,
2909
+ session_id: source_session_id,
2905
2910
  skip_meta: true,
2906
2911
  pairs: 12,
2907
2912
  max_chars: 4_000
2908
2913
  )
2909
2914
  else
2910
2915
  PWN::Memory.find_turn_pair(
2911
- session_id: session_id,
2916
+ session_id: source_session_id,
2912
2917
  match: match,
2913
2918
  skip_meta: true,
2914
2919
  pairs: 12,
2915
2920
  max_chars: 4_000
2916
2921
  ) || PWN::Memory.find_turn_pair(
2917
- session_id: session_id,
2922
+ session_id: source_session_id,
2918
2923
  skip_meta: true,
2919
2924
  pairs: 12,
2920
2925
  max_chars: 4_000
@@ -2931,19 +2936,19 @@ module PWN
2931
2936
  # original utterance when appropriate; default stays newest.
2932
2937
  skip_meta = target == :assistant || last_session
2933
2938
  prior_user = PWN::Memory.prior_user_message(
2934
- session_id: session_id,
2939
+ session_id: source_session_id,
2935
2940
  max_chars: 4_000,
2936
2941
  skip_meta: skip_meta,
2937
2942
  pairs: 8
2938
2943
  )
2939
2944
  prior_asst = PWN::Memory.prior_assistant_message(
2940
- session_id: session_id,
2945
+ session_id: source_session_id,
2941
2946
  max_chars: 4_000,
2942
2947
  skip_meta: skip_meta,
2943
2948
  pairs: 8
2944
2949
  )
2945
2950
  end
2946
- dialog = PWN::Memory.recent_dialog(session_id: session_id, pairs: 4, max_chars: 1_500)
2951
+ dialog = PWN::Memory.recent_dialog(session_id: source_session_id, pairs: 4, max_chars: 1_500)
2947
2952
  end
2948
2953
 
2949
2954
  user_body = prior_user && prior_user[:content].to_s.strip
@@ -3061,7 +3066,7 @@ module PWN
3061
3066
  request: request,
3062
3067
  system_role_content: recall_sys,
3063
3068
  response_history: chat_response_history(
3064
- session_id: session_id,
3069
+ session_id: source_session_id,
3065
3070
  request: request,
3066
3071
  system_role_content: recall_sys
3067
3072
  ),
@@ -172,7 +172,7 @@ module PWN
172
172
  public_class_method def self.record_tokens(opts = {})
173
173
  n = opts[:tokens].to_i
174
174
  cost = opts[:cost].to_f
175
- model = opts[:model].to_s
175
+ model = opts[:model].to_s.to_sym
176
176
  m = load
177
177
  m[:usage] ||= { tokens: 0, cost: 0.0, calls: 0, by_model: {} }
178
178
  m[:usage][:tokens] += n
@@ -98,7 +98,7 @@ module PWN
98
98
  approved: row[:approved] == true,
99
99
  unattended: row[:unattended]
100
100
  )
101
- ids = Array(report[:results]).map { |step| step[:id] || step['id'] }.compact
101
+ ids = Array(report[:results]).filter_map { |step| step[:id] || step['id'] if step[:ok] == true || step['ok'] == true }
102
102
  mutate!(id: row[:id]) do |locked|
103
103
  locked[:last_completed_step] = ids.last if ids.any?
104
104
  locked[:status] = 'open'
@@ -228,8 +228,11 @@ module PWN
228
228
 
229
229
  public_class_method def self.report_text(opts = {})
230
230
  report = opts[:report] || {}
231
- ids = Array(report[:results]).map { |step| step[:id] || step['id'] }
232
- "Resumed mission for #{opts[:request]}. Completed steps: #{ids.join(', ')}. Named-duration work stays open until wall time elapses."
231
+ completed, failed = Array(report[:results]).partition { |step| step[:ok] == true || step['ok'] == true }
232
+ ids = completed.map { |step| step[:id] || step['id'] }
233
+ failures = failed.map { |step| step[:id] || step['id'] }
234
+ failure_text = failures.empty? ? '' : " Failed steps: #{failures.join(', ')}."
235
+ "Resumed mission for #{opts[:request]}. Completed steps: #{ids.join(', ')}.#{failure_text} Named-duration work stays open until wall time elapses."
233
236
  end
234
237
 
235
238
  public_class_method def self.authors
@@ -86,10 +86,10 @@ module PWN
86
86
  end
87
87
  end
88
88
 
89
- def supervise
89
+ def supervise(pid_namespace: true)
90
90
  channel = UNIXSocket.for_fd(3)
91
91
  snapshot = decode(JSON.parse(channel.gets))
92
- checked(native('unshare', [Fiddle::TYPE_INT]).call(0x20000000), 'unshare PID namespace')
92
+ checked(native('unshare', [Fiddle::TYPE_INT]).call(0x20000000), 'unshare PID namespace') if pid_namespace
93
93
  reader, writer = IO.pipe
94
94
  armed, arm = IO.pipe
95
95
  init = fork do
@@ -151,6 +151,13 @@ module PWN
151
151
  channel&.close unless channel&.closed?
152
152
  end
153
153
 
154
+ # Same handshake without util-linux unshare or a user/PID namespace.
155
+ # The supervisor is a process-group leader so cancellation still reaches
156
+ # children that have not called setsid.
157
+ def supervise_host
158
+ supervise(pid_namespace: false)
159
+ end
160
+
154
161
  def execute(descriptor)
155
162
  case descriptor.fetch(:operation).to_sym
156
163
  when :command
@@ -202,21 +209,22 @@ module PWN
202
209
  end
203
210
  snapshot[:requires].uniq!
204
211
  end
212
+ mode = opts[:containment] == :host ? :host : :namespace
205
213
  payload = JSON.generate(self.class.encode(snapshot))
206
- @channel, child = UNIXSocket.pair
207
- mapping = opts.fetch(:fds, {}).merge(3 => child)
208
- @pid = Process.spawn('unshare', '--user', '--map-current-user', '--keep-caps', RbConfig.ruby, '-I', $LOAD_PATH.join(File::PATH_SEPARATOR), '-rpwn', '-e', 'exit!(PWN::AI::Agent::MissionNamespace.supervise || 1)', mapping.merge(close_others: true))
209
- child.close
210
- Timeout.timeout(15) do
211
- @channel.puts(payload)
212
- @pidfd = @channel.recv_io
213
- @channel.write('1')
214
- end
214
+ start_supervisor(payload, opts, mode)
215
215
  rescue Exception => e # rubocop:disable Lint/RescueException -- failed startup cannot leak a child
216
216
  close
217
- raise Unavailable, "mission not started: #{e.message}; install util-linux unshare and enable Linux user/PID namespaces and pidfds"
218
- ensure
219
- child&.close unless child&.closed?
217
+ detail = startup_detail(e)
218
+ raise Unavailable, detail unless mode != :host && !@host_attempted && namespace_denied?(detail)
219
+
220
+ @host_attempted = true
221
+ @child_error = nil
222
+ begin
223
+ start_supervisor(payload, opts, :host)
224
+ rescue Exception => host_error # rubocop:disable Lint/RescueException -- second attempt must not leak a child
225
+ close
226
+ raise Unavailable, "#{detail}; host supervisor: #{startup_detail(host_error)}"
227
+ end
220
228
  end
221
229
 
222
230
  def wait
@@ -230,6 +238,13 @@ module PWN
230
238
  return :reaped unless @mutex
231
239
 
232
240
  @mutex.synchronize do
241
+ if @group && @pid
242
+ begin
243
+ Process.kill('KILL', -@group)
244
+ rescue Errno::ESRCH, Errno::EPERM
245
+ nil
246
+ end
247
+ end
233
248
  if @pidfd && !@pidfd.closed?
234
249
  result = self.class.native('pidfd_send_signal', [Fiddle::TYPE_INT, Fiddle::TYPE_INT, Fiddle::TYPE_VOIDP, Fiddle::TYPE_INT]).call(@pidfd.fileno, Signal.list.fetch('KILL'), 0, 0)
235
250
  self.class.checked(result, 'pidfd_send_signal') unless result.negative? && Fiddle.last_error == Errno::ESRCH::Errno
@@ -263,6 +278,44 @@ module PWN
263
278
 
264
279
  private
265
280
 
281
+ def start_supervisor(payload, opts, mode)
282
+ @channel, child = UNIXSocket.pair
283
+ err_read, err_write = IO.pipe
284
+ mapping = opts.fetch(:fds, {}).merge(3 => child, err: err_write)
285
+ entry = mode == :host ? 'supervise_host' : 'supervise'
286
+ command = [RbConfig.ruby, '-I', $LOAD_PATH.join(File::PATH_SEPARATOR), '-rpwn', '-e', "exit!(PWN::AI::Agent::MissionNamespace.#{entry} || 1)"]
287
+ command = ['unshare', '--user', '--map-current-user', '--keep-caps', *command] if mode == :namespace
288
+ spawn_opts = mapping.merge(close_others: true)
289
+ spawn_opts[:pgroup] = true if mode == :host
290
+ @pid = Process.spawn(*command, spawn_opts)
291
+ @group = @pid if mode == :host
292
+ child.close
293
+ err_write.close
294
+ drain = Thread.new { @child_error = err_read.read }
295
+ drain.report_on_exception = false
296
+ @stderr_thread = drain
297
+ @stderr_read = err_read
298
+ Timeout.timeout(15) do
299
+ @channel.puts(payload)
300
+ @pidfd = @channel.recv_io
301
+ @channel.write('1')
302
+ end
303
+ ensure
304
+ child&.close unless child&.closed?
305
+ err_write&.close unless err_write&.closed?
306
+ end
307
+
308
+ def startup_detail(error)
309
+ [@child_error.to_s.strip, error.message].reject(&:empty?).uniq.join('; ')
310
+ end
311
+
312
+ def namespace_denied?(detail)
313
+ text = detail.to_s
314
+ return false if text.match?(/snapshot|unknown mission operation|ArgumentError/)
315
+
316
+ text.match?(/Broken pipe|unshare|namespace|Operation not permitted|Invalid argument|No such file or directory/i)
317
+ end
318
+
266
319
  def start_prepared(opts, &operation)
267
320
  ready, announce = IO.pipe
268
321
  release, gate = IO.pipe
@@ -321,6 +374,9 @@ module PWN
321
374
  def reap
322
375
  _pid, @status = Process.wait2(@pid) if @pid
323
376
  @pid = nil
377
+ @group = nil
378
+ @stderr_thread&.join(1)
379
+ @stderr_read&.close unless @stderr_read&.closed?
324
380
  @channel&.close unless @channel&.closed?
325
381
  @pidfd&.close unless @pidfd&.closed?
326
382
  :reaped
@@ -1151,7 +1151,7 @@ module PWN
1151
1151
 
1152
1152
  private_class_method def self.terminal_reward(opts = {})
1153
1153
  conf = opts[:confidence]
1154
- conf = 1.0 if conf.nil? || conf.to_f <= 0.0
1154
+ conf = 1.0 if conf.nil?
1155
1155
  conf = conf.to_f.clamp(0.0, 1.0)
1156
1156
  unless opts[:score].nil?
1157
1157
  base = ((2.0 * opts[:score].to_f) - 1.0).clamp(-1.0, 1.0)
@@ -223,7 +223,7 @@ module PWN
223
223
  private_class_method def self.spawn_worker(opts = {})
224
224
  args = opts.fetch(:args)
225
225
  input = opts[:input]
226
- Dir.mktmpdir('pwn-policy-evaluator-', '/tmp') do |root|
226
+ Dir.mktmpdir('pwn-policy-evaluator-') do |root|
227
227
  Open3.popen3(
228
228
  { 'HOME' => root, 'TMPDIR' => root, 'LANG' => 'C.UTF-8' },
229
229
  RbConfig.ruby, RUNNER, *args,
@@ -261,7 +261,7 @@ module PWN
261
261
  private_class_method def self.with_isolated
262
262
  refuse_live_agent
263
263
  original = ENV.to_h
264
- Dir.mktmpdir('pwn-policy-heldout-', '/tmp') do |root|
264
+ Dir.mktmpdir('pwn-policy-heldout-') do |root|
265
265
  ENV.replace('HOME' => root, 'TMPDIR' => root, 'LANG' => 'C.UTF-8')
266
266
  PWN.const_set(:Env, { ai: { agent: { policy: false } } }) unless PWN.const_defined?(:Env)
267
267
  require_relative 'policy'
@@ -93,6 +93,7 @@ module PWN
93
93
  response = with_engine(engine: override, model: model) do
94
94
  engine_chat(
95
95
  engine: engine,
96
+ model: model,
96
97
  request: request.chomp,
97
98
  system_role_content: system_role_content,
98
99
  spinner: spinner,
@@ -393,7 +393,7 @@ module PWN
393
393
  before = TurnFinalizer.artifact_snapshot(paths: @contract[:required_artifacts])
394
394
  begin
395
395
  result = provider_attempt(&)
396
- failed = result.is_a?(Hash) && (result[:error] || result['error'] || result[:success] == false || result['success'] == false || result[:ok] == false || (result.key?(:exit) && result[:exit] != 0))
396
+ failed = result.is_a?(Hash) && (result[:error] || result['error'] || result[:success] == false || result['success'] == false || result[:ok] == false || result['ok'] == false || (result.key?(:exit) && result[:exit] != 0) || (result.key?('exit') && result['exit'] != 0))
397
397
  timed_out = result.is_a?(Hash) && (result[:error] || result['error']).to_s.match?(/timeout/i)
398
398
  # A returned timeout still may have applied. Only a finished
399
399
  # command (exit/stdout, no timeout) is an observation.
@@ -405,24 +405,34 @@ module PWN
405
405
  # trace: 'optional - Array of {name:, args:, result:} or Strings'
406
406
  # )
407
407
  #
408
- # Returns [{idx:, step:, reward: -1|0|1}, ...] and, when session_id
409
- # is given, rewrites each tool line in the transcript with a
410
- # `[step_reward=N]` prefix so exemplars_for / distill_skill can
411
- # keep only reward>0 steps (C4 minimal sufficient trace).
408
+ # Returns [{idx:, step:, reward: -1|0|1|nil}, ...]. Unknown evidence
409
+ # stays nil. With session_id, persist step_reward only on the captured
410
+ # action rows; retained evidence is copy-on-write under its writer protocol.
412
411
 
413
412
  public_class_method def self.prm(opts = {})
414
413
  request = opts[:request].to_s
415
414
  trace = Array(opts[:trace])
416
415
  sid = opts[:session_id]
417
- trace = load_trace(session_id: sid) if trace.empty? && sid
416
+ snapshot = opts[:snapshot] || Thread.current[:pwn_prm_snapshot]
417
+ snapshot = nil unless snapshot.is_a?(Hash) && snapshot[:session_id] == sid && snapshot[:request] == request
418
+ snapshot ||= prm_snapshot(session_id: sid, request: request) if sid
419
+ trace = snapshot[:trace] if trace.empty? && snapshot
420
+ # A caller-supplied trace may be scored, but cannot annotate unrelated rows.
421
+ snapshot = nil unless snapshot && trace == snapshot[:trace]
418
422
 
419
423
  rewards = llm_prm(request: request, trace: trace)
420
424
  rewards ||= heuristic_prm(trace: trace)
425
+ # A judge cannot recover execution status from incomplete display bytes.
426
+ trace.each_with_index do |step, index|
427
+ semantic = semantic_ok(name: 'shell', raw: step.to_s)[:semantic_ok]
428
+ rewards[index] = nil if semantic.nil?
429
+ rewards[index] = [rewards[index], 0].min if semantic == false && rewards[index]
430
+ end
421
431
 
422
432
  out = trace.each_with_index.map do |s, i|
423
- { idx: i + 1, step: s.to_s[0, 200], reward: rewards[i] || 0 }
433
+ { idx: i + 1, step: s.to_s[0, 200], reward: rewards[i] }
424
434
  end
425
- annotate_session(session_id: sid, rewards: rewards) if sid
435
+ annotate_session(session_id: sid, rewards: rewards, binding: snapshot[:binding]) if snapshot
426
436
  out
427
437
  rescue StandardError
428
438
  []
@@ -708,46 +718,51 @@ module PWN
708
718
  public_class_method def self.semantic_ok(opts = {})
709
719
  name = opts[:name].to_s
710
720
  raw = opts[:raw].to_s
711
- ok = raw.include?('"success":true')
712
- err = raw[/"error":"([^"]{1,300})"/, 1]
713
- exit_code = raw[/"exit":(\d+)/, 1]&.to_i
714
- stderr = raw[/"stderr":"([^"]{0,400})"/, 1].to_s
715
-
721
+ envelope = begin
722
+ JSON.parse(raw.sub(/\A\s*[a-z_][a-z0-9_]*\s*(?:→|->)\s*/i, ''), symbolize_names: true)
723
+ rescue JSON::ParserError
724
+ {}
725
+ end
726
+ envelope = {} unless envelope.is_a?(Hash)
727
+ return { ok: nil, semantic_ok: nil, exit: nil, err: nil, benign: false, shape: :unknown } unless [true, false].include?(envelope[:success]) || envelope[:error]
728
+
729
+ result = envelope[:result].is_a?(Hash) ? envelope[:result] : envelope
730
+ ok = envelope[:success] == true
731
+ err = envelope[:error] || result[:error]
732
+ exit_code = Integer(result[:exit], exception: false)
733
+ stderr = result[:stderr].to_s
734
+ status_text = [err, envelope[:code], result[:code]].compact.join(' ')
716
735
  benign = false
717
736
  shape = nil
718
- if name == 'shell' && ok && exit_code && exit_code != 0
737
+ if name == 'shell' && exit_code && exit_code != 0
719
738
  cmd = extract_cmd(args: opts[:args])
720
- # 2.1 — ONLY BENIGN_EXIT regex × allowed codes. The old global
721
- # `stderr.empty? && exit==1 ⇒ benign` laundered real failures
722
- # (pipelines without pipefail, bare false, etc.) into "success".
723
- # For pipelines, match the LAST stage (post-pipe) first, then any.
724
- stages = cmd.split('|').map(&:strip)
725
- last = stages.last.to_s
726
- benign = BENIGN_EXIT.any? { |rx, codes| last.match?(rx) && codes.include?(exit_code) }
727
- benign ||= stages.length > 1 && BENIGN_EXIT.any? { |rx, codes| stages.any? { |s| s.match?(rx) } && codes.include?(exit_code) && stderr.strip.empty? }
728
- shape = recoverable_shape(exit_code: exit_code, stderr: stderr, err: err)
739
+ # Only a completed informational command with an allowed exit is
740
+ # benign. An earlier grep cannot launder a failed final pipeline stage.
741
+ last = cmd.split('|').last.to_s.strip
742
+ benign = err.to_s.empty? && stderr.strip.empty? && result[:success] != false && result[:ok] != false &&
743
+ (envelope[:informational_exit] == true || BENIGN_EXIT.any? { |rx, codes| last.match?(rx) && codes.include?(exit_code) })
744
+ shape = recoverable_shape(exit_code: exit_code, stderr: stderr, err: err) unless benign
729
745
  elsif !ok
730
- shape = recoverable_shape(exit_code: exit_code, stderr: stderr, err: err || raw[0, 200])
746
+ shape = recoverable_shape(exit_code: exit_code, stderr: stderr, err: err)
731
747
  end
732
748
 
733
- if raw.include?('invalid_payload') || err.to_s.include?('invalid_payload')
749
+ if status_text.include?('invalid_payload')
734
750
  semantic = false
735
751
  shape = :invalid_payload
736
752
  err ||= 'invalid_payload'
737
- elsif timeout_result?(err: err, raw: raw)
753
+ elsif timeout_result?(err: err)
738
754
  semantic = false
739
755
  shape = :timeout
740
- err ||= raw[/timeout after \d+s/i] || 'timeout'
756
+ err ||= 'timeout'
741
757
  else
742
- semantic = ok && (exit_code.nil? || exit_code.zero? || benign)
758
+ semantic = (ok || benign) && result[:success] != false && result[:ok] != false && err.to_s.empty? && (exit_code.nil? || exit_code.zero? || benign)
743
759
  end
744
- err ||= raw[/"stderr":"([^"]{4,300})"/, 1] unless semantic
760
+ err ||= stderr[0, 300] unless semantic || stderr.empty?
745
761
  { ok: ok, semantic_ok: semantic, exit: exit_code, err: err, benign: benign, shape: shape }
746
762
  end
747
763
 
748
764
  private_class_method def self.timeout_result?(opts = {})
749
- blob = "#{opts[:err]} #{opts[:raw]}"
750
- blob.match?(/timeout after \d+s/i) || blob.match?(/"error"\s*:\s*"timeout/i)
765
+ opts[:err].to_s.match?(/\Atimeout|timeout after \d+s/i)
751
766
  end
752
767
 
753
768
  # 2.2 — coarse recoverable shape beside the fingerprint. Paths are
@@ -1579,8 +1594,9 @@ module PWN
1579
1594
  private_class_method def self.heuristic_prm(opts = {})
1580
1595
  opts[:trace].map do |t|
1581
1596
  s = semantic_ok(name: 'shell', raw: t.to_s)
1582
- if s[:semantic_ok] then 1
1597
+ if s[:semantic_ok].nil? then nil
1583
1598
  elsif s[:benign] then 0
1599
+ elsif s[:semantic_ok] then 1
1584
1600
  else -1
1585
1601
  end
1586
1602
  end
@@ -1655,46 +1671,118 @@ module PWN
1655
1671
  []
1656
1672
  end
1657
1673
 
1674
+ # Capture before any judge/provider/background work. Row indexes alone
1675
+ # are not identity: bind the exact prefix and each action's original bytes.
1676
+ public_class_method def self.prm_snapshot(opts = {})
1677
+ sid = opts[:session_id]
1678
+ request = opts[:request].to_s
1679
+ rows = PWN::Sessions.load(session_id: sid)
1680
+ user_at = rows.rindex { |row| row[:role].to_s == 'user' && row[:content].to_s == request }
1681
+ return nil unless user_at
1682
+
1683
+ stop = ((user_at + 1)...rows.length).find { |index| rows[index][:role].to_s == 'user' } || rows.length
1684
+ actions = (user_at...stop).filter_map do |index|
1685
+ next unless rows[index][:role].to_s == 'tool'
1686
+
1687
+ { row_index: index, sha256: prm_rows_digest(rows: [rows[index]]).freeze }.freeze
1688
+ end.freeze
1689
+ binding = {
1690
+ version: 1, session_id: sid.to_s.dup.freeze, turn_index: user_at,
1691
+ request_sha256: Digest::SHA256.hexdigest(request).freeze,
1692
+ prefix_length: stop, prefix_sha256: prm_rows_digest(rows: rows.first(stop)).freeze,
1693
+ actions: actions
1694
+ }.freeze
1695
+ { session_id: sid.to_s.dup.freeze, request: request.dup.freeze, binding: binding,
1696
+ trace: actions.map { |action| rows[action[:row_index]][:content].to_s.dup.freeze }.freeze }.freeze
1697
+ rescue StandardError
1698
+ nil
1699
+ end
1700
+
1701
+ # Also used by retained-evidence writers while holding their publication lock.
1702
+ public_class_method def self.prm_binding_valid?(opts = {})
1703
+ binding = opts[:binding]
1704
+ rows = opts[:transcript]
1705
+ return false unless binding.is_a?(Hash) && binding[:version] == 1 && binding[:session_id] == opts[:session_id] && rows.is_a?(Array)
1706
+
1707
+ length = binding[:prefix_length]
1708
+ index = binding[:turn_index]
1709
+ return false unless length.is_a?(Integer) && index.is_a?(Integer) && index >= 0 && length > index && rows.length >= length
1710
+ return false unless rows[index][:role].to_s == 'user' && Digest::SHA256.hexdigest(rows[index][:content].to_s) == binding[:request_sha256]
1711
+ return false unless prm_rows_digest(rows: rows.first(length)) == binding[:prefix_sha256]
1712
+
1713
+ expected = (index...length).select { |at| rows[at][:role].to_s == 'tool' }
1714
+ actions = binding[:actions]
1715
+ return false unless actions.is_a?(Array) && actions.map { |action| action[:row_index] } == expected
1716
+
1717
+ actions.all? { |action| prm_rows_digest(rows: [rows[action[:row_index]]]) == action[:sha256] }
1718
+ rescue StandardError
1719
+ false
1720
+ end
1721
+
1722
+ private_class_method def self.prm_rows_digest(opts = {})
1723
+ Digest::SHA256.hexdigest(JSON.generate(opts[:rows].map { |row| row.except(:step_reward) }))
1724
+ end
1725
+
1658
1726
  private_class_method def self.annotate_session(opts = {})
1659
1727
  sid = opts[:session_id]
1660
1728
  rewards = opts[:rewards]
1661
- return unless sid && defined?(PWN::Sessions)
1729
+ binding = opts[:binding]
1730
+ return unless sid && binding && defined?(PWN::Sessions)
1731
+ return unless rewards.is_a?(Array) && rewards.length == binding[:actions].length && rewards.all? { |reward| reward.nil? || [-1, 0, 1].include?(reward) }
1662
1732
 
1663
1733
  path = File.join(PWN::Sessions.sessions_dir, "#{sid}.jsonl")
1664
1734
  unless File.exist?(path)
1665
- result = Learning.annotate_evidence(session_id: sid, rewards: rewards)
1666
- if result[:annotated]
1667
- PWN::Sessions.load(session_id: sid).select { |row| row[:role].to_s == 'tool' }.each_with_index do |row, index|
1668
- fold_step_reward_to_metrics(content: row[:content], reward: rewards[index]) unless rewards[index].nil?
1669
- end
1735
+ # Older writers ignore unknown options; never invoke one with a bound
1736
+ # annotation, since it could publish credit onto a different turn.
1737
+ return { annotated: false, reason: :binding_unsupported } unless Learning.const_defined?(:EVIDENCE_ANNOTATION_VERSION, false) && Learning::EVIDENCE_ANNOTATION_VERSION >= 2
1738
+
1739
+ result = Learning.annotate_evidence(session_id: sid, rewards: rewards, binding: binding)
1740
+ if result[:annotated] && result[:binding_sha256] == Digest::SHA256.hexdigest(JSON.generate(binding))
1741
+ rows = PWN::Sessions.load(session_id: sid)
1742
+ fold_bound_rewards(binding: binding, transcript: rows, rewards: rewards, session_id: sid)
1670
1743
  end
1671
1744
  return result
1672
1745
  end
1673
1746
 
1674
1747
  lease = PWN::Sessions.activate(session_id: sid)
1675
- lines = File.readlines(path)
1676
- ti = -1
1677
- lines.map! do |l|
1678
- j = JSON.parse(l, symbolize_names: true)
1679
- if j[:role].to_s == 'tool'
1680
- ti += 1
1681
- if rewards[ti]
1682
- j[:step_reward] = rewards[ti]
1683
- # P18 — fold step_reward into Metrics so Registry.rank can bias
1684
- fold_step_reward_to_metrics(content: j[:content], reward: rewards[ti])
1748
+ File.open("#{path}.write.lock", File::RDWR | File::CREAT | File::NOFOLLOW, 0o600) do |writer|
1749
+ writer.flock(File::LOCK_EX)
1750
+ File.open(path, File::RDWR | File::NOFOLLOW) do |file|
1751
+ lines = file.readlines
1752
+ rows = lines.map { |line| JSON.parse(line, symbolize_names: true) }
1753
+ return { annotated: false, reason: :stale_binding } unless prm_binding_valid?(binding: binding, transcript: rows, session_id: sid)
1754
+
1755
+ binding[:actions].each_with_index do |action, index|
1756
+ next if rewards[index].nil?
1757
+
1758
+ at = action[:row_index]
1759
+ rows[at][:step_reward] = rewards[index]
1760
+ lines[at] = "#{JSON.generate(rows[at])}\n"
1685
1761
  end
1762
+ file.rewind
1763
+ file.write(lines.join)
1764
+ file.truncate(file.pos)
1765
+ file.flush
1766
+ file.fsync
1767
+ fold_bound_rewards(binding: binding, transcript: rows, rewards: rewards, session_id: sid)
1686
1768
  end
1687
- "#{JSON.generate(j)}\n"
1688
- rescue StandardError
1689
- l
1690
1769
  end
1691
- File.write(path, lines.join)
1770
+ { annotated: true }
1692
1771
  rescue StandardError
1693
1772
  nil
1694
1773
  ensure
1695
1774
  PWN::Sessions.deactivate(lease: lease)
1696
1775
  end
1697
1776
 
1777
+ private_class_method def self.fold_bound_rewards(opts = {})
1778
+ return unless prm_binding_valid?(opts)
1779
+
1780
+ opts[:binding][:actions].each_with_index do |action, index|
1781
+ reward = opts[:rewards][index]
1782
+ fold_step_reward_to_metrics(content: opts[:transcript][action[:row_index]][:content], reward: reward) unless reward.nil?
1783
+ end
1784
+ end
1785
+
1698
1786
  # Extract tool name from "name → …" session content and record PRM.
1699
1787
  private_class_method def self.fold_step_reward_to_metrics(opts = {})
1700
1788
  return unless defined?(Metrics) && Metrics.respond_to?(:record_step_reward)
@@ -1899,7 +1987,7 @@ module PWN
1899
1987
  a = opts[:args]
1900
1988
  h = a.is_a?(String) ? JSON.parse(a, symbolize_names: true) : a
1901
1989
  # Leading env-vars / sudo / pipes: match any segment.
1902
- h.is_a?(Hash) ? h[:command].to_s.strip : a.to_s
1990
+ h.is_a?(Hash) ? (h[:command] || h['command']).to_s.strip : a.to_s
1903
1991
  rescue StandardError
1904
1992
  opts[:args].to_s
1905
1993
  end
@@ -2033,7 +2121,21 @@ module PWN
2033
2121
  #{self}.prm(
2034
2122
  request: 'required - user goal',
2035
2123
  session_id: 'optional - session to score in place',
2036
- trace: 'optional - Array of {name:, args:, result:} or Strings'
2124
+ trace: 'optional - Array of {name:, args:, result:} or Strings',
2125
+ snapshot: 'optional - immutable host snapshot from prm_snapshot, captured before background work'
2126
+ )
2127
+
2128
+ # Capture original request and exact action identities before scoring.
2129
+ #{self}.prm_snapshot(
2130
+ session_id: 'required - session with the original user turn',
2131
+ request: 'required - original user request'
2132
+ )
2133
+
2134
+ # Validate a captured binding under the transcript writer lock.
2135
+ #{self}.prm_binding_valid?(
2136
+ binding: 'required - binding from prm_snapshot',
2137
+ transcript: 'required - current parsed transcript rows',
2138
+ session_id: 'required - exact captured session identity'
2037
2139
  )
2038
2140
 
2039
2141
  # Plan-quality soft signal (W3 feature / Learning tag)
@@ -21,8 +21,6 @@ module PWN
21
21
  request: request,
22
22
  suppress_pii_warning: true
23
23
  )
24
- rescue StandardError => e
25
- raise e.backtrace
26
24
  end
27
25
 
28
26
  # Author(s):: 0day Inc. <support@0dayinc.com>