bugx-cli 0.0.0-stage → 0.1.0

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 (751) hide show
  1. package/LICENSE +55 -0
  2. package/README.md +280 -2
  3. package/core/CATALOG.json +141 -0
  4. package/core/README.md +254 -0
  5. package/core/adapters/README.md +35 -0
  6. package/core/adapters/android-interaction.json +81 -0
  7. package/core/adapters/android.json +24 -0
  8. package/core/adapters/desktop-macos.json +20 -0
  9. package/core/adapters/ios-interaction.json +34 -0
  10. package/core/adapters/ios.json +23 -0
  11. package/core/adapters/memory-macos.json +24 -0
  12. package/core/agent/README.md +50 -0
  13. package/core/agent/__init__.py +146 -0
  14. package/core/agent/agent_artifacts.py +764 -0
  15. package/core/agent/agent_eval.py +1073 -0
  16. package/core/agent/agent_execution.py +552 -0
  17. package/core/agent/agent_orchestrator.py +1345 -0
  18. package/core/agent/agent_targets.py +871 -0
  19. package/core/agent/agent_workspace.py +770 -0
  20. package/core/assets/README.md +24 -0
  21. package/core/assets/bugx-avatar-1024.png +0 -0
  22. package/core/assets/bugx-avatar-512.png +0 -0
  23. package/core/assets/bugx-avatar-tight.svg +23 -0
  24. package/core/assets/bugx-avatar.svg +28 -0
  25. package/core/assets/bugx-hero-cn.png +0 -0
  26. package/core/assets/bugx-hero-en.png +0 -0
  27. package/core/assets/project-layout.md +42 -0
  28. package/core/audit_packs/README.md +37 -0
  29. package/core/audit_packs/data-audit/manifest.json +94 -0
  30. package/core/audit_packs/data-audit/stages/00-scope.md +14 -0
  31. package/core/audit_packs/data-audit/stages/10-schema-inventory.md +14 -0
  32. package/core/audit_packs/data-audit/stages/20-query-and-integrity.md +14 -0
  33. package/core/audit_packs/data-audit/stages/80-evidence-regression.md +14 -0
  34. package/core/audit_packs/desktop-audit/manifest.json +123 -0
  35. package/core/audit_packs/desktop-audit/stages/00-scope.md +15 -0
  36. package/core/audit_packs/desktop-audit/stages/10-process-model.md +14 -0
  37. package/core/audit_packs/desktop-audit/stages/20-package-integrity.md +15 -0
  38. package/core/audit_packs/desktop-audit/stages/30-ui-behavior.md +14 -0
  39. package/core/audit_packs/desktop-audit/stages/80-evidence-regression.md +15 -0
  40. package/core/audit_packs/memory-testing.md +227 -0
  41. package/core/audit_packs/mobile-audit/manifest.json +155 -0
  42. package/core/audit_packs/mobile-audit/modules/android.md +19 -0
  43. package/core/audit_packs/mobile-audit/modules/h5.md +18 -0
  44. package/core/audit_packs/mobile-audit/modules/ios.md +25 -0
  45. package/core/audit_packs/mobile-audit/modules/miniprogram.md +26 -0
  46. package/core/audit_packs/mobile-audit/modules/webview.md +18 -0
  47. package/core/audit_packs/mobile-audit/stages/00-scope.md +14 -0
  48. package/core/audit_packs/mobile-audit/stages/10-platform-inventory.md +14 -0
  49. package/core/audit_packs/mobile-audit/stages/20-masvs-static.md +20 -0
  50. package/core/audit_packs/mobile-audit/stages/30-component-exposure.md +14 -0
  51. package/core/audit_packs/mobile-audit/stages/40-device-behavior.md +14 -0
  52. package/core/audit_packs/mobile-audit/stages/80-evidence-regression.md +13 -0
  53. package/core/audit_packs/native-audit/manifest.json +127 -0
  54. package/core/audit_packs/native-audit/stages/00-scope.md +14 -0
  55. package/core/audit_packs/native-audit/stages/10-static-white-box.md +14 -0
  56. package/core/audit_packs/native-audit/stages/20-memory-concurrency.md +15 -0
  57. package/core/audit_packs/native-audit/stages/30-behavior-black-box.md +39 -0
  58. package/core/audit_packs/native-audit/stages/80-evidence-regression.md +14 -0
  59. package/core/audit_packs/platform-testing.md +174 -0
  60. package/core/audit_packs/web-audit/manifest.json +191 -0
  61. package/core/audit_packs/web-audit/modules/graphql.md +5 -0
  62. package/core/audit_packs/web-audit/modules/h5.md +18 -0
  63. package/core/audit_packs/web-audit/modules/multi-tenant.md +4 -0
  64. package/core/audit_packs/web-audit/modules/oauth.md +4 -0
  65. package/core/audit_packs/web-audit/modules/upload.md +4 -0
  66. package/core/audit_packs/web-audit/modules/websocket.md +4 -0
  67. package/core/audit_packs/web-audit/stages/00-scope.md +13 -0
  68. package/core/audit_packs/web-audit/stages/10-discovery.md +13 -0
  69. package/core/audit_packs/web-audit/stages/20-auth-session.md +13 -0
  70. package/core/audit_packs/web-audit/stages/30-authz-business.md +13 -0
  71. package/core/audit_packs/web-audit/stages/40-input-output.md +13 -0
  72. package/core/audit_packs/web-audit/stages/50-state-async.md +13 -0
  73. package/core/audit_packs/web-audit/stages/60-file-ssrf-deser.md +12 -0
  74. package/core/audit_packs/web-audit/stages/70-config-dependency.md +12 -0
  75. package/core/audit_packs/web-audit/stages/80-evidence-regression.md +12 -0
  76. package/core/autonomous_cve/INTERFACE.md +61 -0
  77. package/core/autonomous_cve/README.md +58 -0
  78. package/core/autonomous_cve/SPEC.md +25 -0
  79. package/core/autonomous_cve/__init__.py +109 -0
  80. package/core/autonomous_cve/attack_graph.py +1096 -0
  81. package/core/autonomous_cve/attack_graph_store.py +1822 -0
  82. package/core/autonomous_cve/audit_campaign.py +1232 -0
  83. package/core/autonomous_cve/behavior_graph.py +459 -0
  84. package/core/autonomous_cve/ghsa_advisories.py +174 -0
  85. package/core/autonomous_cve/models.py +93 -0
  86. package/core/autonomous_cve/mutator.py +87 -0
  87. package/core/autonomous_cve/patcher.py +126 -0
  88. package/core/autonomous_cve/scout.py +278 -0
  89. package/core/autonomous_cve/synthesizer.py +207 -0
  90. package/core/autonomous_cve/verifier.py +100 -0
  91. package/core/bugx.md +1299 -0
  92. package/core/bugx_paths.py +1846 -0
  93. package/core/cloud_sync/INTERFACE.md +32 -0
  94. package/core/cloud_sync/README.md +62 -0
  95. package/core/cloud_sync/SPEC.md +25 -0
  96. package/core/cloud_sync/__init__.py +23 -0
  97. package/core/cloud_sync/auto_sync.py +398 -0
  98. package/core/cloud_sync/cloud_client.py +1199 -0
  99. package/core/cloud_sync/cloud_onboard.py +702 -0
  100. package/core/cloud_sync/cloud_schema.py +648 -0
  101. package/core/cloud_sync/consent.py +81 -0
  102. package/core/cloud_sync/device_identity.py +307 -0
  103. package/core/cloud_sync/endpoint_router.py +415 -0
  104. package/core/cloud_sync/flywheel_client.py +760 -0
  105. package/core/cloud_sync/network_transport.py +275 -0
  106. package/core/cloud_sync/onboard_wizard.py +493 -0
  107. package/core/cloud_sync/sensitive_filter.py +285 -0
  108. package/core/cloud_sync/sync_pull.py +695 -0
  109. package/core/cloud_sync/sync_push.py +721 -0
  110. package/core/contracts/AGENT_GUIDE.md +362 -0
  111. package/core/contracts/README.md +34 -0
  112. package/core/contracts/bugx-blackbox.md +541 -0
  113. package/core/contracts/bugx-opencode.md +469 -0
  114. package/core/contracts/bugx-quick.md +44 -0
  115. package/core/contracts/bugx-runtime-contract.md +353 -0
  116. package/core/contracts/bugx-worker.md +470 -0
  117. package/core/contracts/engine_gap_contracts.py +390 -0
  118. package/core/coverage/README.md +70 -0
  119. package/core/coverage/__init__.py +106 -0
  120. package/core/coverage/coverage_ai_review.py +185 -0
  121. package/core/coverage/coverage_backfill.py +54 -0
  122. package/core/coverage/coverage_bootstrap.py +713 -0
  123. package/core/coverage/coverage_business.py +36 -0
  124. package/core/coverage/coverage_cli.py +715 -0
  125. package/core/coverage/coverage_discovery.py +859 -0
  126. package/core/coverage/coverage_evidence.py +977 -0
  127. package/core/coverage/coverage_forensics.py +115 -0
  128. package/core/coverage/coverage_gate.py +277 -0
  129. package/core/coverage/coverage_intelligence.py +734 -0
  130. package/core/coverage/coverage_manifest.py +396 -0
  131. package/core/coverage/coverage_platform.py +77 -0
  132. package/core/coverage/coverage_validate.py +236 -0
  133. package/core/coverage/module_coverage.py +157 -0
  134. package/core/dev_harness/INTERFACE.md +20 -0
  135. package/core/dev_harness/README.md +21 -0
  136. package/core/dev_harness/SPEC.md +25 -0
  137. package/core/dev_harness/__init__.py +5 -0
  138. package/core/dev_harness/interaction_preset.py +408 -0
  139. package/core/engine-integrity.json +2625 -0
  140. package/core/fuzzing/README.md +49 -0
  141. package/core/fuzzing/__init__.py +82 -0
  142. package/core/fuzzing/concurrency_fuzzer.py +382 -0
  143. package/core/fuzzing/differential_oracle.py +629 -0
  144. package/core/fuzzing/fuzz_input.py +1188 -0
  145. package/core/fuzzing/stateful_fuzzer.py +332 -0
  146. package/core/governance/README.md +61 -0
  147. package/core/governance/__init__.py +130 -0
  148. package/core/governance/capacity_planner.py +124 -0
  149. package/core/governance/dependency_lock.py +317 -0
  150. package/core/governance/goal_governor.py +754 -0
  151. package/core/governance/guide_budget.py +458 -0
  152. package/core/governance/lockdown.sh +50 -0
  153. package/core/governance/readonly_enforcer.py +154 -0
  154. package/core/governance/runtime_tool_gate.py +373 -0
  155. package/core/governance/secret_redactor.py +772 -0
  156. package/core/governance/token_budget.py +38 -0
  157. package/core/host_acp/INTERFACE.md +36 -0
  158. package/core/host_acp/README.md +51 -0
  159. package/core/host_acp/SPEC.md +25 -0
  160. package/core/host_acp/__init__.py +121 -0
  161. package/core/host_acp/base.py +111 -0
  162. package/core/host_acp/claude.py +41 -0
  163. package/core/host_acp/cline.py +235 -0
  164. package/core/host_acp/codex.py +245 -0
  165. package/core/host_acp/dsh.py +48 -0
  166. package/core/host_acp/opencode.py +154 -0
  167. package/core/host_acp/pi.py +36 -0
  168. package/core/host_acp/zcode.py +41 -0
  169. package/core/host_runtime/INTERFACE.md +24 -0
  170. package/core/host_runtime/README.md +62 -0
  171. package/core/host_runtime/SPEC.md +25 -0
  172. package/core/host_runtime/__init__.py +21 -0
  173. package/core/host_runtime/adapters.py +412 -0
  174. package/core/host_runtime/autonomous_runner.py +1152 -0
  175. package/core/host_runtime/cline.py +435 -0
  176. package/core/host_runtime/common.py +103 -0
  177. package/core/host_runtime/free_models.py +786 -0
  178. package/core/host_runtime/host_bootstrap.py +389 -0
  179. package/core/host_runtime/host_evaluators.py +721 -0
  180. package/core/host_runtime/host_probe.py +41 -0
  181. package/core/host_runtime/host_provider_arbitrator.py +777 -0
  182. package/core/host_runtime/host_registry.py +655 -0
  183. package/core/host_runtime/host_usage.py +127 -0
  184. package/core/host_runtime/mcp_process_tracker.py +509 -0
  185. package/core/host_runtime/mcp_registry_gate.py +368 -0
  186. package/core/hosts/INTERFACE.md +51 -0
  187. package/core/hosts/README.md +67 -0
  188. package/core/hosts/SPEC.md +25 -0
  189. package/core/hosts/__init__.py +136 -0
  190. package/core/hosts/_base_usage.py +152 -0
  191. package/core/hosts/_codex_usage.py +297 -0
  192. package/core/hosts/_dsh_usage.py +184 -0
  193. package/core/hosts/_mcp_toml.py +365 -0
  194. package/core/hosts/_zcode_usage.py +269 -0
  195. package/core/hosts/base.py +451 -0
  196. package/core/hosts/claude.py +157 -0
  197. package/core/hosts/cline.py +225 -0
  198. package/core/hosts/codex.py +948 -0
  199. package/core/hosts/dsh.py +518 -0
  200. package/core/hosts/opencode.py +358 -0
  201. package/core/hosts/pi.py +151 -0
  202. package/core/hosts/zcode.py +219 -0
  203. package/core/i18n.py +252 -0
  204. package/core/infra/README.md +39 -0
  205. package/core/infra/__init__.py +15 -0
  206. package/core/infra/build_info.py +86 -0
  207. package/core/infra/client_metadata.py +185 -0
  208. package/core/infra/python_runtime.py +540 -0
  209. package/core/infra/safe_xml.py +221 -0
  210. package/core/launch_bugx.py +118 -0
  211. package/core/launch_phases/INTERFACE.md +31 -0
  212. package/core/launch_phases/README.md +106 -0
  213. package/core/launch_phases/SPEC.md +25 -0
  214. package/core/launch_phases/__init__.py +29 -0
  215. package/core/launch_phases/candidate_revalidation.py +484 -0
  216. package/core/launch_phases/common.py +1041 -0
  217. package/core/launch_phases/finding_confirm_phase.py +387 -0
  218. package/core/launch_phases/finding_settlement.py +1245 -0
  219. package/core/launch_phases/findings_adjudication.py +666 -0
  220. package/core/launch_phases/findings_snapshot.py +357 -0
  221. package/core/launch_phases/judge_phase.py +791 -0
  222. package/core/launch_phases/lesson_context.py +536 -0
  223. package/core/launch_phases/lifecycle_reporter.py +627 -0
  224. package/core/launch_phases/orchestrator_controls.py +682 -0
  225. package/core/launch_phases/post_commit.py +567 -0
  226. package/core/launch_phases/post_coverage_sync.py +591 -0
  227. package/core/launch_phases/post_dry_run.py +817 -0
  228. package/core/launch_phases/post_observability.py +367 -0
  229. package/core/launch_phases/post_phase.py +1087 -0
  230. package/core/launch_phases/post_receipt.py +362 -0
  231. package/core/launch_phases/post_round_lifecycle.py +786 -0
  232. package/core/launch_phases/pre_phase.py +1029 -0
  233. package/core/launch_phases/pre_recon_scout.py +862 -0
  234. package/core/launch_phases/pre_state_builder.py +1286 -0
  235. package/core/launch_phases/report_sharing.py +414 -0
  236. package/core/launch_phases/round_orchestrator.py +1133 -0
  237. package/core/launch_phases/session_runtime.py +1623 -0
  238. package/core/launch_phases/startup_gates.py +1022 -0
  239. package/core/launch_phases/startup_interaction.py +947 -0
  240. package/core/launch_phases/startup_version_gate.py +873 -0
  241. package/core/launch_phases/supervisor_bridge.py +1224 -0
  242. package/core/launch_phases/supervisor_coverage.py +417 -0
  243. package/core/launch_phases/supervisor_degraded.py +1219 -0
  244. package/core/launch_phases/worker_barriers.py +414 -0
  245. package/core/launch_phases/worker_orchestrator.py +1166 -0
  246. package/core/launch_phases/worker_prior.py +749 -0
  247. package/core/ledger/INTERFACE.md +35 -0
  248. package/core/ledger/README.md +160 -0
  249. package/core/ledger/SPEC.md +25 -0
  250. package/core/ledger/__init__.py +67 -0
  251. package/core/ledger/_facade.py +226 -0
  252. package/core/ledger/archive_ops.py +572 -0
  253. package/core/ledger/auto_materialization.py +459 -0
  254. package/core/ledger/bug-log.md +22 -0
  255. package/core/ledger/cli.py +270 -0
  256. package/core/ledger/export_ops.py +549 -0
  257. package/core/ledger/finding_confirmation.py +1274 -0
  258. package/core/ledger/finding_io.py +299 -0
  259. package/core/ledger/finding_lifecycle.py +307 -0
  260. package/core/ledger/finding_verification.py +369 -0
  261. package/core/ledger/incidents.py +999 -0
  262. package/core/ledger/lesson-replay-cases.json +20 -0
  263. package/core/ledger/lesson_ledger.py +241 -0
  264. package/core/ledger/lesson_replay.py +272 -0
  265. package/core/ledger/life_ledger.py +668 -0
  266. package/core/ledger/mistake-book.md +130 -0
  267. package/core/ledger/patterns.py +681 -0
  268. package/core/ledger/receipt_contract.py +253 -0
  269. package/core/ledger/schema.py +1192 -0
  270. package/core/ledger/sync_ops.py +935 -0
  271. package/core/ledger/tool_experience.py +682 -0
  272. package/core/ledger/verify_life.py +1526 -0
  273. package/core/lesson-ledger.json +275 -0
  274. package/core/locales/README.md +19 -0
  275. package/core/locales/en-US.json +462 -0
  276. package/core/locales/zh-CN.json +462 -0
  277. package/core/mcp_handlers/INTERFACE.md +75 -0
  278. package/core/mcp_handlers/README.md +62 -0
  279. package/core/mcp_handlers/SPEC.md +25 -0
  280. package/core/mcp_handlers/__init__.py +128 -0
  281. package/core/mcp_handlers/base.py +697 -0
  282. package/core/mcp_handlers/channel_lifecycle.py +696 -0
  283. package/core/mcp_handlers/graph_handlers.py +222 -0
  284. package/core/mcp_handlers/knowledge_handlers.py +536 -0
  285. package/core/mcp_handlers/mining_handlers.py +586 -0
  286. package/core/mcp_handlers/resource_prompt_table.py +116 -0
  287. package/core/mcp_handlers/retrieval_handlers.py +239 -0
  288. package/core/mcp_handlers/rpc_server.py +465 -0
  289. package/core/mcp_handlers/supervisor_handlers.py +1435 -0
  290. package/core/mcp_handlers/telemetry_handlers.py +227 -0
  291. package/core/mcp_handlers/tool_table.py +1015 -0
  292. package/core/mcp_runtime_support/README.md +21 -0
  293. package/core/mcp_runtime_support/__init__.py +1 -0
  294. package/core/mcp_runtime_support/common.py +363 -0
  295. package/core/mcp_runtime_support/environment.py +605 -0
  296. package/core/mcp_runtime_support/verifier.py +810 -0
  297. package/core/metadata.txt +5 -0
  298. package/core/planning/README.md +157 -0
  299. package/core/planning/__init__.py +242 -0
  300. package/core/planning/capability_plan.py +187 -0
  301. package/core/planning/capability_planner.py +195 -0
  302. package/core/planning/domain_archetype.py +542 -0
  303. package/core/planning/domain_router.py +267 -0
  304. package/core/planning/dynamic_flow_analyzer.py +328 -0
  305. package/core/planning/impact_pruner.py +435 -0
  306. package/core/planning/intent_adjudicator.py +175 -0
  307. package/core/planning/judge_pipeline.py +1163 -0
  308. package/core/planning/logic_analysis.py +419 -0
  309. package/core/planning/prompt_harness.py +1702 -0
  310. package/core/planning/source_inspector.py +267 -0
  311. package/core/planning/spec_harvester.py +449 -0
  312. package/core/planning/target_sandbox_manager.py +573 -0
  313. package/core/planning/test_capability_verifier.py +1364 -0
  314. package/core/planning/tools-kb.md +38 -0
  315. package/core/planning/unit_kind.py +122 -0
  316. package/core/probes/INTERFACE.md +73 -0
  317. package/core/probes/README.md +51 -0
  318. package/core/probes/SPEC.md +26 -0
  319. package/core/probes/__init__.py +70 -0
  320. package/core/probes/android_probe.py +384 -0
  321. package/core/probes/base.py +147 -0
  322. package/core/probes/codebase_memory_probe.py +590 -0
  323. package/core/probes/desktop_probe.py +238 -0
  324. package/core/probes/differential_probe.py +356 -0
  325. package/core/probes/efficiency_probe.py +168 -0
  326. package/core/probes/ios_binary_probe.py +368 -0
  327. package/core/probes/memory_probe.py +326 -0
  328. package/core/probes/miniprogram_probe.py +323 -0
  329. package/core/probes/mobile_probe.py +281 -0
  330. package/core/probes/native_probe.py +214 -0
  331. package/core/probes/openwiki_probe.py +193 -0
  332. package/core/probes/pattern_probe.py +347 -0
  333. package/core/probes/platform_probe.py +343 -0
  334. package/core/probes/probe_registry.py +1669 -0
  335. package/core/probes/sast_probe.py +1009 -0
  336. package/core/probes/sast_rules.py +841 -0
  337. package/core/probes/sca_scanner.py +731 -0
  338. package/core/probes/web_probe.py +359 -0
  339. package/core/project_profiler/INTERFACE.md +62 -0
  340. package/core/project_profiler/README.md +53 -0
  341. package/core/project_profiler/SPEC.md +28 -0
  342. package/core/project_profiler/__init__.py +201 -0
  343. package/core/project_profiler/arbitrator.py +311 -0
  344. package/core/project_profiler/constants.py +247 -0
  345. package/core/project_profiler/detector.py +392 -0
  346. package/core/project_profiler/extractors.py +836 -0
  347. package/core/project_profiler/fingerprint.py +116 -0
  348. package/core/project_profiler/storage.py +258 -0
  349. package/core/project_profiler/strategy.py +265 -0
  350. package/core/prompts/README.md +35 -0
  351. package/core/prompts/codex_dialog_dispatch.md +9 -0
  352. package/core/prompts/command_routing_en.md +42 -0
  353. package/core/prompts/command_routing_zh.md +42 -0
  354. package/core/prompts/l0_router.md +47 -0
  355. package/core/prompts/rules/anti_patterns.md +16 -0
  356. package/core/prompts/rules/concurrency_rules.md +14 -0
  357. package/core/prompts/rules/memory_leak_rules.md +13 -0
  358. package/core/prompts/rules/prompt_injection_defense.md +13 -0
  359. package/core/prompts/stages/stage_explore.md +31 -0
  360. package/core/prompts/stages/stage_gate.md +43 -0
  361. package/core/prompts/stages/stage_mutate.md +42 -0
  362. package/core/prompts/stages/stage_repair.md +85 -0
  363. package/core/repair/README.md +74 -0
  364. package/core/repair/__init__.py +169 -0
  365. package/core/repair/fix_watchlist.py +391 -0
  366. package/core/repair/l7_dynamic.py +418 -0
  367. package/core/repair/l7_repair_loop.py +465 -0
  368. package/core/repair/l7_selfcheck.py +862 -0
  369. package/core/repair/minimize_repro.py +466 -0
  370. package/core/repair/patch_synthesizer.py +617 -0
  371. package/core/repair/regression_pack.py +379 -0
  372. package/core/repair/rsi_fixer.py +910 -0
  373. package/core/repair/rsi_loop.py +313 -0
  374. package/core/repair/rsi_repair.py +348 -0
  375. package/core/repair/rsi_rounds.py +212 -0
  376. package/core/repair/rsi_scope.py +262 -0
  377. package/core/repair/self_heal.py +604 -0
  378. package/core/repair/test_generator.py +1108 -0
  379. package/core/repair/test_quality_auditor.py +410 -0
  380. package/core/repair/test_strategy.py +511 -0
  381. package/core/report_engine/INTERFACE.md +59 -0
  382. package/core/report_engine/README.md +69 -0
  383. package/core/report_engine/SPEC.md +28 -0
  384. package/core/report_engine/__init__.py +47 -0
  385. package/core/report_engine/attestation.py +224 -0
  386. package/core/report_engine/authority.py +255 -0
  387. package/core/report_engine/finding_report.py +417 -0
  388. package/core/report_engine/formal_report_builder.py +924 -0
  389. package/core/report_engine/html_renderers.py +696 -0
  390. package/core/report_engine/models.py +761 -0
  391. package/core/report_engine/pdf_exporter.py +231 -0
  392. package/core/report_engine/projects_assets.py +730 -0
  393. package/core/report_engine/report_client.py +743 -0
  394. package/core/report_engine/report_data_builder.py +388 -0
  395. package/core/report_engine/report_share.py +459 -0
  396. package/core/report_engine/sast_bridge.py +116 -0
  397. package/core/report_engine/server.py +822 -0
  398. package/core/report_engine/visual_report_builder.py +796 -0
  399. package/core/report_engine/web-conformance.md +63 -0
  400. package/core/report_engine/web_conformance.py +459 -0
  401. package/core/report_engine/workbench_assets.py +484 -0
  402. package/core/retrieval/INTERFACE.md +20 -0
  403. package/core/retrieval/README.md +161 -0
  404. package/core/retrieval/SPEC.md +25 -0
  405. package/core/retrieval/__init__.py +3 -0
  406. package/core/retrieval/code_analyzer.py +1684 -0
  407. package/core/retrieval/codebase_memory_bridge.py +337 -0
  408. package/core/retrieval/context_assembler.py +234 -0
  409. package/core/retrieval/corpus_fetch.py +369 -0
  410. package/core/retrieval/graph_ego.py +597 -0
  411. package/core/retrieval/knowledge_auto.py +662 -0
  412. package/core/retrieval/knowledge_sources.py +168 -0
  413. package/core/retrieval/knowledge_sync.py +909 -0
  414. package/core/retrieval/memory_store.py +480 -0
  415. package/core/retrieval/query_planner.py +1020 -0
  416. package/core/retrieval/rrf_engine.py +137 -0
  417. package/core/retrieval/slice_extractor.py +1209 -0
  418. package/core/retrieval/slice_normalizer.py +373 -0
  419. package/core/retrieval/slice_spec.py +357 -0
  420. package/core/retrieval/symbol_index.py +1132 -0
  421. package/core/retrieval/universal_code_matcher.py +437 -0
  422. package/core/retrieval/xerj_bridge.py +476 -0
  423. package/core/retrieval/xerj_supervisor.py +362 -0
  424. package/core/rules/README.md +33 -0
  425. package/core/rules/ios/PROVENANCE.json +30 -0
  426. package/core/rules/ios/crypto.yaml +36 -0
  427. package/core/rules/ios/network.yaml +20 -0
  428. package/core/rules/ios/resilience.yaml +47 -0
  429. package/core/rules/ios/storage.yaml +48 -0
  430. package/core/rules/mastg/LICENSE +173 -0
  431. package/core/rules/mastg/PROVENANCE.json +270 -0
  432. package/core/rules/mastg/mastg-android-asymmetric-key-pair-used-for-multiple-purposes.yml +13 -0
  433. package/core/rules/mastg/mastg-android-backup-manifest.yml +24 -0
  434. package/core/rules/mastg/mastg-android-biometric-event-bound.yml +49 -0
  435. package/core/rules/mastg/mastg-android-biometric-invalidated-enrollment.yml +11 -0
  436. package/core/rules/mastg/mastg-android-biometric-no-confirmation-required.yml +10 -0
  437. package/core/rules/mastg/mastg-android-biometric-validity-duration.yml +24 -0
  438. package/core/rules/mastg/mastg-android-broken-encryption-algorithms.yaml +9 -0
  439. package/core/rules/mastg/mastg-android-broken-encryption-modes.yaml +13 -0
  440. package/core/rules/mastg/mastg-android-content-provider-exported.yml +35 -0
  441. package/core/rules/mastg/mastg-android-custom-deeplink-scheme.yml +29 -0
  442. package/core/rules/mastg/mastg-android-dangerous-app-permissions.yaml +65 -0
  443. package/core/rules/mastg/mastg-android-data-unencrypted-shared-storage-no-user-interaction-apis.yml +36 -0
  444. package/core/rules/mastg/mastg-android-data-unencrypted-shared-storage-no-user-interaction-manifest.yml +15 -0
  445. package/core/rules/mastg/mastg-android-debuggable-flag.yml +10 -0
  446. package/core/rules/mastg/mastg-android-debugger-checks.yml +12 -0
  447. package/core/rules/mastg/mastg-android-deeplink-autoverify-missing.yml +33 -0
  448. package/core/rules/mastg/mastg-android-deeplink-unvalidated-parameter.yml +11 -0
  449. package/core/rules/mastg/mastg-android-device-passcode-present.yml +17 -0
  450. package/core/rules/mastg/mastg-android-fileprovider-broad-scope.yml +46 -0
  451. package/core/rules/mastg/mastg-android-hardcoded-crypto-keys-usage.yml +14 -0
  452. package/core/rules/mastg/mastg-android-hardcoded-security-provider.yaml +18 -0
  453. package/core/rules/mastg/mastg-android-implicit-intent-internal-communication.yml +30 -0
  454. package/core/rules/mastg/mastg-android-implicit-intent-leaking-extras.yml +29 -0
  455. package/core/rules/mastg/mastg-android-input-field-usage.yml +11 -0
  456. package/core/rules/mastg/mastg-android-key-generation-with-insufficient-key-length.yml +21 -0
  457. package/core/rules/mastg/mastg-android-keyboard-cache-input-types.yml +10 -0
  458. package/core/rules/mastg/mastg-android-local-storage-input-validation.yml +48 -0
  459. package/core/rules/mastg/mastg-android-native-debugger-checks.yml +12 -0
  460. package/core/rules/mastg/mastg-android-network-checkservertrusted.yml +12 -0
  461. package/core/rules/mastg/mastg-android-network-hostname-verification.yml +11 -0
  462. package/core/rules/mastg/mastg-android-network-insecure-trust-anchors.yml +11 -0
  463. package/core/rules/mastg/mastg-android-network-onreceivedsslerror.yml +12 -0
  464. package/core/rules/mastg/mastg-android-non-random-use.yml +16 -0
  465. package/core/rules/mastg/mastg-android-object-deserialization.yml +14 -0
  466. package/core/rules/mastg/mastg-android-overlay-protection.yml +68 -0
  467. package/core/rules/mastg/mastg-android-pendingintent-mutable.yml +39 -0
  468. package/core/rules/mastg/mastg-android-random-apis-insufficient-entropy.yml +17 -0
  469. package/core/rules/mastg/mastg-android-root-detection.yaml +59 -0
  470. package/core/rules/mastg/mastg-android-sdk-version.yml +10 -0
  471. package/core/rules/mastg/mastg-android-sensitive-data-in-notifications-manifest.yml +17 -0
  472. package/core/rules/mastg/mastg-android-sensitive-data-in-notifications.yml +11 -0
  473. package/core/rules/mastg/mastg-android-sensitive-data-in-screenshot.yml +18 -0
  474. package/core/rules/mastg/mastg-android-sql-injection-contentprovider.yml +17 -0
  475. package/core/rules/mastg/mastg-android-ssl-socket-hostnameverifier.yml +15 -0
  476. package/core/rules/mastg/mastg-android-strictmode.yml +10 -0
  477. package/core/rules/mastg/mastg-android-system-alert-window.yml +9 -0
  478. package/core/rules/mastg/mastg-android-webview-allow-local-access.yml +15 -0
  479. package/core/rules/mastg/mastg-android-webview-bridges.yml +28 -0
  480. package/core/rules/mastg/mastg-android-webview-safebrowsing.yml +20 -0
  481. package/core/rules/mastg/mastg-android-webview-url-handlers.yml +41 -0
  482. package/core/rules/miniprogram/PROVENANCE.json +26 -0
  483. package/core/rules/miniprogram/network.yaml +37 -0
  484. package/core/rules/miniprogram/platform.yaml +36 -0
  485. package/core/rules/miniprogram/storage.yaml +48 -0
  486. package/core/rules/mobsfscan-swift/LICENSE +165 -0
  487. package/core/rules/mobsfscan-swift/PROVENANCE.json +58 -0
  488. package/core/rules/mobsfscan-swift/auth.yaml +59 -0
  489. package/core/rules/mobsfscan-swift/crypto.yaml +66 -0
  490. package/core/rules/mobsfscan-swift/jailbreak.yaml +14 -0
  491. package/core/rules/mobsfscan-swift/keyboard.yaml +34 -0
  492. package/core/rules/mobsfscan-swift/logging.yaml +23 -0
  493. package/core/rules/mobsfscan-swift/network.yaml +55 -0
  494. package/core/rules/mobsfscan-swift/resilience.yaml +29 -0
  495. package/core/rules/mobsfscan-swift/secrets.yaml +33 -0
  496. package/core/rules/mobsfscan-swift/storage.yaml +29 -0
  497. package/core/rules/mobsfscan-swift/webview.yaml +32 -0
  498. package/core/runtime/README.md +198 -0
  499. package/core/runtime/__init__.py +3 -0
  500. package/core/runtime/bugx_logging.py +1393 -0
  501. package/core/runtime/daemon_runner.py +623 -0
  502. package/core/runtime/fixture_solidify.py +449 -0
  503. package/core/runtime/global_telemetry.py +549 -0
  504. package/core/runtime/incident_eval.py +148 -0
  505. package/core/runtime/interaction.py +605 -0
  506. package/core/runtime/interaction_store.py +435 -0
  507. package/core/runtime/interactive_menu.py +95 -0
  508. package/core/runtime/log_analytics.py +922 -0
  509. package/core/runtime/mining_quality_framework.py +1387 -0
  510. package/core/runtime/model_runner.py +769 -0
  511. package/core/runtime/platform_adapter.py +579 -0
  512. package/core/runtime/prep_validate.py +476 -0
  513. package/core/runtime/project_graph.py +827 -0
  514. package/core/runtime/project_init.py +481 -0
  515. package/core/runtime/project_profile.py +224 -0
  516. package/core/runtime/project_settings.py +963 -0
  517. package/core/runtime/provider_window.py +97 -0
  518. package/core/runtime/resume_ticket.py +115 -0
  519. package/core/runtime/scenario_eval.py +814 -0
  520. package/core/runtime/seed_drill.py +549 -0
  521. package/core/runtime/self_audit.py +550 -0
  522. package/core/runtime/session_profile.py +205 -0
  523. package/core/runtime/setup_ui_env.py +229 -0
  524. package/core/runtime/startup_environment.py +859 -0
  525. package/core/runtime/sync_store.py +1421 -0
  526. package/core/runtime/tool_install_targets.py +18 -0
  527. package/core/schemas/README.md +35 -0
  528. package/core/schemas/agent-graph.schema.json +368 -0
  529. package/core/schemas/attack-graph.schema.json +88 -0
  530. package/core/schemas/evidence-bundle.schema.json +33 -0
  531. package/core/schemas/skill-pack.schema.json +230 -0
  532. package/core/schemas/worker-checkpoint.schema.json +119 -0
  533. package/core/secure_atomic.py +289 -0
  534. package/core/seed_corpus/README.md +55 -0
  535. package/core/seed_corpus/c.txt +29 -0
  536. package/core/seed_corpus/cpp.txt +32 -0
  537. package/core/seed_corpus/css.txt +70 -0
  538. package/core/seed_corpus/go.txt +46 -0
  539. package/core/seed_corpus/java.txt +30 -0
  540. package/core/seed_corpus/javascript.txt +55 -0
  541. package/core/seed_corpus/kotlin.txt +28 -0
  542. package/core/seed_corpus/python.txt +71 -0
  543. package/core/seed_corpus/rust.txt +53 -0
  544. package/core/seed_corpus/swift.txt +29 -0
  545. package/core/seed_corpus/typescript.txt +29 -0
  546. package/core/skills/README.md +53 -0
  547. package/core/skills/__init__.py +189 -0
  548. package/core/skills/bugx_docs_mcp_server.py +416 -0
  549. package/core/skills/bugx_mcp_server.py +1134 -0
  550. package/core/skills/mcp_runtime.py +968 -0
  551. package/core/skills/mcp_session_proof.py +605 -0
  552. package/core/skills/mobile_ui_inspector.py +405 -0
  553. package/core/skills/skill_pack.py +1214 -0
  554. package/core/skills/skill_synthesizer.py +1153 -0
  555. package/core/skills/tools_kb.py +313 -0
  556. package/core/supervisor/INTERFACE.md +121 -0
  557. package/core/supervisor/README.md +209 -0
  558. package/core/supervisor/SPEC.md +25 -0
  559. package/core/supervisor/__init__.py +175 -0
  560. package/core/supervisor/audit_supervisor.py +1015 -0
  561. package/core/supervisor/budget_governor.py +760 -0
  562. package/core/supervisor/checkpoint_handler.py +368 -0
  563. package/core/supervisor/checkpoint_pipeline.py +1322 -0
  564. package/core/supervisor/checkpoint_sync.py +640 -0
  565. package/core/supervisor/claim_events.py +74 -0
  566. package/core/supervisor/claim_sync.py +590 -0
  567. package/core/supervisor/cli.py +812 -0
  568. package/core/supervisor/context_sync.py +55 -0
  569. package/core/supervisor/coverage_sync.py +115 -0
  570. package/core/supervisor/finding_commit.py +470 -0
  571. package/core/supervisor/finding_sync.py +688 -0
  572. package/core/supervisor/finding_workflow.py +659 -0
  573. package/core/supervisor/finish_policy.py +224 -0
  574. package/core/supervisor/finish_sync.py +185 -0
  575. package/core/supervisor/graph_sync.py +669 -0
  576. package/core/supervisor/lease_manager.py +788 -0
  577. package/core/supervisor/lifecycle_blocks.py +124 -0
  578. package/core/supervisor/next_round_sync.py +126 -0
  579. package/core/supervisor/observability.py +140 -0
  580. package/core/supervisor/recovery_sync.py +165 -0
  581. package/core/supervisor/rejection_remedies.py +308 -0
  582. package/core/supervisor/round_governor.py +306 -0
  583. package/core/supervisor/serial_authorization.py +500 -0
  584. package/core/supervisor/start_sync.py +87 -0
  585. package/core/supervisor/state_store.py +249 -0
  586. package/core/supervisor/supervisor_host.py +511 -0
  587. package/core/supervisor/supervisor_models.py +1143 -0
  588. package/core/supervisor/systemic_failure.py +104 -0
  589. package/core/supervisor/task_scheduler.py +1640 -0
  590. package/core/supervisor/worker_checkpoint.py +223 -0
  591. package/core/supervisor/worker_execution.py +265 -0
  592. package/core/supervisor/worker_handoff.py +192 -0
  593. package/core/supervisor/worker_lifecycle.py +396 -0
  594. package/core/supervisor/worker_runtime.py +999 -0
  595. package/core/supervisor/worker_sync.py +89 -0
  596. package/core/supervisor_types/README.md +36 -0
  597. package/core/supervisor_types/__init__.py +0 -0
  598. package/core/supervisor_types/exceptions.py +52 -0
  599. package/core/supervisor_types/graph_models.py +357 -0
  600. package/core/supervisor_types/path_containment.py +151 -0
  601. package/core/supervisor_types/target_fingerprint.py +310 -0
  602. package/core/supervisor_types/worker_claim.py +402 -0
  603. package/core/webui/INTERFACE.md +50 -0
  604. package/core/webui/README.md +57 -0
  605. package/core/webui/SPEC.md +25 -0
  606. package/core/webui/__init__.py +11 -0
  607. package/core/webui/adapters/__init__.py +27 -0
  608. package/core/webui/adapters/base.py +87 -0
  609. package/core/webui/adapters/bugx.py +102 -0
  610. package/core/webui/adapters/claude.py +218 -0
  611. package/core/webui/adapters/cline.py +399 -0
  612. package/core/webui/adapters/codex.py +256 -0
  613. package/core/webui/adapters/dsh.py +173 -0
  614. package/core/webui/adapters/opencode.py +218 -0
  615. package/core/webui/adapters/pi.py +272 -0
  616. package/core/webui/adapters/registry.py +100 -0
  617. package/core/webui/adapters/zcode.py +312 -0
  618. package/core/webui/api_routes_post.py +668 -0
  619. package/core/webui/dispatcher.py +1376 -0
  620. package/core/webui/docs_session_service.py +473 -0
  621. package/core/webui/handler.py +674 -0
  622. package/core/webui/ide_cloud_service.py +526 -0
  623. package/core/webui/mcp_inspector.py +1743 -0
  624. package/core/webui/static/assets/index-CXAsl8mr.js +333 -0
  625. package/core/webui/static/assets/index-DHQUtWtx.css +1 -0
  626. package/core/webui/static/assets/source-serif-4-cyrillic-400-normal-B8Z6Jvzv.woff +0 -0
  627. package/core/webui/static/assets/source-serif-4-cyrillic-400-normal-C44pakCn.woff2 +0 -0
  628. package/core/webui/static/assets/source-serif-4-cyrillic-500-normal-Bb4u56_6.woff +0 -0
  629. package/core/webui/static/assets/source-serif-4-cyrillic-500-normal-BdVUvljg.woff2 +0 -0
  630. package/core/webui/static/assets/source-serif-4-cyrillic-ext-400-normal-CWV284fw.woff2 +0 -0
  631. package/core/webui/static/assets/source-serif-4-cyrillic-ext-400-normal-DLkyKLvH.woff +0 -0
  632. package/core/webui/static/assets/source-serif-4-cyrillic-ext-500-normal-8-8HP2PF.woff +0 -0
  633. package/core/webui/static/assets/source-serif-4-cyrillic-ext-500-normal-DaDZE_Na.woff2 +0 -0
  634. package/core/webui/static/assets/source-serif-4-greek-400-normal-BccYJ-vZ.woff +0 -0
  635. package/core/webui/static/assets/source-serif-4-greek-400-normal-Cw5-AHNN.woff2 +0 -0
  636. package/core/webui/static/assets/source-serif-4-greek-500-normal-By8GFJzz.woff2 +0 -0
  637. package/core/webui/static/assets/source-serif-4-greek-500-normal-z-Q6FFuG.woff +0 -0
  638. package/core/webui/static/assets/source-serif-4-latin-400-normal-DJ5YJwmz.woff2 +0 -0
  639. package/core/webui/static/assets/source-serif-4-latin-400-normal-Dn3IlU-Z.woff +0 -0
  640. package/core/webui/static/assets/source-serif-4-latin-500-normal-CUHe9xxf.woff2 +0 -0
  641. package/core/webui/static/assets/source-serif-4-latin-500-normal-DVVamBqs.woff +0 -0
  642. package/core/webui/static/assets/source-serif-4-latin-ext-400-normal-CEpydyUl.woff +0 -0
  643. package/core/webui/static/assets/source-serif-4-latin-ext-400-normal-Cp7z-ARB.woff2 +0 -0
  644. package/core/webui/static/assets/source-serif-4-latin-ext-500-normal-BYjRCDVy.woff2 +0 -0
  645. package/core/webui/static/assets/source-serif-4-latin-ext-500-normal-D-qasQTj.woff +0 -0
  646. package/core/webui/static/assets/source-serif-4-vietnamese-400-normal-BbG3LG1A.woff2 +0 -0
  647. package/core/webui/static/assets/source-serif-4-vietnamese-400-normal-DR1UuFon.woff +0 -0
  648. package/core/webui/static/assets/source-serif-4-vietnamese-500-normal-8N8MYVKB.woff +0 -0
  649. package/core/webui/static/assets/source-serif-4-vietnamese-500-normal-Bi3OSTTW.woff2 +0 -0
  650. package/core/webui/static/favicon.png +0 -0
  651. package/core/webui/static/icon-192.png +0 -0
  652. package/core/webui/static/index.html +42 -0
  653. package/core/webui/static/manifest.webmanifest +19 -0
  654. package/core/webui/static/project-settings.css +6458 -0
  655. package/core/webui/static/project-settings.js +9602 -0
  656. package/core/webui/static/sw.js +8 -0
  657. package/core/webui/workspace_service.py +218 -0
  658. package/docs/07_distribution/01_README_NPM.md +281 -0
  659. package/docs/07_distribution/README.md +16 -0
  660. package/docs/README.md +121 -0
  661. package/ecosystem/README.md +129 -0
  662. package/ecosystem/integrations/README.md +38 -0
  663. package/ecosystem/integrations/cline/skills/bugx/SKILL.md +69 -0
  664. package/ecosystem/integrations/dsh/agents/bugx.md +27 -0
  665. package/ecosystem/integrations/dsh/dsh-patch.yml +18 -0
  666. package/ecosystem/integrations/dsh/mcp/cordis.patch.yml +4 -0
  667. package/ecosystem/integrations/dsh/mcp/index.js +219 -0
  668. package/ecosystem/integrations/dsh/mcp/package.json +28 -0
  669. package/ecosystem/integrations/dsh/skills/bugx/SKILL.md +70 -0
  670. package/ecosystem/integrations/dsh/skills/bugx-dsh/SKILL.md +229 -0
  671. package/ecosystem/integrations/dsh/ui/client.js +87 -0
  672. package/ecosystem/integrations/dsh/ui/cordis.patch.yml +4 -0
  673. package/ecosystem/integrations/dsh/ui/index.js +7 -0
  674. package/ecosystem/integrations/dsh/ui/package.json +27 -0
  675. package/ecosystem/integrations/opencode/bugx-mcp-manifest.json +53 -0
  676. package/ecosystem/integrations/opencode/mcp-lock.json +3067 -0
  677. package/ecosystem/integrations/opencode/opencode.json +118 -0
  678. package/ecosystem/integrations/pi/extensions/bugx/README.md +12 -0
  679. package/ecosystem/integrations/pi/extensions/bugx/index.ts +299 -0
  680. package/ecosystem/integrations/pi/extensions/bugx/manifest.json +11 -0
  681. package/ecosystem/integrations/pi/skills/bugx/SKILL.md +69 -0
  682. package/ecosystem/integrations/qoder/CONNECTORS.md +54 -0
  683. package/ecosystem/integrations/qoder/connector-meta.json +21 -0
  684. package/ecosystem/integrations/workbuddy/connector-meta.json +19 -0
  685. package/ecosystem/integrations/workbuddy/icon.png +0 -0
  686. package/ecosystem/integrations/workbuddy/skills/bugx/SKILL.md +70 -0
  687. package/ecosystem/plugins/README.md +37 -0
  688. package/ecosystem/plugins/bugx/.claude-plugin/marketplace.json +17 -0
  689. package/ecosystem/plugins/bugx/.claude-plugin/plugin.json +16 -0
  690. package/ecosystem/plugins/bugx/.codex-plugin/plugin.json +41 -0
  691. package/ecosystem/plugins/bugx/.zcode-plugin/plugin.json +19 -0
  692. package/ecosystem/plugins/bugx/agents/bugx-judge.md +71 -0
  693. package/ecosystem/plugins/bugx/agents/bugx-worker.md +31 -0
  694. package/ecosystem/plugins/bugx/agents/bugx.md +74 -0
  695. package/ecosystem/plugins/bugx/assets/bugx-avatar-512.png +0 -0
  696. package/ecosystem/plugins/bugx/skills/bugx/SKILL.md +118 -0
  697. package/ecosystem/plugins/bugx/skills/bugx-claude/SKILL.md +326 -0
  698. package/ecosystem/plugins/bugx/skills/bugx-dsh/SKILL.md +229 -0
  699. package/ecosystem/plugins/bugx/skills/bugx-opencode/SKILL.md +129 -0
  700. package/ecosystem/plugins/bugx/skills/bugx-zcode/SKILL.md +459 -0
  701. package/interfaces/README.md +143 -0
  702. package/interfaces/bin/README.md +35 -0
  703. package/interfaces/bin/bugx.js +80 -0
  704. package/interfaces/cli/README.md +90 -0
  705. package/interfaces/cli/bugx_cli/__init__.py +4 -0
  706. package/interfaces/cli/bugx_cli/cli.py +1678 -0
  707. package/interfaces/cli/bugx_cli/commands/__init__.py +1 -0
  708. package/interfaces/cli/bugx_cli/commands/advisory.py +94 -0
  709. package/interfaces/cli/bugx_cli/commands/agent.py +3944 -0
  710. package/interfaces/cli/bugx_cli/commands/audit.py +632 -0
  711. package/interfaces/cli/bugx_cli/commands/autonomous.py +260 -0
  712. package/interfaces/cli/bugx_cli/commands/cloud.py +1370 -0
  713. package/interfaces/cli/bugx_cli/commands/daemon.py +50 -0
  714. package/interfaces/cli/bugx_cli/commands/doctor.py +1345 -0
  715. package/interfaces/cli/bugx_cli/commands/goal.py +107 -0
  716. package/interfaces/cli/bugx_cli/commands/interaction.py +244 -0
  717. package/interfaces/cli/bugx_cli/commands/knowledge.py +617 -0
  718. package/interfaces/cli/bugx_cli/commands/lifecycle.py +2763 -0
  719. package/interfaces/cli/bugx_cli/commands/patch.py +1014 -0
  720. package/interfaces/cli/bugx_cli/commands/plugin.py +2714 -0
  721. package/interfaces/cli/bugx_cli/commands/plugin_claude.py +1446 -0
  722. package/interfaces/cli/bugx_cli/commands/plugin_cline.py +269 -0
  723. package/interfaces/cli/bugx_cli/commands/plugin_codex.py +74 -0
  724. package/interfaces/cli/bugx_cli/commands/plugin_funide.py +728 -0
  725. package/interfaces/cli/bugx_cli/commands/plugin_qoder.py +216 -0
  726. package/interfaces/cli/bugx_cli/commands/plugin_zcode.py +710 -0
  727. package/interfaces/cli/bugx_cli/commands/project.py +670 -0
  728. package/interfaces/cli/bugx_cli/commands/report.py +260 -0
  729. package/interfaces/cli/bugx_cli/commands/skill.py +251 -0
  730. package/interfaces/cli/bugx_cli/commands/stats.py +133 -0
  731. package/interfaces/cli/bugx_cli/commands/system.py +2567 -0
  732. package/interfaces/cli/bugx_cli/common.py +898 -0
  733. package/interfaces/cli/bugx_cli/host_adapters.py +1917 -0
  734. package/interfaces/cli/bugx_cli/hosts/__init__.py +80 -0
  735. package/interfaces/cli/bugx_cli/hosts/base.py +99 -0
  736. package/interfaces/cli/bugx_cli/hosts/registry.py +571 -0
  737. package/interfaces/cli/bugx_cli/hosts/template_engine.py +188 -0
  738. package/interfaces/cli/bugx_cli/infra/__init__.py +209 -0
  739. package/interfaces/cli/bugx_cli/infra/ai_advisor.py +721 -0
  740. package/interfaces/cli/bugx_cli/infra/engine_installer.py +1937 -0
  741. package/interfaces/cli/bugx_cli/infra/host_sync.py +545 -0
  742. package/interfaces/cli/bugx_cli/infra/mcp_advisor.py +755 -0
  743. package/interfaces/cli/bugx_cli/infra/security.py +332 -0
  744. package/package.json +98 -4
  745. package/pyproject.toml +246 -0
  746. package/scripts/README.md +118 -0
  747. package/scripts/ensure-python.mjs +97 -0
  748. package/scripts/isolate-npm-readme.mjs +40 -0
  749. package/scripts/runtime.lock.json +31 -0
  750. package/scripts/sync-version.mjs +37 -0
  751. package/scripts/test-npm-wrapper.mjs +265 -0
@@ -0,0 +1,1684 @@
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
+ return {
252
+ "cc": 1, "cognitive": 0, "max_depth": 1, "functions": 0, "classes": 0,
253
+ "god_functions": 0, "taint_flows": [], "imports": [], "maintainability_index": 100.0,
254
+ }
255
+
256
+ class Visitor(ast.NodeVisitor):
257
+ def __init__(self) -> None:
258
+ self.current_depth = 0
259
+ self.max_d = 0
260
+ self.branches = 0
261
+ self.func_count = 0
262
+ self.class_count = 0
263
+ self.god_funcs = 0
264
+ self.cognitive = 0
265
+ self.nesting = 0
266
+ self.operators: Counter[str] = Counter()
267
+ self.operands: Counter[str] = Counter()
268
+ self.taints: list[dict[str, Any]] = []
269
+ self.critical_sinks: list[dict[str, Any]] = []
270
+ self.mitigations: list[dict[str, Any]] = []
271
+ self.imports: list[str] = []
272
+ self.alias_map: dict[str, str] = {}
273
+ self.local_params: set[str] = set()
274
+ self.tainted_vars: set[str] = set()
275
+ self.taint_kind_by_var: dict[str, str] = {}
276
+ self.current_func_name: str = ""
277
+ self.current_env: dict[str, Any] = {}
278
+
279
+ def visit_Import(self, node: ast.Import) -> None:
280
+ for alias in node.names:
281
+ self.imports.append(alias.name)
282
+ if alias.asname:
283
+ self.alias_map[alias.asname] = alias.name
284
+ self.generic_visit(node)
285
+
286
+ def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
287
+ mod = node.module or ""
288
+ if mod:
289
+ self.imports.append(mod)
290
+ for alias in node.names:
291
+ full_name = f"{mod}.{alias.name}" if mod else alias.name
292
+ target_name = alias.asname or alias.name
293
+ self.alias_map[target_name] = full_name
294
+ if full_name:
295
+ self.imports.append(full_name)
296
+ if alias.name:
297
+ self.imports.append(alias.name)
298
+ self.generic_visit(node)
299
+
300
+ def visit_FunctionDef(self, node: ast.FunctionDef | ast.AsyncFunctionDef) -> None:
301
+ self.func_count += 1
302
+ self.operators[node.__class__.__name__] += 1
303
+ func_span = getattr(node, "end_lineno", node.lineno) - node.lineno + 1
304
+ sub_branches = sum(
305
+ 1 for child in ast.walk(node)
306
+ if isinstance(
307
+ child,
308
+ (
309
+ ast.If, ast.While, ast.For, ast.AsyncFor,
310
+ ast.ExceptHandler, ast.With, ast.AsyncWith, ast.Assert
311
+ ),
312
+ )
313
+ )
314
+ if func_span > 100 or sub_branches > 20:
315
+ self.god_funcs += 1
316
+
317
+ old_params = self.local_params
318
+ old_tainted = set(self.tainted_vars)
319
+ old_func = self.current_func_name
320
+ old_env = self.current_env
321
+ self.current_func_name = node.name
322
+
323
+ # 闭包感知:保留外层自由变量的污点标记,叠加函数入参
324
+ new_params = {a.arg for a in node.args.args}
325
+ self.local_params = new_params
326
+ self.tainted_vars.update(new_params)
327
+
328
+ if DynamicFlowAnalyzer:
329
+ try:
330
+ analyzer = DynamicFlowAnalyzer(language="python")
331
+ self.current_env = analyzer.fold_python_function_scope(node)
332
+ for v in self.current_env.values():
333
+ if getattr(v, "is_tainted", False):
334
+ self.tainted_vars.add(v.name)
335
+ except Exception:
336
+ self.current_env = {}
337
+ else:
338
+ self.current_env = {}
339
+
340
+ self.nesting += 1
341
+ old_d = self.current_depth
342
+ self.current_depth += 1
343
+ if self.current_depth > self.max_d:
344
+ self.max_d = self.current_depth
345
+
346
+ self.generic_visit(node)
347
+
348
+ self.current_depth = old_d
349
+ self.nesting -= 1
350
+ self.local_params = old_params
351
+ self.tainted_vars = old_tainted
352
+ self.current_func_name = old_func
353
+ self.current_env = old_env
354
+
355
+ def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None:
356
+ self.visit_FunctionDef(node)
357
+
358
+ def visit_ClassDef(self, node: ast.ClassDef) -> None:
359
+ self.class_count += 1
360
+ self.operators["ClassDef"] += 1
361
+ old_d = self.current_depth
362
+ self.current_depth += 1
363
+ if self.current_depth > self.max_d:
364
+ self.max_d = self.current_depth
365
+ self.generic_visit(node)
366
+ self.current_depth = old_d
367
+
368
+ def visit_If(self, node: ast.If) -> None:
369
+ self.branches += 1
370
+ self.operators["If"] += 1
371
+ is_elif = getattr(node, "_is_elif", False)
372
+ if is_elif:
373
+ self.cognitive += 1
374
+ else:
375
+ self.cognitive += (1 + self.nesting)
376
+
377
+ old_d = self.current_depth
378
+ self.current_depth += 1
379
+ if self.current_depth > self.max_d:
380
+ self.max_d = self.current_depth
381
+
382
+ if len(node.orelse) == 1 and isinstance(node.orelse[0], ast.If):
383
+ node.orelse[0]._is_elif = True
384
+
385
+ self.nesting += 1
386
+ self.generic_visit(node)
387
+ self.nesting -= 1
388
+ self.current_depth = old_d
389
+
390
+ def visit_While(self, node: ast.While) -> None:
391
+ self.branches += 1
392
+ self.operators["While"] += 1
393
+ self.cognitive += (1 + self.nesting)
394
+ old_d = self.current_depth
395
+ self.current_depth += 1
396
+ if self.current_depth > self.max_d:
397
+ self.max_d = self.current_depth
398
+ self.nesting += 1
399
+ self.generic_visit(node)
400
+ self.nesting -= 1
401
+ self.current_depth = old_d
402
+
403
+ def visit_For(self, node: ast.For | ast.AsyncFor) -> None:
404
+ self.branches += 1
405
+ self.operators[node.__class__.__name__] += 1
406
+ self.cognitive += (1 + self.nesting)
407
+ old_d = self.current_depth
408
+ self.current_depth += 1
409
+ if self.current_depth > self.max_d:
410
+ self.max_d = self.current_depth
411
+ self.nesting += 1
412
+ self.generic_visit(node)
413
+ self.nesting -= 1
414
+ self.current_depth = old_d
415
+
416
+ def visit_AsyncFor(self, node: ast.AsyncFor) -> None:
417
+ self.visit_For(node)
418
+
419
+ def visit_ExceptHandler(self, node: ast.ExceptHandler) -> None:
420
+ self.branches += 1
421
+ self.operators["ExceptHandler"] += 1
422
+ self.cognitive += (1 + self.nesting)
423
+ self.nesting += 1
424
+ self.generic_visit(node)
425
+ self.nesting -= 1
426
+
427
+ def visit_BoolOp(self, node: ast.BoolOp) -> None:
428
+ self.branches += len(node.values) - 1
429
+ self.cognitive += 1
430
+ self.operators[node.op.__class__.__name__] += len(node.values) - 1
431
+ self.generic_visit(node)
432
+
433
+ def visit_Break(self, node: ast.Break) -> None:
434
+ self.cognitive += 1
435
+ self.operators["Break"] += 1
436
+ self.generic_visit(node)
437
+
438
+ def visit_Continue(self, node: ast.Continue) -> None:
439
+ self.cognitive += 1
440
+ self.operators["Continue"] += 1
441
+ self.generic_visit(node)
442
+
443
+ def visit_Assign(self, node: ast.Assign) -> None:
444
+ self.operators["Assign"] += 1
445
+ assigned_tainted = False
446
+ taint_kind = ""
447
+
448
+ # 1. 检查右值是否引入或传递未净化输入
449
+ has_user_input = False
450
+ for child in ast.walk(node.value):
451
+ if isinstance(child, ast.Name):
452
+ if child.id in self.tainted_vars:
453
+ has_user_input = True
454
+ elif child.id in {"argv", "environ", "request", "params", "query", "user_input", "cmd", "filename", "filepath", "sql"}:
455
+ has_user_input = True
456
+ elif isinstance(child, ast.Attribute) and child.attr in {"argv", "environ", "args", "form", "json", "params", "GET", "POST"}:
457
+ has_user_input = True
458
+
459
+ # 2. 局部污点折叠:SQL/命令字符串插值与路径拼接
460
+ if isinstance(node.value, ast.JoinedStr) and has_user_input:
461
+ assigned_tainted = True
462
+ taint_kind = "dynamic_sql"
463
+ elif isinstance(node.value, ast.BinOp) and isinstance(node.value.op, (ast.Add, ast.Mod)) and has_user_input:
464
+ assigned_tainted = True
465
+ taint_kind = "dynamic_sql"
466
+ elif (
467
+ isinstance(node.value, ast.Call)
468
+ and isinstance(node.value.func, ast.Attribute)
469
+ and node.value.func.attr == "join"
470
+ and has_user_input
471
+ ):
472
+ assigned_tainted = True
473
+ taint_kind = "path_traversal"
474
+ elif has_user_input:
475
+ assigned_tainted = True
476
+ taint_kind = "generic_taint"
477
+
478
+ if assigned_tainted:
479
+ for target in node.targets:
480
+ if isinstance(target, ast.Name):
481
+ self.tainted_vars.add(target.id)
482
+ if taint_kind:
483
+ self.taint_kind_by_var[target.id] = taint_kind
484
+
485
+ # 3. 检查防御特征 (如 re.match / SafeLoader / shlex.quote)
486
+ if isinstance(node.value, ast.Call):
487
+ call_func = ""
488
+ if isinstance(node.value.func, ast.Name):
489
+ call_func = node.value.func.id
490
+ elif isinstance(node.value.func, ast.Attribute):
491
+ call_func = node.value.func.attr
492
+ if call_func in {"match", "search", "escape", "quote", "int", "float", "isidentifier"}:
493
+ self.mitigations.append({
494
+ "kind": "validation",
495
+ "func": call_func,
496
+ "line": getattr(node, "lineno", 0),
497
+ })
498
+
499
+ self.generic_visit(node)
500
+
501
+ def visit_Call(self, node: ast.Call) -> None:
502
+ self.operators["Call"] += 1
503
+ func_name = ""
504
+ full_resolved = ""
505
+ has_shell_false = False
506
+
507
+ if isinstance(node.func, ast.Name):
508
+ func_name = node.func.id
509
+ full_resolved = self.alias_map.get(func_name, func_name)
510
+ elif isinstance(node.func, ast.Attribute):
511
+ attr_name = node.func.attr
512
+ val_name = ""
513
+ if isinstance(node.func.value, ast.Name):
514
+ val_name = self.alias_map.get(node.func.value.id, node.func.value.id)
515
+ func_name = attr_name
516
+ full_resolved = f"{val_name}.{attr_name}" if val_name else attr_name
517
+ elif (
518
+ isinstance(node.func, ast.Call)
519
+ and isinstance(node.func.func, ast.Name)
520
+ and node.func.func.id == "getattr"
521
+ ):
522
+ if len(node.func.args) >= 2:
523
+ if isinstance(node.func.args[1], ast.Constant) and isinstance(node.func.args[1].value, str):
524
+ func_name = node.func.args[1].value
525
+ full_resolved = func_name
526
+ elif isinstance(node.func.args[1], ast.Name) and getattr(self, "current_env", {}):
527
+ v_obj = self.current_env.get(node.func.args[1].id)
528
+ if v_obj:
529
+ func_name = getattr(v_obj, "value", "")
530
+ full_resolved = func_name
531
+
532
+ # 1. 绝对高危特征判定 (一票置顶 Sink)
533
+ # 反序列化
534
+ if "pickle.loads" in full_resolved or (full_resolved == "loads" and "pickle" in self.imports):
535
+ self.critical_sinks.append({
536
+ "kind": "rce_deserialization",
537
+ "sink": full_resolved,
538
+ "line": getattr(node, "lineno", 0),
539
+ })
540
+ elif "yaml.load" in full_resolved:
541
+ has_safe_loader = False
542
+ for kw in node.keywords:
543
+ if kw.arg == "Loader":
544
+ kw_val = ast.unparse(kw.value) if hasattr(ast, "unparse") else ""
545
+ if "SafeLoader" in kw_val:
546
+ has_safe_loader = True
547
+ if not has_safe_loader:
548
+ self.critical_sinks.append({
549
+ "kind": "rce_deserialization",
550
+ "sink": "yaml.load",
551
+ "line": getattr(node, "lineno", 0),
552
+ })
553
+ else:
554
+ self.mitigations.append({
555
+ "kind": "safe_deserializer",
556
+ "sink": "yaml.SafeLoader",
557
+ "line": getattr(node, "lineno", 0),
558
+ })
559
+ elif "yaml.safe_load" in full_resolved:
560
+ self.mitigations.append({
561
+ "kind": "safe_deserializer",
562
+ "sink": "yaml.safe_load",
563
+ "line": getattr(node, "lineno", 0),
564
+ })
565
+
566
+ # 命令执行
567
+ if full_resolved in {"os.system", "system", "posix.system"} or (
568
+ full_resolved in {"subprocess.Popen", "Popen", "subprocess.call", "call", "subprocess.run", "run"}
569
+ ):
570
+ has_shell_true = False
571
+ has_shell_false = False
572
+ for kw in node.keywords:
573
+ if kw.arg == "shell":
574
+ if isinstance(kw.value, ast.Constant) and kw.value.value is True:
575
+ has_shell_true = True
576
+ elif isinstance(kw.value, ast.Constant) and kw.value.value is False:
577
+ has_shell_false = True
578
+
579
+ if has_shell_true or full_resolved in {"os.system", "system"}:
580
+ self.critical_sinks.append({
581
+ "kind": "command_injection",
582
+ "sink": full_resolved,
583
+ "line": getattr(node, "lineno", 0),
584
+ })
585
+ elif has_shell_false:
586
+ self.mitigations.append({
587
+ "kind": "safe_subprocess",
588
+ "sink": f"{full_resolved}(shell=False)",
589
+ "line": getattr(node, "lineno", 0),
590
+ })
591
+
592
+ # 2. 污点汇聚流检测 (排除显式 safe_subprocess)
593
+ target_sinks = {
594
+ "system", "popen", "call", "check_call", "check_output", "run",
595
+ "eval", "exec", "loads", "execute", "raw_query", "query",
596
+ "render_template_string", "from_string", "open", "read",
597
+ }
598
+ if not has_shell_false and (func_name.lower() in target_sinks or full_resolved.lower() in target_sinks):
599
+ for a in node.args:
600
+ arg_vars = {child.id for child in ast.walk(a) if isinstance(child, ast.Name)}
601
+ tainted_hits = arg_vars.intersection(self.tainted_vars)
602
+ if tainted_hits or isinstance(a, ast.JoinedStr):
603
+ hits = sorted(tainted_hits) if tainted_hits else ["<f-string>"]
604
+ self.taints.append({
605
+ "func": getattr(self, "current_func_name", "") or "unknown",
606
+ "sink": full_resolved or func_name,
607
+ "source_vars": hits,
608
+ "line": getattr(node, "lineno", 0),
609
+ })
610
+ break
611
+ self.generic_visit(node)
612
+
613
+ def visit_Name(self, node: ast.Name) -> None:
614
+ self.operands[node.id] += 1
615
+ self.generic_visit(node)
616
+
617
+ def visit_Constant(self, node: ast.Constant) -> None:
618
+ self.operands[str(type(node.value))] += 1
619
+ self.generic_visit(node)
620
+
621
+ visitor = Visitor()
622
+ visitor.visit(tree)
623
+
624
+ n1 = len(visitor.operators)
625
+ n2 = len(visitor.operands)
626
+ vocab = max(2, n1 + n2)
627
+ length = max(1, sum(visitor.operators.values()) + sum(visitor.operands.values()))
628
+ halstead_v = length * math.log2(vocab)
629
+
630
+ cc = 1 + visitor.branches
631
+ safe_sloc = max(1, sloc)
632
+ raw_mi = 171.0 - 5.2 * math.log(max(1.0, halstead_v)) - 0.23 * cc - 16.2 * math.log(safe_sloc)
633
+ norm_mi = round(max(0.0, min(100.0, raw_mi * 100.0 / 171.0)), 1)
634
+
635
+ return {
636
+ "cc": cc,
637
+ "cognitive": visitor.cognitive,
638
+ "cognitive_complexity": visitor.cognitive,
639
+ "max_depth": max(1, visitor.max_d),
640
+ "functions": visitor.func_count,
641
+ "classes": visitor.class_count,
642
+ "god_functions": visitor.god_funcs,
643
+ "taint_flows": visitor.taints,
644
+ "critical_sinks": visitor.critical_sinks,
645
+ "mitigations": visitor.mitigations,
646
+ "imports": visitor.imports,
647
+ "halstead_volume": round(halstead_v, 2),
648
+ "maintainability_index": norm_mi,
649
+ }
650
+
651
+
652
+
653
+ def _analyze_c_family_structure(lines: list[str], sloc: int = 1, language: str = "") -> dict[str, Any]:
654
+ """Lexical scanner for branch complexity, cognitive load, indentation depth, functions and classes."""
655
+ branches = 0
656
+ funcs = 0
657
+ classes = 0
658
+ max_depth = 0
659
+ cognitive = 0
660
+ imports: list[str] = []
661
+
662
+ for l in lines:
663
+ s = l.strip()
664
+ if not s or s.startswith(("//", "/*", "*")):
665
+ continue
666
+ leading_spaces = len(l) - len(l.lstrip(" "))
667
+ depth = leading_spaces // 2
668
+ if depth > max_depth:
669
+ max_depth = depth
670
+
671
+ found_branches = len(_C_BRANCH_RE.findall(s))
672
+ branches += found_branches
673
+ if found_branches > 0:
674
+ cognitive += (found_branches + depth)
675
+
676
+ if _C_FUNC_RE.search(s):
677
+ funcs += 1
678
+ if _C_CLASS_RE.search(s):
679
+ classes += 1
680
+
681
+ m_imp = re.search(r"""(?:import|require)\s*\(?['"]([^'"]+)['"]""", s)
682
+ if m_imp:
683
+ imports.append(m_imp.group(1))
684
+
685
+ taints: list[dict[str, Any]] = []
686
+ dynamic_langs = {"javascript", "typescript", "php", "ruby"}
687
+ if language in dynamic_langs:
688
+ try:
689
+ flow_analyzer = DynamicFlowAnalyzer(language=language)
690
+ line_env = flow_analyzer.fold_line_scope(lines)
691
+ tainted_vars = {k: v for k, v in line_env.items() if v.is_tainted}
692
+
693
+ sink_patterns = [
694
+ re.compile(r'\b(eval|exec|execSync|spawn|spawnSync|system|passthru|shell_exec|popen|proc_open)\s*\(([^)]*)\)'),
695
+ re.compile(r'\b(query|execute|rawQuery)\s*\(([^)]*)\)'),
696
+ ]
697
+ for lineno, line in enumerate(lines, 1):
698
+ s = line.strip().split("//")[0].split("#")[0].strip()
699
+ if not s:
700
+ continue
701
+ for pat in sink_patterns:
702
+ m = pat.search(s)
703
+ if m:
704
+ sink_name = m.group(1)
705
+ args_expr = m.group(2) if len(m.groups()) >= 2 else ""
706
+ hit_sources = [
707
+ vname for vname in tainted_vars
708
+ if re.search(rf"(?<![A-Za-z0-9_$]){re.escape(vname)}(?![A-Za-z0-9_$])", args_expr)
709
+ ]
710
+ if not hit_sources and flow_analyzer.has_framework_source(args_expr):
711
+ hit_sources = ["<framework_source>"]
712
+ if hit_sources:
713
+ taints.append({
714
+ "func": "unknown",
715
+ "sink": sink_name,
716
+ "source_vars": hit_sources,
717
+ "line": lineno,
718
+ })
719
+ break
720
+ except Exception:
721
+ taints = []
722
+
723
+ safe_sloc = max(1, sloc)
724
+ cc = 1 + branches
725
+ halstead_v = safe_sloc * 4.5
726
+ raw_mi = 171.0 - 5.2 * math.log(max(1.0, halstead_v)) - 0.23 * cc - 16.2 * math.log(safe_sloc)
727
+ norm_mi = round(max(0.0, min(100.0, raw_mi * 100.0 / 171.0)), 1)
728
+
729
+ return {
730
+ "cc": cc,
731
+ "cognitive": cognitive,
732
+ "cognitive_complexity": cognitive,
733
+ "max_depth": max(1, max_depth),
734
+ "functions": funcs,
735
+ "classes": classes,
736
+ "god_functions": 0,
737
+ "taint_flows": taints,
738
+ "imports": imports,
739
+ "halstead_volume": round(halstead_v, 2),
740
+ "maintainability_index": norm_mi,
741
+ }
742
+
743
+
744
+
745
+ def get_python_non_code_mask(raw_bytes: bytes) -> set[int]:
746
+ """Extract line numbers (1-indexed) of comments and standalone docstrings."""
747
+ mask: set[int] = set()
748
+ try:
749
+ tokens = list(tokenize.tokenize(io.BytesIO(raw_bytes).readline))
750
+ prev_tok = None
751
+ for tok in tokens:
752
+ tok_type, _, (srow, _), (erow, _), _ = tok
753
+ if tok_type == tokenize.COMMENT:
754
+ mask.add(srow)
755
+ elif tok_type == tokenize.STRING:
756
+ if prev_tok is None or prev_tok.type in (
757
+ tokenize.INDENT, tokenize.NEWLINE, tokenize.NL, tokenize.ENCODING
758
+ ):
759
+ for r in range(srow, erow + 1):
760
+ mask.add(r)
761
+ if tok_type not in (tokenize.NL, tokenize.COMMENT, tokenize.ENCODING):
762
+ prev_tok = tok
763
+ except Exception:
764
+ pass
765
+ return mask
766
+
767
+
768
+ def get_c_family_non_code_mask(text: str) -> set[int]:
769
+ """Extract line numbers of comments in C-family / JS / Go source code."""
770
+ non_code_lines: set[int] = set()
771
+ in_block_comment = False
772
+ for idx, line in enumerate(text.splitlines(), 1):
773
+ s = line.strip()
774
+ if in_block_comment:
775
+ non_code_lines.add(idx)
776
+ if "*/" in s:
777
+ in_block_comment = False
778
+ continue
779
+ if s.startswith("/*"):
780
+ non_code_lines.add(idx)
781
+ if "*/" not in s:
782
+ in_block_comment = True
783
+ continue
784
+ if s.startswith(("//", "#", "*")):
785
+ non_code_lines.add(idx)
786
+ return non_code_lines
787
+
788
+
789
+ def scan_sensitive_sinks(
790
+ text: str,
791
+ *,
792
+ non_code_mask: set[int] | None = None,
793
+ ) -> int:
794
+ """Return total count of sensitive sink patterns found in active code (excluding comments/docstrings)."""
795
+ if not text:
796
+ return 0
797
+
798
+ lines = text.splitlines()
799
+ line_offsets = []
800
+ curr = 0
801
+ for l in lines:
802
+ line_offsets.append(curr)
803
+ curr += len(l) + 1
804
+
805
+ import bisect
806
+
807
+ total = 0
808
+ for sink_name, pattern in _SENSITIVE_SINKS.items():
809
+ for m in pattern.finditer(text):
810
+ start_pos = m.start()
811
+ lineno = bisect.bisect_right(line_offsets, start_pos)
812
+ if non_code_mask and lineno in non_code_mask:
813
+ continue
814
+
815
+ matched_text = m.group(0)
816
+ if sink_name == "unsafe_deserial" and "yaml.load" in matched_text:
817
+ line_content = lines[lineno - 1] if 0 <= lineno - 1 < len(lines) else ""
818
+ if "SafeLoader" in line_content or "yaml.safe_load" in line_content:
819
+ continue
820
+
821
+ total += 1
822
+ return total
823
+
824
+
825
+ def calculate_shannon_entropy(text: str) -> float:
826
+ """Calculate Shannon information entropy of a string."""
827
+ if not text:
828
+ return 0.0
829
+ freq = Counter(text)
830
+ length = float(len(text))
831
+ return -sum((c / length) * math.log2(c / length) for c in freq.values())
832
+
833
+
834
+ _SECRET_KEYWORD_RE = re.compile(
835
+ r"(?i)(?:api[_-]?key|secret|token|password|passwd|auth|bearer|credentials|private[_-]?key)"
836
+ )
837
+ _SECRET_VALUE_RE = re.compile(
838
+ r"""['"]([a-zA-Z0-9_\-\.\$\/+=]{20,120})['"]"""
839
+ )
840
+
841
+
842
+ def scan_high_entropy_secrets(text: str) -> list[dict[str, Any]]:
843
+ """Scan text for high-entropy strings and secret patterns."""
844
+ secrets = []
845
+ lines = text.splitlines()
846
+ for idx, line in enumerate(lines, 1):
847
+ s_line = line.strip()
848
+ if not s_line or s_line.startswith(("#", "//", "/*", "*")):
849
+ continue
850
+ has_secret_kw = bool(_SECRET_KEYWORD_RE.search(s_line))
851
+ for m in _SECRET_VALUE_RE.finditer(s_line):
852
+ val = m.group(1)
853
+ if val.startswith(("http://", "https://", "ftp://", "file://")):
854
+ continue
855
+ if val.count("/") >= 3 or val.count("\\") >= 3:
856
+ continue
857
+ if re.match(r"^[0-9a-f]{32,64}$", val):
858
+ continue
859
+ if len(set(val)) <= 8:
860
+ continue
861
+
862
+ ent = calculate_shannon_entropy(val)
863
+ if ent >= 4.3 or (has_secret_kw and ent >= 3.6):
864
+ masked = val[:4] + "****" + val[-4:] if len(val) >= 12 else "****"
865
+ secrets.append({
866
+ "line": idx,
867
+ "entropy": round(ent, 2),
868
+ "masked": masked,
869
+ })
870
+ if len(secrets) >= 5:
871
+ break
872
+ if len(secrets) >= 5:
873
+ break
874
+ return secrets
875
+
876
+
877
+ def analyze_file_risk(
878
+ path: Path | str,
879
+ language: str,
880
+ sloc: int,
881
+ is_test: bool,
882
+ *,
883
+ raw_bytes: bytes | None = None,
884
+ ) -> dict[str, Any]:
885
+ """Extract structural complexity, sensitive sinks, cognitive load and intrinsic risk for a single file.
886
+
887
+ ``raw_bytes`` lets a caller that already read the file hand the bytes down so
888
+ a single analysis pass reads every file at most once; omitting it preserves
889
+ the original single-file behaviour.
890
+ """
891
+ if raw_bytes is None:
892
+ try:
893
+ raw_bytes = Path(path).read_bytes()
894
+ except OSError:
895
+ return {
896
+ "cc": 1, "cognitive": 0, "max_depth": 1, "functions": 0, "classes": 0,
897
+ "god_functions": 0, "god_module": False, "sinks": 0,
898
+ "taint_flows": [], "critical_sinks": [], "mitigations": [], "secrets": [], "imports": [], "maintainability_index": 100.0,
899
+ "risk_score": 0.0, "tags": [],
900
+ }
901
+ text = raw_bytes.decode("utf-8", errors="ignore")
902
+
903
+ if language == "python":
904
+ struct = _analyze_python_ast(raw_bytes, sloc=sloc)
905
+ non_code_mask = get_python_non_code_mask(raw_bytes)
906
+ elif language in {
907
+ "javascript", "typescript", "go", "java", "kotlin", "rust",
908
+ "c", "cpp", "csharp", "swift", "vue", "svelte", "dart",
909
+ "php", "ruby",
910
+ }:
911
+ struct = _analyze_c_family_structure(text.splitlines(), sloc=sloc, language=language)
912
+ non_code_mask = get_c_family_non_code_mask(text)
913
+ else:
914
+ struct = {
915
+ "cc": 1, "cognitive": 0, "max_depth": 1, "functions": 0, "classes": 0,
916
+ "god_functions": 0, "taint_flows": [], "critical_sinks": [], "mitigations": [], "imports": [], "maintainability_index": 100.0,
917
+ }
918
+ non_code_mask = set()
919
+
920
+ sinks = scan_sensitive_sinks(text, non_code_mask=non_code_mask)
921
+ secrets = scan_high_entropy_secrets(text) if not is_test else []
922
+ taints = struct.get("taint_flows", [])
923
+ critical_sinks = struct.get("critical_sinks", [])
924
+ mitigations = struct.get("mitigations", [])
925
+ cc = struct.get("cc", 1)
926
+ cognitive = struct.get("cognitive", 0)
927
+ max_depth = struct.get("max_depth", 1)
928
+ mi = struct.get("maintainability_index", 100.0)
929
+
930
+ # God Module: only for production code
931
+ is_god_module = False
932
+ if not is_test and (sloc > 1500 or cc > 80):
933
+ is_god_module = True
934
+
935
+ tags = []
936
+ if is_god_module:
937
+ tags.append("god-module")
938
+ if struct.get("god_functions", 0) > 0:
939
+ tags.append("god-function")
940
+ if cc > 25:
941
+ tags.append("high-cc")
942
+ if cognitive > 30:
943
+ tags.append("high-cognitive")
944
+ if sinks >= 3:
945
+ tags.append("sensitive-sinks")
946
+ if max_depth >= 5:
947
+ tags.append("deep-nesting")
948
+ if len(taints) > 0:
949
+ tags.append("critical-taint")
950
+ if len(critical_sinks) > 0:
951
+ tags.append("critical-sink")
952
+ if len(mitigations) > 0:
953
+ tags.append("mitigated-control")
954
+ if len(secrets) > 0:
955
+ tags.append("hardcoded-secret")
956
+ if mi < 40.0:
957
+ tags.append("low-maintainability")
958
+
959
+ # Composite Risk score calculation (0 ~ 100) - 彻底废除复杂度即风险,确立高危一票置顶
960
+ if len(critical_sinks) > 0 or len(taints) > 0:
961
+ # 基准分直接锁定 80+
962
+ base_score = 80.0 + min(len(critical_sinks) * 5.0 + len(taints) * 5.0, 15.0)
963
+ # 如果存在有效防御且无裸露高危
964
+ if len(mitigations) > 0 and len(critical_sinks) == 0:
965
+ base_score = max(20.0, base_score - len(mitigations) * 30.0)
966
+ else:
967
+ # 无绝对高危 Sink 时,根据结构复杂度与防御进行基准打分,上限压制在 50 分以下
968
+ base_score = min(
969
+ 45.0,
970
+ (cc * 0.2)
971
+ + (cognitive * 0.1)
972
+ + (sinks * 3.0)
973
+ + (len(secrets) * 6.0)
974
+ + (max_depth * 1.5)
975
+ + (10.0 if mi < 40.0 else 0.0),
976
+ )
977
+
978
+ risk_score = round(min(100.0, max(10.0, base_score)), 1)
979
+
980
+ return {
981
+ "cc": cc,
982
+ "cognitive": cognitive,
983
+ "max_depth": max_depth,
984
+ "functions": struct.get("functions", 0),
985
+ "classes": struct.get("classes", 0),
986
+ "god_functions": struct.get("god_functions", 0),
987
+ "god_module": is_god_module,
988
+ "sinks": sinks,
989
+ "taint_flows": taints,
990
+ "critical_sinks": critical_sinks,
991
+ "mitigations": mitigations,
992
+ "secrets": secrets,
993
+ "imports": struct.get("imports", []),
994
+ "maintainability_index": mi,
995
+ "risk_score": risk_score,
996
+ "tags": tags,
997
+ }
998
+
999
+
1000
+ def compute_health_grade(avg_cc: float, god_modules: int, test_ratio: float) -> str:
1001
+ """Deterministic engineering health rating (A / B / C / D)."""
1002
+ if avg_cc <= 8 and god_modules == 0 and test_ratio >= 0.4:
1003
+ return "A"
1004
+ elif avg_cc <= 15 and god_modules <= 2 and test_ratio >= 0.2:
1005
+ return "B"
1006
+ elif avg_cc <= 25 or test_ratio >= 0.1:
1007
+ return "C"
1008
+ else:
1009
+ return "D"
1010
+
1011
+
1012
+ def estimate_scale(sloc: int, primary_lang: str = "unknown") -> dict[str, Any]:
1013
+ """Estimate project scale level, recommended concurrency, and round budget."""
1014
+ if sloc < 5000:
1015
+ level = "micro"
1016
+ concurrency = 1
1017
+ rounds = 1
1018
+ budget = 30000
1019
+ elif sloc < 25000:
1020
+ level = "small"
1021
+ concurrency = 2
1022
+ rounds = 2
1023
+ budget = 80000
1024
+ elif sloc < 100000:
1025
+ level = "medium"
1026
+ concurrency = 3
1027
+ rounds = 3
1028
+ budget = 200000
1029
+ elif sloc < 500000:
1030
+ level = "large"
1031
+ concurrency = 4
1032
+ rounds = 5
1033
+ budget = 500000
1034
+ else:
1035
+ level = "giant"
1036
+ concurrency = 6
1037
+ rounds = 8
1038
+ budget = 1200000
1039
+
1040
+ return {
1041
+ "scale_level": level,
1042
+ "primary_language": primary_lang,
1043
+ "recommended_concurrency": concurrency,
1044
+ "recommended_rounds": rounds,
1045
+ "recommended_token_budget": budget,
1046
+ }
1047
+
1048
+
1049
+ def _window_digest(encoded_window: Sequence[bytes]) -> str:
1050
+ """Stable, collision-resistant digest for one clone-detection window.
1051
+
1052
+ The builtin ``hash()`` of a ``tuple[str, ...]`` is salted per process
1053
+ (``PYTHONHASHSEED``), so clone detection used to drift between runs and was
1054
+ not reproducible. ``blake2b`` is used instead: identical windows always map
1055
+ to the same digest in every process, and distinct windows cannot collide.
1056
+ Each line is length-prefixed so two different line sequences can never
1057
+ encode to the same payload.
1058
+ """
1059
+ hasher = hashlib.blake2b(digest_size=16)
1060
+ for line in encoded_window:
1061
+ hasher.update(len(line).to_bytes(4, "big"))
1062
+ hasher.update(line)
1063
+ return hasher.hexdigest()
1064
+
1065
+
1066
+ def detect_code_duplication(
1067
+ project_root: Path | str,
1068
+ prod_files: list[Any],
1069
+ window_size: int = 8,
1070
+ max_scan_files: int = 150,
1071
+ *,
1072
+ content_cache: Mapping[Path, str] | None = None,
1073
+ ) -> dict[str, Any]:
1074
+ """Detect clone blocks and code duplication ratio using sliding window hashing.
1075
+
1076
+ ``content_cache`` is an optional per-pass mapping of already-decoded file
1077
+ text (see ``analyze_codebase``) so a file is not read a second time just for
1078
+ duplication scanning. A missing entry falls back to reading from disk, so
1079
+ direct callers keep the original behaviour.
1080
+ """
1081
+ root_path = Path(project_root)
1082
+ block_map: dict[str, list[tuple[str, int]]] = defaultdict(list)
1083
+ total_prod_lines = 0
1084
+
1085
+ scan_targets = prod_files[:max_scan_files]
1086
+ for item in scan_targets:
1087
+ if isinstance(item, dict):
1088
+ rel = item.get("rel_path") or item.get("path", "")
1089
+ p = item.get("path")
1090
+ if not isinstance(p, Path):
1091
+ p = root_path / rel
1092
+ elif isinstance(item, (tuple, list)):
1093
+ rel = item[0]
1094
+ p = item[1]
1095
+ if not isinstance(p, Path):
1096
+ p = root_path / rel
1097
+ else:
1098
+ continue
1099
+
1100
+ content = content_cache.get(Path(p)) if content_cache is not None else None
1101
+ if content is None:
1102
+ try:
1103
+ content = p.read_text(encoding="utf-8", errors="ignore")
1104
+ except OSError:
1105
+ continue
1106
+
1107
+ cleaned = []
1108
+ for line in content.splitlines():
1109
+ s = line.strip()
1110
+ if not s or s.startswith(("#", "//", "/*", "*", '"""', "'''")):
1111
+ continue
1112
+ if len(s) < 3 or s in {"{", "}", "(", ")", "[", "]", ":", ";"}:
1113
+ continue
1114
+ cleaned.append(s)
1115
+
1116
+ total_prod_lines += len(cleaned)
1117
+
1118
+ if len(cleaned) >= window_size:
1119
+ encoded = [line.encode("utf-8") for line in cleaned]
1120
+ for i in range(len(cleaned) - window_size + 1):
1121
+ h = _window_digest(encoded[i:i + window_size])
1122
+ block_map[h].append((rel, i))
1123
+
1124
+ duplicated_files: set[str] = set()
1125
+ duplicated_line_count = 0
1126
+ top_clones: list[dict[str, Any]] = []
1127
+
1128
+ for h, occurrences in block_map.items():
1129
+ if len(occurrences) < 2:
1130
+ continue
1131
+ distinct_occurrences = []
1132
+ last_file = ""
1133
+ last_idx = -100
1134
+ for f, idx in occurrences:
1135
+ if f != last_file or (idx - last_idx) >= window_size:
1136
+ distinct_occurrences.append((f, idx))
1137
+ last_file = f
1138
+ last_idx = idx
1139
+
1140
+ if len(distinct_occurrences) >= 2:
1141
+ for f, _ in distinct_occurrences:
1142
+ duplicated_files.add(f)
1143
+ duplicated_line_count += window_size
1144
+ if len(top_clones) < 3:
1145
+ files_involved = sorted(set(f for f, _ in distinct_occurrences))
1146
+ top_clones.append({
1147
+ "files": files_involved[:4],
1148
+ "lines_count": window_size,
1149
+ "occurrences": len(distinct_occurrences),
1150
+ })
1151
+
1152
+ dup_ratio = round(min(100.0, (duplicated_line_count / max(1, total_prod_lines)) * 100.0), 1)
1153
+ return {
1154
+ "duplicated_lines": duplicated_line_count,
1155
+ "duplicate_lines": duplicated_line_count,
1156
+ "duplication_percentage": dup_ratio,
1157
+ "duplication_ratio": dup_ratio,
1158
+ "duplicated_files_count": len(duplicated_files),
1159
+ "top_clones": top_clones,
1160
+ "clone_blocks": top_clones,
1161
+ }
1162
+
1163
+
1164
+ def analyze_architecture_dependencies(
1165
+ arg1: Any,
1166
+ arg2: Any = None,
1167
+ ) -> dict[str, Any]:
1168
+ """Analyze architecture dependency graph, detect circular dependencies via Tarjan SCC, and measure instability."""
1169
+ if arg2 is not None:
1170
+ file_import_map = arg2
1171
+ elif isinstance(arg1, dict):
1172
+ file_import_map = arg1
1173
+ elif isinstance(arg1, list):
1174
+ file_import_map = {}
1175
+ for item in arg1:
1176
+ if isinstance(item, dict):
1177
+ file_import_map[item.get("rel_path") or item.get("module", "")] = item.get("imports", [])
1178
+ else:
1179
+ file_import_map = {}
1180
+
1181
+ all_files = set(file_import_map.keys())
1182
+ mod_to_file: dict[str, str] = {}
1183
+ for f in all_files:
1184
+ no_ext = f.rsplit(".", 1)[0]
1185
+ mod_to_file[no_ext] = f
1186
+ mod_to_file[no_ext.replace("/", ".")] = f
1187
+ mod_to_file[Path(f).name] = f
1188
+ mod_to_file[Path(f).stem] = f
1189
+
1190
+ graph: dict[str, set[str]] = defaultdict(set)
1191
+ in_degrees: Counter[str] = Counter()
1192
+ out_degrees: Counter[str] = Counter()
1193
+
1194
+ for src_file, raw_imports in file_import_map.items():
1195
+ for imp in raw_imports:
1196
+ target = mod_to_file.get(imp)
1197
+ if not target and "/" in imp:
1198
+ target = mod_to_file.get(imp.split("/")[-1])
1199
+ if target and target != src_file and target in all_files:
1200
+ graph[src_file].add(target)
1201
+
1202
+ for src, targets in graph.items():
1203
+ out_degrees[src] += len(targets)
1204
+ for t in targets:
1205
+ in_degrees[t] += 1
1206
+
1207
+ idx = 0
1208
+ indices: dict[str, int] = {}
1209
+ lowlink: dict[str, int] = {}
1210
+ on_stack: set[str] = set()
1211
+ stack: list[str] = []
1212
+ cycles: list[list[str]] = []
1213
+
1214
+ def strongconnect(node: str) -> None:
1215
+ nonlocal idx
1216
+ indices[node] = idx
1217
+ lowlink[node] = idx
1218
+ idx += 1
1219
+ stack.append(node)
1220
+ on_stack.add(node)
1221
+
1222
+ for neighbor in graph.get(node, ()):
1223
+ if neighbor not in indices:
1224
+ strongconnect(neighbor)
1225
+ lowlink[node] = min(lowlink[node], lowlink[neighbor])
1226
+ elif neighbor in on_stack:
1227
+ lowlink[node] = min(lowlink[node], indices[neighbor])
1228
+
1229
+ if lowlink[node] == indices[node]:
1230
+ scc = []
1231
+ while True:
1232
+ w = stack.pop()
1233
+ on_stack.remove(w)
1234
+ scc.append(w)
1235
+ if w == node:
1236
+ break
1237
+ if len(scc) > 1:
1238
+ cycles.append(scc)
1239
+
1240
+ for node in list(all_files):
1241
+ if node not in indices:
1242
+ strongconnect(node)
1243
+
1244
+ cycles.sort(key=len, reverse=True)
1245
+
1246
+ unstable_modules = []
1247
+ module_couplings = []
1248
+ for f in all_files:
1249
+ ca = in_degrees[f]
1250
+ ce = out_degrees[f]
1251
+ instability = round(ce / (ca + ce), 2) if (ca + ce) > 0 else 0.0
1252
+ module_couplings.append({
1253
+ "module": f,
1254
+ "fan_in": ca,
1255
+ "fan_out": ce,
1256
+ "instability": instability,
1257
+ })
1258
+ if (ca + ce) > 0 and instability >= 0.75 and ce >= 2:
1259
+ unstable_modules.append({
1260
+ "file": f,
1261
+ "instability": instability,
1262
+ "fan_in": ca,
1263
+ "fan_out": ce,
1264
+ })
1265
+
1266
+ unstable_modules.sort(key=lambda x: (x["instability"], x["fan_out"]), reverse=True)
1267
+
1268
+ return {
1269
+ "total_cycles": len(cycles),
1270
+ "circular_dependencies_count": len(cycles),
1271
+ "cycles": [c[:6] for c in cycles[:5]],
1272
+ "circular_dependency_cycles": [c[:6] for c in cycles[:5]],
1273
+ "unstable_modules": unstable_modules[:5],
1274
+ "highest_instability_modules": unstable_modules[:5],
1275
+ "module_couplings": module_couplings,
1276
+ "avg_afferent_coupling": round(sum(in_degrees.values()) / max(1, len(all_files)), 1),
1277
+ "avg_efferent_coupling": round(sum(out_degrees.values()) / max(1, len(all_files)), 1),
1278
+ }
1279
+
1280
+
1281
+ def calculate_cocomo_and_debt(
1282
+ sloc: int,
1283
+ god_modules: int = 0,
1284
+ god_functions: int = 0,
1285
+ cycles_count: int = 0,
1286
+ taint_count: int = 0,
1287
+ secrets_count: int = 0,
1288
+ high_cc_count: int = 0,
1289
+ sinks_count: int = 0,
1290
+ duplicate_lines: int = 0,
1291
+ secret_count: int = 0,
1292
+ complex_files_count: int = 0,
1293
+ **kwargs: Any,
1294
+ ) -> dict[str, Any]:
1295
+ """Calculate COCOMO II development baseline and technical debt remediation effort."""
1296
+ eff_secrets = secrets_count or secret_count
1297
+ eff_high_cc = high_cc_count or complex_files_count
1298
+
1299
+ ksloc = sloc / 1000.0
1300
+ effort_pm = max(0.1, round(2.4 * (ksloc ** 1.05), 1))
1301
+ schedule_months = max(0.5, round(2.5 * (effort_pm ** 0.38), 1))
1302
+
1303
+ tech_debt = (
1304
+ (god_modules * 2.0)
1305
+ + (god_functions * 1.5)
1306
+ + (cycles_count * 1.0)
1307
+ + (taint_count * 0.5)
1308
+ + (eff_secrets * 0.5)
1309
+ + (eff_high_cc * 0.3)
1310
+ + (sinks_count * 0.1)
1311
+ + (duplicate_lines * 0.01)
1312
+ )
1313
+ debt_days = round(tech_debt, 1)
1314
+ debt_ratio = min(100.0, round((debt_days / max(1.0, effort_pm * 22.0)) * 100.0, 1))
1315
+
1316
+ debt_breakdown = {
1317
+ "god_modules_debt_days": round(god_modules * 2.0, 1),
1318
+ "god_functions_debt_days": round(god_functions * 1.5, 1),
1319
+ "circular_cycles_debt_days": round(cycles_count * 1.0, 1),
1320
+ "taint_exposure_debt_days": round(taint_count * 0.5, 1),
1321
+ "secret_exposure_debt_days": round(eff_secrets * 0.5, 1),
1322
+ "high_cc_debt_days": round(eff_high_cc * 0.3, 1),
1323
+ "sinks_debt_days": round(sinks_count * 0.1, 1),
1324
+ "duplication_debt_days": round(duplicate_lines * 0.01, 1),
1325
+ }
1326
+
1327
+ return {
1328
+ "effort_person_months": effort_pm,
1329
+ "cocomo_effort_pm": effort_pm,
1330
+ "estimated_schedule_months": schedule_months,
1331
+ "cocomo_schedule_months": schedule_months,
1332
+ "tech_debt_days": debt_days,
1333
+ "tech_debt_ratio_pct": debt_ratio,
1334
+ "tech_debt_ratio": debt_ratio,
1335
+ "debt_breakdown": debt_breakdown,
1336
+ }
1337
+
1338
+
1339
+
1340
+ def analyze_codebase(
1341
+ root: Path | str,
1342
+ files: Sequence[tuple[str, Path, int, str]] | None = None,
1343
+ *,
1344
+ max_files: int = 4000,
1345
+ ) -> dict[str, Any]:
1346
+ """Perform deterministic codebase line, scale, complexity & risk analysis."""
1347
+ project_root = Path(root).resolve()
1348
+
1349
+ if files is None:
1350
+ files_list = []
1351
+ for dirpath, dirnames, filenames in os.walk(project_root, topdown=True):
1352
+ dirnames[:] = [d for d in dirnames if d not in {
1353
+ ".git", ".bugx", ".opencode", ".codex", ".claude", ".cline",
1354
+ ".vscode", ".agents", ".cursor", ".gemini", "node_modules",
1355
+ ".venv", "venv", "__pycache__", "dist", "build", ".idea"
1356
+ } and not d.startswith(".")]
1357
+ for name in filenames:
1358
+ p = Path(dirpath) / name
1359
+ rel = str(p.relative_to(project_root).as_posix())
1360
+ files_list.append((rel, p, p.stat().st_size if p.is_file() else 0, ""))
1361
+ if len(files_list) >= max_files:
1362
+ break
1363
+ if len(files_list) >= max_files:
1364
+ break
1365
+ files = files_list
1366
+
1367
+ lang_stats: dict[str, dict[str, Any]] = {}
1368
+ module_stats: dict[str, dict[str, int]] = {}
1369
+
1370
+ total_files = 0
1371
+ total_lines = 0
1372
+ total_sloc = 0
1373
+ total_comments = 0
1374
+ total_docstrings = 0
1375
+ total_blanks = 0
1376
+
1377
+ code_files = 0
1378
+ code_sloc = 0
1379
+ doc_config_lines = 0
1380
+
1381
+ prod_sloc = 0
1382
+ test_sloc = 0
1383
+ prod_files = 0
1384
+ test_files = 0
1385
+
1386
+ # Risk metrics accumulators
1387
+ total_cc = 0
1388
+ max_cc = 0
1389
+ total_cognitive = 0
1390
+ max_cognitive = 0
1391
+ total_funcs = 0
1392
+ total_classes = 0
1393
+ total_god_funcs = 0
1394
+ total_god_modules = 0
1395
+ total_sinks = 0
1396
+ all_taints: list[dict[str, Any]] = []
1397
+ all_critical_sinks: list[dict[str, Any]] = []
1398
+ all_secrets: list[dict[str, Any]] = []
1399
+ maintainability_scores: list[float] = []
1400
+ file_import_map: dict[str, list[str]] = {}
1401
+ prod_files_list: list[tuple[str, Path, int, str]] = []
1402
+ # Per-pass cache of decoded production source text. ``count_file_lines``,
1403
+ # ``analyze_file_risk`` and ``detect_code_duplication`` used to read every
1404
+ # file separately; the bytes are now read once here and handed down. The
1405
+ # cache lives only for this ``analyze_codebase`` call, so it can never serve
1406
+ # stale content to a later pass over a changed workspace.
1407
+ prod_text_cache: dict[Path, str] = {}
1408
+ hotspots: list[dict[str, Any]] = []
1409
+
1410
+ for rel, abs_path, size, _ in files:
1411
+ ext = Path(rel).suffix.casefold()
1412
+ lang = LANGUAGE_BY_EXTENSION.get(ext)
1413
+ if not lang:
1414
+ continue
1415
+
1416
+ file_path = Path(abs_path)
1417
+ try:
1418
+ raw_bytes = file_path.read_bytes()
1419
+ except OSError:
1420
+ # count_file_lines() reported (0, 0, 0, 0, 0) for unreadable files
1421
+ # and the loop skipped them; keep that outcome without re-reading.
1422
+ continue
1423
+
1424
+ tot, blk, com, doc, sloc = count_file_lines(file_path, lang, raw_bytes=raw_bytes)
1425
+ if tot == 0 and sloc == 0:
1426
+ continue
1427
+
1428
+ total_files += 1
1429
+ total_lines += tot
1430
+ total_sloc += sloc
1431
+ total_comments += com
1432
+ total_docstrings += doc
1433
+ total_blanks += blk
1434
+
1435
+ is_code = lang in _CODE_LANGUAGES
1436
+ is_test = is_test_file(rel)
1437
+
1438
+ if is_code:
1439
+ code_files += 1
1440
+ code_sloc += sloc
1441
+ if is_test:
1442
+ test_sloc += sloc
1443
+ test_files += 1
1444
+ else:
1445
+ prod_sloc += sloc
1446
+ prod_files += 1
1447
+ prod_files_list.append((rel, abs_path, size, ""))
1448
+
1449
+ # Risk and structural analysis
1450
+ risk_info = analyze_file_risk(file_path, lang, sloc, is_test, raw_bytes=raw_bytes)
1451
+ cc = risk_info["cc"]
1452
+ cog = risk_info.get("cognitive", 0)
1453
+ total_cc += cc
1454
+ if cc > max_cc:
1455
+ max_cc = cc
1456
+ total_cognitive += cog
1457
+ if cog > max_cognitive:
1458
+ max_cognitive = cog
1459
+
1460
+ maintainability_scores.append(risk_info.get("maintainability_index", 100.0))
1461
+ if risk_info.get("critical_sinks"):
1462
+ for cs in risk_info["critical_sinks"]:
1463
+ all_critical_sinks.append({
1464
+ **cs,
1465
+ "file": rel,
1466
+ "location": rel,
1467
+ "source_file": rel,
1468
+ })
1469
+ if risk_info.get("taint_flows"):
1470
+ for tf in risk_info["taint_flows"]:
1471
+ all_taints.append({
1472
+ **tf,
1473
+ "file": rel,
1474
+ "location": rel,
1475
+ "source_file": rel,
1476
+ })
1477
+ if risk_info.get("secrets"):
1478
+ for sec in risk_info["secrets"]:
1479
+ all_secrets.append({
1480
+ **sec,
1481
+ "file": rel,
1482
+ "location": rel,
1483
+ "source_file": rel,
1484
+ })
1485
+ if risk_info.get("imports"):
1486
+ file_import_map[rel] = risk_info["imports"]
1487
+
1488
+ total_funcs += risk_info["functions"]
1489
+ total_classes += risk_info["classes"]
1490
+ total_god_funcs += risk_info["god_functions"]
1491
+ if risk_info["god_module"]:
1492
+ total_god_modules += 1
1493
+ total_sinks += risk_info["sinks"]
1494
+
1495
+ # Collect candidates for hotspots (production code with notable risk)
1496
+ if not is_test:
1497
+ prod_text_cache[file_path] = raw_bytes.decode("utf-8", errors="ignore")
1498
+ hotspots.append({
1499
+ "file": rel,
1500
+ "risk_score": risk_info["risk_score"],
1501
+ "cyclomatic_complexity": cc,
1502
+ "cognitive_complexity": cog,
1503
+ "maintainability_index": risk_info.get("maintainability_index", 100.0),
1504
+ "sensitive_sinks": risk_info["sinks"],
1505
+ "max_depth": risk_info["max_depth"],
1506
+ "sloc": sloc,
1507
+ "tags": risk_info["tags"],
1508
+ })
1509
+ else:
1510
+ doc_config_lines += sloc
1511
+
1512
+ # Language aggregate
1513
+ if lang not in lang_stats:
1514
+ lang_stats[lang] = {
1515
+ "files": 0, "total_lines": 0, "code_lines": 0,
1516
+ "comment_lines": 0, "docstring_lines": 0, "blank_lines": 0,
1517
+ "is_code": is_code,
1518
+ }
1519
+ lang_stats[lang]["files"] += 1
1520
+ lang_stats[lang]["total_lines"] += tot
1521
+ lang_stats[lang]["code_lines"] += sloc
1522
+ lang_stats[lang]["comment_lines"] += com
1523
+ lang_stats[lang]["docstring_lines"] += doc
1524
+ lang_stats[lang]["blank_lines"] += blk
1525
+
1526
+ # Module aggregate
1527
+ parts = rel.split("/")
1528
+ if len(parts) > 2 and parts[0] in {"src", "packages", "apps", "pkg"}:
1529
+ mod = f"{parts[0]}/{parts[1]}"
1530
+ elif len(parts) > 1:
1531
+ mod = parts[0]
1532
+ else:
1533
+ mod = "(root)"
1534
+
1535
+ if mod not in module_stats:
1536
+ module_stats[mod] = {"files": 0, "code_lines": 0, "total_lines": 0}
1537
+ module_stats[mod]["files"] += 1
1538
+ module_stats[mod]["code_lines"] += (sloc if is_code else 0)
1539
+ module_stats[mod]["total_lines"] += tot
1540
+
1541
+ # Sort languages
1542
+ languages_breakdown = []
1543
+ primary_lang = "unknown"
1544
+ highest_code_sloc = -1
1545
+
1546
+ for lang, s in sorted(
1547
+ lang_stats.items(),
1548
+ key=lambda x: (1 if x[1]["is_code"] else 0, x[1]["code_lines"]),
1549
+ reverse=True,
1550
+ ):
1551
+ if s["is_code"] and s["code_lines"] > highest_code_sloc:
1552
+ highest_code_sloc = s["code_lines"]
1553
+ primary_lang = lang
1554
+
1555
+ base_sloc = code_sloc if s["is_code"] else max(1, doc_config_lines)
1556
+ ratio = round((s["code_lines"] / max(1, base_sloc)) * 100, 1)
1557
+ languages_breakdown.append({
1558
+ "language": lang,
1559
+ "is_code": s["is_code"],
1560
+ "files": s["files"],
1561
+ "total_lines": s["total_lines"],
1562
+ "code_lines": s["code_lines"],
1563
+ "comment_lines": s["comment_lines"],
1564
+ "docstring_lines": s["docstring_lines"],
1565
+ "blank_lines": s["blank_lines"],
1566
+ "percentage": ratio,
1567
+ })
1568
+
1569
+ # Sort modules
1570
+ sorted_modules = sorted(module_stats.items(), key=lambda x: x[1]["code_lines"], reverse=True)
1571
+ modules_breakdown = []
1572
+ other_mod = {"files": 0, "code_lines": 0, "total_lines": 0}
1573
+
1574
+ for idx, (mod, s) in enumerate(sorted_modules):
1575
+ if idx < 15:
1576
+ ratio = round((s["code_lines"] / max(1, code_sloc if code_sloc > 0 else total_sloc)) * 100, 1)
1577
+ modules_breakdown.append({
1578
+ "module": mod,
1579
+ "files": s["files"],
1580
+ "code_lines": s["code_lines"],
1581
+ "total_lines": s["total_lines"],
1582
+ "percentage": ratio,
1583
+ })
1584
+ else:
1585
+ other_mod["files"] += s["files"]
1586
+ other_mod["code_lines"] += s["code_lines"]
1587
+ other_mod["total_lines"] += s["total_lines"]
1588
+
1589
+ if other_mod["files"] > 0:
1590
+ ratio = round((other_mod["code_lines"] / max(1, code_sloc if code_sloc > 0 else total_sloc)) * 100, 1)
1591
+ modules_breakdown.append({
1592
+ "module": "other",
1593
+ "files": other_mod["files"],
1594
+ "code_lines": other_mod["code_lines"],
1595
+ "total_lines": other_mod["total_lines"],
1596
+ "percentage": ratio,
1597
+ })
1598
+
1599
+ test_to_code_ratio = round(test_sloc / max(1, prod_sloc), 3) if prod_sloc > 0 else 0.0
1600
+ scale = estimate_scale(code_sloc if code_sloc > 0 else total_sloc, primary_lang)
1601
+
1602
+ avg_cc = round(total_cc / max(1, code_files), 1) if code_files > 0 else 1.0
1603
+ avg_cog = round(total_cognitive / max(1, code_files), 1) if code_files > 0 else 0.0
1604
+ avg_mi = round(sum(maintainability_scores) / max(1, len(maintainability_scores)), 1) if maintainability_scores else 100.0
1605
+ mi_grade = "🟢 良好" if avg_mi >= 65 else ("🟡 关注" if avg_mi >= 40 else "🔴 恶化")
1606
+
1607
+ health_grade = compute_health_grade(avg_cc, total_god_modules, test_to_code_ratio)
1608
+
1609
+ # Duplication analysis
1610
+ duplication_info = detect_code_duplication(
1611
+ project_root, prod_files_list, content_cache=prod_text_cache,
1612
+ )
1613
+
1614
+ # Architecture topology & cycles analysis
1615
+ architecture_info = analyze_architecture_dependencies(project_root, file_import_map)
1616
+
1617
+ # COCOMO & Technical debt calculation
1618
+ high_cc_count = sum(1 for h in hotspots if h["cyclomatic_complexity"] > 25)
1619
+ cocomo_debt_info = calculate_cocomo_and_debt(
1620
+ prod_sloc,
1621
+ total_god_modules,
1622
+ total_god_funcs,
1623
+ architecture_info.get("total_cycles", 0),
1624
+ len(all_taints),
1625
+ len(all_secrets),
1626
+ high_cc_count,
1627
+ total_sinks,
1628
+ )
1629
+
1630
+ # Sort hotspots by risk_score descending, keep top 5
1631
+ hotspots.sort(key=lambda x: x["risk_score"], reverse=True)
1632
+ top_hotspots = hotspots[:5]
1633
+
1634
+ return {
1635
+ "summary": {
1636
+ "total_files": total_files,
1637
+ "total_lines": total_lines,
1638
+ "code_lines": code_sloc if code_sloc > 0 else total_sloc,
1639
+ "doc_and_config_lines": doc_config_lines,
1640
+ "comment_lines": total_comments,
1641
+ "docstring_lines": total_docstrings,
1642
+ "blank_lines": total_blanks,
1643
+ "production_code_lines": prod_sloc,
1644
+ "production_files": prod_files,
1645
+ "test_code_lines": test_sloc,
1646
+ "test_files": test_files,
1647
+ "test_to_code_ratio": test_to_code_ratio,
1648
+ },
1649
+ "languages": languages_breakdown,
1650
+ "modules": modules_breakdown,
1651
+ "scale_estimation": scale,
1652
+ "maintainability": {
1653
+ "maintainability_index": avg_mi,
1654
+ "avg_maintainability_index": avg_mi,
1655
+ "maintainability_grade": mi_grade,
1656
+ "avg_cognitive_complexity": avg_cog,
1657
+ "max_cognitive_complexity": max_cognitive,
1658
+ },
1659
+
1660
+ "duplication": duplication_info,
1661
+ "architecture_topology": architecture_info,
1662
+ "engineering_economics": cocomo_debt_info,
1663
+ "risk_metrics": {
1664
+ "health_grade": health_grade,
1665
+ "avg_cyclomatic_complexity": avg_cc,
1666
+ "max_cyclomatic_complexity": max_cc,
1667
+ "total_functions": total_funcs,
1668
+ "total_classes": total_classes,
1669
+ "god_modules_count": total_god_modules,
1670
+ "god_functions_count": total_god_funcs,
1671
+ "total_sensitive_sinks": total_sinks,
1672
+ "total_taint_flows": len(all_taints),
1673
+ "total_hardcoded_secrets": len(all_secrets),
1674
+ "secrets": all_secrets,
1675
+ "critical_sinks": all_critical_sinks,
1676
+ "taint_flows": all_taints,
1677
+ "maintainability_index": avg_mi,
1678
+ "avg_cognitive_complexity": avg_cog,
1679
+ "duplication_percentage": duplication_info.get("duplication_percentage", 0.0),
1680
+ "circular_dependencies_count": architecture_info.get("total_cycles", 0),
1681
+ "tech_debt_days": cocomo_debt_info.get("tech_debt_days", 0.0),
1682
+ "top_risk_hotspots": top_hotspots,
1683
+ },
1684
+ }