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
@@ -1,6 +1,7 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  import argparse
4
+ import concurrent.futures
4
5
  import copy
5
6
  import hashlib
6
7
  import json
@@ -171,7 +172,7 @@ def _heal_project_manifest_version(root: Path, *, force: bool = False) -> tuple[
171
172
  运行态(生命、结算、错题集)。
172
173
 
173
174
  历史缺陷:这段自愈原先嵌在 ``if not version_ok:`` 里,而
174
- ``_version_contract_status`` 的归一化会把 ``1.0.0+2`` 视同 ``1.0.0`` 并返回
175
+ ``_version_contract_status`` 的归一化会把 ``0.1.1+2`` 视同 ``0.1.1`` 并返回
175
176
  ``version_ok=True``,于是**自愈分支永远进不去**——清单永久停在旧标记,而引擎
176
177
  门禁(另一套不归一化的比较)却一直拒绝启动。虚假阻断就这样被"修"成了永久阻断。
177
178
  """
@@ -502,7 +503,7 @@ def _inspect_cli_entry(path: Path) -> dict[str, Any]:
502
503
  if proc.returncode == 0:
503
504
  out = proc.stdout.strip()
504
505
  parts = out.split()
505
- if len(parts) >= 2 and parts[0] in ("bugx", "bugx-agent"):
506
+ if len(parts) >= 2 and parts[0] == "bugx":
506
507
  version = parts[1]
507
508
  elif parts:
508
509
  version = parts[-1]
@@ -786,8 +787,9 @@ def _generate_ai_diagnostics(
786
787
  root: Path,
787
788
  strict: bool = False,
788
789
  auto_repairable_checks: set[str] | None = None,
790
+ use_ai: bool = False,
789
791
  ) -> dict[str, Any]:
790
- """基于失败项生成 AI 根因分析和本地确定性修复提示。"""
792
+ """基于失败项生成根因分析和修复提示(默认确定性基线,--ai 开启 AI 深诊)。"""
791
793
  from ..infra.ai_advisor import DiagnosticAIArbitrator
792
794
  arbitrator = DiagnosticAIArbitrator(root)
793
795
  result = arbitrator.diagnose(
@@ -795,6 +797,7 @@ def _generate_ai_diagnostics(
795
797
  installation_required,
796
798
  strict=strict,
797
799
  auto_repairable_checks=auto_repairable_checks,
800
+ use_ai=use_ai,
798
801
  )
799
802
  return result.as_dict()
800
803
 
@@ -824,6 +827,325 @@ def _render_ai_diagnostics_panel(ai_diag: dict[str, Any], is_explicit_ai: bool =
824
827
  print("╰───────────────────────────────────────────────────────────────────────╯")
825
828
 
826
829
 
830
+ # ---------------------------------------------------------------------------
831
+ # Doctor 并行只读探测(耗时账目 W-002 遗留性能项)
832
+ #
833
+ # 检查项并行性分类(依据 command_doctor 的检查链逐项审计):
834
+ # - 【纯读取可并行】只读文件系统 / 进程表 / 网络探测,互相独立、无顺序依赖:
835
+ # 工作树卫生、云端端点连通性、全局引擎完整性判定、版本契约判定、引擎副本
836
+ # 一致性、OpenCode/Pi 全局入口完整性、各宿主 MCP 配置(repair=False)、
837
+ # 错题集账本、全局错题集、codebase-memory 探测、基础效率工具、MCP 离线
838
+ # runtime 诊断、MCP 会话进程卫生、UI 环境状态、BugX CLI 路径。
839
+ # - 【有写操作须串行】所有 --repair 写路径永远不进入并行块:
840
+ # layout_module.repair / _doctor_repair_assets(项目资产修复)、
841
+ # _install_engine(force=True)(引擎重放)、_heal_project_manifest_version
842
+ # (清单自愈)、pip install(Tree-sitter 补装)、
843
+ # _check_host_mcp_config(repair=True)。因此并行批只在
844
+ # 「非 --repair 且非 --installation-only」的运行态诊断启用,两种模式都
845
+ # 保持原串行路径不变。
846
+ # - 【有顺序依赖】项目初始化状态/.bugx 运行目录依赖 manifest+layout;
847
+ # 宿主适配包检查(_host_bundle_checks)的 installed_host_names 是
848
+ # OpenCode/Pi/MCP 配置检查的注册条件;错题集依赖 initialized;
849
+ # 全局错题集与 UI 检查依赖 layout/ui_script 存在性。这些依赖在入批前
850
+ # 已由串行前置段完成。
851
+ # 渲染处按原始行序从并行结果中取值;timeout 语义与判定逻辑逐字保留。
852
+ # ---------------------------------------------------------------------------
853
+
854
+ _DOCTOR_PARALLEL_MAX_WORKERS = 6
855
+
856
+
857
+ def _doctor_probe_job(fn):
858
+ """包装单个并行探测任务。
859
+
860
+ 各检查 row 函数已在内部按串行语义捕获预期异常类型;此处仅兜底意外异常,
861
+ 取用处(_unwrap_parallel_result)会将其原样重抛,保持与串行实现一致的
862
+ 失败行为:意外异常 = 命令失败,而不是静默降级。
863
+ """
864
+ try:
865
+ return ("ok", fn())
866
+ except Exception as exc: # noqa: BLE001 - 意外异常延迟到取用处重抛
867
+ return ("error", exc)
868
+
869
+
870
+ def _unwrap_parallel_result(parallel_results: dict[str, Any], key: str) -> Any:
871
+ status, value = parallel_results[key]
872
+ if status != "ok":
873
+ raise value
874
+ return value
875
+
876
+
877
+ def _engine_integrity_check_row() -> tuple[bool, str]:
878
+ """全局引擎完整性(只读判定;--repair 的引擎重放写路径留在串行段)。"""
879
+ try:
880
+ return _engine_integrity_status(asset_root(), global_engine_root())
881
+ except (CliError, OSError, ValueError) as exc:
882
+ return False, f"全局引擎无法校验:{exc}"
883
+
884
+
885
+ def _version_contract_check_row(root: Path) -> tuple[bool, str]:
886
+ """版本契约一致性(只读;--repair 的清单自愈写路径留在串行段)。"""
887
+ try:
888
+ return _version_contract_status(root, global_engine_root())
889
+ except (CliError, OSError, ValueError) as exc:
890
+ return False, f"版本契约无法校验:{exc}"
891
+
892
+
893
+ def _lesson_ledger_check_row(root: Path, lesson_json: Path) -> tuple[bool, str]:
894
+ lesson_db = lesson_json.with_suffix(".sqlite3")
895
+ if not lesson_db.is_file() or lesson_db.is_symlink():
896
+ return False, "缺少或不安全的 SQLite 运行库;请从备份恢复,禁止静默重建"
897
+ try:
898
+ result = subprocess.run(
899
+ [sys.executable, str(_script(root, "lesson_ledger.py")),
900
+ "validate", "--ledger", str(lesson_json), "--json"],
901
+ cwd=root, capture_output=True, text=True, check=False, timeout=30,
902
+ env=_python_environment(),
903
+ )
904
+ lesson_ready = result.returncode == 0
905
+ lesson_detail = ("SQLite 运行库有效" if lesson_ready else (
906
+ (result.stderr or result.stdout).strip()[:500] or "SQLite 校验失败"
907
+ ))
908
+ if lesson_ready and (not lesson_json.is_file() or lesson_json.is_symlink()):
909
+ lesson_detail += ";JSON 种子缺失(不影响读取,恢复时需人工确认)"
910
+ return lesson_ready, lesson_detail
911
+ except (OSError, subprocess.TimeoutExpired, CliError) as exc:
912
+ return False, f"SQLite 校验异常:{exc}"
913
+
914
+
915
+ def _global_lesson_ledger_check_row(root: Path, layout: Any) -> tuple[bool, str]:
916
+ global_db = layout.global_knowledge_db
917
+ global_marker = layout.global_knowledge_root / "manifest.json"
918
+ if not global_marker.exists() and not global_db.exists():
919
+ return True, "尚未初始化;项目库可独立运行"
920
+ if not global_db.is_file() or global_db.is_symlink():
921
+ return False, "全局 SQLite 缺失;不会静默从 JSON 重建"
922
+ try:
923
+ result = subprocess.run(
924
+ [sys.executable, str(_script(root, "lesson_ledger.py")),
925
+ "validate", "--ledger", str(layout.global_knowledge_seed), "--json"],
926
+ cwd=root, capture_output=True, text=True, check=False, timeout=30,
927
+ env=_python_environment(),
928
+ )
929
+ global_ok = result.returncode == 0
930
+ global_detail = "全局 SQLite 有效(只读投影源)" if global_ok else (
931
+ (result.stderr or result.stdout).strip()[:500] or "全局 SQLite 校验失败"
932
+ )
933
+ return global_ok, global_detail
934
+ except (OSError, subprocess.TimeoutExpired, CliError) as exc:
935
+ return False, f"全局 SQLite 校验异常:{exc}"
936
+
937
+
938
+ def _codebase_memory_check_row(root: Path) -> tuple[bool, str]:
939
+ # 优化:优先尝试内存级快速 inspect,失败回退子进程(判定语义与串行版一致)
940
+ try:
941
+ from core.probes import codebase_memory_probe
942
+ cbm = codebase_memory_probe.inspect(root)
943
+ cbm_ok = cbm.get("status") == "READY"
944
+ cbm_detail = (
945
+ f"{cbm.get('status')},版本 {cbm.get('version') or '未安装'}"
946
+ + (";项目索引已就绪" if cbm_ok else f";未就绪:{cbm.get('fallback')}")
947
+ )
948
+ return cbm_ok, cbm_detail
949
+ except Exception:
950
+ try:
951
+ cbm_result = subprocess.run(
952
+ [sys.executable, str(_script(root, "codebase_memory_probe.py")),
953
+ "status", "--root", str(root), "--json"],
954
+ cwd=root, capture_output=True, text=True, check=False, timeout=60,
955
+ env=_python_environment(),
956
+ )
957
+ cbm = json.loads(cbm_result.stdout)
958
+ cbm_ok = cbm.get("status") == "READY"
959
+ cbm_detail = (
960
+ f"{cbm.get('status')},版本 {cbm.get('version') or '未安装'}"
961
+ + (";项目索引已就绪" if cbm_ok else f";未就绪:{cbm.get('fallback')}")
962
+ )
963
+ return cbm_ok, cbm_detail
964
+ except (OSError, subprocess.TimeoutExpired, json.JSONDecodeError, CliError) as exc:
965
+ return False, f"DEGRADED:{exc}"
966
+
967
+
968
+ def _efficiency_tools_check_row(root: Path) -> tuple[bool, str]:
969
+ try:
970
+ from core.probes import efficiency_probe
971
+ efficiency = efficiency_probe.inspect(root)
972
+ efficiency_ok = efficiency.get("status") == "READY"
973
+ missing = [
974
+ item.get("name", "unknown")
975
+ for item in efficiency.get("base_tools", []) if not item.get("ok")
976
+ ]
977
+ efficiency_detail = efficiency.get("status", "DEGRADED")
978
+ if missing:
979
+ efficiency_detail += f";待补充 {', '.join(missing)}"
980
+ efficiency_detail += ";内置回退可用"
981
+ return efficiency_ok, efficiency_detail
982
+ except Exception:
983
+ try:
984
+ efficiency_result = subprocess.run(
985
+ [sys.executable, str(_script(root, "efficiency_probe.py")),
986
+ "status", "--root", str(root), "--json"],
987
+ cwd=root, capture_output=True, text=True, check=False, timeout=45,
988
+ env=_python_environment(),
989
+ )
990
+ efficiency = json.loads(efficiency_result.stdout)
991
+ efficiency_ok = efficiency.get("status") == "READY"
992
+ missing = [
993
+ item.get("name", "unknown")
994
+ for item in efficiency.get("base_tools", []) if not item.get("ok")
995
+ ]
996
+ efficiency_detail = efficiency.get("status", "DEGRADED")
997
+ if missing:
998
+ efficiency_detail += f";待补充 {', '.join(missing)}"
999
+ efficiency_detail += ";内置回退可用"
1000
+ return efficiency_ok, efficiency_detail
1001
+ except (OSError, subprocess.TimeoutExpired, json.JSONDecodeError, CliError) as exc:
1002
+ return False, f"DEGRADED:{exc}"
1003
+
1004
+
1005
+ def _mcp_hygiene_check_row(root: Path) -> tuple[bool, str]:
1006
+ # DOC-230 3.2 第 6 项:MCP 会话进程卫生(阈值化 + advisory)。传 state_root
1007
+ # 以做**活动感知**判定,避免把长命但健康的会话误报为泄漏;拿不到状态根时
1008
+ # 退化为跳过遗弃判定。
1009
+ try:
1010
+ import core.bugx_paths as bugx_paths
1011
+
1012
+ mcp_state_root = bugx_paths.require(root).state_root
1013
+ except Exception: # noqa: BLE001 - 拿不到状态根时退化为跳过遗弃判定
1014
+ mcp_state_root = None
1015
+ return _mcp_session_hygiene_check(root, mcp_state_root)
1016
+
1017
+
1018
+ def _ui_env_check_row(root: Path, ui_script: Path) -> tuple[bool, str]:
1019
+ try:
1020
+ ui_res = subprocess.run(
1021
+ [sys.executable, str(ui_script), "status"],
1022
+ cwd=root, capture_output=True, text=True, check=False, timeout=30,
1023
+ env=_python_environment(),
1024
+ )
1025
+ if ui_res.returncode == 0:
1026
+ return True, "UI/TUI 环境就绪(Playwright / TUI 可用)"
1027
+ missing_lines = [
1028
+ line.strip() for line in (ui_res.stdout or "").splitlines()
1029
+ if "缺失" in line or "✗" in line
1030
+ ]
1031
+ detail = missing_lines[0] if missing_lines else (
1032
+ "部分依赖缺失;运行 python3 setup_ui_env.py install 补装"
1033
+ )
1034
+ return False, detail
1035
+ except Exception as exc:
1036
+ return False, f"检测跳过: {exc}"
1037
+
1038
+
1039
+ def _bugx_cli_path_check_row() -> tuple[bool, str]:
1040
+ """BugX CLI 路径检查(只读:PATH 扫描 + 对每个入口采样 --version)。"""
1041
+ cli_paths = _bugx_cli_paths()
1042
+ if len(cli_paths) > 1:
1043
+ inspected = [_inspect_cli_entry(p) for p in cli_paths]
1044
+ active_entry = shutil.which("bugx") or (str(cli_paths[0]) if cli_paths else None)
1045
+ active_path = Path(active_entry).resolve() if active_entry else cli_paths[0]
1046
+
1047
+ has_npm = any(item["type"] == "npm" for item in inspected)
1048
+ has_pip = any(item["type"] in ("pip", "uv", "pyenv", "python") for item in inspected)
1049
+ versions = {item["version"] for item in inspected if item["version"]}
1050
+
1051
+ parts_desc = []
1052
+ for item in inspected:
1053
+ is_active = (item["path"] == active_path)
1054
+ tag = "生效中" if is_active else "被覆盖"
1055
+ ver_str = f" v{item['version']}" if item["version"] else ""
1056
+ parts_desc.append(f"{item['path']} ({item['type']}{ver_str}, {tag})")
1057
+
1058
+ if has_npm and has_pip:
1059
+ if len(versions) > 1:
1060
+ cli_detail = (
1061
+ "发现 npm 与 pip/uv 双重安装且版本冲突:"
1062
+ + ";".join(parts_desc)
1063
+ + "。建议卸载多余版本:npm 运行 npm uninstall -g bugx-cli,"
1064
+ "pip 运行 pip uninstall bugx-cli 或 uv tool uninstall bugx-cli"
1065
+ )
1066
+ else:
1067
+ cli_detail = (
1068
+ "发现 npm 与 pip/uv 均存在安装(当前版本一致):"
1069
+ + ";".join(parts_desc)
1070
+ + "。建议保留单一包管理器以避免后续升级漂移"
1071
+ )
1072
+ else:
1073
+ cli_detail = "发现多个 PATH 中的 BugX 入口,可能存在安装覆盖:" + ";".join(parts_desc)
1074
+ elif cli_paths:
1075
+ cli_detail = str(cli_paths[0])
1076
+ else:
1077
+ cli_detail = "PATH 中未发现 bugx 入口"
1078
+ return len(cli_paths) <= 1, cli_detail
1079
+
1080
+
1081
+ def _doctor_parallel_reads(
1082
+ root: Path,
1083
+ *,
1084
+ layout: Any,
1085
+ initialized: bool,
1086
+ installed_host_names: set[str],
1087
+ target_hosts: set[str] | None,
1088
+ ) -> dict[str, Any]:
1089
+ """并发执行 doctor 中互相独立的【纯读取】检查(仅非 --repair 运行态调用)。
1090
+
1091
+ 只收录同时满足以下条件的检查:
1092
+ 1. 纯读取:只读文件系统、进程表或做网络探测,无写副作用;
1093
+ 2. 互相独立:不依赖其他并行检查的计算结果;
1094
+ 3. 依赖已就绪:依赖 layout/initialized/宿主清单的检查在调用方串行
1095
+ 前置段完成依赖计算后才注册。
1096
+
1097
+ 返回 ``{key: ("ok", value) | ("error", exc)}``;渲染处按原始行序取用,
1098
+ 意外异常在取用处原样重抛(与串行失败语义一致)。
1099
+ codebase-memory 探针含 DOC-180 的一次性索引自举(写外部工具自己的
1100
+ 存储,非项目工作树),是该检查的既有语义,与 --repair 无关。
1101
+ """
1102
+ from .agent import _check_host_mcp_config
1103
+ from .lifecycle import _global_opencode_integrity_check, _global_pi_integrity_check
1104
+
1105
+ jobs: dict[str, Any] = {
1106
+ "worktree_hygiene": lambda: _check_nested_worktrees_hygiene(root),
1107
+ "cloud_endpoint": lambda: _cloud_endpoint_check(root),
1108
+ "engine_integrity": _engine_integrity_check_row,
1109
+ "version_contract": lambda: _version_contract_check_row(root),
1110
+ "engine_replicas": _engine_replica_consistency_check,
1111
+ "detected_hosts": lambda: {item["name"]: item for item in discover_hosts(root)},
1112
+ "codebase_memory": lambda: _codebase_memory_check_row(root),
1113
+ "efficiency_tools": lambda: _efficiency_tools_check_row(root),
1114
+ "mcp_runtime": lambda: _mcp_runtime_check(root),
1115
+ "mcp_hygiene": lambda: _mcp_hygiene_check_row(root),
1116
+ "cli_paths": _bugx_cli_path_check_row,
1117
+ }
1118
+ if "opencode" in installed_host_names and (target_hosts is None or "opencode" in target_hosts):
1119
+ jobs["opencode_integrity"] = _global_opencode_integrity_check
1120
+ if "pi" in installed_host_names and (target_hosts is None or "pi" in target_hosts):
1121
+ jobs["pi_integrity"] = lambda: _global_pi_integrity_check(root)
1122
+ for host_name in sorted(installed_host_names):
1123
+ if target_hosts is not None and host_name not in target_hosts:
1124
+ continue
1125
+ try:
1126
+ get_adapter(host_name)
1127
+ except ValueError:
1128
+ # 未识别宿主:渲染处按原逻辑输出结构化失败行,不进入并行探测。
1129
+ continue
1130
+ jobs[f"mcp_config:{host_name}"] = (
1131
+ lambda host=host_name: _check_host_mcp_config(root, host, repair=False)
1132
+ )
1133
+ if initialized:
1134
+ lesson_json = (
1135
+ layout.knowledge_seed if layout is not None
1136
+ else root / ".bugx" / "knowledge" / "lesson-ledger.json"
1137
+ )
1138
+ jobs["lesson_ledger"] = lambda: _lesson_ledger_check_row(root, lesson_json)
1139
+ if layout is not None:
1140
+ jobs["global_lesson_ledger"] = lambda: _global_lesson_ledger_check_row(root, layout)
1141
+ ui_script = _script(root, "setup_ui_env.py")
1142
+ if ui_script.is_file():
1143
+ jobs["ui_env"] = lambda: _ui_env_check_row(root, ui_script)
1144
+ with concurrent.futures.ThreadPoolExecutor(max_workers=_DOCTOR_PARALLEL_MAX_WORKERS) as pool:
1145
+ futures = {key: pool.submit(_doctor_probe_job, fn) for key, fn in jobs.items()}
1146
+ return {key: future.result() for key, future in futures.items()}
1147
+
1148
+
827
1149
  def command_doctor(args: argparse.Namespace) -> int:
828
1150
  from .agent import _check_host_mcp_config
829
1151
  from .lifecycle import _global_opencode_integrity_check, _global_pi_integrity_check
@@ -913,20 +1235,6 @@ def command_doctor(args: argparse.Namespace) -> int:
913
1235
 
914
1236
  checks.append(("项目初始化状态", initialized, init_detail))
915
1237
  checks.append((".bugx 运行目录", layout is not None, layout_error or str(root / ".bugx")))
916
- wt_ok, wt_detail = _check_nested_worktrees_hygiene(root)
917
- checks.append(("工作树卫生与嵌套隔离", wt_ok, wt_detail))
918
- if getattr(args, "installation_only", False):
919
- checks.append((_CLOUD_ENDPOINT_CHECK_NAME, True, "跳过(--installation-only)"))
920
- else:
921
- checks.append(_cloud_endpoint_check(root))
922
-
923
- if args.repair:
924
- repair_errors = [item for item in repair_actions if item.startswith("ERROR:")]
925
- checks.append((
926
- "项目资产修复",
927
- not repair_errors,
928
- ";".join(repair_errors or repair_actions or ["无需修复"]),
929
- ))
930
1238
  raw_requested_hosts = []
931
1239
  for item in getattr(args, "agent", []):
932
1240
  for sub in str(item).split(","):
@@ -953,13 +1261,48 @@ def command_doctor(args: argparse.Namespace) -> int:
953
1261
  )
954
1262
  for name, ok, detail in host_checks
955
1263
  ]
956
- checks.extend(host_checks)
957
- try:
958
- engine_ok, engine_detail = _engine_integrity_status(
959
- asset_root(), global_engine_root(),
1264
+ # ---- 并行只读探测批(W-002 遗留性能项):仅非 --repair 运行态启用 ----
1265
+ # --repair 的全部写路径(资产修复、引擎重放、清单自愈、pip 补装、MCP 配置
1266
+ # 修复)与 --installation-only 模式都保持原串行路径,绝不进入并行块。
1267
+ # 检查行仍按原始顺序渲染:这里先并发算完互相独立的纯读取检查,
1268
+ # 后续渲染处按各自原始行序从结果中取值。
1269
+ parallel_results: dict[str, Any] = {}
1270
+ if (not getattr(args, "repair", False)
1271
+ and not getattr(args, "installation_only", False)):
1272
+ progress.update(30, "并发执行独立只读检查")
1273
+ parallel_results = _doctor_parallel_reads(
1274
+ root,
1275
+ layout=layout,
1276
+ initialized=initialized,
1277
+ installed_host_names=installed_host_names,
1278
+ target_hosts=target_hosts,
960
1279
  )
961
- except (CliError, OSError, ValueError) as exc:
962
- engine_ok, engine_detail = False, f"全局引擎无法校验:{exc}"
1280
+ progress.update(42, "独立只读检查完成")
1281
+ wt_ok, wt_detail = (
1282
+ _unwrap_parallel_result(parallel_results, "worktree_hygiene")
1283
+ if "worktree_hygiene" in parallel_results
1284
+ else _check_nested_worktrees_hygiene(root)
1285
+ )
1286
+ checks.append(("工作树卫生与嵌套隔离", wt_ok, wt_detail))
1287
+ if getattr(args, "installation_only", False):
1288
+ checks.append((_CLOUD_ENDPOINT_CHECK_NAME, True, "跳过(--installation-only)"))
1289
+ elif "cloud_endpoint" in parallel_results:
1290
+ checks.append(_unwrap_parallel_result(parallel_results, "cloud_endpoint"))
1291
+ else:
1292
+ checks.append(_cloud_endpoint_check(root))
1293
+
1294
+ if args.repair:
1295
+ repair_errors = [item for item in repair_actions if item.startswith("ERROR:")]
1296
+ checks.append((
1297
+ "项目资产修复",
1298
+ not repair_errors,
1299
+ ";".join(repair_errors or repair_actions or ["无需修复"]),
1300
+ ))
1301
+ checks.extend(host_checks)
1302
+ if "engine_integrity" in parallel_results:
1303
+ engine_ok, engine_detail = _unwrap_parallel_result(parallel_results, "engine_integrity")
1304
+ else:
1305
+ engine_ok, engine_detail = _engine_integrity_check_row()
963
1306
  if not engine_ok and getattr(args, "repair", False):
964
1307
  can_replace, guard_detail = _asset_can_replace_global_engine()
965
1308
  if not can_replace:
@@ -974,12 +1317,10 @@ def command_doctor(args: argparse.Namespace) -> int:
974
1317
  except Exception as exc:
975
1318
  engine_detail = f"自动修复全局引擎失败:{exc}"
976
1319
  checks.append(("全局引擎完整性", engine_ok, engine_detail))
977
- try:
978
- version_ok, version_detail = _version_contract_status(
979
- root, global_engine_root(),
980
- )
981
- except (CliError, OSError, ValueError) as exc:
982
- version_ok, version_detail = False, f"版本契约无法校验:{exc}"
1320
+ if "version_contract" in parallel_results:
1321
+ version_ok, version_detail = _unwrap_parallel_result(parallel_results, "version_contract")
1322
+ else:
1323
+ version_ok, version_detail = _version_contract_check_row(root)
983
1324
  # 项目 manifest 只存语义版本;它的基础版本自愈必须独立于完整 Build ID 比对。
984
1325
  if version_ok and getattr(args, "repair", False):
985
1326
  healed = _heal_project_manifest_version(root)
@@ -1000,14 +1341,33 @@ def command_doctor(args: argparse.Namespace) -> int:
1000
1341
  except Exception as exc:
1001
1342
  version_detail = f"自动对齐版本失败:{exc}"
1002
1343
  checks.append(("BugX 版本一致性", version_ok, version_detail))
1003
- replicas_ok, replicas_detail = _engine_replica_consistency_check()
1344
+ if "engine_replicas" in parallel_results:
1345
+ replicas_ok, replicas_detail = _unwrap_parallel_result(parallel_results, "engine_replicas")
1346
+ else:
1347
+ replicas_ok, replicas_detail = _engine_replica_consistency_check()
1004
1348
  checks.append(("引擎副本一致性", replicas_ok, replicas_detail))
1005
1349
  progress.update(45, "引擎和版本检查完成")
1006
1350
  if "opencode" in installed_host_names and (target_hosts is None or "opencode" in target_hosts):
1007
- checks.append(("OpenCode 全局入口完整性", *_global_opencode_integrity_check()))
1351
+ if "opencode_integrity" in parallel_results:
1352
+ checks.append((
1353
+ "OpenCode 全局入口完整性",
1354
+ *_unwrap_parallel_result(parallel_results, "opencode_integrity"),
1355
+ ))
1356
+ else:
1357
+ checks.append(("OpenCode 全局入口完整性", *_global_opencode_integrity_check()))
1008
1358
  if "pi" in installed_host_names and (target_hosts is None or "pi" in target_hosts):
1009
- checks.append(("Pi 全局 Skill 完整性", *_global_pi_integrity_check(root)))
1010
- detected_hosts = {item["name"]: item for item in discover_hosts(root)}
1359
+ if "pi_integrity" in parallel_results:
1360
+ checks.append((
1361
+ "Pi 全局 Skill 完整性",
1362
+ *_unwrap_parallel_result(parallel_results, "pi_integrity"),
1363
+ ))
1364
+ else:
1365
+ checks.append(("Pi 全局 Skill 完整性", *_global_pi_integrity_check(root)))
1366
+ detected_hosts = (
1367
+ _unwrap_parallel_result(parallel_results, "detected_hosts")
1368
+ if "detected_hosts" in parallel_results
1369
+ else {item["name"]: item for item in discover_hosts(root)}
1370
+ )
1011
1371
  for host_name in sorted(installed_host_names):
1012
1372
  if target_hosts is not None and host_name not in target_hosts:
1013
1373
  continue
@@ -1019,10 +1379,14 @@ def command_doctor(args: argparse.Namespace) -> int:
1019
1379
  "当前 CLI 不识别该宿主(可能由更新版本的 BugX 安装);请升级 CLI 后重试",
1020
1380
  ))
1021
1381
  continue
1022
- ok, detail = _check_host_mcp_config(
1023
- root, host_name,
1024
- repair=getattr(args, "repair", False) and not host_registry_fallback,
1025
- )
1382
+ mcp_config_key = f"mcp_config:{host_name}"
1383
+ if mcp_config_key in parallel_results:
1384
+ ok, detail = _unwrap_parallel_result(parallel_results, mcp_config_key)
1385
+ else:
1386
+ ok, detail = _check_host_mcp_config(
1387
+ root, host_name,
1388
+ repair=getattr(args, "repair", False) and not host_registry_fallback,
1389
+ )
1026
1390
  adapter = get_adapter(host_name)
1027
1391
  checks.append((f"{adapter.label} MCP 配置", ok, detail))
1028
1392
  is_installation_only = bool(getattr(args, "installation_only", False))
@@ -1032,7 +1396,7 @@ def command_doctor(args: argparse.Namespace) -> int:
1032
1396
  if layout is not None:
1033
1397
  checks.append(("全局错题集(可选)", True, "跳过运行态检查(--installation-only)"))
1034
1398
  graph = importlib.util.find_spec("tree_sitter_language_pack") is not None
1035
- checks.append(("Tree-sitter 多语言增强", graph, "已安装" if graph else "可选:pip install 'bugx-agent[graph]'"))
1399
+ checks.append(("Tree-sitter 多语言增强", graph, "已安装" if graph else "可选:pip install 'bugx-cli[graph]'"))
1036
1400
  checks.append(("codebase-memory 推荐加速", True, "跳过运行态检查(--installation-only)"))
1037
1401
  checks.append(("基础效率工具", True, "跳过运行态检查(--installation-only)"))
1038
1402
  mcp_runtime_ok, mcp_runtime_detail = _mcp_runtime_check(root)
@@ -1041,50 +1405,20 @@ def command_doctor(args: argparse.Namespace) -> int:
1041
1405
  checks.append(("UI 视觉与浏览器挖掘环境(可选)", True, "跳过运行态检查(--installation-only)"))
1042
1406
  else:
1043
1407
  lesson_json = layout.knowledge_seed if layout is not None else root / ".bugx" / "knowledge" / "lesson-ledger.json"
1044
- lesson_db = lesson_json.with_suffix(".sqlite3")
1045
- lesson_ready = False
1046
- lesson_detail = "项目尚未初始化"
1047
- if initialized:
1048
- if not lesson_db.is_file() or lesson_db.is_symlink():
1049
- lesson_detail = "缺少或不安全的 SQLite 运行库;请从备份恢复,禁止静默重建"
1050
- else:
1051
- try:
1052
- result = subprocess.run(
1053
- [sys.executable, str(_script(root, "lesson_ledger.py")),
1054
- "validate", "--ledger", str(lesson_json), "--json"],
1055
- cwd=root, capture_output=True, text=True, check=False, timeout=30,
1056
- env=_python_environment(),
1057
- )
1058
- lesson_ready = result.returncode == 0
1059
- lesson_detail = ("SQLite 运行库有效" if lesson_ready else (
1060
- (result.stderr or result.stdout).strip()[:500] or "SQLite 校验失败"
1061
- ))
1062
- if lesson_ready and (not lesson_json.is_file() or lesson_json.is_symlink()):
1063
- lesson_detail += ";JSON 种子缺失(不影响读取,恢复时需人工确认)"
1064
- except (OSError, subprocess.TimeoutExpired, CliError) as exc:
1065
- lesson_detail = f"SQLite 校验异常:{exc}"
1408
+ if "lesson_ledger" in parallel_results:
1409
+ lesson_ready, lesson_detail = _unwrap_parallel_result(parallel_results, "lesson_ledger")
1410
+ elif initialized:
1411
+ lesson_ready, lesson_detail = _lesson_ledger_check_row(root, lesson_json)
1412
+ else:
1413
+ lesson_ready, lesson_detail = False, "项目尚未初始化"
1066
1414
  checks.append(("错题集账本", lesson_ready, lesson_detail))
1067
1415
  if layout is not None:
1068
- global_db = layout.global_knowledge_db
1069
- global_marker = layout.global_knowledge_root / "manifest.json"
1070
- if not global_marker.exists() and not global_db.exists():
1071
- global_ok, global_detail = True, "尚未初始化;项目库可独立运行"
1072
- elif not global_db.is_file() or global_db.is_symlink():
1073
- global_ok, global_detail = False, "全局 SQLite 缺失;不会静默从 JSON 重建"
1416
+ if "global_lesson_ledger" in parallel_results:
1417
+ global_ok, global_detail = _unwrap_parallel_result(
1418
+ parallel_results, "global_lesson_ledger",
1419
+ )
1074
1420
  else:
1075
- try:
1076
- result = subprocess.run(
1077
- [sys.executable, str(_script(root, "lesson_ledger.py")),
1078
- "validate", "--ledger", str(layout.global_knowledge_seed), "--json"],
1079
- cwd=root, capture_output=True, text=True, check=False, timeout=30,
1080
- env=_python_environment(),
1081
- )
1082
- global_ok = result.returncode == 0
1083
- global_detail = "全局 SQLite 有效(只读投影源)" if global_ok else (
1084
- (result.stderr or result.stdout).strip()[:500] or "全局 SQLite 校验失败"
1085
- )
1086
- except (OSError, subprocess.TimeoutExpired, CliError) as exc:
1087
- global_ok, global_detail = False, f"全局 SQLite 校验异常:{exc}"
1421
+ global_ok, global_detail = _global_lesson_ledger_check_row(root, layout)
1088
1422
  checks.append(("全局错题集(可选)", global_ok, global_detail))
1089
1423
  graph = importlib.util.find_spec("tree_sitter_language_pack") is not None
1090
1424
  if not graph and getattr(args, "repair", False):
@@ -1099,140 +1433,50 @@ def command_doctor(args: argparse.Namespace) -> int:
1099
1433
  graph = importlib.util.find_spec("tree_sitter_language_pack") is not None
1100
1434
  except Exception:
1101
1435
  pass
1102
- graph_detail = "已就绪" if graph else "可选:缺失(执行 bugx doctor --repair 或 pip install 'bugx-agent[graph]' 启用)"
1436
+ graph_detail = "已就绪" if graph else "可选:缺失(执行 bugx doctor --repair 或 pip install 'bugx-cli[graph]' 启用)"
1103
1437
  checks.append(("Tree-sitter 多语言增强", graph, graph_detail))
1104
- # 优化:优先尝试内存级快速 inspect,失败回退子进程
1105
- try:
1106
- from core.probes import codebase_memory_probe
1107
- cbm = codebase_memory_probe.inspect(root)
1108
- cbm_ok = cbm.get("status") == "READY"
1109
- cbm_detail = (
1110
- f"{cbm.get('status')},版本 {cbm.get('version') or '未安装'}"
1111
- + (f";项目索引已就绪" if cbm_ok else f";未就绪:{cbm.get('fallback')}")
1112
- )
1113
- except Exception:
1114
- try:
1115
- cbm_result = subprocess.run(
1116
- [sys.executable, str(_script(root, "codebase_memory_probe.py")),
1117
- "status", "--root", str(root), "--json"],
1118
- cwd=root, capture_output=True, text=True, check=False, timeout=60,
1119
- env=_python_environment(),
1120
- )
1121
- cbm = json.loads(cbm_result.stdout)
1122
- cbm_ok = cbm.get("status") == "READY"
1123
- cbm_detail = (
1124
- f"{cbm.get('status')},版本 {cbm.get('version') or '未安装'}"
1125
- + (f";项目索引已就绪" if cbm_ok else f";未就绪:{cbm.get('fallback')}")
1126
- )
1127
- except (OSError, subprocess.TimeoutExpired, json.JSONDecodeError, CliError) as exc:
1128
- cbm_ok, cbm_detail = False, f"DEGRADED:{exc}"
1438
+ if "codebase_memory" in parallel_results:
1439
+ cbm_ok, cbm_detail = _unwrap_parallel_result(parallel_results, "codebase_memory")
1440
+ else:
1441
+ cbm_ok, cbm_detail = _codebase_memory_check_row(root)
1129
1442
  checks.append(("codebase-memory 推荐加速", cbm_ok, cbm_detail))
1130
- try:
1131
- from core.probes import efficiency_probe
1132
- efficiency = efficiency_probe.inspect(root)
1133
- efficiency_ok = efficiency.get("status") == "READY"
1134
- missing = [
1135
- item.get("name", "unknown")
1136
- for item in efficiency.get("base_tools", []) if not item.get("ok")
1137
- ]
1138
- efficiency_detail = efficiency.get("status", "DEGRADED")
1139
- if missing:
1140
- efficiency_detail += f";待补充 {', '.join(missing)}"
1141
- efficiency_detail += ";内置回退可用"
1142
- except Exception:
1143
- try:
1144
- efficiency_result = subprocess.run(
1145
- [sys.executable, str(_script(root, "efficiency_probe.py")),
1146
- "status", "--root", str(root), "--json"],
1147
- cwd=root, capture_output=True, text=True, check=False, timeout=45,
1148
- env=_python_environment(),
1149
- )
1150
- efficiency = json.loads(efficiency_result.stdout)
1151
- efficiency_ok = efficiency.get("status") == "READY"
1152
- missing = [
1153
- item.get("name", "unknown")
1154
- for item in efficiency.get("base_tools", []) if not item.get("ok")
1155
- ]
1156
- efficiency_detail = efficiency.get("status", "DEGRADED")
1157
- if missing:
1158
- efficiency_detail += f";待补充 {', '.join(missing)}"
1159
- efficiency_detail += ";内置回退可用"
1160
- except (OSError, subprocess.TimeoutExpired, json.JSONDecodeError, CliError) as exc:
1161
- efficiency_ok, efficiency_detail = False, f"DEGRADED:{exc}"
1443
+ if "efficiency_tools" in parallel_results:
1444
+ efficiency_ok, efficiency_detail = _unwrap_parallel_result(
1445
+ parallel_results, "efficiency_tools",
1446
+ )
1447
+ else:
1448
+ efficiency_ok, efficiency_detail = _efficiency_tools_check_row(root)
1162
1449
  checks.append(("基础效率工具", efficiency_ok, efficiency_detail))
1163
- mcp_runtime_ok, mcp_runtime_detail = _mcp_runtime_check(root)
1450
+ if "mcp_runtime" in parallel_results:
1451
+ mcp_runtime_ok, mcp_runtime_detail = _unwrap_parallel_result(
1452
+ parallel_results, "mcp_runtime",
1453
+ )
1454
+ else:
1455
+ mcp_runtime_ok, mcp_runtime_detail = _mcp_runtime_check(root)
1164
1456
  checks.append(("MCP 离线 runtime", mcp_runtime_ok, mcp_runtime_detail))
1165
1457
  # DOC-230 3.2 第 6 项:MCP 会话进程卫生(阈值化 + advisory,不进
1166
- # installation_required —— 审计 Q7)。传 state_root 以做**活动感知**判定,
1167
- # 避免把长命但健康的会话误报为泄漏。
1168
- try:
1169
- import core.bugx_paths as bugx_paths
1170
-
1171
- mcp_state_root = bugx_paths.require(root).state_root
1172
- except Exception: # noqa: BLE001 - 拿不到状态根时退化为跳过遗弃判定
1173
- mcp_state_root = None
1174
- mcp_hygiene_ok, mcp_hygiene_detail = _mcp_session_hygiene_check(root, mcp_state_root)
1458
+ # installation_required —— 审计 Q7)。state_root 的**活动感知**判定与
1459
+ # 拿不到状态根时的退化跳过都保留在 _mcp_hygiene_check_row 内。
1460
+ if "mcp_hygiene" in parallel_results:
1461
+ mcp_hygiene_ok, mcp_hygiene_detail = _unwrap_parallel_result(
1462
+ parallel_results, "mcp_hygiene",
1463
+ )
1464
+ else:
1465
+ mcp_hygiene_ok, mcp_hygiene_detail = _mcp_hygiene_check_row(root)
1175
1466
  checks.append(("MCP 会话进程卫生", mcp_hygiene_ok, mcp_hygiene_detail))
1176
1467
  progress.update(80, "运行态检查完成")
1177
1468
  # DOC-065: UI 视觉与浏览器挖掘环境诊断(可选)
1178
- try:
1179
- ui_script = _script(root, "setup_ui_env.py")
1180
- if ui_script.is_file():
1181
- ui_res = subprocess.run(
1182
- [sys.executable, str(ui_script), "status"],
1183
- cwd=root, capture_output=True, text=True, check=False, timeout=30,
1184
- env=_python_environment(),
1185
- )
1186
- ui_ok = ui_res.returncode == 0
1187
- if ui_ok:
1188
- ui_detail = "UI/TUI 环境就绪(Playwright / TUI 可用)"
1189
- else:
1190
- missing_lines = [
1191
- line.strip() for line in (ui_res.stdout or "").splitlines()
1192
- if "缺失" in line or "✗" in line
1193
- ]
1194
- ui_detail = missing_lines[0] if missing_lines else "部分依赖缺失;运行 python3 setup_ui_env.py install 补装"
1195
- checks.append(("UI 视觉与浏览器挖掘环境(可选)", ui_ok, ui_detail))
1196
- except Exception as exc:
1197
- checks.append(("UI 视觉与浏览器挖掘环境(可选)", False, f"检测跳过: {exc}"))
1198
- cli_paths = _bugx_cli_paths()
1199
- if len(cli_paths) > 1:
1200
- inspected = [_inspect_cli_entry(p) for p in cli_paths]
1201
- active_entry = shutil.which("bugx") or (str(cli_paths[0]) if cli_paths else None)
1202
- active_path = Path(active_entry).resolve() if active_entry else cli_paths[0]
1203
-
1204
- has_npm = any(item["type"] == "npm" for item in inspected)
1205
- has_pip = any(item["type"] in ("pip", "uv", "pyenv", "python") for item in inspected)
1206
- versions = {item["version"] for item in inspected if item["version"]}
1207
-
1208
- parts_desc = []
1209
- for item in inspected:
1210
- is_active = (item["path"] == active_path)
1211
- tag = "生效中" if is_active else "被覆盖"
1212
- ver_str = f" v{item['version']}" if item["version"] else ""
1213
- parts_desc.append(f"{item['path']} ({item['type']}{ver_str}, {tag})")
1214
-
1215
- if has_npm and has_pip:
1216
- if len(versions) > 1:
1217
- cli_detail = (
1218
- "发现 npm 与 pip/uv 双重安装且版本冲突:"
1219
- + ";".join(parts_desc)
1220
- + "。建议卸载多余版本:npm 运行 npm uninstall -g @bencibro/bugx,"
1221
- "pip 运行 pip uninstall bugx-agent 或 uv tool uninstall bugx-agent"
1222
- )
1223
- else:
1224
- cli_detail = (
1225
- "发现 npm 与 pip/uv 均存在安装(当前版本一致):"
1226
- + ";".join(parts_desc)
1227
- + "。建议保留单一包管理器以避免后续升级漂移"
1228
- )
1229
- else:
1230
- cli_detail = "发现多个 PATH 中的 BugX 入口,可能存在安装覆盖:" + ";".join(parts_desc)
1231
- elif cli_paths:
1232
- cli_detail = str(cli_paths[0])
1469
+ ui_script = _script(root, "setup_ui_env.py")
1470
+ if "ui_env" in parallel_results:
1471
+ ui_ok, ui_detail = _unwrap_parallel_result(parallel_results, "ui_env")
1472
+ checks.append(("UI 视觉与浏览器挖掘环境(可选)", ui_ok, ui_detail))
1473
+ elif ui_script.is_file():
1474
+ checks.append(("UI 视觉与浏览器挖掘环境(可选)", *_ui_env_check_row(root, ui_script)))
1475
+ if "cli_paths" in parallel_results:
1476
+ cli_ok, cli_detail = _unwrap_parallel_result(parallel_results, "cli_paths")
1233
1477
  else:
1234
- cli_detail = "PATH 中未发现 bugx 入口"
1235
- checks.append(("BugX CLI 路径", len(cli_paths) <= 1, cli_detail))
1478
+ cli_ok, cli_detail = _bugx_cli_path_check_row()
1479
+ checks.append(("BugX CLI 路径", cli_ok, cli_detail))
1236
1480
  installation_required = {
1237
1481
  "Python >= 3.11", "安装资源", "全局引擎完整性",
1238
1482
  "BugX 版本一致性",
@@ -1298,6 +1542,7 @@ def command_doctor(args: argparse.Namespace) -> int:
1298
1542
  root,
1299
1543
  strict=strict,
1300
1544
  auto_repairable_checks=auto_repairable_checks,
1545
+ use_ai=bool(getattr(args, "ai", False)),
1301
1546
  )
1302
1547
  escalation = None
1303
1548
  if not ready: