Skip to main content

createPatternDetector

Orchestrates sequence matching, session analysis, and design pattern detection to identify reusable workflow patterns from tool usage history.

Function Signature

function createPatternDetector(): {
  detectPatterns(
    eventSessions: ToolEvent[][],
    options?: PatternDetectorOptions
  ): DetectedPattern[];
  
  getPendingPatterns(
    eventSessions: ToolEvent[][],
    minConfidence?: number
  ): DetectedPattern[];
}
Source: src/core/pattern-detector.ts:185

Return Value

Returns an object with two detection methods:
detectPatterns
function
Main pattern detection pipeline. Analyzes tool sequences, calculates confidence scores, and optionally enriches with v2 session context.
getPendingPatterns
function
Convenience wrapper that filters patterns by minimum confidence threshold (default 0.7).

Methods

detectPatterns

Analyzes grouped event sessions to find repeated tool usage patterns. Pipeline:
  1. Extract tool name sequences from each session
  2. Run sequence matcher to find repeated subsequences
  3. Collect session IDs, timestamps, success rates
  4. Calculate weighted confidence scores
  5. Generate pattern names and descriptions
  6. Optionally enhance with session context and design patterns (v2)
eventSessions
ToolEvent[][]
required
Array of session event arrays. Each inner array represents a complete coding session.
options
PatternDetectorOptions
Optional configuration for pattern detection.
Returns: DetectedPattern[] - Array of patterns sorted by confidence descending.

getPendingPatterns

Filters detected patterns by confidence threshold.
eventSessions
ToolEvent[][]
required
Array of session event arrays.
minConfidence
number
Minimum confidence score (0.0 to 1.0). Patterns below this threshold are filtered out.
Returns: DetectedPattern[] - Filtered patterns meeting the confidence threshold.

DetectedPattern Type

id
string
SHA-256 based pattern identifier (first 12 hex chars).
toolSequence
string[]
Ordered list of tool names (e.g. ["Read", "Edit", "Bash"]).
occurrenceCount
number
Number of times this pattern appeared across sessions.
confidence
number
Weighted confidence score (0.0 to 1.0) based on occurrence, length, success rate, and recency.Formula: occurrence(0.4) + length(0.2) + success(0.25) + recency(0.15)
sessionIds
string[]
List of session IDs where this pattern was observed.
firstSeen
string
ISO-8601 timestamp of first occurrence.
lastSeen
string
ISO-8601 timestamp of most recent occurrence.
successRate
number
Ratio of successful pattern executions (0.0 to 1.0).
suggestedName
string
Human-readable pattern name (e.g. "read-then-edit").
suggestedDescription
string
Plain language description of the workflow.
sessionContext
Record<string, unknown> | null
V2: Aggregated session analysis data (primary intent, problem domains, workflow type).
designPatterns
Record<string, unknown>[]
V2: Detected design patterns (TDD, MVC, Repository, etc.) with confidence scores.
problemSolvingApproach
Record<string, unknown> | null
V2: Detected problem-solving methodology with steps and guidance.

Usage Example

import { createPatternDetector } from "./core/pattern-detector";
import { createEventStore } from "./core/event-store";

// Initialize detector
const detector = createPatternDetector();

// Get event sessions from storage
const store = createEventStore();
const sessions = store.getEventsWithInputs(undefined, 7);

// Detect patterns with custom options
const patterns = detector.detectPatterns(sessions, {
  minOccurrences: 3,
  minSequenceLength: 2,
  maxSequenceLength: 8,
  enableV2: true,
});

console.log(`Found ${patterns.length} patterns`);

for (const pattern of patterns) {
  console.log(`\n${pattern.suggestedName} (confidence: ${pattern.confidence.toFixed(2)})`);
  console.log(`  Tools: ${pattern.toolSequence.join(" → ")}`);
  console.log(`  Occurrences: ${pattern.occurrenceCount}`);
  console.log(`  Success rate: ${(pattern.successRate * 100).toFixed(0)}%`);
  
  if (pattern.sessionContext) {
    const ctx = pattern.sessionContext as Record<string, unknown>;
    console.log(`  Primary intent: ${ctx.primaryIntent}`);
  }
}

// Get only high-confidence patterns
const pendingPatterns = detector.getPendingPatterns(sessions, 0.75);
console.log(`\n${pendingPatterns.length} patterns ready for skill generation`);

Confidence Calculation

The confidence score uses a weighted formula combining four factors: Occurrence Score (40%): Logarithmic scaling log(count+1) / log(10)
  • Rewards patterns that repeat frequently
  • Diminishing returns prevent over-weighting extremely common patterns
Length Score (20%): Optimal range 3-5 tools
  • length 3-5: score = 1.0 (ideal)
  • length 2: score = 0.7 (acceptable)
  • length > 5: score = max(0.5, 1.0 - (length - 5) * 0.1) (penalized)
Success Score (25%): Direct ratio of successful executions
  • successRate = successfulRuns / totalRuns
Recency Score (15%): Time decay since last use
  • max(0.5, 1.0 - daysSinceLast * 0.05)
  • Patterns used recently score higher
Source: src/core/pattern-detector.ts:130-173

V2 Enhancements

When enableV2: true (default), the detector enriches patterns with:

Session Context Analysis

  • Primary user intent (debug, implement, refactor, test, explore, document)
  • Problem domains extracted from file paths
  • Workflow type classification (TDD, Debug-Systematic, Refactor-Safe)
  • Tool success rates and session duration metrics

Design Pattern Detection

  • Architectural patterns (MVC, Repository, Factory, Singleton)
  • Coding patterns (Error-First, REST-API, Async, Decorators)
  • Workflow patterns (TDD, Refactor-Safe, Debug-Systematic)

Problem-Solving Approaches

  • Contextual guidance on when to use the pattern
  • Step-by-step methodology
  • Benefits and tradeoffs
Source: src/core/pattern-detector.ts:278-369

See Also

Build docs developers (and LLMs) love