Pattern Detection
The Pattern Detection system is the brain of Auto-Skill. It analyzes your tool usage history to identify recurring workflow patterns that can be codified into reusable skills.
Detection Pipeline
Pattern detection follows a three-stage pipeline:
Sequence Matching
Identifies repeated tool sequences across sessions using sliding window analysis
Confidence Calculation
Scores patterns based on occurrence, success rate, sequence length, and recency
V2 Enhancement
Enriches patterns with session context, design patterns, and problem-solving approaches
Detection Triggers
Auto-Skill detects patterns through five key triggers:
1. Repetition
The most common trigger. When you use the same tool sequence 3+ times , it becomes a pattern candidate.
// Default configuration from pattern-detector.ts:50-60
export interface PatternDetectorOptions {
minOccurrences ?: number ; // Default: 3
minSequenceLength ?: number ; // Default: 2
maxSequenceLength ?: number ; // Default: 10
lookbackDays ?: number ; // Default: 7
enableV2 ?: boolean ; // Default: true
}
Example : If you repeatedly use Read → Grep → Edit → Bash when debugging, Auto-Skill will detect this as a “Debug-Systematic” pattern.
2. Success Patterns
Tool sequences with high success rates (80%+) are prioritized:
// From pattern-detector.ts:130-173
function calculateConfidence (
occurrenceCount : number ,
sequenceLength : number ,
successRate : number ,
lastSeenMs : number
) : number {
// Weighted formula:
const confidence =
occurrenceScore * 0.4 + // 40% weight on occurrence
lengthScore * 0.2 + // 20% weight on sequence length
successScore * 0.25 + // 25% weight on success rate
recencyScore * 0.15 ; // 15% weight on recency
return Math . min ( 1.0 , Math . max ( 0.0 , confidence ));
}
3. User Corrections
When you redirect the agent’s approach, Auto-Skill learns from the correction pattern.
4. Explicit Teaching
Domain knowledge you provide during conversations is captured and integrated into pattern context.
5. Error Recovery
Successful self-correction sequences are detected as problem-solving patterns.
Confidence Scoring
Each pattern receives a confidence score (0.0-1.0) based on a weighted formula:
Occurrence Score 40% weight — Logarithmic scaling from occurrence countMath.log(count + 1) / Math.log(10)
Length Score 20% weight — Optimal range is 3-5 tools
3-5 tools: 1.0
2 tools: 0.7
6+ tools: decreasing
Success Score 25% weight — Direct success ratesuccessfulRuns / totalRuns
Recency Score 15% weight — 5% decay per day1.0 - daysSinceLast * 0.05
Detected patterns include rich metadata from DetectedPattern type:
// From types/index.ts:30-51
export interface DetectedPattern {
id : string ; // SHA-256 hash (first 12 chars)
toolSequence : string []; // e.g. ["Read", "Edit", "Bash"]
occurrenceCount : number ;
confidence : number ; // 0.0 - 1.0
sessionIds : string [];
firstSeen : string ; // ISO-8601
lastSeen : string ;
successRate : number ;
suggestedName : string ; // e.g. "read-and-bash"
suggestedDescription : string ;
// V2 enhancements
sessionContext ?: Record < string , unknown > | null ;
codeContext ?: Record < string , unknown > | null ;
designPatterns ?: Record < string , unknown >[];
problemSolvingApproach ?: Record < string , unknown > | null ;
mentalContext ?: Record < string , unknown > | null ;
}
Sequence Matching Algorithm
The sequence-matcher.ts module uses a sliding window approach to find common subsequences:
How Sequence Matching Works
Step 1: Extract all subsequences // For each session, extract all subsequences of length 2-10
for ( let length = minLength ; length < maxLength ; length ++ ) {
for ( let start = 0 ; start <= sequence . length - length ; start ++ ) {
const subseq = sequence . slice ( start , start + length );
// Track where this subsequence appears
}
}
Step 2: Filter by minimum occurrence // Only keep sequences that appear in 3+ sessions
if ( sessionIndices . length >= minOccurrences ) {
matches . push ({ sequence , occurrences , sessionIndices });
}
Step 3: Remove subsumed matches // Remove shorter sequences that are fully contained in longer ones
function removeSubsumedMatches ( matches : SequenceMatch []) : SequenceMatch [] {
// Sort by length descending
const sorted = [ ... matches ]. sort (
( a , b ) => b . sequence . length - a . sequence . length
);
// Keep only non-subsumed sequences
}
Pattern Variations
The sequence matcher can also detect pattern variations — sequences that are similar but have 1-2 extra steps:
// From sequence-matcher.ts:159-234
function isVariationOf ( base : string [], candidate : string []) : boolean {
// Must have same start and end tools
if ( candidate [ 0 ] !== base [ 0 ] ||
candidate [ candidate . length - 1 ] !== base [ base . length - 1 ]) {
return false ;
}
// Check that base is a subsequence of candidate
let baseIdx = 0 ;
for ( const tool of candidate ) {
if ( baseIdx < base . length && tool === base [ baseIdx ]) {
baseIdx ++ ;
}
}
return baseIdx === base . length ;
}
Pattern variations allow skills to handle optional steps, making them more flexible for real-world usage.
V2 Enhancements
V2 detection adds three layers of contextual understanding:
Session Context
Design Patterns
Problem-Solving Approach
Analyzes user intent and problem domain from conversation: pattern . sessionContext = {
primaryIntent: "debug" , // debug, implement, refactor, test
problemDomains: [ "api" , "database" ], // extracted from file paths
workflowType: "Debug-Systematic" , // detected workflow pattern
toolSuccessRate: 0.85 ,
avgSessionDurationMinutes: 12.3
};
Detects 18 architectural, coding, and workflow patterns : pattern . designPatterns = [{
name: "TDD" ,
type: "workflow" ,
confidence: 0.85 ,
description: "Test-Driven Development workflow" ,
indicators: [ "Tool sequence: Write -> Bash -> Edit -> Bash" ]
}];
Codifies how to approach similar problems : pattern . problemSolvingApproach = {
type: "TDD" ,
description: "Test-Driven Development workflow" ,
whenToUse: "When building new features or fixing bugs with test coverage" ,
steps: [
"Write a failing test that defines desired behavior" ,
"Run tests to confirm the failure (Red)" ,
"Write minimal code to make the test pass (Green)" ,
"Run tests to confirm they pass" ,
"Refactor code while keeping tests green"
]
};
Patterns are named using human-readable verbs mapped from tool names:
// From pattern-detector.ts:30-42
const TOOL_VERBS : Record < string , string > = {
Read: "read" ,
Write: "write" ,
Edit: "edit" ,
Bash: "run" ,
Grep: "search" ,
Glob: "find" ,
WebFetch: "fetch" ,
WebSearch: "search" ,
Task: "delegate" ,
};
// Example pattern names:
// ["Read", "Edit"] → "read-then-edit"
// ["Grep", "Read", "Write"] → "search-and-write"
Usage Example
Here’s how to use the pattern detector:
import { createPatternDetector } from "./core/pattern-detector" ;
import { createEventStore } from "./core/event-store" ;
// 1. Get tool events from storage
const eventStore = createEventStore ();
const eventSessions = eventStore . getEventsWithInputs (
projectPath ,
lookbackDays : 7
);
// 2. Detect patterns
const detector = createPatternDetector ();
const patterns = detector . detectPatterns ( eventSessions , {
minOccurrences: 3 ,
minSequenceLength: 2 ,
maxSequenceLength: 10 ,
enableV2: true
});
// 3. Filter high-confidence patterns
const pending = patterns . filter ( p => p . confidence >= 0.7 );
console . log ( `Found ${ pending . length } high-confidence patterns` );
Patterns are automatically sorted by confidence score (descending) so the best patterns appear first.
Next Steps
Skill Generation Learn how detected patterns become SKILL.md files
Session Analysis Understand session context and intent detection
Event Store See how tool events are captured and stored
Design Patterns Explore all 18 recognized design patterns