investigate-dependencies
The investigate-dependencies Claude Code skill performs comprehensive audits of imported modules within codebases to identify redundant implementations, unused library features, and improper usage patterns. Use this skill when refactoring code to reduce technical debt, optimize imports, or ensuring dependencies are leveraged according to their design specifications rather than duplicating functionality already available in imported libraries.
git clone --depth 1 https://github.com/taylorsatula/mira-OSS /tmp/investigate-dependencies && cp -r /tmp/investigate-dependencies/.claude/skills/investigate-dependencies ~/.claude/skills/investigate-dependenciesSKILL.md
# Investigate Dependencies: Eliminating Redundant Code Through Dependency Mastery
## 🎯 Mission
Conduct line-by-line walkthroughs of modules to understand how we use external dependencies, identifying:
- **Redundant implementations** of functionality that already exists in imported modules
- **Unused capabilities** in dependencies that could simplify our code
- **Improper usage patterns** that don't align with the module's intended design
- **Missing error handling** for cases the dependency already covers
## 🔍 Investigation Protocol
### Step 1: Import Analysis
For each file under investigation, create an import inventory:
```markdown
## Import Inventory for [filename]
| Import | Source | Purpose | Documentation |
|--------|--------|---------|---------------|
| `uuid` | stdlib | Generate unique identifiers | https://docs.python.org/3/library/uuid.html |
| `FastAPI` | fastapi | Web framework | https://fastapi.tiangolo.com/ |
| `CustomUtil` | local | [Document what we think it does] | [Internal docs] |
```
### Step 2: Line-by-Line Dependency Usage Examination
For each location where an external module is used:
```markdown
### Usage Point: [Function/Method Name] (Lines X-Y)
**Code:**
```python
# Relevant code snippet showing dependency usage
```
**Questions to Answer:**
1. What are we using this dependency for?
2. What capabilities does this dependency offer beyond what we're using?
3. Are we reimplementing functionality the dependency already provides?
4. Does the dependency handle errors/edge cases we're also handling?
5. Are we using this dependency as the authors intended?
**Findings:**
- [Document any redundancies, missing capabilities, or misuse]
```
### Step 3: Documentation Deep Dive
For each significant dependency, review:
1. **Official documentation** - What does the module actually do?
2. **API reference** - What methods/functions are available?
3. **Error handling** - What exceptions does it raise?
4. **Best practices** - How do the authors recommend using it?
5. **Source code** (if needed) - What does the implementation reveal?
### Step 4: Redundancy Detection
Common areas where redundancy occurs:
#### Utility Functions
```python
# ❌ REDUNDANT: Reimplementing datetime.now(UTC)
def get_current_time():
return datetime.datetime.now(datetime.timezone.utc)
# ✅ BETTER: Use the imported utility
from utils.timezone_utils import utc_now
current_time = utc_now() # Already exists in the codebase
```
#### Error Handling
```python
# ❌ REDUNDANT: Manual JSON validation
def parse_json(data: str):
try:
result = json.loads(data)
if not isinstance(result, dict):
raise ValueError("Expected dict")
return result
except json.JSONDecodeError:
return None
# ✅ BETTER: Use Pydantic which handles this
from pydantic import BaseModel
class MyData(BaseModel):
# Pydantic handles JSON parsing, validation, and type checking
pass
```
#### Data Validation
```python
# ❌ REDUNDANT: Manual UUID validation
def validate_uuid(value: str) -> bool:
try:
uuid.UUID(value)
return True
except ValueError:
return False
# ✅ BETTER: Use Pydantic's built-in UUID type
from uuid import UUID
from pydantic import BaseModel
class Request(BaseModel):
user_id: UUID # Pydantic validates this automatically
```
#### Configuration Management
```python
# ❌ REDUNDANT: Manual environment variable handling
def get_config():
host = os.getenv("DB_HOST", "localhost")
port = int(os.getenv("DB_PORT", "5432"))
# Manual type conversion, default handling, validation...
# ✅ BETTER: Use Pydantic Settings
from pydantic_settings import BaseSettings
class DatabaseConfig(BaseSettings):
db_host: str = "localhost"
db_port: int = 5432
# Pydantic handles env vars, types, defaults, validation
```
### Step 5: Capability Gap Analysis
For each dependency, document:
```markdown
## [Dependency Name] - Capability Analysis
### What We're Currently Using:
- [List actual usage]
### Available Capabilities We're Not Using:
- [Feature 1]: Could simplify [code location]
- [Feature 2]: Would eliminate [redundant implementation]
- [Feature 3]: Better error handling for [scenario]
### Recommendations:
1. [Specific refactoring suggestion with rationale]
2. [Another suggestion]
```
## 📋 Investigation Template
When conducting a dependency investigation, follow this structure:
```markdown
# Dependency Investigation: [filename]
## Executive Summary
- **Total Imports**: X (Y external, Z internal)
- **Redundancies Found**: N instances
- **Unused Capabilities**: M opportunities
- **Severity**: HIGH/MEDIUM/LOW
## Import Inventory
[Table of all imports with documentation links]
## Detailed Findings
### [Import 1]
**Usage Locations**: Lines X, Y, Z
**Current Usage**: [What we're doing with it]
**Available Features**: [What else it offers]
**Issues Found**:
- [Redundancy, misuse, or missed opportunity]
**Recommendation**: [Specific action to take]
### [Import 2]
[Same structure]
## Refactoring Recommendations
### Priority 1: Critical Redundancies
1. [High-impact changes that eliminate significant redundancy]
### Priority 2: Capability Enhancements
2. [Changes that leverage unused features]
### Priority 3: Code Simplification
3. [Minor improvements and cleanup]
## Implementation Impact
- **Lines Removed**: ~X
- **Complexity Reduction**: [Qualitative assessment]
- **Maintainability**: [How this improves long-term maintenance]
```
## 🎯 Focus Areas
### Common Redundancy Patterns
1. **Datetime Operations**
- Check: Are we using `datetime.now()` instead of `utils.timezone_utils.utc_now()`?
- Check: Manual timezone conversions vs. utility functions
2. **Type Validation**
- Check: Manual `isinstance()` checks vs. Pydantic models
- Check: Custom validators vs. Pydantic's Field validators
3. **JSON Handling**
- Check: Manual `json.loads/dumps` vs. Pydantic's `.model_dump_json()`
- Check: Custom serializUse this agent when you need to rename classes, methods, functions, or variables in code files to align with specific naming requirements or conventions. Examples: <example>Context: User wants to clean up function names by removing a specific prefix. user: 'Please remove the prefix get_ from all function names in this file' assistant: 'I'll use the code-renamer agent to systematically rename all functions by removing the get_ prefix' <commentary>The user wants systematic renaming of functions, which is exactly what the code-renamer agent is designed for.</commentary></example> <example>Context: User wants to standardize method naming conventions. user: 'Can you rename all the camelCase methods to snake_case in this class?' assistant: 'I'll use the code-renamer agent to convert all camelCase method names to snake_case convention' <commentary>This is a systematic renaming task that requires careful attention to naming conventions.</commentary></example>
Use this agent when the user makes offhanded comments, rhetorical questions, or expresses wishes about understanding something better. Trigger on patterns like:\n\n<example>\nContext: User is reviewing code and sees an assistant's explanation about how a function works.\nuser: "Can you believe this? Is this even right?"\nassistant: "Let me use the investigative-sidekick agent to verify if that explanation is accurate."\n<task tool_call to investigative-sidekick with context about what needs verification>\n</example>\n\n<example>\nContext: User is debugging and expresses frustration.\nuser: "I wish I could figure out what's causing this memory leak in the session handler"\nassistant: "I'll use the investigative-sidekick agent to investigate the root cause of that memory leak."\n<task tool_call to investigative-sidekick with the specific problem to investigate>\n</example>\n\n<example>\nContext: User reads a commit message claiming a performance improvement.\nuser: "Did this actually make things faster though?"\nassistant: "Let me launch the investigative-sidekick agent to verify that performance claim."\n<task tool_call to investigative-sidekick to fact-check the performance assertion>\n</example>\n\n<example>\nContext: User is reviewing documentation that seems questionable.\nuser: "This doesn't seem right - are we really supposed to use sync calls in async contexts?"\nassistant: "I'm going to use the investigative-sidekick agent to investigate whether that's actually correct."\n<task tool_call to investigative-sidekick to verify the technical claim>\n</example>\n\nActivate proactively when the user:\n- Questions accuracy or truthfulness ("Can you believe...", "Is this right?", "Really?")\n- Expresses wishes about understanding ("I wish I could figure out...", "I'd love to know...")\n- Shows skepticism ("Did this actually...", "Does this really...")\n- Makes rhetorical questions that imply investigation ("What's causing...", "Why is this...")\n- Doubts explanations or documentation they're reading
Control thinking token limits via environment variable
Run complete two-agent validation on module+tests (contract extraction + test validation). Binary pass/fail with specific issues.
Check Python logging levels and patterns for correctness. Focus on identifying wrong severity levels and missing exception handling. Use when reviewing code quality.
Detect explicit user_id parameters in functions to identify potential opportunities for using ambient context. This is an investigation tool that flags instances for human review, not a prescriptive analyzer.
Eliminate component hedging anti-patterns that mask infrastructure failures. Build systems that fail loudly when broken instead of limping along in degraded states. Critical for production reliability and operational visibility.