File size: 13,601 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
"""Stage 1: stream one rollout file, split it into turns, keep what later stages need.

Everything is read line by line (never the whole file). Every line is JSON-parsed so that the
malformed / scalar counts are exact. Raw content is only *parsed*, never executed or followed.
"""
import json
import os
import re
from collections import Counter

DROP_RESPONSE_ITEMS = ("reasoning", "web_search_call", "tool_search_call", "tool_search_output")

_CTX_PREFIXES = (
    ("# AGENTS.md instructions", "agents_md"),
    ("<environment_context>", "environment_context"),
    ("<turn_aborted>", "turn_aborted_note"),
    ("<subagent_notification>", "subagent_notification"),
    ("<permissions instructions>", "permissions"),
    ("<model_switch>", "model_switch"),
    ("<collaboration_mode>", "collaboration_mode"),
    ("<skill>", "skill"),
    ("<user_shell_command>", "user_shell_command"),
    ("<INSTRUCTIONS>", "instructions"),
)


def classify_injected(role, text):
    t = (text or "").lstrip()[:60]
    for pre, name in _CTX_PREFIXES:
        if t.startswith(pre):
            return f"{role}:{name}"
    if role == "user":
        return "user:copy_or_other"
    return f"{role}:other"


def message_text(content):
    """Join the text parts of a response_item message content list."""
    if isinstance(content, str):
        return content
    parts = []
    if isinstance(content, list):
        for c in content:
            if isinstance(c, dict):
                tx = c.get("text")
                if isinstance(tx, str):
                    parts.append(tx)
    return "\n".join(parts) if len(parts) != 1 else parts[0]


def uuid7_ms(u):
    """Milliseconds embedded in a UUIDv7 string, or None."""
    try:
        h = u.replace("-", "")
        if len(h) == 32 and h[12] == "7":
            return int(h[:12], 16)
    except Exception:
        pass
    return None


def new_instance(turn_id, ts, started_at, lineno, goal):
    return {
        "turn_id": turn_id, "ts": ts, "started_at": started_at, "line": lineno,
        "ctx": None, "events": [], "call_ids": set(), "complete": False, "last_msg": None,
        "aborted": False, "n_compact": 0, "goal": goal, "goal_in_turn": None, "drop": Counter(),
        "n_user_events": 0, "user_images": 0, "dup_calls": 0,
    }


def scan_file(args):
    path, rel = args
    st = Counter()
    size = os.path.getsize(path)
    file_session = None
    sm_count = 0
    sm_ids = Counter()
    instances = []
    cur = None
    last_by_tid = {}
    last_goal = None
    orphan_calls = 0
    orphan_buf = []        # events seen before any task_started (head of the file destroyed): kept for manual recovery
    orphan_events = Counter()
    orphan_turns = []   # task_complete seen for a turn whose start was lost
    ctx_models = Counter()

    if size == 0:
        st["empty_file"] += 1
        return {"rel": rel, "size": size, "stats": st, "session": None, "sm_count": 0, "foreign_sm": 0, "instances": [],
                "orphan_turns": [], "orphan_events": orphan_events, "pairs": []}

    def open_cur():
        return cur is not None and not cur["complete"]

    with open(path, encoding="utf-8-sig", errors="replace", newline="\n") as f:
        for lineno, line in enumerate(f):
            st["lines"] += 1
            s = line.strip()
            if not s:
                st["blank_lines"] += 1
                continue
            try:
                rec = json.loads(s)
            except (ValueError, RecursionError):
                st["malformed_lines"] += 1
                if "\x00" in s:
                    st["malformed:contains_NUL_bytes"] += 1
                elif "\ufffd" in s:
                    st["malformed:contains_U+FFFD_(undecodable_bytes)"] += 1
                elif s[:1] in "{[":
                    st["malformed:truncated_json"] += 1
                else:
                    st["malformed:non_json_text_fragment"] += 1
                continue
            if not isinstance(rec, dict):
                st["scalar_lines"] += 1
                continue
            t = rec.get("type")
            p = rec.get("payload")
            ts = rec.get("timestamp")
            if not isinstance(p, dict):
                st[f"non_dict_payload:{t}"] += 1
                continue
            pt = p.get("type")
            st["records"] += 1

            if t == "session_meta":
                sm_count += 1
                sm_ids[p.get("id")] += 1
                if file_session is None:
                    file_session = {k: p.get(k) for k in
                                    ("id", "cwd", "thread_source", "agent_role", "agent_nickname", "timestamp")}
                    src = p.get("source")
                    file_session["source_kind"] = list(src.keys())[0] if isinstance(src, dict) and src else src
                continue

            if t == "turn_context":
                tid = p.get("turn_id")
                st["turn_context"] += 1
                if tid is None:
                    continue
                if cur is None or cur["turn_id"] != tid:
                    inst = last_by_tid.get(tid)
                    if inst is None:
                        inst = new_instance(tid, ts, None, lineno, last_goal)
                        instances.append(inst)
                        last_by_tid[tid] = inst
                        st["ctx_without_start"] += 1
                    cur = inst
                if cur["ctx"] is None:
                    cur["ctx"] = {"model": p.get("model"), "effort": p.get("effort"), "cwd": p.get("cwd")}
                    ctx_models[p.get("model")] += 1
                continue

            if t == "compacted":
                st["compacted_records"] += 1
                if open_cur():
                    cur["events"].append(("K",))
                    cur["n_compact"] += 1
                else:
                    st["compacted_outside_turn"] += 1
                continue

            if t == "event_msg":
                if pt == "task_started":
                    tid = p.get("turn_id")
                    inst = new_instance(tid, ts, p.get("started_at"), lineno, last_goal)
                    if tid in last_by_tid:
                        st["restarted_turn_id_in_file"] += 1
                    instances.append(inst)
                    last_by_tid[tid] = inst
                    cur = inst
                    orphan_calls = 0
                elif pt == "task_complete":
                    tid = p.get("turn_id")
                    inst = last_by_tid.get(tid)
                    if inst is None:
                        st["task_complete_unknown_turn"] += 1
                        o = {"turn_id": tid, "orphan_calls": orphan_calls}
                        if orphan_calls > 0:
                            ca, dm = p.get("completed_at"), p.get("duration_ms")
                            o.update({"events": orphan_buf, "last_msg": p.get("last_agent_message"), "ts": ts,
                                      "completed_at": ca, "duration_ms": dm})
                        orphan_turns.append(o)
                        orphan_buf = []
                        orphan_calls = 0
                    else:
                        inst["complete"] = True
                        inst["last_msg"] = p.get("last_agent_message")
                elif pt == "user_message":
                    if open_cur():
                        cur["events"].append(("U", p.get("message")))
                        cur["n_user_events"] += 1
                        if p.get("images") or p.get("local_images"):
                            cur["user_images"] += 1
                    else:
                        orphan_events["event_msg/user_message"] += 1
                        if cur is None:
                            orphan_buf.append(("U", p.get("message")))
                elif pt == "thread_goal_updated":
                    st["goal_events"] += 1
                    g = p.get("goal")
                    obj = g.get("objective") if isinstance(g, dict) else None
                    if isinstance(obj, str) and obj.strip():
                        last_goal = obj
                        if open_cur() and cur["goal_in_turn"] is None:
                            cur["goal_in_turn"] = obj
                elif pt == "turn_aborted":
                    if cur is not None:
                        cur["aborted"] = True
                else:
                    if open_cur():
                        cur["drop"][f"event_msg/{pt}"] += 1
                continue

            if t == "response_item":
                if not open_cur():
                    if cur is None:
                        orphan_events[f"response_item/{pt}"] += 1
                        if pt in ("function_call", "custom_tool_call"):
                            orphan_calls += 1
                            orphan_buf.append(("C", p.get("call_id"), p.get("name"),
                                               p.get("arguments") if pt == "function_call" else p.get("input"),
                                               "f" if pt == "function_call" else "c"))
                        elif pt in ("function_call_output", "custom_tool_call_output"):
                            orphan_buf.append(("O", p.get("call_id"), p.get("output"), "f" if pt == "function_call_output" else "c"))
                        elif pt == "message" and p.get("role") == "assistant":
                            tx = message_text(p.get("content"))
                            if tx and tx.strip():
                                orphan_buf.append(("A", tx))
                    else:
                        st["response_item_after_complete"] += 1
                    continue
                if pt == "message":
                    role = p.get("role")
                    text = message_text(p.get("content"))
                    if role == "assistant":
                        if text and text.strip():
                            cur["events"].append(("A", text))
                        cur["drop"]["assistant_empty"] += 0 if (text and text.strip()) else 1
                    else:
                        cur["drop"]["injected:" + classify_injected(role, text)] += 1
                elif pt in ("function_call", "custom_tool_call"):
                    cid = p.get("call_id")
                    if cid in cur["call_ids"]:
                        cur["dup_calls"] += 1
                        continue
                    cur["call_ids"].add(cid)
                    if pt == "function_call":
                        cur["events"].append(("C", cid, p.get("name"), p.get("arguments"), "f"))
                    else:
                        cur["events"].append(("C", cid, p.get("name"), p.get("input"), "c"))
                elif pt in ("function_call_output", "custom_tool_call_output"):
                    cur["events"].append(("O", p.get("call_id"), p.get("output"), "f" if pt == "function_call_output" else "c"))
                elif pt in DROP_RESPONSE_ITEMS:
                    cur["drop"][pt] += 1
                else:
                    cur["drop"][f"response_item/{pt}"] += 1
                continue

            # anything else (unknown top-level type)
            st[f"other_top_type:{t}"] += 1

    # ---- finalize instances -------------------------------------------------
    # "Own" turn = belongs to the file's own session. A forked subagent file embeds a (thinned) copy of the parent
    # history behind extra session_meta records that carry the PARENT id. Parent turns were created before the
    # child session existed, so their UUIDv7 time is earlier than the child's session id; non-v7 ids only occur
    # in the embedded history. Files whose extra session_meta records all repeat the own id (resumes) are all own.
    own_id = (file_session or {}).get("id")
    foreign_sm = sm_count - sm_ids.get(own_id, 0) if own_id else 0
    sess_ms = uuid7_ms(own_id) if own_id else None
    out_instances = []
    for inst in instances:
        if foreign_sm == 0:
            own = True
        elif sess_ms is not None and inst["turn_id"]:
            tms = uuid7_ms(inst["turn_id"])
            own = tms is not None and tms >= sess_ms - 1000
        else:
            own = inst["ctx"] is not None
        passing = inst["complete"] and len(inst["call_ids"]) >= 1
        first_user = None
        for ev in inst["events"]:
            if ev[0] == "U":
                first_user = ev[1]
                break
        d = {
            "turn_id": inst["turn_id"], "ts": inst["ts"], "started_at": inst["started_at"], "line": inst["line"],
            "ctx": inst["ctx"], "complete": inst["complete"], "last_msg": inst["last_msg"],
            "n_calls": len(inst["call_ids"]), "n_compact": inst["n_compact"], "own": own,
            "goal": inst["goal"], "goal_in_turn": inst["goal_in_turn"], "first_user": first_user,
            "n_user_events": inst["n_user_events"], "aborted": inst["aborted"],
            "user_images": inst["user_images"], "dup_calls": inst["dup_calls"],
            "drop": dict(inst["drop"]), "passing": passing,
            "events": inst["events"] if passing else None,
        }
        out_instances.append(d)
    # only the first_user text of own instances is needed for brief/report pairs; passing instances carry events
    return {"rel": rel, "size": size, "stats": st, "session": file_session, "sm_count": sm_count,
            "foreign_sm": foreign_sm, "instances": out_instances, "orphan_turns": orphan_turns, "orphan_events": orphan_events,
            "ctx_models": ctx_models, "tail_orphan_calls": orphan_calls}