Metadata-Version: 2.4
Name: evaos
Version: 1.1.0
Summary: AI memory engine with identity preservation — remember everything, forget nothing
Author-email: 100Yen Org <dev@100yen.org>
License-Expression: MIT
Project-URL: Homepage, https://github.com/100yenadmin/electric-sheep
Project-URL: Repository, https://github.com/100yenadmin/electric-sheep
Project-URL: Documentation, https://github.com/100yenadmin/electric-sheep#readme
Project-URL: Issues, https://github.com/100yenadmin/electric-sheep/issues
Keywords: ai,memory,llm,identity,companion,evaos
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: aiosqlite>=0.20.0
Requires-Dist: tiktoken>=0.7
Requires-Dist: rapidfuzz>=3.6
Requires-Dist: numpy>=1.26
Requires-Dist: click>=8.1
Provides-Extra: llm
Requires-Dist: openai>=1.50; extra == "llm"
Requires-Dist: anthropic>=0.40; extra == "llm"
Requires-Dist: ollama>=0.4; extra == "llm"
Provides-Extra: embedding
Requires-Dist: voyageai>=0.3; extra == "embedding"
Provides-Extra: server
Requires-Dist: fastapi>=0.115; extra == "server"
Requires-Dist: uvicorn>=0.30; extra == "server"
Requires-Dist: pydantic>=2.0; extra == "server"
Requires-Dist: httpx>=0.27; extra == "server"
Provides-Extra: mcp
Requires-Dist: mcp>=1.0; extra == "mcp"
Provides-Extra: vec
Requires-Dist: sqlite-vec>=0.1.0; extra == "vec"
Provides-Extra: dev
Requires-Dist: pytest>=8.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
Requires-Dist: aiohttp>=3.9; extra == "dev"
Requires-Dist: build>=1.0; extra == "dev"
Requires-Dist: evaos[mcp,server,vec]; extra == "dev"
Provides-Extra: all
Requires-Dist: evaos[dev,embedding,llm,mcp,server,vec]; extra == "all"
Dynamic: license-file

<div align="center">

# 🐑 evaOS (Electric Sheep)

**AI memory that remembers who you are.**

[![PyPI version](https://img.shields.io/pypi/v/evaos.svg)](https://pypi.org/project/evaos/)
[![Python 3.11+](https://img.shields.io/badge/python-3.11%2B-blue.svg)](https://python.org)
[![License: MIT](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
[![Tests](https://img.shields.io/github/actions/workflow/status/100yenadmin/electric-sheep/ci.yml?label=tests)](https://github.com/100yenadmin/electric-sheep/actions)

*Identity-preserving memory engine for AI agents.  
Your agent wakes up tomorrow and still knows who it is.*

</div>

---

## What's New in v1.1

🚀 **v1.1** is a major feature release focused on intelligence, observability, and developer experience:

- **Dialectic Engine** — Ask your memory natural-language questions with single-shot and agentic multi-step query paths
- **Peer Modeling** — Relationship tracking with auto-creation from entities and representation building
- **Brain Graph** — Document indexing with file watching, graph CRUD, and structured retrieval
- **Graph Visualization** — Force-directed graph data endpoints (nodes, edges, paths, neighbors)
- **Dashboard** — 8-page web UI for exploring memories, entities, cornerstones, peers, graph, events, config, and health
- **Webhooks** — Event subscriptions with reliable delivery, retry, and filtering
- **TypeScript SDK** — `@evaos/client` for Node.js/TypeScript consumers
- **16 Event Types** — Full event system with live emission across the entire engine
- **LLM Retry/Backoff** — 3 retries with exponential backoff + provider cascade for resilience
- **Embedding Model Switch Protection** — Prevents silent corruption when switching embedding models
- **API Key Redaction** — Automatic redaction of API keys in all log output
- **Storage Robustness** — 40 write locks, NaN validation, OOM protection

See the [CHANGELOG](CHANGELOG.md) for the full list of changes.

---

## Why evaOS?

Most AI memory systems are glorified vector stores. They dump embeddings into a database and call it "memory." The result: **progressive identity drift** (your agent slowly forgets who it is), **junk accumulation** (10,000 useless coding-session memories), and **no lifecycle** (no consolidation, no forgetting, no sleep).

evaOS is a cognitive memory engine grounded in memory research. It extracts claims, resolves entities, protects core identity, and runs dream cycles to consolidate and prune — just like biological memory.

---

## Install

```bash
pip install evaos
```

With vector search (recommended):
```bash
pip install "evaos[vec]"
```

All extras (LLM providers, HTTP API, MCP server):
```bash
pip install "evaos[all]"
```

---

## 30-Second Quickstart

**CLI:**

```bash
# Initialize a new memory store
evaos init

# Teach it something
evaos remember "Andrew is the founder of 100Yen Org. He lives in Bangkok."

# Ask it later
evaos recall "Where does Andrew live?"
# → Andrew lives in Bangkok. He is the founder of 100Yen Org.

# Ask your memory (Dialectic Engine — new in v1.1)
evaos ask "What do I know about Andrew's work?"
# → Multi-step reasoning across your memory graph
```

**Python SDK:**

```python
import asyncio
from evaos import Cortex

async def main():
    cortex = Cortex(db_path="my_memory.db", profile="companion")
    await cortex.initialize()

    # Start a session
    await cortex.wake(session_id="session_001")

    # Store information — claim extraction happens automatically
    await cortex.remember("Andrew is the founder of 100Yen Org. He lives in Bangkok.")

    # Retrieve relevant memories for an LLM prompt
    context = await cortex.retrieve("Where does Andrew live?")
    print(context.context_block)
    # → "Andrew lives in Bangkok. He is the founder of 100Yen Org."

    # End the session
    await cortex.sleep(session_id="session_001")

asyncio.run(main())
```

That's it. Memories persist in a local SQLite database, searchable via hybrid BM25 + vector retrieval.

---

## Features

### 🧠 5-Layer Memory Model

| Layer | What It Does |
|-------|-------------|
| **Extraction** | LLM-powered claim extraction with noise filtering (skips "changed line 47 of auth.py") |
| **Entity Resolution** | Fuzzy deduplication — "Andrew", "andrew", "@andrew" → same person |
| **Reconciliation** | Smart conflict resolution: ADD / UPDATE / SUPERSEDE / NOOP |
| **Cornerstones** | Immutable identity anchors that resist drift and accidental deletion |
| **Token Budget** | Assembles memory context within configurable token ceilings |

### 🌙 Dream Cycles

Circadian engine with sleep/wake/dream phases. During idle time, evaOS consolidates memories, runs Ebbinghaus decay on low-signal noise, and calculates identity drift against cornerstone baselines.

### 💬 Dialectic Engine *(v1.1)*

Ask your memory natural-language questions. Fast path for simple lookups, agentic multi-step QueryPlanner for complex reasoning across your memory graph.

### 👥 Peer Modeling *(v1.1)*

Track relationships between entities. Auto-creates peer records from entity resolution, builds relationship representations, and integrates with dream cycles for periodic peer refresh.

### 🕸️ Brain Graph

File-watcher + auto-registration document memory graph. Index your docs, specs, and decisions — query them alongside conversational memory.

### 📊 Graph Visualization *(v1.1)*

Force-directed graph data endpoints for visualizing memory relationships: nodes, edges, paths, and neighbors.

### 🖥️ Dashboard *(v1.1)*

8-page web UI for exploring your memory engine: memories, entities, cornerstones, peers, brain graph, events, configuration, and health status.

### 🔔 Webhooks *(v1.1)*

Subscribe to 16 event types with reliable webhook delivery, automatic retry, and event filtering.

### 🔍 Hybrid Retrieval

BM25 full-text search + vector similarity with Reciprocal Rank Fusion. Optional agentic re-ranking for high-stakes queries.

### 🛡️ Resilience *(v1.1)*

- LLM retry with exponential backoff and provider cascade
- Embedding model switch protection (prevents silent vector corruption)
- API key redaction in all log output
- SQLite integrity checks on startup
- 40 write locks, NaN validation, OOM protection

### 🔌 Four Interfaces

| Interface | Use Case |
|-----------|----------|
| **CLI** | `evaos remember`, `evaos recall`, `evaos ask`, `evaos dream` |
| **HTTP API** | FastAPI REST server — `evaos serve` |
| **MCP Server** | Model Context Protocol for agent frameworks — `evaos mcp` |
| **TypeScript SDK** | `@evaos/client` — typed client for Node.js applications |

---

## Python SDK Reference

The `Cortex` class is the recommended way to embed evaOS memory into Python applications.

```python
from evaos import Cortex

# Default — uses OpenAI, stores in cortex.db
cortex = Cortex()

# Customised
cortex = Cortex(
    db_path="~/my_app/memory.db",
    profile="companion",       # companion | developer | local | minimal
    llm_provider="openai",     # openai | anthropic | ollama
    extract_model="gpt-4.1-nano-2025-04-14",
    embed_model="text-embedding-3-small",
)

# From a config file
cortex = Cortex.from_config("~/.config/cortex.toml")
```

### Core methods

| Method | Description |
|--------|-------------|
| `await cortex.initialize()` | Initialize storage + apply migrations |
| `await cortex.wake(session_id)` | Start a session, load cornerstones |
| `await cortex.remember(content)` | Store text/conversation; extraction is automatic |
| `await cortex.retrieve(query)` | Hybrid BM25 + vector search, returns context block |
| `await cortex.ask(query)` | Dialectic engine — ask your memory questions |
| `await cortex.sleep(session_id)` | End session, trigger consolidation |
| `await cortex.dream()` | Run overnight reconsolidation cycle manually |
| `await cortex.seal_cornerstone(label, content)` | Pin an identity anchor |
| `await cortex.check_drift()` | Drift scores for all cornerstones |
| `await cortex.feedback(claim_id, "helpful")` | Rate a retrieved memory |
| `await cortex.health()` | System health dict |
| `await cortex.stats()` | Memory counts (claims, entities, cornerstones, sessions) |
| `await cortex.export(format="json")` | Export all active memories |

---

## TypeScript SDK

```bash
npm install @evaos/client
```

```typescript
import { CortexClient } from '@evaos/client';

const client = new CortexClient({
  baseUrl: 'http://localhost:8420',
  apiKey: 'your-api-key',
});

// Store a memory
await client.remember('Andrew is the founder of 100Yen Org.');

// Retrieve memories
const results = await client.recall('Who is Andrew?');
console.log(results.context_block);
```

See [`sdks/typescript/`](sdks/typescript/) for full documentation.

---

## Architecture

```
┌─────────────────────────────────────────────────┐
│                   evaOS Engine                   │
├──────────┬──────────┬──────────┬────────────────┤
│   CLI    │ HTTP API │   MCP    │  TypeScript SDK │
├──────────┴──────────┴──────────┴────────────────┤
│              Retrieval Pipeline                   │
│         (BM25 + Vector + RRF + Rerank)           │
├──────────────────────────────────────────────────┤
│  Extraction │ Entity Res. │ Reconciliation       │
├──────────────────────────────────────────────────┤
│  Cornerstones │ Drift Calc │ Feedback Loop       │
├──────────────────────────────────────────────────┤
│  Dialectic Engine │ Peer Modeling │ Webhooks     │
├──────────────────────────────────────────────────┤
│         Circadian Engine (Dream Cycles)          │
│       Deprecation Pipeline (Ebbinghaus)          │
├──────────────────────────────────────────────────┤
│  Token Budget │ Brain Graph │ Validation Layer   │
├──────────────────────────────────────────────────┤
│          SQLite + FTS5 + sqlite-vec              │
└──────────────────────────────────────────────────┘
```

---

## Configuration

evaOS uses a `cortex.toml` config file:

```toml
[cortex]
storage_backend = "sqlite"

[cortex.storage]
db_path = "evaos.db"

[cortex.extraction]
model = "haiku"              # or "gpt-4.1-nano"
noise_filter = true

[cortex.cornerstones]
max_count = 7
drift_threshold = 0.15

[cortex.circadian]
dream_interval_hours = 6
decay_curve = "ebbinghaus"
```

See [`docs/`](docs/) for full configuration reference and architecture deep-dives.

---

## CLI Reference

```bash
evaos init [--profile companion|coding|enterprise]
evaos remember "text"
evaos recall "query"
evaos ask "question"                    # Dialectic engine (v1.1)
evaos ask "question" --agentic          # Multi-step reasoning
evaos cornerstones list
evaos cornerstones seal --label "name" --content "text"
evaos dream
evaos stats
evaos health
evaos export [--format json|sql]
evaos serve [--port 8000]
evaos mcp
evaos backup [--output path]
```

---

## Dashboard

evaOS includes a built-in web dashboard for exploring and managing your memory engine.

```bash
evaos serve
# Dashboard available at http://localhost:8420/dashboard
```

**Pages:** Memories · Entities · Cornerstones · Peers · Brain Graph · Events · Config · Health

---

## Project Structure

```
cortex/
├── core/               # Extraction, entity resolution, reconciliation, retrieval
├── storage/            # SQLite adapter with FTS5 + vector support
├── brain_graph/        # Document memory graph with file watching
├── circadian/          # Sleep/wake/dream cycle engine
├── deprecation/        # Ebbinghaus decay pipeline
├── identity/           # Cornerstone guardian + drift calculator
├── config/             # TOML config loading + profiles
├── api/                # FastAPI HTTP server + webhooks
├── integrations/       # MCP server + plugin interface
├── dialectic/          # Dialectic engine (ask your memory)
├── peers/              # Peer modeling (relationship tracking)
├── cli.py              # Click-based CLI
└── types.py            # Shared dataclasses and types

dashboard/              # 8-page web UI (SPA)
sdks/typescript/        # @evaos/client TypeScript SDK
```

---

## Benchmarks

evaOS ships a benchmark suite that measures core operation latency and throughput.
All benchmarks use **mocked LLM/embedding providers** — we measure evaOS code performance, not API latency.

### Run benchmarks

```bash
# Full suite (retrieval at 10K scale takes ~2-3 min)
python -m benchmarks.run_benchmarks

# Skip slow 10K retrieval during development
python -m benchmarks.run_benchmarks --skip-retrieval

# Individual suites
python -m benchmarks.bench_retrieval
python -m benchmarks.bench_remember
python -m benchmarks.bench_consolidation
```

Results are saved to `benchmarks/results/latest.json`.

### What's measured

| Suite | What | Scales |
|---|---|---|
| `bench_retrieval` | vector search, FTS (BM25), hybrid RRF | 100 / 1k / 10k claims |
| `bench_remember` | extract + embed + store pipeline | single / batch 10 / batch 50 |
| `bench_consolidation` | `sleep()` consolidation pass | 100 / 500 / 1k claims |

Metrics: **p50 / p95 / p99 latency in ms**, 50 runs per measurement (10 for consolidation).
Vectors: 1024-dim, deterministic seed=42.

---

## Docker

Run evaOS as a container — no Python setup required.

### Quick start

```bash
# Clone the repo (or just grab the docker-compose.yml)
git clone https://github.com/100yenadmin/electric-sheep.git
cd electric-sheep

# Set your API keys
export OPENAI_API_KEY=sk-...
export VOYAGE_API_KEY=pa-...

# Start the server
docker compose up -d
```

The HTTP API is now available at `http://localhost:8420`.

### Build the image manually

```bash
docker build -t evaos .
docker run -d \
  -p 8420:8420 \
  -v evaos-data:/data \
  -e OPENAI_API_KEY=$OPENAI_API_KEY \
  -e VOYAGE_API_KEY=$VOYAGE_API_KEY \
  evaos
```

### Environment variables

| Variable | Default | Description |
|---|---|---|
| `CORTEX_DB_PATH` | `/data/cortex.db` | Path to the SQLite database |
| `CORTEX_API_KEY` | _(none)_ | API key to protect the HTTP server |
| `OPENAI_API_KEY` | _(none)_ | OpenAI API key for LLM operations |
| `OPENAI_BASE_URL` | _(none)_ | Custom OpenAI-compatible base URL |
| `VOYAGE_API_KEY` | _(none)_ | Voyage AI key for embeddings |

### Persistent storage

The container stores `cortex.db` in `/data` by default. The `docker-compose.yml` creates a named volume (`evaos-data`) that survives container restarts and updates.

### Health check

```bash
curl http://localhost:8420/api/v1/health
```

The container exposes a built-in healthcheck on the same endpoint (30s interval, 5s timeout, 3 retries).

---

## Contributing

See [CONTRIBUTING.md](CONTRIBUTING.md) for dev setup, testing, and PR guidelines.

---

## License

[MIT](LICENSE) — 100Yen Org
