bugx-cli 0.1.2 → 0.1.4

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 (157) hide show
  1. package/README.md +26 -29
  2. package/core/README.md +5 -3
  3. package/core/agent/agent_orchestrator.py +3 -0
  4. package/core/agent/agent_workspace.py +14 -2
  5. package/core/assets/bugx-wechat-group.png +0 -0
  6. package/core/assets/twitter_promo_art.jpg +0 -0
  7. package/core/assets/twitter_promo_card.svg +166 -0
  8. package/core/assets/twitter_promo_clean.jpg +0 -0
  9. package/core/assets/twitter_terminal_real.png +0 -0
  10. package/core/bugx.md +3 -3
  11. package/core/bugx_paths.py +10 -2
  12. package/core/bundled_docs/OVERVIEW.md +310 -0
  13. package/core/bundled_docs/README.md +10 -0
  14. package/core/bundled_docs/README_EN.md +278 -0
  15. package/core/bundled_docs/ai/01_AI_REFERENCE.md +833 -0
  16. package/core/bundled_docs/ai/02_AI_USAGE.md +161 -0
  17. package/core/bundled_docs/ai/03_AI_COMMANDS.md +322 -0
  18. package/core/bundled_docs/guides/01_USER_GUIDE.md +887 -0
  19. package/core/bundled_docs/guides/02_COMMANDS.md +935 -0
  20. package/core/bundled_docs/guides/03_TROUBLESHOOTING.md +763 -0
  21. package/core/bundled_docs/guides/04_CLOUD_AUTH_AND_SYNC_COOKBOOK.md +48 -0
  22. package/core/bundled_docs/guides/05_HOST_MATRIX_AND_DISPATCH.md +23 -0
  23. package/core/bundled_docs/guides/06_PROBES_AND_POC_COOKBOOK.md +49 -0
  24. package/core/bundled_docs/guides/07_LIFECYCLE_AND_RECOVERY_STATES.md +46 -0
  25. package/core/bundled_docs/guides/08_LESSONS_AND_PRIVACY_BOUNDARY.md +35 -0
  26. package/core/bundled_docs/hosts/bugx-claude_SKILL.md +326 -0
  27. package/core/bundled_docs/hosts/bugx-dsh_SKILL.md +229 -0
  28. package/core/bundled_docs/hosts/bugx-opencode_SKILL.md +129 -0
  29. package/core/bundled_docs/hosts/bugx-zcode_SKILL.md +459 -0
  30. package/core/bundled_docs/hosts/bugx_SKILL.md +118 -0
  31. package/core/bundled_docs/hosts/cline_bugx_SKILL.md +69 -0
  32. package/core/bundled_docs/hosts/platform_bugx_SKILL.md +50 -0
  33. package/core/bundled_docs/manifest.json +140 -0
  34. package/core/bundled_docs/reference/01_ENVIRONMENT_VARIABLES.md +421 -0
  35. package/core/bundled_docs/reference/04_REPOSITORY_TOPOLOGY.md +180 -0
  36. package/core/cli-help.txt +7 -3
  37. package/core/cloud_sync/cloud_client.py +81 -2
  38. package/core/cloud_sync/endpoint_router.py +22 -9
  39. package/core/cloud_sync/issue_uploader.py +297 -0
  40. package/core/cloud_sync/sensitive_filter.py +77 -7
  41. package/core/contracts/AGENT_GUIDE.md +3 -9
  42. package/core/contracts/README.md +1 -1
  43. package/core/contracts/bugx-opencode.md +1 -1
  44. package/core/contracts/bugx-runtime-contract.md +10 -20
  45. package/core/contracts/bugx-worker.md +1 -1
  46. package/core/engine-integrity.json +267 -111
  47. package/core/host_acp/antigravity.py +153 -0
  48. package/core/host_acp/kimi.py +175 -0
  49. package/core/host_acp/minimax.py +28 -0
  50. package/core/host_runtime/adapters.py +5 -1
  51. package/core/host_runtime/antigravity.py +162 -0
  52. package/core/host_runtime/host_bootstrap.py +18 -7
  53. package/core/host_runtime/host_evaluators.py +4 -4
  54. package/core/host_runtime/host_registry.py +25 -4
  55. package/core/host_runtime/mcp_process_tracker.py +30 -3
  56. package/core/host_runtime/mcp_registry_gate.py +34 -11
  57. package/core/hosts/antigravity.py +115 -0
  58. package/core/hosts/codex.py +3 -0
  59. package/core/hosts/dsh.py +43 -24
  60. package/core/hosts/kimi.py +293 -0
  61. package/core/hosts/minimax.py +249 -0
  62. package/core/hosts/zcode.py +5 -0
  63. package/core/i18n.py +94 -5
  64. package/core/infra/README.md +1 -1
  65. package/core/infra/build_info.py +30 -5
  66. package/core/launch_phases/README.md +2 -2
  67. package/core/launch_phases/startup_version_gate.py +2 -2
  68. package/core/launch_phases/supervisor_bridge.py +16 -23
  69. package/core/launch_phases/supervisor_degraded.py +7 -5
  70. package/core/ledger/README.md +1 -1
  71. package/core/locales/en-US.json +3 -3
  72. package/core/locales/zh-CN.json +3 -3
  73. package/core/mcp_runtime_support/environment.py +6 -1
  74. package/core/metadata.txt +2 -2
  75. package/core/planning/README.md +1 -1
  76. package/core/planning/prompt_harness.py +2 -2
  77. package/core/probes/codebase_memory_probe.py +43 -24
  78. package/core/probes/probe_registry.py +10 -7
  79. package/core/prompts/command_routing_en.md +6 -5
  80. package/core/prompts/command_routing_zh.md +6 -5
  81. package/core/repair/rsi_rounds.py +3 -0
  82. package/core/repair/self_heal.py +160 -6
  83. package/core/retrieval/README.md +1 -1
  84. package/core/runtime/README.md +1 -1
  85. package/core/runtime/scenario_eval.py +5 -1
  86. package/core/runtime/setup_ui_env.py +4 -7
  87. package/core/runtime/tool_install_targets.py +12 -2
  88. package/core/skills/README.md +4 -2
  89. package/core/skills/bugx_docs_cloud_sync.py +658 -0
  90. package/core/skills/bugx_docs_mcp_server.py +966 -140
  91. package/core/supervisor/README.md +1 -1
  92. package/core/supervisor/cli.py +2 -2
  93. package/core/supervisor/worker_execution.py +16 -3
  94. package/core/webui/docs_session_service.py +40 -2
  95. package/core/webui/mcp_inspector.py +12 -6
  96. package/core/webui/static/index.html +51 -3
  97. package/core/webui/static/manifest.webmanifest +1 -1
  98. package/core/webui/static/project-settings.js +18 -3
  99. package/core/webui/static/robots.txt +36 -0
  100. package/core/webui/static/sitemap.xml +15 -0
  101. package/docs/07_distribution/01_README_NPM.md +26 -29
  102. package/ecosystem/integrations/cline/skills/bugx/SKILL.md +46 -46
  103. package/ecosystem/integrations/dsh/agents/bugx.md +2 -1
  104. package/ecosystem/integrations/dsh/dsh-patch.yml +2 -2
  105. package/ecosystem/integrations/dsh/mcp/package.json +1 -1
  106. package/ecosystem/integrations/dsh/skills/bugx/SKILL.md +6 -6
  107. package/ecosystem/integrations/dsh/skills/bugx-dsh/SKILL.md +1 -1
  108. package/ecosystem/integrations/dsh/ui/package.json +1 -1
  109. package/ecosystem/integrations/opencode/bugx-mcp-manifest.json +2 -2
  110. package/ecosystem/integrations/pi/extensions/bugx/manifest.json +1 -1
  111. package/ecosystem/integrations/pi/skills/bugx/SKILL.md +6 -6
  112. package/ecosystem/integrations/qoder/CONNECTORS.md +11 -23
  113. package/ecosystem/integrations/qoder/connector-meta.json +9 -9
  114. package/ecosystem/integrations/workbuddy/connector-meta.json +9 -9
  115. package/ecosystem/integrations/workbuddy/skills/bugx/SKILL.md +8 -7
  116. package/ecosystem/plugins/bugx/.claude-plugin/marketplace.json +2 -2
  117. package/ecosystem/plugins/bugx/.claude-plugin/plugin.json +2 -2
  118. package/ecosystem/plugins/bugx/.codex-plugin/plugin.json +4 -4
  119. package/ecosystem/plugins/bugx/.zcode-plugin/plugin.json +2 -2
  120. package/ecosystem/plugins/bugx/agents/bugx-worker.md +14 -18
  121. package/ecosystem/plugins/bugx/agents/bugx.md +45 -49
  122. package/ecosystem/plugins/bugx/skills/bugx/SKILL.md +8 -8
  123. package/ecosystem/plugins/bugx/skills/bugx-claude/SKILL.md +1 -1
  124. package/ecosystem/plugins/bugx/skills/bugx-dsh/SKILL.md +1 -1
  125. package/ecosystem/plugins/bugx/skills/bugx-opencode/SKILL.md +1 -1
  126. package/ecosystem/plugins/bugx/skills/bugx-zcode/SKILL.md +3 -3
  127. package/interfaces/bin/bugx.js +2 -0
  128. package/interfaces/cli/bugx_cli/__init__.py +2 -2
  129. package/interfaces/cli/bugx_cli/cli.py +153 -8
  130. package/interfaces/cli/bugx_cli/commands/agent.py +568 -136
  131. package/interfaces/cli/bugx_cli/commands/cloud.py +42 -1
  132. package/interfaces/cli/bugx_cli/commands/doctor.py +668 -223
  133. package/interfaces/cli/bugx_cli/commands/guide.py +143 -0
  134. package/interfaces/cli/bugx_cli/commands/issue.py +262 -0
  135. package/interfaces/cli/bugx_cli/commands/lifecycle.py +99 -62
  136. package/interfaces/cli/bugx_cli/commands/plugin.py +301 -60
  137. package/interfaces/cli/bugx_cli/commands/plugin_antigravity.py +350 -0
  138. package/interfaces/cli/bugx_cli/commands/plugin_claude.py +27 -13
  139. package/interfaces/cli/bugx_cli/commands/plugin_kimi.py +440 -0
  140. package/interfaces/cli/bugx_cli/commands/plugin_minimax.py +522 -0
  141. package/interfaces/cli/bugx_cli/commands/plugin_qoder.py +3 -4
  142. package/interfaces/cli/bugx_cli/commands/plugin_zcode.py +4 -5
  143. package/interfaces/cli/bugx_cli/commands/system.py +75 -5
  144. package/interfaces/cli/bugx_cli/common.py +135 -15
  145. package/interfaces/cli/bugx_cli/host_adapters.py +190 -7
  146. package/interfaces/cli/bugx_cli/hosts/registry.py +6 -3
  147. package/interfaces/cli/bugx_cli/hosts/template_engine.py +31 -11
  148. package/interfaces/cli/bugx_cli/infra/__init__.py +4 -0
  149. package/interfaces/cli/bugx_cli/infra/ai_advisor.py +14 -12
  150. package/interfaces/cli/bugx_cli/infra/engine_installer.py +76 -10
  151. package/interfaces/cli/bugx_cli/infra/host_sync.py +66 -1
  152. package/interfaces/cli/bugx_cli/infra/mcp_advisor.py +242 -52
  153. package/package.json +38 -13
  154. package/pyproject.toml +57 -13
  155. package/scripts/sync-version.mjs +1 -1
  156. package/skills/README.md +24 -0
  157. package/skills/platform/bugx/SKILL.md +50 -0
@@ -27,6 +27,11 @@ from ..infra.engine_installer import (
27
27
  _engine_receipt_build_id,
28
28
  _engine_integrity_status,
29
29
  _engine_self_integrity,
30
+ _global_bugx_dir,
31
+ _installed_engine_version,
32
+ _full_engine_version,
33
+ _is_global_home_scope,
34
+ _is_newer_version,
30
35
  )
31
36
 
32
37
 
@@ -204,7 +209,7 @@ def _heal_project_manifest_version(root: Path, *, force: bool = False) -> tuple[
204
209
 
205
210
 
206
211
  def _asset_can_replace_global_engine() -> tuple[bool, str]:
207
- """Doctor repair may replace the global engine only from a strictly newer asset."""
212
+ """Doctor repair may replace the global engine only from a strictly newer or self-intact same-version asset."""
208
213
  asset_id = _engine_build_id(asset_root())
209
214
  global_id = _engine_build_id(global_engine_root())
210
215
  if asset_id is None:
@@ -214,50 +219,52 @@ def _asset_can_replace_global_engine() -> tuple[bool, str]:
214
219
  "全局引擎缺少 Build ID 标记(可能损坏或未初始化);无法确认目标版本,拒绝自动替换。"
215
220
  "请先备份并核对共享引擎路径与可信安装资源;Doctor 不建议运行 `bugx install --force`。"
216
221
  )
217
- if global_id > asset_id:
222
+
223
+ asset_version = _installed_engine_version(asset_root()) or _full_engine_version(__version__, asset_root())
224
+ global_version = _installed_engine_version(global_engine_root())
225
+
226
+ if _is_newer_version(global_version, asset_version):
218
227
  return False, (
219
- f"CLI 安装资源 build_id={asset_id} 低于全局引擎 build_id={global_id};"
220
- f"拒绝自动降级。请先升级或重装 build_id >= {global_id} 的 CLI wheel,"
228
+ f"CLI 安装资源版本 ({asset_version}) 低于全局引擎版本 ({global_version});"
229
+ f"拒绝自动降级。请先升级或重装更高版本的 CLI wheel,"
221
230
  "再重跑 doctor;不要运行 `bugx install --force`,它会将共享引擎降级。"
222
231
  )
223
- if global_id == asset_id:
224
- # 同 build **不等于**同内容:引擎文件被改坏/删缺时,安装资源仍是完好的
225
- # 同一份 build,此时重放它就是唯一正确的修复。原实现无条件 `return
226
- # False`,于是「引擎已损坏 + 资源同 build」变成永久死锁——doctor 每轮
227
- # 都报完整性失败,却永远拒绝修复,且提示让用户「先升级到更高 build」,
228
- # 而同源安装的 CLI 根本产不出更高 build(工具自己的 AI 诊断都写明了
229
- # 这一点)。这里只在**引擎自身校验失败**时放行重放。
230
- # 这里必须问「引擎与**源**是否一致」,不能问「引擎与自己的清单是否一致」。
231
- # 后者在同源安装下恒为真:改了源码后清单与引擎文件一起漂移,两边自洽,
232
- # 于是 doctor 一边报 bundle_sha256 不一致、一边判定「无需替换」——永久
233
- # 死锁,且提示让用户「升级到更高 build」,而同源 CLI 产不出更高 build。
234
- # 2026-11-03 实测复现:global 与 asset 同 build,前者缺 engine_run_node_flags
235
- # 修复,_engine_self_integrity 仍返回 (True, '488 个静态文件与自身清单一致')。
236
- healthy, _detail = _engine_integrity_status(asset_root(), global_engine_root())
237
- if healthy:
238
- return False, (
239
- f"全局引擎与安装资源 Build ID 相同 (build_id={global_id})"
240
- "且内容与源一致,无需替换。"
241
- )
242
- # 放行前必须确认**来源本身**完好:损坏的引擎配损坏的资源时重放,
243
- # 只会把坏字节原样覆盖回去,还顺手毁掉现场。此前的 `==` 分支无条件
244
- # 拒绝,连带把这条本可救的场景一起挡死了。
232
+
233
+ if _is_newer_version(asset_version, global_version):
245
234
  source_ok, source_detail = _engine_self_integrity(asset_root())
246
235
  if not source_ok:
247
- # 缺陷 #11:两条判据(「引擎与源是否一致」和「源自身是否完好」)
248
- # 用了两套口径,用户因此拿到自相矛盾的处方——doctor 一边报
249
- # 「引擎与源不一致」,一边又说「同 build 无需替换/请升级到更高 build」,
250
- # 而同源安装根本产不出更高 build。这里必须把**两条判据的实际取值**
251
- # 一起说清,并给出唯一真正可执行的动作。
252
236
  return False, (
253
- "全局引擎与安装资源都不自洽:"
254
- f"引擎↔源={_detail or '不一致'};源自身={source_detail}。"
255
- "此时重放资源只会把坏字节原样覆盖回去,故拒绝修复。"
256
- "可执行动作:重装/升级 CLI(写入新的安装资源)后重跑 doctor;"
257
- "若资源是新装的仍报不自洽,说明该 wheel 本身损坏。"
237
+ f"CLI 安装资源版本 ({asset_version}) 严格高于全局引擎 ({global_version}),"
238
+ f"但安装资源自身完整性校验失败:{source_detail};"
239
+ "无法安全替换全局引擎,请重新安装或修复当前 CLI wheel。"
258
240
  )
259
- return True, ""
260
- return True, ""
241
+ return True, f"CLI 安装资源版本 ({asset_version}) 严格高于全局引擎 ({global_version}),允许升级替换。"
242
+
243
+ # 版本解析缺失时的兜底:基于 build_id 比对
244
+ if (asset_version is None or global_version is None) and global_id > asset_id:
245
+ return False, (
246
+ f"CLI 安装资源 build_id={asset_id} 低于全局引擎 build_id={global_id};"
247
+ f"拒绝自动降级。请先升级或重装 build_id >= {global_id} 的 CLI wheel,"
248
+ "再重跑 doctor;不要运行 `bugx install --force`,它会将共享引擎降级。"
249
+ )
250
+
251
+ # 同版本分支:
252
+ healthy, _detail = _engine_integrity_status(asset_root(), global_engine_root())
253
+ if healthy:
254
+ return False, (
255
+ f"全局引擎与安装资源版本相同 ({asset_version or f'build_id={global_id}'})"
256
+ "且内容与源一致,无需替换。"
257
+ )
258
+ source_ok, source_detail = _engine_self_integrity(asset_root())
259
+ if not source_ok:
260
+ return False, (
261
+ "全局引擎与安装资源都不自洽:"
262
+ f"引擎↔源={_detail or '不一致'};源自身={source_detail}。"
263
+ "此时重放资源只会把坏字节原样覆盖回去,故拒绝修复。"
264
+ "可执行动作:重装/升级 CLI(写入新的安装资源)后重跑 doctor;"
265
+ "若资源是新装的仍报不自洽,说明该 wheel 本身损坏。"
266
+ )
267
+ return True, f"同版本安装资源自身完好({source_detail}),允许重放修复损坏的全局引擎。"
261
268
 
262
269
 
263
270
  def _user_site_asset_candidates() -> list[tuple[str, Path]]:
@@ -326,9 +333,11 @@ def _engine_replica_consistency_check() -> tuple[bool, str]:
326
333
  """Compare installed engine copies and the receipt that identifies the global copy."""
327
334
  global_root = global_engine_root()
328
335
  global_id = _engine_build_id(global_root)
336
+ global_version = _installed_engine_version(global_root)
329
337
  asset_build_id: int | None = None
338
+ asset_version: str | None = None
330
339
  issues: list[str] = []
331
- replica_build_ids: list[tuple[str, int]] = []
340
+ replica_versions: list[tuple[str, str, int | None]] = []
332
341
  replica_inventory_complete = True
333
342
  replicas: list[tuple[str, Path]] = [("global", global_root)]
334
343
  try:
@@ -357,16 +366,28 @@ def _engine_replica_consistency_check() -> tuple[bool, str]:
357
366
  continue
358
367
  seen.add(resolved)
359
368
  build_id = _engine_build_id(path)
369
+ ver = _installed_engine_version(path)
360
370
  if name == "asset":
361
371
  asset_build_id = build_id
362
- replica_details.append(f"{name}={path} build_id={build_id!r}")
363
- if build_id is None:
364
- issues.append(f"{name} 引擎副本缺少有效 Build ID:{path}")
372
+ if ver is None and build_id is not None:
373
+ ver = _full_engine_version(__version__, path)
374
+ asset_version = ver
375
+ ver_display = ver or f"build_id={build_id!r}"
376
+ replica_details.append(f"{name}={path} version={ver_display}")
377
+ if build_id is None and ver is None:
378
+ issues.append(f"{name} 引擎副本缺少有效版本或 Build ID:{path}")
365
379
  replica_inventory_complete = False
366
380
  else:
367
- replica_build_ids.append((name, build_id))
368
- if name != "global" and build_id != global_id:
369
- issues.append(f"{name} build_id={build_id} 与 global build_id={global_id!r} 不一致")
381
+ ver_norm = ver or f"0.0.0+build.{build_id}"
382
+ replica_versions.append((name, ver_norm, build_id))
383
+ if name != "global":
384
+ mismatch = False
385
+ if ver is not None and global_version is not None:
386
+ mismatch = (ver != global_version)
387
+ else:
388
+ mismatch = (build_id != global_id)
389
+ if mismatch:
390
+ issues.append(f"{name} version={ver_display} 与 global version={global_version or f'build_id={global_id!r}'} 不一致")
370
391
 
371
392
  receipt_path = global_root.parent / "engine-receipt.json"
372
393
  receipt_id = _engine_receipt_build_id(receipt_path)
@@ -377,8 +398,23 @@ def _engine_replica_consistency_check() -> tuple[bool, str]:
377
398
 
378
399
  if issues:
379
400
  detail = ";".join(issues)
380
- if (global_id is not None and asset_build_id is not None
381
- and asset_build_id < global_id):
401
+ if (
402
+ global_version is not None
403
+ and asset_version is not None
404
+ and _is_newer_version(global_version, asset_version)
405
+ ):
406
+ detail += (
407
+ f";CLI 安装资源 ({asset_version}) 低于全局引擎 ({global_version}),"
408
+ "拒绝自动降级。请先升级或重装更高版本的 CLI wheel 后重跑 doctor;"
409
+ "不要运行 `bugx install --force`,它会将共享引擎降级并影响所有项目。"
410
+ )
411
+ elif (
412
+ asset_version is None
413
+ and global_version is None
414
+ and global_id is not None
415
+ and asset_build_id is not None
416
+ and asset_build_id < global_id
417
+ ):
382
418
  detail += (
383
419
  f";CLI 安装资源 build_id={asset_build_id} 低于全局引擎 build_id={global_id},"
384
420
  f"拒绝自动降级。请先升级或重装 build_id >= {global_id} 的 CLI wheel 后重跑 doctor;"
@@ -388,31 +424,36 @@ def _engine_replica_consistency_check() -> tuple[bool, str]:
388
424
  detail += (
389
425
  ";当前 asset、全局引擎或至少一个已发现副本缺少有效 Build ID/无法读取,"
390
426
  "无法证明替换来源安全;不要运行 `bugx install --force`。"
391
- "先核对上述路径、安装包来源与 Build ID,再按确认后的目标修复。"
427
+ "先核对上述路径、安装包来源与版本,再按确认后的目标修复。"
392
428
  )
393
429
  else:
394
430
  newer_replicas = [
395
- (name, build_id) for name, build_id in replica_build_ids
396
- if name != "asset" and build_id > asset_build_id
431
+ (name, r_ver) for name, r_ver, _ in replica_versions
432
+ if name != "asset" and asset_version is not None and _is_newer_version(r_ver, asset_version)
397
433
  ]
398
434
  if newer_replicas:
399
- newest_name, newest_id = max(newer_replicas, key=lambda item: item[1])
435
+ newest_name, newest_ver = newer_replicas[0]
436
+ detail += (
437
+ f";已发现 {newest_name} 版本 ({newest_ver}) 高于当前 CLI 安装资源 "
438
+ f"({asset_version});不要运行 `bugx install --force`,"
439
+ f"它会用较旧资源覆盖共享引擎。请先改用或升级到更高版本的 CLI。"
440
+ )
441
+ elif asset_version is not None and global_version is not None and _is_newer_version(asset_version, global_version):
400
442
  detail += (
401
- f";已发现 {newest_name} build_id={newest_id} 高于当前 CLI 安装资源 "
402
- f"build_id={asset_build_id};不要运行 `bugx install --force`,"
403
- f"它会用较旧资源覆盖共享引擎。请先改用或升级到安装资源 build_id >= {newest_id} 的 CLI。"
443
+ f";当前 CLI 安装资源 ({asset_version}) 严格高于共享全局引擎 "
444
+ f"({global_version}),且不低于所有已发现副本;如需升级共享引擎,"
445
+ "可运行 `bugx doctor --repair` 或 `bugx install`。"
404
446
  )
405
447
  elif asset_build_id == global_id:
406
448
  detail += (
407
449
  f";当前 CLI 安装资源与共享全局引擎均为 build_id={global_id},"
408
450
  "同号不能证明逐文件内容可安全替换;不要运行 `bugx install --force`。"
409
451
  "该命令只重建共享引擎,不会同步 user-site/cli-prefix 等独立副本;"
410
- "请按上列路径与 Build ID 逐项处理冲突副本。"
452
+ "请按上列路径与版本逐项处理冲突副本。"
411
453
  )
412
454
  else:
413
455
  detail += (
414
- f";当前 CLI 安装资源 build_id={asset_build_id} 严格高于共享全局引擎 "
415
- f"build_id={global_id},且不低于所有已发现副本;如需重建共享引擎,"
456
+ f";当前 CLI 安装资源高于或等于共享全局引擎;如需重建共享引擎,"
416
457
  "可运行 `bugx install --force`。该命令不会同步较旧的 user-site/cli-prefix 副本。"
417
458
  )
418
459
  return False, detail
@@ -585,6 +626,24 @@ def _doctor_repair_assets(root: Path, layout: Any) -> list[str]:
585
626
  except Exception as exc:
586
627
  failed("runtime.json 修复", exc)
587
628
 
629
+ try:
630
+ onboarding_file = root / ".bugx" / "cloud-onboard.json"
631
+ if onboarding_file.is_symlink():
632
+ raise OSError(f"拒绝修复软链接目标:{onboarding_file}")
633
+ if not onboarding_file.is_file():
634
+ payload = {
635
+ "schema_version": 1,
636
+ "state": "local",
637
+ "updated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
638
+ }
639
+ _doctor_atomic_replace(
640
+ onboarding_file,
641
+ json.dumps(payload, indent=2, ensure_ascii=False).encode("utf-8"),
642
+ )
643
+ actions.append("已自动补齐缺失的项目本地 onboarding 配置(.bugx/cloud-onboard.json)")
644
+ except Exception as exc:
645
+ failed("cloud-onboard.json 修复", exc)
646
+
588
647
  try:
589
648
  project_file = root / ".bugx-project.json"
590
649
  if project_file.is_symlink():
@@ -740,11 +799,11 @@ def _host_runtime_gate(
740
799
  ready = False
741
800
  continue
742
801
  bundle_ok = any(
743
- item[0] == f"{adapter.label} 完整适配包" and item[1]
802
+ item[0] in {f"{adapter.label} 完整适配包", f"{adapter.label} 全局适配包"} and item[1]
744
803
  for item in host_checks
745
804
  )
746
805
  detected = detected_hosts.get(name, {})
747
- usable = bool(detected.get("installed") or detected.get("project_marker"))
806
+ usable = bool(detected.get("installed") or detected.get("project_marker") or bundle_ok)
748
807
  ready = ready and bundle_ok and usable
749
808
  return ready
750
809
 
@@ -762,13 +821,26 @@ def _doctor_auto_repairable_checks(
762
821
  Host bundle replacement is deliberately excluded because it used to force
763
822
  rewrite project-owned files without preserving local edits.
764
823
  """
824
+ del installation_only
765
825
  if repair_requested:
766
826
  return set()
767
827
 
768
- failed = {name for name, ok, _detail in checks if not ok}
828
+ failed_items = {name: detail for name, ok, detail in checks if not ok}
829
+ failed = set(failed_items)
769
830
  eligible: set[str] = set()
770
- if not installation_only and "Tree-sitter 多语言增强" in failed:
771
- eligible.add("Tree-sitter 多语言增强")
831
+ for tool_name in (
832
+ "Tree-sitter 语法解析引擎",
833
+ "Tree-sitter 多语言增强",
834
+ "codebase-memory 代码图谱",
835
+ "主目录全局隔离",
836
+ ):
837
+ if tool_name in failed:
838
+ eligible.add(tool_name)
839
+ for name, detail in failed_items.items():
840
+ if name.endswith(" MCP 配置") and not any(
841
+ marker in detail for marker in ("自定义", "旧版", "拒绝自动迁移", "无法解析")
842
+ ):
843
+ eligible.add(name)
772
844
 
773
845
  engine_checks = failed & {"全局引擎完整性", "BugX 版本一致性"}
774
846
  if engine_checks:
@@ -912,9 +984,231 @@ def _lesson_ledger_check_row(root: Path, lesson_json: Path) -> tuple[bool, str]:
912
984
  return False, f"SQLite 校验异常:{exc}"
913
985
 
914
986
 
987
+ _HOME_PSEUDO_PROJECT_FILES = (
988
+ "manifest.json",
989
+ "hosts.json",
990
+ "cloud-onboard.json",
991
+ "startup-todo.md",
992
+ "life-state.json",
993
+ "runtime.json",
994
+ "audit-supervisor.json",
995
+ "prep-record.md",
996
+ "module-coverage.md",
997
+ "knowledge/lessons.json",
998
+ "knowledge/lessons.sqlite3",
999
+ "knowledge/lessons.sqlite3-wal",
1000
+ "knowledge/lessons.sqlite3-shm",
1001
+ )
1002
+
1003
+
1004
+ def _global_home_pseudo_project_residuals(home_bugx: Path | None = None) -> list[str]:
1005
+ """Return relative paths of accidental project state files inside ~/.bugx."""
1006
+ base = home_bugx or _global_bugx_dir()
1007
+ found: list[str] = []
1008
+ if not base.is_dir():
1009
+ return found
1010
+ for rel in _HOME_PSEUDO_PROJECT_FILES:
1011
+ target = base / rel
1012
+ if target.exists() or target.is_symlink():
1013
+ found.append(rel)
1014
+ return found
1015
+
1016
+
1017
+ def _clean_global_home_pseudo_project_residuals(home_bugx: Path | None = None) -> list[str]:
1018
+ """Remove accidental pseudo-project files inside ~/.bugx while preserving core/global knowledge."""
1019
+ base = home_bugx or _global_bugx_dir()
1020
+ removed: list[str] = []
1021
+ if not base.is_dir():
1022
+ return removed
1023
+ for rel in _HOME_PSEUDO_PROJECT_FILES:
1024
+ target = base / rel
1025
+ if not target.exists() and not target.is_symlink():
1026
+ continue
1027
+ if target.is_symlink() or target.is_file():
1028
+ target.unlink()
1029
+ removed.append(rel)
1030
+ return removed
1031
+
1032
+
1033
+ def _global_home_host_checks(
1034
+ root: Path,
1035
+ *,
1036
+ target_hosts: set[str] | None = None,
1037
+ ) -> tuple[list[tuple[str, bool, str]], set[str]]:
1038
+ """Inspect installed user-level host integrations when running Doctor in ~."""
1039
+ from .agent import _dsh_home, _global_opencode_agents_dir
1040
+ from .plugin_claude import _claude_user_agents_dir
1041
+ from .plugin_kimi import _kimi_code_home, validate_install as _validate_kimi
1042
+ from .plugin_minimax import _minimax_plugin_root, validate_install as _validate_minimax
1043
+ from .plugin_qoder import _qoder_user_agents_dir
1044
+ from .plugin_zcode import _zcode_global_plugin_root, _zcode_user_agents_dir
1045
+ from ..host_adapters import workbuddy_user_skill_root
1046
+
1047
+ del root
1048
+ checks: list[tuple[str, bool, str]] = []
1049
+ user_mcp_hosts: set[str] = set()
1050
+
1051
+ def wanted(name: str) -> bool:
1052
+ return target_hosts is None or name in target_hosts
1053
+
1054
+ if wanted("dsh") and (
1055
+ (_dsh_home() / ".agent-presets" / "bugx" / "agent.cordis.yml").exists()
1056
+ or (_dsh_home() / "plugins" / "bugx-ui").exists()
1057
+ or (target_hosts is not None and "dsh" in target_hosts)
1058
+ ):
1059
+ preset_ok = (_dsh_home() / ".agent-presets" / "bugx" / "agent.cordis.yml").is_file()
1060
+ ui_ok = (_dsh_home() / "plugins" / "bugx-ui" / "package.json").is_file()
1061
+ checks.append((
1062
+ "DeepSeek Harness 全局适配包",
1063
+ preset_ok and ui_ok,
1064
+ "全局预设与 UI 包均存在" if (preset_ok and ui_ok) else "全局预设或 UI 包不完整;请运行 `bugx install --agent dsh`",
1065
+ ))
1066
+ user_mcp_hosts.add("dsh")
1067
+
1068
+ if wanted("zcode") and (
1069
+ (_zcode_user_agents_dir() / "bugx.md").exists()
1070
+ or (_zcode_global_plugin_root() / "plugins" / "bugx").exists()
1071
+ or (target_hosts is not None and "zcode" in target_hosts)
1072
+ ):
1073
+ u_dir = _zcode_user_agents_dir()
1074
+ missing = [f for f in ("bugx.md", "bugx-worker.md") if not (u_dir / f).is_file()]
1075
+ checks.append((
1076
+ "ZCode 全局适配包",
1077
+ not missing,
1078
+ "用户级子智能体与全局插件均就绪" if not missing else f"缺少用户级 {', '.join(missing)}({u_dir})",
1079
+ ))
1080
+ user_mcp_hosts.add("zcode")
1081
+
1082
+ if wanted("minimax") and (_minimax_plugin_root().exists() or (target_hosts is not None and "minimax" in target_hosts)):
1083
+ ok_mm, detail_mm = _validate_minimax(Path.home())
1084
+ checks.append(("MiniMax Code 全局适配包", ok_mm, detail_mm))
1085
+ user_mcp_hosts.add("minimax")
1086
+
1087
+ if wanted("kimi") and ((_kimi_code_home() / "plugins" / "managed" / "bugx").exists() or (target_hosts is not None and "kimi" in target_hosts)):
1088
+ ok_km, detail_km = _validate_kimi(Path.home())
1089
+ checks.append(("Kimi Code 全局适配包", ok_km, detail_km))
1090
+ user_mcp_hosts.add("kimi")
1091
+
1092
+ if wanted("opencode") and ((_global_opencode_agents_dir() / "bugx.md").exists() or (target_hosts is not None and "opencode" in target_hosts)):
1093
+ from .lifecycle import _global_opencode_integrity_check
1094
+
1095
+ checks.append(("OpenCode 全局入口完整性", *_global_opencode_integrity_check()))
1096
+
1097
+ if wanted("pi") and ((Path.home() / ".agents" / "skills" / "bugx" / "SKILL.md").exists() or (target_hosts is not None and "pi" in target_hosts)):
1098
+ pi_global = Path.home() / ".agents" / "skills" / "bugx" / "SKILL.md"
1099
+ pi_ok = pi_global.is_file()
1100
+ checks.append((
1101
+ "Pi 全局 Skill 完整性",
1102
+ pi_ok,
1103
+ "~/.agents/skills/bugx/SKILL.md 已就绪" if pi_ok else "缺少 ~/.agents/skills/bugx/SKILL.md;请运行 `bugx install --agent pi`",
1104
+ ))
1105
+
1106
+ if wanted("claude") and ((_claude_user_agents_dir() / "bugx.md").exists() or (target_hosts is not None and "claude" in target_hosts)):
1107
+ c_dir = _claude_user_agents_dir()
1108
+ missing = [f for f in ("bugx.md", "bugx-worker.md") if not (c_dir / f).is_file()]
1109
+ checks.append((
1110
+ "Claude Code 全局适配包",
1111
+ not missing,
1112
+ f"用户级智能体已就绪({c_dir});工作区 .mcp.json 需进入具体项目运行 bugx install" if not missing else f"缺少用户级 {', '.join(missing)}",
1113
+ ))
1114
+
1115
+ if wanted("qoder") and ((_qoder_user_agents_dir() / "bugx.md").exists() or (target_hosts is not None and "qoder" in target_hosts)):
1116
+ q_dir = _qoder_user_agents_dir()
1117
+ missing = [f for f in ("bugx.md", "bugx-worker.md") if not (q_dir / f).is_file()]
1118
+ checks.append((
1119
+ "Qoder 全局适配包",
1120
+ not missing,
1121
+ f"用户级智能体已就绪({q_dir})" if not missing else f"缺少用户级 {', '.join(missing)}",
1122
+ ))
1123
+
1124
+ if wanted("workbuddy") and ((workbuddy_user_skill_root() / "skills" / "bugx" / "SKILL.md").exists() or (target_hosts is not None and "workbuddy" in target_hosts)):
1125
+ wb_skill = workbuddy_user_skill_root() / "skills" / "bugx" / "SKILL.md"
1126
+ checks.append((
1127
+ "WorkBuddy 全局适配包",
1128
+ wb_skill.is_file(),
1129
+ f"用户级 Skill 已就绪({wb_skill})" if wb_skill.is_file() else f"缺少用户级 Skill({wb_skill})",
1130
+ ))
1131
+
1132
+ return checks, user_mcp_hosts
1133
+
1134
+
1135
+ def _repair_active_host_mcp_config(
1136
+ root: Path,
1137
+ host_name: str,
1138
+ *,
1139
+ is_home_scope: bool,
1140
+ ) -> bool:
1141
+ """Safely repair BugX-managed host MCP config without clobbering custom user config."""
1142
+ from .agent import _check_host_mcp_config, _ensure_dsh_patch, _ensure_opencode_config
1143
+ from .plugin import write_host_mcp_config
1144
+
1145
+ ok_before, detail_before = _check_host_mcp_config(root, host_name, repair=False)
1146
+ if ok_before:
1147
+ return True
1148
+ blocked_markers = ("自定义", "旧版", "拒绝自动迁移", "符号链接", "无法解析", "legacy")
1149
+ if any(marker in detail_before for marker in blocked_markers):
1150
+ return False
1151
+ source = asset_root()
1152
+ try:
1153
+ if host_name == "dsh":
1154
+ _ensure_dsh_patch(root)
1155
+ elif host_name == "minimax":
1156
+ from .plugin_minimax import _ensure_minimax_plugin
1157
+
1158
+ _ensure_minimax_plugin(root, source)
1159
+ elif host_name == "kimi":
1160
+ from .plugin_kimi import _ensure_kimi_plugin
1161
+
1162
+ _ensure_kimi_plugin(root, source)
1163
+ elif host_name == "zcode":
1164
+ write_host_mcp_config(root, host_name)
1165
+ elif not is_home_scope and host_name == "opencode":
1166
+ _ensure_opencode_config(root)
1167
+ elif not is_home_scope and host_name in {"claude", "codex", "cline", "trea", "funide", "qoder"}:
1168
+ write_host_mcp_config(root, host_name)
1169
+ else:
1170
+ return False
1171
+ except Exception:
1172
+ return False
1173
+ ok_after, _ = _check_host_mcp_config(root, host_name, repair=False)
1174
+ return ok_after
1175
+
1176
+
1177
+ def _awaiting_first_audit(root: Path, layout: Any) -> bool:
1178
+ """Return True when BugX is installed in project and awaiting its first audit `pre`."""
1179
+ hosts_file = root / ".bugx" / "hosts.json"
1180
+ if not hosts_file.is_file():
1181
+ return False
1182
+ pollings_dir = root / ".bugx" / "pollings"
1183
+ if pollings_dir.is_dir():
1184
+ try:
1185
+ if any(pollings_dir.glob("*/lifecycles/*/rounds/*")):
1186
+ return False
1187
+ except OSError:
1188
+ return False
1189
+ life_file = layout.life if layout is not None and hasattr(layout, "life") else (root / ".bugx" / "life-state.json")
1190
+ if life_file.is_file() and not life_file.is_symlink():
1191
+ try:
1192
+ life_data = json.loads(life_file.read_text(encoding="utf-8"))
1193
+ if isinstance(life_data, dict):
1194
+ if life_data.get("mode") is not None or int(life_data.get("rounds_completed") or 0) > 0:
1195
+ return False
1196
+ except (OSError, UnicodeError, ValueError, TypeError):
1197
+ return False
1198
+ return True
1199
+
1200
+
915
1201
  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"
1202
+ if layout is not None:
1203
+ global_root = layout.global_knowledge_root
1204
+ global_db = layout.global_knowledge_db
1205
+ global_seed = layout.global_knowledge_seed
1206
+ else:
1207
+ override = os.environ.get("BUGX_GLOBAL_KNOWLEDGE_ROOT")
1208
+ global_root = Path(override).expanduser().resolve() if override else (_global_bugx_dir() / "knowledge")
1209
+ global_db = global_root / "global.sqlite3"
1210
+ global_seed = global_root / "global.json"
1211
+ global_marker = global_root / "manifest.json"
918
1212
  if not global_marker.exists() and not global_db.exists():
919
1213
  return True, "尚未初始化;项目库可独立运行"
920
1214
  if not global_db.is_file() or global_db.is_symlink():
@@ -922,7 +1216,7 @@ def _global_lesson_ledger_check_row(root: Path, layout: Any) -> tuple[bool, str]
922
1216
  try:
923
1217
  result = subprocess.run(
924
1218
  [sys.executable, str(_script(root, "lesson_ledger.py")),
925
- "validate", "--ledger", str(layout.global_knowledge_seed), "--json"],
1219
+ "validate", "--ledger", str(global_seed), "--json"],
926
1220
  cwd=root, capture_output=True, text=True, check=False, timeout=30,
927
1221
  env=_python_environment(),
928
1222
  )
@@ -935,37 +1229,47 @@ def _global_lesson_ledger_check_row(root: Path, layout: Any) -> tuple[bool, str]
935
1229
  return False, f"全局 SQLite 校验异常:{exc}"
936
1230
 
937
1231
 
938
- def _codebase_memory_check_row(root: Path) -> tuple[bool, str]:
939
- # 优化:优先尝试内存级快速 inspect,失败回退子进程(判定语义与串行版一致)
1232
+ def _codebase_memory_check_row(root: Path, *, check_project_index: bool = True) -> tuple[bool, str]:
1233
+ # 优化:优先尝试内存级快速 inspect,失败回退子进程
940
1234
  try:
941
1235
  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
1236
+ cbm = codebase_memory_probe.inspect(root, check_project_index=check_project_index)
1237
+ checks = cbm.get("checks") or []
1238
+ binary_ok = all(
1239
+ bool(item.get("ok"))
1240
+ for item in checks
1241
+ if isinstance(item, dict) and item.get("name") in {"binary", "validated_version", "supported_version"}
1242
+ ) and len([item for item in checks if isinstance(item, dict) and item.get("name") in {"binary", "validated_version", "supported_version"}]) >= 3
1243
+ cbm_ok = (cbm.get("status") == "READY") and binary_ok
1244
+ if cbm_ok:
1245
+ suffix = "项目索引已就绪" if check_project_index else "核心工具已就绪(项目索引在审计启动时校准)"
1246
+ return True, f"READY,版本 {cbm.get('version') or 'unknown'};{suffix}"
1247
+ detail = cbm.get("error") or cbm.get("install_hint") or cbm.get("fallback") or "未安装"
1248
+ return False, f"NOT READY(必需核心依赖,不可降级):版本 {cbm.get('version') or '未安装'};{detail}"
949
1249
  except Exception:
950
1250
  try:
1251
+ cmd = [
1252
+ sys.executable, str(_script(root, "codebase_memory_probe.py")),
1253
+ "status", "--root", str(root), "--json",
1254
+ ]
1255
+ if not check_project_index:
1256
+ cmd.append("--installation-only")
951
1257
  cbm_result = subprocess.run(
952
- [sys.executable, str(_script(root, "codebase_memory_probe.py")),
953
- "status", "--root", str(root), "--json"],
1258
+ cmd,
954
1259
  cwd=root, capture_output=True, text=True, check=False, timeout=60,
955
1260
  env=_python_environment(),
956
1261
  )
957
1262
  cbm = json.loads(cbm_result.stdout)
958
1263
  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
1264
+ if cbm_ok:
1265
+ suffix = "项目索引已就绪" if check_project_index else "核心工具已就绪(项目索引在审计启动时校准)"
1266
+ return True, f"READY,版本 {cbm.get('version') or 'unknown'};{suffix}"
1267
+ return False, f"NOT READY(必需核心依赖,不可降级):版本 {cbm.get('version') or '未安装'}"
964
1268
  except (OSError, subprocess.TimeoutExpired, json.JSONDecodeError, CliError) as exc:
965
- return False, f"DEGRADED:{exc}"
1269
+ return False, f"NOT READY(必需核心依赖):{exc}"
966
1270
 
967
1271
 
968
- def _efficiency_tools_check_row(root: Path) -> tuple[bool, str]:
1272
+ def _efficiency_tools_check_row(root: Path, *, strict: bool = False) -> tuple[bool, str]:
969
1273
  try:
970
1274
  from core.probes import efficiency_probe
971
1275
  efficiency = efficiency_probe.inspect(root)
@@ -974,11 +1278,15 @@ def _efficiency_tools_check_row(root: Path) -> tuple[bool, str]:
974
1278
  item.get("name", "unknown")
975
1279
  for item in efficiency.get("base_tools", []) if not item.get("ok")
976
1280
  ]
1281
+ if efficiency_ok:
1282
+ return True, "READY;内置回退与常用加速工具均就绪"
1283
+ if not strict:
1284
+ return True, f"内置检索就绪(可选外部加速 {', '.join(missing)} 将按需在审计阶段使用)"
977
1285
  efficiency_detail = efficiency.get("status", "DEGRADED")
978
1286
  if missing:
979
1287
  efficiency_detail += f";待补充 {', '.join(missing)}"
980
1288
  efficiency_detail += ";内置回退可用"
981
- return efficiency_ok, efficiency_detail
1289
+ return False, efficiency_detail
982
1290
  except Exception:
983
1291
  try:
984
1292
  efficiency_result = subprocess.run(
@@ -993,13 +1301,17 @@ def _efficiency_tools_check_row(root: Path) -> tuple[bool, str]:
993
1301
  item.get("name", "unknown")
994
1302
  for item in efficiency.get("base_tools", []) if not item.get("ok")
995
1303
  ]
1304
+ if efficiency_ok:
1305
+ return True, "READY;内置回退与常用加速工具均就绪"
1306
+ if not strict:
1307
+ return True, f"内置检索就绪(可选外部加速 {', '.join(missing)} 将按需在审计阶段使用)"
996
1308
  efficiency_detail = efficiency.get("status", "DEGRADED")
997
1309
  if missing:
998
1310
  efficiency_detail += f";待补充 {', '.join(missing)}"
999
1311
  efficiency_detail += ";内置回退可用"
1000
- return efficiency_ok, efficiency_detail
1312
+ return False, efficiency_detail
1001
1313
  except (OSError, subprocess.TimeoutExpired, json.JSONDecodeError, CliError) as exc:
1002
- return False, f"DEGRADED:{exc}"
1314
+ return (True, f"内置检索可用(探测异常已跳过:{exc})") if not strict else (False, f"DEGRADED:{exc}")
1003
1315
 
1004
1316
 
1005
1317
  def _mcp_hygiene_check_row(root: Path) -> tuple[bool, str]:
@@ -1015,7 +1327,7 @@ def _mcp_hygiene_check_row(root: Path) -> tuple[bool, str]:
1015
1327
  return _mcp_session_hygiene_check(root, mcp_state_root)
1016
1328
 
1017
1329
 
1018
- def _ui_env_check_row(root: Path, ui_script: Path) -> tuple[bool, str]:
1330
+ def _ui_env_check_row(root: Path, ui_script: Path, *, strict: bool = False) -> tuple[bool, str]:
1019
1331
  try:
1020
1332
  ui_res = subprocess.run(
1021
1333
  [sys.executable, str(ui_script), "status"],
@@ -1031,9 +1343,11 @@ def _ui_env_check_row(root: Path, ui_script: Path) -> tuple[bool, str]:
1031
1343
  detail = missing_lines[0] if missing_lines else (
1032
1344
  "部分依赖缺失;运行 python3 setup_ui_env.py install 补装"
1033
1345
  )
1346
+ if not strict:
1347
+ return True, f"按需延迟启用(进入 UI/E2E 审计阶段时按项目栈检查;当前:{detail})"
1034
1348
  return False, detail
1035
1349
  except Exception as exc:
1036
- return False, f"检测跳过: {exc}"
1350
+ return (True, f"按需延迟启用(跳过:{exc})") if not strict else (False, f"检测跳过: {exc}")
1037
1351
 
1038
1352
 
1039
1353
  def _bugx_cli_path_check_row() -> tuple[bool, str]:
@@ -1085,6 +1399,8 @@ def _doctor_parallel_reads(
1085
1399
  initialized: bool,
1086
1400
  installed_host_names: set[str],
1087
1401
  target_hosts: set[str] | None,
1402
+ strict: bool = False,
1403
+ is_home_scope: bool = False,
1088
1404
  ) -> dict[str, Any]:
1089
1405
  """并发执行 doctor 中互相独立的【纯读取】检查(仅非 --repair 运行态调用)。
1090
1406
 
@@ -1096,28 +1412,32 @@ def _doctor_parallel_reads(
1096
1412
 
1097
1413
  返回 ``{key: ("ok", value) | ("error", exc)}``;渲染处按原始行序取用,
1098
1414
  意外异常在取用处原样重抛(与串行失败语义一致)。
1099
- codebase-memory 探针含 DOC-180 的一次性索引自举(写外部工具自己的
1100
- 存储,非项目工作树),是该检查的既有语义,与 --repair 无关。
1101
1415
  """
1102
1416
  from .agent import _check_host_mcp_config
1103
1417
  from .lifecycle import _global_opencode_integrity_check, _global_pi_integrity_check
1104
1418
 
1105
1419
  jobs: dict[str, Any] = {
1106
- "worktree_hygiene": lambda: _check_nested_worktrees_hygiene(root),
1107
- "cloud_endpoint": lambda: _cloud_endpoint_check(root),
1108
1420
  "engine_integrity": _engine_integrity_check_row,
1109
1421
  "version_contract": lambda: _version_contract_check_row(root),
1110
1422
  "engine_replicas": _engine_replica_consistency_check,
1111
1423
  "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),
1424
+ "codebase_memory": lambda: _codebase_memory_check_row(root, check_project_index=bool(strict and not is_home_scope)),
1425
+ "efficiency_tools": lambda: _efficiency_tools_check_row(root, strict=strict),
1116
1426
  "cli_paths": _bugx_cli_path_check_row,
1427
+ "global_lesson_ledger": lambda: _global_lesson_ledger_check_row(root, layout),
1117
1428
  }
1118
- if "opencode" in installed_host_names and (target_hosts is None or "opencode" in target_hosts):
1429
+ if not is_home_scope:
1430
+ jobs["worktree_hygiene"] = lambda: _check_nested_worktrees_hygiene(root)
1431
+ jobs["cloud_endpoint"] = lambda: _cloud_endpoint_check(root)
1432
+ jobs["mcp_hygiene"] = lambda: _mcp_hygiene_check_row(root)
1433
+ ui_script = _script(root, "setup_ui_env.py")
1434
+ if ui_script.is_file():
1435
+ jobs["ui_env"] = lambda: _ui_env_check_row(root, ui_script, strict=strict)
1436
+ if strict or default_mcp_runtime_root().exists():
1437
+ jobs["mcp_runtime"] = lambda: _mcp_runtime_check(root, strict=strict)
1438
+ if not is_home_scope and "opencode" in installed_host_names and (target_hosts is None or "opencode" in target_hosts):
1119
1439
  jobs["opencode_integrity"] = _global_opencode_integrity_check
1120
- if "pi" in installed_host_names and (target_hosts is None or "pi" in target_hosts):
1440
+ if not is_home_scope and "pi" in installed_host_names and (target_hosts is None or "pi" in target_hosts):
1121
1441
  jobs["pi_integrity"] = lambda: _global_pi_integrity_check(root)
1122
1442
  for host_name in sorted(installed_host_names):
1123
1443
  if target_hosts is not None and host_name not in target_hosts:
@@ -1130,17 +1450,12 @@ def _doctor_parallel_reads(
1130
1450
  jobs[f"mcp_config:{host_name}"] = (
1131
1451
  lambda host=host_name: _check_host_mcp_config(root, host, repair=False)
1132
1452
  )
1133
- if initialized:
1453
+ if not is_home_scope and initialized:
1134
1454
  lesson_json = (
1135
1455
  layout.knowledge_seed if layout is not None
1136
1456
  else root / ".bugx" / "knowledge" / "lesson-ledger.json"
1137
1457
  )
1138
1458
  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
1459
  with concurrent.futures.ThreadPoolExecutor(max_workers=_DOCTOR_PARALLEL_MAX_WORKERS) as pool:
1145
1460
  futures = {key: pool.submit(_doctor_probe_job, fn) for key, fn in jobs.items()}
1146
1461
  return {key: future.result() for key, future in futures.items()}
@@ -1154,6 +1469,8 @@ def command_doctor(args: argparse.Namespace) -> int:
1154
1469
  progress = _CliProgress(args)
1155
1470
  progress.update(0, "准备诊断")
1156
1471
  root = args.root.resolve()
1472
+ strict = bool(getattr(args, "strict", False))
1473
+ is_home_scope = _is_global_home_scope(root)
1157
1474
  if getattr(args, "target", "all") == "mcp-runtime":
1158
1475
  progress.update(20, "正在诊断 MCP runtime")
1159
1476
  runtime_root = default_mcp_runtime_root()
@@ -1176,65 +1493,102 @@ def command_doctor(args: argparse.Namespace) -> int:
1176
1493
  checks.append(("安装资源", True, str(assets)))
1177
1494
  except CliError as exc:
1178
1495
  checks.append(("安装资源", False, str(exc)))
1179
- manifest_ok = (root / ".bugx" / "manifest.json").is_file()
1496
+ manifest_ok = False if is_home_scope else (root / ".bugx" / "manifest.json").is_file()
1180
1497
  layout = None
1181
1498
  layout_error = None
1182
1499
  repair_actions: list[str] = []
1183
1500
  init_issues: list[str] = []
1184
-
1185
- if manifest_ok:
1501
+ home_residuals: list[str] = []
1502
+
1503
+ if is_home_scope:
1504
+ home_bugx = _global_bugx_dir()
1505
+ home_residuals = _global_home_pseudo_project_residuals(home_bugx)
1506
+ if args.repair and home_residuals:
1507
+ removed = _clean_global_home_pseudo_project_residuals(home_bugx)
1508
+ if removed:
1509
+ repair_actions.append(
1510
+ f"已清理全局目录误建伪项目文件:{', '.join(removed)}(已保留 core 与 global.sqlite3)"
1511
+ )
1512
+ home_residuals = _global_home_pseudo_project_residuals(home_bugx)
1186
1513
  try:
1187
- layout_module = _layout_module(root)
1514
+ repaired_links = _ensure_global_cli_symlinks()
1188
1515
  if args.repair:
1189
- layout = layout_module.repair(root)
1190
- repair_actions = _doctor_repair_assets(root, layout)
1191
- else:
1192
- layout = layout_module.require(root)
1193
- except (CliError, OSError, ValueError, RuntimeError) as exc:
1194
- layout_error = str(exc)
1195
-
1196
- if not getattr(args, "installation_only", False):
1197
- onboarding_file = root / ".bugx" / "cloud-onboard.json"
1198
- if not onboarding_file.is_file():
1199
- init_issues.append("缺少云端 onboarding 记录(.bugx/cloud-onboard.json)")
1200
- else:
1201
- try:
1202
- ob_data = json.loads(onboarding_file.read_text(encoding="utf-8"))
1203
- ob_state = ob_data.get("state") if isinstance(ob_data, dict) else None
1204
- if ob_state not in ("done", "local", "sync"):
1205
- init_issues.append(f"云端 onboarding 未决(状态: {ob_state})")
1206
- elif ob_state in ("done", "sync"):
1207
- project_file = root / ".bugx-project.json"
1208
- if not project_file.is_file():
1209
- init_issues.append("开启了云端同步但缺少项目身份文件(.bugx-project.json)")
1210
- except Exception as exc:
1211
- init_issues.append(f"云端 onboarding 记录损坏: {exc}")
1212
-
1213
- startup_todo = root / ".bugx" / "startup-todo.md"
1214
- if not startup_todo.is_file():
1215
- init_issues.append("缺少启动视图(.bugx/startup-todo.md)")
1516
+ for link, status in repaired_links:
1517
+ if status == "created":
1518
+ repair_actions.append(f"已创建全局 CLI 软链接:{link}")
1519
+ except Exception as exc:
1520
+ if args.repair:
1521
+ repair_actions.append(f"ERROR: 全局 CLI 软链接修复失败:{exc}")
1522
+ initialized = True
1523
+ checks.append((
1524
+ "项目初始化状态",
1525
+ True,
1526
+ "用户全局模式(未指定 --root 项目,跳过项目初始化与工作区检查)",
1527
+ ))
1528
+ checks.append((".bugx 运行目录", True, f"全局运行目录:{home_bugx}"))
1529
+ if home_residuals:
1530
+ checks.append((
1531
+ "主目录全局隔离",
1532
+ False,
1533
+ f"检测到 {home_bugx} 中存在误按项目初始化的残留文件({', '.join(home_residuals)});"
1534
+ "运行 `bugx doctor --repair` 自动清理(不会影响全局引擎和 global.sqlite3)",
1535
+ ))
1216
1536
  else:
1217
- init_issues.append("缺少 .bugx/manifest.json")
1537
+ if manifest_ok:
1538
+ try:
1539
+ layout_module = _layout_module(root)
1540
+ if args.repair:
1541
+ layout = layout_module.repair(root)
1542
+ repair_actions = _doctor_repair_assets(root, layout)
1543
+ else:
1544
+ layout = layout_module.require(root)
1545
+ except (CliError, OSError, ValueError, RuntimeError) as exc:
1546
+ layout_error = str(exc)
1547
+
1548
+ if not getattr(args, "installation_only", False):
1549
+ onboarding_file = root / ".bugx" / "cloud-onboard.json"
1550
+ awaiting_first_audit = _awaiting_first_audit(root, layout)
1551
+ if not onboarding_file.is_file():
1552
+ if not awaiting_first_audit:
1553
+ init_issues.append("缺少云端 onboarding 记录(.bugx/cloud-onboard.json)")
1554
+ else:
1555
+ try:
1556
+ ob_data = json.loads(onboarding_file.read_text(encoding="utf-8"))
1557
+ ob_state = ob_data.get("state") if isinstance(ob_data, dict) else None
1558
+ if ob_state not in ("done", "local", "sync"):
1559
+ init_issues.append(f"云端 onboarding 未决(状态: {ob_state})")
1560
+ elif ob_state in ("done", "sync"):
1561
+ project_file = root / ".bugx-project.json"
1562
+ if not project_file.is_file():
1563
+ init_issues.append("开启了云端同步但缺少项目身份文件(.bugx-project.json)")
1564
+ except Exception as exc:
1565
+ init_issues.append(f"云端 onboarding 记录损坏: {exc}")
1218
1566
 
1219
- if layout_error:
1220
- init_issues.insert(0, f".bugx 项目布局校验失败: {layout_error}")
1567
+ startup_todo = root / ".bugx" / "startup-todo.md"
1568
+ if not startup_todo.is_file():
1569
+ init_issues.append("缺少启动视图(.bugx/startup-todo.md)")
1570
+ else:
1571
+ init_issues.append("缺少 .bugx/manifest.json")
1221
1572
 
1222
- initialized = manifest_ok and layout is not None and not init_issues
1223
- status_guidance = (
1224
- "先只读运行 `bugx engine --root <ROOT> status --json`;"
1225
- "只有状态精确为 `UNINITIALIZED` 时才运行 `bugx engine --root <ROOT> pre`。"
1226
- "返回 `FATAL_BLOCKED`、其他状态或检查失败时保留现场并停止;"
1227
- "不得用 `bugx init`、`bugx reset` 或 `--force` 绕过。"
1228
- )
1229
- if initialized:
1230
- init_detail = str(root / ".bugx")
1231
- elif not manifest_ok:
1232
- init_detail = f"项目状态未判定(缺少 .bugx/manifest.json)。{status_guidance}"
1233
- else:
1234
- init_detail = f"初始化未就绪({';'.join(init_issues)})。{status_guidance}"
1573
+ if layout_error:
1574
+ init_issues.insert(0, f".bugx 项目布局校验失败: {layout_error}")
1575
+
1576
+ initialized = manifest_ok and layout is not None and not init_issues
1577
+ status_guidance = (
1578
+ "先只读运行 `bugx engine --root <ROOT> status --json`;"
1579
+ "只有状态精确为 `UNINITIALIZED` 时才运行 `bugx engine --root <ROOT> pre`。"
1580
+ "返回 `FATAL_BLOCKED`、其他状态或检查失败时保留现场并停止;"
1581
+ "不得用 `bugx init`、`bugx reset` 或 `--force` 绕过。"
1582
+ )
1583
+ if initialized:
1584
+ init_detail = str(root / ".bugx")
1585
+ elif not manifest_ok:
1586
+ init_detail = f"项目状态未判定(缺少 .bugx/manifest.json)。{status_guidance}"
1587
+ else:
1588
+ init_detail = f"初始化未就绪({';'.join(init_issues)})。{status_guidance}"
1235
1589
 
1236
- checks.append(("项目初始化状态", initialized, init_detail))
1237
- checks.append((".bugx 运行目录", layout is not None, layout_error or str(root / ".bugx")))
1590
+ checks.append(("项目初始化状态", initialized, init_detail))
1591
+ checks.append((".bugx 运行目录", layout is not None, layout_error or str(root / ".bugx")))
1238
1592
  raw_requested_hosts = []
1239
1593
  for item in getattr(args, "agent", []):
1240
1594
  for sub in str(item).split(","):
@@ -1244,23 +1598,27 @@ def command_doctor(args: argparse.Namespace) -> int:
1244
1598
  target_hosts = set(raw_requested_hosts) if raw_requested_hosts else None
1245
1599
 
1246
1600
  progress.update(25, "项目和宿主检查完成")
1247
- host_checks, installed_host_names = _host_bundle_checks(root, target_hosts=target_hosts)
1248
- if target_hosts:
1249
- installed_host_names = installed_host_names | target_hosts
1250
- host_registry_fallback = any(
1251
- name == "宿主安装清单缺失或损坏" for name, _, _ in host_checks
1252
- )
1253
- host_checks = [
1254
- (
1255
- name,
1256
- ok,
1257
- detail + (
1258
- ";Doctor 不会强制重装整套宿主资产,以免覆盖项目内本地修改;"
1259
- "先检查并保存目标文件,再对单个宿主执行 `bugx install --root <ROOT> --agent <HOST>`。"
1260
- ) if not ok and name.endswith("完整适配包") else detail,
1601
+ if is_home_scope:
1602
+ host_checks, installed_host_names = _global_home_host_checks(root, target_hosts=target_hosts)
1603
+ host_registry_fallback = False
1604
+ else:
1605
+ host_checks, installed_host_names = _host_bundle_checks(root, target_hosts=target_hosts)
1606
+ if target_hosts:
1607
+ installed_host_names = installed_host_names | target_hosts
1608
+ host_registry_fallback = any(
1609
+ name == "宿主安装清单缺失或损坏" for name, _, _ in host_checks
1261
1610
  )
1262
- for name, ok, detail in host_checks
1263
- ]
1611
+ host_checks = [
1612
+ (
1613
+ name,
1614
+ ok,
1615
+ detail + (
1616
+ ";Doctor 不会强制重装整套宿主资产,以免覆盖项目内本地修改;"
1617
+ "先检查并保存目标文件,再对单个宿主执行 `bugx install --root <ROOT> --agent <HOST>`。"
1618
+ ) if not ok and name.endswith("完整适配包") else detail,
1619
+ )
1620
+ for name, ok, detail in host_checks
1621
+ ]
1264
1622
  # ---- 并行只读探测批(W-002 遗留性能项):仅非 --repair 运行态启用 ----
1265
1623
  # --repair 的全部写路径(资产修复、引擎重放、清单自愈、pip 补装、MCP 配置
1266
1624
  # 修复)与 --installation-only 模式都保持原串行路径,绝不进入并行块。
@@ -1276,20 +1634,27 @@ def command_doctor(args: argparse.Namespace) -> int:
1276
1634
  initialized=initialized,
1277
1635
  installed_host_names=installed_host_names,
1278
1636
  target_hosts=target_hosts,
1637
+ strict=strict,
1638
+ is_home_scope=is_home_scope,
1279
1639
  )
1280
1640
  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"))
1641
+ if is_home_scope:
1642
+ wt_ok, wt_detail = True, "跳过(用户全局模式)"
1643
+ checks.append(("工作树卫生与嵌套隔离", wt_ok, wt_detail))
1644
+ checks.append((_CLOUD_ENDPOINT_CHECK_NAME, True, "跳过(用户全局模式)"))
1291
1645
  else:
1292
- checks.append(_cloud_endpoint_check(root))
1646
+ wt_ok, wt_detail = (
1647
+ _unwrap_parallel_result(parallel_results, "worktree_hygiene")
1648
+ if "worktree_hygiene" in parallel_results
1649
+ else _check_nested_worktrees_hygiene(root)
1650
+ )
1651
+ checks.append(("工作树卫生与嵌套隔离", wt_ok, wt_detail))
1652
+ if getattr(args, "installation_only", False):
1653
+ checks.append((_CLOUD_ENDPOINT_CHECK_NAME, True, "跳过(--installation-only)"))
1654
+ elif "cloud_endpoint" in parallel_results:
1655
+ checks.append(_unwrap_parallel_result(parallel_results, "cloud_endpoint"))
1656
+ else:
1657
+ checks.append(_cloud_endpoint_check(root))
1293
1658
 
1294
1659
  if args.repair:
1295
1660
  repair_errors = [item for item in repair_actions if item.startswith("ERROR:")]
@@ -1316,6 +1681,8 @@ def command_doctor(args: argparse.Namespace) -> int:
1316
1681
  engine_detail += "(已自动修复恢复完整性)"
1317
1682
  except Exception as exc:
1318
1683
  engine_detail = f"自动修复全局引擎失败:{exc}"
1684
+ if engine_ok and not (global_engine_root() / "bundled_docs" / "manifest.json").is_file():
1685
+ engine_detail += "(缺少官方离线文档基线 bundled_docs,建议运行 `bugx update --repair-assets` 补齐)"
1319
1686
  checks.append(("全局引擎完整性", engine_ok, engine_detail))
1320
1687
  if "version_contract" in parallel_results:
1321
1688
  version_ok, version_detail = _unwrap_parallel_result(parallel_results, "version_contract")
@@ -1337,7 +1704,8 @@ def command_doctor(args: argparse.Namespace) -> int:
1337
1704
  version_ok, version_detail = _version_contract_status(
1338
1705
  root, global_engine_root(),
1339
1706
  )
1340
- version_detail += "(已自动刷新全局引擎与项目清单;旧项目入口会在 init/install 时直接删除)"
1707
+ if version_ok:
1708
+ version_detail += "(已自动刷新全局引擎与项目清单;旧项目入口会在 init/install 时直接删除)"
1341
1709
  except Exception as exc:
1342
1710
  version_detail = f"自动对齐版本失败:{exc}"
1343
1711
  checks.append(("BugX 版本一致性", version_ok, version_detail))
@@ -1347,7 +1715,7 @@ def command_doctor(args: argparse.Namespace) -> int:
1347
1715
  replicas_ok, replicas_detail = _engine_replica_consistency_check()
1348
1716
  checks.append(("引擎副本一致性", replicas_ok, replicas_detail))
1349
1717
  progress.update(45, "引擎和版本检查完成")
1350
- if "opencode" in installed_host_names and (target_hosts is None or "opencode" in target_hosts):
1718
+ if not is_home_scope and "opencode" in installed_host_names and (target_hosts is None or "opencode" in target_hosts):
1351
1719
  if "opencode_integrity" in parallel_results:
1352
1720
  checks.append((
1353
1721
  "OpenCode 全局入口完整性",
@@ -1355,7 +1723,7 @@ def command_doctor(args: argparse.Namespace) -> int:
1355
1723
  ))
1356
1724
  else:
1357
1725
  checks.append(("OpenCode 全局入口完整性", *_global_opencode_integrity_check()))
1358
- if "pi" in installed_host_names and (target_hosts is None or "pi" in target_hosts):
1726
+ if not is_home_scope and "pi" in installed_host_names and (target_hosts is None or "pi" in target_hosts):
1359
1727
  if "pi_integrity" in parallel_results:
1360
1728
  checks.append((
1361
1729
  "Pi 全局 Skill 完整性",
@@ -1383,26 +1751,112 @@ def command_doctor(args: argparse.Namespace) -> int:
1383
1751
  if mcp_config_key in parallel_results:
1384
1752
  ok, detail = _unwrap_parallel_result(parallel_results, mcp_config_key)
1385
1753
  else:
1754
+ repair_flag = bool(getattr(args, "repair", False) and not host_registry_fallback)
1386
1755
  ok, detail = _check_host_mcp_config(
1387
1756
  root, host_name,
1388
- repair=getattr(args, "repair", False) and not host_registry_fallback,
1757
+ repair=repair_flag,
1389
1758
  )
1759
+ if repair_flag and not ok:
1760
+ if _repair_active_host_mcp_config(root, host_name, is_home_scope=is_home_scope):
1761
+ ok, detail = _check_host_mcp_config(root, host_name, repair=False)
1762
+ if ok:
1763
+ refreshed_bundle_checks, _ = (
1764
+ _global_home_host_checks(root, target_hosts={host_name})
1765
+ if is_home_scope
1766
+ else _host_bundle_checks(root, target_hosts={host_name})
1767
+ )
1768
+ refreshed_map = {n: (n, b_ok, b_det) for n, b_ok, b_det in refreshed_bundle_checks}
1769
+ checks = [refreshed_map.get(item[0], item) for item in checks]
1390
1770
  adapter = get_adapter(host_name)
1391
1771
  checks.append((f"{adapter.label} MCP 配置", ok, detail))
1392
1772
  is_installation_only = bool(getattr(args, "installation_only", False))
1773
+
1774
+ def _run_required_tools_checks(*, check_project_index: bool) -> None:
1775
+ ts_repair_err: str | None = None
1776
+ try:
1777
+ _ensure_core_importable()
1778
+ from core.repair.self_heal import (
1779
+ ensure_codebase_memory_ready,
1780
+ ensure_tree_sitter_ready,
1781
+ mount_bugx_pydeps,
1782
+ )
1783
+ mount_bugx_pydeps()
1784
+ importlib.invalidate_caches()
1785
+ except Exception as exc:
1786
+ ensure_codebase_memory_ready = None # type: ignore[assignment]
1787
+ ensure_tree_sitter_ready = None # type: ignore[assignment]
1788
+ ts_repair_err = str(exc)
1789
+
1790
+ graph = importlib.util.find_spec("tree_sitter_language_pack") is not None
1791
+ if not graph and getattr(args, "repair", False) and ensure_tree_sitter_ready is not None:
1792
+ ts_ok, ts_msg = ensure_tree_sitter_ready()
1793
+ importlib.invalidate_caches()
1794
+ graph = importlib.util.find_spec("tree_sitter_language_pack") is not None
1795
+ if not ts_ok and not graph:
1796
+ ts_repair_err = ts_msg
1797
+ graph_detail = (
1798
+ "已就绪(tree-sitter-language-pack)"
1799
+ if graph
1800
+ else f"NOT READY(必需核心依赖,不可降级;{ts_repair_err or '运行 `bugx doctor --repair` 或 `bugx install` 自动安装'})"
1801
+ )
1802
+ checks.append(("Tree-sitter 语法解析引擎", graph, graph_detail))
1803
+
1804
+ if "codebase_memory" in parallel_results and not getattr(args, "repair", False):
1805
+ cbm_ok, cbm_detail = _unwrap_parallel_result(parallel_results, "codebase_memory")
1806
+ else:
1807
+ cbm_ok, cbm_detail = _codebase_memory_check_row(
1808
+ root, check_project_index=check_project_index,
1809
+ )
1810
+ if not cbm_ok and getattr(args, "repair", False) and ensure_codebase_memory_ready is not None:
1811
+ repaired_cbm_ok, repaired_cbm_msg = ensure_codebase_memory_ready(root)
1812
+ cbm_ok, cbm_detail = _codebase_memory_check_row(
1813
+ root, check_project_index=check_project_index,
1814
+ )
1815
+ if not cbm_ok and not repaired_cbm_ok:
1816
+ cbm_detail = f"NOT READY(必需核心依赖,不可降级):{repaired_cbm_msg}"
1817
+ checks.append(("codebase-memory 代码图谱", cbm_ok, cbm_detail))
1818
+
1819
+ def _run_mcp_runtime_deferred_aware() -> tuple[bool, str]:
1820
+ runtime_root = default_mcp_runtime_root()
1821
+ if not strict and not runtime_root.exists():
1822
+ return True, "按需延迟构建(首次审计需要 playwright/postmcp 等外部 MCP 时再启用,不阻塞安装)"
1823
+ if "mcp_runtime" in parallel_results:
1824
+ return _unwrap_parallel_result(parallel_results, "mcp_runtime")
1825
+ return _mcp_runtime_check(root, strict=strict)
1826
+
1393
1827
  if is_installation_only:
1394
1828
  lesson_ready = True
1395
1829
  checks.append(("错题集账本", True, "跳过运行态检查(--installation-only)"))
1396
- if layout is not None:
1830
+ if is_home_scope or layout is not None:
1397
1831
  checks.append(("全局错题集(可选)", True, "跳过运行态检查(--installation-only)"))
1398
- graph = importlib.util.find_spec("tree_sitter_language_pack") is not None
1399
- checks.append(("Tree-sitter 多语言增强", graph, "已安装" if graph else "可选:pip install 'bugx-cli[graph]'"))
1400
- checks.append(("codebase-memory 推荐加速", True, "跳过运行态检查(--installation-only)"))
1832
+ _run_required_tools_checks(check_project_index=False)
1401
1833
  checks.append(("基础效率工具", True, "跳过运行态检查(--installation-only)"))
1402
- mcp_runtime_ok, mcp_runtime_detail = _mcp_runtime_check(root)
1834
+ mcp_runtime_ok, mcp_runtime_detail = _run_mcp_runtime_deferred_aware()
1403
1835
  checks.append(("MCP 离线 runtime", mcp_runtime_ok, mcp_runtime_detail))
1404
1836
  progress.update(80, "运行态检查已跳过")
1405
1837
  checks.append(("UI 视觉与浏览器挖掘环境(可选)", True, "跳过运行态检查(--installation-only)"))
1838
+ elif is_home_scope:
1839
+ lesson_ready = True
1840
+ checks.append(("错题集账本", True, "跳过(用户全局模式)"))
1841
+ if "global_lesson_ledger" in parallel_results:
1842
+ global_ok, global_detail = _unwrap_parallel_result(
1843
+ parallel_results, "global_lesson_ledger",
1844
+ )
1845
+ else:
1846
+ global_ok, global_detail = _global_lesson_ledger_check_row(root, None)
1847
+ checks.append(("全局错题集(可选)", global_ok, global_detail))
1848
+ _run_required_tools_checks(check_project_index=False)
1849
+ if "efficiency_tools" in parallel_results:
1850
+ efficiency_ok, efficiency_detail = _unwrap_parallel_result(
1851
+ parallel_results, "efficiency_tools",
1852
+ )
1853
+ else:
1854
+ efficiency_ok, efficiency_detail = _efficiency_tools_check_row(root, strict=strict)
1855
+ checks.append(("基础效率工具", efficiency_ok, efficiency_detail))
1856
+ mcp_runtime_ok, mcp_runtime_detail = _run_mcp_runtime_deferred_aware()
1857
+ checks.append(("MCP 离线 runtime", mcp_runtime_ok, mcp_runtime_detail))
1858
+ checks.append(("MCP 会话进程卫生", True, "跳过(用户全局模式)"))
1859
+ progress.update(80, "全局环境检查完成")
1406
1860
  else:
1407
1861
  lesson_json = layout.knowledge_seed if layout is not None else root / ".bugx" / "knowledge" / "lesson-ledger.json"
1408
1862
  if "lesson_ledger" in parallel_results:
@@ -1420,39 +1874,15 @@ def command_doctor(args: argparse.Namespace) -> int:
1420
1874
  else:
1421
1875
  global_ok, global_detail = _global_lesson_ledger_check_row(root, layout)
1422
1876
  checks.append(("全局错题集(可选)", global_ok, global_detail))
1423
- graph = importlib.util.find_spec("tree_sitter_language_pack") is not None
1424
- if not graph and getattr(args, "repair", False):
1425
- # 只有在明确指定 --repair 时才尝试自动安装,普通诊断快速探测不挂起
1426
- try:
1427
- proc = subprocess.run(
1428
- [sys.executable, "-m", "pip", "install", "tree-sitter-language-pack>=1.14.3", "--no-warn-script-location"],
1429
- capture_output=True, text=True, timeout=15, check=False,
1430
- )
1431
- if proc.returncode == 0:
1432
- importlib.invalidate_caches()
1433
- graph = importlib.util.find_spec("tree_sitter_language_pack") is not None
1434
- except Exception:
1435
- pass
1436
- graph_detail = "已就绪" if graph else "可选:缺失(执行 bugx doctor --repair 或 pip install 'bugx-cli[graph]' 启用)"
1437
- checks.append(("Tree-sitter 多语言增强", graph, graph_detail))
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)
1442
- checks.append(("codebase-memory 推荐加速", cbm_ok, cbm_detail))
1877
+ _run_required_tools_checks(check_project_index=bool(strict and not is_home_scope))
1443
1878
  if "efficiency_tools" in parallel_results:
1444
1879
  efficiency_ok, efficiency_detail = _unwrap_parallel_result(
1445
1880
  parallel_results, "efficiency_tools",
1446
1881
  )
1447
1882
  else:
1448
- efficiency_ok, efficiency_detail = _efficiency_tools_check_row(root)
1883
+ efficiency_ok, efficiency_detail = _efficiency_tools_check_row(root, strict=strict)
1449
1884
  checks.append(("基础效率工具", efficiency_ok, efficiency_detail))
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)
1885
+ mcp_runtime_ok, mcp_runtime_detail = _run_mcp_runtime_deferred_aware()
1456
1886
  checks.append(("MCP 离线 runtime", mcp_runtime_ok, mcp_runtime_detail))
1457
1887
  # DOC-230 3.2 第 6 项:MCP 会话进程卫生(阈值化 + advisory,不进
1458
1888
  # installation_required —— 审计 Q7)。state_root 的**活动感知**判定与
@@ -1465,13 +1895,13 @@ def command_doctor(args: argparse.Namespace) -> int:
1465
1895
  mcp_hygiene_ok, mcp_hygiene_detail = _mcp_hygiene_check_row(root)
1466
1896
  checks.append(("MCP 会话进程卫生", mcp_hygiene_ok, mcp_hygiene_detail))
1467
1897
  progress.update(80, "运行态检查完成")
1468
- # DOC-065: UI 视觉与浏览器挖掘环境诊断(可选)
1898
+ # DOC-065: UI 视觉与浏览器挖掘环境(按需延迟,除非 --strict)
1469
1899
  ui_script = _script(root, "setup_ui_env.py")
1470
1900
  if "ui_env" in parallel_results:
1471
1901
  ui_ok, ui_detail = _unwrap_parallel_result(parallel_results, "ui_env")
1472
1902
  checks.append(("UI 视觉与浏览器挖掘环境(可选)", ui_ok, ui_detail))
1473
1903
  elif ui_script.is_file():
1474
- checks.append(("UI 视觉与浏览器挖掘环境(可选)", *_ui_env_check_row(root, ui_script)))
1904
+ checks.append(("UI 视觉与浏览器挖掘环境(可选)", *_ui_env_check_row(root, ui_script, strict=strict)))
1475
1905
  if "cli_paths" in parallel_results:
1476
1906
  cli_ok, cli_detail = _unwrap_parallel_result(parallel_results, "cli_paths")
1477
1907
  else:
@@ -1481,25 +1911,40 @@ def command_doctor(args: argparse.Namespace) -> int:
1481
1911
  "Python >= 3.11", "安装资源", "全局引擎完整性",
1482
1912
  "BugX 版本一致性",
1483
1913
  "引擎副本一致性",
1914
+ "Tree-sitter 语法解析引擎",
1915
+ "codebase-memory 代码图谱",
1484
1916
  }
1917
+ if is_home_scope and home_residuals:
1918
+ installation_required.add("主目录全局隔离")
1485
1919
  # F-L0-01 整改:``--installation-only`` 是「安装体检」,不得因为目标目录
1486
1920
  # 尚未初始化(没有 .bugx/manifest.json)而判定安装失败——安装完整性与
1487
1921
  # 项目状态是两个独立维度。但**已存在项目**(manifest 已落盘)却状态损坏
1488
1922
  # 时必须继续 fail-closed(DOC-227 半初始化拒绝放行),因此仅在
1489
1923
  # 「manifest 存在」或「非 installation-only 模式」时才把项目初始化状态
1490
1924
  # 计入必需项。
1491
- if manifest_ok or not args.installation_only:
1925
+ if not is_home_scope and (manifest_ok or not args.installation_only):
1492
1926
  installation_required.add("项目初始化状态")
1493
- strict = bool(getattr(args, "strict", False))
1494
- if strict:
1927
+ if not is_home_scope and initialized and not args.installation_only:
1928
+ installation_required.add("错题集账本")
1929
+ if strict and not is_home_scope:
1495
1930
  installation_required.add("工作树卫生与嵌套隔离")
1496
1931
  installation_required.add(_CLOUD_ENDPOINT_CHECK_NAME)
1497
1932
  if args.repair:
1498
1933
  installation_required.add("项目资产修复")
1934
+ if strict or default_mcp_runtime_root().exists():
1935
+ installation_required.add("MCP 离线 runtime")
1499
1936
  installation_required.update(name for name, _, _ in host_checks)
1500
- if "opencode" in installed_host_names:
1937
+ for host_name in sorted(installed_host_names):
1938
+ if target_hosts is not None and host_name not in target_hosts:
1939
+ continue
1940
+ try:
1941
+ host_label = get_adapter(host_name).label
1942
+ except ValueError:
1943
+ host_label = host_name
1944
+ installation_required.add(f"{host_label} MCP 配置")
1945
+ if not is_home_scope and "opencode" in installed_host_names:
1501
1946
  installation_required.update({"OpenCode MCP 配置", "OpenCode 全局入口完整性"})
1502
- if "pi" in installed_host_names:
1947
+ if not is_home_scope and "pi" in installed_host_names:
1503
1948
  installation_required.add("Pi 全局 Skill 完整性")
1504
1949
  installation_ready = all(
1505
1950
  ok for name, ok, detail in checks if name in installation_required