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
forgeproof/lenses.py ADDED
@@ -0,0 +1,923 @@
1
+ """KEYSTONE: run every lens and reduce them to ONE verdict.
2
+
3
+ Every customer-facing skin (CI action, MCP server, attestation) must import this
4
+ module rather than re-implement the algebra, so a verdict means the same thing
5
+ everywhere.
6
+
7
+ THE VERDICT ALGEBRA
8
+ FAIL if property-primary fails, OR any enforced lens OBJECTS
9
+ PASS only if property-primary passes and no enforced lens objects
10
+ UNSTABLE if a lens errored and nothing outright failed
11
+ UNSUPPORTED lenses never count for or against
12
+
13
+ An objection is a lens actively asserting the code is wrong:
14
+ metamorphic RELATION-FAIL (gating relations only -- see ADVISORY_RELATIONS)
15
+ invariant FAIL
16
+ twin-consensus FAIL or UNSTABLE (cross-language divergence)
17
+
18
+ Every verdict names which lens objected and why. No LLM anywhere in this path.
19
+ """
20
+ from __future__ import annotations
21
+
22
+ import sys
23
+ import time
24
+ from dataclasses import dataclass, field
25
+ from pathlib import Path
26
+ from typing import Any, Dict, List, Optional
27
+
28
+ from forgeproof.debug_core import DebugEvidence, capture_source
29
+ from forgeproof.unsupported import _u
30
+
31
+ from forgeproof.config import scratch_dir as _scratch_dir # noqa: E402
32
+ from forgeproof.lens_tools import GUARD_LENS
33
+
34
+ # The folder that holds the forgeproof package: src/ in a checkout, site-packages in an
35
+ # install. Child scripts put it on sys.path; it is right in both shapes.
36
+ _PKG_PARENT = Path(__file__).resolve().parents[1]
37
+ # The lens tools (metamorphic, invariant, twin, guard) ship inside the package, in
38
+ # forgeproof/lens_tools/ (KNOWN-DEBT KD-2, done 2026-11-25): an install alone runs every lens,
39
+ # with no source checkout and no FORGE_GATE_HOME. They always come from the package this file
40
+ # is in, never from another checkout, so the lenses and their tools cannot be two versions.
41
+
42
+ BASE_LENS = "property-primary"
43
+ SUPPLEMENTARY_LENSES = ("metamorphic", "invariant", "twin-consensus")
44
+ # NOT "advisory": determinism is in ENFORCED_LENSES and CAN turn PASS -> FAIL. It is
45
+ # enforced with a per-pattern quarantine (DETERMINISM_ADVISORY_PATTERNS) rather than a
46
+ # global disarm. Was labelled ADVISORY_LENSES until 2026-09-05 -- a stale name that had
47
+ # already misled a reader; same shape as guard_lens.py:4 pre-campaign.
48
+ PER_PATTERN_GATED_LENSES = ("determinism",)
49
+ ENFORCED_EXTRA_LENSES = ("guard",)
50
+ ALL_LENSES = (BASE_LENS,) + SUPPLEMENTARY_LENSES + PER_PATTERN_GATED_LENSES + ENFORCED_EXTRA_LENSES
51
+ # Default is EVERY lens. The gate should hand a user its strongest verdict unless they
52
+ # deliberately ask for less. Measured 2026-07-24: all-lens costs ~0.8s more per file
53
+ # (0.14s -> 0.93s) and scores 100/100 on the corpus with zero false positives.
54
+ DEFAULT_LENSES = ALL_LENSES
55
+ # Guard and determinism lenses are ENFORCED: they can turn PASS -> FAIL.
56
+ # Relation soundness law: a lens may only gate where the canonical oracle survives it.
57
+ # Determinism has a per-pattern quarantine below for kmeans_clustering (honestly
58
+ # non-deterministic oracle). The guard lens survived the canonical-oracle bar at
59
+ # commit 876b4863cd3644ea191c72c6df7fee99: 0 of 10 canonical oracles object.
60
+ #
61
+ # A lens is enforced (can turn PASS -> FAIL) only if it survives the relation soundness
62
+ # gate: the canonical oracle must itself satisfy it.
63
+ ENFORCED_LENSES: set = set(SUPPLEMENTARY_LENSES) | {"determinism", "guard"}
64
+
65
+ # PER-PATTERN QUARANTINE for the determinism lens.
66
+ #
67
+ # The RELATION SOUNDNESS LAW says a check may only GATE where the canonical oracle
68
+ # itself survives it. That is a per-pattern fact, not a global one -- so quarantine the
69
+ # specific offender instead of disarming the whole lens (the same shape as
70
+ # ADVISORY_RELATIONS in lens_tools/metamorphic/relations.py).
71
+ #
72
+ # MEASURED 2026-08-01, reproduced across two clean runs:
73
+ # kmeans_clustering canonical oracle -> determinism FAIL
74
+ # centroid [0][0][0]: 3.831617640818665 vs 5.065488147854177
75
+ # Not floating-point noise -- a different cluster centre. k-means reaches a LOCAL
76
+ # optimum fixed by `random.sample(range(n_samples), k)` initialisation, so varying the
77
+ # global RNG lands it in a different (legitimately valid) basin. The oracle is honestly
78
+ # non-deterministic; the lens is right and must not gate it.
79
+ # 4Q called this correctly in commit 390156a. An earlier note in this file claiming the
80
+ # opposite was WRONG: it read a verdict line of "PASS" produced while the lens was
81
+ # advisory -- an advisory lens cannot change a verdict, so that PASS said nothing about
82
+ # what the lens found. No objection recorded is not the same as no problem found.
83
+ #
84
+ # The other 9 oracles pass the lens and it GATES for them.
85
+ DETERMINISM_ADVISORY_PATTERNS = frozenset({"kmeans_clustering"})
86
+
87
+ # VIEW_COVERAGE — which inputs each lens adapter consumes.
88
+ #
89
+ # Enforced by view_coverage.check_all() in the self-test (tests/test_view_coverage.py).
90
+ # The walker verifies BOTH directions: no undeclared reads (an input the adapter
91
+ # reads but does not declare) AND no declared-but-unread inputs (an input the
92
+ # adapter declares but does not evidence in its body). A mismatch fails the build.
93
+ #
94
+ # Conceptual inputs (canonical_oracle, twin) are consumed inside the tool, not
95
+ # the adapter. The walker detects them via _TOOL_INPUTS in view_coverage.py — a
96
+ # call-name → input mapping, not a tool walk. Tool-internal drift is scoped out
97
+ # for v1 (6E 3c).
98
+ VIEW_COVERAGE = {
99
+ "_run_metamorphic": frozenset({"user_file", "pattern"}),
100
+ "_run_invariant": frozenset({"user_file", "pattern"}),
101
+ "_run_twin": frozenset({"user_file", "pattern", "canonical_oracle", "twin", "timeout"}),
102
+ "_run_determinism": frozenset({"user_file", "pattern", "canonical_oracle", "timeout"}),
103
+ "_run_guard": frozenset({"user_file", "timeout"}),
104
+ }
105
+
106
+
107
+ def determinism_gates_for(pattern: str) -> bool:
108
+ """True if the determinism lens may turn a PASS into a FAIL for this pattern."""
109
+ return "determinism" in ENFORCED_LENSES and pattern not in DETERMINISM_ADVISORY_PATTERNS
110
+
111
+
112
+ @dataclass
113
+ class LensResult:
114
+ name: str
115
+ status: str
116
+ reason: str
117
+ objected: bool = False
118
+ detail: List[str] = field(default_factory=list)
119
+ # DEBUG WIRE-UP (step 5, 2026-09-07). Off-path: populated only on
120
+ # FAIL/UNSUPPORTED by the lens adapter, None on PASS/ERROR. The verdict
121
+ # algebra never reads this field (grep evaluate() — it looks at status,
122
+ # reason, objected only), so acceptance criterion 1 ("verdict unchanged
123
+ # with/without debug") holds by construction. Excluded from as_dict() by
124
+ # default so serialization stays byte-identical; pass include_debug=True
125
+ # when a caller explicitly wants the artifact serialized. Per 6E round-2
126
+ # design consultation: "debug is off-path, never in the verdict."
127
+ debug: Optional["DebugEvidence"] = None
128
+
129
+ def as_dict(self, *, include_debug: bool = False) -> Dict[str, Any]:
130
+ d = {"lens": self.name, "status": self.status, "reason": self.reason,
131
+ "objected": self.objected}
132
+ if self.detail:
133
+ d["detail"] = self.detail
134
+ if include_debug and self.debug is not None:
135
+ d["debug"] = self.debug.to_dict()
136
+ return d
137
+
138
+
139
+ @dataclass
140
+ class GateVerdict:
141
+ status: str
142
+ pattern: str
143
+ user_file: str
144
+ reason: str
145
+ lenses: List[LensResult]
146
+ metrics: Dict[str, Any] = field(default_factory=dict)
147
+
148
+ @property
149
+ def objectors(self) -> List[LensResult]:
150
+ return [l for l in self.lenses if l.objected]
151
+
152
+ def as_dict(self) -> Dict[str, Any]:
153
+ return {
154
+ "status": self.status,
155
+ "pattern": self.pattern,
156
+ "file": self.user_file,
157
+ "reason": self.reason,
158
+ "objected_by": [l.name for l in self.objectors],
159
+ "metrics": self.metrics,
160
+ "lenses": [l.as_dict() for l in self.lenses],
161
+ }
162
+
163
+
164
+ def _run_metamorphic(user_file: Path, pattern: str) -> LensResult:
165
+ # DEBUG WIRE-UP (step 5): capture source UNCONDITIONALLY at the top,
166
+ # before any subprocess. Per 6E: the ordering constraint is load-bearing,
167
+ # and capturing always (discarding on PASS) is cheaper than a conditional
168
+ # that might capture too late. capture_source raising is not fatal to
169
+ # verdict — degrade to empty source, verdict path continues.
170
+ try:
171
+ src_text, src_origin = capture_source(user_file)
172
+ except Exception:
173
+ src_text, src_origin = "", str(user_file)
174
+
175
+ try:
176
+ from forgeproof.lens_tools.metamorphic.runner import run_metamorphic
177
+ verdict, results, summary = run_metamorphic(user_file, pattern)
178
+ except Exception as exc:
179
+ # ERROR intentionally leaves debug=None per Q4 design (populate
180
+ # only on FAIL/UNSUPPORTED). ERROR is "harness broke", not a
181
+ # code fault -- no evidence artifact to surface. 6E step-5
182
+ # design-note 2026-09-07: don't pass extras that never surface.
183
+ return LensResult("metamorphic", "ERROR", f"{type(exc).__name__}: {exc}")
184
+ detail = []
185
+ try:
186
+ from forgeproof.lens_tools.metamorphic.relations import is_gating
187
+ for r in results or []:
188
+ if not r.passed:
189
+ mark = "FAIL" if is_gating(r.name) else "ADVISORY"
190
+ detail.append(f"{r.name}: {mark} -- {r.reason}")
191
+ except Exception:
192
+ pass
193
+ if verdict == "RELATION-FAIL":
194
+ result = LensResult("metamorphic", "FAIL", summary, objected=True, detail=detail)
195
+ # DDMIN AT LENS LAYER (step 6). Only on the no-code real-defect path,
196
+ # only when source is long enough for shrinking to be worth the cost.
197
+ # Per 6E Q3 design consultation: route-path property, no user flag.
198
+ shrunk = _shrink_metamorphic_source(user_file, pattern, src_text)
199
+ extras = {"leaf_locals": _relation_frame(results)}
200
+ if shrunk is not None:
201
+ extras["shrunk_input"] = shrunk
202
+ return _attach_debug(result, src_text, src_origin, user_file, extras=extras)
203
+ if verdict == "ERROR":
204
+ return LensResult("metamorphic", "ERROR", summary, detail=detail)
205
+ if verdict == "UNSUPPORTED":
206
+ result = LensResult("metamorphic", "UNSUPPORTED",
207
+ _u("U1:no_coverage", summary).summary())
208
+ return _attach_debug(result, src_text, src_origin, user_file)
209
+ return LensResult("metamorphic", "PASS", summary, detail=detail)
210
+
211
+
212
+ def _relation_frame(results: Any) -> Dict[str, str]:
213
+ """For a metamorphic RELATION-FAIL, surface which relation broke and its
214
+ input→output shape so 'intermediate_values' names WHAT broke, not just
215
+ THAT something did. Returns a dict of stable string reprs -- the debug
216
+ core's intermediate_values field is Dict[str, str] by contract."""
217
+ out: Dict[str, str] = {}
218
+ for r in results or []:
219
+ if not getattr(r, "passed", True):
220
+ out[f"relation:{r.name}"] = str(getattr(r, "reason", ""))
221
+ src = getattr(r, "source_input", None)
222
+ fol = getattr(r, "follow_up_input", None)
223
+ if src is not None:
224
+ out[f"{r.name}.source_input"] = repr(src)[:200]
225
+ if fol is not None:
226
+ out[f"{r.name}.follow_up_input"] = repr(fol)[:200]
227
+ break # first failing relation is enough — do not dump the whole run
228
+ return out
229
+
230
+
231
+ _DDMIN_LENGTH_FLOOR = 8 # per 6E Q3: skip ddmin on trivially-minimal input
232
+ _DDMIN_MAX_STEPS = 40 # bound the cost — each step is a full metamorphic rerun
233
+
234
+
235
+ def _shrink_metamorphic_source(
236
+ user_file: Path, pattern: str, source_text: str,
237
+ ) -> Optional[Dict[str, Any]]:
238
+ """Shrink the user's source file to the minimum lines that still produce
239
+ RELATION-FAIL on the same pattern. Returns a dict with the minimal source
240
+ and the ddmin stats, or None when shrinking is skipped (too short) or
241
+ fails (never reproduced).
242
+
243
+ NAMED LIMIT: each ddmin step invokes a full metamorphic subprocess, so
244
+ this is bounded by _DDMIN_MAX_STEPS. On cap hit, best-so-far is returned
245
+ with hit_step_cap=True in the payload so a formatter can surface that.
246
+
247
+ Predicate errors are treated as PASS by ddmin — a rerun that itself
248
+ broke does not count as "still fails" (safe default: don't converge
249
+ on a predicate defect).
250
+ """
251
+ lines = source_text.splitlines(keepends=True)
252
+ if len(lines) < _DDMIN_LENGTH_FLOOR:
253
+ return None
254
+
255
+ from forgeproof.debug_core import ddmin
256
+
257
+ def still_fails(subset_lines: List[str]) -> bool:
258
+ import tempfile
259
+ with tempfile.NamedTemporaryFile(
260
+ mode="w", suffix=".py", delete=False,
261
+ ) as tf:
262
+ tf.write("".join(subset_lines))
263
+ tmp = Path(tf.name)
264
+ try:
265
+ from forgeproof.lens_tools.metamorphic.runner import run_metamorphic
266
+ v, _, _ = run_metamorphic(tmp, pattern)
267
+ return v == "RELATION-FAIL"
268
+ finally:
269
+ try:
270
+ tmp.unlink()
271
+ except Exception:
272
+ pass
273
+
274
+ result = ddmin(lines, still_fails, max_steps=_DDMIN_MAX_STEPS)
275
+ if not result.predicate_ever_failed:
276
+ return None
277
+ return {
278
+ "minimal_source": "".join(result.minimal),
279
+ "original_lines": len(lines),
280
+ "minimal_lines": len(result.minimal),
281
+ "steps": result.steps,
282
+ "hit_step_cap": result.hit_step_cap,
283
+ }
284
+
285
+
286
+ def _attach_debug(
287
+ result: "LensResult",
288
+ src_text: str,
289
+ src_origin: str,
290
+ user_file: Path,
291
+ *,
292
+ exc: Optional[BaseException] = None,
293
+ extras: Optional[Dict[str, Any]] = None,
294
+ ) -> "LensResult":
295
+ """Populate result.debug for FAIL/UNSUPPORTED verdicts; no-op on PASS.
296
+
297
+ Route through the forgeproof caller layer (debug_caller.route) so U-code
298
+ dispatch and the real-defect path stay in one place. Lazy-imported to
299
+ avoid the debug_caller <-> lenses circular import.
300
+
301
+ Any failure here is swallowed — debug is off-path, must never modify a
302
+ verdict. A raised exception in the wire-up would silently change a PASS
303
+ into an ERROR; the try/except guarantees the verdict returned is exactly
304
+ the verdict computed.
305
+ """
306
+ # UNSTABLE joins FAIL/UNSUPPORTED because twin-consensus produces UNSTABLE
307
+ # on a C++ compile failure, and brief §4.3 explicitly requires the
308
+ # compiler-output debug path there. Design invariant is now:
309
+ # "populate debug only on statuses that objected or expressed uncertainty
310
+ # about the code" -- PASS and ERROR (harness-broke) still stay debug=None.
311
+ if result.status not in ("FAIL", "UNSUPPORTED", "UNSTABLE"):
312
+ return result
313
+ try:
314
+ from forgeproof.debug_caller import route as _debug_route
315
+ result.debug = _debug_route(
316
+ result,
317
+ source_text=src_text,
318
+ source_origin=src_origin,
319
+ failing_input=str(user_file),
320
+ extras=extras,
321
+ exception=exc,
322
+ )
323
+ except Exception: # noqa: BLE001 — debug is off-path
324
+ result.debug = None
325
+ return result
326
+
327
+
328
+ def _run_invariant(user_file: Path, pattern: str) -> LensResult:
329
+ # DEBUG WIRE-UP (step 6, invariant lens). Same pattern as metamorphic:
330
+ # capture source unconditionally at top, _attach_debug on FAIL/UNSUPPORTED.
331
+ try:
332
+ src_text, src_origin = capture_source(user_file)
333
+ except Exception:
334
+ src_text, src_origin = "", str(user_file)
335
+
336
+ try:
337
+ from forgeproof.lens_tools import invariant_gate
338
+ status, reason = invariant_gate.verify(str(user_file), pattern)
339
+ except Exception as exc:
340
+ return LensResult("invariant", "ERROR", f"{type(exc).__name__}: {exc}")
341
+ if status == "FAIL":
342
+ return _attach_debug(
343
+ LensResult("invariant", "FAIL", reason, objected=True),
344
+ src_text, src_origin, user_file,
345
+ extras={"leaf_locals": {"invariant_reason": reason}},
346
+ )
347
+ if status == "UNSUPPORTED":
348
+ # Two shapes from invariant_gate — distinguished by reason substring.
349
+ # If a new UNSUPPORTED reason ever ships from the tool, the fallback
350
+ # here quietly maps it to U1 — the integration test on this branch
351
+ # asserts BOTH known shapes to catch drift.
352
+ code = "U2:contract_unratified" if "not yet ratified" in reason else "U1:no_coverage"
353
+ return _attach_debug(
354
+ LensResult("invariant", "UNSUPPORTED", _u(code, reason).summary()),
355
+ src_text, src_origin, user_file,
356
+ extras={"contract_path": None, "pattern": pattern},
357
+ )
358
+ return LensResult("invariant", "PASS", reason)
359
+
360
+
361
+ def _run_twin(user_file: Path, pattern: str, timeout: float) -> LensResult:
362
+ # DEBUG WIRE-UP (step 6, twin lens). Twin adds a distinct debug path
363
+ # per brief §4.3: compiler_output when the C++ half fails to build.
364
+ # We surface the failing metric side (whichever twin diverged) via
365
+ # tc.details as leaf_locals so the artifact names WHICH twin.
366
+ try:
367
+ src_text, src_origin = capture_source(user_file)
368
+ except Exception:
369
+ src_text, src_origin = "", str(user_file)
370
+
371
+ try:
372
+ from forgeproof.lens_tools import twin_consensus
373
+ tc = twin_consensus.consensus_verify(user_file, pattern, timeout=timeout)
374
+ except Exception as exc:
375
+ return LensResult("twin-consensus", "ERROR", f"{type(exc).__name__}: {exc}")
376
+ detail = list(tc.details or [])
377
+ if tc.status in ("FAIL", "UNSTABLE"):
378
+ # Brief §4.3 spec: "both twin outputs side by side, the metric each
379
+ # produced, and the tolerance that was exceeded." Surface tc.metrics
380
+ # (values) and tc.tolerance (bound) alongside the detail lines so a
381
+ # maintainer sees BY HOW MUCH each twin diverged, not only WHICH.
382
+ # 6E step-6 review Finding 4 (2026-09-07).
383
+ iv: Dict[str, str] = {
384
+ f"twin.detail[{i}]": d for i, d in enumerate(detail[:8])
385
+ }
386
+ metrics = getattr(tc, "metrics", None)
387
+ if isinstance(metrics, dict):
388
+ for k, v in metrics.items():
389
+ iv[f"twin.metric.{k}"] = repr(v)[:100]
390
+ tol = getattr(tc, "tolerance", None)
391
+ if tol is not None:
392
+ iv["twin.tolerance"] = repr(tol)
393
+ # 4Q step-6 review Finding 1: UNSTABLE is the compile-failed shape
394
+ # per brief §4.3; put the compiler output on the dedicated
395
+ # compiler_output field, not stuffed into intermediate_values.
396
+ # tc.compiler_output is the natural source when available; fall back
397
+ # to the detail lines that mention "compile"/"compiler" so a formatter
398
+ # gets SOMETHING on the compiler_output channel.
399
+ extras: Dict[str, Any] = {"leaf_locals": iv}
400
+ co = getattr(tc, "compiler_output", None)
401
+ if co:
402
+ extras["compiler_output"] = co
403
+ elif tc.status == "UNSTABLE":
404
+ compile_lines = [d for d in detail if "compil" in d.lower()]
405
+ if compile_lines:
406
+ extras["compiler_output"] = "\n".join(compile_lines)
407
+ return _attach_debug(
408
+ LensResult("twin-consensus", tc.status, tc.reason, objected=True, detail=detail),
409
+ src_text, src_origin, user_file,
410
+ extras=extras,
411
+ )
412
+ if tc.status == "UNSUPPORTED":
413
+ return _attach_debug(
414
+ LensResult("twin-consensus", "UNSUPPORTED",
415
+ _u("U1:no_coverage", tc.reason).summary(),
416
+ detail=detail),
417
+ src_text, src_origin, user_file,
418
+ )
419
+ return LensResult("twin-consensus", "PASS", tc.reason, detail=detail)
420
+
421
+
422
+ def _canonicalize(obj: Any) -> Any:
423
+ """Convert arbitrary Python return values into a stable, comparable form.
424
+
425
+ Custom objects become dicts of their public attributes; built-in containers
426
+ and primitives pass through. This avoids comparing object ids or memory
427
+ addresses (e.g. `<TreeNode object at 0x...>`) when the underlying data is
428
+ identical.
429
+ """
430
+ if obj is None:
431
+ return None
432
+ if isinstance(obj, (bool, int, float, str)):
433
+ return obj
434
+ if isinstance(obj, (list, tuple)):
435
+ return [_canonicalize(v) for v in obj]
436
+ if isinstance(obj, dict):
437
+ return {str(k): _canonicalize(v) for k, v in sorted(obj.items(), key=lambda kv: str(kv[0]))}
438
+ if hasattr(obj, "__dataclass_fields__"):
439
+ # dataclass — use asdict
440
+ from dataclasses import asdict
441
+ return _canonicalize(asdict(obj))
442
+ if hasattr(obj, "_asdict"):
443
+ # namedtuple
444
+ return _canonicalize(obj._asdict())
445
+ if hasattr(obj, "__dict__") and not isinstance(obj, type):
446
+ return _canonicalize(vars(obj))
447
+ # Fallback: repr is the best stable thing we have for truly opaque objects.
448
+ return repr(obj)
449
+
450
+
451
+ def _run_determinism(user_file: Path, pattern: str, timeout: float) -> LensResult:
452
+ """Detect non-deterministic implementations by varying the global RNG state.
453
+
454
+ Retries on HARNESS error. This lens spawns subprocesses; under load a spawn can
455
+ fail for reasons that have nothing to do with the code under test. Measured
456
+ 2026-08-01: two acceptance suites run back-to-back made this lens report ERROR
457
+ (-> UNSTABLE) for all 10 canonical oracles, which the acceptance test then recorded
458
+ as "the lens is unsound". Run alone, the same code returned 10/10 PASS.
459
+
460
+ THE LAW: a harness error must never be reported as a verdict about the code. A probe
461
+ that fails for its own reasons and reports failure accuses the pattern of a defect it
462
+ does not have -- and that accusation flows onward as if it were measurement.
463
+ """
464
+ # DEBUG WIRE-UP (step 6, determinism lens). Capture source once, attach
465
+ # to whichever final result is non-ERROR. ERROR returns pass through
466
+ # unchanged (design: ERROR leaves debug=None).
467
+ try:
468
+ src_text, src_origin = capture_source(user_file)
469
+ except Exception:
470
+ src_text, src_origin = "", str(user_file)
471
+
472
+ last = None
473
+ for attempt in range(3):
474
+ result = _run_determinism_once(user_file, pattern, timeout)
475
+ if result.status != "ERROR":
476
+ # Brief §4.4: surface tolerance and run-pair alongside the diff.
477
+ # The reason string now names the run pair inline (see
478
+ # _run_determinism_once); extras add the tolerance explicitly so
479
+ # a formatter does not need to parse the reason to find it.
480
+ # 6E step-6 review Finding 5 (2026-09-07).
481
+ return _attach_debug(
482
+ result, src_text, src_origin, user_file,
483
+ extras={"leaf_locals": {
484
+ "determinism_reason": result.reason,
485
+ "determinism_tolerance": "1e-12",
486
+ "determinism_n_runs": "3",
487
+ }},
488
+ )
489
+ last = result
490
+ time.sleep(0.4 * (attempt + 1))
491
+ return LensResult(
492
+ "determinism", "ERROR",
493
+ f"harness failed {3} times, no verdict on the code itself "
494
+ f"(last: {last.reason if last else 'unknown'})",
495
+ )
496
+
497
+
498
+ def _run_determinism_once(user_file: Path, pattern: str, timeout: float) -> LensResult:
499
+ """One attempt. See _run_determinism for the retry rationale."""
500
+ import json
501
+ import os
502
+ import shutil
503
+ import subprocess
504
+ import tempfile
505
+ import textwrap
506
+ import types
507
+
508
+ from .catalog import resolve_pattern
509
+ from .runner import run_file
510
+
511
+ N_RUNS = 3
512
+ TOLERANCE = 1e-12
513
+
514
+ try:
515
+ pattern_meta = resolve_pattern(pattern)
516
+ except Exception as exc:
517
+ return LensResult("determinism", "ERROR", f"cannot resolve pattern: {exc}")
518
+
519
+ fixture_script = Path(__file__).resolve().parent / "fixtures" / f"{pattern_meta['fixture']}.py"
520
+ if not fixture_script.exists():
521
+ return LensResult("determinism", "UNSUPPORTED", _u("U1:no_coverage", f"no fixture for {pattern}").summary())
522
+
523
+ # ---- Step 1: capture the exact arguments the fixture passes to user_fn ----
524
+ capture_src = textwrap.dedent(f"""
525
+ import importlib.util
526
+ import json
527
+ import sys
528
+ import types
529
+
530
+ sys.path.insert(0, {str(_PKG_PARENT)!r})
531
+ import forgeproof.fixture_engine as fe
532
+
533
+ class DataCaptured(Exception):
534
+ pass
535
+
536
+ class FakeUserModule(types.ModuleType):
537
+ def __init__(self):
538
+ super().__init__("user_impl")
539
+ self._captured = None
540
+
541
+ def __getattr__(self, name):
542
+ def capture(*args, **kwargs):
543
+ self._captured = {{"fn": name, "args": args, "kwargs": kwargs}}
544
+ raise DataCaptured("captured")
545
+ return capture
546
+
547
+ fake_user = FakeUserModule()
548
+ sys.modules["user_impl"] = fake_user
549
+
550
+ _real_load_module = fe.load_module
551
+ def _patched_load_module(path, module_name):
552
+ if module_name == "user_impl":
553
+ return fake_user
554
+ return _real_load_module(path, module_name)
555
+ fe.load_module = _patched_load_module
556
+
557
+ fixture_script_arg = sys.argv[1]
558
+ sys.argv = [fixture_script_arg, "/dev/null"]
559
+ spec = importlib.util.spec_from_file_location("fixture_mod", fixture_script_arg)
560
+ fixture_mod = importlib.util.module_from_spec(spec)
561
+ try:
562
+ spec.loader.exec_module(fixture_mod)
563
+ if hasattr(fixture_mod, "main"):
564
+ fixture_mod.main()
565
+ except DataCaptured:
566
+ pass
567
+
568
+ if fake_user._captured is None:
569
+ print("CAPTURE_ERROR no function captured", file=sys.stderr)
570
+ sys.exit(1)
571
+
572
+ print("CAPTURED " + json.dumps(fake_user._captured, default=str))
573
+ """)
574
+
575
+ capture_file = None
576
+ try:
577
+ with tempfile.NamedTemporaryFile(mode="w", suffix=".py", delete=False, dir=_scratch_dir()) as tf:
578
+ tf.write(capture_src)
579
+ capture_file = Path(tf.name)
580
+ res = run_file(capture_file, timeout=timeout, extra_args=[str(fixture_script)], no_network=True, memory_mb=512)
581
+ if res.timed_out:
582
+ return LensResult("determinism", "ERROR", "fixture capture timed out")
583
+ if res.exit_code != 0:
584
+ return LensResult("determinism", "UNSUPPORTED", _u("U4:capture_failed", res.stderr[-200:]).summary())
585
+ captured_json = None
586
+ for line in res.stdout.splitlines():
587
+ if line.startswith("CAPTURED "):
588
+ captured_json = line[len("CAPTURED "):]
589
+ break
590
+ if captured_json is None:
591
+ return LensResult("determinism", "ERROR", "capture produced no CAPTURED line")
592
+ captured = json.loads(captured_json)
593
+ except Exception as exc:
594
+ return LensResult("determinism", "ERROR", f"capture exception: {type(exc).__name__}: {exc}")
595
+ finally:
596
+ if capture_file:
597
+ try:
598
+ capture_file.unlink()
599
+ except Exception:
600
+ pass
601
+
602
+ fn_name = captured["fn"]
603
+ args = captured["args"]
604
+ kwargs = captured["kwargs"]
605
+
606
+ # ---- Step 2: run the user function N times on identical data with different seeds ----
607
+ tmpdir = Path(tempfile.mkdtemp(prefix="fg-determinism-", dir=_scratch_dir()))
608
+ harness = tmpdir / "run_one.py"
609
+ harness.write_text(textwrap.dedent(f"""
610
+ import json
611
+ import random
612
+ import sys
613
+ sys.path.insert(0, {str(_PKG_PARENT)!r})
614
+ from forgeproof.fixture_engine import get_fn, load_module
615
+
616
+ def _can(obj):
617
+ if obj is None or isinstance(obj, (bool, int, float, str)):
618
+ return obj
619
+ if isinstance(obj, (list, tuple)):
620
+ return [_can(v) for v in obj]
621
+ if isinstance(obj, dict):
622
+ return {{str(k): _can(v) for k, v in sorted(obj.items(), key=lambda kv: str(kv[0]))}}
623
+ if hasattr(obj, "__dataclass_fields__"):
624
+ from dataclasses import asdict
625
+ return _can(asdict(obj))
626
+ if hasattr(obj, "_asdict"):
627
+ return _can(obj._asdict())
628
+ if hasattr(obj, "__dict__") and not isinstance(obj, type):
629
+ return _can(vars(obj))
630
+ return repr(obj)
631
+
632
+ seed_idx, user_path = sys.argv[1:3]
633
+ user_mod = load_module(user_path, "user_impl")
634
+ user_fn = get_fn(user_mod, {fn_name!r})
635
+
636
+ if seed_idx == "0":
637
+ random.seed(42)
638
+ else:
639
+ seed = 1000 + int(seed_idx)
640
+ random.seed(seed)
641
+ try:
642
+ import numpy as np
643
+ np.random.seed(2000 + int(seed_idx))
644
+ except Exception:
645
+ pass
646
+
647
+ args = json.loads({json.dumps(args)!r})
648
+ kwargs = json.loads({json.dumps(kwargs)!r})
649
+ try:
650
+ out = user_fn(*args, **kwargs)
651
+ except Exception as exc:
652
+ out = {{"_error": repr(exc)}}
653
+ print(json.dumps(_can(out)))
654
+ """), encoding="utf-8")
655
+
656
+ outputs: list[Any] = []
657
+ from forgeproof.config import python as _python
658
+ runner = _python()
659
+ try:
660
+ for i in range(N_RUNS):
661
+ try:
662
+ env = os.environ.copy()
663
+ env.pop("PYTHONPATH", None)
664
+ env["PYTHONDONTWRITEBYTECODE"] = "1"
665
+ proc = subprocess.run(
666
+ [runner, str(harness), str(i), str(user_file)],
667
+ capture_output=True, text=True, timeout=timeout,
668
+ env=env,
669
+ )
670
+ if proc.returncode != 0:
671
+ return LensResult("determinism", "ERROR", f"run {i} exited {proc.returncode}: {proc.stderr[-200:]}")
672
+ raw = json.loads(proc.stdout.splitlines()[-1])
673
+ outputs.append(_canonicalize(raw))
674
+ except Exception as exc:
675
+ return LensResult("determinism", "ERROR", f"run {i} failed: {type(exc).__name__}: {exc}")
676
+ finally:
677
+ try:
678
+ shutil.rmtree(tmpdir, ignore_errors=True)
679
+ except Exception:
680
+ pass
681
+
682
+ # ---- Step 3: compare all runs to run 0 at 1e-12 ----
683
+ def find_diff(a: Any, b: Any, prefix: str = "") -> Optional[str]:
684
+ if isinstance(a, dict) and isinstance(b, dict):
685
+ for k in sorted(set(a) | set(b)):
686
+ if k not in a:
687
+ return f"{prefix}{k}: missing in first run"
688
+ if k not in b:
689
+ return f"{prefix}{k}: missing in run {i}"
690
+ d = find_diff(a[k], b[k], prefix=f"{prefix}{k}.")
691
+ if d:
692
+ return d
693
+ return None
694
+ if isinstance(a, list) and isinstance(b, list):
695
+ if len(a) != len(b):
696
+ return f"{prefix}list length differs ({len(a)} vs {len(b)})"
697
+ for idx, (x, y) in enumerate(zip(a, b)):
698
+ d = find_diff(x, y, prefix=f"{prefix}[{idx}]")
699
+ if d:
700
+ return d
701
+ return None
702
+ if isinstance(a, bool) or isinstance(b, bool):
703
+ if a != b:
704
+ return f"{prefix}: {a!r} vs {b!r}"
705
+ return None
706
+ if isinstance(a, (int, float)) and isinstance(b, (int, float)):
707
+ if a == b:
708
+ return None
709
+ denom = max(abs(a), abs(b), 1.0)
710
+ if abs(a - b) / denom > TOLERANCE:
711
+ return f"{prefix}: {a!r} vs {b!r}"
712
+ return None
713
+ if a != b:
714
+ return f"{prefix}: {a!r} vs {b!r}"
715
+ return None
716
+
717
+ for i in range(1, N_RUNS):
718
+ diff = find_diff(outputs[0], outputs[i])
719
+ if diff:
720
+ # Brief §4.4 wants "which value diverged, at what tolerance, on
721
+ # which run pair." Name the run pair (0 vs i) in the reason so
722
+ # the wire-up can surface it downstream. Tolerance is a module
723
+ # constant already; the wire-up will add it to extras.
724
+ return LensResult(
725
+ "determinism", "FAIL",
726
+ f"non-deterministic output at run 0 vs run {i} (tolerance {TOLERANCE}): {diff}",
727
+ objected=determinism_gates_for(pattern),
728
+ )
729
+
730
+ return LensResult("determinism", "PASS", f"{N_RUNS} runs identical at tolerance {TOLERANCE}")
731
+
732
+
733
+ def parse_lens_selection(spec: Optional[str]) -> List[str]:
734
+ """'all' | 'default' | comma list. property-primary is always included."""
735
+ if not spec or spec == "default":
736
+ return list(DEFAULT_LENSES)
737
+ if spec == "all":
738
+ return list(ALL_LENSES)
739
+ chosen = [s.strip() for s in spec.split(",") if s.strip()]
740
+ unknown = [c for c in chosen if c not in ALL_LENSES]
741
+ if unknown:
742
+ raise ValueError(
743
+ f"unknown lens(es): {', '.join(unknown)}. choose from: {', '.join(ALL_LENSES)}, "
744
+ "or use 'all' / 'default'"
745
+ )
746
+ return [BASE_LENS] + [c for c in chosen if c != BASE_LENS]
747
+
748
+
749
+ def _run_guard(user_file: Path, timeout: float) -> LensResult:
750
+ """Run the external guard lens subprocess and return an enforced result.
751
+
752
+ The guard lens is now gating: a genuine NaN-defect FAIL sets objected=True
753
+ and can turn PASS -> FAIL. A timeout or crash is returned as ERROR and
754
+ never objected. An INCONCLUSIVE verdict is returned as UNSUPPORTED with a
755
+ U4:coverage_gap reason code — a harness that could not measure must not
756
+ accuse the code, and ERROR would bubble to UNSTABLE which itself accuses.
757
+ """
758
+ import shutil
759
+ import subprocess
760
+
761
+ # DEBUG WIRE-UP (step 5, fast-follow after metamorphic): capture source
762
+ # BEFORE the guard subprocess runs. guard_lens.py uses its own
763
+ # NamedTemporaryFile + finally: unlink() internally; we capture the
764
+ # ADAPTER-side user_file which is a persistent path, so the ordering is
765
+ # trivially safe here. The trap is inside guard_lens.py, not this layer.
766
+ try:
767
+ src_text, src_origin = capture_source(user_file)
768
+ except Exception:
769
+ src_text, src_origin = "", str(user_file)
770
+
771
+ from forgeproof.config import python as _python
772
+ runner = _python()
773
+ if not runner:
774
+ return LensResult("guard", "ERROR", "python3 not available")
775
+
776
+ if not GUARD_LENS.is_file():
777
+ return LensResult("guard", "ERROR", f"guard lens missing from the installed package: {GUARD_LENS}")
778
+ cmd = [runner, str(GUARD_LENS), "--fixture", str(user_file)]
779
+ try:
780
+ proc = subprocess.run(
781
+ cmd,
782
+ capture_output=True,
783
+ text=True,
784
+ timeout=min(timeout, 60.0),
785
+ env={**__import__("os").environ, "PYTHONDONTWRITECOMPILE": "1"},
786
+ )
787
+ except subprocess.TimeoutExpired:
788
+ return LensResult("guard", "ERROR", "guard lens timed out")
789
+ except Exception as exc:
790
+ return LensResult("guard", "ERROR", f"guard lens spawn failed: {type(exc).__name__}: {exc}")
791
+
792
+ # Extract verdict line from stdout.
793
+ verdict = None
794
+ detail: List[str] = []
795
+ for line in proc.stdout.splitlines():
796
+ if line.startswith("verdict:"):
797
+ verdict = line[len("verdict:"):].strip()
798
+ elif line.startswith("detail:"):
799
+ detail.append(line[len("detail:"):].strip())
800
+
801
+ if proc.returncode != 0 or verdict is None:
802
+ return LensResult(
803
+ "guard", "ERROR",
804
+ f"guard lens did not produce verdict (rc={proc.returncode})",
805
+ detail=detail or [proc.stderr[-200:]] if proc.stderr else [],
806
+ )
807
+
808
+ # A genuine NaN-defect FAIL now gates; INCONCLUSIVE/ERROR/PASS do not.
809
+ if verdict.startswith("FAIL"):
810
+ return _attach_debug(
811
+ LensResult("guard", "FAIL", verdict, objected=True, detail=detail),
812
+ src_text, src_origin, user_file,
813
+ extras={"leaf_locals": {"verdict": verdict, "detail": "; ".join(detail)}},
814
+ )
815
+ if verdict.startswith("PASS"):
816
+ return LensResult("guard", "PASS", verdict, detail=detail)
817
+ if verdict.startswith("INCONCLUSIVE"):
818
+ # A harness that could not measure must not accuse the code (§3.2).
819
+ # ERROR would bubble to UNSTABLE — itself an accusation. UNSUPPORTED
820
+ # with an explicit U4 code names the coverage gap without blame.
821
+ return _attach_debug(
822
+ LensResult(
823
+ "guard", "UNSUPPORTED",
824
+ _u("U4:coverage_gap", verdict).summary(),
825
+ detail=detail,
826
+ ),
827
+ src_text, src_origin, user_file,
828
+ extras={"params_aborted": [], "unexercisable": []},
829
+ )
830
+ return _attach_debug(
831
+ LensResult("guard", "UNSUPPORTED", verdict, detail=detail),
832
+ src_text, src_origin, user_file,
833
+ )
834
+
835
+
836
+ # ---------------------------------------------------------------------------
837
+ # evaluate
838
+ # ---------------------------------------------------------------------------
839
+
840
+
841
+ def evaluate(
842
+ *,
843
+ pattern: str,
844
+ user_file: Path,
845
+ base_status: str,
846
+ base_reason: str,
847
+ base_metrics: Dict[str, Any],
848
+ lenses: List[str],
849
+ timeout: float = 60.0,
850
+ short_circuit: bool = True,
851
+ ) -> GateVerdict:
852
+ """Run the selected lenses over an already-computed base verdict and reduce.
853
+
854
+ short_circuit=True skips supplementary lenses once property-primary has failed --
855
+ they cannot overturn it, so running them only costs time. Set False to collect
856
+ every lens's opinion for a demo or a report; the VERDICT is identical either way.
857
+ """
858
+ results: List[LensResult] = [
859
+ LensResult(
860
+ BASE_LENS,
861
+ base_status,
862
+ base_reason,
863
+ objected=(base_status not in ("PASS", "UNSUPPORTED")),
864
+ )
865
+ ]
866
+
867
+ # Supplementary and advisory lenses cannot overturn a base FAIL, so by default
868
+ # we stop there. With short_circuit=False we still gather them as evidence --
869
+ # the verdict is unchanged, we simply show the full picture.
870
+ if base_status == "PASS" or not short_circuit:
871
+ if "metamorphic" in lenses:
872
+ results.append(_run_metamorphic(user_file, pattern))
873
+ if "invariant" in lenses:
874
+ results.append(_run_invariant(user_file, pattern))
875
+ if "twin-consensus" in lenses:
876
+ results.append(_run_twin(user_file, pattern, timeout))
877
+ if "determinism" in lenses:
878
+ results.append(_run_determinism(user_file, pattern, timeout))
879
+ if "guard" in lenses:
880
+ results.append(_run_guard(user_file, timeout))
881
+
882
+ objectors = [l for l in results if l.objected]
883
+ errored = [l for l in results if l.status == "ERROR"]
884
+
885
+ if objectors:
886
+ status = "FAIL"
887
+ if len(objectors) == 1 and objectors[0].name == BASE_LENS:
888
+ reason = base_reason
889
+ else:
890
+ named = "; ".join(f"{l.name}: {l.reason}" for l in objectors)
891
+ reason = f"property-primary passed, but {len(objectors)} lens(es) objected -- {named}"
892
+ elif errored:
893
+ status = "UNSTABLE"
894
+ reason = "; ".join(f"{l.name} errored: {l.reason}" for l in errored)
895
+ else:
896
+ status = "PASS"
897
+ reason = base_reason
898
+ skipped = [l.name for l in results if l.status == "UNSUPPORTED"]
899
+ if skipped:
900
+ reason += f" (unsupported here: {', '.join(skipped)})"
901
+
902
+ return GateVerdict(
903
+ status=status,
904
+ pattern=pattern,
905
+ user_file=str(user_file),
906
+ reason=reason,
907
+ lenses=results,
908
+ metrics=base_metrics or {},
909
+ )
910
+
911
+
912
+ def render(v: GateVerdict, show_table: bool) -> str:
913
+ lines = [f"{v.status}: {v.pattern}", f" file: {v.user_file}", f" reason: {v.reason}"]
914
+ if v.metrics:
915
+ lines.append(f" metrics: {v.metrics}")
916
+ if show_table:
917
+ lines.append(" lenses:")
918
+ for l in v.lenses:
919
+ mark = "<<" if l.objected else " "
920
+ lines.append(f" {l.name:<18} {l.status:<12} {mark} {l.reason}")
921
+ for d in l.detail:
922
+ lines.append(f" - {d}")
923
+ return "\n".join(lines)