Feature ID: 032 Status: Production Ready Version: Introduced in Auto Code 3.0+
Intelligent Pattern Recognition enhances Auto Code's Graphiti memory system to automatically identify, categorize, and suggest coding patterns from completed builds. This feature creates compounding value - the system gets smarter over time as you build more features, unlike competitors that start fresh each session.
The system automatically:
- Extracts patterns from successful builds (architecture decisions, error handling approaches, testing strategies, etc.)
- Categorizes patterns using AI into 14 categories
- Suggests relevant patterns during spec creation and implementation
- Allows user confirmation - you can confirm, reject, or modify suggested patterns
Cross-session memory is a key differentiator for Auto Code. This feature makes that memory actionable:
- Consistency: Future features follow established patterns automatically
- Knowledge retention: Architectural decisions persist across sessions
- Reduced repetition: The system learns from past solutions
- Compounding intelligence: Each build makes the next one smarter
- Location:
apps/backend/integrations/graphiti/pattern_categorizer.py - Purpose: AI-based classification of patterns into categories
- Categories:
- Architecture
- API Design
- State Management
- Error Handling
- Testing
- Security
- Performance
- Database
- UI/UX
- Accessibility
- Documentation
- Deployment
- Integration
- Code Quality
- Confidence Scoring: Returns 95-98% confidence scores for categorization
- Location:
apps/backend/integrations/graphiti/pattern_suggester.py - Purpose: Semantic search and filtering to find relevant patterns
- Features:
- Semantic similarity search using embeddings
- Category-based filtering
- Relevance scoring
- Context-aware suggestions
- Location:
apps/backend/agents/memory_manager.py - Enhancement: Added
get_pattern_suggestions()function - Integration: Fetches and formats pattern suggestions for AI agents
- Schema: New
EPISODE_TYPE_PATTERNinqueries_pkg/schema.py
- Modified Files:
apps/backend/prompt_generator.py- Includes patterns in contextapps/backend/runners/spec_runner.py- Fetches patterns during spec creation
- Phases: Integrated into spec_writing, planning, and quick_spec phases
- Location:
apps/frontend/src/renderer/components/CreateSpecView.tsx - Features:
- Visual display of pattern suggestions
- Category badges with color coding
- Confidence indicators
- Confirm/Reject/Modify actions
- Pattern preview with code snippets
- Location:
apps/frontend/src/main/ipc-handlers/context/memory-data-handlers.ts - Handlers:
CONTEXT_GET_PATTERN_SUGGESTIONS- Retrieves relevant patterns for a taskCONTEXT_CONFIRM_PATTERN- Records user confirmation/rejection in Graphiti
- Integration: Connects frontend UI to Python backend via subprocess
- Create a new spec in the Auto Code UI
- Enter your feature description (e.g., "Add user authentication")
- Review suggested patterns that appear automatically
- For each suggestion:
- Click ✓ Confirm to include it in your spec
- Click ✗ Reject if not relevant
- Click ✎ Modify to adjust the pattern before using
- Continue with spec creation - confirmed patterns guide the implementation
Patterns are automatically injected into agent context during:
- Spec creation (Spec Writer agent)
- Implementation planning (Planner agent)
- Code generation (Coder agent)
No manual intervention required - the system handles it transparently.
Patterns are stored as Graphiti episodes with:
- Type:
EPISODE_TYPE_PATTERN - Metadata: Category, confidence score, source spec
- Content: Pattern description, code examples, context
- Relationships: Linked to related entities (files, concepts, specs)
When a new task is created:
- Task description is embedded using configured embedder (Ollama or OpenAI)
- Semantic search finds similar past patterns
- Results are filtered by relevance threshold (>0.7)
- Category filters apply if specified
- Top N patterns returned (default: 5)
When a user confirms a pattern:
- Frontend sends confirmation via IPC
- Backend creates a new Graphiti episode
- Episode records the confirmation event
- Relationships link pattern → user → task
- Future suggestions weight confirmed patterns higher
Pattern suggestions require an embedder for semantic search:
Option 1: Ollama (Local, Free)
# Set environment variable
OLLAMA_EMBEDDING_MODEL=nomic-embed-textOption 2: OpenAI (Cloud, Paid)
# Set environment variable
OPENAI_API_KEY=your_api_key_hereModify pattern_categorizer.py to:
- Add custom categories
- Adjust confidence thresholds
- Change categorization prompts
Modify pattern_suggester.py to:
- Adjust relevance threshold
- Change number of suggestions
- Customize filtering logic
A comprehensive end-to-end test validates the full workflow:
Location: apps/backend/test_pattern_workflow.py
Test Coverage:
- Pattern categorization (5 patterns, 14 categories)
- Agent registration (pattern_categorizer configured)
- Import paths (GraphitiMemory imports)
- Pattern suggestion (semantic search + filtering)
- Memory manager integration
Run Test:
cd apps/backend
python test_pattern_workflow.pyExpected Output: All 5 tests pass with 95-98% confidence scores
- Complete a feature build with authentication
- Create a new spec for "login feature"
- Verify authentication patterns appear in suggestions
- Confirm a pattern and verify it's included in generated spec
integrations/graphiti/pattern_categorizer.py(NEW)integrations/graphiti/pattern_suggester.py(NEW)integrations/graphiti/queries_pkg/queries.py(MODIFIED)integrations/graphiti/queries_pkg/schema.py(MODIFIED)integrations/graphiti/queries_pkg/search.py(MODIFIED)agents/memory_manager.py(MODIFIED)prompt_generator.py(MODIFIED)runners/spec_runner.py(MODIFIED)
src/renderer/components/CreateSpecView.tsx(MODIFIED)src/main/ipc-handlers/context/memory-data-handlers.ts(MODIFIED)
test_pattern_workflow.py(NEW)
Total Changes: +2,105 lines
- Pattern categorization: ~2-3s per pattern (AI classification)
- Pattern suggestion: ~500ms (semantic search)
- No impact on existing workflows - only activates when creating specs
- ✓ No hardcoded secrets
- ✓ No dangerous operations (eval, innerHTML)
- ✓ Proper input sanitization in IPC handlers
- ✓ Auth tokens handled via
get_auth_token()
- Embedder Required: Pattern suggestions only work with configured embedder (Ollama or OpenAI)
- Cold Start: First few builds won't have patterns to suggest (system needs data)
- Context Window: Very large codebases may exceed context limits for pattern extraction
This PR extends pattern recognition with automatic generation of language-specific pattern libraries from codebase analysis via AST extraction and AI categorization.
The Pattern Library Generator:
- Scans project source files for the specified language(s)
- Extracts patterns using AST analysis (function signatures, class structures, module patterns, error handling, etc.)
- Categorizes each pattern using AI classification
- Generates importable Python modules in the same format as the manual pattern libraries
cd apps/backend
python cli/main.py pattern generate --language python --output patterns/python_patterns.pycd apps/backend
python cli/main.py pattern generate-all --output-dir patterns/| Option | Description |
|---|---|
--language |
Target language (python, javascript, typescript, go, rust, java, csharp, cpp, ruby, php) |
--output |
Output file path for generated module |
--output-dir |
Output directory for batch generation |
--source |
Optional source directory to scan (defaults to project root) |
--max-patterns |
Maximum patterns to extract per language (default: 50) |
--languages |
Comma-separated list for generate-all (defaults to all detected) |
| Language | Extensions |
|---|---|
| Python | .py |
| JavaScript | .js, .jsx |
| TypeScript | .ts, .tsx |
| Go | .go |
| Rust | .rs |
| Java | .java |
| C# | .cs |
| C++ | .cpp, .cc, .cxx, .hpp, .h |
| Ruby | .rb |
| PHP | .php |
cli/pattern_commands.py # CLI interface (generate, generate-all actions)
integrations/graphiti/
├── pattern_library_generator.py # Core generator: scan → extract → categorize → emit
├── pattern_extractor.py # AST-based pattern extraction
└── pattern_categorizer.py # AI-based pattern classification
context/pattern_discovery.py # Runtime pattern discovery from generated libraries
patterns/__init__.py # Dynamic pattern loader
The generator produces importable Python modules compatible with the existing manual pattern libraries:
"""
Auto-generated Python Pattern Library
=====================================
Extracted from codebase analysis.
"""
PYTHON_PATTERNS = {
"error_handling": {
"try_except_logging": "try:\\n result = operation()\\nexcept Exception as e:\\n logger.error(f'Operation failed: {e}')\\n raise",
},
"architecture": {
"factory_pattern": "class ServiceFactory:\\n @staticmethod\\n def create(type: str) -> Service: ...",
},
}# Run pattern library generator tests
python -m pytest tests/test_pattern_library_generator.py -v
# Run CLI integration tests
python -m pytest tests/test_pattern_cli_generation.py -vPotential improvements for future versions:
- Pattern confidence decay over time (older patterns less relevant)
- Pattern versioning (track evolution of patterns)
- Pattern merging (consolidate similar patterns)
- Pattern analytics (most used, most effective patterns)
- Cross-project pattern sharing (team-wide pattern library)
Cause: Embedder not configured or no patterns stored yet
Solution:
- Set
OLLAMA_EMBEDDING_MODELorOPENAI_API_KEY - Complete a few builds to populate pattern database
- Verify embedder is running:
curl http://localhost:11434/api/embeddings(Ollama)
Cause: Pattern description too vague or irrelevant
Solution:
- Reject low-confidence patterns
- Modify pattern descriptions to be more specific
- Adjust confidence threshold in
pattern_categorizer.py
Cause: TypeScript type mismatches or Python subprocess failures
Solution:
- Check
memory-data-handlers.tsfor TypeScript errors - Verify Python backend imports work:
python -c "from integrations.graphiti.pattern_suggester import suggest_patterns; print('OK')" - Check logs in Auto Code terminal
- Spec:
.auto-claude/specs/032-intelligent-pattern-recognition/spec.md - Implementation Plan:
.auto-claude/specs/032-intelligent-pattern-recognition/implementation_plan.json - QA Report:
.auto-claude/specs/032-intelligent-pattern-recognition/qa_report.md - Graphiti Integration:
apps/backend/integrations/graphiti/
To contribute improvements to pattern recognition:
- Read existing pattern categorizer/suggester code
- Follow established Graphiti integration patterns
- Add tests to
test_pattern_workflow.py - Update this documentation with your changes
- Submit PR with QA validation
Questions or issues? Open a GitHub issue or ask in Discord.