
Diagram
- 26 installs
- 16 repo stars
- Updated November 21, 2025
- johnlindquist/claude-workshop-skills
Generate ASCII diagrams and flowcharts from text descriptions for documentation and visualization.
About
Creates ASCII art diagrams from natural language descriptions. Supports flowcharts, sequence diagrams, and architecture visuals.
- Multiple diagram types from text
- Pure ASCII output for docs and terminal
Diagram by the numbers
- 26 all-time installs (skills.sh)
- Ranked #958 of 1,879 Documentation skills by installs in the Skillselion catalog
- Data as of Aug 2, 2026 (Skillselion catalog sync)
npx skills add https://github.com/johnlindquist/claude-workshop-skills --skill diagramAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 26 |
|---|---|
| repo stars | ★ 16 |
| Last updated | November 21, 2025 |
| Repository | johnlindquist/claude-workshop-skills ↗ |
What it does
Generate ASCII diagrams and flowcharts from text descriptions for documentation and visualization.
Files
Diagram Driven Development (DDD) Skill
Maintain the ai/diagrams directory as the single source of truth for system understanding. All diagrams follow DDD principles, connecting Front-Stage (user experience) to Back-Stage (technical implementation) with clear impact annotations.
Capabilities
1. Create Diagrams - Generate new diagrams for features, architectures, journeys, tests, and refactorings 2. Update Diagrams - Synchronize existing diagrams with code changes 3. Audit Diagrams - Identify outdated, missing, or low-quality diagrams 4. Organize Diagrams - Maintain consistent structure and naming conventions 5. Index Management - Keep README.md index up-to-date with all diagrams 6. Quality Validation - Ensure all diagrams follow DDD principles
Quick Reference
For detailed instructions on each operation, see:
- CREATE.md - Creating new diagrams
- UPDATE.md - Updating existing diagrams
- AUDIT.md - Auditing diagram quality and coverage
- ORGANIZE.md - Directory structure and naming
- DDD_PRINCIPLES.md - Diagram Driven Development methodology
- MERMAID_GUIDE.md - Mermaid syntax patterns
Directory Structure
ai/diagrams/
├── README.md # Index of all diagrams
├── features/ # Feature-specific diagrams
├── architecture/ # System architecture diagrams
├── journeys/ # User journey diagrams
├── tests/ # Test coverage diagrams
└── refactoring/ # Before/After improvement diagramsCommon Workflows
Initial Setup Workflow
1. User starts new project or adds DDD to existing project 2. Create ai/diagrams/ directory structure 3. Generate initial system architecture diagram 4. Create README.md index 5. Document key user journeys
New Feature Workflow
1. User requests new feature 2. Create feature diagram showing user value 3. Connect Front-Stage (UX) to Back-Stage (implementation) 4. Document related files and components 5. Update README.md index
Code Change Workflow
1. Code is modified (new features, refactoring, etc.) 2. Identify affected diagrams 3. Update diagrams to reflect changes 4. Update "Last Updated" dates 5. Add change history entries
Audit Workflow
1. User requests diagram audit 2. Scan all diagrams in ai/diagrams/ 3. Check for outdated diagrams (compare dates with git) 4. Identify missing diagrams (features without diagrams) 5. Validate DDD quality (Front-Stage/Back-Stage, impact annotations) 6. Report findings and recommendations
Refactoring Documentation Workflow
1. User plans code refactoring 2. Create "Before" diagram showing current state 3. Create "After" diagram showing improved state (highlight changes in #90EE90) 4. Add impact annotations explaining user benefits 5. Store in refactoring/ directory
Critical Instructions
REQUIRED: Before performing ANY diagram operations, you MUST load the relevant reference file(s) using the Read tool. These references contain essential DDD principles, quality standards, and operational procedures that are NOT included in this overview.
When the user asks to work with diagrams:
1. Identify the operation they want to perform (create, update, audit, organize) 2. MANDATORY: Load the relevant reference file(s) using the Read tool BEFORE executing any operations:
- Creating diagrams → Read
references/CREATE.mdANDreferences/DDD_PRINCIPLES.mdFIRST - Updating diagrams → Read
references/UPDATE.mdANDreferences/DDD_PRINCIPLES.mdFIRST - Auditing diagrams → Read
references/AUDIT.mdFIRST - Organizing/restructuring → Read
references/ORGANIZE.mdFIRST - Understanding DDD → Read
references/DDD_PRINCIPLES.mdFIRST - Mermaid syntax help → Read
references/MERMAID_GUIDE.mdFIRST
3. Execute diagram operations following the exact patterns and quality standards from the loaded references 4. Validate quality using DDD principles checklist 5. Update index in README.md to reflect changes 6. Confirm actions and show diagram preview when possible
DO NOT attempt to create or modify diagrams without first loading and reading the relevant reference documentation, especially DDD_PRINCIPLES.md.
DDD Core Principles (Brief)
Every diagram MUST include:
- ✅ Front-Stage (user experience) AND Back-Stage (implementation)
- ✅ Impact Annotations explaining user value of technical components
- ✅ User Actions as entry/exit points
- ✅ Error Paths and recovery options
- ✅ Related Files documentation
- ❌ NO custom fill colors (except
#90EE90for Before/After changes) - ❌ NO purely technical diagrams without user context
Naming Conventions
File Names
- Descriptive lowercase with hyphens
- Include diagram type prefix
- Format:
{type}-{descriptive-name}.md
Examples:
feature-user-checkout-flow.mdsequence-authentication-journey.mdarch-system-overview.mdflow-payment-processing.md
Type Prefixes
feature-- Feature-specific diagramssequence-- Sequence/journey diagramsarch-- Architecture diagramsflow-- Flow/process diagramstest-- Test coverage diagrams
Diagram File Structure
# [Diagram Title]
**Type:** [Feature Diagram | Sequence Diagram | Architecture Diagram | etc.]
**Last Updated:** [YYYY-MM-DD]
**Related Files:**
- `path/to/implementation.ts`
- `path/to/component.tsx`
## Purpose
[1-2 sentence description of what user value this diagram illustrates]
## Diagram
\`\`\`mermaid
[Mermaid diagram code following DDD principles]
\`\`\`
## Key Insights
- [User impact point 1]
- [User impact point 2]
- [Technical enabler point 1]
## Change History
- **YYYY-MM-DD:** [Description of change]Quality Checklist
Before storing any diagram, verify:
- [ ] Shows both Front-Stage (user experience) AND Back-Stage (implementation)
- [ ] Impact annotations explain user value
- [ ] User actions are clearly visible
- [ ] Error paths shown
- [ ] NO custom fill colors (except #90EE90 for changes)
- [ ] Related code files documented
- [ ] Last updated date is current
- [ ] Key insights explain user impact
- [ ] Mermaid syntax is valid
Best Practices
1. Keep diagrams synchronized - Outdated diagrams are worse than no diagrams 2. Follow DDD principles - Every diagram connects user value to implementation 3. Use subdirectories - Organize by type to prevent chaos 4. Maintain the index - README.md is the entry point 5. Document changes - Update change history when modifying 6. Validate quality - Run through DDD checklist before saving 7. Reference code files - Link diagrams to actual implementation 8. Show error paths - Don't just show happy paths 9. Use consistent naming - Predictable names enable navigation 10. Update after code changes - Diagrams must reflect current state
Integration with Other Skills
- review - Reference diagrams during code reviews to explain impact
- github - Link diagrams in issue descriptions for context
- chrome-devtools - Use diagrams to plan testing flows
Examples
Create feature diagram
User: "Create a diagram for the new notification system"
Agent:
1. Reads references/CREATE.md and references/DDD_PRINCIPLES.md
2. Analyzes notification feature code
3. Creates feature-notification-system.md in features/
4. Includes user journey and technical implementation
5. Adds impact annotations
6. Updates README.md indexUpdate after refactoring
User: "We just refactored the auth flow, update the diagram"
Agent:
1. Reads references/UPDATE.md
2. Finds sequence-authentication-journey.md
3. Compares with new code
4. Updates diagram with changes
5. Updates "Last Updated" date
6. Adds change history entryAudit all diagrams
User: "Audit our diagrams"
Agent:
1. Reads references/AUDIT.md and references/DDD_PRINCIPLES.md
2. Scans ai/diagrams/ directory
3. Checks each diagram against DDD checklist
4. Compares diagram dates with git history
5. Identifies missing diagrams
6. Reports findings with recommendationsCritical Rules
1. Diagrams MUST stay synchronized with code - Check git history vs diagram dates 2. Every diagram MUST follow DDD principles - No purely technical diagrams 3. Organization is critical - Use subdirectories consistently 4. Index MUST be maintained - README.md reflects all diagrams 5. File naming MUST be consistent - Follow type-name pattern 6. Quality over quantity - Better to have 5 great diagrams than 20 poor ones 7. User value is paramount - Every technical detail must connect to user impact 8. Always load references first - DDD principles are not negotiable
Workflow Integration
This skill integrates with development workflow:
1. Before Code Changes - Review existing diagrams to understand system 2. During Planning - Create proposal diagrams showing planned changes 3. During Implementation - Reference diagrams to maintain alignment 4. After Implementation - Update diagrams to reflect changes 5. During Review - Use diagrams to explain impact and context 6. During Onboarding - Diagrams serve as documentation for new team members
Diagrams Skill (Diagram Driven Development)
A comprehensive skill for maintaining Unified Impact Diagrams that connect user value to technical implementation following Diagram Driven Development (DDD) methodology.
Overview
This skill helps you maintain the ai/diagrams directory as the single source of truth for system understanding. Unlike traditional technical diagrams, DDD diagrams always show:
- Front-Stage: What users see and experience
- Back-Stage: How we deliver that experience
- Impact Annotations: Why each technical component matters to users
- Error Paths: What happens when things go wrong
- User Value: Clear connection from code to user benefit
Philosophy
Traditional diagrams answer "What does the code do?" DDD diagrams answer "Why does it matter to users?"
Every technical decision should trace back to user value, and diagrams make that connection explicit.
Skill Structure
diagrams/
├── SKILL.md # Main skill definition
├── README.md # This file
└── references/
├── DDD_PRINCIPLES.md # Core methodology (READ FIRST)
├── CREATE.md # Creating new diagrams
├── UPDATE.md # Updating existing diagrams
├── AUDIT.md # Auditing quality and coverage
├── ORGANIZE.md # Directory structure and naming
└── MERMAID_GUIDE.md # Mermaid syntax patternsCore Capabilities
1. Create Diagrams
Generate new diagrams for features, architectures, user journeys, test coverage, and refactoring plans.
Supported Types:
- Feature diagrams (feature-*.md)
- Sequence diagrams (sequence-*.md)
- Architecture diagrams (arch-*.md)
- Flow diagrams (flow-*.md)
- Test coverage diagrams (test-*.md)
- Refactoring Before/After (in refactoring/)
2. Update Diagrams
Keep diagrams synchronized with code changes, ensuring they remain accurate and useful.
3. Audit Diagrams
- Quality Audit: Check if diagrams follow DDD principles
- Coverage Audit: Identify features without diagrams
- Synchronization Audit: Find outdated diagrams
- Organization Audit: Ensure proper structure and naming
4. Organize Diagrams
Maintain clean directory structure with consistent naming conventions.
5. Index Management
Keep README.md updated as the entry point for understanding the system.
Directory Structure
ai/diagrams/
├── README.md # Index (always up-to-date)
├── features/ # Feature-specific flows
│ └── feature-*.md
├── architecture/ # System-level diagrams
│ └── arch-*.md
├── journeys/ # User journey sequences
│ └── sequence-*.md
├── tests/ # Test coverage
│ └── test-*.md
└── refactoring/ # Before/After improvements
└── feature-*.mdQuick Start
Creating Your First Diagram
1. Understand the user need
- What problem does this solve?
- What value does it deliver?
2. Choose diagram type
- Feature flow →
features/feature-{name}.md - User journey →
journeys/sequence-{name}.md - System architecture →
architecture/arch-{name}.md
3. Read DDD_PRINCIPLES.md (REQUIRED)
references/DDD_PRINCIPLES.md4. Read CREATE.md for patterns
references/CREATE.md5. Create using template
- Both Front-Stage and Back-Stage
- Impact annotations on all Back-Stage components
- Error paths with recovery options
- User as entry/exit point
6. Update README.md index
Usage Examples
Example 1: New Feature Diagram
User Request: "Create a diagram for the new payment processing feature"
Agent Workflow: 1. Reads references/DDD_PRINCIPLES.md and references/CREATE.md 2. Analyzes payment feature code 3. Creates features/feature-checkout-payment-flow.md:
- Shows user clicking "Pay Now" (Front-Stage)
- Shows payment gateway, validation, order creation (Back-Stage)
- Adds impact annotations (🛡️ Secure, 💾 Guarantees save, ⚡ Fast)
- Shows error paths (payment fails → retry options)
4. Updates ai/diagrams/README.md index
Example 2: Update After Code Change
User Request: "We added caching to the search feature, update the diagram"
Agent Workflow: 1. Reads references/UPDATE.md 2. Finds features/feature-search-functionality.md 3. Adds cache layer to diagram with impact annotation (⚡ 80% faster) 4. Updates "Last Updated" date 5. Adds change history entry
Example 3: Audit Diagrams
User Request: "Audit our diagrams for quality and coverage"
Agent Workflow: 1. Reads references/AUDIT.md and references/DDD_PRINCIPLES.md 2. Scans all diagrams in ai/diagrams/ 3. Checks each against DDD quality checklist 4. Identifies features without diagrams 5. Compares diagram dates with git history 6. Creates comprehensive audit report with recommendations
Example 4: Before/After Refactoring
User Request: "We're adding a caching layer to improve performance. Document the change."
Agent Workflow: 1. Reads references/CREATE.md (refactoring section) 2. Creates refactoring/feature-add-caching-layer.md 3. Shows "Before" diagram (current slow flow) 4. Shows "After" diagram (with cache, highlighted in #90EE90) 5. Annotates performance improvements (2s → 50ms) 6. Explains user benefit (instant search results)
DDD Core Principles (Brief)
Every diagram MUST include:
✅ Both Stages
- Front-Stage (user experience)
- Back-Stage (technical implementation)
✅ Impact Annotations
- ⚡ Speed/Performance
- 💾 Storage/Persistence
- 🛡️ Security/Safety
- ✅ Validation/Success
- ⏱️ Responsiveness
- 🔄 Recovery/Retry
- 📊 Data Accuracy
- 🎯 Feature Enablement
✅ User-Centric
- User as entry/exit point
- User actions are visible
- User outcomes are clear
✅ Error Handling
- Error paths shown
- Recovery options included
- Fallback behavior documented
❌ Prohibited
- Purely technical diagrams without user context
- Missing impact annotations
- Only happy path (no errors)
- Custom colors (except #90EE90 for changes)
For complete principles, read references/DDD_PRINCIPLES.md.
Reference Files
DDD_PRINCIPLES.md (START HERE)
Purpose: Core methodology and philosophy Read when: Before creating any diagram Contains: Front-Stage/Back-Stage, impact annotations, error paths, quality checklist
CREATE.md
Purpose: Creating new diagrams Read when: Making a new diagram Contains: Templates, patterns, examples, validation checklist
UPDATE.md
Purpose: Updating existing diagrams Read when: Code changes affect diagrams Contains: Update patterns, synchronization strategies, metadata updates
AUDIT.md
Purpose: Auditing diagram quality Read when: Need to assess diagram health Contains: Quality checks, coverage analysis, synchronization audits, reports
ORGANIZE.md
Purpose: Directory structure and naming Read when: Organizing or reorganizing diagrams Contains: Naming conventions, directory rules, index structure, migration
MERMAID_GUIDE.md
Purpose: Mermaid syntax reference Read when: Need help with Mermaid syntax Contains: Flowchart patterns, sequence diagrams, styling, common mistakes
Workflow Integration
Development Workflow
1. Planning Phase
├─ Review existing diagrams
└─ Create proposal diagrams for new features
2. Implementation Phase
├─ Reference diagrams during coding
└─ Ensure code matches diagram intent
3. Completion Phase
├─ Update diagrams to reflect implementation
└─ Add change history entries
4. Review Phase
├─ Use diagrams to explain changes
└─ Verify diagrams match codeCollaboration Workflow
1. Onboarding
└─ New developers read diagrams to understand system
2. Architecture Reviews
└─ Use diagrams to discuss system design
3. Code Reviews
└─ Reference diagrams to explain impact
4. Documentation
└─ Diagrams serve as living documentationQuality Standards
Minimum Requirements
Every diagram must have:
- [ ] Proper file structure (Type, Last Updated, Related Files, Purpose, Diagram, Key Insights, Change History)
- [ ] Front-Stage showing user experience
- [ ] Back-Stage showing implementation
- [ ] Impact annotations on Back-Stage components
- [ ] At least one error path with recovery
- [ ] Valid Mermaid syntax
- [ ] Entry in README.md index
Excellent Diagram Characteristics
- Clear user journey from start to finish
- Every technical component has meaningful impact annotation
- Multiple error paths with recovery options shown
- Performance metrics quantified where possible
- Related code files documented
- Change history tracks evolution
- Key insights explain user value clearly
Common Workflows
Workflow 1: New Project Setup
# 1. Create directory structure
mkdir -p ai/diagrams/{features,architecture,journeys,tests,refactoring}
# 2. Create README.md index
# (Use ORGANIZE.md template)
# 3. Create system architecture diagram
# (Use CREATE.md patterns)
# 4. Document key user journeys
# (Use sequence diagram patterns)Workflow 2: Feature Addition
1. Create feature diagram before coding
2. Use diagram to guide implementation
3. Update diagram if implementation differs
4. Add to README.md index
5. Reference in pull requestWorkflow 3: Refactoring
1. Create Before diagram (current state)
2. Create After diagram (proposed state)
3. Highlight changes in #90EE90
4. Document user impact of changes
5. Use in architecture review
6. Update after implementationWorkflow 4: Monthly Audit
1. Run quality audit (check DDD compliance)
2. Run coverage audit (find missing diagrams)
3. Run sync audit (find outdated diagrams)
4. Create prioritized fix list
5. Schedule updates for high-priority itemsBest Practices
1. Keep synchronized - Update diagrams immediately after code changes 2. User-first thinking - Always start with user need 3. Show errors - Don't just show happy paths 4. Quantify impact - Use metrics in annotations (2s → 50ms) 5. Maintain index - README.md is the entry point 6. Validate quality - Run through DDD checklist before saving 7. Document changes - Change history helps future understanding 8. Load references - Always read relevant reference files first 9. Test Mermaid - Validate syntax before committing 10. Regular audits - Monthly audits keep diagrams healthy
Integration with Other Skills
With chrome-devtools
Use diagrams to plan testing flows:
- Create sequence diagram of user journey
- Use chrome-devtools to test each step
- Verify error paths actually work
- Update diagram with actual timings
With github
Link diagrams in issues and PRs:
- Reference diagrams to explain features
- Include diagram links in issue descriptions
- Use in PR descriptions to show impact
- Create issues from diagram audit findings
With review
Reference diagrams during code reviews:
- Show how code connects to user value
- Explain architectural decisions
- Discuss error handling strategies
- Validate implementation matches design
Troubleshooting
"I don't know what user value this provides"
Solution: Ask these questions:
- What problem does this solve?
- What happens if we don't have this?
- How does this improve the user experience?
- What metrics improve (speed, reliability, security)?
If you can't answer these, reconsider if the feature is necessary.
"The diagram is too complex"
Solutions:
- Split into multiple diagrams (overview + details)
- Use subgraphs to organize complexity
- Create separate sequence diagrams for detailed flows
- Focus on one aspect per diagram
"Code changed but I don't know which diagrams"
Solution:
# Find diagrams referencing changed files
grep -r "path/to/changed/file" ai/diagrams/
# Check diagram dates vs git history
git log --since="diagram-date" path/to/file"Mermaid won't render"
Solutions:
- Copy code to Mermaid Live Editor
- Check for common syntax errors (see MERMAID_GUIDE.md)
- Validate bracket matching
- Check arrow syntax
- Ensure graph direction is specified
Metrics to Track
Monitor diagram health over time:
- Total number of diagrams
- Percentage meeting DDD standards
- Feature coverage percentage
- Average diagram age
- Time from code change to diagram update
- Number of broken links
- Audit findings trend
Resources
- DDD Command:
/sync-diagrams- Original command this skill is based on - Mermaid Live: https://mermaid.live - Test diagrams
- Mermaid Docs: https://mermaid.js.org - Full documentation
- Review Skill: Use for reviewing diagram quality
Version
Skill created based on /sync-diagrams command (January 2025)
Summary
This skill helps maintain high-quality, user-centric diagrams that bridge the gap between technical implementation and user value. By following DDD principles, your diagrams become powerful tools for:
- Understanding system behavior
- Communicating with stakeholders
- Onboarding new team members
- Making architectural decisions
- Connecting code changes to user impact
Remember: Outdated diagrams are worse than no diagrams. Keep them synchronized, keep them user-focused, and keep them valuable.
Auditing Diagrams
Comprehensive guide for auditing diagram quality, coverage, and synchronization.
Audit Types
1. Quality Audit
Check if diagrams follow DDD principles
2. Coverage Audit
Identify features/flows without diagrams
3. Synchronization Audit
Find outdated diagrams that don't match code
4. Organization Audit
Ensure proper file structure and naming
Quality Audit Process
Step 1: List All Diagrams
# Find all diagram files
find ai/diagrams -name "*.md" -not -name "README.md"
# Count diagrams by type
find ai/diagrams -name "feature-*.md" | wc -l
find ai/diagrams -name "sequence-*.md" | wc -l
find ai/diagrams -name "arch-*.md" | wc -lStep 2: Check Each Diagram Against DDD Principles
For each diagram, verify:
Structure Check
- [ ] File has proper header (Type, Last Updated, Related Files)
- [ ] File has Purpose section
- [ ] File has Mermaid code block
- [ ] File has Key Insights section
- [ ] File has Change History section
DDD Compliance Check
- [ ] Shows Front-Stage (user experience)
- [ ] Shows Back-Stage (implementation)
- [ ] User is entry point or primary actor
- [ ] Impact annotations on Back-Stage components
- [ ] Error paths are shown
- [ ] Recovery options are included
- [ ] No custom colors (except #90EE90 for Before/After)
Content Quality Check
- [ ] Purpose focuses on user value, not technical details
- [ ] Impact annotations use appropriate symbols (⚡💾🛡️✅⏱️🔄📊🎯)
- [ ] Impact annotations explain user benefit
- [ ] Key insights connect technical to user value
- [ ] Mermaid syntax is valid
- [ ] Diagram is readable (not too complex)
Metadata Check
- [ ] "Last Updated" is within reasonable timeframe
- [ ] "Related Files" paths are valid
- [ ] File is in correct directory
- [ ] File name follows naming convention
Step 3: Create Quality Report
# Diagram Quality Audit Report
**Date:** YYYY-MM-DD
**Total Diagrams:** X
## Quality Summary
- ✅ **Excellent** (meets all criteria): X diagrams
- ⚠️ **Needs Improvement** (minor issues): X diagrams
- ❌ **Poor Quality** (major issues): X diagrams
## Issues Found
### High Priority (Blocks user understanding)
1. **feature-checkout-flow.md**
- ❌ Missing error paths
- ❌ No impact annotations
- Action: Add error handling and annotate components
2. **sequence-auth-journey.md**
- ❌ No Front-Stage/Back-Stage separation
- ❌ Missing user recovery options
- Action: Restructure with subgraphs, add recovery paths
### Medium Priority (Reduces clarity)
1. **arch-system-overview.md**
- ⚠️ Impact annotations too technical
- ⚠️ Related files missing
- Action: Rewrite annotations for user value, add file paths
2. **feature-search.md**
- ⚠️ Diagram too complex (should split)
- Action: Create separate detail diagrams
### Low Priority (Minor improvements)
1. **flow-payment-processing.md**
- ⚠️ Purpose could be more user-focused
- ⚠️ Key insights incomplete
- Action: Rewrite purpose, expand insights
## Recommendations
1. Schedule time to fix high-priority issues
2. Create template/checklist for future diagrams
3. Set up pre-commit validation
4. Train team on DDD principlesCoverage Audit Process
Step 1: Identify Features/Flows
# Find feature directories
find src/features -type d
# Find major user-facing components
find src/components -name "*Page.tsx" -o -name "*View.tsx"
# Find API routes
find src/api -name "*.ts" -o -name "routes.ts"
# Find critical services
find src/services -name "*.ts"Step 2: Check if Diagrams Exist
For each major feature/flow:
- Search for related diagram:
grep -r "feature-name" ai/diagrams/ - Check README.md index
- Verify diagram covers the flow
Step 3: Create Coverage Report
# Diagram Coverage Audit Report
**Date:** YYYY-MM-DD
## Features WITH Diagrams ✅
1. **User Authentication**
- sequence-authentication-journey.md
- feature-login-flow.md
2. **E-commerce Checkout**
- feature-checkout-payment-flow.md
- sequence-payment-processing.md
## Features WITHOUT Diagrams ❌
1. **Password Reset Flow**
- Priority: HIGH (security-critical)
- Files: `src/features/auth/PasswordReset.tsx`
- Action: Create sequence diagram
2. **Real-time Notifications**
- Priority: HIGH (complex user flow)
- Files: `src/services/websocket/notificationService.ts`
- Action: Create feature diagram
3. **Search Autocomplete**
- Priority: MEDIUM (performance-critical)
- Files: `src/features/search/SearchInput.tsx`
- Action: Create feature diagram
4. **User Profile Editing**
- Priority: LOW (straightforward CRUD)
- Files: `src/features/profile/ProfileEdit.tsx`
- Action: Consider if diagram needed
## Incomplete Coverage
1. **Checkout Flow** - Has payment diagram but missing cart/shipping
2. **Authentication** - Missing 2FA and OAuth flows
## Recommendations
1. Create diagrams for HIGH priority missing features
2. Complete incomplete coverage areas
3. Re-evaluate LOW priority features (diagram needed?)Synchronization Audit Process
Step 1: Find Recently Changed Files
# Files changed in last 30 days
git log --since="30 days ago" --name-only --pretty=format: | sort | uniq > /tmp/recent-changes.txt
# Or specific time range
git log --since="2025-01-01" --until="2025-01-31" --name-only --pretty=format: | sort | uniqStep 2: Find Diagrams Referencing Changed Files
# For each changed file, find related diagrams
while read file; do
echo "Checking: $file"
grep -l "$file" ai/diagrams/**/*.md
done < /tmp/recent-changes.txtStep 3: Compare Diagram Dates with Change Dates
For each diagram found:
- Read "Last Updated" date from diagram
- Compare with git log for related files
- If files changed after diagram update → OUTDATED
# Get last modified date of related files
git log -1 --format="%ai" -- path/to/file.ts
# Compare with diagram's "Last Updated" date
# If file date > diagram date, diagram is outdatedStep 4: Manual Review for Logic Changes
Not all code changes require diagram updates. Review:
- Are user flows affected?
- Did error handling change?
- Were new features added?
- Did performance characteristics change?
- Are impact annotations still accurate?
Step 5: Create Synchronization Report
# Diagram Synchronization Audit Report
**Date:** YYYY-MM-DD
## Synchronized Diagrams ✅
1. **feature-checkout-payment-flow.md**
- Last Updated: 2025-01-15
- Related files last changed: 2025-01-10
- Status: UP TO DATE
## Outdated Diagrams ⚠️
1. **feature-user-authentication.md**
- Last Updated: 2025-01-01
- Related files last changed: 2025-01-15 (2FA added)
- Impact: Missing 2FA flow
- Action: Add 2FA branch to diagram
2. **sequence-search-journey.md**
- Last Updated: 2024-12-20
- Related files last changed: 2025-01-10 (caching added)
- Impact: Performance annotations inaccurate
- Action: Update with cache layer and new metrics
3. **arch-system-overview.md**
- Last Updated: 2024-11-15
- Related files last changed: 2025-01-05 (microservice split)
- Impact: Architecture no longer matches
- Action: Complete redraw showing microservices
## Suspected Outdated (Needs Manual Review) 🔍
1. **feature-notification-system.md**
- Last Updated: 2025-01-05
- Related files changed: 2025-01-12 (minor refactor)
- Action: Review code changes, update if user-impacting
## Recommendations
1. Update HIGH impact outdated diagrams immediately
2. Review suspected outdated diagrams
3. Set up automated checks (pre-commit hook?)
4. Establish update policy (within 1 week of code change)Organization Audit Process
Step 1: Check Directory Structure
# Verify expected directories exist
ls -la ai/diagrams/
# Expected:
# - features/
# - architecture/
# - journeys/
# - tests/
# - refactoring/
# - README.mdStep 2: Check File Naming
# Find files not following naming convention
find ai/diagrams -name "*.md" -not -name "README.md" | while read file; do
basename "$file" | grep -vE '^(feature|sequence|arch|flow|test)-[a-z0-9-]+\.md$' && echo "Bad name: $file"
done
# Find files in wrong directories
find ai/diagrams/features -name "*.md" | while read file; do
basename "$file" | grep -vE '^feature-' && echo "Wrong directory: $file"
doneStep 3: Check Index Completeness
Compare diagrams on filesystem with README.md index:
# List all diagrams
find ai/diagrams -name "*.md" -not -name "README.md" | sort > /tmp/all-diagrams.txt
# Extract diagrams from README
grep -oP '\[.*?\]\(\K[^)]+' ai/diagrams/README.md | sort > /tmp/indexed-diagrams.txt
# Find diagrams not in index
comm -23 /tmp/all-diagrams.txt /tmp/indexed-diagrams.txtStep 4: Create Organization Report
# Diagram Organization Audit Report
**Date:** YYYY-MM-DD
## Directory Structure
- ✅ All expected directories exist
- ⚠️ Found unexpected directory: `ai/diagrams/old/`
- Action: Review and move or delete
## File Naming Issues
1. ❌ `ai/diagrams/features/checkout.md`
- Issue: Missing type prefix
- Should be: `feature-checkout-flow.md`
2. ❌ `ai/diagrams/journeys/UserAuthenticationFlow.md`
- Issue: Wrong case
- Should be: `sequence-user-authentication-journey.md`
3. ❌ `ai/diagrams/arch-microservices.md`
- Issue: Not in correct directory
- Should be: `ai/diagrams/architecture/arch-microservices.md`
## Index Completeness
### Missing from Index
1. `features/feature-notification-system.md`
2. `refactoring/feature-add-caching-layer.md`
### Broken Links in Index
1. `[User Auth](journeys/auth-flow.md)` → File doesn't exist
## Recommendations
1. Rename files to follow convention
2. Move misplaced files to correct directories
3. Update README.md index
4. Delete obsolete directories
5. Fix broken linksAutomated Audit Script
#!/bin/bash
# audit-diagrams.sh
echo "=== DIAGRAM AUDIT ==="
echo ""
# Quality Check
echo "## Quality Checks"
echo ""
echo "Checking for diagrams missing key sections..."
for file in ai/diagrams/**/*.md; do
if [ "$file" = "ai/diagrams/README.md" ]; then continue; fi
echo "Checking: $file"
# Check for required sections
grep -q "^## Purpose" "$file" || echo " ❌ Missing Purpose section"
grep -q "^## Diagram" "$file" || echo " ❌ Missing Diagram section"
grep -q "^## Key Insights" "$file" || echo " ❌ Missing Key Insights"
grep -q "^## Change History" "$file" || echo " ❌ Missing Change History"
# Check for Front-Stage/Back-Stage
grep -q "Front-Stage" "$file" || echo " ⚠️ No Front-Stage mention"
grep -q "Back-Stage" "$file" || echo " ⚠️ No Back-Stage mention"
# Check for impact annotations
grep -q "[⚡💾🛡️✅⏱️🔄📊🎯]" "$file" || echo " ⚠️ No impact annotation symbols found"
echo ""
done
# Coverage Check
echo "## Coverage Check"
echo ""
echo "Features/Services:"
find src/features -type d -depth 1 | while read dir; do
feature=$(basename "$dir")
if ! grep -q "$feature" ai/diagrams/**/*.md; then
echo " ❌ No diagram for: $feature"
fi
done
# Sync Check
echo "## Synchronization Check"
echo ""
echo "Diagrams with outdated timestamps:"
find ai/diagrams -name "*.md" -not -name "README.md" | while read file; do
# Extract last updated date
date=$(grep -oP '^\*\*Last Updated:\*\* \K[0-9-]+' "$file")
if [ -z "$date" ]; then
echo " ❌ $file: No last updated date"
continue
fi
# Check if older than 90 days
date_seconds=$(date -d "$date" +%s)
now_seconds=$(date +%s)
age_days=$(( ($now_seconds - $date_seconds) / 86400 ))
if [ $age_days -gt 90 ]; then
echo " ⚠️ $file: $age_days days old"
fi
done
echo ""
echo "=== AUDIT COMPLETE ==="Best Practices
1. Schedule regular audits - Monthly for active projects 2. Automate what you can - Use scripts to catch obvious issues 3. Prioritize fixes - Focus on high-impact diagrams first 4. Track improvements - Measure quality over time 5. Make it a habit - Include audits in sprint reviews 6. Document findings - Create actionable reports 7. Set standards - Define acceptable quality thresholds 8. Continuous improvement - Learn from audit findings
Audit Frequency
Weekly
- Quick sync check (are recent code changes reflected?)
- Index completeness check
Monthly
- Full quality audit
- Coverage audit for new features
- Organization audit
Quarterly
- Comprehensive audit of all diagrams
- Review and update DDD standards
- Analyze audit trend data
Metrics to Track
Track these over time:
- Total number of diagrams
- Percentage meeting DDD criteria
- Average diagram age
- Feature coverage percentage
- Time from code change to diagram update
- Number of broken links
- Number of naming violations
Example metrics dashboard:
# Diagram Health Metrics
**Period:** Q1 2025
| Metric | Value | Trend |
|--------|-------|-------|
| Total Diagrams | 42 | +8 ↗️ |
| DDD Compliant | 85% | +5% ↗️ |
| Avg Age (days) | 30 | -10 ↗️ |
| Feature Coverage | 78% | +12% ↗️ |
| Outdated | 3 | -2 ↗️ |
| Broken Links | 0 | -1 ↗️ |
**Overall Health:** 🟢 GOODNext Steps After Audit
1. Create action items from findings 2. Prioritize high-impact fixes 3. Assign ownership for updates 4. Set deadlines for critical fixes 5. Track progress on improvements 6. Schedule next audit to verify fixes 7. Update processes to prevent issues
Creating Diagrams
Comprehensive guide for creating new diagrams following DDD principles.
Before You Start
REQUIRED: Read DDD_PRINCIPLES.md before creating any diagram. Understanding DDD methodology is essential.
Creation Process
1. Understand the User Need
Before writing any Mermaid code, answer these questions:
- What user problem does this solve?
- What value does it deliver to users?
- What user actions trigger this flow?
- What user outcomes result from this flow?
2. Choose the Right Diagram Type
Feature Diagrams (feature-*.md)
- Use for: Specific features or user workflows
- Shows: How a feature delivers user value
- Format: Flowchart with Front-Stage/Back-Stage subgraphs
Sequence Diagrams (sequence-*.md)
- Use for: Time-based user journeys
- Shows: Step-by-step interaction over time
- Format: Sequence diagram with user as primary actor
Architecture Diagrams (arch-*.md)
- Use for: System-level organization
- Shows: Major components and their relationships
- Format: High-level flowchart with impact annotations
Flow Diagrams (flow-*.md)
- Use for: Process flows and decision trees
- Shows: Branching logic and outcomes
- Format: Flowchart with decision nodes
Test Coverage Diagrams (test-*.md)
- Use for: Documenting test strategy
- Shows: What user scenarios are protected by tests
- Format: Flowchart connecting tests to user value
Refactoring Diagrams (in refactoring/)
- Use for: Before/After comparisons
- Shows: Improvements to user experience
- Format: Side-by-side diagrams with changes in #90EE90
3. Determine the Directory
ai/diagrams/
├── features/ # Feature-specific user flows
├── architecture/ # System-level diagrams
├── journeys/ # User journey sequences
├── tests/ # Test coverage and strategy
└── refactoring/ # Before/After improvements4. Create the File Structure
Use this template for all diagrams:
# [Clear, User-Focused Title]
**Type:** [Feature Diagram | Sequence Diagram | Architecture Diagram | Flow Diagram | Test Coverage]
**Last Updated:** [YYYY-MM-DD]
**Related Files:**
- `path/to/implementation.ts`
- `path/to/component.tsx`
- `path/to/test.spec.ts`
## Purpose
[1-2 sentences describing what user value this diagram illustrates. Focus on user benefit, not technical implementation.]
## Diagram
\`\`\`mermaid
[Mermaid code here - see patterns below]
\`\`\`
## Key Insights
- **User Impact 1:** [How this affects user experience]
- **User Impact 2:** [What value this delivers]
- **Technical Enabler:** [What makes the above possible]
## Change History
- **YYYY-MM-DD:** Initial creation5. Write the Mermaid Code
Follow these patterns based on diagram type:
Diagram Patterns
Feature Diagram Pattern
graph TD
subgraph "Front-Stage (User Experience)"
User[User Action] --> UI[UI Response ⚡ Impact]
UI --> Feedback[User Feedback ✅ Impact]
end
subgraph "Back-Stage (Implementation)"
UI --> Service[Service Layer 🛡️ Impact]
Service --> DB[(Database 💾 Impact)]
Service --> Cache[Cache Layer ⚡ Impact]
end
DB --> Success[Success State]
Service -->|Error| ErrorHandler[Error Handler 🔄 Impact]
ErrorHandler --> Retry[User Can Retry]
Cache --> UI
Success --> FeedbackKey elements:
- User is entry point
- Front-Stage/Back-Stage separation
- Impact annotations on every Back-Stage component
- Error path with recovery
- User outcome is clear
Sequence Diagram Pattern
sequenceDiagram
actor User
participant UI as UI Component (Front-Stage)
participant API as API Service (Back-Stage)
participant DB as Database
User->>UI: User Action
Note over UI: UI updates ⚡ Instant feedback
UI->>API: API Request
Note over API: Validates input ✅ Prevents errors
API->>DB: Database Query
Note over DB: Persists data 💾 Guarantees save
DB-->>API: Response
API-->>UI: Data
UI-->>User: Success Message ⚡ Confirmation
alt Error Path
API-->>UI: Error Response
Note over UI: Shows error 🔄 User can fix
UI-->>User: Error Message with Action
endKey elements:
- User as actor
- Notes with impact annotations
- Request/response pairs
- Alt block for errors
- Clear resolution
Architecture Diagram Pattern
graph TB
subgraph "User Layer (Front-Stage)"
Browser[Web Browser]
Mobile[Mobile App]
end
subgraph "Application Layer (Back-Stage)"
API[API Gateway 🛡️ Secures requests]
Auth[Auth Service ✅ Validates users]
Features[Feature Services ⚡ Core functionality]
end
subgraph "Data Layer"
Primary[(Primary DB 💾 Source of truth)]
Cache[(Redis Cache ⚡ Fast reads)]
Queue[Job Queue ⏱️ Async processing]
end
Browser --> API
Mobile --> API
API --> Auth
API --> Features
Features --> Primary
Features --> Cache
Features --> Queue
Queue --> Primary
Cache --> FeaturesKey elements:
- Layered structure
- User touchpoints clear
- Impact annotations explain why each layer exists
- Data flow is evident
Flow Diagram Pattern
graph TD
Start[User Initiates Action] --> Validate{Input Valid?}
Validate -->|Yes| Process[Process Request ⚡ <100ms]
Validate -->|No| Error1[Show Validation Errors ✅]
Process --> Check{Auth OK?}
Check -->|Yes| Execute[Execute Action 💾 Saves data]
Check -->|No| Error2[Show Auth Error 🛡️]
Execute --> Success{Successful?}
Success -->|Yes| Confirm[Show Success ✅]
Success -->|No| Retry[Show Retry Option 🔄]
Error1 --> End1[User Can Correct]
Error2 --> End2[User Can Login]
Retry --> End3[User Can Retry]
Confirm --> End4[User Sees Confirmation]Key elements:
- Decision diamonds for branching
- Multiple end states
- Error paths with recovery
- Impact annotations on operations
Test Coverage Pattern
graph TD
subgraph "User Scenarios (What We Protect)"
S1[User Can Login Successfully]
S2[User Cannot Login with Bad Credentials]
S3[User Can Recover Password]
end
subgraph "Test Types (How We Protect)"
Unit[Unit Tests ⚡ Fast feedback]
Int[Integration Tests 💾 DB interactions]
E2E[E2E Tests ✅ Full user flow]
end
S1 --> E2E
S1 --> Int
S1 --> Unit
S2 --> E2E
S2 --> Unit
S3 --> E2E
S3 --> Int
Unit --> Coverage[85% Coverage 🎯]
Int --> Coverage
E2E --> Coverage
Coverage --> UserValue[Protected User Experience 🛡️]Key elements:
- User scenarios as primary focus
- Tests connected to scenarios
- Coverage metrics
- Clear value proposition
Refactoring (Before/After) Pattern
Before:
graph TD
User[User Action] --> API[API Call]
API --> Process[Process Data]
Process --> DB[(Database)]
DB --> Response[Response to User]
Note1[⏱️ Takes 2-3 seconds]After:
graph TD
User[User Action] --> API[API Call]
API --> Cache{Cache Check}
Cache -->|Hit| Fast[Cached Response ⚡ <50ms]
Cache -->|Miss| Process[Process Data]
Process --> DB[(Database)]
DB --> Store[Store in Cache 💾]
Store --> Response[Response to User]
Fast --> User
Response --> User
style Cache fill:#90EE90
style Fast fill:#90EE90
style Store fill:#90EE90
Note1[⚡ Now <100ms for cached requests]Key elements:
- Before shows current state
- After highlights improvements in #90EE90
- Impact annotations show user benefit
- Performance improvements quantified
Naming Files
Follow this pattern: {type}-{descriptive-name}.md
Good Names
feature-checkout-payment-flow.mdsequence-user-authentication-journey.mdarch-microservices-overview.mdflow-error-recovery-process.mdtest-payment-security-coverage.md
Bad Names
diagram1.md(not descriptive)payment.md(missing type)UserAuthenticationJourneySequenceDiagram.md(wrong case)feature_checkout.md(underscore instead of hyphen)
Impact Annotation Guide
Choosing the Right Symbol
⚡ Speed/Performance - Use when:
- Reducing latency
- Improving response time
- Optimizing load speed
- Caching for faster access
Examples:
API Call ⚡ Responds in <100msImage CDN ⚡ Loads 3x fasterCached Results ⚡ Instant search
💾 Storage/Persistence - Use when:
- Saving user data
- Guaranteeing data persistence
- Database operations
- State management
Examples:
Save to Database 💾 Preserves user workSession Storage 💾 Maintains loginAuto-save 💾 Never lose progress
🛡️ Security/Safety - Use when:
- Authentication/authorization
- Data validation
- Encryption
- Preventing vulnerabilities
Examples:
Auth Check 🛡️ Protects user dataInput Validation 🛡️ Prevents XSSHTTPS Only 🛡️ Encrypted connection
✅ Validation/Correctness - Use when:
- Input validation
- Data verification
- Ensuring accuracy
- Preventing invalid states
Examples:
Validate Form ✅ Prevents errorsCheck Inventory ✅ Accurate stockVerify Email ✅ Valid address
⏱️ Responsiveness/UX - Use when:
- Keeping UI responsive
- Async operations
- Non-blocking operations
- Smooth interactions
Examples:
Async Upload ⏱️ UI stays responsiveBackground Sync ⏱️ No blockingDebounce Input ⏱️ Smooth typing
🔄 Reliability/Recovery - Use when:
- Error recovery
- Retry logic
- Fallback behavior
- Graceful degradation
Examples:
Retry Logic 🔄 Handles failuresFallback Content 🔄 Always shows somethingError Boundary 🔄 Prevents crashes
📊 Data Accuracy - Use when:
- Ensuring data quality
- Maintaining consistency
- Preventing data corruption
- Accurate reporting
Examples:
Transaction 📊 Guarantees consistencyValidation 📊 Clean dataReconciliation 📊 Accurate totals
🎯 Feature Enablement - Use when:
- Enabling functionality
- Making features possible
- Core capabilities
Examples:
WebSockets 🎯 Enables real-time chatSearch Index 🎯 Powers instant searchPayment Gateway 🎯 Accepts payments
Validation Checklist
Before saving, verify:
Structure
- [ ] File is in correct directory (features/, architecture/, etc.)
- [ ] File name follows
{type}-{name}.mdpattern - [ ] All template sections are present
- [ ] Related files are documented
DDD Compliance
- [ ] Both Front-Stage and Back-Stage are shown
- [ ] User is the entry point
- [ ] Impact annotations on all Back-Stage components
- [ ] Error paths are included
- [ ] Recovery options are shown
Content Quality
- [ ] Purpose explains user value (not technical details)
- [ ] Key insights focus on user impact
- [ ] Mermaid syntax is valid
- [ ] No custom colors (except #90EE90 for Before/After)
- [ ] Last updated date is current
User-Centricity
- [ ] Starts with user action
- [ ] Ends with user outcome
- [ ] Every technical component connects to user value
- [ ] Error scenarios include user perspective
Update the Index
After creating a diagram, add it to ai/diagrams/README.md:
## [Category]
- [Diagram Title](category/filename.md) - Brief description focusing on user valueCommon Mistakes to Avoid
❌ Missing User Context
Don't create purely technical diagrams. Every diagram must show user value.
❌ No Impact Annotations
Don't assume user value is obvious. Make it explicit with annotations.
❌ Only Happy Path
Don't ignore errors. Show what happens when things go wrong.
❌ Wrong Directory
Don't put all diagrams in root. Use subdirectories for organization.
❌ Poor File Names
Don't use generic names like "diagram1.md". Be descriptive.
❌ Outdated Metadata
Don't forget to fill in "Related Files" and "Last Updated" fields.
❌ Technical Jargon in Purpose
Don't write: "REST API with JWT authentication" Do write: "Secure login that protects user accounts"
Examples
Example 1: E-commerce Checkout Feature
File: features/feature-checkout-payment-flow.md
# E-commerce Checkout Payment Flow
**Type:** Feature Diagram
**Last Updated:** 2025-01-15
**Related Files:**
- `src/features/checkout/CheckoutPage.tsx`
- `src/services/payment/paymentService.ts`
- `src/services/order/orderService.ts`
## Purpose
Enables users to securely complete purchases with real-time feedback and error recovery options, ensuring they never lose their cart data.
## Diagram
\`\`\`mermaid
graph TD
subgraph "Front-Stage (User Experience)"
User[User Clicks 'Pay Now'] --> Loading[Loading Spinner ⏱️ Shows progress]
Loading --> Success[Order Confirmation ✅]
end
subgraph "Back-Stage (Implementation)"
Loading --> Validate[Validate Cart ✅ Prevents invalid orders]
Validate --> Payment[Payment Gateway 🛡️ Secure transaction]
Payment --> Order[Create Order 💾 Guarantees delivery]
Order --> Email[Send Receipt ⚡ Immediate confirmation]
end
Payment -->|Success| Order
Payment -->|Failed| ErrorHandler[Payment Error Handler 🔄]
ErrorHandler --> RetryUI[Show Retry Options]
RetryUI --> User
Order --> Success
Email --> Success
\`\`\`
## Key Insights
- **Secure Payment**: PCI-compliant payment gateway protects user financial data
- **Never Lose Orders**: Order creation guaranteed even if email fails
- **Error Recovery**: Clear retry options if payment fails, cart is preserved
- **Instant Feedback**: Loading spinner and immediate receipt reduce anxiety
## Change History
- **2025-01-15:** Initial creationExample 2: Real-time Notification System
File: features/feature-notification-system.md
# Real-time Notification System
**Type:** Feature Diagram
**Last Updated:** 2025-01-15
**Related Files:**
- `src/components/NotificationBell.tsx`
- `src/services/websocket/notificationService.ts`
- `src/hooks/useNotifications.ts`
## Purpose
Keeps users instantly informed of important events without requiring page refreshes, improving engagement and ensuring they never miss critical updates.
## Diagram
\`\`\`mermaid
sequenceDiagram
actor User
participant UI as Notification Bell
participant WS as WebSocket Service
participant Server as Notification Server
participant DB as Database
User->>UI: Opens Application
Note over UI: Shows unread count ⚡ Instant visibility
UI->>WS: Connect WebSocket
Note over WS: Establishes connection 🎯 Enables real-time
WS->>Server: Subscribe to Notifications
Server->>DB: Fetch Unread Count
DB-->>Server: Count
Server-->>WS: Initial State
WS-->>UI: Update Badge ⚡
UI-->>User: Shows Unread Count
loop Real-time Updates
Server->>WS: New Notification Event
Note over Server: Pushed instantly ⚡ <100ms delivery
WS->>UI: Update Notification List
UI->>UI: Show Toast 📣 Alerts user
UI-->>User: New Notification Visible
end
alt Connection Drops
WS-->>UI: Connection Lost
Note over UI: Shows offline indicator 🔄
WS->>WS: Auto-reconnect ⏱️
WS->>Server: Reconnect & Sync
Server->>DB: Get Missed Notifications
DB-->>Server: Missed Events
Server-->>WS: Catch-up Data 💾
WS-->>UI: Restore State ✅
end
\`\`\`
## Key Insights
- **Instant Updates**: WebSocket enables <100ms notification delivery
- **Never Miss Anything**: Auto-reconnect and sync ensure reliability
- **Visual Feedback**: Badge count and toasts keep users informed
- **Offline Resilience**: Graceful handling when connection drops
## Change History
- **2025-01-15:** Initial creationNext Steps
After creating a diagram: 1. Validate against DDD checklist 2. Update README.md index 3. Commit with descriptive message 4. Reference in relevant documentation 5. Use in code reviews to explain changes
Diagram Driven Development (DDD) Principles
Core methodology for creating diagrams that connect user value to technical implementation.
Philosophy
Traditional diagrams show WHAT the code does. DDD diagrams show WHY it matters to users.
Every diagram must answer: 1. What user need does this address? 2. How does the technical implementation deliver that value? 3. What happens when things go wrong? 4. Where can we improve the user experience?
The Two Stages
Front-Stage (User Experience)
What users see, feel, and experience:
- User actions and decisions
- UI states and feedback
- Wait times and delays
- Error messages and recovery options
- Success confirmations
Back-Stage (Technical Implementation)
How we deliver the experience:
- Services and APIs
- Data processing
- Caching and optimization
- Error handling
- Integration points
CRITICAL: Every diagram MUST show BOTH stages and how they connect.
Impact Annotations
Every technical component must have an annotation explaining its user impact.
Good Impact Annotations
API Call [⚡ Loads in <100ms for instant search]
Caching Layer [💾 Reduces load time by 80%]
Error Handler [🛡️ Prevents data loss during failures]
Validation [✅ Prevents user frustration from invalid data]
Async Processing [⏱️ Keeps UI responsive during heavy operations]Bad Annotations (Too Technical)
API Call [REST endpoint using JWT]
Caching Layer [Redis with 1hr TTL]
Error Handler [Try/catch block with logging]
Validation [Zod schema validation]Annotation Symbols
- ⚡ Speed/Performance impact
- 💾 Storage/Caching benefit
- 🛡️ Security/Safety benefit
- ✅ Validation/Correctness
- ⏱️ Responsiveness/UX smoothness
- 🔄 Reliability/Recovery
- 📊 Data accuracy/integrity
- 🎯 Feature enablement
Error Path Requirements
Every diagram must show: 1. Happy path - When everything works 2. Error paths - What happens when things fail 3. Recovery options - How users can recover 4. Fallback behavior - Graceful degradation
Example: Login Flow
Good (shows error paths):
graph TD
User[User Enters Credentials] --> Validate[Validate Input ✅ Prevents errors]
Validate -->|Valid| Auth[Authenticate 🛡️ Secure login]
Validate -->|Invalid| Error1[Show Field Errors ⚡ Instant feedback]
Auth -->|Success| Dashboard[Redirect to Dashboard]
Auth -->|Failed| Error2[Show Login Error 🔄 Allow retry]
Error2 --> Retry[User Can Retry or Reset Password]Bad (missing error paths):
graph TD
User[User Enters Credentials] --> Auth[Authenticate]
Auth --> Dashboard[Redirect to Dashboard]Diagram Types and Standards
1. Feature Diagrams
Show how a feature delivers user value.
Required elements:
- User entry point
- User journey through feature
- Technical components with impact annotations
- Success and error outcomes
- Performance/UX improvements
Template:
graph TD
subgraph "Front-Stage (User Experience)"
User[User Action] --> UI[UI Feedback]
end
subgraph "Back-Stage (Implementation)"
UI --> Service[Service ⚡ Impact annotation]
Service --> DB[Database 💾 Impact annotation]
end
DB --> Success[Success State ✅]
Service -->|Error| Fallback[Error Recovery 🔄]2. Sequence Diagrams
Show user journeys over time.
Required elements:
- User as primary actor
- Time-based flow
- Request/response pairs
- Error scenarios
- Impact annotations on each interaction
Template:
sequenceDiagram
actor User
participant UI as UI (Front-Stage)
participant API as API (Back-Stage)
participant DB as Database
User->>UI: Action
Note over UI: Impact annotation
UI->>API: Request
Note over API: Impact annotation
API->>DB: Query
DB-->>API: Response
API-->>UI: Data
UI-->>User: Updated View ⚡
alt Error Path
API-->>UI: Error
UI-->>User: Error Message 🛡️
end3. Architecture Diagrams
Show system-level organization.
Required elements:
- Major system components
- Data flow between systems
- User touchpoints
- Performance/scalability notes
- Impact of architectural decisions
4. Test Coverage Diagrams
Show how tests protect user value.
Required elements:
- User scenarios being tested
- Test types (unit, integration, e2e)
- What user value each test protects
- Coverage gaps
5. Refactoring Diagrams (Before/After)
Show improvements to user experience.
Required elements:
- Before state
- After state
- Changes highlighted in
#90EE90 - User impact of changes
- Performance/UX improvements
Color Usage Rules
ALLOWED
- Default Mermaid colors only (no custom fills except below)
- #90EE90 (light green) for highlighting changes in Before/After diagrams
PROHIBITED
- Custom fill colors for "pretty" diagrams
- Color coding by type (all blues, all reds, etc.)
- Rainbow diagrams
- Theme-based coloring
Reasoning: Colors should convey meaning (changes), not decoration. Consistent default colors make diagrams professional and accessible.
Front-Stage/Back-Stage Separation
Use Subgraphs
graph TD
subgraph "Front-Stage (User Experience)"
User[User Action]
UI[UI Feedback ⚡ Instant updates]
Success[Success Message]
end
subgraph "Back-Stage (Implementation)"
API[API Service 🛡️ Validates data]
DB[Database 💾 Persists changes]
Cache[Cache Layer ⚡ Speeds up reads]
end
User --> UI
UI --> API
API --> DB
API --> Cache
Cache --> UI
UI --> SuccessClear Boundaries
- Front-Stage: What users interact with
- Back-Stage: What makes it work
- Connections: How they communicate
- Annotations: Why it matters
Quality Validation Checklist
Before saving any diagram, verify:
Structure
- [ ] Both Front-Stage and Back-Stage are present
- [ ] Subgraphs separate the two stages clearly
- [ ] User is the primary actor/entry point
- [ ] Error paths are shown
- [ ] Recovery options are documented
Annotations
- [ ] Every Back-Stage component has impact annotation
- [ ] Annotations focus on user benefit, not technical detail
- [ ] Appropriate symbols are used (⚡💾🛡️✅⏱️🔄📊🎯)
- [ ] Performance impacts are quantified where possible
Content
- [ ] Related files are documented
- [ ] Purpose explains user value
- [ ] Key insights list user impacts
- [ ] Change history tracks updates
- [ ] Last updated date is current
Technical
- [ ] Mermaid syntax is valid
- [ ] No custom colors (except #90EE90 for changes)
- [ ] Diagram renders correctly
- [ ] Node labels are clear and concise
User-Centricity
- [ ] Diagram starts and ends with user
- [ ] User value is explicit, not implied
- [ ] Error scenarios include user recovery
- [ ] Performance impacts relate to user experience
Common Anti-Patterns
❌ Purely Technical Diagrams
graph TD
Controller --> Service
Service --> Repository
Repository --> DatabaseProblem: No user context, no impact annotations, no value explanation.
✅ DDD-Compliant Diagram
graph TD
subgraph "Front-Stage"
User[User Saves Settings] --> UI[Settings Page ⚡ Instant save feedback]
end
subgraph "Back-Stage"
UI --> Controller[Settings Controller 🛡️ Validates input]
Controller --> Service[Settings Service 💾 Persists to DB]
Service --> DB[(Database)]
end
DB --> Success[Settings Saved ✅]
Controller -->|Invalid| Error[Error Message 🔄 User can correct]❌ Missing Error Paths
Shows only happy path, ignoring what happens when things fail.
❌ No Impact Annotations
Technical components without explanation of user benefit.
❌ Hidden User Context
User is implied but not shown in diagram.
❌ Custom Colors Everywhere
Rainbow diagrams that distract from content.
Real-World Examples
E-commerce Checkout (Good)
sequenceDiagram
actor User
participant Cart as Shopping Cart
participant Payment as Payment Service
participant Order as Order System
participant Email as Email Notification
User->>Cart: Click "Checkout"
Note over Cart: Validates cart ✅ Prevents empty orders
Cart->>Payment: Process Payment
Note over Payment: Secure transaction 🛡️ PCI compliant
alt Payment Success
Payment-->>Order: Confirm Payment
Note over Order: Creates order 💾 Guarantees delivery
Order-->>Email: Send Confirmation
Note over Email: Immediate receipt ⚡ Peace of mind
Email-->>User: Order Confirmed ✅
else Payment Failed
Payment-->>Cart: Payment Error
Cart-->>User: Show Error & Retry Option 🔄
endWhy this is good:
- Shows user as primary actor
- Front-Stage/Back-Stage implicit but clear
- Impact annotations on every step
- Error path with recovery
- User outcome is clear
Search Feature (Good)
graph TD
subgraph "Front-Stage (User Experience)"
User[User Types Query] --> UI[Search Input ⚡ Live suggestions]
UI --> Results[Results Page]
Results --> Click[User Clicks Result]
end
subgraph "Back-Stage (Implementation)"
UI --> Debounce[Debounce ⏱️ Reduces API calls]
Debounce --> Cache[Check Cache 💾 Instant for common searches]
Cache -->|Cache Hit| UI
Cache -->|Cache Miss| API[Search API 📊 Full-text search]
API --> Rank[Ranking Algorithm 🎯 Most relevant first]
Rank --> Cache
Rank --> Results
end
API -->|Error| Fallback[Show Cached Results 🔄 Never blank page]Why this is good:
- Clear Front-Stage/Back-Stage separation
- Every technical component has impact annotation
- Error path shows graceful fallback
- User starts and ends the flow
- Performance optimizations are explained
Implementation Guidelines
When Creating Diagrams
1. Start with user need
- What problem does this solve?
- What value does it deliver?
2. Map the user journey
- Entry point
- Actions and decisions
- Success outcome
- Error scenarios
3. Add technical components
- How do we deliver the experience?
- What makes it fast/secure/reliable?
4. Add impact annotations
- Why does each component matter?
- What user benefit does it provide?
5. Show error paths
- What can go wrong?
- How do users recover?
6. Validate quality
- Run through DDD checklist
- Ensure Front-Stage/Back-Stage balance
- Verify all annotations explain user value
When Updating Diagrams
1. Identify what changed in code 2. Determine user impact of changes 3. Update diagram to reflect new flow 4. Update impact annotations 5. Add change history entry 6. Update "Last Updated" date 7. Re-validate against DDD checklist
When Auditing Diagrams
1. Check structural quality
- Front-Stage/Back-Stage present?
- Error paths shown?
- User-centric?
2. Check annotation quality
- Do they explain user value?
- Are they specific enough?
- Do they use appropriate symbols?
3. Check synchronization
- Does diagram match current code?
- Is "Last Updated" recent?
- Are related files still correct?
4. Check completeness
- Are there features without diagrams?
- Are there outdated diagrams?
- Are there purely technical diagrams that need upgrading?
DDD in Practice
Before DDD
Developer creates diagram showing technical architecture with boxes and arrows. Diagram shows service layers, databases, APIs, but no mention of what user problem it solves.
After DDD
Developer creates diagram showing:
- User trying to complete a task
- How the UI responds to their actions
- What technical systems enable that response
- Why each system matters to the user experience
- What happens when things go wrong
- How users can recover from errors
Result: Non-technical stakeholders can understand the diagram. Developers understand the "why" behind technical decisions. Everyone sees how code changes impact users.
Conclusion
DDD diagrams are not just documentation—they are a tool for thinking about systems from a user-first perspective. Every technical decision should trace back to user value, and diagrams make that connection explicit and visible.
Remember: If you can't explain the user value of a technical component, reconsider whether it belongs in the system.
Mermaid Syntax Guide for DDD Diagrams
Quick reference for creating effective diagrams with Mermaid. Focus on patterns used in DDD diagrams.
Essential Mermaid Patterns
Flowchart (Most Common for DDD)
graph TD
A[Node] --> B[Another Node]
B --> C{Decision}
C -->|Yes| D[Outcome 1]
C -->|No| E[Outcome 2]Direction:
graph TD- Top to Downgraph LR- Left to Rightgraph BT- Bottom to Topgraph RL- Right to Left
Node Shapes:
graph LR
A[Rectangle - Process/Action]
B(Rounded - Start/End/State)
C{Diamond - Decision}
D[(Database)]
E[[Subroutine]]
F([Stadium - Alternative Process])Sequence Diagrams (For Journeys)
sequenceDiagram
actor User
participant UI
participant API
participant DB
User->>UI: Action
Note over UI: Processing
UI->>API: Request
API->>DB: Query
DB-->>API: Response
API-->>UI: Data
UI-->>User: Result
alt Error Path
API-->>UI: Error
UI-->>User: Error Message
endKey Elements:
actor- User (human)participant- Systems/components->Solid line (sync)-->Dotted line (async/return)->>Solid arrow (message)-->>Dotted arrow (return)Note over- Annotationsalt/else/end- Alternatives
DDD-Specific Patterns
Front-Stage/Back-Stage with Subgraphs
graph TD
subgraph "Front-Stage (User Experience)"
direction TB
User[User Action]
UI[UI Feedback ⚡ Impact]
Success[Success State ✅]
end
subgraph "Back-Stage (Implementation)"
direction TB
Service[Service Layer 🛡️ Impact]
DB[(Database 💾 Impact)]
Cache[Cache ⚡ Impact]
end
User --> UI
UI --> Service
Service --> DB
Service --> Cache
Cache --> UI
UI --> SuccessSubgraph Tips:
- Always label as "Front-Stage" and "Back-Stage"
- Use
direction TBinside subgraphs for vertical layout - Place user-facing components in Front-Stage
- Place technical components in Back-Stage
Impact Annotations in Nodes
graph TD
API[API Call ⚡ Responds in <100ms]
DB[(Database 💾 Persists user data)]
Cache[Cache Layer ⚡ 3x faster]
Auth[Auth Service 🛡️ Secures requests]
Validate[Input Validation ✅ Prevents errors]Annotation Format: Component Name [Symbol] Impact description
Error Paths
graph TD
Start[User Action] --> Validate{Valid Input?}
Validate -->|Yes| Process[Process Request]
Validate -->|No| Error1[Show Error 🔄 User can correct]
Process --> Check{Success?}
Check -->|Yes| Success[Complete]
Check -->|No| Error2[Error Handler 🔄]
Error2 --> Retry[Retry Option]Error Path Tips:
- Always include error branches
- Show recovery options
- Use 🔄 symbol for recovery/retry
- Make error paths obvious (not hidden)
Styling
Highlighting Changes (Before/After Only)
graph TD
A[Old Component]
B[New Component]
C[Modified Component]
style B fill:#90EE90
style C fill:#90EE90CRITICAL: Only use #90EE90 (light green) for Before/After diagrams showing changes. No other custom colors.
Node Styling (Avoid)
# ❌ DON'T DO THIS (custom colors)
graph TD
A[Component]
style A fill:#ff0000,stroke:#333,stroke-width:4pxUse default Mermaid styles unless highlighting changes.
Advanced Patterns
Multiple End States
graph TD
Start[Begin] --> Process{Process}
Process -->|Path 1| End1[Success ✅]
Process -->|Path 2| End2[Partial Success ⚠️]
Process -->|Path 3| End3[Failure - Retry Available 🔄]
Process -->|Path 4| End4[Fatal Error ❌]Parallel Processing
graph TD
Start[User Action] --> Split[Split]
Split -->|Async 1| Task1[Task 1 ⏱️]
Split -->|Async 2| Task2[Task 2 ⏱️]
Split -->|Async 3| Task3[Task 3 ⏱️]
Task1 --> Join[Join Results]
Task2 --> Join
Task3 --> Join
Join --> Complete[All Complete ✅]Nested Subgraphs
graph TD
subgraph "Application Layer"
direction LR
subgraph "Front-Stage"
UI[UI Components]
end
subgraph "Back-Stage"
API[API Layer]
Services[Business Logic]
end
end
subgraph "Data Layer"
DB[(Primary Database)]
Cache[(Cache)]
end
UI --> API
API --> Services
Services --> DB
Services --> CacheSequence Diagram Patterns
Simple Request/Response
sequenceDiagram
User->>API: Request
Note over API: Process ⚡ <100ms
API->>DB: Query
DB-->>API: Data
API-->>User: Response ✅With Authentication
sequenceDiagram
User->>UI: Login
UI->>Auth: Validate Credentials 🛡️
Auth->>DB: Check User
DB-->>Auth: User Data
alt Valid Credentials
Auth-->>UI: Token ✅
UI-->>User: Logged In
else Invalid Credentials
Auth-->>UI: Error 🔄
UI-->>User: Show Error & Retry
endMultiple Alternatives
sequenceDiagram
User->>System: Action
alt Scenario 1
System-->>User: Outcome 1
else Scenario 2
System-->>User: Outcome 2
else Scenario 3
System-->>User: Outcome 3
endLoops
sequenceDiagram
User->>System: Start Process
loop Until Complete
System->>System: Process Batch
System->>DB: Save Progress 💾
Note over System: Continue next batch
end
System-->>User: All Complete ✅Common Mistakes
❌ Too Complex
# Bad: Too many nodes, hard to follow
graph TD
A --> B --> C --> D --> E --> F --> G --> H --> I --> JSolution: Break into multiple diagrams or use subgraphs to organize.
❌ No Labels on Edges
# Bad: Unclear what each path means
Decision --> Option1
Decision --> Option2# Good: Clear edge labels
Decision -->|Valid| Option1
Decision -->|Invalid| Option2❌ Missing User Context
# Bad: No user in diagram
Service --> Database --> Cache# Good: User is visible
User --> Service --> Database --> Cache --> User❌ No Impact Annotations
# Bad: Just technical names
API --> Database --> Response# Good: Impact explained
API --> Database[(Database 💾 Stores order)]
Database --> Response[Response ⚡ <100ms]Testing Your Diagram
Online Editor
Use Mermaid Live Editor to:
- Validate syntax
- Preview rendering
- Test different layouts
- Export images
Common Syntax Errors
Missing Direction:
# ❌ Error
graph
A --> B
# ✅ Correct
graph TD
A --> BInvalid Characters in IDs:
# ❌ Error
graph TD
node-1 --> node-2
# ✅ Correct
graph TD
node1[Node 1] --> node2[Node 2]Unmatched Brackets:
# ❌ Error
graph TD
A[Node --> B
# ✅ Correct
graph TD
A[Node] --> BQuick Reference
Node Types
[Text] Rectangle
(Text) Rounded
{Text} Diamond
[(Text)] Database
[[Text]] Subroutine
([Text]) StadiumArrow Types
--> Dotted line
-> Solid line
->> Solid with arrow
-->> Dotted with arrow
---|Text|--> Labeled lineDirections
TD / TB Top to Down/Bottom
LR Left to Right
BT Bottom to Top
RL Right to LeftCommon Symbols
⚡ Speed/Performance
💾 Storage/Persistence
🛡️ Security/Safety
✅ Validation/Success
⏱️ Responsiveness
🔄 Recovery/Retry
📊 Data Accuracy
🎯 Feature EnableBest Practices
1. Keep it simple - If diagram is too complex, split it 2. Clear labels - Every node and edge should be clear 3. User-centric - User should be visible in diagram 4. Impact annotations - Explain user value, not just technical details 5. Error paths - Always show what happens when things fail 6. Test syntax - Use Mermaid Live Editor to validate 7. Consistent style - Use default styles, avoid custom colors 8. Front-Stage/Back-Stage - Always separate user experience from implementation 9. Direction matters - Choose TD or LR based on what's clearer 10. Validate rendering - Check that diagram actually renders correctly
Resources
Organizing Diagrams
Guide for maintaining clean directory structure and consistent naming conventions.
Directory Structure
ai/diagrams/
├── README.md # Index of all diagrams (REQUIRED)
├── features/ # Feature-specific user flows
│ ├── feature-checkout-payment-flow.md
│ ├── feature-notification-system.md
│ └── feature-search-functionality.md
├── architecture/ # System-level diagrams
│ ├── arch-system-overview.md
│ ├── arch-microservices-architecture.md
│ └── arch-data-flow.md
├── journeys/ # User journey sequences
│ ├── sequence-authentication-journey.md
│ ├── sequence-onboarding-flow.md
│ └── sequence-purchase-completion.md
├── tests/ # Test coverage and strategy
│ ├── test-payment-security-coverage.md
│ └── test-e2e-critical-paths.md
└── refactoring/ # Before/After improvements
├── feature-add-caching-layer.md
└── feature-optimize-database-queries.mdNaming Conventions
Format: {type}-{descriptive-name}.md
Type Prefixes:
feature-→ features/sequence-→ journeys/arch-→ architecture/flow-→ features/ or journeys/ (depending on context)test-→ tests/
Descriptive Name Rules:
- Lowercase only
- Use hyphens (not underscores or spaces)
- Be specific and clear
- 2-5 words is ideal
- Describe the user value or flow
Good Examples
✅ feature-checkout-payment-flow.md
✅ sequence-user-authentication-journey.md
✅ arch-microservices-overview.md
✅ test-payment-security-coverage.md
✅ feature-real-time-notifications.mdBad Examples
❌ checkout.md # Missing type prefix
❌ feature_checkout.md # Underscore instead of hyphen
❌ FeatureCheckout.md # Wrong case
❌ diagram1.md # Not descriptive
❌ feature-checkout-payment-flow-diagram.md # Redundant "diagram"
❌ sequence-user-auth.md # Too abbreviatedDirectory Selection Guide
features/
When to use:
- Specific user-facing features
- Feature workflows
- Component interactions within a feature
- User actions within a bounded context
Examples:
- Checkout flow
- Notification system
- Search functionality
- User profile editing
architecture/
When to use:
- System-level organization
- Multiple services/components interaction
- High-level overviews
- Infrastructure diagrams
- Technology stack diagrams
Examples:
- Microservices architecture
- System overview
- Data flow across services
- Deployment architecture
journeys/
When to use:
- Time-based user journeys
- Multi-step processes
- Cross-feature workflows
- User onboarding
- Complete user stories
Examples:
- Authentication journey (login → 2FA → redirect)
- Purchase journey (browse → cart → checkout → confirmation)
- Onboarding flow (signup → verification → setup)
tests/
When to use:
- Test coverage documentation
- Test strategy diagrams
- Connection between tests and user value
- Critical path testing
- Security/compliance testing
Examples:
- Payment security test coverage
- E2E critical paths
- Integration test strategy
refactoring/
When to use:
- Before/After comparisons
- Performance improvements
- Architecture changes
- Code quality improvements
- Technical debt reduction
Examples:
- Adding caching layer
- Optimizing database queries
- Migrating to microservices
- Improving error handling
README.md Index Structure
The index is the entry point for understanding. Keep it organized and current.
Template
# Unified Impact Diagrams Index
This directory contains all diagrams for the project, following Diagram Driven Development (DDD) methodology.
**Last Updated:** YYYY-MM-DD
## Quick Links
- [System Architecture](#architecture-overview)
- [User Journeys](#user-journeys)
- [Features](#features)
- [Test Coverage](#test-coverage)
## Architecture Overview
High-level system design and component relationships.
- [System Architecture](architecture/arch-system-overview.md) - Complete system with all major services and data flow
- [Microservices Architecture](architecture/arch-microservices-architecture.md) - Service boundaries and communication patterns
## User Journeys
Time-based user experiences across features.
- [User Authentication](journeys/sequence-authentication-journey.md) - Login, 2FA, and account recovery with security focus
- [Purchase Flow](journeys/sequence-purchase-completion.md) - Complete buying journey from browse to confirmation
- [Onboarding](journeys/sequence-onboarding-flow.md) - New user setup and first-time experience
## Features
Individual features and their user value.
- [Checkout & Payment](features/feature-checkout-payment-flow.md) - Secure payment processing with error recovery
- [Real-time Notifications](features/feature-notification-system.md) - WebSocket-based instant updates
- [Search](features/feature-search-functionality.md) - Fast search with autocomplete and caching
## Test Coverage
How we protect user value through testing.
- [Payment Security](tests/test-payment-security-coverage.md) - Comprehensive payment testing strategy
- [Critical E2E Paths](tests/test-e2e-critical-paths.md) - Essential user journeys covered by E2E tests
## Refactoring Plans
Improvements and their expected user impact.
- [Caching Layer](refactoring/feature-add-caching-layer.md) - Reduce load time from 2s to <100ms
- [Query Optimization](refactoring/feature-optimize-database-queries.md) - Improve dashboard performance by 5x
## Diagram Guidelines
All diagrams follow [Diagram Driven Development (DDD)](../commands/sync-diagrams.md) principles:
- Show both Front-Stage (user experience) and Back-Stage (implementation)
- Include impact annotations explaining user value
- Show error paths and recovery options
- Connect technical decisions to user benefit
## Contributing
When creating or updating diagrams:
1. Follow DDD principles (see guidelines above)
2. Use appropriate directory and naming convention
3. Update this index with new/modified diagrams
4. Add change history entry in diagram file
5. Update "Last Updated" in this README
## Recent Changes
- **2025-01-16:** Added caching layer refactoring diagram
- **2025-01-15:** Updated authentication journey with 2FA
- **2025-01-10:** Created real-time notification system diagramIndex Best Practices
1. Keep it current - Update whenever diagrams change 2. Provide context - Brief descriptions with user value 3. Use categories - Group related diagrams 4. Quick links - Make navigation easy 5. Document recent changes - Help team track updates
Reorganization Process
When structure needs changes:
1. Plan the Reorganization
## Reorganization Plan
**Goal:** Consolidate scattered diagrams into proper structure
**Changes:**
1. Move `diagram1.md` → `features/feature-checkout-flow.md`
2. Rename `auth.md` → `sequence-authentication-journey.md`
3. Create `architecture/` directory
4. Move system diagrams to `architecture/`
5. Update all links in README.md2. Execute Systematically
# Create missing directories
mkdir -p ai/diagrams/{features,architecture,journeys,tests,refactoring}
# Move and rename files
mv ai/diagrams/diagram1.md ai/diagrams/features/feature-checkout-flow.md
mv ai/diagrams/auth.md ai/diagrams/journeys/sequence-authentication-journey.md
# Update the diagram metadata (Related Files paths may change)
# Update README.md index3. Validate After Reorganization
- [ ] All diagrams in correct directories
- [ ] All file names follow convention
- [ ] README.md index is updated
- [ ] No broken links
- [ ] Git history is preserved (use
git mv)
Common Organization Issues
Issue 1: Diagrams in Root Directory
Problem:
ai/diagrams/
├── checkout.md
├── auth.md
├── system.md
└── README.mdSolution:
# Move to appropriate directories
mkdir -p ai/diagrams/{features,architecture,journeys}
mv ai/diagrams/checkout.md ai/diagrams/features/feature-checkout-flow.md
mv ai/diagrams/auth.md ai/diagrams/journeys/sequence-authentication-journey.md
mv ai/diagrams/system.md ai/diagrams/architecture/arch-system-overview.mdIssue 2: Inconsistent Naming
Problem:
features/
├── feature-checkout.md
├── checkout-flow.md
├── Checkout.md
└── feature_payment.mdSolution:
# Standardize names
mv feature-checkout.md feature-checkout-flow.md
mv checkout-flow.md feature-checkout-alternate.md # or merge
mv Checkout.md feature-checkout-main.md # or merge
mv feature_payment.md feature-payment-processing.mdIssue 3: Wrong Directory
Problem:
features/arch-system-overview.md # Architecture in features/
journeys/feature-search.md # Feature in journeys/Solution:
# Move to correct directories
mv features/arch-system-overview.md architecture/
mv journeys/feature-search.md features/Issue 4: Duplicate Diagrams
Problem:
features/
├── feature-checkout-flow.md
├── feature-checkout-payment.md
└── feature-payment-checkout.mdSolution: 1. Review all three diagrams 2. Determine if they cover different aspects or duplicate 3. If duplicate: Merge into single comprehensive diagram 4. If different: Clarify names to show distinction
feature-checkout-cart-management.mdfeature-checkout-payment-processing.mdfeature-checkout-order-confirmation.md
Maintenance Commands
List All Diagrams by Type
# Feature diagrams
find ai/diagrams/features -name "feature-*.md"
# Sequence diagrams
find ai/diagrams/journeys -name "sequence-*.md"
# Architecture diagrams
find ai/diagrams/architecture -name "arch-*.md"Find Misplaced Diagrams
# Architecture diagrams not in architecture/
find ai/diagrams -name "arch-*.md" -not -path "*/architecture/*"
# Feature diagrams not in features/
find ai/diagrams -name "feature-*.md" -not -path "*/features/*"
# Sequence diagrams not in journeys/
find ai/diagrams -name "sequence-*.md" -not -path "*/journeys/*"Validate File Names
# Find files not following convention
find ai/diagrams -name "*.md" -not -name "README.md" | while read file; do
basename "$file" | grep -vE '^(feature|sequence|arch|flow|test)-[a-z0-9-]+\.md$' && \
echo "Invalid name: $file"
doneCheck for Broken Links in Index
# Extract links from README
grep -oP '\]\(\K[^)]+' ai/diagrams/README.md | while read link; do
if [ ! -f "ai/diagrams/$link" ]; then
echo "Broken link: $link"
fi
doneMigration Checklist
When reorganizing existing diagrams:
- [ ] Back up current state (git commit)
- [ ] Create reorganization plan
- [ ] Create missing directories
- [ ] Move files with
git mv(preserves history) - [ ] Rename files following convention
- [ ] Update README.md index
- [ ] Update internal links in diagrams (if any)
- [ ] Validate no broken links
- [ ] Commit with descriptive message
- [ ] Inform team of changes
Best Practices
1. Use `git mv` - Preserves file history 2. One diagram type per directory - Don't mix feature and architecture 3. Consistent prefixes - Always use type prefix in filename 4. Descriptive names - Name should indicate content 5. Keep README current - Update index immediately after changes 6. Validate regularly - Run organization audits monthly 7. Document changes - Note reorganizations in README 8. Team communication - Inform team of structure changes 9. No orphans - Every diagram should be in index 10. Regular cleanup - Remove obsolete diagrams
Quick Reference
Directory Decision Tree
Is it showing system architecture?
├─ Yes → architecture/arch-{name}.md
└─ No → Is it a time-based journey?
├─ Yes → journeys/sequence-{name}.md
└─ No → Is it feature-specific?
├─ Yes → features/feature-{name}.md
└─ No → Is it about testing?
├─ Yes → tests/test-{name}.md
└─ No → Is it Before/After comparison?
├─ Yes → refactoring/feature-{name}.md
└─ No → Choose closest matchNaming Quick Check
1. All lowercase? ✓ 2. Has type prefix? ✓ 3. Uses hyphens? ✓ 4. Descriptive (2-5 words)? ✓ 5. Ends with .md? ✓
Index Update Template
## [Category]
- [Clear Title](directory/filename.md) - Brief user-value descriptionUpdating Diagrams
Guide for keeping diagrams synchronized with code changes.
When to Update
Update diagrams when:
- Code implementation changes
- User flows are modified
- New features are added to existing flows
- Performance improvements are made
- Error handling is added/changed
- Dependencies change
- Related files are renamed/moved
Update Process
1. Identify Affected Diagrams
Using git history:
# Find files changed recently
git log --since="1 week ago" --name-only --pretty=format: | sort | uniq
# Compare with diagrams to find outdated ones
find ai/diagrams -name "*.md" -exec grep -l "path/to/changed/file" {} \;Using diagram metadata:
- Check "Related Files" section in diagrams
- Compare file paths with changed files
- Look for outdated "Last Updated" dates
Manual review:
- List all diagrams:
ls -R ai/diagrams/ - Review each diagram's related files
- Identify diagrams that reference changed code
2. Understand the Changes
Before updating diagrams:
- Review code changes (git diff)
- Understand user impact of changes
- Identify new error paths or flows
- Note performance improvements
- Check for new dependencies
3. Update the Diagram
Update Mermaid Code
Adding new components:
# Old
User --> Service --> DB
# New (add caching layer)
User --> Service --> Cache
Cache -->|Hit| User
Cache -->|Miss| DB
DB --> CacheModifying flows:
# Old
Service --> DB --> Response
# New (add validation)
Service --> Validate[Validate ✅]
Validate -->|Valid| DB
Validate -->|Invalid| Error[Error Response 🔄]
DB --> ResponseAdding error paths:
# Old
API --> Process --> Success
# New (add error handling)
API --> Process
Process -->|Success| Success
Process -->|Error| ErrorHandler[Error Handler 🔄]
ErrorHandler --> Retry[User Can Retry]Update Impact Annotations
When implementation changes affect user experience:
Before:
API Call --> DatabaseAfter (added caching):
API Call --> Cache[Cache Layer ⚡ Reduces load time to <50ms]
Cache -->|Miss| DatabaseUpdate Related Files
Keep the "Related Files" section current:
Before:
**Related Files:**
- `src/services/userService.ts`
- `src/components/UserProfile.tsx`After (files renamed):
**Related Files:**
- `src/services/user/userService.ts`
- `src/features/profile/UserProfilePage.tsx`
- `src/hooks/useUserData.ts` (new)4. Update Metadata
Last Updated Date
**Last Updated:** 2025-01-16Change History
## Change History
- **2025-01-16:** Added caching layer for improved performance (2s → 50ms)
- **2025-01-10:** Added error recovery options for failed authentication
- **2025-01-05:** Initial creation5. Update Key Insights
If changes affect user value, update insights:
Before:
## Key Insights
- Secure authentication protects user accounts
- Immediate feedback on login success/failureAfter (added remember me):
## Key Insights
- Secure authentication protects user accounts
- Immediate feedback on login success/failure
- **Remember me option saves time on return visits**
- Auto-logout after 30 days balances convenience and security6. Validate Quality
Run through DDD checklist:
- [ ] Still shows Front-Stage and Back-Stage
- [ ] New components have impact annotations
- [ ] Error paths are current
- [ ] User actions reflect new flows
- [ ] Related files are accurate
- [ ] Last updated date is current
- [ ] Change history explains what changed
Update Patterns
Pattern 1: Adding Performance Optimization
Scenario: Added Redis caching to reduce database load
Before:
graph TD
User[User Searches] --> API[Search API]
API --> DB[(Database)]
DB --> Results[Search Results]
Results --> UserAfter:
graph TD
User[User Searches] --> API[Search API]
API --> Cache{Cache Check}
Cache -->|Hit| Fast[Cached Results ⚡ <50ms]
Cache -->|Miss| DB[(Database)]
DB --> Store[Store in Cache 💾]
Store --> Results[Search Results]
Fast --> User
Results --> User
Note[Note: 80% cache hit rate reduces load time from 2s to 50ms]Update checklist:
- ✅ Added cache layer with impact annotation
- ✅ Showed cache hit/miss paths
- ✅ Quantified performance improvement
- ✅ Updated related files to include cache service
- ✅ Added change history entry
- ✅ Updated last updated date
Pattern 2: Adding Error Handling
Scenario: Added retry logic for failed API calls
Before:
sequenceDiagram
User->>API: Submit Form
API->>DB: Save Data
DB-->>API: Success
API-->>User: ConfirmationAfter:
sequenceDiagram
User->>API: Submit Form
API->>DB: Save Data
alt Success Path
DB-->>API: Success
API-->>User: Confirmation ✅
else Failure Path
DB-->>API: Error
API->>API: Retry Logic 🔄 3 attempts
alt Retry Succeeds
API->>DB: Retry
DB-->>API: Success
API-->>User: Confirmation (Delayed) ✅
else All Retries Fail
API-->>User: Error Message with Save Draft 💾
Note over User: User can save locally and retry later
end
endUpdate checklist:
- ✅ Added error path with retry logic
- ✅ Showed recovery options (save draft)
- ✅ Added impact annotations for resilience
- ✅ Updated key insights about reliability
- ✅ Updated related files (error handler)
Pattern 3: Refactoring Flow
Scenario: Split monolithic service into microservices
Before:
graph TD
User[User Action] --> Monolith[Monolithic Service]
Monolith --> DB1[(Users DB)]
Monolith --> DB2[(Orders DB)]
Monolith --> DB3[(Inventory DB)]
DB1 --> Response
DB2 --> Response
DB3 --> Response
Response --> UserAfter:
graph TD
User[User Action] --> Gateway[API Gateway 🛡️ Routes requests]
Gateway --> UserService[User Service ⚡ Independent scaling]
Gateway --> OrderService[Order Service 💾 Owns order data]
Gateway --> InventoryService[Inventory Service 📊 Real-time stock]
UserService --> DB1[(Users DB)]
OrderService --> DB2[(Orders DB)]
InventoryService --> DB3[(Inventory DB)]
DB1 --> Gateway
DB2 --> Gateway
DB3 --> Gateway
Gateway --> Response[Aggregated Response ⚡ <200ms]
Response --> User
Note[Note: Microservices enable independent deployment and scaling]Update checklist:
- ✅ Restructured diagram for new architecture
- ✅ Added gateway with routing annotation
- ✅ Separated services with clear responsibilities
- ✅ Added impact annotations (scaling, independence)
- ✅ Updated all related files (now 3 services)
- ✅ Updated key insights about scalability
Pattern 4: Adding New Feature to Existing Flow
Scenario: Added two-factor authentication to login
Before:
graph TD
User[Enter Credentials] --> Validate[Validate]
Validate -->|Valid| Auth[Authenticate 🛡️]
Validate -->|Invalid| Error1[Show Error]
Auth -->|Success| Dashboard
Auth -->|Failed| Error2[Login Failed]After:
graph TD
User[Enter Credentials] --> Validate[Validate ✅]
Validate -->|Valid| Auth[Check Password 🛡️]
Validate -->|Invalid| Error1[Show Error 🔄]
Auth -->|Valid| TwoFactor{2FA Enabled?}
Auth -->|Invalid| Error2[Login Failed 🔄]
TwoFactor -->|Yes| SendCode[Send 2FA Code 🛡️ Extra security]
TwoFactor -->|No| Dashboard
SendCode --> EnterCode[User Enters Code]
EnterCode --> VerifyCode[Verify Code ✅]
VerifyCode -->|Valid| Dashboard[Redirect to Dashboard ✅]
VerifyCode -->|Invalid| Error3[Invalid Code 🔄 Can retry]
Error3 --> Resend[Resend Code Option]
Resend --> EnterCodeUpdate checklist:
- ✅ Added 2FA flow branch
- ✅ Maintained existing non-2FA path
- ✅ Added error handling for 2FA
- ✅ Added resend code recovery option
- ✅ Updated key insights about security
- ✅ Updated related files (2FA service)
Common Update Scenarios
Scenario: File Renamed
Action: Update "Related Files" section
# Before
**Related Files:**
- `src/utils/helpers.ts`
# After
**Related Files:**
- `src/utils/stringHelpers.ts`Change History:
- **2025-01-16:** Updated file path after refactoring utils directoryScenario: Performance Improved
Action: Update impact annotations with new metrics
# Before
API Call [⚡ Fast response]
# After
API Call [⚡ <100ms response (improved from 500ms)]Change History:
- **2025-01-16:** Updated performance metrics after optimization - 5x improvementScenario: Error Handling Added
Action: Add error path to diagram
# Before (no error path)
Service --> DB --> Success
# After (with error path)
Service --> DB
DB -->|Success| Success
DB -->|Error| ErrorHandler[Error Handler 🔄 Prevents data loss]
ErrorHandler --> RetryChange History:
- **2025-01-16:** Added error handling with automatic retry logicScenario: New Dependency Added
Action: Add new component to diagram
# Before
API --> Database
# After
API --> Cache[Cache Layer 💾 New dependency]
Cache --> DatabaseRelated Files (add new files):
- `src/services/cache/cacheService.ts` (new)Change History:
- **2025-01-16:** Added Redis caching layer for improved performanceBatch Updates
When multiple diagrams need updating:
1. Create Update List
## Diagrams to Update
1. **feature-user-authentication.md**
- Added 2FA flow
- Update related files
2. **sequence-login-journey.md**
- Add 2FA steps
- Update timing annotations
3. **arch-system-overview.md**
- Add 2FA service component
- Update dependencies2. Update Systematically
Process one diagram at a time:
- Read current diagram
- Make changes
- Validate quality
- Update metadata
- Test Mermaid rendering
3. Update Index
After all updates, update README.md:
## Last Updated
2025-01-16 - Updated authentication diagrams to include 2FA implementationValidation After Updates
Mermaid Syntax Check
Test diagram renders correctly:
- Copy Mermaid code
- Paste into Mermaid Live Editor
- Verify no syntax errors
- Check layout and readability
DDD Compliance Check
- [ ] Still shows Front-Stage and Back-Stage?
- [ ] New components have impact annotations?
- [ ] Error paths are included?
- [ ] User value is clear?
Metadata Check
- [ ] "Last Updated" is current date?
- [ ] "Related Files" are accurate?
- [ ] "Change History" has new entry?
- [ ] "Key Insights" reflect changes?
Content Check
- [ ] Diagram matches current code?
- [ ] Performance metrics are accurate?
- [ ] All branches are shown?
- [ ] No obsolete components remain?
Troubleshooting
Diagram Too Complex After Updates
Problem: Diagram now has too many components
Solutions: 1. Split into multiple diagrams (e.g., auth-overview + auth-2fa-detail) 2. Use subgraphs to organize complexity 3. Create separate Before/After refactoring diagram 4. Move detailed flows to separate sequence diagrams
Can't Determine User Impact
Problem: Technical change but unclear user benefit
Solutions: 1. Ask: "What user problem does this solve?" 2. Look for performance improvements (speed) 3. Look for reliability improvements (fewer errors) 4. Look for security improvements (safer data) 5. If no user impact, reconsider if change was necessary
Multiple Diagrams Affected
Problem: One code change affects many diagrams
Solutions: 1. Prioritize: Update most important diagrams first 2. Create checklist of all affected diagrams 3. Update systematically to avoid missing any 4. Consider if diagrams are too granular (consolidate?)
Unsure What Changed
Problem: Can't remember what changed in code
Solutions:
# View recent changes
git log --since="1 week ago" --oneline
# See specific file changes
git diff HEAD~5 path/to/file
# Compare with diagram date
# Diagram last updated: 2025-01-10
git log --since="2025-01-10" --name-only path/to/related/filesBest Practices
1. Update immediately after code changes - Don't let diagrams drift 2. Be specific in change history - Future you will thank you 3. Update impact annotations - If performance improved, update metrics 4. Test Mermaid syntax - Validate before committing 5. Update related files accurately - Don't leave outdated paths 6. Keep user focus - Every update should maintain user-centricity 7. Validate quality - Run through DDD checklist 8. Batch related updates - Update all affected diagrams together
Next Steps
After updating diagrams: 1. Commit changes with descriptive message 2. Update README.md if needed 3. Reference in pull request description 4. Use in code review to explain changes 5. Share with team in documentation channels