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,1720 @@
1
+ #!/usr/bin/env python3
2
+ """Lightweight, bounded code scale, complexity & risk analyzer for BugX (DOC-058).
3
+
4
+ Provides deterministic line-of-code (SLOC), comment, docstring, blank line,
5
+ language breakdown, module breakdown, test-to-code ratio, scale estimation,
6
+ cyclomatic complexity, God module/function detection, sensitive sinks scanning,
7
+ and intrinsic risk scoring using purely Python standard library primitives.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import ast
13
+ from collections import Counter, defaultdict
14
+ import hashlib
15
+ import io
16
+ import math
17
+ import os
18
+ import re
19
+ import tokenize
20
+ from pathlib import Path
21
+ from typing import Any, Iterable, Mapping, Sequence
22
+
23
+ try:
24
+ from core.planning.dynamic_flow_analyzer import DynamicFlowAnalyzer, FRAMEWORK_SOURCES
25
+ except ImportError:
26
+ DynamicFlowAnalyzer = None
27
+ FRAMEWORK_SOURCES = {}
28
+
29
+ LANGUAGE_BY_EXTENSION: dict[str, str] = {
30
+ ".py": "python", ".pyw": "python", ".pyi": "python",
31
+ ".js": "javascript", ".jsx": "javascript", ".mjs": "javascript", ".cjs": "javascript",
32
+ ".ts": "typescript", ".tsx": "typescript", ".mts": "typescript", ".cts": "typescript",
33
+ ".go": "go",
34
+ ".java": "java",
35
+ ".kt": "kotlin", ".kts": "kotlin",
36
+ ".rs": "rust",
37
+ ".c": "c", ".h": "c",
38
+ ".cpp": "cpp", ".cc": "cpp", ".cxx": "cpp", ".hpp": "cpp", ".hh": "cpp",
39
+ ".cs": "csharp",
40
+ ".swift": "swift",
41
+ ".sh": "shell", ".bash": "shell", ".zsh": "shell",
42
+ ".rb": "ruby",
43
+ ".php": "php",
44
+ ".sql": "sql",
45
+ ".vue": "vue",
46
+ ".svelte": "svelte",
47
+ ".html": "html", ".htm": "html",
48
+ ".css": "css", ".scss": "scss", ".less": "less",
49
+ ".dart": "dart",
50
+ ".lua": "lua",
51
+ ".r": "r",
52
+ ".sol": "solidity",
53
+ ".proto": "protobuf",
54
+ ".json": "json",
55
+ ".yaml": "yaml", ".yml": "yaml",
56
+ ".toml": "toml",
57
+ ".xml": "xml",
58
+ ".md": "markdown",
59
+ }
60
+
61
+ _CODE_LANGUAGES = {
62
+ "python", "javascript", "typescript", "go", "java", "kotlin", "rust",
63
+ "c", "cpp", "csharp", "swift", "shell", "ruby", "php", "sql", "vue",
64
+ "svelte", "dart", "lua", "r", "solidity", "protobuf",
65
+ }
66
+
67
+ _TEST_DIR_PATTERNS = {"/test/", "/tests/", "/__tests__/", "/spec/", "/specs/", "/testing/", "/e2e/"}
68
+
69
+ _TEST_FILE_PREFIXES = ("test_", "spec_")
70
+ _TEST_FILE_SUFFIXES = (
71
+ "_test.py", "_spec.py",
72
+ "_test.go",
73
+ ".test.js", ".spec.js", ".test.jsx", ".spec.jsx",
74
+ ".test.ts", ".spec.ts", ".test.tsx", ".spec.tsx",
75
+ "test.js", "spec.js", "test.ts", "spec.ts",
76
+ "test.py",
77
+ "test.java", "tests.java", "test.kt", "tests.kt",
78
+ )
79
+
80
+ _SENSITIVE_SINKS = {
81
+ "command_exec": re.compile(r"\b(exec|eval|system|popen|subprocess|spawn|child_process|Runtime\.getRuntime|ProcessBuilder)\b"),
82
+ "dynamic_sql": re.compile(r"(?i)\b(execute|query|raw_query|rawQuery)\s*\(\s*(?:f['\"]|['\"].*?(?:%s|\?|\$\d|\{\w+\}))"),
83
+ "unsafe_deserial": re.compile(r"\b(pickle\.loads?|yaml\.load|Marshal\.load|unserialize|readObject)\b"),
84
+ "path_traversal": re.compile(r"\b(extractall|readFile|readFileSync|open)\s*\([^)]*(?:\.\./|\.\.\\)"),
85
+ "weak_crypto": re.compile(r"\b(md5|sha1|DES|RC4)\b"),
86
+ }
87
+
88
+ _C_BRANCH_RE = re.compile(r"\b(if|else\s+if|for|while|switch|case|catch)\b|&&|\|\||\?")
89
+ _C_FUNC_RE = re.compile(r"\b(function|func|fn)\b|=>|\b(?:public|private|protected|static|\w+)\s+\w+\s*\([^)]*\)\s*\{")
90
+ _C_CLASS_RE = re.compile(r"\b(class|struct|interface|enum)\b")
91
+
92
+
93
+ def is_test_file(rel_path: str) -> bool:
94
+ """Deterministic predicate to classify whether a file belongs to automated test suites."""
95
+ norm = "/" + rel_path.replace("\\", "/").strip("/").casefold()
96
+ if any(p in norm for p in _TEST_DIR_PATTERNS):
97
+ return True
98
+ filename = os.path.basename(norm)
99
+ if any(filename.startswith(p) for p in _TEST_FILE_PREFIXES):
100
+ return True
101
+ if any(filename.endswith(s) for s in _TEST_FILE_SUFFIXES):
102
+ return True
103
+ return False
104
+
105
+
106
+ def _count_python(raw_bytes: bytes) -> tuple[int, int, int, int, int]:
107
+ """Tokenize-assisted counter for Python files: (total, blank, comments, docstrings, sloc)."""
108
+ lines = raw_bytes.decode("utf-8", errors="ignore").splitlines()
109
+ total = len(lines)
110
+ blank = sum(1 for l in lines if not l.strip())
111
+
112
+ comment_lines: set[int] = set()
113
+ docstring_lines: set[int] = set()
114
+ code_lines: set[int] = set()
115
+
116
+ try:
117
+ tokens = list(tokenize.tokenize(io.BytesIO(raw_bytes).readline))
118
+ prev_tok = None
119
+ for tok in tokens:
120
+ tok_type, _, (srow, _), (erow, _), _ = tok
121
+ if tok_type == tokenize.COMMENT:
122
+ comment_lines.add(srow)
123
+ elif tok_type == tokenize.STRING:
124
+ if prev_tok is None or prev_tok.type in (
125
+ tokenize.INDENT, tokenize.NEWLINE, tokenize.NL, tokenize.ENCODING
126
+ ):
127
+ for r in range(srow, erow + 1):
128
+ docstring_lines.add(r)
129
+ else:
130
+ for r in range(srow, erow + 1):
131
+ code_lines.add(r)
132
+ elif tok_type not in (
133
+ tokenize.NL, tokenize.NEWLINE, tokenize.INDENT, tokenize.DEDENT,
134
+ tokenize.ENCODING, tokenize.ENDMARKER
135
+ ):
136
+ for r in range(srow, erow + 1):
137
+ code_lines.add(r)
138
+ if tok_type not in (tokenize.NL, tokenize.COMMENT, tokenize.ENCODING):
139
+ prev_tok = tok
140
+ except Exception:
141
+ c = 0
142
+ for l in lines:
143
+ s = l.strip()
144
+ if s.startswith("#"):
145
+ c += 1
146
+ sloc = max(0, total - blank - c)
147
+ return total, blank, c, 0, sloc
148
+
149
+ pure_comments = len(comment_lines - code_lines)
150
+ pure_docstrings = len(docstring_lines - code_lines)
151
+ sloc = len(code_lines)
152
+ return total, blank, pure_comments, pure_docstrings, sloc
153
+
154
+
155
+ def _count_c_family(lines: list[str]) -> tuple[int, int, int, int, int]:
156
+ """Line scanner for C-style comments (// and /* */): C, C++, Go, Java, TS, JS, Rust, C#, Swift."""
157
+ total = len(lines)
158
+ blank = 0
159
+ comment = 0
160
+ code = 0
161
+ in_block = False
162
+
163
+ for line in lines:
164
+ s = line.strip()
165
+ if not s:
166
+ blank += 1
167
+ continue
168
+ if in_block:
169
+ comment += 1
170
+ if "*/" in s:
171
+ in_block = False
172
+ after = s.split("*/", 1)[1].strip()
173
+ if after and not after.startswith("//"):
174
+ code += 1
175
+ continue
176
+ if s.startswith("/*"):
177
+ comment += 1
178
+ if "*/" not in s:
179
+ in_block = True
180
+ continue
181
+ if s.startswith("//"):
182
+ comment += 1
183
+ continue
184
+ code += 1
185
+ if "/*" in s and "*/" not in s:
186
+ in_block = True
187
+
188
+ return total, blank, comment, 0, code
189
+
190
+
191
+ def _count_hash_comment(lines: list[str]) -> tuple[int, int, int, int, int]:
192
+ """Line scanner for hash-based comments (#): Shell, Ruby, YAML, etc."""
193
+ total = len(lines)
194
+ blank = 0
195
+ comment = 0
196
+ code = 0
197
+ for line in lines:
198
+ s = line.strip()
199
+ if not s:
200
+ blank += 1
201
+ elif s.startswith("#"):
202
+ comment += 1
203
+ else:
204
+ code += 1
205
+ return total, blank, comment, 0, code
206
+
207
+
208
+ def _count_generic(lines: list[str]) -> tuple[int, int, int, int, int]:
209
+ """Fallback scanner: count blanks and non-blanks."""
210
+ total = len(lines)
211
+ blank = sum(1 for l in lines if not l.strip())
212
+ code = total - blank
213
+ return total, blank, 0, 0, code
214
+
215
+
216
+ def count_file_lines(
217
+ path: Path | str, language: str, *, raw_bytes: bytes | None = None,
218
+ ) -> tuple[int, int, int, int, int]:
219
+ """Return (total, blank, comments, docstrings, sloc) for a given file.
220
+
221
+ ``raw_bytes`` lets a caller that already read the file (``analyze_codebase``
222
+ does) hand the bytes down instead of triggering a second disk read. When
223
+ it is omitted the file is read from ``path`` exactly as before.
224
+ """
225
+ if raw_bytes is None:
226
+ try:
227
+ raw_bytes = Path(path).read_bytes()
228
+ except OSError:
229
+ return 0, 0, 0, 0, 0
230
+
231
+ if language == "python":
232
+ return _count_python(raw_bytes)
233
+
234
+ lines = raw_bytes.decode("utf-8", errors="ignore").splitlines()
235
+ if language in {
236
+ "javascript", "typescript", "go", "java", "kotlin", "rust",
237
+ "c", "cpp", "csharp", "swift", "vue", "svelte", "dart", "solidity", "protobuf",
238
+ }:
239
+ return _count_c_family(lines)
240
+ elif language in {"shell", "ruby", "yaml", "toml"}:
241
+ return _count_hash_comment(lines)
242
+ else:
243
+ return _count_generic(lines)
244
+
245
+
246
+ def _analyze_python_ast(raw_bytes: bytes | str, sloc: int = 1) -> dict[str, Any]:
247
+ """Extract AST-level complexity, cognitive load, Halstead volume, taints and imports."""
248
+ try:
249
+ tree = ast.parse(raw_bytes)
250
+ except Exception:
251
+ # 解析失败必须可区分(F-RSI-20261115-276):解析器失效/新语法等场景下
252
+ # 返回满分 mi=100.0 会把系统性解析失败伪装成最优健康度。mi 不可信时
253
+ # 返回 None 并携带 parse_status="failed",由调用方与聚合层显式处理。
254
+ return {
255
+ "cc": 1, "cognitive": 0, "max_depth": 1, "functions": 0, "classes": 0,
256
+ "god_functions": 0, "taint_flows": [], "imports": [],
257
+ "maintainability_index": None, "parse_status": "failed",
258
+ }
259
+
260
+ class Visitor(ast.NodeVisitor):
261
+ def __init__(self) -> None:
262
+ self.current_depth = 0
263
+ self.max_d = 0
264
+ self.branches = 0
265
+ self.func_count = 0
266
+ self.class_count = 0
267
+ self.god_funcs = 0
268
+ self.cognitive = 0
269
+ self.nesting = 0
270
+ self.operators: Counter[str] = Counter()
271
+ self.operands: Counter[str] = Counter()
272
+ self.taints: list[dict[str, Any]] = []
273
+ self.critical_sinks: list[dict[str, Any]] = []
274
+ self.mitigations: list[dict[str, Any]] = []
275
+ self.imports: list[str] = []
276
+ self.alias_map: dict[str, str] = {}
277
+ self.local_params: set[str] = set()
278
+ self.tainted_vars: set[str] = set()
279
+ self.taint_kind_by_var: dict[str, str] = {}
280
+ self.current_func_name: str = ""
281
+ self.current_env: dict[str, Any] = {}
282
+
283
+ def visit_Import(self, node: ast.Import) -> None:
284
+ for alias in node.names:
285
+ self.imports.append(alias.name)
286
+ if alias.asname:
287
+ self.alias_map[alias.asname] = alias.name
288
+ self.generic_visit(node)
289
+
290
+ def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
291
+ mod = node.module or ""
292
+ if mod:
293
+ self.imports.append(mod)
294
+ for alias in node.names:
295
+ full_name = f"{mod}.{alias.name}" if mod else alias.name
296
+ target_name = alias.asname or alias.name
297
+ self.alias_map[target_name] = full_name
298
+ if full_name:
299
+ self.imports.append(full_name)
300
+ if alias.name:
301
+ self.imports.append(alias.name)
302
+ self.generic_visit(node)
303
+
304
+ def visit_FunctionDef(self, node: ast.FunctionDef | ast.AsyncFunctionDef) -> None:
305
+ self.func_count += 1
306
+ self.operators[node.__class__.__name__] += 1
307
+ func_span = getattr(node, "end_lineno", node.lineno) - node.lineno + 1
308
+ sub_branches = sum(
309
+ 1 for child in ast.walk(node)
310
+ if isinstance(
311
+ child,
312
+ (
313
+ ast.If, ast.While, ast.For, ast.AsyncFor,
314
+ ast.ExceptHandler, ast.With, ast.AsyncWith, ast.Assert
315
+ ),
316
+ )
317
+ )
318
+ if func_span > 100 or sub_branches > 20:
319
+ self.god_funcs += 1
320
+
321
+ old_params = self.local_params
322
+ old_tainted = set(self.tainted_vars)
323
+ old_func = self.current_func_name
324
+ old_env = self.current_env
325
+ self.current_func_name = node.name
326
+
327
+ # 闭包感知:保留外层自由变量的污点标记,叠加函数入参
328
+ new_params = {a.arg for a in node.args.args}
329
+ self.local_params = new_params
330
+ self.tainted_vars.update(new_params)
331
+
332
+ if DynamicFlowAnalyzer:
333
+ try:
334
+ analyzer = DynamicFlowAnalyzer(language="python")
335
+ self.current_env = analyzer.fold_python_function_scope(node)
336
+ for v in self.current_env.values():
337
+ if getattr(v, "is_tainted", False):
338
+ self.tainted_vars.add(v.name)
339
+ except Exception:
340
+ self.current_env = {}
341
+ else:
342
+ self.current_env = {}
343
+
344
+ self.nesting += 1
345
+ old_d = self.current_depth
346
+ self.current_depth += 1
347
+ if self.current_depth > self.max_d:
348
+ self.max_d = self.current_depth
349
+
350
+ self.generic_visit(node)
351
+
352
+ self.current_depth = old_d
353
+ self.nesting -= 1
354
+ self.local_params = old_params
355
+ self.tainted_vars = old_tainted
356
+ self.current_func_name = old_func
357
+ self.current_env = old_env
358
+
359
+ def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None:
360
+ self.visit_FunctionDef(node)
361
+
362
+ def visit_ClassDef(self, node: ast.ClassDef) -> None:
363
+ self.class_count += 1
364
+ self.operators["ClassDef"] += 1
365
+ old_d = self.current_depth
366
+ self.current_depth += 1
367
+ if self.current_depth > self.max_d:
368
+ self.max_d = self.current_depth
369
+ self.generic_visit(node)
370
+ self.current_depth = old_d
371
+
372
+ def visit_If(self, node: ast.If) -> None:
373
+ self.branches += 1
374
+ self.operators["If"] += 1
375
+ is_elif = getattr(node, "_is_elif", False)
376
+ if is_elif:
377
+ self.cognitive += 1
378
+ else:
379
+ self.cognitive += (1 + self.nesting)
380
+
381
+ old_d = self.current_depth
382
+ self.current_depth += 1
383
+ if self.current_depth > self.max_d:
384
+ self.max_d = self.current_depth
385
+
386
+ if len(node.orelse) == 1 and isinstance(node.orelse[0], ast.If):
387
+ node.orelse[0]._is_elif = True
388
+
389
+ self.nesting += 1
390
+ self.generic_visit(node)
391
+ self.nesting -= 1
392
+ self.current_depth = old_d
393
+
394
+ def visit_While(self, node: ast.While) -> None:
395
+ self.branches += 1
396
+ self.operators["While"] += 1
397
+ self.cognitive += (1 + self.nesting)
398
+ old_d = self.current_depth
399
+ self.current_depth += 1
400
+ if self.current_depth > self.max_d:
401
+ self.max_d = self.current_depth
402
+ self.nesting += 1
403
+ self.generic_visit(node)
404
+ self.nesting -= 1
405
+ self.current_depth = old_d
406
+
407
+ def visit_For(self, node: ast.For | ast.AsyncFor) -> None:
408
+ self.branches += 1
409
+ self.operators[node.__class__.__name__] += 1
410
+ self.cognitive += (1 + self.nesting)
411
+ old_d = self.current_depth
412
+ self.current_depth += 1
413
+ if self.current_depth > self.max_d:
414
+ self.max_d = self.current_depth
415
+ self.nesting += 1
416
+ self.generic_visit(node)
417
+ self.nesting -= 1
418
+ self.current_depth = old_d
419
+
420
+ def visit_AsyncFor(self, node: ast.AsyncFor) -> None:
421
+ self.visit_For(node)
422
+
423
+ def visit_ExceptHandler(self, node: ast.ExceptHandler) -> None:
424
+ self.branches += 1
425
+ self.operators["ExceptHandler"] += 1
426
+ self.cognitive += (1 + self.nesting)
427
+ self.nesting += 1
428
+ self.generic_visit(node)
429
+ self.nesting -= 1
430
+
431
+ def visit_BoolOp(self, node: ast.BoolOp) -> None:
432
+ self.branches += len(node.values) - 1
433
+ self.cognitive += 1
434
+ self.operators[node.op.__class__.__name__] += len(node.values) - 1
435
+ self.generic_visit(node)
436
+
437
+ def visit_Break(self, node: ast.Break) -> None:
438
+ self.cognitive += 1
439
+ self.operators["Break"] += 1
440
+ self.generic_visit(node)
441
+
442
+ def visit_Continue(self, node: ast.Continue) -> None:
443
+ self.cognitive += 1
444
+ self.operators["Continue"] += 1
445
+ self.generic_visit(node)
446
+
447
+ def visit_Assign(self, node: ast.Assign) -> None:
448
+ self.operators["Assign"] += 1
449
+ assigned_tainted = False
450
+ taint_kind = ""
451
+
452
+ # 1. 检查右值是否引入或传递未净化输入
453
+ has_user_input = False
454
+ for child in ast.walk(node.value):
455
+ if isinstance(child, ast.Name):
456
+ if child.id in self.tainted_vars:
457
+ has_user_input = True
458
+ elif child.id in {"argv", "environ", "request", "params", "query", "user_input", "cmd", "filename", "filepath", "sql"}:
459
+ has_user_input = True
460
+ elif isinstance(child, ast.Attribute) and child.attr in {"argv", "environ", "args", "form", "json", "params", "GET", "POST"}:
461
+ has_user_input = True
462
+
463
+ # 2. 局部污点折叠:SQL/命令字符串插值与路径拼接
464
+ if isinstance(node.value, ast.JoinedStr) and has_user_input:
465
+ assigned_tainted = True
466
+ taint_kind = "dynamic_sql"
467
+ elif isinstance(node.value, ast.BinOp) and isinstance(node.value.op, (ast.Add, ast.Mod)) and has_user_input:
468
+ assigned_tainted = True
469
+ taint_kind = "dynamic_sql"
470
+ elif (
471
+ isinstance(node.value, ast.Call)
472
+ and isinstance(node.value.func, ast.Attribute)
473
+ and node.value.func.attr == "join"
474
+ and has_user_input
475
+ ):
476
+ assigned_tainted = True
477
+ taint_kind = "path_traversal"
478
+ elif has_user_input:
479
+ assigned_tainted = True
480
+ taint_kind = "generic_taint"
481
+
482
+ if assigned_tainted:
483
+ for target in node.targets:
484
+ if isinstance(target, ast.Name):
485
+ self.tainted_vars.add(target.id)
486
+ if taint_kind:
487
+ self.taint_kind_by_var[target.id] = taint_kind
488
+
489
+ # 3. 检查防御特征 (如 re.match / SafeLoader / shlex.quote)
490
+ if isinstance(node.value, ast.Call):
491
+ call_func = ""
492
+ if isinstance(node.value.func, ast.Name):
493
+ call_func = node.value.func.id
494
+ elif isinstance(node.value.func, ast.Attribute):
495
+ call_func = node.value.func.attr
496
+ if call_func in {"match", "search", "escape", "quote", "int", "float", "isidentifier"}:
497
+ self.mitigations.append({
498
+ "kind": "validation",
499
+ "func": call_func,
500
+ "line": getattr(node, "lineno", 0),
501
+ })
502
+
503
+ self.generic_visit(node)
504
+
505
+ def visit_Call(self, node: ast.Call) -> None:
506
+ self.operators["Call"] += 1
507
+ func_name = ""
508
+ full_resolved = ""
509
+ has_shell_false = False
510
+
511
+ if isinstance(node.func, ast.Name):
512
+ func_name = node.func.id
513
+ full_resolved = self.alias_map.get(func_name, func_name)
514
+ elif isinstance(node.func, ast.Attribute):
515
+ attr_name = node.func.attr
516
+ val_name = ""
517
+ if isinstance(node.func.value, ast.Name):
518
+ val_name = self.alias_map.get(node.func.value.id, node.func.value.id)
519
+ func_name = attr_name
520
+ full_resolved = f"{val_name}.{attr_name}" if val_name else attr_name
521
+ elif (
522
+ isinstance(node.func, ast.Call)
523
+ and isinstance(node.func.func, ast.Name)
524
+ and node.func.func.id == "getattr"
525
+ ):
526
+ if len(node.func.args) >= 2:
527
+ if isinstance(node.func.args[1], ast.Constant) and isinstance(node.func.args[1].value, str):
528
+ func_name = node.func.args[1].value
529
+ full_resolved = func_name
530
+ elif isinstance(node.func.args[1], ast.Name) and getattr(self, "current_env", {}):
531
+ v_obj = self.current_env.get(node.func.args[1].id)
532
+ if v_obj:
533
+ func_name = getattr(v_obj, "value", "")
534
+ full_resolved = func_name
535
+
536
+ # 1. 绝对高危特征判定 (一票置顶 Sink)
537
+ # 反序列化
538
+ if "pickle.loads" in full_resolved or (full_resolved == "loads" and "pickle" in self.imports):
539
+ self.critical_sinks.append({
540
+ "kind": "rce_deserialization",
541
+ "sink": full_resolved,
542
+ "line": getattr(node, "lineno", 0),
543
+ })
544
+ elif "yaml.load" in full_resolved:
545
+ has_safe_loader = False
546
+ for kw in node.keywords:
547
+ if kw.arg == "Loader":
548
+ kw_val = ast.unparse(kw.value) if hasattr(ast, "unparse") else ""
549
+ if "SafeLoader" in kw_val:
550
+ has_safe_loader = True
551
+ if not has_safe_loader:
552
+ self.critical_sinks.append({
553
+ "kind": "rce_deserialization",
554
+ "sink": "yaml.load",
555
+ "line": getattr(node, "lineno", 0),
556
+ })
557
+ else:
558
+ self.mitigations.append({
559
+ "kind": "safe_deserializer",
560
+ "sink": "yaml.SafeLoader",
561
+ "line": getattr(node, "lineno", 0),
562
+ })
563
+ elif "yaml.safe_load" in full_resolved:
564
+ self.mitigations.append({
565
+ "kind": "safe_deserializer",
566
+ "sink": "yaml.safe_load",
567
+ "line": getattr(node, "lineno", 0),
568
+ })
569
+
570
+ # 命令执行
571
+ if full_resolved in {"os.system", "system", "posix.system"} or (
572
+ full_resolved in {"subprocess.Popen", "Popen", "subprocess.call", "call", "subprocess.run", "run"}
573
+ ):
574
+ has_shell_true = False
575
+ has_shell_false = False
576
+ for kw in node.keywords:
577
+ if kw.arg == "shell":
578
+ if isinstance(kw.value, ast.Constant) and kw.value.value is True:
579
+ has_shell_true = True
580
+ elif isinstance(kw.value, ast.Constant) and kw.value.value is False:
581
+ has_shell_false = True
582
+
583
+ if has_shell_true or full_resolved in {"os.system", "system"}:
584
+ self.critical_sinks.append({
585
+ "kind": "command_injection",
586
+ "sink": full_resolved,
587
+ "line": getattr(node, "lineno", 0),
588
+ })
589
+ elif has_shell_false:
590
+ self.mitigations.append({
591
+ "kind": "safe_subprocess",
592
+ "sink": f"{full_resolved}(shell=False)",
593
+ "line": getattr(node, "lineno", 0),
594
+ })
595
+
596
+ # 2. 污点汇聚流检测 (排除显式 safe_subprocess)
597
+ target_sinks = {
598
+ "system", "popen", "call", "check_call", "check_output", "run",
599
+ "eval", "exec", "loads", "execute", "raw_query", "query",
600
+ "render_template_string", "from_string", "open", "read",
601
+ }
602
+ if not has_shell_false and (func_name.lower() in target_sinks or full_resolved.lower() in target_sinks):
603
+ for a in node.args:
604
+ arg_vars = {child.id for child in ast.walk(a) if isinstance(child, ast.Name)}
605
+ tainted_hits = arg_vars.intersection(self.tainted_vars)
606
+ if tainted_hits or isinstance(a, ast.JoinedStr):
607
+ hits = sorted(tainted_hits) if tainted_hits else ["<f-string>"]
608
+ self.taints.append({
609
+ "func": getattr(self, "current_func_name", "") or "unknown",
610
+ "sink": full_resolved or func_name,
611
+ "source_vars": hits,
612
+ "line": getattr(node, "lineno", 0),
613
+ })
614
+ break
615
+ self.generic_visit(node)
616
+
617
+ def visit_Name(self, node: ast.Name) -> None:
618
+ self.operands[node.id] += 1
619
+ self.generic_visit(node)
620
+
621
+ def visit_Constant(self, node: ast.Constant) -> None:
622
+ self.operands[str(type(node.value))] += 1
623
+ self.generic_visit(node)
624
+
625
+ visitor = Visitor()
626
+ visitor.visit(tree)
627
+
628
+ n1 = len(visitor.operators)
629
+ n2 = len(visitor.operands)
630
+ vocab = max(2, n1 + n2)
631
+ length = max(1, sum(visitor.operators.values()) + sum(visitor.operands.values()))
632
+ halstead_v = length * math.log2(vocab)
633
+
634
+ cc = 1 + visitor.branches
635
+ safe_sloc = max(1, sloc)
636
+ raw_mi = 171.0 - 5.2 * math.log(max(1.0, halstead_v)) - 0.23 * cc - 16.2 * math.log(safe_sloc)
637
+ norm_mi = round(max(0.0, min(100.0, raw_mi * 100.0 / 171.0)), 1)
638
+
639
+ return {
640
+ "cc": cc,
641
+ "cognitive": visitor.cognitive,
642
+ "cognitive_complexity": visitor.cognitive,
643
+ "max_depth": max(1, visitor.max_d),
644
+ "functions": visitor.func_count,
645
+ "classes": visitor.class_count,
646
+ "god_functions": visitor.god_funcs,
647
+ "taint_flows": visitor.taints,
648
+ "critical_sinks": visitor.critical_sinks,
649
+ "mitigations": visitor.mitigations,
650
+ "imports": visitor.imports,
651
+ "halstead_volume": round(halstead_v, 2),
652
+ "maintainability_index": norm_mi,
653
+ "parse_status": "ok",
654
+ }
655
+
656
+
657
+
658
+ def _analyze_c_family_structure(lines: list[str], sloc: int = 1, language: str = "") -> dict[str, Any]:
659
+ """Lexical scanner for branch complexity, cognitive load, indentation depth, functions and classes."""
660
+ branches = 0
661
+ funcs = 0
662
+ classes = 0
663
+ max_depth = 0
664
+ cognitive = 0
665
+ imports: list[str] = []
666
+
667
+ for l in lines:
668
+ s = l.strip()
669
+ if not s or s.startswith(("//", "/*", "*")):
670
+ continue
671
+ leading_spaces = len(l) - len(l.lstrip(" "))
672
+ depth = leading_spaces // 2
673
+ if depth > max_depth:
674
+ max_depth = depth
675
+
676
+ found_branches = len(_C_BRANCH_RE.findall(s))
677
+ branches += found_branches
678
+ if found_branches > 0:
679
+ cognitive += (found_branches + depth)
680
+
681
+ if _C_FUNC_RE.search(s):
682
+ funcs += 1
683
+ if _C_CLASS_RE.search(s):
684
+ classes += 1
685
+
686
+ m_imp = re.search(r"""(?:import|require)\s*\(?['"]([^'"]+)['"]""", s)
687
+ if m_imp:
688
+ imports.append(m_imp.group(1))
689
+
690
+ taints: list[dict[str, Any]] = []
691
+ dynamic_langs = {"javascript", "typescript", "php", "ruby"}
692
+ if language in dynamic_langs:
693
+ try:
694
+ flow_analyzer = DynamicFlowAnalyzer(language=language)
695
+ line_env = flow_analyzer.fold_line_scope(lines)
696
+ tainted_vars = {k: v for k, v in line_env.items() if v.is_tainted}
697
+
698
+ sink_patterns = [
699
+ re.compile(r'\b(eval|exec|execSync|spawn|spawnSync|system|passthru|shell_exec|popen|proc_open)\s*\(([^)]*)\)'),
700
+ re.compile(r'\b(query|execute|rawQuery)\s*\(([^)]*)\)'),
701
+ ]
702
+ for lineno, line in enumerate(lines, 1):
703
+ s = line.strip().split("//")[0].split("#")[0].strip()
704
+ if not s:
705
+ continue
706
+ for pat in sink_patterns:
707
+ m = pat.search(s)
708
+ if m:
709
+ sink_name = m.group(1)
710
+ args_expr = m.group(2) if len(m.groups()) >= 2 else ""
711
+ hit_sources = [
712
+ vname for vname in tainted_vars
713
+ if re.search(rf"(?<![A-Za-z0-9_$]){re.escape(vname)}(?![A-Za-z0-9_$])", args_expr)
714
+ ]
715
+ if not hit_sources and flow_analyzer.has_framework_source(args_expr):
716
+ hit_sources = ["<framework_source>"]
717
+ if hit_sources:
718
+ taints.append({
719
+ "func": "unknown",
720
+ "sink": sink_name,
721
+ "source_vars": hit_sources,
722
+ "line": lineno,
723
+ })
724
+ break
725
+ except Exception:
726
+ taints = []
727
+
728
+ safe_sloc = max(1, sloc)
729
+ cc = 1 + branches
730
+ halstead_v = safe_sloc * 4.5
731
+ raw_mi = 171.0 - 5.2 * math.log(max(1.0, halstead_v)) - 0.23 * cc - 16.2 * math.log(safe_sloc)
732
+ norm_mi = round(max(0.0, min(100.0, raw_mi * 100.0 / 171.0)), 1)
733
+
734
+ return {
735
+ "cc": cc,
736
+ "cognitive": cognitive,
737
+ "cognitive_complexity": cognitive,
738
+ "max_depth": max(1, max_depth),
739
+ "functions": funcs,
740
+ "classes": classes,
741
+ "god_functions": 0,
742
+ "taint_flows": taints,
743
+ "imports": imports,
744
+ "halstead_volume": round(halstead_v, 2),
745
+ "maintainability_index": norm_mi,
746
+ }
747
+
748
+
749
+
750
+ def get_python_non_code_mask(raw_bytes: bytes) -> set[int]:
751
+ """Extract line numbers (1-indexed) of comments and standalone docstrings."""
752
+ mask: set[int] = set()
753
+ try:
754
+ tokens = list(tokenize.tokenize(io.BytesIO(raw_bytes).readline))
755
+ prev_tok = None
756
+ for tok in tokens:
757
+ tok_type, _, (srow, _), (erow, _), _ = tok
758
+ if tok_type == tokenize.COMMENT:
759
+ mask.add(srow)
760
+ elif tok_type == tokenize.STRING:
761
+ if prev_tok is None or prev_tok.type in (
762
+ tokenize.INDENT, tokenize.NEWLINE, tokenize.NL, tokenize.ENCODING
763
+ ):
764
+ for r in range(srow, erow + 1):
765
+ mask.add(r)
766
+ if tok_type not in (tokenize.NL, tokenize.COMMENT, tokenize.ENCODING):
767
+ prev_tok = tok
768
+ except Exception:
769
+ pass
770
+ return mask
771
+
772
+
773
+ def get_c_family_non_code_mask(text: str) -> set[int]:
774
+ """Extract line numbers of comments in C-family / JS / Go source code."""
775
+ non_code_lines: set[int] = set()
776
+ in_block_comment = False
777
+ for idx, line in enumerate(text.splitlines(), 1):
778
+ s = line.strip()
779
+ if in_block_comment:
780
+ non_code_lines.add(idx)
781
+ if "*/" in s:
782
+ in_block_comment = False
783
+ continue
784
+ if s.startswith("/*"):
785
+ non_code_lines.add(idx)
786
+ if "*/" not in s:
787
+ in_block_comment = True
788
+ continue
789
+ if s.startswith(("//", "#", "*")):
790
+ non_code_lines.add(idx)
791
+ return non_code_lines
792
+
793
+
794
+ def scan_sensitive_sinks(
795
+ text: str,
796
+ *,
797
+ non_code_mask: set[int] | None = None,
798
+ ) -> int:
799
+ """Return total count of sensitive sink patterns found in active code (excluding comments/docstrings)."""
800
+ if not text:
801
+ return 0
802
+
803
+ lines = text.splitlines()
804
+ line_offsets = []
805
+ curr = 0
806
+ for l in lines:
807
+ line_offsets.append(curr)
808
+ curr += len(l) + 1
809
+
810
+ import bisect
811
+
812
+ total = 0
813
+ for sink_name, pattern in _SENSITIVE_SINKS.items():
814
+ for m in pattern.finditer(text):
815
+ start_pos = m.start()
816
+ lineno = bisect.bisect_right(line_offsets, start_pos)
817
+ if non_code_mask and lineno in non_code_mask:
818
+ continue
819
+
820
+ matched_text = m.group(0)
821
+ if sink_name == "unsafe_deserial" and "yaml.load" in matched_text:
822
+ line_content = lines[lineno - 1] if 0 <= lineno - 1 < len(lines) else ""
823
+ if "SafeLoader" in line_content or "yaml.safe_load" in line_content:
824
+ continue
825
+
826
+ total += 1
827
+ return total
828
+
829
+
830
+ def calculate_shannon_entropy(text: str) -> float:
831
+ """Calculate Shannon information entropy of a string."""
832
+ if not text:
833
+ return 0.0
834
+ freq = Counter(text)
835
+ length = float(len(text))
836
+ return -sum((c / length) * math.log2(c / length) for c in freq.values())
837
+
838
+
839
+ _SECRET_KEYWORD_RE = re.compile(
840
+ r"(?i)(?:api[_-]?key|secret|token|password|passwd|auth|bearer|credentials|private[_-]?key)"
841
+ )
842
+ _SECRET_VALUE_RE = re.compile(
843
+ r"""['"]([a-zA-Z0-9_\-\.\$\/+=]{20,120})['"]"""
844
+ )
845
+
846
+
847
+ def scan_high_entropy_secrets(text: str) -> list[dict[str, Any]]:
848
+ """Scan text for high-entropy strings and secret patterns."""
849
+ secrets = []
850
+ lines = text.splitlines()
851
+ for idx, line in enumerate(lines, 1):
852
+ s_line = line.strip()
853
+ if not s_line or s_line.startswith(("#", "//", "/*", "*")):
854
+ continue
855
+ has_secret_kw = bool(_SECRET_KEYWORD_RE.search(s_line))
856
+ for m in _SECRET_VALUE_RE.finditer(s_line):
857
+ val = m.group(1)
858
+ if val.startswith(("http://", "https://", "ftp://", "file://")):
859
+ continue
860
+ if val.count("/") >= 3 or val.count("\\") >= 3:
861
+ continue
862
+ if re.match(r"^[0-9a-f]{32,64}$", val):
863
+ continue
864
+ if len(set(val)) <= 8:
865
+ continue
866
+
867
+ ent = calculate_shannon_entropy(val)
868
+ if ent >= 4.3 or (has_secret_kw and ent >= 3.6):
869
+ masked = val[:4] + "****" + val[-4:] if len(val) >= 12 else "****"
870
+ secrets.append({
871
+ "line": idx,
872
+ "entropy": round(ent, 2),
873
+ "masked": masked,
874
+ })
875
+ if len(secrets) >= 5:
876
+ break
877
+ if len(secrets) >= 5:
878
+ break
879
+ return secrets
880
+
881
+
882
+ def analyze_file_risk(
883
+ path: Path | str,
884
+ language: str,
885
+ sloc: int,
886
+ is_test: bool,
887
+ *,
888
+ raw_bytes: bytes | None = None,
889
+ ) -> dict[str, Any]:
890
+ """Extract structural complexity, sensitive sinks, cognitive load and intrinsic risk for a single file.
891
+
892
+ ``raw_bytes`` lets a caller that already read the file hand the bytes down so
893
+ a single analysis pass reads every file at most once; omitting it preserves
894
+ the original single-file behaviour.
895
+ """
896
+ if raw_bytes is None:
897
+ try:
898
+ raw_bytes = Path(path).read_bytes()
899
+ except OSError:
900
+ return {
901
+ "cc": 1, "cognitive": 0, "max_depth": 1, "functions": 0, "classes": 0,
902
+ "god_functions": 0, "god_module": False, "sinks": 0,
903
+ "taint_flows": [], "critical_sinks": [], "mitigations": [], "secrets": [], "imports": [],
904
+ "maintainability_index": None, "parse_status": "unreadable",
905
+ "risk_score": 0.0, "tags": ["unreadable"],
906
+ }
907
+ text = raw_bytes.decode("utf-8", errors="ignore")
908
+
909
+ if language == "python":
910
+ struct = _analyze_python_ast(raw_bytes, sloc=sloc)
911
+ non_code_mask = get_python_non_code_mask(raw_bytes)
912
+ elif language in {
913
+ "javascript", "typescript", "go", "java", "kotlin", "rust",
914
+ "c", "cpp", "csharp", "swift", "vue", "svelte", "dart",
915
+ "php", "ruby",
916
+ }:
917
+ struct = _analyze_c_family_structure(text.splitlines(), sloc=sloc, language=language)
918
+ non_code_mask = get_c_family_non_code_mask(text)
919
+ else:
920
+ struct = {
921
+ "cc": 1, "cognitive": 0, "max_depth": 1, "functions": 0, "classes": 0,
922
+ "god_functions": 0, "taint_flows": [], "critical_sinks": [], "mitigations": [], "imports": [],
923
+ "maintainability_index": None, "parse_status": "not_applicable",
924
+ }
925
+ non_code_mask = set()
926
+
927
+ sinks = scan_sensitive_sinks(text, non_code_mask=non_code_mask)
928
+ secrets = scan_high_entropy_secrets(text) if not is_test else []
929
+ taints = struct.get("taint_flows", [])
930
+ critical_sinks = struct.get("critical_sinks", [])
931
+ mitigations = struct.get("mitigations", [])
932
+ cc = struct.get("cc", 1)
933
+ cognitive = struct.get("cognitive", 0)
934
+ max_depth = struct.get("max_depth", 1)
935
+ mi = struct.get("maintainability_index")
936
+ parse_status = struct.get("parse_status", "ok")
937
+
938
+ # God Module: only for production code
939
+ is_god_module = False
940
+ if not is_test and (sloc > 1500 or cc > 80):
941
+ is_god_module = True
942
+
943
+ tags = []
944
+ if is_god_module:
945
+ tags.append("god-module")
946
+ if struct.get("god_functions", 0) > 0:
947
+ tags.append("god-function")
948
+ if cc > 25:
949
+ tags.append("high-cc")
950
+ if cognitive > 30:
951
+ tags.append("high-cognitive")
952
+ if sinks >= 3:
953
+ tags.append("sensitive-sinks")
954
+ if max_depth >= 5:
955
+ tags.append("deep-nesting")
956
+ if len(taints) > 0:
957
+ tags.append("critical-taint")
958
+ if len(critical_sinks) > 0:
959
+ tags.append("critical-sink")
960
+ if len(mitigations) > 0:
961
+ tags.append("mitigated-control")
962
+ if len(secrets) > 0:
963
+ tags.append("hardcoded-secret")
964
+ if mi is not None and mi < 40.0:
965
+ tags.append("low-maintainability")
966
+ if parse_status == "failed":
967
+ # 解析失败必须出现在标签面(F-RSI-20261115-276):无结构的"满分"伪装
968
+ # 被移除后,文件级降级信号在 hotspots/tags 通道保持可见。
969
+ tags.append("parse-failed")
970
+
971
+ # Composite Risk score calculation (0 ~ 100) - 彻底废除复杂度即风险,确立高危一票置顶
972
+ if len(critical_sinks) > 0 or len(taints) > 0:
973
+ # 基准分直接锁定 80+
974
+ base_score = 80.0 + min(len(critical_sinks) * 5.0 + len(taints) * 5.0, 15.0)
975
+ # 如果存在有效防御且无裸露高危
976
+ if len(mitigations) > 0 and len(critical_sinks) == 0:
977
+ base_score = max(20.0, base_score - len(mitigations) * 30.0)
978
+ else:
979
+ # 无绝对高危 Sink 时,根据结构复杂度与防御进行基准打分,上限压制在 50 分以下
980
+ base_score = min(
981
+ 45.0,
982
+ (cc * 0.2)
983
+ + (cognitive * 0.1)
984
+ + (sinks * 3.0)
985
+ + (len(secrets) * 6.0)
986
+ + (max_depth * 1.5)
987
+ + (10.0 if (mi is not None and mi < 40.0) else 0.0),
988
+ )
989
+
990
+ risk_score = round(min(100.0, max(10.0, base_score)), 1)
991
+
992
+ return {
993
+ "cc": cc,
994
+ "cognitive": cognitive,
995
+ "max_depth": max_depth,
996
+ "functions": struct.get("functions", 0),
997
+ "classes": struct.get("classes", 0),
998
+ "god_functions": struct.get("god_functions", 0),
999
+ "god_module": is_god_module,
1000
+ "sinks": sinks,
1001
+ "taint_flows": taints,
1002
+ "critical_sinks": critical_sinks,
1003
+ "mitigations": mitigations,
1004
+ "secrets": secrets,
1005
+ "imports": struct.get("imports", []),
1006
+ "maintainability_index": mi,
1007
+ "parse_status": parse_status,
1008
+ "risk_score": risk_score,
1009
+ "tags": tags,
1010
+ }
1011
+
1012
+
1013
+ def compute_health_grade(avg_cc: float, god_modules: int, test_ratio: float) -> str:
1014
+ """Deterministic engineering health rating (A / B / C / D)."""
1015
+ if avg_cc <= 8 and god_modules == 0 and test_ratio >= 0.4:
1016
+ return "A"
1017
+ elif avg_cc <= 15 and god_modules <= 2 and test_ratio >= 0.2:
1018
+ return "B"
1019
+ elif avg_cc <= 25 or test_ratio >= 0.1:
1020
+ return "C"
1021
+ else:
1022
+ return "D"
1023
+
1024
+
1025
+ def estimate_scale(sloc: int, primary_lang: str = "unknown") -> dict[str, Any]:
1026
+ """Estimate project scale level, recommended concurrency, and round budget."""
1027
+ if sloc < 5000:
1028
+ level = "micro"
1029
+ concurrency = 1
1030
+ rounds = 1
1031
+ budget = 30000
1032
+ elif sloc < 25000:
1033
+ level = "small"
1034
+ concurrency = 2
1035
+ rounds = 2
1036
+ budget = 80000
1037
+ elif sloc < 100000:
1038
+ level = "medium"
1039
+ concurrency = 3
1040
+ rounds = 3
1041
+ budget = 200000
1042
+ elif sloc < 500000:
1043
+ level = "large"
1044
+ concurrency = 4
1045
+ rounds = 5
1046
+ budget = 500000
1047
+ else:
1048
+ level = "giant"
1049
+ concurrency = 6
1050
+ rounds = 8
1051
+ budget = 1200000
1052
+
1053
+ return {
1054
+ "scale_level": level,
1055
+ "primary_language": primary_lang,
1056
+ "recommended_concurrency": concurrency,
1057
+ "recommended_rounds": rounds,
1058
+ "recommended_token_budget": budget,
1059
+ }
1060
+
1061
+
1062
+ def _window_digest(encoded_window: Sequence[bytes]) -> str:
1063
+ """Stable, collision-resistant digest for one clone-detection window.
1064
+
1065
+ The builtin ``hash()`` of a ``tuple[str, ...]`` is salted per process
1066
+ (``PYTHONHASHSEED``), so clone detection used to drift between runs and was
1067
+ not reproducible. ``blake2b`` is used instead: identical windows always map
1068
+ to the same digest in every process, and distinct windows cannot collide.
1069
+ Each line is length-prefixed so two different line sequences can never
1070
+ encode to the same payload.
1071
+ """
1072
+ hasher = hashlib.blake2b(digest_size=16)
1073
+ for line in encoded_window:
1074
+ hasher.update(len(line).to_bytes(4, "big"))
1075
+ hasher.update(line)
1076
+ return hasher.hexdigest()
1077
+
1078
+
1079
+ def detect_code_duplication(
1080
+ project_root: Path | str,
1081
+ prod_files: list[Any],
1082
+ window_size: int = 8,
1083
+ max_scan_files: int = 150,
1084
+ *,
1085
+ content_cache: Mapping[Path, str] | None = None,
1086
+ ) -> dict[str, Any]:
1087
+ """Detect clone blocks and code duplication ratio using sliding window hashing.
1088
+
1089
+ ``content_cache`` is an optional per-pass mapping of already-decoded file
1090
+ text (see ``analyze_codebase``) so a file is not read a second time just for
1091
+ duplication scanning. A missing entry falls back to reading from disk, so
1092
+ direct callers keep the original behaviour.
1093
+ """
1094
+ root_path = Path(project_root)
1095
+ block_map: dict[str, list[tuple[str, int]]] = defaultdict(list)
1096
+ total_prod_lines = 0
1097
+
1098
+ scan_targets = prod_files[:max_scan_files]
1099
+ for item in scan_targets:
1100
+ if isinstance(item, dict):
1101
+ rel = item.get("rel_path") or item.get("path", "")
1102
+ p = item.get("path")
1103
+ if not isinstance(p, Path):
1104
+ p = root_path / rel
1105
+ elif isinstance(item, (tuple, list)):
1106
+ rel = item[0]
1107
+ p = item[1]
1108
+ if not isinstance(p, Path):
1109
+ p = root_path / rel
1110
+ else:
1111
+ continue
1112
+
1113
+ content = content_cache.get(Path(p)) if content_cache is not None else None
1114
+ if content is None:
1115
+ try:
1116
+ content = p.read_text(encoding="utf-8", errors="ignore")
1117
+ except OSError:
1118
+ continue
1119
+
1120
+ cleaned = []
1121
+ for line in content.splitlines():
1122
+ s = line.strip()
1123
+ if not s or s.startswith(("#", "//", "/*", "*", '"""', "'''")):
1124
+ continue
1125
+ if len(s) < 3 or s in {"{", "}", "(", ")", "[", "]", ":", ";"}:
1126
+ continue
1127
+ cleaned.append(s)
1128
+
1129
+ total_prod_lines += len(cleaned)
1130
+
1131
+ if len(cleaned) >= window_size:
1132
+ encoded = [line.encode("utf-8") for line in cleaned]
1133
+ for i in range(len(cleaned) - window_size + 1):
1134
+ h = _window_digest(encoded[i:i + window_size])
1135
+ block_map[h].append((rel, i))
1136
+
1137
+ duplicated_files: set[str] = set()
1138
+ duplicated_line_count = 0
1139
+ top_clones: list[dict[str, Any]] = []
1140
+
1141
+ for h, occurrences in block_map.items():
1142
+ if len(occurrences) < 2:
1143
+ continue
1144
+ distinct_occurrences = []
1145
+ last_file = ""
1146
+ last_idx = -100
1147
+ for f, idx in occurrences:
1148
+ if f != last_file or (idx - last_idx) >= window_size:
1149
+ distinct_occurrences.append((f, idx))
1150
+ last_file = f
1151
+ last_idx = idx
1152
+
1153
+ if len(distinct_occurrences) >= 2:
1154
+ for f, _ in distinct_occurrences:
1155
+ duplicated_files.add(f)
1156
+ duplicated_line_count += window_size
1157
+ if len(top_clones) < 3:
1158
+ files_involved = sorted(set(f for f, _ in distinct_occurrences))
1159
+ top_clones.append({
1160
+ "files": files_involved[:4],
1161
+ "lines_count": window_size,
1162
+ "occurrences": len(distinct_occurrences),
1163
+ })
1164
+
1165
+ dup_ratio = round(min(100.0, (duplicated_line_count / max(1, total_prod_lines)) * 100.0), 1)
1166
+ return {
1167
+ "duplicated_lines": duplicated_line_count,
1168
+ "duplicate_lines": duplicated_line_count,
1169
+ "duplication_percentage": dup_ratio,
1170
+ "duplication_ratio": dup_ratio,
1171
+ "duplicated_files_count": len(duplicated_files),
1172
+ "top_clones": top_clones,
1173
+ "clone_blocks": top_clones,
1174
+ }
1175
+
1176
+
1177
+ def analyze_architecture_dependencies(
1178
+ arg1: Any,
1179
+ arg2: Any = None,
1180
+ ) -> dict[str, Any]:
1181
+ """Analyze architecture dependency graph, detect circular dependencies via Tarjan SCC, and measure instability."""
1182
+ if arg2 is not None:
1183
+ file_import_map = arg2
1184
+ elif isinstance(arg1, dict):
1185
+ file_import_map = arg1
1186
+ elif isinstance(arg1, list):
1187
+ file_import_map = {}
1188
+ for item in arg1:
1189
+ if isinstance(item, dict):
1190
+ file_import_map[item.get("rel_path") or item.get("module", "")] = item.get("imports", [])
1191
+ else:
1192
+ file_import_map = {}
1193
+
1194
+ all_files = set(file_import_map.keys())
1195
+ mod_to_file: dict[str, str] = {}
1196
+ for f in all_files:
1197
+ no_ext = f.rsplit(".", 1)[0]
1198
+ mod_to_file[no_ext] = f
1199
+ mod_to_file[no_ext.replace("/", ".")] = f
1200
+ mod_to_file[Path(f).name] = f
1201
+ mod_to_file[Path(f).stem] = f
1202
+
1203
+ graph: dict[str, set[str]] = defaultdict(set)
1204
+ in_degrees: Counter[str] = Counter()
1205
+ out_degrees: Counter[str] = Counter()
1206
+
1207
+ for src_file, raw_imports in file_import_map.items():
1208
+ for imp in raw_imports:
1209
+ target = mod_to_file.get(imp)
1210
+ if not target and "/" in imp:
1211
+ target = mod_to_file.get(imp.split("/")[-1])
1212
+ if target and target != src_file and target in all_files:
1213
+ graph[src_file].add(target)
1214
+
1215
+ for src, targets in graph.items():
1216
+ out_degrees[src] += len(targets)
1217
+ for t in targets:
1218
+ in_degrees[t] += 1
1219
+
1220
+ idx = 0
1221
+ indices: dict[str, int] = {}
1222
+ lowlink: dict[str, int] = {}
1223
+ on_stack: set[str] = set()
1224
+ stack: list[str] = []
1225
+ cycles: list[list[str]] = []
1226
+
1227
+ def strongconnect(node: str) -> None:
1228
+ nonlocal idx
1229
+ indices[node] = idx
1230
+ lowlink[node] = idx
1231
+ idx += 1
1232
+ stack.append(node)
1233
+ on_stack.add(node)
1234
+
1235
+ for neighbor in graph.get(node, ()):
1236
+ if neighbor not in indices:
1237
+ strongconnect(neighbor)
1238
+ lowlink[node] = min(lowlink[node], lowlink[neighbor])
1239
+ elif neighbor in on_stack:
1240
+ lowlink[node] = min(lowlink[node], indices[neighbor])
1241
+
1242
+ if lowlink[node] == indices[node]:
1243
+ scc = []
1244
+ while True:
1245
+ w = stack.pop()
1246
+ on_stack.remove(w)
1247
+ scc.append(w)
1248
+ if w == node:
1249
+ break
1250
+ if len(scc) > 1:
1251
+ cycles.append(scc)
1252
+
1253
+ for node in list(all_files):
1254
+ if node not in indices:
1255
+ strongconnect(node)
1256
+
1257
+ cycles.sort(key=len, reverse=True)
1258
+
1259
+ unstable_modules = []
1260
+ module_couplings = []
1261
+ for f in all_files:
1262
+ ca = in_degrees[f]
1263
+ ce = out_degrees[f]
1264
+ instability = round(ce / (ca + ce), 2) if (ca + ce) > 0 else 0.0
1265
+ module_couplings.append({
1266
+ "module": f,
1267
+ "fan_in": ca,
1268
+ "fan_out": ce,
1269
+ "instability": instability,
1270
+ })
1271
+ if (ca + ce) > 0 and instability >= 0.75 and ce >= 2:
1272
+ unstable_modules.append({
1273
+ "file": f,
1274
+ "instability": instability,
1275
+ "fan_in": ca,
1276
+ "fan_out": ce,
1277
+ })
1278
+
1279
+ unstable_modules.sort(key=lambda x: (x["instability"], x["fan_out"]), reverse=True)
1280
+
1281
+ return {
1282
+ "total_cycles": len(cycles),
1283
+ "circular_dependencies_count": len(cycles),
1284
+ "cycles": [c[:6] for c in cycles[:5]],
1285
+ "circular_dependency_cycles": [c[:6] for c in cycles[:5]],
1286
+ "unstable_modules": unstable_modules[:5],
1287
+ "highest_instability_modules": unstable_modules[:5],
1288
+ "module_couplings": module_couplings,
1289
+ "avg_afferent_coupling": round(sum(in_degrees.values()) / max(1, len(all_files)), 1),
1290
+ "avg_efferent_coupling": round(sum(out_degrees.values()) / max(1, len(all_files)), 1),
1291
+ }
1292
+
1293
+
1294
+ def calculate_cocomo_and_debt(
1295
+ sloc: int,
1296
+ god_modules: int = 0,
1297
+ god_functions: int = 0,
1298
+ cycles_count: int = 0,
1299
+ taint_count: int = 0,
1300
+ secrets_count: int = 0,
1301
+ high_cc_count: int = 0,
1302
+ sinks_count: int = 0,
1303
+ duplicate_lines: int = 0,
1304
+ secret_count: int = 0,
1305
+ complex_files_count: int = 0,
1306
+ **kwargs: Any,
1307
+ ) -> dict[str, Any]:
1308
+ """Calculate COCOMO II development baseline and technical debt remediation effort."""
1309
+ eff_secrets = secrets_count or secret_count
1310
+ eff_high_cc = high_cc_count or complex_files_count
1311
+
1312
+ ksloc = sloc / 1000.0
1313
+ effort_pm = max(0.1, round(2.4 * (ksloc ** 1.05), 1))
1314
+ schedule_months = max(0.5, round(2.5 * (effort_pm ** 0.38), 1))
1315
+
1316
+ tech_debt = (
1317
+ (god_modules * 2.0)
1318
+ + (god_functions * 1.5)
1319
+ + (cycles_count * 1.0)
1320
+ + (taint_count * 0.5)
1321
+ + (eff_secrets * 0.5)
1322
+ + (eff_high_cc * 0.3)
1323
+ + (sinks_count * 0.1)
1324
+ + (duplicate_lines * 0.01)
1325
+ )
1326
+ debt_days = round(tech_debt, 1)
1327
+ debt_ratio = min(100.0, round((debt_days / max(1.0, effort_pm * 22.0)) * 100.0, 1))
1328
+
1329
+ debt_breakdown = {
1330
+ "god_modules_debt_days": round(god_modules * 2.0, 1),
1331
+ "god_functions_debt_days": round(god_functions * 1.5, 1),
1332
+ "circular_cycles_debt_days": round(cycles_count * 1.0, 1),
1333
+ "taint_exposure_debt_days": round(taint_count * 0.5, 1),
1334
+ "secret_exposure_debt_days": round(eff_secrets * 0.5, 1),
1335
+ "high_cc_debt_days": round(eff_high_cc * 0.3, 1),
1336
+ "sinks_debt_days": round(sinks_count * 0.1, 1),
1337
+ "duplication_debt_days": round(duplicate_lines * 0.01, 1),
1338
+ }
1339
+
1340
+ return {
1341
+ "effort_person_months": effort_pm,
1342
+ "cocomo_effort_pm": effort_pm,
1343
+ "estimated_schedule_months": schedule_months,
1344
+ "cocomo_schedule_months": schedule_months,
1345
+ "tech_debt_days": debt_days,
1346
+ "tech_debt_ratio_pct": debt_ratio,
1347
+ "tech_debt_ratio": debt_ratio,
1348
+ "debt_breakdown": debt_breakdown,
1349
+ }
1350
+
1351
+
1352
+
1353
+ def analyze_codebase(
1354
+ root: Path | str,
1355
+ files: Sequence[tuple[str, Path, int, str]] | None = None,
1356
+ *,
1357
+ max_files: int = 4000,
1358
+ ) -> dict[str, Any]:
1359
+ """Perform deterministic codebase line, scale, complexity & risk analysis."""
1360
+ project_root = Path(root).resolve()
1361
+
1362
+ if files is None:
1363
+ files_list = []
1364
+ for dirpath, dirnames, filenames in os.walk(project_root, topdown=True):
1365
+ dirnames[:] = [d for d in dirnames if d not in {
1366
+ ".git", ".bugx", ".opencode", ".codex", ".claude", ".cline",
1367
+ ".vscode", ".agents", ".cursor", ".gemini", "node_modules",
1368
+ ".venv", "venv", "__pycache__", "dist", "build", ".idea"
1369
+ } and not d.startswith(".")]
1370
+ for name in filenames:
1371
+ p = Path(dirpath) / name
1372
+ rel = str(p.relative_to(project_root).as_posix())
1373
+ files_list.append((rel, p, p.stat().st_size if p.is_file() else 0, ""))
1374
+ if len(files_list) >= max_files:
1375
+ break
1376
+ if len(files_list) >= max_files:
1377
+ break
1378
+ files = files_list
1379
+
1380
+ lang_stats: dict[str, dict[str, Any]] = {}
1381
+ module_stats: dict[str, dict[str, int]] = {}
1382
+
1383
+ total_files = 0
1384
+ total_lines = 0
1385
+ total_sloc = 0
1386
+ total_comments = 0
1387
+ total_docstrings = 0
1388
+ total_blanks = 0
1389
+
1390
+ code_files = 0
1391
+ code_sloc = 0
1392
+ doc_config_lines = 0
1393
+
1394
+ prod_sloc = 0
1395
+ test_sloc = 0
1396
+ prod_files = 0
1397
+ test_files = 0
1398
+
1399
+ # Risk metrics accumulators
1400
+ total_cc = 0
1401
+ max_cc = 0
1402
+ total_cognitive = 0
1403
+ max_cognitive = 0
1404
+ total_funcs = 0
1405
+ total_classes = 0
1406
+ total_god_funcs = 0
1407
+ total_god_modules = 0
1408
+ total_sinks = 0
1409
+ all_taints: list[dict[str, Any]] = []
1410
+ all_critical_sinks: list[dict[str, Any]] = []
1411
+ all_secrets: list[dict[str, Any]] = []
1412
+ maintainability_scores: list[float] = []
1413
+ maintainability_parse_failed_files = 0
1414
+ file_import_map: dict[str, list[str]] = {}
1415
+ prod_files_list: list[tuple[str, Path, int, str]] = []
1416
+ # Per-pass cache of decoded production source text. ``count_file_lines``,
1417
+ # ``analyze_file_risk`` and ``detect_code_duplication`` used to read every
1418
+ # file separately; the bytes are now read once here and handed down. The
1419
+ # cache lives only for this ``analyze_codebase`` call, so it can never serve
1420
+ # stale content to a later pass over a changed workspace.
1421
+ prod_text_cache: dict[Path, str] = {}
1422
+ hotspots: list[dict[str, Any]] = []
1423
+
1424
+ for rel, abs_path, size, _ in files:
1425
+ ext = Path(rel).suffix.casefold()
1426
+ lang = LANGUAGE_BY_EXTENSION.get(ext)
1427
+ if not lang:
1428
+ continue
1429
+
1430
+ file_path = Path(abs_path)
1431
+ try:
1432
+ raw_bytes = file_path.read_bytes()
1433
+ except OSError:
1434
+ # count_file_lines() reported (0, 0, 0, 0, 0) for unreadable files
1435
+ # and the loop skipped them; keep that outcome without re-reading.
1436
+ continue
1437
+
1438
+ tot, blk, com, doc, sloc = count_file_lines(file_path, lang, raw_bytes=raw_bytes)
1439
+ if tot == 0 and sloc == 0:
1440
+ continue
1441
+
1442
+ total_files += 1
1443
+ total_lines += tot
1444
+ total_sloc += sloc
1445
+ total_comments += com
1446
+ total_docstrings += doc
1447
+ total_blanks += blk
1448
+
1449
+ is_code = lang in _CODE_LANGUAGES
1450
+ is_test = is_test_file(rel)
1451
+
1452
+ if is_code:
1453
+ code_files += 1
1454
+ code_sloc += sloc
1455
+ if is_test:
1456
+ test_sloc += sloc
1457
+ test_files += 1
1458
+ else:
1459
+ prod_sloc += sloc
1460
+ prod_files += 1
1461
+ prod_files_list.append((rel, abs_path, size, ""))
1462
+
1463
+ # Risk and structural analysis
1464
+ risk_info = analyze_file_risk(file_path, lang, sloc, is_test, raw_bytes=raw_bytes)
1465
+ cc = risk_info["cc"]
1466
+ cog = risk_info.get("cognitive", 0)
1467
+ total_cc += cc
1468
+ if cc > max_cc:
1469
+ max_cc = cc
1470
+ total_cognitive += cog
1471
+ if cog > max_cognitive:
1472
+ max_cognitive = cog
1473
+
1474
+ file_mi = risk_info.get("maintainability_index")
1475
+ if file_mi is None:
1476
+ # 解析/读取失败的文件不进入均值(F-RSI-20261115-276):假满分
1477
+ # 会污染聚合,降级文件计数显式暴露给度量看板。
1478
+ if risk_info.get("parse_status", "ok") in {"failed", "unreadable"}:
1479
+ maintainability_parse_failed_files += 1
1480
+ else:
1481
+ maintainability_scores.append(file_mi)
1482
+ if risk_info.get("critical_sinks"):
1483
+ for cs in risk_info["critical_sinks"]:
1484
+ all_critical_sinks.append({
1485
+ **cs,
1486
+ "file": rel,
1487
+ "location": rel,
1488
+ "source_file": rel,
1489
+ })
1490
+ if risk_info.get("taint_flows"):
1491
+ for tf in risk_info["taint_flows"]:
1492
+ all_taints.append({
1493
+ **tf,
1494
+ "file": rel,
1495
+ "location": rel,
1496
+ "source_file": rel,
1497
+ })
1498
+ if risk_info.get("secrets"):
1499
+ for sec in risk_info["secrets"]:
1500
+ all_secrets.append({
1501
+ **sec,
1502
+ "file": rel,
1503
+ "location": rel,
1504
+ "source_file": rel,
1505
+ })
1506
+ if risk_info.get("imports"):
1507
+ file_import_map[rel] = risk_info["imports"]
1508
+
1509
+ total_funcs += risk_info["functions"]
1510
+ total_classes += risk_info["classes"]
1511
+ total_god_funcs += risk_info["god_functions"]
1512
+ if risk_info["god_module"]:
1513
+ total_god_modules += 1
1514
+ total_sinks += risk_info["sinks"]
1515
+
1516
+ # Collect candidates for hotspots (production code with notable risk)
1517
+ if not is_test:
1518
+ prod_text_cache[file_path] = raw_bytes.decode("utf-8", errors="ignore")
1519
+ hotspots.append({
1520
+ "file": rel,
1521
+ "risk_score": risk_info["risk_score"],
1522
+ "cyclomatic_complexity": cc,
1523
+ "cognitive_complexity": cog,
1524
+ "maintainability_index": risk_info.get("maintainability_index"),
1525
+ "sensitive_sinks": risk_info["sinks"],
1526
+ "max_depth": risk_info["max_depth"],
1527
+ "sloc": sloc,
1528
+ "tags": risk_info["tags"],
1529
+ })
1530
+ else:
1531
+ doc_config_lines += sloc
1532
+
1533
+ # Language aggregate
1534
+ if lang not in lang_stats:
1535
+ lang_stats[lang] = {
1536
+ "files": 0, "total_lines": 0, "code_lines": 0,
1537
+ "comment_lines": 0, "docstring_lines": 0, "blank_lines": 0,
1538
+ "is_code": is_code,
1539
+ }
1540
+ lang_stats[lang]["files"] += 1
1541
+ lang_stats[lang]["total_lines"] += tot
1542
+ lang_stats[lang]["code_lines"] += sloc
1543
+ lang_stats[lang]["comment_lines"] += com
1544
+ lang_stats[lang]["docstring_lines"] += doc
1545
+ lang_stats[lang]["blank_lines"] += blk
1546
+
1547
+ # Module aggregate
1548
+ parts = rel.split("/")
1549
+ if len(parts) > 2 and parts[0] in {"src", "packages", "apps", "pkg"}:
1550
+ mod = f"{parts[0]}/{parts[1]}"
1551
+ elif len(parts) > 1:
1552
+ mod = parts[0]
1553
+ else:
1554
+ mod = "(root)"
1555
+
1556
+ if mod not in module_stats:
1557
+ module_stats[mod] = {"files": 0, "code_lines": 0, "total_lines": 0}
1558
+ module_stats[mod]["files"] += 1
1559
+ module_stats[mod]["code_lines"] += (sloc if is_code else 0)
1560
+ module_stats[mod]["total_lines"] += tot
1561
+
1562
+ # Sort languages
1563
+ languages_breakdown = []
1564
+ primary_lang = "unknown"
1565
+ highest_code_sloc = -1
1566
+
1567
+ for lang, s in sorted(
1568
+ lang_stats.items(),
1569
+ key=lambda x: (1 if x[1]["is_code"] else 0, x[1]["code_lines"]),
1570
+ reverse=True,
1571
+ ):
1572
+ if s["is_code"] and s["code_lines"] > highest_code_sloc:
1573
+ highest_code_sloc = s["code_lines"]
1574
+ primary_lang = lang
1575
+
1576
+ base_sloc = code_sloc if s["is_code"] else max(1, doc_config_lines)
1577
+ ratio = round((s["code_lines"] / max(1, base_sloc)) * 100, 1)
1578
+ languages_breakdown.append({
1579
+ "language": lang,
1580
+ "is_code": s["is_code"],
1581
+ "files": s["files"],
1582
+ "total_lines": s["total_lines"],
1583
+ "code_lines": s["code_lines"],
1584
+ "comment_lines": s["comment_lines"],
1585
+ "docstring_lines": s["docstring_lines"],
1586
+ "blank_lines": s["blank_lines"],
1587
+ "percentage": ratio,
1588
+ })
1589
+
1590
+ # Sort modules
1591
+ sorted_modules = sorted(module_stats.items(), key=lambda x: x[1]["code_lines"], reverse=True)
1592
+ modules_breakdown = []
1593
+ other_mod = {"files": 0, "code_lines": 0, "total_lines": 0}
1594
+
1595
+ for idx, (mod, s) in enumerate(sorted_modules):
1596
+ if idx < 15:
1597
+ ratio = round((s["code_lines"] / max(1, code_sloc if code_sloc > 0 else total_sloc)) * 100, 1)
1598
+ modules_breakdown.append({
1599
+ "module": mod,
1600
+ "files": s["files"],
1601
+ "code_lines": s["code_lines"],
1602
+ "total_lines": s["total_lines"],
1603
+ "percentage": ratio,
1604
+ })
1605
+ else:
1606
+ other_mod["files"] += s["files"]
1607
+ other_mod["code_lines"] += s["code_lines"]
1608
+ other_mod["total_lines"] += s["total_lines"]
1609
+
1610
+ if other_mod["files"] > 0:
1611
+ ratio = round((other_mod["code_lines"] / max(1, code_sloc if code_sloc > 0 else total_sloc)) * 100, 1)
1612
+ modules_breakdown.append({
1613
+ "module": "other",
1614
+ "files": other_mod["files"],
1615
+ "code_lines": other_mod["code_lines"],
1616
+ "total_lines": other_mod["total_lines"],
1617
+ "percentage": ratio,
1618
+ })
1619
+
1620
+ test_to_code_ratio = round(test_sloc / max(1, prod_sloc), 3) if prod_sloc > 0 else 0.0
1621
+ scale = estimate_scale(code_sloc if code_sloc > 0 else total_sloc, primary_lang)
1622
+
1623
+ avg_cc = round(total_cc / max(1, code_files), 1) if code_files > 0 else 1.0
1624
+ avg_cog = round(total_cognitive / max(1, code_files), 1) if code_files > 0 else 0.0
1625
+ # 聚合均值只取可解析文件(F-RSI-20261115-276):无可解析文件时不得伪装
1626
+ # 满分 100.0,以 None 表示"未测得",输出层降级为 0.0 并携带降级计数。
1627
+ avg_mi = (
1628
+ round(sum(maintainability_scores) / len(maintainability_scores), 1)
1629
+ if maintainability_scores else None
1630
+ )
1631
+ if avg_mi is None:
1632
+ mi_grade = "⚪ 未测得(无可解析代码文件)"
1633
+ elif avg_mi >= 65:
1634
+ mi_grade = "🟢 良好"
1635
+ elif avg_mi >= 40:
1636
+ mi_grade = "🟡 关注"
1637
+ else:
1638
+ mi_grade = "🔴 恶化"
1639
+
1640
+ health_grade = compute_health_grade(avg_cc, total_god_modules, test_to_code_ratio)
1641
+
1642
+ # Duplication analysis
1643
+ duplication_info = detect_code_duplication(
1644
+ project_root, prod_files_list, content_cache=prod_text_cache,
1645
+ )
1646
+
1647
+ # Architecture topology & cycles analysis
1648
+ architecture_info = analyze_architecture_dependencies(project_root, file_import_map)
1649
+
1650
+ # COCOMO & Technical debt calculation
1651
+ high_cc_count = sum(1 for h in hotspots if h["cyclomatic_complexity"] > 25)
1652
+ cocomo_debt_info = calculate_cocomo_and_debt(
1653
+ prod_sloc,
1654
+ total_god_modules,
1655
+ total_god_funcs,
1656
+ architecture_info.get("total_cycles", 0),
1657
+ len(all_taints),
1658
+ len(all_secrets),
1659
+ high_cc_count,
1660
+ total_sinks,
1661
+ )
1662
+
1663
+ # Sort hotspots by risk_score descending, keep top 5
1664
+ hotspots.sort(key=lambda x: x["risk_score"], reverse=True)
1665
+ top_hotspots = hotspots[:5]
1666
+
1667
+ return {
1668
+ "summary": {
1669
+ "total_files": total_files,
1670
+ "total_lines": total_lines,
1671
+ "code_lines": code_sloc if code_sloc > 0 else total_sloc,
1672
+ "doc_and_config_lines": doc_config_lines,
1673
+ "comment_lines": total_comments,
1674
+ "docstring_lines": total_docstrings,
1675
+ "blank_lines": total_blanks,
1676
+ "production_code_lines": prod_sloc,
1677
+ "production_files": prod_files,
1678
+ "test_code_lines": test_sloc,
1679
+ "test_files": test_files,
1680
+ "test_to_code_ratio": test_to_code_ratio,
1681
+ },
1682
+ "languages": languages_breakdown,
1683
+ "modules": modules_breakdown,
1684
+ "scale_estimation": scale,
1685
+ "maintainability": {
1686
+ "maintainability_index": avg_mi if avg_mi is not None else 0.0,
1687
+ "avg_maintainability_index": avg_mi if avg_mi is not None else 0.0,
1688
+ "maintainability_grade": mi_grade,
1689
+ "parse_failed_files": maintainability_parse_failed_files,
1690
+ "measured_files": len(maintainability_scores),
1691
+ "avg_cognitive_complexity": avg_cog,
1692
+ "max_cognitive_complexity": max_cognitive,
1693
+ },
1694
+
1695
+ "duplication": duplication_info,
1696
+ "architecture_topology": architecture_info,
1697
+ "engineering_economics": cocomo_debt_info,
1698
+ "risk_metrics": {
1699
+ "health_grade": health_grade,
1700
+ "avg_cyclomatic_complexity": avg_cc,
1701
+ "max_cyclomatic_complexity": max_cc,
1702
+ "total_functions": total_funcs,
1703
+ "total_classes": total_classes,
1704
+ "god_modules_count": total_god_modules,
1705
+ "god_functions_count": total_god_funcs,
1706
+ "total_sensitive_sinks": total_sinks,
1707
+ "total_taint_flows": len(all_taints),
1708
+ "total_hardcoded_secrets": len(all_secrets),
1709
+ "secrets": all_secrets,
1710
+ "critical_sinks": all_critical_sinks,
1711
+ "taint_flows": all_taints,
1712
+ "maintainability_index": avg_mi if avg_mi is not None else 0.0,
1713
+ "maintainability_parse_failed_files": maintainability_parse_failed_files,
1714
+ "avg_cognitive_complexity": avg_cog,
1715
+ "duplication_percentage": duplication_info.get("duplication_percentage", 0.0),
1716
+ "circular_dependencies_count": architecture_info.get("total_cycles", 0),
1717
+ "tech_debt_days": cocomo_debt_info.get("tech_debt_days", 0.0),
1718
+ "top_risk_hotspots": top_hotspots,
1719
+ },
1720
+ }