Skip to main content

createEventStore

SQLite persistence layer for tool usage events. Provides storage, querying, and analysis capabilities for pattern detection.

Function Signature

function createEventStore(dbPath?: string): EventStore
Source: src/core/event-store.ts:345

Parameters

dbPath
string
default:"~/.claude/auto-skill/index.db"
Path to SQLite database file. Defaults to the Auto-Skill index database in the Claude config directory.

Return Value

Returns an EventStore instance with storage and query methods.

ToolEvent Type

id
string
Unique event identifier (ULID).
sessionId
string
Session identifier grouping related events.
projectPath
string
Absolute path to the project workspace.
toolName
string
Name of the tool invoked (e.g. "Read", "Edit", "Bash").
toolInput
Record<string, unknown>
JSON object containing tool parameters (file paths, commands, search patterns, etc.).
toolResponse
string | null
Tool output, truncated to 1000 chars to save space. null if no response.
success
boolean
Whether the tool invocation succeeded.
timestamp
string
ISO-8601 timestamp of the event.
agentId
string | undefined
Optional identifier for the coding agent (e.g. "claude-code", "cursor").
Source: src/types/index.ts:14-24

Methods

recordEvent

Records a single tool usage event to the database.
sessionId
string
required
Session identifier for grouping related events.
projectPath
string
required
Absolute path to the project workspace.
toolName
string
required
Name of the tool invoked.
toolInput
Record<string, unknown>
required
Tool parameters as a JSON object.
toolResponse
string | null
Tool output (truncated to 1000 chars). Defaults to null.
success
boolean
default:true
Whether the tool invocation succeeded.
agentId
string
Optional agent identifier.
Returns: ToolEvent - The recorded event with generated ID and timestamp. Source: src/core/event-store.ts:103

getSessionEvents

Retrieves all events for a specific session, ordered chronologically.
sessionId
string
required
Session identifier.
Returns: ToolEvent[] - Ordered list of events in the session. Source: src/core/event-store.ts:151

getToolSequences

Extracts tool name sequences grouped by session for pattern detection.
projectPath
string
Filter to specific project. undefined returns all projects.
lookbackDays
number
default:7
How many days of history to include.
minSequenceLength
number
default:2
Minimum number of tools in a sequence. Sessions with fewer tools are excluded.
Returns: string[][] - List of tool name sequences, one per session. Example return:
[
  ["Read", "Edit", "Bash"],
  ["Grep", "Read", "Write"],
  ["Read", "Edit", "Bash"],
]
Source: src/core/event-store.ts:171

getEventsWithInputs

Retrieves full events (including tool inputs) grouped by session.
projectPath
string
Filter to specific project. undefined returns all projects.
lookbackDays
number
default:7
How many days of history to include.
Returns: ToolEvent[][] - Array of session event arrays with complete metadata. Useful for sophisticated pattern matching that considers tool parameters, not just tool names. Source: src/core/event-store.ts:227

getStats

Calculates summary statistics about stored events. Returns: EventStoreStats object:
totalEvents
number
Total number of recorded events.
uniqueSessions
number
Count of distinct sessions.
uniqueProjects
number
Count of distinct project paths.
topTools
Array<{tool: string, count: number}>
Top 10 most-used tools with usage counts.
Source: src/core/event-store.ts:279

cleanupOldEvents

Deletes events older than the specified retention period.
days
number
default:30
Number of days to keep. Events older than this are deleted.
Returns: number - Count of deleted events. Source: src/core/event-store.ts:322

close

Closes the database connection. Source: src/core/event-store.ts:337

Database Schema

The event store uses a single SQLite table:
CREATE TABLE events (
  id TEXT PRIMARY KEY,
  session_id TEXT NOT NULL,
  project_path TEXT NOT NULL,
  tool_name TEXT NOT NULL,
  tool_input TEXT NOT NULL,  -- JSON
  tool_response TEXT,
  success INTEGER NOT NULL,  -- 0 or 1
  timestamp TEXT NOT NULL,   -- ISO-8601
  agent_id TEXT
)
Indexes:
  • idx_session_id on session_id
  • idx_project_path on project_path
  • idx_timestamp on timestamp
  • idx_tool_name on tool_name
Source: src/core/event-store.ts:70-95

Usage Example

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

// Initialize store
const store = createEventStore();

// Record events during a coding session
const sessionId = "session-123";
const projectPath = "/Users/dev/my-project";

store.recordEvent(
  sessionId,
  projectPath,
  "Read",
  { filePath: "/Users/dev/my-project/src/main.ts" },
  "export function main() {...}",
  true,
  "claude-code"
);

store.recordEvent(
  sessionId,
  projectPath,
  "Edit",
  {
    filePath: "/Users/dev/my-project/src/main.ts",
    oldString: "console.log",
    newString: "logger.info"
  },
  null,
  true
);

store.recordEvent(
  sessionId,
  projectPath,
  "Bash",
  { command: "npm test" },
  "PASS  src/main.test.ts\n✓ main function works",
  true
);

// Query events
const sessionEvents = store.getSessionEvents(sessionId);
console.log(`Session has ${sessionEvents.length} events`);

// Get tool sequences for pattern detection
const sequences = store.getToolSequences(undefined, 7, 2);
console.log(`Found ${sequences.length} sessions`);
console.log(`Example: ${sequences[0].join(" → ")}`);

// Get full events with inputs
const fullSessions = store.getEventsWithInputs(projectPath, 7);
console.log(`Loaded ${fullSessions.length} sessions with full context`);

// Statistics
const stats = store.getStats();
console.log(`\nDatabase Statistics:`);
console.log(`Total events: ${stats.totalEvents}`);
console.log(`Unique sessions: ${stats.uniqueSessions}`);
console.log(`Unique projects: ${stats.uniqueProjects}`);
console.log(`\nTop tools:`);
stats.topTools.slice(0, 5).forEach(({ tool, count }) => {
  console.log(`  ${tool}: ${count} times`);
});

// Cleanup old data (30+ days)
const deleted = store.cleanupOldEvents(30);
console.log(`\nDeleted ${deleted} old events`);

// Close connection
store.close();

Hybrid Storage Model

The event store uses a global database with project tagging:
  • Single database: All events stored in ~/.claude/auto-skill/index.db
  • Project filtering: Each event tagged with project_path
  • Session grouping: Events grouped by session_id for pattern analysis
This hybrid approach allows:
  • Cross-project pattern detection (learning from all projects)
  • Project-specific analysis (filter by project_path)
  • Efficient storage (single database, indexed queries)
Source: src/core/event-store.ts:1-13

Response Truncation

Tool responses are truncated to 1000 characters to save storage space:
"Very long output...[truncated]"
Full responses are typically not needed for pattern detection, which focuses on tool sequences and success rates. Source: src/core/event-store.ts:20-32

See Also

Build docs developers (and LLMs) love