File size: 27,919 Bytes
7e7a701
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cef0508
 
 
7e7a701
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d9fb919
 
 
 
 
 
 
 
 
7e7a701
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cef0508
7e7a701
 
 
 
 
 
 
 
 
 
d9fb919
 
 
7e7a701
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d9fb919
 
 
 
 
 
 
 
 
7e7a701
 
 
d9fb919
 
7e7a701
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cef0508
 
 
7e7a701
 
 
 
 
 
 
 
 
d9fb919
7e7a701
 
cef0508
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7e7a701
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cef0508
 
 
 
7e7a701
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cef0508
 
 
 
 
7e7a701
 
cef0508
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7e7a701
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Standalone validator for the Bash instruction-tuning dataset.

This file is INTENTIONALLY DECOUPLED from generate.py -- generation never calls
it. Run it by hand whenever you want to grade a dataset file.

Checks
  (a) bash -n on every command                 -> syntax-failure rate
  (b) shellcheck (if available), warning-level  -> finding rate, by SC code
  (c) real execution of a SAFE subset in a      -> execution-error rate
      disposable fixture dir  (opt-in: --execute)
  (d) summary of (a)/(b)/(c) broken down by category and utility

Safety: the execution pass runs ONLY self-contained, non-destructive, non-network
commands, inside a throwaway temp dir populated with dummy files/dirs named after
what each command references. Anything matching rm/dd/mkfs/shutdown/reboot/fork-bomb,
touching absolute/system paths, redirecting/writing outside the sandbox, or using
the network is skipped -- never executed.

Usage
  python validate.py                         # static checks (a,b) on the whole file
  python validate.py --data bash_dataset.jsonl
  python validate.py --shellcheck-n 4000     # cap the shellcheck sample (0 = all)
  python validate.py --execute --n 3000      # also run (c) on up to 3000 safe cmds
"""
import argparse, collections, json, os, re, shutil, subprocess, tempfile, random, sys

HERE = os.path.dirname(os.path.abspath(__file__))

def find_bash():
    return shutil.which("bash") or r"C:\Users\User\AppData\Local\Programs\Git\usr\bin\bash.exe"

def find_shellcheck():
    for c in (shutil.which("shellcheck"),
              os.path.join(HERE, ".venv", "Scripts", "shellcheck.exe"),
              os.path.join(HERE, ".venv", "bin", "shellcheck")):
        if c and os.path.exists(c):
            return c
    return None

BASH = find_bash()
SHELLCHECK = find_shellcheck()

def row_nl_bash(o):
    if "messages" in o:
        nl = next(m["content"] for m in o["messages"] if m["role"] == "user")
        bash = next(m["content"] for m in o["messages"] if m["role"] == "assistant")
        return nl, bash
    return o.get("nl", ""), o.get("bash", "")

def load(path):
    rows = []
    with open(path, encoding="utf-8") as fh:
        for line in fh:
            line = line.strip()
            if not line:
                continue
            o = json.loads(line)
            nl, bash = row_nl_bash(o)
            rows.append({"nl": nl, "bash": bash,
                         "category": o.get("category", "?"),
                         "utility": o.get("utility", "?"),
                         "variant_group": o.get("variant_group")})
    return rows

# ----------------------------------------------------------------- (a) bash -n
def bash_n(snippets, chunk=400):
    """Return list[bool] valid? Wraps snippets as functions so multi-line scripts
    parse; falls back to per-snippet on a chunk failure to localize the culprit."""
    d = tempfile.mkdtemp(prefix="bn_")
    out = [True] * len(snippets)
    try:
        for k in range(0, len(snippets), chunk):
            grp = list(range(k, min(k + chunk, len(snippets))))
            combined = os.path.join(d, "c.sh")
            with open(combined, "w", encoding="utf-8", newline="\n") as fh:
                for i in grp:
                    fh.write(f"__v{i}() {{\n{snippets[i]}\n}}\n")
            r = subprocess.run([BASH, "-n", combined], capture_output=True, text=True)
            if r.returncode == 0:
                continue
            for i in grp:                        # localize failures in this chunk
                p = os.path.join(d, "s.sh")
                with open(p, "w", encoding="utf-8", newline="\n") as fh:
                    fh.write(f"__v() {{\n{snippets[i]}\n}}\n")
                rr = subprocess.run([BASH, "-n", p], capture_output=True, text=True)
                out[i] = rr.returncode == 0
    finally:
        shutil.rmtree(d, ignore_errors=True)
    return out

# ------------------------------------------------------------- (b) shellcheck
def shellcheck(rows, cap):
    if not SHELLCHECK:
        return None
    sample = rows if (cap == 0 or cap >= len(rows)) else random.sample(rows, cap)
    d = tempfile.mkdtemp(prefix="sc_")
    files = []
    try:
        for i, r in enumerate(sample):
            p = os.path.join(d, f"s{i}.sh")
            head = "" if r["bash"].startswith("#!") else "#!/usr/bin/env bash\n"
            with open(p, "w", encoding="utf-8", newline="\n") as fh:
                fh.write(head + r["bash"] + "\n")
            files.append((p, r))
        path2row = dict(files)
        codes = collections.Counter()
        flagged = set()
        cat_flag = collections.Counter(); util_flag = collections.Counter()
        for k in range(0, len(files), 150):
            print(f"   shellcheck {k}/{len(files)}", flush=True)
            chunk = files[k:k + 150]
            r = subprocess.run([SHELLCHECK, "-f", "json", "-S", "warning"] + [p for p, _ in chunk],
                               capture_output=True, text=True)
            try:
                issues = json.loads(r.stdout or "[]")
            except json.JSONDecodeError:
                issues = []
            for it in issues:
                f = it.get("file")
                if f in flagged:
                    continue
                codes[f"SC{it['code']}"] += 1
                flagged.add(f)
                row = path2row.get(f)
                if row:
                    cat_flag[row["category"]] += 1
                    util_flag[row["utility"]] += 1
        return {"n": len(sample), "flagged": len(flagged), "codes": codes,
                "cat_flag": cat_flag, "util_flag": util_flag}
    finally:
        shutil.rmtree(d, ignore_errors=True)

# ------------------------------------------------------------- (c) execution
SAFE_UTIL = {"grep", "awk", "sed", "sort", "uniq", "wc", "cut", "tr", "head", "tail",
             "cat", "ls", "find", "nl", "stat", "file", "date", "comm", "paste",
             "cp", "mkdir", "touch", "echo", "printf", "basename", "dirname", "seq",
             "tac", "rev", "fold", "column", "diff", "cmp"}
DANGER = re.compile(r"(^|[\s;&|(])(sudo|rm|rmdir|dd|mkfs\w*|shred|kill|pkill|killall|"
                    r"reboot|shutdown|halt|poweroff|mv|chmod|chown|chgrp|ln|truncate|"
                    r"curl|wget|ssh|scp|rsync|ping|nc|telnet|systemctl|journalctl|service|"
                    r"apt|apt-get|dnf|yum|pacman|brew|pip|npm|git|docker|mount|umount|"
                    r"nice|renice|crontab|tee|gzip|gunzip|zip|unzip|tar|make|convert)([\s;&|)]|$)")
ABSPATH = re.compile(r"(^|[\s'\"=<>(])/(etc|var|srv|opt|home|mnt|usr|dev|proc|sys|boot|root|"
                     r"tmp|backup|data|lib|bin|sbin|run)\b|(^|\s)/\w")
WRITEOUT = re.compile(r">>?\s*/|>\s*/dev/(?!null)")
FORKBOMB = re.compile(r":\s*\(\s*\)\s*\{")
# strip `sudo` only in COMMAND position (start, or after ; | && || `(`), never when
# it's an argument -- e.g. `chgrp sudo file` (group named "sudo") must stay intact.
SUDO = re.compile(r"(^|[;&|(]\s*)sudo\s+")
_GREP_TAIL = re.compile(r"\|\s*(?:z|e|f)?grep\b[^|]*$")   # pipeline ending in grep -> rc1 = no match

# --- permissive mode (throwaway Linux, e.g. WSL) ----------------------------
# In permissive mode almost every single-line command is executed; only two
# classes are withheld: HARD_BLOCK (could damage the host/VM with zero test
# value) and HANG/NET (would block forever or reach the network). Everything
# else runs in a sandbox dir with a timeout and stdin from /dev/null.
_SYS = r"(?:etc|var|usr|boot|lib|lib64|bin|sbin|root|opt|srv|dev|proc|sys|run|mnt|media)"
HARD_BLOCK = re.compile(
    r"(?:^|[\s;&|(])(?:dd|mkfs\w*|mkswap|fdisk|parted|sgdisk|wipefs|blkdiscard|hdparm|"
    r"shutdown|reboot|halt|poweroff|telinit|kexec|mount|umount|swapon|swapoff|"
    r"useradd|userdel|usermod|groupadd|groupdel|passwd|chpasswd|visudo|init|"
    r"kill|pkill|killall|skill|fuser|"             # process-killers can kill the validator itself
    r"crontab)\b"                                  # crontab installs persistent jobs
    r"|of=/dev/|/dev/(?:sd|nvme|vd|mapper)|--no-preserve-root")
WRITE_SYS = re.compile(
    rf"\b(?:rm|rmdir|mv|cp|chmod|chown|chgrp|ln|truncate|shred|tee|install|rsync)\b[^|]*\s/{_SYS}\b"
    rf"|\bsed\s+-i\b[^|]*\s/{_SYS}\b|>>?\s*/{_SYS}\b|\bfind\b[^|]*\s/{_SYS}\b[^|]*-delete"
    rf"|>>?\s*~/|>>?\s*\$HOME|\b(?:rm|mv|shred)\b[^|]*\s~/")
HANG = re.compile(
    r"\b(?:top|htop|watch|vi|vim|nvim|nano|emacs|less|more|man|tmux|screen|irb|ipython|"
    r"mysql|psql|sqlite3|python|python3|node|ssh|sftp|telnet|curl|wget|scp|nc|ncat|netcat)\b"
    r"|\btail\b[^|]*\s-f\b|\bjournalctl\b[^|]*(?:\s-f\b|--follow)|\bdmesg\b[^|]*\s-w\b"
    r"|\bping6?\b|\brsync\b[^|]*@|\byes\b|/dev/(?:zero|urandom|random)"
    r"|\b(?:vmstat|iostat|mpstat|pidstat|sar|dstat)\b\s+\d|\bfree\b[^|]*\s-s\b"
    r"|\b(?:apt|apt-get|dnf|yum|pacman|zypper|snap|flatpak|pip|pip3|npm|npx|yarn|gem|"
    r"cargo|go|brew|docker|make)\b[^|]*\b(?:install|reinstall|update|upgrade|add|pull|"
    r"run|build|-S|-Sy|-Syu)\b"
    r"|\bsleep\b\s+(?:[3-9]|\d\d+)")

# Scripts (multi-line) run in permissive mode too, but infinite loops / sleeps /
# follow-watches would hang. Interactive read/select are safe: with stdin from
# /dev/null they hit EOF and exit fast under `set -e`.
SCRIPT_HANG = re.compile(
    r"while\s+(?:true|:)\b|\bsleep\b"
    r"|\btail\b[^\n]*\s-f\b|\bjournalctl\b[^\n]*\s-f\b|\bdmesg\b[^\n]*\s-w\b|\bwatch\b", re.I)

def exec_class(bash, util, permissive=False):
    """Return 'run' if the command should be executed, else a reason label."""
    if "\n" in bash:
        if not permissive:
            return "multiline"
        if FORKBOMB.search(bash) or HARD_BLOCK.search(bash) or WRITE_SYS.search(bash):
            return "block"
        if HANG.search(bash) or SCRIPT_HANG.search(bash):
            return "skip"
        return "run"
    if permissive:
        if FORKBOMB.search(bash) or HARD_BLOCK.search(bash) or WRITE_SYS.search(bash):
            return "block"
        if HANG.search(bash):
            return "skip"
        return "run"
    # strict (default) mode
    if util not in SAFE_UTIL:
        return "util"
    if FORKBOMB.search(bash) or DANGER.search(bash):
        return "block"
    if ABSPATH.search(bash):
        return "abspath"
    if WRITEOUT.search(bash):
        return "writeout"
    if "$(" in bash or "`" in bash:
        return "cmdsub"
    return "run"

REFED = re.compile(r"[\w./-]+\.\w+|\b(?:src|logs|backup|data|tmp|project|dist|build|config|"
                   r"docs|reports|uploads|scripts|assets|public|cache|vendor|images|media|"
                   r"tests|include|static|templates|fixtures|downloads|releases|artifacts)\b")
SEED_LINES = "\n".join([
    "alice,30,alice@example.com", "bob,25,bob@example.org", "carol,41,carol@example.net",
    "ERROR something failed", "WARNING low disk", "INFO ok", "DEBUG trace", "ERROR again",
    "192.168.1.10 GET /index 200", "10.0.0.5 POST /api 500", "apple", "banana", "apple",
    "1 2 3", "4 5 6", "7 8 9", "",
] * 4)

def build_sandbox(cmds):
    sb = tempfile.mkdtemp(prefix="ds_sandbox_")
    def write_file(path):
        os.makedirs(os.path.dirname(path) or sb, exist_ok=True)
        if not os.path.exists(path):
            with open(path, "w", encoding="utf-8", newline="\n") as fh:
                fh.write(SEED_LINES)
    for bash in cmds:
        for tok in REFED.findall(bash):
            tok = tok.strip("'\"")
            if tok.startswith("/") or ".." in tok or tok.startswith("-"):
                continue
            path = os.path.join(sb, tok)
            try:
                if "." in os.path.basename(tok):
                    write_file(path)
                else:
                    os.makedirs(path, exist_ok=True)
                    for fn in ("a.txt", "b.log", "c.csv"):
                        write_file(os.path.join(path, fn))
            except OSError:
                pass
    for fn in ("part1.txt", "part2.txt", "packages.txt", "checksums.txt", "data.csv",
               "access.log", "metrics.log", "inventory.csv", "users.txt", "emails.txt",
               "syslog", "messages", "app.log", "error.log", "cleanup.log", "output.log",
               "hosts.txt", "servers.txt", "urls.txt", "nodes.txt", "targets.txt",
               "config.yaml", "config.json", "clean.txt", "whole.txt", "emails.txt"):
        write_file(os.path.join(sb, fn))
    return sb

_ENV_UTIL = {"systemctl", "journalctl", "service", "timedatectl", "loginctl",
             "systemd-analyze", "hostnamectl", "dmesg", "renice", "nice"}
_ENV_ERR = re.compile(r"System has not been booted with systemd|Failed to connect to bus|"
                      r"Operation not permitted|must be run as root|are you root|"
                      r"Permission denied|Read-only file system|not permitted", re.I)
# a bad flag mid-pipeline can leave the pipeline exit 0 (a downstream stage
# succeeds), so scan EVERY stage's stderr for these -- caught regardless of exit.
_BADFLAG = re.compile(r"invalid option|unrecognized option|unknown option|illegal option|"
                      r"invalid argument|invalid line count|option requires an argument|"
                      r"not an option", re.I)
# an upstream grep/find/cmp that matches nothing exits non-zero; under pipefail
# that propagates to the pipeline with NO stderr -> not a real error.
_NOMATCH_STAGE = re.compile(r"(?:^|[\s|(])(?:z|e|f)?grep\b|\bfind\b|\bcmp\b|\bcomm\b|"
                            r"\bdiff\b|\bpgrep\b")

def execute(rows, n, permissive=False, timeout=8):
    cls = collections.Counter(exec_class(r["bash"], r["utility"], permissive) for r in rows)
    cands = [r for r in rows if exec_class(r["bash"], r["utility"], permissive) == "run"]
    random.shuffle(cands)
    cands = cands[:n]
    print(f"mode: {'PERMISSIVE (throwaway Linux)' if permissive else 'strict/safe'}  "
          f"| timeout {timeout}s | stdin=/dev/null | sudo stripped")
    print(f"eligible -> executed: {len(cands)} (n cap {n})  of {len(rows)} rows")
    notrun = ", ".join(f"{k}={v}" for k, v in cls.items() if k != "run")
    print(f"not executed: {notrun}")
    if not cands:
        return None
    sb = build_sandbox([r["bash"] for r in cands])
    buckets = collections.Counter()
    cat_err = collections.Counter(); util_err = collections.Counter()
    cat_tot = collections.Counter(); util_tot = collections.Counter()
    fails = []; genuine = []
    try:
        for i, r in enumerate(cands):
            if i % 500 == 0:
                print(f"   exec {i}/{len(cands)}", flush=True)
            cat_tot[r["category"]] += 1; util_tot[r["utility"]] += 1
            cmd = SUDO.sub(r"\1", r["bash"])          # strip sudo -> run as current user
            try:
                # stdout -> /dev/null: infinite-output cmds (yes, cat /dev/zero) must not
                # be buffered into memory (that OOM-killed an earlier run). stderr is
                # capped so a stderr-spamming command can't blow up memory either.
                # `set -o pipefail` so a failing mid-pipe stage isn't masked by a later 0.
                wrapped = "set -o pipefail\n" + cmd
                p = subprocess.run([BASH, "-c", wrapped], cwd=sb,
                                   stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
                                   text=True, errors="replace", timeout=timeout,
                                   stdin=subprocess.DEVNULL)
                rc = p.returncode
            except subprocess.TimeoutExpired:
                buckets["timeout"] += 1
                fails.append(("timeout", r["utility"], r["bash"], ""))
                continue
            except Exception as e:
                buckets["spawn-error"] += 1
                fails.append(("spawn", r["utility"], r["bash"], str(e)[:80]))
                continue
            out = (p.stderr or "")[:4000]             # classification uses stderr only
            errline = out.strip().splitlines()[-1] if out.strip() else ""
            low = out.lower()
            grep_nomatch = r["utility"] in {"grep", "egrep", "fgrep", "zgrep", "cmp",
                                            "comm", "diff", "pgrep"} or _GREP_TAIL.search(cmd)
            if _BADFLAG.search(out):
                buckets["err bad-flag"] += 1                     # invalid/unknown flag, ANY exit code
                cat_err[r["category"]] += 1; util_err[r["utility"]] += 1
                genuine.append({"nl": r["nl"], "bash": r["bash"], "category": r["category"],
                                "utility": r["utility"], "variant_group": r.get("variant_group"),
                                "rc": rc, "err": errline})
                if len(fails) < 80:
                    fails.append(("bad-flag", r["utility"], r["bash"], errline))
            elif rc == 0:
                buckets["ok"] += 1
            elif rc == 1 and grep_nomatch:
                buckets["ok(rc1 no-match)"] += 1                 # grep/pgrep "no match" is fine
            elif rc != 0 and not out.strip() and _NOMATCH_STAGE.search(cmd):
                buckets["ok(rc1 no-match)"] += 1                 # pipefail-propagated grep/find no-match (silent)
            elif rc == 127 or "command not found" in low:
                buckets["tool-missing"] += 1                     # not installed in this env
            elif ("usage:" in low or "required environment variable" in low
                  or "is not set" in low):
                buckets["by-design(needs args/env)"] += 1        # script exits when args/env absent
            elif re.search(r"no such file or directory|cannot open|cannot access|cannot stat|"
                           r"not a directory|is a directory|file exists|already exists|"
                           r"cannot create|cannot remove|read-only file system", low):
                buckets["fixture(missing/collision)"] += 1       # blank/shared sandbox artifact
            elif re.search(r"invalid user|unknown user|no such user|invalid group|"
                           r"unknown group|no such group", low):
                buckets["env(missing user/group)"] += 1
            elif re.search(r"must be root|must be run as root|permission denied|"
                           r"operation not permitted|not permitted|inappropriate ioctl|"
                           r"not a tty|not booted with systemd|failed to connect to bus|"
                           r"not a git repository", low) or r["utility"] in _ENV_UTIL:
                buckets["env(needs-root/systemd)"] += 1
            elif re.search(r"not running|is down|unreachable|does not exist|is missing|"
                           r"cannot parse|could not resolve|name or service not known", low):
                buckets["env(target absent/unresolved)"] += 1    # script correctly signaled absence
            else:
                buckets[f"err rc{rc}"] += 1                      # genuine: bad flag/option/logic
                cat_err[r["category"]] += 1; util_err[r["utility"]] += 1
                genuine.append({"nl": r["nl"], "bash": r["bash"], "category": r["category"],
                                "utility": r["utility"], "variant_group": r.get("variant_group"),
                                "rc": rc, "err": errline})
                if len(fails) < 80:
                    fails.append((f"rc{rc}", r["utility"], r["bash"], errline))
    finally:
        shutil.rmtree(sb, ignore_errors=True)
    total = sum(buckets.values())
    ok = buckets["ok"] + buckets["ok(rc1 no-match)"]
    env_keys = ("tool-missing", "by-design(needs args/env)", "fixture(missing/collision)",
                "env(missing user/group)", "env(needs-root/systemd)", "env(target absent/unresolved)")
    env = sum(buckets[k] for k in env_keys)
    real_err = sum(v for k, v in buckets.items() if k.startswith("err "))
    other = buckets["timeout"] + buckets["spawn-error"]
    return {"total": total, "ok": ok, "env": env, "real_err": real_err, "other": other,
            "buckets": buckets, "fails": fails, "genuine": genuine,
            "cat_err": cat_err, "util_err": util_err, "cat_tot": cat_tot, "util_tot": util_tot}

# ----------------------------------------------------------------- deletion
def delete_rows(path, genuine):
    """Remove rows whose (request, command) matches a genuine-error entry. Writes a
    .bak of the original first. Returns the number of rows removed."""
    keyset = {(g["nl"], g["bash"]) for g in genuine}
    kept, removed = [], 0
    with open(path, encoding="utf-8") as fh:
        for line in fh:
            s = line.strip()
            if not s:
                continue
            nl, bash = row_nl_bash(json.loads(s))
            if (nl, bash) in keyset:
                removed += 1
            else:
                kept.append(line if line.endswith("\n") else line + "\n")
    shutil.copyfile(path, path + ".bak")
    with open(path, "w", encoding="utf-8") as fh:
        fh.writelines(kept)
    return removed

# ----------------------------------------------------------------- reporting
def rate_table(title, err_by, tot_by, top=12):
    print(f"\n  {title}")
    rows = [(k, err_by.get(k, 0), tot_by[k]) for k in tot_by]
    rows.sort(key=lambda x: (-(x[1] / x[2] if x[2] else 0), -x[2]))
    for k, e, t in rows[:top]:
        print(f"     {k:14s} {e:6d}/{t:<6d}  {e/t*100 if t else 0:5.1f}%")

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--data", default=os.path.join(HERE, "bash_dataset.jsonl"))
    ap.add_argument("--execute", action="store_true", help="also run the sandbox execution pass")
    ap.add_argument("--n", type=int, default=3000, help="max commands to execute in (c)")
    ap.add_argument("--permissive", action="store_true",
                    help="throwaway-Linux mode: execute nearly all single-line commands "
                         "(system-info + fs-mutating), blocking only host-dangerous/hanging ones")
    ap.add_argument("--timeout", type=int, default=8, help="per-command execution timeout (s)")
    ap.add_argument("--dump-errors", default=None,
                    help="write every genuine-error command (rc + stderr) to this JSONL file")
    ap.add_argument("--yes", action="store_true", help="delete genuine-error rows without prompting")
    ap.add_argument("--no", action="store_true", help="never delete; skip the prompt")
    ap.add_argument("--shellcheck-n", type=int, default=6000, help="shellcheck sample size (0=all)")
    ap.add_argument("--seed", type=int, default=1234)
    args = ap.parse_args()
    random.seed(args.seed)

    if not os.path.exists(args.data):
        print(f"no such file: {args.data}"); sys.exit(1)
    rows = load(args.data)
    cats = collections.Counter(r["category"] for r in rows)
    print(f"loaded {len(rows)} rows from {args.data}")
    print(f"categories: {dict(cats)}")
    ngroups = len({r['variant_group'] for r in rows if r['variant_group']})
    if ngroups:
        print(f"variant_groups: {ngroups}  (avg {len(rows)/ngroups:.2f} rows/request)")

    # ---- (a) bash -n
    print("\n" + "=" * 66); print("(a) bash -n  (every command)"); print("=" * 66)
    valid = bash_n([r["bash"] for r in rows])
    fails = [rows[i] for i, ok in enumerate(valid) if not ok]
    print(f"syntax failures: {len(fails)}/{len(rows)}  ({len(fails)/len(rows)*100:.3f}%)")
    if fails:
        cat_fail = collections.Counter(r["category"] for r in fails)
        util_fail = collections.Counter(r["utility"] for r in fails)
        print(f"  by category: {dict(cat_fail)}")
        print(f"  top utilities: {util_fail.most_common(10)}")
        for r in fails[:10]:
            print(f"   [{r['utility']}] {r['bash'][:90]}")

    # ---- (b) shellcheck
    print("\n" + "=" * 66); print("(b) shellcheck  (warning level)"); print("=" * 66)
    sc = shellcheck(rows, args.shellcheck_n)
    if sc is None:
        print("shellcheck not found -> skipped (install shellcheck to enable)")
    else:
        clean = sc["n"] - sc["flagged"]
        print(f"clean (no warning+ findings): {clean}/{sc['n']}  ({clean/sc['n']*100:.1f}%)")
        print(f"flagged: {sc['flagged']}  ({sc['flagged']/sc['n']*100:.1f}%)")
        print("top SC codes:")
        for c, n in sc["codes"].most_common(12):
            print(f"   {c}: {n}")
        rate_table("shellcheck-flagged rate by category:", sc["cat_flag"],
                   collections.Counter(r["category"] for r in rows))
        rate_table("shellcheck-flagged rate by utility (worst):", sc["util_flag"],
                   collections.Counter(r["utility"] for r in rows))

    # ---- (c) execution
    print("\n" + "=" * 66); print("(c) real execution in sandbox"); print("=" * 66)
    if not args.execute:
        print("skipped (pass --execute to enable; runs only safe, non-destructive commands)")
    else:
        ex = execute(rows, args.n, permissive=args.permissive, timeout=args.timeout)
        if ex:
            t = ex["total"]
            # "gradable" = commands whose failure would actually mean a bad command
            # (exclude environmental: missing files/users/env/args/root/systemd/tools).
            gradable = ex["ok"] + ex["real_err"]
            print(f"\nexecuted {t}")
            print(f"  ran clean: {ex['ok']}")
            print(f"  environmental (missing file/user/env/args, needs root/systemd, tool absent): "
                  f"{ex['env']}  <- not correctness failures")
            print(f"  timeout/spawn: {ex['other']}")
            print(f"  GENUINE errors (bad flag/option/logic): {ex['real_err']}")
            print(f"  => correctness on gradable commands: "
                  f"{ex['ok']}/{gradable} = {ex['ok']/max(1,gradable)*100:.1f}% clean, "
                  f"{ex['real_err']/max(1,gradable)*100:.2f}% genuine errors")
            print("  buckets:")
            for k, v in ex["buckets"].most_common():
                print(f"     {k}: {v}")
            if args.dump_errors:
                with open(args.dump_errors, "w", encoding="utf-8") as fh:
                    for g in ex["genuine"]:
                        fh.write(json.dumps(g, ensure_ascii=False) + "\n")
                print(f"  wrote {len(ex['genuine'])} genuine-error commands -> {args.dump_errors}")
            rate_table("real-error rate by category:", ex["cat_err"], ex["cat_tot"])
            rate_table("real-error rate by utility (worst):", ex["util_err"], ex["util_tot"])

            # ---- offer to delete the genuine-error rows
            gradable = ex["ok"] + ex["real_err"]
            pct = ex["real_err"] / max(1, gradable) * 100
            if ex["genuine"]:
                print(f"\nverifications finished. {pct:.2f}% are genuine errors "
                      f"({len(ex['genuine'])} rows).")
                if args.yes:
                    ans = "y"
                elif args.no:
                    ans = "n"
                else:
                    try:
                        ans = input("would you like to delete those rows? [y/N] ").strip().lower()
                    except EOFError:
                        ans = ""            # non-interactive -> default No (safe)
                if ans in ("y", "yes"):
                    removed = delete_rows(args.data, ex["genuine"])
                    print(f"deleted {removed} rows -> {args.data}  (backup: {args.data}.bak)")
                else:
                    print("kept all rows. (re-run with --yes to delete non-interactively)")
            else:
                print(f"\nverifications finished. {pct:.2f}% are genuine errors — nothing to delete.")
            if ex["fails"]:
                print("\n  sample non-ok commands:")
                for tag, util, bash, err in ex["fails"][:15]:
                    print(f"   [{tag}/{util}] {bash[:90]}")
                    if err:
                        print(f"        -> {err[:110]}")

    print("\ndone.")

if __name__ == "__main__":
    main()