File size: 16,971 Bytes
b8ea052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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
"""Strongly typed records for the question-first evaluator.

The v1 evaluator placed executable semantics inside a free-form ``params``
dictionary.  V2 makes the normalized predicate, evidence dependencies and
answer provenance first-class records.  Unknown semantics are valid, but they
must be marked ``manual_required`` and can never reach either a deterministic
scorer or an implicit VLM fallback.
"""

from __future__ import annotations

import hashlib
import json
from dataclasses import dataclass, field
from typing import Any, Mapping


SCHEMA_VERSION = "pvr.question_eval.v2"
TERMINAL_EVIDENCE_STATUSES = {"success", "insufficient", "unsupported", "error"}
ANSWER_STATUSES = {"pass", "partial", "fail", "uncertain"}
ANSWER_MODES = {"deterministic", "deterministic_or_vlm", "vlm_required", "manual_only"}
COMPILE_STATUSES = {"executable", "manual_required", "vlm_required"}
DECISION_MODES = {"objective", "manual_only"}
OBJECTIVE_PREDICATE_KINDS = {
    "attribute_object_in_region",
    "change_fraction",
    "count_in_region",
    "source_normalized_clearance",
    "text_match",
}


def _tuple_strings(value: Any) -> tuple[str, ...]:
    if isinstance(value, str):
        return tuple(item.strip() for item in value.split("|") if item.strip())
    if isinstance(value, (list, tuple, set)):
        return tuple(str(item).strip() for item in value if str(item).strip())
    return ()


def _jsonable(value: Any) -> Any:
    if value.__class__.__module__.startswith("numpy"):
        if getattr(value, "ndim", 0) == 0:
            return value.item()
        # Runtime adapters may carry full masks between DAG nodes.  Persist a
        # stable, compact summary rather than megabytes of pixels; visual mask
        # artifacts and source call IDs remain separately auditable.
        return {
            "array_summary": True,
            "shape": [int(item) for item in value.shape],
            "dtype": str(value.dtype),
            "nonzero": int(value.astype(bool).sum()),
        }
    if isinstance(value, tuple):
        return [_jsonable(item) for item in value]
    if isinstance(value, list):
        return [_jsonable(item) for item in value]
    if isinstance(value, dict):
        return {str(key): _jsonable(item) for key, item in value.items()}
    return value


def stable_hash(payload: Mapping[str, Any]) -> str:
    text = json.dumps(_jsonable(dict(payload)), ensure_ascii=False, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(text.encode("utf-8")).hexdigest()


@dataclass(frozen=True)
class QuestionRubric:
    case_id: str
    check_id: str
    question: str
    pass_criteria: str
    partial_criteria: str
    fail_criteria: str
    role: str
    dimension: str
    weight: float
    hard_fail: bool = False

    def __post_init__(self) -> None:
        if not self.case_id or not self.check_id:
            raise ValueError("question rubric requires case_id and check_id")
        if not self.question.strip():
            raise ValueError(f"question rubric {self.check_id!r} has no question")
        if self.role not in {"reward", "penalty"}:
            raise ValueError(f"invalid rubric role: {self.role}")
        if self.weight < 0:
            raise ValueError("rubric weight must be non-negative")

    @classmethod
    def from_contract_item(cls, case_id: str, item: Mapping[str, Any]) -> "QuestionRubric":
        role = "penalty" if str(item.get("role", "")).lower() == "penalty" or "max_deduct" in item else "reward"
        weight_key = "max_deduct" if role == "penalty" else "points"
        return cls(
            case_id=case_id,
            check_id=str(item.get("id") or item.get("check_id") or ""),
            question=str(item.get("question") or item.get("description") or ""),
            pass_criteria=str(item.get("pass_criteria") or ""),
            partial_criteria=str(item.get("partial_criteria") or ""),
            fail_criteria=str(item.get("fail_criteria") or ""),
            role=role,
            dimension=str(item.get("dimension") or ("penalty" if role == "penalty" else "target_completion")),
            weight=float(item.get(weight_key, item.get("weight", 0.0)) or 0.0),
            hard_fail=bool(item.get("hard_fail", False)),
        )

    def to_dict(self) -> dict[str, Any]:
        return _jsonable(self.__dict__)


@dataclass(frozen=True)
class PredicateSpec:
    """Finite, executable predicate semantics.

    ``kind`` belongs to a small registry. ``metric`` names the derived fact
    consumed by the predicate. Bands are explicit numeric intervals such as
    ``{"pass": {"max": 0}, "partial": {"min": 1, "max": 2}}``.
    A semantic VLM predicate has ``deterministic=False`` and no executable
    bands; its frozen rubric remains the source of truth.
    """

    kind: str
    metric: str = ""
    subject_queries: tuple[str, ...] = ()
    region_ids: tuple[str, ...] = ()
    bands: dict[str, dict[str, float | None]] = field(default_factory=dict)
    parameters: dict[str, Any] = field(default_factory=dict)
    deterministic: bool = False
    source_rule_type: str = ""

    def __post_init__(self) -> None:
        if not self.kind:
            raise ValueError("predicate kind is required")
        if self.deterministic:
            if not self.metric:
                raise ValueError("deterministic predicate requires a metric")
            if "pass" not in self.bands or "fail" not in self.bands:
                raise ValueError("deterministic predicate requires pass and fail bands")
        for status, band in self.bands.items():
            if status not in {"pass", "partial", "fail"}:
                raise ValueError(f"invalid predicate band: {status}")
            low, high = band.get("min"), band.get("max")
            if low is not None and high is not None and float(low) > float(high):
                raise ValueError(f"invalid band interval for {status}")

    def to_dict(self) -> dict[str, Any]:
        return _jsonable(self.__dict__)


@dataclass(frozen=True)
class DecisionSpec:
    """Contract-owned instructions for turning evidence into one answer.

    Free-form ``decision_rule.type`` names describe intent but are not an
    executable interface.  This finite record either names a validated
    objective predicate or explicitly sends the question to human review.
    """

    mode: str
    predicate: PredicateSpec
    subject_region_ids: tuple[str, ...] = ()
    target_region_ids: tuple[str, ...] = ()
    required_tools: tuple[str, ...] = ()
    manual_reasons: tuple[str, ...] = ()
    schema_version: str = "pvr.decision_spec.v1"

    def __post_init__(self) -> None:
        if self.mode not in DECISION_MODES:
            raise ValueError(f"invalid decision mode: {self.mode}")
        if self.mode == "objective" and not self.predicate.deterministic:
            raise ValueError("objective decision spec requires deterministic predicate")
        if self.mode == "objective" and self.predicate.kind not in OBJECTIVE_PREDICATE_KINDS:
            raise ValueError(f"unsupported objective predicate kind: {self.predicate.kind}")
        if self.mode == "manual_only" and self.predicate.deterministic:
            raise ValueError("manual-only decision spec cannot carry deterministic predicate")
        overlap = set(self.subject_region_ids) & set(self.target_region_ids)
        if overlap:
            raise ValueError(f"subject and target regions must be disjoint: {sorted(overlap)}")
        if self.mode == "objective" and any("vlm" in tool.lower() for tool in self.required_tools):
            raise ValueError("objective decision spec cannot require a VLM tool")
        if self.mode == "objective" and set(self.predicate.region_ids) != set(self.target_region_ids):
            raise ValueError("objective predicate regions must exactly match target regions")

    @classmethod
    def from_mapping(cls, value: Mapping[str, Any]) -> "DecisionSpec":
        predicate_value = value.get("predicate") if isinstance(value.get("predicate"), Mapping) else {}
        evidence = value.get("evidence") if isinstance(value.get("evidence"), Mapping) else {}
        predicate = PredicateSpec(
            kind=str(predicate_value.get("kind") or "manual_review"),
            metric=str(predicate_value.get("metric") or ""),
            subject_queries=_tuple_strings(predicate_value.get("subject_queries")),
            region_ids=_tuple_strings(predicate_value.get("region_ids") or evidence.get("target_region_ids")),
            bands={
                str(status): {str(key): item for key, item in dict(band).items()}
                for status, band in dict(predicate_value.get("bands") or {}).items()
                if isinstance(band, Mapping)
            },
            parameters=dict(predicate_value.get("parameters") or {}),
            deterministic=bool(predicate_value.get("deterministic", value.get("mode") == "objective")),
            source_rule_type=str(predicate_value.get("source_rule_type") or "decision_spec_v1"),
        )
        return cls(
            mode=str(value.get("mode") or "manual_only"),
            predicate=predicate,
            subject_region_ids=_tuple_strings(evidence.get("subject_region_ids")),
            target_region_ids=_tuple_strings(evidence.get("target_region_ids") or predicate.region_ids),
            required_tools=_tuple_strings(evidence.get("required_tools")),
            manual_reasons=_tuple_strings(value.get("manual_reasons")),
            schema_version=str(value.get("schema_version") or "pvr.decision_spec.v1"),
        )

    def to_dict(self) -> dict[str, Any]:
        return {
            "schema_version": self.schema_version,
            "mode": self.mode,
            "predicate": self.predicate.to_dict(),
            "evidence": {
                "subject_region_ids": list(self.subject_region_ids),
                "target_region_ids": list(self.target_region_ids),
                "required_tools": list(self.required_tools),
            },
            "manual_reasons": list(self.manual_reasons),
        }


@dataclass(frozen=True)
class EvidenceNodeSpec:
    node_id: str
    operation: str
    tool: str
    image_roles: tuple[str, ...]
    depends_on: tuple[str, ...] = ()
    region_ids: tuple[str, ...] = ()
    inputs: tuple[str, ...] = ()
    required: bool = True
    parameters: dict[str, Any] = field(default_factory=dict)

    def __post_init__(self) -> None:
        if not self.node_id or not self.operation or not self.tool:
            raise ValueError("evidence node requires id, operation and tool")
        if self.node_id in self.depends_on:
            raise ValueError(f"evidence node {self.node_id!r} depends on itself")

    def to_dict(self) -> dict[str, Any]:
        return _jsonable(self.__dict__)


@dataclass(frozen=True)
class EvalProcedure:
    rubric: QuestionRubric
    predicate: PredicateSpec
    nodes: tuple[EvidenceNodeSpec, ...]
    answer_mode: str
    compile_status: str
    compile_reasons: tuple[str, ...] = ()
    gt_policy: str = "not_allowed"
    source_decision_rule: dict[str, Any] = field(default_factory=dict)
    decision_spec: DecisionSpec | None = None
    schema_version: str = SCHEMA_VERSION

    def __post_init__(self) -> None:
        if self.answer_mode not in ANSWER_MODES:
            raise ValueError(f"invalid answer mode: {self.answer_mode}")
        if self.compile_status not in COMPILE_STATUSES:
            raise ValueError(f"invalid compile status: {self.compile_status}")
        node_ids = [node.node_id for node in self.nodes]
        if len(node_ids) != len(set(node_ids)):
            raise ValueError("duplicate evidence node ids")
        known = set(node_ids)
        for node in self.nodes:
            missing = set(node.depends_on) - known
            if missing:
                raise ValueError(f"node {node.node_id!r} has unknown dependencies: {sorted(missing)}")
        if self.predicate.deterministic and self.answer_mode == "vlm_required":
            raise ValueError("deterministic predicate cannot require VLM-only answering")
        if self.answer_mode == "manual_only" and self.compile_status != "manual_required":
            raise ValueError("manual-only answer mode requires manual_required compile status")
        if self.answer_mode == "manual_only" and self.predicate.deterministic:
            raise ValueError("manual-only procedure cannot carry deterministic predicate")

    @property
    def procedure_hash(self) -> str:
        return stable_hash(self.to_dict(include_hash=False))

    def to_dict(self, *, include_hash: bool = True) -> dict[str, Any]:
        payload = {
            "schema_version": self.schema_version,
            "rubric": self.rubric.to_dict(),
            "predicate": self.predicate.to_dict(),
            "nodes": [node.to_dict() for node in self.nodes],
            "answer_mode": self.answer_mode,
            "compile_status": self.compile_status,
            "compile_reasons": list(self.compile_reasons),
            "gt_policy": self.gt_policy,
            "source_decision_rule": _jsonable(self.source_decision_rule),
            "decision_spec": self.decision_spec.to_dict() if self.decision_spec is not None else None,
        }
        if include_hash:
            payload["procedure_hash"] = stable_hash(payload)
        return payload


@dataclass(frozen=True)
class QuestionSpec(EvalProcedure):
    """Frozen, executable specification for one audited atomic question.

    ``EvalProcedure`` remains as the compatibility/base type used by DAG
    utilities; compilers emit this more explicit public type.
    """

    pass


@dataclass(frozen=True)
class EvidenceNodeResult:
    node_id: str
    status: str
    call_ids: tuple[str, ...] = ()
    facts: dict[str, Any] = field(default_factory=dict)
    artifacts: tuple[dict[str, Any], ...] = ()
    limitations: tuple[str, ...] = ()

    def __post_init__(self) -> None:
        if self.status not in TERMINAL_EVIDENCE_STATUSES:
            raise ValueError(f"invalid evidence status: {self.status}")
        if self.status == "success" and not self.call_ids and self.node_id not in {"derive_facts", "render_overlay"}:
            raise ValueError(f"successful evidence node {self.node_id!r} requires provenance call_ids")

    def to_dict(self) -> dict[str, Any]:
        return _jsonable(self.__dict__)


@dataclass(frozen=True)
class EvidencePacket:
    case_id: str
    check_id: str
    procedure_hash: str
    nodes: tuple[EvidenceNodeResult, ...]
    derived_facts: dict[str, Any]
    visual_artifacts: tuple[dict[str, Any], ...] = ()
    status: str = "insufficient"
    reasons: tuple[str, ...] = ()
    schema_version: str = "pvr.evidence_packet.v2"

    def __post_init__(self) -> None:
        if self.status not in TERMINAL_EVIDENCE_STATUSES:
            raise ValueError(f"invalid evidence packet status: {self.status}")
        ids = [node.node_id for node in self.nodes]
        if len(ids) != len(set(ids)):
            raise ValueError("duplicate node results in evidence packet")

    @property
    def successful_call_ids(self) -> tuple[str, ...]:
        values = {call_id for node in self.nodes if node.status == "success" for call_id in node.call_ids if call_id}
        return tuple(sorted(values))

    @property
    def packet_hash(self) -> str:
        return stable_hash(self.to_dict(include_hash=False))

    def to_dict(self, *, include_hash: bool = True) -> dict[str, Any]:
        payload = {
            "schema_version": self.schema_version,
            "case_id": self.case_id,
            "check_id": self.check_id,
            "procedure_hash": self.procedure_hash,
            "nodes": [node.to_dict() for node in self.nodes],
            "derived_facts": _jsonable(self.derived_facts),
            "visual_artifacts": [_jsonable(item) for item in self.visual_artifacts],
            "status": self.status,
            "reasons": list(self.reasons),
        }
        if include_hash:
            payload["packet_hash"] = stable_hash(payload)
        return payload


@dataclass(frozen=True)
class AnswerRecord:
    case_id: str
    check_id: str
    status: str
    score: float
    confidence: float
    answer_source: str
    evidence_packet_hash: str
    cited_call_ids: tuple[str, ...]
    rationale: str
    formal_eligible: bool
    reasons: tuple[str, ...] = ()
    schema_version: str = "pvr.answer_record.v2"

    def __post_init__(self) -> None:
        if self.status not in ANSWER_STATUSES:
            raise ValueError(f"invalid answer status: {self.status}")
        if not 0.0 <= self.score <= 1.0 or not 0.0 <= self.confidence <= 1.0:
            raise ValueError("answer score and confidence must be in [0, 1]")
        if self.formal_eligible and (self.status == "uncertain" or not self.cited_call_ids):
            raise ValueError("formal answer requires a resolved status and cited tool calls")

    def to_dict(self) -> dict[str, Any]:
        return _jsonable(self.__dict__)