
sourceatlas
AI-powered codebase understanding assistant. Learn design patterns, analyze impact, trace code flows, and understand any codebase through information theory principles.
- version
- 2.13.1
- GitHub stars
- 49
Install
/plugin install sourceatlas@lis186-SourceAtlasRun it inside Claude Code after adding the marketplace with /plugin marketplace add lis186/SourceAtlas.
Contents
Discovered from sourceSkills 6
Code Flow Tracer
When to Use
Trigger this skill when the user:
- Wants to understand how a feature works end-to-end
- Asks what happens when an action is triggered
- Needs to trace data flow through the system
- Asks "how does X work"
- Asks "what calls X" or "what does X call"
Instructions
- Identify the feature, function, or flow the user wants to trace
- Run
/sourceatlas:flow "<query>"with a natural language description - Returns call graph, boundary detection, and flow visualization
Query Formats
- Feature flow:
/sourceatlas:flow "user login" - Function trace:
/sourceatlas:flow "handleSubmit" - Error paths:
/sourceatlas:flow "error handling flow" - Data origin:
/sourceatlas:flow "where does userProfile come from" - Reverse trace:
/sourceatlas:flow "who calls validateToken"
What User Gets
- Call graph visualization (ASCII tree)
- Boundary detection (API, DB, LIB, CLOUD markers)
- Recursion and cycle detection
- Entry points identification
- 11 analysis modes available
Example Triggers
- "How does the login flow work?"
- "What happens when user clicks submit?"
- "Trace the checkout process"
- "Where does this data come from?"
- "Who calls this function?"
Codebase Overview
When to Use
Trigger this skill when the user:
- Asks about project structure or architecture
- Is new to a codebase and needs orientation
- Wants to understand tech stack or patterns used
- Asks "what is this project about"
- Asks "how is this organized"
Instructions
- Run
/sourceatlas:overviewto analyze the codebase - This scans <5% of high-entropy files (configs, READMEs, models)
- Returns project fingerprint, architecture hypotheses, and AI collaboration level
What User Gets
- Project type and scale
- Tech stack identification
- Architecture patterns with confidence levels
- Code quality signals
- Recommended next steps
Example Triggers
- "I just joined this project, where do I start?"
- "What's the architecture of this codebase?"
- "Give me an overview of this project"
- "What tech stack does this use?"
Dependency Analyzer
When to Use
Trigger this skill when the user:
- Is planning a framework or SDK upgrade
- Wants to know migration effort for version changes
- Asks about deprecated APIs or breaking changes
- Needs to audit usage of a specific library
- Asks "how much work to upgrade X"
Instructions
- Identify the upgrade path or library to analyze
- Run
/sourceatlas:deps "<upgrade>"with the migration description - Returns deprecated APIs, breaking changes, and migration checklist
Command Formats
- iOS upgrade:
/sourceatlas:deps "iOS 16 → 17" - Android:
/sourceatlas:deps "Android API 35" - React:
/sourceatlas:deps "React 17 → 18" - Python:
/sourceatlas:deps "Python 3.11 → 3.12" - Library audit:
/sourceatlas:deps "kotlinx.coroutines"
What User Gets
- Phase 0 Rule Confirmation (preview before scanning)
- Required Changes: Removable checks, deprecated APIs
- Modernization Opportunities: New features available
- Usage Summary: All API usage with file:line references
- Third-party compatibility
- Migration Checklist with effort estimates
Example Triggers
- "We need to upgrade to iOS 17, how much work?"
- "What breaks if we upgrade React to 18?"
- "Plan the Python 3.12 migration"
- "Check our usage of AFNetworking"
- "How hard is the Swift 6 migration?"
History Analyzer
When to Use
Trigger this skill when the user:
- Wants to find code hotspots (frequently changed files)
- Needs to identify who knows specific code areas
- Asks about bus factor or knowledge distribution
- Wants to find hidden coupling between files
- Asks "who should I ask about X"
Instructions
- Run
/sourceatlas:historyfor the entire repo, or/sourceatlas:history <path>for specific directory - Optionally specify time range:
/sourceatlas:history . 6for last 6 months - Returns hotspots, coupling analysis, and contributor distribution
Command Formats
- Full repo:
/sourceatlas:history - Specific directory:
/sourceatlas:history src/ - With time range:
/sourceatlas:history . 6(last 6 months)
What User Gets
- Hotspots: Files with most changes (complexity indicators)
- Temporal Coupling: Files that always change together (hidden dependencies)
- Recent Contributors: Who knows what areas
- Bus Factor Risk: Single-contributor files
- Priority actions for refactoring
Example Triggers
- "What are the hotspots in this codebase?"
- "Who knows the payment module best?"
- "What files always change together?"
- "Is there any bus factor risk?"
- "Show me knowledge distribution"
Impact Analyzer
When to Use
Trigger this skill when the user:
- Is about to modify code and wants to know the impact
- Asks what depends on a file or component
- Wants to understand breaking change risks
- Asks "what will break if I change X"
- Asks "is it safe to modify this"
Instructions
- Identify the file, component, or API the user wants to change
- Run
/sourceatlas:impact "<target>"with the target - Returns dependency analysis, risk assessment, and migration checklist
Target Formats
- File path:
/sourceatlas:impact "src/api/users.ts" - API endpoint:
/sourceatlas:impact "api /api/users/{id}" - Component:
/sourceatlas:impact "UserService" - Model:
/sourceatlas:impact "User model"
What User Gets
- Impact summary (backend, frontend, test files affected)
- Risk level assessment (red/yellow/green)
- Breaking change risks
- Migration checklist
- Test coverage gaps
Example Triggers
- "What happens if I change this file?"
- "What depends on UserService?"
- "Is it safe to modify the authentication module?"
- "Impact of changing the User model"
Pattern Finder
When to Use
Trigger this skill when the user:
- Asks how to implement a specific feature
- Wants to see existing implementation examples
- Needs to follow project conventions
- Asks "how does this project do X"
- Asks "show me examples of X"
Instructions
- Identify what pattern the user is looking for
- Run
/sourceatlas:pattern "<pattern>"with the relevant pattern name - Returns best example files with line numbers and implementation guide
Common Patterns
- API endpoints:
/sourceatlas:pattern "api endpoint" - Authentication:
/sourceatlas:pattern "authentication" - Database queries:
/sourceatlas:pattern "database query" - Background jobs:
/sourceatlas:pattern "background job" - File uploads:
/sourceatlas:pattern "file upload" - Error handling:
/sourceatlas:pattern "error handling" - Validation:
/sourceatlas:pattern "validation" - Testing:
/sourceatlas:pattern "unit test"
What User Gets
- Best example files with exact line numbers
- Standard implementation flow
- Key conventions to follow
- Common pitfalls to avoid
- Testing patterns
Example Triggers
- "How do I add a new API endpoint?"
- "Show me how authentication works here"
- "Where can I find examples of database queries?"
- "How does this project handle errors?"
Commands 28
SourceAtlas: Dependencies
Constitution: ANALYSIS_CONSTITUTION.md v1.1
Context
Target: $ARGUMENTS (library name, version upgrade, or iOS minimum version) Goal: Analyze dependency usage and provide upgrade guidance Time Limit: 5-15 minutes
Quick Start
- Check cache (skip if
--forceflag present) - Detect version from manifest files (package.json, Podfile, etc.)
- Search for upgrade rules using WebSearch (if version upgrade)
- Find all usage points using grep/Glob
- Categorize usage by API type
- Generate YAML report following output-template.md
- Verify output using verification-guide.md
- Auto-save to
.sourceatlas/deps/
Your Task
You are analyzing dependency usage to help users understand:
- Current state: Which version is installed, where it's used
- Upgrade impact: What needs to change for version upgrades
- Migration path: Step-by-step upgrade checklist
- Risk assessment: How complex is the upgrade
Upgrade Types You Handle
| Input Pattern | Type | Focus |
|---|---|---|
iOS 17, iOS 16 → 17 | iOS Minimum Version Upgrade | Removable #available, deprecated APIs, new opportunities |
iOS SDK 26, Xcode 16 | SDK/Compiler Upgrade | Compilation warnings, Swift version, new syntax |
react 17 → 18, pandas 1.x → 2.x | Major Version Upgrade | Breaking changes, deprecated APIs, new patterns |
react, pandas (no version) | Usage Inventory | List usage points only |
Core Workflow
Execute these phases in order. See workflow.md for complete details.
Phase 0: Rule Confirmation (1-2 minutes)
Purpose: Identify upgrade type and confirm analysis rules with user before proceeding.
Steps:
- Detect upgrade type from
$ARGUMENTS - Generate rules preview (what to check, where to search)
- Use
AskUserQuestionto confirm rules
→ See workflow.md#phase-0
Phase 1: Detect Current Version (1 minute)
Purpose: Find current dependency version from manifest files.
Manifest files by ecosystem:
- Node.js:
package.json,package-lock.json - iOS:
Podfile,Package.swift - Android:
build.gradle,build.gradle.kts
→ See workflow.md#phase-1
Phase 2: Search for Upgrade Guide (2-3 minutes)
Purpose: Find official migration guide using WebSearch.
Search for:
- Official migration guide
- Official changelog
- Community upgrade guides
- GitHub release notes
→ See workflow.md#phase-2
Phase 3: Find All Usage Points (3-5 minutes)
Purpose: Locate every place the dependency is used.
Search patterns:
- JavaScript/TypeScript:
importstatements, API calls - Swift/iOS:
importstatements,#availablechecks - Android/Kotlin:
importstatements, API level checks
→ See workflow.md#phase-3
Phase 4: Categorize API Usage (2-3 minutes)
Purpose: Group usage by category and match against upgrade rules.
Categories:
- Hooks (React), Components, Utilities (JavaScript)
- Frameworks, APIs (iOS/Android)
- Availability checks (iOS)
- Deprecated APIs (all platforms)
→ See workflow.md#phase-4
Phase 5: Generate Analysis Report
Purpose: Output complete YAML analysis following template.
→ See output-template.md for complete format
Output Format
Your analysis should follow this YAML structure:
dependency_analysis:
target: "${ARGUMENTS}"
type: "[library|sdk|framework|runtime]"
analysis_time: "[ISO 8601 timestamp]"
constitution_version: "1.1"
version_info:
current: "[detected version]"
source: "[manifest file]"
target: "[target version if upgrade]"
rules_applied:
source: "[built-in|web_search|user_provided]"
rule_count: [number]
# Required changes for upgrade
required_changes:
removable_availability_checks: [...]
deprecated_api_usages: [...]
breaking_change_impacts: [...]
# Optional modernization opportunities
modernization_opportunities:
items: [...]
# Complete usage inventory
usage_inventory:
total_files: [number]
total_usage_points: [number]
by_category: [...]
# Step-by-step migration guide
migration_checklist:
estimated_effort: "[low|medium|high]"
recommended_approach: "[description]"
steps: [...]
# Risk evaluation
risk_assessment:
overall_risk: "[🟢 low|🟡 medium|🔴 high]"
factors: [...]
recommendations: [...]
→ See output-template.md for complete specification and examples
Critical Rules
1. Rule Confirmation Required
- Always use
AskUserQuestionin Phase 0 to confirm rules before full analysis - Show user what you plan to check (availability patterns, deprecated APIs, etc.)
- Get explicit approval before proceeding to Phase 1-5
2. Version Detection Must Be Accurate
- Always grep manifest files for current version
- Use lock files (package-lock.json, Podfile.lock) for actual installed version
- Never guess or estimate version numbers
3. Evidence-Based Analysis Only
- Every usage point must have
file:linereference - All counts must be verifiable via grep
- No assumptions about code you haven't seen
4. Upgrade Guide Source Transparency
rules_applied:
source: "web_search" # Or "built-in" if no guide found
rule_count: 12
- Always disclose where upgrade rules came from
- Prefer official docs over community guides
- Note limitations if no official guide found
5. Verification Required Before Output
- Execute verification-guide.md after generating analysis
- Verify version numbers, file paths, usage counts
- Correct any discrepancies before final output
6. Constitutional Compliance
Follow ANALYSIS_CONSTITUTION.md:
- Article I: Evidence-based (all claims reference actual code)
- Article III: Verification (run V1-V4 checks)
- Article V: Transparency (show cache age, source, limitations)
- Article VII: User Empowerment (actionable checklist, effort estimates)
Self-Verification
After generating your analysis, execute verification steps:
Step V1: Extract Verifiable Claims
Parse output for all quantifiable claims (counts, versions, file paths)
Step V2: Parallel Verification
- Verify version detection
- Verify API usage counts (±5% tolerance)
- Verify file paths (sample 3-5 files)
- Verify upgrade guide quality
Step V3: Handle Results
- ✅ All checks pass → Proceed to output
- ⚠️ Minor issues (1-2 checks) → Correct and note
- ❌ Major issues (3+ checks) → Re-execute analysis
Step V4: Add Verification Summary
verification_summary:
checks_performed: [...]
confidence_level: "high" # high|medium|low
notes: [...]
→ See verification-guide.md for complete checklist
Advanced
Cache Behavior
- Default: Use cache if exists and fresh
- Force flag: Skip cache with
--force - Cache location:
.sourceatlas/deps/${SANITIZED_TARGET}.md
→ See reference.md#cache-behavior
Auto-Save Mechanism
Complete YAML report auto-saves after verification:
💾 Saved to .sourceatlas/deps/react-17-18.md
→ See reference.md#auto-save-behavior
Handoffs to Next Commands
After analysis, suggest appropriate next steps based on risk level.
→ See reference.md#handoffs
Language-Specific Tips
- JavaScript/TypeScript: Include all variants (.js, .jsx, .ts, .tsx)
- Swift/iOS: Exclude Pods directory, check
#availablepatterns - Android/Kotlin: Check compileSdk, minSdk, targetSdk
→ See reference.md#language-specific-best-practices
Support Files
Detailed documentation available in:
- workflow.md - Complete Phase 0-5 execution guide with bash commands and examples
- output-template.md - Full YAML structure, field descriptions, and examples
- verification-guide.md - Self-verification steps V1-V4 with verification scripts
- reference.md - Cache behavior, auto-save, handoffs, language-specific tips
Output Header
Start your output with:
🗺️ SourceAtlas: Dependencies
───────────────────────────────
📦 [target] │ [N] APIs found
Then output complete YAML following output-template.md.
Dependency Analysis Output Template
Complete YAML format specification for dependency upgrade analysis.
Header Format
🗺️ SourceAtlas: Dependencies
───────────────────────────────
📦 [target] │ [N] APIs found
YAML Output Structure
dependency_analysis:
target: "${ARGUMENTS}"
type: "[library|sdk|framework|runtime]"
analysis_time: "[ISO 8601 timestamp]"
constitution_version: "1.1"
version_info:
current: "[detected version or 'unknown']"
source: "[package.json|Podfile|build.gradle|etc.]"
target: "[target version if upgrade]"
rules_applied:
source: "[built-in|web_search|user_provided]"
rule_count: [number]
# ============================================
# SECTION 1: Removable/Modifiable Code (Required for Upgrade)
# ============================================
required_changes:
removable_availability_checks:
description: "Version checks that can be removed after upgrade"
total: [number]
items:
- file: "[path:line]"
code: "[#available(...)]"
action: "Can be removed"
deprecated_api_usages:
description: "Code using deprecated APIs"
total: [number]
items:
- file: "[path:line]"
api: "[deprecated API]"
replacement: "[new API]"
migration_effort: "[low|medium|high]"
breaking_change_impacts:
description: "Code affected by breaking changes"
total: [number]
items:
- file: "[path:line]"
change: "[breaking change description]"
action: "[required action]"
# ============================================
# SECTION 2: Modernization Opportunities (Optional for Upgrade)
# ============================================
modernization_opportunities:
description: "New APIs/Patterns available after upgrade"
items:
- category: "[e.g., Observation Framework]"
current_pattern: "[e.g., ObservableObject + @Published]"
new_pattern: "[e.g., @Observable]"
affected_files: [number]
benefit: "[e.g., Reduce boilerplate code]"
effort: "[low|medium|high]"
files:
- "[path:line]"
# ============================================
# SECTION 3: Usage Inventory
# ============================================
usage_inventory:
total_files: [number]
total_usage_points: [number]
by_category:
hooks: # For React
- name: "useState"
count: [number]
files:
- "[path:line]"
components: # For React/Vue
- name: "Button"
count: [number]
files:
- "[path:line]"
utilities:
- name: "formatDate"
count: [number]
files:
- "[path:line]"
# ============================================
# SECTION 4: Migration Checklist
# ============================================
migration_checklist:
estimated_effort: "[low|medium|high]"
recommended_approach: "[description]"
steps:
- step: 1
action: "[e.g., Update package.json]"
command: "[e.g., npm install react@18]"
- step: 2
action: "[e.g., Remove [N] availability checks]"
files_affected: [number]
- step: 3
action: "[e.g., Update [N] deprecated API usages]"
files_affected: [number]
- step: 4
action: "[e.g., Test all affected areas]"
areas: ["[area1]", "[area2]"]
# ============================================
# SECTION 5: Risk Assessment
# ============================================
risk_assessment:
overall_risk: "[🟢 low|🟡 medium|🔴 high]"
factors:
breaking_changes: "[none|minor|major]"
usage_breadth: "[isolated|moderate|widespread]"
test_coverage: "[good|partial|poor]"
migration_guide_quality: "[excellent|good|poor|missing]"
recommendations:
- "[Recommendation 1]"
- "[Recommendation 2]"
Example: React Upgrade
dependency_analysis:
target: "react 17 → 18"
type: "library"
analysis_time: "2026-01-13T15:30:00Z"
constitution_version: "1.1"
version_info:
current: "17.0.2"
source: "package.json"
target: "18.2.0"
rules_applied:
source: "web_search"
rule_count: 12
required_changes:
deprecated_api_usages:
description: "Code using deprecated APIs"
total: 3
items:
- file: "src/components/Header.tsx:45"
api: "ReactDOM.render()"
replacement: "ReactDOM.createRoot()"
migration_effort: "medium"
- file: "src/App.tsx:12"
api: "unstable_batchedUpdates"
replacement: "Automatic batching (remove)"
migration_effort: "low"
modernization_opportunities:
items:
- category: "Automatic Batching"
current_pattern: "Manual batching with unstable_batchedUpdates"
new_pattern: "Automatic batching (built-in)"
affected_files: 8
benefit: "Reduced boilerplate, better performance"
effort: "low"
files:
- "src/hooks/useAuth.ts:34"
- "src/utils/state.ts:67"
usage_inventory:
total_files: 145
total_usage_points: 487
by_category:
hooks:
- name: "useState"
count: 89
files:
- "src/components/UserProfile.tsx:23"
- "src/hooks/useForm.ts:12"
components:
- name: "Suspense"
count: 12
files:
- "src/App.tsx:45"
migration_checklist:
estimated_effort: "medium"
recommended_approach: "Incremental migration - update root first, then components"
steps:
- step: 1
action: "Update package.json"
command: "npm install react@18 react-dom@18"
- step: 2
action: "Update root rendering"
files_affected: 1
- step: 3
action: "Remove 3 deprecated API usages"
files_affected: 3
- step: 4
action: "Test all components for automatic batching"
areas: ["forms", "auth", "data-fetching"]
risk_assessment:
overall_risk: "🟡 medium"
factors:
breaking_changes: "minor"
usage_breadth: "widespread"
test_coverage: "good"
migration_guide_quality: "excellent"
recommendations:
- "Update tests to use createRoot API"
- "Review automatic batching behavior in forms"
- "Consider adopting new Suspense features"
Example: iOS Minimum Version Upgrade
dependency_analysis:
target: "iOS 15 → 17"
type: "runtime"
analysis_time: "2026-01-13T16:00:00Z"
constitution_version: "1.1"
version_info:
current: "iOS 15.0"
source: "Project.swift"
target: "iOS 17.0"
required_changes:
removable_availability_checks:
description: "Version checks that can be removed"
total: 23
items:
- file: "Sources/UI/ProfileView.swift:45"
code: "if #available(iOS 15.0, *)"
action: "Can be removed - always true on iOS 17+"
- file: "Sources/UI/SettingsView.swift:89"
code: "if #available(iOS 16.0, *)"
action: "Can be removed - always true on iOS 17+"
deprecated_api_usages:
total: 0
items: []
modernization_opportunities:
items:
- category: "Observation Framework"
current_pattern: "ObservableObject + @Published"
new_pattern: "@Observable"
affected_files: 34
benefit: "Simpler syntax, better performance"
effort: "medium"
files:
- "Sources/ViewModels/UserViewModel.swift:12"
migration_checklist:
estimated_effort: "low"
recommended_approach: "Remove availability checks, consider modernization"
steps:
- step: 1
action: "Update minimum deployment target"
command: "Update Project.swift: deploymentTarget: .iOS('17.0')"
- step: 2
action: "Remove 23 availability checks"
files_affected: 15
- step: 3
action: "Test on iOS 17 simulator"
areas: ["all"]
risk_assessment:
overall_risk: "🟢 low"
factors:
breaking_changes: "none"
usage_breadth: "moderate"
test_coverage: "good"
migration_guide_quality: "good"
recommendations:
- "Safe upgrade - mostly code cleanup"
- "Consider adopting @Observable for new code"
Field Descriptions
dependency_analysis
- target: Original ${ARGUMENTS} from user
- type: library/sdk/framework/runtime
- analysis_time: ISO 8601 timestamp
- constitution_version: Current Constitution version
version_info
- current: Detected from manifest file
- source: Which file provided version info
- target: Target version for upgrade
required_changes
Changes that MUST be done for successful upgrade:
- removable_availability_checks: Version checks that are now redundant
- deprecated_api_usages: APIs that will be removed
- breaking_change_impacts: Behavior changes
modernization_opportunities
Optional improvements using new features:
- category: Type of opportunity
- current_pattern: How it's done now
- new_pattern: Modern approach
- benefit: Why it's better
- effort: Migration complexity
usage_inventory
Complete list of API usage:
- by_category: Grouped by type (hooks, components, utilities)
- Each entry includes count and file locations
migration_checklist
Step-by-step upgrade guide:
- estimated_effort: Overall complexity
- recommended_approach: Strategy description
- steps: Ordered actions with commands
risk_assessment
Risk evaluation:
- overall_risk: 🟢 low / 🟡 medium / 🔴 high
- factors: Contributing risk elements
- recommendations: Specific advice
Dependency Analysis Reference
Advanced features, caching behavior, and best practices.
Cache Behavior
When Cache is Used
# Default: Use cache if exists and fresh
/sourceatlas:deps "react"
# Check logic:
if [ -f ".sourceatlas/deps/${SANITIZED_TARGET}.md" ]; then
age_days=$(calculate_age_in_days)
if [ $age_days -eq 0 ]; then
echo "📁 Loading from cache (today)"
elif [ $age_days -eq 1 ]; then
echo "📁 Loading from cache (1 day ago)"
else
echo "📁 Loading from cache ($age_days days ago)"
fi
# Output cached content
exit 0
fi
When Cache is Skipped
# Force flag: Always skip cache
/sourceatlas:deps "react" --force
# → Executes full analysis even if cache exists
# No cache: First time analysis
# → .sourceatlas/deps/ doesn't exist yet
Cache File Naming
# Target sanitization rules:
"react 17 → 18" → "react-17-18.md"
"iOS 16" → "ios-16.md"
"lodash" → "lodash.md"
"@types/node" → "types-node.md"
# Pattern: lowercase, alphanumeric + hyphens only
sanitized=$(echo "$ARGUMENTS" | tr '[:upper:]' '[:lower:]' | \
sed 's/[^a-z0-9]/-/g' | sed 's/--*/-/g' | \
sed 's/^-//' | sed 's/-$//')
Auto-Save Behavior
File Structure
.sourceatlas/deps/
├── react-17-18.md # Analysis for "react 17 → 18"
├── ios-16-17.md # Analysis for "iOS 16 → 17"
├── lodash.md # Analysis for "lodash"
└── pandas-1x-2x.md # Analysis for "pandas 1.x → 2.x"
Save Timing
Auto-save occurs immediately after Step V4 verification:
# After verification passes
verification_summary:
confidence_level: "high"
# Then auto-save
💾 Saved to .sourceatlas/deps/react-17-18.md
What Gets Saved
Complete YAML output including:
- dependency_analysis header
- version_info
- rules_applied
- required_changes (all items)
- modernization_opportunities
- usage_inventory (by_category)
- migration_checklist
- risk_assessment
- verification_summary
Format: Full YAML as specified in output-template.md
Handoffs: When to Suggest Next Commands
After Usage Inventory (No Upgrade)
If user only asked for usage analysis without version upgrade:
usage_inventory:
total_files: 45
total_usage_points: 123
Suggest:
✨ Next steps:
- /sourceatlas:impact "src/hooks/useAuth.ts" - See impact of changing this hook
- /sourceatlas:pattern "react hooks" - Learn project's hook patterns
After Upgrade Analysis (Low Risk)
risk_assessment:
overall_risk: "🟢 low"
Suggest:
✨ Next steps:
- Update package.json and run tests
- /sourceatlas:impact - Check impact after upgrade
After Upgrade Analysis (Medium/High Risk)
risk_assessment:
overall_risk: "🟡 medium"
Suggest:
⚠️ Recommended actions:
1. Review all deprecated API usages carefully
2. Create a feature branch for testing
3. /sourceatlas:impact "ComponentX" - Analyze high-risk components first
If WebSearch/WebFetch Failed
rules_applied:
source: "built-in" # Fallback to built-in rules
Suggest:
⚠️ Could not find official migration guide
Please manually review:
- ${LIBRARY} official changelog
- Breaking changes documentation
Language-Specific Best Practices
JavaScript/TypeScript (Node.js)
Manifest Files:
package.json- Primary sourcepackage-lock.json- Actual installed versionsyarn.lockorpnpm-lock.yaml- Alternative lock files
Search Tips:
# Include all JS/TS variants
--include="*.js" --include="*.jsx" --include="*.ts" --include="*.tsx"
# Exclude common directories
grep -v "node_modules\|dist\|build\|.next"
# Monorepo: Check workspace packages
grep -r "\"workspaces\"" package.json
Common Upgrade Patterns:
- Major versions (e.g., React 17 → 18) → Focus on breaking changes
- Minor versions (e.g., Next.js 13.4 → 13.5) → Focus on new features
- Patch versions → Usually safe, check security fixes
Swift/iOS
Manifest Files:
Podfile- CocoaPods dependenciesPackage.swift- Swift Package ManagerCartfile- Carthage dependencies- Project settings (
.xcodeproj) - iOS deployment target
Search Tips:
# Availability checks
grep -rn "#available(iOS" --include="*.swift" . | grep -v Pods
# Framework imports
grep -rn "^import UIKit\|^import SwiftUI" --include="*.swift" .
# Deprecated APIs
grep -rn "@available(*, deprecated" --include="*.swift" .
iOS Version Upgrades:
- iOS 15 → 17: Focus on removable
#availablechecks - iOS 17+: Consider new APIs like
@Observable,Observation - Check Swift version compatibility
Android/Kotlin
Manifest Files:
build.gradleorbuild.gradle.kts- Main configsettings.gradle- Project structuregradle.properties- SDK versions
Search Tips:
# API level checks
grep -rn "Build.VERSION.SDK_INT" --include="*.kt" --include="*.java" .
# Dependency versions
grep "implementation\|api\|compileOnly" build.gradle
WebSearch Strategy
Query Templates
For major version upgrades:
"${LIBRARY} ${FROM_VERSION} to ${TO_VERSION} migration guide"
"${LIBRARY} ${TO_VERSION} breaking changes"
"${LIBRARY} changelog ${TO_VERSION}"
For iOS/Android SDK:
"iOS ${TO_VERSION} migration guide"
"Android API ${TO_VERSION} migration"
"What's new in iOS ${TO_VERSION}"
Source Priority
-
Official docs (highest priority)
- Library's official website
- GitHub releases page
- Official migration guides
-
Semi-official (high priority)
- Framework maintainer blog posts
- Official YouTube channels
- Conference talks
-
Community (medium priority)
- Dev.to, Medium articles by core contributors
- Stack Overflow highly-voted questions
- GitHub discussions
-
Avoid (low priority)
- Random blogs without verification
- Outdated tutorials
- AI-generated content without sources
Edge Cases
Case 1: Dependency Not Found in Manifest
version_info:
current: "unknown"
source: "not found in manifest files"
Possible reasons:
- Transitive dependency (not directly listed)
- Different package name
- Bundled in framework
Action:
- Search for import/require statements
- Check lock files for transitive deps
- Ask user to clarify package name
Case 2: Multiple Versions Detected
# package.json shows 17.0.2
# package-lock.json shows 17.0.1
Action:
version_info:
current: "17.0.1" # Use lock file version
source: "package-lock.json (installed)"
note: "package.json specifies ^17.0.2"
Case 3: Monorepo with Multiple Packages
# Root package.json: "react": "17.0.2"
# packages/app-a/package.json: "react": "16.8.0"
Action:
-
Clarify scope with user:
⚠️ Multiple versions detected: - Root: 17.0.2 - packages/app-a: 16.8.0 Analyzing root package by default. Use `/sourceatlas:deps "react" --scope=app-a` to analyze specific package. -
Analyze specified scope only
Case 4: No Upgrade Guide Found
rules_applied:
source: "built-in"
rule_count: 0
Action:
- Report usage statistics only
- Skip breaking changes analysis
- Recommend manual changelog review:
⚠️ Could not find migration guide for ${LIBRARY}
Provided usage inventory only. Please manually review:
- ${LIBRARY} official changelog
- GitHub releases: https://github.com/${ORG}/${REPO}/releases
Performance Optimization
For Large Codebases
# Limit grep results to prevent timeout
grep -r "pattern" --include="*.js" . | head -100
# Use --max-count for early exit
grep -r --max-count=50 "pattern" .
# Parallel search for multiple patterns
grep -r "pattern1" . & grep -r "pattern2" . & wait
For Monorepos
# Skip non-source directories
grep -r "pattern" . \
--exclude-dir="node_modules" \
--exclude-dir="dist" \
--exclude-dir="build" \
--exclude-dir=".next" \
--exclude-dir="coverage"
Troubleshooting
Issue: Version Detection Failed
Symptom: current: "unknown"
Debug:
# Check manifest file exists
ls -la package.json Podfile build.gradle
# Verify file format
cat package.json | python -m json.tool
# Search more broadly
grep -i "version" package.json
Issue: No Usage Points Found
Symptom: total_usage_points: 0
Debug:
# Verify library name
echo "Searching for: ${LIBRARY}"
# Try broader pattern
grep -r "${LIBRARY}" . | head -20
# Check file extensions
find . -name "*.js" -o -name "*.ts" | head -10
Issue: WebSearch Returns Irrelevant Results
Symptom: Migration guide for wrong version
Action:
- Add version number to query:
"react 18.0.0 migration"(not just "react 18") - Add "official" keyword:
"official react 18 migration guide" - Use site-specific search:
"site:reactjs.org migration guide"
Constitutional Compliance
Article I: Evidence-Based Analysis
- ✅ Every claim must reference actual files
- ✅ Version numbers from manifest files only
- ✅ Usage counts from verified grep results
Article III: Verification Required
- ✅ Execute verification-guide.md before output
- ✅ Re-verify after corrections
Article V: Transparency
- ✅ Show cache age: "Loading from cache (2 days ago)"
- ✅ Disclose upgrade guide source: "source: web_search"
- ✅ Note any limitations: "No official migration guide found"
Article VII: User Empowerment
- ✅ Provide actionable migration checklist
- ✅ Estimate effort level
- ✅ Suggest next steps
Related Commands
After dependency analysis, consider:
/sourceatlas:impact "Component"- See change impact before upgrade/sourceatlas:pattern "api"- Learn how project uses the library/sourceatlas:history "src/lib/"- Check change frequency in affected areas
Dependency Analysis Self-Verification Guide
Complete verification checklist to ensure dependency analysis accuracy.
When to Verify
Execute after completing your dependency analysis, before outputting final results.
Verification Steps
Step V1: Extract Verifiable Claims
Parse your analysis output to identify all quantifiable claims:
verifiable_claims:
- "Found [N] usage points"
- "Current version: [X.Y.Z]"
- "Detected in [file]"
- "[M] deprecated API usages"
- "[K] removable availability checks"
- "[P] new APIs available"
Extract these for verification:
- Version numbers (current/target)
- File counts
- API usage counts
- Manifest file locations
- Breaking change counts
Step V2: Parallel Verification Execution
Run verification commands in parallel for speed:
V2.1: Verify Version Detection
# For Node.js/npm
grep '"${LIBRARY}"' package.json | head -5
# For iOS/CocoaPods
grep "platform :ios" Podfile | head -5
# For Android/Gradle
grep "compileSdk\|minSdk\|targetSdk" build.gradle build.gradle.kts | head -5
Check:
- ✅ Version numbers match manifest files
- ✅ Source file (package.json/Podfile) exists
- ⚠️ If mismatch → update analysis
V2.2: Verify API Usage Counts
# Count import/require statements
grep -r "import.*${LIBRARY}\|require.*${LIBRARY}" \
--include="*.js" --include="*.ts" --include="*.tsx" \
. | grep -v node_modules | wc -l
# Count specific API usage
grep -r "\.${API_NAME}\|${API_NAME}(" \
--include="*.js" --include="*.ts" \
. | grep -v node_modules | wc -l
Check:
- ✅ Usage count matches analysis (±5% tolerance)
- ⚠️ If significant difference → re-search with better patterns
V2.3: Verify File Paths
Sample 3-5 file paths from your analysis:
# Check files exist
for file in "${FILE_PATHS[@]}"; do
if [ ! -f "$file" ]; then
echo "⚠️ Not found: $file"
fi
done
# Verify line numbers
grep -n "${PATTERN}" "${FILE_PATH}" | head -3
Check:
- ✅ All sampled file paths exist
- ✅ Line numbers are accurate (±2 lines)
- ⚠️ If file not found → remove from analysis
V2.4: Verify Upgrade Guide Source
If you used WebSearch/WebFetch:
# Verify URL accessibility (if applicable)
# Check migration guide quality indicators
Check:
- ✅ URLs are official sources (not third-party blogs)
- ✅ Migration guide matches target version
- ⚠️ If quality low → note in risk_assessment
Step V3: Handle Verification Results
Based on verification outcomes:
If All Checks Pass ✅
verification_status:
verified: true
checks_passed: 4
confidence: high
Proceed to output.
If Minor Issues Found ⚠️ (1-2 checks failed)
Examples:
- File path off by 1-2 lines
- Usage count difference <10%
- Version detection from wrong source
Action:
- Correct the specific claims
- Re-verify those claims
- Add note to output:
verification_notes:
- "Line numbers adjusted after verification"
- "Usage count corrected to [N] (was [M])"
If Major Issues Found ❌ (3+ checks failed)
Examples:
- Claimed files don't exist
- Usage count off by >50%
- Version numbers completely wrong
- Upgrade guide for wrong version
Action:
- STOP - Do not output current analysis
- Re-execute Phase 1-5 from workflow.md
- Use better search patterns
- Verify each step before proceeding
Step V4: Verification Summary
Add to final output:
verification_summary:
timestamp: "[ISO 8601]"
checks_performed:
- "Version detection: ✅"
- "API usage counts: ✅"
- "File path accuracy: ✅"
- "Upgrade guide quality: ✅"
confidence_level: "high" # high|medium|low
notes:
- "[Any corrections made]"
Confidence Level Criteria:
| Level | Criteria |
|---|---|
| High | All 4 checks passed, official sources, recent data |
| Medium | 3/4 checks passed, or no official migration guide |
| Low | <3 checks passed, or upgrade guide missing |
Verification Examples
Example 1: React Upgrade
Claim: "Found 89 useState usages"
Verification:
grep -r "useState" --include="*.ts" --include="*.tsx" . | \
grep -v node_modules | grep -v ".test." | wc -l
# Output: 87
Result: ⚠️ Minor difference (89 → 87)
Action:
- Update analysis:
useState: 87 usages - Note: "Count verified and adjusted"
Example 2: iOS Version Upgrade
Claim: "23 removable availability checks"
Verification:
grep -rn "#available(iOS 1[0-6]" --include="*.swift" . | \
grep -v Pods | wc -l
# Output: 23
Result: ✅ Exact match
Action: Proceed with confidence
Example 3: Version Detection
Claim: "Current version: 17.0.2"
Verification:
grep '"react"' package.json
# Output: "react": "17.0.1"
Result: ❌ Version mismatch
Action:
- Correct to 17.0.1
- Re-check if this affects breaking changes analysis
- Verify package-lock.json for actual installed version
Error Recovery
If Verification Script Fails
# If grep returns no results
# → Pattern might be too specific, broaden search
# If file not found
# → Use find command to locate similar files
# If command times out
# → Add --max-count or | head -N to limit results
If Count Discrepancy Large (>20%)
Likely causes:
- Search pattern too narrow/broad
- Wrong file extensions
- Forgot to exclude test files
- Manifest file outdated
Action:
- Review search pattern from workflow.md#phase-3
- Check file extensions match project
- Verify .gitignore patterns
- Use Glob to list files first, then grep
Best Practices
- Always verify version numbers - Most critical for upgrade analysis
- Sample at least 3 file paths - Ensures grep patterns worked
- Check official sources first - Community guides are secondary
- Note all corrections - Transparency builds trust
- Re-verify after corrections - Don't assume fix is correct
Handoff to Next Steps
After verification:
- ✅ If confidence HIGH → Proceed to output
- ⚠️ If confidence MEDIUM → Warn user about limitations
- ❌ If confidence LOW → Re-execute analysis or ask user for help
See reference.md#handoffs for when to suggest next commands.
Dependency Analysis Workflow
Complete step-by-step guide for dependency upgrade analysis.
Phase 0: Rule Confirmation (1-2 minutes)
Step 0.1: Identify Upgrade Type
Based on ${ARGUMENTS}:
| Input Pattern | Type | Focus Areas |
|---|---|---|
iOS 17, iOS 16 → 17 | iOS Minimum Version Upgrade | Removable #available, deprecated APIs, new opportunities |
iOS SDK 26, Xcode 16 | SDK/Compiler Upgrade | Compilation warnings, Swift version, new syntax |
react 17 → 18, pandas 1.x → 2.x | Major Version Upgrade | Breaking changes, deprecated APIs, new patterns |
react, pandas (no version) | Usage Inventory | List usage points only |
Step 0.2: Generate Rules Preview
Output YAML for user confirmation:
upgrade_rules_preview:
detected_upgrade_type: "[type]"
from_version: "[current]"
to_version: "[target]"
planned_checks:
removable_availability_checks:
patterns: ["#available(iOS [version below target]"]
deprecated_apis:
source: "[built-in|web_search|migration_guide]"
Step 0.3: Confirm with User
Use AskUserQuestion to confirm rules before proceeding.
Phase 1: Detect Current Version (1 minute)
For Node.js/npm
# package.json
grep '"${LIBRARY}"' package.json
For iOS/CocoaPods
# Podfile or Podfile.lock
grep "${POD_NAME}" Podfile Podfile.lock
For Android/Gradle
# build.gradle or build.gradle.kts
grep "${DEPENDENCY}" build.gradle build.gradle.kts
Phase 2: Search for Upgrade Guide (2-3 minutes)
Use WebSearch
# Search for official migration guide
WebSearch: "${LIBRARY} ${FROM_VERSION} to ${TO_VERSION} migration guide"
WebSearch: "${LIBRARY} breaking changes ${TO_VERSION}"
Priority Order
- Official migration guide
- Official changelog
- Community upgrade guides
- GitHub release notes
Phase 3: Find All Usage Points (3-5 minutes)
For JavaScript/TypeScript
# Import statements
grep -rn "^import.*${LIBRARY}\|require.*${LIBRARY}" --include="*.ts" --include="*.tsx" --include="*.js" --include="*.jsx" . | grep -v node_modules | head -100
# Specific API usage
grep -rn "\.${API_NAME}\|${API_NAME}(" --include="*.ts" --include="*.tsx" . | grep -v node_modules | head -50
For Swift/iOS
# Import statements
grep -rn "^import ${FRAMEWORK}" --include="*.swift" . | grep -v Pods | head -100
# Specific API usage (UIKit)
grep -rn "UIView\|UIViewController\|UITableView\|UICollectionView" --include="*.swift" . | grep -v Pods | head -30
# Availability checks
grep -rn "#available(iOS" --include="*.swift" . | grep -v Pods | head -50
For Android/Kotlin
# Import statements
grep -rn "^import.*${LIBRARY}" --include="*.kt" --include="*.java" . | grep -v build | head -50
Phase 4: Categorize API Usage (2-3 minutes)
From usage points found:
- Count unique APIs used
- Group by category (hooks, components, utilities, etc.)
- Note frequency for each API
- Identify file:line for each usage type
- Match against Phase 0 rules to flag deprecated/removable items
Phase 5: Generate Analysis Report
See output-template.md for complete format.
Language-Specific Tips
Swift/iOS
Find removable availability checks:
# iOS version checks below target
grep -rn "#available(iOS 14" --include="*.swift" . | grep -v Pods
grep -rn "#available(iOS 15" --include="*.swift" . | grep -v Pods
# If target is iOS 17, these can be removed
Find deprecated APIs:
# UIWebView (deprecated)
grep -rn "UIWebView" --include="*.swift" . | grep -v Pods
# @UIApplicationMain (use @main instead)
grep -rn "@UIApplicationMain" --include="*.swift" . | grep -v Pods
React/JavaScript
Find deprecated patterns:
# Legacy lifecycle methods
grep -rn "componentWillMount\|componentWillReceiveProps" --include="*.js" --include="*.jsx" .
# String refs (deprecated)
grep -rn 'ref="' --include="*.js" --include="*.jsx" .
Error Handling
If upgrade guide not found:
- Search broader terms
- Check library's official GitHub releases
- Ask user if they have migration guide URL
If no usage found:
- Verify dependency actually installed
- Check different file extensions
- Suggest dependency might be unused
If breaking changes unclear:
- Report usage statistics only
- Recommend manual review of changelog
- Provide comparison script for major APIs
SourceAtlas: Flow Analysis
Target: $ARGUMENTS
STEP 0: Mode Detection (EXECUTE IMMEDIATELY)
IMPORTANT: Check these patterns FIRST before doing anything else.
Check for Tier 2-3 Keywords (External Mode Required)
Scan $ARGUMENTS for these keywords. If ANY match, load external file and STOP reading this document:
| If arguments contain... | Then execute this action |
|---|---|
| "dead code" OR "unreachable" OR "unused" | Read scripts/atlas/flow-modes/mode-13-dead-code.md then follow its instructions |
| "async" OR "thread" OR "concurrent" OR "race" | Read scripts/atlas/flow-modes/mode-14-concurrency.md then follow its instructions |
| "taint" OR "injection" OR "untrusted" | Read scripts/atlas/flow-modes/mode-12-taint-analysis.md then follow its instructions |
| "state" OR "status" OR "lifecycle" | Read scripts/atlas/flow-modes/mode-04-state-machine.md then follow its instructions |
| "transaction" OR "rollback" OR "commit" | Read scripts/atlas/flow-modes/mode-09-transaction.md then follow its instructions |
| "log" OR "logging" OR "from logs" | Read scripts/atlas/flow-modes/mode-06-log-discovery.md then follow its instructions |
| "compare" OR "diff" OR "vs" | Read scripts/atlas/flow-modes/mode-05-flow-comparison.md then follow its instructions |
| "feature toggle" OR "feature flag" | Read scripts/atlas/flow-modes/mode-07-feature-toggle.md then follow its instructions |
| "cache" OR "redis" OR "TTL" | Read scripts/atlas/flow-modes/mode-11-cache-flow.md then follow its instructions |
If a keyword matched above: Load the file NOW, then execute ONLY that mode's instructions. Do NOT continue reading this document.
Check for Tier 1 Keywords (Built-in Modes)
If none of the above matched, check for these Tier 1 patterns:
| If arguments contain... | Mode to use |
|---|---|
| "who calls" OR "callers" OR "called by" | Mode 1: Reverse Tracing (see below) |
| "error" OR "failure" OR "exception" OR "fail" | Mode 2: Error Path (see below) |
| "data flow" OR "how is X calculated" OR "trace variable" | Mode 3: Data Flow (see below) |
| "event" OR "message" OR "pub/sub" OR "listener" | Mode 8: Event Tracing (see below) |
| "permission" OR "role" OR "auth" OR "access control" | Mode 10: Permission Flow (see below) |
| (none of the above) | Standard Flow Tracing (default) |
STEP 1: Cache Check
If --force NOT in arguments:
- Convert flow name to filename: lowercase, spaces→hyphens, max 50 chars
- Check:
ls .sourceatlas/flows/{name}.md 2>/dev/null - If exists: Load and output cache, then STOP
- If not exists: Continue
STEP 2: Find Entry Point
If explicit path given (e.g., "from OrderService.create()"): → Start tracing immediately
If flow description only (e.g., "checkout flow"): → Search for entry points:
grep -rn "{keyword}" --include="*.ts" --include="*.js" --include="*.py" src/ app/ lib/ 2>/dev/null | head -15
→ Present options if multiple matches
STEP 3: Trace Flow
From entry point, trace each step:
- Read the function
- Identify what it calls
- Follow the chain (depth: 5 levels default)
- Stop at boundaries (DB, external API, third-party)
For each step capture:
- Function name
- File:line location
- Business meaning
- Notable patterns (🔒 security, 💾 DB, 🌐 API, ⚡ async, ⚠️ risk)
STEP 4: Output Format
{Flow Name}
===========
Entry Point: {file}:{line}
┌──────┬──────────────────────────────┬───────────────────────┐
│ Step │ Operation │ Location │
├──────┼──────────────────────────────┼───────────────────────┤
│ 1 │ {description} │ {file}:{line} │
│ 2 │ {description} │ {file}:{line} │
└──────┴──────────────────────────────┴───────────────────────┘
Flow Diagram:
{entry}() → {step1}() → {step2}() → {step3}()
Notable Patterns:
├── 🔒 {pattern1}
├── 💾 {pattern2}
└── ⚠️ {pattern3}
───────────────────────────────────
📊 Mode: Standard | Confidence: ~85% | Depth: 5
───────────────────────────────────
Tier 1 Mode: Reverse Tracing
Trigger: "who calls", "callers", "called by"
Find all callers of target function:
Who calls {function}?
=====================
Callers (N found):
├── {Caller1}() → {description}
│ 📍 {file}:{line}
├── {Caller2}() → {description}
│ 📍 {file}:{line}
└── {Caller3}() → {description}
📍 {file}:{line}
💡 Modifying {function} affects these {N} callers
Tier 1 Mode: Error Path
Trigger: "error", "failure", "exception", "fail"
Trace failure scenarios:
{Flow} Error Paths
==================
1. {Step}
📍 {file}:{line}
⚠️ Failure → {ErrorType}
└── {what happens}
📌 Risk: {identified risk}
Tier 1 Mode: Data Flow
Trigger: "data flow", "how is X calculated", "trace variable"
Track data transformations:
Data Flow: {variable}
=====================
[Input] {source}
↓
1. {Transform} → {result}
📍 {file}:{line}
↓
[Output] {final}
Tier 1 Mode: Event Tracing
Trigger: "event", "message", "pub/sub", "listener"
{EVENT} Tracing
===============
📤 Emission: {Publisher}() → emit("{EVENT}")
📍 {file}:{line}
📥 Listeners:
├── {Listener1}() → {action}
│ 📍 {file}:{line}
└── {Listener2}() → {action}
📍 {file}:{line}
Tier 1 Mode: Permission Flow
Trigger: "permission", "role", "auth", "access control"
{Operation} by Role
===================
[ADMIN] → Full access
├── {check} 🔐 @RequireRole("ADMIN")
└── 📍 {file}:{line}
[USER] → Limited access
├── {check} 🔐 @CheckOwnership
└── 📍 {file}:{line}
Self-Verification
Before output, verify:
- File paths exist:
test -f {path} - Methods exist:
grep -q "{method}" {file}
Add to footer: ✅ Verified: [N] paths, [M] methods
Auto-Save (Default Behavior)
After analysis completes, automatically:
mkdir -p .sourceatlas/flows- Save to
.sourceatlas/flows/{name}.md - Append:
💾 Saved to .sourceatlas/flows/{name}.md
Deprecated: --save flag
If --save is in arguments:
- Show:
⚠️ --save is deprecated, auto-save is now default - Remove
--savefrom arguments - Continue normal execution (still auto-saves)
🗺️ SourceAtlas v3.0 │ Tiered Architecture
SourceAtlas: Smart Temporal Analysis (Git History)
Constitution: ANALYSIS_CONSTITUTION.md v1.0
Context
Analysis Scope: $ARGUMENTS (default: entire repository) Goal: Extract actionable insights from git history Time Limit: 5-10 minutes Prerequisite: code-maat (will ask permission to install if missing)
Quick Start
- Check cache (skip if
--forceflag present) - Check code-maat installation (install if needed with permission)
- Generate git log (last 12 months, code-maat compatible)
- Run analyses: Hotspots, Coupling, Contributors
- Risk assessment combining all dimensions
- Generate report following output-template.md
- Verify output using verification-guide.md
- Auto-save to
.sourceatlas/history.md
Your Task
You are analyzing git commit history to understand:
- Hotspots - Files changed most frequently (likely complex/risky)
- Temporal Coupling - Files that change together (hidden dependencies)
- Recent Contributors - Who has knowledge of which areas (bus factor)
- Risk Areas - Aggregate assessment for prioritization
What You'll Discover
| Analysis Type | Insight | Business Value |
|---|---|---|
| Hotspots | Complexity indicators | Refactoring priorities, technical debt |
| Coupling | Hidden dependencies | Architecture review targets |
| Contributors | Knowledge distribution | Bus factor risks, training needs |
| Risk | Aggregate assessment | Resource allocation decisions |
Core Workflow
Execute these steps in order. See workflow.md for complete details.
Step 0: Check Prerequisites (30 seconds)
Purpose: Ensure code-maat is installed and Java is available.
Check code-maat:
if [ -f "$HOME/.sourceatlas/bin/code-maat-1.0.4-standalone.jar" ]; then
export CODEMAAT_JAR="$HOME/.sourceatlas/bin/code-maat-1.0.4-standalone.jar"
fi
If not found, use AskUserQuestion:
- "code-maat required for analysis. Install now? (requires Java 8+)"
- If yes → run
./scripts/install-codemaat.sh - If no → show manual installation steps
→ See workflow.md#step-0
Step 1: Generate Git Log (1 minute)
Purpose: Create code-maat compatible git log file.
Default: Last 12 months
git log --all --numstat --date=short \
--pretty=format:'--%h--%ad--%aN' \
--after="$(date -v-12m +%Y-%m-%d)" \
> /tmp/git-history.log
If scope specified: Filter to directory (e.g., "src/")
→ See workflow.md#step-1
Step 2: Hotspot Analysis (2 minutes)
Purpose: Identify frequently changed files.
Run code-maat revisions:
java -jar "$CODEMAAT_JAR" -l /tmp/git-history.log -c git2 -a revisions
Calculate complexity scores: LOC × Revisions
Identify top 10 hotspots sorted by complexity
→ See workflow.md#step-2
Step 3: Temporal Coupling Analysis (2 minutes)
Purpose: Find files that change together.
Run code-maat coupling:
java -jar "$CODEMAAT_JAR" -l /tmp/git-history.log -c git2 -a coupling
Filter significant couplings: degree ≥ 0.5
Categorize: Expected vs Suspicious
→ See workflow.md#step-3
Step 4: Recent Contributors Analysis (2 minutes)
Purpose: Map knowledge distribution across modules.
Run code-maat entity-ownership:
java -jar "$CODEMAAT_JAR" -l /tmp/git-history.log -c git2 -a entity-ownership
Generate knowledge map by area (src/api/, src/core/, etc.)
Identify bus factor risks: Single-contributor modules
→ See workflow.md#step-4
Step 5: Risk Assessment (1 minute)
Purpose: Combine all dimensions into actionable priorities.
Calculate composite risk: (Revisions × Coupling_Count) / Contributor_Count
Risk categories:
- Bus Factor Risk
- Complexity Risk
- Coupling Risk
- Testing Gap Risk
→ See workflow.md#step-5
Output Format
Your analysis should follow this Markdown structure:
🗺️ SourceAtlas: History
───────────────────────────────
📜 [repo name] │ [N] months
**Analysis Period**: [start] → [end]
**Commits Analyzed**: [count]
**Files Analyzed**: [count]
## 1. Hotspots (Top 10)
[Table with Rank, File, Changes, LOC, Complexity Score]
[Insights paragraph]
## 2. Temporal Coupling (Significant Pairs)
[Table with File A, File B, Coupling, Co-changes]
[Expected vs Suspicious coupling analysis]
## 3. Recent Contributors (Knowledge Map)
[Per-area tables with Contributor, Commits, Last Active]
[Bus Factor Risks section]
## 4. Risk Summary
[Risk aggregation table]
[Priority Actions numbered list]
## 5. Recommendations
[Refactoring candidates, knowledge sharing, architecture review]
## Recommended Next
[Dynamic suggestions based on findings]
→ See output-template.md for complete specification and examples
Critical Rules
1. Privacy Aware
- Use "Recent Contributors" not "Ownership %"
- Focus on knowledge distribution, not blame
- Frame findings as opportunities, not criticisms
2. Actionable Insights
- Every finding must have recommended action
- Reference specific commit counts and file paths
- Provide concrete next steps (not vague suggestions)
3. Evidence-Based
- All hotspot files must exist (verify)
- Commit counts must match git history (±20% tolerance)
- Contributor names must be in git log
4. Time-Bounded
- Default: 12 months (good balance)
- Minimum: 3 months (for meaningful patterns)
- Maximum: 24 months (avoid ancient history)
5. Verification Required
- Execute verification-guide.md after analysis
- Verify file paths, commit counts, contributors
- Correct discrepancies before output
6. Constitutional Compliance
Follow ANALYSIS_CONSTITUTION.md:
- Article I: Evidence-based (all claims from git/code-maat)
- Article III: Verification (run V1-V4 checks)
- Article IV: Evidence format (file:line references)
- Article V: Transparency (show analysis period, cache age)
- Article VII: User Empowerment (actionable recommendations)
Self-Verification
After generating your analysis, execute verification steps:
Step V1: Extract Verifiable Claims
Parse output for all quantifiable claims:
- File paths (hotspots, coupled files)
- Commit counts (total, per file, per contributor)
- Contributor names
- Coupling pairs
- Date ranges
Step V2: Parallel Verification
- Verify hotspot files exist (sample 3-5)
- Verify commit counts (±20% tolerance)
- Verify contributors in git history
- Verify coupling pairs (both files exist)
- Verify date ranges within repository history
Step V3: Handle Results
- ✅ All checks pass → Proceed to output
- ⚠️ Minor issues (1-2 checks) → Correct and note
- ❌ Major issues (3+ checks) → Re-execute analysis
Step V4: Add Verification Summary
verification_summary:
checks_performed: [...]
confidence_level: "high" # high|medium|low
notes: [...]
→ See verification-guide.md for complete checklist
Advanced
Cache Behavior
- Default: Use cache if exists
- Force flag: Skip cache with
--force - Cache location:
.sourceatlas/history.md(fixed path) - Cache age warning: If >30 days old
→ See reference.md#cache-behavior
Auto-Save Mechanism
Complete Markdown report auto-saves after verification:
💾 Saved to .sourceatlas/history.md
→ See reference.md#auto-save-behavior
Handoffs to Next Commands
Based on findings, suggest:
- High-risk hotspot →
/sourceatlas:impact "[hotspot]" - Suspicious coupling →
/sourceatlas:flow "[entry point]" - Refactoring needed →
/sourceatlas:pattern "[pattern]"
→ See reference.md#handoffs
code-maat Installation
- Default location:
~/.sourceatlas/bin/code-maat-1.0.4-standalone.jar - Auto-install via:
./scripts/install-codemaat.sh - Requires: Java 8+
→ See reference.md#code-maat-installation
Interpretation Guidelines
- Hotspots: Not always bad (core logic changes often)
- Coupling: Expected (same domain) vs Suspicious (cross-module)
- Contributors: Healthy = 2-3 per module, Risk = single contributor
→ See reference.md#interpretation-guidelines
Support Files
Detailed documentation available in:
- workflow.md - Complete Step 0-5 execution guide with bash commands
- output-template.md - Full Markdown structure and examples
- verification-guide.md - Self-verification steps V1-V4
- reference.md - Cache, code-maat, interpretation, troubleshooting
Output Header
Start your output with:
🗺️ SourceAtlas: History
───────────────────────────────
📜 [repo name] │ [N] months
Then follow complete structure in output-template.md.
History Analysis Output Template
Complete Markdown format specification for temporal analysis reports.
Header Format
🗺️ SourceAtlas: History
───────────────────────────────
📜 [repo name] │ [N] months
**Analysis Period**: [start date] → [end date]
**Commits Analyzed**: [count]
**Files Analyzed**: [count]
Section 1: Hotspots (Top 10)
Files changed most frequently - likely complex or frequently enhanced.
## 1. Hotspots (Top 10)
Files changed most frequently - likely complex or frequently enhanced:
| Rank | File | Changes | LOC | Complexity Score |
|------|------|---------|-----|------------------|
| 1 | src/core/processor.ts | 45 | 892 | 40,140 |
| 2 | src/api/handlers.ts | 38 | 456 | 17,328 |
| 3 | config/settings.json | 32 | 123 | 3,936 |
| 4 | src/models/user.ts | 28 | 345 | 9,660 |
| 5 | src/utils/helpers.ts | 25 | 234 | 5,850 |
| 6 | src/middleware/auth.ts | 23 | 189 | 4,347 |
| 7 | tests/integration.spec.ts | 21 | 567 | 11,907 |
| 8 | src/routes/index.ts | 19 | 156 | 2,964 |
| 9 | src/services/payment.ts | 18 | 423 | 7,614 |
| 10 | package.json | 17 | 78 | 1,326 |
**Insights**:
- **Hotspot #1**: `processor.ts` has been modified in 45 commits
- Complexity score of 40,140 indicates significant technical debt
- Consider refactoring into smaller modules (Strategy pattern)
- Review recent changes for code duplication
- **Hotspot #2**: `handlers.ts` frequently updated (38 commits)
- API endpoint additions/modifications
- Ensure adequate test coverage for new endpoints
- **Configuration hotspot**: `settings.json` (32 commits)
- Normal for configuration files
- Consider environment-specific configs to reduce churn
- **Test file in hotspots**: `integration.spec.ts` (21 commits)
- Good sign - tests updated with production code
- Complexity score indicates comprehensive test suite
Section 2: Temporal Coupling (Significant Pairs)
Files that frequently change together - may indicate hidden dependencies.
## 2. Temporal Coupling (Significant Pairs)
Files that frequently change together - may indicate hidden dependencies:
| File A | File B | Coupling | Co-changes |
|--------|--------|----------|------------|
| src/user/model.ts | src/user/service.ts | 0.85 | 23 |
| src/api/auth.ts | src/middleware/jwt.ts | 0.72 | 18 |
| src/routes/user.ts | src/controllers/user.ts | 0.68 | 15 |
| src/core/processor.ts | src/core/validator.ts | 0.63 | 12 |
| src/models/order.ts | src/services/payment.ts | 0.58 | 10 |
| config/database.json | src/db/connection.ts | 0.55 | 9 |
**Insights**:
### Expected Coupling ✅
- **user/model.ts ↔ user/service.ts** (0.85, 23 co-changes)
- Same domain, expected coupling
- Model changes naturally require service updates
- **auth.ts ↔ jwt.ts** (0.72, 18 co-changes)
- Authentication flow dependencies
- Normal for security-related code
- **routes ↔ controllers** (0.68, 15 co-changes)
- MVC pattern, expected behavior
### Suspicious Coupling ⚠️
- **order.ts ↔ payment.ts** (0.58, 10 co-changes)
- Cross-module coupling (orders → payments)
- **Review**: Consider event-driven decoupling
- May indicate missing abstraction layer
### Recommendations
1. **High coupling (>0.8)**: Consider merging files if always changed together
2. **Cross-module coupling**: Review for architectural improvements
3. **Config ↔ Code coupling**: Normal, ensure version control best practices
Section 3: Recent Contributors (Knowledge Map)
Who has recent knowledge of each area.
## 3. Recent Contributors (Knowledge Map)
Who has recent knowledge of each area:
### src/api/
| Contributor | Recent Commits | Last Active |
|-------------|----------------|-------------|
| Alice | 12 | 2025-11-28 |
| Bob | 8 | 2025-11-25 |
| Charlie | 3 | 2025-11-15 |
**Coverage**: 3 contributors, good knowledge distribution
---
### src/core/
| Contributor | Recent Commits | Last Active |
|-------------|----------------|-------------|
| Charlie | 15 | 2025-11-29 |
| Alice | 3 | 2025-11-20 |
**Coverage**: 2 contributors, Charlie is primary maintainer
---
### src/legacy/
| Contributor | Recent Commits | Last Active |
|-------------|----------------|-------------|
| David | 2 | 2025-05-10 |
**⚠️ Bus Factor Risk**: Only 1 contributor in last 6 months, no recent activity
---
### src/payments/
| Contributor | Recent Commits | Last Active |
|-------------|----------------|-------------|
| Eve | 5 | 2025-08-15 |
**⚠️ Knowledge Gap**: Primary contributor last active 3 months ago
---
### Bus Factor Risks
| Area | Risk Level | Contributors | Last Activity | Recommendation |
|------|------------|--------------|---------------|----------------|
| src/legacy/* | 🔴 HIGH | 1 | 6 months ago | Document immediately, pair programming |
| src/payments/ | 🟡 MEDIUM | 1 | 3 months ago | Knowledge transfer, cross-training |
| src/core/ | 🟢 LOW | 2 | Recent | Maintain current distribution |
Section 4: Risk Summary
Aggregate risk assessment across all dimensions.
## 4. Risk Summary
| Risk Type | Count | Top Files | Severity |
|-----------|-------|-----------|----------|
| Bus Factor | 3 | legacy/*, payments/gateway.ts, utils/deprecated.ts | 🔴 HIGH |
| High Complexity | 2 | core/processor.ts, api/handlers.ts | 🟡 MEDIUM |
| Suspicious Coupling | 1 | orders/model.ts ↔ payments/service.ts | 🟡 MEDIUM |
| Testing Gap | 1 | core/processor.ts (no corresponding test changes) | 🟡 MEDIUM |
---
### Priority Actions
1. **URGENT - Document Legacy Code** 🔴
- `src/legacy/*` - Single contributor, 6 months inactive
- Action: Schedule knowledge transfer session this week
- Pair junior dev with Charlie to review legacy patterns
2. **HIGH - Add Tests for Hotspots** 🟡
- `core/processor.ts` - 45 changes but no test file activity
- Action: Add unit tests, aim for 80% coverage
- Review recent changes for edge cases
3. **MEDIUM - Review Cross-Module Coupling** 🟡
- `orders/model.ts ↔ payments/service.ts` coupling (0.58)
- Action: Investigate if event-driven architecture is appropriate
- Consider introducing domain events for decoupling
4. **MEDIUM - Knowledge Transfer for Payments** 🟡
- Primary contributor Eve last active 3 months ago
- Action: Cross-train another developer on payment flows
- Document critical payment integration logic
---
### Risk Metrics
| Metric | Value | Threshold | Status |
|--------|-------|-----------|--------|
| Files with single contributor | 8 | <5 | ⚠️ Above threshold |
| Average contributors per module | 2.3 | >2 | ✅ Acceptable |
| Hotspots without tests | 1 | 0 | ⚠️ Needs attention |
| Suspicious couplings | 1 | <2 | ✅ Acceptable |
Section 5: Recommendations
Actionable recommendations based on temporal patterns.
## 5. Recommendations
Based on temporal analysis:
### 1. Refactoring Candidates
**processor.ts** (Hotspot #1)
- **Problem**: 45 changes in 12 months, complexity score 40,140
- **Indicator**: High change frequency suggests unstable design
- **Recommendation**:
- Extract into Strategy or Plugin pattern
- Separate concerns: validation, transformation, persistence
- Target: Reduce file LOC from 892 → <500 per module
**handlers.ts** (Hotspot #2)
- **Problem**: 38 changes, grows with each new API endpoint
- **Recommendation**:
- Consider breaking into feature-specific handler modules
- Use route grouping by domain (users/, orders/, payments/)
---
### 2. Knowledge Sharing
**Schedule Knowledge Transfer Sessions**:
- `src/legacy/*` - Pair David (if available) with 2 developers
- `src/payments/` - Document Eve's integration patterns
- `src/core/` - Charlie to share processor.ts refactoring plan
**Cross-Training Matrix**:
| Module | Primary | Backup | Learning |
|--------|---------|--------|----------|
| api/ | Alice | Bob | Charlie |
| core/ | Charlie | Alice | Bob |
| payments/ | Eve | (needed) | (assign) |
| legacy/ | David | (needed) | (assign) |
---
### 3. Architecture Review
**Investigate Cross-Module Coupling**:
- **orders ↔ payments** (0.58 coupling)
- Current: Direct service calls
- Consider: Event-driven architecture
- Benefit: Reduce coupling, improve scalability
- Trade-off: Increased complexity, eventual consistency
**Review Testing Strategy**:
- Hotspots should have proportional test activity
- `processor.ts`: 45 production changes, 0 test file changes
- Action: Implement test coverage before next refactor
---
### 4. Process Improvements
**Commit Practices**:
- Large, infrequent commits may hide coupling patterns
- Consider: Smaller, atomic commits with clear messages
- Benefit: Better coupling detection, easier rollback
**Code Review Focus**:
- Flag changes to identified hotspots (processor.ts, handlers.ts)
- Extra scrutiny for cross-module coupling
- Require tests for hotspot modifications
Section 6: Recommended Next
Dynamic suggestions based on findings.
## Recommended Next
Based on analysis findings, dynamically suggest 1-2 most relevant follow-up commands:
| # | Command | Purpose |
|---|---------|---------|
| 1 | `/sourceatlas:impact "src/core/processor.ts"` | processor.ts changed 45 times, need to understand dependencies |
| 2 | `/sourceatlas:pattern "strategy pattern"` | Hotspot involves complex processing, need to understand implementation conventions |
💡 Enter a number (e.g., `1`) or copy the command to execute
Rules:
- Only show if there are clear findings (hotspots, coupling, risks)
- Use actual discovered file names, not placeholders
- Limit to 1-2 most actionable recommendations
- Reference specific metrics in Purpose (change count, coupling degree)
Footer Format
───────────────────────────────
🗺️ v2.13.1 │ Constitution v1.1
💾 Saved to .sourceatlas/history.md
Example: Complete Output
🗺️ SourceAtlas: History
───────────────────────────────
📜 sourceatlas2 │ 12 months
**Analysis Period**: 2024-11-30 → 2025-11-30
**Commits Analyzed**: 487
**Files Analyzed**: 234
---
## 1. Hotspots (Top 10)
[... full hotspots table ...]
**Insights**:
[... specific insights ...]
---
## 2. Temporal Coupling (Significant Pairs)
[... full coupling table ...]
**Insights**:
[... expected vs suspicious ...]
---
## 3. Recent Contributors (Knowledge Map)
[... knowledge map by area ...]
**Bus Factor Risks**:
[... specific risks ...]
---
## 4. Risk Summary
[... risk aggregation ...]
**Priority Actions**:
[... numbered action items ...]
---
## 5. Recommendations
[... detailed recommendations ...]
---
## Recommended Next
| # | Command | Purpose |
|---|---------|---------|
| 1 | `/sourceatlas:impact "src/core/processor.ts"` | processor.ts changed 45 times, need to understand dependencies |
💡 Enter a number (e.g., `1`) or copy the command to execute
───────────────────────────────
🗺️ v2.13.1 │ Constitution v1.1
✅ Verified: 10 hotspot files, 5 contributors, commit counts
💾 Saved to .sourceatlas/history.md
Field Descriptions
Hotspots Table
- Rank: 1-10, sorted by revision count descending
- File: Relative path from repository root
- Changes: Number of commits touching this file
- LOC: Current lines of code (use
wc -l) - Complexity Score: LOC × Changes (higher = more risk)
Coupling Table
- File A, File B: The coupled file pair
- Coupling: Degree 0.0-1.0 (percentage they change together)
- Co-changes: Number of commits where both files changed
Contributors Table
- Contributor: Git author name (use
git shortlog) - Recent Commits: Commits in analysis period
- Last Active: Date of most recent commit (YYYY-MM-DD)
Risk Summary
- Risk Type: Bus Factor / High Complexity / Suspicious Coupling / Testing Gap
- Count: Number of instances
- Top Files: Most critical examples
- Severity: 🔴 HIGH / 🟡 MEDIUM / 🟢 LOW
History Analysis Reference
Advanced features, caching behavior, and best practices.
Cache Behavior
When Cache is Used
# Default: Use cache if exists and fresh
/sourceatlas:history
# Check logic:
if [ -f ".sourceatlas/history.md" ]; then
age_days=$(calculate_age_in_days)
if [ $age_days -eq 0 ]; then
echo "📁 Loading from cache (today)"
elif [ $age_days -eq 1 ]; then
echo "📁 Loading from cache (1 day ago)"
else
echo "📁 Loading from cache ($age_days days ago)"
fi
# If >30 days, warn user
if [ $age_days -gt 30 ]; then
echo "⚠️ Cache is older than 30 days, recommend re-analysis"
fi
# Output cached content
exit 0
fi
When Cache is Skipped
# Force flag: Always skip cache
/sourceatlas:history --force
# → Executes full analysis even if cache exists
# No cache: First time analysis
# → .sourceatlas/history.md doesn't exist yet
Cache File Naming
Unlike other commands, history has fixed cache path:
# Always the same
.sourceatlas/history.md
Rationale: History analysis is repository-wide, doesn't vary by target.
Auto-Save Behavior
File Structure
.sourceatlas/
└── history.md # Fixed filename
Save Timing
Auto-save occurs immediately after Step V4 verification:
# After verification passes
verification_summary:
confidence_level: "high"
# Then auto-save
💾 Saved to .sourceatlas/history.md
What Gets Saved
Complete Markdown output including:
- Header with analysis period and counts
- Hotspots table (top 10)
- Temporal coupling table
- Recent contributors knowledge map
- Risk summary
- Recommendations
- Verification summary
Format: Full Markdown as specified in output-template.md
Handoffs: When to Suggest Next Commands
After Hotspot Identification
If high-risk hotspots found (complexity >10,000):
Suggest:
| # | Command | Purpose |
|---|---------|---------|
| 1 | `/sourceatlas:impact "src/core/processor.ts"` | processor.ts changed 45 times, need to understand dependencies |
After Suspicious Coupling Found
If cross-module coupling detected (degree >0.6):
Suggest:
| # | Command | Purpose |
|---|---------|---------|
| 1 | `/sourceatlas:flow "src/orders/checkout"` | Suspicious coupling with payments, trace execution flow |
After Bus Factor Risk Found
If single-contributor modules identified:
Suggest:
| # | Command | Purpose |
|---|---------|---------|
| 1 | `/sourceatlas:pattern "legacy patterns"` | Bus factor risk in legacy/, need to understand patterns before knowledge transfer |
When to Stop (No Recommendations)
- History too short: <50 commits or <3 months
- No significant patterns: All coupling <0.5, all hotspots <10 revisions
- Analysis depth sufficient: User already ran 4+ commands
Output instead:
⚠️ **Insufficient Data Warning**
- Commits: 38 (recommend ≥50)
- Period: 67 days (recommend ≥90 days)
Recommend analyzing temporal patterns again in 3-6 months
code-maat Installation
Default Installation Location
$HOME/.sourceatlas/bin/code-maat-1.0.4-standalone.jar
Environment Variable
export CODEMAAT_JAR="$HOME/.sourceatlas/bin/code-maat-1.0.4-standalone.jar"
Installation Script
./scripts/install-codemaat.sh
What it does:
- Creates
~/.sourceatlas/bin/ - Downloads code-maat JAR from GitHub releases
- Sets executable permissions
- Verifies installation
Manual Installation
If automatic installation fails:
# 1. Download from GitHub
wget https://github.com/adamtornhill/code-maat/releases/download/v1.0.4/code-maat-1.0.4-standalone.jar
# 2. Create directory
mkdir -p ~/.sourceatlas/bin/
# 3. Move JAR
mv code-maat-1.0.4-standalone.jar ~/.sourceatlas/bin/
# 4. Set environment variable
export CODEMAAT_JAR="$HOME/.sourceatlas/bin/code-maat-1.0.4-standalone.jar"
Prerequisites
Java 8+ required:
# Check Java version
java -version
# Install if missing (macOS)
brew install openjdk@11
# Install if missing (Ubuntu)
sudo apt-get install openjdk-11-jdk
Analysis Parameters
Time Range
Default: Last 12 months
git log --after="$(date -v-12m +%Y-%m-%d)" ...
Custom time range:
# Last 6 months
/sourceatlas:history "last 6 months"
# Last 18 months
/sourceatlas:history "last 18 months"
Parsing logic:
# Extract number from arguments
MONTHS=$(echo "$ARGUMENTS" | grep -o '[0-9]\+')
if [ -z "$MONTHS" ]; then
MONTHS=12 # Default
fi
Scope Filtering
Default: Entire repository
Custom scope:
# Specific directory
/sourceatlas:history "src/"
# Multiple directories (future enhancement)
/sourceatlas:history "src/ lib/"
Implementation:
if [ -n "$SCOPE" ]; then
git log --all --numstat ... -- "$SCOPE" > /tmp/git-history.log
else
git log --all --numstat ... > /tmp/git-history.log
fi
Interpretation Guidelines
Hotspots
Not always bad:
- Core logic files naturally change often
- Configuration files updated for environments
- Test files should mirror production changes
Red flags:
- High complexity score (>10,000)
- Hotspot without corresponding test changes
- Frequent changes without documentation updates
Temporal Coupling
Expected (normal):
- Model ↔ Service (same domain)
- Route ↔ Controller (MVC pattern)
- Component ↔ Component styles
- Test ↔ Production code
Suspicious (review needed):
- Cross-layer: API ↔ Database
- Cross-module: User ↔ Payment
- Backend ↔ Frontend (if separated)
Contributors
Healthy distribution:
- 2-3 active contributors per module
- Regular activity (monthly commits)
- Knowledge overlap between contributors
Bus factor risks:
- Single contributor (especially if inactive >6 months)
- Primary contributor left team
- No knowledge overlap in critical modules
Performance Optimization
For Large Repositories (>10K commits)
# Limit analysis to recent history
git log --all --numstat --date=short \
--pretty=format:'--%h--%ad--%aN' \
--after="$(date -v-6m +%Y-%m-%d)" \
--max-count=1000 \
> /tmp/git-history.log
For Monorepos
# Analyze specific package only
git log --all --numstat --date=short \
--pretty=format:'--%h--%ad--%aN' \
-- "packages/app/" \
> /tmp/git-history.log
# Or analyze multiple related packages
git log --all --numstat --date=short \
--pretty=format:'--%h--%ad--%aN' \
-- "packages/app/" "packages/shared/" \
> /tmp/git-history.log
For Slow code-maat Execution
# Use faster analysis types
# revisions: Fast (seconds)
# coupling: Moderate (seconds to minutes)
# entity-ownership: Slow (minutes)
# Skip entity-ownership if too slow
# Focus on revisions + coupling
Edge Cases
Case 1: No Git History
# Check if git repository
if ! git rev-parse --git-dir > /dev/null 2>&1; then
echo "❌ Not a git repository"
echo "History analysis requires git version control"
exit 1
fi
Case 2: Very Short History (<50 commits)
output:
message: |
⚠️ Only 38 commits found in analysis period
Temporal analysis works best with >50 commits.
Consider:
- Extending time range (e.g., --after="2 years ago")
- Analyzing entire repository history (omit --after)
- Waiting for more development activity
Case 3: Monolithic Commits
If commits are very large (>100 files per commit):
warning: |
Large, infrequent commits detected.
This may affect coupling analysis accuracy:
- Many files change together in single commit
- Hard to distinguish real vs coincidental coupling
Recommend:
- Smaller, atomic commits going forward
- Focus on hotspot analysis (more reliable)
Case 4: Multiple Contributors with Same Name
# If "Alice" appears as:
# - Alice Smith <alice@company.com>
# - Alice Johnson <alice@contractor.com>
# code-maat uses author name only, may merge stats
# Verify in git log:
git log --format='%aN <%aE>' | sort -u | grep -i alice
Action: If ambiguous, note in output:
Note: Multiple contributors with name "Alice" found.
Stats may be aggregated.
Constitutional Compliance
Article I: Evidence-Based Analysis
- ✅ Every hotspot must have actual revision count
- ✅ Coupling degrees from code-maat output
- ✅ Contributor names from git log
Article II: Directory Exclusions
- ✅ Git log naturally excludes untracked files
- ✅ code-maat processes committed files only
Article III: Verification Required
- ✅ Execute verification-guide.md before output
- ✅ Re-verify after corrections
Article IV: Evidence Format
- ✅ Use
file:linefor hotspots - ✅ Reference commit hashes where relevant
- ✅ Include coupling degrees in output
Article V: Transparency
- ✅ Show cache age: "Loading from cache (2 days ago)"
- ✅ Show analysis period explicitly
- ✅ Note if history insufficient
Article VI: Scale Awareness
- ✅ Limit analysis to 12 months by default
- ✅ Cap hotspot list to top 10
- ✅ Filter coupling to degree ≥0.5
Article VII: User Empowerment
- ✅ Provide actionable recommendations
- ✅ Suggest next commands based on findings
- ✅ Include priority actions in risk summary
Related Commands
After history analysis, consider:
/sourceatlas:impact "[hotspot]"- Understand dependencies of frequently changed files/sourceatlas:pattern "[pattern]"- Learn patterns used in hotspots before refactoring/sourceatlas:flow "[entry point]"- Trace execution through coupled modules/sourceatlas:overview- Get broader context if history reveals complexity
Troubleshooting
Issue: code-maat Not Found
Symptom: CODEMAAT_JAR not set or file not found
Debug:
# Check environment
echo $CODEMAAT_JAR
# Check default location
ls -la ~/.sourceatlas/bin/code-maat-*.jar
# Verify Java
java -version
Fix: Run installation script or set environment variable
Issue: Empty Git Log
Symptom: 0 commits found
Debug:
# Check git repository
git log --oneline | head -5
# Check date filter
date -v-12m +%Y-%m-%d # macOS
date -d '12 months ago' +%Y-%m-%d # Linux
Fix: Adjust date range or check if repository has history
Issue: code-maat Fails
Symptom: Exception in thread "main" or Java errors
Debug:
# Test code-maat directly
java -jar "$CODEMAAT_JAR" -h
# Check git log format
head -20 /tmp/git-history.log
Fix:
- Verify Java version (need 8+)
- Regenerate git log with correct format
- Re-download code-maat JAR if corrupted
Issue: No Significant Patterns
Symptom: All couplings <0.3, all hotspots <5 revisions
Possible causes:
- Very stable codebase (good!)
- Short history period
- Large, infrequent commits hiding patterns
Action:
✅ No significant temporal patterns detected.
This could mean:
- Clean architecture with good separation
- Young codebase with limited history
- Stable, mature codebase
Consider re-analyzing after more development activity.
Best Practices
- Run quarterly - Temporal patterns evolve over time
- Compare with previous runs - Track if hotspots are growing
- Act on bus factor risks - Document before knowledge is lost
- Review coupling trends - Monitor if architecture is degrading
- Cross-reference with static analysis - Combine history + impact for complete picture
History Analysis Self-Verification Guide
Complete verification checklist to ensure temporal analysis accuracy.
When to Verify
Execute after completing your history analysis, before outputting final results.
Verification Steps
Step V1: Extract Verifiable Claims
Parse your analysis output to identify all quantifiable claims:
verifiable_claims:
- "500 commits analyzed"
- "src/core/processor.ts changed 45 times"
- "Alice made 12 commits to src/api/"
- "Coupling degree 0.85"
- "Analysis period: 2024-11-30 → 2025-11-30"
Extract these for verification:
- File paths (hotspots, coupled files)
- Commit counts (total, per file, per contributor)
- Contributor names
- Date ranges
- Coupling pairs (both files must exist)
- LOC counts
Step V2: Parallel Verification Execution
Run verification commands in parallel for speed:
V2.1: Verify Hotspot Files Exist
# Check top 10 hotspot files
for path in "src/core/processor.ts" "src/api/handlers.ts" "config/settings.json"; do
if [ ! -f "$path" ]; then
echo "❌ FILE_NOT_FOUND: $path"
fi
done
Check:
- ✅ All sampled hotspot file paths exist
- ⚠️ If file not found → Remove from hotspots or find correct path
V2.2: Verify Commit Counts
# Verify total commit count
claimed_total=500
actual_total=$(git rev-list --count HEAD 2>/dev/null)
# Allow ±20% tolerance (git log filters may vary)
min_expected=$((actual_total * 80 / 100))
max_expected=$((actual_total * 120 / 100))
if [ $claimed_total -lt $min_expected ] || [ $claimed_total -gt $max_expected ]; then
echo "⚠️ COMMIT_COUNT_CHECK: claimed $claimed_total, actual ~$actual_total"
fi
# Verify specific file change count
claimed_revisions=45
actual_revisions=$(git log --oneline -- "src/core/processor.ts" | wc -l)
if [ $((actual_revisions * 80 / 100)) -gt $claimed_revisions ] || [ $((actual_revisions * 120 / 100)) -lt $claimed_revisions ]; then
echo "⚠️ FILE_REVISION_MISMATCH: claimed $claimed_revisions, actual $actual_revisions"
fi
Check:
- ✅ Total commit count within ±20% (accounts for filtering differences)
- ✅ Per-file revision counts within ±20%
- ⚠️ If significant difference → Re-run code-maat analysis
V2.3: Verify Contributors
# Verify top contributor exists
claimed_contributor="Alice"
if ! git shortlog -sn --all 2>/dev/null | grep -qi "$claimed_contributor"; then
echo "❌ CONTRIBUTOR_NOT_FOUND: $claimed_contributor"
fi
# Verify contributor commit count
claimed_commits=12
actual_commits=$(git log --author="$claimed_contributor" --oneline | wc -l)
if [ $((actual_commits / 2)) -gt $claimed_commits ] || [ $((actual_commits * 2)) -lt $claimed_commits ]; then
echo "⚠️ CONTRIBUTOR_COUNT_MISMATCH: claimed $claimed_commits, actual $actual_commits"
fi
Check:
- ✅ All mentioned contributors exist in git history
- ✅ Commit counts per contributor are reasonable
- ⚠️ If contributor not found → Check spelling or remove
V2.4: Verify Coupling Pairs
# Verify both files in coupling pair exist
for pair in "src/user/model.ts:src/user/service.ts" "src/api/auth.ts:src/middleware/jwt.ts"; do
IFS=':' read -r f1 f2 <<< "$pair"
if [ ! -f "$f1" ]; then
echo "❌ COUPLING_FILE1_NOT_FOUND: $f1"
fi
if [ ! -f "$f2" ]; then
echo "❌ COUPLING_FILE2_NOT_FOUND: $f2"
fi
done
Check:
- ✅ Both files in each coupling pair exist
- ⚠️ If either file not found → Remove coupling pair
V2.5: Verify Date Range
# Verify analysis period matches actual git history
claimed_start="2024-11-30"
claimed_end="2025-11-30"
actual_start=$(git log --reverse --format="%ai" | head -1 | cut -d' ' -f1)
actual_end=$(git log --format="%ai" | head -1 | cut -d' ' -f1)
echo "Claimed: $claimed_start → $claimed_end"
echo "Actual: $actual_start → $actual_end"
Check:
- ✅ Start date is within repository history
- ✅ End date is recent (not in future)
- ⚠️ If dates outside actual range → Update analysis period
Step V3: Handle Verification Results
Based on verification outcomes:
If All Checks Pass ✅
verification_status:
verified: true
checks_passed: 5
confidence: high
Proceed to output.
If Minor Issues Found ⚠️ (1-2 checks failed)
Examples:
- File revision count off by <30%
- Contributor commit count slightly different
- Date range off by a few days
Action:
- Correct the specific claims
- Re-verify those claims
- Add note to output:
verification_notes:
- "Commit counts adjusted after verification"
- "File revision count corrected to [N] (was [M])"
If Major Issues Found ❌ (3+ checks failed)
Examples:
- Multiple hotspot files don't exist
- Contributor names not in git history
- Commit counts off by >50%
- Coupling pairs with non-existent files
Action:
- STOP - Do not output current analysis
- Re-execute Step 1-5 from workflow.md
- Check code-maat installation
- Verify git log generation
- Re-run all analyses
Step V4: Verification Summary
Add to final output (before footer):
verification_summary:
timestamp: "[ISO 8601]"
checks_performed:
- "Hotspot files: ✅"
- "Commit counts: ✅"
- "Contributors: ✅"
- "Coupling pairs: ✅"
- "Date ranges: ✅"
confidence_level: "high" # high|medium|low
notes:
- "[Any corrections made]"
Confidence Level Criteria:
| Level | Criteria |
|---|---|
| High | All 5 checks passed, no corrections needed |
| Medium | 4/5 checks passed, minor corrections made |
| Low | <4 checks passed, significant corrections made |
Verification Examples
Example 1: Hotspot File Verification
Claim: "processor.ts changed 45 times"
Verification:
git log --oneline -- "src/core/processor.ts" | wc -l
# Output: 43
Result: ⚠️ Minor difference (45 → 43)
Action:
- Update analysis:
processor.ts changed 43 times - Note: "Revision count verified and adjusted"
Example 2: Contributor Verification
Claim: "Alice made 12 commits to src/api/"
Verification:
git log --author="Alice" --oneline -- "src/api/" | wc -l
# Output: 11
Result: ⚠️ Minor difference (12 → 11)
Action:
- Update analysis: "Alice made 11 commits"
- Acceptable within ±1 commit tolerance
Example 3: Coupling Pair Verification
Claim: "model.ts ↔ service.ts coupling 0.85"
Verification:
test -f "src/user/model.ts" && echo "✅ File 1 exists"
test -f "src/user/service.ts" && echo "✅ File 2 exists"
Result: ✅ Both files exist
Action: No correction needed
Example 4: Non-existent File
Claim: "legacy/old-auth.ts is a hotspot"
Verification:
test -f "legacy/old-auth.ts"
# Exit code: 1 (file not found)
Result: ❌ File doesn't exist
Action:
- Search for similar path:
find . -name "*old-auth*" - If found at different path → Update path
- If deleted from codebase → Remove from hotspots entirely
- Note: "File was deleted after analysis period"
Error Recovery
If Verification Script Fails
# If git command fails
# → Check if inside git repository
git status > /dev/null 2>&1 || echo "Not a git repository"
# If file not found
# → Use find to locate
find . -name "processor.ts" 2>/dev/null
# If contributor not found
# → List all contributors
git shortlog -sn | head -10
If Commit Count Discrepancy Large (>30%)
Likely causes:
- Git log time filter different from code-maat
- Branch filtering issues (--all vs single branch)
- Git history rewritten recently
Action:
- Regenerate git log with explicit date range
- Verify code-maat ran successfully
- Check if repository had recent force push
Best Practices
- Always verify file paths - Files may be renamed/deleted after analysis
- Sample at least 3 hotspots - Ensures code-maat output is accurate
- Check contributor spelling - Git author names may have variations
- Verify coupling makes sense - Both files should be in same repository
- Note all corrections - Transparency builds trust
Verification Checklist
Before finalizing output, confirm:
- All hotspot file paths verified to exist (sample 3-5)
- Total commit count reasonable (within ±20% of git rev-list --count)
- Top contributors verified against git shortlog
- Coupling pairs verified (both files exist)
- Date ranges within actual repository history
- LOC counts match current file sizes (use wc -l)
- No placeholder values like "[N]" or "[file]" in output
Handoff to Next Steps
After verification:
- ✅ If confidence HIGH → Proceed to output
- ⚠️ If confidence MEDIUM → Include verification notes, warn user
- ❌ If confidence LOW → Re-execute entire analysis
See reference.md#handoffs for when to suggest next commands.
History Analysis Workflow
Complete step-by-step guide for git temporal analysis using code-maat.
Overview
This workflow uses code-maat to analyze git history and extract:
- Hotspots - Frequently changed files (complexity indicators)
- Temporal Coupling - Files that change together (hidden dependencies)
- Recent Contributors - Knowledge distribution (bus factor risks)
Time Budget: 5-10 minutes total
Step 0: Check Prerequisites (30 seconds)
Check code-maat Installation
# Check if CODEMAAT_JAR is set
if [ -z "$CODEMAAT_JAR" ]; then
# Check default location
if [ -f "$HOME/.sourceatlas/bin/code-maat-1.0.4-standalone.jar" ]; then
export CODEMAAT_JAR="$HOME/.sourceatlas/bin/code-maat-1.0.4-standalone.jar"
echo "✅ code-maat found at $CODEMAAT_JAR"
else
echo "⚠️ code-maat not found."
fi
fi
If code-maat Not Found
Use AskUserQuestion tool:
questions:
- header: "Install Tool"
question: "code-maat is required for git history analysis. Install now? (requires Java 8+)"
multiSelect: false
options:
- label: "Yes, install"
description: "Run installation script automatically"
- label: "No, skip"
description: "Show manual installation instructions"
If User Agrees to Install
# Run installation script
./scripts/install-codemaat.sh
# Verify installation
if [ -f "$HOME/.sourceatlas/bin/code-maat-1.0.4-standalone.jar" ]; then
export CODEMAAT_JAR="$HOME/.sourceatlas/bin/code-maat-1.0.4-standalone.jar"
echo "✅ code-maat installed successfully!"
else
echo "❌ Installation failed. Please check Java installation."
exit 1
fi
Verify code-maat Works
java -jar "$CODEMAAT_JAR" -h > /dev/null 2>&1
if [ $? -ne 0 ]; then
echo "❌ code-maat installation is broken. Please reinstall."
exit 1
fi
Check Java Installation
java -version 2>&1 | head -1
If Java not found, inform user:
⚠️ Java 8+ required for code-maat
Install: brew install openjdk@11
Step 1: Generate Git Log (1 minute)
Default: Last 12 Months
# Generate code-maat compatible git log
git log --all --numstat --date=short \
--pretty=format:'--%h--%ad--%aN' \
--after="$(date -v-12m +%Y-%m-%d 2>/dev/null || date -d '12 months ago' +%Y-%m-%d)" \
> /tmp/git-history.log
# Count commits and files
COMMIT_COUNT=$(grep -c "^--" /tmp/git-history.log)
FILE_COUNT=$(awk 'NF==3 && $1 ~ /^[0-9]+$/' /tmp/git-history.log | cut -f3 | sort -u | wc -l)
echo "📊 Analyzed: $COMMIT_COUNT commits, $FILE_COUNT unique files"
If Scope Specified
If user provides scope (e.g., "src/", "frontend"):
# Filter to specific directory
SCOPE="src/"
git log --all --numstat --date=short \
--pretty=format:'--%h--%ad--%aN' \
--after="$(date -v-12m +%Y-%m-%d)" \
-- "$SCOPE" > /tmp/git-history.log
Custom Time Range
If user specifies time range (e.g., "last 6 months"):
# Parse time range
MONTHS=6
git log --all --numstat --date=short \
--pretty=format:'--%h--%ad--%aN' \
--after="$(date -v-${MONTHS}m +%Y-%m-%d)" \
> /tmp/git-history.log
Validate Log Size
# Check if history is sufficient
if [ $COMMIT_COUNT -lt 50 ]; then
echo "⚠️ Only $COMMIT_COUNT commits found"
echo "Temporal analysis works best with >50 commits"
fi
Step 2: Hotspot Analysis (2 minutes)
Run Revisions Analysis
java -jar "$CODEMAAT_JAR" -l /tmp/git-history.log -c git2 -a revisions \
2>/dev/null > /tmp/revisions.csv
Output format:
entity,n-revs
src/core/processor.ts,45
src/api/handlers.ts,38
...
Identify Top 10 Hotspots
# Sort by revision count descending
cat /tmp/revisions.csv | tail -n +2 | sort -t, -k2 -nr | head -10 > /tmp/hotspots.csv
Calculate Complexity Scores
For each hotspot, calculate: LOC × Revisions
while IFS=, read -r file revs; do
if [ -f "$file" ]; then
LOC=$(wc -l < "$file" 2>/dev/null || echo 0)
COMPLEXITY=$((LOC * revs))
echo "$file,$revs,$LOC,$COMPLEXITY"
fi
done < /tmp/hotspots.csv > /tmp/hotspots-with-loc.csv
Interpret Hotspots
High complexity score (>10,000):
- Indicates frequently changed, large files
- Potential technical debt
- Refactoring candidates
High revision count, low LOC:
- Configuration files (normal)
- Small utility files (normal)
Low revision count, high LOC:
- Stable, mature code
- May need modernization
Step 3: Temporal Coupling Analysis (2 minutes)
Run Coupling Analysis
java -jar "$CODEMAAT_JAR" -l /tmp/git-history.log -c git2 -a coupling \
2>/dev/null > /tmp/coupling.csv
Output format:
entity,coupled,degree,average-revs
src/user/model.ts,src/user/service.ts,0.85,23
src/api/auth.ts,src/middleware/jwt.ts,0.72,18
...
Filter Significant Couplings
# Filter coupling degree >= 0.5
awk -F, 'NR>1 && $3 >= 0.5' /tmp/coupling.csv | \
sort -t, -k3 -nr | \
head -20 > /tmp/significant-coupling.csv
Categorize Couplings
Expected Couplings (normal):
- Model ↔ Service (same domain)
- Test ↔ Production code
- Component ↔ Component styles
Suspicious Couplings (review needed):
- Cross-layer: Controller ↔ View
- Cross-module: User ↔ Payment
- Backend ↔ Frontend
Interpret Coupling Degrees
| Degree | Meaning | Action |
|---|---|---|
| 0.9-1.0 | Always change together | Consider merging files |
| 0.7-0.9 | Very strong coupling | Review dependency |
| 0.5-0.7 | Moderate coupling | Monitor |
| <0.5 | Weak coupling | Normal |
Step 4: Recent Contributors Analysis (2 minutes)
Run Entity Ownership Analysis
java -jar "$CODEMAAT_JAR" -l /tmp/git-history.log -c git2 -a entity-ownership \
2>/dev/null > /tmp/ownership.csv
Output format:
entity,author,added,deleted
src/api/handlers.ts,Alice,234,45
src/api/handlers.ts,Bob,89,12
...
Generate Knowledge Map by Area
# Most recent commits per area
for area in "src/api/" "src/core/" "src/components/"; do
echo "=== $area ==="
git log --pretty=format:'%an|%ad|%s' --date=short -- "$area" | head -5
done
Identify Bus Factor Risks
# Files with single contributor in last 6 months
git log --all --numstat --date=short \
--pretty=format:'--%h--%ad--%aN' \
--after="$(date -v-6m +%Y-%m-%d)" \
> /tmp/recent-6m.log
java -jar "$CODEMAAT_JAR" -l /tmp/recent-6m.log -c git2 -a entity-ownership \
2>/dev/null | awk -F, 'NR>1 {count[$1]++} END {for (f in count) if (count[f]==1) print f}'
High bus factor risk:
- Only 1 contributor in last 6 months
- Primary contributor no longer active
- Critical files with concentrated knowledge
Step 5: Risk Assessment (1 minute)
Calculate Composite Risk Scores
Combine multiple dimensions:
# Risk = (Revisions × Coupling_Count) / Contributor_Count
# Example: processor.ts
# - 45 revisions
# - Coupled with 3 other files
# - 2 contributors
# Risk = (45 × 3) / 2 = 67.5 (HIGH)
Risk Categories
1. Bus Factor Risk
- Single contributor files
- No recent activity (>6 months)
- Critical path files
2. Complexity Risk
- High revision count (>30 in 12 months)
- High LOC (>500 lines)
- Complexity score >10,000
3. Coupling Risk
- Coupled with >5 files
- Cross-module coupling (suspicious)
- High coupling degree (>0.8)
4. Testing Gap Risk
- Hotspot without test file
- Test file change frequency < 20% of production changes
Priority Ranking
🔴 HIGH RISK:
- Bus factor + Complexity + No tests
🟡 MEDIUM RISK:
- Coupling risk + High revisions
🟢 LOW RISK:
- High revisions but well-tested
- Multiple contributors
Error Handling
Issue: Git History Too Short
if [ $COMMIT_COUNT -lt 50 ]; then
echo "⚠️ Only $COMMIT_COUNT commits found"
echo ""
echo "Temporal analysis works best with >50 commits."
echo ""
echo "Consider:"
echo "- Extending time range"
echo "- Analyzing entire repository history"
exit 0
fi
Issue: No Significant Patterns
If all couplings < 0.5 and hotspots < 10 revisions:
✅ No significant temporal patterns detected.
This could mean:
- Clean architecture with good separation
- Young codebase with limited history
- Inconsistent commit practices (large commits)
Issue: code-maat Fails
if ! java -jar "$CODEMAAT_JAR" -h > /dev/null 2>&1; then
echo "❌ code-maat failed to run"
echo ""
echo "Possible causes:"
echo "1. Java not installed (brew install openjdk@11)"
echo "2. JAR file corrupted (re-run install script)"
echo "3. Incompatible Java version (need Java 8+)"
exit 1
fi
Output Generation Tips
Hotspot Table
| Rank | File | Changes | LOC | Complexity Score |
|------|------|---------|-----|------------------|
| 1 | src/core/processor.ts | 45 | 892 | 40,140 |
Insights:
- Reference specific complexity scores
- Mention if file lacks tests
- Suggest concrete actions (refactor, document, test)
Coupling Table
| File A | File B | Coupling | Co-changes |
|--------|--------|----------|------------|
| src/user/model.ts | src/user/service.ts | 0.85 | 23 |
Insights:
- Distinguish expected vs suspicious coupling
- Reference architectural concerns
- Note if cross-layer or cross-module
Knowledge Map
### src/api/
| Contributor | Recent Commits | Last Active |
|-------------|----------------|-------------|
| Alice | 12 | 2025-11-28 |
Insights:
- Highlight bus factor risks
- Note inactive contributors
- Suggest knowledge transfer actions
Performance Optimization
For Large Repositories
# Limit git log to avoid timeout
git log --all --numstat --date=short \
--pretty=format:'--%h--%ad--%aN' \
--after="$(date -v-6m +%Y-%m-%d)" \
--max-count=1000 \
> /tmp/git-history.log
For Monorepos
# Analyze specific module only
git log --all --numstat --date=short \
--pretty=format:'--%h--%ad--%aN' \
-- "packages/app/" \
> /tmp/git-history.log
Integration with Other Commands
After history analysis, suggest:
- High-risk hotspot found →
/sourceatlas:impact "[hotspot]" - Suspicious coupling →
/sourceatlas:flow "[entry point]" - Need refactoring guidance →
/sourceatlas:pattern "[pattern]"
SourceAtlas: Impact Analysis (Static Dependencies)
Constitution: 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)
Context
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.
Quick Start
- Check cache (if no
--forceflag) → See reference.md#cache-behavior - Execute analysis using workflow.md
- Verify output using verification-guide.md
- Auto-save to
.sourceatlas/impact/→ See reference.md#auto-save
Your Task
You are SourceAtlas Impact Analyzer, specialized in tracing static dependencies and identifying change impact.
Help the user understand:
- What code directly depends on the target
- What code indirectly depends on it (call chains)
- Which tests need updating
- Migration checklist and risk assessment
Core Workflow
Follow these high-level steps. For detailed instructions, see workflow.md.
Step 1: Parse Target and Detect Type (1 minute)
Determine analysis type: API, MODEL, or COMPONENT
→ See workflow.md#step-1
Step 2: Project Context Detection (1 minute)
Detect project type and key directories to scan.
→ See workflow.md#step-2
Step 2.5: ast-grep Enhanced Search (Optional)
Use ast-grep for precise dependency search with false positive elimination.
→ See workflow.md#step-25
Step 3: Execute Impact Analysis (3-5 minutes)
Type-specific analysis:
- API: Backend → Type Definitions → Frontend → Hooks → Components
- MODEL: Model → Dependencies → Associations → Business Logic
- COMPONENT: Locate → Imports → Usage → Categorization
CRITICAL: Use exact counts (not estimates), mutually exclusive categories.
→ See workflow.md#step-3
Step 4: Test Impact Analysis (1-2 minutes)
Find related tests and analyze coverage gaps.
→ See workflow.md#step-4
Step 5: Language-Specific Deep Analysis (Optional)
For iOS/Swift projects: Run Swift/Objective-C interop analysis.
→ See workflow.md#step-5
Step 6: Risk Assessment (1 minute)
Evaluate impact level: 🟢 LOW / 🟡 MEDIUM / 🔴 HIGH
Risk Factors:
- Number of direct dependents (>10 = HIGH)
- Presence in critical path (auth, payment = HIGH)
- Test coverage (<50% = HIGH risk)
- Type of change (breaking change = HIGH)
→ See workflow.md#step-6
Output Format
Your analysis should follow this structure:
🗺️ SourceAtlas: Impact
───────────────────────────────
💥 $TARGET │ [total dependents] dependents
📊 Impact Summary
1. Backend/Frontend/Model Layer
2. Component Impact
3. Field Usage Analysis (if applicable)
4. Test Impact
5. Migration Checklist
6. Language-Specific Analysis (iOS only)
7. Recommendations
→ See output-template.md for complete template
Critical Rules
- Static Analysis Only: Analyze code structure, not runtime behavior
- Evidence-Based: Every claim must reference file:line
- Prioritize Impact: Show high-priority dependencies first
- Practical Output: Focus on actionable migration steps
- Risk Assessment: Always provide risk level and reasoning
- Test First: Identify test gaps before changes
- Time Limit: Complete analysis in 5-10 minutes
- Exact Counts: Use actual grep results, not estimates
- Verification Required: Run verification-guide.md before output
Error Handling
If target not found:
- Search with fuzzy matching
- Suggest similar components
- Ask user to clarify
If too many results (>100):
- Sample top 20-30 most relevant
- Group by category (controllers, services, etc.)
- Warn about incomplete analysis
If no dependencies found:
- Verify target exists
- Check if it's a leaf component (no dependents)
- Suggest dead code possibility
→ See workflow.md#error-handling for details
Self-Verification (REQUIRED)
Before outputting results, run verification checks:
- Extract verifiable claims (file paths, counts, imports)
- Execute parallel verification (bash script)
- Handle failures (fix or remove incorrect claims)
- Append verification summary to output
→ See verification-guide.md for complete checklist
Advanced
- Cache behavior: reference.md#cache-behavior
- Auto-save: reference.md#auto-save
- Handoffs rules: reference.md#handoffs
- Best practices: reference.md#best-practices
- Large codebase tips: reference.md#tips-for-complex-projects
Support Files
- workflow.md - Detailed step-by-step execution guide
- output-template.md - Complete output format specification
- verification-guide.md - Verification checklist and error handling
- reference.md - Cache, Auto-Save, Handoffs, best practices
Impact Analysis Output Template
Complete format specification for impact analysis reports.
For API Impact
🗺️ 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
...
}
2. Frontend Layer
API Client/Service
- File: [path:line]
- Wrapper function: [function name]
Custom Hooks (React)
useUser([path:line])- Used by [count] components
- Components: [list]
Direct API Calls
- [component:line] - [usage description]
3. Component Impact
High Priority (Directly affected):
-
[Component A] ([path:line])
- Usage: [how it uses the API/field]
- Impact: [what breaks]
-
[Component B] ([path:line])
- Usage: [description]
Medium Priority (Indirectly affected): 3. [Component C] - Uses Hook that wraps API
4. Field Usage Analysis
Field: role (⚠️ Changing from string → array)
- Total occurrences: [count]
- Locations:
- [file:line] -
if (user.role === 'admin') - [file:line] -
user.role.toUpperCase()
- [file:line] -
Breaking Change Assessment:
- All usages assume string type
- Migration required: Yes
- Backward compatibility: Possible with adapter
5. Test Impact
Test Files to Update:
user.test.ts- Mock data structureuseUser.test.ts- Hook logicUserBadge.test.tsx- Component renderinge2e/user-profile.spec.ts- E2E scenarios
Test Coverage Gaps:
- ⚠️ No tests for [Component X]
- ⚠️ Missing integration tests for [Flow Y]
6. Migration Checklist
- Update API response type definition
- Update [N] API call sites
- Update [N] components using the field
- Add backward compatibility layer (if needed)
- Update [N] test files
- Test all affected pages manually
- 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.
7. Language-Specific Deep Analysis
⚠️ Swift/Objective-C Interop Risks (iOS Projects Only)
Critical Issues 🔴
Nullability Coverage: [X]% ([N] files missing NS_ASSUME_NONNULL)
- Impact: Runtime crashes due to force unwrapping operator (!)
- Auto-fix: Run provided sed script to add annotations
- Priority: CRITICAL - Fix before making changes
Medium Risks 🟡
@objc Exposure: [N] classes + [M] @objcMembers
- Classes exposing members to Objective-C
- Risk: Renaming/removing will break ObjC callers
- Target file impact: [Is/Is not] in interop boundary
Memory Management: [N] unowned references detected
- Risk: Crashes if referenced object is deallocated
- Recommendation: Review and convert to
weakwhere appropriate
Architecture Info ℹ️
UI Framework: [SwiftUI|UIKit|Hybrid]
- SwiftUI files: [N]
- UIKit files: [M]
- Integration points: [N] UIViewRepresentable, [M] UIHostingController
Bridging Headers: [N] found
- Largest imports: [N] headers
- Circular dependencies: [None|Detected]
💡 Full Swift Analysis: Run /sourceatlas:impact [target].m to see complete 7-section analysis
8. Recommendations
- [Recommendation 1]
- [Recommendation 2]
- [Recommendation 3]
---
## 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)*
Field Descriptions
Impact Summary
- Backend/Frontend/Test files: Count of impacted files by category
- Risk Level: Overall assessment based on dependency count, criticality, and test coverage
Component Impact Sections
- High Priority: Components directly using the target (will break immediately)
- Medium Priority: Components indirectly using target (may break)
Field Usage Analysis
- Total occurrences: Exact count from grep
- Locations: File:line references with code snippet
- Breaking Change Assessment: Migration complexity evaluation
Test Impact
- Test Files to Update: Specific test files needing changes
- Coverage Gaps: Missing tests that should be added
Migration Checklist
- Concrete, actionable steps
- Each item should be measurable
- Include counts where known ([N] files)
Language-Specific Deep Analysis
- Only include for iOS/Swift projects
- Focus on interop risks and architecture
- Provide actionable recommendations
Impact Analysis Reference
Advanced features and behaviors reference.
Cache Behavior
Cache Check (Highest Priority)
If --force is not in arguments, check cache first:
-
Extract target name from
$ARGUMENTS(remove--force) -
Convert to filename: spaces →
-, slashes →-, lowercase, remove{}, truncate to 50 characters- Example:
"User model"→user-model.md - Example:
"api /api/users/{id}"→api-users-id.md
- Example:
-
Check cache:
ls -la .sourceatlas/impact/{name}.md 2>/dev/null -
If cache exists:
- Calculate days since creation
- Read cache content using Read tool
- Output:
📁 Loading from cache: .sourceatlas/impact/{name}.md (N days ago) 💡 Use --force to reanalyze --force - If over 30 days, additionally display:
⚠️ Cache is over 30 days old, recommend reanalysis - Then output:
--- [Cache content] - End, do not execute subsequent analysis
-
If cache does not exist: Continue with analysis below
If arguments contain --force: Skip cache check, run analysis directly
Auto-Save (Default Behavior)
After analysis completes, automatically:
Step 1: Parse target name
Extract target name from arguments (remove --force):
"User model"→ target name isuser-model"api /api/users/{id}"→ target name isapi-users-id
Convert to filename:
- Spaces →
- - Slashes →
- - Remove
{,}, special characters - Lowercase
- Example:
"User model"→user-model.md
Step 2: Create directory
mkdir -p .sourceatlas/impact
Step 3: Save output
After generating the complete analysis, save the entire output (from 🗺️ SourceAtlas: Impact to the end) to .sourceatlas/impact/{name}.md
Step 4: Confirm
Add at the very end:
💾 Saved to .sourceatlas/impact/{name}.md
Handoffs (Recommended Next)
Follows 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.13.1 │ Constitution v1.1
End Conditions vs Recommendations (choose one, mutually exclusive)
⚠️ 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:
- Impact scope is small: <5 dependencies, no further analysis needed
- Findings too vague: Cannot provide with high confidence (>0.7) specific parameters
- Analysis depth sufficient: Already executed 4+ commands
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.
Recommendation Selection (applies to Situation B)
| 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 |
Output Format
Use numbered table for quick selection.
Quality Requirements
- Specific parameters: Use actual found file names or entry point
- Quantity limit: 1-2 recommendations, not required to fill all
- Purpose column: Reference specific findings (dependency count, risk level, issues)
Best Practices
For Accurate Analysis
- Use precise grep patterns: Match import statements, not comments
- Follow the call chain: From definition → usage → components
- Check test files separately: Different directory structure
- Consider indirect dependencies: Hooks/Services wrapping the target
Language-Specific Search Patterns
TypeScript/JavaScript:
# Imports
grep -r "import { UserService } from\|import UserService from" --include="*.ts"
# Usage
grep -r "UserService\.\|new UserService(" --include="*.ts"
Ruby:
# Requires
grep -r "require.*user\|require_relative.*user" --include="*.rb"
# Usage
grep -r "User\.create\|User\.find\|User\.where" --include="*.rb"
Go:
# Imports
grep -r 'import.*".*user"' --include="*.go"
# Usage
grep -r "user\.\|User{" --include="*.go"
Python:
# Imports
grep -r "from.*user import\|import user" --include="*.py"
# Usage
grep -r "User(\|user\." --include="*.py"
Deprecated Features
--save flag
If --save is in arguments:
- Show:
⚠️ --save is deprecated, auto-save is now default - Remove
--savefrom arguments - Continue normal execution (still auto-saves)
Tips for Complex Projects
Large Codebases (>100 dependencies)
When facing too many results:
- Sample top 20-30 most relevant
- Group by category (controllers, services, components)
- Provide statistical summary instead of full list
- Warn about incomplete analysis
Example:
📊 **Impact Summary** (sampled from 156 total dependencies):
- Controllers: 23 files
- Services: 45 files
- Components: 88 files
⚠️ Showing top 20 high-priority dependencies. Run with specific filters for complete analysis.
Monorepos
Specify scope to avoid false positives:
# Instead of searching entire repo
grep -r "UserService" .
# Search specific packages
grep -r "UserService" packages/backend/ packages/api/
False Positive Reduction
Exclude common noise:
grep -r "UserService" . \
| grep -v "node_modules" \
| grep -v ".git" \
| grep -v "coverage" \
| grep -v "build" \
| grep -v "dist"
Impact Analysis Verification Guide
Prevent hallucinated file paths, incorrect dependency counts, and fictional impact assessments.
When to Run: After output generation, BEFORE save
Step V1: Extract Verifiable Claims
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 |
Step V2: Parallel Verification Execution
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
Step V3: Handle Verification Results
If ALL checks pass
- Continue to output/save
If ANY check fails
- DO NOT output the uncorrected analysis
- Fix each failed claim:
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 line
- Re-generate affected sections with corrected information
- Re-run verification on corrected sections
Step V4: Verification Summary
Add to footer (before 🗺️ v2.13.1 │ 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
Verification Checklist
Before finalizing output, confirm:
- Target file verified to exist
- All impacted file paths verified to exist
- Dependency count verified against actual grep results
- Import relationships verified via grep
- Line number references verified (content is relevant)
Common Verification Errors
Error: TARGET_NOT_FOUND
Cause: Target file path doesn't exist
Fix:
# Find the correct path
find . -name "*UserService*" -type f | grep -v node_modules | grep -v test
# Update output with correct path
Error: DEP_COUNT_MISMATCH
Cause: Claimed count doesn't match actual grep results
Fix:
# Recount dependencies
actual_count=$(grep -rl "UserService" src/ | wc -l | tr -d ' ')
# Update output with actual count
Error: IMPORT_NOT_FOUND
Cause: Claimed import statement doesn't exist in file
Fix:
# Verify import exists
grep "import.*UserService" src/api/auth.ts
# If not found, remove this dependency from report
Error: LINE_NOT_FOUND
Cause: Referenced line number doesn't exist or file is shorter
Fix:
# Check actual file length
wc -l src/services/UserService.ts
# Re-read file and find correct line
# Update line number in output
Verification Examples
Example 1: Verify dependency count
# Claim: "12 direct dependencies on UserService"
claimed=12
actual=$(grep -rl "import.*UserService\|from.*UserService" src/ | wc -l | tr -d ' ')
if [ "$actual" != "$claimed" ]; then
echo "⚠️ Count mismatch: claimed $claimed, actual $actual"
# Update output with actual count
fi
Example 2: Verify file paths
# Claim: Impact analysis lists 5 files
files=(
"src/api/users.ts"
"src/components/UserBadge.tsx"
"src/hooks/useUser.ts"
"src/services/UserService.ts"
"src/types/user.d.ts"
)
for file in "${files[@]}"; do
if [ ! -f "$file" ]; then
echo "❌ File not found: $file"
fi
done
Example 3: Verify import relationships
# Claim: "UserBadge.tsx imports useUser hook"
if ! grep -q "import.*useUser\|from.*useUser" "src/components/UserBadge.tsx"; then
echo "❌ Import not found: useUser in UserBadge.tsx"
# Remove this claim from output
fi
Quality Assurance
High Confidence Required
Only include claims with >90% confidence:
- File paths you've actually Read
- Counts from actual grep results
- Import statements you've verified
Exclude Low Confidence
Remove claims based on:
- Assumptions without verification
- Estimated counts (use "~")
- Speculative dependencies
Impact Analysis Workflow
Complete step-by-step guide for executing static dependency analysis.
Step 1: Parse Target and Detect Type (1 minute)
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:
- API: Backend → Frontend call chain
- MODEL: Database layer → Business logic → Controllers
- COMPONENT: General dependency search
Step 2: Project Context Detection (1 minute)
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:
- Backend:
src/,app/,lib/,api/ - Frontend:
components/,pages/,app/,hooks/,utils/ - Tests:
__tests__/,spec/,test/,*.test.*,*.spec.* - Types:
types/,*.d.ts,interfaces/ - iOS:
Sources/,**/Classes/,*.xcodeproj/,Tests/
Step 2.5: ast-grep Enhanced Search (Optional, P1 Enhancement)
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:
- Swift UserDto dependencies: 93% false positive elimination
- TypeScript useState: 15% false positive elimination
- Kotlin ViewModel: 92% false positive elimination
Graceful Degradation: Script automatically handles ast-grep unavailability, using --fallback to get equivalent grep command.
Step 3: Execute Impact Analysis (3-5 minutes)
For API Impact (Type: API)
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
For Model Impact (Type: MODEL)
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)- Foreign keys and references
- Validation rules
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
For General Component (Type: COMPONENT)
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"
Step 4: Test Impact Analysis (1-2 minutes)
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:
- Are there tests for the target component?
- Are there integration tests?
- Are there E2E tests covering the flow?
Step 5: Language-Specific Deep Analysis (1-2 minutes, optional)
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:
- Nullability annotation coverage (CRITICAL for Swift interop)
- @objc exposure detection (breaking change risks)
- Memory management warnings (unowned, retain cycles)
- Bridging header circular dependency checks
- SwiftUI vs UIKit architecture detection
Integration: Include key findings in the final report's "Language-Specific Risks" section
Step 6: Risk Assessment (1 minute)
Evaluate impact level based on findings:
Risk Factors:
- Number of direct dependents (>10 = HIGH)
- Presence in critical path (auth, payment = HIGH)
- Test coverage (<50% = HIGH risk)
- Type of change (breaking change = HIGH)
Risk Levels:
- 🟢 LOW: 1-5 dependents, well-tested, non-critical
- 🟡 MEDIUM: 5-15 dependents, partial tests, business logic
- 🔴 HIGH: >15 dependents OR critical path OR breaking change
Error Handling
If target not found:
- Search with fuzzy matching
- Suggest similar components
- Ask user to clarify
If too many results (>100):
- Sample top 20-30 most relevant
- Group by category (controllers, services, etc.)
- Warn about incomplete analysis
If no dependencies found:
- Verify target exists
- Check if it's a leaf component (no dependents)
- Suggest dead code possibility
Tips for Accurate Analysis
- Use precise grep patterns: Match import statements, not comments
- Follow the call chain: From definition → usage → components
- Check test files separately: Different directory structure
- Consider indirect dependencies: Hooks/Services wrapping the target
- Language-specific patterns:
- TypeScript:
import { X } from,X.method(), type definitions - Ruby:
require,include,Class.method - Go:
import, package usage - Python:
from X import,import X
- TypeScript:
SourceAtlas: List Saved Results
Your Task
List all saved analysis results in the .sourceatlas/ directory.
Step 1: Check directory exists
ls -la .sourceatlas/ 2>/dev/null || echo "NOT_FOUND"
If output contains NOT_FOUND or directory is empty:
📁 No saved analyses yet
Use the `--save` parameter to save analysis results:
- `/sourceatlas:overview --save`
- `/sourceatlas:pattern "api" --save`
- `/sourceatlas:history --save`
End.
Step 2: List all files with details
find .sourceatlas -type f -exec ls -lh {} \; 2>/dev/null | sort
Step 3: Format output
Format results into a table, calculate days since modification, and mark expired status (>30 days):
📁 .sourceatlas/ saved analyses:
| Type | File | Size | Modified | Status |
|------|------|------|----------|--------|
| overview | overview.yaml | 2.3 KB | 3 days ago | ✅ |
| pattern | patterns/api.md | 1.5 KB | 45 days ago | ⚠️ |
| pattern | patterns/repository.md | 2.1 KB | 5 days ago | ✅ |
| history | history.md | 4.2 KB | 60 days ago | ⚠️ |
| flow | flows/checkout.md | 3.1 KB | 2 days ago | ✅ |
| impact | impact/user-model.md | 1.8 KB | 4 days ago | ✅ |
| deps | deps/react.md | 2.5 KB | 6 days ago | ✅ |
📊 Stats: 7 cached, 2 expired (>30 days)
💡 Tips:
- Clear cache: `/sourceatlas:reset`
- Clear specific type: `/sourceatlas:reset patterns`
Step 4: List expired items with refresh commands
If there are expired items (>30 days), output copyable re-analysis commands:
⚠️ Expired items (recommend re-analysis):
| File | Days | Re-analyze Command |
|------|------|-------------------|
| patterns/api.md | 45 days | `/sourceatlas:pattern "api" --force --save` |
| history.md | 60 days | `/sourceatlas:history --force --save` |
💡 Copy the commands above to re-analyze
Command generation rules:
| Type | Command Format |
|---|---|
| overview | /sourceatlas:overview --force --save |
| overview-{dir} | /sourceatlas:overview {dir} --force --save |
| patterns/{name}.md | /sourceatlas:pattern "{name}" --force --save |
| history.md | /sourceatlas:history --force --save |
| flows/{name}.md | /sourceatlas:flow "{name}" --force --save |
| impact/{name}.md | /sourceatlas:impact "{name}" --force --save |
| deps/{name}.md | /sourceatlas:deps "{name}" --force --save |
Note: Convert - in filenames back to spaces for parameters (e.g., api-endpoint.md → "api endpoint")
Type Detection Rules
| File Path | Type |
|---|---|
overview.yaml or overview-*.yaml | overview |
patterns/*.md | pattern |
flows/*.md | flow |
history.md | history |
impact/*.md | impact |
deps/*.md | deps |
SourceAtlas: Project Overview (Stage 0 Fingerprint)
Constitution: ANALYSIS_CONSTITUTION.md v1.0
Context
Arguments: ${ARGUMENTS:-.}
Goal: Generate project fingerprint by scanning <5% of files to achieve 70-80% understanding in 10-15 minutes.
Auto-Save: Results automatically saved to .sourceatlas/overview.yaml (or subdirectory-specific path)
Time Limit: 10-15 minutes (typically 0-5 minutes)
Cache Check (Highest Priority)
If --force is NOT in arguments, check cache first:
-
Calculate cache path:
- No path argument or
.:.sourceatlas/overview.yaml - With path (e.g.,
src/api):.sourceatlas/overview-src-api.yaml
- No path argument or
-
Check if cache exists:
ls -la .sourceatlas/overview.yaml 2>/dev/null -
If cache exists:
- Calculate days since modification
- Use Read tool to read cache
- Output:
📁 Loading cache: .sourceatlas/overview.yaml (N days ago) 💡 Add --force to re-analyze - If over 30 days: Show warning
- Output cache content
- End, do not execute analysis
-
If cache does not exist: Continue with analysis
If --force is in arguments: Skip cache, execute analysis
Your Task
Execute Stage 0 Analysis Only - generate project fingerprint using information theory principles.
Information Theory Approach:
- High-entropy files contain disproportionate information
- Scan priority: Documentation → Configuration → Models → Entry Points → Tests
- Scale-aware: TINY/SMALL/MEDIUM/LARGE/VERY_LARGE projects need different approaches
Core Workflow
Execute these phases in order. See workflow.md for complete details.
Phase 1: Project Detection & Scale-Aware Planning (2-3 minutes)
Purpose: Detect project type, count files, determine scale, set scan limits.
Execute detection:
# Try helper script first (recommended)
if [ -f ~/.claude/scripts/atlas/detect-project.sh ]; then
bash ~/.claude/scripts/atlas/detect-project.sh ${ARGUMENTS:-.}
elif [ -f scripts/atlas/detect-project.sh ]; then
bash scripts/atlas/detect-project.sh ${ARGUMENTS:-.}
else
echo "Warning: detect-project.sh not found, using manual detection"
fi
Scale-Aware Scan Limits:
- TINY (<5 files): 1-2 files (50% max)
- SMALL (5-15 files): 2-3 files (10-20%)
- MEDIUM (15-50 files): 4-6 files (8-12%)
- LARGE (50-150 files): 6-10 files (4-7%)
- VERY_LARGE (>150 files): 10-15 files (3-7%)
→ See workflow.md#phase-1 for manual fallback
Phase 2: High-Entropy File Prioritization (5-8 minutes)
Purpose: Scan highest information-density files first.
Scan Priority Order:
- Documentation (README.md, CLAUDE.md, docs/)
- Configuration (package.json, docker-compose.yml, etc.)
- Core Models (models/, entities/, domain/) - pick 2-3 only
- Entry Points (app.ts, routes/) - pick 1-2 examples
- Tests - pick 1-2 examples
Execute scanning:
# Use helper script if available
if [ -f ~/.claude/scripts/atlas/scan-entropy.sh ]; then
bash ~/.claude/scripts/atlas/scan-entropy.sh ${ARGUMENTS:-.}
else
echo "Warning: scan-entropy.sh not found, scanning manually"
fi
AI Tool Detection:
# Detect AI collaboration level (Tier 1 + Tier 2)
if [ -f ~/.claude/scripts/atlas/detect-ai-tools.sh ]; then
bash ~/.claude/scripts/atlas/detect-ai-tools.sh ${ARGUMENTS:-.}
else
# Fallback: manual checks
ls -la CLAUDE.md .cursorrules .windsurfrules CONVENTIONS.md AGENTS.md .aiignore 2>/dev/null
ls -la .claude/ .cursor/rules/ .windsurf/rules/ .clinerules/ .roo/ .continue/rules/ .ruler/ 2>/dev/null
fi
→ See workflow.md#phase-2 for manual commands
Phase 3: Generate Hypotheses (3-5 minutes)
Purpose: Generate scale-appropriate hypotheses with confidence levels and evidence.
Hypothesis Categories:
- Technology Stack: Languages, frameworks, databases, testing
- Architecture: Patterns, structure, layering
- Development Practices: Code quality, testing, documentation
- AI Collaboration: Tool detection (Level 0-4)
- Business Domain: Purpose, entities, features
Scale-Aware Targets:
- TINY: 5-8 hypotheses
- SMALL: 7-10 hypotheses
- MEDIUM: 10-15 hypotheses
- LARGE: 12-18 hypotheses
- VERY_LARGE: 15-20 hypotheses
Each hypothesis must include:
- hypothesis: Clear statement
- confidence: 0.0-1.0 (aim for >0.7)
- evidence: file:line references
- validation_method: How to verify
→ See workflow.md#phase-3 for detailed guidance
Output Format
Generate output with branded header, then YAML format:
🗺️ SourceAtlas: Overview
───────────────────────────────
🔭 [project_name] │ [SCALE] ([file count] files)
Then YAML content with sections:
metadata: project_name, scan_time, total_files, scanned_files, scan_ratio, project_scale, contextproject_fingerprint: project_type, scale, primary_language, framework, architecturetech_stack: backend, frontend (optional), infrastructure (optional)hypotheses: architecture, tech_stack, development, ai_collaboration, businessscanned_files: List with file, reason, key_insightsummary: understanding_depth, key_findings
→ See output-template.md for complete YAML structure and examples
Critical Rules
- Scale-Aware Scanning: Follow recommended file limits from Phase 1
- Exclude Common Bloat: Never scan .venv/, node_modules/, vendor/, pycache, .git/
- Time Limit: Complete in 10-15 minutes (typically 0-5 minutes)
- Hypothesis Quality: Each must have confidence >0.7 and evidence
- Scale-Aware Targets: Use hypothesis targets appropriate for project scale
- No Deep Diving: Understand structure > implementation details
- STOP after Stage 0: Do not proceed to validation or git analysis
Handoffs Decision Rules
Follow Constitution Article VII: Handoffs Principles
⚠️ Choose ONE output, NOT both:
Case A - End (No Table): When any condition is met:
- Project too small: TINY (<10 files)
- Findings too vague: Cannot provide high confidence (>0.7) parameters
- Goal achieved: AI collaboration Level ≥3 and scale TINY/SMALL
Output:
✅ **Analysis sufficient** - Project is small, can read all files directly
Case B - Suggestions (Table): When project scale is large enough or clear next steps exist.
| Finding | Command | Parameter |
|---|---|---|
| Clear patterns | /sourceatlas:pattern | Pattern name |
| Complex architecture | /sourceatlas:flow | Entry point file |
| Scale ≥ LARGE | /sourceatlas:history | No parameters |
| High risk areas | /sourceatlas:impact | Risk file/module |
Format:
## Recommended Next
| # | Command | Purpose |
|---|---------|---------|
| 1 | `/sourceatlas:pattern "repository"` | Found Repository pattern in 15 files |
💡 Enter a number (e.g., `1`) or copy the command to execute
→ See reference.md#handoffs for detailed logic
Self-Verification Phase (REQUIRED)
Purpose: Prevent hallucinated file paths, incorrect counts, fictional configs. Execute AFTER output generation, BEFORE save.
Verification Steps:
Step V1: Extract Verifiable Claims
Extract from generated YAML:
- File paths (
scanned_files[].file) - Config files (
tools_detected[].config_file) - File count (
metadata.total_files) - Git branch (
metadata.context.git_branch) - Evidence references (
hypotheses.*.evidence)
Step V2: Parallel Verification
Run ALL checks in parallel:
- Verify scanned files exist:
test -f path - Verify AI tool configs exist:
test -f config - Verify file count: ±10% tolerance
- Verify git branch:
git branch --show-current - Verify evidence files exist
Step V3: Handle Results
- ✅ All pass → Continue to output/save
- ⚠️ 1-2 fail → Correct claims, note in summary
- ❌ 3+ fail → Re-execute analysis phases
Step V4: Verification Summary
Add to footer:
If all passed:
✅ Verified: [N] scanned files, [M] config paths, file count
If corrected:
🔧 Self-corrected: [list corrections]
✅ Verified: [N] scanned files, [M] config paths, file count
→ See verification-guide.md for complete checklist and examples
Auto-Save (Default Behavior)
After verification passes, automatically:
- Create directory:
mkdir -p .sourceatlas - Save YAML output to:
- Root:
.sourceatlas/overview.yaml - Subdirectory:
.sourceatlas/overview-[path].yaml
- Root:
- Confirm:
💾 Saved to .sourceatlas/overview.yaml
→ See reference.md#auto-save for details
Advanced
- Scale-aware analysis: reference.md#scale-aware-analysis
- Helper scripts: reference.md#helper-scripts
- Cache behavior: reference.md#cache-behavior
- AI collaboration detection: reference.md#ai-collaboration-detection
- Information theory: reference.md#information-theory-principles
Output Header
Start your output with:
🗺️ SourceAtlas: Overview
───────────────────────────────
🔭 [project_name] │ [SCALE] ([file count] files)
Then follow YAML structure in output-template.md.
Overview Output Template
Complete YAML format specification for Stage 0 fingerprint analysis.
Header Format
🗺️ SourceAtlas: Overview
───────────────────────────────
🔭 [project_name] │ [SCALE] ([file count] files)
Example:
🗺️ SourceAtlas: Overview
───────────────────────────────
🔭 sourceatlas2 │ LARGE (127 files)
YAML Structure
Complete YAML output with all sections:
metadata:
project_name: "[detected name]"
scan_time: "[ISO 8601 timestamp]"
target_path: "${ARGUMENTS:-.}"
total_files: [actual count after exclusions]
scanned_files: [files read]
scan_ratio: "[percentage]"
project_scale: "[TINY|SMALL|MEDIUM|LARGE|VERY_LARGE]"
constitution_version: "1.1"
# Branch-Aware Context (v2.8.2)
context:
git_branch: "[branch name or null]"
relative_path: "[path within repo or null]"
package_name: "[detected package name or null]"
project_fingerprint:
project_type: "[WEB_APP|CLI|LIBRARY|MOBILE_APP|MICROSERVICE|MONOREPO]"
scale: "[TINY|SMALL|MEDIUM|LARGE|VERY_LARGE]"
# TINY: <500 LOC, SMALL: 500-2k, MEDIUM: 2k-10k, LARGE: 10k-50k, VERY_LARGE: >50k
primary_language: "[language + version]"
framework: "[framework + version]"
architecture: "[pattern name]"
tech_stack:
backend:
language: "[name + version]"
framework: "[name + version]"
database: "[name + version]"
frontend: # if applicable
language: "[name]"
framework: "[name]"
infrastructure: # if applicable
containerization: "[Docker/none]"
orchestration: "[K8s/none]"
hypotheses:
architecture:
- hypothesis: "[architectural pattern description]"
confidence: 0.0-1.0
evidence: "[file:line references]"
validation_method: "[how to verify]"
tech_stack:
- hypothesis: "[technology decision]"
confidence: 0.0-1.0
evidence: "[file:line references]"
validation_method: "[how to verify]"
development:
- hypothesis: "[development practice]"
confidence: 0.0-1.0
evidence: "[file:line references]"
validation_method: "[how to verify]"
ai_collaboration:
level: 0-4
confidence: 0.0-1.0
tools_detected:
- tool: "[tool name]"
config_file: "[file path]"
content_quality: "[minimal|basic|comprehensive]"
indicators:
- "[indicator 1]"
- "[indicator 2]"
# Level interpretation:
# 0: No AI (no config files, 5-8% comments)
# 1: Occasional (1 config, minimal content)
# 2: Frequent (1-2 configs + indirect indicators)
# 3: Systematic (complete config + high comments + consistent style)
# 4: Ecosystem (multiple tools/AGENTS.md + team standards)
business:
- hypothesis: "[business domain insight]"
confidence: 0.0-1.0
evidence: "[file:line references]"
validation_method: "[how to verify]"
scanned_files:
- file: "[path/to/file]"
reason: "[why scanned]"
key_insight: "[main learning]"
summary:
understanding_depth: "[70-80%]"
key_findings:
- "[finding 1]"
- "[finding 2]"
- "[finding 3]"
Section Specifications
Section 1: metadata
Required Fields:
| Field | Type | Example | Notes |
|---|---|---|---|
| project_name | string | "sourceatlas2" | From package.json, pyproject.toml, or directory name |
| scan_time | ISO 8601 | "2025-01-14T10:30:00Z" | UTC timestamp |
| target_path | string | "." or "src/api" | From $ARGUMENTS, default "." |
| total_files | integer | 127 | After exclusions (no .venv, node_modules) |
| scanned_files | integer | 8 | Actual files read |
| scan_ratio | string | "6.3%" | (scanned_files / total_files * 100) |
| project_scale | enum | "LARGE" | TINY/SMALL/MEDIUM/LARGE/VERY_LARGE |
| constitution_version | string | "1.1" | Current version |
Context Subfields (v2.8.2):
| Field | Type | Example | Notes |
|---|---|---|---|
| git_branch | string or null | "main" | Current branch, null if not git repo |
| relative_path | string or null | "packages/api" | Path within monorepo, null if root |
| package_name | string or null | "@org/api" | From package.json name field |
Example:
metadata:
project_name: "sourceatlas2"
scan_time: "2025-01-14T10:30:00Z"
target_path: "."
total_files: 127
scanned_files: 8
scan_ratio: "6.3%"
project_scale: "LARGE"
constitution_version: "1.1"
context:
git_branch: "main"
relative_path: null
package_name: "@sourceatlas/plugin"
Section 2: project_fingerprint
High-level project classification.
Fields:
| Field | Type | Values | Example |
|---|---|---|---|
| project_type | enum | WEB_APP, CLI, LIBRARY, MOBILE_APP, MICROSERVICE, MONOREPO | "CLI" |
| scale | enum | TINY, SMALL, MEDIUM, LARGE, VERY_LARGE | "LARGE" |
| primary_language | string | Include version | "TypeScript 5.3" |
| framework | string | Include version | "None (vanilla TS)" |
| architecture | string | Pattern name | "Modular CLI with plugins" |
Scale Definitions:
- TINY: <500 LOC
- SMALL: 500-2k LOC
- MEDIUM: 2k-10k LOC
- LARGE: 10k-50k LOC
- VERY_LARGE: >50k LOC
Example:
project_fingerprint:
project_type: "CLI"
scale: "LARGE"
primary_language: "TypeScript 5.3"
framework: "None (vanilla TS)"
architecture: "Modular CLI with plugins"
Section 3: tech_stack
Technology stack breakdown.
Structure:
backend: Always presentfrontend: Optional (web apps, mobile apps)infrastructure: Optional (Docker, K8s)
Example (Backend-Only):
tech_stack:
backend:
language: "Python 3.11"
framework: "FastAPI 0.104"
database: "PostgreSQL 15"
Example (Full Stack):
tech_stack:
backend:
language: "Node.js 20"
framework: "Express 4.18"
database: "MongoDB 7.0"
frontend:
language: "TypeScript"
framework: "React 18.2"
infrastructure:
containerization: "Docker 24.0"
orchestration: "Kubernetes 1.28"
Section 4: hypotheses
Scale-appropriate hypotheses with evidence.
Subsections:
architecture: 2-4 hypothesestech_stack: 2-4 hypothesesdevelopment: 2-4 hypothesesai_collaboration: 1 hypothesis (special structure)business: 1-3 hypotheses
Hypothesis Structure:
- hypothesis: "[clear, specific statement]"
confidence: 0.0-1.0 # aim for >0.7
evidence: "[file:line references]"
validation_method: "[how to verify in Stage 1]"
Example (architecture):
hypotheses:
architecture:
- hypothesis: "3-layer architecture: Controller → Service → Repository"
confidence: 0.85
evidence: "src/controllers/, src/services/, src/repositories/ directories exist"
validation_method: "trace UserController.ts flow to UserService.ts to UserRepository.ts"
- hypothesis: "Dependency injection via constructor parameters"
confidence: 0.90
evidence: "src/controllers/UserController.ts:15-20, src/services/UserService.ts:10-12"
validation_method: "grep 'constructor.*private' src/**/*.ts"
Example (tech_stack):
tech_stack:
- hypothesis: "Express.js 4.18 with TypeScript for REST API"
confidence: 0.95
evidence: "package.json:12, src/app.ts:1-5"
validation_method: "grep 'express' package.json; check tsconfig.json"
- hypothesis: "Sequelize ORM for PostgreSQL database access"
confidence: 0.80
evidence: "package.json:18, src/config/database.ts:5-10"
validation_method: "check models/ directory for Sequelize model definitions"
Example (development):
development:
- hypothesis: "Jest + Supertest for API integration testing"
confidence: 0.85
evidence: "package.json:25, tests/api/users.test.ts:1-20"
validation_method: "run npm test -- --coverage"
- hypothesis: "ESLint + Prettier for code quality enforcement"
confidence: 0.90
evidence: ".eslintrc.json, .prettierrc.json exist"
validation_method: "run npm run lint"
Example (ai_collaboration - Special Structure):
ai_collaboration:
level: 3
confidence: 0.90
tools_detected:
- tool: "Claude Code"
config_file: "CLAUDE.md"
content_quality: "comprehensive"
- tool: "Cursor"
config_file: ".cursorrules"
content_quality: "basic"
indicators:
- "High comment density (18% vs typical 5-8%)"
- "Consistent code style across all files"
- "Comprehensive inline documentation"
- "Conventional Commits with AI tool signatures"
AI Collaboration Levels:
- Level 0: No AI detection
- Level 1: 1 tool config, minimal content
- Level 2: 1-2 tool configs + some indirect indicators
- Level 3: Complete AI config + high comment density + consistent style
- Level 4: Multiple tools (Ruler/.ruler/) or AGENTS.md + team standards
Content Quality:
- minimal: <5 lines, basic instructions
- basic: 5-50 lines, clear guidance
- comprehensive: >50 lines, detailed guidelines, examples
Example (business):
business:
- hypothesis: "E-commerce platform with user, product, order management"
confidence: 0.80
evidence: "README.md:15-30, models/User.ts, models/Product.ts, models/Order.ts"
validation_method: "review core entity relationships in models/"
- hypothesis: "Multi-tenant SaaS with organization-level isolation"
confidence: 0.70
evidence: "models/Organization.ts:5-10, middleware/tenantIsolation.ts:15-30"
validation_method: "trace request flow through tenant middleware"
Section 5: scanned_files
List of files scanned with reasons and insights.
Structure:
scanned_files:
- file: "[path]"
reason: "[why scanned - entropy category]"
key_insight: "[main learning]"
Example:
scanned_files:
- file: "README.md"
reason: "Documentation (highest entropy)"
key_insight: "CLI tool for codebase analysis using information theory"
- file: "package.json"
reason: "Configuration (project-level decisions)"
key_insight: "TypeScript project with 15 dependencies, targets Node.js 18+"
- file: "CLAUDE.md"
reason: "AI collaboration detection"
key_insight: "Comprehensive Claude Code configuration, Level 3 collaboration"
- file: "src/commands/overview/SKILL.md"
reason: "Core model (data structure)"
key_insight: "Stage 0 fingerprint command with scale-aware analysis"
- file: "src/app.ts"
reason: "Entry point (architecture pattern)"
key_insight: "Plugin-based architecture, modular command system"
- file: "tests/integration/overview.test.ts"
reason: "Testing (development practices)"
key_insight: "Jest integration tests with real project fixtures"
Section 6: summary
High-level summary with key findings.
Fields:
| Field | Type | Example | Notes |
|---|---|---|---|
| understanding_depth | string | "75%" | Target: 70-80% |
| key_findings | array | [3-5 findings] | Most important discoveries |
Example:
summary:
understanding_depth: "75%"
key_findings:
- "TypeScript CLI tool for codebase analysis"
- "Modular plugin architecture with 5 analysis commands"
- "Information theory-based approach (scan <5% for 70-80% understanding)"
- "Level 3 AI collaboration with comprehensive CLAUDE.md"
- "Constitutional compliance v1.1 with mandatory exclusions"
Recommended Next Section
Decision Logic: Choose ONE of these outputs, NOT both.
Case A: End Condition (No Table)
When any of these conditions are met:
- Project too small: TINY (<10 files)
- Findings too vague: Cannot provide high confidence (>0.7) parameters
- Goal achieved: AI collaboration Level ≥3 and scale TINY/SMALL
Output:
✅ **Analysis sufficient** - Project is small, can read all files directly to start development
Case B: Suggestions (Table Output)
When project scale is large enough or there are clear next steps:
Format:
## Recommended Next
| # | Command | Purpose |
|---|---------|---------|
| 1 | `/sourceatlas:pattern "[pattern name]"` | [reason based on findings] |
| 2 | `/sourceatlas:flow "[entry point]"` | [reason based on findings] |
💡 Enter a number (e.g., `1`) or copy the command to execute
Suggestion Rules:
| Finding | Suggested Command | Parameter Source |
|---|---|---|
| Clear design patterns | /sourceatlas:pattern | Discovered pattern name |
| Complex architecture (multi-layer/microservices) | /sourceatlas:flow | Main entry point file |
| Scale ≥ LARGE | /sourceatlas:history | No parameters needed |
| High risk areas | /sourceatlas:impact | Risk file/module name |
Requirements:
- Specific parameters: Use actual names from analysis (e.g.,
"repository"not"related pattern") - Quantity limit: 1-2 suggestions, don't force fill
- Purpose column: Reference specific findings (numbers, file names)
Example (Good):
## Recommended Next
| # | Command | Purpose |
|---|---------|---------|
| 1 | `/sourceatlas:pattern "repository pattern"` | Found Repository pattern used in 15 files |
| 2 | `/sourceatlas:flow "src/app.ts"` | Trace 3-layer architecture execution flow |
Example (Bad - Too Generic):
| 1 | `/sourceatlas:pattern "some pattern"` | Learn more patterns |
Footer Format
───────────────────────────────
🗺️ v2.13.1 │ Constitution v1.1
Complete Example
🗺️ SourceAtlas: Overview
───────────────────────────────
🔭 express-api │ MEDIUM (42 files)
```yaml
metadata:
project_name: "express-api"
scan_time: "2025-01-14T10:30:00Z"
target_path: "."
total_files: 42
scanned_files: 5
scan_ratio: "11.9%"
project_scale: "MEDIUM"
constitution_version: "1.1"
context:
git_branch: "main"
relative_path: null
package_name: "@company/express-api"
project_fingerprint:
project_type: "WEB_APP"
scale: "MEDIUM"
primary_language: "TypeScript 5.3"
framework: "Express.js 4.18"
architecture: "3-layer MVC (Controller-Service-Repository)"
tech_stack:
backend:
language: "TypeScript 5.3"
framework: "Express 4.18"
database: "PostgreSQL 15"
infrastructure:
containerization: "Docker 24.0"
orchestration: "none"
hypotheses:
architecture:
- hypothesis: "3-layer architecture: Controller → Service → Repository"
confidence: 0.85
evidence: "src/controllers/, src/services/, src/repositories/ exist"
validation_method: "trace UserController.ts flow"
- hypothesis: "RESTful API design with route-based organization"
confidence: 0.90
evidence: "src/routes/users.ts:1-20, routes follow REST conventions"
validation_method: "check all routes/*.ts files"
tech_stack:
- hypothesis: "Express.js 4.18 with TypeScript for type safety"
confidence: 0.95
evidence: "package.json:12, tsconfig.json:5-10"
validation_method: "grep 'express' package.json"
- hypothesis: "Sequelize ORM for PostgreSQL access"
confidence: 0.80
evidence: "package.json:18, src/config/database.ts:5-10"
validation_method: "check models/ for Sequelize definitions"
development:
- hypothesis: "Jest + Supertest for API testing, likely >70% coverage"
confidence: 0.75
evidence: "package.json:25, tests/api/users.test.ts:1-20"
validation_method: "run npm test -- --coverage"
- hypothesis: "ESLint + Prettier enforce code quality"
confidence: 0.90
evidence: ".eslintrc.json, .prettierrc.json exist"
validation_method: "run npm run lint"
ai_collaboration:
level: 2
confidence: 0.80
tools_detected:
- tool: "Claude Code"
config_file: "CLAUDE.md"
content_quality: "basic"
indicators:
- "High comment density (12% vs typical 5-8%)"
- "Consistent code style"
business:
- hypothesis: "User management API with authentication/authorization"
confidence: 0.80
evidence: "README.md:15-30, models/User.ts, routes/auth.ts"
validation_method: "review auth flow in middleware/auth.ts"
scanned_files:
- file: "README.md"
reason: "Documentation (highest entropy)"
key_insight: "REST API for user management with JWT auth"
- file: "package.json"
reason: "Configuration (project-level decisions)"
key_insight: "Express + TypeScript + Sequelize stack"
- file: "CLAUDE.md"
reason: "AI collaboration detection"
key_insight: "Basic Claude Code config, Level 2 collaboration"
- file: "src/controllers/UserController.ts"
reason: "Entry point (architecture pattern)"
key_insight: "Controller calls UserService, follows 3-layer pattern"
- file: "tests/api/users.test.ts"
reason: "Testing (development practices)"
key_insight: "Jest + Supertest for API integration tests"
summary:
understanding_depth: "75%"
key_findings:
- "Express.js REST API with 3-layer architecture"
- "TypeScript + Sequelize for type-safe database access"
- "JWT-based authentication with role-based authorization"
- "Level 2 AI collaboration (Claude Code, basic config)"
- "Good test coverage with Jest + Supertest"
## Recommended Next
| # | Command | Purpose |
|---|---------|---------|
| 1 | `/sourceatlas:pattern "repository pattern"` | Found Repository pattern in 8 files |
| 2 | `/sourceatlas:flow "src/routes/users.ts"` | Trace 3-layer flow from route to database |
💡 Enter a number (e.g., `1`) or copy the command to execute
───────────────────────────────
🗺️ v2.13.1 │ Constitution v1.1
Overview Reference Guide
Advanced features, scale-aware analysis, helper scripts, and best practices.
Scale-Aware Analysis
Scale Definitions
| Scale | File Count | LOC Range | Scan Limit | Hypothesis Target |
|---|---|---|---|---|
| TINY | <5 | <500 | 1-2 files (50% max) | 5-8 hypotheses |
| SMALL | 5-15 | 500-2K | 2-3 files (10-20%) | 7-10 hypotheses |
| MEDIUM | 15-50 | 2K-10K | 4-6 files (8-12%) | 10-15 hypotheses |
| LARGE | 50-150 | 10K-50K | 6-10 files (4-7%) | 12-18 hypotheses |
| VERY_LARGE | >150 | >50K | 10-15 files (3-7%) | 15-20 hypotheses |
Why Scale-Aware?
Problem: Fixed 5% scan ratio doesn't work for all sizes
- TINY projects: 5% of 4 files = 0 files (unusable)
- VERY_LARGE projects: 5% of 1000 files = 50 files (wasteful)
Solution: Adaptive scan limits
- TINY: Higher ratio (50%) because each file matters
- VERY_LARGE: Lower ratio (3-7%) because diminishing returns
Scale Detection Logic
# Count code files (excluding dependencies)
FILE_COUNT=$(find . -type f \
\( -name "*.py" -o -name "*.js" -o -name "*.ts" -o -name "*.swift" -o -name "*.kt" \) \
-not -path "*/node_modules/*" \
-not -path "*/.venv/*" \
-not -path "*/vendor/*" \
-not -path "*/__pycache__/*" \
2>/dev/null | wc -l | tr -d ' ')
# Determine scale
if [ $FILE_COUNT -lt 5 ]; then
SCALE="TINY"
SCAN_LIMIT="1-2 files"
elif [ $FILE_COUNT -lt 15 ]; then
SCALE="SMALL"
SCAN_LIMIT="2-3 files"
elif [ $FILE_COUNT -lt 50 ]; then
SCALE="MEDIUM"
SCAN_LIMIT="4-6 files"
elif [ $FILE_COUNT -lt 150 ]; then
SCALE="LARGE"
SCAN_LIMIT="6-10 files"
else
SCALE="VERY_LARGE"
SCAN_LIMIT="10-15 files"
fi
Helper Scripts
detect-project.sh
Location:
- Global:
~/.claude/scripts/atlas/detect-project.sh - Local:
scripts/atlas/detect-project.sh
Purpose: Comprehensive project detection and scale analysis
Output:
Project Type: WEB_APP
Primary Language: TypeScript
Framework: Express.js 4.18
File Count: 127 (after exclusions)
Scale: LARGE
Recommended Scan: 6-10 files (4-7%)
Hypothesis Target: 12-18 hypotheses
Context:
- Git Branch: main
- Package Name: @company/api
- Relative Path: (root)
Usage:
bash ~/.claude/scripts/atlas/detect-project.sh .
bash ~/.claude/scripts/atlas/detect-project.sh src/api # subdirectory
scan-entropy.sh
Location:
- Global:
~/.claude/scripts/atlas/scan-entropy.sh - Local:
scripts/atlas/scan-entropy.sh
Purpose: Execute high-entropy file prioritization
Output:
=== High-Entropy Files (Priority Order) ===
[1] Documentation:
- README.md
- CLAUDE.md
- docs/architecture.md
[2] Configuration:
- package.json
- tsconfig.json
- docker-compose.yml
[3] Models (top 3):
- src/models/User.ts
- src/models/Product.ts
- src/models/Order.ts
[4] Entry Points (top 2):
- src/app.ts
- src/routes/index.ts
[5] Tests (top 2):
- tests/integration/api.test.ts
- tests/unit/services/user.test.ts
Usage:
bash ~/.claude/scripts/atlas/scan-entropy.sh .
detect-ai-tools.sh
Location:
- Global:
~/.claude/scripts/atlas/detect-ai-tools.sh - Local:
scripts/atlas/detect-ai-tools.sh
Purpose: Detect AI tool configurations (Tier 1 + Tier 2)
Output:
=== AI Tool Detection ===
Tier 1 (Tool-Specific Config Files):
✅ Claude Code: CLAUDE.md (+0.30)
✅ Cursor: .cursorrules (+0.25)
❌ Windsurf: not found
❌ GitHub Copilot: not found
✅ AGENTS.md: AGENTS.md (+0.20)
Tier 2 (Indirect Indicators):
- Comment density: 18% (vs typical 5-8%) ✅
- Code consistency: 95% (>98% threshold) ❌
- Conventional Commits: 100% ✅
AI Collaboration Level: 3
Confidence: 0.85
Tier 1 Tools Detected:
| Tool | Config Files | Boost |
|---|---|---|
| Claude Code | CLAUDE.md, .claude/ | +0.30 |
| Cursor | .cursorrules, .cursor/rules/*.mdc | +0.25 |
| Windsurf | .windsurfrules, .windsurf/rules/ | +0.25 |
| GitHub Copilot | .github/copilot-instructions.md, **/.instructions.md | +0.20 |
| Cline/Roo | .clinerules, .clinerules/, .roo/ | +0.25 |
| Aider | CONVENTIONS.md, .aider.conf.yml, .aider.input.history | +0.25 |
| Continue.dev | .continuerules, .continue/rules/ | +0.25 |
| JetBrains AI | .aiignore | +0.20 |
| AGENTS.md | AGENTS.md | +0.20 |
| Sourcegraph Cody | .vscode/cody.json | +0.15 |
| Replit | replit.nix + .replit | +0.15 |
| Ruler | .ruler/ | +0.20 |
Usage:
bash ~/.claude/scripts/atlas/detect-ai-tools.sh .
Cache Behavior
Cache Location
Root analysis:
.sourceatlas/overview.yaml
Subdirectory analysis:
# For: /sourceatlas:overview "src/api"
.sourceatlas/overview-src-api.yaml
# For: /sourceatlas:overview "packages/backend"
.sourceatlas/overview-packages-backend.yaml
Naming rule: Replace / with -, lowercase
Cache Check Logic
# Parse arguments
if echo "$ARGUMENTS" | grep -q "\-\-force"; then
echo "⚠️ --force flag detected, skipping cache"
# Skip cache, execute analysis
else
# Calculate cache file name
if [ "$ARGUMENTS" = "." ] || [ -z "$ARGUMENTS" ]; then
CACHE_FILE=".sourceatlas/overview.yaml"
else
# Convert path to cache name
CACHE_NAME=$(echo "$ARGUMENTS" | tr '/' '-' | tr '[:upper:]' '[:lower:]')
CACHE_FILE=".sourceatlas/overview-${CACHE_NAME}.yaml"
fi
# Check if cache exists
if [ -f "$CACHE_FILE" ]; then
# Get modification time
MTIME=$(stat -f "%Sm" -t "%Y-%m-%d" "$CACHE_FILE" 2>/dev/null || stat -c "%y" "$CACHE_FILE" 2>/dev/null | cut -d' ' -f1)
# Calculate age
AGE_DAYS=$(( ($(date +%s) - $(date -j -f "%Y-%m-%d" "$MTIME" +%s 2>/dev/null || date -d "$MTIME" +%s 2>/dev/null)) / 86400 ))
echo "📁 Loading cache: $CACHE_FILE ($AGE_DAYS days ago)"
echo "💡 Add --force to re-analyze"
if [ $AGE_DAYS -gt 30 ]; then
echo "⚠️ Cache is over 30 days old, recommend re-analysis"
fi
# Output cache content
cat "$CACHE_FILE"
exit 0
fi
fi
Cache Age Warning
- <30 days: No warning
- >30 days: Show warning
- >90 days: Strong warning
Rationale: Projects evolve, old fingerprints may be stale.
Auto-Save Behavior
Save Timing
Auto-save occurs after V4 verification passes:
Phase 1 → Phase 2 → Phase 3 → Generate YAML → V1-V4 Verification → Auto-Save
Save Location
mkdir -p .sourceatlas
# Root analysis
SAVE_PATH=".sourceatlas/overview.yaml"
# Subdirectory analysis (e.g., "src/api")
SAVE_PATH=".sourceatlas/overview-src-api.yaml"
Confirmation Message
💾 Saved to .sourceatlas/overview.yaml
Handoffs Decision Rules
Follow Constitution Article VII: Handoffs Principles
Decision Logic
Choose ONE of these outputs, NOT both:
Case A: End Condition (No Table)
When any of these are true:
- Project too small: TINY (<10 files) can be read directly
- Findings too vague: Cannot provide high confidence (>0.7) specific parameters
- Goal achieved: AI collaboration Level ≥3 and scale TINY/SMALL (can start development)
Output:
✅ **Analysis sufficient** - Project is small, can read all files directly to start development
Case B: Suggestions (Table Output)
When project scale is large enough or there are clear next steps.
Suggestion Selection:
| Finding | Command | Parameter Source |
|---|---|---|
| Clear design patterns | /sourceatlas:pattern | Discovered pattern name |
| Complex architecture (multi-layer/microservices) | /sourceatlas:flow | Main entry point file |
| Scale ≥ LARGE | /sourceatlas:history | No parameters |
| High risk areas | /sourceatlas:impact | Risk file/module name |
Output Format:
## Recommended Next
| # | Command | Purpose |
|---|---------|---------|
| 1 | `/sourceatlas:pattern "repository pattern"` | Found Repository pattern used in 15 files |
| 2 | `/sourceatlas:flow "src/app.ts"` | Trace 3-layer architecture flow |
💡 Enter a number (e.g., `1`) or copy the command to execute
Quality Requirements:
- Specific parameters: Use actual discovered names (e.g.,
"repository pattern"not"some pattern") - Quantity limit: 1-2 suggestions max, don't force fill
- Purpose column: Reference specific findings (numbers, file names)
Information Theory Principles
High-Entropy Files
Entropy = Information density = How much you learn per line read
Ranking (highest to lowest):
-
Documentation (README, ARCHITECTURE docs)
- Entropy: ~10 bits/line
- Why: Summarizes entire project purpose, architecture, usage
-
Configuration (package.json, docker-compose.yml)
- Entropy: ~8 bits/line
- Why: Technology stack decisions in one place
-
Models/Entities (User.ts, Product.ts)
- Entropy: ~6 bits/line
- Why: Data structure defines business domain
-
Entry Points (app.ts, routes/index.ts)
- Entropy: ~5 bits/line
- Why: Architecture patterns visible
-
Tests (user.test.ts)
- Entropy: ~4 bits/line
- Why: Development practices visible
-
Implementation (services, controllers)
- Entropy: ~2 bits/line
- Why: Details, not structure
Strategy: Read top 3 categories, sample categories 4-5.
AI Collaboration Detection
Level Definitions
| Level | Criteria | Examples |
|---|---|---|
| 0: No AI | No config files, 5-8% comments, inconsistent style | Manual development |
| 1: Occasional | 1 tool config with minimal content | Experimenting with AI |
| 2: Frequent | 1-2 tool configs + some indirect indicators | Regular AI usage |
| 3: Systematic | Complete AI config + high comments + consistent style | Mature AI workflow |
| 4: Ecosystem | Multiple tools (Ruler) or AGENTS.md + team standards | Organization-wide |
Content Quality Assessment
When config file is found, assess quality:
Minimal (<5 lines):
# .cursorrules
Use TypeScript
Follow ESLint rules
Basic (5-50 lines):
# CLAUDE.md
## Project Overview
This is an Express API for user management.
## Code Style
- Use TypeScript
- Follow 3-layer architecture
- Write tests for all endpoints
Comprehensive (>50 lines):
# CLAUDE.md (full structure)
## What is this project
[Detailed explanation]
## Key Files
[File-by-file breakdown]
## Must Follow
[Detailed guidelines]
## Development Workflow
[Step-by-step instructions]
Scoring:
- minimal → confidence: 0.5-0.6
- basic → confidence: 0.7-0.8
- comprehensive → confidence: 0.9-1.0
Best Practices
For Different Project Sizes
TINY projects (<5 files):
- Read ALL files if possible
- Focus on purpose and usage
- Simple hypotheses (5-8)
SMALL projects (5-15 files):
- Read docs + config + 1-2 models
- Focus on architecture pattern
- Moderate hypotheses (7-10)
MEDIUM projects (15-50 files):
- Standard entropy-based scanning
- Focus on patterns and conventions
- Balanced hypotheses (10-15)
LARGE projects (50-150 files):
- Strict entropy prioritization
- Focus on high-level architecture
- Comprehensive hypotheses (12-18)
VERY_LARGE projects (>150 files):
- Maximum efficiency required
- Focus on fingerprint only, not details
- Extensive hypotheses (15-20)
Integration with Other Commands
After overview fingerprint, consider:
| Finding | Next Command | Reason |
|---|---|---|
| Clear patterns mentioned | /sourceatlas:pattern | Learn implementation |
| Complex architecture | /sourceatlas:flow | Trace execution |
| Large codebase | /sourceatlas:history | Find hotspots |
| High-risk areas identified | /sourceatlas:impact | Assess change impact |
Deprecated Features
--save flag (v2.8.0)
Auto-save is now default behavior.
If user provides --save:
if echo "$ARGUMENTS" | grep -q "\-\-save"; then
echo "⚠️ --save is deprecated, auto-save is now default"
# Remove --save from arguments
ARGUMENTS=$(echo "$ARGUMENTS" | sed 's/--save//g')
# Continue normal execution (still auto-saves)
fi
Troubleshooting
Issue 1: Helper Scripts Not Found
Symptom: Scripts not in ~/.claude/scripts/atlas/ or scripts/atlas/
Solution:
- Use manual fallback commands provided in workflow.md
- All core functionality works without scripts
- Scripts are optimization only
Issue 2: File Count Varies
Symptom: Different counts on different runs
Solution:
- Normal if files are created/deleted between runs
- Use same exclusions in verification
- ±10% variance acceptable
Issue 3: Git Commands Fail
Symptom: Not a git repository
Solution:
- Set
context.git_branch: null - Set
context.relative_path: null - Continue analysis without git context
Issue 4: Too Many/Few Hypotheses
Symptom: Generated hypotheses don't match scale targets
Solution:
- Use scale targets as guidelines, not strict limits
- Quality > quantity
- Each hypothesis must have >0.7 confidence
Version History
- v2.13.1: Current version with Constitution v1.1
- v2.8.2: Added branch-aware context
- v2.8.0: Auto-save default, deprecated --save flag
- v2.5.0: Added scale-aware analysis
- v2.0.0: YAML output format
Overview Self-Verification Guide
Complete verification checklist for Stage 0 fingerprint analysis.
When to Verify
Execute after generating YAML output, before saving to .sourceatlas/overview.yaml.
Purpose
Prevent hallucinated file paths, incorrect counts, and fictional configurations from appearing in output.
Verification Steps
Step V1: Extract Verifiable Claims
After generating the YAML output, extract all verifiable claims.
Claim Types to Extract:
| Type | YAML Path | Verification Method |
|---|---|---|
| File Path | scanned_files[].file | test -f path |
| Directory | Architecture mentions | test -d path |
| File Count | metadata.total_files, metadata.scanned_files | find . -type f | wc -l |
| Config File | hypotheses.ai_collaboration.tools_detected[].config_file | test -f config_file |
| Git Branch | metadata.context.git_branch | git branch --show-current |
| Evidence | hypotheses.*.evidence | Verify file:line exists |
Example extraction:
# From generated YAML:
scanned_files:
- file: "README.md" # ✅ Verify
- file: "package.json" # ✅ Verify
- file: "CLAUDE.md" # ✅ Verify
metadata:
total_files: 127 # ✅ Verify ±10%
scanned_files: 8 # ✅ Verify exact
context:
git_branch: "main" # ✅ Verify
hypotheses:
ai_collaboration:
tools_detected:
- config_file: "CLAUDE.md" # ✅ Verify
- config_file: ".cursorrules" # ✅ Verify
Step V2: Parallel Verification Execution
Run ALL verification checks in parallel for speed.
V2.1: Verify Scanned Files
# Check all scanned_files entries exist
for path in "README.md" "package.json" "CLAUDE.md" "src/app.ts"; do
if [ ! -f "$path" ]; then
echo "❌ FILE_NOT_FOUND: $path"
fi
done
Check:
- ✅ All
scanned_files[].fileentries exist - ⚠️ If file not found → Remove from scanned_files or find correct path
V2.2: Verify AI Tool Config Files
# Check all AI tool config files
for config in "CLAUDE.md" ".cursorrules" ".github/copilot-instructions.md"; do
if [ ! -f "$config" ] && [ ! -d "$config" ]; then
echo "❌ CONFIG_NOT_FOUND: $config"
fi
done
Check:
- ✅ All
tools_detected[].config_fileentries exist - ⚠️ If config not found → Remove from tools_detected
V2.3: Verify File Count
# Verify total_files count is reasonable
claimed_count=127
actual_count=$(find . -type f \
-not -path "*/node_modules/*" \
-not -path "*/.git/*" \
-not -path "*/.venv/*" \
-not -path "*/vendor/*" \
-not -path "*/__pycache__/*" \
2>/dev/null | wc -l | tr -d ' ')
# Allow 10% variance for dynamic counts
lower_bound=$((actual_count * 90 / 100))
upper_bound=$((actual_count * 110 / 100))
if [ $claimed_count -lt $lower_bound ] || [ $claimed_count -gt $upper_bound ]; then
echo "⚠️ COUNT_CHECK: claimed $claimed_count, actual $actual_count (±10% tolerance)"
fi
Check:
- ✅
metadata.total_fileswithin ±10% of actual count - ⚠️ If significant difference → Update with actual count
V2.4: Verify Git Branch
# Verify git branch if claimed
claimed_branch="main"
actual_branch=$(git branch --show-current 2>/dev/null)
if [ -n "$claimed_branch" ] && [ "$actual_branch" != "$claimed_branch" ]; then
echo "❌ BRANCH_MISMATCH: claimed $claimed_branch, actual $actual_branch"
fi
Check:
- ✅
metadata.context.git_branchmatches current branch - ⚠️ If mismatch → Update with actual branch
- ✅ If not a git repo → set to
null
V2.5: Verify Evidence References
# Verify evidence file:line references
evidence_files="package.json README.md src/app.ts"
for file in $evidence_files; do
if [ ! -f "$file" ]; then
echo "❌ EVIDENCE_FILE_NOT_FOUND: $file"
fi
done
Check:
- ✅ All files mentioned in
hypotheses.*.evidenceexist - ⚠️ If file not found → Update evidence or remove hypothesis
V2.6: Verify Directories
# Verify directories mentioned in hypotheses
for dir in "src/controllers" "src/services" "src/repositories"; do
if [ ! -d "$dir" ]; then
echo "❌ DIR_NOT_FOUND: $dir"
fi
done
Check:
- ✅ All directories mentioned in hypotheses exist
- ⚠️ If directory not found → Update hypothesis or remove claim
Step V3: Handle Verification Results
Based on verification outcomes:
If All Checks Pass ✅
verification_status:
verified: true
checks_passed: 6
confidence: high
Action:
- Continue to output/save
- Add verification summary to footer
If Minor Issues Found ⚠️ (1-2 checks failed)
Examples:
- File count off by <10%
- One config file path incorrect
- Git branch name slightly different
Action:
- Correct the specific claims without regenerating entire output
- Re-verify corrected claims
- Add note to verification summary:
verification_notes:
- "File count corrected to 134 (was 127)"
- "Git branch corrected to 'develop' (was 'main')"
If Major Issues Found ❌ (3+ checks failed)
Examples:
- Multiple scanned files don't exist
- AI tool configs not found
- File count wildly different (>20% off)
- Many evidence references invalid
Action:
- STOP - Do not output current analysis
- Re-execute relevant phases:
- If scanned files wrong → Re-run Phase 2 (High-Entropy Scanning)
- If AI tools wrong → Re-run detect-ai-tools.sh
- If file count wrong → Re-run detect-project.sh
- Regenerate affected YAML sections
- Re-run full verification
Step V4: Verification Summary
Add to footer (before 🗺️ v2.13.1 │ Constitution v1.1):
If All Verifications Passed
✅ Verified: [N] scanned files, [M] config paths, file count
Example:
✅ Verified: 8 scanned files, 2 config paths, file count
───────────────────────────────
🗺️ v2.13.1 │ Constitution v1.1
If Corrections Were Made
🔧 Self-corrected: [list specific corrections]
✅ Verified: [N] scanned files, [M] config paths, file count
Example:
🔧 Self-corrected: File count updated to 134 (was 127)
✅ Verified: 8 scanned files, 2 config paths, file count
───────────────────────────────
🗺️ v2.13.1 │ Constitution v1.1
Verification Checklist
Before finalizing output, confirm:
- All
scanned_files[].fileentries verified to exist - All
tools_detected[].config_fileentries verified to exist -
metadata.total_filesverified against filesystem (±10%) -
metadata.scanned_filescount matches actual files read -
metadata.context.git_branchverified against current branch - All evidence file references in hypotheses verified to exist
- All directories mentioned in hypotheses verified to exist
- No placeholder values like
"[detected name]"in output
Verification Examples
Example 1: File Path Verification
Claim:
scanned_files:
- file: "README.md"
Verification:
test -f "README.md"
echo $? # 0 = exists
Result: ✅ File exists
Action: No correction needed
Example 2: Config File Verification
Claim:
hypotheses:
ai_collaboration:
tools_detected:
- tool: "Claude Code"
config_file: "CLAUDE.md"
Verification:
test -f "CLAUDE.md"
echo $? # 0 = exists
Result: ✅ Config exists
Action: No correction needed
Example 3: File Count Verification
Claim:
metadata:
total_files: 127
Verification:
actual=$(find . -type f \
-not -path "*/node_modules/*" \
-not -path "*/.git/*" \
-not -path "*/.venv/*" \
2>/dev/null | wc -l | tr -d ' ')
echo "Claimed: 127, Actual: $actual"
# Output: Claimed: 127, Actual: 134
Result: ⚠️ Count off by 7 (5.5%), within tolerance but should update
Action:
- Update
metadata.total_files: 134 - Recalculate
scan_ratio: "6.0%"(8/134) - Note: "File count corrected to 134"
Example 4: Non-existent Config File
Claim:
hypotheses:
ai_collaboration:
tools_detected:
- tool: "Cursor"
config_file: ".cursorrules"
Verification:
test -f ".cursorrules"
echo $? # 1 = not found
Result: ❌ Config file doesn't exist
Action:
- Remove Cursor from
tools_detected - Lower AI collaboration level if appropriate
- Update confidence level
- Note: "Removed .cursorrules (file not found)"
Example 5: Wrong Git Branch
Claim:
metadata:
context:
git_branch: "main"
Verification:
git branch --show-current
# Output: develop
Result: ❌ Branch mismatch
Action:
- Update
git_branch: "develop" - Note: "Git branch corrected to 'develop'"
Example 6: Directory Not Found
Claim:
hypotheses:
architecture:
- hypothesis: "3-layer architecture: Controller → Service → Repository"
evidence: "src/controllers/, src/services/, src/repositories/ exist"
Verification:
test -d "src/controllers" && test -d "src/services" && test -d "src/repositories"
echo $? # 1 = at least one doesn't exist
# Check individually
test -d "src/controllers" && echo "✅ controllers"
test -d "src/services" && echo "✅ services"
test -d "src/repositories" || echo "❌ repositories not found"
Result: ❌ repositories directory doesn't exist
Action:
- Update hypothesis to reflect reality
- Lower confidence level
- Change evidence: "src/controllers/, src/services/ exist (no repository layer)"
- Update hypothesis: "2-layer architecture: Controller → Service"
Error Recovery
If Verification Script Fails
# If file not found, search for similar
find . -name "*README*" -type f 2>/dev/null
# If git command fails (not a git repo)
git branch 2>&1 | grep -q "not a git repository"
if [ $? -eq 0 ]; then
echo "Not a git repo, set git_branch to null"
fi
# If find fails (permission issues)
find . -type f 2>&1 | grep -i "permission denied" && echo "Permission issues detected"
If Many Files Don't Exist
Likely causes:
- Analyzing wrong directory
- Files from different project
- Placeholder values not replaced
Action:
- Verify current directory:
pwd - Check expected location:
ls -la - Re-run Phase 2 (High-Entropy Scanning)
- Only include files that currently exist
Best Practices
- Always verify file paths - Don't assume files exist
- Check AI tool configs - Many similar filenames (.cursorrules vs .cursor/rules/)
- Verify file counts - Use same exclusions as analysis
- Check git context - Projects may not be git repos
- Note all corrections - Transparency in verification summary
Handoff to Next Steps
After verification:
- ✅ If confidence HIGH → Proceed to save
- ⚠️ If confidence MEDIUM → Save with corrections noted
- ❌ If confidence LOW → Re-execute analysis phases
See reference.md#auto-save for save behavior.
Overview Workflow Guide
Complete step-by-step execution guide for Stage 0 fingerprint analysis.
Overview
This workflow generates a project fingerprint by scanning <5% of files to achieve 70-80% understanding in 10-15 minutes using information theory principles.
Time Budget: 10-15 minutes (typically 0-5 minutes)
Phase 1: Project Detection & Scale-Aware Planning (2-3 minutes)
Purpose
Detect project type, count files, determine scale, and set scan limits.
Step 1.1: Run Enhanced Detection Script
IMPORTANT: Use the script for accurate file counts and recommendations.
# Try global install first, then local
if [ -f ~/.claude/scripts/atlas/detect-project.sh ]; then
bash ~/.claude/scripts/atlas/detect-project.sh ${ARGUMENTS:-.}
elif [ -f scripts/atlas/detect-project.sh ]; then
bash scripts/atlas/detect-project.sh ${ARGUMENTS:-.}
else
echo "⚠️ Warning: detect-project.sh not found, using manual detection"
fi
Script outputs:
- Project type and language
- Actual code file count (excluding .venv, node_modules, vendor, etc.)
- Project scale classification
- Recommended file scan limits
- Hypothesis targets
- Context (git branch, monorepo subdirectory, package name)
Step 1.2: Manual Detection Fallback
If script not available, manually detect:
# Detect primary language
echo "=== Language Detection ==="
find . -type f \( -name "*.py" -o -name "*.js" -o -name "*.ts" -o -name "*.swift" -o -name "*.kt" \) \
-not -path "*/node_modules/*" \
-not -path "*/.venv/*" \
-not -path "*/vendor/*" \
2>/dev/null | head -10
# Count code files
echo "=== File Count ==="
find . -type f \( -name "*.py" -o -name "*.js" -o -name "*.ts" -o -name "*.swift" -o -name "*.kt" \) \
-not -path "*/node_modules/*" \
-not -path "*/.venv/*" \
-not -path "*/vendor/*" \
2>/dev/null | wc -l | tr -d ' '
# Detect project type
echo "=== Project Type ==="
if [ -f "package.json" ]; then
echo "Node.js project detected"
cat package.json | grep -A 5 "\"name\""
elif [ -f "requirements.txt" ] || [ -f "pyproject.toml" ]; then
echo "Python project detected"
elif [ -f "Podfile" ] || [ -f "*.xcodeproj" ]; then
echo "iOS project detected"
elif [ -f "build.gradle" ] || [ -f "build.gradle.kts" ]; then
echo "Android project detected"
fi
# Detect git context
echo "=== Git Context ==="
git branch --show-current 2>/dev/null || echo "Not a git repository"
git rev-parse --show-toplevel 2>/dev/null
Step 1.3: Determine Project Scale
Based on file count:
| Scale | File Count | Scan Limit | Hypothesis Target |
|---|---|---|---|
| TINY | <5 files | 1-2 files (50% max) | 5-8 hypotheses |
| SMALL | 5-15 files | 2-3 files (10-20%) | 7-10 hypotheses |
| MEDIUM | 15-50 files | 4-6 files (8-12%) | 10-15 hypotheses |
| LARGE | 50-150 files | 6-10 files (4-7%) | 12-18 hypotheses |
| VERY_LARGE | >150 files | 10-15 files (3-7%) | 15-20 hypotheses |
Example calculation:
- 120 files detected → LARGE
- Scan limit: 6-10 files (5-8%)
- Hypothesis target: 12-18 hypotheses
Phase 2: High-Entropy File Prioritization (5-8 minutes)
Purpose
Apply information theory - high-entropy files contain disproportionate information.
Step 2.1: Execute Helper Script (Recommended)
# Use helper script if available (try global first, then local)
if [ -f ~/.claude/scripts/atlas/scan-entropy.sh ]; then
bash ~/.claude/scripts/atlas/scan-entropy.sh ${ARGUMENTS:-.}
elif [ -f scripts/atlas/scan-entropy.sh ]; then
bash scripts/atlas/scan-entropy.sh ${ARGUMENTS:-.}
else
echo "⚠️ Warning: scan-entropy.sh not found, scanning manually"
fi
Step 2.2: Manual Scan Priority Order
Scan in this order, respecting scale limits from Phase 1:
2.2.1: Documentation (Highest Entropy)
# Scan README first (often contains 30-40% of understanding)
find . -maxdepth 2 -iname "README*" -type f 2>/dev/null | head -3
# Other high-value docs
find . -maxdepth 2 \( -name "CLAUDE.md" -o -name "CONTRIBUTING.md" -o -name "ARCHITECTURE.md" \) -type f 2>/dev/null
# Docs directory
find . -path "*/docs/*" -o -path "*/documentation/*" -type f 2>/dev/null | head -5
Action: Use Read tool on top 1-2 documentation files.
2.2.2: Configuration Files (Project-Level Decisions)
# Language-specific config
find . -maxdepth 2 \( -name "package.json" -o -name "composer.json" -o -name "Gemfile" \
-o -name "requirements.txt" -o -name "pyproject.toml" -o -name "Podfile" \
-o -name "build.gradle" -o -name "pom.xml" \) -type f 2>/dev/null
# Docker
find . -maxdepth 2 \( -name "docker-compose.yml" -o -name "Dockerfile" \) -type f 2>/dev/null
# Root configs
find . -maxdepth 1 -name "*.json" -o -name "*.yaml" -o -name "*.toml" -type f 2>/dev/null | head -5
Action: Use Read tool on 2-3 key config files.
2.2.3: Core Models (Data Structure - Scan 2-3 Only)
# Find model directories
find . -type d \( -name "models" -o -name "entities" -o -name "domain" \) \
-not -path "*/node_modules/*" \
-not -path "*/.venv/*" \
2>/dev/null | head -3
# Find model files
find . -path "*/models/*" -o -path "*/entities/*" -o -path "*/domain/*" -type f \
-not -path "*/node_modules/*" \
-not -path "*/.venv/*" \
2>/dev/null | head -10
Action: Use Read tool on 2-3 most important models only.
2.2.4: Entry Points (Architecture Patterns - Scan 1-2 Examples)
# Find entry point files
find . -maxdepth 3 \( -name "main.*" -o -name "index.*" -o -name "app.*" -o -name "server.*" \) \
-not -path "*/node_modules/*" \
-not -path "*/.venv/*" \
-type f 2>/dev/null
# Find controller/route directories
find . -type d \( -name "controllers" -o -name "routes" -o -name "api" \) \
-not -path "*/node_modules/*" \
-not -path "*/.venv/*" \
2>/dev/null | head -5
# Sample controllers
find . -path "*/controllers/*" -o -path "*/routes/*" -type f \
-not -path "*/node_modules/*" \
-not -path "*/.venv/*" \
2>/dev/null | head -5
Action: Use Read tool on 1-2 example entry points/controllers.
2.2.5: Tests (Development Practices - Scan 1-2 Examples)
# Find test directories
find . -type d \( -name "test" -o -name "tests" -o -name "spec" -o -name "__tests__" \) \
-not -path "*/node_modules/*" \
2>/dev/null | head -5
# Find test files
find . \( -name "*.test.*" -o -name "*.spec.*" \) -type f \
-not -path "*/node_modules/*" \
2>/dev/null | head -10
Action: Use Read tool on 1-2 example test files to understand testing approach.
Step 2.3: AI Tool Detection
Run AI collaboration detection:
# Use helper script for comprehensive detection
if [ -f ~/.claude/scripts/atlas/detect-ai-tools.sh ]; then
bash ~/.claude/scripts/atlas/detect-ai-tools.sh ${ARGUMENTS:-.}
elif [ -f scripts/atlas/detect-ai-tools.sh ]; then
bash scripts/atlas/detect-ai-tools.sh ${ARGUMENTS:-.}
else
# Fallback: manual checks
echo "=== AI Tool Detection ==="
# Tier 1: Tool-specific config files
ls -la CLAUDE.md .cursorrules .windsurfrules CONVENTIONS.md AGENTS.md .aiignore 2>/dev/null
ls -la .claude/ .cursor/rules/ .windsurf/rules/ .clinerules/ .roo/ .continue/rules/ .ruler/ 2>/dev/null
ls -la .github/copilot-instructions.md .vscode/cody.json .aider.conf.yml .aider.input.history 2>/dev/null
ls -la replit.nix .replit 2>/dev/null
# If found, read key config files
[ -f "CLAUDE.md" ] && echo "Found: CLAUDE.md"
[ -f ".cursorrules" ] && echo "Found: .cursorrules"
[ -f "AGENTS.md" ] && echo "Found: AGENTS.md"
fi
Tier 1 Indicators (High-Confidence):
| Tool | Files | Confidence Boost |
|---|---|---|
| Claude Code | CLAUDE.md, .claude/ | +0.30 |
| Cursor | .cursorrules, .cursor/rules/*.mdc | +0.25 |
| Windsurf | .windsurfrules, .windsurf/rules/ | +0.25 |
| GitHub Copilot | .github/copilot-instructions.md, **/.instructions.md | +0.20 |
| Cline/Roo | .clinerules, .clinerules/, .roo/ | +0.25 |
| Aider | CONVENTIONS.md, .aider.conf.yml, .aider.input.history | +0.25 |
| Continue.dev | .continuerules, .continue/rules/ | +0.25 |
| JetBrains AI | .aiignore | +0.20 |
| AGENTS.md | AGENTS.md (Linux Foundation standard, 60K+ projects) | +0.20 |
| Sourcegraph Cody | .vscode/cody.json | +0.15 |
| Replit | replit.nix + .replit | +0.15 |
| Ruler | .ruler/ (multi-tool manager) | +0.20 |
Tier 2 Indicators (Indirect):
| Indicator | Threshold | Interpretation |
|---|---|---|
| Comment density | >15% | AI-generated code (vs 5-8% manual) |
| Code consistency | >98% | Systematic AI assistance |
| Conventional Commits | 100% | AI tool integration |
| Docs-to-code ratio | >1:1 | AI documentation generation |
Phase 3: Generate Hypotheses (3-5 minutes)
Purpose
Based on scanned files, generate scale-appropriate hypotheses with confidence levels and evidence.
Step 3.1: Technology Stack Hypotheses
Based on config files and imports:
Example hypothesis:
tech_stack:
- hypothesis: "Primary framework is Express.js v4.18 with TypeScript"
confidence: 0.95
evidence: "package.json:12, src/app.ts:1-5"
validation_method: "grep 'express' package.json; check TypeScript config"
Categories:
- Primary language(s) and versions
- Framework(s) and major dependencies
- Database(s) and storage solutions
- Testing frameworks
Step 3.2: Architecture Hypotheses
Based on directory structure and entry points:
Example hypothesis:
architecture:
- hypothesis: "3-layer architecture: Controller → Service → Repository"
confidence: 0.85
evidence: "src/controllers/, src/services/, src/repositories/ exist"
validation_method: "trace UserController.ts flow"
Categories:
- Overall pattern (MVC, Clean Architecture, Microservices, etc.)
- Directory structure conventions
- Layering and separation of concerns
- Design patterns used
Step 3.3: Development Practices Hypotheses
Based on tests, docs, and code quality:
Example hypothesis:
development:
- hypothesis: "Jest + Supertest for API testing, 80%+ coverage"
confidence: 0.75
evidence: "package.json:25, tests/api/users.test.ts:1-20"
validation_method: "run npm test -- --coverage"
Categories:
- Code quality indicators
- Testing coverage and approach
- Documentation depth
- Git workflow patterns
Step 3.4: AI Collaboration Hypotheses
Based on Tier 1 + Tier 2 indicators:
Level Definitions:
- Level 0: No AI - No config files, low comment density (5-8%), inconsistent style
- Level 1: Occasional use - 1 tool config with minimal content
- Level 2: Frequent use - 1-2 tool configs + some indirect indicators
- Level 3: Systematic collaboration - Complete AI config + high comment density + consistent style
- Level 4: Ecosystem-level - Multiple tool configs (Ruler/.ruler/) or AGENTS.md + team-wide standards
Example hypothesis:
ai_collaboration:
level: 3
confidence: 0.90
tools_detected:
- tool: "Claude Code"
config_file: "CLAUDE.md"
content_quality: "comprehensive"
- tool: "Cursor"
config_file: ".cursorrules"
content_quality: "basic"
indicators:
- "High comment density (18% vs typical 5-8%)"
- "Consistent code style across all files"
- "Comprehensive inline documentation"
Step 3.5: Business Domain Hypotheses
Based on README, models, and code:
Example hypothesis:
business:
- hypothesis: "E-commerce platform with user, product, order management"
confidence: 0.80
evidence: "README.md:15-30, models/User.ts, models/Product.ts, models/Order.ts"
validation_method: "review core entity relationships"
Categories:
- What does this project do?
- Key entities and concepts
- Main features
Step 3.6: Hypothesis Quality Requirements
Each hypothesis MUST include:
- hypothesis: Clear, specific statement
- confidence: 0.0-1.0 (aim for >0.7)
- evidence: Specific file:line references
- validation_method: How to verify in Stage 1
Scale-Aware Targets (from Phase 1):
- TINY: 5-8 hypotheses
- SMALL: 7-10 hypotheses
- MEDIUM: 10-15 hypotheses
- LARGE: 12-18 hypotheses
- VERY_LARGE: 15-20 hypotheses
Performance Tips
For Large Codebases
# Limit search depth
find . -maxdepth 3 -name "*.py" ...
# Limit results
... | head -20
# Exclude large directories early
find . -path "*/vendor" -prune -o -path "*/dist" -prune -o ...
For Monorepos
# Search specific package only
find packages/api -name "*.ts" ...
# Or multiple related packages
find packages/{api,core} -name "*.ts" ...
Common Issues
Issue 1: Script Not Found
Symptom: Helper scripts not available
Solution:
- Check global:
~/.claude/scripts/atlas/ - Check local:
scripts/atlas/ - Use manual fallback commands provided in each step
Issue 2: Too Many Files
Symptom: Project scale is VERY_LARGE, overwhelming
Solution:
- Respect scan limits (10-15 files max)
- Focus on highest entropy files only
- Trust the 70-80% understanding goal
Issue 3: Git Not Available
Symptom: git branch fails
Solution:
- Set
context.git_branch: null - Continue analysis without git context
Output Transition
After Phase 3 completes:
- Compile all findings
- Structure as YAML (see output-template.md)
- Execute verification (see verification-guide.md)
- Save result (see reference.md#auto-save)
SourceAtlas: Pattern Learning Mode
Constitution: ANALYSIS_CONSTITUTION.md v1.0
Context
Pattern requested: $ARGUMENTS Goal: Learn how THIS specific codebase implements the requested pattern Time Limit: 5-10 minutes maximum
Quick Start
- Check cache (skip if
--forceflag present) - Detect pattern using
find-patterns.shscript - Apply output mode (--brief / --full / smart)
- Analyze top 2-3 files (high-entropy priority)
- Extract conventions and best practices
- Generate implementation guide
- Verify output using verification-guide.md
- Auto-save to
.sourceatlas/patterns/
Your Task
You are analyzing how THIS codebase implements a specific pattern by:
- Finding 2-3 best example files
- Extracting design patterns and conventions
- Providing actionable implementation guidance
Output Modes
| Parameter | Behavior | Use Case |
|---|---|---|
--brief | List files only | Quick file browser |
--full | Analyze all files | Deep learning |
| (default) | Smart: ≤5 files→full; >5→selection UI | Balanced |
Core Workflow
Execute these steps in order. See workflow.md for complete details.
Step 0: Parse Output Mode (10 seconds)
Purpose: Determine how much analysis to perform.
Detect flags:
--brief→ List files only, no analysis--full→ Analyze all found files- No flag → Smart mode (adapt based on file count)
→ See workflow.md#step-0
Step 1: Execute Pattern Detection (1-2 minutes)
Purpose: Find relevant files using optimized search.
Use find-patterns.sh script first:
# Locate script (global → local)
if [ -f ~/.claude/scripts/atlas/find-patterns.sh ]; then
SCRIPT_PATH=~/.claude/scripts/atlas/find-patterns.sh
elif [ -f scripts/atlas/find-patterns.sh ]; then
SCRIPT_PATH=scripts/atlas/find-patterns.sh
fi
bash "$SCRIPT_PATH" "$ARGUMENTS"
Supported patterns:
- api endpoint / api / endpoint
- background job / job / queue
- swiftui view / view
- view controller / viewcontroller
- authentication / auth / login
- file upload / upload
- database query / database
- networking / network
If unsupported: Fallback to manual Glob/Grep search
→ See workflow.md#step-1
Step 1.5: ast-grep Enhanced Search (Optional)
Purpose: More precise search for content-based patterns.
Use ast-grep-search.sh for:
- async/await patterns
- suspend functions (Kotlin)
- custom hooks (React)
- goroutines (Go)
Graceful degradation: Script handles ast-grep unavailability
→ See workflow.md#step-1-5
Step 2: Apply Output Mode Logic (30 seconds)
Purpose: Decide analysis depth based on file count.
Smart mode logic:
FILE_COUNT = 0 → "No files found"
FILE_COUNT ≤ 5 → Full analysis
FILE_COUNT > 5 → Selection interface
Brief mode: List files, end immediately
Full mode: Analyze all files (warn if >10)
→ See workflow.md#step-2
Step 3: Analyze Selected Files (3-5 minutes)
Purpose: Extract patterns from 2-3 best examples.
High-entropy priority:
- ✅ Main implementation files
- ✅ Complete examples (100-500 lines)
- ✅ Well-structured production code
- ❌ NOT: Utilities, trivial code, generated files
Focus areas:
- Overall structure
- Standard flow
- Naming conventions
- Dependencies
- Error handling
- Configuration
→ See workflow.md#step-3
Step 4: Extract the Pattern (2 minutes)
Purpose: Distill findings into reusable guidance.
Extract:
- How this codebase handles it (2-3 sentences)
- Standard flow (numbered steps)
- Key conventions (bullet points)
- Testing patterns
- Common pitfalls
→ See workflow.md#step-4
Step 5: Find Related Tests (1 minute, optional)
Purpose: Understand how pattern is tested.
find . \( -path "*/test/*" -o -path "*/tests/*" -o -name "*.test.*" \) \
-type f -not -path "*/node_modules/*" | head -20
→ See workflow.md#step-5
Step 6: Generate Implementation Guide (1 minute)
Purpose: Provide concrete steps to follow.
Create actionable, step-by-step guide with:
- Specific file locations
- Code structure templates
- Configuration steps
- Testing approach
→ See workflow.md#step-6
Output Format
Your analysis should follow this Markdown structure:
🗺️ SourceAtlas: Pattern
───────────────────────────────
🧩 [Pattern Name] │ [N] files found
## Overview
[2-3 sentence summary]
## Best Examples
### 1. [File Path]:[line]
[Purpose, Key Code, Key Points]
### 2. [File Path]:[line]
[Same structure]
## Key Conventions
- [Convention 1]
- [Convention 2]
- [Convention 3]
## Testing Pattern
[Test location, approach, examples]
## Common Pitfalls to Avoid
1. [Pitfall 1]
2. [Pitfall 2]
## Step-by-Step Implementation Guide
1. [Step 1]
2. [Step 2]
...
## Related Patterns (Optional)
[If applicable]
## Recommended Next (Optional)
[Dynamic suggestions based on findings]
→ See output-template.md for complete specification and examples
Critical Rules
1. Scan <5% of Files
- Use script for targeted search
- Read only top 2-3 files
- High-entropy priority
2. Focus on PATTERNS
- Extract reusable approaches
- Not line-by-line details
- Actionable conventions
3. Be Specific to THIS Codebase
- Not generic internet advice
- Actual code from this project
- Real file paths and examples
4. Provide Evidence
- file:line references always
- Code snippets from actual files
- Directory paths must exist
5. Time Limit: 5-10 Minutes
- Be efficient
- Don't read entire codebase
- Progressive disclosure
6. Verification Required
- Execute verification-guide.md after analysis
- Verify file paths, line numbers, code snippets
- Correct discrepancies before output
7. Constitutional Compliance
Follow ANALYSIS_CONSTITUTION.md:
- Article I: High-entropy priority (scan 2-3 best examples)
- Article II: Mandatory exclusions (node_modules, .venv, Pods)
- Article IV: Evidence format (file:line references)
Self-Verification
After generating your analysis, execute verification steps:
Step V1: Extract Verifiable Claims
- File paths (with line numbers)
- Directory paths
- Code snippets
- File counts
Step V2: Parallel Verification
- Verify file paths exist
- Verify line numbers within bounds
- Verify code snippets match files
- Verify directories exist
- Verify file counts (±2 tolerance)
Step V3: Handle Results
- ✅ All checks pass → Proceed to output
- ⚠️ Minor issues (1-2 checks) → Correct and note
- ❌ Major issues (3+ checks) → Re-execute analysis
Step V4: Add Verification Summary
verification_summary:
checks_performed: [...]
confidence_level: "high" # high|medium|low
notes: [...]
→ See verification-guide.md for complete checklist
Advanced
Cache Behavior
- Default: Use cache if exists
- Force flag: Skip cache with
--force - Cache location:
.sourceatlas/patterns/${PATTERN_NAME}.md - Cache age warning: If >30 days old
→ See reference.md#cache-behavior
Auto-Save Mechanism
Complete Markdown report auto-saves after verification:
💾 Saved to .sourceatlas/patterns/[pattern-name].md
→ See reference.md#auto-save-behavior
Handoffs to Next Commands
Based on findings, suggest:
- Complex flow →
/sourceatlas:flow "[entry point]" - Wide usage →
/sourceatlas:impact "[core file]" - Related pattern →
/sourceatlas:pattern "[related]"
→ See reference.md#handoffs
find-patterns.sh Script
- Pre-tested patterns for common use cases
- Optimized search (<20 seconds)
- Relevance ranking (⭐⭐⭐ / ⭐⭐ / ⭐)
- Graceful fallback to manual search
ast-grep Integration
- Content-based pattern search
- Higher precision for Type B patterns
- 14-93% false positive reduction
- Automatic fallback if unavailable
Support Files
Detailed documentation available in:
- workflow.md - Complete Step 0-6 execution guide with bash commands
- output-template.md - Full Markdown structure and examples
- verification-guide.md - Self-verification steps V1-V4
- reference.md - Cache, scripts, handoffs
Output Header
Start your output with:
🗺️ SourceAtlas: Pattern
───────────────────────────────
🧩 [Pattern Name] │ [N] files found
Then follow complete structure in output-template.md.
Pattern Learning Output Template
Complete Markdown format specification for pattern analysis reports.
Header Format
🗺️ SourceAtlas: Pattern
───────────────────────────────
🧩 [Pattern Name] │ [N] files found
Section 1: Overview
2-3 sentence summary of how this codebase implements the pattern.
## Overview
This codebase implements [pattern] using [approach/framework]. The pattern follows [architectural style] with [key characteristics]. [Additional context about why this approach was chosen or how it differs from standard implementations].
Example:
## Overview
This codebase implements API endpoints using Express.js controllers with a 3-layer architecture: Controller → Service → Repository. All endpoints follow RESTful conventions and use middleware for auth, validation, and error handling. The pattern emphasizes separation of concerns with clear boundaries between HTTP handling, business logic, and data access.
Section 2: Best Examples
Show 2-3 concrete examples from the codebase.
## Best Examples
### 1. [File Path]:[line]
**Purpose**: [What this example demonstrates - 1 sentence]
**Key Code**:
```[language]
[Relevant code snippet - 5-15 lines showing core pattern]
Key Points:
- [Important observation 1]
- [Important observation 2]
- [Important observation 3]
2. [File Path]:[line]
[Same structure as Example 1]
3. [File Path]:[line] (Optional)
[Only include if it adds significant new insight]
**Example:**
```markdown
## Best Examples
### 1. src/api/controllers/UserController.ts:45
**Purpose**: Demonstrates RESTful endpoint with authentication middleware
**Key Code**:
```typescript
@Controller('/api/users')
export class UserController extends BaseController {
constructor(private userService: UserService) {
super();
}
@Get('/:id')
@UseGuards(AuthGuard)
async getUser(@Param('id') id: string): Promise<UserResponse> {
const user = await this.userService.findById(id);
return this.formatResponse(user);
}
}
Key Points:
- Uses decorator-based routing (@Controller, @Get)
- Extends BaseController for common functionality
- Injects UserService via constructor
- Auth guard applied via @UseGuards decorator
- Async/await pattern for service calls
---
## Section 3: Key Conventions
Observable patterns extracted from examples.
```markdown
## Key Conventions
Based on the examples above, this codebase follows these conventions:
- **[Convention Category 1]** - [Specific rule/pattern]
- Location: [where to find examples]
- Example: [concrete example]
- **[Convention Category 2]** - [Specific rule/pattern]
- Location: [where to find examples]
- Example: [concrete example]
- **[Convention Category 3]** - [Specific rule/pattern]
- Location: [where to find examples]
- Example: [concrete example]
Example:
## Key Conventions
Based on the examples above, this codebase follows these conventions:
- **File Structure** - Controllers → Services → Repositories pattern
- Location: src/api/controllers/, src/services/, src/repositories/
- Example: UserController calls UserService calls UserRepository
- **Naming** - PascalCase for classes, camelCase for methods
- Location: All TypeScript files
- Example: UserController.getUser(), OrderService.createOrder()
- **Dependency Injection** - Constructor injection with private properties
- Location: All service and controller classes
- Example: constructor(private userService: UserService)
- **Error Handling** - Custom exception classes + global error handler
- Location: src/exceptions/, src/middleware/errorHandler.ts
- Example: throw new NotFoundException('User not found')
Section 4: Testing Pattern
How this pattern is tested in the codebase.
## Testing Pattern
**Test Location:** [path/to/tests/ or "No tests found"]
**Testing Approach:**
[Describe framework, structure, key testing strategies - 2-3 sentences]
**Example Test File:** [path/to/example.test.ext] (if available)
**Key Test Patterns:**
- [Test pattern 1]
- [Test pattern 2]
- [Test pattern 3]
Example:
## Testing Pattern
**Test Location:** tests/integration/api/
**Testing Approach:**
Uses Jest + Supertest for API integration tests. Tests follow Arrange-Act-Assert pattern with separate test database setup. Each test file mirrors the controller structure and tests both happy paths and error cases.
**Example Test File:** tests/integration/api/users.test.ts
**Key Test Patterns:**
- Mock external services using jest.mock()
- Test database seeded in beforeEach, cleaned in afterEach
- Use supertest for HTTP request testing
- Separate unit tests for services in tests/unit/services/
Section 5: Common Pitfalls to Avoid
Based on code analysis and anti-patterns observed.
## Common Pitfalls to Avoid
Based on code analysis and observations:
1. **[Pitfall 1]** - [What to avoid]
- Why: [Reason/consequence]
- Instead: [Correct approach]
2. **[Pitfall 2]** - [What to avoid]
- Why: [Reason/consequence]
- Instead: [Correct approach]
3. **[Pitfall 3]** - [What to avoid]
- Why: [Reason/consequence]
- Instead: [Correct approach]
Example:
## Common Pitfalls to Avoid
Based on code analysis and observations:
1. **Don't put business logic in controllers**
- Why: Controllers should only handle HTTP concerns (request parsing, response formatting)
- Instead: Move all business logic to service layer (UserService, OrderService, etc.)
2. **Don't call repositories directly from controllers**
- Why: Breaks the layered architecture and makes testing harder
- Instead: Always go through service layer: Controller → Service → Repository
3. **Don't forget input validation**
- Why: API is public-facing, all user input must be validated
- Instead: Use class-validator decorators on DTOs or middleware validators
Section 6: Step-by-Step Implementation Guide
Concrete steps to implement similar functionality.
## Step-by-Step Implementation Guide
To implement [similar functionality] following this codebase's pattern:
1. **[Step 1 Title]** - [Action with specifics]
- File: [where to create/modify]
- Code structure: [what to include]
- Example: [concrete code snippet or reference]
2. **[Step 2 Title]** - [Action with specifics]
- File: [where to create/modify]
- Code structure: [what to include]
- Example: [concrete code snippet or reference]
... (as many steps as needed, typically 4-7 steps)
Example:
## Step-by-Step Implementation Guide
To implement a new API endpoint following this codebase's pattern:
1. **Create Route Definition**
- File: src/routes/[resource].ts
- Code structure: Import controller, define routes
- Example:
```typescript
import { ProductController } from '../controllers/ProductController';
router.get('/api/products', controller.list);
router.post('/api/products', controller.create);
```
2. **Create Controller Class**
- File: src/controllers/[Resource]Controller.ts
- Code structure: Extend BaseController, inject service
- Example:
```typescript
@Controller('/api/products')
export class ProductController extends BaseController {
constructor(private productService: ProductService) {
super();
}
}
```
3. **Implement Controller Methods**
- File: Same as above
- Code structure: Use decorators, call service methods
- Example:
```typescript
@Get('/')
@UseGuards(AuthGuard)
async list(): Promise<ProductResponse[]> {
const products = await this.productService.findAll();
return this.formatList(products);
}
```
4. **Create Service Class**
- File: src/services/[Resource]Service.ts
- Code structure: Business logic, inject repository
- Example:
```typescript
export class ProductService {
constructor(private productRepo: ProductRepository) {}
async findAll(): Promise<Product[]> {
return this.productRepo.findAll({ active: true });
}
}
```
5. **Create Repository Class** (if database access needed)
- File: src/repositories/[Resource]Repository.ts
- Code structure: Extend BaseRepository, use ORM
- Example:
```typescript
export class ProductRepository extends BaseRepository<Product> {
async findAll(filters: any): Promise<Product[]> {
return this.model.findAll({ where: filters });
}
}
```
6. **Add Integration Tests**
- File: tests/integration/api/[resource].test.ts
- Code structure: Test happy path + error cases
- Example:
```typescript
describe('GET /api/products', () => {
it('returns list of products', async () => {
const response = await request(app).get('/api/products');
expect(response.status).toBe(200);
expect(response.body).toHaveLength(3);
});
});
```
Section 7: Related Patterns (Optional)
Patterns commonly used together.
## Related Patterns
[If applicable, mention related patterns in this codebase]
- **[Related Pattern 1]** - [Brief explanation of relationship]
- **[Related Pattern 2]** - [Brief explanation of relationship]
Example:
## Related Patterns
These patterns are commonly used with API endpoints in this codebase:
- **Middleware Pattern** - Auth, validation, and error handling middleware wrap all endpoints
- **DTO Pattern** - Data Transfer Objects validate and transform request/response data
- **Repository Pattern** - All database access abstracted behind repository interfaces
Section 8: Recommended Next (Optional)
Dynamic suggestions based on findings.
## Recommended Next
| # | Command | Purpose |
|---|---------|---------|
| 1 | `/sourceatlas:[command] "[parameter]"` | [Reason based on specific findings] |
| 2 | `/sourceatlas:[command] "[parameter]"` | [Reason based on specific findings] |
💡 Enter a number (e.g., `1`) or copy the command to execute
Rules:
- Only include if there are clear next steps
- Use actual discovered information (file names, patterns found)
- Limit to 1-2 suggestions
- Reference specific findings in Purpose column
Section 9: Additional Notes (Optional)
Project-specific quirks or important context.
## Additional Notes
[Any project-specific quirks, gotchas, or important context that doesn't fit above]
- [Note 1]
- [Note 2]
Footer Format
───────────────────────────────
🗺️ v2.13.1 │ Constitution v1.1
✅ Verified: [N] file paths, [M] directories, [K] code snippets
💾 Saved to .sourceatlas/patterns/[pattern-name].md
Complete Example
🗺️ SourceAtlas: Pattern
───────────────────────────────
🧩 API Endpoint │ 12 files found
## Overview
This codebase implements API endpoints using Express.js controllers with a 3-layer architecture: Controller → Service → Repository. All endpoints follow RESTful conventions and use middleware for auth, validation, and error handling. The pattern emphasizes separation of concerns with clear boundaries between HTTP handling, business logic, and data access.
---
## Best Examples
### 1. src/api/controllers/UserController.ts:45
**Purpose**: Demonstrates RESTful endpoint with authentication middleware
**Key Code**:
```typescript
@Controller('/api/users')
export class UserController extends BaseController {
constructor(private userService: UserService) {
super();
}
@Get('/:id')
@UseGuards(AuthGuard)
async getUser(@Param('id') id: string): Promise<UserResponse> {
const user = await this.userService.findById(id);
return this.formatResponse(user);
}
}
Key Points:
- Uses decorator-based routing (@Controller, @Get)
- Extends BaseController for common functionality
- Injects UserService via constructor
- Auth guard applied via @UseGuards decorator
- Async/await pattern for service calls
[... rest of sections ...]
─────────────────────────────── 🗺️ v2.13.1 │ Constitution v1.1
✅ Verified: 3 file paths, 4 directories, 5 code snippets
💾 Saved to .sourceatlas/patterns/api-endpoint.md
Pattern Learning Reference
Advanced features, caching behavior, and best practices.
Cache Behavior
When Cache is Used
# Default: Use cache if exists and fresh
/sourceatlas:pattern "api endpoint"
# Check logic:
pattern_name="api-endpoint" # sanitized from arguments
cache_file=".sourceatlas/patterns/${pattern_name}.md"
if [ -f "$cache_file" ]; then
age_days=$(calculate_age_in_days)
echo "📁 Loading from cache ($age_days days ago)"
if [ $age_days -gt 30 ]; then
echo "⚠️ Cache over 30 days old, recommend re-analysis"
fi
cat "$cache_file"
exit 0
fi
When Cache is Skipped
# Force flag: Always skip cache
/sourceatlas:pattern "api endpoint" --force
# → Executes full analysis even if cache exists
# No cache: First time analysis
# → .sourceatlas/patterns/api-endpoint.md doesn't exist yet
Cache File Naming
# Pattern name sanitization
"API Endpoint" → "api-endpoint.md"
"Background Job" → "background-job.md"
"React Component" → "react-component.md"
"Very Long Pattern Name..." → "very-long-pattern-name-that-exceeds-limit.md" (truncated to 50 chars)
# Rules:
# - Spaces → hyphens
# - Lowercase
# - Remove special characters
# - Truncate to 50 characters
Auto-Save Behavior
File Structure
.sourceatlas/patterns/
├── api-endpoint.md
├── background-job.md
├── repository-pattern.md
└── custom-hook.md
Save Timing
Auto-save occurs immediately after Step V4 verification:
# After verification passes
verification_summary:
confidence_level: "high"
# Then auto-save
💾 Saved to .sourceatlas/patterns/api-endpoint.md
What Gets Saved
Complete Markdown output including:
- Header with pattern name and file count
- Overview summary
- Best Examples (2-3 with code snippets)
- Key Conventions
- Testing Pattern
- Common Pitfalls
- Step-by-Step Guide
- Verification summary
Format: Full Markdown as specified in output-template.md
Handoffs: When to Suggest Next Commands
After Pattern with Complex Flow
If pattern involves multi-step execution:
Suggest:
| # | Command | Purpose |
|---|---------|---------|
| 1 | `/sourceatlas:flow "src/api/controllers/UserController.ts"` | Pattern involves 3-layer architecture, trace full execution flow |
After Pattern with Wide Usage
If pattern used in many files:
Suggest:
| # | Command | Purpose |
|---|---------|---------|
| 1 | `/sourceatlas:impact "src/services/BaseService.ts"` | Pattern used in 23 services, need to understand dependencies |
After Finding Related Pattern
If analysis mentions related patterns:
Suggest:
| # | Command | Purpose |
|---|---------|---------|
| 1 | `/sourceatlas:pattern "repository pattern"` | Controllers depend on repositories, need to understand that pattern next |
When to Stop (No Recommendations)
- Pattern is simple: Self-contained, no complex dependencies
- No clear next steps: Analysis complete, ready to implement
- Analysis depth sufficient: User already ran 4+ commands
Output instead:
✅ **Pattern analysis complete** - Can start implementation following the Step-by-Step Guide above
Common Verification Errors
Error 1: Hallucinated File Paths
Symptom: File paths that sound plausible but don't exist
Prevention:
- Always use actual search results
- Never guess file paths
- Verify each path before including
Error 2: Outdated Code Snippets
Symptom: Code snippet doesn't match current file
Recovery:
# Re-read file
cat "path/to/file.ts"
# Extract fresh snippet
sed -n '40,55p' "path/to/file.ts"
Error 3: Wrong Line Numbers
Symptom: Line number points to wrong content
Debug:
# Check file length
wc -l file.ts
# View lines around claimed line
sed -n '43,47p' file.ts # Show 45 ±2 lines
Fix: Re-read file, find correct line number
Integration with Other Commands
After pattern verification, consider:
- Pattern involves complex flow →
/sourceatlas:flow "[entry point]" - Pattern used in many files →
/sourceatlas:impact "[core file]" - Related pattern found →
/sourceatlas:pattern "[related pattern]"
Pattern Learning Self-Verification Guide
Complete verification checklist to ensure pattern analysis accuracy.
When to Verify
Execute after completing your pattern analysis, before outputting final results.
Verification Steps
Step V1: Extract Verifiable Claims
Parse your analysis output to identify all quantifiable claims:
verifiable_claims:
- "path/to/file.ts:45 contains pattern"
- "Found 12 files matching pattern"
- "Controllers placed in app/controllers/ directory"
- "Code snippet from UserController.ts"
Extract these for verification:
- File paths (with line numbers)
- Directory paths
- Code snippets (must match actual file content)
- File counts ("12 files found")
- Pattern-specific claims (naming conventions, structure)
Step V2: Parallel Verification Execution
Run verification commands in parallel for speed:
V2.1: Verify File Paths
# Check all file paths in "Best Examples" section
for path in "src/api/controllers/UserController.ts" "src/services/UserService.ts"; do
if [ ! -f "$path" ]; then
echo "❌ FILE_NOT_FOUND: $path"
fi
done
Check:
- ✅ All referenced file paths exist
- ⚠️ If file not found → Search for similar path or remove example
V2.2: Verify Line Numbers
# Verify line number references
file="src/api/controllers/UserController.ts"
claimed_line=45
# Check if line exists
total_lines=$(wc -l < "$file" 2>/dev/null)
if [ $claimed_line -gt $total_lines ]; then
echo "⚠️ LINE_OUT_OF_RANGE: $file:$claimed_line (file has $total_lines lines)"
fi
# Spot-check content at that line
sed -n "${claimed_line}p" "$file"
Check:
- ✅ Line numbers are within file bounds
- ✅ Content at line number matches description
- ⚠️ If line mismatch → Re-read file and find correct line
V2.3: Verify Code Snippets
# Verify code snippet exists in file
snippet_key_line="async getUser"
file="src/api/controllers/UserController.ts"
if ! grep -q "$snippet_key_line" "$file" 2>/dev/null; then
echo "❌ CODE_NOT_FOUND: '$snippet_key_line' in $file"
fi
Check:
- ✅ Key lines from code snippets exist in claimed files
- ✅ Code syntax is valid (no typos in snippet)
- ⚠️ If code not found → Re-read file and extract correct snippet
V2.4: Verify Directory Paths
# Verify directory paths in "Key Conventions"
for dir in "app/controllers" "app/services" "app/repositories"; do
if [ ! -d "$dir" ]; then
echo "❌ DIR_NOT_FOUND: $dir"
fi
done
Check:
- ✅ All mentioned directories exist
- ⚠️ If directory not found → Search for similar path or correct claim
V2.5: Verify File Counts
# Verify "Found N files" claim
claimed_count=12
actual_count=$(find . -path "*/*Controller.ts" -type f 2>/dev/null | wc -l | tr -d ' ')
if [ "$actual_count" != "$claimed_count" ]; then
echo "⚠️ COUNT_MISMATCH: claimed $claimed_count, actual $actual_count"
fi
Check:
- ✅ File count matches actual search results (±2 tolerance)
- ⚠️ If significant difference → Update count
Step V3: Handle Verification Results
Based on verification outcomes:
If All Checks Pass ✅
verification_status:
verified: true
checks_passed: 5
confidence: high
Proceed to output.
If Minor Issues Found ⚠️ (1-2 checks failed)
Examples:
- Line number off by 1-2 lines
- File count slightly different (±2)
- Directory path has different name
Action:
- Correct the specific claims
- Re-verify those claims
- Add note to output:
verification_notes:
- "Line numbers adjusted after verification"
- "File count corrected to 14 (was 12)"
If Major Issues Found ❌ (3+ checks failed)
Examples:
- Multiple file paths don't exist
- Code snippets not found in claimed files
- Directory structure completely different
Action:
- STOP - Do not output current analysis
- Re-execute Step 1-4 from workflow.md
- Use better search patterns
- Verify each file before including in examples
Step V4: Verification Summary
Add to final output (before footer):
verification_summary:
timestamp: "[ISO 8601]"
checks_performed:
- "File paths: ✅"
- "Line numbers: ✅"
- "Code snippets: ✅"
- "Directories: ✅"
- "File counts: ✅"
confidence_level: "high" # high|medium|low
notes:
- "[Any corrections made]"
Confidence Level Criteria:
| Level | Criteria |
|---|---|
| High | All 5 checks passed, no corrections |
| Medium | 4/5 checks passed, minor corrections |
| Low | <4 checks passed, major corrections |
Verification Examples
Example 1: File Path Verification
Claim: "src/api/controllers/UserController.ts:45"
Verification:
test -f "src/api/controllers/UserController.ts"
# Exit code: 0 (exists)
Result: ✅ File exists
Action: No correction needed
Example 2: Line Number Verification
Claim: "UserController.ts:45 - async getUser method"
Verification:
sed -n '45p' src/api/controllers/UserController.ts
# Output: async getUser(@Param('id') id: string): Promise<User> {
Result: ✅ Line matches description
Action: No correction needed
Example 3: Code Snippet Verification
Claim: Code snippet shows @UseGuards(AuthGuard)
Verification:
grep -n "@UseGuards(AuthGuard)" src/api/controllers/UserController.ts
# Output: 46: @UseGuards(AuthGuard)
Result: ⚠️ Line number slightly off (46 vs 45)
Action:
- Update reference to line 46
- Or expand snippet to show lines 45-46
- Note: "Line number adjusted"
Example 4: Non-existent File
Claim: "src/api/controllers/AdminController.ts example"
Verification:
test -f "src/api/controllers/AdminController.ts"
# Exit code: 1 (not found)
# Search for similar
find . -name "*Admin*Controller*" 2>/dev/null
# Output: src/admin/controllers/AdminController.ts
Result: ❌ File path incorrect
Action:
- Update path to correct location
- Or remove example if file doesn't exist
- Note: "File path corrected"
Example 5: Directory Structure Claim
Claim: "Controllers placed in app/controllers/"
Verification:
test -d "app/controllers"
# Exit code: 1 (not found)
# Search for controllers directory
find . -type d -name "controllers" 2>/dev/null | head -5
# Output:
# ./src/api/controllers
# ./packages/backend/controllers
Result: ❌ Directory path incorrect
Action:
- Update claim: "Controllers placed in src/api/controllers/"
- Note: "Directory path corrected"
Error Recovery
If Verification Script Fails
# If file not found
# → Use find to search
find . -name "UserController*" 2>/dev/null
# If grep fails
# → File might be binary or very large
file "$filepath"
# If wc fails
# → File might not exist
test -f "$filepath" || echo "File missing"
If Code Snippet Doesn't Match
Likely causes:
- Line number off by a few lines
- Code was recently refactored
- Wrong file referenced
Action:
- Re-read the entire file
- Search for key functions/patterns
- Extract fresh snippet with correct line numbers
If Many Files Don't Exist
Likely causes:
- Analyzing wrong directory
- Patterns were from different project
- Files were moved/deleted
Action:
- Verify current directory:
pwd - Check git status:
git status - Re-run pattern search from Step 1
- Only include files that currently exist
Best Practices
- Always verify file paths - Files may be moved/renamed
- Sample at least 3 code snippets - Ensures they're from actual code
- Check line numbers - Code changes, line numbers shift
- Verify directory structure - Projects reorganize over time
- Note all corrections - Transparency builds trust
Verification Checklist
Before finalizing output, confirm:
- All file paths in "Best Examples" verified to exist
- All line number references checked (within file bounds)
- All code snippets verified against actual files
- All directory paths in "Key Conventions" verified
- File counts verified (±2 tolerance acceptable)
- No placeholder values like "[file]" or "[path]" in output
Handoff to Next Steps
After verification:
- ✅ If confidence HIGH → Proceed to output
- ⚠️ If confidence MEDIUM → Include verification notes, warn user
- ❌ If confidence LOW → Re-execute entire analysis
See reference.md#handoffs for when to suggest next commands.
Pattern Learning Workflow
Complete step-by-step guide for learning design patterns from the codebase.
Overview
This workflow helps you understand how the current codebase implements specific patterns by:
- Finding 2-3 best example files (high-entropy priority)
- Analyzing implementation details
- Extracting conventions and best practices
- Providing actionable implementation guidance
Time Budget: 5-10 minutes total
Step 0: Parse Output Mode (10 seconds)
Detect Output Mode Parameter
Parse $ARGUMENTS for mode flags:
# Check for --brief
if echo "$ARGUMENTS" | grep -q "\-\-brief"; then
OUTPUT_MODE="brief"
# Check for --full
elif echo "$ARGUMENTS" | grep -q "\-\-full"; then
OUTPUT_MODE="full"
else
OUTPUT_MODE="smart" # Default
fi
Mode Behaviors
| Mode | Behavior | Use Case |
|---|---|---|
| --brief | List files only, no analysis | Quick file browser |
| --full | Analyze all found files | Deep learning session |
| smart (default) | ≤5 files → full; >5 → show selection UI | Balanced approach |
Step 1: Execute Pattern Detection (1-2 minutes)
Use find-patterns.sh Script
Priority: Try script first (tested, optimized, fast):
# Locate script (global → local fallback)
SCRIPT_PATH=""
if [ -f ~/.claude/scripts/atlas/find-patterns.sh ]; then
SCRIPT_PATH=~/.claude/scripts/atlas/find-patterns.sh
elif [ -f scripts/atlas/find-patterns.sh ]; then
SCRIPT_PATH=scripts/atlas/find-patterns.sh
fi
# Execute if found
if [ -n "$SCRIPT_PATH" ]; then
bash "$SCRIPT_PATH" "$ARGUMENTS"
else
echo "⚠️ find-patterns.sh not found, falling back to manual search"
fi
Script Output Format
src/api/controllers/user_controller.ts ⭐⭐⭐
src/api/controllers/order_controller.ts ⭐⭐⭐
src/api/controllers/payment_controller.ts ⭐⭐
...
Ranking criteria:
- ⭐⭐⭐ Exact filename match + relevant directory
- ⭐⭐ Filename match OR relevant directory
- ⭐ Partial match
Supported Predefined Patterns
The script recognizes these patterns:
Backend patterns:
- api endpoint / api / endpoint
- background job / job / queue
- file upload / upload / file storage
- database query / database / query
- authentication / auth / login
- middleware
- service object
- repository
Frontend patterns:
- react component / component
- custom hook / hook
- swiftui view / view
- view controller / viewcontroller
Infrastructure:
- networking / network
- caching / cache
Fallback: Manual Search
If script returns "Unknown pattern" or not found:
# Extract keywords from pattern
# Example: "video learning progress" → keywords: video, learning, progress
# Search by filename
find . -type f \( -name "*video*" -o -name "*learning*" -o -name "*progress*" \) \
-not -path "*/node_modules/*" \
-not -path "*/.venv/*" \
-not -path "*/Pods/*" \
2>/dev/null | head -20
# Search by content
grep -rl "video.*progress\|learning.*video" --include="*.ts" --include="*.swift" --include="*.py" . | \
grep -v node_modules | head -20
Step 1.5: ast-grep Enhanced Search (Optional)
When to Use
For Type B patterns (content-based, not filename-based):
| Pattern Type | Examples | Tool |
|---|---|---|
| Type A: Filename is pattern | ViewModel, Service, Repository | grep/find sufficient |
| Type B: Requires content analysis | async/await, suspend functions, decorators | ast-grep better |
Use ast-grep-search.sh Script
# Locate script
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
# Examples for different languages
# Swift async functions
$AST_SCRIPT pattern "async" --lang swift --path .
# Kotlin suspend functions
$AST_SCRIPT pattern "suspend" --lang kotlin --path .
# TypeScript custom hooks (use* prefix)
$AST_SCRIPT pattern "hook" --lang tsx --path .
# Go goroutines
$AST_SCRIPT pattern "goroutine" --lang go --path .
Performance Data
Based on integration tests:
| Pattern | False Positive Reduction |
|---|---|
| TypeScript custom hooks | 93% |
| Kotlin suspend functions | 51% |
| Kotlin data classes | 15% |
| Swift async functions | 14% |
Graceful Degradation
# If ast-grep not installed, get fallback command
$AST_SCRIPT pattern "async" --fallback
# Returns: grep equivalent command to use
Step 2: Apply Output Mode Logic (30 seconds)
Count Files Found
FILE_COUNT=$(wc -l < /tmp/pattern-results.txt | tr -d ' ')
Smart Mode Decision
if FILE_COUNT == 0:
→ Output "No matching files found"
→ Suggest alternative patterns
→ END
elif FILE_COUNT <= 5:
→ Proceed to Step 3 (full analysis)
else: # FILE_COUNT > 5
→ Show selection interface
→ Wait for user input
Selection Interface
Found {FILE_COUNT} related files, please select files to analyze:
| # | File Path | Relevance |
|---|-----------|-----------|
| 1 | src/api/controllers/user_controller.ts | ⭐⭐⭐ |
| 2 | src/api/controllers/order_controller.ts | ⭐⭐⭐ |
| 3 | src/api/controllers/payment_controller.ts | ⭐⭐ |
...
**Options:**
- Enter numbers separated by commas (e.g., `1,2,3`)
- Enter "all" to analyze all files
- Enter "top3" to analyze top 3 only
Brief Mode (--brief)
If --brief flag detected:
Found {FILE_COUNT} files matching pattern:
1. src/api/controllers/user_controller.ts ⭐⭐⭐
2. src/api/controllers/order_controller.ts ⭐⭐⭐
...
Use `/sourceatlas:pattern "{pattern}" --full` to analyze all files
Or specify file numbers: `/sourceatlas:pattern "{pattern}" 1,2,3`
Then END (no further analysis).
Full Mode (--full)
If --full flag detected:
- Bypass selection interface
- Proceed to analyze ALL found files
- Warn if >10 files: "Analyzing {N} files, this may take longer..."
Step 3: Analyze Selected Files (3-5 minutes)
High-Entropy File Priority
Read files in relevance order (top-ranked first):
What to prioritize:
- ✅ Main implementation files (controllers, services, handlers)
- ✅ Complete examples (100-500 lines ideal)
- ✅ Well-structured, production code
- ❌ NOT: Helper utilities, trivial code, generated files
Reading Strategy
For each selected file:
# Read file
cat "path/to/file.ts"
# Focus on:
# 1. Class/function structure
# 2. Imports/dependencies
# 3. Main execution flow
# 4. Error handling patterns
# 5. Configuration patterns
Analysis Focus Areas
1. Overall Structure
- How is code organized? (classes, functions, modules)
- What's the typical file length?
- How are concerns separated?
2. Standard Flow
- What's the typical execution path?
- How do components interact?
- What's the lifecycle?
3. Naming Conventions
- Variable naming: camelCase, snake_case, PascalCase?
- File naming: UserService.ts vs user_service.py?
- Directory structure patterns?
4. Dependencies
- What libraries/frameworks are imported?
- How are dependencies injected?
- Configuration management approach?
5. Error Handling
- Try/catch patterns?
- Error types/classes used?
- Error propagation strategy?
6. Testing Patterns
- Where are tests located?
- Testing framework used?
- Coverage approach?
Step 4: Extract the Pattern (2 minutes)
Pattern Summary (2-3 sentences)
Answer:
- How does THIS codebase handle this pattern?
- What makes it unique to this project?
- What's the high-level approach?
Example:
This codebase implements API endpoints using Express.js controllers
with a 3-layer architecture: Controller → Service → Repository.
All endpoints follow RESTful conventions and use middleware for
auth, validation, and error handling.
Standard Flow (Numbered Steps)
Document the typical execution path:
1. Request hits route → routes/users.ts
2. Middleware stack executes (auth, validation)
3. Controller method called → controllers/UserController.ts
4. Service layer handles business logic → services/UserService.ts
5. Repository accesses database → repositories/UserRepository.ts
6. Response formatted and returned
Key Conventions (Bullet Points)
List concrete, observable conventions:
- All controllers extend BaseController class
- Service objects placed in app/services/ directory
- Use constructor injection for dependencies
- Error responses follow RFC 7807 format (Problem Details)
- File naming: PascalCase for classes, camelCase for functions
Testing Pattern
Describe how this pattern is tested:
**Test Location:** tests/integration/api/
**Testing Approach:**
- Supertest for API integration tests
- Jest for unit testing controllers
- Mocks for service layer using jest.mock()
- Test database setup/teardown in beforeEach/afterEach
**Example test:** tests/integration/api/users.test.ts
Common Pitfalls
Identify from code observations:
1. Don't call services directly from routes - use controllers
2. Don't put business logic in controllers - use services
3. Don't forget to sanitize user input - use validators
Step 5: Find Related Tests (1 minute, optional)
Locate Test Files
# Find test directories
find . \( -path "*/test/*" -o -path "*/tests/*" -o -path "*/spec/*" \
-o -path "*/__tests__/*" \) -type d \
-not -path "*/node_modules/*" \
2>/dev/null | head -10
# Find test files by extension
find . \( -name "*.test.*" -o -name "*.spec.*" \) -type f \
-not -path "*/node_modules/*" \
2>/dev/null | head -20
Search for Pattern-Related Tests
# Example: Search for "UserController" tests
grep -rn "UserController\|user.*controller" \
--include="*.test.*" --include="*.spec.*" \
tests/ 2>/dev/null | head -10
Step 6: Generate Implementation Guide (1 minute)
Create Step-by-Step Guide
Based on analysis, provide concrete steps:
## Step-by-Step Implementation Guide
To implement a new API endpoint following this codebase's pattern:
1. **Create route definition**
- File: src/routes/[resource].ts
- Add route: router.get('/api/resource', controller.method)
2. **Create controller**
- File: src/controllers/[Resource]Controller.ts
- Extend BaseController
- Implement method with request validation
3. **Create service**
- File: src/services/[Resource]Service.ts
- Implement business logic
- Use dependency injection for repositories
4. **Create repository** (if database access needed)
- File: src/repositories/[Resource]Repository.ts
- Use ORM (e.g., Sequelize)
5. **Add tests**
- File: tests/integration/api/[resource].test.ts
- Test happy path and error cases
Error Handling
Issue: Pattern Not Recognized by Script
Symptom: Script returns "Unknown pattern"
Action:
- Inform user about unsupported pattern
- Suggest similar supported patterns
- Fall back to manual search using keywords
- Still provide analysis based on findings
Issue: No Files Found
Symptom: 0 results from search
Action:
⚠️ No files found matching pattern: "{pattern}"
Possible reasons:
- Pattern doesn't exist in this codebase
- Using different naming conventions
- Pattern is in language we didn't search
Suggestions:
- Try related patterns: [list similar patterns]
- Check documentation or ask team members
- Use different keywords: [suggest alternatives]
Issue: Pattern Too Generic
Symptom: >50 files found, too broad
Action:
⚠️ Found {N} files for pattern "{pattern}" - too generic
Please specify a more specific pattern:
- Instead of "service", try "payment service" or "email service"
- Instead of "component", try "react component" or "button component"
- Instead of "controller", try "api controller" or "admin controller"
Issue: Files Are Test Files
Symptom: Top results are all test files
Action:
- Filter out test files from ranking
- Look for production implementation files
- Note: "Found mostly test files, looking for production code..."
# Exclude test files from search
grep -v "\.test\." results.txt | grep -v "\.spec\." | grep -v "/test/" | grep -v "/tests/"
Output Generation Tips
Best Examples Section
### 1. src/api/controllers/UserController.ts:45
**Purpose**: Demonstrates RESTful endpoint with auth middleware
**Key Code**:
```typescript
@Get('/api/users/:id')
@UseGuards(AuthGuard)
async getUser(@Param('id') id: string): Promise<User> {
return await this.userService.findById(id);
}
Key Points:
- Uses decorator-based routing
- Auth guard applied via @UseGuards
- Async/await for service calls
- TypeScript types for request/response
### Key Conventions Section
Be specific and observable:
```markdown
## Key Conventions
- **All controllers extend BaseController** - provides common methods (found in: src/common/BaseController.ts)
- **Service objects use constructor injection** - e.g., constructor(private userRepo: UserRepository)
- **Error responses follow RFC 7807** - {type, title, status, detail, instance}
- **File structure**: controllers/ → services/ → repositories/
Performance Optimization
For Large Codebases
# Limit search depth
find . -maxdepth 5 -name "*controller*" ...
# Limit results
... | head -20
# Exclude large directories early
find . -path "*/vendor" -prune -o -path "*/dist" -prune -o ...
For Monorepos
# Search specific package only
find packages/api -name "*controller*" ...
# Or multiple related packages
find packages/{api,core} -name "*controller*" ...
Integration with Other Commands
After pattern analysis, suggest:
- Complex flow found →
/sourceatlas:flow "[entry point]" - Pattern used widely →
/sourceatlas:impact "[core file]" - Related pattern mentioned →
/sourceatlas:pattern "[related pattern]"
SourceAtlas: Clear Saved Results
Context
Target: $ARGUMENTS (default: all)
Your Task
Help user clear saved analysis results from .sourceatlas/ directory.
Step 1: Check what exists
ls -la .sourceatlas/ 2>/dev/null || echo "No .sourceatlas/ directory found"
Also check subdirectories:
# Count files in each subdirectory
for dir in patterns flows impact deps; do
if [ -d ".sourceatlas/$dir" ]; then
count=$(ls -1 ".sourceatlas/$dir" 2>/dev/null | wc -l)
echo "$dir/: $count files"
fi
done
Step 2: Report findings
List what will be deleted based on target:
- If no argument or "all": list everything
- If specific target (e.g., "patterns"): list only that
Example output:
Found the following saved analyses:
- overview.yaml (2025-12-12)
- patterns/ (3 files)
- history.md (2025-12-11)
Are you sure you want to delete?
Step 3: Wait for confirmation
Ask user to confirm. Do NOT proceed without explicit confirmation.
Acceptable confirmations:
- "yes"
- "ok"
- "confirm"
- "delete"
- "sure"
- etc.
Step 4: Delete if confirmed
Based on target:
# All (default, no argument)
rm -rf .sourceatlas/*
# Specific targets
rm -f .sourceatlas/overview.yaml # for "overview"
rm -rf .sourceatlas/patterns/ # for "patterns"
rm -rf .sourceatlas/flows/ # for "flows"
rm -f .sourceatlas/history.md # for "history"
rm -rf .sourceatlas/impact/ # for "impact"
rm -rf .sourceatlas/deps/ # for "deps"
Step 5: Confirm deletion
✅ Cleared [target or ".sourceatlas/"]
If nothing to clear
.sourceatlas/ directory does not exist or is already empty
Target Reference
| Target | Path | Description |
|---|---|---|
overview | .sourceatlas/overview.yaml | Project overview |
patterns | .sourceatlas/patterns/ | Pattern analysis |
flows | .sourceatlas/flows/ | Flow analysis |
history | .sourceatlas/history.md | Temporal analysis |
impact | .sourceatlas/impact/ | Impact analysis |
deps | .sourceatlas/deps/ | Dependency analysis |
| (no argument) | .sourceatlas/* | Clear all |
Sponsors
Details
- Marketplace
- lis186/SourceAtlas
- Source
- plugin
- Category
- Community