bugx-cli 0.0.0-stage → 0.1.1
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.
- package/LICENSE +55 -0
- package/README.md +284 -2
- package/core/CATALOG.json +141 -0
- package/core/README.md +254 -0
- package/core/adapters/README.md +35 -0
- package/core/adapters/android-interaction.json +81 -0
- package/core/adapters/android.json +24 -0
- package/core/adapters/desktop-macos.json +20 -0
- package/core/adapters/ios-interaction.json +34 -0
- package/core/adapters/ios.json +23 -0
- package/core/adapters/memory-macos.json +24 -0
- package/core/agent/README.md +51 -0
- package/core/agent/__init__.py +146 -0
- package/core/agent/agent_artifacts.py +766 -0
- package/core/agent/agent_eval.py +1155 -0
- package/core/agent/agent_execution.py +718 -0
- package/core/agent/agent_orchestrator.py +1351 -0
- package/core/agent/agent_targets.py +877 -0
- package/core/agent/agent_workspace.py +770 -0
- package/core/agent/feature_baseline.py +150 -0
- package/core/assets/README.md +24 -0
- package/core/assets/axe-core/LICENSE-3RD-PARTY.txt +66 -0
- package/core/assets/axe-core/LICENSE.txt +362 -0
- package/core/assets/axe-core/UPSTREAM.md +10 -0
- package/core/assets/axe-core/axe.min.js +12 -0
- package/core/assets/bugx-avatar-1024.png +0 -0
- package/core/assets/bugx-avatar-512.png +0 -0
- package/core/assets/bugx-avatar-tight.svg +23 -0
- package/core/assets/bugx-avatar.svg +28 -0
- package/core/assets/bugx-hero-cn.png +0 -0
- package/core/assets/bugx-hero-en.png +0 -0
- package/core/assets/bugx-hero-en.svg +74 -0
- package/core/assets/bugx-hero-zh.svg +74 -0
- package/core/assets/codex.png +0 -0
- package/core/assets/dsh.png +0 -0
- package/core/assets/project-layout.md +42 -0
- package/core/assets/webui-chatgpt.jpg +0 -0
- package/core/assets/webui-session.jpg +0 -0
- package/core/assets/webui-skills.jpg +0 -0
- package/core/assets/webui-studio.jpg +0 -0
- package/core/assets/webui-zcode.jpg +0 -0
- package/core/assets/zcode.png +0 -0
- package/core/audit_packs/README.md +37 -0
- package/core/audit_packs/data-audit/manifest.json +94 -0
- package/core/audit_packs/data-audit/stages/00-scope.md +14 -0
- package/core/audit_packs/data-audit/stages/10-schema-inventory.md +14 -0
- package/core/audit_packs/data-audit/stages/20-query-and-integrity.md +14 -0
- package/core/audit_packs/data-audit/stages/80-evidence-regression.md +14 -0
- package/core/audit_packs/desktop-audit/manifest.json +123 -0
- package/core/audit_packs/desktop-audit/stages/00-scope.md +15 -0
- package/core/audit_packs/desktop-audit/stages/10-process-model.md +14 -0
- package/core/audit_packs/desktop-audit/stages/20-package-integrity.md +15 -0
- package/core/audit_packs/desktop-audit/stages/30-ui-behavior.md +14 -0
- package/core/audit_packs/desktop-audit/stages/80-evidence-regression.md +15 -0
- package/core/audit_packs/memory-testing.md +227 -0
- package/core/audit_packs/mobile-audit/manifest.json +155 -0
- package/core/audit_packs/mobile-audit/modules/android.md +19 -0
- package/core/audit_packs/mobile-audit/modules/h5.md +18 -0
- package/core/audit_packs/mobile-audit/modules/ios.md +25 -0
- package/core/audit_packs/mobile-audit/modules/miniprogram.md +26 -0
- package/core/audit_packs/mobile-audit/modules/webview.md +18 -0
- package/core/audit_packs/mobile-audit/stages/00-scope.md +14 -0
- package/core/audit_packs/mobile-audit/stages/10-platform-inventory.md +14 -0
- package/core/audit_packs/mobile-audit/stages/20-masvs-static.md +20 -0
- package/core/audit_packs/mobile-audit/stages/30-component-exposure.md +14 -0
- package/core/audit_packs/mobile-audit/stages/40-device-behavior.md +14 -0
- package/core/audit_packs/mobile-audit/stages/80-evidence-regression.md +13 -0
- package/core/audit_packs/native-audit/manifest.json +127 -0
- package/core/audit_packs/native-audit/stages/00-scope.md +14 -0
- package/core/audit_packs/native-audit/stages/10-static-white-box.md +14 -0
- package/core/audit_packs/native-audit/stages/20-memory-concurrency.md +15 -0
- package/core/audit_packs/native-audit/stages/30-behavior-black-box.md +39 -0
- package/core/audit_packs/native-audit/stages/80-evidence-regression.md +14 -0
- package/core/audit_packs/platform-testing.md +174 -0
- package/core/audit_packs/web-audit/manifest.json +191 -0
- package/core/audit_packs/web-audit/modules/graphql.md +5 -0
- package/core/audit_packs/web-audit/modules/h5.md +18 -0
- package/core/audit_packs/web-audit/modules/multi-tenant.md +4 -0
- package/core/audit_packs/web-audit/modules/oauth.md +4 -0
- package/core/audit_packs/web-audit/modules/upload.md +4 -0
- package/core/audit_packs/web-audit/modules/websocket.md +4 -0
- package/core/audit_packs/web-audit/stages/00-scope.md +13 -0
- package/core/audit_packs/web-audit/stages/10-discovery.md +13 -0
- package/core/audit_packs/web-audit/stages/20-auth-session.md +13 -0
- package/core/audit_packs/web-audit/stages/30-authz-business.md +13 -0
- package/core/audit_packs/web-audit/stages/40-input-output.md +13 -0
- package/core/audit_packs/web-audit/stages/50-state-async.md +13 -0
- package/core/audit_packs/web-audit/stages/60-file-ssrf-deser.md +12 -0
- package/core/audit_packs/web-audit/stages/70-config-dependency.md +12 -0
- package/core/audit_packs/web-audit/stages/80-evidence-regression.md +12 -0
- package/core/autonomous_cve/INTERFACE.md +61 -0
- package/core/autonomous_cve/README.md +58 -0
- package/core/autonomous_cve/SPEC.md +25 -0
- package/core/autonomous_cve/__init__.py +109 -0
- package/core/autonomous_cve/attack_graph.py +1096 -0
- package/core/autonomous_cve/attack_graph_store.py +1868 -0
- package/core/autonomous_cve/audit_campaign.py +1232 -0
- package/core/autonomous_cve/behavior_graph.py +465 -0
- package/core/autonomous_cve/ghsa_advisories.py +174 -0
- package/core/autonomous_cve/models.py +93 -0
- package/core/autonomous_cve/mutator.py +87 -0
- package/core/autonomous_cve/patcher.py +126 -0
- package/core/autonomous_cve/scout.py +278 -0
- package/core/autonomous_cve/synthesizer.py +207 -0
- package/core/autonomous_cve/verifier.py +103 -0
- package/core/bugx.md +1299 -0
- package/core/bugx_paths.py +1881 -0
- package/core/cli-help.txt +66 -0
- package/core/cloud_sync/INTERFACE.md +32 -0
- package/core/cloud_sync/README.md +62 -0
- package/core/cloud_sync/SPEC.md +25 -0
- package/core/cloud_sync/__init__.py +23 -0
- package/core/cloud_sync/auto_sync.py +398 -0
- package/core/cloud_sync/cloud_client.py +1218 -0
- package/core/cloud_sync/cloud_onboard.py +743 -0
- package/core/cloud_sync/cloud_schema.py +648 -0
- package/core/cloud_sync/consent.py +81 -0
- package/core/cloud_sync/device_identity.py +307 -0
- package/core/cloud_sync/endpoint_router.py +415 -0
- package/core/cloud_sync/flywheel_client.py +769 -0
- package/core/cloud_sync/network_transport.py +296 -0
- package/core/cloud_sync/onboard_wizard.py +493 -0
- package/core/cloud_sync/sensitive_filter.py +285 -0
- package/core/cloud_sync/sync_pull.py +695 -0
- package/core/cloud_sync/sync_push.py +723 -0
- package/core/contracts/AGENT_GUIDE.md +359 -0
- package/core/contracts/README.md +34 -0
- package/core/contracts/bugx-blackbox.md +541 -0
- package/core/contracts/bugx-opencode.md +469 -0
- package/core/contracts/bugx-quick.md +44 -0
- package/core/contracts/bugx-runtime-contract.md +353 -0
- package/core/contracts/bugx-worker.md +470 -0
- package/core/contracts/engine_gap_contracts.py +473 -0
- package/core/coverage/README.md +70 -0
- package/core/coverage/__init__.py +106 -0
- package/core/coverage/coverage_ai_review.py +185 -0
- package/core/coverage/coverage_backfill.py +54 -0
- package/core/coverage/coverage_bootstrap.py +713 -0
- package/core/coverage/coverage_business.py +36 -0
- package/core/coverage/coverage_cli.py +715 -0
- package/core/coverage/coverage_discovery.py +1429 -0
- package/core/coverage/coverage_evidence.py +1024 -0
- package/core/coverage/coverage_forensics.py +124 -0
- package/core/coverage/coverage_gate.py +277 -0
- package/core/coverage/coverage_intelligence.py +734 -0
- package/core/coverage/coverage_manifest.py +396 -0
- package/core/coverage/coverage_platform.py +77 -0
- package/core/coverage/coverage_validate.py +241 -0
- package/core/coverage/module_coverage.py +157 -0
- package/core/dev_harness/INTERFACE.md +20 -0
- package/core/dev_harness/README.md +21 -0
- package/core/dev_harness/SPEC.md +25 -0
- package/core/dev_harness/__init__.py +5 -0
- package/core/dev_harness/interaction_preset.py +408 -0
- package/core/engine-integrity.json +2797 -0
- package/core/fuzzing/README.md +49 -0
- package/core/fuzzing/__init__.py +82 -0
- package/core/fuzzing/concurrency_fuzzer.py +435 -0
- package/core/fuzzing/differential_oracle.py +1164 -0
- package/core/fuzzing/fuzz_input.py +1291 -0
- package/core/fuzzing/stateful_fuzzer.py +404 -0
- package/core/governance/README.md +61 -0
- package/core/governance/__init__.py +130 -0
- package/core/governance/capacity_planner.py +124 -0
- package/core/governance/dependency_lock.py +317 -0
- package/core/governance/goal_governor.py +754 -0
- package/core/governance/guide_budget.py +458 -0
- package/core/governance/lockdown.sh +50 -0
- package/core/governance/readonly_enforcer.py +154 -0
- package/core/governance/runtime_tool_gate.py +373 -0
- package/core/governance/secret_redactor.py +784 -0
- package/core/governance/token_budget.py +38 -0
- package/core/host_acp/INTERFACE.md +36 -0
- package/core/host_acp/README.md +51 -0
- package/core/host_acp/SPEC.md +25 -0
- package/core/host_acp/__init__.py +121 -0
- package/core/host_acp/base.py +111 -0
- package/core/host_acp/claude.py +99 -0
- package/core/host_acp/cline.py +298 -0
- package/core/host_acp/codex.py +300 -0
- package/core/host_acp/dsh.py +106 -0
- package/core/host_acp/opencode.py +209 -0
- package/core/host_acp/pi.py +94 -0
- package/core/host_acp/zcode.py +99 -0
- package/core/host_runtime/INTERFACE.md +24 -0
- package/core/host_runtime/README.md +62 -0
- package/core/host_runtime/SPEC.md +25 -0
- package/core/host_runtime/__init__.py +21 -0
- package/core/host_runtime/adapters.py +412 -0
- package/core/host_runtime/autonomous_runner.py +1152 -0
- package/core/host_runtime/cline.py +448 -0
- package/core/host_runtime/common.py +103 -0
- package/core/host_runtime/free_models.py +786 -0
- package/core/host_runtime/host_bootstrap.py +389 -0
- package/core/host_runtime/host_evaluators.py +761 -0
- package/core/host_runtime/host_probe.py +41 -0
- package/core/host_runtime/host_provider_arbitrator.py +831 -0
- package/core/host_runtime/host_registry.py +662 -0
- package/core/host_runtime/host_usage.py +127 -0
- package/core/host_runtime/mcp_process_tracker.py +509 -0
- package/core/host_runtime/mcp_registry_gate.py +379 -0
- package/core/host_runtime/pi.py +102 -0
- package/core/host_runtime/provider_facts.py +66 -0
- package/core/hosts/INTERFACE.md +51 -0
- package/core/hosts/README.md +67 -0
- package/core/hosts/SPEC.md +25 -0
- package/core/hosts/__init__.py +140 -0
- package/core/hosts/_base_usage.py +152 -0
- package/core/hosts/_codex_usage.py +297 -0
- package/core/hosts/_dsh_usage.py +184 -0
- package/core/hosts/_mcp_toml.py +365 -0
- package/core/hosts/_zcode_usage.py +269 -0
- package/core/hosts/base.py +479 -0
- package/core/hosts/claude.py +212 -0
- package/core/hosts/cline.py +229 -0
- package/core/hosts/codex.py +1006 -0
- package/core/hosts/dsh.py +526 -0
- package/core/hosts/opencode.py +358 -0
- package/core/hosts/pi.py +308 -0
- package/core/hosts/zcode.py +219 -0
- package/core/i18n.py +252 -0
- package/core/infra/README.md +41 -0
- package/core/infra/__init__.py +17 -0
- package/core/infra/build_info.py +105 -0
- package/core/infra/client_metadata.py +185 -0
- package/core/infra/json_utils.py +22 -0
- package/core/infra/python_runtime.py +540 -0
- package/core/infra/safe_xml.py +221 -0
- package/core/launch_bugx.py +118 -0
- package/core/launch_phases/INTERFACE.md +31 -0
- package/core/launch_phases/README.md +106 -0
- package/core/launch_phases/SPEC.md +25 -0
- package/core/launch_phases/__init__.py +29 -0
- package/core/launch_phases/candidate_revalidation.py +484 -0
- package/core/launch_phases/common.py +1060 -0
- package/core/launch_phases/finding_confirm_phase.py +391 -0
- package/core/launch_phases/finding_settlement.py +1432 -0
- package/core/launch_phases/findings_adjudication.py +666 -0
- package/core/launch_phases/findings_snapshot.py +357 -0
- package/core/launch_phases/judge_phase.py +848 -0
- package/core/launch_phases/lesson_context.py +536 -0
- package/core/launch_phases/lifecycle_reporter.py +627 -0
- package/core/launch_phases/orchestrator_controls.py +686 -0
- package/core/launch_phases/post_commit.py +567 -0
- package/core/launch_phases/post_coverage_sync.py +598 -0
- package/core/launch_phases/post_dry_run.py +817 -0
- package/core/launch_phases/post_observability.py +367 -0
- package/core/launch_phases/post_phase.py +1223 -0
- package/core/launch_phases/post_receipt.py +373 -0
- package/core/launch_phases/post_round_lifecycle.py +786 -0
- package/core/launch_phases/pre_phase.py +1029 -0
- package/core/launch_phases/pre_recon_scout.py +879 -0
- package/core/launch_phases/pre_state_builder.py +1133 -0
- package/core/launch_phases/report_sharing.py +414 -0
- package/core/launch_phases/round_orchestrator.py +1116 -0
- package/core/launch_phases/session_runtime.py +1670 -0
- package/core/launch_phases/startup_gates.py +1050 -0
- package/core/launch_phases/startup_interaction.py +1003 -0
- package/core/launch_phases/startup_version_gate.py +879 -0
- package/core/launch_phases/supervisor_bridge.py +1253 -0
- package/core/launch_phases/supervisor_coverage.py +423 -0
- package/core/launch_phases/supervisor_degraded.py +1211 -0
- package/core/launch_phases/worker_barriers.py +424 -0
- package/core/launch_phases/worker_orchestrator.py +1246 -0
- package/core/launch_phases/worker_prior.py +749 -0
- package/core/ledger/INTERFACE.md +35 -0
- package/core/ledger/README.md +160 -0
- package/core/ledger/SPEC.md +25 -0
- package/core/ledger/__init__.py +67 -0
- package/core/ledger/_facade.py +227 -0
- package/core/ledger/archive_ops.py +630 -0
- package/core/ledger/auto_materialization.py +459 -0
- package/core/ledger/bug-log.md +22 -0
- package/core/ledger/cli.py +275 -0
- package/core/ledger/export_ops.py +554 -0
- package/core/ledger/finding_confirmation.py +1316 -0
- package/core/ledger/finding_io.py +299 -0
- package/core/ledger/finding_lifecycle.py +730 -0
- package/core/ledger/finding_verification.py +405 -0
- package/core/ledger/incidents.py +1005 -0
- package/core/ledger/lesson-replay-cases.json +20 -0
- package/core/ledger/lesson_ledger.py +241 -0
- package/core/ledger/lesson_replay.py +272 -0
- package/core/ledger/life_ledger.py +668 -0
- package/core/ledger/mistake-book.md +130 -0
- package/core/ledger/patterns.py +684 -0
- package/core/ledger/receipt_contract.py +269 -0
- package/core/ledger/schema.py +1192 -0
- package/core/ledger/sync_ops.py +940 -0
- package/core/ledger/tool_experience.py +683 -0
- package/core/ledger/verify_life.py +1597 -0
- package/core/lesson-ledger.json +275 -0
- package/core/locales/README.md +19 -0
- package/core/locales/en-US.json +462 -0
- package/core/locales/zh-CN.json +462 -0
- package/core/mcp_handlers/INTERFACE.md +75 -0
- package/core/mcp_handlers/README.md +62 -0
- package/core/mcp_handlers/SPEC.md +25 -0
- package/core/mcp_handlers/__init__.py +128 -0
- package/core/mcp_handlers/base.py +717 -0
- package/core/mcp_handlers/channel_lifecycle.py +751 -0
- package/core/mcp_handlers/graph_handlers.py +222 -0
- package/core/mcp_handlers/knowledge_handlers.py +536 -0
- package/core/mcp_handlers/mining_handlers.py +586 -0
- package/core/mcp_handlers/resource_prompt_table.py +116 -0
- package/core/mcp_handlers/retrieval_handlers.py +249 -0
- package/core/mcp_handlers/rpc_server.py +470 -0
- package/core/mcp_handlers/supervisor_handlers.py +1461 -0
- package/core/mcp_handlers/telemetry_handlers.py +227 -0
- package/core/mcp_handlers/tool_table.py +1030 -0
- package/core/mcp_runtime_support/README.md +21 -0
- package/core/mcp_runtime_support/__init__.py +1 -0
- package/core/mcp_runtime_support/common.py +363 -0
- package/core/mcp_runtime_support/environment.py +567 -0
- package/core/mcp_runtime_support/verifier.py +758 -0
- package/core/metadata.txt +4 -0
- package/core/planning/README.md +157 -0
- package/core/planning/__init__.py +242 -0
- package/core/planning/capability_plan.py +187 -0
- package/core/planning/capability_planner.py +195 -0
- package/core/planning/domain_archetype.py +542 -0
- package/core/planning/domain_router.py +269 -0
- package/core/planning/dynamic_flow_analyzer.py +533 -0
- package/core/planning/impact_pruner.py +435 -0
- package/core/planning/intent_adjudicator.py +175 -0
- package/core/planning/judge_pipeline.py +1246 -0
- package/core/planning/logic_analysis.py +419 -0
- package/core/planning/prompt_harness.py +1704 -0
- package/core/planning/source_inspector.py +267 -0
- package/core/planning/spec_harvester.py +449 -0
- package/core/planning/target_sandbox_manager.py +573 -0
- package/core/planning/test_capability_verifier.py +1364 -0
- package/core/planning/tools-kb.md +38 -0
- package/core/planning/unit_kind.py +122 -0
- package/core/probes/INTERFACE.md +83 -0
- package/core/probes/README.md +51 -0
- package/core/probes/SPEC.md +36 -0
- package/core/probes/__init__.py +76 -0
- package/core/probes/android_probe.py +552 -0
- package/core/probes/base.py +147 -0
- package/core/probes/codebase_memory_probe.py +647 -0
- package/core/probes/desktop_probe.py +342 -0
- package/core/probes/differential_probe.py +434 -0
- package/core/probes/efficiency_probe.py +232 -0
- package/core/probes/ios_binary_probe.py +472 -0
- package/core/probes/memory_probe.py +392 -0
- package/core/probes/miniprogram_probe.py +385 -0
- package/core/probes/mobile_probe.py +466 -0
- package/core/probes/native_probe.py +302 -0
- package/core/probes/openwiki_probe.py +263 -0
- package/core/probes/pattern_probe.py +453 -0
- package/core/probes/platform_probe.py +424 -0
- package/core/probes/probe_registry.py +1770 -0
- package/core/probes/sast_fixture_corpus.py +340 -0
- package/core/probes/sast_probe.py +1510 -0
- package/core/probes/sast_rules.py +1481 -0
- package/core/probes/sca_scanner.py +779 -0
- package/core/probes/ui_accessibility.py +149 -0
- package/core/probes/ui_audit.py +513 -0
- package/core/probes/ui_contract.py +273 -0
- package/core/probes/ui_evidence.py +212 -0
- package/core/probes/ui_measurements.py +314 -0
- package/core/probes/ui_repair.py +250 -0
- package/core/probes/ui_review.py +133 -0
- package/core/probes/ui_storybook.py +107 -0
- package/core/probes/ui_tokens.py +185 -0
- package/core/probes/ui_visual_diff.py +131 -0
- package/core/probes/web_probe.py +714 -0
- package/core/project_profiler/INTERFACE.md +62 -0
- package/core/project_profiler/README.md +53 -0
- package/core/project_profiler/SPEC.md +28 -0
- package/core/project_profiler/__init__.py +201 -0
- package/core/project_profiler/arbitrator.py +316 -0
- package/core/project_profiler/constants.py +247 -0
- package/core/project_profiler/detector.py +399 -0
- package/core/project_profiler/extractors.py +836 -0
- package/core/project_profiler/fingerprint.py +116 -0
- package/core/project_profiler/storage.py +258 -0
- package/core/project_profiler/strategy.py +301 -0
- package/core/prompts/README.md +35 -0
- package/core/prompts/codex_dialog_dispatch.md +9 -0
- package/core/prompts/command_routing_en.md +42 -0
- package/core/prompts/command_routing_zh.md +42 -0
- package/core/prompts/l0_router.md +47 -0
- package/core/prompts/rules/anti_patterns.md +16 -0
- package/core/prompts/rules/concurrency_rules.md +14 -0
- package/core/prompts/rules/memory_leak_rules.md +13 -0
- package/core/prompts/rules/prompt_injection_defense.md +13 -0
- package/core/prompts/stages/stage_explore.md +31 -0
- package/core/prompts/stages/stage_gate.md +43 -0
- package/core/prompts/stages/stage_mutate.md +42 -0
- package/core/prompts/stages/stage_repair.md +85 -0
- package/core/repair/README.md +74 -0
- package/core/repair/__init__.py +169 -0
- package/core/repair/fix_watchlist.py +391 -0
- package/core/repair/l7_dynamic.py +418 -0
- package/core/repair/l7_repair_loop.py +462 -0
- package/core/repair/l7_selfcheck.py +862 -0
- package/core/repair/minimize_repro.py +466 -0
- package/core/repair/patch_synthesizer.py +617 -0
- package/core/repair/regression_pack.py +379 -0
- package/core/repair/rsi_fixer.py +910 -0
- package/core/repair/rsi_loop.py +311 -0
- package/core/repair/rsi_repair.py +348 -0
- package/core/repair/rsi_rounds.py +212 -0
- package/core/repair/rsi_scope.py +281 -0
- package/core/repair/self_heal.py +604 -0
- package/core/repair/test_generator.py +1108 -0
- package/core/repair/test_quality_auditor.py +410 -0
- package/core/repair/test_strategy.py +511 -0
- package/core/report_engine/INTERFACE.md +59 -0
- package/core/report_engine/README.md +69 -0
- package/core/report_engine/SPEC.md +28 -0
- package/core/report_engine/__init__.py +47 -0
- package/core/report_engine/attestation.py +228 -0
- package/core/report_engine/authority.py +255 -0
- package/core/report_engine/finding_report.py +418 -0
- package/core/report_engine/formal_report_builder.py +924 -0
- package/core/report_engine/html_renderers.py +696 -0
- package/core/report_engine/models.py +759 -0
- package/core/report_engine/pdf_exporter.py +231 -0
- package/core/report_engine/projects_assets.py +730 -0
- package/core/report_engine/report_client.py +743 -0
- package/core/report_engine/report_data_builder.py +388 -0
- package/core/report_engine/report_share.py +459 -0
- package/core/report_engine/sast_bridge.py +116 -0
- package/core/report_engine/server.py +832 -0
- package/core/report_engine/visual_report_builder.py +796 -0
- package/core/report_engine/web-conformance.md +168 -0
- package/core/report_engine/web_conformance.py +428 -0
- package/core/report_engine/workbench_assets.py +484 -0
- package/core/retrieval/INTERFACE.md +20 -0
- package/core/retrieval/README.md +161 -0
- package/core/retrieval/SPEC.md +25 -0
- package/core/retrieval/__init__.py +3 -0
- package/core/retrieval/code_analyzer.py +1720 -0
- package/core/retrieval/codebase_memory_bridge.py +337 -0
- package/core/retrieval/context_assembler.py +240 -0
- package/core/retrieval/corpus_fetch.py +369 -0
- package/core/retrieval/graph_ego.py +597 -0
- package/core/retrieval/knowledge_auto.py +662 -0
- package/core/retrieval/knowledge_sources.py +168 -0
- package/core/retrieval/knowledge_sync.py +1003 -0
- package/core/retrieval/memory_store.py +480 -0
- package/core/retrieval/query_planner.py +1020 -0
- package/core/retrieval/rrf_engine.py +137 -0
- package/core/retrieval/slice_extractor.py +1209 -0
- package/core/retrieval/slice_normalizer.py +373 -0
- package/core/retrieval/slice_spec.py +357 -0
- package/core/retrieval/symbol_index.py +1151 -0
- package/core/retrieval/universal_code_matcher.py +622 -0
- package/core/retrieval/xerj_bridge.py +476 -0
- package/core/retrieval/xerj_supervisor.py +362 -0
- package/core/rules/README.md +33 -0
- package/core/rules/ios/PROVENANCE.json +30 -0
- package/core/rules/ios/crypto.yaml +36 -0
- package/core/rules/ios/network.yaml +20 -0
- package/core/rules/ios/resilience.yaml +47 -0
- package/core/rules/ios/storage.yaml +48 -0
- package/core/rules/mastg/LICENSE +173 -0
- package/core/rules/mastg/PROVENANCE.json +270 -0
- package/core/rules/mastg/mastg-android-asymmetric-key-pair-used-for-multiple-purposes.yml +13 -0
- package/core/rules/mastg/mastg-android-backup-manifest.yml +24 -0
- package/core/rules/mastg/mastg-android-biometric-event-bound.yml +49 -0
- package/core/rules/mastg/mastg-android-biometric-invalidated-enrollment.yml +11 -0
- package/core/rules/mastg/mastg-android-biometric-no-confirmation-required.yml +10 -0
- package/core/rules/mastg/mastg-android-biometric-validity-duration.yml +24 -0
- package/core/rules/mastg/mastg-android-broken-encryption-algorithms.yaml +9 -0
- package/core/rules/mastg/mastg-android-broken-encryption-modes.yaml +13 -0
- package/core/rules/mastg/mastg-android-content-provider-exported.yml +35 -0
- package/core/rules/mastg/mastg-android-custom-deeplink-scheme.yml +29 -0
- package/core/rules/mastg/mastg-android-dangerous-app-permissions.yaml +65 -0
- package/core/rules/mastg/mastg-android-data-unencrypted-shared-storage-no-user-interaction-apis.yml +36 -0
- package/core/rules/mastg/mastg-android-data-unencrypted-shared-storage-no-user-interaction-manifest.yml +15 -0
- package/core/rules/mastg/mastg-android-debuggable-flag.yml +10 -0
- package/core/rules/mastg/mastg-android-debugger-checks.yml +12 -0
- package/core/rules/mastg/mastg-android-deeplink-autoverify-missing.yml +33 -0
- package/core/rules/mastg/mastg-android-deeplink-unvalidated-parameter.yml +11 -0
- package/core/rules/mastg/mastg-android-device-passcode-present.yml +17 -0
- package/core/rules/mastg/mastg-android-fileprovider-broad-scope.yml +46 -0
- package/core/rules/mastg/mastg-android-hardcoded-crypto-keys-usage.yml +14 -0
- package/core/rules/mastg/mastg-android-hardcoded-security-provider.yaml +18 -0
- package/core/rules/mastg/mastg-android-implicit-intent-internal-communication.yml +30 -0
- package/core/rules/mastg/mastg-android-implicit-intent-leaking-extras.yml +29 -0
- package/core/rules/mastg/mastg-android-input-field-usage.yml +11 -0
- package/core/rules/mastg/mastg-android-key-generation-with-insufficient-key-length.yml +21 -0
- package/core/rules/mastg/mastg-android-keyboard-cache-input-types.yml +10 -0
- package/core/rules/mastg/mastg-android-local-storage-input-validation.yml +48 -0
- package/core/rules/mastg/mastg-android-native-debugger-checks.yml +12 -0
- package/core/rules/mastg/mastg-android-network-checkservertrusted.yml +12 -0
- package/core/rules/mastg/mastg-android-network-hostname-verification.yml +11 -0
- package/core/rules/mastg/mastg-android-network-insecure-trust-anchors.yml +11 -0
- package/core/rules/mastg/mastg-android-network-onreceivedsslerror.yml +12 -0
- package/core/rules/mastg/mastg-android-non-random-use.yml +16 -0
- package/core/rules/mastg/mastg-android-object-deserialization.yml +14 -0
- package/core/rules/mastg/mastg-android-overlay-protection.yml +68 -0
- package/core/rules/mastg/mastg-android-pendingintent-mutable.yml +39 -0
- package/core/rules/mastg/mastg-android-random-apis-insufficient-entropy.yml +17 -0
- package/core/rules/mastg/mastg-android-root-detection.yaml +59 -0
- package/core/rules/mastg/mastg-android-sdk-version.yml +10 -0
- package/core/rules/mastg/mastg-android-sensitive-data-in-notifications-manifest.yml +17 -0
- package/core/rules/mastg/mastg-android-sensitive-data-in-notifications.yml +11 -0
- package/core/rules/mastg/mastg-android-sensitive-data-in-screenshot.yml +18 -0
- package/core/rules/mastg/mastg-android-sql-injection-contentprovider.yml +17 -0
- package/core/rules/mastg/mastg-android-ssl-socket-hostnameverifier.yml +15 -0
- package/core/rules/mastg/mastg-android-strictmode.yml +10 -0
- package/core/rules/mastg/mastg-android-system-alert-window.yml +9 -0
- package/core/rules/mastg/mastg-android-webview-allow-local-access.yml +15 -0
- package/core/rules/mastg/mastg-android-webview-bridges.yml +28 -0
- package/core/rules/mastg/mastg-android-webview-safebrowsing.yml +20 -0
- package/core/rules/mastg/mastg-android-webview-url-handlers.yml +41 -0
- package/core/rules/miniprogram/PROVENANCE.json +26 -0
- package/core/rules/miniprogram/network.yaml +37 -0
- package/core/rules/miniprogram/platform.yaml +36 -0
- package/core/rules/miniprogram/storage.yaml +48 -0
- package/core/rules/mobsfscan-swift/LICENSE +165 -0
- package/core/rules/mobsfscan-swift/PROVENANCE.json +58 -0
- package/core/rules/mobsfscan-swift/auth.yaml +59 -0
- package/core/rules/mobsfscan-swift/crypto.yaml +66 -0
- package/core/rules/mobsfscan-swift/jailbreak.yaml +14 -0
- package/core/rules/mobsfscan-swift/keyboard.yaml +34 -0
- package/core/rules/mobsfscan-swift/logging.yaml +23 -0
- package/core/rules/mobsfscan-swift/network.yaml +55 -0
- package/core/rules/mobsfscan-swift/resilience.yaml +29 -0
- package/core/rules/mobsfscan-swift/secrets.yaml +33 -0
- package/core/rules/mobsfscan-swift/storage.yaml +29 -0
- package/core/rules/mobsfscan-swift/webview.yaml +32 -0
- package/core/runtime/README.md +198 -0
- package/core/runtime/__init__.py +3 -0
- package/core/runtime/bugx_logging.py +1464 -0
- package/core/runtime/daemon_runner.py +623 -0
- package/core/runtime/fixture_solidify.py +444 -0
- package/core/runtime/global_telemetry.py +549 -0
- package/core/runtime/incident_eval.py +148 -0
- package/core/runtime/interaction.py +605 -0
- package/core/runtime/interaction_store.py +435 -0
- package/core/runtime/interactive_menu.py +95 -0
- package/core/runtime/log_analytics.py +922 -0
- package/core/runtime/mining_quality_framework.py +1387 -0
- package/core/runtime/model_runner.py +732 -0
- package/core/runtime/platform_adapter.py +579 -0
- package/core/runtime/prep_validate.py +478 -0
- package/core/runtime/project_graph.py +827 -0
- package/core/runtime/project_init.py +481 -0
- package/core/runtime/project_profile.py +224 -0
- package/core/runtime/project_settings.py +964 -0
- package/core/runtime/provider_window.py +97 -0
- package/core/runtime/resume_ticket.py +115 -0
- package/core/runtime/scenario_eval.py +856 -0
- package/core/runtime/seed_drill.py +549 -0
- package/core/runtime/self_audit.py +550 -0
- package/core/runtime/session_profile.py +205 -0
- package/core/runtime/setup_ui_env.py +229 -0
- package/core/runtime/startup_environment.py +859 -0
- package/core/runtime/sync_store.py +1421 -0
- package/core/runtime/tool_install_targets.py +18 -0
- package/core/schemas/README.md +35 -0
- package/core/schemas/agent-graph.schema.json +368 -0
- package/core/schemas/attack-graph.schema.json +88 -0
- package/core/schemas/evidence-bundle.schema.json +33 -0
- package/core/schemas/skill-pack.schema.json +230 -0
- package/core/schemas/worker-checkpoint.schema.json +119 -0
- package/core/secure_atomic.py +289 -0
- package/core/seed_corpus/README.md +55 -0
- package/core/seed_corpus/c.txt +29 -0
- package/core/seed_corpus/cpp.txt +32 -0
- package/core/seed_corpus/css.txt +70 -0
- package/core/seed_corpus/go.txt +46 -0
- package/core/seed_corpus/java.txt +30 -0
- package/core/seed_corpus/javascript.txt +55 -0
- package/core/seed_corpus/kotlin.txt +28 -0
- package/core/seed_corpus/python.txt +71 -0
- package/core/seed_corpus/rust.txt +53 -0
- package/core/seed_corpus/swift.txt +29 -0
- package/core/seed_corpus/typescript.txt +29 -0
- package/core/skills/README.md +53 -0
- package/core/skills/__init__.py +189 -0
- package/core/skills/bugx_docs_mcp_server.py +418 -0
- package/core/skills/bugx_mcp_server.py +1161 -0
- package/core/skills/mcp_runtime.py +968 -0
- package/core/skills/mcp_session_proof.py +605 -0
- package/core/skills/mobile_ui_inspector.py +405 -0
- package/core/skills/skill_pack.py +1214 -0
- package/core/skills/skill_synthesizer.py +1153 -0
- package/core/skills/tools_kb.py +313 -0
- package/core/supervisor/INTERFACE.md +121 -0
- package/core/supervisor/README.md +209 -0
- package/core/supervisor/SPEC.md +25 -0
- package/core/supervisor/__init__.py +175 -0
- package/core/supervisor/audit_supervisor.py +1015 -0
- package/core/supervisor/budget_governor.py +1254 -0
- package/core/supervisor/checkpoint_handler.py +368 -0
- package/core/supervisor/checkpoint_pipeline.py +1564 -0
- package/core/supervisor/checkpoint_sync.py +653 -0
- package/core/supervisor/claim_events.py +74 -0
- package/core/supervisor/claim_sync.py +590 -0
- package/core/supervisor/cli.py +812 -0
- package/core/supervisor/context_sync.py +55 -0
- package/core/supervisor/coverage_sync.py +115 -0
- package/core/supervisor/finding_commit.py +470 -0
- package/core/supervisor/finding_sync.py +688 -0
- package/core/supervisor/finding_workflow.py +676 -0
- package/core/supervisor/finish_policy.py +224 -0
- package/core/supervisor/finish_sync.py +185 -0
- package/core/supervisor/graph_sync.py +669 -0
- package/core/supervisor/lease_manager.py +788 -0
- package/core/supervisor/lifecycle_blocks.py +129 -0
- package/core/supervisor/next_round_sync.py +126 -0
- package/core/supervisor/observability.py +140 -0
- package/core/supervisor/recovery_sync.py +165 -0
- package/core/supervisor/rejection_remedies.py +355 -0
- package/core/supervisor/round_governor.py +306 -0
- package/core/supervisor/serial_authorization.py +544 -0
- package/core/supervisor/start_sync.py +87 -0
- package/core/supervisor/state_store.py +249 -0
- package/core/supervisor/supervisor_host.py +511 -0
- package/core/supervisor/supervisor_models.py +1143 -0
- package/core/supervisor/systemic_failure.py +104 -0
- package/core/supervisor/task_scheduler.py +1640 -0
- package/core/supervisor/worker_checkpoint.py +230 -0
- package/core/supervisor/worker_execution.py +265 -0
- package/core/supervisor/worker_handoff.py +192 -0
- package/core/supervisor/worker_lifecycle.py +396 -0
- package/core/supervisor/worker_runtime.py +1005 -0
- package/core/supervisor/worker_sync.py +89 -0
- package/core/supervisor_types/README.md +36 -0
- package/core/supervisor_types/__init__.py +0 -0
- package/core/supervisor_types/exceptions.py +52 -0
- package/core/supervisor_types/graph_models.py +357 -0
- package/core/supervisor_types/path_containment.py +151 -0
- package/core/supervisor_types/target_fingerprint.py +310 -0
- package/core/supervisor_types/worker_claim.py +411 -0
- package/core/webui/INTERFACE.md +50 -0
- package/core/webui/README.md +57 -0
- package/core/webui/SPEC.md +26 -0
- package/core/webui/__init__.py +11 -0
- package/core/webui/adapters/__init__.py +27 -0
- package/core/webui/adapters/base.py +87 -0
- package/core/webui/adapters/bugx.py +102 -0
- package/core/webui/adapters/claude.py +222 -0
- package/core/webui/adapters/cline.py +407 -0
- package/core/webui/adapters/codex.py +260 -0
- package/core/webui/adapters/dsh.py +177 -0
- package/core/webui/adapters/opencode.py +218 -0
- package/core/webui/adapters/pi.py +272 -0
- package/core/webui/adapters/registry.py +100 -0
- package/core/webui/adapters/zcode.py +312 -0
- package/core/webui/api_routes_post.py +668 -0
- package/core/webui/dispatcher.py +1376 -0
- package/core/webui/docs_session_service.py +473 -0
- package/core/webui/handler.py +674 -0
- package/core/webui/ide_cloud_service.py +526 -0
- package/core/webui/mcp_inspector.py +1747 -0
- package/core/webui/static/00-base.css +1060 -0
- package/core/webui/static/01-monitoring.css +802 -0
- package/core/webui/static/02-header-actions.css +321 -0
- package/core/webui/static/03-trigger-popover.css +697 -0
- package/core/webui/static/04-composer.css +628 -0
- package/core/webui/static/05-skills-center.css +878 -0
- package/core/webui/static/06-mcp-center.css +623 -0
- package/core/webui/static/07-skill-detail.css +265 -0
- package/core/webui/static/08-files-management.css +167 -0
- package/core/webui/static/09-files-center.css +386 -0
- package/core/webui/static/10-icons.css +105 -0
- package/core/webui/static/11-project-options.css +185 -0
- package/core/webui/static/12-profile-tab.css +383 -0
- package/core/webui/static/assets/index-CXAsl8mr.js +333 -0
- package/core/webui/static/assets/index-DHQUtWtx.css +1 -0
- package/core/webui/static/assets/source-serif-4-cyrillic-400-normal-B8Z6Jvzv.woff +0 -0
- package/core/webui/static/assets/source-serif-4-cyrillic-400-normal-C44pakCn.woff2 +0 -0
- package/core/webui/static/assets/source-serif-4-cyrillic-500-normal-Bb4u56_6.woff +0 -0
- package/core/webui/static/assets/source-serif-4-cyrillic-500-normal-BdVUvljg.woff2 +0 -0
- package/core/webui/static/assets/source-serif-4-cyrillic-ext-400-normal-CWV284fw.woff2 +0 -0
- package/core/webui/static/assets/source-serif-4-cyrillic-ext-400-normal-DLkyKLvH.woff +0 -0
- package/core/webui/static/assets/source-serif-4-cyrillic-ext-500-normal-8-8HP2PF.woff +0 -0
- package/core/webui/static/assets/source-serif-4-cyrillic-ext-500-normal-DaDZE_Na.woff2 +0 -0
- package/core/webui/static/assets/source-serif-4-greek-400-normal-BccYJ-vZ.woff +0 -0
- package/core/webui/static/assets/source-serif-4-greek-400-normal-Cw5-AHNN.woff2 +0 -0
- package/core/webui/static/assets/source-serif-4-greek-500-normal-By8GFJzz.woff2 +0 -0
- package/core/webui/static/assets/source-serif-4-greek-500-normal-z-Q6FFuG.woff +0 -0
- package/core/webui/static/assets/source-serif-4-latin-400-normal-DJ5YJwmz.woff2 +0 -0
- package/core/webui/static/assets/source-serif-4-latin-400-normal-Dn3IlU-Z.woff +0 -0
- package/core/webui/static/assets/source-serif-4-latin-500-normal-CUHe9xxf.woff2 +0 -0
- package/core/webui/static/assets/source-serif-4-latin-500-normal-DVVamBqs.woff +0 -0
- package/core/webui/static/assets/source-serif-4-latin-ext-400-normal-CEpydyUl.woff +0 -0
- package/core/webui/static/assets/source-serif-4-latin-ext-400-normal-Cp7z-ARB.woff2 +0 -0
- package/core/webui/static/assets/source-serif-4-latin-ext-500-normal-BYjRCDVy.woff2 +0 -0
- package/core/webui/static/assets/source-serif-4-latin-ext-500-normal-D-qasQTj.woff +0 -0
- package/core/webui/static/assets/source-serif-4-vietnamese-400-normal-BbG3LG1A.woff2 +0 -0
- package/core/webui/static/assets/source-serif-4-vietnamese-400-normal-DR1UuFon.woff +0 -0
- package/core/webui/static/assets/source-serif-4-vietnamese-500-normal-8N8MYVKB.woff +0 -0
- package/core/webui/static/assets/source-serif-4-vietnamese-500-normal-Bi3OSTTW.woff2 +0 -0
- package/core/webui/static/design-tokens.css +113 -0
- package/core/webui/static/favicon.png +0 -0
- package/core/webui/static/icon-192.png +0 -0
- package/core/webui/static/index.html +55 -0
- package/core/webui/static/manifest.webmanifest +19 -0
- package/core/webui/static/project-settings.js +9602 -0
- package/core/webui/static/sw.js +8 -0
- package/core/webui/workspace_service.py +218 -0
- package/docs/07_distribution/01_README_NPM.md +285 -0
- package/ecosystem/README.md +129 -0
- package/ecosystem/integrations/README.md +38 -0
- package/ecosystem/integrations/cline/skills/bugx/SKILL.md +69 -0
- package/ecosystem/integrations/dsh/agents/bugx.md +27 -0
- package/ecosystem/integrations/dsh/dsh-patch.yml +18 -0
- package/ecosystem/integrations/dsh/mcp/cordis.patch.yml +4 -0
- package/ecosystem/integrations/dsh/mcp/index.js +219 -0
- package/ecosystem/integrations/dsh/mcp/package.json +28 -0
- package/ecosystem/integrations/dsh/skills/bugx/SKILL.md +70 -0
- package/ecosystem/integrations/dsh/skills/bugx-dsh/SKILL.md +229 -0
- package/ecosystem/integrations/dsh/ui/client.js +87 -0
- package/ecosystem/integrations/dsh/ui/cordis.patch.yml +4 -0
- package/ecosystem/integrations/dsh/ui/index.js +7 -0
- package/ecosystem/integrations/dsh/ui/package.json +27 -0
- package/ecosystem/integrations/opencode/bugx-mcp-manifest.json +53 -0
- package/ecosystem/integrations/opencode/mcp-lock.json +3075 -0
- package/ecosystem/integrations/opencode/opencode.json +129 -0
- package/ecosystem/integrations/pi/extensions/bugx/README.md +12 -0
- package/ecosystem/integrations/pi/extensions/bugx/index.ts +299 -0
- package/ecosystem/integrations/pi/extensions/bugx/manifest.json +11 -0
- package/ecosystem/integrations/pi/skills/bugx/SKILL.md +69 -0
- package/ecosystem/integrations/qoder/CONNECTORS.md +54 -0
- package/ecosystem/integrations/qoder/connector-meta.json +21 -0
- package/ecosystem/integrations/workbuddy/connector-meta.json +19 -0
- package/ecosystem/integrations/workbuddy/icon.png +0 -0
- package/ecosystem/integrations/workbuddy/skills/bugx/SKILL.md +70 -0
- package/ecosystem/plugins/README.md +37 -0
- package/ecosystem/plugins/bugx/.claude-plugin/marketplace.json +17 -0
- package/ecosystem/plugins/bugx/.claude-plugin/plugin.json +16 -0
- package/ecosystem/plugins/bugx/.codex-plugin/plugin.json +41 -0
- package/ecosystem/plugins/bugx/.zcode-plugin/plugin.json +19 -0
- package/ecosystem/plugins/bugx/agents/bugx-judge.md +71 -0
- package/ecosystem/plugins/bugx/agents/bugx-worker.md +31 -0
- package/ecosystem/plugins/bugx/agents/bugx.md +74 -0
- package/ecosystem/plugins/bugx/assets/bugx-avatar-512.png +0 -0
- package/ecosystem/plugins/bugx/skills/bugx/SKILL.md +118 -0
- package/ecosystem/plugins/bugx/skills/bugx-claude/SKILL.md +326 -0
- package/ecosystem/plugins/bugx/skills/bugx-dsh/SKILL.md +229 -0
- package/ecosystem/plugins/bugx/skills/bugx-opencode/SKILL.md +129 -0
- package/ecosystem/plugins/bugx/skills/bugx-zcode/SKILL.md +459 -0
- package/interfaces/bin/bugx.js +117 -0
- package/interfaces/cli/bugx_cli/__init__.py +6 -0
- package/interfaces/cli/bugx_cli/cli.py +1685 -0
- package/interfaces/cli/bugx_cli/commands/__init__.py +1 -0
- package/interfaces/cli/bugx_cli/commands/advisory.py +94 -0
- package/interfaces/cli/bugx_cli/commands/agent.py +4210 -0
- package/interfaces/cli/bugx_cli/commands/audit.py +632 -0
- package/interfaces/cli/bugx_cli/commands/autonomous.py +260 -0
- package/interfaces/cli/bugx_cli/commands/cloud.py +1371 -0
- package/interfaces/cli/bugx_cli/commands/daemon.py +50 -0
- package/interfaces/cli/bugx_cli/commands/doctor.py +1590 -0
- package/interfaces/cli/bugx_cli/commands/goal.py +107 -0
- package/interfaces/cli/bugx_cli/commands/interaction.py +248 -0
- package/interfaces/cli/bugx_cli/commands/knowledge.py +619 -0
- package/interfaces/cli/bugx_cli/commands/lifecycle.py +2763 -0
- package/interfaces/cli/bugx_cli/commands/patch.py +1014 -0
- package/interfaces/cli/bugx_cli/commands/plugin.py +2749 -0
- package/interfaces/cli/bugx_cli/commands/plugin_claude.py +1446 -0
- package/interfaces/cli/bugx_cli/commands/plugin_cline.py +269 -0
- package/interfaces/cli/bugx_cli/commands/plugin_codex.py +74 -0
- package/interfaces/cli/bugx_cli/commands/plugin_funide.py +729 -0
- package/interfaces/cli/bugx_cli/commands/plugin_qoder.py +216 -0
- package/interfaces/cli/bugx_cli/commands/plugin_zcode.py +710 -0
- package/interfaces/cli/bugx_cli/commands/project.py +670 -0
- package/interfaces/cli/bugx_cli/commands/report.py +256 -0
- package/interfaces/cli/bugx_cli/commands/skill.py +251 -0
- package/interfaces/cli/bugx_cli/commands/stats.py +133 -0
- package/interfaces/cli/bugx_cli/commands/system.py +2567 -0
- package/interfaces/cli/bugx_cli/common.py +906 -0
- package/interfaces/cli/bugx_cli/host_adapters.py +1892 -0
- package/interfaces/cli/bugx_cli/hosts/__init__.py +80 -0
- package/interfaces/cli/bugx_cli/hosts/base.py +99 -0
- package/interfaces/cli/bugx_cli/hosts/registry.py +573 -0
- package/interfaces/cli/bugx_cli/hosts/template_engine.py +188 -0
- package/interfaces/cli/bugx_cli/infra/__init__.py +209 -0
- package/interfaces/cli/bugx_cli/infra/ai_advisor.py +851 -0
- package/interfaces/cli/bugx_cli/infra/engine_installer.py +1945 -0
- package/interfaces/cli/bugx_cli/infra/host_sync.py +548 -0
- package/interfaces/cli/bugx_cli/infra/mcp_advisor.py +826 -0
- package/interfaces/cli/bugx_cli/infra/security.py +339 -0
- package/package.json +99 -4
- package/pyproject.toml +258 -0
- package/scripts/ensure-python.mjs +97 -0
- package/scripts/isolate-npm-readme.mjs +40 -0
- package/scripts/runtime.lock.json +31 -0
- package/scripts/sync-version.mjs +26 -0
- package/scripts/test-npm-wrapper.mjs +265 -0
|
@@ -0,0 +1,1014 @@
|
|
|
1
|
+
"""静态补丁包生成与校验(DOC-113 阶段 0/1)。
|
|
2
|
+
|
|
3
|
+
This module deliberately does not execute package contents or contact a remote
|
|
4
|
+
service. Remote replay, PR submission, signing and distribution are later
|
|
5
|
+
stages with separate security gates.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import hashlib
|
|
11
|
+
import io
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
import re
|
|
15
|
+
import shutil
|
|
16
|
+
import subprocess
|
|
17
|
+
import sys
|
|
18
|
+
import tempfile
|
|
19
|
+
import zipfile
|
|
20
|
+
from pathlib import Path, PurePosixPath
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
from ..common import CliError, _ensure_core_importable
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
MANIFEST_VERSION = 1
|
|
27
|
+
MAX_ARTIFACT_BYTES = 8 * 1024 * 1024
|
|
28
|
+
_HEX64 = re.compile(r"^[0-9a-fA-F]{64}$")
|
|
29
|
+
_SAFE_SIGNATURE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$")
|
|
30
|
+
_VERSION = re.compile(r"^\d+\.\d+\.\d+(?:a\d+)?$")
|
|
31
|
+
_PATCH_KIND = "engine"
|
|
32
|
+
_PATCH_SCOPE_ERROR = "BugX 修复补丁仅允许修复 BugX 自身代码(--kind engine);挖掘目标项目不属于 BugX 补丁"
|
|
33
|
+
# 「修复 BugX agent」的落点不只有 core/ 与 src/:测试、提示词、插件技能、脚本、
|
|
34
|
+
# 文档同样属于 BugX 自身。把它们挡在闸门外会让一批真实缺陷(例如纯 tests/ 的
|
|
35
|
+
# 契约修复)无法打包。这里改为命名空间白名单:允许 BugX 自己的全部命名空间,
|
|
36
|
+
# 仍然拒绝把补丁落到 BugX 之外(目标项目、任意第三方路径)。
|
|
37
|
+
_ENGINE_NAMESPACES = frozenset({
|
|
38
|
+
"core", "src", "tests", "docs", "scripts", "plugins", "skills",
|
|
39
|
+
"config", "integrations", "evals", "prd", "diagrams", "bin", "contrib",
|
|
40
|
+
".bugx-patches", ".github",
|
|
41
|
+
})
|
|
42
|
+
_ENGINE_ROOT_FILES = frozenset({
|
|
43
|
+
"pyproject.toml", "package.json", "MANIFEST.in", "AGENTS.md", "CLAUDE.md",
|
|
44
|
+
"README.md", "RELEASE.md", "HANDOFF.md", "Jenkinsfile", "LICENSE",
|
|
45
|
+
})
|
|
46
|
+
_PATCH_SCOPE_HINT = "补丁只能落在 BugX 自身命名空间内(" + "、".join(sorted(_ENGINE_NAMESPACES)) + ")或 BugX 根级文件"
|
|
47
|
+
# 执行型(红绿回放)失败与静态校验失败在报告里必须分开归因,否则一次 repro 失败
|
|
48
|
+
# 会把明明通过的 provenance/static-scan 也标成 failed。
|
|
49
|
+
_RED_GREEN_ERROR_PREFIX = "红绿闭环验证失败: "
|
|
50
|
+
_TOP_LEVEL = {
|
|
51
|
+
"schema_version", "patch_id", "kind", "base_version", "source_session",
|
|
52
|
+
"problem", "repro", "diff", "tests", "invariant_impact", "risk_class",
|
|
53
|
+
"review",
|
|
54
|
+
}
|
|
55
|
+
_GATE_MARKERS = (
|
|
56
|
+
"finding_confirmation", "agent_eval", "audit_supervisor", "budget_governor",
|
|
57
|
+
"supervisor_models", "checkpoint", "engine-integrity.json", "verify_life",
|
|
58
|
+
"lifecycle_reporter", "worker-checkpoint.schema.json",
|
|
59
|
+
)
|
|
60
|
+
_INFRA_MARKERS = (
|
|
61
|
+
"Jenkinsfile", ".github/workflows/", ".gitea/workflows/", "pyproject.toml",
|
|
62
|
+
"scripts/", "release", "package.json", "package-lock.json",
|
|
63
|
+
)
|
|
64
|
+
# 「纯文档」的判定口径 = 改了它不会改变任何运行时或 Agent 行为的说明性材料。
|
|
65
|
+
# 旧实现用 `path.endswith(".md")` 兜底,把 core/prompts/**、plugins/**、skills/**
|
|
66
|
+
# 这些**可执行的 Agent 指令**一并判成 docs,于是 review=auto、invariant_impact=none ——
|
|
67
|
+
# 改动 Agent 行为反而比改一行 Python 更宽松,无需任何人工审核。提示词退出码契约
|
|
68
|
+
# 被静默回退(PE-009 的修复被推翻)正是从这个缺口进来的。
|
|
69
|
+
_DOC_PATH_SEGMENTS = ("docs/",)
|
|
70
|
+
_AGENT_BEHAVIOR_MARKERS = (
|
|
71
|
+
"core/prompts/", "core/bugx-opencode.md", "plugins/", "skills/",
|
|
72
|
+
)
|
|
73
|
+
# 根级 Agent 指令文件同样是注入给 Agent 的行为约束,不是给人看的说明。
|
|
74
|
+
_AGENT_INSTRUCTION_ROOT_FILES = frozenset({"AGENTS.md", "CLAUDE.md"})
|
|
75
|
+
# 门禁自身的实现文件。改了它就能改判定口径,因此**不能**被自己判成
|
|
76
|
+
# `bugfix-behavioral`/`single` 而自证清白:`_GATE_MARKERS` 里的都是「被门禁守护的
|
|
77
|
+
# 对象」,这里是「门禁本身」,只能走 canary。用精确路径而非子串,避免误伤同名测试
|
|
78
|
+
# (例如 `tests/test_patch_engine.py`)。
|
|
79
|
+
_GATE_IMPLEMENTATION_FILES = frozenset({
|
|
80
|
+
"src/bugx_cli/commands/patch.py",
|
|
81
|
+
})
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _sha256(data: bytes) -> str:
|
|
85
|
+
return hashlib.sha256(data).hexdigest()
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _out_of_scope(paths: list[str]) -> list[str]:
|
|
89
|
+
"""返回不属于 BugX 自身命名空间的路径(保持输入顺序、去重)。"""
|
|
90
|
+
foreign: list[str] = []
|
|
91
|
+
for path in paths:
|
|
92
|
+
head, _, tail = path.partition("/")
|
|
93
|
+
if tail:
|
|
94
|
+
if head not in _ENGINE_NAMESPACES:
|
|
95
|
+
foreign.append(path)
|
|
96
|
+
elif path not in _ENGINE_ROOT_FILES:
|
|
97
|
+
foreign.append(path)
|
|
98
|
+
return foreign
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _safe_rel(value: object, *, field: str) -> str:
|
|
102
|
+
if not isinstance(value, str) or not value.strip():
|
|
103
|
+
raise CliError(f"{field} 必须是非空相对路径")
|
|
104
|
+
raw = value.strip().replace("\\", "/")
|
|
105
|
+
if "\x00" in raw or raw.startswith("/") or re.match(r"^[A-Za-z]:", raw):
|
|
106
|
+
raise CliError(f"{field} 不得是绝对路径")
|
|
107
|
+
if any(part in {"", ".", ".."} for part in raw.split("/")):
|
|
108
|
+
raise CliError(f"{field} 含非法路径段: {value!r}")
|
|
109
|
+
path = PurePosixPath(raw)
|
|
110
|
+
if not path.parts:
|
|
111
|
+
raise CliError(f"{field} 含非法路径段: {value!r}")
|
|
112
|
+
return path.as_posix()
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _source_file(root: Path, value: object, *, field: str) -> tuple[Path, str]:
|
|
116
|
+
relative = _safe_rel(value, field=field)
|
|
117
|
+
candidate = root / Path(*PurePosixPath(relative).parts)
|
|
118
|
+
current = root
|
|
119
|
+
for part in PurePosixPath(relative).parts:
|
|
120
|
+
current = current / part
|
|
121
|
+
if current.is_symlink():
|
|
122
|
+
raise CliError(f"{field} 不得经过 symlink: {relative}")
|
|
123
|
+
try:
|
|
124
|
+
resolved = candidate.resolve(strict=True)
|
|
125
|
+
resolved.relative_to(root)
|
|
126
|
+
except (FileNotFoundError, ValueError) as exc:
|
|
127
|
+
raise CliError(f"{field} 必须位于项目根内且存在: {relative}") from exc
|
|
128
|
+
if not resolved.is_file():
|
|
129
|
+
raise CliError(f"{field} 必须是文件: {relative}")
|
|
130
|
+
if resolved.stat().st_size > MAX_ARTIFACT_BYTES:
|
|
131
|
+
raise CliError(f"{field} 超过 {MAX_ARTIFACT_BYTES} 字节上限: {relative}")
|
|
132
|
+
return resolved, relative
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _read_issue(path: Path) -> tuple[str, bytes]:
|
|
136
|
+
try:
|
|
137
|
+
data = path.read_bytes()
|
|
138
|
+
title = next(
|
|
139
|
+
(line[2:].strip() for line in data.decode("utf-8").splitlines()
|
|
140
|
+
if line.startswith("# ") and line[2:].strip()),
|
|
141
|
+
path.stem,
|
|
142
|
+
)
|
|
143
|
+
except (OSError, UnicodeDecodeError) as exc:
|
|
144
|
+
raise CliError(f"无法读取 SPEC: {path}: {exc}") from exc
|
|
145
|
+
return title[:200], data
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _diff_paths(data: bytes) -> list[str]:
|
|
149
|
+
try:
|
|
150
|
+
text = data.decode("utf-8")
|
|
151
|
+
except UnicodeDecodeError as exc:
|
|
152
|
+
raise CliError("diff 必须是 UTF-8 文本") from exc
|
|
153
|
+
paths: list[str] = []
|
|
154
|
+
for line in text.splitlines():
|
|
155
|
+
if not line.startswith("+++ "):
|
|
156
|
+
continue
|
|
157
|
+
raw = line[4:].strip()
|
|
158
|
+
if raw == "/dev/null":
|
|
159
|
+
continue
|
|
160
|
+
if raw.startswith("b/"):
|
|
161
|
+
raw = raw[2:]
|
|
162
|
+
path = _safe_rel(raw, field="diff 触碰路径")
|
|
163
|
+
if path not in paths:
|
|
164
|
+
paths.append(path)
|
|
165
|
+
if not paths:
|
|
166
|
+
raise CliError("diff 未包含可识别的 unified diff '+++ b/<path>' 路径")
|
|
167
|
+
return paths
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _is_doc_path(path: str) -> bool:
|
|
171
|
+
"""判断路径是否属于「纯文档」—— 改动它不影响运行时或 Agent 行为。
|
|
172
|
+
|
|
173
|
+
Agent 指令类 ``.md``(``core/prompts/**``、``plugins/**``、``skills/**``、
|
|
174
|
+
根级 ``AGENTS.md``/``CLAUDE.md``)虽然也是文档格式,但改动会直接改变 Agent
|
|
175
|
+
行为,必须按行为变更审核(``review=single``),不得借 docs 通道 auto 放行。
|
|
176
|
+
"""
|
|
177
|
+
if any(marker in path for marker in _AGENT_BEHAVIOR_MARKERS):
|
|
178
|
+
return False
|
|
179
|
+
if path in _AGENT_INSTRUCTION_ROOT_FILES:
|
|
180
|
+
return False
|
|
181
|
+
if path.startswith(_DOC_PATH_SEGMENTS) or "/docs/" in path:
|
|
182
|
+
return True
|
|
183
|
+
return "/" not in path and path.endswith(".md")
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _risk_class(paths: list[str]) -> str:
|
|
187
|
+
normalized = [path.replace("\\", "/") for path in paths]
|
|
188
|
+
if any(path in _GATE_IMPLEMENTATION_FILES for path in normalized):
|
|
189
|
+
return "gate-semantics"
|
|
190
|
+
if any(any(marker in path for marker in _GATE_MARKERS) for path in normalized):
|
|
191
|
+
return "gate-semantics"
|
|
192
|
+
if normalized and all(_is_doc_path(path) for path in normalized):
|
|
193
|
+
return "docs"
|
|
194
|
+
if normalized and all(path.startswith("tests/") for path in normalized):
|
|
195
|
+
return "tests"
|
|
196
|
+
if any(any(marker in path for marker in _INFRA_MARKERS) for path in normalized):
|
|
197
|
+
return "infra"
|
|
198
|
+
return "bugfix-behavioral"
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _invariant_impact(paths: list[str], risk_class: str) -> str | dict[str, list[str]]:
|
|
202
|
+
if risk_class != "gate-semantics":
|
|
203
|
+
return "none"
|
|
204
|
+
impacted: set[str] = set()
|
|
205
|
+
for path in paths:
|
|
206
|
+
if any(marker in path for marker in ("finding_confirmation", "agent_eval")):
|
|
207
|
+
impacted.add("INV-1")
|
|
208
|
+
if any(marker in path for marker in ("audit_supervisor", "budget_governor", "supervisor_models", "checkpoint")):
|
|
209
|
+
impacted.update({"INV-3", "INV-6"})
|
|
210
|
+
if any(marker in path for marker in ("engine-integrity.json", "startup_gates")):
|
|
211
|
+
impacted.add("INV-7")
|
|
212
|
+
if any(marker in path for marker in ("coverage", "symbol_index", "module_coverage")):
|
|
213
|
+
impacted.add("INV-5")
|
|
214
|
+
return {"touched": sorted(impacted or {"INV-7"})}
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _review_required(risk_class: str) -> str:
|
|
218
|
+
return {
|
|
219
|
+
"docs": "auto",
|
|
220
|
+
"tests": "auto",
|
|
221
|
+
"bugfix-behavioral": "single",
|
|
222
|
+
"gate-semantics": "canary",
|
|
223
|
+
"infra": "dual",
|
|
224
|
+
}[risk_class]
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def _unknown_fields(value: object, allowed: set[str], label: str) -> list[str]:
|
|
228
|
+
if not isinstance(value, dict):
|
|
229
|
+
return []
|
|
230
|
+
return [f"{label} 含未知字段: {key}" for key in sorted(set(value) - allowed)]
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def _copy_name(index: int, source_name: str, suffix: str) -> str:
|
|
234
|
+
safe = re.sub(r"[^A-Za-z0-9._-]+", "-", source_name).strip(".-") or "artifact"
|
|
235
|
+
return f"{index:04d}-{safe}{suffix}"
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def _require_args(args: Any) -> None:
|
|
239
|
+
if not args.from_issue:
|
|
240
|
+
raise CliError("创建补丁包必须提供 --from-issue")
|
|
241
|
+
if args.kind != _PATCH_KIND:
|
|
242
|
+
raise CliError(_PATCH_SCOPE_ERROR)
|
|
243
|
+
if not args.patch_id or not re.fullmatch(r"PE-\d{8}-\d{3}", args.patch_id):
|
|
244
|
+
raise CliError("--patch-id 必须符合 PE-YYYYMMDD-NNN")
|
|
245
|
+
if not args.diff:
|
|
246
|
+
raise CliError("至少需要一个 --diff")
|
|
247
|
+
if not args.repro:
|
|
248
|
+
raise CliError("至少需要一个 --repro")
|
|
249
|
+
if not args.test:
|
|
250
|
+
raise CliError("至少需要一个 --test")
|
|
251
|
+
if not args.signature or not _SAFE_SIGNATURE.fullmatch(args.signature):
|
|
252
|
+
raise CliError("--signature 必须是 1-256 位安全指纹")
|
|
253
|
+
if args.severity not in {"high", "medium", "low", "info"}:
|
|
254
|
+
raise CliError("--severity 无效")
|
|
255
|
+
if not args.spec_only and not all((args.session_id, args.run_id, args.lifecycle_id, args.repository, args.finding_fingerprint)):
|
|
256
|
+
raise CliError("session 模式必须提供 session/run/lifecycle/repository/finding fingerprint;无证据请使用 --spec-only")
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def _build_package(root: Path, args: Any) -> tuple[dict[str, Any], dict[str, bytes]]:
|
|
260
|
+
_require_args(args)
|
|
261
|
+
issue_path, issue_relative = _source_file(root, args.from_issue, field="--from-issue")
|
|
262
|
+
title, issue_data = _read_issue(issue_path)
|
|
263
|
+
patch_payloads: dict[str, bytes] = {}
|
|
264
|
+
touched: list[str] = []
|
|
265
|
+
patch_files: list[dict[str, str]] = []
|
|
266
|
+
for index, value in enumerate(args.diff, 1):
|
|
267
|
+
source, _ = _source_file(root, value, field="--diff")
|
|
268
|
+
data = source.read_bytes()
|
|
269
|
+
paths = _diff_paths(data)
|
|
270
|
+
for path in paths:
|
|
271
|
+
if path not in touched:
|
|
272
|
+
touched.append(path)
|
|
273
|
+
dest = f"diff/{_copy_name(index, source.name, '.patch')}"
|
|
274
|
+
patch_payloads[dest] = data
|
|
275
|
+
patch_files.append({"path": dest, "sha256": _sha256(data)})
|
|
276
|
+
foreign = _out_of_scope(touched)
|
|
277
|
+
if foreign:
|
|
278
|
+
raise CliError(
|
|
279
|
+
f"补丁落在 BugX 命名空间之外: {', '.join(foreign)};{_PATCH_SCOPE_HINT}"
|
|
280
|
+
)
|
|
281
|
+
|
|
282
|
+
repro_entries: list[dict[str, Any]] = []
|
|
283
|
+
for index, value in enumerate(args.repro, 1):
|
|
284
|
+
source, _ = _source_file(root, value, field="--repro")
|
|
285
|
+
data = source.read_bytes()
|
|
286
|
+
dest = f"repro/{_copy_name(index, source.name, '')}"
|
|
287
|
+
patch_payloads[dest] = data
|
|
288
|
+
repro_entries.append({"path": dest, "before_exit": 0, "after_exit": 1, "sha256": _sha256(data)})
|
|
289
|
+
|
|
290
|
+
test_entries: list[dict[str, str]] = []
|
|
291
|
+
for index, value in enumerate(args.test, 1):
|
|
292
|
+
source, _ = _source_file(root, value, field="--test")
|
|
293
|
+
data = source.read_bytes()
|
|
294
|
+
dest = f"tests/{_copy_name(index, source.name, '')}"
|
|
295
|
+
patch_payloads[dest] = data
|
|
296
|
+
test_entries.append({"path": dest, "sha256": _sha256(data)})
|
|
297
|
+
|
|
298
|
+
risk_class = _risk_class(touched)
|
|
299
|
+
source_session: dict[str, Any]
|
|
300
|
+
if args.spec_only:
|
|
301
|
+
source_session = {"evidence_mode": "spec-only"}
|
|
302
|
+
evidence = ["spec-only"]
|
|
303
|
+
else:
|
|
304
|
+
source_session = {
|
|
305
|
+
"evidence_mode": "session",
|
|
306
|
+
"session_id": args.session_id,
|
|
307
|
+
"run_id": args.run_id,
|
|
308
|
+
"lifecycle_id": args.lifecycle_id,
|
|
309
|
+
"repository": args.repository,
|
|
310
|
+
"finding_fingerprints": list(args.finding_fingerprint),
|
|
311
|
+
}
|
|
312
|
+
evidence = [f"session:{args.session_id}", f"run:{args.run_id}", *[f"finding:{x}" for x in args.finding_fingerprint]]
|
|
313
|
+
manifest: dict[str, Any] = {
|
|
314
|
+
"schema_version": MANIFEST_VERSION,
|
|
315
|
+
"patch_id": args.patch_id,
|
|
316
|
+
"kind": args.kind,
|
|
317
|
+
"base_version": args.base_version,
|
|
318
|
+
"source_session": source_session,
|
|
319
|
+
"problem": {"signature": args.signature, "title": title, "severity": args.severity, "evidence": evidence},
|
|
320
|
+
"repro": repro_entries,
|
|
321
|
+
"diff": {
|
|
322
|
+
"files": sorted(touched),
|
|
323
|
+
"patch_files": patch_files,
|
|
324
|
+
"engine_integrity_updated": "engine-integrity.json" in " ".join(touched),
|
|
325
|
+
},
|
|
326
|
+
"tests": {"new": test_entries},
|
|
327
|
+
"invariant_impact": _invariant_impact(touched, risk_class),
|
|
328
|
+
"risk_class": risk_class,
|
|
329
|
+
"review": {"required": _review_required(risk_class)},
|
|
330
|
+
}
|
|
331
|
+
manifest_errors = validate_manifest(manifest)
|
|
332
|
+
if manifest_errors:
|
|
333
|
+
raise CliError("manifest 校验失败: " + "; ".join(manifest_errors))
|
|
334
|
+
patch_payloads["SPEC.md"] = issue_data
|
|
335
|
+
return manifest, patch_payloads
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def validate_manifest(manifest: object, package_root: Path | None = None) -> list[str]:
|
|
339
|
+
"""Validate the executable MVP contract without importing jsonschema."""
|
|
340
|
+
errors: list[str] = []
|
|
341
|
+
if not isinstance(manifest, dict):
|
|
342
|
+
return ["manifest 必须是 JSON object"]
|
|
343
|
+
unknown = sorted(set(manifest) - _TOP_LEVEL)
|
|
344
|
+
if unknown:
|
|
345
|
+
errors.append("未知字段: " + ", ".join(unknown))
|
|
346
|
+
if manifest.get("schema_version") != MANIFEST_VERSION:
|
|
347
|
+
errors.append("schema_version 不支持")
|
|
348
|
+
if not isinstance(manifest.get("patch_id"), str) or not re.fullmatch(r"PE-\d{8}-\d{3}", manifest.get("patch_id", "")):
|
|
349
|
+
errors.append("patch_id 格式错误")
|
|
350
|
+
kind = manifest.get("kind")
|
|
351
|
+
if kind != _PATCH_KIND:
|
|
352
|
+
errors.append(_PATCH_SCOPE_ERROR)
|
|
353
|
+
if not isinstance(manifest.get("base_version"), str) or not _VERSION.fullmatch(manifest.get("base_version", "")):
|
|
354
|
+
errors.append("base_version 格式错误")
|
|
355
|
+
|
|
356
|
+
source = manifest.get("source_session")
|
|
357
|
+
if not isinstance(source, dict) or source.get("evidence_mode") not in {"session", "spec-only"}:
|
|
358
|
+
errors.append("source_session/evidence_mode 缺失或无效")
|
|
359
|
+
elif source.get("evidence_mode") == "session":
|
|
360
|
+
errors.extend(_unknown_fields(source, {"evidence_mode", "session_id", "run_id", "lifecycle_id", "repository", "finding_fingerprints"}, "source_session"))
|
|
361
|
+
for key in ("session_id", "run_id", "lifecycle_id", "repository"):
|
|
362
|
+
if not isinstance(source.get(key), str) or not source[key].strip():
|
|
363
|
+
errors.append(f"source_session.{key} 缺失")
|
|
364
|
+
if not isinstance(source.get("finding_fingerprints"), list) or not source["finding_fingerprints"]:
|
|
365
|
+
errors.append("source_session.finding_fingerprints 缺失")
|
|
366
|
+
elif isinstance(source, dict):
|
|
367
|
+
errors.extend(_unknown_fields(source, {"evidence_mode"}, "source_session"))
|
|
368
|
+
|
|
369
|
+
problem = manifest.get("problem")
|
|
370
|
+
if not isinstance(problem, dict):
|
|
371
|
+
errors.append("problem 缺失")
|
|
372
|
+
else:
|
|
373
|
+
errors.extend(_unknown_fields(problem, {"signature", "title", "severity", "evidence"}, "problem"))
|
|
374
|
+
if not isinstance(problem.get("signature"), str) or not _SAFE_SIGNATURE.fullmatch(problem.get("signature", "")):
|
|
375
|
+
errors.append("problem.signature 无效")
|
|
376
|
+
if not isinstance(problem.get("title"), str) or not problem["title"].strip():
|
|
377
|
+
errors.append("problem.title 缺失")
|
|
378
|
+
if problem.get("severity") not in {"high", "medium", "low", "info"}:
|
|
379
|
+
errors.append("problem.severity 无效")
|
|
380
|
+
evidence = problem.get("evidence")
|
|
381
|
+
if not isinstance(evidence, list) or not evidence or any(not isinstance(x, str) or not x.strip() for x in evidence):
|
|
382
|
+
errors.append("problem.evidence 必须是非空字符串数组")
|
|
383
|
+
elif isinstance(source, dict) and source.get("evidence_mode") == "spec-only":
|
|
384
|
+
if evidence != ["spec-only"]:
|
|
385
|
+
errors.append("spec-only 补丁的 problem.evidence 必须精确为 ['spec-only']")
|
|
386
|
+
elif isinstance(source, dict) and source.get("evidence_mode") == "session":
|
|
387
|
+
required_evidence = {f"session:{source.get('session_id')}", f"run:{source.get('run_id')}"}
|
|
388
|
+
if not required_evidence.issubset(set(evidence)) or not any(x.startswith("finding:") for x in evidence):
|
|
389
|
+
errors.append("session 补丁的 problem.evidence 必须包含 session/run/finding 引用")
|
|
390
|
+
|
|
391
|
+
diff = manifest.get("diff")
|
|
392
|
+
touched: list[str] = []
|
|
393
|
+
if not isinstance(diff, dict):
|
|
394
|
+
errors.append("diff 缺失")
|
|
395
|
+
else:
|
|
396
|
+
errors.extend(_unknown_fields(diff, {"files", "patch_files", "engine_integrity_updated"}, "diff"))
|
|
397
|
+
raw_paths = diff.get("files")
|
|
398
|
+
if not isinstance(raw_paths, list) or not raw_paths:
|
|
399
|
+
errors.append("diff.files 不能为空")
|
|
400
|
+
else:
|
|
401
|
+
for value in raw_paths:
|
|
402
|
+
try:
|
|
403
|
+
path = _safe_rel(value, field="diff.files")
|
|
404
|
+
touched.append(path)
|
|
405
|
+
except CliError as exc:
|
|
406
|
+
errors.append(str(exc))
|
|
407
|
+
if len(set(touched)) != len(touched):
|
|
408
|
+
errors.append("diff.files 不得重复")
|
|
409
|
+
patch_files = diff.get("patch_files")
|
|
410
|
+
if not isinstance(patch_files, list) or not patch_files:
|
|
411
|
+
errors.append("diff.patch_files 不能为空")
|
|
412
|
+
else:
|
|
413
|
+
for item in patch_files:
|
|
414
|
+
if not isinstance(item, dict) or not isinstance(item.get("path"), str) or not _HEX64.fullmatch(str(item.get("sha256", ""))):
|
|
415
|
+
errors.append("diff.patch_files 项格式错误")
|
|
416
|
+
elif not re.fullmatch(r"diff/[^/]+[.]patch", str(item["path"])):
|
|
417
|
+
errors.append("diff.patch_files 必须位于 diff/")
|
|
418
|
+
if diff.get("engine_integrity_updated") not in {True, False}:
|
|
419
|
+
errors.append("diff.engine_integrity_updated 必须是布尔值")
|
|
420
|
+
if "engine-integrity.json" in touched and diff.get("engine_integrity_updated") is not True:
|
|
421
|
+
errors.append("触碰 engine-integrity.json 时必须显式声明 engine_integrity_updated=true")
|
|
422
|
+
if kind == _PATCH_KIND:
|
|
423
|
+
for path in _out_of_scope(touched):
|
|
424
|
+
errors.append(f"diff.files 落在 BugX 命名空间之外: {path};{_PATCH_SCOPE_HINT}")
|
|
425
|
+
|
|
426
|
+
repro = manifest.get("repro")
|
|
427
|
+
if not isinstance(repro, list) or not repro:
|
|
428
|
+
errors.append("repro 不能为空")
|
|
429
|
+
else:
|
|
430
|
+
for item in repro:
|
|
431
|
+
if not isinstance(item, dict):
|
|
432
|
+
errors.append("repro 项必须是 object")
|
|
433
|
+
else:
|
|
434
|
+
errors.extend(_unknown_fields(item, {"path", "before_exit", "after_exit", "sha256"}, "repro"))
|
|
435
|
+
if not isinstance(item, dict) or item.get("before_exit") != 0 or item.get("after_exit") != 1:
|
|
436
|
+
errors.append("repro 必须声明 before_exit=0/after_exit=1")
|
|
437
|
+
elif not isinstance(item.get("path"), str) or not item["path"].startswith("repro/") or not _HEX64.fullmatch(str(item.get("sha256", ""))):
|
|
438
|
+
errors.append("repro path/sha256 无效")
|
|
439
|
+
tests = manifest.get("tests")
|
|
440
|
+
if not isinstance(tests, dict) or not isinstance(tests.get("new"), list) or not tests["new"]:
|
|
441
|
+
errors.append("tests.new 不能为空")
|
|
442
|
+
elif any(
|
|
443
|
+
not isinstance(x, dict)
|
|
444
|
+
or not isinstance(x.get("path"), str)
|
|
445
|
+
or not x["path"].startswith("tests/")
|
|
446
|
+
or not _HEX64.fullmatch(str(x.get("sha256", "")))
|
|
447
|
+
for x in tests["new"]
|
|
448
|
+
):
|
|
449
|
+
errors.append("tests.new 项必须包含 tests/ 路径和 SHA-256")
|
|
450
|
+
elif _unknown_fields(tests, {"new", "golden_baseline_ref"}, "tests"):
|
|
451
|
+
errors.extend(_unknown_fields(tests, {"new", "golden_baseline_ref"}, "tests"))
|
|
452
|
+
|
|
453
|
+
impact = manifest.get("invariant_impact")
|
|
454
|
+
if isinstance(impact, dict):
|
|
455
|
+
errors.extend(_unknown_fields(impact, {"touched"}, "invariant_impact"))
|
|
456
|
+
impact_ids = impact.get("touched") if isinstance(impact, dict) else []
|
|
457
|
+
if impact != "none" and (not isinstance(impact, dict) or not isinstance(impact_ids, list) or not impact_ids):
|
|
458
|
+
errors.append("invariant_impact 无效")
|
|
459
|
+
if any(not isinstance(x, str) or not re.fullmatch(r"INV-[1-8]", x) for x in impact_ids):
|
|
460
|
+
errors.append("invariant_impact.touched 含未知 INV")
|
|
461
|
+
risk = manifest.get("risk_class")
|
|
462
|
+
expected_risk = _risk_class(touched) if touched else None
|
|
463
|
+
if risk not in {"docs", "tests", "bugfix-behavioral", "gate-semantics", "infra"}:
|
|
464
|
+
errors.append("risk_class 无效")
|
|
465
|
+
elif expected_risk and risk != expected_risk:
|
|
466
|
+
errors.append(f"risk_class 与触碰文件不一致,应为 {expected_risk}")
|
|
467
|
+
if risk == "gate-semantics" and impact == "none":
|
|
468
|
+
errors.append("gate-semantics 必须声明 invariant_impact.touched")
|
|
469
|
+
if risk != "gate-semantics" and impact != "none":
|
|
470
|
+
errors.append("非 gate-semantics 不得声明 touched invariant")
|
|
471
|
+
review = manifest.get("review")
|
|
472
|
+
if risk in {"docs", "tests", "bugfix-behavioral", "gate-semantics", "infra"}:
|
|
473
|
+
errors.extend(_unknown_fields(review, {"required", "approvers"}, "review"))
|
|
474
|
+
if not isinstance(review, dict) or review.get("required") != _review_required(risk):
|
|
475
|
+
errors.append("review.required 与 risk_class 不一致")
|
|
476
|
+
|
|
477
|
+
if package_root is not None and not errors:
|
|
478
|
+
for item in diff["patch_files"]:
|
|
479
|
+
errors.extend(_verify_artifact(package_root, item["path"], item["sha256"]))
|
|
480
|
+
for item in repro:
|
|
481
|
+
errors.extend(_verify_artifact(package_root, item["path"], item["sha256"]))
|
|
482
|
+
for item in tests["new"]:
|
|
483
|
+
errors.extend(_verify_artifact(package_root, item["path"], item["sha256"]))
|
|
484
|
+
try:
|
|
485
|
+
_package_file(package_root, "SPEC.md")
|
|
486
|
+
except CliError as exc:
|
|
487
|
+
errors.append(str(exc))
|
|
488
|
+
return errors
|
|
489
|
+
|
|
490
|
+
|
|
491
|
+
def _package_file(root: Path, relative: str) -> Path:
|
|
492
|
+
safe = _safe_rel(relative, field="artifact")
|
|
493
|
+
path = root / Path(*PurePosixPath(safe).parts)
|
|
494
|
+
current = root
|
|
495
|
+
for part in PurePosixPath(safe).parts:
|
|
496
|
+
current = current / part
|
|
497
|
+
if current.is_symlink():
|
|
498
|
+
raise CliError(f"artifact 不得经过 symlink: {safe}")
|
|
499
|
+
try:
|
|
500
|
+
resolved_root = root.resolve(strict=True)
|
|
501
|
+
resolved = path.resolve(strict=True)
|
|
502
|
+
resolved.relative_to(resolved_root)
|
|
503
|
+
except (FileNotFoundError, ValueError):
|
|
504
|
+
raise CliError(f"缺少或越界 artifact: {safe}")
|
|
505
|
+
if not resolved.is_file():
|
|
506
|
+
raise CliError(f"缺少或非法 artifact: {safe}")
|
|
507
|
+
return resolved
|
|
508
|
+
|
|
509
|
+
|
|
510
|
+
def _verify_artifact(root: Path, relative: str, expected: str) -> list[str]:
|
|
511
|
+
try:
|
|
512
|
+
resolved = _package_file(root, relative)
|
|
513
|
+
except CliError as exc:
|
|
514
|
+
return [str(exc)]
|
|
515
|
+
if resolved.stat().st_size > MAX_ARTIFACT_BYTES:
|
|
516
|
+
return [f"artifact 超过大小上限: {relative}"]
|
|
517
|
+
if _sha256(resolved.read_bytes()) != str(expected).lower():
|
|
518
|
+
return [f"artifact hash 不匹配: {relative}"]
|
|
519
|
+
return []
|
|
520
|
+
|
|
521
|
+
|
|
522
|
+
def _verification_report(
|
|
523
|
+
manifest: dict[str, Any],
|
|
524
|
+
errors: list[str],
|
|
525
|
+
*,
|
|
526
|
+
red_to_green_status: str = "deferred",
|
|
527
|
+
red_to_green_detail: str = "execution_deferred: MVP does not execute package contents",
|
|
528
|
+
) -> dict[str, Any]:
|
|
529
|
+
passed = not errors
|
|
530
|
+
# 静态阶段只看静态校验结果;红绿回放失败属于执行型验证,单独归因到 repro-replay
|
|
531
|
+
static_errors = [e for e in errors if not e.startswith(_RED_GREEN_ERROR_PREFIX)]
|
|
532
|
+
static_passed = not static_errors
|
|
533
|
+
routing_status = "deferred"
|
|
534
|
+
routing_detail = "execution_deferred: MVP does not execute package contents"
|
|
535
|
+
|
|
536
|
+
stages = [
|
|
537
|
+
{"stage": "provenance", "status": "passed" if static_passed else "failed", "detail": "manifest/source/engine contract" if static_passed else "; ".join(static_errors[:8])},
|
|
538
|
+
{"stage": "static-scan", "status": "passed" if static_passed else "failed", "detail": "paths, hashes and risk policy"},
|
|
539
|
+
{"stage": "repro-replay", "status": red_to_green_status if red_to_green_status != "deferred" else "deferred", "detail": red_to_green_detail if red_to_green_status != "deferred" else "execution_deferred: MVP does not execute package contents"},
|
|
540
|
+
{"stage": "invariants", "status": "deferred", "detail": "execution_deferred: MVP does not execute package contents"},
|
|
541
|
+
{"stage": "golden-baseline", "status": "passed" if red_to_green_status == "passed" else "deferred", "detail": "repro and regression tests verified" if red_to_green_status == "passed" else "execution_deferred: MVP does not execute package contents"},
|
|
542
|
+
{"stage": "self-audit", "status": "deferred", "detail": "execution_deferred: MVP does not execute package contents"},
|
|
543
|
+
{"stage": "routing", "status": routing_status, "detail": routing_detail},
|
|
544
|
+
{"stage": "report", "status": "passed", "detail": "deterministic static report"},
|
|
545
|
+
]
|
|
546
|
+
|
|
547
|
+
if not passed:
|
|
548
|
+
decision = "rejected"
|
|
549
|
+
decision_reason = "; ".join(errors)
|
|
550
|
+
elif red_to_green_status == "passed":
|
|
551
|
+
decision = "verified-local"
|
|
552
|
+
decision_reason = f"静态校验与本地红绿受限回放通过: {red_to_green_detail}"
|
|
553
|
+
else:
|
|
554
|
+
decision = "verification-deferred"
|
|
555
|
+
decision_reason = "静态 MVP 通过;执行型验证和远端路由 deferred"
|
|
556
|
+
|
|
557
|
+
return {
|
|
558
|
+
"schema_version": 1,
|
|
559
|
+
"patch_id": manifest.get("patch_id", ""),
|
|
560
|
+
"verifier_version": "static-mvp-1",
|
|
561
|
+
"stages": stages,
|
|
562
|
+
"invariants": {
|
|
563
|
+
"total": 0,
|
|
564
|
+
"failed": [],
|
|
565
|
+
"touched_declared": list((manifest.get("invariant_impact") or {}).get("touched", []))
|
|
566
|
+
if isinstance(manifest.get("invariant_impact"), dict) else [],
|
|
567
|
+
"touched_detected": [],
|
|
568
|
+
"mismatch": False,
|
|
569
|
+
},
|
|
570
|
+
"risk_class_confirmed": manifest.get("risk_class", "bugfix-behavioral"),
|
|
571
|
+
"decision": decision,
|
|
572
|
+
"decision_reason": decision_reason,
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
|
|
576
|
+
def _write_json(path: Path, payload: object) -> None:
|
|
577
|
+
path.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
|
578
|
+
|
|
579
|
+
|
|
580
|
+
def _print_report(report: dict[str, Any], *, as_json: bool) -> None:
|
|
581
|
+
if as_json:
|
|
582
|
+
print(json.dumps(report, ensure_ascii=False, indent=2))
|
|
583
|
+
return
|
|
584
|
+
print(f"patch_id: {report.get('patch_id')}")
|
|
585
|
+
print(f"decision: {report.get('decision')}")
|
|
586
|
+
print(f"reason: {report.get('decision_reason')}")
|
|
587
|
+
for stage in report.get("stages", []):
|
|
588
|
+
print(f" {stage['stage']}: {stage['status']}")
|
|
589
|
+
|
|
590
|
+
|
|
591
|
+
def _import_root_for(root: Path, relative: str) -> Path | None:
|
|
592
|
+
"""推导 ``relative`` 所属的导入根,即应加入 ``sys.path`` 的目录。
|
|
593
|
+
|
|
594
|
+
两种布局:
|
|
595
|
+
|
|
596
|
+
- **常规包**:``src/bugx_cli/commands/cloud.py`` -> ``root/src``
|
|
597
|
+
(``bugx_cli`` 是顶层包,其父目录才是导入根)。
|
|
598
|
+
- **松散模块目录**:引擎 ``core/`` 下没有 ``__init__.py``,其中的模块以顶层
|
|
599
|
+
模块导入(``import cloud_client``),因此 ``core`` 目录本身就是导入根。
|
|
600
|
+
|
|
601
|
+
仓库根下的 ``.py`` 返回 ``None``(``sandbox`` 已在 ``extra_pythonpath`` 中且排在
|
|
602
|
+
``root`` 之前,无需特殊处理);其它无法判定包结构的路径同样返回 ``None``。
|
|
603
|
+
"""
|
|
604
|
+
parts = PurePosixPath(relative).parts
|
|
605
|
+
for index in range(len(parts) - 1, 0, -1):
|
|
606
|
+
candidate = root.joinpath(*parts[:index])
|
|
607
|
+
if not (candidate / "__init__.py").is_file():
|
|
608
|
+
continue
|
|
609
|
+
parent = root.joinpath(*parts[: index - 1])
|
|
610
|
+
if not (parent / "__init__.py").is_file():
|
|
611
|
+
return parent
|
|
612
|
+
if PurePosixPath(relative).suffix == ".py" and len(parts) > 1:
|
|
613
|
+
# 无包结构:所在目录即导入根(``core/cloud_client.py`` -> ``root/core``)。
|
|
614
|
+
# 仓库根下的模块无需特殊处理 —— ``extra_pythonpath`` 里已有 ``sandbox`` 且
|
|
615
|
+
# 排在 ``root`` 之前,``import foo`` 本就会命中沙箱副本。
|
|
616
|
+
return root.joinpath(*parts[:-1])
|
|
617
|
+
return None
|
|
618
|
+
|
|
619
|
+
|
|
620
|
+
def _stage_isolated_copy(root: Path, sandbox: Path, touched: list[str]) -> list[Path]:
|
|
621
|
+
"""在沙箱内重建可导入的隔离副本,返回沙箱侧的导入根列表。
|
|
622
|
+
|
|
623
|
+
只复制受补丁影响的文件是不够的:Python 会从 ``sys.path`` 中第一个命中的位置
|
|
624
|
+
加载整个模块(常规包看 ``__init__.py``,松散模块看同名 ``.py``),落在沙箱里的
|
|
625
|
+
单文件永远不会被导入,红绿回放实际验证的是宿主进程的模块解析结果,补丁等于没被
|
|
626
|
+
验证。因此必须连同导入根一起复制,让沙箱副本成为 ``sys.path`` 上的第一个命中。
|
|
627
|
+
"""
|
|
628
|
+
sandbox_roots: list[Path] = []
|
|
629
|
+
for relative in touched:
|
|
630
|
+
base = _import_root_for(root, relative)
|
|
631
|
+
if base is None:
|
|
632
|
+
source = root / Path(*PurePosixPath(relative).parts)
|
|
633
|
+
if source.is_file():
|
|
634
|
+
target = sandbox / Path(*PurePosixPath(relative).parts)
|
|
635
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
636
|
+
shutil.copy2(source, target)
|
|
637
|
+
continue
|
|
638
|
+
mirror = sandbox / base.relative_to(root)
|
|
639
|
+
if mirror in sandbox_roots:
|
|
640
|
+
continue
|
|
641
|
+
shutil.copytree(
|
|
642
|
+
base,
|
|
643
|
+
mirror,
|
|
644
|
+
dirs_exist_ok=True,
|
|
645
|
+
ignore=shutil.ignore_patterns(".git", "__pycache__", "*.pyc", "*.pyo"),
|
|
646
|
+
)
|
|
647
|
+
sandbox_roots.append(mirror)
|
|
648
|
+
return sandbox_roots
|
|
649
|
+
|
|
650
|
+
|
|
651
|
+
def _platform_adapter() -> Any | None:
|
|
652
|
+
"""导入 core 的 ``platform_adapter``(沙箱执行器与安全白名单的来源)。
|
|
653
|
+
|
|
654
|
+
优先直接 ``import``:沙箱的 ``PYTHONPATH`` 里已经带了 core 引擎目录
|
|
655
|
+
(见 ``_sandbox_env``),所以沙箱内的副本不必依赖 ``asset_root()``。
|
|
656
|
+
这一步是必需的 —— 沙箱里只复制了 ``src/`` 时,``_ensure_core_importable()``
|
|
657
|
+
会因为 ``asset_root()`` 找不到 Agent 资源而抛 ``CliError``,而补丁包内的
|
|
658
|
+
repro/test 恰恰是在这种沙箱里运行的。``_ensure_core_importable()`` 在
|
|
659
|
+
``common._i18n_exc`` 里同样是被 try/except 包住的,本处沿用同一约定。
|
|
660
|
+
|
|
661
|
+
拿不到时返回 ``None``,由调用方 fail-closed。
|
|
662
|
+
"""
|
|
663
|
+
try:
|
|
664
|
+
from core.runtime import platform_adapter
|
|
665
|
+
|
|
666
|
+
return platform_adapter
|
|
667
|
+
except Exception:
|
|
668
|
+
pass
|
|
669
|
+
try:
|
|
670
|
+
_ensure_core_importable()
|
|
671
|
+
from core.runtime import platform_adapter
|
|
672
|
+
|
|
673
|
+
return platform_adapter
|
|
674
|
+
except Exception:
|
|
675
|
+
return None
|
|
676
|
+
|
|
677
|
+
|
|
678
|
+
def _sandbox_env(
|
|
679
|
+
extra_pythonpath: list[Path] | None,
|
|
680
|
+
adapter: Any,
|
|
681
|
+
) -> dict[str, str]:
|
|
682
|
+
"""构造沙箱子进程环境:只放行 core 平台适配器认可的 ``SAFE_ENV`` 白名单。
|
|
683
|
+
|
|
684
|
+
包内 repro/test 是不受信内容(AI 合成;``--verify`` 还可能验别人提交的包)。
|
|
685
|
+
继承整个宿主环境等于把它们要用的凭据一并交出去 ——
|
|
686
|
+
``BUGX_PATCH_VERIFICATION_API_KEY`` 正是提交补丁用的那把密钥。同时也不再把
|
|
687
|
+
宿主的 ``PYTHONPATH`` 透传下去,避免宿主的同名模块遮蔽沙箱副本。
|
|
688
|
+
"""
|
|
689
|
+
env = {name: os.environ[name] for name in adapter.SAFE_ENV if name in os.environ}
|
|
690
|
+
# 禁止写字节码缓存:Phase 1 先导入一次、Phase 2 才打补丁、Phase 3 再导入,
|
|
691
|
+
# 而 pyc 的有效性只比对源文件的 (mtime 秒, 字节数)。补丁若产出**同字节数**的
|
|
692
|
+
# 文件且落在同一秒内,Phase 3 会复用 Phase 1 编译出的陈旧字节码,判定随机器
|
|
693
|
+
# 快慢而变(实测同一用例 5 次里 4 次误判"缺陷未消除")。
|
|
694
|
+
env["PYTHONDONTWRITEBYTECODE"] = "1"
|
|
695
|
+
entries = [str(path.resolve()) for path in (extra_pythonpath or []) if path.exists()]
|
|
696
|
+
# 把 core 引擎目录一并带上,且排在沙箱导入根之后(沙箱副本仍优先命中):
|
|
697
|
+
# 包内 repro/test 会 import bugx_cli,而沙箱内的副本解析 core 时不能再依赖
|
|
698
|
+
# asset_root() —— 沙箱里没有 Agent 资源。
|
|
699
|
+
core_dir = str(Path(adapter.__file__).resolve().parent)
|
|
700
|
+
if core_dir not in entries:
|
|
701
|
+
entries.append(core_dir)
|
|
702
|
+
if entries:
|
|
703
|
+
env["PYTHONPATH"] = os.pathsep.join(entries)
|
|
704
|
+
return env
|
|
705
|
+
|
|
706
|
+
|
|
707
|
+
def _run_sandbox_script(
|
|
708
|
+
script_path: Path,
|
|
709
|
+
*,
|
|
710
|
+
cwd: Path,
|
|
711
|
+
extra_pythonpath: list[Path] | None = None,
|
|
712
|
+
timeout: int = 15,
|
|
713
|
+
) -> tuple[int, str]:
|
|
714
|
+
"""在沙箱中执行包内脚本,返回 ``(退出码, 输出)``。
|
|
715
|
+
|
|
716
|
+
执行交给 core 的 ``_run_bounded``:它建立了新会话(超时可杀掉整个进程组)、
|
|
717
|
+
限制输出上限、并把 stdin 接到 DEVNULL。此前这里是裸 ``subprocess.run``,
|
|
718
|
+
超时只杀直接子进程,孙进程会带着宿主环境继续跑。
|
|
719
|
+
|
|
720
|
+
拿不到加固执行器时 fail-closed:宁可不执行,也不在未加固的环境里跑不受信脚本。
|
|
721
|
+
"""
|
|
722
|
+
adapter = _platform_adapter()
|
|
723
|
+
runner = getattr(adapter, "_run_bounded", None)
|
|
724
|
+
output_limit = getattr(adapter, "DEFAULT_OUTPUT_LIMIT", None)
|
|
725
|
+
safe_env = getattr(adapter, "SAFE_ENV", None)
|
|
726
|
+
if runner is None or output_limit is None or not safe_env:
|
|
727
|
+
return -1, "沙箱执行器不可用: 无法导入 core.platform_adapter,拒绝在未加固环境中执行包内脚本"
|
|
728
|
+
|
|
729
|
+
env = _sandbox_env(extra_pythonpath, adapter)
|
|
730
|
+
|
|
731
|
+
cmd: list[str]
|
|
732
|
+
if script_path.suffix == ".py":
|
|
733
|
+
cmd = [sys.executable, str(script_path)]
|
|
734
|
+
elif script_path.suffix == ".sh":
|
|
735
|
+
cmd = ["/bin/bash", str(script_path)]
|
|
736
|
+
else:
|
|
737
|
+
cmd = [str(script_path)]
|
|
738
|
+
|
|
739
|
+
try:
|
|
740
|
+
code, timed_out, stdout, stdout_meta, stderr, stderr_meta = runner(
|
|
741
|
+
cmd, cwd, env, float(timeout), output_limit,
|
|
742
|
+
)
|
|
743
|
+
except Exception as exc:
|
|
744
|
+
return -1, f"脚本执行异常: {exc}"
|
|
745
|
+
if timed_out:
|
|
746
|
+
return -1, f"脚本执行超时 ({timeout}s)"
|
|
747
|
+
|
|
748
|
+
out = stdout.decode("utf-8", errors="replace")
|
|
749
|
+
err = stderr.decode("utf-8", errors="replace")
|
|
750
|
+
if stdout_meta.get("truncated") or stderr_meta.get("truncated"):
|
|
751
|
+
out += f"\n[输出已截断至 {output_limit} 字节]"
|
|
752
|
+
return code, (out + ("\n" + err if err else "")).strip()
|
|
753
|
+
|
|
754
|
+
|
|
755
|
+
def _apply_patch(sandbox: Path, patch_data: bytes) -> tuple[bool, str]:
|
|
756
|
+
patch_file = sandbox / ".bugx_tmp.patch"
|
|
757
|
+
patch_file.write_bytes(patch_data)
|
|
758
|
+
try:
|
|
759
|
+
if not (sandbox / ".git").is_dir():
|
|
760
|
+
subprocess.run(["git", "init", "-q"], cwd=str(sandbox), check=True)
|
|
761
|
+
subprocess.run(["git", "config", "user.name", "BugX"], cwd=str(sandbox), check=True)
|
|
762
|
+
subprocess.run(["git", "config", "user.email", "bugx@antigravity"], cwd=str(sandbox), check=True)
|
|
763
|
+
subprocess.run(["git", "add", "."], cwd=str(sandbox), check=True)
|
|
764
|
+
|
|
765
|
+
res = subprocess.run(
|
|
766
|
+
["git", "apply", "--whitespace=nowarn", str(patch_file.name)],
|
|
767
|
+
cwd=str(sandbox),
|
|
768
|
+
capture_output=True,
|
|
769
|
+
text=True,
|
|
770
|
+
)
|
|
771
|
+
if res.returncode == 0:
|
|
772
|
+
return True, ""
|
|
773
|
+
return False, res.stderr or res.stdout or "git apply failed"
|
|
774
|
+
except Exception as exc:
|
|
775
|
+
return False, str(exc)
|
|
776
|
+
finally:
|
|
777
|
+
if patch_file.exists():
|
|
778
|
+
patch_file.unlink(missing_ok=True)
|
|
779
|
+
|
|
780
|
+
|
|
781
|
+
def _execute_red_to_green(
|
|
782
|
+
root: Path,
|
|
783
|
+
touched: list[str],
|
|
784
|
+
patch_data_list: list[bytes],
|
|
785
|
+
repro_items: list[tuple[str, int, int, bytes]],
|
|
786
|
+
test_items: list[tuple[str, bytes]],
|
|
787
|
+
) -> tuple[bool, str]:
|
|
788
|
+
with tempfile.TemporaryDirectory(prefix="bugx-r2g-") as tmpdir:
|
|
789
|
+
sandbox = Path(tmpdir).resolve()
|
|
790
|
+
# 1. 在沙箱内重建可导入的隔离副本(仅复制 touched 文件会让补丁成为死代码)
|
|
791
|
+
sandbox_roots = _stage_isolated_copy(root, sandbox, touched)
|
|
792
|
+
# 沙箱导入根必须排在宿主之前,否则受补丁文件会被宿主副本遮蔽
|
|
793
|
+
extra_pythonpath = [
|
|
794
|
+
*sandbox_roots,
|
|
795
|
+
*(root / mirror.relative_to(sandbox) for mirror in sandbox_roots),
|
|
796
|
+
sandbox,
|
|
797
|
+
root,
|
|
798
|
+
]
|
|
799
|
+
|
|
800
|
+
# 2. 写入 repro 脚本
|
|
801
|
+
repro_paths: list[tuple[Path, int, int]] = []
|
|
802
|
+
for rel, before_exit, after_exit, data in repro_items:
|
|
803
|
+
dst = sandbox / Path(*PurePosixPath(rel).parts)
|
|
804
|
+
dst.parent.mkdir(parents=True, exist_ok=True)
|
|
805
|
+
dst.write_bytes(data)
|
|
806
|
+
repro_paths.append((dst, before_exit, after_exit))
|
|
807
|
+
|
|
808
|
+
# 3. 写入 test 脚本
|
|
809
|
+
test_paths: list[Path] = []
|
|
810
|
+
for rel, data in test_items:
|
|
811
|
+
dst = sandbox / Path(*PurePosixPath(rel).parts)
|
|
812
|
+
dst.parent.mkdir(parents=True, exist_ok=True)
|
|
813
|
+
dst.write_bytes(data)
|
|
814
|
+
test_paths.append(dst)
|
|
815
|
+
|
|
816
|
+
# 4. Phase 1 (Red): 执行修复前 repro,必须复现缺陷(返回码等于 before_exit)
|
|
817
|
+
for repro_file, before_exit, _ in repro_paths:
|
|
818
|
+
rc, out = _run_sandbox_script(repro_file, cwd=sandbox, extra_pythonpath=extra_pythonpath)
|
|
819
|
+
if rc != before_exit:
|
|
820
|
+
return False, f"Repro 预检失败 (未复现缺陷): 预期 exit {before_exit}, 实际 exit {rc}. 输出:\n{out}"
|
|
821
|
+
|
|
822
|
+
# 5. Phase 2: 应用补丁 diff
|
|
823
|
+
for patch_data in patch_data_list:
|
|
824
|
+
ok, err = _apply_patch(sandbox, patch_data)
|
|
825
|
+
if not ok:
|
|
826
|
+
return False, f"补丁应用失败: {err}"
|
|
827
|
+
|
|
828
|
+
# 6. Phase 3 (Green): 执行修复后 repro,缺陷必须消除(返回码等于 after_exit)
|
|
829
|
+
for repro_file, _, after_exit in repro_paths:
|
|
830
|
+
rc, out = _run_sandbox_script(repro_file, cwd=sandbox, extra_pythonpath=extra_pythonpath)
|
|
831
|
+
if rc != after_exit:
|
|
832
|
+
return False, f"Repro 修复后验证失败 (缺陷未消除): 预期 exit {after_exit}, 实际 exit {rc}. 输出:\n{out}"
|
|
833
|
+
|
|
834
|
+
# 7. Phase 3 (Green): 执行回归测试,必须全部通过(返回码 0)
|
|
835
|
+
for test_file in test_paths:
|
|
836
|
+
rc, out = _run_sandbox_script(test_file, cwd=sandbox, extra_pythonpath=extra_pythonpath)
|
|
837
|
+
if rc != 0:
|
|
838
|
+
return False, f"回归测试执行失败: {test_file.name} 预期 exit 0, 实际 exit {rc}. 输出:\n{out}"
|
|
839
|
+
|
|
840
|
+
return True, "本地红绿受限回放通过 (Red-to-Green verified: repro 0->1, tests 0)"
|
|
841
|
+
|
|
842
|
+
|
|
843
|
+
def _zip_package(package: Path) -> bytes:
|
|
844
|
+
"""Create a deterministic, non-symlink ZIP for remote verification."""
|
|
845
|
+
output = io.BytesIO()
|
|
846
|
+
with zipfile.ZipFile(output, "w", compression=zipfile.ZIP_DEFLATED) as archive:
|
|
847
|
+
for path in sorted(package.rglob("*")):
|
|
848
|
+
if not path.is_file():
|
|
849
|
+
continue
|
|
850
|
+
if path.is_symlink():
|
|
851
|
+
raise CliError(f"远程补丁包不得包含 symlink: {path}")
|
|
852
|
+
relative = path.relative_to(package).as_posix()
|
|
853
|
+
archive.writestr(relative, path.read_bytes())
|
|
854
|
+
return output.getvalue()
|
|
855
|
+
|
|
856
|
+
|
|
857
|
+
def _remote_client(args: Any):
|
|
858
|
+
# 远程补丁验证走 core 的 CloudClient,与 cloud 命令一样必须先自举 core 到
|
|
859
|
+
# sys.path。缺这一步时,正常安装环境(解释器 >= 3.11,cli.py 顶部的兼容性
|
|
860
|
+
# 注入被跳过)会直接抛 ModuleNotFoundError,使 --submit/--status 全链路不可用。
|
|
861
|
+
_ensure_core_importable()
|
|
862
|
+
from core.cloud_sync.cloud_client import CloudClient, CloudCredentials
|
|
863
|
+
|
|
864
|
+
key = (getattr(args, "api_key", None) or
|
|
865
|
+
os.environ.get("BUGX_PATCH_VERIFICATION_API_KEY", "")).strip()
|
|
866
|
+
if not key:
|
|
867
|
+
raise CliError("远程补丁验证需要 BUGX_PATCH_VERIFICATION_API_KEY 或 --api-key")
|
|
868
|
+
return CloudClient(base_url=getattr(args, "base_url", None),
|
|
869
|
+
credentials=CloudCredentials(api_key=key))
|
|
870
|
+
|
|
871
|
+
|
|
872
|
+
def command_patch_forge(args: Any) -> int:
|
|
873
|
+
if args.status:
|
|
874
|
+
client = _remote_client(args)
|
|
875
|
+
result = client.get_patch_verification(args.status)
|
|
876
|
+
if args.json:
|
|
877
|
+
print(json.dumps(result.data, ensure_ascii=False, indent=2))
|
|
878
|
+
else:
|
|
879
|
+
data = client._data(result)
|
|
880
|
+
print(f"verification_id: {args.status}")
|
|
881
|
+
print(f"status: {data.get('status', 'unknown')}")
|
|
882
|
+
print(f"decision: {data.get('decision', 'unknown')}")
|
|
883
|
+
return 0 if result.ok else 1
|
|
884
|
+
|
|
885
|
+
if args.verify:
|
|
886
|
+
package = Path(args.verify).expanduser().resolve()
|
|
887
|
+
if not package.is_dir():
|
|
888
|
+
raise CliError(f"补丁包目录不存在: {package}")
|
|
889
|
+
try:
|
|
890
|
+
manifest_path = _package_file(package, "manifest.json")
|
|
891
|
+
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
|
|
892
|
+
except (CliError, OSError, json.JSONDecodeError) as exc:
|
|
893
|
+
raise CliError(f"无法读取 manifest.json: {exc}") from exc
|
|
894
|
+
errors = validate_manifest(manifest, package)
|
|
895
|
+
red_to_green_status = "deferred"
|
|
896
|
+
red_to_green_detail = "execution_deferred: MVP does not execute package contents"
|
|
897
|
+
if not errors and getattr(args, "test_red_green", False):
|
|
898
|
+
root = Path(args.root).expanduser().resolve()
|
|
899
|
+
patch_data_list = [
|
|
900
|
+
_package_file(package, item["path"]).read_bytes()
|
|
901
|
+
for item in manifest.get("diff", {}).get("patch_files", [])
|
|
902
|
+
]
|
|
903
|
+
repro_items = [
|
|
904
|
+
(
|
|
905
|
+
item["path"],
|
|
906
|
+
item["before_exit"],
|
|
907
|
+
item["after_exit"],
|
|
908
|
+
_package_file(package, item["path"]).read_bytes(),
|
|
909
|
+
)
|
|
910
|
+
for item in manifest.get("repro", [])
|
|
911
|
+
]
|
|
912
|
+
test_items = [
|
|
913
|
+
(
|
|
914
|
+
item["path"],
|
|
915
|
+
_package_file(package, item["path"]).read_bytes(),
|
|
916
|
+
)
|
|
917
|
+
for item in manifest.get("tests", {}).get("new", [])
|
|
918
|
+
]
|
|
919
|
+
ok, msg = _execute_red_to_green(
|
|
920
|
+
root, manifest.get("diff", {}).get("files", []), patch_data_list, repro_items, test_items
|
|
921
|
+
)
|
|
922
|
+
if not ok:
|
|
923
|
+
errors.append(f"{_RED_GREEN_ERROR_PREFIX}{msg}")
|
|
924
|
+
red_to_green_status = "failed"
|
|
925
|
+
red_to_green_detail = msg
|
|
926
|
+
else:
|
|
927
|
+
red_to_green_status = "passed"
|
|
928
|
+
red_to_green_detail = msg
|
|
929
|
+
|
|
930
|
+
report = _verification_report(
|
|
931
|
+
manifest if isinstance(manifest, dict) else {},
|
|
932
|
+
errors,
|
|
933
|
+
red_to_green_status=red_to_green_status,
|
|
934
|
+
red_to_green_detail=red_to_green_detail,
|
|
935
|
+
)
|
|
936
|
+
_print_report(report, as_json=args.json)
|
|
937
|
+
return 0 if not errors else 1
|
|
938
|
+
|
|
939
|
+
root = Path(args.root).expanduser().resolve()
|
|
940
|
+
manifest, payloads = _build_package(root, args)
|
|
941
|
+
|
|
942
|
+
red_to_green_status = "deferred"
|
|
943
|
+
red_to_green_detail = "execution_deferred: MVP does not execute package contents"
|
|
944
|
+
if getattr(args, "test_red_green", False):
|
|
945
|
+
patch_data_list = [payloads[item["path"]] for item in manifest["diff"]["patch_files"]]
|
|
946
|
+
repro_items = [
|
|
947
|
+
(item["path"], item["before_exit"], item["after_exit"], payloads[item["path"]])
|
|
948
|
+
for item in manifest["repro"]
|
|
949
|
+
]
|
|
950
|
+
test_items = [
|
|
951
|
+
(item["path"], payloads[item["path"]])
|
|
952
|
+
for item in manifest["tests"]["new"]
|
|
953
|
+
]
|
|
954
|
+
ok, msg = _execute_red_to_green(root, manifest["diff"]["files"], patch_data_list, repro_items, test_items)
|
|
955
|
+
if not ok:
|
|
956
|
+
raise CliError(f"红绿闭环验证失败: {msg}")
|
|
957
|
+
red_to_green_status = "passed"
|
|
958
|
+
red_to_green_detail = msg
|
|
959
|
+
print(f"✓ {msg}")
|
|
960
|
+
|
|
961
|
+
if args.dry_run:
|
|
962
|
+
print(json.dumps(manifest, ensure_ascii=False, indent=2))
|
|
963
|
+
return 0
|
|
964
|
+
if not args.output:
|
|
965
|
+
raise CliError("非 dry-run 必须提供 --output")
|
|
966
|
+
output = Path(args.output).expanduser()
|
|
967
|
+
if not output.is_absolute():
|
|
968
|
+
output = root / output
|
|
969
|
+
output = output.resolve()
|
|
970
|
+
if output.exists():
|
|
971
|
+
raise CliError(f"输出目录已存在,拒绝覆盖: {output}")
|
|
972
|
+
output.parent.mkdir(parents=True, exist_ok=True)
|
|
973
|
+
temp = Path(tempfile.mkdtemp(prefix=".patch-forge-", dir=str(output.parent)))
|
|
974
|
+
try:
|
|
975
|
+
for relative, data in payloads.items():
|
|
976
|
+
target = temp / Path(*PurePosixPath(relative).parts)
|
|
977
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
978
|
+
target.write_bytes(data)
|
|
979
|
+
_write_json(temp / "manifest.json", manifest)
|
|
980
|
+
errors = validate_manifest(manifest, temp)
|
|
981
|
+
report = _verification_report(
|
|
982
|
+
manifest,
|
|
983
|
+
errors,
|
|
984
|
+
red_to_green_status=red_to_green_status,
|
|
985
|
+
red_to_green_detail=red_to_green_detail,
|
|
986
|
+
)
|
|
987
|
+
if errors:
|
|
988
|
+
raise CliError("生成的补丁包校验失败: " + "; ".join(errors))
|
|
989
|
+
_write_json(temp / "verification-report.json", report)
|
|
990
|
+
shutil.move(str(temp), str(output))
|
|
991
|
+
except Exception:
|
|
992
|
+
shutil.rmtree(temp, ignore_errors=True)
|
|
993
|
+
raise
|
|
994
|
+
print(f"✓ 补丁包已生成: {output}")
|
|
995
|
+
if not args.submit:
|
|
996
|
+
if red_to_green_status == "passed":
|
|
997
|
+
print(f" execution: verified-local ({red_to_green_detail})")
|
|
998
|
+
else:
|
|
999
|
+
print(" execution: deferred(未执行 repro/test,未提交 remote)")
|
|
1000
|
+
return 0
|
|
1001
|
+
|
|
1002
|
+
client = _remote_client(args)
|
|
1003
|
+
result = client.submit_patch_package(
|
|
1004
|
+
_zip_package(output), output.name + ".zip", source_commit=args.source_commit or "",
|
|
1005
|
+
)
|
|
1006
|
+
if args.json:
|
|
1007
|
+
print(json.dumps(result.data, ensure_ascii=False, indent=2))
|
|
1008
|
+
elif result.ok:
|
|
1009
|
+
data = client._data(result)
|
|
1010
|
+
print(f" remote verification_id: {data.get('verification_id', '')}")
|
|
1011
|
+
print(f" remote status: {data.get('status', 'unknown')}")
|
|
1012
|
+
else:
|
|
1013
|
+
print(f" remote submit failed: {result.error or result.data}")
|
|
1014
|
+
return 0 if result.ok else 1
|