Metadata-Version: 2.4
Name: fractal-memory
Version: 0.3.0
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.0--beta-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="#4-dashboard--visual-organism">
    <img src="docs/screenshots/home.png" alt="Fractal Memory Dashboard" width="720" />
  </a>
</p>
<p align="center">
  <sub>19-page real-time dashboard — <a href="#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 -e ".[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
# Add to ~/.claude.json mcpServers section:
{
  "mcpServers": {
    "fractal-memory": {
      "command": "$(which 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 -e ".[dashboard]"

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

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

```bash
# Add to ~/.claude.json mcpServers section:
{
  "mcpServers": {
    "fractal-memory": {
      "command": "$(which 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`).

The active domain is shown as a `◆ name` badge in the dashboard nav bar. To check: ask Claude "what memory domain are we using?"

**One domain vs. per-project vs. both**

| Strategy | Best for | Downside |
|----------|----------|----------|
| Single domain (`general`) | Few projects, cross-pollination is valuable | Retrieval gets noisy above ~100 memories |
| One per project | Distinct codebases, separate clients | Easy to forget to set the domain; memories get orphaned |
| Hierarchical (recommended) | Most developers | Requires a small naming discipline |

The hierarchical approach uses dot-separated names as a convention — `work`, `work.client-api`, `work.client-b` — and stores at two levels intentionally:

- **Project-specific facts** → `memory_store(text, domain="work.client-api")` — decisions, quirks, tickets
- **Reusable knowledge** → `memory_store(text, domain="work")` — preferences, patterns, conventions that transfer across projects

To retrieve from both at the start of a task, tell Claude once:

> "Always retrieve from both `work.client-api` and `work` at the start of tasks."

Claude will call `memory_retrieve` on each domain and merge the context. The dot notation is a naming convention only — there is no automatic inheritance today. Cross-domain retrieval (where querying `work.client-api` also searches `work` automatically) is planned for Phase 4.

> [!IMPORTANT]
> **How to instruct Claude about domains clearly**
>
> First, confirm the MCP server is connected. In Claude Code, run `/mcp` — you should see `fractal-memory` listed with status `connected`. If it shows `failed` or is missing, the tools are unavailable and Claude cannot store or retrieve anything regardless of what you ask. Fix the connection before proceeding (check `pip install -e ".[dashboard]"` was run and the `.mcp.json` is present in your project directory).
>
> Once connected, describing what you want is not enough. Claude will acknowledge it as a note but not act on it. Always phrase domain instructions as direct commands:
>
> ❌ "I want to use `memory-domain` for this project."
> ✅ "Call `memory_set_domain('memory-domain')` now."
>
> ❌ "Store what we discussed in the memory project domain."
> ✅ "Call `memory_store` with domain `memory-domain` for each of these points: ..."
>
> **To make it permanent** (so you never have to say it again): once the domain exists, store the instruction as a memory inside it:
>
> > "Call `memory_set_domain('memory-domain')` then store this: When working in the fractal-memory project, always set the active domain to memory-domain at session start."
>
> Claude will retrieve that instruction on every future session bootstrap and follow it automatically.
>
> **Easiest option** — set the default via env var and never think about it:
> ```bash
> # ~/.zshrc
> export FRACTAL_DEFAULT_DOMAIN=memory-domain
> ```

**Auto-session behaviour** is on by default — Claude manages sessions automatically. To disable:

```toml
# ~/.fractal_memory/config.toml
auto_session = false
```

Or per-session via env var:
```bash
FRACTAL_AUTO_SESSION=false
```

With `auto_session = false`, tools are still available but Claude only uses them when you explicitly ask.

---

### 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 -e ".[dashboard]"
python run_dashboard.py
# Open http://127.0.0.1:8765
```

<details>
<summary><b>All 19 dashboard pages (click to expand)</b></summary>

#### Overview
| `/` Domain Organs | `/guide` Guide |
|:---:|:---:|
| ![Domain Organs](docs/screenshots/home.png) | ![Guide](docs/screenshots/guide.png) |

#### Memory Systems
| `/brain` Neural Network | `/lifecycle` Lifecycle Chrysalis |
|:---:|:---:|
| ![Neural Network](docs/screenshots/brain.png) | ![Lifecycle](docs/screenshots/lifecycle.png) |

| `/pipeline` Processing Pipeline | `/buffer` Working Buffer |
|:---:|:---:|
| ![Pipeline](docs/screenshots/pipeline.png) | ![Buffer](docs/screenshots/buffer.png) |

#### Organism Health
| `/organism` Organism Health | `/morphogens` Morphogen Landscape |
|:---:|:---:|
| ![Organism](docs/screenshots/organism.png) | ![Morphogens](docs/screenshots/morphogens.png) |

| `/states` System States | `/cascade` Cascade Detector |
|:---:|:---:|
| ![States](docs/screenshots/states.png) | ![Cascade](docs/screenshots/cascade.png) |

#### Processes
| `/consolidation` Consolidation | `/dreaming` Dream Cycles |
|:---:|:---:|
| ![Consolidation](docs/screenshots/consolidation.png) | ![Dreaming](docs/screenshots/dreaming.png) |

| `/apoptosis` Apoptosis | `/maintenance` Maintenance |
|:---:|:---:|
| ![Apoptosis](docs/screenshots/apoptosis.png) | ![Maintenance](docs/screenshots/maintenance.png) |

#### Adaptation
| `/feedback` Feedback | `/bandits` Bandits |
|:---:|:---:|
| ![Feedback](docs/screenshots/feedback.png) | ![Bandits](docs/screenshots/bandits.png) |

| `/niche` Niche Construction | `/folding` Dimensional Folding |
|:---:|:---:|
| ![Niche](docs/screenshots/niche.png) | ![Folding](docs/screenshots/folding.png) |

#### System
| `/config` Configuration |
|:---:|
| ![Config](docs/screenshots/config.png) |

</details>

**Views:**

| Category | URL | Page |
|----------|-----|------|
| **Overview** | `/` | Domain Organs — each domain as a living organ, cross-domain edges, vital signs bar |
| | `/guide` | Guide — comprehensive walkthrough of every dashboard page |
| **Memory** | `/brain` | Neural Network — interactive D3.js force graph of association edges |
| | `/lifecycle` | Lifecycle Chrysalis — memories on concentric rings by maturation stage |
| | `/pipeline` | Processing Pipeline — gate → zoom → embedding → storage flow with throughput counters |
| | `/buffer` | Working Buffer — pinned, auto-promoted, recent memories and habituation state |
| **Organism** | `/organism` | Organism Health — self-model, domain maturity, parameter drift |
| | `/morphogens` | Morphogen Landscape — adaptive response curves and signal trajectories |
| | `/states` | System States — flow/stress/recovery state machine with parameter multipliers |
| | `/cascade` | Cascade Detector — EKF hidden state, circuit breaker, cascade warnings |
| **Processes** | `/consolidation` | Consolidation — merge events, edge decay, scar expiry, freeloader detection |
| | `/dreaming` | Dream Cycles — slow-wave decay and REM recombination stats |
| | `/apoptosis` | Apoptosis — pruned memories, trigger distribution, fragment creation |
| | `/maintenance` | Maintenance — daily/weekly/monthly tier scheduling and action history |
| **Adaptation** | `/feedback` | Feedback — danger theory signals, LLM judge ratings, store signal detection |
| | `/bandits` | Bandits — Thompson-sampling arm statistics and context-bin distribution |
| | `/niche` | Niche Construction — domain clusters, cohesion/separation, Louvain proposals |
| | `/folding` | Dimensional Folding — operational regime, active/folded subsystems, anomaly unfolds |
| **System** | `/config` | Configuration — all parameters grouped by category with sensitivity annotations |
| **Detail** | `/domain/{name}` | Domain detail — memory list, health metrics |
| | `/memory/{id}` | Memory detail — all 5 zoom levels, associations, metadata |

**API endpoints** (all `GET`, JSON responses):

| Category | Endpoint | Returns |
|----------|----------|---------|
| **Core** | `/api/stats` | Full system statistics |
| | `/api/vitals` | Real-time vital signs: `heart_rate`, `pressure`, `temperature`, `domains` |
| **Memory** | `/api/associations/{domain}` | `nodes` + `edges` for D3.js force graph |
| | `/api/lifecycle-distribution` | Counts per lifecycle status + promotion/pruning rates |
| | `/api/pipeline-stats` | Gate throughput, waiting room size, recent memories |
| | `/api/domain-health` | Per-domain health: memory count, edge count, avg weight |
| | `/api/buffer-state` | Working buffer: pinned, auto-promoted, recent, habituation |
| **Organism** | `/api/health-snapshot` | Full organism health from self-model |
| | `/api/domain-maturity` | Maturity classification per domain |
| | `/api/morphogen-trajectory` | Time series of morphogen signals from session history |
| | `/api/response-curves` | Current sigmoid parameters for all response curves |
| | `/api/system-state` | Current system state, morphogen values, bandit arm stats |
| | `/api/explain-last` | Explanation of the last retrieval decision |
| **Processes** | `/api/consolidation-state` | Last consolidation report, merge events, drift suggestions |
| | `/api/consolidation-history` | Per-session consolidation history |
| | `/api/dream-stats` | Last dream cycle stats (slow-wave + REM) |
| | `/api/dream-history` | Per-session dream cycle history |
| | `/api/apoptosis-stats` | Pruning events, trigger distribution, vitality data |
| | `/api/maintenance-state` | Last maintenance report, tier run log |
| | `/api/maintenance-history` | Historical maintenance runs |
| **Adaptation** | `/api/feedback-state` | Danger theory signals, judge ratings, info richness |
| | `/api/feedback-history` | Per-session feedback score history |
| | `/api/bandits-state` | Arm stats, context bins, current arm parameters |
| | `/api/bandits-history` | Per-session bandit selection history |
| | `/api/niche-health` | Per-domain niche health: cohesion, separation, stability |
| | `/api/niche-proposals` | Pending Louvain cluster proposals |
| | `/api/cascade-state` | EKF hidden state, covariance, circuit breaker, warnings |
| | `/api/cascade-history` | Historical cascade warning events |
| | `/api/folding-state` | Regime, active/folded subsystems, anomaly history |
| | `/api/states-data` | Current state machine: state, counters, multipliers |
| | `/api/states-history` | Per-session state history |
| | `/api/scars` | Scar tissue + golden seam data |
| | `/api/correction-timeline` | Per-correction event log |
| **Detail** | `/api/domain/{domain}` | Domain detail: memory list with metadata |
| | `/api/memory/{memory_id}` | Memory detail: all zoom levels, edges |
| | `/api/config-state` | All config parameters with categories and sensitivity |

---

## 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 [CONTRIBUTING.md](CONTRIBUTING.md) for development setup, code style, and PR process.

---

## License

[MIT](LICENSE)
