Codex
Replace the dataset with the current testing tree and the three UT docs.
d26f22a
Raw History Blame Contribute Delete
12.3 kB
"""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,
),
}