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,547 @@
1
+ #!/usr/bin/env python3
2
+ """Qualify changed tests against BASE and check that frozen tests survive repair."""
3
+ import argparse
4
+ from collections import Counter
5
+ from contextlib import contextmanager
6
+ from hashlib import sha256
7
+ import importlib.util
8
+ import json
9
+ import math
10
+ import os
11
+ from pathlib import Path, PurePosixPath
12
+ import re
13
+ import shlex
14
+ import shutil
15
+ import signal
16
+ import stat
17
+ import subprocess
18
+ import sys
19
+ import tempfile
20
+
21
+
22
+ TEST_JS = re.compile(r"\.test\.(?:js|jsx|ts|tsx|mjs|cjs)$")
23
+ WORKER = re.compile(r"[A-Za-z0-9_][A-Za-z0-9._-]*")
24
+ DIGEST = re.compile(r"[0-9a-f]{64}")
25
+ SYNTAX_BROKEN = re.compile(
26
+ r"(?im)^\s*(?:#\s+)?(?:E\s+)?(?:(?:\w+\.)?(?:SyntaxError|IndentationError|TabError):|"
27
+ r"ERROR at (?:setup|teardown)\b)"
28
+ )
29
+ NOT_EXECUTED = re.compile(r"(?im)^\s*(?:ERROR collecting\b|(?:FAIL|#)\s+.*\[(?:build|setup) failed\])")
30
+ MISSING_EXPORT = re.compile(r"(?m)^#? ?SyntaxError: The requested module .* does not provide an export named\b.*$")
31
+ PY_EXCEPTION = re.compile(r"(?m)^(?:E\s+)?([A-Za-z_][\w.]*(?:Error|Exception)): (.*)$")
32
+ GO_ERROR = re.compile(r"(?m)^.*?\.go:\d+:\d+: (.*)$")
33
+ GO_MISSING = re.compile(r"undefined: \S+|\S+ undefined \(type .+ has no field or method \w+\)")
34
+ RUST_MISSING = {"E0425", "E0432", "E0433", "E0599"}
35
+
36
+
37
+ def git(root, *args, timeout=15):
38
+ proc = subprocess.run(["git", "-C", str(root), *args], capture_output=True, timeout=timeout)
39
+ if proc.returncode:
40
+ raise ValueError(f"git {args[0]}: {os.fsdecode(proc.stderr).strip()}")
41
+ return proc.stdout
42
+
43
+
44
+ def git_paths(data):
45
+ return {os.fsdecode(path) for path in data.split(b"\0") if path}
46
+
47
+
48
+ def path_at(root, relative):
49
+ parts = relative.split("/")
50
+ if any(part in {"", ".", ".."} or "\\" in part or ":" in part for part in parts):
51
+ raise ValueError(f"invalid repo-relative path: {relative!r}")
52
+ path = root
53
+ for part in parts:
54
+ path /= part
55
+ if getattr(os.path, "isreserved", lambda p: p.is_reserved())(path):
56
+ raise ValueError(f"reserved path: {relative!r}")
57
+ try:
58
+ info = path.lstat()
59
+ except FileNotFoundError:
60
+ continue
61
+ if stat.S_ISLNK(info.st_mode) or getattr(info, "st_file_attributes", 0) & stat.FILE_ATTRIBUTE_REPARSE_POINT:
62
+ raise ValueError(f"linked path is not allowed: {relative!r}")
63
+ if not (stat.S_ISREG(info.st_mode) or stat.S_ISDIR(info.st_mode)):
64
+ raise ValueError(f"not a regular path: {relative!r}")
65
+ return path
66
+
67
+
68
+ def scratch(path):
69
+ return os.path.normcase(path.split("/", 1)[0]) == ".scratch"
70
+
71
+
72
+ def is_test(path):
73
+ *parents, name = path.split("/")
74
+ return (not scratch(path) and (any(p in {"tests", "__tests__"} for p in parents)
75
+ or name.startswith("test_") and name.endswith(".py")
76
+ or name.endswith(("_test.py", "_test.go")) or TEST_JS.search(name) is not None))
77
+
78
+
79
+ def read_test(root, path):
80
+ file = path_at(root, path)
81
+ if not file.is_file():
82
+ raise ValueError(f"not a regular test file: {path}")
83
+ return file.read_bytes()
84
+
85
+
86
+ def frozen_path(root, worker):
87
+ if not WORKER.fullmatch(worker):
88
+ raise ValueError("invalid worker ID")
89
+ return path_at(root, f".scratch/f2p/{worker}.json")
90
+
91
+
92
+ def freeze(root, worker):
93
+ receipt = frozen_path(root, worker)
94
+ paths = git_paths(git(root, "ls-files", "-z", "--cached", "--others", "--exclude-standard"))
95
+ tests = {}
96
+ for path in sorted(filter(is_test, paths)):
97
+ if path_at(root, path).exists():
98
+ tests[path] = sha256(read_test(root, path)).hexdigest()
99
+ receipt.parent.mkdir(parents=True, exist_ok=True)
100
+ with receipt.open("x", encoding="utf-8") as handle:
101
+ json.dump(tests, handle, indent=2)
102
+ handle.write("\n")
103
+ return {"ok": True, "violations": [], "path": str(receipt), "frozen_tests": list(tests)}
104
+
105
+
106
+ def load_frozen(root, worker):
107
+ if worker is None:
108
+ return {}
109
+ try:
110
+ data = json.loads(frozen_path(root, worker).read_text(encoding="utf-8"))
111
+ except FileNotFoundError as exc:
112
+ raise ValueError(f"missing freeze receipt for {worker}") from exc
113
+ if not isinstance(data, dict) or any(not is_test(k) or not isinstance(v, str) or not DIGEST.fullmatch(v)
114
+ for k, v in data.items()):
115
+ raise ValueError(f"invalid freeze receipt for {worker}")
116
+ return data
117
+
118
+
119
+ def edited_tests(root, digests, rule):
120
+ violations = []
121
+ for path, digest in digests.items():
122
+ try:
123
+ unchanged = sha256(read_test(root, path)).hexdigest() == digest
124
+ except (OSError, ValueError):
125
+ unchanged = False
126
+ if not unchanged:
127
+ violations.append(f"{rule}: {path}")
128
+ return violations
129
+
130
+
131
+ @contextmanager
132
+ def base_worktree(root, base, workspace):
133
+ checkout = workspace / "base"
134
+ hooks = workspace / "no-hooks"
135
+ hooks.mkdir()
136
+ added = False
137
+ try:
138
+ git(root, "-c", f"core.hooksPath={hooks.as_posix()}", "worktree", "add", "--detach", str(checkout), base,
139
+ timeout=60)
140
+ added = True
141
+ yield checkout
142
+ finally:
143
+ if added or checkout.exists():
144
+ git(root, "worktree", "remove", "--force", str(checkout), timeout=30)
145
+
146
+
147
+ def runner_for(root, path):
148
+ test = PurePosixPath(path)
149
+ if test.suffix == ".py" and test.name not in {"__init__.py", "conftest.py"}:
150
+ if (any((root / p).is_file() for p in ("pytest.ini", ".pytest.ini"))
151
+ or importlib.util.find_spec("pytest") is not None):
152
+ return "pytest"
153
+ return "unittest"
154
+ if test.suffix in {".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs"}:
155
+ return "node"
156
+ if test.name.endswith("_test.go"):
157
+ return "go"
158
+ if rust_target(root, path):
159
+ return "cargo"
160
+ return None
161
+
162
+
163
+ def rust_target(root, path):
164
+ test = PurePosixPath(path)
165
+ entry = test.name == "main.rs" and test.parent.parent.name == "tests"
166
+ tests_dir = test.parent.parent if entry else test.parent
167
+ manifest = tests_dir.parent / "Cargo.toml"
168
+ if test.suffix == ".rs" and tests_dir.name == "tests" and (root / manifest).is_file():
169
+ return (test.parent.name if entry else test.stem), manifest.as_posix()
170
+ return None
171
+
172
+
173
+ def command_words(command):
174
+ lexer = shlex.shlex(command, posix=True)
175
+ lexer.whitespace_split = True
176
+ lexer.commenters = ""
177
+ if os.name == "nt":
178
+ lexer.escape = ""
179
+ words = list(lexer)
180
+ if not words:
181
+ raise ValueError("empty test command")
182
+ return words
183
+
184
+
185
+ def command_for(root, path, data, override):
186
+ file = "./" + path
187
+ python = [sys.executable, "-B", "-m"]
188
+ defaults = {"pytest": [*python, "pytest"], "unittest": [*python, "unittest"],
189
+ "node": ["node", "--test"], "go": ["go", "test"], "cargo": ["cargo", "test"]}
190
+ runner = runner_for(root, path)
191
+ if override is None:
192
+ if runner is None:
193
+ return None
194
+ argv = defaults[runner]
195
+ else:
196
+ argv = override.copy()
197
+ exe = Path(argv[0]).stem.lower()
198
+ if exe in {"uv", "poetry"} and argv[1:2] == ["run"] and len(argv) > 2:
199
+ exe = Path(argv[2]).stem.lower()
200
+ if re.fullmatch(r"(?:python(?:\d+(?:\.\d+)?)?|py)", exe) and "-m" in argv:
201
+ module = argv.index("-m") + 1
202
+ exe = argv[module] if module < len(argv) else ""
203
+ selectors = sum(arg == "{files}" for arg in argv)
204
+ if selectors:
205
+ if selectors != 1:
206
+ raise ValueError("use {files} once as a separate argument")
207
+ argv[argv.index("{files}")] = file
208
+ if runner is None:
209
+ return None
210
+ if exe not in defaults:
211
+ if selectors:
212
+ return "auto", argv, set()
213
+ raise ValueError("a test wrapper must take {files} as a separate argument")
214
+ runner = exe
215
+ expected = set()
216
+ if runner == "pytest":
217
+ split = argv.index("--") if "--" in argv else len(argv)
218
+ argv[split:split] = ["-vv", "--color=no", "-o", "console_output_style=classic"]
219
+ if file not in argv:
220
+ argv.append(file)
221
+ elif runner == "unittest":
222
+ if file not in argv:
223
+ if "discover" in argv:
224
+ discovery = argv.index("discover")
225
+ options = argparse.ArgumentParser(add_help=False, exit_on_error=False)
226
+ options.add_argument("-s", "--start-directory")
227
+ options.add_argument("-p", "--pattern")
228
+ _, argv[discovery + 1:] = options.parse_known_args(argv[discovery + 1:])
229
+ else:
230
+ argv.append("discover")
231
+ file_path = PurePosixPath(path)
232
+ argv += ["-s", "./" + file_path.parent.as_posix(), "--pattern=" + file_path.name]
233
+ argv.append("-v")
234
+ elif runner == "node":
235
+ if "--test" not in argv:
236
+ raise ValueError("node command must use --test")
237
+ argv.insert(argv.index("--test") + 1, "--test-reporter=tap")
238
+ if file not in argv:
239
+ argv.append(file)
240
+ elif runner == "go":
241
+ if not path.endswith("_test.go") or file in argv:
242
+ raise ValueError("Go tests must run as a package, not as a file argument")
243
+ expected = set(re.findall(r"(?m)^\s*func\s+((?:Test|Example|Fuzz)\w*)\s*\(", data.decode("utf-8")))
244
+ if not expected:
245
+ raise ValueError("no Go test functions found in " + path)
246
+ package = PurePosixPath(path).parent.as_posix()
247
+ argv = [arg for arg in argv if arg != "./..."]
248
+ argv += ["-json", "-count=1", "-run", "^(" + "|".join(map(re.escape, sorted(expected))) + ")$",
249
+ "." if package == "." else "./" + package]
250
+ elif runner == "cargo":
251
+ target = rust_target(root, path)
252
+ if target is None or file in argv:
253
+ raise ValueError("Cargo tests must run as an integration target, not as a file argument")
254
+ name, manifest = target
255
+ split = argv.index("--") if "--" in argv else len(argv)
256
+ argv[split:split] = ["--manifest-path", manifest, "--test", name, "--color", "never"]
257
+ return runner, argv, expected
258
+
259
+
260
+ def run_test(argv, root, workspace, timeout, target):
261
+ env = dict(os.environ, TMPDIR=str(workspace), TMP=str(workspace), TEMP=str(workspace),
262
+ PYTHONDONTWRITEBYTECODE="1", PYTHONIOENCODING="utf-8", NO_COLOR="1",
263
+ CARGO_TARGET_DIR=str(target))
264
+ cmd = argv
265
+ if os.name == "nt":
266
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "loop"))
267
+ try:
268
+ from windows_job import wrap_command
269
+ finally:
270
+ sys.path.pop(0)
271
+ executable = shutil.which(argv[0])
272
+ cmd = wrap_command([executable or argv[0], *argv[1:]])
273
+ with subprocess.Popen(cmd, cwd=root, env=env, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
274
+ stderr=subprocess.STDOUT, text=True, encoding="utf-8", errors="replace",
275
+ start_new_session=os.name != "nt",
276
+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0)) as proc:
277
+ try:
278
+ output = proc.communicate(timeout=timeout)[0]
279
+ except BaseException as exc:
280
+ if os.name == "nt":
281
+ proc.kill()
282
+ else:
283
+ try:
284
+ os.killpg(proc.pid, signal.SIGKILL)
285
+ except ProcessLookupError:
286
+ pass
287
+ if not isinstance(exc, subprocess.TimeoutExpired):
288
+ raise
289
+ return None, "test command timed out"
290
+ return proc.returncode, output
291
+
292
+
293
+ def summary_counts(output, pattern):
294
+ matches = re.findall(pattern, output, re.M)
295
+ if len(matches) != 1:
296
+ return None
297
+ return tuple(map(int, matches[0] if isinstance(matches[0], tuple) else (matches[0],)))
298
+
299
+
300
+ def executed(runner, output, file, expected):
301
+ if runner == "auto":
302
+ candidates = [cases for r in ("pytest", "unittest", "node", "cargo")
303
+ if (cases := executed(r, output, file, expected))]
304
+ return candidates[0] if len(candidates) == 1 else None
305
+ if runner == "pytest":
306
+ summary = re.findall(r"^=+\s*(.*?)\s+in\s+[\d.]+s\s*=+\s*$", output, re.M)
307
+ if len(summary) != 1 or re.search(r"\b(?:errors?|skipped|deselected|xfailed|xpassed)\b", summary[0]):
308
+ return None
309
+ counts = {status: int(count) for count, status in re.findall(r"(\d+) (passed|failed)\b", summary[0])}
310
+ rows = re.findall(r"^(\S.*?)::(.+?)\s+(PASSED|FAILED)(?:\s+\[\s*\d+%\])?\s*$", output, re.M)
311
+ if any(name.replace("\\", "/").removeprefix("./") != file for name, _, _ in rows):
312
+ return None
313
+ cases = [(name, outcome == "FAILED") for _, name, outcome in rows]
314
+ if (sum(failed for _, failed in cases), sum(not failed for _, failed in cases)) != (
315
+ counts.get("failed", 0), counts.get("passed", 0)):
316
+ return None
317
+ return cases
318
+ if runner == "unittest":
319
+ total = summary_counts(output, r"^Ran (\d+) tests? in [\d.]+s\s*$")
320
+ if not re.search(r"^(?:OK|FAILED \(failures=\d+\))\s*$", output, re.M):
321
+ return None
322
+ rows = re.findall(r"^(\S+ \(.+?\))(?:\n[^\n]+)? \.\.\. (ok|FAIL)\s*$", output, re.M)
323
+ module = PurePosixPath(file).stem
324
+ if total != (len(rows),) or any(not re.search(rf"\((?:[^ )]+\.)?{re.escape(module)}\.", name)
325
+ for name, _ in rows):
326
+ return None
327
+ return [(name, outcome == "FAIL") for name, outcome in rows]
328
+ if runner == "node":
329
+ total = summary_counts(output, r"^# tests (\d+)\s*$")
330
+ passed = summary_counts(output, r"^# pass (\d+)\s*$")
331
+ failed = summary_counts(output, r"^# fail (\d+)\s*$")
332
+ rows = re.findall(r"^([ \t]*)(ok|not ok) \d+ - (.+?)\s*$", output, re.M)
333
+ if (total != (len(rows),) or passed != (sum(ok == "ok" for _, ok, _ in rows),)
334
+ or failed != (sum(ok == "not ok" for _, ok, _ in rows),)
335
+ or any(summary_counts(output, rf"^# {state} (\d+)\s*$") != (0,)
336
+ for state in ("cancelled", "skipped", "todo"))
337
+ or failed != (len(re.findall(r"(?m)^\s*code: ['\"]ERR_ASSERTION['\"]\s*$", output)),)
338
+ or any(name.replace("\\", "/").endswith(file) for _, _, name in rows)):
339
+ return None
340
+ return [(space + name, ok == "not ok") for space, ok, name in rows]
341
+ if runner == "cargo":
342
+ counts = summary_counts(output, r"^test result: (?:ok|FAILED)\. (\d+) passed; (\d+) failed; "
343
+ r"0 ignored; \d+ measured; 0 filtered out;.*$")
344
+ rows = re.findall(r"^test (.+) \.\.\. (ok|FAILED)\s*$", output, re.M)
345
+ if counts != (sum(ok == "ok" for _, ok in rows), sum(ok == "FAILED" for _, ok in rows)):
346
+ return None
347
+ return [(name, ok == "FAILED") for name, ok in rows]
348
+ events = [json.loads(line) for line in output.splitlines() if line.startswith("{")]
349
+ if any(not isinstance(event, dict) or event.get("Action") in {"build-fail", "skip"} or event.get("FailedBuild")
350
+ for event in events):
351
+ return None
352
+ packages = {event.get("Package") for event in events if event.get("Test")}
353
+ cases = [(event["Test"], event["Action"] == "fail") for event in events
354
+ if event.get("Test") and event.get("Action") in {"pass", "fail"}]
355
+ if len(packages) != 1 or {name for name, _ in cases if "/" not in name} != expected:
356
+ return None
357
+ return cases
358
+
359
+
360
+ def python_missing(output):
361
+ found = False
362
+ for name, message in PY_EXCEPTION.findall(output):
363
+ kind = name.rsplit(".", 1)[-1]
364
+ if kind == "AssertionError" or message.startswith("Failed to import test module"):
365
+ continue
366
+ if (kind == "AttributeError" or (kind == "ImportError" and message.startswith("cannot import name"))
367
+ or (kind == "ModuleNotFoundError" and message.startswith("No module named"))):
368
+ found = True
369
+ else:
370
+ return False
371
+ return found
372
+
373
+
374
+ def pytest_missing(code, output):
375
+ return (code == 2 and python_missing(output)
376
+ and re.search(r"(?m)^!+ Interrupted: \d+ errors? during collection !+$", output) is not None
377
+ and re.search(r"(?m)^_+ ERROR collecting \S+ _+$", output) is not None
378
+ and re.search(r"(?m)^\S+::\S.* (?:PASSED|FAILED)\b", output) is None)
379
+
380
+
381
+ def unittest_missing(code, output):
382
+ total = summary_counts(output, r"^Ran (\d+) tests? in [\d.]+s\s*$")
383
+ rows = re.findall(r"^(\S+ \(.+?\))(?:\n[^\n]+)? \.\.\. (\S.*?)\s*$", output, re.M)
384
+ return (code == 1 and python_missing(output) and total == (len(rows),)
385
+ and re.search(r"^FAILED \((?:failures=\d+)?(?:, )?(?:errors=\d+)?\)\s*$", output, re.M) is not None
386
+ and all(outcome in {"FAIL", "ERROR"} for _, outcome in rows))
387
+
388
+
389
+ def node_missing(code, output):
390
+ counts = {state: summary_counts(output, rf"^# {state} (\d+)\s*$")
391
+ for state in ("tests", "pass", "fail", "cancelled", "skipped", "todo")}
392
+ rows = re.findall(r"^[ \t]*(ok|not ok) \d+ - ", output, re.M)
393
+ stripped = MISSING_EXPORT.sub("", output)
394
+ errors = re.findall(r"(?m)^# (?:\w+\.)*\w*(?:Error|Exception)\b.*$", stripped)
395
+ codes = set(re.findall(r"(?m)^\s*code: ['\"](\w+)['\"]\s*$", output))
396
+ return (code == 1 and None not in counts.values() and counts["tests"] == counts["fail"] == (len(rows),)
397
+ and all(counts[state] == (0,) for state in ("pass", "cancelled", "skipped", "todo"))
398
+ and "ok" not in rows and codes <= {"ERR_TEST_FAILURE", "ERR_ASSERTION", "ERR_MODULE_NOT_FOUND"}
399
+ and all("[ERR_MODULE_NOT_FOUND]" in line for line in errors)
400
+ and (MISSING_EXPORT.search(output) is not None or "ERR_MODULE_NOT_FOUND" in codes or bool(errors)))
401
+
402
+
403
+ def go_missing(code, output):
404
+ errors = GO_ERROR.findall(output)
405
+ other = [line for line in output.splitlines()
406
+ if line.strip() and not line.startswith(("#", "{", "FAIL\t")) and GO_ERROR.fullmatch(line) is None
407
+ and line.strip() != "too many errors"]
408
+ return (code == 1 and bool(errors) and not other and "[build failed]" in output
409
+ and all(GO_MISSING.fullmatch(message) for message in errors))
410
+
411
+
412
+ def cargo_missing(code, output):
413
+ codes = re.findall(r"(?m)^error\[(E\d+)\]", output)
414
+ plain = re.findall(r"(?m)^error(?!\[)", output)
415
+ allowed = re.findall(r"(?m)^error: (?:could not compile\b|aborting due to\b)", output)
416
+ return (code == 101 and bool(codes) and set(codes) <= RUST_MISSING and len(plain) == len(allowed)
417
+ and re.search(r"(?m)^test result:", output) is None)
418
+
419
+
420
+ def missing_symbol_failure(runner, code, output):
421
+ if runner == "auto":
422
+ return sum(missing_symbol_failure(r, code, output) for r in ("pytest", "unittest", "node", "cargo")) == 1
423
+ return {"pytest": pytest_missing, "unittest": unittest_missing, "node": node_missing, "go": go_missing,
424
+ "cargo": cargo_missing}[runner](code, output)
425
+
426
+
427
+ def run_phase(root, workspace, commands, timeout, red, result, target):
428
+ result["exit_code"] = 0
429
+ result["runs"] = []
430
+ case_ids = {}
431
+ for path, (runner, argv, expected) in commands.items():
432
+ code, output = run_test(argv, root, workspace, timeout, target)
433
+ result["exit_code"] = code
434
+ evidence = {"file": path, "exit_code": code, "output": output[-5000:]}
435
+ result["runs"].append(evidence)
436
+ intact = code is not None and SYNTAX_BROKEN.search(MISSING_EXPORT.sub("", output)) is None
437
+ cases = executed(runner, output, path, expected) if intact and not NOT_EXECUTED.search(output) else None
438
+ if cases:
439
+ evidence["executed"] = len(cases)
440
+ evidence["failed"] = sum(failed for _, failed in cases)
441
+ allowed = {0} if not red else {101} if runner == "cargo" else {1, 101} if runner == "auto" else {1}
442
+ if cases and code in allowed and all(failed == red for _, failed in cases):
443
+ case_ids[path] = Counter(name for name, _ in cases)
444
+ if red:
445
+ evidence["cause"] = "missing-symbol" if python_missing(output) else "assertion"
446
+ elif red and intact and not cases and missing_symbol_failure(runner, code, output):
447
+ case_ids[path] = None
448
+ evidence["cause"] = "missing-symbol"
449
+ else:
450
+ return None, path
451
+ if red:
452
+ result["cause"] = ("missing-symbol" if any(run["cause"] == "missing-symbol" for run in result["runs"])
453
+ else "assertion")
454
+ return case_ids, None
455
+
456
+
457
+ def verify(root, opts, result):
458
+ violations = result["violations"]
459
+ frozen = load_frozen(root, opts.worker)
460
+ violations.extend(edited_tests(root, frozen, "frozen-test-edited"))
461
+ if violations:
462
+ return
463
+ base = git(root, "rev-parse", "--verify", "--end-of-options", opts.base + "^{commit}").decode("ascii").strip()
464
+ if git(root, "ls-files", "--unmerged", "-z"):
465
+ raise ValueError("unmerged index")
466
+ diff = ("diff", "--no-ext-diff", "--no-renames", "--name-only", "-z", base, "--")
467
+ changed = git_paths(git(root, *diff)) | git_paths(git(root, "ls-files", "--others", "--exclude-standard", "-z"))
468
+ tests = {p: read_test(root, p) for p in sorted(filter(is_test, changed)) if path_at(root, p).exists()}
469
+ result["new_tests"] = list(tests)
470
+ if not tests:
471
+ if any(not scratch(p) and not is_test(p) and PurePosixPath(p).suffix.lower() not in {".md", ".rst", ".adoc"}
472
+ for p in changed):
473
+ violations.append("no-new-tests: non-test changes have no added or modified tests")
474
+ return
475
+ override = command_words(opts.test_cmd) if opts.test_cmd is not None else None
476
+ commands = {p: cmd for p, data in tests.items() if (cmd := command_for(root, p, data, override)) is not None}
477
+ if not commands:
478
+ violations.append("no-new-tests: no runnable changed test files")
479
+ return
480
+ tmp = path_at(root, ".scratch/tmp")
481
+ tmp.mkdir(parents=True, exist_ok=True)
482
+ with tempfile.TemporaryDirectory(prefix="f2p-", dir=tmp) as directory:
483
+ workspace = Path(directory)
484
+ with base_worktree(root, base, workspace) as checkout:
485
+ for path, data in tests.items():
486
+ dest = path_at(checkout, path)
487
+ dest.parent.mkdir(parents=True, exist_ok=True)
488
+ dest.write_bytes(data)
489
+ result["base_result"] = {}
490
+ red_cases, failed = run_phase(checkout, workspace, commands, opts.timeout, True, result["base_result"],
491
+ checkout / ".f2p-cargo-target")
492
+ if failed:
493
+ violations.append(f"base-not-clean-failure: {failed}")
494
+ else:
495
+ result["head_result"] = {}
496
+ green_cases, failed = run_phase(root, workspace, commands, opts.timeout, False, result["head_result"],
497
+ workspace / "head-cargo-target")
498
+ if failed:
499
+ violations.append(f"head-not-pass: {failed}")
500
+ elif any(red is not None and red != green_cases[path] for path, red in red_cases.items()):
501
+ violations.append("test-selection-changed: BASE and HEAD executed different test cases")
502
+ violations.extend(edited_tests(root, frozen, "frozen-test-edited"))
503
+ violations.extend(edited_tests(root, {p: sha256(data).hexdigest() for p, data in tests.items() if p not in frozen},
504
+ "test-edited-during-verify"))
505
+
506
+
507
+ def main():
508
+ parser = argparse.ArgumentParser(description=__doc__)
509
+ commands = parser.add_subparsers(dest="action", required=True)
510
+ check = commands.add_parser("verify")
511
+ check.add_argument("--base", required=True)
512
+ check.add_argument("--test-cmd", help="test runner argv with an optional {files} argument (no shell)")
513
+ check.add_argument("--worker")
514
+ check.add_argument("--timeout", type=float, default=60, help="test-command timeout in seconds")
515
+ lock = commands.add_parser("freeze")
516
+ lock.add_argument("--worker", required=True)
517
+ for command in (check, lock):
518
+ command.add_argument("--root", type=Path, required=True)
519
+ command.add_argument("--json", action="store_true")
520
+ opts = parser.parse_args()
521
+ result = {"ok": False, "violations": [], "new_tests": [], "base_result": None, "head_result": None}
522
+ try:
523
+ root = opts.root.resolve(strict=True)
524
+ top = Path(os.fsdecode(git(root, "rev-parse", "--show-toplevel")).rstrip("\r\n")).resolve()
525
+ if root != top:
526
+ raise ValueError("--root must be the Git worktree root")
527
+ if opts.action == "freeze":
528
+ result = freeze(root, opts.worker)
529
+ else:
530
+ if not math.isfinite(opts.timeout) or opts.timeout <= 0:
531
+ raise ValueError("test timeout must be positive and finite")
532
+ verify(root, opts, result)
533
+ except (OSError, ValueError, subprocess.TimeoutExpired) as exc:
534
+ result["violations"].append(f"f2p-error: {exc}")
535
+ result["ok"] = not result["violations"]
536
+ if opts.json:
537
+ print(json.dumps(result))
538
+ elif result["ok"]:
539
+ print("f2p: " + ("frozen " + result["path"] if opts.action == "freeze" else "ok"))
540
+ else:
541
+ for violation in result["violations"]:
542
+ print(violation, file=sys.stderr)
543
+ return 0 if result["ok"] else 1
544
+
545
+
546
+ if __name__ == "__main__":
547
+ sys.exit(main())
@@ -408,22 +408,16 @@ def _check_cross_lang_gate_parity(root: Path) -> list[dict]:
408
408
  reward_py = root / "plugins" / "deepmodebot" / "skills" / "deepmodebot" / "assets" / "reward-guard" / "reward_guard.py"
409
409
  reward_rs = root / "native" / "dmb-gate" / "src" / "reward.rs"
410
410
  if reward_py.is_file() and reward_rs.is_file():
411
- expected_reward_rules = {
412
- "reward-hack-threshold-zero",
413
- "reward-hack-assertion-weakened",
414
- "reward-hack-test-skip",
415
- "reward-hack-primitive-standin",
416
- "reward-hack-hardcoded-pass",
417
- "reward-hack-contract-tampered",
418
- }
419
- rs_reward_rules = set(re.findall(r'rule:\s*"([a-z0-9-]+)"', reward_rs.read_text(encoding="utf-8", errors="replace")))
420
- for missing in sorted(expected_reward_rules - rs_reward_rules):
411
+ py_txt = reward_py.read_text(encoding="utf-8", errors="replace")
412
+ expected_reward_rules = set(re.findall(r'"rule":\s*"(reward-hack-[a-z0-9-]+)"', py_txt))
413
+ rs_reward_rules = set(re.findall(r'rule:\s*"(reward-hack-[a-z0-9-]+)"', reward_rs.read_text(encoding="utf-8", errors="replace")))
414
+ for drift in sorted(expected_reward_rules ^ rs_reward_rules):
421
415
  findings.append({
422
416
  "severity": "P1",
423
417
  "rule": "cross-lang-gate-drift",
424
418
  "file": "native/dmb-gate/src/reward.rs",
425
419
  "line": 1,
426
- "message": f"Reward-guard rule `{missing}` in reward_guard.py is missing from native/dmb-gate/src/reward.rs.",
420
+ "message": f"Reward-guard rule `{drift}` differs between reward_guard.py and native/dmb-gate/src/reward.rs.",
427
421
  "fix": "Keep reward_guard.py and native/dmb-gate/src/reward.rs rule sets identical.",
428
422
  })
429
423
 
@@ -42,10 +42,10 @@ git( +(-[cC]|--git-dir|--work-tree|--namespace) +("[^"]*"|'[^']*'|[^ "'-])("[^"]
42
42
 
43
43
  # Bypasses verification hooks, zeroes quality thresholds, or tampers with reward-guard ledgers
44
44
  git( +(-[cC]|--git-dir|--work-tree|--namespace) +("[^"]*"|'[^']*'|[^ "'-])("[^"]*"|'[^']*'|[^ "'])*| +-("[^"]*"|'[^']*'|[^ "';&|])+)* +commit( +[^ ;&|]+)* +(-n|--no-verify)( |;|&|\||\)|$)
45
- (^|[ ;&|(])--(gate-)?min-(iou|ssim|psnr|clip|clip-score|dice|f1|score|fidelity|similarity|coverage|accuracy|protrusion)( +|=)["']?(-[0-9]+(\.[0-9]+)?|0+(\.0+)?|[0-9]+(\.[0-9]+)?[eE]-[6-9][0-9]*)["']?( |;|&|\||\)|$)
46
- (^|[ ;&|(])--(skip-reference|skip-fidelity|skip-gates?|bypass-gate)( |;|&|\||\)|$)
47
- (^|[ ;&|(])(--require-spark-receipt( +|=)["']?false|--gate-mode( +|=)["']?off)["']?( |;|&|\||\)|$)
48
- (sqlite3( +[^ ;&|]+)* +[^ ;&|]*reward-guard\.db|(rm|del|unlink)( +[^ ;&|]+)* +[^ ;&|]*(contract-lock\.json|reward-guard\.db)|reward_guard\.py( +[^ ;&|]+)* +record-judge)( |;|&|\||\)|$)
45
+ (^|[ ;&|(])["']?--(skip-reference|skip-fidelity|skip-gates?|skip-verify|skip-validation|bypass-gate|pass-if-no-tests|passWithNoTests|no-cov|(update-snapshots|snapshot-update|overwrite-snapshots|updateSnapshot)(=[^ ;&|)'"]+)?)["']?( |;|&|\||\)|$)
46
+ (^|[ ;&|(])["']?(--require-spark-receipt( +|=)["']?false|--gate-mode( +|=)["']?off|--measured-gates( +|=)["']?off|--check-360( +|=)["']?(false|0))["']?( |;|&|\||\)|$)
47
+ (^|[ ;&|(])((jest|vitest|playwright +test)( +[^ ;&|]+)* +["']?(-u|--update)["']?|cargo( +[^ ;&|]+)* +insta +accept|(UPDATE_SNAPSHOTS|SNAPSHOT_UPDATE|INSTA_UPDATE)=["']?(1|true|always|all)["']?|go +test( +[^ ;&|]+)* +-run(=| +)["']?\^\$["']?)( |;|&|\||\)|$)
48
+ (reward-guard\.db|contract-lock\.json|judge_verdicts|reward_guard\.py +[^;&|]*record-judge)
49
49
 
50
50
  # Strict mode: remove the # below to block every push, so only the human pushes.
51
51
  # git( +(-[cC]|--git-dir|--work-tree|--namespace) +("[^"]*"|'[^']*'|[^ "'-])("[^"]*"|'[^']*'|[^ "'])*| +-("[^"]*"|'[^']*'|[^ "';&|])+)* +push( |;|&|\||\)|$)