bugx-cli 0.1.1 → 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.
Files changed (82) hide show
  1. package/README.md +13 -9
  2. package/core/README.md +1 -1
  3. package/core/assets/README.md +3 -2
  4. package/core/assets/bugx-social-preview.svg +71 -0
  5. package/core/assets/bugx-wechat-group.png +0 -0
  6. package/core/audit_packs/README.md +2 -0
  7. package/core/audit_packs/pitfalls/auth_crypto.json +64 -0
  8. package/core/audit_packs/pitfalls/file_ssrf_cmd.json +64 -0
  9. package/core/audit_packs/pitfalls/go_backend.json +66 -0
  10. package/core/audit_packs/pitfalls/java_spring.json +64 -0
  11. package/core/audit_packs/pitfalls/js_ts_web.json +67 -0
  12. package/core/audit_packs/pitfalls/python_web.json +82 -0
  13. package/core/bugx.md +1 -1
  14. package/core/bugx_paths.py +2 -2
  15. package/core/cloud_sync/cloud_client.py +56 -5
  16. package/core/cloud_sync/consent.py +33 -3
  17. package/core/cloud_sync/flywheel_client.py +186 -24
  18. package/core/contracts/README.md +1 -1
  19. package/core/contracts/bugx-runtime-contract.md +1 -1
  20. package/core/contracts/bugx-worker.md +1 -1
  21. package/core/engine-integrity.json +122 -66
  22. package/core/infra/README.md +1 -1
  23. package/core/infra/build_info.py +2 -2
  24. package/core/launch_phases/README.md +6 -3
  25. package/core/launch_phases/finding_confirm_phase.py +168 -7
  26. package/core/launch_phases/post_phase.py +5 -5
  27. package/core/launch_phases/pre_recon_scout.py +13 -0
  28. package/core/launch_phases/report_sharing.py +3 -7
  29. package/core/launch_phases/round_orchestrator.py +114 -26
  30. package/core/launch_phases/semantic_recon.py +545 -0
  31. package/core/launch_phases/startup_version_gate.py +6 -2
  32. package/core/launch_phases/verify_loop.py +767 -0
  33. package/core/launch_phases/worker_prior.py +115 -0
  34. package/core/ledger/README.md +2 -1
  35. package/core/ledger/finding_verification.py +511 -2
  36. package/core/ledger/fp_ledger.py +255 -0
  37. package/core/metadata.txt +2 -2
  38. package/core/planning/README.md +2 -1
  39. package/core/planning/prompt_harness.py +50 -10
  40. package/core/planning/prompt_policy_engine.py +386 -0
  41. package/core/prompts/README.md +4 -2
  42. package/core/prompts/policies/prompt_policies.json +101 -0
  43. package/core/prompts/stages/stage_verify.defensive.md +42 -0
  44. package/core/prompts/stages/stage_verify.md +44 -0
  45. package/core/report_engine/report_share.py +0 -8
  46. package/core/retrieval/README.md +2 -1
  47. package/core/retrieval/pitfall_packs.py +277 -0
  48. package/core/runtime/README.md +1 -1
  49. package/core/runtime/global_telemetry.py +20 -0
  50. package/core/runtime/scenario_eval.py +1 -1
  51. package/core/supervisor/README.md +1 -1
  52. package/docs/07_distribution/01_README_NPM.md +13 -9
  53. package/ecosystem/integrations/dsh/mcp/package.json +1 -1
  54. package/ecosystem/integrations/dsh/ui/package.json +1 -1
  55. package/ecosystem/integrations/opencode/bugx-mcp-manifest.json +1 -1
  56. package/ecosystem/integrations/pi/extensions/bugx/manifest.json +1 -1
  57. package/ecosystem/integrations/qoder/connector-meta.json +1 -1
  58. package/ecosystem/integrations/workbuddy/connector-meta.json +1 -1
  59. package/ecosystem/integrations/workbuddy/skills/bugx/SKILL.md +1 -1
  60. package/ecosystem/plugins/bugx/.claude-plugin/plugin.json +1 -1
  61. package/ecosystem/plugins/bugx/.codex-plugin/plugin.json +1 -1
  62. package/ecosystem/plugins/bugx/.zcode-plugin/plugin.json +1 -1
  63. package/ecosystem/plugins/bugx/skills/bugx/SKILL.md +2 -2
  64. package/interfaces/bin/bugx.js +7 -7
  65. package/interfaces/cli/bugx_cli/__init__.py +2 -2
  66. package/interfaces/cli/bugx_cli/cli.py +163 -67
  67. package/interfaces/cli/bugx_cli/commands/agent.py +122 -61
  68. package/interfaces/cli/bugx_cli/commands/audit.py +8 -7
  69. package/interfaces/cli/bugx_cli/commands/cloud.py +27 -19
  70. package/interfaces/cli/bugx_cli/commands/knowledge.py +3 -4
  71. package/interfaces/cli/bugx_cli/commands/plugin.py +3 -3
  72. package/interfaces/cli/bugx_cli/commands/plugin_claude.py +2 -2
  73. package/interfaces/cli/bugx_cli/commands/project.py +6 -13
  74. package/interfaces/cli/bugx_cli/commands/system.py +513 -158
  75. package/interfaces/cli/bugx_cli/common.py +6 -8
  76. package/interfaces/cli/bugx_cli/infra/engine_installer.py +21 -10
  77. package/interfaces/cli/bugx_cli/infra/host_sync.py +1 -1
  78. package/package.json +29 -15
  79. package/pyproject.toml +40 -1
  80. package/scripts/sync-version.mjs +1 -1
  81. package/core/assets/bugx-hero-cn.png +0 -0
  82. package/core/assets/bugx-hero-en.png +0 -0
@@ -742,6 +742,121 @@ def unit_execution_seconds(supervisor: Any) -> dict[str, float] | None:
742
742
 
743
743
 
744
744
 
745
+ def build_coldstart_pitfall_guidance(
746
+ root: Path,
747
+ profile: dict[str, Any] | None = None,
748
+ *,
749
+ target_files: list[str] | tuple[str, ...] = (),
750
+ char_budget: int = KNOWLEDGE_GUIDANCE_CHAR_BUDGET,
751
+ limit: int = 5,
752
+ host: str | None = None,
753
+ provider: str | None = None,
754
+ model: str | None = None,
755
+ policy: str | None = None,
756
+ last_error: str | None = None,
757
+ ) -> dict[str, Any]:
758
+ """Assemble dual-track cold-start pitfalls + active source-hash-bound FP guards (P1 / T-005)."""
759
+ from core.retrieval import pitfall_packs
760
+ from core.ledger import fp_ledger
761
+ from core.planning import prompt_policy_engine
762
+
763
+ resolved_root = Path(root).resolve()
764
+ resolved_policy = prompt_policy_engine.resolve_policy(
765
+ host=host,
766
+ provider=provider,
767
+ model=model,
768
+ last_error=last_error,
769
+ explicit_policy=policy,
770
+ root=resolved_root,
771
+ )
772
+ code_chunks: list[str] = []
773
+ active_guards: list[dict[str, Any]] = []
774
+ first_file = ""
775
+
776
+ for raw_rel in target_files:
777
+ if not isinstance(raw_rel, str) or not raw_rel.strip():
778
+ continue
779
+ rel = raw_rel.replace("\\", "/").strip()
780
+ if not first_file:
781
+ first_file = rel
782
+ candidate = Path(rel)
783
+ if not candidate.is_absolute() and ".." not in candidate.parts:
784
+ try:
785
+ abs_path = (resolved_root / candidate).resolve()
786
+ abs_path.relative_to(resolved_root)
787
+ if abs_path.is_file() and not abs_path.is_symlink():
788
+ code_chunks.append(abs_path.read_text(encoding="utf-8", errors="replace")[:16384])
789
+ except (OSError, ValueError):
790
+ pass
791
+ active_guards.extend(fp_ledger.match_false_positive_guards(resolved_root, file_path=rel))
792
+
793
+ # Deduplicate active guards by fp_id
794
+ seen_fp: set[str] = set()
795
+ dedup_guards: list[dict[str, Any]] = []
796
+ for g in active_guards:
797
+ gid = str(g.get("fp_id") or "")
798
+ if gid and gid not in seen_fp:
799
+ seen_fp.add(gid)
800
+ dedup_guards.append(g)
801
+
802
+ pitfalls = pitfall_packs.match_pitfalls(
803
+ profile,
804
+ code_text="\n".join(code_chunks),
805
+ file_path=first_file,
806
+ limit=limit,
807
+ )
808
+
809
+ guard_budget = min(600, max(0, char_budget // 3)) if dedup_guards else 0
810
+ pitfall_budget = max(0, char_budget - guard_budget)
811
+ pitfall_text = pitfall_packs.render_pitfall_guidance(pitfalls, char_budget=pitfall_budget)
812
+ guard_text = fp_ledger.render_fp_guard_guidance(dedup_guards, char_budget=guard_budget)
813
+ parts = [p for p in (pitfall_text, guard_text) if p]
814
+ raw_guidance = "\n\n".join(parts)
815
+ if raw_guidance:
816
+ guidance_text = prompt_policy_engine.apply_policy(
817
+ raw_guidance,
818
+ resolved_policy,
819
+ include_preamble=False,
820
+ include_safe_repro=True,
821
+ )[:char_budget]
822
+ else:
823
+ guidance_text = ""
824
+
825
+ return {
826
+ "pitfalls": pitfalls,
827
+ "active_fp_guards": dedup_guards,
828
+ "policy_profile": resolved_policy.name,
829
+ "guidance_text": guidance_text,
830
+ }
831
+
832
+
833
+ def build_semantic_recon_guidance(
834
+ root: Path,
835
+ *,
836
+ target_files: list[str] | tuple[str, ...] = (),
837
+ char_budget: int = 900,
838
+ ) -> dict[str, Any]:
839
+ """Load anchored semantic recon overlay and render target-filtered guidance (P2 / T-006)."""
840
+ from core.launch_phases import semantic_recon
841
+
842
+ overlay = semantic_recon.load_semantic_overlay(Path(root).resolve(), allow_stale=False)
843
+ text = semantic_recon.render_semantic_overlay_guidance(
844
+ overlay, target_files=target_files, char_budget=char_budget,
845
+ )
846
+ wanted = {f.replace("\\", "/").strip() for f in target_files if isinstance(f, str) and f.strip()}
847
+ def _filt(key: str) -> list[dict[str, Any]]:
848
+ items = overlay.get(key) or []
849
+ return [i for i in items if not wanted or str(i.get("file") or "") in wanted]
850
+
851
+ return {
852
+ "implicit_routes": _filt("implicit_routes"),
853
+ "auth_boundaries": _filt("auth_boundaries"),
854
+ "business_invariants": _filt("business_invariants"),
855
+ "stale_files": overlay.get("stale_files") or [],
856
+ "guidance_text": text,
857
+ }
858
+
859
+
745
860
  _worker_host_plugin = worker_host_plugin
746
861
  _worker_host_profile = worker_host_profile
747
862
  _order_jobs_longest_first = order_jobs_longest_first
@@ -1,6 +1,6 @@
1
1
  # BugX Ledger (攻防复盘账本与错题经验库)
2
2
 
3
- > **版本契约**: `0.1.1` | **所属分层**: `Layer 3: 并发协调、智能体编排与账本`
3
+ > **版本契约**: `0.1.2` | **所属分层**: `Layer 3: 并发协调、智能体编排与账本`
4
4
  > **工程规范**: 参见 [`docs/02_architecture/05_ARCH_NOMENCLATURE_GUIDE.md`](../../docs/02_architecture/05_ARCH_NOMENCLATURE_GUIDE.md)
5
5
  > **守卫机制**: `scripts/verify_directory_indices.py` (100% 物理条目索引覆盖)
6
6
 
@@ -26,6 +26,7 @@ core/ledger/
26
26
  │ ├── patterns.py # 提炼形成的攻击模式、代码脆弱性规则与避坑指南知识库
27
27
  │ ├── tool_experience.py # 工具调用经验库,记录各语言与框架下的最佳参数
28
28
  │ ├── lesson_ledger.py # 错题集主管理门面,支持模式匹配与经验检索
29
+ │ ├── fp_ledger.py # 负样本误报账本与源码哈希防误杀护栏 (P1)
29
30
  │ └── lesson_replay.py # 历史错题与回归用例离线重放引擎
30
31
  │
31
32
  ├── 3. 数据规范、契约与统一调用门面 (Schema, Facade & Verification)
@@ -9,10 +9,12 @@ control once, then records the raw outputs and hashes generated by the engine.
9
9
 
10
10
  from __future__ import annotations
11
11
 
12
+ import ast
12
13
  import hashlib
13
14
  import json
14
15
  import math
15
16
  import os
17
+ import re
16
18
  import tempfile
17
19
  import time
18
20
  import uuid
@@ -399,7 +401,514 @@ def verify_finding_record(*args: Any, **kwargs: Any) -> dict[str, object]:
399
401
  return verify_finding(*args, **kwargs)
400
402
 
401
403
 
404
+ DIAGNOSTIC_MAX_TEXT_BYTES = 4096
405
+
406
+ FAILURE_CODES = frozenset({
407
+ "shell_token_rejected",
408
+ "syntax_or_import_error",
409
+ "positive_not_triggered",
410
+ "positive_flaky",
411
+ "negative_false_trigger",
412
+ "negative_trivial_rejected",
413
+ "env_or_dependency_blocked",
414
+ "timeout_exceeded",
415
+ "source_tampered_rejected",
416
+ "verifier_stalled",
417
+ })
418
+
419
+ RETRYABLE_FAILURE_CODES = frozenset({
420
+ "shell_token_rejected",
421
+ "syntax_or_import_error",
422
+ "positive_not_triggered",
423
+ "negative_false_trigger",
424
+ "negative_trivial_rejected",
425
+ })
426
+
427
+ _REDACT_PATTERNS: tuple[tuple[re.Pattern[str], str], ...] = (
428
+ (re.compile(r"(?i)(bearer\s+)[A-Za-z0-9._\-]{12,}"), r"\1<REDACTED>"),
429
+ (re.compile(r"\b(?:sk|pk|ghp|gho|ghu|ghs|glpat|xoxb|xoxp)-[A-Za-z0-9_\-]{10,}\b"), "<REDACTED_TOKEN>"),
430
+ (re.compile(r"(?i)(\b(?:api[_-]?key|secret|token|password|passwd|access[_-]?key)\s*[:=]\s*['\"]?)([^\s'\",;]{6,})"), r"\1<REDACTED>"),
431
+ )
432
+
433
+ _TRIVIAL_BUILTINS = frozenset({
434
+ "print", "len", "str", "int", "float", "bool", "list", "dict", "set", "tuple",
435
+ "range", "repr", "type", "isinstance", "issubclass", "enumerate", "zip",
436
+ "min", "max", "sum", "abs", "round", "sorted", "reversed", "any", "all",
437
+ "chr", "ord", "id", "hash", "exit", "quit",
438
+ })
439
+
440
+
441
+ def _redact_and_truncate(text: object, *, limit: int = DIAGNOSTIC_MAX_TEXT_BYTES) -> str:
442
+ raw = text.decode("utf-8", errors="replace") if isinstance(text, bytes) else str(text or "")
443
+ for pattern, repl in _REDACT_PATTERNS:
444
+ raw = pattern.sub(repl, raw)
445
+ encoded = raw.encode("utf-8", errors="replace")
446
+ if len(encoded) <= limit:
447
+ return raw
448
+ truncated = encoded[:limit].decode("utf-8", errors="ignore")
449
+ return f"{truncated}\n...[truncated {len(encoded) - limit} bytes]"
450
+
451
+
452
+ def _looks_like_syntax_or_import(stderr: str, stdout: str) -> bool:
453
+ combined = f"{stderr}\n{stdout}"
454
+ markers = (
455
+ "SyntaxError",
456
+ "IndentationError",
457
+ "TabError",
458
+ "ImportError",
459
+ "ModuleNotFoundError",
460
+ "NameError",
461
+ "AttributeError: module",
462
+ "BUGX_VERIFY_POSITIVE unexpected-error=SyntaxError",
463
+ "BUGX_VERIFY_POSITIVE unexpected-error=ImportError",
464
+ "BUGX_VERIFY_POSITIVE unexpected-error=ModuleNotFoundError",
465
+ "BUGX_VERIFY_POSITIVE unexpected-error=NameError",
466
+ )
467
+ return any(marker in combined for marker in markers)
468
+
469
+
470
+ def _looks_like_env_blocked(stderr: str, stdout: str, error_text: str = "") -> bool:
471
+ combined = f"{error_text}\n{stderr}\n{stdout}".lower()
472
+ markers = (
473
+ "connection refused",
474
+ "no such file or directory: 'docker'",
475
+ "permission denied",
476
+ "operation not permitted",
477
+ "cannot connect to",
478
+ "address already in use",
479
+ "executable file not found",
480
+ "command not found",
481
+ )
482
+ return any(marker in combined for marker in markers)
483
+
484
+
485
+ @dataclass(frozen=True)
486
+ class VerificationDiagnostic:
487
+ """Engine-owned structured diagnostic for a failed verification attempt."""
488
+
489
+ finding_key: str
490
+ attempt: int
491
+ failure_code: str
492
+ stage: str
493
+ retryable: bool
494
+ summary: str
495
+ exit_code: int | None = None
496
+ stdout_excerpt: str = ""
497
+ stderr_excerpt: str = ""
498
+ receipt_status: str = ""
499
+ verification_id: str | None = None
500
+ created_at: float = 0.0
501
+
502
+ def to_dict(self) -> dict[str, object]:
503
+ return {
504
+ "finding_key": self.finding_key,
505
+ "attempt": self.attempt,
506
+ "failure_code": self.failure_code,
507
+ "stage": self.stage,
508
+ "retryable": self.retryable,
509
+ "summary": self.summary,
510
+ "exit_code": self.exit_code,
511
+ "stdout_excerpt": self.stdout_excerpt,
512
+ "stderr_excerpt": self.stderr_excerpt,
513
+ "receipt_status": self.receipt_status,
514
+ "verification_id": self.verification_id,
515
+ "created_at": self.created_at or time.time(),
516
+ }
517
+
518
+
519
+ def diagnose_verification_error(
520
+ exc_or_msg: object,
521
+ *,
522
+ attempt: int = 1,
523
+ finding_key: str = "",
524
+ failure_code: str | None = None,
525
+ stage: str = "precheck",
526
+ ) -> VerificationDiagnostic:
527
+ """Build a structured diagnostic from a precheck/supervisor/runtime error."""
528
+ text = _redact_and_truncate(str(exc_or_msg))
529
+ code = failure_code
530
+ if code not in FAILURE_CODES:
531
+ lowered = text.lower()
532
+ if "shell" in lowered or "禁字符" in text or "运算符" in text:
533
+ code = "shell_token_rejected"
534
+ elif "timeout" in lowered or "超时" in text:
535
+ code = "timeout_exceeded"
536
+ elif _looks_like_env_blocked(text, "", text):
537
+ code = "env_or_dependency_blocked"
538
+ elif _looks_like_syntax_or_import(text, ""):
539
+ code = "syntax_or_import_error"
540
+ else:
541
+ code = "positive_not_triggered"
542
+ return VerificationDiagnostic(
543
+ finding_key=finding_key,
544
+ attempt=attempt,
545
+ failure_code=code,
546
+ stage=stage,
547
+ retryable=code in RETRYABLE_FAILURE_CODES,
548
+ summary=text[:400],
549
+ stderr_excerpt=text,
550
+ receipt_status="ERROR",
551
+ created_at=time.time(),
552
+ )
553
+
554
+
555
+ def diagnose_verification_receipt(
556
+ receipt: Mapping[str, object],
557
+ *,
558
+ attempt: int = 1,
559
+ finding_key: str = "",
560
+ ) -> VerificationDiagnostic:
561
+ """Classify an engine verification receipt into a deterministic failure_code."""
562
+ fkey = finding_key or str(receipt.get("finding_key") or "")
563
+ status = str(receipt.get("status") or "")
564
+ vid = receipt.get("verification_id")
565
+ vid_str = str(vid) if vid is not None else None
566
+ now = time.time()
567
+
568
+ if status == "BLOCKED":
569
+ err = _redact_and_truncate(receipt.get("error") or "verification blocked")
570
+ code = "timeout_exceeded" if "timeout" in err.lower() else "env_or_dependency_blocked"
571
+ return VerificationDiagnostic(
572
+ finding_key=fkey,
573
+ attempt=attempt,
574
+ failure_code=code,
575
+ stage="blocked",
576
+ retryable=False,
577
+ summary=err[:400],
578
+ stderr_excerpt=err,
579
+ receipt_status=status,
580
+ verification_id=vid_str,
581
+ created_at=now,
582
+ )
583
+
584
+ pos_runs = receipt.get("positive_runs")
585
+ pos_list = list(pos_runs) if isinstance(pos_runs, Sequence) else []
586
+ neg = receipt.get("negative_control")
587
+ neg_map = neg if isinstance(neg, Mapping) else {}
588
+
589
+ # 1. Timeout check across all runs
590
+ for idx, run in enumerate(pos_list, 1):
591
+ if isinstance(run, Mapping) and bool(run.get("timed_out")):
592
+ return VerificationDiagnostic(
593
+ finding_key=fkey,
594
+ attempt=attempt,
595
+ failure_code="timeout_exceeded",
596
+ stage=f"positive_run_{idx}",
597
+ retryable=False,
598
+ summary=f"positive run {idx} timed out",
599
+ exit_code=run.get("exit_code") if isinstance(run.get("exit_code"), int) else None,
600
+ stdout_excerpt=_redact_and_truncate(run.get("stdout")),
601
+ stderr_excerpt=_redact_and_truncate(run.get("stderr")),
602
+ receipt_status=status,
603
+ verification_id=vid_str,
604
+ created_at=now,
605
+ )
606
+ if bool(neg_map.get("timed_out")):
607
+ return VerificationDiagnostic(
608
+ finding_key=fkey,
609
+ attempt=attempt,
610
+ failure_code="timeout_exceeded",
611
+ stage="negative_control",
612
+ retryable=False,
613
+ summary="negative control timed out",
614
+ exit_code=neg_map.get("exit_code") if isinstance(neg_map.get("exit_code"), int) else None,
615
+ stdout_excerpt=_redact_and_truncate(neg_map.get("stdout")),
616
+ stderr_excerpt=_redact_and_truncate(neg_map.get("stderr")),
617
+ receipt_status=status,
618
+ verification_id=vid_str,
619
+ created_at=now,
620
+ )
621
+
622
+ # 2. Positive runs analysis
623
+ pos_matched = [bool(r.get("oracle_matched")) for r in pos_list if isinstance(r, Mapping)]
624
+ if len(pos_matched) >= 2 and any(pos_matched) and not all(pos_matched):
625
+ failed_idx = next(i for i, ok in enumerate(pos_matched) if not ok)
626
+ run = pos_list[failed_idx]
627
+ return VerificationDiagnostic(
628
+ finding_key=fkey,
629
+ attempt=attempt,
630
+ failure_code="positive_flaky",
631
+ stage=f"positive_run_{failed_idx + 1}",
632
+ retryable=False,
633
+ summary="positive runs disagreed across independent executions (non-deterministic)",
634
+ exit_code=run.get("exit_code") if isinstance(run.get("exit_code"), int) else None,
635
+ stdout_excerpt=_redact_and_truncate(run.get("stdout")),
636
+ stderr_excerpt=_redact_and_truncate(run.get("stderr")),
637
+ receipt_status=status,
638
+ verification_id=vid_str,
639
+ created_at=now,
640
+ )
641
+
642
+ if not pos_matched or not all(pos_matched):
643
+ run = pos_list[0] if pos_list and isinstance(pos_list[0], Mapping) else {}
644
+ stdout = _redact_and_truncate(run.get("stdout"))
645
+ stderr = _redact_and_truncate(run.get("stderr"))
646
+ if _looks_like_syntax_or_import(stderr, stdout):
647
+ code = "syntax_or_import_error"
648
+ summary = "positive PoC failed with syntax/import/name error"
649
+ elif _looks_like_env_blocked(stderr, stdout):
650
+ code = "env_or_dependency_blocked"
651
+ summary = "positive PoC blocked by missing environment or permission"
652
+ else:
653
+ code = "positive_not_triggered"
654
+ summary = f"positive PoC did not match oracle (exit_code={run.get('exit_code')})"
655
+ return VerificationDiagnostic(
656
+ finding_key=fkey,
657
+ attempt=attempt,
658
+ failure_code=code,
659
+ stage="positive_run_1",
660
+ retryable=code in RETRYABLE_FAILURE_CODES,
661
+ summary=summary,
662
+ exit_code=run.get("exit_code") if isinstance(run.get("exit_code"), int) else None,
663
+ stdout_excerpt=stdout,
664
+ stderr_excerpt=stderr,
665
+ receipt_status=status,
666
+ verification_id=vid_str,
667
+ created_at=now,
668
+ )
669
+
670
+ # 3. Negative control analysis
671
+ if not bool(neg_map.get("oracle_matched")):
672
+ stdout = _redact_and_truncate(neg_map.get("stdout"))
673
+ stderr = _redact_and_truncate(neg_map.get("stderr"))
674
+ if _looks_like_syntax_or_import(stderr, stdout):
675
+ code = "syntax_or_import_error"
676
+ summary = "negative control failed with syntax/import/name error"
677
+ elif _looks_like_env_blocked(stderr, stdout):
678
+ code = "env_or_dependency_blocked"
679
+ summary = "negative control blocked by missing environment or permission"
680
+ else:
681
+ code = "negative_false_trigger"
682
+ summary = f"negative control unexpectedly failed oracle (exit_code={neg_map.get('exit_code')})"
683
+ return VerificationDiagnostic(
684
+ finding_key=fkey,
685
+ attempt=attempt,
686
+ failure_code=code,
687
+ stage="negative_control",
688
+ retryable=code in RETRYABLE_FAILURE_CODES,
689
+ summary=summary,
690
+ exit_code=neg_map.get("exit_code") if isinstance(neg_map.get("exit_code"), int) else None,
691
+ stdout_excerpt=stdout,
692
+ stderr_excerpt=stderr,
693
+ receipt_status=status,
694
+ verification_id=vid_str,
695
+ created_at=now,
696
+ )
697
+
698
+ return VerificationDiagnostic(
699
+ finding_key=fkey,
700
+ attempt=attempt,
701
+ failure_code="positive_not_triggered",
702
+ stage="unknown",
703
+ retryable=True,
704
+ summary=f"verification receipt did not reach CONFIRMED (status={status})",
705
+ receipt_status=status,
706
+ verification_id=vid_str,
707
+ created_at=now,
708
+ )
709
+
710
+
711
+ def _has_meaningful_target_activity(tree: ast.AST, target_hints: Sequence[str]) -> bool:
712
+ """Reject trivial no-op negative controls (e.g. `pass`, `sys.exit(0)`, `print('ok')`)."""
713
+ has_import = False
714
+ non_trivial_call = False
715
+ imported_names: set[str] = set()
716
+ referenced_names: set[str] = set()
717
+
718
+ for node in ast.walk(tree):
719
+ if isinstance(node, ast.Import):
720
+ for alias in node.names:
721
+ root_name = alias.name.split(".")[0]
722
+ if root_name != "sys":
723
+ has_import = True
724
+ imported_names.add(alias.name)
725
+ imported_names.add(root_name)
726
+ if alias.asname:
727
+ imported_names.add(alias.asname)
728
+ elif isinstance(node, ast.ImportFrom):
729
+ mod = node.module or ""
730
+ if mod and mod.split(".")[0] != "sys":
731
+ has_import = True
732
+ if mod:
733
+ imported_names.add(mod)
734
+ imported_names.add(mod.split(".")[0])
735
+ for alias in node.names:
736
+ imported_names.add(alias.name)
737
+ if alias.asname:
738
+ imported_names.add(alias.asname)
739
+ elif isinstance(node, ast.Name):
740
+ referenced_names.add(node.id)
741
+ elif isinstance(node, ast.Attribute):
742
+ referenced_names.add(node.attr)
743
+ elif isinstance(node, ast.Call):
744
+ func = node.func
745
+ if isinstance(func, ast.Name):
746
+ if func.id not in _TRIVIAL_BUILTINS:
747
+ non_trivial_call = True
748
+ elif isinstance(func, ast.Attribute):
749
+ is_sys_exit = (
750
+ isinstance(func.value, ast.Name)
751
+ and func.value.id == "sys"
752
+ and func.attr == "exit"
753
+ )
754
+ if not is_sys_exit:
755
+ non_trivial_call = True
756
+ else:
757
+ non_trivial_call = True
758
+
759
+ if not (non_trivial_call or has_import):
760
+ return False
761
+ if not non_trivial_call:
762
+ return False
763
+ if target_hints:
764
+ all_tokens = imported_names | referenced_names
765
+ normalized_hints = {h.strip() for h in target_hints if isinstance(h, str) and h.strip()}
766
+ if normalized_hints and not any(
767
+ hint in token or token in hint
768
+ for hint in normalized_hints
769
+ for token in all_tokens
770
+ if len(token) >= 2
771
+ ):
772
+ return False
773
+ return True
774
+
775
+
776
+ def validate_python_poc_pair(
777
+ positive_code: str,
778
+ negative_code: str,
779
+ *,
780
+ finding_key: str = "",
781
+ attempt: int = 1,
782
+ target_hints: Sequence[str] = (),
783
+ ) -> VerificationDiagnostic | None:
784
+ """Anti-gaming static AST validation for positive/negative Python PoC bodies."""
785
+ pos_text = (positive_code or "").strip()
786
+ neg_text = (negative_code or "").strip()
787
+ if not pos_text or not neg_text:
788
+ return VerificationDiagnostic(
789
+ finding_key=finding_key,
790
+ attempt=attempt,
791
+ failure_code="syntax_or_import_error",
792
+ stage="ast_precheck",
793
+ retryable=True,
794
+ summary="positive and negative code bodies must both be non-empty",
795
+ created_at=time.time(),
796
+ )
797
+ if pos_text == neg_text:
798
+ return VerificationDiagnostic(
799
+ finding_key=finding_key,
800
+ attempt=attempt,
801
+ failure_code="negative_trivial_rejected",
802
+ stage="ast_precheck",
803
+ retryable=True,
804
+ summary="negative control must differ from positive payload",
805
+ created_at=time.time(),
806
+ )
807
+ try:
808
+ pos_tree = ast.parse(pos_text, filename="verification-positive")
809
+ except SyntaxError as exc:
810
+ return VerificationDiagnostic(
811
+ finding_key=finding_key,
812
+ attempt=attempt,
813
+ failure_code="syntax_or_import_error",
814
+ stage="ast_precheck",
815
+ retryable=True,
816
+ summary=f"positive SyntaxError: {exc}",
817
+ stderr_excerpt=str(exc),
818
+ created_at=time.time(),
819
+ )
820
+ try:
821
+ neg_tree = ast.parse(neg_text, filename="verification-negative")
822
+ except SyntaxError as exc:
823
+ return VerificationDiagnostic(
824
+ finding_key=finding_key,
825
+ attempt=attempt,
826
+ failure_code="syntax_or_import_error",
827
+ stage="ast_precheck",
828
+ retryable=True,
829
+ summary=f"negative SyntaxError: {exc}",
830
+ stderr_excerpt=str(exc),
831
+ created_at=time.time(),
832
+ )
833
+ if not _has_meaningful_target_activity(neg_tree, target_hints):
834
+ return VerificationDiagnostic(
835
+ finding_key=finding_key,
836
+ attempt=attempt,
837
+ failure_code="negative_trivial_rejected",
838
+ stage="ast_precheck",
839
+ retryable=True,
840
+ summary="negative control rejected as trivial no-op (must invoke target module/entry)",
841
+ created_at=time.time(),
842
+ )
843
+ if not _has_meaningful_target_activity(pos_tree, ()):
844
+ return VerificationDiagnostic(
845
+ finding_key=finding_key,
846
+ attempt=attempt,
847
+ failure_code="positive_not_triggered",
848
+ stage="ast_precheck",
849
+ retryable=True,
850
+ summary="positive PoC contains no meaningful call or module exercise",
851
+ created_at=time.time(),
852
+ )
853
+ return None
854
+
855
+
856
+ def snapshot_target_hashes(root: Path, rel_paths: Sequence[str]) -> dict[str, str]:
857
+ """Compute SHA-256 hashes of target source files before PoC execution."""
858
+ resolved_root = Path(root).resolve()
859
+ hashes: dict[str, str] = {}
860
+ for raw in rel_paths:
861
+ if not isinstance(raw, str) or not raw.strip():
862
+ continue
863
+ candidate = Path(raw.replace("\\", "/"))
864
+ if candidate.is_absolute() or ".." in candidate.parts:
865
+ continue
866
+ try:
867
+ target = (resolved_root / candidate).resolve()
868
+ target.relative_to(resolved_root)
869
+ except (OSError, ValueError):
870
+ continue
871
+ if target.is_file() and not target.is_symlink():
872
+ try:
873
+ hashes[str(target.relative_to(resolved_root))] = _sha256(target.read_bytes())
874
+ except OSError:
875
+ continue
876
+ return hashes
877
+
878
+
879
+ def verify_target_hashes_unchanged(root: Path, before: Mapping[str, str]) -> list[str]:
880
+ """Return list of target relative paths modified or deleted during PoC execution."""
881
+ resolved_root = Path(root).resolve()
882
+ tampered: list[str] = []
883
+ for rel, expected_hash in before.items():
884
+ target = resolved_root / rel
885
+ if not target.is_file() or target.is_symlink():
886
+ tampered.append(rel)
887
+ continue
888
+ try:
889
+ actual_hash = _sha256(target.read_bytes())
890
+ except OSError:
891
+ tampered.append(rel)
892
+ continue
893
+ if actual_hash != expected_hash:
894
+ tampered.append(rel)
895
+ return tampered
896
+
897
+
402
898
  __all__ = [
403
- "PROTOCOL_VERSION", "VerificationError", "VerificationBlocked", "VerificationRecipe",
404
- "verify_finding", "verify_finding_record",
899
+ "PROTOCOL_VERSION",
900
+ "DIAGNOSTIC_MAX_TEXT_BYTES",
901
+ "FAILURE_CODES",
902
+ "RETRYABLE_FAILURE_CODES",
903
+ "VerificationError",
904
+ "VerificationBlocked",
905
+ "VerificationRecipe",
906
+ "VerificationDiagnostic",
907
+ "verify_finding",
908
+ "verify_finding_record",
909
+ "diagnose_verification_receipt",
910
+ "diagnose_verification_error",
911
+ "validate_python_poc_pair",
912
+ "snapshot_target_hashes",
913
+ "verify_target_hashes_unchanged",
405
914
  ]