bugx-cli 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +55 -0
- package/README.md +280 -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 +50 -0
- package/core/agent/__init__.py +146 -0
- package/core/agent/agent_artifacts.py +764 -0
- package/core/agent/agent_eval.py +1073 -0
- package/core/agent/agent_execution.py +552 -0
- package/core/agent/agent_orchestrator.py +1345 -0
- package/core/agent/agent_targets.py +871 -0
- package/core/agent/agent_workspace.py +770 -0
- package/core/assets/README.md +24 -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/project-layout.md +42 -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 +1822 -0
- package/core/autonomous_cve/audit_campaign.py +1232 -0
- package/core/autonomous_cve/behavior_graph.py +459 -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 +100 -0
- package/core/bugx.md +1299 -0
- package/core/bugx_paths.py +1846 -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 +1199 -0
- package/core/cloud_sync/cloud_onboard.py +702 -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 +760 -0
- package/core/cloud_sync/network_transport.py +275 -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 +721 -0
- package/core/contracts/AGENT_GUIDE.md +362 -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 +390 -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 +859 -0
- package/core/coverage/coverage_evidence.py +977 -0
- package/core/coverage/coverage_forensics.py +115 -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 +236 -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 +2625 -0
- package/core/fuzzing/README.md +49 -0
- package/core/fuzzing/__init__.py +82 -0
- package/core/fuzzing/concurrency_fuzzer.py +382 -0
- package/core/fuzzing/differential_oracle.py +629 -0
- package/core/fuzzing/fuzz_input.py +1188 -0
- package/core/fuzzing/stateful_fuzzer.py +332 -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 +772 -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 +41 -0
- package/core/host_acp/cline.py +235 -0
- package/core/host_acp/codex.py +245 -0
- package/core/host_acp/dsh.py +48 -0
- package/core/host_acp/opencode.py +154 -0
- package/core/host_acp/pi.py +36 -0
- package/core/host_acp/zcode.py +41 -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 +435 -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 +721 -0
- package/core/host_runtime/host_probe.py +41 -0
- package/core/host_runtime/host_provider_arbitrator.py +777 -0
- package/core/host_runtime/host_registry.py +655 -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 +368 -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 +136 -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 +451 -0
- package/core/hosts/claude.py +157 -0
- package/core/hosts/cline.py +225 -0
- package/core/hosts/codex.py +948 -0
- package/core/hosts/dsh.py +518 -0
- package/core/hosts/opencode.py +358 -0
- package/core/hosts/pi.py +151 -0
- package/core/hosts/zcode.py +219 -0
- package/core/i18n.py +252 -0
- package/core/infra/README.md +39 -0
- package/core/infra/__init__.py +15 -0
- package/core/infra/build_info.py +86 -0
- package/core/infra/client_metadata.py +185 -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 +1041 -0
- package/core/launch_phases/finding_confirm_phase.py +387 -0
- package/core/launch_phases/finding_settlement.py +1245 -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 +791 -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 +682 -0
- package/core/launch_phases/post_commit.py +567 -0
- package/core/launch_phases/post_coverage_sync.py +591 -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 +1087 -0
- package/core/launch_phases/post_receipt.py +362 -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 +862 -0
- package/core/launch_phases/pre_state_builder.py +1286 -0
- package/core/launch_phases/report_sharing.py +414 -0
- package/core/launch_phases/round_orchestrator.py +1133 -0
- package/core/launch_phases/session_runtime.py +1623 -0
- package/core/launch_phases/startup_gates.py +1022 -0
- package/core/launch_phases/startup_interaction.py +947 -0
- package/core/launch_phases/startup_version_gate.py +873 -0
- package/core/launch_phases/supervisor_bridge.py +1224 -0
- package/core/launch_phases/supervisor_coverage.py +417 -0
- package/core/launch_phases/supervisor_degraded.py +1219 -0
- package/core/launch_phases/worker_barriers.py +414 -0
- package/core/launch_phases/worker_orchestrator.py +1166 -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 +226 -0
- package/core/ledger/archive_ops.py +572 -0
- package/core/ledger/auto_materialization.py +459 -0
- package/core/ledger/bug-log.md +22 -0
- package/core/ledger/cli.py +270 -0
- package/core/ledger/export_ops.py +549 -0
- package/core/ledger/finding_confirmation.py +1274 -0
- package/core/ledger/finding_io.py +299 -0
- package/core/ledger/finding_lifecycle.py +307 -0
- package/core/ledger/finding_verification.py +369 -0
- package/core/ledger/incidents.py +999 -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 +681 -0
- package/core/ledger/receipt_contract.py +253 -0
- package/core/ledger/schema.py +1192 -0
- package/core/ledger/sync_ops.py +935 -0
- package/core/ledger/tool_experience.py +682 -0
- package/core/ledger/verify_life.py +1526 -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 +697 -0
- package/core/mcp_handlers/channel_lifecycle.py +696 -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 +239 -0
- package/core/mcp_handlers/rpc_server.py +465 -0
- package/core/mcp_handlers/supervisor_handlers.py +1435 -0
- package/core/mcp_handlers/telemetry_handlers.py +227 -0
- package/core/mcp_handlers/tool_table.py +1015 -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 +605 -0
- package/core/mcp_runtime_support/verifier.py +810 -0
- package/core/metadata.txt +5 -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 +267 -0
- package/core/planning/dynamic_flow_analyzer.py +328 -0
- package/core/planning/impact_pruner.py +435 -0
- package/core/planning/intent_adjudicator.py +175 -0
- package/core/planning/judge_pipeline.py +1163 -0
- package/core/planning/logic_analysis.py +419 -0
- package/core/planning/prompt_harness.py +1702 -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 +73 -0
- package/core/probes/README.md +51 -0
- package/core/probes/SPEC.md +26 -0
- package/core/probes/__init__.py +70 -0
- package/core/probes/android_probe.py +384 -0
- package/core/probes/base.py +147 -0
- package/core/probes/codebase_memory_probe.py +590 -0
- package/core/probes/desktop_probe.py +238 -0
- package/core/probes/differential_probe.py +356 -0
- package/core/probes/efficiency_probe.py +168 -0
- package/core/probes/ios_binary_probe.py +368 -0
- package/core/probes/memory_probe.py +326 -0
- package/core/probes/miniprogram_probe.py +323 -0
- package/core/probes/mobile_probe.py +281 -0
- package/core/probes/native_probe.py +214 -0
- package/core/probes/openwiki_probe.py +193 -0
- package/core/probes/pattern_probe.py +347 -0
- package/core/probes/platform_probe.py +343 -0
- package/core/probes/probe_registry.py +1669 -0
- package/core/probes/sast_probe.py +1009 -0
- package/core/probes/sast_rules.py +841 -0
- package/core/probes/sca_scanner.py +731 -0
- package/core/probes/web_probe.py +359 -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 +311 -0
- package/core/project_profiler/constants.py +247 -0
- package/core/project_profiler/detector.py +392 -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 +265 -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 +465 -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 +313 -0
- package/core/repair/rsi_repair.py +348 -0
- package/core/repair/rsi_rounds.py +212 -0
- package/core/repair/rsi_scope.py +262 -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 +224 -0
- package/core/report_engine/authority.py +255 -0
- package/core/report_engine/finding_report.py +417 -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 +761 -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 +822 -0
- package/core/report_engine/visual_report_builder.py +796 -0
- package/core/report_engine/web-conformance.md +63 -0
- package/core/report_engine/web_conformance.py +459 -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 +1684 -0
- package/core/retrieval/codebase_memory_bridge.py +337 -0
- package/core/retrieval/context_assembler.py +234 -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 +909 -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 +1132 -0
- package/core/retrieval/universal_code_matcher.py +437 -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 +1393 -0
- package/core/runtime/daemon_runner.py +623 -0
- package/core/runtime/fixture_solidify.py +449 -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 +769 -0
- package/core/runtime/platform_adapter.py +579 -0
- package/core/runtime/prep_validate.py +476 -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 +963 -0
- package/core/runtime/provider_window.py +97 -0
- package/core/runtime/resume_ticket.py +115 -0
- package/core/runtime/scenario_eval.py +814 -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 +416 -0
- package/core/skills/bugx_mcp_server.py +1134 -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 +760 -0
- package/core/supervisor/checkpoint_handler.py +368 -0
- package/core/supervisor/checkpoint_pipeline.py +1322 -0
- package/core/supervisor/checkpoint_sync.py +640 -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 +659 -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 +124 -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 +308 -0
- package/core/supervisor/round_governor.py +306 -0
- package/core/supervisor/serial_authorization.py +500 -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 +223 -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 +999 -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 +402 -0
- package/core/webui/INTERFACE.md +50 -0
- package/core/webui/README.md +57 -0
- package/core/webui/SPEC.md +25 -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 +218 -0
- package/core/webui/adapters/cline.py +399 -0
- package/core/webui/adapters/codex.py +256 -0
- package/core/webui/adapters/dsh.py +173 -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 +1743 -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/favicon.png +0 -0
- package/core/webui/static/icon-192.png +0 -0
- package/core/webui/static/index.html +42 -0
- package/core/webui/static/manifest.webmanifest +19 -0
- package/core/webui/static/project-settings.css +6458 -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 +281 -0
- package/docs/07_distribution/README.md +16 -0
- package/docs/README.md +121 -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 +3067 -0
- package/ecosystem/integrations/opencode/opencode.json +118 -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/README.md +143 -0
- package/interfaces/bin/README.md +35 -0
- package/interfaces/bin/bugx.js +80 -0
- package/interfaces/cli/README.md +90 -0
- package/interfaces/cli/bugx_cli/__init__.py +4 -0
- package/interfaces/cli/bugx_cli/cli.py +1678 -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 +3944 -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 +1370 -0
- package/interfaces/cli/bugx_cli/commands/daemon.py +50 -0
- package/interfaces/cli/bugx_cli/commands/doctor.py +1345 -0
- package/interfaces/cli/bugx_cli/commands/goal.py +107 -0
- package/interfaces/cli/bugx_cli/commands/interaction.py +244 -0
- package/interfaces/cli/bugx_cli/commands/knowledge.py +617 -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 +2714 -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 +728 -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 +260 -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 +898 -0
- package/interfaces/cli/bugx_cli/host_adapters.py +1917 -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 +571 -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 +721 -0
- package/interfaces/cli/bugx_cli/infra/engine_installer.py +1937 -0
- package/interfaces/cli/bugx_cli/infra/host_sync.py +545 -0
- package/interfaces/cli/bugx_cli/infra/mcp_advisor.py +755 -0
- package/interfaces/cli/bugx_cli/infra/security.py +332 -0
- package/package.json +98 -4
- package/pyproject.toml +246 -0
- package/scripts/README.md +118 -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 +37 -0
- package/scripts/test-npm-wrapper.mjs +265 -0
|
@@ -0,0 +1,1232 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""维护多维审计覆盖、风险优先级和可恢复的最小单元任务队列。"""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
# --- 引擎导入根(直接执行脚本时自举 core.* 命名空间)---
|
|
5
|
+
import sys as _sys
|
|
6
|
+
from pathlib import Path as _Path
|
|
7
|
+
|
|
8
|
+
for _p in _Path(__file__).resolve().parents:
|
|
9
|
+
if (_p / "core" / "bugx.md").is_file():
|
|
10
|
+
if str(_p) not in _sys.path:
|
|
11
|
+
_sys.path.insert(0, str(_p))
|
|
12
|
+
break
|
|
13
|
+
del _p
|
|
14
|
+
import sys
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
import argparse
|
|
19
|
+
import copy
|
|
20
|
+
import contextlib
|
|
21
|
+
import datetime as dt
|
|
22
|
+
import json
|
|
23
|
+
import math
|
|
24
|
+
import os
|
|
25
|
+
import re
|
|
26
|
+
import tempfile
|
|
27
|
+
import threading
|
|
28
|
+
import time
|
|
29
|
+
import uuid
|
|
30
|
+
|
|
31
|
+
from core.runtime import project_graph
|
|
32
|
+
from core.retrieval import symbol_index
|
|
33
|
+
|
|
34
|
+
_CAMPAIGN_LOCK_THREAD = threading.RLock()
|
|
35
|
+
_CAMPAIGN_LOCK_STATE = threading.local()
|
|
36
|
+
|
|
37
|
+
SCHEMA_VERSION = 2
|
|
38
|
+
EXECUTION_STATES = {"not_run", "pass", "fail", "blocked", "not_applicable"}
|
|
39
|
+
EVIDENCE_KINDS = {"source", "test", "command", "finding"}
|
|
40
|
+
EVIDENCE_RESULTS = {"pass", "fail", "blocked", "not_applicable"}
|
|
41
|
+
EVIDENCE_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$")
|
|
42
|
+
SESSION_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$")
|
|
43
|
+
ASSET_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$")
|
|
44
|
+
ASSET_LOCATOR_RE = re.compile(r"^(?:runtime:[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}|env:BUGX_[A-Za-z0-9_]{1,127})$")
|
|
45
|
+
ASSET_KINDS = {"account", "session", "token", "cookie", "fixture", "identifier", "header", "other"}
|
|
46
|
+
ASSET_SENSITIVITIES = {"public", "internal", "secret"}
|
|
47
|
+
ASSET_SOURCES = {"unit", "external"}
|
|
48
|
+
ASSET_FORBIDDEN_FIELDS = {
|
|
49
|
+
"value", "password", "passwd", "token_value", "secret", "cookie_value",
|
|
50
|
+
"authorization", "api_key", "access_token", "refresh_token",
|
|
51
|
+
}
|
|
52
|
+
DEFAULT_LEASE_SECONDS = 300.0
|
|
53
|
+
MAX_LEASE_SECONDS = 24 * 60 * 60
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class CampaignError(ValueError):
|
|
57
|
+
"""审计任务状态协议错误。"""
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _atomic_write(path: Path, payload: dict) -> None:
|
|
61
|
+
if not path.parent.is_dir():
|
|
62
|
+
raise CampaignError(f"输出目录不存在: {path.parent}")
|
|
63
|
+
descriptor, temporary = tempfile.mkstemp(
|
|
64
|
+
dir=str(path.parent), prefix=f".{path.name}.", suffix=".tmp",
|
|
65
|
+
)
|
|
66
|
+
try:
|
|
67
|
+
with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
|
|
68
|
+
json.dump(payload, handle, ensure_ascii=False, indent=2)
|
|
69
|
+
handle.write("\n")
|
|
70
|
+
handle.flush()
|
|
71
|
+
os.fsync(handle.fileno())
|
|
72
|
+
os.replace(temporary, path)
|
|
73
|
+
try:
|
|
74
|
+
parent_fd = os.open(path.parent, os.O_RDONLY)
|
|
75
|
+
except OSError:
|
|
76
|
+
# Directory fsync is unavailable on some supported platforms.
|
|
77
|
+
pass
|
|
78
|
+
else:
|
|
79
|
+
try:
|
|
80
|
+
os.fsync(parent_fd)
|
|
81
|
+
except OSError:
|
|
82
|
+
pass
|
|
83
|
+
finally:
|
|
84
|
+
os.close(parent_fd)
|
|
85
|
+
except BaseException:
|
|
86
|
+
try:
|
|
87
|
+
os.unlink(temporary)
|
|
88
|
+
except OSError:
|
|
89
|
+
pass
|
|
90
|
+
raise
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _now() -> str:
|
|
94
|
+
return dt.datetime.now(dt.timezone.utc).isoformat()
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _epoch() -> float:
|
|
98
|
+
return time.time()
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _finite_epoch(value: object) -> bool:
|
|
102
|
+
try:
|
|
103
|
+
return (
|
|
104
|
+
isinstance(value, (int, float))
|
|
105
|
+
and not isinstance(value, bool)
|
|
106
|
+
and math.isfinite(float(value))
|
|
107
|
+
)
|
|
108
|
+
except (OverflowError, ValueError):
|
|
109
|
+
return False
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
@contextlib.contextmanager
|
|
113
|
+
def _campaign_lock(path: Path, timeout: float = 10.0):
|
|
114
|
+
"""Serialize campaign read-modify-write operations without changing the state path.
|
|
115
|
+
|
|
116
|
+
在 ``.audit-campaign.json.lock`` 上使用 ``fcntl.flock``(POSIX)或
|
|
117
|
+
``msvcrt.locking``(Windows)实现跨进程互斥;缺一不可时显式阻断而非
|
|
118
|
+
静默无锁。进程内再用线程锁避免同进程重入竞争。
|
|
119
|
+
"""
|
|
120
|
+
if not path.parent.is_dir():
|
|
121
|
+
raise CampaignError(f"输出目录不存在: {path.parent}")
|
|
122
|
+
lock_path = path.with_name(f".{path.name}.lock")
|
|
123
|
+
# 符号链接硬化:拒绝直接劫持的锁文件;父目录本身若为符号链接也视为劫持。
|
|
124
|
+
# 不逐层检查 /var 等系统级符号链接(/var -> private/var),避免在 macOS
|
|
125
|
+
# tempfile(/var/folders)下误报;与 bugx_paths 的 resolved-root 策略保持一致。
|
|
126
|
+
if lock_path.is_symlink():
|
|
127
|
+
raise CampaignError(f"拒绝使用符号链接锁文件: {lock_path}")
|
|
128
|
+
if lock_path.parent.is_symlink():
|
|
129
|
+
raise CampaignError(f"拒绝使用符号链接锁目录: {lock_path.parent}")
|
|
130
|
+
lock_key = str(lock_path.resolve(strict=False))
|
|
131
|
+
held_counts = getattr(_CAMPAIGN_LOCK_STATE, "counts", None)
|
|
132
|
+
if held_counts is None:
|
|
133
|
+
held_counts = {}
|
|
134
|
+
_CAMPAIGN_LOCK_STATE.counts = held_counts
|
|
135
|
+
depth = held_counts.get(lock_key, 0)
|
|
136
|
+
if depth > 0:
|
|
137
|
+
held_counts[lock_key] = depth + 1
|
|
138
|
+
try:
|
|
139
|
+
yield
|
|
140
|
+
finally:
|
|
141
|
+
held_counts[lock_key] = depth
|
|
142
|
+
return
|
|
143
|
+
with _CAMPAIGN_LOCK_THREAD:
|
|
144
|
+
# O_NOFOLLOW closes the check-then-open symlink race on POSIX. Keep
|
|
145
|
+
# the explicit checks above for platforms without this flag.
|
|
146
|
+
open_flags = os.O_RDWR | os.O_CREAT
|
|
147
|
+
nofollow = getattr(os, "O_NOFOLLOW", 0)
|
|
148
|
+
try:
|
|
149
|
+
descriptor = os.open(lock_path, open_flags | nofollow, 0o600)
|
|
150
|
+
except OSError as exc:
|
|
151
|
+
raise CampaignError(f"无法安全打开 campaign 锁: {lock_path}") from exc
|
|
152
|
+
handle = os.fdopen(descriptor, "a+")
|
|
153
|
+
_fcntl = None
|
|
154
|
+
_msvcrt = None
|
|
155
|
+
try:
|
|
156
|
+
try:
|
|
157
|
+
import fcntl as _fcntl_mod # type: ignore[import-not-found]
|
|
158
|
+
_fcntl = _fcntl_mod
|
|
159
|
+
except ImportError: # pragma: no cover - Windows fallback
|
|
160
|
+
_fcntl = None
|
|
161
|
+
try:
|
|
162
|
+
import msvcrt as _msvcrt_mod # type: ignore[import-not-found]
|
|
163
|
+
_msvcrt = _msvcrt_mod
|
|
164
|
+
except ImportError: # pragma: no cover - POSIX fallback
|
|
165
|
+
_msvcrt = None
|
|
166
|
+
if _fcntl is not None:
|
|
167
|
+
deadline = time.monotonic() + timeout
|
|
168
|
+
while True:
|
|
169
|
+
try:
|
|
170
|
+
_fcntl.flock(handle.fileno(), _fcntl.LOCK_EX | _fcntl.LOCK_NB)
|
|
171
|
+
break
|
|
172
|
+
except BlockingIOError:
|
|
173
|
+
if time.monotonic() >= deadline:
|
|
174
|
+
raise CampaignError("campaign 锁等待超时")
|
|
175
|
+
time.sleep(0.01)
|
|
176
|
+
elif _msvcrt is not None: # pragma: no cover - Windows
|
|
177
|
+
deadline = time.monotonic() + timeout
|
|
178
|
+
while True:
|
|
179
|
+
try:
|
|
180
|
+
_msvcrt.locking(handle.fileno(), _msvcrt.LK_NBLCK, 1)
|
|
181
|
+
break
|
|
182
|
+
except OSError:
|
|
183
|
+
if time.monotonic() >= deadline:
|
|
184
|
+
raise CampaignError("campaign 锁等待超时")
|
|
185
|
+
time.sleep(0.01)
|
|
186
|
+
else: # pragma: no cover - 无任何可用锁原语
|
|
187
|
+
raise CampaignError("campaign 锁在当前平台不可用(fcntl 和 msvcrt 均缺失),拒绝并发不安全写")
|
|
188
|
+
held_counts[lock_key] = 1
|
|
189
|
+
try:
|
|
190
|
+
yield
|
|
191
|
+
finally:
|
|
192
|
+
held_counts.pop(lock_key, None)
|
|
193
|
+
finally:
|
|
194
|
+
try:
|
|
195
|
+
if _fcntl is not None:
|
|
196
|
+
_fcntl.flock(handle.fileno(), _fcntl.LOCK_UN)
|
|
197
|
+
elif _msvcrt is not None:
|
|
198
|
+
try:
|
|
199
|
+
_msvcrt.locking(handle.fileno(), _msvcrt.LK_UNLCK, 1)
|
|
200
|
+
except OSError:
|
|
201
|
+
pass
|
|
202
|
+
finally:
|
|
203
|
+
handle.close()
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _repo_relative_path(value: object, field: str, root: Path | None) -> str:
|
|
207
|
+
if not isinstance(value, str) or not value or "\x00" in value:
|
|
208
|
+
raise CampaignError(f"{field}.path 必须是非空仓库内相对路径")
|
|
209
|
+
candidate = Path(value.replace("\\", "/"))
|
|
210
|
+
if candidate.is_absolute() or ".." in candidate.parts:
|
|
211
|
+
raise CampaignError(f"{field}.path 必须是仓库内相对路径")
|
|
212
|
+
if root is not None:
|
|
213
|
+
try:
|
|
214
|
+
(root / candidate).resolve(strict=False).relative_to(root.resolve())
|
|
215
|
+
except ValueError as exc:
|
|
216
|
+
raise CampaignError(f"{field}.path 越过仓库根目录") from exc
|
|
217
|
+
return candidate.as_posix()
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def _validate_evidence(item: object, field: str, root: Path | None) -> dict:
|
|
221
|
+
if not isinstance(item, dict):
|
|
222
|
+
raise CampaignError(f"{field} 必须是结构化对象,不能是任意字符串")
|
|
223
|
+
kind = item.get("kind", item.get("type"))
|
|
224
|
+
if not isinstance(kind, str) or kind not in EVIDENCE_KINDS:
|
|
225
|
+
raise CampaignError(f"{field}.kind 必须是 {sorted(EVIDENCE_KINDS)} 之一")
|
|
226
|
+
common_fields = {"kind", "type"}
|
|
227
|
+
kind_fields = {
|
|
228
|
+
"source": {"path", "line", "column"},
|
|
229
|
+
"test": {
|
|
230
|
+
"command", "result", "exit_code", "artifact_path", "artifact_sha256",
|
|
231
|
+
"target_fingerprint", "observed_at", "worker_id", "status", "timestamp",
|
|
232
|
+
"run_id", "round_no", "lease_id",
|
|
233
|
+
},
|
|
234
|
+
"command": {
|
|
235
|
+
"command", "result", "exit_code", "artifact_path", "artifact_sha256",
|
|
236
|
+
"target_fingerprint", "observed_at", "worker_id", "status", "timestamp",
|
|
237
|
+
"run_id", "round_no", "lease_id",
|
|
238
|
+
},
|
|
239
|
+
"finding": {"id", "finding_id", "path", "line", "column"},
|
|
240
|
+
}[kind]
|
|
241
|
+
allowed = common_fields | kind_fields
|
|
242
|
+
unknown = sorted(set(item) - allowed)
|
|
243
|
+
if unknown:
|
|
244
|
+
raise CampaignError(f"{field} 含未知字段: {', '.join(unknown)}")
|
|
245
|
+
if any(isinstance(value, (dict, list, tuple, set))
|
|
246
|
+
for key, value in item.items() if key in allowed):
|
|
247
|
+
raise CampaignError(f"{field} 字段值不能是嵌套对象或数组")
|
|
248
|
+
normalized = {
|
|
249
|
+
key: value for key, value in item.items()
|
|
250
|
+
if key in allowed and key != "type"
|
|
251
|
+
}
|
|
252
|
+
normalized["kind"] = kind
|
|
253
|
+
if kind == "source":
|
|
254
|
+
normalized["path"] = _repo_relative_path(item.get("path"), field, root)
|
|
255
|
+
line = item.get("line")
|
|
256
|
+
if not isinstance(line, int) or isinstance(line, bool) or line < 1:
|
|
257
|
+
raise CampaignError(f"{field}.line 必须是正整数")
|
|
258
|
+
if "column" in item and (
|
|
259
|
+
not isinstance(item["column"], int) or isinstance(item["column"], bool)
|
|
260
|
+
or item["column"] < 1
|
|
261
|
+
):
|
|
262
|
+
raise CampaignError(f"{field}.column 必须是正整数")
|
|
263
|
+
elif kind in {"test", "command"}:
|
|
264
|
+
command = item.get("command")
|
|
265
|
+
result = item.get("result")
|
|
266
|
+
if not isinstance(command, str) or not command.strip() or "\x00" in command:
|
|
267
|
+
raise CampaignError(f"{field}.command 必须是非空字符串")
|
|
268
|
+
if not isinstance(result, str) or result not in EVIDENCE_RESULTS:
|
|
269
|
+
raise CampaignError(f"{field}.result 必须是 {sorted(EVIDENCE_RESULTS)} 之一")
|
|
270
|
+
else:
|
|
271
|
+
finding_id = item.get("id", item.get("finding_id"))
|
|
272
|
+
if not isinstance(finding_id, str) or not EVIDENCE_ID_RE.fullmatch(finding_id):
|
|
273
|
+
raise CampaignError(f"{field}.id 必须是有效 finding ID")
|
|
274
|
+
normalized.pop("finding_id", None)
|
|
275
|
+
normalized["id"] = finding_id
|
|
276
|
+
return normalized
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def _validate_evidence_list(value: object, field: str, root: Path | None) -> list[dict]:
|
|
280
|
+
if not isinstance(value, list):
|
|
281
|
+
raise CampaignError(f"{field} 必须是数组")
|
|
282
|
+
return [_validate_evidence(item, f"{field}[{index}]", root)
|
|
283
|
+
for index, item in enumerate(value)]
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def _validate_asset(item: object, field: str, *, source: str) -> dict:
|
|
287
|
+
"""Validate an opaque test-asset reference; never accept its secret value."""
|
|
288
|
+
if not isinstance(item, dict):
|
|
289
|
+
raise CampaignError(f"{field} 必须是结构化对象")
|
|
290
|
+
forbidden = sorted(set(item) & ASSET_FORBIDDEN_FIELDS)
|
|
291
|
+
if forbidden:
|
|
292
|
+
raise CampaignError(f"{field} 含禁止的秘密字段: {', '.join(forbidden)}")
|
|
293
|
+
allowed = {
|
|
294
|
+
"asset_id", "kind", "source", "locator", "sensitivity",
|
|
295
|
+
"expires_at", "revoked",
|
|
296
|
+
}
|
|
297
|
+
unknown = sorted(set(item) - allowed)
|
|
298
|
+
if unknown:
|
|
299
|
+
raise CampaignError(f"{field} 含未知字段: {', '.join(unknown)}")
|
|
300
|
+
asset_id = item.get("asset_id")
|
|
301
|
+
if not isinstance(asset_id, str) or not ASSET_ID_RE.fullmatch(asset_id):
|
|
302
|
+
raise CampaignError(f"{field}.asset_id 必须是有效资产 ID")
|
|
303
|
+
kind = item.get("kind")
|
|
304
|
+
if not isinstance(kind, str) or kind not in ASSET_KINDS:
|
|
305
|
+
raise CampaignError(f"{field}.kind 必须是 {sorted(ASSET_KINDS)} 之一")
|
|
306
|
+
sensitivity = item.get("sensitivity", "internal")
|
|
307
|
+
if not isinstance(sensitivity, str) or sensitivity not in ASSET_SENSITIVITIES:
|
|
308
|
+
raise CampaignError(
|
|
309
|
+
f"{field}.sensitivity 必须是 {sorted(ASSET_SENSITIVITIES)} 之一"
|
|
310
|
+
)
|
|
311
|
+
normalized = {
|
|
312
|
+
"asset_id": asset_id,
|
|
313
|
+
"kind": kind,
|
|
314
|
+
"sensitivity": sensitivity,
|
|
315
|
+
}
|
|
316
|
+
if source == "consumed":
|
|
317
|
+
asset_source = item.get("source")
|
|
318
|
+
if not isinstance(asset_source, str) or asset_source not in ASSET_SOURCES:
|
|
319
|
+
raise CampaignError(
|
|
320
|
+
f"{field}.source 必须是 {sorted(ASSET_SOURCES)} 之一"
|
|
321
|
+
)
|
|
322
|
+
normalized["source"] = asset_source
|
|
323
|
+
if asset_source == "unit" and "sensitivity" not in item:
|
|
324
|
+
normalized.pop("sensitivity", None)
|
|
325
|
+
locator = item.get("locator")
|
|
326
|
+
if asset_source == "external":
|
|
327
|
+
if (not isinstance(locator, str)
|
|
328
|
+
or not ASSET_LOCATOR_RE.fullmatch(locator)
|
|
329
|
+
or not locator.startswith("env:")):
|
|
330
|
+
raise CampaignError(
|
|
331
|
+
f"{field}.locator 必须是受控 env:BUGX_* 引用"
|
|
332
|
+
)
|
|
333
|
+
elif locator is not None and (
|
|
334
|
+
not isinstance(locator, str) or not ASSET_LOCATOR_RE.fullmatch(locator)
|
|
335
|
+
):
|
|
336
|
+
raise CampaignError(f"{field}.locator 必须是 runtime:<id> 或 env:BUGX_* 引用")
|
|
337
|
+
if locator is not None:
|
|
338
|
+
normalized["locator"] = locator
|
|
339
|
+
else:
|
|
340
|
+
if "source" in item:
|
|
341
|
+
raise CampaignError(f"{field}.source 只允许出现在 consumed 资产")
|
|
342
|
+
locator = item.get("locator")
|
|
343
|
+
if not isinstance(locator, str) or not ASSET_LOCATOR_RE.fullmatch(locator):
|
|
344
|
+
raise CampaignError(
|
|
345
|
+
f"{field}.locator 必须是 runtime:<id> 或 env:BUGX_* 引用"
|
|
346
|
+
)
|
|
347
|
+
normalized["locator"] = locator
|
|
348
|
+
expires_at = item.get("expires_at")
|
|
349
|
+
if expires_at is not None:
|
|
350
|
+
if not isinstance(expires_at, str) or not expires_at.strip():
|
|
351
|
+
raise CampaignError(f"{field}.expires_at 必须是 ISO-8601 字符串")
|
|
352
|
+
try:
|
|
353
|
+
dt.datetime.fromisoformat(expires_at.replace("Z", "+00:00"))
|
|
354
|
+
except ValueError as exc:
|
|
355
|
+
raise CampaignError(f"{field}.expires_at 不是有效 ISO-8601 时间") from exc
|
|
356
|
+
normalized["expires_at"] = expires_at
|
|
357
|
+
revoked = item.get("revoked", False)
|
|
358
|
+
if not isinstance(revoked, bool):
|
|
359
|
+
raise CampaignError(f"{field}.revoked 必须是布尔值")
|
|
360
|
+
normalized["revoked"] = revoked
|
|
361
|
+
return normalized
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
def _validate_resources(value: object, field: str) -> dict[str, list[dict]]:
|
|
365
|
+
if value is None:
|
|
366
|
+
value = {}
|
|
367
|
+
if not isinstance(value, dict):
|
|
368
|
+
raise CampaignError(f"{field} 必须是对象")
|
|
369
|
+
if set(value) - {"consumed", "produced"}:
|
|
370
|
+
raise CampaignError(f"{field} 只允许 consumed/produced")
|
|
371
|
+
consumed = value.get("consumed", [])
|
|
372
|
+
produced = value.get("produced", [])
|
|
373
|
+
if not isinstance(consumed, list) or not isinstance(produced, list):
|
|
374
|
+
raise CampaignError(f"{field}.consumed/produced 必须是数组")
|
|
375
|
+
normalized_consumed = [
|
|
376
|
+
_validate_asset(item, f"{field}.consumed[{index}]", source="consumed")
|
|
377
|
+
for index, item in enumerate(consumed)
|
|
378
|
+
]
|
|
379
|
+
normalized_produced = [
|
|
380
|
+
_validate_asset(item, f"{field}.produced[{index}]", source="produced")
|
|
381
|
+
for index, item in enumerate(produced)
|
|
382
|
+
]
|
|
383
|
+
consumed_ids = [item["asset_id"] for item in normalized_consumed]
|
|
384
|
+
produced_ids = [item["asset_id"] for item in normalized_produced]
|
|
385
|
+
if len(set(consumed_ids)) != len(consumed_ids):
|
|
386
|
+
raise CampaignError(f"{field}.consumed asset_id 不能重复")
|
|
387
|
+
if len(set(produced_ids)) != len(produced_ids):
|
|
388
|
+
raise CampaignError(f"{field}.produced asset_id 不能重复")
|
|
389
|
+
if set(consumed_ids) & set(produced_ids):
|
|
390
|
+
raise CampaignError(f"{field} 同一 Unit 不能同时消费并生产同一资产")
|
|
391
|
+
return {"consumed": normalized_consumed, "produced": normalized_produced}
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
def _validate_dependency_graph(units: list[dict]) -> dict[str, list[str]]:
|
|
395
|
+
by_scope = {unit["scope"]: unit for unit in units}
|
|
396
|
+
graph: dict[str, list[str]] = {}
|
|
397
|
+
for unit in units:
|
|
398
|
+
value = unit.get("prerequisites", [])
|
|
399
|
+
if not isinstance(value, list):
|
|
400
|
+
raise CampaignError(f"{unit['scope']}.prerequisites 必须是数组")
|
|
401
|
+
if any(not isinstance(item, str) or not item for item in value):
|
|
402
|
+
raise CampaignError(f"{unit['scope']}.prerequisites 必须是非空字符串数组")
|
|
403
|
+
if len(set(value)) != len(value):
|
|
404
|
+
raise CampaignError(f"{unit['scope']}.prerequisites 不能重复")
|
|
405
|
+
unknown = sorted(set(value) - set(by_scope))
|
|
406
|
+
if unknown:
|
|
407
|
+
raise CampaignError(
|
|
408
|
+
f"{unit['scope']}.prerequisites 引用未知 Unit: {', '.join(unknown)}"
|
|
409
|
+
)
|
|
410
|
+
if unit["scope"] in value:
|
|
411
|
+
raise CampaignError(f"{unit['scope']} 不能依赖自身")
|
|
412
|
+
graph[unit["scope"]] = list(value)
|
|
413
|
+
visiting: set[str] = set()
|
|
414
|
+
visited: set[str] = set()
|
|
415
|
+
|
|
416
|
+
def visit(scope: str) -> None:
|
|
417
|
+
if scope in visiting:
|
|
418
|
+
raise CampaignError("prerequisites 存在循环依赖")
|
|
419
|
+
if scope in visited:
|
|
420
|
+
return
|
|
421
|
+
visiting.add(scope)
|
|
422
|
+
for prerequisite in graph[scope]:
|
|
423
|
+
visit(prerequisite)
|
|
424
|
+
visiting.remove(scope)
|
|
425
|
+
visited.add(scope)
|
|
426
|
+
|
|
427
|
+
for scope in graph:
|
|
428
|
+
visit(scope)
|
|
429
|
+
return graph
|
|
430
|
+
|
|
431
|
+
|
|
432
|
+
def _asset_catalog(units: list[dict]) -> dict[str, tuple[str, dict]]:
|
|
433
|
+
catalog: dict[str, tuple[str, dict]] = {}
|
|
434
|
+
locator_catalog: dict[str, str] = {}
|
|
435
|
+
for unit in units:
|
|
436
|
+
for asset in unit["resources"]["produced"]:
|
|
437
|
+
asset_id = asset["asset_id"]
|
|
438
|
+
if asset_id in catalog:
|
|
439
|
+
raise CampaignError(
|
|
440
|
+
f"资产 {asset_id} 被多个 Unit 生产,无法确定唯一来源"
|
|
441
|
+
)
|
|
442
|
+
locator = asset["locator"]
|
|
443
|
+
prior_asset_id = locator_catalog.get(locator)
|
|
444
|
+
if prior_asset_id is not None:
|
|
445
|
+
raise CampaignError(
|
|
446
|
+
f"资产 locator {locator} 被多个 asset_id 共享: "
|
|
447
|
+
f"{prior_asset_id}, {asset_id}"
|
|
448
|
+
)
|
|
449
|
+
locator_catalog[locator] = asset_id
|
|
450
|
+
catalog[asset_id] = (unit["scope"], asset)
|
|
451
|
+
return catalog
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
def _dependency_closure(scope: str, graph: dict[str, list[str]]) -> set[str]:
|
|
455
|
+
found: set[str] = set()
|
|
456
|
+
pending = list(graph.get(scope, []))
|
|
457
|
+
while pending:
|
|
458
|
+
current = pending.pop()
|
|
459
|
+
if current in found:
|
|
460
|
+
continue
|
|
461
|
+
found.add(current)
|
|
462
|
+
pending.extend(graph.get(current, []))
|
|
463
|
+
return found
|
|
464
|
+
|
|
465
|
+
|
|
466
|
+
def _asset_expired(asset: dict, now: dt.datetime | None = None) -> bool:
|
|
467
|
+
expires_at = asset.get("expires_at")
|
|
468
|
+
if not expires_at:
|
|
469
|
+
return False
|
|
470
|
+
current = now or dt.datetime.now(dt.timezone.utc)
|
|
471
|
+
try:
|
|
472
|
+
expires = dt.datetime.fromisoformat(str(expires_at).replace("Z", "+00:00"))
|
|
473
|
+
except ValueError:
|
|
474
|
+
return True
|
|
475
|
+
if expires.tzinfo is None:
|
|
476
|
+
expires = expires.replace(tzinfo=dt.timezone.utc)
|
|
477
|
+
return expires <= current
|
|
478
|
+
|
|
479
|
+
|
|
480
|
+
def _asset_usable(asset: dict) -> bool:
|
|
481
|
+
"""Return whether the reference can be handed to a worker right now."""
|
|
482
|
+
if asset.get("revoked") or _asset_expired(asset):
|
|
483
|
+
return False
|
|
484
|
+
locator = asset.get("locator")
|
|
485
|
+
return not (
|
|
486
|
+
isinstance(locator, str)
|
|
487
|
+
and locator.startswith("env:")
|
|
488
|
+
and not os.environ.get(locator.removeprefix("env:"))
|
|
489
|
+
)
|
|
490
|
+
|
|
491
|
+
|
|
492
|
+
def _unit_blockers(unit: dict, by_scope: dict[str, dict], catalog: dict[str, tuple[str, dict]],
|
|
493
|
+
graph: dict[str, list[str]], _seen: set[str] | None = None) -> list[dict[str, str]]:
|
|
494
|
+
seen = _seen if _seen is not None else set()
|
|
495
|
+
blockers: list[dict[str, str]] = []
|
|
496
|
+
for prerequisite in graph.get(unit["scope"], []):
|
|
497
|
+
if not _unit_effectively_complete(by_scope[prerequisite], by_scope, catalog, graph, seen):
|
|
498
|
+
blockers.append({"kind": "prerequisite", "scope": prerequisite})
|
|
499
|
+
for asset in unit["resources"]["consumed"]:
|
|
500
|
+
source = asset["source"]
|
|
501
|
+
if asset.get("revoked"):
|
|
502
|
+
blockers.append({"kind": "asset_revoked", "asset_id": asset["asset_id"]})
|
|
503
|
+
continue
|
|
504
|
+
if _asset_expired(asset):
|
|
505
|
+
blockers.append({"kind": "asset_expired", "asset_id": asset["asset_id"]})
|
|
506
|
+
continue
|
|
507
|
+
if source == "external":
|
|
508
|
+
locator = asset["locator"]
|
|
509
|
+
if not os.environ.get(locator.removeprefix("env:")):
|
|
510
|
+
blockers.append({
|
|
511
|
+
"kind": "missing_external_asset", "asset_id": asset["asset_id"],
|
|
512
|
+
})
|
|
513
|
+
continue
|
|
514
|
+
producer_scope, produced = catalog[asset["asset_id"]]
|
|
515
|
+
if producer_scope not in _dependency_closure(unit["scope"], graph):
|
|
516
|
+
# This is normally rejected during validation; keep the runtime guard
|
|
517
|
+
# so callers using a hand-built payload cannot bypass the contract.
|
|
518
|
+
blockers.append({
|
|
519
|
+
"kind": "undeclared_asset_dependency", "asset_id": asset["asset_id"],
|
|
520
|
+
})
|
|
521
|
+
continue
|
|
522
|
+
if not _unit_effectively_complete(by_scope[producer_scope], by_scope, catalog, graph, seen):
|
|
523
|
+
blockers.append({
|
|
524
|
+
"kind": "asset_producer_incomplete", "asset_id": asset["asset_id"],
|
|
525
|
+
})
|
|
526
|
+
if produced.get("revoked"):
|
|
527
|
+
blockers.append({"kind": "asset_revoked", "asset_id": asset["asset_id"]})
|
|
528
|
+
elif _asset_expired(produced):
|
|
529
|
+
blockers.append({"kind": "asset_expired", "asset_id": asset["asset_id"]})
|
|
530
|
+
elif not _asset_usable(produced):
|
|
531
|
+
blockers.append({
|
|
532
|
+
"kind": "missing_produced_asset", "asset_id": asset["asset_id"],
|
|
533
|
+
})
|
|
534
|
+
return blockers
|
|
535
|
+
|
|
536
|
+
|
|
537
|
+
def _unit_effectively_complete(unit: dict, by_scope: dict[str, dict],
|
|
538
|
+
catalog: dict[str, tuple[str, dict]],
|
|
539
|
+
graph: dict[str, list[str]],
|
|
540
|
+
seen: set[str] | None = None) -> bool:
|
|
541
|
+
"""Completion also requires all declared prerequisites and assets to be usable."""
|
|
542
|
+
if not unit_complete(unit):
|
|
543
|
+
return False
|
|
544
|
+
active = seen if seen is not None else set()
|
|
545
|
+
scope = unit["scope"]
|
|
546
|
+
if scope in active:
|
|
547
|
+
return False
|
|
548
|
+
active.add(scope)
|
|
549
|
+
try:
|
|
550
|
+
return not _unit_blockers(unit, by_scope, catalog, graph, active)
|
|
551
|
+
finally:
|
|
552
|
+
active.remove(scope)
|
|
553
|
+
|
|
554
|
+
|
|
555
|
+
def _resource_context(unit: dict, catalog: dict[str, tuple[str, dict]]) -> list[dict]:
|
|
556
|
+
context: list[dict] = []
|
|
557
|
+
for asset in unit["resources"]["consumed"]:
|
|
558
|
+
if asset["source"] == "external":
|
|
559
|
+
locator = asset["locator"]
|
|
560
|
+
kind = asset["kind"]
|
|
561
|
+
sensitivity = asset["sensitivity"]
|
|
562
|
+
else:
|
|
563
|
+
_producer, produced = catalog[asset["asset_id"]]
|
|
564
|
+
locator = produced["locator"]
|
|
565
|
+
# 生产者元数据是权威值,避免消费方把 secret 资产降级为 public。
|
|
566
|
+
kind = produced["kind"]
|
|
567
|
+
sensitivity = produced["sensitivity"]
|
|
568
|
+
context.append({
|
|
569
|
+
"asset_id": asset["asset_id"], "kind": kind,
|
|
570
|
+
"sensitivity": sensitivity, "locator": locator,
|
|
571
|
+
})
|
|
572
|
+
return context
|
|
573
|
+
|
|
574
|
+
|
|
575
|
+
def _unit_view(unit: dict, by_scope: dict[str, dict], catalog: dict[str, tuple[str, dict]],
|
|
576
|
+
graph: dict[str, list[str]]) -> dict:
|
|
577
|
+
result = copy.deepcopy(unit)
|
|
578
|
+
blockers = _unit_blockers(unit, by_scope, catalog, graph)
|
|
579
|
+
result["dependency_status"] = {
|
|
580
|
+
"ready": not blockers, "blocked_by": blockers,
|
|
581
|
+
}
|
|
582
|
+
result["resource_context"] = _resource_context(unit, catalog)
|
|
583
|
+
return result
|
|
584
|
+
|
|
585
|
+
|
|
586
|
+
def _lease_active(lease: object, now: float) -> bool:
|
|
587
|
+
if not isinstance(lease, dict):
|
|
588
|
+
return False
|
|
589
|
+
expires_at = lease.get("expires_at")
|
|
590
|
+
return _finite_epoch(expires_at) and expires_at > now
|
|
591
|
+
|
|
592
|
+
|
|
593
|
+
def unit_complete(unit: dict) -> bool:
|
|
594
|
+
dimensions = unit["dimensions"]
|
|
595
|
+
return (
|
|
596
|
+
dimensions["enumerated"] is True
|
|
597
|
+
and dimensions["reviewed"] is True
|
|
598
|
+
and dimensions["dynamic"] in {"pass", "not_applicable"}
|
|
599
|
+
and dimensions["boundary"] in {"pass", "not_applicable"}
|
|
600
|
+
and bool(dimensions["evidence"])
|
|
601
|
+
and all(item.get("result") not in {"fail", "blocked"}
|
|
602
|
+
for item in dimensions["evidence"])
|
|
603
|
+
)
|
|
604
|
+
|
|
605
|
+
|
|
606
|
+
def _validate_session_id(value: object, field: str = "campaign.session_id") -> str:
|
|
607
|
+
if not isinstance(value, str) or not SESSION_ID_RE.fullmatch(value):
|
|
608
|
+
raise CampaignError(
|
|
609
|
+
f"{field} 必须是安全的非空 Session ID(仅允许字母、数字、._:-)"
|
|
610
|
+
)
|
|
611
|
+
return value
|
|
612
|
+
|
|
613
|
+
|
|
614
|
+
def _check_session_binding(payload: dict, expected_session_id: str | None) -> None:
|
|
615
|
+
"""Reject a campaign when the caller is operating another Session's state."""
|
|
616
|
+
stored = _validate_session_id(payload.get("session_id"))
|
|
617
|
+
if expected_session_id is None:
|
|
618
|
+
return
|
|
619
|
+
expected = _validate_session_id(expected_session_id, "expected_session_id")
|
|
620
|
+
if stored != expected:
|
|
621
|
+
raise CampaignError(
|
|
622
|
+
f"campaign Session 不匹配: expected={expected}, actual={stored}"
|
|
623
|
+
)
|
|
624
|
+
|
|
625
|
+
|
|
626
|
+
def validate_campaign(payload: dict, root: Path | None = None) -> list[dict]:
|
|
627
|
+
if payload.get("schema_version") != SCHEMA_VERSION:
|
|
628
|
+
raise CampaignError(
|
|
629
|
+
f"campaign.schema_version 必须为 {SCHEMA_VERSION};旧版本不兼容,请重新创建 campaign"
|
|
630
|
+
)
|
|
631
|
+
if not isinstance(payload.get("run_id"), str) or not payload["run_id"]:
|
|
632
|
+
raise CampaignError("campaign 缺 run_id")
|
|
633
|
+
_validate_session_id(payload.get("session_id"))
|
|
634
|
+
revision = payload.get("revision", 0)
|
|
635
|
+
if not isinstance(revision, int) or isinstance(revision, bool) or revision < 0:
|
|
636
|
+
raise CampaignError("campaign.revision 必须是非负整数")
|
|
637
|
+
if root is None and isinstance(payload.get("root"), str):
|
|
638
|
+
root = Path(payload["root"]).resolve()
|
|
639
|
+
units = payload.get("units")
|
|
640
|
+
if not isinstance(units, list) or not units:
|
|
641
|
+
raise CampaignError("campaign.units 必须是非空数组")
|
|
642
|
+
seen: set[str] = set()
|
|
643
|
+
for index, unit in enumerate(units, 1):
|
|
644
|
+
if not isinstance(unit, dict):
|
|
645
|
+
raise CampaignError(f"unit #{index} 必须是对象")
|
|
646
|
+
scope = unit.get("scope")
|
|
647
|
+
if not isinstance(scope, str) or not scope or scope in seen:
|
|
648
|
+
raise CampaignError(f"unit #{index} scope 缺失或重复")
|
|
649
|
+
seen.add(scope)
|
|
650
|
+
priority = unit.get("priority")
|
|
651
|
+
if not isinstance(priority, int) or isinstance(priority, bool) or priority < 0:
|
|
652
|
+
raise CampaignError(f"{scope} priority 必须是非负整数")
|
|
653
|
+
dimensions = unit.get("dimensions")
|
|
654
|
+
if not isinstance(dimensions, dict):
|
|
655
|
+
raise CampaignError(f"{scope} 缺 dimensions")
|
|
656
|
+
for field in ("enumerated", "reviewed"):
|
|
657
|
+
if not isinstance(dimensions.get(field), bool):
|
|
658
|
+
raise CampaignError(f"{scope} dimensions.{field} 必须是布尔值")
|
|
659
|
+
for field in ("dynamic", "boundary"):
|
|
660
|
+
if dimensions.get(field) not in EXECUTION_STATES:
|
|
661
|
+
raise CampaignError(f"{scope} dimensions.{field} 状态无效")
|
|
662
|
+
dimensions["evidence"] = _validate_evidence_list(
|
|
663
|
+
dimensions.get("evidence"), f"{scope}.dimensions.evidence", root,
|
|
664
|
+
)
|
|
665
|
+
lease = unit.get("lease")
|
|
666
|
+
if lease is not None:
|
|
667
|
+
if not isinstance(lease, dict) or not isinstance(lease.get("owner"), str) \
|
|
668
|
+
or not lease["owner"] or not isinstance(lease.get("token"), str) \
|
|
669
|
+
or not lease["token"] or not isinstance(lease.get("expires_at"), (int, float)) \
|
|
670
|
+
or not _finite_epoch(lease.get("expires_at")):
|
|
671
|
+
raise CampaignError(f"{scope}.lease 格式无效")
|
|
672
|
+
prerequisites = unit.get("prerequisites", [])
|
|
673
|
+
if not isinstance(prerequisites, list):
|
|
674
|
+
raise CampaignError(f"{scope}.prerequisites 必须是数组")
|
|
675
|
+
unit["prerequisites"] = list(prerequisites)
|
|
676
|
+
unit["resources"] = _validate_resources(
|
|
677
|
+
unit.get("resources"), f"{scope}.resources",
|
|
678
|
+
)
|
|
679
|
+
unit["status"] = "complete" if unit_complete(unit) else "pending"
|
|
680
|
+
graph = _validate_dependency_graph(units)
|
|
681
|
+
catalog = _asset_catalog(units)
|
|
682
|
+
for unit in units:
|
|
683
|
+
closure = _dependency_closure(unit["scope"], graph)
|
|
684
|
+
for asset in unit["resources"]["consumed"]:
|
|
685
|
+
if asset["source"] != "unit":
|
|
686
|
+
continue
|
|
687
|
+
produced = catalog.get(asset["asset_id"])
|
|
688
|
+
if produced is None:
|
|
689
|
+
raise CampaignError(
|
|
690
|
+
f"{unit['scope']} 消费未知资产: {asset['asset_id']}"
|
|
691
|
+
)
|
|
692
|
+
producer_scope, produced_asset = produced
|
|
693
|
+
if producer_scope not in closure:
|
|
694
|
+
raise CampaignError(
|
|
695
|
+
f"{unit['scope']} 消费资产 {asset['asset_id']} 但未声明其生产 Unit 为前置"
|
|
696
|
+
)
|
|
697
|
+
if produced_asset["kind"] != asset["kind"]:
|
|
698
|
+
raise CampaignError(
|
|
699
|
+
f"资产 {asset['asset_id']} 的 kind 与生产者不一致"
|
|
700
|
+
)
|
|
701
|
+
if (
|
|
702
|
+
"sensitivity" in asset
|
|
703
|
+
and asset["sensitivity"] != produced_asset["sensitivity"]
|
|
704
|
+
):
|
|
705
|
+
raise CampaignError(
|
|
706
|
+
f"资产 {asset['asset_id']} 的 sensitivity 与生产者不一致"
|
|
707
|
+
)
|
|
708
|
+
if "locator" in asset and asset["locator"] != produced_asset["locator"]:
|
|
709
|
+
raise CampaignError(
|
|
710
|
+
f"资产 {asset['asset_id']} 的 locator 与生产者不一致"
|
|
711
|
+
)
|
|
712
|
+
usage = payload.setdefault("asset_usage", {})
|
|
713
|
+
if not isinstance(usage, dict):
|
|
714
|
+
raise CampaignError("campaign.asset_usage 必须是对象")
|
|
715
|
+
for asset_id, count in usage.items():
|
|
716
|
+
if asset_id not in catalog:
|
|
717
|
+
raise CampaignError(f"campaign.asset_usage 引用未知资产: {asset_id}")
|
|
718
|
+
if not isinstance(count, int) or isinstance(count, bool) or count < 0:
|
|
719
|
+
raise CampaignError(f"campaign.asset_usage[{asset_id}] 必须是非负整数")
|
|
720
|
+
return units
|
|
721
|
+
|
|
722
|
+
|
|
723
|
+
def create_campaign(root: Path, base: str | None = None,
|
|
724
|
+
session_id: str | None = None) -> dict:
|
|
725
|
+
root = root.resolve()
|
|
726
|
+
session_id = _validate_session_id(session_id or str(uuid.uuid4()), "session_id")
|
|
727
|
+
priority_by_scope: dict[str, tuple[int, str]] = {}
|
|
728
|
+
if base:
|
|
729
|
+
incremental = project_graph.incremental_plan(root, base)
|
|
730
|
+
priority_by_scope = {
|
|
731
|
+
item["scope"]: (item["priority"], item["reason"])
|
|
732
|
+
for item in incremental["units"]
|
|
733
|
+
}
|
|
734
|
+
try:
|
|
735
|
+
audit_units = symbol_index.audit_units(root, strict=True)
|
|
736
|
+
except symbol_index.SourceDiscoveryError as exc:
|
|
737
|
+
raise CampaignError(str(exc)) from exc
|
|
738
|
+
unit_errors = [unit for unit in audit_units if unit.get("error")]
|
|
739
|
+
if unit_errors:
|
|
740
|
+
raise CampaignError(
|
|
741
|
+
"源码单元解析不完整,拒绝创建假完整任务队列: "
|
|
742
|
+
+ "; ".join(
|
|
743
|
+
f"{unit['path']}: {unit['error']}" for unit in unit_errors[:5]
|
|
744
|
+
)
|
|
745
|
+
)
|
|
746
|
+
units = []
|
|
747
|
+
for unit in audit_units:
|
|
748
|
+
priority, reason = priority_by_scope.get(unit["scope"], (20, "full-coverage"))
|
|
749
|
+
units.append({
|
|
750
|
+
"scope": unit["scope"],
|
|
751
|
+
"path": unit["path"],
|
|
752
|
+
"name": unit["name"],
|
|
753
|
+
"kind": unit["kind"],
|
|
754
|
+
"priority": priority,
|
|
755
|
+
"priority_reason": reason,
|
|
756
|
+
"status": "pending",
|
|
757
|
+
"prerequisites": [],
|
|
758
|
+
"resources": {"consumed": [], "produced": []},
|
|
759
|
+
"dimensions": {
|
|
760
|
+
"enumerated": True,
|
|
761
|
+
"reviewed": False,
|
|
762
|
+
"dynamic": "not_run",
|
|
763
|
+
"boundary": "not_run",
|
|
764
|
+
"evidence": [],
|
|
765
|
+
},
|
|
766
|
+
})
|
|
767
|
+
if not units:
|
|
768
|
+
raise CampaignError("没有发现可审计源码单元")
|
|
769
|
+
units.sort(key=lambda item: (-item["priority"], item["scope"]))
|
|
770
|
+
return {
|
|
771
|
+
"schema_version": SCHEMA_VERSION,
|
|
772
|
+
"run_id": str(uuid.uuid4()),
|
|
773
|
+
"session_id": session_id,
|
|
774
|
+
"created_at": _now(),
|
|
775
|
+
"updated_at": _now(),
|
|
776
|
+
"base": base,
|
|
777
|
+
"root": str(root),
|
|
778
|
+
"revision": 0,
|
|
779
|
+
"asset_usage": {},
|
|
780
|
+
"units": units,
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
|
|
784
|
+
def campaign_summary(payload: dict, *, expected_session_id: str | None = None) -> dict:
|
|
785
|
+
_check_session_binding(payload, expected_session_id)
|
|
786
|
+
units = validate_campaign(payload)
|
|
787
|
+
total = len(units)
|
|
788
|
+
by_scope = {unit["scope"]: unit for unit in units}
|
|
789
|
+
graph = _validate_dependency_graph(units)
|
|
790
|
+
catalog = _asset_catalog(units)
|
|
791
|
+
dimensions = {
|
|
792
|
+
"enumerated": sum(unit["dimensions"]["enumerated"] is True for unit in units),
|
|
793
|
+
"reviewed": sum(unit["dimensions"]["reviewed"] is True for unit in units),
|
|
794
|
+
"dynamic": sum(unit["dimensions"]["dynamic"] in {"pass", "not_applicable"}
|
|
795
|
+
for unit in units),
|
|
796
|
+
"boundary": sum(unit["dimensions"]["boundary"] in {"pass", "not_applicable"}
|
|
797
|
+
for unit in units),
|
|
798
|
+
"evidence": sum(bool(unit["dimensions"]["evidence"]) for unit in units),
|
|
799
|
+
}
|
|
800
|
+
complete = sum(
|
|
801
|
+
_unit_effectively_complete(unit, by_scope, catalog, graph) for unit in units
|
|
802
|
+
)
|
|
803
|
+
blocked_units = []
|
|
804
|
+
for unit in units:
|
|
805
|
+
if _unit_effectively_complete(unit, by_scope, catalog, graph):
|
|
806
|
+
continue
|
|
807
|
+
blockers = _unit_blockers(unit, by_scope, catalog, graph)
|
|
808
|
+
if blockers:
|
|
809
|
+
blocked_units.append({"scope": unit["scope"], "blocked_by": blockers})
|
|
810
|
+
produced = [asset for _scope, asset in catalog.values()]
|
|
811
|
+
available = sum(
|
|
812
|
+
_unit_effectively_complete(by_scope[scope], by_scope, catalog, graph)
|
|
813
|
+
and _asset_usable(asset)
|
|
814
|
+
for scope, asset in catalog.values()
|
|
815
|
+
)
|
|
816
|
+
consumed = [
|
|
817
|
+
asset for unit in units for asset in unit["resources"]["consumed"]
|
|
818
|
+
]
|
|
819
|
+
usage = payload.get("asset_usage", {})
|
|
820
|
+
reuse_count = sum(int(usage.get(asset_id, 0))
|
|
821
|
+
for asset_id in {asset["asset_id"] for asset in consumed})
|
|
822
|
+
reuse_rate = round(reuse_count / len(consumed) * 100, 1) if consumed else 0.0
|
|
823
|
+
return {
|
|
824
|
+
"run_id": payload["run_id"],
|
|
825
|
+
"session_id": payload["session_id"],
|
|
826
|
+
"complete": complete,
|
|
827
|
+
"total": total,
|
|
828
|
+
"percent": round(complete / total * 100, 1),
|
|
829
|
+
"blocked": len(blocked_units),
|
|
830
|
+
"blocked_units": blocked_units,
|
|
831
|
+
"dimensions": {
|
|
832
|
+
key: {"complete": value, "total": total,
|
|
833
|
+
"percent": round(value / total * 100, 1)}
|
|
834
|
+
for key, value in dimensions.items()
|
|
835
|
+
},
|
|
836
|
+
"asset_summary": {
|
|
837
|
+
"total_produced": len(produced),
|
|
838
|
+
"total_consumed": len(consumed),
|
|
839
|
+
"available": available,
|
|
840
|
+
"reuse_count": reuse_count,
|
|
841
|
+
"reuse_rate": reuse_rate,
|
|
842
|
+
},
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
|
|
846
|
+
def next_units(payload: dict, limit: int = 10, owner: str | None = None,
|
|
847
|
+
token: str | None = None, lease_seconds: float = DEFAULT_LEASE_SECONDS,
|
|
848
|
+
expected_session_id: str | None = None) \
|
|
849
|
+
-> list[dict]:
|
|
850
|
+
if owner is not None:
|
|
851
|
+
return claim_units(
|
|
852
|
+
payload, owner, limit, token, lease_seconds,
|
|
853
|
+
expected_session_id=expected_session_id,
|
|
854
|
+
)
|
|
855
|
+
if limit < 1:
|
|
856
|
+
raise CampaignError("limit 必须大于 0")
|
|
857
|
+
_check_session_binding(payload, expected_session_id)
|
|
858
|
+
units = validate_campaign(payload)
|
|
859
|
+
by_scope = {unit["scope"]: unit for unit in units}
|
|
860
|
+
graph = _validate_dependency_graph(units)
|
|
861
|
+
catalog = _asset_catalog(units)
|
|
862
|
+
now = _epoch()
|
|
863
|
+
pending = [
|
|
864
|
+
unit for unit in units
|
|
865
|
+
if not _unit_effectively_complete(unit, by_scope, catalog, graph)
|
|
866
|
+
and not _unit_blockers(unit, by_scope, catalog, graph)
|
|
867
|
+
and not _lease_active(unit.get("lease"), now)
|
|
868
|
+
]
|
|
869
|
+
pending.sort(key=lambda item: (-item["priority"], item["scope"]))
|
|
870
|
+
return [_unit_view(unit, by_scope, catalog, graph) for unit in pending[:limit]]
|
|
871
|
+
|
|
872
|
+
|
|
873
|
+
def claim_units(payload: dict, owner: str, limit: int = 10,
|
|
874
|
+
token: str | None = None,
|
|
875
|
+
lease_seconds: float = DEFAULT_LEASE_SECONDS,
|
|
876
|
+
*, expected_session_id: str | None = None) -> list[dict]:
|
|
877
|
+
if not isinstance(owner, str) or not owner.strip() or "\x00" in owner:
|
|
878
|
+
raise CampaignError("claim owner 必须是非空字符串")
|
|
879
|
+
if token is not None and (not isinstance(token, str) or not token or "\x00" in token):
|
|
880
|
+
raise CampaignError("claim token 必须是非空字符串")
|
|
881
|
+
if limit < 1:
|
|
882
|
+
raise CampaignError("limit 必须大于 0")
|
|
883
|
+
if not isinstance(lease_seconds, (int, float)) or isinstance(lease_seconds, bool) \
|
|
884
|
+
or not 1 <= lease_seconds <= MAX_LEASE_SECONDS:
|
|
885
|
+
raise CampaignError(f"lease_seconds 必须在 1..{MAX_LEASE_SECONDS}")
|
|
886
|
+
_check_session_binding(payload, expected_session_id)
|
|
887
|
+
units = validate_campaign(payload)
|
|
888
|
+
by_scope = {unit["scope"]: unit for unit in units}
|
|
889
|
+
graph = _validate_dependency_graph(units)
|
|
890
|
+
catalog = _asset_catalog(units)
|
|
891
|
+
now = _epoch()
|
|
892
|
+
claim_token = token or uuid.uuid4().hex
|
|
893
|
+
claimed: list[dict] = []
|
|
894
|
+
newly_claimed: list[dict] = []
|
|
895
|
+
for unit in sorted(units, key=lambda item: (-item["priority"], item["scope"])):
|
|
896
|
+
if _unit_effectively_complete(unit, by_scope, catalog, graph):
|
|
897
|
+
continue
|
|
898
|
+
if _unit_blockers(unit, by_scope, catalog, graph):
|
|
899
|
+
continue
|
|
900
|
+
lease = unit.get("lease")
|
|
901
|
+
if _lease_active(lease, now):
|
|
902
|
+
if lease["owner"] == owner and lease["token"] == claim_token:
|
|
903
|
+
claimed.append(_unit_view(unit, by_scope, catalog, graph))
|
|
904
|
+
continue
|
|
905
|
+
if lease is not None:
|
|
906
|
+
unit.pop("lease", None)
|
|
907
|
+
unit["lease"] = {
|
|
908
|
+
"owner": owner,
|
|
909
|
+
"token": claim_token,
|
|
910
|
+
"expires_at": round(now + float(lease_seconds), 3),
|
|
911
|
+
}
|
|
912
|
+
newly_claimed.append(unit)
|
|
913
|
+
if len(claimed) + len(newly_claimed) >= limit:
|
|
914
|
+
break
|
|
915
|
+
# The newly claimed list is separate from the returned views so an
|
|
916
|
+
# idempotent retry with the same owner/token does not inflate usage stats.
|
|
917
|
+
for unit in newly_claimed:
|
|
918
|
+
for asset in unit["resources"]["consumed"]:
|
|
919
|
+
asset_id = asset["asset_id"]
|
|
920
|
+
payload["asset_usage"][asset_id] = payload["asset_usage"].get(asset_id, 0) + 1
|
|
921
|
+
if newly_claimed:
|
|
922
|
+
payload["revision"] = int(payload.get("revision", 0)) + 1
|
|
923
|
+
payload["updated_at"] = _now()
|
|
924
|
+
claimed.extend(
|
|
925
|
+
_unit_view(unit, by_scope, catalog, graph) for unit in newly_claimed
|
|
926
|
+
)
|
|
927
|
+
return claimed
|
|
928
|
+
|
|
929
|
+
|
|
930
|
+
def update_unit(payload: dict, scope: str, reviewed: bool | None = None,
|
|
931
|
+
dynamic: str | None = None, boundary: str | None = None,
|
|
932
|
+
evidence: list[dict] | None = None, owner: str | None = None,
|
|
933
|
+
token: str | None = None, expected_revision: int | None = None,
|
|
934
|
+
prerequisites: list[str] | None = None,
|
|
935
|
+
resources: dict | None = None,
|
|
936
|
+
produce_assets: list[dict] | None = None,
|
|
937
|
+
consume_assets: list[dict] | None = None,
|
|
938
|
+
*, expected_session_id: str | None = None) -> dict:
|
|
939
|
+
_check_session_binding(payload, expected_session_id)
|
|
940
|
+
units = validate_campaign(payload)
|
|
941
|
+
revision = int(payload.get("revision", 0))
|
|
942
|
+
if expected_revision is not None and expected_revision != revision:
|
|
943
|
+
raise CampaignError(
|
|
944
|
+
f"campaign revision 冲突: expected={expected_revision}, actual={revision}"
|
|
945
|
+
)
|
|
946
|
+
target = next((unit for unit in units if unit["scope"] == scope), None)
|
|
947
|
+
if target is None:
|
|
948
|
+
raise CampaignError(f"未知 scope: {scope}")
|
|
949
|
+
lease = target.get("lease")
|
|
950
|
+
if owner is not None or token is not None:
|
|
951
|
+
if not isinstance(owner, str) or not owner or not isinstance(token, str) or not token:
|
|
952
|
+
raise CampaignError("带 owner/token 更新时必须同时提供二者")
|
|
953
|
+
if not _lease_active(lease, _epoch()) or lease["owner"] != owner \
|
|
954
|
+
or lease["token"] != token:
|
|
955
|
+
raise CampaignError("unit lease 不存在、已过期或不属于当前 owner/token")
|
|
956
|
+
candidate = copy.deepcopy(payload)
|
|
957
|
+
candidate_units = validate_campaign(candidate)
|
|
958
|
+
candidate_target = next(item for item in candidate_units if item["scope"] == scope)
|
|
959
|
+
candidate_dimensions = candidate_target["dimensions"]
|
|
960
|
+
if reviewed is not None:
|
|
961
|
+
candidate_dimensions["reviewed"] = reviewed
|
|
962
|
+
for field, value in (("dynamic", dynamic), ("boundary", boundary)):
|
|
963
|
+
if value is not None:
|
|
964
|
+
if value not in EXECUTION_STATES:
|
|
965
|
+
raise CampaignError(f"{field} 状态无效: {value}")
|
|
966
|
+
candidate_dimensions[field] = value
|
|
967
|
+
if evidence:
|
|
968
|
+
checked = _validate_evidence_list(
|
|
969
|
+
evidence, f"{scope}.dimensions.evidence", Path(payload["root"]).resolve()
|
|
970
|
+
if isinstance(payload.get("root"), str) else None,
|
|
971
|
+
)
|
|
972
|
+
merged = [*candidate_dimensions["evidence"], *checked]
|
|
973
|
+
candidate_dimensions["evidence"] = list({
|
|
974
|
+
json.dumps(item, ensure_ascii=False, sort_keys=True): item for item in merged
|
|
975
|
+
}.values())
|
|
976
|
+
if prerequisites is not None:
|
|
977
|
+
candidate_target["prerequisites"] = copy.deepcopy(prerequisites)
|
|
978
|
+
if resources is not None:
|
|
979
|
+
candidate_target["resources"] = copy.deepcopy(resources)
|
|
980
|
+
if produce_assets or consume_assets:
|
|
981
|
+
current_resources = candidate_target.setdefault(
|
|
982
|
+
"resources", {"consumed": [], "produced": []},
|
|
983
|
+
)
|
|
984
|
+
if produce_assets:
|
|
985
|
+
current_resources.setdefault("produced", []).extend(copy.deepcopy(produce_assets))
|
|
986
|
+
if consume_assets:
|
|
987
|
+
current_resources.setdefault("consumed", []).extend(copy.deepcopy(consume_assets))
|
|
988
|
+
candidate_target["status"] = "complete" if unit_complete(candidate_target) else "pending"
|
|
989
|
+
if candidate_target["status"] == "complete":
|
|
990
|
+
candidate_target.pop("lease", None)
|
|
991
|
+
candidate["revision"] = revision + 1
|
|
992
|
+
candidate["updated_at"] = _now()
|
|
993
|
+
validate_campaign(candidate)
|
|
994
|
+
payload.clear()
|
|
995
|
+
payload.update(candidate)
|
|
996
|
+
return next(item for item in payload["units"] if item["scope"] == scope)
|
|
997
|
+
|
|
998
|
+
|
|
999
|
+
def reprioritize(payload: dict, findings_payload: dict, *, bump: int = 15,
|
|
1000
|
+
max_priority: int = 100,
|
|
1001
|
+
expected_session_id: str | None = None) -> dict:
|
|
1002
|
+
"""热点再排序:按本轮 findings 的证据路径提升同路径/同目录单元的优先级。
|
|
1003
|
+
|
|
1004
|
+
静态优先级在登记时固定,热点无法在运行中扩散——模块 A 挖到 bug 后,
|
|
1005
|
+
同根因的兄弟模块大概率也有问题,却仍按初始顺序排队。本函数把
|
|
1006
|
+
findings 的 evidence 路径(及其父目录)映射到未完成单元,有限度地
|
|
1007
|
+
提升 priority 并记录可审计的 priority_history;已 complete 的单元不动。
|
|
1008
|
+
"""
|
|
1009
|
+
if not isinstance(bump, int) or isinstance(bump, bool) or not 1 <= bump <= 50:
|
|
1010
|
+
raise CampaignError("bump 必须在 1..50")
|
|
1011
|
+
if not isinstance(max_priority, int) or isinstance(max_priority, bool) or max_priority < 1:
|
|
1012
|
+
raise CampaignError("max_priority 必须是正整数")
|
|
1013
|
+
_check_session_binding(payload, expected_session_id)
|
|
1014
|
+
findings = findings_payload.get("findings")
|
|
1015
|
+
if not isinstance(findings, list):
|
|
1016
|
+
raise CampaignError("findings_payload.findings 必须是数组")
|
|
1017
|
+
hot_paths: set[str] = set()
|
|
1018
|
+
for finding in findings:
|
|
1019
|
+
if not isinstance(finding, dict):
|
|
1020
|
+
continue
|
|
1021
|
+
confirmation = finding.get("confirmation")
|
|
1022
|
+
if isinstance(confirmation, dict) and confirmation.get("state") == "rejected":
|
|
1023
|
+
continue
|
|
1024
|
+
for evidence in finding.get("evidence", []):
|
|
1025
|
+
if isinstance(evidence, dict) and isinstance(evidence.get("path"), str):
|
|
1026
|
+
normalized = evidence["path"].replace("\\", "/").lstrip("./")
|
|
1027
|
+
hot_paths.add(normalized)
|
|
1028
|
+
parent = normalized.rsplit("/", 1)[0]
|
|
1029
|
+
if parent:
|
|
1030
|
+
hot_paths.add(parent)
|
|
1031
|
+
if not hot_paths:
|
|
1032
|
+
return {"status": "no-op", "boosted": [], "hot_paths": [],
|
|
1033
|
+
"source_findings": len(findings)}
|
|
1034
|
+
units = validate_campaign(payload)
|
|
1035
|
+
boosted: list[dict] = []
|
|
1036
|
+
for unit in units:
|
|
1037
|
+
if unit["status"] == "complete":
|
|
1038
|
+
continue
|
|
1039
|
+
unit_path = str(unit.get("path", "")).replace("\\", "/").lstrip("./")
|
|
1040
|
+
matched = sorted(
|
|
1041
|
+
path for path in hot_paths
|
|
1042
|
+
if unit_path == path or unit_path.startswith(path + "/") or path.startswith(unit_path + "/")
|
|
1043
|
+
)
|
|
1044
|
+
if not matched:
|
|
1045
|
+
continue
|
|
1046
|
+
before = unit["priority"]
|
|
1047
|
+
unit["priority"] = min(before + bump, max_priority)
|
|
1048
|
+
unit["priority_reason"] = "hot-streak:" + ",".join(matched[:3])
|
|
1049
|
+
boosted.append({
|
|
1050
|
+
"scope": unit["scope"], "before": before, "after": unit["priority"],
|
|
1051
|
+
"matched": matched[:3],
|
|
1052
|
+
})
|
|
1053
|
+
if boosted:
|
|
1054
|
+
history = payload.setdefault("priority_history", [])
|
|
1055
|
+
if not isinstance(history, list):
|
|
1056
|
+
raise CampaignError("campaign.priority_history 必须是数组")
|
|
1057
|
+
history.append({
|
|
1058
|
+
"at": _now(),
|
|
1059
|
+
"bump": bump,
|
|
1060
|
+
"source_findings": len(findings),
|
|
1061
|
+
"hot_paths": sorted(hot_paths)[:32],
|
|
1062
|
+
"boosted_scopes": [item["scope"] for item in boosted],
|
|
1063
|
+
})
|
|
1064
|
+
payload["revision"] = int(payload.get("revision", 0)) + 1
|
|
1065
|
+
payload["updated_at"] = _now()
|
|
1066
|
+
units.sort(key=lambda item: (-item["priority"], item["scope"]))
|
|
1067
|
+
return {
|
|
1068
|
+
"status": "boosted" if boosted else "no-op",
|
|
1069
|
+
"boosted": boosted,
|
|
1070
|
+
"hot_paths": sorted(hot_paths),
|
|
1071
|
+
"source_findings": len(findings),
|
|
1072
|
+
}
|
|
1073
|
+
|
|
1074
|
+
|
|
1075
|
+
def _load(path: Path) -> dict:
|
|
1076
|
+
try:
|
|
1077
|
+
value = json.loads(path.read_text(encoding="utf-8"))
|
|
1078
|
+
except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc:
|
|
1079
|
+
raise CampaignError(f"无法读取 campaign: {exc}") from exc
|
|
1080
|
+
if not isinstance(value, dict):
|
|
1081
|
+
raise CampaignError("campaign 根节点必须是对象")
|
|
1082
|
+
return value
|
|
1083
|
+
|
|
1084
|
+
|
|
1085
|
+
def _parse_evidence_args(values: list[str]) -> list[dict]:
|
|
1086
|
+
parsed: list[dict] = []
|
|
1087
|
+
for value in values:
|
|
1088
|
+
try:
|
|
1089
|
+
item = json.loads(value)
|
|
1090
|
+
except json.JSONDecodeError as exc:
|
|
1091
|
+
raise CampaignError("--evidence 必须是 JSON 结构化对象") from exc
|
|
1092
|
+
if not isinstance(item, dict):
|
|
1093
|
+
raise CampaignError("--evidence 必须是 JSON 结构化对象")
|
|
1094
|
+
parsed.append(item)
|
|
1095
|
+
return parsed
|
|
1096
|
+
|
|
1097
|
+
|
|
1098
|
+
def _parse_resource_args(values: list[str], option: str) -> list[dict]:
|
|
1099
|
+
parsed = []
|
|
1100
|
+
for value in values:
|
|
1101
|
+
try:
|
|
1102
|
+
item = json.loads(value)
|
|
1103
|
+
except json.JSONDecodeError as exc:
|
|
1104
|
+
raise CampaignError(f"{option} 必须是 JSON 结构化对象") from exc
|
|
1105
|
+
if not isinstance(item, dict):
|
|
1106
|
+
raise CampaignError(f"{option} 必须是 JSON 结构化对象")
|
|
1107
|
+
parsed.append(item)
|
|
1108
|
+
return parsed
|
|
1109
|
+
|
|
1110
|
+
|
|
1111
|
+
def main(argv: list[str] | None = None) -> int:
|
|
1112
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
1113
|
+
parser.add_argument("command", choices=("create", "status", "next", "claim", "update",
|
|
1114
|
+
"reprioritize"))
|
|
1115
|
+
parser.add_argument("--root", type=Path, default=Path.cwd())
|
|
1116
|
+
parser.add_argument("--campaign", type=Path,
|
|
1117
|
+
help="campaign 文件;省略时使用 .bugx/sessions/<session-id>/audit-campaign.json")
|
|
1118
|
+
parser.add_argument("--session-id",
|
|
1119
|
+
help="当前 Session ID;所有非 create 操作必须显式提供")
|
|
1120
|
+
parser.add_argument("--base")
|
|
1121
|
+
parser.add_argument("--scope")
|
|
1122
|
+
parser.add_argument("--findings", type=Path,
|
|
1123
|
+
help="reprioritize 使用:本轮 findings JSON,驱动热点再排序")
|
|
1124
|
+
parser.add_argument("--reviewed", choices=("true", "false"))
|
|
1125
|
+
parser.add_argument("--dynamic", choices=sorted(EXECUTION_STATES))
|
|
1126
|
+
parser.add_argument("--boundary", choices=sorted(EXECUTION_STATES))
|
|
1127
|
+
parser.add_argument("--evidence", action="append", default=[])
|
|
1128
|
+
parser.add_argument("--prerequisite", action="append", default=[],
|
|
1129
|
+
help="update 使用:前置 Unit scope,可重复")
|
|
1130
|
+
parser.add_argument("--produce-asset", action="append", default=[],
|
|
1131
|
+
help="update 使用:安全资产引用 JSON,不得含秘密值")
|
|
1132
|
+
parser.add_argument("--consume-asset", action="append", default=[],
|
|
1133
|
+
help="update 使用:消费资产引用 JSON,不得含秘密值")
|
|
1134
|
+
parser.add_argument("--limit", type=int, default=10)
|
|
1135
|
+
parser.add_argument("--owner")
|
|
1136
|
+
parser.add_argument("--token")
|
|
1137
|
+
parser.add_argument("--lease-seconds", type=float, default=DEFAULT_LEASE_SECONDS)
|
|
1138
|
+
parser.add_argument("--revision", type=int)
|
|
1139
|
+
parser.add_argument("--bump", type=int, default=15,
|
|
1140
|
+
help="reprioritize 单次优先级提升量(默认 15,上限 50)")
|
|
1141
|
+
parser.add_argument("--json", action="store_true")
|
|
1142
|
+
args = parser.parse_args(argv)
|
|
1143
|
+
try:
|
|
1144
|
+
session_id = args.session_id
|
|
1145
|
+
if args.command == "create":
|
|
1146
|
+
session_id = _validate_session_id(
|
|
1147
|
+
session_id or str(uuid.uuid4()), "session_id",
|
|
1148
|
+
)
|
|
1149
|
+
elif session_id is None:
|
|
1150
|
+
raise CampaignError(f"{args.command} 必须提供 --session-id,防止误用其他 Session 的 campaign")
|
|
1151
|
+
else:
|
|
1152
|
+
session_id = _validate_session_id(session_id, "--session-id")
|
|
1153
|
+
campaign_path = args.campaign or (
|
|
1154
|
+
args.root.resolve() / ".bugx" / "sessions" / session_id / "audit-campaign.json"
|
|
1155
|
+
)
|
|
1156
|
+
if args.command == "create":
|
|
1157
|
+
if args.campaign is None:
|
|
1158
|
+
campaign_path.parent.mkdir(parents=True, exist_ok=True)
|
|
1159
|
+
with _campaign_lock(campaign_path):
|
|
1160
|
+
if campaign_path.exists():
|
|
1161
|
+
raise CampaignError(
|
|
1162
|
+
f"campaign 已存在: {campaign_path};请为新 Session 使用新的目录,禁止覆盖旧运行产物"
|
|
1163
|
+
)
|
|
1164
|
+
payload = create_campaign(args.root, args.base, session_id=session_id)
|
|
1165
|
+
_atomic_write(campaign_path, payload)
|
|
1166
|
+
result: object = campaign_summary(payload, expected_session_id=session_id)
|
|
1167
|
+
else:
|
|
1168
|
+
if args.command == "status":
|
|
1169
|
+
with _campaign_lock(campaign_path):
|
|
1170
|
+
payload = _load(campaign_path)
|
|
1171
|
+
result = campaign_summary(payload, expected_session_id=session_id)
|
|
1172
|
+
elif args.command == "next" and args.owner is None:
|
|
1173
|
+
payload = _load(campaign_path)
|
|
1174
|
+
result = next_units(
|
|
1175
|
+
payload, args.limit, expected_session_id=session_id,
|
|
1176
|
+
)
|
|
1177
|
+
elif args.command in {"next", "claim"}:
|
|
1178
|
+
if not args.owner:
|
|
1179
|
+
raise CampaignError(f"{args.command} 必须提供 --owner")
|
|
1180
|
+
with _campaign_lock(campaign_path):
|
|
1181
|
+
payload = _load(campaign_path)
|
|
1182
|
+
result = claim_units(
|
|
1183
|
+
payload, args.owner, args.limit, args.token, args.lease_seconds,
|
|
1184
|
+
expected_session_id=session_id,
|
|
1185
|
+
)
|
|
1186
|
+
_atomic_write(campaign_path, payload)
|
|
1187
|
+
elif args.command == "reprioritize":
|
|
1188
|
+
if args.findings is None:
|
|
1189
|
+
raise CampaignError("reprioritize 必须提供 --findings")
|
|
1190
|
+
try:
|
|
1191
|
+
findings_payload = json.loads(
|
|
1192
|
+
args.findings.read_text(encoding="utf-8"),
|
|
1193
|
+
)
|
|
1194
|
+
except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc:
|
|
1195
|
+
raise CampaignError(f"无法读取 findings: {exc}") from exc
|
|
1196
|
+
with _campaign_lock(campaign_path):
|
|
1197
|
+
payload = _load(campaign_path)
|
|
1198
|
+
result = reprioritize(
|
|
1199
|
+
payload, findings_payload, bump=args.bump,
|
|
1200
|
+
expected_session_id=session_id,
|
|
1201
|
+
)
|
|
1202
|
+
_atomic_write(campaign_path, payload)
|
|
1203
|
+
else:
|
|
1204
|
+
if not args.scope:
|
|
1205
|
+
raise CampaignError("update 必须提供 --scope")
|
|
1206
|
+
with _campaign_lock(campaign_path):
|
|
1207
|
+
payload = _load(campaign_path)
|
|
1208
|
+
result = update_unit(
|
|
1209
|
+
payload, args.scope,
|
|
1210
|
+
None if args.reviewed is None else args.reviewed == "true",
|
|
1211
|
+
args.dynamic, args.boundary,
|
|
1212
|
+
_parse_evidence_args(args.evidence),
|
|
1213
|
+
args.owner, args.token, args.revision,
|
|
1214
|
+
args.prerequisite or None,
|
|
1215
|
+
None,
|
|
1216
|
+
_parse_resource_args(args.produce_asset, "--produce-asset"),
|
|
1217
|
+
_parse_resource_args(args.consume_asset, "--consume-asset"),
|
|
1218
|
+
expected_session_id=session_id,
|
|
1219
|
+
)
|
|
1220
|
+
_atomic_write(campaign_path, payload)
|
|
1221
|
+
if args.json:
|
|
1222
|
+
print(json.dumps(result, ensure_ascii=False, indent=2))
|
|
1223
|
+
else:
|
|
1224
|
+
print(json.dumps(result, ensure_ascii=False))
|
|
1225
|
+
return 0
|
|
1226
|
+
except CampaignError as exc:
|
|
1227
|
+
print(f"[audit_campaign] ✗ {exc}")
|
|
1228
|
+
return 2
|
|
1229
|
+
|
|
1230
|
+
|
|
1231
|
+
if __name__ == "__main__":
|
|
1232
|
+
raise SystemExit(main())
|