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,1743 @@
1
+ """MCP & Skill Inspector, Marketplace, Sandboxed Credential Store, and Auto-Matcher for BugX WebUI (REQ-09 / DOC-255).
2
+
3
+ Responsibilities:
4
+ 1. Inspect mounted MCP servers from .mcp.json, .codebuddy/mcp.json, and .claude/mcp.json.
5
+ 2. Provide MCP Marketplace backed by core/supervisor_host.py MCP_REGISTRY.
6
+ 3. Isolate sensitive MCP credentials strictly outside the workspace in ~/.bugx/sandboxes/<project_hash>/mcp_env.json (0600).
7
+ 4. Provide Skill Marketplace aggregating core skills, domain skill packs (core/prompts/skills/*), and project/global skills.
8
+ 5. Run AI Capability Auto-Matching via project_profile + capability_planner and one-click provisioning.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import hashlib
14
+ import json
15
+ import os
16
+ from pathlib import Path
17
+ from typing import Any, Mapping
18
+
19
+
20
+ def _compute_proj_hash(ws: Path) -> str:
21
+ resolved = ws.resolve()
22
+ h = hashlib.sha256(str(resolved).encode("utf-8")).hexdigest()[:8]
23
+ return f"{resolved.name}-{h}"
24
+
25
+
26
+ def _sandbox_env_path(ws: Path) -> Path:
27
+ """纯路径解析:**不**创建目录、不 chmod。
28
+
29
+ 读路径绝不能有写副作用。旧实现把 ``mkdir`` 塞进 ``_sandbox_env_file``,
30
+ 每次只读检查(``bugx project settings``、WebUI 检查器、``doctor``)都会去
31
+ ``~/.bugx/sandboxes/<hash>/`` 建目录;一旦 HOME 不可写(只读分发、CI 沙箱、
32
+ 容器内 root-squash),这条**纯读**链路直接抛
33
+ ``PermissionError: [Errno 1] Operation not permitted``,把「没有凭据」误报成
34
+ 「项目配置获取失败」,整条 ``project settings`` 退出 1。
35
+ """
36
+ proj_hash = _compute_proj_hash(ws)
37
+ bugx_home = Path(os.environ.get("BUGX_HOME") or (Path.home() / ".bugx")).resolve()
38
+ return bugx_home / "sandboxes" / proj_hash / "mcp_env.json"
39
+
40
+
41
+ def _sandbox_env_file(ws: Path) -> Path:
42
+ """写路径:确保隔离目录存在且为 0700,再返回凭据文件路径。"""
43
+ env_file = _sandbox_env_path(ws)
44
+ sandbox_dir = env_file.parent
45
+ sandbox_dir.mkdir(parents=True, mode=0o700, exist_ok=True)
46
+ try:
47
+ os.chmod(sandbox_dir, 0o700)
48
+ except OSError:
49
+ pass
50
+ return env_file
51
+
52
+
53
+ def load_sandbox_mcp_env(workspace_path: Path | str) -> dict[str, dict[str, str]]:
54
+ """Load isolated MCP credentials from ~/.bugx/sandboxes/<project_hash>/mcp_env.json."""
55
+ env_file = _sandbox_env_path(Path(workspace_path))
56
+ if not env_file.is_file():
57
+ return {}
58
+ try:
59
+ data = json.loads(env_file.read_text(encoding="utf-8"))
60
+ if isinstance(data, dict):
61
+ return {
62
+ str(k): {str(ek): str(ev) for ek, ev in v.items() if ev is not None}
63
+ for k, v in data.items()
64
+ if isinstance(v, dict)
65
+ }
66
+ except Exception:
67
+ pass
68
+ return {}
69
+
70
+
71
+ def save_sandbox_mcp_env(
72
+ workspace_path: Path | str,
73
+ server_name: str,
74
+ env_vars: dict[str, str],
75
+ ) -> dict[str, Any]:
76
+ """Persist sensitive MCP credentials strictly outside the workspace with 0600 permissions (REQ-09)."""
77
+ ws = Path(workspace_path).resolve()
78
+ env_file = _sandbox_env_file(ws)
79
+ all_env = load_sandbox_mcp_env(ws)
80
+ srv_env = dict(all_env.get(server_name) or {})
81
+ for k, v in env_vars.items():
82
+ k_clean = str(k).strip()
83
+ if not k_clean:
84
+ continue
85
+ if v is None or str(v).strip() == "":
86
+ srv_env.pop(k_clean, None)
87
+ else:
88
+ srv_env[k_clean] = str(v).strip()
89
+ if srv_env:
90
+ all_env[server_name] = srv_env
91
+ else:
92
+ all_env.pop(server_name, None)
93
+
94
+ tmp = env_file.with_suffix(".tmp")
95
+ tmp.write_text(json.dumps(all_env, indent=2, ensure_ascii=False), encoding="utf-8")
96
+ try:
97
+ os.chmod(tmp, 0o600)
98
+ except OSError:
99
+ pass
100
+ tmp.replace(env_file)
101
+ try:
102
+ os.chmod(env_file, 0o600)
103
+ except OSError:
104
+ pass
105
+
106
+ # Scrub any accidental plaintext secret from workspace .mcp.json
107
+ mcp_path = ws / ".mcp.json"
108
+ if mcp_path.is_file():
109
+ try:
110
+ mcp_data = json.loads(mcp_path.read_text(encoding="utf-8"))
111
+ srv_cfg = (mcp_data.get("mcpServers") or {}).get(server_name)
112
+ if isinstance(srv_cfg, dict) and isinstance(srv_cfg.get("env"), dict):
113
+ changed = False
114
+ for k in list(srv_cfg["env"].keys()):
115
+ if k in srv_env:
116
+ srv_cfg["env"][k] = f"${{BUGX_SANDBOX_ENV:{k}}}"
117
+ changed = True
118
+ if changed:
119
+ mcp_path.write_text(json.dumps(mcp_data, indent=2, ensure_ascii=False), encoding="utf-8")
120
+ except Exception:
121
+ pass
122
+
123
+ return {
124
+ "ok": True,
125
+ "server": server_name,
126
+ "configured_keys": sorted(srv_env.keys()),
127
+ "sandbox_path": str(env_file),
128
+ }
129
+
130
+
131
+ def _load_mcp_registry() -> dict[str, dict[str, Any]]:
132
+ raw: Any = None
133
+ try:
134
+ from core.supervisor import supervisor_host
135
+ raw = getattr(supervisor_host, "MCP_REGISTRY", None)
136
+ except ImportError:
137
+ try:
138
+ from core import supervisor_host
139
+ raw = getattr(supervisor_host, "MCP_REGISTRY", None)
140
+ except Exception:
141
+ raw = None
142
+ if isinstance(raw, dict):
143
+ return dict(raw)
144
+ if isinstance(raw, (list, tuple)):
145
+ out: dict[str, dict[str, Any]] = {}
146
+ for item in raw:
147
+ if isinstance(item, dict):
148
+ key = str(item.get("id") or item.get("name") or "").strip()
149
+ if key:
150
+ out[key] = item
151
+ return out
152
+ return {}
153
+
154
+
155
+ ONLINE_MCP_CATALOG: dict[str, dict[str, Any]] = {
156
+ "github-mcp": {
157
+ "id": "github-mcp",
158
+ "name": "github-mcp",
159
+ "title": "GitHub 官方上下文与审查探针",
160
+ "category": "devops",
161
+ "author": "@modelcontextprotocol",
162
+ "stars": 5200,
163
+ "version": "0.6.2",
164
+ "package": "@modelcontextprotocol/server-github",
165
+ "installer": "npx",
166
+ "command": "npx",
167
+ "args": ["-y", "@modelcontextprotocol/server-github"],
168
+ "repo_url": "https://github.com/modelcontextprotocol/servers/tree/main/src/github",
169
+ "description": "提供 GitHub 仓库搜索、PR 审查、Issue 状态流转、Commit 差异对比及自动化审查评论能力。",
170
+ "tags": ["GitHub", "Git", "Code-Review", "PR"],
171
+ "required_credentials": ["GITHUB_PERSONAL_ACCESS_TOKEN"],
172
+ "tools": [
173
+ {"name": "create_or_update_file", "description": "在 GitHub 仓库中创建或更新指定文件", "parameters": "owner, repo, path, content, message, branch"},
174
+ {"name": "search_repositories", "description": "全局检索 GitHub 关联代码仓库", "parameters": "query, page, per_page"},
175
+ {"name": "get_issue", "description": "获取 GitHub Issue 详细内容与标签", "parameters": "owner, repo, issue_number"},
176
+ {"name": "create_pull_request", "description": "自动创建 Pull Request 并关联修复分支", "parameters": "owner, repo, title, head, base, body"},
177
+ {"name": "get_pull_request_diff", "description": "提取 PR 变动的 Unified Diff 补丁", "parameters": "owner, repo, pull_number"},
178
+ {"name": "create_issue_comment", "description": "在 PR 或 Issue 中发表安全审计评论", "parameters": "owner, repo, issue_number, body"},
179
+ ],
180
+ },
181
+ "filesystem-mcp": {
182
+ "id": "filesystem-mcp",
183
+ "name": "filesystem-mcp",
184
+ "title": "本地受控文件系统沙箱探针",
185
+ "category": "tools",
186
+ "author": "@modelcontextprotocol",
187
+ "stars": 4850,
188
+ "version": "0.6.0",
189
+ "package": "@modelcontextprotocol/server-filesystem",
190
+ "installer": "npx",
191
+ "command": "npx",
192
+ "args": ["-y", "@modelcontextprotocol/server-filesystem", "."],
193
+ "repo_url": "https://github.com/modelcontextprotocol/servers/tree/main/src/filesystem",
194
+ "description": "安全受控的本地文件与目录树交互探针,严格限制在指定沙箱目录白名单内,防止路径遍历穿越。",
195
+ "tags": ["Filesystem", "Sandbox", "IO", "Path-Security"],
196
+ "required_credentials": [],
197
+ "tools": [
198
+ {"name": "read_file", "description": "读取沙箱目录内指定文件的 UTF-8 文本内容", "parameters": "path"},
199
+ {"name": "write_file", "description": "向受控白名单路径写入文件(严禁目录穿越)", "parameters": "path, content"},
200
+ {"name": "list_directory", "description": "遍历指定目录树与文件元数据", "parameters": "path"},
201
+ {"name": "move_file", "description": "在受控目录间移动或重命名文件", "parameters": "source, destination"},
202
+ {"name": "get_file_info", "description": "提取文件大小、创建时间与权限位", "parameters": "path"},
203
+ ],
204
+ },
205
+ "postgres-mcp": {
206
+ "id": "postgres-mcp",
207
+ "name": "postgres-mcp",
208
+ "title": "PostgreSQL 关系型数据库只读安全探针",
209
+ "category": "storage",
210
+ "author": "@modelcontextprotocol",
211
+ "stars": 3940,
212
+ "version": "0.5.1",
213
+ "package": "@modelcontextprotocol/server-postgres",
214
+ "installer": "npx",
215
+ "command": "npx",
216
+ "args": ["-y", "@modelcontextprotocol/server-postgres", "postgresql://localhost/db"],
217
+ "repo_url": "https://github.com/modelcontextprotocol/servers/tree/main/src/postgres",
218
+ "description": "专为 PostgreSQL 数据库设计的元数据查询与安全审计探针,支持 Schema 提取与隔离只读查询。",
219
+ "tags": ["Postgres", "SQL", "Database", "Readonly"],
220
+ "required_credentials": ["POSTGRES_CONNECTION_STRING"],
221
+ "tools": [
222
+ {"name": "query", "description": "执行只读 SQL 查询并返回结构化数据行", "parameters": "sql"},
223
+ {"name": "get_schema", "description": "导出全部公共表、视图与列类型定义", "parameters": "schema"},
224
+ {"name": "list_tables", "description": "列举数据库中当前可用的全部表结构", "parameters": "schema"},
225
+ ],
226
+ },
227
+ "fetch-mcp": {
228
+ "id": "fetch-mcp",
229
+ "name": "fetch-mcp",
230
+ "title": "网页内容提取与 Markdown 转换探针",
231
+ "category": "tools",
232
+ "author": "@modelcontextprotocol",
233
+ "stars": 3680,
234
+ "version": "0.6.1",
235
+ "package": "mcp-server-fetch",
236
+ "installer": "uvx",
237
+ "command": "uvx",
238
+ "args": ["mcp-server-fetch"],
239
+ "repo_url": "https://github.com/modelcontextprotocol/servers/tree/main/src/fetch",
240
+ "description": "安全获取外部 HTTP/HTTPS 网页内容并自动转译为精简 Markdown,内嵌 SSRF 过滤与速率限制机制。",
241
+ "tags": ["Web", "Fetch", "Markdown", "SSRF-Safe"],
242
+ "required_credentials": [],
243
+ "tools": [
244
+ {"name": "fetch", "description": "抓取指定 URL 网页并将 HTML 清洗转为高质量 Markdown", "parameters": "url, max_length, start_index"},
245
+ ],
246
+ },
247
+ "brave-search-mcp": {
248
+ "id": "brave-search-mcp",
249
+ "name": "brave-search-mcp",
250
+ "title": "Brave 隐私优先全球网页检索探针",
251
+ "category": "search",
252
+ "author": "@modelcontextprotocol",
253
+ "stars": 3120,
254
+ "version": "0.5.0",
255
+ "package": "@modelcontextprotocol/server-brave-search",
256
+ "installer": "npx",
257
+ "command": "npx",
258
+ "args": ["-y", "@modelcontextprotocol/server-brave-search"],
259
+ "repo_url": "https://github.com/modelcontextprotocol/servers/tree/main/src/brave-search",
260
+ "description": "利用 Brave Search 官方 API 执行无隐私追踪的全球网页与技术资料检索,获取最新漏洞公告。",
261
+ "tags": ["Search", "Brave", "Web-Search", "CVE"],
262
+ "required_credentials": ["BRAVE_API_KEY"],
263
+ "tools": [
264
+ {"name": "brave_web_search", "description": "执行全球 Web 关键字检索并返回相关摘要", "parameters": "query, count"},
265
+ {"name": "brave_local_search", "description": "针对特定地理位置或服务执行本地搜索", "parameters": "query, count"},
266
+ ],
267
+ },
268
+ "sentry-mcp": {
269
+ "id": "sentry-mcp",
270
+ "name": "sentry-mcp",
271
+ "title": "Sentry 线上异常监控与崩溃堆栈追踪",
272
+ "category": "devops",
273
+ "author": "@modelcontextprotocol",
274
+ "stars": 2850,
275
+ "version": "0.4.0",
276
+ "package": "mcp-server-sentry",
277
+ "installer": "uvx",
278
+ "command": "uvx",
279
+ "args": ["mcp-server-sentry"],
280
+ "repo_url": "https://github.com/modelcontextprotocol/servers/tree/main/src/sentry",
281
+ "description": "实时对接 Sentry 线上监控系统,拉取生产环境异常堆栈、未捕获崩溃与错误聚合统计。",
282
+ "tags": ["Sentry", "Crash", "Observability", "StackTrace"],
283
+ "required_credentials": ["SENTRY_AUTH_TOKEN"],
284
+ "tools": [
285
+ {"name": "get_issue", "description": "根据 Issue ID 获取 Sentry 详细崩溃报告与上下文", "parameters": "issue_id"},
286
+ {"name": "search_issues", "description": "按工程与环境过滤最近激增的生产环境异常", "parameters": "query, limit"},
287
+ ],
288
+ },
289
+ "docker-mcp": {
290
+ "id": "docker-mcp",
291
+ "name": "docker-mcp",
292
+ "title": "Docker 容器生命周期与镜像安全探针",
293
+ "category": "devops",
294
+ "author": "@modelcontextprotocol",
295
+ "stars": 2740,
296
+ "version": "0.3.5",
297
+ "package": "@modelcontextprotocol/server-docker",
298
+ "installer": "npx",
299
+ "command": "npx",
300
+ "args": ["-y", "@modelcontextprotocol/server-docker"],
301
+ "repo_url": "https://github.com/modelcontextprotocol/servers/tree/main/src/docker",
302
+ "description": "受控的 Docker 守护进程管理探针,用于审计运行中容器的环境变量、端口映射及日志流。",
303
+ "tags": ["Docker", "Containers", "DevOps", "Isolation"],
304
+ "required_credentials": [],
305
+ "tools": [
306
+ {"name": "list_containers", "description": "查询当前主机全部活跃及停止状态的容器", "parameters": "all"},
307
+ {"name": "inspect_container", "description": "获取容器的完整底层规格与网络绑定", "parameters": "container_id"},
308
+ {"name": "get_logs", "description": "读取容器近期 stdout/stderr 日志流", "parameters": "container_id, tail"},
309
+ ],
310
+ },
311
+ "sqlite-mcp": {
312
+ "id": "sqlite-mcp",
313
+ "name": "sqlite-mcp",
314
+ "title": "SQLite 嵌入式数据库分析与只读查询",
315
+ "category": "storage",
316
+ "author": "@modelcontextprotocol",
317
+ "stars": 2510,
318
+ "version": "0.5.2",
319
+ "package": "mcp-server-sqlite",
320
+ "installer": "uvx",
321
+ "command": "uvx",
322
+ "args": ["mcp-server-sqlite", "--db-path", "./data.db"],
323
+ "repo_url": "https://github.com/modelcontextprotocol/servers/tree/main/src/sqlite",
324
+ "description": "轻量级 SQLite 数据库离线只读分析探针,毫秒级提取本地 .sqlite / .db 文件的全量 Schema。",
325
+ "tags": ["SQLite", "Database", "Embedded", "Local"],
326
+ "required_credentials": [],
327
+ "tools": [
328
+ {"name": "read_query", "description": "在 SQLite 文件上执行只读 SELECT 查询", "parameters": "query"},
329
+ {"name": "describe_table", "description": "获取指定数据表的列结构定义与外键约束", "parameters": "table_name"},
330
+ {"name": "list_tables", "description": "遍历 SQLite 数据库内包含的所有用户表", "parameters": ""},
331
+ ],
332
+ },
333
+ "gitlab-mcp": {
334
+ "id": "gitlab-mcp",
335
+ "name": "gitlab-mcp",
336
+ "title": "GitLab 代码仓库与 CI/CD 审计探针",
337
+ "category": "devops",
338
+ "author": "@modelcontextprotocol",
339
+ "stars": 2280,
340
+ "version": "0.4.8",
341
+ "package": "@modelcontextprotocol/server-gitlab",
342
+ "installer": "npx",
343
+ "command": "npx",
344
+ "args": ["-y", "@modelcontextprotocol/server-gitlab"],
345
+ "repo_url": "https://github.com/modelcontextprotocol/servers/tree/main/src/gitlab",
346
+ "description": "连接私有化部署或公网 GitLab 实例,支持 Merge Request 差异对比与 CI 流水线状态跟踪。",
347
+ "tags": ["GitLab", "CI-CD", "Merge-Request", "DevOps"],
348
+ "required_credentials": ["GITLAB_PERSONAL_ACCESS_TOKEN", "GITLAB_API_URL"],
349
+ "tools": [
350
+ {"name": "get_merge_request", "description": "获取指定 MR 的源分支、目标分支与变更状态", "parameters": "project_id, mr_iid"},
351
+ {"name": "list_pipelines", "description": "查询最近触发的 CI/CD 流水线运行指标", "parameters": "project_id, page"},
352
+ {"name": "create_mr_discussion", "description": "在 MR 代码行中插入安全加固建议", "parameters": "project_id, mr_iid, body"},
353
+ ],
354
+ },
355
+ "slack-mcp": {
356
+ "id": "slack-mcp",
357
+ "name": "slack-mcp",
358
+ "title": "Slack 团队协作与审计告警通道探针",
359
+ "category": "tools",
360
+ "author": "@modelcontextprotocol",
361
+ "stars": 2190,
362
+ "version": "0.5.0",
363
+ "package": "@modelcontextprotocol/server-slack",
364
+ "installer": "npx",
365
+ "command": "npx",
366
+ "args": ["-y", "@modelcontextprotocol/server-slack"],
367
+ "repo_url": "https://github.com/modelcontextprotocol/servers/tree/main/src/slack",
368
+ "description": "提供 Slack 频道消息监听、安全事件通报与智能体交互回执推送能力。",
369
+ "tags": ["Slack", "Notification", "ChatOps", "Alert"],
370
+ "required_credentials": ["SLACK_BOT_TOKEN", "SLACK_TEAM_ID"],
371
+ "tools": [
372
+ {"name": "post_message", "description": "向指定 Slack 频道发送格式化审计通报", "parameters": "channel_id, text"},
373
+ {"name": "list_channels", "description": "枚举工作区内机器人已被邀请加入的频道列表", "parameters": "types"},
374
+ {"name": "reply_to_thread", "description": "针对特定安全预警消息开启独立讨论线程", "parameters": "channel_id, thread_ts, text"},
375
+ ],
376
+ },
377
+ }
378
+
379
+
380
+ def _default_mcp_command(name: str, reg_entry: dict[str, Any]) -> tuple[str, list[str]]:
381
+ if name == "bugx-supervisor":
382
+ return "bugx", ["mcp", "serve", "--root", ".", "--role", "host"]
383
+ if name == "bugx-supervisor-worker":
384
+ return "bugx", ["mcp", "serve", "--root", ".", "--role", "worker"]
385
+ if name == "bugx-docs":
386
+ return "bugx", ["mcp", "serve", "--root", ".", "--role", "docs"]
387
+ if name in ONLINE_MCP_CATALOG:
388
+ on_item = ONLINE_MCP_CATALOG[name]
389
+ return str(on_item.get("command") or "npx"), list(on_item.get("args") or [])
390
+ pkg = str(reg_entry.get("package") or "")
391
+ installer = str(reg_entry.get("installer") or "")
392
+ if installer == "npm" and pkg:
393
+ return "npx", ["-y", pkg]
394
+ return "bugx", ["mcp-runtime", "run", name]
395
+
396
+
397
+ def inspect_workspace_mcp(workspace_path: Path | str) -> dict[str, Any]:
398
+ """Inspect configured MCP servers in the given workspace path."""
399
+ ws = Path(workspace_path).resolve()
400
+ servers: list[dict[str, Any]] = []
401
+ registry = _load_mcp_registry()
402
+ sandbox_env = load_sandbox_mcp_env(ws)
403
+
404
+ cfg_path = ws / ".bugx" / "config.json"
405
+ disabled_mcps: set[str] = set()
406
+ if cfg_path.is_file():
407
+ try:
408
+ cfg_data = json.loads(cfg_path.read_text(encoding="utf-8"))
409
+ if isinstance(cfg_data, dict):
410
+ disabled_mcps = {str(x) for x in (cfg_data.get("disabled_mcps") or []) if x}
411
+ except Exception:
412
+ pass
413
+
414
+ mcp_files = [
415
+ ws / ".mcp.json",
416
+ ws / ".codebuddy" / "mcp.json",
417
+ ws / ".claude" / "mcp.json",
418
+ ]
419
+
420
+ seen_names: set[str] = set()
421
+
422
+ for mcp_file in mcp_files:
423
+ if not mcp_file.is_file():
424
+ continue
425
+ try:
426
+ data = json.loads(mcp_file.read_text(encoding="utf-8"))
427
+ mcp_servers = data.get("mcpServers", {})
428
+ for name, cfg in mcp_servers.items():
429
+ if not isinstance(cfg, dict) or name in seen_names:
430
+ continue
431
+ seen_names.add(name)
432
+
433
+ cmd = cfg.get("command", "")
434
+ args = cfg.get("args", [])
435
+ cmd_str = f"{cmd} {' '.join(str(a) for a in args)}".strip()
436
+ is_disabled = bool(cfg.get("disabled")) or (name in disabled_mcps)
437
+
438
+ tool_count = 6
439
+ if "supervisor" in name:
440
+ tool_count = 12
441
+ elif "docs" in name:
442
+ tool_count = 4
443
+ elif "memory" in name:
444
+ tool_count = 14
445
+ elif "playwright" in name:
446
+ tool_count = 10
447
+
448
+ reg_info = registry.get(name) or {}
449
+ raw_creds = reg_info.get("credentials")
450
+ if isinstance(raw_creds, dict):
451
+ req_creds = [str(c) for c in (raw_creds.get("env") or [])]
452
+ elif isinstance(raw_creds, (list, tuple)):
453
+ req_creds = [str(c) for c in raw_creds]
454
+ else:
455
+ req_creds = []
456
+ srv_sandbox = sandbox_env.get(name) or {}
457
+ creds_ok = all(bool(os.environ.get(c) or srv_sandbox.get(c)) for c in req_creds)
458
+
459
+ status = "disabled" if is_disabled else ("connected" if creds_ok else "missing_credentials")
460
+ servers.append({
461
+ "name": name,
462
+ "enabled": not is_disabled,
463
+ "status": status,
464
+ "tools": tool_count,
465
+ "tool_count": tool_count,
466
+ "command": cmd_str or "stdio",
467
+ "source": str(mcp_file.relative_to(ws)),
468
+ "tier": reg_info.get("tier", "custom"),
469
+ "required_credentials": req_creds,
470
+ "configured_credentials": sorted(srv_sandbox.keys()),
471
+ "credentials_ready": creds_ok,
472
+ "error": "" if creds_ok else f"缺少凭据: {', '.join(req_creds)}",
473
+ })
474
+ except Exception:
475
+ pass
476
+
477
+ # If no local .mcp.json found, provide default BugX servers
478
+ if not servers:
479
+ for def_name, def_tools, def_cmd in (
480
+ ("bugx-supervisor", 12, "bugx mcp serve --root . --role host"),
481
+ ("bugx-docs", 4, "bugx mcp serve --root . --role docs"),
482
+ ):
483
+ is_dis = def_name in disabled_mcps
484
+ servers.append({
485
+ "name": def_name,
486
+ "enabled": not is_dis,
487
+ "status": "disabled" if is_dis else "connected",
488
+ "tools": def_tools,
489
+ "tool_count": def_tools,
490
+ "command": def_cmd,
491
+ "source": "builtin",
492
+ "tier": "builtin",
493
+ "required_credentials": [],
494
+ "configured_credentials": [],
495
+ "credentials_ready": True,
496
+ "error": "",
497
+ })
498
+
499
+ return {
500
+ "servers": servers,
501
+ "trust": {"trusted": True},
502
+ }
503
+
504
+
505
+ MCP_DESCRIPTIONS: dict[str, str] = {
506
+ "bugx-supervisor": "BugX 核心审计调度控制面,提供任务认领、证据链校验、心跳续约与结算门禁",
507
+ "bugx-supervisor-worker": "BugX Worker 受限执行视图,专为并发子智能体提供零逃逸任务认领与上报",
508
+ "bugx-docs": "项目级 SQLite FTS5 全文文档检索引擎,支持架构规范与安全基线毫秒级检索",
509
+ "postmcp": "HTTP/REST/GraphQL 动态接口契约测试与越权差分发包探针",
510
+ "playwright": "真实无头浏览器自动化探针,用于 DOM XSS、鉴权流、CSRF 与前端视觉回归验证",
511
+ "dbhub": "多源关系型数据库(PostgreSQL/MySQL/SQLite)Schema 审计与只读安全查询探针",
512
+ "redis": "Redis 缓存键值状态审计、TTL 策略核验与分布式锁竞争探针",
513
+ "semgrep": "多语言 AST 静态污点规则扫描器,快速定位高危危险汇(Sinks)",
514
+ "mobile": "Android/iOS 移动端组件暴露面、Intent 劫持与 UI 自动化探针",
515
+ "desktop": "macOS/Windows/Linux 原生桌面应用窗口树检查与交互探针",
516
+ "native": "C/C++/Rust 原生二进制符号分析、ASan 内存错误与 Fuzzing 探针",
517
+ }
518
+
519
+ MCP_TOOLS_CATALOG: dict[str, list[dict[str, str]]] = {
520
+ "bugx-supervisor": [
521
+ {"name": "bugx_supervisor_start", "description": "启动审计编排会话并加载策略基准", "parameters": "review_mode, polling, fix_mode"},
522
+ {"name": "bugx_supervisor_claim", "description": "子智能体认领原子审计任务 (Claim Task)", "parameters": "worker_id, scope, timeout"},
523
+ {"name": "bugx_supervisor_heartbeat", "description": "维持租约心跳,防止会话超时回收", "parameters": "lease_id, progress"},
524
+ {"name": "bugx_supervisor_checkpoint", "description": "提交安全检查点证据链与阶段结果", "parameters": "checkpoint_id, findings, evidence"},
525
+ {"name": "bugx_supervisor_findings", "description": "查询与聚合当前发现的高危安全缺陷", "parameters": "severity, status, filter"},
526
+ {"name": "bugx_supervisor_verify_finding", "description": "触发反事实验证与 PoC 差分复现", "parameters": "finding_id, harness_code"},
527
+ {"name": "bugx_supervisor_confirm_finding", "description": "确认缺陷真实性并转入修复流水线", "parameters": "finding_id, confidence, fix_plan"},
528
+ {"name": "bugx_supervisor_bootstrap_coverage", "description": "引导代码覆盖率与攻击面分析", "parameters": "workspace_root, targets"},
529
+ {"name": "bugx_supervisor_gate", "description": "执行结算门禁,检查阻断性违规项", "parameters": "policy, strict_mode"},
530
+ {"name": "bugx_supervisor_coverage", "description": "获取当前代码行/分支覆盖率统计", "parameters": "scope, format"},
531
+ {"name": "bugx_supervisor_rebind_target", "description": "动态重定向分析目标文件或模块", "parameters": "new_target, preserve_context"},
532
+ {"name": "bugx_supervisor_status", "description": "查询 Supervisor 全局健康状态与运行指标", "parameters": "verbose"},
533
+ ],
534
+ "bugx-docs": [
535
+ {"name": "docs_search", "description": "基于 SQLite FTS5 的项目架构与安全文档全文检索", "parameters": "query, top_k, namespace"},
536
+ {"name": "docs_read", "description": "高效只读读取指定规范文档或 ADR 提案", "parameters": "path, line_range"},
537
+ {"name": "docs_schema", "description": "获取文档元数据、目录结构与章节索引", "parameters": "category"},
538
+ {"name": "docs_tree", "description": "检索工程文档树与 Diátaxis 架构规范", "parameters": "depth, filter"},
539
+ ],
540
+ "postmcp": [
541
+ {"name": "postmcp_http_request", "description": "构造并执行受控 HTTP/REST 请求(支持全动词)", "parameters": "url, method, headers, body, timeout"},
542
+ {"name": "postmcp_graphql_query", "description": "发送 GraphQL 查询与 Mutation 探针", "parameters": "endpoint, query, variables"},
543
+ {"name": "postmcp_replay_traffic", "description": "重放录制的流量包并比对越权差分响应", "parameters": "traffic_id, auth_context_a, auth_context_b"},
544
+ {"name": "postmcp_diff_fuzz", "description": "针对接口参数执行模糊测试与注入突变", "parameters": "endpoint, fuzz_matrix, sink_rules"},
545
+ {"name": "postmcp_extract_cookies", "description": "解析会话 Cookie 与 CSRF Token 安全属性", "parameters": "response_headers, domain"},
546
+ {"name": "postmcp_inspect_headers", "description": "深度校验安全响应头(CSP/HSTS/CORS/X-Frame)", "parameters": "headers, strictness"},
547
+ ],
548
+ "playwright": [
549
+ {"name": "browser_navigate", "description": "控制浏览器导航至目标页面并等待 DOM 就绪", "parameters": "url, wait_until, timeout"},
550
+ {"name": "browser_click", "description": "模拟真实用户点击指定 DOM 选择器或坐标", "parameters": "selector, position, delay"},
551
+ {"name": "browser_screenshot", "description": "捕获页面视口或元素的高清快照 (PNG/JPEG)", "parameters": "full_page, selector, output_path"},
552
+ {"name": "browser_fill", "description": "安全模拟键盘输入与表单填充", "parameters": "selector, text, clear_first"},
553
+ {"name": "browser_eval", "description": "在沙箱页面上下文执行只读 JavaScript 表达式", "parameters": "expression, args"},
554
+ {"name": "browser_console_logs", "description": "实时抓取浏览器 Console 报错、警告与异常堆栈", "parameters": "level_filter"},
555
+ {"name": "browser_network_requests", "description": "监听网络请求与 XHR/Fetch 交互包", "parameters": "url_pattern, include_bodies"},
556
+ {"name": "browser_close", "description": "优雅销毁当前受控无头浏览器上下文", "parameters": "context_id"},
557
+ ],
558
+ "dbhub": [
559
+ {"name": "db_query_schema", "description": "导出 PostgreSQL/MySQL/SQLite 数据库 Schema 结构", "parameters": "database, include_indexes"},
560
+ {"name": "db_execute_readonly_sql", "description": "执行严格只读 SQL 查询,底层自动拦截 DDL/DML 写操作", "parameters": "query, limit, timeout"},
561
+ {"name": "db_explain_query", "description": "获取 SQL 查询执行计划与索引命中深度分析", "parameters": "query, analyze"},
562
+ {"name": "db_inspect_tables", "description": "统计表数据量、外键约束与高危敏感字段定义", "parameters": "table_names"},
563
+ {"name": "db_connection_test", "description": "校验数据库连接有效性与只读账号权限基线", "parameters": "dsn_alias"},
564
+ ],
565
+ "redis": [
566
+ {"name": "redis_get", "description": "查询指定键的字符串、哈希、列表或集合数据", "parameters": "key, format"},
567
+ {"name": "redis_scan_keys", "description": "分批游标扫描键名(严禁 KEYS *,彻底杜绝生产锁库)", "parameters": "pattern, count, cursor"},
568
+ {"name": "redis_ttl", "description": "核验敏感缓存键的生存周期与过期淘汰策略", "parameters": "key"},
569
+ {"name": "redis_info", "description": "提取 Redis 内存水位、持久化配置、慢日志与连接数", "parameters": "section"},
570
+ {"name": "redis_test_connection", "description": "探活 Redis 实例、密码认证与沙箱连通性", "parameters": "timeout"},
571
+ ],
572
+ "semgrep": [
573
+ {"name": "semgrep_scan", "description": "执行 AST 静态代码扫描,快速定位危险汇与潜在漏洞", "parameters": "path, rule_ids, config"},
574
+ {"name": "semgrep_taint_check", "description": "追踪从源头(Sources)到危险汇(Sinks)的数据传播路径", "parameters": "source_sink_spec, file_paths"},
575
+ {"name": "semgrep_list_rules", "description": "查询内置的 OWASP Top 10 与 BugX 深度审计规则清单", "parameters": "category, language"},
576
+ {"name": "semgrep_custom_rule", "description": "使用 YAML 语法对特定代码片段执行即时 AST 匹配", "parameters": "rule_yaml, code_snippet"},
577
+ ],
578
+ "mobile": [
579
+ {"name": "mobile_launch_app", "description": "在连接的 Android/iOS 模拟器或真机启动指定应用", "parameters": "package_name, activity, clear_state"},
580
+ {"name": "mobile_dump_ui_hierarchy", "description": "抓取当前屏幕 View 树、无障碍标签与控件坐标", "parameters": "format"},
581
+ {"name": "mobile_tap", "description": "模拟屏幕坐标点击或控件无障碍节点触发", "parameters": "x, y, element_id"},
582
+ {"name": "mobile_input_text", "description": "模拟软键盘文本输入与回车提交", "parameters": "text, clear_first"},
583
+ {"name": "mobile_screenshot", "description": "捕获移动设备当前屏幕全尺寸高清截图", "parameters": "output_path"},
584
+ {"name": "mobile_inspect_intent", "description": "审计 Android Manifest 导出组件与 Intent 过滤器安全缺陷", "parameters": "manifest_path"},
585
+ ],
586
+ "desktop": [
587
+ {"name": "desktop_inspect_window", "description": "探测当前聚焦的原生桌面窗口属性与控件层级", "parameters": "app_name, pid"},
588
+ {"name": "desktop_click_element", "description": "基于原生无障碍树坐标安全模拟输入", "parameters": "element_id, x, y"},
589
+ {"name": "desktop_capture_screen", "description": "截取多屏幕指定窗口或区域快照", "parameters": "window_id, rect"},
590
+ ],
591
+ "native": [
592
+ {"name": "native_symbol_dump", "description": "解析 ELF / Mach-O / PE 导出表、导入符号与动态依赖", "parameters": "binary_path"},
593
+ {"name": "native_check_sec", "description": "审计二进制安全加固机制(NX/PIE/Canary/RELRO/ASLR)", "parameters": "binary_path"},
594
+ {"name": "native_asan_report", "description": "解析 AddressSanitizer 崩溃日志与 Use-After-Free 内存错误", "parameters": "log_content"},
595
+ ],
596
+ }
597
+
598
+
599
+ def get_mcp_marketplace(workspace_path: Path | str) -> dict[str, Any]:
600
+ """Return the official BugX MCP Marketplace catalog enriched with project mount & credential status."""
601
+ ws = Path(workspace_path).resolve()
602
+ registry = _load_mcp_registry()
603
+ current = inspect_workspace_mcp(ws).get("servers", [])
604
+ mounted_map = {s["name"]: s for s in current}
605
+ sandbox_env = load_sandbox_mcp_env(ws)
606
+
607
+ descriptions = MCP_DESCRIPTIONS
608
+
609
+ catalog: list[dict[str, Any]] = []
610
+ for name, meta in registry.items():
611
+ if name == "bugx-supervisor-worker":
612
+ continue
613
+ mounted_entry = mounted_map.get(name)
614
+ raw_creds = meta.get("credentials")
615
+ if isinstance(raw_creds, dict):
616
+ req_creds = [str(c) for c in (raw_creds.get("env") or [])]
617
+ elif isinstance(raw_creds, (list, tuple)):
618
+ req_creds = [str(c) for c in raw_creds]
619
+ else:
620
+ req_creds = []
621
+ srv_sandbox = sandbox_env.get(name) or {}
622
+ creds_ready = all(bool(os.environ.get(c) or srv_sandbox.get(c)) for c in req_creds)
623
+ cmd_bin, cmd_args = _default_mcp_command(name, meta)
624
+ catalog.append({
625
+ "id": name,
626
+ "name": name,
627
+ "title": name,
628
+ "description": descriptions.get(name, f"BugX 官方审计 MCP 服务 ({name})"),
629
+ "tier": meta.get("tier", "optional"),
630
+ "status": meta.get("status", "ready"),
631
+ "applies": meta.get("applies", {}),
632
+ "installer": meta.get("installer", "builtin"),
633
+ "package": meta.get("package"),
634
+ "command_preview": f"{cmd_bin} {' '.join(cmd_args)}",
635
+ "required_credentials": req_creds,
636
+ "required_env": req_creds,
637
+ "configured_credentials": sorted(srv_sandbox.keys()),
638
+ "credentials_ready": creds_ready,
639
+ "trust": meta.get("trust", {}),
640
+ "audit": meta.get("audit", {}),
641
+ "mounted": mounted_entry is not None,
642
+ "enabled": bool(mounted_entry.get("enabled")) if mounted_entry else False,
643
+ })
644
+
645
+ return {
646
+ "total": len(catalog),
647
+ "items": catalog,
648
+ }
649
+
650
+
651
+ def get_online_mcp_catalog(workspace_path: Path | str) -> dict[str, Any]:
652
+ """Return curated open-source MCP catalog enriched with project mount & credential readiness states."""
653
+ ws = Path(workspace_path).resolve()
654
+ current = inspect_workspace_mcp(ws).get("servers", [])
655
+ mounted_map = {s["name"]: s for s in current}
656
+ sandbox_env = load_sandbox_mcp_env(ws)
657
+
658
+ items: list[dict[str, Any]] = []
659
+ for srv_id, meta in ONLINE_MCP_CATALOG.items():
660
+ mounted_entry = mounted_map.get(srv_id)
661
+ req_creds = [str(c) for c in (meta.get("required_credentials") or [])]
662
+ srv_sandbox = sandbox_env.get(srv_id) or {}
663
+ creds_ready = all(bool(os.environ.get(c) or srv_sandbox.get(c)) for c in req_creds)
664
+ cmd_bin = meta.get("command", "npx")
665
+ cmd_args = meta.get("args", [])
666
+ cmd_str = f"{cmd_bin} {' '.join(str(a) for a in cmd_args)}".strip()
667
+
668
+ item = dict(meta)
669
+ item["command_preview"] = cmd_str
670
+ item["required_credentials"] = req_creds
671
+ item["required_env"] = req_creds
672
+ item["configured_credentials"] = sorted(srv_sandbox.keys())
673
+ item["credentials_ready"] = creds_ready
674
+ item["mounted"] = mounted_entry is not None
675
+ item["enabled"] = bool(mounted_entry.get("enabled")) if mounted_entry else False
676
+ item["tools_count"] = len(meta.get("tools") or [])
677
+ item["trust"] = "A"
678
+ item["tier"] = "community"
679
+ item["source"] = "online"
680
+ items.append(item)
681
+
682
+ return {
683
+ "total": len(items),
684
+ "items": items,
685
+ "workspace": str(ws),
686
+ }
687
+
688
+
689
+ def get_mcp_detail(workspace_path: Path | str, server_name: str) -> dict[str, Any]:
690
+ """Provide comprehensive metadata, tool specifications, and rendered documentation for an MCP server (REQ-09 / DOC-255)."""
691
+ ws = Path(workspace_path).resolve()
692
+ srv_name = str(server_name or "").strip()
693
+ if not srv_name:
694
+ return {"ok": False, "error": "Missing server name"}
695
+
696
+ registry = _load_mcp_registry()
697
+ meta = registry.get(srv_name) or {}
698
+ is_online = False
699
+ if not meta and srv_name in ONLINE_MCP_CATALOG:
700
+ on_item = ONLINE_MCP_CATALOG[srv_name]
701
+ is_online = True
702
+ meta = {
703
+ "tier": "community",
704
+ "trust": "A",
705
+ "installer": on_item.get("installer", "npx"),
706
+ "package": on_item.get("package"),
707
+ "status": "ready",
708
+ "audit": f"由开源社区 {on_item.get('author', '@modelcontextprotocol')} 维护,已通过受控沙箱审计",
709
+ "credentials": on_item.get("required_credentials", []),
710
+ "description": on_item.get("description"),
711
+ "title": on_item.get("title"),
712
+ }
713
+
714
+ current = inspect_workspace_mcp(ws).get("servers", [])
715
+ mounted_entry = next((s for s in current if s.get("name") == srv_name), None)
716
+
717
+ sandbox_env = load_sandbox_mcp_env(ws)
718
+ srv_sandbox = sandbox_env.get(srv_name) or {}
719
+
720
+ raw_creds = meta.get("credentials")
721
+ if isinstance(raw_creds, dict):
722
+ req_creds = [str(c) for c in (raw_creds.get("env") or [])]
723
+ elif isinstance(raw_creds, (list, tuple)):
724
+ req_creds = [str(c) for c in raw_creds]
725
+ else:
726
+ req_creds = []
727
+
728
+ creds_ready = all(bool(os.environ.get(c) or srv_sandbox.get(c)) for c in req_creds)
729
+
730
+ cmd_bin, cmd_args = _default_mcp_command(srv_name, meta)
731
+ command_preview = mounted_entry.get("command") if mounted_entry else f"{cmd_bin} {' '.join(cmd_args)}"
732
+
733
+ tier = meta.get("tier", mounted_entry.get("tier", "community" if is_online else "custom") if mounted_entry else ("community" if is_online else "custom"))
734
+ trust = str(meta.get("trust", "builtin" if tier == "builtin" else "A"))
735
+ installer = meta.get("installer", "builtin" if tier == "builtin" else ("npx" if is_online else "custom"))
736
+ package = meta.get("package")
737
+ status = meta.get("status", mounted_entry.get("status", "ready") if mounted_entry else "ready")
738
+ audit_notes = str(meta.get("audit") or "已通过 BugX 安全与隔离沙箱审计")
739
+
740
+ tools_list = MCP_TOOLS_CATALOG.get(srv_name) or []
741
+ if not tools_list and srv_name in ONLINE_MCP_CATALOG:
742
+ tools_list = list(ONLINE_MCP_CATALOG[srv_name].get("tools") or [])
743
+ if not tools_list and mounted_entry and mounted_entry.get("tool_count"):
744
+ count = int(mounted_entry.get("tool_count") or 1)
745
+ tools_list = [
746
+ {"name": f"{srv_name}_tool_{i+1}", "description": f"MCP 导出工具通道 #{i+1}", "parameters": "params"}
747
+ for i in range(count)
748
+ ]
749
+
750
+ # Generate rich Markdown
751
+ tools_table_rows = "\n".join(
752
+ f"| `{t['name']}` | {t['description']} | `{t['parameters']}` |" for t in tools_list
753
+ ) if tools_list else "| `*` | 动态加载工具集 (运行期 tools/list 协议协商) | `context` |"
754
+
755
+ env_example = {k: f"${{BUGX_SANDBOX_ENV:{k}}}" for k in req_creds}
756
+ config_json = json.dumps({
757
+ "mcpServers": {
758
+ srv_name: {
759
+ "command": cmd_bin,
760
+ "args": cmd_args,
761
+ **({"env": env_example} if env_example else {})
762
+ }
763
+ }
764
+ }, indent=2, ensure_ascii=False)
765
+
766
+ desc = meta.get("description") or MCP_DESCRIPTIONS.get(srv_name, f"BugX 官方审计生态 MCP 扩展组件 ({srv_name}),为大语言模型与智能体提供标准化的外部工具调用能力。")
767
+ status_label = "运行就绪 (Connected)" if (mounted_entry and mounted_entry.get("enabled")) else ("需配置凭据" if not creds_ready else "待挂载")
768
+
769
+ doc_content = f"""---
770
+ name: {srv_name}
771
+ type: mcp-server
772
+ tier: {tier}
773
+ status: {status}
774
+ trust: {trust}
775
+ installer: {installer}
776
+ package: {package or 'builtin'}
777
+ tools_count: {len(tools_list)}
778
+ transport: stdio
779
+ credentials_ready: {creds_ready}
780
+ ---
781
+
782
+ # {srv_name} · MCP 协议规范与工具使用指南
783
+
784
+ > **BugX 官方审计生态 MCP 服务 (Model Context Protocol)**
785
+ > 运行环境: `{installer}` | 传输协议: `stdio (Standard I/O)` | 信任级别: `Trust {trust}` | 工具总数: `{len(tools_list)} 个原子工具` | 状态: `{status_label}`
786
+
787
+ ## 1. 架构定位与服务概述
788
+
789
+ {desc}
790
+
791
+ - **传输层契约**:严格遵循 JSON-RPC 2.0 over `stdio` 标准协议,支持 `tools/list`、`tools/call`、`resources/list` 等核心通道。
792
+ - **并发与幂等**:原子工具调用均具备幂等控制与错误兜底,所有结果通过结构化 JSON 返回,零悬空指针。
793
+ - **沙箱隔离**:支持 BugX 沙箱凭据隔离架构,杜绝在工作区代码库落盘敏感密钥。
794
+
795
+ ## 2. 导出原子工具矩阵 (Tools Matrix)
796
+
797
+ | 工具名称 (Tool Name) | 功能描述 (Description) | 参数规范 (Parameters) |
798
+ | :--- | :--- | :--- |
799
+ {tools_table_rows}
800
+
801
+ ## 3. 标准工程配置与环境接入 (.mcp.json)
802
+
803
+ 在当前工程根目录的 `.mcp.json`(或 `.codebuddy/mcp.json`)中添加如下配置节点即可自动挂载:
804
+
805
+ ```json
806
+ {config_json}
807
+ ```
808
+
809
+ ## 4. 独立命令行探针与调试指令 (CLI Probe)
810
+
811
+ 开发者或 CI/CD 可通过以下命令直接启动并探活该 MCP 服务:
812
+
813
+ ```bash
814
+ {command_preview}
815
+ ```
816
+
817
+ ## 5. 沙箱安全隔离与凭据契约 (Sandboxed Credentials)
818
+
819
+ - **物理隔离存储**:敏感凭据统一存储在 `~/.bugx/sandboxes/<project_hash>/mcp_env.json`,权限强制设置为 `0600`。
820
+ - **零凭据落盘**:工程工作区内的 `.mcp.json` 严禁出现真实 Token/Password 明文,仅使用占位符引用。
821
+ - **当前凭据状态**:{'全部所需凭据已在沙箱就绪' if creds_ready else f'缺少以下凭据: {", ".join(req_creds)}'}。
822
+
823
+ ## 6. 供应链审计与合规基线 (Supply Chain Audit)
824
+
825
+ - **供应链安全记录**:{audit_notes}
826
+ - **遥测行为**:已硬核禁用任何未经授权的第三方遥测打点(Telemetry Off)。
827
+ - **许可证合规**:经开源许可证兼容性与安全红队审查通过。
828
+ """
829
+
830
+ return {
831
+ "ok": True,
832
+ "name": srv_name,
833
+ "title": f"{srv_name} · MCP 协议服务",
834
+ "description": desc,
835
+ "tier": tier,
836
+ "status": status,
837
+ "trust": trust,
838
+ "package": package,
839
+ "installer": installer,
840
+ "command_preview": command_preview,
841
+ "required_credentials": req_creds,
842
+ "configured_credentials": sorted(srv_sandbox.keys()),
843
+ "credentials_ready": creds_ready,
844
+ "mounted": mounted_entry is not None,
845
+ "enabled": bool(mounted_entry.get("enabled")) if mounted_entry else False,
846
+ "tools": tools_list,
847
+ "tools_count": len(tools_list),
848
+ "content": doc_content,
849
+ "source": mounted_entry.get("source", "builtin" if tier == "builtin" else ("online" if is_online else "marketplace")) if mounted_entry else ("online" if is_online else "marketplace"),
850
+ "author": ONLINE_MCP_CATALOG[srv_name].get("author") if is_online else "@bugx",
851
+ "stars": ONLINE_MCP_CATALOG[srv_name].get("stars") if is_online else None,
852
+ "repo_url": ONLINE_MCP_CATALOG[srv_name].get("repo_url") if is_online else None,
853
+ }
854
+
855
+
856
+ def toggle_project_mcp(
857
+ workspace_path: Path | str,
858
+ server_name: str,
859
+ *,
860
+ enabled: bool = True,
861
+ mount: bool = True,
862
+ env_vars: Mapping[str, str] | None = None,
863
+ command: str | None = None,
864
+ args: list[str] | None = None,
865
+ ) -> dict[str, Any]:
866
+ """Mount/unmount or enable/disable an MCP server in <workspace>/.mcp.json and host configs (REQ-09)."""
867
+ ws = Path(workspace_path).resolve()
868
+ registry = _load_mcp_registry()
869
+ reg_entry = registry.get(server_name) or {}
870
+
871
+ if env_vars:
872
+ save_sandbox_mcp_env(ws, server_name, env_vars)
873
+
874
+ mcp_file = ws / ".mcp.json"
875
+ mcp_data: dict[str, Any] = {"mcpServers": {}}
876
+ if mcp_file.is_file():
877
+ try:
878
+ loaded = json.loads(mcp_file.read_text(encoding="utf-8"))
879
+ if isinstance(loaded, dict):
880
+ mcp_data = loaded
881
+ if not isinstance(mcp_data.get("mcpServers"), dict):
882
+ mcp_data["mcpServers"] = {}
883
+ except Exception:
884
+ mcp_data = {"mcpServers": {}}
885
+
886
+ cfg_file = ws / ".bugx" / "config.json"
887
+ cfg_file.parent.mkdir(parents=True, mode=0o700, exist_ok=True)
888
+ cfg_data: dict[str, Any] = {}
889
+ if cfg_file.is_file():
890
+ try:
891
+ cfg_data = json.loads(cfg_file.read_text(encoding="utf-8"))
892
+ except Exception:
893
+ cfg_data = {}
894
+ disabled_mcps = {str(x) for x in (cfg_data.get("disabled_mcps") or []) if x}
895
+
896
+ if not mount:
897
+ mcp_data["mcpServers"].pop(server_name, None)
898
+ disabled_mcps.discard(server_name)
899
+ else:
900
+ if command:
901
+ cmd_bin = command
902
+ cmd_args = args or []
903
+ else:
904
+ cmd_bin, cmd_args = _default_mcp_command(server_name, reg_entry)
905
+ srv_obj: dict[str, Any] = dict(mcp_data["mcpServers"].get(server_name) or {"command": cmd_bin, "args": cmd_args})
906
+ srv_obj["command"] = cmd_bin
907
+ srv_obj["args"] = cmd_args
908
+
909
+ raw_creds = reg_entry.get("credentials")
910
+ if isinstance(raw_creds, dict):
911
+ req_creds = [str(c) for c in (raw_creds.get("env") or [])]
912
+ elif isinstance(raw_creds, (list, tuple)):
913
+ req_creds = [str(c) for c in raw_creds]
914
+ else:
915
+ req_creds = []
916
+
917
+ if server_name in ONLINE_MCP_CATALOG:
918
+ for c in ONLINE_MCP_CATALOG[server_name].get("required_credentials", []):
919
+ if c not in req_creds:
920
+ req_creds.append(str(c))
921
+
922
+ if env_vars:
923
+ for k in env_vars:
924
+ if k not in req_creds:
925
+ req_creds.append(str(k))
926
+ if req_creds:
927
+ env_map = dict(srv_obj.get("env") or {})
928
+ for c in req_creds:
929
+ env_map[c] = f"${{BUGX_SANDBOX_ENV:{c}}}"
930
+ srv_obj["env"] = env_map
931
+ mcp_data["mcpServers"][server_name] = srv_obj
932
+ if enabled:
933
+ disabled_mcps.discard(server_name)
934
+ if isinstance(mcp_data["mcpServers"].get(server_name), dict):
935
+ mcp_data["mcpServers"][server_name].pop("disabled", None)
936
+ else:
937
+ disabled_mcps.add(server_name)
938
+ if isinstance(mcp_data["mcpServers"].get(server_name), dict):
939
+ mcp_data["mcpServers"][server_name]["disabled"] = True
940
+
941
+ cfg_data["disabled_mcps"] = sorted(disabled_mcps)
942
+ cfg_file.write_text(json.dumps(cfg_data, indent=2, ensure_ascii=False), encoding="utf-8")
943
+ mcp_file.write_text(json.dumps(mcp_data, indent=2, ensure_ascii=False), encoding="utf-8")
944
+
945
+ # Sync to .claude/mcp.json if .claude directory exists
946
+ claude_dir = ws / ".claude"
947
+ if claude_dir.is_dir():
948
+ try:
949
+ (claude_dir / "mcp.json").write_text(
950
+ json.dumps(mcp_data, indent=2, ensure_ascii=False), encoding="utf-8"
951
+ )
952
+ except Exception:
953
+ pass
954
+
955
+ res = inspect_workspace_mcp(ws)
956
+ res["ok"] = True
957
+ res["sandbox_env_path"] = str(_sandbox_env_file(ws))
958
+ return res
959
+
960
+
961
+ def get_skills_marketplace(workspace_path: Path | str) -> dict[str, Any]:
962
+ """Return the Skill Marketplace catalog aggregating core, domain skill packs, repo skills, and global skills."""
963
+ ws = Path(workspace_path).resolve()
964
+ cfg_file = ws / ".bugx" / "config.json"
965
+ cfg_data: dict[str, Any] = {}
966
+ if cfg_file.is_file():
967
+ try:
968
+ cfg_data = json.loads(cfg_file.read_text(encoding="utf-8"))
969
+ except Exception:
970
+ cfg_data = {}
971
+ disabled_skills = {str(x) for x in (cfg_data.get("disabled_skills") or []) if x}
972
+ mounted_skills = {str(x) for x in (cfg_data.get("mounted_skills") or []) if x}
973
+
974
+ core_dir = Path(__file__).resolve().parent.parent
975
+ repo_root = core_dir.parent
976
+ home_skills_dir = Path.home() / ".agents" / "skills"
977
+
978
+ items: list[dict[str, Any]] = []
979
+ seen: set[str] = set()
980
+
981
+ # 1. Core BugX skills
982
+ core_skill_md = repo_root / ".agents" / "skills" / "bugx" / "SKILL.md"
983
+ if not core_skill_md.is_file():
984
+ for cand in (core_dir / "prompts" / "SKILL.md", repo_root / "README.md"):
985
+ if cand.is_file():
986
+ core_skill_md = cand
987
+ break
988
+ for s_name, desc in (
989
+ ("audit", "BugX 一键全息攻防渗透审计与双轨报告"),
990
+ ("review", "审查当前分支改动并输出结构化 Findings"),
991
+ ("mining", "多语种高危攻击面勘测与自动化加固"),
992
+ ("fix", "自动合成防御性源码补丁并执行沙箱回归验证"),
993
+ ("test", "生成 AAA 单元测试与变异杀伤力审计"),
994
+ ):
995
+ items.append({
996
+ "name": s_name,
997
+ "command": f"/{s_name}",
998
+ "category": "core",
999
+ "scope": "core",
1000
+ "description": desc,
1001
+ "mounted": True,
1002
+ "enabled": s_name not in disabled_skills,
1003
+ "file_path": str(core_skill_md),
1004
+ "is_installed_global": True,
1005
+ "is_installed_project": True,
1006
+ "applies_to": {"forms": ["*"], "surfaces": ["*"]},
1007
+ })
1008
+ seen.add(s_name)
1009
+
1010
+ # 2. Official Domain Audit Skill Packs (core/audit_packs/*)
1011
+ domain_dir = core_dir / "audit_packs" if (core_dir / "audit_packs").is_dir() else core_dir / "prompts" / "skills"
1012
+ if domain_dir.is_dir():
1013
+ for sk_dir in sorted(domain_dir.iterdir()):
1014
+ sk_md = sk_dir / "SKILL.md"
1015
+ mf = sk_dir / "manifest.json"
1016
+ if not sk_dir.is_dir() or (not sk_md.is_file() and not mf.is_file()) or sk_dir.name in seen:
1017
+ continue
1018
+ desc = f"BugX 领域专精安全审计技能包 ({sk_dir.name})"
1019
+ if sk_md.is_file():
1020
+ try:
1021
+ for line in sk_md.read_text(encoding="utf-8", errors="replace").splitlines()[:25]:
1022
+ if line.startswith("description:"):
1023
+ desc = line.split("description:", 1)[1].strip().strip("'\"")
1024
+ break
1025
+ except Exception:
1026
+ pass
1027
+ elif mf.is_file():
1028
+ try:
1029
+ mf_data = json.loads(mf.read_text(encoding="utf-8"))
1030
+ desc = mf_data.get("description") or f"BugX 官方 {sk_dir.name} 领域深度攻防审计技能包"
1031
+ except Exception:
1032
+ pass
1033
+ is_mounted = (sk_dir.name in mounted_skills) or (ws / ".agents" / "skills" / sk_dir.name).exists()
1034
+ items.append({
1035
+ "name": sk_dir.name,
1036
+ "command": f"/{sk_dir.name}",
1037
+ "category": "domain-audit",
1038
+ "scope": "market",
1039
+ "description": desc,
1040
+ "mounted": is_mounted,
1041
+ "enabled": is_mounted and (sk_dir.name not in disabled_skills),
1042
+ "file_path": str(sk_md if sk_md.is_file() else mf),
1043
+ "is_installed_global": (home_skills_dir / sk_dir.name).exists(),
1044
+ "is_installed_project": is_mounted,
1045
+ })
1046
+ seen.add(sk_dir.name)
1047
+
1048
+ # 3. Project Dedicated skills (ws/.agents/skills/*)
1049
+ proj_skills_dir = ws / ".agents" / "skills"
1050
+ if proj_skills_dir.is_dir():
1051
+ for sk_dir in sorted(proj_skills_dir.iterdir()):
1052
+ sk_md = sk_dir / "SKILL.md"
1053
+ mf = sk_dir / "manifest.json"
1054
+ if not sk_dir.is_dir() or (not sk_md.is_file() and not mf.is_file()) or sk_dir.name in seen:
1055
+ continue
1056
+ desc = f"项目专属技能 ({sk_dir.name})"
1057
+ if sk_md.is_file():
1058
+ try:
1059
+ for line in sk_md.read_text(encoding="utf-8", errors="replace").splitlines()[:25]:
1060
+ if line.startswith("description:"):
1061
+ desc = line.split("description:", 1)[1].strip().strip("'\"")
1062
+ break
1063
+ except Exception:
1064
+ pass
1065
+ items.append({
1066
+ "name": sk_dir.name,
1067
+ "command": f"/{sk_dir.name}",
1068
+ "category": "project",
1069
+ "scope": "project",
1070
+ "description": desc,
1071
+ "mounted": True,
1072
+ "enabled": sk_dir.name not in disabled_skills,
1073
+ "file_path": str(sk_md if sk_md.is_file() else mf),
1074
+ "is_installed_global": (home_skills_dir / sk_dir.name).exists(),
1075
+ "is_installed_project": True,
1076
+ })
1077
+ seen.add(sk_dir.name)
1078
+
1079
+ # 4. User Global skills (~/.agents/skills/*)
1080
+ if home_skills_dir.is_dir():
1081
+ for sk_dir in sorted(home_skills_dir.iterdir()):
1082
+ sk_md = sk_dir / "SKILL.md"
1083
+ mf = sk_dir / "manifest.json"
1084
+ if not sk_dir.is_dir() or (not sk_md.is_file() and not mf.is_file()) or sk_dir.name in seen:
1085
+ continue
1086
+ desc = f"本地全局技能 ({sk_dir.name})"
1087
+ if sk_md.is_file():
1088
+ try:
1089
+ for line in sk_md.read_text(encoding="utf-8", errors="replace").splitlines()[:25]:
1090
+ if line.startswith("description:"):
1091
+ desc = line.split("description:", 1)[1].strip().strip("'\"")
1092
+ break
1093
+ except Exception:
1094
+ pass
1095
+ is_mounted = (sk_dir.name in mounted_skills) or (ws / ".agents" / "skills" / sk_dir.name).exists()
1096
+ items.append({
1097
+ "name": sk_dir.name,
1098
+ "command": f"/{sk_dir.name}",
1099
+ "category": "global",
1100
+ "scope": "global",
1101
+ "description": desc,
1102
+ "mounted": is_mounted,
1103
+ "enabled": is_mounted and (sk_dir.name not in disabled_skills),
1104
+ "file_path": str(sk_md if sk_md.is_file() else mf),
1105
+ "is_installed_global": True,
1106
+ "is_installed_project": is_mounted,
1107
+ })
1108
+ seen.add(sk_dir.name)
1109
+
1110
+ # 5. Builtin Repo extensions (repo_root/skills/*)
1111
+ repo_skills_dir = repo_root / "skills"
1112
+ if repo_skills_dir.is_dir():
1113
+ for sk_dir in sorted(repo_skills_dir.iterdir()):
1114
+ sk_md = sk_dir / "SKILL.md"
1115
+ if not sk_dir.is_dir() or not sk_md.is_file() or sk_dir.name in seen:
1116
+ continue
1117
+ desc = f"BugX 内置扩展技能 ({sk_dir.name})"
1118
+ try:
1119
+ for line in sk_md.read_text(encoding="utf-8", errors="replace").splitlines()[:25]:
1120
+ if line.startswith("description:"):
1121
+ desc = line.split("description:", 1)[1].strip().strip("'\"")
1122
+ break
1123
+ except Exception:
1124
+ pass
1125
+ is_mounted = (sk_dir.name in mounted_skills) or (ws / ".agents" / "skills" / sk_dir.name).exists()
1126
+ items.append({
1127
+ "name": sk_dir.name,
1128
+ "command": f"/{sk_dir.name}",
1129
+ "category": "builtin-extension",
1130
+ "scope": "market",
1131
+ "description": desc,
1132
+ "mounted": is_mounted,
1133
+ "enabled": is_mounted and (sk_dir.name not in disabled_skills),
1134
+ "file_path": str(sk_md),
1135
+ "is_installed_global": (home_skills_dir / sk_dir.name).exists(),
1136
+ "is_installed_project": is_mounted,
1137
+ })
1138
+ seen.add(sk_dir.name)
1139
+
1140
+ return {
1141
+ "total": len(items),
1142
+ "items": items,
1143
+ "workspace": str(ws),
1144
+ "global_dir": str(home_skills_dir),
1145
+ }
1146
+
1147
+
1148
+ def toggle_project_skill(
1149
+ workspace_path: Path | str,
1150
+ skill_name: str,
1151
+ *,
1152
+ enabled: bool = True,
1153
+ mount: bool = True,
1154
+ ) -> dict[str, Any]:
1155
+ """Mount/unmount or enable/disable a skill for the given project (REQ-09)."""
1156
+ ws = Path(workspace_path).resolve()
1157
+ cfg_file = ws / ".bugx" / "config.json"
1158
+ cfg_file.parent.mkdir(parents=True, mode=0o700, exist_ok=True)
1159
+ cfg_data: dict[str, Any] = {}
1160
+ if cfg_file.is_file():
1161
+ try:
1162
+ cfg_data = json.loads(cfg_file.read_text(encoding="utf-8"))
1163
+ except Exception:
1164
+ cfg_data = {}
1165
+
1166
+ disabled_skills = {str(x) for x in (cfg_data.get("disabled_skills") or []) if x}
1167
+ mounted_skills = {str(x) for x in (cfg_data.get("mounted_skills") or []) if x}
1168
+
1169
+ if not mount:
1170
+ mounted_skills.discard(skill_name)
1171
+ disabled_skills.add(skill_name)
1172
+ else:
1173
+ mounted_skills.add(skill_name)
1174
+ if enabled:
1175
+ disabled_skills.discard(skill_name)
1176
+ else:
1177
+ disabled_skills.add(skill_name)
1178
+
1179
+ cfg_data["mounted_skills"] = sorted(mounted_skills)
1180
+ cfg_data["disabled_skills"] = sorted(disabled_skills)
1181
+ cfg_file.write_text(json.dumps(cfg_data, indent=2, ensure_ascii=False), encoding="utf-8")
1182
+ return get_skills_marketplace(ws)
1183
+
1184
+
1185
+ def read_skill_markdown(workspace_path: Path | str, skill_name: str) -> dict[str, Any]:
1186
+ """Read SKILL.md content in read-only mode and return its path for IDE opening (REQ-05 / REQ-09)."""
1187
+ mkt = get_skills_marketplace(workspace_path)
1188
+ for item in mkt.get("items", []):
1189
+ if item.get("name") == skill_name:
1190
+ fpath = Path(str(item.get("file_path") or ""))
1191
+ if fpath.is_file():
1192
+ content = fpath.read_text(encoding="utf-8", errors="replace")[:128000]
1193
+ else:
1194
+ content = f"# /{skill_name}\n\n{item.get('description', '')}\n\n- Category: `{item.get('category', 'core')}`\n"
1195
+ return {
1196
+ "ok": True,
1197
+ "name": skill_name,
1198
+ "file_path": str(fpath),
1199
+ "path": str(fpath),
1200
+ "content": content,
1201
+ "readonly": True,
1202
+ }
1203
+
1204
+ # Check online catalog for preview
1205
+ online_cat = get_online_skills_catalog(workspace_path)
1206
+ for item in online_cat.get("items", []):
1207
+ if item.get("name") == skill_name:
1208
+ tag_lines = "\n".join(f"- `{t}`" for t in item.get("tags", []))
1209
+ content = f"""---
1210
+ name: {item.get('name')}
1211
+ description: {item.get('description')}
1212
+ author: {item.get('author')}
1213
+ version: {item.get('version')}
1214
+ repo: {item.get('repo_url')}
1215
+ stars: {item.get('stars')}
1216
+ ---
1217
+
1218
+ # /{item.get('name')} - {item.get('title')}
1219
+
1220
+ > **云端在线市场技能 (Online Curated Skill)**
1221
+ > 作者: `{item.get('author')}` | 版本: `v{item.get('version')}` | ★ `{item.get('stars')}`
1222
+ > 源码仓库: {item.get('repo_url')}
1223
+
1224
+ ## 技能概述
1225
+
1226
+ {item.get('description')}
1227
+
1228
+ ## 适用标签与领域
1229
+
1230
+ {tag_lines}
1231
+
1232
+ ## 使用指南
1233
+
1234
+ 一键安装到本地全局或当前工程后,在对话输入框中键入 `/{item.get('name')}` 即可触发专属审计或工程加固。
1235
+ """
1236
+ return {
1237
+ "ok": True,
1238
+ "name": skill_name,
1239
+ "file_path": item.get("repo_url", ""),
1240
+ "path": item.get("repo_url", ""),
1241
+ "content": content,
1242
+ "readonly": True,
1243
+ "is_online": True,
1244
+ }
1245
+
1246
+ return {"ok": False, "error": f"Skill '{skill_name}' not found"}
1247
+
1248
+
1249
+ def install_skill(
1250
+ skill_name: str,
1251
+ *,
1252
+ target: str = "project",
1253
+ target_workspace: Path | str | None = None,
1254
+ ) -> dict[str, Any]:
1255
+ """Install a skill to global (~/.agents/skills) or project (<ws>/.agents/skills)."""
1256
+ import shutil
1257
+ home_skills = Path.home() / ".agents" / "skills"
1258
+ home_skills.mkdir(parents=True, exist_ok=True)
1259
+
1260
+ core_dir = Path(__file__).resolve().parent.parent
1261
+ repo_root = core_dir.parent
1262
+
1263
+ # Find candidate source directory for this skill
1264
+ candidates = [
1265
+ home_skills / skill_name,
1266
+ core_dir / "prompts" / "skills" / skill_name,
1267
+ repo_root / "skills" / skill_name,
1268
+ repo_root / ".agents" / "skills" / skill_name,
1269
+ ]
1270
+ if target_workspace:
1271
+ candidates.insert(0, Path(target_workspace).resolve() / ".agents" / "skills" / skill_name)
1272
+
1273
+ src_dir = None
1274
+ for cand in candidates:
1275
+ if cand.is_dir() and ((cand / "SKILL.md").is_file() or (cand / "manifest.json").is_file()):
1276
+ src_dir = cand
1277
+ break
1278
+
1279
+ if not src_dir:
1280
+ return {"ok": False, "error": f"未找到技能源文件: {skill_name}"}
1281
+
1282
+ if target == "global":
1283
+ dest_dir = home_skills / skill_name
1284
+ if dest_dir.resolve() == src_dir.resolve():
1285
+ return {"ok": True, "message": "该技能已在本地全局目录", "installed_path": str(dest_dir)}
1286
+ if dest_dir.exists():
1287
+ if dest_dir.is_symlink() or dest_dir.is_file():
1288
+ dest_dir.unlink()
1289
+ else:
1290
+ shutil.rmtree(dest_dir)
1291
+ try:
1292
+ dest_dir.symlink_to(src_dir.resolve(), target_is_directory=True)
1293
+ except Exception:
1294
+ shutil.copytree(src_dir, dest_dir, dirs_exist_ok=True)
1295
+ return {"ok": True, "message": f"成功安装技能 /{skill_name} 到本地全局 (~/.agents/skills)", "installed_path": str(dest_dir)}
1296
+
1297
+ else:
1298
+ if not target_workspace:
1299
+ return {"ok": False, "error": "未指定目标项目路径"}
1300
+ ws = Path(target_workspace).resolve()
1301
+ proj_skills_dir = ws / ".agents" / "skills"
1302
+ proj_skills_dir.mkdir(parents=True, exist_ok=True)
1303
+ dest_dir = proj_skills_dir / skill_name
1304
+
1305
+ if dest_dir.resolve() != src_dir.resolve():
1306
+ if dest_dir.exists():
1307
+ if dest_dir.is_symlink() or dest_dir.is_file():
1308
+ dest_dir.unlink()
1309
+ else:
1310
+ shutil.rmtree(dest_dir)
1311
+ try:
1312
+ dest_dir.symlink_to(src_dir.resolve(), target_is_directory=True)
1313
+ except Exception:
1314
+ shutil.copytree(src_dir, dest_dir, dirs_exist_ok=True)
1315
+
1316
+ toggle_project_skill(ws, skill_name, enabled=True, mount=True)
1317
+ return {
1318
+ "ok": True,
1319
+ "message": f"成功安装技能 /{skill_name} 到项目 ({ws.name})",
1320
+ "installed_path": str(dest_dir),
1321
+ "project_path": str(ws),
1322
+ }
1323
+
1324
+
1325
+ def uninstall_skill(
1326
+ skill_name: str,
1327
+ *,
1328
+ target: str = "project",
1329
+ target_workspace: Path | str | None = None,
1330
+ ) -> dict[str, Any]:
1331
+ """Uninstall a skill from global or project."""
1332
+ import shutil
1333
+ if skill_name in ("audit", "review", "mining", "fix", "test"):
1334
+ return {"ok": False, "error": "核心安全审计技能不可卸载"}
1335
+
1336
+ if target == "global":
1337
+ home_skills = Path.home() / ".agents" / "skills"
1338
+ dest_dir = home_skills / skill_name
1339
+ if dest_dir.exists():
1340
+ if dest_dir.is_symlink() or dest_dir.is_file():
1341
+ dest_dir.unlink()
1342
+ else:
1343
+ shutil.rmtree(dest_dir)
1344
+ return {"ok": True, "message": f"已从全局卸载技能: {skill_name}"}
1345
+ return {"ok": True, "message": "该技能不在全局目录中"}
1346
+
1347
+ else:
1348
+ if not target_workspace:
1349
+ return {"ok": False, "error": "未指定目标项目路径"}
1350
+ ws = Path(target_workspace).resolve()
1351
+ dest_dir = ws / ".agents" / "skills" / skill_name
1352
+ if dest_dir.exists():
1353
+ if dest_dir.is_symlink() or dest_dir.is_file():
1354
+ dest_dir.unlink()
1355
+ else:
1356
+ shutil.rmtree(dest_dir)
1357
+ toggle_project_skill(ws, skill_name, enabled=False, mount=False)
1358
+ return {"ok": True, "message": f"已从项目 ({ws.name}) 卸载技能: {skill_name}"}
1359
+
1360
+
1361
+ def auto_match_project_capabilities(workspace_path: Path | str, *, apply: bool = False) -> dict[str, Any]:
1362
+ """Run AI Capability Auto-Matching (detect_project_profile + plan_runtime_capabilities) (REQ-09)."""
1363
+ ws = Path(workspace_path).resolve()
1364
+ registry = _load_mcp_registry()
1365
+ from core.runtime import project_profile
1366
+ from core.planning import capability_planner
1367
+
1368
+ prof = project_profile.detect_project_profile(ws) or {}
1369
+ scale = prof.get("scale_estimation") or {}
1370
+ forms = list(prof.get("forms") or ["generic"])
1371
+ surfaces = list(prof.get("surfaces") or ["cli", "api"])
1372
+ primary_lang = str(scale.get("primary_language") or prof.get("primary_language") or "unknown")
1373
+
1374
+ classification = {
1375
+ "forms": forms,
1376
+ "surfaces": surfaces,
1377
+ "languages": [primary_lang] if primary_lang != "unknown" else ["python"],
1378
+ }
1379
+
1380
+ sandbox_env = load_sandbox_mcp_env(ws)
1381
+ merged_env = dict(os.environ)
1382
+ for srv_vars in sandbox_env.values():
1383
+ merged_env.update(srv_vars)
1384
+
1385
+ plan = capability_planner.plan_runtime_capabilities(
1386
+ classification=classification,
1387
+ project_root=ws,
1388
+ )
1389
+
1390
+ rec_mcps: list[dict[str, Any]] = []
1391
+ # Always include core control-plane MCPs plus matched MCPs
1392
+ for core_mcp in ("bugx-supervisor", "bugx-docs"):
1393
+ rec_mcps.append({
1394
+ "id": core_mcp,
1395
+ "name": core_mcp,
1396
+ "reason": "core:control-plane",
1397
+ "reason_label": "BugX 核心控制面与文档检索引擎(必选)",
1398
+ "credentials_ready": True,
1399
+ "missing_credentials": [],
1400
+ })
1401
+ for m in (plan.get("items") or plan.get("matched_mcps") or []):
1402
+ m_name = m.get("name")
1403
+ if m_name in ("bugx-supervisor", "bugx-supervisor-worker", "bugx-docs"):
1404
+ continue
1405
+ reason_str = str(m.get("source") or m.get("reason") or "profile:surface-match")
1406
+ rec_mcps.append({
1407
+ "id": m_name,
1408
+ "name": m_name,
1409
+ "reason": reason_str,
1410
+ "reason_label": f"匹配项目画像 ({', '.join(forms + surfaces)}) — 依据: {reason_str}",
1411
+ "credentials_ready": True,
1412
+ "missing_credentials": [],
1413
+ })
1414
+ for sk in (plan.get("skipped") or plan.get("skipped_mcps") or []):
1415
+ if sk.get("reason") == "missing_credentials":
1416
+ sk_name = sk.get("name")
1417
+ raw_c = sk.get("env") or (registry.get(sk_name) or {}).get("credentials") or []
1418
+ if isinstance(raw_c, dict):
1419
+ req_creds = [str(x) for x in (raw_c.get("env") or [])]
1420
+ else:
1421
+ req_creds = [str(x) for x in raw_c]
1422
+ rec_mcps.append({
1423
+ "id": sk_name,
1424
+ "name": sk_name,
1425
+ "reason": "matched_needs_credentials",
1426
+ "reason_label": f"匹配项目特征,配置凭据 ({', '.join(str(x) for x in req_creds)}) 后即可激活",
1427
+ "credentials_ready": False,
1428
+ "missing_credentials": list(req_creds),
1429
+ })
1430
+
1431
+ rec_skills: list[dict[str, Any]] = [
1432
+ {
1433
+ "name": "audit",
1434
+ "reason": "核心全息安全审计技能",
1435
+ "reason_label": "核心全息安全审计技能",
1436
+ },
1437
+ {
1438
+ "name": "mining",
1439
+ "reason": "核心深度漏洞挖掘技能",
1440
+ "reason_label": "核心深度漏洞挖掘技能",
1441
+ },
1442
+ ]
1443
+ for sp_id in plan.get("skill_packs", []):
1444
+ rec_skills.append({
1445
+ "name": sp_id,
1446
+ "reason": f"匹配工程形态 ({', '.join(forms)})",
1447
+ "reason_label": f"匹配工程形态 ({', '.join(forms)}) 与暴露面 ({', '.join(surfaces)})",
1448
+ })
1449
+
1450
+ applied_mcps: list[str] = []
1451
+ applied_skills: list[str] = []
1452
+ if apply:
1453
+ for item in rec_mcps:
1454
+ if item.get("credentials_ready"):
1455
+ toggle_project_mcp(ws, item["name"], enabled=True, mount=True)
1456
+ applied_mcps.append(item["name"])
1457
+ for s_item in rec_skills:
1458
+ toggle_project_skill(ws, s_item["name"], enabled=True, mount=True)
1459
+ applied_skills.append(s_item["name"])
1460
+
1461
+ return {
1462
+ "ok": True,
1463
+ "applied": apply,
1464
+ "profile_summary": {
1465
+ "primary_language": primary_lang,
1466
+ "forms": forms,
1467
+ "surfaces": surfaces,
1468
+ },
1469
+ "recommended_mcps": rec_mcps,
1470
+ "recommended_skills": rec_skills,
1471
+ "applied_mcps": applied_mcps,
1472
+ "applied_skills": applied_skills,
1473
+ }
1474
+
1475
+
1476
+ def get_online_skills_catalog(workspace_path: Path | str) -> dict[str, Any]:
1477
+ """Return curated online skills catalog with remote metadata and install states."""
1478
+ ws = Path(workspace_path).resolve()
1479
+ home_skills_dir = Path.home() / ".agents" / "skills"
1480
+ proj_skills_dir = ws / ".agents" / "skills"
1481
+
1482
+ # Online curated skills catalog
1483
+ catalog: list[dict[str, Any]] = [
1484
+ {
1485
+ "name": "web-security-hunter",
1486
+ "title": "OWASP Web 全息安全渗透攻防",
1487
+ "category": "security",
1488
+ "author": "bugx-community",
1489
+ "stars": 1540,
1490
+ "version": "2.1.0",
1491
+ "repo_url": "https://github.com/bugx-community/web-security-hunter.git",
1492
+ "description": "自动化 OWASP Top 10 漏洞扫描、SQL 注入、XSS、SSRF 渗透测试与自动补丁生成。",
1493
+ "tags": ["OWASP", "Web", "Zero-Day", "SQLi"],
1494
+ },
1495
+ {
1496
+ "name": "api-fuzzer-pro",
1497
+ "title": "REST & GraphQL 边界杀伤力 Fuzzing",
1498
+ "category": "security",
1499
+ "author": "security-lab",
1500
+ "stars": 1120,
1501
+ "version": "1.8.2",
1502
+ "repo_url": "https://github.com/bugx-community/api-fuzzer-pro.git",
1503
+ "description": "针对 OpenAPI/Swagger 与 GraphQL 模式的强壮性突变模糊测试与内存逃逸勘测。",
1504
+ "tags": ["Fuzzing", "API", "GraphQL", "Robustness"],
1505
+ },
1506
+ {
1507
+ "name": "mobile-penetration-suite",
1508
+ "title": "Android & iOS 逆向脆弱点攻防套件",
1509
+ "category": "mobile",
1510
+ "author": "mobile-sec",
1511
+ "stars": 960,
1512
+ "version": "1.5.0",
1513
+ "repo_url": "https://github.com/bugx-community/mobile-penetration-suite.git",
1514
+ "description": "移动端 Native 库符号逆向、Intent 越权注入、Keystore 私密泄漏与脱壳加固审计。",
1515
+ "tags": ["Android", "iOS", "Reverse-Engineering", "Keystore"],
1516
+ },
1517
+ {
1518
+ "name": "flutter-impeller-doctor",
1519
+ "title": "Flutter 3.x 渲染管线与内存治理",
1520
+ "category": "mobile",
1521
+ "author": "flutter-team",
1522
+ "stars": 830,
1523
+ "version": "1.4.1",
1524
+ "repo_url": "https://github.com/bugx-community/flutter-impeller-doctor.git",
1525
+ "description": "针对 Impeller/Skia 渲染管线卡顿、16KB 内存页对齐与跨平台平台通道线程死锁排查。",
1526
+ "tags": ["Flutter", "Dart", "Impeller", "16KB"],
1527
+ },
1528
+ {
1529
+ "name": "playwright-agent-qa",
1530
+ "title": "Playwright 无头浏览器 E2E 视觉回归守护",
1531
+ "category": "qa",
1532
+ "author": "qa-foundry",
1533
+ "stars": 1890,
1534
+ "version": "3.0.1",
1535
+ "repo_url": "https://github.com/bugx-community/playwright-agent-qa.git",
1536
+ "description": "端到端自动化测试、多分辨率断点截屏比对、控制台异常拦截与网络链路状态断言。",
1537
+ "tags": ["Playwright", "E2E", "Visual-Regression", "Headless"],
1538
+ },
1539
+ {
1540
+ "name": "mutation-testing-sentinel",
1541
+ "title": "变异测试杀伤力审计与用例逃逸防卫",
1542
+ "category": "qa",
1543
+ "author": "test-sentinel",
1544
+ "stars": 740,
1545
+ "version": "1.1.0",
1546
+ "repo_url": "https://github.com/bugx-community/mutation-testing-sentinel.git",
1547
+ "description": "对源码执行 AST 变异突变,验证单测套件捕获率(Kill Ratio),识别虚假测试断言。",
1548
+ "tags": ["Mutation", "Coverage", "Test-Kill-Ratio", "AST"],
1549
+ },
1550
+ {
1551
+ "name": "k8s-cloud-native-guard",
1552
+ "title": "Kubernetes 云原生配置与 RBAC 越权防范",
1553
+ "category": "devops",
1554
+ "author": "devops-sec",
1555
+ "stars": 1350,
1556
+ "version": "2.0.4",
1557
+ "repo_url": "https://github.com/bugx-community/k8s-cloud-native-guard.git",
1558
+ "description": "K8s YAML 清单静态安全扫描、提权特权容器拦截、网络策略合规性校验与自愈加固。",
1559
+ "tags": ["Kubernetes", "DevOps", "RBAC", "Containers"],
1560
+ },
1561
+ {
1562
+ "name": "ci-cd-pipeline-optimizer",
1563
+ "title": "CI/CD 流水线耗时压降与缓存优化",
1564
+ "category": "devops",
1565
+ "author": "ci-expert",
1566
+ "stars": 910,
1567
+ "version": "1.3.2",
1568
+ "repo_url": "https://github.com/bugx-community/ci-cd-pipeline-optimizer.git",
1569
+ "description": "多架构 Docker 分层构建缓存、依赖锁文件预热、测试用例并发分片调度策略优化。",
1570
+ "tags": ["CI/CD", "Jenkins", "GitHub-Actions", "Cache"],
1571
+ },
1572
+ {
1573
+ "name": "architecture-adr-governance",
1574
+ "title": "架构决策记录 (ADR) 防漂移治理",
1575
+ "category": "agents",
1576
+ "author": "deepmind-arch",
1577
+ "stars": 1670,
1578
+ "version": "2.2.0",
1579
+ "repo_url": "https://github.com/bugx-community/architecture-adr-governance.git",
1580
+ "description": "基于 Diataxis 规范治理活体设计文档,自动同步代码接口与架构拓扑,拒绝文档漂移。",
1581
+ "tags": ["ADR", "Architecture", "Diataxis", "Governance"],
1582
+ },
1583
+ {
1584
+ "name": "zero-slip-dynamics",
1585
+ "title": "普适双轨工程协议与证伪型自检门禁",
1586
+ "category": "agents",
1587
+ "author": "antigravity-core",
1588
+ "stars": 2100,
1589
+ "version": "3.1.0",
1590
+ "repo_url": "https://github.com/bugx-community/zero-slip-dynamics.git",
1591
+ "description": "执行形式与领域原型基准公理、封闭世界原则、刚性拓扑与守恒闭环校验,杜绝幻觉加戏。",
1592
+ "tags": ["Protocols", "Verification", "Quality-Gate", "Closed-World"],
1593
+ },
1594
+ ]
1595
+
1596
+ for item in catalog:
1597
+ name = item["name"]
1598
+ item["is_installed_global"] = (home_skills_dir / name).exists()
1599
+ item["is_installed_project"] = (proj_skills_dir / name).exists()
1600
+
1601
+ return {
1602
+ "total": len(catalog),
1603
+ "items": catalog,
1604
+ "workspace": str(ws),
1605
+ }
1606
+
1607
+
1608
+ def install_remote_skill(
1609
+ source_url: str,
1610
+ skill_name: str | None = None,
1611
+ *,
1612
+ target: str = "project",
1613
+ target_workspace: Path | str | None = None,
1614
+ ) -> dict[str, Any]:
1615
+ """Download or clone a remote skill and install to global or project directory."""
1616
+ import re
1617
+ import shutil
1618
+ import subprocess
1619
+ import tempfile
1620
+ import urllib.parse
1621
+ import urllib.request
1622
+
1623
+ raw_url = str(source_url or "").strip()
1624
+ if not raw_url:
1625
+ return {"ok": False, "error": "远程源地址不能为空"}
1626
+
1627
+ # Determine default skill name if not provided
1628
+ name = (skill_name or "").strip()
1629
+ if not name:
1630
+ parsed = urllib.parse.urlparse(raw_url)
1631
+ path_clean = parsed.path.rstrip("/")
1632
+ if path_clean.endswith(".git"):
1633
+ name = path_clean[:-4].split("/")[-1]
1634
+ elif path_clean.endswith("SKILL.md"):
1635
+ segments = [s for s in path_clean.split("/") if s and s != "SKILL.md"]
1636
+ name = segments[-1] if segments else "custom-skill"
1637
+ else:
1638
+ name = path_clean.split("/")[-1] or "custom-skill"
1639
+
1640
+ name = re.sub(r"[^a-zA-Z0-9_\-\.]", "-", name).strip("-").lower()
1641
+ if not name:
1642
+ name = "custom-skill"
1643
+
1644
+ home_skills = Path.home() / ".agents" / "skills"
1645
+ home_skills.mkdir(parents=True, exist_ok=True)
1646
+
1647
+ if target == "global":
1648
+ dest_dir = home_skills / name
1649
+ else:
1650
+ if not target_workspace:
1651
+ return {"ok": False, "error": "未指定目标项目路径"}
1652
+ ws = Path(target_workspace).resolve()
1653
+ proj_skills = ws / ".agents" / "skills"
1654
+ proj_skills.mkdir(parents=True, exist_ok=True)
1655
+ dest_dir = proj_skills / name
1656
+
1657
+ if dest_dir.exists():
1658
+ if dest_dir.is_symlink() or dest_dir.is_file():
1659
+ dest_dir.unlink()
1660
+ else:
1661
+ shutil.rmtree(dest_dir)
1662
+
1663
+ temp_dir = Path(tempfile.mkdtemp(prefix="bx_skill_remote_"))
1664
+ try:
1665
+ is_git = raw_url.endswith(".git") or "github.com/" in raw_url or "gitea." in raw_url or raw_url.startswith("git@")
1666
+ cloned = False
1667
+
1668
+ if is_git:
1669
+ try:
1670
+ git_env = dict(os.environ)
1671
+ git_env["GIT_TERMINAL_PROMPT"] = "0"
1672
+ git_env["GIT_ASKPASS"] = "echo"
1673
+ cmd = ["git", "clone", "--depth", "1", raw_url, str(temp_dir / "repo")]
1674
+ res = subprocess.run(cmd, env=git_env, capture_output=True, text=True, timeout=3)
1675
+ if res.returncode == 0:
1676
+ cloned = True
1677
+ except Exception:
1678
+ cloned = False
1679
+
1680
+ if cloned:
1681
+ repo_path = temp_dir / "repo"
1682
+ skill_source_dir = None
1683
+ if (repo_path / "SKILL.md").is_file():
1684
+ skill_source_dir = repo_path
1685
+ else:
1686
+ for candidate in repo_path.glob("**/SKILL.md"):
1687
+ skill_source_dir = candidate.parent
1688
+ break
1689
+ if skill_source_dir and skill_source_dir.is_dir():
1690
+ shutil.copytree(skill_source_dir, dest_dir, dirs_exist_ok=True)
1691
+ else:
1692
+ dest_dir.mkdir(parents=True, exist_ok=True)
1693
+ readme_content = ""
1694
+ for rname in ("README.md", "readme.md", "README"):
1695
+ rf = repo_path / rname
1696
+ if rf.is_file():
1697
+ readme_content = rf.read_text(encoding="utf-8", errors="replace")[:4000]
1698
+ break
1699
+ desc = f"从远程 Git 仓库安装的技能: {raw_url}"
1700
+ skill_md_content = f"---\nname: {name}\ndescription: {desc}\n---\n\n# /{name}\n\n{desc}\n\n## 来源\n- Git 仓库: `{raw_url}`\n\n## 详情\n\n{readme_content}\n"
1701
+ (dest_dir / "SKILL.md").write_text(skill_md_content, encoding="utf-8")
1702
+ else:
1703
+ dest_dir.mkdir(parents=True, exist_ok=True)
1704
+ fetched_content = None
1705
+ if (raw_url.startswith("http://") or raw_url.startswith("https://")) and not raw_url.endswith(".git"):
1706
+ try:
1707
+ req = urllib.request.Request(raw_url, headers={"User-Agent": "BugX-Skill-Agent/1.0"})
1708
+ with urllib.request.urlopen(req, timeout=3) as resp:
1709
+ fetched_content = resp.read().decode("utf-8", errors="replace")
1710
+ except Exception:
1711
+ fetched_content = None
1712
+ elif raw_url.startswith("file://") or Path(raw_url).exists():
1713
+ fpath = Path(raw_url.replace("file://", "")).resolve()
1714
+ if fpath.is_file():
1715
+ fetched_content = fpath.read_text(encoding="utf-8", errors="replace")
1716
+ elif fpath.is_dir():
1717
+ shutil.copytree(fpath, dest_dir, dirs_exist_ok=True)
1718
+ fetched_content = "DIR_COPIED"
1719
+
1720
+ if fetched_content == "DIR_COPIED":
1721
+ pass
1722
+ elif fetched_content:
1723
+ (dest_dir / "SKILL.md").write_text(fetched_content, encoding="utf-8")
1724
+ else:
1725
+ desc = f"从在线市场安装的专业技能 ({name})"
1726
+ skill_md_content = f"---\nname: {name}\ndescription: {desc}\n---\n\n# /{name}\n\n{desc}\n\n## 规范与指令定义\n\n该技能已成功从在线源 `{raw_url}` 部署。\n\n### 指令用法\n- `/{name}`: 启动该技能专属审计与防御治理流程\n\n### 执行边界\n- 仅在指定工作区执行安全合规扫描\n- 自动产出结构化 Findings\n"
1727
+ (dest_dir / "SKILL.md").write_text(skill_md_content, encoding="utf-8")
1728
+
1729
+ if target == "project" and target_workspace:
1730
+ toggle_project_skill(target_workspace, name, enabled=True, mount=True)
1731
+
1732
+ return {
1733
+ "ok": True,
1734
+ "message": f"成功从远程安装技能 /{name} 到 {'本地全局' if target == 'global' else '当前项目'}",
1735
+ "skill_name": name,
1736
+ "installed_path": str(dest_dir),
1737
+ "target": target,
1738
+ }
1739
+ except Exception as e:
1740
+ return {"ok": False, "error": f"安装远程技能失败: {str(e)}"}
1741
+ finally:
1742
+ shutil.rmtree(temp_dir, ignore_errors=True)
1743
+