# Changelog

All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

---

## [2.1.0] - 2026-04-01

### Added

- **Context-aware intelligence query contract**:
  - added optional `organizationId`, `topicId`, `memoryTypes`, and `queryScope` support to the public SDK query surface
  - extended predictive recall request typing so the context-aware contract stays consistent across client, MCP server, and internal tools
- **Shared scoped server-side query resolver**:
  - internal intelligence tools now resolve personal, organization, and hybrid queries through one shared helper instead of hardcoded `user_id`-only paths
  - added resolver test coverage for scoped query behavior

### Changed

- **Consumer compatibility alignment**:
  - CLI intelligence commands now accept additive context flags and forward them through to the SDK contract
  - dashboard memory-intelligence hook now passes optional context fields through the client layer
- **Prediction and related-memory internals**:
  - updated related-memory, health, duplicate, insight, tag, pattern, and predictive helpers to honor the new scoped query contract without forcing a physical storage split

### Fixed

- **Edge envelope compatibility for `queryMemories()`**:
  - switched the SDK memory query path to the enhanced response adapter so `/intelligence/memories` can use the standard edge-function envelope without breaking the client

## [2.0.3] - 2026-02-25

### Added

- **Behavior methods changelog/documentation parity**:
  - `recordBehavior()` - persist successful workflow patterns
  - `recallBehavior()` - retrieve similar patterns by contextual similarity
  - `suggestAction()` - generate next-step suggestions from learned workflows
  - `listBehaviorPatterns()` - enumerate saved behavior patterns for a user
- Added concrete SDK README usage examples for the behavior method surface above (request shape + expected usage flow).

### Fixed

- **Declaration build completeness**: fixed SDK declaration generation so publish artifacts include all expected `.d.ts` entrypoints for `.` / `core` / `node` / `react` / `vue` / `server`.
- Reduced declaration build pressure by preventing oversized MCP server type inference during declaration emit and disabling declaration/source maps for the declaration-only build step.

## [2.0.0] - 2026-01-13

### The AI That Anticipates What You Need

This major release introduces the **Predictive Memory System** - the flagship Phase 2 feature that makes your memory system feel magical. Instead of just storing and retrieving memories, the SDK now **predicts what you'll need before you realize it**.

### Added

#### Predictive Memory System (Phase 2A)

- **`predictiveRecall()`** - AI-powered prediction of memories based on current context
- **Weighted Scoring Algorithm**:
  - Semantic similarity to current context (40%)
  - Temporal relevance with Ebbinghaus decay curve (30%)
  - Usage frequency, logarithmically scaled (20%)
  - Serendipity factor for adjacent discoveries (10%)
- **Explainable Predictions** - Every prediction includes:
  - Confidence score (0-100)
  - Human-readable reason ("Highly relevant to your current work")
  - Score breakdown for transparency
  - Suggested action (apply, review, explore, reference)

#### Personalization

- **User Profile Integration** - Fetches first name, email, organization for personalized responses
- **Personalized Greetings** - "Sarah, here's what you might need" instead of generic messages
- **Contextual Feedback** - "Thanks Sarah! We'll use this to improve your predictions."

#### Premium Tier Gating

- **`checkPremiumAccess()`** - Validate feature access by subscription tier
- **Tier-Based Access Control** - Free, Pro, Business, Enterprise tiers
- **Feature Flags** - Granular per-feature access control
- **Graceful Degradation** - If checks fail, defaults to allowing access

#### Prediction Feedback Loop

- **`recordPredictionFeedback()`** - Track if predictions were useful
- **`getPredictionMetrics()`** - Dashboard metrics for prediction accuracy
- **Access Count Updates** - Predictions that get clicked/saved improve frequency scoring

#### MCP Tools

- **`memory_predictive_recall`** - Full MCP tool with markdown formatting
- **`memory_prediction_feedback`** - Record user feedback on predictions

#### React Integration

```tsx
// New hooks for predictions
const { data } = usePredictiveRecall({
  userId: "user-123",
  context: {
    currentProject: "Building dashboard",
    recentTopics: ["React", "performance"]
  }
});

// Feedback hook
const { mutate: recordFeedback } = usePredictionFeedback();
```

#### Vue Integration

```vue
<script setup>
const { data, execute } = usePredictiveRecall();
const { execute: recordFeedback } = usePredictionFeedback();
</script>
```

#### Database Infrastructure

New migration file `supabase/migrations/20260113_prediction_system.sql` includes:

| Component | Purpose |
|-----------|---------|
| `prediction_feedback` table | Track prediction accuracy |
| `prediction_history` table | Audit log of predictions |
| `increment_access_count()` | Update frequency scores |
| `get_user_profile_for_predictions()` | Personalization data |
| `has_premium_feature()` | Tier-based access control |
| `get_prediction_accuracy()` | Metrics calculation |

### Changed

- **Version bump** - 1.1.0 → 2.0.0 (major version for significant new capabilities)
- **Package description** - Updated to highlight predictive recall
- **Keywords** - Added: predictive, predictions, embeddings, vector-search, personalization, machine-learning

### Technical Details

#### Prediction Algorithm

```
Combined Score = (Semantic × 40%) + (Temporal × 30%) + (Frequency × 20%) + (Serendipity × 10%)
```

- **Semantic**: Cosine similarity between context embedding and memory embedding
- **Temporal**: Exponential decay (Ebbinghaus forgetting curve, 14-day half-life)
- **Frequency**: Logarithmic scaling of access counts (prevents outliers from dominating)
- **Serendipity**: "Adjacent possible" - rewards nearby-but-not-identical topics (0.3-0.6 similarity range)

#### Context Types

```typescript
interface PredictiveContext {
  currentProject?: string;    // "Building dashboard components"
  recentTopics?: string[];    // ["React", "TypeScript", "performance"]
  activeFiles?: string[];     // ["/src/Dashboard.tsx"]
  contextText?: string;       // Free-form: "Optimizing render performance"
  teamContext?: string;       // "Team discussing caching strategies"
}
```

### Migration Guide

1. **Run database migration**:
   ```bash
   # Copy SQL from supabase/migrations/20260113_prediction_system.sql
   # Execute in Supabase SQL Editor
   ```

2. **Enable for users** (optional premium gating):
   ```sql
   UPDATE profiles
   SET subscription_tier = 'pro',
       feature_flags = '{"predictive_recall": true}'::jsonb
   WHERE id = 'user-uuid';
   ```

3. **Use new methods**:
   ```typescript
   // Before (1.x) - manual search
   const related = await client.findRelated({ memoryId, userId });

   // After (2.x) - AI anticipates what you need
   const predictions = await client.predictiveRecall({
     userId,
     context: { currentProject: "My current work" }
   });
   ```

---

## [1.1.0] - 2025-12-20

### Added

- **Behavioral Intelligence Foundation** (Context Patterns v2.0)
- `recordBehavior()` - Store workflow patterns
- `recallBehavior()` - Query patterns with local-first approach
- `suggestBehavior()` - AI-powered next action suggestions
- WorkflowPattern type with trigger, context, actions, outcome tracking

### Improved

- Enhanced offline-fallback caching
- Better error messages for API failures
- Response adapter handles both Edge Function envelope and direct responses

---

## [1.0.1] - 2025-12-18

### Fixed

- Fixed TypeScript compilation errors with OpenAI SDK named imports
- Added proper JSX configuration to tsconfig.json for React components
- Added type annotations for callback parameters to satisfy strict TypeScript checks
- Removed unused type imports that were causing compilation warnings

### Improved

- Enhanced type safety across core client and utility functions
- Improved error messages in core error classes
- Better handling of OpenAI client initialization

---

## [1.0.0] - 2024-12-17

### Initial Release

The first release of `@lanonasis/mem-intel-sdk` - an AI-powered memory intelligence SDK for the LanOnasis Memory-as-a-Service platform.

### Added

#### Core Features

- **`MemoryIntelligenceClient`** - Universal API client with offline-fallback capability
- **Framework Integrations**:
  - React hooks with React Query (`/react`)
  - Vue composables (`/vue`)
  - Node.js optimized client (`/node`)
  - MCP Server creation (`/server`)

#### Intelligence Tools

| Tool | Description |
|------|-------------|
| `analyzePatterns` | Understand usage trends and productivity patterns |
| `suggestTags` | AI-powered tag suggestions with confidence scores |
| `findRelated` | Find semantically related memories using vector similarity |
| `detectDuplicates` | Identify duplicate or near-duplicate memories |
| `extractInsights` | Extract key learnings from your knowledge base |
| `healthCheck` | Analyze organization quality with actionable recommendations |

#### Developer Experience

- Full TypeScript support with comprehensive type definitions
- Dual module support (ESM and CommonJS)
- Custom error classes for better debugging
- Dual response format (JSON and Markdown)
- Zod schema validation for MCP tools

---

## Roadmap

### Coming in 2.1.0 (Q1 2026)

- **Knowledge Gap Detection** - "What should I learn next?"
- Personalized learning paths based on your saved memories
- Integration with YouTube, Medium, Dev.to for resources

### Coming in 2.2.0 (Q2 2026)

- **Team Knowledge Graph** - "Who's the expert on X?"
- Privacy-first aggregation (no individual data exposed)
- Expert finder with topic expertise scoring

### Coming in 3.0.0 (Q3 2026)

- **Privacy-First Local Processing** - ONNX Runtime on-device
- **Autonomous Organization Agent** - Weekly AI cleanup
- **API Marketplace** - Developer ecosystem with 70/30 revenue share

---

## Links

- [GitHub Repository](https://github.com/lanonasis/memory-intelligence-engine)
- [npm Package](https://www.npmjs.com/package/@lanonasis/mem-intel-sdk)
- [Product Roadmap](./PRODUCT-ROADMAP-2025-2026.md)
- [Migration Guide](./supabase/migrations/20260113_prediction_system.sql)

---

Built with care by the LanOnasis team. We believe AI should anticipate your needs, not just respond to commands.
