bugx-cli 0.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (762) hide show
  1. bugx_cli/__init__.py +6 -0
  2. bugx_cli/cli.py +1685 -0
  3. bugx_cli/commands/__init__.py +1 -0
  4. bugx_cli/commands/advisory.py +94 -0
  5. bugx_cli/commands/agent.py +4210 -0
  6. bugx_cli/commands/audit.py +632 -0
  7. bugx_cli/commands/autonomous.py +260 -0
  8. bugx_cli/commands/cloud.py +1371 -0
  9. bugx_cli/commands/daemon.py +50 -0
  10. bugx_cli/commands/doctor.py +1590 -0
  11. bugx_cli/commands/goal.py +107 -0
  12. bugx_cli/commands/interaction.py +248 -0
  13. bugx_cli/commands/knowledge.py +619 -0
  14. bugx_cli/commands/lifecycle.py +2763 -0
  15. bugx_cli/commands/patch.py +1014 -0
  16. bugx_cli/commands/plugin.py +2749 -0
  17. bugx_cli/commands/plugin_claude.py +1446 -0
  18. bugx_cli/commands/plugin_cline.py +269 -0
  19. bugx_cli/commands/plugin_codex.py +74 -0
  20. bugx_cli/commands/plugin_funide.py +729 -0
  21. bugx_cli/commands/plugin_qoder.py +216 -0
  22. bugx_cli/commands/plugin_zcode.py +710 -0
  23. bugx_cli/commands/project.py +670 -0
  24. bugx_cli/commands/report.py +256 -0
  25. bugx_cli/commands/skill.py +251 -0
  26. bugx_cli/commands/stats.py +133 -0
  27. bugx_cli/commands/system.py +2567 -0
  28. bugx_cli/common.py +906 -0
  29. bugx_cli/host_adapters.py +1892 -0
  30. bugx_cli/hosts/__init__.py +80 -0
  31. bugx_cli/hosts/base.py +99 -0
  32. bugx_cli/hosts/registry.py +573 -0
  33. bugx_cli/hosts/template_engine.py +188 -0
  34. bugx_cli/infra/__init__.py +209 -0
  35. bugx_cli/infra/ai_advisor.py +851 -0
  36. bugx_cli/infra/engine_installer.py +1945 -0
  37. bugx_cli/infra/host_sync.py +548 -0
  38. bugx_cli/infra/mcp_advisor.py +826 -0
  39. bugx_cli/infra/security.py +339 -0
  40. bugx_cli-0.1.1.data/data/share/bugx-agent/bugx-mcp-manifest.json +53 -0
  41. bugx_cli-0.1.1.data/data/share/bugx-agent/core/CATALOG.json +141 -0
  42. bugx_cli-0.1.1.data/data/share/bugx-agent/core/README.md +254 -0
  43. bugx_cli-0.1.1.data/data/share/bugx-agent/core/adapters/README.md +35 -0
  44. bugx_cli-0.1.1.data/data/share/bugx-agent/core/adapters/android-interaction.json +81 -0
  45. bugx_cli-0.1.1.data/data/share/bugx-agent/core/adapters/android.json +24 -0
  46. bugx_cli-0.1.1.data/data/share/bugx-agent/core/adapters/desktop-macos.json +20 -0
  47. bugx_cli-0.1.1.data/data/share/bugx-agent/core/adapters/ios-interaction.json +34 -0
  48. bugx_cli-0.1.1.data/data/share/bugx-agent/core/adapters/ios.json +23 -0
  49. bugx_cli-0.1.1.data/data/share/bugx-agent/core/adapters/memory-macos.json +24 -0
  50. bugx_cli-0.1.1.data/data/share/bugx-agent/core/agent/README.md +51 -0
  51. bugx_cli-0.1.1.data/data/share/bugx-agent/core/agent/__init__.py +146 -0
  52. bugx_cli-0.1.1.data/data/share/bugx-agent/core/agent/agent_artifacts.py +766 -0
  53. bugx_cli-0.1.1.data/data/share/bugx-agent/core/agent/agent_eval.py +1155 -0
  54. bugx_cli-0.1.1.data/data/share/bugx-agent/core/agent/agent_execution.py +718 -0
  55. bugx_cli-0.1.1.data/data/share/bugx-agent/core/agent/agent_orchestrator.py +1351 -0
  56. bugx_cli-0.1.1.data/data/share/bugx-agent/core/agent/agent_targets.py +877 -0
  57. bugx_cli-0.1.1.data/data/share/bugx-agent/core/agent/agent_workspace.py +770 -0
  58. bugx_cli-0.1.1.data/data/share/bugx-agent/core/agent/feature_baseline.py +150 -0
  59. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/README.md +24 -0
  60. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/axe-core/LICENSE-3RD-PARTY.txt +66 -0
  61. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/axe-core/LICENSE.txt +362 -0
  62. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/axe-core/UPSTREAM.md +10 -0
  63. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/axe-core/axe.min.js +12 -0
  64. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/bugx-avatar-1024.png +0 -0
  65. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/bugx-avatar-512.png +0 -0
  66. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/bugx-avatar-tight.svg +23 -0
  67. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/bugx-avatar.svg +28 -0
  68. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/bugx-hero-cn.png +0 -0
  69. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/bugx-hero-en.png +0 -0
  70. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/bugx-hero-en.svg +74 -0
  71. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/bugx-hero-zh.svg +74 -0
  72. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/codex.png +0 -0
  73. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/dsh.png +0 -0
  74. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/project-layout.md +42 -0
  75. bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/zcode.png +0 -0
  76. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/README.md +37 -0
  77. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/data-audit/manifest.json +94 -0
  78. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/data-audit/stages/00-scope.md +14 -0
  79. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/data-audit/stages/10-schema-inventory.md +14 -0
  80. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/data-audit/stages/20-query-and-integrity.md +14 -0
  81. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/data-audit/stages/80-evidence-regression.md +14 -0
  82. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/desktop-audit/manifest.json +123 -0
  83. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/desktop-audit/stages/00-scope.md +15 -0
  84. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/desktop-audit/stages/10-process-model.md +14 -0
  85. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/desktop-audit/stages/20-package-integrity.md +15 -0
  86. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/desktop-audit/stages/30-ui-behavior.md +14 -0
  87. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/desktop-audit/stages/80-evidence-regression.md +15 -0
  88. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/memory-testing.md +227 -0
  89. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/manifest.json +155 -0
  90. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/modules/android.md +19 -0
  91. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/modules/h5.md +18 -0
  92. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/modules/ios.md +25 -0
  93. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/modules/miniprogram.md +26 -0
  94. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/modules/webview.md +18 -0
  95. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/stages/00-scope.md +14 -0
  96. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/stages/10-platform-inventory.md +14 -0
  97. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/stages/20-masvs-static.md +20 -0
  98. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/stages/30-component-exposure.md +14 -0
  99. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/stages/40-device-behavior.md +14 -0
  100. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/stages/80-evidence-regression.md +13 -0
  101. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/native-audit/manifest.json +127 -0
  102. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/native-audit/stages/00-scope.md +14 -0
  103. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/native-audit/stages/10-static-white-box.md +14 -0
  104. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/native-audit/stages/20-memory-concurrency.md +15 -0
  105. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/native-audit/stages/30-behavior-black-box.md +39 -0
  106. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/native-audit/stages/80-evidence-regression.md +14 -0
  107. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/platform-testing.md +174 -0
  108. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/manifest.json +191 -0
  109. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/modules/graphql.md +5 -0
  110. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/modules/h5.md +18 -0
  111. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/modules/multi-tenant.md +4 -0
  112. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/modules/oauth.md +4 -0
  113. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/modules/upload.md +4 -0
  114. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/modules/websocket.md +4 -0
  115. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/stages/00-scope.md +13 -0
  116. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/stages/10-discovery.md +13 -0
  117. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/stages/20-auth-session.md +13 -0
  118. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/stages/30-authz-business.md +13 -0
  119. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/stages/40-input-output.md +13 -0
  120. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/stages/50-state-async.md +13 -0
  121. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/stages/60-file-ssrf-deser.md +12 -0
  122. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/stages/70-config-dependency.md +12 -0
  123. bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/stages/80-evidence-regression.md +12 -0
  124. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/INTERFACE.md +61 -0
  125. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/README.md +58 -0
  126. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/SPEC.md +25 -0
  127. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/__init__.py +109 -0
  128. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/attack_graph.py +1096 -0
  129. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/attack_graph_store.py +1868 -0
  130. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/audit_campaign.py +1232 -0
  131. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/behavior_graph.py +465 -0
  132. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/ghsa_advisories.py +174 -0
  133. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/models.py +93 -0
  134. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/mutator.py +87 -0
  135. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/patcher.py +126 -0
  136. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/scout.py +278 -0
  137. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/synthesizer.py +207 -0
  138. bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/verifier.py +103 -0
  139. bugx_cli-0.1.1.data/data/share/bugx-agent/core/bugx.md +1299 -0
  140. bugx_cli-0.1.1.data/data/share/bugx-agent/core/bugx_paths.py +1881 -0
  141. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cli-help.txt +66 -0
  142. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/INTERFACE.md +32 -0
  143. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/README.md +62 -0
  144. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/SPEC.md +25 -0
  145. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/__init__.py +23 -0
  146. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/auto_sync.py +398 -0
  147. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/cloud_client.py +1218 -0
  148. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/cloud_onboard.py +743 -0
  149. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/cloud_schema.py +648 -0
  150. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/consent.py +81 -0
  151. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/device_identity.py +307 -0
  152. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/endpoint_router.py +415 -0
  153. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/flywheel_client.py +769 -0
  154. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/network_transport.py +296 -0
  155. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/onboard_wizard.py +493 -0
  156. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/sensitive_filter.py +285 -0
  157. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/sync_pull.py +695 -0
  158. bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/sync_push.py +723 -0
  159. bugx_cli-0.1.1.data/data/share/bugx-agent/core/contracts/AGENT_GUIDE.md +359 -0
  160. bugx_cli-0.1.1.data/data/share/bugx-agent/core/contracts/README.md +34 -0
  161. bugx_cli-0.1.1.data/data/share/bugx-agent/core/contracts/bugx-blackbox.md +541 -0
  162. bugx_cli-0.1.1.data/data/share/bugx-agent/core/contracts/bugx-opencode.md +469 -0
  163. bugx_cli-0.1.1.data/data/share/bugx-agent/core/contracts/bugx-quick.md +44 -0
  164. bugx_cli-0.1.1.data/data/share/bugx-agent/core/contracts/bugx-runtime-contract.md +353 -0
  165. bugx_cli-0.1.1.data/data/share/bugx-agent/core/contracts/bugx-worker.md +470 -0
  166. bugx_cli-0.1.1.data/data/share/bugx-agent/core/contracts/engine_gap_contracts.py +473 -0
  167. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/README.md +70 -0
  168. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/__init__.py +106 -0
  169. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_ai_review.py +185 -0
  170. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_backfill.py +54 -0
  171. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_bootstrap.py +713 -0
  172. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_business.py +36 -0
  173. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_cli.py +715 -0
  174. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_discovery.py +1429 -0
  175. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_evidence.py +1024 -0
  176. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_forensics.py +124 -0
  177. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_gate.py +277 -0
  178. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_intelligence.py +734 -0
  179. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_manifest.py +396 -0
  180. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_platform.py +77 -0
  181. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_validate.py +241 -0
  182. bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/module_coverage.py +157 -0
  183. bugx_cli-0.1.1.data/data/share/bugx-agent/core/dev_harness/INTERFACE.md +20 -0
  184. bugx_cli-0.1.1.data/data/share/bugx-agent/core/dev_harness/README.md +21 -0
  185. bugx_cli-0.1.1.data/data/share/bugx-agent/core/dev_harness/SPEC.md +25 -0
  186. bugx_cli-0.1.1.data/data/share/bugx-agent/core/dev_harness/__init__.py +5 -0
  187. bugx_cli-0.1.1.data/data/share/bugx-agent/core/dev_harness/interaction_preset.py +408 -0
  188. bugx_cli-0.1.1.data/data/share/bugx-agent/core/engine-integrity.json +2797 -0
  189. bugx_cli-0.1.1.data/data/share/bugx-agent/core/fuzzing/README.md +49 -0
  190. bugx_cli-0.1.1.data/data/share/bugx-agent/core/fuzzing/__init__.py +82 -0
  191. bugx_cli-0.1.1.data/data/share/bugx-agent/core/fuzzing/concurrency_fuzzer.py +435 -0
  192. bugx_cli-0.1.1.data/data/share/bugx-agent/core/fuzzing/differential_oracle.py +1164 -0
  193. bugx_cli-0.1.1.data/data/share/bugx-agent/core/fuzzing/fuzz_input.py +1291 -0
  194. bugx_cli-0.1.1.data/data/share/bugx-agent/core/fuzzing/stateful_fuzzer.py +404 -0
  195. bugx_cli-0.1.1.data/data/share/bugx-agent/core/governance/README.md +61 -0
  196. bugx_cli-0.1.1.data/data/share/bugx-agent/core/governance/__init__.py +130 -0
  197. bugx_cli-0.1.1.data/data/share/bugx-agent/core/governance/capacity_planner.py +124 -0
  198. bugx_cli-0.1.1.data/data/share/bugx-agent/core/governance/dependency_lock.py +317 -0
  199. bugx_cli-0.1.1.data/data/share/bugx-agent/core/governance/goal_governor.py +754 -0
  200. bugx_cli-0.1.1.data/data/share/bugx-agent/core/governance/guide_budget.py +458 -0
  201. bugx_cli-0.1.1.data/data/share/bugx-agent/core/governance/lockdown.sh +50 -0
  202. bugx_cli-0.1.1.data/data/share/bugx-agent/core/governance/readonly_enforcer.py +154 -0
  203. bugx_cli-0.1.1.data/data/share/bugx-agent/core/governance/runtime_tool_gate.py +373 -0
  204. bugx_cli-0.1.1.data/data/share/bugx-agent/core/governance/secret_redactor.py +784 -0
  205. bugx_cli-0.1.1.data/data/share/bugx-agent/core/governance/token_budget.py +38 -0
  206. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/INTERFACE.md +36 -0
  207. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/README.md +51 -0
  208. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/SPEC.md +25 -0
  209. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/__init__.py +121 -0
  210. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/base.py +111 -0
  211. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/claude.py +99 -0
  212. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/cline.py +298 -0
  213. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/codex.py +300 -0
  214. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/dsh.py +106 -0
  215. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/opencode.py +209 -0
  216. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/pi.py +94 -0
  217. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/zcode.py +99 -0
  218. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/INTERFACE.md +24 -0
  219. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/README.md +62 -0
  220. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/SPEC.md +25 -0
  221. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/__init__.py +21 -0
  222. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/adapters.py +412 -0
  223. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/autonomous_runner.py +1152 -0
  224. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/cline.py +448 -0
  225. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/common.py +103 -0
  226. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/free_models.py +786 -0
  227. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/host_bootstrap.py +389 -0
  228. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/host_evaluators.py +761 -0
  229. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/host_probe.py +41 -0
  230. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/host_provider_arbitrator.py +831 -0
  231. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/host_registry.py +662 -0
  232. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/host_usage.py +127 -0
  233. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/mcp_process_tracker.py +509 -0
  234. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/mcp_registry_gate.py +379 -0
  235. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/pi.py +102 -0
  236. bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/provider_facts.py +66 -0
  237. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/INTERFACE.md +51 -0
  238. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/README.md +67 -0
  239. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/SPEC.md +25 -0
  240. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/__init__.py +140 -0
  241. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/_base_usage.py +152 -0
  242. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/_codex_usage.py +297 -0
  243. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/_dsh_usage.py +184 -0
  244. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/_mcp_toml.py +365 -0
  245. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/_zcode_usage.py +269 -0
  246. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/base.py +479 -0
  247. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/claude.py +212 -0
  248. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/cline.py +229 -0
  249. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/codex.py +1006 -0
  250. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/dsh.py +526 -0
  251. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/opencode.py +358 -0
  252. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/pi.py +308 -0
  253. bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/zcode.py +219 -0
  254. bugx_cli-0.1.1.data/data/share/bugx-agent/core/i18n.py +252 -0
  255. bugx_cli-0.1.1.data/data/share/bugx-agent/core/infra/README.md +41 -0
  256. bugx_cli-0.1.1.data/data/share/bugx-agent/core/infra/__init__.py +17 -0
  257. bugx_cli-0.1.1.data/data/share/bugx-agent/core/infra/build_info.py +105 -0
  258. bugx_cli-0.1.1.data/data/share/bugx-agent/core/infra/client_metadata.py +185 -0
  259. bugx_cli-0.1.1.data/data/share/bugx-agent/core/infra/json_utils.py +22 -0
  260. bugx_cli-0.1.1.data/data/share/bugx-agent/core/infra/python_runtime.py +540 -0
  261. bugx_cli-0.1.1.data/data/share/bugx-agent/core/infra/safe_xml.py +221 -0
  262. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_bugx.py +118 -0
  263. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/INTERFACE.md +31 -0
  264. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/README.md +106 -0
  265. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/SPEC.md +25 -0
  266. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/__init__.py +29 -0
  267. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/candidate_revalidation.py +484 -0
  268. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/common.py +1060 -0
  269. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/finding_confirm_phase.py +391 -0
  270. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/finding_settlement.py +1432 -0
  271. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/findings_adjudication.py +666 -0
  272. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/findings_snapshot.py +357 -0
  273. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/judge_phase.py +848 -0
  274. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/lesson_context.py +536 -0
  275. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/lifecycle_reporter.py +627 -0
  276. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/orchestrator_controls.py +686 -0
  277. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/post_commit.py +567 -0
  278. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/post_coverage_sync.py +598 -0
  279. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/post_dry_run.py +817 -0
  280. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/post_observability.py +367 -0
  281. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/post_phase.py +1223 -0
  282. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/post_receipt.py +373 -0
  283. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/post_round_lifecycle.py +786 -0
  284. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/pre_phase.py +1029 -0
  285. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/pre_recon_scout.py +879 -0
  286. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/pre_state_builder.py +1133 -0
  287. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/report_sharing.py +414 -0
  288. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/round_orchestrator.py +1116 -0
  289. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/session_runtime.py +1670 -0
  290. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/startup_gates.py +1050 -0
  291. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/startup_interaction.py +1003 -0
  292. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/startup_version_gate.py +879 -0
  293. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/supervisor_bridge.py +1253 -0
  294. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/supervisor_coverage.py +423 -0
  295. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/supervisor_degraded.py +1211 -0
  296. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/worker_barriers.py +424 -0
  297. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/worker_orchestrator.py +1246 -0
  298. bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/worker_prior.py +749 -0
  299. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/INTERFACE.md +35 -0
  300. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/README.md +160 -0
  301. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/SPEC.md +25 -0
  302. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/__init__.py +67 -0
  303. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/_facade.py +227 -0
  304. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/archive_ops.py +630 -0
  305. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/auto_materialization.py +459 -0
  306. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/bug-log.md +22 -0
  307. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/cli.py +275 -0
  308. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/export_ops.py +554 -0
  309. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/finding_confirmation.py +1316 -0
  310. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/finding_io.py +299 -0
  311. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/finding_lifecycle.py +730 -0
  312. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/finding_verification.py +405 -0
  313. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/incidents.py +1005 -0
  314. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/lesson-replay-cases.json +20 -0
  315. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/lesson_ledger.py +241 -0
  316. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/lesson_replay.py +272 -0
  317. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/life_ledger.py +668 -0
  318. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/mistake-book.md +130 -0
  319. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/patterns.py +684 -0
  320. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/receipt_contract.py +269 -0
  321. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/schema.py +1192 -0
  322. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/sync_ops.py +940 -0
  323. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/tool_experience.py +683 -0
  324. bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/verify_life.py +1597 -0
  325. bugx_cli-0.1.1.data/data/share/bugx-agent/core/lesson-ledger.json +275 -0
  326. bugx_cli-0.1.1.data/data/share/bugx-agent/core/locales/README.md +19 -0
  327. bugx_cli-0.1.1.data/data/share/bugx-agent/core/locales/en-US.json +462 -0
  328. bugx_cli-0.1.1.data/data/share/bugx-agent/core/locales/zh-CN.json +462 -0
  329. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/INTERFACE.md +75 -0
  330. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/README.md +62 -0
  331. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/SPEC.md +25 -0
  332. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/__init__.py +128 -0
  333. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/base.py +717 -0
  334. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/channel_lifecycle.py +751 -0
  335. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/graph_handlers.py +222 -0
  336. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/knowledge_handlers.py +536 -0
  337. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/mining_handlers.py +586 -0
  338. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/resource_prompt_table.py +116 -0
  339. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/retrieval_handlers.py +249 -0
  340. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/rpc_server.py +470 -0
  341. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/supervisor_handlers.py +1461 -0
  342. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/telemetry_handlers.py +227 -0
  343. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/tool_table.py +1030 -0
  344. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_runtime_support/README.md +21 -0
  345. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_runtime_support/__init__.py +1 -0
  346. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_runtime_support/common.py +363 -0
  347. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_runtime_support/environment.py +567 -0
  348. bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_runtime_support/verifier.py +758 -0
  349. bugx_cli-0.1.1.data/data/share/bugx-agent/core/metadata.txt +4 -0
  350. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/README.md +157 -0
  351. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/__init__.py +242 -0
  352. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/capability_plan.py +187 -0
  353. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/capability_planner.py +195 -0
  354. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/domain_archetype.py +542 -0
  355. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/domain_router.py +269 -0
  356. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/dynamic_flow_analyzer.py +533 -0
  357. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/impact_pruner.py +435 -0
  358. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/intent_adjudicator.py +175 -0
  359. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/judge_pipeline.py +1246 -0
  360. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/logic_analysis.py +419 -0
  361. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/prompt_harness.py +1704 -0
  362. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/source_inspector.py +267 -0
  363. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/spec_harvester.py +449 -0
  364. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/target_sandbox_manager.py +573 -0
  365. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/test_capability_verifier.py +1364 -0
  366. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/tools-kb.md +38 -0
  367. bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/unit_kind.py +122 -0
  368. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/INTERFACE.md +83 -0
  369. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/README.md +51 -0
  370. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/SPEC.md +36 -0
  371. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/__init__.py +76 -0
  372. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/android_probe.py +552 -0
  373. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/base.py +147 -0
  374. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/codebase_memory_probe.py +647 -0
  375. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/desktop_probe.py +342 -0
  376. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/differential_probe.py +434 -0
  377. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/efficiency_probe.py +232 -0
  378. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/ios_binary_probe.py +472 -0
  379. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/memory_probe.py +392 -0
  380. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/miniprogram_probe.py +385 -0
  381. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/mobile_probe.py +466 -0
  382. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/native_probe.py +302 -0
  383. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/openwiki_probe.py +263 -0
  384. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/pattern_probe.py +453 -0
  385. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/platform_probe.py +424 -0
  386. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/probe_registry.py +1770 -0
  387. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/sast_fixture_corpus.py +340 -0
  388. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/sast_probe.py +1510 -0
  389. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/sast_rules.py +1481 -0
  390. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/sca_scanner.py +779 -0
  391. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/ui_accessibility.py +149 -0
  392. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/ui_audit.py +513 -0
  393. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/ui_contract.py +273 -0
  394. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/ui_evidence.py +212 -0
  395. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/ui_measurements.py +314 -0
  396. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/ui_repair.py +250 -0
  397. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/ui_review.py +133 -0
  398. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/ui_storybook.py +107 -0
  399. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/ui_tokens.py +185 -0
  400. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/ui_visual_diff.py +131 -0
  401. bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/web_probe.py +714 -0
  402. bugx_cli-0.1.1.data/data/share/bugx-agent/core/project_profiler/INTERFACE.md +62 -0
  403. bugx_cli-0.1.1.data/data/share/bugx-agent/core/project_profiler/README.md +53 -0
  404. bugx_cli-0.1.1.data/data/share/bugx-agent/core/project_profiler/SPEC.md +28 -0
  405. bugx_cli-0.1.1.data/data/share/bugx-agent/core/project_profiler/__init__.py +201 -0
  406. bugx_cli-0.1.1.data/data/share/bugx-agent/core/project_profiler/arbitrator.py +316 -0
  407. bugx_cli-0.1.1.data/data/share/bugx-agent/core/project_profiler/constants.py +247 -0
  408. bugx_cli-0.1.1.data/data/share/bugx-agent/core/project_profiler/detector.py +399 -0
  409. bugx_cli-0.1.1.data/data/share/bugx-agent/core/project_profiler/extractors.py +836 -0
  410. bugx_cli-0.1.1.data/data/share/bugx-agent/core/project_profiler/fingerprint.py +116 -0
  411. bugx_cli-0.1.1.data/data/share/bugx-agent/core/project_profiler/storage.py +258 -0
  412. bugx_cli-0.1.1.data/data/share/bugx-agent/core/project_profiler/strategy.py +301 -0
  413. bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/README.md +35 -0
  414. bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/codex_dialog_dispatch.md +9 -0
  415. bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/command_routing_en.md +42 -0
  416. bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/command_routing_zh.md +42 -0
  417. bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/l0_router.md +47 -0
  418. bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/rules/anti_patterns.md +16 -0
  419. bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/rules/concurrency_rules.md +14 -0
  420. bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/rules/memory_leak_rules.md +13 -0
  421. bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/rules/prompt_injection_defense.md +13 -0
  422. bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/stages/stage_explore.md +31 -0
  423. bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/stages/stage_gate.md +43 -0
  424. bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/stages/stage_mutate.md +42 -0
  425. bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/stages/stage_repair.md +85 -0
  426. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/README.md +74 -0
  427. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/__init__.py +169 -0
  428. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/fix_watchlist.py +391 -0
  429. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/l7_dynamic.py +418 -0
  430. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/l7_repair_loop.py +462 -0
  431. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/l7_selfcheck.py +862 -0
  432. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/minimize_repro.py +466 -0
  433. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/patch_synthesizer.py +617 -0
  434. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/regression_pack.py +379 -0
  435. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/rsi_fixer.py +910 -0
  436. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/rsi_loop.py +311 -0
  437. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/rsi_repair.py +348 -0
  438. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/rsi_rounds.py +212 -0
  439. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/rsi_scope.py +281 -0
  440. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/self_heal.py +604 -0
  441. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/test_generator.py +1108 -0
  442. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/test_quality_auditor.py +410 -0
  443. bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/test_strategy.py +511 -0
  444. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/INTERFACE.md +59 -0
  445. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/README.md +69 -0
  446. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/SPEC.md +28 -0
  447. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/__init__.py +47 -0
  448. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/attestation.py +228 -0
  449. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/authority.py +255 -0
  450. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/finding_report.py +418 -0
  451. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/formal_report_builder.py +924 -0
  452. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/html_renderers.py +696 -0
  453. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/models.py +759 -0
  454. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/pdf_exporter.py +231 -0
  455. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/projects_assets.py +730 -0
  456. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/report_client.py +743 -0
  457. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/report_data_builder.py +388 -0
  458. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/report_share.py +459 -0
  459. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/sast_bridge.py +116 -0
  460. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/server.py +832 -0
  461. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/visual_report_builder.py +796 -0
  462. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/web-conformance.md +168 -0
  463. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/web_conformance.py +428 -0
  464. bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/workbench_assets.py +484 -0
  465. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/INTERFACE.md +20 -0
  466. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/README.md +161 -0
  467. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/SPEC.md +25 -0
  468. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/__init__.py +3 -0
  469. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/code_analyzer.py +1720 -0
  470. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/codebase_memory_bridge.py +337 -0
  471. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/context_assembler.py +240 -0
  472. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/corpus_fetch.py +369 -0
  473. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/graph_ego.py +597 -0
  474. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/knowledge_auto.py +662 -0
  475. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/knowledge_sources.py +168 -0
  476. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/knowledge_sync.py +1003 -0
  477. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/memory_store.py +480 -0
  478. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/query_planner.py +1020 -0
  479. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/rrf_engine.py +137 -0
  480. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/slice_extractor.py +1209 -0
  481. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/slice_normalizer.py +373 -0
  482. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/slice_spec.py +357 -0
  483. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/symbol_index.py +1151 -0
  484. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/universal_code_matcher.py +622 -0
  485. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/xerj_bridge.py +476 -0
  486. bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/xerj_supervisor.py +362 -0
  487. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/README.md +33 -0
  488. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/ios/PROVENANCE.json +30 -0
  489. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/ios/crypto.yaml +36 -0
  490. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/ios/network.yaml +20 -0
  491. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/ios/resilience.yaml +47 -0
  492. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/ios/storage.yaml +48 -0
  493. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/LICENSE +173 -0
  494. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/PROVENANCE.json +270 -0
  495. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-asymmetric-key-pair-used-for-multiple-purposes.yml +13 -0
  496. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-backup-manifest.yml +24 -0
  497. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-biometric-event-bound.yml +49 -0
  498. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-biometric-invalidated-enrollment.yml +11 -0
  499. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-biometric-no-confirmation-required.yml +10 -0
  500. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-biometric-validity-duration.yml +24 -0
  501. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-broken-encryption-algorithms.yaml +9 -0
  502. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-broken-encryption-modes.yaml +13 -0
  503. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-content-provider-exported.yml +35 -0
  504. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-custom-deeplink-scheme.yml +29 -0
  505. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-dangerous-app-permissions.yaml +65 -0
  506. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-data-unencrypted-shared-storage-no-user-interaction-apis.yml +36 -0
  507. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-data-unencrypted-shared-storage-no-user-interaction-manifest.yml +15 -0
  508. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-debuggable-flag.yml +10 -0
  509. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-debugger-checks.yml +12 -0
  510. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-deeplink-autoverify-missing.yml +33 -0
  511. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-deeplink-unvalidated-parameter.yml +11 -0
  512. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-device-passcode-present.yml +17 -0
  513. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-fileprovider-broad-scope.yml +46 -0
  514. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-hardcoded-crypto-keys-usage.yml +14 -0
  515. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-hardcoded-security-provider.yaml +18 -0
  516. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-implicit-intent-internal-communication.yml +30 -0
  517. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-implicit-intent-leaking-extras.yml +29 -0
  518. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-input-field-usage.yml +11 -0
  519. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-key-generation-with-insufficient-key-length.yml +21 -0
  520. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-keyboard-cache-input-types.yml +10 -0
  521. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-local-storage-input-validation.yml +48 -0
  522. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-native-debugger-checks.yml +12 -0
  523. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-network-checkservertrusted.yml +12 -0
  524. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-network-hostname-verification.yml +11 -0
  525. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-network-insecure-trust-anchors.yml +11 -0
  526. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-network-onreceivedsslerror.yml +12 -0
  527. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-non-random-use.yml +16 -0
  528. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-object-deserialization.yml +14 -0
  529. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-overlay-protection.yml +68 -0
  530. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-pendingintent-mutable.yml +39 -0
  531. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-random-apis-insufficient-entropy.yml +17 -0
  532. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-root-detection.yaml +59 -0
  533. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-sdk-version.yml +10 -0
  534. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-sensitive-data-in-notifications-manifest.yml +17 -0
  535. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-sensitive-data-in-notifications.yml +11 -0
  536. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-sensitive-data-in-screenshot.yml +18 -0
  537. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-sql-injection-contentprovider.yml +17 -0
  538. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-ssl-socket-hostnameverifier.yml +15 -0
  539. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-strictmode.yml +10 -0
  540. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-system-alert-window.yml +9 -0
  541. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-webview-allow-local-access.yml +15 -0
  542. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-webview-bridges.yml +28 -0
  543. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-webview-safebrowsing.yml +20 -0
  544. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-webview-url-handlers.yml +41 -0
  545. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/miniprogram/PROVENANCE.json +26 -0
  546. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/miniprogram/network.yaml +37 -0
  547. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/miniprogram/platform.yaml +36 -0
  548. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/miniprogram/storage.yaml +48 -0
  549. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/LICENSE +165 -0
  550. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/PROVENANCE.json +58 -0
  551. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/auth.yaml +59 -0
  552. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/crypto.yaml +66 -0
  553. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/jailbreak.yaml +14 -0
  554. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/keyboard.yaml +34 -0
  555. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/logging.yaml +23 -0
  556. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/network.yaml +55 -0
  557. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/resilience.yaml +29 -0
  558. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/secrets.yaml +33 -0
  559. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/storage.yaml +29 -0
  560. bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/webview.yaml +32 -0
  561. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/README.md +198 -0
  562. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/__init__.py +3 -0
  563. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/bugx_logging.py +1464 -0
  564. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/daemon_runner.py +623 -0
  565. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/fixture_solidify.py +444 -0
  566. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/global_telemetry.py +549 -0
  567. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/incident_eval.py +148 -0
  568. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/interaction.py +605 -0
  569. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/interaction_store.py +435 -0
  570. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/interactive_menu.py +95 -0
  571. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/log_analytics.py +922 -0
  572. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/mining_quality_framework.py +1387 -0
  573. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/model_runner.py +732 -0
  574. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/platform_adapter.py +579 -0
  575. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/prep_validate.py +478 -0
  576. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/project_graph.py +827 -0
  577. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/project_init.py +481 -0
  578. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/project_profile.py +224 -0
  579. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/project_settings.py +964 -0
  580. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/provider_window.py +97 -0
  581. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/resume_ticket.py +115 -0
  582. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/scenario_eval.py +856 -0
  583. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/seed_drill.py +549 -0
  584. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/self_audit.py +550 -0
  585. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/session_profile.py +205 -0
  586. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/setup_ui_env.py +229 -0
  587. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/startup_environment.py +859 -0
  588. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/sync_store.py +1421 -0
  589. bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/tool_install_targets.py +18 -0
  590. bugx_cli-0.1.1.data/data/share/bugx-agent/core/schemas/README.md +35 -0
  591. bugx_cli-0.1.1.data/data/share/bugx-agent/core/schemas/agent-graph.schema.json +368 -0
  592. bugx_cli-0.1.1.data/data/share/bugx-agent/core/schemas/attack-graph.schema.json +88 -0
  593. bugx_cli-0.1.1.data/data/share/bugx-agent/core/schemas/evidence-bundle.schema.json +33 -0
  594. bugx_cli-0.1.1.data/data/share/bugx-agent/core/schemas/skill-pack.schema.json +230 -0
  595. bugx_cli-0.1.1.data/data/share/bugx-agent/core/schemas/worker-checkpoint.schema.json +119 -0
  596. bugx_cli-0.1.1.data/data/share/bugx-agent/core/secure_atomic.py +289 -0
  597. bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/README.md +55 -0
  598. bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/c.txt +29 -0
  599. bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/cpp.txt +32 -0
  600. bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/css.txt +70 -0
  601. bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/go.txt +46 -0
  602. bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/java.txt +30 -0
  603. bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/javascript.txt +55 -0
  604. bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/kotlin.txt +28 -0
  605. bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/python.txt +71 -0
  606. bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/rust.txt +53 -0
  607. bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/swift.txt +29 -0
  608. bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/typescript.txt +29 -0
  609. bugx_cli-0.1.1.data/data/share/bugx-agent/core/skills/README.md +53 -0
  610. bugx_cli-0.1.1.data/data/share/bugx-agent/core/skills/__init__.py +189 -0
  611. bugx_cli-0.1.1.data/data/share/bugx-agent/core/skills/bugx_docs_mcp_server.py +418 -0
  612. bugx_cli-0.1.1.data/data/share/bugx-agent/core/skills/bugx_mcp_server.py +1161 -0
  613. bugx_cli-0.1.1.data/data/share/bugx-agent/core/skills/mcp_runtime.py +968 -0
  614. bugx_cli-0.1.1.data/data/share/bugx-agent/core/skills/mcp_session_proof.py +605 -0
  615. bugx_cli-0.1.1.data/data/share/bugx-agent/core/skills/mobile_ui_inspector.py +405 -0
  616. bugx_cli-0.1.1.data/data/share/bugx-agent/core/skills/skill_pack.py +1214 -0
  617. bugx_cli-0.1.1.data/data/share/bugx-agent/core/skills/skill_synthesizer.py +1153 -0
  618. bugx_cli-0.1.1.data/data/share/bugx-agent/core/skills/tools_kb.py +313 -0
  619. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/INTERFACE.md +121 -0
  620. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/README.md +209 -0
  621. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/SPEC.md +25 -0
  622. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/__init__.py +175 -0
  623. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/audit_supervisor.py +1015 -0
  624. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/budget_governor.py +1254 -0
  625. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/checkpoint_handler.py +368 -0
  626. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/checkpoint_pipeline.py +1564 -0
  627. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/checkpoint_sync.py +653 -0
  628. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/claim_events.py +74 -0
  629. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/claim_sync.py +590 -0
  630. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/cli.py +812 -0
  631. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/context_sync.py +55 -0
  632. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/coverage_sync.py +115 -0
  633. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/finding_commit.py +470 -0
  634. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/finding_sync.py +688 -0
  635. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/finding_workflow.py +676 -0
  636. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/finish_policy.py +224 -0
  637. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/finish_sync.py +185 -0
  638. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/graph_sync.py +669 -0
  639. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/lease_manager.py +788 -0
  640. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/lifecycle_blocks.py +129 -0
  641. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/next_round_sync.py +126 -0
  642. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/observability.py +140 -0
  643. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/recovery_sync.py +165 -0
  644. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/rejection_remedies.py +355 -0
  645. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/round_governor.py +306 -0
  646. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/serial_authorization.py +544 -0
  647. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/start_sync.py +87 -0
  648. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/state_store.py +249 -0
  649. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/supervisor_host.py +511 -0
  650. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/supervisor_models.py +1143 -0
  651. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/systemic_failure.py +104 -0
  652. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/task_scheduler.py +1640 -0
  653. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/worker_checkpoint.py +230 -0
  654. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/worker_execution.py +265 -0
  655. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/worker_handoff.py +192 -0
  656. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/worker_lifecycle.py +396 -0
  657. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/worker_runtime.py +1005 -0
  658. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/worker_sync.py +89 -0
  659. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor_types/README.md +36 -0
  660. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor_types/__init__.py +0 -0
  661. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor_types/exceptions.py +52 -0
  662. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor_types/graph_models.py +357 -0
  663. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor_types/path_containment.py +151 -0
  664. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor_types/target_fingerprint.py +310 -0
  665. bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor_types/worker_claim.py +411 -0
  666. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/INTERFACE.md +50 -0
  667. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/README.md +57 -0
  668. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/SPEC.md +26 -0
  669. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/__init__.py +11 -0
  670. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/adapters/__init__.py +27 -0
  671. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/adapters/base.py +87 -0
  672. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/adapters/bugx.py +102 -0
  673. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/adapters/claude.py +222 -0
  674. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/adapters/cline.py +407 -0
  675. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/adapters/codex.py +260 -0
  676. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/adapters/dsh.py +177 -0
  677. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/adapters/opencode.py +218 -0
  678. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/adapters/pi.py +272 -0
  679. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/adapters/registry.py +100 -0
  680. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/adapters/zcode.py +312 -0
  681. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/api_routes_post.py +668 -0
  682. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/dispatcher.py +1376 -0
  683. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/docs_session_service.py +473 -0
  684. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/handler.py +674 -0
  685. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/ide_cloud_service.py +526 -0
  686. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/mcp_inspector.py +1747 -0
  687. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/00-base.css +1060 -0
  688. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/01-monitoring.css +802 -0
  689. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/02-header-actions.css +321 -0
  690. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/03-trigger-popover.css +697 -0
  691. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/04-composer.css +628 -0
  692. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/05-skills-center.css +878 -0
  693. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/06-mcp-center.css +623 -0
  694. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/07-skill-detail.css +265 -0
  695. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/08-files-management.css +167 -0
  696. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/09-files-center.css +386 -0
  697. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/10-icons.css +105 -0
  698. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/11-project-options.css +185 -0
  699. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/12-profile-tab.css +383 -0
  700. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/index-CXAsl8mr.js +333 -0
  701. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/index-DHQUtWtx.css +1 -0
  702. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-cyrillic-400-normal-B8Z6Jvzv.woff +0 -0
  703. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-cyrillic-400-normal-C44pakCn.woff2 +0 -0
  704. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-cyrillic-500-normal-Bb4u56_6.woff +0 -0
  705. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-cyrillic-500-normal-BdVUvljg.woff2 +0 -0
  706. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-cyrillic-ext-400-normal-CWV284fw.woff2 +0 -0
  707. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-cyrillic-ext-400-normal-DLkyKLvH.woff +0 -0
  708. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-cyrillic-ext-500-normal-8-8HP2PF.woff +0 -0
  709. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-cyrillic-ext-500-normal-DaDZE_Na.woff2 +0 -0
  710. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-greek-400-normal-BccYJ-vZ.woff +0 -0
  711. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-greek-400-normal-Cw5-AHNN.woff2 +0 -0
  712. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-greek-500-normal-By8GFJzz.woff2 +0 -0
  713. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-greek-500-normal-z-Q6FFuG.woff +0 -0
  714. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-latin-400-normal-DJ5YJwmz.woff2 +0 -0
  715. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-latin-400-normal-Dn3IlU-Z.woff +0 -0
  716. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-latin-500-normal-CUHe9xxf.woff2 +0 -0
  717. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-latin-500-normal-DVVamBqs.woff +0 -0
  718. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-latin-ext-400-normal-CEpydyUl.woff +0 -0
  719. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-latin-ext-400-normal-Cp7z-ARB.woff2 +0 -0
  720. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-latin-ext-500-normal-BYjRCDVy.woff2 +0 -0
  721. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-latin-ext-500-normal-D-qasQTj.woff +0 -0
  722. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-vietnamese-400-normal-BbG3LG1A.woff2 +0 -0
  723. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-vietnamese-400-normal-DR1UuFon.woff +0 -0
  724. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-vietnamese-500-normal-8N8MYVKB.woff +0 -0
  725. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-vietnamese-500-normal-Bi3OSTTW.woff2 +0 -0
  726. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/design-tokens.css +113 -0
  727. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/favicon.png +0 -0
  728. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/icon-192.png +0 -0
  729. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/index.html +55 -0
  730. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/manifest.webmanifest +19 -0
  731. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/project-settings.js +9602 -0
  732. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/sw.js +8 -0
  733. bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/workspace_service.py +218 -0
  734. bugx_cli-0.1.1.data/data/share/bugx-agent/dsh/agents/bugx.md +27 -0
  735. bugx_cli-0.1.1.data/data/share/bugx-agent/dsh/dsh-patch.yml +18 -0
  736. bugx_cli-0.1.1.data/data/share/bugx-agent/dsh/mcp/cordis.patch.yml +4 -0
  737. bugx_cli-0.1.1.data/data/share/bugx-agent/dsh/mcp/index.js +219 -0
  738. bugx_cli-0.1.1.data/data/share/bugx-agent/dsh/mcp/package.json +28 -0
  739. bugx_cli-0.1.1.data/data/share/bugx-agent/dsh/skills/bugx/SKILL.md +70 -0
  740. bugx_cli-0.1.1.data/data/share/bugx-agent/dsh/skills/bugx-dsh/SKILL.md +229 -0
  741. bugx_cli-0.1.1.data/data/share/bugx-agent/dsh/ui/client.js +87 -0
  742. bugx_cli-0.1.1.data/data/share/bugx-agent/dsh/ui/cordis.patch.yml +4 -0
  743. bugx_cli-0.1.1.data/data/share/bugx-agent/dsh/ui/index.js +7 -0
  744. bugx_cli-0.1.1.data/data/share/bugx-agent/dsh/ui/package.json +27 -0
  745. bugx_cli-0.1.1.data/data/share/bugx-agent/mcp-lock.json +3075 -0
  746. bugx_cli-0.1.1.data/data/share/bugx-agent/opencode.json +129 -0
  747. bugx_cli-0.1.1.data/data/share/bugx-agent/pi/extensions/bugx/README.md +12 -0
  748. bugx_cli-0.1.1.data/data/share/bugx-agent/pi/extensions/bugx/index.ts +299 -0
  749. bugx_cli-0.1.1.data/data/share/bugx-agent/pi/extensions/bugx/manifest.json +11 -0
  750. bugx_cli-0.1.1.data/data/share/bugx-agent/pi/skills/bugx/SKILL.md +69 -0
  751. bugx_cli-0.1.1.data/data/share/bugx-agent/plugins/bugx/skills/bugx-claude/SKILL.md +326 -0
  752. bugx_cli-0.1.1.data/data/share/bugx-agent/plugins/bugx/skills/bugx-opencode/SKILL.md +129 -0
  753. bugx_cli-0.1.1.data/data/share/bugx-agent/plugins/bugx/skills/bugx-zcode/SKILL.md +459 -0
  754. bugx_cli-0.1.1.data/data/share/bugx-agent/workbuddy/connector-meta.json +19 -0
  755. bugx_cli-0.1.1.data/data/share/bugx-agent/workbuddy/icon.png +0 -0
  756. bugx_cli-0.1.1.data/data/share/bugx-agent/workbuddy/skills/bugx/SKILL.md +70 -0
  757. bugx_cli-0.1.1.dist-info/METADATA +335 -0
  758. bugx_cli-0.1.1.dist-info/RECORD +762 -0
  759. bugx_cli-0.1.1.dist-info/WHEEL +5 -0
  760. bugx_cli-0.1.1.dist-info/entry_points.txt +2 -0
  761. bugx_cli-0.1.1.dist-info/licenses/LICENSE +55 -0
  762. bugx_cli-0.1.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1218 @@
1
+ #!/usr/bin/env python3
2
+ """bugx 云端同步客户端 —— 对接后端 /api/v1/agent/*(DOC-008 V2-only)。
3
+
4
+ 覆盖:device-code 登录(发码+轮询)、api-key、设备登记、project 登记、
5
+ global/project knowledge 的 push/pull、sync/status。复用 report_client 的
6
+ 结构化结果(ReportResult)与解析/错误归一。
7
+
8
+ 协议口径(DOC-008 §5,V2-only,无任何 V1 fallback):
9
+ wire envelope 严格 schema_version=2;records 五个数组恒在;
10
+ manifest_hash 为 canonical hash(见 core/cloud_schema.py)。
11
+ POST /api/v1/agent/auth/device {device_id, name} -> data{device_code,user_code,verification_uri,expires_in,interval}
12
+ POST /api/v1/agent/auth/device-token {device_code, device_id} -> 成功 data{token,refresh_token,user};pending/denied 用 code=403+error 字段
13
+ POST /api/v1/agent/auth/refresh {refresh_token} -> data{token,refresh_token,user}
14
+ POST /api/v1/agent/devices {device_id, name}(Bearer)
15
+ POST /api/v1/agent/projects {project_key,name,slug,owner}(Bearer)-> data{project_id,project_key,slug,name,owner}
16
+ POST /api/v1/agent/global/knowledge V2 push envelope(Bearer)
17
+ GET /api/v1/agent/global/knowledge ?schema_version=2&cursor=<opaque>&page_size&device_id(query-only,禁止 body)
18
+ POST /api/v1/agent/global/knowledge/ack post-import cursor ACK(Bearer)
19
+ GET /api/v1/agent/sync/status -> data{...}
20
+ 旧客户端/旧响应一律明确拒绝(缺 schema、schema=1、legacy lessons/incidents 字段)。
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import base64
26
+ import dataclasses
27
+ import datetime as _datetime
28
+ import hashlib
29
+ import json
30
+ import os
31
+ import re
32
+ import socket
33
+ import ssl
34
+ import subprocess
35
+ import sys
36
+ import time
37
+ import urllib.error
38
+ import urllib.parse
39
+ import urllib.request
40
+ import uuid
41
+ from pathlib import Path
42
+ from typing import Any, Callable, Mapping
43
+
44
+ from core.report_engine.report_client import (
45
+ ReportResult,
46
+ atomic_write_nofollow,
47
+ load_installation_secret, # 设备 ID 文件丢失时的同机稳定派生源
48
+ message_from_response,
49
+ parse_response_json,
50
+ )
51
+ from core.infra.client_metadata import client_headers, client_marker, client_user_agent, client_version, tls_context
52
+ from core.secure_atomic import AtomicWriteError, reject_symlink_components
53
+ from core.cloud_sync.cloud_schema import (
54
+ MAX_CURSOR_LENGTH,
55
+ SCHEMA_VERSION,
56
+ SchemaError,
57
+ SyncError,
58
+ build_push_envelope,
59
+ parse_sync_error,
60
+ validate_pull_response,
61
+ )
62
+
63
+ # 发布包的默认正式云端端点;可由 BUGX_CLOUD_API_BASE 或全局 cloud-config.json 覆盖。
64
+ DEFAULT_BASE = "https://bugx.dev"
65
+ DEFAULT_BASE_CANDIDATES: tuple[str, ...] = ("https://bugx.com.cn", "https://bugx.dev")
66
+ CLOUD_ROUTE_CACHE_PATH = os.environ.get(
67
+ "BUGX_CLOUD_ROUTE_CACHE", str(Path.home() / ".bugx" / "cloud-route-cache.json")
68
+ )
69
+ DEFAULT_ROUTE_TTL = float(os.environ.get("BUGX_CLOUD_ROUTE_TTL", "86400")) # 24 小时
70
+ DEFAULT_PROBE_TIMEOUT = float(os.environ.get("BUGX_PROBE_TIMEOUT", "0.8"))
71
+ _MEMOIZED_BASE_URL: str | None = None
72
+ CRED_PATH = os.environ.get("BUGX_CLOUD_CREDENTIALS", str(Path.home() / ".bugx" / "cloud-credentials.json"))
73
+ DEVICE_ID_PATH = os.environ.get("BUGX_CLOUD_DEVICE_ID", str(Path.home() / ".bugx" / "cloud-device-id"))
74
+ CLOUD_CONFIG_PATH = os.environ.get(
75
+ "BUGX_CLOUD_CONFIG", str(Path.home() / ".bugx" / "cloud-config.json")
76
+ )
77
+ DEFAULT_TIMEOUT = float(os.environ.get("BUGX_CLOUD_TIMEOUT", "8"))
78
+ DEFAULT_RETRIES = int(os.environ.get("BUGX_CLOUD_RETRIES", "1"))
79
+ DEFAULT_PAGE = int(os.environ.get("BUGX_CLOUD_PAGE_SIZE", "100"))
80
+ MAX_PULL_PAGES = int(os.environ.get("BUGX_CLOUD_MAX_PULL_PAGES", "1000"))
81
+ MAX_AGENT_PACKAGE_BYTES = 128 * 1024 * 1024
82
+ AGENT_PACKAGE_READ_CHUNK = 1024 * 1024
83
+
84
+
85
+ from core.cloud_sync.network_transport import (
86
+ CurlResponse,
87
+ NoRedirectHandler,
88
+ build_no_redirect_open,
89
+ build_redirect_opener,
90
+ diagnose_network_error,
91
+ is_private_target_host,
92
+ parse_curl_response_headers,
93
+ tls_context,
94
+ trusted_curl_request,
95
+ )
96
+
97
+ # Compatibility aliases
98
+ _is_private_target_host = is_private_target_host
99
+ _NoRedirectHandler = NoRedirectHandler
100
+ _tls_context = tls_context
101
+ _build_no_redirect_open = build_no_redirect_open
102
+ _build_redirect_opener = build_redirect_opener
103
+ _CurlResponse = CurlResponse
104
+ _parse_curl_response_headers = parse_curl_response_headers
105
+ _trusted_curl_request = trusted_curl_request
106
+ from core.cloud_sync.sensitive_filter import (
107
+ SENSITIVE_POLICIES,
108
+ SYNC_DETAIL_MODES,
109
+ SYNC_POLICY_VOCABS,
110
+ SYNC_SCOPE_DEFAULTS,
111
+ SensitiveSyncError,
112
+ emit_policy_audit,
113
+ iter_record_strings,
114
+ prepare_records_for_sync,
115
+ redact_records_for_sync,
116
+ redact_sensitive_text,
117
+ scan_kind,
118
+ scan_sensitive_text,
119
+ scan_wire_value,
120
+ validate_knowledge_for_sync,
121
+ validate_pull_envelope,
122
+ validate_records_for_sync,
123
+ validate_secret_shapes,
124
+ wire_project_id,
125
+ )
126
+ from core.cloud_sync.endpoint_router import (
127
+ clear_cloud_base_url,
128
+ clear_route_cache,
129
+ cloud_base_url_status,
130
+ cloud_config_path,
131
+ cloud_route_cache_path,
132
+ configured_base_url,
133
+ load_cloud_config,
134
+ load_route_cache,
135
+ probe_candidate_latency,
136
+ read_cloud_config_raw,
137
+ save_route_cache,
138
+ select_lowest_latency_endpoint,
139
+ set_cloud_base_url,
140
+ update_cloud_config,
141
+ validate_base_url,
142
+ )
143
+ from core.cloud_sync.device_identity import (
144
+ CloudCredentials,
145
+ LESSON_FEEDBACK_MAX_ITEMS,
146
+ LESSON_FEEDBACK_OUTCOMES,
147
+ get_device_id,
148
+ get_device_label,
149
+ incident_to_wire,
150
+ lesson_to_wire,
151
+ token_expires_in,
152
+ )
153
+
154
+ # Compatibility aliases
155
+ _scan_wire_value = scan_wire_value
156
+ _scan_kind = scan_kind
157
+ _iter_record_strings = iter_record_strings
158
+ _validate_secret_shapes = validate_secret_shapes
159
+ _emit_policy_audit = emit_policy_audit
160
+ _wire_project_id = wire_project_id
161
+ _validate_base_url = validate_base_url
162
+ _cloud_config_path = cloud_config_path
163
+ _cloud_route_cache_path = cloud_route_cache_path
164
+ _read_cloud_config_raw = read_cloud_config_raw
165
+ _token_expires_in = token_expires_in
166
+
167
+ AGENT_API_PREFIX = "/api/v1/agent"
168
+ DEVICE_PATH = f"{AGENT_API_PREFIX}/auth/device"
169
+ DEVICE_TOKEN_PATH = f"{AGENT_API_PREFIX}/auth/device-token"
170
+ AUTH_REFRESH_PATH = f"{AGENT_API_PREFIX}/auth/refresh"
171
+ ROUTING_PATH = f"{AGENT_API_PREFIX}/routing"
172
+ DEVICES_PATH = f"{AGENT_API_PREFIX}/devices"
173
+ PROJECTS_PATH = f"{AGENT_API_PREFIX}/projects"
174
+ SYNC_STATUS_PATH = f"{AGENT_API_PREFIX}/sync/status"
175
+ VERSION_CHECK_PATH = f"{AGENT_API_PREFIX}/version"
176
+ DOWNLOAD_PATH = f"{AGENT_API_PREFIX}/download"
177
+ KNOWLEDGE_PREFETCH_PATH = f"{AGENT_API_PREFIX}/knowledge/prefetch"
178
+ VULNERABILITY_QUERY_PATH = f"{AGENT_API_PREFIX}/vulnerabilities/query"
179
+ PATCH_VERIFICATION_PATH = f"{AGENT_API_PREFIX}/patch-verifications"
180
+ PROJECT_PROFILE_MAX_BYTES = 256 * 1024
181
+ VULNERABILITY_QUERY_MAX_COMPONENTS = 100
182
+
183
+
184
+ class CloudClient:
185
+ """带认证的云端客户端(device-code / api-key),网络封装单一入口。"""
186
+
187
+ def __init__(
188
+ self,
189
+ base_url: str | None = None,
190
+ credentials: CloudCredentials | None = None,
191
+ cred_path: str | Path | None = None,
192
+ *,
193
+ timeout: float | None = None,
194
+ retries: int | None = None,
195
+ urlopen: Callable[..., Any] | None = None,
196
+ ) -> None:
197
+ self.cred_path = cred_path or CRED_PATH
198
+ self.cred = credentials if credentials is not None else CloudCredentials.load(self.cred_path)
199
+ if base_url:
200
+ # An explicit endpoint is authoritative. Do not inspect user sync
201
+ # configuration or device routing before honoring it.
202
+ self._explicit_base = True
203
+ self._server_route_enabled = False
204
+ self.base = _validate_base_url(base_url)
205
+ else:
206
+ configured = cloud_base_url_status()
207
+ self._explicit_base = configured["source"] != "default"
208
+ self._server_route_enabled = not self._explicit_base and client_marker() not in {"dev", "uat"}
209
+ route_base = (
210
+ self.cred.cloud_api_base
211
+ if self._server_route_enabled and self._route_matches_client() else None
212
+ )
213
+ self.base = route_base or configured_base_url()
214
+ self.timeout = timeout if timeout is not None else DEFAULT_TIMEOUT
215
+ self.retries = retries if retries is not None else DEFAULT_RETRIES
216
+ self.max_pull_pages = MAX_PULL_PAGES
217
+ self._custom_urlopen = urlopen is not None
218
+ self._urlopen = urlopen or _build_no_redirect_open(self.base)
219
+
220
+ @staticmethod
221
+ def _expected_environment() -> str:
222
+ return {"dev": "dev", "uat": "uat"}.get(client_marker(), "prod")
223
+
224
+ def _route_matches_client(self) -> bool:
225
+ return bool(self.cred.cloud_api_base and self.cred.cloud_region
226
+ and self.cred.cloud_route_environment == self._expected_environment())
227
+
228
+ def _route_expired(self) -> bool:
229
+ if self._server_route_enabled and self.cred.is_authenticated() and not self._route_matches_client():
230
+ return True
231
+ value = self.cred.cloud_route_expires_at
232
+ if not value:
233
+ return False
234
+ try:
235
+ expires = _datetime.datetime.fromisoformat(value.replace("Z", "+00:00"))
236
+ except (TypeError, ValueError):
237
+ return True
238
+ if expires.tzinfo is None:
239
+ expires = expires.replace(tzinfo=_datetime.timezone.utc)
240
+ return expires.timestamp() <= time.time()
241
+
242
+ def _store_route(self, route: object) -> bool:
243
+ if not isinstance(route, dict):
244
+ return False
245
+ region = str(route.get("region") or "").strip().lower()
246
+ environment = str(route.get("environment") or "").strip().lower()
247
+ api_base = str(route.get("api_base") or "").strip()
248
+ if region not in {"cn", "global"} or environment != self._expected_environment() or not api_base:
249
+ return False
250
+ try:
251
+ normalized = _validate_base_url(api_base)
252
+ except ValueError:
253
+ return False
254
+ self.cred.cloud_region = region
255
+ self.cred.cloud_api_base = normalized
256
+ self.cred.cloud_route_environment = environment
257
+ self.cred.cloud_route_expires_at = str(route.get("expires_at") or "")
258
+ self.cred.cloud_route_version = str(route.get("config_version") or "")
259
+ if self._server_route_enabled:
260
+ self.base = normalized
261
+ if not self._custom_urlopen:
262
+ self._urlopen = _build_no_redirect_open(self.base)
263
+ return True
264
+
265
+ def _refresh_route(self) -> bool:
266
+ if not self._server_route_enabled or not self.cred.is_authenticated():
267
+ return False
268
+ result = self._request("GET", ROUTING_PATH, auth=True, retry_auth=False)
269
+ if not result.ok:
270
+ return False
271
+ stored = self._store_route(self._data(result))
272
+ if stored:
273
+ self.cred.save(self.cred_path)
274
+ return stored
275
+
276
+ # ---- 内部请求 ----
277
+ def _auth_header(self) -> str | None:
278
+ key = self.cred.api_key or self.cred.token
279
+ return f"Bearer {key}" if key else None
280
+
281
+ @staticmethod
282
+ def _unauthenticated(method: str, path: str) -> ReportResult:
283
+ """Fail closed before egress when no account credential exists."""
284
+ message = (
285
+ f"unauthenticated: {method} {path} 必须携带账号 Bearer token;"
286
+ "project_key 只是幂等标识,不是鉴权凭据"
287
+ )
288
+ return ReportResult(
289
+ ok=False, status=401,
290
+ data={"code": "SYNC_UNAUTHENTICATED", "message": message},
291
+ error=message,
292
+ )
293
+
294
+ def _mark_auth_expired(self) -> None:
295
+ """Keep a server-confirmed 401 visible to the next CLI process."""
296
+ self.cred.auth_state_override = "expired"
297
+ try:
298
+ self.cred.save(self.cred_path)
299
+ except (OSError, ValueError):
300
+ # An unwritable cache must not hide the authoritative 401 result.
301
+ pass
302
+
303
+ def _open_request(self, req: urllib.request.Request) -> Any:
304
+ try:
305
+ return self._urlopen(req, timeout=self.timeout)
306
+ except (urllib.error.URLError, TimeoutError, ConnectionError, OSError) as exc:
307
+ if self._custom_urlopen or not diagnose_network_error(
308
+ exc, req.full_url
309
+ )["is_local_network_blocked"]:
310
+ raise
311
+ try:
312
+ return _trusted_curl_request(req, self.timeout)
313
+ except (urllib.error.URLError, TimeoutError, ConnectionError, OSError,
314
+ ValueError) as fallback_error:
315
+ raise fallback_error from exc
316
+
317
+ def _request(self, method: str, path: str, payload: dict | None = None,
318
+ *, auth: bool = True, retry_auth: bool = True,
319
+ params: dict | None = None,
320
+ extra_headers: dict | None = None) -> ReportResult:
321
+ if auth and path not in {ROUTING_PATH, AUTH_REFRESH_PATH} and self._route_expired():
322
+ self._refresh_route()
323
+ url = self.base + path
324
+ if params:
325
+ url += "?" + urllib.parse.urlencode(params)
326
+ headers = {
327
+ "Accept": "application/json",
328
+ **client_headers(),
329
+ }
330
+ if extra_headers:
331
+ headers.update(extra_headers)
332
+ if auth:
333
+ # 客户端到期前 2 天自动静默续期(API Key 为独立体系,不触发 refresh)
334
+ if retry_auth and not self.cred.api_key and self.cred.token and self.cred.refresh_token:
335
+ expires_in = _token_expires_in(self.cred.token)
336
+ if expires_in is not None and expires_in <= 2 * 86400:
337
+ self._refresh()
338
+ header = self._auth_header()
339
+ if header is None:
340
+ # F-RSI-20261115-145:账号 Bearer token 是云端操作唯一的鉴权凭据,
341
+ # project_key 只是同账号内的幂等标识。缺失账号凭据时不得发出任何
342
+ # 请求(此前会静默省略 Authorization,仅凭 body 里的 project_key 出网)。
343
+ return self._unauthenticated(method, path)
344
+ headers["Authorization"] = header
345
+ body = None
346
+ if payload is not None:
347
+ # V2-only:pull 一律 query 参数(DOC-008 §5.2),GET 禁止携带 body。
348
+ headers["Content-Type"] = "application/json"
349
+ body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
350
+ req = urllib.request.Request(url, data=body, headers=headers, method=method)
351
+ for attempt in range(self.retries + 1):
352
+ try:
353
+ resp = self._open_request(req)
354
+ try:
355
+ status = getattr(resp, "status", 200)
356
+ raw = resp.read() if hasattr(resp, "read") else b""
357
+ finally:
358
+ resp.close()
359
+ data = parse_response_json(raw)
360
+ # V2 errors use their real HTTP status; older handlers may also
361
+ # return a 200 envelope with code>=400, so handle both forms.
362
+ code_marker = data.get("code") if isinstance(data, dict) else None
363
+ biz_401 = (status == 401) or (code_marker == 401)
364
+ if (biz_401 and auth and retry_auth and self.cred.refresh_token
365
+ and self._refresh()):
366
+ return self._request(method, path, payload, auth=auth, retry_auth=False,
367
+ params=params, extra_headers=extra_headers)
368
+ if biz_401 and auth:
369
+ self._mark_auth_expired()
370
+ retryable = (
371
+ status >= 500
372
+ or (isinstance(code_marker, int) and code_marker in (429, 503))
373
+ )
374
+ if retryable and attempt < self.retries:
375
+ time.sleep(self._retry_delay(data, attempt))
376
+ continue
377
+ biz_bad = isinstance(code_marker, int) and code_marker >= 400
378
+ return ReportResult(ok=200 <= status < 300 and not biz_bad,
379
+ status=status, data=data, error=None,
380
+ )
381
+ except urllib.error.HTTPError as exc:
382
+ # 401 → 用 refresh_token 续期后重试一次(覆盖真实 HTTP 401)
383
+ if (exc.code == 401 and auth and retry_auth and self.cred.refresh_token
384
+ and self._refresh()):
385
+ try:
386
+ exc.close()
387
+ except Exception: # noqa: BLE001
388
+ pass
389
+ return self._request(method, path, payload, auth=auth, retry_auth=False,
390
+ params=params, extra_headers=extra_headers)
391
+ if exc.code == 401 and auth:
392
+ self._mark_auth_expired()
393
+ if exc.code >= 500 and attempt < self.retries:
394
+ try:
395
+ exc.close()
396
+ except Exception: # noqa: BLE001
397
+ pass
398
+ time.sleep(0.5 * (attempt + 1))
399
+ continue
400
+ raw = exc.read()
401
+ try:
402
+ exc.close()
403
+ except Exception: # noqa: BLE001
404
+ pass
405
+ return ReportResult(ok=False, status=exc.code, data=parse_response_json(raw), error=message_from_response(raw, exc))
406
+ except (urllib.error.URLError, TimeoutError, ConnectionError, OSError) as exc:
407
+ if attempt < self.retries:
408
+ time.sleep(0.5 * (attempt + 1))
409
+ continue
410
+ diag = diagnose_network_error(exc, url)
411
+ if diag["is_local_network_blocked"]:
412
+ return ReportResult(
413
+ ok=False, status=None,
414
+ data={"code": diag["code"], "message": diag["message"]},
415
+ error=diag["message"],
416
+ )
417
+ message = diag.get("message", str(exc))
418
+ return ReportResult(
419
+ ok=False, status=None,
420
+ data={"code": "SYNC_NETWORK_UNAVAILABLE", "message": message},
421
+ error=message,
422
+ )
423
+ except ValueError as exc:
424
+ return ReportResult(
425
+ ok=False, status=None,
426
+ data={"code": "SYNC_INVALID_RESPONSE", "message": str(exc)},
427
+ error=str(exc),
428
+ )
429
+ return ReportResult(ok=False, status=None, data=None, error="unknown")
430
+
431
+ def _data(self, res: ReportResult) -> dict:
432
+ return (res.data or {}).get("data") if isinstance(res.data, dict) and isinstance(res.data.get("data"), dict) else (res.data or {})
433
+
434
+ def submit_patch_package(self, package: bytes, filename: str, *,
435
+ source_commit: str = "") -> ReportResult:
436
+ """Submit an opaque patch ZIP; the server owns static verification."""
437
+ if not isinstance(package, (bytes, bytearray)) or not package:
438
+ raise ValueError("补丁包不能为空")
439
+ if not filename or "/" in filename or "\\" in filename:
440
+ raise ValueError("补丁包文件名无效")
441
+ boundary = "----bugx-patch-" + uuid.uuid4().hex
442
+ chunks = [
443
+ f"--{boundary}\r\nContent-Disposition: form-data; name=\"package\"; filename=\"{filename}\"\r\nContent-Type: application/zip\r\n\r\n".encode(),
444
+ bytes(package), b"\r\n",
445
+ f"--{boundary}\r\nContent-Disposition: form-data; name=\"source_commit\"\r\n\r\n{source_commit.strip()}\r\n".encode(),
446
+ f"--{boundary}--\r\n".encode(),
447
+ ]
448
+ return self._request_raw(
449
+ "POST", PATCH_VERIFICATION_PATH, b"".join(chunks),
450
+ content_type=f"multipart/form-data; boundary={boundary}",
451
+ )
452
+
453
+ def get_patch_verification(self, verification_id: str) -> ReportResult:
454
+ value = str(verification_id or "").strip()
455
+ if not re.fullmatch(r"[1-9][0-9]*", value):
456
+ raise ValueError("verification_id 必须是正整数")
457
+ return self._request("GET", f"{PATCH_VERIFICATION_PATH}/{value}")
458
+
459
+ def _request_raw(self, method: str, path: str, body: bytes,
460
+ *, content_type: str) -> ReportResult:
461
+ url = self.base + path
462
+ headers = {"Accept": "application/json", **client_headers(),
463
+ "Content-Type": content_type, "Content-Length": str(len(body))}
464
+ auth = self._auth_header()
465
+ if auth is None:
466
+ # 同 _request:补丁包上传同样必须带账号凭据,缺失即零 egress 拒绝。
467
+ return self._unauthenticated(method, path)
468
+ headers["Authorization"] = auth
469
+ req = urllib.request.Request(url, data=body, headers=headers, method=method)
470
+ try:
471
+ resp = self._open_request(req)
472
+ try:
473
+ status = getattr(resp, "status", 200)
474
+ raw = resp.read() if hasattr(resp, "read") else b""
475
+ finally:
476
+ resp.close()
477
+ data = parse_response_json(raw)
478
+ code = data.get("code") if isinstance(data, dict) else None
479
+ return ReportResult(ok=200 <= status < 300 and not (isinstance(code, int) and code >= 400),
480
+ status=status, data=data, error=None)
481
+ except urllib.error.HTTPError as exc:
482
+ raw = exc.read()
483
+ try:
484
+ exc.close()
485
+ except Exception: # noqa: BLE001
486
+ pass
487
+ return ReportResult(ok=False, status=exc.code, data=parse_response_json(raw), error=message_from_response(raw, exc))
488
+ except (urllib.error.URLError, TimeoutError, ConnectionError, OSError) as exc:
489
+ diag = diagnose_network_error(exc, url)
490
+ if diag["is_local_network_blocked"]:
491
+ return ReportResult(
492
+ ok=False, status=None,
493
+ data={"code": diag["code"], "message": diag["message"]},
494
+ error=diag["message"],
495
+ )
496
+ message = diag.get("message", str(exc))
497
+ return ReportResult(ok=False, status=None,
498
+ data={"code": "PATCH_NETWORK_UNAVAILABLE", "message": message},
499
+ error=message)
500
+ except ValueError as exc:
501
+ return ReportResult(ok=False, status=None,
502
+ data={"code": "PATCH_NETWORK_UNAVAILABLE", "message": str(exc)},
503
+ error=str(exc))
504
+
505
+ @staticmethod
506
+ def _retry_delay(data: dict | None, attempt: int) -> float:
507
+ err = parse_sync_error(None, data)
508
+ if err.retry_after_seconds is not None:
509
+ return float(min(err.retry_after_seconds, 30))
510
+ return 0.5 * (attempt + 1)
511
+
512
+ def sync_error(self, res: ReportResult) -> SyncError:
513
+ """把失败响应解析为结构化同步错误(DOC-008 §5.3)。"""
514
+ status = res.status
515
+ body = res.data if isinstance(res.data, dict) else {}
516
+ wrapped = body.get("code") if isinstance(body, dict) else None
517
+ if isinstance(wrapped, int) and not isinstance(wrapped, bool):
518
+ status = status if (status is not None and status >= 400) else wrapped
519
+ return parse_sync_error(status, body)
520
+
521
+ # ---- 认证 ----
522
+ def start_device(self, name: str = "", device_id: str | None = None) -> dict:
523
+ """发起 device-code,返回 {device_code, user_code, verification_uri, expires_in, interval}。"""
524
+ did = device_id or get_device_id()
525
+ res = self._request("POST", DEVICE_PATH, {"device_id": did, "name": name}, auth=False, retry_auth=False)
526
+ if not res.ok:
527
+ raise RuntimeError(f"发起设备授权失败: code={res.status} {res.error}")
528
+ return self._data(res)
529
+
530
+ def poll_device_token(self, device_code: str, device_id: str | None = None,
531
+ max_tries: int = 120, interval: int = 5) -> ReportResult:
532
+ """轮询 device-token:pending/无 token 继续,denied/expired 报错,拿到 token 存凭据。"""
533
+ code_to_msg = {
534
+ "access_denied": "用户已拒绝授权",
535
+ "expired_token": "授权码已过期,请重新登录",
536
+ "expired": "授权码已过期,请重新登录",
537
+ }
538
+ did = device_id or get_device_id()
539
+ backoff = 0.0
540
+ for _ in range(max_tries):
541
+ res = self._request("POST", DEVICE_TOKEN_PATH,
542
+ {"device_code": device_code, "device_id": did},
543
+ auth=False, retry_auth=False)
544
+ data = res.data if isinstance(res.data, dict) else {}
545
+ err = str(data.get("error", "") or "")
546
+ inner = data.get("data") if isinstance(data.get("data"), dict) else {}
547
+ token = inner.get("token") or inner.get("access_token")
548
+ if err in {"access_denied", "expired_token", "expired"}:
549
+ return ReportResult(ok=False, status=getattr(res, "status", None),
550
+ data=res.data, error=code_to_msg.get(err, err))
551
+ if token:
552
+ self.cred = CloudCredentials(
553
+ token=token, refresh_token=inner.get("refresh_token"),
554
+ api_key=inner.get("api_key"), user=inner.get("user"),
555
+ )
556
+ self._store_route(inner.get("route"))
557
+ self.cred.save(self.cred_path)
558
+ return ReportResult(ok=True, status=getattr(res, "status", 200),
559
+ data=res.data, error=None)
560
+ # 限流(联调 I-2):429 不消耗等待授权的轮次(device_code 有效期
561
+ # 远大于 max_tries*interval),按加压退避后重试同一轮询,避免
562
+ # 登录因服务端 RateLimitStrict 凭空失败。
563
+ if getattr(res, "status", None) == 429 or data.get("code") == 429:
564
+ backoff = min(backoff + interval, 30.0)
565
+ time.sleep(backoff)
566
+ continue
567
+ backoff = 0.0
568
+ # 仍在等待授权 -> 继续轮询
569
+ time.sleep(interval)
570
+ return ReportResult(ok=False, status=None, data=None, error="授权超时")
571
+
572
+ def login(self, name: str = "", device_id: str | None = None) -> ReportResult:
573
+ """完整 device-code 登录:发码→打印 URL→尝试自动打开浏览器→轮询→存凭据。"""
574
+ flow = self.start_device(name=name, device_id=device_id)
575
+ uri = flow.get("verification_uri") or ""
576
+ # 授权页必须是普通 http(s) 地址:被劫持/被替换的服务端可能借
577
+ # file:、自定义 scheme 等把宿主浏览器导向本地文件或钓鱼协议,
578
+ # 这里 fail-closed,绝不打印和打开非 http(s) 链接。
579
+ if uri and not str(uri).lower().startswith(("http://", "https://")):
580
+ return ReportResult(ok=False, status=None, data=None,
581
+ error=f"服务端返回的 verification_uri 不是 http(s) 地址: {uri!r}")
582
+ # flush:stdout 可能是管道(自动化/CI),不刷会卡在缓冲里抓不到 user_code
583
+ print(f"请打开授权页完成登录:{uri}", flush=True)
584
+ print(f"(用户码 {flow.get('user_code')};有效期 {flow.get('expires_in')}s)", flush=True)
585
+ # 后台 device-code 需人工在浏览器确认;有桌面环境时自动拉起,失败仅回退到手动打开
586
+ if uri:
587
+ opened = False
588
+ try:
589
+ import webbrowser
590
+ opened = bool(webbrowser.open(uri, new=2))
591
+ except Exception:
592
+ opened = False
593
+ # macOS 的 TUI/子进程有时没有可用的 webbrowser 注册器;
594
+ # 使用系统 opener 再尝试一次,但仍不把打开失败当成授权成功。
595
+ if not opened and sys.platform == "darwin":
596
+ try:
597
+ opened = subprocess.run(
598
+ ["open", uri], check=False,
599
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
600
+ timeout=5,
601
+ ).returncode == 0
602
+ except (OSError, subprocess.SubprocessError):
603
+ opened = False
604
+ if opened:
605
+ print(f"已打开浏览器授权页:{uri}", flush=True)
606
+ else:
607
+ print(f"自动打开浏览器失败,请手动打开授权页:{uri}", flush=True)
608
+ # 轮询间隔来自服务端,属不可信输入:限幅到 [1,30] 秒,拒绝 0/负值
609
+ # 造成的忙轮询,也拒绝异常大值把登录挂死。非法类型回退默认 5s。
610
+ try:
611
+ interval = int(flow.get("interval", 5))
612
+ except (TypeError, ValueError):
613
+ interval = 5
614
+ interval = min(30, max(1, interval))
615
+ return self.poll_device_token(flow.get("device_code", ""),
616
+ device_id=device_id, interval=interval)
617
+
618
+ def set_api_key(self, api_key: str) -> None:
619
+ self.cred.api_key = api_key
620
+ self.cred.auth_state_override = None
621
+ self.cred.save(self.cred_path)
622
+
623
+ def logout(self) -> None:
624
+ self.cred.clear(self.cred_path)
625
+ self.cred = CloudCredentials()
626
+
627
+ def _refresh(self) -> bool:
628
+ res = self._request("POST", AUTH_REFRESH_PATH,
629
+ {"refresh_token": self.cred.refresh_token}, auth=False, retry_auth=False)
630
+ data = self._data(res)
631
+ new_tok = data.get("token") or data.get("access_token")
632
+ if res.ok and new_tok:
633
+ self.cred.token = new_tok
634
+ self.cred.refresh_token = data.get("refresh_token", self.cred.refresh_token)
635
+ self._store_route(data.get("route"))
636
+ self.cred.auth_state_override = None
637
+ self.cred.save(self.cred_path)
638
+ return True
639
+ return False
640
+
641
+ def verify_auth(self) -> ReportResult:
642
+ """用只读同步状态接口验证当前凭据是否被服务端接受。
643
+
644
+ ``CloudCredentials.auth_state`` 只能判断本地 JWT 过期或凭据是否
645
+ 存在;opaque token 必须由服务端确认。该方法不创建项目、不写知识,
646
+ 401 会通过统一请求路径触发 refresh,并在最终失败时标记 expired。
647
+ """
648
+ if not self.cred.is_authenticated():
649
+ return ReportResult(ok=False, status=None, data=None, error="云端凭据未配置")
650
+ result = self._request("GET", SYNC_STATUS_PATH)
651
+ if result.ok:
652
+ # 成功核验清除曾经持久化的拒绝;不持久化 valid,避免 opaque
653
+ # token 在未来过期后仍被永久视为有效。
654
+ if self.cred.auth_state_override == "expired":
655
+ self.cred.auth_state_override = None
656
+ try:
657
+ self.cred.save(self.cred_path)
658
+ except (OSError, ValueError):
659
+ pass
660
+ elif result.status == 401:
661
+ self._mark_auth_expired()
662
+ return result
663
+
664
+ # ---- 设备 / 项目 ----
665
+ def register_device(self, name: str = "", device_id: str | None = None) -> ReportResult:
666
+ return self._request("POST", DEVICES_PATH,
667
+ {"device_id": device_id or get_device_id(), "name": name})
668
+
669
+ def register_project(self, slug: str, name: str, owner: str = "", *,
670
+ project_key: str | None = None) -> ReportResult:
671
+ """Resolve/create a project using its stable repository identity."""
672
+ if not isinstance(project_key, str) or not project_key.strip():
673
+ raise ValueError("project_key 必须提供,禁止使用路径或目录名推导项目身份")
674
+ return self._request(
675
+ "POST", PROJECTS_PATH,
676
+ {"project_key": project_key.strip(), "slug": slug, "name": name, "owner": owner},
677
+ )
678
+
679
+ def list_projects(self) -> ReportResult:
680
+ return self._request("GET", PROJECTS_PATH)
681
+
682
+ def project_id(self, res: ReportResult) -> str:
683
+ """从 register_project 的稳定 DTO 响应提取正整数 project_id。"""
684
+ d = self._data(res)
685
+ value = d.get("project_id")
686
+ if isinstance(value, bool):
687
+ return ""
688
+ if isinstance(value, int) and value > 0:
689
+ return str(value)
690
+ if isinstance(value, str) and re.fullmatch(r"[1-9][0-9]*", value):
691
+ return value
692
+ return ""
693
+
694
+ def project_key(self, res: ReportResult) -> str:
695
+ """从项目登记 DTO 提取服务端回显的稳定身份。"""
696
+ value = self._data(res).get("project_key")
697
+ return value.strip() if isinstance(value, str) else ""
698
+
699
+ # ---- 项目画像元数据(与知识 V2 通道分离)----
700
+ def get_project_profile(self, project_id: str) -> ReportResult:
701
+ """读取当前账号项目的 ProjectProfile 元数据。"""
702
+ return self._request("GET", self._profile_path(project_id))
703
+
704
+ def put_project_profile(self, project_id: str, profile: dict[str, Any], *,
705
+ base_revision: int = 0,
706
+ operation_id: str | None = None) -> ReportResult:
707
+ """幂等写入项目画像;服务端以 revision 做轻量乐观并发控制。"""
708
+ if not isinstance(profile, dict):
709
+ raise ValueError("project_profile 必须是对象")
710
+ if profile.get("schema_version") != 2:
711
+ raise ValueError("project_profile.schema_version 必须为 2")
712
+ if not isinstance(base_revision, int) or isinstance(base_revision, bool) or base_revision < 0:
713
+ raise ValueError("base_revision 必须是非负整数")
714
+ sanitized_profile = dict(profile)
715
+ sanitized_profile.pop("observed_at", None)
716
+ body = {
717
+ "schema_version": 2,
718
+ "profile_revision": int(sanitized_profile.get("revision", 0) or 0),
719
+ "base_revision": base_revision,
720
+ "operation_id": operation_id or f"profile-{uuid.uuid4().hex}",
721
+ "profile": sanitized_profile,
722
+ }
723
+ raw_size = len(json.dumps(body, ensure_ascii=False, sort_keys=True).encode("utf-8"))
724
+ if raw_size > PROJECT_PROFILE_MAX_BYTES:
725
+ raise ValueError("project_profile 超过 256 KiB 限制")
726
+ hits: set[str] = set()
727
+ _scan_wire_value(profile, path="project_profile", hits=hits)
728
+ if hits:
729
+ raise SensitiveSyncError(
730
+ "project_profile 命中敏感信息规则(" + ", ".join(sorted(hits)) + "),拒绝上传"
731
+ )
732
+ return self._request("PUT", self._profile_path(project_id), body)
733
+
734
+ def query_vulnerabilities(self, components: list[dict[str, Any]]) -> ReportResult:
735
+ """Warm/read the server's public version-specific advisory cache.
736
+
737
+ The response is advisory-only: callers keep local SCA candidates as
738
+ the authoritative offline path and must not mutate ProjectProfile from
739
+ this endpoint.
740
+ """
741
+ if not isinstance(components, list) or len(components) > VULNERABILITY_QUERY_MAX_COMPONENTS:
742
+ raise ValueError("漏洞查询组件数不能超过 100")
743
+ normalized: list[dict[str, str]] = []
744
+ seen: set[tuple[str, str, str]] = set()
745
+ for item in components:
746
+ if not isinstance(item, dict):
747
+ raise ValueError("漏洞查询组件必须是对象")
748
+ ecosystem = str(item.get("ecosystem") or "").strip().lower()
749
+ name = str(item.get("name") or item.get("package") or "").strip()
750
+ version = str(
751
+ item.get("resolved_version")
752
+ or item.get("declared_version")
753
+ or item.get("observed_version")
754
+ or ""
755
+ ).strip()
756
+ if not ecosystem or not name or not version:
757
+ continue
758
+ key = (ecosystem, name, version)
759
+ if key in seen:
760
+ continue
761
+ seen.add(key)
762
+ normalized.append({"ecosystem": ecosystem, "name": name, "version": version})
763
+ return self._request(
764
+ "POST", VULNERABILITY_QUERY_PATH,
765
+ {"schema_version": 1, "components": normalized},
766
+ )
767
+
768
+ # ---- 知识同步(V2-only)----
769
+ def push_knowledge(self, scope: str, project_id: str = "",
770
+ lessons: list[dict] | None = None,
771
+ incidents: list[dict] | None = None, *,
772
+ tool_experience: list[dict] | None = None,
773
+ consumption_events: list[dict] | None = None,
774
+ tombstones: list[dict] | None = None,
775
+ snapshot_id: str | None = None,
776
+ operation_id: str | None = None,
777
+ base_version: int | None = None,
778
+ device_id: str | None = None,
779
+ sensitive_policy: str = "redact") -> ReportResult:
780
+ """V2 push:完整 envelope(records 四数组恒在,无 legacy 顶层字段)。
781
+
782
+ DOC-211:sensitive_policy=allow 跳过出网敏感扫描(策略应用已在构建侧
783
+ prepare_records_for_sync 完成);block/redact 在此做最终复核。
784
+ """
785
+ if scope not in {"global", "project"}:
786
+ raise ValueError("scope 必须是 global 或 project")
787
+ if scope == "project" and not str(project_id).strip():
788
+ raise ValueError("project scope 必须显式提供 project_id")
789
+ if base_version is not None and (not isinstance(base_version, int)
790
+ or isinstance(base_version, bool) or base_version < 0):
791
+ raise ValueError("base_version 必须是非负整数")
792
+ filtered_lessons = list(lessons or [])
793
+ filtered_tombstones = list(tombstones or [])
794
+ if scope == "project":
795
+ filtered_lessons = [
796
+ p for p in filtered_lessons
797
+ if not (str(p.get("pattern_id") or p.get("lesson_id") or "").startswith("L-00000000000")
798
+ or ("mistake-book.md" in str(p.get("source_refs") or "")))
799
+ ]
800
+ filtered_tombstones = [
801
+ t for t in filtered_tombstones
802
+ if not (str(t.get("record_type") or "") in ("pattern", "patterns")
803
+ and str(t.get("record_id") or "").startswith("L-00000000000"))
804
+ ]
805
+ records = {
806
+ "patterns": filtered_lessons,
807
+ "incidents": list(incidents or []),
808
+ "tool_experience": list(tool_experience or []),
809
+ "consumption_events": list(consumption_events or []),
810
+ "tombstones": filtered_tombstones,
811
+ }
812
+ validate_records_for_sync(records, policy=sensitive_policy)
813
+ if sensitive_policy != "allow":
814
+ # DOC-211:与 import 档同源——三正则(16+ 值长门槛)之外的裸凭据
815
+ # 形状(短值赋值/sk-/JWT/DSN)由 secret_redactor 形状扫描兜底。
816
+ _validate_secret_shapes(records, policy=sensitive_policy)
817
+ envelope = build_push_envelope(
818
+ scope, _wire_project_id(project_id), records,
819
+ snapshot_id=snapshot_id or uuid.uuid4().hex,
820
+ operation_id=operation_id or f"op-{uuid.uuid4().hex}",
821
+ base_version=0 if base_version is None else base_version,
822
+ device_id=device_id or get_device_id(),
823
+ client_version=current_version_str(),
824
+ )
825
+ # QUA-05:V2-only 传输(DOC-008 §5)。原先这里保留「base64 容器 ->
826
+ # 裸 envelope -> 去除 client_version 的裸 envelope」三级降级级联,
827
+ # 用于适配旧代服务端。**这是破坏性变更**:降级层已移除,服务端若不
828
+ # 接受容器形态就直接失败并暴露错误,不再静默重试旧形态。
829
+ # 移除理由:降级会掩盖服务端不兼容(表现为偶发成功而非明确报错),
830
+ # 且最坏情况下一次 push 会产生 3 次写请求。
831
+ raw = json.dumps(envelope, ensure_ascii=False, sort_keys=True,
832
+ separators=(",", ":")).encode("utf-8")
833
+ container = {
834
+ "transport": "base64-json",
835
+ "payload_b64": base64.b64encode(raw).decode("ascii"),
836
+ }
837
+ return self._request("POST", self.scope_path(scope, project_id), container)
838
+
839
+ def import_knowledge_bundle(self, bundle: dict[str, Any], *, mode: str = "merge",
840
+ sensitive_policy: str = "redact") -> ReportResult:
841
+ """Import one validated V2 JSON bundle through the explicit import API.
842
+
843
+ DOC-211:upload 与 sync 同吃一档策略——block 补凭据形状扫描(堵旧
844
+ 3 正则弱闸放行 bare sk-/JWT/DSN 的旁路);redact 脱敏后重算并回写
845
+ manifest_hash 再发网;allow 原样放行。
846
+ """
847
+ if mode not in {"merge", "local_authoritative"}:
848
+ raise ValueError("mode 必须是 merge 或 local_authoritative")
849
+ if sensitive_policy not in SENSITIVE_POLICIES:
850
+ raise ValueError(
851
+ f"未知敏感策略: {sensitive_policy!r}(允许 {'/'.join(SENSITIVE_POLICIES)})")
852
+ from core.cloud_sync.cloud_schema import validate_push_envelope
853
+ validate_push_envelope(bundle)
854
+ payload = dict(bundle)
855
+ payload["mode"] = mode
856
+ scope = str(bundle.get("scope") or "")
857
+ project_id = str(bundle.get("project_id") or "") if scope == "project" else ""
858
+ if sensitive_policy == "allow":
859
+ return self._request("POST", self._import_path(scope, project_id), payload)
860
+ if sensitive_policy == "redact":
861
+ prepared = prepare_records_for_sync(
862
+ bundle["records"], policy="redact")
863
+ payload["records"] = prepared["records"]
864
+ # redact 改内容后 envelope 的 manifest_hash 必须重算回写,
865
+ # 否则服务端按 manifest==hash(records) 直接拒绝(审计#1-1)。
866
+ from core.cloud_sync.cloud_schema import manifest_hash as _manifest_hash
867
+ payload["manifest_hash"] = _manifest_hash(prepared["records"])
868
+ return self._request("POST", self._import_path(scope, project_id), payload)
869
+ validate_records_for_sync(bundle["records"])
870
+ _validate_secret_shapes(bundle["records"])
871
+ return self._request("POST", self._import_path(scope, project_id), payload)
872
+
873
+ # ---- 错题卡质量闭环(联调方案 §2.4)----
874
+ def post_log_report(self, body: dict) -> ReportResult:
875
+ """内测期诊断日志上报(POST /api/v1/agent/log-reports,登录认证 + 每日限额)。
876
+
877
+ body: {device_id, client_version, kind, payload};payload 为日志文档
878
+ (JSONL 原文或文本)。服务端按账号每日限额(后台可配置)。
879
+ """
880
+ return self._request("POST", "/api/v1/agent/log-reports", body)
881
+
882
+ def post_lesson_hit_feedback(self, feedbacks: list[dict], *, run_id: str = "",
883
+ project_name: str = "") -> ReportResult:
884
+ """扫描收尾批量回报错题卡质量计数(POST /api/v1/agent/lessons/hit-feedback)。
885
+
886
+ feedbacks: [{lesson_id, outcome}],outcome ∈ hit|use|false_positive|miss|rejected;
887
+ 同一 (lesson_id, outcome) 去重;单请求上限 100 条(分批由调用方负责)。
888
+ 鉴权与云同步同会话语义(bxk_ API key / web JWT)。
889
+ """
890
+ dedup: dict[tuple[str, str], dict] = {}
891
+ for index, item in enumerate(feedbacks or []):
892
+ lesson_id = str((item or {}).get("lesson_id", "")).strip()
893
+ outcome = str((item or {}).get("outcome", "")).strip()
894
+ if not lesson_id or outcome not in LESSON_FEEDBACK_OUTCOMES:
895
+ raise ValueError(
896
+ f"hit-feedback[{index}] 参数无效: lesson_id 必填,outcome ∈ "
897
+ f"{'|'.join(LESSON_FEEDBACK_OUTCOMES)}"
898
+ )
899
+ dedup[(lesson_id, outcome)] = {"lesson_id": lesson_id, "outcome": outcome}
900
+ if not dedup:
901
+ raise ValueError("hit-feedback feedbacks 不能为空")
902
+ if len(dedup) > LESSON_FEEDBACK_MAX_ITEMS:
903
+ raise ValueError(f"hit-feedback 单请求最多 {LESSON_FEEDBACK_MAX_ITEMS} 条")
904
+ payload: dict = {"feedbacks": list(dedup.values())}
905
+ if run_id:
906
+ payload["run_id"] = str(run_id)
907
+ if project_name:
908
+ payload["project_name"] = str(project_name)
909
+ return self._request("POST", "/api/v1/agent/lessons/hit-feedback", payload)
910
+
911
+ def pull_knowledge(self, scope: str, project_id: str = "", cursor: str = "",
912
+ page_size: int = DEFAULT_PAGE, *,
913
+ device_id: str | None = None) -> ReportResult:
914
+ """V2 pull:参数只走 query;cursor 是服务端 opaque token,原样透传。"""
915
+ if scope not in {"global", "project"}:
916
+ raise ValueError("scope 必须是 global 或 project")
917
+ if scope == "project" and not str(project_id).strip():
918
+ raise ValueError("project scope 必须显式提供 project_id")
919
+ if not isinstance(page_size, int) or isinstance(page_size, bool) or not 1 <= page_size <= 500:
920
+ raise ValueError("page_size 必须在 1..500")
921
+ if not isinstance(cursor, str):
922
+ raise ValueError("cursor 必须是字符串(opaque token 原样透传)")
923
+ if len(cursor) > MAX_CURSOR_LENGTH:
924
+ raise ValueError(f"cursor 长度不能超过 {MAX_CURSOR_LENGTH}")
925
+ requested_device_id = get_device_id() if device_id is None else device_id
926
+ if not isinstance(requested_device_id, str):
927
+ raise ValueError("device_id 必须是字符串")
928
+ params = {
929
+ "schema_version": SCHEMA_VERSION, "cursor": cursor,
930
+ "page_size": page_size,
931
+ }
932
+ if requested_device_id:
933
+ params["device_id"] = requested_device_id
934
+ result = self._request(
935
+ "GET", self.scope_path(scope, project_id), None,
936
+ params=params,
937
+ extra_headers={"X-BugX-Transport": "base64-json"},
938
+ )
939
+ # The device cursor is a server-side resume hint. If a deployment
940
+ # rotated the server signing key, the hint can be invalid even though
941
+ # the client's local cursor is empty. Retry the initial pull without
942
+ # that hint so the server can return a fresh baseline cursor. Explicit
943
+ # cursors remain fail-closed and are never retried this way.
944
+ if not result.ok and not cursor and requested_device_id:
945
+ err = self.sync_error(result)
946
+ if err.code == "SYNC_INVALID_ENVELOPE" and "cursor" in err.message:
947
+ baseline_params = dict(params)
948
+ baseline_params.pop("device_id", None)
949
+ result = self._request(
950
+ "GET", self.scope_path(scope, project_id), None,
951
+ params=baseline_params,
952
+ )
953
+ if result.ok:
954
+ data = self._data(result)
955
+ # 无损容器:payload_b64 = envelope 原文 base64 + sha256 完整性校验。
956
+ if isinstance(data, dict) and data.get("transport") == "base64-json":
957
+ raw = base64.b64decode(data.get("payload_b64") or "")
958
+ payload = json.loads(raw)
959
+ expected = data.get("content_sha256")
960
+ if expected and expected != "sha256:" + hashlib.sha256(raw).hexdigest():
961
+ return ReportResult(ok=False, status=result.status,
962
+ data=result.data, error="pull 容器 sha256 校验失败")
963
+ # ReportResult 是 frozen dataclass:用 replace 派生解码后的结果
964
+ result = dataclasses.replace(result, data=payload)
965
+ try:
966
+ validate_pull_envelope(self._data(result), scope=scope, project_id=project_id)
967
+ except SchemaError as exc:
968
+ return ReportResult(ok=False, status=result.status,
969
+ data=result.data, error=str(exc))
970
+ return result
971
+
972
+ def ack_knowledge(self, scope: str, project_id: str = "", cursor: str = "",
973
+ *, device_id: str | None = None) -> ReportResult:
974
+ """ACK a durably imported pull cursor so the server may run GC."""
975
+ if scope not in {"global", "project"}:
976
+ raise ValueError("scope 必须是 global 或 project")
977
+ if scope == "project" and not str(project_id).strip():
978
+ raise ValueError("project scope 必须显式提供 project_id")
979
+ if scope == "global" and project_id not in {"", None}:
980
+ raise ValueError("global scope 不得提供 project_id")
981
+ if not isinstance(cursor, str) or not cursor or len(cursor) > MAX_CURSOR_LENGTH:
982
+ raise ValueError("cursor 必须是非空字符串且长度不超过 512")
983
+ requested_device_id = device_id or get_device_id()
984
+ if not isinstance(requested_device_id, str) or not requested_device_id:
985
+ raise ValueError("device_id 必须是非空字符串")
986
+ body = {
987
+ "schema_version": SCHEMA_VERSION,
988
+ "scope": scope,
989
+ "project_id": _wire_project_id(project_id) if scope == "project" else None,
990
+ "cursor": cursor,
991
+ "device_id": requested_device_id,
992
+ }
993
+ return self._request("POST", self._ack_path(scope, project_id), body)
994
+
995
+ def prefetch_knowledge(
996
+ self,
997
+ classification: Mapping[str, Any] | None = None,
998
+ *,
999
+ language: str = "",
1000
+ forms: list[str] | None = None,
1001
+ surfaces: list[str] | None = None,
1002
+ frameworks: list[str] | None = None,
1003
+ routing_tags: dict[str, list[str]] | None = None,
1004
+ tools: list[str] | None = None,
1005
+ tool_names: list[str] | None = None,
1006
+ limit: int = 20,
1007
+ project_id: int | str | None = None,
1008
+ ) -> ReportResult:
1009
+ """DOC-041 Phase 2: 定向预拉错题、经验、推荐工具链与预热规则。
1010
+
1011
+ Agent 在任务启动前按分类画像一次性拉取最相关的错题与经验,
1012
+ 无需执行全量同步。服务端支持 GET 查询参数与 POST JSON 体。
1013
+ """
1014
+ if not isinstance(limit, int) or isinstance(limit, bool) or not 1 <= limit <= 100:
1015
+ raise ValueError("limit 必须在 1..100 之间")
1016
+
1017
+ payload: dict[str, Any] = {}
1018
+ active_tools = tools if tools is not None else tool_names
1019
+ if classification and isinstance(classification, (dict, Mapping)):
1020
+ if not language:
1021
+ language = str(classification.get("primary_language") or classification.get("language") or "")
1022
+ if forms is None and "forms" in classification:
1023
+ forms = classification.get("forms")
1024
+ if surfaces is None and "surfaces" in classification:
1025
+ surfaces = classification.get("surfaces")
1026
+ if frameworks is None and "frameworks" in classification:
1027
+ frameworks = classification.get("frameworks")
1028
+ if routing_tags is None and "routing_tags" in classification:
1029
+ routing_tags = classification.get("routing_tags")
1030
+ if active_tools is None:
1031
+ active_tools = classification.get("tools") or classification.get("tool_names")
1032
+
1033
+ if language and isinstance(language, str) and language.strip() and language.strip() != "unknown":
1034
+ payload["language"] = language.strip()
1035
+ if forms and isinstance(forms, (list, tuple, set)):
1036
+ payload["forms"] = [str(f).strip() for f in forms if str(f).strip()]
1037
+ if surfaces and isinstance(surfaces, (list, tuple, set)):
1038
+ payload["surfaces"] = [str(s).strip() for s in surfaces if str(s).strip()]
1039
+ if frameworks and isinstance(frameworks, (list, tuple, set)):
1040
+ payload["frameworks"] = [str(fw).strip() for fw in frameworks if str(fw).strip()]
1041
+ if active_tools and isinstance(active_tools, (list, tuple, set)):
1042
+ payload["tools"] = [str(t).strip() for t in active_tools if str(t).strip()]
1043
+ if routing_tags and isinstance(routing_tags, dict):
1044
+ payload["routing_tags"] = {
1045
+ str(k).strip(): [str(v).strip() for v in vals if str(v).strip()]
1046
+ for k, vals in routing_tags.items()
1047
+ if isinstance(vals, (list, tuple, set))
1048
+ }
1049
+ payload["limit"] = limit
1050
+ if project_id is not None and str(project_id).strip():
1051
+ try:
1052
+ pid_int = int(project_id)
1053
+ if pid_int > 0:
1054
+ payload["project_id"] = pid_int
1055
+ except (ValueError, TypeError):
1056
+ pass
1057
+
1058
+ return self._request("POST", KNOWLEDGE_PREFETCH_PATH, payload)
1059
+
1060
+ def sync_status(self) -> ReportResult:
1061
+ return self._request("GET", SYNC_STATUS_PATH)
1062
+
1063
+ def scope_path(self, scope: str, project_id: str) -> str:
1064
+ if scope == "global":
1065
+ return f"{AGENT_API_PREFIX}/global/knowledge"
1066
+ value = str(project_id)
1067
+ if not re.fullmatch(r"[1-9][0-9]*", value):
1068
+ raise ValueError("project_id 必须是服务端返回的正整数 ID")
1069
+ return f"{AGENT_API_PREFIX}/projects/{value}/knowledge"
1070
+
1071
+ def _import_path(self, scope: str, project_id: str) -> str:
1072
+ return self.scope_path(scope, project_id) + "/import"
1073
+
1074
+ def _ack_path(self, scope: str, project_id: str) -> str:
1075
+ """Return the post-import ACK endpoint for one V2 knowledge scope."""
1076
+ return self.scope_path(scope, project_id) + "/ack"
1077
+
1078
+ def _profile_path(self, project_id: str) -> str:
1079
+ value = str(project_id)
1080
+ if not re.fullmatch(r"[1-9][0-9]*", value):
1081
+ raise ValueError("project_id 必须是服务端返回的正整数 ID")
1082
+ return f"{AGENT_API_PREFIX}/projects/{value}/profile"
1083
+
1084
+ # ---- 版本检查与 CLI 包下载(Phase 2 自动更新)----
1085
+
1086
+ def check_version(self, current_version: str = "", channel: str = "") -> ReportResult:
1087
+ """GET /api/v1/agent/version — 查询最新版本元数据。
1088
+
1089
+ 当传入 current_version 时,服务端额外返回 update_available 和
1090
+ update_required 布尔字段。channel 用于选择发布通道(stable /
1091
+ alpha);留空使用服务端默认(stable)通道。此端点公开无需认证,仅限流。
1092
+ """
1093
+ params = {}
1094
+ if current_version:
1095
+ params["current"] = current_version
1096
+ if channel and channel.strip():
1097
+ params["channel"] = channel.strip()
1098
+ return self._request("GET", VERSION_CHECK_PATH, None,
1099
+ auth=False, retry_auth=False, params=params or None)
1100
+
1101
+ @staticmethod
1102
+ def _is_allowed_agent_download_url(url: str) -> bool:
1103
+ """升级包最终 URL 白名单:https 任意主机;http 仅限回环地址。
1104
+
1105
+ 明文 HTTP 到远端会被中间人篡改升级包,一律拒绝;但回环地址
1106
+ (127.0.0.1/::1/localhost)不出机器,本地镜像与测试夹具依赖它。
1107
+ """
1108
+ parts = urllib.parse.urlsplit(url)
1109
+ if parts.scheme == "https":
1110
+ return True
1111
+ if parts.scheme == "http":
1112
+ host = (parts.hostname or "").strip("[]").lower()
1113
+ return host in {"127.0.0.1", "::1", "localhost"}
1114
+ return False
1115
+
1116
+ def download_package(self, dest: Path, *, expected_sha256: str = "",
1117
+ expected_version: str = "") -> tuple[bool, str]:
1118
+ """GET /api/v1/agent/download — 下载 CLI 包到指定路径。
1119
+
1120
+ 返回 (success, message)。下载后做 SHA-256 校验(必须提供)。
1121
+ 如果 download_url 指向外部地址,服务端会返回 302 重定向,此方法
1122
+ 跟随重定向下载,但最终 URL 必须仍是 https://(回环地址例外,
1123
+ 见 `_is_allowed_agent_download_url`),否则拒绝。
1124
+
1125
+ dest: 目标文件路径(含文件名)。
1126
+ expected_sha256: 下载后校验哈希(必填,缺失即拒绝下载)。
1127
+ expected_version: 仅用于日志/提示,不影响逻辑。
1128
+ """
1129
+ expected_sha256 = str(expected_sha256 or "").strip().lower()
1130
+ if not expected_sha256:
1131
+ return False, "缺少 SHA-256 校验值,拒绝下载"
1132
+ if not re.fullmatch(r"[0-9a-f]{64}", expected_sha256):
1133
+ return False, "下载失败: expected_sha256 必须是 64 位 SHA-256 hex"
1134
+
1135
+ url = self.base + DOWNLOAD_PATH
1136
+ # 跟随重定向(版本检查端点可能配置了外部 PyPI 镜像地址)
1137
+ opener = _build_redirect_opener(self.base)
1138
+ headers = {"Accept": "application/octet-stream", **client_headers()}
1139
+ req = urllib.request.Request(url, headers=headers)
1140
+ try:
1141
+ resp = opener.open(req, timeout=self.timeout)
1142
+ try:
1143
+ # 升级包绝不能从明文 HTTP 端点拉取;服务端 302 跳转外部
1144
+ # 镜像时,最终 URL 必须仍是 https://,否则整体拒绝。
1145
+ final_url = ""
1146
+ geturl = getattr(resp, "geturl", None)
1147
+ if callable(geturl):
1148
+ final_url = str(geturl() or "")
1149
+ if not self._is_allowed_agent_download_url(final_url):
1150
+ return False, (
1151
+ f"下载失败: 最终 URL 非 HTTPS,拒绝下载: {final_url}"
1152
+ )
1153
+ headers = getattr(resp, "headers", None)
1154
+ content_length = None
1155
+ if headers is not None:
1156
+ raw_length = headers.get("Content-Length")
1157
+ if raw_length:
1158
+ try:
1159
+ content_length = int(raw_length)
1160
+ except (TypeError, ValueError):
1161
+ return False, "下载失败: Content-Length 无效"
1162
+ if content_length < 0 or content_length > MAX_AGENT_PACKAGE_BYTES:
1163
+ return False, "下载失败: CLI 包超过允许大小"
1164
+
1165
+ chunks: list[bytes] = []
1166
+ total = 0
1167
+ while True:
1168
+ try:
1169
+ chunk = resp.read(AGENT_PACKAGE_READ_CHUNK)
1170
+ except TypeError: # 简化测试响应仍可能只接受无参 read()
1171
+ chunk = resp.read()
1172
+ if not chunk:
1173
+ break
1174
+ total += len(chunk)
1175
+ if total > MAX_AGENT_PACKAGE_BYTES:
1176
+ return False, "下载失败: CLI 包超过允许大小"
1177
+ chunks.append(chunk)
1178
+ if content_length is not None and total != content_length:
1179
+ return False, "下载失败: 响应长度与 Content-Length 不一致"
1180
+ data = b"".join(chunks)
1181
+ finally:
1182
+ resp.close()
1183
+ except urllib.error.HTTPError as exc:
1184
+ raw = b""
1185
+ try:
1186
+ raw = exc.read()
1187
+ finally:
1188
+ try:
1189
+ exc.close()
1190
+ except Exception: # noqa: BLE001
1191
+ pass
1192
+ return False, f"下载失败: HTTP {exc.code} {message_from_response(raw, exc)}"
1193
+ except (urllib.error.URLError, OSError) as exc:
1194
+ return False, f"下载失败: {exc}"
1195
+
1196
+ # SHA-256 校验
1197
+ if expected_sha256:
1198
+ actual = hashlib.sha256(data).hexdigest()
1199
+ if actual != expected_sha256:
1200
+ return False, (
1201
+ f"SHA-256 校验失败: 期望 {expected_sha256},实际 {actual}"
1202
+ )
1203
+
1204
+ # 写入目标文件
1205
+ dest.parent.mkdir(parents=True, exist_ok=True)
1206
+ try:
1207
+ atomic_write_nofollow(dest, data)
1208
+ except (OSError, ValueError) as exc:
1209
+ return False, f"写入文件失败: {exc}"
1210
+
1211
+ version_note = f" (v{expected_version})" if expected_version else ""
1212
+ return True, f"CLI 包已下载到 {dest}{version_note}"
1213
+
1214
+
1215
+ def current_version_str() -> str:
1216
+ """返回当前引擎/CLI 版本号,用于 User-Agent(自包含零反向导入)。"""
1217
+ return client_version()
1218
+