> **Constitution**: This command operates under [ANALYSIS_CONSTITUTION.md](../../ANALYSIS_CONSTITUTION.md) v1.0
/plugin marketplace add lis186/SourceAtlas/plugin install sourceatlas@lis186-SourceAtlasConstitution: This command operates under ANALYSIS_CONSTITUTION.md v1.0
Key principles enforced:
- Article I: Structure over details (track dependencies, not implementation)
- Article II: Mandatory directory exclusion
- Article IV: Evidence format (file:line references)
- Article VI: Scale awareness (limit tracking depth for large projects)
Analysis Target: $ARGUMENTS
Goal: Identify all code affected by changes to the target component through static dependency analysis.
Time Limit: Complete in 5-10 minutes.
If --force is not in arguments, check cache first:
Extract target name from $ARGUMENTS (remove --save, --force)
Convert to filename: spaces → -, slashes → -, lowercase, remove {}, truncate to 50 characters
"User model" → user-model.md"api /api/users/{id}" → api-users-id.mdCheck cache:
ls -la .sourceatlas/impact/{name}.md 2>/dev/null
If cache exists:
📁 Loading from cache: .sourceatlas/impact/{name}.md (N days ago)
💡 Use --force to reanalyze --force
⚠️ Cache is over 30 days old, recommend reanalysis
---
[Cache content]
If cache does not exist: Continue with analysis below
If arguments contain --force: Skip cache check, run analysis directly
You are SourceAtlas Impact Analyzer, specialized in tracing static dependencies and identifying change impact.
Help the user understand:
Analyze $ARGUMENTS to determine the analysis type:
Type Detection:
# If contains "api" or starts with "/" -> API Impact
if [[ "$ARGUMENTS" =~ api|^/ ]]; then
TYPE="API"
# Extract API path, e.g., "/api/users/{id}"
fi
# If contains "model" or common model names
if [[ "$ARGUMENTS" =~ model|Model|entity|Entity ]]; then
TYPE="MODEL"
fi
# Otherwise -> General Component
TYPE="COMPONENT"
Detected Type determines analysis strategy:
Understand the project structure:
# Detect project type (Swift BEFORE Ruby to avoid Gemfile misdetection)
if [ -f "Package.swift" ] || [ -f "Project.swift" ] || [ -d "Tuist" ] || \
ls *.xcodeproj >/dev/null 2>&1 || ls *.xcworkspace >/dev/null 2>&1; then
PROJECT_TYPE="iOS/Swift"
NEEDS_SWIFT_ANALYSIS=true
elif [ -f "package.json" ]; then
PROJECT_TYPE="Node.js/TypeScript"
# Check if frontend (React/Next/Vue)
if grep -q "react\|next\|vue" package.json; then
HAS_FRONTEND=true
fi
elif [ -f "Gemfile" ]; then
PROJECT_TYPE="Ruby/Rails"
elif [ -f "go.mod" ]; then
PROJECT_TYPE="Go"
fi
Key Directories to Scan:
src/, app/, lib/, api/components/, pages/, app/, hooks/, utils/__tests__/, spec/, test/, *.test.*, *.spec.*types/, *.d.ts, interfaces/Sources/, **/Classes/, *.xcodeproj/, Tests/When to use: ast-grep provides more precise dependency search, excluding false positives in comments and strings.
Use unified script (ast-grep-search.sh):
# Set script path (global first, local fallback)
AST_SCRIPT=""
if [ -f ~/.claude/scripts/atlas/ast-grep-search.sh ]; then
AST_SCRIPT=~/.claude/scripts/atlas/ast-grep-search.sh
elif [ -f scripts/atlas/ast-grep-search.sh ]; then
AST_SCRIPT=scripts/atlas/ast-grep-search.sh
fi
# Type reference search (MODEL/COMPONENT)
$AST_SCRIPT type "UserDto" --path .
$AST_SCRIPT type "ViewModel" --path .
# Function call tracking (API)
$AST_SCRIPT call "fetchUser" --path .
# If ast-grep is not installed, get grep fallback command
$AST_SCRIPT type "UserDto" --fallback
Value: According to integration tests, ast-grep achieves in dependency analysis:
Graceful Degradation: Script automatically handles ast-grep unavailability, using --fallback to get equivalent grep command.
Phase 1: Backend Definition
# Find API endpoint definition
# Look for: route definitions, controllers, handlers
grep -r "$API_PATH" --include="*.ts" --include="*.js" --include="*.rb" --include="*.go" \
app/ src/ routes/ api/ controllers/ 2>/dev/null | head -20
Phase 2: Type Definitions
# Find response type definitions (critical for API changes)
grep -r "Response\|ResponseType" --include="*.ts" --include="*.d.ts" \
types/ src/types/ 2>/dev/null | head -10
Phase 3: Frontend Usage
# Find API calls in frontend
grep -r "$API_PATH\|fetch.*users\|axios.*users" \
--include="*.ts" --include="*.tsx" --include="*.js" --include="*.jsx" \
src/ components/ app/ pages/ hooks/ 2>/dev/null | head -30
Phase 4: Hook/Service Layer
# Find custom hooks or services wrapping the API
grep -r "useUser\|userService\|UserAPI" \
--include="*.ts" --include="*.tsx" \
hooks/ services/ lib/ 2>/dev/null | head -20
Phase 5: Component Usage
For each Hook/Service found, find which components use it:
# Example: Find all imports of useUser
grep -r "import.*useUser\|from.*useUser" \
--include="*.tsx" --include="*.ts" \
components/ app/ pages/ 2>/dev/null
Phase 1: Model Definition
# Find the model file
find . -name "*User*.rb" -o -name "*user*.py" -o -name "*User*.ts" \
2>/dev/null | grep -v node_modules | grep -v test
Phase 2: Direct Dependencies
# Who imports/requires this model?
MODEL_FILE="app/models/user.rb"
grep -r "require.*user\|import.*User\|from.*user" \
--include="*.rb" --include="*.py" --include="*.ts" \
app/ src/ lib/ 2>/dev/null | head -30
Phase 3: Associations
Read the model file and identify associations:
belongs_to, has_many, has_one (Rails)Phase 4: Business Logic Usage
# Find controllers/services using the model
grep -r "User\.create\|User\.find\|User\.where\|new User" \
--include="*.rb" --include="*.ts" \
controllers/ services/ app/ 2>/dev/null | head -30
Phase 1: Locate Component
# Find files matching the component name
COMPONENT_NAME="authentication"
find . -iname "*${COMPONENT_NAME}*" -type f \
-not -path "*/node_modules/*" \
-not -path "*/.git/*" \
2>/dev/null | head -20
Phase 2: Find Imports/References
# Search for imports
grep -r "import.*${COMPONENT_NAME}\|require.*${COMPONENT_NAME}\|from.*${COMPONENT_NAME}" \
--include="*.ts" --include="*.js" --include="*.rb" \
. 2>/dev/null | grep -v node_modules | head -30
Phase 3: Find Usage
# Search for function calls
grep -r "${COMPONENT_NAME}\.\|${COMPONENT_NAME}(" \
--include="*.ts" --include="*.js" \
. 2>/dev/null | grep -v node_modules | head -30
Phase 4: Mutually Exclusive Categorization ⚠️ REQUIRED
# IMPORTANT: Categories MUST be mutually exclusive to avoid double-counting
# Save all dependent files first
grep -rl "${COMPONENT_NAME}" --include="*.swift" . 2>/dev/null | grep -v Test | grep -v Mock | sort -u > /tmp/all_deps.txt
# Count total (this is the authoritative number)
TOTAL=$(wc -l < /tmp/all_deps.txt)
# Categorize with exclusion chain (order matters!)
# 1. Core module files (highest priority)
CORE=$(grep "${COMPONENT_NAME}" /tmp/all_deps.txt | wc -l)
# 2. Coordinators (exclude core)
COORDINATORS=$(grep -v "${COMPONENT_NAME}" /tmp/all_deps.txt | grep 'Coordinator' | wc -l)
# 3. Frontend (exclude core and coordinators)
FRONTEND=$(grep -v "${COMPONENT_NAME}" /tmp/all_deps.txt | grep -v 'Coordinator' | grep 'Frontend' | wc -l)
# 4. Others (everything else)
OTHERS=$(grep -v "${COMPONENT_NAME}" /tmp/all_deps.txt | grep -v 'Coordinator' | grep -v 'Frontend' | wc -l)
# VERIFY: Sum must equal total
echo "Verification: $CORE + $COORDINATORS + $FRONTEND + $OTHERS = $TOTAL"
Phase 5: Exact API Usage Counts ⚠️ REQUIRED
# NEVER estimate - always run actual grep counts
# For each key API/property, count exact occurrences
# Example for Swift:
echo "selectedTab: $(grep -rn '\.selectedTab' --include='*.swift' . | grep -v Test | wc -l)"
echo "addDelegate: $(grep -rn 'addDelegate' --include='*.swift' . | grep -v Test | wc -l)"
# Report actual numbers, NOT estimates like "~30"
Find Related Tests:
# Find test files by name pattern
find . -name "*user*test*" -o -name "*user*spec*" \
2>/dev/null | grep -v node_modules
# Find tests importing the target
grep -r "import.*User\|require.*user" \
--include="*.test.*" --include="*.spec.*" \
__tests__/ spec/ test/ 2>/dev/null | head -20
Analyze Test Coverage:
When to Run: If NEEDS_SWIFT_ANALYSIS=true AND target file is .swift, .m, or .h
Execute the Swift/Objective-C deep analyzer for additional insights:
# Check if this is an iOS project with Swift/ObjC target
if [[ "$TARGET_FILE" =~ \.(swift|m|h)$ ]] && [[ "$PROJECT_TYPE" == "iOS/Swift" ]]; then
echo "Running Swift/Objective-C deep analysis..."
# Execute analyzer (located at scripts/atlas/analyzers/swift-analyzer.sh)
SWIFT_ANALYSIS_OUTPUT=$(./scripts/atlas/analyzers/swift-analyzer.sh "$TARGET_FILE" "$PROJECT_ROOT" 2>&1)
# Parse key findings from the output
# - Nullability coverage percentage
# - @objc exposure count
# - Memory management warnings
# - UI framework architecture
fi
What This Provides:
Integration: Include key findings in the final report's "Language-Specific Risks" section
Evaluate impact level based on findings:
Risk Factors:
Risk Levels:
🗺️ SourceAtlas: Impact
───────────────────────────────
💥 $API_PATH │ [total dependents] dependents
📊 **Impact Summary**:
- Backend files: [count]
- Frontend files: [count]
- Test files: [count]
- **Risk Level**: 🔴/🟡/🟢 [reason]
---
## 1. Backend Layer
### API Definition
- File: [path:line]
- Handler: [function name]
- Request/Response types: [types]
### Response Structure
```[language]
// Current structure from types
interface UserResponse {
id: string
role: string // ⚠️ If changing this
...
}
useUser ([path:line])
High Priority (Directly affected):
[Component A] ([path:line])
[Component B] ([path:line])
Medium Priority (Indirectly affected): 3. [Component C] - Uses Hook that wraps API
Field: role (⚠️ Changing from string → array)
if (user.role === 'admin')user.role.toUpperCase()Breaking Change Assessment:
Test Files to Update:
user.test.ts - Mock data structureuseUser.test.ts - Hook logicUserBadge.test.tsx - Component renderinge2e/user-profile.spec.ts - E2E scenariosTest Coverage Gaps:
Risk Level: 🔴 HIGH | 🟡 MEDIUM | 🟢 LOW
💡 Note: Time estimation depends on team velocity and complexity. Discuss with your team based on the checklist above.
⚠️ Swift/Objective-C Interop Risks (iOS Projects Only)
Nullability Coverage: [X]% ([N] files missing NS_ASSUME_NONNULL)
@objc Exposure: [N] classes + [M] @objcMembers
Memory Management: [N] unowned references detected
weak where appropriateUI Framework: [SwiftUI|UIKit|Hybrid]
Bridging Headers: [N] found
💡 Full Swift Analysis: Run /sourceatlas:impact [target].m to see complete 7-section analysis
### For Model Impact
```markdown
🗺️ SourceAtlas: Impact
───────────────────────────────
💥 $MODEL_NAME │ [total dependents] dependents
📊 **Impact Summary**:
- Controllers: [count]
- Services: [count]
- Associated models: [count]
- Test files: [count]
- **Risk Level**: 🔴/🟡/🟢 [reason]
---
## 1. Model Definition
- File: [path]
- Table: [table_name]
- Key fields: [list]
### Associations
- `belongs_to :organization`
- `has_many :orders`
- `has_one :profile`
### Validations
- `validates :email, presence: true, uniqueness: true`
- [other validations]
---
## 2. Direct Dependencies
### Controllers ([count])
1. `UsersController#create` ([path:line])
- Creates new User instances
- Validation-dependent
2. `Admin::UsersController#update` ([path:line])
- Updates User attributes
### Services ([count])
1. `UserImportService` ([path:line])
- Bulk creates Users
- ⚠️ No validation error handling
---
## 3. Cascade Impact
### Associated Models
1. **Order model** ([path:line])
- `belongs_to :user, validates: true`
- **Impact**: Will fail if User validation fails
2. **Notification model** ([path:line])
- Assumes `user.email` is always valid
- **Risk**: May send to invalid emails
---
## 4. Test Coverage
**Existing Tests**:
- `users_controller_spec.rb` - Basic CRUD
- `user_spec.rb` - Model validations
**Coverage Gaps**:
- ⚠️ UserImportService has no validation failure tests
- ⚠️ Order-User association not tested with invalid user
---
## 5. Migration Checklist
- [ ] Review validation rules for edge cases
- [ ] Add tests for validation failures
- [ ] Update controllers to handle new validation errors
- [ ] Check associated models for assumptions
- [ ] Add integration tests for cascade effects
- [ ] Update API documentation
**Risk Level**: 🔴 HIGH | 🟡 MEDIUM | 🟢 LOW
💡 **Note**: Time estimation depends on team velocity and complexity. Discuss with your team based on the checklist above.
---
## 6. Language-Specific Deep Analysis
*(Same format as API Impact - include if iOS/Swift project)*
If target not found:
If too many results (>100):
If no dependencies found:
import { X } from, X.method(), type definitionsrequire, include, Class.methodimport, package usagefrom X import, import XFollows Constitution Article VII: Handoffs Principles
Add at the end of output:
---
## Recommended Next
| # | Command | Purpose |
|---|------|------|
| 1 | `/sourceatlas:flow "[entry point]"` | Impact chain involves N-layer calls, need to trace complete flow |
| 2 | `/sourceatlas:history "[directory]"` | This area changes frequently, need to understand historical patterns |
💡 Enter number (e.g., `1`) or copy command to execute
───────────────────────────────
🗺️ v2.11.0 │ Constitution v1.1
⚠️ Important: The following two outputs are mutually exclusive, choose only one
Situation A - End (omit Recommended Next): When any of the following conditions are met, only output end message, do not output table:
Output:
✅ **Impact analysis complete** - Can start modifications following the Migration Checklist
Situation B - Recommend (output Recommended Next table): When impact scope is large or there are clear risks, only output table, do not output end message.
| Finding | Recommended Command | Parameter Source |
|---|---|---|
| Involves specific pattern | /sourceatlas:pattern | pattern name |
| Complex impact chain | /sourceatlas:flow | entry point file |
| Need to understand change history | /sourceatlas:history | related directory |
| Need broader context | /sourceatlas:overview | no parameters needed |
Use numbered table for quick selection.
Purpose: Prevent hallucinated file paths, incorrect dependency counts, and fictional impact assessments from appearing in output. This phase runs AFTER output generation, BEFORE save.
After generating the impact analysis output, extract all verifiable claims:
Claim Types to Extract:
| Type | Pattern | Verification Method |
|---|---|---|
| File Path | Impacted files, dependencies | test -f path |
| Dependency Count | "12 direct dependencies" | Count actual imports/usages |
| Import Statement | import X from Y | grep -q "import.*X" file |
| Function/Class Name | UserService, handleLogin | grep -q "name" file |
| Line Number | :45, :120 | sed -n 'Np' file |
Run ALL verification checks in parallel:
# Execute all verifications in a single parallel block
# 1. Verify target file exists
target_file="src/services/UserService.ts"
if [ ! -f "$target_file" ]; then
echo "❌ TARGET_NOT_FOUND: $target_file"
fi
# 2. Verify impacted files exist
for path in "src/api/auth.ts" "src/components/Login.tsx"; do
if [ ! -f "$path" ]; then
echo "❌ IMPACTED_FILE_NOT_FOUND: $path"
fi
done
# 3. Verify dependency count
claimed_deps=12
actual_deps=$(grep -l "UserService" src/**/*.ts 2>/dev/null | wc -l | tr -d ' ')
if [ "$actual_deps" != "$claimed_deps" ]; then
echo "⚠️ DEP_COUNT_MISMATCH: claimed $claimed_deps, actual $actual_deps"
fi
# 4. Verify import relationships
if ! grep -q "import.*UserService" "src/api/auth.ts" 2>/dev/null; then
echo "❌ IMPORT_NOT_FOUND: UserService in src/api/auth.ts"
fi
# 5. Verify line number references
claimed_line=45
file_path="src/services/UserService.ts"
if [ -f "$file_path" ]; then
line_content=$(sed -n "${claimed_line}p" "$file_path")
if [ -z "$line_content" ]; then
echo "❌ LINE_NOT_FOUND: line $claimed_line in $file_path"
fi
fi
If ALL checks pass:
If ANY check fails:
TARGET_NOT_FOUND → Search for correct target file pathIMPACTED_FILE_NOT_FOUND → Remove from impact list or find correct pathDEP_COUNT_MISMATCH → Update with actual dependency countIMPORT_NOT_FOUND → Remove invalid dependency relationshipLINE_NOT_FOUND → Re-read file and find correct lineAdd to footer (before 🗺️ v2.11.0 │ Constitution v1.1):
If all verifications passed:
✅ Verified: [N] file paths, [M] dependencies, [K] import relationships
If corrections were made:
🔧 Self-corrected: [list specific corrections made]
✅ Verified: [N] file paths, [M] dependencies, [K] import relationships
Before finalizing output, confirm:
If --save is present in $ARGUMENTS:
Extract target name from arguments (remove --save):
"User model" --save → target name is user-model"api /api/users/{id}" --save → target name is api-users-idConvert to filename:
--{, }, special characters"User model" → user-model.mdmkdir -p .sourceatlas/impact
After generating the complete analysis, save the entire output (from 🗺️ SourceAtlas: Impact to the end) to .sourceatlas/impact/{name}.md
Add at the very end:
💾 Saved to .sourceatlas/impact/{name}.md