# Novyx SDK

**Persistent memory + rollback + audit trail for AI agents.** Give your AI persistent memory, semantic search, Magic Rollback to undo mistakes, and cryptographic audit trails. Works with LangChain, CrewAI, or any Python agent framework.

## Installation

```bash
pip install novyx
```

### CLI Installation (Optional)

For the command-line interface:

```bash
pip install novyx[cli]
```

This installs the `novyx` command for managing memory, rollback, audit, and traces from the terminal.

## Quick Start

```python
from novyx import Novyx

# Initialize with your API key
nx = Novyx(api_key="nram_your_key_here")

# Store a memory
nx.remember("User prefers dark mode and async communication", tags=["preferences"])

# Search memories semantically
memories = nx.recall("communication style", limit=5)
for mem in memories:
    print(f"{mem['observation']} (relevance: {mem['score']:.2f})")

# Check audit trail
audit = nx.audit(limit=10)
print(f"Last 10 operations: {[e['operation'] for e in audit]}")

# Magic Rollback - undo to any point in time (Pro+)
nx.rollback("2 hours ago")
```

## Complete Lifecycle Example

```python
from novyx import Novyx

nx = Novyx(api_key="nram_your_key_here")

# 1. Store memories
nx.remember("User mentioned budget is $50K for Q1", tags=["sales", "budget"], importance=8)
nx.remember("User prefers email over phone calls", tags=["preferences"], importance=7)
nx.remember("User is building a real estate AI assistant", tags=["project"])

# 2. Search with semantic recall
memories = nx.recall("what is the user's budget?", limit=3)
print(f"Found: {memories[0]['observation']}")

# 3. Check audit trail
audit = nx.audit(limit=5, operation="CREATE")
print(f"Created {len(audit)} memories")

# 4. Rollback if needed (Pro+ only)
# Preview what will change
preview = nx.rollback_preview("1 hour ago")
if preview["safe_rollback"]:
    result = nx.rollback("1 hour ago")
    print(f"Rolled back {result['operations_undone']} operations")

# 5. Trace agent actions (Pro+ only)
trace = nx.trace_create("sales-agent", session_id="session-123")
nx.trace_step(trace["trace_id"], "thought", "Analyzing budget", content="User has $50K")
nx.trace_step(trace["trace_id"], "action", "draft_proposal", attributes={"budget": 50000})
result = nx.trace_complete(trace["trace_id"])
print(f"Trace completed with signature: {result['signature'][:16]}...")
```

## Features

### 🧠 Persistent Memory
Store observations about users, contexts, and decisions. Your AI remembers everything across sessions.

```python
# Store with metadata
nx.remember(
    "Customer mentioned budget is $50K for Q1",
    tags=["sales", "budget"],
    importance=8,
    metadata={"customer_id": "12345", "quarter": "Q1"}
)

# List all memories
all_memories = nx.memories(limit=100, min_importance=7)
print(f"Found {len(all_memories)} high-importance memories")

# Get specific memory
memory = nx.memory("urn:uuid:abc123...")

# Delete memory
nx.forget("urn:uuid:abc123...")
```

### 🔍 Semantic Search
Find relevant memories using natural language queries. No exact keyword matching required.

```python
memories = nx.recall("what is the user working on?", limit=3)
# Returns: "User is building a real estate AI assistant"

# Filter by tags
memories = nx.recall("budget constraints", tags=["sales"], limit=5)
```

### ⏮️ Magic Rollback (Pro+)
Made a mistake? Roll back your AI's memory to any point in time.

```python
# Preview rollback first
preview = nx.rollback_preview("2 hours ago")
print(f"Will restore {preview['artifacts_restored']} artifacts")
print(f"Warnings: {preview['warnings']}")

# Execute rollback
result = nx.rollback("2 hours ago")
print(f"Rolled back to {result['rolled_back_to']}")

# View rollback history
history = nx.rollback_history(limit=10)
for rb in history:
    print(f"Rollback to {rb['target_timestamp']}")
```

### 📜 Cryptographic Audit Trail
Every operation is logged with SHA-256 hashing for tamper-proof history.

```python
# Get recent audit entries
audit = nx.audit(limit=50, operation="CREATE")

# Filter by time range
from datetime import datetime, timedelta
since = (datetime.now() - timedelta(days=7)).isoformat()
audit = nx.audit(since=since, operation="ROLLBACK")

# Export audit log (Pro+)
csv_data = nx.audit_export(format="csv")
with open("audit.csv", "wb") as f:
    f.write(csv_data)

# Verify integrity
verification = nx.audit_verify()
if verification["valid"]:
    print("✅ Audit trail integrity verified!")
```

### 🔐 Trace Audit (Pro+)
Track agent actions with RSA signatures and real-time policy enforcement.

```python
# Create trace session
trace = nx.trace_create("my-agent", session_id="session-123")

# Add steps
nx.trace_step(trace["trace_id"], "thought", "Planning email")
nx.trace_step(trace["trace_id"], "action", "send_email", attributes={"to": "user@example.com"})
nx.trace_step(trace["trace_id"], "observation", "Email sent successfully")

# Finalize with RSA signature
result = nx.trace_complete(trace["trace_id"])

# Verify integrity later
verification = nx.trace_verify(trace["trace_id"])
print(f"Verified {verification['steps_verified']} steps")
```

### 📊 Usage & Plans
Monitor your usage and explore pricing options.

```python
# Check current usage
usage = nx.usage()
print(f"Tier: {usage['tier']}")
print(f"API calls: {usage['api_calls']['current']}/{usage['api_calls']['limit']}")
print(f"Memories: {usage['memories']['current']}")

# View available plans
plans = nx.plans()
for plan in plans:
    print(f"{plan['name']}: {plan['price_display']}")
    print(f"  Memories: {plan['memory_limit'] or 'Unlimited'}")
    print(f"  Features: {', '.join([k for k, v in plan['features'].items() if v])}")
```

## API Reference

### Memory Methods
| Method | Description |
|--------|-------------|
| `remember(observation, tags=[], importance=5, metadata=None)` | Store a memory |
| `recall(query, limit=5, tags=None, min_score=0.0)` | Semantic search |
| `memories(limit=100, offset=0, tags=None, min_importance=None)` | List all memories |
| `memory(memory_id)` | Get specific memory by ID |
| `forget(memory_id)` | Delete memory |
| `stats()` | Get memory statistics |

### Rollback Methods (Pro+)
| Method | Description |
|--------|-------------|
| `rollback(target, dry_run=False, preserve_evidence=True)` | Rollback to timestamp or relative time |
| `rollback_preview(target)` | Preview rollback changes |
| `rollback_history(limit=50)` | List past rollbacks |

### Audit Methods
| Method | Description |
|--------|-------------|
| `audit(limit=50, since=None, until=None, operation=None)` | Get audit entries |
| `audit_export(format="csv")` | Export audit log (Pro+) |
| `audit_verify()` | Verify audit integrity |

### Trace Methods (Pro+)
| Method | Description |
|--------|-------------|
| `trace_create(agent_id, session_id=None, metadata=None)` | Create trace session |
| `trace_step(trace_id, step_type, name, content=None, attributes=None)` | Add trace step |
| `trace_complete(trace_id)` | Finalize trace with RSA signature |
| `trace_verify(trace_id)` | Verify trace integrity |

### Usage & Plans
| Method | Description |
|--------|-------------|
| `usage()` | Get current usage vs limits |
| `plans()` | List available pricing plans |

## Error Handling

```python
from novyx import (
    Novyx,
    NovyxRateLimitError,
    NovyxForbiddenError,
    NovyxAuthError,
    NovyxNotFoundError
)

nx = Novyx(api_key="nram_...")

try:
    nx.remember("Test memory")
except NovyxRateLimitError as e:
    # Memory limit exceeded
    print(f"Limit exceeded: {e.current}/{e.limit}")
    print(f"Upgrade at: {e.upgrade_url}")
except NovyxForbiddenError as e:
    # Feature not available on current plan
    print(f"Requires {e.tier_required} tier")
    print(f"Upgrade at: {e.upgrade_url}")
except NovyxAuthError as e:
    # Invalid API key
    print(f"Auth error: {e}")
except NovyxNotFoundError as e:
    # Resource not found
    print(f"Not found: {e}")
```

## Pricing

| Tier | Price | Memories | API Calls | Rollbacks | Audit | Features |
|------|-------|----------|-----------|-----------|-------|----------|
| **Free** | $0 | 5,000 | 5,000/mo | 10/month | 7 days | Basic memory |
| **Starter** | $12/mo | 25,000 | 25,000/mo | 30/month | 14 days | + Basic rollback |
| **Pro** | $39/mo | Unlimited | 100,000/mo | Unlimited | 30 days | + Rollback, trace audit, anomaly alerts |
| **Enterprise** | $199/mo | Unlimited | Unlimited | Unlimited | 90 days | + Priority support, SSO-ready |

## Command-Line Interface (CLI)

Novyx includes a powerful CLI for managing memory, rollback, audit, and traces from the terminal.

### Setup

```bash
# Install with CLI support
pip install novyx[cli]

# Configure API key
novyx config set api_key nram_your_key_here

# Or use environment variable
export NOVYX_API_KEY=nram_your_key_here
```

### Quick Start

```bash
# Check API health and usage
novyx status

# List memories
novyx memories list --limit 20

# Semantic search
novyx memories search "user preferences"

# Get memory count
novyx memories count

# Delete memory
novyx memories delete <uuid>
```

### Memory Management

```bash
# List all memories
novyx memories list --limit 100 --format table

# Export as JSON
novyx memories list --format json > memories.json

# Filter by tags
novyx memories list --tags "important,user-data"

# Semantic search with relevance scores
novyx memories search "what are the user's communication preferences?" --limit 5

# Delete with confirmation
novyx memories delete urn:uuid:abc123...
```

### Rollback (Pro+)

```bash
# Preview rollback (ALWAYS do this first)
novyx rollback preview "2 hours ago"

# Execute rollback (shows preview + confirmation)
novyx rollback "2 hours ago"

# Skip confirmation (use with caution!)
novyx rollback "1 hour ago" --yes

# View rollback history
novyx rollback history --limit 10
```

### Audit Trail

```bash
# List recent audit entries
novyx audit list --limit 50

# Filter by operation
novyx audit list --operation CREATE --limit 20
novyx audit list --operation ROLLBACK

# Export audit log (Pro+)
novyx audit export --format csv > audit.csv
novyx audit export --format json > audit.json

# Verify audit integrity
novyx audit verify
```

### Trace Audit (Pro+)

```bash
# Verify trace integrity
novyx traces verify trace-abc123

# List and show coming in v2.1
novyx traces list
novyx traces show trace-abc123
```

### Account & Status

```bash
# Show API health, plan, and usage
novyx status

# Configure API key
novyx config set api_key nram_your_key_here

# Show configuration (API key masked)
novyx config show

# Reset configuration
novyx config reset
```

### CLI Features

- **Rich Output**: Beautiful tables and colored output with [Rich](https://github.com/Textualize/rich)
- **Progress Indicators**: Spinners for long-running operations
- **Safety First**: Rollback always shows preview + requires confirmation
- **Multiple Formats**: JSON or table output for easy parsing
- **API Key Resolution**: Flag > Environment > Config file (priority order)
- **Error Handling**: Clear, human-readable error messages

### API Key Priority

The CLI resolves API keys in this order:

1. `--api-key` flag (highest priority)
2. `NOVYX_API_KEY` environment variable
3. `~/.novyx/config.json` (lowest priority)

```bash
# Using flag
novyx --api-key nram_xxx status

# Using environment variable
export NOVYX_API_KEY=nram_xxx
novyx status

# Using config file
novyx config set api_key nram_xxx
novyx status
```

### Example Workflow

```bash
# 1. Check system status
novyx status

# 2. List recent memories
novyx memories list --limit 20

# 3. Search for specific context
novyx memories search "budget constraints" --min-score 0.7

# 4. Made a mistake? Preview rollback
novyx rollback preview "1 hour ago"

# 5. Execute rollback if safe
novyx rollback "1 hour ago"

# 6. Verify audit integrity
novyx audit verify

# 7. Export audit for compliance
novyx audit export --format csv > audit-2026-02.csv
```

## Links

- [Documentation](https://novyxlabs.com/docs)
- [GitHub](https://github.com/novyxlabs/novyx-core)
- [Pricing](https://novyxlabs.com/pricing)
- [Get API Key](https://novyxlabs.com)

## License

MIT License - see [LICENSE](https://github.com/novyxlabs/novyx-core/blob/main/LICENSE) for details.
