claude-dev-env 1.65.0 → 1.65.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -6,8 +6,10 @@ project, so a constant defined there is never proven dead by a single-file scan
6
6
  alone. This check resolves the enclosing package tree — the scan root — and
7
7
  flags an UPPER_SNAKE constant defined in the written module whose name appears
8
8
  in no ``.py`` module anywhere under that root: not as an imported name, not as a
9
- read, not as a re-export. That is the ``MEDIUM_TEXT``-style dead constant the
10
- CODE_RULES §9.8 dead-code rule targets, caught at Write/Edit time before the
9
+ read, not as a re-export. When a constant looks dead in the package tree, the
10
+ scan widens to the whole repository so a consumer in a sibling tree counts
11
+ before the constant is flagged. That is the ``MEDIUM_TEXT``-style dead constant
12
+ the CODE_RULES §9.8 dead-code rule targets, caught at Write/Edit time before the
11
13
  unused constant lands.
12
14
 
13
15
  The scan is deliberately conservative to keep false positives near zero:
@@ -18,11 +20,19 @@ The scan is deliberately conservative to keep false positives near zero:
18
20
  surface explicitly, so a name listed there is live by declaration and a name
19
21
  absent there is the author's stated intent, neither of which this check second
20
22
  guesses.
21
- - A constant is live when its name appears anywhere under the scan root
23
+ - A constant is live when its name appears anywhere the scan reaches
22
24
  imported, read, listed in ``__all__``, or referenced in a string annotation —
23
25
  in any ``.py`` module, including the constants module itself.
24
- - Test modules under the scan root still count as references, so a constant used
25
- only by a test stays live.
26
+ - 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 combined file count of the package-tree and widened passes is bounded by a
32
+ cap, so a write under an unexpectedly large tree cannot stall the hook; a write
33
+ whose scan hits the cap is treated as "cannot prove dead" and flags nothing.
34
+ - Test modules under the scanned tree still count as references, so a constant
35
+ used only by a test stays live.
26
36
  """
27
37
 
28
38
  import ast
@@ -48,6 +58,7 @@ from hooks_constants.dead_module_constant_constants import ( # noqa: E402
48
58
  DEAD_MODULE_CONSTANT_GUIDANCE,
49
59
  DUNDER_ALL_NAME,
50
60
  DUNDER_INIT_FILENAME,
61
+ GIT_DIRECTORY_NAME,
51
62
  MAX_DEAD_MODULE_CONSTANT_ISSUES,
52
63
  MAX_SCAN_ROOT_FILE_COUNT,
53
64
  MINIMUM_UPPER_SNAKE_LENGTH,
@@ -197,46 +208,100 @@ def _scan_root_for_constants_module(file_path: str) -> Path:
197
208
  return enclosing_directory
198
209
 
199
210
 
211
+ def _is_under_directory(candidate_path: Path, ancestor_directory: Path) -> bool:
212
+ """Return whether a resolved path lies inside a resolved ancestor directory.
213
+
214
+ Args:
215
+ candidate_path: The resolved file path to test.
216
+ ancestor_directory: The resolved directory that may contain the path.
217
+
218
+ Returns:
219
+ True when ``candidate_path`` is the ancestor directory itself or a
220
+ descendant of it, False otherwise.
221
+ """
222
+ try:
223
+ candidate_path.relative_to(ancestor_directory)
224
+ except ValueError:
225
+ return False
226
+ return True
227
+
228
+
200
229
  def _all_referenced_names_under_root(
201
230
  scan_root: Path,
202
231
  written_path: Path,
203
232
  written_content: str,
204
- ) -> tuple[set[str], bool]:
205
- """Return referenced names under the scan root and whether the file cap was hit.
233
+ already_scanned_count: int = 0,
234
+ excluded_subtree: Path | None = None,
235
+ ) -> tuple[set[str], int, bool]:
236
+ """Return referenced names under the scan root, the running count, and a cap flag.
206
237
 
207
238
  The written module's on-disk text is replaced by ``written_content`` so the
208
- post-edit view is judged, never the stale disk copy. Sibling modules are
209
- read from disk. Reading stops after the configured file cap so a write under
210
- an unexpectedly large tree cannot stall the hook; the boolean signals the
211
- caller to treat that case as "cannot prove dead".
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
245
+ package-tree scan already covered.
212
246
 
213
247
  Args:
214
248
  scan_root: The directory tree to scan.
215
249
  written_path: The resolved path of the module being written.
216
250
  written_content: The post-edit text of the written module.
251
+ already_scanned_count: The file count accumulated by a prior pass, so the
252
+ cap bounds the combined work of the package-tree and widened passes.
253
+ excluded_subtree: A resolved directory whose ``.py`` modules are skipped,
254
+ or None to scan every file under the root.
217
255
 
218
256
  Returns:
219
- A (referenced_names, cap_was_hit) pair. The name set is the union across
220
- every scanned module; cap_was_hit is True when the scan stopped at the
221
- configured file cap before scanning the whole tree.
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.
222
262
  """
223
263
  all_referenced_names = _referenced_names_in_source(written_content, load_only=True)
224
264
  written_path_key = os.path.normcase(str(written_path))
225
- scanned_file_count = 1
265
+ scanned_file_count = already_scanned_count
226
266
  for each_path in scan_root.rglob("*" + PYTHON_SOURCE_SUFFIX):
227
267
  if not each_path.is_file():
228
268
  continue
229
- if os.path.normcase(str(each_path.resolve())) == written_path_key:
269
+ resolved_path = each_path.resolve()
270
+ if os.path.normcase(str(resolved_path)) == written_path_key:
271
+ continue
272
+ if excluded_subtree is not None and _is_under_directory(resolved_path, excluded_subtree):
230
273
  continue
231
274
  scanned_file_count += 1
232
275
  if scanned_file_count > MAX_SCAN_ROOT_FILE_COUNT:
233
- return all_referenced_names, True
276
+ return all_referenced_names, scanned_file_count, True
234
277
  try:
235
278
  sibling_source = each_path.read_text(encoding="utf-8")
236
279
  except (OSError, UnicodeDecodeError):
237
280
  continue
238
281
  all_referenced_names |= _referenced_names_in_source(sibling_source)
239
- return all_referenced_names, False
282
+ return all_referenced_names, scanned_file_count, False
283
+
284
+
285
+ def _repository_root_for(written_path: Path) -> Path | None:
286
+ """Return the nearest ancestor directory that holds a ``.git`` entry.
287
+
288
+ Walks upward from the written module toward the filesystem root. A normal
289
+ checkout carries a ``.git`` directory and a git worktree carries a ``.git``
290
+ file; both satisfy ``exists()``. The repository root bounds the widened
291
+ cross-tree reference scan.
292
+
293
+ Args:
294
+ written_path: The resolved path of the constants module being written.
295
+
296
+ Returns:
297
+ The repository root directory, or ``None`` when no ancestor carries a
298
+ ``.git`` entry, so a module outside any repository triggers no widened
299
+ scan.
300
+ """
301
+ for each_ancestor in written_path.parents:
302
+ if (each_ancestor / GIT_DIRECTORY_NAME).exists():
303
+ return each_ancestor
304
+ return None
240
305
 
241
306
 
242
307
  def _module_is_exempt_from_constant_check(file_path: str) -> bool:
@@ -269,10 +334,14 @@ def check_dead_module_constants(
269
334
  Runs only on a dedicated constants module (``*_constants.py`` or a module
270
335
  under ``config/``); every other production module's file-global constants
271
336
  are governed by the use-count rule instead. A constant is dead when its name
272
- appears in no ``.py`` module anywhere under the enclosing package tree not
273
- imported, not read, not listed in an ``__all__`` literal, not named in a
274
- string annotation. A module declaring its own ``__all__`` is skipped so the
275
- author's explicit export surface is never second-guessed. Whole-file
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 unreferenced not 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
276
345
  analysis runs against ``full_file_content`` when supplied so an Edit fragment
277
346
  is judged against the reconstructed post-edit file.
278
347
 
@@ -285,7 +354,9 @@ def check_dead_module_constants(
285
354
 
286
355
  Returns:
287
356
  One violation message per dead module-level constant, capped at the
288
- configured maximum.
357
+ 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.
289
360
  """
290
361
  if _module_is_exempt_from_constant_check(file_path):
291
362
  return []
@@ -301,13 +372,29 @@ def check_dead_module_constants(
301
372
  return []
302
373
  scan_root = _scan_root_for_constants_module(file_path)
303
374
  written_path = Path(file_path).resolve()
304
- all_referenced_names, cap_was_hit = _all_referenced_names_under_root(
375
+ all_referenced_names, scanned_file_count, cap_was_hit = _all_referenced_names_under_root(
305
376
  scan_root,
306
377
  written_path,
307
378
  effective_content,
308
379
  )
309
380
  if cap_was_hit:
310
381
  return []
382
+ has_unreferenced_constant = any(
383
+ each_name not in all_referenced_names for each_name, _ in constant_definitions
384
+ )
385
+ if has_unreferenced_constant:
386
+ repository_root = _repository_root_for(written_path)
387
+ 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(
389
+ repository_root,
390
+ written_path,
391
+ effective_content,
392
+ already_scanned_count=scanned_file_count,
393
+ excluded_subtree=scan_root,
394
+ )
395
+ if widened_cap_was_hit:
396
+ return []
397
+ all_referenced_names |= widened_names
311
398
  issues: list[str] = []
312
399
  for each_name, each_line in constant_definitions:
313
400
  if each_name in all_referenced_names:
@@ -39,8 +39,13 @@ def neutral_root() -> Iterator[Path]:
39
39
  own ``tmp_path`` directory name embeds the test name, which would make every
40
40
  synthetic constants path look like a test file. A neutral ``mkdtemp`` root
41
41
  mirrors how a production constants module path looks.
42
+
43
+ A ``.git`` marker is planted at the root so the cross-tree widening resolves
44
+ the repository root to this synthetic tree, never an enclosing real
45
+ checkout, keeping every test bounded and deterministic.
42
46
  """
43
47
  neutral_directory = Path(tempfile.mkdtemp(prefix="deadconst-")).resolve()
48
+ (neutral_directory / ".git").mkdir()
44
49
  try:
45
50
  yield neutral_directory
46
51
  finally:
@@ -186,3 +191,86 @@ def test_is_skipped_on_a_constants_test_file(neutral_root: Path) -> None:
186
191
  test_constants_path.write_text(body, encoding="utf-8")
187
192
  issues = _check(body, str(test_constants_path))
188
193
  assert issues == [], f"Test files are exempt, got: {issues}"
194
+
195
+
196
+ def _build_cross_tree_repository(
197
+ repository_root: Path,
198
+ constants_body: str,
199
+ sibling_consumer_body: str,
200
+ ) -> Path:
201
+ config_directory = repository_root / "shared" / "theme_db" / "config"
202
+ config_directory.mkdir(parents=True)
203
+ constants_path = config_directory / "constants.py"
204
+ constants_path.write_text(constants_body, encoding="utf-8")
205
+ sibling_directory = repository_root / "cdp"
206
+ sibling_directory.mkdir(parents=True)
207
+ (sibling_directory / "tally.py").write_text(sibling_consumer_body, encoding="utf-8")
208
+ return constants_path
209
+
210
+
211
+ def test_does_not_flag_constant_used_only_in_a_sibling_tree(neutral_root: Path) -> None:
212
+ constants_body = 'CROSS_TREE_CONSTANT = "cross"\nLOCALLY_DEAD_CONSTANT = "dead"\n'
213
+ sibling_consumer_body = (
214
+ "from shared.theme_db.config.constants import CROSS_TREE_CONSTANT\n"
215
+ "\n"
216
+ "def tally() -> str:\n"
217
+ " return CROSS_TREE_CONSTANT\n"
218
+ )
219
+ constants_path = _build_cross_tree_repository(
220
+ neutral_root, constants_body, sibling_consumer_body
221
+ )
222
+ issues = _check(constants_body, str(constants_path))
223
+ assert not any("CROSS_TREE_CONSTANT" in each_issue for each_issue in issues), (
224
+ f"A constant consumed by a sibling tree in the repository must not be flagged, got: {issues}"
225
+ )
226
+ assert any("LOCALLY_DEAD_CONSTANT" in each_issue for each_issue in issues), (
227
+ f"A constant referenced nowhere in the repository stays flagged, got: {issues}"
228
+ )
229
+
230
+
231
+ def test_returns_empty_list_at_file_cap(
232
+ neutral_root: Path, monkeypatch: pytest.MonkeyPatch
233
+ ) -> None:
234
+ monkeypatch.setattr("code_rules_dead_module_constant.MAX_SCAN_ROOT_FILE_COUNT", 0)
235
+ constants_path = _build_constants_package(
236
+ neutral_root / "workflow",
237
+ CONSTANTS_BODY,
238
+ "def noop() -> None:\n pass\n",
239
+ )
240
+ issues = _check(CONSTANTS_BODY, str(constants_path))
241
+ assert issues == [], f"File cap hit must return [] (cannot prove dead), got: {issues}"
242
+
243
+
244
+ def test_widened_scan_reads_each_file_at_most_once(
245
+ neutral_root: Path, monkeypatch: pytest.MonkeyPatch
246
+ ) -> None:
247
+ constants_body = 'CROSS_TREE_CONSTANT = "cross"\nLOCALLY_DEAD_CONSTANT = "dead"\n'
248
+ sibling_consumer_body = (
249
+ "from shared.theme_db.config.constants import CROSS_TREE_CONSTANT\n"
250
+ "\n"
251
+ "def tally() -> str:\n"
252
+ " return CROSS_TREE_CONSTANT\n"
253
+ )
254
+ constants_path = _build_cross_tree_repository(
255
+ neutral_root, constants_body, sibling_consumer_body
256
+ )
257
+ package_tree_neighbor = constants_path.parent.parent / "neighbor.py"
258
+ package_tree_neighbor.write_text(
259
+ "def neighbor() -> int:\n return 1\n", encoding="utf-8"
260
+ )
261
+ read_counts: dict[str, int] = {}
262
+ original_read_text = Path.read_text
263
+
264
+ def counting_read_text(self: Path, *positional: object, **keyword: object) -> str:
265
+ normalized_key = os.path.normcase(str(self.resolve()))
266
+ read_counts[normalized_key] = read_counts.get(normalized_key, 0) + 1
267
+ return original_read_text(self, *positional, **keyword) # type: ignore[arg-type] # forwards args
268
+
269
+ monkeypatch.setattr(Path, "read_text", counting_read_text)
270
+ _check(constants_body, str(constants_path))
271
+ over_read_paths = {
272
+ each_path: each_count for each_path, each_count in read_counts.items() if each_count > 1
273
+ }
274
+ assert not over_read_paths, (
275
+ f"Widening must read each .py file at most once, got over-reads: {over_read_paths}"
276
+ )
@@ -10,6 +10,7 @@ DUNDER_INIT_FILENAME: str = "__init__.py"
10
10
  CONSTANTS_MODULE_SUFFIX: str = "_constants.py"
11
11
  CONFIG_DIRECTORY_SEGMENT: str = "config"
12
12
  DUNDER_ALL_NAME: str = "__all__"
13
+ GIT_DIRECTORY_NAME: str = ".git"
13
14
  MINIMUM_UPPER_SNAKE_LENGTH: int = 2
14
15
  MAX_DEAD_MODULE_CONSTANT_ISSUES: int = 25
15
16
  MAX_SCAN_ROOT_FILE_COUNT: int = 2000
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-dev-env",
3
- "version": "1.65.0",
3
+ "version": "1.65.1",
4
4
  "description": "Claude Code development standards — rules, hooks, agents, commands, and skills",
5
5
  "type": "module",
6
6
  "bin": {
@@ -96,7 +96,7 @@ test('FIX_SCHEMA requires blockedNeedingEdit and blockerDetail', () => {
96
96
  });
97
97
 
98
98
  test('FIX_RECOVERY_MAX_ATTEMPTS is declared and bounds the recovery loop at 2', () => {
99
- assert.match(constantLine('FIX_RECOVERY_MAX_ATTEMPTS'), /=\s*2/);
99
+ assert.match(constantLine('FIX_RECOVERY_MAX_ATTEMPTS'), /=\s*2\s*$/);
100
100
  });
101
101
 
102
102
  for (const commitFunctionName of ['commitVerifiedFixes', 'commitRepairFixes']) {
@@ -154,6 +154,13 @@ test('commitWithRecovery bounds the loop, re-verifies, and retries the commit on
154
154
  editGuardIndex < verifyGateIndex,
155
155
  'expected the no-edit break to precede the re-verify gate',
156
156
  );
157
+ const recoverEditIndex = recoveryBody.search(/runRecoverEdit\(/);
158
+ const reverifyIndex = recoveryBody.search(/runVerify\(/);
159
+ const retryCommitIndex = recoveryBody.lastIndexOf('runCommit(');
160
+ assert.ok(
161
+ recoverEditIndex < reverifyIndex && reverifyIndex < retryCommitIndex,
162
+ 'expected order recover-edit -> re-verify -> retry commit, so a verify/commit swap fails',
163
+ );
157
164
  });
158
165
 
159
166
  test('applyFixes routes its commit through commitWithRecovery wired to the fix-path steps', () => {
@@ -808,7 +808,7 @@ function recoverCommitBlockEdit(head, blockerDetail, sourceLabel, attempt) {
808
808
  )
809
809
  }
810
810
 
811
- const FIX_RECOVERY_MAX_ATTEMPTS = 4
811
+ const FIX_RECOVERY_MAX_ATTEMPTS = 2
812
812
 
813
813
  /**
814
814
  * Run a commit step and, when it is blocked by a commit-time hook or gate that
@@ -858,6 +858,8 @@ async function applyFixes(head, findings, sourceLabel) {
858
858
  pushed: false,
859
859
  resolvedWithoutCommit: true,
860
860
  summary: editResult?.summary || 'fixes resolved without a code change',
861
+ blockedNeedingEdit: false,
862
+ blockerDetail: '',
861
863
  }
862
864
  }
863
865
  const verifyTranscript = await verifyFixesInWorkingTree(head, findings, sourceLabel)
@@ -867,6 +869,8 @@ async function applyFixes(head, findings, sourceLabel) {
867
869
  pushed: false,
868
870
  resolvedWithoutCommit: false,
869
871
  summary: `verify step did not pass the working-tree fixes for ${findings.length} finding(s) — not committing`,
872
+ blockedNeedingEdit: false,
873
+ blockerDetail: '',
870
874
  }
871
875
  }
872
876
  return commitWithRecovery({
@@ -1091,6 +1095,8 @@ async function repairConvergence(head, failures) {
1091
1095
  pushed: false,
1092
1096
  resolvedWithoutCommit: true,
1093
1097
  summary: editResult?.summary || 'convergence gates resolved without a code change or rebase',
1098
+ blockedNeedingEdit: false,
1099
+ blockerDetail: '',
1094
1100
  }
1095
1101
  }
1096
1102
  const verifyTranscript = await verifyRepairChanges(head, failures)
@@ -1100,6 +1106,8 @@ async function repairConvergence(head, failures) {
1100
1106
  pushed: false,
1101
1107
  resolvedWithoutCommit: false,
1102
1108
  summary: `repair verify step did not pass the working-tree repair on HEAD ${head} — not pushing`,
1109
+ blockedNeedingEdit: false,
1110
+ blockerDetail: '',
1103
1111
  }
1104
1112
  }
1105
1113
  const wasRebased = editResult?.rebased === true