bugx-cli 0.1.1 → 0.1.3

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.
Files changed (131) hide show
  1. package/README.md +36 -35
  2. package/core/README.md +1 -1
  3. package/core/agent/agent_orchestrator.py +3 -0
  4. package/core/agent/agent_workspace.py +14 -2
  5. package/core/assets/README.md +3 -2
  6. package/core/assets/bugx-social-preview.svg +71 -0
  7. package/core/assets/bugx-wechat-group.png +0 -0
  8. package/core/assets/twitter_promo_art.jpg +0 -0
  9. package/core/assets/twitter_promo_card.svg +166 -0
  10. package/core/assets/twitter_promo_clean.jpg +0 -0
  11. package/core/assets/twitter_terminal_real.png +0 -0
  12. package/core/audit_packs/README.md +2 -0
  13. package/core/audit_packs/pitfalls/auth_crypto.json +64 -0
  14. package/core/audit_packs/pitfalls/file_ssrf_cmd.json +64 -0
  15. package/core/audit_packs/pitfalls/go_backend.json +66 -0
  16. package/core/audit_packs/pitfalls/java_spring.json +64 -0
  17. package/core/audit_packs/pitfalls/js_ts_web.json +67 -0
  18. package/core/audit_packs/pitfalls/python_web.json +82 -0
  19. package/core/bugx.md +2 -2
  20. package/core/bugx_paths.py +2 -2
  21. package/core/cli-help.txt +1 -1
  22. package/core/cloud_sync/cloud_client.py +56 -5
  23. package/core/cloud_sync/consent.py +33 -3
  24. package/core/cloud_sync/flywheel_client.py +186 -24
  25. package/core/contracts/README.md +1 -1
  26. package/core/contracts/bugx-opencode.md +1 -1
  27. package/core/contracts/bugx-runtime-contract.md +1 -1
  28. package/core/contracts/bugx-worker.md +1 -1
  29. package/core/engine-integrity.json +191 -95
  30. package/core/host_acp/kimi.py +175 -0
  31. package/core/host_acp/minimax.py +28 -0
  32. package/core/host_runtime/host_registry.py +23 -3
  33. package/core/hosts/dsh.py +1 -1
  34. package/core/hosts/kimi.py +293 -0
  35. package/core/hosts/minimax.py +248 -0
  36. package/core/hosts/zcode.py +5 -0
  37. package/core/infra/README.md +1 -1
  38. package/core/infra/build_info.py +30 -5
  39. package/core/launch_phases/README.md +6 -3
  40. package/core/launch_phases/finding_confirm_phase.py +168 -7
  41. package/core/launch_phases/post_phase.py +5 -5
  42. package/core/launch_phases/pre_recon_scout.py +13 -0
  43. package/core/launch_phases/report_sharing.py +3 -7
  44. package/core/launch_phases/round_orchestrator.py +114 -26
  45. package/core/launch_phases/semantic_recon.py +545 -0
  46. package/core/launch_phases/startup_version_gate.py +6 -2
  47. package/core/launch_phases/supervisor_bridge.py +14 -23
  48. package/core/launch_phases/verify_loop.py +767 -0
  49. package/core/launch_phases/worker_prior.py +115 -0
  50. package/core/ledger/README.md +2 -1
  51. package/core/ledger/finding_verification.py +511 -2
  52. package/core/ledger/fp_ledger.py +255 -0
  53. package/core/metadata.txt +2 -2
  54. package/core/planning/README.md +2 -1
  55. package/core/planning/prompt_harness.py +50 -10
  56. package/core/planning/prompt_policy_engine.py +386 -0
  57. package/core/prompts/README.md +4 -2
  58. package/core/prompts/policies/prompt_policies.json +101 -0
  59. package/core/prompts/stages/stage_verify.defensive.md +42 -0
  60. package/core/prompts/stages/stage_verify.md +44 -0
  61. package/core/report_engine/report_share.py +0 -8
  62. package/core/retrieval/README.md +2 -1
  63. package/core/retrieval/pitfall_packs.py +277 -0
  64. package/core/runtime/README.md +1 -1
  65. package/core/runtime/global_telemetry.py +20 -0
  66. package/core/runtime/scenario_eval.py +1 -1
  67. package/core/runtime/setup_ui_env.py +4 -7
  68. package/core/supervisor/README.md +1 -1
  69. package/core/supervisor/cli.py +2 -2
  70. package/core/webui/mcp_inspector.py +6 -0
  71. package/core/webui/static/index.html +51 -3
  72. package/core/webui/static/manifest.webmanifest +1 -1
  73. package/core/webui/static/project-settings.js +18 -3
  74. package/core/webui/static/robots.txt +36 -0
  75. package/core/webui/static/sitemap.xml +15 -0
  76. package/docs/07_distribution/01_README_NPM.md +36 -35
  77. package/ecosystem/integrations/cline/skills/bugx/SKILL.md +1 -1
  78. package/ecosystem/integrations/dsh/agents/bugx.md +1 -1
  79. package/ecosystem/integrations/dsh/dsh-patch.yml +2 -2
  80. package/ecosystem/integrations/dsh/mcp/package.json +1 -1
  81. package/ecosystem/integrations/dsh/skills/bugx/SKILL.md +1 -1
  82. package/ecosystem/integrations/dsh/skills/bugx-dsh/SKILL.md +1 -1
  83. package/ecosystem/integrations/dsh/ui/package.json +1 -1
  84. package/ecosystem/integrations/opencode/bugx-mcp-manifest.json +1 -1
  85. package/ecosystem/integrations/pi/extensions/bugx/manifest.json +1 -1
  86. package/ecosystem/integrations/pi/skills/bugx/SKILL.md +1 -1
  87. package/ecosystem/integrations/qoder/connector-meta.json +9 -9
  88. package/ecosystem/integrations/workbuddy/connector-meta.json +9 -9
  89. package/ecosystem/integrations/workbuddy/skills/bugx/SKILL.md +2 -2
  90. package/ecosystem/plugins/bugx/.claude-plugin/marketplace.json +2 -2
  91. package/ecosystem/plugins/bugx/.claude-plugin/plugin.json +2 -2
  92. package/ecosystem/plugins/bugx/.codex-plugin/plugin.json +4 -4
  93. package/ecosystem/plugins/bugx/.zcode-plugin/plugin.json +2 -2
  94. package/ecosystem/plugins/bugx/agents/bugx-worker.md +1 -1
  95. package/ecosystem/plugins/bugx/agents/bugx.md +1 -1
  96. package/ecosystem/plugins/bugx/skills/bugx/SKILL.md +3 -3
  97. package/ecosystem/plugins/bugx/skills/bugx-claude/SKILL.md +1 -1
  98. package/ecosystem/plugins/bugx/skills/bugx-dsh/SKILL.md +1 -1
  99. package/ecosystem/plugins/bugx/skills/bugx-opencode/SKILL.md +1 -1
  100. package/ecosystem/plugins/bugx/skills/bugx-zcode/SKILL.md +1 -1
  101. package/interfaces/bin/bugx.js +9 -7
  102. package/interfaces/cli/bugx_cli/__init__.py +2 -2
  103. package/interfaces/cli/bugx_cli/cli.py +178 -67
  104. package/interfaces/cli/bugx_cli/commands/agent.py +313 -127
  105. package/interfaces/cli/bugx_cli/commands/audit.py +8 -7
  106. package/interfaces/cli/bugx_cli/commands/cloud.py +27 -19
  107. package/interfaces/cli/bugx_cli/commands/doctor.py +18 -0
  108. package/interfaces/cli/bugx_cli/commands/knowledge.py +3 -4
  109. package/interfaces/cli/bugx_cli/commands/lifecycle.py +54 -47
  110. package/interfaces/cli/bugx_cli/commands/plugin.py +9 -9
  111. package/interfaces/cli/bugx_cli/commands/plugin_claude.py +27 -13
  112. package/interfaces/cli/bugx_cli/commands/plugin_kimi.py +348 -0
  113. package/interfaces/cli/bugx_cli/commands/plugin_minimax.py +322 -0
  114. package/interfaces/cli/bugx_cli/commands/plugin_qoder.py +3 -4
  115. package/interfaces/cli/bugx_cli/commands/plugin_zcode.py +4 -5
  116. package/interfaces/cli/bugx_cli/commands/project.py +6 -13
  117. package/interfaces/cli/bugx_cli/commands/system.py +577 -162
  118. package/interfaces/cli/bugx_cli/common.py +102 -15
  119. package/interfaces/cli/bugx_cli/host_adapters.py +150 -4
  120. package/interfaces/cli/bugx_cli/hosts/registry.py +4 -2
  121. package/interfaces/cli/bugx_cli/hosts/template_engine.py +10 -9
  122. package/interfaces/cli/bugx_cli/infra/engine_installer.py +21 -10
  123. package/interfaces/cli/bugx_cli/infra/host_sync.py +1 -1
  124. package/interfaces/cli/bugx_cli/infra/mcp_advisor.py +2 -2
  125. package/package.json +54 -16
  126. package/pyproject.toml +64 -1
  127. package/scripts/sync-version.mjs +1 -1
  128. package/skills/README.md +25 -0
  129. package/skills/platform/bugx-user/SKILL.md +92 -0
  130. package/core/assets/bugx-hero-cn.png +0 -0
  131. package/core/assets/bugx-hero-en.png +0 -0
@@ -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
+ ]