bugx-cli 0.1.1__py3-none-any.whl

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 (762) hide show
  1. bugx_cli/__init__.py +6 -0
  2. bugx_cli/cli.py +1685 -0
  3. bugx_cli/commands/__init__.py +1 -0
  4. bugx_cli/commands/advisory.py +94 -0
  5. bugx_cli/commands/agent.py +4210 -0
  6. bugx_cli/commands/audit.py +632 -0
  7. bugx_cli/commands/autonomous.py +260 -0
  8. bugx_cli/commands/cloud.py +1371 -0
  9. bugx_cli/commands/daemon.py +50 -0
  10. bugx_cli/commands/doctor.py +1590 -0
  11. bugx_cli/commands/goal.py +107 -0
  12. bugx_cli/commands/interaction.py +248 -0
  13. bugx_cli/commands/knowledge.py +619 -0
  14. bugx_cli/commands/lifecycle.py +2763 -0
  15. bugx_cli/commands/patch.py +1014 -0
  16. bugx_cli/commands/plugin.py +2749 -0
  17. bugx_cli/commands/plugin_claude.py +1446 -0
  18. bugx_cli/commands/plugin_cline.py +269 -0
  19. bugx_cli/commands/plugin_codex.py +74 -0
  20. bugx_cli/commands/plugin_funide.py +729 -0
  21. bugx_cli/commands/plugin_qoder.py +216 -0
  22. bugx_cli/commands/plugin_zcode.py +710 -0
  23. bugx_cli/commands/project.py +670 -0
  24. bugx_cli/commands/report.py +256 -0
  25. bugx_cli/commands/skill.py +251 -0
  26. bugx_cli/commands/stats.py +133 -0
  27. bugx_cli/commands/system.py +2567 -0
  28. bugx_cli/common.py +906 -0
  29. bugx_cli/host_adapters.py +1892 -0
  30. bugx_cli/hosts/__init__.py +80 -0
  31. bugx_cli/hosts/base.py +99 -0
  32. bugx_cli/hosts/registry.py +573 -0
  33. bugx_cli/hosts/template_engine.py +188 -0
  34. bugx_cli/infra/__init__.py +209 -0
  35. bugx_cli/infra/ai_advisor.py +851 -0
  36. bugx_cli/infra/engine_installer.py +1945 -0
  37. bugx_cli/infra/host_sync.py +548 -0
  38. bugx_cli/infra/mcp_advisor.py +826 -0
  39. bugx_cli/infra/security.py +339 -0
  40. bugx_cli-0.1.1.data/data/share/bugx-agent/bugx-mcp-manifest.json +53 -0
  41. bugx_cli-0.1.1.data/data/share/bugx-agent/core/CATALOG.json +141 -0
  42. bugx_cli-0.1.1.data/data/share/bugx-agent/core/README.md +254 -0
  43. bugx_cli-0.1.1.data/data/share/bugx-agent/core/adapters/README.md +35 -0
  44. bugx_cli-0.1.1.data/data/share/bugx-agent/core/adapters/android-interaction.json +81 -0
  45. bugx_cli-0.1.1.data/data/share/bugx-agent/core/adapters/android.json +24 -0
  46. bugx_cli-0.1.1.data/data/share/bugx-agent/core/adapters/desktop-macos.json +20 -0
  47. bugx_cli-0.1.1.data/data/share/bugx-agent/core/adapters/ios-interaction.json +34 -0
  48. bugx_cli-0.1.1.data/data/share/bugx-agent/core/adapters/ios.json +23 -0
  49. bugx_cli-0.1.1.data/data/share/bugx-agent/core/adapters/memory-macos.json +24 -0
  50. bugx_cli-0.1.1.data/data/share/bugx-agent/core/agent/README.md +51 -0
  51. bugx_cli-0.1.1.data/data/share/bugx-agent/core/agent/__init__.py +146 -0
  52. bugx_cli-0.1.1.data/data/share/bugx-agent/core/agent/agent_artifacts.py +766 -0
  53. bugx_cli-0.1.1.data/data/share/bugx-agent/core/agent/agent_eval.py +1155 -0
  54. bugx_cli-0.1.1.data/data/share/bugx-agent/core/agent/agent_execution.py +718 -0
  55. bugx_cli-0.1.1.data/data/share/bugx-agent/core/agent/agent_orchestrator.py +1351 -0
  56. bugx_cli-0.1.1.data/data/share/bugx-agent/core/agent/agent_targets.py +877 -0
  57. bugx_cli-0.1.1.data/data/share/bugx-agent/core/agent/agent_workspace.py +770 -0
  58. bugx_cli-0.1.1.data/data/share/bugx-agent/core/agent/feature_baseline.py +150 -0
  59. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/README.md +24 -0
  60. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/axe-core/LICENSE-3RD-PARTY.txt +66 -0
  61. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/axe-core/LICENSE.txt +362 -0
  62. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/axe-core/UPSTREAM.md +10 -0
  63. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/axe-core/axe.min.js +12 -0
  64. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/bugx-avatar-1024.png +0 -0
  65. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/bugx-avatar-512.png +0 -0
  66. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/bugx-avatar-tight.svg +23 -0
  67. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/bugx-avatar.svg +28 -0
  68. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/bugx-hero-cn.png +0 -0
  69. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/bugx-hero-en.png +0 -0
  70. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/bugx-hero-en.svg +74 -0
  71. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/bugx-hero-zh.svg +74 -0
  72. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/codex.png +0 -0
  73. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/dsh.png +0 -0
  74. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/project-layout.md +42 -0
  75. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/zcode.png +0 -0
  76. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/README.md +37 -0
  77. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/data-audit/manifest.json +94 -0
  78. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/data-audit/stages/00-scope.md +14 -0
  79. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/data-audit/stages/10-schema-inventory.md +14 -0
  80. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/data-audit/stages/20-query-and-integrity.md +14 -0
  81. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/data-audit/stages/80-evidence-regression.md +14 -0
  82. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/desktop-audit/manifest.json +123 -0
  83. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/desktop-audit/stages/00-scope.md +15 -0
  84. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/desktop-audit/stages/10-process-model.md +14 -0
  85. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/desktop-audit/stages/20-package-integrity.md +15 -0
  86. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/desktop-audit/stages/30-ui-behavior.md +14 -0
  87. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/desktop-audit/stages/80-evidence-regression.md +15 -0
  88. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/memory-testing.md +227 -0
  89. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/manifest.json +155 -0
  90. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/modules/android.md +19 -0
  91. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/modules/h5.md +18 -0
  92. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/modules/ios.md +25 -0
  93. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/modules/miniprogram.md +26 -0
  94. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/modules/webview.md +18 -0
  95. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/stages/00-scope.md +14 -0
  96. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/stages/10-platform-inventory.md +14 -0
  97. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/stages/20-masvs-static.md +20 -0
  98. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/stages/30-component-exposure.md +14 -0
  99. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/stages/40-device-behavior.md +14 -0
  100. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/stages/80-evidence-regression.md +13 -0
  101. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/native-audit/manifest.json +127 -0
  102. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/native-audit/stages/00-scope.md +14 -0
  103. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/native-audit/stages/10-static-white-box.md +14 -0
  104. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/native-audit/stages/20-memory-concurrency.md +15 -0
  105. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/native-audit/stages/30-behavior-black-box.md +39 -0
  106. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/native-audit/stages/80-evidence-regression.md +14 -0
  107. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/platform-testing.md +174 -0
  108. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/manifest.json +191 -0
  109. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/modules/graphql.md +5 -0
  110. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/modules/h5.md +18 -0
  111. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/modules/multi-tenant.md +4 -0
  112. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/modules/oauth.md +4 -0
  113. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/modules/upload.md +4 -0
  114. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/modules/websocket.md +4 -0
  115. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/stages/00-scope.md +13 -0
  116. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/stages/10-discovery.md +13 -0
  117. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/stages/20-auth-session.md +13 -0
  118. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/stages/30-authz-business.md +13 -0
  119. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/stages/40-input-output.md +13 -0
  120. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/stages/50-state-async.md +13 -0
  121. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/stages/60-file-ssrf-deser.md +12 -0
  122. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/stages/70-config-dependency.md +12 -0
  123. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/stages/80-evidence-regression.md +12 -0
  124. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/INTERFACE.md +61 -0
  125. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/README.md +58 -0
  126. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/SPEC.md +25 -0
  127. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/__init__.py +109 -0
  128. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/attack_graph.py +1096 -0
  129. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/attack_graph_store.py +1868 -0
  130. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/audit_campaign.py +1232 -0
  131. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/behavior_graph.py +465 -0
  132. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/ghsa_advisories.py +174 -0
  133. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/models.py +93 -0
  134. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/mutator.py +87 -0
  135. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/patcher.py +126 -0
  136. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/scout.py +278 -0
  137. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/synthesizer.py +207 -0
  138. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/verifier.py +103 -0
  139. bugx_cli-0.1.1.data/data/share/bugx-agent/core/bugx.md +1299 -0
  140. bugx_cli-0.1.1.data/data/share/bugx-agent/core/bugx_paths.py +1881 -0
  141. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cli-help.txt +66 -0
  142. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/INTERFACE.md +32 -0
  143. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/README.md +62 -0
  144. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/SPEC.md +25 -0
  145. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/__init__.py +23 -0
  146. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/auto_sync.py +398 -0
  147. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/cloud_client.py +1218 -0
  148. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/cloud_onboard.py +743 -0
  149. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/cloud_schema.py +648 -0
  150. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/consent.py +81 -0
  151. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/device_identity.py +307 -0
  152. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/endpoint_router.py +415 -0
  153. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/flywheel_client.py +769 -0
  154. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/network_transport.py +296 -0
  155. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/onboard_wizard.py +493 -0
  156. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/sensitive_filter.py +285 -0
  157. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/sync_pull.py +695 -0
  158. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/sync_push.py +723 -0
  159. bugx_cli-0.1.1.data/data/share/bugx-agent/core/contracts/AGENT_GUIDE.md +359 -0
  160. bugx_cli-0.1.1.data/data/share/bugx-agent/core/contracts/README.md +34 -0
  161. bugx_cli-0.1.1.data/data/share/bugx-agent/core/contracts/bugx-blackbox.md +541 -0
  162. bugx_cli-0.1.1.data/data/share/bugx-agent/core/contracts/bugx-opencode.md +469 -0
  163. bugx_cli-0.1.1.data/data/share/bugx-agent/core/contracts/bugx-quick.md +44 -0
  164. bugx_cli-0.1.1.data/data/share/bugx-agent/core/contracts/bugx-runtime-contract.md +353 -0
  165. bugx_cli-0.1.1.data/data/share/bugx-agent/core/contracts/bugx-worker.md +470 -0
  166. bugx_cli-0.1.1.data/data/share/bugx-agent/core/contracts/engine_gap_contracts.py +473 -0
  167. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/README.md +70 -0
  168. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/__init__.py +106 -0
  169. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_ai_review.py +185 -0
  170. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_backfill.py +54 -0
  171. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_bootstrap.py +713 -0
  172. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_business.py +36 -0
  173. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_cli.py +715 -0
  174. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_discovery.py +1429 -0
  175. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_evidence.py +1024 -0
  176. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_forensics.py +124 -0
  177. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_gate.py +277 -0
  178. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_intelligence.py +734 -0
  179. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_manifest.py +396 -0
  180. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_platform.py +77 -0
  181. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_validate.py +241 -0
  182. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/module_coverage.py +157 -0
  183. bugx_cli-0.1.1.data/data/share/bugx-agent/core/dev_harness/INTERFACE.md +20 -0
  184. bugx_cli-0.1.1.data/data/share/bugx-agent/core/dev_harness/README.md +21 -0
  185. bugx_cli-0.1.1.data/data/share/bugx-agent/core/dev_harness/SPEC.md +25 -0
  186. bugx_cli-0.1.1.data/data/share/bugx-agent/core/dev_harness/__init__.py +5 -0
  187. bugx_cli-0.1.1.data/data/share/bugx-agent/core/dev_harness/interaction_preset.py +408 -0
  188. bugx_cli-0.1.1.data/data/share/bugx-agent/core/engine-integrity.json +2797 -0
  189. bugx_cli-0.1.1.data/data/share/bugx-agent/core/fuzzing/README.md +49 -0
  190. bugx_cli-0.1.1.data/data/share/bugx-agent/core/fuzzing/__init__.py +82 -0
  191. bugx_cli-0.1.1.data/data/share/bugx-agent/core/fuzzing/concurrency_fuzzer.py +435 -0
  192. bugx_cli-0.1.1.data/data/share/bugx-agent/core/fuzzing/differential_oracle.py +1164 -0
  193. bugx_cli-0.1.1.data/data/share/bugx-agent/core/fuzzing/fuzz_input.py +1291 -0
  194. bugx_cli-0.1.1.data/data/share/bugx-agent/core/fuzzing/stateful_fuzzer.py +404 -0
  195. bugx_cli-0.1.1.data/data/share/bugx-agent/core/governance/README.md +61 -0
  196. bugx_cli-0.1.1.data/data/share/bugx-agent/core/governance/__init__.py +130 -0
  197. bugx_cli-0.1.1.data/data/share/bugx-agent/core/governance/capacity_planner.py +124 -0
  198. bugx_cli-0.1.1.data/data/share/bugx-agent/core/governance/dependency_lock.py +317 -0
  199. bugx_cli-0.1.1.data/data/share/bugx-agent/core/governance/goal_governor.py +754 -0
  200. bugx_cli-0.1.1.data/data/share/bugx-agent/core/governance/guide_budget.py +458 -0
  201. bugx_cli-0.1.1.data/data/share/bugx-agent/core/governance/lockdown.sh +50 -0
  202. bugx_cli-0.1.1.data/data/share/bugx-agent/core/governance/readonly_enforcer.py +154 -0
  203. bugx_cli-0.1.1.data/data/share/bugx-agent/core/governance/runtime_tool_gate.py +373 -0
  204. bugx_cli-0.1.1.data/data/share/bugx-agent/core/governance/secret_redactor.py +784 -0
  205. bugx_cli-0.1.1.data/data/share/bugx-agent/core/governance/token_budget.py +38 -0
  206. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/INTERFACE.md +36 -0
  207. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/README.md +51 -0
  208. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/SPEC.md +25 -0
  209. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/__init__.py +121 -0
  210. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/base.py +111 -0
  211. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/claude.py +99 -0
  212. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/cline.py +298 -0
  213. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/codex.py +300 -0
  214. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/dsh.py +106 -0
  215. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/opencode.py +209 -0
  216. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/pi.py +94 -0
  217. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/zcode.py +99 -0
  218. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/INTERFACE.md +24 -0
  219. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/README.md +62 -0
  220. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/SPEC.md +25 -0
  221. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/__init__.py +21 -0
  222. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/adapters.py +412 -0
  223. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/autonomous_runner.py +1152 -0
  224. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/cline.py +448 -0
  225. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/common.py +103 -0
  226. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/free_models.py +786 -0
  227. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/host_bootstrap.py +389 -0
  228. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/host_evaluators.py +761 -0
  229. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/host_probe.py +41 -0
  230. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/host_provider_arbitrator.py +831 -0
  231. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/host_registry.py +662 -0
  232. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/host_usage.py +127 -0
  233. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/mcp_process_tracker.py +509 -0
  234. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/mcp_registry_gate.py +379 -0
  235. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/pi.py +102 -0
  236. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/provider_facts.py +66 -0
  237. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/INTERFACE.md +51 -0
  238. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/README.md +67 -0
  239. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/SPEC.md +25 -0
  240. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/__init__.py +140 -0
  241. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/_base_usage.py +152 -0
  242. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/_codex_usage.py +297 -0
  243. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/_dsh_usage.py +184 -0
  244. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/_mcp_toml.py +365 -0
  245. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/_zcode_usage.py +269 -0
  246. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/base.py +479 -0
  247. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/claude.py +212 -0
  248. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/cline.py +229 -0
  249. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/codex.py +1006 -0
  250. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/dsh.py +526 -0
  251. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/opencode.py +358 -0
  252. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/pi.py +308 -0
  253. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/zcode.py +219 -0
  254. bugx_cli-0.1.1.data/data/share/bugx-agent/core/i18n.py +252 -0
  255. bugx_cli-0.1.1.data/data/share/bugx-agent/core/infra/README.md +41 -0
  256. bugx_cli-0.1.1.data/data/share/bugx-agent/core/infra/__init__.py +17 -0
  257. bugx_cli-0.1.1.data/data/share/bugx-agent/core/infra/build_info.py +105 -0
  258. bugx_cli-0.1.1.data/data/share/bugx-agent/core/infra/client_metadata.py +185 -0
  259. bugx_cli-0.1.1.data/data/share/bugx-agent/core/infra/json_utils.py +22 -0
  260. bugx_cli-0.1.1.data/data/share/bugx-agent/core/infra/python_runtime.py +540 -0
  261. bugx_cli-0.1.1.data/data/share/bugx-agent/core/infra/safe_xml.py +221 -0
  262. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_bugx.py +118 -0
  263. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/INTERFACE.md +31 -0
  264. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/README.md +106 -0
  265. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/SPEC.md +25 -0
  266. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/__init__.py +29 -0
  267. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/candidate_revalidation.py +484 -0
  268. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/common.py +1060 -0
  269. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/finding_confirm_phase.py +391 -0
  270. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/finding_settlement.py +1432 -0
  271. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/findings_adjudication.py +666 -0
  272. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/findings_snapshot.py +357 -0
  273. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/judge_phase.py +848 -0
  274. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/lesson_context.py +536 -0
  275. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/lifecycle_reporter.py +627 -0
  276. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/orchestrator_controls.py +686 -0
  277. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/post_commit.py +567 -0
  278. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/post_coverage_sync.py +598 -0
  279. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/post_dry_run.py +817 -0
  280. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/post_observability.py +367 -0
  281. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/post_phase.py +1223 -0
  282. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/post_receipt.py +373 -0
  283. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/post_round_lifecycle.py +786 -0
  284. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/pre_phase.py +1029 -0
  285. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/pre_recon_scout.py +879 -0
  286. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/pre_state_builder.py +1133 -0
  287. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/report_sharing.py +414 -0
  288. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/round_orchestrator.py +1116 -0
  289. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/session_runtime.py +1670 -0
  290. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/startup_gates.py +1050 -0
  291. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/startup_interaction.py +1003 -0
  292. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/startup_version_gate.py +879 -0
  293. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/supervisor_bridge.py +1253 -0
  294. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/supervisor_coverage.py +423 -0
  295. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/supervisor_degraded.py +1211 -0
  296. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/worker_barriers.py +424 -0
  297. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/worker_orchestrator.py +1246 -0
  298. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/worker_prior.py +749 -0
  299. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/INTERFACE.md +35 -0
  300. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/README.md +160 -0
  301. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/SPEC.md +25 -0
  302. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/__init__.py +67 -0
  303. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/_facade.py +227 -0
  304. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/archive_ops.py +630 -0
  305. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/auto_materialization.py +459 -0
  306. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/bug-log.md +22 -0
  307. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/cli.py +275 -0
  308. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/export_ops.py +554 -0
  309. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/finding_confirmation.py +1316 -0
  310. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/finding_io.py +299 -0
  311. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/finding_lifecycle.py +730 -0
  312. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/finding_verification.py +405 -0
  313. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/incidents.py +1005 -0
  314. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/lesson-replay-cases.json +20 -0
  315. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/lesson_ledger.py +241 -0
  316. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/lesson_replay.py +272 -0
  317. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/life_ledger.py +668 -0
  318. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/mistake-book.md +130 -0
  319. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/patterns.py +684 -0
  320. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/receipt_contract.py +269 -0
  321. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/schema.py +1192 -0
  322. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/sync_ops.py +940 -0
  323. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/tool_experience.py +683 -0
  324. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/verify_life.py +1597 -0
  325. bugx_cli-0.1.1.data/data/share/bugx-agent/core/lesson-ledger.json +275 -0
  326. bugx_cli-0.1.1.data/data/share/bugx-agent/core/locales/README.md +19 -0
  327. bugx_cli-0.1.1.data/data/share/bugx-agent/core/locales/en-US.json +462 -0
  328. bugx_cli-0.1.1.data/data/share/bugx-agent/core/locales/zh-CN.json +462 -0
  329. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/INTERFACE.md +75 -0
  330. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/README.md +62 -0
  331. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/SPEC.md +25 -0
  332. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/__init__.py +128 -0
  333. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/base.py +717 -0
  334. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/channel_lifecycle.py +751 -0
  335. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/graph_handlers.py +222 -0
  336. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/knowledge_handlers.py +536 -0
  337. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/mining_handlers.py +586 -0
  338. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/resource_prompt_table.py +116 -0
  339. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/retrieval_handlers.py +249 -0
  340. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/rpc_server.py +470 -0
  341. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/supervisor_handlers.py +1461 -0
  342. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/telemetry_handlers.py +227 -0
  343. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/tool_table.py +1030 -0
  344. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_runtime_support/README.md +21 -0
  345. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_runtime_support/__init__.py +1 -0
  346. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_runtime_support/common.py +363 -0
  347. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_runtime_support/environment.py +567 -0
  348. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_runtime_support/verifier.py +758 -0
  349. bugx_cli-0.1.1.data/data/share/bugx-agent/core/metadata.txt +4 -0
  350. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/README.md +157 -0
  351. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/__init__.py +242 -0
  352. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/capability_plan.py +187 -0
  353. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/capability_planner.py +195 -0
  354. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/domain_archetype.py +542 -0
  355. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/domain_router.py +269 -0
  356. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/dynamic_flow_analyzer.py +533 -0
  357. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/impact_pruner.py +435 -0
  358. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/intent_adjudicator.py +175 -0
  359. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/judge_pipeline.py +1246 -0
  360. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/logic_analysis.py +419 -0
  361. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/prompt_harness.py +1704 -0
  362. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/source_inspector.py +267 -0
  363. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/spec_harvester.py +449 -0
  364. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/target_sandbox_manager.py +573 -0
  365. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/test_capability_verifier.py +1364 -0
  366. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/tools-kb.md +38 -0
  367. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/unit_kind.py +122 -0
  368. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/INTERFACE.md +83 -0
  369. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/README.md +51 -0
  370. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/SPEC.md +36 -0
  371. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/__init__.py +76 -0
  372. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/android_probe.py +552 -0
  373. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/base.py +147 -0
  374. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/codebase_memory_probe.py +647 -0
  375. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/desktop_probe.py +342 -0
  376. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/differential_probe.py +434 -0
  377. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/efficiency_probe.py +232 -0
  378. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/ios_binary_probe.py +472 -0
  379. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/memory_probe.py +392 -0
  380. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/miniprogram_probe.py +385 -0
  381. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/mobile_probe.py +466 -0
  382. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/native_probe.py +302 -0
  383. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/openwiki_probe.py +263 -0
  384. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/pattern_probe.py +453 -0
  385. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/platform_probe.py +424 -0
  386. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/probe_registry.py +1770 -0
  387. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/sast_fixture_corpus.py +340 -0
  388. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/sast_probe.py +1510 -0
  389. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/sast_rules.py +1481 -0
  390. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/sca_scanner.py +779 -0
  391. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/ui_accessibility.py +149 -0
  392. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/ui_audit.py +513 -0
  393. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/ui_contract.py +273 -0
  394. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/ui_evidence.py +212 -0
  395. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/ui_measurements.py +314 -0
  396. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/ui_repair.py +250 -0
  397. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/ui_review.py +133 -0
  398. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/ui_storybook.py +107 -0
  399. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/ui_tokens.py +185 -0
  400. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/ui_visual_diff.py +131 -0
  401. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/web_probe.py +714 -0
  402. bugx_cli-0.1.1.data/data/share/bugx-agent/core/project_profiler/INTERFACE.md +62 -0
  403. bugx_cli-0.1.1.data/data/share/bugx-agent/core/project_profiler/README.md +53 -0
  404. bugx_cli-0.1.1.data/data/share/bugx-agent/core/project_profiler/SPEC.md +28 -0
  405. bugx_cli-0.1.1.data/data/share/bugx-agent/core/project_profiler/__init__.py +201 -0
  406. bugx_cli-0.1.1.data/data/share/bugx-agent/core/project_profiler/arbitrator.py +316 -0
  407. bugx_cli-0.1.1.data/data/share/bugx-agent/core/project_profiler/constants.py +247 -0
  408. bugx_cli-0.1.1.data/data/share/bugx-agent/core/project_profiler/detector.py +399 -0
  409. bugx_cli-0.1.1.data/data/share/bugx-agent/core/project_profiler/extractors.py +836 -0
  410. bugx_cli-0.1.1.data/data/share/bugx-agent/core/project_profiler/fingerprint.py +116 -0
  411. bugx_cli-0.1.1.data/data/share/bugx-agent/core/project_profiler/storage.py +258 -0
  412. bugx_cli-0.1.1.data/data/share/bugx-agent/core/project_profiler/strategy.py +301 -0
  413. bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/README.md +35 -0
  414. bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/codex_dialog_dispatch.md +9 -0
  415. bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/command_routing_en.md +42 -0
  416. bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/command_routing_zh.md +42 -0
  417. bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/l0_router.md +47 -0
  418. bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/rules/anti_patterns.md +16 -0
  419. bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/rules/concurrency_rules.md +14 -0
  420. bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/rules/memory_leak_rules.md +13 -0
  421. bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/rules/prompt_injection_defense.md +13 -0
  422. bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/stages/stage_explore.md +31 -0
  423. bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/stages/stage_gate.md +43 -0
  424. bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/stages/stage_mutate.md +42 -0
  425. bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/stages/stage_repair.md +85 -0
  426. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/README.md +74 -0
  427. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/__init__.py +169 -0
  428. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/fix_watchlist.py +391 -0
  429. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/l7_dynamic.py +418 -0
  430. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/l7_repair_loop.py +462 -0
  431. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/l7_selfcheck.py +862 -0
  432. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/minimize_repro.py +466 -0
  433. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/patch_synthesizer.py +617 -0
  434. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/regression_pack.py +379 -0
  435. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/rsi_fixer.py +910 -0
  436. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/rsi_loop.py +311 -0
  437. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/rsi_repair.py +348 -0
  438. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/rsi_rounds.py +212 -0
  439. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/rsi_scope.py +281 -0
  440. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/self_heal.py +604 -0
  441. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/test_generator.py +1108 -0
  442. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/test_quality_auditor.py +410 -0
  443. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/test_strategy.py +511 -0
  444. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/INTERFACE.md +59 -0
  445. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/README.md +69 -0
  446. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/SPEC.md +28 -0
  447. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/__init__.py +47 -0
  448. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/attestation.py +228 -0
  449. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/authority.py +255 -0
  450. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/finding_report.py +418 -0
  451. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/formal_report_builder.py +924 -0
  452. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/html_renderers.py +696 -0
  453. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/models.py +759 -0
  454. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/pdf_exporter.py +231 -0
  455. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/projects_assets.py +730 -0
  456. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/report_client.py +743 -0
  457. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/report_data_builder.py +388 -0
  458. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/report_share.py +459 -0
  459. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/sast_bridge.py +116 -0
  460. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/server.py +832 -0
  461. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/visual_report_builder.py +796 -0
  462. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/web-conformance.md +168 -0
  463. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/web_conformance.py +428 -0
  464. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/workbench_assets.py +484 -0
  465. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/INTERFACE.md +20 -0
  466. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/README.md +161 -0
  467. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/SPEC.md +25 -0
  468. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/__init__.py +3 -0
  469. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/code_analyzer.py +1720 -0
  470. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/codebase_memory_bridge.py +337 -0
  471. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/context_assembler.py +240 -0
  472. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/corpus_fetch.py +369 -0
  473. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/graph_ego.py +597 -0
  474. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/knowledge_auto.py +662 -0
  475. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/knowledge_sources.py +168 -0
  476. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/knowledge_sync.py +1003 -0
  477. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/memory_store.py +480 -0
  478. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/query_planner.py +1020 -0
  479. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/rrf_engine.py +137 -0
  480. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/slice_extractor.py +1209 -0
  481. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/slice_normalizer.py +373 -0
  482. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/slice_spec.py +357 -0
  483. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/symbol_index.py +1151 -0
  484. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/universal_code_matcher.py +622 -0
  485. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/xerj_bridge.py +476 -0
  486. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/xerj_supervisor.py +362 -0
  487. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/README.md +33 -0
  488. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/ios/PROVENANCE.json +30 -0
  489. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/ios/crypto.yaml +36 -0
  490. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/ios/network.yaml +20 -0
  491. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/ios/resilience.yaml +47 -0
  492. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/ios/storage.yaml +48 -0
  493. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/LICENSE +173 -0
  494. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/PROVENANCE.json +270 -0
  495. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-asymmetric-key-pair-used-for-multiple-purposes.yml +13 -0
  496. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-backup-manifest.yml +24 -0
  497. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-biometric-event-bound.yml +49 -0
  498. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-biometric-invalidated-enrollment.yml +11 -0
  499. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-biometric-no-confirmation-required.yml +10 -0
  500. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-biometric-validity-duration.yml +24 -0
  501. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-broken-encryption-algorithms.yaml +9 -0
  502. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-broken-encryption-modes.yaml +13 -0
  503. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-content-provider-exported.yml +35 -0
  504. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-custom-deeplink-scheme.yml +29 -0
  505. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-dangerous-app-permissions.yaml +65 -0
  506. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-data-unencrypted-shared-storage-no-user-interaction-apis.yml +36 -0
  507. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-data-unencrypted-shared-storage-no-user-interaction-manifest.yml +15 -0
  508. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-debuggable-flag.yml +10 -0
  509. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-debugger-checks.yml +12 -0
  510. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-deeplink-autoverify-missing.yml +33 -0
  511. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-deeplink-unvalidated-parameter.yml +11 -0
  512. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-device-passcode-present.yml +17 -0
  513. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-fileprovider-broad-scope.yml +46 -0
  514. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-hardcoded-crypto-keys-usage.yml +14 -0
  515. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-hardcoded-security-provider.yaml +18 -0
  516. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-implicit-intent-internal-communication.yml +30 -0
  517. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-implicit-intent-leaking-extras.yml +29 -0
  518. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-input-field-usage.yml +11 -0
  519. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-key-generation-with-insufficient-key-length.yml +21 -0
  520. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-keyboard-cache-input-types.yml +10 -0
  521. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-local-storage-input-validation.yml +48 -0
  522. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-native-debugger-checks.yml +12 -0
  523. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-network-checkservertrusted.yml +12 -0
  524. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-network-hostname-verification.yml +11 -0
  525. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-network-insecure-trust-anchors.yml +11 -0
  526. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-network-onreceivedsslerror.yml +12 -0
  527. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-non-random-use.yml +16 -0
  528. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-object-deserialization.yml +14 -0
  529. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-overlay-protection.yml +68 -0
  530. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-pendingintent-mutable.yml +39 -0
  531. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-random-apis-insufficient-entropy.yml +17 -0
  532. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-root-detection.yaml +59 -0
  533. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-sdk-version.yml +10 -0
  534. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-sensitive-data-in-notifications-manifest.yml +17 -0
  535. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-sensitive-data-in-notifications.yml +11 -0
  536. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-sensitive-data-in-screenshot.yml +18 -0
  537. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-sql-injection-contentprovider.yml +17 -0
  538. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-ssl-socket-hostnameverifier.yml +15 -0
  539. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-strictmode.yml +10 -0
  540. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-system-alert-window.yml +9 -0
  541. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-webview-allow-local-access.yml +15 -0
  542. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-webview-bridges.yml +28 -0
  543. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-webview-safebrowsing.yml +20 -0
  544. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-webview-url-handlers.yml +41 -0
  545. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/miniprogram/PROVENANCE.json +26 -0
  546. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/miniprogram/network.yaml +37 -0
  547. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/miniprogram/platform.yaml +36 -0
  548. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/miniprogram/storage.yaml +48 -0
  549. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/LICENSE +165 -0
  550. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/PROVENANCE.json +58 -0
  551. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/auth.yaml +59 -0
  552. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/crypto.yaml +66 -0
  553. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/jailbreak.yaml +14 -0
  554. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/keyboard.yaml +34 -0
  555. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/logging.yaml +23 -0
  556. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/network.yaml +55 -0
  557. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/resilience.yaml +29 -0
  558. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/secrets.yaml +33 -0
  559. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/storage.yaml +29 -0
  560. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/webview.yaml +32 -0
  561. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/README.md +198 -0
  562. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/__init__.py +3 -0
  563. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/bugx_logging.py +1464 -0
  564. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/daemon_runner.py +623 -0
  565. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/fixture_solidify.py +444 -0
  566. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/global_telemetry.py +549 -0
  567. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/incident_eval.py +148 -0
  568. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/interaction.py +605 -0
  569. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/interaction_store.py +435 -0
  570. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/interactive_menu.py +95 -0
  571. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/log_analytics.py +922 -0
  572. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/mining_quality_framework.py +1387 -0
  573. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/model_runner.py +732 -0
  574. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/platform_adapter.py +579 -0
  575. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/prep_validate.py +478 -0
  576. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/project_graph.py +827 -0
  577. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/project_init.py +481 -0
  578. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/project_profile.py +224 -0
  579. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/project_settings.py +964 -0
  580. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/provider_window.py +97 -0
  581. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/resume_ticket.py +115 -0
  582. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/scenario_eval.py +856 -0
  583. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/seed_drill.py +549 -0
  584. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/self_audit.py +550 -0
  585. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/session_profile.py +205 -0
  586. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/setup_ui_env.py +229 -0
  587. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/startup_environment.py +859 -0
  588. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/sync_store.py +1421 -0
  589. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/tool_install_targets.py +18 -0
  590. bugx_cli-0.1.1.data/data/share/bugx-agent/core/schemas/README.md +35 -0
  591. bugx_cli-0.1.1.data/data/share/bugx-agent/core/schemas/agent-graph.schema.json +368 -0
  592. bugx_cli-0.1.1.data/data/share/bugx-agent/core/schemas/attack-graph.schema.json +88 -0
  593. bugx_cli-0.1.1.data/data/share/bugx-agent/core/schemas/evidence-bundle.schema.json +33 -0
  594. bugx_cli-0.1.1.data/data/share/bugx-agent/core/schemas/skill-pack.schema.json +230 -0
  595. bugx_cli-0.1.1.data/data/share/bugx-agent/core/schemas/worker-checkpoint.schema.json +119 -0
  596. bugx_cli-0.1.1.data/data/share/bugx-agent/core/secure_atomic.py +289 -0
  597. bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/README.md +55 -0
  598. bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/c.txt +29 -0
  599. bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/cpp.txt +32 -0
  600. bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/css.txt +70 -0
  601. bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/go.txt +46 -0
  602. bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/java.txt +30 -0
  603. bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/javascript.txt +55 -0
  604. bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/kotlin.txt +28 -0
  605. bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/python.txt +71 -0
  606. bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/rust.txt +53 -0
  607. bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/swift.txt +29 -0
  608. bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/typescript.txt +29 -0
  609. bugx_cli-0.1.1.data/data/share/bugx-agent/core/skills/README.md +53 -0
  610. bugx_cli-0.1.1.data/data/share/bugx-agent/core/skills/__init__.py +189 -0
  611. bugx_cli-0.1.1.data/data/share/bugx-agent/core/skills/bugx_docs_mcp_server.py +418 -0
  612. bugx_cli-0.1.1.data/data/share/bugx-agent/core/skills/bugx_mcp_server.py +1161 -0
  613. bugx_cli-0.1.1.data/data/share/bugx-agent/core/skills/mcp_runtime.py +968 -0
  614. bugx_cli-0.1.1.data/data/share/bugx-agent/core/skills/mcp_session_proof.py +605 -0
  615. bugx_cli-0.1.1.data/data/share/bugx-agent/core/skills/mobile_ui_inspector.py +405 -0
  616. bugx_cli-0.1.1.data/data/share/bugx-agent/core/skills/skill_pack.py +1214 -0
  617. bugx_cli-0.1.1.data/data/share/bugx-agent/core/skills/skill_synthesizer.py +1153 -0
  618. bugx_cli-0.1.1.data/data/share/bugx-agent/core/skills/tools_kb.py +313 -0
  619. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/INTERFACE.md +121 -0
  620. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/README.md +209 -0
  621. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/SPEC.md +25 -0
  622. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/__init__.py +175 -0
  623. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/audit_supervisor.py +1015 -0
  624. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/budget_governor.py +1254 -0
  625. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/checkpoint_handler.py +368 -0
  626. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/checkpoint_pipeline.py +1564 -0
  627. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/checkpoint_sync.py +653 -0
  628. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/claim_events.py +74 -0
  629. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/claim_sync.py +590 -0
  630. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/cli.py +812 -0
  631. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/context_sync.py +55 -0
  632. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/coverage_sync.py +115 -0
  633. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/finding_commit.py +470 -0
  634. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/finding_sync.py +688 -0
  635. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/finding_workflow.py +676 -0
  636. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/finish_policy.py +224 -0
  637. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/finish_sync.py +185 -0
  638. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/graph_sync.py +669 -0
  639. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/lease_manager.py +788 -0
  640. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/lifecycle_blocks.py +129 -0
  641. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/next_round_sync.py +126 -0
  642. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/observability.py +140 -0
  643. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/recovery_sync.py +165 -0
  644. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/rejection_remedies.py +355 -0
  645. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/round_governor.py +306 -0
  646. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/serial_authorization.py +544 -0
  647. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/start_sync.py +87 -0
  648. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/state_store.py +249 -0
  649. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/supervisor_host.py +511 -0
  650. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/supervisor_models.py +1143 -0
  651. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/systemic_failure.py +104 -0
  652. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/task_scheduler.py +1640 -0
  653. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/worker_checkpoint.py +230 -0
  654. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/worker_execution.py +265 -0
  655. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/worker_handoff.py +192 -0
  656. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/worker_lifecycle.py +396 -0
  657. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/worker_runtime.py +1005 -0
  658. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/worker_sync.py +89 -0
  659. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor_types/README.md +36 -0
  660. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor_types/__init__.py +0 -0
  661. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor_types/exceptions.py +52 -0
  662. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor_types/graph_models.py +357 -0
  663. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor_types/path_containment.py +151 -0
  664. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor_types/target_fingerprint.py +310 -0
  665. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor_types/worker_claim.py +411 -0
  666. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/INTERFACE.md +50 -0
  667. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/README.md +57 -0
  668. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/SPEC.md +26 -0
  669. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/__init__.py +11 -0
  670. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/adapters/__init__.py +27 -0
  671. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/adapters/base.py +87 -0
  672. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/adapters/bugx.py +102 -0
  673. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/adapters/claude.py +222 -0
  674. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/adapters/cline.py +407 -0
  675. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/adapters/codex.py +260 -0
  676. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/adapters/dsh.py +177 -0
  677. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/adapters/opencode.py +218 -0
  678. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/adapters/pi.py +272 -0
  679. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/adapters/registry.py +100 -0
  680. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/adapters/zcode.py +312 -0
  681. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/api_routes_post.py +668 -0
  682. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/dispatcher.py +1376 -0
  683. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/docs_session_service.py +473 -0
  684. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/handler.py +674 -0
  685. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/ide_cloud_service.py +526 -0
  686. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/mcp_inspector.py +1747 -0
  687. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/00-base.css +1060 -0
  688. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/01-monitoring.css +802 -0
  689. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/02-header-actions.css +321 -0
  690. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/03-trigger-popover.css +697 -0
  691. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/04-composer.css +628 -0
  692. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/05-skills-center.css +878 -0
  693. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/06-mcp-center.css +623 -0
  694. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/07-skill-detail.css +265 -0
  695. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/08-files-management.css +167 -0
  696. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/09-files-center.css +386 -0
  697. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/10-icons.css +105 -0
  698. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/11-project-options.css +185 -0
  699. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/12-profile-tab.css +383 -0
  700. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/index-CXAsl8mr.js +333 -0
  701. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/index-DHQUtWtx.css +1 -0
  702. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-cyrillic-400-normal-B8Z6Jvzv.woff +0 -0
  703. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-cyrillic-400-normal-C44pakCn.woff2 +0 -0
  704. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-cyrillic-500-normal-Bb4u56_6.woff +0 -0
  705. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-cyrillic-500-normal-BdVUvljg.woff2 +0 -0
  706. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-cyrillic-ext-400-normal-CWV284fw.woff2 +0 -0
  707. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-cyrillic-ext-400-normal-DLkyKLvH.woff +0 -0
  708. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-cyrillic-ext-500-normal-8-8HP2PF.woff +0 -0
  709. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-cyrillic-ext-500-normal-DaDZE_Na.woff2 +0 -0
  710. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-greek-400-normal-BccYJ-vZ.woff +0 -0
  711. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-greek-400-normal-Cw5-AHNN.woff2 +0 -0
  712. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-greek-500-normal-By8GFJzz.woff2 +0 -0
  713. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-greek-500-normal-z-Q6FFuG.woff +0 -0
  714. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-latin-400-normal-DJ5YJwmz.woff2 +0 -0
  715. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-latin-400-normal-Dn3IlU-Z.woff +0 -0
  716. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-latin-500-normal-CUHe9xxf.woff2 +0 -0
  717. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-latin-500-normal-DVVamBqs.woff +0 -0
  718. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-latin-ext-400-normal-CEpydyUl.woff +0 -0
  719. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-latin-ext-400-normal-Cp7z-ARB.woff2 +0 -0
  720. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-latin-ext-500-normal-BYjRCDVy.woff2 +0 -0
  721. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-latin-ext-500-normal-D-qasQTj.woff +0 -0
  722. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-vietnamese-400-normal-BbG3LG1A.woff2 +0 -0
  723. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-vietnamese-400-normal-DR1UuFon.woff +0 -0
  724. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-vietnamese-500-normal-8N8MYVKB.woff +0 -0
  725. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-vietnamese-500-normal-Bi3OSTTW.woff2 +0 -0
  726. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/design-tokens.css +113 -0
  727. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/favicon.png +0 -0
  728. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/icon-192.png +0 -0
  729. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/index.html +55 -0
  730. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/manifest.webmanifest +19 -0
  731. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/project-settings.js +9602 -0
  732. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/sw.js +8 -0
  733. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/workspace_service.py +218 -0
  734. bugx_cli-0.1.1.data/data/share/bugx-agent/dsh/agents/bugx.md +27 -0
  735. bugx_cli-0.1.1.data/data/share/bugx-agent/dsh/dsh-patch.yml +18 -0
  736. bugx_cli-0.1.1.data/data/share/bugx-agent/dsh/mcp/cordis.patch.yml +4 -0
  737. bugx_cli-0.1.1.data/data/share/bugx-agent/dsh/mcp/index.js +219 -0
  738. bugx_cli-0.1.1.data/data/share/bugx-agent/dsh/mcp/package.json +28 -0
  739. bugx_cli-0.1.1.data/data/share/bugx-agent/dsh/skills/bugx/SKILL.md +70 -0
  740. bugx_cli-0.1.1.data/data/share/bugx-agent/dsh/skills/bugx-dsh/SKILL.md +229 -0
  741. bugx_cli-0.1.1.data/data/share/bugx-agent/dsh/ui/client.js +87 -0
  742. bugx_cli-0.1.1.data/data/share/bugx-agent/dsh/ui/cordis.patch.yml +4 -0
  743. bugx_cli-0.1.1.data/data/share/bugx-agent/dsh/ui/index.js +7 -0
  744. bugx_cli-0.1.1.data/data/share/bugx-agent/dsh/ui/package.json +27 -0
  745. bugx_cli-0.1.1.data/data/share/bugx-agent/mcp-lock.json +3075 -0
  746. bugx_cli-0.1.1.data/data/share/bugx-agent/opencode.json +129 -0
  747. bugx_cli-0.1.1.data/data/share/bugx-agent/pi/extensions/bugx/README.md +12 -0
  748. bugx_cli-0.1.1.data/data/share/bugx-agent/pi/extensions/bugx/index.ts +299 -0
  749. bugx_cli-0.1.1.data/data/share/bugx-agent/pi/extensions/bugx/manifest.json +11 -0
  750. bugx_cli-0.1.1.data/data/share/bugx-agent/pi/skills/bugx/SKILL.md +69 -0
  751. bugx_cli-0.1.1.data/data/share/bugx-agent/plugins/bugx/skills/bugx-claude/SKILL.md +326 -0
  752. bugx_cli-0.1.1.data/data/share/bugx-agent/plugins/bugx/skills/bugx-opencode/SKILL.md +129 -0
  753. bugx_cli-0.1.1.data/data/share/bugx-agent/plugins/bugx/skills/bugx-zcode/SKILL.md +459 -0
  754. bugx_cli-0.1.1.data/data/share/bugx-agent/workbuddy/connector-meta.json +19 -0
  755. bugx_cli-0.1.1.data/data/share/bugx-agent/workbuddy/icon.png +0 -0
  756. bugx_cli-0.1.1.data/data/share/bugx-agent/workbuddy/skills/bugx/SKILL.md +70 -0
  757. bugx_cli-0.1.1.dist-info/METADATA +335 -0
  758. bugx_cli-0.1.1.dist-info/RECORD +762 -0
  759. bugx_cli-0.1.1.dist-info/WHEEL +5 -0
  760. bugx_cli-0.1.1.dist-info/entry_points.txt +2 -0
  761. bugx_cli-0.1.1.dist-info/licenses/LICENSE +55 -0
  762. bugx_cli-0.1.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1704 @@
1
+ #!/usr/bin/env python3
2
+ """prompt_harness.py — BugX 阶段 Harness 与提示词编译装配中心 (DOC-038, DOC-043)。
3
+
4
+ 提供:
5
+ - load_stage: 按阶段加载 L1 提示词 (gate / explore / mutate / repair)
6
+ - load_rule: 按名称加载 L2 专项规则库 (concurrency / memory_leak / prompt_injection / anti_patterns)
7
+ - get_stage_prompt: 组装阶段 Harness 与动态上下文
8
+ - analyze_source_rules: 基于 AST 静态推断源码关联规则 (DOC-043)
9
+ - detect_unit_rule_slice: 依据 AST 特征或单元特质智能提取 L2 规则片段 (DOC-043)
10
+ - get_stage_metadata: 获取阶段行为契约与异构模型分级建议 (DOC-043)
11
+ - decorate_stage_task: 状态机驱动的主动任务修饰与 Harness 注入 (DOC-043)
12
+ - enforce_section_budget: 注入分段的 Token 硬预算强制与截断留痕 (DOC-043, DOC-125)
13
+ - enforce_global_budget: 在段级上限之内分配统一 Prompt 总预算
14
+ - distill_evidence: 长堆栈与 Fuzz 输出结构化证据蒸馏 (DOC-043)
15
+ """
16
+
17
+ from __future__ import annotations
18
+ from collections.abc import Sequence
19
+
20
+ import ast
21
+ from collections import OrderedDict
22
+ import logging
23
+ import os
24
+ from pathlib import Path
25
+ import re
26
+ from typing import Any, Mapping
27
+
28
+ from core.planning import unit_kind
29
+
30
+ try:
31
+ from core.governance import token_budget
32
+ except ImportError:
33
+ try:
34
+ from core.governance import token_budget
35
+ except ImportError: # pragma: no cover
36
+ token_budget = None # type: ignore[assignment]
37
+
38
+ try:
39
+ import core.i18n as i18n
40
+ except ImportError:
41
+ try:
42
+ from . import i18n
43
+ except ImportError:
44
+ i18n = None # type: ignore[assignment]
45
+
46
+ def _get_skill_pack():
47
+ from core.skills import skill_pack
48
+ return skill_pack
49
+
50
+ try:
51
+ from core.planning import domain_archetype
52
+ except ImportError:
53
+ try:
54
+ from . import domain_archetype
55
+ except ImportError: # pragma: no cover
56
+ domain_archetype = None # type: ignore[assignment]
57
+
58
+ SKILL_WORKER_AFFINITY_TIER = {
59
+ "recon": ("Recon-Worker", "FAST"),
60
+ "auth": ("Auth-Worker", "BALANCED"),
61
+ "logic": ("Logic-Worker", "PRO"),
62
+ "exploit": ("Exploit-Worker", "PRO"),
63
+ "patch": ("Patch-Worker", "BALANCED"),
64
+ }
65
+
66
+ # DOC-043 / DOC-125 / DOC-248:各注入分段的硬预算上限(单位:conservative token)。
67
+ # 这些数值此前只是提示词里的标签字符串,本模块现在在出口真正强制它们。
68
+ # 数值来源:core/bugx-runtime-contract.md §下一代智能 Prompt Harness 契约。
69
+ HARNESS_SECTION_BUDGETS: dict[str, int] = {
70
+ "l0_router": 1500, # L0 路由入口
71
+ "l1_stage_harness": 2500, # L1 阶段专精 Harness
72
+ "l2_rule_slice": 500, # L2 专项规则智能切片
73
+ "l2_risk_radar": 500, # L2 代码智能脆弱性雷达
74
+ "skill_l1_checklist": 300, # 技能包 L1 核心行动清单(DOC-125 默认)
75
+ "skill_attack_graph_slice": 200, # 技能包 Attack Graph 切片摘要
76
+ "skill_experience_hint": 600, # 技能包 L2 经验检索建议(DOC-125 默认)
77
+ # DOC-248 三维正交领域专精分段预算
78
+ "header_role": 150,
79
+ "role_sop": 1200,
80
+ "tech_slice": 500,
81
+ "probes_spec": 600,
82
+ "domain_fixtures": 800,
83
+ "task_context": 500,
84
+ }
85
+
86
+ # DOC-139 / DOC-248:段级预算的安全天花板。调用方可以把某一段预算调高,但不能
87
+ # 通过配置绕过这些上限;低于地板的值也不会让截断标记本身被截掉。
88
+ HARNESS_SECTION_BUDGET_CEILINGS: dict[str, int] = {
89
+ "l0_router": 3000,
90
+ "l1_stage_harness": 4000,
91
+ "l2_rule_slice": 1200,
92
+ "l2_risk_radar": 1200,
93
+ "skill_l1_checklist": 800,
94
+ "skill_attack_graph_slice": 600,
95
+ "skill_experience_hint": 1500,
96
+ "dynamic_context": 800,
97
+ # DOC-248
98
+ "header_role": 300,
99
+ "role_sop": 2000,
100
+ "tech_slice": 1000,
101
+ "probes_spec": 1000,
102
+ "domain_fixtures": 1500,
103
+ "task_context": 1000,
104
+ }
105
+
106
+ # 这是段级 clamp 已经使用的最小可分配额度,而不是凭空新增的总预算。
107
+ # 全局预算由调用方实际启用的段级 ceiling 求和得到,避免另造一套数字。
108
+ HARNESS_SECTION_BUDGET_FLOOR = 50
109
+ # Keep a usable task specification even when a high-priority rule section is
110
+ # larger than the worker envelope; fail closed if the caller cannot afford it.
111
+ HARNESS_TASK_TEXT_FLOOR = 200
112
+
113
+ # The worker task itself is a budgeted section too. These totals preserve the
114
+ # existing documented envelopes while preventing a full L1 card from reducing
115
+ # the actual task specification to the 50-token floor.
116
+ HARNESS_WORKER_GLOBAL_BUDGET = 3500
117
+ HARNESS_SKILL_GLOBAL_BUDGET = 1800
118
+
119
+ logger = logging.getLogger("bugx.prompt_harness")
120
+ _TOKEN_ESTIMATOR_FAILURE_LOGGED = False
121
+
122
+ _STAGE_MAP = {
123
+ "l0": "l0_router.md",
124
+ "gate": "stages/stage_gate.md",
125
+ "explore": "stages/stage_explore.md",
126
+ "mutate": "stages/stage_mutate.md",
127
+ "repair": "stages/stage_repair.md",
128
+ }
129
+
130
+ _RULE_MAP = {
131
+ "concurrency": "rules/concurrency_rules.md",
132
+ "memory_leak": "rules/memory_leak_rules.md",
133
+ "prompt_injection": "rules/prompt_injection_defense.md",
134
+ "anti_patterns": "rules/anti_patterns.md",
135
+ }
136
+
137
+ _STAGE_TIER_MAP: dict[str, dict[str, Any]] = {
138
+ "gate": {
139
+ "tier": "tier_1_lightweight",
140
+ "description": "快速轻量级模型 (Flash / Haiku / GPT-4o-mini),适用于快速门禁与基线核验",
141
+ "allowed_actions": ["check", "inspect", "diff", "pre_check"],
142
+ "recommended_tools": ["bugx_supervisor_gate", "bugx_supervisor_status"],
143
+ },
144
+ "explore": {
145
+ "tier": "tier_1_lightweight",
146
+ "description": "高吞吐扫描模型 (Flash / Haiku / GPT-4o-mini),适用于大规模单元与路由勘察",
147
+ "allowed_actions": ["discover", "scan", "ast_inspect", "manifest_build", "mining_explore", "plan_audit"],
148
+ "recommended_tools": ["bugx_mining_explore", "bugx_mining_audit", "bugx_mining_harden"],
149
+ },
150
+ "mutate": {
151
+ "tier": "tier_2_deep_reasoning",
152
+ "description": "深度推理模型 (Sonnet / DeepSeek-R1 / GPT-4o),适用于并发竞态、状态推演与差分验证",
153
+ "allowed_actions": ["fuzz", "perturb", "differential_test", "race_detect", "test_verify"],
154
+ "recommended_tools": ["bugx_test_verify", "bugx_test_mutate", "bugx_fuzz_input", "bugx_fuzz_concurrency", "bugx_fuzz_stateful"],
155
+ },
156
+ "repair": {
157
+ "tier": "tier_3_precise_code",
158
+ "description": "高精度工程代码模型 (Claude 3.5 Sonnet / Codex),适用于 TDD 最小修复与单测闭环",
159
+ "allowed_actions": ["minimize_repro", "tdd_fix", "directed_test", "post_settle", "test_verify"],
160
+ "recommended_tools": ["bugx_minimize_repro", "bugx_test_verify"],
161
+ },
162
+ }
163
+
164
+ _AST_RULE_CACHE_MAX = 256
165
+ _AST_RULE_CACHE: OrderedDict[str, tuple[int, int, list[str]]] = OrderedDict()
166
+
167
+
168
+ def _cached_ast_rules(path: Path) -> list[str] | None:
169
+ """Return rules only while the cached file fingerprint is unchanged."""
170
+ key = str(path.resolve())
171
+ try:
172
+ stat = path.stat()
173
+ except OSError:
174
+ _AST_RULE_CACHE.pop(key, None)
175
+ return None
176
+ cached = _AST_RULE_CACHE.get(key)
177
+ if cached and cached[:2] == (stat.st_mtime_ns, stat.st_size):
178
+ _AST_RULE_CACHE.move_to_end(key)
179
+ return cached[2]
180
+ if cached:
181
+ _AST_RULE_CACHE.pop(key, None)
182
+ return None
183
+
184
+
185
+ def _cache_ast_rules(path: Path, rules: list[str]) -> None:
186
+ key = str(path.resolve())
187
+ try:
188
+ stat = path.stat()
189
+ except OSError:
190
+ return
191
+ _AST_RULE_CACHE[key] = (stat.st_mtime_ns, stat.st_size, rules)
192
+ _AST_RULE_CACHE.move_to_end(key)
193
+ while len(_AST_RULE_CACHE) > _AST_RULE_CACHE_MAX:
194
+ _AST_RULE_CACHE.popitem(last=False)
195
+
196
+ _RE_PY_TRACE = re.compile(
197
+ r'File "(?P<file>[^"]+)", line (?P<line>\d+), in (?P<func>\w+)\n\s*(?P<code>.+)',
198
+ re.MULTILINE,
199
+ )
200
+ _RE_EXC_LINE = re.compile(
201
+ r'^(?P<exc>[A-Za-z0-9_]+(?:Error|Exception)):\s*(?P<msg>.*)$',
202
+ re.MULTILINE,
203
+ )
204
+ _RE_ASSERT_FAIL = re.compile(r'AssertionError:\s*(.*)', re.DOTALL)
205
+
206
+
207
+ def _estimate_section_tokens(text: str) -> tuple[int, str]:
208
+ """复用 ``token_budget.estimate_tokens``;缺失时退化为保守 UTF-8 估算。
209
+
210
+ 绝不返回“假装精确”的模型真实 token 数,同时保证本模块在 token_budget
211
+ 不可导入时仍能强制预算(fail-closed,而不是静默放行)。
212
+ """
213
+ if token_budget is not None:
214
+ try:
215
+ return token_budget.estimate_tokens(text)
216
+ except Exception as exc: # pragma: no cover - provider failure is environment-specific
217
+ global _TOKEN_ESTIMATOR_FAILURE_LOGGED
218
+ if not _TOKEN_ESTIMATOR_FAILURE_LOGGED:
219
+ logger.warning("prompt token estimator failed; using conservative fallback: %s", exc)
220
+ _TOKEN_ESTIMATOR_FAILURE_LOGGED = True
221
+ raw = text.encode("utf-8")
222
+ return max(1, (len(raw) + 2) // 3), "conservative-utf8-fallback"
223
+
224
+
225
+ class BudgetAllocationError(ValueError):
226
+ """全局预算无法同时满足段级地板时的显式失败。"""
227
+
228
+
229
+ def _clamp_section_budget(name: str, requested: object, default: int) -> int:
230
+ """应用段级地板/ceiling;非法配置显式失败,不静默放大预算。"""
231
+ try:
232
+ value = default if requested is None else int(requested)
233
+ except (TypeError, ValueError, OverflowError) as exc:
234
+ raise BudgetAllocationError(f"{name} budget 必须是整数") from exc
235
+ if isinstance(requested, bool):
236
+ raise BudgetAllocationError(f"{name} budget 不接受布尔值")
237
+ ceiling = HARNESS_SECTION_BUDGET_CEILINGS.get(name, value)
238
+ return min(max(value, HARNESS_SECTION_BUDGET_FLOOR), ceiling)
239
+
240
+
241
+ def enforce_global_budget(
242
+ sections: Mapping[str, str],
243
+ total_budget: int,
244
+ *,
245
+ caps: Mapping[str, int] | None = None,
246
+ floors: Mapping[str, int] | None = None,
247
+ priorities: Mapping[str, int] | None = None,
248
+ labels: Mapping[str, str] | None = None,
249
+ ) -> tuple[dict[str, str], list[dict[str, Any]]]:
250
+ """在段级 ceiling 之内分配一个真实的全局预算。
251
+
252
+ ``enforce_section_budget`` 仍负责最终的保留前缀与降级标记;本函数只
253
+ 决定每段在同一个总额中的额度。分配先满足每个非空段的 floor,再按
254
+ ``priorities`` 从高到低给有剩余需求的段分配,无法满足 floor 时显式失败。
255
+ 未传 ``caps`` 时不猜数字,而是使用调用方给出的段级 ceiling/默认值。
256
+ """
257
+ if isinstance(total_budget, bool) or not isinstance(total_budget, int) or total_budget < 1:
258
+ raise BudgetAllocationError("全局 prompt budget 必须是正整数")
259
+
260
+ ordered = list(sections.items())
261
+ cap_map = dict(caps or {})
262
+ floor_map = dict(floors or {})
263
+ priority_map = dict(priorities or {})
264
+ label_map = dict(labels or {})
265
+ prepared: list[dict[str, Any]] = []
266
+ for index, (name, text) in enumerate(ordered):
267
+ if not isinstance(text, str):
268
+ raise BudgetAllocationError(f"{name} prompt section 必须是字符串")
269
+ if not text.strip():
270
+ continue
271
+ default_cap = cap_map.get(name, total_budget)
272
+ cap = _clamp_section_budget(name, default_cap, total_budget)
273
+ requested_floor = floor_map.get(name, HARNESS_SECTION_BUDGET_FLOOR)
274
+ floor = _clamp_section_budget(name, requested_floor, HARNESS_SECTION_BUDGET_FLOOR)
275
+ if floor > cap:
276
+ floor = cap
277
+ actual, method = _estimate_section_tokens(text)
278
+ desired = min(actual, cap)
279
+ prepared.append({
280
+ "name": name,
281
+ "text": text,
282
+ "actual": actual,
283
+ "method": method,
284
+ "cap": cap,
285
+ "floor": min(desired, floor),
286
+ "desired": desired,
287
+ "priority": priority_map.get(name, -index),
288
+ "label": label_map.get(name, name),
289
+ })
290
+
291
+ required = sum(item["floor"] for item in prepared)
292
+ if required > total_budget:
293
+ raise BudgetAllocationError(
294
+ f"全局 prompt budget {total_budget}T 不足以满足段级地板 {required}T"
295
+ )
296
+
297
+ remaining = total_budget - required
298
+ # 稳定排序:显式 priority 高的先分配,同优先级保留调用方顺序。
299
+ allocation = {item["name"]: item["floor"] for item in prepared}
300
+ for item in sorted(prepared, key=lambda value: -value["priority"]):
301
+ extra = min(remaining, item["desired"] - allocation[item["name"]])
302
+ allocation[item["name"]] += extra
303
+ remaining -= extra
304
+ if remaining == 0:
305
+ break
306
+
307
+ result: dict[str, str] = {}
308
+ degradations: list[dict[str, Any]] = []
309
+ for item in prepared:
310
+ name = item["name"]
311
+ text, record = enforce_section_budget(
312
+ item["text"], allocation[name], item["label"],
313
+ )
314
+ result[name] = text
315
+ if record:
316
+ record["global_budget"] = total_budget
317
+ record["allocated"] = allocation[name]
318
+ degradations.append(record)
319
+ # 保留空段,方便调用方不必重新拼装不存在的可选片段。
320
+ result.update({name: text for name, text in ordered if name not in result})
321
+ return result, degradations
322
+
323
+
324
+ def enforce_section_budget(
325
+ text: str,
326
+ cap: int,
327
+ label: str,
328
+ ) -> tuple[str, dict[str, Any] | None]:
329
+ """把单段注入文本硬截断到 ``cap`` token 以内(DOC-043 / DOC-125)。
330
+
331
+ 返回 ``(可能被截断的文本, 截断记录或 None)``。截断记录包含 ``label`` /
332
+ ``cap`` / ``tokens`` / ``token_method``,用于上层汇总为 DEGRADED 事件。
333
+ 截断处会留下显式标记,绝不静默丢弃内容。
334
+ """
335
+ if not isinstance(cap, int) or isinstance(cap, bool) or cap <= 0:
336
+ raise BudgetAllocationError(f"{label} budget 必须是正整数")
337
+ if not text or not text.strip():
338
+ return text, None
339
+
340
+ tokens, method = _estimate_section_tokens(text)
341
+ if tokens <= cap:
342
+ return text, None
343
+
344
+ marker = (
345
+ f"\n... [BUDGET-DEGRADED: {label} 超出硬预算 {cap}T"
346
+ f"(实测 {tokens}T),已硬截断;完整内容见原始文件] ..."
347
+ )
348
+ marker_tokens, _ = _estimate_section_tokens(marker)
349
+ if marker_tokens > cap:
350
+ raise BudgetAllocationError(
351
+ f"{label} budget {cap}T 小于截断标记所需 {marker_tokens}T"
352
+ )
353
+ # 二分查找最大前缀,保证「前缀 + 标记」整体不超预算。
354
+ lo, hi, best = 0, len(text), 0
355
+ while lo <= hi:
356
+ mid = (lo + hi) // 2
357
+ if _estimate_section_tokens(text[:mid] + marker)[0] <= cap:
358
+ best = mid
359
+ lo = mid + 1
360
+ else:
361
+ hi = mid - 1
362
+
363
+ truncated = text[:best].rstrip() + marker
364
+ return truncated, {
365
+ "label": label,
366
+ "cap": cap,
367
+ "tokens": tokens,
368
+ "token_method": method,
369
+ "truncated": True,
370
+ }
371
+
372
+
373
+ def _record_budget_degradations(
374
+ degradations: list[dict[str, Any]],
375
+ *,
376
+ stage: str,
377
+ ) -> str:
378
+ """汇总截断记录:发出 DEGRADED 事件并渲染机器可读的降级记录段。"""
379
+ if not degradations:
380
+ return ""
381
+ logger.warning(
382
+ "harness.budget_degraded: stage=%s sections=%s",
383
+ stage,
384
+ ", ".join(
385
+ f"{d['label']}({d['tokens']}T>{d['cap']}T)" for d in degradations
386
+ ),
387
+ extra={
388
+ "bugx_event": "harness.budget_degraded",
389
+ "status": "DEGRADED",
390
+ "stage": stage,
391
+ "sections": [
392
+ {
393
+ "label": d["label"],
394
+ "cap": d["cap"],
395
+ "tokens": d["tokens"],
396
+ "token_method": d["token_method"],
397
+ }
398
+ for d in degradations
399
+ ],
400
+ },
401
+ )
402
+ lines = [
403
+ "",
404
+ "-" * 57,
405
+ "=== Budget Degradation Record (DEGRADED) ===",
406
+ ]
407
+ for d in degradations:
408
+ lines.append(
409
+ f"- {d['label']}: 实测 {d['tokens']}T > 硬预算 {d['cap']}T,已硬截断"
410
+ )
411
+ return "\n".join(lines)
412
+
413
+
414
+ def get_prompts_dir(root: Path | None = None) -> Path:
415
+ """定位全局引擎 prompts 根目录,兼容源码目录与安装目录。"""
416
+ if root is not None:
417
+ p1 = root / "core" / "prompts"
418
+ if p1.is_dir():
419
+ return p1
420
+ current = Path(__file__).resolve().parent
421
+ local_prompts = current / "prompts"
422
+ if local_prompts.is_dir():
423
+ return local_prompts
424
+
425
+ home = os.environ.get("BUGX_HOME")
426
+ if home:
427
+ home_prompts = Path(home).expanduser() / "core" / "prompts"
428
+ if home_prompts.is_dir():
429
+ return home_prompts
430
+
431
+ # 全局引擎根(BUGX_GLOBAL_ENGINE_ROOT 刻意不隔离:引擎是只读资产)。
432
+ # 测试沙盒只隔离 HOME/BUGX_HOME,经它们解析会落到缺资产的假家;
433
+ # 只读的阶段提示词应回到真实引擎根解析,否则「直跑单模块过、进
434
+ # runner 的 shard 沙盒就 FileNotFoundError」。
435
+ global_engine_root = os.environ.get("BUGX_GLOBAL_ENGINE_ROOT")
436
+ if global_engine_root:
437
+ global_prompts = Path(global_engine_root).expanduser() / "prompts"
438
+ if global_prompts.is_dir():
439
+ return global_prompts
440
+
441
+ # 回退至全局引擎 prompts
442
+ default_home = Path.home() / ".bugx" / "core" / "prompts"
443
+ return default_home
444
+
445
+
446
+ def list_available_stages() -> list[str]:
447
+ return sorted(k for k in _STAGE_MAP.keys() if k != "l0")
448
+
449
+
450
+ # bugx.md 权威章节 → 阶段映射(P1,2026-09-06)。
451
+ # 阶段卡是精简执行摘要;详细规则的权威来源是 bugx.md 对应章节。
452
+ # 键 = prompt_harness 阶段名;值 = bugx.md 章节标题(与文内 `## `/`### ` 精确匹配)。
453
+ STAGE_SECTIONS: dict[str, tuple[str, ...]] = {
454
+ "gate": (
455
+ "当前执行口径(唯一生效规则)",
456
+ "宿主原生交互适配",
457
+ "宪法",
458
+ ),
459
+ "explore": (
460
+ "工作流程(每轮内的完整动作)",
461
+ "持久化状态文件",
462
+ ),
463
+ "mutate": (
464
+ "Round 内 Life 执行(严格遵守)",
465
+ "目标内容注入防御(对抗性红线)",
466
+ ),
467
+ "repair": (
468
+ "修复环节(发现之后必须做的闭环)",
469
+ "寿命结算规则(决定你的生死)",
470
+ "错题集(经验记忆:反思 → 归类 → 复用)",
471
+ "bug 记录清单(只记录模式的产物,也是全模式的去重依据)",
472
+ ),
473
+ }
474
+
475
+
476
+ def stage_sections(stage: str, root: Path | None = None) -> list[str]:
477
+ """返回该阶段在 bugx.md 的权威章节标题(存在性已校验)。
478
+
479
+ 显式传入 root 时严格以 `<root>/core/bugx.md` 为准,缺失返回空——
480
+ 协议测试沙盒不得静默回退读取安装引擎的真实 bugx.md。
481
+ """
482
+ if root is not None:
483
+ guide = root / "core" / "bugx.md"
484
+ if not guide.is_file():
485
+ return []
486
+ else:
487
+ guide = get_prompts_dir(root).parent / "bugx.md"
488
+ if not guide.is_file():
489
+ return []
490
+ try:
491
+ text = guide.read_text(encoding="utf-8")
492
+ except (OSError, UnicodeError):
493
+ return []
494
+ return [
495
+ title for title in STAGE_SECTIONS.get(stage.strip().lower(), ())
496
+ if re.search(rf"^##+\s*{re.escape(title)}\s*$", text, re.M)
497
+ ]
498
+
499
+
500
+ def _stage_section_pointers(stage: str, root: Path | None = None) -> str:
501
+ """生成阶段卡尾部的权威章节指针段(机器生成,不漂移)。"""
502
+ titles = stage_sections(stage, root)
503
+ if not titles:
504
+ return ""
505
+ lines = ["", "## 权威章节指针(bugx.md 按需提取;本卡与全文冲突时以全文为准)"]
506
+ for title in titles:
507
+ lines.append(
508
+ f"- bugx.md §{title}(`bugx engine path --name bugx.md` 后按章节读取)"
509
+ )
510
+ return "\n".join(lines)
511
+
512
+
513
+ def load_stage(stage: str, root: Path | None = None) -> str:
514
+ """加载指定阶段的提示词内容。"""
515
+ key = stage.strip().lower()
516
+ if key not in _STAGE_MAP:
517
+ raise ValueError(
518
+ f"未知的阶段: {stage},可选: {', '.join(sorted(_STAGE_MAP.keys()))}"
519
+ )
520
+ prompts_dir = get_prompts_dir(root)
521
+ file_path = prompts_dir / _STAGE_MAP[key]
522
+ if not file_path.is_file():
523
+ raise FileNotFoundError(f"阶段提示词文件缺失: {file_path}")
524
+ content = file_path.read_text(encoding="utf-8").strip()
525
+ # P1:附加 bugx.md 权威章节指针,消除"阶段卡 vs 全文"双源竞争。
526
+ content += _stage_section_pointers(key, root)
527
+ if key == "l0":
528
+ # CLI 的 ``prompt --stage l0`` 直接调用 load_stage,因此 L0 不能
529
+ # 只在 get_stage_prompt 中受预算保护。
530
+ sections, degradations = enforce_global_budget(
531
+ {"l0_router": content},
532
+ HARNESS_SECTION_BUDGETS["l0_router"],
533
+ caps={"l0_router": HARNESS_SECTION_BUDGETS["l0_router"]},
534
+ labels={"l0_router": "L0 路由入口"},
535
+ )
536
+ return sections["l0_router"] + _record_budget_degradations(
537
+ degradations, stage="l0",
538
+ )
539
+ return content
540
+
541
+
542
+ def load_rule(rule_name: str, root: Path | None = None) -> str:
543
+ """加载指定名称的规则库内容。"""
544
+ key = rule_name.strip().lower()
545
+ if key not in _RULE_MAP:
546
+ raise ValueError(
547
+ f"未知的规则: {rule_name},可选: {', '.join(sorted(_RULE_MAP.keys()))}"
548
+ )
549
+ prompts_dir = get_prompts_dir(root)
550
+ file_path = prompts_dir / _RULE_MAP[key]
551
+ if not file_path.is_file():
552
+ raise FileNotFoundError(f"专项规则文件缺失: {file_path}")
553
+ return file_path.read_text(encoding="utf-8").strip()
554
+
555
+
556
+ def get_stage_prompt(
557
+ stage: str,
558
+ context: Mapping[str, object] | None = None,
559
+ root: Path | None = None,
560
+ locale: str | None = None,
561
+ ) -> str:
562
+ """组装阶段提示词,注入动态上下文事实 (DOC-043, DOC-067, DOC-139)。"""
563
+ key = stage.strip().lower()
564
+ base_prompt = load_stage(key, root=root)
565
+ if not context:
566
+ # L0 是常驻入口,也必须经过和其他注入段相同的硬预算出口。
567
+ if key == "l0":
568
+ return base_prompt
569
+ return base_prompt
570
+
571
+ title = "## 动态运行时事实(Dynamic Context)"
572
+ if i18n is not None:
573
+ title = i18n.prompt_text("harness.dynamic_context_title", locale=locale, fallback=title)
574
+ context_lines = [f"\n\n{title}"]
575
+ for k, v in context.items():
576
+ value = str(v)
577
+ if len(value) > 500:
578
+ value = value[:470] + " ...[TRUNCATED]"
579
+ context_lines.append(f"- **{k}**: {value}")
580
+ context_text = "\n".join(context_lines)
581
+ context_text, context_degradations = enforce_section_budget(
582
+ context_text,
583
+ _clamp_section_budget(
584
+ "dynamic_context",
585
+ HARNESS_SECTION_BUDGET_CEILINGS["dynamic_context"],
586
+ HARNESS_SECTION_BUDGET_CEILINGS["dynamic_context"],
587
+ ),
588
+ "Dynamic Context 事实注入",
589
+ )
590
+ if key == "l0":
591
+ # L0 与动态事实共同受一个总额约束;不把动态事实偷偷追加到
592
+ # 已经满额的常驻路由卡之后。
593
+ sections, degradations = enforce_global_budget(
594
+ {"l0_router": base_prompt, "dynamic_context": context_text},
595
+ HARNESS_SECTION_BUDGETS["l0_router"]
596
+ + HARNESS_SECTION_BUDGET_CEILINGS["dynamic_context"],
597
+ caps={
598
+ "l0_router": HARNESS_SECTION_BUDGETS["l0_router"],
599
+ "dynamic_context": HARNESS_SECTION_BUDGET_CEILINGS["dynamic_context"],
600
+ },
601
+ priorities={"l0_router": 2, "dynamic_context": 1},
602
+ labels={
603
+ "l0_router": "L0 路由入口",
604
+ "dynamic_context": "Dynamic Context 事实注入",
605
+ },
606
+ )
607
+ return sections["l0_router"] + sections["dynamic_context"] + _record_budget_degradations(
608
+ context_degradations + degradations, stage="l0",
609
+ )
610
+ return base_prompt + context_text + _record_budget_degradations(
611
+ context_degradations, stage=key,
612
+ )
613
+
614
+
615
+ def get_stage_metadata(stage: str, locale: str | None = None) -> dict[str, Any]:
616
+ """返回指定阶段的模型分级与行为契约元数据 (DOC-043, DOC-067)。"""
617
+ key = stage.strip().lower()
618
+ meta = _STAGE_TIER_MAP.get(key)
619
+ if meta is None:
620
+ desc = "通用默认模型"
621
+ if i18n is not None:
622
+ desc = i18n.prompt_text("tier.default.description", locale=locale, fallback=desc)
623
+ return {
624
+ "stage": key,
625
+ "tier": "tier_1_lightweight",
626
+ "description": desc,
627
+ "allowed_actions": ["general_audit"],
628
+ }
629
+ desc = meta.get("description", "")
630
+ if i18n is not None:
631
+ desc = i18n.prompt_text(f"tier.{key}.description", locale=locale, fallback=desc)
632
+ return {
633
+ "stage": key,
634
+ **meta,
635
+ "description": desc,
636
+ }
637
+
638
+
639
+
640
+ def analyze_source_rules(source_code: str) -> list[str]:
641
+ """通过 Python AST 静态推断源码所涉及的技术领域,返回匹配的规则名列表 (DOC-043)。"""
642
+ if not source_code or not source_code.strip():
643
+ return []
644
+ rules: list[str] = []
645
+ try:
646
+ tree = ast.parse(source_code)
647
+ except (SyntaxError, UnicodeDecodeError, ValueError):
648
+ return []
649
+
650
+ has_concurrency = False
651
+ has_leak = False
652
+ has_injection = False
653
+
654
+ for node in ast.walk(tree):
655
+ if isinstance(node, ast.Import):
656
+ for alias in node.names:
657
+ name = alias.name.lower()
658
+ if any(m in name for m in ("threading", "multiprocessing", "asyncio", "concurrent.futures")):
659
+ has_concurrency = True
660
+ if any(m in name for m in ("socket", "sqlite3", "psycopg", "pymysql", "sqlalchemy", "requests", "aiohttp", "urllib")):
661
+ has_leak = True
662
+ if any(m in name for m in ("pickle", "yaml", "subprocess", "shutil")):
663
+ has_injection = True
664
+ elif isinstance(node, ast.ImportFrom):
665
+ mod = (node.module or "").lower()
666
+ if any(m in mod for m in ("threading", "multiprocessing", "asyncio", "concurrent")):
667
+ has_concurrency = True
668
+ if any(m in mod for m in ("socket", "sqlite3", "psycopg", "pymysql", "sqlalchemy", "urllib")):
669
+ has_leak = True
670
+ if any(m in mod for m in ("pickle", "yaml", "subprocess")):
671
+ has_injection = True
672
+ elif isinstance(node, (ast.AsyncFunctionDef, ast.AsyncWith, ast.Await)):
673
+ has_concurrency = True
674
+ elif isinstance(node, ast.Call):
675
+ func_name = ""
676
+ if isinstance(node.func, ast.Name):
677
+ func_name = node.func.id.lower()
678
+ elif isinstance(node.func, ast.Attribute):
679
+ func_name = node.func.attr.lower()
680
+
681
+ # Concurrency calls
682
+ if func_name in ("acquire", "release", "lock", "rlock", "semaphore", "event", "condition"):
683
+ has_concurrency = True
684
+ # Resource leak calls
685
+ if func_name in ("open", "connect", "cursor", "listen", "accept", "socket", "session", "connection"):
686
+ has_leak = True
687
+ # Injection / parsing calls
688
+ if func_name in ("loads", "load", "eval", "exec", "popen", "system", "run", "check_output"):
689
+ has_injection = True
690
+
691
+ if has_concurrency:
692
+ rules.append("concurrency")
693
+ if has_leak:
694
+ rules.append("memory_leak")
695
+ if has_injection:
696
+ rules.append("prompt_injection")
697
+ return rules
698
+
699
+
700
+ def detect_unit_rule_slice(
701
+ unit_id: str,
702
+ root: Path | None = None,
703
+ source_code: str | None = None,
704
+ file_path: Path | str | None = None,
705
+ ) -> str | None:
706
+ """依据覆盖单元特质(AST 语法树特征或名称关键词),智能匹配并提取对应的 L2 规则片段 (DOC-043)。"""
707
+ matched_rule: str | None = None
708
+
709
+ # 1. 优先尝试 AST 静态推断
710
+ code_to_parse = source_code
711
+ target_file = Path(file_path) if file_path else None
712
+ if not code_to_parse and target_file and target_file.is_file() and target_file.suffix == ".py":
713
+ ast_rules = _cached_ast_rules(target_file)
714
+ if ast_rules is not None:
715
+ if ast_rules:
716
+ matched_rule = ast_rules[0]
717
+ else:
718
+ try:
719
+ code_to_parse = target_file.read_text(encoding="utf-8", errors="ignore")
720
+ except OSError:
721
+ pass
722
+
723
+ if not matched_rule and not code_to_parse and root:
724
+ cand_rel = str(unit_id).split(":")[0]
725
+ f_p = (Path(root) / cand_rel).resolve()
726
+ if f_p.is_file() and f_p.suffix == ".py":
727
+ ast_rules = _cached_ast_rules(f_p)
728
+ if ast_rules is not None:
729
+ if ast_rules:
730
+ matched_rule = ast_rules[0]
731
+ else:
732
+ try:
733
+ code_to_parse = f_p.read_text(encoding="utf-8", errors="ignore")
734
+ except OSError:
735
+ pass
736
+
737
+ if code_to_parse and not matched_rule:
738
+ ast_rules = analyze_source_rules(code_to_parse)
739
+ if target_file:
740
+ _cache_ast_rules(target_file, ast_rules)
741
+ elif root:
742
+ cand_rel = str(unit_id).split(":")[0]
743
+ f_p = (Path(root) / cand_rel).resolve()
744
+ if f_p.is_file():
745
+ _cache_ast_rules(f_p, ast_rules)
746
+ if ast_rules:
747
+ matched_rule = ast_rules[0]
748
+
749
+ # 2. 回退降级至名称关键字推断
750
+ if not matched_rule:
751
+ normalized = unit_id.lower()
752
+ if any(kw in normalized for kw in ("lock", "race", "thread", "async", "concurrent", "mutex", "deadlock")):
753
+ matched_rule = "concurrency"
754
+ elif any(kw in normalized for kw in ("leak", "pool", "socket", "stream", "fd", "handle", "memory", "gc")):
755
+ matched_rule = "memory_leak"
756
+ elif any(kw in normalized for kw in ("parse", "json", "ast", "payload", "fuzz", "inject", "sanitize")):
757
+ matched_rule = "prompt_injection"
758
+
759
+ if not matched_rule:
760
+ return None
761
+
762
+ try:
763
+ content = load_rule(matched_rule, root=root)
764
+ lines = content.splitlines()
765
+ # 提取前 15 行核心规则摘要,避免 token 膨胀
766
+ summary = "\n".join(lines[:15]).strip()
767
+ return f"【领域定向规则推荐 - {matched_rule}】\n{summary}"
768
+ except (FileNotFoundError, ValueError):
769
+ return None
770
+
771
+
772
+ def get_unit_risk_advice(unit_id: str, root: Path | None = None) -> str | None:
773
+ """提取当前单元所属模块的代码智能内在风险雷达报告与变异攻击建议 (DOC-060)。"""
774
+ if not unit_id or not unit_id.strip():
775
+ return None
776
+
777
+ clean_id = unit_kind.strip_unit_prefix(unit_id)
778
+ parts = clean_id.split(":")
779
+ if len(parts) > 1 and parts[0].isdigit():
780
+ clean_id = ":".join(parts[1:])
781
+ fp = clean_id.split("::")[0].strip()
782
+ if not fp:
783
+ return None
784
+
785
+ target_root = root or Path.cwd()
786
+ profile_path = target_root / ".bugx" / "knowledge" / "project-profile.json"
787
+ if not profile_path.is_file():
788
+ return None
789
+
790
+ try:
791
+ import json
792
+ pdata = json.loads(profile_path.read_text(encoding="utf-8"))
793
+ risk_metrics = pdata.get("risk_metrics") or {}
794
+ hotspots = risk_metrics.get("top_risk_hotspots") or []
795
+
796
+ matched_hotspot = None
797
+ for h in hotspots:
798
+ if isinstance(h, dict) and "file" in h:
799
+ h_file = str(h["file"]).replace("\\", "/")
800
+ if h_file == fp or h_file.endswith(fp) or fp.endswith(h_file):
801
+ matched_hotspot = h
802
+ break
803
+
804
+ if not matched_hotspot:
805
+ return None
806
+
807
+ cc = matched_hotspot.get("cyclomatic_complexity", 1)
808
+ cog = matched_hotspot.get("cognitive_complexity", 0)
809
+ tags = matched_hotspot.get("tags") or []
810
+ sinks = matched_hotspot.get("sensitive_sinks", 0)
811
+
812
+ advice_points = []
813
+ if "critical-taint" in tags or "sensitive-sinks" in tags:
814
+ advice_points.append("发现入参直通敏感执行/反序列化/代码调用槽位,重点设计命令注入、特殊字符逃逸与反序列化边界 Payload。")
815
+ if "deep-nesting" in tags or "high-cognitive" in tags:
816
+ advice_points.append(f"认知复杂度较高 ({cog}),嵌套深且分支复杂,重点测试多重分支边界与反常序调用。")
817
+ if "hardcoded-secret" in tags:
818
+ advice_points.append("扫描到疑似高熵机密,重点核验凭证未授权访问与身份绕过。")
819
+ if not advice_points:
820
+ advice_points.append(f"圈复杂度 {cc},重点设计边界值反转与异常条件注入。")
821
+
822
+ tags_str = " · ".join(tags[:4]) if tags else "high-complexity"
823
+ return (
824
+ f"【⚠️ 代码智能脆弱性雷达 (Vulnerability Radar)】\n"
825
+ f"• 模块特征: CC={cc} | 认知负荷={cog} | 敏感槽位={sinks} | 标签: {tags_str}\n"
826
+ f"• 渗透指引: {' '.join(advice_points)}"
827
+ )
828
+ except Exception:
829
+ return None
830
+
831
+
832
+ def decorate_skill_stage_task(
833
+ stage_id: str,
834
+ task_text: str,
835
+ *,
836
+ skill_id: str = "web-audit",
837
+ worker_affinity: str = "logic",
838
+ attack_graph_slice: str = "",
839
+ experience_hint: str = "",
840
+ root: Path | None = None,
841
+ locale: str | None = None,
842
+ budgets: Mapping[str, Any] | None = None,
843
+ global_budget: int | None = None,
844
+ ) -> str:
845
+ """DOC-125: 审计技能包双层 Token 硬隔离任务修饰器。"""
846
+ b = dict(budgets or {})
847
+ max_l1 = _clamp_section_budget(
848
+ "skill_l1_checklist",
849
+ b.get("max_l1_checklist_tokens"),
850
+ HARNESS_SECTION_BUDGETS["skill_l1_checklist"],
851
+ )
852
+ max_exp_cards = b.get("max_experience_cards", 3)
853
+ max_exp_tokens = _clamp_section_budget(
854
+ "skill_experience_hint",
855
+ b.get("max_experience_tokens"),
856
+ HARNESS_SECTION_BUDGETS["skill_experience_hint"],
857
+ )
858
+ max_attack_graph = _clamp_section_budget(
859
+ "skill_attack_graph_slice",
860
+ b.get("max_attack_graph_tokens"),
861
+ HARNESS_SECTION_BUDGETS["skill_attack_graph_slice"],
862
+ )
863
+
864
+ affinity_info = SKILL_WORKER_AFFINITY_TIER.get(
865
+ worker_affinity.lower(),
866
+ (f"{worker_affinity.title()}-Worker", "PRO"),
867
+ )
868
+ worker_label, tier_label = affinity_info
869
+
870
+ l1_checklist = ""
871
+ l2_playbook_path = f"core/audit_packs/{skill_id}/stages/{stage_id}.md"
872
+ prompts_dir = get_prompts_dir(root)
873
+ audit_packs_base = prompts_dir.parent / "audit_packs"
874
+ skills_base = audit_packs_base if audit_packs_base.is_dir() else prompts_dir / "skills"
875
+ if not (prompts_dir.parent / l2_playbook_path).exists() and (prompts_dir / f"skills/{skill_id}/stages/{stage_id}.md").exists():
876
+ l2_playbook_path = f"core/prompts/skills/{skill_id}/stages/{stage_id}.md"
877
+ skill_pack = _get_skill_pack()
878
+ if skill_pack is not None:
879
+ try:
880
+ pack = skill_pack.load_skill_pack(skill_id, skills_dir=skills_base)
881
+ stage_info = pack.get("stages", {}).get(stage_id)
882
+ if stage_info:
883
+ l1_checklist = stage_info.get("l1_checklist", "")
884
+ l2_playbook_path = stage_info.get("file_path", l2_playbook_path)
885
+ try:
886
+ if root:
887
+ l2_playbook_path = str(Path(l2_playbook_path).relative_to(root))
888
+ except (ValueError, OSError):
889
+ pass
890
+ except Exception:
891
+ pass
892
+
893
+ if not l1_checklist:
894
+ l1_checklist = f"1. 执行 {stage_id} 审计任务;产出结构化验证证据与对照实验数据。"
895
+
896
+ # DOC-125/DOC-139:段级 ceiling/clamp 后,再由同一个全局出口分配
897
+ # 总额。任务正文保留独立地板,避免完整 L1 卡吞掉可执行任务。
898
+ sections, degradations = enforce_global_budget(
899
+ {
900
+ "skill_l1_checklist": l1_checklist,
901
+ "skill_attack_graph_slice": attack_graph_slice.strip(),
902
+ "skill_experience_hint": experience_hint.strip(),
903
+ "task_text": task_text,
904
+ },
905
+ global_budget
906
+ if global_budget is not None
907
+ else int(
908
+ b.get(
909
+ "global_budget",
910
+ b.get("total_budget", HARNESS_SKILL_GLOBAL_BUDGET),
911
+ )
912
+ ),
913
+ caps={
914
+ "skill_l1_checklist": max_l1,
915
+ "skill_attack_graph_slice": max_attack_graph,
916
+ "skill_experience_hint": max_exp_tokens,
917
+ },
918
+ priorities={
919
+ "skill_l1_checklist": 4,
920
+ "task_text": 3,
921
+ "skill_attack_graph_slice": 2,
922
+ "skill_experience_hint": 1,
923
+ },
924
+ floors={"task_text": HARNESS_TASK_TEXT_FLOOR},
925
+ labels={
926
+ "skill_l1_checklist": "技能包 L1 核心行动清单",
927
+ "skill_attack_graph_slice": "Attack Graph 切片摘要",
928
+ "skill_experience_hint": "技能包 L2 经验检索建议",
929
+ "task_text": "任务主体",
930
+ },
931
+ )
932
+ l1_checklist = sections["skill_l1_checklist"]
933
+ attack_graph_slice = sections["skill_attack_graph_slice"]
934
+ experience_hint = sections["skill_experience_hint"]
935
+ task_text = sections["task_text"]
936
+
937
+ banner_top = "=== BugX Stage Harness (Active Injection) ==="
938
+ stage_header = f"[Stage: {stage_id.upper()} · Worker: {worker_label} · Tier: {tier_label}]"
939
+ sep = "-" * 57
940
+
941
+ lines = [
942
+ banner_top,
943
+ stage_header,
944
+ sep,
945
+ f"[L1 核心行动清单 (Hard Cap: ≤{max_l1} tokens)]:",
946
+ f" {l1_checklist}",
947
+ f" 遇到复杂拦截,使用 Read 工具查阅攻防手册:\n {l2_playbook_path}",
948
+ ]
949
+
950
+ if attack_graph_slice:
951
+ lines.extend([
952
+ sep,
953
+ f"[Attack Graph 切片摘要 (≤{max_attack_graph} tokens)]:",
954
+ f" {attack_graph_slice}",
955
+ ])
956
+
957
+ if experience_hint:
958
+ lines.extend([
959
+ sep,
960
+ f"[L2 经验检索建议 (有界检索: ≤{max_exp_cards} 卡/{max_exp_tokens}T)]:",
961
+ f" {experience_hint}",
962
+ ])
963
+
964
+ lines.extend([
965
+ sep,
966
+ "=== 任务主体 (Task Specification) ===",
967
+ task_text,
968
+ ])
969
+ return "\n".join(lines) + _record_budget_degradations(degradations, stage=stage_id)
970
+
971
+
972
+ def decorate_stage_task(
973
+ stage: str,
974
+ task_text: str,
975
+ unit_id: str = "",
976
+ root: Path | None = None,
977
+ context: Mapping[str, object] | None = None,
978
+ locale: str | None = None,
979
+ global_budget: int | None = None,
980
+ ) -> str:
981
+ """为 Worker 任务主动注入当前阶段的 Harness 前缀与智能切片 (Active Injection) (DOC-043, DOC-060, DOC-067, DOC-125)。"""
982
+ eff_locale = locale or (os.environ.get("BUGX_LOCALE") or "zh-CN")
983
+
984
+ # DOC-125: 若为技能包阶段或显式声明 skill_plan,走技能包双层 Harness 修饰
985
+ if stage.startswith(("00-", "10-", "20-", "30-", "40-", "50-", "60-", "70-", "80-")) or (context and "skill_plan" in context):
986
+ skill_id = "web-audit"
987
+ stage_id = stage
988
+ worker_affinity = "logic"
989
+ attack_graph_slice = ""
990
+ experience_hint = ""
991
+ budgets = None
992
+ if context:
993
+ plan = context.get("skill_plan")
994
+ if isinstance(plan, Mapping):
995
+ skill_id = str(plan.get("skill_id", skill_id))
996
+ b = plan.get("budgets")
997
+ if isinstance(b, Mapping):
998
+ budgets = b
999
+ if "stage_id" in context:
1000
+ stage_id = str(context["stage_id"])
1001
+ if "worker_affinity" in context:
1002
+ worker_affinity = str(context["worker_affinity"])
1003
+ if "attack_graph_slice" in context:
1004
+ attack_graph_slice = str(context["attack_graph_slice"])
1005
+ if "experience_hint" in context:
1006
+ experience_hint = str(context["experience_hint"])
1007
+ return decorate_skill_stage_task(
1008
+ stage_id=stage_id,
1009
+ task_text=task_text,
1010
+ skill_id=skill_id,
1011
+ worker_affinity=worker_affinity,
1012
+ attack_graph_slice=attack_graph_slice,
1013
+ experience_hint=experience_hint,
1014
+ root=root,
1015
+ locale=eff_locale,
1016
+ budgets=budgets,
1017
+ global_budget=global_budget,
1018
+ )
1019
+
1020
+ stage_prompt = get_stage_prompt(stage, context=context, root=root, locale=eff_locale)
1021
+ rule_slice = detect_unit_rule_slice(unit_id, root=root) if unit_id else None
1022
+ risk_radar = get_unit_risk_advice(unit_id, root=root) if unit_id else None
1023
+ meta = get_stage_metadata(stage, locale=eff_locale)
1024
+
1025
+ banner_top = "=== BugX Stage Harness (Active Injection) ==="
1026
+ stage_info = f"当前阶段: {stage.upper()} · 推荐模型等级: {meta['tier']}"
1027
+ task_spec_banner = "=== 任务主体 (Task Specification) ==="
1028
+ if i18n is not None:
1029
+ banner_top = i18n.prompt_text("harness.banner_top", locale=eff_locale, fallback=banner_top)
1030
+ stage_info = i18n.prompt_text(
1031
+ "harness.stage_info",
1032
+ locale=eff_locale,
1033
+ fallback=stage_info,
1034
+ stage=stage.upper(),
1035
+ tier=meta["tier"],
1036
+ )
1037
+ task_spec_banner = i18n.prompt_text("harness.task_spec_banner", locale=eff_locale, fallback=task_spec_banner)
1038
+
1039
+ # DOC-043/DOC-139:把 L1、L2 和任务主体交给同一个全局出口;任务主体
1040
+ # 不再是预算旁路,并保留可执行的正文地板。
1041
+ sections, degradations = enforce_global_budget(
1042
+ {
1043
+ "l1_stage_harness": stage_prompt,
1044
+ "l2_rule_slice": rule_slice or "",
1045
+ "l2_risk_radar": risk_radar or "",
1046
+ "task_text": task_text,
1047
+ },
1048
+ global_budget
1049
+ if global_budget is not None
1050
+ else HARNESS_WORKER_GLOBAL_BUDGET,
1051
+ caps={
1052
+ "l1_stage_harness": HARNESS_SECTION_BUDGETS["l1_stage_harness"],
1053
+ "l2_rule_slice": HARNESS_SECTION_BUDGETS["l2_rule_slice"],
1054
+ "l2_risk_radar": HARNESS_SECTION_BUDGETS["l2_risk_radar"],
1055
+ },
1056
+ priorities={
1057
+ "l1_stage_harness": 4,
1058
+ "task_text": 3,
1059
+ "l2_rule_slice": 2,
1060
+ "l2_risk_radar": 1,
1061
+ },
1062
+ floors={"task_text": HARNESS_TASK_TEXT_FLOOR},
1063
+ labels={
1064
+ "l1_stage_harness": "L1 阶段专精 Harness",
1065
+ "l2_rule_slice": "L2 专项规则智能切片",
1066
+ "l2_risk_radar": "L2 代码智能脆弱性雷达",
1067
+ "task_text": "任务主体",
1068
+ },
1069
+ )
1070
+ stage_prompt = sections["l1_stage_harness"]
1071
+ rule_slice = sections["l2_rule_slice"]
1072
+ risk_radar = sections["l2_risk_radar"]
1073
+ task_text = sections["task_text"]
1074
+
1075
+ lines = [
1076
+ banner_top,
1077
+ stage_info,
1078
+ "-" * 45,
1079
+ stage_prompt,
1080
+ ]
1081
+ if rule_slice:
1082
+ lines.extend([
1083
+ "-" * 45,
1084
+ rule_slice,
1085
+ ])
1086
+ if risk_radar:
1087
+ lines.extend([
1088
+ "-" * 45,
1089
+ risk_radar,
1090
+ ])
1091
+ lines.extend([
1092
+ task_spec_banner,
1093
+ task_text,
1094
+ ])
1095
+ return "\n".join(lines) + _record_budget_degradations(degradations, stage=stage)
1096
+
1097
+
1098
+ def route_source_inspection(
1099
+ path: str,
1100
+ *,
1101
+ symbol: str | None = None,
1102
+ kind: str | None = None,
1103
+ start_line: int = 1,
1104
+ end_line: int | None = None,
1105
+ ) -> dict[str, Any]:
1106
+ """Determine whether a source inspection request should route to structured slice retrieval.
1107
+
1108
+ When inspecting code with a specific symbol or method target, routes to bugx_retrieve_slice
1109
+ for dense, self-contained syntax slices, while falling back safely to bugx_inspect_source.
1110
+ """
1111
+ path_clean = str(path).strip()
1112
+ is_code = path_clean.endswith((
1113
+ ".py", ".go", ".rs", ".js", ".ts", ".jsx", ".tsx",
1114
+ ".c", ".cpp", ".cc", ".h", ".hpp", ".java", ".kt", ".swift",
1115
+ ))
1116
+ if is_code and symbol and symbol.strip():
1117
+ return {
1118
+ "prefer_slice": True,
1119
+ "target_tool": "bugx_retrieve_slice",
1120
+ "slice_args": {
1121
+ "target": path_clean,
1122
+ "symbol": symbol.strip(),
1123
+ "kind": kind,
1124
+ "to_executable": True,
1125
+ "include_context": True,
1126
+ },
1127
+ "fallback_tool": "bugx_inspect_source",
1128
+ "fallback_args": {
1129
+ "path": path_clean,
1130
+ "start_line": start_line,
1131
+ "end_line": end_line,
1132
+ },
1133
+ }
1134
+ return {
1135
+ "prefer_slice": False,
1136
+ "target_tool": "bugx_inspect_source",
1137
+ "slice_args": None,
1138
+ "fallback_tool": "bugx_inspect_source",
1139
+ "fallback_args": {
1140
+ "path": path_clean,
1141
+ "start_line": start_line,
1142
+ "end_line": end_line,
1143
+ },
1144
+ }
1145
+
1146
+
1147
+
1148
+ def distill_evidence(raw_output: str, max_lines: int = 15, locale: str | None = None) -> str:
1149
+ """将冗长复杂的终端异常堆栈或 Fuzz 运行日志蒸馏为 ≤15 行结构化 Markdown 证据提要 (DOC-043, DOC-067)。"""
1150
+ eff_locale = locale or (os.environ.get("BUGX_LOCALE") or "zh-CN")
1151
+ no_output = "无输出内容"
1152
+ if i18n is not None:
1153
+ no_output = i18n.prompt_text("evidence.no_output", locale=eff_locale, fallback=no_output)
1154
+
1155
+ if not raw_output or not raw_output.strip():
1156
+ return no_output
1157
+
1158
+ text = raw_output.strip()
1159
+ # 1. 尝试提取 Python Traceback
1160
+ tb_matches = list(_RE_PY_TRACE.finditer(text))
1161
+ exc_match = _RE_EXC_LINE.search(text)
1162
+
1163
+ distilled_lines: list[str] = []
1164
+ if tb_matches or exc_match:
1165
+ distilled_title = "### 🔍 结构化异常证据提要 (Distilled Evidence)"
1166
+ if i18n is not None:
1167
+ distilled_title = i18n.prompt_text("evidence.distilled_title", locale=eff_locale, fallback=distilled_title)
1168
+ distilled_lines.append(distilled_title)
1169
+
1170
+ if exc_match:
1171
+ exc_line = f"- **异常类型**: `{exc_match.group('exc')}`"
1172
+ err_line = f"- **错误详情**: {exc_match.group('msg').strip()}"
1173
+ if i18n is not None:
1174
+ exc_line = i18n.prompt_text("evidence.exc_type", locale=eff_locale, fallback=exc_line, exc=exc_match.group('exc'))
1175
+ err_line = i18n.prompt_text("evidence.error_detail", locale=eff_locale, fallback=err_line, msg=exc_match.group('msg').strip())
1176
+ distilled_lines.append(exc_line)
1177
+ distilled_lines.append(err_line)
1178
+
1179
+ if tb_matches:
1180
+ # 取最深一层的项目内或目标代码触发点
1181
+ last_frame = tb_matches[-1]
1182
+ loc_line = f"- **触发位置**: `{last_frame.group('file')}:{last_frame.group('line')}` in `{last_frame.group('func')}`"
1183
+ fault_line = f"- **故障代码**: `{last_frame.group('code').strip()}`"
1184
+ if i18n is not None:
1185
+ loc_line = i18n.prompt_text(
1186
+ "evidence.trigger_location",
1187
+ locale=eff_locale,
1188
+ fallback=loc_line,
1189
+ location=f"{last_frame.group('file')}:{last_frame.group('line')}",
1190
+ func=last_frame.group('func'),
1191
+ )
1192
+ fault_line = i18n.prompt_text(
1193
+ "evidence.fault_code",
1194
+ locale=eff_locale,
1195
+ fallback=fault_line,
1196
+ code=last_frame.group('code').strip(),
1197
+ )
1198
+ distilled_lines.append(loc_line)
1199
+ distilled_lines.append(fault_line)
1200
+
1201
+ if len(tb_matches) > 1:
1202
+ call_chain = " ➔ ".join(m.group("func") for m in tb_matches[-3:])
1203
+ chain_line = f"- **调用链末端**: `{call_chain}`"
1204
+ if i18n is not None:
1205
+ chain_line = i18n.prompt_text(
1206
+ "evidence.call_chain",
1207
+ locale=eff_locale,
1208
+ fallback=chain_line,
1209
+ chain=call_chain,
1210
+ )
1211
+ distilled_lines.append(chain_line)
1212
+
1213
+ # 检查是否有断言失败差异
1214
+ assert_match = _RE_ASSERT_FAIL.search(text)
1215
+ if assert_match:
1216
+ first_assert_line = assert_match.group(1).strip().splitlines()[0]
1217
+ diff_line = f"- **断言差异**: `{first_assert_line[:120]}`"
1218
+ if i18n is not None:
1219
+ diff_line = i18n.prompt_text(
1220
+ "evidence.assert_diff",
1221
+ locale=eff_locale,
1222
+ fallback=diff_line,
1223
+ diff=first_assert_line[:120],
1224
+ )
1225
+ distilled_lines.append(diff_line)
1226
+
1227
+ footer = "_(完整日志已归档至 `.bugx/logs/bugx.jsonl`,可通过 `bugx log` 查看)_"
1228
+ if i18n is not None:
1229
+ footer = i18n.prompt_text("evidence.footer", locale=eff_locale, fallback=footer)
1230
+ distilled_lines.append(footer)
1231
+ return "\n".join(distilled_lines[:max_lines])
1232
+
1233
+ # 2. 兜底通用压缩:保留头部 4 行与尾部 8 行
1234
+ lines = text.splitlines()
1235
+ if len(lines) <= max_lines:
1236
+ return text
1237
+
1238
+ head = lines[:4]
1239
+ tail = lines[-8:]
1240
+ omitted = len(lines) - 12
1241
+ omitted_msg = f"... [省略 {omitted} 行冗余输出,完整记录查阅 .bugx/logs/bugx.jsonl] ..."
1242
+ if i18n is not None:
1243
+ omitted_msg = i18n.prompt_text("evidence.omitted", locale=eff_locale, fallback=omitted_msg, omitted=omitted)
1244
+ compressed = head + [omitted_msg] + tail
1245
+ return "\n".join(compressed[:max_lines])
1246
+
1247
+
1248
+
1249
+ def parse_structured_evidence(text: str, distilled: str | None = None) -> dict[str, object]:
1250
+ """从原始终端输出或 Traceback 中提取结构化异常元数据 (DOC-045)。"""
1251
+ tb_matches = list(_RE_PY_TRACE.finditer(text))
1252
+ exc_match = _RE_EXC_LINE.search(text)
1253
+ assert_match = _RE_ASSERT_FAIL.search(text)
1254
+
1255
+ location = ""
1256
+ function_name = ""
1257
+ failing_code = ""
1258
+ call_chain: list[str] = []
1259
+ if tb_matches:
1260
+ last = tb_matches[-1]
1261
+ location = f"{last.group('file')}:{last.group('line')}"
1262
+ function_name = last.group("func")
1263
+ failing_code = last.group("code").strip()
1264
+ call_chain = [m.group("func") for m in tb_matches]
1265
+
1266
+ assertion_diff = ""
1267
+ if assert_match:
1268
+ assertion_diff = assert_match.group(1).strip().splitlines()[0][:120]
1269
+
1270
+ msg = exc_match.group("msg").strip() if exc_match else ""
1271
+ return {
1272
+ "exception_type": exc_match.group("exc") if exc_match else "Unknown",
1273
+ "error_message": msg,
1274
+ "summary": msg,
1275
+ "failing_location": location,
1276
+ "failing_function": function_name,
1277
+ "failing_code": failing_code,
1278
+ "call_chain": call_chain,
1279
+ "assertion_diff": assertion_diff,
1280
+ "distilled_summary": distilled or distill_evidence(text, max_lines=5),
1281
+ }
1282
+
1283
+
1284
+ # ── DOC-248 三维正交技术栈规则切片 (300~500 Tokens) ───────────────────
1285
+ TECH_STACK_RULE_SLICES: dict[str, str] = {
1286
+ "java": (
1287
+ "### [Tech Stack Slice: Java / JVM & Spring Ecosystem (DOC-248)]\n"
1288
+ "- 反序列化利用链 (Deserialization Gadgets):\n"
1289
+ " * 重点审计 Fastjson (`@type` 自动类型解析)、Jackson (`enableDefaultTyping` / `TypeNameHandling`) 以及原生 `ObjectInputStream`。\n"
1290
+ " * 检查类路径中是否存在 Commons-Collections, Spring-Beans, C3P0, Rome 等已知 RCE 利用链;禁止反序列化外部不可信字节流。\n"
1291
+ "- 表达式注入与远程代码执行 (SpEL & OGNL):\n"
1292
+ " * 审查 SpEL 表达式解析:用户输入传入 `ExpressionParser.parseExpression().getValue()` 时必须使用只读 `SimpleEvaluationContext`,禁止传入高权限 `StandardEvaluationContext`。\n"
1293
+ "- 数据访问与 SQL 拼接 (MyBatis / JPA / Hibernate):\n"
1294
+ " * 排查 MyBatis XML 中的 `${}` 直接字符串拼接(尤其是 ORDER BY、LIKE、IN 语句),强制重构为 `#{}` 参数化占位符。\n"
1295
+ "- JNDI 与远程服务查找:\n"
1296
+ " * `InitialContext.lookup()` 严禁拼接用户可控协议前缀(如 `ldap://`, `rmi://`);防范 Log4j / Fastjson 驱动的 JNDI 注入。\n"
1297
+ "- 暴露面与配置泄露:\n"
1298
+ " * 检查 Spring Boot Actuator (`/actuator/env`, `/actuator/heapdump`, `/actuator/gateway`) 是否未授权对外暴露敏感环境变量或堆内存。"
1299
+ ),
1300
+ "csharp": (
1301
+ "### [Tech Stack Slice: C# / .NET Ecosystem (DOC-248)]\n"
1302
+ "- 危险反序列化 (Unsafe Deserialization):\n"
1303
+ " * 彻底禁用 `BinaryFormatter.Deserialize()`;审查 `Json.NET` 是否启用了危险的 `TypeNameHandling.Auto` / `All` / `Objects`。\n"
1304
+ " * 防范 `NetDataContractSerializer`, `LosFormatter`, `SoapFormatter` 等历史遗留易受反序列化攻击的类型组件。\n"
1305
+ "- ViewState 与 MAC 完整性校验:\n"
1306
+ " * ASP.NET WebForms 中 ViewState 必须开启 MAC 校验 (`EnableViewStateMac=true`);严禁硬编码默认 `machineKey` 导致远程执行。\n"
1307
+ "- 路径穿越与绝对路径覆盖风险:\n"
1308
+ " * `Path.Combine(basePath, userInput)`: 在 .NET 中若 `userInput` 以 `/` 或 `\\` 开头,将被视作绝对根路径直接覆盖 `basePath`,造成致命越权路径写。\n"
1309
+ "- 动态表达式与 LINQ 注入:\n"
1310
+ " * `System.Linq.Dynamic.Core` 动态构造查询字符串时必须使用参数化占位符,严禁字符串拼接触发任意方法调用注入。\n"
1311
+ "- 外部通信与 WCF 安全:\n"
1312
+ " * 审查 WCF / .NET Remoting 契约端点,杜绝未认证暴露或明文传输敏感凭据。"
1313
+ ),
1314
+ "kotlin": (
1315
+ "### [Tech Stack Slice: Kotlin & Android Native (DOC-248)]\n"
1316
+ "- JNI 与 Native C/C++ 内存生命周期:\n"
1317
+ " * JNI 本地方法调用中跨边界指针的生命周期管理;排查内存释放后使用 (UAF) 与缓冲区越界。\n"
1318
+ " * 审查 `GetStringUTFChars` 与 `ReleaseStringUTFChars` 是否严格成对释放,防范 Native 堆内存泄漏。\n"
1319
+ "- 协程异常安全与死锁:\n"
1320
+ " * 审查 `CoroutineExceptionHandler` 与 `SupervisorJob` 作用域;防止子协程未捕获异常级联取消根作用域引发 App 崩溃。\n"
1321
+ " * 警惕在挂起函数中持有非协程安全的锁 (如 Java 原生 `synchronized` 或 `ReentrantLock`) 引发的协程调度死锁。\n"
1322
+ "- 弱引用与生命周期持有:\n"
1323
+ " * 检查 `WeakReference` 在异步回调中的空安全校验;防止 Activity 销毁后异步任务持有野指针引发空指针异常 (NPE) 或内存泄漏。\n"
1324
+ "- 移动端组件导出与 Intent 走私:\n"
1325
+ " * 检查 `AndroidManifest.xml` 中未受保护的 `android:exported=\"true\"` 组件与未鉴权 DeepLink。\n"
1326
+ " * 构造 `PendingIntent` 时必须显式声明 `FLAG_IMMUTABLE`,杜绝恶意第三方 App 篡改内部 Intent 参数。"
1327
+ ),
1328
+ "go": (
1329
+ "### [Tech Stack Slice: Go / Golang Systems (DOC-248)]\n"
1330
+ "- Goroutine 闭包变量捕获竞态 (Closure Capture Race):\n"
1331
+ " * 审查循环体中并发启动的 goroutine: `for i, v := range items { go func() { use(v) }() }`,必须显式以参数传递或在循环局部重新绑定。\n"
1332
+ "- Channel 阻塞与 Goroutine 泄漏:\n"
1333
+ " * 审查无缓冲 Channel 在超时或发送异常时的阻塞;确保每个 `context.WithTimeout` / `WithCancel` 都被及时 `defer cancel()`。\n"
1334
+ "- 数据读写竞争 (Data Race Invariant):\n"
1335
+ " * 共享变量(如全局 map、切片、统计计数器)必须使用 `sync.Mutex` / `sync.RWMutex` 或 `sync/atomic` 保护,严禁无锁并发读写。\n"
1336
+ "- SQL 拼接与命令执行:\n"
1337
+ " * `database/sql` 必须使用参数占位符 (`?` 或 `$1`),严禁使用 `fmt.Sprintf` 拼接 SQL 语句。\n"
1338
+ " * `os/exec.Command` 禁止拼接外部不可信字符串调用 `sh -c` / `bash -c`,防范命令注入。"
1339
+ ),
1340
+ "python": (
1341
+ "### [Tech Stack Slice: Python & Modern Frameworks (DOC-248)]\n"
1342
+ "- 属性与原型污染 (Attribute & Prototype Pollution):\n"
1343
+ " * 递归字典更新或动态属性赋值时,必须严格拦截 `__class__`, `__globals__`, `__subclasses__`, `__builtins__`,防范沙箱逃逸与元对象篡改。\n"
1344
+ "- 不安全反序列化与模板渲染:\n"
1345
+ " * 彻底禁止加载外部输入的 `pickle.loads()`;`yaml.load()` 必须显式声明 `Loader=SafeLoader`。\n"
1346
+ " * 审查 Jinja2 / Django 模板渲染,严禁直接拼接用户输入至 `render_template_string` 引发的 SSTI。\n"
1347
+ "- 多线程与 GIL 释放竞态:\n"
1348
+ " * 审查调用底层 C-Extension 或 I/O 密集型代码释放 GIL 后的并发共享变量读写,确保线程安全。\n"
1349
+ "- 进程命令执行与路径拼接:\n"
1350
+ " * `subprocess.Popen(..., shell=True)` 传入变量必须经 `shlex.quote` 转义或改用列表传参。\n"
1351
+ " * `os.path.join(base, user_input)`: 当 `user_input` 包含前导 `/` 时会静默丢弃 `base`,必须做安全前缀检查与规范化。"
1352
+ ),
1353
+ "generic": (
1354
+ "### [Tech Stack Slice: Generic Systems & Secure Invariants (DOC-248)]\n"
1355
+ "- 输入边界验证: 外部不可信输入必须在入口层执行严格白名单类型、长度与正则过滤。\n"
1356
+ "- 状态守恒与鉴权对齐: 权限校验与底层资源访问必须处于同一原子上下文中,杜绝 TOCTOU 竞争。\n"
1357
+ "- 防御性失败 (Fail-Closed): 发生异常时必须安全熔断,严禁空异常捕获,禁止对外回显调试错误堆栈。"
1358
+ ),
1359
+ }
1360
+
1361
+ # ── DOC-248 动态黑盒探针工具契约 ──────────────────────────────────────
1362
+ PROBE_SPECIFICATIONS: dict[str, str] = {
1363
+ "web_dynamic_probe": (
1364
+ "### [黑盒探针: WebDynamicProbe (Playwright & Raw Socket)]\n"
1365
+ "- 工具接口: `headless_browser_action` (DOM 点击/表单提交/Cookie 读取), `http_raw_request` (HTTP/1.1 与 HTTP/2 畸形头/管道走私)\n"
1366
+ "- 操作规范: 结合网络状态码与 DOM 执行树验证 XSS、CORS 凭据泄露及请求走私漏洞。"
1367
+ ),
1368
+ "android_probe": (
1369
+ "### [黑盒探针: AndroidProbe (APK Decompile & ADB Dispatcher)]\n"
1370
+ "- 工具接口: `apk_decompile_manifest` (解析 exported 组件与 DeepLink 过滤器), `adb_send_intent` (跨进程触发 Intent 越权)\n"
1371
+ "- 操作规范: 验证能否未认证越权拉起私有 Activity/Service,或通过伪造 Intent Extras 提取沙箱 SQLite 敏感数据。"
1372
+ ),
1373
+ "ios_binary": (
1374
+ "### [黑盒探针: ios_binary (Mach-O 加固 / 代码签名 / entitlements / ATS)]\n"
1375
+ "- 工具接口: `codesign`/`otool`/`nm` 宿主二进制审计(PIE、栈保护、cryptid、entitlements), "
1376
+ "Info.plist 静态安全门(ATS 放宽 `NSAllowsArbitraryLoads*`、`UIFileSharingEnabled` 明文落盘)\n"
1377
+ "- 操作规范: 审查 ATS 强制放宽、敏感 entitlements 过宽(keychain-access-groups 等)"
1378
+ "及二进制加固缺失(no-PIE / no-stack-canary)对应的可利用面。"
1379
+ ),
1380
+ "miniprogram_probe": (
1381
+ "### [黑盒探针: MiniProgramProbe (Subpackage Router & Cloud Functions)]\n"
1382
+ "- 工具接口: `miniprogram_router_crawler` (`app.json` 全量子包未授权直达), `cloud_function_probe` (`OPENID` 缺失探测)\n"
1383
+ "- 操作规范: 验证能否绕过前端登录守卫直达管理员分包页面,或未校验 `OPENID` 篡改他人数据。"
1384
+ ),
1385
+ "binary_probe": (
1386
+ "### [黑盒探针: BinaryProbe (ASan Instrumentation & Fuzzing)]\n"
1387
+ "- 工具接口: `run_fuzz_mutation` (边界变异生成器), Clang `-fsanitize=address,undefined` 编译插桩\n"
1388
+ "- 操作规范: 针对 C/C++ 内存分配、指针运算驱动边界变异测试,捕获缓冲区溢出与 UAF 崩溃。"
1389
+ ),
1390
+ }
1391
+
1392
+ # ── DOC-248 五大核心行为角色 SOP ──────────────────────────────────────
1393
+ ROLE_SOP_SPECIFICATIONS: dict[str, str] = {
1394
+ "Recon-Worker": (
1395
+ "### [核心行为角色 SOP: Recon-Worker (广度优先资产侦察)]\n"
1396
+ "- **思维模式**: 广度覆盖、无死角测绘、暴露面拓扑建模。\n"
1397
+ "- **核心职责**:\n"
1398
+ " 1. 梳理系统所有对外暴露接口、路由、未授权端点与组件入口;\n"
1399
+ " 2. 提取入参模式与身份约束边界,构建初始攻击面假说图谱;\n"
1400
+ " 3. 快速归纳资产拓扑,为下游专精 Worker 提供高价值靶标索引,禁止做耗时单点深挖。"
1401
+ ),
1402
+ "Auth-Worker": (
1403
+ "### [核心行为角色 SOP: Auth-Worker (鉴权与越权专精挖掘)]\n"
1404
+ "- **思维模式**: 对抗性身份切换、双租户交叉矩阵推演、租户物理隔离边界审计。\n"
1405
+ "- **核心职责**:\n"
1406
+ " 1. 必须始终基于注入的双租户身份矩阵 (Role A vs Role B) 进行对比验证;\n"
1407
+ " 2. 深挖水平越权 (BOLA/IDOR)、垂直提权、Token 签名失效与未授权访问;\n"
1408
+ " 3. 严格执行跨租户断言门禁:Role A 请求 Tenant B 必须返回 401/403,任何返回 200 或泄漏数据一律裁决为高危越权。"
1409
+ ),
1410
+ "Logic-Worker": (
1411
+ "### [核心行为角色 SOP: Logic-Worker (状态机与并发竞态专精)]\n"
1412
+ "- **思维模式**: 时序推演、微秒级竞争碰撞、状态跃迁合法性审查、守恒定律验证。\n"
1413
+ "- **核心职责**:\n"
1414
+ " 1. 针对支付、充值、扣款、库存、卡券等状态转换,强制执行并发竞态压测;\n"
1415
+ " 2. 严格使用 `ThreadPoolExecutor(max_workers=10)` 脚手架,受 3.0s 硬熔断保护 (AUDIT-04);\n"
1416
+ " 3. 验证业务状态守恒:并发 10 线程扣款必须严格仅成功 1 笔,余额绝不可为负数。"
1417
+ ),
1418
+ "Exploit-Worker": (
1419
+ "### [核心行为角色 SOP: Exploit-Worker (深度利用与差分验证)]\n"
1420
+ "- **思维模式**: 污点溯源 (Source->Sanitizer->Sink)、实锤验证、零误报物理差分。\n"
1421
+ "- **核心职责**:\n"
1422
+ " 1. 沿 AST 污点路径追踪外部输入至高危 Sink 点 (SQL, 命令执行, 反序列化, SSTI, SpEL);\n"
1423
+ " 2. 严格遵循 AUDIT-05:必须产出独立的双沙箱 0/1 退出码差分验证脚本;\n"
1424
+ " 3. 严禁仅凭 HTTP 500/403 单独定性,只有攻击沙箱确凿复现且退出码为 1 才可立案。"
1425
+ ),
1426
+ "Patch-Worker": (
1427
+ "### [核心行为角色 SOP: Patch-Worker (规范修复与回归闭环)]\n"
1428
+ "- **思维模式**: 最小外科手术式修改、防御性契约加固、零业务功能回归、绝对路径物理脱敏。\n"
1429
+ "- **核心职责**:\n"
1430
+ " 1. 依据 CWE 知识库制定针对性修复方案,根除病灶而非表面遮掩;\n"
1431
+ " 2. 生成自动化验证脚本 `verify.py`,确保退出码 0 为修复且无回归,退出码 1 为失败;\n"
1432
+ " 3. 严格执行绝对路径脱敏红线:补丁与脚本中绝对禁止出现本地 `/Users/...` 或 `/home/...`。"
1433
+ ),
1434
+ }
1435
+
1436
+
1437
+ def build_domain_specialized_prompt(
1438
+ worker_role: str,
1439
+ target_form: str = "backend",
1440
+ tech_stack: str = "generic",
1441
+ active_probes: Sequence[str] = (),
1442
+ *,
1443
+ task_desc: str = "",
1444
+ unit_id: str = "",
1445
+ file_path: str = "",
1446
+ symbol_name: str = "",
1447
+ ast_features: Mapping[str, Any] | None = None,
1448
+ max_prompt_tokens: int = 2200,
1449
+ root: Path | None = None,
1450
+ locale: str | None = None,
1451
+ extra_context: Mapping[str, Any] | None = None,
1452
+ ) -> str:
1453
+ """DOC-248: 三维正交领域专精 JIT 提示词拼装与硬预算门禁。
1454
+
1455
+ 参数:
1456
+ worker_role: 核心角色 (recon, auth, logic, exploit, patch 或对应 Worker 名)
1457
+ target_form: 目标形态 (backend, web, mobile_android, mobile_ios, miniprogram, binary)
1458
+ tech_stack: 技术栈领域 (java, csharp, kotlin, go, python, generic)
1459
+ active_probes: 挂载的黑盒动态探针清单
1460
+ max_prompt_tokens: 严格硬预算上限 (AUDIT-03,默认 <= 2200)
1461
+
1462
+ 按角色优先级保障:核心 SOP (100) > 技术栈切片 (80) > 探针描述 (70) > 领域夹具 (50) > 任务上下文 (40)。
1463
+ """
1464
+ # 1. 规范化核心角色与亲和性等级
1465
+ role_raw = (worker_role or "generalist").strip()
1466
+ role_key = role_raw.lower().replace("-worker", "")
1467
+ if role_key in SKILL_WORKER_AFFINITY_TIER:
1468
+ role_label, tier_label = SKILL_WORKER_AFFINITY_TIER[role_key]
1469
+ affinity = role_key
1470
+ else:
1471
+ role_label = f"{role_key.title()}-Worker" if not role_raw.endswith("-Worker") else role_raw
1472
+ affinity = role_key
1473
+ tier_label = "BALANCED"
1474
+
1475
+ # 2. 规范化形态与技术栈
1476
+ target_form_norm = (target_form or "backend").strip().lower()
1477
+ tech_norm = (tech_stack or "generic").strip().lower()
1478
+ if tech_norm in ("c#", "cs", ".net"):
1479
+ tech_norm = "csharp"
1480
+ elif tech_norm in ("kt", "kts"):
1481
+ tech_norm = "kotlin"
1482
+ elif tech_norm in ("golang",):
1483
+ tech_norm = "go"
1484
+ elif tech_norm in ("py",):
1485
+ tech_norm = "python"
1486
+ elif tech_norm not in TECH_STACK_RULE_SLICES:
1487
+ tech_norm = "generic"
1488
+
1489
+ # 3. 规范化探针清单
1490
+ probes = list(active_probes or ())
1491
+ if not probes:
1492
+ if target_form_norm == "web":
1493
+ probes = ["web_dynamic_probe"]
1494
+ elif target_form_norm in ("mobile_android", "android"):
1495
+ probes = ["android_probe"]
1496
+ elif target_form_norm in ("mobile_ios", "ios"):
1497
+ probes = ["ios_binary"]
1498
+ elif target_form_norm in ("miniprogram", "wechat"):
1499
+ probes = ["miniprogram_probe"]
1500
+ elif target_form_norm in ("binary", "embedded"):
1501
+ probes = ["binary_probe"]
1502
+
1503
+ # 4. 构建分段
1504
+ # A. 头部基础信息
1505
+ header_text = (
1506
+ f"## BugHunter 领域专精 Worker JIT 提示词 (DOC-248)\n"
1507
+ f"- **专精角色**: {role_label} (亲和性: {affinity}, 建议模型等级: {tier_label})\n"
1508
+ f"- **目标形态**: {target_form_norm}\n"
1509
+ f"- **技术栈知识**: {tech_norm}\n"
1510
+ f"- **挂载动态探针**: {', '.join(probes) if probes else '无(纯静态代码审计)'}\n"
1511
+ )
1512
+
1513
+ # B. 核心角色 SOP
1514
+ role_sop_text = ROLE_SOP_SPECIFICATIONS.get(
1515
+ role_label,
1516
+ ROLE_SOP_SPECIFICATIONS.get(
1517
+ f"{role_key.title()}-Worker",
1518
+ f"### [核心行为角色 SOP: {role_label}]\n- 依据领域专精特征执行针对性审计任务。\n",
1519
+ ),
1520
+ )
1521
+
1522
+ # C. 技术栈规则切片 (300~500T)
1523
+ tech_slice_text = TECH_STACK_RULE_SLICES.get(tech_norm, TECH_STACK_RULE_SLICES["generic"])
1524
+
1525
+ # D. 探针描述
1526
+ probe_items = []
1527
+ for p in probes:
1528
+ spec = PROBE_SPECIFICATIONS.get(p)
1529
+ if spec:
1530
+ probe_items.append(spec)
1531
+ else:
1532
+ probe_items.append(f"### [黑盒探针: {p}]\n已挂载探针工具,请依据形态契约执行交互验证。")
1533
+ probes_text = "\n\n".join(probe_items) if probe_items else ""
1534
+
1535
+ # E. 领域专属测试底座夹具 (Auth, Logic, Exploit, Patch, Mobile, Web)
1536
+ if domain_archetype is not None:
1537
+ fixture_pack = domain_archetype.generate_domain_fixtures(
1538
+ worker_role=role_label,
1539
+ target_form=target_form_norm,
1540
+ tech_stack=tech_norm,
1541
+ )
1542
+ else:
1543
+ fixture_pack = {
1544
+ "worker_role": role_label,
1545
+ "target_form": target_form_norm,
1546
+ "tech_stack": tech_norm,
1547
+ "fixtures": {},
1548
+ "scaffold_code": "",
1549
+ "guidance": "",
1550
+ }
1551
+
1552
+ fixtures_text_parts = ["### [领域专属测试底座夹具 (Domain Synthetic Fixtures)]"]
1553
+ if fixture_pack.get("guidance"):
1554
+ fixtures_text_parts.append(f"**操作指引**: {fixture_pack['guidance']}")
1555
+
1556
+ fixtures_dict = fixture_pack.get("fixtures", {})
1557
+ if "dual_identity_token_matrix" in fixtures_dict:
1558
+ matrix = fixtures_dict["dual_identity_token_matrix"]
1559
+ ra, rb = matrix.get("role_a", {}), matrix.get("role_b", {})
1560
+ fixtures_text_parts.append(
1561
+ "- **双租户身份矩阵 (Role A vs Role B)**:\n"
1562
+ f" * Role A (租户 A): User={ra.get('user_id')}, Tenant={ra.get('tenant_id')}, Token={ra.get('token')}\n"
1563
+ f" * Role B (租户 B): User={rb.get('user_id')}, Tenant={rb.get('tenant_id')}, Token={rb.get('token')}\n"
1564
+ "- **跨租户访问断言**: Role A 请求 Tenant B 必须返回 401/403,任何 200/204 均判定为 BOLA/IDOR 严重越权。"
1565
+ )
1566
+
1567
+ if "concurrency_threadpool_10" in fixtures_dict:
1568
+ fixtures_text_parts.append(
1569
+ "- **并发竞态压测契约 (AUDIT-04)**:\n"
1570
+ " * 物理并发上限: max_workers <= 10 (严格限制并发度防雪崩)\n"
1571
+ " * 硬熔断时间: 3.0s 超时强制中断 (防止死锁)\n"
1572
+ " * 状态守恒校验: 10 线程并发扣款必须严格只有 1 笔成功,余额不得为负。"
1573
+ )
1574
+
1575
+ if "twin_sandbox_oracle" in fixtures_dict:
1576
+ fixtures_text_parts.append(
1577
+ "- **AST 污点上下文与 0/1 差分真值 (AUDIT-05)**:\n"
1578
+ " * 污点追踪: Source -> Sanitizer -> Sink 完整路径分析\n"
1579
+ " * 0/1 差分门禁: 基准良性沙箱退出码为 0,攻击利用沙箱确凿复现且退出码为 1;严禁凭单一 HTTP 状态码定性。"
1580
+ )
1581
+
1582
+ if "cwe_knowledge_base" in fixtures_dict:
1583
+ fixtures_text_parts.append(
1584
+ "- **CWE 知识库与规范修复**:\n"
1585
+ " * 参照 CWE 规则实施针对性最小修复,根除根本病灶。\n"
1586
+ " * 绝对路径物理脱敏: 补丁与脚本中绝对禁止出现本地 `/Users/...` 或 `/home/...`,必须统一使用 `<PROJECT_ROOT>` 或仓库相对路径替代。\n"
1587
+ " * verify.py 规范: 独立自动化验证脚本,退出码 0 代表成功修复且无回归,退出码 1 代表失败。"
1588
+ )
1589
+
1590
+ if fixture_pack.get("scaffold_code"):
1591
+ code_snip = fixture_pack["scaffold_code"].strip()
1592
+ fixtures_text_parts.append(f"```python\n{code_snip}\n```")
1593
+
1594
+ fixtures_text = "\n\n".join(fixtures_text_parts)
1595
+
1596
+ # F. 任务上下文
1597
+ task_context_parts = []
1598
+ if unit_id or file_path or symbol_name or task_desc:
1599
+ task_context_parts.append("### [任务上下文与被测标的]")
1600
+ if unit_id:
1601
+ task_context_parts.append(f"- **单元标识**: `{unit_id}`")
1602
+ if file_path:
1603
+ task_context_parts.append(f"- **源码路径**: `{file_path}`")
1604
+ if symbol_name:
1605
+ task_context_parts.append(f"- **目标符号**: `{symbol_name}`")
1606
+ if task_desc:
1607
+ task_context_parts.append(f"- **任务描述**: {task_desc}")
1608
+ task_context_text = "\n".join(task_context_parts) if task_context_parts else ""
1609
+
1610
+ # 5. 拼装与预算硬裁剪 (AUDIT-03)
1611
+ sections = OrderedDict()
1612
+ sections["header_role"] = header_text
1613
+ sections["role_sop"] = role_sop_text
1614
+ sections["tech_slice"] = tech_slice_text
1615
+ if probes_text:
1616
+ sections["probes_spec"] = probes_text
1617
+ sections["domain_fixtures"] = fixtures_text
1618
+ if task_context_text:
1619
+ sections["task_context"] = task_context_text
1620
+
1621
+ max_tokens = max(100, int(max_prompt_tokens))
1622
+ separator_tokens = len(sections) * 2
1623
+ effective_budget = max(50 * len(sections), max_tokens - separator_tokens)
1624
+
1625
+ # 角色优先级策略:保核心 SOP (100) > 技术栈切片 (80) > 探针描述 (70) > 领域夹具 (50) > 任务上下文 (40)
1626
+ priorities = {
1627
+ "header_role": 90,
1628
+ "role_sop": 100,
1629
+ "tech_slice": 80,
1630
+ "probes_spec": 70,
1631
+ "domain_fixtures": 50,
1632
+ "task_context": 40,
1633
+ }
1634
+
1635
+ num_sections = len(sections)
1636
+ dyn_floor = min(HARNESS_SECTION_BUDGET_FLOOR, effective_budget // (num_sections * 2))
1637
+ dyn_floor = max(10, dyn_floor)
1638
+ floors = {k: dyn_floor for k in sections}
1639
+
1640
+ try:
1641
+ budgeted_sections, degradations = enforce_global_budget(
1642
+ sections,
1643
+ total_budget=effective_budget,
1644
+ priorities=priorities,
1645
+ floors=floors,
1646
+ )
1647
+ assembled = "\n\n".join(text for text in budgeted_sections.values() if text.strip())
1648
+ except BudgetAllocationError:
1649
+ raw_combined = "\n\n".join(text for text in sections.values() if text.strip())
1650
+ assembled, _ = enforce_section_budget(raw_combined, max_tokens, "domain_specialized_prompt")
1651
+
1652
+ final_tokens, _ = _estimate_section_tokens(assembled)
1653
+ if final_tokens > max_tokens:
1654
+ assembled, _ = enforce_section_budget(assembled, max_tokens, "domain_specialized_prompt")
1655
+
1656
+ return assembled
1657
+
1658
+
1659
+ def build_worker_prompt(
1660
+ worker_role: str,
1661
+ target_form: str = "backend",
1662
+ tech_stack: str = "generic",
1663
+ active_probes: Sequence[str] = (),
1664
+ **kwargs: Any,
1665
+ ) -> str:
1666
+ """DOC-248: build_domain_specialized_prompt 别名与外层通用包装。"""
1667
+ return build_domain_specialized_prompt(
1668
+ worker_role=worker_role,
1669
+ target_form=target_form,
1670
+ tech_stack=tech_stack,
1671
+ active_probes=active_probes,
1672
+ **kwargs,
1673
+ )
1674
+
1675
+
1676
+ __all__ = [
1677
+ "BudgetAllocationError",
1678
+ "HARNESS_SECTION_BUDGET_CEILINGS",
1679
+ "HARNESS_SECTION_BUDGETS",
1680
+ "HARNESS_SECTION_BUDGET_FLOOR",
1681
+ "HARNESS_TASK_TEXT_FLOOR",
1682
+ "HARNESS_SKILL_GLOBAL_BUDGET",
1683
+ "HARNESS_WORKER_GLOBAL_BUDGET",
1684
+ "PROBE_SPECIFICATIONS",
1685
+ "ROLE_SOP_SPECIFICATIONS",
1686
+ "SKILL_WORKER_AFFINITY_TIER",
1687
+ "TECH_STACK_RULE_SLICES",
1688
+ "analyze_source_rules",
1689
+ "build_domain_specialized_prompt",
1690
+ "build_worker_prompt",
1691
+ "decorate_stage_task",
1692
+ "detect_unit_rule_slice",
1693
+ "distill_evidence",
1694
+ "enforce_section_budget",
1695
+ "enforce_global_budget",
1696
+ "get_prompts_dir",
1697
+ "get_stage_metadata",
1698
+ "get_stage_prompt",
1699
+ "list_available_stages",
1700
+ "load_rule",
1701
+ "load_stage",
1702
+ "parse_structured_evidence",
1703
+ ]
1704
+