Metadata-Version: 2.4
Name: fractal-memory
Version: 0.3.2
Summary: Fractal Memory — multi-resolution AI memory with living organism design
Project-URL: Homepage, https://github.com/entropyvector/fractal-memory
Project-URL: Documentation, https://github.com/entropyvector/fractal-memory#readme
Project-URL: Repository, https://github.com/entropyvector/fractal-memory
Project-URL: Issues, https://github.com/entropyvector/fractal-memory/issues
Project-URL: Changelog, https://github.com/entropyvector/fractal-memory/blob/main/CHANGELOG.md
Author-email: Zaur Jafarov <entropyvector.dev@gmail.com>
License: MIT
License-File: LICENSE
Keywords: agent,ai,associative-memory,claude,llm,long-term-memory,mcp,memory,multi-resolution
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.11
Requires-Dist: aiosqlite>=0.19
Requires-Dist: click>=8.0
Requires-Dist: mcp>=1.0
Requires-Dist: networkx>=3.0
Requires-Dist: numpy>=1.24
Requires-Dist: sentence-transformers>=2.2
Provides-Extra: api
Requires-Dist: anthropic>=0.25; extra == 'api'
Provides-Extra: dashboard
Requires-Dist: fastapi>=0.110; extra == 'dashboard'
Requires-Dist: jinja2>=3.1; extra == 'dashboard'
Requires-Dist: python-multipart>=0.0.9; extra == 'dashboard'
Requires-Dist: uvicorn[standard]>=0.29; extra == 'dashboard'
Provides-Extra: dev
Requires-Dist: anthropic>=0.25; extra == 'dev'
Requires-Dist: hypothesis>=6.90; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
Requires-Dist: pytest>=8; extra == 'dev'
Provides-Extra: experiments
Requires-Dist: numpy>=1.24; extra == 'experiments'
Provides-Extra: ollama
Requires-Dist: httpx>=0.27; extra == 'ollama'
Description-Content-Type: text/markdown

# Fractal Memory

[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Python 3.11+](https://img.shields.io/badge/python-3.11+-blue.svg)](https://www.python.org/downloads/)
[![Version](https://img.shields.io/badge/version-0.3.2-green.svg)](https://github.com/entropyvector/fractal-memory)

Multi-resolution AI memory with a living organism design. Memories exist at 5 zoom levels simultaneously — the system shows the AI everything, but at graduated detail. Associations form, corrections leave scar tissue, sessions consolidate while you sleep.

> **Current phase: 3 (Forest)** — associations, danger theory, scar tissue, morphogenetic self-calibration, dreaming, maintenance scheduling, and diagnostic dashboard are live.

<p align="center">
  <a href="https://github.com/entropyvector/fractal-memory#4-dashboard--visual-organism">
    <img src="https://raw.githubusercontent.com/entropyvector/fractal-memory/main/docs/screenshots/home.png" alt="Fractal Memory Dashboard" width="720" />
  </a>
</p>
<p align="center">
  <sub>19-page real-time dashboard — <a href="https://github.com/entropyvector/fractal-memory#4-dashboard--visual-organism">see all pages</a></sub>
</p>

---

## Why Fractal Memory?

- **Multi-resolution retrieval** — every memory is stored at 5 zoom levels (tag, label, summary, full, raw). Top 200 as labels, top 50 as summaries, top 10 as full context — all within one token budget. No "lost context" problem.
- **Living organism, not a dead database** — memories have lifecycles (probation → confirmed → permanent), associations form and decay, corrections leave scar tissue, vitality scores drive apoptosis. The system self-organizes.
- **Session intelligence** — automatic session start/end with bootstrap context, LLM judge scoring, consolidation, and morphogenetic parameter tuning. Gets smarter every session.
- **Works with what you have** — MCP server for Claude Code / Cursor / Windsurf, Python library for custom apps. Uses Claude Code Pro (free), Anthropic API, or local Ollama for LLM calls.

---

## Quickstart (Claude Code)

```bash
# 1. Install
pip install "fractal-memory[dashboard]"

# 2. Add to your project's .mcp.json (or copy .mcp.json.example)
cat > .mcp.json << 'EOF'
{
  "mcpServers": {
    "fractal-memory": {
      "command": "fractal-memory-mcp"
    }
  }
}
EOF

# 3. Restart Claude Code — memory is live
```

For global setup (active in every Claude Code session):

```bash
# Install globally (isolated from your project venvs)
pipx install "fractal-memory[dashboard]"

# Add to ~/.claude.json mcpServers section:
{
  "mcpServers": {
    "fractal-memory": {
      "command": "fractal-memory-mcp"
    }
  }
}
```

> **No pipx?** You can install into any venv and use the absolute path instead:
> ```json
> { "command": "/path/to/your/venv/bin/fractal-memory-mcp" }
> ```

---

## CLI

Global options: `--db <path>` (override database), `--domain <name>` (set active domain).

**Core**

```bash
fractal store "Always use async/await for I/O" --domain my-project --intensity 0.8
fractal retrieve "coding conventions" --domain my-project --budget 4000
```

**Session management**

```bash
fractal session start --domain my-project
fractal session end
```

**Memory management**

```bash
fractal inspect <memory-id>       # Show full detail for a memory (all zoom levels, metadata)
fractal delete <memory-id>        # Delete a memory (with confirmation prompt)
fractal pin <memory-id>           # Promote to PERMANENT lifecycle
fractal unpin <memory-id>         # Revert to CONFIRMED lifecycle
```

**Organism inspection**

```bash
fractal stats                     # Quick summary: memories, domains, edges, scars, sessions
fractal health                    # Full health report: hit rate, scars, morphogen convergence
fractal explain                   # Explain the last retrieval decision
fractal morphogens                # Morphogen values, response curves, convergence status
fractal bandits                   # Bandit arm statistics (alpha, beta, mean, pulls)
fractal domains                   # List all domains with memory counts
fractal memories --domain my-project --lifecycle confirmed --limit 50
```

**Database**

```bash
fractal lint                      # Check database health and report issues
fractal lint --fix                # Auto-repair safe issues (orphaned edges, broken chains)
```

**Maintenance**

```bash
fractal maintenance --tier daily   # Trigger a maintenance cycle
fractal maintenance --tier weekly
fractal maintenance --tier monthly
```

**Export**

```bash
fractal export memories --domain my-project --format json
fractal export memories --domain my-project --format markdown --output export.md
fractal export stats              # Full system stats as JSON
```

**Audit trail**

```bash
fractal audit sessions --limit 10
fractal audit corrections --limit 10
fractal audit consolidation       # Last 5 sessions' consolidation activity
```

---

## Ways to use it

There are three independent ways to use Fractal Memory. Pick the one that fits your situation — they share the same database and the same organism.

---

### 1. Claude Code — MCP server (recommended)

The most natural way. Fractal Memory becomes Claude's long-term memory. Every session, Claude automatically retrieves what it knows about your project, stores new decisions and discoveries, and consolidates everything at session end.

**Setup for this project only** (`.mcp.json`):

```bash
# Install
pip install "fractal-memory[dashboard]"

# Copy the example MCP config
cp .mcp.json.example .mcp.json
```

**Setup globally** (active in every Claude Code session on this machine):

```bash
# Install globally (isolated from your project venvs)
pipx install "fractal-memory[dashboard]"
```

```bash
# Add to ~/.claude.json mcpServers section:
{
  "mcpServers": {
    "fractal-memory": {
      "command": "fractal-memory-mcp"
    }
  }
}
```

> **No pipx?** Install into any venv and use the absolute path:
> `"command": "/path/to/your/venv/bin/fractal-memory-mcp"`

Restart Claude Code. The MCP server starts automatically and co-launches the dashboard at `http://127.0.0.1:8765`.

**Available MCP tools:**

| Tool | What it does |
|------|-------------|
| `memory_store(text, domain, intensity)` | Store a memory |
| `memory_retrieve(query, domain)` | Retrieve relevant memories |
| `memory_session_start(domain)` | Start a session explicitly |
| `memory_session_end()` | End session, run consolidation |
| `memory_correct(memory_id, correction)` | Correct a wrong memory — creates scar tissue |
| `memory_confirm(memory_id)` | Confirm a memory is accurate — strengthens trails |
| `memory_get(memory_id)` | Fetch a specific memory by ID |
| `memory_delete(memory_id)` | Delete a memory |
| `memory_pin(memory_id)` | Pin to permanent lifecycle (always in context) |
| `memory_unpin(memory_id)` | Revert pin |
| `memory_mark_critical(memory_id)` | Mark as safety-critical (highest lifecycle, never pruned, always injected) |
| `memory_set_domain(domain)` | Set active domain for this conversation |
| `memory_get_domain()` | Check currently active domain |
| `memory_list_domains()` | List all domains with counts |
| `memory_stats()` | Full system statistics |
| `task_add(description, priority)` | Add a persistent task |
| `task_complete(task_id)` | Mark task done |
| `task_list(status)` | List tasks |
| `open_dashboard()` | Open the dashboard in the default browser |

**Domain selection** controls which memory space Claude reads and writes. Three levels of control:

| Level | How | When to use |
|-------|-----|-------------|
| Shell default | `export FRACTAL_DEFAULT_DOMAIN=my-project` in `~/.zshrc` | One main project per machine |
| Config file | `default_domain = "my-project"` in `~/.fractal_memory/config.toml` | Persistent per-install default |
| Mid-conversation | Tell Claude "switch to project X" or call `memory_set_domain("x")` | Switching projects within a session |

Domain names must be alphanumeric with hyphens, underscores, or dots (e.g. `fractal-memory-dev`, `client-acme`, `personal`).

---

### 2. Other MCP clients (Cursor, Windsurf, any MCP-compatible tool)

Same MCP server, any client that speaks the MCP protocol.

**Configuration** (add to your client's MCP settings):
```json
{
  "mcpServers": {
    "fractal-memory": {
      "command": "fractal-memory-mcp"
    }
  }
}
```

The server runs over stdio transport — compatible with all standard MCP clients.

---

### 3. Python library — direct API

Use `FractalMemory` directly in your own code. Full async API.

**Install:**
```bash
pip install fractal-memory
# With dashboard:
pip install "fractal-memory[dashboard]"
# With direct Anthropic API access:
pip install "fractal-memory[api]"
# With Ollama local LLM:
pip install "fractal-memory[ollama]"
```

**Basic usage:**
```python
import asyncio
from fractal_memory import FractalMemory

async def main():
    fm = FractalMemory()
    await fm.initialize()

    ctx = await fm.session_start("my-project")
    print(f"Bootstrap memories: {len(ctx.bootstrap_memories)}")
    print(f"Last session summary: {ctx.last_summary}")

    # Store
    mem = await fm.store(
        "Always use async/await for all I/O — never sync drivers in async contexts",
        domain="my-project",
        intensity=0.8,
    )

    # Retrieve — returns memories at 3 zoom levels
    result = await fm.retrieve("what are the coding conventions?", domain="my-project")
    for m in result.l3_memories:   # full context, top 10
        print(f"[L3] {m.l3_full}")
    for m in result.l2_memories:   # summaries, top 50
        print(f"[L2] {m.l2_summary}")
    for m in result.l1_memories:   # labels only, top 200
        print(f"[L1] {m.l1_label}")

    # Correct a wrong memory — creates scar tissue to avoid the pattern
    corrected = await fm.correct(mem.id, "Actually trio is preferred over asyncio here")

    # Confirm a memory is right — strengthens association trails
    await fm.confirm(mem.id)

    # Session end — runs LLM judge + consolidation + scar expiry
    summary = await fm.session_end()
    print(f"Stored: {summary.memories_stored}, Retrieved: {summary.memories_retrieved}")
    print(f"Summary: {summary.summary}")

    await fm.close()

asyncio.run(main())
```

**Configuration:**
```python
from fractal_memory.config import FractalConfig, load_config

# Defaults — reads ~/.fractal_memory/config.toml + env vars
fm = FractalMemory()

# Custom config
config = FractalConfig(
    db_path="~/my-project/.memory.db",
    llm_provider="anthropic",           # "bridge" | "anthropic" | "ollama"
    llm_model="claude-sonnet-4-6",
    gate_signal_count=1,                # 1 = store everything, 2 = require confirmation
    auto_session=True,
)
fm = FractalMemory(config)

# From TOML file
config = load_config(path="./my-config.toml")
```

**Config file** (`~/.fractal_memory/config.toml`):
```toml
db_path = "~/.fractal_memory/memory.db"
llm_provider = "bridge"           # uses Claude Code Pro — $0 cost
gate_signal_count = 1             # Pioneer mode: store everything
auto_session = true               # MCP auto-manages sessions
default_domain = "general"        # fallback domain for all store/retrieve calls
activity_flush_interval = 5       # ops between dashboard heartbeat flushes
dashboard_port = 8765
```

**LLM providers:**

| Provider | Config | Notes |
|----------|--------|-------|
| `bridge` (default) | nothing | Uses Claude Code's active session. Free with Pro subscription. |
| `anthropic` | `llm_api_key` or `FRACTAL_LLM_API_KEY` | Direct Anthropic API. Install `[api]` extra. |
| `ollama` | `llm_model = "llama3"` | Local LLM. Install `[ollama]` extra. Ollama must be running. |

---

### 4. Dashboard — visual organism

The dashboard shows the memory organism in real time: association network, lifecycle rings, processing pipeline, domain organs, vital signs.

**It starts automatically** with the MCP server (co-launched on the same process, same live data).

To run it standalone against your database:
```bash
pip install "fractal-memory[dashboard]"
python run_dashboard.py
# Open http://127.0.0.1:8765
```

**19 dashboard pages** covering every aspect of the organism:

| Category | Pages |
|----------|-------|
| **Overview** | Domain Organs, Guide |
| **Memory** | Neural Network (D3.js force graph), Lifecycle Chrysalis, Processing Pipeline, Working Buffer |
| **Organism** | Organism Health, Morphogen Landscape, System States, Cascade Detector |
| **Processes** | Consolidation, Dream Cycles, Apoptosis, Maintenance |
| **Adaptation** | Feedback & Danger Theory, Bandits, Niche Construction, Dimensional Folding |
| **System** | Configuration |
| **Detail** | Per-domain view, Per-memory view (all 5 zoom levels) |

See the full dashboard gallery with screenshots on [GitHub](https://github.com/entropyvector/fractal-memory#4-dashboard--visual-organism).

---

## Requirements

- Python 3.11+
- For LLM calls (zoom level generation, consolidation): Claude Code Pro active session (default), or Anthropic API key, or Ollama running locally
- For dashboard: `pip install "fractal-memory[dashboard]"`

---

## Architecture in one paragraph

Each memory is stored at 5 zoom levels (L0 tag → L1 label → L2 summary → L3 full → L4 raw). On retrieval, all memories are scored by cosine similarity + intensity weighting + association spreading activation − scar penalties. The top 200 are shown as labels, top 50 as summaries, top 10 as full context — all within one token budget. At session end, an LLM judge rates which memories were actually used, scars expire, similar memories merge, and association edge weights decay. The organism gets smarter with each session.

---

## Status

| Phase | Name | Status | What it adds |
|-------|------|--------|-------------|
| 1 | Pioneer | Complete | Store, retrieve, zoom levels, lifecycle, gate, session bootstrap |
| 2 | Shrub | Complete | Associations, danger theory, scar tissue, consolidation, domains, dashboard |
| 3 | Forest | Complete | Morphogenetic self-calibration, niche construction, Kintsugi, maintenance scheduling, dreaming |
| 4 | Old Growth | Planned | Aliveness diagnostic, memory packs, cross-domain discovery, full dreaming |

---

## Contributing

See the [GitHub repository](https://github.com/entropyvector/fractal-memory) for development setup and contribution guidelines.

---

## License

[MIT](https://github.com/entropyvector/fractal-memory/blob/main/LICENSE)
