File size: 36,947 Bytes
7bdf36e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Clean Codex rollout logs into a tool-use training dataset.

Run:  python3 -I dataset-clean/scripts/build.py [--out DIR] [--files-list FILE] [--workers 8]

Reads  : /home/israel/Downloads/sessions/05/**/rollout-*.jsonl   (read-only, streamed line by line)
Writes : <out>/trajectories.{train,eval}.jsonl, pairs.{train,eval}.jsonl, redactions.jsonl,
         manifest.json   (REPORT.md is produced by report.py after validate.py)
"""
import argparse
import datetime
import glob
import hashlib
import json
import multiprocessing as mp
import os
import random
import re
import sys
import time
from collections import Counter, defaultdict

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)  # python -I does not add the script dir to sys.path
import extract  # noqa: E402
import redact  # noqa: E402

ROOT = "/home/israel/Downloads/sessions"
RAW = ROOT + "/05"
DEFAULT_OUT = ROOT + "/dataset-clean"

SYSTEM_TMPL = ("You are a coding agent working in a local Windows workspace. Use the available tools to inspect "
               "files, edit code, build and run tests. Working directory: {cwd}.")
COMPACT_NOTE = "[Earlier context in this task was compacted. Its summary is not available.]"
GOAL_PREFIX = "Continue working on this goal:\n"
TRUNC_LIMIT, TRUNC_HEAD, TRUNC_TAIL = 4000, 2000, 2000
LARGE_ARG = 20000
SPLIT_SEED = 42
EXIT_RE = re.compile(r"\s*Exit code:\s*(-?\d+)")
UUID_RE = re.compile(r"([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$")

SELECTED = []  # filled in the parent before forking Stage 2 workers
RECOVERY = {}  # turn_id -> manual recovery entry (scripts/manual_recoveries.json)
MANUAL_FILE = os.path.join(HERE, "manual_recoveries.json")


# ============================================================================ helpers
def norm_output(o, stats):
    """Tool output -> plain string."""
    if isinstance(o, str):
        return o
    stats["non_string_output"] += 1
    if o is None:
        return ""
    if isinstance(o, list):
        parts = []
        for it in o:
            if isinstance(it, dict):
                t = it.get("text")
                if isinstance(t, str):
                    parts.append(t)
                elif "image" in str(it.get("type", "")):
                    stats["image_output_omitted"] += 1
                    parts.append("[image omitted]")
                else:
                    parts.append(json.dumps(it, ensure_ascii=False))
            else:
                parts.append(str(it))
        return "\n".join(parts)
    if isinstance(o, dict):
        c = o.get("content")
        if isinstance(c, (str, list)):
            return norm_output(c, stats)
        return json.dumps(o, ensure_ascii=False)
    return str(o)


def is_failed(output_text):
    """Non-zero exit code, or a failed apply_patch."""
    m = EXIT_RE.match(output_text[:200])
    if m and int(m.group(1)) != 0:
        return True
    return output_text.lstrip()[:60].startswith("apply_patch verification failed")


def to_line(obj):
    s = json.dumps(obj, ensure_ascii=False)
    try:
        s.encode("utf-8")
    except UnicodeEncodeError:  # lone surrogates from the raw log: keep them escaped, stay valid JSON
        s = json.dumps(obj, ensure_ascii=True)
    return s


def truncate_output(text, events, stats):
    """4000-char rule: first 2000 + last 2000 with a marker. Redaction events that fall in the removed
    middle are dropped from the log (they no longer exist in the data)."""
    if len(text) <= TRUNC_LIMIT:
        return text, events
    n = len(text) - TRUNC_LIMIT
    new = text[:TRUNC_HEAD] + f"\n[... {n} chars truncated ...]\n" + text[-TRUNC_TAIL:]
    kept = []
    for ev in events:
        s, e = ev[0], ev[1]
        if s < 0 or s < TRUNC_HEAD or e > len(text) - TRUNC_TAIL:
            kept.append(ev)
        else:
            stats["redactions_in_truncated_middle"] += 1
    stats["outputs_truncated"] += 1
    stats["chars_removed_by_truncation"] += n
    return new, kept


# ============================================================================ stage 2: one turn -> rows
def build_segment_messages(seg_events, stats):
    """Convert one segment of raw events into chat messages (pre-redaction).
    Returns (messages, n_calls, n_failed)."""
    call_ids = {e[1] for e in seg_events if e[0] == "C"}
    out_first = {}
    for e in seg_events:
        if e[0] == "O" and e[1] in call_ids and e[1] not in out_first:
            out_first[e[1]] = e
    msgs = []
    pend_text = None
    pend_calls = []
    n_calls = 0
    n_failed = 0
    seen_out = set()
    seen_calls_in_pending = set()

    def flush():
        nonlocal pend_text, pend_calls
        if pend_text is not None or pend_calls:
            m = {"role": "assistant", "content": pend_text}
            if pend_calls:
                m["tool_calls"] = pend_calls
            msgs.append(m)
        pend_text = None
        pend_calls = []

    for e in seg_events:
        k = e[0]
        if k == "A":
            if pend_calls:
                stats["text_after_unanswered_calls"] += 1
            flush()
            pend_text = e[1]
        elif k == "C":
            cid = e[1]
            if cid not in out_first:
                stats["tool_calls_dropped_no_output"] += 1
                continue
            args = e[3]
            kind = e[4]
            if kind == "f" and not isinstance(args, str):
                stats["non_string_arguments"] += 1
                args = json.dumps(args, ensure_ascii=False)
            if kind == "c" and not isinstance(args, str):
                stats["non_string_arguments"] += 1
                args = "" if args is None else json.dumps(args, ensure_ascii=False)
            pend_calls.append({"id": cid, "type": "function",
                               "function": {"name": e[2] or "", "arguments": args, "_kind": kind}})
            n_calls += 1
        elif k == "O":
            cid = e[1]
            if cid not in call_ids:
                stats["tool_outputs_dropped_orphan"] += 1
                continue
            if cid in seen_out:
                stats["tool_outputs_dropped_duplicate"] += 1
                continue
            if out_first.get(cid) is not e:
                continue
            seen_out.add(cid)
            flush()
            text = norm_output(e[2], stats)
            if is_failed(text):
                n_failed += 1
            msgs.append({"role": "tool", "tool_call_id": cid, "content": text})
        elif k == "U":
            flush()
            msgs.append({"role": "user", "content": e[1]})
    flush()
    return msgs, n_calls, n_failed


def build_turn(idx):
    sel = SELECTED[idx]
    inst = sel["inst"]
    meta = sel["file"]
    stats = Counter()
    logs = []          # (row_id, field, kind, sha, replacement)
    res = {"idx": idx, "rows": [], "logs": logs, "stats": stats, "drop": None}

    ctx = inst["ctx"] or {}
    session = meta["session"] or {}
    cwd = ctx.get("cwd") or session.get("cwd") or "unknown"
    events = [e for e in inst["events"]]
    rec = RECOVERY.get(inst["turn_id"])
    rec_kind = rec["kind"] if rec else None

    # ---- task message (step 3) -------------------------------------------------
    task = None
    task_source = None
    if rec_kind == "task_reconstructed":
        task, task_source = rec["task"], "reconstructed"
    for k, e in enumerate(events if task is None else []):
        if e[0] == "U":
            if isinstance(e[1], str) and e[1].strip():
                task, task_source = e[1], "user"
                if any(x[0] in ("A", "C", "O") for x in events[:k]):
                    stats["content_before_first_user_message"] += 1
                del events[k]
                break
    if task is None:
        goal = inst["goal_in_turn"] if rec_kind == "goal_set_inside_turn" else inst["goal"]
        if goal:
            task, task_source = GOAL_PREFIX + goal, "goal"
        else:
            res["drop"] = "no_task_message_and_no_goal"
            if inst["goal_in_turn"]:
                stats["no_task_but_goal_inside_turn"] += 1
            return res
    # drop empty mid-turn user messages
    n0 = len(events)
    events = [e for e in events if not (e[0] == "U" and not (isinstance(e[1], str) and e[1].strip()))]
    stats["empty_user_events_dropped"] += n0 - len(events)

    # ---- segmentation at compaction points (step 7) ---------------------------------
    segs = [[]]
    for e in events:
        if e[0] == "K":
            segs.append([])
        else:
            segs[-1].append(e)
    stats["compaction_markers"] += len(segs) - 1
    cleaned = []
    for si, sg in enumerate(segs):
        empty = not any(x[0] in ("A", "C", "O", "U") for x in sg)
        if empty and si < len(segs) - 1:
            stats["empty_segment_before_compaction_ignored"] += 1   # leading / back-to-back compactions
            continue
        cleaned.append(sg)
    segs = cleaned
    split = len(segs) > 1

    # ---- messages per segment ---------------------------------------------------
    seg_msgs = []
    total_calls = 0
    for sg in segs:
        m, nc, nf = build_segment_messages(sg, stats)
        seg_msgs.append([m, nc, nf])
        total_calls += nc
    if total_calls == 0:
        res["drop"] = "no_tool_calls_with_output"
        return res

    # ---- final answer (step 5) -----------------------------------------------------
    final = inst["last_msg"]
    last_raw = segs[-1][-1] if segs[-1] else None
    if not (isinstance(final, str) and final.strip()):
        # task_complete.last_agent_message is null (plan-mode turns, interrupted goal turns).
        # If the turn really ends on an assistant text message, that text is the final answer.
        if last_raw is not None and last_raw[0] == "A" and last_raw[1].strip():
            final = last_raw[1]
            stats["final_answer_taken_from_last_assistant_text"] += 1
        elif rec_kind == "ends_on_tool_output":
            final = None   # manual decision: keep the turn as it is, ending on the last tool message; nothing is invented
            stats["manual_turn_kept_without_final_answer"] += 1
        else:
            res["drop"] = "no_final_answer_(null_last_agent_message,_turn_ends_on_tool_output)"
            return res
    if final is None:
        pass
    elif last_raw is not None and last_raw[0] == "A" and last_raw[1].strip() == final.strip():
        stats["final_answer_already_last"] += 1
    else:
        seg_msgs[-1][0].append({"role": "assistant", "content": final})
        stats["final_answer_appended"] += 1

    # ---- build rows: redact + truncate + flags -------------------------------------------
    turn_id = inst["turn_id"]
    cache = {}

    def red(text, row_id, field, is_output=False):
        key = text if len(text) < 200000 else None
        if key is not None and key in cache and not is_output:
            new, ev = cache[key]
        else:
            new, ev = redact.redact_text(text)
            if key is not None and not is_output:
                cache[key] = (new, ev)
        if is_output:
            new, ev = truncate_output(new, ev, stats)
        for (_s, _e, kind, sha, rep) in ev:
            logs.append((row_id, field, kind, sha, rep))
            stats["redact:" + kind] += 1
        return new

    def red_args(kind, raw, row_id, field):
        if kind == "c":
            new = red(raw, row_id, field)
            return json.dumps({"input": new})
        obj = None
        try:
            obj = json.loads(raw)
        except (ValueError, RecursionError):
            pass
        if isinstance(obj, (dict, list)):
            sink = []
            new_obj, changed = redact.redact_json_leaves(obj, sink)
            for (kd, sha, rep) in sink:
                logs.append((row_id, field, kd, sha, rep))
                stats["redact:" + kd] += 1
            if not changed:
                return raw
            return json.dumps(new_obj, ensure_ascii=False, separators=(",", ":"))
        return red(raw, row_id, field)

    ts_ctx = None
    for si, (msgs, nc, nf) in enumerate(seg_msgs):
        seg_no = si + 1
        row_id = f"{turn_id}#{seg_no}"
        head = [{"role": "system", "content": SYSTEM_TMPL.format(cwd=cwd)},
                {"role": "user", "content": task}]
        if seg_no > 1:
            head.append({"role": "user", "content": COMPACT_NOTE})
        allm = head + msgs
        out_msgs = []
        calls_seen = Counter()
        n_calls_row = 0
        large = False
        for mi, m in enumerate(allm):
            role = m["role"]
            if role == "tool":
                text = red(m["content"], row_id, f"messages[{mi}].content", is_output=True)
                out_msgs.append({"role": "tool", "tool_call_id": m["tool_call_id"], "content": text})
            elif role == "assistant":
                content = m.get("content")
                if content is not None:
                    content = red(content, row_id, f"messages[{mi}].content")
                om = {"role": "assistant", "content": content}
                if "tool_calls" in m:
                    tcs = []
                    for ci, tc in enumerate(m["tool_calls"]):
                        fn = tc["function"]
                        field = f"messages[{mi}].tool_calls[{ci}].function.arguments"
                        a = red_args(fn["_kind"], fn["arguments"], row_id, field)
                        if len(a) > LARGE_ARG:
                            large = True
                        calls_seen[(fn["name"], a)] += 1
                        n_calls_row += 1
                        tcs.append({"id": tc["id"], "type": "function", "function": {"name": fn["name"], "arguments": a}})
                    om["tool_calls"] = tcs
                out_msgs.append(om)
            else:
                text = red(m["content"], row_id, f"messages[{mi}].content")
                out_msgs.append({"role": role, "content": text})
        # flags (step 9)
        flags = []
        n_dup = sum(c - 1 for c in calls_seen.values())
        if n_calls_row and n_dup / n_calls_row > 0.10:
            flags.append("high_dup_calls")
        last = out_msgs[-1]
        if seg_no == len(seg_msgs) and last["role"] == "assistant" and len(last.get("content") or "") < 200:
            flags.append("short_final")
        if large:
            flags.append("large_patch")
        if rec and seg_no == len(seg_msgs):
            flags.append("manual_recovery")
            if final is None:
                flags.append("ends_on_tool_output")
        elif rec:
            flags.append("manual_recovery")
        if n_calls_row != nc:
            stats["internal_call_count_mismatch"] += 1
        row_cwd = red(cwd, row_id, "cwd")
        row = {
            "id": row_id, "session_id": meta["session_id"], "turn_id": turn_id, "segment": seg_no,
            "segments_total": len(seg_msgs), "compaction_summary_available": not split,
            "source_file": meta["rel"], "thread_source": session.get("thread_source"),
            "agent_role": session.get("agent_role"), "model": ctx.get("model"), "effort": ctx.get("effort"),
            "cwd": row_cwd, "timestamp": inst["ts"], "task_source": task_source,
            "n_tool_calls": n_calls_row, "n_failed_calls": nf, "flags": flags, "messages": out_msgs,
        }
        if split and seg_no < len(seg_msgs):
            stats["non_final_segments"] += 1
            if out_msgs[-1]["role"] != "assistant":
                stats["non_final_segments_ending_in_" + out_msgs[-1]["role"]] += 1
        res["rows"].append((meta["session_id"], row_id, to_line(row)))
    if split:
        stats["turns_split"] += 1
    stats["rows"] += len(seg_msgs)
    return res


# ============================================================================ pairs (step 10)
def build_pairs(file_results, stats):
    """Brief/report pairs for subagent sessions: the own turn(s) whose task is the session's first user message."""
    pairs = []
    pair_logs = []
    seen_briefs = {}
    for fr in file_results:
        sess = fr["session"]
        if not sess or sess.get("thread_source") != "subagent":
            continue
        stats["subagent_files"] += 1
        own = [i for i in fr["instances"] if i["own"]]
        first = None
        for i in own:
            if isinstance(i["first_user"], str) and i["first_user"].strip():
                first = i["first_user"]
                break
        if first is None:
            stats["subagent_files_without_first_user_message"] += 1
            continue
        got_one = False
        for i in own:
            if i["first_user"] != first:
                continue
            if not i["complete"]:
                stats["pair_candidate_turn_not_complete"] += 1
                continue
            report = i["last_msg"]
            if not (isinstance(report, str) and report.strip()):
                stats["pair_candidate_empty_report"] += 1
                continue
            row_id = "pair:" + i["turn_id"]
            brief_r, ev1 = redact.redact_text(first)
            report_r, ev2 = redact.redact_text(report)
            cwd = (i["ctx"] or {}).get("cwd") or sess.get("cwd")
            cwd_r, ev3 = redact.redact_text(cwd) if cwd else (cwd, [])
            if brief_r in seen_briefs:
                stats["pairs_dropped_duplicate_brief"] += 1
                continue
            seen_briefs[brief_r] = i["turn_id"]
            for field, ev in (("brief", ev1), ("report", ev2), ("cwd", ev3)):
                for (_s, _e, kind, sha, rep) in ev:
                    pair_logs.append((row_id, field, kind, sha, rep))
                    stats["pair_redact:" + kind] += 1
            pairs.append({
                "session_id": fr["session_id"],
                "line": to_line({"id": i["turn_id"], "session_id": fr["session_id"], "turn_id": i["turn_id"],
                                 "agent_role": sess.get("agent_role"), "cwd": cwd_r, "brief": brief_r,
                                 "report": report_r}),
                "rel": fr["rel"], "start_line": i["line"], "tool_calls": i["n_calls"],
            })
            got_one = True
        if not got_one:
            stats["subagent_files_without_pair"] += 1
    return pairs, pair_logs


# ============================================================================ main
def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--out", default=DEFAULT_OUT)
    ap.add_argument("--files-list", default=None, help="dev: only process the files listed in this text file")
    ap.add_argument("--workers", type=int, default=8)
    ap.add_argument("--no-manual", action="store_true", help="ignore scripts/manual_recoveries.json (automatic rules only)")
    args = ap.parse_args()
    out = os.path.abspath(args.out)
    for forbidden in (RAW, ROOT + "/dataset-analysis"):
        if out == forbidden or out.startswith(forbidden + "/"):
            sys.exit("refusing to write into read-only input: " + out)
    os.makedirs(out, exist_ok=True)
    t0 = time.time()

    if args.files_list:
        files = [l.strip() for l in open(args.files_list) if l.strip()]
    else:
        files = glob.glob(RAW + "/*/rollout-*.jsonl")
    files = sorted(set(files))
    jobs = [(p, os.path.relpath(p, ROOT)) for p in files]
    jobs_by_size = sorted(jobs, key=lambda j: -os.path.getsize(j[0]))
    print(f"[stage1] {len(jobs)} files, {sum(os.path.getsize(j[0]) for j in jobs)/1e9:.2f} GB", flush=True)

    ctx = mp.get_context("fork")
    results = {}
    with ctx.Pool(args.workers) as pool:
        for k, r in enumerate(pool.imap_unordered(extract.scan_file, jobs_by_size, chunksize=1)):
            results[r["rel"]] = r
            if (k + 1) % 50 == 0 or r["size"] > 3e8:
                print(f"[stage1] {k+1}/{len(jobs)} done ({time.time()-t0:.0f}s) last={r['rel'][-40:]} size={r['size']/1e6:.0f}MB", flush=True)
    file_results = [results[j[1]] for j in jobs]
    file_results.sort(key=lambda r: r["rel"])
    print(f"[stage1] finished in {time.time()-t0:.0f}s", flush=True)

    man = {"manifest_version": 1}
    gstats = Counter()
    for fr in file_results:
        gstats.update(fr["stats"])
        # session id: first session_meta, fallback to the uuid in the file name
        m = UUID_RE.search(fr["rel"])
        fname_id = m.group(1) if m else None
        sess = fr["session"]
        fr["session_id"] = (sess or {}).get("id") or fname_id
        if sess and fname_id and sess.get("id") != fname_id:
            gstats["session_id_differs_from_filename"] += 1
        if not sess and fr["size"] > 0:
            gstats["files_without_session_meta"] += 1
        if fr["stats"].get("malformed_lines") or fr["stats"].get("scalar_lines"):
            gstats["files_with_malformed_or_scalar_lines"] += 1
        if sess and fr["sm_count"] > 1:
            gstats["files_with_embedded_parent_context"] += 1
    man["files_read"] = len(file_results)
    man["files_empty_0_bytes"] = gstats["empty_file"]
    man["files_without_session_meta_nonempty"] = gstats["files_without_session_meta"]
    man["files_with_embedded_parent_context"] = gstats["files_with_embedded_parent_context"]
    man["files_with_malformed_or_scalar_lines"] = gstats["files_with_malformed_or_scalar_lines"]
    man["lines_total"] = gstats["lines"]
    man["blank_lines"] = gstats["blank_lines"]
    man["malformed_lines"] = gstats["malformed_lines"]
    man["scalar_lines"] = gstats["scalar_lines"]
    man["malformed_lines_breakdown"] = {k.split(":", 1)[1]: v for k, v in sorted(gstats.items()) if k.startswith("malformed:")}
    man["records_parsed"] = gstats["records"]
    man["bytes_read"] = sum(fr["size"] for fr in file_results)

    # ---- turn accounting (steps 1-2) ---------------------------------------------------
    inst_all = []
    for fr in file_results:
        for i in fr["instances"]:
            inst_all.append((fr, i))
    reasons = Counter()
    passing = []
    for fr, i in inst_all:
        if i["turn_id"] is None:
            reasons["instance_without_turn_id"] += 1
        elif not i["complete"] and i["n_calls"] == 0:
            reasons["no_task_complete_and_no_tool_calls"] += 1
        elif not i["complete"]:
            reasons["no_task_complete_but_has_tool_calls"] += 1
        elif i["n_calls"] == 0:
            reasons["has_task_complete_but_no_tool_calls"] += 1
        else:
            passing.append((fr, i))
    man["turn_instances_found"] = len(inst_all)
    man["unique_turn_ids_found"] = len({i["turn_id"] for _, i in inst_all})
    man["turn_instances_passing_step1_filter"] = len(passing)
    by_tid = defaultdict(list)
    for fr, i in passing:
        by_tid[i["turn_id"]].append((fr, i))
    selected = []
    dup_dropped = 0
    for tid, lst in by_tid.items():
        lst.sort(key=lambda x: (-x[1]["n_calls"], x[0]["size"], x[0]["rel"], x[1]["line"]))
        selected.append(lst[0])
        dup_dropped += len(lst) - 1
    selected.sort(key=lambda x: (x[0]["rel"], x[1]["line"]))
    reasons["duplicate_turn_id_lower_priority_copy"] = dup_dropped
    # Sensitivity of the step order (spec: filter, then dedup). "Dedup first" would pick the copy with the most calls
    # among ALL copies and then filter; count turn_ids where that gives a different outcome.
    all_by_tid = defaultdict(list)
    for fr, i in inst_all:
        if i["turn_id"] is not None:
            all_by_tid[i["turn_id"]].append((fr, i))
    order_diff = 0
    for tid, lst in all_by_tid.items():
        best = sorted(lst, key=lambda x: (-x[1]["n_calls"], x[0]["size"], x[0]["rel"], x[1]["line"]))[0]
        best_passes = best[1]["complete"] and best[1]["n_calls"] >= 1
        any_pass = any(i["complete"] and i["n_calls"] >= 1 for _, i in lst)
        if any_pass and not best_passes:
            order_diff += 1
    man["dedup_order_sensitivity_turn_ids_that_would_differ_if_dedup_ran_before_filter"] = order_diff
    orphan_with_calls = sum(1 for fr in file_results for o in fr["orphan_turns"] if o["orphan_calls"] > 0)
    orphan_all = sum(len(fr["orphan_turns"]) for fr in file_results)
    man["orphan_turns_task_complete_without_start"] = {"total": orphan_all, "with_tool_calls": orphan_with_calls}
    man["turns_after_dedup"] = len(selected)          # the spec's step-2 number; manual recoveries are added AFTER it
    man["selected_turns_not_belonging_to_files_own_session"] = sum(1 for _, i in selected if not i["own"])
    print(f"[dedup] instances={len(inst_all)} passing={len(passing)} unique_after_dedup={len(selected)}", flush=True)
    selected_core = list(selected)

    # ---- manual recoveries (scripts/manual_recoveries.json) ------------------------------------------
    RECOVERY.clear()
    n_orphans_recovered = 0
    manual_cfg = {"recoveries": [], "left_out": []}
    if not args.no_manual and os.path.exists(MANUAL_FILE):
        manual_cfg = json.load(open(MANUAL_FILE, encoding="utf-8"))
        core_ids = {i["turn_id"] for _, i in selected_core}
        orphan_index = {}
        for fr in file_results:
            for o in fr["orphan_turns"]:
                if o.get("events"):
                    orphan_index[o["turn_id"]] = (fr, o)
        for entry in manual_cfg["recoveries"]:
            tid, kind = entry["turn_id"], entry["kind"]
            RECOVERY[tid] = entry
            if kind == "task_reconstructed":
                if tid not in orphan_index:
                    sys.exit(f"manual recovery {tid}: no orphan turn with that id")
                fr, o = orphan_index[tid]
                started = None
                if o.get("completed_at") is not None and o.get("duration_ms") is not None:
                    st_epoch = int(o["completed_at"]) - round(int(o["duration_ms"]) / 1000)
                    started = datetime.datetime.fromtimestamp(st_epoch, datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
                inst = {"turn_id": tid, "ts": started, "started_at": None, "line": -1,
                        "ctx": {"model": None, "effort": None, "cwd": entry["cwd"]}, "complete": True,
                        "last_msg": o["last_msg"], "n_calls": o["orphan_calls"], "n_compact": 0, "own": True,
                        "goal": None, "goal_in_turn": None, "first_user": None, "n_user_events": 0, "aborted": False,
                        "drop": {}, "passing": True, "events": o["events"], "user_images": 0, "dup_calls": 0,
                        "manual_orphan": True}
                fr2 = dict(fr)
                fr2["session"] = {"thread_source": entry.get("thread_source"), "agent_role": entry.get("agent_role"),
                                  "cwd": entry["cwd"], "id": fr["session_id"]}
                selected.append((fr2, inst))
                n_orphans_recovered += 1
            elif tid not in core_ids:
                sys.exit(f"manual recovery {tid}: not among the {len(core_ids)} turns that passed step 1")
        selected.sort(key=lambda x: (x[0]["rel"], x[1]["line"]))
    reasons["task_complete_without_task_started_(file_corruption)"] = orphan_all - n_orphans_recovered

    # ---- stage 2 ----------------------------------------------------------------------------
    SELECTED.clear()
    for fr, i in selected:
        SELECTED.append({"inst": i, "file": {"rel": fr["rel"], "session": fr["session"], "session_id": fr["session_id"]}})
    s2 = Counter()
    results2 = [None] * len(SELECTED)
    t1 = time.time()
    with ctx.Pool(args.workers) as pool:  # forked after SELECTED is filled: workers share it copy-on-write
        for k, r in enumerate(pool.imap_unordered(build_turn, range(len(SELECTED)), chunksize=1)):
            results2[r["idx"]] = r
    print(f"[stage2] built in {time.time()-t1:.0f}s", flush=True)

    rows = []         # (rel, line_no, seg, session_id, row_id, json)
    logs = []
    turn_drop = Counter()
    for idx, r in enumerate(results2):
        s2.update(r["stats"])
        if r["drop"]:
            turn_drop[r["drop"]] += 1
            continue
        for (sid, row_id, line) in r["rows"]:
            rows.append((sid, row_id, line))
        logs.extend(r["logs"])
    reasons.update({"step3_" + k if k.startswith("no_task") else "step5_" + k: v for k, v in turn_drop.items()})

    # ---- pairs ------------------------------------------------------------------------------
    pstats = Counter()
    pairs, pair_logs = build_pairs(file_results, pstats)
    logs.extend(pair_logs)

    # ---- split by session id (seed 42) ----------------------------------------------------------
    sessions = sorted({r[0] for r in rows} | {p["session_id"] for p in pairs})
    rng = random.Random(SPLIT_SEED)
    shuffled = list(sessions)
    rng.shuffle(shuffled)
    n_eval = max(1, round(0.1 * len(shuffled))) if shuffled else 0
    eval_sessions = set(shuffled[:n_eval])
    outputs = {"trajectories.train.jsonl": [], "trajectories.eval.jsonl": [],
               "pairs.train.jsonl": [], "pairs.eval.jsonl": []}
    for sid, row_id, line in rows:
        outputs["trajectories.eval.jsonl" if sid in eval_sessions else "trajectories.train.jsonl"].append(line)
    for p in pairs:
        outputs["pairs.eval.jsonl" if p["session_id"] in eval_sessions else "pairs.train.jsonl"].append(p["line"])
    sizes = {}
    for name, lines in outputs.items():
        with open(os.path.join(out, name), "w", encoding="utf-8", newline="\n") as f:
            for ln in lines:
                f.write(ln + "\n")
        sizes[name] = os.path.getsize(os.path.join(out, name))
    with open(os.path.join(out, "redactions.jsonl"), "w", encoding="utf-8", newline="\n") as f:
        for (row_id, field, kind, sha, rep) in logs:
            f.write(json.dumps({"row_id": row_id, "field": field, "kind": kind, "sha256_of_original": sha,
                                "replacement": rep}, ensure_ascii=False) + "\n")
    sizes["redactions.jsonl"] = os.path.getsize(os.path.join(out, "redactions.jsonl"))

    # ---- manifest ---------------------------------------------------------------------------------
    n_rows = len(rows)
    kept_idx = [k for k, r in enumerate(results2) if not r["drop"]]
    kept_inst = [selected[k][1] for k in kept_idx]
    man["turns_funnel"] = {
        "turn_instances_found_in_all_files": len(inst_all),
        "  of_which_with_task_complete": sum(1 for _, i in inst_all if i["complete"]),
        "  of_which_with_task_complete_and_>=1_tool_call (step 1)": len(passing),
        "unique_turns_after_dedup (step 2)": len(selected_core),
        "  plus manually recovered turns whose task_started was destroyed": n_orphans_recovered,
        "  with_a_task_message (step 3)": len(selected) - turn_drop["no_task_message_and_no_goal"],
        "  with_a_final_answer_or_manual_exception_and_>=1_paired_call (step 5)": len(kept_idx),
    }
    reasons_clean = {k: v for k, v in reasons.items()}
    man["turns_dropped_per_reason"] = reasons_clean
    man["turns_dropped_per_reason_note"] = (
        "Counts are turn instances (one per task_started per file), AFTER manual recoveries. The first three reasons "
        "are step 1 (embedded parent-history copies dominate them); the orphan row is file corruption; the step3/step5 "
        "rows act on the 395 turns that passed step 1.")
    man["turns_kept"] = len(kept_idx)
    man["segments_total_rows"] = n_rows
    man["turns_split_at_compaction"] = s2["turns_split"]
    man["compaction_reconciliation"] = {
        "selected_turns_containing_a_compacted_record": sum(1 for _, i in selected_core if i["n_compact"] > 0),
        "  of_which_in_kept_turns": sum(1 for i in kept_inst if i["n_compact"] > 0),
        "  of_which_split_into_segments": s2["turns_split"],
        "compaction_markers_ignored_because_nothing_precedes_them": s2["empty_segment_before_compaction_ignored"],
        "extra_segments_created": n_rows - len(kept_idx),
    }
    man["compaction_markers_in_kept_turns"] = s2["compaction_markers"]
    rec_rows = Counter()
    for sid, row_id, line in rows:
        if '"manual_recovery"' in line[:200000] and json.loads(line)["turn_id"] in RECOVERY:
            rec_rows[json.loads(line)["turn_id"]] += 1
    man["manual_recoveries"] = {
        "source": "scripts/manual_recoveries.json" if RECOVERY else None,
        "turns_recovered": sum(1 for t in RECOVERY if rec_rows.get(t)),
        "by_kind": dict(Counter(e["kind"] for t, e in RECOVERY.items() if rec_rows.get(t))),
        "turn_ids": {t: {"kind": RECOVERY[t]["kind"], "rows": rec_rows[t]} for t in RECOVERY if rec_rows.get(t)},
        "requested_but_not_produced": [t for t in RECOVERY if not rec_rows.get(t)],
        "tool_outputs_dropped_because_their_call_was_destroyed": sum(
            results2[k]["stats"]["tool_outputs_dropped_orphan"] for k in range(len(results2))
            if SELECTED[k]["inst"]["turn_id"] in RECOVERY),
        "left_out": manual_cfg.get("left_out", []),
    }
    man["rows"] = {
        "train": len(outputs["trajectories.train.jsonl"]), "eval": len(outputs["trajectories.eval.jsonl"]),
        "pairs_train": len(outputs["pairs.train.jsonl"]), "pairs_eval": len(outputs["pairs.eval.jsonl"]),
    }
    man["split"] = {"unit": "session_id", "seed": SPLIT_SEED,
                    "algorithm": "sorted unique ids -> random.Random(42).shuffle -> first round(10%) to eval",
                    "sessions_total": len(sessions), "sessions_eval": len(eval_sessions),
                    "trajectory_rows_eval_share": round(man["rows"]["eval"] / n_rows, 4) if n_rows else None,
                    "pairs_eval_share": round(man["rows"]["pairs_eval"] / max(1, len(pairs)), 4)}
    man["tool_outputs"] = {"truncated": s2["outputs_truncated"], "chars_removed_by_truncation": s2["chars_removed_by_truncation"],
                           "non_string_outputs_normalised": s2["non_string_output"],
                           "image_parts_replaced_by_placeholder": s2["image_output_omitted"]}
    man["tool_calls"] = {"dropped_no_output": s2["tool_calls_dropped_no_output"],
                         "orphan_outputs_dropped": s2["tool_outputs_dropped_orphan"],
                         "duplicate_outputs_dropped": s2["tool_outputs_dropped_duplicate"],
                         "duplicate_call_ids_dropped": sum(i["dup_calls"] for i in kept_inst)}
    drop_cnt = Counter()
    for i in kept_inst:
        drop_cnt.update(i["drop"])
    man["dropped_records_in_kept_turns"] = dict(sorted(drop_cnt.items(), key=lambda kv: -kv[1]))
    man["user_messages_with_images_in_kept_turns(images_not_included)"] = sum(i["user_images"] for i in kept_inst)
    man["redactions"] = {k.split(":", 1)[1]: v for k, v in sorted(s2.items()) if k.startswith("redact:")}
    man["redactions_total_logged"] = len(logs)
    man["redactions_in_truncated_middle_not_logged"] = s2["redactions_in_truncated_middle"]
    man["pairs"] = {"subagent_files": pstats["subagent_files"], "pairs_written": len(pairs),
                    "dropped_duplicate_brief": pstats["pairs_dropped_duplicate_brief"],
                    "subagent_files_without_pair": pstats["subagent_files_without_pair"],
                    "no_pair_because_brief_turn_never_completed": pstats["pair_candidate_turn_not_complete"],
                    "no_pair_because_no_own_user_message": pstats["subagent_files_without_first_user_message"],
                    "no_pair_because_empty_report": pstats["pair_candidate_empty_report"]}
    man["kept_turn_diagnostics"] = {k: v for k, v in sorted(s2.items()) if not k.startswith("redact:")}
    man["raw_scan_counts_all_files_incl_embedded_replays"] = {k: v for k, v in sorted(gstats.items()) if not k.startswith("malformed:") and k not in (
        "lines", "records", "blank_lines", "malformed_lines", "scalar_lines", "empty_file", "files_without_session_meta",
        "files_with_embedded_parent_context", "files_with_malformed_or_scalar_lines")}
    man["headline"] = {
        "files_read": man["files_read"], "malformed_lines": man["malformed_lines"],
        "turns_found": man["turn_instances_found"], "unique_turn_ids_found": man["unique_turn_ids_found"],
        "turns_after_dedup": man["turns_after_dedup"], "turns_kept": man["turns_kept"],
        "segments": n_rows, "rows_per_split": dict(man["rows"]),
        "outputs_truncated": s2["outputs_truncated"], "chars_removed_by_truncation": s2["chars_removed_by_truncation"],
    }
    man["bytes_per_output_file"] = sizes
    man["bytes_total_output"] = sum(sizes.values())
    man["wall_seconds"] = round(time.time() - t0, 1)
    with open(os.path.join(out, "manifest.json"), "w") as f:
        json.dump(man, f, indent=2, sort_keys=False, ensure_ascii=False)
    print(json.dumps({k: man[k] for k in ("files_read", "turn_instances_found", "turns_after_dedup", "turns_kept",
                                           "segments_total_rows", "rows", "bytes_total_output", "wall_seconds")}, indent=1))


if __name__ == "__main__":
    main()