bugx-cli 0.1.0 → 0.1.2

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 (338) hide show
  1. package/README.md +193 -185
  2. package/core/README.md +2 -2
  3. package/core/agent/README.md +2 -1
  4. package/core/agent/agent_artifacts.py +8 -6
  5. package/core/agent/agent_eval.py +136 -54
  6. package/core/agent/agent_execution.py +218 -52
  7. package/core/agent/agent_orchestrator.py +14 -8
  8. package/core/agent/agent_targets.py +8 -2
  9. package/core/agent/feature_baseline.py +150 -0
  10. package/core/assets/README.md +3 -2
  11. package/core/assets/axe-core/LICENSE-3RD-PARTY.txt +66 -0
  12. package/core/assets/axe-core/LICENSE.txt +362 -0
  13. package/core/assets/axe-core/UPSTREAM.md +10 -0
  14. package/core/assets/axe-core/axe.min.js +12 -0
  15. package/core/assets/bugx-hero-en.svg +74 -0
  16. package/core/assets/bugx-hero-zh.svg +74 -0
  17. package/core/assets/bugx-social-preview.svg +71 -0
  18. package/core/assets/bugx-wechat-group.png +0 -0
  19. package/core/assets/codex.png +0 -0
  20. package/core/assets/dsh.png +0 -0
  21. package/core/assets/webui-chatgpt.jpg +0 -0
  22. package/core/assets/webui-session.jpg +0 -0
  23. package/core/assets/webui-skills.jpg +0 -0
  24. package/core/assets/webui-studio.jpg +0 -0
  25. package/core/assets/webui-zcode.jpg +0 -0
  26. package/core/assets/zcode.png +0 -0
  27. package/core/audit_packs/README.md +2 -0
  28. package/core/audit_packs/pitfalls/auth_crypto.json +64 -0
  29. package/core/audit_packs/pitfalls/file_ssrf_cmd.json +64 -0
  30. package/core/audit_packs/pitfalls/go_backend.json +66 -0
  31. package/core/audit_packs/pitfalls/java_spring.json +64 -0
  32. package/core/audit_packs/pitfalls/js_ts_web.json +67 -0
  33. package/core/audit_packs/pitfalls/python_web.json +82 -0
  34. package/core/autonomous_cve/SPEC.md +1 -1
  35. package/core/autonomous_cve/attack_graph_store.py +152 -106
  36. package/core/autonomous_cve/behavior_graph.py +8 -2
  37. package/core/autonomous_cve/verifier.py +4 -1
  38. package/core/bugx.md +1 -1
  39. package/core/bugx_paths.py +43 -8
  40. package/core/cli-help.txt +66 -0
  41. package/core/cloud_sync/SPEC.md +1 -1
  42. package/core/cloud_sync/cloud_client.py +81 -11
  43. package/core/cloud_sync/cloud_onboard.py +42 -1
  44. package/core/cloud_sync/consent.py +33 -3
  45. package/core/cloud_sync/flywheel_client.py +186 -15
  46. package/core/cloud_sync/network_transport.py +24 -3
  47. package/core/cloud_sync/sensitive_filter.py +2 -2
  48. package/core/cloud_sync/sync_push.py +12 -10
  49. package/core/contracts/AGENT_GUIDE.md +6 -9
  50. package/core/contracts/README.md +2 -2
  51. package/core/contracts/bugx-runtime-contract.md +1 -1
  52. package/core/contracts/bugx-worker.md +1 -1
  53. package/core/contracts/engine_gap_contracts.py +86 -3
  54. package/core/coverage/coverage_discovery.py +599 -29
  55. package/core/coverage/coverage_evidence.py +47 -0
  56. package/core/coverage/coverage_forensics.py +9 -0
  57. package/core/coverage/coverage_validate.py +6 -1
  58. package/core/dev_harness/SPEC.md +1 -1
  59. package/core/engine-integrity.json +670 -442
  60. package/core/fuzzing/concurrency_fuzzer.py +53 -0
  61. package/core/fuzzing/differential_oracle.py +562 -27
  62. package/core/fuzzing/fuzz_input.py +109 -6
  63. package/core/fuzzing/stateful_fuzzer.py +72 -0
  64. package/core/governance/secret_redactor.py +22 -10
  65. package/core/host_acp/SPEC.md +1 -1
  66. package/core/host_acp/__init__.py +4 -4
  67. package/core/host_acp/claude.py +59 -1
  68. package/core/host_acp/cline.py +64 -1
  69. package/core/host_acp/codex.py +56 -1
  70. package/core/host_acp/dsh.py +59 -1
  71. package/core/host_acp/opencode.py +56 -1
  72. package/core/host_acp/pi.py +59 -1
  73. package/core/host_acp/zcode.py +59 -1
  74. package/core/host_runtime/SPEC.md +1 -1
  75. package/core/host_runtime/adapters.py +1 -1
  76. package/core/host_runtime/cline.py +13 -0
  77. package/core/host_runtime/host_evaluators.py +44 -4
  78. package/core/host_runtime/host_probe.py +1 -1
  79. package/core/host_runtime/host_provider_arbitrator.py +116 -62
  80. package/core/host_runtime/host_registry.py +15 -8
  81. package/core/host_runtime/mcp_registry_gate.py +12 -1
  82. package/core/host_runtime/pi.py +102 -0
  83. package/core/host_runtime/provider_facts.py +66 -0
  84. package/core/hosts/SPEC.md +1 -1
  85. package/core/hosts/__init__.py +6 -2
  86. package/core/hosts/_dsh_usage.py +1 -1
  87. package/core/hosts/base.py +32 -4
  88. package/core/hosts/claude.py +55 -0
  89. package/core/hosts/cline.py +6 -2
  90. package/core/hosts/codex.py +58 -0
  91. package/core/hosts/dsh.py +9 -1
  92. package/core/hosts/opencode.py +6 -6
  93. package/core/hosts/pi.py +159 -2
  94. package/core/infra/README.md +4 -2
  95. package/core/infra/__init__.py +2 -0
  96. package/core/infra/build_info.py +22 -3
  97. package/core/infra/client_metadata.py +1 -1
  98. package/core/infra/json_utils.py +22 -0
  99. package/core/launch_phases/README.md +6 -3
  100. package/core/launch_phases/SPEC.md +1 -1
  101. package/core/launch_phases/common.py +21 -2
  102. package/core/launch_phases/finding_confirm_phase.py +170 -5
  103. package/core/launch_phases/finding_settlement.py +188 -1
  104. package/core/launch_phases/judge_phase.py +69 -12
  105. package/core/launch_phases/orchestrator_controls.py +11 -7
  106. package/core/launch_phases/post_coverage_sync.py +9 -2
  107. package/core/launch_phases/post_phase.py +144 -8
  108. package/core/launch_phases/post_receipt.py +12 -1
  109. package/core/launch_phases/pre_phase.py +3 -3
  110. package/core/launch_phases/pre_recon_scout.py +66 -36
  111. package/core/launch_phases/pre_state_builder.py +23 -176
  112. package/core/launch_phases/report_sharing.py +3 -7
  113. package/core/launch_phases/round_orchestrator.py +129 -58
  114. package/core/launch_phases/semantic_recon.py +545 -0
  115. package/core/launch_phases/session_runtime.py +56 -9
  116. package/core/launch_phases/startup_gates.py +36 -8
  117. package/core/launch_phases/startup_interaction.py +68 -12
  118. package/core/launch_phases/startup_version_gate.py +13 -3
  119. package/core/launch_phases/supervisor_bridge.py +46 -17
  120. package/core/launch_phases/supervisor_coverage.py +8 -2
  121. package/core/launch_phases/supervisor_degraded.py +1 -9
  122. package/core/launch_phases/verify_loop.py +767 -0
  123. package/core/launch_phases/worker_barriers.py +15 -5
  124. package/core/launch_phases/worker_orchestrator.py +105 -25
  125. package/core/launch_phases/worker_prior.py +115 -0
  126. package/core/ledger/README.md +2 -1
  127. package/core/ledger/SPEC.md +1 -1
  128. package/core/ledger/_facade.py +2 -1
  129. package/core/ledger/archive_ops.py +60 -2
  130. package/core/ledger/cli.py +6 -1
  131. package/core/ledger/export_ops.py +6 -1
  132. package/core/ledger/finding_confirmation.py +48 -6
  133. package/core/ledger/finding_lifecycle.py +428 -5
  134. package/core/ledger/finding_verification.py +555 -10
  135. package/core/ledger/fp_ledger.py +255 -0
  136. package/core/ledger/incidents.py +10 -4
  137. package/core/ledger/patterns.py +10 -7
  138. package/core/ledger/receipt_contract.py +17 -1
  139. package/core/ledger/sync_ops.py +21 -16
  140. package/core/ledger/tool_experience.py +2 -1
  141. package/core/ledger/verify_life.py +88 -17
  142. package/core/locales/en-US.json +2 -2
  143. package/core/locales/zh-CN.json +2 -2
  144. package/core/mcp_handlers/SPEC.md +1 -1
  145. package/core/mcp_handlers/base.py +23 -3
  146. package/core/mcp_handlers/channel_lifecycle.py +85 -30
  147. package/core/mcp_handlers/retrieval_handlers.py +11 -1
  148. package/core/mcp_handlers/rpc_server.py +6 -1
  149. package/core/mcp_handlers/supervisor_handlers.py +32 -6
  150. package/core/mcp_handlers/tool_table.py +15 -0
  151. package/core/mcp_runtime_support/environment.py +0 -38
  152. package/core/mcp_runtime_support/verifier.py +0 -52
  153. package/core/metadata.txt +2 -3
  154. package/core/planning/README.md +2 -1
  155. package/core/planning/domain_router.py +4 -2
  156. package/core/planning/dynamic_flow_analyzer.py +219 -14
  157. package/core/planning/judge_pipeline.py +87 -4
  158. package/core/planning/prompt_harness.py +57 -15
  159. package/core/planning/prompt_policy_engine.py +386 -0
  160. package/core/planning/spec_harvester.py +4 -4
  161. package/core/probes/INTERFACE.md +11 -1
  162. package/core/probes/SPEC.md +11 -1
  163. package/core/probes/__init__.py +46 -40
  164. package/core/probes/android_probe.py +177 -9
  165. package/core/probes/codebase_memory_probe.py +57 -0
  166. package/core/probes/desktop_probe.py +104 -0
  167. package/core/probes/differential_probe.py +99 -21
  168. package/core/probes/efficiency_probe.py +64 -0
  169. package/core/probes/ios_binary_probe.py +105 -1
  170. package/core/probes/memory_probe.py +66 -0
  171. package/core/probes/miniprogram_probe.py +75 -13
  172. package/core/probes/mobile_probe.py +215 -30
  173. package/core/probes/native_probe.py +88 -0
  174. package/core/probes/openwiki_probe.py +70 -0
  175. package/core/probes/pattern_probe.py +106 -0
  176. package/core/probes/platform_probe.py +81 -0
  177. package/core/probes/probe_registry.py +108 -7
  178. package/core/probes/sast_fixture_corpus.py +340 -0
  179. package/core/probes/sast_probe.py +553 -52
  180. package/core/probes/sast_rules.py +668 -28
  181. package/core/probes/sca_scanner.py +48 -0
  182. package/core/probes/ui_accessibility.py +149 -0
  183. package/core/probes/ui_audit.py +513 -0
  184. package/core/probes/ui_contract.py +273 -0
  185. package/core/probes/ui_evidence.py +212 -0
  186. package/core/probes/ui_measurements.py +314 -0
  187. package/core/probes/ui_repair.py +250 -0
  188. package/core/probes/ui_review.py +133 -0
  189. package/core/probes/ui_storybook.py +107 -0
  190. package/core/probes/ui_tokens.py +185 -0
  191. package/core/probes/ui_visual_diff.py +131 -0
  192. package/core/probes/web_probe.py +373 -18
  193. package/core/project_profiler/SPEC.md +1 -1
  194. package/core/project_profiler/arbitrator.py +6 -1
  195. package/core/project_profiler/detector.py +8 -1
  196. package/core/project_profiler/strategy.py +51 -15
  197. package/core/prompts/README.md +4 -2
  198. package/core/prompts/command_routing_en.md +2 -2
  199. package/core/prompts/command_routing_zh.md +2 -2
  200. package/core/prompts/policies/prompt_policies.json +101 -0
  201. package/core/prompts/stages/stage_repair.md +1 -1
  202. package/core/prompts/stages/stage_verify.defensive.md +42 -0
  203. package/core/prompts/stages/stage_verify.md +44 -0
  204. package/core/repair/README.md +1 -1
  205. package/core/repair/l7_repair_loop.py +1 -4
  206. package/core/repair/rsi_fixer.py +4 -4
  207. package/core/repair/rsi_loop.py +1 -3
  208. package/core/repair/rsi_repair.py +7 -7
  209. package/core/repair/rsi_scope.py +27 -8
  210. package/core/report_engine/SPEC.md +1 -1
  211. package/core/report_engine/attestation.py +8 -4
  212. package/core/report_engine/finding_report.py +2 -1
  213. package/core/report_engine/models.py +7 -9
  214. package/core/report_engine/report_share.py +0 -8
  215. package/core/report_engine/sast_bridge.py +2 -2
  216. package/core/report_engine/server.py +18 -8
  217. package/core/report_engine/web-conformance.md +123 -18
  218. package/core/report_engine/web_conformance.py +21 -52
  219. package/core/retrieval/README.md +2 -1
  220. package/core/retrieval/SPEC.md +1 -1
  221. package/core/retrieval/code_analyzer.py +50 -14
  222. package/core/retrieval/context_assembler.py +7 -1
  223. package/core/retrieval/knowledge_sync.py +108 -14
  224. package/core/retrieval/pitfall_packs.py +277 -0
  225. package/core/retrieval/symbol_index.py +25 -6
  226. package/core/retrieval/universal_code_matcher.py +234 -49
  227. package/core/runtime/README.md +1 -1
  228. package/core/runtime/bugx_logging.py +78 -7
  229. package/core/runtime/fixture_solidify.py +5 -10
  230. package/core/runtime/global_telemetry.py +20 -0
  231. package/core/runtime/incident_eval.py +1 -1
  232. package/core/runtime/model_runner.py +4 -41
  233. package/core/runtime/platform_adapter.py +2 -2
  234. package/core/runtime/prep_validate.py +4 -2
  235. package/core/runtime/project_settings.py +2 -1
  236. package/core/runtime/scenario_eval.py +50 -8
  237. package/core/skills/bugx_docs_mcp_server.py +3 -1
  238. package/core/skills/bugx_mcp_server.py +29 -2
  239. package/core/skills/tools_kb.py +1 -1
  240. package/core/supervisor/README.md +1 -1
  241. package/core/supervisor/SPEC.md +1 -1
  242. package/core/supervisor/budget_governor.py +503 -9
  243. package/core/supervisor/checkpoint_pipeline.py +248 -6
  244. package/core/supervisor/checkpoint_sync.py +13 -0
  245. package/core/supervisor/claim_events.py +1 -1
  246. package/core/supervisor/finding_workflow.py +22 -5
  247. package/core/supervisor/lease_manager.py +1 -1
  248. package/core/supervisor/lifecycle_blocks.py +6 -1
  249. package/core/supervisor/rejection_remedies.py +52 -5
  250. package/core/supervisor/serial_authorization.py +48 -4
  251. package/core/supervisor/task_scheduler.py +2 -2
  252. package/core/supervisor/worker_checkpoint.py +8 -1
  253. package/core/supervisor/worker_runtime.py +8 -2
  254. package/core/supervisor_types/worker_claim.py +9 -0
  255. package/core/webui/README.md +1 -1
  256. package/core/webui/SPEC.md +2 -1
  257. package/core/webui/adapters/claude.py +5 -1
  258. package/core/webui/adapters/cline.py +10 -2
  259. package/core/webui/adapters/codex.py +5 -1
  260. package/core/webui/adapters/dsh.py +5 -1
  261. package/core/webui/docs_session_service.py +2 -2
  262. package/core/webui/mcp_inspector.py +11 -7
  263. package/core/webui/static/00-base.css +1060 -0
  264. package/core/webui/static/01-monitoring.css +802 -0
  265. package/core/webui/static/02-header-actions.css +321 -0
  266. package/core/webui/static/03-trigger-popover.css +697 -0
  267. package/core/webui/static/04-composer.css +628 -0
  268. package/core/webui/static/05-skills-center.css +878 -0
  269. package/core/webui/static/06-mcp-center.css +623 -0
  270. package/core/webui/static/07-skill-detail.css +265 -0
  271. package/core/webui/static/08-files-management.css +167 -0
  272. package/core/webui/static/09-files-center.css +386 -0
  273. package/core/webui/static/10-icons.css +105 -0
  274. package/core/webui/static/11-project-options.css +185 -0
  275. package/core/webui/static/12-profile-tab.css +383 -0
  276. package/core/webui/static/design-tokens.css +113 -0
  277. package/core/webui/static/index.html +14 -1
  278. package/core/webui/workspace_service.py +1 -1
  279. package/docs/07_distribution/01_README_NPM.md +193 -185
  280. package/ecosystem/integrations/README.md +1 -1
  281. package/ecosystem/integrations/dsh/mcp/package.json +1 -1
  282. package/ecosystem/integrations/dsh/skills/bugx-dsh/SKILL.md +1 -1
  283. package/ecosystem/integrations/dsh/ui/package.json +1 -1
  284. package/ecosystem/integrations/opencode/bugx-mcp-manifest.json +4 -4
  285. package/ecosystem/integrations/opencode/mcp-lock.json +14 -6
  286. package/ecosystem/integrations/opencode/opencode.json +23 -12
  287. package/ecosystem/integrations/pi/extensions/bugx/manifest.json +1 -1
  288. package/ecosystem/integrations/qoder/connector-meta.json +1 -1
  289. package/ecosystem/integrations/workbuddy/connector-meta.json +1 -1
  290. package/ecosystem/integrations/workbuddy/skills/bugx/SKILL.md +1 -1
  291. package/ecosystem/plugins/bugx/.claude-plugin/plugin.json +1 -1
  292. package/ecosystem/plugins/bugx/.codex-plugin/plugin.json +1 -1
  293. package/ecosystem/plugins/bugx/.zcode-plugin/plugin.json +1 -1
  294. package/ecosystem/plugins/bugx/skills/bugx/SKILL.md +2 -2
  295. package/ecosystem/plugins/bugx/skills/bugx-dsh/SKILL.md +1 -1
  296. package/ecosystem/plugins/bugx/skills/bugx-opencode/SKILL.md +1 -1
  297. package/ecosystem/plugins/bugx/skills/bugx-zcode/SKILL.md +1 -1
  298. package/interfaces/bin/bugx.js +37 -0
  299. package/interfaces/cli/bugx_cli/__init__.py +4 -2
  300. package/interfaces/cli/bugx_cli/cli.py +172 -69
  301. package/interfaces/cli/bugx_cli/commands/advisory.py +1 -1
  302. package/interfaces/cli/bugx_cli/commands/agent.py +461 -134
  303. package/interfaces/cli/bugx_cli/commands/audit.py +10 -9
  304. package/interfaces/cli/bugx_cli/commands/autonomous.py +1 -1
  305. package/interfaces/cli/bugx_cli/commands/cloud.py +31 -22
  306. package/interfaces/cli/bugx_cli/commands/doctor.py +449 -204
  307. package/interfaces/cli/bugx_cli/commands/interaction.py +5 -1
  308. package/interfaces/cli/bugx_cli/commands/knowledge.py +5 -4
  309. package/interfaces/cli/bugx_cli/commands/lifecycle.py +3 -3
  310. package/interfaces/cli/bugx_cli/commands/plugin.py +58 -23
  311. package/interfaces/cli/bugx_cli/commands/plugin_claude.py +7 -7
  312. package/interfaces/cli/bugx_cli/commands/plugin_funide.py +2 -1
  313. package/interfaces/cli/bugx_cli/commands/plugin_zcode.py +1 -1
  314. package/interfaces/cli/bugx_cli/commands/project.py +6 -13
  315. package/interfaces/cli/bugx_cli/commands/report.py +2 -6
  316. package/interfaces/cli/bugx_cli/commands/system.py +524 -169
  317. package/interfaces/cli/bugx_cli/common.py +21 -15
  318. package/interfaces/cli/bugx_cli/host_adapters.py +29 -54
  319. package/interfaces/cli/bugx_cli/hosts/registry.py +8 -6
  320. package/interfaces/cli/bugx_cli/infra/ai_advisor.py +157 -27
  321. package/interfaces/cli/bugx_cli/infra/engine_installer.py +35 -16
  322. package/interfaces/cli/bugx_cli/infra/host_sync.py +11 -8
  323. package/interfaces/cli/bugx_cli/infra/mcp_advisor.py +76 -5
  324. package/interfaces/cli/bugx_cli/infra/security.py +13 -6
  325. package/package.json +30 -15
  326. package/pyproject.toml +60 -9
  327. package/scripts/ensure-python.mjs +7 -7
  328. package/scripts/sync-version.mjs +10 -21
  329. package/scripts/test-npm-wrapper.mjs +1 -1
  330. package/core/assets/bugx-hero-cn.png +0 -0
  331. package/core/assets/bugx-hero-en.png +0 -0
  332. package/core/webui/static/project-settings.css +0 -6458
  333. package/docs/07_distribution/README.md +0 -16
  334. package/docs/README.md +0 -121
  335. package/interfaces/README.md +0 -143
  336. package/interfaces/bin/README.md +0 -35
  337. package/interfaces/cli/README.md +0 -90
  338. package/scripts/README.md +0 -118
@@ -9,6 +9,7 @@ import os
9
9
  import re
10
10
  import shutil
11
11
  import stat
12
+ import struct
12
13
  import subprocess
13
14
  import sys
14
15
  import tempfile
@@ -49,6 +50,7 @@ from ..host_adapters import (
49
50
  ENTRY_SKILL_PAYLOAD,
50
51
  ENTRY_USER_REGISTRATION,
51
52
  HOST_ADAPTERS,
53
+ HostAdapter,
52
54
  HOST_NAME_CLAUDE,
53
55
  HOST_NAME_FUNIDE,
54
56
  HOST_NAME_QODER,
@@ -123,32 +125,54 @@ class _CliProgress:
123
125
  # Backward-compatible test/import name; the renderer is shared by all long CLI commands.
124
126
  _InstallProgress = _CliProgress
125
127
 
126
- #: **未迁移**宿主的安装面基线(逐宿主切片时删除对应项)。已迁移宿主的目录由
127
- #: ``HOST_ADAPTERS.managed_surfaces()``(插件 marker 投影)自动追加。
128
- #: **未迁移**宿主的用户级可见位置提示;已迁移宿主用 ``全局 <label> 可见``。
128
+ #: 安装事务始终保护的共享运行面。宿主目录由本次选中的适配器按需追加,
129
+ #: 避免安装一个宿主时因为另一个宿主的用户自定义链接而提前失败。
130
+ #: 宿主用户级注册后的「在哪里可见」提示。
129
131
  _USER_AGENT_VISIBILITY_HINTS = {
130
132
  "funide": "FunIDE 设置 → 智能体可见",
131
133
  }
132
134
 
133
135
 
134
136
  def _user_agent_visibility(host_name: str) -> str:
135
- """用户级注册后的「在哪里可见」提示(未迁移宿主走基线表)。"""
137
+ """返回用户级注册后的「在哪里可见」提示。"""
136
138
 
137
139
  hint = _USER_AGENT_VISIBILITY_HINTS.get(host_name)
138
140
  return hint or f"全局 {engine_host_label(host_name)} 可见"
139
141
 
140
142
 
141
- _BASE_AGENT_INSTALL_SURFACES = (
142
- ".bugx", ".opencode", ".claude", ".zcode", ".pi", ".agents",
143
- ".workbuddy", ".codebuddy", ".qoder", ".github",
144
- ".dsh", "plugins", CONFIG_NAME,
145
- )
146
- _AGENT_INSTALL_SURFACES = tuple(
147
- dict.fromkeys(
148
- list(_BASE_AGENT_INSTALL_SURFACES)
149
- + [surface for adapter in HOST_ADAPTERS for surface in adapter.managed_surfaces()]
150
- )
151
- )
143
+ _BASE_AGENT_INSTALL_SURFACES = (".bugx",)
144
+
145
+
146
+ def _agent_install_surfaces(
147
+ selected_adapters: tuple[HostAdapter, ...] | None = None,
148
+ ) -> tuple[str, ...]:
149
+ """Return the project surfaces that this transaction may write.
150
+
151
+ ``None`` preserves the complete registry projection for direct in-process
152
+ callers. The CLI install path passes the selected adapters so an unrelated
153
+ host directory cannot veto the transaction.
154
+ """
155
+ adapters = HOST_ADAPTERS if selected_adapters is None else selected_adapters
156
+ surfaces = list(_BASE_AGENT_INSTALL_SURFACES)
157
+ plugins = {
158
+ str(plugin.identity.name): plugin
159
+ for plugin in engine_host_plugins()
160
+ if getattr(plugin, "identity", None) is not None
161
+ }
162
+ for adapter in adapters:
163
+ surfaces.extend(adapter.managed_surfaces())
164
+ if adapter.supports(CAP_PROJECT_MCP_CONFIG):
165
+ surfaces.append(CONFIG_NAME)
166
+ plugin = plugins.get(adapter.name)
167
+ if plugin is not None:
168
+ for relative in plugin.install.mcp_relpaths:
169
+ path = Path(relative)
170
+ if not path.is_absolute() and path.parts:
171
+ surfaces.append(path.parts[0])
172
+ return tuple(dict.fromkeys(surfaces))
173
+
174
+
175
+ _AGENT_INSTALL_SURFACES = _agent_install_surfaces()
152
176
 
153
177
  # The transaction protects only BugX-owned files that the install path can
154
178
  # write. It must never copy an entire host directory: user-level installs
@@ -282,17 +306,17 @@ def _warn_engine_version_drift(
282
306
  if replaced is True:
283
307
  remedy = (
284
308
  "本次安装已把共享引擎回退到该 CLI 自带的版本,可能影响依赖新引擎的其他项目;"
285
- "请升级 CLI 后重跑(例如 'uv tool install --reinstall bugx-agent')。"
309
+ "请升级 CLI 后重跑(例如 'uv tool install --reinstall bugx-cli')。"
286
310
  )
287
311
  elif replaced is False:
288
312
  remedy = (
289
313
  "已跳过引擎替换以避免回退所有项目共享的引擎;"
290
- "请升级 CLI 后重跑(例如 'uv tool install --reinstall bugx-agent'),"
314
+ "请升级 CLI 后重跑(例如 'uv tool install --reinstall bugx-cli'),"
291
315
  "确需回退请追加 '--force'。"
292
316
  )
293
317
  else:
294
318
  remedy = (
295
- "请升级 CLI 后重跑(例如 'uv tool install --reinstall bugx-agent');"
319
+ "请升级 CLI 后重跑(例如 'uv tool install --reinstall bugx-cli');"
296
320
  "确需回退请追加 '--force'。"
297
321
  )
298
322
  else:
@@ -327,8 +351,12 @@ def command_agent(args: argparse.Namespace) -> int:
327
351
  progress = _CliProgress(args)
328
352
  progress.update(0, "准备安装")
329
353
  root = args.root.resolve()
354
+ _ensure_core_importable()
355
+ selected_adapters = _select_install_adapters(
356
+ args, root, discover_hosts(root),
357
+ )
330
358
  try:
331
- staging, existed = _agent_install_snapshot(root)
359
+ staging, existed = _agent_install_snapshot(root, selected_adapters)
332
360
  except (OSError, shutil.Error) as exc:
333
361
  raise CliError(_i18n_exc(
334
362
  "agent.install_snapshot_failed",
@@ -338,7 +366,11 @@ def command_agent(args: argparse.Namespace) -> int:
338
366
  token = _GLOBAL_TX.set(staging)
339
367
  preserve_staging = False
340
368
  try:
341
- return _command_agent_impl(args, progress=progress)
369
+ return _command_agent_impl(
370
+ args,
371
+ progress=progress,
372
+ selected_adapters=selected_adapters,
373
+ )
342
374
  except BaseException as install_error:
343
375
  progress.fail()
344
376
  rollback_errors: list[str] = []
@@ -390,7 +422,10 @@ def _ignore_install_snapshot_entries(directory: str, names: list[str]) -> list[s
390
422
  return [name for name in names if _is_special_install_entry(Path(directory) / name)]
391
423
 
392
424
 
393
- def _agent_install_snapshot(root: Path) -> tuple[Path, dict[str, bool]]:
425
+ def _agent_install_snapshot(
426
+ root: Path,
427
+ selected_adapters: tuple[HostAdapter, ...] | None = None,
428
+ ) -> tuple[Path, dict[str, bool]]:
394
429
  """Stage only BugX-owned files before a host install.
395
430
 
396
431
  Installation touches shared runtime files as well as one or more host
@@ -402,7 +437,7 @@ def _agent_install_snapshot(root: Path) -> tuple[Path, dict[str, bool]]:
402
437
  staging = Path(tempfile.mkdtemp(prefix="bugx-install-transaction-")).resolve()
403
438
  existed: dict[str, bool] = {}
404
439
  try:
405
- for relative in _AGENT_INSTALL_SURFACES:
440
+ for relative in _agent_install_surfaces(selected_adapters):
406
441
  target = root / relative
407
442
  existed[relative] = target.exists() or _is_reparse_point(target)
408
443
  if not existed[relative]:
@@ -735,34 +770,14 @@ def _installed_engine_build_id() -> int:
735
770
  pass
736
771
  return get_build_id() or 1
737
772
 
738
- def _command_agent_impl(
739
- args: argparse.Namespace, *, progress: _CliProgress | None = None,
740
- ) -> int:
741
- """发现并安装到宿主 AI;不启动宿主,也不执行审计。"""
742
- root = args.root.resolve()
743
- command = getattr(args, "agent_command", "install")
744
- _ensure_core_importable()
745
- import core.i18n as i18n
746
- deployment_locale = i18n.resolve_locale().resolved_locale
747
- if getattr(args, "locale", None):
748
- norm = i18n.normalize_locale(args.locale)
749
- if not norm:
750
- raise CliError(_i18n_exc("common.invalid_locale", f"不支持的 locale: {args.locale};可选:zh-CN, en-US", locale=args.locale))
751
- deployment_locale = norm
752
- hosts = discover_hosts(root)
753
- if command == "discover":
754
- payload = {"root": str(root), "hosts": hosts, "execution": "none"}
755
- if args.json:
756
- print(json.dumps(payload, ensure_ascii=False, indent=2))
757
- else:
758
- for item in hosts:
759
- state = "FOUND" if item["installed"] else "NOT_FOUND"
760
- executable = item["executable"] or item.get("app_path") or "-"
761
- print(f"{item['name']}\t{state}\t{executable}\t{item['install_path']}")
762
- return 0
763
- if command != "install":
764
- raise CliError(_i18n_exc("agent.unknown_agent_command", f"未知 Agent 命令: {command}", command=command))
765
- raw_requested = []
773
+
774
+ def _select_install_adapters(
775
+ args: argparse.Namespace,
776
+ root: Path,
777
+ hosts: list[dict[str, object]],
778
+ ) -> tuple[HostAdapter, ...]:
779
+ """Resolve and validate the requested hosts before opening the transaction."""
780
+ raw_requested: list[str] = []
766
781
  for item in getattr(args, "agent", []):
767
782
  for sub in str(item).split(","):
768
783
  sub = sub.strip()
@@ -771,32 +786,37 @@ def _command_agent_impl(
771
786
  requested = list(dict.fromkeys(raw_requested))
772
787
  if not requested:
773
788
  if args.non_interactive:
774
- raise CliError(_i18n_exc("agent.non_interactive_agent_required", "非交互安装必须显式提供 --agent opencode/dsh/codex/cline/claude/zcode/workbuddy/pi/chatgpt/qoder/trea/funide"))
789
+ raise CliError(_i18n_exc(
790
+ "agent.non_interactive_agent_required",
791
+ "非交互安装必须显式提供 --agent opencode/dsh/codex/cline/claude/zcode/workbuddy/pi/chatgpt/qoder/trea/funide",
792
+ ))
775
793
  if not sys.stdin.isatty():
776
- raise CliError(_i18n_exc("agent.non_tty_agent_required", "当前不是交互终端;请显式提供 --agent"))
794
+ raise CliError(_i18n_exc(
795
+ "agent.non_tty_agent_required",
796
+ "当前不是交互终端;请显式提供 --agent",
797
+ ))
777
798
  requested = _prompt_for_hosts(hosts, root)
778
799
  if "all" in requested:
779
800
  available_names = [str(item["name"]) for item in hosts if item["installed"]]
780
801
  if not available_names and not args.allow_missing:
781
802
  raise CliError(_i18n_exc(
782
803
  "plugin.no_agent_detected",
783
- "没有检测到已安装的 AI Agent;请安装 OpenCode/Codex/Claude/ZCode/Pi/ChatGPT,"
784
- "或显式指定 --agent",
804
+ "没有检测到已安装的 AI Agent;请安装 OpenCode/Codex/Claude/ZCode/Pi/ChatGPT,或显式指定 --agent",
785
805
  ))
786
806
  if not available_names and args.allow_missing:
787
807
  available_names = [str(item["name"]) for item in hosts]
788
- expanded = []
808
+ expanded: list[str] = []
789
809
  for name in requested:
790
810
  if name == "all":
791
- for av in available_names:
792
- if av not in expanded:
793
- expanded.append(av)
794
- else:
795
- if name not in expanded:
796
- expanded.append(name)
811
+ for available in available_names:
812
+ if available not in expanded:
813
+ expanded.append(available)
814
+ elif name not in expanded:
815
+ expanded.append(name)
797
816
  requested = expanded
798
- selected = []
799
- seen_adapters = set()
817
+
818
+ selected: list[HostAdapter] = []
819
+ seen_adapters: set[str] = set()
800
820
  for name in requested:
801
821
  try:
802
822
  adapter = get_adapter(name)
@@ -807,8 +827,50 @@ def _command_agent_impl(
807
827
  seen_adapters.add(adapter.name)
808
828
  detected = next(item for item in hosts if item["name"] == adapter.name)
809
829
  if not detected["installed"] and not args.allow_missing:
810
- raise CliError(_i18n_exc("agent.adapter_missing_allow_missing", f"未检测到 {adapter.label};如仍要写入项目入口,请加 --allow-missing", label=adapter.label))
830
+ raise CliError(_i18n_exc(
831
+ "agent.adapter_missing_allow_missing",
832
+ f"未检测到 {adapter.label};如仍要写入项目入口,请加 --allow-missing",
833
+ label=adapter.label,
834
+ ))
811
835
  selected.append(adapter)
836
+ return tuple(selected)
837
+
838
+
839
+ def _command_agent_impl(
840
+ args: argparse.Namespace,
841
+ *,
842
+ progress: _CliProgress | None = None,
843
+ selected_adapters: tuple[HostAdapter, ...] | None = None,
844
+ ) -> int:
845
+ """发现并安装到宿主 AI;不启动宿主,也不执行审计。"""
846
+ root = args.root.resolve()
847
+ command = getattr(args, "agent_command", "install")
848
+ _ensure_core_importable()
849
+ import core.i18n as i18n
850
+ deployment_locale = i18n.resolve_locale().resolved_locale
851
+ if getattr(args, "locale", None):
852
+ norm = i18n.normalize_locale(args.locale)
853
+ if not norm:
854
+ raise CliError(_i18n_exc("common.invalid_locale", f"不支持的 locale: {args.locale};可选:zh-CN, en-US", locale=args.locale))
855
+ deployment_locale = norm
856
+ hosts = discover_hosts(root)
857
+ if command == "discover":
858
+ payload = {"root": str(root), "hosts": hosts, "execution": "none"}
859
+ if args.json:
860
+ print(json.dumps(payload, ensure_ascii=False, indent=2))
861
+ else:
862
+ for item in hosts:
863
+ state = "FOUND" if item["installed"] else "NOT_FOUND"
864
+ executable = item["executable"] or item.get("app_path") or "-"
865
+ print(f"{item['name']}\t{state}\t{executable}\t{item['install_path']}")
866
+ return 0
867
+ if command != "install":
868
+ raise CliError(_i18n_exc("agent.unknown_agent_command", f"未知 Agent 命令: {command}", command=command))
869
+ selected = list(
870
+ _select_install_adapters(args, root, hosts)
871
+ if selected_adapters is None
872
+ else selected_adapters
873
+ )
812
874
  if progress is not None:
813
875
  progress.update(10, "已确认安装目标")
814
876
 
@@ -1505,7 +1567,7 @@ def _command_agent_impl(
1505
1567
  print(f" Claude Desktop 独立安装包:已生成 bugx.plugin 与 bugx.skill({packages_res['dist']})")
1506
1568
  plugins_res = claude_user_agents.get("plugins")
1507
1569
  if isinstance(plugins_res, dict) and plugins_res.get("registered"):
1508
- print(f" Claude Desktop 插件系统:已就绪并启用 bugx@bugx(版本 1.0.0)")
1570
+ print(f" Claude Desktop 插件系统:已就绪并启用 bugx@bugx(版本 {__version__})")
1509
1571
  if (qoder_user_agents := user_agents_by_host.get(HOST_NAME_QODER)) is not None:
1510
1572
  reported_user_agents.add(HOST_NAME_QODER)
1511
1573
  changed = [
@@ -1940,7 +2002,7 @@ def _ensure_dsh_patch(root: Path) -> tuple[str, dict[str, object] | None]:
1940
2002
  # MCP」——修好调用却报告缺失,是更难排查的破窗。
1941
2003
  if patch_path.is_file():
1942
2004
  project_patch = patch_path.read_text(encoding="utf-8")
1943
- with_overlay = _ensure_official_mcp_overlay(project_patch)
2005
+ with_overlay = _ensure_official_mcp_overlay(project_patch, root)
1944
2006
  if with_overlay != project_patch:
1945
2007
  _atomic_write_global_file_tx(patch_path, with_overlay.encode("utf-8"))
1946
2008
  patched = True
@@ -1948,7 +2010,7 @@ def _ensure_dsh_patch(root: Path) -> tuple[str, dict[str, object] | None]:
1948
2010
  # Deploy BugX's agent preset and the browser UI bundle to their native
1949
2011
  # DSH user-level locations.
1950
2012
  try:
1951
- _deploy_dsh_preset()
2013
+ _deploy_dsh_preset(root)
1952
2014
  ui_plugin = _deploy_dsh_ui_plugin()
1953
2015
  except (CliError, OSError) as exc:
1954
2016
  raise CliError(_i18n_exc("agent.dsh_preset_write_failed", f"写入 dsh 全局预设失败:{exc}", exc=exc)) from exc
@@ -1958,7 +2020,7 @@ def _ensure_dsh_patch(root: Path) -> tuple[str, dict[str, object] | None]:
1958
2020
  return ("unchanged", ui_plugin)
1959
2021
 
1960
2022
 
1961
- def _deploy_dsh_preset() -> None:
2023
+ def _deploy_dsh_preset(root: Path) -> None:
1962
2024
  """Deploy the BugX preset cleanly to ~/.dsh/.agent-presets/bugx/.
1963
2025
 
1964
2026
  Reads the installed standard preset, replaces the persona text with BugX's
@@ -1973,62 +2035,31 @@ def _deploy_dsh_preset() -> None:
1973
2035
  standard_preset = next((p for p in candidates if p.is_file()), None)
1974
2036
 
1975
2037
  composition_path = preset_dir / "agent.cordis.yml"
2038
+ # F-RSI-20261119-011/013/014:插件名与行集合都必须跟随**每个 dsh home
2039
+ # 实际使用的运行时**。CLI dsh 0.1.1-rc.2 只有 worker-thread;DSH Desktop
2040
+ # 0.14+ 随 app.asar 内置 dsh 0.2.2(只认 workflow-ptc,且启动校验会把
2041
+ # worker-thread 判为 blocking 错误)。desktop home 直接使用 Desktop 自带
2042
+ # 的官方 standard preset 模板(dsh-web-app/presets/standard.patch.yml),
2043
+ # CLI home 继续用 CLI dsh 包内模板——两侧都与其运行时自洽。
1976
2044
  if standard_preset and standard_preset.is_file():
1977
2045
  lines = standard_preset.read_text(encoding="utf-8").splitlines()
1978
- out_lines = []
1979
- i = 0
1980
- while i < len(lines):
1981
- line = lines[i]
1982
- if line.strip() == "- id: persona":
1983
- # Emit a single persona entry with the BugX persona text.
1984
- out_lines.append("- id: persona")
1985
- out_lines.append(" name: '@deepseek-ai/dsh-persona'")
1986
- out_lines.append(" config:")
1987
- out_lines.append(" prefix: >-")
1988
- out_lines.append(" You are BugX, an autonomous adversarial code-audit agent. Before")
1989
- out_lines.append(" any exploration, first run bugx engine path --name bugx-quick.md (the L0 protocol card), then consult the global AGENT_GUIDE.md and bugx.md sections on demand, and")
1990
- out_lines.append(" follow the life-ledger, supervisor lease, evidence and report protocol. The DSH package checkout and DSH_HOME are not the project root; use the active Session cwd for every project path and run pwd when paths are ambiguous.")
1991
- # Skip every remaining line of the original persona entry.
1992
- i += 1
1993
- while i < len(lines) and not lines[i].strip().startswith("- id:"):
1994
- i += 1
1995
- continue
1996
- if line.strip() == "- id: workflow-worker-thread":
1997
- indent = len(line) - len(line.lstrip())
1998
- line = (" " * indent) + "- id: workflow-ptc"
1999
- elif "@deepseek-ai/dsh-workflow-worker-thread" in line:
2000
- indent = len(line) - len(line.lstrip())
2001
- line = (" " * indent) + "name: '@deepseek-ai/dsh-workflow-ptc'"
2002
- out_lines.append(line)
2003
- i += 1
2046
+ out_lines = _apply_bugx_persona(lines)
2004
2047
  else:
2005
2048
  # Fallback: minimal viable preset composition when the installed dsh
2006
2049
  # standard template is not discoverable (e.g. isolated test HOME).
2007
- out_lines = [
2050
+ out_lines = _apply_bugx_persona([
2008
2051
  "# BugX minimal preset composition (fallback).",
2009
2052
  "- id: persona",
2010
2053
  " name: '@deepseek-ai/dsh-persona'",
2011
2054
  " config:",
2012
- " prefix: >-",
2013
- " You are BugX, an autonomous adversarial code-audit agent. Before",
2014
- " any exploration, first run bugx engine path --name bugx-quick.md (L0 card), then consult the global AGENT_GUIDE.md and bugx.md sections on demand,",
2015
- " and follow the life-ledger, supervisor lease, evidence protocol. The DSH package checkout and DSH_HOME are not the project root; use the active Session cwd for every project path and run pwd when paths are ambiguous.",
2055
+ " prefix: placeholder",
2016
2056
  "- id: skill-filesystem",
2017
2057
  " name: '@deepseek-ai/dsh-skill-filesystem'",
2018
- ]
2058
+ ])
2019
2059
 
2020
2060
  # Native DSH questions are an agent capability, not merely a skill
2021
- # instruction. Older standard presets and the isolated fallback may not
2022
- # include the model-facing tool, so make the registration idempotently
2023
- # explicit. The Web/TUI answerer remains host-owned and is not mounted
2024
- # into the agent preset.
2025
- if "@deepseek-ai/dsh-tool-ask-user" not in "\n".join(out_lines):
2026
- out_lines.extend([
2027
- "",
2028
- "# ── BugX native question interaction ───────────────────────────────────",
2029
- "- id: tool-ask-user",
2030
- " name: '@deepseek-ai/dsh-tool-ask-user'",
2031
- ])
2061
+ # instruction; the check below runs on the final per-home composition
2062
+ # inside the write loop (Desktop's official template already carries it).
2032
2063
 
2033
2064
  # 预设层**不再**注入 MCP client。三条通道(supervisor / supervisor-worker /
2034
2065
  # docs)由 ``core/hosts/dsh.py::_mcp_insert_block`` 以官方
@@ -2049,9 +2080,31 @@ def _deploy_dsh_preset() -> None:
2049
2080
  "适合在项目提测发版前、安全合规体检或排查疑难缺陷时开启;日常开发与普通交流不打扰。"
2050
2081
  )
2051
2082
  preset_order = 0
2052
- composition_text = "\n".join(out_lines) + "\n"
2053
2083
 
2054
2084
  for home in _all_dsh_homes():
2085
+ preset_plugin, workflow_plugin = _dsh_runtime_plugin_names(home)
2086
+ if "dsh-desktop" in home.parts:
2087
+ # F-RSI-20261119-014:desktop home 使用 Desktop 自带的官方
2088
+ # standard preset 模板——CLI 0.1.1 模板里的 0.1.x 专属行
2089
+ # (tool-ralph、tool-subagent-codex/claude-code/list-agents)在
2090
+ # 0.2.x 官方 preset 中已被移除,其激活在 0.2.x 运行时上会失败,
2091
+ # registry 据此把整个 preset 判为 broken(UI 显示「加载失败」)。
2092
+ desktop_template = _dsh_desktop_standard_template()
2093
+ base_lines = (
2094
+ _apply_bugx_persona(_dsh_desktop_preset_rows(desktop_template))
2095
+ if desktop_template else out_lines
2096
+ )
2097
+ else:
2098
+ base_lines = out_lines
2099
+ composition_lines = _rewrite_dsh_workflow_plugin(base_lines, workflow_plugin)
2100
+ if "@deepseek-ai/dsh-tool-ask-user" not in "\n".join(composition_lines):
2101
+ composition_lines.extend([
2102
+ "",
2103
+ "# ── BugX native question interaction ───────────────────────────────────",
2104
+ "- id: tool-ask-user",
2105
+ " name: '@deepseek-ai/dsh-tool-ask-user'",
2106
+ ])
2107
+ composition_text = "\n".join(composition_lines) + "\n"
2055
2108
  p_dir = home / ".agent-presets" / "bugx"
2056
2109
  _assert_no_symlink_components(p_dir)
2057
2110
  p_dir.mkdir(parents=True, exist_ok=True)
@@ -2074,15 +2127,248 @@ def _deploy_dsh_preset() -> None:
2074
2127
  name=preset_name,
2075
2128
  description=preset_desc.replace("\n", " "),
2076
2129
  order=preset_order,
2130
+ preset_plugin_name=preset_plugin,
2131
+ root=root,
2077
2132
  )
2078
2133
 
2079
2134
 
2135
+ _DSH_LEGACY_WORKFLOW_PLUGIN = "@deepseek-ai/dsh-workflow-worker-thread"
2136
+ _DSH_PTC_WORKFLOW_PLUGIN = "@deepseek-ai/dsh-workflow-ptc"
2137
+
2138
+
2139
+ def _dsh_desktop_asar_candidates() -> list[Path]:
2140
+ """Return DSH Desktop ``app.asar`` paths that may carry the bundled runtime."""
2141
+ resources = Path("Contents", "Resources", "app.asar")
2142
+ return [
2143
+ Path.home().resolve() / "Applications" / "DSH Desktop.app" / resources,
2144
+ Path("/Applications") / "DSH Desktop.app" / resources,
2145
+ ]
2146
+
2147
+
2148
+ def _asar_lists_bundled_package(asar: Path, package: str) -> bool:
2149
+ """Check an Electron ``app.asar`` header for ``node_modules/@deepseek-ai/<package>``.
2150
+
2151
+ DSH Desktop bundles its entire dsh runtime inside app.asar instead of the
2152
+ harness profile, so probing the profile's node_modules tells us what the
2153
+ *CLI* installed there, not what the Desktop runtime resolves at launch.
2154
+ Only the asar header is read; file payloads are never touched.
2155
+ """
2156
+ try:
2157
+ with asar.open("rb") as handle:
2158
+ head = handle.read(8)
2159
+ if len(head) < 8:
2160
+ return False
2161
+ header_size = struct.unpack("<I", head[4:8])[0]
2162
+ if header_size <= 0 or header_size > 64 * 1024 * 1024:
2163
+ return False
2164
+ header = handle.read(header_size)
2165
+ except OSError:
2166
+ return False
2167
+ # The asar header is a nested file tree, so the package path never appears
2168
+ # as one contiguous byte string; parse the JSON and walk the "files" maps.
2169
+ start = header.find(b'{"files":')
2170
+ if start < 0:
2171
+ return False
2172
+ try:
2173
+ tree, _ = json.JSONDecoder().raw_decode(
2174
+ header[start:].decode("utf-8", "ignore"),
2175
+ )
2176
+ except (UnicodeDecodeError, json.JSONDecodeError):
2177
+ return False
2178
+ node: Any = tree
2179
+ for part in ("files", "node_modules", "files", "@deepseek-ai", "files", package):
2180
+ if not isinstance(node, dict):
2181
+ return False
2182
+ node = node.get(part)
2183
+ return isinstance(node, dict)
2184
+
2185
+
2186
+ def _dsh_desktop_runtime_names() -> tuple[str, str] | None:
2187
+ """Detect the preset/workflow plugin names DSH Desktop's bundled runtime accepts.
2188
+
2189
+ DSH Desktop 0.14 bundles dsh 0.2.2: ``@deepseek-ai/dsh-agent-preset``
2190
+ (singular) and ``@deepseek-ai/dsh-workflow-ptc``. Older Desktop builds
2191
+ bundled the 0.1.x names (plural preset plugin + worker-thread). The
2192
+ bundled app.asar is the only authoritative source for the desktop home.
2193
+ """
2194
+ for asar in _dsh_desktop_asar_candidates():
2195
+ if not asar.is_file():
2196
+ continue
2197
+ if _asar_lists_bundled_package(asar, "dsh-workflow-ptc"):
2198
+ return ("@deepseek-ai/dsh-agent-preset", _DSH_PTC_WORKFLOW_PLUGIN)
2199
+ if _asar_lists_bundled_package(asar, "dsh-workflow-worker-thread"):
2200
+ return ("@deepseek-ai/dsh-agent-presets", _DSH_LEGACY_WORKFLOW_PLUGIN)
2201
+ return None
2202
+
2203
+
2204
+ def _dsh_runtime_plugin_names(home: Path) -> tuple[str, str]:
2205
+ """Return ``(preset_plugin_name, workflow_plugin_name)`` for one dsh home.
2206
+
2207
+ F-RSI-20261119-012/013:包名随 dsh 版本变化——0.1.1-rc.2 是
2208
+ 复数 ``dsh-agent-presets`` + ``dsh-workflow-worker-thread``;0.2.x 是
2209
+ 单数 ``dsh-agent-preset`` + ``dsh-workflow-ptc``。DSH Desktop 的运行时
2210
+ 内置在 app.asar 中,必须先探测 asar;其余 home 以
2211
+ ``profiles/node_modules`` 为准(那是其插件解析根)。
2212
+ """
2213
+ if "dsh-desktop" in home.parts:
2214
+ detected = _dsh_desktop_runtime_names()
2215
+ if detected is not None:
2216
+ return detected
2217
+ base = home / "profiles" / "node_modules" / "@deepseek-ai"
2218
+ if (base / "dsh-agent-preset").is_dir():
2219
+ preset_plugin = "@deepseek-ai/dsh-agent-preset"
2220
+ else:
2221
+ preset_plugin = "@deepseek-ai/dsh-agent-presets"
2222
+ if (base / "dsh-workflow-ptc").is_dir():
2223
+ workflow_plugin = _DSH_PTC_WORKFLOW_PLUGIN
2224
+ else:
2225
+ workflow_plugin = _DSH_LEGACY_WORKFLOW_PLUGIN
2226
+ return preset_plugin, workflow_plugin
2227
+
2228
+
2229
+ def _rewrite_dsh_workflow_plugin(
2230
+ lines: list[str], workflow_plugin: str,
2231
+ ) -> list[str]:
2232
+ """Rewrite the template's worker-thread row to the home's workflow plugin."""
2233
+ if workflow_plugin == _DSH_LEGACY_WORKFLOW_PLUGIN:
2234
+ return list(lines)
2235
+ out: list[str] = []
2236
+ for line in lines:
2237
+ stripped = line.strip()
2238
+ indent = len(line) - len(line.lstrip())
2239
+ if stripped == "- id: workflow-worker-thread":
2240
+ line = (" " * indent) + "- id: workflow-ptc"
2241
+ elif _DSH_LEGACY_WORKFLOW_PLUGIN in line:
2242
+ line = (" " * indent) + f"name: '{_DSH_PTC_WORKFLOW_PLUGIN}'"
2243
+ out.append(line)
2244
+ return out
2245
+
2246
+
2247
+ _BUGX_PERSONA_TEXT = (
2248
+ "You are BugX, an autonomous adversarial code-audit agent. Before any "
2249
+ "exploration, first run bugx engine path --name bugx-quick.md (the L0 "
2250
+ "protocol card), then consult the global AGENT_GUIDE.md and bugx.md "
2251
+ "sections on demand, and follow the life-ledger, supervisor lease, "
2252
+ "evidence and report protocol. The DSH package checkout and DSH_HOME are "
2253
+ "not the project root; use the active Session cwd for every project path "
2254
+ "and run pwd when paths are ambiguous."
2255
+ )
2256
+
2257
+
2258
+ def _persona_block_lines(indent: str) -> list[str]:
2259
+ """One persona entry with the BugX persona text at ``indent`` (may be empty)."""
2260
+ lines = [
2261
+ f"{indent}- id: persona",
2262
+ f"{indent} name: '@deepseek-ai/dsh-persona'",
2263
+ f"{indent} config:",
2264
+ f"{indent} prefix: >-",
2265
+ ]
2266
+ # Folded scalar (>-): line breaks fold into spaces, so wrapping is cosmetic.
2267
+ words = _BUGX_PERSONA_TEXT.split(" ")
2268
+ row: list[str] = []
2269
+ for word in words:
2270
+ row.append(word)
2271
+ if len(" ".join(row)) >= 96:
2272
+ lines.append(f"{indent} {' '.join(row)}")
2273
+ row = []
2274
+ if row:
2275
+ lines.append(f"{indent} {' '.join(row)}")
2276
+ return lines
2277
+
2278
+
2279
+ def _apply_bugx_persona(lines: list[str]) -> list[str]:
2280
+ """Replace the template's persona entry with BugX's, preserving indentation."""
2281
+ out: list[str] = []
2282
+ i = 0
2283
+ while i < len(lines):
2284
+ line = lines[i]
2285
+ if line.strip() == "- id: persona":
2286
+ indent = " " * (len(line) - len(line.lstrip()))
2287
+ out.extend(_persona_block_lines(indent))
2288
+ # Skip every remaining line of the original persona entry.
2289
+ i += 1
2290
+ while i < len(lines) and not lines[i].strip().startswith("- id:"):
2291
+ i += 1
2292
+ continue
2293
+ out.append(line)
2294
+ i += 1
2295
+ return out
2296
+
2297
+
2298
+ def _asar_read_text(asar: Path, member: str) -> str | None:
2299
+ """Read one UTF-8 file out of an Electron ``app.asar`` by archive path."""
2300
+ try:
2301
+ with asar.open("rb") as handle:
2302
+ head = handle.read(8)
2303
+ if len(head) < 8:
2304
+ return None
2305
+ header_size = struct.unpack("<I", head[4:8])[0]
2306
+ if header_size <= 0 or header_size > 64 * 1024 * 1024:
2307
+ return None
2308
+ header = handle.read(header_size)
2309
+ start = header.find(b'{"files":')
2310
+ if start < 0:
2311
+ return None
2312
+ tree, _ = json.JSONDecoder().raw_decode(
2313
+ header[start:].decode("utf-8", "ignore"),
2314
+ )
2315
+ node: Any = tree
2316
+ for part in member.split("/"):
2317
+ if not isinstance(node, dict):
2318
+ return None
2319
+ node = node.get("files", {}).get(part) if "files" in node else node.get(part)
2320
+ if node is None:
2321
+ return None
2322
+ if not isinstance(node, dict) or "offset" not in node:
2323
+ return None
2324
+ handle.seek(int(node["offset"]) + 8 + header_size)
2325
+ return handle.read(int(node["size"])).decode("utf-8")
2326
+ except (OSError, UnicodeDecodeError, json.JSONDecodeError):
2327
+ return None
2328
+
2329
+
2330
+ _DSH_DESKTOP_STANDARD_PRESET_MEMBER = (
2331
+ "node_modules/@deepseek-ai/dsh-web-app/presets/standard.patch.yml"
2332
+ )
2333
+
2334
+
2335
+ def _dsh_desktop_standard_template() -> str | None:
2336
+ """DSH Desktop 自带的官方 standard preset 组态(0.2.x 行集合)。
2337
+
2338
+ F-RSI-20261119-014:desktop home 的 preset 行集合必须与其内置运行时
2339
+ 同代。CLI dsh 包内模板是 0.1.x 行集合(tool-ralph 等),在 0.2.x 上
2340
+ 激活失败会让 registry 把 preset 判 broken;Desktop 随包分发的
2341
+ ``dsh-web-app/presets/standard.patch.yml`` 是唯一与其运行时自洽的
2342
+ 官方行集合来源。旧版 Desktop 没有该文件时返回 None(回退 CLI 模板)。
2343
+ """
2344
+ for asar in _dsh_desktop_asar_candidates():
2345
+ if not asar.is_file():
2346
+ continue
2347
+ text = _asar_read_text(asar, _DSH_DESKTOP_STANDARD_PRESET_MEMBER)
2348
+ if text:
2349
+ return text
2350
+ return None
2351
+
2352
+
2353
+ def _dsh_desktop_preset_rows(template_text: str) -> list[str]:
2354
+ """Extract the plugin rows under the official template's ``plugins:`` key."""
2355
+ lines = template_text.splitlines()
2356
+ for idx, line in enumerate(lines):
2357
+ if line.strip() == "plugins:":
2358
+ rows = lines[idx + 1:]
2359
+ while rows and not rows[-1].strip():
2360
+ rows.pop()
2361
+ return rows
2362
+ return []
2363
+
2364
+
2080
2365
  def _format_dsh_preset_patch(
2081
2366
  preset_id: str,
2082
2367
  composition_text: str,
2083
2368
  name: str,
2084
2369
  description: str,
2085
2370
  order: int = 0,
2371
+ preset_plugin_name: str = "@deepseek-ai/dsh-agent-presets",
2086
2372
  ) -> str:
2087
2373
  """Format an agent-preset patch block for DSH profile cordis.patch.yml."""
2088
2374
  fields = [f" id: {preset_id}"]
@@ -2092,13 +2378,15 @@ def _format_dsh_preset_patch(
2092
2378
  fields.append(f" order: {order}")
2093
2379
 
2094
2380
  rows = []
2095
- for line in composition_text.strip().splitlines():
2381
+ # rstrip(而非 strip):desktop 官方模板的组态首行自带缩进,strip 会把
2382
+ # 首行缩进剥掉,产出错位的 patch 块(YAML 解析失败 → preset broken)。
2383
+ for line in composition_text.rstrip("\n").splitlines():
2096
2384
  rows.append(f" {line}" if line.strip() else "")
2097
2385
 
2098
2386
  header = (
2099
2387
  f"- insert:\n"
2100
2388
  f" - id: preset-{preset_id}\n"
2101
- f" name: '@deepseek-ai/dsh-agent-preset'\n"
2389
+ f" name: '{preset_plugin_name}'\n"
2102
2390
  f" config:"
2103
2391
  )
2104
2392
  return (
@@ -2116,17 +2404,40 @@ def _sync_dsh_profile_patch(
2116
2404
  name: str,
2117
2405
  description: str,
2118
2406
  order: int = 0,
2407
+ preset_plugin_name: str = "@deepseek-ai/dsh-agent-presets",
2408
+ root: Path | None = None,
2119
2409
  ) -> None:
2120
- """Ensure profiles/web/cordis.patch.yml carries the latest preset patch block."""
2121
- profile_dir = home / "profiles" / "web"
2122
- if not profile_dir.is_dir():
2123
- return
2410
+ """Ensure profiles/{web,desktop}/cordis.patch.yml carry the latest preset block.
2411
+
2412
+ F-RSI-20261119-012:DSH Desktop 的会话实际读 ``profiles/desktop`` 的
2413
+ legacy preset 块;此前只同步 ``profiles/web``,导致 desktop 侧残留旧
2414
+ preset(错误插件名)并使「自定义 agent 加载失败」。
2415
+ """
2416
+ patch_block = _format_dsh_preset_patch(
2417
+ preset_id, composition_text, name, description, order,
2418
+ preset_plugin_name=preset_plugin_name,
2419
+ )
2420
+ for profile_name in ("web", "desktop"):
2421
+ profile_dir = home / "profiles" / profile_name
2422
+ if not profile_dir.is_dir():
2423
+ continue
2424
+ _sync_one_profile_patch(
2425
+ profile_dir, profile_name, preset_id, patch_block, root=root,
2426
+ )
2427
+
2428
+
2429
+ def _sync_one_profile_patch(
2430
+ profile_dir: Path,
2431
+ profile_name: str,
2432
+ preset_id: str,
2433
+ patch_block: str,
2434
+ root: Path | None = None,
2435
+ ) -> None:
2436
+ """把 preset 块写入/替换到单个 profile 的 cordis.patch.yml。"""
2124
2437
  patch_path = profile_dir / "cordis.patch.yml"
2125
2438
  _assert_no_symlink_components(patch_path)
2126
- patch_block = _format_dsh_preset_patch(preset_id, composition_text, name, description, order)
2127
-
2128
2439
  if not patch_path.is_file():
2129
- content = f"# Web profile user patch layer\n\n{patch_block}\n"
2440
+ content = f"# {profile_name.capitalize()} profile user patch layer\n\n{patch_block}\n"
2130
2441
  _atomic_write_global_file_tx(patch_path, content.encode("utf-8"))
2131
2442
  return
2132
2443
 
@@ -2150,7 +2461,9 @@ def _sync_dsh_profile_patch(
2150
2461
  else:
2151
2462
  updated = f"{content.rstrip()}\n\n{patch_block}\n"
2152
2463
 
2153
- updated = _ensure_official_mcp_overlay(updated)
2464
+ if root is None:
2465
+ raise CliError("_sync_one_profile_patch 需要 root 以绝对化 MCP --root/--db(F-RSI-20261119-015)")
2466
+ updated = _ensure_official_mcp_overlay(updated, root)
2154
2467
 
2155
2468
  if updated != content:
2156
2469
  _atomic_write_global_file_tx(patch_path, updated.encode("utf-8"))
@@ -2160,17 +2473,28 @@ def _sync_dsh_profile_patch(
2160
2473
  _OFFICIAL_MCP_CLIENT = "@deepseek-ai/dsh-mcp-client"
2161
2474
  #: 三条受控通道;serverName 必须唯一,且与 core/hosts/dsh.py 的声明一致。
2162
2475
  _OFFICIAL_MCP_SERVERS = (
2163
- ("bugx-supervisor", ["mcp", "serve", "--root", "."]),
2164
- ("bugx-supervisor-worker", ["mcp", "serve", "--root", ".", "--role", "worker"]),
2165
- ("bugx-docs", ["mcp", "docs", "serve", "--root", ".", "--db",
2166
- ".bugx/knowledge/docs.sqlite3"]),
2476
+ # F-RSI-20261119-015:与 core/hosts/dsh.py::_MCP_SERVERS 同一契约——
2477
+ # dsh 的 MCP server 由宿主进程 spawn,cwd 不是工作区,``--root .`` 会解析
2478
+ # 到宿主自己的 cwd(实测报「缺少有效的 .bugx 项目运行布局」)。因此这里
2479
+ # 与 install 侧一样使用 {ROOT} 占位,由 overlay 以**绝对项目根**替换。
2480
+ # 修改任一侧时必须同步另一侧,两处常量必须逐字一致。
2481
+ ("bugx-supervisor", ["mcp", "serve", "--root", "{ROOT}"]),
2482
+ ("bugx-supervisor-worker", ["mcp", "serve", "--root", "{ROOT}", "--role", "worker"]),
2483
+ ("bugx-docs", ["mcp", "docs", "serve", "--root", "{ROOT}", "--db",
2484
+ "{ROOT}/.bugx/knowledge/docs.sqlite3"]),
2167
2485
  )
2168
2486
  _OFFICIAL_MCP_MARKER = "# BugX MCP overlay — official dsh-mcp-client (stdio)"
2169
2487
 
2170
2488
 
2171
- def _ensure_official_mcp_overlay(content: str) -> str:
2489
+ def _ensure_official_mcp_overlay(content: str, root: Path) -> str:
2172
2490
  """向 profile patch 追加/更新官方 MCP 三通道 ``- insert:`` 块。
2173
2491
 
2492
+ ``root`` 是安装时项目根:``--root``/``--db`` 必须随根绝对化(契约见
2493
+ core/hosts/dsh.py::_MCP_SERVERS 注释——宿主进程 spawn 的 MCP server cwd
2494
+ 不是工作区,相对路径会解析到宿主 cwd)。此前这里写死 ``--root .``,与
2495
+ install 侧的绝对根互相覆盖:install 写对、deploy 又改回相对路径,两条
2496
+ 路径产物永不相等(F-RSI-20261119-015)。
2497
+
2174
2498
  为什么必须由 install 自己写:``bugx install --agent dsh`` 之后
2175
2499
  ``bugx doctor`` 的「DeepSeek Harness MCP 配置」会扫项目 patch 与全局预设,
2176
2500
  确认 supervisor 通道存在。此前这份内容由预设层的第三方
@@ -2180,6 +2504,7 @@ def _ensure_official_mcp_overlay(content: str) -> str:
2180
2504
  不再承载 MCP,若 install 也不写,doctor 就会判定「缺少 bugx-supervisor
2181
2505
  MCP」,形成「修好调用却报告缺失」的新破窗。
2182
2506
  """
2507
+ root_text = str(Path(root).resolve())
2183
2508
  lines = [_OFFICIAL_MCP_MARKER, "- insert:"]
2184
2509
  for server_name, argv in _OFFICIAL_MCP_SERVERS:
2185
2510
  lines.extend([
@@ -2191,7 +2516,9 @@ def _ensure_official_mcp_overlay(content: str) -> str:
2191
2516
  " command: bugx",
2192
2517
  " args:",
2193
2518
  ])
2194
- lines.extend(f" - '{arg}'" for arg in argv)
2519
+ lines.extend(
2520
+ f" - '{arg.replace('{ROOT}', root_text)}'" for arg in argv
2521
+ )
2195
2522
  block = "\n".join(lines) + "\n"
2196
2523
 
2197
2524
  # 归一算法(2026-11-08 实测重写,两次迭代):按**条目 id** 识别受控块,
@@ -2539,8 +2866,8 @@ def _unlink_global_pi_skill(root: Path, removed: list[str], preserved: list[str]
2539
2866
  def _sync_workbuddy_private_venv(
2540
2867
  source: Path, *, target_version: str | None = None,
2541
2868
  ) -> tuple[bool, str]:
2542
- """探测并同步 WorkBuddy 私有 Python 虚拟环境中的 bugx-agent 包 (DOC-181)。"""
2543
- from bugx_cli.host_adapters import workbuddy_cli_venv
2869
+ """探测并同步 WorkBuddy 私有 Python 虚拟环境中的 bugx-cli 包 (DOC-181)。"""
2870
+ from ..host_adapters import workbuddy_cli_venv
2544
2871
  venv = workbuddy_cli_venv()
2545
2872
  if not venv:
2546
2873
  return False, "未检测到 WorkBuddy 私有虚拟环境"
@@ -2556,7 +2883,7 @@ def _sync_workbuddy_private_venv(
2556
2883
  if is_source:
2557
2884
  cmd = [str(py_exe), "-m", "pip", "install", "-e", str(source.resolve()), "--no-deps"]
2558
2885
  else:
2559
- pkg = f"bugx-agent=={target_version}" if target_version else "bugx-agent"
2886
+ pkg = f"bugx-cli=={target_version}" if target_version else "bugx-cli"
2560
2887
  cmd = [str(py_exe), "-m", "pip", "install", "--upgrade", pkg, "--no-deps"]
2561
2888
  try:
2562
2889
  proc = subprocess.run(
@@ -2879,7 +3206,7 @@ def _ensure_workbuddy_custom_expert(
2879
3206
  # 3. Plugin manifest
2880
3207
  plugin_meta = {
2881
3208
  "name": "bugx",
2882
- "version": "1.0.0",
3209
+ "version": __version__,
2883
3210
  "expertType": "agent",
2884
3211
  "displayName": {
2885
3212
  "zh": "BugX",
@@ -3500,7 +3827,7 @@ def _check_host_mcp_config(root: Path, host_name: str, *, repair: bool = False)
3500
3827
  return False, "缺少 .agents/plugins/marketplace.json;请运行 bugx install --agent chatgpt"
3501
3828
 
3502
3829
  if host_name == "workbuddy":
3503
- from bugx_cli.host_adapters import WORKBUDDY_PROJECT_PATHS
3830
+ from ..host_adapters import WORKBUDDY_PROJECT_PATHS
3504
3831
 
3505
3832
  missing = [relative for relative in WORKBUDDY_PROJECT_PATHS
3506
3833
  if not (root / relative).is_file()]
@@ -3527,7 +3854,7 @@ def _check_host_mcp_config(root: Path, host_name: str, *, repair: bool = False)
3527
3854
  return False, user_detail
3528
3855
 
3529
3856
  # DOC-181 方案 2:WorkBuddy 沙箱 Python 运行态一致性检查与自愈
3530
- from bugx_cli.host_adapters import workbuddy_cli_venv, workbuddy_cli_venv_version
3857
+ from ..host_adapters import workbuddy_cli_venv, workbuddy_cli_venv_version
3531
3858
  venv = workbuddy_cli_venv()
3532
3859
  venv_detail = ""
3533
3860
  if venv is not None: