deepmodebot 0.10.0 → 0.11.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 (75) hide show
  1. package/.agents/plugins/marketplace.json +1 -1
  2. package/.claude-plugin/marketplace.json +2 -2
  3. package/.omp-plugin/marketplace.json +2 -2
  4. package/README.md +15 -6
  5. package/bin/deepmodebot.mjs +104 -10
  6. package/native/dmb-gate/Cargo.toml +1 -1
  7. package/native/dmb-gate/src/agents.rs +58 -25
  8. package/native/dmb-gate/src/ci.rs +530 -14
  9. package/native/dmb-gate/src/main.rs +215 -7
  10. package/native/dmb-gate/src/reward.rs +1895 -242
  11. package/native/dmb-gate/src/sim.rs +969 -0
  12. package/native/dmb-gate/src/slop.rs +1061 -295
  13. package/package.json +1 -1
  14. package/plugins/deepmodebot/.antigravity-plugin/plugin.json +1 -1
  15. package/plugins/deepmodebot/.antigravity-plugin/skills/deep/SKILL.md +1 -1
  16. package/plugins/deepmodebot/.claude-plugin/plugin.json +1 -1
  17. package/plugins/deepmodebot/.codex-plugin/plugin.json +2 -2
  18. package/plugins/deepmodebot/agents/comment-sicko.md +29 -0
  19. package/plugins/deepmodebot/agents/researcher.md +29 -0
  20. package/plugins/deepmodebot/agents/reviewer.md +29 -0
  21. package/plugins/deepmodebot/agents/scout.md +28 -0
  22. package/plugins/deepmodebot/agents/security-reviewer.md +27 -0
  23. package/plugins/deepmodebot/commands/deep.md +3 -2
  24. package/plugins/deepmodebot/commands/tournament.md +1 -1
  25. package/plugins/deepmodebot/hooks/hooks.json +12 -2
  26. package/plugins/deepmodebot/hooks.json +1 -1
  27. package/plugins/deepmodebot/scripts/antigravity-guard.mjs +740 -37
  28. package/plugins/deepmodebot/skills/agent-harnesses/references/antigravity.md +2 -2
  29. package/plugins/deepmodebot/skills/deepmodebot/SKILL.md +19 -11
  30. package/plugins/deepmodebot/skills/deepmodebot/assets/agents-md/agents_md.py +51 -20
  31. package/plugins/deepmodebot/skills/deepmodebot/assets/autoroute/autoroute.py +54 -49
  32. package/plugins/deepmodebot/skills/deepmodebot/assets/contain/claude-guard.sh +4 -0
  33. package/plugins/deepmodebot/skills/deepmodebot/assets/contain/claude_guard.py +658 -21
  34. package/plugins/deepmodebot/skills/deepmodebot/assets/contain/holdout_guard_cases.json +272 -0
  35. package/plugins/deepmodebot/skills/deepmodebot/assets/contain/omp-contain.ts +774 -23
  36. package/plugins/deepmodebot/skills/deepmodebot/assets/f2p-gate/f2p_gate.py +547 -0
  37. package/plugins/deepmodebot/skills/deepmodebot/assets/gap-audit/gap_audit.py +5 -11
  38. package/plugins/deepmodebot/skills/deepmodebot/assets/git-guardrails/git-guard-patterns.txt +4 -4
  39. package/plugins/deepmodebot/skills/deepmodebot/assets/git-guardrails/git-guard.sh +53 -6
  40. package/plugins/deepmodebot/skills/deepmodebot/assets/git-guardrails/git-guard.ts +48 -2
  41. package/plugins/deepmodebot/skills/deepmodebot/assets/local-ci/local_ci.py +262 -6
  42. package/plugins/deepmodebot/skills/deepmodebot/assets/local-ci/slop_gate.py +529 -122
  43. package/plugins/deepmodebot/skills/deepmodebot/assets/loop/loop.py +747 -46
  44. package/plugins/deepmodebot/skills/deepmodebot/assets/memory/project_memory.py +404 -5
  45. package/plugins/deepmodebot/skills/deepmodebot/assets/mutation/mutation_gate.py +798 -0
  46. package/plugins/deepmodebot/skills/deepmodebot/assets/reward-guard/reward_guard.py +2050 -200
  47. package/plugins/deepmodebot/skills/deepmodebot/assets/rules/rule-paths.json +44 -1
  48. package/plugins/deepmodebot/skills/deepmodebot/assets/rules/rule_ledger.py +278 -252
  49. package/plugins/deepmodebot/skills/deepmodebot/assets/rules/rules_watch.py +436 -0
  50. package/plugins/deepmodebot/skills/deepmodebot/assets/self-grill/self_grill.py +594 -18
  51. package/plugins/deepmodebot/skills/deepmodebot/assets/setup/project_setup.py +41 -5
  52. package/plugins/deepmodebot/skills/deepmodebot/assets/sim/sim.py +856 -0
  53. package/plugins/deepmodebot/skills/deepmodebot/assets/worker-gate/worker_gate.py +237 -0
  54. package/plugins/deepmodebot/skills/deepmodebot/references/catalog.md +3 -2
  55. package/plugins/deepmodebot/skills/deepmodebot/references/delegation.md +6 -2
  56. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/authoring-a-skill.md +1 -1
  57. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/hillclimb.md +1 -0
  58. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/self-authoring.md +1 -1
  59. package/plugins/deepmodebot/skills/deepmodebot/references/principles/no-reward-hacking.md +6 -6
  60. package/plugins/deepmodebot/skills/deepmodebot/references/rule-approval.md +36 -16
  61. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/autoroute.md +9 -8
  62. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/correct.md +1 -0
  63. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/inner-loop.md +6 -2
  64. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/mutation-testing.md +31 -9
  65. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/no-comments.md +1 -1
  66. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/panel.md +4 -4
  67. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/sim.md +41 -0
  68. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/tdd.md +12 -0
  69. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/tournament.md +24 -13
  70. package/plugins/deepmodebot/skills/deepmodebot/worker.md +28 -16
  71. package/plugins/deepmodebot/agents/comment-sicko/agent.md +0 -35
  72. package/plugins/deepmodebot/agents/researcher/agent.md +0 -33
  73. package/plugins/deepmodebot/agents/reviewer/agent.md +0 -35
  74. package/plugins/deepmodebot/agents/scout/agent.md +0 -33
  75. package/plugins/deepmodebot/agents/security-reviewer/agent.md +0 -31
@@ -0,0 +1,798 @@
1
+ #!/usr/bin/env python3
2
+ """Mutate the changed source lines of a diff and require the test command to fail for every valid mutant."""
3
+ import argparse
4
+ from contextlib import contextmanager
5
+ from dataclasses import dataclass
6
+ import importlib.util
7
+ import io
8
+ import json
9
+ import math
10
+ import os
11
+ from pathlib import Path, PurePosixPath
12
+ import random
13
+ import re
14
+ import shutil
15
+ import stat
16
+ import subprocess
17
+ import sys
18
+ import tempfile
19
+ import time
20
+ import tokenize
21
+
22
+ sys.dont_write_bytecode = True
23
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "f2p-gate"))
24
+ try:
25
+ import f2p_gate
26
+ finally:
27
+ sys.path.pop(0)
28
+
29
+
30
+ LANGUAGES = {".py": "python", ".js": "js", ".jsx": "js", ".mjs": "js", ".cjs": "js", ".ts": "js", ".tsx": "js",
31
+ ".mts": "js", ".cts": "js", ".go": "go", ".rs": "rust"}
32
+ DOCS_SUFFIXES = {".md", ".mdx", ".rst", ".adoc", ".txt", ".json", ".jsonc", ".yml", ".yaml", ".toml", ".ini", ".cfg",
33
+ ".conf", ".lock", ".xml", ".csv", ".svg", ".png", ".jpg", ".jpeg", ".gif", ".ico", ".webp", ".pdf"}
34
+ DOCS_NAMES = {".gitignore", ".gitattributes", ".editorconfig", ".npmrc", ".nvmrc", "license", "notice", "codeowners",
35
+ "go.sum", "go.mod"}
36
+ TEST_PARENTS = {"test", "tests", "__tests__", "spec"}
37
+ SPEC_JS = re.compile(r"\.spec\.(?:js|jsx|ts|tsx|mjs|cjs)$")
38
+ KEYWORDS = frozenset({"return", "and", "or", "not", "in", "is", "if", "elif", "else", "yield", "await", "typeof",
39
+ "case", "lambda", "assert", "del", "raise", "while", "for", "with", "throw", "new", "delete",
40
+ "void", "instanceof", "of", "import", "from", "print", "match", "let", "const", "var", "as",
41
+ "where", "mut", "ref", "move", "break", "continue", "do", "extends"})
42
+ REGEX_AFTER = frozenset("(,=:[!&|?{};+-*%<>~^")
43
+ REGEX_WORDS = frozenset({"return", "typeof", "case", "throw", "in", "of", "delete", "void", "do", "else", "yield",
44
+ "await", "instanceof", "new"})
45
+ CHAR_LITERAL = re.compile(r"'(?:\\(?:u\{[0-9A-Fa-f_]+\}|x[0-9A-Fa-f]{2}|[^\n])|[^\\'\n])'")
46
+ RAW_STRING = re.compile(r"b?r(#*)\"")
47
+
48
+ EQUALITY_PY = re.compile(r"(?<![=!<>])(==|!=)(?!=)")
49
+ EQUALITY_C = re.compile(r"(?<![=!<>:])(===|!==|==|!=)(?!=)")
50
+ EQUALITY_SWAP = {"==": "!=", "!=": "==", "===": "!==", "!==": "==="}
51
+ RELATION_PY = re.compile(r"(?<![<>=!\-])(<=|>=|<(?![<=])|>(?![>=]))(?!=)")
52
+ RELATION_C = re.compile(r"(?<=\s)(<=|>=|<|>)(?=\s)")
53
+ RELATION_SWAP = {"<": "<=", "<=": "<", ">": ">=", ">=": ">"}
54
+ LOGIC_PY = re.compile(r"(?<![.\w])(and|or)(?!\w)")
55
+ LOGIC_C = re.compile(r"(?<![&|])(&&|\|\|)(?![&|=])")
56
+ LOGIC_SWAP = {"and": "or", "or": "and", "&&": "||", "||": "&&"}
57
+ BOOL_PY = re.compile(r"(?<![.\w])(True|False)(?!\w)")
58
+ BOOL_C = re.compile(r"(?<![.\w$])(true|false)(?![\w$])")
59
+ BOOL_SWAP = {"True": "False", "False": "True", "true": "false", "false": "true"}
60
+ NOT_PY = re.compile(r"(?<![.\w])not\b\s*")
61
+ NOT_C = re.compile(r"(?<![\w)\]!=<>])!(?![=!\[])")
62
+ GUARD_PY = re.compile(r"^\s*(?:if|elif)\s+(?P<c>.+?)\s*:$")
63
+ GUARD_JS = re.compile(r"\bif\s*\((?P<c>.*)\)\s*\{?$")
64
+ GUARD_BLOCK = re.compile(r"\bif\s+(?P<c>[^{]+?)\s*\{$")
65
+ RETURN_PY = re.compile(r"^\s*return\s+(?P<e>\S.*?)\s*$")
66
+ RETURN_C = re.compile(r"^\s*(?:\}\s*)?return\s+(?P<e>[^;]+?)\s*;?\s*$")
67
+ EXPONENT = re.compile(r"(?<![\w.])\d[\d_.]*[eE]$")
68
+ COMPILE_FAILURE = {
69
+ "go": re.compile(r"(?m)^FAIL\t\S+ \[(?:build|setup) failed\]"),
70
+ "rust": re.compile(r"(?m)^error(?:\[E\d+\])?: (?:could not compile|aborting due to)"),
71
+ "js": re.compile(r"(?m)^(?:SyntaxError: |.*ERR_(?:INVALID|UNSUPPORTED)_TYPESCRIPT_SYNTAX)"),
72
+ }
73
+ ZERO_TESTS = {"unittest": re.compile(r"(?m)^Ran 0 tests? "), "node": re.compile(r"(?m)^# tests 0\s*$")}
74
+ INVALID_CAP_FACTOR = 4
75
+ BOUNDARY_OPERATORS = frozenset({"rel-swap"})
76
+ DEFAULT_MIN_SCORE = 0.6
77
+ OUTPUT_TAIL = 4000
78
+
79
+
80
+ @dataclass(frozen=True)
81
+ class Mutant:
82
+ file: str
83
+ lang: str
84
+ line: int
85
+ start: int
86
+ end: int
87
+ replacement: str
88
+ operator: str
89
+ original: str
90
+ mutated: str
91
+
92
+
93
+ def blanked(chars, start, end):
94
+ for index in range(start, end):
95
+ if chars[index] not in "\r\n":
96
+ chars[index] = " "
97
+
98
+
99
+ def python_blanks(text):
100
+ starts = [0]
101
+ starts.extend(match.end() for match in re.finditer("\n", text))
102
+ fstring_middle = getattr(tokenize, "FSTRING_MIDDLE", None)
103
+ fstring_start = getattr(tokenize, "FSTRING_START", None)
104
+ fstring_end = getattr(tokenize, "FSTRING_END", None)
105
+ opened = []
106
+ for token in tokenize.generate_tokens(io.StringIO(text).readline):
107
+ if token.type not in {tokenize.COMMENT, tokenize.STRING, fstring_start, fstring_end, fstring_middle}:
108
+ continue
109
+ begin = starts[token.start[0] - 1] + token.start[1]
110
+ finish = starts[token.end[0] - 1] + token.end[1]
111
+ if token.type == tokenize.STRING:
112
+ yield begin + 1, finish - 1
113
+ elif token.type == fstring_start:
114
+ opened.append(begin)
115
+ elif token.type == fstring_end and opened:
116
+ yield opened.pop() + 1, finish - 1
117
+ elif token.type != fstring_end:
118
+ yield begin, finish
119
+
120
+
121
+ def mask_python(text):
122
+ chars = list(text)
123
+ try:
124
+ for begin, finish in python_blanks(text):
125
+ blanked(chars, begin, finish)
126
+ except (tokenize.TokenError, SyntaxError) as exc:
127
+ raise ValueError(f"cannot tokenize: {exc}") from exc
128
+ return "".join(chars)
129
+
130
+
131
+ def quoted_end(text, index, multiline):
132
+ quote = text[index]
133
+ size = len(text)
134
+ cursor = index + 1
135
+ while cursor < size and text[cursor] != quote and (multiline or text[cursor] != "\n"):
136
+ cursor += 2 if text[cursor] == "\\" else 1
137
+ return min(cursor + 1, size) if cursor < size and text[cursor] == quote else min(cursor, size)
138
+
139
+
140
+ def template_end(text, index):
141
+ size = len(text)
142
+ while index < size:
143
+ char = text[index]
144
+ if char == "\\":
145
+ index += 2
146
+ elif char == "`":
147
+ return index + 1
148
+ elif text.startswith("${", index):
149
+ index = expression_end(text, index + 2)
150
+ else:
151
+ index += 1
152
+ return size
153
+
154
+
155
+ def expression_end(text, index):
156
+ size = len(text)
157
+ depth = 1
158
+ while index < size:
159
+ char = text[index]
160
+ if char in "\"'":
161
+ index = quoted_end(text, index, False)
162
+ elif char == "`":
163
+ index = template_end(text, index + 1)
164
+ else:
165
+ depth += (char == "{") - (char == "}")
166
+ index += 1
167
+ if depth == 0:
168
+ return index
169
+ return size
170
+
171
+
172
+ def rust_block_comment_end(text, index):
173
+ depth = 0
174
+ size = len(text)
175
+ while index < size:
176
+ if text.startswith("/*", index):
177
+ depth += 1
178
+ index += 2
179
+ elif text.startswith("*/", index):
180
+ depth -= 1
181
+ index += 2
182
+ if depth == 0:
183
+ return index
184
+ else:
185
+ index += 1
186
+ return size
187
+
188
+
189
+ def regex_span(text, index):
190
+ size = len(text)
191
+ end = index + 1
192
+ in_class = False
193
+ while end < size and text[end] != "\n" and (in_class or text[end] != "/"):
194
+ if text[end] == "\\":
195
+ end += 1
196
+ elif text[end] in "[]":
197
+ in_class = text[end] == "["
198
+ end += 1
199
+ return (end + 1, index + 1, end, ")") if end < size and text[end] == "/" else None
200
+
201
+
202
+ def literal_span(text, index, lang, previous, word):
203
+ char = text[index]
204
+ size = len(text)
205
+ if text.startswith("//", index):
206
+ end = text.find("\n", index)
207
+ end = size if end < 0 else end
208
+ return end, index, end, ""
209
+ if text.startswith("/*", index):
210
+ if lang == "rust":
211
+ end = rust_block_comment_end(text, index)
212
+ else:
213
+ end = text.find("*/", index + 2)
214
+ end = size if end < 0 else end + 2
215
+ return end, index, end, ""
216
+ if char == '"' or (char == "'" and lang == "js"):
217
+ end = quoted_end(text, index, lang != "js")
218
+ closed = end - 1 > index and text[end - 1] == char
219
+ return end, index + 1, end - 1 if closed else end, char
220
+ if char == "'":
221
+ literal = CHAR_LITERAL.match(text, index)
222
+ end = literal.end() if literal else index + 1
223
+ return end, index + 1, end - 1 if literal else index + 1, "'"
224
+ if char == "`" and lang == "js":
225
+ end = template_end(text, index + 1)
226
+ return end, index + 1, end - 1, char
227
+ if char == "`" and lang == "go":
228
+ end = text.find("`", index + 1)
229
+ end = size if end < 0 else end + 1
230
+ return end, index + 1, end - 1, char
231
+ raw = RAW_STRING.match(text, index) if lang == "rust" and char in "rb" else None
232
+ if raw:
233
+ close = '"' + raw.group(1)
234
+ found = text.find(close, raw.end())
235
+ end = size if found < 0 else found + len(close)
236
+ return end, raw.end(), max(raw.end(), end - len(close)), '"'
237
+ if char == "/" and lang == "js" and (previous == "" or previous in REGEX_AFTER or word in REGEX_WORDS):
238
+ return regex_span(text, index)
239
+ return None
240
+
241
+
242
+ def mask_c(text, lang):
243
+ size = len(text)
244
+ chars = list(text)
245
+ index = 0
246
+ previous = ""
247
+ word = ""
248
+ while index < size:
249
+ char = text[index]
250
+ if char.isspace():
251
+ index += 1
252
+ continue
253
+ span = literal_span(text, index, lang, previous, word)
254
+ if span is not None:
255
+ end, start, stop, last = span
256
+ blanked(chars, start, stop)
257
+ index = end
258
+ if last:
259
+ previous, word = last, ""
260
+ elif char.isalnum() or char in "_$":
261
+ end = index
262
+ while end < size and (text[end].isalnum() or text[end] in "_$"):
263
+ end += 1
264
+ word = text[index:end]
265
+ previous = word[-1]
266
+ index = end
267
+ else:
268
+ index += 1
269
+ previous, word = char, ""
270
+ return "".join(chars)
271
+
272
+
273
+ def mask(text, lang):
274
+ return mask_python(text) if lang == "python" else mask_c(text, lang)
275
+
276
+
277
+ def operand_before(masked, index):
278
+ before = masked[:index].rstrip()
279
+ if not before or not (before[-1].isalnum() or before[-1] in "_$)]}\"'`"):
280
+ return False
281
+ word = re.search(r"[A-Za-z_]\w*$", before)
282
+ return word is None or word.group() not in KEYWORDS
283
+
284
+
285
+ def pattern_sites(pattern, masked, swap, operator, group=1):
286
+ return [(m.start(group), m.end(group), swap[m.group(group)], operator) for m in pattern.finditer(masked)]
287
+
288
+
289
+ def arithmetic_sites(masked):
290
+ sites = []
291
+ for index, char in enumerate(masked):
292
+ if char not in "+-" or index == 0:
293
+ continue
294
+ following = masked[index + 1:index + 2]
295
+ if masked[index - 1] in "+-=" or following in {"+", "-", "=", ">"}:
296
+ continue
297
+ after = masked[index + 1:].lstrip()
298
+ if not after or not (after[0].isalnum() or after[0] in "_$(\"'[`"):
299
+ continue
300
+ if EXPONENT.search(masked[:index]) or not operand_before(masked, index):
301
+ continue
302
+ sites.append((index, index + 1, "-" if char == "+" else "+", "arith-swap"))
303
+ return sites
304
+
305
+
306
+ def guard_sites(masked, lang):
307
+ line = masked.rstrip()
308
+ if lang == "python":
309
+ found = GUARD_PY.match(line)
310
+ if found and "__name__" in found.group("c"):
311
+ return []
312
+ else:
313
+ found = (GUARD_JS if lang == "js" else GUARD_BLOCK).search(line)
314
+ if found and lang != "js" and (found.group("c").startswith("let ") or (lang == "go" and ";" in found.group("c"))):
315
+ return []
316
+ if not found:
317
+ return []
318
+ truth = ("True", "False") if lang == "python" else ("true", "false")
319
+ condition = found.group("c").strip()
320
+ return [(found.start("c"), found.end("c"), value, f"guard-{str(value).lower()}")
321
+ for value in truth if condition != value]
322
+
323
+
324
+ def return_sites(masked, lang):
325
+ found = (RETURN_PY if lang == "python" else RETURN_C).match(masked.rstrip())
326
+ if not found:
327
+ return []
328
+ start, end = found.start("e"), found.end("e")
329
+ expression = found.group("e")
330
+ swap = BOOL_SWAP.get(expression)
331
+ if swap is not None:
332
+ return [(start, end, swap, "return-const")]
333
+ number = re.fullmatch(r"-?\d+", expression)
334
+ if number:
335
+ return [(start, end, "1" if int(expression) == 0 else "0", "return-const")]
336
+ quotes = "\"'" if lang in {"python", "js"} else '"'
337
+ if len(expression) >= 3 and expression[0] in quotes and expression[0] == expression[-1] and expression[1:-1].strip() == "":
338
+ return [(start, end, expression[0] * 2, "return-const")]
339
+ return []
340
+
341
+
342
+ def find_sites(masked, lang):
343
+ python = lang == "python"
344
+ sites = pattern_sites(EQUALITY_PY if python else EQUALITY_C, masked, EQUALITY_SWAP, "eq-swap")
345
+ sites += pattern_sites(RELATION_PY if python else RELATION_C, masked, RELATION_SWAP, "rel-swap")
346
+ for found in (LOGIC_PY if python else LOGIC_C).finditer(masked):
347
+ if python or operand_before(masked, found.start()):
348
+ sites.append((found.start(), found.end(), LOGIC_SWAP[found.group(1)], "logic-swap"))
349
+ sites += arithmetic_sites(masked)
350
+ sites += pattern_sites(BOOL_PY if python else BOOL_C, masked, BOOL_SWAP, "bool-swap")
351
+ sites += [(m.start(), m.end(), "", "drop-not") for m in (NOT_PY if python else NOT_C).finditer(masked)]
352
+ sites += guard_sites(masked, lang)
353
+ sites += return_sites(masked, lang)
354
+ return sites
355
+
356
+
357
+ def cutoff_line(masked_lines, lang):
358
+ pattern = {"python": r"if\s+__name__\s*==", "rust": r"#\[cfg\(test\)\]"}.get(lang)
359
+ if pattern is None:
360
+ return None
361
+ for number, line in enumerate(masked_lines, 1):
362
+ if re.match(pattern, line):
363
+ return number
364
+ return None
365
+
366
+
367
+ def file_mutants(path, lang, text, changed):
368
+ original = text.split("\n")
369
+ masked_lines = mask(text, lang).split("\n")
370
+ cutoff = cutoff_line(masked_lines, lang)
371
+ found = {}
372
+ for number in sorted(changed):
373
+ if number < 1 or number > len(original) or (cutoff is not None and number >= cutoff):
374
+ continue
375
+ line = original[number - 1]
376
+ for start, end, replacement, operator in find_sites(masked_lines[number - 1], lang):
377
+ mutated = line[:start] + replacement + line[end:]
378
+ if mutated != line:
379
+ found.setdefault((number, mutated), Mutant(path, lang, number, start, end, replacement, operator,
380
+ line.strip(), mutated.strip()))
381
+ return list(found.values())
382
+
383
+
384
+ def mutated_bytes(text, mutant):
385
+ lines = text.split("\n")
386
+ line = lines[mutant.line - 1]
387
+ lines[mutant.line - 1] = line[:mutant.start] + mutant.replacement + line[mutant.end:]
388
+ return "\n".join(lines).encode("utf-8")
389
+
390
+
391
+ def is_test(path):
392
+ parents = path.split("/")[:-1]
393
+ return (f2p_gate.is_test(path) or any(part in TEST_PARENTS for part in parents)
394
+ or SPEC_JS.search(path.rsplit("/", 1)[-1]) is not None)
395
+
396
+
397
+ def classify(path):
398
+ if f2p_gate.scratch(path):
399
+ return "ignored"
400
+ if is_test(path):
401
+ return "test"
402
+ name = PurePosixPath(path).name.lower()
403
+ suffix = PurePosixPath(path).suffix.lower()
404
+ if name.endswith(".d.ts") or suffix in DOCS_SUFFIXES or name in DOCS_NAMES:
405
+ return "docs"
406
+ return "source" if suffix in LANGUAGES else "unsupported"
407
+
408
+
409
+ def hunk_lines(diff):
410
+ lines = set()
411
+ for match in re.finditer(r"(?m)^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@", diff):
412
+ count = 1 if match.group(2) is None else int(match.group(2))
413
+ lines.update(range(int(match.group(1)), int(match.group(1)) + count))
414
+ return lines
415
+
416
+
417
+ def changed_paths(root, base):
418
+ tracked = f2p_gate.git_paths(f2p_gate.git(root, "diff", "--no-ext-diff", "--no-renames", "--name-only", "-z", base, "--"))
419
+ untracked = f2p_gate.git_paths(f2p_gate.git(root, "ls-files", "--others", "--exclude-standard", "-z"))
420
+ return sorted(tracked | untracked), untracked
421
+
422
+
423
+ def read_source(root, path):
424
+ file = f2p_gate.path_at(root, path)
425
+ if not file.is_file():
426
+ return None
427
+ return file.read_bytes().decode("utf-8")
428
+
429
+
430
+ def changed_line_numbers(root, base, path, text, untracked):
431
+ if path in untracked:
432
+ return set(range(1, text.count("\n") + 2))
433
+ diff = f2p_gate.git(root, "diff", "--no-ext-diff", "--no-renames", "--no-color", "-U0", base, "--", path)
434
+ return hunk_lines(diff.decode("utf-8", errors="replace"))
435
+
436
+
437
+ def plan_mutants(root, base, result):
438
+ notes = result["notes"]
439
+ paths, untracked = changed_paths(root, base)
440
+ sources, mutants, others = {}, [], []
441
+ for path in paths:
442
+ kind = classify(path)
443
+ if kind == "source":
444
+ try:
445
+ text = read_source(root, path)
446
+ except UnicodeDecodeError:
447
+ notes.append(f"unmutable-file: {path} is not UTF-8")
448
+ others.append(path)
449
+ continue
450
+ if text is None:
451
+ continue
452
+ sources[path] = text
453
+ lang = LANGUAGES[PurePosixPath(path).suffix.lower()]
454
+ try:
455
+ found = file_mutants(path, lang, text, changed_line_numbers(root, base, path, text, untracked))
456
+ except ValueError as exc:
457
+ notes.append(f"unmutable-file: {path}: {exc}")
458
+ others.append(path)
459
+ continue
460
+ if not found:
461
+ notes.append(f"no-mutable-lines: {path}")
462
+ others.append(path)
463
+ mutants.extend(found)
464
+ elif kind == "unsupported":
465
+ notes.append(f"unsupported-language: {path}")
466
+ others.append(path)
467
+ return sources, mutants, others
468
+
469
+
470
+ def spread(mutants, seed):
471
+ ordered = sorted(mutants, key=lambda m: (m.file, m.line, m.start, m.operator, m.replacement))
472
+ random.Random(seed).shuffle(ordered)
473
+ seen, first, rest = set(), [], []
474
+ for mutant in ordered:
475
+ key = (mutant.file, mutant.line)
476
+ (rest if key in seen else first).append(mutant)
477
+ seen.add(key)
478
+ return first + rest
479
+
480
+
481
+ def detect_command(root, lang):
482
+ interpreter = [sys.executable, "-B", "-m"]
483
+ if lang == "python":
484
+ if any((root / name).is_file() for name in ("pytest.ini", ".pytest.ini")) or importlib.util.find_spec("pytest"):
485
+ return "pytest", [*interpreter, "pytest", "-x", "-q", "-p", "no:cacheprovider"]
486
+ return "unittest", [*interpreter, "unittest", "discover", "-f"]
487
+ if lang == "js":
488
+ manifest = root / "package.json"
489
+ script = json.loads(manifest.read_text(encoding="utf-8")).get("scripts", {}).get("test") if manifest.is_file() else None
490
+ if isinstance(script, str) and "no test specified" not in script:
491
+ return "npm", ["npm", "test"]
492
+ return "node", ["node", "--test", "--test-reporter=tap"]
493
+ if lang == "go" and (root / "go.mod").is_file():
494
+ return "go", ["go", "test", "./..."]
495
+ if lang == "rust" and (root / "Cargo.toml").is_file():
496
+ return "cargo", ["cargo", "test", "--color", "never"]
497
+ return None
498
+
499
+
500
+ def ran_nothing(runner, output):
501
+ if runner in ZERO_TESTS:
502
+ return ZERO_TESTS[runner].search(output) is not None
503
+ if runner == "go":
504
+ return re.search(r"(?m)^ok\s", output) is None
505
+ if runner == "cargo":
506
+ return re.search(r"(?m)^running [1-9]\d* tests?", output) is None
507
+ return False
508
+
509
+
510
+ def detach_link(path):
511
+ if os.path.lexists(path):
512
+ try:
513
+ os.rmdir(path)
514
+ except OSError:
515
+ os.unlink(path)
516
+ if os.path.lexists(path):
517
+ raise OSError(f"could not detach linked directory: {path}")
518
+
519
+
520
+ def unlock(function, path, _error):
521
+ os.chmod(path, stat.S_IWRITE)
522
+ function(path)
523
+
524
+
525
+ def remove_tree(path, links=()):
526
+ for link in links:
527
+ detach_link(path / link)
528
+ for attempt in range(5):
529
+ if not path.exists():
530
+ return
531
+ try:
532
+ if sys.version_info >= (3, 12):
533
+ shutil.rmtree(path, onexc=unlock)
534
+ else:
535
+ shutil.rmtree(path, onerror=unlock)
536
+ except OSError:
537
+ time.sleep(0.2 * (attempt + 1))
538
+ if path.exists():
539
+ raise OSError(f"could not remove {path}")
540
+
541
+
542
+ def link_directory(source, destination):
543
+ if os.name == "nt":
544
+ import _winapi
545
+ _winapi.CreateJunction(str(source), str(destination))
546
+ else:
547
+ os.symlink(source, destination, target_is_directory=True)
548
+
549
+
550
+ def tree_names(root):
551
+ listed = f2p_gate.git(root, "ls-files", "-z", "--cached", "--others", "--exclude-standard")
552
+ return sorted(name for name in f2p_gate.git_paths(listed)
553
+ if not f2p_gate.scratch(name) and os.path.lexists(root.joinpath(*name.split("/"))))
554
+
555
+
556
+ def linked_directories(root, names):
557
+ modules = root / "node_modules"
558
+ tracked = any(name.startswith("node_modules/") for name in names)
559
+ return ["node_modules"] if modules.is_dir() and not modules.is_symlink() and not tracked else []
560
+
561
+
562
+ @contextmanager
563
+ def workspace(root, names, links, parent):
564
+ destination = parent / "copy"
565
+ destination.mkdir()
566
+ try:
567
+ for name in names:
568
+ source = root.joinpath(*name.split("/"))
569
+ target = destination.joinpath(*name.split("/"))
570
+ target.parent.mkdir(parents=True, exist_ok=True)
571
+ if source.is_dir() and not source.is_symlink():
572
+ shutil.copytree(source, target, symlinks=True)
573
+ else:
574
+ shutil.copy2(source, target, follow_symlinks=False)
575
+ for link in links:
576
+ link_directory(root / link, destination / link)
577
+ yield destination
578
+ finally:
579
+ remove_tree(destination, links)
580
+
581
+
582
+ def run_command(argv, directory, run_dir, timeout):
583
+ found = (directory / argv[0]).is_file() if os.path.dirname(argv[0]) else shutil.which(argv[0]) is not None
584
+ if not found:
585
+ raise ValueError(f"test-command-error: cannot run {argv[0]!r}: not found")
586
+ scratch = run_dir / "tmp"
587
+ scratch.mkdir(exist_ok=True)
588
+ try:
589
+ return f2p_gate.run_test(argv, directory, scratch, timeout, run_dir / "cargo-target")
590
+ except OSError as exc:
591
+ raise ValueError(f"test-command-error: cannot run {argv[0]!r}: {exc}") from exc
592
+
593
+
594
+ def precheck(directory, mutant, data):
595
+ if mutant.lang == "python":
596
+ try:
597
+ compile(data, mutant.file, "exec", dont_inherit=True)
598
+ except (SyntaxError, ValueError) as exc:
599
+ return f"does not parse: {exc}"
600
+ return None
601
+ if mutant.file.endswith((".js", ".mjs", ".cjs")):
602
+ proc = subprocess.run(["node", "--check", mutant.file], cwd=directory, capture_output=True, text=True,
603
+ encoding="utf-8", errors="replace", timeout=60)
604
+ if proc.returncode:
605
+ return "does not parse: " + ((proc.stderr.strip().splitlines() or [""])[-1])
606
+ return None
607
+
608
+
609
+ def judge(mutant, code, output):
610
+ if code is None:
611
+ return "timeout", output
612
+ if code == 0:
613
+ return "survived", None
614
+ pattern = COMPILE_FAILURE.get(mutant.lang)
615
+ if pattern is not None and pattern.search(output):
616
+ return "invalid", "does not compile"
617
+ return "killed", None
618
+
619
+
620
+ def evaluate(root, names, links, commands, run_dir, mutant, text, timeout):
621
+ data = mutated_bytes(text, mutant)
622
+ with workspace(root, names, links, run_dir) as directory:
623
+ f2p_gate.path_at(directory, mutant.file).write_bytes(data)
624
+ reason = precheck(directory, mutant, data)
625
+ if reason:
626
+ return "invalid", reason
627
+ _, argv = commands[mutant.lang]
628
+ code, output = run_command(argv, directory, run_dir, timeout)
629
+ return judge(mutant, code, output)
630
+
631
+
632
+ def check_baseline(root, names, links, commands, run_dir, timeout, result):
633
+ seen = set()
634
+ with workspace(root, names, links, run_dir) as directory:
635
+ for lang, (runner, argv) in sorted(commands.items()):
636
+ if tuple(argv) in seen:
637
+ continue
638
+ seen.add(tuple(argv))
639
+ code, output = run_command(argv, directory, run_dir, timeout)
640
+ if code is None:
641
+ result["violations"].append(f"baseline-timeout: {lang} tests exceeded {timeout:g}s on the unmutated tree")
642
+ elif code != 0:
643
+ result["violations"].append(f"baseline-red: {lang} tests fail on the unmutated tree (exit {code})")
644
+ elif ran_nothing(runner, output):
645
+ result["violations"].append(f"baseline-red: {lang} test command executed no tests")
646
+ else:
647
+ continue
648
+ result["baseline"] = {"command": argv, "exit_code": code, "output": output[-OUTPUT_TAIL:]}
649
+ return False
650
+ return True
651
+
652
+
653
+ def record(mutant, number, status, detail):
654
+ entry = {"id": f"m{number}", "file": mutant.file, "line": mutant.line, "operator": mutant.operator,
655
+ "original": mutant.original, "mutated": mutant.mutated, "status": status}
656
+ if detail:
657
+ entry["detail"] = detail[-OUTPUT_TAIL:]
658
+ return entry
659
+
660
+
661
+ def summarize(result, opts):
662
+ entries = result["mutants"]
663
+ killed = [e for e in entries if e["status"] == "killed"]
664
+ survived_all = [e for e in entries if e["status"] == "survived"]
665
+ boundary = [e for e in survived_all if e["operator"] in BOUNDARY_OPERATORS]
666
+ survived = [e for e in survived_all if e["operator"] not in BOUNDARY_OPERATORS]
667
+ timeouts = [e for e in entries if e["status"] == "timeout"]
668
+ result["killed"] = len(killed)
669
+ result["survived"] = survived
670
+ result["survived_boundary"] = boundary
671
+ result["timeouts"] = timeouts
672
+ result["invalid"] = sum(e["status"] == "invalid" for e in entries)
673
+ evaluated = len(killed) + len(survived_all) + len(timeouts)
674
+ if not evaluated:
675
+ result["violations"].append("no-valid-mutants: every candidate mutant was invalid")
676
+ return
677
+ result["score"] = len(killed) / evaluated
678
+ where = "{file}:{line}: {original} => {mutated} ({operator})"
679
+ result["violations"].extend("timeout: " + where.format(**e) for e in timeouts)
680
+ if result["score"] < opts.min_score:
681
+ result["violations"].extend("survived-mutant: " + where.format(**e) for e in survived)
682
+ result["violations"].extend("survived-boundary: " + where.format(**e) for e in boundary)
683
+ elif survived_all:
684
+ result["notes"].append(f"survivors-tolerated: score {result['score']:.2f} >= --min-score {opts.min_score:g}"
685
+ f" ({len(survived)} survived, {len(boundary)} survived_boundary)")
686
+
687
+
688
+ def run_mutants(root, base, opts, result):
689
+ sources, mutants, others = plan_mutants(root, base, result)
690
+ if not mutants:
691
+ result["notes"].append("no-mutable-lines")
692
+ if others:
693
+ result["violations"].append("no-mutable-lines: changed files have no mutable lines: " + ", ".join(others))
694
+ return
695
+ override = f2p_gate.command_words(opts.test_cmd) if opts.test_cmd is not None else None
696
+ commands = {}
697
+ for lang in sorted({m.lang for m in mutants}):
698
+ detected = ("custom", override) if override is not None else detect_command(root, lang)
699
+ if detected is None:
700
+ result["violations"].append(f"test-command-error: no test command detected for {lang}; pass --test-cmd")
701
+ return
702
+ commands[lang] = detected
703
+ tmp = f2p_gate.path_at(root, ".scratch/tmp")
704
+ tmp.mkdir(parents=True, exist_ok=True)
705
+ names = tree_names(root)
706
+ links = linked_directories(root, names)
707
+ run_dir = Path(tempfile.mkdtemp(prefix="mutate-", dir=tmp))
708
+ try:
709
+ if not check_baseline(root, names, links, commands, run_dir, opts.timeout, result):
710
+ return
711
+ valid, invalid, cap = 0, 0, opts.max_mutants * INVALID_CAP_FACTOR
712
+ for mutant in spread(mutants, opts.seed):
713
+ if valid >= opts.max_mutants or invalid >= cap:
714
+ break
715
+ status, detail = evaluate(root, names, links, commands, run_dir, mutant, sources[mutant.file], opts.timeout)
716
+ result["mutants"].append(record(mutant, len(result["mutants"]) + 1, status, detail))
717
+ if status == "invalid":
718
+ invalid += 1
719
+ else:
720
+ valid += 1
721
+ if invalid >= cap:
722
+ result["notes"].append(f"invalid-cap: stopped after {invalid} invalid mutants")
723
+ summarize(result, opts)
724
+ finally:
725
+ try:
726
+ remove_tree(run_dir)
727
+ except OSError as exc:
728
+ result["violations"].append(f"cleanup-failed: {exc}")
729
+
730
+
731
+ def verify(root, opts, result):
732
+ base = f2p_gate.git(root, "rev-parse", "--verify", "--end-of-options", opts.base + "^{commit}").decode("ascii").strip()
733
+ result["base"] = base
734
+ if f2p_gate.git(root, "ls-files", "--unmerged", "-z"):
735
+ raise ValueError("unmerged index")
736
+ run_mutants(root, base, opts, result)
737
+
738
+
739
+ def positive_int(value):
740
+ number = int(value)
741
+ if number < 1:
742
+ raise argparse.ArgumentTypeError("must be at least 1")
743
+ return number
744
+
745
+
746
+ def unit_interval(value):
747
+ number = float(value)
748
+ if not 0 <= number <= 1:
749
+ raise argparse.ArgumentTypeError("must be between 0 and 1")
750
+ return number
751
+
752
+
753
+ def main():
754
+ parser = argparse.ArgumentParser(description=__doc__)
755
+ commands = parser.add_subparsers(dest="action", required=True)
756
+ run = commands.add_parser("run")
757
+ run.add_argument("--root", type=Path, required=True)
758
+ run.add_argument("--base", required=True)
759
+ run.add_argument("--test-cmd", help="test command argv (no shell); run in a throwaway copy of the repo")
760
+ run.add_argument("--max-mutants", type=positive_int, default=8)
761
+ run.add_argument("--timeout", type=float, default=60, help="per test run, in seconds")
762
+ run.add_argument("--seed", type=int, default=0)
763
+ run.add_argument("--min-score", type=unit_interval, default=DEFAULT_MIN_SCORE,
764
+ help="minimum killed/evaluated ratio (default %(default)g); boundary rel-swaps (< <-> <=, > <-> >=)"
765
+ " are frequently equivalent mutants, so the default tolerates some; the coordinator may raise it per task")
766
+ run.add_argument("--json", action="store_true")
767
+ opts = parser.parse_args()
768
+ for stream in (sys.stdout, sys.stderr):
769
+ stream.reconfigure(encoding="utf-8", errors="replace")
770
+ result = {"ok": False, "score": None, "killed": 0, "survived": [], "survived_boundary": [], "invalid": 0,
771
+ "timeouts": [], "mutants": [], "violations": [], "notes": []}
772
+ try:
773
+ if not math.isfinite(opts.timeout) or opts.timeout <= 0:
774
+ raise ValueError("test timeout must be positive and finite")
775
+ root = opts.root.resolve(strict=True)
776
+ top = Path(os.fsdecode(f2p_gate.git(root, "rev-parse", "--show-toplevel")).rstrip("\r\n")).resolve()
777
+ if root != top:
778
+ raise ValueError("--root must be the Git worktree root")
779
+ verify(root, opts, result)
780
+ except (OSError, ValueError, subprocess.TimeoutExpired) as exc:
781
+ message = str(exc)
782
+ result["violations"].append(message if message.startswith("test-command-error") else f"mutation-error: {message}")
783
+ result["ok"] = not result["violations"]
784
+ if opts.json:
785
+ print(json.dumps(result))
786
+ else:
787
+ for entry in result["mutants"]:
788
+ print(f"{entry['status']:8} {entry['file']}:{entry['line']}: {entry['original']} => {entry['mutated']}")
789
+ for violation in result["violations"]:
790
+ print(violation, file=sys.stderr)
791
+ if result["ok"]:
792
+ score = "n/a" if result["score"] is None else f"{result['score']:.2f}"
793
+ print(f"mutation: ok (score {score}, killed {result['killed']}, invalid {result['invalid']})")
794
+ return 0 if result["ok"] else 1
795
+
796
+
797
+ if __name__ == "__main__":
798
+ sys.exit(main())