# HIS.js — Universal AI History & Action System

[![npm version](https://badge.fury.io/js/%40his-js%2Fcore.svg)](https://www.npmjs.com/package/@tarun923/his-js)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

**Deterministic, filesystem-based AI history, task, and action logger designed to work across all AI models.**

HIS.js is a universal logging system for AI-driven development that records every decision, action, and change made by AI models (ChatGPT, Claude, Gemini, local LLMs, etc.) in a structured, replayable format.

## 🎯 Core Philosophy

1. **No hidden state** – Everything the AI does is recorded
2. **Replayable actions** – Every change can be undone or replayed
3. **Small JSONs over big blobs** – Atomic, human-readable files
4. **Filesystem = Source of Truth** – No databases required
5. **Model-agnostic** – Works with any LLM
6. **Deterministic outputs** – Same input → same action plan
7. **Multi-model orchestration** – Compare and select best AI outputs
8. **Provider-agnostic adapters** – Works with OpenAI, Claude, Gemini, Ollama, custom APIs
9. **Local AI integration** – Built-in offline AI capabilities
10. **Advanced analytics** – Deep insights into AI performance and usage

## 📦 Installation

```bash
npm install @tarun923/his-js
```

## 🚀 Quick Start

```javascript
import HisJS from '@tarun923/his-js';

// Initialize
const his = new HisJS({
  projectRoot: process.cwd(),
  historyDir: '.his',  // optional, defaults to .his
});

await his.initialize();

// Start a session
const session = await his.startSession(
  'Add user authentication',
  'gpt-4',
  'openai'
);

// Record events
await his.recordEvent(
  'file_create',
  'src/auth.js',
  '+ export function login() { ... }',
  null,
  'hash-abc123'
);

// Create a task plan
const todo = await his.createTodo(
  'Implement authentication system',
  [
    'Create auth module',
    'Add login endpoint',
    'Add logout endpoint',
    'Write tests'
  ]
);

// Update task progress
await his.updateTodoStep(todo.task_id, 1, 'done');

// End session
await his.endSession('completed');
```

## 📁 Directory Structure

```
.his/
├── sessions/          # One folder per AI run
├── events/            # Atomic file edits & actions
├── todos/             # Multi-step task plans
├── summaries/         # Long-term compressed memory
├── cache/             # Temporary / discardable context
├── collaborations/    # Multi-AI collaboration logs
├── analytics/         # Analytics data and reports
├── backups/           # Backup and sync data
├── config.json        # Behavior & limits
└── index.json         # Global registry
```

## 📖 API Reference

### Constructor

```typescript
new HisJS(config: HisConfig)
```

**Config Options:**
- `projectRoot` (string, required) - Root directory of your project
- `historyDir` (string, optional) - History directory name, defaults to `.his`
- `maxCacheAge` (number, optional) - Cache TTL in milliseconds, defaults to 3600000 (1 hour)
- `autoCleanup` (boolean, optional) - Auto-clean expired cache, defaults to true

### Initialization

```typescript
await his.initialize(): Promise<void>
```

Creates the `.his/` directory structure and initializes index files.

### Session Management

```typescript
// Start a new session
await his.startSession(
  userIntent: string,
  model: string,
  provider: string,
  traceId?: string
): Promise<Session>

// Get current active session
his.getCurrentSession(): Session | null

// End current session
await his.endSession(status?: 'completed' | 'aborted'): Promise<void>

// Get session by ID
await his.getSession(sessionId: string): Promise<Session>

// List all sessions
await his.listSessions(): Promise<Session[]>

// Create high-level AI session with automatic history management
await his.createAISession(config: AISessionConfig): Promise<AISessionHandle>
```

### Event Recording

```typescript
// Record an event
await his.recordEvent(
  type: 'file_edit' | 'file_create' | 'file_delete' | 'command' | 'analysis' | 'message',
  target: string,
  diff: string,
  before?: string | null,
  after?: string | null,
  options?: {
    traceId?: string;
    spanId?: string;
    parentSpanId?: string | null;
    metadata?: Record<string, any>;
  }
): Promise<Event>

// Record chat messages (provider-agnostic)
await his.recordMessage(message: AIModelMessage): Promise<Event>

// Get event by ID
await his.getEvent(eventId: string): Promise<Event>

// List all events (optionally filter by session)
await his.listEvents(sessionId?: string): Promise<Event[]>

// List recorded messages
await his.listMessages(sessionId?: string): Promise<AIModelMessage[]>

// Get pruned message history with automatic summarization
await his.getPrunedHistory(maxTokens: number, options?: PruneHistoryOptions): Promise<AIModelMessage[]>

// Build trace trees for multi-agent workflows
await his.getTraceTree(traceId: string): Promise<TraceNode[]>

// File history and reconstruction
await his.getFileHistory(targetPath: string): Promise<Event[]>
await his.reconstructFileAt(targetPath: string, options?: {timestamp?: string, eventId?: string}): Promise<string | null>
```

### Task Management

```typescript
// Create a TODO task
await his.createTodo(goal: string, steps: string[]): Promise<Todo>

// Update task step status
await his.updateTodoStep(
  taskId: string,
  stepId: number,
  status: 'pending' | 'active' | 'done' | 'failed'
): Promise<void>

// Generate TODOs using any AI model adapter
await his.generateTodoWithModel(
  adapterName: string,
  goal: string,
  options?: { context?: any, call?: Partial<AIModelCall> }
): Promise<{ todo: Todo; aiResponse: AIModelResponse }>

// Get task by ID
await his.getTodo(taskId: string): Promise<Todo>

// List all tasks
await his.listTodos(): Promise<Todo[]>
```

### Summary Management

```typescript
// Update project summary
await his.updateSummary(summary: {
  project: string,
  architecture: string,
  decisions: string[]
}): Promise<void>

// Get current summary
await his.getSummary(): Promise<Summary | null>
```

### Cache Management

```typescript
// Set cache entry
await his.setCache(key: string, context: any, ttl?: number): Promise<void>

// Get cache entry
await his.getCache(key: string): Promise<any | null>

// Delete cache entry
await his.deleteCache(key: string): Promise<void>

// Clean expired cache entries
await his.cleanCache(): Promise<void>
```

## 🤖 Multi-Model Orchestration

### Generate Code with Multiple Models

```typescript
// Ask multiple models to generate code and automatically select the best
const result = await his.generateCodeWithMultipleModels({
  task: 'Create a REST API endpoint for user authentication',
  adapters: ['openai:gpt-4', 'anthropic:claude-3', 'google:gemini-pro'],
  context: { framework: 'express', database: 'postgresql' },
  evaluationAdapterName: 'gpt-4' // Optional evaluator
});

console.log('Best code:', result.best.response.content);
console.log('Selected from:', result.best.adapterName);
console.log('All candidates:', result.candidates.length);
```

### AI Session Workflow

```typescript
// High-level AI session with automatic history management
const session = await his.createAISession({
  userIntent: 'Build a complete CRUD application',
  adapters: ['openai:gpt-4', 'anthropic:claude-3'],
  evaluationAdapterName: 'gpt-4'
});

// Ask questions with automatic context pruning
const response = await session.ask(
  'How should I implement user authentication?',
  { maxTokens: 2048, temperature: 0.7 }
);

// Generate code with multiple models
const codeResult = await session.generateCode(
  'Create user login endpoint',
  { context: 'express.js with JWT' }
);

// Commit file changes with automatic snapshots
const { event, rollback } = await session.commitFileChange(
  'src/auth.js',
  async () => {
    // Your file modification logic here
    await writeFile('src/auth.js', newContent);
  }
);

// Rollback if needed
await rollback();
```

## 🔌 Provider-Agnostic Model Adapters

### Register Custom Adapters

```typescript
import { createHTTPAdapter } from '@tarun923/his-js';

// OpenAI Adapter
his.registerModelAdapter(createHTTPAdapter({
  name: 'openai:gpt-4',
  provider: 'openai',
  defaultModel: 'gpt-4',
  endpoint: 'https://api.openai.com/v1/chat/completions',
  headers: { 'Authorization': `Bearer ${process.env.OPENAI_API_KEY}` },
  buildRequestBody: (request) => ({
    model: request.model,
    messages: request.messages,
    max_tokens: request.maxTokens,
    temperature: request.temperature
  }),
  parseResponse: (json) => ({
    content: json.choices[0].message.content,
    tokens: {
      input: json.usage.prompt_tokens,
      output: json.usage.completion_tokens,
      total: json.usage.total_tokens
    }
  })
}));

// Ollama (Local) Adapter
his.registerModelAdapter(createHTTPAdapter({
  name: 'ollama:llama3',
  provider: 'ollama',
  defaultModel: 'llama3:8b',
  endpoint: 'http://localhost:11434/api/chat',
  buildRequestBody: (request) => ({
    model: request.model,
    messages: request.messages,
    stream: false
  }),
  parseResponse: (json) => ({
    content: json.message.content,
    model: json.model
  })
}));

// Custom API Adapter
his.registerModelAdapter(createHTTPAdapter({
  name: 'custom:api',
  provider: 'custom',
  endpoint: 'https://your-api.com/v1/generate',
  buildHeaders: (request) => ({ 'X-API-Key': getDynamicKey() }),
  buildRequestBody: (request) => ({ prompt: request.messages }),
  parseResponse: (json) => ({ content: json.output })
}));
```

### Use Any Model

```typescript
// Generate todos with any registered adapter
const { todo, aiResponse } = await his.generateTodoWithModel(
  'openai:gpt-4',
  'Build a React component library',
  { context: { typescript: true, storybook: true } }
);

// The same interface works for all providers
const claudeTodo = await his.generateTodoWithModel(
  'anthropic:claude-3',
  'Build a React component library',
  { context: { typescript: true, storybook: true } }
);
```

## 🧠 Local AI Integration

### Built-in Local AI

```typescript
// Zero configuration - uses built-in models
const his = new HisJS({
  projectRoot: process.cwd(),
  localAI: {
    enableCache: true
  }
});

await his.initialize();

// Generate todos instantly (no API calls)
const { todo } = await his.generateTodoWithAI(
  'Create a comprehensive testing strategy'
);

// Quick content analysis
const analysis = await his.analyzeWithAI(
  'function calculateTotal(items) { return items.reduce((a, b) => a + b.price, 0); }',
  { type: 'javascript function' }
);

// Get suggestions
const suggestions = await his.getSuggestionsWithAI(
  'The code is slow with large datasets'
);

// Generate summaries
const summary = await his.generateQuickSummary(
  'The project involves building a scalable e-commerce platform with microservices architecture'
);

// Check Local AI status
const status = his.getLocalAIStatus();
console.log('Local AI Ready:', status.isReady);
console.log('Cache size:', status.cacheStats?.size);
```

### Custom Local Models

```typescript
// Use your own GGUF models
const his = new HisJS({
  projectRoot: process.cwd(),
  localAI: {
    modelPath: './models/my-custom-model.gguf',
    tokenizerPath: './models/my-tokenizer.json',
    contextSize: 4096,
    maxTokens: 1024,
    temperature: 0.7,
    enableCache: true
  }
});

// Auto-download from Hugging Face
const hisWithDownload = new HisJS({
  projectRoot: process.cwd(),
  localAI: {
    autoDownload: true,
    repoUrl: 'https://huggingface.co/tarun923/his-js',
    enableCache: true
  }
});
```

## 📊 Advanced Analytics & Insights

### Comprehensive Analytics

```typescript
// Get detailed analytics with custom queries
const analytics = await his.getAnalytics({
  timeRange: '30d',
  metrics: [
    'session_count',
    'task_completion_rate', 
    'productivity_score',
    'cost_analysis',
    'error_rate',
    'model_usage'
  ],
  models: ['gpt-4', 'claude-sonnet'],
  groupBy: 'model'
});

console.log('Top performing model:', analytics.summary.topModel);
console.log('Insights:', analytics.insights);
console.log('Recommendations:', analytics.recommendations);

// Cost breakdown
const costs = await his.getCostBreakdown('monthly');
console.log('Monthly cost: $', costs.totalCost);
console.log('By model:', costs.byModel);
console.log('Projected next month: $', costs.projections.nextMonth);
```

### Pattern Detection

```typescript
// Detect patterns in AI behavior
const errorPatterns = await his.detectPatterns({
  type: 'repeated_errors',
  threshold: 3,
  confidence: 0.8
});

errorPatterns.forEach(pattern => {
  console.log(`Pattern: ${pattern.description}`);
  console.log(`Frequency: ${pattern.frequency}`);
  console.log(`Recommendations: ${pattern.recommendations.join(', ')}`);
});

// Model preference analysis
const preferences = await his.detectPatterns({
  type: 'model_preferences',
  threshold: 0.7
});
```

### Model Performance Comparison

```typescript
// Compare different AI models
const performance = await his.compareModels({
  models: ['gpt-4', 'claude-sonnet', 'gemini-pro'],
  tasks: ['code_generation', 'debugging', 'refactoring'],
  timeRange: '90d'
});

performance.forEach(model => {
  console.log(`${model.model}:`);
  console.log(`  Success Rate: ${model.metrics.successRate}`);
  console.log(`  Cost per Task: $${model.metrics.costPerTask}`);
  console.log(`  Rank: #${model.comparison.rank}`);
  console.log(`  Better than: ${model.comparison.betterThan.join(', ')}`);
});
```

### Dashboard Overview

```typescript
// Combined cost & quality snapshot for dashboards
const overview = await his.getCostAndQualityOverview();
console.log('Total cost (30d): $', overview.cost.totalCost);
console.log('Top 3 models:', overview.topModels.slice(0, 3));
console.log('Recent patterns:', overview.recentPatterns.length);

// Model usage overview
const usage = await his.getModelUsageOverview();
console.log('Total sessions:', usage.totalSessions);
console.log('By model:', usage.byModel);
console.log('By provider:', usage.byProvider);
```

## 🔌 Plugin System

### Create Custom Plugins

```typescript
class CodeQualityPlugin implements HisPlugin {
  name = 'code-quality';
  version = '1.0.0';
  description = 'Analyzes code quality in real-time';
  author = 'Your Name';
  
  async initialize(his: HisJS) {
    console.log('Code quality plugin initialized');
  }
  
  async onEvent(event: Event) {
    if (event.type === 'file_edit') {
      const quality = this.analyzeCodeQuality(event.diff);
      if (quality.score < 0.7) {
        console.log(`Low quality detected in ${event.target}: ${quality.score}`);
      }
    }
  }
  
  async validateEvent(event: Event): Promise<boolean> {
    // Custom validation logic
    return event.diff.length > 0;
  }
  
  private analyzeCodeQuality(diff: string) {
    // Simple quality analysis
    const hasTests = /test|spec/i.test(diff);
    const hasComments = /\/\/|\/\*/.test(diff);
    const complexity = diff.split('\n').length;
    
    return {
      score: (hasTests ? 0.3 : 0) + (hasComments ? 0.2 : 0) + Math.min(0.5, 10 / complexity),
      hasTests,
      hasComments,
      complexity
    };
  }
}

// Load plugins
await his.use(new CodeQualityPlugin());
await his.use(new SecurityPlugin());
await his.use(new PerformancePlugin());

// List active plugins
const plugins = his.listPlugins();
console.log('Active plugins:', plugins.map(p => p.name));
```

### Plugin Hooks

```typescript
class AnalyticsPlugin implements HisPlugin {
  name = 'analytics';
  version = '1.0.0';
  
  async onAnalyticsQuery(query: AnalyticsQuery): Promise<AnalyticsQuery> {
    // Modify queries before execution
    if (!query.models.includes('gpt-4')) {
      query.models.push('gpt-4');
    }
    return query;
  }
  
  async onAnalyticsResult(result: AnalyticsResult): Promise<AnalyticsResult> {
    // Enhance results with custom insights
    result.insights.push('Custom insight from plugin');
    return result;
  }
  
  async onSessionStart(session: Session) {
    console.log(`Session started: ${session.session_id}`);
  }
  
  async onSessionEnd(session: Session) {
    console.log(`Session ended: ${session.session_id} (${session.status})`);
  }
}
```

## 🔄 Replay & Analysis

```typescript
// Replay all events from a session
await his.replaySession(sessionId: string): Promise<Event[]>

// Get complete session timeline
await his.getSessionTimeline(sessionId: string): Promise<{
  session: Session,
  events: Event[],
  todos: Todo[]
}>

// Get timeline with filters
const timeline = await his.getTimeline({
  sessionId: 'session-123',
  traceId: 'trace-456'
});

// Dashboard overview
const overview = await his.getTimeline({
  // No filters = everything
});
```

## 🎯 Feedback & Evaluation

### Structured Feedback System

```typescript
// Add feedback to any event
await his.addFeedbackToEvent(eventId, {
  rating: 3, // 1-5 scale
  comment: 'The AI missed the requirement for error handling',
  userCorrectedText: 'Added try-catch blocks around async operations',
  tags: ['error-handling', 'async', 'improvement-needed']
});

// List events with feedback
const lowRatedEvents = await his.listEventsWithFeedback({
  maxRating: 2 // Only get poorly rated events
});

const highRatedEvents = await his.listEventsWithFeedback({
  minRating: 4
});

// Export low-rated interactions for analysis
lowRatedEvents.forEach(event => {
  console.log(`Event ${event.event_id}: ${event.feedback?.comment}`);
  console.log(`User correction: ${event.feedback?.userCorrectedText}`);
});
```

## 🌍 Environment Variables (HNV)

### Simple Environment Management

```typescript
import { hnv } from '@tarun923/his-js';

// Load environment variables with validation
const { env, missing } = await hnv.load({
  projectRoot: process.cwd(),
  fileName: '.env',
  required: ['OPENAI_API_KEY', 'DATABASE_URL'],
  defaults: {
    NODE_ENV: 'development',
    PORT: '3000'
  },
  overrideExisting: false // process.env takes precedence
});

if (missing.length > 0) {
  console.error('Missing required environment variables:', missing);
  process.exit(1);
}

// Use environment variables
const his = new HisJS({
  projectRoot: process.cwd(),
  localAI: {
    modelUrl: env.AI_MODEL_URL,
    enableCache: env.ENABLE_AI_CACHE === 'true'
  }
});
```

## 📸 File Snapshots & Rollback

### Automatic File Change Tracking

```typescript
// Record file changes with automatic snapshots
const { event, rollback } = await his.recordFileActionWithSnapshot(
  'file_edit',
  'src/components/UserProfile.tsx',
  async () => {
    // Your file modification logic
    const newContent = await generateComponent();
    await fs.writeFile('src/components/UserProfile.tsx', newContent);
  },
  {
    traceId: 'trace-123',
    metadata: { reason: 'feature-add', component: 'UserProfile' }
  }
);

console.log('File change recorded:', event.event_id);

// Rollback if needed
await rollback();
console.log('File rolled back to previous state');

// File history analysis
const history = await his.getFileHistory('src/components/UserProfile.tsx');
console.log(`File has ${history.length} recorded changes`);

// Reconstruct file at specific point in time
const fileAtTime = await his.reconstructFileAt(
  'src/components/UserProfile.tsx',
  { timestamp: '2024-01-15T10:30:00Z' }
);

const fileAtEvent = await his.reconstructFileAt(
  'src/components/UserProfile.tsx',
  { eventId: 'event-123' }
);
```

## 📡 Event System

### Real-time Event Monitoring

```typescript
// Listen to all HIS.js events
his.on('session_started', (data) => {
  console.log(`Session ${data.session_id} started with ${data.model}`);
});

his.on('event_recorded', (data) => {
  console.log(`AI ${data.type}: ${data.target}`);
  
  // Trigger real-time notifications
  if (data.type === 'file_edit') {
    notifyTeam(`File modified: ${data.target}`);
  }
});

his.on('collaboration_started', (data) => {
  console.log(`Multi-AI collaboration ${data.collaboration_id} started`);
});

his.on('plugin_added', (data) => {
  console.log(`Plugin ${data.name} v${data.version} loaded`);
});

his.on('message_sent', (data) => {
  console.log(`${data.from} → ${data.to}: ${data.content}`);
});

// Custom event handling
his.on('analysis', (data) => {
  if (data.metadata?.tokens) {
    updateTokenUsage(data.metadata.tokens);
  }
});
```

## 🔧 Use Cases

### 1. AI Code Editor Integration

```javascript
// In your Electron app
import HisJS from '@tarun923/his-js';

const his = new HisJS({ projectRoot: workspace.path });
await his.initialize();

// Before AI makes changes
const session = await his.startSession(
  userPrompt,
  'claude-sonnet-4',
  'anthropic'
);

// Track each AI action
for (const change of aiChanges) {
  await his.recordEvent(
    'file_edit',
    change.file,
    change.diff,
    change.beforeHash,
    change.afterHash
  );
}

await his.endSession('completed');
```

### 2. Advanced Analytics & Insights

```javascript
// Get comprehensive analytics
const analytics = await his.getAnalytics({
  timeRange: '30d',
  metrics: ['productivity_score', 'error_rate', 'cost_analysis'],
  models: ['gpt-4', 'claude-sonnet'],
  groupBy: 'model'
});

console.log('Top performing model:', analytics.summary.topModel);
console.log('Insights:', analytics.insights);
console.log('Recommendations:', analytics.recommendations);

// Detect patterns in AI behavior
const patterns = await his.detectPatterns({
  type: 'repeated_errors',
  threshold: 3,
  confidence: 0.8
});

patterns.forEach(pattern => {
  console.log(`Pattern: ${pattern.description}`);
  console.log(`Recommendations: ${pattern.recommendations.join(', ')}`);
});
```

### 3. AI Model Performance Comparison

```javascript
// Compare different AI models
const performance = await his.compareModels({
  models: ['gpt-4', 'claude-sonnet', 'gemini-pro'],
  tasks: ['code_generation', 'debugging', 'refactoring'],
  timeRange: '90d'
});

performance.forEach(model => {
  console.log(`${model.model}:`);
  console.log(`  Success Rate: ${model.metrics.successRate}`);
  console.log(`  Cost per Task: $${model.metrics.costPerTask}`);
  console.log(`  Rank: #${model.comparison.rank}`);
});

// Cost analysis
const costs = await his.getCostBreakdown('monthly');
console.log(`Monthly cost: $${costs.totalCost}`);
console.log('By model:', costs.byModel);
```

### 4. Real-time Multi-AI Collaboration

```javascript
// Start collaboration between multiple AI models
const collaboration = await his.startCollaboration([
  {
    model: 'gpt-4',
    provider: 'openai',
    role: 'architect',
    capabilities: ['system_design', 'architecture']
  },
  {
    model: 'claude-sonnet',
    provider: 'anthropic',
    role: 'implementer',
    capabilities: ['coding', 'debugging']
  }
]);

// AI models can communicate
await his.sendMessageToCollaboration(
  collaboration.collaboration_id,
  'gpt-4',
  'claude-sonnet',
  'Please implement the authentication system based on the architecture',
  'task_assignment'
);

// Monitor collaboration events
his.on('message_sent', (message) => {
  console.log(`${message.from} → ${message.to}: ${message.content}`);
});
```

### 5. Plugin System & Extensibility

```javascript
// Create custom plugins
class CodeQualityPlugin extends HisPlugin {
  name = 'code-quality';
  version = '1.0.0';
  
  async initialize(his) {
    console.log('Code quality plugin initialized');
  }
  
  async onEvent(event) {
    if (event.type === 'file_edit') {
      const quality = this.analyzeCodeQuality(event.diff);
      if (quality.score < 0.7) {
        console.log(`Low quality detected in ${event.target}`);
      }
    }
  }
}

// Load plugins
await his.use(new CodeQualityPlugin());
await his.use(new SecurityPlugin());
await his.use(new PerformancePlugin());

// List all plugins
console.log('Active plugins:', his.listPlugins().map(p => p.name));
```

### 6. Visual Timeline & Diff Viewer

```javascript
// Create interactive timeline
const timeline = his.createTimeline({
  view: 'gantt',
  filters: { models: ['gpt-4'], dateRange: { start: '2024-01-01', end: '2024-01-31' } },
  grouping: 'day',
  layout: { width: 1200, height: 600, theme: 'dark' }
});

// Render timeline (integrates with visualization libraries)
document.body.appendChild(timeline.render());

// Show diff viewer
const diffViewer = his.showDiff(session.session_id, {
  format: 'side-by-side',
  syntax: true,
  lineNumbers: true,
  context: 3
});
```

### 7. Event-Driven Architecture

```javascript
// Set up event listeners
his.on('session_started', (data) => {
  console.log(`Session ${data.session_id} started with ${data.model}`);
});

his.on('event_recorded', (data) => {
  // Trigger real-time notifications
  notifyTeam(`AI ${data.type}: ${data.target}`);
});

his.on('collaboration_started', (data) => {
  console.log(`Multi-AI collaboration ${data.collaboration_id} started`);
});

his.on('plugin_added', (data) => {
  console.log(`Plugin ${data.name} v${data.version} loaded`);
});
```

### 8. Debugging AI Behavior

```javascript
// List all sessions
const sessions = await his.listSessions();

// Get timeline of specific session
const timeline = await his.getSessionTimeline(sessions[0].session_id);

console.log('What the AI did:', timeline.events);
console.log('What it planned:', timeline.todos);

// Analyze patterns across sessions
const errorPatterns = await his.detectPatterns({
  type: 'repeated_errors',
  threshold: 2
});

errorPatterns.forEach(pattern => {
  console.log(`Repeated error: ${pattern.description}`);
  console.log(`Examples:`, pattern.examples);
});
```

### 9. Rollback AI Changes

```javascript
// Get events from problematic session
const events = await his.replaySession(problemSessionId);

// Reverse apply diffs
for (const event of events.reverse()) {
  if (event.type === 'file_edit') {
    // Apply reverse diff
    applyPatch(event.target, reverseDiff(event.diff));
  }
}
```

### 10. Enterprise Analytics Dashboard

```javascript
// Get comprehensive analytics for team
const teamAnalytics = await his.getAnalytics({
  timeRange: '90d',
  metrics: [
    'session_count',
    'task_completion_rate', 
    'productivity_score',
    'cost_analysis',
    'error_rate'
  ],
  models: ['gpt-4', 'claude-sonnet', 'gemini-pro'],
  groupBy: 'provider'
});

// Generate insights for management
const insights = {
  topPerformingModel: analytics.summary.topModel,
  costEfficiency: analytics.summary.totalCost / analytics.summary.totalSessions,
  productivityTrend: analytics.data.map(d => d.metrics.productivity_score),
  recommendations: analytics.recommendations
};

// Export for dashboard
exportToDashboard(insights);
```

### 11. Local AI Integration (Hugging Face Clone)

```javascript
// Clone models from Hugging Face repository (recommended)
const his = new HisJS({
  projectRoot: process.cwd(),
  localAI: {
    autoDownload: true,
    repoUrl: 'https://huggingface.co/tarun923/his-js',  // Your Hugging Face repo
    enableCache: true
  }
});

await his.initialize(); // Clones repository automatically if models missing

// AI-powered todo generation (instant, no API calls)
const { todo } = await his.generateTodoWithAI(
  'Build a comprehensive authentication system'
);

console.log('Generated steps:', todo.steps.map((s, i) => `${i + 1}. ${s.action}`));

// Clone from any git repository
const hisWithCustomRepo = new HisJS({
  projectRoot: process.cwd(),
  localAI: {
    autoDownload: true,
    repoUrl: 'https://github.com/yourusername/ai-models',  // Any git repo
    enableCache: true
  }
});

// Or use your own models directly
const hisWithLocalModels = new HisJS({
  projectRoot: process.cwd(),
  localAI: {
    modelPath: './models/my-custom-model.gguf',     // Your local model
    tokenizerPath: './models/my-tokenizer.json',   // Your tokenizer
    contextSize: 2048,
    maxTokens: 512,
    temperature: 0.7,
    enableCache: true
  }
});
```

## 🎨 TypeScript Support

Full TypeScript definitions included:

```typescript
import HisJS, { Session, Event, Todo, Summary } from '@tarun923/his-js';

const his: HisJS = new HisJS({ projectRoot: __dirname });
const session: Session = await his.startSession(...);
```

## 🔒 Security Notes

- **Never store API keys or secrets** in HIS files
- The `.his/` directory should be added to `.gitignore` for private projects
- Event diffs may contain sensitive code - review before sharing

## 🧪 Testing

```bash
npm test
```

## 🤝 Contributing

Contributions welcome! Please read our contributing guidelines.

## 📄 License

MIT © 2024

## 🌟 Why HIS.js?

Traditional version control (Git) tracks *what* changed. HIS.js tracks *why* an AI changed it, *what it planned*, and *how it executed* the plan. This makes AI-driven development:

- **Debuggable** - Understand AI decision-making
- **Auditable** - Review every AI action
- **Reversible** - Rollback problematic changes
- **Reproducible** - Replay AI sessions
- **Model-agnostic** - Works with any LLM

## 🔗 Links

- [Documentation](https://github.com/yourusername/his-js#readme)
- [Issue Tracker](https://github.com/yourusername/his-js/issues)
- [NPM Package](https://www.npmjs.com/package/@tarun923/his-js)

## 🙏 Acknowledgments

Built for the AI-native development era.
