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
@@ -2,8 +2,10 @@ use crate::util::{glob_match, json_escape, parallel_map};
2
2
  use std::collections::BTreeSet;
3
3
  use std::fs;
4
4
  use std::path::{Path, PathBuf};
5
- use std::process::{Command, ExitCode};
5
+ use std::io::Read;
6
+ use std::process::{Command, ExitCode, Stdio};
6
7
  use std::thread;
8
+ use std::time::{Duration, Instant};
7
9
 
8
10
  #[derive(Clone, Debug, PartialEq, Eq)]
9
11
  pub struct Finding {
@@ -15,6 +17,14 @@ pub struct Finding {
15
17
  pub fix: &'static str,
16
18
  }
17
19
 
20
+ const BRANCH_BASES: &[&str] = &["origin/HEAD", "origin/main", "origin/master", "main", "master"];
21
+ const JS_EXTS: &[&str] = &["js", "mjs", "cjs", "jsx", "ts", "tsx"];
22
+ const DIFF_EXEMPT_DIRS: &[&str] = &[".deepmodebot", "scripts", "docs", "evals"];
23
+
24
+ fn extension(rel: &str) -> &str {
25
+ Path::new(rel).extension().and_then(|s| s.to_str()).unwrap_or("")
26
+ }
27
+
18
28
  const GUARDRAIL_CONFIGS: &[&str] = &[
19
29
  ".deepmodebot/ci.yml",
20
30
  ".deepmodebot/policy.xml",
@@ -45,7 +55,31 @@ fn git(root: &Path, args: &[&str]) -> Option<(bool, String)> {
45
55
  ))
46
56
  }
47
57
 
48
- fn changed_files(root: &Path, staged: bool, explicit: &[String]) -> Vec<String> {
58
+ fn merge_base(root: &Path, base: &str) -> Option<String> {
59
+ if base.starts_with('-') {
60
+ return None;
61
+ }
62
+ let (ok, id) = git(root, &["merge-base", "HEAD", base])?;
63
+ ok.then(|| id.trim().to_owned())
64
+ }
65
+
66
+ fn git_paths(root: &Path, args: &[&str]) -> impl Iterator<Item = String> {
67
+ git(root, args)
68
+ .filter(|(ok, _)| *ok)
69
+ .into_iter()
70
+ .flat_map(|(_, paths)| {
71
+ paths.split_terminator('\0').map(str::to_owned).collect::<Vec<_>>()
72
+ })
73
+ }
74
+
75
+ fn change_scope(
76
+ root: &Path,
77
+ staged: bool,
78
+ explicit: &[String],
79
+ base: Option<&str>,
80
+ ) -> Result<(Vec<String>, Option<String>), String> {
81
+ let head = git(root, &["rev-parse", "--verify", "HEAD"])
82
+ .and_then(|(ok, id)| ok.then(|| id.trim().to_owned()));
49
83
  if !explicit.is_empty() {
50
84
  let mut set = BTreeSet::new();
51
85
  for raw in explicit {
@@ -60,44 +94,36 @@ fn changed_files(root: &Path, staged: bool, explicit: &[String]) -> Vec<String>
60
94
  }
61
95
  }
62
96
  }
63
- return set.into_iter().collect();
97
+ return Ok((set.into_iter().collect(), head));
64
98
  }
65
- let mut set = BTreeSet::new();
66
- let has_head = git(root, &["rev-parse", "--verify", "HEAD"])
67
- .map(|(ok, _)| ok)
68
- .unwrap_or(false);
69
99
  if staged {
70
- if let Some((true, out)) =
71
- git(root, &["diff", "--cached", "--name-only", "--diff-filter=ACMR"])
72
- {
73
- for l in out.lines().map(str::trim).filter(|l| !l.is_empty()) {
74
- set.insert(l.to_string());
75
- }
100
+ let files = git_paths(root, &["diff", "--cached", "--name-only", "-z", "--diff-filter=ACMR"]).collect();
101
+ return Ok((files, head));
102
+ }
103
+ let mut paths: BTreeSet<_> = git_paths(root, &["ls-files", "--others", "--exclude-standard", "-z"]).collect();
104
+ let branch_base = if let Some(base) = base {
105
+ Some(merge_base(root, base).ok_or_else(|| format!("cannot resolve a merge base for {base:?}"))?)
106
+ } else if let Some(head) = head.as_deref().filter(|_| paths.is_empty()) {
107
+ if git_paths(root, &["diff", head, "--name-only", "-z"]).next().is_none() {
108
+ BRANCH_BASES.iter().filter_map(|base| merge_base(root, base)).find(|base| base != head)
109
+ } else {
110
+ None
76
111
  }
77
112
  } else {
78
- if has_head {
79
- if let Some((true, out)) =
80
- git(root, &["diff", "HEAD", "--name-only", "--diff-filter=ACMR"])
81
- {
82
- for l in out.lines().map(str::trim).filter(|l| !l.is_empty()) {
83
- set.insert(l.to_string());
84
- }
85
- }
86
- } else if let Some((true, out)) = git(root, &["ls-files"]) {
87
- for l in out.lines().map(str::trim).filter(|l| !l.is_empty()) {
88
- set.insert(l.to_string());
89
- }
90
- }
91
- if let Some((true, out)) = git(root, &["ls-files", "--others", "--exclude-standard"]) {
92
- for l in out.lines().map(str::trim).filter(|l| !l.is_empty()) {
93
- set.insert(l.to_string());
94
- }
95
- }
113
+ None
114
+ };
115
+ if let Some(base) = branch_base.as_deref().filter(|b| Some(*b) != head.as_deref()) {
116
+ let range = format!("{base}..HEAD");
117
+ paths.extend(git_paths(root, &["diff", &range, "--name-only", "-z", "--diff-filter=ACMR"]));
96
118
  }
97
- set.into_iter().collect()
119
+ let baseline = branch_base.or(head);
120
+ paths.extend(git_paths(root, &[
121
+ "diff", baseline.as_deref().unwrap_or("--cached"), "--name-only", "-z", "--diff-filter=ACMR",
122
+ ]));
123
+ Ok((paths.into_iter().collect(), baseline))
98
124
  }
99
125
 
100
- fn added_lines_for_file(root: &Path, rel: &str, staged: bool) -> Vec<(usize, String)> {
126
+ fn added_lines_for_file(root: &Path, rel: &str, staged: bool, baseline: Option<&str>, text: &str) -> Vec<(usize, String)> {
101
127
  let full = root.join(rel);
102
128
  let Ok(meta) = fs::symlink_metadata(&full) else {
103
129
  return Vec::new();
@@ -105,26 +131,13 @@ fn added_lines_for_file(root: &Path, rel: &str, staged: bool) -> Vec<(usize, Str
105
131
  if meta.file_type().is_symlink() || !meta.is_file() || meta.len() > 1_048_576 {
106
132
  return Vec::new();
107
133
  }
108
- let has_head = git(root, &["rev-parse", "--verify", "HEAD"])
109
- .map(|(ok, _)| ok)
110
- .unwrap_or(false);
111
- let tracked = git(root, &["ls-files", "--error-unmatch", "--", rel])
112
- .map(|(ok, _)| ok)
113
- .unwrap_or(false);
114
- if (!has_head || !tracked) && !staged {
115
- let Ok(txt) = fs::read_to_string(&full) else {
116
- return Vec::new();
117
- };
118
- return txt
119
- .lines()
120
- .enumerate()
121
- .map(|(i, l)| (i + 1, l.to_string()))
122
- .collect();
134
+ if !staged && (baseline.is_none() || !matches!(git(root, &["ls-files", "--error-unmatch", "--", rel]), Some((true, _)))) {
135
+ return text.lines().enumerate().map(|(i, l)| (i + 1, l.to_owned())).collect();
123
136
  }
124
137
  let args: Vec<&str> = if staged {
125
138
  vec!["diff", "--cached", "-U0", "--", rel]
126
139
  } else {
127
- vec!["diff", "HEAD", "-U0", "--", rel]
140
+ vec!["diff", baseline.unwrap_or("HEAD"), "-U0", "--", rel]
128
141
  };
129
142
  let Some((true, diff)) = git(root, &args) else {
130
143
  return Vec::new();
@@ -140,7 +153,7 @@ fn added_lines_for_file(root: &Path, rel: &str, staged: bool) -> Vec<(usize, Str
140
153
  cur_line = n;
141
154
  }
142
155
  }
143
- } else if raw.starts_with('+') && !raw.starts_with("+++") {
156
+ } else if cur_line != 0 && raw.starts_with('+') {
144
157
  out.push((cur_line, raw[1..].to_string()));
145
158
  cur_line += 1;
146
159
  }
@@ -150,19 +163,42 @@ fn added_lines_for_file(root: &Path, rel: &str, staged: bool) -> Vec<(usize, Str
150
163
 
151
164
  fn is_test_file(rel: &str) -> bool {
152
165
  let low = rel.to_ascii_lowercase();
153
- low.starts_with("tests/")
154
- || low.starts_with("test/")
155
- || low.starts_with("spec/")
156
- || low.starts_with("__tests__/")
157
- || low.contains("/tests/")
158
- || low.contains("/test/")
159
- || low.contains("/spec/")
160
- || low.contains("/__tests__/")
161
- || low.starts_with("test_")
162
- || low.contains("/test_")
163
- || low.contains("_test.")
164
- || low.contains(".test.")
165
- || low.contains(".spec.")
166
+ let (dirs, file) = low.rsplit_once('/').unwrap_or(("", &low));
167
+ dirs.split('/').any(|dir| matches!(dir, "test" | "tests" | "spec" | "__tests__"))
168
+ || file.rsplit_once('.').is_some_and(|(stem, ext)| {
169
+ !ext.is_empty() && (stem.strip_prefix("test_").is_some_and(|s| !s.is_empty())
170
+ || ["_test", ".test", ".spec"].iter().any(|suffix| stem.strip_suffix(suffix).is_some_and(|s| !s.is_empty())))
171
+ })
172
+ }
173
+
174
+ fn is_test_target(rel: &str, ext: &str) -> bool {
175
+ if !matches!(ext, "py" | "go" | "rs") && !JS_EXTS.contains(&ext) {
176
+ return false;
177
+ }
178
+ let low = rel.to_ascii_lowercase();
179
+ let mut parts = low.rsplit('/');
180
+ let stem = parts.next().and_then(|file| file.rsplit_once('.')).map_or("", |(stem, _)| stem);
181
+ if ext == "go" {
182
+ return stem.ends_with("_test");
183
+ }
184
+ if stem.starts_with("test_") || ["_test", ".test", ".spec"].iter().any(|suffix| stem.ends_with(suffix)) {
185
+ return true;
186
+ }
187
+ if JS_EXTS.contains(&ext) {
188
+ return parts.any(|dir| dir == "__tests__");
189
+ }
190
+ ext == "rs" && (parts.next() == Some("tests") || stem == "main" && parts.next() == Some("tests"))
191
+ }
192
+
193
+ fn empty_test_finding(rel: &str) -> Finding {
194
+ Finding {
195
+ severity: "P1",
196
+ rule: "empty-test-file",
197
+ file: rel.to_owned(),
198
+ line: 1,
199
+ message: "Test file contains no test definitions.".into(),
200
+ fix: "Add a behavioral test or move helpers out of the test target.",
201
+ }
166
202
  }
167
203
 
168
204
  fn is_alnum_run(s: &str, min_len: usize) -> bool {
@@ -418,17 +454,24 @@ fn has_workers_ctx_destructure(js: &str) -> bool {
418
454
  }
419
455
 
420
456
  pub fn scan_added_lines(rel: &str, lines: &[(usize, String)], out: &mut Vec<Finding>) {
457
+ scan_added_lines_ctx(rel, lines, None, out);
458
+ }
459
+
460
+ fn scan_added_lines_ctx(
461
+ rel: &str,
462
+ lines: &[(usize, String)],
463
+ rs_cfg_ln: Option<usize>,
464
+ out: &mut Vec<Finding>,
465
+ ) {
421
466
  let ext = Path::new(rel)
422
467
  .extension()
423
468
  .and_then(|e| e.to_str())
424
469
  .map(|s| s.to_ascii_lowercase())
425
470
  .unwrap_or_default();
426
471
  let test_file = is_test_file(rel);
427
- let mut in_cfg_test = false;
472
+
428
473
  for (ln, line) in lines {
429
- if ext == "rs" && line.trim().starts_with("#[cfg(test)]") {
430
- in_cfg_test = true;
431
- }
474
+ let in_test_ctx = test_file || rs_cfg_ln.is_some_and(|cfg| *ln >= cfg);
432
475
  if let Some((rule, msg)) = has_secret(line) {
433
476
  out.push(Finding {
434
477
  severity: "P0",
@@ -453,10 +496,7 @@ pub fn scan_added_lines(rel: &str, lines: &[(usize, String)], out: &mut Vec<Find
453
496
  fix: "Pin to full 40-char commit SHA with version comment.",
454
497
  });
455
498
  }
456
- if test_file || in_cfg_test {
457
- continue;
458
- }
459
- if ext == "py"
499
+ if !test_file && ext == "py"
460
500
  && (contains_unquoted(line, "# noqa")
461
501
  || contains_unquoted(line, "# type: ignore")
462
502
  || contains_unquoted(line, "# pyright: ignore"))
@@ -470,7 +510,7 @@ pub fn scan_added_lines(rel: &str, lines: &[(usize, String)], out: &mut Vec<Find
470
510
  fix: "Fix root cause instead of suppressing.",
471
511
  });
472
512
  }
473
- if matches!(ext.as_str(), "ts" | "tsx" | "js" | "jsx" | "mjs")
513
+ if !test_file && matches!(ext.as_str(), "ts" | "tsx" | "js" | "jsx" | "mjs")
474
514
  && (contains_unquoted(line, "@ts-ignore")
475
515
  || contains_unquoted(line, "@ts-expect-error")
476
516
  || contains_unquoted(line, "eslint-disable"))
@@ -484,7 +524,7 @@ pub fn scan_added_lines(rel: &str, lines: &[(usize, String)], out: &mut Vec<Find
484
524
  fix: "Fix root cause instead of suppressing.",
485
525
  });
486
526
  }
487
- if matches!(ext.as_str(), "ts" | "tsx")
527
+ if !in_test_ctx && matches!(ext.as_str(), "ts" | "tsx")
488
528
  && (contains_unquoted(line, " as any")
489
529
  || contains_unquoted(line, " as unknown as "))
490
530
  {
@@ -497,7 +537,7 @@ pub fn scan_added_lines(rel: &str, lines: &[(usize, String)], out: &mut Vec<Find
497
537
  fix: "Use a type guard or validated schema.",
498
538
  });
499
539
  }
500
- if ext == "rs" && contains_unquoted(line, ".unwrap()") {
540
+ if !in_test_ctx && ext == "rs" && contains_unquoted(line, ".unwrap()") {
501
541
  out.push(Finding {
502
542
  severity: "P1",
503
543
  rule: "rust-prod-unwrap",
@@ -507,7 +547,7 @@ pub fn scan_added_lines(rel: &str, lines: &[(usize, String)], out: &mut Vec<Find
507
547
  fix: "Propagate with `?` or handle explicitly.",
508
548
  });
509
549
  }
510
- if ext == "go" && contains_unquoted(line, "_ = err") {
550
+ if !test_file && ext == "go" && contains_unquoted(line, "_ = err") {
511
551
  out.push(Finding {
512
552
  severity: "P1",
513
553
  rule: "go-ignored-err",
@@ -517,7 +557,7 @@ pub fn scan_added_lines(rel: &str, lines: &[(usize, String)], out: &mut Vec<Find
517
557
  fix: "Check and return or handle `err`.",
518
558
  });
519
559
  }
520
- if has_client_env_secret(line) {
560
+ if !in_test_ctx && has_client_env_secret(line) {
521
561
  out.push(Finding {
522
562
  severity: "P0",
523
563
  rule: "client-env-secret",
@@ -527,12 +567,12 @@ pub fn scan_added_lines(rel: &str, lines: &[(usize, String)], out: &mut Vec<Find
527
567
  fix: "Keep secrets in server-only env vars behind a server route or Action.",
528
568
  });
529
569
  }
530
- let js_code = if matches!(ext.as_str(), "js" | "mjs" | "cjs" | "ts" | "tsx" | "jsx" | "svelte" | "vue") {
570
+ let js_code = if !in_test_ctx && matches!(ext.as_str(), "js" | "mjs" | "cjs" | "ts" | "tsx" | "jsx" | "svelte" | "vue") {
531
571
  scrub_js_code_line(line)
532
572
  } else {
533
573
  String::new()
534
574
  };
535
- if !js_code.is_empty() && has_llm_browser_key(&js_code) {
575
+ if !in_test_ctx && !js_code.is_empty() && has_llm_browser_key(&js_code) {
536
576
  out.push(Finding {
537
577
  severity: "P0",
538
578
  rule: "llm-browser-key-exposure",
@@ -542,7 +582,7 @@ pub fn scan_added_lines(rel: &str, lines: &[(usize, String)], out: &mut Vec<Find
542
582
  fix: "Proxy LLM SDK calls through a server route or Durable Object.",
543
583
  });
544
584
  }
545
- if matches!(ext.as_str(), "js" | "mjs" | "ts" | "tsx") && has_legacy_implements_do(&js_code) {
585
+ if !in_test_ctx && matches!(ext.as_str(), "js" | "mjs" | "ts" | "tsx") && has_legacy_implements_do(&js_code) {
546
586
  out.push(Finding {
547
587
  severity: "P1",
548
588
  rule: "workers-legacy-implements-do",
@@ -552,7 +592,7 @@ pub fn scan_added_lines(rel: &str, lines: &[(usize, String)], out: &mut Vec<Find
552
592
  fix: "Import `DurableObject` from `cloudflare:workers` and use `extends DurableObject<Env>`.",
553
593
  });
554
594
  }
555
- if matches!(ext.as_str(), "js" | "mjs" | "ts" | "tsx") && has_workers_ctx_destructure(&js_code) {
595
+ if !in_test_ctx && matches!(ext.as_str(), "js" | "mjs" | "ts" | "tsx") && has_workers_ctx_destructure(&js_code) {
556
596
  out.push(Finding {
557
597
  severity: "P1",
558
598
  rule: "workers-ctx-destructure",
@@ -562,7 +602,7 @@ pub fn scan_added_lines(rel: &str, lines: &[(usize, String)], out: &mut Vec<Find
562
602
  fix: "Call `ctx.waitUntil(...)` directly on `ctx`.",
563
603
  });
564
604
  }
565
- if matches!(ext.as_str(), "js" | "mjs" | "cjs" | "ts" | "tsx" | "jsx")
605
+ if !in_test_ctx && matches!(ext.as_str(), "js" | "mjs" | "cjs" | "ts" | "tsx" | "jsx")
566
606
  && (contains_unquoted(line, ".innerHTML =")
567
607
  || contains_unquoted(line, "dangerouslySetInnerHTML")
568
608
  || contains_unquoted(line, "eval("))
@@ -610,6 +650,395 @@ pub fn scan_added_lines(rel: &str, lines: &[(usize, String)], out: &mut Vec<Find
610
650
  }
611
651
  }
612
652
 
653
+ #[derive(Clone, Copy)]
654
+ struct Token<'a> {
655
+ value: &'a str,
656
+ line: usize,
657
+ pair: Option<usize>,
658
+ }
659
+
660
+ fn source_tokens<'a>(text: &'a str, ext: &str) -> Vec<Token<'a>> {
661
+ let rust = ext == "rs";
662
+ let python = ext == "py";
663
+ let bytes = text.as_bytes();
664
+ let mut tokens: Vec<Token<'_>> = Vec::new();
665
+ let mut stack = Vec::new();
666
+ let (mut i, mut line) = (0, 1);
667
+ while i < bytes.len() {
668
+ let start = i;
669
+ let c = bytes[i];
670
+ i += 1;
671
+ let mut literal = false;
672
+ if c.is_ascii_whitespace() {
673
+ line += usize::from(c == b'\n');
674
+ continue;
675
+ }
676
+ if if python { c == b'#' } else { bytes[start..].starts_with(b"//") } {
677
+ while i < bytes.len() && bytes[i] != b'\n' {
678
+ i += 1;
679
+ }
680
+ continue;
681
+ }
682
+ if !python && bytes[start..].starts_with(b"/*") {
683
+ i += 1;
684
+ let mut depth = 1;
685
+ while i < bytes.len() && depth != 0 {
686
+ if bytes[i..].starts_with(b"*/") {
687
+ depth -= 1;
688
+ i += 2;
689
+ } else if rust && bytes[i..].starts_with(b"/*") {
690
+ depth += 1;
691
+ i += 2;
692
+ } else {
693
+ line += usize::from(bytes[i] == b'\n');
694
+ i += 1;
695
+ }
696
+ }
697
+ continue;
698
+ }
699
+ let quote = if rust && c == b'r' {
700
+ i + bytes[i..].iter().take_while(|b| **b == b'#').count()
701
+ } else {
702
+ start
703
+ };
704
+ if quote != start && bytes.get(quote) == Some(&b'"') {
705
+ literal = true;
706
+ let hashes = &bytes[start + 1..quote];
707
+ i = quote + 1;
708
+ while i < bytes.len() {
709
+ i += 1;
710
+ if bytes[i - 1] == b'"' && bytes[i..].starts_with(hashes) {
711
+ i += hashes.len();
712
+ break;
713
+ }
714
+ }
715
+ } else if python && matches!(c, b'\'' | b'"') && bytes.get(i..i + 2) == Some(&[c, c]) {
716
+ literal = true;
717
+ i += 2;
718
+ while i < bytes.len() {
719
+ if bytes.get(i..i + 3) == Some(&[c, c, c]) {
720
+ i += 3;
721
+ break;
722
+ }
723
+ i += if bytes[i] == b'\\' && i + 1 < bytes.len() { 2 } else { 1 };
724
+ }
725
+ } else if c == b'"' || c == b'`' || c == b'\'' && !rust {
726
+ literal = true;
727
+ while i < bytes.len() {
728
+ let b = bytes[i];
729
+ i += 1;
730
+ if b == c {
731
+ break;
732
+ }
733
+ if b == b'\\' && !(c == b'`' && ext == "go") && i < bytes.len() {
734
+ i += 1;
735
+ }
736
+ }
737
+ } else if rust && c == b'\'' {
738
+ let char_end = if bytes.get(i) == Some(&b'\\') {
739
+ bytes[i + 1..].iter().take(12).position(|b| *b == b'\'').map(|n| i + n + 1)
740
+ } else {
741
+ text[i..].chars().next().map(|ch| i + ch.len_utf8())
742
+ };
743
+ if let Some(end) = char_end.filter(|end| bytes.get(*end) == Some(&b'\'')) {
744
+ literal = true;
745
+ i = end + 1;
746
+ }
747
+ } else if is_js_ident_byte(c) || !c.is_ascii() {
748
+ while i < bytes.len() && (is_js_ident_byte(bytes[i]) || !bytes[i].is_ascii()) {
749
+ i += 1;
750
+ }
751
+ } else if matches!(bytes.get(start..start + 2), Some(b"=>" | b"->" | b"::")) {
752
+ i += 1;
753
+ }
754
+ let value = if literal { "<literal>" } else { &text[start..i] };
755
+ let index = tokens.len();
756
+ let mut pair = None;
757
+ match value {
758
+ "{" | "(" | "[" => stack.push(index),
759
+ "}" | ")" | "]" => {
760
+ if let Some(&open) = stack.last() {
761
+ if matches!((tokens[open].value, value), ("{", "}") | ("(", ")") | ("[", "]")) {
762
+ stack.pop();
763
+ tokens[open].pair = Some(index);
764
+ pair = Some(open);
765
+ }
766
+ }
767
+ }
768
+ _ => {}
769
+ }
770
+ tokens.push(Token { value, line, pair });
771
+ if literal {
772
+ line += bytes[start..i].iter().filter(|b| **b == b'\n').count();
773
+ }
774
+ }
775
+ tokens
776
+ }
777
+
778
+ fn token_sequence(tokens: &[Token<'_>], at: usize, pattern: &[&str]) -> bool {
779
+ tokens.get(at..at + pattern.len()).is_some_and(|items| {
780
+ items.iter().zip(pattern).all(|(token, expected)| token.value == *expected)
781
+ })
782
+ }
783
+
784
+ fn next_top_level(tokens: &[Token<'_>], mut at: usize, end: usize, stops: &[&str]) -> usize {
785
+ while at < end && !stops.contains(&tokens[at].value) {
786
+ at = tokens[at].pair.filter(|pair| *pair > at).unwrap_or(at) + 1;
787
+ }
788
+ at.min(end)
789
+ }
790
+
791
+ fn rust_after_attributes(tokens: &[Token<'_>], mut at: usize) -> usize {
792
+ while token_sequence(tokens, at, &["#", "["]) {
793
+ let Some(end) = tokens[at + 1].pair else { break };
794
+ at = end + 1;
795
+ }
796
+ at
797
+ }
798
+
799
+ fn rust_test_ranges<'a>(tokens: &'a [Token<'a>]) -> impl Iterator<Item = (usize, usize)> + 'a {
800
+ tokens.iter().enumerate().filter_map(|(i, token)| {
801
+ if token.value != "#" || !token_sequence(tokens, i, &["#", "[", "cfg", "(", "test", ")", "]"]) {
802
+ return None;
803
+ }
804
+ let start = rust_after_attributes(tokens, i + 7);
805
+ let end = next_top_level(tokens, start, tokens.len(), &["{", ";"]);
806
+ let end = tokens.get(end)?.pair.unwrap_or(end);
807
+ Some((token.line, tokens[end].line))
808
+ })
809
+ }
810
+
811
+ fn test_body(tokens: &[Token<'_>], i: usize, ext: &str) -> Option<(usize, usize, bool)> {
812
+ let value = tokens[i].value;
813
+ let next = tokens.get(i + 1)?;
814
+ if JS_EXTS.contains(&ext) {
815
+ if !matches!(value, "it" | "test") || next.value != "(" {
816
+ return None;
817
+ }
818
+ let end = next.pair?;
819
+ let marker = next_top_level(tokens, i + 2, end, &["=>", "function"]);
820
+ if marker == end {
821
+ return None;
822
+ }
823
+ let body = if tokens[marker].value == "function" {
824
+ next_top_level(tokens, marker + 1, end, &["{"])
825
+ } else {
826
+ marker + 1
827
+ };
828
+ if body >= end {
829
+ return None;
830
+ }
831
+ return if tokens[body].value == "{" {
832
+ Some((body + 1, tokens[body].pair?, false))
833
+ } else {
834
+ Some((body, next_top_level(tokens, body, end, &[","]), false))
835
+ };
836
+ }
837
+ if ext == "go" {
838
+ if value != "func" || !next.value.starts_with("Test") || !token_sequence(tokens, i + 2, &["("]) {
839
+ return None;
840
+ }
841
+ let body = tokens.get(i + 2)?.pair? + 1;
842
+ return token_sequence(tokens, body, &["{"]).then(|| (body + 1, tokens[body].pair, false))
843
+ .and_then(|(start, end, oracle)| Some((start, end?, oracle)));
844
+ }
845
+ if value != "#" || next.value != "[" {
846
+ return None;
847
+ }
848
+ let attr_end = next.pair?;
849
+ if !token_sequence(tokens, i + 2, &["test", "]"])
850
+ && !token_sequence(tokens, i + 2, &["tokio", "::", "test", "]"])
851
+ && !token_sequence(tokens, i + 2, &["tokio", "::", "test", "("])
852
+ {
853
+ return None;
854
+ }
855
+ let start = rust_after_attributes(tokens, attr_end + 1);
856
+ let fun = next_top_level(tokens, start, tokens.len(), &["fn", "{", ";", "}"]);
857
+ if !token_sequence(tokens, fun, &["fn"]) {
858
+ return None;
859
+ }
860
+ let body = next_top_level(tokens, fun + 1, tokens.len(), &["{", ";", "}"]);
861
+ if !token_sequence(tokens, body, &["{"]) {
862
+ return None;
863
+ }
864
+ let mut prior = i;
865
+ while prior >= 2 && tokens[prior - 1].value == "]" {
866
+ let Some(open) = tokens[prior - 1].pair else { break };
867
+ if open == 0 || tokens[open - 1].value != "#" {
868
+ break;
869
+ }
870
+ prior = open - 1;
871
+ }
872
+ let oracle = (prior..fun).any(|j| token_sequence(tokens, j, &["#", "[", "should_panic"]))
873
+ || (fun + 1..body).any(|j| token_sequence(tokens, j, &["->", "Result", "<"]));
874
+ Some((body + 1, tokens[body].pair?, oracle))
875
+ }
876
+
877
+ fn brace_declares_tests(tokens: &[Token<'_>], ext: &str) -> bool {
878
+ if !JS_EXTS.contains(&ext) {
879
+ return (0..tokens.len()).any(|i| test_body(tokens, i, ext).is_some());
880
+ }
881
+ for (i, token) in tokens.iter().enumerate() {
882
+ if !matches!(token.value, "test" | "it") || i > 0 && tokens[i - 1].value == "function" {
883
+ continue;
884
+ }
885
+ let mut start = i + 1;
886
+ while token_sequence(tokens, start, &["."]) && tokens.get(start + 1)
887
+ .is_some_and(|t| matches!(t.value, "only" | "skip" | "todo" | "concurrent" | "each"))
888
+ {
889
+ start += 2;
890
+ }
891
+ if token_sequence(tokens, start, &["("]) && tokens[start].pair.is_some_and(|end|
892
+ end > start + 1 && !token_sequence(tokens, end + 1, &["{"]))
893
+ {
894
+ return true;
895
+ }
896
+ }
897
+ false
898
+ }
899
+
900
+ fn python_declares_tests(text: &str) -> bool {
901
+ let tokens = source_tokens(text, "py");
902
+ let mut lines = text.lines();
903
+ let (mut line, mut indent, mut i) = (0, 0, 0);
904
+ let mut classes = Vec::new();
905
+ while let Some(token) = tokens.get(i) {
906
+ if token.line > line {
907
+ let source = lines.nth(token.line - line - 1).unwrap_or("");
908
+ line = token.line;
909
+ indent = source.len() - source.trim_start().len();
910
+ while classes.last().is_some_and(|&(depth, _)| depth >= indent) {
911
+ classes.pop();
912
+ }
913
+ }
914
+ if let Some(name) = tokens.get(i + 1).map(|t| t.value) {
915
+ let mut next = i + 2;
916
+ if token_sequence(&tokens, next, &["["]) {
917
+ next = tokens[next].pair.map_or(next, |end| end + 1);
918
+ }
919
+ if token.value == "def" && token_sequence(&tokens, next, &["("])
920
+ && (name.starts_with("test_") || name.starts_with("test") && classes.last().is_some_and(|&(_, case)| case))
921
+ {
922
+ return true;
923
+ }
924
+ if token.value == "class" {
925
+ if name.starts_with("Test") && tokens.get(next).is_some_and(|t| matches!(t.value, "(" | ":")) {
926
+ return true;
927
+ }
928
+ let mut case = false;
929
+ if token_sequence(&tokens, next, &["("]) {
930
+ if let Some(end) = tokens[next].pair {
931
+ let mut base = next + 1;
932
+ while base < end {
933
+ let boundary = next_top_level(&tokens, base, end, &[","]);
934
+ case |= boundary > base && tokens[boundary - 1].value == "TestCase"
935
+ && (boundary == base + 1 || tokens[boundary - 2].value == ".");
936
+ base = boundary + 1;
937
+ }
938
+ next = end + 1;
939
+ }
940
+ }
941
+ if token_sequence(&tokens, next, &[":"]) {
942
+ let header_end = tokens[next].line;
943
+ if header_end > line {
944
+ lines.nth(header_end - line - 1);
945
+ line = header_end;
946
+ }
947
+ classes.push((indent, case));
948
+ i = next;
949
+ }
950
+ }
951
+ }
952
+ i += 1;
953
+ }
954
+ false
955
+ }
956
+
957
+ fn staged_test_target_is_empty(root: &Path, rel: &str, ext: &str) -> bool {
958
+ let Some((true, text)) = git(root, &["show", &format!(":{rel}")]) else { return false };
959
+ text.len() <= 1_048_576 && if ext == "py" {
960
+ !python_declares_tests(&text)
961
+ } else {
962
+ !brace_declares_tests(&source_tokens(&text, ext), ext)
963
+ }
964
+ }
965
+
966
+ fn test_theater(rel: &str, line: usize, rule: &'static str, message: &str) -> Finding {
967
+ Finding {
968
+ severity: "P1",
969
+ rule,
970
+ file: rel.to_owned(),
971
+ line,
972
+ message: message.to_owned(),
973
+ fix: "Assert an observable behavior that fails when the implementation regresses.",
974
+ }
975
+ }
976
+
977
+ fn scan_brace_tests(rel: &str, ext: &str, tokens: &[Token<'_>], added: &BTreeSet<usize>, out: &mut Vec<Finding>) {
978
+ let js = JS_EXTS.contains(&ext);
979
+ for (i, token) in tokens.iter().enumerate() {
980
+ let Some((start, end, mut oracle)) = test_body(tokens, i, ext) else { continue };
981
+ if added.range(token.line..=tokens[end].line).next().is_none() {
982
+ continue;
983
+ }
984
+ if start == end {
985
+ out.push(test_theater(rel, token.line, "test-theater-empty", "Empty test proves nothing."));
986
+ continue;
987
+ }
988
+ for j in start..end {
989
+ let name = tokens[j].value;
990
+ let next = tokens.get(j + 1).map(|t| t.value);
991
+ let tautology = if js {
992
+ oracle |= (matches!(name, "expect" | "assert" | "rejects" | "throws" | "verify")
993
+ && matches!(next, Some("(" | ".")))
994
+ || (matches!(name, "rejects" | "throws") && tokens[j - 1].value == ".");
995
+ name == "expect" && tokens.get(j + 2).is_some_and(|t| {
996
+ let literal = t.value;
997
+ matches!(literal, "true" | "false" | "1")
998
+ && token_sequence(tokens, j + 1, &["(", literal, ")", ".", "toBe", "(", literal, ")"])
999
+ })
1000
+ } else if ext == "rs" {
1001
+ oracle |= (name.starts_with("assert") || name.starts_with("debug_assert") || name == "panic") && next == Some("!");
1002
+ (name == "assert" && token_sequence(tokens, j + 1, &["!", "(", "true", ")"]))
1003
+ || (name == "assert_eq" && token_sequence(tokens, j + 1, &["!", "(", "1", ",", "1", ")"]))
1004
+ } else {
1005
+ oracle |= next == Some(".") && (matches!(name, "assert" | "require") || name == "t"
1006
+ && tokens.get(j + 2).is_some_and(|t| matches!(t.value, "Fatal" | "Fatalf" | "Error" | "Errorf" | "Fail" | "FailNow")));
1007
+ false
1008
+ };
1009
+ if tautology && added.contains(&tokens[j].line) {
1010
+ out.push(test_theater(rel, tokens[j].line, "test-theater-tautology", "Test assertion always passes."));
1011
+ }
1012
+ }
1013
+ if !oracle {
1014
+ out.push(test_theater(rel, token.line, "test-theater-no-assert", "Test has zero behavioral assertions."));
1015
+ }
1016
+ }
1017
+ }
1018
+
1019
+ fn python_tautology(line: &str) -> bool {
1020
+ if let Some(assertion) = line.strip_prefix("assert ") {
1021
+ let assertion = assertion.trim();
1022
+ if assertion == "True" || assertion.starts_with("True,") {
1023
+ return true;
1024
+ }
1025
+ if let Some((left, right)) = assertion.split_once("==") {
1026
+ return left.trim() == right.split(',').next().unwrap_or("").trim();
1027
+ }
1028
+ let compact: String = assertion.chars().filter(|ch| !ch.is_whitespace()).collect();
1029
+ return (compact.starts_with("isinstance(") && compact.ends_with(",object)"))
1030
+ || (compact.starts_with("len(") && compact.ends_with(")>=0"))
1031
+ || (compact.starts_with("0<=len(") && compact.ends_with(')'));
1032
+ }
1033
+ let compact: String = line.chars().filter(|ch| !ch.is_whitespace()).collect();
1034
+ if compact.contains(".assertTrue(True)") {
1035
+ return true;
1036
+ }
1037
+ compact.split_once(".assertEqual(").and_then(|(_, args)| {
1038
+ args.strip_suffix(')')?.split_once(',')
1039
+ }).is_some_and(|(a, b)| a == b)
1040
+ }
1041
+
613
1042
  fn scan_python_structural(
614
1043
  rel: &str,
615
1044
  txt: &str,
@@ -678,18 +1107,31 @@ fn scan_python_structural(
678
1107
  let start_ln = i + 1;
679
1108
  let mut j = i + 1;
680
1109
  let mut body_lines: Vec<(usize, &str)> = Vec::new();
1110
+ let mut in_triple: Option<&str> = None;
681
1111
  while j < all_lines.len() {
682
1112
  let bl = all_lines[j];
683
1113
  let bc = bl.split('#').next().unwrap_or("").trim();
684
- if bc.is_empty() {
1114
+ let continued_string = in_triple.is_some();
1115
+ if !continued_string && bc.is_empty() {
685
1116
  j += 1;
686
1117
  continue;
687
1118
  }
688
1119
  let b_ind = bl.len() - bl.trim_start().len();
689
- if b_ind <= def_ind {
1120
+ if !continued_string && b_ind <= def_ind {
690
1121
  break;
691
1122
  }
692
- body_lines.push((j + 1, bc));
1123
+ let mut rest = if continued_string { bl } else { bl.split('#').next().unwrap_or("") };
1124
+ while let Some((at, quote)) = ["\"\"\"", "'''"]
1125
+ .into_iter()
1126
+ .filter(|quote| in_triple.is_none_or(|open| open == *quote))
1127
+ .flat_map(|quote| rest.match_indices(quote))
1128
+ .filter(|(at, _)| rest.as_bytes()[..*at].iter().rev().take_while(|&&b| b == b'\\').count() % 2 == 0)
1129
+ .min_by_key(|(at, _)| *at)
1130
+ {
1131
+ in_triple = if in_triple.is_some() { None } else { Some(quote) };
1132
+ rest = &rest[at + quote.len()..];
1133
+ }
1134
+ body_lines.push((j + 1, if continued_string { "" } else { bc }));
693
1135
  j += 1;
694
1136
  }
695
1137
  let end_ln = body_lines.last().map(|(l, _)| *l).unwrap_or(start_ln);
@@ -709,25 +1151,17 @@ fn scan_python_structural(
709
1151
  } else {
710
1152
  let mut has_oracle = false;
711
1153
  for (bln, bs) in &body_lines {
712
- if *bs == "assert True" || bs.starts_with("assert True,") {
713
- has_oracle = true;
714
- out.push(Finding {
715
- severity: "P1",
716
- rule: "test-theater-tautology",
717
- file: rel.to_string(),
718
- line: *bln,
719
- message: format!("`assert True` in `{}` is a tautology.", fname),
720
- fix: "Assert a real output/state invariant that fails if the fix is reverted.",
721
- });
722
- } else if bs.starts_with("assert ")
723
- || bs.contains(".assert")
724
- || bs.contains("raises(")
725
- || bs.contains(".fail(")
726
- || bs.contains("verify(")
727
- || bs.contains("check(")
728
- {
729
- has_oracle = true;
1154
+ if added_lines.contains(bln) && python_tautology(bs) {
1155
+ out.push(test_theater(rel, *bln, "test-theater-tautology", "Test assertion always passes."));
1156
+ }
1157
+ let mut parts = bs.split('(').peekable();
1158
+ while let Some(part) = parts.next().filter(|_| parts.peek().is_some()) {
1159
+ let name = part.trim_end().rsplit(|ch: char| !ch.is_alphanumeric() && ch != '_')
1160
+ .next().unwrap_or("");
1161
+ has_oracle |= name.starts_with("assert") || name.starts_with("check_")
1162
+ || matches!(name, "fail" | "raises" | "warns" | "called");
730
1163
  }
1164
+ has_oracle |= bs.starts_with("assert ");
731
1165
  }
732
1166
  if !has_oracle {
733
1167
  out.push(Finding {
@@ -859,159 +1293,293 @@ fn check_policy_xml(root: &Path, changed: &[String], out: &mut Vec<Finding>) {
859
1293
  }
860
1294
  }
861
1295
 
862
- fn tool_exists(name: &str) -> bool {
863
- Command::new(name)
864
- .arg("--version")
865
- .output()
866
- .map(|o| o.status.success())
867
- .unwrap_or(false)
1296
+ fn tool_path(name: &str, directory: Option<&Path>) -> Option<PathBuf> {
1297
+ fn in_dir(dir: &Path, name: &str) -> Option<PathBuf> {
1298
+ #[cfg(windows)]
1299
+ {
1300
+ let extensions = std::env::var("PATHEXT").unwrap_or_else(|_| ".COM;.EXE;.BAT;.CMD".into());
1301
+ extensions.split(';').filter(|ext| !ext.is_empty())
1302
+ .map(|ext| dir.join(format!("{name}{ext}"))).find(|path| path.is_file())
1303
+ }
1304
+ #[cfg(not(windows))]
1305
+ {
1306
+ use std::os::unix::fs::PermissionsExt;
1307
+ let path = dir.join(name);
1308
+ fs::metadata(&path).ok()
1309
+ .filter(|meta| meta.is_file() && meta.permissions().mode() & 0o111 != 0)
1310
+ .map(|_| path)
1311
+ }
1312
+ }
1313
+ directory.and_then(|d| in_dir(d, name)).or_else(|| {
1314
+ std::env::split_paths(&std::env::var_os("PATH")?).find_map(|d| in_dir(&d, name))
1315
+ })
868
1316
  }
869
1317
 
870
- fn run_parallel_linters(root: &Path, changed: &[String]) -> (Vec<&'static str>, Vec<Finding>) {
871
- let py_files: Vec<String> = changed
872
- .iter()
873
- .filter(|f| f.ends_with(".py") && root.join(f).is_file())
874
- .cloned()
875
- .collect();
876
- let js_files: Vec<String> = changed
877
- .iter()
878
- .filter(|f| (f.ends_with(".js") || f.ends_with(".mjs")) && root.join(f).is_file())
879
- .cloned()
880
- .collect();
881
- let sh_files: Vec<String> = changed
882
- .iter()
883
- .filter(|f| f.ends_with(".sh") && root.join(f).is_file())
884
- .cloned()
885
- .collect();
886
-
887
- let mut active_linters = Vec::new();
888
- let mut findings = Vec::new();
1318
+ fn run_linter(mut cmd: Command, seconds: u64) -> Result<(), String> {
1319
+ let deadline = Instant::now() + Duration::from_secs(seconds);
1320
+ let mut child = cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped())
1321
+ .spawn().map_err(|err| err.to_string())?;
1322
+ fn drain(mut pipe: impl Read + Send + 'static) -> std::sync::mpsc::Receiver<Vec<u8>> {
1323
+ let (tx, rx) = std::sync::mpsc::channel();
1324
+ thread::spawn(move || {
1325
+ let mut output = Vec::new();
1326
+ let _ = pipe.read_to_end(&mut output);
1327
+ let _ = tx.send(output);
1328
+ });
1329
+ rx
1330
+ }
1331
+ let stdout = drain(child.stdout.take().expect("piped stdout"));
1332
+ let stderr = drain(child.stderr.take().expect("piped stderr"));
1333
+ let timed_out = || format!("timed out after {seconds}s");
1334
+ let status = loop {
1335
+ if let Some(status) = child.try_wait().map_err(|err| err.to_string())? {
1336
+ break status;
1337
+ }
1338
+ if Instant::now() >= deadline {
1339
+ let _ = child.kill();
1340
+ let _ = child.wait();
1341
+ return Err(timed_out());
1342
+ }
1343
+ thread::sleep(Duration::from_millis(10));
1344
+ };
1345
+ let output = stdout.recv_timeout(deadline.saturating_duration_since(Instant::now())).map_err(|_| timed_out())?;
1346
+ let errors = stderr.recv_timeout(deadline.saturating_duration_since(Instant::now())).map_err(|_| timed_out())?;
1347
+ if status.success() {
1348
+ Ok(())
1349
+ } else if output.is_empty() && errors.is_empty() {
1350
+ Err(status.to_string())
1351
+ } else {
1352
+ Err(format!("{}\n{}", String::from_utf8_lossy(&output), String::from_utf8_lossy(&errors)))
1353
+ }
1354
+ }
889
1355
 
890
- thread::scope(|s| {
891
- let py_h = if !py_files.is_empty() && tool_exists("ruff") {
892
- active_linters.push("ruff");
893
- Some(s.spawn(|| {
894
- let mut f = Vec::new();
895
- let mut cmd = Command::new("ruff");
896
- cmd.arg("check")
897
- .arg("--select")
898
- .arg("E9,F63,F7,F82,F401")
899
- .arg("--output-format")
900
- .arg("concise")
901
- .current_dir(root);
902
- for p in &py_files {
903
- cmd.arg(p);
904
- }
905
- if let Ok(out) = cmd.output() {
906
- if !out.status.success() {
907
- let txt = String::from_utf8_lossy(&out.stdout);
908
- for line in txt.lines() {
909
- let parts: Vec<&str> = line.splitn(4, ':').collect();
910
- if parts.len() == 4 {
911
- let ln = parts[1].trim().parse::<usize>().unwrap_or(1);
912
- f.push(Finding {
913
- severity: "P1",
914
- rule: "ruff",
915
- file: parts[0].replace('\\', "/"),
916
- line: ln,
917
- message: parts[3].trim().to_string(),
918
- fix: "Fix ruff diagnostic on changed Python file.",
919
- });
920
- }
921
- }
922
- }
1356
+ struct Linter<'a> {
1357
+ name: &'static str,
1358
+ rule: &'static str,
1359
+ files: Vec<&'a str>,
1360
+ tool: PathBuf,
1361
+ args: &'static [&'static str],
1362
+ with_files: bool,
1363
+ }
1364
+
1365
+ fn tsc_diagnostic(line: &str) -> Option<(&str, usize, &str)> {
1366
+ let (location, message) = line.split_once("): error TS")?;
1367
+ let (file, position) = location.rsplit_once('(')?;
1368
+ let (row, _) = position.split_once(',')?;
1369
+ Some((file, row.parse().ok()?, message.split_once(": ")?.1))
1370
+ }
1371
+
1372
+ fn run_parallel_linters(root: &Path, changed: &[String]) -> (Vec<&'static str>, Vec<Finding>) {
1373
+ let mut linters = Vec::new();
1374
+ let files: Vec<&str> = changed.iter().map(String::as_str).filter(|file| {
1375
+ fs::symlink_metadata(root.join(file)).is_ok_and(|meta| meta.is_file())
1376
+ }).collect();
1377
+ let select = |exts: &[&str]| files.iter().copied().filter(|file| {
1378
+ exts.iter().any(|ext| extension(file).eq_ignore_ascii_case(ext))
1379
+ }).collect::<Vec<_>>();
1380
+ let mut add = |name, rule, files, tool, args: &'static [&'static str], with_files| {
1381
+ linters.push(Linter { name, rule, files, tool, args, with_files });
1382
+ };
1383
+ let py = select(&["py"]);
1384
+ if !py.is_empty() {
1385
+ if let Some(tool) = tool_path("ruff", None) {
1386
+ add("ruff", "ruff", py.clone(), tool, &[
1387
+ "check", "--no-cache", "--select", "E9,F63,F7,F82,F401,F811,F841,B006,B007,B012,B023,S102,S307",
1388
+ "--output-format", "concise", "--",
1389
+ ][..], true);
1390
+ }
1391
+ if root.join("pyrightconfig.json").is_file() {
1392
+ if let Some(tool) = tool_path("pyright", None) {
1393
+ add("pyright", "pyright", py, tool, &[], true);
1394
+ }
1395
+ }
1396
+ }
1397
+ let js = select(JS_EXTS);
1398
+ if !js.is_empty() {
1399
+ let node_files = select(&["js", "mjs", "cjs"]);
1400
+ if !node_files.is_empty() {
1401
+ if let Some(tool) = tool_path("node", None) {
1402
+ for file in node_files {
1403
+ add("node-check", "node-syntax", vec![file], tool.clone(), &["--check"], true);
923
1404
  }
924
- f
925
- }))
926
- } else {
927
- None
928
- };
1405
+ }
1406
+ }
1407
+ if let Some(tool) = tool_path("oxlint", None) {
1408
+ add("oxlint", "oxlint", js, tool, &["-D", "correctness", "-D", "suspicious", "--"], true);
1409
+ } else if ["biome.json", "biome.jsonc"].iter().any(|file| root.join(file).is_file()) {
1410
+ if let Some(tool) = tool_path("biome", None) {
1411
+ add("biome", "biome", js, tool, &["lint", "--"], true);
1412
+ }
1413
+ }
1414
+ let ts = select(&["ts", "tsx"]);
1415
+ if !ts.is_empty() && root.join("tsconfig.json").is_file() {
1416
+ if let Some(tool) = tool_path("tsc", Some(&root.join("node_modules/.bin"))) {
1417
+ add("tsc", "ts-typecheck", ts, tool, &["--noEmit", "--pretty", "false"], false);
1418
+ }
1419
+ }
1420
+ }
1421
+ let go = select(&["go"]);
1422
+ if !go.is_empty() && root.join("go.mod").is_file() {
1423
+ if let Some(tool) = tool_path("go", None) {
1424
+ add("go-vet", "go-vet", go, tool, &["vet", "./..."], false);
1425
+ }
1426
+ }
1427
+ let sh = select(&["sh"]);
1428
+ if !sh.is_empty() {
1429
+ if let Some(tool) = tool_path("shellcheck", None) {
1430
+ add("shellcheck", "shellcheck", sh, tool, &["-S", "error", "-f", "gcc", "--"], true);
1431
+ }
1432
+ }
929
1433
 
930
- let js_h = if !js_files.is_empty() && tool_exists("node") {
931
- active_linters.push("node-check");
932
- Some(s.spawn(|| {
933
- let mut f = Vec::new();
934
- for p in &js_files {
935
- if let Ok(out) = Command::new("node")
936
- .arg("--check")
937
- .arg(root.join(p))
938
- .output()
1434
+ let mut names = Vec::new();
1435
+ for linter in &linters {
1436
+ if !names.contains(&linter.name) {
1437
+ names.push(linter.name);
1438
+ }
1439
+ }
1440
+ let results = parallel_map(&linters, |linter| {
1441
+ let mut command = Command::new(&linter.tool);
1442
+ command.current_dir(root).args(linter.args);
1443
+ if linter.with_files {
1444
+ command.args(linter.files.iter().map(|file| format!("./{file}")));
1445
+ }
1446
+ let mut findings = Vec::new();
1447
+ if let Err(output) = run_linter(command, if linter.name == "node-check" { 15 } else { 30 }) {
1448
+ let mut add = |file: &str, line, message: &str| findings.push(Finding {
1449
+ severity: if linter.name == "node-check" { "P0" } else { "P1" },
1450
+ rule: linter.rule,
1451
+ file: file.to_owned(),
1452
+ line,
1453
+ message: message.to_owned(),
1454
+ fix: "Resolve the linter diagnostic.",
1455
+ });
1456
+ let mut saw_file = false;
1457
+ if linter.name == "tsc" {
1458
+ for (file, line, msg) in output.lines().filter_map(tsc_diagnostic) {
1459
+ saw_file = true;
1460
+ let file = crate::util::normalize_rel(root, &root.join(file));
1461
+ if let Some(file) = linter.files.iter().find(|candidate| **candidate == file
1462
+ || cfg!(windows) && candidate.eq_ignore_ascii_case(&file))
939
1463
  {
940
- if !out.status.success() {
941
- let msg = String::from_utf8_lossy(&out.stderr)
942
- .lines()
943
- .next()
944
- .unwrap_or("Syntax error")
945
- .to_string();
946
- f.push(Finding {
947
- severity: "P0",
948
- rule: "node-syntax",
949
- file: p.clone(),
950
- line: 1,
951
- message: msg,
952
- fix: "Fix JS syntax error.",
953
- });
954
- }
1464
+ add(file, line, msg);
955
1465
  }
956
1466
  }
957
- f
958
- }))
959
- } else {
960
- None
961
- };
1467
+ }
1468
+ if !saw_file {
1469
+ let start = output.char_indices().rev().nth(1499).map_or(0, |(i, _)| i);
1470
+ add(linter.files[0], 1, output[start..].trim());
1471
+ }
1472
+ }
1473
+ findings
1474
+ });
1475
+ (names, results.into_iter().flatten().collect())
1476
+ }
962
1477
 
963
- let sh_h = if !sh_files.is_empty() && tool_exists("shellcheck") {
964
- active_linters.push("shellcheck");
965
- Some(s.spawn(|| {
966
- let mut f = Vec::new();
967
- let mut cmd = Command::new("shellcheck");
968
- cmd.arg("-f").arg("gcc").arg("-S").arg("error").current_dir(root);
969
- for p in &sh_files {
970
- cmd.arg(p);
971
- }
972
- if let Ok(out) = cmd.output() {
973
- if !out.status.success() {
974
- let txt = String::from_utf8_lossy(&out.stdout);
975
- for line in txt.lines() {
976
- let parts: Vec<&str> = line.splitn(4, ':').collect();
977
- if parts.len() == 4 {
978
- let ln = parts[1].trim().parse::<usize>().unwrap_or(1);
979
- f.push(Finding {
980
- severity: "P1",
981
- rule: "shellcheck",
982
- file: parts[0].replace('\\', "/"),
983
- line: ln,
984
- message: parts[3].trim().to_string(),
985
- fix: "Fix shellcheck error.",
986
- });
987
- }
988
- }
989
- }
990
- }
991
- f
992
- }))
993
- } else {
994
- None
995
- };
1478
+ fn read_source(path: &Path, max_bytes: u64) -> Option<String> {
1479
+ let meta = fs::symlink_metadata(path).ok()?;
1480
+ if !meta.is_file() || meta.len() > max_bytes {
1481
+ return None;
1482
+ }
1483
+ fs::read(path).ok().map(|bytes| match String::from_utf8(bytes) {
1484
+ Ok(text) => text,
1485
+ Err(err) => String::from_utf8_lossy(err.as_bytes()).into_owned(),
1486
+ })
1487
+ }
996
1488
 
997
- if let Some(h) = py_h {
998
- findings.extend(h.join().unwrap_or_default());
999
- }
1000
- if let Some(h) = js_h {
1001
- findings.extend(h.join().unwrap_or_default());
1489
+ fn append_reward(out: &mut Vec<Finding>, findings: Vec<crate::reward::RewardFinding>) {
1490
+ out.extend(findings.into_iter().map(|f| Finding {
1491
+ severity: f.severity, rule: f.rule, file: f.file, line: f.line, message: f.message, fix: f.fix,
1492
+ }));
1493
+ }
1494
+
1495
+ fn scan_scratch_reward(root: &Path, out: &mut Vec<Finding>) {
1496
+ const LIMIT: u64 = 16 * 1024 * 1024;
1497
+ const SKIP: &[&str] = &["reward-guard", "self-grill", "evidence", "goals", "gen-ui", "agents-md-backup", "quota-guard"];
1498
+ const PREFIXES: &[&str] = &["check-", "npm-test-", "init-cli-test-", "panel-", "autoroute-test-"];
1499
+ let scratch = root.join(".scratch");
1500
+ let mut pending = vec![scratch.clone()];
1501
+ let mut scripts = 0;
1502
+ while let Some(path) = pending.pop() {
1503
+ let Ok(meta) = fs::symlink_metadata(&path) else { continue };
1504
+ let rel = crate::util::normalize_rel(root, &path);
1505
+ if meta.file_type().is_symlink() {
1506
+ out.push(Finding {
1507
+ severity: "P0", rule: "reward-hack-scratch-symlink", file: rel, line: 1,
1508
+ message: "Symlink inside `.scratch/` can hide an external script.".into(),
1509
+ fix: "Remove the symlink and keep scripts inside the project root.",
1510
+ });
1511
+ continue;
1002
1512
  }
1003
- if let Some(h) = sh_h {
1004
- findings.extend(h.join().unwrap_or_default());
1513
+ if meta.is_dir() {
1514
+ let name = path.file_name().and_then(|name| name.to_str()).unwrap_or("");
1515
+ if (path.parent() == Some(&scratch) && SKIP.contains(&name))
1516
+ || PREFIXES.iter().any(|prefix| name.starts_with(prefix))
1517
+ {
1518
+ continue;
1519
+ }
1520
+ if let Ok(entries) = fs::read_dir(path) {
1521
+ let mut children: Vec<_> = entries.flatten().map(|entry| entry.path()).collect();
1522
+ children.sort_unstable_by(|a, b| b.cmp(a));
1523
+ pending.extend(children);
1524
+ }
1525
+ } else if meta.is_file() && matches!(extension(&rel).to_ascii_lowercase().as_str(), "py" | "sh" | "ps1" | "cmd" | "bat" | "js" | "mjs" | "cjs" | "ts") {
1526
+ if meta.len() > LIMIT {
1527
+ out.push(Finding {
1528
+ severity: "P0", rule: "reward-hack-oversized-scratch-script", file: rel, line: 1,
1529
+ message: "Scratch script exceeds 16 MiB (padding bypass blocked).".into(),
1530
+ fix: "Remove the oversized script.",
1531
+ });
1532
+ } else if scripts < 500 && meta.len() != 0 {
1533
+ scripts += 1;
1534
+ if let Some(text) = read_source(&path, LIMIT) {
1535
+ let added: Vec<_> = text.lines().enumerate().map(|(i, line)| (i + 1, line.to_owned())).collect();
1536
+ let mut findings = Vec::new();
1537
+ crate::reward::scan_file_reward_hacks_full(&rel, &added, &[], true, false, None, None, Some(&text), &mut findings);
1538
+ append_reward(out, findings);
1539
+ }
1540
+ }
1005
1541
  }
1006
- });
1542
+ }
1543
+ }
1007
1544
 
1008
- (active_linters, findings)
1545
+ fn scan_stub_slop(rel: &str, ext: &str, baseline: &str, text: &str, out: &mut Vec<Finding>) {
1546
+ fn key(ext: &str, line: &str) -> Option<&'static str> {
1547
+ let line = line.trim();
1548
+ let text = match ext {
1549
+ "py" if line.starts_with("raise NotImplementedError") => return Some("NotImplementedError"),
1550
+ "rs" => scrub_js_code_line(line),
1551
+ _ => return None,
1552
+ };
1553
+ ["todo!", "unimplemented!"].into_iter().find(|needle| {
1554
+ text.match_indices(needle).any(|(i, code)| text[i + code.len()..].trim_start().starts_with('('))
1555
+ })
1556
+ }
1557
+ let mut old = std::collections::BTreeMap::new();
1558
+ for line in baseline.lines().filter_map(|line| key(ext, line)) {
1559
+ *old.entry(line).or_insert(0usize) += 1;
1560
+ }
1561
+ for (i, line) in text.lines().enumerate() {
1562
+ if let Some(marker) = key(ext, line) {
1563
+ if let Some(n) = old.get_mut(marker).filter(|n| **n > 0) {
1564
+ *n -= 1;
1565
+ } else {
1566
+ out.push(Finding {
1567
+ severity: "P1", rule: "stub-placeholder", file: rel.to_owned(), line: i + 1,
1568
+ message: format!("New `{marker}` placeholder."),
1569
+ fix: "Implement the behavior rather than leaving a placeholder.",
1570
+ });
1571
+ }
1572
+ }
1573
+ }
1009
1574
  }
1010
1575
 
1576
+
1011
1577
  pub fn run(args: &[String]) -> ExitCode {
1012
1578
  let mut root = PathBuf::from(".");
1013
1579
  let mut staged = false;
1014
1580
  let mut allow_config = false;
1581
+ let mut base = None;
1582
+ let mut allow_untested = false;
1015
1583
  let mut no_linters = false;
1016
1584
  let mut as_json = false;
1017
1585
  let mut explicit_files: Vec<String> = Vec::new();
@@ -1027,6 +1595,18 @@ pub fn run(args: &[String]) -> ExitCode {
1027
1595
  staged = true;
1028
1596
  i += 1;
1029
1597
  }
1598
+ "--base" if i + 1 < args.len() && !args[i + 1].starts_with("--") => {
1599
+ base = Some(args[i + 1].as_str());
1600
+ i += 2;
1601
+ }
1602
+ "--base" => {
1603
+ eprintln!("dmb-gate slop: --base requires a ref");
1604
+ return ExitCode::from(2);
1605
+ }
1606
+ "--allow-untested" => {
1607
+ allow_untested = true;
1608
+ i += 1;
1609
+ }
1030
1610
  "--allow-config-change" => {
1031
1611
  allow_config = true;
1032
1612
  i += 1;
@@ -1052,7 +1632,16 @@ pub fn run(args: &[String]) -> ExitCode {
1052
1632
  }
1053
1633
  }
1054
1634
  let root = fs::canonicalize(&root).unwrap_or(root);
1055
- let changed = changed_files(&root, staged, &explicit_files);
1635
+ let (changed, baseline) = match change_scope(&root, staged, &explicit_files, base) {
1636
+ Ok(scope) => scope,
1637
+ Err(error) => {
1638
+ eprintln!("dmb-gate slop: {error}");
1639
+ return ExitCode::from(2);
1640
+ }
1641
+ };
1642
+ let baseline = baseline.as_deref();
1643
+ let scan_scratch = !staged && explicit_files.is_empty();
1644
+ let count_prod = !allow_untested && explicit_files.is_empty() && !changed.iter().any(|f| is_test_file(f));
1056
1645
 
1057
1646
  // Parallel diff & line scanning across all changed files
1058
1647
  let per_file_findings = parallel_map(&changed, |rel| {
@@ -1067,82 +1656,141 @@ pub fn run(args: &[String]) -> ExitCode {
1067
1656
  fix: "Fix code instead of loosening guardrails, or pass --allow-config-change.",
1068
1657
  });
1069
1658
  }
1070
- let added = added_lines_for_file(&root, rel, staged);
1071
- if !added.is_empty() {
1072
- scan_added_lines(rel, &added, &mut local);
1659
+ let ext = extension(rel).to_ascii_lowercase();
1660
+ let ext = ext.as_str();
1661
+ let test_target = is_test_target(rel, ext);
1662
+ if staged && test_target && staged_test_target_is_empty(&root, rel, ext) {
1663
+ local.push(empty_test_finding(rel));
1073
1664
  }
1074
- let (mut r_added, r_hunks) = crate::reward::diff_file_hunks(&root, rel, staged, None);
1075
- if r_added.is_empty() && !added.is_empty() {
1076
- r_added = added.clone();
1665
+ let file = root.join(rel);
1666
+ let Some(text) = read_source(&file, 1_048_576) else { return (local, 0, false) };
1667
+ if !staged && test_target && ext == "py" && !python_declares_tests(&text) {
1668
+ local.push(empty_test_finding(rel));
1077
1669
  }
1078
- if !r_added.is_empty() || !r_hunks.is_empty() {
1079
- let rs_cfg_ln = if rel.ends_with(".rs") {
1080
- fs::read_to_string(root.join(rel))
1081
- .ok()
1082
- .and_then(|t| crate::reward::find_rs_cfg_test_line(&t))
1083
- } else {
1084
- None
1085
- };
1670
+ let mut added = added_lines_for_file(&root, rel, staged, baseline, &text);
1671
+ if added.is_empty() && !explicit_files.is_empty() {
1672
+ added = text.lines().enumerate().map(|(i, line)| (i + 1, line.to_owned())).collect();
1673
+ }
1674
+ let rs_cfg_ln = if ext == "rs" { crate::reward::find_rs_cfg_test_line(&text) } else { None };
1675
+ scan_added_lines_ctx(rel, &added, rs_cfg_ln, &mut local);
1676
+
1677
+ if !scan_scratch || !rel.starts_with(".scratch/") {
1678
+ let (_, r_hunks) = crate::reward::diff_file_hunks(&root, rel, staged, baseline);
1679
+ if !added.is_empty() || !r_hunks.is_empty() {
1680
+ let mypy_lines = (ext == "ini" || ext == "cfg").then(|| crate::reward::find_mypy_section_lines(&text));
1086
1681
  let mut r_findings = Vec::new();
1087
- crate::reward::scan_file_reward_hacks(rel, &r_added, &r_hunks, true, false, rs_cfg_ln, &mut r_findings);
1088
- for rf in r_findings {
1682
+ crate::reward::scan_file_reward_hacks_full(
1683
+ rel, &added, &r_hunks, true, false, rs_cfg_ln, mypy_lines.as_ref(), Some(&text), &mut r_findings,
1684
+ );
1685
+ append_reward(&mut local, r_findings);
1686
+ }
1687
+ }
1688
+ if !is_test_file(rel) && ((ext == "py" && text.contains("NotImplementedError"))
1689
+ || (ext == "rs" && (text.contains("todo!") || text.contains("unimplemented!"))))
1690
+ {
1691
+ let base = baseline.and_then(|base| git(&root, &["show", &format!("{base}:{rel}")]))
1692
+ .filter(|(ok, _)| *ok).map(|(_, text)| text).unwrap_or_default();
1693
+ scan_stub_slop(rel, ext, &base, &text, &mut local);
1694
+ }
1695
+ if matches!(rel.as_str(), ".github/dependabot.yml" | ".github/dependabot.yaml") && !added.is_empty() {
1696
+ if text.contains("cooldown:") {
1697
+ local.retain(|f| f.rule != "supply-chain-dependabot-cooldown");
1698
+ } else if !local.iter().any(|f| f.rule == "supply-chain-dependabot-cooldown") {
1089
1699
  local.push(Finding {
1090
- severity: rf.severity,
1091
- rule: rf.rule,
1092
- file: rf.file,
1093
- line: rf.line,
1094
- message: rf.message,
1095
- fix: rf.fix,
1700
+ severity: "P2",
1701
+ rule: "supply-chain-dependabot-cooldown",
1702
+ file: rel.clone(),
1703
+ line: 1,
1704
+ message: "`.github/dependabot.yml` has no `cooldown:` window.".to_string(),
1705
+ fix: "Add `cooldown: { default-days: 7 }` to reduce zero-day supply-chain exposure.",
1096
1706
  });
1097
1707
  }
1098
1708
  }
1099
- if (rel == ".github/dependabot.yml" || rel == ".github/dependabot.yaml") && !added.is_empty() {
1100
- if let Ok(dep_txt) = fs::read_to_string(root.join(rel)) {
1101
- if dep_txt.contains("cooldown:") {
1102
- local.retain(|f| f.rule != "supply-chain-dependabot-cooldown");
1103
- } else if !local.iter().any(|f| f.rule == "supply-chain-dependabot-cooldown") {
1709
+ if ext == "py" && !added.is_empty() {
1710
+ scan_python_structural(rel, &text, &added, &mut local);
1711
+ }
1712
+ let test_file = is_test_file(rel);
1713
+ if !test_file && (JS_EXTS.contains(&ext) || matches!(ext, "py" | "rs" | "go" | "sh" | "css" | "html" | "svelte")) {
1714
+ local.extend(crate::perf::scan_text(rel, &text).into_iter().filter(|f| f.severity == "high").map(|f| Finding {
1715
+ severity: "P1", rule: f.rule_id, file: f.file, line: f.line, message: f.message.into(),
1716
+ fix: "Batch DB/async calls or move sync I/O off the hot loop.",
1717
+ }));
1718
+ }
1719
+ if crate::ui::UI_EXTS.contains(&ext) {
1720
+ for uf in crate::ui::scan_ui(rel, &text) {
1721
+ if uf.severity == "P0" || uf.severity == "P1" {
1104
1722
  local.push(Finding {
1105
- severity: "P2",
1106
- rule: "supply-chain-dependabot-cooldown",
1107
- file: rel.clone(),
1108
- line: 1,
1109
- message: "`.github/dependabot.yml` has no `cooldown:` window.".to_string(),
1110
- fix: "Add `cooldown: { default-days: 7 }` to reduce zero-day supply-chain exposure.",
1723
+ severity: uf.severity,
1724
+ rule: uf.rule,
1725
+ file: uf.file,
1726
+ line: uf.line,
1727
+ message: uf.message.to_string(),
1728
+ fix: "Fix UI token/a11y/motion violation per frontend-ui.",
1111
1729
  });
1112
1730
  }
1113
1731
  }
1114
1732
  }
1115
- if rel.ends_with(".py") && !added.is_empty() {
1116
- if let Ok(py_txt) = fs::read_to_string(root.join(rel)) {
1117
- scan_python_structural(rel, &py_txt, &added, &mut local);
1733
+ let count_file = count_prod && !DIFF_EXEMPT_DIRS.contains(&rel.split('/').next().unwrap_or(""));
1734
+ let (mut production, mut test_touched) = (0, false);
1735
+ if (ext == "rs" || ext == "go" || JS_EXTS.contains(&ext))
1736
+ && (test_target && !staged || !added.is_empty() && (ext == "rs" || test_file || count_file))
1737
+ {
1738
+ let tokens = source_tokens(&text, ext);
1739
+ if !staged && test_target && !brace_declares_tests(&tokens, ext) {
1740
+ local.push(empty_test_finding(rel));
1118
1741
  }
1119
- }
1120
- let is_ui = Path::new(rel)
1121
- .extension()
1122
- .and_then(|e| e.to_str())
1123
- .map(|s| crate::ui::UI_EXTS.contains(&s.to_ascii_lowercase().as_str()))
1124
- .unwrap_or(false);
1125
- if is_ui {
1126
- if let Ok(txt) = fs::read_to_string(root.join(rel)) {
1127
- for uf in crate::ui::scan_ui(rel, &txt) {
1128
- if uf.severity == "P0" || uf.severity == "P1" {
1129
- local.push(Finding {
1130
- severity: uf.severity,
1131
- rule: uf.rule,
1132
- file: uf.file,
1133
- line: uf.line,
1134
- message: uf.message.to_string(),
1135
- fix: "Fix UI token/a11y/motion violation per frontend-ui.",
1136
- });
1137
- }
1742
+ let added_lines: BTreeSet<_> = added.iter().map(|(line, _)| *line).collect();
1743
+ let mut rust_tests = false;
1744
+ if ext == "rs" {
1745
+ for (start, end) in rust_test_ranges(&tokens) {
1746
+ rust_tests = true;
1747
+ test_touched |= added_lines.range(start..=end).next().is_some();
1138
1748
  }
1139
1749
  }
1750
+ if test_file || rust_tests {
1751
+ scan_brace_tests(rel, ext, &tokens, &added_lines, &mut local);
1752
+ }
1753
+ if count_file {
1754
+ let mut last = 0;
1755
+ production = tokens.iter().filter(|t| {
1756
+ let first = t.line != last;
1757
+ last = t.line;
1758
+ first && added_lines.contains(&t.line)
1759
+ }).count();
1760
+ }
1761
+ } else if count_file && ext == "py" {
1762
+ production = added.iter().filter(|(_, line)| {
1763
+ let code = line.trim_start();
1764
+ !code.is_empty() && !code.starts_with('#')
1765
+ }).count();
1140
1766
  }
1141
- local
1767
+ (local, production, test_touched)
1142
1768
  });
1143
1769
 
1144
- let mut findings: Vec<Finding> = per_file_findings.into_iter().flatten().collect();
1770
+ let mut findings = Vec::new();
1771
+ let (mut total, mut largest, mut test_touched) = (0, ("", 0), false);
1772
+ for (file, (local, production, tests)) in changed.iter().zip(per_file_findings) {
1773
+ findings.extend(local);
1774
+ total += production;
1775
+ test_touched |= tests;
1776
+ if production > largest.1 {
1777
+ largest = (file.as_str(), production);
1778
+ }
1779
+ }
1780
+ if total >= 30 && !test_touched && git_paths(&root, &["ls-files", "-z"]).any(|f| is_test_file(&f)) {
1781
+ findings.push(Finding {
1782
+ severity: "P1", rule: "untested-code-diff", file: largest.0.to_owned(), line: 1,
1783
+ message: "At least 30 production lines were added without changing any tests.".into(),
1784
+ fix: "Add behavioral regression tests or pass --allow-untested for an approved exception.",
1785
+ });
1786
+ }
1787
+ if scan_scratch {
1788
+ scan_scratch_reward(&root, &mut findings);
1789
+ }
1145
1790
  check_policy_xml(&root, &changed, &mut findings);
1791
+ let sim_changed = if explicit_files.is_empty() { None } else { Some(changed.as_slice()) };
1792
+ let sim_base = if staged || !explicit_files.is_empty() { None } else { baseline };
1793
+ findings.extend(crate::sim::check(&root, sim_changed, staged, sim_base).findings);
1146
1794
 
1147
1795
  let linters = if no_linters {
1148
1796
  Vec::new()
@@ -1232,7 +1880,125 @@ mod tests {
1232
1880
  assert_eq!(out[0].rule, "supply-chain-dependabot-cooldown");
1233
1881
 
1234
1882
  let explicit = vec![".github/dependabot.yml,./src/a.py".to_string()];
1235
- let norm = changed_files(Path::new("."), false, &explicit);
1883
+ let (norm, _) = change_scope(Path::new("."), false, &explicit, None).unwrap();
1236
1884
  assert_eq!(norm, vec![".github/dependabot.yml", "src/a.py"]);
1237
1885
  }
1886
+
1887
+ fn git_ok(root: &Path, args: &[&str]) {
1888
+ let status = Command::new("git")
1889
+ .args(["-c", "core.hooksPath=disabled-hooks", "-c", "commit.gpgsign=false", "-C"])
1890
+ .arg(root).args(args).status().unwrap();
1891
+ assert!(status.success(), "git {args:?}");
1892
+ }
1893
+
1894
+ #[test]
1895
+ fn clean_feature_commit_and_explicit_base_include_the_right_changes() {
1896
+ let root = crate::tests::TestRepo::new("branch");
1897
+ let root = &root.0;
1898
+ git_ok(root, &["init", "-q", "-b", "main"]);
1899
+ git_ok(root, &["config", "user.email", "test@example.com"]);
1900
+ git_ok(root, &["config", "user.name", "Gate Test"]);
1901
+ let path = root.join("app.py");
1902
+ fs::write(&path, "def legacy():\n raise NotImplementedError\n").unwrap();
1903
+ git_ok(root, &["add", "."]);
1904
+ git_ok(root, &["commit", "-qm", "main"]);
1905
+ let (files, _) = change_scope(root, false, &[], None).unwrap();
1906
+ assert!(files.is_empty(), "{files:?}");
1907
+ git_ok(root, &["switch", "-qc", "feature"]);
1908
+ let text = "def legacy():\n raise NotImplementedError\n\ndef added():\n raise NotImplementedError\n";
1909
+ fs::write(&path, text).unwrap();
1910
+ git_ok(root, &["add", "."]);
1911
+ git_ok(root, &["commit", "-qm", "feature"]);
1912
+ let (files, baseline) = change_scope(root, false, &[], None).unwrap();
1913
+ assert_eq!(files, ["app.py"]);
1914
+ let baseline = baseline.unwrap();
1915
+ let added = added_lines_for_file(root, "app.py", false, Some(&baseline), text);
1916
+ assert_eq!(added.last().map(|(line, _)| *line), Some(5));
1917
+ let mut findings = Vec::new();
1918
+ let (_, old) = git(root, &["show", &format!("{baseline}:app.py")]).unwrap();
1919
+ scan_stub_slop("app.py", "py", &old, text, &mut findings);
1920
+ assert_eq!(findings.iter().map(|f| (f.rule, f.line)).collect::<Vec<_>>(), [("stub-placeholder", 5)]);
1921
+ let args = ["--root".into(), root.to_string_lossy().into_owned(), "--no-linters".into(), "--json".into()];
1922
+ assert_eq!(run(&args), ExitCode::from(1));
1923
+
1924
+ fs::write(root.join("local.go"), "package demo\n").unwrap();
1925
+ let (files, _) = change_scope(root, false, &[], Some("main")).unwrap();
1926
+ assert_eq!(files, ["app.py", "local.go"]);
1927
+ let (files, _) = change_scope(root, false, &[], None).unwrap();
1928
+ assert_eq!(files, ["local.go"]);
1929
+ assert!(change_scope(root, false, &[], Some("bad-ref")).is_err());
1930
+ }
1931
+
1932
+ fn declares_tests(rel: &str, text: &str) -> bool {
1933
+ let ext = extension(rel).to_ascii_lowercase();
1934
+ assert!(is_test_target(rel, &ext), "{rel}");
1935
+ if ext == "py" {
1936
+ python_declares_tests(text)
1937
+ } else {
1938
+ brace_declares_tests(&source_tokens(text, &ext), &ext)
1939
+ }
1940
+ }
1941
+
1942
+ #[test]
1943
+ fn empty_test_targets_ignore_comments_strings_and_non_target_helpers() {
1944
+ for (rel, text) in [
1945
+ ("empty.test.mjs", ""),
1946
+ ("fake.spec.ts", "/* it('fake', () => {}); */\nconst text = `test('fake', () => {});`;\n"),
1947
+ ("test_fake.py", "# def test_fake(): ...\ntext = \"\"\"\nclass TestFake:\n def test_fake(self): ...\n\"\"\"\n"),
1948
+ ("fake_test.go", "package demo\n/* func TestFake(t *testing.T) {} */\nvar raw = `func TestFake(t *testing.T) {}`\n"),
1949
+ ("tests/fake.rs", "/* outer /* nested */ #[test] fn fake() {} */\nconst RAW: &str = r##\"#[test] fn fake() {}\"##;\n"),
1950
+ ] {
1951
+ assert!(!declares_tests(rel, text), "{rel}");
1952
+ }
1953
+ for (rel, text) in [
1954
+ ("real.test.mjs", "import {test} from 'node:test';\nfunction checks() { assert.equal(Number('7'), 7); }\ntest('parses a digit', checks);\n"),
1955
+ ("test_real.py", "import unittest\nclass Contract(unittest.TestCase):\n def testRoundTrip(self):\n self.assertEqual(bytes.fromhex('71'), b'q')\n"),
1956
+ ("real_test.go", "package demo\nimport \"testing\"\nfunc TestContract(t *testing.T) { if parse() != 7 { t.Fatal(\"parse\") } }\n"),
1957
+ ("tests/real.rs", "#[test]\nfn contract() { assert_eq!(\"7\".parse::<u32>().unwrap(), 7); }\n"),
1958
+ ] {
1959
+ assert!(declares_tests(rel, text), "{rel}");
1960
+ }
1961
+ assert!(!is_test_target("tests/helper.py", "py"));
1962
+ assert!(!is_test_target("tests/common/mod.rs", "rs"));
1963
+ assert!(is_test_target("tests/real.rs", "rs"));
1964
+ }
1965
+
1966
+ #[test]
1967
+ fn brace_test_theater_distinguishes_comments_literals_and_oracles() {
1968
+ for (rel, text, expected) in [
1969
+ ("test/example.mjs", format!("test('}}', () => {{ /* expect({t}) }} */ }});\nit('no', () => {{ const x = 'expect({t})'; }});\nit('fake', () => expect({t}).toBe({t}));\nit('real', () => assert.equal(get(), 7));", t = "true"), vec![(1, "test-theater-empty"), (2, "test-theater-no-assert"), (3, "test-theater-tautology")]),
1970
+ ("example.test.ts", format!("test('empty', async ({{ obj }}) => {{}});\ntest('bad', function () {{ run(); }});\ntest('false', () => expect({f}).toBe({f}));\ntest('one', () => expect({n}).toBe({n}));", f = "false", n = 1), vec![(1, "test-theater-empty"), (2, "test-theater-no-assert"), (3, "test-theater-tautology"), (4, "test-theater-tautology")]),
1971
+ ("src/lib.rs", format!("#[cfg(test)] mod tests {{\n#[test] fn empty() {{ /* assert!({t}) */ }}\n#[tokio::test] async fn no_oracle() {{ run(); }}\n#[test] fn fake() {{ assert!({t}); assert_eq!({n}, {n}); }}\n#[should_panic] #[test] fn contract() {{ rejects_bad_input(); }}\n#[test] fn result() -> Result<(), Error> {{ verify_operation()?; Ok(()) }}\n}}", t = "true", n = 1), vec![(2, "test-theater-empty"), (3, "test-theater-no-assert"), (4, "test-theater-tautology"), (4, "test-theater-tautology")]),
1972
+ ("app_test.go", "func TestEmpty(t *testing.T) { // t.Error()\n}\nfunc TestNoOracle(t *testing.T) { _ = `t.Fatal(\"}\")` }\nfunc TestReal(t *testing.T) { if x() != 2 { t.Errorf(\"unexpected result\") } }".to_owned(), vec![(1, "test-theater-empty"), (3, "test-theater-no-assert")]),
1973
+ ] {
1974
+ let ext = extension(rel);
1975
+ let tokens = source_tokens(&text, ext);
1976
+ let added = (1..=text.lines().count()).collect();
1977
+ let mut findings = Vec::new();
1978
+ scan_brace_tests(rel, ext, &tokens, &added, &mut findings);
1979
+ assert_eq!(findings.iter().map(|f| (f.line, f.rule)).collect::<Vec<_>>(), expected, "{rel}");
1980
+ }
1981
+ }
1982
+
1983
+ #[test]
1984
+ fn slop_blocks_untested_code_and_scans_ignored_scratch_reward_hacks() {
1985
+ let root = crate::tests::TestRepo::new("slop");
1986
+ let root = &root.0;
1987
+ git_ok(root, &["init", "-q", "-b", "main"]);
1988
+ fs::write(root.join(".gitignore"), ".scratch/\n").unwrap();
1989
+ fs::write(root.join("test_app.py"), "def test_contract():\n assert produced() == 'expected'\n").unwrap();
1990
+ git_ok(root, &["add", "."]);
1991
+ git_ok(root, &["-c", "user.name=Gate Test", "-c", "user.email=test@example.com", "commit", "-qm", "base"]);
1992
+ fs::write(root.join("app.py"), (0..30).map(|i| format!("value_{i} = {i}\n")).collect::<String>()).unwrap();
1993
+ let mut args = vec!["--root".into(), root.to_string_lossy().into_owned(), "--no-linters".into()];
1994
+ assert_eq!(run(&args), ExitCode::from(1));
1995
+ args.push("--allow-untested".into());
1996
+ assert_eq!(run(&args), ExitCode::SUCCESS);
1997
+ fs::create_dir(root.join(".scratch")).unwrap();
1998
+ fs::write(root.join(".scratch/score.ps1"), "npx playwright test --update-snapshots=all\n").unwrap();
1999
+ assert_eq!(run(&args), ExitCode::from(1));
2000
+ let mut findings = Vec::new();
2001
+ scan_scratch_reward(root, &mut findings);
2002
+ assert!(findings.iter().any(|f| f.rule == "reward-hack-snapshot-overwrite" && f.file == ".scratch/score.ps1"));
2003
+ }
1238
2004
  }