Skip to main content

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

function createDesignPatternDetector(): {
  detectWorkflowPattern(
    toolSequence: string[],
    sessionContext?: Record<string, unknown>
  ): DesignPattern | null;
  
  detectPatternsFromFiles(
    filePaths: string[],
    fileContents: Map<string, string>
  ): DesignPattern[];
  
  getPatternContext(patternName: string): PatternContext | null;
  
  suggestPatternsForContext(
    intent: string,
    problemDomain: string
  ): Array<{ pattern: string; relevance: number }>;
}
Source: 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.
toolSequence
string[]
required
Ordered list of tool names used in a session (e.g. ["Write", "Bash", "Edit", "Bash"]).
sessionContext
Record<string, unknown>
Optional session context from createSessionAnalyzer for confidence boosting.
Returns: DesignPattern | null - Detected workflow pattern, or null if no match. Detection logic:
  1. Match tool sequence against known workflow patterns (TDD, Debug-Systematic, Refactor-Safe, Explore-Then-Implement)
  2. Base confidence: 0.7 for sequence match
  3. Boost confidence by 0.05 per matching keyword indicator in session context (max 0.95)
Source: src/core/design-pattern-detector.ts:271

detectPatternsFromFiles

Detects architectural and coding patterns from file paths and source code.
filePaths
string[]
required
List of file paths to inspect (e.g. ["/src/models/User.ts", "/src/controllers/AuthController.ts"]).
fileContents
Map<string, string>
required
Map from file path to source code content.
Returns: DesignPattern[] - List of detected patterns sorted by confidence descending. Detection logic:
  1. Architectural patterns: Check file paths for directory structure indicators (models/, views/, controllers/, repository/, factory/)
  2. Coding patterns: Check file contents for code indicators (try/except, @decorator, async/await)
  3. Calculate confidence based on indicator matches vs. total indicators
  4. Filter patterns meeting minimum confidence threshold
  5. Extract code examples for coding patterns
Source: src/core/design-pattern-detector.ts:328

getPatternContext

Retrieves contextual guidance for when to use a pattern.
patternName
string
required
Name of the pattern (e.g. "MVC", "TDD", "Repository").
Returns: 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.
intent
string
required
User intent (e.g. "implement", "refactor", "debug", "test").
problemDomain
string
required
Problem domain (e.g. "api", "database", "async", "web").
Returns: Array<{pattern: string, relevance: number}> - Suggested patterns sorted by relevance descending. Suggestion logic:
  1. Match intent against INTENT_PATTERN_MAP (relevance 0.8)
  2. Match domain against DOMAIN_PATTERN_MAP (relevance 0.7)
  3. Deduplicate and take highest relevance per pattern
  4. Sort by relevance descending
Source: src/core/design-pattern-detector.ts:476

DesignPattern Type

patternId
string
Unique identifier (e.g. "workflow-tdd", "arch-mvc", "code-async-pattern").
patternType
string
Pattern category: "architectural", "coding", or "workflow".
patternName
string
Human-readable pattern name (e.g. "MVC", "TDD", "Factory").
confidence
number
Detection confidence score (0.0 to 1.0).
description
string
Plain language description of the pattern.
indicators
string[]
List of indicators that triggered detection (e.g. ["Found 'model' in User.ts", "Found 'view' in index.html"]).
affectedFiles
string[]
List of files where the pattern was detected (up to 10).
codeExamples
string[]
Code snippets demonstrating the pattern (up to 3, max 200 chars each).
metadata
Record<string, unknown>
Additional pattern-specific metadata.
Source: src/types/index.ts:249-259

PatternContext Type

patternName
string
Pattern name.
whenToUse
string
Description of when this pattern is appropriate.
benefits
string[]
List of benefits from using this pattern.
tradeOffs
string[]
List of tradeoffs and costs.
commonMistakes
string[]
Common pitfalls when implementing this pattern.
Source: src/types/index.ts:262-268

Detected Patterns

Architectural Patterns (8)

MVC - Model-View-Controller separation pattern
  • Indicators: model, view, controller, models/, views/, controllers/
Repository - Data access abstraction
  • Indicators: repository, repo, data_access, dal
Factory - Object creation
  • Indicators: factory, create_, builder
Singleton - Single-instance classes
  • Indicators: singleton, _instance, get_instance
Strategy - Interchangeable algorithms
  • Indicators: strategy, algorithm, policy
Observer - Event handling
  • Indicators: observer, subscriber, listener, event
Adapter - Interface compatibility
  • Indicators: adapter, wrapper, facade
Dependency-Injection - DI pattern
  • Indicators: inject, container, provider, di_
Source: src/core/design-pattern-detector.ts:32-80

Coding Patterns (6)

Error-First-Handling - Error-first error handling
  • Indicators: try, except, raise, error, exception
REST-API-Design - RESTful API design
  • Indicators: @app.route, @router, GET, POST, PUT, DELETE
Async-Pattern - Asynchronous programming
  • Indicators: async, await, asyncio, concurrent
Decorator-Pattern - Python decorators
  • Indicators: @decorator, @property, @staticmethod
Context-Manager - Context managers (with statement)
  • Indicators: __enter__, __exit__, with , contextmanager
Builder-Pattern - Fluent builder
  • Indicators: builder, build(), with_, set_
Source: 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
Refactor-Safe - Safe refactoring with tests
  • Tool sequence: ["Read", "Edit", "Bash"]
  • Keywords: refactor, test, extract, rename
Debug-Systematic - Systematic debugging
  • Tool sequence: ["Read", "Grep", "Bash", "Edit"]
  • Keywords: debug, print, log, trace
Explore-Then-Implement - Exploration before implementation
  • Tool sequence: ["Grep", "Read", "Read", "Write"]
  • Keywords: understand, explore, analyze
Source: src/core/design-pattern-detector.ts:115-136

Usage Example

import { createDesignPatternDetector } from "./core/design-pattern-detector";
import { createSessionAnalyzer } from "./core/session-analyzer";
import { createEventStore } from "./core/event-store";
import fs from "node:fs";

// Initialize detector
const detector = createDesignPatternDetector();

// Detect workflow pattern from tool sequence
const store = createEventStore();
const analyzer = createSessionAnalyzer();

const sessionId = "session-123";
const events = store.getSessionEvents(sessionId);
const toolSequence = events.map(e => e.toolName);

const sessionContext = analyzer.analyzeSession(sessionId, events);
const workflowPattern = detector.detectWorkflowPattern(
  toolSequence,
  sessionContext
);

if (workflowPattern) {
  console.log(`\nDetected workflow: ${workflowPattern.patternName}`);
  console.log(`Confidence: ${workflowPattern.confidence.toFixed(2)}`);
  console.log(`Description: ${workflowPattern.description}`);
  console.log(`Indicators: ${workflowPattern.indicators.join(", ")}`);
}

// Detect patterns from source files
const filePaths = [
  "/src/models/User.ts",
  "/src/controllers/AuthController.ts",
  "/src/views/dashboard.tsx",
  "/src/repositories/UserRepository.ts",
];

const fileContents = new Map<string, string>();
for (const path of filePaths) {
  fileContents.set(path, fs.readFileSync(path, "utf-8"));
}

const codePatterns = detector.detectPatternsFromFiles(filePaths, fileContents);

console.log(`\n\nDetected ${codePatterns.length} patterns from code:\n`);

for (const pattern of codePatterns) {
  console.log(`${pattern.patternName} (${pattern.patternType})`);
  console.log(`  Confidence: ${pattern.confidence.toFixed(2)}`);
  console.log(`  Description: ${pattern.description}`);
  console.log(`  Affected files: ${pattern.affectedFiles.length}`);
  
  if (pattern.codeExamples.length > 0) {
    console.log(`  Example:\n${pattern.codeExamples[0]}`);
  }
  
  // Get usage guidance
  const context = detector.getPatternContext(pattern.patternName);
  if (context) {
    console.log(`  When to use: ${context.whenToUse}`);
    console.log(`  Benefits: ${context.benefits.slice(0, 2).join(", ")}`);
  }
  
  console.log();
}

// Suggest patterns for a context
const suggestions = detector.suggestPatternsForContext(
  "implement",
  "api"
);

console.log(`\n\nPattern suggestions for implementing an API:\n`);
for (const { pattern, relevance } of suggestions) {
  console.log(`${pattern} (relevance: ${relevance.toFixed(2)})`);
}

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
Tradeoffs:
  • Can be overkill for simple applications
  • More files and indirection
Common mistakes:
  • 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
Tradeoffs:
  • Slower initial development
  • Requires discipline
Common mistakes:
  • Testing implementation instead of behavior
  • Skipping refactor step
Source: 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
Source: src/core/design-pattern-detector.ts:200-212

Confidence Calculation

Architectural & Coding Patterns

confidence = min(1.0, indicatorsFound / (totalIndicators * multiplier))
  • Architectural patterns: multiplier = 2
  • Coding patterns: multiplier = 3
  • Must meet minConfidence threshold 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
Source: src/core/design-pattern-detector.ts:367-383, 285-298

Code Example Extraction

For coding patterns, the detector extracts small code examples:
  1. Find first line containing the indicator
  2. Extract 3 lines before and after (7 lines total)
  3. Truncate to 200 chars
Example output:
try {
  const result = await api.fetch();
  return result.data;
} catch (error) {
  logger.error(error);
  throw new ApiError(error);
}
Source: src/core/design-pattern-detector.ts:439

See Also

Build docs developers (and LLMs) love