File size: 26,006 Bytes
f6e7a63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
#!/usr/bin/env python3
"""Build the mash finetune dataset: (mangled | natural-language) -> correct command.

Sources, in order of quality:
  1. Your own accepted fixes from ~/.fash/events.jsonl (kind=fix/args with a chosen
     command) — real human pairs, mixed in automatically.
  2. tldr-pages (github.com/tldr-pages/tldr, CC-BY-4.0): canonical example
     invocations for ~3000 commands, with per-example descriptions. Descriptions
     become natural-language -> command pairs; the commands get synthetically
     mangled into typo -> command pairs.

Mangling taxonomy (mirrors how commands really break — cf. thefuck's rules):
  transposed chars (gti status), dropped chars (grp), adjacent-key typos
  (gir status), doubled chars, single/double dash confusion (-help / --l),
  merged words (cd.. / gitpush), and stripped quotes.

Output: train/valid/test .jsonl in mlx-lm chat format, ready for `mlx_lm.lora`.

Usage:
  uv run python training/build_dataset.py --out training/data
  uv run python training/build_dataset.py --out training/data --max-pairs 20000 --no-events
"""

from __future__ import annotations

import argparse
import io
import json
import random
import re
import sys
import urllib.request
import zipfile
from pathlib import Path

# single source of truth for the context-header format Mash sees at inference
sys.path.insert(0, str(Path(__file__).parent.parent))
from fash.llm.prompts import local_context_block  # noqa: E402

SYSTEM_PROMPT = "Return the shell command the user most likely wants. Reply with the command only."

TLDR_ZIP_URL = "https://github.com/tldr-pages/tldr/archive/refs/heads/main.zip"
TLDR_SECTIONS = ("pages/common/", "pages/osx/", "pages/linux/")
EVENTS_PATH = Path("~/.fash/events.jsonl").expanduser()

# ------------------------------------------------------------------ tldr parsing

_EXAMPLE_RE = re.compile(r"^- (?P<desc>.+?):\s*$")
_CODE_RE = re.compile(r"^`(?P<cmd>.+)`\s*$")
_PLACEHOLDER_RE = re.compile(r"\{\{(.+?)\}\}")

# Concrete scenarios: the same noun fills the command placeholder AND rewrites
# the description, so NL pairs read like real requests ("open the settings
# file" -> `joe settings.json`) instead of template-speak mapped to arbitrary
# filenames.
# Each noun has several plausible concrete forms; exactly ONE appears in the
# synthetic directory listing, and the command must use that one — teaching the
# model to resolve "the settings file" against what actually exists.
FILE_SCENARIOS = [
    ("settings", ["settings.json", "settings.toml", "settings.yaml", "settings.ini"]),
    ("config", ["config.yaml", "config.json", "config.toml"]),
    ("notes", ["notes.txt", "notes.md"]),
    ("readme", ["README.md", "README.rst", "readme.txt"]),
    ("log", ["app.log", "server.log", "debug.log"]),
    ("deploy script", ["deploy.sh", "deploy.py"]),
    ("data", ["data.csv", "data.json"]),
    ("backup", ["backup.tar.gz", "backup.zip"]),
    ("env", [".env", ".env.local", ".env.production"]),
]
DIR_SCENARIOS = [
    ("source", ["./src"]),
    ("build", ["./build", "./dist"]),
    ("project", ["~/projects/demo"]),
    ("downloads", ["~/Downloads"]),
    ("temp", ["/tmp/scratch"]),
]

LISTING_DISTRACTORS = [
    "main.py", "package.json", "Makefile", ".gitignore", "src/", "tests/",
    "index.ts", "Dockerfile", "pyproject.toml", "LICENSE", "app.py",
    "utils.py", ".git/", "docs/", "scripts/", "requirements.txt",
]
CWD_POOL = ["~/projects/demo", "~/work/api", "~/code/webapp", "/opt/services/worker", "~/dev/tool"]

_FILE_PLACEHOLDER_RE = re.compile(r"path/to/.*file|filename|file", re.I)
_DIR_PLACEHOLDER_RE = re.compile(r"path/to/.*dir|directory|folder", re.I)

_PLACEHOLDER_VALUES = [
    (re.compile(r"branch", re.I), "main"),
    (re.compile(r"remote", re.I), "origin"),
    (re.compile(r"url|link", re.I), "https://example.com"),
    (re.compile(r"package|module|library", re.I), "requests"),
    (re.compile(r"port", re.I), "8080"),
    (re.compile(r"pid|process_id", re.I), "12345"),
    (re.compile(r"user(name)?", re.I), "alice"),
    (re.compile(r"host|server|ip", re.I), "example.com"),
    (re.compile(r"pattern|regex|search_term|query", re.I), "TODO"),
    (re.compile(r"message|commit", re.I), '"update readme"'),
    (re.compile(r"image", re.I), "ubuntu"),
    (re.compile(r"container", re.I), "web"),
    (re.compile(r"version|tag", re.I), "1.2.0"),
    (re.compile(r"count|number|n\b", re.I), "5"),
    (re.compile(r"name", re.I), "demo"),
]


def _fill_static(inner: str) -> str:
    for pattern, value in _PLACEHOLDER_VALUES:
        if pattern.search(inner):
            return value
    # fall back to the placeholder text itself, de-templated
    token = inner.strip().split("/")[-1] or "value"
    return re.sub(r"[^A-Za-z0-9._-]", "", token) or "value"


_GENERIC_FILE_RE = re.compile(r"\b(?:a|the)\s+(?:specific|specified|given|particular)\s+files?\b|\ba file\b", re.I)
_GENERIC_DIR_RE = re.compile(
    r"\b(?:a|the)\s+(?:specific|specified|given|particular)\s+(?:directory|folder)\b|\ba (?:directory|folder)\b", re.I
)


def _pick_scenario(scenarios: list, hints: str, rng: random.Random) -> tuple[str, list[str]]:
    """Prefer the scenario the example already talks about ('config', 'log', …)."""
    for noun, variants in scenarios:
        if noun.split()[0] in hints:
            return noun, variants
    return rng.choice(scenarios)


def make_listing(must_contain: list[str], rng: random.Random) -> list[str]:
    """A plausible cwd listing containing the target entries plus distractors.

    Distractors never include confusable siblings of the targets, so exactly
    one 'settings.*' (etc.) exists and the model must use the one that's there.
    """
    entries = set(must_contain)
    entries.update(rng.sample(LISTING_DISTRACTORS, rng.randint(4, 8)))
    return sorted(entries, key=str.lower)


def fill_example(description: str, command_template: str, rng: random.Random) -> tuple[str, str, str]:
    """Fill placeholders with a concrete scenario; rewrite the description to
    match; return a context header grounding the choice in a directory listing.

    'Open a specific file:' + `joe {{path/to/file}}` ->
      ('Open the settings file:', 'joe settings.toml',
       'cwd: ~/work/api\\nfiles: .git/  Makefile  settings.toml  src/')
    """
    hints = f"{description} {command_template}".lower()
    file_noun, file_variants = _pick_scenario(FILE_SCENARIOS, hints, rng)
    file_value = rng.choice(file_variants)
    dir_noun, dir_variants = _pick_scenario(DIR_SCENARIOS, hints, rng)
    dir_value = rng.choice(dir_variants)
    used = {"file": False, "dir": False}

    typed_files: list[str] = []

    def _fill(match: re.Match) -> str:
        inner = match.group(1).split("|")[0]
        if _DIR_PLACEHOLDER_RE.search(inner):
            used["dir"] = True
            return dir_value
        if _FILE_PLACEHOLDER_RE.search(inner):
            base = inner.strip().split("/")[-1]
            # extension-typed placeholders ({{path/to/file.pam}}) keep their
            # extension — `pamfile settings.json` would be nonsense
            if re.search(r"\.[A-Za-z0-9]{1,6}$", base):
                cleaned = re.sub(r"[^A-Za-z0-9._-]", "", base)
                typed_files.append(cleaned)
                return cleaned
            used["file"] = True
            return file_value
        return _fill_static(inner)

    command = _PLACEHOLDER_RE.sub(_fill, command_template).strip()
    context = ""
    targets: list[str] = []
    if used["file"]:
        description = _GENERIC_FILE_RE.sub(f"the {file_noun} file", description)
        targets.append(file_value)
    targets.extend(typed_files)
    if used["dir"]:
        description = _GENERIC_DIR_RE.sub(f"the {dir_noun} directory", description)
        if dir_value.startswith("./"):
            targets.append(dir_value[2:] + "/")
    if targets:
        context = local_context_block(rng.choice(CWD_POOL), make_listing(targets, rng))
    return description, command, context


def parse_tldr_page(text: str) -> list[tuple[str, str]]:
    """Return (description, command_template) pairs from one tldr page body.

    Placeholders are left intact — fill_example() resolves them per example so
    the description and the filled command stay coherent.
    """
    pairs: list[tuple[str, str]] = []
    description = ""
    for line in text.splitlines():
        described = _EXAMPLE_RE.match(line)
        if described:
            description = described.group("desc").strip()
            continue
        code = _CODE_RE.match(line)
        if code:
            command = code.group("cmd").strip()
            if command and len(command) <= 160 and not command.startswith("#"):
                pairs.append((description, command))
            description = ""
    return pairs


def load_tldr_pairs(cache_dir: Path) -> list[tuple[str, str]]:
    cache_dir.mkdir(parents=True, exist_ok=True)
    zip_path = cache_dir / "tldr-main.zip"
    if zip_path.exists() and not zipfile.is_zipfile(zip_path):
        print("cached tldr zip is corrupt (interrupted download?) — refetching")
        zip_path.unlink()
    if not zip_path.exists():
        print(f"downloading tldr-pages ({TLDR_ZIP_URL}) …")
        partial = zip_path.with_suffix(".part")
        with urllib.request.urlopen(TLDR_ZIP_URL, timeout=120) as response:
            partial.write_bytes(response.read())
        if not zipfile.is_zipfile(partial):
            partial.unlink(missing_ok=True)
            raise SystemExit("downloaded tldr archive is not a valid zip — try again")
        partial.rename(zip_path)
    pairs: list[tuple[str, str]] = []
    with zipfile.ZipFile(io.BytesIO(zip_path.read_bytes())) as archive:
        for name in archive.namelist():
            if not name.endswith(".md"):
                continue
            if not any(section in name for section in TLDR_SECTIONS):
                continue
            pairs.extend(parse_tldr_page(archive.read(name).decode("utf-8", errors="replace")))
    return pairs


# ------------------------------------------------------------------ casual requests

_STOPWORDS = {"a", "an", "the", "your", "specific", "given", "particular", "certain", "currently"}
_VERB_SWAPS = [
    (re.compile(r"^display\b"), "show"),
    (re.compile(r"^print\b"), "show"),
    (re.compile(r"^view\b"), "show"),
    (re.compile(r"^remove\b"), "delete"),
    (re.compile(r"^execute\b"), "run"),
]


def casualize(description: str, rng: random.Random) -> list[str]:
    """Terse request variants of a tldr description — how people actually type.

    'Commit staged files to the repository with a message:' ->
      ['commit staged files with message', 'commit staged files']
    """
    base = description.rstrip(":").strip().lower()
    if not base:
        return []
    # cut trailing clauses
    base = base.split(";")[0].split(". ")[0]
    words = [w for w in base.split() if w not in _STOPWORDS]
    if not words:
        return []
    terse = " ".join(words)
    for pattern, replacement in _VERB_SWAPS:
        terse = pattern.sub(replacement, terse)
    variants = [terse]
    # even shorter: cut at the first comma or first preposition-y tail
    comma_cut = terse.split(",")[0].strip()
    if comma_cut != terse and len(comma_cut.split()) >= 2:
        variants.append(comma_cut)
    words = terse.split()
    if len(words) > 5:
        for cut_word in ("to", "from", "in", "with", "using", "for"):
            if cut_word in words[2:]:
                short = " ".join(words[: words[2:].index(cut_word) + 2]).strip()
                if len(short.split()) >= 2:
                    variants.append(short)
                break
    # dedupe preserving order; return at most 2, randomly favoring the shortest
    seen: list[str] = []
    for variant in variants:
        if variant not in seen:
            seen.append(variant)
    if len(seen) > 2:
        seen = [seen[0], rng.choice(seen[1:])]
    return seen


# ------------------------------------------------------------------ common head typos

# highest-frequency real-world command typos; each always yields a training pair
COMMON_TYPOS = {
    "git": ["gti", "gt", "gitt", "igt"],
    "grep": ["gerp", "grpe", "gerep"],
    "ls": ["sl", "lls", "l s"],
    "cd": ["dc", "cd.."],
    "clear": ["celar", "claer", "clera"],
    "sudo": ["suod", "sudp", "sduo"],
    "python": ["pyhton", "pytohn", "pythno"],
    "python3": ["pyhton3", "pytohn3"],
    "docker": ["dokcer", "docekr", "dcoker"],
    "kubectl": ["kubeclt", "kubctl", "kubetcl"],
    "npm": ["nmp", "npn"],
    "make": ["mkae", "amke"],
    "ssh": ["shh", "ssh-"],
    "curl": ["culr", "crul"],
    "brew": ["brwe", "berw"],
    "cargo": ["cagro", "carog"],
    "vim": ["ivm", "vmi"],
    "tar": ["tra", "atr"],
    "find": ["fnid", "fidn"],
    "chmod": ["chmdo", "cmhod"],
}


def head_typo(command: str, rng: random.Random) -> str | None:
    head, _, rest = command.partition(" ")
    typos = COMMON_TYPOS.get(head)
    if not typos:
        return None
    mangled_head = rng.choice(typos)
    return f"{mangled_head} {rest}".strip()


# ------------------------------------------------------------------ manglers

QWERTY_NEIGHBORS = {
    "q": "wa", "w": "qes", "e": "wrd", "r": "etf", "t": "ryg", "y": "tuh",
    "u": "yij", "i": "uok", "o": "ipl", "p": "o", "a": "qsz", "s": "adwx",
    "d": "sfec", "f": "dgrv", "g": "fhtb", "h": "gjyn", "j": "hkum",
    "k": "jli", "l": "ko", "z": "asx", "x": "zsdc", "c": "xdfv",
    "v": "cfgb", "b": "vghn", "n": "bhjm", "m": "njk",
}


def _word_spans(command: str) -> list[tuple[int, int]]:
    """Spans of alphabetic words worth corrupting (commands/subcommands, not values)."""
    spans = []
    for match in re.finditer(r"[A-Za-z]{3,}", command):
        # don't corrupt inside quotes
        prefix = command[: match.start()]
        if prefix.count('"') % 2 == 0 and prefix.count("'") % 2 == 0:
            spans.append(match.span())
    return spans[:3]  # bias corruption toward the head of the line


def mangle_transpose(command: str, rng: random.Random) -> str | None:
    spans = _word_spans(command)
    if not spans:
        return None
    start, end = rng.choice(spans)
    if end - start < 3:
        return None
    i = rng.randrange(start, end - 1)
    chars = list(command)
    chars[i], chars[i + 1] = chars[i + 1], chars[i]
    return "".join(chars)


def mangle_drop(command: str, rng: random.Random) -> str | None:
    spans = _word_spans(command)
    if not spans:
        return None
    start, end = rng.choice(spans)
    i = rng.randrange(start, end)
    return command[:i] + command[i + 1 :]


def mangle_adjacent(command: str, rng: random.Random) -> str | None:
    spans = _word_spans(command)
    if not spans:
        return None
    start, end = rng.choice(spans)
    candidates = [i for i in range(start, end) if command[i].lower() in QWERTY_NEIGHBORS]
    if not candidates:
        return None
    i = rng.choice(candidates)
    replacement = rng.choice(QWERTY_NEIGHBORS[command[i].lower()])
    if command[i].isupper():
        replacement = replacement.upper()
    return command[:i] + replacement + command[i + 1 :]


def mangle_double(command: str, rng: random.Random) -> str | None:
    spans = _word_spans(command)
    if not spans:
        return None
    start, end = rng.choice(spans)
    i = rng.randrange(start, end)
    return command[:i] + command[i] + command[i:]


def mangle_dashes(command: str, rng: random.Random) -> str | None:
    double = list(re.finditer(r"(?<!\S)--(\w[\w-]+)", command))
    single = list(re.finditer(r"(?<!\S)-(\w)(?!\w)", command))
    if double and (not single or rng.random() < 0.5):
        match = rng.choice(double)
        return command[: match.start()] + "-" + match.group(1) + command[match.end() :]
    if single:
        match = rng.choice(single)
        return command[: match.start()] + "--" + match.group(1) + command[match.end() :]
    return None


def mangle_merge_words(command: str, rng: random.Random) -> str | None:
    spaces = [i for i, ch in enumerate(command) if ch == " "]
    if not spaces:
        return None
    i = rng.choice(spaces[:2])  # merging happens near the head (cd.., gitpush)
    return command[:i] + command[i + 1 :]


def mangle_unquote(command: str, rng: random.Random) -> str | None:
    match = re.search(r"([\"'])(.+?)\1", command)
    if not match:
        return None
    return command[: match.start()] + match.group(2) + command[match.end() :]


def mangle_sudo(command: str, rng: random.Random) -> str | None:
    # missing sudo (the common real-world case) or a spurious one
    if command.startswith("sudo "):
        return command[len("sudo ") :]
    if rng.random() < 0.3 and not command.startswith(("cd", "export")):
        return "sudo " + command
    return None


def mangle_prompt_prefix(command: str, rng: random.Random) -> str | None:
    # copy-pasted from docs with the shell prompt still attached
    return ("$ " if rng.random() < 0.8 else "> ") + command


def mangle_dup_word(command: str, rng: random.Random) -> str | None:
    head, sep, rest = command.partition(" ")
    if not sep:
        return None
    return f"{head} {head} {rest}"


_SMART_SWAPS = [("'", "’"), ('"', "“"), ("--", "–")]


def mangle_smart_chars(command: str, rng: random.Random) -> str | None:
    # smart quotes / en-dashes picked up from web pages
    applicable = [(a, b) for a, b in _SMART_SWAPS if a in command]
    if not applicable:
        return None
    plain, smart = rng.choice(applicable)
    return command.replace(plain, smart, 1)


MANGLERS = [
    (mangle_transpose, 0.24),
    (mangle_drop, 0.12),
    (mangle_adjacent, 0.16),
    (mangle_double, 0.08),
    (mangle_dashes, 0.09),
    (mangle_merge_words, 0.08),
    (mangle_unquote, 0.04),
    (mangle_sudo, 0.08),
    (mangle_prompt_prefix, 0.06),
    (mangle_dup_word, 0.03),
    (mangle_smart_chars, 0.02),
]


def mangle(command: str, rng: random.Random) -> str | None:
    """Apply one weighted-random corruption; occasionally two."""
    result = command
    rounds = 2 if rng.random() < 0.15 else 1
    changed = False
    for _ in range(rounds):
        # weighted permutation (Efraimidis-Spirakis) — tries every mangler once,
        # in weight-biased order, so an applicable one is never skipped
        ordered = sorted(MANGLERS, key=lambda mw: rng.random() ** (1.0 / mw[1]), reverse=True)
        for fn, _ in ordered:
            mangled = fn(result, rng)
            if mangled and mangled != result:
                result = mangled
                changed = True
                break
    return result if changed and result != command else None


# ------------------------------------------------------------------ nl2bash

NL2BASH_CM_URL = "https://raw.githubusercontent.com/TellinaTool/nl2bash/master/data/bash/all.cm"
NL2BASH_NL_URL = "https://raw.githubusercontent.com/TellinaTool/nl2bash/master/data/bash/all.nl"


def load_nl2bash_pairs(cache_dir: Path) -> list[tuple[str, str]]:
    """(description, command) pairs from the NL2Bash corpus (MIT). Best-effort."""
    cache_dir.mkdir(parents=True, exist_ok=True)
    texts: list[str] = []
    for url, name in ((NL2BASH_NL_URL, "nl2bash.nl"), (NL2BASH_CM_URL, "nl2bash.cm")):
        path = cache_dir / name
        try:
            if not path.exists():
                with urllib.request.urlopen(url, timeout=60) as response:
                    path.write_bytes(response.read())
            texts.append(path.read_text(encoding="utf-8", errors="replace"))
        except (OSError, urllib.error.URLError):
            print(f"note: could not fetch {name} — continuing without nl2bash")
            return []
    descriptions, commands = texts[0].splitlines(), texts[1].splitlines()
    pairs: list[tuple[str, str]] = []
    for desc, cmd in zip(descriptions, commands):
        desc, cmd = desc.strip(), cmd.strip()
        if desc and cmd and len(cmd) <= 120:
            pairs.append((desc, cmd))
    return pairs


# ------------------------------------------------------------------ fash events

_COMMAND_FILE_RE = re.compile(
    r"\b[\w.-]+\.(?:gz|tgz|tar|zip|txt|csv|tsv|json|yaml|yml|toml|md|log|py|sh|rb|js|ts|go|rs|c|cpp|h|pdf|png|jpg|mov|mp4|conf|cfg|ini|sql|env)\b"
)


def extract_files_from_command(command: str) -> list[str]:
    """Concrete filenames already present in a command (nl2bash rows have no
    placeholders) — they seed a listing so context-conditioning covers that
    corpus too."""
    return list(dict.fromkeys(_COMMAND_FILE_RE.findall(command)))[:3]


def load_event_pairs() -> list[tuple[str, str]]:
    """Accepted fixes from your own fash usage: the highest-quality pairs."""
    if not EVENTS_PATH.exists():
        return []
    pairs: list[tuple[str, str]] = []
    with EVENTS_PATH.open("r", encoding="utf-8") as handle:
        for raw in handle:
            try:
                event = json.loads(raw)
            except json.JSONDecodeError:
                continue
            if event.get("kind") in {"fix", "args"} and event.get("chosen") and event.get("line"):
                pairs.append((str(event["line"]), str(event["chosen"])))
    return pairs


# ------------------------------------------------------------------ assembly

def row(user: str, assistant: str) -> dict:
    return {
        "messages": [
            {"role": "system", "content": SYSTEM_PROMPT},
            {"role": "user", "content": user},
            {"role": "assistant", "content": assistant},
        ]
    }


def build(out_dir: Path, max_pairs: int, seed: int, include_events: bool, nl_share: float) -> None:
    rng = random.Random(seed)
    cache = Path(__file__).parent / ".cache"
    tldr = load_tldr_pairs(cache)
    print(f"tldr examples: {len(tldr)}")
    nl2bash = load_nl2bash_pairs(cache)
    print(f"nl2bash examples: {len(nl2bash)}")
    corpus = tldr + nl2bash
    rng.shuffle(corpus)

    def with_context(user: str, context: str, probability: float) -> str:
        """Attach the cwd/files header some of the time — Mash must work both
        with context (to resolve 'the settings file' against the listing) and
        bare (context capture may be unavailable)."""
        if context and rng.random() < probability:
            return f"{context}\n{user}"
        return user

    rows: list[dict] = []
    for raw_description, template in corpus:
        description, command, context = fill_example(raw_description, template, rng)
        if not command or len(command) > 120:
            continue
        if not context:
            named = extract_files_from_command(command)
            if named:
                context = local_context_block(rng.choice(CWD_POOL), make_listing(named, rng))
            elif rng.random() < 0.08:
                # irrelevant listing: teaches ignoring context that doesn't help
                context = local_context_block(rng.choice(CWD_POOL), make_listing([], rng))
        mangled = mangle(command, rng)
        if mangled:
            rows.append(row(with_context(mangled, context, 0.5), command))
        typo = head_typo(command, rng)
        if typo:
            rows.append(row(typo, command))
        if description and rng.random() < nl_share:
            for variant in casualize(description, rng):
                # NL requests get the listing most of the time: choosing the
                # file that actually exists is the whole point
                rows.append(row(with_context(variant, context, 0.85), command))
        # identity pairs: correct input maps to itself, so the model learns not
        # to over-correct (its echo doubles as an "already fine" signal). Kept
        # small — at ~12% of rows a 1.5B run learned to echo 39% of genuinely
        # garbled inputs; ~5% preserves the signal without teaching timidity.
        if rng.random() < 0.10:
            rows.append(row(command, command))
        if len(rows) >= max_pairs:
            break

    event_rows: list[dict] = []
    if include_events:
        event_pairs = list(dict.fromkeys(load_event_pairs()))  # dedupe, keep order
        print(f"pairs from your fash history: {len(event_pairs)}")
        event_rows = [row(garbled, chosen) for garbled, chosen in event_pairs]
        rows.extend(event_rows)  # once each — upweighting happens after the split

    rng.shuffle(rows)
    n = len(rows)
    valid_n = max(64, int(n * 0.02)) if n > 200 else max(1, n // 10)
    splits = {
        "valid": rows[:valid_n],
        "test": rows[valid_n : valid_n * 2],
        "train": rows[valid_n * 2 :],
    }
    if event_rows:
        # 3x weight for real accepted-fix pairs, applied only inside train so
        # duplicates can never leak into valid/test
        event_keys = {json.dumps(r, sort_keys=True) for r in event_rows}
        extra = [r for r in splits["train"] if json.dumps(r, sort_keys=True) in event_keys]
        splits["train"].extend(extra * 2)
        rng.shuffle(splits["train"])
    out_dir.mkdir(parents=True, exist_ok=True)
    for name, split_rows in splits.items():
        path = out_dir / f"{name}.jsonl"
        with path.open("w", encoding="utf-8") as handle:
            for item in split_rows:
                handle.write(json.dumps(item, ensure_ascii=False) + "\n")
        print(f"{path}: {len(split_rows)} rows")


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--out", type=Path, default=Path(__file__).parent / "data")
    parser.add_argument("--max-pairs", type=int, default=42000)
    parser.add_argument("--seed", type=int, default=7)
    parser.add_argument("--nl-share", type=float, default=0.4, help="fraction of examples that also emit natural-language request pairs")
    parser.add_argument("--no-events", dest="events", action="store_false", help="skip pairs from ~/.fash/events.jsonl")
    args = parser.parse_args()
    build(args.out, args.max_pairs, args.seed, args.events, args.nl_share)


if __name__ == "__main__":
    main()