bugx-cli 0.0.0-stage → 0.1.0

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 (751) hide show
  1. package/LICENSE +55 -0
  2. package/README.md +280 -2
  3. package/core/CATALOG.json +141 -0
  4. package/core/README.md +254 -0
  5. package/core/adapters/README.md +35 -0
  6. package/core/adapters/android-interaction.json +81 -0
  7. package/core/adapters/android.json +24 -0
  8. package/core/adapters/desktop-macos.json +20 -0
  9. package/core/adapters/ios-interaction.json +34 -0
  10. package/core/adapters/ios.json +23 -0
  11. package/core/adapters/memory-macos.json +24 -0
  12. package/core/agent/README.md +50 -0
  13. package/core/agent/__init__.py +146 -0
  14. package/core/agent/agent_artifacts.py +764 -0
  15. package/core/agent/agent_eval.py +1073 -0
  16. package/core/agent/agent_execution.py +552 -0
  17. package/core/agent/agent_orchestrator.py +1345 -0
  18. package/core/agent/agent_targets.py +871 -0
  19. package/core/agent/agent_workspace.py +770 -0
  20. package/core/assets/README.md +24 -0
  21. package/core/assets/bugx-avatar-1024.png +0 -0
  22. package/core/assets/bugx-avatar-512.png +0 -0
  23. package/core/assets/bugx-avatar-tight.svg +23 -0
  24. package/core/assets/bugx-avatar.svg +28 -0
  25. package/core/assets/bugx-hero-cn.png +0 -0
  26. package/core/assets/bugx-hero-en.png +0 -0
  27. package/core/assets/project-layout.md +42 -0
  28. package/core/audit_packs/README.md +37 -0
  29. package/core/audit_packs/data-audit/manifest.json +94 -0
  30. package/core/audit_packs/data-audit/stages/00-scope.md +14 -0
  31. package/core/audit_packs/data-audit/stages/10-schema-inventory.md +14 -0
  32. package/core/audit_packs/data-audit/stages/20-query-and-integrity.md +14 -0
  33. package/core/audit_packs/data-audit/stages/80-evidence-regression.md +14 -0
  34. package/core/audit_packs/desktop-audit/manifest.json +123 -0
  35. package/core/audit_packs/desktop-audit/stages/00-scope.md +15 -0
  36. package/core/audit_packs/desktop-audit/stages/10-process-model.md +14 -0
  37. package/core/audit_packs/desktop-audit/stages/20-package-integrity.md +15 -0
  38. package/core/audit_packs/desktop-audit/stages/30-ui-behavior.md +14 -0
  39. package/core/audit_packs/desktop-audit/stages/80-evidence-regression.md +15 -0
  40. package/core/audit_packs/memory-testing.md +227 -0
  41. package/core/audit_packs/mobile-audit/manifest.json +155 -0
  42. package/core/audit_packs/mobile-audit/modules/android.md +19 -0
  43. package/core/audit_packs/mobile-audit/modules/h5.md +18 -0
  44. package/core/audit_packs/mobile-audit/modules/ios.md +25 -0
  45. package/core/audit_packs/mobile-audit/modules/miniprogram.md +26 -0
  46. package/core/audit_packs/mobile-audit/modules/webview.md +18 -0
  47. package/core/audit_packs/mobile-audit/stages/00-scope.md +14 -0
  48. package/core/audit_packs/mobile-audit/stages/10-platform-inventory.md +14 -0
  49. package/core/audit_packs/mobile-audit/stages/20-masvs-static.md +20 -0
  50. package/core/audit_packs/mobile-audit/stages/30-component-exposure.md +14 -0
  51. package/core/audit_packs/mobile-audit/stages/40-device-behavior.md +14 -0
  52. package/core/audit_packs/mobile-audit/stages/80-evidence-regression.md +13 -0
  53. package/core/audit_packs/native-audit/manifest.json +127 -0
  54. package/core/audit_packs/native-audit/stages/00-scope.md +14 -0
  55. package/core/audit_packs/native-audit/stages/10-static-white-box.md +14 -0
  56. package/core/audit_packs/native-audit/stages/20-memory-concurrency.md +15 -0
  57. package/core/audit_packs/native-audit/stages/30-behavior-black-box.md +39 -0
  58. package/core/audit_packs/native-audit/stages/80-evidence-regression.md +14 -0
  59. package/core/audit_packs/platform-testing.md +174 -0
  60. package/core/audit_packs/web-audit/manifest.json +191 -0
  61. package/core/audit_packs/web-audit/modules/graphql.md +5 -0
  62. package/core/audit_packs/web-audit/modules/h5.md +18 -0
  63. package/core/audit_packs/web-audit/modules/multi-tenant.md +4 -0
  64. package/core/audit_packs/web-audit/modules/oauth.md +4 -0
  65. package/core/audit_packs/web-audit/modules/upload.md +4 -0
  66. package/core/audit_packs/web-audit/modules/websocket.md +4 -0
  67. package/core/audit_packs/web-audit/stages/00-scope.md +13 -0
  68. package/core/audit_packs/web-audit/stages/10-discovery.md +13 -0
  69. package/core/audit_packs/web-audit/stages/20-auth-session.md +13 -0
  70. package/core/audit_packs/web-audit/stages/30-authz-business.md +13 -0
  71. package/core/audit_packs/web-audit/stages/40-input-output.md +13 -0
  72. package/core/audit_packs/web-audit/stages/50-state-async.md +13 -0
  73. package/core/audit_packs/web-audit/stages/60-file-ssrf-deser.md +12 -0
  74. package/core/audit_packs/web-audit/stages/70-config-dependency.md +12 -0
  75. package/core/audit_packs/web-audit/stages/80-evidence-regression.md +12 -0
  76. package/core/autonomous_cve/INTERFACE.md +61 -0
  77. package/core/autonomous_cve/README.md +58 -0
  78. package/core/autonomous_cve/SPEC.md +25 -0
  79. package/core/autonomous_cve/__init__.py +109 -0
  80. package/core/autonomous_cve/attack_graph.py +1096 -0
  81. package/core/autonomous_cve/attack_graph_store.py +1822 -0
  82. package/core/autonomous_cve/audit_campaign.py +1232 -0
  83. package/core/autonomous_cve/behavior_graph.py +459 -0
  84. package/core/autonomous_cve/ghsa_advisories.py +174 -0
  85. package/core/autonomous_cve/models.py +93 -0
  86. package/core/autonomous_cve/mutator.py +87 -0
  87. package/core/autonomous_cve/patcher.py +126 -0
  88. package/core/autonomous_cve/scout.py +278 -0
  89. package/core/autonomous_cve/synthesizer.py +207 -0
  90. package/core/autonomous_cve/verifier.py +100 -0
  91. package/core/bugx.md +1299 -0
  92. package/core/bugx_paths.py +1846 -0
  93. package/core/cloud_sync/INTERFACE.md +32 -0
  94. package/core/cloud_sync/README.md +62 -0
  95. package/core/cloud_sync/SPEC.md +25 -0
  96. package/core/cloud_sync/__init__.py +23 -0
  97. package/core/cloud_sync/auto_sync.py +398 -0
  98. package/core/cloud_sync/cloud_client.py +1199 -0
  99. package/core/cloud_sync/cloud_onboard.py +702 -0
  100. package/core/cloud_sync/cloud_schema.py +648 -0
  101. package/core/cloud_sync/consent.py +81 -0
  102. package/core/cloud_sync/device_identity.py +307 -0
  103. package/core/cloud_sync/endpoint_router.py +415 -0
  104. package/core/cloud_sync/flywheel_client.py +760 -0
  105. package/core/cloud_sync/network_transport.py +275 -0
  106. package/core/cloud_sync/onboard_wizard.py +493 -0
  107. package/core/cloud_sync/sensitive_filter.py +285 -0
  108. package/core/cloud_sync/sync_pull.py +695 -0
  109. package/core/cloud_sync/sync_push.py +721 -0
  110. package/core/contracts/AGENT_GUIDE.md +362 -0
  111. package/core/contracts/README.md +34 -0
  112. package/core/contracts/bugx-blackbox.md +541 -0
  113. package/core/contracts/bugx-opencode.md +469 -0
  114. package/core/contracts/bugx-quick.md +44 -0
  115. package/core/contracts/bugx-runtime-contract.md +353 -0
  116. package/core/contracts/bugx-worker.md +470 -0
  117. package/core/contracts/engine_gap_contracts.py +390 -0
  118. package/core/coverage/README.md +70 -0
  119. package/core/coverage/__init__.py +106 -0
  120. package/core/coverage/coverage_ai_review.py +185 -0
  121. package/core/coverage/coverage_backfill.py +54 -0
  122. package/core/coverage/coverage_bootstrap.py +713 -0
  123. package/core/coverage/coverage_business.py +36 -0
  124. package/core/coverage/coverage_cli.py +715 -0
  125. package/core/coverage/coverage_discovery.py +859 -0
  126. package/core/coverage/coverage_evidence.py +977 -0
  127. package/core/coverage/coverage_forensics.py +115 -0
  128. package/core/coverage/coverage_gate.py +277 -0
  129. package/core/coverage/coverage_intelligence.py +734 -0
  130. package/core/coverage/coverage_manifest.py +396 -0
  131. package/core/coverage/coverage_platform.py +77 -0
  132. package/core/coverage/coverage_validate.py +236 -0
  133. package/core/coverage/module_coverage.py +157 -0
  134. package/core/dev_harness/INTERFACE.md +20 -0
  135. package/core/dev_harness/README.md +21 -0
  136. package/core/dev_harness/SPEC.md +25 -0
  137. package/core/dev_harness/__init__.py +5 -0
  138. package/core/dev_harness/interaction_preset.py +408 -0
  139. package/core/engine-integrity.json +2625 -0
  140. package/core/fuzzing/README.md +49 -0
  141. package/core/fuzzing/__init__.py +82 -0
  142. package/core/fuzzing/concurrency_fuzzer.py +382 -0
  143. package/core/fuzzing/differential_oracle.py +629 -0
  144. package/core/fuzzing/fuzz_input.py +1188 -0
  145. package/core/fuzzing/stateful_fuzzer.py +332 -0
  146. package/core/governance/README.md +61 -0
  147. package/core/governance/__init__.py +130 -0
  148. package/core/governance/capacity_planner.py +124 -0
  149. package/core/governance/dependency_lock.py +317 -0
  150. package/core/governance/goal_governor.py +754 -0
  151. package/core/governance/guide_budget.py +458 -0
  152. package/core/governance/lockdown.sh +50 -0
  153. package/core/governance/readonly_enforcer.py +154 -0
  154. package/core/governance/runtime_tool_gate.py +373 -0
  155. package/core/governance/secret_redactor.py +772 -0
  156. package/core/governance/token_budget.py +38 -0
  157. package/core/host_acp/INTERFACE.md +36 -0
  158. package/core/host_acp/README.md +51 -0
  159. package/core/host_acp/SPEC.md +25 -0
  160. package/core/host_acp/__init__.py +121 -0
  161. package/core/host_acp/base.py +111 -0
  162. package/core/host_acp/claude.py +41 -0
  163. package/core/host_acp/cline.py +235 -0
  164. package/core/host_acp/codex.py +245 -0
  165. package/core/host_acp/dsh.py +48 -0
  166. package/core/host_acp/opencode.py +154 -0
  167. package/core/host_acp/pi.py +36 -0
  168. package/core/host_acp/zcode.py +41 -0
  169. package/core/host_runtime/INTERFACE.md +24 -0
  170. package/core/host_runtime/README.md +62 -0
  171. package/core/host_runtime/SPEC.md +25 -0
  172. package/core/host_runtime/__init__.py +21 -0
  173. package/core/host_runtime/adapters.py +412 -0
  174. package/core/host_runtime/autonomous_runner.py +1152 -0
  175. package/core/host_runtime/cline.py +435 -0
  176. package/core/host_runtime/common.py +103 -0
  177. package/core/host_runtime/free_models.py +786 -0
  178. package/core/host_runtime/host_bootstrap.py +389 -0
  179. package/core/host_runtime/host_evaluators.py +721 -0
  180. package/core/host_runtime/host_probe.py +41 -0
  181. package/core/host_runtime/host_provider_arbitrator.py +777 -0
  182. package/core/host_runtime/host_registry.py +655 -0
  183. package/core/host_runtime/host_usage.py +127 -0
  184. package/core/host_runtime/mcp_process_tracker.py +509 -0
  185. package/core/host_runtime/mcp_registry_gate.py +368 -0
  186. package/core/hosts/INTERFACE.md +51 -0
  187. package/core/hosts/README.md +67 -0
  188. package/core/hosts/SPEC.md +25 -0
  189. package/core/hosts/__init__.py +136 -0
  190. package/core/hosts/_base_usage.py +152 -0
  191. package/core/hosts/_codex_usage.py +297 -0
  192. package/core/hosts/_dsh_usage.py +184 -0
  193. package/core/hosts/_mcp_toml.py +365 -0
  194. package/core/hosts/_zcode_usage.py +269 -0
  195. package/core/hosts/base.py +451 -0
  196. package/core/hosts/claude.py +157 -0
  197. package/core/hosts/cline.py +225 -0
  198. package/core/hosts/codex.py +948 -0
  199. package/core/hosts/dsh.py +518 -0
  200. package/core/hosts/opencode.py +358 -0
  201. package/core/hosts/pi.py +151 -0
  202. package/core/hosts/zcode.py +219 -0
  203. package/core/i18n.py +252 -0
  204. package/core/infra/README.md +39 -0
  205. package/core/infra/__init__.py +15 -0
  206. package/core/infra/build_info.py +86 -0
  207. package/core/infra/client_metadata.py +185 -0
  208. package/core/infra/python_runtime.py +540 -0
  209. package/core/infra/safe_xml.py +221 -0
  210. package/core/launch_bugx.py +118 -0
  211. package/core/launch_phases/INTERFACE.md +31 -0
  212. package/core/launch_phases/README.md +106 -0
  213. package/core/launch_phases/SPEC.md +25 -0
  214. package/core/launch_phases/__init__.py +29 -0
  215. package/core/launch_phases/candidate_revalidation.py +484 -0
  216. package/core/launch_phases/common.py +1041 -0
  217. package/core/launch_phases/finding_confirm_phase.py +387 -0
  218. package/core/launch_phases/finding_settlement.py +1245 -0
  219. package/core/launch_phases/findings_adjudication.py +666 -0
  220. package/core/launch_phases/findings_snapshot.py +357 -0
  221. package/core/launch_phases/judge_phase.py +791 -0
  222. package/core/launch_phases/lesson_context.py +536 -0
  223. package/core/launch_phases/lifecycle_reporter.py +627 -0
  224. package/core/launch_phases/orchestrator_controls.py +682 -0
  225. package/core/launch_phases/post_commit.py +567 -0
  226. package/core/launch_phases/post_coverage_sync.py +591 -0
  227. package/core/launch_phases/post_dry_run.py +817 -0
  228. package/core/launch_phases/post_observability.py +367 -0
  229. package/core/launch_phases/post_phase.py +1087 -0
  230. package/core/launch_phases/post_receipt.py +362 -0
  231. package/core/launch_phases/post_round_lifecycle.py +786 -0
  232. package/core/launch_phases/pre_phase.py +1029 -0
  233. package/core/launch_phases/pre_recon_scout.py +862 -0
  234. package/core/launch_phases/pre_state_builder.py +1286 -0
  235. package/core/launch_phases/report_sharing.py +414 -0
  236. package/core/launch_phases/round_orchestrator.py +1133 -0
  237. package/core/launch_phases/session_runtime.py +1623 -0
  238. package/core/launch_phases/startup_gates.py +1022 -0
  239. package/core/launch_phases/startup_interaction.py +947 -0
  240. package/core/launch_phases/startup_version_gate.py +873 -0
  241. package/core/launch_phases/supervisor_bridge.py +1224 -0
  242. package/core/launch_phases/supervisor_coverage.py +417 -0
  243. package/core/launch_phases/supervisor_degraded.py +1219 -0
  244. package/core/launch_phases/worker_barriers.py +414 -0
  245. package/core/launch_phases/worker_orchestrator.py +1166 -0
  246. package/core/launch_phases/worker_prior.py +749 -0
  247. package/core/ledger/INTERFACE.md +35 -0
  248. package/core/ledger/README.md +160 -0
  249. package/core/ledger/SPEC.md +25 -0
  250. package/core/ledger/__init__.py +67 -0
  251. package/core/ledger/_facade.py +226 -0
  252. package/core/ledger/archive_ops.py +572 -0
  253. package/core/ledger/auto_materialization.py +459 -0
  254. package/core/ledger/bug-log.md +22 -0
  255. package/core/ledger/cli.py +270 -0
  256. package/core/ledger/export_ops.py +549 -0
  257. package/core/ledger/finding_confirmation.py +1274 -0
  258. package/core/ledger/finding_io.py +299 -0
  259. package/core/ledger/finding_lifecycle.py +307 -0
  260. package/core/ledger/finding_verification.py +369 -0
  261. package/core/ledger/incidents.py +999 -0
  262. package/core/ledger/lesson-replay-cases.json +20 -0
  263. package/core/ledger/lesson_ledger.py +241 -0
  264. package/core/ledger/lesson_replay.py +272 -0
  265. package/core/ledger/life_ledger.py +668 -0
  266. package/core/ledger/mistake-book.md +130 -0
  267. package/core/ledger/patterns.py +681 -0
  268. package/core/ledger/receipt_contract.py +253 -0
  269. package/core/ledger/schema.py +1192 -0
  270. package/core/ledger/sync_ops.py +935 -0
  271. package/core/ledger/tool_experience.py +682 -0
  272. package/core/ledger/verify_life.py +1526 -0
  273. package/core/lesson-ledger.json +275 -0
  274. package/core/locales/README.md +19 -0
  275. package/core/locales/en-US.json +462 -0
  276. package/core/locales/zh-CN.json +462 -0
  277. package/core/mcp_handlers/INTERFACE.md +75 -0
  278. package/core/mcp_handlers/README.md +62 -0
  279. package/core/mcp_handlers/SPEC.md +25 -0
  280. package/core/mcp_handlers/__init__.py +128 -0
  281. package/core/mcp_handlers/base.py +697 -0
  282. package/core/mcp_handlers/channel_lifecycle.py +696 -0
  283. package/core/mcp_handlers/graph_handlers.py +222 -0
  284. package/core/mcp_handlers/knowledge_handlers.py +536 -0
  285. package/core/mcp_handlers/mining_handlers.py +586 -0
  286. package/core/mcp_handlers/resource_prompt_table.py +116 -0
  287. package/core/mcp_handlers/retrieval_handlers.py +239 -0
  288. package/core/mcp_handlers/rpc_server.py +465 -0
  289. package/core/mcp_handlers/supervisor_handlers.py +1435 -0
  290. package/core/mcp_handlers/telemetry_handlers.py +227 -0
  291. package/core/mcp_handlers/tool_table.py +1015 -0
  292. package/core/mcp_runtime_support/README.md +21 -0
  293. package/core/mcp_runtime_support/__init__.py +1 -0
  294. package/core/mcp_runtime_support/common.py +363 -0
  295. package/core/mcp_runtime_support/environment.py +605 -0
  296. package/core/mcp_runtime_support/verifier.py +810 -0
  297. package/core/metadata.txt +5 -0
  298. package/core/planning/README.md +157 -0
  299. package/core/planning/__init__.py +242 -0
  300. package/core/planning/capability_plan.py +187 -0
  301. package/core/planning/capability_planner.py +195 -0
  302. package/core/planning/domain_archetype.py +542 -0
  303. package/core/planning/domain_router.py +267 -0
  304. package/core/planning/dynamic_flow_analyzer.py +328 -0
  305. package/core/planning/impact_pruner.py +435 -0
  306. package/core/planning/intent_adjudicator.py +175 -0
  307. package/core/planning/judge_pipeline.py +1163 -0
  308. package/core/planning/logic_analysis.py +419 -0
  309. package/core/planning/prompt_harness.py +1702 -0
  310. package/core/planning/source_inspector.py +267 -0
  311. package/core/planning/spec_harvester.py +449 -0
  312. package/core/planning/target_sandbox_manager.py +573 -0
  313. package/core/planning/test_capability_verifier.py +1364 -0
  314. package/core/planning/tools-kb.md +38 -0
  315. package/core/planning/unit_kind.py +122 -0
  316. package/core/probes/INTERFACE.md +73 -0
  317. package/core/probes/README.md +51 -0
  318. package/core/probes/SPEC.md +26 -0
  319. package/core/probes/__init__.py +70 -0
  320. package/core/probes/android_probe.py +384 -0
  321. package/core/probes/base.py +147 -0
  322. package/core/probes/codebase_memory_probe.py +590 -0
  323. package/core/probes/desktop_probe.py +238 -0
  324. package/core/probes/differential_probe.py +356 -0
  325. package/core/probes/efficiency_probe.py +168 -0
  326. package/core/probes/ios_binary_probe.py +368 -0
  327. package/core/probes/memory_probe.py +326 -0
  328. package/core/probes/miniprogram_probe.py +323 -0
  329. package/core/probes/mobile_probe.py +281 -0
  330. package/core/probes/native_probe.py +214 -0
  331. package/core/probes/openwiki_probe.py +193 -0
  332. package/core/probes/pattern_probe.py +347 -0
  333. package/core/probes/platform_probe.py +343 -0
  334. package/core/probes/probe_registry.py +1669 -0
  335. package/core/probes/sast_probe.py +1009 -0
  336. package/core/probes/sast_rules.py +841 -0
  337. package/core/probes/sca_scanner.py +731 -0
  338. package/core/probes/web_probe.py +359 -0
  339. package/core/project_profiler/INTERFACE.md +62 -0
  340. package/core/project_profiler/README.md +53 -0
  341. package/core/project_profiler/SPEC.md +28 -0
  342. package/core/project_profiler/__init__.py +201 -0
  343. package/core/project_profiler/arbitrator.py +311 -0
  344. package/core/project_profiler/constants.py +247 -0
  345. package/core/project_profiler/detector.py +392 -0
  346. package/core/project_profiler/extractors.py +836 -0
  347. package/core/project_profiler/fingerprint.py +116 -0
  348. package/core/project_profiler/storage.py +258 -0
  349. package/core/project_profiler/strategy.py +265 -0
  350. package/core/prompts/README.md +35 -0
  351. package/core/prompts/codex_dialog_dispatch.md +9 -0
  352. package/core/prompts/command_routing_en.md +42 -0
  353. package/core/prompts/command_routing_zh.md +42 -0
  354. package/core/prompts/l0_router.md +47 -0
  355. package/core/prompts/rules/anti_patterns.md +16 -0
  356. package/core/prompts/rules/concurrency_rules.md +14 -0
  357. package/core/prompts/rules/memory_leak_rules.md +13 -0
  358. package/core/prompts/rules/prompt_injection_defense.md +13 -0
  359. package/core/prompts/stages/stage_explore.md +31 -0
  360. package/core/prompts/stages/stage_gate.md +43 -0
  361. package/core/prompts/stages/stage_mutate.md +42 -0
  362. package/core/prompts/stages/stage_repair.md +85 -0
  363. package/core/repair/README.md +74 -0
  364. package/core/repair/__init__.py +169 -0
  365. package/core/repair/fix_watchlist.py +391 -0
  366. package/core/repair/l7_dynamic.py +418 -0
  367. package/core/repair/l7_repair_loop.py +465 -0
  368. package/core/repair/l7_selfcheck.py +862 -0
  369. package/core/repair/minimize_repro.py +466 -0
  370. package/core/repair/patch_synthesizer.py +617 -0
  371. package/core/repair/regression_pack.py +379 -0
  372. package/core/repair/rsi_fixer.py +910 -0
  373. package/core/repair/rsi_loop.py +313 -0
  374. package/core/repair/rsi_repair.py +348 -0
  375. package/core/repair/rsi_rounds.py +212 -0
  376. package/core/repair/rsi_scope.py +262 -0
  377. package/core/repair/self_heal.py +604 -0
  378. package/core/repair/test_generator.py +1108 -0
  379. package/core/repair/test_quality_auditor.py +410 -0
  380. package/core/repair/test_strategy.py +511 -0
  381. package/core/report_engine/INTERFACE.md +59 -0
  382. package/core/report_engine/README.md +69 -0
  383. package/core/report_engine/SPEC.md +28 -0
  384. package/core/report_engine/__init__.py +47 -0
  385. package/core/report_engine/attestation.py +224 -0
  386. package/core/report_engine/authority.py +255 -0
  387. package/core/report_engine/finding_report.py +417 -0
  388. package/core/report_engine/formal_report_builder.py +924 -0
  389. package/core/report_engine/html_renderers.py +696 -0
  390. package/core/report_engine/models.py +761 -0
  391. package/core/report_engine/pdf_exporter.py +231 -0
  392. package/core/report_engine/projects_assets.py +730 -0
  393. package/core/report_engine/report_client.py +743 -0
  394. package/core/report_engine/report_data_builder.py +388 -0
  395. package/core/report_engine/report_share.py +459 -0
  396. package/core/report_engine/sast_bridge.py +116 -0
  397. package/core/report_engine/server.py +822 -0
  398. package/core/report_engine/visual_report_builder.py +796 -0
  399. package/core/report_engine/web-conformance.md +63 -0
  400. package/core/report_engine/web_conformance.py +459 -0
  401. package/core/report_engine/workbench_assets.py +484 -0
  402. package/core/retrieval/INTERFACE.md +20 -0
  403. package/core/retrieval/README.md +161 -0
  404. package/core/retrieval/SPEC.md +25 -0
  405. package/core/retrieval/__init__.py +3 -0
  406. package/core/retrieval/code_analyzer.py +1684 -0
  407. package/core/retrieval/codebase_memory_bridge.py +337 -0
  408. package/core/retrieval/context_assembler.py +234 -0
  409. package/core/retrieval/corpus_fetch.py +369 -0
  410. package/core/retrieval/graph_ego.py +597 -0
  411. package/core/retrieval/knowledge_auto.py +662 -0
  412. package/core/retrieval/knowledge_sources.py +168 -0
  413. package/core/retrieval/knowledge_sync.py +909 -0
  414. package/core/retrieval/memory_store.py +480 -0
  415. package/core/retrieval/query_planner.py +1020 -0
  416. package/core/retrieval/rrf_engine.py +137 -0
  417. package/core/retrieval/slice_extractor.py +1209 -0
  418. package/core/retrieval/slice_normalizer.py +373 -0
  419. package/core/retrieval/slice_spec.py +357 -0
  420. package/core/retrieval/symbol_index.py +1132 -0
  421. package/core/retrieval/universal_code_matcher.py +437 -0
  422. package/core/retrieval/xerj_bridge.py +476 -0
  423. package/core/retrieval/xerj_supervisor.py +362 -0
  424. package/core/rules/README.md +33 -0
  425. package/core/rules/ios/PROVENANCE.json +30 -0
  426. package/core/rules/ios/crypto.yaml +36 -0
  427. package/core/rules/ios/network.yaml +20 -0
  428. package/core/rules/ios/resilience.yaml +47 -0
  429. package/core/rules/ios/storage.yaml +48 -0
  430. package/core/rules/mastg/LICENSE +173 -0
  431. package/core/rules/mastg/PROVENANCE.json +270 -0
  432. package/core/rules/mastg/mastg-android-asymmetric-key-pair-used-for-multiple-purposes.yml +13 -0
  433. package/core/rules/mastg/mastg-android-backup-manifest.yml +24 -0
  434. package/core/rules/mastg/mastg-android-biometric-event-bound.yml +49 -0
  435. package/core/rules/mastg/mastg-android-biometric-invalidated-enrollment.yml +11 -0
  436. package/core/rules/mastg/mastg-android-biometric-no-confirmation-required.yml +10 -0
  437. package/core/rules/mastg/mastg-android-biometric-validity-duration.yml +24 -0
  438. package/core/rules/mastg/mastg-android-broken-encryption-algorithms.yaml +9 -0
  439. package/core/rules/mastg/mastg-android-broken-encryption-modes.yaml +13 -0
  440. package/core/rules/mastg/mastg-android-content-provider-exported.yml +35 -0
  441. package/core/rules/mastg/mastg-android-custom-deeplink-scheme.yml +29 -0
  442. package/core/rules/mastg/mastg-android-dangerous-app-permissions.yaml +65 -0
  443. package/core/rules/mastg/mastg-android-data-unencrypted-shared-storage-no-user-interaction-apis.yml +36 -0
  444. package/core/rules/mastg/mastg-android-data-unencrypted-shared-storage-no-user-interaction-manifest.yml +15 -0
  445. package/core/rules/mastg/mastg-android-debuggable-flag.yml +10 -0
  446. package/core/rules/mastg/mastg-android-debugger-checks.yml +12 -0
  447. package/core/rules/mastg/mastg-android-deeplink-autoverify-missing.yml +33 -0
  448. package/core/rules/mastg/mastg-android-deeplink-unvalidated-parameter.yml +11 -0
  449. package/core/rules/mastg/mastg-android-device-passcode-present.yml +17 -0
  450. package/core/rules/mastg/mastg-android-fileprovider-broad-scope.yml +46 -0
  451. package/core/rules/mastg/mastg-android-hardcoded-crypto-keys-usage.yml +14 -0
  452. package/core/rules/mastg/mastg-android-hardcoded-security-provider.yaml +18 -0
  453. package/core/rules/mastg/mastg-android-implicit-intent-internal-communication.yml +30 -0
  454. package/core/rules/mastg/mastg-android-implicit-intent-leaking-extras.yml +29 -0
  455. package/core/rules/mastg/mastg-android-input-field-usage.yml +11 -0
  456. package/core/rules/mastg/mastg-android-key-generation-with-insufficient-key-length.yml +21 -0
  457. package/core/rules/mastg/mastg-android-keyboard-cache-input-types.yml +10 -0
  458. package/core/rules/mastg/mastg-android-local-storage-input-validation.yml +48 -0
  459. package/core/rules/mastg/mastg-android-native-debugger-checks.yml +12 -0
  460. package/core/rules/mastg/mastg-android-network-checkservertrusted.yml +12 -0
  461. package/core/rules/mastg/mastg-android-network-hostname-verification.yml +11 -0
  462. package/core/rules/mastg/mastg-android-network-insecure-trust-anchors.yml +11 -0
  463. package/core/rules/mastg/mastg-android-network-onreceivedsslerror.yml +12 -0
  464. package/core/rules/mastg/mastg-android-non-random-use.yml +16 -0
  465. package/core/rules/mastg/mastg-android-object-deserialization.yml +14 -0
  466. package/core/rules/mastg/mastg-android-overlay-protection.yml +68 -0
  467. package/core/rules/mastg/mastg-android-pendingintent-mutable.yml +39 -0
  468. package/core/rules/mastg/mastg-android-random-apis-insufficient-entropy.yml +17 -0
  469. package/core/rules/mastg/mastg-android-root-detection.yaml +59 -0
  470. package/core/rules/mastg/mastg-android-sdk-version.yml +10 -0
  471. package/core/rules/mastg/mastg-android-sensitive-data-in-notifications-manifest.yml +17 -0
  472. package/core/rules/mastg/mastg-android-sensitive-data-in-notifications.yml +11 -0
  473. package/core/rules/mastg/mastg-android-sensitive-data-in-screenshot.yml +18 -0
  474. package/core/rules/mastg/mastg-android-sql-injection-contentprovider.yml +17 -0
  475. package/core/rules/mastg/mastg-android-ssl-socket-hostnameverifier.yml +15 -0
  476. package/core/rules/mastg/mastg-android-strictmode.yml +10 -0
  477. package/core/rules/mastg/mastg-android-system-alert-window.yml +9 -0
  478. package/core/rules/mastg/mastg-android-webview-allow-local-access.yml +15 -0
  479. package/core/rules/mastg/mastg-android-webview-bridges.yml +28 -0
  480. package/core/rules/mastg/mastg-android-webview-safebrowsing.yml +20 -0
  481. package/core/rules/mastg/mastg-android-webview-url-handlers.yml +41 -0
  482. package/core/rules/miniprogram/PROVENANCE.json +26 -0
  483. package/core/rules/miniprogram/network.yaml +37 -0
  484. package/core/rules/miniprogram/platform.yaml +36 -0
  485. package/core/rules/miniprogram/storage.yaml +48 -0
  486. package/core/rules/mobsfscan-swift/LICENSE +165 -0
  487. package/core/rules/mobsfscan-swift/PROVENANCE.json +58 -0
  488. package/core/rules/mobsfscan-swift/auth.yaml +59 -0
  489. package/core/rules/mobsfscan-swift/crypto.yaml +66 -0
  490. package/core/rules/mobsfscan-swift/jailbreak.yaml +14 -0
  491. package/core/rules/mobsfscan-swift/keyboard.yaml +34 -0
  492. package/core/rules/mobsfscan-swift/logging.yaml +23 -0
  493. package/core/rules/mobsfscan-swift/network.yaml +55 -0
  494. package/core/rules/mobsfscan-swift/resilience.yaml +29 -0
  495. package/core/rules/mobsfscan-swift/secrets.yaml +33 -0
  496. package/core/rules/mobsfscan-swift/storage.yaml +29 -0
  497. package/core/rules/mobsfscan-swift/webview.yaml +32 -0
  498. package/core/runtime/README.md +198 -0
  499. package/core/runtime/__init__.py +3 -0
  500. package/core/runtime/bugx_logging.py +1393 -0
  501. package/core/runtime/daemon_runner.py +623 -0
  502. package/core/runtime/fixture_solidify.py +449 -0
  503. package/core/runtime/global_telemetry.py +549 -0
  504. package/core/runtime/incident_eval.py +148 -0
  505. package/core/runtime/interaction.py +605 -0
  506. package/core/runtime/interaction_store.py +435 -0
  507. package/core/runtime/interactive_menu.py +95 -0
  508. package/core/runtime/log_analytics.py +922 -0
  509. package/core/runtime/mining_quality_framework.py +1387 -0
  510. package/core/runtime/model_runner.py +769 -0
  511. package/core/runtime/platform_adapter.py +579 -0
  512. package/core/runtime/prep_validate.py +476 -0
  513. package/core/runtime/project_graph.py +827 -0
  514. package/core/runtime/project_init.py +481 -0
  515. package/core/runtime/project_profile.py +224 -0
  516. package/core/runtime/project_settings.py +963 -0
  517. package/core/runtime/provider_window.py +97 -0
  518. package/core/runtime/resume_ticket.py +115 -0
  519. package/core/runtime/scenario_eval.py +814 -0
  520. package/core/runtime/seed_drill.py +549 -0
  521. package/core/runtime/self_audit.py +550 -0
  522. package/core/runtime/session_profile.py +205 -0
  523. package/core/runtime/setup_ui_env.py +229 -0
  524. package/core/runtime/startup_environment.py +859 -0
  525. package/core/runtime/sync_store.py +1421 -0
  526. package/core/runtime/tool_install_targets.py +18 -0
  527. package/core/schemas/README.md +35 -0
  528. package/core/schemas/agent-graph.schema.json +368 -0
  529. package/core/schemas/attack-graph.schema.json +88 -0
  530. package/core/schemas/evidence-bundle.schema.json +33 -0
  531. package/core/schemas/skill-pack.schema.json +230 -0
  532. package/core/schemas/worker-checkpoint.schema.json +119 -0
  533. package/core/secure_atomic.py +289 -0
  534. package/core/seed_corpus/README.md +55 -0
  535. package/core/seed_corpus/c.txt +29 -0
  536. package/core/seed_corpus/cpp.txt +32 -0
  537. package/core/seed_corpus/css.txt +70 -0
  538. package/core/seed_corpus/go.txt +46 -0
  539. package/core/seed_corpus/java.txt +30 -0
  540. package/core/seed_corpus/javascript.txt +55 -0
  541. package/core/seed_corpus/kotlin.txt +28 -0
  542. package/core/seed_corpus/python.txt +71 -0
  543. package/core/seed_corpus/rust.txt +53 -0
  544. package/core/seed_corpus/swift.txt +29 -0
  545. package/core/seed_corpus/typescript.txt +29 -0
  546. package/core/skills/README.md +53 -0
  547. package/core/skills/__init__.py +189 -0
  548. package/core/skills/bugx_docs_mcp_server.py +416 -0
  549. package/core/skills/bugx_mcp_server.py +1134 -0
  550. package/core/skills/mcp_runtime.py +968 -0
  551. package/core/skills/mcp_session_proof.py +605 -0
  552. package/core/skills/mobile_ui_inspector.py +405 -0
  553. package/core/skills/skill_pack.py +1214 -0
  554. package/core/skills/skill_synthesizer.py +1153 -0
  555. package/core/skills/tools_kb.py +313 -0
  556. package/core/supervisor/INTERFACE.md +121 -0
  557. package/core/supervisor/README.md +209 -0
  558. package/core/supervisor/SPEC.md +25 -0
  559. package/core/supervisor/__init__.py +175 -0
  560. package/core/supervisor/audit_supervisor.py +1015 -0
  561. package/core/supervisor/budget_governor.py +760 -0
  562. package/core/supervisor/checkpoint_handler.py +368 -0
  563. package/core/supervisor/checkpoint_pipeline.py +1322 -0
  564. package/core/supervisor/checkpoint_sync.py +640 -0
  565. package/core/supervisor/claim_events.py +74 -0
  566. package/core/supervisor/claim_sync.py +590 -0
  567. package/core/supervisor/cli.py +812 -0
  568. package/core/supervisor/context_sync.py +55 -0
  569. package/core/supervisor/coverage_sync.py +115 -0
  570. package/core/supervisor/finding_commit.py +470 -0
  571. package/core/supervisor/finding_sync.py +688 -0
  572. package/core/supervisor/finding_workflow.py +659 -0
  573. package/core/supervisor/finish_policy.py +224 -0
  574. package/core/supervisor/finish_sync.py +185 -0
  575. package/core/supervisor/graph_sync.py +669 -0
  576. package/core/supervisor/lease_manager.py +788 -0
  577. package/core/supervisor/lifecycle_blocks.py +124 -0
  578. package/core/supervisor/next_round_sync.py +126 -0
  579. package/core/supervisor/observability.py +140 -0
  580. package/core/supervisor/recovery_sync.py +165 -0
  581. package/core/supervisor/rejection_remedies.py +308 -0
  582. package/core/supervisor/round_governor.py +306 -0
  583. package/core/supervisor/serial_authorization.py +500 -0
  584. package/core/supervisor/start_sync.py +87 -0
  585. package/core/supervisor/state_store.py +249 -0
  586. package/core/supervisor/supervisor_host.py +511 -0
  587. package/core/supervisor/supervisor_models.py +1143 -0
  588. package/core/supervisor/systemic_failure.py +104 -0
  589. package/core/supervisor/task_scheduler.py +1640 -0
  590. package/core/supervisor/worker_checkpoint.py +223 -0
  591. package/core/supervisor/worker_execution.py +265 -0
  592. package/core/supervisor/worker_handoff.py +192 -0
  593. package/core/supervisor/worker_lifecycle.py +396 -0
  594. package/core/supervisor/worker_runtime.py +999 -0
  595. package/core/supervisor/worker_sync.py +89 -0
  596. package/core/supervisor_types/README.md +36 -0
  597. package/core/supervisor_types/__init__.py +0 -0
  598. package/core/supervisor_types/exceptions.py +52 -0
  599. package/core/supervisor_types/graph_models.py +357 -0
  600. package/core/supervisor_types/path_containment.py +151 -0
  601. package/core/supervisor_types/target_fingerprint.py +310 -0
  602. package/core/supervisor_types/worker_claim.py +402 -0
  603. package/core/webui/INTERFACE.md +50 -0
  604. package/core/webui/README.md +57 -0
  605. package/core/webui/SPEC.md +25 -0
  606. package/core/webui/__init__.py +11 -0
  607. package/core/webui/adapters/__init__.py +27 -0
  608. package/core/webui/adapters/base.py +87 -0
  609. package/core/webui/adapters/bugx.py +102 -0
  610. package/core/webui/adapters/claude.py +218 -0
  611. package/core/webui/adapters/cline.py +399 -0
  612. package/core/webui/adapters/codex.py +256 -0
  613. package/core/webui/adapters/dsh.py +173 -0
  614. package/core/webui/adapters/opencode.py +218 -0
  615. package/core/webui/adapters/pi.py +272 -0
  616. package/core/webui/adapters/registry.py +100 -0
  617. package/core/webui/adapters/zcode.py +312 -0
  618. package/core/webui/api_routes_post.py +668 -0
  619. package/core/webui/dispatcher.py +1376 -0
  620. package/core/webui/docs_session_service.py +473 -0
  621. package/core/webui/handler.py +674 -0
  622. package/core/webui/ide_cloud_service.py +526 -0
  623. package/core/webui/mcp_inspector.py +1743 -0
  624. package/core/webui/static/assets/index-CXAsl8mr.js +333 -0
  625. package/core/webui/static/assets/index-DHQUtWtx.css +1 -0
  626. package/core/webui/static/assets/source-serif-4-cyrillic-400-normal-B8Z6Jvzv.woff +0 -0
  627. package/core/webui/static/assets/source-serif-4-cyrillic-400-normal-C44pakCn.woff2 +0 -0
  628. package/core/webui/static/assets/source-serif-4-cyrillic-500-normal-Bb4u56_6.woff +0 -0
  629. package/core/webui/static/assets/source-serif-4-cyrillic-500-normal-BdVUvljg.woff2 +0 -0
  630. package/core/webui/static/assets/source-serif-4-cyrillic-ext-400-normal-CWV284fw.woff2 +0 -0
  631. package/core/webui/static/assets/source-serif-4-cyrillic-ext-400-normal-DLkyKLvH.woff +0 -0
  632. package/core/webui/static/assets/source-serif-4-cyrillic-ext-500-normal-8-8HP2PF.woff +0 -0
  633. package/core/webui/static/assets/source-serif-4-cyrillic-ext-500-normal-DaDZE_Na.woff2 +0 -0
  634. package/core/webui/static/assets/source-serif-4-greek-400-normal-BccYJ-vZ.woff +0 -0
  635. package/core/webui/static/assets/source-serif-4-greek-400-normal-Cw5-AHNN.woff2 +0 -0
  636. package/core/webui/static/assets/source-serif-4-greek-500-normal-By8GFJzz.woff2 +0 -0
  637. package/core/webui/static/assets/source-serif-4-greek-500-normal-z-Q6FFuG.woff +0 -0
  638. package/core/webui/static/assets/source-serif-4-latin-400-normal-DJ5YJwmz.woff2 +0 -0
  639. package/core/webui/static/assets/source-serif-4-latin-400-normal-Dn3IlU-Z.woff +0 -0
  640. package/core/webui/static/assets/source-serif-4-latin-500-normal-CUHe9xxf.woff2 +0 -0
  641. package/core/webui/static/assets/source-serif-4-latin-500-normal-DVVamBqs.woff +0 -0
  642. package/core/webui/static/assets/source-serif-4-latin-ext-400-normal-CEpydyUl.woff +0 -0
  643. package/core/webui/static/assets/source-serif-4-latin-ext-400-normal-Cp7z-ARB.woff2 +0 -0
  644. package/core/webui/static/assets/source-serif-4-latin-ext-500-normal-BYjRCDVy.woff2 +0 -0
  645. package/core/webui/static/assets/source-serif-4-latin-ext-500-normal-D-qasQTj.woff +0 -0
  646. package/core/webui/static/assets/source-serif-4-vietnamese-400-normal-BbG3LG1A.woff2 +0 -0
  647. package/core/webui/static/assets/source-serif-4-vietnamese-400-normal-DR1UuFon.woff +0 -0
  648. package/core/webui/static/assets/source-serif-4-vietnamese-500-normal-8N8MYVKB.woff +0 -0
  649. package/core/webui/static/assets/source-serif-4-vietnamese-500-normal-Bi3OSTTW.woff2 +0 -0
  650. package/core/webui/static/favicon.png +0 -0
  651. package/core/webui/static/icon-192.png +0 -0
  652. package/core/webui/static/index.html +42 -0
  653. package/core/webui/static/manifest.webmanifest +19 -0
  654. package/core/webui/static/project-settings.css +6458 -0
  655. package/core/webui/static/project-settings.js +9602 -0
  656. package/core/webui/static/sw.js +8 -0
  657. package/core/webui/workspace_service.py +218 -0
  658. package/docs/07_distribution/01_README_NPM.md +281 -0
  659. package/docs/07_distribution/README.md +16 -0
  660. package/docs/README.md +121 -0
  661. package/ecosystem/README.md +129 -0
  662. package/ecosystem/integrations/README.md +38 -0
  663. package/ecosystem/integrations/cline/skills/bugx/SKILL.md +69 -0
  664. package/ecosystem/integrations/dsh/agents/bugx.md +27 -0
  665. package/ecosystem/integrations/dsh/dsh-patch.yml +18 -0
  666. package/ecosystem/integrations/dsh/mcp/cordis.patch.yml +4 -0
  667. package/ecosystem/integrations/dsh/mcp/index.js +219 -0
  668. package/ecosystem/integrations/dsh/mcp/package.json +28 -0
  669. package/ecosystem/integrations/dsh/skills/bugx/SKILL.md +70 -0
  670. package/ecosystem/integrations/dsh/skills/bugx-dsh/SKILL.md +229 -0
  671. package/ecosystem/integrations/dsh/ui/client.js +87 -0
  672. package/ecosystem/integrations/dsh/ui/cordis.patch.yml +4 -0
  673. package/ecosystem/integrations/dsh/ui/index.js +7 -0
  674. package/ecosystem/integrations/dsh/ui/package.json +27 -0
  675. package/ecosystem/integrations/opencode/bugx-mcp-manifest.json +53 -0
  676. package/ecosystem/integrations/opencode/mcp-lock.json +3067 -0
  677. package/ecosystem/integrations/opencode/opencode.json +118 -0
  678. package/ecosystem/integrations/pi/extensions/bugx/README.md +12 -0
  679. package/ecosystem/integrations/pi/extensions/bugx/index.ts +299 -0
  680. package/ecosystem/integrations/pi/extensions/bugx/manifest.json +11 -0
  681. package/ecosystem/integrations/pi/skills/bugx/SKILL.md +69 -0
  682. package/ecosystem/integrations/qoder/CONNECTORS.md +54 -0
  683. package/ecosystem/integrations/qoder/connector-meta.json +21 -0
  684. package/ecosystem/integrations/workbuddy/connector-meta.json +19 -0
  685. package/ecosystem/integrations/workbuddy/icon.png +0 -0
  686. package/ecosystem/integrations/workbuddy/skills/bugx/SKILL.md +70 -0
  687. package/ecosystem/plugins/README.md +37 -0
  688. package/ecosystem/plugins/bugx/.claude-plugin/marketplace.json +17 -0
  689. package/ecosystem/plugins/bugx/.claude-plugin/plugin.json +16 -0
  690. package/ecosystem/plugins/bugx/.codex-plugin/plugin.json +41 -0
  691. package/ecosystem/plugins/bugx/.zcode-plugin/plugin.json +19 -0
  692. package/ecosystem/plugins/bugx/agents/bugx-judge.md +71 -0
  693. package/ecosystem/plugins/bugx/agents/bugx-worker.md +31 -0
  694. package/ecosystem/plugins/bugx/agents/bugx.md +74 -0
  695. package/ecosystem/plugins/bugx/assets/bugx-avatar-512.png +0 -0
  696. package/ecosystem/plugins/bugx/skills/bugx/SKILL.md +118 -0
  697. package/ecosystem/plugins/bugx/skills/bugx-claude/SKILL.md +326 -0
  698. package/ecosystem/plugins/bugx/skills/bugx-dsh/SKILL.md +229 -0
  699. package/ecosystem/plugins/bugx/skills/bugx-opencode/SKILL.md +129 -0
  700. package/ecosystem/plugins/bugx/skills/bugx-zcode/SKILL.md +459 -0
  701. package/interfaces/README.md +143 -0
  702. package/interfaces/bin/README.md +35 -0
  703. package/interfaces/bin/bugx.js +80 -0
  704. package/interfaces/cli/README.md +90 -0
  705. package/interfaces/cli/bugx_cli/__init__.py +4 -0
  706. package/interfaces/cli/bugx_cli/cli.py +1678 -0
  707. package/interfaces/cli/bugx_cli/commands/__init__.py +1 -0
  708. package/interfaces/cli/bugx_cli/commands/advisory.py +94 -0
  709. package/interfaces/cli/bugx_cli/commands/agent.py +3944 -0
  710. package/interfaces/cli/bugx_cli/commands/audit.py +632 -0
  711. package/interfaces/cli/bugx_cli/commands/autonomous.py +260 -0
  712. package/interfaces/cli/bugx_cli/commands/cloud.py +1370 -0
  713. package/interfaces/cli/bugx_cli/commands/daemon.py +50 -0
  714. package/interfaces/cli/bugx_cli/commands/doctor.py +1345 -0
  715. package/interfaces/cli/bugx_cli/commands/goal.py +107 -0
  716. package/interfaces/cli/bugx_cli/commands/interaction.py +244 -0
  717. package/interfaces/cli/bugx_cli/commands/knowledge.py +617 -0
  718. package/interfaces/cli/bugx_cli/commands/lifecycle.py +2763 -0
  719. package/interfaces/cli/bugx_cli/commands/patch.py +1014 -0
  720. package/interfaces/cli/bugx_cli/commands/plugin.py +2714 -0
  721. package/interfaces/cli/bugx_cli/commands/plugin_claude.py +1446 -0
  722. package/interfaces/cli/bugx_cli/commands/plugin_cline.py +269 -0
  723. package/interfaces/cli/bugx_cli/commands/plugin_codex.py +74 -0
  724. package/interfaces/cli/bugx_cli/commands/plugin_funide.py +728 -0
  725. package/interfaces/cli/bugx_cli/commands/plugin_qoder.py +216 -0
  726. package/interfaces/cli/bugx_cli/commands/plugin_zcode.py +710 -0
  727. package/interfaces/cli/bugx_cli/commands/project.py +670 -0
  728. package/interfaces/cli/bugx_cli/commands/report.py +260 -0
  729. package/interfaces/cli/bugx_cli/commands/skill.py +251 -0
  730. package/interfaces/cli/bugx_cli/commands/stats.py +133 -0
  731. package/interfaces/cli/bugx_cli/commands/system.py +2567 -0
  732. package/interfaces/cli/bugx_cli/common.py +898 -0
  733. package/interfaces/cli/bugx_cli/host_adapters.py +1917 -0
  734. package/interfaces/cli/bugx_cli/hosts/__init__.py +80 -0
  735. package/interfaces/cli/bugx_cli/hosts/base.py +99 -0
  736. package/interfaces/cli/bugx_cli/hosts/registry.py +571 -0
  737. package/interfaces/cli/bugx_cli/hosts/template_engine.py +188 -0
  738. package/interfaces/cli/bugx_cli/infra/__init__.py +209 -0
  739. package/interfaces/cli/bugx_cli/infra/ai_advisor.py +721 -0
  740. package/interfaces/cli/bugx_cli/infra/engine_installer.py +1937 -0
  741. package/interfaces/cli/bugx_cli/infra/host_sync.py +545 -0
  742. package/interfaces/cli/bugx_cli/infra/mcp_advisor.py +755 -0
  743. package/interfaces/cli/bugx_cli/infra/security.py +332 -0
  744. package/package.json +98 -4
  745. package/pyproject.toml +246 -0
  746. package/scripts/README.md +118 -0
  747. package/scripts/ensure-python.mjs +97 -0
  748. package/scripts/isolate-npm-readme.mjs +40 -0
  749. package/scripts/runtime.lock.json +31 -0
  750. package/scripts/sync-version.mjs +37 -0
  751. package/scripts/test-npm-wrapper.mjs +265 -0
@@ -0,0 +1,1345 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import copy
5
+ import hashlib
6
+ import json
7
+ import os
8
+ import re
9
+ import shutil
10
+ import site
11
+ import subprocess
12
+ import sys
13
+ import tempfile
14
+ import time
15
+ import urllib.error
16
+ import urllib.parse
17
+ import urllib.request
18
+ from pathlib import Path
19
+ from typing import Any
20
+
21
+ from .. import __version__
22
+ from ..common import *
23
+ from ..infra import _mcp_session_hygiene_check
24
+ from ..infra.engine_installer import (
25
+ _engine_build_id,
26
+ _engine_receipt_build_id,
27
+ _engine_integrity_status,
28
+ _engine_self_integrity,
29
+ )
30
+
31
+
32
+ _CLOUD_ENDPOINT_CHECK_NAME = "云端端点连通性"
33
+ _CLOUD_DEFAULT_BASE_URL = "https://bugx.dev"
34
+ _CLOUD_HEALTH_PATHS = ("/health", "/api/v1/health")
35
+ _CLOUD_PROBE_TIMEOUT = 1.5
36
+
37
+
38
+ def _normalize_cloud_probe_base_url(raw: object) -> str:
39
+ if not isinstance(raw, str) or not raw.strip():
40
+ raise ValueError("云端地址为空")
41
+ value = raw.strip()
42
+ if not value.startswith(("http://", "https://")):
43
+ value = "https://" + value
44
+ parsed = urllib.parse.urlsplit(value)
45
+ if parsed.scheme not in {"http", "https"} or not parsed.netloc:
46
+ raise ValueError("云端地址必须是带 host 的 http(s) URL")
47
+ if parsed.username or parsed.password or parsed.query or parsed.fragment:
48
+ raise ValueError("云端地址不能包含用户名、密码、查询参数或 fragment")
49
+ host = (parsed.hostname or "").lower()
50
+ if parsed.scheme == "http" and host not in {"127.0.0.1", "localhost", "::1"}:
51
+ raise ValueError("远程云端地址必须使用 HTTPS;HTTP 只允许本机测试服务")
52
+ base_url = value.rstrip("/")
53
+ if base_url.endswith("/api/v1"):
54
+ base_url = base_url[: -len("/api/v1")]
55
+ return base_url
56
+
57
+
58
+ def _project_cloud_mode_enabled(root: Path) -> bool:
59
+ onboarding = root / ".bugx" / "cloud-onboard.json"
60
+ try:
61
+ data = json.loads(onboarding.read_text(encoding="utf-8"))
62
+ except (OSError, UnicodeError, json.JSONDecodeError):
63
+ return False
64
+ return isinstance(data, dict) and data.get("state") in {"done", "sync"}
65
+
66
+
67
+ def _cloud_probe_target(root: Path) -> tuple[str | None, bool, str | None]:
68
+ """Resolve an explicit cloud target without triggering route selection or DNS."""
69
+ env_base = os.environ.get("BUGX_CLOUD_API_BASE", "").strip()
70
+ if env_base:
71
+ try:
72
+ return _normalize_cloud_probe_base_url(env_base), True, None
73
+ except ValueError as exc:
74
+ return None, True, f"BUGX_CLOUD_API_BASE 无效:{exc}"
75
+
76
+ try:
77
+ from .cloud import _telemetry_config_path
78
+
79
+ config_path = _telemetry_config_path()
80
+ config = json.loads(config_path.read_text(encoding="utf-8")) if config_path.is_file() else {}
81
+ except (OSError, UnicodeError, json.JSONDecodeError, TypeError) as exc:
82
+ return None, True, f"云端配置读取失败:{exc}"
83
+ if not isinstance(config, dict):
84
+ return None, True, "云端配置必须是 JSON 对象"
85
+
86
+ raw_base = config.get("base_url")
87
+ cloud_mode = _project_cloud_mode_enabled(root)
88
+ if raw_base is not None and (not isinstance(raw_base, str) or raw_base.strip()):
89
+ try:
90
+ base_url = _normalize_cloud_probe_base_url(raw_base)
91
+ except ValueError as exc:
92
+ return None, True, f"cloud-config.json 的 base_url 无效:{exc}"
93
+ # The stock endpoint is intentionally skipped for a local-only project;
94
+ # an explicit onboarding state still means the user opted into cloud mode.
95
+ return base_url, base_url != _CLOUD_DEFAULT_BASE_URL or cloud_mode, None
96
+ if cloud_mode:
97
+ return _CLOUD_DEFAULT_BASE_URL, True, None
98
+ return None, False, None
99
+
100
+
101
+ def _cloud_endpoint_check(root: Path) -> tuple[str, bool, str]:
102
+ base_url, explicit, config_error = _cloud_probe_target(root)
103
+ if config_error:
104
+ return _CLOUD_ENDPOINT_CHECK_NAME, False, config_error
105
+ if not explicit or not base_url:
106
+ return _CLOUD_ENDPOINT_CHECK_NAME, True, "跳过(未配置自定义云端端点)"
107
+
108
+ _ensure_core_importable()
109
+ ctx = None
110
+ try:
111
+ from core.infra.client_metadata import tls_context
112
+ ctx = tls_context(base_url=base_url)
113
+ except Exception:
114
+ pass
115
+
116
+ last_error: Exception | None = None
117
+ for path in _CLOUD_HEALTH_PATHS:
118
+ health_url = f"{base_url}{path}"
119
+ try:
120
+ kwargs: dict[str, Any] = {"timeout": _CLOUD_PROBE_TIMEOUT}
121
+ if ctx is not None:
122
+ kwargs["context"] = ctx
123
+ response = urllib.request.urlopen(health_url, **kwargs)
124
+ try:
125
+ status = getattr(response, "status", None)
126
+ if not isinstance(status, int):
127
+ status = response.getcode()
128
+ finally:
129
+ close = getattr(response, "close", None)
130
+ if callable(close):
131
+ close()
132
+ if status in (200, 204):
133
+ return _CLOUD_ENDPOINT_CHECK_NAME, True, f"{base_url} 在线 (HTTP {status})"
134
+ if status in (401, 403):
135
+ return _CLOUD_ENDPOINT_CHECK_NAME, True, f"{base_url} 在线 (HTTP {status} 需鉴权)"
136
+ return _CLOUD_ENDPOINT_CHECK_NAME, False, f"{base_url} 端点可达,但健康检查返回 HTTP {status}"
137
+ except urllib.error.HTTPError as exc:
138
+ if exc.code in (200, 204):
139
+ return _CLOUD_ENDPOINT_CHECK_NAME, True, f"{base_url} 在线 (HTTP {exc.code})"
140
+ if exc.code in (401, 403):
141
+ return _CLOUD_ENDPOINT_CHECK_NAME, True, f"{base_url} 在线 (HTTP {exc.code} 需鉴权)"
142
+ if exc.code == 404 and path != _CLOUD_HEALTH_PATHS[-1]:
143
+ last_error = exc
144
+ continue
145
+ return _CLOUD_ENDPOINT_CHECK_NAME, False, f"{base_url} 端点可达,但健康检查返回 HTTP {exc.code}"
146
+ except Exception as exc: # noqa: BLE001 - doctor must report, not crash, on network errors.
147
+ last_error = exc
148
+ break
149
+
150
+ if last_error is not None:
151
+ try:
152
+ from core.cloud_sync.cloud_client import diagnose_network_error
153
+ diag = diagnose_network_error(last_error, health_url)
154
+ if diag.get("code") in {
155
+ "LOCAL_NETWORK_BLOCKED",
156
+ "LOCAL_NETWORK_UNREACHABLE",
157
+ "LOCAL_NETWORK_PROBE_UNAVAILABLE",
158
+ }:
159
+ return _CLOUD_ENDPOINT_CHECK_NAME, False, f"{base_url} 连通性诊断:{diag['message']}"
160
+ except Exception:
161
+ pass
162
+ return _CLOUD_ENDPOINT_CHECK_NAME, False, f"{base_url} 连通性检查失败:{last_error}"
163
+
164
+ return _CLOUD_ENDPOINT_CHECK_NAME, False, f"{base_url} 健康检查未返回结果"
165
+
166
+
167
+ def _heal_project_manifest_version(root: Path, *, force: bool = False) -> tuple[str, str] | None:
168
+ """把滞后于当前 CLI 的 ``manifest.bugx_version`` 就地对齐(DOC-180)。
169
+
170
+ 返回 ``(旧值, 新值)``;无需对齐时返回 ``None``。只改这一个字段,绝不触碰
171
+ 运行态(生命、结算、错题集)。
172
+
173
+ 历史缺陷:这段自愈原先嵌在 ``if not version_ok:`` 里,而
174
+ ``_version_contract_status`` 的归一化会把 ``1.0.0+2`` 视同 ``1.0.0`` 并返回
175
+ ``version_ok=True``,于是**自愈分支永远进不去**——清单永久停在旧标记,而引擎
176
+ 门禁(另一套不归一化的比较)却一直拒绝启动。虚假阻断就这样被"修"成了永久阻断。
177
+ """
178
+ manifest_file = root / ".bugx" / "manifest.json"
179
+ if not manifest_file.is_file() or manifest_file.is_symlink():
180
+ return None
181
+ try:
182
+ data = json.loads(manifest_file.read_text(encoding="utf-8"))
183
+ except (OSError, UnicodeError, json.JSONDecodeError):
184
+ return None
185
+ if not isinstance(data, dict):
186
+ return None
187
+ old = data.get("bugx_version")
188
+ if not isinstance(old, str) or old == __version__:
189
+ return None
190
+ from ..infra.engine_installer import _contract_version
191
+ if not force and _contract_version(old) != _contract_version(__version__):
192
+ return None
193
+ data["bugx_version"] = __version__
194
+ try:
195
+ _doctor_atomic_replace(
196
+ manifest_file,
197
+ (json.dumps(data, indent=2, ensure_ascii=False) + "\n").encode("utf-8"),
198
+ mode=manifest_file.stat().st_mode & 0o777,
199
+ )
200
+ except OSError:
201
+ return None
202
+ return old, __version__
203
+
204
+
205
+ def _asset_can_replace_global_engine() -> tuple[bool, str]:
206
+ """Doctor repair may replace the global engine only from a strictly newer asset."""
207
+ asset_id = _engine_build_id(asset_root())
208
+ global_id = _engine_build_id(global_engine_root())
209
+ if asset_id is None:
210
+ return False, "安装资源(asset_root)缺少有效的 Build ID 标记,无法自动修复;请重新安装/升级 CLI。"
211
+ if global_id is None:
212
+ return False, (
213
+ "全局引擎缺少 Build ID 标记(可能损坏或未初始化);无法确认目标版本,拒绝自动替换。"
214
+ "请先备份并核对共享引擎路径与可信安装资源;Doctor 不建议运行 `bugx install --force`。"
215
+ )
216
+ if global_id > asset_id:
217
+ return False, (
218
+ f"CLI 安装资源 build_id={asset_id} 低于全局引擎 build_id={global_id};"
219
+ f"拒绝自动降级。请先升级或重装 build_id >= {global_id} 的 CLI wheel,"
220
+ "再重跑 doctor;不要运行 `bugx install --force`,它会将共享引擎降级。"
221
+ )
222
+ if global_id == asset_id:
223
+ # 同 build **不等于**同内容:引擎文件被改坏/删缺时,安装资源仍是完好的
224
+ # 同一份 build,此时重放它就是唯一正确的修复。原实现无条件 `return
225
+ # False`,于是「引擎已损坏 + 资源同 build」变成永久死锁——doctor 每轮
226
+ # 都报完整性失败,却永远拒绝修复,且提示让用户「先升级到更高 build」,
227
+ # 而同源安装的 CLI 根本产不出更高 build(工具自己的 AI 诊断都写明了
228
+ # 这一点)。这里只在**引擎自身校验失败**时放行重放。
229
+ # 这里必须问「引擎与**源**是否一致」,不能问「引擎与自己的清单是否一致」。
230
+ # 后者在同源安装下恒为真:改了源码后清单与引擎文件一起漂移,两边自洽,
231
+ # 于是 doctor 一边报 bundle_sha256 不一致、一边判定「无需替换」——永久
232
+ # 死锁,且提示让用户「升级到更高 build」,而同源 CLI 产不出更高 build。
233
+ # 2026-11-03 实测复现:global 与 asset 同 build,前者缺 engine_run_node_flags
234
+ # 修复,_engine_self_integrity 仍返回 (True, '488 个静态文件与自身清单一致')。
235
+ healthy, _detail = _engine_integrity_status(asset_root(), global_engine_root())
236
+ if healthy:
237
+ return False, (
238
+ f"全局引擎与安装资源 Build ID 相同 (build_id={global_id})"
239
+ "且内容与源一致,无需替换。"
240
+ )
241
+ # 放行前必须确认**来源本身**完好:损坏的引擎配损坏的资源时重放,
242
+ # 只会把坏字节原样覆盖回去,还顺手毁掉现场。此前的 `==` 分支无条件
243
+ # 拒绝,连带把这条本可救的场景一起挡死了。
244
+ source_ok, source_detail = _engine_self_integrity(asset_root())
245
+ if not source_ok:
246
+ # 缺陷 #11:两条判据(「引擎与源是否一致」和「源自身是否完好」)
247
+ # 用了两套口径,用户因此拿到自相矛盾的处方——doctor 一边报
248
+ # 「引擎与源不一致」,一边又说「同 build 无需替换/请升级到更高 build」,
249
+ # 而同源安装根本产不出更高 build。这里必须把**两条判据的实际取值**
250
+ # 一起说清,并给出唯一真正可执行的动作。
251
+ return False, (
252
+ "全局引擎与安装资源都不自洽:"
253
+ f"引擎↔源={_detail or '不一致'};源自身={source_detail}。"
254
+ "此时重放资源只会把坏字节原样覆盖回去,故拒绝修复。"
255
+ "可执行动作:重装/升级 CLI(写入新的安装资源)后重跑 doctor;"
256
+ "若资源是新装的仍报不自洽,说明该 wheel 本身损坏。"
257
+ )
258
+ return True, ""
259
+ return True, ""
260
+
261
+
262
+ def _user_site_asset_candidates() -> list[tuple[str, Path]]:
263
+ """Enumerate user-site engine payloads across interpreters and platforms.
264
+
265
+ ``site.getuserbase()`` describes only the *running* interpreter, yet the
266
+ replica that actually drifts is the one another interpreter installed (a
267
+ second pyenv version, a Homebrew Python, or ``pip install --user`` under a
268
+ different toolchain). Those land in well-known per-platform bases, so all
269
+ of them are enumerated instead of trusting a single lookup.
270
+ """
271
+ home = Path.home()
272
+ candidates: list[tuple[str, Path]] = []
273
+
274
+ def add(label: str, base: Path | None) -> None:
275
+ if base is not None:
276
+ candidates.append((label, base / "share" / "bugx-agent" / "core"))
277
+
278
+ try:
279
+ add("user-site", Path(site.getuserbase()))
280
+ except Exception: # noqa: BLE001 - discovery degrades, never aborts the check.
281
+ pass
282
+ # macOS: pip --user installs into ~/Library/Python/<X.Y>/
283
+ mac_root = home / "Library" / "Python"
284
+ if mac_root.is_dir():
285
+ for base in sorted(mac_root.iterdir()):
286
+ if base.is_dir():
287
+ add(f"user-site:macos/{base.name}", base)
288
+ # POSIX/pyenv: pip --user installs into ~/.local
289
+ add("user-site:posix", home / ".local")
290
+ # Windows: %APPDATA%\Python and %APPDATA%\Python<XY>
291
+ appdata = os.environ.get("APPDATA")
292
+ if appdata:
293
+ roaming = Path(appdata)
294
+ add("user-site:windows", roaming / "Python")
295
+ if roaming.is_dir():
296
+ for base in sorted(roaming.glob("Python*")):
297
+ if base.is_dir():
298
+ add(f"user-site:windows/{base.name}", base)
299
+ return candidates
300
+
301
+
302
+ def _path_entry_asset_candidates() -> list[tuple[str, Path]]:
303
+ """Derive engine payload paths from every BugX console entry on PATH.
304
+
305
+ A console script lives at ``<prefix>/bin/bugx`` (POSIX) or
306
+ ``<prefix>\\Scripts\\bugx.exe`` (Windows), and pip installs the engine payload
307
+ relative to that same prefix. This catches interpreters whose data
308
+ directory is unrelated to the running one (extra venvs, pipx, pyenv).
309
+ """
310
+ candidates: list[tuple[str, Path]] = []
311
+ try:
312
+ entries = _bugx_cli_paths()
313
+ except Exception: # noqa: BLE001 - discovery degrades, never aborts the check.
314
+ return candidates
315
+ for entry in entries:
316
+ prefix = entry.parent.parent
317
+ candidates.append((
318
+ f"cli-prefix:{prefix.name or prefix}",
319
+ prefix / "share" / "bugx-agent" / "core",
320
+ ))
321
+ return candidates
322
+
323
+
324
+ def _engine_replica_consistency_check() -> tuple[bool, str]:
325
+ """Compare installed engine copies and the receipt that identifies the global copy."""
326
+ global_root = global_engine_root()
327
+ global_id = _engine_build_id(global_root)
328
+ asset_build_id: int | None = None
329
+ issues: list[str] = []
330
+ replica_build_ids: list[tuple[str, int]] = []
331
+ replica_inventory_complete = True
332
+ replicas: list[tuple[str, Path]] = [("global", global_root)]
333
+ try:
334
+ replicas.append(("asset", asset_root()))
335
+ except Exception as exc: # Doctor reports discovery errors instead of aborting.
336
+ issues.append(f"asset_root 无法读取:{exc}")
337
+ replica_inventory_complete = False
338
+ for label, user_asset in _user_site_asset_candidates() + _path_entry_asset_candidates():
339
+ try:
340
+ if user_asset.exists() or user_asset.is_symlink():
341
+ replicas.append((label, user_asset))
342
+ except OSError as exc:
343
+ issues.append(f"{label} 安装资源路径无法读取:{user_asset}:{exc}")
344
+ replica_inventory_complete = False
345
+
346
+ seen: set[Path] = set()
347
+ replica_details: list[str] = []
348
+ for name, path in replicas:
349
+ try:
350
+ resolved = path.resolve()
351
+ except (OSError, RuntimeError) as exc:
352
+ issues.append(f"{name} 引擎副本路径无法解析:{path} ({exc})")
353
+ replica_inventory_complete = False
354
+ continue
355
+ if resolved in seen:
356
+ continue
357
+ seen.add(resolved)
358
+ build_id = _engine_build_id(path)
359
+ if name == "asset":
360
+ asset_build_id = build_id
361
+ replica_details.append(f"{name}={path} build_id={build_id!r}")
362
+ if build_id is None:
363
+ issues.append(f"{name} 引擎副本缺少有效 Build ID:{path}")
364
+ replica_inventory_complete = False
365
+ else:
366
+ replica_build_ids.append((name, build_id))
367
+ if name != "global" and build_id != global_id:
368
+ issues.append(f"{name} build_id={build_id} 与 global build_id={global_id!r} 不一致")
369
+
370
+ receipt_path = global_root.parent / "engine-receipt.json"
371
+ receipt_id = _engine_receipt_build_id(receipt_path)
372
+ if receipt_id is None:
373
+ issues.append(f"全局引擎安装回执缺失或无效:{receipt_path}")
374
+ elif receipt_id != global_id:
375
+ issues.append(f"安装回执 engine_build_id={receipt_id} 与 global build_id={global_id!r} 不一致")
376
+
377
+ if issues:
378
+ detail = ";".join(issues)
379
+ if (global_id is not None and asset_build_id is not None
380
+ and asset_build_id < global_id):
381
+ detail += (
382
+ f";CLI 安装资源 build_id={asset_build_id} 低于全局引擎 build_id={global_id},"
383
+ f"拒绝自动降级。请先升级或重装 build_id >= {global_id} 的 CLI wheel 后重跑 doctor;"
384
+ "不要运行 `bugx install --force`,它会将共享引擎降级并影响所有项目。"
385
+ )
386
+ elif asset_build_id is None or global_id is None or not replica_inventory_complete:
387
+ detail += (
388
+ ";当前 asset、全局引擎或至少一个已发现副本缺少有效 Build ID/无法读取,"
389
+ "无法证明替换来源安全;不要运行 `bugx install --force`。"
390
+ "先核对上述路径、安装包来源与 Build ID,再按确认后的目标修复。"
391
+ )
392
+ else:
393
+ newer_replicas = [
394
+ (name, build_id) for name, build_id in replica_build_ids
395
+ if name != "asset" and build_id > asset_build_id
396
+ ]
397
+ if newer_replicas:
398
+ newest_name, newest_id = max(newer_replicas, key=lambda item: item[1])
399
+ detail += (
400
+ f";已发现 {newest_name} build_id={newest_id} 高于当前 CLI 安装资源 "
401
+ f"build_id={asset_build_id};不要运行 `bugx install --force`,"
402
+ f"它会用较旧资源覆盖共享引擎。请先改用或升级到安装资源 build_id >= {newest_id} 的 CLI。"
403
+ )
404
+ elif asset_build_id == global_id:
405
+ detail += (
406
+ f";当前 CLI 安装资源与共享全局引擎均为 build_id={global_id},"
407
+ "同号不能证明逐文件内容可安全替换;不要运行 `bugx install --force`。"
408
+ "该命令只重建共享引擎,不会同步 user-site/cli-prefix 等独立副本;"
409
+ "请按上列路径与 Build ID 逐项处理冲突副本。"
410
+ )
411
+ else:
412
+ detail += (
413
+ f";当前 CLI 安装资源 build_id={asset_build_id} 严格高于共享全局引擎 "
414
+ f"build_id={global_id},且不低于所有已发现副本;如需重建共享引擎,"
415
+ "可运行 `bugx install --force`。该命令不会同步较旧的 user-site/cli-prefix 副本。"
416
+ )
417
+ return False, detail
418
+ return True, ";".join(replica_details) + f";receipt engine_build_id={receipt_id}"
419
+
420
+
421
+ def _bugx_cli_paths() -> list[Path]:
422
+ """Find every BugX console entry visible through PATH, one per directory.
423
+
424
+ npm publishes several shim spellings (``bugx``/``bugx.cmd``/``bugx.ps1``)
425
+ side by side in the same global bin directory. Those are one install
426
+ source, not an overwrite conflict, so they are collapsed to a single
427
+ representative; only entries resolving into different directories are
428
+ reported as distinct sources.
429
+
430
+ pyenv also introduces shims (``~/.pyenv/shims/bugx``) that proxy execution
431
+ to the active pyenv Python installation (e.g. ``~/.pyenv/versions/.../bin/bugx``).
432
+ When both the shim and the resolved pyenv executable are present, they are
433
+ collapsed to a single pyenv source rather than reported as conflicting installations.
434
+ """
435
+ names = ("bugx", "bugx.exe", "bugx.cmd", "bugx.bat") if os.name == "nt" else ("bugx",)
436
+ found: list[Path] = []
437
+ found_dirs: set[str] = set()
438
+ for raw_entry in os.environ.get("PATH", "").split(os.pathsep):
439
+ entry = Path(raw_entry or os.curdir)
440
+ for name in names:
441
+ candidate = (entry / name).resolve()
442
+ if not candidate.is_file():
443
+ continue
444
+ if candidate.parent.name == "shims" and (
445
+ ".pyenv" in str(candidate) or candidate.parent.parent.name == ".pyenv"
446
+ ):
447
+ try:
448
+ res = subprocess.run(
449
+ ["pyenv", "which", candidate.name],
450
+ capture_output=True,
451
+ text=True,
452
+ timeout=1.0,
453
+ )
454
+ if res.returncode == 0 and res.stdout.strip():
455
+ target = Path(res.stdout.strip()).resolve()
456
+ if target.is_file():
457
+ candidate = target
458
+ except (subprocess.SubprocessError, OSError):
459
+ pass
460
+ directory = os.path.normcase(str(candidate.parent.resolve()))
461
+ if directory in found_dirs:
462
+ continue
463
+ if ".pyenv" in directory and any(".pyenv" in d for d in found_dirs):
464
+ continue
465
+ found_dirs.add(directory)
466
+ found.append(candidate)
467
+ return found
468
+
469
+
470
+ def _inspect_cli_entry(path: Path) -> dict[str, Any]:
471
+ """Classify a BugX executable path and sample its version."""
472
+ path_str = str(path)
473
+ source_type = "python"
474
+ if "node_modules" in path_str or ".nvm" in path_str:
475
+ source_type = "npm"
476
+ elif path.is_file():
477
+ try:
478
+ head = path.read_bytes()[:256]
479
+ if b"node" in head or b"bugx.js" in head:
480
+ source_type = "npm"
481
+ elif b"uv" in head or "uv/tools" in path_str:
482
+ source_type = "uv"
483
+ except OSError:
484
+ pass
485
+
486
+ if source_type != "npm":
487
+ if "uv/tools" in path_str or ".local/share/uv" in path_str:
488
+ source_type = "uv"
489
+ elif "pyenv" in path_str:
490
+ source_type = "pyenv"
491
+ elif "pip" in path_str or "site-packages" in path_str:
492
+ source_type = "pip"
493
+
494
+ version: str | None = None
495
+ try:
496
+ proc = subprocess.run(
497
+ [str(path), "--version"],
498
+ capture_output=True,
499
+ text=True,
500
+ timeout=1.5,
501
+ )
502
+ if proc.returncode == 0:
503
+ out = proc.stdout.strip()
504
+ parts = out.split()
505
+ if len(parts) >= 2 and parts[0] in ("bugx", "bugx-agent"):
506
+ version = parts[1]
507
+ elif parts:
508
+ version = parts[-1]
509
+ except (subprocess.SubprocessError, OSError):
510
+ pass
511
+
512
+ return {
513
+ "path": path,
514
+ "type": source_type,
515
+ "version": version,
516
+ }
517
+
518
+
519
+ def _doctor_atomic_replace(target: Path, payload: bytes, *, mode: int | None = None) -> None:
520
+ """Replace a regular project file atomically without following a target symlink."""
521
+ if target.is_symlink():
522
+ raise OSError(f"拒绝修复软链接目标:{target}")
523
+ target.parent.mkdir(parents=True, exist_ok=True)
524
+ descriptor, temporary = tempfile.mkstemp(
525
+ dir=str(target.parent), prefix=f".{target.name}.", suffix=".tmp",
526
+ )
527
+ try:
528
+ with os.fdopen(descriptor, "wb") as handle:
529
+ handle.write(payload)
530
+ if mode is not None:
531
+ os.chmod(temporary, mode)
532
+ os.replace(temporary, target)
533
+ except BaseException:
534
+ try:
535
+ os.unlink(temporary)
536
+ except OSError:
537
+ pass
538
+ raise
539
+
540
+
541
+ def _doctor_repair_assets(root: Path, layout: Any) -> list[str]:
542
+ """修复损坏或缺失的运行态、覆盖清单与调度状态。"""
543
+ actions: list[str] = []
544
+ if layout is None:
545
+ return actions
546
+ def failed(step: str, exc: BaseException) -> None:
547
+ actions.append(f"ERROR: {step}失败:{exc}")
548
+
549
+ try:
550
+ runtime_path = layout.runtime
551
+ if runtime_path.is_symlink():
552
+ raise OSError(f"拒绝修复软链接目标:{runtime_path}")
553
+ bak_path = runtime_path.with_name(runtime_path.name + ".bak")
554
+ need_repair = False
555
+ if runtime_path.is_file() and not runtime_path.is_symlink():
556
+ try:
557
+ content = runtime_path.read_text(encoding="utf-8").strip()
558
+ if not content:
559
+ need_repair = True
560
+ else:
561
+ json.loads(content)
562
+ except (json.JSONDecodeError, OSError):
563
+ need_repair = True
564
+ elif runtime_path.is_symlink() or bak_path.is_file():
565
+ need_repair = True
566
+
567
+ if need_repair:
568
+ restored = False
569
+ if bak_path.is_file() and not bak_path.is_symlink():
570
+ try:
571
+ bak_data = json.loads(bak_path.read_text(encoding="utf-8").strip())
572
+ if isinstance(bak_data, dict):
573
+ _doctor_atomic_replace(
574
+ runtime_path, bak_path.read_bytes(),
575
+ mode=bak_path.stat().st_mode & 0o777,
576
+ )
577
+ actions.append("runtime.json 从 .bak 恢复")
578
+ restored = True
579
+ except Exception as exc:
580
+ failed("runtime.json 备份恢复", exc)
581
+ if not restored:
582
+ if not any(item.startswith("ERROR: runtime.json 备份恢复") for item in actions):
583
+ actions.append("ERROR: runtime.json 损坏且无有效 .bak,拒绝重建;请从可信备份恢复")
584
+ except Exception as exc:
585
+ failed("runtime.json 修复", exc)
586
+
587
+ try:
588
+ project_file = root / ".bugx-project.json"
589
+ if project_file.is_symlink():
590
+ raise OSError(f"拒绝修复软链接目标:{project_file}")
591
+ if not project_file.is_file():
592
+ onboarding_file = root / ".bugx" / "cloud-onboard.json"
593
+ if onboarding_file.is_file():
594
+ try:
595
+ ob = json.loads(onboarding_file.read_text(encoding="utf-8"))
596
+ if isinstance(ob, dict) and ob.get("state") == "done":
597
+ import uuid
598
+ proj_id = f"proj-{uuid.uuid4().hex[:12]}"
599
+ payload = {
600
+ "project_id": proj_id,
601
+ "slug": root.name,
602
+ "created_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
603
+ }
604
+ _doctor_atomic_replace(
605
+ project_file,
606
+ json.dumps(payload, indent=2, ensure_ascii=False).encode("utf-8"),
607
+ )
608
+ actions.append("已自动补齐缺失的项目身份文件 .bugx-project.json")
609
+ except Exception as exc:
610
+ failed("项目身份文件修复", exc)
611
+ except Exception as exc:
612
+ failed("项目身份文件修复", exc)
613
+
614
+ try:
615
+ sup_state = layout.supervisor
616
+ if sup_state.is_symlink():
617
+ raise OSError(f"拒绝修复软链接目标:{sup_state}")
618
+ if sup_state.is_file():
619
+ try:
620
+ json.loads(sup_state.read_text(encoding="utf-8"))
621
+ except (json.JSONDecodeError, OSError):
622
+ corrupted = sup_state.parent / f"{sup_state.name}.corrupted.{int(time.time())}"
623
+ os.replace(sup_state, corrupted)
624
+ bak = sup_state.with_name(sup_state.name + ".bak")
625
+ if bak.is_file():
626
+ try:
627
+ bak_data = json.loads(bak.read_text(encoding="utf-8"))
628
+ if not isinstance(bak_data, dict):
629
+ raise ValueError("备份内容不是 JSON 对象")
630
+ _doctor_atomic_replace(
631
+ sup_state, bak.read_bytes(), mode=bak.stat().st_mode & 0o777,
632
+ )
633
+ actions.append("audit-supervisor.json 从 .bak 恢复")
634
+ except Exception as exc:
635
+ failed("audit-supervisor.json 备份恢复", exc)
636
+ else:
637
+ actions.append("ERROR: audit-supervisor.json 损坏且无 .bak,拒绝重建")
638
+ except Exception as exc:
639
+ failed("audit-supervisor.json 修复", exc)
640
+
641
+ try:
642
+ repaired_links = _ensure_global_cli_symlinks()
643
+ for link, status in repaired_links:
644
+ if status == "created":
645
+ actions.append(f"已创建全局 CLI 软链接:{link}")
646
+ except Exception as exc:
647
+ failed("全局 CLI 软链接修复", exc)
648
+
649
+ try:
650
+ from .lifecycle import _ensure_project_startup_todo
651
+ startup_todo = root / ".bugx" / "startup-todo.md"
652
+ if startup_todo.is_symlink():
653
+ raise OSError(f"拒绝修复软链接目标:{startup_todo}")
654
+ if not startup_todo.is_file():
655
+ _ensure_project_startup_todo(root)
656
+ actions.append("已重新生成 .bugx/startup-todo.md")
657
+ except Exception as exc:
658
+ failed("startup-todo.md 修复", exc)
659
+ return actions
660
+
661
+
662
+ def _check_nested_worktrees_hygiene(root: Path) -> tuple[bool, str]:
663
+ """检查 Git 注册的、位于项目根目录内的 linked worktree。"""
664
+ git_dir = root / ".git"
665
+ if not git_dir.exists():
666
+ return True, "非 Git 仓库"
667
+
668
+ try:
669
+ result = subprocess.run(
670
+ ["git", "worktree", "list", "--porcelain"],
671
+ cwd=str(root), capture_output=True, text=True, check=False, timeout=2,
672
+ )
673
+ except (OSError, subprocess.SubprocessError) as exc:
674
+ return False, f"无法读取 Git linked worktree:{exc}"
675
+ if result.returncode != 0:
676
+ detail = (result.stderr or result.stdout).strip() or "未知 Git 错误"
677
+ return False, f"无法读取 Git linked worktree:{detail}"
678
+
679
+ # `git worktree list --porcelain` emits one `worktree <path>` line per
680
+ # registered worktree. The first entry is the current checkout itself;
681
+ # only linked worktrees nested below root can pollute this repository.
682
+ nested_worktrees: list[Path] = []
683
+ for line in result.stdout.splitlines():
684
+ if not line.startswith("worktree "):
685
+ continue
686
+ candidate = Path(line.removeprefix("worktree ").strip()).expanduser()
687
+ try:
688
+ resolved = candidate.resolve()
689
+ resolved.relative_to(root.resolve())
690
+ except (OSError, ValueError):
691
+ continue
692
+ if resolved != root.resolve():
693
+ nested_worktrees.append(resolved)
694
+
695
+ if nested_worktrees:
696
+ unignored: list[str] = []
697
+ for wt in nested_worktrees:
698
+ rel = wt.relative_to(root.resolve())
699
+ try:
700
+ res = subprocess.run(
701
+ ["git", "check-ignore", "-q", "--", str(rel)],
702
+ cwd=str(root),
703
+ capture_output=True,
704
+ timeout=2,
705
+ )
706
+ if res.returncode != 0:
707
+ unignored.append(str(rel))
708
+ except Exception:
709
+ unignored.append(str(rel))
710
+ if unignored:
711
+ return False, f"发现未被 .gitignore 忽略的嵌套 worktree({', '.join(unignored)}),极易污染索引,建议加入 .gitignore 或移出仓库"
712
+ return True, "工作树隔离正常(无未忽略嵌套 worktree)"
713
+
714
+
715
+
716
+ def _host_runtime_gate(
717
+ host_checks: list[tuple[str, bool, str]],
718
+ installed_host_names: list[str] | set[str],
719
+ detected_hosts: dict[str, dict[str, object]],
720
+ ) -> bool:
721
+ """Decide whether every recorded host is runtime-ready.
722
+
723
+ ``installed_host_names`` comes from ``.bugx/hosts.json`` (BugX wiring was
724
+ installed); ``detected_hosts`` comes from live discovery, where
725
+ ``installed`` means "the host CLI is on PATH" and ``project_marker`` means
726
+ "the project-level wiring exists". Those are different facts (P3f: the dsh
727
+ adapter deliberately decouples marker from CLI presence), so a host whose
728
+ CLI is missing from PATH but whose complete bundle is wired into the project
729
+ must not flip ``runtime_ready`` to False — that produced the contradictory
730
+ "44 checks green, runtime_ready=false" report.
731
+ """
732
+ if not installed_host_names:
733
+ return True
734
+ ready = True
735
+ for name in installed_host_names:
736
+ try:
737
+ adapter = get_adapter(name)
738
+ except ValueError:
739
+ ready = False
740
+ continue
741
+ bundle_ok = any(
742
+ item[0] == f"{adapter.label} 完整适配包" and item[1]
743
+ for item in host_checks
744
+ )
745
+ detected = detected_hosts.get(name, {})
746
+ usable = bool(detected.get("installed") or detected.get("project_marker"))
747
+ ready = ready and bundle_ok and usable
748
+ return ready
749
+
750
+
751
+ def _doctor_auto_repairable_checks(
752
+ checks: list[tuple[str, bool, str]],
753
+ *,
754
+ repair_requested: bool,
755
+ installation_only: bool,
756
+ ) -> set[str]:
757
+ """Return only checks with a concrete, currently available Doctor repair path.
758
+
759
+ ``doctor --repair`` has already attempted its repairs before diagnostics are
760
+ rendered, so remaining failures must not be offered the same repair again.
761
+ Host bundle replacement is deliberately excluded because it used to force
762
+ rewrite project-owned files without preserving local edits.
763
+ """
764
+ if repair_requested:
765
+ return set()
766
+
767
+ failed = {name for name, ok, _detail in checks if not ok}
768
+ eligible: set[str] = set()
769
+ if not installation_only and "Tree-sitter 多语言增强" in failed:
770
+ eligible.add("Tree-sitter 多语言增强")
771
+
772
+ engine_checks = failed & {"全局引擎完整性", "BugX 版本一致性"}
773
+ if engine_checks:
774
+ try:
775
+ can_replace, _detail = _asset_can_replace_global_engine()
776
+ except (CliError, OSError, ValueError):
777
+ can_replace = False
778
+ if can_replace:
779
+ eligible.update(engine_checks)
780
+ return eligible
781
+
782
+
783
+ def _generate_ai_diagnostics(
784
+ checks: list[tuple[str, bool, str]],
785
+ installation_required: set[str],
786
+ root: Path,
787
+ strict: bool = False,
788
+ auto_repairable_checks: set[str] | None = None,
789
+ ) -> dict[str, Any]:
790
+ """基于失败项生成 AI 根因分析和本地确定性修复提示。"""
791
+ from ..infra.ai_advisor import DiagnosticAIArbitrator
792
+ arbitrator = DiagnosticAIArbitrator(root)
793
+ result = arbitrator.diagnose(
794
+ checks,
795
+ installation_required,
796
+ strict=strict,
797
+ auto_repairable_checks=auto_repairable_checks,
798
+ )
799
+ return result.as_dict()
800
+
801
+
802
+ def _render_ai_diagnostics_panel(ai_diag: dict[str, Any], is_explicit_ai: bool = False) -> None:
803
+ items = ai_diag.get("items", [])
804
+ if items:
805
+ print("\n╭── 🤖 BugX AI 根因分析与确定性修复提示 ─────────────────────────────────╮")
806
+ print(f"│ {ai_diag.get('summary', '')}")
807
+ print("│")
808
+ for idx, item in enumerate(items, 1):
809
+ req_badge = "[必需]" if item.get("required") else "[可选]"
810
+ repair_badge = " (可由 doctor --repair 尝试修复)" if item.get("auto_repairable") else ""
811
+ print(f"│ {idx}. {req_badge} 【{item['name']}】{repair_badge}")
812
+ print(f"│ • 根因分析: {item['root_cause']}")
813
+ print(f"│ • 修复处方: {item['prescription']}")
814
+ if idx < len(items):
815
+ print("│")
816
+ if ai_diag.get("can_auto_repair"):
817
+ print("│")
818
+ print("│ Doctor 检测到可尝试的修复项;执行前请确认其影响范围:")
819
+ print(f"│ 👉 {ai_diag['auto_repair_command']}")
820
+ print("╰───────────────────────────────────────────────────────────────────────╯")
821
+ elif is_explicit_ai:
822
+ print("\n╭── 🤖 BugX AI 智能排障分析 ──────────────────────────────────────────╮")
823
+ print(f"│ {ai_diag.get('summary', '')}")
824
+ print("╰───────────────────────────────────────────────────────────────────────╯")
825
+
826
+
827
+ def command_doctor(args: argparse.Namespace) -> int:
828
+ from .agent import _check_host_mcp_config
829
+ from .lifecycle import _global_opencode_integrity_check, _global_pi_integrity_check
830
+ from .agent import _CliProgress
831
+
832
+ progress = _CliProgress(args)
833
+ progress.update(0, "准备诊断")
834
+ root = args.root.resolve()
835
+ if getattr(args, "target", "all") == "mcp-runtime":
836
+ progress.update(20, "正在诊断 MCP runtime")
837
+ runtime_root = default_mcp_runtime_root()
838
+ code, payload = _mcp_runtime_doctor_payload(root, runtime_root)
839
+ progress.finish("MCP runtime 诊断完成")
840
+ if args.json:
841
+ print(json.dumps(payload, ensure_ascii=False, indent=2))
842
+ else:
843
+ print(f"BugX {get_full_version()} · MCP 离线 runtime 诊断")
844
+ for item in payload.get("checks", []):
845
+ marker = "✓" if item["ok"] else "!"
846
+ print(f" {marker} {item['name']}: {item['detail']}")
847
+ for issue in payload.get("issues", []):
848
+ print(f" ! 不一致:{issue}")
849
+ return code
850
+ checks = []
851
+ checks.append(("Python >= 3.11", sys.version_info >= (3, 11), sys.version.split()[0]))
852
+ try:
853
+ assets = asset_root()
854
+ checks.append(("安装资源", True, str(assets)))
855
+ except CliError as exc:
856
+ checks.append(("安装资源", False, str(exc)))
857
+ manifest_ok = (root / ".bugx" / "manifest.json").is_file()
858
+ layout = None
859
+ layout_error = None
860
+ repair_actions: list[str] = []
861
+ init_issues: list[str] = []
862
+
863
+ if manifest_ok:
864
+ try:
865
+ layout_module = _layout_module(root)
866
+ if args.repair:
867
+ layout = layout_module.repair(root)
868
+ repair_actions = _doctor_repair_assets(root, layout)
869
+ else:
870
+ layout = layout_module.require(root)
871
+ except (CliError, OSError, ValueError, RuntimeError) as exc:
872
+ layout_error = str(exc)
873
+
874
+ if not getattr(args, "installation_only", False):
875
+ onboarding_file = root / ".bugx" / "cloud-onboard.json"
876
+ if not onboarding_file.is_file():
877
+ init_issues.append("缺少云端 onboarding 记录(.bugx/cloud-onboard.json)")
878
+ else:
879
+ try:
880
+ ob_data = json.loads(onboarding_file.read_text(encoding="utf-8"))
881
+ ob_state = ob_data.get("state") if isinstance(ob_data, dict) else None
882
+ if ob_state not in ("done", "local", "sync"):
883
+ init_issues.append(f"云端 onboarding 未决(状态: {ob_state})")
884
+ elif ob_state in ("done", "sync"):
885
+ project_file = root / ".bugx-project.json"
886
+ if not project_file.is_file():
887
+ init_issues.append("开启了云端同步但缺少项目身份文件(.bugx-project.json)")
888
+ except Exception as exc:
889
+ init_issues.append(f"云端 onboarding 记录损坏: {exc}")
890
+
891
+ startup_todo = root / ".bugx" / "startup-todo.md"
892
+ if not startup_todo.is_file():
893
+ init_issues.append("缺少启动视图(.bugx/startup-todo.md)")
894
+ else:
895
+ init_issues.append("缺少 .bugx/manifest.json")
896
+
897
+ if layout_error:
898
+ init_issues.insert(0, f".bugx 项目布局校验失败: {layout_error}")
899
+
900
+ initialized = manifest_ok and layout is not None and not init_issues
901
+ status_guidance = (
902
+ "先只读运行 `bugx engine --root <ROOT> status --json`;"
903
+ "只有状态精确为 `UNINITIALIZED` 时才运行 `bugx engine --root <ROOT> pre`。"
904
+ "返回 `FATAL_BLOCKED`、其他状态或检查失败时保留现场并停止;"
905
+ "不得用 `bugx init`、`bugx reset` 或 `--force` 绕过。"
906
+ )
907
+ if initialized:
908
+ init_detail = str(root / ".bugx")
909
+ elif not manifest_ok:
910
+ init_detail = f"项目状态未判定(缺少 .bugx/manifest.json)。{status_guidance}"
911
+ else:
912
+ init_detail = f"初始化未就绪({';'.join(init_issues)})。{status_guidance}"
913
+
914
+ checks.append(("项目初始化状态", initialized, init_detail))
915
+ 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
+ raw_requested_hosts = []
931
+ for item in getattr(args, "agent", []):
932
+ for sub in str(item).split(","):
933
+ sub = sub.strip()
934
+ if sub:
935
+ raw_requested_hosts.append(sub)
936
+ target_hosts = set(raw_requested_hosts) if raw_requested_hosts else None
937
+
938
+ progress.update(25, "项目和宿主检查完成")
939
+ host_checks, installed_host_names = _host_bundle_checks(root, target_hosts=target_hosts)
940
+ if target_hosts:
941
+ installed_host_names = installed_host_names | target_hosts
942
+ host_registry_fallback = any(
943
+ name == "宿主安装清单缺失或损坏" for name, _, _ in host_checks
944
+ )
945
+ host_checks = [
946
+ (
947
+ name,
948
+ ok,
949
+ detail + (
950
+ ";Doctor 不会强制重装整套宿主资产,以免覆盖项目内本地修改;"
951
+ "先检查并保存目标文件,再对单个宿主执行 `bugx install --root <ROOT> --agent <HOST>`。"
952
+ ) if not ok and name.endswith("完整适配包") else detail,
953
+ )
954
+ for name, ok, detail in host_checks
955
+ ]
956
+ checks.extend(host_checks)
957
+ try:
958
+ engine_ok, engine_detail = _engine_integrity_status(
959
+ asset_root(), global_engine_root(),
960
+ )
961
+ except (CliError, OSError, ValueError) as exc:
962
+ engine_ok, engine_detail = False, f"全局引擎无法校验:{exc}"
963
+ if not engine_ok and getattr(args, "repair", False):
964
+ can_replace, guard_detail = _asset_can_replace_global_engine()
965
+ if not can_replace:
966
+ engine_detail = guard_detail
967
+ else:
968
+ try:
969
+ _install_engine(asset_root(), force=True)
970
+ engine_ok, engine_detail = _engine_integrity_status(
971
+ asset_root(), global_engine_root(),
972
+ )
973
+ engine_detail += "(已自动修复恢复完整性)"
974
+ except Exception as exc:
975
+ engine_detail = f"自动修复全局引擎失败:{exc}"
976
+ 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}"
983
+ # 项目 manifest 只存语义版本;它的基础版本自愈必须独立于完整 Build ID 比对。
984
+ if version_ok and getattr(args, "repair", False):
985
+ healed = _heal_project_manifest_version(root)
986
+ if healed is not None:
987
+ version_detail += f"(已就地对齐项目清单版本 {healed[0]} → {healed[1]})"
988
+ if not version_ok and getattr(args, "repair", False):
989
+ can_replace, guard_detail = _asset_can_replace_global_engine()
990
+ if not can_replace:
991
+ version_detail = guard_detail
992
+ else:
993
+ try:
994
+ _install_engine(asset_root(), force=True)
995
+ _heal_project_manifest_version(root, force=True)
996
+ version_ok, version_detail = _version_contract_status(
997
+ root, global_engine_root(),
998
+ )
999
+ version_detail += "(已自动刷新全局引擎与项目清单;旧项目入口会在 init/install 时直接删除)"
1000
+ except Exception as exc:
1001
+ version_detail = f"自动对齐版本失败:{exc}"
1002
+ checks.append(("BugX 版本一致性", version_ok, version_detail))
1003
+ replicas_ok, replicas_detail = _engine_replica_consistency_check()
1004
+ checks.append(("引擎副本一致性", replicas_ok, replicas_detail))
1005
+ progress.update(45, "引擎和版本检查完成")
1006
+ if "opencode" in installed_host_names and (target_hosts is None or "opencode" in target_hosts):
1007
+ checks.append(("OpenCode 全局入口完整性", *_global_opencode_integrity_check()))
1008
+ 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)}
1011
+ for host_name in sorted(installed_host_names):
1012
+ if target_hosts is not None and host_name not in target_hosts:
1013
+ continue
1014
+ if host_name not in {adapter.name for adapter in HOST_ADAPTERS}:
1015
+ # hosts.json 可能由更新版本的 CLI 写入(降级/前向兼容场景)。
1016
+ # doctor 必须结构化报告未知宿主,禁止以未处理异常崩溃。
1017
+ checks.append((
1018
+ f"{host_name} MCP 配置", False,
1019
+ "当前 CLI 不识别该宿主(可能由更新版本的 BugX 安装);请升级 CLI 后重试",
1020
+ ))
1021
+ continue
1022
+ ok, detail = _check_host_mcp_config(
1023
+ root, host_name,
1024
+ repair=getattr(args, "repair", False) and not host_registry_fallback,
1025
+ )
1026
+ adapter = get_adapter(host_name)
1027
+ checks.append((f"{adapter.label} MCP 配置", ok, detail))
1028
+ is_installation_only = bool(getattr(args, "installation_only", False))
1029
+ if is_installation_only:
1030
+ lesson_ready = True
1031
+ checks.append(("错题集账本", True, "跳过运行态检查(--installation-only)"))
1032
+ if layout is not None:
1033
+ checks.append(("全局错题集(可选)", True, "跳过运行态检查(--installation-only)"))
1034
+ 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]'"))
1036
+ checks.append(("codebase-memory 推荐加速", True, "跳过运行态检查(--installation-only)"))
1037
+ checks.append(("基础效率工具", True, "跳过运行态检查(--installation-only)"))
1038
+ mcp_runtime_ok, mcp_runtime_detail = _mcp_runtime_check(root)
1039
+ checks.append(("MCP 离线 runtime", mcp_runtime_ok, mcp_runtime_detail))
1040
+ progress.update(80, "运行态检查已跳过")
1041
+ checks.append(("UI 视觉与浏览器挖掘环境(可选)", True, "跳过运行态检查(--installation-only)"))
1042
+ else:
1043
+ 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}"
1066
+ checks.append(("错题集账本", lesson_ready, lesson_detail))
1067
+ 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 重建"
1074
+ 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}"
1088
+ checks.append(("全局错题集(可选)", global_ok, global_detail))
1089
+ graph = importlib.util.find_spec("tree_sitter_language_pack") is not None
1090
+ if not graph and getattr(args, "repair", False):
1091
+ # 只有在明确指定 --repair 时才尝试自动安装,普通诊断快速探测不挂起
1092
+ try:
1093
+ proc = subprocess.run(
1094
+ [sys.executable, "-m", "pip", "install", "tree-sitter-language-pack>=1.14.3", "--no-warn-script-location"],
1095
+ capture_output=True, text=True, timeout=15, check=False,
1096
+ )
1097
+ if proc.returncode == 0:
1098
+ importlib.invalidate_caches()
1099
+ graph = importlib.util.find_spec("tree_sitter_language_pack") is not None
1100
+ except Exception:
1101
+ pass
1102
+ graph_detail = "已就绪" if graph else "可选:缺失(执行 bugx doctor --repair 或 pip install 'bugx-agent[graph]' 启用)"
1103
+ 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}"
1129
+ 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}"
1162
+ checks.append(("基础效率工具", efficiency_ok, efficiency_detail))
1163
+ mcp_runtime_ok, mcp_runtime_detail = _mcp_runtime_check(root)
1164
+ checks.append(("MCP 离线 runtime", mcp_runtime_ok, mcp_runtime_detail))
1165
+ # 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)
1175
+ checks.append(("MCP 会话进程卫生", mcp_hygiene_ok, mcp_hygiene_detail))
1176
+ progress.update(80, "运行态检查完成")
1177
+ # 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])
1233
+ else:
1234
+ cli_detail = "PATH 中未发现 bugx 入口"
1235
+ checks.append(("BugX CLI 路径", len(cli_paths) <= 1, cli_detail))
1236
+ installation_required = {
1237
+ "Python >= 3.11", "安装资源", "全局引擎完整性",
1238
+ "BugX 版本一致性",
1239
+ "引擎副本一致性",
1240
+ }
1241
+ # F-L0-01 整改:``--installation-only`` 是「安装体检」,不得因为目标目录
1242
+ # 尚未初始化(没有 .bugx/manifest.json)而判定安装失败——安装完整性与
1243
+ # 项目状态是两个独立维度。但**已存在项目**(manifest 已落盘)却状态损坏
1244
+ # 时必须继续 fail-closed(DOC-227 半初始化拒绝放行),因此仅在
1245
+ # 「manifest 存在」或「非 installation-only 模式」时才把项目初始化状态
1246
+ # 计入必需项。
1247
+ if manifest_ok or not args.installation_only:
1248
+ installation_required.add("项目初始化状态")
1249
+ strict = bool(getattr(args, "strict", False))
1250
+ if strict:
1251
+ installation_required.add("工作树卫生与嵌套隔离")
1252
+ installation_required.add(_CLOUD_ENDPOINT_CHECK_NAME)
1253
+ if args.repair:
1254
+ installation_required.add("项目资产修复")
1255
+ installation_required.update(name for name, _, _ in host_checks)
1256
+ if "opencode" in installed_host_names:
1257
+ installation_required.update({"OpenCode MCP 配置", "OpenCode 全局入口完整性"})
1258
+ if "pi" in installed_host_names:
1259
+ installation_required.add("Pi 全局 Skill 完整性")
1260
+ installation_ready = all(
1261
+ ok for name, ok, detail in checks if name in installation_required
1262
+ )
1263
+ if installed_host_names:
1264
+ host_runtime_ready = _host_runtime_gate(
1265
+ host_checks, installed_host_names, detected_hosts,
1266
+ )
1267
+ runtime_ready = installation_ready and lesson_ready and host_runtime_ready
1268
+ else:
1269
+ # BugX core is host-neutral. With no host selected, doctor validates
1270
+ # the core and knowledge stores only; an AI host may be installed later.
1271
+ runtime_ready = installation_ready and lesson_ready
1272
+ if (default_mcp_runtime_root()).exists():
1273
+ # 已安装过 runtime 时才参与就绪门禁;未安装只是可选项,不阻断。
1274
+ runtime_ready = runtime_ready and mcp_runtime_ok
1275
+ # 可选项(Tree-sitter、codebase-memory、效率工具、UI 环境等)失败只降级,
1276
+ # 不再把退出码拖到 1;只有 --strict 时才把它们计入。
1277
+ optional_degraded = [
1278
+ name for name, ok, _detail in checks
1279
+ if not ok and name not in installation_required
1280
+ ]
1281
+ if args.installation_only:
1282
+ ready = installation_ready
1283
+ else:
1284
+ ready = runtime_ready if strict else installation_ready
1285
+ failed_required = [
1286
+ {"name": name, "detail": detail}
1287
+ for name, ok, detail in checks
1288
+ if not ok and name in installation_required
1289
+ ]
1290
+ auto_repairable_checks = _doctor_auto_repairable_checks(
1291
+ checks,
1292
+ repair_requested=bool(getattr(args, "repair", False)),
1293
+ installation_only=is_installation_only,
1294
+ )
1295
+ ai_diag = _generate_ai_diagnostics(
1296
+ checks,
1297
+ installation_required,
1298
+ root,
1299
+ strict=strict,
1300
+ auto_repairable_checks=auto_repairable_checks,
1301
+ )
1302
+ escalation = None
1303
+ if not ready:
1304
+ escalation = {
1305
+ "required": True,
1306
+ "failed_checks": failed_required,
1307
+ "suggested_llm_action": "diagnose_environment_failure",
1308
+ "message": "程序级检查未完全通过,已生成 AI 智能诊断分析与自愈处方",
1309
+ "ai_prescriptions": [
1310
+ {
1311
+ "name": item["name"],
1312
+ "root_cause": item["root_cause"],
1313
+ "prescription": item["prescription"],
1314
+ "auto_repairable": item["auto_repairable"],
1315
+ }
1316
+ for item in ai_diag.get("items", [])
1317
+ if item.get("required")
1318
+ ],
1319
+ "auto_repair_command": ai_diag.get("auto_repair_command"),
1320
+ }
1321
+ payload = {
1322
+ "version": __version__, "root": str(root),
1323
+ "mode": "installation-only" if args.installation_only else "runtime",
1324
+ "installation_ready": installation_ready,
1325
+ "runtime_ready": runtime_ready,
1326
+ "optional_degraded": optional_degraded,
1327
+ "strict": strict,
1328
+ "ready": ready,
1329
+ "escalation": escalation,
1330
+ "ai_diagnostics": ai_diag,
1331
+ "checks": [{"name": name, "ok": ok, "detail": detail} for name, ok, detail in checks],
1332
+ }
1333
+ progress.finish("诊断完成")
1334
+ if args.json:
1335
+ print(json.dumps(payload, ensure_ascii=False, indent=2))
1336
+ else:
1337
+ print(f"BugX {get_full_version()}")
1338
+ for name, ok, detail in checks:
1339
+ optional_miss = (not ok) and name not in installation_required
1340
+ marker = "✓" if ok else ("△" if optional_miss else "!")
1341
+ suffix = "(可选增强缺失,不影响退出码)" if optional_miss and not strict else ""
1342
+ print(f" {marker} {name}: {detail}{suffix}")
1343
+ if getattr(args, "ai", False) or not payload["ready"] or (strict and optional_degraded):
1344
+ _render_ai_diagnostics_panel(ai_diag, is_explicit_ai=bool(getattr(args, "ai", False)))
1345
+ return 0 if payload["ready"] else 1