npm package: @meldscience/context-manager
Description: Context management system for AI agents
Latest version: 0.1.0

# @meldscience/context-manager

Context management system for AI agents, optimized for small-scale use with Claude. Maintains relevant context across conversations through priority-based selection and tag organization.

## Important Note on Scale

This module is designed for small-scale use (single human user with multiple Claude agents) and optimizes for reliability and user experience rather than performance or scale.

Intended Scale:
- Single human user
- Small number of Claude agents
- Modest database size
- Non-critical response times

## Installation

```bash
npm install @meldscience/context-manager
```

### Prerequisites
- Node.js 16+
- PostgreSQL 12+

## Quick Start

1. Set up your database:
```bash
# Create the database
createdb my_context_db

# Set environment variable
export DATABASE_URL="postgresql://user:password@localhost:5432/my_context_db"
```

2. Initialize the context manager:
```typescript
import { createContextManager } from '@meldscience/context-manager';

const manager = await createContextManager({
  database: {
    url: process.env.DATABASE_URL
  },
  selection: {
    maxEntries: 50,
    minPriority: 3
  },
  priority: {
    baseWeight: 0.6,
    userWeight: 0.4
  }
});
```

3. Basic usage:
```typescript
// Add context
const contextId = await manager.addContext('Important architectural decision', {
  tags: ['architecture', 'decision'],
  priority: 4
});

// Update priority
await manager.updatePriority({
  contextId,
  userId: 'user1',
  priority: 5
});

// Get active context
const context = await manager.getActiveContext({
  minPriority: 3,
  tags: ['architecture']
});
```

## Core Features

### Priority Management
- Priority scale: 1-5
- User priority signals
- Automatic priority calculation
- Priority-based selection

### Tag Organization
- Group related context
- Filter by tags
- Tag-based retrieval
- Automatic tag maintenance

### Context Selection
- Priority-based filtering
- Tag-based filtering
- Recency consideration
- Automatic pruning

## Integration Examples

### Discord Bot Integration
```typescript
import { DiscordBot } from 'discord.js';
import { createContextManager } from '@meldscience/context-manager';

const bot = new DiscordBot();
const manager = await createContextManager(config);

// Store message as context
bot.on('messageCreate', async (message) => {
  if (message.author.bot) return;
  
  await manager.addContext(message.content, {
    tags: ['discord', message.channel.name],
    metadata: {
      channelId: message.channel.id,
      authorId: message.author.id
    }
  });
});

// Handle priority reactions
bot.on('messageReactionAdd', async (reaction, user) => {
  const priority = getPriorityFromEmoji(reaction.emoji);
  if (priority) {
    await manager.updatePriority({
      contextId: reaction.message.id,
      userId: user.id,
      priority
    });
  }
});
```

### Claude Integration
```typescript
import { Claude } from '@anthropic-ai/sdk';
import { createContextManager } from '@meldscience/context-manager';

const claude = new Claude();
const manager = await createContextManager(config);

async function getResponse(prompt: string) {
  // Get relevant context
  const context = await manager.getActiveContext({
    minPriority: 3,
    tags: ['architecture', 'decisions']
  });
  
  // Format context for Claude
  const contextString = formatContextForClaude(context);
  
  // Get response
  const response = await claude.complete({
    prompt: contextString + prompt
  });
  
  // Store response as context
  await manager.addContext(response, {
    tags: ['claude-response'],
    metadata: { prompt }
  });
  
  return response;
}
```

## Event System

Subscribe to system events:
```typescript
// Priority updates
manager.on('priorityUpdated', (event) => {
  console.log(`Priority changed for ${event.contextId}`);
});

// Selection changes
manager.on('selectionUpdated', (event) => {
  console.log('Active context changed');
});
```

## Configuration

```typescript
interface ContextManagerConfig {
  // Database settings
  database: {
    url: string;
    poolSize?: number;
  };
  
  // Selection settings
  selection: {
    maxEntries: number;
    minPriority?: number;
    maxAgeHours?: number;
  };
  
  // Priority settings
  priority: {
    baseWeight: number;
    userWeight: number;
  };
}
```

## Error Handling

```typescript
import { ContextManagerError } from '@meldscience/context-manager';

try {
  await manager.addContext('...');
} catch (error) {
  if (error instanceof ContextManagerError) {
    console.error('Context manager error:', error.message);
  }
}
```

## Contributing

See [CONTRIBUTING.md](./CONTRIBUTING.md) for development setup and guidelines.

## License

MIT