1use std::collections::{BTreeMap, BTreeSet};
7use std::path::Path;
8
9use regex::Regex;
10use sha2::{Digest, Sha256};
11
12use crate::tools::paths::{Class, Protected};
13use crate::tools::policy::Policy;
14use crate::worktree::{Change, ChangeKind};
15
16const SKIPPED_DIRS: &[&str] = &[
19 ".git",
20 "target",
21 "node_modules",
22 ".venv",
23 "venv",
24 "__pycache__",
25 ".tox",
26 ".mypy_cache",
27 ".pytest_cache",
28];
29
30#[derive(Debug, Clone, Default, PartialEq, Eq)]
34pub struct JudgeSnapshot(BTreeMap<String, String>);
35
36#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
38pub struct Drift {
39 pub path: String,
41 pub class: &'static str,
43 pub change: &'static str,
45}
46
47impl JudgeSnapshot {
48 #[must_use]
51 pub fn take(root: &Path, policy: &Policy) -> Self {
52 let mut files = BTreeMap::new();
53 let walk = ignore::WalkBuilder::new(root)
54 .hidden(false)
55 .ignore(false)
56 .git_ignore(false)
57 .git_global(false)
58 .git_exclude(false)
59 .parents(false)
60 .follow_links(false)
61 .filter_entry(|e| {
62 !(e.depth() > 0
63 && e.file_type().is_some_and(|t| t.is_dir())
64 && SKIPPED_DIRS.contains(&e.file_name().to_string_lossy().as_ref()))
65 })
66 .build();
67 for entry in walk.flatten() {
68 if !entry.file_type().is_some_and(|t| t.is_file()) {
69 continue;
70 }
71 let Ok(rel) = entry.path().strip_prefix(root) else {
72 continue;
73 };
74 let rel = rel.to_string_lossy().replace('\\', "/");
75 if class_of(policy, &rel).is_none() {
76 continue;
77 }
78 if let Ok(bytes) = std::fs::read(entry.path()) {
79 files.insert(rel, sha256_hex(&bytes));
80 }
81 }
82 Self(files)
83 }
84
85 #[must_use]
87 pub fn entries(&self) -> &BTreeMap<String, String> {
88 &self.0
89 }
90
91 #[must_use]
93 pub fn from_entries(entries: BTreeMap<String, String>) -> Self {
94 Self(entries)
95 }
96
97 pub fn set(&mut self, path: &str, hash: String) {
99 self.0.insert(path.to_owned(), hash);
100 }
101
102 #[must_use]
105 pub fn drift(&self, later: &Self, policy: &Policy, approved: &BTreeSet<String>) -> Vec<Drift> {
106 let mut out = Vec::new();
107 let paths: BTreeSet<&String> = self.0.keys().chain(later.0.keys()).collect();
108 for path in paths {
109 let change = match (self.0.get(path), later.0.get(path)) {
110 (None, Some(_)) => "added",
111 (Some(_), None) => "deleted",
112 (Some(a), Some(b)) if a != b => "modified",
113 _ => continue,
114 };
115 if approved.contains(path.as_str()) {
116 continue;
117 }
118 if let Some(class) = class_of(policy, path) {
119 out.push(Drift {
120 path: path.clone(),
121 class,
122 change,
123 });
124 }
125 }
126 out
127 }
128}
129
130fn class_of(policy: &Policy, rel: &str) -> Option<&'static str> {
131 match policy.write_protected(rel) {
132 Some(Class::Judge) => Some("judge"),
133 Some(Class::Intent) => Some("intent"),
134 Some(_) => None,
135 None if policy.protected().is_context(rel) => Some("context"),
136 None => None,
137 }
138}
139
140const TEST_MARKERS: &str = r"#\[(tokio::)?test\b|^\s*def test_|^\s*(async\s+)?fn test_|\b(it|test)\s*\(\s*['\x22`]|@Test\b|^\s*func Test";
142const SKIP_MARKERS: &str = r"#\[ignore\b|@pytest\.mark\.(skip|xfail)|\.skip\s*\(|\bx(it|describe|test)\s*\(|@Disabled\b|@Ignore\b|\bt\.Skip(Now)?\s*\(|@unittest\.skip|\.todo\s*\(";
144
145const TEST_NAMES: &str = r#"(?m)#\[(?:tokio::)?test\b[^\]]*\]\s*(?:#\[[^\]]*\]\s*)*(?:pub(?:\([^)]*\))?\s+)?(?:async\s+)?fn\s+(\w+)|^\s*(?:async\s+)?def\s+(test_\w+)|^\s*func\s+(Test\w+)|\b(?:it|test)\s*\(\s*['"`]([^'"`]+)['"`]"#;
148
149#[must_use]
151pub fn removed_tests(before: &str, after: &str) -> Vec<String> {
152 let Ok(re) = Regex::new(TEST_NAMES) else {
153 return Vec::new();
154 };
155 let names = |text: &str| -> Vec<String> {
156 re.captures_iter(text)
157 .filter_map(|c| {
158 c.iter()
159 .skip(1)
160 .flatten()
161 .next()
162 .map(|m| m.as_str().to_owned())
163 })
164 .collect()
165 };
166 let kept: BTreeSet<String> = names(after).into_iter().collect();
167 let mut gone = names(before);
168 gone.retain(|n| !kept.contains(n));
169 gone.dedup();
170 gone
171}
172
173const PLACEHOLDER_MARKERS: &str = r#"\braise\s+NotImplementedError\b|\btodo!\s*\(|\bunimplemented!\s*\(|(?i:throw\s+new\s+Error\s*\(\s*['"`](?:not implemented|todo|placeholder))|(?i:\b(?:t\.Fatal|pytest\.fail|fail)\s*\(\s*['"`](?:not implemented|todo|placeholder))"#;
176
177#[must_use]
181pub fn has_placeholder(text: &str) -> bool {
182 Regex::new(PLACEHOLDER_MARKERS).is_ok_and(|r| r.is_match(text))
183}
184
185#[must_use]
187pub fn has_skip_marker(text: &str) -> bool {
188 Regex::new(SKIP_MARKERS).is_ok_and(|r| r.is_match(text))
189}
190
191#[must_use]
194pub fn only_additions(old: &str, new: &str) -> bool {
195 let mut new_lines = new.lines();
196 old.lines().all(|line| new_lines.any(|n| n == line))
197}
198
199#[must_use]
205pub fn audit(
206 changes: &[Change],
207 patch: &str,
208 frozen: &BTreeSet<String>,
209 additions_ok: bool,
210 approved: &BTreeSet<String>,
211) -> Vec<String> {
212 audit_in(
213 &Protected::default(),
214 changes,
215 patch,
216 frozen,
217 additions_ok,
218 approved,
219 )
220}
221
222#[must_use]
224pub fn audit_in(
225 protected: &Protected,
226 changes: &[Change],
227 patch: &str,
228 frozen: &BTreeSet<String>,
229 additions_ok: bool,
230 approved: &BTreeSet<String>,
231) -> Vec<String> {
232 let mut findings = Vec::new();
233 let removed_lines = removed_lines(patch);
234
235 for c in changes {
236 if frozen
237 .iter()
238 .any(|f| f.to_lowercase() == c.path.to_lowercase())
239 {
240 match c.kind {
241 ChangeKind::Deleted => findings.push(format!("frozen test deleted: {}", c.path)),
242 ChangeKind::Modified
243 if additions_ok && removed_lines.get(&c.path).copied().unwrap_or(0) == 0 => {}
244 ChangeKind::Modified => findings.push(format!("frozen test modified: {}", c.path)),
245 ChangeKind::Added => {}
246 }
247 }
248 match protected.write_class(&c.path) {
249 Some(Class::Judge) => findings.push(format!("verification input changed: {}", c.path)),
250 Some(Class::Intent) => findings.push(format!("spec changed: {}", c.path)),
251 None if protected.is_context(&c.path) && !approved.contains(&c.path) => {
252 findings.push(format!("agent context file changed: {}", c.path));
253 }
254 _ => {}
255 }
256 }
257
258 let (Ok(test), Ok(skip)) = (Regex::new(TEST_MARKERS), Regex::new(SKIP_MARKERS)) else {
259 return findings;
260 };
261 let mut tests: BTreeMap<String, (usize, usize)> = BTreeMap::new(); let mut text: BTreeMap<String, (String, String)> = BTreeMap::new(); let mut skips: BTreeSet<String> = BTreeSet::new();
264 let mut file = String::new();
265 for line in patch.lines() {
266 if let Some(header) = line.strip_prefix("diff --git a/") {
267 file = header
270 .split_once(" b/")
271 .map_or(header, |(a, _)| a)
272 .to_owned();
273 } else if line.starts_with("+++ ") || line.starts_with("--- ") {
274 } else if let Some(added) = line.strip_prefix('+') {
276 let t = text.entry(file.clone()).or_default();
277 t.0.push_str(added);
278 t.0.push('\n');
279 if test.is_match(added) {
280 tests.entry(file.clone()).or_default().0 += 1;
281 }
282 if skip.is_match(added) {
283 skips.insert(file.clone());
284 }
285 } else if let Some(removed) = line.strip_prefix('-') {
286 let t = text.entry(file.clone()).or_default();
287 t.1.push_str(removed);
288 t.1.push('\n');
289 if test.is_match(removed) {
290 tests.entry(file.clone()).or_default().1 += 1;
291 }
292 }
293 }
294 let deleted: BTreeSet<&str> = changes
295 .iter()
296 .filter(|c| c.kind == ChangeKind::Deleted)
297 .map(|c| c.path.as_str())
298 .collect();
299 for (path, (added, removed)) in tests {
300 if removed > added && !deleted.contains(path.as_str()) {
302 let names = text
303 .get(&path)
304 .map(|(a, r)| removed_tests(r, a))
305 .unwrap_or_default();
306 let named = if names.is_empty() {
307 String::new()
308 } else {
309 format!(": {}", names.join(", "))
310 };
311 findings.push(format!(
312 "test removed in {path} ({removed} removed, {added} added){named}"
313 ));
314 }
315 }
316 for path in skips {
317 findings.push(format!("skip marker added in {path}"));
318 }
319 findings
320}
321
322fn removed_lines(patch: &str) -> BTreeMap<String, usize> {
324 let mut out: BTreeMap<String, usize> = BTreeMap::new();
325 let mut file = String::new();
326 for line in patch.lines() {
327 if let Some(header) = line.strip_prefix("diff --git a/") {
328 file = header
329 .split_once(" b/")
330 .map_or(header, |(a, _)| a)
331 .to_owned();
332 } else if line.starts_with('-') && !line.starts_with("--- ") {
333 *out.entry(file.clone()).or_default() += 1;
334 }
335 }
336 out
337}
338
339#[must_use]
342pub fn sha256_hex(bytes: &[u8]) -> String {
343 Sha256::digest(bytes)
344 .iter()
345 .map(|b| format!("{b:02x}"))
346 .collect()
347}
348
349pub(crate) fn untick(bytes: &[u8]) -> Vec<u8> {
351 let mut out = bytes.to_vec();
352 for i in 1..out.len().saturating_sub(1) {
353 if out[i - 1] == b'[' && out[i + 1] == b']' && matches!(out[i], b'x' | b'X') {
354 out[i] = b' ';
355 }
356 }
357 out
358}
359
360#[cfg(test)]
361mod tests {
362
363 use super::*;
364
365 fn change(path: &str, kind: ChangeKind) -> Change {
366 Change {
367 path: path.to_owned(),
368 kind,
369 }
370 }
371
372 #[test]
373 fn removed_tests_are_named_across_languages() {
374 let before = "#[cfg(test)]\nmod tests {\n #[test]\n fn it_works() {}\n #[tokio::test]\n async fn later() {}\n}\ndef test_py(): pass\nfunc TestGo(t *testing.T) {}\nit('greets', () => {})\n";
375 assert_eq!(
376 removed_tests(before, "#[test]\nfn later() {}\n"),
377 ["it_works", "test_py", "TestGo", "greets"]
378 );
379 assert!(removed_tests(before, before).is_empty());
380 }
381
382 #[test]
383 fn flags_tampering_and_passes_clean_diffs() {
384 let frozen: BTreeSet<String> = ["tests/api.rs".to_owned()].into();
385 let patch = "diff --git a/src/lib.rs b/src/lib.rs\n--- a/src/lib.rs\n+++ b/src/lib.rs\n@@ -1 +1 @@\n- #[test]\n+ #[ignore]\n+ #[test]\n";
386 let f = audit(
387 &[
388 change("tests/api.rs", ChangeKind::Deleted),
389 change("speccoder.toml", ChangeKind::Modified),
390 ],
391 patch,
392 &frozen,
393 false,
394 &BTreeSet::new(),
395 );
396 assert_eq!(
397 f,
398 [
399 "frozen test deleted: tests/api.rs",
400 "verification input changed: speccoder.toml",
401 "skip marker added in src/lib.rs",
402 ]
403 );
404
405 let removed = "diff --git a/src/lib.rs b/src/lib.rs\n--- a/src/lib.rs\n+++ b/src/lib.rs\n@@ -5,4 +4,0 @@\n- #[test]\n- fn a() {}\n";
406 assert_eq!(
407 audit(&[], removed, &BTreeSet::new(), false, &BTreeSet::new()),
408 ["test removed in src/lib.rs (1 removed, 0 added): a"]
409 );
410
411 let clean = "diff --git a/src/lib.rs b/src/lib.rs\n--- a/src/lib.rs\n+++ b/src/lib.rs\n@@ -1 +1,4 @@\n+pub fn add() {}\n+ #[test]\n+ fn adds() {}\n";
412 assert!(
413 audit(
414 &[
415 change("src/lib.rs", ChangeKind::Modified),
416 change("tests/new.rs", ChangeKind::Added)
417 ],
418 clean,
419 &frozen,
420 false,
421 &BTreeSet::new()
422 )
423 .is_empty()
424 );
425 }
426
427 #[test]
428 fn additions_to_a_frozen_test_pass_only_in_additions_mode() {
429 let frozen: BTreeSet<String> = ["tests/api.rs".to_owned()].into();
430 let added = "diff --git a/tests/api.rs b/tests/api.rs\n--- a/tests/api.rs\n+++ b/tests/api.rs\n@@ -1,2 +1,4 @@\n #[test]\n fn a() {}\n+#[test]\n+fn b() {}\n";
431 let changed = "diff --git a/tests/api.rs b/tests/api.rs\n--- a/tests/api.rs\n+++ b/tests/api.rs\n@@ -1,2 +1,2 @@\n #[test]\n-fn a() { assert!(x()) }\n+fn a() {}\n";
432 let modified = [change("tests/api.rs", ChangeKind::Modified)];
433 assert!(audit(&modified, added, &frozen, true, &BTreeSet::new()).is_empty());
434 assert_eq!(
435 audit(&modified, added, &frozen, false, &BTreeSet::new()),
436 ["frozen test modified: tests/api.rs"]
437 );
438 assert_eq!(
439 audit(&modified, changed, &frozen, true, &BTreeSet::new()),
440 ["frozen test modified: tests/api.rs"]
441 );
442
443 assert!(only_additions("a\nb\n", "a\nnew\nb\nmore\n"));
444 assert!(!only_additions("a\nb\n", "a\nB\n"));
445 assert!(!only_additions("a\nb\n", "b\na\n"));
446 }
447
448 #[test]
449 fn a_snapshot_sees_ignored_judge_inputs_and_reports_drift() {
450 use crate::tools::policy::Policy;
451 let dir = tempfile::tempdir().unwrap();
452 let root = dir.path();
453 std::fs::create_dir_all(root.join(".claude")).unwrap();
454 std::fs::create_dir_all(root.join("target/debug")).unwrap();
455 std::fs::write(root.join(".claude/settings.json"), "{}").unwrap();
456 std::fs::write(root.join("AGENTS.md"), "a").unwrap();
457 std::fs::write(root.join("speccoder.toml"), "x").unwrap();
458 std::fs::write(root.join("src.rs"), "free").unwrap();
459 std::fs::write(root.join("target/debug/speccoder.toml"), "skipped").unwrap();
460 let policy = Policy::new(&[], &[]);
461 let before = JudgeSnapshot::take(root, &policy);
462 assert_eq!(
463 before.0.len(),
464 3,
465 "{:?}",
466 before.0.keys().collect::<Vec<_>>()
467 );
468
469 std::fs::write(root.join(".claude/settings.local.json"), "{}").unwrap();
470 std::fs::write(root.join("AGENTS.md"), "b").unwrap();
471 std::fs::remove_file(root.join("speccoder.toml")).unwrap();
472 std::fs::write(root.join("src.rs"), "changed").unwrap();
473 let after = JudgeSnapshot::take(root, &policy);
474 let drift = before.drift(&after, &policy, &BTreeSet::new());
475 let seen: Vec<(&str, &str, &str)> = drift
476 .iter()
477 .map(|d| (d.path.as_str(), d.class, d.change))
478 .collect();
479 assert_eq!(
480 seen,
481 [
482 (".claude/settings.local.json", "judge", "added"),
483 ("AGENTS.md", "context", "modified"),
484 ("speccoder.toml", "judge", "deleted"),
485 ]
486 );
487 let approved: BTreeSet<String> = ["AGENTS.md".to_owned()].into();
489 assert_eq!(before.drift(&after, &policy, &approved).len(), 2);
490 std::fs::write(root.join("AGENTS.md"), "a").unwrap();
492 std::fs::write(root.join("speccoder.toml"), "x").unwrap();
493 std::fs::remove_file(root.join(".claude/settings.local.json")).unwrap();
494 assert!(
495 before
496 .drift(
497 &JudgeSnapshot::take(root, &policy),
498 &policy,
499 &BTreeSet::new()
500 )
501 .is_empty()
502 );
503 }
504
505 #[test]
509 fn a_judge_input_in_another_letter_case_is_drift() {
510 use crate::tools::policy::Policy;
511 let dir = tempfile::tempdir().unwrap();
512 let root = dir.path();
513 let policy = Policy::new(&[], &[]);
514 let before = JudgeSnapshot::take(root, &policy);
515 std::fs::create_dir_all(root.join(".CLAUDE")).unwrap();
516 std::fs::write(root.join(".CLAUDE/settings.json"), "{}").unwrap();
517 std::fs::create_dir_all(root.join(".Cursor")).unwrap();
518 std::fs::write(root.join(".Cursor/rules.json"), "{}").unwrap();
519 std::fs::write(root.join("Makefile.x"), "free").unwrap();
520 std::fs::write(root.join("MAKEFILE"), "all:").unwrap();
521 let after = JudgeSnapshot::take(root, &policy);
522 let drift: Vec<&str> = before
523 .drift(&after, &policy, &BTreeSet::new())
524 .iter()
525 .map(|d| d.class)
526 .collect();
527 assert_eq!(drift, ["judge", "judge", "judge"], "{:?}", after.0.keys());
528 let frozen: BTreeSet<String> = ["tests/api.rs".to_owned()].into();
530 assert_eq!(
531 audit(
532 &[change("Tests/API.rs", ChangeKind::Deleted)],
533 "",
534 &frozen,
535 false,
536 &BTreeSet::new()
537 ),
538 ["frozen test deleted: Tests/API.rs"]
539 );
540 }
541
542 #[test]
543 fn a_placeholder_test_is_known_in_each_language() {
544 for text in [
545 "def test_a():\n raise NotImplementedError(\"later\")\n",
546 "#[test] fn a() { todo!() }",
547 "#[test] fn a() { unimplemented!(\"x\") }",
548 "it('a', () => { throw new Error('Not implemented') })",
549 "func TestA(t *testing.T) { t.Fatal(\"not implemented\") }",
550 ] {
551 assert!(has_placeholder(text), "{text}");
552 }
553 for text in [
554 "def test_a():\n with pytest.raises(NotImplementedError):\n f()\n",
555 "#[test] fn a() { assert_eq!(f(), 2) }",
556 "it('a', () => expect(() => f()).toThrow('not implemented'))",
557 ] {
558 assert!(!has_placeholder(text), "{text}");
559 }
560 }
561}