File size: 23,481 Bytes
b8ea052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Strict execution-completeness audit for typed PVR agent tool plans.

The ledger deliberately separates *an artifact exists* from *a planned call
completed*.  A call is complete only when evidence contains its exact
``call_id``, a recognized terminal status, and valid ``check_id`` provenance.
Dependencies must also have completed successfully before a call, check, or
case is eligible for fixed scoring or a leaderboard.
"""

from __future__ import annotations

import csv
import json
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Iterable, Mapping, Sequence


csv.field_size_limit(16 * 1024 * 1024)


LEDGER_SCHEMA_VERSION = "pvr.agent_execution_ledger.v1"

SUCCESS_STATUSES = frozenset(
    {
        "ok",
        "success",
        "succeeded",
        "complete",
        "completed",
        # A negative observation is still successful tool execution.
        "no_detections",
        "no_detection",
        "no_text",
        "no_matches",
        "empty_result",
    }
)
INSUFFICIENT_STATUSES = frozenset(
    {
        "error",
        "failed",
        "failure",
        "timeout",
        "cancelled",
        "canceled",
        "invalid",
        "insufficient",
        "uncertain",
        "low_confidence",
        "conflict",
        "partial",
    }
)
UNSUPPORTED_STATUSES = frozenset(
    {"unsupported", "not_supported", "unimplemented", "not_implemented", "tool_unavailable"}
)
NONTERMINAL_STATUSES = frozenset({"", "planned", "pending", "queued", "running", "started"})


def _clean_status(value: Any) -> str:
    return str(value or "").strip().lower().replace("-", "_").replace(" ", "_")


def _list_value(value: Any) -> tuple[str, ...]:
    if value is None:
        return ()
    if isinstance(value, (list, tuple, set)):
        return tuple(dict.fromkeys(str(item).strip() for item in value if str(item).strip()))
    text = str(value).strip()
    if not text:
        return ()
    if text[:1] in {"[", "{"}:
        try:
            decoded = json.loads(text)
        except (TypeError, ValueError, json.JSONDecodeError):
            decoded = None
        if isinstance(decoded, list):
            return _list_value(decoded)
    separator = "|" if "|" in text else ","
    return tuple(dict.fromkeys(item.strip() for item in text.split(separator) if item.strip()))


def _bool_text(value: bool) -> str:
    return "true" if value else "false"


def _json_text(value: Any) -> str:
    return json.dumps(value, ensure_ascii=False, separators=(",", ":"))


@dataclass(frozen=True)
class EvidenceRecord:
    """One evidence record loaded from a TSV row or JSON cache payload."""

    source: str
    call_id: str
    status: str
    check_ids: tuple[str, ...]
    case_key: str = ""
    location: str = ""

    @property
    def status_class(self) -> str:
        if self.status in SUCCESS_STATUSES:
            return "success"
        if self.status in INSUFFICIENT_STATUSES:
            return "insufficient"
        if self.status in UNSUPPORTED_STATUSES:
            return "unsupported"
        return "nonterminal"


def read_tsv_rows(path: str | Path) -> list[dict[str, str]]:
    with Path(path).open(encoding="utf-8") as handle:
        return list(csv.DictReader(handle, delimiter="\t"))


def _evidence_from_mapping(
    item: Mapping[str, Any], *, source: Path, location: str, inferred_call_id: str = ""
) -> EvidenceRecord | None:
    status = _clean_status(item.get("status") or item.get("execution_status") or item.get("terminal_status"))
    call_id = str(item.get("call_id") or inferred_call_id or "").strip()
    if not call_id and not status:
        return None
    check_ids = _list_value(item.get("check_ids"))
    singular = str(item.get("check_id") or "").strip()
    if singular and singular not in check_ids:
        check_ids = (*check_ids, singular)
    return EvidenceRecord(
        source=str(source),
        call_id=call_id,
        status=status,
        check_ids=check_ids,
        case_key=str(item.get("case_key") or "").strip(),
        location=location,
    )


def load_evidence_file(path: str | Path) -> list[EvidenceRecord]:
    """Load evidence rows from a TSV or a JSON executor/cache artifact.

    JSON cache filenames may supply ``call_id`` only when their stem begins
    with ``call_``.  This supports current per-call caches while preventing an
    arbitrary JSON file from being mistaken for execution evidence.
    """

    evidence_path = Path(path)
    records: list[EvidenceRecord] = []
    if evidence_path.suffix.lower() == ".tsv":
        for index, item in enumerate(read_tsv_rows(evidence_path), 2):
            record = _evidence_from_mapping(item, source=evidence_path, location=f"row:{index}")
            if record is not None:
                records.append(record)
        return records
    if evidence_path.suffix.lower() != ".json":
        raise ValueError(f"unsupported evidence file type: {evidence_path}")
    payload = json.loads(evidence_path.read_text(encoding="utf-8"))
    inferred = evidence_path.stem if evidence_path.stem.startswith("call_") else ""
    if isinstance(payload, list):
        items: Sequence[Any] = payload
    elif isinstance(payload, dict) and isinstance(payload.get("rows"), list) and payload["rows"]:
        # Executor rows carry finer status and provenance than the cache header.
        items = payload["rows"]
    elif isinstance(payload, dict):
        items = [payload]
    else:
        items = []
    for index, item in enumerate(items):
        if not isinstance(item, Mapping):
            continue
        record = _evidence_from_mapping(
            item,
            source=evidence_path,
            location=f"json:{index}",
            inferred_call_id=inferred,
        )
        if record is not None:
            records.append(record)
    return records


def load_evidence(paths: Iterable[str | Path]) -> list[EvidenceRecord]:
    """Load one or more evidence files or recursively scanned cache dirs."""

    files: list[Path] = []
    for raw_path in paths:
        path = Path(raw_path)
        if path.is_dir():
            files.extend(sorted(item for item in path.rglob("*") if item.suffix.lower() in {".tsv", ".json"}))
        elif path.is_file():
            files.append(path)
        else:
            raise FileNotFoundError(path)
    return [record for path in files for record in load_evidence_file(path)]


def _plan_calls(rows: Sequence[Mapping[str, Any]]) -> dict[str, dict[str, Any]]:
    planned: dict[str, dict[str, Any]] = {}
    for row in rows:
        call_id = str(row.get("call_id") or "").strip()
        if not call_id:
            raise ValueError("tool_calls row is missing call_id")
        if call_id in planned:
            raise ValueError(f"duplicate planned call_id: {call_id}")
        check_ids = _list_value(row.get("check_ids"))
        if not check_ids:
            raise ValueError(f"planned call has no check_ids: {call_id}")
        planned[call_id] = {
            "call_id": call_id,
            "case_key": str(row.get("case_key") or "").strip(),
            "tool": str(row.get("tool") or "").strip(),
            "check_ids": check_ids,
            "depends_on": _list_value(row.get("depends_on")),
        }
    return planned


def _intrinsic_call_row(plan: Mapping[str, Any], records: Sequence[EvidenceRecord]) -> dict[str, Any]:
    planned_checks = set(plan["check_ids"])
    terminal = [record for record in records if record.status_class != "nonterminal"]
    unknown_statuses = sorted({record.status for record in records if record.status not in NONTERMINAL_STATUSES and record.status_class == "nonterminal"})
    provenance_errors: list[str] = []
    evidenced_checks: set[str] = set()
    for record in terminal:
        record_checks = set(record.check_ids)
        evidenced_checks.update(record_checks)
        if not record_checks:
            provenance_errors.append(f"missing_check_id@{record.source}:{record.location}")
        extra = sorted(record_checks - planned_checks)
        if extra:
            provenance_errors.append(f"unplanned_check_ids:{'|'.join(extra)}@{record.source}:{record.location}")
        if record.case_key and plan["case_key"] and record.case_key != plan["case_key"]:
            provenance_errors.append(f"case_key_mismatch:{record.case_key}@{record.source}:{record.location}")
    missing_checks = sorted(planned_checks - evidenced_checks)
    if terminal and missing_checks:
        provenance_errors.append(f"planned_check_ids_without_evidence:{'|'.join(missing_checks)}")
    classes = {record.status_class for record in terminal}
    classes_by_source: dict[str, set[str]] = {}
    for record in terminal:
        classes_by_source.setdefault(record.source, set()).add(record.status_class)
    successful_sources = sorted(source for source, values in classes_by_source.items() if values == {"success"})
    degraded_sources = sorted(source for source, values in classes_by_source.items() if values != {"success"})
    reasons: list[str] = []
    if not records:
        status = "missing"
        reasons.append("no_matching_call_id_evidence")
    elif not terminal:
        status = "missing"
        reasons.append("no_recognized_terminal_evidence_status")
        if unknown_statuses:
            reasons.append(f"unknown_statuses:{'|'.join(unknown_statuses)}")
    elif provenance_errors:
        status = "insufficient"
        reasons.append("invalid_check_id_provenance")
    elif successful_sources:
        # DINO and YOLO-World are redundant backends for one typed detector
        # call.  A complete, provenance-valid result from either backend is
        # sufficient; a failed corroborator must not erase primary evidence.
        status = "success"
        if degraded_sources:
            reasons.append("redundant_backend_degraded")
    elif classes == {"unsupported"}:
        status = "unsupported"
        reasons.append("executor_reported_unsupported")
    elif "insufficient" in classes or len(classes) > 1:
        status = "insufficient"
        reasons.append("terminal_evidence_not_uniformly_successful")
    elif classes == {"success"}:
        status = "success"
    else:
        status = "insufficient"
        reasons.append("unclassified_terminal_evidence")
    return {
        "call_id": plan["call_id"],
        "case_key": plan["case_key"],
        "tool": plan["tool"],
        "planned": True,
        "executed": bool(terminal),
        "status": status,
        "planned_check_ids": sorted(planned_checks),
        "evidenced_check_ids": sorted(evidenced_checks),
        "depends_on": list(plan["depends_on"]),
        "dependency_valid": True,
        "dependency_errors": [],
        "provenance_valid": not provenance_errors,
        "provenance_errors": provenance_errors,
        "evidence_records": len(records),
        "terminal_records": len(terminal),
        "terminal_statuses": sorted({record.status for record in terminal}),
        "evidence_sources": sorted({record.source for record in records}),
        "successful_evidence_sources": successful_sources,
        "degraded_evidence_sources": degraded_sources,
        "reasons": reasons,
    }


def _dependency_errors(call_id: str, planned: Mapping[str, Mapping[str, Any]], rows: Mapping[str, Mapping[str, Any]]) -> list[str]:
    errors: list[str] = []
    visiting: set[str] = set()
    visited: set[str] = set()

    def visit(current: str) -> None:
        if current in visiting:
            errors.append(f"dependency_cycle:{current}")
            return
        if current in visited:
            return
        visiting.add(current)
        for dependency in planned[current]["depends_on"]:
            if dependency not in planned:
                errors.append(f"unknown_dependency:{dependency}")
                continue
            if rows[dependency]["status"] != "success":
                errors.append(f"dependency_not_successful:{dependency}:{rows[dependency]['status']}")
            visit(dependency)
        visiting.remove(current)
        visited.add(current)

    visit(call_id)
    return list(dict.fromkeys(errors))


def _check_plan_map(
    check_plan_rows: Sequence[Mapping[str, Any]] | None,
    planned_calls: Mapping[str, Mapping[str, Any]],
) -> dict[tuple[str, str], dict[str, Any]]:
    checks: dict[tuple[str, str], dict[str, Any]] = {}
    for call in planned_calls.values():
        for check_id in call["check_ids"]:
            key = (call["case_key"], check_id)
            checks.setdefault(key, {"call_ids": [], "plan_status": "executable", "fallback": "", "reasons": []})
            checks[key]["call_ids"].append(call["call_id"])
    for row in check_plan_rows or []:
        key = (str(row.get("case_key") or "").strip(), str(row.get("check_id") or "").strip())
        if not key[1]:
            raise ValueError("check_plans row is missing check_id")
        item = checks.setdefault(key, {"call_ids": [], "plan_status": "", "fallback": "", "reasons": []})
        explicit_calls = _list_value(row.get("tool_call_ids"))
        item["call_ids"] = list(dict.fromkeys((*item["call_ids"], *explicit_calls)))
        item["plan_status"] = str(row.get("status") or item["plan_status"] or "").strip()
        item["fallback"] = str(row.get("fallback") or "").strip()
        item["reasons"] = list(_list_value(row.get("reasons")))
    return checks


def audit_execution(
    tool_call_rows: Sequence[Mapping[str, Any]],
    evidence_records: Sequence[EvidenceRecord],
    *,
    check_plan_rows: Sequence[Mapping[str, Any]] | None = None,
) -> dict[str, Any]:
    """Build strict per-call, per-check, and per-case execution ledgers."""

    planned = _plan_calls(tool_call_rows)
    records_by_call: dict[str, list[EvidenceRecord]] = {call_id: [] for call_id in planned}
    orphan_records: list[EvidenceRecord] = []
    for record in evidence_records:
        if record.call_id in records_by_call:
            records_by_call[record.call_id].append(record)
        else:
            orphan_records.append(record)

    call_by_id = {
        call_id: _intrinsic_call_row(plan, records_by_call[call_id])
        for call_id, plan in planned.items()
    }
    for call_id, row in call_by_id.items():
        dependency_errors = _dependency_errors(call_id, planned, call_by_id)
        terminal_result_owns_adequacy = bool(
            row["tool"] in {"contract_metric_binding", "structured_checker"}
            and row["status"] == "success"
            and row["provenance_valid"]
        )
        # Terminal evaluators are fail-closed: they report ``insufficient``
        # when a missing dependency is actually required for the verdict.  A
        # provenance-valid known terminal result may therefore close the call
        # even when optional generic parser branches declared in the broad
        # plan were unsupported.  Keep the degraded dependency list visible
        # for audit rather than rewriting history.
        row["dependency_valid"] = not dependency_errors or terminal_result_owns_adequacy
        row["dependency_errors"] = dependency_errors
        row["dependency_adequacy_overridden_by_terminal_result"] = bool(
            dependency_errors and terminal_result_owns_adequacy
        )
        if dependency_errors and terminal_result_owns_adequacy:
            row["reasons"].append("known_terminal_result_closed_degraded_declared_dependencies")
        elif dependency_errors and row["status"] == "success":
            row["status"] = "insufficient"
            row["reasons"].append("dependency_validation_failed")
        row["success"] = row["status"] == "success"
        row["insufficient"] = row["status"] == "insufficient"
        row["unsupported"] = row["status"] == "unsupported"
        row["missing"] = row["status"] == "missing"
        row["leaderboard_eligible"] = row["success"] and row["dependency_valid"] and row["provenance_valid"]

    check_map = _check_plan_map(check_plan_rows, planned)
    check_rows: list[dict[str, Any]] = []
    for (case_key, check_id), check in sorted(check_map.items()):
        call_ids = list(dict.fromkeys(check["call_ids"]))
        missing_plan_calls = [call_id for call_id in call_ids if call_id not in call_by_id]
        call_rows = [call_by_id[call_id] for call_id in call_ids if call_id in call_by_id]
        statuses = [row["status"] for row in call_rows]
        plan_status = check["plan_status"] or "executable"
        reasons = list(check["reasons"])
        terminal_tools = {"contract_metric_binding", "structured_checker"}
        decision_rows = [row for row in call_rows if row["tool"] in terminal_tools]
        successful_decisions = [
            row for row in decision_rows
            if row["status"] == "success" and row["dependency_valid"] and row["provenance_valid"]
        ]
        if missing_plan_calls:
            status = "missing"
            reasons.append(f"check_references_unknown_calls:{'|'.join(missing_plan_calls)}")
        elif successful_decisions and plan_status in {"executable", "fallback_required"}:
            # A fail-closed registered metric is the terminal decision node.
            # Its dependency closure is already validated at call level, so
            # a declared semantic fallback and unrelated auxiliary tools cannot
            # erase a conclusive result.  Unknown contract metrics report an
            # insufficient executor status and therefore never enter here.
            status = "success"
            if any(value != "success" for value in statuses):
                terminal_names = {row["tool"] for row in successful_decisions}
                reasons.append(
                    "terminal_structured_checker_succeeded_with_degraded_auxiliary_calls"
                    if "structured_checker" in terminal_names
                    else "terminal_contract_metric_succeeded_with_degraded_auxiliary_calls"
                )
        elif plan_status != "executable":
            status = "unsupported" if not call_rows and any("unsupported" in reason for reason in reasons) else "insufficient"
            reasons.append(f"plan_status:{plan_status}")
        elif not call_rows:
            status = "missing"
            reasons.append("check_has_no_planned_tool_calls")
        else:
            # A registered metric binding is the terminal decision for its
            # check. Its own dependency closure has already been validated at
            # call level, so unrelated auxiliary parser failures must not
            # erase a conclusive, provenance-valid metric. Unknown metrics are
            # still insufficient because their executor never reports ok.
            if all(value == "success" for value in statuses):
                status = "success"
            elif "missing" in statuses:
                status = "missing"
                reasons.append("one_or_more_calls_missing")
            elif statuses and all(value == "unsupported" for value in statuses):
                status = "unsupported"
                reasons.append("all_calls_unsupported")
            else:
                status = "insufficient"
                reasons.append("one_or_more_calls_not_successful")
        leaderboard_eligible = status == "success" and (
            plan_status == "executable" or bool(successful_decisions)
        )
        check_rows.append(
            {
                "case_key": case_key,
                "check_id": check_id,
                "planned": True,
                "executed": bool(call_rows) and all(row["executed"] for row in call_rows),
                "status": status,
                "success": status == "success",
                "insufficient": status == "insufficient",
                "unsupported": status == "unsupported",
                "missing": status == "missing",
                "plan_status": plan_status,
                "fallback": check["fallback"],
                "call_ids": call_ids,
                "call_statuses": {row["call_id"]: row["status"] for row in call_rows},
                "leaderboard_eligible": leaderboard_eligible,
                "reasons": list(dict.fromkeys(reasons)),
            }
        )

    case_rows: list[dict[str, Any]] = []
    case_keys = sorted({row["case_key"] for row in check_rows})
    for case_key in case_keys:
        rows = [row for row in check_rows if row["case_key"] == case_key]
        counts = {status: sum(row["status"] == status for row in rows) for status in ("success", "insufficient", "unsupported", "missing")}
        case_rows.append(
            {
                "case_key": case_key,
                "checks": len(rows),
                "status_counts": counts,
                "leaderboard_eligible": bool(rows) and all(row["leaderboard_eligible"] for row in rows),
            }
        )

    status_counts = {status: sum(row["status"] == status for row in call_by_id.values()) for status in ("success", "insufficient", "unsupported", "missing")}
    check_status_counts = {status: sum(row["status"] == status for row in check_rows) for status in ("success", "insufficient", "unsupported", "missing")}
    summary = {
        "planned_calls": len(call_by_id),
        "planned_checks": len(check_rows),
        "cases": len(case_rows),
        "call_status_counts": status_counts,
        "check_status_counts": check_status_counts,
        "orphan_evidence_records": len(orphan_records),
        "orphan_call_ids": sorted({record.call_id for record in orphan_records if record.call_id}),
        "leaderboard_eligible_cases": sum(row["leaderboard_eligible"] for row in case_rows),
        "leaderboard_eligible": bool(case_rows) and all(row["leaderboard_eligible"] for row in case_rows),
    }
    return {
        "schema_version": LEDGER_SCHEMA_VERSION,
        "summary": summary,
        "calls": [call_by_id[call_id] for call_id in sorted(call_by_id)],
        "checks": check_rows,
        "cases": case_rows,
        "orphan_evidence": [
            {
                "source": record.source,
                "location": record.location,
                "call_id": record.call_id,
                "status": record.status,
                "check_ids": list(record.check_ids),
                "case_key": record.case_key,
            }
            for record in orphan_records
        ],
    }


CALL_LEDGER_FIELDS = (
    "call_id", "case_key", "tool", "planned", "executed", "status", "success", "insufficient",
    "unsupported", "missing", "planned_check_ids", "evidenced_check_ids", "depends_on",
    "dependency_valid", "dependency_errors", "provenance_valid", "provenance_errors", "evidence_records",
    "terminal_records", "terminal_statuses", "evidence_sources", "leaderboard_eligible", "reasons",
)
CHECK_LEDGER_FIELDS = (
    "case_key", "check_id", "planned", "executed", "status", "success", "insufficient", "unsupported",
    "missing", "plan_status", "fallback", "call_ids", "call_statuses", "leaderboard_eligible", "reasons",
)


def tsv_row(row: Mapping[str, Any], fields: Sequence[str]) -> dict[str, Any]:
    """Encode nested ledger values for a stable TSV representation."""

    encoded: dict[str, Any] = {}
    for field in fields:
        value = row.get(field, "")
        if isinstance(value, bool):
            encoded[field] = _bool_text(value)
        elif isinstance(value, (list, tuple, dict)):
            encoded[field] = _json_text(value)
        else:
            encoded[field] = value
    return encoded