quasar-rs 0.1.3
Hybrid Rust/Python Agentic AI Memory Kernel
Keywords: ai, rust, maturin, memory, agents, embedding, quasar

# QUASAR: Universal Memory Kernel for AI Systems

A production-grade, encrypted, multi-backend memory orchestration system for AI applications.

QUASAR provides event-sourced memory management with graceful degradation, auto-healing, semantic search, and enterprise-grade security. Built for reasoning models that need reliable, context-aware memory across conversations.

**Status:** v0.1.0 (Hybrid Rust/Python Architecture)

[![PyPI version](https://badge.fury.io/py/quasar-rs.svg)](https://badge.fury.io/py/quasar-rs)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

---

## 🌟 Key Features

### Core Capabilities

- **Event-Sourced Architecture:** Immutable, append-only event log with complete audit trail
- **Hybrid Rust Core:** Critical paths (encryption, indexing, caching, context assembly) written in Rust for millisecond latency
- **Multi-Backend Storage:** Write to all backends simultaneously, read from the fastest available
- **Graceful Degradation:** System continues operating even when backends fail
- **Auto-Healing:** Automatically backfills recovered backends without manual intervention
- **Sibling-Graph Model:** Efficient branching and context assembly without strict hierarchies
- **End-to-End Encryption:** AES-256-GCM encryption for data at rest with Argon2id key derivation

### Advanced Features

- **Hippocampus Layer:** High-speed, concurrent in-memory cache (powered by Moka) for instant access to recent and frequently used memories
- **Smart Context Assembly:** Intelligently assembles context for LLMs by prioritizing "Pinned" memories, relevant "Semantic Facts," and recent "Episodic History" within a strict token budget
- **Semantic Search:** Vector similarity search across conversations using pgvector (Postgres) or local embeddings
- **Multi-Tenancy:** Database-level isolation with per-DB namespacing
- **Role-Based Access Control:** Admin, user, auditor, and read-only roles
- **Python API & Interactive CLI:** Both programmatic access and rich command-line interface

---

## 📦 Installation

### Python Package (Recommended)

```bash
pip install quasar-rs
```

### From Source

```bash
# Clone repository
git clone https://github.com/LinearJet/Quasar-rs.git
cd Quasar-rs

# Install with maturin (for development)
pip install maturin
maturin develop --release
```

### Prerequisites

- **Python:** 3.10 or later
- **PostgreSQL:** 14+ with pgvector extension (optional, for vector search)
- **Rust:** Latest stable (only needed for building from source)

---

## 🚀 Quick Start

### Python API

```python
from quasar_core_rs import QuasarEngine
import uuid

# Initialize engine
engine = QuasarEngine(
    config_path="quasar.yml",
    db_path="my_app.quasardb",
    password="your-secure-password"  # Optional: enables encryption
)

# Create a session
session_id = str(uuid.uuid4())

# Add events
event_id = engine.add_event(
    session_id=session_id,
    role="user",
    text="What is the capital of France?",
    embedding=None  # Auto-generated if model is loaded
)

# Retrieve events
event_json = engine.get_event(event_id)
print(event_json)

# Execute commands
result = engine.execute_command(f'SEARCH "capital France"')
print(result)
```

**For detailed API usage, see [USAGE.md](USAGE.md)**

### Interactive CLI

```bash
# Install and run CLI
pip install quasar-rs
python -m quasar_core_rs.cli

# Or if using from source
python cli.py
```

**First Run:**
- Creates root user and `auth.quasardb`
- Prompts for master password

**Common Commands:**
```bash
# Memory management
ADD user "The project deadline is next Friday." --session <uuid>
GET <event_id>
EDIT <event_id> "corrected text"

# Search & context
SEARCH "project deadlines"
CTX IN <session_id> "what are the tasks?"

# System management
STATUS
HEAL ALL
BENCHMARK
```

---

## 🗃️ Architecture

### The "Hippocampus" Architecture

At the heart of QUASAR is the Hippocampus Layer, a high-speed, concurrent in-memory cache that ensures recent and frequently accessed memories are available instantly, while older data is durably stored in slower layers.

### Storage Layers

| Layer | Type | Purpose | Implementation | Encryption |
|-------|------|---------|----------------|------------|
| **Hippocampus** | In-memory | Hot-path caching, instant recall | 🦀 Rust (Moka) | ✓ In-memory only |
| **Canonical DB** | `.quasardb` | Encrypted source of truth | 🦀 Rust | ✓ AES-256-GCM |
| **JSON** | File-based | Human-readable baseline fallback | 🦀 Rust | ✓ Per-file AES-256-GCM |
| **SQLite** | Embedded DB | Local relational queries, graph traversal | 🦀 Rust | ✓ Column-level AES-256-GCM |
| **Postgres** | Network DB | ACID guarantees, durable storage | 🦀 Rust | ✗ Network-based |

### Database Isolation

Each `.quasardb` file creates isolated namespaces across all layers:

```
main.quasardb          → Namespace: "main"
├─ json/main/          → Isolated JSON files
├─ sqlite/main/        → Isolated SQLite database
└─ Postgres: "main"    → Dedicated schema/table

project_x.quasardb     → Namespace: "project_x"
├─ json/project_x/
├─ sqlite/project_x/
└─ Postgres: "project_x"
```

---

## 🔒 Security Features

### Encryption

- **Algorithm:** AES-256-GCM (authenticated encryption)
- **Key Derivation:** Argon2id (resistant to brute-force attacks)
- **Salt:** 128-bit random salt per database
- **Nonce:** 96-bit random nonce per encrypted block

**What's Encrypted:**
- ✓ Canonical `.quasardb` file
- ✓ JSON accelerator files
- ✓ SQLite accelerator
- ✓ Authentication database

### Authentication & Authorization

```python
# Add users via Python API
from quasar_core_rs import QuasarAuth

auth = QuasarAuth("auth.quasardb", "master-password")
auth.add_user("alice", "secure_password", "admin")

# Verify credentials
is_valid = auth.verify_user("alice", "secure_password")
```

**Role Permissions:**

| Role | Read | Write | Admin Commands | System Diagnostics |
|------|------|-------|----------------|-------------------|
| admin | ✓ | ✓ | ✓ | ✓ |
| user | ✓ | ✓ | ✗ | ✗ |
| auditor | ✓ | ✗ | ✗ | ✓ |
| read-only | ✓ | ✗ | ✗ | ✗ |

---

## 📊 Performance

| Operation | Latency | Notes |
|-----------|---------|-------|
| Hippocampus Cache Hit | <1ms | Rust in-memory |
| Single Event Write | 8-15ms | All backends parallel |
| Canonical DB Write | 3-6ms | Rust core only |
| Full Session Read | 20-35ms | 50+ events |
| Context Assembly | 5-10ms | Smart prioritization |
| Semantic Search | 30-60ms | After model load |

---

## 🛠️ Configuration

### Basic Configuration (`quasar.yml`)

```yaml
layers:
  json:
    path: "./quasar_storage/json_logs"
  sqlite:
    path: "./quasar_storage/sqlite/quasar.db"
```

### Enable PostgreSQL (Optional)

```bash
export DATABASE_URL="postgresql://user:password@localhost:5432/quasar_db"
```

### Enable Encryption

```python
# Programmatic
engine = QuasarEngine("quasar.yml", "secure.quasardb", password="my-secret")

# Or via CLI
CREATE DB secure.quasardb WITH "my-password"
```

---

## 📚 Documentation

- **[USAGE.md](USAGE.md)** - Comprehensive Python API guide
- **[CLI Commands](docs/CLI.md)** - Full CLI reference (coming soon)
- **[Architecture](docs/ARCHITECTURE.md)** - System design deep-dive (coming soon)

---

## 🗺️ Roadmap

### Completed (v0.1.0)
- ✓ Hybrid Rust/Python architecture
- ✓ Multi-backend orchestration
- ✓ End-to-end encryption
- ✓ RBAC authentication
- ✓ Interactive CLI
- ✓ Python package on PyPI

### In Progress (v0.2)
- 🔄 Performance optimization (sub-5ms writes)
- 🔄 Comprehensive test suite
- 🔄 Docker deployment
- 🔄 FastAPI REST server

### Planned (v0.3+)
- 📋 Real-time WebSocket subscriptions
- 📋 Distributed QUASAR (multi-node)
- 📋 Event compaction strategies
- 📋 Custom backend plugins
- 📋 Memory policy engine

---

## 🤝 Contributing

We welcome contributions! Areas of focus:

- **Backend Implementations:** Cassandra, MongoDB, S3
- **Rust Core Optimization:** Performance improvements
- **Embedding Models:** Alternative providers
- **Visualization:** Knowledge graph rendering
- **Documentation:** Guides and tutorials

---

## 📜 License

MIT License - See [LICENSE](LICENSE) for details.

---

## 🔗 Links

- **Repository:** [github.com/LinearJet/Quasar-rs](https://github.com/LinearJet/Quasar-rs)
- **PyPI Package:** [pypi.org/project/quasar-rs](https://pypi.org/project/quasar-rs)
- **Python Version:** [github.com/LinearJet/Quasar](https://github.com/LinearJet/Quasar)
- **Issues:** [GitHub Issues](https://github.com/LinearJet/Quasar-rs/issues)
- **Discussions:** [GitHub Discussions](https://github.com/LinearJet/Quasar-rs/discussions)

---

## 💡 Philosophy

QUASAR is built on three core principles:

1. **Resilience over Perfection:** Better to have 3/5 backends working than wait for all 5
2. **Composability over Monoliths:** Each backend does one thing exceptionally well
3. **Intelligence over Infrastructure:** Reasoning models should orchestrate their own memory

---

## Acknowledgments

Built with:
- [Rust](https://rust-lang.org) - Systems programming language
- [PyO3](https://pyo3.rs) - Rust-Python bindings
- [Maturin](https://www.maturin.rs) - Build tool for Rust-Python packages
- [Candle](https://github.com/huggingface/candle) - ML framework in Rust
- [SQLx](https://github.com/launchbadge/sqlx) - Async SQL toolkit

---