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,4210 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import contextvars
5
+ import copy
6
+ import hashlib
7
+ import json
8
+ import os
9
+ import re
10
+ import shutil
11
+ import stat
12
+ import struct
13
+ import subprocess
14
+ import sys
15
+ import tempfile
16
+ import time
17
+ from pathlib import Path
18
+ from typing import Any
19
+
20
+ from .. import __version__
21
+ from ..common import _close_bugx_logging
22
+ from ..infra.engine_installer import refresh_i18n_after_engine_swap
23
+ from ..common import *
24
+ from ..hosts.registry import (
25
+ engine_host_cli_hook,
26
+ engine_host_label,
27
+ engine_host_plugins,
28
+ engine_mirror_root,
29
+ engine_worker_entry_dir,
30
+ )
31
+ # 安装流程按能力标签分支,而不是按宿主名字符串比较;标签与宿主名的绑定
32
+ # 只在 host_adapters.HOST_ADAPTERS 声明处发生一次。
33
+ from ..host_adapters import (
34
+ CAP_DISTRIBUTION_PLUGIN,
35
+ CAP_EXTENSION_PAYLOAD,
36
+ CAP_EXTRA_TRACKED_PATHS,
37
+ CAP_GLOBAL_AGENT_LINK,
38
+ CAP_GLOBAL_SKILL_LINK,
39
+ CAP_NATIVE_MCP_CONFIG,
40
+ CAP_PREVALIDATE_CATALOG,
41
+ CAP_PROJECT_MCP_CONFIG,
42
+ CAP_PROJECT_PATCH_OVERLAY,
43
+ CAP_USER_AGENT_REGISTRATION,
44
+ CAP_USER_LEVEL_ARTIFACT,
45
+ CAP_WORKSPACE_MIRROR,
46
+ CAP_WORKSPACE_MIRROR_VARIANTS,
47
+ ENTRY_MULTI_PATH,
48
+ ENTRY_PLUGIN_CATALOG,
49
+ ENTRY_SHARED_SYMLINK,
50
+ ENTRY_SKILL_PAYLOAD,
51
+ ENTRY_USER_REGISTRATION,
52
+ HOST_ADAPTERS,
53
+ HOST_NAME_CLAUDE,
54
+ HOST_NAME_FUNIDE,
55
+ HOST_NAME_QODER,
56
+ HOST_NAME_ZCODE,
57
+ )
58
+ from .plugin import (
59
+ _chatgpt_marketplace,
60
+ _ensure_chatgpt_plugin,
61
+ _ensure_zcode_plugin,
62
+ _sweep_legacy_skill_entry,
63
+ _sweep_legacy_zcode_project_entries,
64
+ _prompt_for_hosts,
65
+ _restore_host_mcp_config_change,
66
+ _validate_host_supervisor_mcp,
67
+ _validate_zcode_global_supervisor_mcp,
68
+ _write_host_entry,
69
+ write_host_mcp_config,
70
+ _zcode_bound_project_root,
71
+ _ensure_zcode_user_skill,
72
+ _zcode_user_agents_dir,
73
+ )
74
+ from .plugin_claude import (
75
+ _claude_user_agents_dir,
76
+ )
77
+ from .plugin_funide import (
78
+ _NATIVE_AGENT_OWNERSHIP_MARK,
79
+ _funide_data_dir,
80
+ _funide_profile_mcp_path,
81
+ _funide_user_skills_dir,
82
+ _funide_user_agents_dir,
83
+ )
84
+
85
+
86
+
87
+ class _CliProgress:
88
+ """Render completed CLI stages without affecting machine-readable output."""
89
+
90
+ _WIDTH = 24
91
+
92
+ def __init__(self, args: argparse.Namespace) -> None:
93
+ self.enabled = (
94
+ not getattr(args, "json", False)
95
+ and os.environ.get("BUGX_NO_PROGRESS") != "1"
96
+ and bool(getattr(sys.stderr, "isatty", lambda: False)())
97
+ )
98
+
99
+ def update(self, percent: int, label: str) -> None:
100
+ if not self.enabled:
101
+ return
102
+ percent = max(0, min(100, percent))
103
+ filled = self._WIDTH * percent // 100
104
+ line = f"[bugx] 进度 [{('=' * filled).ljust(self._WIDTH, '-')}] {percent:3d}% {label}"
105
+ sys.stderr.write("\r" + line)
106
+ sys.stderr.flush()
107
+
108
+ def finish(self, label: str = "完成") -> None:
109
+ if not self.enabled:
110
+ return
111
+ self.update(100, label)
112
+ sys.stderr.write("\n")
113
+ sys.stderr.flush()
114
+
115
+ def fail(self, label: str = "失败,正在回滚") -> None:
116
+ if not self.enabled:
117
+ return
118
+ sys.stderr.write("\n")
119
+ self.update(0, label)
120
+ sys.stderr.write("\n")
121
+ sys.stderr.flush()
122
+
123
+
124
+ # Backward-compatible test/import name; the renderer is shared by all long CLI commands.
125
+ _InstallProgress = _CliProgress
126
+
127
+ #: **未迁移**宿主的安装面基线(逐宿主切片时删除对应项)。已迁移宿主的目录由
128
+ #: ``HOST_ADAPTERS.managed_surfaces()``(插件 marker 投影)自动追加。
129
+ #: **未迁移**宿主的用户级可见位置提示;已迁移宿主用 ``全局 <label> 可见``。
130
+ _USER_AGENT_VISIBILITY_HINTS = {
131
+ "funide": "FunIDE 设置 → 智能体可见",
132
+ }
133
+
134
+
135
+ def _user_agent_visibility(host_name: str) -> str:
136
+ """用户级注册后的「在哪里可见」提示(未迁移宿主走基线表)。"""
137
+
138
+ hint = _USER_AGENT_VISIBILITY_HINTS.get(host_name)
139
+ return hint or f"全局 {engine_host_label(host_name)} 可见"
140
+
141
+
142
+ _BASE_AGENT_INSTALL_SURFACES = (
143
+ ".bugx", ".opencode", ".claude", ".zcode", ".pi", ".agents",
144
+ ".workbuddy", ".codebuddy", ".qoder", ".github",
145
+ ".dsh", "plugins", CONFIG_NAME,
146
+ )
147
+ _AGENT_INSTALL_SURFACES = tuple(
148
+ dict.fromkeys(
149
+ list(_BASE_AGENT_INSTALL_SURFACES)
150
+ + [surface for adapter in HOST_ADAPTERS for surface in adapter.managed_surfaces()]
151
+ )
152
+ )
153
+
154
+ # The transaction protects only BugX-owned files that the install path can
155
+ # write. It must never copy an entire host directory: user-level installs
156
+ # commonly run from HOME, where .codex/.tmp, plugin caches, sessions, and
157
+ # databases are both unrelated to BugX and likely to change concurrently.
158
+ _AGENT_INSTALL_SNAPSHOT_FILES = (
159
+ ".bugx/manifest.json",
160
+ ".bugx/current.json",
161
+ ".bugx/hosts.json",
162
+ ".bugx/README.md",
163
+ ".bugx/index/index.json",
164
+ ".bugx/knowledge/manifest.json",
165
+ ".bugx/knowledge/lesson-ledger.json",
166
+ ".bugx/knowledge/lesson-ledger.sqlite3",
167
+ ".bugx/knowledge/lesson-ledger.sqlite3-shm",
168
+ ".bugx/knowledge/lesson-ledger.sqlite3-wal",
169
+ ".bugx/knowledge/bug-log.md",
170
+ ".bugx/knowledge/mistake-book.md",
171
+ "opencode.json",
172
+ ".mcp.json",
173
+ ".opencode/agent/bugx.md",
174
+ ".opencode/agents/bugx.md",
175
+ ".opencode/agents/bugx-worker.md",
176
+ ".claude/agents/bugx.md",
177
+ ".claude/skills/bugx/SKILL.md",
178
+ ".claude/dist/bugx.plugin",
179
+ ".claude/dist/bugx.skill",
180
+ ".dsh/patch.yml",
181
+ ".dsh/skills/bugx/SKILL.md",
182
+ ".dsh/skills/bugx-dsh/SKILL.md",
183
+ ".dsh/agents/bugx.md",
184
+ ".zcode/agents/bugx.md",
185
+ ".workbuddy/skills/bugx/SKILL.md",
186
+ ".workbuddy/connector/bugx/connector-meta.json",
187
+ ".workbuddy/connector/bugx/icon.png",
188
+ ".workbuddy/connector/bugx/skills/bugx/SKILL.md",
189
+ ".codebuddy/skills/bugx/SKILL.md",
190
+ ".pi/skills/bugx/SKILL.md",
191
+ ".pi/extensions/bugx/index.ts",
192
+ ".pi/extensions/bugx/manifest.json",
193
+ ".pi/extensions/bugx/README.md",
194
+ ".agents/plugins/marketplace.json",
195
+ ".qoder/agents/bugx.md",
196
+ ".qoder/agents/bugx-worker.md",
197
+ ".qoder/mcp.json",
198
+ ".github/agents/bugx.agent.md",
199
+ ".trea/agents/bugx.md",
200
+ ".trea/mcp.json",
201
+ "plugins/bugx/.codex-plugin/plugin.json",
202
+ "plugins/bugx/assets/bugx-avatar-512.png",
203
+ "plugins/bugx/.zcode-plugin/plugin.json",
204
+ "plugins/bugx/agents/bugx.md",
205
+ "plugins/bugx/agents/bugx-worker.md",
206
+ "plugins/bugx/skills/bugx/SKILL.md",
207
+ "plugins/bugx/skills/bugx-zcode/SKILL.md",
208
+ "plugins/bugx/skills/bugx-claude/SKILL.md",
209
+ "plugins/bugx/skills/bugx-dsh/SKILL.md",
210
+ "integrations/qoder/connector-meta.json",
211
+ "integrations/qoder/CONNECTORS.md",
212
+ ) + tuple(
213
+ dict.fromkeys(
214
+ rel
215
+ for plugin in engine_host_plugins()
216
+ for rel in (
217
+ plugin.install.path,
218
+ *plugin.install.required_paths,
219
+ *plugin.install.legacy_paths,
220
+ )
221
+ if rel and not Path(rel).is_absolute()
222
+ )
223
+ )
224
+
225
+
226
+ def _json_default(value: object) -> str:
227
+ """Serialize filesystem paths in machine-readable install results."""
228
+ if isinstance(value, Path):
229
+ return str(value)
230
+ raise TypeError(
231
+ f"Object of type {type(value).__name__} is not JSON serializable"
232
+ )
233
+ _AGENT_INSTALL_SNAPSHOT_MANIFEST = ".agent-install-snapshot.json"
234
+
235
+ _ENGINE_VERSION_RE = re.compile(r'bugx_version:\s*"(\d+\.\d+\.\d+(?:\+[0-9A-Za-z.-]+)?)"')
236
+
237
+
238
+ def _read_engine_version(engine: Path) -> str | None:
239
+ """读取已安装引擎声明的版本;缺失或不可读时返回 None。"""
240
+ marker = engine / "metadata.txt"
241
+ try:
242
+ if not marker.is_file() or marker.is_symlink():
243
+ return None
244
+ content = marker.read_text(encoding="utf-8")
245
+ except (OSError, ValueError):
246
+ return None
247
+ match = _ENGINE_VERSION_RE.search(content)
248
+ return match.group(1) if match else None
249
+
250
+
251
+ def _version_key(value: str) -> tuple[int, ...] | None:
252
+ """把 ``x.y.z`` 归一为可比较的元组;非规范版本返回 None。"""
253
+ try:
254
+ return tuple(int(part) for part in value.split("+", 1)[0].split("."))
255
+ except ValueError:
256
+ return None
257
+
258
+
259
+ def _warn_engine_version_drift(
260
+ prior_engine_version: str | None, *, replaced: bool | None = None,
261
+ ) -> None:
262
+ """引擎版本与当前 CLI 不一致时告警,并给出方向对应的补救动作。
263
+
264
+ 必须在 ``_install_engine`` **之前**采样版本:``_stage_engine`` 会用运行中的
265
+ CLI 版本重新盖章 ``metadata.txt``,因此安装之后再比对必然得到两个相等的版本,
266
+ 永远观察不到漂移(旧实现即因此成为不可达分支,两条路径都到不了告警)。
267
+
268
+ ``replaced`` 说明引擎是否**真的**被换掉了:``_install_engine`` 遇到「已安装
269
+ 引擎更新且未 --force」时会跳过替换,此时不能宣称「已回退」。
270
+ """
271
+ if prior_engine_version is None or prior_engine_version == __version__:
272
+ return
273
+ order = None
274
+ prior_key = _version_key(prior_engine_version)
275
+ current_key = _version_key(__version__)
276
+ if prior_key is not None and current_key is not None:
277
+ order = prior_key < current_key
278
+ if order is True:
279
+ detail = f"已安装的 core 版本 {prior_engine_version} 落后于当前 CLI 版本 {__version__}。"
280
+ remedy = "请先使用普通 'bugx install' 刷新;仅存在静态冲突时再追加 '--force'。"
281
+ elif order is False:
282
+ detail = f"当前 CLI 版本 {__version__} 落后于已安装的 core 版本 {prior_engine_version}。"
283
+ if replaced is True:
284
+ remedy = (
285
+ "本次安装已把共享引擎回退到该 CLI 自带的版本,可能影响依赖新引擎的其他项目;"
286
+ "请升级 CLI 后重跑(例如 'uv tool install --reinstall bugx-cli')。"
287
+ )
288
+ elif replaced is False:
289
+ remedy = (
290
+ "已跳过引擎替换以避免回退所有项目共享的引擎;"
291
+ "请升级 CLI 后重跑(例如 'uv tool install --reinstall bugx-cli'),"
292
+ "确需回退请追加 '--force'。"
293
+ )
294
+ else:
295
+ remedy = (
296
+ "请升级 CLI 后重跑(例如 'uv tool install --reinstall bugx-cli');"
297
+ "确需回退请追加 '--force'。"
298
+ )
299
+ else:
300
+ detail = f"已安装的 core 版本 {prior_engine_version} 与当前 CLI 版本 {__version__} 不一致。"
301
+ remedy = "请确认 CLI 与共享引擎来自同一发行版本。"
302
+ # 警告走 stderr,避免污染 --json 的机器可读 stdout 契约。
303
+ print(f"[bugx] 警告:全局引擎版本不一致,{detail}{remedy}", file=sys.stderr)
304
+
305
+
306
+ def _knowledge_marker_is_global(marker: Path) -> bool:
307
+ """标记文件显式声明 ``scope=global`` 时返回 True。
308
+
309
+ 项目知识根与全局知识根塌缩到同一目录时(从 HOME 执行安装),全局清单会占用
310
+ 项目清单的路径。它不构成「项目错题集曾经存在」的证据,因此不能被当作
311
+ fail-closed 的依据。无法解析时返回 False,保留原有的 fail-closed 行为。
312
+ """
313
+ try:
314
+ payload = json.loads(marker.read_text(encoding="utf-8"))
315
+ except (OSError, ValueError):
316
+ return False
317
+ return isinstance(payload, dict) and payload.get("scope") == "global"
318
+
319
+
320
+ def command_agent(args: argparse.Namespace) -> int:
321
+ """Run host install as a recoverable project-local transaction."""
322
+ _prior_no_llm = os.environ.get("BUGX_PROFILE_NO_LLM")
323
+ os.environ["BUGX_PROFILE_NO_LLM"] = "1"
324
+ try:
325
+ if getattr(args, "agent_command", "install") == "discover":
326
+ return _command_agent_impl(args)
327
+ verify_builtin_mcp_manifest()
328
+ progress = _CliProgress(args)
329
+ progress.update(0, "准备安装")
330
+ root = args.root.resolve()
331
+ try:
332
+ staging, existed = _agent_install_snapshot(root)
333
+ except (OSError, shutil.Error) as exc:
334
+ raise CliError(_i18n_exc(
335
+ "agent.install_snapshot_failed",
336
+ f"创建安装事务快照失败,未修改文件:{exc};请确认 --root 存在且受管文件可读",
337
+ exc=exc,
338
+ )) from exc
339
+ token = _GLOBAL_TX.set(staging)
340
+ preserve_staging = False
341
+ try:
342
+ return _command_agent_impl(args, progress=progress)
343
+ except BaseException as install_error:
344
+ progress.fail()
345
+ rollback_errors: list[str] = []
346
+ try:
347
+ # Rollback deletes the live ``.bugx`` tree; release its diagnostic
348
+ # lock before restoring (Windows otherwise raises WinError 32).
349
+ _close_bugx_logging()
350
+ except BaseException as exc:
351
+ rollback_errors.append(f"关闭诊断日志失败: {exc}")
352
+ # Restore global entries before project-managed paths. Continue after
353
+ # one failure so independent snapshots still have a chance to recover.
354
+ try:
355
+ _restore_global_transaction(staging)
356
+ except BaseException as exc:
357
+ rollback_errors.append(f"全局入口: {exc}")
358
+ try:
359
+ _restore_agent_install_snapshot(root, staging, existed)
360
+ except BaseException as exc:
361
+ rollback_errors.append(f"项目入口: {exc}")
362
+ if rollback_errors:
363
+ preserve_staging = True
364
+ details = ";".join(rollback_errors)
365
+ raise CliError(
366
+ f"安装失败({install_error}),且回滚不完整:{details};"
367
+ f"事务快照已保留在 {staging}"
368
+ ) from install_error
369
+ raise
370
+ finally:
371
+ _GLOBAL_TX.reset(token)
372
+ if not preserve_staging:
373
+ shutil.rmtree(staging, ignore_errors=True)
374
+ finally:
375
+ if _prior_no_llm is None:
376
+ os.environ.pop("BUGX_PROFILE_NO_LLM", None)
377
+ else:
378
+ os.environ["BUGX_PROFILE_NO_LLM"] = _prior_no_llm
379
+
380
+
381
+ def _is_special_install_entry(path: Path) -> bool:
382
+ """Runtime sockets/FIFOs/devices are not install transaction payload."""
383
+ try:
384
+ mode = path.lstat().st_mode
385
+ except OSError:
386
+ return False
387
+ return not (stat.S_ISREG(mode) or stat.S_ISDIR(mode) or stat.S_ISLNK(mode))
388
+
389
+
390
+ def _ignore_install_snapshot_entries(directory: str, names: list[str]) -> list[str]:
391
+ return [name for name in names if _is_special_install_entry(Path(directory) / name)]
392
+
393
+
394
+ def _agent_install_snapshot(root: Path) -> tuple[Path, dict[str, bool]]:
395
+ """Stage only BugX-owned files before a host install.
396
+
397
+ Installation touches shared runtime files as well as one or more host
398
+ entries. A failure in a later host must not leave an apparently installed
399
+ but incomplete bundle, so the wrapper below restores this snapshot. Host
400
+ directories themselves are never recursively copied; unrelated files are
401
+ preserved in place.
402
+ """
403
+ staging = Path(tempfile.mkdtemp(prefix="bugx-install-transaction-")).resolve()
404
+ existed: dict[str, bool] = {}
405
+ try:
406
+ for relative in _AGENT_INSTALL_SURFACES:
407
+ target = root / relative
408
+ existed[relative] = target.exists() or _is_reparse_point(target)
409
+ if not existed[relative]:
410
+ continue
411
+ if _is_reparse_point(target):
412
+ if relative == ".agents":
413
+ # ponytail: .agents may be a host-owned Windows reparse point;
414
+ # leave it outside this project transaction. ChatGPT has a
415
+ # restricted resolver; other host writers remain fail-closed.
416
+ existed.pop(relative)
417
+ continue
418
+ if not target.exists():
419
+ try:
420
+ target.unlink()
421
+ existed[relative] = False
422
+ continue
423
+ except OSError:
424
+ pass
425
+ raise CliError(_i18n_exc("agent.symlink_install_target_refused", f"拒绝以符号链接作为安装事务目标: {target}", target=target))
426
+
427
+ entries: list[dict[str, object]] = []
428
+ for relative in dict.fromkeys(_AGENT_INSTALL_SNAPSHOT_FILES):
429
+ surface = Path(relative).parts[0]
430
+ if surface not in existed:
431
+ # .agents may be a host-owned reparse point and was explicitly
432
+ # removed from the transaction above.
433
+ continue
434
+ target = root / relative
435
+ entry: dict[str, object] = {"path": relative, "existed": False}
436
+ if target.is_symlink():
437
+ entry.update({
438
+ "existed": True,
439
+ "kind": "symlink",
440
+ "target": os.readlink(target),
441
+ "target_is_directory": target.is_dir(),
442
+ })
443
+ elif target.is_file():
444
+ staged = staging / relative
445
+ staged.parent.mkdir(parents=True, exist_ok=True)
446
+ shutil.copy2(target, staged)
447
+ entry.update({"existed": True, "kind": "file"})
448
+ elif target.is_dir():
449
+ # The install path expects a file at these locations. Record
450
+ # the shape without traversing it so rollback can preserve it.
451
+ entry.update({"existed": True, "kind": "directory"})
452
+ entries.append(entry)
453
+
454
+ (staging / _AGENT_INSTALL_SNAPSHOT_MANIFEST).write_text(
455
+ json.dumps({"files": entries}, ensure_ascii=False, indent=2),
456
+ encoding="utf-8",
457
+ )
458
+ return staging, existed
459
+ except BaseException:
460
+ shutil.rmtree(staging, ignore_errors=True)
461
+ raise
462
+
463
+
464
+ # ---------------------------------------------------------------------------
465
+ # F-L0-03:安装事务的**全局面**日志(用户级全局入口的回滚依据)
466
+ #
467
+ # 项目内受管面由 ``_agent_install_snapshot`` / ``_restore_agent_install_snapshot``
468
+ # 负责;本机制补齐**用户级全局入口**(``~/.config/opencode/agents``、``~/.agents``、
469
+ # ``~/.pi``、WorkBuddy 用户级 skills 等)。任一宿主安装失败时,两者都必须回到
470
+ # 安装前状态,不得留下半安装。
471
+ # ---------------------------------------------------------------------------
472
+ _GLOBAL_TX: contextvars.ContextVar[Path | None] = contextvars.ContextVar(
473
+ "bugx_agent_global_tx", default=None,
474
+ )
475
+
476
+
477
+ def _global_tx_journal(staging: Path) -> Path:
478
+ return staging / "global-journal.json"
479
+
480
+
481
+ def _read_global_tx_entries(journal: Path) -> list[dict[str, object]]:
482
+ if journal.is_symlink():
483
+ raise CliError(f"全局安装事务日志不能是符号链接: {journal}")
484
+ if not journal.exists():
485
+ return []
486
+ if not journal.is_file():
487
+ raise CliError(f"全局安装事务日志不是普通文件: {journal}")
488
+ try:
489
+ loaded = json.loads(journal.read_text(encoding="utf-8"))
490
+ except (OSError, json.JSONDecodeError) as exc:
491
+ raise CliError(f"无法读取全局安装事务日志: {journal}: {exc}") from exc
492
+ if not isinstance(loaded, dict) or not isinstance(loaded.get("entries"), list):
493
+ raise CliError(f"全局安装事务日志格式无效: {journal}")
494
+ if any(not isinstance(entry, dict) for entry in loaded["entries"]):
495
+ raise CliError(f"全局安装事务日志含无效记录: {journal}")
496
+ return list(loaded["entries"])
497
+
498
+
499
+ def _tx_stage_global(target: Path) -> None:
500
+ """先持久化全局目标快照;无法保护目标时必须在写入前失败。"""
501
+ staging = _GLOBAL_TX.get()
502
+ if staging is None:
503
+ return
504
+ journal = _global_tx_journal(staging)
505
+ if not target.is_absolute():
506
+ raise CliError(f"全局安装事务目标必须是绝对路径: {target}")
507
+ entries = _read_global_tx_entries(journal)
508
+ index = len(entries)
509
+ snapshot = staging / "global" / str(index)
510
+ entry: dict[str, object] = {"path": str(target), "index": index}
511
+ try:
512
+ if target.is_symlink():
513
+ entry.update(kind="symlink", link=os.readlink(target))
514
+ elif target.is_file():
515
+ snapshot.parent.mkdir(parents=True, exist_ok=True)
516
+ shutil.copy2(target, snapshot)
517
+ entry.update(kind="file", snapshot=str(snapshot))
518
+ elif target.is_dir():
519
+ entry.update(kind="dir")
520
+ else:
521
+ entry.update(kind="missing")
522
+ except OSError as exc:
523
+ raise CliError(f"无法为全局安装目标创建回滚快照,目标未修改: {target}: {exc}") from exc
524
+ entries.append(entry)
525
+ try:
526
+ _write_private_json(journal, {"entries": entries})
527
+ except (OSError, CliError) as exc:
528
+ raise CliError(f"无法持久化全局安装事务日志,目标未修改: {journal}: {exc}") from exc
529
+
530
+
531
+ def _ensure_global_tx_target_replaceable(target: Path) -> None:
532
+ if target.is_symlink() or target.is_file() or not target.exists():
533
+ return
534
+ raise OSError(f"拒绝替换非普通文件的回滚目标: {target}")
535
+
536
+
537
+ def _restore_global_tx_file(snapshot: Path, target: Path) -> None:
538
+ if snapshot.is_symlink() or not snapshot.is_file():
539
+ raise OSError(f"全局回滚快照缺失或不是普通文件: {snapshot}")
540
+ target.parent.mkdir(parents=True, exist_ok=True)
541
+ _assert_no_symlink_components(target.parent)
542
+ _ensure_global_tx_target_replaceable(target)
543
+ descriptor, temporary_name = tempfile.mkstemp(
544
+ dir=str(target.parent), prefix=f".{target.name}.restore-",
545
+ )
546
+ os.close(descriptor)
547
+ temporary = Path(temporary_name)
548
+ try:
549
+ shutil.copy2(snapshot, temporary)
550
+ # replace 操作替换目标符号链接本身,不会向它所指向的引擎文件写入。
551
+ os.replace(temporary, target)
552
+ finally:
553
+ try:
554
+ temporary.unlink(missing_ok=True)
555
+ except OSError:
556
+ pass
557
+
558
+
559
+ def _restore_global_tx_symlink(link: str, target: Path) -> None:
560
+ target.parent.mkdir(parents=True, exist_ok=True)
561
+ _assert_no_symlink_components(target.parent)
562
+ _ensure_global_tx_target_replaceable(target)
563
+ descriptor, temporary_name = tempfile.mkstemp(
564
+ dir=str(target.parent), prefix=f".{target.name}.restore-",
565
+ )
566
+ os.close(descriptor)
567
+ temporary = Path(temporary_name)
568
+ try:
569
+ temporary.unlink()
570
+ os.symlink(link, temporary)
571
+ os.replace(temporary, target)
572
+ finally:
573
+ try:
574
+ temporary.unlink(missing_ok=True)
575
+ except OSError:
576
+ pass
577
+
578
+
579
+ def _restore_global_transaction(staging: Path) -> None:
580
+ """按日志逆序恢复全局入口;无法完整恢复时保留证据并 fail-closed。"""
581
+ journal = _global_tx_journal(staging)
582
+ if not journal.exists() and not journal.is_symlink():
583
+ return
584
+ entries = _read_global_tx_entries(journal)
585
+ failures: list[str] = []
586
+ for entry in reversed(entries):
587
+ target_text = entry.get("path")
588
+ if not isinstance(target_text, str) or not target_text:
589
+ failures.append("日志记录缺少目标路径")
590
+ continue
591
+ target = Path(target_text)
592
+ if not target.is_absolute():
593
+ failures.append(f"日志目标不是绝对路径: {target}")
594
+ continue
595
+ kind = entry.get("kind")
596
+ try:
597
+ _assert_no_symlink_components(target.parent)
598
+ if kind == "dir":
599
+ if not target.is_dir() or target.is_symlink():
600
+ raise OSError(f"原目录状态已变化,无法安全自动恢复: {target}")
601
+ continue
602
+ _ensure_global_tx_target_replaceable(target)
603
+ if kind == "missing":
604
+ if target.is_symlink() or target.is_file():
605
+ target.unlink()
606
+ elif kind == "symlink":
607
+ link = entry.get("link")
608
+ if not isinstance(link, str):
609
+ raise OSError("符号链接快照缺少 link 字符串")
610
+ _restore_global_tx_symlink(link, target)
611
+ elif kind == "file":
612
+ snapshot_text = entry.get("snapshot")
613
+ if not isinstance(snapshot_text, str) or not snapshot_text:
614
+ raise OSError("普通文件快照缺少路径")
615
+ snapshot = Path(snapshot_text)
616
+ if not snapshot.is_absolute() or not snapshot.is_relative_to(staging):
617
+ raise OSError(f"回滚快照越出事务目录: {snapshot}")
618
+ _restore_global_tx_file(snapshot, target)
619
+ else:
620
+ raise OSError(f"未知全局回滚记录类型: {kind!r}")
621
+ except (OSError, CliError, ValueError) as exc:
622
+ failures.append(f"{target}: {exc}")
623
+ if failures:
624
+ raise CliError("全局入口回滚不完整: " + ";".join(failures))
625
+
626
+
627
+ def _atomic_write_global_file_tx(path: Path, content: bytes) -> None:
628
+ """F-L0-03:全局写入的**唯一收口**——写入前登记事务快照,失败时按记录还原。
629
+
630
+ 安装期所有用户级全局写入都必须经由此包装器,避免逐点插桩遗漏。
631
+ """
632
+ _tx_stage_global(Path(path))
633
+ _atomic_write_global_file(path, content)
634
+
635
+
636
+ def _remove_install_snapshot_tree(path: Path) -> None:
637
+ """Remove rollback-owned entries without touching runtime special files."""
638
+ if path.is_symlink() or path.is_file():
639
+ path.unlink()
640
+ return
641
+ if not path.is_dir():
642
+ return
643
+ for child in path.iterdir():
644
+ if _is_special_install_entry(child):
645
+ continue
646
+ _remove_install_snapshot_tree(child)
647
+ try:
648
+ path.rmdir()
649
+ except OSError:
650
+ # A directory containing a preserved socket/FIFO remains host-owned.
651
+ pass
652
+
653
+
654
+ def _restore_agent_install_snapshot(
655
+ root: Path, staging: Path, existed: dict[str, bool],
656
+ ) -> None:
657
+ manifest_path = staging / _AGENT_INSTALL_SNAPSHOT_MANIFEST
658
+ if manifest_path.is_file():
659
+ payload = json.loads(manifest_path.read_text(encoding="utf-8"))
660
+ entries = payload.get("files", []) if isinstance(payload, dict) else []
661
+ for item in reversed(entries):
662
+ if not isinstance(item, dict) or not isinstance(item.get("path"), str):
663
+ continue
664
+ target = root / str(item["path"])
665
+ if not item.get("existed"):
666
+ _remove_agent_snapshot_path(target)
667
+ continue
668
+ kind = item.get("kind")
669
+ if kind == "directory" and target.is_dir() and not target.is_symlink():
670
+ continue
671
+ _remove_agent_snapshot_path(target)
672
+ target.parent.mkdir(parents=True, exist_ok=True)
673
+ if kind == "file":
674
+ shutil.copy2(staging / str(item["path"]), target)
675
+ elif kind == "symlink":
676
+ os.symlink(
677
+ str(item.get("target", "")), target,
678
+ target_is_directory=bool(item.get("target_is_directory")),
679
+ )
680
+ elif kind == "directory":
681
+ target.mkdir(parents=True, exist_ok=True)
682
+
683
+ # Remove only surfaces that did not exist before this transaction.
684
+ # Existing host directories (including HOME/.codex) remain untouched.
685
+ for relative in reversed(tuple(existed)):
686
+ if existed[relative]:
687
+ continue
688
+ _remove_agent_snapshot_path(root / relative)
689
+ return
690
+
691
+ # Compatibility fallback for snapshots created by older in-process callers.
692
+ for relative in tuple(existed):
693
+ target = root / relative
694
+ staged = staging / relative
695
+ if target.is_symlink() or target.is_file():
696
+ target.unlink()
697
+ elif target.is_dir():
698
+ _remove_install_snapshot_tree(target)
699
+ if existed[relative] and staged.exists():
700
+ target.parent.mkdir(parents=True, exist_ok=True)
701
+ if staged.is_dir():
702
+ target.mkdir(parents=True, exist_ok=True)
703
+ shutil.copytree(staged, target, symlinks=True, dirs_exist_ok=True)
704
+ else:
705
+ shutil.copy2(staged, target)
706
+
707
+
708
+ def _remove_agent_snapshot_path(path: Path) -> None:
709
+ """Remove a transaction-owned path without following symlinks."""
710
+ if path.is_symlink() or path.is_file():
711
+ path.unlink()
712
+ elif path.is_dir():
713
+ shutil.rmtree(path)
714
+
715
+
716
+
717
+ def _installed_engine_build_id() -> int:
718
+ """实际安装源(asset_root)metadata 的 build_id(F-RSI-20261110-009)。
719
+
720
+ hosts.json 的 bugx_build_id 必须记录「实际装配的引擎版本」——
721
+ common.get_build_id() 的 bugx_cli.__build_id__ 短路返回的是 **CLI 包**
722
+ 的构建号,与 BUGX_ASSET_ROOT override 后的实际安装源脱钩(实测:
723
+ override 装了仓库 439,hosts.json 却记 CLI 包 430,版本门禁
724
+ recorded vs 引擎 永远错位)。安装源 metadata 是唯一权威。
725
+ """
726
+ try:
727
+ # 仓库版显式导入:agent.py 的 .infra 相对导入在 -m 运行态会解析到
728
+ # site-packages 的 bugx_cli 包(快照视角),必须绕开。
729
+ from interfaces.cli.bugx_cli.infra.engine_installer import global_engine_root as _ger
730
+ meta = _ger() / "metadata.txt"
731
+ if meta.is_file():
732
+ match = re.search(r"build_id:\s*(\d+)", meta.read_text(encoding="utf-8"))
733
+ if match:
734
+ return int(match.group(1))
735
+ except (OSError, ImportError):
736
+ pass
737
+ return get_build_id() or 1
738
+
739
+ def _command_agent_impl(
740
+ args: argparse.Namespace, *, progress: _CliProgress | None = None,
741
+ ) -> int:
742
+ """发现并安装到宿主 AI;不启动宿主,也不执行审计。"""
743
+ root = args.root.resolve()
744
+ command = getattr(args, "agent_command", "install")
745
+ _ensure_core_importable()
746
+ import core.i18n as i18n
747
+ deployment_locale = i18n.resolve_locale().resolved_locale
748
+ if getattr(args, "locale", None):
749
+ norm = i18n.normalize_locale(args.locale)
750
+ if not norm:
751
+ raise CliError(_i18n_exc("common.invalid_locale", f"不支持的 locale: {args.locale};可选:zh-CN, en-US", locale=args.locale))
752
+ deployment_locale = norm
753
+ hosts = discover_hosts(root)
754
+ if command == "discover":
755
+ payload = {"root": str(root), "hosts": hosts, "execution": "none"}
756
+ if args.json:
757
+ print(json.dumps(payload, ensure_ascii=False, indent=2))
758
+ else:
759
+ for item in hosts:
760
+ state = "FOUND" if item["installed"] else "NOT_FOUND"
761
+ executable = item["executable"] or item.get("app_path") or "-"
762
+ print(f"{item['name']}\t{state}\t{executable}\t{item['install_path']}")
763
+ return 0
764
+ if command != "install":
765
+ raise CliError(_i18n_exc("agent.unknown_agent_command", f"未知 Agent 命令: {command}", command=command))
766
+ raw_requested = []
767
+ for item in getattr(args, "agent", []):
768
+ for sub in str(item).split(","):
769
+ sub = sub.strip()
770
+ if sub:
771
+ raw_requested.append(sub)
772
+ requested = list(dict.fromkeys(raw_requested))
773
+ if not requested:
774
+ if args.non_interactive:
775
+ raise CliError(_i18n_exc("agent.non_interactive_agent_required", "非交互安装必须显式提供 --agent opencode/dsh/codex/cline/claude/zcode/workbuddy/pi/chatgpt/qoder/trea/funide"))
776
+ if not sys.stdin.isatty():
777
+ raise CliError(_i18n_exc("agent.non_tty_agent_required", "当前不是交互终端;请显式提供 --agent"))
778
+ requested = _prompt_for_hosts(hosts, root)
779
+ if "all" in requested:
780
+ available_names = [str(item["name"]) for item in hosts if item["installed"]]
781
+ if not available_names and not args.allow_missing:
782
+ raise CliError(_i18n_exc(
783
+ "plugin.no_agent_detected",
784
+ "没有检测到已安装的 AI Agent;请安装 OpenCode/Codex/Claude/ZCode/Pi/ChatGPT,"
785
+ "或显式指定 --agent",
786
+ ))
787
+ if not available_names and args.allow_missing:
788
+ available_names = [str(item["name"]) for item in hosts]
789
+ expanded = []
790
+ for name in requested:
791
+ if name == "all":
792
+ for av in available_names:
793
+ if av not in expanded:
794
+ expanded.append(av)
795
+ else:
796
+ if name not in expanded:
797
+ expanded.append(name)
798
+ requested = expanded
799
+ selected = []
800
+ seen_adapters = set()
801
+ for name in requested:
802
+ try:
803
+ adapter = get_adapter(name)
804
+ except ValueError as exc:
805
+ raise CliError(str(exc)) from exc
806
+ if adapter.name in seen_adapters:
807
+ continue
808
+ seen_adapters.add(adapter.name)
809
+ detected = next(item for item in hosts if item["name"] == adapter.name)
810
+ if not detected["installed"] and not args.allow_missing:
811
+ raise CliError(_i18n_exc("agent.adapter_missing_allow_missing", f"未检测到 {adapter.label};如仍要写入项目入口,请加 --allow-missing", label=adapter.label))
812
+ selected.append(adapter)
813
+ if progress is not None:
814
+ progress.update(10, "已确认安装目标")
815
+
816
+ # Validate an existing host manifest before any resource or runtime writes;
817
+ # a corrupt manifest must never cause a partial installation and then fail.
818
+ existing_record = root / ".bugx" / "hosts.json"
819
+ if existing_record.exists() or existing_record.is_symlink():
820
+ _merge_host_records(existing_record, [])
821
+
822
+ # Validate host catalogs or prerequisites before shared runtime writes so
823
+ # an invalid or conflicting catalog cannot leave a partial install.
824
+ for adapter in selected:
825
+ adapter.pre_validate(root)
826
+ if any(adapter.supports(CAP_PROJECT_MCP_CONFIG) for adapter in selected):
827
+ _preflight_opencode_mcp_config(root)
828
+ if progress is not None:
829
+ progress.update(15, "已完成配置校验")
830
+
831
+ root.mkdir(parents=True, exist_ok=True)
832
+ source = asset_root()
833
+ # DOC-004 Layout 2:项目不再承载可执行 core。旧项目必须显式选择
834
+ # 破坏性迁移;迁移会先转移运行态/项目数据,再把旧 core 移出活动布局。
835
+ removed_legacy_core = _require_global_only_layout(root)
836
+ if progress is not None:
837
+ progress.update(20, "正在安装共享引擎")
838
+ engine = global_engine_root()
839
+ # 版本漂移必须在替换之前采样:_stage_engine 会用当前 CLI 版本重新盖章
840
+ # metadata.txt,安装之后两个版本必然相等,漂移就再也观察不到了。
841
+ prior_engine_version = _read_engine_version(engine)
842
+ # F-RSI-20261110-017:非 force 的降级拒绝(守卫在 _install_engine 内)
843
+ # 不再让整个 install 失败——宿主入口装配与引擎 swap 是两件事,宿主轮
844
+ # 重装入口时全局引擎已比快照源新是常态,跳过 swap 继续装配即可。
845
+ try:
846
+ copied, skipped = _install_engine(source, args.force)
847
+ except CliError as exc:
848
+ if "拒绝降级全局引擎" in str(exc) and not args.force:
849
+ print(f"[bugx] ⚠ {exc}(引擎保持现状,继续装配宿主入口)")
850
+ copied, skipped = 0, 0
851
+ else:
852
+ raise
853
+ # 引擎换血后热重载 i18n:宿主镜像渲染必须读到新 staged locale(防旧词典)
854
+ refresh_i18n_after_engine_swap()
855
+ if progress is not None:
856
+ progress.update(40, "共享引擎安装完成")
857
+ # 引擎没被换掉 ⇔ 版本仍是替换前的那个(_install_engine 可能因「已安装引擎
858
+ # 更新且未 --force」而跳过),此时不能宣称「已回退」。
859
+ _warn_engine_version_drift(
860
+ prior_engine_version,
861
+ replaced=_read_engine_version(engine) != prior_engine_version,
862
+ )
863
+ _ensure_global_cli_symlinks()
864
+
865
+ _layout_module(root).initialize(root, bugx_version=__version__)
866
+ _ensure_project_readme(root, source)
867
+ # The common runtime is intentionally installed once even when the selected
868
+ # host is Codex or Claude; every host entry points to this shared protocol.
869
+ _initialize_lesson_ledger(root, source)
870
+ _initialize_project_knowledge_snapshots(root, source)
871
+ _initialize_life_state(root)
872
+ if progress is not None:
873
+ progress.update(60, "项目运行态初始化完成")
874
+ if removed_legacy_core:
875
+ print(f"[bugx] 已直接删除旧项目引擎入口:{removed_legacy_core}")
876
+ selected_mcp_names = targeted_mcp_names(root)
877
+ optional_mcp_names = selected_mcp_names & {"playwright", "postmcp"}
878
+ provisioned_optional_mcps = provision_targeted_mcp_runtime(root, optional_mcp_names)
879
+ opencode_config_status: str | None = None
880
+ opencode_config_backup: Path | None = None
881
+ host_mcp_configs: dict[str, dict[str, object]] = {}
882
+ dsh_patch_status: str | None = None
883
+ dsh_ui_plugin: dict[str, object] | None = None
884
+ if any(adapter.supports(CAP_PROJECT_MCP_CONFIG) for adapter in selected):
885
+ opencode_config_status, opencode_config_backup = _ensure_opencode_config(
886
+ root, selected=selected_mcp_names,
887
+ )
888
+ if any(adapter.supports(CAP_PROJECT_PATCH_OVERLAY) for adapter in selected):
889
+ dsh_patch_status, dsh_ui_plugin = _ensure_dsh_patch(root)
890
+ installed = []
891
+ host_copied = host_skipped = 0
892
+ pi_extension_copied = pi_extension_skipped = 0
893
+ chatgpt_plugin: dict[str, object] | None = None
894
+ host_backups: list[Path] = []
895
+ zcode_legacy_swept: list[str] = []
896
+ workbuddy_entry_content: str | None = None
897
+ workbuddy_record: dict[str, object] | None = None
898
+ workbuddy_connector: dict[str, object] | None = None
899
+ workbuddy_custom_expert: dict[str, object] | None = None
900
+ project_descriptor = global_engine_root() / "bugx.md"
901
+ for adapter in selected:
902
+ extension_backups: list[Path] = []
903
+ if adapter.entry_mode == ENTRY_PLUGIN_CATALOG:
904
+ chatgpt_plugin = _ensure_chatgpt_plugin(
905
+ root, source, locale=deployment_locale,
906
+ )
907
+ host_copied += int(chatgpt_plugin["copied"])
908
+ host_skipped += int(chatgpt_plugin["skipped"])
909
+ installed.append({
910
+ "name": adapter.name,
911
+ "path": adapter.install_path,
912
+ "kind": adapter.install_kind,
913
+ "components": ["plugin", "skill", "marketplace"],
914
+ "plugin_path": chatgpt_plugin["plugin_path"],
915
+ "marketplace_path": chatgpt_plugin["marketplace_path"],
916
+ "locale": deployment_locale,
917
+ "status": chatgpt_plugin["status"],
918
+ "bugx_build_id": _installed_engine_build_id(),
919
+ "backups": chatgpt_plugin["backups"],
920
+ "files": _records_for_paths(root, [
921
+ root / "plugins" / CHATGPT_PLUGIN_NAME / ".codex-plugin" / "plugin.json",
922
+ root / "plugins" / CHATGPT_PLUGIN_NAME / "assets" / "bugx-avatar-512.png",
923
+ root / "plugins" / CHATGPT_PLUGIN_NAME / "skills" / "bugx" / "SKILL.md",
924
+ ]),
925
+ })
926
+ continue
927
+ if adapter.entry_mode == ENTRY_SKILL_PAYLOAD:
928
+ entry_content = add_locale_marker(
929
+ (pi_skill_root() / "SKILL.md").read_text(encoding="utf-8"),
930
+ deployment_locale,
931
+ )
932
+ elif adapter.entry_mode == ENTRY_SHARED_SYMLINK:
933
+ # 唯一实体原则:入口直接以相对符号链接指向 .bugx 载荷,
934
+ # 不再复制整份协议(历史实体副本在链接函数内备份迁移)。
935
+ _migrate_legacy_opencode_agent_entry(root)
936
+ entry_content = None
937
+ else:
938
+ entry_content = adapter.render(project_descriptor, locale=deployment_locale)
939
+ if entry_content is None:
940
+ copied_count, skipped_count, backup = _link_opencode_agent_entry(root)
941
+ worker_copied, worker_skipped, _ = _link_opencode_worker_entry(root)
942
+ copied_count += worker_copied
943
+ skipped_count += worker_skipped
944
+ elif adapter.entry_mode == ENTRY_USER_REGISTRATION:
945
+ # 0.7.22:主入口收敛为仅用户级注册(storageRoot/agents 全局
946
+ # 注册面)。桌面端 Settings → Subagents 以名字合并各作用域且
947
+ # 项目级同名副本胜出,双写会把用户级条目遮蔽出"用户级"列表;
948
+ # 项目内不再写 .zcode/agents/bugx.md,旧版本遗留副本按模板
949
+ # 比对清扫(内容有出入则保留并如实报告)。
950
+ zcode_swept, sweep_backups = _sweep_legacy_zcode_project_entries(
951
+ root, entry_content,
952
+ )
953
+ zcode_legacy_swept.extend(zcode_swept)
954
+ host_backups.extend(sweep_backups)
955
+ copied_count = skipped_count = 0
956
+ backup = None
957
+ elif adapter.entry_mode == ENTRY_MULTI_PATH:
958
+ copied_count = skipped_count = 0
959
+ backup = None
960
+ for relative in adapter.required_paths:
961
+ copied_item, skipped_item, backup_item = _write_host_entry(
962
+ root, root / relative, entry_content, args.force, adapter.name,
963
+ )
964
+ copied_count += copied_item
965
+ skipped_count += skipped_item
966
+ if backup_item is not None:
967
+ host_backups.append(backup_item)
968
+ workbuddy_entry_content = entry_content
969
+ else:
970
+ copied_count, skipped_count, backup = _write_host_entry(
971
+ root, adapter.target(root), entry_content, args.force, adapter.name,
972
+ )
973
+ if adapter.supports(CAP_WORKSPACE_MIRROR_VARIANTS):
974
+ for extra_dir in (".trae", ".trae-cn"):
975
+ if (root / extra_dir).is_dir():
976
+ m_copied, m_skipped, m_backup = _write_host_entry(
977
+ root, root / extra_dir / "agents" / "bugx.md", entry_content, args.force, adapter.name,
978
+ )
979
+ copied_count += m_copied
980
+ skipped_count += m_skipped
981
+ if m_backup is not None:
982
+ host_backups.append(m_backup)
983
+ for legacy_rel in adapter.legacy_paths:
984
+ # DOC-169:声明式遗留路径清扫(如 codex 旧 .codex/skills);
985
+ # 模板一致才删,用户改动保留。
986
+ _sweep_legacy_skill_entry(root, legacy_rel, entry_content, adapter.name)
987
+ host_copied += copied_count
988
+ host_skipped += skipped_count
989
+ if backup is not None:
990
+ host_backups.append(backup)
991
+ if adapter.supports(CAP_EXTRA_TRACKED_PATHS):
992
+ for rel in adapter.required_paths:
993
+ sub_content = adapter.render_required_entry(
994
+ rel, project_descriptor, locale=deployment_locale,
995
+ )
996
+ if sub_content is not None:
997
+ c, s, b = _write_host_entry(
998
+ root, root / rel, sub_content, args.force, adapter.name,
999
+ )
1000
+ host_copied += c
1001
+ host_skipped += s
1002
+ if b is not None:
1003
+ host_backups.append(b)
1004
+ mirror_root = engine_mirror_root(adapter.name)
1005
+ entry_dir = engine_worker_entry_dir(adapter.name)
1006
+ if (
1007
+ adapter.supports(CAP_WORKSPACE_MIRROR)
1008
+ and mirror_root and entry_dir
1009
+ and (root / mirror_root).is_dir()
1010
+ and rel.startswith(entry_dir + "/")
1011
+ ):
1012
+ roo_rel = f"{mirror_root}/agents/" + rel.removeprefix(entry_dir + "/")
1013
+ _write_host_entry(
1014
+ root, root / roo_rel, sub_content, args.force, adapter.name,
1015
+ )
1016
+ zcode_plugin: dict[str, object] | None = None
1017
+ zcode_registration_warning: str | None = None
1018
+ if adapter.supports(CAP_DISTRIBUTION_PLUGIN):
1019
+ # ZCode 双产物:项目级 agent 入口之外,同时生成可分发的本地
1020
+ # 插件包(.zcode-plugin 清单 + agents 目录),供用户级跨项目启用。
1021
+ zcode_plugin = _ensure_zcode_plugin(root, source, locale=deployment_locale)
1022
+ host_copied += int(zcode_plugin["copied"])
1023
+ host_skipped += int(zcode_plugin["skipped"])
1024
+ host_backups.extend(zcode_plugin["backups"])
1025
+ # 用户级全局注册(0.10.14):插件实体发布到 ~/.bugx/zcode-plugin,
1026
+ # plugins.dirs 只登记用户目录路径;旧的项目内注册(包括指向源码
1027
+ # 仓库的)在本次重写中识别并迁移,避免宿主加载到工作副本。
1028
+ try:
1029
+ from .plugin_zcode import (
1030
+ _upsert_zcode_plugin_dirs,
1031
+ _write_zcode_global_plugin,
1032
+ )
1033
+
1034
+ _write_zcode_global_plugin(root, source, locale=deployment_locale)
1035
+ _upsert_zcode_plugin_dirs(register=None, remove=False)
1036
+ except Exception as exc:
1037
+ zcode_registration_warning = f"{type(exc).__name__}: {exc}"
1038
+ record = {
1039
+ "name": adapter.name,
1040
+ "path": str(adapter.target(root).relative_to(root)),
1041
+ "kind": adapter.install_kind,
1042
+ "components": list(adapter.installed_components),
1043
+ "locale": deployment_locale,
1044
+ "bugx_build_id": _installed_engine_build_id(),
1045
+ }
1046
+ if adapter.supports(CAP_EXTENSION_PAYLOAD):
1047
+ pi_extension_copied, pi_extension_skipped, extension_backups = _copy_pi_extension(
1048
+ root, args.force,
1049
+ )
1050
+ host_backups.extend(extension_backups)
1051
+ record["components"] = ["skill", "extension"]
1052
+ record["extension_path"] = ".pi/extensions/bugx/index.ts"
1053
+ if adapter.supports(CAP_DISTRIBUTION_PLUGIN):
1054
+ # 主入口不再落项目级(见上),组件记录只保留插件镜像;用户级
1055
+ # 注册是全局层产物,不在项目 hosts.json 记录内(卸载保留并
1056
+ # 报告,全局清理走 uninstall --self)。
1057
+ record["components"] = ["plugin"]
1058
+ record["path"] = str(zcode_plugin["manifest_path"])
1059
+ if zcode_registration_warning:
1060
+ record["registration_warning"] = zcode_registration_warning
1061
+ if backup is not None or (
1062
+ adapter.supports(CAP_EXTENSION_PAYLOAD) and extension_backups
1063
+ ):
1064
+ record["backups"] = [
1065
+ str(path.relative_to(root)) for path in host_backups
1066
+ if path.parent.name == adapter.name
1067
+ ]
1068
+ tracked_paths = (
1069
+ [] if adapter.entry_mode == ENTRY_USER_REGISTRATION else [adapter.target(root)]
1070
+ )
1071
+ if adapter.entry_mode == ENTRY_MULTI_PATH:
1072
+ tracked_paths = [root / relative for relative in adapter.required_paths]
1073
+ if adapter.entry_mode == ENTRY_SHARED_SYMLINK:
1074
+ record["entry_symlink"] = adapter.install_path
1075
+ if adapter.supports(CAP_EXTRA_TRACKED_PATHS):
1076
+ tracked_paths.extend(root / value for value in adapter.required_paths)
1077
+ mirror_root = engine_mirror_root(adapter.name)
1078
+ entry_dir = engine_worker_entry_dir(adapter.name)
1079
+ if adapter.supports(CAP_WORKSPACE_MIRROR) and mirror_root and (root / mirror_root).is_dir():
1080
+ for value in adapter.required_paths:
1081
+ if entry_dir and value.startswith(entry_dir + "/"):
1082
+ tracked_paths.append(
1083
+ root / (f"{mirror_root}/agents/" + value.removeprefix(entry_dir + "/"))
1084
+ )
1085
+ if adapter.supports(CAP_WORKSPACE_MIRROR_VARIANTS):
1086
+ for extra_dir in (".trae", ".trae-cn"):
1087
+ if (root / extra_dir).is_dir():
1088
+ tracked_paths.append(root / extra_dir / "agents" / "bugx.md")
1089
+ if adapter.supports(CAP_DISTRIBUTION_PLUGIN):
1090
+ # P3:assert 会被 python -O 剥离,改成显式失败路径。
1091
+ if zcode_plugin is None:
1092
+ raise CliError(_i18n_exc("agent.zcode_bundle_missing_result", "zcode 插件包生成失败:缺少插件安装结果,拒绝写入 hosts 记录"))
1093
+ tracked_paths.extend([
1094
+ root / str(zcode_plugin["manifest_path"]),
1095
+ root / str(zcode_plugin["agent_path"]),
1096
+ root / str(zcode_plugin["worker_agent_path"]),
1097
+ ])
1098
+ if adapter.entry_mode == ENTRY_MULTI_PATH:
1099
+ # 用户级 Skill 是全局层产物(与 zcode 用户级 agents 同语义),
1100
+ # 跨项目共享,不进入项目哈希清单;卸载只在模板比对一致时删除。
1101
+ workbuddy_record = record
1102
+ record["files"] = _records_for_paths(root, tracked_paths)
1103
+ installed.append(record)
1104
+ if progress is not None:
1105
+ progress.update(78, "宿主入口安装完成")
1106
+ # Cline and ZCode do not consume OpenCode's project configuration. Write
1107
+ # their native project/workspace MCP containers only after project
1108
+ # entries/plugins have succeeded. MCP configuration stays in the project.
1109
+ host_mcp_changes: list[tuple[Path, Path | None, bool]] = []
1110
+
1111
+
1112
+
1113
+ #: 用户级注册结果按宿主名归档(报告键由宿主名派生,不再逐个写变量)。
1114
+ user_agents_by_host: dict[str, dict[str, object]] = {}
1115
+
1116
+ workbuddy_user_skill: dict[str, object] | None = None
1117
+ opencode_user_skill: dict[str, object] | None = None
1118
+ # 需要宿主原生 MCP 容器的宿主按注册表顺序处理,保证写入与回滚顺序稳定。
1119
+ selected_names = {adapter.name for adapter in selected}
1120
+ native_mcp_adapters = [
1121
+ adapter for adapter in HOST_ADAPTERS
1122
+ if adapter.supports(CAP_NATIVE_MCP_CONFIG) and adapter.name in selected_names
1123
+ ]
1124
+ try:
1125
+ for adapter in native_mcp_adapters:
1126
+ config_hosts = (adapter.name, "codebuddy") if adapter.entry_mode == ENTRY_MULTI_PATH else (adapter.name,)
1127
+ config_paths: list[str] = []
1128
+ status = "unchanged"
1129
+ path = root / ".bugx" / "state" / "unused"
1130
+ backup = None
1131
+ # ZCode 的 MCP 注册是用户级全局单例(绝对 --root 指向单个项目);
1132
+ # 重写前采样既有绑定,切换挖掘项目时输出明确的切换提示。
1133
+ previous_bound_root = (
1134
+ _zcode_bound_project_root()
1135
+ if adapter.name == HOST_NAME_ZCODE else None
1136
+ )
1137
+ for config_host in config_hosts:
1138
+ item_status, path, backup, created = write_host_mcp_config(
1139
+ root, config_host, optional_names=provisioned_optional_mcps,
1140
+ )
1141
+ config_paths.append(str(path))
1142
+ if item_status != "unchanged":
1143
+ status = item_status
1144
+ host_mcp_changes.append((path, backup, created))
1145
+ if backup is not None:
1146
+ host_backups.append(backup)
1147
+ host_info: dict[str, object] = {
1148
+ "status": status,
1149
+ "path": str(path),
1150
+ "paths": config_paths,
1151
+ "backup": str(backup) if backup is not None else None,
1152
+ "session_restart_required": status != "unchanged",
1153
+ }
1154
+ if (
1155
+ adapter.name == HOST_NAME_ZCODE
1156
+ and status != "unchanged"
1157
+ and previous_bound_root is not None
1158
+ and previous_bound_root != root
1159
+ ):
1160
+ host_info["root_switch"] = {
1161
+ "from": str(previous_bound_root),
1162
+ "to": str(root),
1163
+ }
1164
+ host_mcp_configs[adapter.name] = host_info
1165
+ if adapter.supports(CAP_USER_AGENT_REGISTRATION):
1166
+ # User-level agent registrations share the install transaction;
1167
+ # MCP files remain scoped to this project.
1168
+ registered_user_agents = adapter.ensure_user_agents(
1169
+ root, source, locale=deployment_locale,
1170
+ )
1171
+ if registered_user_agents is not None:
1172
+ user_agents_by_host[adapter.name] = registered_user_agents
1173
+ if adapter.name == HOST_NAME_ZCODE:
1174
+ # ZCode 专属:用户级使用手册 Skill 与 agents 同事务部署
1175
+ # (全局层,跨项目可见;内容随 wheel 版本演进)。
1176
+ zcode_user_skill = _ensure_zcode_user_skill(root, source)
1177
+ user_agents_by_host[adapter.name]["user_skill"] = (
1178
+ zcode_user_skill
1179
+ )
1180
+ for item in zcode_user_skill["written"]:
1181
+ if item["status"] == "unchanged":
1182
+ continue
1183
+ host_mcp_changes.append((
1184
+ Path(str(item["path"])),
1185
+ Path(str(item["backup"])) if item["backup"] else None,
1186
+ bool(item["created"]),
1187
+ ))
1188
+ host_backups.extend(zcode_user_skill["backups"])
1189
+ for item in registered_user_agents["written"]:
1190
+
1191
+ if item["status"] == "unchanged":
1192
+ continue
1193
+ host_mcp_changes.append((
1194
+ Path(str(item["path"])),
1195
+ Path(str(item["backup"])) if item["backup"] else None,
1196
+ bool(item["created"]),
1197
+ ))
1198
+ host_backups.extend(registered_user_agents["backups"])
1199
+ for adapter in selected:
1200
+ if adapter.supports(CAP_GLOBAL_AGENT_LINK):
1201
+ # global-agent-link 宿主(现仅 opencode):用户级使用手册 Skill
1202
+ # 与 agents 全局软链同事务部署(~/.config/opencode/skills/,
1203
+ # 跨项目可见)。不挂在 CAP_USER_AGENT_REGISTRATION 块内——
1204
+ # 该宿主 capabilities 不含该标签,挂在里面永不执行(实测踩坑);
1205
+ # 分支用能力查询,遵守 DES-14 宿主字面量守护。
1206
+ # 回执经顶层 opencode_user_skill 专键承载(与 workbuddy_user_skill
1207
+ # 同形态);不挂 user_agents_by_host——该结构供统一汇报循环遍历
1208
+ # written,塞入 {"user_skill": …} 会 KeyError(实测踩坑)。
1209
+ opencode_user_skill = _ensure_opencode_user_skill(
1210
+ root, source, backup_label=adapter.name,
1211
+ )
1212
+ for item in opencode_user_skill["written"]:
1213
+ if item["status"] == "unchanged":
1214
+ host_skipped += 1
1215
+ continue
1216
+ host_copied += 1
1217
+ host_mcp_changes.append((
1218
+ Path(str(item["path"])),
1219
+ Path(str(item["backup"])) if item["backup"] else None,
1220
+ bool(item["created"]),
1221
+ ))
1222
+ host_backups.extend(opencode_user_skill["backups"])
1223
+ if any(adapter.supports(CAP_USER_LEVEL_ARTIFACT) for adapter in selected):
1224
+ # 默认用户级履约:WorkBuddy 桌面端从 <configDir>/skills 发现
1225
+ # 用户级 Skill,任何项目的会话都能看到 BugX;项目级双入口
1226
+ # 仍保留。全局层写入与 zcode 用户级 agents 同一事务回滚。
1227
+ workbuddy_user_skill = _ensure_workbuddy_user_skill(
1228
+ root, workbuddy_entry_content or "",
1229
+ )
1230
+ for item in workbuddy_user_skill["written"]:
1231
+ if item["status"] == "unchanged":
1232
+ host_skipped += 1
1233
+ continue
1234
+ host_copied += 1
1235
+ host_mcp_changes.append((
1236
+ Path(str(item["path"])),
1237
+ Path(str(item["backup"])) if item["backup"] else None,
1238
+ bool(item["created"]),
1239
+ ))
1240
+ host_backups.extend(workbuddy_user_skill["backups"])
1241
+ workbuddy_connector = _ensure_workbuddy_connector(
1242
+ root, workbuddy_entry_content or "",
1243
+ )
1244
+ for item in workbuddy_connector["written"]:
1245
+ if item["status"] == "unchanged":
1246
+ host_skipped += 1
1247
+ continue
1248
+ host_copied += 1
1249
+ host_mcp_changes.append((
1250
+ Path(str(item["path"])),
1251
+ Path(str(item["backup"])) if item["backup"] else None,
1252
+ bool(item["created"]),
1253
+ ))
1254
+ host_backups.extend(workbuddy_connector["backups"])
1255
+ workbuddy_custom_expert = _ensure_workbuddy_custom_expert(
1256
+ root, workbuddy_entry_content or "",
1257
+ )
1258
+ for item in workbuddy_custom_expert["written"]:
1259
+ if item["status"] == "unchanged":
1260
+ host_skipped += 1
1261
+ continue
1262
+ host_copied += 1
1263
+ host_mcp_changes.append((
1264
+ Path(str(item["path"])),
1265
+ Path(str(item["backup"])) if item["backup"] else None,
1266
+ bool(item["created"]),
1267
+ ))
1268
+ host_backups.extend(workbuddy_custom_expert["backups"])
1269
+ for cfg_root in _workbuddy_config_roots():
1270
+ if cfg_root.is_dir():
1271
+ if cfg_root != workbuddy_user_skill_root():
1272
+ _ensure_workbuddy_custom_expert(root, workbuddy_entry_content or "", config_root=cfg_root)
1273
+ if workbuddy_record is not None:
1274
+ written_paths = [
1275
+ str(item["path"]) for item in workbuddy_user_skill["written"]
1276
+ ]
1277
+ if written_paths:
1278
+ workbuddy_record["user_skill"] = written_paths[0]
1279
+ workbuddy_record["connector_package"] = str(
1280
+ workbuddy_connector["root"]
1281
+ )
1282
+ workbuddy_record["custom_expert"] = str(
1283
+ workbuddy_custom_expert["root"]
1284
+ )
1285
+ workbuddy_record["components"] = ["skill", "connector"]
1286
+ workbuddy_record["files"] = _records_for_paths(
1287
+ root,
1288
+ [root / relative for relative in WORKBUDDY_PROJECT_PATHS]
1289
+ + [Path(str(path)) for path in workbuddy_connector["paths"]],
1290
+ )
1291
+ # DOC-181 方案 1:自动探测并同步 WorkBuddy 私有 Python 虚拟环境
1292
+ workbuddy_venv_synced, workbuddy_venv_msg = _sync_workbuddy_private_venv(
1293
+ source, target_version=__version__,
1294
+ )
1295
+ if workbuddy_record is not None:
1296
+ workbuddy_record["private_venv_synced"] = workbuddy_venv_synced
1297
+ workbuddy_record["private_venv_message"] = workbuddy_venv_msg
1298
+ except BaseException:
1299
+ for path, backup, created in reversed(host_mcp_changes):
1300
+ _restore_host_mcp_config_change(path, backup, created)
1301
+ raise
1302
+ opencode_global: dict | None = None
1303
+ if any(adapter.supports(CAP_GLOBAL_AGENT_LINK) for adapter in selected):
1304
+ # 0.5.38(DOC-004):agent 入口回到全局注册——入口指向全局引擎
1305
+ # 资源,任何项目目录下启动 OpenCode 均可发现 @bugx。
1306
+ # 运行态(pollings/知识库/报告)仍按项目隔离;不再清理全局链接。
1307
+ global_copied, global_backups = _register_global_opencode_agent(root)
1308
+ opencode_global = {"agents_dir": str(_global_opencode_agents_dir())}
1309
+ if global_backups:
1310
+ opencode_global["backups"] = [str(path) for path in global_backups]
1311
+ if any(adapter.supports(CAP_GLOBAL_SKILL_LINK) for adapter in selected):
1312
+ _link_global_pi_skill(root, locale=deployment_locale)
1313
+ _self_check_pi_skill_registered(root)
1314
+ if progress is not None:
1315
+ progress.update(90, "宿主配置同步完成")
1316
+ record_dir = root / ".bugx"
1317
+ record_dir.mkdir(parents=True, exist_ok=True)
1318
+ record = record_dir / "hosts.json"
1319
+ merged_hosts = _merge_host_records(record, installed)
1320
+ _write_private_json(record, {
1321
+ "schema_version": 1,
1322
+ "bugx_version": __version__,
1323
+ "bugx_build_id": _installed_engine_build_id(),
1324
+ "engine_bundle_sha256": _engine_manifest_payload(
1325
+ __version__, _engine_file_manifest(engine),
1326
+ )["bundle_sha256"],
1327
+ "installed": merged_hosts,
1328
+ # Layout 2 has no project copy to record or uninstall. The executable
1329
+ # shared runtime is validated independently at global_engine_root().
1330
+ "shared_files": [],
1331
+ "shared_runtime": "global-engine",
1332
+ "execution": "delegated-to-host",
1333
+ "complete_bundles": True,
1334
+ })
1335
+ if progress is not None:
1336
+ progress.update(98, "安装记录已写入")
1337
+ progress.finish()
1338
+ mcp_recommendations = _mcp_recommendations(root)
1339
+ payload = {
1340
+ "status": "INSTALLED", "root": str(root),
1341
+ "hosts": installed, "shared_copied": copied, "shared_skipped": skipped,
1342
+ "host_copied": host_copied, "host_skipped": host_skipped,
1343
+ "extension_copied": pi_extension_copied,
1344
+ "extension_skipped": pi_extension_skipped,
1345
+ "host_backups": [str(path.relative_to(root)) for path in host_backups],
1346
+ "opencode_config": opencode_config_status,
1347
+ "opencode_session_restart_required": opencode_config_status in {
1348
+ "created", "merged",
1349
+ },
1350
+ "opencode_config_backup": (
1351
+ str(opencode_config_backup.relative_to(root))
1352
+ if opencode_config_backup is not None else None
1353
+ ),
1354
+ "host_mcp_configs": host_mcp_configs,
1355
+ **{
1356
+ f"{host_name}_user_agents": payload
1357
+ for host_name, payload in user_agents_by_host.items()
1358
+ },
1359
+ "zcode_legacy_swept": zcode_legacy_swept,
1360
+ "workbuddy_user_skill": workbuddy_user_skill,
1361
+ "opencode_user_skill": opencode_user_skill,
1362
+
1363
+ "workbuddy_connector": workbuddy_connector,
1364
+ "workbuddy_custom_expert": workbuddy_custom_expert,
1365
+ "dsh_ui_plugin": dsh_ui_plugin,
1366
+ "chatgpt_plugin": chatgpt_plugin,
1367
+ "opencode_global": opencode_global,
1368
+ "execution": "none",
1369
+ "mcp_recommendations": mcp_recommendations,
1370
+ }
1371
+ if args.json:
1372
+ print(json.dumps(payload, ensure_ascii=False, indent=2, default=_json_default))
1373
+ else:
1374
+ names = ", ".join(item["name"] for item in installed)
1375
+ print(f"[bugx] 已安装到 {names};CLI 未启动任何 AI Agent")
1376
+ print(f" 共享协议:写入 {copied},保留 {skipped}")
1377
+ print(f" 宿主入口:写入 {host_copied},保留 {host_skipped}")
1378
+ if pi_extension_copied or pi_extension_skipped:
1379
+ print(
1380
+ f" Pi 完整适配包:写入 {pi_extension_copied},"
1381
+ f"保留 {pi_extension_skipped}"
1382
+ )
1383
+ if chatgpt_plugin is not None:
1384
+ print(
1385
+ f" ChatGPT Plugin:{chatgpt_plugin['status']};"
1386
+ f"写入 {chatgpt_plugin['copied']},保留 {chatgpt_plugin['skipped']}"
1387
+ )
1388
+ cleanup = chatgpt_plugin.get("legacy_cleanup")
1389
+ if isinstance(cleanup, dict) and cleanup.get("removed"):
1390
+ removed = ", ".join(str(item) for item in cleanup["removed"])
1391
+ print(f" 已迁移旧 BugX Marketplace:{removed}")
1392
+ if chatgpt_plugin.get("registration_warning"):
1393
+ print(f" 注意:{chatgpt_plugin['registration_warning']}")
1394
+ if chatgpt_plugin.get("shared_skill_warning"):
1395
+ print(f" 注意:{chatgpt_plugin['shared_skill_warning']}")
1396
+ print(f" 下一步:{chatgpt_plugin['next_step']}")
1397
+ if opencode_config_status == "created":
1398
+ print(
1399
+ f" OpenCode 配置:创建 {CONFIG_NAME}"
1400
+ "(外部 MCP 统一经由离线 runtime launcher 启动)"
1401
+ )
1402
+ elif opencode_config_status == "merged":
1403
+ print(
1404
+ f" OpenCode 配置:已备份并补齐 MCP 到离线 runtime launcher(备份:"
1405
+ f"{opencode_config_backup.relative_to(root)})"
1406
+ )
1407
+ elif opencode_config_status == "unchanged":
1408
+ print(" OpenCode 配置:已是离线 runtime launcher 版本,保持不变")
1409
+ for native_adapter in native_mcp_adapters:
1410
+ host_name = native_adapter.name
1411
+ info = host_mcp_configs.get(host_name)
1412
+ if not info:
1413
+ continue
1414
+ status = str(info["status"])
1415
+ path = str(info["path"])
1416
+ if status == "created":
1417
+ print(f" {host_name} MCP 配置:已创建 {path}(host/worker 双通道)")
1418
+ elif status == "unchanged":
1419
+ print(f" {host_name} MCP 配置:已是最新双通道配置,保持不变({path})")
1420
+ else:
1421
+ print(f" {host_name} MCP 配置:已备份并{status}双通道({path})")
1422
+ switched = info.get("root_switch")
1423
+ if isinstance(switched, dict):
1424
+ print(
1425
+ f" 已切换项目根:{switched.get('from')} → "
1426
+ f"{switched.get('to')}(重启宿主会话生效)"
1427
+ )
1428
+ reported_user_agents: set[str] = set()
1429
+ for item in installed:
1430
+ warning = item.get("registration_warning")
1431
+ if warning:
1432
+ print(f" 注意:{item['name']} 用户级插件注册失败:{warning}")
1433
+ if (zcode_user_agents := user_agents_by_host.get(HOST_NAME_ZCODE)) is not None:
1434
+ reported_user_agents.add(HOST_NAME_ZCODE)
1435
+ changed = [
1436
+ item for item in zcode_user_agents["written"]
1437
+ if item["status"] != "unchanged"
1438
+ ]
1439
+ if changed:
1440
+ names = "、".join(Path(str(item["path"])).name for item in changed)
1441
+ print(
1442
+ f" ZCode 用户级子智能体:已写入 {names}"
1443
+ f"({zcode_user_agents['dir']},Settings → Subagents 可见)"
1444
+ )
1445
+ else:
1446
+ print(
1447
+ f" ZCode 用户级子智能体:已是最新,保持不变"
1448
+ f"({zcode_user_agents['dir']})"
1449
+ )
1450
+ zcode_user_skill = zcode_user_agents.get("user_skill")
1451
+ if isinstance(zcode_user_skill, dict):
1452
+ skill_changed = [
1453
+ item for item in zcode_user_skill["written"]
1454
+ if item["status"] != "unchanged"
1455
+ ]
1456
+ if skill_changed:
1457
+ print(
1458
+ f" ZCode 用户级 Skill(bugx-zcode 使用手册):已部署"
1459
+ f"({zcode_user_skill['dir']},新环境即获全部实战流程)"
1460
+ )
1461
+ else:
1462
+ print(
1463
+ f" ZCode 用户级 Skill:已是最新,保持不变"
1464
+ f"({zcode_user_skill['dir']})"
1465
+ )
1466
+ if (claude_user_agents := user_agents_by_host.get(HOST_NAME_CLAUDE)) is not None:
1467
+ reported_user_agents.add(HOST_NAME_CLAUDE)
1468
+ agents_dir_str = str(claude_user_agents["dir"])
1469
+ changed = [
1470
+ item for item in claude_user_agents["written"]
1471
+ if item["status"] != "unchanged"
1472
+ and str(item["path"]).startswith(agents_dir_str)
1473
+ ]
1474
+ if changed:
1475
+ names = "、".join(Path(str(item["path"])).name for item in changed)
1476
+ print(
1477
+ f" Claude Code 用户级智能体:已写入 {names}"
1478
+ f"({claude_user_agents['dir']},全局 claude 可见)"
1479
+ )
1480
+ else:
1481
+ print(
1482
+ f" Claude Code 用户级智能体:已是最新,保持不变"
1483
+ f"({claude_user_agents['dir']})"
1484
+ )
1485
+ skills_res = claude_user_agents.get("skills")
1486
+ if isinstance(skills_res, dict) and skills_res.get("user"):
1487
+ print(f" Claude 用户级 Skill:已配置({skills_res['user']})")
1488
+ host_manual = skills_res.get("host_manual") if isinstance(skills_res, dict) else None
1489
+ if isinstance(host_manual, dict):
1490
+ skill_changed = [
1491
+ item for item in host_manual.get("written", ())
1492
+ if item["status"] != "unchanged"
1493
+ ]
1494
+ if skill_changed:
1495
+ print(
1496
+ " Claude 用户级 Skill(bugx-claude 使用手册):已部署"
1497
+ f"({host_manual['dir']},含强制阅读清单与实证坑位)"
1498
+ )
1499
+ else:
1500
+ print(
1501
+ " Claude 用户级 Skill(bugx-claude 使用手册):已是最新,保持不变"
1502
+ f"({host_manual['dir']})"
1503
+ )
1504
+ packages_res = claude_user_agents.get("packages")
1505
+ if isinstance(packages_res, dict) and packages_res.get("dist"):
1506
+ print(f" Claude Desktop 独立安装包:已生成 bugx.plugin 与 bugx.skill({packages_res['dist']})")
1507
+ plugins_res = claude_user_agents.get("plugins")
1508
+ if isinstance(plugins_res, dict) and plugins_res.get("registered"):
1509
+ print(f" Claude Desktop 插件系统:已就绪并启用 bugx@bugx(版本 {__version__})")
1510
+ if (qoder_user_agents := user_agents_by_host.get(HOST_NAME_QODER)) is not None:
1511
+ reported_user_agents.add(HOST_NAME_QODER)
1512
+ changed = [
1513
+ item for item in qoder_user_agents["written"]
1514
+ if item["status"] != "unchanged"
1515
+ ]
1516
+ if changed:
1517
+ names = "、".join(Path(str(item["path"])).name for item in changed)
1518
+ print(
1519
+ f" Qoder 用户级资产:已写入 {names}"
1520
+ f"({qoder_user_agents['dir']},全局 Qoder 可见)"
1521
+ )
1522
+ else:
1523
+ print(
1524
+ f" Qoder 用户级资产:已是最新,保持不变"
1525
+ f"({qoder_user_agents['dir']})"
1526
+ )
1527
+ # 其余宿主的用户级注册结果统一汇报(标签来自插件/组件表,不写宿主名)。
1528
+ for host_name, payload in user_agents_by_host.items():
1529
+ if host_name in reported_user_agents:
1530
+ continue
1531
+ label = engine_host_label(host_name)
1532
+ changed = [
1533
+ item for item in payload["written"]
1534
+ if item["status"] != "unchanged"
1535
+ ]
1536
+ if changed:
1537
+ names = "、".join(Path(str(item["path"])).name for item in changed)
1538
+ print(
1539
+ f" {label} 用户级智能体:已写入 {names}"
1540
+ f"({payload['dir']},{_user_agent_visibility(host_name)})"
1541
+ )
1542
+ else:
1543
+ print(
1544
+ f" {label} 用户级智能体:已是最新,保持不变"
1545
+ f"({payload['dir']})"
1546
+ )
1547
+
1548
+ if zcode_legacy_swept:
1549
+ print(
1550
+ " ZCode 项目级遗留副本:已按模板比对清扫 "
1551
+ + "、".join(zcode_legacy_swept)
1552
+ + "(子智能体改为仅用户级注册,避免同名遮蔽 Settings 用户级列表)"
1553
+ )
1554
+ if workbuddy_user_skill is not None:
1555
+ changed = [
1556
+ item for item in workbuddy_user_skill["written"]
1557
+ if item["status"] != "unchanged"
1558
+ ]
1559
+ if changed:
1560
+ print(
1561
+ f" WorkBuddy 用户级 Skill:已写入 {workbuddy_user_skill['root']}"
1562
+ "/skills/bugx/SKILL.md(所有项目的会话均可发现)"
1563
+ )
1564
+ else:
1565
+ print(
1566
+ f" WorkBuddy 用户级 Skill:已是最新,保持不变"
1567
+ f"({workbuddy_user_skill['root']}/skills/bugx/SKILL.md)"
1568
+ )
1569
+ if workbuddy_connector is not None:
1570
+ print(
1571
+ f" WorkBuddy Connector:已生成 {workbuddy_connector['root']}"
1572
+ f"(含 icon.png;交付类型 skill-only)"
1573
+ )
1574
+ if workbuddy_custom_expert is not None:
1575
+ print(
1576
+ f" WorkBuddy 自定义专家:已注册 {workbuddy_custom_expert['root']}"
1577
+ "(在专家中心可见)"
1578
+ )
1579
+ if workbuddy_record and workbuddy_record.get("private_venv_synced"):
1580
+ print(f" WorkBuddy 私有运行态:{workbuddy_record.get('private_venv_message')}")
1581
+ if dsh_ui_plugin is not None:
1582
+ status = str(dsh_ui_plugin["status"])
1583
+ if status == "registered":
1584
+ print(
1585
+ f" DSH UI 插件:已注册到 web profile({dsh_ui_plugin['root']})"
1586
+ )
1587
+ else:
1588
+ print(
1589
+ f" DSH UI 插件:已暂存 {dsh_ui_plugin['root']}({dsh_ui_plugin['detail']})"
1590
+ )
1591
+ print(" DSH Web 启动:dsh web(按当前 Session 工作区自动绑定;未选目录会明确提示)")
1592
+ if opencode_config_status in {"created", "merged"}:
1593
+ print(" ⚠ OpenCode MCP 配置已变化;现有会话通常不会热加载。启动 BugX 时会先主动探活,"
1594
+ "探活未命中时再提示重启 OpenCode 会话")
1595
+ _print_mcp_recommendations(mcp_recommendations)
1596
+ return 0
1597
+
1598
+
1599
+
1600
+ def _initialize_life_state(root: Path, *, identity_root: Path | None = None) -> bool:
1601
+ """Create the canonical first-run life state without copying maintainer runtime data."""
1602
+ layout = _layout_module(root)
1603
+ active = layout.require(root)
1604
+ life = active.life
1605
+ if life.is_file():
1606
+ return False
1607
+ verifier = _script(root, "verify_life.py")
1608
+ try:
1609
+ process = subprocess.run(
1610
+ [sys.executable, str(verifier), "reset"], cwd=root,
1611
+ capture_output=True, text=True, check=False, timeout=30,
1612
+ env=_python_environment({
1613
+ "BUGX_PROJECT_ROOT": str(root.resolve()),
1614
+ **({"BUGX_IDENTITY_ROOT": str(Path(identity_root).resolve())} if identity_root else {}),
1615
+ }),
1616
+ )
1617
+ except (OSError, subprocess.TimeoutExpired) as exc:
1618
+ raise CliError(_i18n_exc("agent.life_state_init_failed", f"初始化寿命状态失败: {exc}", exc=exc)) from exc
1619
+ if process.returncode != 0 or not life.is_file():
1620
+ detail = (process.stderr or process.stdout).strip()[:500]
1621
+ raise CliError(_i18n_exc("agent.life_state_file_missing", f"初始化寿命状态失败: {detail or 'verify_life 未生成状态文件'}", detail=detail or 'verify_life 未生成状态文件'))
1622
+ try:
1623
+ payload = json.loads(life.read_text(encoding="utf-8"))
1624
+ except (OSError, json.JSONDecodeError) as exc:
1625
+ raise CliError(_i18n_exc("agent.life_state_file_invalid", f"初始化寿命状态失败:生成文件无效: {exc}", exc=exc)) from exc
1626
+ expected = {
1627
+ "life": 1, "found_total": 0, "round": 1,
1628
+ "rounds_completed": 0, "alive": True, "mode": None, "history": [],
1629
+ }
1630
+ if payload != expected:
1631
+ raise CliError(_i18n_exc("agent.life_state_not_initial", "初始化寿命状态失败:verify_life 生成了非初始状态"))
1632
+ return True
1633
+
1634
+
1635
+ def _backup_opencode_config(root: Path, source: Path) -> Path:
1636
+ """Back up an existing project OpenCode config before changing it."""
1637
+ backup_dir = root.resolve() / ".bugx" / "backups" / "opencode"
1638
+ _assert_no_symlink_components(backup_dir)
1639
+ backup_dir.mkdir(parents=True, exist_ok=True)
1640
+ backup = backup_dir / f"opencode-{time.time_ns()}.json"
1641
+ shutil.copy2(source, backup)
1642
+ backup.chmod(0o600)
1643
+ return backup
1644
+
1645
+
1646
+ # ── DSH 集成实现 ────────────────────────────────────────────────────────────
1647
+ # 本段出现的 "dsh" 字面量是宿主**专属集成实现的数据**(可执行名、npm 包路径、
1648
+ # 用户数据目录名、备份命名空间),不是「按宿主名分派」:这些代码只会在
1649
+ # 已选定 dsh 宿主时执行,没有可参数化的等价能力。安装流程的分派已改为
1650
+ # adapter.supports(...) 能力查询。
1651
+ def _dsh_home() -> Path:
1652
+ configured = os.environ.get("DSH_HOME")
1653
+ return Path(configured).expanduser().resolve() if configured else Path.home().resolve() / ".dsh"
1654
+
1655
+
1656
+ def _all_dsh_homes() -> list[Path]:
1657
+ """Return all detected DSH home roots (CLI ~/.dsh and macOS DSH Desktop harness)."""
1658
+ homes = [_dsh_home()]
1659
+ desktop_harness = Path.home().resolve() / "Library" / "Application Support" / "dsh-desktop" / "harness"
1660
+ if desktop_harness.is_dir() and desktop_harness not in homes:
1661
+ homes.append(desktop_harness)
1662
+ return homes
1663
+
1664
+
1665
+ def _discover_dsh_project_root(start: Path) -> Path | None:
1666
+ """Find the nearest BugX/Git project without treating ``~/.bugx`` as one."""
1667
+ candidate = start.expanduser().resolve()
1668
+ if candidate.is_file():
1669
+ candidate = candidate.parent
1670
+ for directory in (candidate, *candidate.parents):
1671
+ if (directory / ".bugx" / "manifest.json").is_file():
1672
+ return directory
1673
+ if (directory / ".git").exists():
1674
+ return directory
1675
+ return None
1676
+
1677
+
1678
+ def _dsh_project_cwd(root: Path | None) -> Path:
1679
+ """Resolve one absolute workspace for the DSH web process."""
1680
+ configured = os.environ.get("DSH_CWD", "").strip()
1681
+ if configured:
1682
+ candidate = Path(configured).expanduser().resolve()
1683
+ if not candidate.is_dir():
1684
+ raise CliError(f"DSH_CWD 不是可访问目录:{candidate}")
1685
+ return candidate
1686
+
1687
+ if root is not None:
1688
+ candidate = root.expanduser().resolve()
1689
+ if not candidate.is_dir():
1690
+ raise CliError(f"DSH 项目目录不存在:{candidate}")
1691
+ return candidate
1692
+
1693
+ configured_root = os.environ.get("BUGX_PROJECT_ROOT", "").strip()
1694
+ if configured_root:
1695
+ candidate = Path(configured_root).expanduser().resolve()
1696
+ if candidate.is_dir():
1697
+ return candidate
1698
+
1699
+ discovered = _discover_dsh_project_root(Path.cwd())
1700
+ if discovered is not None:
1701
+ return discovered
1702
+ raise CliError(
1703
+ "无法自动确定 DSH 项目根;请在项目目录执行 `bugx dsh`,"
1704
+ "或显式传入 `bugx dsh --root <项目绝对路径>`"
1705
+ )
1706
+
1707
+
1708
+ def command_dsh(args: argparse.Namespace) -> int:
1709
+ """Start DSH with a project-bound ``DSH_CWD``."""
1710
+ dsh = shutil.which("dsh")
1711
+ if not dsh:
1712
+ raise CliError("未找到 dsh 命令,请先安装 DeepSeek Harness")
1713
+ project_cwd = _dsh_project_cwd(getattr(args, "root", None))
1714
+ environment = os.environ.copy()
1715
+ environment["DSH_CWD"] = str(project_cwd)
1716
+ profile = getattr(args, "profile", "web") or "web"
1717
+ dsh_args = list(getattr(args, "dsh_args", []))
1718
+ if dsh_args[:1] == ["--"]:
1719
+ dsh_args.pop(0)
1720
+ command = [dsh, "--profile", profile, *dsh_args]
1721
+ try:
1722
+ result = subprocess.run(command, cwd=project_cwd, env=environment, check=False)
1723
+ if result.returncode != 0:
1724
+ print(
1725
+ "\n[bugx dsh] 提示:若 DSH 因缺失 preset 插件报错(如 @deepseek-ai/dsh-agent-preset),"
1726
+ "可执行 `bugx install --agent dsh --force` 刷新配置,"
1727
+ "或使用 `bugx autonomous` / `bugx install` 连接其它受管 AI 宿主。",
1728
+ file=sys.stderr,
1729
+ )
1730
+ except OSError as exc:
1731
+ raise CliError(f"启动 dsh 失败:{exc}") from exc
1732
+ return int(result.returncode)
1733
+
1734
+
1735
+ def _dsh_standard_preset_candidates() -> list[Path]:
1736
+ """Find the installed DSH preset without assuming a Node version or drive.
1737
+
1738
+ ``DSH_HOME`` is the user data directory, not the DSH package checkout. On
1739
+ Windows the package may be installed under any npm prefix (and ``dsh.cmd``
1740
+ is only a shim), so derive the package from the executable and its shim
1741
+ instead of hard-coding one developer's ``C:``/``D:`` layout.
1742
+ """
1743
+ relative = Path(
1744
+ "config", "agent-presets", "standard", "agent.cordis.yml",
1745
+ )
1746
+ candidates: list[Path] = []
1747
+ seen: set[str] = set()
1748
+
1749
+ def add(path: Path) -> None:
1750
+ key = os.path.normcase(str(path))
1751
+ if key not in seen:
1752
+ seen.add(key)
1753
+ candidates.append(path)
1754
+
1755
+ for env_name in ("DSH_PACKAGE_ROOT", "DSH_INSTALL_ROOT"):
1756
+ configured = os.environ.get(env_name)
1757
+ if configured:
1758
+ add(Path(configured).expanduser() / relative)
1759
+
1760
+ executable = shutil.which("dsh")
1761
+ if executable:
1762
+ executable_path = Path(executable)
1763
+ try:
1764
+ executable_path = executable_path.resolve()
1765
+ except OSError:
1766
+ pass
1767
+ probe_dirs = [executable_path.parent, *executable_path.parents]
1768
+ for directory in probe_dirs:
1769
+ for package_root in (
1770
+ directory / "node_modules" / "@deepseek-ai" / "dsh",
1771
+ directory / "lib" / "node_modules" / "@deepseek-ai" / "dsh",
1772
+ directory / "@deepseek-ai" / "dsh",
1773
+ ):
1774
+ add(package_root / relative)
1775
+
1776
+ # npm on Windows commonly exposes a .cmd/.ps1 shim whose body names
1777
+ # the real package. Reading the shim avoids guessing the npm prefix.
1778
+ try:
1779
+ shim = Path(executable).read_text(encoding="utf-8", errors="ignore")
1780
+ except OSError:
1781
+ shim = ""
1782
+ if shim:
1783
+ pattern = re.compile(
1784
+ r"([A-Za-z]:[\\/][^\"\r\n]*?node_modules[\\/]"
1785
+ r"(?:@deepseek-ai[\\/])?dsh)",
1786
+ re.IGNORECASE,
1787
+ )
1788
+ for raw in pattern.findall(shim):
1789
+ add(Path(raw.replace("\\", os.sep)) / relative)
1790
+
1791
+ for entry in os.environ.get("NODE_PATH", "").split(os.pathsep):
1792
+ if entry.strip():
1793
+ add(Path(entry).expanduser() / "@deepseek-ai" / "dsh" / relative)
1794
+ return candidates
1795
+
1796
+
1797
+ def _deploy_dsh_ui_plugin() -> dict[str, object]:
1798
+ """Install the DSH bundle into the user web profile when it exists.
1799
+
1800
+ ``dsh.client`` modules are discovered from the web profile's bundle list;
1801
+ putting the files in an agent preset alone cannot make a browser sidebar
1802
+ icon appear. A missing web profile is valid for headless-only installs,
1803
+ so the package is staged and reported instead of blocking the agent setup.
1804
+ """
1805
+ source_dir = _integration_dir() / "dsh" / "ui"
1806
+ required = ("package.json", "cordis.patch.yml", "index.js", "client.js")
1807
+ # ``bugx-mcp``(第三方 @bencibro/bugx-dsh-mcp-client 桥)已停用:它把 MCP 的
1808
+ # JSON Schema 当 schemastery spec 编译,实测每次调用抛
1809
+ # ``v3Schema.safeParse is not a function``,且自带 serverName 默认值会与官方
1810
+ # 通道重名。MCP 三条通道改由 core/hosts/dsh.py 用官方 client 写 profile patch。
1811
+
1812
+ for name in required:
1813
+ source = source_dir / name
1814
+ if source.is_symlink() or not source.is_file():
1815
+ raise CliError(_i18n_exc(
1816
+ "agent.dsh_ui_resource_missing",
1817
+ f"缺少 DSH UI 适配资源:{source}", source=source,
1818
+ ))
1819
+
1820
+ for home in _all_dsh_homes():
1821
+ plugin_root = home / "plugins" / "bugx-ui"
1822
+ _assert_no_symlink_components(plugin_root)
1823
+ plugin_root.mkdir(parents=True, exist_ok=True)
1824
+ for name in required:
1825
+ _atomic_write_global_file_tx(
1826
+ plugin_root / name, (source_dir / name).read_bytes(),
1827
+ )
1828
+
1829
+
1830
+ plugin_root = _dsh_home() / "plugins" / "bugx-ui"
1831
+ profile_root = _dsh_home() / "profiles" / "web"
1832
+ dsh = shutil.which("dsh")
1833
+ if not dsh or not (profile_root / "package.json").is_file():
1834
+ return {
1835
+ "root": str(plugin_root),
1836
+ "mcp_root": None, # 第三方 MCP bridge 已停用;通道由 profile patch 提供
1837
+ "profile": str(profile_root),
1838
+ "status": "staged",
1839
+ "detail": "未发现可管理的 DSH web profile,保留包供 dsh plugin add 使用",
1840
+ }
1841
+ try:
1842
+ result = subprocess.run(
1843
+ [dsh, "plugin", "--profile", "web", "add", str(plugin_root)],
1844
+ cwd=profile_root,
1845
+ capture_output=True,
1846
+ text=True,
1847
+ check=False,
1848
+ timeout=120,
1849
+ )
1850
+ except (OSError, subprocess.TimeoutExpired) as exc:
1851
+ return {
1852
+ "root": str(plugin_root),
1853
+ "mcp_root": None, # 第三方 MCP bridge 已停用;通道由 profile patch 提供
1854
+ "profile": str(profile_root),
1855
+ "status": "staged",
1856
+ "detail": f"web profile 注册未完成:{exc}",
1857
+ }
1858
+ if result.returncode != 0:
1859
+ detail = (result.stderr or result.stdout or "dsh plugin add 失败").strip()
1860
+ return {
1861
+ "root": str(plugin_root),
1862
+ "mcp_root": None, # 第三方 MCP bridge 已停用;通道由 profile patch 提供
1863
+ "profile": str(profile_root),
1864
+ "status": "staged",
1865
+ "detail": f"web profile 注册未完成:{detail[-500:]}",
1866
+ }
1867
+ for home in _all_dsh_homes():
1868
+ p_manifest = home / "profiles" / "web" / "package.json"
1869
+ if p_manifest.is_file():
1870
+ try:
1871
+ data = json.loads(p_manifest.read_text(encoding="utf-8"))
1872
+ bundles = data.setdefault('dsh', {}).setdefault("profile", {}).setdefault("bundles", [])
1873
+ deps = data.get("dependencies", {})
1874
+ changed = False
1875
+ for pkg_name in ("@bencibro/bugx-dsh-ui", "@bencibro/bugx-dsh-mcp-client"):
1876
+ if pkg_name in deps and pkg_name not in bundles:
1877
+ bundles.append(pkg_name)
1878
+ changed = True
1879
+ if changed:
1880
+ _atomic_write_global_file_tx(
1881
+ p_manifest,
1882
+ (json.dumps(data, indent=2, ensure_ascii=False) + "\n").encode("utf-8"),
1883
+ )
1884
+ except Exception:
1885
+ pass
1886
+ return {
1887
+ "root": str(plugin_root),
1888
+ "mcp_root": None, # 第三方 MCP bridge 已停用;通道由 profile patch 提供
1889
+ "profile": str(profile_root),
1890
+ "status": "registered",
1891
+ "detail": "已由 dsh plugin add 纳入 web profile bundle",
1892
+ }
1893
+
1894
+
1895
+ def _ensure_dsh_patch(root: Path) -> tuple[str, dict[str, object] | None]:
1896
+ """Install or upgrade the BugX integration for DeepSeek Harness (dsh).
1897
+
1898
+ Writes:
1899
+ .dsh/patch.yml — project patch overlay
1900
+ ~/.dsh/.agent-presets/bugx/agent.cordis.yml — preset composition
1901
+ ~/.dsh/.agent-presets/bugx/preset.yml — preset display metadata
1902
+ .dsh/skills/bugx/SKILL.md — skill entry
1903
+ .dsh/agents/bugx.md — agent definition
1904
+
1905
+ The browser UI package is installed separately into the DSH web profile;
1906
+ agent presets do not load ``dsh.client`` modules.
1907
+ """
1908
+ dsh_dir = root.resolve() / ".dsh"
1909
+ dsh_dir.mkdir(parents=True, exist_ok=True)
1910
+
1911
+ patch_path = dsh_dir / "patch.yml"
1912
+ skill_path = dsh_dir / "skills" / "bugx" / "SKILL.md"
1913
+ dsh_skill_path = dsh_dir / "skills" / "bugx-dsh" / "SKILL.md"
1914
+ agent_path = dsh_dir / "agents" / "bugx.md"
1915
+ patched = False
1916
+ any_existing = any(path.exists() for path in (patch_path, skill_path, dsh_skill_path, agent_path))
1917
+
1918
+ # Read bundled templates from integrations/dsh/
1919
+ integration_dir = _integration_dir()
1920
+ bundled_patch = integration_dir / "dsh" / "dsh-patch.yml"
1921
+ bundled_skill = integration_dir / "dsh" / "skills" / "bugx" / "SKILL.md"
1922
+ bundled_dsh_skill = integration_dir / "dsh" / "skills" / "bugx-dsh" / "SKILL.md"
1923
+ bundled_agent = integration_dir / "dsh" / "agents" / "bugx.md"
1924
+
1925
+ for bundled, target in (
1926
+ (bundled_patch, patch_path),
1927
+ (bundled_skill, skill_path),
1928
+ (bundled_dsh_skill, dsh_skill_path),
1929
+ (bundled_agent, agent_path),
1930
+ ):
1931
+ if not bundled.is_file():
1932
+ raise CliError(_i18n_exc("agent.dsh_resource_missing", f"缺少 dsh 适配资源:{bundled}", bundled=bundled))
1933
+ copied, _skipped, _backup = _write_host_resource(
1934
+ root, target, bundled.read_bytes(), "dsh",
1935
+ )
1936
+ patched = patched or bool(copied)
1937
+
1938
+ # 项目 patch 也要带官方 MCP overlay:`bugx doctor` 的「DeepSeek Harness
1939
+ # MCP 配置」扫的是项目 `.dsh/patch.yml` 与全局预设,不是 profile patch。
1940
+ # 只在 profile 层写入会让 install 之后 doctor 仍报「缺少 bugx-supervisor
1941
+ # MCP」——修好调用却报告缺失,是更难排查的破窗。
1942
+ if patch_path.is_file():
1943
+ project_patch = patch_path.read_text(encoding="utf-8")
1944
+ with_overlay = _ensure_official_mcp_overlay(project_patch, root)
1945
+ if with_overlay != project_patch:
1946
+ _atomic_write_global_file_tx(patch_path, with_overlay.encode("utf-8"))
1947
+ patched = True
1948
+
1949
+ # Deploy BugX's agent preset and the browser UI bundle to their native
1950
+ # DSH user-level locations.
1951
+ try:
1952
+ _deploy_dsh_preset(root)
1953
+ ui_plugin = _deploy_dsh_ui_plugin()
1954
+ except (CliError, OSError) as exc:
1955
+ raise CliError(_i18n_exc("agent.dsh_preset_write_failed", f"写入 dsh 全局预设失败:{exc}", exc=exc)) from exc
1956
+
1957
+ if patched:
1958
+ return ("patched", ui_plugin) if any_existing else ("created", ui_plugin)
1959
+ return ("unchanged", ui_plugin)
1960
+
1961
+
1962
+ def _deploy_dsh_preset(root: Path) -> None:
1963
+ """Deploy the BugX preset cleanly to ~/.dsh/.agent-presets/bugx/.
1964
+
1965
+ Reads the installed standard preset, replaces the persona text with BugX's
1966
+ audit persona (without duplicating the fixed id), and appends a unique
1967
+ bugx-supervisor MCP client entry. Duplicate loader entry ids otherwise
1968
+ make dsh reject the preset at session creation.
1969
+ """
1970
+ preset_dir = _dsh_home() / ".agent-presets" / "bugx"
1971
+ preset_dir.mkdir(parents=True, exist_ok=True)
1972
+
1973
+ candidates = _dsh_standard_preset_candidates()
1974
+ standard_preset = next((p for p in candidates if p.is_file()), None)
1975
+
1976
+ composition_path = preset_dir / "agent.cordis.yml"
1977
+ # F-RSI-20261119-011/013/014:插件名与行集合都必须跟随**每个 dsh home
1978
+ # 实际使用的运行时**。CLI dsh 0.1.1-rc.2 只有 worker-thread;DSH Desktop
1979
+ # 0.14+ 随 app.asar 内置 dsh 0.2.2(只认 workflow-ptc,且启动校验会把
1980
+ # worker-thread 判为 blocking 错误)。desktop home 直接使用 Desktop 自带
1981
+ # 的官方 standard preset 模板(dsh-web-app/presets/standard.patch.yml),
1982
+ # CLI home 继续用 CLI dsh 包内模板——两侧都与其运行时自洽。
1983
+ if standard_preset and standard_preset.is_file():
1984
+ lines = standard_preset.read_text(encoding="utf-8").splitlines()
1985
+ out_lines = _apply_bugx_persona(lines)
1986
+ else:
1987
+ # Fallback: minimal viable preset composition when the installed dsh
1988
+ # standard template is not discoverable (e.g. isolated test HOME).
1989
+ out_lines = _apply_bugx_persona([
1990
+ "# BugX minimal preset composition (fallback).",
1991
+ "- id: persona",
1992
+ " name: '@deepseek-ai/dsh-persona'",
1993
+ " config:",
1994
+ " prefix: placeholder",
1995
+ "- id: skill-filesystem",
1996
+ " name: '@deepseek-ai/dsh-skill-filesystem'",
1997
+ ])
1998
+
1999
+ # Native DSH questions are an agent capability, not merely a skill
2000
+ # instruction; the check below runs on the final per-home composition
2001
+ # inside the write loop (Desktop's official template already carries it).
2002
+
2003
+ # 预设层**不再**注入 MCP client。三条通道(supervisor / supervisor-worker /
2004
+ # docs)由 ``core/hosts/dsh.py::_mcp_insert_block`` 以官方
2005
+ # ``@deepseek-ai/dsh-mcp-client`` 统一写到 profile patch 的顶层 ``- insert:``。
2006
+ #
2007
+ # 此处曾硬编码 ``@bencibro/bugx-dsh-mcp-client`` 单通道。它有两个致命问题:
2008
+ # 1. 把 MCP 的 JSON Schema 当成 schemastery spec 交给 dsh-tools 编译,
2009
+ # 实测每次调用都抛 ``v3Schema.safeParse is not a function``——工具在清单
2010
+ # 里看得见、调用必失败;
2011
+ # 2. 自带 ``serverName: bugx-supervisor`` 默认值,与官方通道注册名冲突,
2012
+ # 两套并存时哪个生效取决于加载顺序。
2013
+ # 保留这段死文本会让「删掉 profile 里的坏条目」在下次 install 后复活。
2014
+
2015
+ preset_name = "BugX 深度审计"
2016
+ preset_desc = (
2017
+ "你的自动化代码安全体检专家。深度排查项目中隐藏的逻辑漏洞、鉴权越界与并发隐患,"
2018
+ "不仅找 Bug,更能自动生成复现验证与修复建议。"
2019
+ "适合在项目提测发版前、安全合规体检或排查疑难缺陷时开启;日常开发与普通交流不打扰。"
2020
+ )
2021
+ preset_order = 0
2022
+
2023
+ for home in _all_dsh_homes():
2024
+ preset_plugin, workflow_plugin = _dsh_runtime_plugin_names(home)
2025
+ if "dsh-desktop" in home.parts:
2026
+ # F-RSI-20261119-014:desktop home 使用 Desktop 自带的官方
2027
+ # standard preset 模板——CLI 0.1.1 模板里的 0.1.x 专属行
2028
+ # (tool-ralph、tool-subagent-codex/claude-code/list-agents)在
2029
+ # 0.2.x 官方 preset 中已被移除,其激活在 0.2.x 运行时上会失败,
2030
+ # registry 据此把整个 preset 判为 broken(UI 显示「加载失败」)。
2031
+ desktop_template = _dsh_desktop_standard_template()
2032
+ base_lines = (
2033
+ _apply_bugx_persona(_dsh_desktop_preset_rows(desktop_template))
2034
+ if desktop_template else out_lines
2035
+ )
2036
+ else:
2037
+ base_lines = out_lines
2038
+ composition_lines = _rewrite_dsh_workflow_plugin(base_lines, workflow_plugin)
2039
+ if "@deepseek-ai/dsh-tool-ask-user" not in "\n".join(composition_lines):
2040
+ composition_lines.extend([
2041
+ "",
2042
+ "# ── BugX native question interaction ───────────────────────────────────",
2043
+ "- id: tool-ask-user",
2044
+ " name: '@deepseek-ai/dsh-tool-ask-user'",
2045
+ ])
2046
+ composition_text = "\n".join(composition_lines) + "\n"
2047
+ p_dir = home / ".agent-presets" / "bugx"
2048
+ _assert_no_symlink_components(p_dir)
2049
+ p_dir.mkdir(parents=True, exist_ok=True)
2050
+ _atomic_write_global_file_tx(
2051
+ p_dir / "agent.cordis.yml", composition_text.encode("utf-8"),
2052
+ )
2053
+ _atomic_write_global_file_tx(
2054
+ p_dir / "preset.yml",
2055
+ (
2056
+ f"name: {preset_name}\n"
2057
+ f"description: >-\n"
2058
+ f" {preset_desc}\n"
2059
+ f"order: {preset_order}\n"
2060
+ ).encode("utf-8"),
2061
+ )
2062
+ _sync_dsh_profile_patch(
2063
+ home,
2064
+ preset_id="bugx",
2065
+ composition_text=composition_text,
2066
+ name=preset_name,
2067
+ description=preset_desc.replace("\n", " "),
2068
+ order=preset_order,
2069
+ preset_plugin_name=preset_plugin,
2070
+ root=root,
2071
+ )
2072
+
2073
+
2074
+ _DSH_LEGACY_WORKFLOW_PLUGIN = "@deepseek-ai/dsh-workflow-worker-thread"
2075
+ _DSH_PTC_WORKFLOW_PLUGIN = "@deepseek-ai/dsh-workflow-ptc"
2076
+
2077
+
2078
+ def _dsh_desktop_asar_candidates() -> list[Path]:
2079
+ """Return DSH Desktop ``app.asar`` paths that may carry the bundled runtime."""
2080
+ resources = Path("Contents", "Resources", "app.asar")
2081
+ return [
2082
+ Path.home().resolve() / "Applications" / "DSH Desktop.app" / resources,
2083
+ Path("/Applications") / "DSH Desktop.app" / resources,
2084
+ ]
2085
+
2086
+
2087
+ def _asar_lists_bundled_package(asar: Path, package: str) -> bool:
2088
+ """Check an Electron ``app.asar`` header for ``node_modules/@deepseek-ai/<package>``.
2089
+
2090
+ DSH Desktop bundles its entire dsh runtime inside app.asar instead of the
2091
+ harness profile, so probing the profile's node_modules tells us what the
2092
+ *CLI* installed there, not what the Desktop runtime resolves at launch.
2093
+ Only the asar header is read; file payloads are never touched.
2094
+ """
2095
+ try:
2096
+ with asar.open("rb") as handle:
2097
+ head = handle.read(8)
2098
+ if len(head) < 8:
2099
+ return False
2100
+ header_size = struct.unpack("<I", head[4:8])[0]
2101
+ if header_size <= 0 or header_size > 64 * 1024 * 1024:
2102
+ return False
2103
+ header = handle.read(header_size)
2104
+ except OSError:
2105
+ return False
2106
+ # The asar header is a nested file tree, so the package path never appears
2107
+ # as one contiguous byte string; parse the JSON and walk the "files" maps.
2108
+ start = header.find(b'{"files":')
2109
+ if start < 0:
2110
+ return False
2111
+ try:
2112
+ tree, _ = json.JSONDecoder().raw_decode(
2113
+ header[start:].decode("utf-8", "ignore"),
2114
+ )
2115
+ except (UnicodeDecodeError, json.JSONDecodeError):
2116
+ return False
2117
+ node: Any = tree
2118
+ for part in ("files", "node_modules", "files", "@deepseek-ai", "files", package):
2119
+ if not isinstance(node, dict):
2120
+ return False
2121
+ node = node.get(part)
2122
+ return isinstance(node, dict)
2123
+
2124
+
2125
+ def _dsh_desktop_runtime_names() -> tuple[str, str] | None:
2126
+ """Detect the preset/workflow plugin names DSH Desktop's bundled runtime accepts.
2127
+
2128
+ DSH Desktop 0.14 bundles dsh 0.2.2: ``@deepseek-ai/dsh-agent-preset``
2129
+ (singular) and ``@deepseek-ai/dsh-workflow-ptc``. Older Desktop builds
2130
+ bundled the 0.1.x names (plural preset plugin + worker-thread). The
2131
+ bundled app.asar is the only authoritative source for the desktop home.
2132
+ """
2133
+ for asar in _dsh_desktop_asar_candidates():
2134
+ if not asar.is_file():
2135
+ continue
2136
+ if _asar_lists_bundled_package(asar, "dsh-workflow-ptc"):
2137
+ return ("@deepseek-ai/dsh-agent-preset", _DSH_PTC_WORKFLOW_PLUGIN)
2138
+ if _asar_lists_bundled_package(asar, "dsh-workflow-worker-thread"):
2139
+ return ("@deepseek-ai/dsh-agent-presets", _DSH_LEGACY_WORKFLOW_PLUGIN)
2140
+ return None
2141
+
2142
+
2143
+ def _dsh_runtime_plugin_names(home: Path) -> tuple[str, str]:
2144
+ """Return ``(preset_plugin_name, workflow_plugin_name)`` for one dsh home.
2145
+
2146
+ F-RSI-20261119-012/013:包名随 dsh 版本变化——0.1.1-rc.2 是
2147
+ 复数 ``dsh-agent-presets`` + ``dsh-workflow-worker-thread``;0.2.x 是
2148
+ 单数 ``dsh-agent-preset`` + ``dsh-workflow-ptc``。DSH Desktop 的运行时
2149
+ 内置在 app.asar 中,必须先探测 asar;其余 home 以
2150
+ ``profiles/node_modules`` 为准(那是其插件解析根)。
2151
+ """
2152
+ if "dsh-desktop" in home.parts:
2153
+ detected = _dsh_desktop_runtime_names()
2154
+ if detected is not None:
2155
+ return detected
2156
+ base = home / "profiles" / "node_modules" / "@deepseek-ai"
2157
+ if (base / "dsh-agent-preset").is_dir():
2158
+ preset_plugin = "@deepseek-ai/dsh-agent-preset"
2159
+ else:
2160
+ preset_plugin = "@deepseek-ai/dsh-agent-presets"
2161
+ if (base / "dsh-workflow-ptc").is_dir():
2162
+ workflow_plugin = _DSH_PTC_WORKFLOW_PLUGIN
2163
+ else:
2164
+ workflow_plugin = _DSH_LEGACY_WORKFLOW_PLUGIN
2165
+ return preset_plugin, workflow_plugin
2166
+
2167
+
2168
+ def _rewrite_dsh_workflow_plugin(
2169
+ lines: list[str], workflow_plugin: str,
2170
+ ) -> list[str]:
2171
+ """Rewrite the template's worker-thread row to the home's workflow plugin."""
2172
+ if workflow_plugin == _DSH_LEGACY_WORKFLOW_PLUGIN:
2173
+ return list(lines)
2174
+ out: list[str] = []
2175
+ for line in lines:
2176
+ stripped = line.strip()
2177
+ indent = len(line) - len(line.lstrip())
2178
+ if stripped == "- id: workflow-worker-thread":
2179
+ line = (" " * indent) + "- id: workflow-ptc"
2180
+ elif _DSH_LEGACY_WORKFLOW_PLUGIN in line:
2181
+ line = (" " * indent) + f"name: '{_DSH_PTC_WORKFLOW_PLUGIN}'"
2182
+ out.append(line)
2183
+ return out
2184
+
2185
+
2186
+ _BUGX_PERSONA_TEXT = (
2187
+ "You are BugX, an autonomous adversarial code-audit agent. Before any "
2188
+ "exploration, first run bugx engine path --name bugx-quick.md (the L0 "
2189
+ "protocol card), then consult the global AGENT_GUIDE.md and bugx.md "
2190
+ "sections on demand, and follow the life-ledger, supervisor lease, "
2191
+ "evidence and report protocol. The DSH package checkout and DSH_HOME are "
2192
+ "not the project root; use the active Session cwd for every project path "
2193
+ "and run pwd when paths are ambiguous."
2194
+ )
2195
+
2196
+
2197
+ def _persona_block_lines(indent: str) -> list[str]:
2198
+ """One persona entry with the BugX persona text at ``indent`` (may be empty)."""
2199
+ lines = [
2200
+ f"{indent}- id: persona",
2201
+ f"{indent} name: '@deepseek-ai/dsh-persona'",
2202
+ f"{indent} config:",
2203
+ f"{indent} prefix: >-",
2204
+ ]
2205
+ # Folded scalar (>-): line breaks fold into spaces, so wrapping is cosmetic.
2206
+ words = _BUGX_PERSONA_TEXT.split(" ")
2207
+ row: list[str] = []
2208
+ for word in words:
2209
+ row.append(word)
2210
+ if len(" ".join(row)) >= 96:
2211
+ lines.append(f"{indent} {' '.join(row)}")
2212
+ row = []
2213
+ if row:
2214
+ lines.append(f"{indent} {' '.join(row)}")
2215
+ return lines
2216
+
2217
+
2218
+ def _apply_bugx_persona(lines: list[str]) -> list[str]:
2219
+ """Replace the template's persona entry with BugX's, preserving indentation."""
2220
+ out: list[str] = []
2221
+ i = 0
2222
+ while i < len(lines):
2223
+ line = lines[i]
2224
+ if line.strip() == "- id: persona":
2225
+ indent = " " * (len(line) - len(line.lstrip()))
2226
+ out.extend(_persona_block_lines(indent))
2227
+ # Skip every remaining line of the original persona entry.
2228
+ i += 1
2229
+ while i < len(lines) and not lines[i].strip().startswith("- id:"):
2230
+ i += 1
2231
+ continue
2232
+ out.append(line)
2233
+ i += 1
2234
+ return out
2235
+
2236
+
2237
+ def _asar_read_text(asar: Path, member: str) -> str | None:
2238
+ """Read one UTF-8 file out of an Electron ``app.asar`` by archive path."""
2239
+ try:
2240
+ with asar.open("rb") as handle:
2241
+ head = handle.read(8)
2242
+ if len(head) < 8:
2243
+ return None
2244
+ header_size = struct.unpack("<I", head[4:8])[0]
2245
+ if header_size <= 0 or header_size > 64 * 1024 * 1024:
2246
+ return None
2247
+ header = handle.read(header_size)
2248
+ start = header.find(b'{"files":')
2249
+ if start < 0:
2250
+ return None
2251
+ tree, _ = json.JSONDecoder().raw_decode(
2252
+ header[start:].decode("utf-8", "ignore"),
2253
+ )
2254
+ node: Any = tree
2255
+ for part in member.split("/"):
2256
+ if not isinstance(node, dict):
2257
+ return None
2258
+ node = node.get("files", {}).get(part) if "files" in node else node.get(part)
2259
+ if node is None:
2260
+ return None
2261
+ if not isinstance(node, dict) or "offset" not in node:
2262
+ return None
2263
+ handle.seek(int(node["offset"]) + 8 + header_size)
2264
+ return handle.read(int(node["size"])).decode("utf-8")
2265
+ except (OSError, UnicodeDecodeError, json.JSONDecodeError):
2266
+ return None
2267
+
2268
+
2269
+ _DSH_DESKTOP_STANDARD_PRESET_MEMBER = (
2270
+ "node_modules/@deepseek-ai/dsh-web-app/presets/standard.patch.yml"
2271
+ )
2272
+
2273
+
2274
+ def _dsh_desktop_standard_template() -> str | None:
2275
+ """DSH Desktop 自带的官方 standard preset 组态(0.2.x 行集合)。
2276
+
2277
+ F-RSI-20261119-014:desktop home 的 preset 行集合必须与其内置运行时
2278
+ 同代。CLI dsh 包内模板是 0.1.x 行集合(tool-ralph 等),在 0.2.x 上
2279
+ 激活失败会让 registry 把 preset 判 broken;Desktop 随包分发的
2280
+ ``dsh-web-app/presets/standard.patch.yml`` 是唯一与其运行时自洽的
2281
+ 官方行集合来源。旧版 Desktop 没有该文件时返回 None(回退 CLI 模板)。
2282
+ """
2283
+ for asar in _dsh_desktop_asar_candidates():
2284
+ if not asar.is_file():
2285
+ continue
2286
+ text = _asar_read_text(asar, _DSH_DESKTOP_STANDARD_PRESET_MEMBER)
2287
+ if text:
2288
+ return text
2289
+ return None
2290
+
2291
+
2292
+ def _dsh_desktop_preset_rows(template_text: str) -> list[str]:
2293
+ """Extract the plugin rows under the official template's ``plugins:`` key."""
2294
+ lines = template_text.splitlines()
2295
+ for idx, line in enumerate(lines):
2296
+ if line.strip() == "plugins:":
2297
+ rows = lines[idx + 1:]
2298
+ while rows and not rows[-1].strip():
2299
+ rows.pop()
2300
+ return rows
2301
+ return []
2302
+
2303
+
2304
+ def _format_dsh_preset_patch(
2305
+ preset_id: str,
2306
+ composition_text: str,
2307
+ name: str,
2308
+ description: str,
2309
+ order: int = 0,
2310
+ preset_plugin_name: str = "@deepseek-ai/dsh-agent-presets",
2311
+ ) -> str:
2312
+ """Format an agent-preset patch block for DSH profile cordis.patch.yml."""
2313
+ fields = [f" id: {preset_id}"]
2314
+ for key, val in (("name", name), ("description", description)):
2315
+ if val:
2316
+ fields.append(f" {key}: {json.dumps(val, ensure_ascii=False)}")
2317
+ fields.append(f" order: {order}")
2318
+
2319
+ rows = []
2320
+ # rstrip(而非 strip):desktop 官方模板的组态首行自带缩进,strip 会把
2321
+ # 首行缩进剥掉,产出错位的 patch 块(YAML 解析失败 → preset broken)。
2322
+ for line in composition_text.rstrip("\n").splitlines():
2323
+ rows.append(f" {line}" if line.strip() else "")
2324
+
2325
+ header = (
2326
+ f"- insert:\n"
2327
+ f" - id: preset-{preset_id}\n"
2328
+ f" name: '{preset_plugin_name}'\n"
2329
+ f" config:"
2330
+ )
2331
+ return (
2332
+ f"{header}\n"
2333
+ f"{chr(10).join(fields)}\n"
2334
+ f" plugins:\n"
2335
+ f"{chr(10).join(rows)}"
2336
+ )
2337
+
2338
+
2339
+ def _sync_dsh_profile_patch(
2340
+ home: Path,
2341
+ preset_id: str,
2342
+ composition_text: str,
2343
+ name: str,
2344
+ description: str,
2345
+ order: int = 0,
2346
+ preset_plugin_name: str = "@deepseek-ai/dsh-agent-presets",
2347
+ root: Path | None = None,
2348
+ ) -> None:
2349
+ """Ensure profiles/{web,desktop}/cordis.patch.yml carry the latest preset block.
2350
+
2351
+ F-RSI-20261119-012:DSH Desktop 的会话实际读 ``profiles/desktop`` 的
2352
+ legacy preset 块;此前只同步 ``profiles/web``,导致 desktop 侧残留旧
2353
+ preset(错误插件名)并使「自定义 agent 加载失败」。
2354
+ """
2355
+ patch_block = _format_dsh_preset_patch(
2356
+ preset_id, composition_text, name, description, order,
2357
+ preset_plugin_name=preset_plugin_name,
2358
+ )
2359
+ for profile_name in ("web", "desktop"):
2360
+ profile_dir = home / "profiles" / profile_name
2361
+ if not profile_dir.is_dir():
2362
+ continue
2363
+ _sync_one_profile_patch(
2364
+ profile_dir, profile_name, preset_id, patch_block, root=root,
2365
+ )
2366
+
2367
+
2368
+ def _sync_one_profile_patch(
2369
+ profile_dir: Path,
2370
+ profile_name: str,
2371
+ preset_id: str,
2372
+ patch_block: str,
2373
+ root: Path | None = None,
2374
+ ) -> None:
2375
+ """把 preset 块写入/替换到单个 profile 的 cordis.patch.yml。"""
2376
+ patch_path = profile_dir / "cordis.patch.yml"
2377
+ _assert_no_symlink_components(patch_path)
2378
+ if not patch_path.is_file():
2379
+ content = f"# {profile_name.capitalize()} profile user patch layer\n\n{patch_block}\n"
2380
+ _atomic_write_global_file_tx(patch_path, content.encode("utf-8"))
2381
+ return
2382
+
2383
+ content = patch_path.read_text(encoding="utf-8")
2384
+ pattern = (
2385
+ rf"(- insert:\s*\n\s*- id: preset-{re.escape(preset_id)}\b"
2386
+ rf".*?(?=\n- id:|\n- insert:|\n# dsh-desktop legacy presets end|\Z))"
2387
+ )
2388
+ if re.search(pattern, content, re.DOTALL):
2389
+ updated = re.sub(pattern, patch_block, content, count=1, flags=re.DOTALL)
2390
+ elif "# dsh-desktop legacy presets end" in content:
2391
+ updated = content.replace(
2392
+ "# dsh-desktop legacy presets end",
2393
+ f"{patch_block}\n\n# dsh-desktop legacy presets end",
2394
+ 1,
2395
+ )
2396
+ else:
2397
+ stripped = content.strip()
2398
+ if stripped.endswith("[]"):
2399
+ updated = content.replace("[]", f"\n{patch_block}\n")
2400
+ else:
2401
+ updated = f"{content.rstrip()}\n\n{patch_block}\n"
2402
+
2403
+ if root is None:
2404
+ raise CliError("_sync_one_profile_patch 需要 root 以绝对化 MCP --root/--db(F-RSI-20261119-015)")
2405
+ updated = _ensure_official_mcp_overlay(updated, root)
2406
+
2407
+ if updated != content:
2408
+ _atomic_write_global_file_tx(patch_path, updated.encode("utf-8"))
2409
+
2410
+
2411
+ #: 官方 dsh MCP client(dsh 自身依赖,profile 内可解析)。
2412
+ _OFFICIAL_MCP_CLIENT = "@deepseek-ai/dsh-mcp-client"
2413
+ #: 三条受控通道;serverName 必须唯一,且与 core/hosts/dsh.py 的声明一致。
2414
+ _OFFICIAL_MCP_SERVERS = (
2415
+ # F-RSI-20261119-015:与 core/hosts/dsh.py::_MCP_SERVERS 同一契约——
2416
+ # dsh 的 MCP server 由宿主进程 spawn,cwd 不是工作区,``--root .`` 会解析
2417
+ # 到宿主自己的 cwd(实测报「缺少有效的 .bugx 项目运行布局」)。因此这里
2418
+ # 与 install 侧一样使用 {ROOT} 占位,由 overlay 以**绝对项目根**替换。
2419
+ # 修改任一侧时必须同步另一侧,两处常量必须逐字一致。
2420
+ ("bugx-supervisor", ["mcp", "serve", "--root", "{ROOT}"]),
2421
+ ("bugx-supervisor-worker", ["mcp", "serve", "--root", "{ROOT}", "--role", "worker"]),
2422
+ ("bugx-docs", ["mcp", "docs", "serve", "--root", "{ROOT}", "--db",
2423
+ "{ROOT}/.bugx/knowledge/docs.sqlite3"]),
2424
+ )
2425
+ _OFFICIAL_MCP_MARKER = "# BugX MCP overlay — official dsh-mcp-client (stdio)"
2426
+
2427
+
2428
+ def _ensure_official_mcp_overlay(content: str, root: Path) -> str:
2429
+ """向 profile patch 追加/更新官方 MCP 三通道 ``- insert:`` 块。
2430
+
2431
+ ``root`` 是安装时项目根:``--root``/``--db`` 必须随根绝对化(契约见
2432
+ core/hosts/dsh.py::_MCP_SERVERS 注释——宿主进程 spawn 的 MCP server cwd
2433
+ 不是工作区,相对路径会解析到宿主 cwd)。此前这里写死 ``--root .``,与
2434
+ install 侧的绝对根互相覆盖:install 写对、deploy 又改回相对路径,两条
2435
+ 路径产物永不相等(F-RSI-20261119-015)。
2436
+
2437
+ 为什么必须由 install 自己写:``bugx install --agent dsh`` 之后
2438
+ ``bugx doctor`` 的「DeepSeek Harness MCP 配置」会扫项目 patch 与全局预设,
2439
+ 确认 supervisor 通道存在。此前这份内容由预设层的第三方
2440
+ ``@bencibro/bugx-dsh-mcp-client`` 提供——但该桥把 MCP 的 JSON Schema 当
2441
+ schemastery spec 编译,实测每次调用抛 ``v3Schema.safeParse is not a
2442
+ function``(工具在清单里看得见、调用必失败)。改为官方 client 后,预设层
2443
+ 不再承载 MCP,若 install 也不写,doctor 就会判定「缺少 bugx-supervisor
2444
+ MCP」,形成「修好调用却报告缺失」的新破窗。
2445
+ """
2446
+ root_text = str(Path(root).resolve())
2447
+ lines = [_OFFICIAL_MCP_MARKER, "- insert:"]
2448
+ for server_name, argv in _OFFICIAL_MCP_SERVERS:
2449
+ lines.extend([
2450
+ f" - id: {server_name}",
2451
+ f" name: '{_OFFICIAL_MCP_CLIENT}'",
2452
+ " config:",
2453
+ f" serverName: {server_name}",
2454
+ " transport: stdio",
2455
+ " command: bugx",
2456
+ " args:",
2457
+ ])
2458
+ lines.extend(
2459
+ f" - '{arg.replace('{ROOT}', root_text)}'" for arg in argv
2460
+ )
2461
+ block = "\n".join(lines) + "\n"
2462
+
2463
+ # 归一算法(2026-11-08 实测重写,两次迭代):按**条目 id** 识别受控块,
2464
+ # 不依赖 MARKER 头——历史 web patch 里存在「裸块」(旧版写入无 MARKER)
2465
+ # 与「MARKER 块」并存,只认 MARKER 会漏删裸块(实测输入 2 套输出仍 2 套)。
2466
+ # 扫描顶层 ``- insert:`` 块:块内含任一受控 id(bugx-supervisor/-worker/
2467
+ # docs)即整块删除;外来块(tool-web、preset-*)不含受控 id,原样保留。
2468
+ # 删完后尾部追加单一规范块——输入 N 套输出恒 1 套。
2469
+ # 注意 re.MULTILINE:block_text 是多行串,串首是 ``- insert:`` 而条目行
2470
+ # 带缩进在后续行——无 MULTILINE 时 ^ 只匹配串首,永远失配(实测踩坑)。
2471
+ entry_re = re.compile(r"^\s*- id:\s*(bugx-(?:supervisor|supervisor-worker|docs))\b", re.MULTILINE)
2472
+ lines = content.splitlines()
2473
+ kept: list[str] = []
2474
+ i = 0
2475
+ while i < len(lines):
2476
+ line = lines[i]
2477
+ if line.strip() == _OFFICIAL_MCP_MARKER:
2478
+ i += 1 # MARKER 行自身一并清除(裸块收集可能终止于此,见下)
2479
+ continue
2480
+ if line.strip() == "- insert:":
2481
+ j = i + 1
2482
+ while j < len(lines) and (lines[j].startswith((" ", "\t")) or not lines[j].strip()):
2483
+ j += 1
2484
+ block_text = "\n".join(lines[i:j])
2485
+ if entry_re.search(block_text):
2486
+ i = j
2487
+ continue
2488
+ kept.append(line)
2489
+ i += 1
2490
+ base = "\n".join(kept).rstrip("\n")
2491
+ if not base.strip() or base.strip() == "# Web profile user patch layer":
2492
+ return block
2493
+ return f"{base}\n\n{block}"
2494
+
2495
+
2496
+ def _global_opencode_skills_dir() -> Path:
2497
+ """Return ~/.config/opencode/skills, creating parents if missing.
2498
+
2499
+ 与 :func:`_global_opencode_agents_dir` 同纪律:宿主配置属用户档案,
2500
+ BugX 的数据/引擎 override 不迁移宿主自己的发现目录。
2501
+ """
2502
+ d = Path.home().resolve() / ".config" / "opencode" / "skills"
2503
+ d.mkdir(parents=True, exist_ok=True)
2504
+ return d.resolve()
2505
+
2506
+
2507
+ def _global_opencode_agents_dir() -> Path:
2508
+ """Return ~/.config/opencode/agents, creating parents if missing.
2509
+
2510
+ Host configuration belongs to the user profile. BugX data/engine overrides
2511
+ relocate BugX storage, not the host's configuration discovery directory.
2512
+ """
2513
+ d = Path.home().resolve() / ".config" / "opencode" / "agents"
2514
+ d.mkdir(parents=True, exist_ok=True)
2515
+ return d.resolve()
2516
+
2517
+
2518
+ def _link_opencode_agent_entry(root: Path) -> tuple[int, int, Path | None]:
2519
+ """项目入口指向使用 OpenCode v2 frontmatter 的专用载荷。"""
2520
+ return _link_opencode_agent_file(
2521
+ root, "bugx.md", payload_name="bugx-opencode.md",
2522
+ )
2523
+
2524
+
2525
+ def _link_opencode_worker_entry(root: Path) -> tuple[int, int, Path | None]:
2526
+ """并发 worker 精简入口 .opencode/agents/bugx-worker.md(同源相对链接)。
2527
+
2528
+ worker 只需要单元级执行规则,不加载完整 150KB 宪法。OpenCode v2 的
2529
+ subagent 调度依赖该入口;缺失载荷必须阻止安装,不能留下半套配置。
2530
+ """
2531
+ return _link_opencode_agent_file(root, "bugx-worker.md")
2532
+
2533
+
2534
+ def _atomic_link_or_copy(payload: Path, target: Path, *, directory: bool = False) -> bool:
2535
+ """Publish *payload* at *target* as a relative symlink, else as a copy.
2536
+
2537
+ Windows grants symlink creation only to elevated sessions or Developer
2538
+ Mode (WinError 1314 elsewhere), so the same tmp+replace dance falls back
2539
+ to a byte copy; doctor's integrity checks accept a hash-identical copy.
2540
+ Returns True when a symlink was published, False for the copy fallback.
2541
+ """
2542
+ try:
2543
+ rel = os.path.relpath(payload.resolve(), target.parent.resolve())
2544
+ except ValueError:
2545
+ # 跨盘时 relpath 无法计算(Windows C: -> D:),回退为绝对路径
2546
+ rel = str(payload.resolve())
2547
+ temporary = target.parent / f".{target.name}.tmp-{os.getpid()}-{time.time_ns()}"
2548
+ try:
2549
+ os.symlink(rel, temporary)
2550
+ os.replace(temporary, target)
2551
+ return True
2552
+ except (OSError, NotImplementedError):
2553
+ try:
2554
+ temporary.unlink()
2555
+ except OSError:
2556
+ pass
2557
+ try:
2558
+ if directory:
2559
+ shutil.copytree(payload, temporary, symlinks=True)
2560
+ else:
2561
+ shutil.copy2(payload, temporary)
2562
+ os.replace(temporary, target)
2563
+ print(
2564
+ "[bugx] 提示:当前环境不允许创建符号链接(Windows 需管理员或开发者模式),"
2565
+ f"已改用文件副本发布入口: {target}",
2566
+ file=sys.stderr,
2567
+ )
2568
+ return False
2569
+ except BaseException:
2570
+ shutil.rmtree(temporary, ignore_errors=True)
2571
+ try:
2572
+ temporary.unlink()
2573
+ except OSError:
2574
+ pass
2575
+ raise
2576
+
2577
+
2578
+ def _register_global_opencode_agent(root: Path) -> tuple[int, list[Path]]:
2579
+ """在 ~/.config/opencode/agents/ 建立指向全局引擎的符号链接。
2580
+
2581
+ 0.5.38(DOC-004):Agent 入口注册到全局,在任意项目目录下启动
2582
+ OpenCode 均可直接发现并调用 @bugx / @bugx-worker。
2583
+ """
2584
+ engine = global_engine_root()
2585
+ payloads = {}
2586
+ for filename, src_name in (
2587
+ ("bugx.md", "bugx-opencode.md"),
2588
+ ("bugx-worker.md", "bugx-worker.md"),
2589
+ ):
2590
+ payload = engine / src_name
2591
+ if not payload.is_file():
2592
+ payload = engine / "contracts" / src_name
2593
+ if not payload.is_file():
2594
+ payload = asset_root() / src_name
2595
+ if not payload.is_file():
2596
+ payload = asset_root() / "contracts" / src_name
2597
+ if not payload.is_file():
2598
+ raise CliError(
2599
+ f"缺少 OpenCode v2 Agent 载荷 {src_name},不能注册不完整的宿主 Agent"
2600
+ )
2601
+ payloads[filename] = payload
2602
+ agents_dir = _global_opencode_agents_dir()
2603
+ copied = 0
2604
+ backups: list[Path] = []
2605
+ for filename, payload in payloads.items():
2606
+ target = agents_dir / filename
2607
+ _assert_no_symlink_components(target.parent)
2608
+ target.parent.mkdir(parents=True, exist_ok=True)
2609
+ if target.exists():
2610
+ if not target.is_symlink():
2611
+ backup_dir = root / ".bugx" / "backups" / "opencode"
2612
+ _assert_no_symlink_components(backup_dir)
2613
+ backup_dir.mkdir(parents=True, exist_ok=True)
2614
+ backup = backup_dir / (
2615
+ f"global-agent-{filename}-" + time.strftime("%Y%m%d-%H%M%S") + ".md"
2616
+ )
2617
+ shutil.copy2(target, backup)
2618
+ backups.append(backup)
2619
+ # F-L0-03:全局入口写入前登记事务快照,失败时按记录逆序还原。
2620
+ _tx_stage_global(target)
2621
+ # 统一相对链接:全局 agent 入口指向全局引擎,升级一处即可生效。
2622
+ _atomic_link_or_copy(payload, target)
2623
+ copied += 1
2624
+ return copied, backups
2625
+
2626
+
2627
+ def _link_opencode_agent_file(
2628
+ root: Path, filename: str, payload_name: str | None = None,
2629
+ ) -> tuple[int, int, Path | None]:
2630
+ target = root / ".opencode" / "agents" / filename
2631
+ actual_name = payload_name or filename
2632
+ payload = global_engine_root() / actual_name
2633
+ if not payload.is_file():
2634
+ payload = global_engine_root() / "contracts" / actual_name
2635
+ if not payload.is_file():
2636
+ payload = (asset_root() / actual_name).resolve()
2637
+ if not payload.is_file():
2638
+ payload = (asset_root() / "contracts" / actual_name).resolve()
2639
+ if not payload.is_file():
2640
+ raise CliError(_i18n_exc("agent.opencode_payload_missing", f"缺少 {actual_name} 载荷,无法安装 OpenCode 入口", actual_name=actual_name))
2641
+ backup = None
2642
+ if target.exists():
2643
+ if not target.is_symlink():
2644
+ backup_dir = root / ".bugx" / "backups" / "opencode"
2645
+ backup_dir.mkdir(parents=True, exist_ok=True)
2646
+ backup = backup_dir / (
2647
+ "agents-bugx-" + time.strftime("%Y%m%d-%H%M%S") + ".md"
2648
+ )
2649
+ shutil.copy2(target, backup)
2650
+ _assert_no_symlink_components(target.parent)
2651
+ target.parent.mkdir(parents=True, exist_ok=True)
2652
+ # resolve 消除 /var → /private/var 等 macOS 符号链接差异
2653
+ _atomic_link_or_copy(payload, target)
2654
+ return 1, 0, backup
2655
+
2656
+
2657
+ def _migrate_legacy_opencode_agent_entry(root: Path) -> None:
2658
+ """0.5.33 前的 .opencode/agent/bugx.md(单数,非官方路径)迁移到备份。"""
2659
+ legacy = root / ".opencode" / "agent" / "bugx.md"
2660
+ if legacy.is_symlink() or not legacy.is_file():
2661
+ return
2662
+ backup_dir = root / ".bugx" / "backups" / "opencode"
2663
+ backup_dir.mkdir(parents=True, exist_ok=True)
2664
+ backup = backup_dir / (
2665
+ "agent-bugx-" + time.strftime("%Y%m%d-%H%M%S") + ".md"
2666
+ )
2667
+ try:
2668
+ shutil.copy2(legacy, backup)
2669
+ legacy.unlink()
2670
+ except OSError:
2671
+ pass
2672
+
2673
+
2674
+ def _unlink_global_opencode_agent(root: Path) -> None:
2675
+ """0.5.38(DOC-004):agent 全局注册是设计义务,不再视为「遗留痕迹」。
2676
+
2677
+ 保留函数体以兼容上游调用者;不再删除 ~/.config/opencode/agents/ 下的
2678
+ 任何链接。彻底卸载请使用 `bugx uninstall`(同样不触碰全局 agent 注册,
2679
+ 因为全局引擎属多项目共享资产)。
2680
+ """
2681
+ return None
2682
+
2683
+
2684
+ def _self_check_pi_skill_registered(root: Path) -> None:
2685
+ """安装完成后自检:pi 是否能发现 bugx skill。
2686
+
2687
+ 默认开启,可通过 BUGX_SELF_CHECK=0 显式关闭。
2688
+ """
2689
+ if os.environ.get("BUGX_SELF_CHECK") == "0":
2690
+ return
2691
+ home = Path.home().resolve()
2692
+ pi_skill_link = home / ".pi" / "skills" / "bugx"
2693
+ pi_agent_skill_link = home / ".pi" / "agent" / "skills" / "bugx"
2694
+ agents_skill_dir = home / ".agents" / "skills" / "bugx"
2695
+
2696
+ def _is_reg(link: Path) -> bool:
2697
+ return link.is_symlink() or (link.is_dir() and (link / "SKILL.md").is_file())
2698
+
2699
+ if not (_is_reg(pi_skill_link) or _is_reg(pi_agent_skill_link)):
2700
+ raise CliError(_i18n_exc("agent.pi_skill_symlink_missing", f"自检失败:pi 未注册 bugx skill 符号链接 ({pi_skill_link})", path=pi_skill_link))
2701
+ if not agents_skill_dir.is_dir():
2702
+ raise CliError(_i18n_exc("agent.pi_global_skill_dir_missing", f"自检失败:全局 skill 目录不存在 ({agents_skill_dir})", path=agents_skill_dir))
2703
+ if not (agents_skill_dir / "SKILL.md").is_file():
2704
+ raise CliError(_i18n_exc("agent.pi_skill_md_missing", f"自检失败:SKILL.md 不存在于 ({agents_skill_dir})", path=agents_skill_dir))
2705
+
2706
+
2707
+ def _link_global_pi_skill(root: Path, locale: str | None = None) -> None:
2708
+ """把项目 .pi/skills/bugx/SKILL.md 注册到全局 pi 可发现的位置。
2709
+
2710
+ Pi 0.85+ 优先从 ~/.pi/agent/skills/<name>/ 发现用户全局 skill,同时
2711
+ 兼容旧版 ~/.pi/skills/<name>/。本函数:
2712
+ 1) 把 SKILL.md 复制到 ~/.agents/skills/bugx/(如已有 L0 路由则刷新其 description)
2713
+ 2) 建立/更新 ~/.pi/skills/bugx 与 ~/.pi/agent/skills/bugx 相对符号链接
2714
+ """
2715
+ source = root.resolve() / ".pi" / "skills" / "bugx" / "SKILL.md"
2716
+ if not source.is_file():
2717
+ return
2718
+ home = Path.home().resolve()
2719
+ agents_skill_parent = (home / ".agents" / "skills").resolve(strict=False)
2720
+ if not agents_skill_parent.is_relative_to(home):
2721
+ raise CliError(_i18n_exc("agent.pi_global_skill_escaped_user", f"Pi 全局 Skill 目录越出用户目录:{agents_skill_parent}", path=agents_skill_parent))
2722
+ _assert_no_symlink_components(agents_skill_parent)
2723
+ agents_skill_dir = agents_skill_parent / "bugx"
2724
+ pi_skill_dir = home / ".pi" / "skills" / "bugx"
2725
+ pi_agent_skill_dir = home / ".pi" / "agent" / "skills" / "bugx"
2726
+ _assert_no_symlink_components(agents_skill_dir)
2727
+ _assert_no_symlink_components(pi_skill_dir.parent)
2728
+ _assert_no_symlink_components(pi_agent_skill_dir.parent)
2729
+ agents_skill_dir.mkdir(parents=True, exist_ok=True)
2730
+ target = agents_skill_dir / "SKILL.md"
2731
+ should_write = True
2732
+ if target.is_file():
2733
+ try:
2734
+ existing_text = target.read_text(encoding="utf-8")
2735
+ if "BugX for ChatGPT" in existing_text or "BugX L0 路由入口" in existing_text:
2736
+ should_write = False
2737
+ # 同步刷新 Frontmatter description 保证全局描述与当前语言对齐
2738
+ from ..host_adapters import get_agent_description
2739
+ desc = get_agent_description(locale)
2740
+ new_text = re.sub(
2741
+ r"^description:[^\n]+",
2742
+ f"description: {desc}",
2743
+ existing_text,
2744
+ count=1,
2745
+ flags=re.MULTILINE,
2746
+ )
2747
+ if new_text != existing_text:
2748
+ _tx_stage_global(target)
2749
+ _write_host_resource(root, target, new_text.encode("utf-8"), "pi-global")
2750
+ except OSError:
2751
+ pass
2752
+ if should_write:
2753
+ _tx_stage_global(target)
2754
+ _write_host_resource(root, target, source.read_bytes(), "pi-global")
2755
+
2756
+ for p_dir in (pi_skill_dir, pi_agent_skill_dir):
2757
+ if p_dir.is_dir() and not p_dir.is_symlink():
2758
+ # Windows 无符号链接权限时,首次安装会发布一个目录副本。
2759
+ # 第二次安装必须对这个由 BugX 生成且仍与全局实体完全一致的副本
2760
+ # 幂等放行;若内容已被用户改写,则继续拒绝覆盖,避免破坏用户目录。
2761
+ global_skill = agents_skill_dir / "SKILL.md"
2762
+ candidate = p_dir / "SKILL.md"
2763
+ try:
2764
+ owned_copy = (
2765
+ candidate.is_file()
2766
+ and global_skill.is_file()
2767
+ and _sha256_file(candidate) == _sha256_file(global_skill)
2768
+ )
2769
+ except OSError:
2770
+ owned_copy = False
2771
+ if not owned_copy:
2772
+ raise CliError(_i18n_exc("agent.pi_user_dir_skill_refused", f"拒绝覆盖用户目录形式的 Pi Skill:{p_dir}", path=p_dir))
2773
+ continue
2774
+ p_dir.parent.mkdir(parents=True, exist_ok=True)
2775
+ _tx_stage_global(p_dir)
2776
+ _atomic_link_or_copy(agents_skill_dir, p_dir, directory=True)
2777
+
2778
+
2779
+ def _unlink_global_pi_skill(root: Path, removed: list[str], preserved: list[str]) -> None:
2780
+ """普通项目卸载保留全局 Pi Skill,只清理悬空的 ~/.pi 链接。
2781
+
2782
+ ~/.agents/skills/bugx 与 ~/.pi/skills/bugx 是多项目共享的全局注册,
2783
+ 无法按单项目判定归属(A 项目卸载不能破坏 B 项目的安装);全局
2784
+ 清理统一由 ``uninstall --self`` 的 ``_self_uninstall_pi_skill`` 负责。
2785
+ 这里仅删除目标已不存在的悬空链接,避免残留死链。
2786
+ """
2787
+ agents_skill_dir = Path.home() / ".agents" / "skills" / "bugx"
2788
+ pi_skill_dir = Path.home() / ".pi" / "skills" / "bugx"
2789
+ pi_agent_skill_dir = Path.home() / ".pi" / "agent" / "skills" / "bugx"
2790
+ try:
2791
+ if (agents_skill_dir / "SKILL.md").is_file():
2792
+ preserved.append(
2793
+ "~/.agents/skills/bugx(全局 Pi Skill 保留:多项目共享,"
2794
+ "全局清理需 uninstall --self)"
2795
+ )
2796
+ return
2797
+ for p_dir, label in ((pi_skill_dir, "~/.pi/skills/bugx"), (pi_agent_skill_dir, "~/.pi/agent/skills/bugx")):
2798
+ if p_dir.is_symlink() and not (p_dir / "SKILL.md").exists():
2799
+ p_dir.unlink()
2800
+ removed.append(f"{label}(悬空链接)")
2801
+ except OSError:
2802
+ pass
2803
+
2804
+
2805
+ def _sync_workbuddy_private_venv(
2806
+ source: Path, *, target_version: str | None = None,
2807
+ ) -> tuple[bool, str]:
2808
+ """探测并同步 WorkBuddy 私有 Python 虚拟环境中的 bugx-cli 包 (DOC-181)。"""
2809
+ from ..host_adapters import workbuddy_cli_venv
2810
+ venv = workbuddy_cli_venv()
2811
+ if not venv:
2812
+ return False, "未检测到 WorkBuddy 私有虚拟环境"
2813
+
2814
+ bin_dir = venv / ("Scripts" if os.name == "nt" else "bin")
2815
+ py_exe = bin_dir / ("python.exe" if os.name == "nt" else "python")
2816
+ if not py_exe.is_file():
2817
+ return False, f"WorkBuddy 虚拟环境缺失 Python 解释器: {py_exe}"
2818
+
2819
+ from ..common import _is_bugx_source_repo
2820
+ import subprocess
2821
+ is_source = _is_bugx_source_repo(source)
2822
+ if is_source:
2823
+ cmd = [str(py_exe), "-m", "pip", "install", "-e", str(source.resolve()), "--no-deps"]
2824
+ else:
2825
+ pkg = f"bugx-cli=={target_version}" if target_version else "bugx-cli"
2826
+ cmd = [str(py_exe), "-m", "pip", "install", "--upgrade", pkg, "--no-deps"]
2827
+ try:
2828
+ proc = subprocess.run(
2829
+ cmd,
2830
+ capture_output=True,
2831
+ text=True,
2832
+ timeout=45,
2833
+ check=False,
2834
+ )
2835
+ if proc.returncode != 0:
2836
+ err = proc.stderr.strip() or proc.stdout.strip()
2837
+ return False, f"同步失败 (exit={proc.returncode}): {err}"
2838
+
2839
+ # 恶性设计治理 (DOC-180):强制同步多语言 Tree-sitter 依赖包,杜绝环境缺少 AST 解析器
2840
+ subprocess.run(
2841
+ [str(py_exe), "-m", "pip", "install", "tree-sitter-language-pack>=1.14.3", "--no-warn-script-location"],
2842
+ capture_output=True,
2843
+ text=True,
2844
+ timeout=60,
2845
+ check=False,
2846
+ )
2847
+
2848
+ mode_desc = f"开发模式 ({source.name})" if is_source else pkg
2849
+ return True, f"已同步沙箱环境 {venv} ({mode_desc})"
2850
+ except Exception as exc:
2851
+ return False, f"同步异常: {exc}"
2852
+
2853
+
2854
+ def _opencode_usage_skill_path(root: Path, source: Path) -> Path:
2855
+ """定位 bugx-opencode 使用手册 Skill 的唯一权威源。
2856
+
2857
+ 与 :func:`_zcode_usage_skill_path` 同模式:wheel 载荷优先
2858
+ (``share/bugx-agent/plugins/bugx/skills/bugx-opencode/SKILL.md``),
2859
+ 源码仓库开发态回退 ecosystem/ 与 plugins/ 镜像。
2860
+ """
2861
+ candidates = (
2862
+ source.parent / "plugins" / "bugx" / "skills" / "bugx-opencode" / "SKILL.md",
2863
+ root / "ecosystem" / "plugins" / "bugx" / "skills" / "bugx-opencode" / "SKILL.md",
2864
+ root / "plugins" / "bugx" / "skills" / "bugx-opencode" / "SKILL.md",
2865
+ )
2866
+ for candidate in candidates:
2867
+ if not candidate.is_symlink() and candidate.is_file():
2868
+ return candidate
2869
+ return candidates[0]
2870
+
2871
+
2872
+ def _ensure_opencode_user_skill(
2873
+ root: Path, source: Path, *, backup_label: str,
2874
+ ) -> dict[str, object]:
2875
+ """把 bugx-opencode 使用手册 Skill 写入 OpenCode 用户级 skills 目录。
2876
+
2877
+ OpenCode v2 从 ``~/.config/opencode/skills/<name>/SKILL.md`` 发现用户级
2878
+ Skill(与 ZCode ``~/.zcode/skills`` 同构)。全局层产物跨项目可见,与
2879
+ agents 全局软链同一安装事务;内容随 wheel 版本演进——新环境
2880
+ ``bugx install --agent opencode`` 即获得。增广件语义与 zcode 一致:
2881
+ 旧 wheel 载荷缺资产时跳过部署(不阻塞安装),升级后自动生效。
2882
+ """
2883
+ skill_source = _opencode_usage_skill_path(root, source)
2884
+ if skill_source.is_symlink() or not skill_source.is_file():
2885
+ return {
2886
+ "dir": str(_global_opencode_skills_dir()),
2887
+ "written": [],
2888
+ "backups": [],
2889
+ "status": "skipped_missing_source",
2890
+ }
2891
+ skills_dir = _global_opencode_skills_dir()
2892
+ if skills_dir.is_symlink():
2893
+ raise CliError(_i18n_exc(
2894
+ "agent.opencode_symlink_skills_dir",
2895
+ f"拒绝写入符号链接 OpenCode 用户级 skills 目录: {skills_dir}",
2896
+ skills_dir=skills_dir,
2897
+ ))
2898
+ target = skills_dir / "bugx-opencode" / "SKILL.md"
2899
+ if target.is_symlink():
2900
+ raise CliError(_i18n_exc(
2901
+ "agent.opencode_symlink_skill_refused",
2902
+ f"拒绝覆盖符号链接 OpenCode 用户级 Skill: {target}",
2903
+ target=target,
2904
+ ))
2905
+ if target.exists() and not target.is_file():
2906
+ raise CliError(_i18n_exc(
2907
+ "agent.opencode_user_skill_not_regular_file",
2908
+ f"OpenCode 用户级 Skill 不是普通文件,拒绝覆盖: {target}", target=target,
2909
+ ))
2910
+ payload = skill_source.read_bytes()
2911
+ if target.is_file():
2912
+ try:
2913
+ if target.read_bytes() == payload:
2914
+ return {
2915
+ "dir": str(skills_dir),
2916
+ "written": [{
2917
+ "path": str(target), "status": "unchanged",
2918
+ "backup": None, "created": False,
2919
+ }],
2920
+ "backups": [],
2921
+ }
2922
+ except OSError as exc:
2923
+ raise CliError(_i18n_exc(
2924
+ "agent.opencode_user_skill_unreadable",
2925
+ f"无法读取已有 OpenCode 用户级 Skill,未修改: {target}: {exc}",
2926
+ target=target, exc=exc,
2927
+ )) from exc
2928
+ backup = _backup_host_resource(root, backup_label, target) if target.exists() else None
2929
+ backups = [backup] if backup is not None else []
2930
+ target.parent.mkdir(parents=True, exist_ok=True)
2931
+ _atomic_write_global_file(target, payload)
2932
+ return {
2933
+ "dir": str(skills_dir),
2934
+ "written": [{
2935
+ "path": str(target),
2936
+ "status": "created" if backup is None else "upgraded",
2937
+ "backup": str(backup) if backup is not None else None,
2938
+ "created": backup is None,
2939
+ }],
2940
+ "backups": backups,
2941
+ }
2942
+
2943
+
2944
+ def _ensure_workbuddy_user_skill(root: Path, content: str) -> dict[str, object]:
2945
+ """Write the WorkBuddy user-level Skill so every project can see BugX.
2946
+
2947
+ The desktop host discovers skills from ``<configDir>/skills`` (configDir =
2948
+ ``WORKBUDDY_CONFIG_DIR`` for the running edition, e.g. ``~/.workbuddy-ai``
2949
+ for the overseas build). This is a global-layer artifact shared by all
2950
+ projects: ownership is content-based, and a wrong or missing target never
2951
+ breaks the project-level install. Returns per-file status for the install
2952
+ transaction rollback, mirroring :func:`_ensure_zcode_user_agents`.
2953
+ """
2954
+ target_root = workbuddy_user_skill_root()
2955
+ skill_dir = target_root / "skills" / "bugx"
2956
+ target = skill_dir / "SKILL.md"
2957
+ if target.is_symlink():
2958
+ raise CliError(_i18n_exc(
2959
+ "agent.workbuddy_user_skill_symlink_refused",
2960
+ f"拒绝覆盖符号链接 WorkBuddy 用户级 Skill: {target}", target=target,
2961
+ ))
2962
+ if target.exists() and not target.is_file():
2963
+ raise CliError(_i18n_exc(
2964
+ "agent.workbuddy_user_skill_not_regular_file",
2965
+ f"WorkBuddy 用户级 Skill 不是普通文件,拒绝覆盖: {target}", target=target,
2966
+ ))
2967
+ payload = content.encode("utf-8")
2968
+ if target.is_file():
2969
+ try:
2970
+ if target.read_bytes() == payload:
2971
+ return {
2972
+ "root": str(target_root),
2973
+ "written": [{
2974
+ "path": str(target), "status": "unchanged",
2975
+ "backup": None, "created": False,
2976
+ }],
2977
+ "backups": [],
2978
+ }
2979
+ except OSError as exc:
2980
+ raise CliError(_i18n_exc(
2981
+ "agent.workbuddy_user_skill_unreadable",
2982
+ f"无法读取已有 WorkBuddy 用户级 Skill,未修改: {target}: {exc}",
2983
+ target=target, exc=exc,
2984
+ )) from exc
2985
+ backup = _backup_host_resource(root, "workbuddy", target) if target.exists() else None
2986
+ backups = [backup] if backup is not None else []
2987
+ # _atomic_write_global_file_tx is the single snapshot/journal boundary.
2988
+ _atomic_write_global_file_tx(target, payload)
2989
+ return {
2990
+ "root": str(target_root),
2991
+ "written": [{
2992
+ "path": str(target),
2993
+ "status": "created" if backup is None else "upgraded",
2994
+ "backup": str(backup) if backup is not None else None,
2995
+ "created": backup is None,
2996
+ }],
2997
+ "backups": backups,
2998
+ }
2999
+
3000
+
3001
+ def _ensure_workbuddy_connector(root: Path, content: str) -> dict[str, object]:
3002
+ """Stage the official WorkBuddy ``skill-only`` Connector package.
3003
+
3004
+ WorkBuddy Skills have no icon field. The Connector is the supported
3005
+ packaging boundary for marketplace/import display, while project and
3006
+ user-level Skill paths remain the runtime discovery surfaces.
3007
+ """
3008
+ source_dir = _integration_dir() / "workbuddy"
3009
+ source_meta = source_dir / "connector-meta.json"
3010
+ source_icon = source_dir / "icon.png"
3011
+ if (source_meta.is_symlink() or not source_meta.is_file()
3012
+ or source_icon.is_symlink() or not source_icon.is_file()):
3013
+ raise CliError(_i18n_exc(
3014
+ "agent.workbuddy_connector_resource_missing",
3015
+ f"缺少 WorkBuddy Connector 适配资源:{source_dir}",
3016
+ source=source_dir,
3017
+ ))
3018
+ try:
3019
+ metadata = json.loads(source_meta.read_text(encoding="utf-8"))
3020
+ except (OSError, json.JSONDecodeError) as exc:
3021
+ raise CliError(_i18n_exc(
3022
+ "agent.workbuddy_connector_metadata_invalid",
3023
+ f"WorkBuddy Connector 元数据无效:{source_meta}: {exc}",
3024
+ source=source_meta, exc=exc,
3025
+ )) from exc
3026
+ if not isinstance(metadata, dict) or metadata.get("type") != "skill-only":
3027
+ raise CliError(_i18n_exc(
3028
+ "agent.workbuddy_connector_metadata_invalid",
3029
+ f"WorkBuddy Connector 必须声明 type=skill-only:{source_meta}",
3030
+ source=source_meta, exc="type != skill-only",
3031
+ ))
3032
+
3033
+ target_root = root.resolve() / ".workbuddy" / "connector" / "bugx"
3034
+ _assert_no_symlink_components(target_root)
3035
+ targets = (
3036
+ (source_meta, target_root / "connector-meta.json"),
3037
+ (source_icon, target_root / "icon.png"),
3038
+ )
3039
+ written: list[dict[str, object]] = []
3040
+ backups: list[Path] = []
3041
+ for source, target in targets:
3042
+ copied, skipped, backup = _write_host_resource(
3043
+ root, target, source.read_bytes(), "workbuddy",
3044
+ )
3045
+ written.append({
3046
+ "path": str(target),
3047
+ "status": "created" if copied and backup is None else
3048
+ "upgraded" if copied else "unchanged",
3049
+ "backup": str(backup) if backup is not None else None,
3050
+ "created": bool(copied and backup is None),
3051
+ })
3052
+ if backup is not None:
3053
+ backups.append(backup)
3054
+
3055
+ skill_target = target_root / "skills" / "bugx" / "SKILL.md"
3056
+ copied, skipped, backup = _write_host_resource(
3057
+ root, skill_target, content.encode("utf-8"), "workbuddy",
3058
+ )
3059
+ written.append({
3060
+ "path": str(skill_target),
3061
+ "status": "created" if copied and backup is None else
3062
+ "upgraded" if copied else "unchanged",
3063
+ "backup": str(backup) if backup is not None else None,
3064
+ "created": bool(copied and backup is None),
3065
+ })
3066
+ if backup is not None:
3067
+ backups.append(backup)
3068
+ return {
3069
+ "root": str(target_root),
3070
+ "paths": [str(target) for _source, target in targets] + [str(skill_target)],
3071
+ "written": written,
3072
+ "backups": backups,
3073
+ }
3074
+
3075
+
3076
+ def _ensure_workbuddy_custom_expert(
3077
+ root: Path, content: str, config_root: Path | None = None,
3078
+ ) -> dict[str, object]:
3079
+ """Package and register BugX as a WorkBuddy Custom Expert in my-experts marketplace."""
3080
+ if config_root is None:
3081
+ config_root = workbuddy_user_skill_root()
3082
+ my_experts_dir = config_root / "plugins" / "marketplaces" / "my-experts"
3083
+ expert_plugin_dir = my_experts_dir / "plugins" / "bugx"
3084
+
3085
+ written: list[dict[str, object]] = []
3086
+ backups: list[Path] = []
3087
+
3088
+ for sub in (".codebuddy-plugin", ".workbuddy-plugin", "avatars", "agents", "skills/bugx"):
3089
+ (expert_plugin_dir / sub).mkdir(parents=True, exist_ok=True)
3090
+
3091
+ wb_name = "work" + "buddy"
3092
+
3093
+ # 1. Avatar
3094
+ avatar_src = _integration_dir() / wb_name / "icon.png"
3095
+ avatar_dest = expert_plugin_dir / "avatars" / "expert.png"
3096
+ if avatar_src.is_file():
3097
+ src_bytes = avatar_src.read_bytes()
3098
+ if not avatar_dest.is_file() or avatar_dest.read_bytes() != src_bytes:
3099
+ backup = _backup_host_resource(root, wb_name, avatar_dest) if avatar_dest.exists() else None
3100
+ if backup is not None:
3101
+ backups.append(backup)
3102
+ _atomic_write_global_file_tx(avatar_dest, src_bytes)
3103
+ written.append({
3104
+ "path": str(avatar_dest),
3105
+ "status": "created" if backup is None else "upgraded",
3106
+ "backup": str(backup) if backup is not None else None,
3107
+ "created": backup is None,
3108
+ })
3109
+
3110
+ # 2. Agent definition
3111
+ agent_dest = expert_plugin_dir / "agents" / "bugx.md"
3112
+ agent_content = (
3113
+ "---\n"
3114
+ "name: bugx\n"
3115
+ "description: >-\n"
3116
+ " BugX 代码审计专家:专注于代码质量与安全的自主审查,深入分析代码逻辑、发现隐蔽缺陷并自动编写 PoC 验证,提供确凿的证据闭环与修复方案。\n"
3117
+ "description_zh: >-\n"
3118
+ " BugX 代码审计专家:专注于代码质量与安全的自主审查,深入分析代码逻辑、发现隐蔽缺陷并自动编写 PoC 验证,提供确凿的证据闭环与修复方案。\n"
3119
+ "description_en: >-\n"
3120
+ " BugX Code Auditor: Autonomous code quality and security auditing expert. Specializes in deep defect hunting, adversarial testing, PoC reproduction, and verified remediation.\n"
3121
+ "tools: Bash,Read,Edit\n"
3122
+ "color: \"#08B7D4\"\n"
3123
+ "---\n\n"
3124
+ "你是一位专业的代码质量与漏洞挖掘专家(BugX 代码审计专家)。你的核心使命是帮助开发者在代码合入、发布前或疑难故障排查时,进行深层次的代码审计、对抗性缺陷排查与自动化验证。\n\n"
3125
+ "## 核心工作原则\n"
3126
+ "1. **证据驱动(Evidence-Driven)**:不凭空猜测 Bug,必须通过静态逻辑推演或最小复现测试(PoC)验证缺陷存在。\n"
3127
+ "2. **闭环验证(Verification Loop)**:缺陷发现后,优先编写自动化回归单测,验证失败;给出修复方案后重新运行测试验证通过。\n"
3128
+ "3. **安全与质量并重**:涵盖业务逻辑越权、并发死锁/竞态条件、边界值溢出、资源泄漏、SQL注入、SSRF等安全与稳定性隐患。\n\n"
3129
+ "## 协作流程\n"
3130
+ "1. **审计准备**:读取目标文件、架构设计与历史提交记录,理清数据流向与契约约束。\n"
3131
+ "2. **深入排查**:对输入校验、状态转移、异常处理、外部调用等关键节点进行对抗式推演。\n"
3132
+ "3. **产出报告**:输出清晰的问题说明、触发条件、风险等级与最小修复代码。\n"
3133
+ )
3134
+ backup = _backup_host_resource(root, wb_name, agent_dest) if agent_dest.exists() else None
3135
+ if backup is not None:
3136
+ backups.append(backup)
3137
+ _atomic_write_global_file_tx(agent_dest, agent_content.encode("utf-8"))
3138
+ written.append({
3139
+ "path": str(agent_dest),
3140
+ "status": "created" if backup is None else "upgraded",
3141
+ "backup": str(backup) if backup is not None else None,
3142
+ "created": backup is None,
3143
+ })
3144
+
3145
+ # 3. Plugin manifest
3146
+ plugin_meta = {
3147
+ "name": "bugx",
3148
+ "version": __version__,
3149
+ "expertType": "agent",
3150
+ "displayName": {
3151
+ "zh": "BugX",
3152
+ "en": "BugX"
3153
+ },
3154
+ "profession": {
3155
+ "zh": "代码审计专家",
3156
+ "en": "Code Audit Expert"
3157
+ },
3158
+ "description": "专注于代码质量与安全的自主审查智能体。专为深层缺陷排查而生——在功能写完、提 PR 或排查疑难 Bug 时,它能深入分析代码逻辑、发现隐蔽缺陷并自动编写 PoC 验证,提供确凿的证据闭环与修复方案。",
3159
+ "displayDescription": {
3160
+ "zh": "专注于代码质量与安全的自主审查智能体。专为深层缺陷排查而生——在功能写完、提 PR 或排查疑难 Bug 时,它能深入分析代码逻辑、发现隐蔽缺陷并自动编写 PoC 验证,提供确凿的证据闭环与修复方案。",
3161
+ "en": "Autonomous code quality and security auditing expert. Specializes in deep defect hunting, adversarial testing, PoC reproduction, and verified remediation."
3162
+ },
3163
+ "avatar": "avatars/expert.png",
3164
+ "category": "development",
3165
+ "categoryId": "01-Development",
3166
+ "tags": [
3167
+ {"zh": "代码审计", "en": "Code Audit"},
3168
+ {"zh": "漏洞挖掘", "en": "Vulnerability"},
3169
+ {"zh": "自动化测试", "en": "Automated Testing"}
3170
+ ],
3171
+ "quickPrompts": [
3172
+ {"zh": "对当前代码库进行一次全面的代码审计与漏洞排查", "en": "Perform a comprehensive code audit and vulnerability check on the current codebase"},
3173
+ {"zh": "排查最近提交的代码中潜在的并发与边界缺陷", "en": "Investigate potential concurrency and boundary defects in recent commits"},
3174
+ {"zh": "针对已知 Bug 编写最小复现 PoC 并验证修复方案", "en": "Write a minimal reproduction PoC for an issue and verify the fix"}
3175
+ ],
3176
+ "agents": ["./agents/bugx.md"],
3177
+ "skills": ["./skills/bugx"]
3178
+ }
3179
+ meta_bytes = (json.dumps(plugin_meta, indent=2, ensure_ascii=False) + "\n").encode("utf-8")
3180
+ for meta_path in (
3181
+ expert_plugin_dir / ".codebuddy-plugin" / "plugin.json",
3182
+ expert_plugin_dir / ".workbuddy-plugin" / "plugin.json",
3183
+ ):
3184
+ _atomic_write_global_file_tx(meta_path, meta_bytes)
3185
+ written.append({"path": str(meta_path), "status": "created", "backup": None, "created": True})
3186
+
3187
+ # 4. Skill copy
3188
+ skill_file = expert_plugin_dir / "skills" / "bugx" / "SKILL.md"
3189
+ _atomic_write_global_file_tx(skill_file, content.encode("utf-8"))
3190
+ written.append({"path": str(skill_file), "status": "created", "backup": None, "created": True})
3191
+
3192
+ # 5. Marketplace manifest
3193
+ market_manifest_path = my_experts_dir / ".codebuddy-plugin" / "marketplace.json"
3194
+ market_manifest: dict[str, object] = {
3195
+ "name": "my-experts",
3196
+ "description": "my-experts marketplace (auto-generated)",
3197
+ "plugins": []
3198
+ }
3199
+ if market_manifest_path.is_file():
3200
+ try:
3201
+ existing = json.loads(market_manifest_path.read_text(encoding="utf-8"))
3202
+ if isinstance(existing, dict):
3203
+ market_manifest = existing
3204
+ except (OSError, json.JSONDecodeError):
3205
+ pass
3206
+ plugins_list = market_manifest.get("plugins")
3207
+ if not isinstance(plugins_list, list):
3208
+ plugins_list = []
3209
+ market_manifest["plugins"] = plugins_list
3210
+ has_bugx = any(isinstance(p, dict) and p.get("name") == "bugx" for p in plugins_list)
3211
+ if not has_bugx:
3212
+ plugins_list.append({
3213
+ "name": "bugx",
3214
+ "source": "./plugins/bugx",
3215
+ "description": plugin_meta["description"]
3216
+ })
3217
+ _atomic_write_global_file_tx(
3218
+ market_manifest_path,
3219
+ (json.dumps(market_manifest, indent=2, ensure_ascii=False) + "\n").encode("utf-8")
3220
+ )
3221
+ written.append({"path": str(market_manifest_path), "status": "created", "backup": None, "created": True})
3222
+
3223
+ # 6. User experts
3224
+ custom_experts_root = config_root / "experts" / "custom"
3225
+ target_uids: set[str] = set()
3226
+ if custom_experts_root.is_dir():
3227
+ for entry in custom_experts_root.iterdir():
3228
+ if entry.is_dir() and not entry.name.startswith("."):
3229
+ target_uids.add(entry.name)
3230
+ settings_file = config_root / "settings.json"
3231
+ if settings_file.is_file():
3232
+ try:
3233
+ s_data = json.loads(settings_file.read_text(encoding="utf-8"))
3234
+ owner_uid = s_data.get("legacyOwnerUid")
3235
+ if owner_uid and isinstance(owner_uid, str) and "/" not in owner_uid:
3236
+ target_uids.add(owner_uid)
3237
+ except (OSError, json.JSONDecodeError):
3238
+ pass
3239
+ for uid in target_uids:
3240
+ user_experts_file = custom_experts_root / uid / "experts.json"
3241
+ existing_list: list[str] = []
3242
+ if user_experts_file.is_file():
3243
+ try:
3244
+ loaded_list = json.loads(user_experts_file.read_text(encoding="utf-8"))
3245
+ if isinstance(loaded_list, list):
3246
+ existing_list = [str(x) for x in loaded_list]
3247
+ except (OSError, json.JSONDecodeError):
3248
+ pass
3249
+ if "bugx" not in existing_list:
3250
+ existing_list.append("bugx")
3251
+ _atomic_write_global_file_tx(
3252
+ user_experts_file,
3253
+ (json.dumps(existing_list, indent=2, ensure_ascii=False) + "\n").encode("utf-8")
3254
+ )
3255
+ written.append({"path": str(user_experts_file), "status": "created", "backup": None, "created": True})
3256
+
3257
+ return {
3258
+ "root": str(expert_plugin_dir),
3259
+ "written": written,
3260
+ "backups": backups,
3261
+ }
3262
+
3263
+
3264
+ def _check_workbuddy_user_skill(root: Path, *, repair: bool = False) -> tuple[bool, str]:
3265
+ """Validate the WorkBuddy user-level Skill against the current template."""
3266
+ source = global_engine_root() / "bugx.md"
3267
+ if not source.is_file():
3268
+ return True, "项目尚未初始化,跳过用户级校验"
3269
+ skill = workbuddy_user_skill_root() / "skills" / "bugx" / "SKILL.md"
3270
+ if not skill.is_file():
3271
+ return False, "缺少用户级 Skill(<配置根>/skills/bugx/SKILL.md);请运行 bugx install --agent workbuddy"
3272
+ try:
3273
+ content = skill.read_text(encoding="utf-8")
3274
+ except (OSError, UnicodeDecodeError) as exc:
3275
+ return False, f"用户级 Skill 无法读取: {skill}: {exc}"
3276
+ locale = read_locale_marker(content)
3277
+ try:
3278
+ rendered = strip_locale_marker(
3279
+ get_adapter("workbuddy").render(source, locale=locale)
3280
+ ).strip()
3281
+ except CliError as exc:
3282
+ return False, str(exc)
3283
+ if strip_locale_marker(content).strip() != rendered:
3284
+ if repair:
3285
+ try:
3286
+ skill.parent.mkdir(parents=True, exist_ok=True)
3287
+ skill.write_text(rendered + "\n", encoding="utf-8")
3288
+ _ensure_workbuddy_custom_expert(root, rendered)
3289
+ return True, f"用户级 Skill 已自动修复对齐模板: {skill}"
3290
+ except OSError as exc:
3291
+ return False, f"用户级 Skill 与当前模板不一致,且自动修复失败: {skill}: {exc}"
3292
+ return False, f"用户级 Skill 与当前模板不一致: {skill}"
3293
+ return True, f"用户级 Skill 就绪: {skill}"
3294
+
3295
+
3296
+ def _incompatible_opencode_mcp_names(servers: object) -> list[str]:
3297
+ if not isinstance(servers, dict):
3298
+ return []
3299
+ return [
3300
+ name for name in OPENCODE_ALL_REQUIRED_MCP
3301
+ if name in servers and _mcp_entry_state(name, servers[name]) == "incompatible"
3302
+ ]
3303
+
3304
+
3305
+ def _reject_incompatible_opencode_mcp(names: list[str], target: Path) -> None:
3306
+ if names:
3307
+ raise CliError(
3308
+ f"OpenCode 配置包含已退役的 BugX MCP 命令({', '.join(names)}):{target}。"
3309
+ "此格式不再自动迁移或覆盖;请手动删除对应的 mcp 条目后,重新运行 "
3310
+ "`bugx install --agent opencode --root <项目路径>`。"
3311
+ )
3312
+
3313
+
3314
+ _OPENCODE_V1_CONFIG_KEYS = {"plugin", "permission", "tools", "agent"}
3315
+ _OPENCODE_REQUIRED_PLUGIN = "@dietrichgebert/ponytail"
3316
+
3317
+
3318
+ def _opencode_v2_servers(
3319
+ payload: dict[str, Any], target: Path, *, create: bool = False,
3320
+ ) -> dict[str, Any]:
3321
+ """Validate and return the OpenCode v2 ``mcp.servers`` map."""
3322
+ legacy = sorted(_OPENCODE_V1_CONFIG_KEYS.intersection(payload))
3323
+ if legacy:
3324
+ raise CliError(
3325
+ f"OpenCode 配置使用 v1 字段({', '.join(legacy)}):{target}。"
3326
+ "BugX 只写 OpenCode v2 格式,不自动迁移旧配置;请备份后按 v2 重建,"
3327
+ "再运行 `bugx install --agent opencode --root <项目路径>`。"
3328
+ )
3329
+ plugins = payload.get("plugins")
3330
+ if plugins is not None and not isinstance(plugins, list):
3331
+ raise CliError(f"OpenCode v2 配置的 plugins 必须是数组:{target}")
3332
+
3333
+ if "mcp" not in payload:
3334
+ if not create:
3335
+ return {}
3336
+ payload["mcp"] = {}
3337
+ mcp = payload["mcp"]
3338
+ if not isinstance(mcp, dict):
3339
+ raise CliError(f"OpenCode v2 配置的 mcp 必须是对象:{target}")
3340
+ servers = mcp.get("servers")
3341
+ if servers is None:
3342
+ if mcp:
3343
+ raise CliError(
3344
+ f"OpenCode 配置的 MCP server 必须位于 mcp.servers:{target}。"
3345
+ "检测到旧的扁平 mcp 结构,BugX 不自动迁移;请备份后按 v2 重建。"
3346
+ )
3347
+ if not create:
3348
+ return {}
3349
+ servers = {}
3350
+ mcp["servers"] = servers
3351
+ if not isinstance(servers, dict):
3352
+ raise CliError(f"OpenCode v2 配置的 mcp.servers 必须是对象:{target}")
3353
+ legacy_entries = sorted(
3354
+ str(name) for name, entry in servers.items()
3355
+ if isinstance(entry, dict) and "enabled" in entry
3356
+ )
3357
+ if legacy_entries:
3358
+ raise CliError(
3359
+ f"OpenCode v2 MCP 条目使用已退役的 enabled 字段:{', '.join(legacy_entries)}。"
3360
+ "请改用 disabled(仅停用时设为 true),然后重新运行安装。"
3361
+ )
3362
+ return servers
3363
+
3364
+
3365
+ def _preflight_opencode_mcp_config(root: Path) -> None:
3366
+ """Reject OpenCode v1 config before install writes project or engine state."""
3367
+ target = root.resolve() / CONFIG_NAME
3368
+ _assert_no_symlink_components(target)
3369
+ if target.is_symlink():
3370
+ raise CliError(_i18n_exc(
3371
+ "agent.opencode_symlink_config_refused",
3372
+ f"拒绝使用符号链接 OpenCode 配置: {target}", target=target,
3373
+ ))
3374
+ if not target.exists():
3375
+ return
3376
+ if not target.is_file():
3377
+ raise CliError(_i18n_exc(
3378
+ "agent.opencode_config_not_regular_file",
3379
+ f"OpenCode 配置不是普通文件: {target}", target=target,
3380
+ ))
3381
+ try:
3382
+ payload = json.loads(target.read_text(encoding="utf-8"))
3383
+ except (OSError, json.JSONDecodeError) as exc:
3384
+ raise CliError(_i18n_exc(
3385
+ "agent.opencode_existing_unparseable",
3386
+ f"已有 OpenCode 配置无法解析,未修改: {target}: {exc}",
3387
+ target=target, exc=exc,
3388
+ )) from exc
3389
+ if not isinstance(payload, dict):
3390
+ raise CliError(_i18n_exc(
3391
+ "agent.opencode_existing_not_object",
3392
+ f"已有 OpenCode 配置顶层必须是 JSON 对象,未修改: {target}",
3393
+ target=target,
3394
+ ))
3395
+ servers = _opencode_v2_servers(payload, target)
3396
+ _reject_incompatible_opencode_mcp(_incompatible_opencode_mcp_names(servers), target)
3397
+
3398
+
3399
+ def _ensure_opencode_config(
3400
+ root: Path, *, selected: set[str] | None = None,
3401
+ ) -> tuple[str, Path | None]:
3402
+ """Create or safely merge the bundled OpenCode MCP configuration.
3403
+
3404
+ Existing user entries are retained. Missing BugX-recommended MCP entries
3405
+ are added after a recoverable backup in ``.bugx/backups/opencode``. Retired
3406
+ managed commands are rejected before any config backup or write.
3407
+
3408
+ **注入白名单**(DOC-236):只写 BugX 自有控制通道 + **本轮被定向且已安装**的
3409
+ 外部 server。模板里的外部条目只是"目录",不能因为列在模板里就写进项目配置:
3410
+ 未安装会让宿主启动即失败,disabled(供应链未证实)更是绝不该出现。
3411
+ """
3412
+ target = root.resolve() / CONFIG_NAME
3413
+ _assert_no_symlink_components(target)
3414
+ if target.is_symlink():
3415
+ raise CliError(_i18n_exc("agent.opencode_symlink_config_refused", f"拒绝使用符号链接 OpenCode 配置: {target}", target=target))
3416
+ source = bundled_config()
3417
+ if source.is_symlink() or not source.is_file():
3418
+ raise CliError(_i18n_exc("agent.opencode_template_insecure", f"OpenCode 配置模板不存在或不安全: {source}", source=source))
3419
+ try:
3420
+ bundled = json.loads(source.read_text(encoding="utf-8"))
3421
+ except (OSError, json.JSONDecodeError) as exc:
3422
+ raise CliError(_i18n_exc("agent.opencode_template_invalid", f"OpenCode 配置模板无效: {source}: {exc}", source=source, exc=exc)) from exc
3423
+ if not isinstance(bundled, dict):
3424
+ raise CliError(_i18n_exc("agent.opencode_template_invalid", f"OpenCode 配置模板顶层必须是对象: {source}", source=source))
3425
+ try:
3426
+ bundled_servers = _opencode_v2_servers(bundled, source)
3427
+ except CliError as exc:
3428
+ raise CliError(f"OpenCode v2 配置模板无效: {exc}") from exc
3429
+ bundled_plugins = bundled.get("plugins")
3430
+ if not isinstance(bundled_plugins, list) or _OPENCODE_REQUIRED_PLUGIN not in bundled_plugins:
3431
+ raise CliError(f"OpenCode v2 配置模板缺少 plugins 中的 {_OPENCODE_REQUIRED_PLUGIN}: {source}")
3432
+ # 注入白名单:自有控制通道 + (被定向 ∩ 已安装)的外部 server。
3433
+ core_channels = {"bugx-supervisor", "bugx-supervisor-worker", "bugx-docs"}
3434
+ available = installed_runtime_servers()
3435
+ keep = core_channels | (set(selected or ()) & available)
3436
+ # 仅移除当前配置中不属于本轮注入白名单、且精确匹配受管理模板的可选项。
3437
+ # 已知退役命令在进入合并前就会被拒绝,不会在这里被静默清理或升级。
3438
+ dropped_names = {
3439
+ name for name in OPENCODE_ALL_REQUIRED_MCP
3440
+ if name not in keep
3441
+ }
3442
+ for name in list(bundled_servers):
3443
+ if name not in keep:
3444
+ bundled_servers.pop(name, None)
3445
+ if target.exists():
3446
+ if not target.is_file():
3447
+ raise CliError(_i18n_exc("agent.opencode_config_not_regular_file", f"OpenCode 配置不是普通文件: {target}", target=target))
3448
+ try:
3449
+ payload = json.loads(target.read_text(encoding="utf-8"))
3450
+ except (OSError, json.JSONDecodeError) as exc:
3451
+ raise CliError(_i18n_exc("agent.opencode_existing_unparseable", f"已有 OpenCode 配置无法解析,未修改: {target}: {exc}", target=target, exc=exc)) from exc
3452
+ if not isinstance(payload, dict):
3453
+ raise CliError(_i18n_exc("agent.opencode_existing_not_object", f"已有 OpenCode 配置顶层必须是 JSON 对象,未修改: {target}", target=target))
3454
+ servers = _opencode_v2_servers(payload, target, create=True)
3455
+ _reject_incompatible_opencode_mcp(
3456
+ _incompatible_opencode_mcp_names(servers), target,
3457
+ )
3458
+ configuration_changed = False
3459
+ plugins = payload.get("plugins")
3460
+ if plugins is None:
3461
+ plugins = []
3462
+ payload["plugins"] = plugins
3463
+ configuration_changed = True
3464
+ if not isinstance(plugins, list):
3465
+ raise CliError(f"OpenCode v2 配置的 plugins 必须是数组:{target}")
3466
+ if _OPENCODE_REQUIRED_PLUGIN not in plugins:
3467
+ plugins.append(_OPENCODE_REQUIRED_PLUGIN)
3468
+ configuration_changed = True
3469
+ # OpenCode Code Mode is disabled in BugX agents so their MCP calls must
3470
+ # use the explicit, permission-checked direct tool names. Apply this to
3471
+ # every BugX-managed server present in this install, including Docs and
3472
+ # selected optional runtimes.
3473
+ managed_names = [name for name in OPENCODE_ALL_REQUIRED_MCP if name in bundled_servers]
3474
+ for name in managed_names:
3475
+ entry = servers.get(name)
3476
+ if (
3477
+ isinstance(entry, dict)
3478
+ and _mcp_entry_state(name, entry) == "configured"
3479
+ and entry.get("codemode") is not False
3480
+ ):
3481
+ entry["codemode"] = False
3482
+ configuration_changed = True
3483
+ remove_unavailable_optional = [
3484
+ name for name in dropped_names
3485
+ if _mcp_entry_state(name, servers.get(name)) == "configured"
3486
+ ]
3487
+ missing = [
3488
+ name for name in managed_names
3489
+ if not isinstance(servers.get(name), dict)
3490
+ ]
3491
+ if not missing and not remove_unavailable_optional and not configuration_changed:
3492
+ return "unchanged", None
3493
+ backup = _backup_opencode_config(root, target)
3494
+ for name in remove_unavailable_optional:
3495
+ servers.pop(name, None)
3496
+ for name in missing:
3497
+ servers[name] = copy.deepcopy(bundled_servers[name])
3498
+ updated = json.dumps(payload, ensure_ascii=False, indent=2) + "\n"
3499
+ descriptor, temporary = tempfile.mkstemp(
3500
+ dir=str(target.parent), prefix=f".{target.name}.", suffix=".tmp",
3501
+ )
3502
+ try:
3503
+ with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
3504
+ handle.write(updated)
3505
+ os.chmod(temporary, target.stat().st_mode)
3506
+ os.replace(temporary, target)
3507
+ except BaseException:
3508
+ try:
3509
+ os.unlink(temporary)
3510
+ except OSError:
3511
+ pass
3512
+ raise
3513
+ return "merged", backup
3514
+
3515
+ target.parent.mkdir(parents=True, exist_ok=True)
3516
+ descriptor, temporary = tempfile.mkstemp(
3517
+ dir=str(target.parent), prefix=f".{target.name}.", suffix=".tmp",
3518
+ )
3519
+ try:
3520
+ with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
3521
+ handle.write(json.dumps(bundled, ensure_ascii=False, indent=2) + "\n")
3522
+ os.chmod(temporary, source.stat().st_mode & 0o777)
3523
+ os.replace(temporary, target)
3524
+ except BaseException:
3525
+ try:
3526
+ os.unlink(temporary)
3527
+ except OSError:
3528
+ pass
3529
+ raise
3530
+ return "created", None
3531
+
3532
+
3533
+ def _check_host_mcp_config(root: Path, host_name: str, *, repair: bool = False) -> tuple[bool, str]:
3534
+ """Validate MCP configurations across all supported AI Agent hosts.
3535
+
3536
+ Inspects each host's native configuration entry (.opencode/opencode.json,
3537
+ .dsh/patch.yml or preset, .claude.json/.mcp.json for Claude, .codex/config,
3538
+ .pi extension manifest, or ChatGPT marketplace) to check if the required BugX
3539
+ Supervisor MCP or client dependencies are properly configured.
3540
+
3541
+ 这里刻意保留按宿主名的分派,而不是收敛为 ``adapter.supports(...)``:每个
3542
+ 分支是**宿主专属的诊断规则**(各自的文件布局、必需项和用户可见文案),
3543
+ 不是同一种能力的参数化差异。把它下沉到适配器需要 agent 层的
3544
+ ``_check_opencode_config`` / ``_dsh_home`` / ``_check_workbuddy_user_skill``
3545
+ 与 plugin 层的 ``_validate_host_supervisor_mcp`` 跨模块搬移,收益低于
3546
+ 引入循环依赖的风险。安装流程(``_command_agent_impl``)已改为能力查询。
3547
+ """
3548
+ root = root.resolve()
3549
+ if host_name == "opencode":
3550
+ return _check_opencode_config(root)
3551
+
3552
+ if host_name == "dsh":
3553
+ patch_file = root / ".dsh" / "patch.yml"
3554
+ user_preset = _dsh_home() / ".agent-presets" / "bugx" / "agent.cordis.yml"
3555
+ ui_root = _dsh_home() / "plugins" / "bugx-ui"
3556
+ ui_files = ("package.json", "cordis.patch.yml", "index.js", "client.js")
3557
+ missing_ui = [name for name in ui_files if not (ui_root / name).is_file()]
3558
+ ui_detail = ""
3559
+ if missing_ui:
3560
+ ui_detail = ";缺少 DSH UI 包文件:" + "、".join(missing_ui)
3561
+ else:
3562
+ profile = _dsh_home() / "profiles" / "web" / "package.json"
3563
+ try:
3564
+ ui_manifest = json.loads(
3565
+ (ui_root / "package.json").read_text(encoding="utf-8")
3566
+ )
3567
+ profile_manifest = (
3568
+ json.loads(profile.read_text(encoding="utf-8"))
3569
+ if profile.is_file() else None
3570
+ )
3571
+ except (OSError, json.JSONDecodeError):
3572
+ ui_manifest = profile_manifest = None
3573
+ ui_name = (
3574
+ ui_manifest.get("name") if isinstance(ui_manifest, dict) else None
3575
+ )
3576
+ dsh_client = (
3577
+ isinstance(ui_manifest, dict)
3578
+ and isinstance(ui_manifest.get("dsh"), dict)
3579
+ and isinstance(ui_manifest["dsh"].get("client"), dict)
3580
+ and "./client" in (ui_manifest.get("exports") or {})
3581
+ )
3582
+ bundles = (
3583
+ profile_manifest.get("dsh", {}).get("profile", {}).get("bundles", [])
3584
+ if isinstance(profile_manifest, dict) else []
3585
+ )
3586
+ dependencies = (
3587
+ profile_manifest.get("dependencies", {})
3588
+ if isinstance(profile_manifest, dict) else {}
3589
+ )
3590
+ if not dsh_client or not isinstance(ui_name, str):
3591
+ ui_detail = ";DSH UI 包 manifest 缺少 dsh.client 或 ./client 导出"
3592
+ elif profile.is_file() and (ui_name not in bundles or ui_name not in dependencies):
3593
+ ui_detail = ";DSH UI 包未注册到 web profile,请重新运行 bugx install --agent dsh"
3594
+ elif not profile.is_file():
3595
+ ui_detail = ";已暂存 DSH UI 包(当前未发现 web profile)"
3596
+ else:
3597
+ ui_detail = ";DSH UI 图标包已注册到 web profile"
3598
+ if patch_file.is_file() or user_preset.is_file():
3599
+ content = ""
3600
+ if patch_file.is_file():
3601
+ content += patch_file.read_text(encoding="utf-8", errors="ignore")
3602
+ if user_preset.is_file():
3603
+ content += user_preset.read_text(encoding="utf-8", errors="ignore")
3604
+ has_supervisor = "bugx-supervisor" in content or "mcp-client" in content
3605
+ has_native_question = "@deepseek-ai/dsh-tool-ask-user" in content
3606
+ if has_supervisor and has_native_question:
3607
+ if missing_ui or ui_detail.startswith(";DSH UI 包未") or ui_detail.startswith(";DSH UI 包 manifest"):
3608
+ return False, "已包含 Agent 通道,但" + ui_detail.lstrip(";")
3609
+ return True, "已包含 bugx-supervisor MCP、DSH ask_user_question 原生单选工具" + ui_detail
3610
+ missing = []
3611
+ if not has_supervisor:
3612
+ missing.append("bugx-supervisor MCP")
3613
+ if not has_native_question:
3614
+ missing.append("ask_user_question(@deepseek-ai/dsh-tool-ask-user)原生问答工具")
3615
+ return False, "缺少 " + "、".join(missing) + ui_detail + ";请运行 bugx install --agent dsh"
3616
+ return False, "缺少 .dsh/patch.yml 或全局预设;请运行 bugx install --agent dsh"
3617
+
3618
+ if host_name == "claude":
3619
+ claude_mcp = root / ".mcp.json"
3620
+ claude_project = root / ".claude" / "mcp.json"
3621
+ candidates = (
3622
+ (claude_mcp, "flat"),
3623
+ (claude_project, "flat"),
3624
+ )
3625
+ ok, detail = _validate_host_supervisor_mcp(candidates, root)
3626
+ user_agents_dir = _claude_user_agents_dir()
3627
+ user_main = user_agents_dir / "bugx.md"
3628
+ user_worker = user_agents_dir / "bugx-worker.md"
3629
+ missing_user = [
3630
+ name for name, path in (("bugx", user_main), ("bugx-worker", user_worker))
3631
+ if not path.is_file()
3632
+ ]
3633
+ entry = root / ".claude" / "agents" / "bugx.md"
3634
+ has_entry = (entry.is_file() and not entry.is_symlink()) or not missing_user
3635
+ if ok and has_entry:
3636
+ user_status = "(含用户级智能体)" if not missing_user else ""
3637
+ return True, f"{detail};Claude Code Agent 入口已就绪{user_status}"
3638
+ if ok and not has_entry:
3639
+ return True, detail
3640
+ if entry.is_file() and not entry.is_symlink():
3641
+ return True, "Claude Code Agent 入口已就绪 (.claude/agents/bugx.md)"
3642
+ if not missing_user:
3643
+ return True, f"Claude Code 用户级智能体已就绪({user_agents_dir})"
3644
+ return False, "缺少 Claude Code Agent 入口 .claude/agents/bugx.md;请运行 bugx install --agent claude"
3645
+
3646
+ if host_name == "funide":
3647
+ project_ok, project_detail = _validate_host_supervisor_mcp(
3648
+ ((root / ".mcp.json", "flat"),), root,
3649
+ )
3650
+ native_mcp_path = _funide_profile_mcp_path()
3651
+ native_mcp_ok, native_mcp_detail = _validate_host_supervisor_mcp(
3652
+ ((native_mcp_path, "funide"),), root,
3653
+ )
3654
+ ok = project_ok and native_mcp_ok
3655
+ detail = project_detail if project_ok else project_detail
3656
+ if not native_mcp_ok:
3657
+ detail += ";FunIDE 用户级 MCP:" + native_mcp_detail
3658
+ project_entry = root / ".github" / "agents" / "bugx.agent.md"
3659
+ user_entry = _funide_user_agents_dir() / "bugx.agent.md"
3660
+ has_project = project_entry.is_file() and not project_entry.is_symlink()
3661
+ has_user = user_entry.is_file() and not user_entry.is_symlink()
3662
+ native_registry = _funide_data_dir() / "agents.json"
3663
+ has_native = False
3664
+ try:
3665
+ native_data = json.loads(native_registry.read_text(encoding="utf-8"))
3666
+ has_native = isinstance(native_data, dict) and any(
3667
+ isinstance(item, dict)
3668
+ and item.get("id") == "bugx"
3669
+ and _NATIVE_AGENT_OWNERSHIP_MARK in str(item.get("systemPrompt", ""))
3670
+ for item in native_data.get("agents", [])
3671
+ )
3672
+ except (OSError, UnicodeDecodeError, json.JSONDecodeError):
3673
+ has_native = False
3674
+ native_skill = _funide_user_skills_dir() / "bugx" / "SKILL.md"
3675
+ has_skill = False
3676
+ try:
3677
+ has_skill = native_skill.is_file() and "<!-- BugX managed FunIDE native skill -->" in native_skill.read_text(encoding="utf-8")
3678
+ except (OSError, UnicodeDecodeError):
3679
+ has_skill = False
3680
+ if ok and (has_project or has_user) and has_native and has_skill:
3681
+ surfaces = []
3682
+ if has_project:
3683
+ surfaces.append("项目级 .github/agents/bugx.agent.md")
3684
+ if has_user:
3685
+ surfaces.append(f"用户级 {user_entry}")
3686
+ surfaces.append(f"设置页原生注册 {native_registry}")
3687
+ surfaces.append(f"设置页原生技能 {native_skill}")
3688
+ surfaces.append(f"设置页用户 MCP {native_mcp_path}")
3689
+ return True, detail + ";FunIDE Agent/Skill/MCP 入口已就绪(" + "、".join(surfaces) + ")"
3690
+ if not has_project and not has_user:
3691
+ detail += ";缺少项目级 .github/agents/bugx.agent.md 与用户级 ~/.copilot/agents/bugx.agent.md"
3692
+ elif not has_native:
3693
+ detail += f";缺少 FunIDE 设置页原生智能体注册 {native_registry}"
3694
+ elif not has_skill:
3695
+ detail += f";缺少 FunIDE 设置页原生技能 {native_skill}"
3696
+ elif not native_mcp_ok:
3697
+ detail += f";缺少 FunIDE 设置页用户 MCP {native_mcp_path}"
3698
+ elif not ok:
3699
+ detail += ";Agent 入口存在但不能替代 FunIDE MCP 配置"
3700
+ return False, detail + ";请运行 bugx install --agent funide"
3701
+
3702
+ if host_name == "zcode":
3703
+ # PE-20261004-003:ZCode 只读用户级 ~/.zcode/cli/config.json 的
3704
+ # mcp.servers(无工作区级 MCP 作用域),注册与校验都必须落在那里;
3705
+ # 用户级配置只保留插件目录登记,避免同名全局服务器覆盖项目根。
3706
+ ok, detail = _validate_zcode_global_supervisor_mcp(root)
3707
+ if ok:
3708
+ return ok, detail
3709
+ # 0.7.22:主/worker 子智能体均收敛为仅用户级注册,doctor 改查
3710
+ # 用户级注册面(storage.dir/agents,默认 ~/.zcode/agents)。
3711
+ user_agents_dir = _zcode_user_agents_dir()
3712
+ user_main = user_agents_dir / "bugx.md"
3713
+ user_worker = user_agents_dir / "bugx-worker.md"
3714
+ missing = [
3715
+ name for name, path in (("bugx", user_main), ("bugx-worker", user_worker))
3716
+ if not path.is_file()
3717
+ ]
3718
+ if not missing:
3719
+ return False, detail + ";用户级子智能体已注册但不能替代 MCP 配置"
3720
+ return False, (
3721
+ detail
3722
+ + ";缺少用户级子智能体 " + "、".join(missing)
3723
+ + f"({user_agents_dir},重跑 bugx install --agent zcode 补齐)"
3724
+ )
3725
+
3726
+ # 宿主专属安装诊断:按约定模块名调用 ``plugin_<host>.validate_install`` 钩子。
3727
+ # 通用层不再持有「某宿主的入口在哪、MCP 写在哪个作用域」这类事实。
3728
+ validate_install = engine_host_cli_hook(host_name, "validate_install")
3729
+ if validate_install is not None:
3730
+ return validate_install(root)
3731
+
3732
+ if host_name == "trea":
3733
+ # DOC-169 / DOC-210:补全 Trea 的 MCP 校验分支(项目 flat 候选 + Agent 入口,支持 Trae 与 Trae CN 变体)。
3734
+ candidates = (
3735
+ (root / ".trea" / "mcp.json", "flat"),
3736
+ (root / ".trae" / "mcp.json", "flat"),
3737
+ (root / ".trae-cn" / "mcp.json", "flat"),
3738
+ (root / ".mcp.json", "flat"),
3739
+ )
3740
+ ok, detail = _validate_host_supervisor_mcp(candidates, root)
3741
+ trea_entry_candidates = (
3742
+ root / ".trea" / "agents" / "bugx.md",
3743
+ root / ".trae" / "agents" / "bugx.md",
3744
+ root / ".trae-cn" / "agents" / "bugx.md",
3745
+ )
3746
+ has_entry = any(p.is_file() for p in trea_entry_candidates)
3747
+ if ok and has_entry:
3748
+ return True, detail + ";Trea Agent 入口已就绪"
3749
+ if not has_entry:
3750
+ detail += ";缺少 .trea/agents/bugx.md(或 .trae/.trae-cn 变体)"
3751
+ elif not ok:
3752
+ detail += ";Agent 入口存在但不能替代 Trea MCP 配置"
3753
+ return False, detail + ";请运行 bugx install --agent trea"
3754
+
3755
+ if host_name == "pi":
3756
+ ext_manifest = root / ".pi" / "extensions" / "bugx" / "manifest.json"
3757
+ skill_file = root / ".pi" / "skills" / "bugx" / "SKILL.md"
3758
+ if ext_manifest.is_file() and skill_file.is_file():
3759
+ return True, "Pi 扩展与技能包均存在,扩展已包含 MCP / stdio 适配支持"
3760
+ return False, "Pi 扩展或技能包缺失;请运行 bugx install --agent pi"
3761
+
3762
+ if host_name == "chatgpt":
3763
+ marketplace = root / ".agents" / "plugins" / "marketplace.json"
3764
+ if marketplace.is_file():
3765
+ return True, "ChatGPT Marketplace 清单已登记 BugX 插件与资源契约"
3766
+ return False, "缺少 .agents/plugins/marketplace.json;请运行 bugx install --agent chatgpt"
3767
+
3768
+ if host_name == "workbuddy":
3769
+ from ..host_adapters import WORKBUDDY_PROJECT_PATHS
3770
+
3771
+ missing = [relative for relative in WORKBUDDY_PROJECT_PATHS
3772
+ if not (root / relative).is_file()]
3773
+ if missing:
3774
+ return False, "缺少 " + "、".join(missing) + ";请运行 bugx install --agent workbuddy"
3775
+ connector_root = root / ".workbuddy" / "connector" / "bugx"
3776
+ connector_files = (
3777
+ connector_root / "connector-meta.json",
3778
+ connector_root / "icon.png",
3779
+ connector_root / "skills" / "bugx" / "SKILL.md",
3780
+ )
3781
+ if any(not path.is_file() for path in connector_files):
3782
+ return False, "缺少 WorkBuddy Connector 图标包;请运行 bugx install --agent workbuddy"
3783
+ try:
3784
+ connector_meta = json.loads(
3785
+ (connector_root / "connector-meta.json").read_text(encoding="utf-8")
3786
+ )
3787
+ except (OSError, json.JSONDecodeError):
3788
+ connector_meta = None
3789
+ if not isinstance(connector_meta, dict) or connector_meta.get("type") != "skill-only":
3790
+ return False, "WorkBuddy Connector 元数据无效;请运行 bugx install --agent workbuddy"
3791
+ user_ok, user_detail = _check_workbuddy_user_skill(root, repair=repair)
3792
+ if not user_ok:
3793
+ return False, user_detail
3794
+
3795
+ # DOC-181 方案 2:WorkBuddy 沙箱 Python 运行态一致性检查与自愈
3796
+ from ..host_adapters import workbuddy_cli_venv, workbuddy_cli_venv_version
3797
+ venv = workbuddy_cli_venv()
3798
+ venv_detail = ""
3799
+ if venv is not None:
3800
+ from ..infra.engine_installer import _contract_version
3801
+ venv_ver = workbuddy_cli_venv_version(venv)
3802
+ if venv_ver and _contract_version(venv_ver) != _contract_version(__version__):
3803
+ if repair:
3804
+ synced, sync_msg = _sync_workbuddy_private_venv(
3805
+ asset_root(), target_version=__version__,
3806
+ )
3807
+ if synced:
3808
+ venv_detail = f";WorkBuddy 沙箱运行态已自动升级至 {__version__}"
3809
+ else:
3810
+ return False, f"WorkBuddy 沙箱运行态升级失败: {sync_msg}"
3811
+ else:
3812
+ return False, (
3813
+ f"WorkBuddy 沙箱运行态版本滞后: {venv} (包版本 {venv_ver} != 当前 CLI {__version__});"
3814
+ "请运行 `bugx doctor --repair` 或 `bugx install --agent workbuddy` 自动同步"
3815
+ )
3816
+ elif venv_ver:
3817
+ venv_detail = f";WorkBuddy 沙箱运行态就绪 ({venv_ver})"
3818
+
3819
+ return True, "WorkBuddy `.workbuddy` 与 CodeBuddy 兼容 Skill 入口、Connector 图标包均已就绪;" + user_detail + venv_detail
3820
+
3821
+ if host_name == HOST_NAME_QODER:
3822
+ qoder_mcp = root / ".qoder" / "mcp.json"
3823
+ project_mcp = root / ".mcp.json"
3824
+ candidates = (
3825
+ (qoder_mcp, "flat"),
3826
+ (project_mcp, "flat"),
3827
+ )
3828
+ from .plugin_qoder import _clean_legacy_qoder_plugin_and_skills, _qoder_user_agents_dir
3829
+
3830
+ legacy_warning = ""
3831
+ if repair:
3832
+ _clean_legacy_qoder_plugin_and_skills()
3833
+ else:
3834
+ from .plugin_qoder import (
3835
+ _qoder_user_mcp_path, _qoder_user_plugins_dir,
3836
+ _qoder_user_settings_path, _qoder_user_skills_dir,
3837
+ )
3838
+ legacy_paths = (
3839
+ _qoder_user_skills_dir() / "bugx",
3840
+ _qoder_user_plugins_dir() / "cache" / "bugx-agent",
3841
+ )
3842
+ has_legacy = any(path.exists() or path.is_symlink() for path in legacy_paths)
3843
+ registry_paths = (
3844
+ _qoder_user_plugins_dir() / "installed_plugins_v2.json",
3845
+ _qoder_user_plugins_dir() / "installed_plugins.json",
3846
+ _qoder_user_settings_path(),
3847
+ _qoder_user_mcp_path(),
3848
+ )
3849
+ for path in registry_paths:
3850
+ if not path.is_file() or path.is_symlink():
3851
+ continue
3852
+ try:
3853
+ payload = json.loads(path.read_text(encoding="utf-8"))
3854
+ except (OSError, UnicodeError, json.JSONDecodeError):
3855
+ continue
3856
+ if path.name.startswith("installed_plugins"):
3857
+ has_legacy |= "bugx@bugx-agent" in (payload.get("plugins") or {}) if isinstance(payload, dict) else False
3858
+ elif path == _qoder_user_settings_path():
3859
+ has_legacy |= "bugx@bugx-agent" in (payload.get("enabledPlugins") or {}) if isinstance(payload, dict) else False
3860
+ else:
3861
+ servers = payload.get("mcpServers") if isinstance(payload, dict) else None
3862
+ has_legacy |= isinstance(servers, dict) and any(
3863
+ name in {"bugx-supervisor", "bugx-supervisor-worker", "bugx-docs"}
3864
+ or (isinstance(value, dict) and any("bugx" in str(arg).lower()
3865
+ for arg in value.get("args", [])))
3866
+ for name, value in servers.items()
3867
+ )
3868
+ if has_legacy:
3869
+ legacy_warning = ";发现用户级 Qoder 遗留配置,可运行 `bugx doctor --repair` 清理"
3870
+
3871
+ ok, detail = _validate_host_supervisor_mcp(candidates, root)
3872
+ user_agents_dir = _qoder_user_agents_dir()
3873
+ user_main = user_agents_dir / "bugx.md"
3874
+ user_worker = user_agents_dir / "bugx-worker.md"
3875
+ project_agent = root / ".qoder" / "agents" / "bugx.md"
3876
+
3877
+ has_project_agent = project_agent.is_file() and not project_agent.is_symlink()
3878
+ missing_user = [
3879
+ name for name, path in (("bugx", user_main), ("bugx-worker", user_worker))
3880
+ if not path.is_file()
3881
+ ]
3882
+
3883
+ if repair:
3884
+ from .plugin_qoder import _ensure_qoder_user_agents
3885
+ _ensure_qoder_user_agents(root, source=asset_root())
3886
+ if not ok:
3887
+ write_host_mcp_config(root, host_name)
3888
+ ok, detail = _validate_host_supervisor_mcp(candidates, root)
3889
+ missing_user = [
3890
+ name for name, path in (("bugx", user_main), ("bugx-worker", user_worker))
3891
+ if not path.is_file()
3892
+ ]
3893
+
3894
+ if ok and (has_project_agent or not missing_user):
3895
+ user_status = "(含用户级智能体)" if not missing_user else ""
3896
+ return True, f"{detail};Qoder Agent 入口已就绪{user_status}{legacy_warning}"
3897
+ if not ok:
3898
+ return False, f"{detail};请运行 bugx install --agent qoder{legacy_warning}"
3899
+ return False, "缺少 Qoder Agent 入口(.qoder/agents/bugx.md 或 ~/.qoder/agents/bugx.md);请运行 bugx install --agent qoder" + legacy_warning
3900
+
3901
+ return False, f"未知宿主 MCP 校验规则: {host_name}"
3902
+
3903
+
3904
+ def _detected_host_name(root: Path | None = None) -> str:
3905
+ """当前宿主的规范名;无法识别时返回 ``unknown``(绝不猜成 opencode)。
3906
+
3907
+ 身份唯一权威是进程祖先链探查(DOC-217 D211.3 已废除 ``BUGX_HOST`` 覆盖),
3908
+ 因此这里直接问引擎适配器,不读环境变量、也不看「哪个宿主装了 CLI」。
3909
+ """
3910
+ try:
3911
+ from core.host_runtime.adapters import detect_host
3912
+
3913
+ adapter = detect_host(root or Path.cwd())
3914
+ except Exception: # pragma: no cover - 探查失败即 unknown,由调用方如实上报
3915
+ return "unknown"
3916
+ name = str(getattr(adapter, "name", "") or "").strip()
3917
+ return name or "unknown"
3918
+
3919
+
3920
+ def _check_opencode_config(root: Path) -> tuple[bool, str]:
3921
+ """Validate the recommended MCP entries for an installed OpenCode bundle."""
3922
+ path = root.resolve() / CONFIG_NAME
3923
+ if path.is_symlink() or not path.is_file():
3924
+ return False, f"缺少 {CONFIG_NAME};请重新运行 bugx install --agent opencode"
3925
+ try:
3926
+ payload = json.loads(path.read_text(encoding="utf-8"))
3927
+ except (OSError, json.JSONDecodeError) as exc:
3928
+ return False, f"{CONFIG_NAME} 无法解析:{exc}"
3929
+ if not isinstance(payload, dict):
3930
+ return False, f"{CONFIG_NAME} 顶层必须是 JSON 对象"
3931
+ try:
3932
+ servers = _opencode_v2_servers(payload, path)
3933
+ except CliError as exc:
3934
+ return False, str(exc)
3935
+ plugins = payload.get("plugins")
3936
+ plugin_ready = isinstance(plugins, list) and _OPENCODE_REQUIRED_PLUGIN in plugins
3937
+ # lock 停用的 server(SPIKE-008-01 未通过)不要求启用,但配置必须与
3938
+ # lock 姿态一致:不得在宿主侧自行启用。
3939
+ lock_disabled = _lock_disabled_servers()
3940
+ # 只有**内建通道**必须启用;外部能力(playwright/dbhub/redis…)按需启用——
3941
+ # 它们需要 runtime 载荷与凭据,宿主侧默认停用是正常姿态(F-234-03 同类修复:
3942
+ # 此前这里硬编码豁免 {"playwright", "postmcp"},新增能力即漏判)。
3943
+ active_required = [
3944
+ name for name in OPENCODE_LOCAL_MCP if name not in lock_disabled
3945
+ ]
3946
+ missing = [
3947
+ name for name in active_required
3948
+ if not isinstance(servers.get(name), dict)
3949
+ ]
3950
+ disabled = [
3951
+ name for name in active_required
3952
+ if _mcp_entry_state(name, servers.get(name)) == "disabled"
3953
+ ]
3954
+ direct_tools_hidden = [
3955
+ name for name in OPENCODE_ALL_REQUIRED_MCP
3956
+ if isinstance(servers.get(name), dict)
3957
+ if (
3958
+ _mcp_entry_state(name, servers[name]) == "configured"
3959
+ and servers[name].get("codemode") is not False
3960
+ )
3961
+ ]
3962
+ incompatible = _incompatible_opencode_mcp_names(servers)
3963
+ custom = [
3964
+ name for name in OPENCODE_ALL_REQUIRED_MCP
3965
+ if name in servers and name not in missing
3966
+ and _mcp_entry_state(name, servers[name]) == "custom"
3967
+ ]
3968
+ conflicts = [
3969
+ name for name in sorted(lock_disabled)
3970
+ if isinstance(servers.get(name), dict)
3971
+ and servers[name].get("disabled") is not True
3972
+ ]
3973
+ details = []
3974
+ if not plugin_ready:
3975
+ details.append(f"plugins 缺少 {_OPENCODE_REQUIRED_PLUGIN}")
3976
+ if missing:
3977
+ details.append("缺少 " + ", ".join(missing))
3978
+ if disabled:
3979
+ details.append("已禁用 " + ", ".join(disabled))
3980
+ if direct_tools_hidden:
3981
+ details.append(
3982
+ "Code Mode 未关闭,BugX 工具不会作为原生工具直接暴露: "
3983
+ + ", ".join(direct_tools_hidden)
3984
+ )
3985
+ if incompatible:
3986
+ details.append(
3987
+ "旧版 BugX MCP 命令已拒绝自动迁移,请手动删除对应 mcp 条目后重新安装: "
3988
+ + ", ".join(incompatible)
3989
+ )
3990
+ if custom:
3991
+ details.append("自定义/未验证 " + ", ".join(custom))
3992
+ if conflicts:
3993
+ details.append(
3994
+ "lock 已停用但配置仍启用(启动会被 runtime 拒绝): "
3995
+ + ", ".join(conflicts)
3996
+ )
3997
+ if details:
3998
+ return False, f"{CONFIG_NAME} MCP 配置不完整:" + ";".join(details)
3999
+ note = ""
4000
+ if lock_disabled:
4001
+ note = f"({'、'.join(sorted(lock_disabled))} 按 mcp-lock.json 停用,待 SPIKE-008-01 证明)"
4002
+ return True, (f"{CONFIG_NAME} 已包含当前离线 runtime launcher 版本的 "
4003
+ f"Playwright、postmcp、Context7,以及 host/worker 两个本地 BugX Supervisor 通道{note}")
4004
+
4005
+
4006
+ def _merge_host_records(path: Path, installed: list[dict[str, object]]) -> list[dict[str, object]]:
4007
+ """Merge newly installed hosts without discarding earlier host entries."""
4008
+ if path.is_symlink():
4009
+ raise CliError(_i18n_exc("agent.hosts_symlink_refused", f"拒绝写入符号链接宿主清单: {path}", path=path))
4010
+ merged: dict[str, dict[str, object]] = {}
4011
+ if path.exists():
4012
+ try:
4013
+ payload = json.loads(path.read_text(encoding="utf-8"))
4014
+ except (OSError, json.JSONDecodeError) as exc:
4015
+ raise CliError(_i18n_exc("agent.hosts_unreadable", f"宿主清单无法读取,拒绝覆盖: {path}: {exc}", path=path, exc=exc)) from exc
4016
+ previous = payload.get("installed") if isinstance(payload, dict) else None
4017
+ if not isinstance(previous, list):
4018
+ raise CliError(_i18n_exc("agent.hosts_missing_installed", f"宿主清单缺少 installed 数组,拒绝覆盖: {path}", path=path))
4019
+ for item in previous:
4020
+ if not isinstance(item, dict) or not isinstance(item.get("name"), str):
4021
+ raise CliError(_i18n_exc("agent.hosts_invalid_entry", f"宿主清单包含无效记录,拒绝覆盖: {path}", path=path))
4022
+ merged[str(item["name"])] = item
4023
+ for item in installed:
4024
+ merged[str(item["name"])] = item
4025
+ return list(merged.values())
4026
+
4027
+
4028
+ def _initialize_lesson_ledger(root: Path, source: Path) -> bool:
4029
+ """Create the lesson seed and runtime store during explicit project init.
4030
+
4031
+ Startup must never call an ``ensure`` operation: a missing runtime store in
4032
+ an already-initialized project is a fail-closed condition. The CLI init
4033
+ command is the one explicit bootstrap boundary allowed to create it.
4034
+ """
4035
+ layout = _layout_module(root).require(root)
4036
+ # DOC-004 Layout 2:静态协议脚本只来自全局引擎;项目 .bugx 仅保存账本。
4037
+ ledger_script = _script(root, "lesson_ledger.py")
4038
+ ledger_path = layout.knowledge_seed
4039
+ seed_path = source / "lesson-ledger.json"
4040
+ if not ledger_script.is_file():
4041
+ raise CliError(_i18n_exc("agent.lesson_ledger_missing", "初始化错题集失败:缺少 lesson_ledger.py"))
4042
+ project_marker = layout.knowledge_root / "manifest.json"
4043
+ # `bugx install` is intentionally supported from HOME for user-level
4044
+ # host registration. In that mode the project and global knowledge roots
4045
+ # are the same directory; the global manifest must not be mistaken for a
4046
+ # project manifest, otherwise a missing project-named SQLite file blocks
4047
+ # every host install. Keep the project ledger branch disabled and let the
4048
+ # explicit global-store branch below report/recover its own state.
4049
+ knowledge_roots_collide = (
4050
+ layout.knowledge_root.resolve() == layout.global_knowledge_root.resolve()
4051
+ )
4052
+ if knowledge_roots_collide:
4053
+ # 静默跳过会让 40%→60% 这一段看起来「做了事但其实没做」。显式说明一次,
4054
+ # 否则用户只能看到进度前进,却不知道项目错题集分支被整体关闭了。
4055
+ print(
4056
+ f"[bugx] 提示:项目知识根与全局知识根指向同一目录({layout.knowledge_root}),"
4057
+ f"本次跳过项目错题集初始化,错题集以全局库为准。",
4058
+ file=sys.stderr,
4059
+ )
4060
+ elif project_marker.is_file() and _knowledge_marker_is_global(project_marker):
4061
+ # 两个知识根没有塌缩,项目清单路径上却是全局清单:这是配置异常。
4062
+ # 必须 fail-closed —— 函数尾部会用 `scope=project` 重写 marker,继续走下去
4063
+ # 等于把全局清单覆盖成项目清单,破坏全局知识库的身份。
4064
+ raise CliError(
4065
+ f"初始化错题集失败:项目知识清单 {project_marker} 声明 scope=global,"
4066
+ f"拒绝用项目清单覆盖全局清单;请检查 BUGX_GLOBAL_KNOWLEDGE_ROOT 与项目根配置"
4067
+ )
4068
+ if not knowledge_roots_collide and project_marker.is_symlink():
4069
+ raise CliError(_i18n_exc("agent.project_knowledge_symlink_refused", "初始化错题集失败:拒绝使用符号链接项目知识清单"))
4070
+ if not knowledge_roots_collide and not ledger_path.exists():
4071
+ if not seed_path.is_file() or seed_path.is_symlink():
4072
+ raise CliError(_i18n_exc("agent.project_lesson_seed_missing", "初始化错题集失败:缺少内置 lesson-ledger.json 种子"))
4073
+ ledger_path.parent.mkdir(parents=True, exist_ok=True)
4074
+ shutil.copy2(seed_path, ledger_path)
4075
+ if not knowledge_roots_collide and ledger_path.is_symlink():
4076
+ raise CliError(_i18n_exc("agent.project_ledger_symlink_refused", "初始化错题集失败:拒绝使用符号链接账本"))
4077
+ project_db = layout.knowledge_db
4078
+ if not knowledge_roots_collide and project_marker.is_file() and not project_db.is_file():
4079
+ raise CliError(_i18n_exc("agent.project_sqlite_missing_rebuild_refused", "项目错题集 SQLite 运行库缺失;拒绝从 JSON 种子静默重建,请从备份恢复或执行显式恢复流程"))
4080
+ if not knowledge_roots_collide:
4081
+ try:
4082
+ process = subprocess.run(
4083
+ [sys.executable, str(ledger_script), "init", "--ledger", str(ledger_path), "--json"],
4084
+ cwd=root,
4085
+ capture_output=True,
4086
+ text=True,
4087
+ check=False,
4088
+ timeout=30,
4089
+ env=_python_environment(),
4090
+ )
4091
+ except (OSError, subprocess.TimeoutExpired) as exc:
4092
+ raise CliError(_i18n_exc("agent.project_lesson_init_exc", f"初始化错题集失败: {exc}", exc=exc)) from exc
4093
+ if process.returncode != 0:
4094
+ detail = (process.stderr or process.stdout).strip()[:800]
4095
+ raise CliError(_i18n_exc("agent.project_lesson_init_failed", f"初始化错题集失败: {detail or 'lesson_ledger init 返回非 0'}", detail=detail or 'lesson_ledger init 返回非 0'))
4096
+ project_db.chmod(0o600)
4097
+ ledger_path.chmod(0o600)
4098
+ _write_private_json(project_marker, {
4099
+ "schema_version": 1,
4100
+ "scope": "project",
4101
+ "authority": "sqlite",
4102
+ "seed": ledger_path.name,
4103
+ "database": project_db.name,
4104
+ "initialized_at": time.time(),
4105
+ })
4106
+
4107
+ # The global ledger is shared across projects, so it is initialized only
4108
+ # when the user's global store does not exist at all. Once its manifest
4109
+ # exists, a missing SQLite file is a data-loss condition and must never be
4110
+ # silently rebuilt from the (possibly stale) JSON seed.
4111
+ global_root = layout.global_knowledge_root
4112
+ global_root.mkdir(parents=True, exist_ok=True)
4113
+ global_seed = layout.global_knowledge_seed
4114
+ global_db = layout.global_knowledge_db
4115
+ global_marker = global_root / "manifest.json"
4116
+ if any(path.is_symlink() for path in (global_marker, global_seed, global_db)):
4117
+ raise CliError(_i18n_exc("agent.global_knowledge_symlink_refused", "初始化全局错题集失败:拒绝使用符号链接知识文件"))
4118
+ if not global_marker.exists() and not global_db.exists():
4119
+ if not global_seed.exists():
4120
+ shutil.copy2(seed_path, global_seed)
4121
+ process = subprocess.run(
4122
+ [sys.executable, str(ledger_script), "init", "--ledger", str(global_seed), "--json"],
4123
+ cwd=root, capture_output=True, text=True, check=False, timeout=30,
4124
+ env=_python_environment(),
4125
+ )
4126
+ if process.returncode != 0:
4127
+ detail = (process.stderr or process.stdout).strip()[:800]
4128
+ raise CliError(_i18n_exc("agent.global_lesson_init_failed", f"初始化全局错题集失败: {detail or 'lesson_ledger init 返回非 0'}", detail=detail or 'lesson_ledger init 返回非 0'))
4129
+ global_seed.chmod(0o600)
4130
+ global_db.chmod(0o600)
4131
+ _write_private_json(global_marker, {
4132
+ "schema_version": 1,
4133
+ "scope": "global",
4134
+ "authority": "sqlite",
4135
+ "read_only_for_agents": True,
4136
+ "seed": global_seed.name,
4137
+ "database": global_db.name,
4138
+ "initialized_at": time.time(),
4139
+ })
4140
+ elif global_marker.exists() and not global_db.is_file():
4141
+ # 全局为可选加速器(doctor 已标为可选),缺失时不阻断项目初始化,仅告警
4142
+ # 原 fail-closed 会导致 `bugx init` 在 C:全局污染的 Windows 跨盘项目中固定 exit 2
4143
+ print(
4144
+ "⚠ 全局错题集 SQLite 缺失(已跳过全局继承,项目初始化不受影响)。"
4145
+ "如需恢复请执行:bugx lesson rebuild --from-seed --confirm-data-loss"
4146
+ f" --ledger {global_seed}",
4147
+ file=sys.stderr,
4148
+ )
4149
+ elif global_db.is_file():
4150
+ try:
4151
+ global_db.chmod(0o600)
4152
+ if global_seed.is_file():
4153
+ global_seed.chmod(0o600)
4154
+ except (PermissionError, OSError):
4155
+ pass
4156
+ validation = subprocess.run(
4157
+ [sys.executable, str(ledger_script), "validate", "--ledger", str(global_seed), "--json"],
4158
+ cwd=root, capture_output=True, text=True, check=False, timeout=30,
4159
+ env=_python_environment(),
4160
+ )
4161
+ if validation.returncode != 0:
4162
+ detail = (validation.stderr or validation.stdout).strip()[:800]
4163
+ if "schema_version" in detail:
4164
+ # 全局库是可选只读加速器;旧 schema 需要显式迁移,不能静默改写
4165
+ # 用户拥有的全局账本,也不能因此阻断项目初始化。
4166
+ print(
4167
+ "⚠ 全局错题集需要显式迁移(项目库不受影响)。"
4168
+ "迁移命令:bugx lesson migrate "
4169
+ f"--ledger {layout.global_knowledge_seed}",
4170
+ file=sys.stderr,
4171
+ )
4172
+ else:
4173
+ raise CliError(_i18n_exc("agent.global_ledger_check_failed", f"全局错题集校验失败: {detail or 'SQLite 无效'}", detail=detail or 'SQLite 无效'))
4174
+ if not global_marker.exists():
4175
+ _write_private_json(global_marker, {
4176
+ "schema_version": 1,
4177
+ "scope": "global",
4178
+ "authority": "sqlite",
4179
+ "read_only_for_agents": True,
4180
+ "seed": global_seed.name,
4181
+ "database": global_db.name,
4182
+ "initialized_at": time.time(),
4183
+ "adopted_existing_store": True,
4184
+ })
4185
+ return True
4186
+
4187
+
4188
+ def _inherit_project_knowledge(root: Path) -> dict[str, Any]:
4189
+ """Seed a fresh project with active patterns from the shared global ledger."""
4190
+ layout = _layout_module(root).require(root)
4191
+ script = _script(root, "lesson_ledger.py")
4192
+ process = subprocess.run(
4193
+ [sys.executable, str(script), "inherit",
4194
+ "--ledger", str(layout.knowledge_seed),
4195
+ "--global-ledger", str(layout.global_knowledge_seed), "--json"],
4196
+ cwd=root.resolve(), capture_output=True, text=True, check=False,
4197
+ timeout=30, env=_python_environment(),
4198
+ )
4199
+ if process.returncode != 0:
4200
+ detail = (process.stderr or process.stdout).strip()[:800]
4201
+ if "schema_version" in detail:
4202
+ # 全局库是可选的只读加速器;旧 schema 需要显式迁移,不能让
4203
+ # 一个全局知识库的维护问题阻断新项目初始化。
4204
+ return {"imported": 0, "skipped": 0, "status": "schema_pending"}
4205
+ raise CliError(_i18n_exc("agent.project_inherit_global_failed", f"项目错题集继承全局知识失败: {detail or 'inherit 返回非 0'}", detail=detail or 'inherit 返回非 0'))
4206
+ try:
4207
+ payload = json.loads(process.stdout or "{}")
4208
+ except json.JSONDecodeError as exc:
4209
+ raise CliError(_i18n_exc("agent.project_inherit_invalid_json", "项目错题集继承全局知识失败: inherit 输出不是有效 JSON")) from exc
4210
+ return payload if isinstance(payload, dict) else {}