Codex
Replace the dataset with the current testing tree and the three UT docs.
d26f22a
Raw History Blame Contribute Delete
33.8 kB
"""UT-P001 through UT-P016.
Script checks compare shard fields with the final YAML and the rendered
Markdown tables. P004, P006, and P007 ask the model only about meaning.
"""
from __future__ import annotations
import re
import subprocess
import tempfile
from pathlib import Path
from typing import Any
from .contracts import (EmptyParams, EvaluationContext, EvaluatorDefinition,
EvaluatorResult, EvidenceBinding, LLMJudgeDefinition,
LLMJudgeRequest, ScorePolicy, assessment_result,
incomplete_result, measurement_result)
from .ut_mechanical import _manifest, _path_from_manifest, _task_dir
_PASS_FAIL = ScorePolicy(
label_mapping={"pass": "pass", "partial": "partial", "fail": "fail"},
score_mapping={"pass": 1.0, "partial": 0.5, "fail": 0.0},
)
_JUDGE_SCHEMA = {
"type": "object", "additionalProperties": False,
"required": ["label", "reason", "evidence_refs"],
"properties": {
"label": {"type": "string", "enum": ["pass", "partial", "fail"]},
"reason": {"type": "string", "minLength": 1},
"evidence_refs": {"type": "array", "minItems": 1, "items": {"type": "string"}},
},
}
_METHODS = (
("register_test", "寄存器测试"),
("memory_test", "存储器测试"),
("performance_test", "性能验证"),
("formal_verification", "形式验证"),
("clock_reset_low_power", "时钟复位/低功耗"),
)
_OPTIONAL = {"interface": "接口", "scenario": "场景", "exception": "异常"}
def _norm(value: Any) -> str:
if isinstance(value, list):
return ", ".join(_norm(item) for item in value)
if value is None:
return ""
return re.sub(r"\s+", " ", str(value)).strip()
def _load_yaml(path: Path) -> dict[str, Any] | None:
try:
import yaml
except ImportError:
return None
try:
data = yaml.safe_load(path.read_text(encoding="utf-8"))
except (OSError, yaml.YAMLError):
return None
return data if isinstance(data, dict) else None
def _shards(root: Path) -> list[dict[str, Any]]:
found = []
for path in sorted(root.rglob("*.yaml")):
if ".payloads" in path.parts:
continue
data = _load_yaml(path)
if data is None or not isinstance(data.get("stage"), str) or not isinstance(data.get("payload"), dict):
continue
match = re.search(r"stage-(\d+)", data["stage"])
if match is None:
continue
found.append({
"path": path, "stage_no": int(match.group(1)),
"directory": path.parent.name, "payload": data["payload"],
})
return found
def _merge(payloads: list[dict[str, Any]]) -> dict[str, Any]:
merged: dict[str, Any] = {}
for payload in payloads:
for key, value in payload.items():
if key == "shard_kind":
continue
current = merged.get(key)
if isinstance(value, list):
merged[key] = [*(current if isinstance(current, list) else []), *value]
elif isinstance(value, dict) and isinstance(current, dict):
merged[key] = _merge([current, value])
else:
merged[key] = value
return merged
def _docs(context: EvaluationContext) -> dict[str, Any] | None:
task_dir = _task_dir(context)
manifest = _manifest(task_dir) if task_dir is not None else None
if task_dir is None or manifest is None:
return None
output = _path_from_manifest(task_dir, manifest, "output_dir")
if output is None or not output.is_dir():
return None
identity = manifest.get("identity") if isinstance(manifest.get("identity"), dict) else {}
dut = identity.get("dut_name") if isinstance(identity.get("dut_name"), str) else ""
plan_yaml = output / f"V_{dut}_verification_plan.yaml" if dut else None
plan_md = output / f"V_{dut}_verification_plan.md" if dut else None
if dut == "" or (plan_yaml is not None and not plan_yaml.is_file() and plan_md is not None and not plan_md.is_file()):
matches = sorted(output.glob("V_*_verification_plan.yaml"))
if len(matches) == 1:
plan_yaml = matches[0]
plan_md = matches[0].with_suffix(".md")
spec = _path_from_manifest(task_dir, manifest, "task_as_path")
return {
"output": output,
"dut": dut,
"spec": spec,
"shards": _shards(output / ".ut-testplan-gen"),
"tp_yaml": output / "testpoint-decomposition.yaml",
"tp_md": output / "testpoint-decomposition.md",
"plan_yaml": plan_yaml,
"plan_md": plan_md,
"plan_validation": None if plan_yaml is None else plan_yaml.with_name(plan_yaml.stem + ".validation.json"),
"skill_root": Path(context.skill.root) if context.skill.root else None,
}
def _stage(docs: dict[str, Any], number: int) -> dict[str, Any]:
return _merge([item["payload"] for item in docs["shards"] if item["stage_no"] == number])
def _read(path: Path | None) -> dict[str, Any] | None:
if path is None or not path.is_file():
return None
return _load_yaml(path)
def _text(path: Path | None) -> str:
if path is None or not path.is_file():
return ""
return path.read_text(encoding="utf-8", errors="replace")
def _section(text: str, heading: str) -> str:
lines = text.splitlines()
level = len(heading) - len(heading.lstrip("#"))
start = next((index + 1 for index, line in enumerate(lines) if line.strip().startswith(heading)), None)
if start is None:
return ""
end = next((index for index in range(start, len(lines))
if re.match(rf"^#{{1,{level}}}\s", lines[index])), len(lines))
return "\n".join(lines[start:end])
def _rows(section: str) -> list[list[str]]:
rows = []
for line in section.splitlines():
stripped = line.strip()
if not stripped.startswith("|"):
continue
cells = [_norm(cell) for cell in stripped.strip("|").split("|")]
if cells and all(re.fullmatch(r":?-{3,}:?", cell.replace(" ", "")) or cell == "" for cell in cells):
continue
if cells and cells[0] in {"编号", "接口/Feature", "专项", "covergroup", "用例名称", "机制", "组件"}:
continue
rows.append(cells)
return rows
def _contains(haystack: str, needle: Any) -> bool:
text = _norm(needle)
return bool(text) and text in _norm(haystack)
def _unavailable(metric: str, explanation: str) -> EvaluatorResult:
return measurement_result(
value=None, metric=metric, unit="check", status="unavailable", explanation=explanation,
)
def _check(metric: str, value: dict[str, bool], explanation: str) -> EvaluatorResult:
return measurement_result(
value=value, metric=metric, unit="check", score=float(all(value.values())),
explanation=explanation,
)
def _fail(explanation: str) -> EvaluatorResult:
return assessment_result(score=0.0, label="fail", explanation=explanation)
def _items(node: Any, key: str) -> list[dict[str, Any]]:
if isinstance(node, dict):
value = node.get(key)
if isinstance(value, list):
return [item for item in value if isinstance(item, dict)]
if isinstance(value, dict):
found = []
for child in value.values():
if isinstance(child, list):
found.extend(item for item in child if isinstance(item, dict))
return found
return []
def render_markdown(skill_root: Path | None, template_name: str, data_path: Path) -> str | None:
"""Render one YAML document with the Skill template. None means it did not run."""
if skill_root is None:
return None
script = skill_root / "scripts" / "render_template.py"
template = skill_root / "reference" / "templates" / template_name
if not script.is_file() or not template.is_file() or not data_path.is_file():
return None
with tempfile.TemporaryDirectory() as directory:
output = Path(directory) / "rendered.md"
try:
completed = subprocess.run(
["python3", str(script), "--template", str(template), "--data", str(data_path),
"--output", str(output)],
text=True, capture_output=True, timeout=60, check=False,
)
except (OSError, subprocess.TimeoutExpired):
return None
if completed.returncode != 0 or not output.is_file():
return None
return output.read_text(encoding="utf-8", errors="replace")
def ut_p001_deliverables(context: EvaluationContext, params: EmptyParams) -> EvaluatorResult:
del params
docs = _docs(context)
if docs is None:
return _unavailable("UT-P001", "testplan 输出目录不存在")
output = docs["output"]
dut = docs["dut"]
names = [
"testpoint-decomposition.yaml", "testpoint-decomposition.md", "testpoint-decomposition.html",
f"V_{dut}_verification_plan.yaml", f"V_{dut}_verification_plan.md", f"V_{dut}_verification_plan.html",
]
value = {name: (output / name).is_file() for name in names}
return _check("UT-P001", value, "六个交付文件")
def ut_p002_stage_dirs(context: EvaluationContext, params: EmptyParams) -> EvaluatorResult:
del params
docs = _docs(context)
if docs is None or not docs["shards"]:
return _unavailable("UT-P002", "没有分片")
present = {item["stage_no"] for item in docs["shards"]}
placed = all(
item["directory"] == ("testpoints" if item["stage_no"] <= 5 else "verification-plan")
for item in docs["shards"]
)
value = {"stages": present >= set(range(1, 13)), "placed": placed}
return _check("UT-P002", value, "Stage 1~5 在 testpoints,6~12 在 verification-plan")
def ut_p003_features(context: EvaluationContext, params: EmptyParams) -> EvaluatorResult:
del params
docs = _docs(context)
report = _read(docs["tp_yaml"]) if docs else None
if docs is None or report is None:
return _unavailable("UT-P003", "测试点 YAML 不存在")
shards = _items(_stage(docs, 1), "features")
final = _items(report, "features")
md = _text(docs["tp_md"])
same = {(item.get("id"), item.get("parent_id")) for item in shards} == {
(item.get("id"), item.get("parent_id")) for item in final
}
listed = all(_contains(md, item.get("id")) for item in shards) if shards else False
return _check("UT-P003", {"records": same and listed}, "Feature 与 Sub Feature 的编号和数量")
def _testpoints(merged: dict[str, Any], category: str) -> list[dict[str, Any]]:
groups = merged.get("testpoints")
if not isinstance(groups, dict):
return []
return [item for item in groups.get(category) or [] if isinstance(item, dict)]
def ut_p004_testpoint_meaning(context: EvaluationContext, params: EmptyParams) -> EvaluatorResult | LLMJudgeRequest:
del params
docs = _docs(context)
if docs is None or docs["spec"] is None or not docs["spec"].is_file():
return incomplete_result("没有 Spec,无法判断测试点含义")
grouped = {name: _testpoints(_stage(docs, 2), name) for name in ("functional", "structural", "performance")}
if any(not items for items in grouped.values()):
return _fail("功能、结构、性能三类测试点不齐全")
compact = {
name: [{"id": item.get("id"), "feature": item.get("feature"), "testpoint": item.get("testpoint"),
"source": item.get("source")} for item in items]
for name, items in grouped.items()
}
return LLMJudgeRequest(
evidence={
"spec_path": str(docs["spec"]),
"spec": _text(docs["spec"])[:8000],
"testpoint_source": "ut/ut-testplan-gen/.ut-testplan-gen/testpoints 下 stage-02-standard-testpoints 分片",
"testpoints": compact,
},
evidence_refs=("spec", "testpoints"),
projection_truncated=len(_text(docs["spec"])) > 8000,
)
def ut_p005_testcase_fields(context: EvaluationContext, params: EmptyParams) -> EvaluatorResult:
del params
docs = _docs(context)
if docs is None:
return _unavailable("UT-P005", "testplan 输出目录不存在")
cases = _items(_stage(docs, 3), "testcases") + _items(_stage(docs, 4), "testcases")
md = _text(docs["tp_md"])
if not cases or not md:
return _unavailable("UT-P005", "用例或测试点 MD 不存在")
present = []
for case in cases:
steps = case.get("steps") if isinstance(case.get("steps"), list) else []
checks = case.get("checks") if isinstance(case.get("checks"), list) else []
completion = case.get("completion") if isinstance(case.get("completion"), dict) else {}
present.append(
_contains(md, case.get("logical_name"))
and all(_contains(md, step.get("action")) for step in steps if isinstance(step, dict))
and all(_contains(md, check.get("pass_criteria")) for check in checks if isinstance(check, dict))
and _contains(md, completion.get("drain_condition"))
)
return _check("UT-P005", {"fields": all(present)}, "用例步骤、预期和完成条件")
def ut_p006_optional_categories(context: EvaluationContext, params: EmptyParams) -> EvaluatorResult | LLMJudgeRequest:
del params
docs = _docs(context)
if docs is None or docs["spec"] is None or not docs["spec"].is_file():
return incomplete_result("没有 Spec,无法判断可选测试点类别")
merged = _stage(docs, 4)
skipped = _norm(merged.get("skipped_sections"))
grouped = {name: _testpoints(merged, name) for name in _OPTIONAL}
missing = [
label for name, label in _OPTIONAL.items()
if not grouped[name] and label not in skipped
]
if missing:
return _fail("接口、场景或异常既没有分片,也没有跳过记录")
compact = {
name: [{"id": item.get("id"), "testpoint": item.get("testpoint"), "source": item.get("source")}
for item in items]
for name, items in grouped.items()
}
return LLMJudgeRequest(
evidence={
"spec_path": str(docs["spec"]),
"spec": _text(docs["spec"])[:8000],
"optional_source": "ut/ut-testplan-gen/.ut-testplan-gen/testpoints 下 stage-04-optional-sections 分片",
"testpoints": compact,
"skipped": skipped or "无",
},
evidence_refs=("spec", "testpoints", "skipped"),
)
def ut_p007_dispositions(context: EvaluationContext, params: EmptyParams) -> EvaluatorResult | LLMJudgeRequest:
del params
docs = _docs(context)
if docs is None:
return incomplete_result("testplan 输出目录不存在")
closure = _stage(docs, 5)
updates = closure.get("checklist_updates") if isinstance(closure.get("checklist_updates"), dict) else {}
dispositions = [item for item in updates.get("item_dispositions") or [] if isinstance(item, dict)]
sources = updates.get("applied_rag_sources") or []
if not dispositions or not sources or any(not item.get("reason") for item in dispositions):
return _fail("closure、处置理由或 RAG 来源不完整")
return LLMJudgeRequest(
evidence={
"closure_source": "ut/ut-testplan-gen/.ut-testplan-gen/testpoints 下 stage-05-closure 分片",
"dispositions": {"items": dispositions, "sources": sources},
},
evidence_refs=("dispositions",),
)
def _plan_section(docs: dict[str, Any], heading: str) -> str:
return _section(_text(docs["plan_md"]), heading)
def ut_p008_architecture(context: EvaluationContext, params: EmptyParams) -> EvaluatorResult:
del params
docs = _docs(context)
if docs is None:
return _unavailable("UT-P008", "testplan 输出目录不存在")
merged = _stage(docs, 6)
strategy = _plan_section(docs, "## 0.")
architecture = _plan_section(docs, "## 1.")
info = merged.get("file_info") if isinstance(merged.get("file_info"), dict) else {}
baseline = merged.get("baseline_strategy") if isinstance(merged.get("baseline_strategy"), dict) else {}
tb = merged.get("tb_architecture") if isinstance(merged.get("tb_architecture"), dict) else {}
finals = [item.get("final") for item in baseline.values() if isinstance(item, dict)]
names = [item.get("name") for item in tb.get("interfaces") or [] if isinstance(item, dict)]
value = {
"file_info": _contains(_text(docs["plan_md"]), info.get("design_name")),
"strategy": bool(finals) and all(_contains(strategy, item) for item in finals),
"architecture": bool(names) and all(_contains(architecture, item) for item in names),
}
return _check("UT-P008", value, "文件信息、策略和架构")
def ut_p009_stimulus_checking(context: EvaluationContext, params: EmptyParams) -> EvaluatorResult:
del params
docs = _docs(context)
if docs is None:
return _unavailable("UT-P009", "testplan 输出目录不存在")
requirements = _stage(docs, 7).get("stimulus_checking_requirements")
requirements = requirements if isinstance(requirements, dict) else {}
stimulus = requirements.get("stimulus_requirements") or []
checking = requirements.get("checking_requirements") or []
stimulus_rows = {
(_norm(item.get("interface_or_feature")), _norm(item.get("stimulus_content")),
_norm(item.get("randomization_range")), _norm(item.get("backpressure_timing")),
_norm(item.get("source")))
for item in stimulus if isinstance(item, dict)
}
checking_rows = {
(_norm(item.get("interface_or_feature")), _norm(item.get("check_target")),
_norm(item.get("check_method")), _norm(item.get("order_or_match_rule")),
_norm(item.get("pass_fail_criteria")), _norm(item.get("source")))
for item in checking if isinstance(item, dict)
}
found_stimulus = {tuple(row[:5]) for row in _rows(_plan_section(docs, "### 2.1")) if len(row) >= 5}
found_checking = {tuple(row[:6]) for row in _rows(_plan_section(docs, "### 2.2")) if len(row) >= 6}
if not stimulus_rows or not checking_rows:
return _unavailable("UT-P009", "激励或检查分片不存在")
return _check("UT-P009", {
"stimulus": stimulus_rows <= found_stimulus,
"checking": checking_rows <= found_checking,
}, "激励和检查条目")
def ut_p010_difficulties(context: EvaluationContext, params: EmptyParams) -> EvaluatorResult:
del params
docs = _docs(context)
if docs is None:
return _unavailable("UT-P010", "testplan 输出目录不存在")
items = _items(_stage(docs, 8), "difficulties_countermeasures")
if not items:
return _unavailable("UT-P010", "没有难点分片")
found = {row[0]: row[1:6] for row in _rows(_plan_section(docs, "## 3.")) if len(row) >= 6}
matched = all(
found.get(_norm(item.get("id"))) == [
_norm(item.get("difficulty")), _norm(item.get("risk")), _norm(item.get("countermeasure")),
_norm(item.get("components")), _norm(item.get("source")),
]
for item in items
)
return _check("UT-P010", {"rows": matched and len(found) == len(items)}, "难点和对策表格")
def ut_p011_special_methods(context: EvaluationContext, params: EmptyParams) -> EvaluatorResult:
del params
docs = _docs(context)
if docs is None:
return _unavailable("UT-P011", "testplan 输出目录不存在")
methods = _stage(docs, 9).get("special_methods")
if not isinstance(methods, dict):
return _unavailable("UT-P011", "没有专项方法分片")
found = {row[0]: row[1:3] for row in _rows(_plan_section(docs, "## 4.")) if len(row) >= 3}
matched = True
for key, label in _METHODS:
item = methods.get(key)
if not isinstance(item, dict):
matched = False
continue
expected = ["Y" if item.get("applicable") else "N", _norm(item.get("method"))]
matched = matched and found.get(label) == expected
return _check("UT-P011", {"rows": matched}, "专项方法表格")
def ut_p012_covergroups(context: EvaluationContext, params: EmptyParams) -> EvaluatorResult:
del params
docs = _docs(context)
if docs is None:
return _unavailable("UT-P012", "testplan 输出目录不存在")
groups = _items(_stage(docs, 10).get("coverage_model"), "covergroups")
if not groups:
return _unavailable("UT-P012", "没有 covergroup 分片")
section = _plan_section(docs, "## 5.")
shaped = []
for group in groups:
points = group.get("coverpoints") if isinstance(group.get("coverpoints"), list) else []
points_ok = bool(points) and all(
isinstance(point, dict) and point.get("bins") and point.get("goal") for point in points
)
shaped.append(bool(group.get("sample_event")) and (points_ok or bool(group.get("coverpoints_bins")))
and _contains(section, group.get("name")))
return _check("UT-P012", {"functional": all(shaped)}, "功能覆盖的采样、bin 和 goal")
def ut_p013_components(context: EvaluationContext, params: EmptyParams) -> EvaluatorResult:
del params
docs = _docs(context)
if docs is None:
return _unavailable("UT-P013", "testplan 输出目录不存在")
design = _stage(docs, 11).get("component_design")
design = design if isinstance(design, dict) else {}
section = _plan_section(docs, "## 6.")
model = design.get("reference_model") if isinstance(design.get("reference_model"), dict) else {}
board = design.get("scoreboard") if isinstance(design.get("scoreboard"), dict) else {}
drivers = [item for item in design.get("drivers_monitors") or [] if isinstance(item, dict)]
assertions = [item for item in design.get("assertions") or [] if isinstance(item, dict)]
timeouts = [item for item in design.get("timeout_protection") or [] if isinstance(item, dict)]
names = [item.get("component") for item in drivers] + [item.get("name") for item in assertions]
names += [item.get("mechanism") for item in timeouts]
value = {
"reference_model": bool(model.get("algorithm")) and _contains(section, "Reference Model"),
"scoreboard": bool(board.get("compare_fields")) and _contains(section, "Scoreboard"),
"drivers_monitors": bool(drivers) and all(_contains(section, name) for name in names if name),
"assertions": bool(assertions),
"timeout_protection": bool(timeouts),
}
return _check("UT-P013", value, "组件和保护机制")
def ut_p014_plan_closure(context: EvaluationContext, params: EmptyParams) -> EvaluatorResult:
del params
docs = _docs(context)
plan = _read(docs["plan_yaml"]) if docs else None
if docs is None or plan is None:
return _unavailable("UT-P014", "验证计划 YAML 不存在")
validation = plan.get("checklist_validation") if isinstance(plan.get("checklist_validation"), dict) else {}
summary = validation.get("summary") if isinstance(validation.get("summary"), list) else []
section = _plan_section(docs, "## 7.")
names = [_norm(item.get("checklist")) for item in summary if isinstance(item, dict)]
value = {
"summary": bool(names) and all(_contains(section, name) for name in names),
"plan_summary": isinstance(plan.get("plan_summary"), dict),
"validation_file": bool(docs["plan_validation"] and docs["plan_validation"].is_file()),
}
return _check("UT-P014", value, "checklist 和方案汇总")
def _same_render(docs: dict[str, Any], template_name: str, data_path: Path | None, actual: Path | None) -> bool | None:
if data_path is None or actual is None or not data_path.is_file() or not actual.is_file():
return None
rendered = render_markdown(docs["skill_root"], template_name, data_path)
if rendered is None:
return None
return _norm(rendered) == _norm(_text(actual))
def ut_p015_template(context: EvaluationContext, params: EmptyParams) -> EvaluatorResult:
del params
docs = _docs(context)
if docs is None:
return _unavailable("UT-P015", "testplan 输出目录不存在")
pair = {
"testpoint": _same_render(docs, "testpoint_report.md.j2", docs["tp_yaml"], docs["tp_md"]),
"plan": _same_render(docs, "verification_plan.md.j2", docs["plan_yaml"], docs["plan_md"]),
}
if any(item is None for item in pair.values()):
return _unavailable("UT-P015", "模板没有渲染出来")
return _check("UT-P015", {key: bool(value) for key, value in pair.items()}, "模板重渲染与现有 MD")
def _id_set(items: list[dict[str, Any]], key: str) -> set[str]:
return {_norm(item.get(key)) for item in items if _norm(item.get(key))}
def ut_p016_traceability(context: EvaluationContext, params: EmptyParams) -> EvaluatorResult:
del params
docs = _docs(context)
report = _read(docs["tp_yaml"]) if docs else None
plan = _read(docs["plan_yaml"]) if docs else None
if docs is None or report is None or plan is None:
return _unavailable("UT-P016", "最终 YAML 不存在")
expected_features = _id_set(_items(_stage(docs, 1), "features"), "id")
actual_features = _id_set(_items(report, "features"), "id")
expected_points = set()
actual_points = set()
for category in ("functional", "structural", "performance", *_OPTIONAL):
expected_points |= _id_set(_testpoints(_stage(docs, 2), category) + _testpoints(_stage(docs, 4), category), "id")
actual_points |= _id_set(_testpoints(report, category), "id")
expected_cases = _id_set(_items(_stage(docs, 3), "testcases") + _items(_stage(docs, 4), "testcases"), "logical_name")
actual_cases = _id_set(_items(report, "testcases"), "logical_name")
expected_difficulty = _id_set(_items(_stage(docs, 8), "difficulties_countermeasures"), "id")
actual_difficulty = _id_set(_items(plan, "difficulties_countermeasures"), "id")
rendered = [
_same_render(docs, "testpoint_report.md.j2", docs["tp_yaml"], docs["tp_md"]),
_same_render(docs, "verification_plan.md.j2", docs["plan_yaml"], docs["plan_md"]),
]
if any(item is None for item in rendered):
return _unavailable("UT-P016", "模板没有渲染出来,无法核对 MD 多出的内容")
value = {
"features": expected_features == actual_features and bool(expected_features),
"testpoints": expected_points == actual_points and bool(expected_points),
"testcases": expected_cases == actual_cases and bool(expected_cases),
"difficulties": expected_difficulty == actual_difficulty and bool(expected_difficulty),
"markdown": all(rendered),
}
return _check("UT-P016", value, "分片编号与最终 YAML,以及 MD 与模板")
_TEXT_SOURCES = {"spec", "spec_path", "testpoint_source", "optional_source", "closure_source", "skipped"}
def _judge(prompt: str, mapping: dict[str, str]) -> LLMJudgeDefinition:
return LLMJudgeDefinition(
prompt_template=prompt,
input_mapping={name: EvidenceBinding(source, "text" if source in _TEXT_SOURCES else "json")
for name, source in mapping.items()},
response_schema=_JUDGE_SCHEMA,
output_mapping={"label": "label", "reason": "explanation", "evidence_refs": "evidence_refs"},
score_policy=_PASS_FAIL,
)
P004_JUDGE = _judge(
"""检查 UT-P004。
检查对象:
- Spec:${spec_path}
- 测试点:${testpoint_source}。下面只给出 functional、structural、performance 三类,字段是 id、feature、testpoint、source。
检查标准:
- pass:每条都同时满足。functional 描述该 feature 在 Spec 中的行为或结果。structural 描述位宽、边界、状态或数据组织。performance 描述吞吐、延时、带宽或拍数。testpoint 的行为能在 Spec 里该 feature 的段落找到依据。
- fail:任一条类别和内容不符,或 testpoint 的行为在 Spec 对应段落里没有依据。
- partial:某条缺少 id、feature 或 testpoint,或 Spec 摘录被截断后无法对上。
返回:
- label 只能是 pass、partial、fail。
- reason 写出不符合的测试点 id,以及 Spec 里的依据。全部符合时,列出核对过的 id。
- evidence_refs 只能从这些名字里选,至少一项:${evidence_refs}
只根据下面的文字判断。
Spec 正文:
${spec}
测试点:
${testpoints}""",
{"spec_path": "spec_path", "testpoint_source": "testpoint_source", "evidence_refs": "evidence_refs",
"spec": "spec", "testpoints": "testpoints"},
)
P006_JUDGE = _judge(
"""检查 UT-P006。
检查对象:
- Spec:${spec_path}
- 可选测试点:${optional_source}。下面只给出 interface、scenario、exception 三类,字段是 id、testpoint、source。
- 跳过记录:${skipped}。记录里点名的类别不要求再有测试点。
检查标准:
- pass:interface 测的是端口或协议行为,scenario 测的是多个条件一起出现,exception 测的是非法输入或异常结果。已有条目都放对类别。
- fail:任一条测试点的内容不属于它所在的类别。
- partial:testpoint 太短,看不出它属于哪一类。
返回:
- label 只能是 pass、partial、fail。
- reason 写出放错的测试点 id 和它实际描述的内容。全部符合时,列出核对过的 id。
- evidence_refs 只能从这些名字里选,至少一项:${evidence_refs}
只根据下面的文字判断。
Spec 正文:
${spec}
测试点:
${testpoints}""",
{"spec_path": "spec_path", "optional_source": "optional_source", "skipped": "skipped",
"evidence_refs": "evidence_refs", "spec": "spec", "testpoints": "testpoints"},
)
P007_JUDGE = _judge(
"""检查 UT-P007。
检查对象:
- 来源:${closure_source}
- 材料:每条 item_dispositions 的 item、status、reason,以及 applied_rag_sources。
检查标准:
- pass:每条 reason 里的覆盖结论或 N/A 结论,能在该条自己的 source、reason 里点名的 TP,或 applied_rag_sources 中找到对应说法。
- fail:reason 声称某测试点或文档支持这个结论,但给出的引用里没有这个说法。
- partial:引用只有文件名或编号,正文不在本次材料里,无法核对说法是否成立。
返回:
- label 只能是 pass、partial、fail。
- reason 写出对不上的 item_id,并引用 reason 和来源的原句。全部符合时,列出核对过的 item_id。
- evidence_refs 只能从这些名字里选,至少一项:${evidence_refs}
只根据下面的材料判断。
处置和引用:
${dispositions}""",
{"closure_source": "closure_source", "evidence_refs": "evidence_refs", "dispositions": "dispositions"},
)
def _normalize_empty(params: dict[str, Any]) -> EmptyParams:
if params:
raise ValueError(f"unknown evaluator params: {sorted(params)}")
return EmptyParams()
def _measurement(evaluator_id: str, rule: Any, metric: str) -> EvaluatorDefinition:
return EvaluatorDefinition(
evaluator_id=evaluator_id, family="execution", result_kind="measurement",
expansion="once", rule=rule, scope="skill", metric=metric, unit="check",
required_evidence=frozenset({"execution_workspace"}), aggregation="mean",
direction="maximize", params_type=EmptyParams, normalize_params=_normalize_empty,
params_schema={"type": "object", "additionalProperties": False},
)
def _assessment(evaluator_id: str, rule: Any, judge: LLMJudgeDefinition) -> EvaluatorDefinition:
return EvaluatorDefinition(
evaluator_id=evaluator_id, family="execution", result_kind="assessment",
expansion="once", rule=rule, scope="skill", judge=judge,
required_evidence=frozenset({"execution_workspace"}), aggregation="mean",
direction="maximize", params_type=EmptyParams, normalize_params=_normalize_empty,
params_schema={"type": "object", "additionalProperties": False},
)
UT_TESTPLAN_EVALUATORS = {
"ut_p001_deliverables": _measurement("ut_p001_deliverables", ut_p001_deliverables, "UT-P001"),
"ut_p002_stage_dirs": _measurement("ut_p002_stage_dirs", ut_p002_stage_dirs, "UT-P002"),
"ut_p003_features": _measurement("ut_p003_features", ut_p003_features, "UT-P003"),
"ut_p004_testpoint_meaning": _assessment("ut_p004_testpoint_meaning", ut_p004_testpoint_meaning, P004_JUDGE),
"ut_p005_testcase_fields": _measurement("ut_p005_testcase_fields", ut_p005_testcase_fields, "UT-P005"),
"ut_p006_optional_categories": _assessment("ut_p006_optional_categories", ut_p006_optional_categories, P006_JUDGE),
"ut_p007_dispositions": _assessment("ut_p007_dispositions", ut_p007_dispositions, P007_JUDGE),
"ut_p008_architecture": _measurement("ut_p008_architecture", ut_p008_architecture, "UT-P008"),
"ut_p009_stimulus_checking": _measurement("ut_p009_stimulus_checking", ut_p009_stimulus_checking, "UT-P009"),
"ut_p010_difficulties": _measurement("ut_p010_difficulties", ut_p010_difficulties, "UT-P010"),
"ut_p011_special_methods": _measurement("ut_p011_special_methods", ut_p011_special_methods, "UT-P011"),
"ut_p012_covergroups": _measurement("ut_p012_covergroups", ut_p012_covergroups, "UT-P012"),
"ut_p013_components": _measurement("ut_p013_components", ut_p013_components, "UT-P013"),
"ut_p014_plan_closure": _measurement("ut_p014_plan_closure", ut_p014_plan_closure, "UT-P014"),
"ut_p015_template": _measurement("ut_p015_template", ut_p015_template, "UT-P015"),
"ut_p016_traceability": _measurement("ut_p016_traceability", ut_p016_traceability, "UT-P016"),
}