Metadata-Version: 2.4
Name: novyx
Version: 3.0.2
Summary: Agent memory infrastructure — store, recall, rollback, eval, and audit for AI agents.
Home-page: https://novyxlabs.com
Author: Novyx Labs
Author-email: blake@novyxlabs.com
Project-URL: Documentation, https://docs.novyxlabs.com
Keywords: ai,agents,memory,llm,langchain,semantic-search,rollback,audit,trace,eval,observability,cli
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.8
Description-Content-Type: text/markdown
Requires-Dist: requests>=2.28.0
Provides-Extra: cli
Requires-Dist: click>=8.0.0; extra == "cli"
Requires-Dist: rich>=13.0.0; extra == "cli"
Provides-Extra: async
Requires-Dist: httpx>=0.25.0; extra == "async"
Dynamic: author
Dynamic: author-email
Dynamic: classifier
Dynamic: description
Dynamic: description-content-type
Dynamic: home-page
Dynamic: keywords
Dynamic: project-url
Dynamic: provides-extra
Dynamic: requires-dist
Dynamic: requires-python
Dynamic: summary

# Novyx SDK

**Agent memory infrastructure — store, review, merge, recall, rollback, eval, and audit for AI agents.** Give your AI persistent memory, semantic search, draft review before memory becomes canonical, Magic Rollback to undo mistakes, memory health evaluation with CI/CD gates, cryptographic audit trails, context spaces for multi-agent collaboration, replay for time-travel debugging, and cortex for autonomous memory intelligence. Works with LangChain, CrewAI, or any Python agent framework.

## Installation

```bash
pip install novyx
```

### Async Support (Optional)

```bash
pip install novyx[async]
```

### CLI Installation (Optional)

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

## Quick Start (Sync)

```python
from novyx import Novyx

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})")

# Evaluate memory health
health = nx.eval_run()
print(f"Memory health: {health['health_score']}/100")

# Review memory before it becomes real
draft = nx.draft_memory("Staging deploy fails without REDIS_URL", tags=["ops", "staging"])
nx.merge_draft(draft["draft_id"])

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

## Quick Start (Async)

```python
from novyx import AsyncNovyx

async with AsyncNovyx(api_key="nram_your_key_here") as nx:
    await nx.remember("User prefers dark mode", tags=["preferences"])
    memories = await nx.recall("user preferences")
    health = await nx.eval_run()
    print(f"Health: {health['health_score']}/100")
```

## 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 — user has $50K")
nx.trace_step(trace["trace_id"], "action", "draft_proposal", metadata={"budget": 50000})
result = nx.trace_complete(trace["trace_id"])
print(f"Trace completed with signature: {result['signature'][:16]}...")
```

## Canonical Workflow: Draft, Review, Merge

If an agent learns something high-impact, don't write it straight into canonical memory.

```python
from novyx import Novyx

nx = Novyx(api_key="nram_your_key_here")

draft = nx.draft_memory(
    "Deploys fail if REDIS_URL is missing in staging",
    tags=["ops", "staging"],
    importance=8,
    branch_id="staging-fixes",
)

branch = nx.memory_branch("staging-fixes")
print(branch["recommendations"])

# Compare one draft against the closest existing memory
diff = nx.draft_diff(draft["draft_id"])
print(diff["recommendation"])

# Merge the whole reviewed branch
merged = nx.merge_branch("staging-fixes")
print(merged["merged_memory_ids"])

# Or reject the whole branch instead
# nx.reject_branch("staging-fixes", reason="not verified yet")
```

This is the safest default when an agent is learning operational facts, preferences, or anything that could drive future actions across a coding session.

## 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. Send plain text — Novyx handles embedding generation server-side.

```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", metadata={"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")
```

### 🌐 Context Spaces (Multi-Agent)
Create shared memory spaces for multi-agent collaboration with fine-grained permissions.

```python
# Share a tag with another user
result = nx.share_context("project-notes", "colleague@example.com", permission="write")

# List shared spaces
ctx = nx.shared_contexts()
for s in ctx["shared_by_me"]:
    print(f"Shared '{s['tag']}' with {s.get('shared_with_email')}")

# Store memory in a space
nx.remember("Shared insight", space_id="cs_abc123", tags=["shared"])

# Recall from a space
memories = nx.recall("insights", space_id="cs_abc123")
```

### 🔄 Replay — Time-Travel Debugging (Pro+)
Inspect how your agent's memory changed over time.

```python
# Timeline of operations
timeline = nx.replay_timeline(since="2026-01-01T00:00:00Z", limit=50)
for event in timeline["entries"]:
    print(f"{event['timestamp']} - {event['operation']}")

# Point-in-time snapshot
snapshot = nx.replay_snapshot("2026-01-15T10:00:00Z")
print(f"{snapshot['total']} memories at that point")

# Full lifecycle of a memory
lifecycle = nx.replay_memory("urn:uuid:abc123...")

# Diff between two timestamps
diff = nx.replay_diff("2026-01-01T00:00:00Z", "2026-01-15T00:00:00Z")
print(f"Added: {diff['added']}, Removed: {diff['removed']}")

# Counterfactual recall (Enterprise)
result = nx.replay_recall("user preferences", at="2026-01-10T00:00:00Z")
```

### 🧬 Cortex — Autonomous Memory Intelligence (Pro+)
Your memory gets smarter on its own. Cortex consolidates near-duplicates, boosts frequently-recalled memories, decays forgotten ones, and generates insights.

```python
# Check cortex status
status = nx.cortex_status()
print(f"Enabled: {status['enabled']}, Last run: {status['last_run_at']}")

# Configure cortex
nx.cortex_update_config(
    consolidation_enabled=True,
    consolidation_threshold=0.90,
    decay_age_days=30,
)

# Trigger a manual cycle
result = nx.cortex_run()
print(f"Consolidated: {result['consolidated']}, Boosted: {result['boosted']}, Decayed: {result['decayed']}")

# Get insights (Enterprise)
insights = nx.cortex_insights(limit=10)
for insight in insights["insights"]:
    print(f"Insight: {insight['observation']}")
```

### 📊 Eval — Memory Health Scoring
Score your agent's memory health, detect regressions, and gate CI/CD deployments.

```python
# Run a health evaluation
result = nx.eval_run()
print(f"Health: {result['health_score']}/100")
print(f"Recall: {result['breakdown']['recall_consistency']}")
print(f"Drift: {result['breakdown']['drift_score']}")

# CI/CD gate — block deploys below threshold
gate = nx.eval_gate(min_score=80.0)
if not gate["passed"]:
    raise Exception(f"Memory health too low: {gate['health_score']}")

# Save baselines for regression testing
nx.eval_baseline_create("capital of France", "The capital of France is Paris")

# Check drift over time
drift = nx.eval_drift()
print(f"Memory count delta: {drift['memory_count_delta']}")

# View eval history
history = nx.eval_history(limit=10)
for entry in history["entries"]:
    print(f"{entry['created_at']}: {entry['health_score']}")
```

### 📊 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, content, metadata=None)` | Add trace step |
| `trace_complete(trace_id)` | Finalize trace with RSA signature |
| `trace_verify(trace_id)` | Verify trace integrity |

### Context Space Methods
| Method | Description |
|--------|-------------|
| `share_context(tag, to_email, permission="read")` | Share a tag/space with another user |
| `accept_shared_context(token)` | Accept a share invitation |
| `shared_contexts()` | List spaces shared by and with you |
| `revoke_shared_context(token)` | Revoke a share invitation |

### Replay Methods (Pro+)
| Method | Description |
|--------|-------------|
| `replay_timeline(since=None, until=None, operations=None, limit=100)` | Timeline of memory operations |
| `replay_snapshot(at, limit=500)` | Reconstruct memory state at a timestamp |
| `replay_memory(memory_id)` | Full lifecycle of a single memory |
| `replay_diff(from_ts, to_ts)` | Diff between two timestamps |
| `replay_recall(query, at, limit=5)` | Counterfactual recall (Enterprise) |
| `replay_drift(from_ts, to_ts)` | Memory composition drift (Enterprise) |

### Cortex Methods (Pro+)
| Method | Description |
|--------|-------------|
| `cortex_status()` | Get cortex status, last run, and config |
| `cortex_config()` | Get current cortex configuration |
| `cortex_update_config(**kwargs)` | Update cortex settings |
| `cortex_run()` | Trigger a manual cortex cycle |
| `cortex_insights(limit=20)` | Get generated insights (Enterprise) |

### Knowledge Graph Methods (Pro+)
| Method | Description |
|--------|-------------|
| `triple(subject, predicate, object)` | Create a knowledge graph triple |
| `triples(subject=None, predicate=None, object=None)` | Query triples |
| `delete_triple(triple_id)` | Delete a triple |
| `entities(entity_type=None, q=None)` | List entities |
| `entity(entity_id)` | Get entity with connections |
| `delete_entity(entity_id)` | Delete entity and its triples |

### Link / Edge Methods
| Method | Description |
|--------|-------------|
| `link(source_id, target_id, relation="related")` | Create a directed edge |
| `unlink(source_id, target_id)` | Remove edge(s) |
| `links(memory_id)` | Get edges for a memory |
| `edges(relation=None, limit=100)` | List all edges |

### Eval Methods
| Method | Description |
|--------|-------------|
| `eval_run(min_score=None)` | Run memory health evaluation |
| `eval_gate(min_score)` | CI/CD gate — fail if health below threshold |
| `eval_history(limit=50, offset=0, days=None)` | List past eval runs |
| `eval_drift(from_ts=None, to_ts=None)` | Get memory drift analysis |
| `eval_baseline_create(query, expected_observation)` | Create a recall baseline |
| `eval_baselines()` | List all baselines |
| `eval_baseline_delete(baseline_id)` | Delete a baseline |

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

## 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, LWW conflict resolution, eval (3/day) |
| **Starter** | $12/mo | 25,000 | 25,000/mo | 30/month | 14 days | + All conflict strategies, eval (30/day, 5 baselines) |
| **Pro** | $39/mo | Unlimited | 100,000/mo | Unlimited | 30 days | + Replay, Cortex, traces, knowledge graph, eval (unlimited + CI/CD gate + drift detail) |
| **Enterprise** | $199/mo | Unlimited | Unlimited | Unlimited | 90 days | + Cortex insights, counterfactual recall, drift analysis, eval (365-day history) |

## 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://docs.novyxlabs.com)
- [Pricing](https://novyxlabs.com/pricing)
- [Get API Key](https://novyxlabs.com)

## License

MIT
