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
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
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
"""Dataset-agnostic domain objects shared by the evaluation runtime."""

from __future__ import annotations

import hashlib
import json
from dataclasses import dataclass, field, fields, is_dataclass
from pathlib import Path
from types import MappingProxyType
from collections.abc import Mapping, Sequence
from typing import Any, TYPE_CHECKING

if TYPE_CHECKING:
    from .evaluators.contracts import EvaluatorResult


# Domain identity and result fields have dedicated attributes on
# ``EvaluatorResult``/``ScoreRecord``.  Keeping the reservation in one leaf
# module lets every boundary discard stale carrier-shaped copies uniformly.
STRUCTURED_METADATA_FIELDS = frozenset({
    "evaluator_id", "family", "engine", "result_kind", "scope",
    "evaluator_version", "testpoint_id", "metric", "unit", "value",
    "status", "score", "label", "explanation", "evidence_refs",
})


def deep_freeze(value: Any) -> Any:
    """Recursively normalize domain values to immutable containers."""
    if isinstance(value, Mapping):
        return MappingProxyType({key: deep_freeze(item) for key, item in value.items()})
    if isinstance(value, (list, tuple)):
        return tuple(deep_freeze(item) for item in value)
    if isinstance(value, (set, frozenset)):
        return frozenset(deep_freeze(item) for item in value)
    return value


def deep_thaw(value: Any) -> Any:
    """Return JSON-friendly mutable containers at an adapter boundary."""
    if isinstance(value, Mapping):
        return {key: deep_thaw(item) for key, item in value.items()}
    if isinstance(value, (list, tuple, set, frozenset)):
        return [deep_thaw(item) for item in value]
    if is_dataclass(value):
        return {item.name: deep_thaw(getattr(value, item.name)) for item in fields(value)}
    return value


def _json(value: Any) -> Any:
    if is_dataclass(value):
        return {item.name: _json(getattr(value, item.name)) for item in fields(value)}
    if hasattr(value, "to_dict"):
        return value.to_dict()
    if hasattr(value, "as_dict"):
        return value.as_dict()
    if isinstance(value, Path):
        return value.as_posix()
    if isinstance(value, (list, tuple)):
        return [_json(item) for item in value]
    if isinstance(value, Mapping):
        return {str(key): _json(item) for key, item in value.items()}
    return value


def _decode_artifact_refs(value: Any) -> list[str]:
    if value is None:
        return []
    if not isinstance(value, (list, tuple)):
        raise TypeError("task artifact artifact_refs must be a list")
    if any(not isinstance(item, str) or not item for item in value):
        raise ValueError("task artifact artifact_refs must contain non-empty strings")
    return list(value)


def _decode_metadata(value: Any) -> dict[str, Any]:
    if value is None:
        return {}
    if not isinstance(value, Mapping):
        raise TypeError("task artifact metadata must be an object")
    return dict(value)


def stable_hash(data: bytes) -> str:
    return hashlib.sha256(data).hexdigest()


@dataclass(frozen=True)
class SkillReference:
    skill_id: str
    version: str
    entrypoint: str
    entrypoint_hash: str
    bundle_hash: str

    def to_dict(self) -> dict[str, Any]:
        return _json(self)


@dataclass(frozen=True)
class SkillBundle(SkillReference):
    """Loaded skill content made available to task adapters."""

    content: str = ""
    root: str = ""

    @classmethod
    def load(cls, path: str | Path, version: str = "working") -> "SkillBundle":
        entrypoint = Path(path).resolve()
        if entrypoint.is_dir():
            entrypoint = entrypoint / "SKILL.md"
        if not entrypoint.is_file():
            raise FileNotFoundError(f"Skill entrypoint does not exist: {entrypoint}")
        content = entrypoint.read_text(encoding="utf-8")
        skill_id = entrypoint.parent.name
        for line in content.splitlines():
            if line.startswith("name:"):
                skill_id = line.split(":", 1)[1].strip() or skill_id
                break
        root = entrypoint.parent
        digest = hashlib.sha256()
        files = sorted(
            file_path for file_path in root.rglob("*")
            if file_path.is_file()
            and not any(part.startswith(".") or part == "__pycache__" for part in file_path.relative_to(root).parts)
            and file_path.suffix != ".pyc"
            and file_path.relative_to(root).as_posix() != "skill.yaml"
        )
        for file_path in files:
            relative = file_path.relative_to(root).as_posix().encode("utf-8")
            data = file_path.read_bytes()
            digest.update(len(relative).to_bytes(8, "big")); digest.update(relative)
            digest.update(len(data).to_bytes(8, "big")); digest.update(data)
        return cls(skill_id, version, entrypoint.as_posix(), stable_hash(entrypoint.read_bytes()), digest.hexdigest(), content, root.as_posix())

    def ref_dict(self) -> dict[str, Any]:
        return {"skill_id": self.skill_id, "version": self.version, "entrypoint": self.entrypoint,
                "entrypoint_hash": self.entrypoint_hash, "bundle_hash": self.bundle_hash}

    def to_dict(self) -> dict[str, Any]:
        return _json(self)


@dataclass(frozen=True)
class TaskArtifact:
    run_id: str
    case_id: str
    status: str
    output: Any
    artifact_refs: list[str] = field(default_factory=list)
    metadata: dict[str, Any] = field(default_factory=dict)
    execution: "ExecutionEvidence | None" = None
    trace_ref: "TraceRef | None" = None

    def __post_init__(self) -> None:
        object.__setattr__(self, "output", deep_freeze(self.output))
        object.__setattr__(self, "artifact_refs", tuple(str(item) for item in self.artifact_refs))
        object.__setattr__(self, "metadata", deep_freeze(self.metadata))

    def to_dict(self) -> dict[str, Any]:
        return _json(self)

    @classmethod
    def from_dict(cls, value: "TaskArtifact | Mapping[str, Any]") -> "TaskArtifact":
        """Decode the typed task result carried through experiment backends."""
        if isinstance(value, cls):
            return value
        if not isinstance(value, Mapping):
            raise TypeError("task artifact must be a TaskArtifact or object")
        allowed_keys = {
            "run_id", "case_id", "status", "output", "artifact_refs",
            "metadata", "execution", "trace_ref",
        }
        unknown_keys = set(value) - allowed_keys
        if unknown_keys:
            raise ValueError(f"task artifact contains unknown fields: {sorted(unknown_keys)}")
        execution_value = value.get("execution")
        if isinstance(execution_value, ExecutionEvidence):
            execution = execution_value
        elif isinstance(execution_value, Mapping):
            execution = ExecutionEvidence(**dict(execution_value))
        elif execution_value is None:
            execution = None
        else:
            raise TypeError("task artifact execution must be an object or null")
        trace_value = value.get("trace_ref")
        if isinstance(trace_value, TraceRef):
            trace_ref = trace_value
        elif isinstance(trace_value, Mapping):
            project = trace_value.get("project")
            session_id = trace_value.get("session_id")
            if not isinstance(project, str) or not project.strip() or not isinstance(session_id, str) or not session_id.strip():
                raise ValueError("task artifact trace_ref requires non-empty project and session_id")
            trace_ref = TraceRef(project=project, session_id=session_id)
        elif trace_value is None:
            trace_ref = None
        else:
            raise TypeError("task artifact trace_ref must be an object or null")
        return cls(
            run_id=str(value.get("run_id", "unknown")),
            case_id=str(value.get("case_id", "unknown")),
            status=str(value.get("status", "failed")),
            output=value.get("output"),
            artifact_refs=_decode_artifact_refs(value.get("artifact_refs", [])),
            metadata=_decode_metadata(value.get("metadata", {})),
            execution=execution,
            trace_ref=trace_ref,
        )


@dataclass(frozen=True)
class ExecutionEvidence:
    """Facts observed by an execution adapter, independent of storage backend."""

    final_output: str = ""
    tool_calls: list[dict[str, Any]] = field(default_factory=list)
    validation: list[dict[str, Any]] = field(default_factory=list)
    changed_files: list[str] = field(default_factory=list)
    duration_seconds: float | None = None
    task_workspace: str | None = None
    returncode: int | None = None

    def __post_init__(self) -> None:
        for name in ("tool_calls", "validation", "changed_files"):
            value = getattr(self, name)
            if value is not None:
                object.__setattr__(self, name, deep_freeze(value))

    def to_dict(self) -> dict[str, Any]:
        return _json(self)


@dataclass(frozen=True)
class TraceRef:
    """The minimum reference needed by a post-run trace reader."""

    project: str
    session_id: str

    def to_dict(self) -> dict[str, Any]:
        return _json(self)


@dataclass(frozen=True)
class TestPoint:
    test_point_id: str
    kind: str
    ordinal: int
    name: str
    previous_test_point_id: str | None
    requirement: str
    weight: float = 1.0

    def to_dict(self) -> dict[str, Any]:
        return _json(self)


@dataclass(frozen=True)
class TestPointSet:
    skill_id: str
    skill_version: str
    skill_bundle_hash: str
    compiler_version: str
    test_points: list[TestPoint]
    set_hash: str = ""

    def __post_init__(self) -> None:
        object.__setattr__(self, "test_points", tuple(self.test_points))
        if self.set_hash:
            return
        payload = json.dumps({
            "skill_id": self.skill_id,
            "skill_version": self.skill_version,
            "skill_bundle_hash": self.skill_bundle_hash,
            "compiler_version": self.compiler_version,
            "test_points": [point.to_dict() for point in self.test_points],
        }, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode()
        object.__setattr__(self, "set_hash", stable_hash(payload))

    def to_dict(self) -> dict[str, Any]:
        return _json(self)


@dataclass(frozen=True)
class ScoreIdentity:
    run_id: str
    case_id: str
    evaluator_id: str
    family: str
    engine: str
    scope: str
    evaluator_version: str
    testpoint_id: str | None = None

    def to_dict(self) -> dict[str, Any]:
        return _json(self)


@dataclass(frozen=True)
class ScoreRecord:
    """Canonical audit record of one typed evaluator result.

    The constructor deliberately mirrors the domain shape: identity and the
    tagged result are stored once, with backend provenance kept separately.
    Flat artifact fields are read-only projections below.
    """

    score_id: str
    identity: ScoreIdentity
    result: "EvaluatorResult"
    provenance: Mapping[str, Any] = field(default_factory=dict)

    def __post_init__(self) -> None:
        if not isinstance(self.identity, ScoreIdentity):
            raise TypeError("ScoreRecord identity must be ScoreIdentity")
        from .evaluators.contracts import EvaluatorResult
        if not isinstance(self.result, EvaluatorResult):
            raise TypeError("ScoreRecord result must be an EvaluatorResult")
        object.__setattr__(self, "provenance", deep_freeze(self.provenance))

    @classmethod
    def from_dict(cls, value: Mapping[str, Any]) -> ScoreRecord:
        """Restore the flat audit format through the normal domain validators."""
        from .evaluators.contracts import evaluator_result

        identity = ScoreIdentity(**{f.name: value[f.name] for f in fields(ScoreIdentity)})
        result = evaluator_result(**{name: value[name] for name in (
            "score", "label", "explanation", "status", "result_kind", "value", "metric", "unit", "evidence_refs",
        )})
        return cls(value["score_id"], identity, result, value["metadata"])

    @property
    def run_id(self) -> str: return self.identity.run_id
    @property
    def case_id(self) -> str: return self.identity.case_id
    @property
    def evaluator_id(self) -> str: return self.identity.evaluator_id
    @property
    def engine(self) -> str: return self.identity.engine
    @property
    def family(self) -> str: return self.identity.family
    @property
    def scope(self) -> str: return self.identity.scope
    @property
    def evaluator_version(self) -> str: return self.identity.evaluator_version
    @property
    def testpoint_id(self) -> str | None: return self.identity.testpoint_id
    @property
    def score(self) -> float | None: return getattr(self.result, "score", None)
    @property
    def label(self) -> str:
        # Measurements intentionally have no semantic label field.  Emit the
        # conventional carrier label only at the flat projection boundary.
        if self.result_kind == "measurement":
            return "measurement"
        return getattr(self.result, "label", "")
    @property
    def status(self) -> str: return str(self.result.status)
    @property
    def explanation(self) -> str: return self.result.explanation
    @property
    def evidence_refs(self) -> tuple[str, ...]: return self.result.evidence_refs
    @property
    def result_kind(self) -> str: return str(self.result.result_kind)
    @property
    def value(self) -> Any: return getattr(self.result, "value", None)
    @property
    def metric(self) -> str | None: return getattr(self.result, "metric", None)
    @property
    def unit(self) -> str | None: return getattr(self.result, "unit", None)
    @property
    def metadata(self) -> Mapping[str, Any]: return self.provenance

    @property
    def source(self) -> str:
        return str(self.provenance.get("source", "experiment"))

    def to_dict(self) -> dict[str, Any]:
        # Keep the on-disk shape flat and stable even though memory is nested.
        return {
            "score_id": self.score_id, "run_id": self.run_id,
            "case_id": self.case_id, "evaluator_id": self.evaluator_id,
            "engine": self.engine, "family": self.family, "scope": self.scope,
            "evaluator_version": self.evaluator_version,
            "testpoint_id": self.testpoint_id, "result_kind": self.result_kind,
            "status": self.status, "score": self.score, "label": self.label,
            "explanation": self.explanation, "evidence_refs": list(self.evidence_refs),
            "value": deep_thaw(self.value), "metric": self.metric, "unit": self.unit,
            "metadata": deep_thaw(self.provenance),
        }


def score_statistics(scores: Sequence[ScoreRecord]) -> dict[str, Any]:
    """Shared domain counts; missing assessment evidence stays in the denominator."""
    assessments = [s for s in scores if s.result_kind == "assessment"]
    diagnostics = [s for s in scores if s.result_kind == "diagnostic"]
    return {
        "score_count": len(scores),
        "assessment_count": len(assessments),
        "measurement_count": sum(s.result_kind == "measurement" for s in scores),
        "diagnostic_count": len(diagnostics),
        "diagnosed_count": sum(s.label == "diagnosed" for s in diagnostics),
        "diagnostic_not_selected_count": sum(s.label == "not_selected" for s in diagnostics),
        "diagnostic_incomplete_count": sum(s.label == "incomplete" for s in diagnostics),
        "diagnostic_error_count": sum(s.label == "error" or s.status == "error" for s in diagnostics),
        "execution_score_count": sum(s.family == "execution" for s in scores),
        "trace_score_count": sum(s.family == "trace" for s in scores),
        "generic_evaluator_count": len({s.evaluator_id for s in scores if s.scope == "generic"}),
        "skill_evaluator_count": len({s.evaluator_id for s in scores if s.scope == "skill"}),
        "pass_rate": sum(s.status == "success" and s.score == 1 for s in assessments) / len(assessments) if assessments else 0.0,
        "failed_count": sum(s.status == "success" and s.score == 0 for s in assessments),
        "incomplete_count": sum(s.status in {"incomplete", "unavailable", "error"} for s in assessments),
    }


@dataclass(frozen=True)
class BackendRunResult:
    """Backend-neutral outcome returned by ``ExperimentBackend.run``."""

    backend_name: str
    experiment_id: str
    runs: tuple[TaskArtifact, ...] = ()
    scores: tuple[ScoreRecord, ...] = ()
    run_count: int = 0
    evaluation_count: int = 0
    failed_evaluation_count: int = 0
    published_result_count: int = 0
    metadata: Mapping[str, Any] = field(default_factory=dict)

    def __post_init__(self) -> None:
        if not self.backend_name or not self.experiment_id:
            raise ValueError("backend result requires backend_name and experiment_id")
        for field_name in (
            "run_count",
            "evaluation_count",
            "failed_evaluation_count",
            "published_result_count",
        ):
            value = getattr(self, field_name)
            if isinstance(value, bool) or not isinstance(value, int) or value < 0:
                raise ValueError(f"backend result {field_name} must be a non-negative integer")
        object.__setattr__(self, "runs", tuple(self.runs))
        object.__setattr__(self, "scores", tuple(self.scores))
        object.__setattr__(self, "metadata", deep_freeze(self.metadata))


@dataclass(frozen=True)
class FeedbackRecord:
    feedback_id: str
    run_id: str
    case_id: str
    evaluator_id: str
    failure_type: str
    root_cause: str
    explanation: str
    evidence_refs: list[str]
    suggested_change: str | None = None

    def __post_init__(self) -> None:
        object.__setattr__(self, "evidence_refs", tuple(str(item) for item in self.evidence_refs))

    def to_dict(self) -> dict[str, Any]:
        return _json(self)


def write_jsonl(path: str | Path, rows: list[Any]) -> None:
    target = Path(path)
    target.parent.mkdir(parents=True, exist_ok=True)
    def record(row: Any) -> Any:
        # Domain records own their public artifact shape.  In particular,
        # ScoreRecord deliberately stores identity/result/provenance as a
        # nested in-memory model but exposes a stable flat JSONL record.
        to_dict = getattr(row, "to_dict", None)
        return to_dict() if callable(to_dict) else _json(row)

    target.write_text(
        "".join(
            json.dumps(record(row), ensure_ascii=False, sort_keys=True) + "\n"
            for row in rows
        ),
        encoding="utf-8",
    )