File size: 36,997 Bytes
fd11263
 
 
 
 
 
 
 
d26f22a
fd11263
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d26f22a
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
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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
"""Trace-family evaluator rules and their static definitions."""

from __future__ import annotations

from dataclasses import dataclass
from typing import Any, Mapping

from ..models import TestPoint, TestPointSet
from ..trace_evidence import TraceEvidence
from ..models import deep_thaw
from .contracts import (EmptyParams, EvaluationContext, EvaluatorDefinition,
                        EvaluatorResult, EvidenceBinding, FrozenParams,
                        LLMJudgeDefinition, LLMJudgeRequest, ScorePolicy,
                        evaluator_result)


@dataclass(frozen=True)
class DurationWithinLimitParams(FrozenParams):
    max_duration_seconds: float


@dataclass(frozen=True)
class ProcessQualityParams(FrozenParams):
    max_steps: int


@dataclass(frozen=True)
class BottleneckDiagnosisParams(FrozenParams):
    min_duration_seconds: float
    max_testpoints_per_case: int
    max_trace_chars: int
    max_span_chars: int
    max_skill_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 validate_no_params(params: dict[str, Any]) -> None:
    _validate_keys(params, set())


def validate_duration(params: dict[str, Any]) -> None:
    _validate_keys(params, {"max_duration_seconds"})
    value = params.get("max_duration_seconds")
    if not isinstance(value, (int, float)) or isinstance(value, bool) or value < 0:
        raise ValueError("duration_within_limit requires non-negative numeric max_duration_seconds")


def validate_process_quality(params: dict[str, Any]) -> None:
    _validate_keys(params, {"max_steps"})
    value = params.get("max_steps")
    if not isinstance(value, int) or isinstance(value, bool) or value < 1:
        raise ValueError("process_quality max_steps must be a positive integer")


def validate_bottleneck_diagnosis(params: dict[str, Any]) -> None:
    required = {
        "min_duration_seconds", "max_testpoints_per_case", "max_trace_chars",
        "max_span_chars", "max_skill_chars",
    }
    _validate_keys(params, required)
    missing = required - set(params)
    if missing:
        raise ValueError(f"testpoint_bottleneck_diagnosis is missing params: {sorted(missing)}")
    duration = params["min_duration_seconds"]
    if not isinstance(duration, (int, float)) or isinstance(duration, bool) or duration < 0:
        raise ValueError("min_duration_seconds must be a non-negative number")
    for key in ("max_testpoints_per_case", "max_trace_chars", "max_span_chars", "max_skill_chars"):
        value = params[key]
        if not isinstance(value, int) or isinstance(value, bool) or value < 1:
            raise ValueError(f"{key} must be a positive integer")
    if params["max_trace_chars"] < params["max_span_chars"]:
        raise ValueError("max_trace_chars must be >= max_span_chars")


def normalize_empty_params(params: Mapping[str, Any]) -> EmptyParams:
    validate_no_params(dict(params))
    return EmptyParams()


def normalize_duration_params(params: Mapping[str, Any]) -> DurationWithinLimitParams:
    raw = dict(params)
    validate_duration(raw)
    return DurationWithinLimitParams(float(raw["max_duration_seconds"]))


def normalize_process_quality_params(params: Mapping[str, Any]) -> ProcessQualityParams:
    raw = dict(params)
    validate_process_quality(raw)
    return ProcessQualityParams(int(raw["max_steps"]))


def normalize_bottleneck_params(params: Mapping[str, Any]) -> BottleneckDiagnosisParams:
    raw = dict(params)
    validate_bottleneck_diagnosis(raw)
    return BottleneckDiagnosisParams(
        float(raw["min_duration_seconds"]), int(raw["max_testpoints_per_case"]),
        int(raw["max_trace_chars"]), int(raw["max_span_chars"]),
        int(raw["max_skill_chars"]),
    )


_ASSESSMENT_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"}},
    },
}

PROCESS_QUALITY_JUDGE = LLMJudgeDefinition(
    prompt_template="""Evaluate only the quality of the recorded execution process.
Pass requires a coherent progression through the expected testpoints without material failed,
duplicated, disordered, or wasteful steps. Partial means the process is substantially useful but
contains a material gap, ambiguity, failure, or avoidable detour. Fail means the process is mostly
failed, incoherent, unsupported by its explicit events, or does not meaningfully execute the task.
Do not judge deliverable contents and do not infer hidden prompt or tool content.

Expected testpoints:
${testpoints}

Trace status:
${trace_status}

Observed testpoint events:
${testpoint_events}

Ordered trace steps:
${steps}

Evidence references:
${evidence_refs}""",
    input_mapping={
        "testpoints": EvidenceBinding("skill.expected_testpoints", "json"),
        "trace_status": EvidenceBinding("trace.status", "text"),
        "testpoint_events": EvidenceBinding("trace.testpoint_event_status", "json"),
        "steps": EvidenceBinding("trace.steps", "json"),
        "evidence_refs": EvidenceBinding("evidence_refs", "json"),
    },
    response_schema=_ASSESSMENT_RESPONSE_SCHEMA,
    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},
    ),
)

TESTPOINT_BOTTLENECK_JUDGE = LLMJudgeDefinition(
    prompt_template="""Diagnose why this selected TestPoint consumed substantial time.
Identify concrete latency bottlenecks supported by the supplied trace structure and visible content.
Distinguish repeated work, failed or retried tools, unnecessary serialization, excessive reasoning,
large I/O, and Skill-instruction problems when the evidence supports them. Explain the impact and
recommend a specific change. Do not infer redacted, missing, truncated, or policy-omitted content,
and do not judge final deliverable quality.

Selection:
${selection}

Trace interval:
${trace}

Skill context:
${skill}

Evidence completeness:
${evidence_completeness}

Evidence references:
${evidence_refs}""",
    input_mapping={
        "selection": EvidenceBinding("selection", "json"),
        "trace": EvidenceBinding("trace", "json"),
        "skill": EvidenceBinding("skill", "json"),
        "evidence_completeness": EvidenceBinding("evidence_completeness", "text"),
        "evidence_refs": EvidenceBinding("evidence_refs", "json"),
    },
    response_schema={
        "type": "object",
        "required": ["summary", "bottlenecks", "evidence_completeness"],
        "additionalProperties": False,
        "properties": {
            "summary": {"type": "string", "minLength": 1},
            "bottlenecks": {
                "type": "array", "minItems": 1,
                "items": {
                    "type": "object",
                    "required": ["category", "finding", "impact", "recommendation",
                                 "confidence", "evidence_refs"],
                    "additionalProperties": False,
                    "properties": {
                        "category": {"type": "string", "minLength": 1},
                        "finding": {"type": "string", "minLength": 1},
                        "impact": {"type": "string", "minLength": 1},
                        "recommendation": {"type": "string", "minLength": 1},
                        "confidence": {"type": "string", "enum": ["low", "medium", "high"]},
                        "evidence_refs": {"type": "array", "minItems": 1,
                                          "items": {"type": "string"}},
                    },
                },
            },
            "evidence_completeness": {"type": "string", "enum": ["complete", "partial"]},
        },
    },
    output_mapping={"summary": "explanation", "bottlenecks": "value.bottlenecks",
                    "evidence_completeness": "metadata.evidence_completeness"},
    score_policy=ScorePolicy(
        label_mapping={"diagnosed": "diagnosed", "not_selected": "not_selected",
                       "incomplete": "incomplete"}, score_mapping={}
    ),
)


def _trace(context: EvaluationContext) -> TraceEvidence:
    if context.trace is None:
        raise ValueError("trace evaluator requires TraceEvidence")
    return context.trace


def process_quality(
    context: EvaluationContext, params: ProcessQualityParams
) -> LLMJudgeRequest:
    evidence = _trace(context)
    max_steps = int(params.max_steps)
    all_steps = [{
        "index": step.index, "span_id": step.span_id, "parent_id": step.parent_id,
        "name": step.name, "kind": step.kind, "status": step.status,
        "duration_seconds": step.duration_seconds,
    } for step in (evidence.steps or [])]
    steps = all_steps[:max_steps]
    return LLMJudgeRequest(
        evidence={
            "case": {"case_id": context.case.case_id},
            "skill": {
                "skill_id": context.skill.skill_id,
                "expected_testpoints": [
                    point.to_dict() for point in context.testpoint_set.test_points
                ],
            },
            "trace": {
                "status": evidence.status,
                "duration_seconds": evidence.duration_seconds,
                "testpoint_event_status": evidence.testpoint_event_status or {},
                "steps": steps,
                "step_count": len(all_steps),
            },
        },
        evidence_refs=("skill.testpoints", "trace.root",
                       "trace.testpoint_events", "trace.steps"),
        projection_truncated=len(steps) < len(all_steps),
    )


def duration_within_limit(
    context: EvaluationContext, params: DurationWithinLimitParams
) -> EvaluatorResult:
    evidence = _trace(context)
    limit = float(params.max_duration_seconds)
    passed = evidence.duration_seconds is not None and evidence.duration_seconds <= limit
    return evaluator_result(score=float(passed), label="pass" if passed else "fail",
        explanation=f"duration={evidence.duration_seconds}; limit={limit}",
        evidence_refs=["trace.root.duration_seconds"],
        metadata={"session_id": evidence.session_id, "limit": limit})


def testpoint_reached(
    context: EvaluationContext, params: EmptyParams
) -> EvaluatorResult:
    evidence = _trace(context)
    point = context.testpoint
    if point is None:
        raise ValueError("testpoint evaluator requires a bound TestPoint")
    state = _testpoint_status(evidence, point)
    passed = state == "exact"
    return evaluator_result(score=float(passed), label="pass" if passed else "fail",
        explanation=f"expected={point.test_point_id}; event_status={state}",
        evidence_refs=["trace.events", "trace.testpoint_event_status"],
        metadata={"session_id": evidence.session_id,
                  "attribution_status": state})


def trace_shape(
    context: EvaluationContext, params: EmptyParams
) -> EvaluatorResult:
    evidence = _trace(context)
    passed = "Turn" in evidence.span_names and any(name.startswith("LLM") for name in evidence.span_names)
    return evaluator_result(score=float(passed), label="pass" if passed else "fail",
        explanation=f"spans={evidence.span_names}",
        evidence_refs=["trace.span_names", "trace.root.status"],
        metadata={"session_id": evidence.session_id})


def _testpoint_status(evidence: TraceEvidence, point: TestPoint) -> str:
    """Return a diagnostic state without conflating missing and unreached."""
    status = (evidence.testpoint_event_status or {}).get(point.test_point_id)
    if status:
        matching = [event for event in (evidence.events or [])
                    if event.entity_type == "testpoint" and event.entity_id == point.test_point_id]
        if status == "exact" and (len(matching) != 1 or matching[0].sequence != point.ordinal):
            return "ambiguous"
        return status
    return "missing_explicit_event" if not evidence.events else "testpoint_not_reached"


def testpoint_interval(evidence: TraceEvidence, point: TestPoint) -> tuple[float, float] | None:
    completions = evidence.testpoint_completion_times or {}
    if _testpoint_status(evidence, point) != "exact":
        return None
    end = completions.get(point.test_point_id)
    if end is None:
        return None
    start = (evidence.root_start_time if point.previous_test_point_id is None
             else completions.get(point.previous_test_point_id))
    return None if start is None or end < start else (start, end)


def testpoint_interval_status(evidence: TraceEvidence, point: TestPoint) -> str:
    """Explain why an exact event does or does not form a time interval.

    ``testpoint_not_reached`` is reserved for a missing completion event.  An
    observed completion with an unusable neighboring boundary is a distinct
    evidence condition and must not be reported as an execution failure.
    """
    state = _testpoint_status(evidence, point)
    if state != "exact":
        return state
    completions = evidence.testpoint_completion_times or {}
    if point.test_point_id not in completions:
        return "completion_timestamp_unavailable"
    if point.previous_test_point_id is None:
        if evidence.root_start_time is None:
            return "root_start_timestamp_unavailable"
        return "exact"
    previous_id = point.previous_test_point_id
    previous_state = (evidence.testpoint_event_status or {}).get(previous_id)
    if previous_state != "exact":
        return "previous_boundary_ambiguous" if previous_state else "previous_boundary_unavailable"
    if previous_id not in completions:
        return "previous_boundary_timestamp_unavailable"
    if completions[point.test_point_id] < completions[previous_id]:
        return "invalid_interval_order"
    return "exact"


def testpoint_duration_seconds(evidence: TraceEvidence, point: TestPoint) -> float | None:
    interval = testpoint_interval(evidence, point)
    return None if interval is None else max(0.0, interval[1] - interval[0])


def select_slow_testpoints(evidence: TraceEvidence, testpoint_set: TestPointSet,
                           params: BottleneckDiagnosisParams) -> dict[str, dict[str, Any]]:
    """Apply one deterministic threshold-plus-Top-K policy for a case trace."""
    threshold = float(params.min_duration_seconds)
    maximum = int(params.max_testpoints_per_case)
    selections: dict[str, dict[str, Any]] = {}
    eligible: list[tuple[float, int, TestPoint]] = []
    for point in testpoint_set.test_points:
        state = _testpoint_status(evidence, point)
        duration = testpoint_duration_seconds(evidence, point)
        entry = {
            "testpoint_id": point.test_point_id,
            "duration_seconds": duration,
            "min_duration_seconds": threshold,
            "max_testpoints_per_case": maximum,
            "rank": None,
            "eligible": False,
            "selected": False,
            "reason": state if state != "exact" else "below_threshold",
        }
        if state == "exact" and duration is not None and duration >= threshold:
            entry["eligible"] = True
            eligible.append((duration, point.ordinal, point))
        elif state == "exact" and duration is None:
            entry["reason"] = "duration_unavailable"
        selections[point.test_point_id] = entry
    eligible.sort(key=lambda item: (-item[0], item[1]))
    for rank, (_, _, point) in enumerate(eligible, start=1):
        entry = selections[point.test_point_id]
        entry["rank"] = rank
        entry["selected"] = rank <= maximum
        entry["reason"] = "selected" if entry["selected"] else "outside_top_k"
    return selections


def _bounded_content(text: str | None, status: str, *, per_span: int,
                     remaining: int) -> tuple[str | None, str, int, bool]:
    if status != "available" or text is None:
        return None, status, remaining, False
    allowed = min(per_span, max(0, remaining))
    selected = text[:allowed]
    truncated = len(selected) < len(text)
    return selected, "truncated" if truncated else "available", remaining - len(selected), truncated


def project_testpoint_trace(evidence: TraceEvidence, point: TestPoint, *,
                            max_trace_chars: int, max_span_chars: int) -> dict[str, Any]:
    """Project one explicit TestPoint interval without reading raw adapter artifacts."""
    interval = testpoint_interval(evidence, point)
    if interval is None:
        return {
            "interval": None, "steps": [], "events": [], "evidence_refs": [],
            "projection_truncated": False, "evidence_completeness": "insufficient",
            "actionable_span_count": 0,
        }
    start, end = interval
    remaining = max_trace_chars
    projected_steps: list[dict[str, Any]] = []
    refs: list[str] = []
    truncated = False
    partial = False
    actionable = 0
    for step in evidence.steps or []:
        if step.start_time is None or step.end_time is None:
            continue
        starts_after_previous = (
            step.end_time > start if point.previous_test_point_id is not None
            else step.end_time >= start
        )
        if not starts_after_previous or step.start_time > end:
            continue
        if step.start_time < start and step.end_time > end:
            relation = "encloses_interval"
        elif step.start_time < start:
            relation = "crosses_start"
        elif step.end_time > end:
            relation = "crosses_end"
        else:
            relation = "contained"
        attribution = "exact" if relation == "contained" else "shared"
        span_remaining = max_span_chars
        input_text, input_status, remaining, input_truncated = _bounded_content(
            step.input_text, step.input_status, per_span=span_remaining, remaining=remaining
        )
        span_remaining -= len(input_text or "")
        output_text, output_status, remaining, output_truncated = _bounded_content(
            step.output_text, step.output_status, per_span=max(0, span_remaining), remaining=remaining
        )
        item = {
            **step.to_dict(),
            "input_text": input_text, "input_status": input_status,
            "output_text": output_text, "output_status": output_status,
            "interval_relation": relation, "attribution_status": attribution,
        }
        projected_steps.append(item)
        if step.span_id:
            ref = f"trace.span:{step.span_id}"
            if ref not in refs:
                refs.append(ref)
        if step.kind in {"llm", "tool"}:
            actionable += 1
        step_partial = attribution == "shared" or any(
            value in {"redacted", "missing", "truncated"}
            for value in (input_status, output_status)
        )
        partial = partial or step_partial
        truncated = truncated or input_truncated or output_truncated
    projected_events: list[dict[str, Any]] = []
    for event in evidence.events or []:
        if event.entity_type != "testpoint" or event.entity_id != point.test_point_id:
            continue
        item = {
            "protocol": event.protocol, "event_type": event.event_type,
            "entity_type": event.entity_type, "entity_id": event.entity_id,
            "state": event.state, "sequence": event.sequence, "payload": deep_thaw(event.payload),
            "source": event.source, "span_id": event.span_id,
            "parent_span_id": event.parent_span_id, "observed_at": event.observed_at,
            "attribution_status": event.attribution_status,
        }
        projected_events.append(item)
        if event.span_id:
            ref = f"trace.event:{event.span_id}:{event.entity_id}"
            if ref not in refs:
                refs.append(ref)
    completeness = "insufficient" if actionable == 0 else ("partial" if partial or truncated else "complete")
    return {
        "interval": {"start_time": start, "end_time": end,
                     "duration_seconds": max(0.0, end - start)},
        "steps": projected_steps, "events": projected_events,
        "evidence_refs": refs, "projection_truncated": truncated,
        "evidence_completeness": completeness,
        "actionable_span_count": actionable,
    }


def _diagnostic_lifecycle(label: str, explanation: str, *, selection: dict[str, Any],
                          completeness: str = "insufficient",
                          evidence_refs: list[str] | None = None) -> EvaluatorResult:
    return evaluator_result(
        score=None, label=label, explanation=explanation,
        evidence_refs=evidence_refs or [],
        status=("incomplete" if label == "incomplete" else "success"),
        metadata={"selection": selection, "evidence_completeness": completeness},
        result_kind="diagnostic",
    )


def testpoint_bottleneck_diagnosis(
    context: EvaluationContext, params: BottleneckDiagnosisParams
) -> EvaluatorResult | LLMJudgeRequest:
    evidence = _trace(context)
    point = context.testpoint
    if point is None:
        raise ValueError("testpoint evaluator requires a bound TestPoint")
    selection = select_slow_testpoints(
        evidence, context.testpoint_set, params
    )[point.test_point_id]
    if selection["reason"] not in {"selected", "below_threshold", "outside_top_k"}:
        return _diagnostic_lifecycle(
            "incomplete", f"{point.test_point_id} has no exact duration boundary: {selection['reason']}",
            selection=selection,
        )
    if not selection["selected"]:
        return _diagnostic_lifecycle(
            "not_selected", f"{point.test_point_id} was not selected by the slow TestPoint policy",
            selection=selection,
        )
    projection = project_testpoint_trace(
        evidence, point, max_trace_chars=int(params.max_trace_chars),
        max_span_chars=int(params.max_span_chars),
    )
    if projection["evidence_completeness"] == "insufficient":
        return _diagnostic_lifecycle(
            "incomplete", f"{point.test_point_id} has no actionable persisted spans",
            selection=selection, evidence_refs=list(projection["evidence_refs"]),
        )
    max_skill_chars = int(params.max_skill_chars)
    skill_content = context.skill.content[:max_skill_chars]
    skill_truncated = len(skill_content) < len(context.skill.content)
    completeness = "partial" if skill_truncated else projection["evidence_completeness"]
    skill_refs = [f"skill.entrypoint:{context.skill.bundle_hash}",
                  f"skill.testpoint:{point.test_point_id}"]
    refs = tuple(dict.fromkeys([*projection["evidence_refs"], *skill_refs]))
    return LLMJudgeRequest(
        evidence={
            "case": {"case_id": context.case.case_id},
            "selection": selection,
            "evidence_completeness": completeness,
            "trace": projection,
            "skill": {
                "skill_id": context.skill.skill_id,
                "bundle_hash": context.skill.bundle_hash,
                "target_testpoint": point.to_dict(),
                "testpoint_outline": [
                    item.to_dict() for item in context.testpoint_set.test_points
                ],
                "content": skill_content, "content_truncated": skill_truncated,
                "original_char_count": len(context.skill.content),
            },
        },
        evidence_refs=refs,
        projection_truncated=bool(projection["projection_truncated"] or skill_truncated),
        metadata={"selection": selection, "evidence_completeness": completeness,
                  "testpoint_id": point.test_point_id},
    )


def _overlapping_spans(evidence: TraceEvidence, interval: tuple[float, float], point: TestPoint):
    start, end = interval
    anchors = evidence.testpoint_completion_llm_ids or {}
    current_anchor = anchors.get(point.test_point_id)
    previous_anchor = anchors.get(point.previous_test_point_id) if point.previous_test_point_id else None
    if current_anchor and previous_anchor and current_anchor == previous_anchor:
        # One LLM span can parent multiple sequential emitter calls. Its token
        # total is indivisible, so never attribute it to both adjacent points.
        return
    llm_ids = {span.span_id for span in evidence.llm_spans or []}
    if current_anchor not in llm_ids:
        current_anchor = None
    if previous_anchor not in llm_ids:
        previous_anchor = None
    # A completion event without an LLM parent has a valid timestamp for the
    # duration evaluator, but it does not establish token ownership.  Do not
    # fall back to interval overlap: that would turn unrelated LLM spans into
    # an apparently exact TestPoint measurement.
    if current_anchor is None:
        return
    for span in evidence.llm_spans or []:
        if span.start_time is None or span.end_time is None:
            continue
        overlap = max(0.0, min(end, span.end_time) - max(start, span.start_time))
        if overlap <= 0 and not (start == end == span.start_time == span.end_time):
            continue
        anchored = current_anchor is not None and span.span_id == current_anchor
        fully_inside = span.start_time >= start and span.end_time <= end
        if current_anchor:
            # The event carrier's parent LLM span is the authoritative owner
            # for this boundary. Keep it once for the TestPoint even though its
            # message/tool span may wrap child spans; keep other spans only
            # when wholly inside the interval to prevent double counting.
            if not (anchored or fully_inside):
                continue
        elif span.span_id == previous_anchor:
            continue
        # Even an explicitly anchored owner is partial when its persisted
        # interval crosses the TestPoint boundary. We keep the whole token count
        # (no proportional estimate), but expose the attribution limitation.
        yield span, not fully_inside


def _measurement(*, metric: str, unit: str, value: Any, score: float | int | None = None,
                 attribution_status: str, explanation: str, evidence_refs: list[str],
                 session_id: str, testpoint_id: str) -> EvaluatorResult:
    available = value is not None
    return evaluator_result(score=score if score is not None else value,
        label="measurement" if value is not None else "unavailable",
        explanation=explanation, evidence_refs=evidence_refs,
        status="success" if available else "unavailable",
        value=value, metric=metric, unit=unit,
        result_kind="measurement",
        metadata={"attribution_status": attribution_status, "session_id": session_id})


def testpoint_total_tokens(
    context: EvaluationContext, params: EmptyParams
) -> EvaluatorResult:
    evidence = _trace(context)
    point = context.testpoint
    if point is None:
        raise ValueError("testpoint evaluator requires a bound TestPoint")
    interval = testpoint_interval(evidence, point)
    state = _testpoint_status(evidence, point)
    if state in {"missing_explicit_event", "testpoint_not_reached"}:
        return _measurement(metric="testpoint_total_tokens", unit="tokens", value=None,
            attribution_status=state, explanation=f"{point.test_point_id} completion event unavailable",
            evidence_refs=["trace.events"], session_id=evidence.session_id, testpoint_id=point.test_point_id)
    if state != "exact":
        return _measurement(metric="testpoint_total_tokens", unit="tokens", value=None,
            attribution_status=state,
            explanation=f"{point.test_point_id} event attribution is not exact",
            evidence_refs=["trace.events"], session_id=evidence.session_id, testpoint_id=point.test_point_id)
    if interval is None:
        interval_status = testpoint_interval_status(evidence, point)
        return _measurement(metric="testpoint_total_tokens", unit="tokens", value=None,
            attribution_status=interval_status, explanation=f"{point.test_point_id} interval unavailable: {interval_status}",
            evidence_refs=["trace.testpoint_completion_times"], session_id=evidence.session_id, testpoint_id=point.test_point_id)
    anchors = evidence.testpoint_completion_llm_ids or {}
    if point.previous_test_point_id and anchors.get(point.test_point_id) == anchors.get(point.previous_test_point_id):
        return _measurement(metric="testpoint_total_tokens", unit="tokens", value=None,
            attribution_status="ambiguous", explanation=f"{point.test_point_id} reuses the previous TestPoint LLM owner",
            evidence_refs=["trace.testpoint_completion_llm_ids"], session_id=evidence.session_id, testpoint_id=point.test_point_id)
    matches = list(_overlapping_spans(evidence, interval, point))
    if not matches or any(
        token is None
        for span, _ in matches
        for token in (span.prompt_tokens, span.completion_tokens, span.total_tokens)
    ):
        return _measurement(metric="testpoint_total_tokens", unit="tokens", value=None,
            attribution_status="token_attributes_missing", explanation=f"{point.test_point_id} has no complete LLM token attributes",
            evidence_refs=["trace.llm_spans.token_count"], session_id=evidence.session_id, testpoint_id=point.test_point_id)
    value = {
        "prompt": sum(int(span.prompt_tokens or 0) for span, _ in matches),
        "completion": sum(int(span.completion_tokens or 0) for span, _ in matches),
        "total": sum(int(span.total_tokens) for span, _ in matches),
    }
    status = "partial" if any(clipped for _, clipped in matches) else "exact"
    return _measurement(metric="testpoint_total_tokens", unit="tokens", value=value,
        score=value["total"],
        attribution_status=status, explanation=f"{point.test_point_id} total tokens={value}",
        evidence_refs=["trace.llm_spans.token_count", "trace.testpoint_completion_times"],
        session_id=evidence.session_id, testpoint_id=point.test_point_id)


def testpoint_duration(
    context: EvaluationContext, params: EmptyParams
) -> EvaluatorResult:
    evidence = _trace(context)
    point = context.testpoint
    if point is None:
        raise ValueError("testpoint evaluator requires a bound TestPoint")
    interval = testpoint_interval(evidence, point)
    state = _testpoint_status(evidence, point)
    if state in {"missing_explicit_event", "testpoint_not_reached"}:
        return _measurement(metric="testpoint_duration", unit="seconds", value=None,
            attribution_status=state, explanation=f"{point.test_point_id} completion event unavailable",
            evidence_refs=["trace.events"], session_id=evidence.session_id, testpoint_id=point.test_point_id)
    if state != "exact":
        return _measurement(metric="testpoint_duration", unit="seconds", value=None,
            attribution_status=state,
            explanation=f"{point.test_point_id} event attribution is not exact",
            evidence_refs=["trace.events"], session_id=evidence.session_id, testpoint_id=point.test_point_id)
    if interval is None:
        interval_status = testpoint_interval_status(evidence, point)
        return _measurement(metric="testpoint_duration", unit="seconds", value=None,
            attribution_status=interval_status, explanation=f"{point.test_point_id} interval unavailable: {interval_status}",
            evidence_refs=["trace.testpoint_completion_times"], session_id=evidence.session_id, testpoint_id=point.test_point_id)
    value = max(0.0, interval[1] - interval[0])
    return _measurement(metric="testpoint_duration", unit="seconds", value=value,
        attribution_status="exact", explanation=f"{point.test_point_id} duration={value:.6f}s",
        evidence_refs=["trace.root.start_time", "trace.testpoint_completion_times"],
        session_id=evidence.session_id, testpoint_id=point.test_point_id)


TRACE_EVALUATORS = {
    "duration_within_limit": EvaluatorDefinition(
        evaluator_id="duration_within_limit", family="trace",
        result_kind="assessment", expansion="once", rule=duration_within_limit,
        scope="generic",
        required_evidence=frozenset({"trace_shape"}), aggregation="mean", direction="maximize",
        params_type=DurationWithinLimitParams, normalize_params=normalize_duration_params,
        params_schema={"type": "object", "required": ["max_duration_seconds"], "additionalProperties": False,
                       "properties": {"max_duration_seconds": {"type": "number", "minimum": 0}}},
        ),
    "testpoint_reached": EvaluatorDefinition(
        evaluator_id="testpoint_reached", family="trace",
        result_kind="assessment", expansion="testpoint", rule=testpoint_reached,
        scope="skill",
        required_evidence=frozenset({"testpoint_state"}), aggregation="mean", direction="maximize",
        params_type=EmptyParams, normalize_params=normalize_empty_params,
        params_schema={"type": "object", "additionalProperties": False},
        ),
    "trace_shape": EvaluatorDefinition(
        evaluator_id="trace_shape", family="trace",
        result_kind="assessment", expansion="once", rule=trace_shape,
        scope="generic",
        required_evidence=frozenset({"trace_shape"}), aggregation="mean", direction="maximize",
        params_type=EmptyParams, normalize_params=normalize_empty_params,
        params_schema={"type": "object", "additionalProperties": False},
        ),
    "testpoint_total_tokens": EvaluatorDefinition(
        evaluator_id="testpoint_total_tokens", family="trace",
        result_kind="measurement", expansion="testpoint", rule=testpoint_total_tokens,
        scope="skill",
        metric="testpoint_total_tokens", unit="tokens",
        required_evidence=frozenset({"testpoint_state", "event_timestamp", "event_span_owner", "llm_token_attributes"}),
        aggregation="mean", direction="minimize", params_type=EmptyParams,
        normalize_params=normalize_empty_params,
        params_schema={"type": "object", "additionalProperties": False},
        ),
    "testpoint_duration": EvaluatorDefinition(
        evaluator_id="testpoint_duration", family="trace",
        result_kind="measurement", expansion="testpoint", rule=testpoint_duration,
        scope="skill",
        metric="testpoint_duration", unit="seconds",
        required_evidence=frozenset({"testpoint_state", "event_timestamp"}), aggregation="mean", direction="minimize",
        params_type=EmptyParams, normalize_params=normalize_empty_params,
        params_schema={"type": "object", "additionalProperties": False},
        ),
    "process_quality": EvaluatorDefinition(
        evaluator_id="process_quality", family="trace",
        result_kind="assessment", expansion="once", rule=process_quality,
        scope="skill",
        version="process-quality-v1",
        required_evidence=frozenset({"trace_shape", "testpoint_state"}), aggregation="mean", direction="maximize",
        params_type=ProcessQualityParams, normalize_params=normalize_process_quality_params,
        params_schema={"type": "object", "required": ["max_steps"], "additionalProperties": False,
                       "properties": {"max_steps": {"type": "integer", "minimum": 1}}},
        judge=PROCESS_QUALITY_JUDGE),
    "testpoint_bottleneck_diagnosis": EvaluatorDefinition(
        evaluator_id="testpoint_bottleneck_diagnosis", family="trace",
        result_kind="diagnostic", expansion="testpoint", rule=testpoint_bottleneck_diagnosis,
        scope="skill",
        version="testpoint-bottleneck-diagnosis-v1",
        required_evidence=frozenset({"testpoint_state", "event_timestamp", "trace_content"}),
        aggregation="none", direction="neutral", params_type=BottleneckDiagnosisParams,
        normalize_params=normalize_bottleneck_params,
        params_schema={"type": "object", "required": ["min_duration_seconds", "max_testpoints_per_case", "max_trace_chars", "max_span_chars", "max_skill_chars"],
                       "additionalProperties": False, "properties": {
                           "min_duration_seconds": {"type": "number", "minimum": 0},
                           "max_testpoints_per_case": {"type": "integer", "minimum": 1},
                           "max_trace_chars": {"type": "integer", "minimum": 1},
                           "max_span_chars": {"type": "integer", "minimum": 1},
                           "max_skill_chars": {"type": "integer", "minimum": 1},
                       }},
        judge=TESTPOINT_BOTTLENECK_JUDGE),
}