File size: 12,285 Bytes
fd11263
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Execution-family evaluator rules and their static definitions."""

from __future__ import annotations

import fnmatch
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Mapping

from .contracts import (EvaluationContext, EvaluatorDefinition,
                        EvaluatorResult, EvidenceBinding, FrozenParams,
                        LLMJudgeDefinition, LLMJudgeRequest, ScorePolicy,
                        evaluator_result)


@dataclass(frozen=True)
class ExpectedFilesParams(FrozenParams):
    expected_files: tuple[str, ...]


@dataclass(frozen=True)
class DeliverableQualityParams(FrozenParams):
    artifact_paths: tuple[str, ...]
    include_fixture: bool
    max_chars_per_file: int
    max_total_chars: int


def _validate_keys(params: dict[str, Any], allowed: set[str]) -> None:
    if not isinstance(params, dict):
        raise ValueError("evaluator params must be an object")
    unknown = set(params) - allowed
    if unknown:
        raise ValueError(f"unknown evaluator params: {sorted(unknown)}")


def _safe_relative_path(value: Any) -> bool:
    if not isinstance(value, str) or not value or "\x00" in value:
        return False
    normalized = value.replace("\\", "/")
    if normalized.startswith(("/", "~")):
        return False
    if len(normalized) >= 2 and normalized[1] == ":" and normalized[0].isalpha():
        return False
    return all(part not in {"", ".", ".."} for part in normalized.split("/"))


def validate_expected_files(params: dict[str, Any]) -> None:
    _validate_keys(params, {"expected_files"})
    files = params.get("expected_files")
    if not isinstance(files, list) or not files or any(not _safe_relative_path(path) for path in files):
        raise ValueError("expected_files_present requires a non-empty safe relative expected_files list")


def validate_deliverable_quality(params: dict[str, Any]) -> None:
    _validate_keys(params, {"artifact_paths", "include_fixture", "max_chars_per_file", "max_total_chars"})
    paths = params.get("artifact_paths")
    if not isinstance(paths, list) or not paths or any(not _safe_relative_path(path) for path in paths):
        raise ValueError("deliverable_quality requires non-empty safe relative artifact_paths")
    if len(paths) != len(set(paths)):
        raise ValueError("deliverable_quality artifact_paths must be unique")
    if not isinstance(params.get("include_fixture"), bool):
        raise ValueError("deliverable_quality include_fixture must be boolean")
    per_file = params.get("max_chars_per_file")
    total = params.get("max_total_chars")
    if not isinstance(per_file, int) or isinstance(per_file, bool) or per_file < 1:
        raise ValueError("deliverable_quality max_chars_per_file must be a positive integer")
    if not isinstance(total, int) or isinstance(total, bool) or total < 1:
        raise ValueError("deliverable_quality max_total_chars must be a positive integer")
    if total < per_file:
        raise ValueError("deliverable_quality max_total_chars must be >= max_chars_per_file")


def normalize_expected_files_params(params: Mapping[str, Any]) -> ExpectedFilesParams:
    raw = dict(params)
    validate_expected_files(raw)
    return ExpectedFilesParams(tuple(raw["expected_files"]))


def normalize_deliverable_quality_params(params: Mapping[str, Any]) -> DeliverableQualityParams:
    raw = dict(params)
    validate_deliverable_quality(raw)
    return DeliverableQualityParams(
        tuple(raw["artifact_paths"]), bool(raw["include_fixture"]),
        int(raw["max_chars_per_file"]), int(raw["max_total_chars"]),
    )


def _execution(context: EvaluationContext) -> dict[str, Any]:
    if context.artifact.execution is not None:
        return context.artifact.execution.to_dict()
    return dict(context.artifact.metadata)


def expected_files_present(
    context: EvaluationContext, params: ExpectedFilesParams
) -> EvaluatorResult:
    """Check files in the adapter's isolated ai-output workspace."""
    expected_files = list(params.expected_files)
    workspace = _execution(context).get("task_workspace")
    missing: list[str] = []
    if workspace:
        root = (Path(workspace) / "ai-output").resolve()
        actual = [path.relative_to(root).as_posix() for path in root.rglob("*") if path.is_file()]
        for relative in expected_files:
            if relative.startswith("/") or ".." in relative.split("/"):
                raise ValueError(f"expected file escapes ai-output: {relative}")
            if not any(fnmatch.fnmatch(path, relative) for path in actual):
                missing.append(relative)
    else:
        missing = list(expected_files)
    return evaluator_result(
        score=float(not missing), label="pass" if not missing else "fail",
        explanation="all expected files present" if not missing else f"missing={missing}",
        evidence_refs=["metadata.task_workspace", "output.changed_files"],
        metadata={"expected_files": expected_files},
    )


DELIVERABLE_QUALITY_JUDGE = LLMJudgeDefinition(
    prompt_template="""Evaluate only the delivered result for this case.
Pass requires the declared deliverables to be present, internally consistent, grounded in the
case input/fixture, and sufficiently complete to execute the requested work. Partial means useful
work exists but one or more material requirements are unsupported, incomplete, or truncated.
Fail means the deliverables are absent, substantially incorrect, contradictory, or not grounded
in the supplied case evidence. Do not grade process efficiency or infer unread content.

Case task:
${task}

Execution validation:
${validation}

Deliverables:
${deliverables}

Skill testpoints:
${testpoints}

Case fixture:
${fixture}

Final output:
${final_output}

Evidence references:
${evidence_refs}""",
    input_mapping={
        "task": EvidenceBinding("case.input", "text"),
        "validation": EvidenceBinding("execution.validation", "json"),
        "deliverables": EvidenceBinding("execution.deliverables", "json"),
        "testpoints": EvidenceBinding("skill.testpoints", "json"),
        "fixture": EvidenceBinding("case.fixture", "json"),
        "final_output": EvidenceBinding("execution.final_output", "text"),
        "evidence_refs": EvidenceBinding("evidence_refs", "json"),
    },
    response_schema={
        "type": "object", "required": ["label", "reason", "evidence_refs"],
        "additionalProperties": False,
        "properties": {
            "label": {"type": "string", "enum": ["pass", "partial", "fail"]},
            "reason": {"type": "string", "minLength": 1},
            "evidence_refs": {"type": "array", "minItems": 1,
                              "items": {"type": "string"}},
        },
    },
    output_mapping={"label": "label", "reason": "explanation",
                    "evidence_refs": "evidence_refs"},
    score_policy=ScorePolicy(
        label_mapping={"pass": "pass", "partial": "partial", "fail": "fail"},
        score_mapping={"pass": 1.0, "partial": 0.5, "fail": 0.0},
    ),
)


def _bounded_text(path: Path, *, limit: int, remaining: int) -> tuple[dict[str, Any], int, bool]:
    if not path.is_file():
        return {"status": "missing", "content": None}, remaining, False
    data = path.read_bytes()
    if b"\x00" in data:
        return {"status": "binary", "size_bytes": len(data), "content": None}, remaining, False
    try:
        content = data.decode("utf-8")
    except UnicodeDecodeError:
        return {"status": "binary", "size_bytes": len(data), "content": None}, remaining, False
    allowed = min(limit, max(0, remaining))
    selected = content[:allowed]
    truncated = len(selected) < len(content)
    return {
        "status": "truncated" if truncated else "complete",
        "size_bytes": len(data), "content": selected,
    }, remaining - len(selected), truncated


def deliverable_quality(
    context: EvaluationContext, params: DeliverableQualityParams
) -> LLMJudgeRequest:
    """Project only explicitly configured, run-local deliverables for LLM review."""
    artifact = context.artifact
    execution = _execution(context)
    workspace = execution.get("task_workspace")
    root = (Path(str(workspace)) / "ai-output").resolve() if workspace else None
    remaining = int(params.max_total_chars)
    per_file = int(params.max_chars_per_file)
    truncated = False
    deliverables: dict[str, Any] = {}
    for relative in params.artifact_paths:
        target = (root / relative).resolve() if root else None
        if root is None or target is None or not target.is_relative_to(root):
            item = {"status": "missing", "content": None}
        else:
            item, remaining, item_truncated = _bounded_text(
                target, limit=per_file, remaining=remaining
            )
            truncated = truncated or item_truncated
        deliverables[relative] = item

    fixture: dict[str, Any] | None = None
    if params.include_fixture:
        fixture_copy = artifact.metadata.get("fixture_copy")
        input_root = (Path(str(workspace)) / "input").resolve() if workspace else None
        fixture_path = Path(str(fixture_copy)).resolve() if fixture_copy else None
        if (input_root is not None and fixture_path is not None
                and fixture_path.is_relative_to(input_root)):
            fixture, remaining, fixture_truncated = _bounded_text(
                fixture_path, limit=per_file, remaining=remaining
            )
            truncated = truncated or fixture_truncated
        else:
            fixture = {"status": "missing", "content": None}

    if fixture is None:
        fixture = {"status": "omitted_by_policy", "content": None}
    refs = ["case.input", "case.fixture", "execution.final_output", "execution.validation",
            "skill.testpoints", "execution.deliverables"]
    evidence = {
        "case": {"case_id": context.case.case_id, "input": context.case.input},
        "execution": {
            "status": artifact.status,
            "final_output": execution.get("final_output", ""),
            "validation": execution.get("validation", []),
            "deliverables": deliverables,
        },
        "skill": {
            "skill_id": context.skill.skill_id,
            "testpoints": [point.to_dict() for point in context.testpoint_set.test_points],
        },
    }
    evidence["case"]["fixture"] = fixture
    return LLMJudgeRequest(
        evidence=evidence, evidence_refs=tuple(refs),
        projection_truncated=truncated,
    )


EXECUTION_EVALUATORS = {
    "expected_files_present": EvaluatorDefinition(
        evaluator_id="expected_files_present", family="execution",
        result_kind="assessment", expansion="once", rule=expected_files_present,
        scope="skill",
        required_evidence=frozenset({"execution_workspace"}),
        aggregation="mean", direction="maximize", params_type=ExpectedFilesParams,
        normalize_params=normalize_expected_files_params,
        params_schema={"type": "object", "required": ["expected_files"], "additionalProperties": False,
                       "properties": {"expected_files": {"type": "array", "minItems": 1, "items": {"type": "string"}}}},
    ),
    "deliverable_quality": EvaluatorDefinition(
        evaluator_id="deliverable_quality", family="execution",
        result_kind="assessment", expansion="once", rule=deliverable_quality,
        scope="skill",
        version="deliverable-quality-v2",
        required_evidence=frozenset({"execution_workspace"}),
        aggregation="mean", direction="maximize", params_type=DeliverableQualityParams,
        normalize_params=normalize_deliverable_quality_params,
        params_schema={"type": "object", "required": ["artifact_paths", "include_fixture", "max_chars_per_file", "max_total_chars"],
                       "additionalProperties": False, "properties": {
                           "artifact_paths": {"type": "array", "minItems": 1, "items": {"type": "string"}},
                           "include_fixture": {"type": "boolean"},
                           "max_chars_per_file": {"type": "integer", "minimum": 1},
                           "max_total_chars": {"type": "integer", "minimum": 1},
                       }},
        judge=DELIVERABLE_QUALITY_JUDGE,
    ),
}