claude-dev-env 1.77.0 → 1.79.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 (46) hide show
  1. package/audit-rubrics/category_rubrics/category-k-codebase-conflicts.md +1 -0
  2. package/bin/install.mjs +1 -0
  3. package/bin/install.test.mjs +3 -2
  4. package/hooks/blocking/CLAUDE.md +5 -2
  5. package/hooks/blocking/code_rules_dead_module_constant.py +215 -59
  6. package/hooks/blocking/code_rules_dead_split_branch.py +225 -0
  7. package/hooks/blocking/code_rules_docstrings.py +951 -6
  8. package/hooks/blocking/code_rules_enforcer.py +64 -0
  9. package/hooks/blocking/code_rules_naming_collection.py +76 -1
  10. package/hooks/blocking/code_rules_paired_test.py +517 -0
  11. package/hooks/blocking/code_rules_string_magic.py +71 -1
  12. package/hooks/blocking/code_rules_test_assertions.py +159 -1
  13. package/hooks/blocking/convergence_gate_blocker.py +24 -15
  14. package/hooks/blocking/env_var_table_code_drift_blocker.py +475 -0
  15. package/hooks/blocking/package_inventory_stale_blocker.py +54 -15
  16. package/hooks/blocking/test_code_rules_enforcer_dead_module_constant.py +89 -2
  17. package/hooks/blocking/test_code_rules_enforcer_dead_split_branch.py +105 -0
  18. package/hooks/blocking/test_code_rules_enforcer_docstring_field_runmode_outcome.py +129 -0
  19. package/hooks/blocking/test_code_rules_enforcer_docstring_length_constant_superlative.py +198 -0
  20. package/hooks/blocking/test_code_rules_enforcer_docstring_mark_glyph_enumeration.py +262 -0
  21. package/hooks/blocking/test_code_rules_enforcer_docstring_no_network.py +115 -0
  22. package/hooks/blocking/test_code_rules_enforcer_docstring_raises_largezipfile.py +226 -0
  23. package/hooks/blocking/test_code_rules_enforcer_docstring_unreferenced_param.py +160 -0
  24. package/hooks/blocking/test_code_rules_enforcer_module_docstring_data_schema_scope.py +82 -0
  25. package/hooks/blocking/test_code_rules_enforcer_paired_test.py +339 -0
  26. package/hooks/blocking/test_code_rules_enforcer_polarity_name_contradiction.py +76 -0
  27. package/hooks/blocking/test_code_rules_enforcer_vacuous_cleanup_assertion.py +132 -0
  28. package/hooks/blocking/test_code_rules_enforcer_whitespace_indentation_magic.py +74 -0
  29. package/hooks/blocking/test_convergence_gate_blocker.py +71 -0
  30. package/hooks/blocking/test_env_var_table_code_drift_blocker.py +94 -0
  31. package/hooks/blocking/test_package_inventory_stale_blocker.py +46 -0
  32. package/hooks/blocking/test_pre_tool_use_dispatcher.py +7 -7
  33. package/hooks/hooks_constants/CLAUDE.md +2 -0
  34. package/hooks/hooks_constants/blocking_check_limits.py +102 -0
  35. package/hooks/hooks_constants/code_rules_enforcer_constants.py +28 -0
  36. package/hooks/hooks_constants/env_var_table_code_drift_constants.py +64 -0
  37. package/hooks/hooks_constants/package_inventory_stale_blocker_constants.py +20 -9
  38. package/hooks/hooks_constants/paired_test_coverage_constants.py +35 -0
  39. package/hooks/hooks_constants/pre_tool_use_dispatcher_constants.py +4 -0
  40. package/package.json +1 -1
  41. package/rules/CLAUDE.md +2 -0
  42. package/rules/docstring-prose-matches-implementation.md +56 -53
  43. package/rules/env-var-table-code-drift.md +24 -0
  44. package/rules/file-global-constants.md +2 -2
  45. package/rules/package-inventory-stale-entry.md +4 -4
  46. package/rules/paired-test-coverage.md +35 -0
@@ -22,6 +22,7 @@
22
22
  - A module's existing `_resolve_base_ref` guards a missing remote with `getattr(remote, "name", "") or DEFAULT_REMOTE`; the diff adds `_resolve_head_ref` beside it that dereferences `remote.name` bare, crashing on the detached-HEAD case its sibling survives.
23
23
  - A rules reference whose enforcement table marks letter J with ⚡ (blocking hook) while its audit-surface section three paragraphs later lists J under "non-blocking, multi-file reasoning" — one letter, two contradictory enforcement claims in one document.
24
24
  - A hooks.json with the same hook registered in two parallel matcher blocks (Write|Edit + MultiEdit) when an existing Write|Edit|MultiEdit block already handles the same surface.
25
+ - A new function re-implements an in-place atomic file rewrite — stream to a temp sibling, `os.replace` over the original, best-effort temp cleanup on failure — that a shared helper already centralizes (`rewrite_stp_member_atomically` and the like); the two copies drift the moment one gets a temp-naming or concurrency fix the other misses (CODE_RULES §3, reuse before create). The audit catches it by matching the diff's temp-sibling-plus-`os.replace` orchestration against the shared module the same file already imports from.
25
26
 
26
27
  **Companion reference:** see `../source-material-section-types.md`.
27
28
 
package/bin/install.mjs CHANGED
@@ -312,6 +312,7 @@ export const FOLDED_HOOK_RELATIVE_PATHS = new Set([
312
312
  'blocking/verified_commit_message_accuracy_blocker.py',
313
313
  'blocking/workflow_substitution_slot_blocker.py',
314
314
  'blocking/claude_md_orphan_file_blocker.py',
315
+ 'blocking/env_var_table_code_drift_blocker.py',
315
316
  'blocking/pytest_testpaths_orphan_blocker.py',
316
317
  'blocking/open_questions_in_plans_blocker.py',
317
318
  'blocking/plain_language_blocker.py',
@@ -718,8 +718,8 @@ const OLD_FOLDED_HOOKS_SETTINGS = {
718
718
  };
719
719
 
720
720
 
721
- test('FOLDED_HOOK_RELATIVE_PATHS contains all 15 hooks removed from hooks.json', () => {
722
- assert.equal(FOLDED_HOOK_RELATIVE_PATHS.size, 15);
721
+ test('FOLDED_HOOK_RELATIVE_PATHS contains all 16 hooks removed from hooks.json', () => {
722
+ assert.equal(FOLDED_HOOK_RELATIVE_PATHS.size, 16);
723
723
  assert.ok(FOLDED_HOOK_RELATIVE_PATHS.has('blocking/write_existing_file_blocker.py'));
724
724
  assert.ok(FOLDED_HOOK_RELATIVE_PATHS.has('blocking/plain_language_blocker.py'));
725
725
  assert.ok(FOLDED_HOOK_RELATIVE_PATHS.has('blocking/code_rules_enforcer.py'));
@@ -741,6 +741,7 @@ test('FOLDED_HOOK_RELATIVE_PATHS lists every hook the PreToolUse dispatcher host
741
741
  'blocking/verified_commit_message_accuracy_blocker.py',
742
742
  'blocking/workflow_substitution_slot_blocker.py',
743
743
  'blocking/claude_md_orphan_file_blocker.py',
744
+ 'blocking/env_var_table_code_drift_blocker.py',
744
745
  'blocking/pytest_testpaths_orphan_blocker.py',
745
746
  'blocking/open_questions_in_plans_blocker.py',
746
747
  'blocking/plain_language_blocker.py',
@@ -29,6 +29,7 @@ The check modules it calls are the `code_rules_<concern>.py` files below.
29
29
  | `code_rules_dead_config_field.py` | `*Config` / `*Selectors` dataclass fields with no live references |
30
30
  | `code_rules_dead_dataclass_field.py` | Dataclass fields with no consuming references |
31
31
  | `code_rules_dead_module_constant.py` | `UPPER_SNAKE` constants in `*_constants.py` modules with no importers |
32
+ | `code_rules_dead_split_branch.py` | A conditional whose falsy branch is unreachable because the tested value comes from a separator `str.split()`, which never returns an empty list |
32
33
  | `code_rules_docstrings.py` | Google-style docstrings; `Args:` section matches signature; fallback-branch coverage |
33
34
  | `code_rules_duplicate_body.py` | A function body copied from a sibling module, or a helper body inlined as a block inside a larger function in the same file |
34
35
  | `code_rules_imports_logging.py` | Imports at top of file; logging format-arg style; printf tokens in `str.format`-logger messages |
@@ -37,6 +38,7 @@ The check modules it calls are the `code_rules_<concern>.py` files below.
37
38
  | `code_rules_naming_collection.py` | Collection names must use `all_*` prefix |
38
39
  | `code_rules_optional_params.py` | No optional parameters where a required one would do |
39
40
  | `code_rules_orphan_css_class.py` | CSS class attributes in Python markup with no matching `.<class>` selector |
41
+ | `code_rules_paired_test.py` | A public function omitted by a module's established paired test suite must get a behavioral test — checked on both the production-module write and the stem-matched test-file write |
40
42
  | `code_rules_path_utils.py` | Path utility helpers shared across check modules |
41
43
  | `code_rules_paths_syspath.py` | `sys.path.insert` must be guarded |
42
44
  | `code_rules_probe_chains.py` | Probe-chain detection logic |
@@ -44,7 +46,7 @@ The check modules it calls are the `code_rules_<concern>.py` files below.
44
46
  | `code_rules_probe_recording.py` | Probe recording utilities |
45
47
  | `code_rules_scope_binding.py` | Scope/binding analysis utilities |
46
48
  | `code_rules_shared.py` | Shared dataclasses and helpers used by multiple check modules |
47
- | `code_rules_string_magic.py` | Magic string detection with masking and f-string support |
49
+ | `code_rules_string_magic.py` | Magic string detection with masking and f-string support; whitespace-only indentation literals in function bodies |
48
50
  | `code_rules_test_assertions.py` | Test assertion style rules |
49
51
  | `code_rules_test_branching_except.py` | No bare or broad `except` in test branches |
50
52
  | `code_rules_test_isolation.py` | Tests must not rely on home-dir or temp-dir side effects |
@@ -64,6 +66,7 @@ The check modules it calls are the `code_rules_<concern>.py` files below.
64
66
  | `destructive_command_blocker.py` | PreToolUse (Bash/PowerShell) | Shell commands with destructive literals (`rm -rf`, `git reset --hard`, etc.) |
65
67
  | `docstring_rule_gate_count_blocker.py` | PreToolUse (Write/Edit/MultiEdit) | A stale spelled-out gate-validator count in `docstring-prose-matches-implementation.md` — the "N more gate validators" / "M gated slices" count drifting from the `check_docstring_*` validators the prose names |
66
68
  | `duplicate_rmtree_helper_blocker.py` | PreToolUse (Write/Edit) | A local re-definition of the Windows-safe rmtree helper trio (`_strip_read_only_and_retry`, `_force_remove_tree` / `force_rmtree`) in place of importing a shared helper |
69
+ | `env_var_table_code_drift_blocker.py` | PreToolUse (Write/Edit/MultiEdit) | A markdown env-var summary table row attributing an environment variable to a code file whose source never references that variable name |
67
70
  | `es_exe_path_rewriter.py` | PreToolUse | Rewrites paths referencing `.exe` under the Everything search path |
68
71
  | `gh_body_arg_blocker.py` | PreToolUse (Bash) | `gh` commands passing `--body`/`-b` directly (requires `--body-file` instead) |
69
72
  | `gh_pr_author_enforcer.py` | PreToolUse | Enforces PR author identity rules |
@@ -73,7 +76,7 @@ The check modules it calls are the `code_rules_<concern>.py` files below.
73
76
  | `intent_only_ending_blocker.py` | Stop | Responses that end on a plan or intent without doing the work |
74
77
  | `md_to_html_blocker.py` | PreToolUse (Write/Edit) | Writing `.md` files when an `.html` companion is required |
75
78
  | `open_questions_in_plans_blocker.py` | PreToolUse (Write/Edit) | Plan documents with unresolved open questions |
76
- | `package_inventory_stale_blocker.py` | PreToolUse (Write) | A new production code file created in a directory whose `README.md`/`CLAUDE.md` inventory names two or more sibling files but no entry for the new file |
79
+ | `package_inventory_stale_blocker.py` | PreToolUse (Write) | A new production code file created in a directory whose `README.md`/`CLAUDE.md` inventory (or a parent skill's `SKILL.md` Layout table mapping the `scripts/` subdirectory) names two or more sibling files but no entry for the new file |
77
80
  | `plain_language_blocker.py` | PreToolUse (Write/Edit/AskUserQuestion) | Heavy or jargon words in user-facing prose |
78
81
  | `pr_converge_bugteam_enforcer.py` | PreToolUse | Enforces that bugteam runs in parallel with bugbot in pr-converge loops |
79
82
  | `pr_description_enforcer.py` | PreToolUse (Bash) | `gh pr create`/`edit` without a PR-description-writer-authored body |
@@ -16,18 +16,26 @@ The scan is deliberately conservative to keep false positives near zero:
16
16
 
17
17
  - Only dedicated constants modules participate; ordinary production modules,
18
18
  whose file-global constants are governed by the use-count rule, are skipped.
19
- - A module declaring ``__all__`` is skipped: the author has named its export
20
- surface explicitly, so a name listed there is live by declaration and a name
21
- absent there is the author's stated intent, neither of which this check second
22
- guesses.
23
- - A constant is live when its name appears anywhere the scan reaches —
24
- imported, read, listed in ``__all__``, or referenced in a string annotation —
25
- in any ``.py`` module, including the constants module itself.
19
+ - A module declaring ``__all__`` narrows the check to the constants its
20
+ ``__all__`` list names the explicit export surface. Each exported constant
21
+ must be imported or read by some other module, since a name an author exports
22
+ yet no module consumes is dead by §9.8; the module's own ``__all__`` entry
23
+ never counts as that consumer. A constant the module defines but ``__all__``
24
+ omits is the author's stated private value and is left alone.
25
+ - A constant is live when its name appears in another ``.py`` module the scan
26
+ reaches — imported, read, listed in that module's ``__all__``, or referenced
27
+ in a string annotation — or when the constants module itself reads it in code;
28
+ a name listed only in the constants module's own ``__all__`` does not keep an
29
+ exported constant live.
26
30
  - When the package-tree scan leaves a constant unreferenced, the scan widens to
27
- the repository root (the nearest ``.git`` ancestor) so a consumer in a sibling
28
- tree of the same repository counts; a module outside any repository is judged
29
- on the package-tree scan alone. The widened pass skips the package subtree the
30
- first pass already covered, so no file is read twice.
31
+ the repository root (the nearest ``.git`` ancestor). The widened pass counts a
32
+ sibling-tree reference only when a module imports the name through a
33
+ ``from <module> import`` whose final dotted segment equals the written
34
+ module's filename stem, so a genuine cross-tree consumer of this constants
35
+ module keeps the constant live while a same-named constant exported by an
36
+ unrelated module never masks a dead one. A module outside any repository is
37
+ judged on the package-tree scan alone, and the widened pass skips the package
38
+ subtree the first pass already covered, so no file is read twice.
31
39
  - The combined file count of the package-tree and widened passes is bounded by a
32
40
  cap, so a write under an unexpectedly large tree cannot stall the hook; a write
33
41
  whose scan hits the cap is treated as "cannot prove dead" and flags nothing.
@@ -38,6 +46,8 @@ The scan is deliberately conservative to keep false positives near zero:
38
46
  import ast
39
47
  import os
40
48
  import sys
49
+ from collections.abc import Callable
50
+ from functools import partial
41
51
  from pathlib import Path
42
52
 
43
53
  _blocking_directory = str(Path(__file__).resolve().parent)
@@ -146,21 +156,61 @@ def _module_declares_dunder_all(tree: ast.Module) -> bool:
146
156
  return any(_statement_binds_dunder_all(each_node) for each_node in tree.body)
147
157
 
148
158
 
149
- def _referenced_names_in_source(source: str, load_only: bool = False) -> set[str]:
159
+ def _dunder_all_member_names(tree: ast.Module) -> set[str]:
160
+ """Return the string member names a module's ``__all__`` sequence lists.
161
+
162
+ Reads the value of each ``__all__`` assignment whose value is a list, tuple,
163
+ or set literal and collects every string element. A non-literal ``__all__``
164
+ value (built by concatenation or a comprehension) contributes no names, so a
165
+ constant the check cannot prove is exported stays out of the exported set.
166
+
167
+ Args:
168
+ tree: The parsed constants module.
169
+
170
+ Returns:
171
+ The set of names the module names in its ``__all__`` literal.
172
+ """
173
+ member_names: set[str] = set()
174
+ for each_statement in tree.body:
175
+ if not _statement_binds_dunder_all(each_statement):
176
+ continue
177
+ value_node: ast.expr | None = None
178
+ if isinstance(each_statement, ast.Assign):
179
+ value_node = each_statement.value
180
+ elif isinstance(each_statement, ast.AnnAssign):
181
+ value_node = each_statement.value
182
+ if not isinstance(value_node, ast.List | ast.Tuple | ast.Set):
183
+ continue
184
+ for each_element in value_node.elts:
185
+ if isinstance(each_element, ast.Constant) and isinstance(each_element.value, str):
186
+ member_names.add(each_element.value)
187
+ return member_names
188
+
189
+
190
+ def _referenced_names_in_source(
191
+ source: str,
192
+ load_only: bool = False,
193
+ collect_string_literals: bool = True,
194
+ ) -> set[str]:
150
195
  """Return every name a module references — imported, read, or re-exported.
151
196
 
152
197
  Collects imported binding names, ``from`` import member names, name
153
- references, attribute roots, and string literals (so a name listed in an
154
- ``__all__`` literal or named in a string annotation counts as a reference).
155
- A module that fails to parse contributes no names. With ``load_only`` set,
156
- only ``Load``-context names count, so a constant's own assignment target in
157
- the module being judged does not count as a reference to itself.
198
+ references, attribute roots, and (when ``collect_string_literals`` is set)
199
+ string literals, so a name listed in an ``__all__`` literal or named in a
200
+ string annotation counts as a reference. A module that fails to parse
201
+ contributes no names. With ``load_only`` set, only ``Load``-context names
202
+ count, so a constant's own assignment target in the module being judged does
203
+ not count as a reference to itself.
158
204
 
159
205
  Args:
160
206
  source: The full text of a ``.py`` module under the scan root.
161
207
  load_only: When True, count only ``Load``-context name references,
162
208
  excluding ``Store``/``Del`` targets. Used for the written constants
163
209
  module so a definition is not mistaken for its own consumer.
210
+ collect_string_literals: When True, count every string literal as a
211
+ referenced name. Set False for the written module under an ``__all__``
212
+ export check so the module's own ``__all__`` entry never shields an
213
+ exported constant that no other module consumes.
164
214
 
165
215
  Returns:
166
216
  The set of names the module references.
@@ -179,11 +229,63 @@ def _referenced_names_in_source(source: str, load_only: bool = False) -> set[str
179
229
  for each_alias in each_node.names:
180
230
  referenced_names.add(each_alias.asname or each_alias.name)
181
231
  referenced_names.add(each_alias.name)
182
- elif isinstance(each_node, ast.Constant) and isinstance(each_node.value, str):
232
+ elif (
233
+ collect_string_literals
234
+ and isinstance(each_node, ast.Constant)
235
+ and isinstance(each_node.value, str)
236
+ ):
183
237
  referenced_names.add(each_node.value)
184
238
  return referenced_names
185
239
 
186
240
 
241
+ def _module_final_segment(module_path: str | None) -> str:
242
+ """Return the final dotted segment of an import module path.
243
+
244
+ Args:
245
+ module_path: The ``module`` attribute of a ``from ... import`` node, or
246
+ None for a bare relative import (``from . import x``).
247
+
248
+ Returns:
249
+ The text after the last dot, the whole string when it carries no dot, or
250
+ the empty string when ``module_path`` is None or empty.
251
+ """
252
+ if not module_path:
253
+ return ""
254
+ return module_path.rsplit(".", 1)[-1]
255
+
256
+
257
+ def _qualified_import_member_names(source: str, module_stem: str) -> set[str]:
258
+ """Return names imported from a module whose filename stem is ``module_stem``.
259
+
260
+ A cross-package consumer of an exported constant imports it through an
261
+ explicit ``from <module> import NAME`` whose module path ends in the defining
262
+ module's filename stem. Collecting only those member names binds a
263
+ widened-scan reference to the module that actually defines the constant, so a
264
+ same-named constant exported by an unrelated module never masks a dead one.
265
+
266
+ Args:
267
+ source: The full text of a ``.py`` module under the repository root.
268
+ module_stem: The filename stem of the constants module being judged.
269
+
270
+ Returns:
271
+ The member names imported from a module whose final dotted segment equals
272
+ ``module_stem``. A module that fails to parse contributes no names.
273
+ """
274
+ try:
275
+ tree = ast.parse(source)
276
+ except SyntaxError:
277
+ return set()
278
+ member_names: set[str] = set()
279
+ for each_node in ast.walk(tree):
280
+ if not isinstance(each_node, ast.ImportFrom):
281
+ continue
282
+ if _module_final_segment(each_node.module) != module_stem:
283
+ continue
284
+ for each_alias in each_node.names:
285
+ member_names.add(each_alias.name)
286
+ return member_names
287
+
288
+
187
289
  def _scan_root_for_constants_module(file_path: str) -> Path:
188
290
  """Return the directory tree to scan for references to the module's constants.
189
291
 
@@ -226,41 +328,48 @@ def _is_under_directory(candidate_path: Path, ancestor_directory: Path) -> bool:
226
328
  return True
227
329
 
228
330
 
229
- def _all_referenced_names_under_root(
331
+ def _collect_names_under_root(
230
332
  scan_root: Path,
231
333
  written_path: Path,
232
- written_content: str,
334
+ all_seed_names: set[str],
335
+ extract_names: Callable[[str], set[str]],
233
336
  already_scanned_count: int = 0,
234
337
  excluded_subtree: Path | None = None,
235
338
  ) -> tuple[set[str], int, bool]:
236
- """Return referenced names under the scan root, the running count, and a cap flag.
237
-
238
- The written module's on-disk text is replaced by ``written_content`` so the
239
- post-edit view is judged, never the stale disk copy. Sibling modules are read
240
- from disk. Reading stops once the running file count exceeds the configured
241
- cap so a write under an unexpectedly large tree cannot stall the hook; the
242
- boolean signals the caller to treat that case as "cannot prove dead". When
243
- ``excluded_subtree`` is supplied, every ``.py`` module under that directory is
244
- skipped, so the widened repository scan never re-reads a file the
339
+ """Collect referenced names under the scan root via a per-module extractor.
340
+
341
+ Walks every ``.py`` module under ``scan_root`` (excluding the written module
342
+ itself, and any module under ``excluded_subtree``), applies ``extract_names``
343
+ to each module's text, and unions the result onto ``all_seed_names``. Reading
344
+ stops once the running file count exceeds the configured cap so a write under
345
+ an unexpectedly large tree cannot stall the hook; the boolean signals the
346
+ caller to treat that case as "cannot prove dead". The ``excluded_subtree``
347
+ skip keeps the widened repository scan from re-reading a file the
245
348
  package-tree scan already covered.
246
349
 
247
350
  Args:
248
351
  scan_root: The directory tree to scan.
249
- written_path: The resolved path of the module being written.
250
- written_content: The post-edit text of the written module.
352
+ written_path: The resolved path of the module being written, skipped so
353
+ its own text is judged through ``all_seed_names`` rather than the
354
+ stale disk copy.
355
+ all_seed_names: The names the written module itself contributes, unioned
356
+ in before the walk begins.
357
+ extract_names: Maps one module's source text to the set of names it
358
+ contributes — the generous reference collector for the package-tree
359
+ pass, the stem-bound import collector for the widened pass.
251
360
  already_scanned_count: The file count accumulated by a prior pass, so the
252
361
  cap bounds the combined work of the package-tree and widened passes.
253
362
  excluded_subtree: A resolved directory whose ``.py`` modules are skipped,
254
363
  or None to scan every file under the root.
255
364
 
256
365
  Returns:
257
- A (referenced_names, running_count, cap_was_hit) triple. The name set is
258
- the union across every scanned module, unioned with the names the written
259
- module itself references; running_count is the cumulative file count
260
- including ``already_scanned_count``; cap_was_hit is True when the scan
261
- stopped at the configured file cap before scanning the whole tree.
366
+ A (collected_names, running_count, cap_was_hit) triple. collected_names
367
+ is ``all_seed_names`` unioned with every scanned module's contribution;
368
+ running_count is the cumulative file count including
369
+ ``already_scanned_count``; cap_was_hit is True when the scan stopped at
370
+ the configured file cap before scanning the whole tree.
262
371
  """
263
- all_referenced_names = _referenced_names_in_source(written_content, load_only=True)
372
+ collected_names = set(all_seed_names)
264
373
  written_path_key = os.path.normcase(str(written_path))
265
374
  scanned_file_count = already_scanned_count
266
375
  for each_path in scan_root.rglob("*" + PYTHON_SOURCE_SUFFIX):
@@ -273,13 +382,13 @@ def _all_referenced_names_under_root(
273
382
  continue
274
383
  scanned_file_count += 1
275
384
  if scanned_file_count > MAX_SCAN_ROOT_FILE_COUNT:
276
- return all_referenced_names, scanned_file_count, True
385
+ return collected_names, scanned_file_count, True
277
386
  try:
278
387
  sibling_source = each_path.read_text(encoding="utf-8")
279
388
  except (OSError, UnicodeDecodeError):
280
389
  continue
281
- all_referenced_names |= _referenced_names_in_source(sibling_source)
282
- return all_referenced_names, scanned_file_count, False
390
+ collected_names |= extract_names(sibling_source)
391
+ return collected_names, scanned_file_count, False
283
392
 
284
393
 
285
394
  def _repository_root_for(written_path: Path) -> Path | None:
@@ -324,6 +433,37 @@ def _module_is_exempt_from_constant_check(file_path: str) -> bool:
324
433
  return not _is_dedicated_constants_module(file_path)
325
434
 
326
435
 
436
+ def _constants_under_check(tree: ast.Module) -> tuple[list[tuple[str, int]], bool]:
437
+ """Return the constants to judge and whether the seed counts string literals.
438
+
439
+ A module without ``__all__`` judges every module-scope constant and lets its
440
+ own string literals seed the reference scan. A module declaring ``__all__``
441
+ judges only the constants its ``__all__`` list names — the explicit export
442
+ surface — and withholds its own string literals from the seed, so an
443
+ ``__all__`` entry never counts as the consumer that keeps an exported constant
444
+ live. A constant the module defines but ``__all__`` omits is the author's
445
+ stated private value and is left out of the judged set.
446
+
447
+ Args:
448
+ tree: The parsed constants module.
449
+
450
+ Returns:
451
+ A (definitions, seed_collect_string_literals) pair: the (name, line)
452
+ constants to judge, and whether the written module's string literals seed
453
+ the referenced-name set.
454
+ """
455
+ constant_definitions = _module_constant_definitions(tree)
456
+ if not _module_declares_dunder_all(tree):
457
+ return constant_definitions, True
458
+ exported_names = _dunder_all_member_names(tree)
459
+ exported_definitions = [
460
+ (each_name, each_line)
461
+ for each_name, each_line in constant_definitions
462
+ if each_name in exported_names
463
+ ]
464
+ return exported_definitions, False
465
+
466
+
327
467
  def check_dead_module_constants(
328
468
  content: str,
329
469
  file_path: str,
@@ -334,16 +474,23 @@ def check_dead_module_constants(
334
474
  Runs only on a dedicated constants module (``*_constants.py`` or a module
335
475
  under ``config/``); every other production module's file-global constants
336
476
  are governed by the use-count rule instead. A constant is dead when its name
337
- appears in no ``.py`` module under the enclosing package tree, nor anywhere
338
- in the repository the scan widens to when the package-tree scan leaves the
339
- constant unreferencednot imported, not read, not listed in an ``__all__``
340
- literal, not named in a string annotation. A module declaring its own
341
- ``__all__`` is skipped so the author's explicit export surface is never
342
- second-guessed. A scan whose combined package-tree and widened file count
343
- exceeds the configured cap returns ``[]`` (cannot prove dead), bounding the
344
- work so the blocking hook cannot stall under a large tree. Whole-file
345
- analysis runs against ``full_file_content`` when supplied so an Edit fragment
346
- is judged against the reconstructed post-edit file.
477
+ appears in no ``.py`` module under the enclosing package tree not imported,
478
+ not read, not listed in another module's ``__all__`` literal, not named in a
479
+ string annotationand, in the repository-wide scan the check widens to when
480
+ the package-tree scan leaves the constant unreferenced, no module imports the
481
+ name from a ``from <module> import`` whose final dotted segment equals this
482
+ module's filename stem. Binding the widened scan to the stem keeps a genuine
483
+ cross-tree consumer counting while a same-named constant exported by an
484
+ unrelated module never masks a dead one. A module declaring ``__all__``
485
+ narrows the check to the constants its ``__all__`` list names: each must be
486
+ imported or read by another module, and the module's own ``__all__`` entry
487
+ never counts as that consumer, so an exported constant no module consumes is
488
+ flagged; a constant the module defines but ``__all__`` omits is the author's
489
+ private value and is left alone. A scan whose combined package-tree and
490
+ widened file count exceeds the configured cap returns ``[]`` (cannot prove
491
+ dead), bounding the work so the blocking hook cannot stall under a large tree.
492
+ Whole-file analysis runs against ``full_file_content`` when supplied so an
493
+ Edit fragment is judged against the reconstructed post-edit file.
347
494
 
348
495
  Args:
349
496
  content: The new content under validation (Edit fragment or whole file).
@@ -355,8 +502,9 @@ def check_dead_module_constants(
355
502
  Returns:
356
503
  One violation message per dead module-level constant, capped at the
357
504
  configured maximum. Returns an empty list when the file is exempt, no
358
- constant is defined, the module declares ``__all__``, the scan exceeds the
359
- file cap, or a SyntaxError prevents parsing.
505
+ constant is in scope (none defined, or none exported when ``__all__`` is
506
+ declared), the scan exceeds the file cap, or a SyntaxError prevents
507
+ parsing.
360
508
  """
361
509
  if _module_is_exempt_from_constant_check(file_path):
362
510
  return []
@@ -365,17 +513,21 @@ def check_dead_module_constants(
365
513
  tree = ast.parse(effective_content)
366
514
  except SyntaxError:
367
515
  return []
368
- if _module_declares_dunder_all(tree):
369
- return []
370
- constant_definitions = _module_constant_definitions(tree)
516
+ constant_definitions, seed_collect_string_literals = _constants_under_check(tree)
371
517
  if not constant_definitions:
372
518
  return []
373
519
  scan_root = _scan_root_for_constants_module(file_path)
374
520
  written_path = Path(file_path).resolve()
375
- all_referenced_names, scanned_file_count, cap_was_hit = _all_referenced_names_under_root(
521
+ written_seed_names = _referenced_names_in_source(
522
+ effective_content,
523
+ load_only=True,
524
+ collect_string_literals=seed_collect_string_literals,
525
+ )
526
+ all_referenced_names, scanned_file_count, cap_was_hit = _collect_names_under_root(
376
527
  scan_root,
377
528
  written_path,
378
- effective_content,
529
+ written_seed_names,
530
+ _referenced_names_in_source,
379
531
  )
380
532
  if cap_was_hit:
381
533
  return []
@@ -385,10 +537,14 @@ def check_dead_module_constants(
385
537
  if has_unreferenced_constant:
386
538
  repository_root = _repository_root_for(written_path)
387
539
  if repository_root is not None and repository_root != scan_root:
388
- widened_names, _widened_count, widened_cap_was_hit = _all_referenced_names_under_root(
540
+ collect_qualified_imports = partial(
541
+ _qualified_import_member_names, module_stem=written_path.stem
542
+ )
543
+ widened_names, _widened_count, widened_cap_was_hit = _collect_names_under_root(
389
544
  repository_root,
390
545
  written_path,
391
- effective_content,
546
+ set(),
547
+ collect_qualified_imports,
392
548
  already_scanned_count=scanned_file_count,
393
549
  excluded_subtree=scan_root,
394
550
  )