bugx-cli 0.1.1__py3-none-any.whl
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.
- bugx_cli/__init__.py +6 -0
- bugx_cli/cli.py +1685 -0
- bugx_cli/commands/__init__.py +1 -0
- bugx_cli/commands/advisory.py +94 -0
- bugx_cli/commands/agent.py +4210 -0
- bugx_cli/commands/audit.py +632 -0
- bugx_cli/commands/autonomous.py +260 -0
- bugx_cli/commands/cloud.py +1371 -0
- bugx_cli/commands/daemon.py +50 -0
- bugx_cli/commands/doctor.py +1590 -0
- bugx_cli/commands/goal.py +107 -0
- bugx_cli/commands/interaction.py +248 -0
- bugx_cli/commands/knowledge.py +619 -0
- bugx_cli/commands/lifecycle.py +2763 -0
- bugx_cli/commands/patch.py +1014 -0
- bugx_cli/commands/plugin.py +2749 -0
- bugx_cli/commands/plugin_claude.py +1446 -0
- bugx_cli/commands/plugin_cline.py +269 -0
- bugx_cli/commands/plugin_codex.py +74 -0
- bugx_cli/commands/plugin_funide.py +729 -0
- bugx_cli/commands/plugin_qoder.py +216 -0
- bugx_cli/commands/plugin_zcode.py +710 -0
- bugx_cli/commands/project.py +670 -0
- bugx_cli/commands/report.py +256 -0
- bugx_cli/commands/skill.py +251 -0
- bugx_cli/commands/stats.py +133 -0
- bugx_cli/commands/system.py +2567 -0
- bugx_cli/common.py +906 -0
- bugx_cli/host_adapters.py +1892 -0
- bugx_cli/hosts/__init__.py +80 -0
- bugx_cli/hosts/base.py +99 -0
- bugx_cli/hosts/registry.py +573 -0
- bugx_cli/hosts/template_engine.py +188 -0
- bugx_cli/infra/__init__.py +209 -0
- bugx_cli/infra/ai_advisor.py +851 -0
- bugx_cli/infra/engine_installer.py +1945 -0
- bugx_cli/infra/host_sync.py +548 -0
- bugx_cli/infra/mcp_advisor.py +826 -0
- bugx_cli/infra/security.py +339 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/bugx-mcp-manifest.json +53 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/CATALOG.json +141 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/README.md +254 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/adapters/README.md +35 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/adapters/android-interaction.json +81 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/adapters/android.json +24 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/adapters/desktop-macos.json +20 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/adapters/ios-interaction.json +34 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/adapters/ios.json +23 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/adapters/memory-macos.json +24 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/agent/README.md +51 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/agent/__init__.py +146 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/agent/agent_artifacts.py +766 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/agent/agent_eval.py +1155 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/agent/agent_execution.py +718 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/agent/agent_orchestrator.py +1351 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/agent/agent_targets.py +877 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/agent/agent_workspace.py +770 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/agent/feature_baseline.py +150 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/README.md +24 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/axe-core/LICENSE-3RD-PARTY.txt +66 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/axe-core/LICENSE.txt +362 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/axe-core/UPSTREAM.md +10 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/axe-core/axe.min.js +12 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/bugx-avatar-1024.png +0 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/bugx-avatar-512.png +0 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/bugx-avatar-tight.svg +23 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/bugx-avatar.svg +28 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/bugx-hero-cn.png +0 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/bugx-hero-en.png +0 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/bugx-hero-en.svg +74 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/bugx-hero-zh.svg +74 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/codex.png +0 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/dsh.png +0 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/project-layout.md +42 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/assets/zcode.png +0 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/README.md +37 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/data-audit/manifest.json +94 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/data-audit/stages/00-scope.md +14 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/data-audit/stages/10-schema-inventory.md +14 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/data-audit/stages/20-query-and-integrity.md +14 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/data-audit/stages/80-evidence-regression.md +14 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/desktop-audit/manifest.json +123 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/desktop-audit/stages/00-scope.md +15 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/desktop-audit/stages/10-process-model.md +14 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/desktop-audit/stages/20-package-integrity.md +15 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/desktop-audit/stages/30-ui-behavior.md +14 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/desktop-audit/stages/80-evidence-regression.md +15 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/memory-testing.md +227 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/manifest.json +155 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/modules/android.md +19 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/modules/h5.md +18 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/modules/ios.md +25 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/modules/miniprogram.md +26 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/modules/webview.md +18 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/stages/00-scope.md +14 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/stages/10-platform-inventory.md +14 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/stages/20-masvs-static.md +20 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/stages/30-component-exposure.md +14 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/stages/40-device-behavior.md +14 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/mobile-audit/stages/80-evidence-regression.md +13 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/native-audit/manifest.json +127 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/native-audit/stages/00-scope.md +14 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/native-audit/stages/10-static-white-box.md +14 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/native-audit/stages/20-memory-concurrency.md +15 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/native-audit/stages/30-behavior-black-box.md +39 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/native-audit/stages/80-evidence-regression.md +14 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/platform-testing.md +174 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/manifest.json +191 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/modules/graphql.md +5 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/modules/h5.md +18 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/modules/multi-tenant.md +4 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/modules/oauth.md +4 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/modules/upload.md +4 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/modules/websocket.md +4 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/stages/00-scope.md +13 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/stages/10-discovery.md +13 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/stages/20-auth-session.md +13 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/stages/30-authz-business.md +13 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/stages/40-input-output.md +13 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/stages/50-state-async.md +13 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/stages/60-file-ssrf-deser.md +12 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/stages/70-config-dependency.md +12 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/audit_packs/web-audit/stages/80-evidence-regression.md +12 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/INTERFACE.md +61 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/README.md +58 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/SPEC.md +25 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/__init__.py +109 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/attack_graph.py +1096 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/attack_graph_store.py +1868 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/audit_campaign.py +1232 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/behavior_graph.py +465 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/ghsa_advisories.py +174 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/models.py +93 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/mutator.py +87 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/patcher.py +126 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/scout.py +278 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/synthesizer.py +207 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/autonomous_cve/verifier.py +103 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/bugx.md +1299 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/bugx_paths.py +1881 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/cli-help.txt +66 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/INTERFACE.md +32 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/README.md +62 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/SPEC.md +25 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/__init__.py +23 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/auto_sync.py +398 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/cloud_client.py +1218 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/cloud_onboard.py +743 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/cloud_schema.py +648 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/consent.py +81 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/device_identity.py +307 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/endpoint_router.py +415 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/flywheel_client.py +769 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/network_transport.py +296 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/onboard_wizard.py +493 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/sensitive_filter.py +285 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/sync_pull.py +695 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/cloud_sync/sync_push.py +723 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/contracts/AGENT_GUIDE.md +359 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/contracts/README.md +34 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/contracts/bugx-blackbox.md +541 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/contracts/bugx-opencode.md +469 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/contracts/bugx-quick.md +44 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/contracts/bugx-runtime-contract.md +353 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/contracts/bugx-worker.md +470 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/contracts/engine_gap_contracts.py +473 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/README.md +70 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/__init__.py +106 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_ai_review.py +185 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_backfill.py +54 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_bootstrap.py +713 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_business.py +36 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_cli.py +715 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_discovery.py +1429 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_evidence.py +1024 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_forensics.py +124 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_gate.py +277 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_intelligence.py +734 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_manifest.py +396 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_platform.py +77 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/coverage_validate.py +241 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/coverage/module_coverage.py +157 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/dev_harness/INTERFACE.md +20 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/dev_harness/README.md +21 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/dev_harness/SPEC.md +25 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/dev_harness/__init__.py +5 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/dev_harness/interaction_preset.py +408 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/engine-integrity.json +2797 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/fuzzing/README.md +49 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/fuzzing/__init__.py +82 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/fuzzing/concurrency_fuzzer.py +435 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/fuzzing/differential_oracle.py +1164 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/fuzzing/fuzz_input.py +1291 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/fuzzing/stateful_fuzzer.py +404 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/governance/README.md +61 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/governance/__init__.py +130 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/governance/capacity_planner.py +124 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/governance/dependency_lock.py +317 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/governance/goal_governor.py +754 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/governance/guide_budget.py +458 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/governance/lockdown.sh +50 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/governance/readonly_enforcer.py +154 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/governance/runtime_tool_gate.py +373 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/governance/secret_redactor.py +784 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/governance/token_budget.py +38 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/INTERFACE.md +36 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/README.md +51 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/SPEC.md +25 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/__init__.py +121 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/base.py +111 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/claude.py +99 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/cline.py +298 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/codex.py +300 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/dsh.py +106 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/opencode.py +209 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/pi.py +94 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_acp/zcode.py +99 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/INTERFACE.md +24 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/README.md +62 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/SPEC.md +25 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/__init__.py +21 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/adapters.py +412 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/autonomous_runner.py +1152 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/cline.py +448 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/common.py +103 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/free_models.py +786 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/host_bootstrap.py +389 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/host_evaluators.py +761 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/host_probe.py +41 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/host_provider_arbitrator.py +831 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/host_registry.py +662 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/host_usage.py +127 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/mcp_process_tracker.py +509 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/mcp_registry_gate.py +379 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/pi.py +102 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/host_runtime/provider_facts.py +66 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/INTERFACE.md +51 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/README.md +67 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/SPEC.md +25 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/__init__.py +140 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/_base_usage.py +152 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/_codex_usage.py +297 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/_dsh_usage.py +184 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/_mcp_toml.py +365 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/_zcode_usage.py +269 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/base.py +479 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/claude.py +212 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/cline.py +229 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/codex.py +1006 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/dsh.py +526 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/opencode.py +358 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/pi.py +308 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/hosts/zcode.py +219 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/i18n.py +252 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/infra/README.md +41 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/infra/__init__.py +17 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/infra/build_info.py +105 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/infra/client_metadata.py +185 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/infra/json_utils.py +22 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/infra/python_runtime.py +540 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/infra/safe_xml.py +221 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_bugx.py +118 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/INTERFACE.md +31 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/README.md +106 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/SPEC.md +25 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/__init__.py +29 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/candidate_revalidation.py +484 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/common.py +1060 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/finding_confirm_phase.py +391 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/finding_settlement.py +1432 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/findings_adjudication.py +666 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/findings_snapshot.py +357 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/judge_phase.py +848 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/lesson_context.py +536 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/lifecycle_reporter.py +627 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/orchestrator_controls.py +686 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/post_commit.py +567 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/post_coverage_sync.py +598 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/post_dry_run.py +817 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/post_observability.py +367 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/post_phase.py +1223 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/post_receipt.py +373 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/post_round_lifecycle.py +786 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/pre_phase.py +1029 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/pre_recon_scout.py +879 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/pre_state_builder.py +1133 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/report_sharing.py +414 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/round_orchestrator.py +1116 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/session_runtime.py +1670 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/startup_gates.py +1050 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/startup_interaction.py +1003 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/startup_version_gate.py +879 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/supervisor_bridge.py +1253 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/supervisor_coverage.py +423 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/supervisor_degraded.py +1211 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/worker_barriers.py +424 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/worker_orchestrator.py +1246 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/launch_phases/worker_prior.py +749 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/INTERFACE.md +35 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/README.md +160 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/SPEC.md +25 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/__init__.py +67 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/_facade.py +227 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/archive_ops.py +630 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/auto_materialization.py +459 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/bug-log.md +22 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/cli.py +275 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/export_ops.py +554 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/finding_confirmation.py +1316 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/finding_io.py +299 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/finding_lifecycle.py +730 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/finding_verification.py +405 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/incidents.py +1005 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/lesson-replay-cases.json +20 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/lesson_ledger.py +241 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/lesson_replay.py +272 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/life_ledger.py +668 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/mistake-book.md +130 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/patterns.py +684 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/receipt_contract.py +269 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/schema.py +1192 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/sync_ops.py +940 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/tool_experience.py +683 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/ledger/verify_life.py +1597 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/lesson-ledger.json +275 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/locales/README.md +19 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/locales/en-US.json +462 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/locales/zh-CN.json +462 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/INTERFACE.md +75 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/README.md +62 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/SPEC.md +25 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/__init__.py +128 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/base.py +717 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/channel_lifecycle.py +751 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/graph_handlers.py +222 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/knowledge_handlers.py +536 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/mining_handlers.py +586 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/resource_prompt_table.py +116 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/retrieval_handlers.py +249 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/rpc_server.py +470 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/supervisor_handlers.py +1461 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/telemetry_handlers.py +227 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_handlers/tool_table.py +1030 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_runtime_support/README.md +21 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_runtime_support/__init__.py +1 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_runtime_support/common.py +363 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_runtime_support/environment.py +567 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/mcp_runtime_support/verifier.py +758 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/metadata.txt +4 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/README.md +157 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/__init__.py +242 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/capability_plan.py +187 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/capability_planner.py +195 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/domain_archetype.py +542 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/domain_router.py +269 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/dynamic_flow_analyzer.py +533 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/impact_pruner.py +435 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/intent_adjudicator.py +175 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/judge_pipeline.py +1246 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/logic_analysis.py +419 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/prompt_harness.py +1704 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/source_inspector.py +267 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/spec_harvester.py +449 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/target_sandbox_manager.py +573 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/test_capability_verifier.py +1364 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/tools-kb.md +38 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/planning/unit_kind.py +122 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/INTERFACE.md +83 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/README.md +51 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/SPEC.md +36 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/__init__.py +76 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/android_probe.py +552 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/base.py +147 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/codebase_memory_probe.py +647 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/desktop_probe.py +342 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/differential_probe.py +434 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/efficiency_probe.py +232 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/ios_binary_probe.py +472 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/memory_probe.py +392 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/miniprogram_probe.py +385 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/mobile_probe.py +466 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/native_probe.py +302 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/openwiki_probe.py +263 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/pattern_probe.py +453 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/platform_probe.py +424 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/probe_registry.py +1770 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/sast_fixture_corpus.py +340 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/sast_probe.py +1510 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/sast_rules.py +1481 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/sca_scanner.py +779 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/ui_accessibility.py +149 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/ui_audit.py +513 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/ui_contract.py +273 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/ui_evidence.py +212 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/ui_measurements.py +314 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/ui_repair.py +250 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/ui_review.py +133 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/ui_storybook.py +107 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/ui_tokens.py +185 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/ui_visual_diff.py +131 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/probes/web_probe.py +714 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/project_profiler/INTERFACE.md +62 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/project_profiler/README.md +53 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/project_profiler/SPEC.md +28 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/project_profiler/__init__.py +201 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/project_profiler/arbitrator.py +316 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/project_profiler/constants.py +247 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/project_profiler/detector.py +399 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/project_profiler/extractors.py +836 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/project_profiler/fingerprint.py +116 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/project_profiler/storage.py +258 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/project_profiler/strategy.py +301 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/README.md +35 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/codex_dialog_dispatch.md +9 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/command_routing_en.md +42 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/command_routing_zh.md +42 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/l0_router.md +47 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/rules/anti_patterns.md +16 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/rules/concurrency_rules.md +14 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/rules/memory_leak_rules.md +13 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/rules/prompt_injection_defense.md +13 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/stages/stage_explore.md +31 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/stages/stage_gate.md +43 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/stages/stage_mutate.md +42 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/prompts/stages/stage_repair.md +85 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/README.md +74 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/__init__.py +169 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/fix_watchlist.py +391 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/l7_dynamic.py +418 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/l7_repair_loop.py +462 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/l7_selfcheck.py +862 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/minimize_repro.py +466 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/patch_synthesizer.py +617 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/regression_pack.py +379 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/rsi_fixer.py +910 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/rsi_loop.py +311 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/rsi_repair.py +348 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/rsi_rounds.py +212 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/rsi_scope.py +281 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/self_heal.py +604 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/test_generator.py +1108 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/test_quality_auditor.py +410 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/repair/test_strategy.py +511 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/INTERFACE.md +59 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/README.md +69 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/SPEC.md +28 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/__init__.py +47 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/attestation.py +228 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/authority.py +255 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/finding_report.py +418 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/formal_report_builder.py +924 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/html_renderers.py +696 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/models.py +759 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/pdf_exporter.py +231 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/projects_assets.py +730 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/report_client.py +743 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/report_data_builder.py +388 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/report_share.py +459 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/sast_bridge.py +116 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/server.py +832 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/visual_report_builder.py +796 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/web-conformance.md +168 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/web_conformance.py +428 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/report_engine/workbench_assets.py +484 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/INTERFACE.md +20 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/README.md +161 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/SPEC.md +25 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/__init__.py +3 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/code_analyzer.py +1720 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/codebase_memory_bridge.py +337 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/context_assembler.py +240 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/corpus_fetch.py +369 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/graph_ego.py +597 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/knowledge_auto.py +662 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/knowledge_sources.py +168 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/knowledge_sync.py +1003 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/memory_store.py +480 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/query_planner.py +1020 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/rrf_engine.py +137 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/slice_extractor.py +1209 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/slice_normalizer.py +373 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/slice_spec.py +357 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/symbol_index.py +1151 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/universal_code_matcher.py +622 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/xerj_bridge.py +476 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/retrieval/xerj_supervisor.py +362 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/README.md +33 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/ios/PROVENANCE.json +30 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/ios/crypto.yaml +36 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/ios/network.yaml +20 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/ios/resilience.yaml +47 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/ios/storage.yaml +48 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/LICENSE +173 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/PROVENANCE.json +270 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-asymmetric-key-pair-used-for-multiple-purposes.yml +13 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-backup-manifest.yml +24 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-biometric-event-bound.yml +49 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-biometric-invalidated-enrollment.yml +11 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-biometric-no-confirmation-required.yml +10 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-biometric-validity-duration.yml +24 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-broken-encryption-algorithms.yaml +9 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-broken-encryption-modes.yaml +13 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-content-provider-exported.yml +35 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-custom-deeplink-scheme.yml +29 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-dangerous-app-permissions.yaml +65 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-data-unencrypted-shared-storage-no-user-interaction-apis.yml +36 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-data-unencrypted-shared-storage-no-user-interaction-manifest.yml +15 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-debuggable-flag.yml +10 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-debugger-checks.yml +12 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-deeplink-autoverify-missing.yml +33 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-deeplink-unvalidated-parameter.yml +11 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-device-passcode-present.yml +17 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-fileprovider-broad-scope.yml +46 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-hardcoded-crypto-keys-usage.yml +14 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-hardcoded-security-provider.yaml +18 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-implicit-intent-internal-communication.yml +30 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-implicit-intent-leaking-extras.yml +29 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-input-field-usage.yml +11 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-key-generation-with-insufficient-key-length.yml +21 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-keyboard-cache-input-types.yml +10 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-local-storage-input-validation.yml +48 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-native-debugger-checks.yml +12 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-network-checkservertrusted.yml +12 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-network-hostname-verification.yml +11 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-network-insecure-trust-anchors.yml +11 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-network-onreceivedsslerror.yml +12 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-non-random-use.yml +16 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-object-deserialization.yml +14 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-overlay-protection.yml +68 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-pendingintent-mutable.yml +39 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-random-apis-insufficient-entropy.yml +17 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-root-detection.yaml +59 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-sdk-version.yml +10 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-sensitive-data-in-notifications-manifest.yml +17 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-sensitive-data-in-notifications.yml +11 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-sensitive-data-in-screenshot.yml +18 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-sql-injection-contentprovider.yml +17 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-ssl-socket-hostnameverifier.yml +15 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-strictmode.yml +10 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-system-alert-window.yml +9 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-webview-allow-local-access.yml +15 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-webview-bridges.yml +28 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-webview-safebrowsing.yml +20 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mastg/mastg-android-webview-url-handlers.yml +41 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/miniprogram/PROVENANCE.json +26 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/miniprogram/network.yaml +37 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/miniprogram/platform.yaml +36 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/miniprogram/storage.yaml +48 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/LICENSE +165 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/PROVENANCE.json +58 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/auth.yaml +59 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/crypto.yaml +66 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/jailbreak.yaml +14 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/keyboard.yaml +34 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/logging.yaml +23 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/network.yaml +55 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/resilience.yaml +29 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/secrets.yaml +33 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/storage.yaml +29 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/rules/mobsfscan-swift/webview.yaml +32 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/README.md +198 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/__init__.py +3 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/bugx_logging.py +1464 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/daemon_runner.py +623 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/fixture_solidify.py +444 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/global_telemetry.py +549 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/incident_eval.py +148 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/interaction.py +605 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/interaction_store.py +435 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/interactive_menu.py +95 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/log_analytics.py +922 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/mining_quality_framework.py +1387 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/model_runner.py +732 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/platform_adapter.py +579 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/prep_validate.py +478 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/project_graph.py +827 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/project_init.py +481 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/project_profile.py +224 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/project_settings.py +964 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/provider_window.py +97 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/resume_ticket.py +115 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/scenario_eval.py +856 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/seed_drill.py +549 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/self_audit.py +550 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/session_profile.py +205 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/setup_ui_env.py +229 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/startup_environment.py +859 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/sync_store.py +1421 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/runtime/tool_install_targets.py +18 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/schemas/README.md +35 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/schemas/agent-graph.schema.json +368 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/schemas/attack-graph.schema.json +88 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/schemas/evidence-bundle.schema.json +33 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/schemas/skill-pack.schema.json +230 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/schemas/worker-checkpoint.schema.json +119 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/secure_atomic.py +289 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/README.md +55 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/c.txt +29 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/cpp.txt +32 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/css.txt +70 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/go.txt +46 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/java.txt +30 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/javascript.txt +55 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/kotlin.txt +28 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/python.txt +71 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/rust.txt +53 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/swift.txt +29 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/seed_corpus/typescript.txt +29 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/skills/README.md +53 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/skills/__init__.py +189 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/skills/bugx_docs_mcp_server.py +418 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/skills/bugx_mcp_server.py +1161 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/skills/mcp_runtime.py +968 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/skills/mcp_session_proof.py +605 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/skills/mobile_ui_inspector.py +405 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/skills/skill_pack.py +1214 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/skills/skill_synthesizer.py +1153 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/skills/tools_kb.py +313 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/INTERFACE.md +121 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/README.md +209 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/SPEC.md +25 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/__init__.py +175 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/audit_supervisor.py +1015 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/budget_governor.py +1254 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/checkpoint_handler.py +368 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/checkpoint_pipeline.py +1564 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/checkpoint_sync.py +653 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/claim_events.py +74 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/claim_sync.py +590 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/cli.py +812 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/context_sync.py +55 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/coverage_sync.py +115 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/finding_commit.py +470 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/finding_sync.py +688 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/finding_workflow.py +676 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/finish_policy.py +224 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/finish_sync.py +185 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/graph_sync.py +669 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/lease_manager.py +788 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/lifecycle_blocks.py +129 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/next_round_sync.py +126 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/observability.py +140 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/recovery_sync.py +165 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/rejection_remedies.py +355 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/round_governor.py +306 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/serial_authorization.py +544 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/start_sync.py +87 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/state_store.py +249 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/supervisor_host.py +511 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/supervisor_models.py +1143 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/systemic_failure.py +104 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/task_scheduler.py +1640 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/worker_checkpoint.py +230 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/worker_execution.py +265 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/worker_handoff.py +192 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/worker_lifecycle.py +396 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/worker_runtime.py +1005 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor/worker_sync.py +89 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor_types/README.md +36 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor_types/__init__.py +0 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor_types/exceptions.py +52 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor_types/graph_models.py +357 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor_types/path_containment.py +151 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor_types/target_fingerprint.py +310 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/supervisor_types/worker_claim.py +411 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/INTERFACE.md +50 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/README.md +57 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/SPEC.md +26 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/__init__.py +11 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/adapters/__init__.py +27 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/adapters/base.py +87 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/adapters/bugx.py +102 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/adapters/claude.py +222 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/adapters/cline.py +407 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/adapters/codex.py +260 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/adapters/dsh.py +177 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/adapters/opencode.py +218 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/adapters/pi.py +272 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/adapters/registry.py +100 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/adapters/zcode.py +312 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/api_routes_post.py +668 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/dispatcher.py +1376 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/docs_session_service.py +473 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/handler.py +674 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/ide_cloud_service.py +526 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/mcp_inspector.py +1747 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/00-base.css +1060 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/01-monitoring.css +802 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/02-header-actions.css +321 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/03-trigger-popover.css +697 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/04-composer.css +628 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/05-skills-center.css +878 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/06-mcp-center.css +623 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/07-skill-detail.css +265 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/08-files-management.css +167 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/09-files-center.css +386 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/10-icons.css +105 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/11-project-options.css +185 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/12-profile-tab.css +383 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/index-CXAsl8mr.js +333 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/index-DHQUtWtx.css +1 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-cyrillic-400-normal-B8Z6Jvzv.woff +0 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-cyrillic-400-normal-C44pakCn.woff2 +0 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-cyrillic-500-normal-Bb4u56_6.woff +0 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-cyrillic-500-normal-BdVUvljg.woff2 +0 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-cyrillic-ext-400-normal-CWV284fw.woff2 +0 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-cyrillic-ext-400-normal-DLkyKLvH.woff +0 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-cyrillic-ext-500-normal-8-8HP2PF.woff +0 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-cyrillic-ext-500-normal-DaDZE_Na.woff2 +0 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-greek-400-normal-BccYJ-vZ.woff +0 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-greek-400-normal-Cw5-AHNN.woff2 +0 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-greek-500-normal-By8GFJzz.woff2 +0 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-greek-500-normal-z-Q6FFuG.woff +0 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-latin-400-normal-DJ5YJwmz.woff2 +0 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-latin-400-normal-Dn3IlU-Z.woff +0 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-latin-500-normal-CUHe9xxf.woff2 +0 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-latin-500-normal-DVVamBqs.woff +0 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-latin-ext-400-normal-CEpydyUl.woff +0 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-latin-ext-400-normal-Cp7z-ARB.woff2 +0 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-latin-ext-500-normal-BYjRCDVy.woff2 +0 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-latin-ext-500-normal-D-qasQTj.woff +0 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-vietnamese-400-normal-BbG3LG1A.woff2 +0 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-vietnamese-400-normal-DR1UuFon.woff +0 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-vietnamese-500-normal-8N8MYVKB.woff +0 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/assets/source-serif-4-vietnamese-500-normal-Bi3OSTTW.woff2 +0 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/design-tokens.css +113 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/favicon.png +0 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/icon-192.png +0 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/index.html +55 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/manifest.webmanifest +19 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/project-settings.js +9602 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/static/sw.js +8 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/core/webui/workspace_service.py +218 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/dsh/agents/bugx.md +27 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/dsh/dsh-patch.yml +18 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/dsh/mcp/cordis.patch.yml +4 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/dsh/mcp/index.js +219 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/dsh/mcp/package.json +28 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/dsh/skills/bugx/SKILL.md +70 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/dsh/skills/bugx-dsh/SKILL.md +229 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/dsh/ui/client.js +87 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/dsh/ui/cordis.patch.yml +4 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/dsh/ui/index.js +7 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/dsh/ui/package.json +27 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/mcp-lock.json +3075 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/opencode.json +129 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/pi/extensions/bugx/README.md +12 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/pi/extensions/bugx/index.ts +299 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/pi/extensions/bugx/manifest.json +11 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/pi/skills/bugx/SKILL.md +69 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/plugins/bugx/skills/bugx-claude/SKILL.md +326 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/plugins/bugx/skills/bugx-opencode/SKILL.md +129 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/plugins/bugx/skills/bugx-zcode/SKILL.md +459 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/workbuddy/connector-meta.json +19 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/workbuddy/icon.png +0 -0
- bugx_cli-0.1.1.data/data/share/bugx-agent/workbuddy/skills/bugx/SKILL.md +70 -0
- bugx_cli-0.1.1.dist-info/METADATA +335 -0
- bugx_cli-0.1.1.dist-info/RECORD +762 -0
- bugx_cli-0.1.1.dist-info/WHEEL +5 -0
- bugx_cli-0.1.1.dist-info/entry_points.txt +2 -0
- bugx_cli-0.1.1.dist-info/licenses/LICENSE +55 -0
- bugx_cli-0.1.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,2567 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import base64
|
|
5
|
+
import copy
|
|
6
|
+
import csv
|
|
7
|
+
import hashlib
|
|
8
|
+
import importlib.metadata
|
|
9
|
+
import io
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import re
|
|
13
|
+
import shutil
|
|
14
|
+
import signal
|
|
15
|
+
import stat
|
|
16
|
+
import subprocess
|
|
17
|
+
import sys
|
|
18
|
+
import sysconfig
|
|
19
|
+
import tempfile
|
|
20
|
+
import time
|
|
21
|
+
import urllib.error
|
|
22
|
+
import urllib.parse
|
|
23
|
+
import urllib.request
|
|
24
|
+
from pathlib import Path, PurePosixPath
|
|
25
|
+
from typing import Any
|
|
26
|
+
|
|
27
|
+
from .. import __build_id__, __version__
|
|
28
|
+
from ..common import *
|
|
29
|
+
from ..infra import _abandoned_mcp_processes, _layout_module
|
|
30
|
+
from ..infra.engine_installer import (
|
|
31
|
+
MissingAgentAssetError,
|
|
32
|
+
_engine_build_id,
|
|
33
|
+
_engine_install_lock,
|
|
34
|
+
_engine_self_integrity,
|
|
35
|
+
resolve_engine_file,
|
|
36
|
+
)
|
|
37
|
+
from ..infra.security import _assert_no_symlink_components
|
|
38
|
+
from .cloud import _supervisor_deploy, _supervisor_status
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
_COMPLETION_CHILDREN = {
|
|
42
|
+
"auth": ("login", "status", "set-key", "logout"),
|
|
43
|
+
"cloud": (
|
|
44
|
+
"config", "status", "log-report", "feedback", "sync", "export",
|
|
45
|
+
"upload", "conflicts", "projects", "devices", "onboard",
|
|
46
|
+
),
|
|
47
|
+
"completion": ("bash", "zsh", "fish"),
|
|
48
|
+
"hosts": ("--json", "--root"),
|
|
49
|
+
"install": ("--agent", "--allow-missing", "--force", "--json", "--non-interactive", "--root"),
|
|
50
|
+
"autonomous": ("--agent-timeout", "--host", "--json", "--max-turns", "--max-wall-time", "--root"),
|
|
51
|
+
"skill": ("list", "status", "validate", "rollback"),
|
|
52
|
+
"update": ("--allow-downgrade", "--channel", "--check", "--force", "--repair-assets", "--root"),
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
_ASSET_REPAIR_ATTEMPT_ENV = "BUGX_ASSET_REPAIR_ATTEMPTED"
|
|
56
|
+
# Stable package recovery is a separate trust path from the user's configurable
|
|
57
|
+
# knowledge/sync endpoint. Keep it pinned to the production release service.
|
|
58
|
+
_STABLE_AGENT_RELEASE_BASE = "https://bugx.dev"
|
|
59
|
+
_STABLE_AGENT_PYPI_JSON = "https://pypi.org/pypi/bugx-cli/json"
|
|
60
|
+
_STABLE_AGENT_PYPI_HOST = "pypi.org"
|
|
61
|
+
_STABLE_AGENT_FILES_HOST = "files.pythonhosted.org"
|
|
62
|
+
_MAX_PYPI_METADATA_BYTES = 4 * 1024 * 1024
|
|
63
|
+
_MAX_PYPI_WHEEL_BYTES = 128 * 1024 * 1024
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def command_completion(args: argparse.Namespace) -> int:
|
|
67
|
+
"""Print a small, dependency-free shell completion script."""
|
|
68
|
+
commands = tuple(getattr(args, "completion_commands", ()))
|
|
69
|
+
if not commands:
|
|
70
|
+
commands = (
|
|
71
|
+
"auth", "autonomous", "cloud", "completion", "daemon", "doctor", "dsh", "help", "hosts",
|
|
72
|
+
"init", "install", "knowledge", "lesson", "log", "logic-analysis",
|
|
73
|
+
"mcp", "mcp-runtime", "mining-audit", "patch-forge", "plugin", "probe",
|
|
74
|
+
"project", "reset", "self-audit", "skill", "stats", "supervisor", "test-audit",
|
|
75
|
+
"test-generate", "test-verify", "uninstall", "update",
|
|
76
|
+
)
|
|
77
|
+
words = " ".join(commands)
|
|
78
|
+
children = {name: " ".join(values) for name, values in _COMPLETION_CHILDREN.items()}
|
|
79
|
+
shell = args.shell
|
|
80
|
+
if shell == "bash":
|
|
81
|
+
print(f'''_bugx_complete() {{
|
|
82
|
+
local cur="${{COMP_WORDS[COMP_CWORD]}}"
|
|
83
|
+
local cmd="${{COMP_WORDS[1]:-}}"
|
|
84
|
+
local words="{words}"
|
|
85
|
+
if [[ "$COMP_CWORD" -eq 1 ]]; then
|
|
86
|
+
COMPREPLY=( $(compgen -W "$words" -- "$cur") )
|
|
87
|
+
return
|
|
88
|
+
fi
|
|
89
|
+
case "$cmd" in
|
|
90
|
+
auth) words="{children['auth']}" ;;
|
|
91
|
+
cloud) words="{children['cloud']}" ;;
|
|
92
|
+
completion) words="{children['completion']}" ;;
|
|
93
|
+
hosts) words="{children['hosts']}" ;;
|
|
94
|
+
install) words="{children['install']}" ;;
|
|
95
|
+
autonomous) words="{children['autonomous']}" ;;
|
|
96
|
+
skill) words="{children['skill']}" ;;
|
|
97
|
+
update) words="{children['update']}" ;;
|
|
98
|
+
*) return ;;
|
|
99
|
+
esac
|
|
100
|
+
COMPREPLY=( $(compgen -W "$words" -- "$cur") )
|
|
101
|
+
}}
|
|
102
|
+
complete -F _bugx_complete bugx''')
|
|
103
|
+
elif shell == "zsh":
|
|
104
|
+
command_items = " ".join(f"'{item}'" for item in commands)
|
|
105
|
+
print(f'''#compdef bugx
|
|
106
|
+
_bugx() {{
|
|
107
|
+
local -a commands
|
|
108
|
+
commands=({command_items})
|
|
109
|
+
_arguments '1:command:->command' '*::arg:->args'
|
|
110
|
+
case $state in
|
|
111
|
+
command) _describe 'command' commands ;;
|
|
112
|
+
args)
|
|
113
|
+
case $words[2] in
|
|
114
|
+
auth) _describe 'auth action' ({children['auth'].replace(' ', ' ')}) ;;
|
|
115
|
+
cloud) _describe 'cloud command' ({children['cloud']}) ;;
|
|
116
|
+
completion) _describe 'shell' ({children['completion']}) ;;
|
|
117
|
+
hosts) _describe 'option' ({children['hosts']}) ;;
|
|
118
|
+
install) _describe 'option' ({children['install']}) ;;
|
|
119
|
+
autonomous) _describe 'option' ({children['autonomous']}) ;;
|
|
120
|
+
skill) _describe 'skill action' ({children['skill']}) ;;
|
|
121
|
+
update) _describe 'option' ({children['update']}) ;;
|
|
122
|
+
esac
|
|
123
|
+
;;
|
|
124
|
+
esac
|
|
125
|
+
}}
|
|
126
|
+
_bugx''')
|
|
127
|
+
elif shell == "fish":
|
|
128
|
+
print(f'''complete -c bugx -f -n '__fish_use_subcommand' -a '{words}'
|
|
129
|
+
complete -c bugx -f -n '__fish_seen_subcommand_from auth' -a '{children['auth']}'
|
|
130
|
+
complete -c bugx -f -n '__fish_seen_subcommand_from cloud' -a '{children['cloud']}'
|
|
131
|
+
complete -c bugx -f -n '__fish_seen_subcommand_from completion' -a '{children['completion']}'
|
|
132
|
+
complete -c bugx -f -n '__fish_seen_subcommand_from hosts' -a '{children['hosts']}'
|
|
133
|
+
complete -c bugx -f -n '__fish_seen_subcommand_from install' -a '{children['install']}'
|
|
134
|
+
complete -c bugx -f -n '__fish_seen_subcommand_from autonomous' -a '{children['autonomous']}'
|
|
135
|
+
complete -c bugx -f -n '__fish_seen_subcommand_from skill' -a '{children['skill']}'
|
|
136
|
+
complete -c bugx -f -n '__fish_seen_subcommand_from update' -a '{children['update']}' ''')
|
|
137
|
+
else: # argparse choices make this unreachable; keep the handler safe for embedding.
|
|
138
|
+
raise CliError(f"不支持的 shell: {shell}")
|
|
139
|
+
return 0
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _print_version_tls_hint(error: object) -> None:
|
|
143
|
+
text = str(error)
|
|
144
|
+
if "CERTIFICATE_VERIFY_FAILED" in text or "certificate verify failed" in text.lower():
|
|
145
|
+
print(
|
|
146
|
+
"[update] TLS 证书校验失败;内网或自签 CA 可设置 "
|
|
147
|
+
"BUGX_CA_BUNDLE=/path/to/ca.pem 后重试"
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _update_channel(args: argparse.Namespace) -> str:
|
|
152
|
+
channel = str(getattr(args, "channel", "") or "").strip()
|
|
153
|
+
if channel:
|
|
154
|
+
return channel
|
|
155
|
+
try:
|
|
156
|
+
from core.infra.client_metadata import release_channel
|
|
157
|
+
|
|
158
|
+
return release_channel()
|
|
159
|
+
except (ImportError, OSError, ValueError):
|
|
160
|
+
return "stable"
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def command_version_check(args: argparse.Namespace) -> int:
|
|
164
|
+
"""bugx update --check:向服务端查询最新版本,提示更新。
|
|
165
|
+
|
|
166
|
+
不执行更新,只输出版本信息和建议。退出码:
|
|
167
|
+
0 = 已最新或无需更新
|
|
168
|
+
1 = 有更新可用
|
|
169
|
+
2 = 检查失败(网络不可达等)
|
|
170
|
+
"""
|
|
171
|
+
if not getattr(args, "check", False):
|
|
172
|
+
# 仅供内部复用;公共入口是 bugx update --check。
|
|
173
|
+
print(f"BugX CLI v{__version__}")
|
|
174
|
+
return 0
|
|
175
|
+
if os.environ.get("BUGX_DISABLE_VERSION_CHECK", "").lower() in {"1", "true", "yes"}:
|
|
176
|
+
print("[update] 版本检查已由 BUGX_DISABLE_VERSION_CHECK 禁用")
|
|
177
|
+
return 0
|
|
178
|
+
|
|
179
|
+
try:
|
|
180
|
+
_ensure_core_importable()
|
|
181
|
+
from core.cloud_sync.cloud_client import CloudClient
|
|
182
|
+
except Exception as exc: # noqa: BLE001
|
|
183
|
+
print(f"[update] 依赖加载失败: {exc}")
|
|
184
|
+
return 2
|
|
185
|
+
|
|
186
|
+
client = CloudClient()
|
|
187
|
+
channel = _update_channel(args)
|
|
188
|
+
try:
|
|
189
|
+
result = client.check_version(current_version=__version__, channel=channel)
|
|
190
|
+
except Exception as exc: # noqa: BLE001
|
|
191
|
+
print(f"[update] 版本检查失败: {exc}")
|
|
192
|
+
_print_version_tls_hint(exc)
|
|
193
|
+
return 2
|
|
194
|
+
|
|
195
|
+
if not result.ok:
|
|
196
|
+
# 网络不可达时静默提示,不阻断
|
|
197
|
+
err = getattr(result, "error", "") or "未知错误"
|
|
198
|
+
print(f"[update] 无法检查更新: {err}")
|
|
199
|
+
_print_version_tls_hint(err)
|
|
200
|
+
print("[update] 可使用 BUGX_DISABLE_VERSION_CHECK=1 跳过启动时检查")
|
|
201
|
+
return 2
|
|
202
|
+
|
|
203
|
+
data = result.data if isinstance(result.data, dict) else {}
|
|
204
|
+
info = data.get("data") if isinstance(data.get("data"), dict) else data
|
|
205
|
+
latest = str(info.get("latest_version") or "").strip()
|
|
206
|
+
min_client = str(info.get("min_client_version") or "").strip()
|
|
207
|
+
notes = str(info.get("release_notes") or "")
|
|
208
|
+
current_version = _release_version_tuple(__version__)
|
|
209
|
+
latest_version = _release_version_tuple(latest)
|
|
210
|
+
min_version = _release_version_tuple(min_client) if min_client else None
|
|
211
|
+
metadata_error = None
|
|
212
|
+
if current_version is None or latest_version is None:
|
|
213
|
+
metadata_error = f"服务端返回了无效版本号: {latest!r}"
|
|
214
|
+
elif latest_version < current_version:
|
|
215
|
+
metadata_error = f"服务端版本 {latest} 低于当前版本 {__version__}"
|
|
216
|
+
elif min_client and min_version is None:
|
|
217
|
+
metadata_error = f"服务端返回了无效最低兼容版本: {min_client!r}"
|
|
218
|
+
elif min_version is not None and min_version > latest_version:
|
|
219
|
+
metadata_error = (
|
|
220
|
+
f"服务端版本元数据矛盾:最低兼容版本 {min_client} 高于发布版本 {latest}"
|
|
221
|
+
)
|
|
222
|
+
if metadata_error:
|
|
223
|
+
if getattr(args, "json", False):
|
|
224
|
+
payload = dict(info)
|
|
225
|
+
payload["error"] = metadata_error
|
|
226
|
+
print(json.dumps(payload, ensure_ascii=False, indent=2))
|
|
227
|
+
else:
|
|
228
|
+
print(f"[update] {metadata_error}")
|
|
229
|
+
return 2
|
|
230
|
+
|
|
231
|
+
update_available = (info.get("update_available") is True
|
|
232
|
+
or latest_version > current_version)
|
|
233
|
+
update_required = (info.get("update_required") is True
|
|
234
|
+
or (min_version is not None and current_version < min_version))
|
|
235
|
+
|
|
236
|
+
if getattr(args, "json", False):
|
|
237
|
+
print(json.dumps(info, ensure_ascii=False, indent=2))
|
|
238
|
+
return 0
|
|
239
|
+
|
|
240
|
+
print(f"当前版本: {__version__}")
|
|
241
|
+
if latest:
|
|
242
|
+
print(f"最新版本: {latest}")
|
|
243
|
+
if min_client:
|
|
244
|
+
print(f"最低兼容: {min_client}")
|
|
245
|
+
if notes:
|
|
246
|
+
print(f"变更说明: {notes}")
|
|
247
|
+
|
|
248
|
+
if update_required:
|
|
249
|
+
print(f"\n⚠ 当前版本 {__version__} 低于最低兼容版本 {min_client},必须更新!")
|
|
250
|
+
print("执行以下命令更新:")
|
|
251
|
+
print(" bugx update")
|
|
252
|
+
return 1
|
|
253
|
+
if update_available:
|
|
254
|
+
print(f"\n✦ 发现新版本 {latest},建议执行:bugx update")
|
|
255
|
+
return 1
|
|
256
|
+
|
|
257
|
+
print(f"\n✓ BugX 已是最新版本 ({__version__})")
|
|
258
|
+
return 0
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
RELEASE_VERSION_RE = re.compile(
|
|
262
|
+
r"^(?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)"
|
|
263
|
+
r"(?:(?P<pre>a|b|rc)(?P<pre_num>\d+)|\+[0-9A-Za-z.-]+)?$"
|
|
264
|
+
)
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def _release_version_tuple(value: object) -> tuple[int, int, int, int, int] | None:
|
|
268
|
+
"""Parse the server release contract, including explicit prereleases.
|
|
269
|
+
|
|
270
|
+
The update endpoint uses the compact PEP 440-style prerelease spelling
|
|
271
|
+
``X.Y.ZaN``, ``X.Y.ZbN`` or ``X.Y.ZrcN``. A stable ``X.Y.Z`` release sorts
|
|
272
|
+
after all prereleases of the same base version. No other suffixes are
|
|
273
|
+
accepted so malformed server metadata remains fail-closed.
|
|
274
|
+
"""
|
|
275
|
+
if not isinstance(value, str):
|
|
276
|
+
return None
|
|
277
|
+
match = RELEASE_VERSION_RE.fullmatch(value.strip())
|
|
278
|
+
if match is None:
|
|
279
|
+
return None
|
|
280
|
+
prerelease = match.group("pre")
|
|
281
|
+
stage = {"a": 0, "b": 1, "rc": 2}.get(prerelease, 3)
|
|
282
|
+
number = int(match.group("pre_num")) if prerelease else 0
|
|
283
|
+
return (
|
|
284
|
+
int(match.group("major")),
|
|
285
|
+
int(match.group("minor")),
|
|
286
|
+
int(match.group("patch")),
|
|
287
|
+
stage,
|
|
288
|
+
number,
|
|
289
|
+
)
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
class _RejectReleaseRedirects(urllib.request.HTTPRedirectHandler):
|
|
293
|
+
"""Do not let release metadata redirect recovery requests to another host."""
|
|
294
|
+
|
|
295
|
+
def redirect_request(self, req, fp, code, msg, headers, newurl): # noqa: D102
|
|
296
|
+
return None
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def _validate_official_pypi_url(value: object, *, expected_host: str) -> str:
|
|
300
|
+
url = str(value or "").strip()
|
|
301
|
+
try:
|
|
302
|
+
parsed = urllib.parse.urlsplit(url)
|
|
303
|
+
port = parsed.port
|
|
304
|
+
except (TypeError, ValueError) as exc:
|
|
305
|
+
raise CliError("PyPI 返回了无效的 HTTPS URL") from exc
|
|
306
|
+
if (
|
|
307
|
+
parsed.scheme != "https"
|
|
308
|
+
or parsed.hostname != expected_host
|
|
309
|
+
or parsed.username is not None
|
|
310
|
+
or parsed.password is not None
|
|
311
|
+
or port is not None
|
|
312
|
+
or parsed.query
|
|
313
|
+
or parsed.fragment
|
|
314
|
+
):
|
|
315
|
+
raise CliError(f"PyPI URL 不在固定 HTTPS 主机白名单内:{url[:160]}")
|
|
316
|
+
return url
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def _read_official_pypi_response(
|
|
320
|
+
url: str,
|
|
321
|
+
*,
|
|
322
|
+
expected_host: str,
|
|
323
|
+
accept: str,
|
|
324
|
+
max_bytes: int,
|
|
325
|
+
) -> bytes:
|
|
326
|
+
trusted_url = _validate_official_pypi_url(url, expected_host=expected_host)
|
|
327
|
+
request = urllib.request.Request(
|
|
328
|
+
trusted_url,
|
|
329
|
+
headers={
|
|
330
|
+
"Accept": accept,
|
|
331
|
+
"User-Agent": f"BugX-Client/{__version__} (marker=stable; channel=stable)",
|
|
332
|
+
},
|
|
333
|
+
)
|
|
334
|
+
opener = urllib.request.build_opener(_RejectReleaseRedirects())
|
|
335
|
+
try:
|
|
336
|
+
response = opener.open(request, timeout=15)
|
|
337
|
+
except urllib.error.HTTPError as exc:
|
|
338
|
+
try:
|
|
339
|
+
status = exc.code
|
|
340
|
+
if 300 <= status < 400:
|
|
341
|
+
raise CliError("PyPI 响应试图重定向,已拒绝请求") from exc
|
|
342
|
+
raise CliError(f"PyPI 请求失败:HTTP {status}") from exc
|
|
343
|
+
finally:
|
|
344
|
+
exc.close()
|
|
345
|
+
except Exception as exc: # noqa: BLE001
|
|
346
|
+
raise CliError(f"PyPI 请求失败:{type(exc).__name__}: {exc}") from exc
|
|
347
|
+
|
|
348
|
+
try:
|
|
349
|
+
final_url = str(response.geturl() or "")
|
|
350
|
+
_validate_official_pypi_url(final_url, expected_host=expected_host)
|
|
351
|
+
headers = getattr(response, "headers", None)
|
|
352
|
+
raw_length = headers.get("Content-Length") if headers is not None else None
|
|
353
|
+
if raw_length:
|
|
354
|
+
try:
|
|
355
|
+
content_length = int(raw_length)
|
|
356
|
+
except (TypeError, ValueError) as exc:
|
|
357
|
+
raise CliError("PyPI 响应 Content-Length 无效") from exc
|
|
358
|
+
if content_length < 0 or content_length > max_bytes:
|
|
359
|
+
raise CliError("PyPI 响应超过允许大小")
|
|
360
|
+
data = response.read(max_bytes + 1)
|
|
361
|
+
if len(data) > max_bytes:
|
|
362
|
+
raise CliError("PyPI 响应超过允许大小")
|
|
363
|
+
if raw_length and len(data) != content_length:
|
|
364
|
+
raise CliError("PyPI 响应长度与 Content-Length 不一致")
|
|
365
|
+
return data
|
|
366
|
+
finally:
|
|
367
|
+
response.close()
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def _select_pypi_stable_wheel(payload: object, *, current_version: str) -> dict[str, str]:
|
|
371
|
+
"""Select one non-yanked official pure-Python stable wheel without downgrades."""
|
|
372
|
+
current_order = _release_version_tuple(current_version)
|
|
373
|
+
if current_order is None or current_order[3] != 3:
|
|
374
|
+
raise CliError(f"当前 CLI 版本不是可验证的 stable 版本:{current_version!r}")
|
|
375
|
+
if not isinstance(payload, dict):
|
|
376
|
+
raise CliError("PyPI JSON 根节点格式无效")
|
|
377
|
+
info = payload.get("info")
|
|
378
|
+
releases = payload.get("releases")
|
|
379
|
+
if not isinstance(info, dict) or not isinstance(releases, dict):
|
|
380
|
+
raise CliError("PyPI JSON 缺少 info 或 releases 对象")
|
|
381
|
+
package_name = re.sub(r"[-_.]+", "-", str(info.get("name") or "").strip().lower())
|
|
382
|
+
if package_name != "bugx-cli":
|
|
383
|
+
raise CliError(f"PyPI 返回了错误的发行名:{package_name or '未知'}")
|
|
384
|
+
|
|
385
|
+
candidates: list[tuple[tuple[int, int, int, int, int], dict[str, str]]] = []
|
|
386
|
+
for version, files in releases.items():
|
|
387
|
+
version_text = str(version)
|
|
388
|
+
order = _release_version_tuple(version_text)
|
|
389
|
+
if (
|
|
390
|
+
not re.fullmatch(r"\d+\.\d+\.\d+", version_text)
|
|
391
|
+
or order is None
|
|
392
|
+
or order[3] != 3
|
|
393
|
+
or order < current_order
|
|
394
|
+
or not isinstance(files, list)
|
|
395
|
+
):
|
|
396
|
+
continue
|
|
397
|
+
expected_filename = f"bugx_cli-{version_text}-py3-none-any.whl"
|
|
398
|
+
matching = [
|
|
399
|
+
item for item in files
|
|
400
|
+
if isinstance(item, dict)
|
|
401
|
+
and item.get("packagetype") == "bdist_wheel"
|
|
402
|
+
and item.get("filename") == expected_filename
|
|
403
|
+
]
|
|
404
|
+
eligible: list[dict[str, str]] = []
|
|
405
|
+
for item in matching:
|
|
406
|
+
if item.get("yanked") is not False:
|
|
407
|
+
continue
|
|
408
|
+
digests = item.get("digests")
|
|
409
|
+
digest = str(
|
|
410
|
+
digests.get("sha256") if isinstance(digests, dict) else ""
|
|
411
|
+
).strip().lower()
|
|
412
|
+
if not re.fullmatch(r"[0-9a-f]{64}", digest):
|
|
413
|
+
raise CliError(f"PyPI {expected_filename} 缺少有效 SHA-256")
|
|
414
|
+
url = _validate_official_pypi_url(
|
|
415
|
+
item.get("url"), expected_host=_STABLE_AGENT_FILES_HOST,
|
|
416
|
+
)
|
|
417
|
+
eligible.append({
|
|
418
|
+
"version": version_text,
|
|
419
|
+
"checksum_sha256": digest,
|
|
420
|
+
"url": url,
|
|
421
|
+
"filename": expected_filename,
|
|
422
|
+
})
|
|
423
|
+
if len(eligible) > 1:
|
|
424
|
+
raise CliError(f"PyPI {expected_filename} 存在重复的候选 wheel")
|
|
425
|
+
if eligible:
|
|
426
|
+
candidates.append((order, eligible[0]))
|
|
427
|
+
|
|
428
|
+
if not candidates:
|
|
429
|
+
advertised = str(info.get("version") or "未知")
|
|
430
|
+
raise CliError(
|
|
431
|
+
f"PyPI 没有不低于 CLI {current_version} 的未撤回 stable py3-none-any wheel "
|
|
432
|
+
f"(当前公告版本:{advertised})"
|
|
433
|
+
)
|
|
434
|
+
_, selected = max(candidates, key=lambda item: item[0])
|
|
435
|
+
return selected
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
def _fetch_pypi_stable_wheel(*, current_version: str) -> dict[str, str]:
|
|
439
|
+
raw = _read_official_pypi_response(
|
|
440
|
+
_STABLE_AGENT_PYPI_JSON,
|
|
441
|
+
expected_host=_STABLE_AGENT_PYPI_HOST,
|
|
442
|
+
accept="application/json",
|
|
443
|
+
max_bytes=_MAX_PYPI_METADATA_BYTES,
|
|
444
|
+
)
|
|
445
|
+
try:
|
|
446
|
+
payload = json.loads(raw.decode("utf-8", errors="strict"))
|
|
447
|
+
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
|
|
448
|
+
raise CliError("PyPI stable 发行元数据不是有效 UTF-8 JSON") from exc
|
|
449
|
+
return _select_pypi_stable_wheel(payload, current_version=current_version)
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
def _download_pypi_stable_wheel(
|
|
453
|
+
url: str,
|
|
454
|
+
destination: Path,
|
|
455
|
+
*,
|
|
456
|
+
expected_sha256: str,
|
|
457
|
+
) -> tuple[bool, str]:
|
|
458
|
+
digest = str(expected_sha256 or "").strip().lower()
|
|
459
|
+
if not re.fullmatch(r"[0-9a-f]{64}", digest):
|
|
460
|
+
return False, "PyPI wheel 缺少有效 SHA-256"
|
|
461
|
+
try:
|
|
462
|
+
trusted_url = _validate_official_pypi_url(
|
|
463
|
+
url, expected_host=_STABLE_AGENT_FILES_HOST,
|
|
464
|
+
)
|
|
465
|
+
except CliError as exc:
|
|
466
|
+
return False, str(exc)
|
|
467
|
+
request = urllib.request.Request(
|
|
468
|
+
trusted_url,
|
|
469
|
+
headers={
|
|
470
|
+
"Accept": "application/octet-stream",
|
|
471
|
+
"User-Agent": f"BugX-Client/{__version__} (marker=stable; channel=stable)",
|
|
472
|
+
},
|
|
473
|
+
)
|
|
474
|
+
opener = urllib.request.build_opener(_RejectReleaseRedirects())
|
|
475
|
+
try:
|
|
476
|
+
response = opener.open(request, timeout=30)
|
|
477
|
+
except urllib.error.HTTPError as exc:
|
|
478
|
+
try:
|
|
479
|
+
if 300 <= exc.code < 400:
|
|
480
|
+
return False, "PyPI wheel 响应试图重定向,已拒绝下载"
|
|
481
|
+
return False, f"PyPI wheel 下载失败:HTTP {exc.code}"
|
|
482
|
+
finally:
|
|
483
|
+
exc.close()
|
|
484
|
+
except Exception as exc: # noqa: BLE001
|
|
485
|
+
return False, f"PyPI wheel 下载失败:{type(exc).__name__}: {exc}"
|
|
486
|
+
|
|
487
|
+
fd: int | None = None
|
|
488
|
+
try:
|
|
489
|
+
_validate_official_pypi_url(
|
|
490
|
+
str(response.geturl() or ""), expected_host=_STABLE_AGENT_FILES_HOST,
|
|
491
|
+
)
|
|
492
|
+
headers = getattr(response, "headers", None)
|
|
493
|
+
raw_length = headers.get("Content-Length") if headers is not None else None
|
|
494
|
+
content_length: int | None = None
|
|
495
|
+
if raw_length:
|
|
496
|
+
try:
|
|
497
|
+
content_length = int(raw_length)
|
|
498
|
+
except (TypeError, ValueError):
|
|
499
|
+
return False, "PyPI wheel 响应 Content-Length 无效"
|
|
500
|
+
if content_length < 0 or content_length > _MAX_PYPI_WHEEL_BYTES:
|
|
501
|
+
return False, "PyPI wheel 超过允许大小"
|
|
502
|
+
flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL
|
|
503
|
+
if hasattr(os, "O_NOFOLLOW"):
|
|
504
|
+
flags |= os.O_NOFOLLOW
|
|
505
|
+
fd = os.open(destination, flags, 0o600)
|
|
506
|
+
hasher = hashlib.sha256()
|
|
507
|
+
total = 0
|
|
508
|
+
with os.fdopen(fd, "wb") as output:
|
|
509
|
+
fd = None
|
|
510
|
+
while True:
|
|
511
|
+
chunk = response.read(64 * 1024)
|
|
512
|
+
if not chunk:
|
|
513
|
+
break
|
|
514
|
+
total += len(chunk)
|
|
515
|
+
if total > _MAX_PYPI_WHEEL_BYTES:
|
|
516
|
+
raise CliError("PyPI wheel 超过允许大小")
|
|
517
|
+
output.write(chunk)
|
|
518
|
+
hasher.update(chunk)
|
|
519
|
+
if content_length is not None and total != content_length:
|
|
520
|
+
raise CliError("PyPI wheel 响应长度与 Content-Length 不一致")
|
|
521
|
+
if hasher.hexdigest() != digest:
|
|
522
|
+
raise CliError("PyPI wheel SHA-256 与发行元数据不匹配")
|
|
523
|
+
return True, f"PyPI wheel 已下载并校验:{destination.name}"
|
|
524
|
+
except Exception as exc: # noqa: BLE001
|
|
525
|
+
try:
|
|
526
|
+
destination.unlink(missing_ok=True)
|
|
527
|
+
except OSError:
|
|
528
|
+
pass
|
|
529
|
+
return False, str(exc)
|
|
530
|
+
finally:
|
|
531
|
+
if fd is not None:
|
|
532
|
+
os.close(fd)
|
|
533
|
+
response.close()
|
|
534
|
+
|
|
535
|
+
|
|
536
|
+
def _prepare_cli_package(path: Path) -> Path:
|
|
537
|
+
"""Give a downloaded wheel/sdist the extension pip uses to identify it."""
|
|
538
|
+
try:
|
|
539
|
+
if zipfile.is_zipfile(path):
|
|
540
|
+
with zipfile.ZipFile(path) as archive:
|
|
541
|
+
metadata_names = sorted(
|
|
542
|
+
name for name in archive.namelist()
|
|
543
|
+
if name.endswith(".dist-info/METADATA")
|
|
544
|
+
)
|
|
545
|
+
wheel_names = sorted(
|
|
546
|
+
name for name in archive.namelist()
|
|
547
|
+
if name.endswith(".dist-info/WHEEL")
|
|
548
|
+
)
|
|
549
|
+
if not metadata_names:
|
|
550
|
+
raise CliError(_i18n_exc("system.wheel_metadata_missing", "wheel 包缺少 dist-info/METADATA"))
|
|
551
|
+
metadata = Parser().parsestr(
|
|
552
|
+
archive.read(metadata_names[0]).decode("utf-8", errors="strict")
|
|
553
|
+
)
|
|
554
|
+
name = str(metadata.get("Name") or "").strip()
|
|
555
|
+
version = str(metadata.get("Version") or "").strip()
|
|
556
|
+
if not name or not version:
|
|
557
|
+
raise CliError(_i18n_exc("system.wheel_name_version_missing", "wheel 包缺少 Name/Version 元数据"))
|
|
558
|
+
tags: list[str] = []
|
|
559
|
+
if wheel_names:
|
|
560
|
+
for line in archive.read(wheel_names[0]).decode(
|
|
561
|
+
"utf-8", errors="strict"
|
|
562
|
+
).splitlines():
|
|
563
|
+
if line.startswith("Tag:"):
|
|
564
|
+
tag = line.split(":", 1)[1].strip()
|
|
565
|
+
if tag:
|
|
566
|
+
tags.append(tag)
|
|
567
|
+
tag = tags[0] if tags else "py3-none-any"
|
|
568
|
+
safe_name = re.sub(r"[^A-Za-z0-9]+", "_", name).strip("_")
|
|
569
|
+
safe_version = re.sub(r"[^A-Za-z0-9.]+", "_", version).strip("_")
|
|
570
|
+
if not safe_name or not safe_version or not re.fullmatch(
|
|
571
|
+
r"[A-Za-z0-9_.-]+", tag
|
|
572
|
+
):
|
|
573
|
+
raise CliError(_i18n_exc("system.wheel_metadata_filename_invalid", "wheel 包元数据无法生成合法文件名"))
|
|
574
|
+
target = path.with_name(
|
|
575
|
+
f"{safe_name}-{safe_version}-{tag}.whl"
|
|
576
|
+
)
|
|
577
|
+
elif tarfile.is_tarfile(path):
|
|
578
|
+
with tarfile.open(path, "r:*") as archive:
|
|
579
|
+
roots = sorted({
|
|
580
|
+
member.name.split("/", 1)[0]
|
|
581
|
+
for member in archive.getmembers()
|
|
582
|
+
if member.name and not member.name.startswith("/")
|
|
583
|
+
})
|
|
584
|
+
root = next((item for item in roots if re.fullmatch(
|
|
585
|
+
r"[A-Za-z0-9_.-]+", item
|
|
586
|
+
)), None)
|
|
587
|
+
if root is None:
|
|
588
|
+
raise CliError(_i18n_exc("system.sdist_missing_top_dir", "源码包缺少合法的顶层项目目录"))
|
|
589
|
+
target = path.with_name(f"{root}.tar.gz")
|
|
590
|
+
else:
|
|
591
|
+
raise CliError(_i18n_exc("system.unrecognized_package_archive", "下载内容不是可识别的 wheel 或源码包"))
|
|
592
|
+
except (OSError, UnicodeError, tarfile.TarError, zipfile.BadZipFile) as exc:
|
|
593
|
+
raise CliError(_i18n_exc("system.cli_package_format_unrecognized", f"无法识别 CLI 包格式: {exc}", exc=exc)) from exc
|
|
594
|
+
if target != path:
|
|
595
|
+
path.replace(target)
|
|
596
|
+
return target
|
|
597
|
+
|
|
598
|
+
|
|
599
|
+
def _installed_cli_distribution_version() -> str | None:
|
|
600
|
+
"""Read the version metadata installed into the interpreter running BugX."""
|
|
601
|
+
try:
|
|
602
|
+
return importlib.metadata.version("bugx-cli")
|
|
603
|
+
except importlib.metadata.PackageNotFoundError:
|
|
604
|
+
return None
|
|
605
|
+
|
|
606
|
+
|
|
607
|
+
def _trusted_repair_cloud_client():
|
|
608
|
+
"""Load CloudClient only from a self-consistent installed global engine."""
|
|
609
|
+
engine_root = global_engine_root()
|
|
610
|
+
valid, detail = _engine_self_integrity(engine_root)
|
|
611
|
+
if not valid:
|
|
612
|
+
raise CliError(f"全局引擎无法作为资源恢复引导源:{detail}")
|
|
613
|
+
client_path = engine_root / "cloud_client.py"
|
|
614
|
+
if client_path.is_symlink() or not client_path.is_file():
|
|
615
|
+
raise CliError(f"全局引擎缺少安全的 cloud_client.py:{client_path}")
|
|
616
|
+
|
|
617
|
+
trusted_modules = (
|
|
618
|
+
"cloud_client", "report_client", "client_metadata", "secure_atomic", "cloud_schema",
|
|
619
|
+
)
|
|
620
|
+
for name in trusted_modules:
|
|
621
|
+
loaded = sys.modules.get(name)
|
|
622
|
+
if loaded is None:
|
|
623
|
+
continue
|
|
624
|
+
loaded_path = getattr(loaded, "__file__", None)
|
|
625
|
+
try:
|
|
626
|
+
loaded_root = (
|
|
627
|
+
Path(loaded_path).resolve(strict=True).is_relative_to(
|
|
628
|
+
engine_root.resolve(strict=True)
|
|
629
|
+
)
|
|
630
|
+
if loaded_path is not None else False
|
|
631
|
+
)
|
|
632
|
+
except (OSError, RuntimeError, ValueError) as exc:
|
|
633
|
+
raise CliError(f"无法验证当前进程已加载的 {name} 来源") from exc
|
|
634
|
+
if not loaded_root:
|
|
635
|
+
raise CliError(f"当前进程已加载非全局引擎的 {name};拒绝混用恢复代码")
|
|
636
|
+
|
|
637
|
+
# ``core/`` 是命名空间包:``import core.*`` 需要它的父目录在 sys.path 上。
|
|
638
|
+
engine_paths = [str(engine_root.resolve(strict=True))]
|
|
639
|
+
engine_paths.append(str(Path(engine_paths[0]).parent))
|
|
640
|
+
inserted = [item for item in engine_paths if item not in sys.path]
|
|
641
|
+
for item in inserted:
|
|
642
|
+
sys.path.insert(0, item)
|
|
643
|
+
try:
|
|
644
|
+
module = importlib.import_module("core.cloud_sync.cloud_client")
|
|
645
|
+
except Exception as exc: # noqa: BLE001
|
|
646
|
+
raise CliError(f"无法从已验证全局引擎加载恢复客户端:{exc}") from exc
|
|
647
|
+
finally:
|
|
648
|
+
for item in inserted:
|
|
649
|
+
try:
|
|
650
|
+
sys.path.remove(item)
|
|
651
|
+
except ValueError:
|
|
652
|
+
pass
|
|
653
|
+
|
|
654
|
+
module_path = getattr(module, "__file__", None)
|
|
655
|
+
if module_path is None or Path(module_path).resolve(strict=True) != client_path.resolve(strict=True):
|
|
656
|
+
raise CliError("恢复客户端实际来源与已验证全局引擎不一致")
|
|
657
|
+
for name in trusted_modules:
|
|
658
|
+
loaded = sys.modules.get(name)
|
|
659
|
+
if loaded is None:
|
|
660
|
+
continue
|
|
661
|
+
loaded_path = getattr(loaded, "__file__", None)
|
|
662
|
+
if loaded_path is None or not Path(loaded_path).resolve(strict=True).is_relative_to(
|
|
663
|
+
engine_root.resolve(strict=True)
|
|
664
|
+
):
|
|
665
|
+
raise CliError(f"全局引擎恢复客户端混入了非可信模块 {name}")
|
|
666
|
+
client_type = getattr(module, "CloudClient", None)
|
|
667
|
+
if not callable(client_type):
|
|
668
|
+
raise CliError("已验证全局引擎中的 CloudClient 不可用")
|
|
669
|
+
return client_type
|
|
670
|
+
|
|
671
|
+
|
|
672
|
+
def _construct_stable_repair_cloud_client(client_type):
|
|
673
|
+
"""Construct the pinned release client without consulting sync routing."""
|
|
674
|
+
env_key = "BUGX_CLOUD_API_BASE"
|
|
675
|
+
had_value = env_key in os.environ
|
|
676
|
+
previous_value = os.environ.get(env_key)
|
|
677
|
+
# Build 334's trusted bootstrap engine parses cloud_base_url_status() even
|
|
678
|
+
# when base_url is explicit. Shadow arbitrary/invalid user routing only for
|
|
679
|
+
# that synchronous constructor, then restore the process environment.
|
|
680
|
+
os.environ[env_key] = _STABLE_AGENT_RELEASE_BASE
|
|
681
|
+
try:
|
|
682
|
+
return client_type(base_url=_STABLE_AGENT_RELEASE_BASE)
|
|
683
|
+
finally:
|
|
684
|
+
if had_value:
|
|
685
|
+
os.environ[env_key] = previous_value or ""
|
|
686
|
+
else:
|
|
687
|
+
os.environ.pop(env_key, None)
|
|
688
|
+
|
|
689
|
+
|
|
690
|
+
def _validate_agent_repair_wheel(
|
|
691
|
+
wheel_path: Path,
|
|
692
|
+
*,
|
|
693
|
+
expected_version: str,
|
|
694
|
+
minimum_build_id: int,
|
|
695
|
+
extraction_root: Path,
|
|
696
|
+
) -> int:
|
|
697
|
+
"""Validate release identity and the complete engine payload before pip runs."""
|
|
698
|
+
if wheel_path.suffix.lower() != ".whl":
|
|
699
|
+
raise CliError("资源自动修复只接受 wheel;拒绝安装源码包")
|
|
700
|
+
max_unpacked_bytes = 256 * 1024 * 1024
|
|
701
|
+
try:
|
|
702
|
+
with zipfile.ZipFile(wheel_path) as archive:
|
|
703
|
+
members = archive.infolist()
|
|
704
|
+
names = [item.filename for item in members]
|
|
705
|
+
if len(names) != len(set(names)):
|
|
706
|
+
raise CliError("wheel 含有重复文件路径,拒绝安装")
|
|
707
|
+
|
|
708
|
+
total_size = 0
|
|
709
|
+
for item in members:
|
|
710
|
+
name = item.filename
|
|
711
|
+
if "\\" in name or name.startswith("/"):
|
|
712
|
+
raise CliError("wheel 含有非规范或绝对路径,拒绝安装")
|
|
713
|
+
parts = name.rstrip("/").split("/")
|
|
714
|
+
if not parts or any(
|
|
715
|
+
part in {"", ".", ".."} or ":" in part or part.endswith((".", " "))
|
|
716
|
+
for part in parts
|
|
717
|
+
):
|
|
718
|
+
raise CliError("wheel 含有路径穿越条目,拒绝安装")
|
|
719
|
+
mode = (item.external_attr >> 16) & 0o170000
|
|
720
|
+
if mode == stat.S_IFLNK:
|
|
721
|
+
raise CliError("wheel 含有符号链接条目,拒绝安装")
|
|
722
|
+
if not item.is_dir():
|
|
723
|
+
total_size += item.file_size
|
|
724
|
+
if total_size > max_unpacked_bytes:
|
|
725
|
+
raise CliError("wheel 解包体积超过资源修复上限,拒绝安装")
|
|
726
|
+
|
|
727
|
+
metadata_names = [name for name in names if name.endswith(".dist-info/METADATA")]
|
|
728
|
+
if len(metadata_names) != 1:
|
|
729
|
+
raise CliError("wheel 必须且只能包含一个 dist-info/METADATA")
|
|
730
|
+
dist_info = metadata_names[0].rsplit("/", 1)[0]
|
|
731
|
+
if f"{dist_info}/WHEEL" not in names or f"{dist_info}/RECORD" not in names:
|
|
732
|
+
raise CliError("wheel 缺少 WHEEL 或 RECORD 元数据")
|
|
733
|
+
wheel_metadata = Parser().parsestr(
|
|
734
|
+
archive.read(f"{dist_info}/WHEEL").decode("utf-8", errors="strict")
|
|
735
|
+
)
|
|
736
|
+
wheel_tags = {str(tag).strip() for tag in wheel_metadata.get_all("Tag", [])}
|
|
737
|
+
if wheel_metadata.get("Root-Is-Purelib", "").strip().lower() != "true" or wheel_tags != {"py3-none-any"}:
|
|
738
|
+
raise CliError("资源修复仅接受 py3-none-any 纯 Python wheel")
|
|
739
|
+
metadata = Parser().parsestr(archive.read(metadata_names[0]).decode("utf-8", errors="strict"))
|
|
740
|
+
package_name = re.sub(r"[-_.]+", "-", str(metadata.get("Name") or "")).lower()
|
|
741
|
+
package_version = str(metadata.get("Version") or "").strip()
|
|
742
|
+
if package_name != "bugx-cli" or package_version != expected_version:
|
|
743
|
+
raise CliError(
|
|
744
|
+
f"wheel 身份不匹配:期望 bugx-cli {expected_version},"
|
|
745
|
+
f"收到 {package_name or '未知包'} {package_version or '未知版本'}"
|
|
746
|
+
)
|
|
747
|
+
|
|
748
|
+
init_path = "bugx_cli/__init__.py"
|
|
749
|
+
if init_path not in names:
|
|
750
|
+
raise CliError("wheel 缺少 bugx_cli/__init__.py,无法确认 Build ID")
|
|
751
|
+
init_source = archive.read(init_path).decode("utf-8", errors="strict")
|
|
752
|
+
version_match = re.search(r"^__version__\s*=\s*['\"]([^'\"]+)['\"]\s*$", init_source, re.M)
|
|
753
|
+
build_match = re.search(r"^__build_id__\s*:\s*int\s*=\s*(\d+)\s*$", init_source, re.M)
|
|
754
|
+
if version_match is None or version_match.group(1) != expected_version or build_match is None:
|
|
755
|
+
raise CliError("wheel 中的 CLI 版本或 Build ID 声明无效")
|
|
756
|
+
wheel_build_id = int(build_match.group(1))
|
|
757
|
+
if wheel_build_id < minimum_build_id:
|
|
758
|
+
raise CliError(
|
|
759
|
+
f"拒绝 Build ID 降级:最低要求 {minimum_build_id},wheel {wheel_build_id}"
|
|
760
|
+
)
|
|
761
|
+
|
|
762
|
+
engine_prefix = f"bugx_cli-{expected_version}.data/data/share/bugx-agent/core/"
|
|
763
|
+
if not any(name.startswith(engine_prefix) for name in names):
|
|
764
|
+
raise CliError("wheel 未包含 share/bugx-agent/core 引擎载荷")
|
|
765
|
+
core_root = extraction_root / "validated-core"
|
|
766
|
+
for item in members:
|
|
767
|
+
if not item.filename.startswith(engine_prefix) or item.is_dir():
|
|
768
|
+
continue
|
|
769
|
+
relative = item.filename[len(engine_prefix):]
|
|
770
|
+
relative_parts = PurePosixPath(relative).parts
|
|
771
|
+
if not relative_parts or any(part in {"", ".", ".."} for part in relative_parts):
|
|
772
|
+
raise CliError("wheel 核心载荷路径无效,拒绝安装")
|
|
773
|
+
destination = core_root.joinpath(*relative_parts)
|
|
774
|
+
destination.parent.mkdir(parents=True, exist_ok=True)
|
|
775
|
+
with archive.open(item, "r") as source, destination.open("xb") as target:
|
|
776
|
+
shutil.copyfileobj(source, target, length=1024 * 1024)
|
|
777
|
+
|
|
778
|
+
if not (core_root / "bugx.md").is_file() or not (core_root / "launch_bugx.py").is_file():
|
|
779
|
+
raise CliError("wheel 缺少 bugx.md 或 launch_bugx.py")
|
|
780
|
+
valid, detail = _engine_self_integrity(core_root)
|
|
781
|
+
if not valid:
|
|
782
|
+
raise CliError(f"wheel 核心载荷与自身清单不一致:{detail}")
|
|
783
|
+
metadata_text = (core_root / "metadata.txt").read_text(encoding="utf-8")
|
|
784
|
+
engine_build_match = re.search(r"^build_id:\s*(\d+)\s*$", metadata_text, re.M)
|
|
785
|
+
if engine_build_match is None or int(engine_build_match.group(1)) != wheel_build_id:
|
|
786
|
+
raise CliError("wheel 的 CLI 与引擎 Build ID 不一致")
|
|
787
|
+
return wheel_build_id
|
|
788
|
+
except (OSError, UnicodeError, zipfile.BadZipFile, RuntimeError) as exc:
|
|
789
|
+
if isinstance(exc, CliError):
|
|
790
|
+
raise
|
|
791
|
+
raise CliError(f"无法安全校验资源修复 wheel:{exc}") from exc
|
|
792
|
+
|
|
793
|
+
|
|
794
|
+
def _asset_repair_state(current_build_id: int) -> dict[str, object]:
|
|
795
|
+
"""Inspect the installed payload and derive a non-downgrade repair floor."""
|
|
796
|
+
explicitly_configured = (
|
|
797
|
+
os.environ.get("BUGX_ASSET_ROOT") is not None
|
|
798
|
+
or os.environ.get("BUGX_DEV_ASSET_ROOT") == "1"
|
|
799
|
+
)
|
|
800
|
+
selected_assets: Path | None = None
|
|
801
|
+
try:
|
|
802
|
+
selected_assets = asset_root()
|
|
803
|
+
except MissingAgentAssetError as exc:
|
|
804
|
+
if not exc.repairable:
|
|
805
|
+
raise CliError(f"显式资源路径或开发模式资源错误,不执行包修复:{exc}") from exc
|
|
806
|
+
|
|
807
|
+
if selected_assets is not None and explicitly_configured:
|
|
808
|
+
return {"complete": True, "message": "已安装 Agent 资源完整,无需修复"}
|
|
809
|
+
|
|
810
|
+
data_root = sysconfig.get_path("data")
|
|
811
|
+
if not data_root:
|
|
812
|
+
raise CliError("无法确定当前 Python 的安装数据目录,拒绝覆盖其他资源副本")
|
|
813
|
+
installed_assets = Path(data_root) / "share" / "bugx-agent" / "core"
|
|
814
|
+
try:
|
|
815
|
+
_assert_no_symlink_components(installed_assets)
|
|
816
|
+
except CliError as exc:
|
|
817
|
+
raise CliError(
|
|
818
|
+
f"当前解释器安装资源路径包含符号链接或重解析点,拒绝自动写入:{installed_assets}"
|
|
819
|
+
) from exc
|
|
820
|
+
if installed_assets.exists() and not installed_assets.is_dir():
|
|
821
|
+
raise CliError(f"当前解释器安装资源路径不是目录,拒绝自动覆盖:{installed_assets}")
|
|
822
|
+
if selected_assets is not None:
|
|
823
|
+
if selected_assets.is_symlink():
|
|
824
|
+
raise CliError(f"当前 Agent 资源目录是符号链接,拒绝包修复:{selected_assets}")
|
|
825
|
+
try:
|
|
826
|
+
selected_path = selected_assets.resolve(strict=True)
|
|
827
|
+
installed_path = installed_assets.resolve(strict=False)
|
|
828
|
+
except (OSError, RuntimeError) as exc:
|
|
829
|
+
raise CliError(f"无法验证当前 Agent 资源目录:{exc}") from exc
|
|
830
|
+
if selected_path != installed_path:
|
|
831
|
+
raise CliError(
|
|
832
|
+
f"当前 Agent 资源位于其他 Python 副本,拒绝覆盖:{selected_path};"
|
|
833
|
+
f"当前解释器 wheel 载荷位置为 {installed_path}"
|
|
834
|
+
)
|
|
835
|
+
|
|
836
|
+
global_root = global_engine_root()
|
|
837
|
+
global_build_id = _engine_build_id(global_root)
|
|
838
|
+
asset_build_id = _engine_build_id(selected_assets) if selected_assets is not None else None
|
|
839
|
+
asset_valid = False
|
|
840
|
+
if selected_assets is not None:
|
|
841
|
+
asset_valid, _ = _engine_self_integrity(selected_assets)
|
|
842
|
+
|
|
843
|
+
if (
|
|
844
|
+
selected_assets is not None
|
|
845
|
+
and asset_valid
|
|
846
|
+
and asset_build_id == current_build_id
|
|
847
|
+
and (
|
|
848
|
+
global_build_id is None
|
|
849
|
+
or (global_build_id > 0 and current_build_id >= global_build_id)
|
|
850
|
+
)
|
|
851
|
+
):
|
|
852
|
+
return {"complete": True, "message": "已安装 Agent 资源完整,无需修复"}
|
|
853
|
+
|
|
854
|
+
if global_build_id is None or global_build_id < 1:
|
|
855
|
+
raise CliError("全局引擎缺少有效 Build ID,无法确定安全的 CLI wheel 修复下限")
|
|
856
|
+
minimum_build_id = max(
|
|
857
|
+
current_build_id,
|
|
858
|
+
asset_build_id if isinstance(asset_build_id, int) and asset_build_id > 0 else 0,
|
|
859
|
+
global_build_id,
|
|
860
|
+
)
|
|
861
|
+
return {
|
|
862
|
+
"complete": False,
|
|
863
|
+
"global_root": global_root,
|
|
864
|
+
"installed_assets": installed_assets,
|
|
865
|
+
"asset_build_id": asset_build_id,
|
|
866
|
+
"global_build_id": global_build_id,
|
|
867
|
+
"minimum_build_id": minimum_build_id,
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
|
|
871
|
+
def _installed_cli_build_id(distribution: Any, *, expected_version: str) -> int:
|
|
872
|
+
"""Read the CLI Build ID from the installed distribution without importing it."""
|
|
873
|
+
init_path = Path(distribution.locate_file("bugx_cli/__init__.py"))
|
|
874
|
+
if init_path.is_symlink() or not init_path.is_file():
|
|
875
|
+
raise CliError(f"安装后缺少可信 CLI 声明:{init_path}")
|
|
876
|
+
try:
|
|
877
|
+
init_source = init_path.read_text(encoding="utf-8")
|
|
878
|
+
except (OSError, UnicodeError) as exc:
|
|
879
|
+
raise CliError(f"安装后无法读取 CLI Build ID:{exc}") from exc
|
|
880
|
+
version_match = re.search(r"^__version__\s*=\s*['\"]([^'\"]+)['\"]\s*$", init_source, re.M)
|
|
881
|
+
build_match = re.search(r"^__build_id__\s*:\s*int\s*=\s*(\d+)\s*$", init_source, re.M)
|
|
882
|
+
if version_match is None or version_match.group(1) != expected_version or build_match is None:
|
|
883
|
+
raise CliError("安装后 CLI 版本或 Build ID 声明无效")
|
|
884
|
+
return int(build_match.group(1))
|
|
885
|
+
|
|
886
|
+
|
|
887
|
+
def _installed_distribution_core_records(
|
|
888
|
+
installed_assets: Path,
|
|
889
|
+
) -> tuple[dict[str, tuple[str, int]] | None, str]:
|
|
890
|
+
"""Read exact core file hashes from this interpreter's non-editable wheel RECORD."""
|
|
891
|
+
try:
|
|
892
|
+
distribution = importlib.metadata.distribution("bugx-cli")
|
|
893
|
+
package_name = re.sub(
|
|
894
|
+
r"[-_.]+", "-", str(distribution.metadata.get("Name") or ""),
|
|
895
|
+
).lower()
|
|
896
|
+
if package_name != "bugx-cli" or str(distribution.version) != __version__:
|
|
897
|
+
return None, "当前 distribution 名称或版本与 CLI 不一致"
|
|
898
|
+
record_text = distribution.read_text("RECORD")
|
|
899
|
+
if not record_text:
|
|
900
|
+
return None, "当前 wheel 缺少 RECORD"
|
|
901
|
+
direct_url_text = distribution.read_text("direct_url.json")
|
|
902
|
+
if direct_url_text:
|
|
903
|
+
direct_url = json.loads(direct_url_text)
|
|
904
|
+
if not isinstance(direct_url, dict):
|
|
905
|
+
return None, "当前 wheel direct_url.json 格式无效"
|
|
906
|
+
dir_info = direct_url.get("dir_info")
|
|
907
|
+
if isinstance(dir_info, dict) and dir_info.get("editable") is True:
|
|
908
|
+
return None, "当前安装为 editable,不能用其 RECORD 恢复 wheel 资源"
|
|
909
|
+
except importlib.metadata.PackageNotFoundError:
|
|
910
|
+
return None, "当前 Python 未安装 bugx-cli distribution"
|
|
911
|
+
except (OSError, UnicodeError, json.JSONDecodeError, ValueError, TypeError) as exc:
|
|
912
|
+
return None, f"无法读取当前 wheel RECORD:{exc}"
|
|
913
|
+
|
|
914
|
+
try:
|
|
915
|
+
record_rows = list(csv.reader(io.StringIO(record_text)))
|
|
916
|
+
except (csv.Error, UnicodeError, ValueError, TypeError) as exc:
|
|
917
|
+
return None, f"当前 wheel RECORD CSV 无效:{exc}"
|
|
918
|
+
if not record_rows:
|
|
919
|
+
return None, "当前 wheel RECORD 没有可验证的文件清单"
|
|
920
|
+
try:
|
|
921
|
+
_assert_no_symlink_components(installed_assets)
|
|
922
|
+
installed_root = installed_assets.resolve(strict=False)
|
|
923
|
+
except (CliError, OSError, RuntimeError) as exc:
|
|
924
|
+
return None, f"当前解释器安装资源路径不安全:{exc}"
|
|
925
|
+
|
|
926
|
+
marker = "share/bugx-agent/core/"
|
|
927
|
+
records: dict[str, tuple[str, int]] = {}
|
|
928
|
+
total_size = 0
|
|
929
|
+
for row in record_rows:
|
|
930
|
+
if not row:
|
|
931
|
+
continue
|
|
932
|
+
if len(row) != 3 or not row[0]:
|
|
933
|
+
return None, "当前 wheel RECORD 含有无效记录行"
|
|
934
|
+
normalized = row[0].replace("\\", "/")
|
|
935
|
+
if marker not in normalized:
|
|
936
|
+
continue
|
|
937
|
+
if normalized.count(marker) != 1 or normalized.startswith("/"):
|
|
938
|
+
return None, "当前 wheel RECORD 含有非规范引擎资源路径"
|
|
939
|
+
relative = normalized.split(marker, 1)[1]
|
|
940
|
+
parts = PurePosixPath(relative).parts
|
|
941
|
+
if not parts or any(
|
|
942
|
+
part in {"", ".", ".."} or ":" in part or part.endswith((".", " "))
|
|
943
|
+
for part in parts
|
|
944
|
+
):
|
|
945
|
+
return None, "当前 wheel RECORD 含有路径穿越条目"
|
|
946
|
+
if "__pycache__" in parts or parts[-1].endswith(".pyc"):
|
|
947
|
+
continue
|
|
948
|
+
expected_path = installed_root.joinpath(*parts)
|
|
949
|
+
try:
|
|
950
|
+
located_path = Path(distribution.locate_file(normalized)).resolve(strict=False)
|
|
951
|
+
if located_path != expected_path.resolve(strict=False):
|
|
952
|
+
return None, "当前 wheel RECORD 引擎资源不属于当前解释器数据目录"
|
|
953
|
+
except (OSError, RuntimeError, TypeError, ValueError) as exc:
|
|
954
|
+
return None, f"当前 wheel RECORD 路径无法验证:{exc}"
|
|
955
|
+
|
|
956
|
+
hash_algorithm, separator, hash_value = row[1].partition("=")
|
|
957
|
+
if not separator:
|
|
958
|
+
hash_value = ""
|
|
959
|
+
size_text = row[2]
|
|
960
|
+
if (
|
|
961
|
+
hash_algorithm != "sha256"
|
|
962
|
+
or not re.fullmatch(r"[A-Za-z0-9_-]{43}", hash_value)
|
|
963
|
+
):
|
|
964
|
+
return None, "当前 wheel RECORD 引擎资源缺少有效 SHA-256"
|
|
965
|
+
if not re.fullmatch(r"[0-9]+", size_text):
|
|
966
|
+
return None, "当前 wheel RECORD 引擎资源文件大小无效"
|
|
967
|
+
if len(size_text) > 9:
|
|
968
|
+
return None, "当前 wheel RECORD 引擎资源超过 256 MiB 上限"
|
|
969
|
+
file_size = int(size_text)
|
|
970
|
+
if relative in records:
|
|
971
|
+
return None, "当前 wheel RECORD 含有重复引擎资源路径"
|
|
972
|
+
total_size += file_size
|
|
973
|
+
if total_size > 256 * 1024 * 1024:
|
|
974
|
+
return None, "当前 wheel RECORD 引擎资源超过 256 MiB 上限"
|
|
975
|
+
records[relative] = (hash_value, file_size)
|
|
976
|
+
|
|
977
|
+
required = {"bugx.md", "launch_bugx.py", "metadata.txt", "engine-integrity.json"}
|
|
978
|
+
if not required.issubset(records):
|
|
979
|
+
return None, "当前 wheel RECORD 未完整记录 BugX 核心入口与清单"
|
|
980
|
+
return records, "当前 wheel RECORD 可用于逐项恢复"
|
|
981
|
+
|
|
982
|
+
|
|
983
|
+
def _file_matches_distribution_record(
|
|
984
|
+
path: Path,
|
|
985
|
+
record: tuple[str, int],
|
|
986
|
+
) -> bool:
|
|
987
|
+
try:
|
|
988
|
+
file_stat = path.lstat()
|
|
989
|
+
if not stat.S_ISREG(file_stat.st_mode) or file_stat.st_size != record[1]:
|
|
990
|
+
return False
|
|
991
|
+
digest = hashlib.sha256()
|
|
992
|
+
with path.open("rb") as source:
|
|
993
|
+
for chunk in iter(lambda: source.read(1024 * 1024), b""):
|
|
994
|
+
digest.update(chunk)
|
|
995
|
+
actual = base64.urlsafe_b64encode(digest.digest()).rstrip(b"=").decode("ascii")
|
|
996
|
+
return actual == record[0]
|
|
997
|
+
except OSError:
|
|
998
|
+
return False
|
|
999
|
+
|
|
1000
|
+
|
|
1001
|
+
def _remove_failed_agent_asset_restore_target(
|
|
1002
|
+
installed_assets: Path,
|
|
1003
|
+
expected_identity: tuple[int, int],
|
|
1004
|
+
) -> str:
|
|
1005
|
+
"""Remove only this restore's failed publication, preserving replacements."""
|
|
1006
|
+
quarantined = installed_assets.with_name(
|
|
1007
|
+
f".{installed_assets.name}.failed-restore-{time.time_ns()}"
|
|
1008
|
+
)
|
|
1009
|
+
if quarantined.exists() or quarantined.is_symlink():
|
|
1010
|
+
raise CliError(f"失败资源隔离目标已存在:{quarantined}")
|
|
1011
|
+
try:
|
|
1012
|
+
os.replace(installed_assets, quarantined)
|
|
1013
|
+
except FileNotFoundError:
|
|
1014
|
+
return "失败发布目标已不存在"
|
|
1015
|
+
|
|
1016
|
+
try:
|
|
1017
|
+
info = quarantined.lstat()
|
|
1018
|
+
except OSError as exc:
|
|
1019
|
+
raise CliError(f"无法核对失败资源隔离目录 {quarantined}:{exc}") from exc
|
|
1020
|
+
is_our_directory = (
|
|
1021
|
+
stat.S_ISDIR(info.st_mode)
|
|
1022
|
+
and (info.st_dev, info.st_ino) == expected_identity
|
|
1023
|
+
)
|
|
1024
|
+
if is_our_directory:
|
|
1025
|
+
shutil.rmtree(quarantined)
|
|
1026
|
+
return "已清理本次发布的失败资源目录"
|
|
1027
|
+
|
|
1028
|
+
if installed_assets.exists() or installed_assets.is_symlink():
|
|
1029
|
+
raise CliError(
|
|
1030
|
+
f"失败资源目标被并发替换且原目标路径已被占用;保留隔离路径 {quarantined}"
|
|
1031
|
+
)
|
|
1032
|
+
try:
|
|
1033
|
+
os.replace(quarantined, installed_assets)
|
|
1034
|
+
except OSError as exc:
|
|
1035
|
+
raise CliError(
|
|
1036
|
+
f"失败资源目标被并发替换且无法原子恢复;保留隔离路径 {quarantined}:{exc}"
|
|
1037
|
+
) from exc
|
|
1038
|
+
raise CliError("失败资源目标已被并发替换;已保留原目标,停止自动修复")
|
|
1039
|
+
|
|
1040
|
+
|
|
1041
|
+
def _restore_agent_assets_from_global_record(
|
|
1042
|
+
global_root: Path,
|
|
1043
|
+
installed_assets: Path,
|
|
1044
|
+
*,
|
|
1045
|
+
current_build_id: int,
|
|
1046
|
+
) -> tuple[bool, str, int]:
|
|
1047
|
+
"""Restore only wheel-recorded bytes from a complete same-build global engine."""
|
|
1048
|
+
try:
|
|
1049
|
+
_assert_no_symlink_components(global_root)
|
|
1050
|
+
_assert_no_symlink_components(installed_assets)
|
|
1051
|
+
except CliError as exc:
|
|
1052
|
+
return False, f"拒绝通过符号链接或重解析点恢复:{exc}", 0
|
|
1053
|
+
|
|
1054
|
+
global_build_id = _engine_build_id(global_root)
|
|
1055
|
+
if global_build_id != current_build_id:
|
|
1056
|
+
return False, (
|
|
1057
|
+
f"全局引擎 Build ID={global_build_id!r} 与当前 CLI Build ID="
|
|
1058
|
+
f"{current_build_id} 不相同"
|
|
1059
|
+
), 0
|
|
1060
|
+
global_valid, global_detail = _engine_self_integrity(global_root)
|
|
1061
|
+
if not global_valid:
|
|
1062
|
+
return False, f"全局引擎完整性校验失败:{global_detail}", 0
|
|
1063
|
+
|
|
1064
|
+
records, detail = _installed_distribution_core_records(installed_assets)
|
|
1065
|
+
if records is None:
|
|
1066
|
+
return False, detail, 0
|
|
1067
|
+
global_resolved = global_root.resolve(strict=True)
|
|
1068
|
+
for relative, record in records.items():
|
|
1069
|
+
source = global_resolved.joinpath(*PurePosixPath(relative).parts)
|
|
1070
|
+
try:
|
|
1071
|
+
_assert_no_symlink_components(source)
|
|
1072
|
+
except CliError as exc:
|
|
1073
|
+
return False, f"全局引擎资源路径不安全 {relative}:{exc}", 0
|
|
1074
|
+
if not _file_matches_distribution_record(source, record):
|
|
1075
|
+
return False, f"全局引擎资源与当前 wheel RECORD 不匹配:{relative}", 0
|
|
1076
|
+
|
|
1077
|
+
parent = installed_assets.parent
|
|
1078
|
+
stage_root: Path | None = None
|
|
1079
|
+
backup: Path | None = None
|
|
1080
|
+
backup_moved = False
|
|
1081
|
+
published_identity: tuple[int, int] | None = None
|
|
1082
|
+
try:
|
|
1083
|
+
_assert_no_symlink_components(parent)
|
|
1084
|
+
parent.mkdir(parents=True, exist_ok=True)
|
|
1085
|
+
_assert_no_symlink_components(parent)
|
|
1086
|
+
if installed_assets.is_symlink():
|
|
1087
|
+
raise CliError(f"安装资源目录是符号链接,拒绝替换:{installed_assets}")
|
|
1088
|
+
if installed_assets.exists() and not installed_assets.is_dir():
|
|
1089
|
+
raise CliError(f"安装资源路径不是目录,拒绝替换:{installed_assets}")
|
|
1090
|
+
|
|
1091
|
+
stage_root = Path(tempfile.mkdtemp(prefix=".bugx-core-repair-", dir=parent))
|
|
1092
|
+
os.chmod(stage_root, 0o700)
|
|
1093
|
+
for relative, record in records.items():
|
|
1094
|
+
parts = PurePosixPath(relative).parts
|
|
1095
|
+
source = global_resolved.joinpath(*parts)
|
|
1096
|
+
target = stage_root.joinpath(*parts)
|
|
1097
|
+
target.parent.mkdir(parents=True, exist_ok=True, mode=0o755)
|
|
1098
|
+
with source.open("rb") as source_file, target.open("xb") as target_file:
|
|
1099
|
+
shutil.copyfileobj(source_file, target_file, length=1024 * 1024)
|
|
1100
|
+
source_mode = stat.S_IMODE(source.stat().st_mode) & 0o755
|
|
1101
|
+
target.chmod(source_mode or 0o644)
|
|
1102
|
+
if not _file_matches_distribution_record(target, record):
|
|
1103
|
+
raise CliError(f"暂存引擎资源与当前 wheel RECORD 不匹配:{relative}")
|
|
1104
|
+
|
|
1105
|
+
staged_valid, staged_detail = _engine_self_integrity(stage_root)
|
|
1106
|
+
if not staged_valid or _engine_build_id(stage_root) != current_build_id:
|
|
1107
|
+
raise CliError(f"暂存引擎完整性或 Build ID 校验失败:{staged_detail}")
|
|
1108
|
+
os.chmod(stage_root, 0o755)
|
|
1109
|
+
|
|
1110
|
+
if installed_assets.exists():
|
|
1111
|
+
backup = installed_assets.with_name(
|
|
1112
|
+
f".{installed_assets.name}.repair-backup-{time.time_ns()}"
|
|
1113
|
+
)
|
|
1114
|
+
if backup.exists() or backup.is_symlink():
|
|
1115
|
+
raise CliError(f"资源恢复备份目标已存在:{backup}")
|
|
1116
|
+
os.replace(installed_assets, backup)
|
|
1117
|
+
backup_moved = True
|
|
1118
|
+
stage_info = stage_root.lstat()
|
|
1119
|
+
published_identity = (stage_info.st_dev, stage_info.st_ino)
|
|
1120
|
+
os.replace(stage_root, installed_assets)
|
|
1121
|
+
stage_root = None
|
|
1122
|
+
|
|
1123
|
+
_assert_no_symlink_components(installed_assets)
|
|
1124
|
+
installed_valid, installed_detail = _engine_self_integrity(installed_assets)
|
|
1125
|
+
if (
|
|
1126
|
+
not installed_valid
|
|
1127
|
+
or _engine_build_id(installed_assets) != current_build_id
|
|
1128
|
+
or any(
|
|
1129
|
+
not _file_matches_distribution_record(
|
|
1130
|
+
installed_assets.joinpath(*PurePosixPath(relative).parts), record,
|
|
1131
|
+
)
|
|
1132
|
+
for relative, record in records.items()
|
|
1133
|
+
)
|
|
1134
|
+
):
|
|
1135
|
+
raise CliError(f"恢复后安装载荷校验失败:{installed_detail}")
|
|
1136
|
+
|
|
1137
|
+
backup_detail = ""
|
|
1138
|
+
if backup_moved and backup is not None:
|
|
1139
|
+
try:
|
|
1140
|
+
shutil.rmtree(backup)
|
|
1141
|
+
backup_moved = False
|
|
1142
|
+
except OSError as exc:
|
|
1143
|
+
backup_detail = f";旧损坏载荷暂存于 {backup}(清理失败:{exc})"
|
|
1144
|
+
return True, f"从同 Build ID 的全局引擎按 wheel RECORD 恢复 {len(records)} 个文件{backup_detail}", len(records)
|
|
1145
|
+
except Exception as exc: # noqa: BLE001 - verified wheel remains the fallback
|
|
1146
|
+
if backup_moved and backup is not None:
|
|
1147
|
+
try:
|
|
1148
|
+
if installed_assets.is_symlink():
|
|
1149
|
+
raise CliError(
|
|
1150
|
+
f"回滚目标被替换为符号链接,拒绝覆盖:{installed_assets}"
|
|
1151
|
+
)
|
|
1152
|
+
if installed_assets.exists():
|
|
1153
|
+
if not installed_assets.is_dir():
|
|
1154
|
+
raise CliError(
|
|
1155
|
+
f"回滚目标被替换为非目录文件,拒绝覆盖:{installed_assets}"
|
|
1156
|
+
)
|
|
1157
|
+
shutil.rmtree(installed_assets)
|
|
1158
|
+
os.replace(backup, installed_assets)
|
|
1159
|
+
backup_moved = False
|
|
1160
|
+
except Exception as rollback_exc: # noqa: BLE001 - ambiguous state must fail closed
|
|
1161
|
+
raise CliError(
|
|
1162
|
+
f"本地资源恢复失败且原目录回滚失败;保留备份 {backup}:{rollback_exc}"
|
|
1163
|
+
) from exc
|
|
1164
|
+
rollback_detail = ""
|
|
1165
|
+
if published_identity is not None and backup is None:
|
|
1166
|
+
try:
|
|
1167
|
+
rollback_detail = _remove_failed_agent_asset_restore_target(
|
|
1168
|
+
installed_assets, published_identity,
|
|
1169
|
+
)
|
|
1170
|
+
except Exception as rollback_exc: # noqa: BLE001 - preserve ambiguous targets
|
|
1171
|
+
raise CliError(
|
|
1172
|
+
f"本地资源恢复失败或目标状态已变化,停止自动修复:{rollback_exc}"
|
|
1173
|
+
) from exc
|
|
1174
|
+
suffix = f";{rollback_detail}" if rollback_detail else ""
|
|
1175
|
+
return False, f"本地资源恢复未完成:{exc}{suffix}", 0
|
|
1176
|
+
finally:
|
|
1177
|
+
if stage_root is not None and stage_root.exists():
|
|
1178
|
+
shutil.rmtree(stage_root, ignore_errors=True)
|
|
1179
|
+
|
|
1180
|
+
|
|
1181
|
+
def repair_cli_agent_assets(
|
|
1182
|
+
*,
|
|
1183
|
+
channel: str = "stable",
|
|
1184
|
+
root: Path | None = None,
|
|
1185
|
+
) -> str:
|
|
1186
|
+
"""Restore missing installed Agent data from a verified official wheel."""
|
|
1187
|
+
if channel != "stable":
|
|
1188
|
+
raise CliError("CLI 安装资源自动修复仅接受 stable 发布通道")
|
|
1189
|
+
project_root = Path(root or Path.cwd()).resolve()
|
|
1190
|
+
started = time.monotonic()
|
|
1191
|
+
request_fields: dict[str, object] = {}
|
|
1192
|
+
|
|
1193
|
+
def record(event: str, message: str, *, phase: str, **fields: object) -> None:
|
|
1194
|
+
_log_update_event(
|
|
1195
|
+
project_root, event, message,
|
|
1196
|
+
phase=phase, duration_ms=round((time.monotonic() - started) * 1000, 1),
|
|
1197
|
+
**fields,
|
|
1198
|
+
)
|
|
1199
|
+
|
|
1200
|
+
try:
|
|
1201
|
+
current_build_id = __build_id__
|
|
1202
|
+
if not isinstance(current_build_id, int) or isinstance(current_build_id, bool) or current_build_id < 1:
|
|
1203
|
+
raise CliError("资源自动修复失败:当前 CLI 缺少可信的正整数 Build ID")
|
|
1204
|
+
repair_state = _asset_repair_state(current_build_id)
|
|
1205
|
+
except Exception as exc: # noqa: BLE001
|
|
1206
|
+
record(
|
|
1207
|
+
"asset_repair_failed", str(exc), phase="preflight",
|
|
1208
|
+
failure_kind=type(exc).__name__, channel=channel,
|
|
1209
|
+
)
|
|
1210
|
+
raise
|
|
1211
|
+
if repair_state["complete"]:
|
|
1212
|
+
return str(repair_state["message"])
|
|
1213
|
+
request_fields.update({
|
|
1214
|
+
"minimum_build_id": repair_state["minimum_build_id"],
|
|
1215
|
+
"current_cli_build_id": current_build_id,
|
|
1216
|
+
"current_asset_build_id": repair_state["asset_build_id"],
|
|
1217
|
+
"global_build_id": repair_state["global_build_id"],
|
|
1218
|
+
})
|
|
1219
|
+
|
|
1220
|
+
lock_target = Path.home() / ".bugx" / "cli-package-repair"
|
|
1221
|
+
record(
|
|
1222
|
+
"asset_repair_started", "开始修复 BugX CLI 安装资源", phase="preflight",
|
|
1223
|
+
channel=channel, **request_fields,
|
|
1224
|
+
)
|
|
1225
|
+
try:
|
|
1226
|
+
with _engine_install_lock(lock_target):
|
|
1227
|
+
repair_state = _asset_repair_state(current_build_id)
|
|
1228
|
+
if repair_state["complete"]:
|
|
1229
|
+
record("asset_repair_skipped", "另一个 CLI 进程已完成资源修复", phase="lock")
|
|
1230
|
+
return "另一个 CLI 进程已完成资源修复"
|
|
1231
|
+
minimum_build_id = int(repair_state["minimum_build_id"])
|
|
1232
|
+
global_root = Path(repair_state["global_root"])
|
|
1233
|
+
installed_assets = Path(repair_state["installed_assets"])
|
|
1234
|
+
request_fields.update({
|
|
1235
|
+
"minimum_build_id": minimum_build_id,
|
|
1236
|
+
"current_cli_build_id": current_build_id,
|
|
1237
|
+
"current_asset_build_id": repair_state["asset_build_id"],
|
|
1238
|
+
"global_build_id": repair_state["global_build_id"],
|
|
1239
|
+
})
|
|
1240
|
+
|
|
1241
|
+
local_recovery_ok, local_recovery_detail, restored_files = (
|
|
1242
|
+
_restore_agent_assets_from_global_record(
|
|
1243
|
+
global_root,
|
|
1244
|
+
installed_assets,
|
|
1245
|
+
current_build_id=current_build_id,
|
|
1246
|
+
)
|
|
1247
|
+
)
|
|
1248
|
+
local_recovery_restored = local_recovery_ok
|
|
1249
|
+
if local_recovery_ok:
|
|
1250
|
+
verified_state = _asset_repair_state(current_build_id)
|
|
1251
|
+
if verified_state["complete"]:
|
|
1252
|
+
message = (
|
|
1253
|
+
f"BugX CLI {__version__}+build.{current_build_id} 安装资源已恢复"
|
|
1254
|
+
f"(来源:当前 wheel RECORD,对照恢复 {restored_files} 个文件)"
|
|
1255
|
+
)
|
|
1256
|
+
record(
|
|
1257
|
+
"asset_repair_succeeded", message,
|
|
1258
|
+
phase="local_record_restore", build_id=current_build_id,
|
|
1259
|
+
restored_files=restored_files, **request_fields,
|
|
1260
|
+
)
|
|
1261
|
+
return message
|
|
1262
|
+
local_recovery_ok = False
|
|
1263
|
+
local_recovery_detail = (
|
|
1264
|
+
"本地字节恢复完成,但安装后状态复验仍未通过:"
|
|
1265
|
+
+ str(verified_state.get("message") or "载荷版本或完整性仍不一致")
|
|
1266
|
+
)
|
|
1267
|
+
request_fields["local_recovery"] = (
|
|
1268
|
+
"restored_but_unverified" if local_recovery_restored else "unavailable"
|
|
1269
|
+
)
|
|
1270
|
+
request_fields["local_recovery_detail"] = local_recovery_detail[:240]
|
|
1271
|
+
record(
|
|
1272
|
+
"asset_repair_local_recovery_unavailable",
|
|
1273
|
+
local_recovery_detail,
|
|
1274
|
+
phase="local_record_restore",
|
|
1275
|
+
channel=channel,
|
|
1276
|
+
**request_fields,
|
|
1277
|
+
)
|
|
1278
|
+
|
|
1279
|
+
cloud_client_type = _trusted_repair_cloud_client()
|
|
1280
|
+
client = _construct_stable_repair_cloud_client(cloud_client_type)
|
|
1281
|
+
release_source = "stable_api"
|
|
1282
|
+
package_url: str | None = None
|
|
1283
|
+
api_failure = ""
|
|
1284
|
+
try:
|
|
1285
|
+
result = client.check_version(current_version=__version__, channel=channel)
|
|
1286
|
+
except Exception as exc: # noqa: BLE001
|
|
1287
|
+
result = None
|
|
1288
|
+
api_failure = f"{type(exc).__name__}: {exc}"
|
|
1289
|
+
if not getattr(result, "ok", False):
|
|
1290
|
+
if result is not None:
|
|
1291
|
+
api_failure = (
|
|
1292
|
+
str(getattr(result, "error", "") or "")
|
|
1293
|
+
or "发布服务未返回可用版本"
|
|
1294
|
+
)
|
|
1295
|
+
request_fields.update(_update_failure_fields(result))
|
|
1296
|
+
record(
|
|
1297
|
+
"asset_repair_fallback_started",
|
|
1298
|
+
f"BugX stable API 不可用,检查官方 PyPI stable wheel:{api_failure}",
|
|
1299
|
+
phase="pypi_fallback", channel=channel,
|
|
1300
|
+
release_source="pypi", **request_fields,
|
|
1301
|
+
)
|
|
1302
|
+
try:
|
|
1303
|
+
pypi_release = _fetch_pypi_stable_wheel(current_version=__version__)
|
|
1304
|
+
except Exception as exc: # noqa: BLE001
|
|
1305
|
+
record(
|
|
1306
|
+
"asset_repair_failed", str(exc), phase="pypi_metadata",
|
|
1307
|
+
failure_kind=type(exc).__name__, release_source="pypi",
|
|
1308
|
+
release_api_error=api_failure, **request_fields,
|
|
1309
|
+
)
|
|
1310
|
+
raise CliError(
|
|
1311
|
+
f"BugX stable 发布 API 不可用:{api_failure};"
|
|
1312
|
+
f"PyPI 后备也不可用:{exc};"
|
|
1313
|
+
f"同 Build ID 本地 wheel RECORD 恢复不可用:{local_recovery_detail}"
|
|
1314
|
+
) from exc
|
|
1315
|
+
release_source = "pypi"
|
|
1316
|
+
latest = pypi_release["version"]
|
|
1317
|
+
checksum = pypi_release["checksum_sha256"]
|
|
1318
|
+
package_url = pypi_release["url"]
|
|
1319
|
+
min_client = ""
|
|
1320
|
+
remote_build_id = None
|
|
1321
|
+
request_fields.update({
|
|
1322
|
+
"release_source": release_source,
|
|
1323
|
+
"release_api_error": api_failure[:240],
|
|
1324
|
+
"pypi_wheel": pypi_release["filename"],
|
|
1325
|
+
})
|
|
1326
|
+
record(
|
|
1327
|
+
"asset_repair_fallback_selected",
|
|
1328
|
+
f"已选择 PyPI stable wheel {pypi_release['filename']}",
|
|
1329
|
+
phase="pypi_metadata",
|
|
1330
|
+
latest_version=latest, **request_fields,
|
|
1331
|
+
)
|
|
1332
|
+
else:
|
|
1333
|
+
request_fields.update(_update_failure_fields(result))
|
|
1334
|
+
payload = result.data if isinstance(result.data, dict) else {}
|
|
1335
|
+
info = payload.get("data") if isinstance(payload.get("data"), dict) else payload
|
|
1336
|
+
latest = str(info.get("latest_version") or "").strip()
|
|
1337
|
+
min_client = str(info.get("min_client_version") or "").strip()
|
|
1338
|
+
checksum = str(info.get("checksum_sha256") or "").strip().lower()
|
|
1339
|
+
remote_build_id = info.get("build_id")
|
|
1340
|
+
request_fields["release_source"] = release_source
|
|
1341
|
+
|
|
1342
|
+
latest_order = _release_version_tuple(latest)
|
|
1343
|
+
current_order = _release_version_tuple(__version__)
|
|
1344
|
+
minimum_order = _release_version_tuple(min_client) if min_client else None
|
|
1345
|
+
if latest_order is None or current_order is None:
|
|
1346
|
+
raise CliError(f"资源自动修复失败:{release_source} 返回无效版本 {latest!r}")
|
|
1347
|
+
if latest_order[3] != 3:
|
|
1348
|
+
raise CliError(f"资源自动修复拒绝安装 {release_source} 预发布版本")
|
|
1349
|
+
if release_source == "pypi" and not re.fullmatch(r"\d+\.\d+\.\d+", latest):
|
|
1350
|
+
raise CliError("PyPI stable wheel 必须使用 X.Y.Z 版本,拒绝安装")
|
|
1351
|
+
if min_client and minimum_order is None:
|
|
1352
|
+
raise CliError(f"资源自动修复失败:发布服务返回无效最低版本 {min_client!r}")
|
|
1353
|
+
if minimum_order is not None and minimum_order > latest_order:
|
|
1354
|
+
raise CliError("资源自动修复失败:发布服务的最低兼容版本高于发布版本")
|
|
1355
|
+
if latest_order < current_order:
|
|
1356
|
+
raise CliError(
|
|
1357
|
+
f"资源自动修复拒绝版本降级:当前 {__version__},服务端 {latest}"
|
|
1358
|
+
)
|
|
1359
|
+
if not re.fullmatch(r"[0-9a-f]{64}", checksum):
|
|
1360
|
+
raise CliError("资源自动修复失败:发布服务未提供有效 SHA-256 校验值")
|
|
1361
|
+
if remote_build_id is not None and (
|
|
1362
|
+
not isinstance(remote_build_id, int)
|
|
1363
|
+
or isinstance(remote_build_id, bool)
|
|
1364
|
+
or remote_build_id < 1
|
|
1365
|
+
):
|
|
1366
|
+
raise CliError("资源自动修复失败:发布服务返回无效 Build ID")
|
|
1367
|
+
if remote_build_id is not None and remote_build_id < minimum_build_id:
|
|
1368
|
+
raise CliError(
|
|
1369
|
+
f"资源自动修复拒绝低于共享引擎的发布包:最低要求 Build ID "
|
|
1370
|
+
f"{minimum_build_id},服务端 {remote_build_id}"
|
|
1371
|
+
)
|
|
1372
|
+
|
|
1373
|
+
with tempfile.TemporaryDirectory(prefix="bugx-asset-repair-") as temp_name:
|
|
1374
|
+
temp_root = Path(temp_name)
|
|
1375
|
+
package_path = temp_root / "agent.package"
|
|
1376
|
+
if release_source == "pypi":
|
|
1377
|
+
ok, download_message = _download_pypi_stable_wheel(
|
|
1378
|
+
package_url or "", package_path, expected_sha256=checksum,
|
|
1379
|
+
)
|
|
1380
|
+
else:
|
|
1381
|
+
ok, download_message = client.download_package(
|
|
1382
|
+
package_path, expected_sha256=checksum, expected_version=latest,
|
|
1383
|
+
)
|
|
1384
|
+
if not ok:
|
|
1385
|
+
record(
|
|
1386
|
+
"asset_repair_failed", download_message, phase="package_download",
|
|
1387
|
+
failure_kind="download", latest_version=latest,
|
|
1388
|
+
release_source=release_source,
|
|
1389
|
+
)
|
|
1390
|
+
raise CliError(f"资源自动修复下载失败:{download_message}")
|
|
1391
|
+
wheel_path = _prepare_cli_package(package_path)
|
|
1392
|
+
if wheel_path.suffix.lower() != ".whl":
|
|
1393
|
+
raise CliError("资源自动修复只接受 wheel;拒绝安装源码包")
|
|
1394
|
+
wheel_build_id = _validate_agent_repair_wheel(
|
|
1395
|
+
wheel_path, expected_version=latest,
|
|
1396
|
+
minimum_build_id=minimum_build_id, extraction_root=temp_root,
|
|
1397
|
+
)
|
|
1398
|
+
if remote_build_id is not None and remote_build_id != wheel_build_id:
|
|
1399
|
+
raise CliError(
|
|
1400
|
+
f"资源自动修复失败:服务端 Build ID {remote_build_id} 与 wheel {wheel_build_id} 不一致"
|
|
1401
|
+
)
|
|
1402
|
+
|
|
1403
|
+
with _engine_install_lock(global_root):
|
|
1404
|
+
global_valid, global_detail = _engine_self_integrity(global_root)
|
|
1405
|
+
if not global_valid:
|
|
1406
|
+
raise CliError(f"安装前全局引擎完整性校验失败:{global_detail}")
|
|
1407
|
+
latest_global_build_id = _engine_build_id(global_root)
|
|
1408
|
+
latest_asset_build_id = _engine_build_id(installed_assets)
|
|
1409
|
+
if latest_global_build_id is None or latest_global_build_id < 1:
|
|
1410
|
+
raise CliError("安装前全局引擎 Build ID 失效,拒绝调用 pip")
|
|
1411
|
+
latest_floor = max(
|
|
1412
|
+
current_build_id,
|
|
1413
|
+
latest_global_build_id,
|
|
1414
|
+
latest_asset_build_id if latest_asset_build_id and latest_asset_build_id > 0 else 0,
|
|
1415
|
+
)
|
|
1416
|
+
if wheel_build_id < latest_floor:
|
|
1417
|
+
raise CliError(
|
|
1418
|
+
f"资源自动修复拒绝过期 wheel:下载期间 Build ID 下限升至 "
|
|
1419
|
+
f"{latest_floor},wheel 为 {wheel_build_id}"
|
|
1420
|
+
)
|
|
1421
|
+
|
|
1422
|
+
pip_cmd = [
|
|
1423
|
+
sys.executable, "-m", "pip", "install", "--force-reinstall",
|
|
1424
|
+
"--no-deps", "--no-input", "--disable-pip-version-check",
|
|
1425
|
+
str(wheel_path),
|
|
1426
|
+
]
|
|
1427
|
+
try:
|
|
1428
|
+
proc = subprocess.run(pip_cmd, capture_output=True, text=True, timeout=120)
|
|
1429
|
+
except (OSError, subprocess.TimeoutExpired) as exc:
|
|
1430
|
+
record(
|
|
1431
|
+
"asset_repair_failed", str(exc), phase="package_install",
|
|
1432
|
+
failure_kind="install_exception", latest_version=latest,
|
|
1433
|
+
)
|
|
1434
|
+
raise CliError(f"资源自动修复 pip 安装失败:{exc}") from exc
|
|
1435
|
+
if proc.returncode != 0:
|
|
1436
|
+
detail = (proc.stderr or proc.stdout or "pip 未提供错误详情")[-500:]
|
|
1437
|
+
record(
|
|
1438
|
+
"asset_repair_failed", "pip 安装返回非零状态", phase="package_install",
|
|
1439
|
+
failure_kind="nonzero_exit", exit_code=proc.returncode,
|
|
1440
|
+
latest_version=latest,
|
|
1441
|
+
)
|
|
1442
|
+
raise CliError(
|
|
1443
|
+
f"资源自动修复 pip 安装失败(exit {proc.returncode}):{detail}"
|
|
1444
|
+
)
|
|
1445
|
+
|
|
1446
|
+
installed_version = _installed_cli_distribution_version()
|
|
1447
|
+
if installed_version != latest:
|
|
1448
|
+
raise CliError(
|
|
1449
|
+
f"资源自动修复后版本不匹配:期望 {latest},实际 {installed_version or '未知'}"
|
|
1450
|
+
)
|
|
1451
|
+
try:
|
|
1452
|
+
distribution = importlib.metadata.distribution("bugx-cli")
|
|
1453
|
+
direct_url_text = distribution.read_text("direct_url.json")
|
|
1454
|
+
direct_url = json.loads(direct_url_text) if direct_url_text else {}
|
|
1455
|
+
except (importlib.metadata.PackageNotFoundError, json.JSONDecodeError, OSError) as exc:
|
|
1456
|
+
raise CliError(f"资源自动修复后无法验证安装来源:{exc}") from exc
|
|
1457
|
+
if not isinstance(direct_url, dict):
|
|
1458
|
+
raise CliError("资源自动修复后 direct_url.json 格式无效")
|
|
1459
|
+
dir_info = direct_url.get("dir_info")
|
|
1460
|
+
if isinstance(dir_info, dict) and dir_info.get("editable") is True:
|
|
1461
|
+
raise CliError("资源自动修复后仍为 editable 安装,拒绝继续执行")
|
|
1462
|
+
installed_cli_build_id = _installed_cli_build_id(
|
|
1463
|
+
distribution, expected_version=latest,
|
|
1464
|
+
)
|
|
1465
|
+
if installed_cli_build_id != wheel_build_id:
|
|
1466
|
+
raise CliError(
|
|
1467
|
+
f"资源自动修复后 CLI Build ID 不匹配:期望 {wheel_build_id},"
|
|
1468
|
+
f"实际 {installed_cli_build_id}"
|
|
1469
|
+
)
|
|
1470
|
+
|
|
1471
|
+
if installed_assets.is_symlink() or not installed_assets.is_dir():
|
|
1472
|
+
raise CliError(f"资源自动修复后安装载荷目录缺失或不安全:{installed_assets}")
|
|
1473
|
+
valid, detail = _engine_self_integrity(installed_assets)
|
|
1474
|
+
if not valid:
|
|
1475
|
+
raise CliError(f"资源自动修复后引擎资源校验失败:{detail}")
|
|
1476
|
+
installed_asset_build_id = _engine_build_id(installed_assets)
|
|
1477
|
+
if installed_asset_build_id != wheel_build_id:
|
|
1478
|
+
raise CliError(
|
|
1479
|
+
f"资源自动修复后 asset Build ID 不匹配:期望 {wheel_build_id},"
|
|
1480
|
+
f"实际 {installed_asset_build_id}"
|
|
1481
|
+
)
|
|
1482
|
+
try:
|
|
1483
|
+
resolved_assets = asset_root()
|
|
1484
|
+
except MissingAgentAssetError as exc:
|
|
1485
|
+
raise CliError(f"资源自动修复后 CLI 仍找不到安装载荷:{exc}") from exc
|
|
1486
|
+
if resolved_assets.resolve(strict=True) != installed_assets.resolve(strict=True):
|
|
1487
|
+
raise CliError("资源自动修复后 asset_root 未指向刚安装的 wheel 载荷")
|
|
1488
|
+
|
|
1489
|
+
source_label = "官方 PyPI" if release_source == "pypi" else "BugX stable 发行 API"
|
|
1490
|
+
message = f"BugX CLI {latest}+build.{wheel_build_id} 安装资源已恢复(来源:{source_label})"
|
|
1491
|
+
record(
|
|
1492
|
+
"asset_repair_succeeded", message, phase="package_verify",
|
|
1493
|
+
latest_version=latest, build_id=wheel_build_id, **request_fields,
|
|
1494
|
+
)
|
|
1495
|
+
return message
|
|
1496
|
+
except Exception as exc: # noqa: BLE001
|
|
1497
|
+
record(
|
|
1498
|
+
"asset_repair_failed", str(exc), phase="repair", failure_kind=type(exc).__name__,
|
|
1499
|
+
channel=channel, **request_fields,
|
|
1500
|
+
)
|
|
1501
|
+
raise
|
|
1502
|
+
|
|
1503
|
+
|
|
1504
|
+
def restart_cli_after_asset_repair() -> None:
|
|
1505
|
+
"""Restart this exact CLI command once so imports use the installed wheel."""
|
|
1506
|
+
os.environ[_ASSET_REPAIR_ATTEMPT_ENV] = "1"
|
|
1507
|
+
command = [sys.executable, "-m", "bugx_cli.cli", *sys.argv[1:]]
|
|
1508
|
+
try:
|
|
1509
|
+
os.execv(sys.executable, command)
|
|
1510
|
+
except OSError as exc:
|
|
1511
|
+
raise CliError(f"资源已修复,但无法重启 CLI:{exc}") from exc
|
|
1512
|
+
raise CliError("资源已修复,但 CLI 进程替换意外返回")
|
|
1513
|
+
|
|
1514
|
+
|
|
1515
|
+
def _update_host_names(root: Path) -> list[str]:
|
|
1516
|
+
"""Return BugX-managed hosts that should be refreshed after a CLI update."""
|
|
1517
|
+
known_hosts = {adapter.name for adapter in HOST_ADAPTERS}
|
|
1518
|
+
names: list[str] = []
|
|
1519
|
+
record = root / ".bugx" / "hosts.json"
|
|
1520
|
+
if record.is_file() and not record.is_symlink():
|
|
1521
|
+
try:
|
|
1522
|
+
payload = json.loads(record.read_text(encoding="utf-8"))
|
|
1523
|
+
installed = payload.get("installed") if isinstance(payload, dict) else None
|
|
1524
|
+
if isinstance(installed, list):
|
|
1525
|
+
for item in installed:
|
|
1526
|
+
name = item.get("name") if isinstance(item, dict) else None
|
|
1527
|
+
if isinstance(name, str) and name in known_hosts and name not in names:
|
|
1528
|
+
names.append(name)
|
|
1529
|
+
except (OSError, json.JSONDecodeError):
|
|
1530
|
+
# A malformed historical record must not become a command source;
|
|
1531
|
+
# fall back to the live host detector below.
|
|
1532
|
+
pass
|
|
1533
|
+
if names:
|
|
1534
|
+
return names
|
|
1535
|
+
try:
|
|
1536
|
+
return [
|
|
1537
|
+
str(item["name"])
|
|
1538
|
+
for item in discover_hosts(root)
|
|
1539
|
+
if isinstance(item, dict)
|
|
1540
|
+
and item.get("installed") is True
|
|
1541
|
+
and isinstance(item.get("name"), str)
|
|
1542
|
+
and item["name"] in known_hosts
|
|
1543
|
+
]
|
|
1544
|
+
except (OSError, ValueError, RuntimeError):
|
|
1545
|
+
return []
|
|
1546
|
+
|
|
1547
|
+
|
|
1548
|
+
def command_update(args: argparse.Namespace) -> int:
|
|
1549
|
+
"""bugx update:检查、下载并安装最新 CLI 包。
|
|
1550
|
+
|
|
1551
|
+
流程:
|
|
1552
|
+
1. GET /api/v1/agent/version 获取最新版本元数据
|
|
1553
|
+
2. 如果已是最新 → 提示并退出
|
|
1554
|
+
3. 下载 CLI 包到临时目录
|
|
1555
|
+
4. SHA-256 校验
|
|
1556
|
+
5. pip install --upgrade <下载的包路径>
|
|
1557
|
+
6. bugx install --agent <已登记宿主> --root . --force --non-interactive(刷新宿主入口)
|
|
1558
|
+
7. bugx doctor --installation-only 验证
|
|
1559
|
+
"""
|
|
1560
|
+
root = getattr(args, "root", Path.cwd()).resolve()
|
|
1561
|
+
started = time.monotonic()
|
|
1562
|
+
|
|
1563
|
+
if getattr(args, "repair_assets", False):
|
|
1564
|
+
if getattr(args, "check", False):
|
|
1565
|
+
print("[update] --check 为只读操作,不能与 --repair-assets 同时使用")
|
|
1566
|
+
return 2
|
|
1567
|
+
if not getattr(args, "_console_entrypoint", False):
|
|
1568
|
+
print("[update] --repair-assets 只允许由已安装的 CLI 控制台入口执行")
|
|
1569
|
+
return 2
|
|
1570
|
+
if getattr(args, "channel", "") not in {"", "stable"}:
|
|
1571
|
+
print("[update] --repair-assets 只使用 stable 发布通道;请移除 -c alpha")
|
|
1572
|
+
return 2
|
|
1573
|
+
if os.environ.get(_ASSET_REPAIR_ATTEMPT_ENV) == "1":
|
|
1574
|
+
print("[update] CLI 安装资源已恢复。")
|
|
1575
|
+
return 0
|
|
1576
|
+
else:
|
|
1577
|
+
try:
|
|
1578
|
+
detail = repair_cli_agent_assets(
|
|
1579
|
+
channel="stable", root=root,
|
|
1580
|
+
)
|
|
1581
|
+
except Exception as exc: # noqa: BLE001
|
|
1582
|
+
print(f"[update] 安装资源修复失败:{exc}")
|
|
1583
|
+
return 2
|
|
1584
|
+
if detail == "已安装 Agent 资源完整,无需修复":
|
|
1585
|
+
print(f"[update] {detail}")
|
|
1586
|
+
return 0
|
|
1587
|
+
print(f"[update] {detail};正在重启原命令以加载新安装... ")
|
|
1588
|
+
restart_cli_after_asset_repair()
|
|
1589
|
+
|
|
1590
|
+
def record_failure(message: str, *, phase: str, **fields: object) -> None:
|
|
1591
|
+
_log_update_event(
|
|
1592
|
+
root, "update_check_failed", message,
|
|
1593
|
+
phase=phase, duration_ms=round((time.monotonic() - started) * 1000, 1),
|
|
1594
|
+
**fields,
|
|
1595
|
+
)
|
|
1596
|
+
|
|
1597
|
+
try:
|
|
1598
|
+
_ensure_core_importable()
|
|
1599
|
+
from core.cloud_sync.cloud_client import CloudClient
|
|
1600
|
+
except MissingAgentAssetError:
|
|
1601
|
+
# Preserve the typed failure for main(), where only an actual console
|
|
1602
|
+
# invocation may repair the current Python install and re-exec once.
|
|
1603
|
+
raise
|
|
1604
|
+
except Exception as exc: # noqa: BLE001
|
|
1605
|
+
record_failure(str(exc), phase="dependency_load", failure_kind="dependency")
|
|
1606
|
+
print(f"[update] 依赖加载失败: {exc}")
|
|
1607
|
+
return 2
|
|
1608
|
+
|
|
1609
|
+
if getattr(args, "check", False):
|
|
1610
|
+
return command_version_check(args)
|
|
1611
|
+
|
|
1612
|
+
client = CloudClient()
|
|
1613
|
+
|
|
1614
|
+
# 1. 版本检查(支持指定发布通道)
|
|
1615
|
+
channel = _update_channel(args)
|
|
1616
|
+
try:
|
|
1617
|
+
result = client.check_version(current_version=__version__, channel=channel)
|
|
1618
|
+
except Exception as exc: # noqa: BLE001
|
|
1619
|
+
record_failure(str(exc), phase="version_check", failure_kind="exception")
|
|
1620
|
+
print(f"[update] 版本检查失败: {exc}")
|
|
1621
|
+
# `bugx update --check` 早就有这个提示,但非 --check 路径漏了:
|
|
1622
|
+
# 自签/内网 CA 下的升级失败只剩一串 CERTIFICATE_VERIFY_FAILED,
|
|
1623
|
+
# 而升级通道恰恰是用户摆脱旧 CLI 的唯一出路。
|
|
1624
|
+
_print_version_tls_hint(exc)
|
|
1625
|
+
return 2
|
|
1626
|
+
|
|
1627
|
+
if not result.ok:
|
|
1628
|
+
err = getattr(result, "error", "") or "未知错误"
|
|
1629
|
+
record_failure(
|
|
1630
|
+
err, phase="version_check", failure_kind="remote",
|
|
1631
|
+
**_update_failure_fields(result),
|
|
1632
|
+
)
|
|
1633
|
+
print(f"[update] 无法获取版本信息: {err}")
|
|
1634
|
+
_print_version_tls_hint(err)
|
|
1635
|
+
return 2
|
|
1636
|
+
|
|
1637
|
+
data = result.data if isinstance(result.data, dict) else {}
|
|
1638
|
+
info = data.get("data") if isinstance(data.get("data"), dict) else data
|
|
1639
|
+
if channel:
|
|
1640
|
+
print(f"[update] 检查通道 ({channel}) 最新版本...")
|
|
1641
|
+
latest = str(info.get("latest_version") or "").strip()
|
|
1642
|
+
min_client = str(info.get("min_client_version") or "").strip()
|
|
1643
|
+
checksum = str(info.get("checksum_sha256") or "").strip().lower()
|
|
1644
|
+
notes = str(info.get("release_notes") or "")
|
|
1645
|
+
update_available = info.get("update_available") is True
|
|
1646
|
+
update_required = info.get("update_required") is True
|
|
1647
|
+
rollback_required = (info.get("rollback_required") is True
|
|
1648
|
+
or info.get("allow_downgrade") is True)
|
|
1649
|
+
allow_downgrade = (getattr(args, "allow_downgrade", False)
|
|
1650
|
+
or getattr(args, "force", False)
|
|
1651
|
+
or rollback_required)
|
|
1652
|
+
|
|
1653
|
+
current_version = _release_version_tuple(__version__)
|
|
1654
|
+
latest_version = _release_version_tuple(latest)
|
|
1655
|
+
min_version = _release_version_tuple(min_client) if min_client else None
|
|
1656
|
+
if current_version is None or latest_version is None:
|
|
1657
|
+
record_failure("服务端返回了无效版本号", phase="version_validation",
|
|
1658
|
+
failure_kind="invalid_version", latest_version=latest)
|
|
1659
|
+
print(f"[update] 服务端返回了无效版本号: {latest!r}")
|
|
1660
|
+
return 2
|
|
1661
|
+
if min_client and min_version is None:
|
|
1662
|
+
record_failure("服务端返回了无效最低兼容版本", phase="version_validation",
|
|
1663
|
+
failure_kind="invalid_min_client", min_client_version=min_client)
|
|
1664
|
+
print(f"[update] 服务端返回了无效最低兼容版本: {min_client!r}")
|
|
1665
|
+
return 2
|
|
1666
|
+
if min_version is not None and min_version > latest_version:
|
|
1667
|
+
record_failure("服务端版本元数据矛盾", phase="version_validation",
|
|
1668
|
+
failure_kind="inconsistent_metadata",
|
|
1669
|
+
latest_version=latest, min_client_version=min_client)
|
|
1670
|
+
print(
|
|
1671
|
+
f"[update] 服务端版本元数据矛盾:最低兼容版本 {min_client} "
|
|
1672
|
+
f"高于发布版本 {latest}"
|
|
1673
|
+
)
|
|
1674
|
+
return 2
|
|
1675
|
+
is_rollback = latest_version < current_version
|
|
1676
|
+
if is_rollback and not allow_downgrade:
|
|
1677
|
+
record_failure("服务端版本低于当前版本", phase="version_validation",
|
|
1678
|
+
failure_kind="downgrade", latest_version=latest,
|
|
1679
|
+
current_version=__version__)
|
|
1680
|
+
print(f"[update] 拒绝降级:服务端版本 {latest} 低于当前版本 {__version__}(使用 --allow-downgrade 允许版本回退)")
|
|
1681
|
+
return 2
|
|
1682
|
+
if is_rollback:
|
|
1683
|
+
print(f"[update] 确认服务端版本回退请求 ({__version__} → {latest})...")
|
|
1684
|
+
|
|
1685
|
+
# 2. 已是最新?
|
|
1686
|
+
if (latest_version == current_version and not update_available and not update_required
|
|
1687
|
+
and not getattr(args, "force", False)):
|
|
1688
|
+
print(f"[update] BugX 已是最新版本 ({__version__})")
|
|
1689
|
+
return 0
|
|
1690
|
+
|
|
1691
|
+
# The package is downloaded through the trusted BugX endpoint even when
|
|
1692
|
+
# the server internally redirects to an external mirror. This preserves
|
|
1693
|
+
# one client-side verification path and prevents pip from installing an
|
|
1694
|
+
# arbitrary URL without the advertised digest. A checksum is not needed
|
|
1695
|
+
# for the no-op path above, but is mandatory for every actual install.
|
|
1696
|
+
if not re.fullmatch(r"[0-9a-fA-F]{64}", checksum):
|
|
1697
|
+
record_failure("服务端未提供有效 SHA-256 校验值", phase="package_validation",
|
|
1698
|
+
failure_kind="missing_checksum", latest_version=latest)
|
|
1699
|
+
print("[update] 服务端未提供有效 SHA-256 校验值,拒绝安装未校验的升级包")
|
|
1700
|
+
return 2
|
|
1701
|
+
|
|
1702
|
+
print(f"[update] 当前版本: {__version__}")
|
|
1703
|
+
print(f"[update] 目标版本: {latest}")
|
|
1704
|
+
if notes:
|
|
1705
|
+
print(f"[update] 变更说明: {notes}")
|
|
1706
|
+
|
|
1707
|
+
# 3. 下载 CLI 包。无论 download_url 是否为外部地址,都走服务端
|
|
1708
|
+
# /agent/download;服务端的 302 由下载器跟随,摘要校验始终在本地完成。
|
|
1709
|
+
tmpdir = Path(tempfile.mkdtemp(prefix="bugx-update-"))
|
|
1710
|
+
try:
|
|
1711
|
+
dest = tmpdir / f"bugx-{latest}.package"
|
|
1712
|
+
print(f"[update] 正在下载 CLI 包...")
|
|
1713
|
+
ok, msg = client.download_package(
|
|
1714
|
+
dest, expected_sha256=checksum, expected_version=latest,
|
|
1715
|
+
)
|
|
1716
|
+
if not ok:
|
|
1717
|
+
record_failure(msg, phase="package_download", failure_kind="download")
|
|
1718
|
+
print(f"[update] {msg}")
|
|
1719
|
+
return 1
|
|
1720
|
+
print(f"[update] {msg}")
|
|
1721
|
+
try:
|
|
1722
|
+
package_target = str(_prepare_cli_package(dest))
|
|
1723
|
+
except (CliError, OSError) as exc:
|
|
1724
|
+
record_failure(str(exc), phase="package_validation", failure_kind="package_format")
|
|
1725
|
+
print(f"[update] {exc}")
|
|
1726
|
+
return 1
|
|
1727
|
+
|
|
1728
|
+
# 4. pip install --upgrade
|
|
1729
|
+
print(f"[update] 执行 pip install --upgrade {package_target}...")
|
|
1730
|
+
pip_cmd = [sys.executable, "-m", "pip", "install", "--upgrade",
|
|
1731
|
+
"--no-input", package_target]
|
|
1732
|
+
if is_rollback:
|
|
1733
|
+
# 回退到更低版本:pip --upgrade 不会降级,改用 --force-reinstall
|
|
1734
|
+
pip_cmd = [sys.executable, "-m", "pip", "install",
|
|
1735
|
+
"--force-reinstall", "--no-input", package_target]
|
|
1736
|
+
try:
|
|
1737
|
+
proc = subprocess.run(pip_cmd, capture_output=True, text=True, timeout=120)
|
|
1738
|
+
except subprocess.TimeoutExpired:
|
|
1739
|
+
record_failure("pip install 超时(120s)", phase="package_install", failure_kind="timeout")
|
|
1740
|
+
print("[update] pip install 超时(120s)")
|
|
1741
|
+
return 1
|
|
1742
|
+
except OSError as exc:
|
|
1743
|
+
record_failure(str(exc), phase="package_install", failure_kind="exec")
|
|
1744
|
+
print(f"[update] pip install 执行失败: {exc}")
|
|
1745
|
+
return 1
|
|
1746
|
+
|
|
1747
|
+
if proc.returncode != 0:
|
|
1748
|
+
record_failure(
|
|
1749
|
+
f"pip install exit {proc.returncode}", phase="package_install",
|
|
1750
|
+
failure_kind="nonzero_exit", exit_code=proc.returncode,
|
|
1751
|
+
)
|
|
1752
|
+
print(f"[update] pip install 失败 (exit {proc.returncode})")
|
|
1753
|
+
if proc.stderr:
|
|
1754
|
+
print(proc.stderr[-500:])
|
|
1755
|
+
return 1
|
|
1756
|
+
|
|
1757
|
+
installed_version = _installed_cli_distribution_version()
|
|
1758
|
+
if installed_version != latest:
|
|
1759
|
+
record_failure(
|
|
1760
|
+
"安装后版本校验失败", phase="package_install",
|
|
1761
|
+
failure_kind="version_mismatch", expected_version=latest,
|
|
1762
|
+
installed_version=installed_version,
|
|
1763
|
+
)
|
|
1764
|
+
print(
|
|
1765
|
+
f"[update] 安装后版本校验失败:期望 {latest},"
|
|
1766
|
+
f"实际 {installed_version or '未知'}"
|
|
1767
|
+
)
|
|
1768
|
+
return 1
|
|
1769
|
+
print(f"[update] pip install 成功,已安装版本 {installed_version}")
|
|
1770
|
+
|
|
1771
|
+
# 更新全局运行时引擎与宿主登记独立;没有 hosts.json 也必须刷新并验证。
|
|
1772
|
+
try:
|
|
1773
|
+
_install_engine(asset_root(), force=False)
|
|
1774
|
+
engine_ok, engine_detail = _engine_integrity_status(
|
|
1775
|
+
asset_root(), global_engine_root(),
|
|
1776
|
+
)
|
|
1777
|
+
except Exception as exc: # noqa: BLE001
|
|
1778
|
+
engine_ok, engine_detail = False, str(exc)
|
|
1779
|
+
if not engine_ok:
|
|
1780
|
+
record_failure(engine_detail, phase="engine_refresh", failure_kind="integrity")
|
|
1781
|
+
print(f"[update] 全局引擎刷新或完整性校验失败:{engine_detail}")
|
|
1782
|
+
return 1
|
|
1783
|
+
|
|
1784
|
+
# 5. 刷新宿主入口。失败必须报告失败,不能把“CLI 已更新但项目仍旧”
|
|
1785
|
+
# 伪装成完整成功;用户可重试 bugx install --force。
|
|
1786
|
+
host_names = _update_host_names(root)
|
|
1787
|
+
if host_names:
|
|
1788
|
+
print("[update] 刷新 BugX 宿主入口...")
|
|
1789
|
+
install_cmd = [sys.executable, "-m", "bugx_cli.cli",
|
|
1790
|
+
"install", "--root", str(root), "--force",
|
|
1791
|
+
"--non-interactive", "--allow-missing"]
|
|
1792
|
+
for host_name in host_names:
|
|
1793
|
+
install_cmd.extend(["--agent", host_name])
|
|
1794
|
+
try:
|
|
1795
|
+
install_proc = subprocess.run(
|
|
1796
|
+
install_cmd, capture_output=True, text=True, timeout=30,
|
|
1797
|
+
)
|
|
1798
|
+
except subprocess.TimeoutExpired:
|
|
1799
|
+
record_failure("宿主入口刷新超时", phase="host_refresh", failure_kind="timeout")
|
|
1800
|
+
print("[update] 宿主入口刷新失败:超时(30s)")
|
|
1801
|
+
return 1
|
|
1802
|
+
except OSError as exc:
|
|
1803
|
+
record_failure(str(exc), phase="host_refresh", failure_kind="exec")
|
|
1804
|
+
print(f"[update] 宿主入口刷新失败:{exc}")
|
|
1805
|
+
return 1
|
|
1806
|
+
if install_proc.returncode != 0:
|
|
1807
|
+
record_failure(
|
|
1808
|
+
f"宿主入口刷新 exit {install_proc.returncode}", phase="host_refresh",
|
|
1809
|
+
failure_kind="nonzero_exit", exit_code=install_proc.returncode,
|
|
1810
|
+
)
|
|
1811
|
+
print(f"[update] 宿主入口刷新失败 (exit {install_proc.returncode})")
|
|
1812
|
+
if install_proc.stderr:
|
|
1813
|
+
print(install_proc.stderr[-500:])
|
|
1814
|
+
if install_proc.stdout:
|
|
1815
|
+
print(install_proc.stdout[-1000:])
|
|
1816
|
+
return 1
|
|
1817
|
+
print("[update] 宿主入口已刷新:" + ", ".join(host_names))
|
|
1818
|
+
else:
|
|
1819
|
+
print("[update] 未发现已登记的 BugX 宿主,跳过宿主入口刷新")
|
|
1820
|
+
|
|
1821
|
+
# 6. 验证安装完整性。必须校验同一个 --root,避免更新 A 项目却诊断
|
|
1822
|
+
# 当前工作目录 B 项目。
|
|
1823
|
+
print("[update] 验证安装完整性...")
|
|
1824
|
+
doctor_cmd = [sys.executable, "-m", "bugx_cli.cli", "doctor",
|
|
1825
|
+
"--root", str(root), "--installation-only"]
|
|
1826
|
+
try:
|
|
1827
|
+
doctor_proc = subprocess.run(doctor_cmd, capture_output=True, text=True, timeout=30)
|
|
1828
|
+
except subprocess.TimeoutExpired:
|
|
1829
|
+
record_failure("安装验证超时", phase="installation_verify", failure_kind="timeout")
|
|
1830
|
+
print("[update] 安装验证失败:超时(30s)")
|
|
1831
|
+
return 1
|
|
1832
|
+
except OSError as exc:
|
|
1833
|
+
record_failure(str(exc), phase="installation_verify", failure_kind="exec")
|
|
1834
|
+
print(f"[update] 安装验证失败:{exc}")
|
|
1835
|
+
return 1
|
|
1836
|
+
if doctor_proc.returncode != 0:
|
|
1837
|
+
record_failure(
|
|
1838
|
+
f"安装验证 exit {doctor_proc.returncode}", phase="installation_verify",
|
|
1839
|
+
failure_kind="nonzero_exit", exit_code=doctor_proc.returncode,
|
|
1840
|
+
)
|
|
1841
|
+
print(f"[update] 安装验证失败 (exit {doctor_proc.returncode})")
|
|
1842
|
+
if doctor_proc.stderr:
|
|
1843
|
+
print(doctor_proc.stderr[-500:])
|
|
1844
|
+
if doctor_proc.stdout:
|
|
1845
|
+
print(doctor_proc.stdout[-1500:])
|
|
1846
|
+
return 1
|
|
1847
|
+
print("[update] 安装验证通过")
|
|
1848
|
+
|
|
1849
|
+
print(f"\n✓ BugX 已更新到 {latest}")
|
|
1850
|
+
print("请重新运行 bugx 命令以使用新版本。")
|
|
1851
|
+
return 0
|
|
1852
|
+
finally:
|
|
1853
|
+
try:
|
|
1854
|
+
shutil.rmtree(tmpdir, ignore_errors=True)
|
|
1855
|
+
except Exception: # noqa: BLE001
|
|
1856
|
+
pass
|
|
1857
|
+
|
|
1858
|
+
|
|
1859
|
+
|
|
1860
|
+
# DOC-230 层 1:恢复动作的带外入口。这些动作在 MCP 侧是 host-only,而 host 通道
|
|
1861
|
+
# 可能被闲置会话独占(BX-ENGINE-11),导致宿主无法恢复/推进/收尾。CLI 直连引擎
|
|
1862
|
+
# `supervisor/cli.py`,经 Supervisor 自身状态锁串行化,因此不引入提权面(审计 R2-Q1)。
|
|
1863
|
+
SUPERVISOR_RECOVERY_ACTIONS = (
|
|
1864
|
+
"reset-budget", "recover", "rebind-target", "gate", "repair-fence",
|
|
1865
|
+
)
|
|
1866
|
+
|
|
1867
|
+
# DOC-230 §3.8 第 4 项:severity 修复通道(历史脏数据出口,host 或 CLI)。
|
|
1868
|
+
# 与恢复动作**分列**:修复不是 `next_action` 恢复链的一环,混在一起会让
|
|
1869
|
+
# 「恢复链穷举」守卫与 CLI 白名单语义互相污染。
|
|
1870
|
+
SUPERVISOR_REPAIR_ACTIONS = ("findings",)
|
|
1871
|
+
|
|
1872
|
+
# DOC-230 §3.1:`finish` / `next_round` 等**决策类**动作在 MCP 侧保持 host-only
|
|
1873
|
+
# (它们表达"宿主决策"),但"必须通过层 2/3 变得**可达**"。CLI 直连即该可达性,
|
|
1874
|
+
# 故纳入带外白名单——否则恢复动作注册表指向的 `bugx supervisor next-round`
|
|
1875
|
+
# 会被 argparse 拒绝(声明不可达,与 A1 同型)。
|
|
1876
|
+
SUPERVISOR_DECISION_ACTIONS = ("next-round", "finish")
|
|
1877
|
+
|
|
1878
|
+
# CLI `choices` 与 dispatch 的**唯一**白名单真源。此前两处各自硬编码枚举
|
|
1879
|
+
# (argparse choices 与 dispatch 元组),新增动作时漏改任一处即出现
|
|
1880
|
+
# 「帮助里列出但调用被拒」或反之的静默漂移——与本会话反复审计的
|
|
1881
|
+
# 「声明与实现不一致」同型,故由本元组派生。
|
|
1882
|
+
SUPERVISOR_PASSTHROUGH_ACTIONS = (
|
|
1883
|
+
SUPERVISOR_RECOVERY_ACTIONS
|
|
1884
|
+
+ SUPERVISOR_REPAIR_ACTIONS
|
|
1885
|
+
+ SUPERVISOR_DECISION_ACTIONS
|
|
1886
|
+
)
|
|
1887
|
+
|
|
1888
|
+
|
|
1889
|
+
def _supervisor_recovery_action(root: Path, action: str, forwarded: list[str]) -> int:
|
|
1890
|
+
"""把恢复动作转发给引擎 supervisor CLI,并强制指向**真实**的生命周期状态路径。
|
|
1891
|
+
|
|
1892
|
+
引擎 CLI 的默认 ``--state .bugx/audit-supervisor.json`` 与真实状态
|
|
1893
|
+
(``.bugx/pollings/<p>/lifecycles/<l>/state/supervisor.json``)不一致;
|
|
1894
|
+
沿用默认值会让命令「成功」却作用在一个不存在的账本上(静默空转)。
|
|
1895
|
+
"""
|
|
1896
|
+
try:
|
|
1897
|
+
layout = _layout_module(root).require(root)
|
|
1898
|
+
state_path = Path(layout.supervisor)
|
|
1899
|
+
except Exception as exc: # noqa: BLE001 - 布局不可解析时必须显式失败
|
|
1900
|
+
print(f"[supervisor] 无法解析生命周期状态路径: {exc}", file=sys.stderr)
|
|
1901
|
+
return 2
|
|
1902
|
+
argv: list[str] = [action, "--root", str(root), "--state", str(state_path)]
|
|
1903
|
+
skip_next = False
|
|
1904
|
+
for item in forwarded:
|
|
1905
|
+
if skip_next:
|
|
1906
|
+
skip_next = False
|
|
1907
|
+
continue
|
|
1908
|
+
if item in ("--root", "--state"):
|
|
1909
|
+
skip_next = True
|
|
1910
|
+
continue
|
|
1911
|
+
if item.startswith("--root=") or item.startswith("--state="):
|
|
1912
|
+
continue
|
|
1913
|
+
argv.append(item)
|
|
1914
|
+
return _run_script(root, Path("supervisor") / "cli.py", argv)
|
|
1915
|
+
|
|
1916
|
+
|
|
1917
|
+
def command_supervisor(args: argparse.Namespace) -> int:
|
|
1918
|
+
"""canonical supervisor MCP:install(部署/接线)/ status(部署状态)/ rpc(协议回退通道)。"""
|
|
1919
|
+
forwarded = list(getattr(args, "supervisor_args", []) or [])
|
|
1920
|
+
# ``supervisor_args`` uses argparse.REMAINDER so rpc options can be passed
|
|
1921
|
+
# through. That also captures ``--root`` when it appears after the action
|
|
1922
|
+
# (for example ``supervisor status --root <project>``). Honor that root for
|
|
1923
|
+
# all actions while leaving rpc's argv intact.
|
|
1924
|
+
root = args.root
|
|
1925
|
+
index = 0
|
|
1926
|
+
while index < len(forwarded):
|
|
1927
|
+
item = forwarded[index]
|
|
1928
|
+
if item == "--root":
|
|
1929
|
+
if index + 1 >= len(forwarded) or not forwarded[index + 1]:
|
|
1930
|
+
print("[supervisor] --root 缺少路径", file=sys.stderr)
|
|
1931
|
+
return 2
|
|
1932
|
+
root = Path(forwarded[index + 1])
|
|
1933
|
+
index += 2
|
|
1934
|
+
continue
|
|
1935
|
+
if item.startswith("--root="):
|
|
1936
|
+
value = item.partition("=")[2]
|
|
1937
|
+
if not value:
|
|
1938
|
+
print("[supervisor] --root 缺少路径", file=sys.stderr)
|
|
1939
|
+
return 2
|
|
1940
|
+
root = Path(value)
|
|
1941
|
+
index += 1
|
|
1942
|
+
root = root.expanduser().resolve()
|
|
1943
|
+
act = args.supervisor_command
|
|
1944
|
+
if act == "rpc":
|
|
1945
|
+
# PE-20261005-003 集成:worker 协议 CLI 回退通道,一问一答直连引擎
|
|
1946
|
+
has_forwarded_root = any(
|
|
1947
|
+
item == "--root" or item.startswith("--root=")
|
|
1948
|
+
for item in forwarded
|
|
1949
|
+
)
|
|
1950
|
+
if not has_forwarded_root:
|
|
1951
|
+
forwarded = ["--root", str(root), *forwarded]
|
|
1952
|
+
return _run_script(root, Path("supervisor") / "cli.py", ["rpc", *forwarded])
|
|
1953
|
+
if act == "install":
|
|
1954
|
+
return _supervisor_deploy(root)
|
|
1955
|
+
if act == "status":
|
|
1956
|
+
return _supervisor_status(root)
|
|
1957
|
+
if act in SUPERVISOR_PASSTHROUGH_ACTIONS:
|
|
1958
|
+
return _supervisor_recovery_action(root, act, forwarded)
|
|
1959
|
+
return 2
|
|
1960
|
+
|
|
1961
|
+
|
|
1962
|
+
|
|
1963
|
+
def command_self_audit(args: argparse.Namespace) -> int:
|
|
1964
|
+
"""Expose the safe core self-audit orchestrator as a discoverable CLI command."""
|
|
1965
|
+
root = args.root.resolve()
|
|
1966
|
+
forwarded = list(getattr(args, "self_audit_args", []) or [])
|
|
1967
|
+
if forwarded and forwarded[0] == "--":
|
|
1968
|
+
forwarded = forwarded[1:]
|
|
1969
|
+
if not forwarded:
|
|
1970
|
+
forwarded = [
|
|
1971
|
+
"run", "--root", str(root),
|
|
1972
|
+
"--out", str(root / ".bugx" / "evidence" / "self-audit"),
|
|
1973
|
+
]
|
|
1974
|
+
elif forwarded[0] == "run" and "--root" not in forwarded:
|
|
1975
|
+
forwarded[1:1] = ["--root", str(root)]
|
|
1976
|
+
return _run_script(root, "self_audit.py", forwarded, timeout=300)
|
|
1977
|
+
|
|
1978
|
+
|
|
1979
|
+
def command_engine(args: argparse.Namespace) -> int:
|
|
1980
|
+
"""Run the lifecycle launcher from the single global engine.
|
|
1981
|
+
|
|
1982
|
+
This is the public replacement for the removed project-local launch entry.
|
|
1983
|
+
``BUGX_PROJECT_ROOT`` is passed to
|
|
1984
|
+
the engine so the same command works from Windows, Linux and macOS even
|
|
1985
|
+
when the global engine and project live on different volumes.
|
|
1986
|
+
"""
|
|
1987
|
+
root = resolve_project_root(args.root).resolve()
|
|
1988
|
+
if not root.is_dir():
|
|
1989
|
+
# 宿主最容易犯的错是把 `--root` 指到拼错的路径 / 还没 clone 的目录。
|
|
1990
|
+
# 静默让 subprocess 以 cwd 缺失抛 FileNotFoundError 只会产出一条
|
|
1991
|
+
# 「Unhandled exception」堆栈,宿主无法判断是参数错还是引擎坏。
|
|
1992
|
+
raise CliError(
|
|
1993
|
+
f"项目根目录不存在或不是目录:{root};"
|
|
1994
|
+
"请用 `--root` 指向已初始化的项目目录(或先在该目录执行 `bugx init`)。"
|
|
1995
|
+
)
|
|
1996
|
+
forwarded = list(getattr(args, "engine_args", []) or [])
|
|
1997
|
+
if forwarded and forwarded[0] == "--":
|
|
1998
|
+
forwarded = forwarded[1:]
|
|
1999
|
+
if not forwarded:
|
|
2000
|
+
forwarded = ["status"]
|
|
2001
|
+
if forwarded[0] == "path":
|
|
2002
|
+
if len(forwarded) != 3 or forwarded[1] not in {"--name", "-n"}:
|
|
2003
|
+
raise CliError("用法:bugx engine --root <项目> path --name <引擎文件>")
|
|
2004
|
+
# 引擎按领域拆包后,逐层白名单永远滞后于一次重构;改为「精确相对路径 →
|
|
2005
|
+
# 同名递归查找(必须唯一)」,命中歧义时 fail-closed。
|
|
2006
|
+
print(resolve_engine_file(Path(forwarded[2]), kind="文件").resolve())
|
|
2007
|
+
return 0
|
|
2008
|
+
script = _script(root, "launch_bugx.py")
|
|
2009
|
+
environment = _python_environment({
|
|
2010
|
+
"BUGX_PROJECT_ROOT": str(root),
|
|
2011
|
+
"BUGX_GLOBAL_ENGINE_ROOT": str(global_engine_root()),
|
|
2012
|
+
# The global launcher cannot infer which installed CLI wrapper invoked
|
|
2013
|
+
# it when PATH contains an older `bugx`. Pass the current wrapper's
|
|
2014
|
+
# contract explicitly so an unrelated PATH entry cannot create a false
|
|
2015
|
+
# version drift report.
|
|
2016
|
+
"BUGX_CLI_VERSION": __version__,
|
|
2017
|
+
})
|
|
2018
|
+
return subprocess.call(
|
|
2019
|
+
[sys.executable, str(script), *forwarded],
|
|
2020
|
+
cwd=root,
|
|
2021
|
+
env=environment,
|
|
2022
|
+
)
|
|
2023
|
+
|
|
2024
|
+
|
|
2025
|
+
def command_probe(args: argparse.Namespace, extra_args: list[str] | None = None) -> int:
|
|
2026
|
+
"""运行探针包装命令,透传选定 probe 的参数。"""
|
|
2027
|
+
root = args.root.resolve()
|
|
2028
|
+
script_name = PROBE_SCRIPTS[args.probe_kind]
|
|
2029
|
+
forward_args: list[str] = []
|
|
2030
|
+
actual_extra = extra_args if extra_args is not None else getattr(args, "probe_args", [])
|
|
2031
|
+
if actual_extra:
|
|
2032
|
+
forward_args.extend(actual_extra)
|
|
2033
|
+
if args.probe_kind not in PROBES_WITHOUT_ROOT_ARGUMENT \
|
|
2034
|
+
and "--root" not in forward_args and "-r" not in forward_args:
|
|
2035
|
+
forward_args.extend(["--root", str(root)])
|
|
2036
|
+
return _run_script(root, script_name, forward_args, timeout=300)
|
|
2037
|
+
|
|
2038
|
+
|
|
2039
|
+
def command_mcp_prune(args: argparse.Namespace) -> int:
|
|
2040
|
+
"""DOC-230 3.2 / A11: 清理被遗弃的同项目 MCP 会话进程(默认 dry-run)。"""
|
|
2041
|
+
import core.bugx_paths as bugx_paths
|
|
2042
|
+
|
|
2043
|
+
root = resolve_project_root(args.root).resolve()
|
|
2044
|
+
older_than = float(getattr(args, "older_than", 1800.0) or 0.0)
|
|
2045
|
+
scope = bugx_paths.require(root)
|
|
2046
|
+
candidates, failure = _abandoned_mcp_processes(
|
|
2047
|
+
root, scope.state_root, older_than=older_than,
|
|
2048
|
+
)
|
|
2049
|
+
if failure is not None:
|
|
2050
|
+
print(
|
|
2051
|
+
f"MCP 进程枚举失败,结果未知;拒绝声称为空或继续清理:{failure}",
|
|
2052
|
+
file=sys.stderr,
|
|
2053
|
+
)
|
|
2054
|
+
return 1
|
|
2055
|
+
if not candidates:
|
|
2056
|
+
print(f"无被遗弃的 MCP 会话进程(root={root}, older-than={older_than:.0f}s)")
|
|
2057
|
+
return 0
|
|
2058
|
+
print(f"检测到 {len(candidates)} 个可能遗弃的 MCP 会话(仅展示,不会裸 PID 终止):")
|
|
2059
|
+
for entry in candidates:
|
|
2060
|
+
age = float(entry["age_seconds"])
|
|
2061
|
+
activity = entry.get("activity_age_seconds")
|
|
2062
|
+
activity_note = "无活动记录" if activity is None else f"活动距今 {float(activity):.0f}s"
|
|
2063
|
+
print(
|
|
2064
|
+
f" PID {entry['pid']}(存活 {age:.0f}s,"
|
|
2065
|
+
f"{activity_note}):{entry['command']}"
|
|
2066
|
+
)
|
|
2067
|
+
if getattr(args, "yes", False):
|
|
2068
|
+
print(
|
|
2069
|
+
"拒绝 --yes:当前证据不含可验证的进程身份与协作式退出确认,"
|
|
2070
|
+
"不会仅凭 PID 发送信号。",
|
|
2071
|
+
file=sys.stderr,
|
|
2072
|
+
)
|
|
2073
|
+
return 2
|
|
2074
|
+
print("dry-run:只有获得稳定身份与协作式退出证据后才能执行清理。")
|
|
2075
|
+
return 0
|
|
2076
|
+
|
|
2077
|
+
|
|
2078
|
+
def command_mcp(args: argparse.Namespace) -> int:
|
|
2079
|
+
"""启动本地 stdio MCP;MCP 只协调 Supervisor,不执行 worker。"""
|
|
2080
|
+
root = resolve_project_root(args.root).resolve()
|
|
2081
|
+
forwarded = ["serve", "--root", str(root), "--role", args.role]
|
|
2082
|
+
if getattr(args, "takeover", False):
|
|
2083
|
+
forwarded.append("--takeover")
|
|
2084
|
+
return _run_script(root, "bugx_mcp_server.py", forwarded)
|
|
2085
|
+
|
|
2086
|
+
|
|
2087
|
+
def command_mcp_docs(args: argparse.Namespace) -> int:
|
|
2088
|
+
"""索引或启动本地项目文档 MCP,不访问第三方文档服务。"""
|
|
2089
|
+
root = resolve_project_root(args.root).resolve()
|
|
2090
|
+
forwarded = [args.mcp_docs_command, "--root", str(root), "--db", str(args.db)]
|
|
2091
|
+
if args.project_id:
|
|
2092
|
+
forwarded.extend(["--project-id", args.project_id])
|
|
2093
|
+
if args.version:
|
|
2094
|
+
forwarded.extend(["--version", args.version])
|
|
2095
|
+
if getattr(args, "no_auto_index", False):
|
|
2096
|
+
forwarded.append("--no-auto-index")
|
|
2097
|
+
return _run_script(
|
|
2098
|
+
root, "bugx_docs_mcp_server.py", forwarded,
|
|
2099
|
+
timeout=None if args.mcp_docs_command == "serve" else 300,
|
|
2100
|
+
)
|
|
2101
|
+
|
|
2102
|
+
|
|
2103
|
+
def command_mcp_schema(args: argparse.Namespace) -> int:
|
|
2104
|
+
"""输出 MCP 工具契约,不绑定项目,也不启动 Supervisor。"""
|
|
2105
|
+
_ensure_core_importable()
|
|
2106
|
+
# 单一导入路径(MCP 服务已归档到 ``core/skills/``)。
|
|
2107
|
+
from core.skills import bugx_mcp_server
|
|
2108
|
+
|
|
2109
|
+
print(json.dumps(
|
|
2110
|
+
{"server": bugx_mcp_server.SERVER_NAME,
|
|
2111
|
+
"version": bugx_mcp_server.SERVER_VERSION,
|
|
2112
|
+
"tools": bugx_mcp_server._tool_definitions(args.role)},
|
|
2113
|
+
ensure_ascii=False,
|
|
2114
|
+
separators=(",", ":"),
|
|
2115
|
+
))
|
|
2116
|
+
return 0
|
|
2117
|
+
|
|
2118
|
+
|
|
2119
|
+
def command_mcp_spy(args: argparse.Namespace) -> int:
|
|
2120
|
+
"""以透明管道代理底层 MCP 进程并录制双向 JSON-RPC wire 报文。"""
|
|
2121
|
+
raw_cmd = list(getattr(args, "spy_cmd", []))
|
|
2122
|
+
if raw_cmd and raw_cmd[0] == "--":
|
|
2123
|
+
raw_cmd = raw_cmd[1:]
|
|
2124
|
+
if not raw_cmd:
|
|
2125
|
+
print("[bugx mcp spy] 错误:必须指定被代理的目标命令,例如:bugx mcp spy -- bugx mcp serve", file=sys.stderr)
|
|
2126
|
+
return 1
|
|
2127
|
+
|
|
2128
|
+
root = resolve_project_root(args.root).resolve()
|
|
2129
|
+
log_file = args.log
|
|
2130
|
+
if log_file is None:
|
|
2131
|
+
log_dir = root / ".bugx" / "logs"
|
|
2132
|
+
log_dir.mkdir(parents=True, exist_ok=True)
|
|
2133
|
+
log_file = log_dir / "mcp-wire.log"
|
|
2134
|
+
else:
|
|
2135
|
+
log_file = Path(log_file).resolve()
|
|
2136
|
+
log_file.parent.mkdir(parents=True, exist_ok=True)
|
|
2137
|
+
|
|
2138
|
+
import datetime as dt
|
|
2139
|
+
import subprocess
|
|
2140
|
+
import threading
|
|
2141
|
+
|
|
2142
|
+
dump_stream = log_file.open("a", encoding="utf-8", buffering=1)
|
|
2143
|
+
lock = threading.Lock()
|
|
2144
|
+
|
|
2145
|
+
def record_wire(direction: str, data: str) -> None:
|
|
2146
|
+
now = dt.datetime.now(dt.timezone.utc).isoformat()
|
|
2147
|
+
with lock:
|
|
2148
|
+
dump_stream.write(f"[{now}] [{direction}] {data}\n")
|
|
2149
|
+
dump_stream.flush()
|
|
2150
|
+
|
|
2151
|
+
record_wire("META", f"SPY_START target={raw_cmd}")
|
|
2152
|
+
|
|
2153
|
+
proc = subprocess.Popen(
|
|
2154
|
+
raw_cmd,
|
|
2155
|
+
stdin=subprocess.PIPE,
|
|
2156
|
+
stdout=subprocess.PIPE,
|
|
2157
|
+
stderr=sys.stderr,
|
|
2158
|
+
bufsize=0,
|
|
2159
|
+
)
|
|
2160
|
+
|
|
2161
|
+
def forward_stdin() -> None:
|
|
2162
|
+
try:
|
|
2163
|
+
while True:
|
|
2164
|
+
line = sys.stdin.readline()
|
|
2165
|
+
if not line:
|
|
2166
|
+
break
|
|
2167
|
+
record_wire("IN ", line.rstrip("\r\n"))
|
|
2168
|
+
if proc.stdin is not None:
|
|
2169
|
+
proc.stdin.write(line.encode("utf-8"))
|
|
2170
|
+
proc.stdin.flush()
|
|
2171
|
+
except (BrokenPipeError, OSError):
|
|
2172
|
+
pass
|
|
2173
|
+
finally:
|
|
2174
|
+
if proc.stdin is not None:
|
|
2175
|
+
try:
|
|
2176
|
+
proc.stdin.close()
|
|
2177
|
+
except OSError:
|
|
2178
|
+
pass
|
|
2179
|
+
|
|
2180
|
+
def forward_stdout() -> None:
|
|
2181
|
+
try:
|
|
2182
|
+
assert proc.stdout is not None
|
|
2183
|
+
while True:
|
|
2184
|
+
line_bytes = proc.stdout.readline()
|
|
2185
|
+
if not line_bytes:
|
|
2186
|
+
break
|
|
2187
|
+
line_str = line_bytes.decode("utf-8", errors="replace")
|
|
2188
|
+
record_wire("OUT", line_str.rstrip("\r\n"))
|
|
2189
|
+
sys.stdout.write(line_str)
|
|
2190
|
+
sys.stdout.flush()
|
|
2191
|
+
except (BrokenPipeError, OSError):
|
|
2192
|
+
pass
|
|
2193
|
+
|
|
2194
|
+
t_in = threading.Thread(target=forward_stdin, name="mcp-spy-stdin", daemon=True)
|
|
2195
|
+
t_out = threading.Thread(target=forward_stdout, name="mcp-spy-stdout", daemon=True)
|
|
2196
|
+
t_in.start()
|
|
2197
|
+
t_out.start()
|
|
2198
|
+
|
|
2199
|
+
ret = proc.wait()
|
|
2200
|
+
t_out.join(timeout=1.0)
|
|
2201
|
+
record_wire("META", f"SPY_END exit_code={ret}")
|
|
2202
|
+
dump_stream.close()
|
|
2203
|
+
return ret
|
|
2204
|
+
|
|
2205
|
+
|
|
2206
|
+
|
|
2207
|
+
|
|
2208
|
+
def _run_mcp_runtime_captured(
|
|
2209
|
+
root: Path, script_args: list[str], *, before_output: Any = None,
|
|
2210
|
+
) -> int:
|
|
2211
|
+
"""Run the engine and reprint its stdout at the Python layer.
|
|
2212
|
+
|
|
2213
|
+
机器可读子命令(install/verify/rollback/start --print-command)必须让
|
|
2214
|
+
调用方可以可靠地捕获输出;真正的 ``start`` 执行仍走原始 stdio 直通。
|
|
2215
|
+
"""
|
|
2216
|
+
result = subprocess.run(
|
|
2217
|
+
[sys.executable, str(_script(root, "mcp_runtime.py")), *script_args],
|
|
2218
|
+
cwd=root, capture_output=True, text=True, check=False,
|
|
2219
|
+
env=_python_environment(), timeout=300,
|
|
2220
|
+
)
|
|
2221
|
+
if callable(before_output):
|
|
2222
|
+
before_output(result.returncode)
|
|
2223
|
+
if result.stdout:
|
|
2224
|
+
print(result.stdout if result.stdout.endswith("\n")
|
|
2225
|
+
else result.stdout + "\n", end="")
|
|
2226
|
+
if result.returncode != 0 and result.stderr:
|
|
2227
|
+
print(result.stderr.rstrip(), file=sys.stderr)
|
|
2228
|
+
return result.returncode
|
|
2229
|
+
|
|
2230
|
+
|
|
2231
|
+
def command_mcp_runtime(args: argparse.Namespace) -> int:
|
|
2232
|
+
"""管理 lock-hash 专用离线 MCP runtime(DOC-008 §12)。"""
|
|
2233
|
+
root = args.root.resolve()
|
|
2234
|
+
runtime_root = Path(args.runtime_root).expanduser() \
|
|
2235
|
+
if args.runtime_root else default_mcp_runtime_root()
|
|
2236
|
+
subcommand = args.mcp_runtime_command
|
|
2237
|
+
script_args: list[str]
|
|
2238
|
+
passthrough = False
|
|
2239
|
+
if subcommand == "install":
|
|
2240
|
+
lock_path = Path(args.lock).expanduser().resolve() \
|
|
2241
|
+
if args.lock else bundled_lock()
|
|
2242
|
+
script_args = [
|
|
2243
|
+
"install", "--lock", str(lock_path),
|
|
2244
|
+
"--runtime-root", str(runtime_root),
|
|
2245
|
+
"--bugx-version", __version__,
|
|
2246
|
+
]
|
|
2247
|
+
if args.json:
|
|
2248
|
+
script_args.append("--json")
|
|
2249
|
+
elif subcommand == "verify":
|
|
2250
|
+
script_args = ["verify", "--runtime-root", str(runtime_root)]
|
|
2251
|
+
if args.json:
|
|
2252
|
+
script_args.append("--json")
|
|
2253
|
+
elif subcommand == "start":
|
|
2254
|
+
script_args = [
|
|
2255
|
+
"start", "--server", args.server,
|
|
2256
|
+
"--runtime-root", str(runtime_root),
|
|
2257
|
+
]
|
|
2258
|
+
if args.print_command:
|
|
2259
|
+
script_args.append("--print-command")
|
|
2260
|
+
else:
|
|
2261
|
+
# 真正启动:引擎以 os.execve 换身 node,stdio 必须直通宿主。
|
|
2262
|
+
passthrough = True
|
|
2263
|
+
elif subcommand == "rollback":
|
|
2264
|
+
script_args = ["rollback", "--runtime-root", str(runtime_root)]
|
|
2265
|
+
if args.json:
|
|
2266
|
+
script_args.append("--json")
|
|
2267
|
+
else: # pragma: no cover - argparse restricts choices
|
|
2268
|
+
raise CliError(_i18n_exc("system.unknown_mcp_runtime_subcommand", f"未知的 mcp-runtime 子命令: {subcommand}", subcommand=subcommand))
|
|
2269
|
+
if passthrough:
|
|
2270
|
+
return _run_script(root, "mcp_runtime.py", script_args)
|
|
2271
|
+
from .agent import _CliProgress
|
|
2272
|
+
progress = _CliProgress(args)
|
|
2273
|
+
progress.update(0, f"准备 mcp-runtime {subcommand}")
|
|
2274
|
+
progress.update(20, f"正在执行 mcp-runtime {subcommand}")
|
|
2275
|
+
|
|
2276
|
+
def finish_progress(returncode: int) -> None:
|
|
2277
|
+
if returncode == 0:
|
|
2278
|
+
progress.finish(f"mcp-runtime {subcommand} 完成")
|
|
2279
|
+
else:
|
|
2280
|
+
progress.fail(f"mcp-runtime {subcommand} 失败")
|
|
2281
|
+
|
|
2282
|
+
try:
|
|
2283
|
+
return _run_mcp_runtime_captured(
|
|
2284
|
+
root, script_args, before_output=finish_progress,
|
|
2285
|
+
)
|
|
2286
|
+
except BaseException:
|
|
2287
|
+
progress.fail(f"mcp-runtime {subcommand} 失败")
|
|
2288
|
+
raise
|
|
2289
|
+
|
|
2290
|
+
|
|
2291
|
+
def _lock_server_flags(lock_path: Path) -> dict[str, tuple[bool, str]]:
|
|
2292
|
+
"""读取 lock 中各 server 的启用姿态与**停用理由**(缺省启用)。
|
|
2293
|
+
|
|
2294
|
+
``enabled: false`` 表示载荷已安装但**不会被启动**(供应链姿态,如 SPIKE-008-01)。
|
|
2295
|
+
计划输出必须如实区分"已装配"与"已安装但禁用",并给出 lock 中记录的理由,
|
|
2296
|
+
否则用户只看到"被禁用"却无从判断该补什么证明。
|
|
2297
|
+
"""
|
|
2298
|
+
try:
|
|
2299
|
+
data = json.loads(lock_path.read_text(encoding="utf-8"))
|
|
2300
|
+
except (OSError, ValueError):
|
|
2301
|
+
return {}
|
|
2302
|
+
flags: dict[str, tuple[bool, str]] = {}
|
|
2303
|
+
for name, meta in (data.get("servers") or {}).items():
|
|
2304
|
+
if isinstance(meta, dict):
|
|
2305
|
+
flags[str(name)] = (
|
|
2306
|
+
bool(meta.get("enabled", True)),
|
|
2307
|
+
str(meta.get("disabled_reason") or ""),
|
|
2308
|
+
)
|
|
2309
|
+
return flags
|
|
2310
|
+
|
|
2311
|
+
|
|
2312
|
+
def command_capability(args: argparse.Namespace) -> int:
|
|
2313
|
+
"""探查项目形态并装配能力(DOC-233/234)。
|
|
2314
|
+
|
|
2315
|
+
``plan`` 只读输出画像 → 技能包 → MCP/工具 的完整装配计划;
|
|
2316
|
+
``install`` 按计划装齐**所需 MCP 运行时**(lock-hash 校验 + 真实可执行自检),
|
|
2317
|
+
缺凭据的能力自动跳过并给出需要设置的环境变量。
|
|
2318
|
+
|
|
2319
|
+
缺失可选件(凭据/未安装)**绝不阻断**:退出码只在运行时安装/校验失败时非零。
|
|
2320
|
+
"""
|
|
2321
|
+
root = args.root.resolve() if args.root else Path.cwd().resolve()
|
|
2322
|
+
plan = _run_script_json(root, "capability_plan.py",
|
|
2323
|
+
["plan", "--root", str(root), "--json"])
|
|
2324
|
+
if plan is None:
|
|
2325
|
+
raise CliError(_i18n_exc(
|
|
2326
|
+
"system.capability_plan_failed",
|
|
2327
|
+
"无法生成能力计划(capability_plan.py 未返回结构化结果)",
|
|
2328
|
+
))
|
|
2329
|
+
|
|
2330
|
+
lock_path = Path(args.lock).expanduser().resolve() \
|
|
2331
|
+
if getattr(args, "lock", None) else bundled_lock()
|
|
2332
|
+
# 如实标注启用姿态:disabled 的 server 载荷会被安装但不会被启动。
|
|
2333
|
+
flags = _lock_server_flags(lock_path)
|
|
2334
|
+
for item in plan.get("mcp") or ():
|
|
2335
|
+
enabled, reason = flags.get(str(item.get("name")), (True, ""))
|
|
2336
|
+
item["enabled"] = enabled
|
|
2337
|
+
if reason:
|
|
2338
|
+
item["disabled_reason"] = reason
|
|
2339
|
+
|
|
2340
|
+
if args.capability_command == "plan":
|
|
2341
|
+
if args.json:
|
|
2342
|
+
print(json.dumps(plan, ensure_ascii=False, indent=2))
|
|
2343
|
+
return 0
|
|
2344
|
+
profile = plan.get("profile") or {}
|
|
2345
|
+
print("[capability] 项目形态: forms=%s surfaces=%s frameworks=%s"
|
|
2346
|
+
% (profile.get("forms"), profile.get("surfaces"),
|
|
2347
|
+
profile.get("frameworks")))
|
|
2348
|
+
print("[capability] 技能包: " + (", ".join(
|
|
2349
|
+
str(item.get("skill_id")) for item in plan.get("packs") or ()
|
|
2350
|
+
) or "无"))
|
|
2351
|
+
print("[capability] MCP: " + (", ".join(
|
|
2352
|
+
f"{item.get('name')}<-{item.get('source')}"
|
|
2353
|
+
+ (
|
|
2354
|
+
f"(lock 禁用:{item['disabled_reason']})"
|
|
2355
|
+
if not item.get("enabled", True) and item.get("disabled_reason")
|
|
2356
|
+
else ("" if item.get("enabled", True) else "(lock 禁用,不会启动)")
|
|
2357
|
+
)
|
|
2358
|
+
for item in plan.get("mcp") or ()
|
|
2359
|
+
) or "无"))
|
|
2360
|
+
for item in plan.get("skipped") or ():
|
|
2361
|
+
print(" ⏸ %s:缺少凭据,请设置 %s"
|
|
2362
|
+
% (item.get("name"), "、".join(item.get("env") or ()) or "(未声明)"))
|
|
2363
|
+
print("[capability] 工具: " + (", ".join(plan.get("tools") or ()) or "无"))
|
|
2364
|
+
for error in plan.get("errors") or ():
|
|
2365
|
+
print(f" ⚠ {error}")
|
|
2366
|
+
return 0
|
|
2367
|
+
|
|
2368
|
+
# ---- install ----
|
|
2369
|
+
installers = plan.get("installers") or {}
|
|
2370
|
+
assembled = {str(item.get("name")) for item in plan.get("mcp") or ()}
|
|
2371
|
+
# **禁用即不安装**:lock 里 enabled:false 的 server 永不启动,装载荷纯属浪费
|
|
2372
|
+
# (启用要改 lock ⇒ 换 hash ⇒ 照旧重装,缓存零收益),还会伪造"已装配"。
|
|
2373
|
+
# 是否要跑 install 由 **lock 的启用集**决定:runtime 是整 lock 制品,
|
|
2374
|
+
# 与本项目是否装配某个能力无关。
|
|
2375
|
+
enabled_lock = sorted(name for name, (flag, _r) in flags.items() if flag)
|
|
2376
|
+
disabled_lock = sorted(name for name, (flag, _r) in flags.items() if not flag)
|
|
2377
|
+
status: dict[str, Any] = {
|
|
2378
|
+
"installed": False, "verified": False, "enabled_servers": enabled_lock,
|
|
2379
|
+
}
|
|
2380
|
+
scope = {
|
|
2381
|
+
"lock_servers": sorted(flags),
|
|
2382
|
+
"assembled": sorted(assembled),
|
|
2383
|
+
"not_assembled": sorted(set(flags) - assembled),
|
|
2384
|
+
"installed_enabled": enabled_lock,
|
|
2385
|
+
"not_installed_disabled": disabled_lock,
|
|
2386
|
+
"selective_install_supported": False,
|
|
2387
|
+
}
|
|
2388
|
+
status["scope"] = scope
|
|
2389
|
+
if enabled_lock:
|
|
2390
|
+
runtime_root = Path(args.runtime_root).expanduser() \
|
|
2391
|
+
if getattr(args, "runtime_root", None) else default_mcp_runtime_root()
|
|
2392
|
+
install_code = _run_script(root, "mcp_runtime.py", [
|
|
2393
|
+
"install", "--lock", str(lock_path),
|
|
2394
|
+
"--runtime-root", str(runtime_root),
|
|
2395
|
+
"--bugx-version", __version__, "--json",
|
|
2396
|
+
])
|
|
2397
|
+
status["installed"] = install_code == 0
|
|
2398
|
+
verify_code = _run_script(root, "mcp_runtime.py", [
|
|
2399
|
+
"verify", "--runtime-root", str(runtime_root), "--json",
|
|
2400
|
+
])
|
|
2401
|
+
status["verified"] = verify_code == 0
|
|
2402
|
+
else:
|
|
2403
|
+
status["installed"] = status["verified"] = True
|
|
2404
|
+
|
|
2405
|
+
if args.json:
|
|
2406
|
+
print(json.dumps({**plan, "runtime": status}, ensure_ascii=False, indent=2))
|
|
2407
|
+
else:
|
|
2408
|
+
print("[capability] 已装配 %d 个 MCP(%d 个因缺凭据跳过)"
|
|
2409
|
+
% (len(plan.get("mcp") or ()), len(plan.get("skipped") or ())))
|
|
2410
|
+
print("[capability] 安装范围:整个 lock(%d 个 server;lock-hash 为整体制品,"
|
|
2411
|
+
"不支持只装子集)" % len(scope["lock_servers"]))
|
|
2412
|
+
print(" 安装(lock 启用,可启动):" + ("、".join(enabled_lock) or "无"))
|
|
2413
|
+
if disabled_lock:
|
|
2414
|
+
print(" 未安装(lock 禁用,永不启动):" + "、".join(disabled_lock))
|
|
2415
|
+
not_assembled = [n for n in scope["not_assembled"] if n not in disabled_lock]
|
|
2416
|
+
if not_assembled:
|
|
2417
|
+
print(" 本项目未装配(载荷已装,但不适用于当前形态):"
|
|
2418
|
+
+ "、".join(not_assembled))
|
|
2419
|
+
for item in plan.get("mcp") or ():
|
|
2420
|
+
name = str(item.get("name"))
|
|
2421
|
+
if name in disabled_lock:
|
|
2422
|
+
reason = str(item.get("disabled_reason") or "")
|
|
2423
|
+
print(" ⏸ %s:lock 禁用,**未安装**载荷%s"
|
|
2424
|
+
% (name, (";理由:" + reason) if reason else ""))
|
|
2425
|
+
elif name in enabled_lock:
|
|
2426
|
+
print(" ✓ %s(%s)" % (name, installers.get(name, "runtime")))
|
|
2427
|
+
if enabled_lock and not (status["installed"] and status["verified"]):
|
|
2428
|
+
print(" ✗ MCP 运行时安装或自检失败,请运行 bugx mcp-runtime verify 排查")
|
|
2429
|
+
print("[capability] 可用工具: " + (", ".join(plan.get("tools") or ()) or "无"))
|
|
2430
|
+
return 0 if (status["installed"] and status["verified"]) else 1
|
|
2431
|
+
|
|
2432
|
+
|
|
2433
|
+
def _parser_for_command_path(parser: argparse.ArgumentParser,
|
|
2434
|
+
command_path: list[str]) -> argparse.ArgumentParser:
|
|
2435
|
+
"""Return the argparse parser for a top-level or nested command path."""
|
|
2436
|
+
current = parser
|
|
2437
|
+
for command in command_path:
|
|
2438
|
+
subparsers = next(
|
|
2439
|
+
(action for action in current._actions
|
|
2440
|
+
if isinstance(action, argparse._SubParsersAction)),
|
|
2441
|
+
None,
|
|
2442
|
+
)
|
|
2443
|
+
if subparsers is None or command not in subparsers.choices:
|
|
2444
|
+
path = " ".join(command_path)
|
|
2445
|
+
raise CliError(_i18n_exc("system.unknown_help_topic", f"未知的帮助主题:{path}", path=path))
|
|
2446
|
+
current = subparsers.choices[command]
|
|
2447
|
+
return current
|
|
2448
|
+
|
|
2449
|
+
|
|
2450
|
+
def command_help(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int:
|
|
2451
|
+
"""Print root or command-specific help without entering command dispatch."""
|
|
2452
|
+
command_path = list(getattr(args, "help_command", []))
|
|
2453
|
+
try:
|
|
2454
|
+
target = _parser_for_command_path(parser, command_path)
|
|
2455
|
+
except CliError as exc:
|
|
2456
|
+
parser.error(str(exc))
|
|
2457
|
+
target.print_help()
|
|
2458
|
+
return 0
|
|
2459
|
+
|
|
2460
|
+
|
|
2461
|
+
def command_log(args: argparse.Namespace) -> int:
|
|
2462
|
+
"""bugx log:诊断日志分析、错误过滤、链路跟踪与耗时瀑布图。"""
|
|
2463
|
+
root = getattr(args, "root", Path.cwd()).resolve()
|
|
2464
|
+
try:
|
|
2465
|
+
_ensure_core_importable()
|
|
2466
|
+
from core.runtime import log_analytics
|
|
2467
|
+
return log_analytics.run_log_command(root, args)
|
|
2468
|
+
except Exception as exc:
|
|
2469
|
+
print(f"[bugx log] ✗ 日志分析执行失败: {exc}")
|
|
2470
|
+
return 1
|
|
2471
|
+
|
|
2472
|
+
|
|
2473
|
+
|
|
2474
|
+
|
|
2475
|
+
|
|
2476
|
+
def command_test_generate(args: argparse.Namespace) -> int:
|
|
2477
|
+
"""运行 core/repair/test_generator.py 自动生成测试脚手架或 PoC。"""
|
|
2478
|
+
root = getattr(args, "root", Path.cwd()).resolve()
|
|
2479
|
+
forwarded = [
|
|
2480
|
+
"--root", str(root),
|
|
2481
|
+
"--scope", str(args.scope),
|
|
2482
|
+
"--techniques", str(args.techniques),
|
|
2483
|
+
]
|
|
2484
|
+
if getattr(args, "out", None):
|
|
2485
|
+
forwarded.extend(["--out", str(args.out)])
|
|
2486
|
+
if getattr(args, "standalone", False):
|
|
2487
|
+
forwarded.append("--standalone")
|
|
2488
|
+
if getattr(args, "assert_expr", ""):
|
|
2489
|
+
forwarded.extend(["--assert-expr", str(args.assert_expr)])
|
|
2490
|
+
if getattr(args, "expected_exc", ""):
|
|
2491
|
+
forwarded.extend(["--expected-exc", str(args.expected_exc)])
|
|
2492
|
+
if getattr(args, "json", False):
|
|
2493
|
+
forwarded.append("--json")
|
|
2494
|
+
return _run_script(root, "test_generator.py", forwarded, timeout=120)
|
|
2495
|
+
|
|
2496
|
+
|
|
2497
|
+
def command_test_audit(args: argparse.Namespace) -> int:
|
|
2498
|
+
"""运行 core/repair/test_quality_auditor.py 对测试用例进行四维质量量化审计。"""
|
|
2499
|
+
root = getattr(args, "root", Path.cwd()).resolve()
|
|
2500
|
+
forwarded = [str(args.file)]
|
|
2501
|
+
if getattr(args, "scope", ""):
|
|
2502
|
+
forwarded.extend(["--scope", str(args.scope)])
|
|
2503
|
+
if getattr(args, "min_score", None) is not None:
|
|
2504
|
+
forwarded.extend(["--min-score", str(args.min_score)])
|
|
2505
|
+
if getattr(args, "strict", False):
|
|
2506
|
+
forwarded.append("--strict")
|
|
2507
|
+
if getattr(args, "json", False):
|
|
2508
|
+
forwarded.append("--json")
|
|
2509
|
+
return _run_script(root, "test_quality_auditor.py", forwarded, timeout=120)
|
|
2510
|
+
|
|
2511
|
+
|
|
2512
|
+
def command_mining_audit(args: argparse.Namespace) -> int:
|
|
2513
|
+
"""运行 core/mining_quality_framework.py 对挖掘方案进行四维质量量化审计与加固。"""
|
|
2514
|
+
root = getattr(args, "root", Path.cwd()).resolve()
|
|
2515
|
+
sub = getattr(args, "mining_subcommand", "audit")
|
|
2516
|
+
forwarded = [sub]
|
|
2517
|
+
if sub == "audit":
|
|
2518
|
+
forwarded.append(str(args.plan_file))
|
|
2519
|
+
forwarded.extend(["--root", str(root)])
|
|
2520
|
+
if getattr(args, "min_score", None) is not None:
|
|
2521
|
+
forwarded.extend(["--min-score", str(args.min_score)])
|
|
2522
|
+
if getattr(args, "strict", False):
|
|
2523
|
+
forwarded.append("--strict")
|
|
2524
|
+
if getattr(args, "allow_degraded", False):
|
|
2525
|
+
forwarded.append("--allow-degraded")
|
|
2526
|
+
if getattr(args, "json", False):
|
|
2527
|
+
forwarded.append("--json")
|
|
2528
|
+
elif sub == "explore":
|
|
2529
|
+
forwarded.extend(["--root", str(root)])
|
|
2530
|
+
if getattr(args, "language", None):
|
|
2531
|
+
forwarded.extend(["--language", str(args.language)])
|
|
2532
|
+
if getattr(args, "json", False):
|
|
2533
|
+
forwarded.append("--json")
|
|
2534
|
+
elif sub == "harden":
|
|
2535
|
+
forwarded.append(str(args.plan_file))
|
|
2536
|
+
forwarded.extend(["--root", str(root)])
|
|
2537
|
+
if getattr(args, "out", None):
|
|
2538
|
+
forwarded.extend(["--out", str(args.out)])
|
|
2539
|
+
return _run_script(root, "mining_quality_framework.py", forwarded, timeout=120)
|
|
2540
|
+
|
|
2541
|
+
|
|
2542
|
+
def command_test_verify(args: argparse.Namespace) -> int:
|
|
2543
|
+
"""运行 core/test_capability_verifier.py 对测试用例能力进行动态变异杀伤验证。"""
|
|
2544
|
+
root = getattr(args, "root", Path.cwd()).resolve()
|
|
2545
|
+
sub = getattr(args, "verify_subcommand", "verify")
|
|
2546
|
+
forwarded = [sub]
|
|
2547
|
+
if sub == "verify":
|
|
2548
|
+
forwarded.extend(["--target", str(args.target)])
|
|
2549
|
+
forwarded.extend(["--test", str(args.test)])
|
|
2550
|
+
if getattr(args, "max_mutants", None) is not None:
|
|
2551
|
+
forwarded.extend(["--max-mutants", str(args.max_mutants)])
|
|
2552
|
+
if getattr(args, "timeout", None) is not None:
|
|
2553
|
+
forwarded.extend(["--timeout", str(args.timeout)])
|
|
2554
|
+
if getattr(args, "strict", False):
|
|
2555
|
+
forwarded.append("--strict")
|
|
2556
|
+
if getattr(args, "json", False):
|
|
2557
|
+
forwarded.append("--json")
|
|
2558
|
+
elif sub == "mutate":
|
|
2559
|
+
forwarded.extend(["--target", str(args.target)])
|
|
2560
|
+
if getattr(args, "max_mutants", None) is not None:
|
|
2561
|
+
forwarded.extend(["--max-mutants", str(args.max_mutants)])
|
|
2562
|
+
if getattr(args, "json", False):
|
|
2563
|
+
forwarded.append("--json")
|
|
2564
|
+
return _run_script(root, "test_capability_verifier.py", forwarded, timeout=180)
|
|
2565
|
+
|
|
2566
|
+
|
|
2567
|
+
|