#!/usr/bin/env python3 """Validate dataset-clean outputs. Usage: python3 -I validate.py [OUT_DIR] Writes the results into /manifest.json under "validation" and prints a PASS/FAIL table. Checks: spec checks (JSON parse, tool pairing, final assistant message, forbidden strings), schema/consistency checks, residual-PII scans, and an independent re-parse of the raw logs for every kept turn. """ import glob import json import multiprocessing as mp import os import re import sys from collections import Counter, defaultdict HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) import build # noqa: E402 (module-level code is import-safe; main() is guarded) import redact # noqa: E402 OUT = os.path.abspath(sys.argv[1]) if len(sys.argv) > 1 else build.DEFAULT_OUT ROOT = build.ROOT DATA_FILES = ["trajectories.train.jsonl", "trajectories.eval.jsonl", "pairs.train.jsonl", "pairs.eval.jsonl", "redactions.jsonl"] ROW_KEYS = ["id", "session_id", "turn_id", "segment", "segments_total", "compaction_summary_available", "source_file", "thread_source", "agent_role", "model", "effort", "cwd", "timestamp", "task_source", "n_tool_calls", "n_failed_calls", "flags", "messages"] PAIR_KEYS = ["id", "session_id", "turn_id", "agent_role", "cwd", "brief", "report"] RED_KEYS = ["row_id", "field", "kind", "sha256_of_original", "replacement"] SYSTEM_RE = re.compile(r"^You are a coding agent working in a local Windows workspace\. Use the available tools to " r"inspect files, edit code, build and run tests\. Working directory: .+\.$", re.S) DEV_PATH_RE = re.compile(r"(?i)users(?:\\+|/+)developer") LEFTOVER_USER_PATH = re.compile(r"[A-Za-z]:(?:\\+|/+)(?i:users)(?:\\+|/+)(?!user(?:\\|/|$|\W)|Public\b|Default\b|All Users\b)[^\\/\s\"']+") def _is_cut_replacement(t, end, name): """True when `name` is just the start of our replacement name 'user' cut by output truncation.""" return "user".startswith(name.lower()) and t[end:end + 7].startswith("\n[... ") def _real_user_path_hits(t): n = 0 for (s, e, k, rep) in redact._find_user_paths(t): name = re.split(r"[\\/]+", t[s:e])[-1] if not _is_cut_replacement(t, e, name): n += 1 return n def _leftover_hits(t): n = 0 for m in LEFTOVER_USER_PATH.finditer(t): name = re.split(r"[\\/]+", m.group(0))[-1] if not _is_cut_replacement(t, m.end(), name): n += 1 return n MARKER_RE = re.compile(r"\n\[\.\.\. (\d+) chars truncated \.\.\.\]\n") results = {} MANUAL_CFG = {} if os.path.exists(build.MANUAL_FILE): _cfg = json.load(open(build.MANUAL_FILE, encoding="utf-8")) MANUAL_CFG = {e["turn_id"]: e for e in _cfg["recoveries"]} MANUAL_LEFT_OUT = {e["turn_id"] for e in _cfg.get("left_out", [])} else: MANUAL_LEFT_OUT = set() def record(name, ok, detail=""): results[name] = {"pass": bool(ok), "detail": detail} print(f"[{'PASS' if ok else 'FAIL'}] {name}" + (f" -- {detail}" if detail else ""), flush=True) def load_rows(): rows = {"train": [], "eval": []} pairs = {"train": [], "eval": []} parse_errors = Counter() line_counts = {} for name in DATA_FILES + ["manifest.json"]: path = os.path.join(OUT, name) n = 0 with open(path, encoding="utf-8") as f: if name == "manifest.json": try: json.load(f) n = 1 except ValueError: parse_errors[name] += 1 line_counts[name] = n continue for ln, line in enumerate(f): n += 1 try: obj = json.loads(line) except ValueError: parse_errors[name] += 1 continue if name.startswith("trajectories"): rows["train" if ".train." in name else "eval"].append(obj) elif name.startswith("pairs"): pairs["train" if ".train." in name else "eval"].append(obj) line_counts[name] = n return rows, pairs, parse_errors, line_counts # ----------------------------------------------------------------------------------------------- independent raw re-parse def _new_turn(goal, ts): return {"users": [], "a": [], "calls": [], "outs": [], "last": None, "k": 0, "done": False, "goal": goal, "goal_in": None, "ts": ts, "orphan": False} def raw_turn_view(args): """Independent, deliberately simple re-parse of one raw file for the wanted turn ids. Handles files whose head (task_started ...) was destroyed: records before the first task_started are collected and attached to the turn named by the following task_complete (flagged orphan).""" path, wanted = args res = {} cur = None head = _new_turn(None, None) last_goal = None with open(path, encoding="utf-8-sig", errors="replace", newline="\n") as f: for line in f: line = line.strip() if not line: continue try: o = json.loads(line) except ValueError: continue if not isinstance(o, dict): continue p = o.get("payload") if not isinstance(p, dict): continue t, pt = o.get("type"), p.get("type") if pt == "thread_goal_updated": g = p.get("goal") if isinstance(g, dict) and isinstance(g.get("objective"), str) and g["objective"].strip(): last_goal = g["objective"] d_ = res.get(cur) if cur is not None else None if d_ is not None and not d_["done"] and d_["goal_in"] is None: d_["goal_in"] = last_goal continue if pt == "task_started": cur = p.get("turn_id") if cur in wanted: res[cur] = _new_turn(last_goal, o.get("timestamp")) continue if pt == "task_complete": tid = p.get("turn_id") if tid in res and not res[tid]["done"]: res[tid]["done"] = True res[tid]["last"] = p.get("last_agent_message") elif cur is None: if tid in wanted and tid not in res: head.update(done=True, last=p.get("last_agent_message"), orphan=True) res[tid] = head head = _new_turn(None, None) continue if cur is None: d = head elif cur in res and not res[cur]["done"]: d = res[cur] else: continue if pt == "user_message": d["users"].append(p.get("message")) elif t == "compacted": d["k"] += 1 elif t == "response_item" and pt == "message" and p.get("role") == "assistant": txt = build.extract.message_text(p.get("content")) if txt and txt.strip(): d["a"].append(txt) elif t == "response_item" and pt in ("function_call", "custom_tool_call"): d["calls"].append((p.get("call_id"), p.get("name"), p.get("arguments") if pt == "function_call" else p.get("input"), pt)) elif t == "response_item" and pt in ("function_call_output", "custom_tool_call_output"): d["outs"].append((p.get("call_id"), p.get("output"))) return res def crosscheck(rows_all): by_turn = defaultdict(list) for r in rows_all: by_turn[r["turn_id"]].append(r) for v in by_turn.values(): v.sort(key=lambda r: r["segment"]) by_file = defaultdict(set) for tid, v in by_turn.items(): by_file[v[0]["source_file"]].add(tid) jobs = [(os.path.join(ROOT, rel), tids) for rel, tids in by_file.items()] jobs.sort(key=lambda j: -os.path.getsize(j[0])) raw = {} with mp.get_context("fork").Pool(8) as pool: for part in pool.imap_unordered(raw_turn_view, jobs, chunksize=1): raw.update(part) problems = Counter() examples = defaultdict(list) def bad(kind, tid): problems[kind] += 1 if len(examples[kind]) < 3: examples[kind].append(tid) stats = Counter() for tid, segs in by_turn.items(): rv = raw.get(tid) if rv is None: bad("turn_not_found_in_raw", tid) continue # ---- calls & ids, in order, restricted to calls that have an output out_ids = [] seen = set() for cid, _ in rv["outs"]: if cid not in seen: seen.add(cid) out_ids.append(cid) raw_calls = [] seen_c = set() for c in rv["calls"]: if c[0] in seen_c: continue seen_c.add(c[0]) if c[0] in seen: raw_calls.append(c) row_calls = [] row_outs = [] row_assistant_texts = [] row_users = [] for r in segs: for m in r["messages"]: if m["role"] == "assistant": for tc in m.get("tool_calls") or []: row_calls.append((tc["id"], tc["function"]["name"], tc["function"]["arguments"])) if m.get("content"): row_assistant_texts.append(m["content"]) elif m["role"] == "tool": row_outs.append((m["tool_call_id"], m["content"])) elif m["role"] == "user": row_users.append(m["content"]) if [c[0] for c in raw_calls] != [c[0] for c in row_calls]: bad("call_id_sequence_mismatch", tid) else: for rc, wc in zip(raw_calls, row_calls): if rc[1] != wc[1]: bad("tool_name_mismatch", tid) break if rc[3] == "custom_tool_call": want = json.dumps({"input": redact.redact_text(rc[2] if isinstance(rc[2], str) else "")[0]}) if want != wc[2]: bad("custom_tool_input_mismatch", tid) break else: try: a = json.loads(rc[2]) except (ValueError, TypeError): a = None b = None try: b = json.loads(wc[2]) except ValueError: pass if a is None: if redact.redact_text(rc[2] or "")[0] != wc[2]: bad("arguments_mismatch", tid) break else: want, _ = redact.redact_json_leaves(a, []) if want != b: bad("arguments_mismatch", tid) break # ---- outputs (first output per call id, same order as in the rows) first_out = {} for cid, o in rv["outs"]: first_out.setdefault(cid, o) st = Counter() for cid, content in row_outs: if cid not in first_out: bad("output_without_raw_counterpart", tid) continue txt = build.norm_output(first_out[cid], st) new, ev = redact.redact_text(txt) new, _ = build.truncate_output(new, ev, st) if new != content: bad("output_content_mismatch", tid) # ---- assistant texts: row texts == redacted raw texts in order, optionally followed by the appended final answer want_a = [redact.redact_text(x)[0] for x in rv["a"]] got_a = list(row_assistant_texts) last_ok = isinstance(rv["last"], str) and rv["last"].strip() fin_r = redact.redact_text(rv["last"])[0] if last_ok else None if got_a == want_a: stats["final_already_last_or_taken_from_last_text"] += 1 elif fin_r is not None and got_a == want_a + [fin_r]: stats["final_appended"] += 1 else: bad("assistant_text_sequence_mismatch", tid) # ---- task message users_raw = [u for u in rv["users"] if isinstance(u, str) and u.strip()] task = segs[0]["messages"][1]["content"] mc = MANUAL_CFG.get(tid) if mc and mc["kind"] == "task_reconstructed": if task != redact.redact_text(mc["task"])[0] or segs[0]["task_source"] != "reconstructed" or not rv["orphan"]: bad("reconstructed_task_mismatch", tid) elif users_raw: if task != redact.redact_text(users_raw[0])[0]: bad("task_mismatch_user", tid) if segs[0]["task_source"] != "user": bad("task_source_mismatch", tid) mids = [redact.redact_text(u)[0] for u in users_raw[1:]] got_mids = [u for r in segs for u in [m["content"] for m in r["messages"][2:] if m["role"] == "user"] if u != build.COMPACT_NOTE] if mids != got_mids: bad("mid_turn_user_messages_mismatch", tid) else: goal = rv["goal_in"] if (mc and mc["kind"] == "goal_set_inside_turn") else rv["goal"] want = redact.redact_text(build.GOAL_PREFIX + (goal or ""))[0] if task != want or segs[0]["task_source"] != "goal": bad("task_mismatch_goal", tid) if len(segs) > 1 + rv["k"] or (rv["k"] == 0 and len(segs) != 1): bad("segment_count_mismatch", tid) if not rv["orphan"] and rv["ts"] != segs[0]["timestamp"]: bad("timestamp_mismatch", tid) stats["turns_checked"] += 1 return problems, examples, stats # ----------------------------------------------------------------------------------------------- main def main(): rows, pairs, parse_errors, line_counts = load_rows() all_rows = rows["train"] + rows["eval"] all_pairs = pairs["train"] + pairs["eval"] record("1_every_line_parses_as_json", not parse_errors, f"lines={line_counts} errors={dict(parse_errors)}") # ---- tool pairing pair_viol = Counter() for r in all_rows: issued, answered = {}, set() for m in r["messages"]: if m["role"] == "assistant": for tc in m.get("tool_calls") or []: if tc["id"] in issued: pair_viol["duplicate_call_id_in_row"] += 1 issued[tc["id"]] = True elif m["role"] == "tool": if m["tool_call_id"] not in issued: pair_viol["tool_reply_without_earlier_call"] += 1 elif m["tool_call_id"] in answered: pair_viol["call_answered_twice"] += 1 answered.add(m["tool_call_id"]) pair_viol["call_without_reply"] += len(set(issued) - answered) record("2_tool_messages_pair_with_earlier_calls_exactly_once", not any(pair_viol.values()), dict(pair_viol) and str(dict(pair_viol)) or f"rows={len(all_rows)}") # ---- last message final_bad = 0 declared_tool_end = 0 nonfinal_tool = 0 nonfinal_asst = 0 nonfinal = 0 for r in all_rows: last = r["messages"][-1] ok = last["role"] == "assistant" and isinstance(last.get("content"), str) and last["content"].strip() != "" and not last.get("tool_calls") if r["segment"] == r["segments_total"]: if "ends_on_tool_output" in r["flags"]: declared_tool_end += 1 # manual decision: kept without a final answer, flagged final_bad += ok # a flagged row that does end with an assistant message would be inconsistent else: final_bad += (not ok) else: nonfinal += 1 if ok: nonfinal_asst += 1 else: nonfinal_tool += 1 n_final = len(all_rows) - nonfinal record("3a_final_segments_end_with_nonempty_assistant_message", final_bad == 0, f"{n_final - declared_tool_end - final_bad}/{n_final - declared_tool_end} final segments; " f"plus {declared_tool_end} manually kept turns flagged ends_on_tool_output (no final answer exists in the log)") record("3b_non_final_segments_end_with_assistant_message", nonfinal_tool == 0, f"{nonfinal_asst}/{nonfinal} end with an assistant message; {nonfinal_tool} end with a tool message BY CONSTRUCTION " f"(compaction fell right after a tool output; cutting there is what step 7 specifies)") # ---- forbidden strings in the output files (raw bytes of the files = JSON-escaped text) and in decoded text forbid = Counter() secret_hits = Counter() for name in DATA_FILES + ["manifest.json"]: with open(os.path.join(OUT, name), encoding="utf-8") as f: data = f.read() forbid["gAAAA"] += data.count("gAAAA") forbid["C:\\Users\\Developer (file text, any escaping/separator)"] += len(DEV_PATH_RE.findall(data)) forbid["encrypted_content"] += data.count("encrypted_content") for rn, rx in redact.VALIDATION_REGEXES.items(): secret_hits[rn] += len(rx.findall(data)) decoded_hits = Counter() for r in all_rows: texts = [] for m in r["messages"]: if m.get("content"): texts.append(m["content"]) for tc in m.get("tool_calls") or []: texts.append(tc["function"]["arguments"]) try: texts.append(json.dumps(json.loads(tc["function"]["arguments"]), ensure_ascii=False)) except ValueError: pass texts.append(r["cwd"] or "") for t in texts: for rn, rx in redact.VALIDATION_REGEXES.items(): decoded_hits[rn] += len(rx.findall(t)) decoded_hits["gAAAA"] += t.count("gAAAA") if DEV_PATH_RE.search(t): decoded_hits["Users/Developer"] += 1 for p in all_pairs: for t in (p["brief"], p["report"], p["cwd"] or ""): for rn, rx in redact.VALIDATION_REGEXES.items(): decoded_hits[rn] += len(rx.findall(t)) decoded_hits["gAAAA"] += t.count("gAAAA") if DEV_PATH_RE.search(t): decoded_hits["Users/Developer"] += 1 record("4a_no_gAAAA_encrypted_blobs", forbid["gAAAA"] == 0 and decoded_hits["gAAAA"] == 0, f"file_hits={forbid['gAAAA']} decoded_hits={decoded_hits['gAAAA']} encrypted_content_key={forbid['encrypted_content']}") record("4b_no_C:\\Users\\Developer", forbid["C:\\Users\\Developer (file text, any escaping/separator)"] == 0 and decoded_hits["Users/Developer"] == 0, f"file_hits={forbid['C:\\Users\\Developer (file text, any escaping/separator)']} decoded_hits={decoded_hits['Users/Developer']}") sh = {k: secret_hits[k] + decoded_hits[k] for k in redact.VALIDATION_REGEXES} record("4c_no_secret_regex_hits", not any(sh.values()), json.dumps(sh)) # ---- residual PII scan with the redaction finders themselves (decoded text, all fields) resid = Counter() for r in all_rows: texts = [m["content"] for m in r["messages"] if m.get("content")] texts += [tc["function"]["arguments"] for m in r["messages"] for tc in (m.get("tool_calls") or [])] for t in texts: for _s, _e, k, _rep in redact._find_secrets(t): resid["secret:" + k] += 1 resid["email"] += len(redact._find_emails(t)) resid["ipv4"] += len(redact._find_ips(t)) resid["onedrive_org"] += len(redact._find_onedrive_org(t)) resid["win_user_path"] += _real_user_path_hits(t) resid["leftover_user_path_regex"] += _leftover_hits(t) for p in all_pairs: for t in (p["brief"], p["report"]): resid["email"] += len(redact._find_emails(t)) resid["onedrive_org"] += len(redact._find_onedrive_org(t)) resid["ipv4"] += len(redact._find_ips(t)) resid["win_user_path"] += _real_user_path_hits(t) resid["leftover_user_path_regex"] += _leftover_hits(t) for _s, _e, k, _rep in redact._find_secrets(t): resid["secret:" + k] += 1 record("5_no_residual_pii_or_secrets_found_by_redaction_finders", not any(resid.values()), json.dumps(dict(resid)) if resid else "0 residual matches (secrets, e-mail, IPv4, user paths, OneDrive organisation names)") # ---- schema & consistency sch = Counter() ids = set() turn_segments = defaultdict(list) for r in all_rows: if list(r.keys()) != ROW_KEYS: sch["row_keys"] += 1 if r["id"] != f"{r['turn_id']}#{r['segment']}": sch["id_format"] += 1 if r["id"] in ids: sch["duplicate_id"] += 1 ids.add(r["id"]) turn_segments[r["turn_id"]].append(r) ms = r["messages"] if not (ms[0]["role"] == "system" and SYSTEM_RE.match(ms[0]["content"])): sch["system_prompt"] += 1 if ms[1]["role"] != "user": sch["task_message_role"] += 1 if r["segment"] > 1 and not (ms[2]["role"] == "user" and ms[2]["content"] == build.COMPACT_NOTE): sch["compaction_note_missing"] += 1 if r["segment"] == 1 and any(m.get("content") == build.COMPACT_NOTE for m in ms[2:]): sch["compaction_note_in_segment1"] += 1 if r["compaction_summary_available"] != (r["segments_total"] == 1): sch["compaction_summary_flag"] += 1 if r["task_source"] not in ("user", "goal", "reconstructed"): sch["task_source"] += 1 if r["task_source"] == "reconstructed" and "manual_recovery" not in r["flags"]: sch["reconstructed_without_flag"] += 1 if "ends_on_tool_output" in r["flags"] and not (r["segment"] == r["segments_total"] and ms[-1]["role"] == "tool"): sch["ends_on_tool_output_flag_inconsistent"] += 1 if r["task_source"] == "goal" and not ms[1]["content"].startswith(build.GOAL_PREFIX): sch["goal_prefix"] += 1 calls = [tc for m in ms if m["role"] == "assistant" for tc in (m.get("tool_calls") or [])] if r["n_tool_calls"] != len(calls): sch["n_tool_calls"] += 1 # arguments: valid JSON string, never truncated for tc in calls: try: json.loads(tc["function"]["arguments"]) except ValueError: sch["arguments_not_json"] += 1 if tc["type"] != "function" or set(tc.keys()) != {"id", "type", "function"} or set(tc["function"].keys()) != {"name", "arguments"}: sch["tool_call_shape"] += 1 if "chars truncated ...]" in tc["function"]["arguments"] and MARKER_RE.search(tc["function"]["arguments"]): sch["marker_in_arguments"] += 1 # failed calls nf = sum(1 for m in ms if m["role"] == "tool" and build.is_failed(m["content"])) if nf != r["n_failed_calls"]: sch["n_failed_calls"] += 1 # flags recomputed cs = Counter((tc["function"]["name"], tc["function"]["arguments"]) for tc in calls) dup = sum(c - 1 for c in cs.values()) want = [] if calls and dup / len(calls) > 0.10: want.append("high_dup_calls") if r["segment"] == r["segments_total"] and ms[-1]["role"] == "assistant" and len(ms[-1].get("content") or "") < 200: want.append("short_final") if any(len(tc["function"]["arguments"]) > build.LARGE_ARG for tc in calls): want.append("large_patch") if want != [f for f in r["flags"] if f not in ("manual_recovery", "ends_on_tool_output")]: sch["flags"] += 1 # tool output length rule for m in ms: if m["role"] == "tool": c = m["content"] mm = MARKER_RE.search(c) if mm: if len(c) != 4000 + len(mm.group(0)) or c.find(mm.group(0)) != 2000: sch["truncation_shape"] += 1 elif len(c) > 4000: sch["tool_output_over_4000_untruncated"] += 1 if m["role"] == "assistant" and "content" not in m: sch["assistant_without_content_key"] += 1 for tid, segs in turn_segments.items(): segs.sort(key=lambda r: r["segment"]) if [r["segment"] for r in segs] != list(range(1, len(segs) + 1)) or any(r["segments_total"] != len(segs) for r in segs): sch["segment_numbering"] += 1 if len({r["session_id"] for r in segs}) != 1: sch["session_per_turn"] += 1 # split integrity s_train = {r["session_id"] for r in rows["train"]} | {p["session_id"] for p in pairs["train"]} s_eval = {r["session_id"] for r in rows["eval"]} | {p["session_id"] for p in pairs["eval"]} if s_train & s_eval: sch["session_in_both_splits"] += len(s_train & s_eval) t_train = {r["turn_id"] for r in rows["train"]} t_eval = {r["turn_id"] for r in rows["eval"]} if t_train & t_eval: sch["turn_in_both_splits"] += len(t_train & t_eval) pk = Counter() brief_seen = Counter() for p in all_pairs: if list(p.keys()) != PAIR_KEYS: pk["pair_keys"] += 1 brief_seen[p["brief"]] += 1 if not p["brief"].strip() or not p["report"].strip(): pk["pair_empty"] += 1 if any(c > 1 for c in brief_seen.values()): pk["duplicate_brief"] += 1 sch.update(pk) record("6_schema_and_consistency (keys, ids, system prompt, segments, flags, n_failed, truncation shape, split disjoint)", not any(sch.values()), json.dumps(dict(sch)) if sch else f"{len(all_rows)} rows / {len(all_pairs)} pairs all consistent") # ---- redaction log rl = Counter() row_ids = ids | {"pair:" + p["turn_id"] for p in all_pairs} kinds = Counter() with open(os.path.join(OUT, "redactions.jsonl"), encoding="utf-8") as f: for line in f: o = json.loads(line) if list(o.keys()) != RED_KEYS: rl["keys"] += 1 if o["row_id"] not in row_ids: rl["unknown_row_id"] += 1 if not re.fullmatch(r"[0-9a-f]{64}", o["sha256_of_original"]): rl["sha_format"] += 1 if o["replacement"] == o.get("original"): rl["original_present"] += 1 kinds[o["kind"]] += 1 record("7_redactions_log_wellformed_no_originals", not any(rl.values()), json.dumps(dict(rl)) if rl else f"kinds={dict(kinds)}") # ---- independent raw re-parse problems, examples, stats = crosscheck(all_rows) record("8_independent_raw_crosscheck_of_every_kept_turn", not problems, (json.dumps({"problems": dict(problems), "examples": examples}) if problems else f"{stats['turns_checked']} turns: call ids/order/names/arguments, outputs, assistant texts, task, mid-turn user msgs, timestamps all match the raw logs")) # ---- manual recoveries mr = Counter() flagged = defaultdict(list) for r in all_rows: if "manual_recovery" in r["flags"]: flagged[r["turn_id"]].append(r) if set(flagged) != set(MANUAL_CFG): mr["flagged_turns_differ_from_config"] += len(set(flagged) ^ set(MANUAL_CFG)) for tid, rs in flagged.items(): if len(rs) != max(r["segments_total"] for r in rs): mr["not_every_segment_flagged"] += 1 recon_rows = {r["turn_id"] for r in all_rows if r["task_source"] == "reconstructed"} if recon_rows != {t for t, e in MANUAL_CFG.items() if e["kind"] == "task_reconstructed"}: mr["reconstructed_set_differs"] += 1 tool_end = {r["turn_id"] for r in all_rows if "ends_on_tool_output" in r["flags"]} if tool_end != {t for t, e in MANUAL_CFG.items() if e["kind"] == "ends_on_tool_output"}: mr["ends_on_tool_output_set_differs"] += 1 present = {r["turn_id"] for r in all_rows} if present & MANUAL_LEFT_OUT: mr["left_out_turn_present"] += 1 record("10_manual_recoveries_match_scripts/manual_recoveries.json_and_are_flagged", not mr, json.dumps(dict(mr)) if mr else f"{len(flagged)} turns / {sum(len(v) for v in flagged.values())} rows flagged manual_recovery: " f"{dict(Counter(MANUAL_CFG[t]['kind'] for t in flagged))}; left out: {sorted(MANUAL_LEFT_OUT)}") # ---- ballpark man = json.load(open(os.path.join(OUT, "manifest.json"))) total_mb = sum(os.path.getsize(os.path.join(OUT, n)) for n in DATA_FILES) / 1e6 record("9_ballpark (~395 turns, ~430 rows, 30-100 MB)", 380 <= man["turns_after_dedup"] <= 410 and 400 <= len(all_rows) <= 460 and 30 <= total_mb <= 100, f"turns_after_dedup={man['turns_after_dedup']} turns_kept={man['turns_kept']} rows={len(all_rows)} total_MB={total_mb:.1f}") extra = { "tool_calls_in_rows": sum(r["n_tool_calls"] for r in all_rows), "failed_calls_in_rows": sum(r["n_failed_calls"] for r in all_rows), "rows_with_zero_tool_calls": sum(1 for r in all_rows if r["n_tool_calls"] == 0), "flag_counts": dict(Counter(f for r in all_rows for f in r["flags"])), "rows_by_task_source": dict(Counter(r["task_source"] for r in all_rows)), "rows_by_thread_source": dict(Counter(str(r["thread_source"]) for r in all_rows)), "non_final_segments_ending_in_tool_message": nonfinal_tool, "residual_scan": dict(resid), "crosscheck_turns": stats["turns_checked"], "manual_recovery_rows": sum(len(v) for v in flagged.values()), "rows_ending_on_tool_output_final_segment": declared_tool_end, "reconstructed_task_rows": sum(1 for r in all_rows if r["task_source"] == "reconstructed"), } man["validation"] = {"all_passed_except_expected_3b": all(v["pass"] for k, v in results.items() if not k.startswith("3b")), "checks": results, "extra": extra} with open(os.path.join(OUT, "manifest.json"), "w") as f: json.dump(man, f, indent=2, ensure_ascii=False) print("\nSUMMARY:", sum(v["pass"] for v in results.values()), "of", len(results), "checks pass") if __name__ == "__main__": main()