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,1370 @@
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 subprocess
11
+ import sys
12
+ import tempfile
13
+ import time
14
+ import uuid
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ from .. import __version__
19
+ from ..common import *
20
+ from .agent import (
21
+ _check_host_mcp_config,
22
+ _check_opencode_config,
23
+ _detected_host_name,
24
+ _ensure_opencode_config,
25
+ )
26
+ from .knowledge import _cloud_login_and_register, _cloud_sync_command
27
+
28
+ MAX_SYNC_BUNDLE_BYTES = 16 * 1024 * 1024
29
+
30
+
31
+ _TLS_ERROR_MARKERS = (
32
+ "CERTIFICATE_VERIFY_FAILED",
33
+ "certificate verify failed",
34
+ "self-signed certificate",
35
+ "certificate has expired",
36
+ "SSLCertVerificationError",
37
+ "hostname mismatch",
38
+ )
39
+
40
+
41
+ def _is_tls_failure(error: object) -> bool:
42
+ """区分 TLS 信任失败与普通网络不可达。
43
+
44
+ 两者在 ``verify_auth()`` 中都表现为“联网核验失败”,但处置方式完全不同:
45
+ 前者需要信任证书或配置 ``SSL_CERT_FILE``,后者需要排查网络与地址。
46
+ 混为一谈会把证书问题误导成“API key 失效”。
47
+ """
48
+ text = str(error or "")
49
+ return any(marker in text for marker in _TLS_ERROR_MARKERS)
50
+
51
+
52
+ def _is_local_network_privacy_failure(error: object, base_url: str = "") -> bool:
53
+ """识别 macOS 私网访问被本地网络隐私权限拦截的失败。"""
54
+ data = error if isinstance(error, dict) else getattr(error, "data", None)
55
+ if isinstance(data, dict):
56
+ code = data.get("code")
57
+ nested = data.get("data")
58
+ if isinstance(nested, dict):
59
+ code = nested.get("code", code)
60
+ if str(code or "").upper() == "LOCAL_NETWORK_BLOCKED":
61
+ return True
62
+
63
+ if not base_url:
64
+ return False
65
+ try:
66
+ from core.cloud_sync.cloud_client import diagnose_network_error
67
+ except (ImportError, AttributeError):
68
+ return False
69
+ raw_error = error.get("error") if isinstance(error, dict) else getattr(error, "error", error)
70
+ if not isinstance(raw_error, BaseException):
71
+ raw_error = Exception(str(raw_error or error))
72
+ return bool(diagnose_network_error(raw_error, str(base_url)).get(
73
+ "is_local_network_blocked", False
74
+ ))
75
+
76
+
77
+ def _telemetry_config_path() -> Path:
78
+ default = Path(os.environ.get("BUGX_HOME", str(Path.home() / ".bugx"))) / "cloud-config.json"
79
+ return Path(os.environ.get("BUGX_CLOUD_CONFIG", str(default))).expanduser()
80
+
81
+
82
+ def _save_data_sharing(value: bool) -> None:
83
+ path = _telemetry_config_path()
84
+ path.parent.mkdir(parents=True, exist_ok=True)
85
+ try:
86
+ current = json.loads(path.read_text(encoding="utf-8")) if path.is_file() else {}
87
+ except (OSError, json.JSONDecodeError):
88
+ current = {}
89
+ if not isinstance(current, dict):
90
+ current = {}
91
+ telemetry = dict(current.get("telemetry") or {})
92
+ telemetry["data_sharing"] = bool(value)
93
+ current["telemetry"] = telemetry
94
+ temporary = path.with_suffix(path.suffix + ".tmp")
95
+ temporary.write_text(json.dumps(current, ensure_ascii=False, indent=2), encoding="utf-8")
96
+ os.replace(temporary, path)
97
+ os.chmod(path, 0o600)
98
+
99
+
100
+ def confirm_data_sharing(args: argparse.Namespace) -> bool:
101
+ """数据共享同意;**已选择云同步即视为同意**,不再重复询问。
102
+
103
+ 为什么这样改(build 297):``--cloud-sync sync`` 与「是否允许共享」在用户
104
+ 视角是**同一个决策**——不许上传的话选 sync 毫无意义。此前 ``init`` 末尾会
105
+ 再弹一次「允许 BugX 上传脱敏后的攻防数据用于改进平台?」,等于同一个决定
106
+ 问两遍,且两套状态各存一处(``cloud-onboard.json`` vs ``cloud-config.json``),
107
+ 很容易出现「选了 sync 却因共享未表态而同步不了」。
108
+
109
+ 语义收敛:
110
+ * ``--cloud-sync sync`` ⇒ 共享同意落盘为 true(选择即同意);
111
+ * ``--cloud-sync local`` ⇒ **不写**共享状态(只表示本项目不同步,
112
+ 不应替用户做「全局撤销」这种跨项目决定);
113
+ * 未指定 cloud-sync ⇒ 保持原有询问/默认逻辑。
114
+ """
115
+ if str(getattr(args, "cloud_sync", "") or "").strip().lower() == "sync":
116
+ _save_data_sharing(True)
117
+ return True
118
+ if getattr(args, "privacy", "standard") == "strict":
119
+ _save_data_sharing(bool(getattr(args, "accept_data_sharing", False)))
120
+ return bool(getattr(args, "accept_data_sharing", False))
121
+ if getattr(args, "accept_data_sharing", False) or os.environ.get("BUGX_ACCEPT_DATA_SHARING") == "1":
122
+ _save_data_sharing(True)
123
+ return True
124
+ path = _telemetry_config_path()
125
+ try:
126
+ config = json.loads(path.read_text(encoding="utf-8")) if path.is_file() else {}
127
+ stored = (config.get("telemetry") or {}).get("data_sharing")
128
+ except (OSError, json.JSONDecodeError):
129
+ stored = None
130
+ if isinstance(stored, bool):
131
+ return stored
132
+ if (
133
+ os.environ.get("CI", "").lower() == "true"
134
+ or os.environ.get("BUGX_NON_INTERACTIVE") == "1"
135
+ or os.environ.get("BUGX_HEADLESS") == "1"
136
+ or "unittest" in sys.modules
137
+ or "pytest" in sys.modules
138
+ or not sys.stdin.isatty()
139
+ ):
140
+ # **不得替用户撤销同意**(build 293 实测缺陷):此前这里
141
+ # ``_save_data_sharing(False)`` 把「本次无法交互确认」永久写成
142
+ # ``data_sharing=false`` ⇒ 一次非交互运行就让该用户此后所有云同步被
143
+ # ``data_sharing_revoked`` 拒绝,而用户从未做过任何撤销动作。
144
+ # 契约是「默认允许、仅显式 false 才拒绝」(``require_sharing`` 只看
145
+ # ``sharing_revoked()``),所以非交互时**不落盘**、按默认允许处理。
146
+ return True
147
+ try:
148
+ answer = input("允许 BugX 上传脱敏后的攻防数据用于改进平台?[y/N] ").strip().lower()
149
+ except (EOFError, OSError):
150
+ answer = "n"
151
+ allowed = answer in {"y", "yes"}
152
+ _save_data_sharing(allowed)
153
+ return allowed
154
+
155
+
156
+ def command_telemetry(args: argparse.Namespace) -> int:
157
+ """Inspect and export the independent flywheel outbox/forensic ledger."""
158
+ try:
159
+ _ensure_core_importable()
160
+ from core.cloud_sync.flywheel_client import FlywheelUploader
161
+ uploader = FlywheelUploader(data_sharing=True)
162
+ action = getattr(args, "telemetry_command", "inspect")
163
+ if action == "inspect":
164
+ result = uploader.inspect(latest=bool(getattr(args, "latest", False)))
165
+ if getattr(args, "json", False):
166
+ print(json.dumps(result, ensure_ascii=False, indent=2))
167
+ else:
168
+ for entry in result:
169
+ print(json.dumps(entry, ensure_ascii=False))
170
+ return 0
171
+ if action in {"flush", "upload"}:
172
+ batch_size = int(getattr(args, "batch_size", 20) or 20)
173
+ flushed = uploader.flush(batch_size=batch_size)
174
+ sent = flushed.get("sent", flushed) if isinstance(flushed, dict) else flushed
175
+ print(f"[telemetry] 已推送并清空本地 Outbox:{sent} 条事件")
176
+ return 0
177
+ output = uploader.export_bundle(
178
+ getattr(args, "out"),
179
+ passphrase=getattr(args, "passphrase", None) or os.environ.get("BUGX_TELEMETRY_PASSPHRASE"),
180
+ )
181
+ print(f"[telemetry] 已导出加密穿梭包: {output}")
182
+ return 0
183
+ except Exception as exc: # noqa: BLE001
184
+ print(f"[telemetry] 操作失败: {exc}")
185
+ return 1
186
+
187
+
188
+ def command_telemetry_config(args: argparse.Namespace) -> int:
189
+ config_key = getattr(args, "config_key", "")
190
+ config_value = getattr(args, "config_value", "")
191
+ if config_key == "telemetry.data_sharing":
192
+ if config_value not in ("true", "false"):
193
+ print("[config] telemetry.data_sharing 只接受 true/false")
194
+ return 2
195
+ enabled = config_value == "true"
196
+ try:
197
+ _save_data_sharing(enabled)
198
+ if not enabled:
199
+ _ensure_core_importable()
200
+ from core.cloud_sync.flywheel_client import FlywheelUploader
201
+ cleared = FlywheelUploader(data_sharing=True).clear_outbox()
202
+ print(f"[config] telemetry.data_sharing=false;已清空 {cleared} 条飞轮记录")
203
+ print("[config] 云端同步已停用:撤销态下 sync_layers/auto_sync 拒绝所有 push/pull")
204
+ else:
205
+ print("[config] telemetry.data_sharing=true")
206
+ return 0
207
+ except Exception as exc: # noqa: BLE001
208
+ print(f"[config] 写入失败: {exc}")
209
+ return 1
210
+ if config_key.startswith("cloud."):
211
+ # DOC-211 同步内容策略键;清飞轮等副作用严格限定在 data_sharing。
212
+ field = config_key[len("cloud."):]
213
+ try:
214
+ from core.cloud_sync.cloud_client import update_cloud_config
215
+ written = update_cloud_config({field: config_value})
216
+ except ValueError as exc:
217
+ print(f"[config] 写入失败: {exc}")
218
+ return 2
219
+ except Exception as exc: # noqa: BLE001
220
+ print(f"[config] 写入失败: {exc}")
221
+ return 1
222
+ print(f"[config] {config_key}={written.get(field)} 已写入 ~/.bugx/cloud-config.json")
223
+ return 0
224
+ return 2
225
+
226
+
227
+ def _build_local_sync_bundle(client: Any, root: Path, scope: str,
228
+ detail_mode: str) -> dict[str, Any]:
229
+ from core.cloud_sync.cloud_onboard import get_account_id, get_imports, layer_ledger, resolve_store_path
230
+ from core.cloud_sync.cloud_schema import build_push_envelope
231
+ from core.cloud_sync.sync_push import _private_v2_records
232
+
233
+ ns = get_imports()
234
+ project_id = ""
235
+ if scope == "project":
236
+ from core.cloud_sync.cloud_onboard import load_project_binding
237
+ project_id = load_project_binding(root)
238
+ if not project_id:
239
+ raise ValueError("项目 scope 缺少 .bugx/cloud-project.json 绑定")
240
+ account_id = get_account_id(client)
241
+ store = ns["SyncStore"](resolve_store_path(ns, root, scope))
242
+ try:
243
+ state = store.get_scope_state(account_id, scope, project_id) or {}
244
+ prepared = _private_v2_records(
245
+ ns, layer_ledger(ns, root, scope), detail_mode=detail_mode,
246
+ sync_states=store.get_record_states(account_id, scope, project_id),
247
+ layer=scope,
248
+ )
249
+ finally:
250
+ store.close()
251
+ pid = int(project_id) if project_id else None
252
+ return build_push_envelope(
253
+ scope, pid, prepared["records"],
254
+ snapshot_id=f"export-{uuid.uuid4().hex}",
255
+ operation_id=f"export-op-{uuid.uuid4().hex}",
256
+ base_version=int(state.get("remote_version") or 0),
257
+ device_id=ns["get_device_id"](),
258
+ )
259
+
260
+
261
+ def _read_sync_bundle(path: Path) -> dict[str, Any]:
262
+ from core.secure_atomic import reject_symlink_components
263
+ from core.cloud_sync.cloud_schema import validate_push_envelope
264
+
265
+ reject_symlink_components(path)
266
+ if path.is_symlink() or not path.is_file():
267
+ raise ValueError("bundle 必须是普通文件,不能是符号链接")
268
+ if path.stat().st_size > MAX_SYNC_BUNDLE_BYTES:
269
+ raise ValueError(f"bundle 超过 {MAX_SYNC_BUNDLE_BYTES // (1024 * 1024)} MiB 限制")
270
+ try:
271
+ bundle = json.loads(path.read_text(encoding="utf-8"))
272
+ except (OSError, UnicodeError, json.JSONDecodeError) as exc:
273
+ raise ValueError("bundle 不是合法 JSON") from exc
274
+ return validate_push_envelope(bundle)
275
+
276
+
277
+ def command_cloud(args: argparse.Namespace) -> int:
278
+ """云端同步:登录 / 同步 / 项目 / 设备 / onboarding。"""
279
+ try:
280
+ _ensure_core_importable()
281
+ from core.cloud_sync.cloud_client import CloudClient, get_device_id, lesson_to_wire, incident_to_wire
282
+ from core.ledger.lesson_ledger import read as read_ledger, list_incidents
283
+ from core.bugx_paths import global_knowledge_root, project_knowledge_root
284
+ except Exception as exc: # noqa: BLE001
285
+ print(f"[cloud] 依赖加载失败: {exc}")
286
+ return 2
287
+
288
+ root = args.root.resolve()
289
+ act = args.cloud_command
290
+
291
+ if act == "config":
292
+ try:
293
+ from core.cloud_sync.cloud_client import (
294
+ clear_cloud_base_url, cloud_base_url_status,
295
+ load_cloud_config, set_cloud_base_url,
296
+ )
297
+ disable_vc = getattr(args, "disable_version_check", None)
298
+ if getattr(args, "clear_base_url", False):
299
+ clear_cloud_base_url()
300
+ result = cloud_base_url_status()
301
+ message = "[cloud] 已清除持久化 Base URL"
302
+ elif getattr(args, "refresh_route", False):
303
+ from core.cloud_sync.cloud_client import clear_route_cache
304
+ clear_route_cache()
305
+ result = cloud_base_url_status()
306
+ message = f"[cloud] 已刷新路由测速缓存,当前端点: {result['base_url']}(来源: {result['source']})"
307
+ elif getattr(args, "base_url", None):
308
+ normalized = set_cloud_base_url(args.base_url)
309
+ result = cloud_base_url_status()
310
+ message = f"[cloud] 已设置云端 Base URL: {normalized}"
311
+ elif disable_vc is not None:
312
+ # Read current config, update disable_version_check, persist.
313
+ from core.cloud_sync.cloud_client import _cloud_config_path
314
+ from core.report_engine.report_client import _atomic_write_nofollow
315
+ cfg_path = _cloud_config_path()
316
+ existing = load_cloud_config(cfg_path)
317
+ existing["disable_version_check"] = (disable_vc == "true")
318
+ payload = json.dumps(existing, ensure_ascii=False, indent=2).encode("utf-8")
319
+ _atomic_write_nofollow(cfg_path, payload, parent_mode=0o700)
320
+ result = cloud_base_url_status()
321
+ result["disable_version_check"] = existing.get("disable_version_check", False)
322
+ if disable_vc == "true":
323
+ os.environ["BUGX_DISABLE_VERSION_CHECK"] = "1"
324
+ message = "[cloud] 已禁用启动时版本检查"
325
+ else:
326
+ os.environ.pop("BUGX_DISABLE_VERSION_CHECK", None)
327
+ message = "[cloud] 已启用启动时版本检查"
328
+ else:
329
+ result = cloud_base_url_status()
330
+ # Also show disable_version_check status.
331
+ cfg = load_cloud_config()
332
+ result["disable_version_check"] = cfg.get("disable_version_check", False)
333
+ vc_status = "禁用" if result["disable_version_check"] else "启用"
334
+ message = (
335
+ f"[cloud] 当前云端 Base URL: {result['base_url']}"
336
+ f"(来源: {result['source']});版本检查: {vc_status}"
337
+ )
338
+ except (OSError, ValueError, ImportError) as exc:
339
+ # P3d:_cloud_config_path/_atomic_write_nofollow 的二次 import
340
+ # 也会抛 ImportError,不能让它逃逸成未受控堆栈。
341
+ print(f"[cloud] 配置失败: {exc}")
342
+ return 2
343
+ if getattr(args, "json", False):
344
+ print(json.dumps(result, ensure_ascii=False, indent=2))
345
+ else:
346
+ print(message)
347
+ return 0
348
+
349
+ try:
350
+ client = CloudClient()
351
+ except ValueError as exc:
352
+ # DOC-211:坏配置不得裸奔 traceback;cloud config 子命令不经此路径,
353
+ # 修复入口始终可用。
354
+ print(f"[cloud] cloud-config.json 配置非法: {exc}")
355
+ print("[cloud] 修复:bugx config set cloud.<键> <合法值>,"
356
+ "或删除 ~/.bugx/cloud-config.json 后重试")
357
+ return 1
358
+
359
+ if act == "export":
360
+ try:
361
+ bundle = _build_local_sync_bundle(
362
+ client, root, args.bundle_scope,
363
+ getattr(args, "detail_mode", None) or "full",
364
+ )
365
+ output = Path(args.output).expanduser().absolute()
366
+ from core.report_engine.report_client import _atomic_write_nofollow
367
+ _atomic_write_nofollow(
368
+ output,
369
+ json.dumps(bundle, ensure_ascii=False, indent=2).encode("utf-8"),
370
+ parent_mode=0o700,
371
+ )
372
+ except (OSError, ValueError, RuntimeError) as exc:
373
+ print(f"[cloud] JSON 导出失败: {exc}")
374
+ return 1
375
+ print(f"[cloud] 已导出 {bundle['scope']} bundle: {output}")
376
+ return 0
377
+
378
+ if act == "upload":
379
+ try:
380
+ bundle = _read_sync_bundle(Path(args.input).expanduser().absolute())
381
+ # DOC-211:upload 与 sync 同吃一档敏感策略(配置缺省 allow 透传)。
382
+ try:
383
+ from core.cloud_sync.cloud_client import load_cloud_config
384
+ upload_policy = load_cloud_config().get("sensitive_policy") or "allow"
385
+ except Exception: # noqa: BLE001
386
+ upload_policy = "allow"
387
+ result = client.import_knowledge_bundle(
388
+ bundle, mode=args.mode, sensitive_policy=upload_policy)
389
+ except (OSError, ValueError, RuntimeError) as exc:
390
+ print(f"[cloud] JSON 上传失败: {exc}")
391
+ return 1
392
+ if not result.ok:
393
+ err = client.sync_error(result)
394
+ print(f"[cloud] JSON 上传被拒绝: code={err.code} {err.message or result.error}")
395
+ return 1
396
+ data = client._data(result)
397
+ if args.mode in ("local_authoritative", "merge"):
398
+ try:
399
+ from core.cloud_sync.cloud_onboard import get_account_id, get_imports, resolve_store_path
400
+ from core.cloud_sync.sync_pull import pull_layer
401
+ ns = get_imports()
402
+ account_id = get_account_id(client)
403
+ if account_id:
404
+ project_id = str(bundle.get("project_id") or "") if bundle["scope"] == "project" else ""
405
+ version = data.get("snapshot_version")
406
+ snapshot_id = data.get("snapshot_id")
407
+ if not isinstance(version, int) or isinstance(version, bool) or version < 0 \
408
+ or not isinstance(snapshot_id, str) or not snapshot_id:
409
+ raise ValueError("服务端导入响应缺少可信 snapshot_id/snapshot_version")
410
+ store = ns["SyncStore"](resolve_store_path(ns, root, bundle["scope"]))
411
+ try:
412
+ store.adopt_import_snapshot(
413
+ account_id, bundle["scope"], project_id,
414
+ snapshot_id=snapshot_id, remote_version=version,
415
+ )
416
+ finally:
417
+ store.close()
418
+ pull_result = pull_layer(
419
+ client, ns, root, bundle["scope"], project_id, account_id,
420
+ force_baseline=True,
421
+ )
422
+ if not isinstance(pull_result, dict) or not pull_result.get("ok"):
423
+ raise RuntimeError(
424
+ (pull_result or {}).get("error", "baseline pull failed")
425
+ if isinstance(pull_result, dict) else "baseline pull failed"
426
+ )
427
+ except Exception as exc: # noqa: BLE001
428
+ print(f"[cloud] 本地导入状态未能收敛: {exc}")
429
+ return 1
430
+ if getattr(args, "json", False):
431
+ print(json.dumps(data, ensure_ascii=False, indent=2))
432
+ else:
433
+ print(f"[cloud] JSON 上传完成: scope={bundle['scope']} mode={args.mode}")
434
+ return 0
435
+
436
+ if act == "log-report":
437
+ """内测期诊断日志上报:打包 bugx.jsonl 尾部 -> POST /agent/log-reports。
438
+
439
+ 默认不上报:仅在 AI/用户显式调用本命令时执行;服务端还有登录认证
440
+ 与每账号每日限额(后台可配置)。
441
+ """
442
+ tail_kb = max(1, min(1024, int(getattr(args, "tail_kb", 256) or 256)))
443
+ # 读取方必须跟随写入方的落点:未初始化项目会回退到用户级日志,
444
+ # 直接拼 <root>/.bugx/logs 会永远报"未找到诊断日志"。
445
+ log_file = diagnostic_log_path(root)
446
+ content = ""
447
+ lines = 0
448
+ if log_file.is_file():
449
+ size = log_file.stat().st_size
450
+ with log_file.open("rb") as fh:
451
+ if size > tail_kb * 1024:
452
+ fh.seek(size - tail_kb * 1024)
453
+ fh.readline() # 丢弃不完整的半行
454
+ content = fh.read().decode("utf-8", errors="replace")
455
+ lines = content.count("\n")
456
+ else:
457
+ print("[cloud] 未找到诊断日志(本次会话尚未产生日志),无需上报")
458
+ return 0
459
+ if not content.strip():
460
+ print("[cloud] 诊断日志为空,无需上报")
461
+ return 0
462
+
463
+ from core.cloud_sync.cloud_client import current_version_str
464
+ kind = str(getattr(args, "kind", None) or "cli-diagnostics").strip() or "cli-diagnostics"
465
+ body = {
466
+ "device_id": get_device_id(),
467
+ "client_version": current_version_str(),
468
+ "kind": kind,
469
+ "payload": content,
470
+ }
471
+ if getattr(args, "json", False):
472
+ print(json.dumps({"bytes": len(content.encode("utf-8")), "lines": lines},
473
+ ensure_ascii=False))
474
+ try:
475
+ result = client.post_log_report(body)
476
+ except Exception as exc: # noqa: BLE001
477
+ print(f"[cloud] 日志上报失败: {exc}")
478
+ return 1
479
+ envelope = getattr(result, "data", None)
480
+ payload_data = envelope.get("data") if isinstance(envelope, dict) else None
481
+ remaining = payload_data.get("remaining") if isinstance(payload_data, dict) else None
482
+ if not getattr(result, "ok", False):
483
+ err_text = getattr(result, "error", None) or str(envelope)
484
+ print(f"[cloud] 日志上报被拒绝: {err_text}")
485
+ if isinstance(payload_data, dict) and payload_data.get("limit") is not None:
486
+ print(f"[cloud] 今日配额: 已用 {payload_data.get('used')}/"
487
+ f"{payload_data.get('limit')},请明日再试")
488
+ return 1
489
+ tail_note = f",剩余 {remaining} 次" if remaining is not None else ""
490
+ print(f"[cloud] 日志上报成功({lines} 行{tail_note})")
491
+ return 0
492
+
493
+ if act == "feedback":
494
+ """错题卡质量闭环:本地 feedback 汇总 -> POST /agent/lessons/hit-feedback。"""
495
+ try:
496
+ from core.ledger.lesson_ledger import feedback_outcomes
497
+ from core.bugx_paths import project_knowledge_root
498
+ except Exception as exc: # noqa: BLE001
499
+ print(f"[cloud] 依赖加载失败: {exc}")
500
+ return 2
501
+ try:
502
+ items = feedback_outcomes(
503
+ project_knowledge_root(root) / "lesson-ledger.sqlite3",
504
+ lifecycle_id=getattr(args, "lifecycle", None) or None,
505
+ limit=max(1, min(100, int(getattr(args, "limit", 100) or 100))),
506
+ )
507
+ except Exception as exc: # noqa: BLE001
508
+ print(f"[cloud] 本地反馈读取失败: {exc}")
509
+ return 2
510
+ if getattr(args, "json", False) or getattr(args, "dry_run", False):
511
+ preview = json.dumps({"items": items, "count": len(items)},
512
+ ensure_ascii=False, indent=2)
513
+ print(preview)
514
+ if getattr(args, "dry_run", False):
515
+ return 0
516
+ if not items:
517
+ print("[cloud] 没有可上报的错题卡反馈")
518
+ return 0
519
+ try:
520
+ result = client.post_lesson_hit_feedback(
521
+ items, run_id=getattr(args, "run_id", "") or "",
522
+ project_name=getattr(args, "project_name", "") or "",
523
+ )
524
+ except Exception as exc: # noqa: BLE001
525
+ print(f"[cloud] hit-feedback 上报失败: {exc}")
526
+ return 1
527
+ envelope = getattr(result, "data", None)
528
+ payload = envelope.get("data") if isinstance(envelope, dict) else None
529
+ updated = payload.get("updated") if isinstance(payload, dict) else "?"
530
+ missing = payload.get("missing") if isinstance(payload, dict) else "?"
531
+ if not getattr(result, "ok", False):
532
+ print(f"[cloud] hit-feedback 上报被拒绝: {getattr(result, 'error', None) or envelope}")
533
+ return 1
534
+ print(f"[cloud] hit-feedback 已上报: updated={updated} missing={missing}")
535
+ return 0
536
+
537
+ if act == "status":
538
+ """只读展示本地同步状态;不登录、不联网、不创建 sync store。"""
539
+ try:
540
+ from core.runtime.sync_store import SyncStore, SyncStoreError, global_store_path, project_store_path
541
+ except Exception as exc: # noqa: BLE001
542
+ print(f"[cloud] 同步状态依赖加载失败: {exc}")
543
+ return 2
544
+
545
+ scope = getattr(args, "status_scope", "all")
546
+ scopes = ("global", "project") if scope == "all" else (scope,)
547
+ credential = getattr(client, "cred", None)
548
+ user = getattr(credential, "user", None)
549
+ account_id = ""
550
+ if isinstance(user, dict):
551
+ for key in ("id", "user_id", "account_id", "sub"):
552
+ if user.get(key) not in (None, ""):
553
+ account_id = str(user[key])
554
+ break
555
+ auth_state = "missing"
556
+ try:
557
+ auth_state = credential.auth_state() if credential is not None else "missing"
558
+ except Exception: # noqa: BLE001
559
+ auth_state = "unknown"
560
+
561
+ project_id = ""
562
+ binding_path = root / ".bugx" / "cloud-project.json"
563
+ try:
564
+ binding = json.loads(binding_path.read_text(encoding="utf-8"))
565
+ if isinstance(binding, dict):
566
+ project_id = str(binding.get("project_id") or "")
567
+ except (OSError, UnicodeError, json.JSONDecodeError):
568
+ pass
569
+ onboarding = "pending"
570
+ onboarding_path = root / ".bugx" / "cloud-onboard.json"
571
+ try:
572
+ onboarding_data = json.loads(onboarding_path.read_text(encoding="utf-8"))
573
+ if isinstance(onboarding_data, dict):
574
+ onboarding = str(onboarding_data.get("state") or "pending")
575
+ except (OSError, UnicodeError, json.JSONDecodeError):
576
+ pass
577
+
578
+ stores: dict[str, dict] = {}
579
+ errors: list[str] = []
580
+ for layer in scopes:
581
+ store_path = global_store_path() if layer == "global" else project_store_path(root)
582
+ layer_project_id = "" if layer == "global" else project_id
583
+ try:
584
+ stores[layer] = SyncStore.inspect_scope(
585
+ store_path, account_id, layer, layer_project_id,
586
+ )
587
+ except SyncStoreError as exc:
588
+ stores[layer] = {
589
+ "path": str(store_path), "scope": layer,
590
+ "project_id": layer_project_id, "state": "error", "error": str(exc),
591
+ }
592
+ errors.append(f"{layer}: {exc}")
593
+
594
+ payload = {
595
+ "authenticated": bool(credential and credential.is_authenticated()),
596
+ "auth_state": auth_state,
597
+ "auth_source": (
598
+ "api_key" if getattr(credential, "api_key", None) else
599
+ "local_cache" if getattr(credential, "token", None) else "none"
600
+ ),
601
+ "auth_verified": None,
602
+ "auth_verification_status": "not_checked",
603
+ "has_account_id": bool(account_id),
604
+ "onboarding": onboarding,
605
+ "project_id": project_id or None,
606
+ "scopes": stores,
607
+ }
608
+ if getattr(args, "json", False):
609
+ print(json.dumps(payload, ensure_ascii=False, indent=2))
610
+ else:
611
+ auth_note = ""
612
+ if auth_state == "expired" and getattr(credential, "auth_state_override", None) == "expired":
613
+ auth_note = "(已记录服务端拒绝;需重新登录或使用 `bugx auth status --verify`)"
614
+ elif payload["auth_verification_status"] == "not_checked" \
615
+ and payload["auth_source"] in {"local_cache", "api_key"}:
616
+ auth_note = "(本地凭据,未联网核验;需 `bugx auth status --verify`)"
617
+ print(f"[cloud] 登录态: {auth_state}{auth_note};onboarding: {onboarding}")
618
+ print(f"[cloud] 项目绑定: {project_id or '未绑定'}")
619
+ for layer, item in stores.items():
620
+ state = item.get("scope_state") or {}
621
+ outbox = item.get("outbox") or {}
622
+ conflicts = item.get("conflicts") or {}
623
+ print(
624
+ f" {layer}: {item.get('state')},"
625
+ f"cursor={state.get('committed_cursor') or '未提交'},"
626
+ f"error={state.get('last_error_code') or '无'},"
627
+ f"pending={outbox.get('pending', 0)},"
628
+ f"inflight={outbox.get('inflight', 0)},"
629
+ f"dead_letter={outbox.get('dead_letter', 0)},"
630
+ f"conflicts_open={conflicts.get('open', 0)}"
631
+ )
632
+ if errors:
633
+ print("[cloud] 状态读取失败: " + "; ".join(errors))
634
+ return 1 if errors else 0
635
+
636
+ if act == "conflicts":
637
+ """冲突队列治理:list/prune 与 resolve --side local 离线执行;
638
+ resolve --side remote 需要联网拉取远端权威内容后解决。"""
639
+ try:
640
+ from core.runtime.sync_store import (
641
+ SyncStore, SyncStoreError, global_store_path, project_store_path,
642
+ )
643
+ except Exception as exc: # noqa: BLE001
644
+ print(f"[cloud] 冲突队列依赖加载失败: {exc}")
645
+ return 2
646
+ conflict_action = getattr(args, "conflict_action", "list")
647
+ scope = getattr(args, "conflict_scope", "all")
648
+ layers = (("global", global_store_path()), ("project", project_store_path(root)))
649
+ if scope != "all":
650
+ layers = tuple(item for item in layers if item[0] == scope)
651
+
652
+ if conflict_action == "list":
653
+ conflicts: list[dict] = []
654
+ errors = []
655
+ for layer, store_path in layers:
656
+ if not store_path.exists():
657
+ continue
658
+ try:
659
+ store = SyncStore(store_path)
660
+ try:
661
+ conflicts.extend(store.list_conflicts())
662
+ finally:
663
+ store.close()
664
+ except SyncStoreError as exc:
665
+ errors.append(f"{layer}: {exc}")
666
+ if getattr(args, "json", False):
667
+ print(json.dumps({"conflicts": conflicts, "count": len(conflicts)},
668
+ ensure_ascii=False, indent=2))
669
+ elif not conflicts:
670
+ print("[cloud] 没有待治理的同步冲突")
671
+ else:
672
+ print(f"[cloud] 同步冲突队列: {len(conflicts)} 条待治理")
673
+ for item in conflicts:
674
+ print(
675
+ f" [{item.get('scope')}] {item.get('conflict_id')} "
676
+ f"{item.get('record_type')}/{item.get('record_id')} "
677
+ f"local_v={item.get('local_version')} "
678
+ f"remote_v={item.get('remote_version')} "
679
+ f"reason={item.get('reason') or 'unknown'} "
680
+ f"created={item.get('created_at')}"
681
+ )
682
+ if errors:
683
+ print("[cloud] 冲突队列读取失败: " + "; ".join(errors))
684
+ return 1 if errors else 0
685
+
686
+ if conflict_action == "prune":
687
+ account_id = ""
688
+ credential = getattr(client, "cred", None)
689
+ user = getattr(credential, "user", None)
690
+ if isinstance(user, dict):
691
+ for key in ("id", "user_id", "account_id", "sub"):
692
+ if user.get(key) not in (None, ""):
693
+ account_id = str(user[key])
694
+ break
695
+ project_id = ""
696
+ binding_path = root / ".bugx" / "cloud-project.json"
697
+ try:
698
+ binding = json.loads(binding_path.read_text(encoding="utf-8"))
699
+ if isinstance(binding, dict):
700
+ project_id = str(binding.get("project_id") or "")
701
+ except Exception:
702
+ pass
703
+ total_pruned = 0
704
+ errors = []
705
+ for layer, store_path in layers:
706
+ if not store_path.exists():
707
+ continue
708
+ try:
709
+ store = SyncStore(store_path)
710
+ try:
711
+ layer_pid = project_id if layer == "project" else ""
712
+ total_pruned += store.prune_converged_conflicts(
713
+ account_id, layer, layer_pid, resolver_identity="cli-conflicts-prune"
714
+ )
715
+ finally:
716
+ store.close()
717
+ except SyncStoreError as exc:
718
+ errors.append(f"{layer}: {exc}")
719
+ if errors:
720
+ print("[cloud] 冲突修剪失败: " + "; ".join(errors))
721
+ return 1
722
+ print(f"[cloud] 冲突队列修剪完成:已自动关闭 {total_pruned} 条已收敛/无分歧冲突")
723
+ return 0
724
+
725
+ # resolve(G3' 实效化):
726
+ # local = 保留本地——清除该记录的远端版本元数据(本地权威但**不发明
727
+ # 版本**),下一轮正常 push 以变更内容走服务器分配新版本;
728
+ # remote = 接受远端版本——先联网拉取权威内容经既有导入事务写账本并
729
+ # upsert_record_states 对齐 remote_version/remote_hash,再落
730
+ # 解决记账;拉取失败则不解决(fail-closed,冲突保持 open)。
731
+ # resolve 是显式人工命令,没有任何自动触发路径。
732
+ side = getattr(args, "conflict_side", None) or ""
733
+ if side not in {"local", "remote"}:
734
+ print("[cloud] 用法: bugx cloud conflicts resolve <conflict_id>|--all "
735
+ "--side local|remote [--reason-filter <reason>]")
736
+ return 2
737
+ resolution = "resolved_local" if side == "local" else "resolved_remote"
738
+
739
+ def _pull_authoritative(layer: str, project_id: str, account_id: str) -> dict:
740
+ # --side remote 专用:一次翻页 pull(页数受 client.max_pull_pages
741
+ # 约束)拉取权威内容,经 _pull_layer 既有导入事务写账本,并由
742
+ # inbox 提交回写 record_state。
743
+ from core.cloud_sync.cloud_onboard import get_account_id, get_imports
744
+ from core.cloud_sync.sync_pull import pull_layer
745
+ ns = get_imports()
746
+ return pull_layer(client, ns, root, layer, project_id,
747
+ account_id or get_account_id(client),
748
+ resolve_converged_conflicts=True)
749
+
750
+ def _pull_detail(pull: Any) -> str:
751
+ if isinstance(pull, dict):
752
+ return str(pull.get("error") or "unknown")
753
+ return "unknown"
754
+
755
+ if getattr(args, "conflict_all", False):
756
+ # 批量形态:遍历冲突队列逐条按选边解决;单条失败不中断,
757
+ # 收集后汇总 resolved/failed 计数(R6 曾需手工循环 56 次)。
758
+ if getattr(args, "conflict_id", None):
759
+ print("[cloud] --all 与 conflict_id 互斥,不能同时使用")
760
+ return 2
761
+ reason_filter = str(getattr(args, "conflict_reason_filter", "") or "")
762
+ # G3' 限速保护:--side remote 批量解决总数上限 200;网络侧每层
763
+ # 至多一次翻页 pull 会话(优于逐条 pull 的请求放大)。
764
+ remote_budget = 200
765
+ resolved_count = 0
766
+ failed_count = 0
767
+ over_limit = 0
768
+ failures: list[str] = []
769
+ pulled_layers: list[str] = []
770
+ errors = []
771
+ for layer, store_path in layers:
772
+ if not store_path.exists():
773
+ continue
774
+ try:
775
+ store = SyncStore(store_path)
776
+ except SyncStoreError as exc:
777
+ errors.append(f"{layer}: {exc}")
778
+ continue
779
+ try:
780
+ if side == "remote":
781
+ pending_rows = [
782
+ item for item in store.list_conflicts()
783
+ if not reason_filter
784
+ or (item.get("reason") or "") == reason_filter
785
+ ]
786
+ if not pending_rows:
787
+ continue
788
+ if remote_budget <= 0:
789
+ over_limit += len(pending_rows)
790
+ continue
791
+ first = pending_rows[0]
792
+ try:
793
+ pull = _pull_authoritative(
794
+ layer, str(first.get("project_id") or ""),
795
+ str(first.get("account_id") or ""))
796
+ except Exception as exc: # noqa: BLE001
797
+ failed_count += len(pending_rows)
798
+ failures.append(
799
+ f"{layer}: 权威内容拉取失败 "
800
+ f"{type(exc).__name__}: {exc}")
801
+ continue
802
+ if not isinstance(pull, dict) or not pull.get("ok"):
803
+ failed_count += len(pending_rows)
804
+ failures.append(
805
+ f"{layer}: 权威内容拉取失败 {_pull_detail(pull)}")
806
+ continue
807
+ pulled_layers.append(layer)
808
+ for item in store.list_conflicts():
809
+ if reason_filter and (item.get("reason") or "") != reason_filter:
810
+ continue
811
+ if side == "remote":
812
+ if remote_budget <= 0:
813
+ over_limit += 1
814
+ continue
815
+ remote_budget -= 1
816
+ try:
817
+ store.resolve_conflict(
818
+ str(item["conflict_id"]), resolution,
819
+ resolver_identity="bugx-cli")
820
+ resolved_count += 1
821
+ except SyncStoreError as exc:
822
+ current = store.get_conflict(str(item["conflict_id"]))
823
+ if current and current.get("state") != "open":
824
+ # pull 的冲突感知导入已把该记录幂等收敛
825
+ resolved_count += 1
826
+ continue
827
+ failed_count += 1
828
+ failures.append(f"{layer}/{item.get('conflict_id')}: {exc}")
829
+ finally:
830
+ store.close()
831
+ note = ("保留本地,丢弃远端记录(该记录远端版本元数据已清除)"
832
+ if side == "local" else "接受远端版本(已拉取权威内容入账本)")
833
+ if errors:
834
+ print("[cloud] 冲突队列读取失败: " + "; ".join(errors))
835
+ if getattr(args, "json", False):
836
+ payload = {
837
+ "all": True, "side": side, "resolution": resolution,
838
+ "reason_filter": reason_filter or None,
839
+ "resolved": resolved_count, "failed": failed_count,
840
+ "failures": failures,
841
+ "pulled": pulled_layers,
842
+ }
843
+ if over_limit:
844
+ payload["over_limit"] = over_limit
845
+ print(json.dumps(payload, ensure_ascii=False))
846
+ else:
847
+ filter_note = f",reason={reason_filter}" if reason_filter else ""
848
+ limit_note = f",超出上限未处理 {over_limit} 条" if over_limit else ""
849
+ print(f"[cloud] 批量解决完成(side={side},{note}{filter_note}): "
850
+ f"resolved={resolved_count} failed={failed_count}{limit_note}")
851
+ for failure in failures:
852
+ print(f" [failed] {failure}")
853
+ return 1 if (errors or failed_count) else 0
854
+ conflict_id = getattr(args, "conflict_id", None) or ""
855
+ if not conflict_id:
856
+ print("[cloud] 用法: bugx cloud conflicts resolve <conflict_id>|--all "
857
+ "--side local|remote [--reason-filter <reason>]")
858
+ return 2
859
+ resolved_scopes: list[str] = []
860
+ resolve_failures: list[str] = []
861
+ errors = []
862
+ for layer, store_path in layers:
863
+ if not store_path.exists():
864
+ continue
865
+ try:
866
+ store = SyncStore(store_path)
867
+ except SyncStoreError as exc:
868
+ errors.append(f"{layer}: {exc}")
869
+ continue
870
+ try:
871
+ row = store.get_conflict(conflict_id)
872
+ if not row or row.get("state") != "open":
873
+ # 该层没有这条 open 冲突;conflict_id 是跨层唯一的确定性哈希。
874
+ continue
875
+ if side == "remote":
876
+ try:
877
+ pull = _pull_authoritative(
878
+ layer, str(row.get("project_id") or ""),
879
+ str(row.get("account_id") or ""))
880
+ except Exception as exc: # noqa: BLE001
881
+ resolve_failures.append(
882
+ f"{layer}: 权威内容拉取失败 {type(exc).__name__}: {exc}")
883
+ continue
884
+ if not isinstance(pull, dict) or not pull.get("ok"):
885
+ resolve_failures.append(
886
+ f"{layer}: 权威内容拉取失败 {_pull_detail(pull)}")
887
+ continue
888
+ try:
889
+ store.resolve_conflict(conflict_id, resolution,
890
+ resolver_identity="bugx-cli")
891
+ except SyncStoreError:
892
+ current = store.get_conflict(conflict_id)
893
+ if not (side == "remote" and current
894
+ and current.get("state") == "resolved_remote"):
895
+ raise # 既未显式解决、pull 也未收敛:按失败处理
896
+ resolved_scopes.append(layer)
897
+ except SyncStoreError as exc:
898
+ resolve_failures.append(f"{layer}: {exc}")
899
+ finally:
900
+ store.close()
901
+ if errors:
902
+ print("[cloud] 冲突队列读取失败: " + "; ".join(errors))
903
+ return 1
904
+ if resolve_failures:
905
+ for failure in resolve_failures:
906
+ print(f"[cloud] {failure}")
907
+ print(f"[cloud] 冲突 {conflict_id} 未能解决:远端权威内容未落地,"
908
+ "冲突保持 open(fail-closed)")
909
+ return 1
910
+ if not resolved_scopes:
911
+ print(f"[cloud] 冲突 {conflict_id} 不存在或已解决")
912
+ return 1
913
+ note = ("保留本地,丢弃远端记录(该记录远端版本元数据已清除,"
914
+ "下一轮 push 由服务器分配新版本)"
915
+ if side == "local" else
916
+ "接受远端版本(已拉取权威内容入账本并回写记录版本元数据)")
917
+ if getattr(args, "json", False):
918
+ print(json.dumps({
919
+ "conflict_id": conflict_id, "resolution": resolution,
920
+ "side": side, "scopes": resolved_scopes,
921
+ }, ensure_ascii=False))
922
+ else:
923
+ print(f"[cloud] 冲突 {conflict_id} 已解决(side={side},{note})"
924
+ f": scopes={','.join(resolved_scopes)}")
925
+ return 0
926
+
927
+ if act == "dead-letter":
928
+ """本地死信队列治理(不联网):list / purge。
929
+
930
+ purge 必须显式 ``--confirm`` 才删除;缺省只 dry-run 打印将删条数。
931
+ 删除前先把将删行整体导出到 ``.bugx/cloud-sync/dead-letter-archive-<ts>.json``
932
+ 留档(可追溯),归档失败的层不删除。
933
+ """
934
+ try:
935
+ from core.runtime.sync_store import (
936
+ SyncStore, SyncStoreError, global_store_path, project_store_path,
937
+ )
938
+ except Exception as exc: # noqa: BLE001
939
+ print(f"[cloud] 死信队列依赖加载失败: {exc}")
940
+ return 2
941
+ dead_action = getattr(args, "dead_letter_action", "list")
942
+ dead_scope = getattr(args, "dead_letter_scope", "all")
943
+ layers = (("global", global_store_path()), ("project", project_store_path(root)))
944
+ if dead_scope != "all":
945
+ layers = tuple(item for item in layers if item[0] == dead_scope)
946
+ try:
947
+ older_than_days = int(getattr(args, "dead_letter_older_than_days", 0) or 0)
948
+ except (TypeError, ValueError):
949
+ print("[cloud] --older-than-days 必须是非负整数")
950
+ return 2
951
+ if older_than_days < 0:
952
+ print("[cloud] --older-than-days 必须是非负整数")
953
+ return 2
954
+
955
+ scanned: list[tuple[str, Path, list[dict]]] = []
956
+ errors: list[str] = []
957
+ for layer, store_path in layers:
958
+ if not store_path.exists():
959
+ continue
960
+ try:
961
+ store = SyncStore(store_path)
962
+ try:
963
+ rows = store.list_dead_letters(older_than_days=older_than_days)
964
+ finally:
965
+ store.close()
966
+ scanned.append((layer, store_path, rows))
967
+ except SyncStoreError as exc:
968
+ errors.append(f"{layer}: {exc}")
969
+ total = sum(len(rows) for _layer, _path, rows in scanned)
970
+
971
+ def dead_letter_view(layer: str, row: dict) -> dict:
972
+ return {
973
+ "layer": layer,
974
+ "scope": row.get("scope"),
975
+ "operation_id": row.get("operation_id"),
976
+ "record_type": row.get("record_type"),
977
+ "record_id": row.get("record_id"),
978
+ "last_error_code": row.get("last_error_code"),
979
+ "created_at": row.get("created_at"),
980
+ "attempts": row.get("attempts"),
981
+ }
982
+
983
+ if dead_action == "list":
984
+ if getattr(args, "json", False):
985
+ payload = {
986
+ "dead_letters": [
987
+ dead_letter_view(layer, row)
988
+ for layer, _path, rows in scanned for row in rows
989
+ ],
990
+ "count": total,
991
+ }
992
+ print(json.dumps(payload, ensure_ascii=False, indent=2))
993
+ elif total == 0:
994
+ print("[cloud] 没有滞留的同步死信")
995
+ else:
996
+ print(f"[cloud] 同步死信队列: {total} 条滞留")
997
+ for layer, _path, rows in scanned:
998
+ for row in rows:
999
+ print(
1000
+ f" [{layer}/{row.get('scope')}] {row.get('operation_id')} "
1001
+ f"{row.get('record_type')}/{row.get('record_id')} "
1002
+ f"error={row.get('last_error_code') or 'unknown'} "
1003
+ f"created={row.get('created_at')} "
1004
+ f"attempts={row.get('attempts')}"
1005
+ )
1006
+ if errors:
1007
+ print("[cloud] 死信队列读取失败: " + "; ".join(errors))
1008
+ return 1 if errors else 0
1009
+
1010
+ # purge
1011
+ if not getattr(args, "dead_letter_confirm", False):
1012
+ # dry-run:只有显式 --confirm 才会真正删除。
1013
+ if getattr(args, "json", False):
1014
+ print(json.dumps({"dry_run": True, "would_purge": total},
1015
+ ensure_ascii=False))
1016
+ elif total:
1017
+ print(f"[cloud] dry-run:将清理 {total} 条死信(先归档后删除);"
1018
+ "追加 --confirm 执行")
1019
+ else:
1020
+ print("[cloud] 没有可清理的死信")
1021
+ if errors:
1022
+ print("[cloud] 死信队列读取失败: " + "; ".join(errors))
1023
+ return 1 if errors else 0
1024
+
1025
+ archive_stamp = time.strftime("%Y%m%dT%H%M%SZ", time.gmtime())
1026
+ purged_total = 0
1027
+ archives: list[str] = []
1028
+ for layer, store_path, rows in scanned:
1029
+ if not rows:
1030
+ continue
1031
+ archive_path = store_path.parent / f"dead-letter-archive-{archive_stamp}.json"
1032
+ if archive_path.exists():
1033
+ # 同秒二次清理:不覆盖前一次留档。
1034
+ archive_path = store_path.parent / (
1035
+ f"dead-letter-archive-{archive_stamp}-{uuid.uuid4().hex[:8]}.json")
1036
+ payload = {
1037
+ "schema_version": 1,
1038
+ "archived_at": archive_stamp,
1039
+ "layer": layer,
1040
+ "source_store": str(store_path),
1041
+ "dead_letters": rows,
1042
+ }
1043
+ try:
1044
+ # 原子留档(同 cloud.py 内 _save_data_sharing 的写法):
1045
+ # 归档失败的层绝不进入删除步骤。
1046
+ temporary = archive_path.with_name(archive_path.name + ".tmp")
1047
+ temporary.write_text(
1048
+ json.dumps(payload, ensure_ascii=False, indent=2),
1049
+ encoding="utf-8")
1050
+ os.replace(temporary, archive_path)
1051
+ os.chmod(archive_path, 0o600)
1052
+ except OSError as exc:
1053
+ errors.append(f"{layer}: 死信归档失败,已跳过删除: {exc}")
1054
+ continue
1055
+ try:
1056
+ store = SyncStore(store_path)
1057
+ try:
1058
+ purged_total += store.purge_dead_letters(
1059
+ [str(row["operation_id"]) for row in rows])
1060
+ finally:
1061
+ store.close()
1062
+ except SyncStoreError as exc:
1063
+ errors.append(f"{layer}: {exc}")
1064
+ continue
1065
+ archives.append(str(archive_path))
1066
+ if getattr(args, "json", False):
1067
+ print(json.dumps({
1068
+ "purged": purged_total, "archives": archives, "errors": errors,
1069
+ }, ensure_ascii=False))
1070
+ else:
1071
+ summary = f"[cloud] 死信清理完成:已清理 {purged_total} 条死信"
1072
+ if archives:
1073
+ summary += ";归档: " + ", ".join(archives)
1074
+ print(summary)
1075
+ if errors:
1076
+ print("[cloud] 死信清理部分失败: " + "; ".join(errors))
1077
+ return 1
1078
+ return 0
1079
+
1080
+ def pattern_list(ledger_path: Path) -> list:
1081
+ try:
1082
+ data = read_ledger(ledger_path)
1083
+ return list((data.get("lessons") or {}).values())
1084
+ except Exception: # noqa: BLE001
1085
+ return []
1086
+
1087
+ def incident_list(ledger_path: Path) -> list:
1088
+ try:
1089
+ return list_incidents(ledger_path)
1090
+ except Exception: # noqa: BLE001
1091
+ return []
1092
+
1093
+ def layer_ledger(layer: str) -> Path:
1094
+ if layer == "global":
1095
+ return global_knowledge_root() / "lesson-ledger.json"
1096
+ return project_knowledge_root(root) / "lesson-ledger.json"
1097
+
1098
+ if act == "auth":
1099
+ auth_action = getattr(args, "auth_action", "")
1100
+ if auth_action == "login":
1101
+ sharing = confirm_data_sharing(args)
1102
+ if not sharing:
1103
+ print("[cloud] 未同意数据反哺;本地保持离线隐私模式")
1104
+ try:
1105
+ _cloud_login_and_register(client, get_device_id)
1106
+ except RuntimeError as exc:
1107
+ print(f"[cloud] 登录失败: {exc}")
1108
+ return 1
1109
+ print("[cloud] 登录成功,凭据已保存")
1110
+ try:
1111
+ from core.cloud_sync.cloud_onboard import get_state, set_state
1112
+ if get_state(root) in {"dismissed", "local"}:
1113
+ set_state(root, "pending")
1114
+ print("[cloud] 已重新开启本项目 onboarding;下次 Agent 启动会询问同步")
1115
+ except Exception as exc: # noqa: BLE001
1116
+ print(f"[cloud] onboarding 状态未更新: {exc}")
1117
+ return 0
1118
+ if auth_action == "set-key":
1119
+ if not args.api_key:
1120
+ raise CliError(_i18n_exc("cloud.auth_set_key_api_key_required", "auth set-key 必须提供 --api-key"))
1121
+ client.set_api_key(args.api_key)
1122
+ print("[cloud] api-key 已保存")
1123
+ return 0
1124
+ if auth_action == "logout":
1125
+ client.logout()
1126
+ print("[cloud] 已退出云端登录;设备身份和本地同步状态未删除")
1127
+ return 0
1128
+ if auth_action == "status":
1129
+ credential = client.cred
1130
+ user = credential.user if isinstance(credential.user, dict) else {}
1131
+ user_id = next(
1132
+ (str(user[key]) for key in ("id", "user_id", "account_id", "sub")
1133
+ if user.get(key) not in (None, "")),
1134
+ "",
1135
+ )
1136
+ payload = {
1137
+ "authenticated": credential.is_authenticated(),
1138
+ "auth_state": credential.auth_state(),
1139
+ "auth_source": (
1140
+ "api_key" if credential.api_key else
1141
+ "local_cache" if credential.token else "none"
1142
+ ),
1143
+ "has_api_key": bool(credential.api_key),
1144
+ "has_refresh_token": bool(credential.refresh_token),
1145
+ "user_id": user_id or None,
1146
+ "auth_verified": None,
1147
+ "auth_verification_status": "not_checked",
1148
+ }
1149
+ if getattr(args, "verify_auth", False):
1150
+ verified = client.verify_auth()
1151
+ verification_error = getattr(verified, "error", None)
1152
+ verification_data = getattr(verified, "data", None)
1153
+ if not verification_error and isinstance(verification_data, dict):
1154
+ verification_error = verification_data.get("message") or verification_data.get("error")
1155
+ verification_http_status = getattr(verified, "status", None)
1156
+ payload["auth_verified"] = bool(verified.ok)
1157
+ local_network_blocked = (
1158
+ not verified.ok
1159
+ and _is_local_network_privacy_failure(
1160
+ verified,
1161
+ getattr(client, "base", "") or getattr(client, "base_url", ""),
1162
+ )
1163
+ )
1164
+ payload["auth_verification_status"] = (
1165
+ "valid" if verified.ok else
1166
+ "expired" if verification_http_status == 401 else
1167
+ "local_network_blocked" if local_network_blocked else
1168
+ "tls_untrusted" if _is_tls_failure(verification_error) else
1169
+ "unavailable"
1170
+ )
1171
+ payload["auth_verification_error"] = verification_error
1172
+ payload["auth_verification_http_status"] = verification_http_status
1173
+ payload["auth_state"] = credential.auth_state()
1174
+ if getattr(args, "json", False):
1175
+ print(json.dumps(payload, ensure_ascii=False, indent=2))
1176
+ else:
1177
+ state_note = ""
1178
+ if payload["auth_verification_status"] == "not_checked" \
1179
+ and payload["auth_source"] == "local_cache":
1180
+ state_note = "(本地缓存,未联网验证)"
1181
+ elif payload["auth_verification_status"] == "local_network_blocked":
1182
+ reason = payload.get("auth_verification_error") or "局域网目标不可达"
1183
+ state_note = f"(服务端验证: local_network_blocked,原因: {reason})"
1184
+ elif payload["auth_verification_status"] != "not_checked":
1185
+ state_note = f"(服务端验证: {payload['auth_verification_status']})"
1186
+ if payload.get("auth_verification_error") \
1187
+ and payload["auth_verification_status"] != "local_network_blocked":
1188
+ state_note += f",原因: {payload['auth_verification_error']}"
1189
+ print(f"[cloud] 登录态: {payload['auth_state']}{state_note}")
1190
+ print(f"[cloud] API Key: {'已配置' if payload['has_api_key'] else '未配置'}")
1191
+ print(f"[cloud] Refresh Token: {'已配置' if payload['has_refresh_token'] else '未配置'}")
1192
+ print(f"[cloud] 账号: {payload['user_id'] or '未识别'}")
1193
+ return 0
1194
+ return 2
1195
+
1196
+ if act == "sync":
1197
+ # DOC-211:--scope 缺省时读用户级 sync_scope_default(默认 all);
1198
+ # onboard-on(:1216)刻意传显式 "all",不受配置收窄。
1199
+ try:
1200
+ from core.cloud_sync.cloud_client import load_cloud_config
1201
+ sync_default_scope = load_cloud_config().get("sync_scope_default") or "all"
1202
+ except Exception: # noqa: BLE001
1203
+ sync_default_scope = "all"
1204
+ if getattr(args, "sync_scope", None) is None and sync_default_scope != "all":
1205
+ print(f"[cloud] sync_scope_default={sync_default_scope}(配置生效;显式 --scope 可覆盖)")
1206
+ return _cloud_sync_command(args, client, root, get_device_id,
1207
+ default_scope=sync_default_scope)
1208
+
1209
+ if act == "projects":
1210
+ sub = getattr(args, "cloud_project_action", "list")
1211
+ if sub == "list":
1212
+ r = client.list_projects()
1213
+ data = client._data(r)
1214
+ print("[cloud] 已登记项目:", json.dumps(data, ensure_ascii=False) if data else "(无)")
1215
+ return 0 if r.ok else 1
1216
+ if sub == "add":
1217
+ try:
1218
+ # 显式登记命令保持“缺省创建新身份”的能力(用户意图明确),
1219
+ # 但同样要暴露“身份文件未提交”的跨设备风险(DOC-031 P0)。
1220
+ import importlib
1221
+ cloud_onboard = importlib.import_module("core.cloud_sync.cloud_onboard")
1222
+ _save_project_binding = getattr(cloud_onboard, "_save_project_binding", None) or getattr(cloud_onboard, "save_project_binding")
1223
+ onboard_wizard = importlib.import_module("core.cloud_sync.onboard_wizard")
1224
+ ensure_project_identity = getattr(onboard_wizard, "ensure_project_identity", None) or getattr(onboard_wizard, "_ensure_project_identity")
1225
+ warn_uncommitted_identity = getattr(onboard_wizard, "warn_uncommitted_identity", None) or getattr(onboard_wizard, "_warn_uncommitted_identity")
1226
+ identity = ensure_project_identity(root, args.project_slug)
1227
+ warn_uncommitted_identity(root)
1228
+ except Exception as exc: # noqa: BLE001
1229
+ print(f"[cloud] 项目身份准备失败: {exc}")
1230
+ return 1
1231
+ r = client.register_project(
1232
+ slug=identity["slug"], name=identity["slug"],
1233
+ project_key=identity["project_key"],
1234
+ )
1235
+ print(f"[cloud] 登记项目: status={r.status} {r.error or ''}")
1236
+ if r.ok:
1237
+ pid = client.project_id(r)
1238
+ remote_key = client.project_key(r)
1239
+ if not pid:
1240
+ print("[cloud] 项目登记响应缺少 project_id,拒绝写入项目绑定")
1241
+ return 1
1242
+ if remote_key != identity["project_key"]:
1243
+ print("[cloud] 项目登记响应 project_key 不一致,拒绝写入项目绑定")
1244
+ return 1
1245
+ try:
1246
+ _save_project_binding(
1247
+ root, pid, identity["slug"], identity["project_key"],
1248
+ )
1249
+ print("[cloud] 已写入 .bugx-project.json(请提交到仓库,换机克隆即可对上同一云端项目)")
1250
+ except Exception as exc: # noqa: BLE001
1251
+ print(f"[cloud] 项目绑定/身份文件写入失败: {exc}")
1252
+ return 1
1253
+ return 0 if r.ok else 1
1254
+ return 2
1255
+
1256
+ if act == "devices":
1257
+ r = client.sync_status()
1258
+ data = client._data(r)
1259
+ print("[cloud] 设备同步状态:", json.dumps(data, ensure_ascii=False) if data else "(空)")
1260
+ return 0 if r.ok else 1
1261
+
1262
+ if act == "onboard":
1263
+ # 项目级 onboarding 状态;显式 ``on`` 是“开启并立即同步”,而不是
1264
+ # 只写一个 pending 标记再要求 Agent 解释下一步。
1265
+ try:
1266
+ from core.cloud_sync.cloud_onboard import get_state, set_state
1267
+ cur = get_state(root)
1268
+ except Exception as exc: # noqa: BLE001
1269
+ print(f"[cloud] onboarding 状态读取失败: {exc}")
1270
+ return 1
1271
+ onboard_action = getattr(args, "onboard_action", "status")
1272
+ if onboard_action == "status":
1273
+ print(f"[cloud] 本项目 onboarding: {cur}")
1274
+ return 0
1275
+ if onboard_action == "off":
1276
+ try:
1277
+ set_state(root, "local")
1278
+ except Exception as exc: # noqa: BLE001
1279
+ print(f"[cloud] onboarding 写失败: {exc}")
1280
+ return 1
1281
+ print("[cloud] onboarding 已设为 local(本地模式)")
1282
+ return 0
1283
+ # ``on`` 是显式用户动作:立即走完整登录/设备登记/全量同步链路。
1284
+ try:
1285
+ set_state(root, "pending")
1286
+ except Exception as exc: # noqa: BLE001
1287
+ print(f"[cloud] onboarding 写失败: {exc}")
1288
+ return 1
1289
+ print("[cloud] 已开启云端同步,立即同步 global + project…")
1290
+ sync_args = argparse.Namespace(
1291
+ project_slug=args.project_slug,
1292
+ sync_scope="all",
1293
+ detail_mode=None,
1294
+ )
1295
+ return _cloud_sync_command(sync_args, client, root, get_device_id)
1296
+
1297
+ return 2
1298
+
1299
+
1300
+ def _supervisor_deploy(root: Path) -> int:
1301
+ """接入 canonical stdio MCP。"""
1302
+ try:
1303
+ status, backup = _ensure_opencode_config(root)
1304
+ except CliError as exc:
1305
+ print(f"[supervisor] OpenCode 配置未修改: {exc}")
1306
+ return 1
1307
+ suffix = f";备份={backup.relative_to(root)}" if backup else ""
1308
+ print(f"[supervisor] 已接入 canonical bugx-supervisor stdio MCP({status}{suffix})")
1309
+ return 0
1310
+
1311
+
1312
+ def _supervisor_status(root: Path) -> int:
1313
+ """显示运行态和宿主配置状态。
1314
+
1315
+ 先检查是否有活跃的 legacy 运行态(audit-supervisor.json),
1316
+ 再检查 engine runtime 状态,最后才检查宿主 MCP 配置。
1317
+ 避免在运行态正常但宿主配置缺失时误导操作者。
1318
+ """
1319
+ print(" Supervisor 状态")
1320
+ print("-" * 40)
1321
+
1322
+ # 1. 检查 legacy 运行态
1323
+ legacy_state_path = root / ".bugx" / "audit-supervisor.json"
1324
+ if legacy_state_path.is_file():
1325
+ try:
1326
+ import json
1327
+ raw = json.loads(legacy_state_path.read_text(encoding="utf-8"))
1328
+ status_val = raw.get("status", "unknown")
1329
+ covered = len(raw.get("coverage", {}))
1330
+ covered_count = sum(
1331
+ 1 for v in raw.get("coverage", {}).values()
1332
+ if isinstance(v, dict) and v.get("status") == "covered"
1333
+ ) if isinstance(raw.get("coverage"), dict) else 0
1334
+ total_units = raw.get("total_units") or covered
1335
+ findings = len(raw.get("findings", []))
1336
+ print(f" 运行态: {status_val}")
1337
+ print(f" 覆盖: {covered_count}/{total_units} 单元")
1338
+ print(f" Findings: {findings}")
1339
+ if status_val in ("BUDGET_EXHAUSTED", "FAILED"):
1340
+ print(f" ⚠ 运行态处于 {status_val},需要处理")
1341
+ except (OSError, ValueError) as exc:
1342
+ print(f" 运行态文件存在但解析失败: {exc}")
1343
+ else:
1344
+ print(" 运行态: 未启动(无 audit-supervisor.json)")
1345
+
1346
+ # 2. 检查 engine runtime
1347
+ runtime_path = root / ".bugx" / "bugx-runtime.json"
1348
+ if runtime_path.is_file():
1349
+ try:
1350
+ import json
1351
+ rt = json.loads(runtime_path.read_text(encoding="utf-8"))
1352
+ lid = rt.get("lifecycle_id", "-")
1353
+ print(f" Lifecycle: {lid}")
1354
+ except (OSError, ValueError):
1355
+ pass
1356
+
1357
+ print("-" * 40)
1358
+
1359
+ # 3. 检查**当前宿主**的 MCP 配置
1360
+ # 缺陷 #12:这里原本无条件调用 OpenCode 的检查器并打印 ``OpenCode canonical
1361
+ # MCP 配置``,于是在 dsh / claude / codex 宿主上 status 永远报「✗ 缺少
1362
+ # opencode.json」,让用户去装一个根本没在用的宿主。宿主名必须来自环境探测,
1363
+ # 配置校验复用 ``_check_host_mcp_config`` 的逐宿主分派。
1364
+ host_name = _detected_host_name(root)
1365
+ config_ok, config_detail = _check_host_mcp_config(root, host_name)
1366
+ display = "未识别宿主" if host_name == "unknown" else host_name
1367
+ print(f" {'✓' if config_ok else '✗'} {display} 宿主 MCP 配置")
1368
+ if not config_ok:
1369
+ print(f" {config_detail}")
1370
+ return 0 if config_ok else 1