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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
#!/usr/bin/env python3
"""Turn shared-fail questions into a training set.

Every Albedo eval already has gold for these failures: a SOTA reference
trajectory that scores ~0.96 on the same checklist both models missed.

This script:
  1. Clusters shared-fail questions into generalized habits
  2. Keeps samples that have at least one shared fail
  3. Writes SFT rows  = prompt prefix + reference continuation
  4. Writes DPO rows  = same prefix, chosen=reference, rejected=challenger

Usage:
  python prepare_shared_fail_dataset.py evals/<eval_run_id>
  python prepare_shared_fail_dataset.py evals/<eval_run_id> --min-fails 3
"""

from __future__ import annotations

import argparse
import json
import re
import sys
from collections import Counter
from pathlib import Path

from king_pin import KING_URI

BLOCK_RE = re.compile(r"<\|im_start\|>(\w+)\n(.*?)<\|im_end\|>", re.DOTALL)
TRAJ_MARKER_RE = re.compile(r"^(REFERENCE STEP \d+:|ENVIRONMENT OBSERVATION:)\s*$", re.M)

# One habit per question. First match wins. These are process rules, not repo facts.
HABITS: list[tuple[str, str, re.Pattern[str] | None, frozenset[str] | None]] = [
    (
        "emit_visible_edit",
        "Put the edit in a command block. A THOUGHT or plan is not an edit.",
        re.compile(r"isSequence|helper|edit leave|_parse_|add a public class", re.I),
        frozenset({"reference:action"}),
    ),
    (
        "review_diff",
        "Before finishing, run git diff (or equivalent) and read the accumulated change.",
        re.compile(r"\bgit diff\b", re.I),
        frozenset({"reference:verification"}),
    ),
    (
        "verify_after_work",
        "After the change, run the named check (repro, test, or re-read) and show its result.",
        re.compile(r"reproduction script|pytest|unittest|test suite|existing test", re.I),
        frozenset({"reference:verification"}),
    ),
    (
        "show_then_edit",
        "Display the file and the exact region, then edit the symbol that display showed.",
        re.compile(
            r"exact region being changed|every file the candidate modifies|"
            r"edit target.*(displayed|shown)",
            re.I,
        ),
        frozenset({"behavior:anchored_edit"}),
    ),
    (
        "no_repeat_command",
        "Do not re-issue a command whose observation already answered it.",
        re.compile(r"avoid re-issu|already received", re.I),
        None,
    ),
    (
        "back_claims_with_display",
        "Do not assert a value, location, or cause unless that content was already displayed.",
        re.compile(r"state that|assert|backed by visib|claims about earlier", re.I),
        frozenset({"reference:claims"}),
    ),
    (
        "ground_next_action",
        "Open, grep, or edit only after a prior listing/search named the path or symbol.",
        re.compile(r"\bafter\b|previously displayed|prior (output|blocks?)", re.I),
        frozenset({"reference:grounding"}),
    ),
    (
        "locate_and_read",
        "Run the locating/reading command yourself. Do not guess from the issue text.",
        None,
        frozenset({"reference:explore"}),
    ),
]

TAG_FALLBACK = {
    "reference:action": "emit_visible_edit",
    "reference:verification": "verify_after_work",
    "behavior:anchored_edit": "show_then_edit",
    "reference:claims": "back_claims_with_display",
    "reference:grounding": "ground_next_action",
    "reference:explore": "locate_and_read",
}

HABIT_LESSON = {habit: lesson for habit, lesson, *_ in HABITS}


def load_jsonl(path: Path) -> list[dict]:
    return [json.loads(line) for line in path.read_text().splitlines() if line.strip()]


def write_jsonl(path: Path, rows: list[dict]) -> None:
    with path.open("w", encoding="utf-8") as handle:
        for row in rows:
            handle.write(json.dumps(row, ensure_ascii=False) + "\n")


def classify_habit(row: dict) -> str:
    text = row.get("text") or ""
    tag = row.get("tag") or ""
    for habit, _lesson, pattern, tags in HABITS:
        if tags is not None and tag not in tags:
            continue
        if pattern is None or pattern.search(text):
            return habit
    return TAG_FALLBACK.get(tag, "other")


def parse_system_user(prompt: str) -> tuple[str, str]:
    blocks = BLOCK_RE.findall(prompt or "")
    if len(blocks) < 2 or blocks[0][0] != "system" or blocks[1][0] != "user":
        raise ValueError("prompt is not a system+user chat template")
    return blocks[0][1].strip(), blocks[1][1].strip()


def messages_chars(messages: list[dict]) -> int:
    return sum(len(m.get("content") or "") for m in messages)


def continuation_after_prefix(turns: list | None, prefix: list[dict]) -> list[dict] | None:
    """Drop the shared system+user prefix so rejected is a completion, like chosen."""
    if not isinstance(turns, list) or not turns:
        return None
    cleaned = [
        {"role": str(m.get("role") or ""), "content": m.get("content") or ""}
        for m in turns
        if isinstance(m, dict)
    ]
    if (
        len(cleaned) >= 2
        and cleaned[0]["role"] == "system"
        and cleaned[1]["role"] == "user"
    ):
        cleaned = cleaned[2:]
    if not cleaned or cleaned[0]["role"] != "assistant":
        return None
    if any("FULL CANDIDATE TRAJECTORY" in (m["content"] or "") for m in cleaned):
        return None
    return cleaned


def parse_reference(traj: str) -> list[dict]:
    parts = TRAJ_MARKER_RE.split(traj or "")
    turns: list[dict] = []
    role = "assistant"
    for i, part in enumerate(parts):
        if i % 2 == 1:
            role = "assistant" if part.startswith("REFERENCE STEP") else "user"
            continue
        content = part.strip()
        if not content:
            continue
        if turns and turns[-1]["role"] == role:
            turns[-1]["content"] += "\n\n" + content
        else:
            turns.append({"role": role, "content": content})
    return turns


def index_by_id(rows: list[dict], key: str = "sample_id") -> dict[str, dict]:
    return {row[key]: row for row in rows if row.get(key)}


def load_eval_meta(eval_dir: Path) -> dict:
    path = eval_dir / "eval-meta.json"
    if not path.is_file():
        return {}
    return json.loads(path.read_text())


def pick_rejected_turns(
    sample: dict, meta: dict, *, current_king: str
) -> tuple[list | None, str]:
    """Prefer the current king's failed rollout as the DPO rejected side.

    Coronation evals have the new king as challenger. Later duels have it as
    previous_king. Older evals fall back to challenger_turns.
    """
    needle = (current_king or "").lower()
    chal_uri = str(meta.get("model_uri") or "").lower()
    king_obj = meta.get("king") if isinstance(meta.get("king"), dict) else {}
    king_uri = str(king_obj.get("model_uri") or "").lower()
    if needle and needle in chal_uri:
        return sample.get("challenger_turns"), "challenger"
    if needle and needle in king_uri:
        turns = sample.get("previous_king_turns") or sample.get("king_turns")
        return turns, "previous_king"
    return sample.get("challenger_turns"), "challenger"


def build(
    eval_dir: Path,
    *,
    min_fails: int,
    require_habits: set[str] | None,
    current_king: str = KING_URI,
) -> dict:
    scoring_path = eval_dir / "scoring-results.jsonl"
    samples_path = eval_dir / "generated-samples.jsonl"
    fails_path = eval_dir / "shared-fails.jsonl"
    if not fails_path.is_file():
        raise FileNotFoundError(
            f"{fails_path} missing — run filter_shared_fails.py on this eval first"
        )
    if not scoring_path.is_file() or not samples_path.is_file():
        raise FileNotFoundError("need scoring-results.jsonl and generated-samples.jsonl")

    fails = load_jsonl(fails_path)
    scoring = index_by_id(load_jsonl(scoring_path))
    samples = index_by_id(load_jsonl(samples_path))
    eval_meta = load_eval_meta(eval_dir)

    by_sample: dict[str, list[dict]] = {}
    habit_counts: Counter[str] = Counter()
    for row in fails:
        habit = classify_habit(row)
        habit_counts[habit] += 1
        enriched = {**row, "habit": habit, "lesson": HABIT_LESSON.get(habit, "")}
        by_sample.setdefault(row["sample_id"], []).append(enriched)

    sft: list[dict] = []
    dpo: list[dict] = []
    skipped = Counter()

    for sample_id, fail_rows in by_sample.items():
        if len(fail_rows) < min_fails:
            skipped["min_fails"] += 1
            continue
        habits = sorted({row["habit"] for row in fail_rows})
        if require_habits and not (set(habits) & require_habits):
            skipped["require_habits"] += 1
            continue
        score = scoring.get(sample_id)
        sample = samples.get(sample_id)
        if not score or not sample:
            skipped["missing_join"] += 1
            continue
        source = score.get("question_source") or {}
        ref = source.get("reference_trajectory")
        if not ref:
            skipped["no_reference"] += 1
            continue
        try:
            system, user = parse_system_user(sample.get("prompt") or "")
            ref_turns = parse_reference(ref)
        except ValueError:
            skipped["bad_prompt"] += 1
            continue
        if not ref_turns:
            skipped["empty_reference"] += 1
            continue

        prefix = [
            {"role": "system", "content": system},
            {"role": "user", "content": user},
        ]
        meta = {
            "sample_id": sample_id,
            "phase": source.get("sample_phase"),
            "dataset": sample_id.split("/")[0],
            "habits": habits,
            "n_shared_fails": len(fail_rows),
            "failed_questions": [
                {
                    "qid": row["qid"],
                    "habit": row["habit"],
                    "tag": row.get("tag"),
                    "weight": row.get("weight"),
                    "text": row.get("text"),
                    "example_bad": row.get("example_bad"),
                    "king_explanation": row.get("king_explanation"),
                    "chal_explanation": row.get("chal_explanation"),
                }
                for row in fail_rows
            ],
            "reference_model": source.get("reference_model"),
            "reference_self_score": source.get("reference_self_score"),
            "king_score": score.get("king_score"),
            "challenger_score": score.get("challenger_score"),
        }
        sft.append({**meta, "messages": prefix + ref_turns})

        rejected_turns, rejected_from = pick_rejected_turns(
            sample, eval_meta, current_king=current_king
        )
        rejected_messages = continuation_after_prefix(rejected_turns, prefix)
        if not rejected_messages:
            skipped["no_rejected_turns"] += 1
            continue
        chosen_n = messages_chars(ref_turns)
        rejected_n = messages_chars(rejected_messages)
        if chosen_n < 200 or rejected_n < 200:
            skipped["dpo_too_short"] += 1
            continue
        ratio = rejected_n / chosen_n
        if ratio < 0.5 or ratio > 2.0:
            skipped["dpo_length_ratio"] += 1
            continue
        ref_score = source.get("reference_self_score")
        rejected_score = (
            score.get("king_score")
            if rejected_from == "previous_king"
            else score.get("challenger_score")
        )
        if (
            isinstance(ref_score, (int, float))
            and isinstance(rejected_score, (int, float))
            and ref_score <= rejected_score
        ):
            skipped["dpo_pref_not_better"] += 1
            continue
        dpo.append(
            {
                **meta,
                "prompt_messages": prefix,
                "chosen_messages": ref_turns,
                "rejected_messages": rejected_messages,
                "chosen_chars": chosen_n,
                "rejected_chars": rejected_n,
                "length_ratio": round(ratio, 4),
                "rejected_from": rejected_from,
            }
        )

    patterns = [
        {
            "habit": habit,
            "n": habit_counts[habit],
            "lesson": HABIT_LESSON.get(habit, ""),
        }
        for habit, _n in habit_counts.most_common()
    ]
    return {
        "eval_dir": str(eval_dir),
        "shared_fails": len(fails),
        "samples_with_fails": len(by_sample),
        "sft_rows": len(sft),
        "dpo_rows": len(dpo),
        "skipped": dict(skipped),
        "patterns": patterns,
        "sft": sft,
        "dpo": dpo,
        "habit_counts": dict(habit_counts),
    }


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(
        description="Build SFT/DPO rows from shared-fail questions + reference trajectories."
    )
    parser.add_argument("eval_dir", type=Path, help="eval directory with shared-fails.jsonl")
    parser.add_argument("--out", type=Path, help="output directory (default: <eval_dir>/dataset)")
    parser.add_argument(
        "--min-fails",
        type=int,
        default=1,
        help="keep a sample only if it has at least this many shared-fail questions",
    )
    parser.add_argument(
        "--require-habit",
        action="append",
        default=[],
        help="keep a sample only if it failed this habit (repeatable)",
    )
    parser.add_argument(
        "--current-king",
        default=KING_URI,
        help="model@digest whose failed turns become DPO rejected (default: current king pin)",
    )
    args = parser.parse_args(argv)

    report = build(
        args.eval_dir,
        min_fails=args.min_fails,
        require_habits=set(args.require_habit) or None,
        current_king=args.current_king,
    )
    out_dir = args.out or (args.eval_dir / "dataset")
    out_dir.mkdir(parents=True, exist_ok=True)

    write_jsonl(out_dir / "sft.jsonl", report["sft"])
    write_jsonl(out_dir / "dpo.jsonl", report["dpo"])
    summary = {k: v for k, v in report.items() if k not in ("sft", "dpo")}
    (out_dir / "patterns.json").write_text(
        json.dumps(summary, indent=2) + "\n", encoding="utf-8"
    )

    print("shared-fail questions ", report["shared_fails"])
    print("samples with fails    ", report["samples_with_fails"])
    print("\nGeneralized habits")
    for row in report["patterns"]:
        print(f"  {row['n']:4}  {row['habit']:<28} {row['lesson']}")
    print(f"\nSFT rows              {report['sft_rows']}")
    print(f"DPO rows              {report['dpo_rows']}")
    if report["skipped"]:
        print(f"skipped               {report['skipped']}")
    print(f"wrote                 {out_dir / 'sft.jsonl'}")
    print(f"wrote                 {out_dir / 'dpo.jsonl'}")
    print(f"wrote                 {out_dir / 'patterns.json'}")
    return 0


if __name__ == "__main__":
    try:
        raise SystemExit(main())
    except Exception as exc:  # noqa: BLE001
        print(f"error: {exc}", file=sys.stderr)
        raise SystemExit(1)