Skip to main content

createSessionAnalyzer

Analyzes complete coding session history to understand user intent, decision-making patterns, problem-solving strategies, and learning patterns.

Function Signature

function createSessionAnalyzer(): {
  analyzeSession(
    sessionId: string,
    events: ToolEvent[],
    conversationLog?: string
  ): SessionContext;
  
  detectProblemSolvingPatterns(
    sessions: Array<{ sessionId: string; events: ToolEvent[] }>
  ): ProblemSolvingPattern[];
}
Source: src/core/session-analyzer.ts:105

Return Value

Returns an object with session analysis methods.

Methods

analyzeSession

Analyzes a complete session with full context extraction.
sessionId
string
required
Session identifier.
events
ToolEvent[]
required
Ordered list of tool events from the session.
conversationLog
string
Optional full conversation transcript for deeper intent analysis.
Returns: SessionContext - Rich analysis including intent, domains, workflow type, and success metrics. Analysis pipeline:
  1. Parse conversation turns (grouped by 60-second gaps)
  2. Detect primary user intent via keyword scoring
  3. Extract problem domains from file paths
  4. Detect workflow type from tool sequences
  5. Calculate success indicators (tool success rate, duration)
Source: src/core/session-analyzer.ts:302

detectProblemSolvingPatterns

Detects high-level problem-solving patterns across multiple sessions.
sessions
Array<{sessionId: string, events: ToolEvent[]}>
required
Array of session data with events.
Returns: ProblemSolvingPattern[] - List of detected patterns sorted by success rate descending. Detection logic:
  1. Analyze each session individually
  2. Group sessions by workflow type
  3. Calculate success rates per workflow
  4. Extract common domains and intents
  5. Create patterns for groups with 2+ occurrences
Source: src/core/session-analyzer.ts:340

SessionContext Type

sessionId
string
Session identifier.
startTime
string
ISO-8601 timestamp of first event.
endTime
string
ISO-8601 timestamp of last event.
projectPath
string
Absolute path to the project workspace.
turns
ConversationTurn[]
Array of conversation turns (user messages + agent responses + tools used).
primaryIntent
string | null
Detected user intent: "debug", "implement", "refactor", "test", "explore", or "document".
problemDomains
string[]
List of problem domains extracted from file paths (e.g. ["src", "tests", "api"]).
workflowType
string | null
Detected workflow pattern: "TDD", "Debug-Systematic", "Refactor-Safe", or "Explore-Then-Implement".
successIndicators
Record<string, unknown>
Success metrics:
  • tool_success_rate: Ratio of successful tool invocations (0.0 to 1.0)
  • total_tools_used: Count of tools invoked
  • session_duration_minutes: Session duration in minutes
keyDecisions
string[]
Important decisions made during the session (future enhancement).
Source: src/types/index.ts:81-92

ConversationTurn Type

sessionId
string
Session identifier.
timestamp
string
ISO-8601 timestamp of the turn.
userMessage
string | null
User’s message (null if not available).
claudeResponse
string | null
Agent’s response (null if not available).
toolsUsed
string[]
List of tools invoked during this turn.
intentCategory
string | null
Categorized intent for this turn.
problemDomain
string | null
Problem domain for this turn.
outcome
string | null
Outcome of this turn (success/failure).
Source: src/types/index.ts:69-78

ProblemSolvingPattern Type

patternId
string
Unique pattern identifier (e.g. "ps-TDD").
patternType
string
Workflow type (e.g. "TDD", "Debug-Systematic").
description
string
Plain language description of the pattern.
workflowSteps
string[]
Generic workflow steps (e.g. ["Analyze problem", "Plan approach", "Implement", "Verify"]).
successRate
number
Success rate across sessions using this pattern (0.0 to 1.0).
occurrenceCount
number
Number of sessions matching this pattern.
exampleSessions
string[]
Sample session IDs (up to 3).
contextualIndicators
Record<string, unknown>
Context metadata:
  • primary_intents: List of primary intents across sessions
  • common_domains: Top 3 problem domains
Source: src/types/index.ts:95-104

Intent Detection

Intent is detected via keyword scoring across conversation turns:

Intent Keywords

debug: bug, error, fix, issue, problem, not working, broken implement: create, add, implement, build, make, new feature refactor: refactor, clean up, reorganize, improve, optimize test: test, TDD, unit test, testing, coverage explore: understand, explain, how does, what is, show me document: document, comment, README, docs, documentation Scoring algorithm:
  1. Scan all user messages for keywords
  2. Increment intent score for each keyword match
  3. Return intent with highest score, or null if no matches
Source: src/core/session-analyzer.ts:21-28, 174

Workflow Detection

Workflow types are detected by matching tool sequences against known patterns:

Workflow Patterns

TDD: ["Write", "Bash", "Edit", "Bash"]
  • Keywords: test, TDD, red-green-refactor
Debug-Systematic: ["Read", "Grep", "Bash", "Edit"]
  • Keywords: error, bug, debug, fix
Refactor-Safe: ["Read", "Edit", "Bash"]
  • Keywords: refactor, improve, clean
Explore-Then-Implement: ["Grep", "Read", "Write"]
  • Keywords: understand, then, create
Source: src/core/session-analyzer.ts:31-51, 237

Usage Example

import { createSessionAnalyzer } from "./core/session-analyzer";
import { createEventStore } from "./core/event-store";

// Initialize analyzer
const analyzer = createSessionAnalyzer();
const store = createEventStore();

// Analyze a single session
const sessionId = "session-123";
const events = store.getSessionEvents(sessionId);

const context = analyzer.analyzeSession(sessionId, events);

console.log(`\nSession Analysis: ${sessionId}`);
console.log(`Duration: ${context.endTime} - ${context.startTime}`);
console.log(`Primary intent: ${context.primaryIntent}`);
console.log(`Workflow type: ${context.workflowType}`);
console.log(`Problem domains: ${context.problemDomains.join(", ")}`);
console.log(`\nSuccess Metrics:`);
console.log(`  Tool success rate: ${(context.successIndicators.tool_success_rate * 100).toFixed(1)}%`);
console.log(`  Total tools used: ${context.successIndicators.total_tools_used}`);
console.log(`  Session duration: ${context.successIndicators.session_duration_minutes.toFixed(1)} minutes`);
console.log(`\nConversation turns: ${context.turns.length}`);

// Detect patterns across multiple sessions
const sessions = store.getEventsWithInputs(undefined, 30)
  .map((events, i) => ({
    sessionId: events[0]?.sessionId ?? `session-${i}`,
    events,
  }));

const patterns = analyzer.detectProblemSolvingPatterns(sessions);

console.log(`\n\nDetected ${patterns.length} problem-solving patterns:\n`);

for (const pattern of patterns) {
  console.log(`${pattern.patternType} (${pattern.occurrenceCount} sessions)`);
  console.log(`  Success rate: ${(pattern.successRate * 100).toFixed(1)}%`);
  console.log(`  Description: ${pattern.description}`);
  console.log(`  Primary intents: ${pattern.contextualIndicators.primary_intents.join(", ")}`);
  console.log(`  Common domains: ${pattern.contextualIndicators.common_domains.join(", ")}`);
  console.log(`  Example sessions: ${pattern.exampleSessions.slice(0, 2).join(", ")}`);
  console.log();
}

Problem Domain Extraction

Domains are extracted from file paths in tool inputs:
// Input: /Users/dev/project/src/api/routes.ts
// Domain: "api"

// Input: /Users/dev/project/tests/unit/auth.test.ts
// Domain: "unit"
Algorithm:
  1. Extract path or file_path from tool inputs
  2. Split path by / or \\
  3. Take parent directory name (second-to-last component)
  4. Return up to 5 unique domains
Source: src/core/session-analyzer.ts:210

Conversation Turn Grouping

Events are grouped into turns based on 60-second time gaps:
// Events with < 60 seconds between them = same turn
Event 1: 14:30:00 (Read)
Event 2: 14:30:15 (Edit)   ← Same turn
Event 3: 14:30:45 (Bash)   ← Same turn

// Gap > 60 seconds = new turn
Event 4: 14:32:00 (Grep)   ← New turn
This grouping helps identify discrete problem-solving steps within a session. Source: src/core/session-analyzer.ts:119

Success Rate Calculation

Success indicators are calculated from event metadata: Tool Success Rate:
successfulTools / totalTools
Session Duration:
(lastEventTimestamp - firstEventTimestamp) / 60000  // milliseconds to minutes
Source: src/core/session-analyzer.ts:255

See Also

Build docs developers (and LLMs) love