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,1640 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""task_scheduler.py — 下一代智能任务调度与高并发弹性引擎 (DOC-044)。
|
|
3
|
+
|
|
4
|
+
核心能力:
|
|
5
|
+
1. UnitPriorityScheduler: 基于 DAG 拓扑前置、AST 变更波及面与历史缺陷密度的多因子加权优先级调度;
|
|
6
|
+
2. AffinityBundler: 同文件/强调用关系单元的拓扑亲和性聚合与批处理;
|
|
7
|
+
3. AdaptiveConcurrencyController: 以机器可承载并发为基线,仅在真实 CPU/RAM 压力下进行背压;
|
|
8
|
+
4. ComplexityLeaseCalculator: 复杂度自适应租约时长推算;
|
|
9
|
+
5. ZombieDetector: 基于本地子进程存活性与心跳断流的僵死 Worker 毫秒级抢占回收探针。
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import ast
|
|
15
|
+
import ctypes
|
|
16
|
+
import errno
|
|
17
|
+
import itertools
|
|
18
|
+
import json
|
|
19
|
+
import math
|
|
20
|
+
import os
|
|
21
|
+
import re
|
|
22
|
+
import shutil
|
|
23
|
+
import signal
|
|
24
|
+
import subprocess
|
|
25
|
+
import sys
|
|
26
|
+
import time
|
|
27
|
+
from collections import defaultdict, deque
|
|
28
|
+
from contextlib import contextmanager
|
|
29
|
+
from dataclasses import dataclass, field
|
|
30
|
+
from pathlib import Path
|
|
31
|
+
from typing import Any, Iterable, Mapping, Sequence, Iterator
|
|
32
|
+
|
|
33
|
+
from core.planning import unit_kind
|
|
34
|
+
|
|
35
|
+
SCHEMA_VERSION = 1
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
# ---------------------------------------------------------------------------
|
|
39
|
+
# 进程内共享调度器(DOC-140 调度提速)
|
|
40
|
+
# ---------------------------------------------------------------------------
|
|
41
|
+
# 调度器构造 = 全仓建图 + 影响网络 + 多个 JSON 工件加载,而无人值守的一轮
|
|
42
|
+
# 里它会被构造 2+N 次(workers() 两次 + 每个 worker turn 一次 + claim 兜底)。
|
|
43
|
+
# 同一 (root, HEAD, manifest mtime) 只构建一次;目标HEAD或清单变更即重建,
|
|
44
|
+
# 保证不会拿过期图做派发决策。
|
|
45
|
+
_SHARED_SCHEDULER_CACHE: dict[str, tuple[Any, str, float]] = {}
|
|
46
|
+
# C3:scheduler_history 临时文件唯一性计数器(配合 PID 防并发互踩)。
|
|
47
|
+
_TMP_COUNTER = itertools.count()
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _shared_cache_key_parts(root: Path) -> tuple[str, str]:
|
|
51
|
+
"""(清单内容 hash, 清单 mtime 兜底)。
|
|
52
|
+
|
|
53
|
+
A2:原键用 git HEAD——无人值守每轮 auto-fix 都会 commit,HEAD 必变,
|
|
54
|
+
缓存每轮失效、重付一次全仓索引(实测 5-8s)。而调度决策的真实输入是
|
|
55
|
+
覆盖清单的单元集合,与 HEAD 无关。改用清单内容 hash 做主键:内容不变
|
|
56
|
+
即命中(跨 commit 稳定),内容变才失效。mtime 仅作 hash 计算失败时的
|
|
57
|
+
兜底,不参与正常判定。
|
|
58
|
+
"""
|
|
59
|
+
try:
|
|
60
|
+
import hashlib as _hl
|
|
61
|
+
from core.coverage import module_coverage as _mc
|
|
62
|
+
manifest = _mc.default_manifest_for_root(root)
|
|
63
|
+
if manifest.is_file():
|
|
64
|
+
data = manifest.read_bytes()
|
|
65
|
+
return _hl.sha256(data).hexdigest()[:16], str(manifest.stat().st_mtime)
|
|
66
|
+
except Exception:
|
|
67
|
+
pass
|
|
68
|
+
return "", "0"
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def shared_scheduler(root: Path | str | None = None, **kwargs: Any) -> "UnitPriorityScheduler":
|
|
72
|
+
"""返回进程内共享调度器;策略输入变化时安全失效,避免重复全仓建图。"""
|
|
73
|
+
key_root = str(Path(root).resolve()) if root else ""
|
|
74
|
+
digest, mtime = _shared_cache_key_parts(Path(key_root)) if key_root else ("", "0")
|
|
75
|
+
# unit_risks/surfaces/traversal strategy 都影响排序,必须进入 cache key。
|
|
76
|
+
import hashlib as _hl, json as _json
|
|
77
|
+
strategy_key = _hl.sha256(_json.dumps(kwargs, ensure_ascii=False, sort_keys=True, default=str).encode()).hexdigest()[:16]
|
|
78
|
+
key = key_root + "|" + strategy_key
|
|
79
|
+
cached = _SHARED_SCHEDULER_CACHE.get(key)
|
|
80
|
+
if cached is not None:
|
|
81
|
+
scheduler, cached_digest, cached_mtime = cached
|
|
82
|
+
if cached_digest == digest and cached_mtime == mtime:
|
|
83
|
+
return scheduler
|
|
84
|
+
scheduler = UnitPriorityScheduler(root, **kwargs)
|
|
85
|
+
if key_root:
|
|
86
|
+
_SHARED_SCHEDULER_CACHE[key] = (scheduler, digest, mtime)
|
|
87
|
+
return scheduler
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def reset_shared_scheduler(root: Path | str | None = None) -> None:
|
|
91
|
+
"""清空共享缓存(测试或目标切换后用)。"""
|
|
92
|
+
if root is None:
|
|
93
|
+
_SHARED_SCHEDULER_CACHE.clear()
|
|
94
|
+
return
|
|
95
|
+
prefix = str(Path(root).resolve()) + "|"
|
|
96
|
+
for cache_key in tuple(_SHARED_SCHEDULER_CACHE):
|
|
97
|
+
if cache_key == str(Path(root).resolve()) or cache_key.startswith(prefix):
|
|
98
|
+
_SHARED_SCHEDULER_CACHE.pop(cache_key, None)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
# 命令行中出现的 BugX Worker 标志。用于在终止进程前独立证明「这确实是一个
|
|
103
|
+
# BugX Worker」——Worker 可以自报任意 PID,但无法让无关进程的命令行出现这些
|
|
104
|
+
# 标志。刻意使用小写比较(调用方先 casefold)。
|
|
105
|
+
WORKER_CMDLINE_MARKERS = (
|
|
106
|
+
"bugx-worker", "bugx_worker", "--agent bugx", "bugx-worker.md",
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
TRAVERSAL_STRATEGIES = frozenset({"auto", "dfs", "bfs", "hybrid"})
|
|
110
|
+
|
|
111
|
+
#: 推荐租约的硬上限(LOG-06)。必须与以下两处逐字一致:
|
|
112
|
+
#: * ``supervisor_models.MAX_LEASE_SECONDS``(核心侧接受上限);
|
|
113
|
+
#: * ``bugx_mcp_server`` 的 ``lease_seconds.inputSchema.maximum``。
|
|
114
|
+
#: 三处漂移会让「推荐值」与「接受上限」脱节:调用方按推荐值申请却拿到更长的
|
|
115
|
+
#: 租约,或反之。一致性契约以本注释为准。
|
|
116
|
+
LEASE_SECONDS_CEILING = 3600.0
|
|
117
|
+
_SENSITIVE_SURFACES = {
|
|
118
|
+
"auth": 3.0, "login": 3.0, "payment": 3.0, "billing": 3.0,
|
|
119
|
+
"file": 2.0, "upload": 2.0, "download": 2.0,
|
|
120
|
+
"rest": 2.0, "api": 2.0, "route": 2.0,
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def extract_unit_scope(unit_id: str) -> tuple[str, str]:
|
|
125
|
+
"""从 coverage unit ID 提取 (file_path, symbol)。
|
|
126
|
+
|
|
127
|
+
样例:
|
|
128
|
+
- "内部:1:core/foo.py::func_a" -> ("core/foo.py", "func_a")
|
|
129
|
+
- "内部:core/foo.py" -> ("core/foo.py", "")
|
|
130
|
+
- "业务:CheckoutFlow" -> ("CheckoutFlow", "")
|
|
131
|
+
"""
|
|
132
|
+
text = str(unit_id).strip()
|
|
133
|
+
for prefix in unit_kind.PREFIXES:
|
|
134
|
+
if text.startswith(prefix):
|
|
135
|
+
text = text[len(prefix):]
|
|
136
|
+
break
|
|
137
|
+
parts = text.split(":")
|
|
138
|
+
if len(parts) > 1 and parts[0].isdigit():
|
|
139
|
+
text = ":".join(parts[1:])
|
|
140
|
+
if "::" in text:
|
|
141
|
+
fp, sym = text.split("::", 1)
|
|
142
|
+
return fp.strip(), sym.strip()
|
|
143
|
+
return text.strip(), ""
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
# DOC-141:高危攻击面(命中即 deep)与高危路径词(语义等价信号)。
|
|
147
|
+
_HIGH_VALUE_SURFACES = {
|
|
148
|
+
"auth", "login", "payment", "billing", "admin", "rbac",
|
|
149
|
+
"token", "secret", "credential",
|
|
150
|
+
}
|
|
151
|
+
_HIGH_VALUE_PATH_TOKENS = (
|
|
152
|
+
"security", "inject", "sql", "query", "traversal", "escape",
|
|
153
|
+
"deserial", "exec", "upload", "download", "encrypt", "decrypt",
|
|
154
|
+
"crypto", "cipher", "key", "aes", "pem", "rsa", "ssh", "database", "db",
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
_TRIVIAL_ACCESSOR_SYMBOLS = frozenset({
|
|
158
|
+
"id", "name", "severity", "description", "reference", "fix_command", "fmt",
|
|
159
|
+
})
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _scope_tokens(value: str) -> set[str]:
|
|
163
|
+
"""Return exact path/symbol tokens, avoiding substring collisions."""
|
|
164
|
+
return set(re.findall(r"[a-z0-9]+", value.casefold()))
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def verification_tier(
|
|
168
|
+
unit_id: str,
|
|
169
|
+
risk_score: float = 0.0,
|
|
170
|
+
surfaces: Iterable[str] | None = None,
|
|
171
|
+
) -> str:
|
|
172
|
+
"""Map a unit to a bounded verification depth without changing coverage truth.
|
|
173
|
+
|
|
174
|
+
DOC-141 策略升级(面感感知):原策略只对 auth/login/payment/billing 四个
|
|
175
|
+
面给 deep,其余一律要 risk≥70。实测的漏报代价不对称——越权/注入/遍历类
|
|
176
|
+
面的中度风险单元(risk≥50)同样值得 deep:这些面的缺陷单点代价高,
|
|
177
|
+
浅验证的漏报成本远多于多花的验证 token。triage 侧语义不变。
|
|
178
|
+
"""
|
|
179
|
+
path, symbol = extract_unit_scope(unit_id)
|
|
180
|
+
normalized = path.casefold().replace("\\", "/")
|
|
181
|
+
symbol_normalized = re.sub(r"@l[0-9]+$", "", symbol.casefold().strip())
|
|
182
|
+
path_tokens = _scope_tokens(normalized)
|
|
183
|
+
symbol_tokens = _scope_tokens(symbol_normalized)
|
|
184
|
+
sensitive = {
|
|
185
|
+
key for key in _SENSITIVE_SURFACES
|
|
186
|
+
if key in path_tokens or key in symbol_tokens
|
|
187
|
+
}
|
|
188
|
+
# 高危面:命中即 deep(不限风险分)——这些面的存在本身就是强信号。
|
|
189
|
+
high_value = sensitive.intersection(_HIGH_VALUE_SURFACES)
|
|
190
|
+
# 语义面:路径里出现这些词同样按高危面处理(query/sql/inject/traversal…)。
|
|
191
|
+
semantic_hit = bool(
|
|
192
|
+
path_tokens.intersection(_HIGH_VALUE_PATH_TOKENS)
|
|
193
|
+
or symbol_tokens.intersection(_HIGH_VALUE_PATH_TOKENS)
|
|
194
|
+
)
|
|
195
|
+
try:
|
|
196
|
+
score = float(risk_score)
|
|
197
|
+
except (TypeError, ValueError):
|
|
198
|
+
score = 0.0
|
|
199
|
+
explicit_surfaces = {str(item).casefold() for item in (surfaces or ())}
|
|
200
|
+
if score >= 70.0 or explicit_surfaces.intersection(_HIGH_VALUE_SURFACES):
|
|
201
|
+
return "deep"
|
|
202
|
+
if symbol_normalized in _TRIVIAL_ACCESSOR_SYMBOLS:
|
|
203
|
+
return "triage"
|
|
204
|
+
if score >= 70.0 or high_value or semantic_hit:
|
|
205
|
+
return "deep"
|
|
206
|
+
if score >= 50.0 and sensitive:
|
|
207
|
+
# 中度风险 + 任一敏感面:deep 的期望收益高于 token 成本。
|
|
208
|
+
return "deep"
|
|
209
|
+
if score < 30.0 and not sensitive:
|
|
210
|
+
return "triage"
|
|
211
|
+
return "standard"
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
class UnitPriorityScheduler:
|
|
215
|
+
"""DAG 拓扑感知、遍历策略与缺陷密度驱动的智能优先级调度器。"""
|
|
216
|
+
|
|
217
|
+
def __init__(
|
|
218
|
+
self,
|
|
219
|
+
root: Path | str | None = None,
|
|
220
|
+
*,
|
|
221
|
+
project_root: Path | str | None = None,
|
|
222
|
+
graph: dict[str, Any] | None = None,
|
|
223
|
+
impact_network: dict[str, Any] | None = None,
|
|
224
|
+
defect_modules: set[str] | None = None,
|
|
225
|
+
unit_risks: Mapping[str, float] | None = None,
|
|
226
|
+
traversal_strategy: str = "auto",
|
|
227
|
+
surfaces: Iterable[str] | None = None,
|
|
228
|
+
**kwargs: Any,
|
|
229
|
+
) -> None:
|
|
230
|
+
target_root = project_root if project_root is not None else root
|
|
231
|
+
self.root = Path(target_root).resolve() if target_root else None
|
|
232
|
+
self.traversal_strategy = self._normalize_traversal_strategy(traversal_strategy)
|
|
233
|
+
self.last_strategy_info: dict[str, Any] = {}
|
|
234
|
+
self.in_degrees: dict[str, int] = defaultdict(int)
|
|
235
|
+
self.adjacency: dict[str, set[str]] = defaultdict(set)
|
|
236
|
+
self.reverse_adjacency: dict[str, set[str]] = defaultdict(set)
|
|
237
|
+
self.graph_nodes: set[str] = set()
|
|
238
|
+
self.graph_edge_count = 0
|
|
239
|
+
self.changed_files: set[str] = set()
|
|
240
|
+
self.impacted_files: set[str] = set()
|
|
241
|
+
self.defect_modules: set[str] = set(defect_modules or ())
|
|
242
|
+
self.unit_risks: dict[str, float] = dict(unit_risks or {})
|
|
243
|
+
self.surfaces: set[str] = {str(item).casefold() for item in (surfaces or ())}
|
|
244
|
+
self.dynamic_priorities: dict[str, float] = defaultdict(float)
|
|
245
|
+
# 调度热路径缓存(DOC-140 调度提速):score_unit 的 size_factor 只需
|
|
246
|
+
# 行数分档,按 fp 缓存避免 rank_units 内 2N 次整文件读;历史批量写
|
|
247
|
+
# 标记让一批 advance_cycle/record_audit_attempt 只落盘一次。
|
|
248
|
+
self._line_counts: dict[str, int] = {}
|
|
249
|
+
self._defer_save: int = 0
|
|
250
|
+
self._history_dirty: bool = False
|
|
251
|
+
|
|
252
|
+
if not self.unit_risks and self.root:
|
|
253
|
+
self._try_load_unit_risks()
|
|
254
|
+
|
|
255
|
+
if graph is not None:
|
|
256
|
+
self._load_graph(graph)
|
|
257
|
+
elif self.root:
|
|
258
|
+
self._try_load_project_graph()
|
|
259
|
+
|
|
260
|
+
if impact_network is not None:
|
|
261
|
+
self.changed_files = set(impact_network.get("changed_files", []))
|
|
262
|
+
self.impacted_files = set(impact_network.get("impacted_files", []))
|
|
263
|
+
elif self.root:
|
|
264
|
+
self._try_load_impact_network()
|
|
265
|
+
|
|
266
|
+
if self.root:
|
|
267
|
+
self._try_load_attack_graph()
|
|
268
|
+
|
|
269
|
+
# DOC-137 2.0 / D137-08: 基于 UCB1 多臂老虎机的探索与深度利用自适应平衡
|
|
270
|
+
self.enable_ucb1: bool = bool(kwargs.get("enable_ucb1", True))
|
|
271
|
+
self.ucb1_c: float = float(kwargs.get("ucb1_c", 40.0))
|
|
272
|
+
self.total_trials: int = 0
|
|
273
|
+
self.unit_trials: dict[str, int] = defaultdict(int)
|
|
274
|
+
self.unit_rewards: dict[str, float] = defaultdict(float)
|
|
275
|
+
self.unit_unpicked_cycles: dict[str, int] = defaultdict(int)
|
|
276
|
+
|
|
277
|
+
if self.root:
|
|
278
|
+
self._try_load_scheduler_history()
|
|
279
|
+
|
|
280
|
+
def _history_file_path(self) -> Path | None:
|
|
281
|
+
if not self.root:
|
|
282
|
+
return None
|
|
283
|
+
return self.root / ".bugx" / "state" / "scheduler_history.json"
|
|
284
|
+
|
|
285
|
+
def _try_load_scheduler_history(self) -> None:
|
|
286
|
+
path = self._history_file_path()
|
|
287
|
+
if not path or not path.is_file():
|
|
288
|
+
return
|
|
289
|
+
try:
|
|
290
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
291
|
+
self.total_trials = int(data.get("total_trials", 0))
|
|
292
|
+
for k, v in (data.get("unit_trials") or {}).items():
|
|
293
|
+
self.unit_trials[k] = int(v)
|
|
294
|
+
for k, v in (data.get("unit_rewards") or {}).items():
|
|
295
|
+
self.unit_rewards[k] = float(v)
|
|
296
|
+
for k, v in (data.get("unit_unpicked_cycles") or {}).items():
|
|
297
|
+
self.unit_unpicked_cycles[k] = int(v)
|
|
298
|
+
except Exception:
|
|
299
|
+
pass
|
|
300
|
+
|
|
301
|
+
def _source_line_count(self, fp: str) -> int | None:
|
|
302
|
+
"""源文件行数(按 fp 缓存;读失败返回 None 走默认分档)。"""
|
|
303
|
+
if fp in self._line_counts:
|
|
304
|
+
return self._line_counts[fp]
|
|
305
|
+
if not self.root:
|
|
306
|
+
return None
|
|
307
|
+
try:
|
|
308
|
+
lines = (self.root / fp).read_text(
|
|
309
|
+
encoding="utf-8", errors="ignore").count("\n")
|
|
310
|
+
except OSError:
|
|
311
|
+
return None
|
|
312
|
+
self._line_counts[fp] = lines
|
|
313
|
+
return lines
|
|
314
|
+
|
|
315
|
+
@contextmanager
|
|
316
|
+
def batch_history(self) -> Iterator[None]:
|
|
317
|
+
"""批量更新调度历史的上下文:期间的 save_history 只标记脏,
|
|
318
|
+
退出时统一落盘一次(把"每单元一次全量 JSON 写"降为"每批一次")。"""
|
|
319
|
+
self._defer_save += 1
|
|
320
|
+
try:
|
|
321
|
+
yield
|
|
322
|
+
finally:
|
|
323
|
+
self._defer_save = max(0, self._defer_save - 1)
|
|
324
|
+
if self._defer_save == 0 and self._history_dirty:
|
|
325
|
+
self._history_dirty = False
|
|
326
|
+
self.save_history()
|
|
327
|
+
|
|
328
|
+
def save_history(self) -> None:
|
|
329
|
+
path = self._history_file_path()
|
|
330
|
+
if not path:
|
|
331
|
+
return
|
|
332
|
+
if self._defer_save:
|
|
333
|
+
self._history_dirty = True
|
|
334
|
+
return
|
|
335
|
+
try:
|
|
336
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
337
|
+
payload = {
|
|
338
|
+
"schema_version": 1,
|
|
339
|
+
"total_trials": self.total_trials,
|
|
340
|
+
"unit_trials": dict(self.unit_trials),
|
|
341
|
+
"unit_rewards": dict(self.unit_rewards),
|
|
342
|
+
"unit_unpicked_cycles": dict(self.unit_unpicked_cycles),
|
|
343
|
+
"updated_at": time.time(),
|
|
344
|
+
}
|
|
345
|
+
# C3:唯一临时文件名。原固定 .tmp 在并发写下互相覆盖,可能把
|
|
346
|
+
# 半截内容 replace 上去(且被下方 except 静默吞掉)。
|
|
347
|
+
tmp = path.with_name(
|
|
348
|
+
f"{path.name}.{os.getpid()}.{next(_TMP_COUNTER)}.tmp"
|
|
349
|
+
)
|
|
350
|
+
tmp.write_text(json.dumps(payload, indent=2, ensure_ascii=False), encoding="utf-8")
|
|
351
|
+
tmp.replace(path)
|
|
352
|
+
except Exception:
|
|
353
|
+
pass
|
|
354
|
+
|
|
355
|
+
def advance_cycle(
|
|
356
|
+
self,
|
|
357
|
+
selected_unit_id: str | None = None,
|
|
358
|
+
candidate_units: Sequence[str] | None = None,
|
|
359
|
+
) -> None:
|
|
360
|
+
"""推进调度轮次:重置入选单元饥饿度,增加未入选候选单元饥饿度。"""
|
|
361
|
+
if candidate_units:
|
|
362
|
+
for u in candidate_units:
|
|
363
|
+
if u != selected_unit_id:
|
|
364
|
+
self.unit_unpicked_cycles[u] += 1
|
|
365
|
+
if selected_unit_id:
|
|
366
|
+
self.unit_unpicked_cycles[selected_unit_id] = 0
|
|
367
|
+
self.save_history()
|
|
368
|
+
|
|
369
|
+
def _attack_graph_snapshot_path(self) -> Path | None:
|
|
370
|
+
"""生产者(attack_graph_store)实际输出的攻击图快照路径。"""
|
|
371
|
+
if not self.root:
|
|
372
|
+
return None
|
|
373
|
+
try:
|
|
374
|
+
import core.bugx_paths as bugx_paths
|
|
375
|
+
scope = bugx_paths.require(self.root)
|
|
376
|
+
candidate = scope.polling_root / "attack-graph-snapshot.json"
|
|
377
|
+
return candidate if candidate.is_file() else None
|
|
378
|
+
except Exception:
|
|
379
|
+
return None
|
|
380
|
+
|
|
381
|
+
def _try_load_attack_graph(self) -> None:
|
|
382
|
+
"""DOC-137 / D137-03: 从动态攻击面图谱中提取利用链出度,动态衍生下游关联单元优先级。"""
|
|
383
|
+
if not self.root:
|
|
384
|
+
return
|
|
385
|
+
try:
|
|
386
|
+
# DOC-141 L2:读取路径必须对齐**生产者**的实际输出。生产者
|
|
387
|
+
# (attack_graph_store.save_graph)写 ``polling_root/attack-graph-snapshot.json``,
|
|
388
|
+
# 而原实现只找 .bugx/knowledge/attack-graph.json 与
|
|
389
|
+
# .bugx/pollings/*/state/attack-graph.json——两条路都接不上,
|
|
390
|
+
# 高危边动态加权(+25/边)从未生效。现在以生产者路径为主,
|
|
391
|
+
# 旧路径保留为兼容回退。
|
|
392
|
+
ag_path = self._attack_graph_snapshot_path()
|
|
393
|
+
if ag_path is None or not ag_path.is_file():
|
|
394
|
+
legacy = self.root / ".bugx" / "knowledge" / "attack-graph.json"
|
|
395
|
+
if legacy.is_file():
|
|
396
|
+
ag_path = legacy
|
|
397
|
+
if not ag_path.is_file():
|
|
398
|
+
candidates = sorted(self.root.glob(".bugx/pollings/*/state/attack-graph.json"), reverse=True)
|
|
399
|
+
if candidates:
|
|
400
|
+
ag_path = candidates[0]
|
|
401
|
+
if ag_path.is_file():
|
|
402
|
+
raw = json.loads(ag_path.read_text(encoding="utf-8"))
|
|
403
|
+
edges = raw.get("edges", []) if isinstance(raw, dict) else []
|
|
404
|
+
for edge in edges:
|
|
405
|
+
if not isinstance(edge, dict):
|
|
406
|
+
continue
|
|
407
|
+
rel = str(edge.get("relation", "")).upper()
|
|
408
|
+
if any(marker in rel for marker in ("EXPLOITED", "UNAUTHORIZED", "IDOR", "ESCALATION", "UNAUTHENTICATED")):
|
|
409
|
+
target = edge.get("to") or edge.get("target")
|
|
410
|
+
target_file = self._graph_file_scope(target)
|
|
411
|
+
if target_file:
|
|
412
|
+
self.dynamic_priorities[target_file] += 25.0
|
|
413
|
+
except Exception:
|
|
414
|
+
pass
|
|
415
|
+
|
|
416
|
+
def _try_load_unit_risks(self) -> None:
|
|
417
|
+
"""从项目已持久化的 project-profile.json 与 AI 语义侦察成果自动提取风险评分映射 (DOC-060, DOC-241)。"""
|
|
418
|
+
if not self.root:
|
|
419
|
+
return
|
|
420
|
+
try:
|
|
421
|
+
profile_path = self.root / ".bugx" / "knowledge" / "project-profile.json"
|
|
422
|
+
if profile_path.is_file():
|
|
423
|
+
import json
|
|
424
|
+
data = json.loads(profile_path.read_text(encoding="utf-8"))
|
|
425
|
+
if isinstance(data, dict):
|
|
426
|
+
risk_metrics = data.get("risk_metrics") or {}
|
|
427
|
+
for hotspot in risk_metrics.get("top_risk_hotspots") or []:
|
|
428
|
+
if isinstance(hotspot, dict) and "file" in hotspot:
|
|
429
|
+
self.unit_risks[str(hotspot["file"])] = float(hotspot.get("risk_score", 50.0))
|
|
430
|
+
except Exception:
|
|
431
|
+
pass
|
|
432
|
+
# DOC-241: 结合攻击图谱 AI 假说与语义审查重点焦点 (Priority Focus) 优先置顶
|
|
433
|
+
try:
|
|
434
|
+
from core.autonomous_cve import attack_graph_store
|
|
435
|
+
for hypo in attack_graph_store.get_hypotheses(self.root):
|
|
436
|
+
src = hypo.get("source_file") or hypo.get("target")
|
|
437
|
+
if src:
|
|
438
|
+
self.unit_risks[str(src)] = max(self.unit_risks.get(str(src), 0.0), 90.0)
|
|
439
|
+
except Exception:
|
|
440
|
+
pass
|
|
441
|
+
try:
|
|
442
|
+
rev_file = self.root / ".bugx" / "state" / "l1-semantic-review.json"
|
|
443
|
+
if rev_file.is_file():
|
|
444
|
+
import json
|
|
445
|
+
rev_data = json.loads(rev_file.read_text(encoding="utf-8"))
|
|
446
|
+
p_focus = (rev_data.get("audit_strategy_verdict") or {}).get("priority_focus") or []
|
|
447
|
+
for pf in p_focus:
|
|
448
|
+
if pf:
|
|
449
|
+
self.unit_risks[str(pf)] = max(self.unit_risks.get(str(pf), 0.0), 95.0)
|
|
450
|
+
except Exception:
|
|
451
|
+
pass
|
|
452
|
+
|
|
453
|
+
@staticmethod
|
|
454
|
+
def _normalize_traversal_strategy(value: str | None) -> str:
|
|
455
|
+
strategy = str(value or "auto").strip().lower()
|
|
456
|
+
return strategy if strategy in TRAVERSAL_STRATEGIES else "auto"
|
|
457
|
+
|
|
458
|
+
@staticmethod
|
|
459
|
+
def _graph_file_scope(value: object) -> str:
|
|
460
|
+
clean = str(value or "").strip()
|
|
461
|
+
for prefix in ("file:", "symbol:"):
|
|
462
|
+
if clean.startswith(prefix):
|
|
463
|
+
clean = clean[len(prefix):]
|
|
464
|
+
break
|
|
465
|
+
return clean.split("::", 1)[0].strip()
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+
def _load_graph(self, graph: dict[str, Any]) -> None:
|
|
469
|
+
edges = graph.get("edges", [])
|
|
470
|
+
for edge in edges:
|
|
471
|
+
if not isinstance(edge, dict):
|
|
472
|
+
continue
|
|
473
|
+
source = edge.get("source") or edge.get("from")
|
|
474
|
+
target = edge.get("target") or edge.get("to")
|
|
475
|
+
if target:
|
|
476
|
+
clean_target = str(target)
|
|
477
|
+
for prefix in ("file:", "symbol:"):
|
|
478
|
+
if clean_target.startswith(prefix):
|
|
479
|
+
clean_target = clean_target[len(prefix):]
|
|
480
|
+
break
|
|
481
|
+
fp = clean_target.split("::")[0]
|
|
482
|
+
self.in_degrees[fp] += 1
|
|
483
|
+
self.in_degrees[clean_target] += 1
|
|
484
|
+
source_scope = self._graph_file_scope(source)
|
|
485
|
+
target_scope = self._graph_file_scope(target)
|
|
486
|
+
if not source_scope or not target_scope or source_scope == target_scope:
|
|
487
|
+
continue
|
|
488
|
+
self.graph_nodes.update((source_scope, target_scope))
|
|
489
|
+
if target_scope not in self.adjacency[source_scope]:
|
|
490
|
+
self.adjacency[source_scope].add(target_scope)
|
|
491
|
+
self.reverse_adjacency[target_scope].add(source_scope)
|
|
492
|
+
self.graph_edge_count += 1
|
|
493
|
+
|
|
494
|
+
def _risk_for_unit(
|
|
495
|
+
self,
|
|
496
|
+
unit_id: str,
|
|
497
|
+
risks: Mapping[str, float],
|
|
498
|
+
) -> float:
|
|
499
|
+
# DOC-141 提速:O(1) 精确键优先; miss 时按长度降序找匹配——
|
|
500
|
+
# 原实现对每个未命中单元线性扫描整张风险表(O(N·R))。
|
|
501
|
+
fp, _ = extract_unit_scope(unit_id)
|
|
502
|
+
value = risks.get(unit_id, risks.get(fp))
|
|
503
|
+
if value is None and risks:
|
|
504
|
+
cached_sorted = getattr(self, "_cached_sorted_risks", None)
|
|
505
|
+
if (
|
|
506
|
+
cached_sorted is None
|
|
507
|
+
or cached_sorted[0] != id(risks)
|
|
508
|
+
or len(cached_sorted[1]) != len(risks)
|
|
509
|
+
):
|
|
510
|
+
sorted_keys = [k for k in sorted(risks, key=len, reverse=True) if k]
|
|
511
|
+
self._cached_sorted_risks = (id(risks), sorted_keys)
|
|
512
|
+
else:
|
|
513
|
+
sorted_keys = cached_sorted[1]
|
|
514
|
+
for risk_path in sorted_keys:
|
|
515
|
+
if risk_path == fp or fp.endswith(risk_path) or risk_path.endswith(fp):
|
|
516
|
+
value = risks[risk_path]
|
|
517
|
+
break
|
|
518
|
+
try:
|
|
519
|
+
return max(float(value or 0.0), 0.0)
|
|
520
|
+
except (TypeError, ValueError):
|
|
521
|
+
return 0.0
|
|
522
|
+
|
|
523
|
+
def _graph_traversal(self, risks: Mapping[str, float]) -> dict[str, Any]:
|
|
524
|
+
"""生成确定性的图遍历顺序及深度/层宽指标。"""
|
|
525
|
+
if not self.graph_nodes:
|
|
526
|
+
return {
|
|
527
|
+
"order": [], "dfs_order": [], "depths": {}, "max_depth": 0,
|
|
528
|
+
"max_frontier": 0, "avg_out_degree": 0.0,
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
def node_key(node: str) -> tuple[float, str]:
|
|
532
|
+
return (-self._risk_for_unit(node, risks), node)
|
|
533
|
+
|
|
534
|
+
roots = sorted(
|
|
535
|
+
(node for node in self.graph_nodes if not self.reverse_adjacency.get(node)),
|
|
536
|
+
key=node_key,
|
|
537
|
+
)
|
|
538
|
+
if not roots:
|
|
539
|
+
roots = sorted(self.graph_nodes, key=node_key)
|
|
540
|
+
|
|
541
|
+
order: list[str] = []
|
|
542
|
+
depths: dict[str, int] = {}
|
|
543
|
+
seen: set[str] = set()
|
|
544
|
+
frontier_widths: dict[int, int] = defaultdict(int)
|
|
545
|
+
|
|
546
|
+
queue: deque[tuple[str, int]] = deque((root, 0) for root in roots)
|
|
547
|
+
while queue:
|
|
548
|
+
node, depth = queue.popleft()
|
|
549
|
+
if node in seen:
|
|
550
|
+
continue
|
|
551
|
+
seen.add(node)
|
|
552
|
+
order.append(node)
|
|
553
|
+
depths[node] = depth
|
|
554
|
+
frontier_widths[depth] += 1
|
|
555
|
+
for child in sorted(self.adjacency.get(node, ()), key=node_key):
|
|
556
|
+
if child not in seen:
|
|
557
|
+
queue.append((child, depth + 1))
|
|
558
|
+
|
|
559
|
+
for node in sorted(self.graph_nodes - seen, key=node_key):
|
|
560
|
+
order.append(node)
|
|
561
|
+
depths[node] = 0
|
|
562
|
+
frontier_widths[0] += 1
|
|
563
|
+
|
|
564
|
+
dfs_order: list[str] = []
|
|
565
|
+
dfs_seen: set[str] = set()
|
|
566
|
+
stack = list(reversed(roots))
|
|
567
|
+
while stack:
|
|
568
|
+
node = stack.pop()
|
|
569
|
+
if node in dfs_seen:
|
|
570
|
+
continue
|
|
571
|
+
dfs_seen.add(node)
|
|
572
|
+
dfs_order.append(node)
|
|
573
|
+
children = sorted(self.adjacency.get(node, ()), key=node_key)
|
|
574
|
+
stack.extend(reversed(children))
|
|
575
|
+
stack.extend(sorted(self.graph_nodes - dfs_seen, key=node_key, reverse=True))
|
|
576
|
+
while stack:
|
|
577
|
+
node = stack.pop()
|
|
578
|
+
if node in dfs_seen:
|
|
579
|
+
continue
|
|
580
|
+
dfs_seen.add(node)
|
|
581
|
+
dfs_order.append(node)
|
|
582
|
+
stack.extend(reversed(sorted(self.adjacency.get(node, ()), key=node_key)))
|
|
583
|
+
|
|
584
|
+
return {
|
|
585
|
+
"order": order,
|
|
586
|
+
"dfs_order": dfs_order,
|
|
587
|
+
"depths": depths,
|
|
588
|
+
"max_depth": max(depths.values(), default=0),
|
|
589
|
+
"max_frontier": max(frontier_widths.values(), default=0),
|
|
590
|
+
"avg_out_degree": self.graph_edge_count / max(len(self.graph_nodes), 1),
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
def _select_traversal_strategy(
|
|
594
|
+
self,
|
|
595
|
+
units: Sequence[str],
|
|
596
|
+
risks: Mapping[str, float],
|
|
597
|
+
) -> tuple[str, str, dict[str, Any]]:
|
|
598
|
+
traversal = self._graph_traversal(risks)
|
|
599
|
+
candidate_nodes = {
|
|
600
|
+
extract_unit_scope(unit)[0]
|
|
601
|
+
for unit in units
|
|
602
|
+
if extract_unit_scope(unit)[0] in self.graph_nodes
|
|
603
|
+
}
|
|
604
|
+
risk_values = [self._risk_for_unit(unit, risks) for unit in units]
|
|
605
|
+
risk_total = sum(risk_values)
|
|
606
|
+
risk_concentration = max(risk_values, default=0.0) / risk_total if risk_total else 0.0
|
|
607
|
+
metrics = {
|
|
608
|
+
"graph_nodes": len(self.graph_nodes),
|
|
609
|
+
"graph_edges": self.graph_edge_count,
|
|
610
|
+
"candidate_graph_nodes": len(candidate_nodes),
|
|
611
|
+
"max_depth": traversal["max_depth"],
|
|
612
|
+
"max_frontier": traversal["max_frontier"],
|
|
613
|
+
"avg_out_degree": traversal["avg_out_degree"],
|
|
614
|
+
"risk_concentration": risk_concentration,
|
|
615
|
+
"order": traversal["order"],
|
|
616
|
+
"depths": traversal["depths"],
|
|
617
|
+
}
|
|
618
|
+
if self.traversal_strategy != "auto":
|
|
619
|
+
strategy = self.traversal_strategy
|
|
620
|
+
metrics["order"] = traversal["dfs_order"] if strategy == "dfs" else traversal["order"]
|
|
621
|
+
return strategy, f"显式指定 {strategy}", metrics
|
|
622
|
+
if len(candidate_nodes) < 3 or self.graph_edge_count < 2:
|
|
623
|
+
return "hybrid", "图规模不足,保留风险与评分排序", metrics
|
|
624
|
+
if (
|
|
625
|
+
traversal["max_depth"] >= 4
|
|
626
|
+
and (
|
|
627
|
+
traversal["max_depth"] >= 2 * max(traversal["max_frontier"], 1)
|
|
628
|
+
or risk_concentration >= 0.45
|
|
629
|
+
)
|
|
630
|
+
):
|
|
631
|
+
metrics["order"] = traversal["dfs_order"]
|
|
632
|
+
return "dfs", "图较深或风险集中,优先沿依赖链深入", metrics
|
|
633
|
+
if traversal["max_frontier"] >= 3 or traversal["avg_out_degree"] >= 1.75:
|
|
634
|
+
return "bfs", "图层较宽,优先铺开同层单元", metrics
|
|
635
|
+
return "hybrid", "深度与层宽均衡,混合风险和遍历顺序", metrics
|
|
636
|
+
|
|
637
|
+
def strategy_info(
|
|
638
|
+
self,
|
|
639
|
+
units: Sequence[str],
|
|
640
|
+
unit_risks: Mapping[str, float] | None = None,
|
|
641
|
+
) -> dict[str, Any]:
|
|
642
|
+
"""返回本批次自动选择的遍历策略及可观测指标。"""
|
|
643
|
+
risks = dict(self.unit_risks)
|
|
644
|
+
if unit_risks:
|
|
645
|
+
risks.update(unit_risks)
|
|
646
|
+
strategy, reason, metrics = self._select_traversal_strategy(units, risks)
|
|
647
|
+
info = {"strategy": strategy, "reason": reason, **metrics}
|
|
648
|
+
self.last_strategy_info = info
|
|
649
|
+
return info
|
|
650
|
+
|
|
651
|
+
def _try_load_project_graph(self) -> None:
|
|
652
|
+
if not self.root:
|
|
653
|
+
return
|
|
654
|
+
try:
|
|
655
|
+
from core.runtime import project_graph
|
|
656
|
+
g = project_graph.build_graph(self.root)
|
|
657
|
+
self._load_graph(g)
|
|
658
|
+
except Exception:
|
|
659
|
+
pass
|
|
660
|
+
|
|
661
|
+
def _try_load_impact_network(self) -> None:
|
|
662
|
+
if not self.root:
|
|
663
|
+
return
|
|
664
|
+
try:
|
|
665
|
+
from core.planning import impact_pruner
|
|
666
|
+
net = impact_pruner.compute_impact_network(self.root, depth=2)
|
|
667
|
+
self.changed_files = set(net.get("changed_files", []))
|
|
668
|
+
self.impacted_files = set(net.get("impacted_files", []))
|
|
669
|
+
except Exception:
|
|
670
|
+
pass
|
|
671
|
+
|
|
672
|
+
def record_defect(self, unit_id: str, severity: str = "HIGH") -> None:
|
|
673
|
+
"""记录缺陷反馈,动态提高该单元及其关联依赖的调度权重。"""
|
|
674
|
+
fp, _ = extract_unit_scope(unit_id)
|
|
675
|
+
self.defect_modules.add(fp)
|
|
676
|
+
bonus = 150.0 if severity.upper() in {"CRITICAL", "HIGH"} else 60.0
|
|
677
|
+
self.dynamic_priorities[unit_id] += bonus
|
|
678
|
+
self.dynamic_priorities[fp] += bonus
|
|
679
|
+
|
|
680
|
+
# 联动 UCB1 多臂老虎机回报累积
|
|
681
|
+
reward = 3.0 if severity.upper() in {"CRITICAL", "HIGH"} else 1.0
|
|
682
|
+
self.unit_rewards[unit_id] += reward
|
|
683
|
+
if fp != unit_id:
|
|
684
|
+
self.unit_rewards[fp] += reward
|
|
685
|
+
|
|
686
|
+
def record_audit_attempt(
|
|
687
|
+
self,
|
|
688
|
+
unit_id: str,
|
|
689
|
+
reward: float = 0.0,
|
|
690
|
+
findings_count: int = 0,
|
|
691
|
+
) -> None:
|
|
692
|
+
"""DOC-137 2.0 / D137-08: 记录一次审计派发与探索尝试,更新 UCB1 臂拉动次数与回报,并重置 Aging 周期。"""
|
|
693
|
+
self.total_trials += 1
|
|
694
|
+
self.unit_trials[unit_id] += 1
|
|
695
|
+
self.unit_unpicked_cycles[unit_id] = 0
|
|
696
|
+
effective_reward = reward if reward > 0.0 else float(findings_count)
|
|
697
|
+
fp, _ = extract_unit_scope(unit_id)
|
|
698
|
+
if fp != unit_id:
|
|
699
|
+
self.unit_trials[fp] += 1
|
|
700
|
+
self.unit_unpicked_cycles[fp] = 0
|
|
701
|
+
if effective_reward > 0.0:
|
|
702
|
+
self.unit_rewards[unit_id] += effective_reward
|
|
703
|
+
if fp != unit_id:
|
|
704
|
+
self.unit_rewards[fp] += effective_reward
|
|
705
|
+
if self.root:
|
|
706
|
+
self.save_history()
|
|
707
|
+
|
|
708
|
+
def score_unit(
|
|
709
|
+
self,
|
|
710
|
+
unit_id: str,
|
|
711
|
+
coverage_status: str = "pending",
|
|
712
|
+
risk_score: float | None = None,
|
|
713
|
+
) -> float:
|
|
714
|
+
"""计算单元综合优先级得分(得分越高越优先出队)。"""
|
|
715
|
+
score = 0.0
|
|
716
|
+
# 1. 阶段绝对硬边界:内部优先于业务
|
|
717
|
+
if unit_kind.is_internal(unit_id):
|
|
718
|
+
score += 1000.0
|
|
719
|
+
elif not unit_kind.is_business(unit_id):
|
|
720
|
+
score += 500.0
|
|
721
|
+
|
|
722
|
+
# 2. 债务重试加权:未完成债务优先于全新单元
|
|
723
|
+
if coverage_status in {"partial", "unverified", "stale", "blocked"}:
|
|
724
|
+
score += 50.0
|
|
725
|
+
|
|
726
|
+
fp, sym = extract_unit_scope(unit_id)
|
|
727
|
+
|
|
728
|
+
# 3. 拓扑依赖加权:入度越高说明越是公共基础库/被依赖核心
|
|
729
|
+
in_deg = self.in_degrees.get(fp, 0)
|
|
730
|
+
if sym:
|
|
731
|
+
in_deg = max(in_deg, self.in_degrees.get(f"{fp}::{sym}", 0))
|
|
732
|
+
score += min(in_deg, 20) * 5.0
|
|
733
|
+
|
|
734
|
+
# 4. AST 变更波及面加权
|
|
735
|
+
if fp in self.changed_files:
|
|
736
|
+
score += 200.0
|
|
737
|
+
elif fp in self.impacted_files:
|
|
738
|
+
score += 80.0
|
|
739
|
+
|
|
740
|
+
# 5. 历史缺陷聚集加权
|
|
741
|
+
if fp in self.defect_modules:
|
|
742
|
+
score += 100.0
|
|
743
|
+
|
|
744
|
+
# 6. 静态风险分数加权
|
|
745
|
+
r_score = risk_score
|
|
746
|
+
if r_score is None:
|
|
747
|
+
r_score = self._risk_for_unit(unit_id, self.unit_risks)
|
|
748
|
+
bounded_risk = min(max(float(r_score or 0.0), 0.0), 100.0)
|
|
749
|
+
surface_weight = max(
|
|
750
|
+
[_SENSITIVE_SURFACES[key] for key in _SENSITIVE_SURFACES
|
|
751
|
+
if key in fp.casefold()],
|
|
752
|
+
default=1.0,
|
|
753
|
+
)
|
|
754
|
+
size_factor = 1.0
|
|
755
|
+
if self.root:
|
|
756
|
+
# 行数按 fp 缓存:rank_units 对同一单元多次调用 score_unit,
|
|
757
|
+
# 整文件读只需首次发生一次。
|
|
758
|
+
lines = self._source_line_count(fp)
|
|
759
|
+
if lines is not None:
|
|
760
|
+
size_factor = 1.15 if lines > 800 else 1.05 if lines > 300 else 1.0
|
|
761
|
+
score += bounded_risk * surface_weight * size_factor * 1.5
|
|
762
|
+
|
|
763
|
+
# 7. 动态反馈加权 (自适应重规划抢跑)
|
|
764
|
+
score += self.dynamic_priorities.get(unit_id, self.dynamic_priorities.get(fp, 0.0))
|
|
765
|
+
|
|
766
|
+
# 7.1 DOC-138 / S2-11: 消费显式配置的目标 surfaces,对命中指定攻击面的单元加权
|
|
767
|
+
if self.surfaces:
|
|
768
|
+
fp_lower = fp.casefold()
|
|
769
|
+
sym_lower = (sym or "").casefold()
|
|
770
|
+
if any(s in fp_lower or s in sym_lower for s in self.surfaces):
|
|
771
|
+
score += 150.0
|
|
772
|
+
|
|
773
|
+
# 8. DOC-137 2.0 / D137-08: 基于 UCB1 多臂老虎机的探索与深度利用平衡加权
|
|
774
|
+
if self.enable_ucb1:
|
|
775
|
+
import math
|
|
776
|
+
n_u = self.unit_trials.get(unit_id, self.unit_trials.get(fp, 0))
|
|
777
|
+
r_u = self.unit_rewards.get(unit_id, self.unit_rewards.get(fp, 0.0))
|
|
778
|
+
exploitation = (r_u / (n_u + 1)) * 50.0
|
|
779
|
+
n_total = max(self.total_trials, 1)
|
|
780
|
+
exploration = self.ucb1_c * math.sqrt(2.0 * math.log(n_total + 1) / (n_u + 1))
|
|
781
|
+
score += exploitation + exploration
|
|
782
|
+
|
|
783
|
+
# 9. Aging 饥饿防御:未被调度轮次线性补偿,防止中低风险单元长期死锁
|
|
784
|
+
unpicked = self.unit_unpicked_cycles.get(unit_id, self.unit_unpicked_cycles.get(fp, 0))
|
|
785
|
+
score += min(unpicked * 15.0, 300.0)
|
|
786
|
+
|
|
787
|
+
return score
|
|
788
|
+
|
|
789
|
+
def rank_units(
|
|
790
|
+
self,
|
|
791
|
+
units: Sequence[str],
|
|
792
|
+
coverage: Mapping[str, str] | None = None,
|
|
793
|
+
unit_risks: Mapping[str, float] | None = None,
|
|
794
|
+
update_aging: bool = False,
|
|
795
|
+
) -> list[str]:
|
|
796
|
+
"""对候选单元进行稳定多因子与 DFS/BFS/Hybrid 优先级排序。"""
|
|
797
|
+
cov = coverage or {}
|
|
798
|
+
risks = dict(self.unit_risks)
|
|
799
|
+
if unit_risks:
|
|
800
|
+
risks.update(unit_risks)
|
|
801
|
+
info = self.strategy_info(units, unit_risks=risks)
|
|
802
|
+
traversal_order = {node: index for index, node in enumerate(info["order"])}
|
|
803
|
+
depths = info["depths"]
|
|
804
|
+
# DOC-141 提速:score_unit 每单元只算一次并复用——原实现在 scored
|
|
805
|
+
# 列表、traversal_key、hybrid 排序键里对同一单元重复调用(每次含
|
|
806
|
+
# 整文件行数读取),2N 次起。
|
|
807
|
+
score_by_unit = {
|
|
808
|
+
u: self.score_unit(
|
|
809
|
+
u, cov.get(u, "pending"),
|
|
810
|
+
risk_score=self._risk_for_unit(u, risks),
|
|
811
|
+
)
|
|
812
|
+
for u in units
|
|
813
|
+
}
|
|
814
|
+
scored = [(score_by_unit[u], u) for u in units]
|
|
815
|
+
fallback_rank = len(traversal_order)
|
|
816
|
+
|
|
817
|
+
def traversal_key(unit_id: str) -> tuple[int, int, float, str]:
|
|
818
|
+
fp, _ = extract_unit_scope(unit_id)
|
|
819
|
+
stage = 0 if unit_kind.is_internal(unit_id) else 1
|
|
820
|
+
return (
|
|
821
|
+
stage,
|
|
822
|
+
traversal_order.get(fp, fallback_rank),
|
|
823
|
+
-score_by_unit[unit_id],
|
|
824
|
+
unit_id in mismatched,
|
|
825
|
+
unit_id,
|
|
826
|
+
)
|
|
827
|
+
|
|
828
|
+
strategy = info["strategy"]
|
|
829
|
+
# 平台亲和:宿主无法验证的跨平台专属单元沉底,避免空转调度。
|
|
830
|
+
try:
|
|
831
|
+
from core.coverage import module_coverage as _mc
|
|
832
|
+
host = _mc.host_platform()
|
|
833
|
+
mismatched = {
|
|
834
|
+
u for u in units if (pu := _mc.unit_platform(u)) and pu != host
|
|
835
|
+
}
|
|
836
|
+
except Exception:
|
|
837
|
+
mismatched = set()
|
|
838
|
+
if strategy == "dfs":
|
|
839
|
+
scored.sort(key=lambda item: traversal_key(item[1]))
|
|
840
|
+
elif strategy == "bfs":
|
|
841
|
+
scored.sort(key=lambda item: (
|
|
842
|
+
0 if unit_kind.is_internal(item[1]) else 1,
|
|
843
|
+
depths.get(extract_unit_scope(item[1])[0], fallback_rank),
|
|
844
|
+
traversal_order.get(extract_unit_scope(item[1])[0], fallback_rank),
|
|
845
|
+
-item[0],
|
|
846
|
+
item[1],
|
|
847
|
+
))
|
|
848
|
+
else:
|
|
849
|
+
risk_values = [self._risk_for_unit(unit_id, risks) for _, unit_id in scored]
|
|
850
|
+
priority_values = risk_values if any(risk_values) else [score for score, _ in scored]
|
|
851
|
+
value_min = min(priority_values, default=0.0)
|
|
852
|
+
value_span = max(priority_values, default=0.0) - value_min
|
|
853
|
+
for index, (score, unit_id) in enumerate(scored):
|
|
854
|
+
fp, _ = extract_unit_scope(unit_id)
|
|
855
|
+
rank = traversal_order.get(fp, fallback_rank + index)
|
|
856
|
+
traversal_value = (
|
|
857
|
+
1.0 - rank / max(fallback_rank + len(scored) - 1, 1)
|
|
858
|
+
if traversal_order else 0.0
|
|
859
|
+
)
|
|
860
|
+
risk_value = (
|
|
861
|
+
(priority_values[index] - value_min) / value_span
|
|
862
|
+
if value_span else 0.0
|
|
863
|
+
)
|
|
864
|
+
scored[index] = (
|
|
865
|
+
0.6 * risk_value + 0.4 * traversal_value,
|
|
866
|
+
unit_id,
|
|
867
|
+
)
|
|
868
|
+
scored.sort(key=lambda item: (
|
|
869
|
+
0 if unit_kind.is_internal(item[1]) else 1,
|
|
870
|
+
-item[0],
|
|
871
|
+
-score_by_unit[item[1]],
|
|
872
|
+
item[1],
|
|
873
|
+
))
|
|
874
|
+
ranked = [u for _, u in scored]
|
|
875
|
+
if update_aging and ranked:
|
|
876
|
+
self.advance_cycle(selected_unit_id=ranked[0], candidate_units=ranked)
|
|
877
|
+
return ranked
|
|
878
|
+
|
|
879
|
+
|
|
880
|
+
|
|
881
|
+
class AffinityBundler:
|
|
882
|
+
"""拓扑内聚单元亲和性调度与打包器 (DOC-044)。"""
|
|
883
|
+
|
|
884
|
+
@staticmethod
|
|
885
|
+
def bundle_units(
|
|
886
|
+
units: Sequence[str],
|
|
887
|
+
max_bundle_size: int = 3,
|
|
888
|
+
) -> list[list[str]]:
|
|
889
|
+
"""将高内聚单元(同源码文件)聚合成任务包。
|
|
890
|
+
|
|
891
|
+
约束:
|
|
892
|
+
- 内部单元与业务单元绝不混包;
|
|
893
|
+
- 单包单元数量受限在 [1, max_bundle_size] (上限 5);
|
|
894
|
+
- 保持排序优先级:首个单元优先级最高的文件包先产出。
|
|
895
|
+
"""
|
|
896
|
+
limit = max(1, min(max_bundle_size, 5))
|
|
897
|
+
if limit == 1:
|
|
898
|
+
return [[u] for u in units]
|
|
899
|
+
|
|
900
|
+
# 区分阶段
|
|
901
|
+
internal_units = [u for u in units if unit_kind.is_internal(u)]
|
|
902
|
+
business_units = [u for u in units if not unit_kind.is_internal(u)]
|
|
903
|
+
|
|
904
|
+
bundles: list[list[str]] = []
|
|
905
|
+
|
|
906
|
+
for group in (internal_units, business_units):
|
|
907
|
+
if not group:
|
|
908
|
+
continue
|
|
909
|
+
# 按 file_path 聚合,同时记录首次出现的顺序
|
|
910
|
+
file_to_units: dict[str, list[str]] = defaultdict(list)
|
|
911
|
+
file_order: list[str] = []
|
|
912
|
+
for u in group:
|
|
913
|
+
fp, _ = extract_unit_scope(u)
|
|
914
|
+
if fp not in file_to_units:
|
|
915
|
+
file_order.append(fp)
|
|
916
|
+
file_to_units[fp].append(u)
|
|
917
|
+
|
|
918
|
+
# 组装 bundles
|
|
919
|
+
for fp in file_order:
|
|
920
|
+
u_list = file_to_units[fp]
|
|
921
|
+
for i in range(0, len(u_list), limit):
|
|
922
|
+
bundles.append(u_list[i:i + limit])
|
|
923
|
+
|
|
924
|
+
return bundles
|
|
925
|
+
|
|
926
|
+
@staticmethod
|
|
927
|
+
def rebalance_for_parallelism(
|
|
928
|
+
bundles: Sequence[Sequence[str]], desired_workers: int,
|
|
929
|
+
) -> list[list[str]]:
|
|
930
|
+
"""在亲和包不足以填满槽位时,安全退化为单元级 Bundle。"""
|
|
931
|
+
normalized = [list(bundle) for bundle in bundles if bundle]
|
|
932
|
+
if desired_workers <= len(normalized):
|
|
933
|
+
return normalized
|
|
934
|
+
# ponytail: only split when affinity would leave slots idle; keep the
|
|
935
|
+
# ordered units and existing resource isolation, no second packer.
|
|
936
|
+
return [[unit] for bundle in normalized for unit in bundle]
|
|
937
|
+
|
|
938
|
+
|
|
939
|
+
class AdaptiveConcurrencyController:
|
|
940
|
+
"""自适应弹性并发与背压调节引擎 (DOC-044)。"""
|
|
941
|
+
|
|
942
|
+
def __init__(
|
|
943
|
+
self,
|
|
944
|
+
min_concurrency: int = 2,
|
|
945
|
+
max_concurrency: int | None = None,
|
|
946
|
+
target_cpu_load: float = 0.85,
|
|
947
|
+
) -> None:
|
|
948
|
+
self.min_concurrency = max(1, min_concurrency)
|
|
949
|
+
if max_concurrency is None:
|
|
950
|
+
try:
|
|
951
|
+
from .supervisor_models import resolve_system_concurrency
|
|
952
|
+
_, default_ceil = resolve_system_concurrency()
|
|
953
|
+
except Exception:
|
|
954
|
+
default_ceil = 8
|
|
955
|
+
max_concurrency = default_ceil
|
|
956
|
+
self.max_concurrency = max(self.min_concurrency, max_concurrency)
|
|
957
|
+
self.target_cpu_load = target_cpu_load
|
|
958
|
+
self.concurrency_window: float = float(self.min_concurrency)
|
|
959
|
+
|
|
960
|
+
def get_system_pressure(self) -> float:
|
|
961
|
+
"""获取系统实时压力指数(0.0 ~ 2.0)。
|
|
962
|
+
|
|
963
|
+
Windows 无 os.getloadavg:用最近 1 秒忙进程计数 / 逻辑核数近似
|
|
964
|
+
(psutil 缺失时的轻量探针),避免恒定 0.5 伪值让 AIMD 永远按
|
|
965
|
+
半载决策。
|
|
966
|
+
"""
|
|
967
|
+
cores = os.cpu_count() or 1
|
|
968
|
+
try:
|
|
969
|
+
load1 = os.getloadavg()[0]
|
|
970
|
+
return max(0.0, float(load1) / float(cores))
|
|
971
|
+
except (AttributeError, OSError):
|
|
972
|
+
pass
|
|
973
|
+
try:
|
|
974
|
+
import ctypes
|
|
975
|
+
|
|
976
|
+
idle_time = ctypes.c_ulonglong()
|
|
977
|
+
kernel_times = ctypes.c_ulonglong()
|
|
978
|
+
user_times = ctypes.c_ulonglong()
|
|
979
|
+
|
|
980
|
+
class _FT(ctypes.Structure):
|
|
981
|
+
_fields_ = [("dwLowDateTime", ctypes.c_ulong),
|
|
982
|
+
("dwHighDateTime", ctypes.c_ulong)]
|
|
983
|
+
|
|
984
|
+
idle, kernel, user = _FT(), _FT(), _FT()
|
|
985
|
+
if not ctypes.windll.kernel32.GetSystemTimes(
|
|
986
|
+
ctypes.byref(idle), ctypes.byref(kernel), ctypes.byref(user),
|
|
987
|
+
):
|
|
988
|
+
return 0.5
|
|
989
|
+
|
|
990
|
+
def _u64(ft: "_FT") -> int:
|
|
991
|
+
return (ft.dwHighDateTime << 32) | ft.dwLowDateTime
|
|
992
|
+
|
|
993
|
+
total = (_u64(kernel) - _u64(idle)) + _u64(user)
|
|
994
|
+
busy = _u64(kernel) + _u64(user)
|
|
995
|
+
if total <= 0:
|
|
996
|
+
return 0.5
|
|
997
|
+
cpu_percent = min(100.0, busy / total * 100.0)
|
|
998
|
+
return max(0.0, cpu_percent / 100.0 / 1.0)
|
|
999
|
+
except Exception:
|
|
1000
|
+
return 0.5
|
|
1001
|
+
|
|
1002
|
+
def _get_system_load(self) -> tuple[float, float | None]:
|
|
1003
|
+
"""兼容接口:返回 (cpu_pressure, ram_usage_percent)。"""
|
|
1004
|
+
return self.get_system_pressure(), self.get_memory_pressure()
|
|
1005
|
+
|
|
1006
|
+
@staticmethod
|
|
1007
|
+
def get_memory_pressure() -> float | None:
|
|
1008
|
+
"""读取当前系统内存占用;探针不可用时返回 None。"""
|
|
1009
|
+
if sys.platform.startswith("linux"):
|
|
1010
|
+
try:
|
|
1011
|
+
values: dict[str, float] = {}
|
|
1012
|
+
for line in Path("/proc/meminfo").read_text(encoding="utf-8").splitlines():
|
|
1013
|
+
key, _, raw = line.partition(":")
|
|
1014
|
+
if key in {"MemTotal", "MemAvailable"}:
|
|
1015
|
+
values[key] = float(raw.strip().split()[0])
|
|
1016
|
+
total = values.get("MemTotal", 0.0)
|
|
1017
|
+
available = values.get("MemAvailable")
|
|
1018
|
+
if total > 0 and available is not None:
|
|
1019
|
+
return max(0.0, min(100.0, (1.0 - available / total) * 100.0))
|
|
1020
|
+
except (OSError, ValueError, IndexError):
|
|
1021
|
+
return None
|
|
1022
|
+
return None
|
|
1023
|
+
if sys.platform == "darwin":
|
|
1024
|
+
try:
|
|
1025
|
+
total = int(subprocess.run(
|
|
1026
|
+
["sysctl", "-n", "hw.memsize"],
|
|
1027
|
+
capture_output=True, text=True, check=False, timeout=2,
|
|
1028
|
+
).stdout.strip())
|
|
1029
|
+
output = subprocess.run(
|
|
1030
|
+
["vm_stat"], capture_output=True, text=True,
|
|
1031
|
+
check=False, timeout=2,
|
|
1032
|
+
).stdout
|
|
1033
|
+
page_match = re.search(r"page size of (\d+) bytes", output)
|
|
1034
|
+
if total <= 0 or not page_match:
|
|
1035
|
+
return None
|
|
1036
|
+
available_pages = 0
|
|
1037
|
+
for name in (
|
|
1038
|
+
"Pages free", "Pages inactive", "Pages speculative",
|
|
1039
|
+
"Pages purgeable", "File-backed pages",
|
|
1040
|
+
):
|
|
1041
|
+
match = re.search(rf"^{re.escape(name)}:\s+(\d+)", output, re.MULTILINE)
|
|
1042
|
+
if match:
|
|
1043
|
+
available_pages += int(match.group(1))
|
|
1044
|
+
available = available_pages * int(page_match.group(1))
|
|
1045
|
+
return max(0.0, min(100.0, (1.0 - available / total) * 100.0))
|
|
1046
|
+
except (OSError, ValueError, subprocess.SubprocessError):
|
|
1047
|
+
return None
|
|
1048
|
+
if os.name == "nt":
|
|
1049
|
+
try:
|
|
1050
|
+
class MemoryStatusEx(ctypes.Structure):
|
|
1051
|
+
_fields_ = [
|
|
1052
|
+
("dwLength", ctypes.c_ulong),
|
|
1053
|
+
("dwMemoryLoad", ctypes.c_ulong),
|
|
1054
|
+
("ullTotalPhys", ctypes.c_ulonglong),
|
|
1055
|
+
("ullAvailPhys", ctypes.c_ulonglong),
|
|
1056
|
+
("ullTotalPageFile", ctypes.c_ulonglong),
|
|
1057
|
+
("ullAvailPageFile", ctypes.c_ulonglong),
|
|
1058
|
+
("ullTotalVirtual", ctypes.c_ulonglong),
|
|
1059
|
+
("ullAvailVirtual", ctypes.c_ulonglong),
|
|
1060
|
+
("ullAvailExtendedVirtual", ctypes.c_ulonglong),
|
|
1061
|
+
]
|
|
1062
|
+
status = MemoryStatusEx()
|
|
1063
|
+
status.dwLength = ctypes.sizeof(MemoryStatusEx)
|
|
1064
|
+
if ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(status)):
|
|
1065
|
+
return float(status.dwMemoryLoad)
|
|
1066
|
+
except (AttributeError, OSError, TypeError, ValueError):
|
|
1067
|
+
return None
|
|
1068
|
+
return None
|
|
1069
|
+
|
|
1070
|
+
def compute_capacity(
|
|
1071
|
+
self,
|
|
1072
|
+
current_active: int,
|
|
1073
|
+
budget: Any,
|
|
1074
|
+
run_state: Any = None,
|
|
1075
|
+
state: Any = None,
|
|
1076
|
+
) -> int:
|
|
1077
|
+
"""按机器承载能力计算容量,仅在真实 CPU/RAM 压力下背压。"""
|
|
1078
|
+
actual_state = run_state if run_state is not None else state
|
|
1079
|
+
adaptive = getattr(budget, "adaptive_concurrency", True)
|
|
1080
|
+
configured_max = getattr(budget, "max_concurrency", None)
|
|
1081
|
+
if configured_max is None:
|
|
1082
|
+
try:
|
|
1083
|
+
from .supervisor_models import resolve_system_concurrency
|
|
1084
|
+
configured_max = resolve_system_concurrency()[0]
|
|
1085
|
+
except Exception:
|
|
1086
|
+
configured_max = 4
|
|
1087
|
+
if not adaptive or not getattr(budget, "require_parallel", True) or configured_max <= 1:
|
|
1088
|
+
return max(0, configured_max - current_active)
|
|
1089
|
+
|
|
1090
|
+
c_min = max(1, int(getattr(budget, "min_concurrency", self.min_concurrency)))
|
|
1091
|
+
c_max = getattr(budget, "max_concurrency_ceiling", None)
|
|
1092
|
+
if c_max is None:
|
|
1093
|
+
try:
|
|
1094
|
+
from .supervisor_models import resolve_system_concurrency
|
|
1095
|
+
c_max = resolve_system_concurrency()[1]
|
|
1096
|
+
except Exception:
|
|
1097
|
+
c_max = self.max_concurrency
|
|
1098
|
+
configured_max = max(c_min, int(configured_max))
|
|
1099
|
+
c_max = max(configured_max, int(c_max))
|
|
1100
|
+
# The persisted AIMD window is retained for old state compatibility and
|
|
1101
|
+
# telemetry, but must not silently under-fill a healthy machine.
|
|
1102
|
+
# ponytail: use one hardware limit; add per-provider quotas only when
|
|
1103
|
+
# an external API exposes a real capacity signal.
|
|
1104
|
+
effective_limit = float(configured_max)
|
|
1105
|
+
|
|
1106
|
+
# 1. 主机系统负载调节
|
|
1107
|
+
try:
|
|
1108
|
+
pressure, memory_pressure = self._get_system_load()
|
|
1109
|
+
except Exception:
|
|
1110
|
+
pressure = self.get_system_pressure()
|
|
1111
|
+
memory_pressure = None
|
|
1112
|
+
|
|
1113
|
+
if pressure > self.target_cpu_load or (
|
|
1114
|
+
memory_pressure is not None and memory_pressure > 85.0
|
|
1115
|
+
):
|
|
1116
|
+
reduction = (pressure - self.target_cpu_load) * 4.0
|
|
1117
|
+
if memory_pressure is not None and memory_pressure > 85.0:
|
|
1118
|
+
reduction = max(reduction, effective_limit * 0.2)
|
|
1119
|
+
effective_limit = max(float(c_min), effective_limit - reduction)
|
|
1120
|
+
self.concurrency_window = effective_limit
|
|
1121
|
+
|
|
1122
|
+
# DOC-137 2.0 / D137-06: 漏洞产出速率 (Yield Velocity) 与高回报动态提速
|
|
1123
|
+
if actual_state is not None and getattr(actual_state, "recent_high_yield", False) is True:
|
|
1124
|
+
if pressure <= self.target_cpu_load and (memory_pressure is None or memory_pressure <= 75.0):
|
|
1125
|
+
effective_limit = min(float(c_max), effective_limit * 1.5)
|
|
1126
|
+
|
|
1127
|
+
self.concurrency_window = effective_limit
|
|
1128
|
+
if actual_state is not None and hasattr(actual_state, "adaptive_concurrency_window"):
|
|
1129
|
+
actual_state.adaptive_concurrency_window = self.concurrency_window
|
|
1130
|
+
|
|
1131
|
+
return max(0, int(effective_limit) - current_active)
|
|
1132
|
+
|
|
1133
|
+
def record_outcome(self, state: Any, outcome: str) -> None:
|
|
1134
|
+
"""记录 Worker 结果;结果不再自动降低健康机器的并发。"""
|
|
1135
|
+
if not getattr(getattr(state, "budget", None), "adaptive_concurrency", True):
|
|
1136
|
+
return
|
|
1137
|
+
budget = state.budget
|
|
1138
|
+
if not getattr(budget, "require_parallel", True) or getattr(budget, "max_concurrency", 1) <= 1:
|
|
1139
|
+
return
|
|
1140
|
+
c_min = max(1, int(getattr(budget, "min_concurrency", self.min_concurrency)))
|
|
1141
|
+
c_max = int(getattr(budget, "max_concurrency_ceiling", self.max_concurrency))
|
|
1142
|
+
current = getattr(state, "adaptive_concurrency_window", None)
|
|
1143
|
+
if not isinstance(current, (int, float)) or isinstance(current, bool):
|
|
1144
|
+
current = float(getattr(budget, "max_concurrency", c_min))
|
|
1145
|
+
current = max(float(c_min), min(float(c_max), float(current)))
|
|
1146
|
+
if outcome in {"expired", "preempted", "failed"}:
|
|
1147
|
+
# Keep the window as telemetry only. Capacity is reduced only by
|
|
1148
|
+
# the live CPU/RAM pressure check in compute_capacity().
|
|
1149
|
+
state.adaptive_success_streak = 0
|
|
1150
|
+
state.adaptive_failure_streak = min(
|
|
1151
|
+
int(getattr(state, "adaptive_failure_streak", 0)) + 1, 1000,
|
|
1152
|
+
)
|
|
1153
|
+
return
|
|
1154
|
+
if outcome != "completed":
|
|
1155
|
+
return
|
|
1156
|
+
state.adaptive_failure_streak = 0
|
|
1157
|
+
streak = int(getattr(state, "adaptive_success_streak", 0)) + 1
|
|
1158
|
+
state.adaptive_concurrency_window = current
|
|
1159
|
+
state.adaptive_success_streak = streak
|
|
1160
|
+
|
|
1161
|
+
|
|
1162
|
+
class ComplexityLeaseCalculator:
|
|
1163
|
+
"""复杂度感知动态租约计算器。"""
|
|
1164
|
+
|
|
1165
|
+
@staticmethod
|
|
1166
|
+
def calculate_lease(
|
|
1167
|
+
unit_ids: Sequence[str],
|
|
1168
|
+
root: Path | None = None,
|
|
1169
|
+
defect_modules: set[str] | None = None,
|
|
1170
|
+
) -> float:
|
|
1171
|
+
"""根据单元数量、代码行数与业务类型动态计算推荐租约 TTL。
|
|
1172
|
+
|
|
1173
|
+
AI-agent worker 完成一个单元需要 10~25 分钟(全文读码 + 动态复现
|
|
1174
|
+
+ 证据落盘 + schema 校验),因此下限为 1800 秒;每个追加单元
|
|
1175
|
+
+600 秒;上限 ``LEASE_SECONDS_CEILING``(3600 秒)对齐常用
|
|
1176
|
+
max_round_wall_seconds 与 Supervisor 的租约接受上限。
|
|
1177
|
+
"""
|
|
1178
|
+
if not unit_ids:
|
|
1179
|
+
return 1800.0
|
|
1180
|
+
|
|
1181
|
+
# 单单元基础 1800s,多单元聚合每个追加 600s
|
|
1182
|
+
base_lease = 1800.0 + max(0, len(unit_ids) - 1) * 600.0
|
|
1183
|
+
|
|
1184
|
+
# 检查是否包含业务链路单元
|
|
1185
|
+
if any(unit_kind.is_business(u) for u in unit_ids):
|
|
1186
|
+
base_lease = max(base_lease, 2400.0)
|
|
1187
|
+
|
|
1188
|
+
# 检查是否命中历史错题/高危缺陷
|
|
1189
|
+
if defect_modules:
|
|
1190
|
+
for u in unit_ids:
|
|
1191
|
+
fp, _ = extract_unit_scope(u)
|
|
1192
|
+
if fp in defect_modules or any(m in fp for m in defect_modules):
|
|
1193
|
+
base_lease += 600.0
|
|
1194
|
+
break
|
|
1195
|
+
|
|
1196
|
+
# 检查源码文件行数复杂度
|
|
1197
|
+
if root:
|
|
1198
|
+
for u in unit_ids:
|
|
1199
|
+
fp, _ = extract_unit_scope(u)
|
|
1200
|
+
target = (root / fp).resolve()
|
|
1201
|
+
if target.is_file():
|
|
1202
|
+
try:
|
|
1203
|
+
lines = len(target.read_text(encoding="utf-8", errors="ignore").splitlines())
|
|
1204
|
+
if lines > 500:
|
|
1205
|
+
base_lease += 600.0
|
|
1206
|
+
elif lines > 200:
|
|
1207
|
+
base_lease += 300.0
|
|
1208
|
+
except OSError:
|
|
1209
|
+
pass
|
|
1210
|
+
|
|
1211
|
+
return max(1800.0, min(base_lease, LEASE_SECONDS_CEILING))
|
|
1212
|
+
|
|
1213
|
+
estimate_lease = calculate_lease
|
|
1214
|
+
|
|
1215
|
+
|
|
1216
|
+
class ZombieDetector:
|
|
1217
|
+
"""僵死 Worker 探活与秒级抢占探针。"""
|
|
1218
|
+
|
|
1219
|
+
@staticmethod
|
|
1220
|
+
def is_pid_alive(pid: int | None) -> bool:
|
|
1221
|
+
"""检测指定 PID 本地进程是否仍在活跃运行。"""
|
|
1222
|
+
if pid is None or pid <= 0:
|
|
1223
|
+
return False
|
|
1224
|
+
try:
|
|
1225
|
+
os.kill(pid, 0)
|
|
1226
|
+
return True
|
|
1227
|
+
except OSError as exc:
|
|
1228
|
+
return exc.errno == errno.EPERM
|
|
1229
|
+
|
|
1230
|
+
@staticmethod
|
|
1231
|
+
def pid_command_line(pid: int) -> str | None:
|
|
1232
|
+
"""读取进程命令行;无法读取时返回 None。
|
|
1233
|
+
|
|
1234
|
+
``None`` 必须被调用方当作「无法证明归属」处理,绝不能当作「可以终止」。
|
|
1235
|
+
"""
|
|
1236
|
+
if pid <= 0:
|
|
1237
|
+
return None
|
|
1238
|
+
if os.name == "posix":
|
|
1239
|
+
try:
|
|
1240
|
+
raw = Path(f"/proc/{pid}/cmdline").read_bytes()
|
|
1241
|
+
except OSError:
|
|
1242
|
+
raw = b""
|
|
1243
|
+
if raw:
|
|
1244
|
+
return raw.replace(b"\x00", b" ").decode("utf-8", "replace")
|
|
1245
|
+
try:
|
|
1246
|
+
result = subprocess.run(
|
|
1247
|
+
["ps", "-o", "command=", "-p", str(pid)],
|
|
1248
|
+
capture_output=True, text=True, check=False, timeout=2,
|
|
1249
|
+
)
|
|
1250
|
+
except (OSError, subprocess.SubprocessError):
|
|
1251
|
+
return None
|
|
1252
|
+
if result.returncode == 0 and result.stdout.strip():
|
|
1253
|
+
return result.stdout.strip()
|
|
1254
|
+
return None
|
|
1255
|
+
|
|
1256
|
+
@staticmethod
|
|
1257
|
+
def is_worker_process(pid: int) -> bool:
|
|
1258
|
+
"""判断 ``pid`` 的命令行是否明确指向 BugX Worker。
|
|
1259
|
+
|
|
1260
|
+
``process_pid`` 完全由 Worker 通过 MCP 参数自报(只校验 ``>= 1``)。
|
|
1261
|
+
若仅凭该 PID 发信号,Worker 就能让宿主终止任意进程——包括 PID 复用
|
|
1262
|
+
导致的无关进程,以及 ``os.killpg`` 波及的整组进程。因此终止前必须
|
|
1263
|
+
独立取得「这确实是一个 BugX Worker」的正向证据。
|
|
1264
|
+
"""
|
|
1265
|
+
cmdline = ZombieDetector.pid_command_line(pid)
|
|
1266
|
+
if not cmdline:
|
|
1267
|
+
return False
|
|
1268
|
+
lowered = cmdline.casefold()
|
|
1269
|
+
return any(marker in lowered for marker in WORKER_CMDLINE_MARKERS)
|
|
1270
|
+
|
|
1271
|
+
@staticmethod
|
|
1272
|
+
def _parent_pid(pid: int) -> int | None:
|
|
1273
|
+
"""读取 ``pid`` 的父进程号;无法读取时返回 None。"""
|
|
1274
|
+
if pid <= 0 or os.name != "posix":
|
|
1275
|
+
return None
|
|
1276
|
+
try:
|
|
1277
|
+
raw = Path(f"/proc/{pid}/stat").read_text(encoding="utf-8", errors="replace")
|
|
1278
|
+
except OSError:
|
|
1279
|
+
raw = ""
|
|
1280
|
+
if raw:
|
|
1281
|
+
# ``comm`` 可能含空格/括号,取最后一个 ')' 之后再切分:
|
|
1282
|
+
# 之后依次是 state、ppid。
|
|
1283
|
+
tail = raw.rsplit(")", 1)[-1].split()
|
|
1284
|
+
if len(tail) >= 2:
|
|
1285
|
+
try:
|
|
1286
|
+
return int(tail[1])
|
|
1287
|
+
except ValueError:
|
|
1288
|
+
return None
|
|
1289
|
+
try:
|
|
1290
|
+
result = subprocess.run(
|
|
1291
|
+
["ps", "-o", "ppid=", "-p", str(pid)],
|
|
1292
|
+
capture_output=True, text=True, check=False, timeout=2,
|
|
1293
|
+
)
|
|
1294
|
+
except (OSError, subprocess.SubprocessError):
|
|
1295
|
+
return None
|
|
1296
|
+
if result.returncode == 0 and result.stdout.strip():
|
|
1297
|
+
try:
|
|
1298
|
+
return int(result.stdout.split()[0])
|
|
1299
|
+
except (ValueError, IndexError):
|
|
1300
|
+
return None
|
|
1301
|
+
return None
|
|
1302
|
+
|
|
1303
|
+
@staticmethod
|
|
1304
|
+
def is_ancestor_of_self(pid: int | None) -> bool:
|
|
1305
|
+
"""判断 ``pid`` 是否是当前进程的祖先(父 / 祖父 / ...)。
|
|
1306
|
+
|
|
1307
|
+
祖先链上是宿主自身、用户 shell、``launchd``,以及拉起宿主的
|
|
1308
|
+
``opencode --agent bugx`` 主会话——后者的命令行恰好含有 BugX 标志,
|
|
1309
|
+
仅凭命令行证据无法排除。Worker 由宿主派生,绝不可能是宿主的祖先,
|
|
1310
|
+
因此命中即拒绝终止,杜绝「误伤用户主会话/终端」。
|
|
1311
|
+
"""
|
|
1312
|
+
if pid is None or pid <= 0:
|
|
1313
|
+
return False
|
|
1314
|
+
current = os.getpid()
|
|
1315
|
+
seen: set[int] = set()
|
|
1316
|
+
while current > 1 and current not in seen:
|
|
1317
|
+
seen.add(current)
|
|
1318
|
+
parent = ZombieDetector._parent_pid(current)
|
|
1319
|
+
if parent is None:
|
|
1320
|
+
return False
|
|
1321
|
+
if parent == pid:
|
|
1322
|
+
return True
|
|
1323
|
+
current = parent
|
|
1324
|
+
return False
|
|
1325
|
+
|
|
1326
|
+
@staticmethod
|
|
1327
|
+
def owns_process_group(pid: int) -> bool:
|
|
1328
|
+
"""判断 ``pid`` 是否是「本 BugX 会话自行创建」的进程组组长。
|
|
1329
|
+
|
|
1330
|
+
BugX 一律用 ``start_new_session=True`` 拉起 Worker
|
|
1331
|
+
(``core/worker_execution.py``),因此真实 Worker 必然是自己新建会话的
|
|
1332
|
+
组长:``getsid(pid) == getpgid(pid) == pid``。用户终端 / ``launchd``
|
|
1333
|
+
子会话即使恰好是组长,也不是本会话创建的,返回 False。只有为 True 时
|
|
1334
|
+
才允许 ``os.killpg``,否则退化为对单个 PID 发信号,避免一次终止波及
|
|
1335
|
+
整组无关进程。
|
|
1336
|
+
"""
|
|
1337
|
+
try:
|
|
1338
|
+
return os.getpgid(pid) == pid and os.getsid(pid) == pid
|
|
1339
|
+
except OSError:
|
|
1340
|
+
return False
|
|
1341
|
+
|
|
1342
|
+
@staticmethod
|
|
1343
|
+
def _signal_target(pid: int):
|
|
1344
|
+
"""返回本次终止使用的信号投递函数。
|
|
1345
|
+
|
|
1346
|
+
仅当目标确为「本会话创建的进程组组长」时才用 ``os.killpg``;否则退回
|
|
1347
|
+
单 PID 的 ``os.kill``。无法证明归属时一律不整组投递。
|
|
1348
|
+
"""
|
|
1349
|
+
if ZombieDetector.owns_process_group(pid):
|
|
1350
|
+
return lambda sig: os.killpg(pid, sig)
|
|
1351
|
+
return lambda sig: os.kill(pid, sig)
|
|
1352
|
+
|
|
1353
|
+
@staticmethod
|
|
1354
|
+
def terminate_claim(claim: Any, workspace_root: Path | str | None = None) -> tuple[bool, str]:
|
|
1355
|
+
"""按 claim 记录的归属信息终止其 Worker,返回 ``(是否已终止, 原因)``。
|
|
1356
|
+
|
|
1357
|
+
``claim`` 同时携带 ``process_pid`` 与 ``process_start_token``,把归属
|
|
1358
|
+
决策收敛到单点,调用方不再各自复制守卫。原因为空串表示成功;否则是
|
|
1359
|
+
拒绝/失败原因码,供调用方写入审计事件,使「拒绝」不再静默。
|
|
1360
|
+
终止成功后自动触发 OrphanSandboxReaper 物理收割其临时沙箱 (DOC-242)。
|
|
1361
|
+
"""
|
|
1362
|
+
terminated, refusal = ZombieDetector._terminate_pid_verdict(
|
|
1363
|
+
getattr(claim, "process_pid", None),
|
|
1364
|
+
expected_start_token=getattr(claim, "process_start_token", None),
|
|
1365
|
+
)
|
|
1366
|
+
if terminated:
|
|
1367
|
+
worker_id = getattr(claim, "worker_id", None)
|
|
1368
|
+
OrphanSandboxReaper.reap_worker_sandbox(workspace_root, worker_id)
|
|
1369
|
+
return terminated, refusal
|
|
1370
|
+
|
|
1371
|
+
@staticmethod
|
|
1372
|
+
def is_pid_cpu_active(pid: int | None) -> bool:
|
|
1373
|
+
"""检查本地进程是否有非零 CPU 时间或活跃运行 (DOC-242)。"""
|
|
1374
|
+
if pid is None or pid <= 0:
|
|
1375
|
+
return False
|
|
1376
|
+
if not ZombieDetector.is_pid_alive(pid):
|
|
1377
|
+
return False
|
|
1378
|
+
if os.name == "posix":
|
|
1379
|
+
stat_path = Path(f"/proc/{pid}/stat")
|
|
1380
|
+
if stat_path.is_file():
|
|
1381
|
+
try:
|
|
1382
|
+
parts = stat_path.read_text(encoding="utf-8", errors="replace").rsplit(")", 1)[-1].split()
|
|
1383
|
+
if len(parts) >= 13:
|
|
1384
|
+
utime = int(parts[11])
|
|
1385
|
+
stime = int(parts[12])
|
|
1386
|
+
return (utime + stime) > 0
|
|
1387
|
+
except Exception:
|
|
1388
|
+
pass
|
|
1389
|
+
try:
|
|
1390
|
+
result = subprocess.run(
|
|
1391
|
+
["ps", "-o", "cputime=", "-p", str(pid)],
|
|
1392
|
+
capture_output=True, text=True, check=False, timeout=2,
|
|
1393
|
+
)
|
|
1394
|
+
if result.returncode == 0 and result.stdout.strip():
|
|
1395
|
+
val = result.stdout.strip()
|
|
1396
|
+
return val not in ("0:00.00", "00:00.00", "0:00", "")
|
|
1397
|
+
except Exception:
|
|
1398
|
+
pass
|
|
1399
|
+
return True
|
|
1400
|
+
|
|
1401
|
+
@staticmethod
|
|
1402
|
+
def _terminate_pid_verdict(
|
|
1403
|
+
pid: int | None, *, expected_start_token: str | None,
|
|
1404
|
+
) -> tuple[bool, str]:
|
|
1405
|
+
"""终止决策的单点实现,返回 ``(是否已终止, 原因)``。
|
|
1406
|
+
|
|
1407
|
+
fail-closed 的五道校验,任一不成立即拒绝发信号:
|
|
1408
|
+
1. PID 合法、不是本进程、也不是本进程的祖先进程;
|
|
1409
|
+
2. 命令行独立证明这确实是 BugX Worker(``is_worker_process``);
|
|
1410
|
+
3. claim 记录过启动令牌——未记录即无法证明 PID 未被复用,拒绝;
|
|
1411
|
+
4. 当前 PID 的启动令牌与记录一致;读不到令牌同样拒绝。
|
|
1412
|
+
整组投递(``killpg``)另有 :meth:`owns_process_group` 把关。
|
|
1413
|
+
"""
|
|
1414
|
+
if pid is None or pid <= 0:
|
|
1415
|
+
return False, "refused_invalid_pid"
|
|
1416
|
+
if pid == os.getpid():
|
|
1417
|
+
return False, "refused_self_pid"
|
|
1418
|
+
if ZombieDetector.is_ancestor_of_self(pid):
|
|
1419
|
+
return False, "refused_ancestor_process"
|
|
1420
|
+
if not ZombieDetector.is_pid_alive(pid):
|
|
1421
|
+
return True, ""
|
|
1422
|
+
if not ZombieDetector.is_worker_process(pid):
|
|
1423
|
+
return False, "refused_no_worker_evidence"
|
|
1424
|
+
if expected_start_token is None:
|
|
1425
|
+
return False, "refused_missing_start_token"
|
|
1426
|
+
try:
|
|
1427
|
+
from . import supervisor_models
|
|
1428
|
+
live_token = supervisor_models.process_start_token(pid)
|
|
1429
|
+
except Exception:
|
|
1430
|
+
return False, "refused_start_token_unavailable"
|
|
1431
|
+
if live_token is None:
|
|
1432
|
+
return False, "refused_start_token_unavailable"
|
|
1433
|
+
if live_token != expected_start_token:
|
|
1434
|
+
return False, "refused_start_token_mismatch"
|
|
1435
|
+
try:
|
|
1436
|
+
if os.name == "nt": # pragma: no cover - exercised on Windows
|
|
1437
|
+
result = subprocess.run(
|
|
1438
|
+
["taskkill", "/PID", str(pid), "/T", "/F"],
|
|
1439
|
+
capture_output=True, text=True, check=False, timeout=5,
|
|
1440
|
+
)
|
|
1441
|
+
terminated = result.returncode == 0 or not ZombieDetector.is_pid_alive(pid)
|
|
1442
|
+
return terminated, ("" if terminated else "signal_failed")
|
|
1443
|
+
|
|
1444
|
+
signal_target = ZombieDetector._signal_target(pid)
|
|
1445
|
+
try:
|
|
1446
|
+
signal_target(signal.SIGTERM)
|
|
1447
|
+
except OSError:
|
|
1448
|
+
os.kill(pid, signal.SIGTERM)
|
|
1449
|
+
deadline = time.monotonic() + 0.5
|
|
1450
|
+
while ZombieDetector.is_pid_alive(pid) and time.monotonic() < deadline:
|
|
1451
|
+
time.sleep(0.02)
|
|
1452
|
+
if ZombieDetector.is_pid_alive(pid):
|
|
1453
|
+
try:
|
|
1454
|
+
signal_target(signal.SIGKILL)
|
|
1455
|
+
except OSError:
|
|
1456
|
+
os.kill(pid, signal.SIGKILL)
|
|
1457
|
+
terminated = not ZombieDetector.is_pid_alive(pid)
|
|
1458
|
+
return terminated, ("" if terminated else "signal_failed")
|
|
1459
|
+
except (OSError, subprocess.SubprocessError):
|
|
1460
|
+
terminated = not ZombieDetector.is_pid_alive(pid)
|
|
1461
|
+
return terminated, ("" if terminated else "signal_failed")
|
|
1462
|
+
|
|
1463
|
+
@staticmethod
|
|
1464
|
+
def terminate_pid(pid: int | None, *, expected_start_token: str | None = None) -> bool:
|
|
1465
|
+
"""终止卡死的本地 Worker,成功返回时进程已不再存活。
|
|
1466
|
+
|
|
1467
|
+
兼容入口,保留既有签名;归属判定走 :meth:`_terminate_pid_verdict`
|
|
1468
|
+
单点实现。``expected_start_token`` 缺失即拒绝:无法证明 PID 未被复用
|
|
1469
|
+
时宁可不终止,租约照常过期,调度不受影响。
|
|
1470
|
+
"""
|
|
1471
|
+
terminated, _reason = ZombieDetector._terminate_pid_verdict(
|
|
1472
|
+
pid, expected_start_token=expected_start_token,
|
|
1473
|
+
)
|
|
1474
|
+
return terminated
|
|
1475
|
+
|
|
1476
|
+
@staticmethod
|
|
1477
|
+
def check_zombie_claim(
|
|
1478
|
+
claim: Any,
|
|
1479
|
+
now: float,
|
|
1480
|
+
heartbeat_timeout_window: float = 450.0,
|
|
1481
|
+
now_mono: float | None = None,
|
|
1482
|
+
) -> tuple[bool, str]:
|
|
1483
|
+
"""检查指定 Claim 是否已处于僵死状态需要立即抢占 (DOC-242: 支持单调时钟)。"""
|
|
1484
|
+
# 1. 进程存活性检查
|
|
1485
|
+
pid = getattr(claim, "process_pid", None)
|
|
1486
|
+
if pid is not None and not ZombieDetector.is_pid_alive(pid):
|
|
1487
|
+
return True, f"process_{pid}_dead"
|
|
1488
|
+
|
|
1489
|
+
# 2. 连续心跳断流检查 (两个时钟任一判定断流/到期即生效,防模拟时钟与单调时钟脱敏)
|
|
1490
|
+
execution_state = getattr(claim, "execution_state", "")
|
|
1491
|
+
last_hb = getattr(claim, "last_heartbeat_at", None)
|
|
1492
|
+
last_hb_mono = getattr(claim, "last_heartbeat_mono", None)
|
|
1493
|
+
if execution_state == "running" and last_hb is not None:
|
|
1494
|
+
silence_wall = now - last_hb
|
|
1495
|
+
silence_mono = (now_mono - last_hb_mono) if (now_mono is not None and last_hb_mono is not None) else silence_wall
|
|
1496
|
+
silence = max(silence_wall, silence_mono)
|
|
1497
|
+
if silence > heartbeat_timeout_window:
|
|
1498
|
+
# C1 宽限:租约是 worker 对自身执行时长的申报。进程存活且
|
|
1499
|
+
# 租约未到期时,心跳断流只说明"该保活了",不构成僵死证据——
|
|
1500
|
+
# 否则无人值守 worker(模型+差分+补丁合成常超 450s)会被同批
|
|
1501
|
+
# 并发线程的 refresh 误判抢占,整批静默失败。仅当断流超过
|
|
1502
|
+
# 租约剩余量(连申报的时长都守不住)才判僵尸。
|
|
1503
|
+
# A7(Wave 1 交接 §4-1):租约过期只看**单调时钟**。
|
|
1504
|
+
# 旧实现 ``wall_expired or mono_expired`` 把墙钟 OR 进来,墙钟前跳
|
|
1505
|
+
# 会错杀仍存活的 worker(长任务常超 450s)。
|
|
1506
|
+
# 缺 mono 锚点 ⇒ fail-closed 视为过期:不得靠墙钟猜(旧快照已由
|
|
1507
|
+
# ``from_dict`` 拒绝,此处为第二道防线)。
|
|
1508
|
+
lease_expires_at = getattr(claim, "lease_expires_at", None)
|
|
1509
|
+
lease_expires_mono = getattr(claim, "lease_expires_mono", None)
|
|
1510
|
+
if lease_expires_mono is None or now_mono is None:
|
|
1511
|
+
return True, "heartbeat_timeout_missing_mono_anchor"
|
|
1512
|
+
if now_mono >= lease_expires_mono:
|
|
1513
|
+
return True, "heartbeat_timeout"
|
|
1514
|
+
|
|
1515
|
+
# 剩余租约的**夹紧**仍保留墙钟兜底:silence 计算本身还混用墙钟
|
|
1516
|
+
# (Wave 1 交接 §4-3 的 grace 窗/Wave 3 统一口径)。这里只把
|
|
1517
|
+
# 「是否过期」的判定收紧为 mono,不提前改动 silence 语义。
|
|
1518
|
+
rem_wall = max(0.0, (lease_expires_at or now) - now)
|
|
1519
|
+
rem_mono = max(0.0, lease_expires_mono - now_mono)
|
|
1520
|
+
remaining_lease = min(rem_wall, rem_mono)
|
|
1521
|
+
|
|
1522
|
+
# 活性证据自适应(卡死木桶修复):``process_pid`` 是「进程还活着」
|
|
1523
|
+
# 的独立证据;没有它时(宿主 Task 子代理、CLI 会话等)**心跳就是
|
|
1524
|
+
# 唯一活性证据**,此时不能用「断流超过租约剩余量」这把宽限尺子——
|
|
1525
|
+
# 那等于要求等完整个租约。实测:worker 心跳停滞 age=113s 而租约仍剩
|
|
1526
|
+
# 2290s,日志刷了 38 分钟「无法走孤儿快通道回收」,单元被白占。
|
|
1527
|
+
# 因此:无进程证据 → 断流超窗口即回收;有进程证据才保留 C1 宽限。
|
|
1528
|
+
# judge collect/settle 的宿主簿记 claim(provider="judge-*")
|
|
1529
|
+
# 全程无独立进程、设计上不心跳:collect→判读→settle 单轮可达
|
|
1530
|
+
# 分钟级,心跳断流不代表死亡。这类 claim 的存活契约是租约本身
|
|
1531
|
+
# (collect 建约时 lease_seconds=1800),断流超窗不再构成僵尸
|
|
1532
|
+
# 证据,交给租约到期兜底——否则长判读波次的 claim 必被误杀。
|
|
1533
|
+
provider = str(getattr(claim, "provider", "") or "")
|
|
1534
|
+
if (
|
|
1535
|
+
pid is None
|
|
1536
|
+
and silence > heartbeat_timeout_window
|
|
1537
|
+
and not provider.startswith("judge-")
|
|
1538
|
+
):
|
|
1539
|
+
return True, "heartbeat_timeout_no_process_evidence"
|
|
1540
|
+
if silence > remaining_lease + heartbeat_timeout_window:
|
|
1541
|
+
return True, "heartbeat_timeout_beyond_lease"
|
|
1542
|
+
|
|
1543
|
+
return False, ""
|
|
1544
|
+
|
|
1545
|
+
is_zombie = check_zombie_claim
|
|
1546
|
+
|
|
1547
|
+
|
|
1548
|
+
class OrphanSandboxReaper:
|
|
1549
|
+
"""异常终止 Worker 的沙箱与临时锁物理收割器 (DOC-242)。"""
|
|
1550
|
+
|
|
1551
|
+
@staticmethod
|
|
1552
|
+
def reap_worker_sandbox(workspace_root: Path | str | None, worker_id: str | None) -> bool:
|
|
1553
|
+
"""物理清理指定 Worker 的临时沙箱目录与挂载点。"""
|
|
1554
|
+
if not worker_id or not isinstance(worker_id, str):
|
|
1555
|
+
return False
|
|
1556
|
+
clean_id = worker_id.strip()
|
|
1557
|
+
# 严格校验 worker_id 字符集,杜绝路径穿透
|
|
1558
|
+
if not re.match(r"^[a-zA-Z0-9_\-]+$", clean_id):
|
|
1559
|
+
return False
|
|
1560
|
+
if not workspace_root:
|
|
1561
|
+
return False
|
|
1562
|
+
try:
|
|
1563
|
+
root = Path(workspace_root).resolve()
|
|
1564
|
+
targets = [
|
|
1565
|
+
root / ".bugx" / "sandboxes" / clean_id,
|
|
1566
|
+
root / ".bugx" / "sandboxes" / f"w-{clean_id}",
|
|
1567
|
+
root / ".bugx" / "state" / "sandboxes" / clean_id,
|
|
1568
|
+
]
|
|
1569
|
+
reaped = False
|
|
1570
|
+
for target in targets:
|
|
1571
|
+
if target.is_dir() and not target.is_symlink():
|
|
1572
|
+
shutil.rmtree(target, ignore_errors=True)
|
|
1573
|
+
reaped = True
|
|
1574
|
+
return reaped
|
|
1575
|
+
except Exception:
|
|
1576
|
+
return False
|
|
1577
|
+
|
|
1578
|
+
|
|
1579
|
+
MIN_ROUND_WALL_SECONDS = 180.0
|
|
1580
|
+
MAX_ROUND_WALL_SECONDS = 7200.0
|
|
1581
|
+
DEFAULT_ROUND_WALL_SECONDS = 900.0
|
|
1582
|
+
|
|
1583
|
+
|
|
1584
|
+
class RoundBudgetCalculator:
|
|
1585
|
+
"""自适应轮次预算计算器 (DOC-150)。
|
|
1586
|
+
|
|
1587
|
+
根据当前 Round 内规划派发的单元集合、代码行数与 AST 复杂度、
|
|
1588
|
+
调用链依赖深度以及历史错题/高危模块密度,动态推算科学合理的轮次预算墙钟。
|
|
1589
|
+
避免对全轻量级任务赋予死板的 900s 冗余,也避免对重度复杂链路过早硬超时。
|
|
1590
|
+
"""
|
|
1591
|
+
|
|
1592
|
+
@staticmethod
|
|
1593
|
+
def calculate_round_budget(
|
|
1594
|
+
unit_ids: Sequence[str],
|
|
1595
|
+
*,
|
|
1596
|
+
root: Path | None = None,
|
|
1597
|
+
concurrency: int = 1,
|
|
1598
|
+
defect_modules: set[str] | None = None,
|
|
1599
|
+
base_seconds: float = DEFAULT_ROUND_WALL_SECONDS,
|
|
1600
|
+
) -> float:
|
|
1601
|
+
if not unit_ids:
|
|
1602
|
+
return base_seconds
|
|
1603
|
+
|
|
1604
|
+
concurrency = max(1, int(concurrency))
|
|
1605
|
+
# 1. 基础时间:按并发分摊基础工作量(单单元基准估算 450s 勘察与验证)
|
|
1606
|
+
parallel_batches = math.ceil(len(unit_ids) / concurrency)
|
|
1607
|
+
calculated = max(MIN_ROUND_WALL_SECONDS, parallel_batches * 450.0)
|
|
1608
|
+
|
|
1609
|
+
# 2. 业务链路与深层调用加权
|
|
1610
|
+
biz_units = [u for u in unit_ids if unit_kind.is_business(u)]
|
|
1611
|
+
if biz_units:
|
|
1612
|
+
calculated += len(biz_units) * 150.0
|
|
1613
|
+
|
|
1614
|
+
# 3. 历史缺陷与错题模块排雷加权
|
|
1615
|
+
if defect_modules:
|
|
1616
|
+
matched_defects = 0
|
|
1617
|
+
for u in unit_ids:
|
|
1618
|
+
fp, _ = extract_unit_scope(u)
|
|
1619
|
+
if fp in defect_modules or any(m in fp for m in defect_modules):
|
|
1620
|
+
matched_defects += 1
|
|
1621
|
+
if matched_defects > 0:
|
|
1622
|
+
calculated += min(1200.0, matched_defects * 200.0)
|
|
1623
|
+
|
|
1624
|
+
# 4. 代码规模与复杂度加权
|
|
1625
|
+
if root:
|
|
1626
|
+
total_lines = 0
|
|
1627
|
+
for u in unit_ids:
|
|
1628
|
+
fp, _ = extract_unit_scope(u)
|
|
1629
|
+
target = (root / fp).resolve()
|
|
1630
|
+
if target.is_file():
|
|
1631
|
+
try:
|
|
1632
|
+
total_lines += len(target.read_text(encoding="utf-8", errors="ignore").splitlines())
|
|
1633
|
+
except OSError:
|
|
1634
|
+
pass
|
|
1635
|
+
if total_lines > 2000:
|
|
1636
|
+
calculated += 600.0
|
|
1637
|
+
elif total_lines > 800:
|
|
1638
|
+
calculated += 300.0
|
|
1639
|
+
|
|
1640
|
+
return max(MIN_ROUND_WALL_SECONDS, min(calculated, MAX_ROUND_WALL_SECONDS))
|