#!/usr/bin/env python3 """Write REPORT.md from the finished outputs. Usage: python3 -I report.py [OUT_DIR] Run order: build.py -> validate.py -> report.py (needs manifest["validation"]).""" import json import os import statistics import sys from collections import Counter, defaultdict HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) import build # noqa: E402 import redact # noqa: E402 from view import compact_view # noqa: E402 OUT = os.path.abspath(sys.argv[1]) if len(sys.argv) > 1 else build.DEFAULT_OUT def jl(name): with open(os.path.join(OUT, name), encoding="utf-8") as f: return [json.loads(l) for l in f] def fmt_bytes(n): return f"{n/1e6:.2f} MB" if n >= 1e6 else f"{n/1e3:.1f} KB" def main(): man = json.load(open(os.path.join(OUT, "manifest.json"))) val = man.get("validation") if not val: sys.exit("run validate.py first") rows = jl("trajectories.train.jsonl") + jl("trajectories.eval.jsonl") pairs = jl("pairs.train.jsonl") + jl("pairs.eval.jsonl") # ---- phone-like candidates (reported, never redacted) cands = defaultdict(lambda: [0, None, set()]) def scan(t, where): for c in redact.phone_candidates(t): e = cands[c] e[0] += 1 e[1] = e[1] or where e[2].add(where.split("#")[0]) for r in rows: for m in r["messages"]: if m.get("content"): scan(m["content"], r["id"]) for tc in m.get("tool_calls") or []: scan(tc["function"]["arguments"], r["id"]) for p in pairs: scan(p["brief"], "pair:" + p["turn_id"]) scan(p["report"], "pair:" + p["turn_id"]) cand_sorted = sorted(cands.items(), key=lambda kv: (-kv[1][0], kv[0])) # ---- samples: short / medium / long by number of messages (rows with >=1 tool call) # short / medium: unsplit rows (a plain turn); long: the longest row overall (it happens to be a later segment of a compacted goal turn) plain = sorted([r for r in rows if r["n_tool_calls"] >= 3 and r["segments_total"] == 1], key=lambda r: (len(r["messages"]), r["id"])) longest = max(rows, key=lambda r: (len(r["messages"]), r["id"])) short, medium, long_ = plain[0], plain[len(plain) // 2], longest L = [] w = L.append w("# Codex rollout logs -> tool-use training dataset: cleaning report\n") w("Generated by `scripts/build.py` -> `scripts/validate.py` -> `scripts/report.py`. " "Inputs (`05/`, `dataset-analysis/`) were only read. Every file was streamed line by line.\n") f = man["turns_funnel"] w("## 1. Summary\n") w(f"* **{man['files_read']} files / {man['bytes_read']/1e9:.2f} GB / {man['lines_total']:,} lines** read in {man['wall_seconds']} s with 8 workers.") w(f"* **{man['turn_instances_found']:,} turn instances** found (**{man['unique_turn_ids_found']:,} distinct turn ids**, so embedded parent-history copies make up most of them). " f"**{man['turn_instances_passing_step1_filter']} pass step 1** (task_complete + >=1 tool call) -> **{man['turns_after_dedup']} after dedup** (the expected ~395) -> " f"**{man['turns_kept']} turns kept**: {man['turns_kept'] - man['manual_recoveries']['turns_recovered']} by the automatic rules plus " f"**{man['manual_recoveries']['turns_recovered']} manual recoveries** (section 5, every such row is flagged `manual_recovery`).") w(f"* **{man['segments_total_rows']} trajectory rows** after splitting at compaction points ({man['rows']['train']} train / {man['rows']['eval']} eval) " f"and **{man['rows']['pairs_train'] + man['rows']['pairs_eval']} brief/report pairs** ({man['rows']['pairs_train']} train / {man['rows']['pairs_eval']} eval).") w(f"* Output: **{man['bytes_total_output']/1e6:.1f} MB** total (inside the 30-100 MB ballpark).") w(f"* Validation: **{sum(v['pass'] for v in val['checks'].values())} of {len(val['checks'])} checks pass**; the one that does not (3b) is a conflict inside the spec, explained in section 4.\n") w("## 2. Counts\n") w("### Turn funnel\n") w("| stage | turns |\n|---|---:|") for k, v in f.items(): w(f"| {k.strip().replace('_', ' ')} | {v:,} |") w("") w("### Turns dropped, per reason\n") w("| reason | count |\n|---|---:|") for k, v in man["turns_dropped_per_reason"].items(): w(f"| `{k}` | {v:,} |") w("\nCounts are turn instances (one per `task_started` per file). Rows 1-3 are step 1 failures (embedded parent-history copies dominate them), " "the orphan row is a step 1 casualty of file corruption, `duplicate…` is step 2, and the `step3_`/`step5_` rows act on the 395 turns that passed.\n") w("Notes on the reasons:\n") w("* `has_task_complete_but_no_tool_calls`, `no_task_complete_*`: overwhelmingly the thinned parent-history copies embedded in forked subagent files " "(they keep `task_started`/`user_message`/`task_complete` but no tool calls), plus chat-only turns and interrupted turns.") w("* `duplicate_turn_id_lower_priority_copy` is **0**: after the step 1 filter no turn id survives in more than one file, so the " f"\"most calls, then smaller file\" rule never had to choose. Running dedup *before* the filter would change the outcome for " f"{man['dedup_order_sensitivity_turn_ids_that_would_differ_if_dedup_ran_before_filter']} turn ids.") w("* `task_complete_without_task_started_(file_corruption)`: " f"{man['orphan_turns_task_complete_without_start']['total']} `task_complete` records whose `task_started` was destroyed " f"({man['orphan_turns_task_complete_without_start']['with_tool_calls']} of them follow tool calls). They sit in the NUL-damaged files: no `task_started`, no task message. " f"The {man['orphan_turns_task_complete_without_start']['with_tool_calls']} that still have their tool calls were rebuilt manually with a reconstructed task (section 5); " "the rest have no tool calls and are not turns for this dataset.") w("* The automatic rules alone dropped 1 turn at step 3 (no `user_message`, goal objective set only *inside* the turn, while the spec asks for one from *before* it starts) " "and 4 at step 5 (`last_agent_message` null and the turn ends on a tool output). Manual recoveries brought back the step 3 turn and 3 of the step 5 turns; " "the remaining step 5 turn is listed under `left_out` in section 5.") w("* Two more turns with a null `last_agent_message` end on an assistant `` message; that text is used as the final answer automatically (see `final_answer_taken_from_last_assistant_text`).\n") cr = man["compaction_reconciliation"] w("### Segments\n") w(f"* {cr['selected_turns_containing_a_compacted_record']} of the {man['turns_after_dedup']} turns contain a `compacted` record (the expected ~33). " f"{man['turns_split_at_compaction']} kept turns were split ({man['compaction_markers_in_kept_turns']} markers); " f"{cr['compaction_markers_ignored_because_nothing_precedes_them']} markers were ignored because the compaction happened before any content in the turn (nothing to cut off). " f"{cr['extra_segments_created']} extra segments were created, so {man['turns_kept']} turns became {man['segments_total_rows']} rows.") w(f"* {val['extra']['rows_with_zero_tool_calls']} rows have zero tool calls: they are final segments where the compaction fell right before the final answer " "(`[system, task, note, final answer]`). They are kept, per \"flag, don't filter\"; filter on `n_tool_calls == 0` to drop them.\n") w("### Tool outputs, calls and records\n") to, tc = man["tool_outputs"], man["tool_calls"] w(f"* Outputs truncated (>4,000 chars -> 2,000 + 2,000): **{to['truncated']:,}**; characters removed: **{to['chars_removed_by_truncation']:,}**.") w(f"* Tool calls dropped because they had no output: **{tc['dropped_no_output']}** (expected < 10); orphan outputs dropped: {tc['orphan_outputs_dropped']}; duplicate call ids: {tc['duplicate_call_ids_dropped']}.") w(f"* Tool calls in rows: {val['extra']['tool_calls_in_rows']:,}; failed (non-zero exit or failed patch): {val['extra']['failed_calls_in_rows']:,}.") w(f"* Non-string tool outputs normalised to text: {to['non_string_outputs_normalised']} ({to['image_parts_replaced_by_placeholder']} image parts -> `[image omitted]`).") w(f"* Flags: {val['extra']['flag_counts']}. Task source: {val['extra']['rows_by_task_source']}.") w(f"* User messages with attached images in kept turns: {man['user_messages_with_images_in_kept_turns(images_not_included)']} (attached images are not reproduced).") w("* Records dropped inside kept turns (count): " + ", ".join(f"`{k}` {v:,}" for k, v in list(man["dropped_records_in_kept_turns"].items())[:14]) + ".\n") w("### Raw-file health\n") w(f"* {man['files_empty_0_bytes']} files are empty (0 bytes); {man['files_without_session_meta_nonempty']} more non-empty files have no `session_meta` (their head is NUL/garbage-filled; the session id then comes from the file name).") bd = ", ".join(f"{v:,} {k.replace('_', ' ')}" for k, v in sorted(man["malformed_lines_breakdown"].items(), key=lambda kv: -kv[1])) w(f"* **{man['malformed_lines']:,} malformed lines** in {man['files_with_malformed_or_scalar_lines']} files ({bd}), {man['scalar_lines']} bare JSON scalars, {man['blank_lines']} blank lines (not counted as malformed). " f"Parsed records: {man['records_parsed']:,}. {man['lines_total']:,} = parsed + malformed + scalar + blank.") w(f"* {man['files_with_embedded_parent_context']} files carry embedded parent history behind extra `session_meta` records.\n") w("### Redactions\n") w("| kind | replacements logged |\n|---|---:|") kinds = Counter() with open(os.path.join(OUT, "redactions.jsonl"), encoding="utf-8") as fh: for line in fh: kinds[json.loads(line)["kind"]] += 1 for k, v in sorted(kinds.items(), key=lambda kv: -kv[1]): w(f"| `{k}` | {v:,} |") w(f"\nTotal {man['redactions_total_logged']:,} entries in `redactions.jsonl` (original values never written; only SHA-256). " f"A further {man['redactions_in_truncated_middle_not_logged']} replacements happened inside the middle part of outputs that truncation later removed; they are not logged because they no longer exist in the data.\n") w("* `win_user_path`: every `X:\\Users\\\\` (also `\\\\`, `/`, and WSL `/mnt/x/Users/`) -> `...\\Users\\user\\`. The shared profiles `Public`, `Default`, `Default User`, `All Users` are not user names and were kept. `M:\\Codex\\...` project paths are untouched.") w("* `onedrive_org`: the organisation in a work/school OneDrive folder name (`OneDrive - \\...`) -> `OneDrive - \\...`. The generic `OneDrive - Personal` is kept.") w("* Secret rules follow the spec exactly: `AKIA[0-9A-Z]{16}`, `gh[pousr]_...`, `github_pat_...`, `sk-[A-Za-z0-9_-]{20,}`, PEM private-key blocks (also unterminated ones), `Authorization: Bearer `, and values assigned to `password|passwd|token|api_key|apikey|secret`.") n_emb = kinds.get("secret:sk_key:embedded_in_word", 0) w(f"* **Collateral of the literal `sk-` rule:** the spec's regex has no word boundary, so {n_emb} replacements hit lowercase hyphenated words such as file names containing `…task-…`, " "not credentials. They carry the kind `secret:sk_key:embedded_in_word` in the log, so they are easy to find. To avoid them, anchor `_SK` on the left in `scripts/redact.py` and re-run (about 10 s); check 4c would then report the un-anchored regex hits. No real credential of any type was found in the corpus (0 AKIA / ghp / github_pat / PEM / Bearer).") n_kv = sum(v for k, v in kinds.items() if k.startswith("secret:kv")) w(f"* Key/value secrets need a literal-looking value: `// Token: 0x06000001` decompiler metadata, `var token = this.Client.Token`, and `token:` at the end of a line were false positives in the first pass (172 hits) and are now excluded. The log has {n_kv} `secret:kv:*` replacements, so nothing in the data looked like an assigned secret.") w(f"* IPv4: .NET `Version=x.x.x.x` assembly versions are not addresses and are left alone; the {kinds.get('ipv4', 0)} replaced addresses are public DNS A-record answers. The {kinds.get('email', 0)} e-mail addresses are vendor contact addresses in decompiled code and docs.\n") w("### Phone-like candidates (reported, NOT redacted)\n") w(f"Regex: optional `+CC`, then groups of 2-4 / 3-4 / 3-4 (/1-4) digits separated by space, dot or dash, 9-15 digits in total. " f"{len(cand_sorted)} distinct candidates, {sum(v[0] for v in cands.values())} occurrences. Almost all are codec numbers (resolutions, frame sizes, float pairs). " "Only `425-893-4300` looks like a real phone number: it is the `ProductPhone` constant in a vendor's public `changes.html` (a business number, next to the `ProductEmail` constant that was redacted).\n") w("| candidate | occurrences | first seen in |\n|---|---:|---|") for c, (n, first, _files) in cand_sorted: w(f"| `{c}` | {n} | `{first}` |") w("") w("## 3. Output files\n") w("| file | size | lines |\n|---|---:|---:|") for name, size in man["bytes_per_output_file"].items(): with open(os.path.join(OUT, name), "rb") as fh: n = sum(1 for _ in fh) w(f"| `{name}` | {fmt_bytes(size)} ({size:,} B) | {n:,} |") w(f"\nSplit: by session id, seed 42 ({man['split']['sessions_total']} sessions, {man['split']['sessions_eval']} to eval). " f"Eval holds {man['rows']['eval']} trajectory rows ({man['split']['trajectory_rows_eval_share']*100:.1f}%) and {man['rows']['pairs_eval']} pairs ({man['split']['pairs_eval_share']*100:.1f}%): " "the row share is below 10% only because a few sessions are very large; the split unit is the session, as asked.\n") w("## 4. Validation\n") w("| check | result | detail |\n|---|---|---|") for name, v in val["checks"].items(): d = str(v["detail"]).replace("|", "\\|") if len(d) > 400: d = d[:400] + "…" w(f"| {name} | {'PASS' if v['pass'] else '**FAIL**'} | {d} |") w("") w("**About 3b (the only failing check).** The spec asks both for a cut at every compaction point and for every trajectory to end with an assistant message. " f"In this data {val['extra']['non_final_segments_ending_in_tool_message']} of the {val['extra']['non_final_segments_ending_in_tool_message']} non-final segments end with a tool message, " "because Codex compacts right after a tool result and the next assistant message belongs to the next segment. I did not invent an assistant message to close them. " f"Every *final* segment ends with the non-empty final answer, except the {val['extra']['rows_ending_on_tool_output_final_segment']} manually kept turns flagged `ends_on_tool_output` (section 5). " "If you want the rule to hold for every row, keep rows with `segment == segments_total` and without the `ends_on_tool_output` flag, or decide how those should be handled (drop, or keep as is).\n") w(f"**About check 8.** It re-parses the raw logs with a separate, deliberately simple implementation and compares every kept turn: call ids and order, tool names, arguments, outputs (after the same redaction/truncation), assistant texts, task message, mid-turn user messages and timestamps. All {val['extra']['crosscheck_turns']} match, including the six whose `task_started` was destroyed (their body is re-read from the raw file; for the reconstructed task the check compares with `manual_recoveries.json`).\n") mr = man["manual_recoveries"] cfg = json.load(open(build.MANUAL_FILE, encoding="utf-8")) if os.path.exists(build.MANUAL_FILE) else {"recoveries": [], "left_out": []} n_rows_rec = sum(v["rows"] for v in mr["turn_ids"].values()) w(f"## 5. Manual recoveries ({mr['turns_recovered']} turns, {n_rows_rec} rows)\n") w("Requested: recover 10 turns by hand so the dataset reaches 400. Every decision is in `scripts/manual_recoveries.json` (with its evidence), " "`build.py` reads it, and every row of these turns carries the flag `manual_recovery`. Run `build.py --no-manual` (or delete an entry) to undo.\n") w("| turn id | kind | rows | what was done |\n|---|---|---:|---|") what = {"goal_set_inside_turn": "task = the goal objective set inside the turn (`task_source: goal`); nothing invented", "ends_on_tool_output": "kept as is; ends on its last tool message because no final answer exists; flag `ends_on_tool_output`; nothing invented", "task_reconstructed": "body is the real, intact trajectory; **task message written by a reviewer** (`task_source: reconstructed`)"} for e in cfg["recoveries"]: info = mr["turn_ids"].get(e["turn_id"], {"rows": 0}) w(f"| `{e['turn_id']}` | `{e['kind']}` | {info['rows']} | {what[e['kind']]} |") w("") w("**Reconstructed tasks: not from the logs.** In six files the first lines were overwritten by NUL bytes: `session_meta`, `task_started`, `turn_context` and the task message are gone, " "and the parent's `spawn_agent` prompt is not in the corpus (the replayed history only keeps the `` results). The intact body of each turn " "(tool calls, outputs, assistant text, final report) is used unchanged. The task text below was written from that body (assistant statements, commands, final-report headings) and is " "a plausible brief, **not the original**. Treat these 6 rows as synthetic prompts on real trajectories; filter on `task_source == \"reconstructed\"` if you do not want them.\n") for e in cfg["recoveries"]: if e["kind"] != "task_reconstructed": continue w(f"* `{e['turn_id']}`: \"{e['task']}\"") w(f" * Evidence: {e['basis']}") w("") w("Metadata for the reconstructed rows: `model` and `effort` are `null` (the `turn_context` is gone); `thread_source` is `subagent` (the parent received a `` naming each id; " "the file's own `session_meta` is gone); `agent_role` is `null`; `cwd` is the `workdir` of the turn's shell calls (`M:\\Codex\\Bink2Combined` in all six); `session_id` comes from the file name; " "`timestamp` is derived as `completed_at - duration_ms` (second precision, `Z`). " f"{mr['tool_outputs_dropped_because_their_call_was_destroyed']} tool outputs whose calls were destroyed are dropped, so these trajectories can have small gaps. " "They have no brief/report pair.\n") w("**Kept without a final answer (3 turns).** Their runs were cut off (one user message mentions a balance problem): `task_complete.last_agent_message` is null and the last record is a tool output. " "I did not write a final message for them. The final segment ends on a tool message and has the flag `ends_on_tool_output`; check 3a counts them separately.\n") for e in cfg.get("left_out", []): w(f"**Left out:** `{e['turn_id']}`. {e['reason']}\n") w("## 6. Decisions and surprises\n") w("* **Dedup was a no-op in the output.** The embedded parent copies in the big forked files were thinned by Codex (no tool calls), so all 395 qualifying turns are unique and belong to the file's own session. " "To tell own turns from embedded ones (needed for the brief/report pairs) I compare each turn id's UUIDv7 time with the file's own session id: parent turns are older, and non-v7 ids only occur in the replay. A `turn_context` record is *not* a safe signal: the replayed turns have those too.") w(f"* **Pairs: {man['pairs']['pairs_written']} instead of ~317.** {man['pairs']['subagent_files']} subagent files; " f"{man['pairs']['no_pair_because_brief_turn_never_completed']} have a brief turn that never reached `task_complete` (interrupted or still running) and " f"{man['pairs']['no_pair_because_no_own_user_message']} forked files end right after the replayed history without ever starting their own turn. No two briefs were identical.") w("* **Final answer:** `last_agent_message` is null for 6 qualifying turns: 2 end on an assistant `` (used as the final answer automatically); " "4 end on a tool output because the run was cut off (the user mentions a balance problem). For 3 of those 4 the turn is kept as it is, ending on its last tool message, " "flagged `ends_on_tool_output`; no final answer was written for them. See section 5.") nsub = man["dropped_records_in_kept_turns"].get("injected:user:subagent_notification", 0) w(f"* **Injected user-role messages are dropped as specified**, including `` messages ({nsub} in kept turns). The orchestrator therefore sometimes reacts to results it can no longer see in the transcript.") w("* **`timestamp`** is the timestamp of the `task_started` record (the file's own turns are never replayed history). Exception: the six reconstructed rows, whose `task_started` was destroyed, use a derived start time (section 5).") w(f"* **Goal turns** (`task_source: goal`): {val['extra']['rows_by_task_source'].get('goal', 0)} rows; the task is `Continue working on this goal:\\n` with the latest objective seen before the turn started.") w("* **Arguments are never truncated**; patches over 20,000 characters are flagged `large_patch`. A turn's `apply_patch` input is stored as `json.dumps({\"input\": ...})`.") steer_rows = sum(1 for r in rows if any(m["role"] == "user" and m["content"] != build.COMPACT_NOTE for m in r["messages"][2:])) hoisted = man["kept_turn_diagnostics"].get("content_before_first_user_message", 0) w(f"* Message order follows the file. The first non-empty `user_message` becomes the task message (hoisted to position 2 if anything preceded it: {hoisted} turn); later ones stay in place as steering messages ({steer_rows} rows).\n") w("## 7. Sample rows (role, tool names, first ~150 characters of each message)\n") for label, r in (("short", short), ("medium", medium), ("long", long_)): note = "" if r["segments_total"] == 1 else f", segment {r['segment']} of {r['segments_total']} of a compacted turn" w(f"### {label}: `{r['id']}` ({len(r['messages'])} messages{note})\n") w("```text") w(compact_view(r, 150, 10, 6)) w("```\n") w("## 8. Reproduce\n") w("```bash\ncd /home/israel/Downloads/sessions\npython3 -I dataset-clean/scripts/build.py # ~10 s, writes data + manifest.json (add --no-manual to skip manual_recoveries.json)\n" "python3 -I dataset-clean/scripts/validate.py # adds manifest.json -> validation\npython3 -I dataset-clean/scripts/report.py # writes REPORT.md\n" "python3 -I dataset-clean/scripts/test_redact.py\n```") with open(os.path.join(OUT, "REPORT.md"), "w", encoding="utf-8") as fh: fh.write("\n".join(L) + "\n") print("wrote", os.path.join(OUT, "REPORT.md")) if __name__ == "__main__": main()