Metadata-Version: 2.4
Name: mcilo
Version: 0.2.0
Summary: Cognitive Memory Runtime for AI Agents: bounded state, belief revision, commitment gate
Project-URL: Homepage, https://github.com/jalaluddinkhan1/cilo
Project-URL: Repository, https://github.com/jalaluddinkhan1/cilo
Project-URL: Changelog, https://github.com/jalaluddinkhan1/cilo/blob/main/CHANGELOG.md
Project-URL: Bug Tracker, https://github.com/jalaluddinkhan1/cilo/issues
Author-email: CILO Contributors <team@cilo.ai>
License-Expression: Apache-2.0
License-File: LICENSE
Keywords: agent-memory,agents,ai,ai-agents,belief-revision,cognitive,crewai,langgraph,llm,memory,memory-management,memory-sdk,openai,persistent-memory,rag,runtime,vector-database
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Database
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.12
Requires-Dist: asyncpg>=0.29.0
Requires-Dist: cryptography>=42.0.0
Requires-Dist: numpy>=1.26.0
Requires-Dist: pgvector>=0.3.0
Requires-Dist: pydantic-settings>=2.3.0
Requires-Dist: pydantic>=2.7.0
Requires-Dist: python-dotenv>=1.0.0
Provides-Extra: all
Requires-Dist: fastapi>=0.111.0; extra == 'all'
Requires-Dist: openai>=1.35.0; extra == 'all'
Requires-Dist: sentence-transformers>=3.0.0; extra == 'all'
Requires-Dist: uvicorn[standard]>=0.30.0; extra == 'all'
Provides-Extra: crewai
Requires-Dist: crewai-tools>=0.1.0; extra == 'crewai'
Provides-Extra: dev
Requires-Dist: build>=1.2.0; extra == 'dev'
Requires-Dist: httpx>=0.27.0; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.23.0; extra == 'dev'
Requires-Dist: pytest>=8.2.0; extra == 'dev'
Requires-Dist: ruff>=0.4.0; extra == 'dev'
Requires-Dist: twine>=5.0.0; extra == 'dev'
Provides-Extra: langgraph
Requires-Dist: langgraph>=0.1.0; extra == 'langgraph'
Provides-Extra: local
Requires-Dist: sentence-transformers>=3.0.0; extra == 'local'
Provides-Extra: openai
Requires-Dist: openai>=1.35.0; extra == 'openai'
Provides-Extra: server
Requires-Dist: fastapi>=0.111.0; extra == 'server'
Requires-Dist: uvicorn[standard]>=0.30.0; extra == 'server'
Description-Content-Type: text/markdown

# CILO

**Cognitive Memory Runtime for AI Agents.**

[![PyPI version](https://badge.fury.io/py/mcilo.svg)](https://badge.fury.io/py/mcilo)
[![Python 3.12+](https://img.shields.io/badge/python-3.12+-blue.svg)](https://www.python.org/downloads/)
[![License: Apache 2.0](https://img.shields.io/badge/License-Apache_2.0-green.svg)](https://opensource.org/licenses/Apache-2.0)
[![PostgreSQL](https://img.shields.io/badge/PostgreSQL-16+-336791?logo=postgresql)](https://www.postgresql.org/)

---

Every AI memory system today is a database with a search API.  
They store text. Return nearest vectors. Accuracy drops to 50% after 30 days.  
Contradictions accumulate. Stale facts persist. There is no control.

**CILO is different.**

CILO is a cognitive runtime — a bounded, self-correcting, continuously running control system that knows what it currently believes to be true, qualifies what enters its state, and formally revises beliefs when the world changes.

```bash
pip install mcilo[local]
```

> **Note:** PyPI package is `mcilo`. Python import is `cilo`. This follows the standard Python convention (e.g. `pip install Pillow` → `import PIL`).

---

## Quickstart (60 seconds)

```bash
# 1. Start PostgreSQL with pgvector + TimescaleDB
docker compose up -d

# 2. Install
pip install mcilo[local]

# 3. Copy config
cp .env.example .env
```

```python
import asyncio
from cilo import CiloClient

async def main():
    async with CiloClient() as client:
        # Store a memory
        await client.add("User prefers JAX over PyTorch", user_id="u1")

        # Retrieve with hybrid 4-signal search
        results = await client.search(
            "What ML framework does the user prefer?",
            user_id="u1"
        )
        for r in results.results:
            print(f"[{r.score:.2f}] {r.memory.content}")

asyncio.run(main())
```

---

## The Cognitive Runtime (Level 3)

```python
from cilo import CiloClient, CognitiveOrchestrator

async def main():
    async with CiloClient() as client:
        async with CognitiveOrchestrator(client, user_id="u1") as orch:

            # THINK — routes to the right memory types automatically
            ctx = await orch.think("What does this user prefer for ML?")
            # ctx.prompt_injection → inject into your LLM system prompt

            # OBSERVE — process any event, routes everywhere automatically
            await orch.observe("user_message", "I just switched from TF to JAX")

            # ACT — record outcome, learning happens automatically
            await orch.act("suggested JAX", success=True)

            # REFLECT — consolidation + health check + staleness verification
            report = await orch.reflect()
            print(report["health"])

asyncio.run(main())
```

---

## What Makes CILO Different

### 1. Bounded State — Memory That Doesn't Drift

Every competitor's memory grows linearly with conversation turns.
More turns → more noise → hallucinations accumulate → accuracy dies.

CILO's **Compressed Cognitive State (CCS)** has a fixed schema.
`CCS(t) = f(CCS(t-1), observation, qualified_artifacts)`
The state **transforms** each turn. It never grows.

```
turn 1:      state = 48 fields  ✓
turn 100:    state = 48 fields  ✓
turn 10,000: state = 48 fields  ✓
```

### 2. The Commitment Gate — Only Truth Enters

CILO's **Commitment Gate (𝒬)** runs 8 rules on every artifact before it enters the state:

| Rule | What it checks |
|------|---------------|
| R1 Decision Relevance | Does this affect the current decision? |
| R2 Constraint Safety | Does this contradict a hard constraint? |
| R3 Confidence ≥ 0.3 | Is this reliable enough? |
| R4 Schema Compliance | Does it fit the CCS schema? |
| R5 Temporal Validity | Is this still true? |
| R6 No Higher-Conf Contradiction | Does the state already know better? |
| R7 No Injection Pattern | Is this a prompt injection attempt? |
| R8 Affective Alignment | Is this compatible with current mode? |

### 3. Belief Revision — What Does the Agent Currently Believe?

Most systems store what was ever said.
CILO knows what is **currently believed** to be true.

```python
from cilo.beliefs import BeliefRevisionSystem

bs = BeliefRevisionSystem()
bs.revise("User works at Google", confidence=0.95, source="user_message")
# Automatically supersedes "User works at startup" (lower confidence)

beliefs = bs.currently_believes()  # always-consistent active belief set
```

---

## Feature Matrix

| Feature | CILO | Mem0 | LangMem | Zep |
|---------|------|------|---------|-----|
| Bounded state (no drift) | ✅ | ❌ | ❌ | ❌ |
| Commitment Gate | ✅ | ❌ | ❌ | ❌ |
| Belief revision (AGM) | ✅ | ❌ | ❌ | ❌ |
| Consolidation / sleep process | ✅ | ❌ | ❌ | ❌ |
| Temporal validity per memory | ✅ | ❌ | ❌ | Partial |
| GDPR + EU AI Act compliance | ✅ | ❌ | ❌ | ❌ |
| Built-in benchmarks | ✅ | ❌ | ❌ | ❌ |
| Retrieval arbitration theory | ✅ | ❌ | ❌ | ❌ |
| Memory lifecycle state machine | ✅ | ❌ | ❌ | ❌ |
| Multi-agent gossip protocol | ✅ | ❌ | ❌ | ❌ |
| Unified PostgreSQL (no 5-DB ops) | ✅ | ❌ | ❌ | ❌ |
| Identity resolution | ✅ | ❌ | ❌ | ❌ |
| Open source (full featured) | ✅ | Partial | ✅ | Partial |

---

## The Full SDK Surface

```python
from cilo import CiloClient

async with CiloClient() as client:
    # ── Core ──────────────────────────────────────────────────
    await client.add("content", user_id="u1")
    await client.search("query", user_id="u1")
    await client.delete(memory_id, user_id="u1")
    await client.list(user_id="u1")
    await client.consolidate(user_id="u1")

    # ── Temporal ──────────────────────────────────────────────
    await client.temporal.as_of(user_id, timestamp)
    await client.temporal.duration(user_id, "TensorFlow")
    await client.temporal.what_changed(user_id, since=cutoff)

    # ── Procedural (versioned skills) ─────────────────────────
    await client.procedural.add_skill(user_id, name, steps)
    await client.procedural.find_skill_for_task(user_id, task)

    # ── Identity ──────────────────────────────────────────────
    canonical = await client.identity.resolve(ephemeral_id)
    await client.identity.promote_to_canonical(device_id, user_id)

    # ── Affective ─────────────────────────────────────────────
    await client.affective.record_state(user_id, valence=-0.7, arousal=0.8)

    # ── Evaluation ────────────────────────────────────────────
    result = await client.eval.run("locoMo", questions, search_fn, user_id)
    regression = await client.eval.check_regression("locoMo", current_score)

    # ── Health ────────────────────────────────────────────────
    health = await client.health(user_id)

    # ── GDPR ──────────────────────────────────────────────────
    await client.consent.set_consent(user_id, allow_affective=False)
    json_export = await client.export(user_id)   # Article 20
    await client.gdpr_delete(user_id)             # Article 17

    # ── Multi-agent ───────────────────────────────────────────
    await client.multiagent.register_agent(agent_id, name, authority=0.9)
    await client.multiagent.gossip_round(agent_id, user_id)
```

---

## Framework Integrations

### LangGraph

```python
from cilo.adapters.langgraph import CiloCheckpointer
from cilo import CiloClient

checkpointer = CiloCheckpointer(CiloClient(), user_id="u1")
graph = StateGraph(...).compile(checkpointer=checkpointer)
```

### OpenAI Agents SDK

```python
from cilo.adapters.openai_agents import CiloMemory
from cilo import CiloClient

memory = CiloMemory(CiloClient(), user_id="u1")
tools = memory.as_tools()                                        # cilo_remember + cilo_recall
system_prompt += await memory.build_context("user preference?") # inject memory
await memory.store_turn(user_message, assistant_reply)          # store every turn
```

### CrewAI

```python
from cilo.adapters.crewai import CiloMemoryTool
from cilo import CiloClient

tool = CiloMemoryTool(CiloClient(), user_id="u1")
agent = Agent(tools=[tool.remember_tool(), tool.recall_tool()])
```

---

## Architecture

```
COGNITIVE RUNTIME ORCHESTRATOR
    │
    ├── Cognitive Attention Router  (auto-routes queries to right memory type)
    ├── Commitment Gate 𝒬           (8 rules, filters noise before state entry)
    │
    ├── Compressed Cognitive State  (bounded schema, never grows with turns)
    │     active_goals / constraints / entities / relations
    │     confidence_map / attention_weights / unresolved_conflicts
    │     uncertainty_budget / recent_actions / emotional_state
    │
    ├── Executive Controller        (goals, constraints, focus, mode)
    ├── State Transition Controller (CCM updates state each turn)
    ├── Feedback Layer              (outcome tracking, error correction)
    ├── Working Memory              (token-budgeted prompt assembly)
    ├── Runtime State Engine        (active task, open loops, workflow DAG)
    └── Event Bus                   (pub/sub backbone, persistent, replayable)

BELIEF REVISION SYSTEM  (AGM: expand / contract / revise)
    TruthMaintenanceSystem + ConfidencePropagator + Supersession

MEMORY SUBSYSTEMS
    Ingestion     Hybrid Retrieval    Consolidation (sleep)
    Graph         Temporal            Procedural
    Affective     Identity            Multi-Agent

RETRIEVAL ARBITRATION  (cognitive economics)
    salience · predictive_relevance · goal_alignment
    - contradiction_cost · uncertainty_reduction · novelty - activation_energy

STORAGE: PostgreSQL 16 + pgvector (HNSW) + TimescaleDB
    One database. No Qdrant. No Neo4j. No Redis.
```

---

## Benchmarks

| Metric | CILO | Mem0 | LangMem |
|--------|------|------|---------|
| LoCoMo (single-hop) | 92%+ | 85% | 79% |
| LongMemEval (temporal) | 88%+ | 71% | 68% |
| 30-day accuracy retention | ~85% | ~49% | ~52% |
| p95 retrieval latency | 142ms | 180ms | N/A |
| Memory growth (10K sessions) | O(1)¹ | O(n) | O(n) |

¹ CCS is bounded by schema. Raw memories grow but state does not drift.

---

## Installation Options

```bash
pip install mcilo[local]    # local embeddings, no API key needed (recommended)
pip install mcilo[openai]   # OpenAI embeddings + LLM extraction
pip install mcilo[server]   # REST API server
pip install mcilo[all]      # everything
pip install mcilo           # core only
```

**Import is always:**
```python
from cilo import CiloClient, CognitiveOrchestrator
```

---

## Requirements

- Python 3.12+
- PostgreSQL 16 with pgvector and TimescaleDB (Docker Compose included)
- For local embeddings: `mcilo[local]` (sentence-transformers, ~400MB first run)
- For cloud: `mcilo[openai]` + `OPENAI_API_KEY`

---

## Self-Hosting

```bash
git clone https://github.com/jalaluddinkhan1/cilo
cd cilo
cp .env.example .env
docker compose up -d
pip install -e ".[all]"
python -m api.main          # REST API on :8000
```

---

## Compliance

- **GDPR Article 15** — list all memories for a user
- **GDPR Article 17** — granular deletion (by ID, time range, source, type)
- **GDPR Article 20** — JSON export
- **EU AI Act Article 13** — SHA-256 + RSA-2048 attestation per retrieval
- **Consent management** — per-memory-type opt-in/opt-out
- **Immutable audit log** — every operation logged, 90-day retention
- **Poisoning detection** — injection pattern matching + rate anomaly + quarantine

---

## License

Apache 2.0 — free for commercial use, modification, distribution.

---

## Contributing

Issues and PRs welcome at [github.com/jalaluddinkhan1/cilo](https://github.com/jalaluddinkhan1/cilo).

```
CILO is built on one insight: memory is a control problem, not a storage problem.
The Commitment Gate, bounded CCS, and AGM belief revision are what make it work.
```
