claude-dev-env 2.17.0 → 2.19.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 (117) hide show
  1. package/.agents/skills/AGENTS.md +4 -4
  2. package/.agents/skills/_shared/AGENTS.md +1 -0
  3. package/.agents/skills/_shared/pr-loop/AGENTS.md +1 -0
  4. package/.agents/skills/_shared/pr-loop/preflight-proposal.contract.test.mjs +89 -0
  5. package/.agents/skills/_shared/pr-loop/preflight-proposal.md +5 -0
  6. package/.agents/skills/orchestrator/SKILL.md +6 -4
  7. package/.agents/skills/orchestrator-refresh/SKILL.md +9 -5
  8. package/.agents/skills/pr-cleanup/SKILL.md +17 -85
  9. package/.agents/skills/pr-cleanup/reference/process-inventory.md +15 -0
  10. package/.agents/skills/pr-cleanup/reference/task-seeds.md +20 -0
  11. package/.agents/skills/{name-by-capability-audit → pr-name-by-capability}/SKILL.md +18 -12
  12. package/.agents/skills/{name-by-capability-audit → pr-name-by-capability}/reference/offense-examples.md +1 -1
  13. package/.agents/skills/{name-by-capability-audit → pr-name-by-capability}/reference/task-seeds.md +3 -2
  14. package/.agents/skills/pr-refinement/SKILL.md +31 -0
  15. package/.agents/skills/{shared-extraction-audit → pr-shared-extraction}/SKILL.md +24 -7
  16. package/.agents/skills/{small-cl → pr-small-cl}/SKILL.md +1 -1
  17. package/.agents/skills/prototype/scripts/test_probe_sandbox_safety.py +33 -5
  18. package/.agents/skills/skill-builder/SKILL.md +1 -0
  19. package/.agents/skills/team-advisor/SKILL.md +5 -5
  20. package/.agents/skills-archived/bugteam/SKILL.md +1 -1
  21. package/.agents/skills-archived/bugteam/test_skill_additions.py +1 -1
  22. package/.agents/skills-archived/comments/SKILL.md +1 -1
  23. package/.agents/skills-archived/descriptions/SKILL.md +1 -1
  24. package/.agents/skills-archived/reviews/SKILL.md +1 -1
  25. package/AGENTS.md +1 -1
  26. package/_shared/advisor/AGENTS.md +5 -5
  27. package/_shared/advisor/advisor-protocol.md +54 -31
  28. package/_shared/advisor/reference/advisor-block.md +5 -1
  29. package/_shared/advisor/reference/consult-format.md +1 -1
  30. package/_shared/advisor/reference/identity.md +28 -0
  31. package/_shared/advisor/reference/lifecycle.md +8 -1
  32. package/_shared/advisor/reference/sol-rung.md +12 -7
  33. package/_shared/advisor/reference/spawn-walk-log.md +6 -5
  34. package/_shared/advisor/reference/third-party-bind.md +5 -6
  35. package/_shared/advisor/reference/warm-up.md +9 -2
  36. package/_shared/advisor/scripts/codex_sol_advisor.py +66 -11
  37. package/_shared/advisor/scripts/config/advisor_scripts_constants/advisor_route_constants.py +9 -0
  38. package/_shared/advisor/scripts/config/advisor_scripts_constants/model_tier_run_validator_constants.py +16 -4
  39. package/_shared/advisor/scripts/config/advisor_scripts_constants/sol_advisor_constants.py +11 -10
  40. package/_shared/advisor/scripts/model_tier_run_validator.py +50 -23
  41. package/_shared/advisor/scripts/tests/test_codex_sol_advisor.py +108 -3
  42. package/_shared/advisor/scripts/tests/test_model_tier_run_validator.py +171 -82
  43. package/_shared/advisor/scripts/tests/test_tier_model_ids.py +43 -0
  44. package/_shared/advisor/scripts/tier_model_ids.py +75 -7
  45. package/_shared/pr-loop/AGENTS.md +2 -1
  46. package/_shared/pr-loop/preflight-proposal.md +56 -0
  47. package/_shared/pr-loop/scripts/code_rules_gate_parts/tests/test_gate_running.py +47 -4
  48. package/_shared/pr-loop/worker-spawn.md +4 -3
  49. package/bin/ever-shipped-skills.mjs +14 -0
  50. package/bin/install-constants.mjs +5 -0
  51. package/bin/install.agents-home.test.mjs +23 -0
  52. package/bin/install.codex-rules.test.mjs +61 -6
  53. package/bin/install.mjs +57 -9
  54. package/bin/install.prune.test.mjs +65 -3
  55. package/bin/install.test.mjs +202 -2
  56. package/docs/CODE_RULES.md +4 -0
  57. package/docs/references/team-advisor-skill.md +2 -2
  58. package/hooks/advisory/migration_safety_advisor.py +14 -14
  59. package/hooks/advisory/test_migration_safety_advisor.py +120 -0
  60. package/hooks/atomic_file_writer.py +81 -0
  61. package/hooks/blocking/AGENTS.md +2 -1
  62. package/hooks/blocking/code_rules_banned_identifiers.py +55 -4
  63. package/hooks/blocking/code_rules_enforcer_test_support.py +92 -0
  64. package/hooks/blocking/destructive_command_blocker.py +8 -7
  65. package/hooks/blocking/pre_tool_use_dispatcher.py +11 -7
  66. package/hooks/blocking/precommit_code_rules_gate.py +14 -139
  67. package/hooks/blocking/sensitive_file_protector.py +8 -6
  68. package/hooks/blocking/session_edit_stage_gate.py +31 -1
  69. package/hooks/blocking/test_claude_md_orphan_file_blocker.py +171 -1
  70. package/hooks/blocking/test_code_rules_enforcer_agent_home_tooling.py +37 -12
  71. package/hooks/blocking/test_code_rules_enforcer_banned_noun_word.py +54 -0
  72. package/hooks/blocking/test_code_rules_enforcer_duplicate_body_hook_routing.py +15 -53
  73. package/hooks/blocking/test_code_rules_enforcer_ephemeral.py +13 -62
  74. package/hooks/blocking/test_code_rules_enforcer_narrow_edit.py +308 -0
  75. package/hooks/blocking/test_code_rules_enforcer_precheck_forecast.py +14 -71
  76. package/hooks/blocking/test_code_rules_enforcer_scratchpad.py +14 -16
  77. package/hooks/blocking/test_code_rules_enforcer_split_entry_2.py +31 -46
  78. package/hooks/blocking/test_code_rules_enforcer_stage.py +192 -0
  79. package/hooks/blocking/test_code_rules_enforcer_zero_payload_alias_hook_routing.py +13 -59
  80. package/hooks/blocking/test_destructive_command_blocker_deny_mode.py +42 -25
  81. package/hooks/blocking/test_destructive_command_blocker_no_verify.py +58 -38
  82. package/hooks/blocking/test_docstring_rule_gate_count_blocker.py +113 -1
  83. package/hooks/blocking/test_env_var_table_code_drift_blocker.py +70 -3
  84. package/hooks/blocking/test_hook_subprocess_support.py +296 -0
  85. package/hooks/blocking/test_package_inventory_stale_blocker.py +1 -1
  86. package/hooks/blocking/test_pii_scanner.py +81 -0
  87. package/hooks/blocking/test_pre_tool_use_dispatcher.py +32 -3
  88. package/hooks/blocking/test_precommit_code_rules_gate.py +11 -16
  89. package/hooks/blocking/test_precommit_code_rules_gate_native_owner.py +168 -0
  90. package/hooks/blocking/test_pytest_testpaths_orphan_blocker.py +25 -18
  91. package/hooks/blocking/test_sensitive_file_protector.py +145 -5
  92. package/hooks/blocking/test_session_edit_stage_gate_staging.py +64 -0
  93. package/hooks/blocking/test_session_edit_stage_gate_support.py +204 -0
  94. package/hooks/blocking/test_session_edit_stage_gate_tracker.py +116 -0
  95. package/hooks/blocking/test_shared_stdin_adoption.py +31 -20
  96. package/hooks/blocking/test_test_preflight_check.py +80 -0
  97. package/hooks/git-hooks/pre_commit.py +6 -2
  98. package/hooks/git-hooks/test_pre_push.py +57 -0
  99. package/hooks/hooks_constants/AGENTS.md +3 -1
  100. package/hooks/hooks_constants/atomic_file_writer_constants.py +4 -0
  101. package/hooks/hooks_constants/banned_identifiers_constants.py +1 -0
  102. package/hooks/hooks_constants/destructive_command_environment_constants.py +18 -0
  103. package/hooks/hooks_constants/destructive_command_segment_constants.py +1 -11
  104. package/hooks/hooks_constants/hardcoded_user_path_constants.py +9 -3
  105. package/hooks/hooks_constants/pre_tool_use_dispatcher_constants.py +1 -1
  106. package/hooks/hooks_constants/sensitive_file_protector_constants.py +2 -4
  107. package/hooks/json_file_reader.py +22 -0
  108. package/hooks/pending_sidecars.py +33 -0
  109. package/hooks/test_atomic_file_writer.py +73 -0
  110. package/hooks/test_json_file_reader.py +24 -0
  111. package/hooks/test_pending_sidecars.py +25 -0
  112. package/package.json +1 -1
  113. /package/.agents/skills/{name-by-capability-audit → pr-name-by-capability}/reference/fetch-commands.md +0 -0
  114. /package/.agents/skills/{name-by-capability-audit → pr-name-by-capability}/reference/report-template.md +0 -0
  115. /package/.agents/skills/{name-by-capability-audit → pr-name-by-capability}/reference/rule-checklist.md +0 -0
  116. /package/.agents/skills/{shared-extraction-audit → pr-shared-extraction}/reference/examples.md +0 -0
  117. /package/.agents/skills/{shared-extraction-audit → pr-shared-extraction}/reference/offense-taxonomy.md +0 -0
@@ -2,12 +2,13 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- import io
6
5
  import json
7
6
  import sys
8
7
  from pathlib import Path
9
8
  from types import SimpleNamespace
10
9
 
10
+ import pytest
11
+
11
12
  _BLOCKING_DIRECTORY = str(Path(__file__).resolve().parent)
12
13
  _HOOKS_DIRECTORY = str(Path(__file__).resolve().parent.parent)
13
14
  if _BLOCKING_DIRECTORY not in sys.path:
@@ -23,6 +24,9 @@ from code_rules_enforcer import ( # noqa: E402
23
24
  prior_and_post_edit_content,
24
25
  validate_content,
25
26
  )
27
+ from code_rules_enforcer_test_support import ( # noqa: E402
28
+ run_serialized_payload_entrypoint,
29
+ )
26
30
 
27
31
  code_rules_enforcer = SimpleNamespace(
28
32
  FUNCTION_LENGTH_BLOCKING_THRESHOLD=FUNCTION_LENGTH_BLOCKING_THRESHOLD,
@@ -35,9 +39,7 @@ code_rules_enforcer = SimpleNamespace(
35
39
 
36
40
  def _oversized_function_source(name: str) -> str:
37
41
  body_line_count = code_rules_enforcer.FUNCTION_LENGTH_BLOCKING_THRESHOLD - 1
38
- body_lines = [
39
- f" bound_{each_index} = {each_index}" for each_index in range(body_line_count)
40
- ]
42
+ body_lines = [f" bound_{each_index} = {each_index}" for each_index in range(body_line_count)]
41
43
  return f"def {name}() -> None:\n" + "\n".join(body_lines) + "\n"
42
44
 
43
45
 
@@ -45,21 +47,8 @@ def _run_main_with_edit_payload(
45
47
  file_path: str,
46
48
  old_string: str,
47
49
  new_string: str,
48
- monkeypatch: object,
49
- capsys: object,
50
50
  ) -> str:
51
- """Drive ``main()`` through its stdin entry point for an Edit and return stdout.
52
-
53
- Args:
54
- file_path: The on-disk path the Edit targets.
55
- old_string: The Edit's ``old_string`` fragment.
56
- new_string: The Edit's ``new_string`` fragment.
57
- monkeypatch: The pytest fixture used to redirect ``sys.stdin``.
58
- capsys: The pytest fixture used to capture the deny payload on stdout.
59
-
60
- Returns:
61
- The captured stdout, which holds the deny payload when violations fire.
62
- """
51
+ """Drive ``main()`` through its stdin entry point for an Edit."""
63
52
  edit_payload = json.dumps(
64
53
  {
65
54
  "tool_name": "Edit",
@@ -70,13 +59,10 @@ def _run_main_with_edit_payload(
70
59
  },
71
60
  }
72
61
  )
73
- getattr(monkeypatch, "setattr")(code_rules_enforcer.sys, "stdin", io.StringIO(edit_payload))
74
- try:
75
- code_rules_enforcer.main([])
76
- except SystemExit:
77
- pass
78
- captured = getattr(capsys, "readouterr")()
79
- return captured.out
62
+ captured_stdout, _exit_code = run_serialized_payload_entrypoint(
63
+ code_rules_enforcer.main, edit_payload
64
+ )
65
+ return captured_stdout
80
66
 
81
67
 
82
68
  def test_banned_noun_word_keeps_in_scope_binding_among_untouched_ones() -> None:
@@ -85,8 +71,7 @@ def test_banned_noun_word_keeps_in_scope_binding_among_untouched_ones() -> None:
85
71
  binding while leaving the untouched bindings out of scope."""
86
72
  leading_count = 5
87
73
  leading_bindings = "".join(
88
- f"LEADING_{each_index}_RESULT_PATH = {each_index}\n"
89
- for each_index in range(leading_count)
74
+ f"LEADING_{each_index}_RESULT_PATH = {each_index}\n" for each_index in range(leading_count)
90
75
  )
91
76
  target_before = "PLACEHOLDER_NAME = 0\n"
92
77
  target_after = "INTRODUCED_RESULT_PATH = 0\n"
@@ -99,9 +84,9 @@ def test_banned_noun_word_keeps_in_scope_binding_among_untouched_ones() -> None:
99
84
  full_file_content=post_edit_full_file,
100
85
  prior_full_file_content=prior_full_file,
101
86
  )
102
- assert any(
103
- "INTRODUCED_RESULT_PATH" in each_issue for each_issue in issues
104
- ), f"in-scope banned-noun past the cap window must still block, got: {issues!r}"
87
+ assert any("INTRODUCED_RESULT_PATH" in each_issue for each_issue in issues), (
88
+ f"in-scope banned-noun past the cap window must still block, got: {issues!r}"
89
+ )
105
90
 
106
91
 
107
92
  def test_banned_noun_edit_drops_untouched_out_of_scope_binding() -> None:
@@ -122,9 +107,9 @@ def test_banned_noun_edit_drops_untouched_out_of_scope_binding() -> None:
122
107
  full_file_content=post_edit_full_file,
123
108
  prior_full_file_content=prior_full_file,
124
109
  )
125
- assert not any(
126
- "RESULT_PATH" in each_issue for each_issue in issues
127
- ), f"untouched banned-noun bindings must stay out of scope, got: {issues!r}"
110
+ assert not any("RESULT_PATH" in each_issue for each_issue in issues), (
111
+ f"untouched banned-noun bindings must stay out of scope, got: {issues!r}"
112
+ )
128
113
 
129
114
 
130
115
  def test_banned_noun_edit_keeps_touched_binding_in_scope() -> None:
@@ -144,9 +129,9 @@ def test_banned_noun_edit_keeps_touched_binding_in_scope() -> None:
144
129
  full_file_content=post_edit_full_file,
145
130
  prior_full_file_content=prior_full_file,
146
131
  )
147
- assert any(
148
- "INTRODUCED_RESULT_PATH" in each_issue for each_issue in issues
149
- ), f"introduced banned-noun binding must block, got: {issues!r}"
132
+ assert any("INTRODUCED_RESULT_PATH" in each_issue for each_issue in issues), (
133
+ f"introduced banned-noun binding must block, got: {issues!r}"
134
+ )
150
135
 
151
136
 
152
137
  def test_banned_noun_edit_does_not_reflag_param_when_unrelated_body_line_changes() -> None:
@@ -171,9 +156,9 @@ def test_banned_noun_edit_does_not_reflag_param_when_unrelated_body_line_changes
171
156
  full_file_content=post_edit_full_file,
172
157
  prior_full_file_content=prior_full_file,
173
158
  )
174
- assert not any(
175
- "canned_results" in each_issue for each_issue in issues
176
- ), f"pre-existing param must not re-flag on unrelated body edit, got: {issues!r}"
159
+ assert not any("canned_results" in each_issue for each_issue in issues), (
160
+ f"pre-existing param must not re-flag on unrelated body edit, got: {issues!r}"
161
+ )
177
162
 
178
163
 
179
164
  def test_unreadable_prior_yields_no_prior_and_no_reconstruction() -> None:
@@ -191,13 +176,13 @@ def test_unreadable_prior_yields_no_prior_and_no_reconstruction() -> None:
191
176
 
192
177
 
193
178
  def test_edit_with_missing_old_string_runs_whole_file_against_on_disk_content(
194
- tmp_path_factory: object, monkeypatch: object, capsys: object,
179
+ tmp_path_factory: pytest.TempPathFactory,
195
180
  ) -> None:
196
181
  """When an Edit's old_string is absent from the file, ``prior_and_post_edit_content``
197
182
  yields ``(None, None)``; ``main()`` must analyze the real on-disk file whole-file
198
183
  rather than the new_string fragment, so an oversized function elsewhere in the
199
184
  file is still reported with its true line numbers."""
200
- production_directory = getattr(tmp_path_factory, "mktemp")("production_pkg")
185
+ production_directory = tmp_path_factory.mktemp("production_pkg")
201
186
  untouched_long_function = _oversized_function_source("untouched_long")
202
187
  short_helper = "def short_helper() -> int:\n return 1\n"
203
188
  on_disk_content = untouched_long_function + "\n" + short_helper
@@ -206,7 +191,9 @@ def test_edit_with_missing_old_string_runs_whole_file_against_on_disk_content(
206
191
  absent_fragment_old = "def absent_function() -> int:\n return 0\n"
207
192
  short_fragment_new = "def absent_function() -> int:\n return 2\n"
208
193
  stdout = _run_main_with_edit_payload(
209
- str(source_file), absent_fragment_old, short_fragment_new, monkeypatch, capsys,
194
+ str(source_file),
195
+ absent_fragment_old,
196
+ short_fragment_new,
210
197
  )
211
198
  assert "untouched_long" in stdout, (
212
199
  "an unreconstructable Edit must fall back to whole-file on-disk analysis, "
@@ -215,13 +202,13 @@ def test_edit_with_missing_old_string_runs_whole_file_against_on_disk_content(
215
202
 
216
203
 
217
204
  def test_edit_with_unreadable_file_does_not_analyze_fragment_as_whole_file(
218
- tmp_path_factory: object, monkeypatch: object, capsys: object,
205
+ tmp_path_factory: pytest.TempPathFactory,
219
206
  ) -> None:
220
207
  """When the on-disk file cannot be read, no well-defined post-edit content
221
208
  exists; ``main()`` must exit cleanly rather than analyze the new_string
222
209
  fragment as if it were the whole file, so the fragment's own function-length
223
210
  violation does not surface as a deny payload."""
224
- production_directory = getattr(tmp_path_factory, "mktemp")("production_pkg")
211
+ production_directory = tmp_path_factory.mktemp("production_pkg")
225
212
  missing_path = str(production_directory / "never_created.py")
226
213
  oversized_fragment_old = "def grows() -> int:\n return 0\n"
227
214
  oversized_fragment_new = _oversized_function_source("grows")
@@ -229,8 +216,6 @@ def test_edit_with_unreadable_file_does_not_analyze_fragment_as_whole_file(
229
216
  missing_path,
230
217
  oversized_fragment_old,
231
218
  oversized_fragment_new,
232
- monkeypatch,
233
- capsys,
234
219
  )
235
220
  assert stdout == "", (
236
221
  "an unreadable Edit target has no well-defined whole-file content, so the "
@@ -0,0 +1,192 @@
1
+ """Test stage ownership for the code-rules enforcer entrypoint."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import io
6
+ import json
7
+ import subprocess
8
+ import sys
9
+ from pathlib import Path
10
+
11
+ import pytest
12
+
13
+ _BLOCKING_DIRECTORY = str(Path(__file__).resolve().parent)
14
+ _HOOKS_DIRECTORY = str(Path(__file__).resolve().parent.parent)
15
+ _PR_LOOP_SCRIPTS_DIRECTORY = str(
16
+ Path(__file__).resolve().parents[2] / "_shared" / "pr-loop" / "scripts"
17
+ )
18
+ if _BLOCKING_DIRECTORY not in sys.path:
19
+ sys.path.insert(0, _BLOCKING_DIRECTORY)
20
+ if _HOOKS_DIRECTORY not in sys.path:
21
+ sys.path.insert(0, _HOOKS_DIRECTORY)
22
+ if _PR_LOOP_SCRIPTS_DIRECTORY not in sys.path:
23
+ sys.path.insert(0, _PR_LOOP_SCRIPTS_DIRECTORY)
24
+
25
+ from code_rules_enforcer import ( # noqa: E402
26
+ _fragment_or_deferred_check,
27
+ main,
28
+ validate_content,
29
+ )
30
+ from code_rules_gate_parts import gate_running # noqa: E402
31
+ from code_rules_gate_parts.tests._repo_test_helpers import ( # noqa: E402
32
+ init_repository,
33
+ write_commit_and_stage_change,
34
+ )
35
+
36
+
37
+ PRODUCTION_FILE_PATH = "packages/app/services.py"
38
+ ENFORCER_SCRIPT_PATH = Path(__file__).with_name("code_rules_enforcer.py")
39
+
40
+
41
+ def _write_payload(file_path: str, source: str) -> str:
42
+ return json.dumps(
43
+ {
44
+ "tool_name": "Write",
45
+ "tool_input": {"file_path": file_path, "content": source},
46
+ }
47
+ )
48
+
49
+
50
+ def _run_write_stage(
51
+ file_path: str,
52
+ source: str,
53
+ monkeypatch: pytest.MonkeyPatch,
54
+ capsys: pytest.CaptureFixture[str],
55
+ ) -> str:
56
+ payload = _write_payload(file_path, source)
57
+ monkeypatch.setattr(sys, "stdin", io.StringIO(payload))
58
+ try:
59
+ main([])
60
+ except SystemExit:
61
+ pass
62
+ return capsys.readouterr().out
63
+ def _run_precheck_stage(candidate_path: Path, target_path: str) -> subprocess.CompletedProcess[str]:
64
+ return subprocess.run(
65
+ [
66
+ sys.executable,
67
+ str(ENFORCER_SCRIPT_PATH),
68
+ "--check",
69
+ str(candidate_path),
70
+ "--as",
71
+ target_path,
72
+ ],
73
+ check=False,
74
+ capture_output=True,
75
+ text=True,
76
+ )
77
+ def test_edit_stage_baselines_the_new_fragment_against_the_old_fragment() -> None:
78
+ all_seen_contents: list[str] = []
79
+
80
+ def record_check(content: str, file_path: str) -> list[str]:
81
+ all_seen_contents.append(content)
82
+ if "introduced" in content:
83
+ return [f"finding in {file_path}"]
84
+ return []
85
+
86
+ all_issues = _fragment_or_deferred_check(
87
+ record_check,
88
+ "existing fragment",
89
+ "introduced fragment",
90
+ PRODUCTION_FILE_PATH,
91
+ defer_scope_to_caller=False,
92
+ )
93
+
94
+ assert all_seen_contents == ["introduced fragment", "existing fragment"]
95
+ assert all_issues == [f"finding in {PRODUCTION_FILE_PATH}"]
96
+
97
+
98
+ def test_commit_stage_owns_scope_and_scans_the_complete_candidate_once() -> None:
99
+ all_seen_contents: list[str] = []
100
+
101
+ def record_check(content: str, file_path: str) -> list[str]:
102
+ all_seen_contents.append(content)
103
+ return [f"finding in {file_path}"]
104
+
105
+ all_issues = _fragment_or_deferred_check(
106
+ record_check,
107
+ "HEAD content",
108
+ "staged candidate",
109
+ PRODUCTION_FILE_PATH,
110
+ defer_scope_to_caller=True,
111
+ )
112
+
113
+ assert all_seen_contents == ["staged candidate"]
114
+ assert all_issues == [f"finding in {PRODUCTION_FILE_PATH}"]
115
+
116
+
117
+ def test_write_stage_runs_the_real_entrypoint_and_reports_a_deny_payload(
118
+ tmp_path_factory: pytest.TempPathFactory,
119
+ monkeypatch: pytest.MonkeyPatch,
120
+ capsys: pytest.CaptureFixture[str],
121
+ ) -> None:
122
+ staging_directory = tmp_path_factory.mktemp("stage")
123
+ target_path = str(staging_directory / "service.py")
124
+ source = "def process_data() -> None:\n print('payload')\n"
125
+
126
+ captured_stdout = _run_write_stage(target_path, source, monkeypatch, capsys)
127
+
128
+ deny_payload = json.loads(captured_stdout)
129
+ deny_reason = deny_payload["hookSpecificOutput"]["permissionDecisionReason"]
130
+ assert deny_payload["hookSpecificOutput"]["permissionDecision"] == "deny"
131
+ assert "process_data" in deny_reason
132
+
133
+
134
+ def test_write_stage_allows_a_clean_candidate_through_the_real_entrypoint(
135
+ tmp_path_factory: pytest.TempPathFactory,
136
+ monkeypatch: pytest.MonkeyPatch,
137
+ capsys: pytest.CaptureFixture[str],
138
+ ) -> None:
139
+ staging_directory = tmp_path_factory.mktemp("stage")
140
+ target_path = str(staging_directory / "service.py")
141
+ source = "def calculate_total() -> int:\n return 0\n"
142
+
143
+ captured_stdout = _run_write_stage(target_path, source, monkeypatch, capsys)
144
+
145
+ assert captured_stdout == ""
146
+
147
+
148
+ def test_precheck_stage_runs_the_cli_and_uses_the_declared_target_path(
149
+ tmp_path_factory: pytest.TempPathFactory,
150
+ ) -> None:
151
+ staging_directory = tmp_path_factory.mktemp("stage")
152
+ candidate_path = staging_directory / "candidate.py"
153
+ candidate_path.write_text(
154
+ "def process_data() -> None:\n print('payload')\n",
155
+ encoding="utf-8",
156
+ )
157
+ target_path = str(staging_directory / "service.py")
158
+
159
+ completed_process = _run_precheck_stage(candidate_path, target_path)
160
+
161
+ assert completed_process.returncode == 1
162
+ assert "process_data" in completed_process.stdout
163
+ def test_gate_caller_scans_staged_content_with_commit_stage_scope(
164
+ tmp_path: Path,
165
+ ) -> None:
166
+ repository_root = tmp_path / "repository"
167
+ repository_root.mkdir()
168
+ init_repository(repository_root)
169
+ committed_source = "def calculate_total() -> int:\n return 0\n"
170
+ staged_source = (
171
+ "def calculate_total() -> int:\n"
172
+ " total = 9999\n"
173
+ " return total\n"
174
+ )
175
+ file_path = write_commit_and_stage_change(
176
+ repository_root,
177
+ "service.py",
178
+ committed_source,
179
+ staged_source,
180
+ )
181
+
182
+ all_partitioned_violations = gate_running._scoped_violations_for_file(
183
+ validate_content=validate_content,
184
+ resolved_path=file_path,
185
+ repository_root=repository_root,
186
+ all_added_lines_for_file={2, 3},
187
+ should_read_staged_content=True,
188
+ )
189
+
190
+ assert all_partitioned_violations is not None
191
+ all_blocking_violations, _all_advisory_violations = all_partitioned_violations
192
+ assert any("9999" in each_issue for each_issue in all_blocking_violations)
@@ -14,16 +14,12 @@ the target path the same way it would for the real directory.
14
14
 
15
15
  from __future__ import annotations
16
16
 
17
- import contextlib
18
- import io
19
17
  import json
20
18
  import pathlib
21
19
  import shutil
22
- import subprocess
23
20
  import sys
24
21
  import tempfile
25
22
  from collections.abc import Iterator
26
- from types import SimpleNamespace
27
23
 
28
24
  import pytest
29
25
 
@@ -35,10 +31,10 @@ if str(_HOOKS_PARENT) not in sys.path:
35
31
  sys.path.insert(0, str(_HOOKS_PARENT))
36
32
 
37
33
  from code_rules_enforcer import main # noqa: E402
38
-
39
- code_rules_enforcer = SimpleNamespace(main=main, sys=sys)
40
-
41
- _ENFORCER_SCRIPT_PATH = _HOOK_DIRECTORY / "code_rules_enforcer.py"
34
+ from code_rules_enforcer_test_support import ( # noqa: E402
35
+ run_precheck,
36
+ run_write_entrypoint,
37
+ )
42
38
 
43
39
  PASS_THROUGH_ALIAS_SOURCE = (
44
40
  "def find_bare_path_segments(content: str) -> set[str]:\n"
@@ -62,39 +58,8 @@ def hook_blocking_dir() -> Iterator[pathlib.Path]:
62
58
  shutil.rmtree(base_directory, ignore_errors=False)
63
59
 
64
60
 
65
- def _run_main_with_write_payload(
66
- file_path: str,
67
- content: str,
68
- monkeypatch: pytest.MonkeyPatch,
69
- capsys: pytest.CaptureFixture[str],
70
- ) -> str:
71
- """Drive ``main()`` through its stdin entry point for a Write and return stdout.
72
-
73
- Args:
74
- file_path: The on-disk path the Write targets.
75
- content: The whole-file body the Write would create.
76
- monkeypatch: The fixture used to redirect ``sys.stdin``.
77
- capsys: The fixture used to capture the deny payload on stdout.
78
-
79
- Returns:
80
- The captured stdout, which holds the deny payload when violations fire.
81
- """
82
- write_payload = json.dumps(
83
- {
84
- "tool_name": "Write",
85
- "tool_input": {"file_path": file_path, "content": content},
86
- }
87
- )
88
- monkeypatch.setattr(code_rules_enforcer.sys, "stdin", io.StringIO(write_payload))
89
- with contextlib.suppress(SystemExit):
90
- code_rules_enforcer.main([])
91
- return capsys.readouterr().out
92
-
93
-
94
61
  def test_write_of_pass_through_alias_into_hook_directory_denies(
95
62
  hook_blocking_dir: pathlib.Path,
96
- monkeypatch: pytest.MonkeyPatch,
97
- capsys: pytest.CaptureFixture[str],
98
63
  ) -> None:
99
64
  """A Write that introduces a pass-through alias into a hook file is denied.
100
65
 
@@ -103,14 +68,16 @@ def test_write_of_pass_through_alias_into_hook_directory_denies(
103
68
  directory its docstring names as the motivating case — at the PreToolUse Write
104
69
  point, not only through ``validate_content``."""
105
70
  new_file = hook_blocking_dir / "new_blocker.py"
106
- stdout = _run_main_with_write_payload(
107
- str(new_file), PASS_THROUGH_ALIAS_SOURCE, monkeypatch, capsys
71
+ captured_stdout, _exit_code = run_write_entrypoint(
72
+ main,
73
+ str(new_file),
74
+ PASS_THROUGH_ALIAS_SOURCE,
108
75
  )
109
- assert stdout != "", (
76
+ assert captured_stdout != "", (
110
77
  "A pass-through alias written into a hook-infrastructure file must produce "
111
78
  "a deny payload, got empty stdout"
112
79
  )
113
- deny_payload = json.loads(stdout)
80
+ deny_payload = json.loads(captured_stdout)
114
81
  decision = deny_payload["hookSpecificOutput"]["permissionDecision"]
115
82
  reason = deny_payload["hookSpecificOutput"]["permissionDecisionReason"]
116
83
  assert decision == "deny", f"expected deny, got: {decision!r}"
@@ -121,31 +88,18 @@ def test_write_of_pass_through_alias_into_hook_directory_denies(
121
88
 
122
89
  def test_precheck_of_pass_through_alias_at_hook_target_exits_nonzero(
123
90
  hook_blocking_dir: pathlib.Path,
124
- tmp_path_factory: pytest.TempPathFactory,
91
+ tmp_path: pathlib.Path,
125
92
  ) -> None:
126
93
  """The pre-check CLI flags a pass-through alias judged at a hook-infrastructure target.
127
94
 
128
95
  Driving the real ``--check`` argv path proves the gate's pre-check mode also
129
96
  routes a hook ``.py`` target through the zero-payload-alias check rather than
130
97
  exiting clean on the blanket hook-infrastructure exemption."""
131
- staging_directory = tmp_path_factory.mktemp("staging")
98
+ staging_directory = tmp_path
132
99
  candidate_file = staging_directory / "candidate.py"
133
100
  candidate_file.write_text(PASS_THROUGH_ALIAS_SOURCE, encoding="utf-8")
134
101
  target_path = str(hook_blocking_dir / "new_blocker.py")
135
- completed = subprocess.run(
136
- [
137
- sys.executable,
138
- str(_ENFORCER_SCRIPT_PATH),
139
- "--check",
140
- str(candidate_file),
141
- "--as",
142
- target_path,
143
- ],
144
- input="",
145
- capture_output=True,
146
- text=True,
147
- check=False,
148
- )
102
+ completed = run_precheck(candidate_file, target_path, None)
149
103
  assert completed.returncode == 1, (
150
104
  "a pass-through alias at a hook target must exit nonzero, got: "
151
105
  f"{completed.returncode}, stdout: {completed.stdout!r}, "
@@ -9,37 +9,54 @@ a ``deny`` so the sandbox can be contained.
9
9
  from __future__ import annotations
10
10
 
11
11
  import json
12
- import os
13
12
  import subprocess
14
13
  import sys
15
14
  from pathlib import Path
16
15
 
17
- SCRIPT_PATH = Path(__file__).parent / "destructive_command_blocker.py"
18
- DENY_MODE_ENV_VAR = "CLAUDE_DESTRUCTIVE_DENY_MODE"
19
-
20
-
21
- def _run_hook_with_environment(command: str, extra_environment: dict[str, str]) -> dict:
22
- child_environment = os.environ.copy()
23
- child_environment.pop(DENY_MODE_ENV_VAR, None)
24
- child_environment.update(extra_environment)
25
- completed_process = subprocess.run(
26
- [sys.executable, str(SCRIPT_PATH)],
27
- input=json.dumps({"tool_name": "Bash", "tool_input": {"command": command}}),
28
- text=True,
29
- capture_output=True,
30
- check=False,
31
- env=child_environment,
16
+ _BLOCKING_DIRECTORY = Path(__file__).resolve().parent
17
+ if str(_BLOCKING_DIRECTORY) not in sys.path:
18
+ sys.path.insert(0, str(_BLOCKING_DIRECTORY))
19
+
20
+ SCRIPT_PATH = _BLOCKING_DIRECTORY / "destructive_command_blocker.py"
21
+
22
+ import _path_setup # noqa: E402, F401
23
+
24
+ from test_hook_subprocess_support import ( # noqa: E402
25
+ build_bash_payload,
26
+ run_hook_as_subprocess,
27
+ )
28
+
29
+
30
+ def _run_hook_with_environment(
31
+ command: str,
32
+ environment_update_by_name: dict[str, str],
33
+ temporary_home_directory: Path,
34
+ ) -> subprocess.CompletedProcess[str]:
35
+ return run_hook_as_subprocess(
36
+ hook_script_path=SCRIPT_PATH,
37
+ payload_text=build_bash_payload(command),
38
+ working_directory=temporary_home_directory,
39
+ home_directory=temporary_home_directory,
40
+ all_environment_names_to_remove=("CLAUDE_DESTRUCTIVE_DENY_MODE",),
41
+ environment_updates_by_name=environment_update_by_name,
42
+ )
43
+
44
+
45
+ def test_rm_rf_denies_when_deny_mode_env_is_set(tmp_path: Path) -> None:
46
+ completed_hook = _run_hook_with_environment(
47
+ "rm -rf /var/log/myapp",
48
+ {"CLAUDE_DESTRUCTIVE_DENY_MODE": "1"},
49
+ tmp_path,
32
50
  )
33
- return json.loads(completed_process.stdout)
51
+ hook_decision_by_field = json.loads(completed_hook.stdout)
34
52
 
53
+ assert hook_decision_by_field["hookSpecificOutput"]["permissionDecision"] == "deny"
54
+ assert "rm -rf" in hook_decision_by_field["hookSpecificOutput"]["permissionDecisionReason"]
35
55
 
36
- def test_rm_rf_denies_when_deny_mode_env_is_set() -> None:
37
- response = _run_hook_with_environment("rm -rf /var/log/myapp", {DENY_MODE_ENV_VAR: "1"})
38
- assert response["hookSpecificOutput"]["permissionDecision"] == "deny"
39
- assert "rm -rf" in response["hookSpecificOutput"]["permissionDecisionReason"]
40
56
 
57
+ def test_rm_rf_asks_when_deny_mode_env_is_absent(tmp_path: Path) -> None:
58
+ completed_hook = _run_hook_with_environment("rm -rf /var/log/myapp", {}, tmp_path)
59
+ hook_decision_by_field = json.loads(completed_hook.stdout)
41
60
 
42
- def test_rm_rf_asks_when_deny_mode_env_is_absent() -> None:
43
- response = _run_hook_with_environment("rm -rf /var/log/myapp", {})
44
- assert response["hookSpecificOutput"]["permissionDecision"] == "ask"
45
- assert "rm -rf" in response["hookSpecificOutput"]["permissionDecisionReason"]
61
+ assert hook_decision_by_field["hookSpecificOutput"]["permissionDecision"] == "ask"
62
+ assert "rm -rf" in hook_decision_by_field["hookSpecificOutput"]["permissionDecisionReason"]