From claude-commands
Enforces investigation of existing code before writing new code to prevent duplication. Includes a pre-implementation checklist and evidence documentation for reuse decisions.
How this skill is triggered — by the user, by Claude, or both
Slash command
/claude-commands:code-centralizationThe summary Claude sees in its skill listing — used to decide when to auto-load this skill
**Purpose**: Before writing ANY new code, you MUST investigate existing code to prevent duplication. This is not optional.
Purpose: Before writing ANY new code, you MUST investigate existing code to prevent duplication. This is not optional.
DEFAULT: REUSE EXISTING CODE - You must prove similar code doesn't already exist before writing new code.
Before writing ANY new function, class, or module:
Search for existing implementations
# Search for similar function names
grep -r "def similar_name" --include="*.py"
# Search for similar logic patterns
grep -r "pattern_keyword" --include="*.py"
# Search imports to find utility modules
grep -r "from.*utils import" --include="*.py"
Document what you found
Justify new code only if reuse is impossible
### Code Investigation for: <what you're implementing>
**Search performed:**
- `grep -r "keyword1" --include="*.py"` → Found: <results>
- `grep -r "keyword2" --include="*.py"` → Found: <results>
**Similar code found:**
- `file1.py:function_name()` - Does X, but not Y (can't reuse because...)
- `file2.py:other_function()` - Does Y, can be extended to also do X
**Decision:**
- [ ] Reuse existing: <which function>
- [ ] Extend existing: <which function + what extension>
- [ ] New code justified: <why reuse/extension impossible>
Duplication is a maintenance liability. When the same logic exists in multiple places, changes must be made in multiple locations, increasing the risk of inconsistencies and bugs.
Identical Logic in Multiple Files
hasattr() checks repeatedSimilar Patterns with Minor Variations
Maintenance Burden
Before (Duplicated Logic):
# ❌ BAD - llm_response.py (22 lines)
@property
def action_resolution(self) -> dict[str, Any]:
if self.structured_response:
if hasattr(self.structured_response, "action_resolution"):
ar = self.structured_response.action_resolution
if ar is not None:
return ar
if hasattr(self.structured_response, "outcome_resolution"):
or_val = self.structured_response.outcome_resolution
if or_val is not None:
return or_val
return {}
# ❌ BAD - world_logic.py (13 lines) - Same logic duplicated
if hasattr(structured_response, "action_resolution"):
action_resolution = getattr(structured_response, "action_resolution", None)
if action_resolution is not None:
unified_response["action_resolution"] = (
action_resolution if isinstance(action_resolution, dict) else {}
)
if hasattr(structured_response, "outcome_resolution"):
outcome_resolution = getattr(structured_response, "outcome_resolution", None)
if outcome_resolution is not None:
unified_response["outcome_resolution"] = (
outcome_resolution if isinstance(outcome_resolution, dict) else {}
)
After (Centralized):
# ✅ GOOD - action_resolution_utils.py (single source of truth)
def get_action_resolution(structured_response: Any) -> dict[str, Any]:
"""Get action_resolution with backward compat fallback."""
if structured_response is None:
return {}
if hasattr(structured_response, "action_resolution"):
ar = structured_response.action_resolution
if ar is not None:
return ar
if hasattr(structured_response, "outcome_resolution"):
or_val = structured_response.outcome_resolution
if or_val is not None:
return or_val
return {}
def add_action_resolution_to_response(structured_response: Any, unified_response: dict[str, Any]) -> None:
"""Add action_resolution/outcome_resolution to API response."""
if structured_response is None:
return
if hasattr(structured_response, "action_resolution"):
ar = getattr(structured_response, "action_resolution", None)
if ar is not None:
unified_response["action_resolution"] = (
ar if isinstance(ar, dict) else {}
)
if hasattr(structured_response, "outcome_resolution"):
or_val = getattr(structured_response, "outcome_resolution", None)
if or_val is not None:
unified_response["outcome_resolution"] = (
or_val if isinstance(or_val, dict) else {}
)
# ✅ GOOD - llm_response.py (2 lines)
@property
def action_resolution(self) -> dict[str, Any]:
return get_action_resolution(self.structured_response)
# ✅ GOOD - world_logic.py (1 line)
add_action_resolution_to_response(structured_response, unified_response)
Results:
Before extracting code, write comprehensive tests for the helper functions:
# ✅ GOOD - Test all edge cases before extraction
def test_get_action_resolution_with_action_resolution(self):
"""Test returns action_resolution when present"""
mock_response = MagicMock()
mock_response.action_resolution = {"player_input": "I attack"}
result = get_action_resolution(mock_response)
self.assertEqual(result["player_input"], "I attack")
def test_get_action_resolution_falls_back_to_outcome_resolution(self):
"""Test falls back to outcome_resolution when action_resolution missing"""
# ... test implementation
def test_get_action_resolution_handles_none(self):
"""Test handles None structured_response"""
result = get_action_resolution(None)
self.assertEqual(result, {})
# ... 15+ more edge case tests
Create helper module with functions that make tests pass:
# ✅ GOOD - Helper module with clear responsibilities
# $PROJECT_ROOT/action_resolution_utils.py
def get_action_resolution(structured_response: Any) -> dict[str, Any]:
"""Single source of truth for fallback logic."""
# Implementation that passes all tests
def add_action_resolution_to_response(structured_response: Any, unified_response: dict[str, Any]) -> None:
"""API response builder with type coercion."""
# Implementation that passes all tests
Replace duplicated logic with helper calls:
# ✅ GOOD - Replace 22 lines with 1 function call
@property
def action_resolution(self) -> dict[str, Any]:
return get_action_resolution(self.structured_response)
Run all existing tests to ensure behavior unchanged:
# ✅ GOOD - Verify backward compatibility
pytest $PROJECT_ROOT/tests/test_action_resolution.py
pytest $PROJECT_ROOT/tests/test_end2end/test_action_resolution_backward_compat_end2end.py
pytest $PROJECT_ROOT/tests/test_action_resolution_utils.py # New helper tests
Each helper function should do one thing well:
# ✅ GOOD - Clear, focused function
def get_action_resolution(structured_response: Any) -> dict[str, Any]:
"""Get action_resolution with backward compat fallback."""
# Only handles retrieval logic
# ❌ BAD - Does too much
def process_action_resolution(structured_response: Any, validate: bool, coerce: bool) -> dict[str, Any]:
"""Gets, validates, and coerces action_resolution."""
# Mixes retrieval, validation, and coercion
Helper functions must maintain exact same behavior:
# ✅ GOOD - Preserves empty dict {} as "present" (not None)
if ar is not None: # Empty dict {} passes this check
return ar
# ❌ BAD - Would break existing behavior
if ar: # Empty dict {} fails this check
return ar
Handle None and invalid types gracefully:
# ✅ GOOD - Defensive None checks
if structured_response is None:
return {}
# ✅ GOOD - Type coercion for API responses
unified_response["action_resolution"] = (
action_resolution if isinstance(action_resolution, dict) else {}
)
Function names should clearly indicate purpose:
# ✅ GOOD - Self-documenting names
get_action_resolution() # Retrieves with fallback
add_action_resolution_to_response() # Adds to API response
# ❌ BAD - Ambiguous names
process_resolution() # What does it do?
handle_action() # Too generic
Different Purposes
Performance Critical
Tight Coupling
Example: narrative_response_schema.py initialization logic stays separate because it handles validation/normalization at object creation time, which is different from runtime property access.
Ensure existing tests provide safety net:
Add comprehensive tests for helpers:
Minimum: 15-20 test cases per helper function to cover all edge cases.
Track improvements:
| Metric | Before | After | Improvement |
|---|---|---|---|
| Lines of duplicated logic | 35 | 0 | -35 lines |
| Helper module lines | 0 | 20 | +20 lines |
| Consuming code lines | 35 | 3 | -32 lines |
| Net change | 35 | 23 | -12 lines |
| Test coverage | 19 tests | 37 tests | +18 tests |
These patterns are explicitly banned and must never appear in code:
_v2/_new/_backup/_old File Names# ❌ BANNED - Never create these files
auth_service_v2.py # Edit the original instead
user_model_new.py # Edit the original instead
config_backup.py # Use git for backups
helper_old.py # Delete and replace
# ✅ CORRECT - Edit existing files directly
auth_service.py # Modify in place
user_model.py # Modify in place
Why banned: Creates confusion about which file is authoritative. Use git for version history.
# ❌ BANNED PHRASES - Never use these
"This is a pre-existing issue"
"This test was already failing"
"Not caused by my changes"
"Unrelated to this PR"
# ✅ CORRECT - Fix ALL failures
# If a test fails vs origin/main, FIX IT. No excuses.
Why banned: All test failures must be fixed in the current PR. There are no "pre-existing" issues - if it fails, fix it.
import logging (in $PROJECT_ROOT/)# ❌ BANNED - Direct logging module in $PROJECT_ROOT/
import logging
logger = logging.getLogger(__name__)
logger.info("message")
# ✅ CORRECT - Use unified logging_util
from mvp_site import logging_util
logging_util.info("message")
logging_util.warning("something concerning")
logging_util.error("something failed")
Why banned: logging_util provides unified output to both GCP Cloud Logging and local files with consistent formatting. Direct import logging bypasses this.
Exception: Test files ($PROJECT_ROOT/tests/*) may use direct logging.
Don't extract code that's only used once:
# ❌ BAD - Over-engineering for single use
def get_single_use_helper():
"""Only called once - not worth extracting"""
pass
Don't create helpers that are harder to use than inline code:
# ❌ BAD - More complex than original
def process_with_fallback(obj, primary_field, fallback_field, default_value, type_check, coerce_func):
"""Too many parameters - harder to use than inline"""
pass
# ✅ GOOD - Simple, focused helper
def get_action_resolution(structured_response: Any) -> dict[str, Any]:
"""Clear purpose, minimal parameters"""
pass
Don't change behavior when centralizing:
# ❌ BAD - Changed behavior (empty dict now returns fallback)
if ar: # Changed from "if ar is not None"
return ar
# ✅ GOOD - Preserves exact behavior
if ar is not None: # Same as original
return ar
Before extracting duplicated code:
See $PROJECT_ROOT/action_resolution_utils.py for a complete example:
llm_response.py and world_logic.pynpx claudepluginhub jleechanorg/claude-commands --plugin claude-commandsDetects and consolidates duplicated code, logic, data, or knowledge across a codebase following the DRY principle.
Extracts duplicated code into shared utilities, components, hooks, and modules from repeated patterns across files like identical functions, UI blocks, state management, or boilerplate.
Detects code duplication and reinvented wheels, recommends existing Python/Rust libraries via PyPI/crates.io, PyO3 bindings, and upstream contributions over forks.