claude-dev-env 8.106.4 → 8.107.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 (35) hide show
  1. package/_shared/pr-loop/scripts/code_rules_gate_parts/tests/test_gate_running.py +1 -1
  2. package/bin/codex-trimmed-sol.test.mjs +1 -0
  3. package/bin/install-pele-package.mjs +161 -0
  4. package/bin/install-pele-package.test.mjs +269 -0
  5. package/bin/install-pstack-plugin.mjs +5 -3
  6. package/bin/install.agents-home.test.mjs +1 -0
  7. package/bin/install.codex-rules.test.mjs +2 -0
  8. package/bin/install.cursor-rules.test.mjs +1 -0
  9. package/bin/install.mjs +18 -0
  10. package/bin/install.pr-visual.test.mjs +1 -1
  11. package/bin/install.profile-settings.test.mjs +1 -0
  12. package/bin/install.prune.test.mjs +1 -0
  13. package/bin/install.question-presentation.test.mjs +4 -0
  14. package/bin/install.settings-defaults.test.mjs +1 -0
  15. package/bin/install.shared-settings.test.mjs +1 -0
  16. package/bin/install.test.mjs +8 -0
  17. package/bin/install.transaction.test.mjs +8 -0
  18. package/bin/install.uninstall-transaction.test.mjs +2 -0
  19. package/bin/install.update-keeps-hooks.test.mjs +1 -0
  20. package/docs/CODE_RULES.md +2 -2
  21. package/docs/code-rules/core-principles-and-config.md +2 -1
  22. package/hooks/blocking/code_rules_magic_values.py +134 -1
  23. package/hooks/blocking/test_code_rules_enforcer_stage.py +1 -1
  24. package/hooks/blocking/test_code_rules_enforcer_string_magic.py +1 -1
  25. package/hooks/blocking/test_code_rules_magic_values.py +162 -0
  26. package/hooks/blocking/test_code_rules_validation_phase.py +1 -1
  27. package/hooks/validators/magic_value_checks.py +77 -12
  28. package/hooks/validators/test_magic_value_checks.py +88 -4
  29. package/hooks/validators/test_run_all_validators_pretooluse.py +1 -1
  30. package/hooks/validators/test_todo_checks.py +13 -1
  31. package/hooks/validators/test_validator_base.py +19 -1
  32. package/hooks/validators/todo_checks.py +2 -12
  33. package/hooks/validators/validator_base.py +33 -2
  34. package/package.json +1 -1
  35. package/scripts/ci/scratch-home-install.test.mjs +1 -1
@@ -3049,6 +3049,7 @@ test('a failed update preserves an existing skills lookup pointer', () => {
3049
3049
  GIT_CONFIG_GLOBAL: join(homeDirectory, '.gitconfig'),
3050
3050
  CDE_INSTALL_PSTACK: '0',
3051
3051
  CDE_INSTALL_DEEPSTACK: '0',
3052
+ CDE_INSTALL_PELE: '0',
3052
3053
  CDE_INSTALL_USAGE_WRAPUP: '0',
3053
3054
  CDE_INSTALL_SUBAGENT_MODELS: '0',
3054
3055
  CDE_INSTALL_SECURITY_GUIDANCE: '0',
@@ -3104,6 +3105,7 @@ function runPstackInstaller(homeDirectory, extraArguments, environmentOverrides
3104
3105
  GIT_CONFIG_GLOBAL: join(homeDirectory, '.gitconfig'),
3105
3106
  CDE_INSTALL_PSTACK: '1',
3106
3107
  CDE_INSTALL_DEEPSTACK: '0',
3108
+ CDE_INSTALL_PELE: '0',
3107
3109
  CDE_INSTALL_USAGE_WRAPUP: '0',
3108
3110
  CDE_INSTALL_SUBAGENT_MODELS: '0',
3109
3111
  CDE_INSTALL_SECURITY_GUIDANCE: '0',
@@ -3189,6 +3191,7 @@ test('a full install adds DeepStack for Claude, Codex, and Cursor', t => {
3189
3191
  ...sandbox.environment,
3190
3192
  CDE_INSTALL_PSTACK: '0',
3191
3193
  CDE_INSTALL_DEEPSTACK: '1',
3194
+ CDE_INSTALL_PELE: '0',
3192
3195
  CDE_DEEPSTACK_SOURCE: sourceDirectory,
3193
3196
  });
3194
3197
 
@@ -3484,6 +3487,7 @@ test('the help output names the usage-wrapup opt-out beside the pstack one', ()
3484
3487
 
3485
3488
  assert.equal(helpRun.status, 0, helpRun.stderr);
3486
3489
  assert.match(helpRun.stdout, /--no-pstack .*\n.*--no-deepstack .*CDE_INSTALL_DEEPSTACK=0.*\n.*--no-usage-wrapup .*CDE_INSTALL_USAGE_WRAPUP=0/);
3490
+ assert.match(helpRun.stdout, /--no-security-guidance .*\n.*--no-pele .*CDE_INSTALL_PELE=0/);
3487
3491
  assert.doesNotMatch(helpRun.stdout, /--no-deepen-first-prompt/);
3488
3492
  });
3489
3493
 
@@ -3672,6 +3676,7 @@ function installWithGlobalPrefix(context, globalPrefix) {
3672
3676
  CLAUDE_DEV_ENV_INSTALL_FAULT: undefined,
3673
3677
  CDE_INSTALL_PSTACK: '0',
3674
3678
  CDE_INSTALL_DEEPSTACK: '0',
3679
+ CDE_INSTALL_PELE: '0',
3675
3680
  CDE_INSTALL_USAGE_WRAPUP: '0',
3676
3681
  CDE_INSTALL_SUBAGENT_MODELS: '0',
3677
3682
  CDE_INSTALL_SECURITY_GUIDANCE: '0',
@@ -3729,6 +3734,7 @@ test('install adds the open-tasks Stop gate to every profile with its own settin
3729
3734
  CLAUDE_DEV_ENV_INSTALL_FAULT: undefined,
3730
3735
  CDE_INSTALL_PSTACK: '0',
3731
3736
  CDE_INSTALL_DEEPSTACK: '0',
3737
+ CDE_INSTALL_PELE: '0',
3732
3738
  CDE_INSTALL_USAGE_WRAPUP: '0',
3733
3739
  CDE_INSTALL_SUBAGENT_MODELS: '0',
3734
3740
  CDE_INSTALL_SECURITY_GUIDANCE: '0',
@@ -3772,6 +3778,7 @@ test('a profile settings.json that is not valid JSON is left alone and named und
3772
3778
  CLAUDE_DEV_ENV_INSTALL_FAULT: undefined,
3773
3779
  CDE_INSTALL_PSTACK: '0',
3774
3780
  CDE_INSTALL_DEEPSTACK: '0',
3781
+ CDE_INSTALL_PELE: '0',
3775
3782
  CDE_INSTALL_USAGE_WRAPUP: '0',
3776
3783
  CDE_INSTALL_SUBAGENT_MODELS: '0',
3777
3784
  CDE_INSTALL_SECURITY_GUIDANCE: '0',
@@ -3818,6 +3825,7 @@ test('uninstall stops before changing anything while a profile settings.json tha
3818
3825
  CLAUDE_DEV_ENV_INSTALL_FAULT: undefined,
3819
3826
  CDE_INSTALL_PSTACK: '0',
3820
3827
  CDE_INSTALL_DEEPSTACK: '0',
3828
+ CDE_INSTALL_PELE: '0',
3821
3829
  CDE_INSTALL_USAGE_WRAPUP: '0',
3822
3830
  CDE_INSTALL_SUBAGENT_MODELS: '0',
3823
3831
  CDE_INSTALL_SECURITY_GUIDANCE: '0',
@@ -89,6 +89,7 @@ test('capture and restore recover settings, manifest, files, and hooksPath', ()
89
89
  LLM_SETTINGS_PROFILES_ROOT: undefined,
90
90
  CDE_INSTALL_PSTACK: '0',
91
91
  CDE_INSTALL_DEEPSTACK: '0',
92
+ CDE_INSTALL_PELE: '0',
92
93
  CDE_INSTALL_USAGE_WRAPUP: '0',
93
94
  CDE_INSTALL_SUBAGENT_MODELS: '0',
94
95
  CDE_INSTALL_SECURITY_GUIDANCE: '0',
@@ -156,6 +157,7 @@ test('capture and restore recover an additional host settings file', () => {
156
157
  LLM_SETTINGS_PROFILES_ROOT: undefined,
157
158
  CDE_INSTALL_PSTACK: '0',
158
159
  CDE_INSTALL_DEEPSTACK: '0',
160
+ CDE_INSTALL_PELE: '0',
159
161
  CDE_INSTALL_USAGE_WRAPUP: '0',
160
162
  CDE_INSTALL_SUBAGENT_MODELS: '0',
161
163
  CDE_INSTALL_SECURITY_GUIDANCE: '0',
@@ -196,6 +198,7 @@ test('runWithInstallTransaction restores prior state on injected fault', () => {
196
198
  LLM_SETTINGS_PROFILES_ROOT: undefined,
197
199
  CDE_INSTALL_PSTACK: '0',
198
200
  CDE_INSTALL_DEEPSTACK: '0',
201
+ CDE_INSTALL_PELE: '0',
199
202
  CDE_INSTALL_USAGE_WRAPUP: '0',
200
203
  CDE_INSTALL_SUBAGENT_MODELS: '0',
201
204
  CDE_INSTALL_SECURITY_GUIDANCE: '0',
@@ -255,6 +258,7 @@ test('runWithInstallTransaction commits and discards journal on success', () =>
255
258
  LLM_SETTINGS_PROFILES_ROOT: undefined,
256
259
  CDE_INSTALL_PSTACK: '0',
257
260
  CDE_INSTALL_DEEPSTACK: '0',
261
+ CDE_INSTALL_PELE: '0',
258
262
  CDE_INSTALL_USAGE_WRAPUP: '0',
259
263
  CDE_INSTALL_SUBAGENT_MODELS: '0',
260
264
  CDE_INSTALL_SECURITY_GUIDANCE: '0',
@@ -303,6 +307,7 @@ function runInstaller(homeDirectory, extraArguments, options = {}) {
303
307
  LLM_SETTINGS_PROFILES_ROOT: undefined,
304
308
  CDE_INSTALL_PSTACK: '0',
305
309
  CDE_INSTALL_DEEPSTACK: '0',
310
+ CDE_INSTALL_PELE: '0',
306
311
  CDE_INSTALL_USAGE_WRAPUP: '0',
307
312
  CDE_INSTALL_SUBAGENT_MODELS: '0',
308
313
  CDE_INSTALL_SECURITY_GUIDANCE: '0',
@@ -341,6 +346,7 @@ test('a later install fault removes newly seeded Codex pstack files', () => {
341
346
  environment: {
342
347
  CDE_INSTALL_PSTACK: '1',
343
348
  CDE_INSTALL_DEEPSTACK: '0',
349
+ CDE_INSTALL_PELE: '0',
344
350
  CDE_INSTALL_USAGE_WRAPUP: '0',
345
351
  CDE_INSTALL_SUBAGENT_MODELS: '0',
346
352
  CDE_INSTALL_SECURITY_GUIDANCE: '0',
@@ -489,6 +495,7 @@ test('installer fault after_git_config restores prior core.hooksPath', () => {
489
495
  LLM_SETTINGS_PROFILES_ROOT: undefined,
490
496
  CDE_INSTALL_PSTACK: '0',
491
497
  CDE_INSTALL_DEEPSTACK: '0',
498
+ CDE_INSTALL_PELE: '0',
492
499
  CDE_INSTALL_USAGE_WRAPUP: '0',
493
500
  CDE_INSTALL_SUBAGENT_MODELS: '0',
494
501
  CDE_INSTALL_SECURITY_GUIDANCE: '0',
@@ -511,6 +518,7 @@ test('installer fault after_git_config restores prior core.hooksPath', () => {
511
518
  LLM_SETTINGS_PROFILES_ROOT: undefined,
512
519
  CDE_INSTALL_PSTACK: '0',
513
520
  CDE_INSTALL_DEEPSTACK: '0',
521
+ CDE_INSTALL_PELE: '0',
514
522
  CDE_INSTALL_USAGE_WRAPUP: '0',
515
523
  CDE_INSTALL_SUBAGENT_MODELS: '0',
516
524
  CDE_INSTALL_SECURITY_GUIDANCE: '0',
@@ -75,6 +75,7 @@ function runInstaller(homeDirectory, extraArguments, options = {}) {
75
75
  LLM_SETTINGS_PROFILES_ROOT: undefined,
76
76
  CDE_INSTALL_PSTACK: '0',
77
77
  CDE_INSTALL_DEEPSTACK: '0',
78
+ CDE_INSTALL_PELE: '0',
78
79
  CDE_INSTALL_USAGE_WRAPUP: '0',
79
80
  CDE_INSTALL_SUBAGENT_MODELS: '0',
80
81
  CDE_INSTALL_SECURITY_GUIDANCE: '0',
@@ -314,6 +315,7 @@ test('uninstall fault after_git_config restores prior core.hooksPath', () => {
314
315
  LLM_SETTINGS_PROFILES_ROOT: undefined,
315
316
  CDE_INSTALL_PSTACK: '0',
316
317
  CDE_INSTALL_DEEPSTACK: '0',
318
+ CDE_INSTALL_PELE: '0',
317
319
  CDE_INSTALL_USAGE_WRAPUP: '0',
318
320
  CDE_INSTALL_SUBAGENT_MODELS: '0',
319
321
  CDE_INSTALL_SECURITY_GUIDANCE: '0',
@@ -26,6 +26,7 @@ function installerEnvironment(homeDirectory) {
26
26
  LLM_SETTINGS_PROFILES_ROOT: undefined,
27
27
  CDE_INSTALL_PSTACK: '0',
28
28
  CDE_INSTALL_DEEPSTACK: '0',
29
+ CDE_INSTALL_PELE: '0',
29
30
  CDE_INSTALL_USAGE_WRAPUP: '0',
30
31
  CDE_INSTALL_SUBAGENT_MODELS: '0',
31
32
  CDE_INSTALL_SECURITY_GUIDANCE: '0',
@@ -13,13 +13,13 @@ A keep marker is the one comment that may be added and kept: a comment that open
13
13
 
14
14
  ## CORE PRINCIPLES
15
15
 
16
- Use clear names. Keep shared constants in `config/`. Search before adding helpers. Put construction and formatting with the data owner. Encapsulation enables cleaner naming, so prefer `isMaxLevel(level)` to `level >= MAXIMUM_LEVEL`. Session policy lives in [`code-standards.md`](../rules/code-standards.md).
16
+ Use clear names. Keep shared and tuned constants in `config/`; a value used once stays in its function under a local name. Search before adding helpers. Put construction and formatting with the data owner. Encapsulation enables cleaner naming, so prefer `isMaxLevel(level)` to `level >= MAXIMUM_LEVEL`. Session policy lives in [`code-standards.md`](../rules/code-standards.md).
17
17
 
18
18
  Open [details](code-rules/core-principles-and-config.md) when adding shared values or construction logic.
19
19
 
20
20
  ## ⚡ LINT-ENFORCED RULES
21
21
 
22
- Staged lint runs `code_rules_enforcer.py`. Keep imports at the top, parameterize logging, guard path insertion, use specific exceptions, and follow checks for values, types, docstrings, names, and tests. Magic values exempt 0, 1, and -1. Type escape hatches are allowed in boundary files. Stub bodies are allowed in abstract and Protocol classes.
22
+ Staged lint runs `code_rules_enforcer.py`. Keep imports at the top, parameterize logging, guard path insertion, use specific exceptions, and follow checks for values, types, docstrings, names, and tests. Magic values exempt 0, 1, and -1, and a number bound alone to a named local passes. Type escape hatches are allowed in boundary files. Stub bodies are allowed in abstract and Protocol classes.
23
23
 
24
24
  - UPPER_SNAKE constants belong in `config/`. Exemptions include `config/*`, `/migrations/`, and test paths or names matching `test_`, `_test.`, `.spec.`, `conftest`, or `/tests/`.
25
25
  - Workflow registries: a path that contains any of these substrings, `/workflow/`, `_tab.py`, `/states.py`, or `/modules.py`, is exempt; each matches independently as a substring.
@@ -24,7 +24,7 @@ I search for shared code and configuration before adding a constant or repeating
24
24
 
25
25
  The code-rules enforcer runs constant, path, magic-value, and duplicate-format checks on changed *.py files. String and collection checks inspect production function bodies in *.py files.
26
26
 
27
- Search config for the exact value and a semantic match. Add timing to config/timing.py, ports and thresholds to config/constants.py, and selectors to config/selectors.py. Keep construction and formatting with the owner of the data. Constants outside config are exempt in migrations, workflow registries, and test files. Workflow registry matching uses path substrings /workflow/, _tab.py, /states.py, and /modules.py. The test-file patterns include test_, _test., .spec., conftest, and /tests/.
27
+ A value used once stays in its function under a local name, such as `retry_backoff_factor = 2.5`. A value moves to config when two modules share it or someone tunes it, such as a timeout, threshold, port, or selector. Search config for the exact value and a semantic match. Add timing to config/timing.py, ports and thresholds to config/constants.py, and selectors to config/selectors.py. Keep construction and formatting with the owner of the data. Constants outside config are exempt in migrations, workflow registries, and test files. Workflow registry matching uses path substrings /workflow/, _tab.py, /states.py, and /modules.py. The test-file patterns include test_, _test., .spec., conftest, and /tests/.
28
28
 
29
29
  ## Proving it
30
30
 
@@ -35,6 +35,7 @@ Run the named pytest node or command with the described input. A breach produces
35
35
  - check_constants_outside_config_advisory: a function-local UPPER_SNAKE constant; `python -m pytest packages/claude-dev-env/hooks/blocking/test_code_rules_enforcer_split_constants_config.py::test_advisory_should_flag_annotated_function_body_constant` reports a stderr advisory.
36
36
  - check_fstring_structural_literals: an f-string that embeds a URL path fragment; `python -m pytest packages/claude-dev-env/hooks/blocking/test_code_rules_enforcer_fstring_scan.py::test_should_flag_fstring_with_url_path` reports a named violation.
37
37
  - check_magic_values: a production function comparing a value with 2; `python -m pytest packages/claude-dev-env/hooks/blocking/test_code_rules_enforcer_magic_allowlist.py::test_check_magic_values_should_flag_literal_two_in_function_body` reports a named violation.
38
+ - check_magic_values exemption: a function binding `retry_backoff_factor = 2.5` alone on its line; `python -m pytest packages/claude-dev-env/hooks/blocking/test_code_rules_magic_values.py::test_should_pass_a_number_bound_to_a_local_name` passes with no violation.
38
39
  - check_duplicated_format_patterns: the same f-string skeleton at three call sites; `python -m pytest packages/claude-dev-env/hooks/blocking/test_code_rules_enforcer_split_optional_params.py::test_should_advise_when_fstring_skeleton_appears_three_or_more_times` reports a stderr advisory.
39
40
  - check_hardcoded_user_paths: a fixed user-home path in source; `python -m pytest packages/claude-dev-env/hooks/blocking/test_code_rules_enforcer_hardcoded_user_path.py::test_should_flag_windows_user_path_with_forward_slashes` reports a named violation.
40
41
  - check_sys_path_insert_deduplication_guard: an unguarded module-level sys.path.insert call; `python -m pytest packages/claude-dev-env/hooks/blocking/test_code_rules_enforcer_sys_path_insert.py::test_should_flag_unguarded_module_level_insert` reports a named violation.
@@ -3,6 +3,9 @@
3
3
  import ast
4
4
  import re
5
5
  import sys
6
+ import textwrap
7
+ from collections import Counter
8
+ from collections.abc import Iterator
6
9
  from pathlib import Path
7
10
 
8
11
  _blocking_directory = str(Path(__file__).resolve().parent)
@@ -148,15 +151,135 @@ def _is_magic_number_inside_slice_bound(masked_line: str, number_text: str) -> b
148
151
  return False
149
152
 
150
153
 
154
+ def _named_number_binding_line_numbers(content: str) -> set[int] | None:
155
+ """Return the lines where a function binds one number literal to one name.
156
+
157
+ The name carries the meaning, so the number needs no constant::
158
+
159
+ def backoff_seconds(attempt: int) -> float:
160
+ retry_backoff_factor = 2.5
161
+
162
+ A binding sharing its line with another statement, a number in an
163
+ expression, a keyword argument, a module-level binding, and a ``global``
164
+ or ``nonlocal`` name still fire. A fragment is dedented before the
165
+ parse; content that does not parse returns None.
166
+ """
167
+ try:
168
+ syntax_tree = ast.parse(textwrap.dedent(content))
169
+ except SyntaxError:
170
+ return None
171
+
172
+ all_outer_scope_names = _global_and_nonlocal_names(syntax_tree)
173
+ statement_count_by_line = Counter(
174
+ each_node.lineno for each_node in ast.walk(syntax_tree) if isinstance(each_node, ast.stmt)
175
+ )
176
+ return {
177
+ each_node.lineno
178
+ for each_node in _nodes_inside_functions(syntax_tree)
179
+ if isinstance(each_node, ast.stmt)
180
+ and _number_bound_name(each_node) not in (None, *all_outer_scope_names)
181
+ and each_node.lineno == each_node.end_lineno
182
+ and statement_count_by_line[each_node.lineno] == 1
183
+ }
184
+
185
+
186
+ def _global_and_nonlocal_names(syntax_tree: ast.AST) -> set[str]:
187
+ """Return every name a ``global`` or ``nonlocal`` statement declares in the file."""
188
+ return {
189
+ each_name
190
+ for each_node in ast.walk(syntax_tree)
191
+ if isinstance(each_node, (ast.Global, ast.Nonlocal))
192
+ for each_name in each_node.names
193
+ }
194
+
195
+
196
+ def _nodes_inside_functions(syntax_tree: ast.AST) -> Iterator[ast.AST]:
197
+ """Yield every node whose nearest enclosing scope is a function, each one once."""
198
+ all_pending: list[tuple[ast.AST, bool]] = [(syntax_tree, False)]
199
+ while all_pending:
200
+ node, is_inside_function = all_pending.pop()
201
+ if is_inside_function:
202
+ yield node
203
+ is_child_inside_function = not isinstance(node, ast.ClassDef) and (
204
+ is_inside_function or isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
205
+ )
206
+ all_pending.extend((each_child, is_child_inside_function) for each_child in ast.iter_child_nodes(node))
207
+
208
+
209
+ def _fragment_global_and_nonlocal_names(content: str) -> set[str]:
210
+ """Return every name a ``global`` or ``nonlocal`` line declares in text that does not parse."""
211
+ return {
212
+ each_name.strip()
213
+ for each_match in re.finditer(r"^[ \t]*(?:global|nonlocal)[ \t]+([\w \t,]+)", content, re.MULTILINE)
214
+ for each_name in each_match.group(1).split(",")
215
+ }
216
+
217
+
218
+ def _is_fragment_named_number_line(
219
+ all_lines: list[str], line_number: int, function_indent: int, all_outer_scope_names: set[str]
220
+ ) -> bool:
221
+ """Return True when a line of unparseable content binds one number to one name in a function.
222
+
223
+ An Edit fragment that ends partway through a block does not parse whole::
224
+
225
+ def backoff_seconds(attempt: int) -> float:
226
+ retry_backoff_factor = 2.5
227
+ if attempt > 0:
228
+
229
+ The line must sit deeper than the last ``def`` line and parse alone as
230
+ the binding, so ``retry_backoff_factor = 2.5`` passes there. A name a
231
+ ``global`` or ``nonlocal`` line declares still fires, and so does a line
232
+ after one ending in ``,``, ``(``, ``[`` or ``{``, such as the last
233
+ keyword argument of a call split across lines.
234
+ """
235
+ line = all_lines[line_number - 1]
236
+ stripped_line = line.strip()
237
+ all_earlier_code_lines = [each_line.strip() for each_line in all_lines[: line_number - 1] if each_line.strip()]
238
+ is_inside_brackets = bool(all_earlier_code_lines) and all_earlier_code_lines[-1].endswith((",", "(", "[", "{"))
239
+ if is_inside_brackets or len(line) - len(line.lstrip()) <= function_indent:
240
+ return False
241
+ try:
242
+ line_tree = ast.parse(stripped_line)
243
+ except SyntaxError:
244
+ return False
245
+ return len(line_tree.body) == 1 and _number_bound_name(line_tree.body[0]) not in (None, *all_outer_scope_names)
246
+
247
+
248
+ def _number_bound_name(node: ast.AST) -> str | None:
249
+ """Return the name ``node`` binds one signed number literal to, else None."""
250
+ if isinstance(node, ast.Assign):
251
+ all_targets, bound_value = node.targets, node.value
252
+ elif isinstance(node, ast.AnnAssign) and node.value is not None:
253
+ all_targets, bound_value = [node.target], node.value
254
+ else:
255
+ return None
256
+ if len(all_targets) != 1 or not isinstance(all_targets[0], ast.Name):
257
+ return None
258
+ while isinstance(bound_value, ast.UnaryOp) and isinstance(bound_value.op, (ast.USub, ast.UAdd)):
259
+ bound_value = bound_value.operand
260
+ is_number_literal = isinstance(bound_value, ast.Constant) and type(bound_value.value) in (int, float)
261
+ return all_targets[0].id if is_number_literal else None
262
+
263
+
151
264
  def check_magic_values(content: str, file_path: str) -> list[str]:
152
- """Check for magic values in function bodies."""
265
+ """Check for magic values in function bodies.
266
+
267
+ A line inside a function that binds a single number literal to a name
268
+ passes, since the name explains the number. A number inside a larger
269
+ expression fires.
270
+ """
153
271
  if is_config_file(file_path) or is_test_file(file_path):
154
272
  return []
155
273
 
156
274
  issues = []
157
275
  lines = content.split("\n")
158
276
  all_docstring_line_numbers = docstring_line_numbers(content)
277
+ all_named_number_line_numbers = _named_number_binding_line_numbers(content)
278
+ all_fragment_outer_scope_names = (
279
+ _fragment_global_and_nonlocal_names(content) if all_named_number_line_numbers is None else set()
280
+ )
159
281
  is_inside_function = False
282
+ function_indent = 0
160
283
 
161
284
  number_pattern = re.compile(r"(?<![.\w])(\d+\.?\d*)(?![.\w])")
162
285
  allowed_numbers = ALL_ALLOWED_MAGIC_NUMBER_LITERALS
@@ -172,6 +295,7 @@ def check_magic_values(content: str, file_path: str) -> list[str]:
172
295
 
173
296
  if re.match(r"^(async\s+)?def\s+\w+", stripped):
174
297
  is_inside_function = True
298
+ function_indent = len(each_line) - len(each_line.lstrip())
175
299
  continue
176
300
 
177
301
  if re.match(r"^class\s+\w+", stripped):
@@ -182,6 +306,15 @@ def check_magic_values(content: str, file_path: str) -> list[str]:
182
306
  if "=" in stripped and stripped.split("=")[0].strip().isupper():
183
307
  continue
184
308
 
309
+ if all_named_number_line_numbers is None:
310
+ is_named_number_line = _is_fragment_named_number_line(
311
+ lines, each_line_number, function_indent, all_fragment_outer_scope_names
312
+ )
313
+ else:
314
+ is_named_number_line = each_line_number in all_named_number_line_numbers
315
+ if is_named_number_line:
316
+ continue
317
+
185
318
  if stripped.startswith(("return", "yield", "raise")):
186
319
  continue
187
320
 
@@ -171,7 +171,7 @@ def test_gate_caller_scans_staged_content_with_commit_stage_scope(
171
171
  committed_source = "def calculate_total() -> int:\n return 0\n"
172
172
  staged_source = (
173
173
  "def calculate_total() -> int:\n"
174
- " total = 9999\n"
174
+ " total = abs(9999)\n"
175
175
  " return total\n"
176
176
  )
177
177
  file_path = write_commit_and_stage_change(
@@ -317,7 +317,7 @@ def test_should_block_second_identical_string_magic_per_occurrence() -> None:
317
317
  def test_should_surface_magic_when_gate_defers_scope_with_head_as_old() -> None:
318
318
  source = (
319
319
  "def compute() -> int:\n"
320
- " old_number = 9999\n"
320
+ " old_number = abs(9999)\n"
321
321
  " return old_number\n"
322
322
  )
323
323
  issues = code_rules_enforcer.validate_content_for_full_gate(
@@ -52,3 +52,165 @@ def test_magic_value_check_still_flags_real_magic_number_in_code_statement() ->
52
52
  assert any(issue.endswith("Magic value 42 - extract to named constant") for issue in issues), (
53
53
  f"Expected the real magic number 42 to stay flagged, got: {issues}"
54
54
  )
55
+
56
+
57
+ def _magic_issues_for_function_line(function_body_line: str) -> list[str]:
58
+ source = f"def backoff_seconds(attempt: int) -> float:\n {function_body_line}\n return attempt\n"
59
+ return check_magic_values(source, PRODUCTION_FILE_PATH)
60
+
61
+
62
+ def test_should_pass_a_number_bound_to_a_local_name() -> None:
63
+ assert _magic_issues_for_function_line("retry_backoff_factor = 2.5") == []
64
+
65
+
66
+ def test_should_pass_an_annotated_number_bound_to_a_local_name() -> None:
67
+ assert _magic_issues_for_function_line("header_row_count: int | None = 30") == []
68
+
69
+
70
+ def test_should_pass_a_named_number_with_a_trailing_comment() -> None:
71
+ assert _magic_issues_for_function_line("header_row_count = 30 # rows") == []
72
+
73
+
74
+ def test_should_pass_a_negative_number_bound_to_a_local_name() -> None:
75
+ assert _magic_issues_for_function_line("lowest_offset = -40") == []
76
+
77
+
78
+ def test_should_flag_a_number_inside_an_expression() -> None:
79
+ assert _magic_issues_for_function_line("backoff = attempt * 2.5") == [
80
+ "Line 2: Magic value 2.5 - extract to named constant"
81
+ ]
82
+
83
+
84
+ def test_should_flag_a_number_in_a_comparison_assignment() -> None:
85
+ assert _magic_issues_for_function_line("is_slow = attempt > 40") == [
86
+ "Line 2: Magic value 40 - extract to named constant"
87
+ ]
88
+
89
+
90
+ def test_should_flag_a_keyword_argument_on_its_own_line() -> None:
91
+ source = "def backoff_seconds(attempt: int) -> float:\n wait_for(\n attempt,\n timeout=30\n )\n return attempt\n"
92
+ assert check_magic_values(source, PRODUCTION_FILE_PATH) == [
93
+ "Line 4: Magic value 30 - extract to named constant"
94
+ ]
95
+
96
+
97
+ def test_should_flag_a_module_level_binding_after_a_function() -> None:
98
+ source = "def backoff_seconds(attempt: int) -> float:\n return attempt\nretry_limit = 30\n"
99
+ assert check_magic_values(source, PRODUCTION_FILE_PATH) == [
100
+ "Line 3: Magic value 30 - extract to named constant"
101
+ ]
102
+
103
+
104
+ def test_should_pass_a_positive_signed_number_bound_to_a_local_name() -> None:
105
+ assert _magic_issues_for_function_line("lowest_offset = +40") == []
106
+
107
+
108
+ def test_should_flag_a_number_sharing_a_line_with_a_named_binding() -> None:
109
+ assert _magic_issues_for_function_line("limit = 5; scaled = attempt * 99") == [
110
+ "Line 2: Magic value 5 - extract to named constant"
111
+ ]
112
+
113
+
114
+ def test_should_flag_two_named_bindings_sharing_one_line() -> None:
115
+ assert _magic_issues_for_function_line("low_offset = 30; high_offset = 40") == [
116
+ "Line 2: Magic value 30 - extract to named constant"
117
+ ]
118
+
119
+
120
+ def test_should_flag_a_condition_number_beside_a_named_binding() -> None:
121
+ assert _magic_issues_for_function_line("if attempt > 99: limit = 40") == [
122
+ "Line 2: Magic value 99 - extract to named constant"
123
+ ]
124
+
125
+
126
+ def test_should_pass_a_named_number_in_an_indented_method_fragment() -> None:
127
+ fragment = " def backoff_seconds(self) -> float:\n retry_backoff_factor = 2.5\n return retry_backoff_factor\n"
128
+ assert check_magic_values(fragment, PRODUCTION_FILE_PATH) == []
129
+
130
+
131
+ def test_should_pass_a_doubly_signed_number_bound_to_a_local_name() -> None:
132
+ assert _magic_issues_for_function_line("lowest_offset = --40") == []
133
+
134
+
135
+ def test_should_flag_a_keyword_argument_in_an_indented_method_fragment() -> None:
136
+ fragment = " def wait(self) -> None:\n wait_for(\n self,\n timeout=30\n )\n"
137
+ assert check_magic_values(fragment, PRODUCTION_FILE_PATH) == [
138
+ "Line 4: Magic value 30 - extract to named constant"
139
+ ]
140
+
141
+
142
+ def test_should_flag_a_module_level_binding_in_unparseable_content() -> None:
143
+ source = "def build() -> int:\n return 0\nretry_limit = 30\nprint 'x'\n"
144
+ assert check_magic_values(source, PRODUCTION_FILE_PATH) == [
145
+ "Line 3: Magic value 30 - extract to named constant"
146
+ ]
147
+
148
+
149
+ def test_should_flag_a_number_bound_to_a_global_name() -> None:
150
+ source = "retry_limit = 0\ndef raise_limit() -> None:\n global retry_limit\n retry_limit = 40\n"
151
+ assert check_magic_values(source, PRODUCTION_FILE_PATH) == [
152
+ "Line 4: Magic value 40 - extract to named constant"
153
+ ]
154
+
155
+
156
+ def test_should_pass_a_named_number_in_a_fragment_ending_inside_a_block() -> None:
157
+ source = "def backoff_seconds(attempt: int) -> float:\n retry_backoff_factor = 2.5\n if attempt > 0:\n"
158
+ assert check_magic_values(source, PRODUCTION_FILE_PATH) == []
159
+
160
+
161
+ def test_should_pass_a_named_number_in_a_method_fragment_with_a_column_zero_string() -> None:
162
+ source = (
163
+ " def backoff_seconds(self) -> float:\n"
164
+ " retry_backoff_factor = 2.5\n"
165
+ ' banner = """\n'
166
+ "hello\n"
167
+ '"""\n'
168
+ " return retry_backoff_factor\n"
169
+ )
170
+ assert check_magic_values(source, PRODUCTION_FILE_PATH) == []
171
+
172
+
173
+ def test_should_flag_a_global_name_binding_in_a_fragment_ending_inside_a_block() -> None:
174
+ source = "def raise_limit(attempt: int) -> None:\n global retry_limit\n retry_limit = 40\n if attempt > 0:\n"
175
+ assert check_magic_values(source, PRODUCTION_FILE_PATH) == [
176
+ "Line 3: Magic value 40 - extract to named constant"
177
+ ]
178
+
179
+
180
+ def test_should_flag_the_last_keyword_argument_in_a_fragment_ending_inside_a_block() -> None:
181
+ source = (
182
+ "def fetch(address: str) -> None:\n"
183
+ " response = send(\n"
184
+ " address,\n"
185
+ " timeout=30\n"
186
+ " )\n"
187
+ " if response:\n"
188
+ )
189
+ assert check_magic_values(source, PRODUCTION_FILE_PATH) == [
190
+ "Line 4: Magic value 30 - extract to named constant"
191
+ ]
192
+
193
+
194
+ def test_should_flag_each_name_of_consecutive_global_lines_in_a_fragment() -> None:
195
+ source = (
196
+ "def tally(attempt: int) -> None:\n"
197
+ " global total\n"
198
+ " global count\n"
199
+ " total = 7\n"
200
+ " if attempt > 0:\n"
201
+ )
202
+ assert check_magic_values(source, PRODUCTION_FILE_PATH) == [
203
+ "Line 4: Magic value 7 - extract to named constant"
204
+ ]
205
+
206
+
207
+ def test_should_flag_a_global_name_declared_beside_a_comment_in_a_fragment() -> None:
208
+ source = (
209
+ "def tally(attempt: int) -> None:\n"
210
+ " global total # shared\n"
211
+ " total = 7\n"
212
+ " if attempt > 0:\n"
213
+ )
214
+ assert check_magic_values(source, PRODUCTION_FILE_PATH) == [
215
+ "Line 3: Magic value 7 - extract to named constant"
216
+ ]
@@ -185,7 +185,7 @@ def _write_scoped_service_file_with_a_committed_baseline(repository_root: Path)
185
185
  repository_root,
186
186
  "service.py",
187
187
  "def read_port() -> int:\n return 0\n",
188
- "def read_port() -> int:\n port_number = 9999\n return port_number\n",
188
+ "def read_port() -> int:\n port_number = abs(9999)\n return port_number\n",
189
189
  )
190
190
 
191
191