claude-dev-env 2.31.0 → 2.31.1

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 (47) hide show
  1. package/docs/CODE_RULES.md +2 -1
  2. package/hooks/blocking/code_rules_duplicate_body.py +272 -100
  3. package/hooks/blocking/code_rules_enforcer.py +32 -14
  4. package/hooks/blocking/code_rules_shared.py +64 -14
  5. package/hooks/blocking/pr_description_writer_gate.py +18 -25
  6. package/hooks/blocking/tdd_enforcer.py +8 -4
  7. package/hooks/blocking/test_code_rules_enforcer_ephemeral.py +12 -1
  8. package/hooks/blocking/test_code_rules_enforcer_ephemeral_repository_root.py +118 -0
  9. package/hooks/blocking/test_code_rules_enforcer_same_file_inline_duplicate.py +244 -0
  10. package/hooks/blocking/test_code_rules_enforcer_split_entry_2.py +22 -0
  11. package/hooks/blocking/test_pr_description_writer_gate.py +21 -3
  12. package/hooks/blocking/test_pre_tool_use_dispatcher_native.py +9 -2
  13. package/hooks/blocking/test_state_description_blocker.py +99 -53
  14. package/hooks/blocking/test_tdd_enforcer.py +64 -0
  15. package/hooks/hooks_constants/pr_description_writer_gate_constants.py +34 -0
  16. package/hooks/hooks_constants/subprocess_budget_completeness_content.py +2 -2
  17. package/hooks/hooks_constants/test_multi_edit_reconstruction.py +1 -0
  18. package/hooks/hooks_constants/test_subprocess_budget_completeness_content.py +33 -0
  19. package/hooks/observability/pr_description_writer_spawn_tracker.py +4 -12
  20. package/hooks/observability/test_pr_description_writer_spawn_tracker.py +6 -2
  21. package/hooks/validators/abbreviation_checks.py +3 -3
  22. package/hooks/validators/code_quality_checks.py +4 -4
  23. package/hooks/validators/config/baseline_identity_constants.py +12 -0
  24. package/hooks/validators/config/directory_exemption_constants.py +44 -1
  25. package/hooks/validators/config/validator_base_constants.py +9 -0
  26. package/hooks/validators/fast_save_validators.py +23 -80
  27. package/hooks/validators/pr_reference_checks.py +2 -2
  28. package/hooks/validators/python_antipattern_checks.py +3 -3
  29. package/hooks/validators/python_style_checks.py +3 -2
  30. package/hooks/validators/react_checks.py +2 -9
  31. package/hooks/validators/run_all_validators.py +190 -145
  32. package/hooks/validators/security_checks.py +3 -3
  33. package/hooks/validators/test_directory_exemption_constants.py +30 -24
  34. package/hooks/validators/test_fast_save_validators.py +16 -16
  35. package/hooks/validators/test_hook_timing_harness.py +10 -1
  36. package/hooks/validators/test_run_all_validators_pretooluse.py +161 -0
  37. package/hooks/validators/test_run_all_validators_repository_root.py +202 -0
  38. package/hooks/validators/test_validator_base.py +51 -2
  39. package/hooks/validators/todo_checks.py +2 -2
  40. package/hooks/validators/type_safety_checks.py +3 -3
  41. package/hooks/validators/useless_test_checks.py +3 -3
  42. package/hooks/validators/validator_base.py +73 -1
  43. package/package.json +1 -1
  44. package/scripts/dev_env_scripts_constants/grok_worker_constants.py +15 -0
  45. package/scripts/grok_headless_runner.py +15 -12
  46. package/scripts/shared_tree_paths.py +70 -0
  47. package/scripts/test_shared_tree_paths.py +143 -0
@@ -9,6 +9,7 @@ import argparse
9
9
  import ast
10
10
  import json
11
11
  import os
12
+ import re
12
13
  import subprocess
13
14
  import sys
14
15
  import tempfile
@@ -20,17 +21,29 @@ from pathlib import Path
20
21
  from typing import Callable, Dict, List, Optional, Tuple
21
22
 
22
23
  from ._path_setup import hooks_directory_on_path # noqa: F401
24
+ from .config.baseline_identity_constants import (
25
+ QUALIFIED_SCOPE_NAME_SEPARATOR,
26
+ SCOPE_NAME_PLACEHOLDER,
27
+ SHAPE_NUMBER_PLACEHOLDER,
28
+ STANDALONE_NUMBER_PATTERN,
29
+ WORD_BOUNDARY_PATTERN,
30
+ )
23
31
  from .config.directory_exemption_constants import (
24
32
  ALL_DIRECTORY_EXEMPTION_SEGMENT_NAMES,
25
33
  ALL_DIRECTORY_EXEMPTION_SUBSTRING_PATTERNS,
34
+ is_pytest_scratch_directory_segment,
26
35
  )
27
- from .fast_save_validators import FastSaveCheckOutcome, run_fast_save_validators
36
+ from .fast_save_validators import run_fast_save_validators
28
37
  from .health_check import get_system_health, get_validator_version, print_health_report
29
- from .mypy_integration import check_mypy_available, run_mypy_check
30
- from .system_temporary_roots import enclosing_system_temporary_root
38
+ from .mypy_integration import (
39
+ check_mypy_available,
40
+ find_module_resolution_root,
41
+ run_mypy_check,
42
+ )
31
43
  from .output_formatter import OutputFormatter, OutputMode, ValidatorResultDict
32
44
  from .python_style_checks import fix_file
33
- from .ruff_integration import check_ruff_available, run_ruff_check
45
+ from .ruff_integration import run_ruff_check
46
+ from .validator_base import ValidatorResult
34
47
  from blocking.code_rules_shared import is_ephemeral_path
35
48
  from hooks_constants.hook_block_logger import log_hook_block
36
49
  from hooks_constants.multi_edit_reconstruction import (
@@ -43,35 +56,6 @@ hooks_dir = VALIDATORS_DIR.parent
43
56
  package_name = VALIDATORS_DIR.name
44
57
 
45
58
 
46
- def _gate_entry_for_fast_save_check(
47
- check_outcome: FastSaveCheckOutcome,
48
- ) -> "ValidatorResult":
49
- """Wrap one in-process check's finding into the gate's shared reporting type."""
50
- return ValidatorResult(
51
- name=check_outcome.display_name,
52
- checks=check_outcome.checks,
53
- passed=check_outcome.is_clean,
54
- output=check_outcome.violation_report,
55
- )
56
-
57
-
58
- def _run_fast_save_checks(files: List[Path]) -> List["ValidatorResult"]:
59
- """Run the save-path roster in-process and wrap each finding for the gate.
60
-
61
- Args:
62
- files: The files under validation -- one reconstructed file in gate mode.
63
-
64
- Returns:
65
- One ValidatorResult per in-process save-path check. Ruff and Mypy are
66
- not part of this roster; the caller adds Ruff separately and never
67
- adds Mypy on the save path.
68
- """
69
- return [
70
- _gate_entry_for_fast_save_check(each_outcome)
71
- for each_outcome in run_fast_save_validators(files)
72
- ]
73
-
74
-
75
59
  def _windows_non_unc_working_directory_string(
76
60
  candidate_directory_strings: list[str | None],
77
61
  ) -> str:
@@ -260,17 +244,6 @@ def build_json_output(
260
244
  }
261
245
 
262
246
 
263
- @dataclass(frozen=True)
264
- class ValidatorResult:
265
- """Result from running a validator."""
266
-
267
- name: str
268
- checks: str
269
- passed: bool
270
- output: str
271
- skipped: bool = False
272
-
273
-
274
247
  def run_with_fallback(
275
248
  validator_func: Callable[[], ValidatorResult],
276
249
  fallback_name: str,
@@ -446,15 +419,11 @@ def run_comment_checks(files: List[Path]) -> ValidatorResult:
446
419
  def run_ruff_checks(
447
420
  files: List[Path], config_source_path: Optional[Path] = None
448
421
  ) -> ValidatorResult:
449
- """Run ruff for fast Python linting."""
450
- if not check_ruff_available():
451
- return ValidatorResult(
452
- name="Ruff",
453
- checks="37",
454
- passed=True,
455
- output="Ruff not installed - skipping",
456
- )
422
+ """Run ruff for fast Python linting.
457
423
 
424
+ run_ruff_check makes the same availability probe and returns the same
425
+ skip message, so probing here would spawn ruff --version twice.
426
+ """
458
427
  result = run_ruff_check(files, config_source_path)
459
428
 
460
429
  return ValidatorResult(
@@ -786,69 +755,77 @@ def _escapes_temporary_root(path_part: str) -> bool:
786
755
  return part_as_path.is_absolute() or bool(part_as_path.anchor)
787
756
 
788
757
 
789
- def _is_absolute_path_under_system_temporary_directory(file_path: str) -> bool:
790
- """Return True when *file_path* is absolute and resolves under an OS temp root.
758
+ def _directory_segment_signals_exemption(segment_lower: str) -> bool:
759
+ """Return True when a directory segment carries a path-exemption signal.
791
760
 
792
761
  ::
793
762
 
794
- ok: "<windows-temp-root>/pytest-of-x/test_foo0/a.py" -> True
795
- ok: "/home/runner/work/_temp/pytest-basetemp/.../a.py" when RUNNER_TEMP
796
- flag: "packages/demo/test_helpers/worker.py" -> False (relative)
797
- flag: "C:/repo/pkg/test_helpers/worker.py" -> False (project)
763
+ ok: "test_helpers" -> True (contains the ``test_`` fragment)
764
+ ok: "scripts" -> True (exact CLI-marker segment name)
765
+ flag: "latest" -> False (neither exact name nor a fragment)
766
+ flag: "test_edit_foo0" -> False (pytest generated it, not the project)
798
767
 
799
- Absolute paths under system temporary directories often carry pytest
800
- ``tmp_path`` segments named ``test_*``. Those segments must not be treated
801
- as project exemption signals, or a production file staged from a pytest
802
- path would inherit a false test-file exemption.
768
+ A segment is kept during staging when its name exactly matches an exemption
769
+ directory name, or when a separator-free substring pattern that
770
+ ``is_test_file`` matches anywhere in a path appears inside it — that is what
771
+ preserves ``pkg/test_helpers/``. A directory pytest generated for its own
772
+ scratch tree is excluded from the substring pass, so a ``test_*`` scratch
773
+ parent never lends a staged production file a false test exemption.
803
774
 
804
775
  Args:
805
- file_path: Destination path the write or edit targets.
776
+ segment_lower: One lowercased directory component of the target path.
806
777
 
807
778
  Returns:
808
- True when *file_path* is absolute and lives under ``tempfile.gettempdir()``
809
- or a known temporary-root environment variable (``TEMP``, ``TMP``,
810
- ``TMPDIR``, ``RUNNER_TEMP``).
779
+ True when staging must keep this segment to reproduce the exemption.
811
780
  """
812
- destination_path = Path(file_path)
813
- if not destination_path.is_absolute():
781
+ if segment_lower in ALL_DIRECTORY_EXEMPTION_SEGMENT_NAMES:
782
+ return True
783
+ if is_pytest_scratch_directory_segment(segment_lower):
814
784
  return False
815
- return enclosing_system_temporary_root(destination_path) is not None
785
+ return any(
786
+ each_pattern in segment_lower
787
+ for each_pattern in ALL_DIRECTORY_EXEMPTION_SUBSTRING_PATTERNS
788
+ )
816
789
 
817
790
 
818
- def _directory_segment_signals_exemption(
819
- segment_lower: str, *, is_substring_match_enabled: bool
820
- ) -> bool:
821
- """Return True when a directory segment carries a path-exemption signal.
791
+ def _path_parts_the_project_owns(destination_path: Path) -> tuple[str, ...]:
792
+ """Return the destination's path parts from its own project root downward.
822
793
 
823
794
  ::
824
795
 
825
- ok: "test_helpers" (substring on) -> True (contains the ``test_`` fragment)
826
- ok: "scripts" -> True (exact CLI-marker segment name)
827
- flag: "latest" -> False (neither exact name nor a fragment)
828
- flag: "test_edit_foo0" (substring off) -> False (pytest-shaped; exact-only mode)
796
+ ok: "/home/tests/proj/src/worker.py" (proj is the root) -> ("src", "worker.py")
797
+ ok: "/home/dana/.claude/hooks/gate.py" (no root) -> (".claude", "hooks", "gate.py")
798
+ ok: "config/x.py" (relative) -> ("config", "x.py")
829
799
 
830
- A segment is kept during staging when its name exactly matches an exemption
831
- directory name. When *is_substring_match_enabled* is True, a separator-free
832
- substring pattern that ``is_test_file`` matches anywhere in a path also
833
- counts — that is what preserves ``pkg/test_helpers/``. Substring matching is
834
- disabled for absolute paths under the system temporary directory so pytest
835
- ``tmp_path`` parents named ``test_*`` do not falsely trip test exemptions.
800
+ Directory names above the project root were chosen by whoever laid out the
801
+ disk, not by the project, so a home directory named ``tests`` or a checkout
802
+ parked under ``config`` must lend the staged path no exemption signal.
803
+ Dropping those segments is strictly narrowing: it can remove a signal, never
804
+ invent one.
805
+
806
+ A relative destination is already project-relative and is returned whole,
807
+ which keeps the result independent of the process working directory. A
808
+ destination with no project root above it -- an install target such as
809
+ ``~/.claude/hooks/`` -- keeps every segment, because those segments are the
810
+ only exemption signal such a target carries.
836
811
 
837
812
  Args:
838
- segment_lower: One lowercased directory component of the target path.
839
- is_substring_match_enabled: When False, only exact exemption names count.
813
+ destination_path: Real destination path the write or edit targets.
840
814
 
841
815
  Returns:
842
- True when staging must keep this segment to reproduce the exemption.
816
+ The path parts staging walks for exemption signals, root anchor removed.
843
817
  """
844
- if segment_lower in ALL_DIRECTORY_EXEMPTION_SEGMENT_NAMES:
845
- return True
846
- if not is_substring_match_enabled:
847
- return False
848
- return any(
849
- each_pattern in segment_lower
850
- for each_pattern in ALL_DIRECTORY_EXEMPTION_SUBSTRING_PATTERNS
851
- )
818
+ all_path_parts = destination_path.parts
819
+ if not destination_path.anchor:
820
+ return all_path_parts
821
+ all_path_parts = all_path_parts[1:]
822
+ project_root = find_module_resolution_root(destination_path)
823
+ if project_root is None:
824
+ return all_path_parts
825
+ try:
826
+ return destination_path.resolve().relative_to(project_root).parts
827
+ except ValueError:
828
+ return all_path_parts
852
829
 
853
830
 
854
831
  def _temporary_path_preserving_directory_signal(
@@ -860,11 +837,12 @@ def _temporary_path_preserving_directory_signal(
860
837
  path fragments (``test_`` inside ``test_helpers``) match substrings of the
861
838
  real file path. Staging under a flat temp basename drops those segments.
862
839
  Mirroring the first exemption-signaling directory through the basename
863
- restores that signal. Substring fragment matching is skipped for absolute
864
- paths under the system temporary directory so pytest ``tmp_path`` parents
865
- that contain ``test_`` do not falsely trip test-file exemptions; exact
866
- exemption directory names (``config``, ``scripts``, ``tests``, ...) still
867
- anchor staging on those absolute temp paths.
840
+ restores that signal. A directory pytest generated for its own scratch tree
841
+ is recognized by name and skipped, so a ``tmp_path`` parent containing
842
+ ``test_`` never trips a test-file exemption. The staged path reads the same
843
+ wherever ``--basetemp`` places that scratch tree. The walk starts at the
844
+ destination's own project root, so a directory above the project lends it
845
+ no signal.
868
846
 
869
847
  Args:
870
848
  temporary_directory: Root of the ephemeral staging tree.
@@ -875,21 +853,14 @@ def _temporary_path_preserving_directory_signal(
875
853
  (when present) and the real basename.
876
854
  """
877
855
  destination_path = Path(file_path)
878
- path_parts = destination_path.parts
879
- if destination_path.anchor:
880
- path_parts = path_parts[1:]
856
+ path_parts = _path_parts_the_project_owns(destination_path)
881
857
  if not path_parts:
882
858
  path_parts = (destination_path.name,)
883
859
 
884
- is_substring_match_enabled = not _is_absolute_path_under_system_temporary_directory(
885
- file_path
886
- )
887
860
  start_index = len(path_parts) - 1
888
861
  for each_index, each_part in enumerate(path_parts[:-1]):
889
862
  part_lower = each_part.lower()
890
- if not _directory_segment_signals_exemption(
891
- part_lower, is_substring_match_enabled=is_substring_match_enabled
892
- ):
863
+ if not _directory_segment_signals_exemption(part_lower):
893
864
  continue
894
865
  start_index = each_index
895
866
  break
@@ -943,7 +914,7 @@ def validate_proposed_file(
943
914
  else Path(file_path)
944
915
  )
945
916
  return [
946
- *_run_fast_save_checks([temporary_file]),
917
+ *run_fast_save_validators([temporary_file]),
947
918
  run_ruff_checks([temporary_file], resolved_config_source_path),
948
919
  ]
949
920
 
@@ -1187,6 +1158,63 @@ def _line_identity(
1187
1158
  )
1188
1159
 
1189
1160
 
1161
+ def _scope_agnostic_message(identity_scope: str, violation_message: str) -> str:
1162
+ """Return the message with its own function's name and shape metrics masked.
1163
+
1164
+ ::
1165
+
1166
+ "over_long_fn", "Function 'over_long_fn' is 37 lines (max 30)"
1167
+ -> "Function '<name>' is <number> lines (max <number>)"
1168
+ "compute_total", "Magic number 199 - use named constant"
1169
+ -> "Magic number 199 - use named constant"
1170
+
1171
+ A message that names its enclosing function reports that function's shape,
1172
+ so the numbers in it belong to the same shape and are masked alongside the
1173
+ name. A message that never names the function keeps its numbers, so a magic
1174
+ value and a ruff rule code still tell two violations apart.
1175
+
1176
+ Args:
1177
+ identity_scope: The enclosing function's qualified name, or the empty
1178
+ string for a module-scope violation.
1179
+ violation_message: The message text of one violation line.
1180
+
1181
+ Returns:
1182
+ The message with the enclosing function's name replaced by a fixed
1183
+ placeholder, and its metric numbers replaced too when that name was
1184
+ present; the unchanged message otherwise.
1185
+ """
1186
+ short_scope_name = identity_scope.rpartition(QUALIFIED_SCOPE_NAME_SEPARATOR)[2]
1187
+ if not short_scope_name:
1188
+ return violation_message
1189
+ scope_name_pattern = (
1190
+ WORD_BOUNDARY_PATTERN + re.escape(short_scope_name) + WORD_BOUNDARY_PATTERN
1191
+ )
1192
+ if not re.search(scope_name_pattern, violation_message):
1193
+ return violation_message
1194
+ masked_message = re.sub(
1195
+ scope_name_pattern, SCOPE_NAME_PLACEHOLDER, violation_message
1196
+ )
1197
+ return re.sub(
1198
+ STANDALONE_NUMBER_PATTERN, SHAPE_NUMBER_PLACEHOLDER, masked_message
1199
+ )
1200
+
1201
+
1202
+ def _shape_key(violation_identity: ViolationIdentity) -> tuple[str, str]:
1203
+ """Return an identity's ``(validator, scope-agnostic message)`` shape key.
1204
+
1205
+ Args:
1206
+ violation_identity: One violation's full identity key.
1207
+
1208
+ Returns:
1209
+ The key a violation keeps when only its enclosing function's name
1210
+ changes, so a rename, a split, or a move still finds its baseline.
1211
+ """
1212
+ return (
1213
+ violation_identity[0],
1214
+ _scope_agnostic_message(violation_identity[1], violation_identity[2]),
1215
+ )
1216
+
1217
+
1190
1218
  def _violation_identities(
1191
1219
  failed_results: List[ValidatorResult], content: str
1192
1220
  ) -> Counter[ViolationIdentity]:
@@ -1195,7 +1223,8 @@ def _violation_identities(
1195
1223
  Keying on the enclosing function rather than the raw line number keeps a
1196
1224
  key stable when an edit shifts that function, and counting rather than set
1197
1225
  membership keeps a second violation of the same validator in the same
1198
- function visible as new.
1226
+ function visible as new. A rename moves that key rather than shifting it,
1227
+ which is why matching falls back to the shape key.
1199
1228
 
1200
1229
  Args:
1201
1230
  failed_results: The validator results that fired.
@@ -1228,22 +1257,37 @@ def _baseline_violation_identities(file_path: str) -> Counter[ViolationIdentity]
1228
1257
  return _violation_identities(baseline_failed, baseline_content)
1229
1258
 
1230
1259
 
1231
- def _identity_key_counts(
1232
- baseline_identities: Counter[ViolationIdentity],
1233
- ) -> Counter[tuple[str, str]]:
1234
- """Sum baseline counts down to ``(validator, enclosing function)`` keys.
1260
+ def _compatible_baseline_identity(
1261
+ line_identity: ViolationIdentity, remaining_exact: Counter[ViolationIdentity]
1262
+ ) -> Optional[ViolationIdentity]:
1263
+ """Return an unconsumed baseline identity *line_identity* may be charged to.
1264
+
1265
+ A same-validator baseline entry in the same enclosing function absorbs a
1266
+ message that drifted with the edit. A same-validator entry of the same
1267
+ shape absorbs a message whose enclosing function was renamed, split, or
1268
+ moved. The same-function entry is preferred, so a drifted message inside an
1269
+ untouched function never spends a renamed function's allowance.
1235
1270
 
1236
1271
  Args:
1237
- baseline_identities: The baseline identity multiset.
1272
+ line_identity: The proposed line's identity key.
1273
+ remaining_exact: The unconsumed baseline identity budget.
1238
1274
 
1239
1275
  Returns:
1240
- The per-key line counts with messages ignored, so a violation whose
1241
- message drifted with the edit still finds its baseline budget.
1276
+ The baseline identity to charge, or None when the budget is spent.
1242
1277
  """
1243
- key_counts: Counter[tuple[str, str]] = Counter()
1244
- for each_identity, each_count in baseline_identities.items():
1245
- key_counts[each_identity[:2]] += each_count
1246
- return key_counts
1278
+ all_available_identities = [
1279
+ each_identity
1280
+ for each_identity, each_count in remaining_exact.items()
1281
+ if each_count > 0 and each_identity[0] == line_identity[0]
1282
+ ]
1283
+ for each_identity in all_available_identities:
1284
+ if each_identity[1] == line_identity[1]:
1285
+ return each_identity
1286
+ line_shape_key = _shape_key(line_identity)
1287
+ for each_identity in all_available_identities:
1288
+ if _shape_key(each_identity) == line_shape_key:
1289
+ return each_identity
1290
+ return None
1247
1291
 
1248
1292
 
1249
1293
  def _result_with_output(
@@ -1262,7 +1306,6 @@ def _result_with_output(
1262
1306
  def _consume_exact_matches(
1263
1307
  all_line_identities: List[ViolationIdentity],
1264
1308
  remaining_exact: Counter[ViolationIdentity],
1265
- remaining_by_key: Counter[tuple[str, str]],
1266
1309
  ) -> set[int]:
1267
1310
  """Mark the lines whose full identity matches an unconsumed baseline entry.
1268
1311
 
@@ -1270,7 +1313,6 @@ def _consume_exact_matches(
1270
1313
  all_line_identities: One identity per located line, in output order.
1271
1314
  remaining_exact: The unconsumed baseline identity budget, decremented
1272
1315
  in place per match.
1273
- remaining_by_key: The unconsumed per-key budget, decremented in step.
1274
1316
 
1275
1317
  Returns:
1276
1318
  The indexes of the exactly-matched lines.
@@ -1280,7 +1322,6 @@ def _consume_exact_matches(
1280
1322
  if remaining_exact[each_identity] <= 0:
1281
1323
  continue
1282
1324
  remaining_exact[each_identity] -= 1
1283
- remaining_by_key[each_identity[:2]] -= 1
1284
1325
  all_matched_line_indexes.add(each_line_index)
1285
1326
  return all_matched_line_indexes
1286
1327
 
@@ -1289,42 +1330,45 @@ def _line_is_preexisting(
1289
1330
  line_index: int,
1290
1331
  all_line_identities: List[ViolationIdentity],
1291
1332
  all_matched_line_indexes: set[int],
1292
- remaining_by_key: Counter[tuple[str, str]],
1333
+ remaining_exact: Counter[ViolationIdentity],
1293
1334
  ) -> bool:
1294
1335
  """Return whether one located line matches the baseline budget.
1295
1336
 
1296
- An exact identity match is pre-existing. A leftover line whose
1297
- ``(validator, enclosing function)`` key still has baseline budget is
1298
- pre-existing with a drifted message. A line beyond its key's budget is new.
1337
+ An exact identity match is pre-existing. A leftover line a compatible
1338
+ unconsumed baseline entry can be charged to is pre-existing with a drifted
1339
+ message or a renamed enclosing function. Charging spends that one entry, so
1340
+ a line beyond the baseline's count for its validator is new.
1299
1341
 
1300
1342
  Args:
1301
1343
  line_index: The line's position in the located-line order.
1302
1344
  all_line_identities: One identity per located line.
1303
1345
  all_matched_line_indexes: The exactly-matched line indexes.
1304
- remaining_by_key: The unconsumed per-key budget, decremented in place.
1346
+ remaining_exact: The unconsumed baseline identity budget, decremented
1347
+ in place per charge.
1305
1348
 
1306
1349
  Returns:
1307
1350
  True when the line is pre-existing, False when it is new.
1308
1351
  """
1309
1352
  if line_index in all_matched_line_indexes:
1310
1353
  return True
1311
- each_key = all_line_identities[line_index][:2]
1312
- if remaining_by_key[each_key] > 0:
1313
- remaining_by_key[each_key] -= 1
1314
- return True
1315
- return False
1354
+ compatible_identity = _compatible_baseline_identity(
1355
+ all_line_identities[line_index], remaining_exact
1356
+ )
1357
+ if compatible_identity is None:
1358
+ return False
1359
+ remaining_exact[compatible_identity] -= 1
1360
+ return True
1316
1361
 
1317
1362
 
1318
1363
  def _partition_output_lines(
1319
1364
  each_result: ValidatorResult,
1320
1365
  name_by_line: dict[int, str],
1321
1366
  remaining_exact: Counter[ViolationIdentity],
1322
- remaining_by_key: Counter[tuple[str, str]],
1323
1367
  ) -> tuple[List[str], List[str]]:
1324
1368
  """Split one result's located lines into a (new, pre-existing) line pair.
1325
1369
 
1326
- The exact and per-key baseline budgets are consumed in place, exact
1327
- matches first, so a later result never double-spends an earlier match.
1370
+ The single baseline budget is consumed in place, exact matches first, so a
1371
+ later result never double-spends an earlier match.
1328
1372
  """
1329
1373
  located_lines = _located_violation_lines(each_result)
1330
1374
  all_line_identities = [
@@ -1332,13 +1376,13 @@ def _partition_output_lines(
1332
1376
  for each_line in located_lines
1333
1377
  ]
1334
1378
  all_matched_line_indexes = _consume_exact_matches(
1335
- all_line_identities, remaining_exact, remaining_by_key
1379
+ all_line_identities, remaining_exact
1336
1380
  )
1337
1381
  all_new_lines: List[str] = []
1338
1382
  all_preexisting_lines: List[str] = []
1339
1383
  for each_line_index, each_line in enumerate(located_lines):
1340
1384
  is_preexisting = _line_is_preexisting(
1341
- each_line_index, all_line_identities, all_matched_line_indexes, remaining_by_key
1385
+ each_line_index, all_line_identities, all_matched_line_indexes, remaining_exact
1342
1386
  )
1343
1387
  (all_preexisting_lines if is_preexisting else all_new_lines).append(each_line)
1344
1388
  return all_new_lines, all_preexisting_lines
@@ -1382,13 +1426,12 @@ def _scope_new_and_preexisting(
1382
1426
  """
1383
1427
  name_by_line = _enclosing_function_name_by_line(proposed_content)
1384
1428
  remaining_exact = Counter(baseline_identities)
1385
- remaining_by_key = _identity_key_counts(baseline_identities)
1386
1429
  all_new_results: List[ValidatorResult] = []
1387
1430
  all_preexisting_results: List[ValidatorResult] = []
1388
1431
  for each_result in all_proposed_failed_results:
1389
1432
  new_results, preexisting_results = _grouped_result_lines(
1390
1433
  each_result,
1391
- _partition_output_lines(each_result, name_by_line, remaining_exact, remaining_by_key),
1434
+ _partition_output_lines(each_result, name_by_line, remaining_exact),
1392
1435
  )
1393
1436
  all_new_results.extend(new_results)
1394
1437
  all_preexisting_results.extend(preexisting_results)
@@ -1434,10 +1477,12 @@ def _evaluate_pre_tool_use_payload() -> None:
1434
1477
  payload, so an ephemeral scratch or session scratchpad target passes without
1435
1478
  validation before any baseline-scoped decision runs. For a non-exempt target,
1436
1479
  each located violation is keyed by validator name, enclosing function, and
1437
- message, then counted against the on-disk baseline. A violation beyond the
1438
- baseline's budget for its key denies the write; one the baseline already
1439
- carries passes with a stderr advisory. Writes nothing for a clean file, an
1440
- exempt target, or an unparseable payload.
1480
+ message, then charged against the on-disk baseline. A violation the
1481
+ baseline cannot pay for denies the write, whether by an exact key, by the
1482
+ same enclosing function, or by the same message shape under a renamed
1483
+ function; one the baseline already carries passes with a stderr advisory.
1484
+ Writes nothing for a clean file, an exempt target, or an unparseable
1485
+ payload.
1441
1486
  """
1442
1487
  pre_tool_use_payload = json.load(sys.stdin)
1443
1488
  if not isinstance(pre_tool_use_payload, dict):
@@ -12,7 +12,7 @@ import sys
12
12
  from pathlib import Path
13
13
  from typing import List
14
14
 
15
- from .validator_base import Violation
15
+ from .validator_base import Violation, source_text, syntax_tree
16
16
 
17
17
 
18
18
  SECRET_PATTERNS: frozenset[str] = frozenset({
@@ -95,12 +95,12 @@ def validate_file(file_path: Path) -> List[Violation]:
95
95
  filename = str(file_path)
96
96
 
97
97
  try:
98
- source = file_path.read_text(encoding="utf-8")
98
+ source = source_text(file_path)
99
99
  except Exception as error:
100
100
  return [Violation(filename, 0, f"Error reading file: {error}")]
101
101
 
102
102
  try:
103
- tree = ast.parse(source)
103
+ tree = syntax_tree(source)
104
104
  except SyntaxError as error:
105
105
  return [Violation(filename, error.lineno or 0, f"Syntax error: {error.msg}")]
106
106
 
@@ -8,8 +8,6 @@ from __future__ import annotations
8
8
 
9
9
  from pathlib import Path
10
10
 
11
- import pytest
12
-
13
11
  from hooks_constants.code_rules_enforcer_constants import ALL_CLI_FILE_PATH_MARKERS
14
12
  from hooks_constants.code_rules_path_utils_constants import ALL_CONFIG_DIRECTORY_NAMES
15
13
  from validators.config.directory_exemption_constants import (
@@ -19,6 +17,7 @@ from validators.config.directory_exemption_constants import (
19
17
  all_directory_segments_in_path_pattern,
20
18
  directory_segment_names_from_path_patterns,
21
19
  is_filename_like_path_segment,
20
+ is_pytest_scratch_directory_segment,
22
21
  substring_patterns_from_path_patterns,
23
22
  )
24
23
  from validators.exempt_paths import (
@@ -36,6 +35,9 @@ ALL_SYNTHETIC_DIRECTORY_PATTERNS = frozenset(
36
35
  {"/foo/", "\\bar\\", "/baz.py", "plain", "/.hidden/qux/"}
37
36
  )
38
37
  ALL_EXPECTED_SYNTHETIC_SEGMENTS = frozenset({"foo", "bar", ".hidden", "qux"})
38
+ OVER_LONG_STEM_DIRECTORY_NAME = "test_helpers_for_a_very_long_domain_name0"
39
+ PROJECT_ROOTED_BASETEMP_PATH = "/srv/projects/scratch-basetemp"
40
+ PYTEST_SCRATCH_DIRECTORY_NAME = "test_edit_introducing_new_viol0"
39
41
 
40
42
 
41
43
  def test_is_filename_like_path_segment_detects_extensions() -> None:
@@ -45,6 +47,21 @@ def test_is_filename_like_path_segment_detects_extensions() -> None:
45
47
  assert is_filename_like_path_segment(".claude") is False
46
48
 
47
49
 
50
+ def test_is_pytest_scratch_directory_segment_detects_numbered_test_directories() -> None:
51
+ assert is_pytest_scratch_directory_segment("test_drops_leading_anchor0") is True
52
+ assert is_pytest_scratch_directory_segment("test_edit_introducing_new_viol0") is True
53
+ assert is_pytest_scratch_directory_segment("pytest-of-root") is True
54
+ assert is_pytest_scratch_directory_segment("pytest-9") is True
55
+
56
+
57
+ def test_is_pytest_scratch_directory_segment_keeps_real_project_directories() -> None:
58
+ assert is_pytest_scratch_directory_segment("test_helpers") is False
59
+ assert is_pytest_scratch_directory_segment("tests") is False
60
+ assert is_pytest_scratch_directory_segment("scripts") is False
61
+ assert is_pytest_scratch_directory_segment("conftest") is False
62
+ assert is_pytest_scratch_directory_segment(OVER_LONG_STEM_DIRECTORY_NAME) is False
63
+
64
+
48
65
  def test_all_directory_segments_in_path_pattern_keeps_directory_tokens_only() -> None:
49
66
  assert all_directory_segments_in_path_pattern("/.claude/hooks/") == [
50
67
  ".claude",
@@ -136,32 +153,21 @@ def test_absolute_system_temp_pytest_shaped_path_stages_flat_basename(
136
153
  assert staged_path == staging_root / "legacy_module.py"
137
154
 
138
155
 
139
- def test_runner_temp_pytest_shaped_path_stages_flat_basename_when_gettempdir_differs(
156
+ def test_pytest_shaped_path_stages_flat_basename_under_every_basetemp_placement(
140
157
  tmp_path: Path,
141
- monkeypatch: pytest.MonkeyPatch,
142
158
  ) -> None:
143
- """GHA basetemp lives under RUNNER_TEMP while gettempdir is often /tmp."""
144
- runner_temp_root = tmp_path / "runner_temp"
145
- os_gettemp = tmp_path / "os_gettemp"
146
- runner_temp_root.mkdir()
147
- os_gettemp.mkdir()
148
- monkeypatch.setenv("RUNNER_TEMP", str(runner_temp_root))
149
- monkeypatch.setattr(
150
- "validators.system_temporary_roots.tempfile.gettempdir",
151
- lambda: str(os_gettemp),
152
- )
153
- pytest_shaped_target = (
154
- runner_temp_root
155
- / "pytest-basetemp-pkg"
156
- / "test_edit_introducing_new_viol0"
157
- / "legacy_module.py"
158
- )
159
+ """A ``--basetemp`` outside every temp root must not change the staged path."""
159
160
  staging_root = tmp_path / "staging_root"
160
161
  staging_root.mkdir()
161
- staged_path = _temporary_path_preserving_directory_signal(
162
- staging_root, str(pytest_shaped_target)
163
- )
164
- assert staged_path == staging_root / "legacy_module.py"
162
+ all_basetemp_roots = (tmp_path, Path(PROJECT_ROOTED_BASETEMP_PATH))
163
+ all_staged_paths = {
164
+ _temporary_path_preserving_directory_signal(
165
+ staging_root,
166
+ str(each_root / PYTEST_SCRATCH_DIRECTORY_NAME / "legacy_module.py"),
167
+ )
168
+ for each_root in all_basetemp_roots
169
+ }
170
+ assert all_staged_paths == {staging_root / "legacy_module.py"}
165
171
 
166
172
 
167
173
  def test_substring_patterns_from_path_patterns_skips_directory_tokens() -> None: