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,721 @@
1
+ #!/usr/bin/env python3
2
+ """src/bugx_cli/infra/ai_advisor.py - AI 辅助意图理解、智能排障与确定性自愈协同引擎。
3
+
4
+ 设计原则:
5
+ - AI 负责:理解非结构化报错、补充根因分析与语义模糊匹配;
6
+ - 程序负责:选择已实现的修复路径、原子操作执行、文件沙箱隔离与确定性验活门禁;
7
+ - 双轨协同:在线/宿主可用时唤起宿主 AI 动态推断,离线/受限环境平滑退守本地确定性专家基线。
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import difflib
13
+ import errno
14
+ import json
15
+ import os
16
+ import re
17
+ import shutil
18
+ import subprocess
19
+ import sys
20
+ import time
21
+ from dataclasses import dataclass, field
22
+ from pathlib import Path
23
+ from typing import Any, Mapping
24
+
25
+ from .. import __version__
26
+
27
+
28
+ COMMAND_CAPABILITIES: dict[str, dict[str, Any]] = {
29
+ "init": {
30
+ "description": "初始化项目 BugX 核心环境与运行态",
31
+ "keywords": ["初始化", "建仓", "开始", "创建", "setup", "start", "initialize", "new"],
32
+ },
33
+ "doctor": {
34
+ "description": "环境健康度诊断、依赖检测与一键自愈",
35
+ "keywords": ["体检", "健康", "诊断", "排查", "修复", "自愈", "检查", "环境", "check", "fix", "health", "doctor"],
36
+ },
37
+ "hosts": {
38
+ "description": "发现系统中已安装的可接入 AI 宿主 Agent",
39
+ "keywords": ["宿主", "智能体", "接入", "agent", "hosts", "discover"],
40
+ },
41
+ "install": {
42
+ "description": "安装 BugX MCP / Skill 至已发现的 AI 宿主",
43
+ "keywords": ["安装", "集成", "配置宿主", "install", "setup", "integrate"],
44
+ },
45
+ "uninstall": {
46
+ "description": "从指定 AI 宿主卸载 BugX 集成",
47
+ "keywords": ["卸载", "清理", "移除", "uninstall", "remove"],
48
+ },
49
+ "audit": {
50
+ "description": "项目级漏洞渗透挖掘与代码安全审计",
51
+ "keywords": ["审计", "漏洞", "扫描", "找洞", "安全", "渗透", "audit", "scan", "security", "vulnerability"],
52
+ },
53
+ "autonomous": {
54
+ "description": "启动全自动无人值守 BugX 漏洞挖掘",
55
+ "keywords": ["自主", "无人值守", "自动挖掘", "挂机", "探索", "autonomous", "mine", "auto"],
56
+ },
57
+ "analyze": {
58
+ "description": "项目画像深度分析与代码覆盖度全景扫描",
59
+ "keywords": ["画像", "分析", "覆盖度", "项目全景", "技术栈", "analyze", "profile", "coverage"],
60
+ },
61
+ "project": {
62
+ "description": "项目元数据管理、画像展示与云端同步",
63
+ "keywords": ["项目", "元数据", "云同步", "project", "sync"],
64
+ },
65
+ "patch": {
66
+ "description": "补丁合成、验证、对抗与自动应用",
67
+ "keywords": ["补丁", "修复代码", "修bug", "合成", "patch", "repair-code"],
68
+ },
69
+ "skill": {
70
+ "description": "BugX 动态扩展 Skill 市场管理与挂载",
71
+ "keywords": ["技能", "插件", "skill", "plugins"],
72
+ },
73
+ "cloud": {
74
+ "description": "BugX 云端多设备协同、同步与设备认证",
75
+ "keywords": ["云端", "多设备", "同步", "协同", "cloud", "sync"],
76
+ },
77
+ "auth": {
78
+ "description": "云端登录、凭据管理与设备配对",
79
+ "keywords": ["登录", "认证", "token", "凭证", "auth", "login"],
80
+ },
81
+ "stats": {
82
+ "description": "代码漏洞挖掘统计指标与 ROI 分析",
83
+ "keywords": ["统计", "度量", "指标", "投入产出", "stats", "metrics"],
84
+ },
85
+ "report": {
86
+ "description": "本地 Web 控制台与审计报告预览",
87
+ "keywords": ["报告", "控制台", "预览", "看板", "report", "console", "dashboard", "web"],
88
+ },
89
+ "engine": {
90
+ "description": "全局引擎核心管理与状态查询",
91
+ "keywords": ["引擎", "核心", "版本", "engine", "core"],
92
+ },
93
+ "daemon": {
94
+ "description": "BugX 后台常驻守护进程管理",
95
+ "keywords": ["守护", "后台", "常驻", "daemon", "service"],
96
+ },
97
+ "reset": {
98
+ "description": "重置项目运行态或全局错题集缓存",
99
+ "keywords": ["重置", "清空", "还原", "reset", "clear"],
100
+ },
101
+ "help": {
102
+ "description": "查看 BugX 命令使用说明",
103
+ "keywords": ["帮助", "说明", "手册", "help", "usage"],
104
+ },
105
+ }
106
+
107
+
108
+ @dataclass
109
+ class IntentArbitrationResult:
110
+ matched_command: str | None
111
+ suggestions: list[tuple[str, str]]
112
+ source: str # "ai_dynamic", "heuristic_synonym", "fuzzy_match", "none"
113
+ reasoning: str = ""
114
+
115
+
116
+ class CommandIntentArbitrator:
117
+ """AI 与程序协同的命令意图理解与纠错仲裁器。"""
118
+
119
+ def __init__(self, root: Path | None = None) -> None:
120
+ self.root = (root or Path.cwd()).resolve()
121
+
122
+ def infer_intent(self, raw_input: str) -> IntentArbitrationResult:
123
+ cleaned = str(raw_input or "").strip()
124
+ if not cleaned:
125
+ return IntentArbitrationResult(None, [], "none", "输入为空")
126
+
127
+ # 1. 本地快速同义词与关键词精确初筛
128
+ low = cleaned.casefold()
129
+ for cmd, meta in COMMAND_CAPABILITIES.items():
130
+ if low == cmd or low in meta["keywords"]:
131
+ return IntentArbitrationResult(
132
+ matched_command=cmd,
133
+ suggestions=[(cmd, meta["description"])],
134
+ source="heuristic_synonym",
135
+ reasoning=f"输入精确匹配命令或同义词: '{cleaned}'",
136
+ )
137
+
138
+ # 2. 尝试调用宿主 AI 进行动态语义意图推断 (若当前处于在线宿主环境)
139
+ ai_result = self._try_ai_dynamic_inference(cleaned)
140
+ if ai_result:
141
+ return ai_result
142
+
143
+ # 3. 本地语义关键词多路打分启发式匹配
144
+ scored: dict[str, int] = {}
145
+ for cmd, meta in COMMAND_CAPABILITIES.items():
146
+ score = 0
147
+ for kw in meta["keywords"]:
148
+ kw_low = kw.casefold()
149
+ if len(kw_low) >= 2 and kw_low in low:
150
+ score += len(kw_low) * 10
151
+ if score > 0:
152
+ scored[cmd] = score
153
+
154
+ if scored:
155
+ ranked = sorted(scored.items(), key=lambda x: x[1], reverse=True)
156
+ top_cmd = ranked[0][0]
157
+ suggestions = [
158
+ (c, COMMAND_CAPABILITIES[c]["description"])
159
+ for c, _ in ranked[:2]
160
+ ]
161
+ return IntentArbitrationResult(
162
+ matched_command=top_cmd,
163
+ suggestions=suggestions,
164
+ source="heuristic_synonym",
165
+ reasoning=f"根据语义关键词匹配推荐: '{cleaned}'",
166
+ )
167
+
168
+ # 4. 兜底编辑距离模糊匹配 (difflib)
169
+ candidates = list(COMMAND_CAPABILITIES.keys())
170
+ close = difflib.get_close_matches(low, candidates, n=2, cutoff=0.35)
171
+ if close:
172
+ return IntentArbitrationResult(
173
+ matched_command=close[0],
174
+ suggestions=[(c, COMMAND_CAPABILITIES[c]["description"]) for c in close],
175
+ source="fuzzy_match",
176
+ reasoning=f"编辑距离近似推荐",
177
+ )
178
+
179
+ return IntentArbitrationResult(None, [], "none", "未匹配到有效意图")
180
+
181
+ def _try_ai_dynamic_inference(self, raw_input: str) -> IntentArbitrationResult | None:
182
+ """调用宿主 AI 理解复杂自然语言或未知拼写意图。"""
183
+ if os.environ.get("BUGX_OFFLINE") == "1" or os.environ.get("BUGX_INTENT_NO_LLM") == "1":
184
+ return None
185
+
186
+ active_host = ""
187
+ try:
188
+ from core.host_runtime import host_registry
189
+ active_host = host_registry.resolve_scout_host(self.root)
190
+ except Exception:
191
+ return None
192
+
193
+ if not active_host:
194
+ return None
195
+
196
+ try:
197
+ from core.host_runtime import host_registry
198
+
199
+ prompt_payload = {
200
+ "user_input": raw_input,
201
+ "supported_commands": {k: v["description"] for k, v in COMMAND_CAPABILITIES.items()},
202
+ }
203
+ prompt_content = (
204
+ "<system_rules>\n"
205
+ "You are the BugX CLI Intent Parser.\n"
206
+ "Understand user's input (Chinese or English, possibly with typos or natural language) and map to the most accurate BugX command.\n"
207
+ "Output STRICTLY a JSON object with this exact schema (no markdown, no other text):\n"
208
+ "{\n"
209
+ ' "matched_command": "one of supported_commands or null",\n'
210
+ ' "confidence": "high|medium|low",\n'
211
+ ' "reasoning": "brief explanation in Chinese"\n'
212
+ "}\n"
213
+ "</system_rules>\n"
214
+ "<context>\n"
215
+ f"{json.dumps(prompt_payload, ensure_ascii=False, indent=2)}\n"
216
+ "</context>\n"
217
+ )
218
+
219
+ tmp_prompt = self.root / ".bugx" / "run" / "intent_prompt.txt"
220
+ tmp_prompt.parent.mkdir(parents=True, exist_ok=True)
221
+ tmp_prompt.write_text(prompt_content, encoding="utf-8")
222
+
223
+ cmd = host_registry.build_recon_scout_command(active_host, self.root, tmp_prompt)
224
+ if not cmd:
225
+ return None
226
+ child_env = os.environ.copy()
227
+ child_env["BUGX_RECON_SCOUT_ACTIVE"] = "1"
228
+
229
+ res = subprocess.run(
230
+ cmd, cwd=self.root, capture_output=True, text=True,
231
+ timeout=10, env=child_env, check=False,
232
+ )
233
+ raw_out = (res.stdout or "").strip()
234
+ # 提取 JSON 对象
235
+ m = re.search(r"\{[\s\S]*\}", raw_out)
236
+ if not m:
237
+ return None
238
+ data = json.loads(m.group(0))
239
+ matched = data.get("matched_command")
240
+ if matched and matched in COMMAND_CAPABILITIES:
241
+ return IntentArbitrationResult(
242
+ matched_command=matched,
243
+ suggestions=[(matched, COMMAND_CAPABILITIES[matched]["description"])],
244
+ source="ai_dynamic",
245
+ reasoning=data.get("reasoning", "AI 语义意图理解推荐"),
246
+ )
247
+ except Exception:
248
+ return None
249
+ return None
250
+
251
+
252
+ @dataclass
253
+ class DiagnosticItem:
254
+ name: str
255
+ detail: str
256
+ required: bool
257
+ root_cause: str
258
+ prescription: str
259
+ auto_repairable: bool
260
+ confidence: str = "high"
261
+
262
+
263
+ @dataclass
264
+ class DiagnosticsResult:
265
+ summary: str
266
+ can_auto_repair: bool
267
+ auto_repair_command: str | None
268
+ items: list[DiagnosticItem] = field(default_factory=list)
269
+ ai_arbitrated: bool = False
270
+
271
+ def as_dict(self) -> dict[str, Any]:
272
+ return {
273
+ "summary": self.summary,
274
+ "can_auto_repair": self.can_auto_repair,
275
+ "auto_repair_command": self.auto_repair_command,
276
+ "ai_arbitrated": self.ai_arbitrated,
277
+ "items": [
278
+ {
279
+ "name": item.name,
280
+ "detail": item.detail,
281
+ "required": item.required,
282
+ "root_cause": item.root_cause,
283
+ "prescription": item.prescription,
284
+ "auto_repairable": item.auto_repairable,
285
+ "confidence": item.confidence,
286
+ }
287
+ for item in self.items
288
+ ],
289
+ }
290
+
291
+
292
+ class DiagnosticAIArbitrator:
293
+ """AI 根因分析与程序确定性修复提示仲裁器。"""
294
+
295
+ # 本地确定性诊断知识。模式必须完整匹配检查项名称,未知检查不得继承修复能力。
296
+ BASELINE_KNOWLEDGE = [
297
+ (
298
+ r"Python >= 3\.11",
299
+ "当前 Python 解释器版本低于 3.11 或运行态环境不满足要求,缺少异步上下文与现代类型特性。",
300
+ "请升级 Python 至 >= 3.11,或激活符合要求的虚拟环境 (例如: conda activate py311 或 pyenv shell 3.11)。",
301
+ ),
302
+ (
303
+ r"安装资源",
304
+ "核心静态资源或模板文件缺失,可能由于打包解压损坏或安装目录被意外清理。",
305
+ "检查报错中的安装资源目录;使用 `bugx update --repair-assets` 修复当前 Python 安装资源,或重装经校验的 BugX wheel。",
306
+ ),
307
+ (
308
+ r"(?:全局引擎完整性|引擎副本一致性)",
309
+ "全局引擎代码清单 (engine-integrity.json) 哈希不匹配或文件缺失,存在版本漂移或代码被意外修改。",
310
+ "`bugx doctor --repair` 在两种情况下会重放安装资源修好引擎:(1) 安装资源 Build ID 严格高于全局引擎;(2) 同 Build ID 且安装资源自身完好。仅当资源自身也损坏(或需要降级)时才会拒绝,此时请重装 CLI。",
311
+ ),
312
+ (
313
+ r"BugX 版本一致性",
314
+ "CLI 命令入口与全局引擎、镜像清单版本声明不一致,存在环境版本漂移。",
315
+ "运行 `bugx doctor --repair` 前先确认安装资源 Build ID 严格高于全局引擎;不满足时升级 CLI wheel 后重试。",
316
+ ),
317
+ (
318
+ r"项目初始化状态",
319
+ # 旧文案硬编码"manifest.json 缺失",但 initialized 实际由
320
+ # manifest_ok ∧ layout ∧ init_issues 三者合取判定,最常见的
321
+ # 实因是缺 .bugx/cloud-onboard.json。模板不得覆盖真实 detail,
322
+ # 否则用户按"manifest 缺失"排查会走进死胡同(实测该文件存在
323
+ # 且 project_id 完全匹配,诊断仍报缺失)。
324
+ "项目初始化未通过完整性判定(manifest 存在不代表就绪:还需 .bugx 布局可加载、"
325
+ "云端 onboarding 记录与启动视图齐备);具体缺口见本项 detail。",
326
+ "先只读运行 `bugx engine --root <ROOT> status --json`;只有状态精确为 `UNINITIALIZED` 时才运行 `bugx engine --root <ROOT> pre`。若返回 `FATAL_BLOCKED`、其他状态或检查失败,保留现场并停止;不得用 `bugx init`、`bugx reset` 或 `--force` 绕过。",
327
+ ),
328
+ (
329
+ r"工作树卫生与嵌套隔离",
330
+ "当前工作树存在未跟踪改动或存在嵌套 Git 仓库冲突,可能导致自动化漏洞验证隔离失效。",
331
+ "检查 git status,将未跟踪的临时产物加入 .gitignore,或提交当前未保存的代码。",
332
+ ),
333
+ (
334
+ r"云端端点连通性",
335
+ "与 BugX 云端服务协同端点通信失败,可能由于未登录鉴权、网络代理阻塞或端点不可达。",
336
+ "若需鉴权请运行 bugx auth login;若为网络问题请检查系统网络与 BUGX_CLOUD_API_BASE 设置。",
337
+ ),
338
+ (
339
+ r"项目资产修复",
340
+ "项目 .bugx 目录中的运行态快照、current.json 或历史记录链存在断裂或文件损坏。",
341
+ "查看 Doctor 列出的具体修复错误;缺少可信备份或校验失败时,从可信备份恢复,不能凭空重建运行态数据。",
342
+ ),
343
+ (
344
+ r"MCP 离线 runtime",
345
+ "本地离线 MCP 运行时沙箱未建立或环境依赖缺失,导致离线代码工具链不可用。",
346
+ "按需运行 `bugx system mcp-runtime install` 建立隔离运行时;这不是 `bugx doctor --repair` 的修复项。",
347
+ ),
348
+ (
349
+ r"MCP 会话进程卫生",
350
+ "检测到系统中存在失控或遗留的 MCP 僵尸进程,可能持续占用端口与系统句柄。",
351
+ "运行 bugx system mcp-runtime clean 清理遗留僵尸进程。",
352
+ ),
353
+ (
354
+ r"BugX CLI 路径",
355
+ "PATH 环境变量中同时存在多个不同包管理器安装的 bugx 入口(例如 npm 与 pip 冲突)。",
356
+ "建议卸载冲突的多余版本(npm: npm uninstall -g @bencibro/bugx,pip: pip uninstall bugx-agent)。",
357
+ ),
358
+ (
359
+ r"基础效率工具",
360
+ "系统缺失部分提速工具(如 ast-grep, ripgrep 等),当前已平滑降级至内置 Python 解析引擎。",
361
+ "可使用包管理器安装对应外部工具(如 brew install ast-grep ripgrep)提升大规模审计速度。",
362
+ ),
363
+ (
364
+ r"Tree-sitter 多语言增强",
365
+ "未检测到 tree-sitter-language-pack 库,跨语言语法树深度解析回退至词法模式。",
366
+ "运行 `bugx doctor --repair` 可尝试安装 `tree-sitter-language-pack`;安装失败时请按错误详情检查 Python 环境和网络。",
367
+ ),
368
+ (
369
+ r"codebase-memory 推荐加速",
370
+ "知识图谱组件 codebase-memory 未就绪或未启动,当前运行于基础模式。",
371
+ "这是可选加速组件;检查插件安装与索引状态,基础模式仍可运行。",
372
+ ),
373
+ (
374
+ r"UI 视觉与浏览器挖掘环境(?:(可选))?",
375
+ "Playwright 浏览器驱动或系统渲染依赖未就绪,UI 自动化挖掘功能受限。",
376
+ "按需运行 `python3 setup_ui_env.py install` 安装 Chromium 浏览器驱动及依赖。",
377
+ ),
378
+ (
379
+ r".+ (?:完整适配包|MCP 配置|全局入口完整性|全局 Skill 完整性)",
380
+ "宿主配置或适配资产与 BugX 当前模板不一致;本地文件可能包含用户自定义内容。",
381
+ "先检查并保存目标配置中的本地修改,再按单个宿主执行 `bugx install --root <ROOT> --agent <HOST>`;不要用 Doctor 批量强制覆盖宿主资产。",
382
+ ),
383
+ ]
384
+
385
+ # 只有这些修复路径由 Doctor 当前控制流直接实现;调用方还必须证明本次
386
+ # 检查满足运行时前置条件。模型输出和静态知识均不能自行扩大这个集合。
387
+ AUTO_REPAIRABLE_CHECKS = frozenset({
388
+ "全局引擎完整性",
389
+ "BugX 版本一致性",
390
+ "Tree-sitter 多语言增强",
391
+ })
392
+
393
+ def __init__(self, root: Path) -> None:
394
+ self.root = root.resolve()
395
+
396
+ def _baseline_for_name(self, name: str) -> tuple[str, str] | None:
397
+ for pattern, cause, prescription in self.BASELINE_KNOWLEDGE:
398
+ if re.fullmatch(pattern, name, re.IGNORECASE):
399
+ return cause, prescription
400
+ return None
401
+
402
+ def diagnose(
403
+ self,
404
+ checks: list[tuple[str, bool, str]],
405
+ installation_required: set[str],
406
+ strict: bool = False,
407
+ auto_repairable_checks: set[str] | None = None,
408
+ ) -> DiagnosticsResult:
409
+ eligible_repairs = set(auto_repairable_checks or ()) & self.AUTO_REPAIRABLE_CHECKS
410
+ failed_raw = [(n, d, n in installation_required) for n, ok, d in checks if not ok]
411
+ if not failed_raw:
412
+ return DiagnosticsResult(
413
+ summary="🎉 所有环境检测项与就绪门禁全部通过,BugX 处于最优运行状态!",
414
+ can_auto_repair=False,
415
+ auto_repair_command=None,
416
+ items=[],
417
+ ai_arbitrated=False,
418
+ )
419
+
420
+ # 1. 优先尝试唤起宿主 AI 生成动态深入诊断分析
421
+ ai_items = self._try_ai_deep_diagnosis(failed_raw)
422
+ if ai_items:
423
+ for item in ai_items:
424
+ baseline = self._baseline_for_name(item.name)
425
+ item.prescription = baseline[1] if baseline else (
426
+ "该检查项没有经过本地规则验证的修复路径;请根据失败详情先做只读排查,勿运行批量修复。"
427
+ )
428
+ item.auto_repairable = item.name in eligible_repairs
429
+ item.confidence = "medium" if baseline else "low"
430
+ repairable_count = sum(1 for item in ai_items if item.auto_repairable)
431
+ can_auto_repair = repairable_count > 0
432
+ return DiagnosticsResult(
433
+ summary=self._build_summary(len(ai_items), repairable_count),
434
+ can_auto_repair=can_auto_repair,
435
+ auto_repair_command="bugx doctor --repair" if can_auto_repair else None,
436
+ items=ai_items,
437
+ ai_arbitrated=True,
438
+ )
439
+
440
+ # 2. 回退到本地高可靠专家知识库
441
+ baseline_items: list[DiagnosticItem] = []
442
+ for name, detail, is_req in failed_raw:
443
+ baseline = self._baseline_for_name(name)
444
+ if baseline:
445
+ canned_cause, prescription = baseline
446
+ # 模板给出的是"可能的根因族",detail 才是本机实测事实。
447
+ # 两者必须同时呈现:只给模板会把用户引向错误的排查方向。
448
+ cause = f"{canned_cause} 实测详情:{detail}" if detail else canned_cause
449
+ confidence = "high"
450
+ else:
451
+ cause = f"检查项 '{name}' 返回未就绪状态:{detail}"
452
+ prescription = "该检查项没有经过本地规则验证的修复路径;请根据失败详情先做只读排查,勿运行批量修复。"
453
+ confidence = "low"
454
+ baseline_items.append(DiagnosticItem(
455
+ name=name,
456
+ detail=detail,
457
+ required=is_req,
458
+ root_cause=cause,
459
+ prescription=prescription,
460
+ auto_repairable=name in eligible_repairs,
461
+ confidence=confidence,
462
+ ))
463
+
464
+ repairable_count = sum(1 for item in baseline_items if item.auto_repairable)
465
+ can_auto_repair = repairable_count > 0
466
+ return DiagnosticsResult(
467
+ summary=self._build_summary(len(baseline_items), repairable_count),
468
+ can_auto_repair=can_auto_repair,
469
+ auto_repair_command="bugx doctor --repair" if can_auto_repair else None,
470
+ items=baseline_items,
471
+ ai_arbitrated=False,
472
+ )
473
+
474
+ def _build_summary(self, total: int, repairable: int) -> str:
475
+ if repairable == total and total > 0:
476
+ return f"检测到 {total} 项环境异常,均有 Doctor 已实现的修复路径;可运行 `bugx doctor --repair` 尝试处理。"
477
+ if repairable > 0:
478
+ return f"检测到 {total} 项环境异常,其中 {repairable} 项有 Doctor 已实现的修复路径。"
479
+ return f"检测到 {total} 项环境异常,请参考下方诊断和对应处置指引。"
480
+
481
+ def _try_ai_deep_diagnosis(
482
+ self,
483
+ failed_raw: list[tuple[str, str, bool]],
484
+ ) -> list[DiagnosticItem] | None:
485
+ """调用宿主 AI 分析当前异常根因;修复权限由本地逻辑裁定。"""
486
+ if os.environ.get("BUGX_OFFLINE") == "1" or os.environ.get("BUGX_DOCTOR_NO_LLM") == "1":
487
+ return None
488
+
489
+ active_host = ""
490
+ try:
491
+ from core.host_runtime import host_registry
492
+ active_host = host_registry.resolve_scout_host(self.root)
493
+ except Exception:
494
+ return None
495
+
496
+ if not active_host:
497
+ return None
498
+
499
+ try:
500
+ from core.host_runtime import host_registry
501
+
502
+ prompt_payload = {
503
+ "os": sys.platform,
504
+ "python_version": sys.version,
505
+ "failed_checks": [
506
+ {"name": n, "detail": d, "is_required": r}
507
+ for n, d, r in failed_raw
508
+ ],
509
+ }
510
+ prompt_content = (
511
+ "<system_rules>\n"
512
+ "You are the BugX System Diagnostic Expert.\n"
513
+ "Analyze the failed environment checks and explain a likely technical root cause for each item.\n"
514
+ "Do not prescribe commands or classify repairability; BugX will use locally verified repair rules for those decisions.\n"
515
+ "Output STRICTLY a JSON object with this exact schema (no markdown, no other text):\n"
516
+ "{\n"
517
+ ' "diagnostics": [\n'
518
+ ' {\n'
519
+ ' "name": "check item name",\n'
520
+ ' "root_cause": "likely technical root cause in Chinese"\n'
521
+ ' }\n'
522
+ ' ]\n'
523
+ "}\n"
524
+ "</system_rules>\n"
525
+ "<context>\n"
526
+ f"{json.dumps(prompt_payload, ensure_ascii=False, indent=2)}\n"
527
+ "</context>\n"
528
+ )
529
+
530
+ # 临时 prompt 必须落在**项目树之外**:``bugx doctor`` 对外承诺
531
+ # 「默认只读诊断」,此前写 ``<root>/.bugx/run/doctor_prompt.txt``
532
+ # 会连带创建 ``.bugx/run`` 等 23 个条目,直接违反零写盘契约
533
+ # (test_a1_doctor_is_read_only_by_default 实测失败)。改用系统临时目录,
534
+ # 用完即删。
535
+ import tempfile
536
+
537
+ tmp_fd, tmp_prompt_name = tempfile.mkstemp(
538
+ prefix="bugx-doctor-prompt-", suffix=".txt",
539
+ )
540
+ os.close(tmp_fd)
541
+ tmp_prompt = Path(tmp_prompt_name)
542
+ try:
543
+ tmp_prompt.write_text(prompt_content, encoding="utf-8")
544
+ except OSError:
545
+ tmp_prompt.unlink(missing_ok=True)
546
+ return None
547
+
548
+ cmd = host_registry.build_recon_scout_command(active_host, self.root, tmp_prompt)
549
+ if not cmd:
550
+ return None
551
+ child_env = os.environ.copy()
552
+ child_env["BUGX_RECON_SCOUT_ACTIVE"] = "1"
553
+
554
+ try:
555
+ res = subprocess.run(
556
+ cmd, cwd=self.root, capture_output=True, text=True,
557
+ timeout=12, env=child_env, check=False,
558
+ )
559
+ finally:
560
+ # 临时 prompt 已在子进程读取后被消费,立即清理避免 /tmp 泄漏。
561
+ tmp_prompt.unlink(missing_ok=True)
562
+ raw_out = (res.stdout or "").strip()
563
+ m = re.search(r"\{[\s\S]*\}", raw_out)
564
+ if not m:
565
+ return None
566
+ data = json.loads(m.group(0))
567
+ diag_list = data.get("diagnostics")
568
+ if not isinstance(diag_list, list) or len(diag_list) != len(failed_raw):
569
+ return None
570
+
571
+ items: list[DiagnosticItem] = []
572
+ expected_names = [name for name, _detail, _required in failed_raw]
573
+ if any(not isinstance(item, dict) for item in diag_list):
574
+ return None
575
+ returned_names = [item.get("name") for item in diag_list]
576
+ if (
577
+ any(not isinstance(name, str) for name in returned_names)
578
+ or len(set(returned_names)) != len(expected_names)
579
+ or set(returned_names) != set(expected_names)
580
+ ):
581
+ return None
582
+ diag_map = {item["name"]: item for item in diag_list}
583
+ for n, d, r in failed_raw:
584
+ parsed = diag_map[n]
585
+ cause = parsed.get("root_cause")
586
+ if not isinstance(cause, str) or not cause.strip():
587
+ return None
588
+ items.append(DiagnosticItem(
589
+ name=n,
590
+ detail=d,
591
+ required=r,
592
+ root_cause=cause,
593
+ prescription="",
594
+ auto_repairable=False,
595
+ confidence="medium",
596
+ ))
597
+ return items
598
+ except Exception:
599
+ return None
600
+
601
+
602
+ def _is_pid_alive(pid: int) -> bool:
603
+ """跨平台安全检测进程 PID 是否存活。"""
604
+ if pid <= 0:
605
+ return False
606
+ try:
607
+ os.kill(pid, 0)
608
+ return True
609
+ except OSError as err:
610
+ return err.errno == errno.EPERM
611
+
612
+
613
+ class DeterministicHealer:
614
+ """只清理已确认失效的 BugX 锁;不创建或重建项目状态。"""
615
+
616
+ def __init__(self, root: Path) -> None:
617
+ self.root = root.resolve()
618
+
619
+ def heal_stale_locks(self) -> tuple[bool, str]:
620
+ """扫描并解除残留的僵尸锁文件(PID 已消亡或锁文件过期)。"""
621
+ dot_bugx = self.root / ".bugx"
622
+ if dot_bugx.is_symlink() or not dot_bugx.is_dir():
623
+ return False, "锁目录不存在,未修改项目状态"
624
+
625
+ removed_locks: list[str] = []
626
+ lock_candidates = list(dot_bugx.rglob("*.lock"))
627
+ now = time.time()
628
+
629
+ for lock_file in lock_candidates:
630
+ if not lock_file.is_file():
631
+ continue
632
+ should_remove = False
633
+ reason = ""
634
+
635
+ try:
636
+ content = lock_file.read_text(encoding="utf-8").strip()
637
+ if not content:
638
+ if now - lock_file.stat().st_mtime > 5:
639
+ should_remove = True
640
+ reason = "空锁超时"
641
+ else:
642
+ pid = None
643
+ try:
644
+ data = json.loads(content)
645
+ if isinstance(data, dict):
646
+ pid = data.get("pid")
647
+ except Exception:
648
+ try:
649
+ pid = int(content)
650
+ except Exception:
651
+ pass
652
+
653
+ if pid is not None and isinstance(pid, int):
654
+ if not _is_pid_alive(pid):
655
+ should_remove = True
656
+ reason = f"持有锁的进程 PID {pid} 已消亡"
657
+ else:
658
+ if now - lock_file.stat().st_mtime > 60:
659
+ should_remove = True
660
+ reason = "锁文件超时残留"
661
+ except Exception:
662
+ pass
663
+
664
+ if should_remove:
665
+ try:
666
+ lock_file.unlink()
667
+ removed_locks.append(f"{lock_file.name} ({reason})")
668
+ except Exception:
669
+ pass
670
+
671
+ if removed_locks:
672
+ return True, f"已安全清除僵尸锁: {', '.join(removed_locks)}"
673
+ return False, "未发现可安全清除的僵尸锁"
674
+
675
+ class RuntimeSelfHealInterceptor:
676
+ """运行时执行异常拦截与就地自愈恢复器。
677
+
678
+ 只允许清理已确认失效的锁并最多重试一次。项目布局、身份、manifest、配置、
679
+ JSON 损坏和启动门禁错误均由调用方保留现场并 fail-closed。
680
+ """
681
+
682
+ def __init__(self, root: Path) -> None:
683
+ self.root = root.resolve()
684
+ self._retried = False
685
+
686
+ def can_heal(self, exc: Exception, command: str | None = None) -> bool:
687
+ """仅白名单内的锁故障可进入确定性修复。"""
688
+ if os.environ.get("BUGX_NO_AUTO_HEAL") == "1":
689
+ return False
690
+ if self._retried:
691
+ return False
692
+
693
+ text = str(exc).casefold()
694
+ if "fatal_blocked" in text or "project_layout=" in text:
695
+ return False
696
+
697
+ # 锁错误也可能出现在门禁或损坏状态的描述中;这些标记始终优先拒绝。
698
+ project_state_markers = (
699
+ "尚未初始化", "not initialized", "manifest.json", "current.json",
700
+ ".bugx-project.json", "缺少项目身份", "身份文件损坏", "配置损坏",
701
+ "jsondecodeerror", "json.decoder", "expecting value", "unterminated string",
702
+ "破损", "格式错误", "版本漂移", "哈希不匹配",
703
+ )
704
+ if any(marker.casefold() in text for marker in project_state_markers):
705
+ return False
706
+
707
+ stale_lock_markers = (
708
+ "timeout waiting for lock", "lock acquisition exceeded",
709
+ "锁文件已存在", "supervisor lock",
710
+ )
711
+ return any(marker in text for marker in stale_lock_markers)
712
+
713
+ def try_heal(self, exc: Exception, command: str | None = None) -> tuple[bool, str]:
714
+ """对已通过白名单的锁故障清理一次;其他异常保持现场。"""
715
+ if not self.can_heal(exc, command=command):
716
+ return False, "异常不在运行时安全修复白名单中;项目状态未修改"
717
+
718
+ self._retried = True
719
+ healer = DeterministicHealer(self.root)
720
+ return healer.heal_stale_locks()
721
+