File size: 43,224 Bytes
43b4299
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Build the public corpus from read-only workspace inputs. Python 3.10+.

Raw recordings are grouped by the audited inventory identity, never by bytes
alone. JSON strings in Parquet preserve heterogeneous source schemas.
"""
from __future__ import annotations

import argparse
import collections
import gzip
import hashlib
import json
import math
import re
import subprocess
from pathlib import Path

import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq

VERSION = "trajectory-study-parser-v1.0.0"
REPO = "pranay5255/agent-trajectory-study-20260930"
FOREST_REPO = "pranay5255/forestofaudits-agent-grader-traces-20260608-backfilled"
FOREST_REV = "b78e6f7adc3e14323d877d61edd94432938ddfe8"
PROJECTS = {"Olmo-RewardHacking": "olmo", "rl_experiments": "qwen", "forestOfAudits": "forest"}
UUID = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
AUTH_KEY = re.compile(r"(?:^|_)(?:api_key|apikey|access_token|auth_token|refresh_token|authorization|authentication|password|passwd|secret|credentials|credential|cookie|client_secret|hf_token|github_token|openai_api_key)(?:$|_)", re.I)
SECRET_PATTERNS = [
    re.compile(r"\b(?:hf_[A-Za-z0-9]{20,}|sk-(?:proj-)?[A-Za-z0-9_-]{20,}|gh[pousr]_[A-Za-z0-9]{20,}|AKIA[A-Z0-9]{16})\b"),
    re.compile(r"(?i)\bBearer\s+[A-Za-z0-9._~+/-]{8,}"),
    re.compile(r"(?i)(?<![A-Za-z0-9_])(?:[A-Z_]{0,64}(?:API_KEY|ACCESS_TOKEN|AUTH_TOKEN|PASSWORD|CLIENT_SECRET|HF_TOKEN|GITHUB_TOKEN)|[\"'](?:api_key|authorization|password|access_token)[\"'])\s*[:=]\s*(?:\"[^\"\n]*\"|'[^'\n]*'|[^\s,;}]+)"),
    re.compile(r"(?i)([?&](?:api_key|token|access_token|key|secret)=)[^&\s\"']+"),
    re.compile(r"https?://[^/\s:@]+:[^/\s@]+@"),
]


def dumps(obj):
    return json.dumps(obj, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False)


def digest(data):
    return hashlib.sha256(data).hexdigest()


def identity(key):
    return digest(key.encode())[:24]


def finite(value):
    return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value)


def nullable_number(value):
    if value is None or value == "":
        return None
    number = float(value)
    return number if math.isfinite(number) else None


class Redactor:
    def __init__(self):
        self.rows = []

    def mark(self, source, coordinate, kind):
        self.rows.append({"source_path": source, "coordinate": coordinate, "kind": kind})

    def text(self, value, source, coordinate):
        for i, pattern in enumerate(SECRET_PATTERNS):
            value, n = pattern.subn("[REDACTED]", value)
            if n:
                self.mark(source, coordinate, f"text_pattern_{i}:{n}")
        return value

    def clean(self, obj, source, coordinate="$"):
        if isinstance(obj, dict):
            out = {}
            for k, v in obj.items():
                coord = coordinate + "." + k
                # Token counts, token IDs and logprobs are scientific telemetry.
                if AUTH_KEY.search(k):
                    self.mark(source, coord, "authentication_field_removed")
                    continue
                out[k] = self.clean(v, source, coord)
            return out
        if isinstance(obj, list):
            # Avoid visiting millions of scalar token IDs individually.
            if not obj or all(isinstance(x, (int, float, bool, type(None))) for x in obj):
                return [x if not isinstance(x, float) or math.isfinite(x) else None for x in obj]
            return [self.clean(v, source, f"{coordinate}[{i}]") for i, v in enumerate(obj)]
        if isinstance(obj, str):
            return self.text(obj, source, coordinate)
        if isinstance(obj, float) and not math.isfinite(obj):
            return None
        return obj


def parse_payload(payload, jsonl=False):
    if not jsonl:
        try:
            return json.loads(payload), []
        except (ValueError, UnicodeError) as exc:
            return None, [{"line": 1, "error": str(exc)}]
    rows, errors = [], []
    for i, line in enumerate(payload.decode("utf-8", errors="replace").splitlines(), 1):
        if not line.strip():
            continue
        try:
            rows.append({"source_line": i, "value": json.loads(line)})
        except ValueError as exc:
            errors.append({"line": i, "error": str(exc)})
    return rows, errors


def flatten_text(value):
    if value is None:
        return ""
    if isinstance(value, str):
        return value
    if isinstance(value, list):
        return "\n".join(flatten_text(v) for v in value)
    if isinstance(value, dict):
        if "text" in value or "content" in value:
            return flatten_text(value.get("text", value.get("content")))
        return dumps(value)
    return str(value)


def commands_from(tool):
    args = tool.get("arguments", tool.get("input", {}))
    if isinstance(args, str):
        try:
            args = json.loads(args)
        except ValueError:
            return args if tool.get("name") in {"bash", "exec_command", "shell"} else ""
    if isinstance(args, dict):
        return flatten_text(args.get("command", args.get("cmd", args.get("keystrokes", ""))))
    return ""


def indicators(command):
    """Overlapping observable command indicators, not claims about intent."""
    c = command.lower()
    return {
        "read": bool(re.search(r"(?:^|[\s;&|])(cat|head|tail|sed|less|nl)\b", c)),
        "search": bool(re.search(r"(?:^|[\s;&|])(rg|grep|find|ls|glob)\b", c)),
        "edit": bool(re.search(r"(?:>>?|apply_patch|sed\s+-i|\.write_text\(|open\([^\n]*[\"']w)", c)),
        "test": bool(re.search(r"\b(pytest|forge test|npm test|cargo test|go test|test\.py|compile|slither)\b", c)),
        "submission": bool(re.search(r"(submission|findings\.json|audit\.md|complete_task|submit|finish)", c)),
        "evaluator_reference": bool(re.search(r"(test\.py|test_cases\.json|reward\.txt|grader|verifier)", c)),
    }


def telemetry(metrics):
    ids = metrics.get("completion_token_ids", metrics.get("output_token_ids"))
    lps = metrics.get("logprobs", metrics.get("selected_logprobs"))
    if not isinstance(ids, list) or not isinstance(lps, list):
        return {"token_count": 0, "logprob_count": 0, "alignment": "unavailable", "nll_sum": None, "surprisal_nats": None}
    # A nested array is a batch; this function accepts one sequence only.
    valid = all(isinstance(t, int) and not isinstance(t, bool) for t in ids) and all(finite(v) and v <= 1e-6 for v in lps)
    aligned = valid and len(ids) == len(lps) and len(ids) > 0
    return {"token_count": len(ids), "logprob_count": len(lps),
            "alignment": "aligned" if aligned else "invalid_or_misaligned",
            "nll_sum": -sum(lps) if aligned else None,
            "surprisal_nats": -sum(lps) / len(lps) if aligned else None}


def normalize(obj, fmt, episode_id, recording_id):
    events = []

    def emit(coord, kind, text="", command="", observation="", metrics=None, rejected=False, step=None, line=1, timestamp=None):
        metrics = metrics or {}
        event = {"episode_id": episode_id, "recording_id": recording_id, "event_index": len(events),
                 "coordinate": coord, "source_line": line, "step_id": str(step) if step is not None else None,
                 "timestamp": str(timestamp) if timestamp is not None else None,
                 "kind": kind, "text": flatten_text(text), "command": flatten_text(command),
                 "observation": flatten_text(observation), "rejected_response": rejected,
                 "prompt_tokens": metrics.get("prompt_tokens"), "completion_tokens": metrics.get("completion_tokens")}
        event.update(telemetry(metrics))
        event.update({f"indicator_{k}": v for k, v in indicators(event["command"]).items()})
        events.append(event)

    if obj is None:
        return events
    if "jsonl" in fmt:
        for wrapped in obj:
            item, line = wrapped["value"], wrapped["source_line"]
            typ = item.get("type", "unknown")
            data = item.get("payload") or {}
            coord = f"$line[{line}]"
            if typ == "response_item":
                typ = data.get("type", "unknown")
                if typ == "message":
                    emit(coord, data.get("role", "message"), data.get("content"), line=line, timestamp=item.get("timestamp"))
                elif typ in {"function_call", "custom_tool_call"}:
                    command = commands_from(data) or (data.get("input", "") if data.get("name") == "apply_patch" else "")
                    emit(coord, "tool_call", data.get("name", ""), command, line=line)
                elif typ in {"function_call_output", "custom_tool_call_output"}:
                    emit(coord, "observation", observation=data.get("output"), line=line)
                elif typ == "reasoning":
                    emit(coord, "reasoning", data.get("summary"), line=line)
            elif typ in {"item.completed", "item.started"}:
                if typ != "item.completed":
                    continue  # incomplete views remain in raw recording; avoid counting twice
                v = item.get("item") or {}
                emit(coord, v.get("type", typ), v.get("text", ""), v.get("command", ""), v.get("aggregated_output", ""), line=line)
            elif typ == "tool_use":
                part = item.get("part") or {}
                state = part.get("state") or {}
                command = commands_from({"input": state.get("input", {}), "name": part.get("tool")})
                emit(coord, "tool_call", part.get("tool", ""), command, state.get("output", ""), line=line)
            elif typ in {"text", "reasoning"}:
                emit(coord, typ, (item.get("part") or {}).get("text", ""), line=line)
            elif typ in {"error", "turn.failed"}:
                emit(coord, "error", item.get("error", item), line=line)
            elif typ in {"turn.completed", "step_finish"}:
                usage = item.get("usage") or (item.get("part") or {}).get("tokens") or {}
                emit(coord, "usage", metrics={"prompt_tokens": usage.get("input_tokens", usage.get("input")),
                                               "completion_tokens": usage.get("output_tokens", usage.get("output"))}, line=line)
        return events
    if isinstance(obj, dict) and isinstance(obj.get("steps"), list):
        for i, s in enumerate(obj["steps"]):
            tools = s.get("tool_calls") or []
            command = "\n".join(commands_from(t) for t in tools)
            obs = flatten_text((s.get("observation") or {}).get("results", []))
            emit(f"$.steps[{i}]", s.get("source", "unknown"), s.get("message", ""), command, obs,
                 s.get("metrics"), step=s.get("step_id"), timestamp=s.get("timestamp"))
        return events
    seq = obj if isinstance(obj, list) else obj.get("messages", [])
    for i, s in enumerate(seq):
        if not isinstance(s, dict):
            continue
        content = flatten_text(s.get("content"))
        command = "\n".join(commands_from(t) for t in s.get("tool_calls", []))
        # Mini-SWE uses shell code fences. This is an observed proposed command.
        if s.get("role") == "assistant" and not command:
            command = "\n".join(re.findall(r"```(?:bash|sh|shell)\s*\n(.*?)```", content, flags=re.S))
        prefix = "$" if isinstance(obj, list) else "$.messages"
        emit(f"{prefix}[{i}]", s.get("role", "unknown"), content, command, timestamp=s.get("timestamp"))
        response = (s.get("extra") or {}).get("model_response_summary")
        if response:
            emit(f"{prefix}[{i}].extra.model_response_summary", "rejected_response", response.get("content"),
                 rejected=True, metrics=response.get("usage"))
    return events


def write_table(out, name, rows):
    path = out / "data" / f"{name}.parquet"
    path.parent.mkdir(parents=True, exist_ok=True)
    # Most nested values are explicitly serialized; do not infer fragile structs.
    frame = pd.DataFrame(rows)
    if frame.empty and not len(frame.columns):
        frame = pd.DataFrame({"empty": pd.Series(dtype="string")})
    frame.to_parquet(path, index=False, compression="zstd", row_group_size=1024)
    return len(frame)


class Builder:
    def __init__(self, root, public, out):
        self.root, self.public, self.out = root, public, out
        self.redactor = Redactor()
        self.sources, self.coverage, self.episodes, self.annotations = [], [], [], []
        self.token_rows, self.joins, self.examples = [], [], []
        self.event_rows = collections.defaultdict(list)
        self.event_parts = collections.Counter()
        self.forest_keys = collections.defaultdict(set)
        self.packet_map = {}
        self.inventory = pd.read_csv(root / "trajectory_inventory/recordings.csv", keep_default_na=False)
        self.selected = self.inventory[self.inventory.project.isin(PROJECTS) & (self.inventory.archive_member == "")]
        self.qwen_base = root / "rl_experiments/artifacts/qwen_rollout_trajectories"
        self.qwen_metrics = {}
        for line in (self.qwen_base / "analysis/trajectory_metrics.jsonl").open():
            o = json.loads(line)
            self.qwen_metrics[o["path"]] = o
        self.qwen_summaries = {}
        for p in (self.qwen_base / "runs").rglob("*summary.json"):
            self.qwen_summaries[p.parent.name] = json.loads(p.read_text())

    def read(self, path, role, collection):
        stored = path.read_bytes()
        payload = gzip.decompress(stored) if path.suffix == ".gz" else stored
        source = str(path.relative_to(self.root)) if path.is_relative_to(self.root) else str(path.relative_to(self.public))
        obj, errors = parse_payload(payload, path.name.endswith((".jsonl", ".jsonl.gz")))
        clean = self.redactor.clean(obj, source) if obj is not None else self.redactor.text(payload.decode("utf-8", errors="replace"), source, "$")
        published = dumps(clean).encode()
        row = {"source_path": source, "collection": collection, "role": role,
               "source_sha256": digest(stored), "source_bytes": len(stored),
               "decoded_source_sha256": digest(payload), "decoded_source_bytes": len(payload),
               "source_encoding": "gzip" if path.suffix == ".gz" else "plain",
               "publication_sha256": digest(published), "publication_bytes": len(published),
               "parser_version": VERSION, "parse_errors_json": dumps(errors)}
        self.sources.append(row)
        return clean, row, errors

    def flush_events(self, collection):
        rows = self.event_rows[collection]
        if not rows:
            return
        target = self.out / "data/events" / collection / f"part-{self.event_parts[collection]:04d}.parquet"
        target.parent.mkdir(parents=True, exist_ok=True)
        # Explicit types keep empty token metrics compatible across all shards.
        strings = {"episode_id", "recording_id", "coordinate", "step_id", "timestamp", "kind", "text", "command", "observation", "alignment"}
        ints = {"event_index", "source_line", "token_count", "logprob_count", "prompt_tokens", "completion_tokens"}
        fields = []
        for key in rows[0]:
            if key in strings:
                dtype = pa.string()
            elif key in ints:
                dtype = pa.int64()
            elif key.startswith("indicator_") or key in {"rejected_response", "canonical_view"}:
                dtype = pa.bool_()
            else:
                dtype = pa.float64()
            fields.append((key, dtype))
        schema = pa.schema(fields)
        pq.write_table(pa.Table.from_pylist(rows, schema=schema), target, compression="zstd", row_group_size=1024)
        self.event_parts[collection] += 1
        self.event_rows[collection] = []

    def add_telemetry(self, episode_id, recording_id, source, coordinate, metrics):
        row = {"episode_id": episode_id, "recording_id": recording_id, "source_path": source,
               "coordinate": coordinate, **telemetry(metrics)}
        self.token_rows.append(row)
        return row

    def forest_identity(self, path):
        """Exact audit trial UUID plus complete branch suffix. Never fuzzy-match."""
        match = UUID.search(path)
        if not match:
            return None
        trial_start = path.rfind("/", 0, match.start()) + 1
        audit = path[trial_start:match.start()].rstrip("_")
        suffix = path[match.end():]
        if suffix.startswith("__"):
            suffix = suffix[suffix.find("/"):]
        suffix = suffix.removeprefix("/agent_data")
        # Trial coordinates must have a file/branch, or the join is uncertain.
        if not suffix or suffix == "/":
            return None
        return audit, match.group(), suffix

    def build_episodes(self):
        grouped = list(self.selected.groupby("episode_key", sort=True))
        print(f"Building {len(grouped)} episode identities", flush=True)
        for n, (key, group) in enumerate(grouped):
            canonical_rows = group[group.canonical == True]
            # The two invalid Qwen files have no canonical episode in the inventory.
            if canonical_rows.empty:
                for record in group.to_dict("records"):
                    obj, src, errors = self.read(self.root / record["path"], "invalid_recording", PROJECTS[record["project"]])
                    rel = f"invalid/{identity(record['path'])}.json.gz"
                    raw_text = self.redactor.text((self.root / record["path"]).read_text(errors="replace"), record["path"], "$raw_invalid")
                    self.bundle(rel, {"data": obj, "source": src, "raw_text_redacted": raw_text})
                    self.coverage.append({"collection": PROJECTS[record["project"]], "unit": "recording_file", "status": "invalid", "source_path": record["path"], "episode_id": None, "details_json": dumps(errors), "detail_path": rel})
                continue
            assert len(canonical_rows) == 1, key
            canonical = canonical_rows.iloc[0].to_dict()
            eid, collection = identity(key), PROJECTS[canonical["project"]]
            views, all_events, canonical_obj, metadata = [], [], None, {}
            result, config, telemetry_rows = {}, {}, []
            for record in group.to_dict("records"):
                path = self.root / record["path"]
                obj, src, errors = self.read(path, record["role"], collection)
                assert src["decoded_source_sha256"] == record["sha256"], f"Source drift: {path}"
                rid = identity(record["path"])
                src.update(episode_id=eid, recording_id=rid, canonical=bool(record["canonical"]))
                events = normalize(obj if not isinstance(obj, str) else None, record["format"], eid, rid)
                for e in events:
                    e["canonical_view"] = bool(record["canonical"])
                # canonical_view is stored in the bundle; Parquet has it too.
                all_events.extend(events)
                views.append({"source": src, "format": record["format"], "data": obj})
                for e in events:
                    if e["alignment"] != "unavailable":
                        telemetry_rows.append({"episode_id": eid, "recording_id": rid, "source_path": src["source_path"], "coordinate": e["coordinate"], **{k:e[k] for k in ["token_count", "logprob_count", "alignment", "nll_sum", "surprisal_nats"]}})
                if record["canonical"]:
                    canonical_obj = obj
                if collection == "forest":
                    fkey = self.forest_identity(record["path"])
                    if fkey:
                        self.forest_keys[fkey].add(eid)
                if errors:
                    self.coverage.append({"collection": collection, "unit": "recording_file", "status": "invalid", "source_path": src["source_path"], "episode_id": eid, "details_json": dumps(errors), "detail_path": f"recordings/{collection}/{eid}.json.gz"})
            path = self.root / canonical["path"]
            # Harbor metadata and token details. Qwen's archived tensors are in ATIF.
            if path.parent.name == "agent":
                for name in ["config.json", "result.json"]:
                    p = path.parent.parent / name
                    if p.exists():
                        obj, src, errors = self.read(p, "trial_metadata", collection)
                        src.update(episode_id=eid, recording_id=identity(str(p.relative_to(self.root))), canonical=False)
                        views.append({"source": src, "format": "metadata-json", "data": obj})
                        if isinstance(obj, dict):
                            if name == "config.json":
                                config = obj
                            else:
                                result = obj
                for p in (path.parent.parent / "verifier").glob("*.json"):
                    obj, src, _ = self.read(p, "verifier_evidence", collection)
                    src.update(episode_id=eid, recording_id=identity(str(p.relative_to(self.root))), canonical=False)
                    views.append({"source": src, "format": "verifier-json", "data": obj})
            metadata = (result.get("agent_result") or {}).get("metadata") or {}
            kwargs = ((config.get("agent") or {}).get("kwargs")) or {}
            if isinstance(canonical_obj, dict):
                info = canonical_obj.get("info") or {}
                c = info.get("config") or {}
                if not config:
                    config = c
            else:
                info = {}
            # Selected-token diagnostics from OLMo rollout_details are separate from
            # normalized action events. Turn alignment is not assumed.
            rd = (result.get("agent_result") or {}).get("rollout_details") or []
            for i, batch in enumerate(rd):
                ids, lps = batch.get("completion_token_ids", []), batch.get("logprobs", [])
                if ids and isinstance(ids[0], list):
                    for j in range(max(len(ids), len(lps))):
                        telemetry_rows.append({"episode_id": eid, "recording_id": identity(str(path.parent.parent / "result.json")), "source_path": str((path.parent.parent / "result.json").relative_to(self.root)), "coordinate": f"$.agent_result.rollout_details[{i}].sequence[{j}]", **telemetry({"completion_token_ids": ids[j] if j < len(ids) else [], "logprobs": lps[j] if j < len(lps) else []})})
                else:
                    telemetry_rows.append({"episode_id": eid, "recording_id": identity(str(path.parent.parent / "result.json")), "source_path": str((path.parent.parent / "result.json").relative_to(self.root)), "coordinate": f"$.agent_result.rollout_details[{i}]", **telemetry(batch)})
            self.token_rows.extend(telemetry_rows)
            self.event_rows[collection].extend(all_events)
            if len(self.event_rows[collection]) >= 10000:
                self.flush_events(collection)
            relative = canonical["path"].removeprefix("rl_experiments/artifacts/qwen_rollout_trajectories/")
            qm = self.qwen_metrics.get(relative, {})
            run = Path(canonical["experiment"]).name
            task = result.get("task_name") or qm.get("task") or info.get("task_name")
            if not task:
                match = re.search(r"/([^/]+)_" + UUID.pattern, canonical["path"])
                task = match.group(1) if match else path.parent.parent.name.split("__")[0] if path.parent.name == "agent" else path.stem
            vr = result.get("verifier_result") or {}
            rewards = vr.get("rewards") or {}
            exception = result.get("exception_info")
            # Gate rewards are retained as grouped annotations, never guessed as
            # per-episode outcomes from repetition order.
            reward = rewards.get("reward")
            if reward is None and rewards:
                reward = rewards.get("score")
            ce = [e for e in all_events if e["canonical_view"]]
            cmds = [e["command"].strip() for e in ce if e["command"].strip()]
            cmd_counts = collections.Counter(cmds)
            observed_text = "\n".join(e["observation"] + "\n" + e["text"] for e in ce).lower()
            parser_errors = sum(bool(re.search(r"parsing errors|no tool calls found|formaterror|was not parsed|parsingerror", e["observation"].lower())) for e in ce)
            model = canonical["model"] or (info.get("config", {}).get("model", {}).get("model_name")) or qm.get("model_name", "")
            model_revision = kwargs.get("checkpoint_revision", metadata.get("model_revision"))
            stage = qm.get("stage") or ("generation_only_gate" if "gate" in run else "stress" if "stress" in run else "diagnostic" if "diag" in run else "rollout_collection")
            if collection == "qwen" and stage == "gate":
                stage = "generation_only_gate"
            submission = info.get("submission")
            stats = info.get("model_stats") or {}
            mode = "detect" if collection == "qwen" else next((m for m in ["detect", "patch", "exploit"] if re.search(r"(?:[/_-]|^)" + m + r"(?:[/_-]|$)", canonical["path"])), "coding" if collection == "olmo" else "unknown")
            aligned = [t for t in telemetry_rows if t["alignment"] == "aligned"]
            total_tokens = sum(t["token_count"] for t in aligned)
            row = {"episode_id": eid, "episode_key": key, "collection": collection, "task": task,
                   "task_checksum": result.get("task_checksum"), "task_mode": mode, "run": run,
                   "collection_stage": stage, "model": model, "model_revision": model_revision,
                   "model_family": kwargs.get("model_family", metadata.get("model_family")),
                   "checkpoint_stage": kwargs.get("model_stage", metadata.get("model_stage")),
                   "harness": kwargs.get("harness_id", canonical["agent"]),
                   "canonical_source_path": canonical["path"], "canonical_recording_id": identity(canonical["path"]),
                   "recording_views": len(group), "status": canonical["status"], "assistant_turns": canonical["assistant_turns"],
                   "events": len(ce), "commands": len(cmds), "unique_commands": len(cmd_counts),
                   "max_command_repetitions": max(cmd_counts.values(), default=0),
                   "text_chars": sum(len(e["text"]) for e in ce), "observation_chars": sum(len(e["observation"]) for e in ce),
                   "rejected_responses": sum(e["rejected_response"] for e in all_events),
                   "reported_prompt_tokens": nullable_number(canonical["reported_prompt_tokens"]),
                   "reported_completion_tokens": nullable_number(canonical["reported_completion_tokens"]),
                   "context_limit": kwargs.get("max_seq_len", self.qwen_summaries.get(run, {}).get("max_seq_len", config.get("model", {}).get("model_kwargs", {}).get("max_model_len"))),
                   "output_limit": kwargs.get("max_output_tokens", ((canonical_obj or {}).get("agent", {}).get("extra", {}).get("llm_kwargs", {}).get("max_tokens")) if isinstance(canonical_obj, dict) else None),
                   "recorded_cost_usd": (result.get("agent_result") or {}).get("cost_usd", stats.get("instance_cost", stats.get("cost"))),
                   "reward": reward, "outcome_status": "observed" if rewards else "unknown",
                   "verifier_results_json": dumps(rewards), "exception_json": dumps(exception),
                   "submission_present": bool(submission) if "submission" in info else None,
                   "exit_status": info.get("exit_status"), "parser_error_indicators": parser_errors,
                   "exception_recorded": bool(exception),
                   "infrastructure_failure_indicator": bool(re.search(r"docker|sandbox|connection|environment.*(?:error|timeout)|verifier.*timeout|http.*error|rate.limit", dumps(exception).lower())),
                   "budget_exhaustion_indicator": bool(re.search(r"context.length|maximum context|step.limit|turn.budget|output.length|token.limit|cost.limit|timeout", observed_text + dumps(exception).lower() + str(info.get("exit_status", "")).lower())),
                   "retry_count": metadata.get("request_retry_count"),
                   "aligned_sequences": len(aligned), "misaligned_sequences": sum(t["alignment"] == "invalid_or_misaligned" for t in telemetry_rows),
                   "aligned_selected_tokens": total_tokens,
                   "selected_token_surprisal_nats": sum(t["nll_sum"] for t in aligned) / total_tokens if total_tokens else None,
                   "detail_path": f"recordings/{collection}/{eid}.json.gz",
                   "retained_experiment2_id": canonical["retained_experiment2_id"] or None,
                   "parser_version": VERSION}
            row.update({f"indicator_{k}_commands": sum(indicators(c)[k] for c in cmds) for k in indicators("")})
            self.episodes.append(row)
            self.bundle(row["detail_path"], {"episode": row, "recordings": views, "events": all_events, "token_diagnostics": telemetry_rows})
            if qm:
                self.annotations.append({"collection": collection, "episode_id": eid, "subject_id": eid, "kind": "existing_command_analysis", "evidence_layer": "derived_observable_indicators", "source_path": "rl_experiments/artifacts/qwen_rollout_trajectories/analysis/trajectory_metrics.jsonl", "source_coordinate": relative, "data_json": dumps(self.redactor.clean(qm, relative))})
            if n % 100 == 0:
                print(f"  {n}/{len(grouped)}", flush=True)
        for c in PROJECTS.values():
            self.flush_events(c)

    def bundle(self, relative, obj):
        path = self.out / relative
        path.parent.mkdir(parents=True, exist_ok=True)
        with path.open("wb") as handle:
            with gzip.GzipFile(fileobj=handle, mode="wb", mtime=0, compresslevel=5) as zipped:
                zipped.write(dumps(obj).encode())

    def import_forest(self):
        for name, kind, expected in [("train_sft_process_all_actions.jsonl", "process", 8633), ("train_sft_gold_clean_final.jsonl", "final", 218), ("rejected_or_unparsed_records.jsonl", "rejection", 74)]:
            path = self.public / name
            raw = path.read_bytes()
            rows = [json.loads(l) for l in raw.splitlines() if l.strip()]
            assert len(rows) == expected
            clean = self.redactor.clean(rows, f"{FOREST_REPO}@{FOREST_REV}/{name}")
            relative = f"derived/forest/{name}.gz"
            # Keep original JSONL row structure and ordering in a compressed copy.
            target = self.out / relative
            target.parent.mkdir(parents=True, exist_ok=True)
            text = "\n".join(dumps(o) for o in clean) + "\n"
            with target.open("wb") as h:
                with gzip.GzipFile(fileobj=h, mode="wb", mtime=0) as z:
                    z.write(text.encode())
            self.sources.append({"source_path": name, "collection": "forest", "role": "public_derived_" + kind, "source_sha256": digest(raw), "source_bytes": len(raw), "publication_sha256": digest(text.encode()), "publication_bytes": len(text.encode()), "public_path": relative, "source_repository": FOREST_REPO, "source_revision": FOREST_REV, "parser_version": VERSION})
            for line, o in enumerate(clean, 1):
                meta = o.get("metadata") or o
                source_path = meta.get("source_path", "")
                k = self.forest_identity(source_path)
                candidates = self.forest_keys.get(k, set()) if k else set()
                eid = next(iter(candidates)) if len(candidates) == 1 else None
                match_status = "verified_trial_uuid_and_branch" if eid else "ambiguous" if candidates else "unmatched_source" if source_path else "gold_without_trajectory"
                example_id = o.get("id") or f"rejection:{line}"
                if source_path:
                    self.joins.append({"example_id": example_id, "example_kind": kind, "public_source_path": source_path, "episode_id": eid, "match_status": match_status, "candidate_count": len(candidates), "identity_json": dumps(k), "source_revision": FOREST_REV})
                messages = o.get("messages") or []
                self.examples.append({"collection": "forest", "example_id": example_id, "example_kind": kind, "episode_id": eid,
                                      "task": o.get("audit_id"), "task_mode": o.get("task_mode"), "source": o.get("source"),
                                      "match_status": match_status, "truncated": bool(meta.get("truncated") or meta.get("assistant_truncated") or meta.get("user_truncated")),
                                      "messages_json": dumps(messages), "metadata_json": dumps(meta), "source_path": name, "source_line": line,
                                      "source_repository": FOREST_REPO, "source_revision": FOREST_REV, "detail_path": relative,
                                      "data_json": dumps(o) if kind == "rejection" else None})
        for name in ["README.md", "dataset_summary.json", "audit_splits.json", ".gitattributes"]:
            p = self.public / name
            raw = p.read_bytes()
            clean = self.redactor.text(raw.decode(), name, "$")
            target = self.out / "provenance/forest_public" / name
            target.parent.mkdir(parents=True, exist_ok=True)
            target.write_text(clean)
            self.sources.append({"source_path": name, "collection": "forest", "role": "public_source_metadata", "source_sha256": digest(raw), "source_bytes": len(raw), "publication_sha256": digest(clean.encode()), "publication_bytes": len(clean.encode()), "public_path": str(target.relative_to(self.out)), "source_repository": FOREST_REPO, "source_revision": FOREST_REV, "parser_version": VERSION})

    def import_judges(self):
        base = self.root / "Olmo-RewardHacking/results/judge-baseline-20260910"
        packet_path = base / "experiment1/frozen-packets.jsonl"
        packets, src, errors = self.read(packet_path, "derived_judge_packets", "olmo")
        assert not errors and len(packets) == 144
        for wrapped in packets:
            o = wrapped["value"]
            pid = o["packet_id"]
            relative = f"derived/olmo/packets/{pid}.json.gz"
            self.bundle(relative, o)
            self.packet_map[o["run_id"]] = pid
            self.examples.append({"collection": "olmo", "example_id": pid, "example_kind": "experiment1_judge_packet", "episode_id": None,
                                  "task": (o["packet"].get("task") or {}).get("task_id") if isinstance(o["packet"].get("task"), dict) else str(o["packet"].get("task")),
                                  "task_mode": "coding", "match_status": "original_raw_run_missing", "truncated": None,
                                  "metadata_json": dumps({k:v for k,v in o.items() if k != "packet"}), "source_path": src["source_path"], "source_line": wrapped["source_line"], "detail_path": relative})
        # One authoritative snapshot per label source. Avoid combined duplicate views.
        for name in ["experiment1-luna-judgments.jsonl", "experiment1/gpt5-trajectory-judgments.jsonl", "experiment1/gpt5-solution-judgments.jsonl", "experiment2-luna-judgments.jsonl", "experiment1-gpt5-vs-luna.jsonl", "experiment1-luna-judgments.attempts.jsonl"]:
            p = base / name
            rows, src, errors = self.read(p, "existing_judge_labels", "olmo")
            assert not errors
            self.bundle(f"derived/olmo/{p.name}.gz", rows)
            retained = {e["retained_experiment2_id"]:e["episode_id"] for e in self.episodes if e["retained_experiment2_id"]}
            for row in rows:
                o = row["value"]
                pid = o.get("packet_id") or self.packet_map.get(o.get("run_id"))
                # Experiment 2 custom_id is not an episode identity; join by the
                # explicit retained trajectory identity if present only.
                eid = retained.get(o.get("trajectory_id"))
                self.annotations.append({"collection": "olmo", "episode_id": eid, "subject_id": pid or o.get("custom_id") or o.get("run_id"),
                                         "kind": p.stem, "evidence_layer": "judge_interpretation" if "attempts" not in name else "judge_execution_log", "source_path": src["source_path"], "source_coordinate": f"line:{row['source_line']}", "data_json": dumps(o)})
        self.coverage.append({"collection": "olmo", "unit": "judge_packet_population", "status": "original_raw_run_missing", "count": 144, "source_path": "Olmo-RewardHacking/runs/think-instruct-pilot/20260822T114511Z", "details_json": dumps({"packets_available": True, "judge_labels_available": True})})

    def import_auxiliary(self):
        datasets = pd.read_csv(self.root / "trajectory_inventory/datasets.csv")
        p = self.root / datasets[datasets.kind == "transition_log"].iloc[0].path
        rows, src, errors = self.read(p, "auxiliary_q09_transition_log", "q09")
        assert not errors and len(rows) == 446
        self.bundle("auxiliary/q09_transitions.json.gz", rows)
        write_table(self.out, "q09_transitions", [{"transition_index": r["source_line"] - 1, "source_path": src["source_path"], "source_line": r["source_line"], "data_json": dumps(r["value"])} for r in rows])
        for p in sorted(self.qwen_base.rglob("*.json")):
            if p.name == "trajectory.json":
                continue
            # Trial verifier evidence is already stored with its episode.
            if "trials" in p.parts:
                continue
            obj, src, _ = self.read(p, "qwen_collection_metadata", "qwen")
            self.bundle("provenance/qwen/" + identity(src["source_path"]) + ".json.gz", obj)
            if p.name.endswith("summary.json"):
                self.annotations.append({"collection": "qwen", "episode_id": None, "subject_id": p.parent.name, "kind": p.stem, "evidence_layer": "recorded_generation_gate", "source_path": src["source_path"], "source_coordinate": "$", "data_json": dumps(obj)})
        remote = json.loads((self.qwen_base / "remote_index.json").read_text())
        extant = {str(p.relative_to(self.qwen_base)) for p in (self.qwen_base / "runs").rglob("trajectory.json")}
        missing = [p for paths in remote["runs"].values() for p in paths if p not in extant]
        assert len(missing) == 368
        for p in missing:
            self.coverage.append({"collection": "qwen", "unit": "candidate_trial", "status": "trajectory_missing_at_archive_time", "source_path": p, "details_json": dumps({"outcome_status": "unknown", "archive_time": "2026-08-17"})})
        base = self.root / "rl_experiments/artifacts/qwen38_27b_64k_gate_001"
        rows, src, errors = self.read(base / "analysis/trajectory_metrics.jsonl", "qwen_27b_summary_only", "qwen")
        assert not errors and len(rows) == 64
        self.bundle("auxiliary/qwen27b_summary_only.json.gz", rows)
        write_table(self.out, "qwen27b_summary_only", [{"summary_index": i, "run": "qwen38_27b_64k_gate_001", "data_json": dumps(r["value"])} for i,r in enumerate(rows)])
        for i, r in enumerate(rows):
            self.coverage.append({"collection": "qwen", "unit": "summary_record", "status": "27b_summary_only", "source_path": src["source_path"], "source_line": r["source_line"], "details_json": dumps(r["value"])})
        for name in ["gate_summary.json", "manifest.json", "analysis/aggregate.json"]:
            obj, src, _ = self.read(base / name, "qwen_27b_summary_metadata", "qwen")
            self.bundle("provenance/qwen/" + identity(src["source_path"]) + ".json.gz", obj)
            if name == "gate_summary.json":
                self.annotations.append({"collection": "qwen", "episode_id": None, "subject_id": base.name, "kind": "gate_summary", "evidence_layer": "recorded_generation_gate_summary_only", "source_path": src["source_path"], "source_coordinate": "$", "data_json": dumps(obj)})

    def finish(self):
        for c in PROJECTS.values():
            write_table(self.out, c, [e for e in self.episodes if e["collection"] == c])
        for name, rows in [("sources", self.sources), ("coverage", self.coverage), ("annotations", self.annotations), ("examples", self.examples), ("forest_joins", self.joins), ("token_diagnostics", self.token_rows), ("redactions", self.redactor.rows)]:
            write_table(self.out, name, rows)
        # Exact selected input inventory, including alternate recording views.
        self.selected.to_csv(self.out / "provenance/recording_inventory.csv", index=False)
        repos = {}
        for project in PROJECTS:
            def git(*args):
                p = subprocess.run(["git", "-C", str(self.root / project), *args], capture_output=True, text=True)
                return p.stdout.strip() if p.returncode == 0 else None
            repos[project] = {"head": git("rev-parse", "HEAD"), "dirty": bool(git("status", "--porcelain")), "remote": git("remote", "get-url", "origin")}
        counts = collections.Counter(e["collection"] for e in self.episodes)
        assert dict(counts) == {"olmo": 570, "qwen": 510, "forest": 371}, counts
        assert len(set(e["episode_id"] for e in self.episodes)) == len(self.episodes)
        summary = {"schema_version": VERSION, "repository": REPO, "episode_counts": dict(counts),
                   "recording_views": self.selected.groupby("project").size().to_dict(),
                   "source_files": len(self.sources), "examples": dict(collections.Counter(e["example_kind"] for e in self.examples)),
                   "join_status": dict(collections.Counter(j["match_status"] for j in self.joins)),
                   "token_alignment": dict(collections.Counter(t["alignment"] for t in self.token_rows)),
                   "coverage": dict(collections.Counter(c["status"] for c in self.coverage)),
                   "redaction_operations": len(self.redactor.rows), "source_repositories": self.redactor.clean(repos, "git_provenance"),
                   "forest_public_repository": FOREST_REPO, "forest_public_revision": FOREST_REV,
                   "scope": "Rollout collections. Qwen generation gates do not demonstrate RL updates. Derived examples are not additional episodes."}
        (self.out / "provenance/build_summary.json").write_text(json.dumps(summary, indent=2) + "\n")
        print(json.dumps(summary, indent=2), flush=True)


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--root", type=Path, default=Path("/home/experiments_base"))
    parser.add_argument("--forest-public", type=Path, default=Path("/home/experiments_base/trajectory_study_inputs/forest_public"))
    parser.add_argument("--out", type=Path, default=Path(__file__).resolve().parents[1])
    args = parser.parse_args()
    (args.out / "provenance").mkdir(parents=True, exist_ok=True)
    builder = Builder(args.root, args.forest_public, args.out)
    builder.build_episodes()
    builder.import_forest()
    builder.import_judges()
    builder.import_auxiliary()
    builder.finish()


if __name__ == "__main__":
    main()