bugx-cli 0.1.0 → 0.1.2
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/README.md +193 -185
- package/core/README.md +2 -2
- package/core/agent/README.md +2 -1
- package/core/agent/agent_artifacts.py +8 -6
- package/core/agent/agent_eval.py +136 -54
- package/core/agent/agent_execution.py +218 -52
- package/core/agent/agent_orchestrator.py +14 -8
- package/core/agent/agent_targets.py +8 -2
- package/core/agent/feature_baseline.py +150 -0
- package/core/assets/README.md +3 -2
- package/core/assets/axe-core/LICENSE-3RD-PARTY.txt +66 -0
- package/core/assets/axe-core/LICENSE.txt +362 -0
- package/core/assets/axe-core/UPSTREAM.md +10 -0
- package/core/assets/axe-core/axe.min.js +12 -0
- package/core/assets/bugx-hero-en.svg +74 -0
- package/core/assets/bugx-hero-zh.svg +74 -0
- package/core/assets/bugx-social-preview.svg +71 -0
- package/core/assets/bugx-wechat-group.png +0 -0
- package/core/assets/codex.png +0 -0
- package/core/assets/dsh.png +0 -0
- package/core/assets/webui-chatgpt.jpg +0 -0
- package/core/assets/webui-session.jpg +0 -0
- package/core/assets/webui-skills.jpg +0 -0
- package/core/assets/webui-studio.jpg +0 -0
- package/core/assets/webui-zcode.jpg +0 -0
- package/core/assets/zcode.png +0 -0
- package/core/audit_packs/README.md +2 -0
- package/core/audit_packs/pitfalls/auth_crypto.json +64 -0
- package/core/audit_packs/pitfalls/file_ssrf_cmd.json +64 -0
- package/core/audit_packs/pitfalls/go_backend.json +66 -0
- package/core/audit_packs/pitfalls/java_spring.json +64 -0
- package/core/audit_packs/pitfalls/js_ts_web.json +67 -0
- package/core/audit_packs/pitfalls/python_web.json +82 -0
- package/core/autonomous_cve/SPEC.md +1 -1
- package/core/autonomous_cve/attack_graph_store.py +152 -106
- package/core/autonomous_cve/behavior_graph.py +8 -2
- package/core/autonomous_cve/verifier.py +4 -1
- package/core/bugx.md +1 -1
- package/core/bugx_paths.py +43 -8
- package/core/cli-help.txt +66 -0
- package/core/cloud_sync/SPEC.md +1 -1
- package/core/cloud_sync/cloud_client.py +81 -11
- package/core/cloud_sync/cloud_onboard.py +42 -1
- package/core/cloud_sync/consent.py +33 -3
- package/core/cloud_sync/flywheel_client.py +186 -15
- package/core/cloud_sync/network_transport.py +24 -3
- package/core/cloud_sync/sensitive_filter.py +2 -2
- package/core/cloud_sync/sync_push.py +12 -10
- package/core/contracts/AGENT_GUIDE.md +6 -9
- package/core/contracts/README.md +2 -2
- package/core/contracts/bugx-runtime-contract.md +1 -1
- package/core/contracts/bugx-worker.md +1 -1
- package/core/contracts/engine_gap_contracts.py +86 -3
- package/core/coverage/coverage_discovery.py +599 -29
- package/core/coverage/coverage_evidence.py +47 -0
- package/core/coverage/coverage_forensics.py +9 -0
- package/core/coverage/coverage_validate.py +6 -1
- package/core/dev_harness/SPEC.md +1 -1
- package/core/engine-integrity.json +670 -442
- package/core/fuzzing/concurrency_fuzzer.py +53 -0
- package/core/fuzzing/differential_oracle.py +562 -27
- package/core/fuzzing/fuzz_input.py +109 -6
- package/core/fuzzing/stateful_fuzzer.py +72 -0
- package/core/governance/secret_redactor.py +22 -10
- package/core/host_acp/SPEC.md +1 -1
- package/core/host_acp/__init__.py +4 -4
- package/core/host_acp/claude.py +59 -1
- package/core/host_acp/cline.py +64 -1
- package/core/host_acp/codex.py +56 -1
- package/core/host_acp/dsh.py +59 -1
- package/core/host_acp/opencode.py +56 -1
- package/core/host_acp/pi.py +59 -1
- package/core/host_acp/zcode.py +59 -1
- package/core/host_runtime/SPEC.md +1 -1
- package/core/host_runtime/adapters.py +1 -1
- package/core/host_runtime/cline.py +13 -0
- package/core/host_runtime/host_evaluators.py +44 -4
- package/core/host_runtime/host_probe.py +1 -1
- package/core/host_runtime/host_provider_arbitrator.py +116 -62
- package/core/host_runtime/host_registry.py +15 -8
- package/core/host_runtime/mcp_registry_gate.py +12 -1
- package/core/host_runtime/pi.py +102 -0
- package/core/host_runtime/provider_facts.py +66 -0
- package/core/hosts/SPEC.md +1 -1
- package/core/hosts/__init__.py +6 -2
- package/core/hosts/_dsh_usage.py +1 -1
- package/core/hosts/base.py +32 -4
- package/core/hosts/claude.py +55 -0
- package/core/hosts/cline.py +6 -2
- package/core/hosts/codex.py +58 -0
- package/core/hosts/dsh.py +9 -1
- package/core/hosts/opencode.py +6 -6
- package/core/hosts/pi.py +159 -2
- package/core/infra/README.md +4 -2
- package/core/infra/__init__.py +2 -0
- package/core/infra/build_info.py +22 -3
- package/core/infra/client_metadata.py +1 -1
- package/core/infra/json_utils.py +22 -0
- package/core/launch_phases/README.md +6 -3
- package/core/launch_phases/SPEC.md +1 -1
- package/core/launch_phases/common.py +21 -2
- package/core/launch_phases/finding_confirm_phase.py +170 -5
- package/core/launch_phases/finding_settlement.py +188 -1
- package/core/launch_phases/judge_phase.py +69 -12
- package/core/launch_phases/orchestrator_controls.py +11 -7
- package/core/launch_phases/post_coverage_sync.py +9 -2
- package/core/launch_phases/post_phase.py +144 -8
- package/core/launch_phases/post_receipt.py +12 -1
- package/core/launch_phases/pre_phase.py +3 -3
- package/core/launch_phases/pre_recon_scout.py +66 -36
- package/core/launch_phases/pre_state_builder.py +23 -176
- package/core/launch_phases/report_sharing.py +3 -7
- package/core/launch_phases/round_orchestrator.py +129 -58
- package/core/launch_phases/semantic_recon.py +545 -0
- package/core/launch_phases/session_runtime.py +56 -9
- package/core/launch_phases/startup_gates.py +36 -8
- package/core/launch_phases/startup_interaction.py +68 -12
- package/core/launch_phases/startup_version_gate.py +13 -3
- package/core/launch_phases/supervisor_bridge.py +46 -17
- package/core/launch_phases/supervisor_coverage.py +8 -2
- package/core/launch_phases/supervisor_degraded.py +1 -9
- package/core/launch_phases/verify_loop.py +767 -0
- package/core/launch_phases/worker_barriers.py +15 -5
- package/core/launch_phases/worker_orchestrator.py +105 -25
- package/core/launch_phases/worker_prior.py +115 -0
- package/core/ledger/README.md +2 -1
- package/core/ledger/SPEC.md +1 -1
- package/core/ledger/_facade.py +2 -1
- package/core/ledger/archive_ops.py +60 -2
- package/core/ledger/cli.py +6 -1
- package/core/ledger/export_ops.py +6 -1
- package/core/ledger/finding_confirmation.py +48 -6
- package/core/ledger/finding_lifecycle.py +428 -5
- package/core/ledger/finding_verification.py +555 -10
- package/core/ledger/fp_ledger.py +255 -0
- package/core/ledger/incidents.py +10 -4
- package/core/ledger/patterns.py +10 -7
- package/core/ledger/receipt_contract.py +17 -1
- package/core/ledger/sync_ops.py +21 -16
- package/core/ledger/tool_experience.py +2 -1
- package/core/ledger/verify_life.py +88 -17
- package/core/locales/en-US.json +2 -2
- package/core/locales/zh-CN.json +2 -2
- package/core/mcp_handlers/SPEC.md +1 -1
- package/core/mcp_handlers/base.py +23 -3
- package/core/mcp_handlers/channel_lifecycle.py +85 -30
- package/core/mcp_handlers/retrieval_handlers.py +11 -1
- package/core/mcp_handlers/rpc_server.py +6 -1
- package/core/mcp_handlers/supervisor_handlers.py +32 -6
- package/core/mcp_handlers/tool_table.py +15 -0
- package/core/mcp_runtime_support/environment.py +0 -38
- package/core/mcp_runtime_support/verifier.py +0 -52
- package/core/metadata.txt +2 -3
- package/core/planning/README.md +2 -1
- package/core/planning/domain_router.py +4 -2
- package/core/planning/dynamic_flow_analyzer.py +219 -14
- package/core/planning/judge_pipeline.py +87 -4
- package/core/planning/prompt_harness.py +57 -15
- package/core/planning/prompt_policy_engine.py +386 -0
- package/core/planning/spec_harvester.py +4 -4
- package/core/probes/INTERFACE.md +11 -1
- package/core/probes/SPEC.md +11 -1
- package/core/probes/__init__.py +46 -40
- package/core/probes/android_probe.py +177 -9
- package/core/probes/codebase_memory_probe.py +57 -0
- package/core/probes/desktop_probe.py +104 -0
- package/core/probes/differential_probe.py +99 -21
- package/core/probes/efficiency_probe.py +64 -0
- package/core/probes/ios_binary_probe.py +105 -1
- package/core/probes/memory_probe.py +66 -0
- package/core/probes/miniprogram_probe.py +75 -13
- package/core/probes/mobile_probe.py +215 -30
- package/core/probes/native_probe.py +88 -0
- package/core/probes/openwiki_probe.py +70 -0
- package/core/probes/pattern_probe.py +106 -0
- package/core/probes/platform_probe.py +81 -0
- package/core/probes/probe_registry.py +108 -7
- package/core/probes/sast_fixture_corpus.py +340 -0
- package/core/probes/sast_probe.py +553 -52
- package/core/probes/sast_rules.py +668 -28
- package/core/probes/sca_scanner.py +48 -0
- package/core/probes/ui_accessibility.py +149 -0
- package/core/probes/ui_audit.py +513 -0
- package/core/probes/ui_contract.py +273 -0
- package/core/probes/ui_evidence.py +212 -0
- package/core/probes/ui_measurements.py +314 -0
- package/core/probes/ui_repair.py +250 -0
- package/core/probes/ui_review.py +133 -0
- package/core/probes/ui_storybook.py +107 -0
- package/core/probes/ui_tokens.py +185 -0
- package/core/probes/ui_visual_diff.py +131 -0
- package/core/probes/web_probe.py +373 -18
- package/core/project_profiler/SPEC.md +1 -1
- package/core/project_profiler/arbitrator.py +6 -1
- package/core/project_profiler/detector.py +8 -1
- package/core/project_profiler/strategy.py +51 -15
- package/core/prompts/README.md +4 -2
- package/core/prompts/command_routing_en.md +2 -2
- package/core/prompts/command_routing_zh.md +2 -2
- package/core/prompts/policies/prompt_policies.json +101 -0
- package/core/prompts/stages/stage_repair.md +1 -1
- package/core/prompts/stages/stage_verify.defensive.md +42 -0
- package/core/prompts/stages/stage_verify.md +44 -0
- package/core/repair/README.md +1 -1
- package/core/repair/l7_repair_loop.py +1 -4
- package/core/repair/rsi_fixer.py +4 -4
- package/core/repair/rsi_loop.py +1 -3
- package/core/repair/rsi_repair.py +7 -7
- package/core/repair/rsi_scope.py +27 -8
- package/core/report_engine/SPEC.md +1 -1
- package/core/report_engine/attestation.py +8 -4
- package/core/report_engine/finding_report.py +2 -1
- package/core/report_engine/models.py +7 -9
- package/core/report_engine/report_share.py +0 -8
- package/core/report_engine/sast_bridge.py +2 -2
- package/core/report_engine/server.py +18 -8
- package/core/report_engine/web-conformance.md +123 -18
- package/core/report_engine/web_conformance.py +21 -52
- package/core/retrieval/README.md +2 -1
- package/core/retrieval/SPEC.md +1 -1
- package/core/retrieval/code_analyzer.py +50 -14
- package/core/retrieval/context_assembler.py +7 -1
- package/core/retrieval/knowledge_sync.py +108 -14
- package/core/retrieval/pitfall_packs.py +277 -0
- package/core/retrieval/symbol_index.py +25 -6
- package/core/retrieval/universal_code_matcher.py +234 -49
- package/core/runtime/README.md +1 -1
- package/core/runtime/bugx_logging.py +78 -7
- package/core/runtime/fixture_solidify.py +5 -10
- package/core/runtime/global_telemetry.py +20 -0
- package/core/runtime/incident_eval.py +1 -1
- package/core/runtime/model_runner.py +4 -41
- package/core/runtime/platform_adapter.py +2 -2
- package/core/runtime/prep_validate.py +4 -2
- package/core/runtime/project_settings.py +2 -1
- package/core/runtime/scenario_eval.py +50 -8
- package/core/skills/bugx_docs_mcp_server.py +3 -1
- package/core/skills/bugx_mcp_server.py +29 -2
- package/core/skills/tools_kb.py +1 -1
- package/core/supervisor/README.md +1 -1
- package/core/supervisor/SPEC.md +1 -1
- package/core/supervisor/budget_governor.py +503 -9
- package/core/supervisor/checkpoint_pipeline.py +248 -6
- package/core/supervisor/checkpoint_sync.py +13 -0
- package/core/supervisor/claim_events.py +1 -1
- package/core/supervisor/finding_workflow.py +22 -5
- package/core/supervisor/lease_manager.py +1 -1
- package/core/supervisor/lifecycle_blocks.py +6 -1
- package/core/supervisor/rejection_remedies.py +52 -5
- package/core/supervisor/serial_authorization.py +48 -4
- package/core/supervisor/task_scheduler.py +2 -2
- package/core/supervisor/worker_checkpoint.py +8 -1
- package/core/supervisor/worker_runtime.py +8 -2
- package/core/supervisor_types/worker_claim.py +9 -0
- package/core/webui/README.md +1 -1
- package/core/webui/SPEC.md +2 -1
- package/core/webui/adapters/claude.py +5 -1
- package/core/webui/adapters/cline.py +10 -2
- package/core/webui/adapters/codex.py +5 -1
- package/core/webui/adapters/dsh.py +5 -1
- package/core/webui/docs_session_service.py +2 -2
- package/core/webui/mcp_inspector.py +11 -7
- package/core/webui/static/00-base.css +1060 -0
- package/core/webui/static/01-monitoring.css +802 -0
- package/core/webui/static/02-header-actions.css +321 -0
- package/core/webui/static/03-trigger-popover.css +697 -0
- package/core/webui/static/04-composer.css +628 -0
- package/core/webui/static/05-skills-center.css +878 -0
- package/core/webui/static/06-mcp-center.css +623 -0
- package/core/webui/static/07-skill-detail.css +265 -0
- package/core/webui/static/08-files-management.css +167 -0
- package/core/webui/static/09-files-center.css +386 -0
- package/core/webui/static/10-icons.css +105 -0
- package/core/webui/static/11-project-options.css +185 -0
- package/core/webui/static/12-profile-tab.css +383 -0
- package/core/webui/static/design-tokens.css +113 -0
- package/core/webui/static/index.html +14 -1
- package/core/webui/workspace_service.py +1 -1
- package/docs/07_distribution/01_README_NPM.md +193 -185
- package/ecosystem/integrations/README.md +1 -1
- package/ecosystem/integrations/dsh/mcp/package.json +1 -1
- package/ecosystem/integrations/dsh/skills/bugx-dsh/SKILL.md +1 -1
- package/ecosystem/integrations/dsh/ui/package.json +1 -1
- package/ecosystem/integrations/opencode/bugx-mcp-manifest.json +4 -4
- package/ecosystem/integrations/opencode/mcp-lock.json +14 -6
- package/ecosystem/integrations/opencode/opencode.json +23 -12
- package/ecosystem/integrations/pi/extensions/bugx/manifest.json +1 -1
- package/ecosystem/integrations/qoder/connector-meta.json +1 -1
- package/ecosystem/integrations/workbuddy/connector-meta.json +1 -1
- package/ecosystem/integrations/workbuddy/skills/bugx/SKILL.md +1 -1
- package/ecosystem/plugins/bugx/.claude-plugin/plugin.json +1 -1
- package/ecosystem/plugins/bugx/.codex-plugin/plugin.json +1 -1
- package/ecosystem/plugins/bugx/.zcode-plugin/plugin.json +1 -1
- package/ecosystem/plugins/bugx/skills/bugx/SKILL.md +2 -2
- package/ecosystem/plugins/bugx/skills/bugx-dsh/SKILL.md +1 -1
- package/ecosystem/plugins/bugx/skills/bugx-opencode/SKILL.md +1 -1
- package/ecosystem/plugins/bugx/skills/bugx-zcode/SKILL.md +1 -1
- package/interfaces/bin/bugx.js +37 -0
- package/interfaces/cli/bugx_cli/__init__.py +4 -2
- package/interfaces/cli/bugx_cli/cli.py +172 -69
- package/interfaces/cli/bugx_cli/commands/advisory.py +1 -1
- package/interfaces/cli/bugx_cli/commands/agent.py +461 -134
- package/interfaces/cli/bugx_cli/commands/audit.py +10 -9
- package/interfaces/cli/bugx_cli/commands/autonomous.py +1 -1
- package/interfaces/cli/bugx_cli/commands/cloud.py +31 -22
- package/interfaces/cli/bugx_cli/commands/doctor.py +449 -204
- package/interfaces/cli/bugx_cli/commands/interaction.py +5 -1
- package/interfaces/cli/bugx_cli/commands/knowledge.py +5 -4
- package/interfaces/cli/bugx_cli/commands/lifecycle.py +3 -3
- package/interfaces/cli/bugx_cli/commands/plugin.py +58 -23
- package/interfaces/cli/bugx_cli/commands/plugin_claude.py +7 -7
- package/interfaces/cli/bugx_cli/commands/plugin_funide.py +2 -1
- package/interfaces/cli/bugx_cli/commands/plugin_zcode.py +1 -1
- package/interfaces/cli/bugx_cli/commands/project.py +6 -13
- package/interfaces/cli/bugx_cli/commands/report.py +2 -6
- package/interfaces/cli/bugx_cli/commands/system.py +524 -169
- package/interfaces/cli/bugx_cli/common.py +21 -15
- package/interfaces/cli/bugx_cli/host_adapters.py +29 -54
- package/interfaces/cli/bugx_cli/hosts/registry.py +8 -6
- package/interfaces/cli/bugx_cli/infra/ai_advisor.py +157 -27
- package/interfaces/cli/bugx_cli/infra/engine_installer.py +35 -16
- package/interfaces/cli/bugx_cli/infra/host_sync.py +11 -8
- package/interfaces/cli/bugx_cli/infra/mcp_advisor.py +76 -5
- package/interfaces/cli/bugx_cli/infra/security.py +13 -6
- package/package.json +30 -15
- package/pyproject.toml +60 -9
- package/scripts/ensure-python.mjs +7 -7
- package/scripts/sync-version.mjs +10 -21
- package/scripts/test-npm-wrapper.mjs +1 -1
- package/core/assets/bugx-hero-cn.png +0 -0
- package/core/assets/bugx-hero-en.png +0 -0
- package/core/webui/static/project-settings.css +0 -6458
- package/docs/07_distribution/README.md +0 -16
- package/docs/README.md +0 -121
- package/interfaces/README.md +0 -143
- package/interfaces/bin/README.md +0 -35
- package/interfaces/cli/README.md +0 -90
- package/scripts/README.md +0 -118
|
@@ -0,0 +1,767 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""verify_loop.py — 独立 Verification 角色盲审包构造与报错驱动 PoC 自纠错闭环(P0 / T-004)。
|
|
3
|
+
|
|
4
|
+
职责边界:
|
|
5
|
+
1. 盲审隔离(D-01):从 Supervisor 权威态构造最小 ``VerifyBundle``(只含白名单
|
|
6
|
+
缺陷声明 + 目标代码切片 + 入口摘要 + 运行环境事实 + 上一轮引擎诊断),绝不透传
|
|
7
|
+
Analysis/Judge 长推理链。
|
|
8
|
+
2. 结构化失败诊断(D-02):将每次引擎 ``verify_finding`` 失败按 8 类精确
|
|
9
|
+
``failure_code`` 落盘至当前 lifecycle ``state/verify/<fp_slug>/attempt-<n>.json``。
|
|
10
|
+
3. 有界自纠错循环(D-03):最多 ``max_attempts``(默认 3,上限 5)轮报错驱动修订;
|
|
11
|
+
连续两轮代码哈希相同即判定自旋锁(``verifier_stalled``)立即熔断;遇到
|
|
12
|
+
``env_or_dependency_blocked`` 或连续 2 次 ``positive_flaky`` 立即熔断。
|
|
13
|
+
4. 显式终态收敛(D-04):禁止静默丢弃;成功进 ``confirmed``,环境阻塞标 ``blocked``,
|
|
14
|
+
预算耗尽标 ``deferred_budget_exhausted``(保持 pending 可续跑),重试耗尽按
|
|
15
|
+
规范 ``rejection_class``(``not_reproducible`` / ``flaky`` / ``insufficient_evidence``)驳回。
|
|
16
|
+
5. Anti-Gaming(D-05):锁定 ``oracle_reference`` / ``oracle_hash`` 不可被重试覆写;
|
|
17
|
+
AST 拦截空壳负对照;执行前后校验目标源码 SHA-256 防止 PoC 篡改被测代码。
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import hashlib
|
|
23
|
+
import json
|
|
24
|
+
import os
|
|
25
|
+
import sys
|
|
26
|
+
import tempfile
|
|
27
|
+
import time
|
|
28
|
+
from pathlib import Path
|
|
29
|
+
from typing import Any, Callable, Mapping, Sequence
|
|
30
|
+
|
|
31
|
+
from core.ledger.finding_verification import (
|
|
32
|
+
RETRYABLE_FAILURE_CODES,
|
|
33
|
+
VerificationDiagnostic,
|
|
34
|
+
diagnose_verification_error,
|
|
35
|
+
diagnose_verification_receipt,
|
|
36
|
+
snapshot_target_hashes,
|
|
37
|
+
validate_python_poc_pair,
|
|
38
|
+
verify_target_hashes_unchanged,
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
DEFAULT_MAX_ATTEMPTS = 3
|
|
42
|
+
HARD_MAX_ATTEMPTS = 5
|
|
43
|
+
MAX_SLICE_BYTES = 8 * 1024
|
|
44
|
+
_SHELL_TOKENS = (";", "&&", "||", "`", "$(", ">", "<")
|
|
45
|
+
|
|
46
|
+
_POS_EXEC_TEMPLATE = (
|
|
47
|
+
"import sys as _s\n"
|
|
48
|
+
"_g = {{'__name__': '__bugx_verification__'}}\n"
|
|
49
|
+
"_rc = 0\n"
|
|
50
|
+
"try:\n"
|
|
51
|
+
" exec(compile({src!r}, 'verification-positive', 'exec'), _g)\n"
|
|
52
|
+
"except SystemExit as _e:\n"
|
|
53
|
+
" _rc = _e.code if isinstance(_e.code, int) else 1\n"
|
|
54
|
+
"except BaseException as _e:\n"
|
|
55
|
+
" _rc = 0\n"
|
|
56
|
+
" print('BUGX_VERIFY_POSITIVE unexpected-error=%s' % (type(_e).__name__,))\n"
|
|
57
|
+
"print('BUGX_VERIFY_POSITIVE rc=%s' % (_rc,))\n"
|
|
58
|
+
"_s.exit(1 if _rc else 0)\n"
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _sha256_text(text: str) -> str:
|
|
63
|
+
return hashlib.sha256(text.encode("utf-8")).hexdigest()
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _fp_slug(fingerprint: str) -> str:
|
|
67
|
+
return _sha256_text(fingerprint.strip())[:16]
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _atomic_write_json(path: Path, payload: Mapping[str, Any]) -> None:
|
|
71
|
+
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
72
|
+
data = json.dumps(payload, ensure_ascii=False, indent=2, sort_keys=True).encode("utf-8")
|
|
73
|
+
fd, tmp_name = tempfile.mkstemp(prefix=f".{path.name}.", dir=str(path.parent))
|
|
74
|
+
try:
|
|
75
|
+
os.fchmod(fd, 0o600)
|
|
76
|
+
with os.fdopen(fd, "wb") as handle:
|
|
77
|
+
handle.write(data)
|
|
78
|
+
handle.flush()
|
|
79
|
+
os.fsync(handle.fileno())
|
|
80
|
+
os.replace(tmp_name, path)
|
|
81
|
+
except BaseException:
|
|
82
|
+
try:
|
|
83
|
+
os.close(fd)
|
|
84
|
+
except OSError:
|
|
85
|
+
pass
|
|
86
|
+
try:
|
|
87
|
+
os.unlink(tmp_name)
|
|
88
|
+
except OSError:
|
|
89
|
+
pass
|
|
90
|
+
raise
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def strip_runner_wrapper(code: str) -> str:
|
|
94
|
+
"""Strip accidental `python3 -c` / `python -c` wrapper from verifier output."""
|
|
95
|
+
text = (code or "").strip()
|
|
96
|
+
for prefix in ("python3 -c", "python -c"):
|
|
97
|
+
if text.startswith(prefix):
|
|
98
|
+
body = text[len(prefix):].strip()
|
|
99
|
+
if len(body) >= 2 and body[0] in "'\"" and body[-1] == body[0]:
|
|
100
|
+
body = body[1:-1]
|
|
101
|
+
return body.strip()
|
|
102
|
+
return text
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def precheck_shell_tokens(code: str, label: str) -> str | None:
|
|
106
|
+
for token in _SHELL_TOKENS:
|
|
107
|
+
if token in code:
|
|
108
|
+
return f"{label} 含 shell 禁字符 {token!r}:请改用换行分隔语句或 chr() 构造载荷"
|
|
109
|
+
return None
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def wrap_positive_argv(code: str) -> list[str]:
|
|
113
|
+
return [sys.executable or "python3", "-c", _POS_EXEC_TEMPLATE.format(src=strip_runner_wrapper(code))]
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def wrap_negative_argv(code: str) -> list[str]:
|
|
117
|
+
return [sys.executable or "python3", "-c", strip_runner_wrapper(code)]
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def normalize_max_attempts(value: int | None) -> int:
|
|
121
|
+
if value is None:
|
|
122
|
+
return DEFAULT_MAX_ATTEMPTS
|
|
123
|
+
if isinstance(value, bool) or not isinstance(value, int) or value < 1 or value > HARD_MAX_ATTEMPTS:
|
|
124
|
+
raise ValueError(f"max_attempts 必须为 1..{HARD_MAX_ATTEMPTS} 之间的整数,收到: {value!r}")
|
|
125
|
+
return value
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def verify_dir_for_finding(state_dir: Path, fingerprint: str) -> Path:
|
|
129
|
+
path = Path(state_dir) / "verify" / _fp_slug(fingerprint)
|
|
130
|
+
path.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
131
|
+
return path
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _extract_target_file_and_line(finding: Mapping[str, Any]) -> tuple[str, int | None]:
|
|
135
|
+
file_val = str(finding.get("file") or finding.get("path") or "").strip()
|
|
136
|
+
line_val = finding.get("line")
|
|
137
|
+
line_no = line_val if isinstance(line_val, int) and line_val > 0 else None
|
|
138
|
+
location = str(finding.get("location") or "").strip()
|
|
139
|
+
if not file_val and location:
|
|
140
|
+
parts = location.split(":", 1)
|
|
141
|
+
file_val = parts[0].strip()
|
|
142
|
+
if len(parts) == 2 and parts[1].strip().isdigit():
|
|
143
|
+
line_no = int(parts[1].strip())
|
|
144
|
+
elif line_no is None and ":" in location:
|
|
145
|
+
tail = location.rsplit(":", 1)[-1].strip()
|
|
146
|
+
if tail.isdigit():
|
|
147
|
+
line_no = int(tail)
|
|
148
|
+
return file_val.replace("\\", "/"), line_no
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _extract_target_hints(finding: Mapping[str, Any], rel_file: str) -> tuple[str, ...]:
|
|
152
|
+
hints: list[str] = []
|
|
153
|
+
if rel_file:
|
|
154
|
+
stem = Path(rel_file).stem
|
|
155
|
+
if stem and stem != "__init__":
|
|
156
|
+
hints.append(stem)
|
|
157
|
+
parent = Path(rel_file).parent.name
|
|
158
|
+
if parent and parent not in {".", ""}:
|
|
159
|
+
hints.append(parent)
|
|
160
|
+
for key in ("symbol", "function", "method"):
|
|
161
|
+
raw = str(finding.get(key) or "").strip()
|
|
162
|
+
if raw:
|
|
163
|
+
hints.append(raw.split(".")[-1])
|
|
164
|
+
deduped: list[str] = []
|
|
165
|
+
for h in hints:
|
|
166
|
+
if h not in deduped:
|
|
167
|
+
deduped.append(h)
|
|
168
|
+
return tuple(deduped)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _extract_code_slice(root: Path, rel_file: str, line_no: int | None) -> tuple[str, bool]:
|
|
172
|
+
"""Extract bounded AST/line slice for blind verification without leaking analysis text."""
|
|
173
|
+
if not rel_file:
|
|
174
|
+
return "", True
|
|
175
|
+
resolved_root = Path(root).resolve()
|
|
176
|
+
candidate = Path(rel_file)
|
|
177
|
+
if candidate.is_absolute() or ".." in candidate.parts:
|
|
178
|
+
return "", True
|
|
179
|
+
try:
|
|
180
|
+
target = (resolved_root / candidate).resolve()
|
|
181
|
+
target.relative_to(resolved_root)
|
|
182
|
+
except (OSError, ValueError):
|
|
183
|
+
return "", True
|
|
184
|
+
if not target.is_file() or target.is_symlink():
|
|
185
|
+
return "", True
|
|
186
|
+
|
|
187
|
+
# Try AST slice_extractor first if available
|
|
188
|
+
slice_fallback = False
|
|
189
|
+
try:
|
|
190
|
+
from core.retrieval import slice_extractor # type: ignore
|
|
191
|
+
if hasattr(slice_extractor, "extract_slice"):
|
|
192
|
+
extracted = slice_extractor.extract_slice(target, line_no or 1)
|
|
193
|
+
if isinstance(extracted, str) and extracted.strip():
|
|
194
|
+
raw = extracted.encode("utf-8", errors="replace")[:MAX_SLICE_BYTES].decode("utf-8", errors="ignore")
|
|
195
|
+
return raw, False
|
|
196
|
+
except Exception:
|
|
197
|
+
slice_fallback = True
|
|
198
|
+
|
|
199
|
+
# Bounded line-window fallback (fail-closed recorded via slice_fallback=True)
|
|
200
|
+
try:
|
|
201
|
+
lines = target.read_text(encoding="utf-8", errors="replace").splitlines()
|
|
202
|
+
except OSError:
|
|
203
|
+
return "", True
|
|
204
|
+
center = max(1, line_no or 1)
|
|
205
|
+
start = max(1, center - 25)
|
|
206
|
+
end = min(len(lines), center + 45)
|
|
207
|
+
numbered = [f"{idx}: {lines[idx - 1]}" for idx in range(start, end + 1)]
|
|
208
|
+
text = "\n".join(numbered)
|
|
209
|
+
raw = text.encode("utf-8", errors="replace")[:MAX_SLICE_BYTES].decode("utf-8", errors="ignore")
|
|
210
|
+
return raw, True
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def ensure_locked_oracle(root: Path, finding: Mapping[str, Any]) -> tuple[str, str]:
|
|
214
|
+
"""Deterministically create and lock the immutable oracle file + SHA-256."""
|
|
215
|
+
fp = str(finding.get("fingerprint") or finding.get("id") or "").strip()
|
|
216
|
+
if not fp:
|
|
217
|
+
raise ValueError("finding 缺少 fingerprint")
|
|
218
|
+
slug = _sha256_text(fp)[:12]
|
|
219
|
+
oracle_dir = Path(root).resolve() / ".bugx" / "knowledge" / "oracles"
|
|
220
|
+
oracle_dir.mkdir(parents=True, exist_ok=True)
|
|
221
|
+
oracle_rel = f".bugx/knowledge/oracles/{slug}.txt"
|
|
222
|
+
oracle_path = oracle_dir / f"{slug}.txt"
|
|
223
|
+
if not oracle_path.is_file():
|
|
224
|
+
severity = str(finding.get("severity") or "unknown")
|
|
225
|
+
category = str(finding.get("category") or "unknown")
|
|
226
|
+
rel_file, line_no = _extract_target_file_and_line(finding)
|
|
227
|
+
loc = f"{rel_file}:{line_no}" if rel_file and line_no else rel_file
|
|
228
|
+
oracle_path.write_text(
|
|
229
|
+
f"fingerprint={fp}\n"
|
|
230
|
+
f"severity={severity}\n"
|
|
231
|
+
f"category={category}\n"
|
|
232
|
+
f"location={loc}\n"
|
|
233
|
+
f"positive: 漏洞存在时非零退出(引擎锁定,独立验证员不可篡改)\n"
|
|
234
|
+
f"negative: 安全输入下 0 退出(必须调用同一目标入口)\n",
|
|
235
|
+
encoding="utf-8",
|
|
236
|
+
)
|
|
237
|
+
oracle_hash = hashlib.sha256(oracle_path.read_bytes()).hexdigest()
|
|
238
|
+
return oracle_rel, oracle_hash
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def build_verify_bundle(
|
|
242
|
+
root: Path,
|
|
243
|
+
state_dir: Path,
|
|
244
|
+
finding: Mapping[str, Any],
|
|
245
|
+
*,
|
|
246
|
+
attempt: int = 1,
|
|
247
|
+
max_attempts: int = DEFAULT_MAX_ATTEMPTS,
|
|
248
|
+
last_diagnostic: Mapping[str, Any] | None = None,
|
|
249
|
+
host: str | None = None,
|
|
250
|
+
provider: str | None = None,
|
|
251
|
+
model: str | None = None,
|
|
252
|
+
policy: str | None = None,
|
|
253
|
+
last_error: str | None = None,
|
|
254
|
+
) -> tuple[Path, dict[str, Any]]:
|
|
255
|
+
"""Build and persist the blind-review VerifyBundle (D-01 + Prompt Policy Engine)."""
|
|
256
|
+
from core.planning import prompt_policy_engine
|
|
257
|
+
|
|
258
|
+
fp = str(finding.get("fingerprint") or finding.get("id") or "").strip()
|
|
259
|
+
if not fp:
|
|
260
|
+
raise ValueError("finding 缺少 fingerprint")
|
|
261
|
+
rel_file, line_no = _extract_target_file_and_line(finding)
|
|
262
|
+
code_slice, slice_fallback = _extract_code_slice(root, rel_file, line_no)
|
|
263
|
+
oracle_rel, oracle_hash = ensure_locked_oracle(root, finding)
|
|
264
|
+
target_hints = list(_extract_target_hints(finding, rel_file))
|
|
265
|
+
|
|
266
|
+
resolved_policy = prompt_policy_engine.resolve_policy(
|
|
267
|
+
host=host,
|
|
268
|
+
provider=provider,
|
|
269
|
+
model=model,
|
|
270
|
+
last_error=last_error,
|
|
271
|
+
explicit_policy=policy,
|
|
272
|
+
root=Path(root).resolve(),
|
|
273
|
+
)
|
|
274
|
+
override_rel = prompt_policy_engine.resolve_stage_override_relpath(resolved_policy, "verify")
|
|
275
|
+
protocol_ref = f"core/prompts/{override_rel}" if override_rel else "core/prompts/stages/stage_verify.md"
|
|
276
|
+
|
|
277
|
+
summary_text = str(
|
|
278
|
+
finding.get("summary")
|
|
279
|
+
or finding.get("title")
|
|
280
|
+
or finding.get("description")
|
|
281
|
+
or ""
|
|
282
|
+
).strip()[:300]
|
|
283
|
+
|
|
284
|
+
bundle: dict[str, Any] = {
|
|
285
|
+
"schema_version": 1,
|
|
286
|
+
"role": "verification_specialist",
|
|
287
|
+
"policy_profile": resolved_policy.name,
|
|
288
|
+
"protocol_ref": protocol_ref,
|
|
289
|
+
"safe_repro_directive": resolved_policy.safe_repro_directive,
|
|
290
|
+
"attempt": attempt,
|
|
291
|
+
"max_attempts": max_attempts,
|
|
292
|
+
"candidate": {
|
|
293
|
+
"fingerprint": fp,
|
|
294
|
+
"category": str(finding.get("category") or ""),
|
|
295
|
+
"severity": str(finding.get("severity") or ""),
|
|
296
|
+
"file": rel_file,
|
|
297
|
+
"line": line_no,
|
|
298
|
+
"location": f"{rel_file}:{line_no}" if rel_file and line_no else rel_file,
|
|
299
|
+
"summary": summary_text,
|
|
300
|
+
"target_hints": target_hints,
|
|
301
|
+
},
|
|
302
|
+
"code_slice": {
|
|
303
|
+
"path": rel_file,
|
|
304
|
+
"content": code_slice,
|
|
305
|
+
"slice_fallback": slice_fallback,
|
|
306
|
+
},
|
|
307
|
+
"locked_oracle": {
|
|
308
|
+
"oracle_reference": oracle_rel,
|
|
309
|
+
"oracle_hash": oracle_hash,
|
|
310
|
+
"immutable": True,
|
|
311
|
+
},
|
|
312
|
+
"environment": {
|
|
313
|
+
"cwd": ".",
|
|
314
|
+
"python_executable": sys.executable or "python3",
|
|
315
|
+
"timeout_seconds": 30,
|
|
316
|
+
},
|
|
317
|
+
"last_diagnostic": dict(last_diagnostic) if isinstance(last_diagnostic, Mapping) else None,
|
|
318
|
+
"created_at": time.time(),
|
|
319
|
+
}
|
|
320
|
+
vdir = verify_dir_for_finding(state_dir, fp)
|
|
321
|
+
bundle_path = vdir / "bundle.json"
|
|
322
|
+
_atomic_write_json(bundle_path, bundle)
|
|
323
|
+
return bundle_path, bundle
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def _load_attempt_history(vdir: Path) -> list[dict[str, Any]]:
|
|
327
|
+
history: list[dict[str, Any]] = []
|
|
328
|
+
if not vdir.is_dir():
|
|
329
|
+
return history
|
|
330
|
+
for path in sorted(vdir.glob("attempt-*.json")):
|
|
331
|
+
try:
|
|
332
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
333
|
+
if isinstance(data, dict):
|
|
334
|
+
history.append(data)
|
|
335
|
+
except (OSError, ValueError):
|
|
336
|
+
continue
|
|
337
|
+
return history
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def record_attempt_diagnostic(
|
|
341
|
+
vdir: Path,
|
|
342
|
+
diagnostic: VerificationDiagnostic,
|
|
343
|
+
*,
|
|
344
|
+
code_digest: str = "",
|
|
345
|
+
) -> Path:
|
|
346
|
+
payload = diagnostic.to_dict()
|
|
347
|
+
if code_digest:
|
|
348
|
+
payload["code_digest"] = code_digest
|
|
349
|
+
path = vdir / f"attempt-{diagnostic.attempt}.json"
|
|
350
|
+
_atomic_write_json(path, payload)
|
|
351
|
+
return path
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
def _code_pair_digest(positive: str, negative: str) -> str:
|
|
355
|
+
norm_pos = strip_runner_wrapper(positive)
|
|
356
|
+
norm_neg = strip_runner_wrapper(negative)
|
|
357
|
+
return _sha256_text(f"{norm_pos}\n---\n{norm_neg}")
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def _rejection_class_for_failure(failure_code: str) -> str:
|
|
361
|
+
if failure_code == "positive_flaky":
|
|
362
|
+
return "flaky"
|
|
363
|
+
if failure_code in {"positive_not_triggered", "negative_false_trigger"}:
|
|
364
|
+
return "not_reproducible"
|
|
365
|
+
return "insufficient_evidence"
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
def execute_verify_attempt(
|
|
369
|
+
*,
|
|
370
|
+
root: Path,
|
|
371
|
+
state_dir: Path,
|
|
372
|
+
supervisor: Any,
|
|
373
|
+
finding: Mapping[str, Any],
|
|
374
|
+
positive: str,
|
|
375
|
+
negative: str,
|
|
376
|
+
max_attempts: int = DEFAULT_MAX_ATTEMPTS,
|
|
377
|
+
attempt: int | None = None,
|
|
378
|
+
budget_remaining: int | None = None,
|
|
379
|
+
auto_settle_terminal: bool = True,
|
|
380
|
+
) -> dict[str, Any]:
|
|
381
|
+
"""Execute one bounded verifier attempt with Anti-Gaming, diagnostic persistence & terminal settlement."""
|
|
382
|
+
max_attempts = normalize_max_attempts(max_attempts)
|
|
383
|
+
fp = str(finding.get("fingerprint") or finding.get("id") or "").strip()
|
|
384
|
+
if not fp:
|
|
385
|
+
raise ValueError("finding 缺少 fingerprint")
|
|
386
|
+
vdir = verify_dir_for_finding(state_dir, fp)
|
|
387
|
+
history = _load_attempt_history(vdir)
|
|
388
|
+
current_attempt = attempt if attempt is not None else (len(history) + 1)
|
|
389
|
+
|
|
390
|
+
if budget_remaining is not None and budget_remaining <= 0:
|
|
391
|
+
return {
|
|
392
|
+
"status": "DEFERRED_BUDGET_EXHAUSTED",
|
|
393
|
+
"fingerprint": fp,
|
|
394
|
+
"attempt": current_attempt,
|
|
395
|
+
"max_attempts": max_attempts,
|
|
396
|
+
"reason": "verification budget exhausted; finding remains pending for resume",
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
oracle_rel, oracle_hash = ensure_locked_oracle(root, finding)
|
|
400
|
+
rel_file, _ = _extract_target_file_and_line(finding)
|
|
401
|
+
target_hints = _extract_target_hints(finding, rel_file)
|
|
402
|
+
|
|
403
|
+
norm_pos = strip_runner_wrapper(positive)
|
|
404
|
+
norm_neg = strip_runner_wrapper(negative)
|
|
405
|
+
pair_digest = _code_pair_digest(norm_pos, norm_neg)
|
|
406
|
+
|
|
407
|
+
# Anti-spinlock: reject identical consecutive code submissions
|
|
408
|
+
if history and history[-1].get("code_digest") == pair_digest:
|
|
409
|
+
diag = VerificationDiagnostic(
|
|
410
|
+
finding_key=fp,
|
|
411
|
+
attempt=current_attempt,
|
|
412
|
+
failure_code="verifier_stalled",
|
|
413
|
+
stage="spinlock_guard",
|
|
414
|
+
retryable=False,
|
|
415
|
+
summary="verifier submitted identical positive/negative code on consecutive attempts",
|
|
416
|
+
created_at=time.time(),
|
|
417
|
+
)
|
|
418
|
+
diag_path = record_attempt_diagnostic(vdir, diag, code_digest=pair_digest)
|
|
419
|
+
if auto_settle_terminal:
|
|
420
|
+
supervisor.confirm_finding(
|
|
421
|
+
finding=fp,
|
|
422
|
+
decision="rejected",
|
|
423
|
+
reason=f"verify_loop 熔断(verifier_stalled):连续两轮提交相同 PoC({diag_path.name})",
|
|
424
|
+
rejection_class="insufficient_evidence",
|
|
425
|
+
)
|
|
426
|
+
return {
|
|
427
|
+
"status": "STALLED",
|
|
428
|
+
"fingerprint": fp,
|
|
429
|
+
"attempt": current_attempt,
|
|
430
|
+
"max_attempts": max_attempts,
|
|
431
|
+
"diagnostic": diag.to_dict(),
|
|
432
|
+
"diagnostic_path": str(diag_path),
|
|
433
|
+
"terminal_decision": "rejected" if auto_settle_terminal else None,
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
# 1. Shell token precheck
|
|
437
|
+
shell_err = precheck_shell_tokens(norm_pos, f"{fp} positive") or precheck_shell_tokens(norm_neg, f"{fp} negative")
|
|
438
|
+
if shell_err:
|
|
439
|
+
diag = diagnose_verification_error(
|
|
440
|
+
shell_err, attempt=current_attempt, finding_key=fp,
|
|
441
|
+
failure_code="shell_token_rejected", stage="shell_precheck",
|
|
442
|
+
)
|
|
443
|
+
return _finalize_failed_attempt(
|
|
444
|
+
root=root, state_dir=state_dir, supervisor=supervisor, finding=finding,
|
|
445
|
+
vdir=vdir, diag=diag, code_digest=pair_digest, history=history,
|
|
446
|
+
current_attempt=current_attempt, max_attempts=max_attempts,
|
|
447
|
+
auto_settle_terminal=auto_settle_terminal,
|
|
448
|
+
)
|
|
449
|
+
|
|
450
|
+
# 2. Anti-Gaming AST validation (reject trivial/empty negative control & syntax errors)
|
|
451
|
+
ast_diag = validate_python_poc_pair(
|
|
452
|
+
norm_pos, norm_neg, finding_key=fp, attempt=current_attempt, target_hints=target_hints,
|
|
453
|
+
)
|
|
454
|
+
if ast_diag is not None:
|
|
455
|
+
return _finalize_failed_attempt(
|
|
456
|
+
root=root, state_dir=state_dir, supervisor=supervisor, finding=finding,
|
|
457
|
+
vdir=vdir, diag=ast_diag, code_digest=pair_digest, history=history,
|
|
458
|
+
current_attempt=current_attempt, max_attempts=max_attempts,
|
|
459
|
+
auto_settle_terminal=auto_settle_terminal,
|
|
460
|
+
)
|
|
461
|
+
|
|
462
|
+
# 3. Snapshot target source hashes before execution (D-05 anti-tamper)
|
|
463
|
+
watched_files = [rel_file] if rel_file else []
|
|
464
|
+
before_hashes = snapshot_target_hashes(root, watched_files)
|
|
465
|
+
|
|
466
|
+
# 4. Build immutable-oracle recipe and execute via engine
|
|
467
|
+
recipe = {
|
|
468
|
+
"positive": {
|
|
469
|
+
"argv": wrap_positive_argv(norm_pos),
|
|
470
|
+
"oracle": {"kind": "exit_code", "expected_exit_code": 1},
|
|
471
|
+
},
|
|
472
|
+
"negative_control": {
|
|
473
|
+
"argv": wrap_negative_argv(norm_neg),
|
|
474
|
+
"oracle": {"kind": "exit_code", "expected_exit_code": 0},
|
|
475
|
+
},
|
|
476
|
+
"cwd": ".",
|
|
477
|
+
"timeout_seconds": 30,
|
|
478
|
+
"oracle_reference": oracle_rel,
|
|
479
|
+
"oracle_hash": oracle_hash,
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
try:
|
|
483
|
+
verify_res = supervisor.verify_finding(finding=fp, recipe=recipe)
|
|
484
|
+
except Exception as exc:
|
|
485
|
+
tampered = verify_target_hashes_unchanged(root, before_hashes)
|
|
486
|
+
if tampered:
|
|
487
|
+
diag = VerificationDiagnostic(
|
|
488
|
+
finding_key=fp, attempt=current_attempt,
|
|
489
|
+
failure_code="source_tampered_rejected", stage="anti_tamper",
|
|
490
|
+
retryable=False,
|
|
491
|
+
summary=f"PoC modified target source file(s): {', '.join(tampered)}",
|
|
492
|
+
created_at=time.time(),
|
|
493
|
+
)
|
|
494
|
+
else:
|
|
495
|
+
diag = diagnose_verification_error(
|
|
496
|
+
exc, attempt=current_attempt, finding_key=fp, stage="supervisor_verify",
|
|
497
|
+
)
|
|
498
|
+
return _finalize_failed_attempt(
|
|
499
|
+
root=root, state_dir=state_dir, supervisor=supervisor, finding=finding,
|
|
500
|
+
vdir=vdir, diag=diag, code_digest=pair_digest, history=history,
|
|
501
|
+
current_attempt=current_attempt, max_attempts=max_attempts,
|
|
502
|
+
auto_settle_terminal=auto_settle_terminal,
|
|
503
|
+
)
|
|
504
|
+
|
|
505
|
+
# 5. Post-execution source tamper check (even if receipt says CONFIRMED!)
|
|
506
|
+
tampered = verify_target_hashes_unchanged(root, before_hashes)
|
|
507
|
+
if tampered:
|
|
508
|
+
diag = VerificationDiagnostic(
|
|
509
|
+
finding_key=fp,
|
|
510
|
+
attempt=current_attempt,
|
|
511
|
+
failure_code="source_tampered_rejected",
|
|
512
|
+
stage="anti_tamper",
|
|
513
|
+
retryable=False,
|
|
514
|
+
summary=f"PoC modified target source file(s): {', '.join(tampered)}",
|
|
515
|
+
created_at=time.time(),
|
|
516
|
+
)
|
|
517
|
+
return _finalize_failed_attempt(
|
|
518
|
+
root=root, state_dir=state_dir, supervisor=supervisor, finding=finding,
|
|
519
|
+
vdir=vdir, diag=diag, code_digest=pair_digest, history=history,
|
|
520
|
+
current_attempt=current_attempt, max_attempts=max_attempts,
|
|
521
|
+
auto_settle_terminal=auto_settle_terminal,
|
|
522
|
+
)
|
|
523
|
+
|
|
524
|
+
receipt = verify_res.get("receipt") if isinstance(verify_res, Mapping) else {}
|
|
525
|
+
status = str(verify_res.get("status") or (receipt.get("status") if isinstance(receipt, Mapping) else ""))
|
|
526
|
+
if status == "CONFIRMED":
|
|
527
|
+
severity = str(finding.get("severity") or "").strip() or None
|
|
528
|
+
supervisor.confirm_finding(
|
|
529
|
+
finding=fp,
|
|
530
|
+
decision="confirmed",
|
|
531
|
+
reason=f"verify_loop 独立盲审验证通过(第 {current_attempt}/{max_attempts} 轮双正例+负对照 CONFIRMED)",
|
|
532
|
+
root_cause_verified=True,
|
|
533
|
+
oracle={"tier": "differential", "provenance_kind": "runtime-invariant", "reference": oracle_rel},
|
|
534
|
+
severity=severity,
|
|
535
|
+
)
|
|
536
|
+
summary_payload = {
|
|
537
|
+
"fingerprint": fp,
|
|
538
|
+
"status": "CONFIRMED",
|
|
539
|
+
"verified_at_attempt": current_attempt,
|
|
540
|
+
"max_attempts": max_attempts,
|
|
541
|
+
"oracle_reference": oracle_rel,
|
|
542
|
+
"oracle_hash": oracle_hash,
|
|
543
|
+
"verification_id": receipt.get("verification_id") if isinstance(receipt, Mapping) else None,
|
|
544
|
+
"attempt_history_count": len(history) + 1,
|
|
545
|
+
"completed_at": time.time(),
|
|
546
|
+
}
|
|
547
|
+
_atomic_write_json(vdir / "summary.json", summary_payload)
|
|
548
|
+
return summary_payload
|
|
549
|
+
|
|
550
|
+
diag = diagnose_verification_receipt(
|
|
551
|
+
receipt if isinstance(receipt, Mapping) else {},
|
|
552
|
+
attempt=current_attempt,
|
|
553
|
+
finding_key=fp,
|
|
554
|
+
)
|
|
555
|
+
return _finalize_failed_attempt(
|
|
556
|
+
root=root, state_dir=state_dir, supervisor=supervisor, finding=finding,
|
|
557
|
+
vdir=vdir, diag=diag, code_digest=pair_digest, history=history,
|
|
558
|
+
current_attempt=current_attempt, max_attempts=max_attempts,
|
|
559
|
+
auto_settle_terminal=auto_settle_terminal,
|
|
560
|
+
)
|
|
561
|
+
|
|
562
|
+
|
|
563
|
+
def _finalize_failed_attempt(
|
|
564
|
+
*,
|
|
565
|
+
root: Path,
|
|
566
|
+
state_dir: Path,
|
|
567
|
+
supervisor: Any,
|
|
568
|
+
finding: Mapping[str, Any],
|
|
569
|
+
vdir: Path,
|
|
570
|
+
diag: VerificationDiagnostic,
|
|
571
|
+
code_digest: str,
|
|
572
|
+
history: Sequence[Mapping[str, Any]],
|
|
573
|
+
current_attempt: int,
|
|
574
|
+
max_attempts: int,
|
|
575
|
+
auto_settle_terminal: bool,
|
|
576
|
+
) -> dict[str, Any]:
|
|
577
|
+
fp = diag.finding_key
|
|
578
|
+
diag_path = record_attempt_diagnostic(vdir, diag, code_digest=code_digest)
|
|
579
|
+
|
|
580
|
+
# Immediate circuit-breakers (D-03)
|
|
581
|
+
if diag.failure_code == "env_or_dependency_blocked":
|
|
582
|
+
summary = {
|
|
583
|
+
"status": "BLOCKED",
|
|
584
|
+
"fingerprint": fp,
|
|
585
|
+
"attempt": current_attempt,
|
|
586
|
+
"max_attempts": max_attempts,
|
|
587
|
+
"diagnostic": diag.to_dict(),
|
|
588
|
+
"diagnostic_path": str(diag_path),
|
|
589
|
+
"terminal_decision": "blocked",
|
|
590
|
+
}
|
|
591
|
+
_atomic_write_json(vdir / "summary.json", summary)
|
|
592
|
+
return summary
|
|
593
|
+
|
|
594
|
+
if diag.failure_code == "source_tampered_rejected":
|
|
595
|
+
if auto_settle_terminal:
|
|
596
|
+
supervisor.confirm_finding(
|
|
597
|
+
finding=fp,
|
|
598
|
+
decision="rejected",
|
|
599
|
+
reason=f"verify_loop 反作弊阻断(source_tampered_rejected):{diag.summary}",
|
|
600
|
+
rejection_class="insufficient_evidence",
|
|
601
|
+
)
|
|
602
|
+
summary = {
|
|
603
|
+
"status": "REJECTED",
|
|
604
|
+
"fingerprint": fp,
|
|
605
|
+
"attempt": current_attempt,
|
|
606
|
+
"max_attempts": max_attempts,
|
|
607
|
+
"diagnostic": diag.to_dict(),
|
|
608
|
+
"diagnostic_path": str(diag_path),
|
|
609
|
+
"terminal_decision": "rejected" if auto_settle_terminal else None,
|
|
610
|
+
"rejection_class": "insufficient_evidence",
|
|
611
|
+
}
|
|
612
|
+
_atomic_write_json(vdir / "summary.json", summary)
|
|
613
|
+
return summary
|
|
614
|
+
|
|
615
|
+
flaky_count = sum(1 for item in history if item.get("failure_code") == "positive_flaky") + (
|
|
616
|
+
1 if diag.failure_code == "positive_flaky" else 0
|
|
617
|
+
)
|
|
618
|
+
can_retry = (
|
|
619
|
+
diag.retryable
|
|
620
|
+
and diag.failure_code in RETRYABLE_FAILURE_CODES
|
|
621
|
+
and current_attempt < max_attempts
|
|
622
|
+
and flaky_count < 2
|
|
623
|
+
)
|
|
624
|
+
if can_retry:
|
|
625
|
+
next_bundle_path, _ = build_verify_bundle(
|
|
626
|
+
root,
|
|
627
|
+
state_dir,
|
|
628
|
+
finding,
|
|
629
|
+
attempt=current_attempt + 1,
|
|
630
|
+
max_attempts=max_attempts,
|
|
631
|
+
last_diagnostic=diag.to_dict(),
|
|
632
|
+
)
|
|
633
|
+
return {
|
|
634
|
+
"status": "RETRY",
|
|
635
|
+
"fingerprint": fp,
|
|
636
|
+
"attempt": current_attempt,
|
|
637
|
+
"next_attempt": current_attempt + 1,
|
|
638
|
+
"max_attempts": max_attempts,
|
|
639
|
+
"diagnostic": diag.to_dict(),
|
|
640
|
+
"diagnostic_path": str(diag_path),
|
|
641
|
+
"next_bundle_path": str(next_bundle_path),
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
# Terminal rejection (never silently dropped)
|
|
645
|
+
rej_class = _rejection_class_for_failure(diag.failure_code)
|
|
646
|
+
if auto_settle_terminal:
|
|
647
|
+
supervisor.confirm_finding(
|
|
648
|
+
finding=fp,
|
|
649
|
+
decision="rejected",
|
|
650
|
+
reason=(
|
|
651
|
+
f"verify_loop 验证耗尽/熔断({diag.failure_code}, "
|
|
652
|
+
f"attempt {current_attempt}/{max_attempts}):{diag.summary}"
|
|
653
|
+
),
|
|
654
|
+
rejection_class=rej_class,
|
|
655
|
+
)
|
|
656
|
+
# P1-D04: 仅当真实实跑证伪(not_reproducible)时沉淀为带源码哈希绑定的负样本护栏;
|
|
657
|
+
# 严禁把 env_blocked / timeout / source_tampered / flaky 误记为“代码安全”。
|
|
658
|
+
fp_guard_id: str | None = None
|
|
659
|
+
if rej_class == "not_reproducible" and diag.failure_code in {"positive_not_triggered", "negative_false_trigger"}:
|
|
660
|
+
rel_file, _ = _extract_target_file_and_line(finding)
|
|
661
|
+
if rel_file:
|
|
662
|
+
try:
|
|
663
|
+
from core.ledger import fp_ledger
|
|
664
|
+
rec = fp_ledger.record_false_positive(
|
|
665
|
+
root,
|
|
666
|
+
file_path=rel_file,
|
|
667
|
+
rejection_class=rej_class,
|
|
668
|
+
guard_evidence=(
|
|
669
|
+
f"verify_loop {current_attempt}/{max_attempts} 轮实跑证伪 "
|
|
670
|
+
f"({diag.failure_code}): {diag.summary}"
|
|
671
|
+
),
|
|
672
|
+
category=str(finding.get("category") or ""),
|
|
673
|
+
cwe=str(finding.get("cwe") or ""),
|
|
674
|
+
symbol=str(finding.get("symbol") or ""),
|
|
675
|
+
fingerprint=fp,
|
|
676
|
+
)
|
|
677
|
+
fp_guard_id = str(rec.get("fp_id") or "") or None
|
|
678
|
+
except Exception:
|
|
679
|
+
fp_guard_id = None
|
|
680
|
+
summary = {
|
|
681
|
+
"status": "REJECTED",
|
|
682
|
+
"fingerprint": fp,
|
|
683
|
+
"attempt": current_attempt,
|
|
684
|
+
"max_attempts": max_attempts,
|
|
685
|
+
"diagnostic": diag.to_dict(),
|
|
686
|
+
"diagnostic_path": str(diag_path),
|
|
687
|
+
"terminal_decision": "rejected" if auto_settle_terminal else None,
|
|
688
|
+
"rejection_class": rej_class,
|
|
689
|
+
"fp_guard_id": fp_guard_id,
|
|
690
|
+
}
|
|
691
|
+
_atomic_write_json(vdir / "summary.json", summary)
|
|
692
|
+
return summary
|
|
693
|
+
|
|
694
|
+
|
|
695
|
+
def run_verification_loop(
|
|
696
|
+
*,
|
|
697
|
+
root: Path,
|
|
698
|
+
state_dir: Path,
|
|
699
|
+
supervisor: Any,
|
|
700
|
+
finding: Mapping[str, Any],
|
|
701
|
+
proposer: Callable[[Mapping[str, Any]], Mapping[str, Any]],
|
|
702
|
+
max_attempts: int = DEFAULT_MAX_ATTEMPTS,
|
|
703
|
+
budget_remaining: int | None = None,
|
|
704
|
+
auto_settle_terminal: bool = True,
|
|
705
|
+
) -> dict[str, Any]:
|
|
706
|
+
"""Drive the full error-driven PoC self-correction loop via a pluggable Verifier proposer."""
|
|
707
|
+
max_attempts = normalize_max_attempts(max_attempts)
|
|
708
|
+
last_diag: Mapping[str, Any] | None = None
|
|
709
|
+
remaining = budget_remaining
|
|
710
|
+
|
|
711
|
+
for attempt_no in range(1, max_attempts + 1):
|
|
712
|
+
if remaining is not None and remaining <= 0:
|
|
713
|
+
return {
|
|
714
|
+
"status": "DEFERRED_BUDGET_EXHAUSTED",
|
|
715
|
+
"fingerprint": str(finding.get("fingerprint") or ""),
|
|
716
|
+
"attempt": attempt_no,
|
|
717
|
+
"max_attempts": max_attempts,
|
|
718
|
+
"reason": "verification budget exhausted; finding remains pending for resume",
|
|
719
|
+
}
|
|
720
|
+
_, bundle = build_verify_bundle(
|
|
721
|
+
root,
|
|
722
|
+
state_dir,
|
|
723
|
+
finding,
|
|
724
|
+
attempt=attempt_no,
|
|
725
|
+
max_attempts=max_attempts,
|
|
726
|
+
last_diagnostic=last_diag,
|
|
727
|
+
)
|
|
728
|
+
proposal = proposer(bundle) or {}
|
|
729
|
+
if remaining is not None:
|
|
730
|
+
remaining -= 1
|
|
731
|
+
result = execute_verify_attempt(
|
|
732
|
+
root=root,
|
|
733
|
+
state_dir=state_dir,
|
|
734
|
+
supervisor=supervisor,
|
|
735
|
+
finding=finding,
|
|
736
|
+
positive=str(proposal.get("positive") or ""),
|
|
737
|
+
negative=str(proposal.get("negative") or ""),
|
|
738
|
+
max_attempts=max_attempts,
|
|
739
|
+
attempt=attempt_no,
|
|
740
|
+
budget_remaining=(None if remaining is None else remaining + 1),
|
|
741
|
+
auto_settle_terminal=auto_settle_terminal,
|
|
742
|
+
)
|
|
743
|
+
if result.get("status") != "RETRY":
|
|
744
|
+
return result
|
|
745
|
+
last_diag = result.get("diagnostic")
|
|
746
|
+
|
|
747
|
+
return {
|
|
748
|
+
"status": "REJECTED",
|
|
749
|
+
"fingerprint": str(finding.get("fingerprint") or ""),
|
|
750
|
+
"attempt": max_attempts,
|
|
751
|
+
"max_attempts": max_attempts,
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
|
|
755
|
+
__all__ = [
|
|
756
|
+
"DEFAULT_MAX_ATTEMPTS",
|
|
757
|
+
"HARD_MAX_ATTEMPTS",
|
|
758
|
+
"verify_dir_for_finding",
|
|
759
|
+
"ensure_locked_oracle",
|
|
760
|
+
"build_verify_bundle",
|
|
761
|
+
"record_attempt_diagnostic",
|
|
762
|
+
"execute_verify_attempt",
|
|
763
|
+
"run_verification_loop",
|
|
764
|
+
"normalize_max_attempts",
|
|
765
|
+
"strip_runner_wrapper",
|
|
766
|
+
"precheck_shell_tokens",
|
|
767
|
+
]
|