createDesignPatternDetector
Detects design patterns at multiple levels: architectural patterns (MVC, Repository, Factory), coding patterns (error handling, async, decorators), and workflow patterns (TDD, debugging strategies).Function Signature
src/core/design-pattern-detector.ts:249
Return Value
Returns an object with pattern detection and suggestion methods.Methods
detectWorkflowPattern
Detects a workflow pattern from tool usage sequences.Ordered list of tool names used in a session (e.g.
["Write", "Bash", "Edit", "Bash"]).Optional session context from
createSessionAnalyzer for confidence boosting.DesignPattern | null - Detected workflow pattern, or null if no match.
Detection logic:
- Match tool sequence against known workflow patterns (TDD, Debug-Systematic, Refactor-Safe, Explore-Then-Implement)
- Base confidence: 0.7 for sequence match
- Boost confidence by 0.05 per matching keyword indicator in session context (max 0.95)
src/core/design-pattern-detector.ts:271
detectPatternsFromFiles
Detects architectural and coding patterns from file paths and source code.List of file paths to inspect (e.g.
["/src/models/User.ts", "/src/controllers/AuthController.ts"]).Map from file path to source code content.
DesignPattern[] - List of detected patterns sorted by confidence descending.
Detection logic:
- Architectural patterns: Check file paths for directory structure indicators (models/, views/, controllers/, repository/, factory/)
- Coding patterns: Check file contents for code indicators (try/except, @decorator, async/await)
- Calculate confidence based on indicator matches vs. total indicators
- Filter patterns meeting minimum confidence threshold
- Extract code examples for coding patterns
src/core/design-pattern-detector.ts:328
getPatternContext
Retrieves contextual guidance for when to use a pattern.Name of the pattern (e.g.
"MVC", "TDD", "Repository").PatternContext | null - Usage guidance, or null if unknown pattern.
Source: src/core/design-pattern-detector.ts:462
suggestPatternsForContext
Suggests relevant patterns based on user intent and problem domain.User intent (e.g.
"implement", "refactor", "debug", "test").Problem domain (e.g.
"api", "database", "async", "web").Array<{pattern: string, relevance: number}> - Suggested patterns sorted by relevance descending.
Suggestion logic:
- Match intent against
INTENT_PATTERN_MAP(relevance 0.8) - Match domain against
DOMAIN_PATTERN_MAP(relevance 0.7) - Deduplicate and take highest relevance per pattern
- Sort by relevance descending
src/core/design-pattern-detector.ts:476
DesignPattern Type
Unique identifier (e.g.
"workflow-tdd", "arch-mvc", "code-async-pattern").Pattern category:
"architectural", "coding", or "workflow".Human-readable pattern name (e.g.
"MVC", "TDD", "Factory").Detection confidence score (0.0 to 1.0).
Plain language description of the pattern.
List of indicators that triggered detection (e.g.
["Found 'model' in User.ts", "Found 'view' in index.html"]).List of files where the pattern was detected (up to 10).
Code snippets demonstrating the pattern (up to 3, max 200 chars each).
Additional pattern-specific metadata.
src/types/index.ts:249-259
PatternContext Type
Pattern name.
Description of when this pattern is appropriate.
List of benefits from using this pattern.
List of tradeoffs and costs.
Common pitfalls when implementing this pattern.
src/types/index.ts:262-268
Detected Patterns
Architectural Patterns (8)
MVC - Model-View-Controller separation pattern- Indicators:
model,view,controller,models/,views/,controllers/
- Indicators:
repository,repo,data_access,dal
- Indicators:
factory,create_,builder
- Indicators:
singleton,_instance,get_instance
- Indicators:
strategy,algorithm,policy
- Indicators:
observer,subscriber,listener,event
- Indicators:
adapter,wrapper,facade
- Indicators:
inject,container,provider,di_
src/core/design-pattern-detector.ts:32-80
Coding Patterns (6)
Error-First-Handling - Error-first error handling- Indicators:
try,except,raise,error,exception
- Indicators:
@app.route,@router,GET,POST,PUT,DELETE
- Indicators:
async,await,asyncio,concurrent
- Indicators:
@decorator,@property,@staticmethod
- Indicators:
__enter__,__exit__,with,contextmanager
- Indicators:
builder,build(),with_,set_
src/core/design-pattern-detector.ts:82-113
Workflow Patterns (4)
TDD - Test-Driven Development- Tool sequence:
["Write", "Bash", "Edit", "Bash"] - Keywords: test, assert, pytest, unittest
- Tool sequence:
["Read", "Edit", "Bash"] - Keywords: refactor, test, extract, rename
- Tool sequence:
["Read", "Grep", "Bash", "Edit"] - Keywords: debug, print, log, trace
- Tool sequence:
["Grep", "Read", "Read", "Write"] - Keywords: understand, explore, analyze
src/core/design-pattern-detector.ts:115-136
Usage Example
Pattern Context Examples
MVC Pattern
When to use: Building web applications with clear separation of concerns Benefits:- Separates business logic from presentation
- Easier to test and maintain
- Multiple views can share same model
- Can be overkill for simple applications
- More files and indirection
- Putting business logic in controllers
- Tight coupling between layers
TDD Pattern
When to use: When building new features or fixing bugs Benefits:- Better test coverage
- Forces you to think about requirements
- Refactoring confidence
- Slower initial development
- Requires discipline
- Testing implementation instead of behavior
- Skipping refactor step
src/core/design-pattern-detector.ts:142-194
Pattern Suggestion Maps
Intent → Patterns
- implement: Factory, Builder-Pattern, Strategy
- refactor: Refactor-Safe, Extract-Method
- debug: Debug-Systematic, Error-First-Handling
- test: TDD, Mock-Pattern
Domain → Patterns
- api: REST-API-Design, Adapter, Repository
- database: Repository, DAO
- async: Async-Pattern, Observer
- web: MVC, REST-API-Design
src/core/design-pattern-detector.ts:200-212
Confidence Calculation
Architectural & Coding Patterns
- Architectural patterns: multiplier = 2
- Coding patterns: multiplier = 3
- Must meet
minConfidencethreshold to be included
Workflow Patterns
- Base confidence: 0.7 for sequence match
- Boost: +0.05 per matching keyword in session context
- Max confidence: 0.95
src/core/design-pattern-detector.ts:367-383, 285-298
Code Example Extraction
For coding patterns, the detector extracts small code examples:- Find first line containing the indicator
- Extract 3 lines before and after (7 lines total)
- Truncate to 200 chars
src/core/design-pattern-detector.ts:439
See Also
- createPatternDetector - Uses design patterns for v2 enrichment
- createSessionAnalyzer - Provides session context for detection
- DesignPattern Type - Full pattern schema