File size: 5,637 Bytes
9368cc4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Generate compound tasks by combining already-validated single defects.

Every single-defect task in the corpus has been through the builder, so its
fault is known findable and its tests known correct against the reference. A
compound is the union of several such tasks whose broken files are disjoint --
that disjointness is what guarantees no single edit repairs more than one, which
is the property the difficulty dial depends on.

Nothing is invented here: the break overlays and the tests are the ones already
validated, and only the instruction is composed.
"""
import argparse, itertools, json, sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).parent))
from make_tasks import CORPUS  # noqa: E402


def read_tree(root: Path) -> dict:
    if not root.is_dir():
        return {}
    return {str(p.relative_to(root)): p.read_text()
            for p in sorted(root.rglob("*")) if p.is_file()}


def load_singles(repo: str):
    """Every task in `repo` that breaks exactly one file and is not compound."""
    out = []
    tasks_dir = CORPUS / repo / "tasks"
    for task_dir in sorted(tasks_dir.glob("*")):
        meta_path = task_dir / "task.json"
        if not meta_path.is_file():
            continue
        meta = json.loads(meta_path.read_text())
        if meta.get("compound"):
            continue
        broken = read_tree(task_dir / "break")
        tests = read_tree(task_dir / "tests")
        if len(broken) != 1 or not tests:
            continue          # compounds and malformed tasks are not ingredients
        out.append({
            "id": task_dir.name,
            "files": broken,
            "tests": tests,
            "instruction": meta["instruction"],
            "difficulty": meta.get("difficulty", 3),
        })
    return out


def compose_instruction(parts) -> str:
    """One triage ticket listing each symptom, renumbered."""
    head = (f"{len(parts)} findings from this week's triage. They have separate "
            f"causes and are not related to one another; all {len(parts)} need "
            f"fixing.\n")
    body = []
    for n, part in enumerate(parts, 1):
        # keep only the symptom prose, dropping each source task's own numbering
        text = part["instruction"].strip()
        text = "\n   ".join(line.strip() for line in text.splitlines() if line.strip())
        body.append(f"\n{n}. {text}")
    return head + "\n".join(body)


def build(repo: str, lang: str, size: int, limit: int, prefix: str):
    singles = load_singles(repo)
    made, used_pairs = 0, set()
    # Cap how often one defect is reused. Without this the generator anchors
    # nearly every compound on whichever ingredient sorts first, which
    # correlates the outcomes: one defect a model cannot fix would sink most of
    # the corpus at once, and the resolved rate would measure that single bug
    # rather than the breadth it is meant to.
    max_uses = max(2, (limit * size) // max(len(singles), 1) + 1)
    uses: dict = {}

    for combo in itertools.combinations(singles, size):
        if made >= limit:
            break
        touched = [set(c["files"]) for c in combo]
        # disjoint files: no single edit can repair two of them
        if any(a & b for a, b in itertools.combinations(touched, 2)):
            continue
        ids = tuple(sorted(c["id"] for c in combo))
        if any(uses.get(i, 0) >= max_uses for i in ids):
            continue
        # avoid re-using the same pair of ingredients across many compounds
        pairs = set(itertools.combinations(ids, 2))
        if pairs & used_pairs:
            continue
        used_pairs |= pairs
        for i in ids:
            uses[i] = uses.get(i, 0) + 1

        merged_files, merged_tests = {}, {}
        for part in combo:
            merged_files.update(part["files"])
            for name, body in part["tests"].items():
                key = name
                if key in merged_tests and merged_tests[key] != body:
                    stem, dot, ext = name.partition(".")
                    key = f"{stem}_{part['id'].replace('-', '_')}{dot}{ext}"
                merged_tests[key] = body

        task_id = f"{prefix}-{made + 1:02d}"
        tdir = CORPUS / repo / "tasks" / task_id
        (tdir / "tests").mkdir(parents=True, exist_ok=True)
        for rel, content in merged_files.items():
            out = tdir / "break" / rel
            out.parent.mkdir(parents=True, exist_ok=True)
            out.write_text(content)
        for name, body in merged_tests.items():
            (tdir / "tests" / name).write_text(body)
        (tdir / "task.json").write_text(json.dumps({
            "lang": lang,
            "category": "logic",
            "difficulty": 5,
            "compound": True,
            "ingredients": list(ids),
            "instruction": compose_instruction(combo),
        }, indent=2) + "\n")
        print(f"  {task_id}: {' + '.join(ids)}")
        made += 1

    print(f"{made} compound task(s) for {repo}")
    return made


if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("--size", type=int, default=3, help="defects per compound")
    ap.add_argument("--limit", type=int, default=8, help="max compounds per repo")
    args = ap.parse_args()

    total = 0
    for repo, lang, prefix in (("python/scheduler", "python", "triage"),
                               ("typescript/router", "typescript", "review"),
                               ("python/ledger", "python", "audit")):
        total += build(repo, lang, args.size, args.limit, f"{prefix}{args.size}")
    print(f"\n{total} total")