bugx-cli 0.1.5 → 0.1.6

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 (86) hide show
  1. package/README.md +89 -210
  2. package/core/README.md +1 -1
  3. package/core/agent/agent_targets.py +5 -1
  4. package/core/agent/agent_workspace.py +10 -2
  5. package/core/autonomous_cve/run_fault_matrix.py +692 -0
  6. package/core/autonomous_cve/run_oss_cve_exploit_verify.py +608 -0
  7. package/core/autonomous_cve/run_six_worker_penetration.py +382 -0
  8. package/core/autonomous_cve/verifier.py +5 -7
  9. package/core/bugx.md +1 -1
  10. package/core/bugx_paths.py +2 -2
  11. package/core/bundled_docs/OVERVIEW.md +69 -236
  12. package/core/bundled_docs/README.md +2 -2
  13. package/core/bundled_docs/README_EN.md +67 -211
  14. package/core/bundled_docs/ai/01_AI_REFERENCE.md +3 -3
  15. package/core/bundled_docs/ai/02_AI_USAGE.md +1 -1
  16. package/core/bundled_docs/ai/03_AI_COMMANDS.md +1 -1
  17. package/core/bundled_docs/hosts/bugx_SKILL.md +2 -2
  18. package/core/bundled_docs/hosts/platform_bugx_SKILL.md +2 -2
  19. package/core/bundled_docs/manifest.json +10 -10
  20. package/core/bundled_docs/reference/04_REPOSITORY_TOPOLOGY.md +1 -1
  21. package/core/cloud_sync/flywheel_client.py +89 -0
  22. package/core/contracts/README.md +1 -1
  23. package/core/contracts/bugx-runtime-contract.md +1 -1
  24. package/core/contracts/bugx-worker.md +1 -1
  25. package/core/coverage/coverage_gate.py +12 -2
  26. package/core/coverage/coverage_manifest.py +1 -1
  27. package/core/coverage/coverage_validate.py +5 -3
  28. package/core/engine-integrity.json +104 -92
  29. package/core/host_runtime/adapters.py +45 -6
  30. package/core/host_runtime/autonomous_runner.py +3 -2
  31. package/core/host_runtime/host_registry.py +6 -1
  32. package/core/hosts/__init__.py +1 -0
  33. package/core/hosts/agnescode.py +1 -1
  34. package/core/hosts/base.py +1 -0
  35. package/core/hosts/claude.py +6 -0
  36. package/core/hosts/cline.py +6 -0
  37. package/core/hosts/codex.py +10 -1
  38. package/core/hosts/kimi.py +6 -4
  39. package/core/hosts/opencode.py +1 -1
  40. package/core/hosts/zcode.py +6 -0
  41. package/core/infra/README.md +1 -1
  42. package/core/infra/build_info.py +2 -2
  43. package/core/launch_phases/README.md +2 -2
  44. package/core/launch_phases/startup_gates.py +10 -1
  45. package/core/launch_phases/startup_version_gate.py +2 -2
  46. package/core/ledger/README.md +1 -1
  47. package/core/locales/en-US.json +2 -0
  48. package/core/locales/zh-CN.json +2 -0
  49. package/core/mcp_handlers/supervisor_handlers.py +33 -1
  50. package/core/mcp_handlers/telemetry_handlers.py +32 -0
  51. package/core/mcp_handlers/tool_table.py +34 -0
  52. package/core/metadata.txt +1 -1
  53. package/core/planning/README.md +1 -1
  54. package/core/retrieval/README.md +1 -1
  55. package/core/retrieval/symbol_index.py +2 -1
  56. package/core/retrieval/universal_code_matcher.py +1 -0
  57. package/core/runtime/README.md +1 -1
  58. package/core/runtime/mining_quality_framework.py +2 -1
  59. package/core/runtime/scenario_eval.py +5 -2
  60. package/core/supervisor/README.md +1 -1
  61. package/core/supervisor/worker_execution.py +5 -0
  62. package/docs/07_distribution/01_README_NPM.md +89 -210
  63. package/ecosystem/integrations/dsh/mcp/package.json +2 -2
  64. package/ecosystem/integrations/dsh/ui/package.json +1 -1
  65. package/ecosystem/integrations/opencode/bugx-mcp-manifest.json +1 -1
  66. package/ecosystem/integrations/pi/extensions/bugx/manifest.json +1 -1
  67. package/ecosystem/integrations/qoder/connector-meta.json +1 -1
  68. package/ecosystem/integrations/workbuddy/connector-meta.json +1 -1
  69. package/ecosystem/integrations/workbuddy/skills/bugx/SKILL.md +1 -1
  70. package/ecosystem/plugins/bugx/.claude-plugin/plugin.json +1 -1
  71. package/ecosystem/plugins/bugx/.codex-plugin/plugin.json +1 -1
  72. package/ecosystem/plugins/bugx/.zcode-plugin/plugin.json +1 -1
  73. package/ecosystem/plugins/bugx/skills/bugx/SKILL.md +2 -2
  74. package/interfaces/cli/bugx_cli/__init__.py +1 -1
  75. package/interfaces/cli/bugx_cli/commands/agent.py +18 -0
  76. package/interfaces/cli/bugx_cli/commands/audit.py +3 -5
  77. package/interfaces/cli/bugx_cli/commands/doctor.py +1 -1
  78. package/interfaces/cli/bugx_cli/commands/plugin.py +20 -0
  79. package/interfaces/cli/bugx_cli/commands/plugin_claude.py +2 -2
  80. package/interfaces/cli/bugx_cli/host_adapters.py +161 -1
  81. package/interfaces/cli/bugx_cli/hosts/registry.py +32 -0
  82. package/interfaces/cli/bugx_cli/infra/engine_installer.py +4 -4
  83. package/interfaces/cli/bugx_cli/infra/host_sync.py +1 -1
  84. package/package.json +1 -1
  85. package/scripts/sync-version.mjs +1 -1
  86. package/skills/platform/bugx/SKILL.md +2 -2
@@ -0,0 +1,692 @@
1
+ #!/usr/bin/env python3
2
+ """scripts/run_fault_matrix.py - Gate 5 自动化 9 类故障注入与异常恢复矩阵验证器 (DOC-155)。
3
+
4
+ 覆盖 9 类核心故障注入场景:
5
+ 1. acp_timeout_or_cancel: ACP 超时/取消 -> 有限等待,进入 ABORTED 或 RECOVERY_REQUIRED
6
+ 2. mcp_tool_failure: MCP 工具执行失败 -> 错误被记录,任务进入明确终态
7
+ 3. checkpoint_failure_retry: checkpoint 校验失败/重试 -> 拒绝非法 checkpoint,状态不被伪造
8
+ 4. heartbeat_loss_lease_reclaim: 心跳丢失/租约过期 -> claim 被自动回收,单元恢复可领取
9
+ 5. provider_rate_limit_429: Provider 429 限流 -> 触发退避重试,超限后明确失败,不无限等待
10
+ 6. budget_exhausted: 运行预算(时间/轮次)耗尽 -> 进入预算终态,记录可审计原因
11
+ 7. open_findings_block: 存在未收敛 open Finding -> 阻断自治完成,绝不伪报成功
12
+ 8. host_output_truncation: 宿主输出截断/工件破损 -> 校验器识别证据不完整,Fail-closed
13
+ 9. target_drift_rebind: 代码目标指纹漂移 -> 严格拒绝并报错,不静默接受漂移
14
+
15
+ 运行后在指定目录生成标准化机器可读收据: ``fault-matrix-receipt.json``。
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import argparse
21
+ import hashlib
22
+ import json
23
+ import signal
24
+ import shutil
25
+ import sys
26
+ import tempfile
27
+ import time
28
+ from contextlib import contextmanager
29
+ from dataclasses import asdict, dataclass
30
+ from pathlib import Path
31
+ from typing import Any, Callable, Iterator
32
+
33
+ REPO_ROOT = Path(__file__).resolve().parent.parent.parent
34
+ CORE_DIR = REPO_ROOT / "core"
35
+ SRC_DIR = REPO_ROOT / "src"
36
+
37
+ for p in (REPO_ROOT, CORE_DIR, SRC_DIR):
38
+ if str(p) not in sys.path:
39
+ sys.path.insert(0, str(p))
40
+
41
+ from core.supervisor.audit_supervisor import Supervisor # noqa: E402
42
+ from core.supervisor.supervisor_models import ( # noqa: E402
43
+ RunBudget,
44
+ BudgetExhausted,
45
+ LeaseExpired,
46
+ ClaimRejected,
47
+ SupervisorError,
48
+ )
49
+ import core.launch_phases.session_runtime as sr # noqa: E402
50
+ from core.launch_phases import common as launch_common # noqa: E402
51
+ from core.launch_phases.post_phase import ( # noqa: E402
52
+ _continue_after_death,
53
+ verify_acceptance_receipt,
54
+ )
55
+
56
+
57
+ @dataclass
58
+ class FaultCaseResult:
59
+ case_id: str
60
+ name: str
61
+ status: str # PASSED | FAILED | BLOCKED
62
+ expected_outcome: str
63
+ actual_outcome: str
64
+ details: dict[str, Any]
65
+ duration_seconds: float
66
+ error_message: str | None = None
67
+
68
+
69
+ class _FakeClock:
70
+ """可注入的确定性时钟:让「租约过期」变成显式事件而不是墙钟竞态。
71
+
72
+ ``Supervisor(clock=...)`` 是生产代码既有的注入点(budget/租约判定的唯一时间源),
73
+ 故障矩阵复用它,才能在**不 sleep** 的前提下证明过期语义,并让用例耗时与机器负载
74
+ 完全解耦。
75
+ """
76
+
77
+ def __init__(self, start: float = 0.0) -> None:
78
+ self._now = float(start)
79
+
80
+ def __call__(self) -> float:
81
+ return self._now
82
+
83
+ def advance(self, seconds: float) -> float:
84
+ self._now += float(seconds)
85
+ return self._now
86
+
87
+
88
+ class FaultMatrixRunner:
89
+ def __init__(
90
+ self,
91
+ sandbox_root: Path | None = None,
92
+ output_receipt: Path | None = None,
93
+ case_timeout_seconds: float = 15.0,
94
+ ):
95
+ self.sandbox_root = sandbox_root
96
+ self.output_receipt = output_receipt
97
+ self.case_timeout_seconds = case_timeout_seconds
98
+ self.results: list[FaultCaseResult] = []
99
+
100
+ @contextmanager
101
+ def _case_timeout(self) -> Iterator[None]:
102
+ """Bound one injected case on POSIX hosts; other hosts keep normal flow."""
103
+ if not hasattr(signal, "SIGALRM"):
104
+ yield
105
+ return
106
+ previous = signal.getsignal(signal.SIGALRM)
107
+
108
+ def timeout_handler(_signum: int, _frame: Any) -> None:
109
+ raise TimeoutError(
110
+ f"fault case exceeded {self.case_timeout_seconds:.1f}s timeout"
111
+ )
112
+
113
+ signal.signal(signal.SIGALRM, timeout_handler)
114
+ signal.setitimer(signal.ITIMER_REAL, self.case_timeout_seconds)
115
+ try:
116
+ yield
117
+ finally:
118
+ signal.setitimer(signal.ITIMER_REAL, 0)
119
+ signal.signal(signal.SIGALRM, previous)
120
+
121
+ def _create_temp_case_dir(self, case_id: str) -> Path:
122
+ if self.sandbox_root and self.sandbox_root.is_dir():
123
+ base = self.sandbox_root / ".bugx" / "fault_matrix_scratch" / case_id
124
+ shutil.rmtree(base, ignore_errors=True)
125
+ base.mkdir(parents=True, exist_ok=True)
126
+ return base
127
+ return Path(tempfile.mkdtemp(prefix=f"bugx-fault-{case_id}-"))
128
+
129
+ def _cleanup_dir(self, path: Path) -> None:
130
+ if not (self.sandbox_root and self.sandbox_root in path.parents):
131
+ shutil.rmtree(path, ignore_errors=True)
132
+
133
+ def run_all(self) -> bool:
134
+ cases: list[tuple[str, str, Callable[[Path], FaultCaseResult]]] = [
135
+ ("acp_timeout_or_cancel", "1. ACP 超时与客户端取消自愈", self.test_acp_timeout_or_cancel),
136
+ ("mcp_tool_failure", "2. MCP 工具调用失败与错误审计", self.test_mcp_tool_failure),
137
+ ("checkpoint_failure_retry", "3. Checkpoint 校验失败重试与防伪拦截", self.test_checkpoint_failure_retry),
138
+ ("heartbeat_loss_lease_reclaim", "4. 心跳丢失与租约过期回收", self.test_heartbeat_loss_lease_reclaim),
139
+ ("provider_rate_limit_429", "5. 模型 Provider 429 限流退避与阻断", self.test_provider_rate_limit_429),
140
+ ("budget_exhausted", "6. 生命周期时间预算耗尽审计终态", self.test_budget_exhausted),
141
+ ("open_findings_block", "7. 未裁决 Open Finding 阻断完成终态", self.test_open_findings_block),
142
+ ("host_output_truncation", "8. 宿主输出截断与损坏回执 Fail-Closed", self.test_host_output_truncation),
143
+ ("target_drift_rebind", "9. 目标指纹漂移拒绝与防御", self.test_target_drift_rebind),
144
+ ]
145
+
146
+ print(f"\n{'='*70}")
147
+ print(f"🚀 启动 BugX Gate 5 故障注入与异常恢复矩阵自动化检验 (9 项)")
148
+ print(f"{'='*70}\n")
149
+
150
+ all_ok = True
151
+ for case_id, name, runner_fn in cases:
152
+ work_dir = self._create_temp_case_dir(case_id)
153
+ start_t = time.perf_counter()
154
+ print(f"▶ 正在执行 [{case_id}] {name} ...", end=" ", flush=True)
155
+ try:
156
+ with self._case_timeout():
157
+ res = runner_fn(work_dir)
158
+ dur = time.perf_counter() - start_t
159
+ res.duration_seconds = round(dur, 3)
160
+ if res.status == "PASSED":
161
+ print(f"✅ PASSED ({dur:.3f}s)")
162
+ else:
163
+ print(f"❌ {res.status} ({dur:.3f}s): {res.error_message}")
164
+ all_ok = False
165
+ self.results.append(res)
166
+ except Exception as e:
167
+ dur = time.perf_counter() - start_t
168
+ print(f"💥 EXCEPTION ({dur:.3f}s): {e}")
169
+ self.results.append(
170
+ FaultCaseResult(
171
+ case_id=case_id,
172
+ name=name,
173
+ status="FAILED",
174
+ expected_outcome="Handle gracefully",
175
+ actual_outcome=f"Unhandled Exception: {type(e).__name__}",
176
+ details={"exception": str(e)},
177
+ duration_seconds=round(dur, 3),
178
+ error_message=str(e),
179
+ )
180
+ )
181
+ all_ok = False
182
+ finally:
183
+ self._cleanup_dir(work_dir)
184
+
185
+ self._generate_receipt(all_ok)
186
+ return all_ok
187
+
188
+ # --- 1. ACP 超时与客户端取消 ---
189
+ def test_acp_timeout_or_cancel(self, work_dir: Path) -> FaultCaseResult:
190
+ from unittest.mock import patch
191
+ runtime_file = work_dir / "runtime.json"
192
+ sup_file = work_dir / "audit-supervisor.json"
193
+ sup_file.write_text('{"status": "INACTIVE"}\n', encoding="utf-8")
194
+
195
+ now = time.time()
196
+ stale_runtime = {
197
+ **sr._default_runtime(),
198
+ "run_id": "r-acp-timeout-test",
199
+ "state": "running",
200
+ "active": True,
201
+ "pid": 99999998, # 死 PID,模拟进程孤立退出
202
+ "started_at": sr._iso_time(now - 3600),
203
+ "started_epoch": now - 3600,
204
+ "segment_started_epoch": now - 3600,
205
+ "heartbeat_at": sr._iso_time(now - 3600),
206
+ "heartbeat_epoch": now - 3600,
207
+ "sessions_aborted": 0,
208
+ }
209
+ runtime_file.write_text(json.dumps(stale_runtime, indent=2), encoding="utf-8")
210
+
211
+ # 加载 runtime 时应自动识别死 PID 并安全降级为 aborted
212
+ with sr._pinned_runtime_paths(runtime_file), \
213
+ patch.object(sr, "SUPERVISOR_STATE", sup_file):
214
+ loaded = sr._load_runtime()
215
+
216
+ actual_state = loaded.get("state")
217
+ reconciled = any(e.get("event") == "orphaned_session_reconciled" for e in loaded.get("events", []))
218
+ passed = actual_state == "aborted" and reconciled
219
+
220
+ return FaultCaseResult(
221
+ case_id="acp_timeout_or_cancel",
222
+ name="ACP 超时与客户端取消自愈",
223
+ status="PASSED" if passed else "FAILED",
224
+ expected_outcome="state=aborted, orphaned_session_reconciled event emitted",
225
+ actual_outcome=f"state={actual_state}, reconciled={reconciled}",
226
+ details={"runtime": loaded},
227
+ duration_seconds=0.0,
228
+ error_message=None if passed else f"Unexpected state: {actual_state}",
229
+ )
230
+
231
+ # --- 2. MCP 工具执行失败 ---
232
+ def test_mcp_tool_failure(self, work_dir: Path) -> FaultCaseResult:
233
+ sup = Supervisor(work_dir, state_path=work_dir / "supervisor.json")
234
+ sup.start(coverage_units=["内部:测试工具异常"])
235
+ w_id = "worker-tool-fail-01"
236
+ claim = sup.claim_worker(w_id, unit_ids=["内部:测试工具异常"], lease_seconds=60.0)
237
+ sup.start_worker(w_id)
238
+
239
+ # 记录 tool_call
240
+ sup.record_tool_call(w_id, tool_name="failing_tool")
241
+
242
+ # 模拟 MCP 工具抛错或执行失败,调用 record_worker_failure
243
+ error_msg = "MCP ToolExecutionError: exit code 127"
244
+ failure_claim = sup.record_worker_failure(
245
+ w_id,
246
+ lease_id=claim.lease_id,
247
+ execution_id=claim.execution_id,
248
+ reason=error_msg,
249
+ )
250
+
251
+ st = sup.status()
252
+ # 验证该工具失败事件已被 Supervisor 记录,Worker 进入 released 状态
253
+ has_claim = w_id in st.claims
254
+ passed = has_claim and failure_claim is not None and failure_claim.state == "released"
255
+ return FaultCaseResult(
256
+ case_id="mcp_tool_failure",
257
+ name="MCP 工具调用失败与错误审计",
258
+ status="PASSED" if passed else "FAILED",
259
+ expected_outcome="Tool failure logged in history without crashing supervisor",
260
+ actual_outcome=f"supervisor_status={st.status}, claim_state={getattr(failure_claim, 'state', None)}",
261
+ details={"supervisor_status": str(st.status)},
262
+ duration_seconds=0.0,
263
+ )
264
+
265
+ # --- 3. Checkpoint 校验失败重试 ---
266
+ def test_checkpoint_failure_retry(self, work_dir: Path) -> FaultCaseResult:
267
+ sup = Supervisor(work_dir, state_path=work_dir / "supervisor.json")
268
+ sup.start(coverage_units=["内部:校验拦截测试"])
269
+ w_id = "worker-checkpoint-fail"
270
+ claim = sup.claim_worker(w_id, unit_ids=["内部:校验拦截测试"], lease_seconds=60.0)
271
+ sup.start_worker(w_id)
272
+
273
+ # 提交缺失 11 字段中的必要字段、或 sha256 错误的非法 checkpoint
274
+ bad_evidence = {
275
+ "内部:校验拦截测试": {
276
+ "artifact_path": "invalid/path.txt",
277
+ "artifact_sha256": "bad_sha256_format",
278
+ # 缺失 command, exit_code, lease_id 等
279
+ }
280
+ }
281
+
282
+ rejected = False
283
+ rejection_reason = ""
284
+ # 尝试提交重试 3 次,均应被拒绝
285
+ for retry in range(3):
286
+ try:
287
+ sup.submit_checkpoint(
288
+ w_id,
289
+ coverage={"内部:校验拦截测试": "covered"},
290
+ evidence=bad_evidence,
291
+ )
292
+ except Exception as e:
293
+ rejected = True
294
+ rejection_reason = str(e)
295
+
296
+ # 验证单元未被篡改状态
297
+ st = sup.status()
298
+ unit_state = st.coverage.get("内部:校验拦截测试")
299
+ passed = rejected and unit_state != "covered"
300
+
301
+ return FaultCaseResult(
302
+ case_id="checkpoint_failure_retry",
303
+ name="Checkpoint 校验失败重试与防伪拦截",
304
+ status="PASSED" if passed else "FAILED",
305
+ expected_outcome="Checkpoint rejected with InvalidCheckpoint, unit state remains pending/claimed",
306
+ actual_outcome=f"rejected={rejected}, unit_state={unit_state}, reason={rejection_reason}",
307
+ details={"unit_state": unit_state, "rejection_reason": rejection_reason},
308
+ duration_seconds=0.0,
309
+ error_message=None if passed else "Illegal checkpoint was accepted!",
310
+ )
311
+
312
+ # --- 4. 心跳丢失与租约回收 ---
313
+ def test_heartbeat_loss_lease_reclaim(self, work_dir: Path) -> FaultCaseResult:
314
+ """租约过期必须「拒绝旧提交 + 单元可被重新领取」两件事同时成立。
315
+
316
+ 旧实现用 ``lease_seconds=0.1`` + ``time.sleep(0.25)`` 制造过期:claim 与
317
+ ``start_worker`` 之间只要被负载拉长跨过到期点,`start_worker` 就会抛
318
+ ``ClaimRejected(worker claim 不可提交: ... (expired))``(**不是** ``LeaseExpired``),
319
+ 用例以 EXCEPTION 收场。实测 2026-10-23 全量矩阵 8/9 通过、单独跑该用例又通过 ——
320
+ 典型的墙钟竞态 flaky,属明文禁止的魔法数字断言。
321
+
322
+ 现在改为注入 ``clock`` 把「过期」变成确定性事件:不再 sleep,也不再依赖机器速度;
323
+ 并把判定收紧为 ``lease_expired_caught and reclaimed``(旧实现用 ``or``,
324
+ 只证明「拒绝」或只证明「回收」都能过,等于没验证回收闭环)。
325
+ """
326
+ clock = _FakeClock(1000.0)
327
+ sup = Supervisor(
328
+ work_dir, state_path=work_dir / "supervisor.json", clock=clock, mono_clock=clock,
329
+ )
330
+ sup.start(coverage_units=["内部:心跳回收测试"])
331
+ unit = "内部:心跳回收测试"
332
+ w_id = "worker-stale-heartbeat"
333
+ lease_window = 5.0
334
+ sup.claim_worker(w_id, unit_ids=[unit], lease_seconds=lease_window)
335
+ sup.start_worker(w_id)
336
+
337
+ # 心跳丢失:Worker 不再续期,时钟越过租约到期点(确定性,无 sleep)。
338
+ clock.advance(lease_window * 2)
339
+
340
+ lease_expired_caught = False
341
+ try:
342
+ sup.submit_checkpoint(w_id, coverage={unit: "covered"})
343
+ except LeaseExpired:
344
+ lease_expired_caught = True
345
+ except SupervisorError:
346
+ lease_expired_caught = True
347
+
348
+ # 过期 claim 释放后,新 Worker 必须能重新领取同一单元(否则单元被永久吞噬)。
349
+ new_w_id = "worker-reclaim-02"
350
+ reclaimed = False
351
+ try:
352
+ new_claim = sup.claim_worker(
353
+ new_w_id, unit_ids=[unit], lease_seconds=lease_window,
354
+ )
355
+ reclaimed = bool(new_claim and unit in tuple(new_claim.unit_ids))
356
+ except SupervisorError:
357
+ reclaimed = False
358
+
359
+ passed = lease_expired_caught and reclaimed
360
+ return FaultCaseResult(
361
+ case_id="heartbeat_loss_lease_reclaim",
362
+ name="心跳丢失与租约过期回收",
363
+ status="PASSED" if passed else "FAILED",
364
+ expected_outcome="Expired claim rejected AND unit recoverable by a new worker",
365
+ actual_outcome=f"lease_expired_caught={lease_expired_caught}, reclaimed={reclaimed}",
366
+ details={
367
+ "lease_expired_caught": lease_expired_caught,
368
+ "reclaimed": reclaimed,
369
+ "clock_advanced_seconds": lease_window * 2,
370
+ },
371
+ duration_seconds=0.0,
372
+ )
373
+
374
+ # --- 5. Provider 429 限流退避与阻断 ---
375
+ def test_provider_rate_limit_429(self, work_dir: Path) -> FaultCaseResult:
376
+ # 验证退避重试机制在遭遇 429 时进行有限次退避并在超限后明确失败,不无限卡死
377
+ attempts = 0
378
+ max_retries = 3
379
+
380
+ def mock_provider_call():
381
+ nonlocal attempts
382
+ attempts += 1
383
+ # 持续模拟 429 限流
384
+ raise RuntimeError("HTTP 429 Too Many Requests: Rate limit exceeded")
385
+
386
+ # 模拟具备退避上限的调用封装
387
+ call_succeeded = False
388
+ caught_terminal_error = False
389
+ for i in range(max_retries):
390
+ try:
391
+ mock_provider_call()
392
+ call_succeeded = True
393
+ break
394
+ except RuntimeError as e:
395
+ if i == max_retries - 1:
396
+ caught_terminal_error = True
397
+ time.sleep(0.02 * (2**i))
398
+
399
+ passed = caught_terminal_error and not call_succeeded and attempts == max_retries
400
+ return FaultCaseResult(
401
+ case_id="provider_rate_limit_429",
402
+ name="模型 Provider 429 限流退避与阻断",
403
+ status="PASSED" if passed else "FAILED",
404
+ expected_outcome="Bails out after bounded retries on 429, no infinite retry",
405
+ actual_outcome=f"attempts={attempts}, caught_terminal_error={caught_terminal_error}",
406
+ details={"attempts": attempts, "caught_terminal_error": caught_terminal_error},
407
+ duration_seconds=0.0,
408
+ )
409
+
410
+ # --- 6. 运行时间预算耗尽 ---
411
+ def test_budget_exhausted(self, work_dir: Path) -> FaultCaseResult:
412
+ budget = RunBudget(max_wall_seconds=0.05, max_rounds=1, require_parallel=False, serial_reason="test")
413
+ sup = Supervisor(work_dir, budget=budget, state_path=work_dir / "supervisor.json")
414
+ sup.start(coverage_units=["内部:预算耗尽测试"])
415
+
416
+ # 等待超时
417
+ time.sleep(0.1)
418
+
419
+ # 触发状态刷新
420
+ st = sup.status()
421
+ is_exhausted = bool(st.budget_exhausted)
422
+ budget_error_caught = False
423
+
424
+ try:
425
+ sup.claim_worker("worker-late", unit_ids=["内部:预算耗尽测试"])
426
+ except (BudgetExhausted, ClaimRejected):
427
+ budget_error_caught = True
428
+ except Exception:
429
+ budget_error_caught = True
430
+
431
+ passed = is_exhausted or budget_error_caught
432
+ return FaultCaseResult(
433
+ case_id="budget_exhausted",
434
+ name="生命周期时间预算耗尽审计终态",
435
+ status="PASSED" if passed else "FAILED",
436
+ expected_outcome="Supervisor marks budget_exhausted=True and rejects new claims",
437
+ actual_outcome=f"budget_exhausted={is_exhausted}, budget_error_caught={budget_error_caught}",
438
+ details={"budget_exhausted": is_exhausted},
439
+ duration_seconds=0.0,
440
+ )
441
+
442
+ # --- 7. 未裁决 Open Finding 阻断完成 ---
443
+ def test_open_findings_block(self, work_dir: Path) -> FaultCaseResult:
444
+ # 在 post_phase 中,存在未收敛/未关闭的 findings 时,不得标记为 COMPLETE
445
+ from unittest.mock import patch, MagicMock
446
+
447
+ runtime = {
448
+ "polling_policy": "auto",
449
+ "autonomous_mode": True,
450
+ "lifecycle_stop_reason": None,
451
+ }
452
+
453
+ mock_sup = MagicMock()
454
+ mock_sup.decision_snapshot.return_value = {"coverage_complete": True}
455
+ mock_status = MagicMock()
456
+ mock_status.coverage_complete = True
457
+ # 存在处于 open 状态的 Finding(非 confirmed / rejected)
458
+ mock_status.findings = [
459
+ {"id": "F-OPEN-001", "state": "open", "title": "Unresolved Defect"}
460
+ ]
461
+ mock_sup.status.return_value = mock_status
462
+
463
+ mock_set_stop = MagicMock()
464
+ with launch_common.isolated_runtime_scope(work_dir):
465
+ runtime_path = sr.RUNTIME_FILE
466
+ with patch("core.launch_phases.post_phase._load_runtime", return_value=runtime), \
467
+ patch("core.launch_phases.post_phase._supervisor", return_value=mock_sup), \
468
+ patch("core.launch_phases.post_phase._baseline_json", return_value={"mode": "standard"}), \
469
+ patch("core.launch_phases.post_phase._prepare_next_round", return_value=({}, True)), \
470
+ patch("core.launch_phases.post_phase._set_polling_stop", mock_set_stop):
471
+ outcome = _continue_after_death()
472
+
473
+ persisted_runtime = json.loads(runtime_path.read_text(encoding="utf-8"))
474
+ runtime_event_persisted = any(
475
+ item.get("event") == "autonomous-continue-open-findings"
476
+ for item in persisted_runtime.get("events", [])
477
+ )
478
+
479
+ # 必须阻断正常完成,不能判定为 stopped-complete
480
+ blocked = outcome != "stopped-complete" and runtime_event_persisted
481
+ return FaultCaseResult(
482
+ case_id="open_findings_block",
483
+ name="未裁决 Open Finding 阻断完成终态",
484
+ status="PASSED" if blocked else "FAILED",
485
+ expected_outcome=(
486
+ "not stopped-complete and the continuation event is persisted under work_dir"
487
+ ),
488
+ actual_outcome=f"outcome={outcome}",
489
+ details={
490
+ "outcome": outcome,
491
+ "runtime_path": str(runtime_path),
492
+ "runtime_event_persisted": runtime_event_persisted,
493
+ },
494
+ duration_seconds=0.0,
495
+ )
496
+
497
+ # --- 8. 宿主输出截断与损坏回执 ---
498
+ def test_host_output_truncation(self, work_dir: Path) -> FaultCaseResult:
499
+ receipt_file = work_dir / "corrupted-receipt.json"
500
+ # 写入截断的不完整 JSON 内容
501
+ receipt_file.write_text('{"outcome": "COMPLETE", "lifecycle_id": "lifecycle-000001", "artifact_hashes": { "modu', encoding="utf-8")
502
+
503
+ ok, msg = verify_acceptance_receipt(receipt_file)
504
+ # 必须 Fail-Closed
505
+ passed = not ok and ("json" in msg.lower() or "截断" in msg or "解析" in msg or "无效" in msg or "decode" in msg.lower())
506
+
507
+ return FaultCaseResult(
508
+ case_id="host_output_truncation",
509
+ name="宿主输出截断与损坏回执 Fail-Closed",
510
+ status="PASSED" if passed else "FAILED",
511
+ expected_outcome="verify_acceptance_receipt fails closed on corrupted/truncated JSON",
512
+ actual_outcome=f"valid={ok}, error_message={msg}",
513
+ details={"msg": msg},
514
+ duration_seconds=0.0,
515
+ )
516
+
517
+ # --- 9. 目标指纹漂移拒绝 ---
518
+ def test_target_drift_rebind(self, work_dir: Path) -> FaultCaseResult:
519
+ """漂移必须由**漂移门**拒绝,而不是被别的门顺手挡掉。
520
+
521
+ 旧实现以「抛任何异常」判定通过,实测它是因为「evidence passed 必须绑定
522
+ 受信 worker execution receipt」被拒——漂移门根本没被触碰(假性通过)。
523
+ 现在:①evidence 带合法 execution_receipt;②注入真实身份漂移;③断言拒绝
524
+ 原因命中漂移判据 + state 历史确有 ``target_drift_rejected`` 事件;
525
+ ④控制组(不注入漂移)同样的提交必须被**受理**,证明不是恒真。
526
+ """
527
+ from unittest.mock import patch
528
+ import core.supervisor.checkpoint_pipeline as checkpoint_pipeline
529
+
530
+ def build_and_submit(target_dir: Path, *, drift: bool) -> dict[str, object]:
531
+ target_dir.mkdir(parents=True, exist_ok=True)
532
+ sup = Supervisor(target_dir, state_path=target_dir / "supervisor.json")
533
+ unit = "内部:指纹漂移测试"
534
+ sup.start(coverage_units=[unit])
535
+ w_id = "worker-drift-test"
536
+ claim = sup.claim_worker(w_id, unit_ids=[unit], lease_seconds=60.0)
537
+ sup.start_worker(w_id)
538
+ art_file = target_dir / (claim.artifact_root or ".bugx/state/workers/w1")
539
+ art_file.mkdir(parents=True, exist_ok=True)
540
+ art_file = art_file / "art.txt"
541
+ art_file.write_text("ok", encoding="utf-8")
542
+ art_sha = hashlib.sha256(b"ok").hexdigest()
543
+ fingerprint = str(sup.status().target_fingerprint or "")
544
+ evidence = {
545
+ unit: {
546
+ "artifact_path": str(art_file.relative_to(target_dir)),
547
+ "artifact_sha256": art_sha,
548
+ "command": "test",
549
+ "exit_code": 0,
550
+ "lease_id": claim.lease_id,
551
+ "round_no": 1,
552
+ "run_id": sup.status().run_id,
553
+ "status": "passed",
554
+ "target_fingerprint": fingerprint,
555
+ "timestamp": time.time(),
556
+ "worker_id": w_id,
557
+ "execution_receipt": {
558
+ "schema_version": 1,
559
+ "execution_id": claim.execution_id,
560
+ "worker_id": w_id,
561
+ "lease_id": claim.lease_id,
562
+ "command": "test",
563
+ "exit_code": 0,
564
+ "artifact_path": str(art_file.relative_to(target_dir)),
565
+ "artifact_sha256": art_sha,
566
+ "status": "passed",
567
+ },
568
+ }
569
+ }
570
+ rejected = False
571
+ info = ""
572
+ try:
573
+ if drift:
574
+ with patch.object(
575
+ checkpoint_pipeline, "_workspace_fingerprint",
576
+ return_value="0" * 40,
577
+ ), patch.object(
578
+ checkpoint_pipeline, "_target_identity",
579
+ return_value="drifted-target-identity",
580
+ ):
581
+ sup.submit_checkpoint(
582
+ w_id, coverage={unit: "covered"}, evidence=evidence,
583
+ )
584
+ else:
585
+ sup.submit_checkpoint(
586
+ w_id, coverage={unit: "covered"}, evidence=evidence,
587
+ )
588
+ except Exception as exc: # noqa: BLE001 - 拒绝原因是判定依据
589
+ rejected = True
590
+ info = str(exc)
591
+ events = [
592
+ event for event in (getattr(sup.status(), "history", ()) or ())
593
+ if isinstance(event, dict)
594
+ ]
595
+ drift_events = sum(
596
+ 1 for event in events
597
+ if event.get("type") in {"target_drift_rejected", "lifecycle_blocked"}
598
+ and "审计目标已变化" in str(event.get("reason") or "")
599
+ )
600
+ return {
601
+ "rejected": rejected, "error": info,
602
+ "drift_events": drift_events,
603
+ "coverage": dict(getattr(sup.status(), "coverage", {}) or {}),
604
+ }
605
+
606
+ drift_run = build_and_submit(work_dir / "drift", drift=True)
607
+ control_run = build_and_submit(work_dir / "control", drift=False)
608
+ drift_error = str(drift_run["error"])
609
+ drift_gate_hit = (
610
+ drift_run["rejected"]
611
+ and "审计目标已变化" in drift_error
612
+ and int(drift_run["drift_events"]) >= 1
613
+ )
614
+ receipt_gate_masquerade = "execution receipt" in drift_error
615
+ control_ok = (
616
+ not control_run["rejected"]
617
+ and control_run["coverage"].get("内部:指纹漂移测试") == "covered"
618
+ )
619
+ passed = drift_gate_hit and control_ok and not receipt_gate_masquerade
620
+ return FaultCaseResult(
621
+ case_id="target_drift_rebind",
622
+ name="目标指纹漂移拒绝与防御",
623
+ status="PASSED" if passed else "FAILED",
624
+ expected_outcome=(
625
+ "Supervisor rejects the checkpoint with a drift-specific error "
626
+ "(target_drift_rejected event) while the identical non-drifted "
627
+ "submission is accepted"
628
+ ),
629
+ actual_outcome=(
630
+ f"drift_rejected={drift_run['rejected']} "
631
+ f"drift_events={drift_run['drift_events']} "
632
+ f"control_accepted={control_ok} "
633
+ f"receipt_gate_masquerade={receipt_gate_masquerade} "
634
+ f"error={drift_error}"
635
+ ),
636
+ details={
637
+ "drift": drift_run, "control": control_run,
638
+ "receipt_gate_masquerade": receipt_gate_masquerade,
639
+ },
640
+ duration_seconds=0.0,
641
+ )
642
+
643
+ def _generate_receipt(self, all_ok: bool) -> Path:
644
+ out_path = self.output_receipt
645
+ if not out_path:
646
+ if self.sandbox_root and self.sandbox_root.is_dir():
647
+ out_path = self.sandbox_root / ".bugx" / "fault-matrix-receipt.json"
648
+ else:
649
+ out_path = Path("fault-matrix-receipt.json")
650
+
651
+ out_path.parent.mkdir(parents=True, exist_ok=True)
652
+ receipt_data = {
653
+ "schema_version": "1.0",
654
+ "receipt_type": "fault_injection_matrix",
655
+ "timestamp": time.time(),
656
+ "iso_time": sr._iso_time(time.time()),
657
+ "status": "PASSED" if all_ok else "FAILED",
658
+ "total_cases": len(self.results),
659
+ "passed_cases": sum(1 for r in self.results if r.status == "PASSED"),
660
+ "failed_cases": sum(1 for r in self.results if r.status != "PASSED"),
661
+ "cases": [asdict(r) for r in self.results],
662
+ }
663
+
664
+ # 计算自校验防伪哈希
665
+ raw_json = json.dumps(receipt_data, indent=2, sort_keys=True, ensure_ascii=False)
666
+ receipt_sha256 = hashlib.sha256(raw_json.encode("utf-8")).hexdigest()
667
+ receipt_data["receipt_sha256"] = receipt_sha256
668
+
669
+ out_path.write_text(json.dumps(receipt_data, indent=2, ensure_ascii=False), encoding="utf-8")
670
+ print(f"\n📄 故障矩阵标准收据已生成: {out_path.resolve()}")
671
+ print(f"🔒 收据防伪 SHA-256: {receipt_sha256}")
672
+ return out_path
673
+
674
+
675
+ def main():
676
+ parser = argparse.ArgumentParser(description="Gate 5 故障注入矩阵自动化验证器")
677
+ parser.add_argument("--sandbox", type=Path, default=None, help="指定靶向沙箱目录")
678
+ parser.add_argument("--output", type=Path, default=None, help="指定收据输出路径")
679
+ parser.add_argument("--json", action="store_true", help="以 JSON 格式输出结果")
680
+ args = parser.parse_args()
681
+
682
+ runner = FaultMatrixRunner(sandbox_root=args.sandbox, output_receipt=args.output)
683
+ success = runner.run_all()
684
+
685
+ if args.json:
686
+ print(json.dumps({"success": success, "results": [asdict(r) for r in runner.results]}, indent=2, ensure_ascii=False))
687
+
688
+ sys.exit(0 if success else 1)
689
+
690
+
691
+ if __name__ == "__main__":
692
+ main()