claude-dev-env 2.30.1 → 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 (143) hide show
  1. package/.agents/agents/pr-description-writer.md +1 -1
  2. package/AGENTS.md +6 -0
  3. package/_shared/pr-loop/scripts/code_rules_gate_parts/tests/test_enforcer_loading.py +37 -0
  4. package/bin/install.prune.test.mjs +4 -2
  5. package/docs/CODE_RULES.md +12 -0
  6. package/hooks/advisory/migration_safety_advisor.py +25 -1
  7. package/hooks/advisory/refactor_guard.py +85 -18
  8. package/hooks/advisory/test_migration_safety_advisor.py +89 -5
  9. package/hooks/advisory/test_refactor_guard.py +87 -0
  10. package/hooks/advisory/test_refactor_guard_advisory.py +72 -1
  11. package/hooks/blocking/code_rules_constants_config.py +7 -6
  12. package/hooks/blocking/code_rules_duplicate_body.py +272 -100
  13. package/hooks/blocking/code_rules_enforcer.py +89 -45
  14. package/hooks/blocking/code_rules_shared.py +64 -14
  15. package/hooks/blocking/codex_apply_patch.py +136 -21
  16. package/hooks/blocking/config/codex_apply_patch_constants.py +13 -0
  17. package/hooks/blocking/conftest.py +70 -0
  18. package/hooks/blocking/duplicate_rmtree_helper_blocker.py +26 -16
  19. package/hooks/blocking/hook_prose_detector_consistency.py +30 -20
  20. package/hooks/blocking/pii_payload_scan.py +61 -0
  21. package/hooks/blocking/pii_prevention_blocker.py +5 -0
  22. package/hooks/blocking/pr_description_writer_gate.py +256 -0
  23. package/hooks/blocking/pre_tool_use_dispatcher.py +1 -1
  24. package/hooks/blocking/sensitive_file_protector.py +18 -3
  25. package/hooks/blocking/shell_substitution_blocker.py +25 -47
  26. package/hooks/blocking/stale_comment_reference_blocker.py +94 -24
  27. package/hooks/blocking/state_description_blocker.py +39 -26
  28. package/hooks/blocking/subprocess_budget_completeness.py +17 -43
  29. package/hooks/blocking/tdd_enforcer.py +63 -16
  30. package/hooks/blocking/tdd_enforcer_parts/config/tdd_enforcer_constants.py +11 -1
  31. package/hooks/blocking/tdd_enforcer_parts/content_hash_store.py +180 -0
  32. package/hooks/blocking/tdd_enforcer_parts/decisions.py +6 -2
  33. package/hooks/blocking/tdd_enforcer_parts/freshness.py +18 -3
  34. package/hooks/blocking/tdd_enforcer_parts/git_tracking.py +66 -1
  35. package/hooks/blocking/tdd_enforcer_parts/tests/test_content_hash_store.py +143 -0
  36. package/hooks/blocking/tdd_enforcer_parts/tests/test_decisions.py +12 -0
  37. package/hooks/blocking/tdd_enforcer_parts/tests/test_git_tracking.py +63 -0
  38. package/hooks/blocking/test_bash_pre_tool_use_dispatcher.py +1 -0
  39. package/hooks/blocking/test_code_rules_enforcer_cap_meta.py +81 -2
  40. package/hooks/blocking/test_code_rules_enforcer_codex_apply_patch.py +35 -0
  41. package/hooks/blocking/test_code_rules_enforcer_config_path.py +29 -16
  42. package/hooks/blocking/test_code_rules_enforcer_duplicate_body_hook_routing.py +2 -0
  43. package/hooks/blocking/test_code_rules_enforcer_ephemeral.py +12 -1
  44. package/hooks/blocking/test_code_rules_enforcer_ephemeral_repository_root.py +118 -0
  45. package/hooks/blocking/test_code_rules_enforcer_multi_edit.py +118 -0
  46. package/hooks/blocking/test_code_rules_enforcer_narrow_edit.py +2 -0
  47. package/hooks/blocking/test_code_rules_enforcer_precheck_forecast.py +2 -0
  48. package/hooks/blocking/test_code_rules_enforcer_same_file_inline_duplicate.py +244 -0
  49. package/hooks/blocking/test_code_rules_enforcer_split_constants_config.py +29 -28
  50. package/hooks/blocking/test_code_rules_enforcer_split_entry_2.py +24 -0
  51. package/hooks/blocking/test_code_rules_enforcer_stage.py +2 -0
  52. package/hooks/blocking/test_code_rules_enforcer_zero_payload_alias_hook_routing.py +2 -0
  53. package/hooks/blocking/test_codex_apply_patch.py +43 -0
  54. package/hooks/blocking/test_duplicate_rmtree_helper_blocker.py +68 -0
  55. package/hooks/blocking/test_hook_prose_detector_consistency.py +41 -0
  56. package/hooks/blocking/test_pii_payload_scan.py +65 -2
  57. package/hooks/blocking/test_pii_prevention_blocker.py +80 -10
  58. package/hooks/blocking/test_pr_description_writer_gate.py +234 -0
  59. package/hooks/blocking/test_pre_tool_use_dispatcher.py +215 -25
  60. package/hooks/blocking/test_pre_tool_use_dispatcher_native.py +18 -6
  61. package/hooks/blocking/test_sensitive_file_protector.py +42 -2
  62. package/hooks/blocking/test_stale_comment_reference_blocker.py +71 -0
  63. package/hooks/blocking/test_state_description_blocker.py +163 -49
  64. package/hooks/blocking/test_subprocess_budget_completeness.py +67 -0
  65. package/hooks/blocking/test_tdd_enforcer.py +246 -2
  66. package/hooks/blocking/test_windows_rmtree_blocker.py +63 -0
  67. package/hooks/blocking/test_write_existing_file_blocker.py +122 -0
  68. package/hooks/blocking/windows_rmtree_blocker.py +21 -7
  69. package/hooks/blocking/write_existing_file_blocker.py +75 -29
  70. package/hooks/conftest.py +47 -0
  71. package/hooks/hooks.json +7 -12
  72. package/hooks/hooks_constants/bash_pre_tool_use_dispatcher_constants.py +3 -0
  73. package/hooks/hooks_constants/code_rules_enforcer_constants.py +4 -0
  74. package/hooks/hooks_constants/duplicate_rmtree_helper_blocker_constants.py +3 -0
  75. package/hooks/hooks_constants/hook_prose_detector_consistency_constants.py +7 -2
  76. package/hooks/hooks_constants/migration_safety_advisor_constants.py +7 -0
  77. package/hooks/hooks_constants/multi_edit_reconstruction.py +44 -3
  78. package/hooks/hooks_constants/pii_prevention_constants.py +9 -7
  79. package/hooks/hooks_constants/pr_description_writer_gate_constants.py +73 -0
  80. package/hooks/hooks_constants/pre_tool_use_dispatcher_constants.py +31 -14
  81. package/hooks/hooks_constants/session_edit_stage_gate_constants.py +15 -1
  82. package/hooks/hooks_constants/state_description_blocker_constants.py +1 -0
  83. package/hooks/hooks_constants/subprocess_budget_completeness_content.py +71 -0
  84. package/hooks/hooks_constants/test_bash_pre_tool_use_dispatcher_constants.py +2 -0
  85. package/hooks/hooks_constants/test_code_rules_enforcer_constants.py +2 -0
  86. package/hooks/hooks_constants/test_multi_edit_reconstruction.py +103 -0
  87. package/hooks/hooks_constants/test_pre_tool_use_dispatcher_constants.py +139 -25
  88. package/hooks/hooks_constants/test_subprocess_budget_completeness_content.py +103 -0
  89. package/hooks/hooks_constants/validation_phase_constants.py +2 -0
  90. package/hooks/hooks_constants/workflow_substitution_slot_blocker_constants.py +7 -3
  91. package/hooks/observability/pr_description_writer_spawn_tracker.py +113 -0
  92. package/hooks/observability/session_file_edit_tracker.py +25 -4
  93. package/hooks/observability/test_pr_description_writer_spawn_tracker.py +150 -0
  94. package/hooks/observability/test_session_file_edit_tracker.py +32 -0
  95. package/hooks/validation/hook_format_validator.py +23 -9
  96. package/hooks/validation/test_hook_format_validator.py +58 -0
  97. package/hooks/validators/README.md +1 -1
  98. package/hooks/validators/abbreviation_checks.py +6 -8
  99. package/hooks/validators/code_quality_checks.py +4 -4
  100. package/hooks/validators/config/abbreviation_checks_constants.py +3 -0
  101. package/hooks/validators/config/baseline_identity_constants.py +12 -0
  102. package/hooks/validators/config/directory_exemption_constants.py +44 -1
  103. package/hooks/validators/config/fast_save_validator_constants.py +32 -0
  104. package/hooks/validators/config/hook_timing_harness_constants.py +3 -1
  105. package/hooks/validators/config/test_abbreviation_checks_constants.py +11 -0
  106. package/hooks/validators/config/validator_base_constants.py +9 -0
  107. package/hooks/validators/fast_save_validators.py +275 -0
  108. package/hooks/validators/hook_timing_harness.py +8 -4
  109. package/hooks/validators/pr_reference_checks.py +2 -2
  110. package/hooks/validators/python_antipattern_checks.py +3 -3
  111. package/hooks/validators/python_style_checks.py +37 -62
  112. package/hooks/validators/python_style_helpers.py +16 -2
  113. package/hooks/validators/python_style_import_bootstrap.py +83 -0
  114. package/hooks/validators/react_checks.py +2 -9
  115. package/hooks/validators/run_all_validators.py +201 -155
  116. package/hooks/validators/security_checks.py +3 -3
  117. package/hooks/validators/test_abbreviation_checks.py +20 -0
  118. package/hooks/validators/test_directory_exemption_constants.py +30 -24
  119. package/hooks/validators/test_fast_save_validators.py +172 -0
  120. package/hooks/validators/test_hook_timing_harness.py +10 -1
  121. package/hooks/validators/test_python_style_checks.py +9 -0
  122. package/hooks/validators/test_python_style_checks_import_order.py +81 -0
  123. package/hooks/validators/test_python_style_helpers.py +35 -0
  124. package/hooks/validators/test_python_style_import_bootstrap.py +69 -0
  125. package/hooks/validators/test_run_all_validators.py +46 -0
  126. package/hooks/validators/test_run_all_validators_pretooluse.py +163 -0
  127. package/hooks/validators/test_run_all_validators_repository_root.py +202 -0
  128. package/hooks/validators/test_validator_base.py +51 -2
  129. package/hooks/validators/todo_checks.py +2 -2
  130. package/hooks/validators/type_safety_checks.py +3 -3
  131. package/hooks/validators/useless_test_checks.py +3 -3
  132. package/hooks/validators/validator_base.py +73 -1
  133. package/package.json +1 -1
  134. package/rules/docstring-prose-matches-implementation.md +1 -1
  135. package/rules/git-workflow.md +2 -0
  136. package/rules/testing.md +4 -0
  137. package/scripts/codex_compat_materializer.py +5 -0
  138. package/scripts/dev_env_scripts_constants/grok_worker_constants.py +15 -0
  139. package/scripts/grok_headless_runner.py +15 -12
  140. package/scripts/shared_tree_paths.py +70 -0
  141. package/scripts/test_shared_tree_paths.py +143 -0
  142. package/scripts/tests/test_codex_compat_materializer.py +37 -11
  143. package/hooks/blocking/tests/conftest.py +0 -10
@@ -16,6 +16,7 @@ in-process AST scan the production enforcer runs.
16
16
 
17
17
  from __future__ import annotations
18
18
 
19
+ import ast
19
20
  import importlib.util
20
21
  import pathlib
21
22
  import sys
@@ -34,6 +35,20 @@ _hook_module = importlib.util.module_from_spec(_hook_spec)
34
35
  _hook_spec.loader.exec_module(_hook_module)
35
36
  check_same_file_inline_duplicate_body = _hook_module.check_same_file_inline_duplicate_body
36
37
 
38
+ _duplicate_body_spec = importlib.util.spec_from_file_location(
39
+ "code_rules_duplicate_body",
40
+ _HOOK_DIRECTORY / "code_rules_duplicate_body.py",
41
+ )
42
+ assert _duplicate_body_spec is not None
43
+ assert _duplicate_body_spec.loader is not None
44
+ _duplicate_body_module = importlib.util.module_from_spec(_duplicate_body_spec)
45
+ _duplicate_body_spec.loader.exec_module(_duplicate_body_module)
46
+
47
+ MEMO_CORPUS_MODULE_GLOB = "code_rules_*.py"
48
+ TEST_MODULE_NAME_PREFIX = "test_"
49
+ MINIMUM_MEMO_CORPUS_MODULE_COUNT = 20
50
+ EXTRA_DUPLICATE_PAIRS_BEYOND_THE_CEILING = 5
51
+
37
52
 
38
53
  PR_470_SHAPE_SOURCE = (
39
54
  "import asyncio\n"
@@ -464,3 +479,232 @@ def test_should_carry_both_helper_and_enclosing_spans_for_the_commit_gate_scoper
464
479
  "the union the PreToolUse path scopes on — not the helper span alone, "
465
480
  f"got: {matching_issues[0]}"
466
481
  )
482
+
483
+
484
+ NO_INLINE_DUPLICATE_SOURCE = (
485
+ "async def _wait_for_content_image_to_render(automation: object) -> None:\n"
486
+ " assert automation.detector is not None\n"
487
+ " await automation.detector.wait_for_element(selector)\n"
488
+ " logger.info('rendered')\n"
489
+ "\n"
490
+ "\n"
491
+ "async def _do_other_work(automation: object) -> None:\n"
492
+ " await automation.cdp.reload()\n"
493
+ " logger.info('reloaded')\n"
494
+ " return None\n"
495
+ )
496
+
497
+
498
+ def _memo_corpus_module_paths() -> list[pathlib.Path]:
499
+ """Return the production code-rules modules used as a statement corpus.
500
+
501
+ Returns:
502
+ Every non-test ``code_rules_*.py`` module in the blocking hook directory,
503
+ in sorted order, which supplies thousands of real statements of every
504
+ shape the scan meets in practice.
505
+ """
506
+ return sorted(
507
+ each_path
508
+ for each_path in _HOOK_DIRECTORY.glob(MEMO_CORPUS_MODULE_GLOB)
509
+ if not each_path.name.startswith(TEST_MODULE_NAME_PREFIX)
510
+ )
511
+
512
+
513
+ def _all_statements_in_module(module_path: pathlib.Path) -> list[ast.stmt]:
514
+ """Return every statement node parsed from a repository module.
515
+
516
+ The returned list holds the nodes, so they stay alive across both memo passes
517
+ and the second pass reads the very objects the first pass recorded.
518
+
519
+ Args:
520
+ module_path: The repository module to parse.
521
+
522
+ Returns:
523
+ Every statement node in the module, in walk order.
524
+ """
525
+ parsed_module = ast.parse(module_path.read_text(encoding="utf-8"))
526
+ return [
527
+ each_node
528
+ for each_node in ast.walk(parsed_module)
529
+ if isinstance(each_node, ast.stmt)
530
+ ]
531
+
532
+
533
+ def _memo_disagreements(
534
+ all_statements: list[ast.stmt],
535
+ dump_by_statement: dict[ast.stmt, str],
536
+ module_name: str,
537
+ ) -> list[str]:
538
+ """Return a location for every statement the memo dumps differently.
539
+
540
+ Args:
541
+ all_statements: The statement nodes to compare.
542
+ dump_by_statement: The memo under test, mutated in place.
543
+ module_name: The module name to name in a disagreement location.
544
+
545
+ Returns:
546
+ A ``module:line`` location per statement whose memoized dump differs from
547
+ the uncached dump, and an empty list when the memo is transparent.
548
+ """
549
+ return [
550
+ f"{module_name}:{each_statement.lineno}"
551
+ for each_statement in all_statements
552
+ if _duplicate_body_module._memoized_statement_dump(
553
+ each_statement, dump_by_statement
554
+ )
555
+ != _duplicate_body_module._normalized_statement_dump(each_statement)
556
+ ]
557
+
558
+
559
+ def _cold_and_warm_memo_disagreements(
560
+ all_module_paths: list[pathlib.Path],
561
+ ) -> tuple[list[str], list[str]]:
562
+ """Compare memoized against uncached dumps twice over the same statements.
563
+
564
+ The first pass over a module fills the memo and the second reads it warm, so
565
+ both the computed value and the served value are held against the uncached
566
+ dump.
567
+
568
+ Args:
569
+ all_module_paths: The corpus modules to parse and compare.
570
+
571
+ Returns:
572
+ The cold-pass disagreement locations and the warm-pass disagreement
573
+ locations.
574
+ """
575
+ dump_by_statement: dict[ast.stmt, str] = {}
576
+ all_cold_disagreements: list[str] = []
577
+ all_warm_disagreements: list[str] = []
578
+ for each_path in all_module_paths:
579
+ all_statements = _all_statements_in_module(each_path)
580
+ all_cold_disagreements += _memo_disagreements(
581
+ all_statements, dump_by_statement, each_path.name
582
+ )
583
+ all_warm_disagreements += _memo_disagreements(
584
+ all_statements, dump_by_statement, each_path.name
585
+ )
586
+ assert dump_by_statement, "the memo recorded nothing, so nothing was proven"
587
+ return all_cold_disagreements, all_warm_disagreements
588
+
589
+
590
+ def test_should_memoize_every_repository_statement_dump_transparently() -> None:
591
+ """The memo must be invisible: every dump it serves equals the uncached dump.
592
+
593
+ The inline scan's speed rests on serving each statement's dump from a memo,
594
+ which makes the memo the one place a behavior change could hide. Real
595
+ repository modules supply the statements, so the proof covers every statement
596
+ shape the scan meets in this repository.
597
+ """
598
+ all_module_paths = _memo_corpus_module_paths()
599
+ assert len(all_module_paths) >= MINIMUM_MEMO_CORPUS_MODULE_COUNT, (
600
+ "the transparency proof needs a real corpus, but the glob found "
601
+ f"only {len(all_module_paths)} modules"
602
+ )
603
+ all_cold, all_warm = _cold_and_warm_memo_disagreements(all_module_paths)
604
+ assert all_cold == [], (
605
+ "a cold memo must compute the same dump the uncached helper computes, "
606
+ f"but these statements disagreed: {all_cold[:10]}"
607
+ )
608
+ assert all_warm == [], (
609
+ "a warm memo must serve the same dump the uncached helper computes, "
610
+ f"but these statements disagreed: {all_warm[:10]}"
611
+ )
612
+
613
+
614
+ def test_should_report_the_same_verdict_when_an_earlier_scan_used_the_same_path() -> None:
615
+ """No memo may outlive one scan, so an earlier scan cannot color a later one.
616
+
617
+ A dump memo that persisted between calls — keyed on a path, or on a node slot
618
+ a later parse could reuse — would let one file's statements answer for
619
+ another's. Two different sources are scanned under one path, then the first is
620
+ scanned again, so a verdict that shifted on the repeat would expose the leak.
621
+ """
622
+ first_duplicate_issues = check_same_file_inline_duplicate_body(
623
+ PR_470_SHAPE_SOURCE, "account_switcher.py"
624
+ )
625
+ clean_issues = check_same_file_inline_duplicate_body(
626
+ NO_INLINE_DUPLICATE_SOURCE, "account_switcher.py"
627
+ )
628
+ repeat_duplicate_issues = check_same_file_inline_duplicate_body(
629
+ PR_470_SHAPE_SOURCE, "account_switcher.py"
630
+ )
631
+ assert first_duplicate_issues, "the duplicate source must flag on its own"
632
+ assert clean_issues == [], (
633
+ "the clean source must not inherit a verdict from the duplicate source "
634
+ f"scanned before it under the same path, got: {clean_issues}"
635
+ )
636
+ assert repeat_duplicate_issues == first_duplicate_issues, (
637
+ "the duplicate source must produce the same verdict on a repeat scan, "
638
+ f"got {repeat_duplicate_issues} after {first_duplicate_issues}"
639
+ )
640
+
641
+
642
+ def test_should_read_no_function_when_the_file_holds_no_qualifying_helper() -> None:
643
+ """A file with no candidate helper is answered without reading any function.
644
+
645
+ Most files carry no function that clears the helper-window filter, so the scan
646
+ leaves them after that filter and takes no per-function readings. The memo
647
+ stays empty in that case, which both proves the readings were skipped and
648
+ pins the verdict such a file gets.
649
+ """
650
+ all_module_functions = ast.parse(NO_INLINE_DUPLICATE_SOURCE).body
651
+ all_windows = [
652
+ _duplicate_body_module._helper_match_window_dumps(each_function)
653
+ for each_function in all_module_functions
654
+ if isinstance(each_function, ast.FunctionDef | ast.AsyncFunctionDef)
655
+ ]
656
+ assert all(each_window is None for each_window in all_windows), (
657
+ "this source must hold no qualifying helper for the skip to be exercised, "
658
+ f"got windows: {all_windows}"
659
+ )
660
+ issues = check_same_file_inline_duplicate_body(
661
+ NO_INLINE_DUPLICATE_SOURCE, "module.py"
662
+ )
663
+ assert issues == [], f"a file with no qualifying helper must not flag, got: {issues}"
664
+
665
+
666
+ def _duplicated_helper_pair_source(pair_index: int) -> str:
667
+ """Return one helper and one strictly larger function that inlines its body.
668
+
669
+ Each pair carries its own variable name, so a helper matches only the
670
+ enclosing function of its own pair and every pair contributes one report.
671
+
672
+ Args:
673
+ pair_index: The number distinguishing this pair from the others.
674
+
675
+ Returns:
676
+ Source text holding the helper and its enclosing function.
677
+ """
678
+ duplicated_block = (
679
+ " try:\n"
680
+ f" record_{pair_index} = records.load({pair_index})\n"
681
+ " except KeyError:\n"
682
+ " logger.warning('record missing')\n"
683
+ f" record_{pair_index} = None\n"
684
+ f" return record_{pair_index}\n"
685
+ )
686
+ return (
687
+ f"def load_record_{pair_index}(records):\n{duplicated_block}\n\n"
688
+ f"def refresh_record_{pair_index}(records):\n"
689
+ f" records.begin({pair_index})\n{duplicated_block}\n\n"
690
+ )
691
+
692
+
693
+ def test_should_cap_the_reported_issue_count_at_the_module_ceiling() -> None:
694
+ """A file full of inline duplicates reports the ceiling, not one per pair.
695
+
696
+ The blocking payload a single write can carry is bounded, so a file holding
697
+ more duplicated helpers than the ceiling still reports exactly the ceiling.
698
+ The source is built with more pairs than the ceiling allows, so a lost bound
699
+ would show up as a longer report.
700
+ """
701
+ ceiling = _duplicate_body_module.MAX_DUPLICATE_BODY_ISSUES
702
+ pair_count = ceiling + EXTRA_DUPLICATE_PAIRS_BEYOND_THE_CEILING
703
+ source = "".join(
704
+ _duplicated_helper_pair_source(each_index) for each_index in range(pair_count)
705
+ )
706
+ issues = check_same_file_inline_duplicate_body(source, "module.py")
707
+ assert len(issues) == ceiling, (
708
+ f"{pair_count} duplicated pairs must report the {ceiling}-issue ceiling, "
709
+ f"got {len(issues)} issues"
710
+ )
@@ -6,6 +6,8 @@ import sys
6
6
  from pathlib import Path
7
7
  from types import SimpleNamespace
8
8
 
9
+ import pytest
10
+
9
11
  _BLOCKING_DIRECTORY = str(Path(__file__).resolve().parent)
10
12
  _HOOKS_DIRECTORY = str(Path(__file__).resolve().parent.parent)
11
13
  if _BLOCKING_DIRECTORY not in sys.path:
@@ -103,7 +105,19 @@ def test_scan_function_body_constants_does_not_flag_module_level() -> None:
103
105
  assert advisory_issues == []
104
106
 
105
107
 
106
- def test_advisory_should_not_flag_class_attribute_after_method_def() -> None:
108
+ def _advisory_stderr(source: str, capsys: pytest.CaptureFixture[str]) -> str:
109
+ """Run the advisory check over source and hand back what it wrote to stderr.
110
+
111
+ The check returns nothing, so stderr is the only place a finding shows up.
112
+ """
113
+ code_rules_enforcer.check_constants_outside_config_advisory(
114
+ source,
115
+ "example_module.py",
116
+ )
117
+ return capsys.readouterr().err
118
+
119
+
120
+ def test_advisory_should_not_flag_class_attribute_after_method_def(capsys: pytest.CaptureFixture[str]) -> None:
107
121
  source_with_class_attribute_after_method = (
108
122
  "class ExampleModel:\n"
109
123
  " def method_a(self) -> None:\n"
@@ -111,49 +125,40 @@ def test_advisory_should_not_flag_class_attribute_after_method_def() -> None:
111
125
  "\n"
112
126
  " TABLE_NAME = \"example\"\n"
113
127
  )
114
- advisory_issues = code_rules_enforcer.check_constants_outside_config_advisory(
115
- source_with_class_attribute_after_method,
116
- "example_module.py",
117
- )
118
- assert advisory_issues == [], (
128
+ flagged_names = _advisory_stderr(source_with_class_attribute_after_method, capsys)
129
+ assert flagged_names == "", (
119
130
  "Class-level TABLE_NAME attribute must not be flagged as function-local"
120
131
  )
121
132
 
122
133
 
123
- def test_advisory_should_still_flag_actual_method_body_constant() -> None:
134
+ def test_advisory_should_still_flag_actual_method_body_constant(capsys: pytest.CaptureFixture[str]) -> None:
124
135
  source_with_method_body_constant = (
125
136
  "class ExampleModel:\n"
126
137
  " def method_a(self) -> None:\n"
127
138
  " MAXIMUM_RETRIES = 3\n"
128
139
  " return None\n"
129
140
  )
130
- advisory_issues = code_rules_enforcer.check_constants_outside_config_advisory(
131
- source_with_method_body_constant,
132
- "example_module.py",
133
- )
134
- assert len(advisory_issues) == 1, (
135
- "Method-body UPPER_SNAKE constant must still surface as advisory"
141
+ flagged_names = _advisory_stderr(source_with_method_body_constant, capsys)
142
+ assert "MAXIMUM_RETRIES" in flagged_names, (
143
+ f"Method-body UPPER_SNAKE constant must still surface as advisory, "
144
+ f"got: {flagged_names!r}"
136
145
  )
137
- assert "MAXIMUM_RETRIES" in advisory_issues[0]
138
146
 
139
147
 
140
- def test_advisory_should_flag_annotated_function_body_constant() -> None:
148
+ def test_advisory_should_flag_annotated_function_body_constant(capsys: pytest.CaptureFixture[str]) -> None:
141
149
  source_with_annotated_function_body_constant = (
142
150
  "def example_function() -> None:\n"
143
151
  " MAXIMUM_RETRIES: int = 3\n"
144
152
  " return None\n"
145
153
  )
146
- advisory_issues = code_rules_enforcer.check_constants_outside_config_advisory(
147
- source_with_annotated_function_body_constant,
148
- "example_module.py",
154
+ flagged_names = _advisory_stderr(source_with_annotated_function_body_constant, capsys)
155
+ assert "MAXIMUM_RETRIES" in flagged_names, (
156
+ f"Annotated function-body UPPER_SNAKE constant (PEP 526) must surface as advisory, "
157
+ f"got: {flagged_names!r}"
149
158
  )
150
- assert len(advisory_issues) == 1, (
151
- "Annotated function-body UPPER_SNAKE constant (PEP 526) must surface as advisory"
152
- )
153
- assert "MAXIMUM_RETRIES" in advisory_issues[0]
154
159
 
155
160
 
156
- def test_advisory_should_flag_outer_constants_after_nested_def() -> None:
161
+ def test_advisory_should_flag_outer_constants_after_nested_def(capsys: pytest.CaptureFixture[str]) -> None:
157
162
  source_with_nested_def = (
158
163
  "def outer():\n"
159
164
  " OUTER_CONST = 1\n"
@@ -161,11 +166,7 @@ def test_advisory_should_flag_outer_constants_after_nested_def() -> None:
161
166
  " INNER_CONST = 2\n"
162
167
  " ANOTHER_OUTER = 3\n"
163
168
  )
164
- advisory_issues = code_rules_enforcer.check_constants_outside_config_advisory(
165
- source_with_nested_def,
166
- "example_module.py",
167
- )
168
- flagged_names = " ".join(advisory_issues)
169
+ flagged_names = _advisory_stderr(source_with_nested_def, capsys)
169
170
  assert "OUTER_CONST" in flagged_names, (
170
171
  "OUTER_CONST before nested def must be flagged"
171
172
  )
@@ -36,6 +36,8 @@ code_rules_enforcer = SimpleNamespace(
36
36
  validate_content=validate_content,
37
37
  )
38
38
 
39
+ pytestmark = pytest.mark.usefixtures("ephemeral_exempt_off")
40
+
39
41
 
40
42
  def _oversized_function_source(name: str) -> str:
41
43
  body_line_count = code_rules_enforcer.FUNCTION_LENGTH_BLOCKING_THRESHOLD - 1
@@ -175,6 +177,28 @@ def test_unreadable_prior_yields_no_prior_and_no_reconstruction() -> None:
175
177
  assert post_edit_content is None
176
178
 
177
179
 
180
+ def test_prior_and_post_edit_content_honors_replace_all(
181
+ tmp_path_factory: pytest.TempPathFactory,
182
+ ) -> None:
183
+ """An Edit carrying replace_all rewrites every occurrence in the post-edit view.
184
+
185
+ The MultiEdit lane reconstructs through apply_edits and has honored the flag
186
+ since it landed there. The Edit lane must agree, or the enforcer judges a
187
+ replace_all Edit against a file that never exists on disk.
188
+ """
189
+ production_directory = tmp_path_factory.mktemp("replace_all_pkg")
190
+ source_file = production_directory / "edited_module.py"
191
+ source_file.write_text("value = 1\nvalue = 1\n", encoding="utf-8")
192
+ prior_content, post_edit_content = code_rules_enforcer.prior_and_post_edit_content(
193
+ str(source_file),
194
+ old_string="value = 1",
195
+ new_string="value = 2",
196
+ is_replace_all=True,
197
+ )
198
+ assert prior_content == "value = 1\nvalue = 1\n"
199
+ assert post_edit_content == "value = 2\nvalue = 2\n"
200
+
201
+
178
202
  def test_edit_with_missing_old_string_runs_whole_file_against_on_disk_content(
179
203
  tmp_path_factory: pytest.TempPathFactory,
180
204
  ) -> None:
@@ -33,6 +33,8 @@ from code_rules_gate_parts.tests._repo_test_helpers import ( # noqa: E402
33
33
  write_commit_and_stage_change,
34
34
  )
35
35
 
36
+ pytestmark = pytest.mark.usefixtures("ephemeral_exempt_off")
37
+
36
38
 
37
39
  PRODUCTION_FILE_PATH = "packages/app/services.py"
38
40
  ENFORCER_SCRIPT_PATH = Path(__file__).with_name("code_rules_enforcer.py")
@@ -36,6 +36,8 @@ from code_rules_enforcer_test_support import ( # noqa: E402
36
36
  run_write_entrypoint,
37
37
  )
38
38
 
39
+ pytestmark = pytest.mark.usefixtures("ephemeral_exempt_off")
40
+
39
41
  PASS_THROUGH_ALIAS_SOURCE = (
40
42
  "def find_bare_path_segments(content: str) -> set[str]:\n"
41
43
  " return {part for part in content.split() if part}\n"
@@ -0,0 +1,43 @@
1
+ """Tests for the Codex apply_patch path-only target resolver."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+ import pytest
8
+
9
+ from codex_apply_patch import (
10
+ CODEX_ADD_OPERATION,
11
+ CodexPatchError,
12
+ codex_patch_operation_targets,
13
+ )
14
+
15
+
16
+ def test_codex_patch_operation_targets_names_every_section_without_reading_content(
17
+ tmp_path: Path, three_operation_patch: str
18
+ ) -> None:
19
+ """The path-only helper resolves every section's target without any disk read.
20
+
21
+ Unlike ``parse_codex_apply_patch``, it never reads prior file content, so a
22
+ caller that only needs each target path is not tripped up by an unreadable
23
+ prior file.
24
+ """
25
+ all_targets = codex_patch_operation_targets(three_operation_patch, str(tmp_path))
26
+
27
+ all_target_names = {
28
+ (each_operation, str(each_path).rsplit("/", 1)[-1])
29
+ for each_operation, each_path in all_targets
30
+ }
31
+ assert all_target_names == {
32
+ ("update", "updated.py"),
33
+ (CODEX_ADD_OPERATION, "added.py"),
34
+ ("delete", "deleted.py"),
35
+ }
36
+
37
+
38
+ def test_codex_patch_operation_targets_rejects_path_traversal(tmp_path: Path) -> None:
39
+ """A patch path that escapes the working directory is rejected before any read."""
40
+ escaping_patch = "*** Begin Patch\n*** Add File: ../outside.py\n+content\n*** End Patch"
41
+
42
+ with pytest.raises(CodexPatchError):
43
+ codex_patch_operation_targets(escaping_patch, str(tmp_path))
@@ -205,6 +205,74 @@ def test_extract_payload_text_returns_empty_for_unknown_tool() -> None:
205
205
  assert extracted == ("", "")
206
206
 
207
207
 
208
+ def test_every_applicable_tool_name_reads_payload_text() -> None:
209
+ """extract_payload_text reads content for every name the shared constant lists."""
210
+ for each_applicable_tool_name in hook_module.ALL_APPLICABLE_TOOL_NAMES:
211
+ _file_path, scanned_text = extract_payload_text(
212
+ each_applicable_tool_name,
213
+ {
214
+ "file_path": "foo.py",
215
+ "content": "abc",
216
+ "new_string": "abc",
217
+ "edits": [{"old_string": "a", "new_string": "abc"}],
218
+ },
219
+ )
220
+ assert scanned_text, f"{each_applicable_tool_name} must read some scanned text"
221
+
222
+
223
+ def test_extract_payload_text_reads_every_multi_edit_new_string() -> None:
224
+ extracted = extract_payload_text(
225
+ "MultiEdit",
226
+ {
227
+ "file_path": "foo.py",
228
+ "edits": [
229
+ {"old_string": "a = 1", "new_string": "a = 11"},
230
+ {"old_string": "b = 2", "new_string": "def force_rmtree(target_path):\n pass"},
231
+ ],
232
+ },
233
+ )
234
+ assert extracted[0] == "foo.py"
235
+ assert "force_rmtree" in extracted[1]
236
+
237
+
238
+ def test_main_blocks_trio_copy_introduced_by_second_multi_edit() -> None:
239
+ """A helper definition in the second edit of a MultiEdit is caught, not only the first."""
240
+ stdout_text, exit_code = _run_hook(
241
+ {
242
+ "tool_name": "MultiEdit",
243
+ "tool_input": {
244
+ "file_path": "shared_utils/samsung_utils/cert_failure_processor/parser.py",
245
+ "edits": [
246
+ {"old_string": "a = 1", "new_string": "a = 11"},
247
+ {"old_string": "b = 2", "new_string": COPIED_TRIO},
248
+ ],
249
+ },
250
+ }
251
+ )
252
+ assert exit_code == 0
253
+ response_payload = json.loads(stdout_text)
254
+ decision_block = response_payload["hookSpecificOutput"]
255
+ assert decision_block["permissionDecision"] == "deny"
256
+ assert "duplicate-rmtree-helper" in decision_block["permissionDecisionReason"]
257
+
258
+
259
+ def test_main_allows_clean_multi_edit() -> None:
260
+ stdout_text, exit_code = _run_hook(
261
+ {
262
+ "tool_name": "MultiEdit",
263
+ "tool_input": {
264
+ "file_path": "shared_utils/samsung_utils/cert_failure_processor/parser.py",
265
+ "edits": [
266
+ {"old_string": "a = 1", "new_string": "a = 11"},
267
+ {"old_string": "b = 2", "new_string": "b = 22"},
268
+ ],
269
+ },
270
+ }
271
+ )
272
+ assert exit_code == 0
273
+ assert stdout_text == ""
274
+
275
+
208
276
  def _run_hook_with_stdin_text(stdin_text: str) -> tuple[str, str, int]:
209
277
  captured_stdout = io.StringIO()
210
278
  captured_stderr = io.StringIO()
@@ -193,6 +193,16 @@ def test_written_content_reads_edit_new_string() -> None:
193
193
  assert written_content("Edit", edit_input) == "edited body"
194
194
 
195
195
 
196
+ def test_written_content_reads_every_multi_edit_new_string() -> None:
197
+ multi_edit_input = {
198
+ "edits": [
199
+ {"old_string": "a = 1", "new_string": "a = 11"},
200
+ {"old_string": "b = 2", "new_string": _OVERSTATED_MESSAGE_MODULE},
201
+ ]
202
+ }
203
+ assert _OVERSTATED_MESSAGE_MODULE in written_content("MultiEdit", multi_edit_input)
204
+
205
+
196
206
  def _run_main_with_io(
197
207
  input_text: str, *, is_prose_style_enabled: bool = True
198
208
  ) -> str:
@@ -248,6 +258,37 @@ def test_main_blocks_overstated_hook_module_edit() -> None:
248
258
  assert payload["hookSpecificOutput"]["permissionDecision"] == "deny"
249
259
 
250
260
 
261
+ def test_main_blocks_overstatement_introduced_by_second_multi_edit() -> None:
262
+ """An overstated claim in the second edit of a MultiEdit is caught, not only the first."""
263
+ hook_input = {
264
+ "tool_name": "MultiEdit",
265
+ "tool_input": {
266
+ "file_path": "/repo/hooks/hooks_constants/some_blocker_constants.py",
267
+ "edits": [
268
+ {"old_string": "a = 1", "new_string": "a = 11"},
269
+ {"old_string": "b = 2", "new_string": _OVERSTATED_MESSAGE_MODULE},
270
+ ],
271
+ },
272
+ }
273
+ output_text = _run_main_with_io(json.dumps(hook_input))
274
+ payload = json.loads(output_text)
275
+ assert payload["hookSpecificOutput"]["permissionDecision"] == "deny"
276
+
277
+
278
+ def test_main_passes_clean_multi_edit() -> None:
279
+ hook_input = {
280
+ "tool_name": "MultiEdit",
281
+ "tool_input": {
282
+ "file_path": "/repo/hooks/hooks_constants/some_blocker_constants.py",
283
+ "edits": [
284
+ {"old_string": "a = 1", "new_string": "a = 11"},
285
+ {"old_string": "b = 2", "new_string": _FIXED_MESSAGE_MODULE},
286
+ ],
287
+ },
288
+ }
289
+ assert _run_main_with_io(json.dumps(hook_input)) == ""
290
+
291
+
251
292
  def test_main_passes_fixed_hook_module_write() -> None:
252
293
  hook_input = {
253
294
  "tool_name": "Write",
@@ -13,12 +13,22 @@ _HOOK_DIR = Path(__file__).parent
13
13
  _HOOKS_DIR = _HOOK_DIR.parent
14
14
 
15
15
  try:
16
- from pii_payload_scan import evaluate_post_body_texts, evaluate_write_edit_payload
16
+ from pii_payload_scan import (
17
+ evaluate_apply_patch_payload,
18
+ evaluate_post_body_texts,
19
+ evaluate_write_edit_payload,
20
+ )
17
21
  except ImportError:
18
22
  for each_bootstrap_directory in (str(_HOOK_DIR), str(_HOOKS_DIR)):
19
23
  if each_bootstrap_directory not in sys.path:
20
24
  sys.path.insert(0, each_bootstrap_directory)
21
- from pii_payload_scan import evaluate_post_body_texts, evaluate_write_edit_payload
25
+ from pii_payload_scan import (
26
+ evaluate_apply_patch_payload,
27
+ evaluate_post_body_texts,
28
+ evaluate_write_edit_payload,
29
+ )
30
+
31
+ pytestmark = pytest.mark.usefixtures("ephemeral_exempt_off")
22
32
 
23
33
  _ALLOW_SLUG = "AllowOwner/allow-repo"
24
34
  _OTHER_SLUG = "OtherOwner/other-repo"
@@ -166,3 +176,56 @@ def test_allowlisted_value_under_missing_nested_parent_is_allowed(
166
176
  nested_target = repository_root / "new_dir" / "deeper" / "notes.md"
167
177
  assert not nested_target.parent.exists()
168
178
  assert _write_deny_reason(nested_target, allowed_value) is None
179
+
180
+
181
+ def test_apply_patch_add_with_pii_is_denied(tmp_path: Path) -> None:
182
+ repository_root = tmp_path / "repo"
183
+ _init_repo_with_github_origin(repository_root, _ALLOW_SLUG)
184
+ deny_reason = evaluate_apply_patch_payload(
185
+ {
186
+ "command": (
187
+ "*** Begin Patch\n"
188
+ "*** Add File: notes.md\n"
189
+ f"+Reach me at {_assembled_fixture_email()}\n"
190
+ "*** End Patch"
191
+ )
192
+ },
193
+ hook_payload={"cwd": str(repository_root)},
194
+ )
195
+ assert deny_reason is not None
196
+ assert "email" in deny_reason
197
+
198
+
199
+ def test_apply_patch_add_with_clean_content_is_allowed(tmp_path: Path) -> None:
200
+ repository_root = tmp_path / "repo"
201
+ _init_repo_with_github_origin(repository_root, _ALLOW_SLUG)
202
+ deny_reason = evaluate_apply_patch_payload(
203
+ {
204
+ "command": (
205
+ "*** Begin Patch\n"
206
+ "*** Add File: notes.md\n"
207
+ "+nothing sensitive here\n"
208
+ "*** End Patch"
209
+ )
210
+ },
211
+ hook_payload={"cwd": str(repository_root)},
212
+ )
213
+ assert deny_reason is None
214
+
215
+
216
+ def test_apply_patch_payload_accepts_the_tool_input_keyword(tmp_path: Path) -> None:
217
+ """evaluate_apply_patch_payload's first parameter is named all_tool_input."""
218
+ repository_root = tmp_path / "repo"
219
+ _init_repo_with_github_origin(repository_root, _ALLOW_SLUG)
220
+ deny_reason = evaluate_apply_patch_payload(
221
+ all_tool_input={
222
+ "command": (
223
+ "*** Begin Patch\n"
224
+ "*** Add File: notes.md\n"
225
+ "+nothing sensitive here\n"
226
+ "*** End Patch"
227
+ )
228
+ },
229
+ hook_payload={"cwd": str(repository_root)},
230
+ )
231
+ assert deny_reason is None