forgeproof-cli 0.2.0__py3-none-any.whl

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 (89) hide show
  1. forge_gate/__init__.py +44 -0
  2. forge_gate/_deprecated_cli.py +16 -0
  3. forgeproof/__init__.py +3 -0
  4. forgeproof/catalog.py +110 -0
  5. forgeproof/cli.py +560 -0
  6. forgeproof/config.py +339 -0
  7. forgeproof/data/gate_catalog.json +66 -0
  8. forgeproof/data/host_sets.json +7 -0
  9. forgeproof/debug_caller.py +271 -0
  10. forgeproof/debug_core.py +368 -0
  11. forgeproof/fixture_engine.py +81 -0
  12. forgeproof/fixtures/__init__.py +19 -0
  13. forgeproof/fixtures/decision_tree_id3.py +90 -0
  14. forgeproof/fixtures/gradient_descent_momentum.py +73 -0
  15. forgeproof/fixtures/kmeans_clustering.py +98 -0
  16. forgeproof/fixtures/knn_classifier.py +79 -0
  17. forgeproof/fixtures/linear_regression_gd.py +77 -0
  18. forgeproof/fixtures/logistic_regression.py +85 -0
  19. forgeproof/fixtures/naive_bayes_text.py +114 -0
  20. forgeproof/fixtures/perceptron.py +84 -0
  21. forgeproof/fixtures/polynomial_regression.py +67 -0
  22. forgeproof/fixtures/ridge_regression_normal_eq.py +75 -0
  23. forgeproof/ledger.py +633 -0
  24. forgeproof/lens_tools/__init__.py +11 -0
  25. forgeproof/lens_tools/guard_lens.py +1250 -0
  26. forgeproof/lens_tools/invariant_contracts/linear_regression_gd.json +74 -0
  27. forgeproof/lens_tools/invariant_contracts/polynomial_regression.json +86 -0
  28. forgeproof/lens_tools/invariant_contracts/ridge_regression_normal_eq.json +86 -0
  29. forgeproof/lens_tools/invariant_gate.py +199 -0
  30. forgeproof/lens_tools/metamorphic/__init__.py +9 -0
  31. forgeproof/lens_tools/metamorphic/relations.py +962 -0
  32. forgeproof/lens_tools/metamorphic/runner.py +112 -0
  33. forgeproof/lens_tools/twin_consensus.py +395 -0
  34. forgeproof/lenses.py +923 -0
  35. forgeproof/paths.py +56 -0
  36. forgeproof/reference/ORIGIN.md +29 -0
  37. forgeproof/reference/decision_tree_id3.py +197 -0
  38. forgeproof/reference/gradient_descent_momentum.py +141 -0
  39. forgeproof/reference/kmeans_clustering.py +139 -0
  40. forgeproof/reference/knn_classifier.py +118 -0
  41. forgeproof/reference/linear_regression_gd.py +106 -0
  42. forgeproof/reference/logistic_regression.py +141 -0
  43. forgeproof/reference/naive_bayes_text.py +152 -0
  44. forgeproof/reference/perceptron.py +123 -0
  45. forgeproof/reference/polynomial_regression.py +125 -0
  46. forgeproof/reference/ridge_regression_normal_eq.py +165 -0
  47. forgeproof/runner.py +147 -0
  48. forgeproof/scout/__init__.py +7 -0
  49. forgeproof/scout/behaviour.py +365 -0
  50. forgeproof/scout/box.py +581 -0
  51. forgeproof/scout/cards.py +180 -0
  52. forgeproof/scout/contract.py +37 -0
  53. forgeproof/scout/corpus.py +104 -0
  54. forgeproof/scout/embed.py +217 -0
  55. forgeproof/scout/engines/__init__.py +1 -0
  56. forgeproof/scout/engines/chaos.py +454 -0
  57. forgeproof/scout/engines/chaos_port.py +1331 -0
  58. forgeproof/scout/engines/chaos_runner.py +178 -0
  59. forgeproof/scout/engines/executor_port.py +239 -0
  60. forgeproof/scout/envfit.py +54 -0
  61. forgeproof/scout/experience.py +161 -0
  62. forgeproof/scout/fetchproxy.py +368 -0
  63. forgeproof/scout/ghcache.py +395 -0
  64. forgeproof/scout/ghpool.py +253 -0
  65. forgeproof/scout/ghsearch.py +248 -0
  66. forgeproof/scout/ids.py +82 -0
  67. forgeproof/scout/intent_lens.py +170 -0
  68. forgeproof/scout/learn.py +583 -0
  69. forgeproof/scout/meaning_lens.py +231 -0
  70. forgeproof/scout/outcomes.py +42 -0
  71. forgeproof/scout/plant.py +327 -0
  72. forgeproof/scout/ratify.py +214 -0
  73. forgeproof/scout/report.py +448 -0
  74. forgeproof/scout/rule2.py +177 -0
  75. forgeproof/scout/shape.py +107 -0
  76. forgeproof/scout/shape_lens.py +71 -0
  77. forgeproof/scout/signature.py +52 -0
  78. forgeproof/scout/slots.py +39 -0
  79. forgeproof/scout/upstream_facts.py +536 -0
  80. forgeproof/unsupported.py +83 -0
  81. forgeproof/verifier.py +208 -0
  82. forgeproof/view_coverage.py +166 -0
  83. forgeproof_cli-0.2.0.dist-info/METADATA +285 -0
  84. forgeproof_cli-0.2.0.dist-info/RECORD +89 -0
  85. forgeproof_cli-0.2.0.dist-info/WHEEL +5 -0
  86. forgeproof_cli-0.2.0.dist-info/entry_points.txt +3 -0
  87. forgeproof_cli-0.2.0.dist-info/licenses/LICENSE +201 -0
  88. forgeproof_cli-0.2.0.dist-info/licenses/NOTICE +23 -0
  89. forgeproof_cli-0.2.0.dist-info/top_level.txt +2 -0
@@ -0,0 +1,112 @@
1
+ """Runner for metamorphic relation checks."""
2
+ from __future__ import annotations
3
+
4
+ import importlib.util
5
+ import sys
6
+ from pathlib import Path
7
+ from typing import Any, List, Tuple
8
+
9
+ from .relations import RelationResult, evaluate_relations, is_gating, registry
10
+
11
+
12
+ def load_module(path: str, module_name: str = "user_impl") -> Any:
13
+ p = Path(path)
14
+ if not p.is_absolute():
15
+ p = Path.cwd() / p
16
+ p = p.resolve()
17
+ if not p.exists():
18
+ raise FileNotFoundError(f"File not found: {p}")
19
+ spec = importlib.util.spec_from_file_location(module_name, str(p))
20
+ if spec is None or spec.loader is None:
21
+ raise ImportError(f"Cannot load module from {p}")
22
+ mod = importlib.util.module_from_spec(spec)
23
+ spec.loader.exec_module(mod)
24
+ return mod
25
+
26
+
27
+ def _category_for_pattern(pattern: str) -> str:
28
+ if pattern in {
29
+ "linear_regression_gd",
30
+ "polynomial_regression",
31
+ "ridge_regression_normal_eq",
32
+ }:
33
+ return "regression"
34
+ if pattern in {
35
+ "logistic_regression",
36
+ "knn_classifier",
37
+ "decision_tree_id3",
38
+ "naive_bayes_text",
39
+ "perceptron",
40
+ }:
41
+ return "classification"
42
+ if pattern == "kmeans_clustering":
43
+ return "clustering"
44
+ if pattern == "gradient_descent_momentum":
45
+ return "optimization"
46
+ return "unknown"
47
+
48
+
49
+ def run_metamorphic(user_file: Path, pattern: str) -> Tuple[str, List[RelationResult], str]:
50
+ """Run metamorphic relations for a pattern against a user file.
51
+
52
+ Returns (verdict, results, summary). Verdict is RELATION-PASS, RELATION-FAIL,
53
+ UNSUPPORTED, or ERROR.
54
+ """
55
+ category = _category_for_pattern(pattern)
56
+ if category == "unknown":
57
+ return "UNSUPPORTED", [], f"No metamorphic relations for pattern {pattern}"
58
+
59
+ relations = registry().get(category, [])
60
+ if not relations:
61
+ return "UNSUPPORTED", [], f"No relations registered for category {category}"
62
+
63
+ try:
64
+ mod = load_module(str(user_file))
65
+ results = evaluate_relations(category, mod, pattern=pattern)
66
+ except Exception as exc:
67
+ return "ERROR", [], f"{type(exc).__name__}: {exc}"
68
+
69
+ failed = [r for r in results if not r.passed and is_gating(r.name)]
70
+ advisory = [r for r in results if not r.passed and not is_gating(r.name)]
71
+ n_gating = sum(1 for r in results if is_gating(r.name))
72
+
73
+ if failed:
74
+ summary = f"{len(failed)}/{n_gating} gating relations failed; first: {failed[0].name}"
75
+ if advisory:
76
+ summary += f" (+{len(advisory)} advisory objection(s))"
77
+ return "RELATION-FAIL", results, summary
78
+
79
+ if advisory:
80
+ names = ", ".join(r.name for r in advisory)
81
+ return "RELATION-PASS", results, (
82
+ f"All {n_gating} gating relations passed; "
83
+ f"{len(advisory)} advisory relation(s) objected but cannot gate: {names}"
84
+ )
85
+ return "RELATION-PASS", results, f"All {n_gating} gating relations passed"
86
+
87
+
88
+ def main() -> int:
89
+ if len(sys.argv) < 3:
90
+ print("usage: python3 -m forgeproof.lens_tools.metamorphic.runner <user_file.py> <pattern>", file=sys.stderr)
91
+ return 2
92
+ user_file = Path(sys.argv[1])
93
+ pattern = sys.argv[2]
94
+ verdict, results, summary = run_metamorphic(user_file, pattern)
95
+ print(f"{verdict}: {pattern}")
96
+ print(f" file: {user_file}")
97
+ print(f" summary: {summary}")
98
+ if results:
99
+ print(" relations:")
100
+ for r in results:
101
+ if r.passed:
102
+ mark = "PASS"
103
+ elif is_gating(r.name):
104
+ mark = "FAIL"
105
+ else:
106
+ mark = "ADVIS"
107
+ print(f" {r.name:40} {mark:5} {r.reason}")
108
+ return 0 if verdict == "RELATION-PASS" else 1
109
+
110
+
111
+ if __name__ == "__main__":
112
+ sys.exit(main())
@@ -0,0 +1,395 @@
1
+ #!/usr/bin/env python3
2
+ """Twin-consensus verifier — Wave 1 / 1B, CHUNK 2.
3
+
4
+ Fix from chunk 1:
5
+ - User verdict is PROPERTY-PRIMARY: reuse the existing fixture's PASS/FAIL verdict.
6
+ - Twin consensus means >=2 language REFERENCE twins (py + cpp for linear_regression_gd)
7
+ must agree WITH EACH OTHER. If they disagree → UNSTABLE (drift signal).
8
+
9
+ Usage:
10
+ PYTHONPATH=src python3 -m forgeproof.lens_tools.twin_consensus \
11
+ verify tests/corpus/linreg_sgd.py --pattern linear_regression_gd
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import os
17
+ import re
18
+ import shutil
19
+ import subprocess
20
+ import sys
21
+ import tempfile
22
+ from dataclasses import dataclass, field
23
+ from pathlib import Path
24
+ from typing import Any, Dict, List, Optional, Tuple
25
+
26
+ # The forgeproof package this file ships in (KD-2): its fixtures/ sit one level up.
27
+ PKG = Path(__file__).resolve().parents[1]
28
+
29
+ from forgeproof.catalog import CatalogError, load_aura_catalog, resolve_pattern
30
+ from forgeproof.config import NotConfigured, library_dir
31
+ from forgeproof.runner import run_file
32
+ from forgeproof.verifier import verdict
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class TwinConsensus:
37
+ status: str # PASS | FAIL | UNSTABLE | UNSUPPORTED
38
+ pattern: str
39
+ user_file: str
40
+ reason: str
41
+ user_verdict: str
42
+ twin_count: int
43
+ consensus_status: Optional[str] = None
44
+ details: List[str] = field(default_factory=list)
45
+ metrics: Dict[str, Any] = field(default_factory=dict)
46
+
47
+
48
+ def _extract_gate_json(stdout: str) -> Optional[Dict]:
49
+ for line in reversed(stdout.splitlines()):
50
+ line = line.strip()
51
+ if line.startswith("FORGE_GATE_RESULT "):
52
+ try:
53
+ return json.loads(line[len("FORGE_GATE_RESULT "):])
54
+ except json.JSONDecodeError:
55
+ continue
56
+ if line.startswith("{") and line.endswith("}"):
57
+ try:
58
+ return json.loads(line)
59
+ except json.JSONDecodeError:
60
+ continue
61
+ return None
62
+
63
+
64
+ def _run_fixture(fixture: Path, user_file: Path, timeout: float) -> Dict[str, Any]:
65
+ """Run a Python fixture against a user file; return its structured result."""
66
+ result = run_file(
67
+ fixture,
68
+ extra_args=[str(user_file)],
69
+ timeout=timeout,
70
+ no_network=True,
71
+ memory_mb=512,
72
+ )
73
+ payload = _extract_gate_json(result.stdout) or {}
74
+ return {
75
+ "exit": result.exit_code,
76
+ "status": payload.get("status", "FAIL"),
77
+ "reason": payload.get("reason", "fixture reported failure"),
78
+ "metrics": payload.get("metrics", {}),
79
+ "stdout": result.stdout,
80
+ "stderr": result.stderr,
81
+ }
82
+
83
+
84
+ def _compile_cpp(src: Path) -> Optional[Path]:
85
+ """Compile a C++ twin to a temporary binary. Returns binary path or None."""
86
+ gxx = shutil.which("g++")
87
+ if not gxx:
88
+ return None
89
+ out = Path(tempfile.gettempdir()) / f"_fg_twin_{src.stem}"
90
+ try:
91
+ proc = subprocess.run(
92
+ [gxx, "-O2", "-std=c++17", str(src), "-o", str(out)],
93
+ capture_output=True,
94
+ text=True,
95
+ timeout=60,
96
+ )
97
+ if proc.returncode != 0:
98
+ return None
99
+ return out
100
+ except Exception:
101
+ return None
102
+
103
+
104
+ def _run_cpp_twin(src: Path, timeout: float) -> Dict[str, Any]:
105
+ """Compile and run a C++ twin; return structured result."""
106
+ binary = _compile_cpp(src)
107
+ if not binary:
108
+ return {"status": "UNSTABLE", "reason": "C++ twin failed to compile"}
109
+ try:
110
+ proc = subprocess.run(
111
+ [str(binary)],
112
+ capture_output=True,
113
+ text=True,
114
+ timeout=timeout,
115
+ )
116
+ ok = proc.returncode == 0
117
+ # Extract R² and weights from stdout if possible.
118
+ nums = _extract_numbers(proc.stdout)
119
+ return {
120
+ "status": "PASS" if ok else "FAIL",
121
+ "reason": "C++ twin ran" if ok else "C++ twin assertion failed",
122
+ "metrics": nums,
123
+ "stdout": proc.stdout,
124
+ "stderr": proc.stderr,
125
+ }
126
+ except subprocess.TimeoutExpired as exc:
127
+ return {"status": "UNSTABLE", "reason": "C++ twin timed out"}
128
+
129
+
130
+ def _extract_numbers(text: str) -> Dict[str, float]:
131
+ out: Dict[str, float] = {}
132
+ for line in text.splitlines():
133
+ # Look for "R²=0.123" or "R2 = 0.123" etc.
134
+ m = re.search(r"R[²2]\s*=?\s*([-+]?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?)", line, re.I)
135
+ if m:
136
+ out["r2"] = float(m.group(1))
137
+ # Generic named-number extraction for twin stdout, e.g. "intra=0.557".
138
+ for wm in re.finditer(r"\b(\w+)\s*[:=]\s*([-+]?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?)", line):
139
+ name = wm.group(1).lower()
140
+ if name in {"exit", "code", "line", "seed", "version", "copyright", "cpp", "pass"}:
141
+ continue
142
+ # Keep sensible metric names; ignore raw integers that are likely counts/indices.
143
+ val = float(wm.group(2))
144
+ out[name] = val
145
+ return out
146
+
147
+
148
+ def _resolve_twins(pattern: str) -> List[Tuple[str, Path]]:
149
+ """Return [(language, path), ...] for all language twins of this pattern."""
150
+ lib = library_dir() # the twins live only in the library; unset -> NotConfigured
151
+ catalog = load_aura_catalog(lib)
152
+ langs_str, _ = catalog.get(pattern, ("", ""))
153
+ if not langs_str:
154
+ return []
155
+
156
+ twins: List[Tuple[str, Path]] = []
157
+ lang_ext = {
158
+ "python": ".py",
159
+ "cpp": ".cpp",
160
+ "go": ".go",
161
+ "rust": ".rs",
162
+ "r": ".R",
163
+ }
164
+ declared = [x.strip() for x in langs_str.split("·")]
165
+
166
+ for lang in declared:
167
+ ext = lang_ext.get(lang)
168
+ if not ext:
169
+ continue
170
+ for p in lib.rglob(f"{pattern}{ext}"):
171
+ twins.append((lang, p))
172
+
173
+ return twins
174
+
175
+
176
+ def _metrics_consensus(
177
+ results: List[Dict[str, Any]],
178
+ tolerance: float = 1e-3,
179
+ aliases: Optional[Dict[str, str]] = None,
180
+ require_value_match: bool = True,
181
+ ) -> Tuple[bool, List[str], List[str]]:
182
+ """Compare a list of twin results to each other.
183
+
184
+ Returns (agree, disagreements, coverage_notes).
185
+
186
+ A COVERAGE NOTE is not a disagreement. Two twins that both PASS but share no
187
+ comparable metric have not contradicted each other -- there was simply nothing
188
+ to compare. Reporting that as drift false-FAILs correct code. It is surfaced as
189
+ an explicit disclosure instead, so a status-level check is never mistaken for a
190
+ metric-level one.
191
+
192
+ Only metrics present in BOTH twins are compared; extra keys are ignored.
193
+ This prevents a C++ twin that emits only R² from disagreeing with a Python
194
+ twin that emits weights + bias + R².
195
+
196
+ `aliases` maps twin metric names to canonical names, e.g. {"intra": "intra_cluster_distance"}.
197
+ If `require_value_match` is False, only statuses and presence of metrics are checked
198
+ (used when language twins use different seed-locked fixtures and absolute values
199
+ are not expected to match, e.g. k-means with different RNG streams).
200
+ """
201
+ if len(results) < 2:
202
+ return True, [], []
203
+ base = results[0]
204
+ if base["status"] != "PASS":
205
+ return True, [], []
206
+
207
+ def normalize(m: Dict[str, float]) -> Dict[str, float]:
208
+ out: Dict[str, float] = {}
209
+ for k, v in m.items():
210
+ canon = (aliases or {}).get(k, k)
211
+ out[canon] = v
212
+ return out
213
+
214
+ base_metrics = normalize(base.get("metrics", {}))
215
+ disagreements: List[str] = []
216
+ coverage_notes: List[str] = []
217
+ for r in results[1:]:
218
+ if r["status"] != base["status"]:
219
+ disagreements.append(f"status {base.get('twin','?')}={base['status']} vs {r.get('twin','?')}={r['status']}")
220
+ continue
221
+ if not require_value_match:
222
+ # Ensure both produced at least one numeric metric; exact values are not compared.
223
+ other_metrics = normalize(r.get("metrics", {}))
224
+ if not base_metrics and not other_metrics:
225
+ disagreements.append(f"no metrics from either twin")
226
+ continue
227
+ other_metrics = normalize(r.get("metrics", {}))
228
+ common = set(base_metrics.keys()) & set(other_metrics.keys())
229
+ if not common:
230
+ # COVERAGE GAP, not drift: both twins agreed on status, they just expose
231
+ # no metric under a shared name. Disclose it; do not object.
232
+ coverage_notes.append(
233
+ f"no shared metric between {base.get('twin','?')} and {r.get('twin','?')} "
234
+ "-- status-level consensus only, metric-level drift NOT checked"
235
+ )
236
+ continue
237
+ for key in common:
238
+ av, bv = base_metrics[key], other_metrics[key]
239
+ if isinstance(av, (int, float)) and isinstance(bv, (int, float)):
240
+ denom = max(abs(av), abs(bv), 1.0)
241
+ if abs(av - bv) / denom > tolerance:
242
+ disagreements.append(f"metric '{key}' differs: {base.get('twin','?')}={av} vs {r.get('twin','?')}={bv}")
243
+ break
244
+ elif av != bv:
245
+ disagreements.append(f"metric '{key}' differs: {base.get('twin','?')}={av!r} vs {r.get('twin','?')}={bv!r}")
246
+ break
247
+ return not disagreements, disagreements, coverage_notes
248
+
249
+
250
+ def _metrics_match(a: Dict, b: Dict, tolerance: float) -> bool:
251
+ for key in a:
252
+ if key not in b:
253
+ return False
254
+ av, bv = a[key], b[key]
255
+ if isinstance(av, (int, float)) and isinstance(bv, (int, float)):
256
+ denom = max(abs(av), abs(bv), 1.0)
257
+ if abs(av - bv) / denom > tolerance:
258
+ return False
259
+ elif av != bv:
260
+ return False
261
+ return True
262
+
263
+
264
+ def consensus_verify(user_file: Path, pattern: str, timeout: float = 60.0) -> TwinConsensus:
265
+ if not user_file.exists():
266
+ return TwinConsensus("FAIL", pattern, str(user_file), "user file not found", "FAIL", 0)
267
+
268
+ try:
269
+ meta = resolve_pattern(pattern)
270
+ except CatalogError as exc:
271
+ return TwinConsensus("UNSUPPORTED", pattern, str(user_file), str(exc), "UNSUPPORTED", 0)
272
+
273
+ fixture = PKG / "fixtures" / f"{meta['fixture']}.py"
274
+ if not fixture.exists():
275
+ return TwinConsensus("UNSUPPORTED", pattern, str(user_file), f"fixture missing: {fixture}", "UNSUPPORTED", 0)
276
+
277
+ # 1. Property-primary verdict on the USER implementation.
278
+ user_run = _run_fixture(fixture, user_file, timeout)
279
+ user_status = user_run["status"]
280
+
281
+ if user_status not in ("PASS", "FAIL", "UNSTABLE"):
282
+ user_status = "FAIL"
283
+
284
+ # 2. Resolve and run all language reference twins.
285
+ try:
286
+ twins = _resolve_twins(pattern)
287
+ except NotConfigured as exc:
288
+ # BLIND, not ERROR: the lens could not look, and says which key would let it.
289
+ return TwinConsensus("UNSUPPORTED", pattern, str(user_file),
290
+ f"twin lens needs the pattern library: {exc}", user_status, 0)
291
+ twin_results: List[Dict[str, Any]] = []
292
+ for lang, path in twins:
293
+ if lang == "python":
294
+ # Python twin: run it through the same fixture as the user.
295
+ r = _run_fixture(fixture, path, timeout)
296
+ r["twin"] = path.name
297
+ r["lang"] = "python"
298
+ twin_results.append(r)
299
+ elif lang == "cpp":
300
+ r = _run_cpp_twin(path, timeout)
301
+ r["twin"] = path.name
302
+ r["lang"] = "cpp"
303
+ twin_results.append(r)
304
+
305
+ # 3. Consensus among reference twins (not user-vs-twin).
306
+ # Per-pattern metric aliases so C++ twins can match Python fixture names.
307
+ # Patterns whose language twins use different synthetic fixtures (different RNG
308
+ # streams) get `require_value_match=False`; we then only require both twins to
309
+ # PASS and emit at least one numeric metric.
310
+ status_only_patterns = {"kmeans_clustering", "logistic_regression", "decision_tree_id3", "knn_classifier", "naive_bayes_text", "perceptron", "polynomial_regression"}
311
+ aliases: Dict[str, str] = {
312
+ "intra": "intra_cluster_distance",
313
+ "r2": "r2",
314
+ "accuracy": "accuracy",
315
+ "mse_2": "mse",
316
+ }
317
+ require_value_match = pattern not in status_only_patterns
318
+ consensus_ok, disagreements, coverage_notes = _metrics_consensus(
319
+ twin_results, aliases=aliases, require_value_match=require_value_match
320
+ )
321
+
322
+ if len(twin_results) < 2:
323
+ consensus_label = "insufficient_twins"
324
+ elif not consensus_ok:
325
+ consensus_label = "disagree"
326
+ elif coverage_notes:
327
+ consensus_label = "agree_status_only"
328
+ else:
329
+ consensus_label = "agree"
330
+
331
+ # Final verdict:
332
+ # FAIL if user fails.
333
+ # UNSUPPORTED if no twins.
334
+ # UNSTABLE if twins disagree (drift signal).
335
+ # PASS only if user passes AND twins agree.
336
+ if user_status == "FAIL":
337
+ final = "FAIL"
338
+ reason = f"user implementation fails property check: {user_run['reason']}"
339
+ elif not twin_results:
340
+ final = "UNSUPPORTED"
341
+ reason = "no language twins found for this pattern"
342
+ elif consensus_label == "disagree":
343
+ final = "UNSTABLE"
344
+ reason = "reference twins disagree: " + "; ".join(disagreements)
345
+ elif consensus_label == "agree_status_only":
346
+ final = "PASS"
347
+ reason = (
348
+ f"user passes and {len(twin_results)} reference twin(s) agree at STATUS level; "
349
+ + "; ".join(coverage_notes)
350
+ )
351
+ else:
352
+ final = "PASS"
353
+ reason = f"user passes and {len(twin_results)} reference twin(s) agree on shared metrics"
354
+
355
+ return TwinConsensus(
356
+ status=final,
357
+ pattern=pattern,
358
+ user_file=str(user_file),
359
+ reason=reason,
360
+ user_verdict=user_status,
361
+ twin_count=len(twin_results),
362
+ consensus_status=consensus_label,
363
+ details=[f"{r.get('lang','?')}/{r.get('twin','?')} -> {r['status']}" for r in twin_results],
364
+ metrics=user_run.get("metrics", {}),
365
+ )
366
+
367
+
368
+ def main(argv: List[str]) -> int:
369
+ if len(argv) < 2 or argv[0] != "verify":
370
+ print("usage: twin_consensus.py verify <user_file> --pattern <pattern>")
371
+ return 2
372
+ user_file = Path(argv[1]).expanduser().resolve()
373
+ pattern = None
374
+ for i, a in enumerate(argv):
375
+ if a == "--pattern" and i + 1 < len(argv):
376
+ pattern = argv[i + 1]
377
+ if not pattern:
378
+ print("--pattern required")
379
+ return 2
380
+
381
+ result = consensus_verify(user_file, pattern)
382
+ print(f"{result.status}: {result.pattern}")
383
+ print(f" file: {result.user_file}")
384
+ print(f" reason: {result.reason}")
385
+ print(f" user: {result.user_verdict}")
386
+ print(f" twins: {result.twin_count} (consensus={result.consensus_status})")
387
+ for d in result.details[:12]:
388
+ print(f" - {d}")
389
+ if result.metrics:
390
+ print(f" metrics: {result.metrics}")
391
+ return 0 if result.status == "PASS" else 1
392
+
393
+
394
+ if __name__ == "__main__":
395
+ sys.exit(main(sys.argv[1:]))