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,1510 @@
1
+ #!/usr/bin/env python3
2
+ """探测并执行 SAST 静态分析与轻量 SCA 依赖安全扫描 (DOC-061)。
3
+
4
+ SAST 层定位:
5
+ 1. 规则驱动的已知漏洞模式扫描(SQLi/XSS/SSRF/RCE/SCA/反模式/反序列化/机密泄漏);
6
+ 2. 零外部依赖多语言支持:内置通用结构化分词与括号平衡树引擎,
7
+ 原生覆盖 Go、Java、TypeScript/JavaScript、Rust、C/C++、Python、PHP 等主流语言;
8
+ 3. 供应链安全 (SCA):内置轻量离线依赖漏洞匹配器 (pom.xml/package.json/go.mod/requirements.txt/Cargo.lock);
9
+ 4. 企业级工程治理:支持跨语言行级抑制 (// bugx-ignore)、项目级路径忽略
10
+ (根目录 ``.bugxignore``,gitignore 子集)、基线快照 (--baseline) 与
11
+ OASIS SARIF v2.1.0 标准导出;
12
+ 5. 非侵入容灾原则:严禁强制外部工具安装,无外部工具时 100% 自动无缝降级至内置多语言引擎。
13
+ """
14
+
15
+ from __future__ import annotations
16
+ from typing import Any
17
+ # --- 引擎导入根(直接执行脚本时自举 core.* 命名空间)---
18
+ import sys as _sys
19
+ from pathlib import Path as _Path
20
+
21
+ for _p in _Path(__file__).resolve().parents:
22
+ if (_p / "core" / "bugx.md").is_file():
23
+ if str(_p) not in _sys.path:
24
+ _sys.path.insert(0, str(_p))
25
+ break
26
+ del _p
27
+
28
+ import argparse
29
+ import ast
30
+ import collections
31
+ import hashlib
32
+ import json
33
+ import math
34
+ import os
35
+ import re
36
+ import shutil
37
+ import subprocess
38
+ import time
39
+ import sys
40
+ from pathlib import Path
41
+
42
+ _CURRENT_DIR = Path(__file__).resolve().parent
43
+ _CORE_DIR = _CURRENT_DIR.parent
44
+ _REPO_ROOT = _CORE_DIR.parent
45
+ for _p in (str(_REPO_ROOT), str(_CORE_DIR), str(_CURRENT_DIR)):
46
+ if _p not in sys.path:
47
+ sys.path.insert(0, _p)
48
+
49
+ from core.probes.sast_rules import BUILTIN_RULES, SASTRuleMatcher
50
+ from core.probes.sca_scanner import SCAScanner
51
+
52
+ from core.planning.dynamic_flow_analyzer import DynamicFlowAnalyzer
53
+
54
+ from core.runtime.tool_install_targets import OPTIONAL_TOOL_PACKAGE_SPECS
55
+ from core.retrieval.universal_code_matcher import (
56
+ EXT_TO_LANG,
57
+ ParsedSource,
58
+ UniversalCodeMatcher,
59
+ extract_suppressions,
60
+ is_suppressed,
61
+ )
62
+
63
+ VALIDATED = {
64
+ "semgrep": "1.80.0",
65
+ "codeql": "2.18.0",
66
+ "trivy": "0.54.0",
67
+ "bandit": "1.8.6",
68
+ }
69
+ # Exact package pins remain separate from VALIDATED: an install target is not
70
+ # evidence that this checkout exercised the corresponding runtime.
71
+ MINIMUM = {
72
+ "semgrep": "1.50.0",
73
+ "codeql": "2.15.0",
74
+ "trivy": "0.40.0",
75
+ "bandit": "1.7.0",
76
+ }
77
+ VERSION_FLAG = {"codeql": "version"}
78
+
79
+ SKIP_DIRS = {
80
+ ".git", ".bugx", ".venv", "venv", "node_modules", "__pycache__",
81
+ "dist", "build", "target", ".tox", ".mypy_cache", ".pytest_cache",
82
+ "vendor", "Pods", ".gradle", ".idea",
83
+ }
84
+
85
+ #: 项目级忽略文件名(放在项目根,gitignore 语法)。
86
+ #: ``SKIP_DIRS`` 只能排除固定的**目录名**,排不掉「本仓里这段路径是靶场/夹具」
87
+ #: 这种 per-project 事实:``verification/sandboxes`` 下故意留洞的 CVE 修复
88
+ #: 样例被当产品代码扫出 20 条 finding,只能靠用户配置的路径模式排除。
89
+ IGNORE_FILE_NAME = ".bugxignore"
90
+
91
+
92
+ def _ignore_glob_to_regex(pattern: str) -> str:
93
+ """把 gitignore 风格的 glob 译成正则体(不含首尾锚点)。
94
+
95
+ 支持 ``*``(不跨 ``/``)、``**``(跨层级)、``?``、``[abc]`` / ``[!abc]``
96
+ 与 ``\\`` 转义;不支持 ``{a,b}`` 花括号展开(正则里会被当字面量)。
97
+ """
98
+ out: list[str] = []
99
+ index = 0
100
+ length = len(pattern)
101
+ while index < length:
102
+ char = pattern[index]
103
+ if char == "*":
104
+ end = index
105
+ while end < length and pattern[end] == "*":
106
+ end += 1
107
+ if end - index >= 2 and end < length and pattern[end] == "/":
108
+ out.append("(?:.*/)?") # ``**/``:跨任意层级目录
109
+ index = end + 1
110
+ elif end - index >= 2:
111
+ out.append(".*")
112
+ index = end
113
+ else:
114
+ out.append("[^/]*")
115
+ index = end
116
+ elif char == "?":
117
+ out.append("[^/]")
118
+ index += 1
119
+ elif char == "[":
120
+ close = pattern.find("]", index + 1)
121
+ if close == -1:
122
+ out.append(re.escape(char))
123
+ index += 1
124
+ else:
125
+ inner = pattern[index + 1:close]
126
+ if inner.startswith("!"):
127
+ inner = "^" + inner[1:]
128
+ out.append(f"[{inner}]")
129
+ index = close + 1
130
+ elif char == "\\" and index + 1 < length:
131
+ out.append(re.escape(pattern[index + 1]))
132
+ index += 2
133
+ else:
134
+ out.append(re.escape(char))
135
+ index += 1
136
+ return "".join(out)
137
+
138
+
139
+ class PathIgnoreSpec:
140
+ """某个项目根下 ``.bugxignore`` 解析出的忽略规格。
141
+
142
+ 刻意**不做模块级缓存**:本探针可能在同一进程里被多次以不同 ``--root``
143
+ 调用,进程级缓存会让 A 项目的模式串到 B 项目。规格由 ``load()`` 读一次,
144
+ 调用方(``run_scan``)持有并在整轮扫描内复用;「重新加载」的时机就是
145
+ 「下一次 ``run_scan(root)``」,与 ``SKIP_DIRS`` 这类进程级常量解耦。
146
+
147
+ 语义是 gitignore 的子集:按行序取**最后一条命中**,``!`` 取反;不带
148
+ ``/`` 的模式匹配任意层级的同名节点,带 ``/`` 的模式锚定项目根;命中
149
+ 某个目录时其下所有文件一并忽略。与 git 的差异:``!`` 可以直接把被忽略
150
+ 目录内的文件重新纳入(git 要求先解除父目录忽略)。
151
+ """
152
+
153
+ def __init__(
154
+ self,
155
+ root: Path,
156
+ rules: tuple[tuple[bool, re.Pattern[str]], ...],
157
+ patterns: tuple[str, ...],
158
+ ) -> None:
159
+ self.root = root
160
+ self._rules = rules
161
+ self.patterns = patterns
162
+
163
+ @classmethod
164
+ def load(cls, root: Path) -> "PathIgnoreSpec":
165
+ root = root.resolve()
166
+ rules: list[tuple[bool, re.Pattern[str]]] = []
167
+ patterns: list[str] = []
168
+ try:
169
+ text = (root / IGNORE_FILE_NAME).read_text(encoding="utf-8", errors="replace")
170
+ except OSError:
171
+ return cls(root, (), ())
172
+ for raw in text.splitlines():
173
+ line = raw.strip()
174
+ if not line or line.startswith("#"):
175
+ continue
176
+ negated = line.startswith("!")
177
+ body = line[1:].strip() if negated else line
178
+ if body.endswith("/"):
179
+ body = body.rstrip("/")
180
+ anchored = body.startswith("/") or "/" in body
181
+ body = body.lstrip("/")
182
+ if not body:
183
+ continue
184
+ prefix = "" if anchored else "(?:.*/)?"
185
+ try:
186
+ regex = re.compile(f"^{prefix}{_ignore_glob_to_regex(body)}$")
187
+ except re.error:
188
+ continue
189
+ rules.append((negated, regex))
190
+ patterns.append(line)
191
+ return cls(root, tuple(rules), tuple(patterns))
192
+
193
+ def matches(self, relative: str | Path) -> bool:
194
+ """``relative`` 为相对项目根的路径;命中任一祖先目录同样算忽略。"""
195
+ if not self._rules:
196
+ return False
197
+ rel = str(relative).replace("\\", "/").strip("/")
198
+ if not rel:
199
+ return False
200
+ parts = rel.split("/")
201
+ candidates = [rel]
202
+ for depth in range(1, len(parts)):
203
+ candidates.append("/".join(parts[:depth]))
204
+ ignored = False
205
+ for negated, regex in self._rules:
206
+ if any(regex.match(candidate) for candidate in candidates):
207
+ ignored = not negated
208
+ return ignored
209
+
210
+ def literal_excludes(self) -> tuple[str, ...]:
211
+ """可下发给外部工具的**字面量**前缀:含通配的规则无法安全翻译,跳过。"""
212
+ literals: list[str] = []
213
+ for pattern in self.patterns:
214
+ if pattern.startswith("!"):
215
+ continue
216
+ if any(char in pattern for char in "*?["):
217
+ continue
218
+ literals.append(pattern.strip("/"))
219
+ return tuple(literals)
220
+
221
+ def describe(self) -> dict[str, Any]:
222
+ return {
223
+ "file": str(self.root / IGNORE_FILE_NAME),
224
+ "patterns": list(self.patterns),
225
+ }
226
+
227
+
228
+ def _skipped(relative: Path, ignore: PathIgnoreSpec | None = None) -> bool:
229
+ """枚举期跳过判定:内置目录白名单 + 引擎命名空间 + 项目级忽略。
230
+
231
+ SAST 也要排除引擎/宿主的 ``.bugx*`` 运行态命名空间:此前只按 ``SKIP_DIRS``
232
+ 的字面名排除 ``.bugx``,``.bugx-audit-artifacts`` 这类兄弟目录会被当源码
233
+ 扫描——实测靶场里宿主写的 ``repro.py`` 就产生了两条
234
+ ``SEC-006-SILENT-EXCEPTION``,被报告当成被测产品的缺陷。判定与覆盖枚举
235
+ 同源(``core.retrieval.symbol_index``),避免两份名单漂移。
236
+
237
+ ``ignore`` 是**按 root 加载**的 ``PathIgnoreSpec``(``None`` = 只有内置规则)。
238
+ 三条判定串成一条链:用户模式不再另起一条过滤通道,避免「枚举跳过」与
239
+ 「事后过滤」两处口径漂移。
240
+ """
241
+ from core.retrieval.symbol_index import is_engine_namespace_segment
242
+
243
+ if any(
244
+ part in SKIP_DIRS or is_engine_namespace_segment(part)
245
+ for part in relative.parts
246
+ ):
247
+ return True
248
+ return ignore is not None and ignore.matches(relative)
249
+
250
+
251
+ #: 逐文件扫描失败的分类(F-207)。``syntax_error``/``parse_error`` 属解析失败,
252
+ #: ``unreadable``/``scanner_error`` 属读取或扫描期失败;两者都必须带 file+reason
253
+ #: 出现在 ``run_scan`` 的 ``skipped_files`` 里,不能与「文件无缺陷」同形。
254
+ _PARSE_FAILURE_REASONS = frozenset({"syntax_error", "parse_error"})
255
+
256
+
257
+ def _skip_reason(exc: BaseException) -> str:
258
+ if isinstance(exc, SyntaxError):
259
+ return "syntax_error"
260
+ if isinstance(exc, ValueError):
261
+ return "parse_error"
262
+ if isinstance(exc, OSError):
263
+ return "unreadable"
264
+ return "scanner_error"
265
+
266
+
267
+ def _record_skip(
268
+ stats: dict[str, Any] | None, *, rel: str, stage: str, exc: BaseException,
269
+ ) -> dict[str, Any]:
270
+ """把一次逐文件跳过折成结构化记录并挂到 ``stats["skipped_files"]``。
271
+
272
+ 聚合层(``run_scan``)据此输出 ``parse_errors``/``skipped_files``;没有它,
273
+ 解析失败的文件只会让 ``scanned_files`` 少一,报告层无法区分「漏扫」与
274
+ 「按规则排除」(F-207)。
275
+ """
276
+ reason = _skip_reason(exc)
277
+ if isinstance(exc, SyntaxError):
278
+ line = int(exc.lineno or 0)
279
+ col = int(exc.offset or 0)
280
+ detail = exc.msg or ""
281
+ else:
282
+ line = 0
283
+ col = 0
284
+ detail = str(exc)
285
+ record = {
286
+ "skipped": True,
287
+ "reason": reason,
288
+ "stage": stage,
289
+ "file": rel,
290
+ "line": line,
291
+ "col": col,
292
+ "detail": detail,
293
+ }
294
+ if stats is not None:
295
+ stats.setdefault("skipped_files", []).append(record)
296
+ return record
297
+
298
+
299
+ def _merge_skipped(records: list[dict[str, Any]]) -> list[dict[str, Any]]:
300
+ """按 (file, reason) 去重并稳定排序逐文件跳过记录。
301
+
302
+ Python 源码会经过 AST 与多语言两条枚举路径,同一份解析失败会被两边各记
303
+ 一次;去重后 ``parse_errors`` 才是「文件数」而不是「路径数」。
304
+ """
305
+ seen: set[tuple[str, str]] = set()
306
+ merged: list[dict[str, Any]] = []
307
+ for item in records:
308
+ key = (str(item.get("file")), str(item.get("reason")))
309
+ if key in seen:
310
+ continue
311
+ seen.add(key)
312
+ merged.append(item)
313
+ merged.sort(key=lambda item: (str(item.get("file")), str(item.get("reason"))))
314
+ return merged
315
+
316
+
317
+ def _probe_environment() -> dict[str, str]:
318
+ try:
319
+ try:
320
+ from .probe_registry import normalized_tool_environment
321
+ except (ImportError, ValueError):
322
+ try:
323
+ from .probe_registry import normalized_tool_environment
324
+ except ImportError:
325
+ from core.probes.probe_registry import normalized_tool_environment
326
+ return normalized_tool_environment()
327
+ except ImportError:
328
+ return dict(os.environ)
329
+
330
+
331
+ def version_tuple(value: str) -> tuple[int, ...]:
332
+ match = re.search(r"(\d+(?:\.\d+){1,3})", value)
333
+ return tuple(int(part) for part in match.group(1).split(".")) if match else ()
334
+
335
+
336
+ _TOOL_PROBE_CACHE: dict[str, dict] = {}
337
+
338
+
339
+ def clear_tool_probe_cache() -> None:
340
+ _TOOL_PROBE_CACHE.clear()
341
+
342
+
343
+ def _tool_candidates(names: tuple[str, ...], search_path: str) -> list[str]:
344
+ """Return deduplicated executables in PATH order for the requested aliases."""
345
+ directories = [entry for entry in search_path.split(os.pathsep) if entry]
346
+ candidates: list[str] = []
347
+ seen: set[str] = set()
348
+ for name in names:
349
+ for directory in directories:
350
+ candidate = shutil.which(name, path=directory)
351
+ if not candidate:
352
+ continue
353
+ identity = os.path.normcase(os.path.realpath(candidate))
354
+ if identity in seen:
355
+ continue
356
+ seen.add(identity)
357
+ candidates.append(candidate)
358
+ return candidates
359
+
360
+
361
+ def _candidate_signature(candidates: list[str], search_path: str) -> tuple:
362
+ """Invalidate cached versions when PATH candidates or their files change."""
363
+ signatures = []
364
+ for candidate in candidates:
365
+ try:
366
+ stat = Path(candidate).stat()
367
+ file_signature = (stat.st_mtime_ns, stat.st_size)
368
+ except OSError:
369
+ file_signature = None
370
+ signatures.append((candidate, os.path.realpath(candidate), file_signature))
371
+ return search_path, tuple(signatures)
372
+
373
+
374
+ def _version_at_least(actual: tuple[int, ...], minimum: tuple[int, ...]) -> bool:
375
+ width = max(len(actual), len(minimum))
376
+ return actual + (0,) * (width - len(actual)) >= minimum + (0,) * (width - len(minimum))
377
+
378
+
379
+ def _command(names: tuple[str, ...], expected: str) -> dict:
380
+ environment = _probe_environment()
381
+ search_path = environment.get("PATH", "")
382
+ candidates = _tool_candidates(names, search_path)
383
+ if not candidates:
384
+ return {"name": expected, "ok": False, "path": None, "version": None,
385
+ "detail": "未安装"}
386
+
387
+ signature = _candidate_signature(candidates, search_path)
388
+ cached = _TOOL_PROBE_CACHE.get(expected)
389
+ if cached and cached.get("_signature") == signature:
390
+ return {key: value for key, value in cached.items() if key != "_signature"}
391
+
392
+ flag = VERSION_FLAG.get(expected, "--version")
393
+ minimum = version_tuple(MINIMUM[expected])
394
+ observations: list[dict] = []
395
+ transient_failure = False
396
+ for path in candidates:
397
+ try:
398
+ result = subprocess.run(
399
+ [path, flag], capture_output=True, text=True,
400
+ check=False, timeout=10, env=environment,
401
+ )
402
+ except (OSError, subprocess.TimeoutExpired) as exc:
403
+ transient_failure = True
404
+ observations.append({
405
+ "path": path, "version": None, "detail": type(exc).__name__,
406
+ })
407
+ continue
408
+ output = f"{result.stdout or ''}\n{result.stderr or ''}"
409
+ version_text = next(
410
+ (line.strip() for line in output.splitlines() if version_tuple(line)), "",
411
+ )
412
+ actual = version_tuple(version_text)
413
+ if result.returncode == 0 and actual and _version_at_least(actual, minimum):
414
+ info = {
415
+ "name": expected,
416
+ "ok": True,
417
+ "path": path,
418
+ "version": version_text,
419
+ "minimum": MINIMUM[expected],
420
+ "validated": VALIDATED[expected],
421
+ "detail": version_text,
422
+ "rejected_candidates": observations,
423
+ }
424
+ _TOOL_PROBE_CACHE[expected] = {**info, "_signature": signature}
425
+ return info
426
+ observations.append({
427
+ "path": path,
428
+ "version": version_text or None,
429
+ "detail": version_text or f"--version exited {result.returncode}",
430
+ })
431
+
432
+ first = observations[0] if observations else {}
433
+ info = {
434
+ "name": expected,
435
+ "ok": False,
436
+ "path": first.get("path", candidates[0]),
437
+ "version": first.get("version"),
438
+ "minimum": MINIMUM[expected],
439
+ "validated": VALIDATED[expected],
440
+ "detail": f"未找到满足最低版本 {MINIMUM[expected]} 的 PATH 候选",
441
+ "rejected_candidates": observations,
442
+ }
443
+ if not transient_failure:
444
+ _TOOL_PROBE_CACHE[expected] = {**info, "_signature": signature}
445
+ return info
446
+
447
+
448
+ def check_tool(name: str) -> dict:
449
+ """Check one registered SAST executable using the same PATH/version policy."""
450
+ if name not in MINIMUM:
451
+ raise ValueError(f"不支持的 SAST 工具: {name}")
452
+ return _command((name,), name)
453
+
454
+
455
+ #: 通道状态探针声明(AM-6 差距修复):``check``/``status`` 只探测外部工具链
456
+ #: 在场性(findings 恒空),与 mobile/ios_binary 的 ``check``(产出 findings)
457
+ #: 语义不同。显式输出声明行,避免调用方把「通道就绪」误读成「扫过没问题」。
458
+ CHANNEL_STATUS_NOTE = (
459
+ "channel-status only; run 'bugx probe sast scan' for findings"
460
+ )
461
+
462
+
463
+ def inspect(root: Path) -> dict:
464
+ root = root.resolve()
465
+ base = [
466
+ _command(("semgrep",), "semgrep"),
467
+ _command(("codeql",), "codeql"),
468
+ _command(("trivy",), "trivy"),
469
+ _command(("bandit",), "bandit"),
470
+ ]
471
+ ready = any(item["ok"] for item in base)
472
+ return {
473
+ "status": "READY" if ready else "DEGRADED",
474
+ "required": False,
475
+ "recommended": True,
476
+ "root": str(root),
477
+ "probe_kind": "channel_status",
478
+ "semantic_note": CHANNEL_STATUS_NOTE,
479
+ "base_tools": base,
480
+ "install": {
481
+ "semgrep": f"pipx install {OPTIONAL_TOOL_PACKAGE_SPECS['semgrep']}",
482
+ "codeql": "https://github.com/github/codeql-cli-binaries/releases",
483
+ "trivy": "brew install trivy",
484
+ "bandit": f"pipx install {OPTIONAL_TOOL_PACKAGE_SPECS['bandit']}",
485
+ },
486
+ "fallback": "pattern_probe.py scan + ast-grep 有界静态扫描",
487
+ "workflow": "SAST 扫描出候选点 → codebase-memory trace_path 验 Source→Sink → PostMCP/Playwright 发 PoC 复现",
488
+ }
489
+
490
+
491
+ def print_report(report: dict, as_json: bool = False) -> None:
492
+ if as_json:
493
+ print(json.dumps(report, ensure_ascii=False, indent=2))
494
+ return
495
+ print(f"[{report['status']}] SAST 静态分析工具链(推荐,非硬依赖,支持多语言自动降级)")
496
+ # 通道状态探针声明:check/status 不产出 findings,「READY」只代表工具链
497
+ # 就绪,绝不代表「扫过没问题」;实际扫描必须走 scan 子命令。
498
+ print(f" · 通道状态探针({CHANNEL_STATUS_NOTE})——findings 恒空,非漏洞扫描结果")
499
+ for item in report["base_tools"]:
500
+ print(f" {'✓' if item['ok'] else '!'} {item['name']}: {item['detail']}")
501
+ if report["status"] != "READY":
502
+ print(f" → 回退:{report['fallback']}")
503
+ print(" → 架构契约:非侵入式零依赖,未安装外部工具时直接使用内置多语言分析引擎,无需配置或编译环境。")
504
+
505
+
506
+ #: 常见的「占位符」值片段:命中即说明是文档/测试假凭证而非真实机密。
507
+ _SECRET_PLACEHOLDER_HINTS = (
508
+ "example", "placeholder", "changeme", "dummy", "sample", "redacted",
509
+ "your_", "xxxxx", "todo", "fixme", "fake",
510
+ )
511
+ _SECRET_CHAR_CLASSES = (r"[a-z]", r"[A-Z]", r"\d", r"[^A-Za-z0-9]")
512
+
513
+
514
+ def _shannon_entropy(value: str) -> float:
515
+ """字符级 Shannon 熵(bits/char),用于区分随机密钥与可读占位串。"""
516
+ if not value:
517
+ return 0.0
518
+ length = len(value)
519
+ return -sum(
520
+ (count / length) * math.log2(count / length)
521
+ for count in collections.Counter(value).values()
522
+ )
523
+
524
+
525
+ def _looks_like_hardcoded_secret(value: str) -> bool:
526
+ """判断字面量本身是否具备「硬编码机密」的值特征(QUA-08)。
527
+
528
+ 仅按变量名(含 ``api_key``/``token``)判定会把中文提示文案、状态哨兵与
529
+ 测试假 token 全部报成 high,真实机密告警被误报淹没。这里要求值同时满足:
530
+ 长度 ≥ 16、纯 ASCII 无空白、非 SCREAMING_SNAKE_CASE 常量、非占位符,
531
+ 且字符级熵达标(两类字符时阈值更高)。
532
+ """
533
+ if len(value) < 16 or not value.isascii():
534
+ return False
535
+ if any(character.isspace() for character in value):
536
+ return False
537
+ if value.startswith(("http://", "https://", "ENV_")):
538
+ return False
539
+ if re.fullmatch(r"[A-Z0-9_]+", value): # 常量名 / 状态哨兵,不是机密
540
+ return False
541
+ lowered = value.lower()
542
+ if any(hint in lowered for hint in _SECRET_PLACEHOLDER_HINTS):
543
+ return False
544
+ classes = sum(1 for pattern in _SECRET_CHAR_CLASSES if re.search(pattern, value))
545
+ if classes < 2:
546
+ return False
547
+ return _shannon_entropy(value) >= (3.5 if classes == 2 else 3.0)
548
+
549
+
550
+ class BuiltinAstScanner(ast.NodeVisitor):
551
+ """基于 Python 标准库 AST 的确定性安全与风险反模式检测器(保持向前兼容)。"""
552
+
553
+ def __init__(self, filepath: Path, rel_path: str, source_lines: list[str]) -> None:
554
+ self.filepath = filepath
555
+ self.rel_path = rel_path
556
+ self.source_lines = source_lines
557
+ self.findings: list[dict[str, Any]] = []
558
+ self.dynamic_analyzer = DynamicFlowAnalyzer(language="python")
559
+ self.var_env: dict[str, Any] = {}
560
+
561
+ def _get_snippet(self, lineno: int) -> str:
562
+ if 1 <= lineno <= len(self.source_lines):
563
+ return self.source_lines[lineno - 1].strip()
564
+ return ""
565
+
566
+ def visit_FunctionDef(self, node: ast.FunctionDef) -> None:
567
+ self.var_env.update(self.dynamic_analyzer.fold_python_function_scope(node))
568
+ self.generic_visit(node)
569
+
570
+ def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None:
571
+ self.var_env.update(self.dynamic_analyzer.fold_python_function_scope(node))
572
+ self.generic_visit(node)
573
+
574
+ def visit_Call(self, node: ast.Call) -> None:
575
+ func_name = ""
576
+ if isinstance(node.func, ast.Name):
577
+ func_name = node.func.id
578
+ elif isinstance(node.func, ast.Attribute):
579
+ func_name = node.func.attr
580
+
581
+ # os.system / os.popen 与 tempfile.mktemp,支持直接和 getattr 调用。
582
+ mod = ""
583
+ attr = ""
584
+ if isinstance(node.func, ast.Attribute) and isinstance(node.func.value, ast.Name):
585
+ mod = node.func.value.id
586
+ attr = node.func.attr
587
+ elif (
588
+ isinstance(node.func, ast.Call)
589
+ and isinstance(node.func.func, ast.Name)
590
+ and node.func.func.id == "getattr"
591
+ and len(node.func.args) >= 2
592
+ ):
593
+ target, attr_value = node.func.args[:2]
594
+ if isinstance(target, ast.Name):
595
+ mod = target.id
596
+ if isinstance(attr_value, ast.Constant) and isinstance(attr_value.value, str):
597
+ attr = attr_value.value
598
+ elif isinstance(attr_value, ast.Name) and attr_value.id in self.var_env:
599
+ value = self.var_env[attr_value.id].value
600
+ attr = value if isinstance(value, str) else ""
601
+ if mod == "os" and attr in {"system", "popen"}:
602
+ self.findings.append({
603
+ "rule_id": "SEC-001-OS-SYSTEM",
604
+ "name": "OS Command Injection via os.system",
605
+ "category": "command-injection",
606
+ "severity": "high",
607
+ "confidence": "high",
608
+ "cwe": "CWE-78",
609
+ "message": f"调用 {mod}.{attr} 执行外部命令,存在命令注入风险",
610
+ "file": self.rel_path,
611
+ "line": node.lineno,
612
+ "col": node.col_offset,
613
+ "evidence": self._get_snippet(node.lineno),
614
+ "remediation": "建议使用 subprocess.run 并传入数组形式的 argv,避免 shell 解析",
615
+ })
616
+ elif mod == "tempfile" and attr == "mktemp":
617
+ self.findings.append({
618
+ "rule_id": "SEC-007-INSECURE-TEMPFILE",
619
+ "name": "Insecure Temporary File",
620
+ "category": "race-condition",
621
+ "severity": "medium",
622
+ "confidence": "high",
623
+ "cwe": "CWE-377",
624
+ "message": "使用不安全的 tempfile.mktemp 创建临时文件,存在 TOCTOU 竞态漏洞",
625
+ "file": self.rel_path,
626
+ "line": node.lineno,
627
+ "col": node.col_offset,
628
+ "evidence": self._get_snippet(node.lineno),
629
+ "remediation": "改用 tempfile.NamedTemporaryFile 或 tempfile.mkstemp",
630
+ })
631
+
632
+ # subprocess(..., shell=True)
633
+ for kw in node.keywords:
634
+ if kw.arg == "shell":
635
+ is_true = False
636
+ if isinstance(kw.value, ast.Constant) and kw.value.value is True:
637
+ is_true = True
638
+ if is_true:
639
+ self.findings.append({
640
+ "rule_id": "SEC-001-SUBPROCESS-SHELL",
641
+ "name": "Subprocess shell=True Injection",
642
+ "category": "command-injection",
643
+ "severity": "high",
644
+ "confidence": "high",
645
+ "cwe": "CWE-78",
646
+ "message": "subprocess 执行携带 shell=True,可能导致未转义命令注入",
647
+ "file": self.rel_path,
648
+ "line": node.lineno,
649
+ "col": node.col_offset,
650
+ "evidence": self._get_snippet(node.lineno),
651
+ "remediation": "移除 shell=True,将命令拆分为参数列表传入",
652
+ })
653
+
654
+ # SEC-002: 危险执行 eval / exec
655
+ if func_name in {"eval", "exec"}:
656
+ self.findings.append({
657
+ "rule_id": "SEC-002-DANGEROUS-EVAL",
658
+ "name": "Dangerous Dynamic Code Execution",
659
+ "category": "code-injection",
660
+ "severity": "critical",
661
+ "confidence": "medium",
662
+ "cwe": "CWE-95",
663
+ "message": f"直接调用动态代码执行函数 {func_name}()",
664
+ "file": self.rel_path,
665
+ "line": node.lineno,
666
+ "col": node.col_offset,
667
+ "evidence": self._get_snippet(node.lineno),
668
+ "remediation": "避免使用 eval/exec;如需解析字面量使用 ast.literal_eval",
669
+ })
670
+
671
+ # SEC-003: 不安全反序列化 pickle.loads / marshal.loads
672
+ if isinstance(node.func, ast.Attribute) and isinstance(node.func.value, ast.Name):
673
+ if node.func.value.id in {"pickle", "_pickle", "cPickle", "marshal"} and node.func.attr in {"load", "loads"}:
674
+ self.findings.append({
675
+ "rule_id": "SEC-003-INSECURE-DESERIALIZATION",
676
+ "name": "Insecure Deserialization",
677
+ "category": "deserialization",
678
+ "severity": "critical",
679
+ "confidence": "high",
680
+ "cwe": "CWE-502",
681
+ "message": f"使用未受信任的 {node.func.value.id}.{node.func.attr} 反序列化,可导致任意代码执行",
682
+ "file": self.rel_path,
683
+ "line": node.lineno,
684
+ "col": node.col_offset,
685
+ "evidence": self._get_snippet(node.lineno),
686
+ "remediation": "改用安全的结构化格式(如 json / protobuf / hmac 签名)",
687
+ })
688
+
689
+ # SEC-SSTI-001: Python SSTI (render_template_string, jinja2.Template)
690
+ if func_name == "render_template_string" or (
691
+ isinstance(node.func, ast.Attribute) and node.func.attr in {"render_template_string", "from_string"}
692
+ ):
693
+ is_vuln = True
694
+ if node.args:
695
+ first_arg = node.args[0]
696
+ if isinstance(first_arg, ast.Constant) and isinstance(first_arg.value, str):
697
+ # 纯静态字面量视为安全
698
+ is_vuln = False
699
+ elif isinstance(first_arg, ast.Name) and first_arg.id in self.var_env:
700
+ var_obj = self.var_env[first_arg.id]
701
+ if var_obj.is_constant:
702
+ is_vuln = False
703
+ if is_vuln:
704
+ self.findings.append({
705
+ "rule_id": "SEC-SSTI-001",
706
+ "name": "Server-Side Template Injection (SSTI)",
707
+ "category": "template-injection",
708
+ "severity": "critical",
709
+ "confidence": "high",
710
+ "cwe": "CWE-1336",
711
+ "message": "动态渲染外部可控的模版字符串,可能导致服务端模版注入与远程代码执行",
712
+ "file": self.rel_path,
713
+ "line": node.lineno,
714
+ "col": node.col_offset,
715
+ "evidence": self._get_snippet(node.lineno),
716
+ "remediation": "改用静态模版文件并传递参数字典(如 render_template),严禁直接动态编译外部字符串为模版。",
717
+ })
718
+
719
+ self.generic_visit(node)
720
+
721
+ def visit_ExceptHandler(self, node: ast.ExceptHandler) -> None:
722
+ if len(node.body) == 1 and isinstance(node.body[0], ast.Pass):
723
+ is_broad = node.type is None
724
+ if isinstance(node.type, ast.Name) and node.type.id in {"Exception", "BaseException"}:
725
+ is_broad = True
726
+ if is_broad:
727
+ self.findings.append({
728
+ "rule_id": "SEC-006-SILENT-EXCEPTION",
729
+ "name": "Silent Generic Exception Swallowing",
730
+ "category": "error-handling",
731
+ "severity": "low",
732
+ "confidence": "high",
733
+ "cwe": "CWE-391",
734
+ "message": "静默捕获并吞没通用异常(except: pass),掩盖运行时致命故障",
735
+ "file": self.rel_path,
736
+ "line": node.lineno,
737
+ "col": node.col_offset,
738
+ "evidence": self._get_snippet(node.lineno),
739
+ "remediation": "指定具体异常类型,并在 except 块中记录日志或妥善恢复",
740
+ })
741
+ self.generic_visit(node)
742
+
743
+ def visit_Assign(self, node: ast.Assign) -> None:
744
+ sensitive_kw = {"password", "secret", "api_key", "apikey", "token", "private_key"}
745
+ for target in node.targets:
746
+ target_name = ""
747
+ if isinstance(target, ast.Name):
748
+ target_name = target.id.lower()
749
+ elif isinstance(target, ast.Attribute):
750
+ target_name = target.attr.lower()
751
+
752
+ if any(kw in target_name for kw in sensitive_kw):
753
+ if isinstance(node.value, ast.Constant) and isinstance(node.value.value, str):
754
+ val = node.value.value
755
+ # QUA-08:变量名匹配只是必要条件;值本身还必须像机密。
756
+ # 行级抑制不在这里判——``scan_source_ast`` 汇合点统一按规则名过滤。
757
+ if _looks_like_hardcoded_secret(val):
758
+ self.findings.append({
759
+ "rule_id": "SEC-004-HARDCODED-SECRET",
760
+ "name": "Hardcoded Secret",
761
+ "category": "secrets",
762
+ "severity": "high",
763
+ "confidence": "medium",
764
+ "cwe": "CWE-798",
765
+ "message": f"疑似在变量 {target_name} 中硬编码静态机密凭证",
766
+ "file": self.rel_path,
767
+ "line": node.lineno,
768
+ "col": node.col_offset,
769
+ "evidence": self._get_snippet(node.lineno),
770
+ "remediation": "从安全环境变量或凭据保险箱动态获取,切勿写入代码",
771
+ })
772
+ self.generic_visit(node)
773
+
774
+
775
+ def scan_source_ast(
776
+ root: Path, max_files: int = 1000, stats: dict[str, Any] | None = None,
777
+ ignore: PathIgnoreSpec | None = None,
778
+ ) -> list[dict[str, Any]]:
779
+ """扫描 Python 源码(BuiltinAstScanner,保持向前兼容)。
780
+
781
+ ``stats`` 若给出,会填入 ``files``(成功解析的文件数)与 ``skipped_files``
782
+ (逐文件跳过记录:``reason`` 区分 ``syntax_error``/``unreadable`` 等)。
783
+ 报告层需要这两个数字才能说清覆盖范围:只有 ``files`` 时,解析失败的文件
784
+ 与「扫描范围外」在证据上无法区分(F-207)。
785
+
786
+ 行级抑制**不在这里**判:抑制统一在 ``run_scan`` 的去重之后执行(见
787
+ ``_apply_suppressions``)。若在收集期就吃掉命中,跨规则去重会把同源的另一
788
+ 条规则顶上来,用户抑制掉一条、报告里换个规则名继续报。
789
+ """
790
+ findings: list[dict[str, Any]] = []
791
+ scanned = 0
792
+ for path in sorted(root.rglob("*.py")):
793
+ if scanned >= max_files:
794
+ break
795
+ if path.is_symlink() or not path.is_file():
796
+ continue
797
+ try:
798
+ rel = path.relative_to(root).as_posix()
799
+ except ValueError:
800
+ rel = str(path)
801
+ if _skipped(Path(rel), ignore):
802
+ continue
803
+ try:
804
+ content = path.read_text(encoding="utf-8", errors="replace")
805
+ source_lines = content.splitlines()
806
+ tree = ast.parse(content, filename=str(path))
807
+ except (SyntaxError, OSError) as exc:
808
+ _record_skip(stats, rel=rel, stage="builtin_ast", exc=exc)
809
+ continue
810
+ scanner = BuiltinAstScanner(path, rel, source_lines)
811
+ scanner.visit(tree)
812
+ findings.extend(scanner.findings)
813
+ scanned += 1
814
+ if stats is not None:
815
+ stats["files"] = stats.get("files", 0) + scanned
816
+ return findings
817
+
818
+
819
+ def scan_multilang_sources(
820
+ root: Path, max_files: int = 2000, stats: dict[str, Any] | None = None,
821
+ ignore: PathIgnoreSpec | None = None,
822
+ ) -> list[dict[str, Any]]:
823
+ """使用 UniversalCodeMatcher 与 SASTRuleMatcher 对多语言源码(含 Python)执行扫描。"""
824
+ matcher = SASTRuleMatcher(BUILTIN_RULES)
825
+ findings: list[dict[str, Any]] = []
826
+ scanned = 0
827
+
828
+ # 必须覆盖 Python:``BUILTIN_RULES`` 里有 10 条规则声明了 ``python`` 规格
829
+ # (SQLi / 反序列化 / 路径穿越 / SSRF / 弱加密 / 临时文件 / SSTI …),而
830
+ # ``BuiltinAstScanner`` 只覆盖命令注入、动态执行、硬编码凭据三类。早先这里
831
+ # 跳过 ``.py`` 让那 10 条规则的 Python 规格成了永不执行的死代码——靶场种子
832
+ # 「pathlib 拼接式路径穿越」因此完全漏检(F-RSI-20261110-010)。AST 扫描器
833
+ # 与规则引擎对同一处命令注入/eval 的重叠命中由 ``_dedupe_cross_tool`` 合并。
834
+ for ext in EXT_TO_LANG:
835
+ for path in root.rglob(f"*{ext}"):
836
+ if scanned >= max_files:
837
+ break
838
+ if path.is_symlink() or not path.is_file():
839
+ continue
840
+ try:
841
+ rel = path.relative_to(root).as_posix()
842
+ except ValueError:
843
+ rel = str(path)
844
+ if _skipped(Path(rel), ignore):
845
+ continue
846
+
847
+ try:
848
+ content = path.read_text(encoding="utf-8", errors="replace")
849
+ parsed = UniversalCodeMatcher.parse_file(path, rel_path=rel, content=content)
850
+ # 抑制不在收集期判:清空解析出的抑制表,统一交给 ``run_scan`` 在
851
+ # 去重之后过滤。否则 ``sast_rules`` 会先吃掉多语言命中,同源的
852
+ # AST 规则在去重时无从得知它被合并(``merged_rule_ids`` 为空),
853
+ # 用户按规则目录写 ``# bugx-ignore: SEC-CMD-001`` 就静默失效。
854
+ parsed.suppressions = {}
855
+ file_findings = matcher.match_file(parsed)
856
+ findings.extend(file_findings)
857
+ scanned += 1
858
+ except Exception as exc: # noqa: BLE001 - 结构化记录,不再静默 continue
859
+ # 逐文件失败不再裸 ``continue``:记录 file+reason 后由 ``run_scan``
860
+ # 汇总为 ``skipped_files``。单文件失败不中断整轮扫描,但必须在
861
+ # 证据上可区分(F-207)。
862
+ _record_skip(stats, rel=rel, stage="multilang", exc=exc)
863
+ continue
864
+
865
+ # Python 文件的 AST 专有规则由 ``matcher._scan_python_specifics`` 内部记录
866
+ # 解析失败(matcher 层维护 parse_error 清单),这里并入同一份聚合结果,
867
+ # 避免只暴露「多语言外壳」抛出的失败而漏掉 AST 规则层的跳过。
868
+ if stats is not None:
869
+ stats.setdefault("skipped_files", []).extend(matcher.parse_errors)
870
+ stats["files"] = stats.get("files", 0) + scanned
871
+ return findings
872
+
873
+
874
+ def scan_external_bandit(
875
+ root: Path, timeout: float = 60.0, ignore: PathIgnoreSpec | None = None,
876
+ ) -> list[dict[str, Any]]:
877
+ """调用外部 Native Bandit 对 Python 源码进行深度安全扫描。
878
+
879
+ ``timeout`` 由调用方按**剩余总预算**下发(``run_scan(deadline_seconds=...)``),
880
+ 使外部工具无法把整轮扫描拖过调用方的墙钟上限。
881
+ """
882
+ environment = _probe_environment()
883
+ exe = shutil.which("bandit", path=environment.get("PATH"))
884
+ if not exe:
885
+ return []
886
+ try:
887
+ # 外部工具自己遍历磁盘,只能靠 ``-x`` 下发同一份忽略规格(仅字面量前缀)。
888
+ excludes = list(SKIP_DIRS)
889
+ if ignore is not None:
890
+ excludes.extend(str(root / literal) for literal in ignore.literal_excludes())
891
+ cmd = [exe, "-r", str(root), "-f", "json", "-q", "-x", ",".join(excludes)]
892
+ res = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout,
893
+ check=False, env=environment)
894
+ if res.returncode not in (0, 1):
895
+ return []
896
+ if not res.stdout.strip():
897
+ return []
898
+ try:
899
+ data = json.loads(res.stdout)
900
+ except json.JSONDecodeError:
901
+ return []
902
+ results = []
903
+ for item in data.get("results", []):
904
+ path_str = item.get("filename", "")
905
+ try:
906
+ rel = Path(path_str).relative_to(root).as_posix()
907
+ except Exception:
908
+ rel = path_str
909
+ cwe_id = "CWE-General"
910
+ issue_cwe = item.get("issue_cwe")
911
+ if isinstance(issue_cwe, dict) and issue_cwe.get("id"):
912
+ cwe_id = f"CWE-{issue_cwe.get('id')}"
913
+ results.append({
914
+ "rule_id": item.get("test_id", "bandit-rule"),
915
+ "name": item.get("test_name", "Bandit Finding"),
916
+ "category": "sast-bandit",
917
+ "severity": str(item.get("issue_severity", "medium")).lower(),
918
+ "confidence": str(item.get("issue_confidence", "medium")).lower(),
919
+ "cwe": cwe_id,
920
+ "message": item.get("issue_text", "Bandit 安全规则触发"),
921
+ "file": rel,
922
+ "line": item.get("line_number", 1),
923
+ "col": item.get("col_offset", 1),
924
+ "evidence": str(item.get("code", "")).strip(),
925
+ "remediation": f"参考 Bandit 规则文档修复: {item.get('more_info', '')}",
926
+ })
927
+ return results
928
+ except Exception:
929
+ return []
930
+
931
+
932
+ def scan_external_semgrep(
933
+ root: Path, timeout: float = 60.0, ignore: PathIgnoreSpec | None = None,
934
+ ) -> list[dict[str, Any]]:
935
+ """调用外部 Semgrep 做深度规则扫描;``timeout`` 由调用方的剩余预算下发。"""
936
+ environment = _probe_environment()
937
+ exe = shutil.which("semgrep", path=environment.get("PATH"))
938
+ if not exe:
939
+ return []
940
+ try:
941
+ cmd = [exe, "scan", "--json", "--quiet", "--config", "p/security-audit"]
942
+ if ignore is not None:
943
+ for literal in ignore.literal_excludes():
944
+ cmd.extend(["--exclude", literal])
945
+ cmd.append(str(root))
946
+ res = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout,
947
+ check=False, env=environment)
948
+ if res.returncode not in (0, 1):
949
+ return []
950
+ data = json.loads(res.stdout)
951
+ results = []
952
+ for item in data.get("results", []):
953
+ path_str = item.get("path", "")
954
+ try:
955
+ rel = Path(path_str).relative_to(root).as_posix()
956
+ except Exception:
957
+ rel = path_str
958
+ start = item.get("start", {})
959
+ extra = item.get("extra", {})
960
+ results.append({
961
+ "rule_id": item.get("check_id", "semgrep-rule"),
962
+ "name": item.get("check_id", "Semgrep Finding"),
963
+ "category": "sast-semgrep",
964
+ "severity": extra.get("severity", "medium").lower(),
965
+ "confidence": "high",
966
+ "cwe": (extra.get("metadata", {}).get("cwe") or ["CWE-General"])[0],
967
+ "message": extra.get("message", "Semgrep 规则触发"),
968
+ "file": rel,
969
+ "line": start.get("line", 1),
970
+ "col": start.get("col", 1),
971
+ "evidence": extra.get("lines", "").strip(),
972
+ "remediation": "根据 Semgrep 安全最佳实践修复代码逻辑",
973
+ })
974
+ return results
975
+ except Exception:
976
+ return []
977
+
978
+
979
+ def compute_finding_fingerprint(finding: dict[str, Any]) -> str:
980
+ """计算用于基线快照匹配的确定性指纹"""
981
+ raw = f"{finding.get('rule_id')}:{finding.get('file')}:{finding.get('evidence', '').strip()}"
982
+ return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:16]
983
+
984
+
985
+ def apply_baseline_filter(findings: list[dict[str, Any]], baseline_path: Path) -> tuple[list[dict[str, Any]], int]:
986
+ """过滤掉已存在于基线快照中的历史 Finding"""
987
+ if not baseline_path.exists():
988
+ return findings, 0
989
+ try:
990
+ data = json.loads(baseline_path.read_text(encoding="utf-8"))
991
+ baseline_hashes = set(data.get("fingerprints", []))
992
+ except Exception:
993
+ return findings, 0
994
+
995
+ filtered = []
996
+ suppressed_count = 0
997
+ for item in findings:
998
+ fp = compute_finding_fingerprint(item)
999
+ if fp in baseline_hashes:
1000
+ suppressed_count += 1
1001
+ else:
1002
+ filtered.append(item)
1003
+ return filtered, suppressed_count
1004
+
1005
+
1006
+ def save_baseline(findings: list[dict[str, Any]], baseline_path: Path) -> None:
1007
+ fingerprints = sorted(list({compute_finding_fingerprint(f) for f in findings}))
1008
+ payload = {
1009
+ "version": 1,
1010
+ "total": len(fingerprints),
1011
+ "fingerprints": fingerprints,
1012
+ }
1013
+ baseline_path.parent.mkdir(parents=True, exist_ok=True)
1014
+ baseline_path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
1015
+
1016
+
1017
+ def export_to_sarif(scan_res: dict[str, Any]) -> dict[str, Any]:
1018
+ """将扫描结果导出为标准 OASIS SARIF v2.1.0 格式"""
1019
+ results = []
1020
+ rules_map: dict[str, dict[str, Any]] = {}
1021
+
1022
+ for f in scan_res.get("findings", []):
1023
+ rule_id = f.get("rule_id", "BUGX-RULE")
1024
+ if rule_id not in rules_map:
1025
+ rules_map[rule_id] = {
1026
+ "id": rule_id,
1027
+ "name": f.get("name", rule_id),
1028
+ "shortDescription": {"text": f.get("name", rule_id)},
1029
+ "fullDescription": {"text": f.get("message", "")},
1030
+ "help": {"text": f.get("remediation", f.get("recommendation", ""))},
1031
+ "properties": {
1032
+ "cwe": f.get("cwe", "CWE-Unknown"),
1033
+ "category": f.get("category", "security"),
1034
+ }
1035
+ }
1036
+
1037
+ level = "warning"
1038
+ sev = f.get("severity", "medium").lower()
1039
+ if sev in {"critical", "high"}:
1040
+ level = "error"
1041
+ elif sev == "low":
1042
+ level = "note"
1043
+
1044
+ results.append({
1045
+ "ruleId": rule_id,
1046
+ "level": level,
1047
+ "message": {"text": f.get("message", "")},
1048
+ "locations": [{
1049
+ "physicalLocation": {
1050
+ "artifactLocation": {"uri": f.get("file", "")},
1051
+ "region": {
1052
+ "startLine": f.get("line", 1),
1053
+ "startColumn": f.get("col", 1) + 1,
1054
+ "snippet": {"text": f.get("evidence", "")}
1055
+ }
1056
+ }
1057
+ }]
1058
+ })
1059
+
1060
+ return {
1061
+ "$schema": "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json",
1062
+ "version": "2.1.0",
1063
+ "runs": [{
1064
+ "tool": {
1065
+ "driver": {
1066
+ "name": "BugX-SAST",
1067
+ "informationUri": "https://bugx.dev",
1068
+ "rules": list(rules_map.values()),
1069
+ }
1070
+ },
1071
+ "results": results,
1072
+ }]
1073
+ }
1074
+
1075
+
1076
+ def _cwe_head(value: Any) -> str:
1077
+ """取 CWE 编号本体:semgrep 会给出 ``CWE-78: Improper Neutralization...``。"""
1078
+ return str(value or "").strip().upper().split(":", 1)[0].strip()
1079
+
1080
+
1081
+ def _finding_source_lines(root: Path, rel: str) -> list[str] | None:
1082
+ """读取 finding 指向的源文件行;越出 ``root`` 或读不到时返回 ``None``。"""
1083
+ candidate = Path(rel)
1084
+ path = candidate if candidate.is_absolute() else root / candidate
1085
+ try:
1086
+ resolved = path.resolve()
1087
+ resolved.relative_to(root)
1088
+ except (OSError, ValueError):
1089
+ return None
1090
+ try:
1091
+ return resolved.read_text(encoding="utf-8", errors="replace").splitlines()
1092
+ except OSError:
1093
+ return None
1094
+
1095
+
1096
+ def _apply_suppressions(
1097
+ root: Path, findings: list[dict[str, Any]]
1098
+ ) -> tuple[list[dict[str, Any]], int]:
1099
+ """按行级抑制过滤**去重之后**的最终结果,返回 (保留项, 被抑制数)。
1100
+
1101
+ 抑制必须作用在「缺陷」上,而不是各扫描器「原始命中」上。跨规则去重会把
1102
+ 同一处的重复命中合并成一条代表(同文件 + 同 CWE + 行距 ≤3),若抑制发生在
1103
+ 去重之前,用户抑制掉看得见的那条规则后,被吞掉的同源规则会顶上来——实测
1104
+ ``exec`` 被 AST 的 ``SEC-002-DANGEROUS-EVAL`` 与多语言的 ``SEC-EVAL-001``
1105
+ 双报,注释只写前者时总数与 critical 纹丝不动,等于抑制静默失效。
1106
+
1107
+ 放在这里还有一个好处:抑制口径对 AST / 多语言 / 外部工具一视同仁,不再
1108
+ 取决于各扫描器是否记得自己调一次判定。
1109
+
1110
+ 匹配时取 ``{rule_id} ∪ merged_rule_ids``:去重把同源的另一条规则(如
1111
+ ``SEC-CMD-001``)并进了代表条目,它仍是规则目录里的正式编号,按它写抑制
1112
+ 必须同样生效,否则「照文档写注释 → 静默无效果」。
1113
+ """
1114
+ cache: dict[str, dict[int, set[str]]] = {}
1115
+ kept: list[dict[str, Any]] = []
1116
+ suppressed = 0
1117
+ for item in findings:
1118
+ rel = str(item.get("file") or "")
1119
+ try:
1120
+ lineno = int(item.get("line") or 0)
1121
+ except (TypeError, ValueError):
1122
+ lineno = 0
1123
+ if not rel or lineno <= 0:
1124
+ kept.append(item)
1125
+ continue
1126
+ if rel not in cache:
1127
+ lines = _finding_source_lines(root, rel)
1128
+ cache[rel] = extract_suppressions(lines) if lines is not None else {}
1129
+ rule_ids = {str(item.get("rule_id") or "")}
1130
+ rule_ids.update(str(rule) for rule in (item.get("merged_rule_ids") or ()))
1131
+ rule_ids.discard("")
1132
+ if any(is_suppressed(cache[rel], lineno, rule) for rule in rule_ids):
1133
+ suppressed += 1
1134
+ continue
1135
+ kept.append(item)
1136
+ # ``merged_rule_ids`` 只是抑制判定的中间产物(去重时记下的同源规则身份),
1137
+ # 不是缺陷本身的属性:它不参与指纹/SARIF,留在输出里会变成别人依赖的隐式
1138
+ # 契约,把去重判据锁死。判定用完即摘。
1139
+ for item in kept:
1140
+ item.pop("merged_rule_ids", None)
1141
+ return kept, suppressed
1142
+
1143
+
1144
+ def _dedupe_cross_tool(findings: list[dict[str, Any]]) -> list[dict[str, Any]]:
1145
+ """合并不同扫描器对同一处缺陷的重复命中(同文件 + 同 CWE + 行号相近)。
1146
+
1147
+ 合并时把被吞掉的 ``rule_id`` 记进代表条目的 ``merged_rule_ids``:规则目录里
1148
+ 的正式编号(如 ``SEC-CMD-001``)与去重后输出的编号(``SEC-001-OS-SYSTEM``)
1149
+ 不是同一个,用户照文档写抑制注释时必须同样生效,否则抑制静默失效。只在
1150
+ 真的合并了**不同** ``rule_id`` 时才写这个字段,代表条目自身的 ``rule_id``
1151
+ 与输出口径保持不变。
1152
+ """
1153
+ kept: list[dict[str, Any]] = []
1154
+ seen: list[tuple[str, str, str, int]] = []
1155
+ for item in findings:
1156
+ path = str(item.get("file") or "")
1157
+ cwe = _cwe_head(item.get("cwe"))
1158
+ rule = str(item.get("rule_id") or "")
1159
+ try:
1160
+ line = int(item.get("line") or 0)
1161
+ except (TypeError, ValueError):
1162
+ line = 0
1163
+ duplicate_of = -1
1164
+ if path and cwe:
1165
+ for index, (seen_path, seen_cwe, seen_rule, seen_line) in enumerate(seen):
1166
+ # 只有**不同规则**命中同一处才算跨工具重复:同一条规则在相邻
1167
+ # 两行命中是两处真实缺陷(实测 src/config.py:5 与 :6 是两个
1168
+ # 独立的硬编码凭据),不能被合并掉。
1169
+ if (seen_path == path and seen_cwe == cwe
1170
+ and seen_rule != rule and abs(seen_line - line) <= 3):
1171
+ duplicate_of = index
1172
+ break
1173
+ if duplicate_of >= 0:
1174
+ # ``kept`` 与 ``seen`` 同步追加、从不删除,索引一一对应。
1175
+ representative = kept[duplicate_of]
1176
+ merged = representative.setdefault("merged_rule_ids", [])
1177
+ if rule and rule not in merged and rule != representative.get("rule_id"):
1178
+ merged.append(rule)
1179
+ continue
1180
+ seen.append((path, cwe, rule, line))
1181
+ kept.append(item)
1182
+ return kept
1183
+
1184
+
1185
+ def run_scan(
1186
+ root: Path,
1187
+ tools: str = "auto",
1188
+ baseline: Path | None = None,
1189
+ write_baseline: Path | None = None,
1190
+ include_sca: bool = True,
1191
+ deadline_seconds: float | None = None,
1192
+ ) -> dict[str, Any]:
1193
+ """执行一次 SAST 扫描。
1194
+
1195
+ ``deadline_seconds`` 给出**整轮扫描的总墙钟预算**(None = 不限)。预算只约束
1196
+ 「是否还允许启动下一个外部工具」以及每个外部子进程的 ``timeout``:内建
1197
+ AST/multilang/SCA 阶段是纯进程内计算,不设预算;外部 semgrep/bandit 一旦
1198
+ 剩余预算不足(<=0.5s)就跳过并标记 ``status=DEGRADED`` +
1199
+ ``budget_exhausted=True``,绝不静默返回 ``COMPLETED`` 冒充完整扫描。
1200
+ """
1201
+ root = root.resolve()
1202
+ # 忽略规格按本次调用的 root 加载一次,整轮扫描内复用:不同 --root 的调用
1203
+ # 各拿各的 ``.bugxignore``,不会因进程内复用而串味。
1204
+ ignore = PathIgnoreSpec.load(root)
1205
+ findings: list[dict[str, Any]] = []
1206
+ file_stats: dict[str, Any] = {}
1207
+ used_tools: list[str] = []
1208
+ started_at = time.monotonic()
1209
+ deadline = (
1210
+ None if deadline_seconds is None else started_at + max(0.0, float(deadline_seconds))
1211
+ )
1212
+ budget_exhausted = False
1213
+
1214
+ def _remaining() -> float | None:
1215
+ if deadline is None:
1216
+ return None
1217
+ return deadline - time.monotonic()
1218
+
1219
+ # 1. 执行 Python 原生 AST 扫描 (保持向前兼容)
1220
+ builtin_py_results = scan_source_ast(root, stats=file_stats, ignore=ignore)
1221
+ findings.extend(builtin_py_results)
1222
+ used_tools.append("builtin-ast")
1223
+
1224
+ # 2. 执行多语言通用结构化模式扫描 (Go, Java, JS/TS, Rust, C/C++, PHP 等)
1225
+ multilang_results = scan_multilang_sources(root, stats=file_stats, ignore=ignore)
1226
+ if multilang_results:
1227
+ findings.extend(multilang_results)
1228
+ used_tools.append("builtin-multilang-sast")
1229
+
1230
+ # 3. 执行多语言依赖供应链分析 (SCA)
1231
+ if include_sca:
1232
+ sca = SCAScanner()
1233
+ # ``SCAScanner`` 自带清单枚举(另一个模块,本次不动),这里按同一份
1234
+ # ``PathIgnoreSpec`` 收口:被忽略的清单不产生 finding。清单解析是毫秒级,
1235
+ # 真正省时间的是上面两条 AST/多语言枚举路径。
1236
+ sca_results = [
1237
+ item for item in sca.scan_project(root)
1238
+ if not ignore.matches(item.get("file", ""))
1239
+ ]
1240
+ if sca_results:
1241
+ findings.extend(sca_results)
1242
+ used_tools.append("builtin-sca")
1243
+
1244
+ # 4. 外部 Native 工具加速通道(若存在且被允许)
1245
+ allow_external = os.environ.get("BUGX_DISABLE_EXTERNAL_SAST") != "1"
1246
+ if allow_external and tools in {"auto", "semgrep"} and shutil.which(
1247
+ "semgrep", path=_probe_environment().get("PATH")
1248
+ ):
1249
+ remaining = _remaining()
1250
+ if remaining is not None and remaining <= 0.5:
1251
+ budget_exhausted = True
1252
+ else:
1253
+ semgrep_results = scan_external_semgrep(
1254
+ root, timeout=60.0 if remaining is None else min(60.0, remaining),
1255
+ ignore=ignore,
1256
+ )
1257
+ if semgrep_results:
1258
+ findings.extend(semgrep_results)
1259
+ used_tools.append("semgrep")
1260
+
1261
+ if allow_external and tools in {"auto", "bandit"} and shutil.which(
1262
+ "bandit", path=_probe_environment().get("PATH")
1263
+ ):
1264
+ remaining = _remaining()
1265
+ if remaining is not None and remaining <= 0.5:
1266
+ budget_exhausted = True
1267
+ else:
1268
+ bandit_results = scan_external_bandit(
1269
+ root, timeout=60.0 if remaining is None else min(60.0, remaining),
1270
+ ignore=ignore,
1271
+ )
1272
+ if bandit_results:
1273
+ findings.extend(bandit_results)
1274
+ used_tools.append("bandit")
1275
+
1276
+ # 跨工具去重:内建 AST 与 semgrep/bandit 会独立命中同一处缺陷(实测
1277
+ # ``eval`` 在 src/evals.py:11 被内建与 semgrep 各报一次,``shell=True``
1278
+ # 被内建报在 11 行、semgrep 报在 12 行)。不去重时报告会把一个漏洞
1279
+ # 计入两条发现、双倍抬升严重度计数。判据是「同一文件 + 同一 CWE +
1280
+ # 行号相近(<=3 行)」,保留首个(内建优先,字段最全)。
1281
+ findings = _dedupe_cross_tool(findings)
1282
+
1283
+ # 行级抑制在**去重之后**统一执行(唯一应用点):先合并同源重复,再按
1284
+ # 「行 + 规则名」压制去重后的代表条目,被吞掉的同源规则不会顶上来。
1285
+ findings, suppressed_by_comment = _apply_suppressions(root, findings)
1286
+ file_stats["suppressed"] = suppressed_by_comment
1287
+
1288
+ # 排序:按严重度及路径排序
1289
+ findings.sort(key=lambda x: (_SEVERITY_RANK.get(x.get("severity", "medium"), 2), x.get("file", ""), x.get("line", 0)))
1290
+
1291
+ # 保存基线
1292
+ if write_baseline:
1293
+ save_baseline(findings, write_baseline)
1294
+
1295
+ # 过滤基线
1296
+ suppressed_baseline = 0
1297
+ if baseline:
1298
+ findings, suppressed_baseline = apply_baseline_filter(findings, baseline)
1299
+
1300
+ # 逐文件跳过(含解析失败)的结构化收据:``scanned_files`` 只说明「成功扫了
1301
+ # 多少」,没有这两个字段时「解析失败漏扫」与「文件无缺陷」不可区分(F-207)。
1302
+ skipped_files = _merge_skipped(file_stats.get("skipped_files") or [])
1303
+ parse_errors = sum(
1304
+ 1 for item in skipped_files if item.get("reason") in _PARSE_FAILURE_REASONS
1305
+ )
1306
+ skipped_reasons: dict[str, int] = {}
1307
+ for item in skipped_files:
1308
+ reason = str(item.get("reason"))
1309
+ skipped_reasons[reason] = skipped_reasons.get(reason, 0) + 1
1310
+
1311
+ return {
1312
+ "schema_version": 2,
1313
+ "status": "DEGRADED" if budget_exhausted else "COMPLETED",
1314
+ "root": str(root),
1315
+ # 报告层需要「扫了多少文件」才能说清楚覆盖范围。此前收据不报这个数,
1316
+ # 调用方只能用命中数顶替,把「命中数」当成「暴露面总量」呈现。
1317
+ "scanned_files": int(file_stats.get("files", 0)),
1318
+ # 解析失败/读取失败的文件数与明细:``reason`` 区分 syntax_error /
1319
+ # parse_error / unreadable / scanner_error,``file``+``line``+``col``
1320
+ # 给出定位,报告层不必再从日志里反推漏扫了什么。
1321
+ "parse_errors": parse_errors,
1322
+ "skipped_files": skipped_files,
1323
+ "skipped_reasons": skipped_reasons,
1324
+ # 路径级忽略是「为什么少扫了」的可解释证据:报告层不该只能看到变小的
1325
+ # 数字却说不清是漏扫还是按规则排除。
1326
+ "path_ignore": ignore.describe(),
1327
+ # 被行级抑制压掉的命中数:抑制生效与否必须可观测,否则「写了不生效」
1328
+ # 只能靠人肉复现。
1329
+ "suppressed_findings": int(file_stats.get("suppressed", 0)),
1330
+ "tools_executed": used_tools,
1331
+ "total_findings": len(findings),
1332
+ "suppressed_by_baseline": suppressed_baseline,
1333
+ "budget_exhausted": budget_exhausted,
1334
+ "elapsed_seconds": round(time.monotonic() - started_at, 3),
1335
+ "findings": findings,
1336
+ }
1337
+
1338
+
1339
+ #: 严重度排序权重(0 最严重)。findings 排序与人读摘要共用同一份口径。
1340
+ _SEVERITY_RANK = {"critical": 0, "high": 1, "medium": 2, "low": 3}
1341
+
1342
+ #: 人读输出里「批量命中」的计数阈值:达到该值的规则会得到 --baseline /
1343
+ #: .bugxignore 的可操作提示,而不是让用户逐条复核。
1344
+ _BULK_RULE_THRESHOLD = 20
1345
+
1346
+
1347
+ def _rule_summary(findings: list[dict[str, Any]]) -> list[tuple[str, str, int]]:
1348
+ """按规则聚合 ``(rule_id, 该规则最高严重度, 计数)``。
1349
+
1350
+ 严重度取该规则**所有命中**里的最高值,不是第一条命中的——按严重度排序的
1351
+ 明细里同一条规则可能散落在多行,用首条会把 306 条 low 的批量规则和 3 条
1352
+ high 的规则显示成同一档。
1353
+ 排序:最高严重度从高到低,同档按计数从多到少,再按 rule_id 兜底稳定。
1354
+ """
1355
+ counts: collections.Counter[str] = collections.Counter()
1356
+ severities: dict[str, str] = {}
1357
+ for item in findings:
1358
+ rule = str(item.get("rule_id") or "")
1359
+ if not rule:
1360
+ continue
1361
+ counts[rule] += 1
1362
+ severity = str(item.get("severity") or "medium").lower()
1363
+ current = severities.get(rule)
1364
+ if current is None or _SEVERITY_RANK.get(severity, 2) < _SEVERITY_RANK.get(current, 2):
1365
+ severities[rule] = severity
1366
+ rows = [(rule, severities[rule], count) for rule, count in counts.items()]
1367
+ rows.sort(key=lambda row: (_SEVERITY_RANK.get(row[1], 2), -row[2], row[0]))
1368
+ return rows
1369
+
1370
+
1371
+ def _print_rule_summary(rows: list[tuple[str, str, int]], total: int) -> None:
1372
+ """打印规则级摘要(只走人读输出,``--json`` / ``--sarif`` 不经过这里)。"""
1373
+ rule_width = max(len(rule) for rule, _, _ in rows)
1374
+ severity_width = max(len(severity) for _, severity, _ in rows) + 2 # 含方括号
1375
+ print(f" 规则摘要({len(rows)} 条规则 / {total} 项,按最高严重度排序):")
1376
+ for rule, severity, count in rows:
1377
+ tag = f"[{severity.upper()}]".ljust(severity_width)
1378
+ print(f" {tag}{rule.ljust(rule_width)} {count}")
1379
+
1380
+
1381
+ def main(argv: list[str] | None = None) -> int:
1382
+ parser = argparse.ArgumentParser(description=__doc__)
1383
+ parser.add_argument("command", choices=("check", "status", "scan"), nargs="?", default="check")
1384
+ parser.add_argument("--root", type=Path, default=Path.cwd())
1385
+ parser.add_argument("--json", action="store_true")
1386
+ parser.add_argument("--sarif", action="store_true", help="输出 OASIS SARIF v2.1.0 格式")
1387
+ parser.add_argument("--strict", action="store_true")
1388
+ parser.add_argument(
1389
+ "--allow-degraded", action="store_true",
1390
+ help="明确允许使用回退方案;否则 DEGRADED 返回 2,要求调用方先取得用户决策",
1391
+ )
1392
+ parser.add_argument("--tools", choices=("auto", "builtin", "semgrep"), default="auto", help="指定扫描使用的工具")
1393
+ parser.add_argument("--baseline", type=Path, default=None, help="从已有基线快照过滤已知历史问题")
1394
+ parser.add_argument("--write-baseline", type=Path, default=None, help="将当前扫描结果持久化为基线快照")
1395
+ args = parser.parse_args(argv)
1396
+
1397
+ if args.command == "scan":
1398
+ scan_res = run_scan(
1399
+ args.root,
1400
+ tools=args.tools,
1401
+ baseline=args.baseline,
1402
+ write_baseline=args.write_baseline,
1403
+ )
1404
+ if args.sarif:
1405
+ sarif_doc = export_to_sarif(scan_res)
1406
+ print(json.dumps(sarif_doc, ensure_ascii=False, indent=2))
1407
+ elif args.json:
1408
+ print(json.dumps(scan_res, ensure_ascii=False, indent=2))
1409
+ else:
1410
+ print(f"[SAST Scan] 执行完成(工具链: {', '.join(scan_res['tools_executed'])}),发现 {scan_res['total_findings']} 个候选漏洞:")
1411
+ if scan_res.get("parse_errors"):
1412
+ reasons = "、".join(
1413
+ f"{reason}×{count}"
1414
+ for reason, count in sorted((scan_res.get("skipped_reasons") or {}).items())
1415
+ )
1416
+ print(
1417
+ f" ⚠️ {scan_res['parse_errors']} 个文件因解析失败被跳过"
1418
+ f"({reasons}),其 AST 级规则未覆盖;明细见 --json 的 skipped_files"
1419
+ )
1420
+ if scan_res.get("suppressed_by_baseline", 0) > 0:
1421
+ print(f" ℹ️ 已基于 Baseline 过滤 {scan_res['suppressed_by_baseline']} 个已知历史问题")
1422
+ truncated = scan_res["total_findings"] > 25
1423
+ rule_rows = _rule_summary(scan_res["findings"])
1424
+ # 摘要只在明细确实被截断时打:小规模扫描打摘要等于把明细抄一遍。
1425
+ if truncated:
1426
+ _print_rule_summary(rule_rows, scan_res["total_findings"])
1427
+ for idx, item in enumerate(scan_res["findings"][:25], 1):
1428
+ cwe_tag = f"[{item.get('cwe', '')}] " if item.get('cwe') else ""
1429
+ print(f" #{idx} [{item['severity'].upper()}] {item['file']}:{item['line']} - {cwe_tag}{item['rule_id']}: {item['message']}")
1430
+ if truncated:
1431
+ print(f" ... 以及另外 {scan_res['total_findings'] - 25} 项(使用 --json 或 --sarif 查看全量)")
1432
+ # 批量命中给可操作出口:这类项逐条复核没有意义,应当固化基线或
1433
+ # 按路径排除。按计数判,不认规则名。
1434
+ bulk = [(rule, count) for rule, _, count in rule_rows if count >= _BULK_RULE_THRESHOLD]
1435
+ if bulk:
1436
+ names = "、".join(f"{rule}({count} 项)" for rule, count in bulk)
1437
+ print(
1438
+ f" 提示:{names}属于批量命中(≥{_BULK_RULE_THRESHOLD} 项),"
1439
+ "建议用 --baseline 固化历史,或用 .bugxignore 排除整类路径,而不是逐条复核。"
1440
+ )
1441
+ return 0
1442
+
1443
+ report = inspect(args.root)
1444
+ print_report(report, args.json)
1445
+ if report["status"] == "READY":
1446
+ return 0
1447
+ if not args.json and not args.allow_degraded and not args.strict:
1448
+ print(" ⏸ 当前仅完成探测,等待用户明确允许回退或配置工具;不会自动进入下一步。")
1449
+ if args.strict:
1450
+ return 1
1451
+ return 0 if args.allow_degraded else 2
1452
+
1453
+
1454
+ def is_available() -> tuple[bool, str]:
1455
+ """降级契约:机械探活外部 SAST 工具是否在 PATH(零子进程 which)。
1456
+
1457
+ 缺失不阻断:本模块架构契约是非侵入式零依赖,外部工具只做加速通道;
1458
+ 但调用方必须据此走 ``run_static_degraded`` 显式标记降级扫描,禁止把
1459
+ 纯内置引擎扫描伪装成完整外部工具链扫描。
1460
+ """
1461
+ environment = _probe_environment()
1462
+ path = environment.get("PATH")
1463
+ found = [name for name in ("semgrep", "codeql", "trivy", "bandit") if shutil.which(name, path=path)]
1464
+ if not found:
1465
+ return False, "无外部 SAST 工具(semgrep/codeql/trivy/bandit);内置多语言引擎兜底"
1466
+ return True, f"外部工具: {', '.join(found)}"
1467
+
1468
+
1469
+ def run_static_degraded(root: Path, *, deadline_seconds: float | None = None) -> dict:
1470
+ """降级契约:仅执行内置 AST/多语言/SCA 阶段,显式标记降级扫描。
1471
+
1472
+ 输出与成功路径(``run_scan`` 的 ``status="COMPLETED"`` 完整工具链扫描)
1473
+ 字段级可区分:``status="degraded"`` + ``degraded=True`` + ``degraded_reason``;
1474
+ ``tools="builtin"`` 硬性跳过全部外部工具通道,绝不静默混入外部结果。
1475
+ """
1476
+ available, availability_detail = is_available()
1477
+ result = run_scan(root, tools="builtin", deadline_seconds=deadline_seconds)
1478
+ return {
1479
+ "schema_version": result["schema_version"],
1480
+ "success": True,
1481
+ "status": "degraded",
1482
+ "degraded": True,
1483
+ "degraded_reason": (
1484
+ "static_mode_forced" if available else "external_sast_tools_unavailable"
1485
+ ),
1486
+ "probe_mode": "static_degraded",
1487
+ "root": result["root"],
1488
+ "scan_status": result["status"],
1489
+ "scanned_files": result["scanned_files"],
1490
+ "parse_errors": result["parse_errors"],
1491
+ "skipped_files": result["skipped_files"],
1492
+ "skipped_reasons": result["skipped_reasons"],
1493
+ "tools_executed": result["tools_executed"],
1494
+ "total_findings": result["total_findings"],
1495
+ "suppressed_by_baseline": result["suppressed_by_baseline"],
1496
+ "findings": result["findings"],
1497
+ "evidence": {
1498
+ "availability_detail": availability_detail,
1499
+ "external_tools_skipped": ["semgrep", "bandit", "codeql", "trivy"],
1500
+ },
1501
+ "metadata": {
1502
+ "degraded_mode": "builtin_engine_only",
1503
+ "external_channels_executed": False,
1504
+ "fallback": "外部 SAST 工具缺失时由内置多语言引擎完成扫描;加速通道缺失需在准备记录留痕",
1505
+ },
1506
+ }
1507
+
1508
+
1509
+ if __name__ == "__main__":
1510
+ raise SystemExit(main())