File size: 28,033 Bytes
6502024
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Audit H3 trajectory edits with a Friday-hosted multimodal GPT model.

Each audit compares a source-video contact sheet with a generated candidate and
returns two independent judgments:

1. whether protected visual semantics drifted; and
2. whether the requested trajectory edit was actually followed.

Results are append-only JSONL so interrupted campaigns can resume safely.
"""

from __future__ import annotations

import argparse
import base64
import importlib.util
import json
import os
import re
import threading
import time
from collections import Counter, defaultdict
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass
from datetime import UTC, datetime
from pathlib import Path
from typing import Any

import av
import requests  # type: ignore[import-untyped]
from PIL import Image, ImageDraw

REPO_ROOT = Path(__file__).resolve().parents[2]
DEFAULT_CAMPAIGN = REPO_ROOT / "runs" / "injection" / "pilot_full_200_v1"
DEFAULT_OUTPUT = REPO_ROOT / "runs" / "evaluation" / "friday_trajectory_audit_v1"
DEFAULT_CONFIG_MODULE = Path(
    "<internal-path>"
    "Longcat-1p5/evaluate_kangaroo_prompts_gpt55_vision.py"
)

SYSTEM_PROMPT = """你是严格的视频轨迹编辑审计员。输入是一张对比拼图:上半部分是源视频,
下半部分是 H3 编辑候选;每格标有相对时间。你必须把两个问题分开判断:

1. instruction_following:候选是否真正执行了指定的轨迹/状态转移 edit 指令;
2. semantic_drift:除目标变化外,人物/物体身份、数量、场景、机位、光照、非目标动作等
   保护语义是否发生偏离。

不得因为视频可播放就判定成功。看不清时必须输出 INCONCLUSIVE。只根据图像判断视觉事实,
不要声称验证了音频。输出必须是一个 JSON 对象,不得输出 Markdown。字段必须严格如下:
{
  "instruction_following": {
    "verdict": "PASS|PARTIAL|FAIL|INCONCLUSIVE",
    "score": 0到4整数,
    "observed_change": "实际观察到的运动或状态变化",
    "evidence": ["带时间的简短证据"],
    "failure_mode": "none|no_effect|wrong_direction|wrong_endpoint|wrong_path|"
                    "wrong_handoff|timing_failure|ambiguous|other"
  },
  "semantic_drift": {
    "verdict": "NONE|MINOR|MAJOR|INCONCLUSIVE",
    "score": 0到4整数,其中4表示保持最好,
    "unintended_changes": ["非目标变化"],
    "preserved_facts_summary": "保护事实保持情况"
  },
  "naturalness": {
    "verdict": "PASS|FAIL|INCONCLUSIVE",
    "issues": ["明显形变、闪烁、穿模或时序问题"]
  },
  "single_fault_purity": {
    "verdict": "PASS|FAIL|INCONCLUSIVE",
    "secondary_faults": ["与目标错误同等严重的其他错误"]
  },
  "instruction_assessment": {
    "clarity": "CLEAR|AMBIGUOUS|CONTRADICTORY",
    "estimated_difficulty": "EASY|MEDIUM|HARD|TOO_HARD",
    "difficulty_reason": "为何对 H3 容易或困难"
  },
  "overall_accept": true或false,
  "summary": "一句中文结论"
}

overall_accept 只有在 instruction_following=PASS、semantic_drift 为 NONE 或 MINOR、
naturalness=PASS、single_fault_purity=PASS 时才能为 true。"""


@dataclass(frozen=True)
class FridayConfig:
    api_base: str
    api_key: str
    model: str


class RateLimiter:
    def __init__(self, rpm: float) -> None:
        if rpm <= 0:
            raise ValueError("rpm must be positive")
        self._interval = 60.0 / rpm
        self._next = time.monotonic()
        self._lock = threading.Lock()

    def acquire(self) -> None:
        with self._lock:
            now = time.monotonic()
            wait = max(0.0, self._next - now)
            self._next = max(self._next, now) + self._interval
        if wait:
            time.sleep(wait)


def utc_now() -> str:
    return datetime.now(UTC).isoformat()


def load_friday_config(module_path: Path, model_override: str | None) -> FridayConfig:
    api_base = os.environ.get("FRIDAY_API_BASE")
    api_key = os.environ.get("FRIDAY_API_KEY") or os.environ.get("FRIDAY_APP_ID")
    model = model_override or os.environ.get("FRIDAY_MODEL")
    if not api_base or not api_key or not model:
        if not module_path.is_file():
            raise FileNotFoundError(module_path)
        spec = importlib.util.spec_from_file_location("trace_repair_friday_config", module_path)
        if spec is None or spec.loader is None:
            raise RuntimeError(f"cannot load Friday config module: {module_path}")
        module = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(module)
        api_base = api_base or str(module.API_BASE)
        api_key = api_key or str(module.API_KEY)
        model = model or str(module.MODEL)
    if not api_key:
        raise RuntimeError("Friday credential is unavailable")
    return FridayConfig(str(api_base).rstrip("/"), str(api_key), str(model))


def _frame_time(frame: Any, fallback_index: int, fps: float) -> float:
    if frame.time is not None:
        return float(frame.time)
    return fallback_index / fps


def sample_frames(
    video: Path,
    count: int = 8,
    window_seconds: float = 5.0,
) -> list[tuple[float, Image.Image]]:
    with av.open(str(video)) as container:
        stream = container.streams.video[0]
        fps = float(stream.average_rate or 24)
        duration = (
            float(container.duration / av.time_base)
            if container.duration is not None
            else window_seconds
        )
        end = max(0.1, min(duration, window_seconds))
        targets = [index * max(0.0, end - 0.05) / (count - 1) for index in range(count)]
        sampled: list[tuple[float, Image.Image]] = []
        target_index = 0
        last: tuple[float, Image.Image] | None = None
        for frame_index, frame in enumerate(container.decode(stream)):
            stamp = _frame_time(frame, frame_index, fps)
            image = frame.to_image().convert("RGB")
            last = (stamp, image)
            while target_index < len(targets) and stamp >= targets[target_index]:
                sampled.append((stamp, image.copy()))
                target_index += 1
            if target_index == len(targets):
                break
        if last is None:
            raise ValueError(f"video contains no decodable frame: {video}")
        while len(sampled) < count:
            sampled.append((last[0], last[1].copy()))
        return sampled
    raise AssertionError("unreachable")


def _video_grid(
    frames: list[tuple[float, Image.Image]],
    label: str,
    tile_width: int = 256,
    tile_height: int = 144,
) -> Image.Image:
    columns = 4
    rows = 2
    header_height = 28
    caption_height = 24
    grid = Image.new(
        "RGB",
        (columns * tile_width, header_height + rows * (tile_height + caption_height)),
        "white",
    )
    draw = ImageDraw.Draw(grid)
    draw.text((8, 7), label, fill=(0, 0, 0))
    for index, (stamp, frame) in enumerate(frames):
        frame.thumbnail((tile_width, tile_height))
        tile = Image.new("RGB", (tile_width, tile_height), (238, 238, 238))
        tile.paste(frame, ((tile_width - frame.width) // 2, (tile_height - frame.height) // 2))
        x = (index % columns) * tile_width
        y = header_height + (index // columns) * (tile_height + caption_height)
        grid.paste(tile, (x, y))
        draw.text((x + 6, y + tile_height + 4), f"t={stamp:.2f}s", fill=(0, 0, 0))
    return grid


def build_comparison_sheet(source: Path, candidate: Path, output: Path) -> str:
    source_grid = _video_grid(sample_frames(source), "SOURCE / clean reference")
    candidate_grid = _video_grid(sample_frames(candidate), "CANDIDATE / H3 trajectory edit")
    gap = 12
    sheet = Image.new(
        "RGB",
        (
            max(source_grid.width, candidate_grid.width),
            source_grid.height + gap + candidate_grid.height,
        ),
        "white",
    )
    sheet.paste(source_grid, (0, 0))
    sheet.paste(candidate_grid, (0, source_grid.height + gap))
    output.parent.mkdir(parents=True, exist_ok=True)
    sheet.save(output, format="JPEG", quality=88, optimize=True)
    return base64.b64encode(output.read_bytes()).decode("ascii")


def strip_json_fence(content: str) -> str:
    content = content.strip()
    content = re.sub(r"^```(?:json)?\s*", "", content)
    content = re.sub(r"\s*```$", "", content)
    start = content.find("{")
    end = content.rfind("}")
    return content[start : end + 1] if start >= 0 and end > start else content


def validate_result(value: Any) -> dict[str, Any]:
    if not isinstance(value, dict):
        raise ValueError("Friday result is not an object")
    required = {
        "instruction_following",
        "semantic_drift",
        "naturalness",
        "single_fault_purity",
        "instruction_assessment",
        "overall_accept",
        "summary",
    }
    missing = required - value.keys()
    if missing:
        raise ValueError(f"Friday result missing fields: {sorted(missing)}")
    instruction = value["instruction_following"]
    drift = value["semantic_drift"]
    if instruction.get("verdict") not in {"PASS", "PARTIAL", "FAIL", "INCONCLUSIVE"}:
        raise ValueError("invalid instruction_following verdict")
    if drift.get("verdict") not in {"NONE", "MINOR", "MAJOR", "INCONCLUSIVE"}:
        raise ValueError("invalid semantic_drift verdict")
    value["overall_accept"] = (
        instruction["verdict"] == "PASS"
        and drift["verdict"] in {"NONE", "MINOR"}
        and value["naturalness"].get("verdict") == "PASS"
        and value["single_fault_purity"].get("verdict") == "PASS"
    )
    return value


def call_friday(
    *,
    config: FridayConfig,
    limiter: RateLimiter,
    comparison_b64: str,
    context: dict[str, Any],
    timeout: float,
    retries: int,
) -> dict[str, Any]:
    payload = {
        "model": config.model,
        "messages": [
            {"role": "system", "content": SYSTEM_PROMPT},
            {
                "role": "user",
                "content": [
                    {
                        "type": "text",
                        "text": json.dumps(context, ensure_ascii=False),
                    },
                    {
                        "type": "image_url",
                        "image_url": {"url": "data:image/jpeg;base64," + comparison_b64},
                    },
                ],
            },
        ],
    }
    headers = {"Authorization": f"Bearer {config.api_key}", "Content-Type": "application/json"}
    last_error: Exception | None = None
    for attempt in range(1, retries + 1):
        try:
            limiter.acquire()
            session = requests.Session()
            session.trust_env = False
            response = session.post(
                f"{config.api_base}/chat/completions",
                headers=headers,
                json=payload,
                timeout=timeout,
            )
            if response.status_code == 429:
                raise RuntimeError(f"RATE_LIMIT: {response.text[:500]}")
            if response.status_code != 200:
                raise RuntimeError(f"Friday HTTP {response.status_code}: {response.text[:500]}")
            content = response.json()["choices"][0]["message"]["content"]
            return validate_result(json.loads(strip_json_fence(str(content))))
        except Exception as error:  # noqa: BLE001
            last_error = error
            if attempt == retries:
                break
            delay = min(120.0, 5.0 * (2 ** (attempt - 1)))
            if "RATE_LIMIT" in str(error):
                delay = max(delay, 30.0 * attempt)
            time.sleep(delay)
    raise RuntimeError(
        f"Friday audit failed after {retries} attempts: {last_error}"
    ) from last_error


def load_completed(path: Path) -> dict[str, dict[str, Any]]:
    if not path.is_file():
        return {}
    completed: dict[str, dict[str, Any]] = {}
    for line in path.read_text(encoding="utf-8").splitlines():
        if not line.strip():
            continue
        record = json.loads(line)
        if record.get("status") == "completed":
            completed[str(record["candidate_key"])] = record
    return completed


def append_jsonl(path: Path, value: dict[str, Any], lock: threading.Lock) -> None:
    payload = json.dumps(value, ensure_ascii=False) + "\n"
    with lock, path.open("a", encoding="utf-8") as stream:
        stream.write(payload)
        stream.flush()


def candidate_record(row: dict[str, Any]) -> dict[str, Any] | None:
    candidate_dir = Path(row["candidate_dir"])
    video = candidate_dir / "candidate.mp4"
    if not video.is_file():
        return None
    case_dir = candidate_dir.parents[1]
    spec = json.loads((case_dir / "spec.json").read_text(encoding="utf-8"))
    source = Path(spec["source_path"])
    source_observation = spec.get("source_observation", {})
    structured_trajectory = spec.get("structured_trajectory", {})
    source_description = spec.get("source_description") or source_observation.get(
        "source_trajectory"
    )
    target_error = spec.get("target_error") or spec.get("benchmark_edit_instruction")
    if not source_description or not target_error:
        raise ValueError(
            f"unsupported trajectory spec for {row['case_id']}: "
            "missing source description or edit instruction"
        )
    protected_facts = structured_trajectory.get("protected_facts") or [
        "人物和物体的身份、外观、数量保持不变",
        "环境、光照、视觉风格、机位和镜头结构保持不变",
        "除目标轨迹外的动作和事件保持不变",
        "不增加新人物、物体、文字、特效或事件",
    ]
    key = f"{row['case_id']}:{row['seed']}"
    return {
        "candidate_key": key,
        "case_id": row["case_id"],
        "family": row["family"],
        "seed": row["seed"],
        "candidate_dir": str(candidate_dir),
        "candidate_video": str(video),
        "source_video": str(source),
        "source_description": source_description,
        "target_error": target_error,
        "protected_facts": protected_facts,
    }


def audit_one(
    item: dict[str, Any],
    *,
    output_dir: Path,
    config: FridayConfig,
    limiter: RateLimiter,
    timeout: float,
    retries: int,
) -> dict[str, Any]:
    safe_key = item["candidate_key"].replace(":", "__")
    sheet_path = output_dir / "contact_sheets" / f"{safe_key}.jpg"
    comparison_b64 = build_comparison_sheet(
        Path(item["source_video"]), Path(item["candidate_video"]), sheet_path
    )
    context = {
        "case_id": item["case_id"],
        "error_family": item["family"],
        "source_description": item["source_description"],
        "target_edit_instruction": item["target_error"],
        "protected_facts": item["protected_facts"],
        "comparison_layout": "上半部分是源视频0-5秒;下半部分是候选视频0-5秒。",
        "audio_scope": "本次只判断视觉语义;不得声称验证音频。",
    }
    started = time.monotonic()
    result = call_friday(
        config=config,
        limiter=limiter,
        comparison_b64=comparison_b64,
        context=context,
        timeout=timeout,
        retries=retries,
    )
    return {
        **item,
        "status": "completed",
        "audited_at": utc_now(),
        "model": config.model,
        "contact_sheet": str(sheet_path),
        "elapsed_seconds": time.monotonic() - started,
        "result": result,
    }


def empirical_difficulty(pass_rate: float) -> str:
    if pass_rate >= 0.80:
        return "EASY"
    if pass_rate >= 0.50:
        return "MEDIUM"
    if pass_rate >= 0.20:
        return "HARD"
    return "TOO_HARD"


def aggregate_group(records: list[dict[str, Any]]) -> dict[str, Any]:
    total = len(records)
    instruction = Counter(r["result"]["instruction_following"]["verdict"] for r in records)
    drift = Counter(r["result"]["semantic_drift"]["verdict"] for r in records)
    naturalness = Counter(r["result"]["naturalness"]["verdict"] for r in records)
    purity = Counter(r["result"]["single_fault_purity"]["verdict"] for r in records)
    clarity = Counter(r["result"]["instruction_assessment"]["clarity"] for r in records)
    accepted = sum(bool(r["result"]["overall_accept"]) for r in records)
    modes = Counter(
        r["result"]["instruction_following"].get("failure_mode", "other") for r in records
    )
    pass_rate = instruction["PASS"] / total if total else 0.0
    return {
        "total": total,
        "instruction_verdicts": dict(instruction),
        "semantic_drift_verdicts": dict(drift),
        "naturalness_verdicts": dict(naturalness),
        "single_fault_purity_verdicts": dict(purity),
        "instruction_clarity": dict(clarity),
        "instruction_pass_rate": pass_rate,
        "accept_rate": accepted / total if total else 0.0,
        "accepted": accepted,
        "empirical_difficulty": empirical_difficulty(pass_rate),
        "failure_modes": dict(modes),
    }


def write_reports(records: list[dict[str, Any]], output_dir: Path, model: str) -> None:
    records = sorted(records, key=lambda r: (r["case_id"], int(r["seed"])))
    by_case: dict[str, list[dict[str, Any]]] = defaultdict(list)
    by_family: dict[str, list[dict[str, Any]]] = defaultdict(list)
    by_source: dict[str, list[dict[str, Any]]] = defaultdict(list)
    for record in records:
        by_case[record["case_id"]].append(record)
        by_family[record["family"]].append(record)
        by_source[Path(record["source_video"]).name].append(record)
    overall = aggregate_group(records)
    summary: dict[str, Any] = {
        "schema_version": "trace-repair.friday-trajectory-audit-summary.v1",
        "generated_at": utc_now(),
        "model": model,
        "visual_only": True,
        "overall": overall,
        "by_case": {key: aggregate_group(value) for key, value in sorted(by_case.items())},
        "by_family": {key: aggregate_group(value) for key, value in sorted(by_family.items())},
        "by_source": {key: aggregate_group(value) for key, value in sorted(by_source.items())},
    }
    (output_dir / "summary.json").write_text(
        json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
    )

    def pct(value: float) -> str:
        return f"{100 * value:.1f}%"

    instruction = overall["instruction_verdicts"]
    drift = overall["semantic_drift_verdicts"]
    failure_modes = Counter(overall["failure_modes"])
    failure_modes.pop("none", None)
    pass_records = [
        record
        for record in records
        if record["result"]["instruction_following"]["verdict"] == "PASS"
    ]
    pass_major_drift = sum(
        record["result"]["semantic_drift"]["verdict"] == "MAJOR" for record in pass_records
    )
    clear = overall["instruction_clarity"].get("CLEAR", 0)

    lines = [
        "# Friday/GPT 轨迹扰动复核报告",
        "",
        f"- 生成时间:{summary['generated_at']}",
        f"- 模型:`{model}`",
        f"- 已复核候选:**{overall['total']}**",
        f"- 指令完全遵循率:**{pct(overall['instruction_pass_rate'])}**",
        f"- 四门联合接受率:**{pct(overall['accept_rate'])}**",
        "- 范围:仅视觉 contact sheet;音频语义未由 GPT 验证。",
        "",
        "## 总体判定",
        "",
        "| 指标 | 数量 | 比例 |",
        "|---|---:|---:|",
        f"| 指令 PASS | {instruction.get('PASS', 0)} | "
        f"{pct(instruction.get('PASS', 0) / overall['total'])} |",
        f"| 指令 PARTIAL | {instruction.get('PARTIAL', 0)} | "
        f"{pct(instruction.get('PARTIAL', 0) / overall['total'])} |",
        f"| 指令 FAIL | {instruction.get('FAIL', 0)} | "
        f"{pct(instruction.get('FAIL', 0) / overall['total'])} |",
        f"| 语义漂移 NONE | {drift.get('NONE', 0)} | "
        f"{pct(drift.get('NONE', 0) / overall['total'])} |",
        f"| 语义漂移 MINOR | {drift.get('MINOR', 0)} | "
        f"{pct(drift.get('MINOR', 0) / overall['total'])} |",
        f"| 语义漂移 MAJOR | {drift.get('MAJOR', 0)} | "
        f"{pct(drift.get('MAJOR', 0) / overall['total'])} |",
        f"| 四门联合接受 | {overall['accepted']} | {pct(overall['accept_rate'])} |",
        "",
        "## 对 H3 的影响结论",
        "",
        f"- {clear}/{overall['total']} 条 edit 被 GPT 判断为 `CLEAR`;"
        "因此低成功率主要不是语言歧义。",
        f"- 只有 {instruction.get('PASS', 0)}/{overall['total']} 条完全执行 edit;按经验阈值,"
        f"整体属于 `{overall['empirical_difficulty']}`。",
        f"- 在 {len(pass_records)} 条指令 PASS 中,有 {pass_major_drift} 条同时发生 "
        "MAJOR 语义漂移;"
        "这说明“动作改对”不等于“样本可用”。",
        f"- 最终只有 {overall['accepted']}/{overall['total']} 条通过全部四道门,"
        "不应直接把未筛选候选作为训练数据。",
        "",
        "## 指令未遵循的主要模式",
        "",
        "| Failure mode | 数量 | 占非 PASS 样本 |",
        "|---|---:|---:|",
    ]
    non_pass = overall["total"] - instruction.get("PASS", 0)
    for name, count in failure_modes.most_common():
        lines.append(f"| {name} | {count} | {pct(count / non_pass)} |")
    lines += [
        "",
        "## 按错误类型",
        "",
        "| Error family | N | 指令遵循率 | 联合接受率 | 经验难度 |",
        "|---|---:|---:|---:|---|",
    ]
    for family, value in summary["by_family"].items():
        lines.append(
            f"| {family} | {value['total']} | {pct(value['instruction_pass_rate'])} | "
            f"{pct(value['accept_rate'])} | {value['empirical_difficulty']} |"
        )
    lines += [
        "",
        "## 按源视频",
        "",
        "| Source | N | 指令遵循率 | MAJOR 语义漂移率 | 联合接受率 |",
        "|---|---:|---:|---:|---:|",
    ]
    for source, value in summary["by_source"].items():
        major_rate = value["semantic_drift_verdicts"].get("MAJOR", 0) / value["total"]
        lines.append(
            f"| {source} | {value['total']} | {pct(value['instruction_pass_rate'])} | "
            f"{pct(major_rate)} | {pct(value['accept_rate'])} |"
        )
    lines += [
        "",
        "## 按注入规格",
        "",
        "| Case | Family | N | 指令遵循率 | 联合接受率 | 经验难度 | 主要失败模式 |",
        "|---|---|---:|---:|---:|---|---|",
    ]
    for case_id, value in summary["by_case"].items():
        family = by_case[case_id][0]["family"]
        top_modes = ", ".join(
            f"{name}:{count}" for name, count in Counter(value["failure_modes"]).most_common(3)
        )
        lines.append(
            f"| {case_id} | {family} | {value['total']} | "
            f"{pct(value['instruction_pass_rate'])} | {pct(value['accept_rate'])} | "
            f"{value['empirical_difficulty']} | {top_modes} |"
        )
    lines += [
        "",
        "## 判定口径",
        "",
        "- 指令遵循率只统计 `instruction_following=PASS`。",
        "- 联合接受要求:指令遵循 PASS、语义偏离不超过 MINOR、自然度 PASS、单一错误纯度 PASS。",
        "- 经验难度按同一规格的完全遵循率计算:≥80% EASY,≥50% MEDIUM,≥20% HARD,否则 TOO_HARD。",
        "- `PARTIAL` 不计入完全遵循率,但保留在原始 JSONL 供错误分析。",
        "",
        "## 限制",
        "",
        "- GPT 看到的是均匀抽帧拼图,不是连续播放,快速或短暂事件可能被漏判。",
        "- 当前结果是模型复核,不替代两名独立人工标注者和第三人裁决。",
        "- 当前源素材是 H3 官方 demo calibration 集,不是正式 150 项目 benchmark。",
    ]
    (output_dir / "report.md").write_text("\n".join(lines) + "\n", encoding="utf-8")


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser()
    parser.add_argument("--campaign", type=Path, default=DEFAULT_CAMPAIGN)
    parser.add_argument("--output", type=Path, default=DEFAULT_OUTPUT)
    parser.add_argument("--config-module", type=Path, default=DEFAULT_CONFIG_MODULE)
    parser.add_argument("--model")
    parser.add_argument("--workers", type=int, default=4)
    parser.add_argument("--rpm", type=float, default=24.0)
    parser.add_argument("--timeout", type=float, default=240.0)
    parser.add_argument("--retries", type=int, default=5)
    parser.add_argument("--limit", type=int)
    parser.add_argument("--case-id", action="append", default=[])
    return parser.parse_args()


def main() -> int:
    args = parse_args()
    args.output.mkdir(parents=True, exist_ok=True)
    manifest = json.loads((args.campaign / "manifest.json").read_text(encoding="utf-8"))
    items = [candidate_record(row) for row in manifest["candidates"]]
    candidates = [item for item in items if item is not None]
    if args.case_id:
        allowed = set(args.case_id)
        candidates = [item for item in candidates if item["case_id"] in allowed]
    if args.limit is not None:
        candidates = candidates[: args.limit]
    raw_path = args.output / "results.jsonl"
    completed = load_completed(raw_path)
    pending = [item for item in candidates if item["candidate_key"] not in completed]
    config = load_friday_config(args.config_module, args.model)
    limiter = RateLimiter(args.rpm)
    write_lock = threading.Lock()
    print(
        json.dumps(
            {
                "campaign_candidates_with_video": len(candidates),
                "completed": len(completed),
                "pending": len(pending),
                "model": config.model,
                "workers": args.workers,
                "rpm": args.rpm,
            },
            ensure_ascii=False,
        ),
        flush=True,
    )
    failures = 0
    with ThreadPoolExecutor(max_workers=args.workers) as executor:
        futures = {
            executor.submit(
                audit_one,
                item,
                output_dir=args.output,
                config=config,
                limiter=limiter,
                timeout=args.timeout,
                retries=args.retries,
            ): item
            for item in pending
        }
        for position, future in enumerate(as_completed(futures), start=1):
            item = futures[future]
            try:
                record = future.result()
                completed[record["candidate_key"]] = record
                append_jsonl(raw_path, record, write_lock)
                result = record["result"]
                print(
                    f"[{position}/{len(pending)}] {record['candidate_key']} "
                    f"instruction={result['instruction_following']['verdict']} "
                    f"drift={result['semantic_drift']['verdict']} "
                    f"accept={result['overall_accept']}",
                    flush=True,
                )
            except Exception as error:  # noqa: BLE001
                failures += 1
                failure = {
                    **item,
                    "status": "failed",
                    "audited_at": utc_now(),
                    "error": str(error),
                }
                append_jsonl(args.output / "failures.jsonl", failure, write_lock)
                print(f"FAILED {item['candidate_key']}: {error}", flush=True)
    write_reports(list(completed.values()), args.output, config.model)
    print(
        json.dumps(
            {
                "completed": len(completed),
                "failed_this_run": failures,
                "raw_results": str(raw_path),
                "report": str(args.output / "report.md"),
            },
            ensure_ascii=False,
        ),
        flush=True,
    )
    return 1 if failures else 0


if __name__ == "__main__":
    raise SystemExit(main())