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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
"""Release gate for natural-language contract to typed-predicate compilation.

Schema validation answers whether a predicate record is well formed.  This
module answers the stricter question needed before an evaluation run: did
every scored contract check become an executable, tool-backed predicate?
"""

from __future__ import annotations

from collections import Counter
from dataclasses import dataclass
import hashlib
from typing import Any, Mapping

from pvr_eval.agent.executable_predicate import validate_executable_predicate
from pvr_eval.agent.source_instance_selector import has_relational_identity_query
from pvr_eval.contracts.fact_producer_registry import (
    objective_obligation_producer,
    objective_producer_for_binding,
    runtime_producer_supports_binding,
)
from pvr_eval.contracts.predicate_lowering import (
    reviewed_region_policy_reasons,
    reviewed_source_check_sha256,
)
from pvr_eval.contracts.region_materializer_registry import executable_region_materializer
from pvr_eval.core.schema import EvalContract


@dataclass(frozen=True)
class CompilationGatePolicy:
    """Policy controlling which compiled contracts may enter evaluation."""

    name: str = "strict-zero-vlm"
    minimum_executable_weight_coverage: float = 1.0
    allow_manual_review: bool = False
    allow_vlm_fallback: bool = False
    require_physical_tool_calls: bool = True


def policy_for_name(name: str) -> CompilationGatePolicy:
    normalized = str(name or "").strip().lower()
    if normalized == "strict-zero-vlm":
        return CompilationGatePolicy()
    if normalized == "hybrid-review":
        return CompilationGatePolicy(
            name="hybrid-review",
            minimum_executable_weight_coverage=0.0,
            allow_manual_review=True,
            allow_vlm_fallback=True,
        )
    if normalized == "report-only":
        return CompilationGatePolicy(
            name="report-only",
            minimum_executable_weight_coverage=0.0,
            allow_manual_review=True,
            allow_vlm_fallback=True,
            require_physical_tool_calls=False,
        )
    raise ValueError(f"unknown compilation gate policy: {name!r}")


def _mapping(value: Any) -> Mapping[str, Any]:
    return value if isinstance(value, Mapping) else {}


def _predicate_from_compiled_check(compiled: Mapping[str, Any]) -> Mapping[str, Any]:
    direct = compiled.get("executable_predicate")
    if isinstance(direct, Mapping):
        return direct
    params = _mapping(compiled.get("params"))
    nested = params.get("executable_predicate")
    return nested if isinstance(nested, Mapping) else {}


def _region_ids(values: Any) -> set[str]:
    if not isinstance(values, (list, tuple)):
        return set()
    return {
        str(item.get("region_id") or item.get("id") or "").strip()
        for item in values
        if isinstance(item, Mapping) and str(item.get("region_id") or item.get("id") or "").strip()
    }


def _source_contract_sha256(contract: EvalContract) -> str:
    if contract.source_path is None or not contract.source_path.is_file():
        return ""
    return hashlib.sha256(contract.source_path.read_bytes()).hexdigest()


def validate_contract_compilation(
    contract: EvalContract,
    plan: Mapping[str, Any],
    *,
    policy: CompilationGatePolicy | None = None,
) -> dict[str, Any]:
    """Validate semantic executability of one compiled contract and plan.

    ``blocked_uncompiled`` is a valid serialization state, but it is never a
    successful compilation in strict mode.  The report keeps that distinction
    explicit so a batch cannot receive a green light merely because all JSON
    records conform to their schemas.
    """

    policy = policy or CompilationGatePolicy()
    checks_by_id = {check.check_id: check for check in contract.atomic_checks}
    plan_rows = {
        str(item.get("check_id") or ""): item
        for item in plan.get("check_plans", [])
        if isinstance(item, Mapping) and item.get("check_id")
    }
    compiled_rows = _mapping(plan.get("compiled_checks"))

    total_weight = sum(max(0.0, check.weight) for check in contract.atomic_checks)
    executable_weight = 0.0
    manual_weight = 0.0
    fallback_weight = 0.0
    status_counts: Counter[str] = Counter()
    reason_counts: Counter[str] = Counter()
    detail_rows: list[dict[str, Any]] = []
    fatal_reasons: list[str] = []

    expected_ids = set(checks_by_id)
    plan_ids = set(plan_rows)
    for missing in sorted(expected_ids - plan_ids):
        fatal_reasons.append(f"missing_check_plan:{missing}")
    for extra in sorted(plan_ids - expected_ids):
        fatal_reasons.append(f"orphan_check_plan:{extra}")

    for check_id, check in checks_by_id.items():
        check_plan = _mapping(plan_rows.get(check_id))
        compiled = _mapping(compiled_rows.get(check_id))
        predicate = _predicate_from_compiled_check(compiled)
        plan_status = str(check_plan.get("status") or "missing")
        predicate_status = str(predicate.get("status") or "missing")
        plan_reasons = [str(item) for item in check_plan.get("reasons", []) or []]
        validation = validate_executable_predicate(predicate) if predicate else None
        check_reasons: list[str] = []
        runtime_missing_fact_capabilities: list[dict[str, str]] = []

        status_counts[plan_status] += 1
        for reason in plan_reasons:
            reason_counts[reason] += 1

        if not check_plan:
            check_reasons.append("missing_check_plan")
        if not predicate:
            check_reasons.append("missing_executable_predicate")
        elif validation is not None and not validation.valid:
            check_reasons.extend(f"invalid_predicate:{item}" for item in validation.reasons)

        unmapped = list(predicate.get("unmapped_contract_parameters", []) or []) if predicate else []
        if unmapped:
            check_reasons.append("unmapped_contract_parameters")
        if (
            predicate
            and str(predicate.get("family") or "") == "source_region_clearance"
            and has_relational_identity_query(predicate)
            and not str(_mapping(predicate.get("parameters")).get("source_selector_profile") or "")
        ):
            check_reasons.append("relational_identity_without_typed_selector")

        compiled_params = _mapping(compiled.get("params"))
        declared_region_ids = _region_ids(compiled_params.get("planned_regions"))
        consumed_region_ids = _region_ids(predicate.get("regions")) if predicate else set()
        ignored_region_ids = {
            str(item) for item in predicate.get("explicitly_ignored_region_ids", []) or []
        } if predicate else set()
        unconsumed_region_ids = sorted(declared_region_ids - consumed_region_ids - ignored_region_ids)
        if unconsumed_region_ids and not (
            plan_status == "manual_review_required" and policy.allow_manual_review
        ):
            check_reasons.append("unconsumed_contract_regions")

        # Reviewed golden-IR predicates carry stronger semantic evidence than
        # the base executable schema.  Validate that every source parameter is
        # bound, every materializer is concrete, and all mutation witnesses ran.
        if predicate and predicate.get("capability_versions"):
            policy_reasons = reviewed_region_policy_reasons(predicate)
            if policy_reasons:
                check_reasons.extend(policy_reasons)
            source_parameters = _mapping(_mapping(compiled_params.get("decision_rule")).get("parameters"))
            parameter_bindings = [
                item for item in predicate.get("parameter_bindings", []) or []
                if isinstance(item, Mapping)
            ]
            bound_keys = {
                str(item.get("source_key") or "") for item in parameter_bindings
                if str(item.get("source_key") or "") in source_parameters
            }
            missing_parameter_bindings = sorted(set(source_parameters) - bound_keys)
            if missing_parameter_bindings:
                check_reasons.append("source_parameters_without_bindings")
            materializer_failures = [
                str(item.get("region_id") or "")
                for item in predicate.get("regions", []) or []
                if isinstance(item, Mapping)
                and str(_mapping(item.get("materializer")).get("kind") or "") in {"", "unsupported"}
            ]
            if materializer_failures:
                check_reasons.append("unregistered_region_materializers")
            runtime_materializer_failures = [
                str(item.get("region_id") or "")
                for item in predicate.get("regions", []) or []
                if isinstance(item, Mapping)
                and not executable_region_materializer(
                    str(_mapping(item.get("materializer")).get("kind") or "")
                )
            ]
            if runtime_materializer_failures:
                check_reasons.append("region_materializer_runtime_unavailable")
            witnesses = [
                item for item in predicate.get("witness_results", []) or []
                if isinstance(item, Mapping)
            ]
            if not witnesses:
                check_reasons.append("missing_compilation_witnesses")
            elif any(not bool(item.get("passed")) for item in witnesses):
                check_reasons.append("compilation_witness_failed")
            if not str(predicate.get("source_check_sha256") or ""):
                check_reasons.append("missing_source_check_sha256")
            elif (
                _mapping(predicate.get("provenance")).get("compiler")
                == "pvr_eval.contracts.predicate_lowering.lower_reviewed_predicate"
                and check.source_payload
                and
                str(predicate.get("source_check_sha256") or "")
                != reviewed_source_check_sha256(check.source_payload)
            ):
                check_reasons.append("source_check_hash_mismatch")
            decision_bindings = [
                item for item in predicate.get("parameter_bindings", []) or []
                if isinstance(item, Mapping) and item.get("consumer") == "decision_clause"
            ]
            producer_rows = [
                item for item in predicate.get("fact_producers", []) or []
                if isinstance(item, Mapping)
            ]
            producers_by_clause = {
                str(item.get("clause_id") or ""): item for item in producer_rows
            }
            missing_fact_producers = [
                str(item.get("clause_id") or item.get("fact") or "missing")
                for item in decision_bindings
                if not str(_mapping(producers_by_clause.get(str(item.get("clause_id") or ""))).get("producer") or "")
            ]
            if missing_fact_producers:
                check_reasons.append("decision_facts_without_registered_producers")
            producer_mismatches: list[str] = []
            predicate_family = str(predicate.get("family") or "")
            predicate_rule = str(predicate.get("source_rule_type") or "")
            expected_obligation_producer = objective_obligation_producer(
                predicate_family,
                predicate_rule,
            )
            for binding in decision_bindings:
                clause_id = str(binding.get("clause_id") or binding.get("fact") or "missing")
                producer_row = _mapping(producers_by_clause.get(str(binding.get("clause_id") or "")))
                declared_producer = str(producer_row.get("producer") or "")
                declared_mode = str(producer_row.get("mode") or "")
                binding_producer = str(binding.get("producer") or "")
                binding_mode = str(binding.get("producer_mode") or "")
                fact = str(binding.get("fact") or "")
                expected_objective = objective_producer_for_binding(
                    predicate_family,
                    binding,
                    _mapping(predicate.get("parameters")),
                )
                if fact.startswith("obligation:"):
                    if expected_obligation_producer:
                        valid = (
                            declared_producer == expected_obligation_producer
                            and declared_mode == "objective"
                        )
                    else:
                        valid = (
                            declared_producer == "reviewed_semantic_vlm"
                            and declared_mode == "semantic_vlm"
                        )
                elif expected_objective:
                    valid = declared_producer == expected_objective and declared_mode == "objective"
                else:
                    valid = declared_producer == "reviewed_semantic_vlm" and declared_mode == "semantic_vlm"
                valid = bool(
                    valid
                    and binding_producer == declared_producer
                    and binding_mode == declared_mode
                )
                if not valid:
                    producer_mismatches.append(clause_id)
                elif declared_mode == "objective" and not runtime_producer_supports_binding(
                    declared_producer,
                    binding,
                    predicate,
                ):
                    runtime_missing_fact_capabilities.append(
                        {
                            "clause_id": clause_id,
                            "fact": fact,
                            "producer": declared_producer,
                        }
                    )
            if producer_mismatches:
                check_reasons.append("fact_producer_runtime_mismatch")
            if runtime_missing_fact_capabilities:
                check_reasons.append("objective_fact_runtime_capability_missing")
            semantic_requirements = [
                item for item in producer_rows
                if str(item.get("mode") or "") == "semantic_vlm"
            ]
            if semantic_requirements and not policy.allow_vlm_fallback:
                check_reasons.append("semantic_vlm_forbidden_by_policy")

        decision = _mapping(predicate.get("decision")) if predicate else {}
        if plan_status in {"executable", "fallback_required"}:
            allowed_outcomes = {
                str(item) for item in decision.get("allowed_outcomes", []) or []
            }
            explicit_or_allowed = set(decision) | allowed_outcomes
            missing_branches = [
                branch for branch in ("pass", "fail", "unknown")
                if branch not in explicit_or_allowed
            ]
            if missing_branches:
                check_reasons.append("incomplete_decision_table:" + ",".join(missing_branches))
            source_decision = _mapping(compiled_params.get("decision_rule"))
            if (
                str(source_decision.get("partial_condition") or "").strip()
                and "partial" not in explicit_or_allowed
            ):
                check_reasons.append("missing_partial_decision_branch")

        tool_call_ids = [str(item) for item in check_plan.get("tool_call_ids", []) or []]
        if plan_status == "executable":
            if predicate_status != "executable":
                check_reasons.append(f"predicate_status_mismatch:{predicate_status}")
            if policy.require_physical_tool_calls and not tool_call_ids:
                check_reasons.append("executable_check_has_no_physical_tool_calls")
            if not check_reasons:
                executable_weight += max(0.0, check.weight)
        elif plan_status == "manual_review_required":
            manual_weight += max(0.0, check.weight)
            if not policy.allow_manual_review:
                check_reasons.append("manual_review_forbidden_by_policy")
        elif plan_status == "fallback_required":
            fallback = str(check_plan.get("fallback") or "")
            if not fallback:
                check_reasons.append("fallback_required_without_explicit_executor")
            if predicate_status != "executable":
                check_reasons.append(f"predicate_status_mismatch:{predicate_status}")
            if not policy.allow_vlm_fallback:
                check_reasons.append("vlm_fallback_forbidden_by_policy")
            if policy.require_physical_tool_calls and not tool_call_ids:
                check_reasons.append("fallback_check_has_no_physical_tool_calls")
            if not check_reasons:
                fallback_weight += max(0.0, check.weight)
        else:
            check_reasons.append(f"non_executable_plan_status:{plan_status}")

        for reason in check_reasons:
            reason_counts[reason] += 1
            fatal_reasons.append(f"{check_id}:{reason}")
        detail_rows.append(
            {
                "check_id": check_id,
                "role": check.role,
                "weight": check.weight,
                "checker": check.checker,
                "plan_status": plan_status,
                "predicate_status": predicate_status,
                "predicate_family": str(predicate.get("family") or ""),
                "source_rule_type": str(predicate.get("source_rule_type") or ""),
                "tool_call_count": len(tool_call_ids),
                "unmapped_contract_parameters": unmapped,
                "declared_region_ids": sorted(declared_region_ids),
                "consumed_region_ids": sorted(consumed_region_ids),
                "unconsumed_region_ids": unconsumed_region_ids,
                "runtime_unavailable_region_ids": (
                    runtime_materializer_failures
                    if predicate and predicate.get("capability_versions")
                    else []
                ),
                "witness_count": len(predicate.get("witness_results", []) or []) if predicate else 0,
                "semantic_fact_count": len(predicate.get("semantic_fact_requirements", []) or []) if predicate else 0,
                "runtime_missing_fact_capabilities": runtime_missing_fact_capabilities,
                "plan_reasons": plan_reasons,
                "gate_reasons": check_reasons,
                "passed": not check_reasons,
            }
        )

    coverage = executable_weight / total_weight if total_weight > 0 else 0.0
    if coverage + 1e-12 < policy.minimum_executable_weight_coverage:
        fatal_reasons.append(
            "executable_weight_coverage_below_minimum:"
            f"{coverage:.6f}<{policy.minimum_executable_weight_coverage:.6f}"
        )

    # report-only is intentionally non-blocking, but still exposes whether the
    # same batch would pass the semantic release gate.
    semantic_passed = not fatal_reasons
    enforced_passed = True if policy.name == "report-only" else semantic_passed
    return {
        "schema_version": "pvr.contract_compilation_gate.v1",
        "case_id": contract.case_id,
        "source_contract_sha256": _source_contract_sha256(contract),
        "policy": policy.name,
        "passed": enforced_passed,
        "semantic_passed": semantic_passed,
        "check_count": len(contract.atomic_checks),
        "total_weight": round(total_weight, 6),
        "executable_weight": round(executable_weight, 6),
        "manual_review_weight": round(manual_weight, 6),
        "fallback_weight": round(fallback_weight, 6),
        "executable_weight_coverage": round(coverage, 6),
        "minimum_executable_weight_coverage": policy.minimum_executable_weight_coverage,
        "status_counts": dict(sorted(status_counts.items())),
        "reason_counts": dict(reason_counts.most_common()),
        "fatal_reasons": fatal_reasons,
        "checks": detail_rows,
    }


def summarize_compilation_gates(
    reports: list[Mapping[str, Any]],
    *,
    policy_name: str,
) -> dict[str, Any]:
    status_counts: Counter[str] = Counter()
    reason_counts: Counter[str] = Counter()
    total_checks = 0
    total_weight = executable_weight = fallback_weight = 0.0
    failed_cases: list[str] = []
    for report in reports:
        total_checks += int(report.get("check_count", 0))
        total_weight += float(report.get("total_weight", 0.0))
        executable_weight += float(report.get("executable_weight", 0.0))
        fallback_weight += float(report.get("fallback_weight", 0.0))
        status_counts.update(_mapping(report.get("status_counts")))
        reason_counts.update(_mapping(report.get("reason_counts")))
        if not bool(report.get("passed")):
            failed_cases.append(str(report.get("case_id") or ""))
    return {
        "schema_version": "pvr.contract_compilation_gate_batch.v1",
        "policy": policy_name,
        "passed": not failed_cases,
        "case_count": len(reports),
        "failed_case_count": len(failed_cases),
        "failed_cases": failed_cases,
        "check_count": total_checks,
        "total_weight": round(total_weight, 6),
        "executable_weight": round(executable_weight, 6),
        "fallback_weight": round(fallback_weight, 6),
        "executable_weight_coverage": round(executable_weight / total_weight, 6) if total_weight else 0.0,
        "status_counts": dict(sorted(status_counts.items())),
        "reason_counts": dict(reason_counts.most_common()),
    }