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.
- package/.agents/plugins/marketplace.json +1 -1
- package/.claude-plugin/marketplace.json +2 -2
- package/.omp-plugin/marketplace.json +2 -2
- package/README.md +15 -6
- package/bin/deepmodebot.mjs +104 -10
- package/native/dmb-gate/Cargo.toml +1 -1
- package/native/dmb-gate/src/agents.rs +58 -25
- package/native/dmb-gate/src/ci.rs +530 -14
- package/native/dmb-gate/src/main.rs +215 -7
- package/native/dmb-gate/src/reward.rs +1895 -242
- package/native/dmb-gate/src/sim.rs +969 -0
- package/native/dmb-gate/src/slop.rs +1061 -295
- package/package.json +1 -1
- package/plugins/deepmodebot/.antigravity-plugin/plugin.json +1 -1
- package/plugins/deepmodebot/.antigravity-plugin/skills/deep/SKILL.md +1 -1
- package/plugins/deepmodebot/.claude-plugin/plugin.json +1 -1
- package/plugins/deepmodebot/.codex-plugin/plugin.json +2 -2
- package/plugins/deepmodebot/agents/comment-sicko.md +29 -0
- package/plugins/deepmodebot/agents/researcher.md +29 -0
- package/plugins/deepmodebot/agents/reviewer.md +29 -0
- package/plugins/deepmodebot/agents/scout.md +28 -0
- package/plugins/deepmodebot/agents/security-reviewer.md +27 -0
- package/plugins/deepmodebot/commands/deep.md +3 -2
- package/plugins/deepmodebot/commands/tournament.md +1 -1
- package/plugins/deepmodebot/hooks/hooks.json +12 -2
- package/plugins/deepmodebot/hooks.json +1 -1
- package/plugins/deepmodebot/scripts/antigravity-guard.mjs +740 -37
- package/plugins/deepmodebot/skills/agent-harnesses/references/antigravity.md +2 -2
- package/plugins/deepmodebot/skills/deepmodebot/SKILL.md +19 -11
- package/plugins/deepmodebot/skills/deepmodebot/assets/agents-md/agents_md.py +51 -20
- package/plugins/deepmodebot/skills/deepmodebot/assets/autoroute/autoroute.py +54 -49
- package/plugins/deepmodebot/skills/deepmodebot/assets/contain/claude-guard.sh +4 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/contain/claude_guard.py +658 -21
- package/plugins/deepmodebot/skills/deepmodebot/assets/contain/holdout_guard_cases.json +272 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/contain/omp-contain.ts +774 -23
- package/plugins/deepmodebot/skills/deepmodebot/assets/f2p-gate/f2p_gate.py +547 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/gap-audit/gap_audit.py +5 -11
- package/plugins/deepmodebot/skills/deepmodebot/assets/git-guardrails/git-guard-patterns.txt +4 -4
- package/plugins/deepmodebot/skills/deepmodebot/assets/git-guardrails/git-guard.sh +53 -6
- package/plugins/deepmodebot/skills/deepmodebot/assets/git-guardrails/git-guard.ts +48 -2
- package/plugins/deepmodebot/skills/deepmodebot/assets/local-ci/local_ci.py +262 -6
- package/plugins/deepmodebot/skills/deepmodebot/assets/local-ci/slop_gate.py +529 -122
- package/plugins/deepmodebot/skills/deepmodebot/assets/loop/loop.py +747 -46
- package/plugins/deepmodebot/skills/deepmodebot/assets/memory/project_memory.py +404 -5
- package/plugins/deepmodebot/skills/deepmodebot/assets/mutation/mutation_gate.py +798 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/reward-guard/reward_guard.py +2050 -200
- package/plugins/deepmodebot/skills/deepmodebot/assets/rules/rule-paths.json +44 -1
- package/plugins/deepmodebot/skills/deepmodebot/assets/rules/rule_ledger.py +278 -252
- package/plugins/deepmodebot/skills/deepmodebot/assets/rules/rules_watch.py +436 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/self-grill/self_grill.py +594 -18
- package/plugins/deepmodebot/skills/deepmodebot/assets/setup/project_setup.py +41 -5
- package/plugins/deepmodebot/skills/deepmodebot/assets/sim/sim.py +856 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/worker-gate/worker_gate.py +237 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/catalog.md +3 -2
- package/plugins/deepmodebot/skills/deepmodebot/references/delegation.md +6 -2
- package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/authoring-a-skill.md +1 -1
- package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/hillclimb.md +1 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/self-authoring.md +1 -1
- package/plugins/deepmodebot/skills/deepmodebot/references/principles/no-reward-hacking.md +6 -6
- package/plugins/deepmodebot/skills/deepmodebot/references/rule-approval.md +36 -16
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/autoroute.md +9 -8
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/correct.md +1 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/inner-loop.md +6 -2
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/mutation-testing.md +31 -9
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/no-comments.md +1 -1
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/panel.md +4 -4
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/sim.md +41 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/tdd.md +12 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/tournament.md +24 -13
- package/plugins/deepmodebot/skills/deepmodebot/worker.md +28 -16
- package/plugins/deepmodebot/agents/comment-sicko/agent.md +0 -35
- package/plugins/deepmodebot/agents/researcher/agent.md +0 -33
- package/plugins/deepmodebot/agents/reviewer/agent.md +0 -35
- package/plugins/deepmodebot/agents/scout/agent.md +0 -33
- package/plugins/deepmodebot/agents/security-reviewer/agent.md +0 -31
|
@@ -9,6 +9,7 @@ Runs deterministically on changed files/lines only (0 LLM tokens, <1s typical):
|
|
|
9
9
|
- AST-checks changed Python tests for 0-assertion/tautological test theater and new functions for god-function bloat.
|
|
10
10
|
- Auto-dispatches installed fast linters (ruff, shellcheck, node --check, oxlint, biome) on changed files only.
|
|
11
11
|
- Enforces .deepmodebot/policy.xml <boundaries> (import layer rules) and <budgets> (file byte/line ceilings).
|
|
12
|
+
- Enforces Self-Improvement Memory (assets/sim/sim.py): harness edits need a new recorded SIM attempt.
|
|
12
13
|
"""
|
|
13
14
|
|
|
14
15
|
from __future__ import annotations
|
|
@@ -100,6 +101,16 @@ JS_IMPORT_RE = re.compile(r"""(?:import\s+(?:[^'"]+?\s+from\s+)?|require\s*\(\s*
|
|
|
100
101
|
CODE_EXTS = frozenset({".py", ".js", ".mjs", ".cjs", ".ts", ".tsx", ".jsx", ".rs", ".go", ".sh", ".css", ".html", ".svelte"})
|
|
101
102
|
UI_EXTS = frozenset({".html", ".htm", ".css", ".scss", ".jsx", ".tsx", ".vue", ".svelte"})
|
|
102
103
|
TEST_FILE_RE = re.compile(r"(?:^|/)(?:tests?/|spec/|__tests__/)|(?:^|/)(?:test_[^/]+|[^/]+(?:_test|\.test|\.spec))\.[^/]+$", re.I)
|
|
104
|
+
JS_EXTS = {".js", ".mjs", ".cjs", ".jsx", ".ts", ".tsx"}
|
|
105
|
+
PROD_EXTS = JS_EXTS | {".py", ".rs", ".go"}
|
|
106
|
+
BRACE_EXTS = JS_EXTS | {".rs", ".go"}
|
|
107
|
+
DIFF_EXEMPT_DIRS = {".deepmodebot", "scripts", "docs", "evals"}
|
|
108
|
+
BRANCH_BASES = ("origin/HEAD", "origin/main", "origin/master", "main", "master")
|
|
109
|
+
TS_DIAGNOSTIC_RE = re.compile(r"^(.+)\((\d+),\d+\): error TS\d+: (.+)$")
|
|
110
|
+
BRACE_TOKEN_RE = re.compile(
|
|
111
|
+
r"""(?P<comment>//[^\n]*|/\*[\s\S]*?(?:\*/|\Z))|(?P<literal>r(?P<hash>#+)"[\s\S]*?"(?P=hash)|"(?:\\[\s\S]|[^"\\])*"|'(?:\\[^\n]|[^'\\\n])*'|`(?:\\[\s\S]|[^`\\])*`)|[\w$]+|=>|->|::|[^\s]"""
|
|
112
|
+
)
|
|
113
|
+
_BLOCK_COMMENT_DELIMITER = re.compile(r"/\*|\*/")
|
|
103
114
|
GUARDRAIL_EXTRA = (".deepmodebot/ci.yml", ".deepmodebot/policy.xml", ".github/dependabot.yml")
|
|
104
115
|
|
|
105
116
|
|
|
@@ -114,10 +125,17 @@ def _load_mod(name: str, path: Path):
|
|
|
114
125
|
|
|
115
126
|
|
|
116
127
|
def _git(root: Path, *args: str) -> subprocess.CompletedProcess:
|
|
117
|
-
|
|
128
|
+
p = subprocess.run(
|
|
118
129
|
["git", "-C", str(root), *args],
|
|
119
|
-
capture_output=True,
|
|
120
|
-
timeout=30,
|
|
130
|
+
capture_output=True,
|
|
131
|
+
timeout=30,
|
|
132
|
+
creationflags=NO_WINDOW,
|
|
133
|
+
)
|
|
134
|
+
return subprocess.CompletedProcess(
|
|
135
|
+
p.args,
|
|
136
|
+
p.returncode,
|
|
137
|
+
p.stdout.decode("utf-8", errors="replace"),
|
|
138
|
+
p.stderr.decode("utf-8", errors="replace"),
|
|
121
139
|
)
|
|
122
140
|
|
|
123
141
|
|
|
@@ -128,66 +146,82 @@ def _norm_rel_arg(raw: str) -> str:
|
|
|
128
146
|
return s.lstrip("/")
|
|
129
147
|
|
|
130
148
|
|
|
131
|
-
def
|
|
149
|
+
def _merge_base(root: Path, ref: str) -> str | None:
|
|
150
|
+
result = _git(root, "merge-base", "HEAD", ref) if not ref.startswith("-") else None
|
|
151
|
+
return result.stdout.strip() if result is not None and result.returncode == 0 else None
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _change_scope(
|
|
155
|
+
root: Path, staged: bool, explicit_files: list[str] | None, base: str | None
|
|
156
|
+
) -> tuple[list[str], str | None]:
|
|
157
|
+
rev = _git(root, "rev-parse", "--verify", "HEAD")
|
|
158
|
+
head = rev.stdout.strip() if rev.returncode == 0 else None
|
|
132
159
|
if explicit_files:
|
|
133
|
-
return sorted({_norm_rel_arg(f) for f in explicit_files if _norm_rel_arg(f)})
|
|
134
|
-
|
|
135
|
-
|
|
160
|
+
return sorted({_norm_rel_arg(f) for f in explicit_files if _norm_rel_arg(f)}), head
|
|
161
|
+
|
|
162
|
+
def paths(*args: str) -> set[str]:
|
|
163
|
+
result = _git(root, *args)
|
|
164
|
+
return set(result.stdout.split("\0")) - {""} if result.returncode == 0 else set()
|
|
165
|
+
|
|
136
166
|
if staged:
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
167
|
+
return sorted(paths("diff", "--cached", "--name-only", "-z", "--diff-filter=ACMR")), head
|
|
168
|
+
|
|
169
|
+
diff = ["diff", "--name-only", "-z"]
|
|
170
|
+
untracked = paths("ls-files", "--others", "--exclude-standard", "-z")
|
|
171
|
+
if base is not None:
|
|
172
|
+
baseline = _merge_base(root, base)
|
|
173
|
+
if baseline is None:
|
|
174
|
+
raise ValueError(f"cannot resolve a merge base for {base!r}")
|
|
175
|
+
elif head and not untracked and not paths(*diff, head):
|
|
176
|
+
baseline = next((mb for ref in BRANCH_BASES if (mb := _merge_base(root, ref)) and mb != head), head)
|
|
140
177
|
else:
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
178
|
+
baseline = head
|
|
179
|
+
changed = paths(*diff, baseline or "--cached", "--diff-filter=ACMR") | untracked
|
|
180
|
+
if baseline != head:
|
|
181
|
+
changed |= paths(*diff, f"{baseline}..HEAD", "--diff-filter=ACMR")
|
|
182
|
+
return sorted(changed), baseline
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def _split_lf_lines(text: str) -> list[str]:
|
|
186
|
+
if not text:
|
|
187
|
+
return []
|
|
188
|
+
parts = text.split("\n")
|
|
189
|
+
if parts and parts[-1] == "":
|
|
190
|
+
parts.pop()
|
|
191
|
+
return [p[:-1] if p.endswith("\r") else p for p in parts]
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _added_lines_for_file(root: Path, rel: str, staged: bool, baseline: str | None, text: str) -> dict[int, str]:
|
|
156
195
|
full = root / rel
|
|
157
196
|
if not full.is_file() or full.is_symlink():
|
|
158
197
|
return {}
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
tracked = _git(root, "ls-files", "--error-unmatch", "--", rel).returncode == 0
|
|
163
|
-
if not tracked and not staged:
|
|
164
|
-
return {i: l for i, l in enumerate(full.read_text(encoding="utf-8", errors="replace").splitlines(), 1)}
|
|
165
|
-
cmd = ["diff", "--cached", "-U0", "--", rel] if staged else ["diff", "HEAD", "-U0", "--", rel]
|
|
198
|
+
if not staged and (not baseline or _git(root, "ls-files", "--error-unmatch", "--", rel).returncode != 0):
|
|
199
|
+
return dict(enumerate(_split_lf_lines(text), 1))
|
|
200
|
+
cmd = ["diff", "--cached", "-U0", "--", rel] if staged else ["diff", baseline, "-U0", "--", rel]
|
|
166
201
|
diff = _git(root, *cmd)
|
|
167
202
|
if diff.returncode != 0:
|
|
168
203
|
return {}
|
|
169
204
|
added: dict[int, str] = {}
|
|
170
205
|
cur_line = 0
|
|
171
|
-
for raw in diff.stdout
|
|
206
|
+
for raw in _split_lf_lines(diff.stdout):
|
|
172
207
|
if raw.startswith("@@ "):
|
|
173
208
|
m = re.search(r"\+(\d+)", raw)
|
|
174
209
|
if m:
|
|
175
210
|
cur_line = int(m.group(1))
|
|
176
|
-
elif
|
|
211
|
+
elif cur_line and raw.startswith("+"):
|
|
177
212
|
added[cur_line] = raw[1:]
|
|
178
213
|
cur_line += 1
|
|
179
214
|
return added
|
|
180
215
|
|
|
181
|
-
|
|
182
|
-
def _read_text_safe(root: Path, rel: str) -> str | None:
|
|
216
|
+
def _read_text_safe(root: Path, rel: str, max_bytes: int = 1_048_576) -> str | None:
|
|
183
217
|
p = root / rel
|
|
184
218
|
if p.is_symlink() or not p.is_file():
|
|
185
219
|
return None
|
|
186
220
|
if not p.resolve().is_relative_to(root.resolve()):
|
|
187
221
|
return None
|
|
188
|
-
if p.stat().st_size >
|
|
222
|
+
if p.stat().st_size > max_bytes:
|
|
189
223
|
return None
|
|
190
|
-
return p.
|
|
224
|
+
return p.read_bytes().decode("utf-8", errors="replace")
|
|
191
225
|
|
|
192
226
|
|
|
193
227
|
def _max_ast_nesting(node: ast.AST, depth: int = 0) -> int:
|
|
@@ -200,7 +234,75 @@ def _max_ast_nesting(node: ast.AST, depth: int = 0) -> int:
|
|
|
200
234
|
return best
|
|
201
235
|
|
|
202
236
|
|
|
203
|
-
def
|
|
237
|
+
def _named_call(node: ast.AST, name: str) -> bool:
|
|
238
|
+
return isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == name
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _tautological_assertion(node: ast.AST) -> bool:
|
|
242
|
+
if isinstance(node, ast.Constant):
|
|
243
|
+
return node.value is True
|
|
244
|
+
if _named_call(node, "isinstance"):
|
|
245
|
+
return len(node.args) == 2 and isinstance(node.args[1], ast.Name) and node.args[1].id == "object"
|
|
246
|
+
if not isinstance(node, ast.Compare) or len(node.ops) != 1:
|
|
247
|
+
return False
|
|
248
|
+
left, op, right = node.left, node.ops[0], node.comparators[0]
|
|
249
|
+
if isinstance(op, ast.Eq):
|
|
250
|
+
return ast.dump(left) == ast.dump(right)
|
|
251
|
+
if isinstance(op, ast.LtE):
|
|
252
|
+
left, right = right, left
|
|
253
|
+
return (
|
|
254
|
+
isinstance(op, (ast.GtE, ast.LtE))
|
|
255
|
+
and _named_call(left, "len")
|
|
256
|
+
and len(left.args) == 1
|
|
257
|
+
and isinstance(right, ast.Constant)
|
|
258
|
+
and type(right.value) is int
|
|
259
|
+
and right.value == 0
|
|
260
|
+
)
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def _test_theater_finding(rel: str, line: int, reason: str) -> dict:
|
|
264
|
+
return {"severity": "P1", "rule": f"test-theater-{reason}", "file": rel, "line": line,
|
|
265
|
+
"message": {"empty": "Empty test proves nothing.", "no-assert": "Test has zero behavioral assertions.",
|
|
266
|
+
"tautology": "Test assertion always passes."}[reason],
|
|
267
|
+
"fix": "Assert an observable behavior that fails when the implementation regresses."}
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def _is_test_target(rel: str, ext: str) -> bool:
|
|
271
|
+
if ext not in PROD_EXTS:
|
|
272
|
+
return False
|
|
273
|
+
parts = rel.lower().split("/")
|
|
274
|
+
stem = parts[-1][:-len(ext)]
|
|
275
|
+
if ext == ".go":
|
|
276
|
+
return stem.endswith("_test")
|
|
277
|
+
if stem.startswith("test_") or stem.endswith(("_test", ".test", ".spec")):
|
|
278
|
+
return True
|
|
279
|
+
if ext in JS_EXTS:
|
|
280
|
+
return "__tests__" in parts[:-1]
|
|
281
|
+
return ext == ".rs" and (parts[-2:-1] == ["tests"] or stem == "main" and parts[-3:-2] == ["tests"])
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def _empty_test_finding(rel: str) -> dict:
|
|
285
|
+
return {"severity": "P1", "rule": "empty-test-file", "file": rel, "line": 1,
|
|
286
|
+
"message": "Test file contains no test definitions.",
|
|
287
|
+
"fix": "Add a behavioral test or move helpers out of the test target."}
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def _python_declares_tests(tree: ast.AST) -> bool:
|
|
291
|
+
functions = (ast.FunctionDef, ast.AsyncFunctionDef)
|
|
292
|
+
for node in ast.walk(tree):
|
|
293
|
+
if isinstance(node, functions) and node.name.startswith("test_"):
|
|
294
|
+
return True
|
|
295
|
+
if isinstance(node, ast.ClassDef):
|
|
296
|
+
if node.name.startswith("Test"):
|
|
297
|
+
return True
|
|
298
|
+
if any(isinstance(base, ast.Name) and base.id == "TestCase"
|
|
299
|
+
or isinstance(base, ast.Attribute) and base.attr == "TestCase" for base in node.bases):
|
|
300
|
+
if any(isinstance(child, functions) and child.name.startswith("test") for child in node.body):
|
|
301
|
+
return True
|
|
302
|
+
return False
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def _check_python_ast(rel: str, text: str, added_lines: dict[int, str], max_func_lines: int, max_nesting: int, *, check_empty: bool) -> list[dict]:
|
|
204
306
|
findings: list[dict] = []
|
|
205
307
|
try:
|
|
206
308
|
tree = ast.parse(text, filename=rel)
|
|
@@ -208,6 +310,9 @@ def _check_python_ast(rel: str, text: str, added_lines: dict[int, str], max_func
|
|
|
208
310
|
return [{"severity": "P0", "rule": "py-syntax", "file": rel, "line": exc.lineno or 1,
|
|
209
311
|
"message": f"SyntaxError: {exc.msg}", "fix": "Fix Python syntax before continuing."}]
|
|
210
312
|
|
|
313
|
+
if check_empty and not _python_declares_tests(tree):
|
|
314
|
+
findings.append(_empty_test_finding(rel))
|
|
315
|
+
|
|
211
316
|
is_test = bool(TEST_FILE_RE.search(rel))
|
|
212
317
|
added_set = set(added_lines.keys())
|
|
213
318
|
|
|
@@ -229,21 +334,21 @@ def _check_python_ast(rel: str, text: str, added_lines: dict[int, str], max_func
|
|
|
229
334
|
continue
|
|
230
335
|
has_oracle = False
|
|
231
336
|
for sub in ast.walk(node):
|
|
337
|
+
tautology = False
|
|
232
338
|
if isinstance(sub, ast.Assert):
|
|
233
339
|
has_oracle = True
|
|
234
|
-
|
|
235
|
-
findings.append({"severity": "P1", "rule": "test-theater-tautology", "file": rel, "line": sub.lineno,
|
|
236
|
-
"message": f"`assert True` in `{node.name}` is a tautology.",
|
|
237
|
-
"fix": "Assert a real output/state invariant that fails if the fix is reverted."})
|
|
340
|
+
tautology = _tautological_assertion(sub.test)
|
|
238
341
|
elif isinstance(sub, ast.Call):
|
|
239
342
|
fn = sub.func
|
|
240
343
|
fname = fn.attr if isinstance(fn, ast.Attribute) else (fn.id if isinstance(fn, ast.Name) else "")
|
|
241
|
-
if fname.startswith("assert") or fname in ("fail", "raises", "
|
|
344
|
+
if fname.startswith(("assert", "check_")) or fname in ("fail", "raises", "warns", "called"):
|
|
242
345
|
has_oracle = True
|
|
243
|
-
if fname == "assertEqual" and len(sub.args) >= 2
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
346
|
+
if fname == "assertEqual" and len(sub.args) >= 2:
|
|
347
|
+
tautology = ast.dump(sub.args[0]) == ast.dump(sub.args[1])
|
|
348
|
+
elif fname == "assertTrue" and sub.args:
|
|
349
|
+
tautology = _tautological_assertion(sub.args[0])
|
|
350
|
+
if tautology and sub.lineno in added_set:
|
|
351
|
+
findings.append(_test_theater_finding(rel, sub.lineno, "tautology"))
|
|
247
352
|
if not has_oracle:
|
|
248
353
|
findings.append({"severity": "P1", "rule": "test-theater-no-assert", "file": rel, "line": start,
|
|
249
354
|
"message": f"Test `{node.name}` has zero assertions.",
|
|
@@ -272,6 +377,185 @@ def _check_python_ast(rel: str, text: str, added_lines: dict[int, str], max_func
|
|
|
272
377
|
return findings
|
|
273
378
|
|
|
274
379
|
|
|
380
|
+
def _brace_tokens(text: str, ext: str) -> tuple[list[str], list[int], dict[int, int]]:
|
|
381
|
+
values: list[str] = []
|
|
382
|
+
lines: list[int] = []
|
|
383
|
+
closes: dict[int, int] = {}
|
|
384
|
+
stack: list[int] = []
|
|
385
|
+
line = 1
|
|
386
|
+
end = 0
|
|
387
|
+
pairs = {"}": "{", ")": "(", "]": "["}
|
|
388
|
+
while match := BRACE_TOKEN_RE.search(text, end):
|
|
389
|
+
line += text.count("\n", end, match.start())
|
|
390
|
+
start, end = match.span()
|
|
391
|
+
if ext == ".rs" and text.startswith("/*", start):
|
|
392
|
+
depth, end = 1, start + 2
|
|
393
|
+
while depth and (delimiter := _BLOCK_COMMENT_DELIMITER.search(text, end)) is not None:
|
|
394
|
+
end = delimiter.end()
|
|
395
|
+
depth += 1 if delimiter[0] == "/*" else -1
|
|
396
|
+
if depth:
|
|
397
|
+
end = len(text)
|
|
398
|
+
if match.group("comment") is None:
|
|
399
|
+
value = "<literal>" if match.group("literal") is not None else match[0]
|
|
400
|
+
if ext == ".go" and text[start] == "`":
|
|
401
|
+
closing = text.find("`", start + 1)
|
|
402
|
+
end = closing + 1 if closing >= 0 else len(text)
|
|
403
|
+
value = "<literal>"
|
|
404
|
+
index = len(values)
|
|
405
|
+
if value in ("{", "(", "["):
|
|
406
|
+
stack.append(index)
|
|
407
|
+
elif value in pairs and stack and values[stack[-1]] == pairs[value]:
|
|
408
|
+
closes[stack.pop()] = index
|
|
409
|
+
values.append(value)
|
|
410
|
+
lines.append(line)
|
|
411
|
+
line += text.count("\n", start, end)
|
|
412
|
+
return values, lines, closes
|
|
413
|
+
|
|
414
|
+
|
|
415
|
+
def _next_top_level(values: list[str], closes: dict[int, int], start: int, end: int, stops: set[str]) -> int:
|
|
416
|
+
while start < end and values[start] not in stops:
|
|
417
|
+
start = closes.get(start, start) + 1
|
|
418
|
+
return start
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
def _rust_test_ranges(values: list[str], lines: list[int], closes: dict[int, int]) -> list[tuple[int, int]]:
|
|
422
|
+
ranges = []
|
|
423
|
+
for i, value in enumerate(values):
|
|
424
|
+
if value != "#" or values[i:i + 7] != ["#", "[", "cfg", "(", "test", ")", "]"]:
|
|
425
|
+
continue
|
|
426
|
+
start = i + 7
|
|
427
|
+
while values[start:start + 2] == ["#", "["] and start + 1 in closes:
|
|
428
|
+
start = closes[start + 1] + 1
|
|
429
|
+
end = _next_top_level(values, closes, start, len(values), {"{", ";"})
|
|
430
|
+
if end < len(values):
|
|
431
|
+
ranges.append((lines[i], lines[closes.get(end, end)]))
|
|
432
|
+
return ranges
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
def _brace_tests(
|
|
436
|
+
ext: str, values: list[str], closes: dict[int, int]
|
|
437
|
+
):
|
|
438
|
+
opens = {end: start for start, end in closes.items()} if ext == ".rs" else {}
|
|
439
|
+
for i, value in enumerate(values):
|
|
440
|
+
tail = values[i + 1:i + 2]
|
|
441
|
+
if ext in JS_EXTS and value in ("it", "test") and tail == ["("] and i + 1 in closes:
|
|
442
|
+
end = closes[i + 1]
|
|
443
|
+
marker = _next_top_level(values, closes, i + 2, end, {"=>", "function"})
|
|
444
|
+
if marker == end:
|
|
445
|
+
continue
|
|
446
|
+
if values[marker] == "function":
|
|
447
|
+
body = _next_top_level(values, closes, marker + 1, end, {"{"})
|
|
448
|
+
else:
|
|
449
|
+
body = marker + 1
|
|
450
|
+
if body < end:
|
|
451
|
+
if values[body] == "{" and body in closes:
|
|
452
|
+
yield i, body + 1, closes[body], closes[body], False
|
|
453
|
+
else:
|
|
454
|
+
end = _next_top_level(values, closes, body, end, {","})
|
|
455
|
+
yield i, body, end, end, False
|
|
456
|
+
continue
|
|
457
|
+
if ext == ".rs" and value == "#" and tail == ["["] and i + 1 in closes:
|
|
458
|
+
end = closes[i + 1]
|
|
459
|
+
if values[i + 2:end] not in (["test"], ["tokio", "::", "test"]) and values[i + 2:i + 6] != ["tokio", "::", "test", "("]:
|
|
460
|
+
continue
|
|
461
|
+
start = end + 1
|
|
462
|
+
while values[start:start + 2] == ["#", "["] and start + 1 in closes:
|
|
463
|
+
start = closes[start + 1] + 1
|
|
464
|
+
fn = _next_top_level(values, closes, start, len(values), {"fn", "{", ";", "}"})
|
|
465
|
+
if values[fn:fn + 1] != ["fn"]:
|
|
466
|
+
continue
|
|
467
|
+
body = _next_top_level(values, closes, fn + 1, len(values), {"{", ";", "}"})
|
|
468
|
+
if values[body:body + 1] == ["{"] and body in closes:
|
|
469
|
+
prior = i
|
|
470
|
+
while prior >= 2 and values[prior - 1] == "]":
|
|
471
|
+
attr = opens.get(prior - 1, 0)
|
|
472
|
+
if attr == 0 or values[attr - 1] != "#":
|
|
473
|
+
break
|
|
474
|
+
prior = attr - 1
|
|
475
|
+
special = any(values[j:j + 3] == ["#", "[", "should_panic"] for j in range(prior, fn)) or any(
|
|
476
|
+
values[j:j + 3] == ["->", "Result", "<"] for j in range(fn + 1, body)
|
|
477
|
+
)
|
|
478
|
+
yield i, body + 1, closes[body], closes[body], special
|
|
479
|
+
continue
|
|
480
|
+
if ext == ".go" and value == "func" and tail and tail[0].startswith("Test") and values[i + 2:i + 3] == ["("]:
|
|
481
|
+
body = closes.get(i + 2, i + 2) + 1
|
|
482
|
+
if values[body:body + 1] == ["{"] and body in closes:
|
|
483
|
+
yield i, body + 1, closes[body], closes[body], False
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
def _brace_declares_tests(ext: str, values: list[str], closes: dict[int, int]) -> bool:
|
|
487
|
+
if ext not in JS_EXTS:
|
|
488
|
+
return any(True for _ in _brace_tests(ext, values, closes))
|
|
489
|
+
for i, value in enumerate(values):
|
|
490
|
+
if value not in ("test", "it") or values[i - 1:i] == ["function"]:
|
|
491
|
+
continue
|
|
492
|
+
start = i + 1
|
|
493
|
+
while values[start:start + 1] == ["."] and values[start + 1:start + 2] in (
|
|
494
|
+
["only"], ["skip"], ["todo"], ["concurrent"], ["each"],
|
|
495
|
+
):
|
|
496
|
+
start += 2
|
|
497
|
+
if values[start:start + 1] != ["("] or start not in closes:
|
|
498
|
+
continue
|
|
499
|
+
end = closes[start]
|
|
500
|
+
if end > start + 1 and values[end + 1:end + 2] != ["{"]:
|
|
501
|
+
return True
|
|
502
|
+
return False
|
|
503
|
+
|
|
504
|
+
|
|
505
|
+
def _check_staged_test_target(root: Path, rel: str, ext: str) -> list[dict]:
|
|
506
|
+
blob = _git(root, "show", f":{rel}")
|
|
507
|
+
if blob.returncode != 0 or len(blob.stdout) > 1_048_576:
|
|
508
|
+
return []
|
|
509
|
+
if ext == ".py":
|
|
510
|
+
try:
|
|
511
|
+
tree = ast.parse(blob.stdout, filename=rel)
|
|
512
|
+
except SyntaxError:
|
|
513
|
+
return []
|
|
514
|
+
found = _python_declares_tests(tree)
|
|
515
|
+
else:
|
|
516
|
+
values, _, closes = _brace_tokens(blob.stdout, ext)
|
|
517
|
+
found = _brace_declares_tests(ext, values, closes)
|
|
518
|
+
return [] if found else [_empty_test_finding(rel)]
|
|
519
|
+
|
|
520
|
+
|
|
521
|
+
def _scan_brace_tests(
|
|
522
|
+
rel: str, ext: str, values: list[str], lines: list[int], closes: dict[int, int], added: dict[int, str],
|
|
523
|
+
) -> list[dict]:
|
|
524
|
+
findings = []
|
|
525
|
+
for start, body, end, last, oracle in _brace_tests(ext, values, closes):
|
|
526
|
+
if not any(line in added for line in range(lines[start], lines[last] + 1)):
|
|
527
|
+
continue
|
|
528
|
+
if body == end:
|
|
529
|
+
findings.append(_test_theater_finding(rel, lines[start], "empty"))
|
|
530
|
+
continue
|
|
531
|
+
for i in range(body, end):
|
|
532
|
+
token = values[i]
|
|
533
|
+
following = values[i + 1:i + 2]
|
|
534
|
+
tautology = False
|
|
535
|
+
if ext in JS_EXTS:
|
|
536
|
+
oracle |= (token in {"expect", "assert", "rejects", "throws", "verify"} and following in (["("], ["."])) or (
|
|
537
|
+
token in {"rejects", "throws"} and values[i - 1:i] == ["."]
|
|
538
|
+
)
|
|
539
|
+
if token == "expect" and values[i + 2:i + 3] in (["true"], ["false"], ["1"]):
|
|
540
|
+
literal = values[i + 2]
|
|
541
|
+
tautology = values[i:i + 9] == ["expect", "(", literal, ")", ".", "toBe", "(", literal, ")"]
|
|
542
|
+
if ext == ".rs":
|
|
543
|
+
oracle |= (token.startswith(("assert", "debug_assert")) or token == "panic") and following == ["!"]
|
|
544
|
+
if token == "assert":
|
|
545
|
+
tautology = values[i + 1:i + 5] == ["!", "(", "true", ")"]
|
|
546
|
+
elif token == "assert_eq":
|
|
547
|
+
tautology = values[i + 1:i + 7] == ["!", "(", "1", ",", "1", ")"]
|
|
548
|
+
elif ext not in JS_EXTS:
|
|
549
|
+
oracle |= following == ["."] and (token in {"assert", "require"} or (
|
|
550
|
+
token == "t" and values[i + 2:i + 3] in (["Fatal"], ["Fatalf"], ["Error"], ["Errorf"], ["Fail"], ["FailNow"])
|
|
551
|
+
))
|
|
552
|
+
if tautology and lines[i] in added:
|
|
553
|
+
findings.append(_test_theater_finding(rel, lines[i], "tautology"))
|
|
554
|
+
if not oracle:
|
|
555
|
+
findings.append(_test_theater_finding(rel, lines[start], "no-assert"))
|
|
556
|
+
return findings
|
|
557
|
+
|
|
558
|
+
|
|
275
559
|
def _check_secrets_and_patterns(rel: str, added_lines: dict[int, str], full_text: str) -> list[dict]:
|
|
276
560
|
findings: list[dict] = []
|
|
277
561
|
ext = Path(rel).suffix.lower()
|
|
@@ -409,92 +693,166 @@ def _check_policy_xml(root: Path, changed: list[str]) -> list[dict]:
|
|
|
409
693
|
return findings
|
|
410
694
|
|
|
411
695
|
|
|
696
|
+
def _diagnostic_rel(root: Path, path: str | None) -> str | None:
|
|
697
|
+
if path:
|
|
698
|
+
candidate = root / path
|
|
699
|
+
try:
|
|
700
|
+
return candidate.resolve().relative_to(root).as_posix()
|
|
701
|
+
except (ValueError, OSError):
|
|
702
|
+
pass
|
|
703
|
+
return None
|
|
704
|
+
|
|
705
|
+
|
|
412
706
|
def _run_polyglot_linters(root: Path, changed: list[str]) -> tuple[list[dict], list[str]]:
|
|
413
707
|
findings: list[dict] = []
|
|
414
708
|
ran: list[str] = []
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
ran
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
cwd=
|
|
425
|
-
|
|
426
|
-
)
|
|
709
|
+
files = [f for f in changed if (root / f).is_file() and not (root / f).is_symlink()]
|
|
710
|
+
py_files = [f for f in files if f.endswith(".py")]
|
|
711
|
+
js_files = [f for f in files if Path(f).suffix.lower() in JS_EXTS]
|
|
712
|
+
sh_files = [f for f in files if f.endswith(".sh")]
|
|
713
|
+
|
|
714
|
+
def invoke(name: str, command: list[str], timeout: int = 30) -> subprocess.CompletedProcess:
|
|
715
|
+
if name not in ran:
|
|
716
|
+
ran.append(name)
|
|
717
|
+
try:
|
|
718
|
+
return subprocess.run(command, cwd=root, capture_output=True, encoding="utf-8",
|
|
719
|
+
errors="replace", timeout=timeout, creationflags=NO_WINDOW)
|
|
720
|
+
except (OSError, subprocess.TimeoutExpired) as exc:
|
|
721
|
+
return subprocess.CompletedProcess(command, 124, "", str(exc))
|
|
722
|
+
|
|
723
|
+
def failure(rule: str, file: str, result: subprocess.CompletedProcess, severity: str = "P1") -> None:
|
|
724
|
+
message = (result.stdout + "\n" + result.stderr).strip()
|
|
725
|
+
findings.append({"severity": severity, "rule": rule, "file": file, "line": 1,
|
|
726
|
+
"message": message[-1500:] or f"{rule} exited with status {result.returncode}.",
|
|
727
|
+
"fix": f"Resolve the {rule} diagnostics."})
|
|
728
|
+
|
|
729
|
+
if py_files and (ruff := shutil.which("ruff")):
|
|
730
|
+
r = invoke("ruff", [ruff, "check", "--no-cache", "--select",
|
|
731
|
+
"E9,F63,F7,F82,F401,F811,F841,B006,B007,B012,B023,S102,S307",
|
|
732
|
+
"--output-format", "json", "--", *py_files])
|
|
427
733
|
if r.returncode != 0:
|
|
428
734
|
try:
|
|
429
|
-
items = json.loads(r.stdout
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
findings.append({"severity": "P1", "rule": "ruff
|
|
438
|
-
"
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
if
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
735
|
+
items = json.loads(r.stdout)
|
|
736
|
+
except ValueError:
|
|
737
|
+
items = []
|
|
738
|
+
if not items:
|
|
739
|
+
failure("ruff", py_files[0], r)
|
|
740
|
+
for it in items[:20]:
|
|
741
|
+
loc = it.get("location") or {}
|
|
742
|
+
fname = _diagnostic_rel(root, it.get("filename")) or py_files[0]
|
|
743
|
+
findings.append({"severity": "P1", "rule": f"ruff-{it.get('code', 'ERR')}", "file": fname,
|
|
744
|
+
"line": int(loc.get("row") or 1), "message": it.get("message", "ruff error"),
|
|
745
|
+
"fix": "Fix the ruff diagnostic on the changed Python file."})
|
|
746
|
+
|
|
747
|
+
if py_files and (root / "pyrightconfig.json").is_file() and (pyright := shutil.which("pyright")):
|
|
748
|
+
r = invoke("pyright", [pyright, *["./" + f for f in py_files]])
|
|
749
|
+
if r.returncode != 0:
|
|
750
|
+
failure("pyright", py_files[0], r)
|
|
751
|
+
|
|
752
|
+
if js_files:
|
|
753
|
+
if node := shutil.which("node"):
|
|
754
|
+
for file in js_files:
|
|
755
|
+
if Path(file).suffix.lower() not in {".js", ".mjs", ".cjs"}:
|
|
756
|
+
continue
|
|
757
|
+
r = invoke("node-check", [node, "--check", "./" + file], timeout=15)
|
|
758
|
+
if r.returncode != 0:
|
|
759
|
+
failure("node-syntax", file, r, "P0")
|
|
760
|
+
if oxlint := shutil.which("oxlint"):
|
|
761
|
+
r = invoke("oxlint", [oxlint, "-D", "correctness", "-D", "suspicious", "--", *js_files])
|
|
448
762
|
if r.returncode != 0:
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
763
|
+
failure("oxlint", js_files[0], r)
|
|
764
|
+
elif any((root / f).is_file() for f in ("biome.json", "biome.jsonc")) and (biome := shutil.which("biome")):
|
|
765
|
+
r = invoke("biome", [biome, "lint", "--", *js_files])
|
|
766
|
+
if r.returncode != 0:
|
|
767
|
+
failure("biome", js_files[0], r)
|
|
768
|
+
|
|
769
|
+
ts_files = {f for f in js_files if Path(f).suffix.lower() in {".ts", ".tsx"}}
|
|
770
|
+
if ts_files and (root / "tsconfig.json").is_file():
|
|
771
|
+
bin_dir = root / "node_modules/.bin"
|
|
772
|
+
tsc = next((str(path) for name in ("tsc.cmd", "tsc") if (path := bin_dir / name).is_file()), None) if sys.platform == "win32" else None
|
|
773
|
+
if not tsc:
|
|
774
|
+
tsc = shutil.which(str(bin_dir / "tsc")) or shutil.which("tsc")
|
|
775
|
+
if tsc:
|
|
776
|
+
r = invoke("tsc", [tsc, "--noEmit", "--pretty", "false"])
|
|
777
|
+
failed_without_file = r.returncode != 0
|
|
778
|
+
for line in (r.stdout + "\n" + r.stderr).splitlines():
|
|
779
|
+
if match := TS_DIAGNOSTIC_RE.match(line):
|
|
780
|
+
failed_without_file = False
|
|
781
|
+
file = _diagnostic_rel(root, match[1])
|
|
782
|
+
if file in ts_files:
|
|
783
|
+
findings.append({"severity": "P1", "rule": "ts-typecheck", "file": file,
|
|
784
|
+
"line": int(match[2]), "message": match[3],
|
|
785
|
+
"fix": "Fix the TypeScript error on the changed file."})
|
|
786
|
+
if failed_without_file:
|
|
787
|
+
failure("ts-typecheck", min(ts_files), r)
|
|
788
|
+
|
|
789
|
+
go_files = [f for f in files if f.endswith(".go")]
|
|
790
|
+
if go_files and (root / "go.mod").is_file() and (go := shutil.which("go")):
|
|
791
|
+
r = invoke("go-vet", [go, "vet", "./..."])
|
|
792
|
+
if r.returncode != 0:
|
|
793
|
+
failure("go-vet", go_files[0], r)
|
|
794
|
+
|
|
795
|
+
if sh_files and (shellcheck := shutil.which("shellcheck")):
|
|
796
|
+
r = invoke("shellcheck", [shellcheck, "-S", "error", "-f", "json", "--", *sh_files])
|
|
461
797
|
if r.returncode != 0:
|
|
462
798
|
try:
|
|
463
|
-
|
|
464
|
-
findings.append({"severity": "P1", "rule": f"SC{it.get('code', '')}", "file": it.get("file", sh_files[0]),
|
|
465
|
-
"line": int(it.get("line") or 1), "message": it.get("message", "shellcheck error"),
|
|
466
|
-
"fix": "Fix the shellcheck error."})
|
|
799
|
+
items = json.loads(r.stdout)
|
|
467
800
|
except ValueError:
|
|
468
|
-
|
|
801
|
+
items = []
|
|
802
|
+
if not items:
|
|
803
|
+
failure("shellcheck", sh_files[0], r)
|
|
804
|
+
for it in items[:15]:
|
|
805
|
+
findings.append({"severity": "P1", "rule": f"SC{it.get('code', '')}", "file": it.get("file", sh_files[0]),
|
|
806
|
+
"line": int(it.get("line") or 1), "message": it.get("message", "shellcheck error"),
|
|
807
|
+
"fix": "Fix the shellcheck error."})
|
|
469
808
|
|
|
470
809
|
return findings, ran
|
|
471
810
|
|
|
472
811
|
|
|
812
|
+
REWARD_HACK_GOTCHA = "a verification or evaluation step changed behavior; keep its original behavior and fix the underlying failure"
|
|
813
|
+
|
|
814
|
+
|
|
815
|
+
def _gotcha_content(pm, findings: list[dict], key: str, source: str) -> str:
|
|
816
|
+
"""Note text that the memory screen accepts: scanner-authored messages describe the trigger, so they stay out."""
|
|
817
|
+
rules = sorted({f["rule"] for f in findings})[:6]
|
|
818
|
+
sample = findings[0]
|
|
819
|
+
head = f"Slop gate blocked {len(findings)} issue(s) ({', '.join(rules)})"
|
|
820
|
+
if sample["rule"].startswith("reward-hack-"):
|
|
821
|
+
return f"{head}: {REWARD_HACK_GOTCHA}."
|
|
822
|
+
detail = f"{head}: {sample['message']} -> {sample['fix']}"
|
|
823
|
+
if pm.note_violations(key=key, kind="gotcha", content=detail, tags="slop-gate,ci", source=source):
|
|
824
|
+
return f"{head}: see {source} and fix the reported cause."
|
|
825
|
+
return detail
|
|
826
|
+
|
|
827
|
+
|
|
473
828
|
def _record_gotcha_memory(root: Path, findings: list[dict]) -> None:
|
|
474
829
|
mem_path = ASSETS_DIR / "memory" / "project_memory.py"
|
|
475
830
|
if not mem_path.is_file() or not findings:
|
|
476
831
|
return
|
|
477
832
|
try:
|
|
478
833
|
pm = _load_mod("dmb_slop_pm", mem_path)
|
|
479
|
-
|
|
480
|
-
|
|
834
|
+
key = f"slop-gotcha:{sorted({f['rule'] for f in findings})[0]}"
|
|
835
|
+
source = f"{findings[0]['file']}:{findings[0]['line']}"
|
|
481
836
|
pm.put_memory(
|
|
482
837
|
root,
|
|
483
|
-
key=
|
|
838
|
+
key=key,
|
|
484
839
|
kind="gotcha",
|
|
485
840
|
priority=1,
|
|
486
841
|
tags="slop-gate,ci",
|
|
487
|
-
source=
|
|
488
|
-
content=
|
|
842
|
+
source=source,
|
|
843
|
+
content=_gotcha_content(pm, findings, key, source),
|
|
489
844
|
)
|
|
490
845
|
except (OSError, ImportError, ValueError) as exc:
|
|
491
846
|
print(f"warning: slop memory record skipped: {exc}", file=sys.stderr)
|
|
492
847
|
|
|
848
|
+
|
|
493
849
|
def run_slop_gate(
|
|
494
850
|
root: Path,
|
|
495
851
|
*,
|
|
496
852
|
staged: bool = False,
|
|
497
853
|
explicit_files: list[str] | None = None,
|
|
854
|
+
base: str | None = None,
|
|
855
|
+
allow_untested: bool = False,
|
|
498
856
|
allow_config_change: bool = False,
|
|
499
857
|
run_linters: bool = True,
|
|
500
858
|
record_memory: bool = False,
|
|
@@ -502,7 +860,7 @@ def run_slop_gate(
|
|
|
502
860
|
max_nesting: int = DEFAULT_MAX_NESTING,
|
|
503
861
|
) -> dict:
|
|
504
862
|
resolved_root = root.resolve()
|
|
505
|
-
changed =
|
|
863
|
+
changed, baseline = _change_scope(resolved_root, staged, explicit_files, base)
|
|
506
864
|
findings: list[dict] = []
|
|
507
865
|
|
|
508
866
|
loop_mod = _load_mod("dmb_loop_slop", ASSETS_DIR / "loop" / "loop.py")
|
|
@@ -517,21 +875,26 @@ def run_slop_gate(
|
|
|
517
875
|
"message": f"Guardrail config `{rel}` modified without explicit authorization.",
|
|
518
876
|
"fix": "Revert guardrail weakening or re-run with `--allow-config-change` when intentional."})
|
|
519
877
|
|
|
520
|
-
|
|
521
|
-
|
|
878
|
+
count_prod = not allow_untested and not explicit_files
|
|
879
|
+
changed_tests = any(TEST_FILE_RE.search(rel) for rel in changed)
|
|
880
|
+
prod_counts: dict[str, int] = {}
|
|
881
|
+
batched_reward = reward_mod._batch_diffs_for_files(resolved_root, changed, staged=staged, base=baseline) if reward_mod is not None else {}
|
|
522
882
|
for rel in changed:
|
|
883
|
+
ext = Path(rel).suffix.lower()
|
|
884
|
+
test_target = _is_test_target(rel, ext)
|
|
885
|
+
if staged and test_target:
|
|
886
|
+
findings.extend(_check_staged_test_target(resolved_root, rel, ext))
|
|
523
887
|
text = _read_text_safe(resolved_root, rel)
|
|
524
888
|
if text is None:
|
|
525
889
|
continue
|
|
526
|
-
added = _added_lines_for_file(resolved_root, rel, staged
|
|
890
|
+
added = _added_lines_for_file(resolved_root, rel, staged, baseline, text)
|
|
527
891
|
if not added and explicit_files:
|
|
528
|
-
added = {i: l for i, l in enumerate(text
|
|
529
|
-
|
|
892
|
+
added = {i: l for i, l in enumerate(_split_lf_lines(text), 1)}
|
|
530
893
|
cur_slop = loop_mod.scan_text_slop(rel, text)
|
|
531
894
|
if cur_slop:
|
|
532
895
|
base_findings = []
|
|
533
|
-
if
|
|
534
|
-
blob = _git(resolved_root, "show", f"
|
|
896
|
+
if baseline:
|
|
897
|
+
blob = _git(resolved_root, "show", f"{baseline}:{rel}")
|
|
535
898
|
if blob.returncode == 0:
|
|
536
899
|
base_findings = loop_mod.scan_text_slop(rel, blob.stdout)
|
|
537
900
|
new_slop = loop_mod.diff_new_slop(cur_slop, loop_mod.slop_counts(base_findings))
|
|
@@ -541,14 +904,36 @@ def run_slop_gate(
|
|
|
541
904
|
|
|
542
905
|
findings.extend(_check_secrets_and_patterns(rel, added, text))
|
|
543
906
|
|
|
544
|
-
if
|
|
545
|
-
findings.extend(_check_python_ast(rel, text, added, max_func_lines=max_func_lines,
|
|
907
|
+
if ext == ".py":
|
|
908
|
+
findings.extend(_check_python_ast(rel, text, added, max_func_lines=max_func_lines,
|
|
909
|
+
max_nesting=max_nesting, check_empty=test_target and not staged))
|
|
910
|
+
test_file = bool(TEST_FILE_RE.search(rel))
|
|
911
|
+
count_file = count_prod and not changed_tests and not test_file and ext in PROD_EXTS and rel.split("/", 1)[0] not in DIFF_EXEMPT_DIRS
|
|
912
|
+
if ext in BRACE_EXTS and (test_target and not staged or added and (ext == ".rs" or test_file or count_file)):
|
|
913
|
+
values, lines, closes = _brace_tokens(text, ext)
|
|
914
|
+
if test_target and not staged and not _brace_declares_tests(ext, values, closes):
|
|
915
|
+
findings.append(_empty_test_finding(rel))
|
|
916
|
+
rust_tests = _rust_test_ranges(values, lines, closes) if ext == ".rs" else []
|
|
917
|
+
changed_tests |= any(start <= n <= end for start, end in rust_tests for n in added)
|
|
918
|
+
if test_file or rust_tests:
|
|
919
|
+
findings.extend(_scan_brace_tests(rel, ext, values, lines, closes, added))
|
|
920
|
+
if count_file:
|
|
921
|
+
prod_counts[rel] = len(added.keys() & set(lines))
|
|
922
|
+
elif count_file and ext == ".py":
|
|
923
|
+
prod_counts[rel] = sum(bool(line.strip()) and not line.lstrip().startswith("#") for line in added.values())
|
|
546
924
|
|
|
547
925
|
if reward_mod is not None:
|
|
548
926
|
_, r_hunks = batched_reward.get(rel, ({}, []))
|
|
549
927
|
findings.extend(
|
|
550
928
|
reward_mod.scan_added_lines_for_reward_hacks(rel, added, r_hunks, include_primitives=False, full_text=text)
|
|
551
929
|
)
|
|
930
|
+
if not changed_tests and sum(prod_counts.values()) >= 30:
|
|
931
|
+
tracked = _git(resolved_root, "ls-files", "-z")
|
|
932
|
+
if tracked.returncode == 0 and any(TEST_FILE_RE.search(rel) for rel in tracked.stdout.split("\0")):
|
|
933
|
+
largest = max(prod_counts, key=prod_counts.__getitem__)
|
|
934
|
+
findings.append({"severity": "P1", "rule": "untested-code-diff", "file": largest, "line": 1,
|
|
935
|
+
"message": "At least 30 production lines were added without changing any tests.",
|
|
936
|
+
"fix": "Add behavioral regression tests or pass --allow-untested for an approved exception."})
|
|
552
937
|
perf_path = ASSETS_DIR / "perf-audit" / "perf_audit.py"
|
|
553
938
|
code_changed = [f for f in changed if Path(f).suffix.lower() in CODE_EXTS and not TEST_FILE_RE.search(f) and (resolved_root / f).is_file()]
|
|
554
939
|
if perf_path.is_file() and code_changed:
|
|
@@ -579,10 +964,31 @@ def run_slop_gate(
|
|
|
579
964
|
|
|
580
965
|
findings.extend(_check_policy_xml(resolved_root, changed))
|
|
581
966
|
if reward_mod is not None:
|
|
967
|
+
if not staged and not explicit_files:
|
|
968
|
+
changed_set = set(changed)
|
|
969
|
+
sc_files, sym_findings = reward_mod._discover_scratch_scripts_and_symlinks(resolved_root)
|
|
970
|
+
findings.extend(sym_findings)
|
|
971
|
+
for srel in sc_files:
|
|
972
|
+
if srel in changed_set:
|
|
973
|
+
continue
|
|
974
|
+
stxt = _read_text_safe(resolved_root, srel, max_bytes=reward_mod.MAX_SCRATCH_SCRIPT_BYTES)
|
|
975
|
+
if stxt is not None:
|
|
976
|
+
sadded = {i: ln for i, ln in enumerate(_split_lf_lines(stxt), 1)}
|
|
977
|
+
findings.extend(
|
|
978
|
+
reward_mod.scan_added_lines_for_reward_hacks(srel, sadded, [([], list(sadded.items()))], include_primitives=False, full_text=stxt)
|
|
979
|
+
)
|
|
582
980
|
findings.extend(reward_mod._check_locked_contracts(resolved_root))
|
|
583
981
|
rules_path = ASSETS_DIR / "rules" / "rule_ledger.py"
|
|
584
982
|
if rules_path.is_file():
|
|
585
|
-
findings.extend(_load_mod("dmb_rule_ledger", rules_path).check(
|
|
983
|
+
findings.extend(_load_mod("dmb_rule_ledger", rules_path).check(
|
|
984
|
+
resolved_root, staged=staged, base=base if not staged and not explicit_files else None,
|
|
985
|
+
)["findings"])
|
|
986
|
+
sim_path = ASSETS_DIR / "sim" / "sim.py"
|
|
987
|
+
if sim_path.is_file():
|
|
988
|
+
findings.extend(_load_mod("dmb_sim", sim_path).check_repo(
|
|
989
|
+
resolved_root, changed=changed if explicit_files else None, staged=staged,
|
|
990
|
+
base_ref=baseline if not staged and not explicit_files else None,
|
|
991
|
+
)["findings"])
|
|
586
992
|
|
|
587
993
|
counts = {"P0": 0, "P1": 0, "P2": 0}
|
|
588
994
|
for f in findings:
|
|
@@ -607,8 +1013,10 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
607
1013
|
p = argparse.ArgumentParser(description="Zero-token diff-only anti-slop, secret, linter, boundary & budget CI gate.")
|
|
608
1014
|
p.add_argument("--root", default=".")
|
|
609
1015
|
p.add_argument("--staged", action="store_true", help="Scan staged git changes only (for pre-commit hooks).")
|
|
1016
|
+
p.add_argument("--base", help="Scan changes since the merge base with this ref, including local changes.")
|
|
610
1017
|
p.add_argument("--files", nargs="*", default=None, help="Optional comma- or space-separated repo-relative file list.")
|
|
611
1018
|
p.add_argument("--allow-config-change", action="store_true", help="Allow edits to guardrail configs in this run.")
|
|
1019
|
+
p.add_argument("--allow-untested", action="store_true", help="Allow large production changes without changed tests.")
|
|
612
1020
|
p.add_argument("--no-linters", action="store_true", help="Skip external PATH linters (ruff/shellcheck/node).")
|
|
613
1021
|
p.add_argument("--record-memory", action="store_true", help="Record failing rules as P1 gotchas in deepmode-memory.db.")
|
|
614
1022
|
p.add_argument("--max-func-lines", type=int, default=DEFAULT_MAX_FUNC_LINES)
|
|
@@ -617,16 +1025,15 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
617
1025
|
args = p.parse_args(argv)
|
|
618
1026
|
|
|
619
1027
|
explicit = [x.strip() for raw_f in (args.files or []) for x in raw_f.split(",") if x.strip()] or None
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
)
|
|
1028
|
+
try:
|
|
1029
|
+
res = run_slop_gate(
|
|
1030
|
+
Path(args.root), staged=args.staged, explicit_files=explicit, base=args.base,
|
|
1031
|
+
allow_config_change=args.allow_config_change, allow_untested=args.allow_untested,
|
|
1032
|
+
run_linters=not args.no_linters, record_memory=args.record_memory,
|
|
1033
|
+
max_func_lines=args.max_func_lines, max_nesting=args.max_nesting,
|
|
1034
|
+
)
|
|
1035
|
+
except ValueError as exc:
|
|
1036
|
+
p.error(str(exc))
|
|
630
1037
|
if args.json:
|
|
631
1038
|
print(json.dumps(res, indent=2))
|
|
632
1039
|
else:
|