@chrono-meta/fh-gate 3.24.0 → 3.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/.claude/rules/fh_4axis_gate.md +14 -1
  2. package/.claude-plugin/marketplace.json +4 -4
  3. package/CLAUDE.md +5 -4
  4. package/README.md +8 -6
  5. package/knowledge/shared/harness-core/claude_md_gate_details.md +34 -0
  6. package/knowledge/shared/harness-core/fh_integration_contract.md +0 -1
  7. package/knowledge/shared/harness-core/fh_opencode_governance_wrapper.md +0 -1
  8. package/knowledge/shared/harness-core/fh_three_layer_canon.md +110 -2
  9. package/knowledge/shared/harness-core/field_verdict_crossfamily_gate.md +22 -0
  10. package/knowledge/shared/harness-core/governance_engineering_definition.md +16 -0
  11. package/knowledge/shared/harness-core/harness_verification_core_extended.md +26 -0
  12. package/knowledge/shared/harness-core/ship_readiness_gate.md +3 -0
  13. package/knowledge/shared/harness-core/sonnet_floor_doctrine.md +19 -0
  14. package/package.json +10 -2
  15. package/plugins/fh-commons/.claude-plugin/plugin.json +1 -1
  16. package/plugins/fh-meta/.claude-plugin/plugin.json +1 -1
  17. package/plugins/fh-meta/CHANGELOG.md +9 -0
  18. package/plugins/fh-meta/skills/install-wizard/SKILL_detail.md +17 -3
  19. package/plugins/fh-meta/skills/verify-bidirectional/SKILL.md +1 -1
  20. package/plugins/fh-preprep/.claude-plugin/plugin.json +2 -2
  21. package/plugins/fh-preprep/README.md +11 -0
  22. package/plugins/fh-preprep/skills/preprep/SKILL.md +47 -1
  23. package/plugins/fh-preprep/skills/preprep/lane_speech_coach.py +1080 -0
  24. package/plugins/fh-preprep/skills/preprep/test_lane_speech_coach.py +705 -0
  25. package/plugins/fh-qp/.claude-plugin/plugin.json +1 -1
  26. package/scripts/cluster_capability_scan.sh +17 -0
  27. package/scripts/compaction_probe.sh +102 -23
  28. package/scripts/count_check.sh +37 -10
  29. package/scripts/field_canon_preload.sh +84 -2
  30. package/scripts/marker_diff_sha.sh +13 -0
  31. package/scripts/mutation_probe.py +1541 -0
  32. package/scripts/revert_probe.sh +5 -6
  33. package/scripts/selfcheck.sh +48 -0
  34. package/scripts/test_axis23_skip_reason_lanes.sh +109 -0
  35. package/scripts/test_count_check_all_plugins_lanes.sh +130 -0
  36. package/scripts/test_field_canon_lanes.sh +33 -0
  37. package/scripts/test_hook_templates_copilot_compat_lanes.sh +250 -0
  38. package/scripts/test_marker_diff_sha_lanes.sh +129 -0
  39. package/scripts/test_mutation_probe_lanes.sh +786 -0
  40. package/scripts/test_preprep_speech_coach_lanes.sh +62 -0
  41. package/scripts/test_skill_canon_preload_lanes.sh +148 -0
  42. package/scripts/universal_guard_check.sh +2 -0
  43. package/templates/.git-hooks/pre-commit +109 -5
  44. package/templates/goal-quench-hook-setup.md +3 -3
  45. package/templates/goal-quench-settings-merged.json +0 -1
  46. package/templates/settings.Compaction.snippet.json +0 -2
  47. package/templates/settings.FieldCanon.snippet.json +0 -1
  48. package/templates/settings.SessionStart.snippet.json +0 -2
  49. package/templates/settings.SubagentStop.snippet.json +0 -1
  50. package/templates/subagent-tally-hook.json +0 -1
@@ -0,0 +1,1541 @@
1
+ #!/usr/bin/env python3
2
+ """mutation_probe.py — operator-generated mutants on a gate's VERDICT CHANNEL, run against its lanes.
3
+
4
+ WHY THIS EXISTS (2026-10-07). `revert_probe.sh` asks «does the lane go red when *the author's chosen*
5
+ change is undone» — one mutant, picked by the person who wrote the lane, so it shares the lane's blind
6
+ spot. This tool generates the mutants mechanically (comparison flips, boundary shifts, failure codes
7
+ forced to 0) and reports which ones the lane suite does NOT notice. A survivor can expose an untested boundary even when the suite stays green. FH's
8
+ `new-code-anchor` checks whether added files have executable anchors; this tool asks whether
9
+ those anchors notice mechanically selected perturbations. 6-axis placement: an extension of ⓕ (revert) —
10
+ `fh_three_layer_canon.md §1-a-2`.
11
+
12
+ v6 (2026-10-07) — THE GENERATOR WAS REBUILT, NOT PATCHED. Six blind detectors (same family, inputs
13
+ varied) reproduced dozens of generator defects in v5 — comments, quotes, heredocs, word boundaries,
14
+ line splitting — all from reading bash/python with per-line regexes. Two structural changes:
15
+ · python: the standard `tokenize` module. Only OP / NAME / NUMBER tokens are ever mutated, so
16
+ comments, strings and docstrings are excluded by token type, not by a guess.
17
+ · bash: one character-level scanner over the whole file with real state — single/double/ANSI-C
18
+ quotes across lines, `#` only at a word start, heredocs queued per line with an exact terminator
19
+ (`<<-` strips tabs only), `$( )` / `(( ))` / `$(( ))` / `$[ ]` / `${ }` nesting, here-strings.
20
+ Mutations happen only on WORDS the scanner classified as code, and only in context: test operators
21
+ inside `[ ]` / `[[ ]]` / `test …` (a word at command position), `< <= > >= == !=` inside an
22
+ arithmetic context, `exit N` / `return N` / `FAILED=1`-style assignments at command position.
23
+ Embedded python is recognised only as `python… -c '…'` or a heredoc on a `python… -` command, both
24
+ in the SAME simple command and outside comments/quotes — and is then handed to `tokenize`.
25
+
26
+ v7 (2026-10-08) — FAIL-CLOSED. v6 still guessed where it was unsure; v7 refuses instead. A region the scanner
27
+ cannot classify with certainty — `((` / `$((` that bash re-reads as nested subshells, an unclosed quote or frame,
28
+ an unreadable heredoc delimiter — is BLOCKED and named in a `note:`. Double quotes, `${ }` and backticks are
29
+ scanned as real frames (nested quotes no longer flip polarity) and everything inside them is quiet. A heredoc
30
+ delimiter is a whole shell word (`<<END-X`), `<<-` bodies lose their tabs before python sees them, a `case`
31
+ pattern is data (nested `case` too), a keyword in argument position is an argument, `exit 1>&2` is a
32
+ redirect, a test operator is mutated only in OPERATOR position (`[ "$1" = -eq ]` has an operand `-eq`),
33
+ array literals `x=( … )` and `<( … )` are data, and a `[` that never closes poisons nothing after it. The remaining
34
+ misses are the fail-closed trade — see «Named residuals» and the shipped regression lanes.
35
+
36
+ SCOPE — verdict channel only:
37
+ bash : -eq↔-ne · -lt→-le · -le→-lt · -gt→-ge · -ge→-gt · == ↔ != · = → != (`==` is not generated for
38
+ a `#!/bin/sh` subject — not POSIX) · arithmetic < <= > >= == != · exit N→0 · return N→0 ·
39
+ FAILED/FAIL/failed/fail/rc=1 → 0
40
+ python : < <= > >= == != · is ↔ is not · sys.exit(N)/exit(N)/quit(N)/os._exit(N)/SystemExit(N) → 0
41
+ (N may be -N) · return N / -N / (N) → return 0 · return True ↔ False · `x = True` ↔ False at
42
+ statement level only (never a keyword argument, a default, or a lambda) — each only when it ends
43
+ the statement. A literal equal to zero (0x0, 0.0, 0j …) is never «mutated» to 0.
44
+ embedded python: `python… -c '…'` when -c (alone or as `-Sc`) is an INTERPRETER option, or a heredoc on a
45
+ python command reading its script from stdin (`python3 -` or no script argument). A heredoc the
46
+ shell expands (unquoted delimiter with $ ` \ in the body) is not mutated.
47
+ Languages: bash and POSIX sh. zsh / ksh / mksh are other grammars and are refused (exit 2), not guessed.
48
+ Named residuals: python `in` / `not` / `and` / `or` are not mutated · f-string bodies on python < 3.12
49
+ are one STRING token · code inside double quotes, `${ }` or backticks is not mutated (it IS code — this is
50
+ the fail-closed trade) · `SystemExit(code=N)` keyword form is not mutated · an embedded python block that
51
+ does not compile on its own is skipped (reported).
52
+
53
+ 🟥 THE OUTPUT IS A LIST OF QUESTIONS, NOT A SCORE. A surviving mutant is EQUIVALENT · BOUNDARY ·
54
+ REDUNDANT · GAP — a reviewer triages it. No `--fail-under`: coverage and mutation metrics are context-dependent for LLM-generated tests
55
+ (https://arxiv.org/abs/2607.22880); that study does not establish a universal loss of correlation
56
+ after controlling suite size. §Mechanization Boundary forbids promoting a verdict by its score.
57
+
58
+ SAFETY OF THE IN-PLACE EDIT (lanes find their subject by repo path, as with revert_probe.sh):
59
+ · original bytes + mode are read and backed up BEFORE the baseline; a lane that writes, deletes or
60
+ replaces its subject — at baseline OR during any mutant — makes the run «cannot judge»
61
+ · every write goes through ONE file descriptor opened on the original inode (O_NOFOLLOW); the path is
62
+ checked after each lane run and never written through: a symlink / directory in its place → exit 3,
63
+ a regular file with a new inode (or nothing) → a FRESH file with the original bytes is renamed into
64
+ place — never written into, since that inode may be anything the lane linked there — and the run is
65
+ «cannot judge»
66
+ · locks: one namespace keyed by INODE, shared by every user (/tmp/mutation_probe.locks/, sticky) —
67
+ subject and lane alike, so another probe on the same file under any name, any uid, or with the roles
68
+ swapped exits 2. (v6 kept per-uid, per-role locks: crossed probes both ran.) The lock directory must
69
+ be sticky and owned by root or you; if another user created it, every other user gets exit 2 — a
70
+ refusal, not a bypass (named residual). The subject is re-read under the lock: a difference → 2.
71
+ · the backup is keyed by the subject's real path AND its inode; a leftover (SIGKILL, power loss) blocks
72
+ the next run through either and names itself
73
+ · a POSITIVE CONTROL runs after the baseline: the subject replaced by one that exits at once (113). A
74
+ lane that stays green on it never runs the subject — every mutant would «survive» — so exit 2
75
+ · after the last mutant the lane runs ONCE MORE on the restored original; it must be green and leave
76
+ the subject alone — whatever it built from the last mutant is rebuilt from the original
77
+ · Linux: the probe is a child subreaper, so lane descendants that escape with setsid are killed after
78
+ every run (elsewhere: named residual, reported)
79
+ · the lane is executed by the KERNEL when it is executable (its shebang gets one argument, as the
80
+ kernel gives it); otherwise by a Linux-style single-argument shebang fallback, else python3/bash
81
+ · supported asynchronous terminating signals (including SIGABRT) restore and kill the lane's
82
+ process group and temp dirs; SIGKILL, power loss and synchronous hardware faults are not recoverable
83
+ · every write gets a NEW whole second of mtime, later than the end of the previous lane run, never in
84
+ the future: a same-size mutant must not share a pyc key with the previous write, and nothing a lane
85
+ built may look as new as the next write. A subject whose mtime is already in the future is refused. The subject's own pycs (any interpreter tag, incl. unchecked-hash) are deleted
86
+ before the baseline and after the last restore
87
+ · syntax checks run in-process (`compile`) or via `bash -n`/`sh -n` on a private temp file — no
88
+ `python -m` (a module in the cwd could hijack it)
89
+
90
+ USAGE
91
+ python3 scripts/mutation_probe.py <subject> <lane-suite> [--timeout SEC] [--max N] [--json OUT]
92
+ python3 scripts/mutation_probe.py <subject> --list # enumerate mutants; NOT a measurement
93
+
94
+ The lane is run by its shebang, else `python3` for *.py, else `bash`, from the current directory,
95
+ stdin closed, once on the unmodified subject (baseline) and once per mutant.
96
+
97
+ EXIT
98
+ 0 = measured — at least one mutant was KILLED or SURVIVED (survivors are printed; still 0: this is a
99
+ review surface, not a gate). With --list: mutants were enumerated (nothing was measured).
100
+ 2 = cannot judge — usage error · subject/lane missing or the same file · unsupported language ·
101
+ non-UTF-8 · subject not writable (mode bits, also for root) · mtime in the future · another probe
102
+ holds the subject or the lane · a leftover backup · bad --timeout / --json · baseline red, timed
103
+ out or not runnable · positive control survived · a lane that writes or replaces its subject ·
104
+ the final run on the original not green · no mutants · nothing measured. --json is written ONLY
105
+ for exit 0 (and carries "measured": true).
106
+ 3 = RESTORE FAILED — the subject may still hold a mutant (or is no longer a file). Loud, never folded
107
+ into a verdict.
108
+ """
109
+ import argparse, ast, fcntl, hashlib, io, json, os, re, shlex, shutil, signal, stat, subprocess, sys, tempfile
110
+ import time, tokenize
111
+
112
+ PY_INTERP = re.compile(r'^python(\d+(\.\d+)*)?$')
113
+ SH_INTERP = {'sh', 'dash', 'ash', 'posh'}
114
+ BASH_INTERP = {'bash'} | SH_INTERP # zsh/ksh/mksh: other grammars — refused, not guessed (v7)
115
+
116
+ # ───────────────────────────── language ─────────────────────────────
117
+
118
+ def shebang_split(first):
119
+ """What the Linux kernel does with a `#!` line: the interpreter, then AT MOST ONE argument — the rest
120
+ of the line, unsplit. (shlex is not what runs the file.)"""
121
+ body = first[2:].strip(' \t\r')
122
+ if not body:
123
+ return []
124
+ parts = body.split(None, 1)
125
+ return [parts[0]] + ([parts[1].strip()] if len(parts) > 1 and parts[1].strip() else [])
126
+
127
+
128
+ def shebang_interp(text):
129
+ first = text.split('\n', 1)[0]
130
+ if not first.startswith('#!'):
131
+ return None
132
+ parts = shebang_split(first)
133
+ if not parts:
134
+ return None
135
+ name = os.path.basename(parts[0])
136
+ if name == 'env':
137
+ rest = [p for p in ' '.join(parts[1:]).split() if not p.startswith('-')]
138
+ name = os.path.basename(rest[0]) if rest else ''
139
+ return name
140
+
141
+
142
+ def language(path, text):
143
+ """('python'|'bash', is_posix_sh) or (None, False)."""
144
+ ext = os.path.splitext(path)[1]
145
+ interp = shebang_interp(text)
146
+ if ext == '.py' or (interp and PY_INTERP.match(interp)):
147
+ return 'python', False
148
+ if interp and interp not in BASH_INTERP and not PY_INTERP.match(interp):
149
+ return None, False
150
+ if ext in ('.sh', '.bash') or (interp in BASH_INTERP):
151
+ return 'bash', interp in SH_INTERP
152
+ return None, False
153
+
154
+ # ───────────────────────────── python (tokenize) ─────────────────────────────
155
+
156
+ PY_CMP = {'<': '<=', '<=': '<', '>': '>=', '>=': '>', '==': '!=', '!=': '=='}
157
+ EXIT_CALLEES = {('sys', 'exit'), ('', 'exit'), ('', 'quit'), ('os', '_exit'), ('', 'SystemExit')}
158
+ PY_SKIP = (tokenize.NL, tokenize.COMMENT, tokenize.INDENT, tokenize.DEDENT)
159
+
160
+
161
+ def py_zero(s):
162
+ """True when the literal is zero — or when we cannot tell (fail-closed: unknown → not mutated)."""
163
+ try:
164
+ return ast.literal_eval(s) == 0
165
+ except (ValueError, SyntaxError):
166
+ return True
167
+
168
+
169
+ def py_mutants(src, posmap=None):
170
+ """Mutants for python source `src`. `posmap(k)` maps an index of `src` to a file offset
171
+ (identity by default). Raises on untokenizable source."""
172
+ starts = [0]
173
+ for i, c in enumerate(src):
174
+ if c == '\n':
175
+ starts.append(i + 1)
176
+
177
+ def off(rc):
178
+ k = starts[rc[0] - 1] + rc[1]
179
+ return posmap(k) if posmap else k
180
+ toks, depth, lam = [], 0, False
181
+ for t in tokenize.generate_tokens(io.StringIO(src).readline):
182
+ if t.type in PY_SKIP:
183
+ continue
184
+ if t.type in (tokenize.NEWLINE, tokenize.ENDMARKER) or (t.type == tokenize.OP and t.string == ';' and depth == 0):
185
+ if toks:
186
+ toks[-1]['eol'] = True
187
+ lam = False
188
+ continue
189
+ if t.type == tokenize.NAME and t.string == 'lambda':
190
+ lam = True
191
+ d0 = depth
192
+ if t.type == tokenize.OP and t.string in '([{':
193
+ depth += 1
194
+ elif t.type == tokenize.OP and t.string in ')]}':
195
+ depth = max(0, depth - 1)
196
+ toks.append({'t': t, 'depth': d0, 'lam': lam, 'eol': False})
197
+
198
+ def is_(k, typ, s=None):
199
+ return 0 <= k < len(toks) and toks[k]['t'].type == typ and (s is None or toks[k]['t'].string == s)
200
+
201
+ def operand(k):
202
+ """An exit-status operand starting at k: N · -N · (N) · (-N). Returns (end_index, text) or None."""
203
+ j, neg = k, False
204
+ par = is_(j, tokenize.OP, '(')
205
+ if par:
206
+ j += 1
207
+ if is_(j, tokenize.OP, '-'):
208
+ neg, j = True, j + 1
209
+ if not is_(j, tokenize.NUMBER):
210
+ return None
211
+ num = toks[j]['t'].string
212
+ if par:
213
+ if not is_(j + 1, tokenize.OP, ')'):
214
+ return None
215
+ j += 1
216
+ if py_zero(num):
217
+ return None
218
+ return j, src[starts[toks[k]['t'].start[0] - 1] + toks[k]['t'].start[1]:
219
+ starts[toks[j]['t'].end[0] - 1] + toks[j]['t'].end[1]]
220
+
221
+ out = []
222
+ for i, e in enumerate(toks):
223
+ t = e['t']
224
+ prev = toks[i - 1]['t'] if i else None
225
+ if t.type == tokenize.OP and t.string in PY_CMP:
226
+ out.append((off(t.start), off(t.end), PY_CMP[t.string], '%s→%s' % (t.string, PY_CMP[t.string])))
227
+ elif t.type == tokenize.NAME and t.string == 'is':
228
+ if is_(i + 1, tokenize.NAME, 'not'):
229
+ out.append((off(t.start), off(toks[i + 1]['t'].end), 'is', 'is not→is'))
230
+ else:
231
+ out.append((off(t.start), off(t.end), 'is not', 'is→is not'))
232
+ elif t.type == tokenize.NAME and t.string in ('True', 'False') and prev is not None and e['eol'] and (
233
+ (prev.type == tokenize.NAME and prev.string == 'return') or
234
+ (prev.type == tokenize.OP and prev.string == '=' and e['depth'] == 0 and not e['lam'])):
235
+ new = 'False' if t.string == 'True' else 'True'
236
+ out.append((off(t.start), off(t.end), new, '%s→%s' % (t.string, new)))
237
+ elif t.type == tokenize.NAME and t.string == 'return':
238
+ r = operand(i + 1)
239
+ if r and toks[r[0]]['eol']:
240
+ out.append((off(toks[i + 1]['t'].start), off(toks[r[0]]['t'].end), '0',
241
+ 'return %s→return 0' % r[1]))
242
+ elif t.type == tokenize.OP and t.string == '(' and i >= 1 and is_(i - 1, tokenize.NAME):
243
+ callee = toks[i - 1]['t'].string
244
+ owner = toks[i - 3]['t'].string if i >= 3 and is_(i - 2, tokenize.OP, '.') else ''
245
+ if (owner, callee) not in EXIT_CALLEES:
246
+ continue
247
+ j = i + 1
248
+ if is_(j, tokenize.OP, '-'):
249
+ j += 1
250
+ if not is_(j, tokenize.NUMBER) or not is_(j + 1, tokenize.OP, ')') or py_zero(toks[j]['t'].string):
251
+ continue
252
+ label = ('%s.%s' % (owner, callee)) if owner else callee
253
+ s0, s1 = off(toks[i + 1]['t'].start), off(toks[j]['t'].end)
254
+ arg = src[starts[toks[i + 1]['t'].start[0] - 1] + toks[i + 1]['t'].start[1]:
255
+ starts[toks[j]['t'].end[0] - 1] + toks[j]['t'].end[1]]
256
+ out.append((s0, s1, '0', '%s(%s)→%s(0)' % (label, arg, label)))
257
+ return out
258
+
259
+ # ───────────────────────────── bash (character-level scanner, fail-closed) ─────────────────────────────
260
+
261
+ TEST_SWAP = {'-eq': '-ne', '-ne': '-eq', '-lt': '-le', '-le': '-lt', '-gt': '-ge', '-ge': '-gt',
262
+ '==': '!=', '!=': '==', '=': '!='}
263
+ TEST_SWAP_POSIX = dict(TEST_SWAP, **{'!=': '='})
264
+ CMD_KEYWORDS = {'then', 'do', 'else', 'elif', 'if', 'while', 'until', '!', '{', 'time', 'exec', 'command'}
265
+ ASSIGN_LEAD = {'local', 'export', 'declare', 'readonly', 'typeset'}
266
+ FAIL_ASSIGN = re.compile(r'^(FAILED|FAIL|failed|fail|rc)=1$')
267
+ ARITH_OP = re.compile(r'(?<![<>=!])(<=|>=|==|!=|<|>)(?![<>=])')
268
+ ARITH_ONLY = True # the revert probe flips this — arithmetic operators outside (( )) are redirects
269
+ WORD_END = set(' \t\n;&|()<>')
270
+ PY_FLAG_ONLY = set('bBdEhiIOqsSuvVxPR') # python options that take no argument
271
+ PY_FLAG_ARG = {'-W', '-X', '-Q'} # options whose argument is the next word
272
+ TERMINATOR_OK = re.compile(r'^[ \t]*(?:\d*[<>]&?[ \t]*\S+[ \t]*)*(?:$|\||&&|;|&|\))')
273
+
274
+
275
+ class BashScan:
276
+ """Classify every character of a bash file. Words are collected only at code level; every region
277
+ the scanner cannot classify with certainty is BLOCKED (no mutation there) and named in a note."""
278
+
279
+ def __init__(self, text):
280
+ self.t = text
281
+ self.n = len(text)
282
+ self.code = [False] * self.n # character is shell code (not comment/string/heredoc data)
283
+ self.arith = [False] * self.n # character is inside an arithmetic context
284
+ self.block = [False] * self.n # fail-closed: never mutate here
285
+ self.words = [] # (start, end, text, at_command, in_test, data)
286
+ self.py = [] # (start, end, strip_tabs) of embedded python source
287
+ self.notes = []
288
+ self._scan()
289
+
290
+ # ── helpers ──
291
+ def _line(self, i):
292
+ return self.t.count('\n', 0, i) + 1
293
+
294
+ def _uncertain(self, s, e, why):
295
+ for k in range(max(0, s), min(self.n, e)):
296
+ self.block[k] = True
297
+ self.notes.append('L%d: %s — not mutated (fail-closed)' % (self._line(s), why))
298
+
299
+ def _paren_extent(self, i):
300
+ """From i (just after an opening paren), find the matching close at depth 0.
301
+ Returns (index_of_close, closes_as_double) or (None, False) at EOF."""
302
+ t, n, depth, j = self.t, self.n, 0, i
303
+ while j < n:
304
+ c = t[j]
305
+ if c == '\\':
306
+ j += 2
307
+ continue
308
+ if c in '\'"`':
309
+ k = j + 1
310
+ while k < n and t[k] != c:
311
+ k += 2 if (c != "'" and t[k] == '\\') else 1
312
+ j = k + 1
313
+ continue
314
+ if c == '(':
315
+ depth += 1
316
+ elif c == ')':
317
+ if depth == 0:
318
+ return j, t.startswith('))', j)
319
+ depth -= 1
320
+ j += 1
321
+ return None, False
322
+
323
+ @staticmethod
324
+ def _frame(kind, start, quiet, closer=None):
325
+ return {'kind': kind, 'start': start, 'quiet': quiet, 'closer': closer, 'cmd': [], 'at_cmd': True,
326
+ 'test': None, 'cur': None, 'cur_bad': False, 'assign_ok': False, 'data_next': False,
327
+ 'case': None, 'case_outer': [], 'depth': 0, 'bdepth': 0, 'fn': 0,
328
+ 'tpos': 0, 'twords': []}
329
+
330
+ # ── main loop ──
331
+ def _scan(self):
332
+ t, n = self.t, self.n
333
+ stack = [self._frame('code', 0, False)]
334
+ pending = [] # heredocs queued on this line: (delim, strip_tabs, is_py, expands)
335
+ i = 0
336
+ while i < n:
337
+ f = stack[-1]
338
+ c = t[i]
339
+ k = f['kind']
340
+ if k == 'dq': # "…" — data; nested expansions are scanned but quiet
341
+ if c == '\\':
342
+ i += 2
343
+ elif c == '"':
344
+ stack.pop()
345
+ i += 1
346
+ elif c == '`':
347
+ stack.append(self._frame('bq', i, True))
348
+ i += 1
349
+ elif c == '$' and i + 1 < n and t[i + 1] in '([':
350
+ i = self._open_dollar(stack, i, True)
351
+ elif t.startswith('${', i):
352
+ stack.append(self._frame('brace', i, True))
353
+ i += 2
354
+ else:
355
+ i += 1
356
+ continue
357
+ if k == 'bq':
358
+ if c == '\\':
359
+ i += 2
360
+ elif c == '`':
361
+ stack.pop()
362
+ i += 1
363
+ else:
364
+ i += 1
365
+ continue
366
+ if k == 'brace': # ${ … } — quotes inside protect the closing brace
367
+ if c == '\\':
368
+ i += 2
369
+ elif c == '}':
370
+ stack.pop()
371
+ i += 1
372
+ elif c == "'":
373
+ j = t.find("'", i + 1)
374
+ i = n if j == -1 else j + 1
375
+ elif c == '"':
376
+ stack.append(self._frame('dq', i, True))
377
+ i += 1
378
+ elif c == '$' and i + 1 < n and t[i + 1] in '([':
379
+ i = self._open_dollar(stack, i, True)
380
+ elif t.startswith('${', i):
381
+ stack.append(self._frame('brace', i, True))
382
+ i += 2
383
+ else:
384
+ i += 1
385
+ continue
386
+ if k == 'arith':
387
+ if c == '\\':
388
+ i += 2
389
+ continue
390
+ if c == '"':
391
+ stack.append(self._frame('dq', i, True))
392
+ i += 1
393
+ continue
394
+ if c == "'":
395
+ j = t.find("'", i + 1)
396
+ i = n if j == -1 else j + 1
397
+ continue
398
+ if c == '$' and i + 1 < n and t[i + 1] in '([':
399
+ i = self._open_dollar(stack, i, f['quiet'])
400
+ continue
401
+ if t.startswith('${', i):
402
+ stack.append(self._frame('brace', i, True))
403
+ i += 2
404
+ continue
405
+ if c == '(':
406
+ f['depth'] += 1
407
+ elif c == ')' and f['depth'] > 0:
408
+ f['depth'] -= 1
409
+ elif c == '[':
410
+ f['bdepth'] += 1
411
+ elif c == ']' and f['bdepth'] > 0:
412
+ f['bdepth'] -= 1
413
+ elif f['closer'] == '))' and t.startswith('))', i) and f['depth'] == 0:
414
+ stack.pop()
415
+ i += 2
416
+ continue
417
+ elif f['closer'] == ']' and c == ']' and f['bdepth'] == 0 and f['depth'] == 0:
418
+ stack.pop()
419
+ i += 1
420
+ continue
421
+ self.code[i] = True
422
+ self.arith[i] = True
423
+ if f['quiet']:
424
+ self.block[i] = True
425
+ i += 1
426
+ continue
427
+ # ── code frame ──
428
+ if c == '\\' and i + 1 < n:
429
+ if t[i + 1] == '\n': # line continuation
430
+ if f['cur'] is not None:
431
+ f['cur_bad'] = True
432
+ i += 2
433
+ continue
434
+ self._word_char(f, i)
435
+ self.code[i] = self.code[i + 1] = True
436
+ i += 2
437
+ continue
438
+ if c == '#' and f['cur'] is None:
439
+ j = t.find('\n', i)
440
+ i = n if j == -1 else j
441
+ continue
442
+ if c == "'" or t.startswith("$'", i):
443
+ ansi = c == '$'
444
+ q0 = i + (2 if ansi else 1)
445
+ j = q0
446
+ while j < n and t[j] != "'":
447
+ j += 2 if (ansi and t[j] == '\\') else 1
448
+ if j >= n:
449
+ self._uncertain(i, n, 'unterminated single quote')
450
+ i = n
451
+ continue
452
+ if not ansi and f['cur'] is None and not f['quiet'] and not f['data_next'] and self._python_c(f) and \
453
+ (j + 1 >= n or t[j + 1] in WORD_END):
454
+ self.py.append((q0, j, False))
455
+ self._word_char(f, i)
456
+ i = j + 1
457
+ continue
458
+ if c == '"':
459
+ self._word_char(f, i)
460
+ stack.append(self._frame('dq', i, True))
461
+ i += 1
462
+ continue
463
+ if c == '`':
464
+ self._word_char(f, i)
465
+ stack.append(self._frame('bq', i, True))
466
+ i += 1
467
+ continue
468
+ if c == '$' and i + 1 < n and t[i + 1] in '([':
469
+ self._word_char(f, i)
470
+ i = self._open_dollar(stack, i, f['quiet'])
471
+ continue
472
+ if t.startswith('${', i):
473
+ self._word_char(f, i)
474
+ stack.append(self._frame('brace', i, True))
475
+ i += 2
476
+ continue
477
+ if t.startswith('((', i) and f['cur'] is None:
478
+ close, double = self._paren_extent(i + 2)
479
+ if close is not None and double:
480
+ stack.append(self._frame('arith', i, f['quiet'], '))'))
481
+ i += 2
482
+ continue
483
+ # bash reads this as nested subshells — and so do we, but we do not trust our reading
484
+ outer, _ = self._paren_extent(i + 1)
485
+ self._uncertain(i, n if outer is None else outer + 1, '«((» that is not arithmetic (nested subshell)')
486
+ self._end_word(f, i)
487
+ self._separator(f)
488
+ i += 1
489
+ continue
490
+ if t.startswith('<<<', i):
491
+ self._end_word(f, i)
492
+ f['data_next'] = True
493
+ i += 3
494
+ continue
495
+ if t.startswith('<<', i):
496
+ self._end_word(f, i)
497
+ i = self._heredoc_op(f, i, pending)
498
+ continue
499
+ if c == '\n':
500
+ self._end_word(f, i)
501
+ self._separator(f)
502
+ i += 1
503
+ if pending:
504
+ i = self._heredoc_bodies(i, pending)
505
+ pending = []
506
+ continue
507
+ if c in '<>' and i + 1 < n and t[i + 1] == '(': # <( … ) / >( … ): a word, code inside (quiet)
508
+ self._word_char(f, i)
509
+ stack.append(self._frame('code', i, True, ')'))
510
+ i += 2
511
+ continue
512
+ if c == '(' and f['cur'] is not None and t[f['cur']:i].endswith('='): # x=( … ) array: data
513
+ close, _ = self._paren_extent(i + 1)
514
+ end = n if close is None else close + 1
515
+ for k2 in range(i, end):
516
+ self.block[k2] = True
517
+ if close is None:
518
+ self._uncertain(i, n, 'unclosed array literal')
519
+ i = end
520
+ continue
521
+ if f['test'] == ']]' and c in '&|': # [[ a && b ]]: internal, not a separator
522
+ self._end_word(f, i)
523
+ f['tpos'] = 0
524
+ self.code[i] = True
525
+ i += 1
526
+ continue
527
+ if f['case'] == 'body' and (t.startswith(';;', i) or t.startswith(';&', i)):
528
+ self._end_word(f, i)
529
+ self._separator(f)
530
+ f['case'] = 'pattern'
531
+ i += 3 if t.startswith(';;&', i) else 2
532
+ continue
533
+ if c == ')' and f['case'] == 'pattern':
534
+ self._end_word(f, i)
535
+ self._separator(f)
536
+ f['case'] = 'body'
537
+ self.code[i] = True
538
+ i += 1
539
+ continue
540
+ if c == ')' and f['closer'] == ')' and f['depth'] == 0:
541
+ self._end_word(f, i)
542
+ stack.pop()
543
+ i += 1
544
+ continue
545
+ if f['test'] is None and (c in '<>' or t.startswith('&>', i)):
546
+ # A descriptor adjacent to a redirect is not the command. Its operand is data,
547
+ # even if it looks like a failure assignment; preserve command position after it.
548
+ if f['cur'] is not None and t[f['cur']:i].isdigit():
549
+ f['cur'], f['cur_bad'] = None, False
550
+ else:
551
+ self._end_word(f, i)
552
+ op = re.match(r'(?:&>>|&>|>>|<>|>&|<&|>\||>|<)', t[i:]).group()
553
+ for offset in range(i, i + len(op)):
554
+ self.code[offset] = True
555
+ f['data_next'] = True
556
+ i += len(op)
557
+ continue
558
+ if c in ';&|()':
559
+ self._end_word(f, i)
560
+ if c == '(' and f['closer'] == ')':
561
+ f['depth'] += 1
562
+ elif c == ')' and f['depth'] > 0:
563
+ f['depth'] -= 1
564
+ if not (c == '(' and f['case'] == 'pattern'):
565
+ self._separator(f)
566
+ self.code[i] = True
567
+ i += 1
568
+ continue
569
+ if c in ' \t':
570
+ self._end_word(f, i)
571
+ i += 1
572
+ continue
573
+ if c in '<>':
574
+ self._end_word(f, i)
575
+ self.code[i] = True
576
+ i += 1
577
+ continue
578
+ self._word_char(f, i)
579
+ self.code[i] = True
580
+ if f['quiet']:
581
+ self.block[i] = True
582
+ i += 1
583
+ for fr in stack[1:]:
584
+ self._uncertain(fr['start'], n, 'unclosed %s' % fr['kind'])
585
+ self._end_word(stack[0], n)
586
+
587
+ def _open_dollar(self, stack, i, quiet):
588
+ """At `$(` · `$((` · `$[` — push the right frame and return the new index."""
589
+ t = self.t
590
+ if t.startswith('$[', i):
591
+ stack.append(self._frame('arith', i, quiet, ']'))
592
+ return i + 2
593
+ if t.startswith('$((', i):
594
+ close, double = self._paren_extent(i + 3)
595
+ if close is not None and double:
596
+ stack.append(self._frame('arith', i, quiet, '))'))
597
+ return i + 3
598
+ outer, _ = self._paren_extent(i + 2)
599
+ self._uncertain(i, self.n if outer is None else outer + 1, '«$((» that is not arithmetic')
600
+ fr = self._frame('code', i, True, ')')
601
+ stack.append(fr)
602
+ return i + 2
603
+ stack.append(self._frame('code', i, quiet, ')'))
604
+ return i + 2
605
+
606
+ def _heredoc_op(self, f, i, pending):
607
+ t, n = self.t, self.n
608
+ strip = t.startswith('<<-', i)
609
+ j = i + (3 if strip else 2)
610
+ while j < n and t[j] in ' \t':
611
+ j += 1
612
+ delim, quoted = [], False
613
+ while j < n and t[j] not in WORD_END:
614
+ c = t[j]
615
+ if c == '\\' and j + 1 < n:
616
+ delim.append(t[j + 1])
617
+ quoted = True
618
+ j += 2
619
+ elif c in '\'"':
620
+ k = t.find(c, j + 1)
621
+ if k == -1:
622
+ break
623
+ delim.append(t[j + 1:k])
624
+ quoted = True
625
+ j = k + 1
626
+ elif c in '$`':
627
+ delim = [] # an expanding delimiter — we do not model it
628
+ break
629
+ else:
630
+ delim.append(c)
631
+ j += 1
632
+ d = ''.join(delim)
633
+ if not d:
634
+ self._uncertain(i, n, 'heredoc delimiter we cannot read')
635
+ return n
636
+ rest = t[j:t.find('\n', j) if t.find('\n', j) != -1 else n]
637
+ is_py = not f['quiet'] and self._python_stdin(f) and TERMINATOR_OK.match(rest) is not None
638
+ pending.append((d, strip, is_py, not quoted))
639
+ return j
640
+
641
+ @staticmethod
642
+ def _word_char(f, i):
643
+ if f['cur'] is None:
644
+ f['cur'] = i
645
+
646
+ def _end_word(self, f, e):
647
+ if f['cur'] is None:
648
+ return
649
+ s = f['cur']
650
+ bad = f['cur_bad']
651
+ f['cur'], f['cur_bad'] = None, False
652
+ word = self.t[s:e]
653
+ redirect_operand = f['data_next']
654
+ data = bad or redirect_operand or f['quiet']
655
+ f['data_next'] = False
656
+ if redirect_operand:
657
+ self.words.append((s, e, word, False, False, True))
658
+ return
659
+ if f['case'] in ('word', 'in'):
660
+ f['case'] = 'in' if f['case'] == 'word' else ('pattern' if word == 'in' else None)
661
+ self.words.append((s, e, word, False, False, True))
662
+ return
663
+ if f['case'] == 'pattern':
664
+ if word == 'esac':
665
+ f['case'] = f['case_outer'].pop() if f['case_outer'] else None
666
+ self.words.append((s, e, word, False, False, True))
667
+ return
668
+ at_cmd = f['at_cmd'] or (f['assign_ok'] and '=' in word)
669
+ # a test operator only in OPERATOR position: exactly one operand since the test opened or since a
670
+ # connector (! -a -o && || ( ) — `[ "$1" = -eq ]` has an operand `-eq`, not an operator (rev7 #6)
671
+ in_test = f['test'] is not None and word not in (']', ']]') and f['tpos'] == 1
672
+ if f['test'] is not None and word not in (']', ']]'):
673
+ f['tpos'] = 0 if word in ('!', '-a', '-o', '(', ')', '\\(', '\\)') else f['tpos'] + 1
674
+ k_word = len(self.words)
675
+ self.words.append((s, e, word, at_cmd, in_test, data))
676
+ if f['test'] is not None:
677
+ f['twords'].append(k_word)
678
+ f['cmd'].append(word)
679
+ if f['at_cmd']:
680
+ if word in ('[', '[['):
681
+ f['test'] = ']' if word == '[' else ']]'
682
+ f['tpos'], f['twords'] = 0, []
683
+ elif word == 'test':
684
+ f['test'] = 'cmd'
685
+ f['tpos'], f['twords'] = 0, []
686
+ elif word == 'case':
687
+ if f['case'] is not None:
688
+ f['case_outer'].append(f['case'])
689
+ f['case'] = 'word'
690
+ elif word == 'esac':
691
+ f['case'] = f['case_outer'].pop() if f['case_outer'] else None
692
+ if f['test'] in (']', ']]') and word == f['test']:
693
+ f['test'] = None
694
+ f['twords'] = []
695
+ f['assign_ok'] = (f['at_cmd'] and word in ASSIGN_LEAD) or \
696
+ (f['assign_ok'] and ('=' in word or word.startswith('-')))
697
+ was_cmd, fn = f['at_cmd'], f['fn']
698
+ f['at_cmd'] = f['at_cmd'] and (word in CMD_KEYWORDS or re.match(r'^\w+=', word) is not None)
699
+ # `function NAME {` — the body opens at command position (v7 post-freeze fix: the keyword-position
700
+ # rule had stopped treating that `{` as a keyword)
701
+ f['fn'] = 1 if (was_cmd and word == 'function') else (2 if fn == 1 else 0)
702
+ if fn == 2 and word == '{':
703
+ f['at_cmd'] = True
704
+
705
+ def _separator(self, f):
706
+ if f['test'] in (']', ']]') and f['twords']:
707
+ # the command ended with its [ / [[ still open — the test was never what we thought (rev7 #10)
708
+ for k in f['twords']:
709
+ s, e, w, a, _, _ = self.words[k]
710
+ self.words[k] = (s, e, w, a, False, True)
711
+ self.notes.append('L%d: a test that never closes — not mutated (fail-closed)' % self._line(self.words[f['twords'][0]][0]))
712
+ f['test'] = None
713
+ f['twords'] = []
714
+ f['tpos'] = 0
715
+ f['fn'] = 0
716
+ f['cmd'] = []
717
+ f['at_cmd'] = True
718
+ f['assign_ok'] = False
719
+ f['data_next'] = False
720
+ if f['test'] == 'cmd':
721
+ f['test'] = None
722
+
723
+ @staticmethod
724
+ def _python_args(f):
725
+ """None if this command is not a python interpreter; else ('c'|'stdin'|'script'|'module'|'opts')
726
+ — what the arguments so far make of it."""
727
+ words = [w for w in f['cmd'] if not re.match(r'^\w+=', w)]
728
+ if words and os.path.basename(words[0]) == 'env':
729
+ words = words[1:]
730
+ while words and words[0].startswith('-'):
731
+ words = words[1:]
732
+ if not words or PY_INTERP.match(os.path.basename(words[0].strip('\'"'))) is None:
733
+ return None
734
+ state, skip = 'opts', False
735
+ for w in words[1:]:
736
+ if skip:
737
+ skip = False
738
+ continue
739
+ if state == 'c':
740
+ return 'c-done' # the -c argument is already behind us
741
+ if state != 'opts':
742
+ return state
743
+ if w == '-':
744
+ state = 'stdin'
745
+ elif w in PY_FLAG_ARG:
746
+ skip = True
747
+ elif w == '-m' or w.startswith('-m'):
748
+ return 'module'
749
+ elif re.match(r'^-[A-Za-z]+$', w):
750
+ body = w[1:]
751
+ if body.endswith('c') and all(ch in PY_FLAG_ONLY for ch in body[:-1]):
752
+ state = 'c'
753
+ elif not all(ch in PY_FLAG_ONLY for ch in body):
754
+ return 'unknown'
755
+ elif w.startswith('-'):
756
+ return 'unknown'
757
+ else:
758
+ return 'script'
759
+ return state
760
+
761
+ def _python_c(self, f):
762
+ return self._python_args(f) == 'c'
763
+
764
+ def _python_stdin(self, f):
765
+ return self._python_args(f) in ('stdin', 'opts')
766
+
767
+ def _heredoc_bodies(self, i, pending):
768
+ t, n = self.t, self.n
769
+ for delim, strip_tabs, is_py, expands in pending:
770
+ body_start = i
771
+ found = False
772
+ while i < n:
773
+ j = t.find('\n', i)
774
+ line_end = n if j == -1 else j
775
+ line = t[i:line_end]
776
+ if (line.lstrip('\t') if strip_tabs else line) == delim:
777
+ found = True
778
+ body_end = i
779
+ i = line_end + 1
780
+ break
781
+ i = line_end + 1
782
+ if not found:
783
+ self._uncertain(body_start, n, 'heredoc «%s» has no terminator' % delim)
784
+ return n
785
+ if is_py:
786
+ body = t[body_start:body_end]
787
+ if expands and re.search(r'[$`\\]', body):
788
+ self.notes.append('L%d: python heredoc is expanded by the shell — not mutated (fail-closed)'
789
+ % self._line(body_start))
790
+ else:
791
+ self.py.append((body_start, body_end, strip_tabs))
792
+ return i
793
+
794
+
795
+ def py_block(text, s, e, strip_tabs):
796
+ """(source, posmap) for an embedded python block; `<<-` bodies lose their leading tabs first."""
797
+ if not strip_tabs:
798
+ return text[s:e], (lambda k: s + k)
799
+ src, pos, k = [], [], s
800
+ for line in text[s:e].splitlines(True):
801
+ lead = len(line) - len(line.lstrip('\t'))
802
+ src.append(line[lead:])
803
+ pos.extend(range(k + lead, k + len(line)))
804
+ k += len(line)
805
+ pos.append(e)
806
+ return ''.join(src), (lambda j: pos[j])
807
+
808
+
809
+ def py_block_ok(src):
810
+ try:
811
+ compile(src, '<embedded>', 'exec')
812
+ return True
813
+ except (SyntaxError, ValueError):
814
+ return False
815
+
816
+
817
+ def bash_mutants(text, posix_sh=False):
818
+ sc = BashScan(text)
819
+ swap = TEST_SWAP_POSIX if posix_sh else TEST_SWAP
820
+ out = []
821
+ words = sc.words
822
+ for k, (s, e, w, at_cmd, in_test, data) in enumerate(words):
823
+ if data:
824
+ continue
825
+ if in_test and w in swap:
826
+ new = swap[w]
827
+ if posix_sh and '==' in (w, new):
828
+ continue
829
+ out.append((s, e, new, '%s→%s' % (w, new)))
830
+ elif at_cmd and w in ('exit', 'return') and k + 1 < len(words):
831
+ ns, ne, nw, _, _, ndata = words[k + 1]
832
+ if (re.match(r'^[1-9]\d*$', nw) and not ndata and re.match(r'^[ \t]*(\\\n[ \t]*)*$', text[e:ns])
833
+ and (ne >= len(text) or text[ne] not in '<>')):
834
+ out.append((ns, ne, '0', '%s %s→%s 0' % (w, nw, w)))
835
+ elif at_cmd and FAIL_ASSIGN.match(w):
836
+ name = w.split('=')[0]
837
+ out.append((s, e, name + '=0', '%s→%s=0' % (w, name)))
838
+ for m in ARITH_OP.finditer(text):
839
+ s = m.start()
840
+ if not all(sc.code[x] for x in range(s, m.end())):
841
+ continue
842
+ if ARITH_ONLY and not sc.arith[s]:
843
+ continue
844
+ new = PY_CMP[m.group(1)]
845
+ out.append((s, m.end(), new, '%s→%s' % (m.group(1), new)))
846
+ notes = list(sc.notes)
847
+ for (ps, pe, strip) in sc.py:
848
+ src, pmap = py_block(text, ps, pe, strip)
849
+ if not py_block_ok(src):
850
+ notes.append('L%d: embedded python does not compile on its own — not mutated' % (text.count('\n', 0, ps) + 1))
851
+ continue
852
+ try:
853
+ out.extend(py_mutants(src, pmap))
854
+ except (tokenize.TokenError, SyntaxError, IndentationError) as exc:
855
+ notes.append('L%d: embedded python did not tokenize (%s) — not mutated'
856
+ % (text.count('\n', 0, ps) + 1, type(exc).__name__))
857
+ kept = [m for m in out if not any(sc.block[x] for x in range(m[0], max(m[1], m[0] + 1)))]
858
+ kept.sort(key=lambda m: (m[0], m[1]))
859
+ return kept, notes, sc
860
+
861
+ # ───────────────────────────── mutants ─────────────────────────────
862
+
863
+ def enumerate_mutants(path, text):
864
+ lang, posix_sh = language(path, text)
865
+ if lang is None:
866
+ return None, posix_sh, [], []
867
+ if lang == 'python':
868
+ try:
869
+ raw, notes = py_mutants(text), []
870
+ except (tokenize.TokenError, SyntaxError, IndentationError) as exc:
871
+ return 'python', False, [], ['subject did not tokenize: %s' % type(exc).__name__]
872
+ else:
873
+ raw, notes, _ = bash_mutants(text, posix_sh)
874
+ muts, seen = [], set()
875
+ for s, e, new, label in raw:
876
+ if (s, e) in seen:
877
+ continue
878
+ seen.add((s, e))
879
+ data = text[:s] + new + text[e:]
880
+ line_no = text.count('\n', 0, s) + 1
881
+ ls = data.rfind('\n', 0, s) + 1
882
+ le = data.find('\n', s)
883
+ after = data[ls:(len(data) if le == -1 else le)].rstrip('\r')
884
+ muts.append({'line': line_no, 'op': label, 'after': after.strip(), '_data': data})
885
+ return lang, posix_sh, muts, notes
886
+
887
+
888
+ TEMPS = set()
889
+
890
+
891
+ ORIG_BLOCKS = {}
892
+
893
+
894
+ def py_blocks_ok(text):
895
+ return [py_block_ok(py_block(text, s, e, strip)[0]) for s, e, strip in BashScan(text).py]
896
+
897
+
898
+ def syntax_ok(lang, posix_sh, data, orig=None):
899
+ if lang == 'python':
900
+ try:
901
+ compile(data, '<mutant>', 'exec')
902
+ return True
903
+ except (SyntaxError, ValueError):
904
+ return False
905
+ d = tempfile.mkdtemp(prefix='mutation_probe_syn.')
906
+ TEMPS.add(d)
907
+ try:
908
+ p = os.path.join(d, 'm.sh')
909
+ with open(p, 'w', encoding='utf-8', newline='') as fh:
910
+ fh.write(data)
911
+ shell = 'sh' if posix_sh and shutil.which('sh') else 'bash'
912
+ r = subprocess.run([shell, '-n', p], capture_output=True, stdin=subprocess.DEVNULL)
913
+ if r.returncode != 0:
914
+ return False
915
+ # embedded python must still compile — but only blocks that compiled in the ORIGINAL: a block the
916
+ # shell expands, or one that never compiled, must not turn every mutant INVALID (v6 G20)
917
+ if orig is not None:
918
+ if orig not in ORIG_BLOCKS:
919
+ ORIG_BLOCKS[orig] = py_blocks_ok(orig)
920
+ before, after = ORIG_BLOCKS[orig], py_blocks_ok(data)
921
+ if len(before) != len(after):
922
+ return False
923
+ return all(a or not b for a, b in zip(after, before))
924
+ return True
925
+ finally:
926
+ shutil.rmtree(d, ignore_errors=True)
927
+ TEMPS.discard(d)
928
+
929
+ # ───────────────────────────── running ─────────────────────────────
930
+
931
+ CURRENT = {'proc': None}
932
+ STDOUT_DEAD = [False]
933
+
934
+
935
+ def say(msg='', err=False):
936
+ stream = sys.stderr if err else sys.stdout
937
+ if stream is sys.stdout and STDOUT_DEAD[0]:
938
+ return
939
+ try:
940
+ print(msg, file=stream, flush=True)
941
+ except BrokenPipeError:
942
+ if stream is sys.stdout:
943
+ STDOUT_DEAD[0] = True
944
+ try:
945
+ os.dup2(os.open(os.devnull, os.O_WRONLY), sys.stdout.fileno())
946
+ except OSError:
947
+ pass
948
+
949
+
950
+ def lane_cmd(lane):
951
+ try:
952
+ with open(lane, 'rb') as fh:
953
+ first = fh.readline().decode('utf-8', 'replace')
954
+ except OSError:
955
+ first = ''
956
+ if first.startswith('#!'):
957
+ if os.access(lane, os.X_OK): # let the kernel read its own shebang (v6: shlex split it differently)
958
+ return [lane if os.sep in lane else os.path.join(os.curdir, lane)]
959
+ parts = shebang_split(first.rstrip('\n'))
960
+ if parts:
961
+ return parts + [lane]
962
+ if lane.endswith('.py'):
963
+ return [sys.executable, lane]
964
+ return ['bash', lane]
965
+
966
+
967
+ SUBREAPER = [False]
968
+
969
+
970
+ def become_subreaper():
971
+ """Linux: orphans of the lane (incl. `setsid` escapees) are reparented to us, so we can kill them."""
972
+ try:
973
+ import ctypes
974
+ libc = ctypes.CDLL(None, use_errno=True)
975
+ SUBREAPER[0] = libc.prctl(36, 1, 0, 0, 0) == 0 # PR_SET_CHILD_SUBREAPER
976
+ except (OSError, AttributeError):
977
+ SUBREAPER[0] = False
978
+ return SUBREAPER[0]
979
+
980
+
981
+ def kill_descendants():
982
+ """SIGKILL every process whose parent is us (orphaned lane descendants), until none are left."""
983
+ me = os.getpid()
984
+ for _ in range(50):
985
+ kids = []
986
+ try:
987
+ for pid in os.listdir('/proc'):
988
+ if not pid.isdigit():
989
+ continue
990
+ try:
991
+ with open('/proc/%s/stat' % pid, 'rb') as fh:
992
+ st = fh.read().decode('ascii', 'replace')
993
+ if int(st.rsplit(')', 1)[1].split()[1]) == me:
994
+ kids.append(int(pid))
995
+ except (OSError, ValueError, IndexError):
996
+ continue
997
+ except OSError:
998
+ return
999
+ for pid in kids:
1000
+ try:
1001
+ os.kill(pid, signal.SIGKILL)
1002
+ except (ProcessLookupError, PermissionError):
1003
+ pass
1004
+ while True:
1005
+ try:
1006
+ r, _ = os.waitpid(-1, os.WNOHANG)
1007
+ except ChildProcessError:
1008
+ break
1009
+ if r == 0:
1010
+ break
1011
+ if not kids:
1012
+ return
1013
+ time.sleep(0.02)
1014
+
1015
+
1016
+ LANE_END = [0]
1017
+
1018
+
1019
+ def run_lane(lane, timeout):
1020
+ cache = tempfile.mkdtemp(prefix='mutation_probe_pyc.')
1021
+ TEMPS.add(cache)
1022
+ env = dict(os.environ, PYTHONDONTWRITEBYTECODE='1', PYTHONPYCACHEPREFIX=cache)
1023
+ try:
1024
+ p = subprocess.Popen(lane_cmd(lane), stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
1025
+ stderr=subprocess.DEVNULL, env=env, start_new_session=True)
1026
+ except OSError as exc:
1027
+ shutil.rmtree(cache, ignore_errors=True)
1028
+ TEMPS.discard(cache)
1029
+ return 'NOT-RUNNABLE:%s' % type(exc).__name__
1030
+ CURRENT['proc'] = p
1031
+ try:
1032
+ return p.wait(timeout=timeout)
1033
+ except subprocess.TimeoutExpired:
1034
+ return 'TIMEOUT'
1035
+ finally:
1036
+ try:
1037
+ os.killpg(p.pid, signal.SIGKILL) # the whole group, also after a normal exit
1038
+ except (ProcessLookupError, PermissionError):
1039
+ pass
1040
+ p.wait()
1041
+ CURRENT['proc'] = None
1042
+ if SUBREAPER[0]:
1043
+ kill_descendants()
1044
+ LANE_END[0] = time.time_ns() // 10**9
1045
+ shutil.rmtree(cache, ignore_errors=True)
1046
+ TEMPS.discard(cache)
1047
+
1048
+
1049
+ def digest(b):
1050
+ return hashlib.sha256(b).hexdigest()
1051
+
1052
+
1053
+ def read_bytes(path):
1054
+ with open(path, 'rb') as fh:
1055
+ return fh.read()
1056
+
1057
+
1058
+ def write_bytes(path, b):
1059
+ with open(path, 'wb') as fh:
1060
+ fh.write(b)
1061
+
1062
+
1063
+ def subject_pycs(subject):
1064
+ stem = os.path.splitext(os.path.basename(subject))[0]
1065
+ cache_dir = os.path.join(os.path.dirname(os.path.abspath(subject)), '__pycache__')
1066
+ pat = re.compile(r'^%s\.[^.]+(\.opt-\d)?\.pyc$' % re.escape(stem))
1067
+ try:
1068
+ return [os.path.join(cache_dir, f) for f in os.listdir(cache_dir) if pat.match(f)]
1069
+ except OSError:
1070
+ return []
1071
+
1072
+
1073
+ # SIGPIPE is deliberately absent: python ignores it and raises BrokenPipeError, which say() absorbs —
1074
+ # a closed stdout must not abort a run half-way (it did in the first v6 draft: rc 141).
1075
+ TERMINATING = [s for s in ('SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGTERM', 'SIGABRT', 'SIGPWR', 'SIGUSR1', 'SIGUSR2', 'SIGALRM',
1076
+ 'SIGVTALRM', 'SIGPROF', 'SIGXCPU', 'SIGXFSZ') if hasattr(signal, s)]
1077
+
1078
+
1079
+ HELD = []
1080
+
1081
+
1082
+ def control_bytes(lang, text):
1083
+ """The positive control: a subject that stops at once. A lane that stays green on it never runs it."""
1084
+ first = text.split('\n', 1)[0]
1085
+ head = first + '\n' if first.startswith('#!') else ''
1086
+ return (head + ('raise SystemExit(113)\n' if lang == 'python' else 'exit 113\n')).encode('utf-8')
1087
+
1088
+
1089
+ def main():
1090
+ ap = argparse.ArgumentParser(add_help=True)
1091
+ ap.add_argument('subject')
1092
+ ap.add_argument('lane', nargs='?')
1093
+ ap.add_argument('--timeout', type=float, default=300)
1094
+ ap.add_argument('--max', type=int, default=0)
1095
+ ap.add_argument('--list', action='store_true')
1096
+ ap.add_argument('--json', dest='json_out')
1097
+ try:
1098
+ a = ap.parse_args()
1099
+ except SystemExit as exc:
1100
+ return 0 if exc.code == 0 else 2 # --help prints and succeeds
1101
+ subj = os.path.realpath(a.subject)
1102
+ try:
1103
+ lst0 = os.lstat(subj)
1104
+ except OSError:
1105
+ lst0 = None
1106
+ if lst0 is None or not stat.S_ISREG(lst0.st_mode):
1107
+ say('CANNOT JUDGE: subject not found or not a regular file: %s' % a.subject, err=True)
1108
+ return 2
1109
+ orig = read_bytes(subj)
1110
+ try:
1111
+ text = orig.decode('utf-8')
1112
+ except UnicodeDecodeError:
1113
+ say('CANNOT JUDGE: subject is not UTF-8: %s' % a.subject, err=True)
1114
+ return 2
1115
+ lang, posix_sh, muts, notes = enumerate_mutants(a.subject, text)
1116
+ if lang is None:
1117
+ say('CANNOT JUDGE: unsupported language (bash/sh/python by extension or shebang; zsh/ksh are not '
1118
+ 'modelled): %s' % a.subject, err=True)
1119
+ return 2
1120
+ for note in notes:
1121
+ say('note: %s' % note)
1122
+ if a.max > 0:
1123
+ muts = muts[:a.max]
1124
+ if a.list:
1125
+ say('lang=%s mutants=%d' % (lang, len(muts)))
1126
+ for m in muts:
1127
+ say(' L%d [%s] %s' % (m['line'], m['op'], m['after']))
1128
+ if a.json_out:
1129
+ say('note: --json is ignored with --list')
1130
+ return 0 if muts else 2
1131
+ if not a.lane or not os.path.isfile(a.lane):
1132
+ say('CANNOT JUDGE: lane suite not found: %s' % a.lane, err=True)
1133
+ return 2
1134
+ if os.path.samefile(subj, a.lane):
1135
+ say('CANNOT JUDGE: the subject and the lane are the same file', err=True)
1136
+ return 2
1137
+ if not (a.timeout > 0):
1138
+ say('CANNOT JUDGE: --timeout must be > 0 (got %s)' % a.timeout, err=True)
1139
+ return 2
1140
+ if a.json_out:
1141
+ jdir = os.path.dirname(os.path.abspath(a.json_out))
1142
+ clash = os.path.exists(a.json_out) and (os.path.samefile(a.json_out, subj) or
1143
+ os.path.samefile(a.json_out, a.lane))
1144
+ if clash or os.path.realpath(a.json_out) in (subj, os.path.realpath(a.lane)):
1145
+ say('CANNOT JUDGE: --json points at the subject or the lane — refusing to overwrite it', err=True)
1146
+ return 2
1147
+ if not (os.path.isdir(jdir) and os.access(jdir, os.W_OK)):
1148
+ say('CANNOT JUDGE: --json not writable: %s' % a.json_out, err=True)
1149
+ return 2
1150
+ if not muts:
1151
+ say('CANNOT JUDGE: no mutants generated for %s — 0 survivors over 0 mutants is not «clean»' % a.subject,
1152
+ err=True)
1153
+ return 2
1154
+ if not (lst0.st_mode & stat.S_IWUSR) or not os.access(subj, os.W_OK):
1155
+ say('CANNOT JUDGE: subject is not writable: %s' % a.subject, err=True) # mode bits too: root ignores W_OK
1156
+ return 2
1157
+ if lst0.st_mtime_ns // 10**9 > time.time() + 5:
1158
+ say('CANNOT JUDGE: the subject\'s mtime is in the future — every restore would have to move it further; '
1159
+ 'fix the mtime first: %s' % a.subject, err=True)
1160
+ return 2
1161
+
1162
+ # ── one open file description per file: every write goes to the ORIGINAL inode, never through a path
1163
+ # a lane may have swapped for a link; flock on it is the lock (cross-uid, hard links, subject↔lane)
1164
+ try:
1165
+ fd0 = os.open(subj, os.O_RDWR | getattr(os, 'O_NOFOLLOW', 0))
1166
+ lfd = os.open(a.lane, os.O_RDONLY)
1167
+ except OSError as exc:
1168
+ say('CANNOT JUDGE: cannot open %s: %s' % (a.subject, exc), err=True)
1169
+ return 2
1170
+ st0 = os.fstat(fd0)
1171
+ if (st0.st_dev, st0.st_ino) != (lst0.st_dev, lst0.st_ino):
1172
+ say('CANNOT JUDGE: the subject changed while starting', err=True)
1173
+ return 2
1174
+ # locks: ONE namespace keyed by inode, shared by every user — subject and lane alike, so a probe whose
1175
+ # lane is another probe's subject (or the same file under another name or uid) is refused
1176
+ ldir = os.path.join('/tmp' if os.path.isdir('/tmp') else tempfile.gettempdir(), 'mutation_probe.locks')
1177
+ try:
1178
+ try:
1179
+ os.mkdir(ldir, 0o1777)
1180
+ os.chmod(ldir, 0o1777)
1181
+ except FileExistsError:
1182
+ pass
1183
+ lds = os.lstat(ldir)
1184
+ if (not stat.S_ISDIR(lds.st_mode) or not (lds.st_mode & stat.S_ISVTX)
1185
+ or lds.st_uid not in (0, os.getuid())):
1186
+ raise OSError('%s is not a sticky directory owned by root or this user' % ldir)
1187
+ except OSError as exc:
1188
+ say('CANNOT JUDGE: cannot use the lock directory: %s — refusing to run unlocked' % exc, err=True)
1189
+ return 2
1190
+ lst_l = os.fstat(lfd)
1191
+ for (dev, ino), what in (((st0.st_dev, st0.st_ino), 'the subject (or uses it as its lane)'),
1192
+ ((lst_l.st_dev, lst_l.st_ino), 'the lane (or mutates it)')):
1193
+ lp = os.path.join(ldir, 'i-%d-%d.lock' % (dev, ino))
1194
+ try:
1195
+ kfd = os.open(lp, os.O_RDONLY | os.O_CREAT | getattr(os, 'O_NOFOLLOW', 0), 0o444)
1196
+ fcntl.flock(kfd, fcntl.LOCK_EX | fcntl.LOCK_NB)
1197
+ except BlockingIOError:
1198
+ say('CANNOT JUDGE: another mutation_probe holds %s' % what, err=True)
1199
+ return 2
1200
+ except OSError as exc:
1201
+ say('CANNOT JUDGE: cannot take the lock %s (%s) — refusing to run unlocked' % (lp, exc), err=True)
1202
+ return 2
1203
+ HELD.append(kfd)
1204
+
1205
+ # what we enumerated was read BEFORE the lock — another probe may have had a mutant live then (rev7 #1)
1206
+ os.lseek(fd0, 0, os.SEEK_SET)
1207
+ under_lock = b''
1208
+ while True:
1209
+ chunk = os.read(fd0, 1 << 16)
1210
+ if not chunk:
1211
+ break
1212
+ under_lock += chunk
1213
+ if under_lock != orig:
1214
+ say('CANNOT JUDGE: the subject changed between reading it and locking it (another probe may have had a '
1215
+ 'mutant live) — re-run when it is idle', err=True)
1216
+ return 2
1217
+
1218
+ sdir = os.path.join('/tmp' if os.path.isdir('/tmp') else tempfile.gettempdir(),
1219
+ 'mutation_probe-%d' % os.getuid())
1220
+ try:
1221
+ os.makedirs(sdir, mode=0o700, exist_ok=True)
1222
+ sst = os.lstat(sdir)
1223
+ if not stat.S_ISDIR(sst.st_mode) or sst.st_uid != os.getuid() or stat.S_IMODE(sst.st_mode) & 0o077:
1224
+ raise OSError('state dir is not a private directory owned by this user')
1225
+ except OSError as exc:
1226
+ say('CANNOT JUDGE: cannot use the state directory %s: %s' % (sdir, exc), err=True)
1227
+ return 2
1228
+ backup = os.path.join(sdir, 'path-%s.backup' % digest(subj.encode())[:16])
1229
+ ibackup = os.path.join(sdir, 'inode-%d-%d.backup' % (st0.st_dev, st0.st_ino))
1230
+ for b in (backup, ibackup):
1231
+ if os.path.lexists(b):
1232
+ say('CANNOT JUDGE: a previous run left a backup at %s — %s (or another name of it) may hold a mutant. '
1233
+ 'Compare, restore by hand if needed, then delete the backups.' % (b, a.subject), err=True)
1234
+ return 2
1235
+ try:
1236
+ os.utime(fd0, ns=(st0.st_atime_ns, st0.st_mtime_ns))
1237
+ except OSError as exc:
1238
+ say('CANNOT JUDGE: cannot set the mtime of %s (%s) — the pyc/make guard depends on it' % (a.subject, exc), err=True)
1239
+ return 2
1240
+ if not become_subreaper():
1241
+ say('note: no subreaper on this OS — a lane descendant that escapes with setsid is not killed (named residual)')
1242
+
1243
+ want = digest(orig)
1244
+ mode = stat.S_IMODE(st0.st_mode)
1245
+ last_sec = [st0.st_mtime_ns // 10**9]
1246
+ state = {'backup_written': False}
1247
+
1248
+ def stamp():
1249
+ """A new whole second per write — later than the previous write AND than the end of the last lane
1250
+ run (so nothing the lane built can look as new) — never in the future."""
1251
+ floor = max(last_sec[0], LANE_END[0])
1252
+ now = time.time_ns()
1253
+ if now // 10**9 <= floor:
1254
+ time.sleep(((floor + 1) * 10**9 - now) / 1e9 + 0.002)
1255
+ now = time.time_ns()
1256
+ os.utime(fd0, ns=(st0.st_atime_ns, now))
1257
+ last_sec[0] = now // 10**9
1258
+
1259
+ def put(b):
1260
+ os.ftruncate(fd0, 0)
1261
+ os.lseek(fd0, 0, os.SEEK_SET)
1262
+ view = memoryview(b)
1263
+ while view:
1264
+ view = view[os.write(fd0, view):]
1265
+
1266
+ def get():
1267
+ os.lseek(fd0, 0, os.SEEK_SET)
1268
+ chunks = []
1269
+ while True:
1270
+ c = os.read(fd0, 1 << 16)
1271
+ if not c:
1272
+ return b''.join(chunks)
1273
+ chunks.append(c)
1274
+
1275
+ def path_state():
1276
+ try:
1277
+ ls = os.lstat(subj)
1278
+ except FileNotFoundError:
1279
+ return 'missing'
1280
+ if stat.S_ISLNK(ls.st_mode):
1281
+ return 'link'
1282
+ if not stat.S_ISREG(ls.st_mode):
1283
+ return 'other'
1284
+ return 'ok' if (ls.st_dev, ls.st_ino) == (st0.st_dev, st0.st_ino) else 'replaced'
1285
+
1286
+ def drop_pycs():
1287
+ for f in subject_pycs(subj) if lang == 'python' else []:
1288
+ try:
1289
+ os.unlink(f)
1290
+ except OSError as exc:
1291
+ say('note: could not delete %s (%s) — a stale pyc may remain' % (f, exc))
1292
+
1293
+ def restore():
1294
+ """The original inode gets the original bytes. The PATH is then checked, never written through."""
1295
+ try:
1296
+ put(orig)
1297
+ os.fchmod(fd0, mode)
1298
+ stamp()
1299
+ drop_pycs()
1300
+ if get() != orig:
1301
+ return False
1302
+ except OSError:
1303
+ return False
1304
+ ps = path_state()
1305
+ if ps == 'ok':
1306
+ return True
1307
+ if ps in ('missing', 'replaced'):
1308
+ # a regular file at the path that is not ours (a hard link to anything — even the lane), or nothing:
1309
+ # never write INTO it (rev7 #2). Put a fresh file with the original bytes in its place, atomically.
1310
+ tmp = None
1311
+ try:
1312
+ tfd, tmp = tempfile.mkstemp(prefix='.mutation_probe.', dir=os.path.dirname(subj))
1313
+ try:
1314
+ os.write(tfd, orig)
1315
+ os.fchmod(tfd, mode)
1316
+ finally:
1317
+ os.close(tfd)
1318
+ if path_state() == 'other':
1319
+ return False
1320
+ os.rename(tmp, subj)
1321
+ tmp = None
1322
+ return digest(read_bytes(subj)) == want and path_state() == 'replaced'
1323
+ except OSError:
1324
+ return False
1325
+ finally:
1326
+ if tmp:
1327
+ try:
1328
+ os.unlink(tmp)
1329
+ except OSError:
1330
+ pass
1331
+ return False # a link, a directory, or nothing: not written through, loud
1332
+
1333
+ def cleanup_temps():
1334
+ for d in list(TEMPS):
1335
+ shutil.rmtree(d, ignore_errors=True)
1336
+ TEMPS.discard(d)
1337
+
1338
+ def finish_ok():
1339
+ for sig in TERMINATING:
1340
+ try:
1341
+ signal.signal(getattr(signal, sig), signal.SIG_DFL)
1342
+ except (OSError, ValueError):
1343
+ pass
1344
+ cleanup_temps()
1345
+ for b in (backup, ibackup):
1346
+ try:
1347
+ os.unlink(b)
1348
+ except FileNotFoundError:
1349
+ pass
1350
+
1351
+ def on_signal(signum, _frame):
1352
+ p = CURRENT['proc']
1353
+ if p is not None:
1354
+ try:
1355
+ os.killpg(p.pid, signal.SIGKILL)
1356
+ except (ProcessLookupError, PermissionError):
1357
+ pass
1358
+ if SUBREAPER[0]:
1359
+ kill_descendants() # also a lane started but not yet recorded in CURRENT
1360
+ cleanup_temps()
1361
+ if state['backup_written'] and not restore():
1362
+ say('🟥🟥🟥 RESTORE FAILED on signal %d — %s may hold a mutant. Backup: %s' % (signum, a.subject, backup), err=True)
1363
+ os._exit(3)
1364
+ finish_ok()
1365
+ os._exit(128 + signum)
1366
+ for sig in TERMINATING:
1367
+ try:
1368
+ signal.signal(getattr(signal, sig), on_signal) # installed BEFORE the backup exists
1369
+ except (OSError, ValueError):
1370
+ pass
1371
+
1372
+ def fail_restore(why):
1373
+ say('🟥🟥🟥 RESTORE FAILED (%s) — %s may hold a mutant, or the path is no longer the subject (a link / '
1374
+ 'directory / missing — nothing was written through it). Backup: %s' % (why, a.subject, backup), err=True)
1375
+ return 3
1376
+
1377
+ try:
1378
+ fd = os.open(backup, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
1379
+ with os.fdopen(fd, 'wb') as fh:
1380
+ fh.write(orig)
1381
+ os.link(backup, ibackup)
1382
+ state['backup_written'] = True
1383
+ except OSError as exc:
1384
+ finish_ok()
1385
+ say('CANNOT JUDGE: cannot write the backup %s: %s — nothing was mutated' % (backup, exc), err=True)
1386
+ return 2
1387
+
1388
+ def after_lane():
1389
+ """'ok' · 'wrote' (same inode, other bytes) · 'replaced' (another file at the path) · 'gone'."""
1390
+ try:
1391
+ live_lane = os.stat(a.lane)
1392
+ if (live_lane.st_dev, live_lane.st_ino) != (lst_l.st_dev, lst_l.st_ino):
1393
+ return 'lane-replaced'
1394
+ except OSError:
1395
+ return 'lane-replaced'
1396
+ ps = path_state()
1397
+ if ps in ('link', 'other', 'missing'):
1398
+ return 'gone'
1399
+ if ps == 'replaced':
1400
+ return 'replaced'
1401
+ return 'ok'
1402
+
1403
+ res, lane_wrote = [], []
1404
+ try:
1405
+ drop_pycs() # an unchecked-hash pyc left from before would make every mutant invisible
1406
+ say('── mutation_probe ─────────────────────────────────────────────')
1407
+ say('subject: %s (%s%s) · lane: %s · mutants: %d' % (a.subject, lang, ', posix sh' if posix_sh else '',
1408
+ a.lane, len(muts)))
1409
+ say('🟥 survivors are QUESTIONS (equivalent / boundary / redundant / gap), not a score.')
1410
+
1411
+ def guarded_run(data, what):
1412
+ """Write `data` (None = original as it stands), run the lane, check what it did to the subject."""
1413
+ if data is not None:
1414
+ put(data)
1415
+ stamp() # its own whole second — never shares a pyc / make key
1416
+ rc = run_lane(a.lane, a.timeout)
1417
+ seen = after_lane()
1418
+ content_ok = get() == (orig if data is None else data)
1419
+ if seen != 'ok' or not content_ok:
1420
+ if not restore():
1421
+ return None, fail_restore('%s: the lane %s the subject' % (
1422
+ what, 'replaced' if seen != 'ok' else 'wrote'))
1423
+ return rc, 'replaced' if seen != 'ok' else 'wrote'
1424
+ return rc, None
1425
+
1426
+ base, bad = guarded_run(None, 'baseline')
1427
+ if base is None:
1428
+ return bad
1429
+ if bad:
1430
+ finish_ok()
1431
+ say('CANNOT JUDGE: the baseline lane WROTE the subject%s — a lane that edits its own subject cannot be '
1432
+ 'probed' % (' (it replaced the file — a new inode)' if bad == 'replaced' else ''), err=True)
1433
+ return 2
1434
+ if base != 0:
1435
+ finish_ok()
1436
+ if isinstance(base, str) and base.startswith('NOT-RUNNABLE'):
1437
+ say('CANNOT JUDGE: the lane could not be started (%s) — check its shebang / interpreter' % base, err=True)
1438
+ elif base == 'TIMEOUT':
1439
+ say('CANNOT JUDGE: the baseline lane timed out after %ss — raise --timeout' % a.timeout, err=True)
1440
+ else:
1441
+ say('CANNOT JUDGE: baseline lane is not green (rc=%s) — every mutant would read as «killed»' % base,
1442
+ err=True)
1443
+ return 2
1444
+ # positive control: a subject that exits at once must turn the lane red
1445
+ ctl, bad = guarded_run(control_bytes(lang, text), 'control')
1446
+ if ctl is None:
1447
+ return bad
1448
+ if not restore():
1449
+ return fail_restore('after the control')
1450
+ if bad:
1451
+ finish_ok()
1452
+ say('CANNOT JUDGE: the lane wrote the subject during the control run', err=True)
1453
+ return 2
1454
+ if ctl == 0:
1455
+ finish_ok()
1456
+ say('CANNOT JUDGE: positive control SURVIVED — the lane stays green on a subject that exits at once, so '
1457
+ 'it does not run %s; every mutant would read as «survived»' % a.subject, err=True)
1458
+ return 2
1459
+ if isinstance(ctl, str):
1460
+ finish_ok()
1461
+ say('CANNOT JUDGE: the positive control did not finish (%s) — a lane that hangs is not a lane that '
1462
+ 'noticed' % ctl, err=True)
1463
+ return 2
1464
+ for m in muts:
1465
+ if not syntax_ok(lang, posix_sh, m['_data'], text if lang == 'bash' else None):
1466
+ m['verdict'] = 'INVALID'
1467
+ res.append(m)
1468
+ continue
1469
+ rc, bad = guarded_run(m['_data'].encode('utf-8'), 'mutant L%d [%s]' % (m['line'], m['op']))
1470
+ if rc is None:
1471
+ return bad
1472
+ if bad:
1473
+ lane_wrote.append(m)
1474
+ elif not restore():
1475
+ return fail_restore('after mutant L%d' % m['line'])
1476
+ if isinstance(rc, str) and rc.startswith('NOT-RUNNABLE'):
1477
+ m['verdict'] = 'INVALID'
1478
+ else:
1479
+ m['verdict'] = 'TIMEOUT' if rc == 'TIMEOUT' else ('KILLED' if rc != 0 else 'SURVIVED')
1480
+ res.append(m)
1481
+ # final run on the restored original: whatever the lane built from the last mutant is rebuilt from it
1482
+ fin, bad = guarded_run(None, 'final')
1483
+ if fin is None:
1484
+ return bad
1485
+ except Exception as exc: # noqa: BLE001 — any failure here must end in a restore check, loudly
1486
+ if not restore():
1487
+ return fail_restore('probe error: %s' % type(exc).__name__)
1488
+ finish_ok()
1489
+ say('CANNOT JUDGE: probe error after restore: %s: %s' % (type(exc).__name__, exc), err=True)
1490
+ return 2
1491
+ if not restore():
1492
+ return fail_restore('final restore')
1493
+ finish_ok()
1494
+
1495
+ count = {k: sum(1 for r in res if r['verdict'] == k) for k in ('KILLED', 'SURVIVED', 'TIMEOUT', 'INVALID')}
1496
+ say('mutants=%d killed=%d survived=%d timeout=%d invalid=%d' % (
1497
+ len(res), count['KILLED'], count['SURVIVED'], count['TIMEOUT'], count['INVALID']))
1498
+ for r in res:
1499
+ if r['verdict'] in ('SURVIVED', 'TIMEOUT', 'INVALID'):
1500
+ say(' %-8s L%d [%s] %s' % (r['verdict'], r['line'], r['op'], r['after'][:100]))
1501
+ if count['SURVIVED']:
1502
+ say('triage each survivor: EQUIVALENT · BOUNDARY · REDUNDANT · GAP — only GAP asks for a new lane')
1503
+ if lane_wrote:
1504
+ say('CANNOT JUDGE: the lane WROTE or REPLACED the subject while a mutant was live (%s) — those verdicts are '
1505
+ 'not about the mutant' % ', '.join('L%d [%s]' % (m['line'], m['op']) for m in lane_wrote), err=True)
1506
+ return 2
1507
+ if bad:
1508
+ say('CANNOT JUDGE: the final lane run on the restored original %s the subject' % bad, err=True)
1509
+ return 2
1510
+ if fin != 0:
1511
+ say('CANNOT JUDGE: the final lane run on the restored original is not green (rc=%s) — something the lane '
1512
+ 'built from a mutant may persist, or the lane is not deterministic' % fin, err=True)
1513
+ return 2
1514
+ if count['KILLED'] + count['SURVIVED'] == 0:
1515
+ say('CANNOT JUDGE: nothing was measured — every mutant was INVALID or TIMEOUT', err=True)
1516
+ return 2
1517
+ if a.json_out: # written only for a measured run — never for «cannot judge»
1518
+ try:
1519
+ jfd = os.open(a.json_out, os.O_WRONLY | os.O_CREAT | os.O_NONBLOCK | getattr(os, 'O_NOFOLLOW', 0), 0o644)
1520
+ jst = os.fstat(jfd)
1521
+ # Also exclude the current paths: a lane can replace its original inode.
1522
+ current_inodes = {(st.st_dev, st.st_ino) for st in (os.stat(subj), os.stat(a.lane))}
1523
+ if (not stat.S_ISREG(jst.st_mode) or (jst.st_dev, jst.st_ino) in
1524
+ current_inodes | {(st0.st_dev, st0.st_ino), (lst_l.st_dev, lst_l.st_ino)}):
1525
+ os.close(jfd)
1526
+ say('CANNOT JUDGE: --json now points at the subject or the lane (or is not a regular file) — '
1527
+ 'refusing to write it (rev7 #3)', err=True)
1528
+ return 2
1529
+ os.ftruncate(jfd, 0)
1530
+ with os.fdopen(jfd, 'w', encoding='utf-8') as fh:
1531
+ json.dump({'measured': True, 'subject': a.subject, 'lane': a.lane, 'lang': lang, 'counts': count,
1532
+ 'mutants': [{k: v for k, v in r.items() if k != '_data'} for r in res]},
1533
+ fh, ensure_ascii=False, indent=1)
1534
+ except OSError as exc:
1535
+ say('CANNOT JUDGE: --json not writable: %s' % exc, err=True)
1536
+ return 2
1537
+ return 0
1538
+
1539
+
1540
+ if __name__ == '__main__':
1541
+ sys.exit(main())